From 9fe130cd73317c18ae01b305b969f03e49b1386f Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 11 Nov 2025 13:49:01 +0100 Subject: [PATCH] All: Reformat according to new standard --- .github/problemMatcher/msvc.json | 3 +- src/Base/AxisPyImp.cpp | 3 +- src/Base/Base64.cpp | 3 +- src/Base/Base64.h | 3 +- src/Base/Base64Filter.h | 55 +- src/Base/BaseClass.cpp | 10 +- src/Base/BaseClass.h | 156 +- src/Base/BoundBox.h | 201 +- src/Base/BoundBoxPyImp.cpp | 98 +- src/Base/Builder3D.cpp | 46 +- src/Base/Builder3D.h | 48 +- src/Base/Color.h | 26 +- src/Base/Console.cpp | 275 +- src/Base/Console.h | 182 +- src/Base/ConsoleObserver.cpp | 65 +- src/Base/ConsoleObserver.h | 40 +- src/Base/Converter.h | 18 +- src/Base/CoordinateSystemPyImp.cpp | 18 +- src/Base/Debugger.h | 2 +- src/Base/DualQuaternion.cpp | 24 +- src/Base/Exception.cpp | 14 +- src/Base/Exception.h | 101 +- src/Base/Factory.h | 2 +- src/Base/FileInfo.cpp | 11 +- src/Base/GeometryPyCXX.cpp | 5 +- src/Base/GeometryPyCXX.h | 6 +- src/Base/Handle.h | 2 +- src/Base/InputSource.cpp | 29 +- src/Base/InputSource.h | 14 +- src/Base/Interpreter.cpp | 99 +- src/Base/Interpreter.h | 76 +- src/Base/Matrix.cpp | 40 +- src/Base/Matrix.h | 5 +- src/Base/MatrixPyImp.cpp | 26 +- src/Base/Observer.h | 45 +- src/Base/Parameter.cpp | 252 +- src/Base/Parameter.h | 104 +- src/Base/ParameterPy.cpp | 65 +- src/Base/PersistencePyImp.cpp | 11 +- src/Base/Placement.h | 3 +- src/Base/PlacementPyImp.cpp | 21 +- src/Base/PreCompiled.h | 16 +- src/Base/Profiler.h | 178 +- src/Base/ProgressIndicator.h | 3 +- src/Base/ProgressIndicatorPy.cpp | 3 +- src/Base/PyExport.h | 18 +- src/Base/PyWrapParseTupleAndKeywords.h | 16 +- src/Base/PythonTypeExt.cpp | 11 +- src/Base/PythonTypeExt.h | 10 +- src/Base/Quantity.cpp | 58 +- src/Base/Quantity.h | 6 +- src/Base/QuantityPyImp.cpp | 7 +- src/Base/Reader.cpp | 72 +- src/Base/Reader.h | 29 +- src/Base/Rotation.cpp | 90 +- src/Base/Rotation.h | 15 +- src/Base/RotationPyImp.cpp | 5 +- src/Base/ServiceProvider.h | 12 +- src/Base/StackWalker.cpp | 389 +- src/Base/StackWalker.h | 20 +- src/Base/Stream.cpp | 63 +- src/Base/Stream.h | 84 +- src/Base/Tools.cpp | 4 +- src/Base/Tools.h | 2 +- src/Base/Tools2D.cpp | 3 +- src/Base/Tools2D.h | 2 +- src/Base/Tools3D.h | 2 +- src/Base/Translate.cpp | 98 +- src/Base/Translate.h | 2 +- src/Base/Type.cpp | 29 +- src/Base/Type.h | 16 +- src/Base/UniqueNameManager.cpp | 37 +- src/Base/UniqueNameManager.h | 10 +- src/Base/Unit.cpp | 35 +- src/Base/Unit.h | 23 +- src/Base/UnitPyImp.cpp | 3 +- src/Base/UnitsApi.cpp | 3 +- src/Base/UnitsApi.h | 6 +- src/Base/UnitsApiPy.cpp | 6 +- src/Base/UnitsSchema.cpp | 40 +- src/Base/UnitsSchema.h | 7 +- src/Base/UnitsSchemas.cpp | 16 +- src/Base/UnitsSchemasData.h | 22 +- src/Base/UnlimitedUnsigned.h | 19 +- src/Base/Uuid.h | 2 +- src/Base/Vector3D.cpp | 58 +- src/Base/Vector3D.h | 23 +- src/Base/VectorPyImp.cpp | 127 +- src/Base/ViewProj.cpp | 5 +- src/Base/Writer.h | 5 +- src/Base/XMLTools.cpp | 41 +- src/Base/XMLTools.h | 26 +- src/Base/ZipHeader.cpp | 28 +- src/Base/swigpyrun.cpp | 38 +- .../3Dconnexion/GuiAbstractNativeEvent.cpp | 8 +- src/Gui/3Dconnexion/GuiAbstractNativeEvent.h | 36 +- src/Gui/3Dconnexion/GuiNativeEventLinux.cpp | 37 +- src/Gui/3Dconnexion/GuiNativeEventLinux.h | 32 +- .../3Dconnexion/GuiNativeEventLinuxX11.cpp | 48 +- src/Gui/3Dconnexion/GuiNativeEventLinuxX11.h | 33 +- src/Gui/3Dconnexion/GuiNativeEventMac.cpp | 158 +- src/Gui/3Dconnexion/GuiNativeEventMac.h | 77 +- src/Gui/3Dconnexion/GuiNativeEventWin32.cpp | 678 ++-- src/Gui/3Dconnexion/GuiNativeEventWin32.h | 114 +- src/Gui/3Dconnexion/GuiRawInputEventFilter.h | 55 +- src/Gui/3Dconnexion/I3dMouseParams.h | 97 +- src/Gui/3Dconnexion/MouseParameters.cpp | 68 +- src/Gui/3Dconnexion/MouseParameters.h | 60 +- src/Gui/Action.cpp | 397 +- src/Gui/Action.h | 135 +- src/Gui/ActionFunction.cpp | 51 +- src/Gui/ActionFunction.h | 8 +- src/Gui/ActiveObjectList.cpp | 155 +- src/Gui/ActiveObjectList.h | 144 +- src/Gui/Application.cpp | 362 +- src/Gui/Application.h | 130 +- src/Gui/ApplicationPy.cpp | 1223 +++--- src/Gui/ApplicationPy.h | 5 +- src/Gui/ArcEngine.cpp | 154 +- src/Gui/ArcEngine.h | 16 +- src/Gui/Assistant.cpp | 84 +- src/Gui/Assistant.h | 13 +- src/Gui/AutoSaver.cpp | 162 +- src/Gui/AutoSaver.h | 20 +- src/Gui/AxisOrigin.cpp | 172 +- src/Gui/AxisOrigin.h | 50 +- src/Gui/AxisOrigin.pyi | 2 - src/Gui/AxisOriginPyImp.cpp | 61 +- src/Gui/BitmapFactory.cpp | 314 +- src/Gui/BitmapFactory.h | 49 +- src/Gui/CallTips.cpp | 333 +- src/Gui/CallTips.h | 32 +- src/Gui/Camera.cpp | 44 +- src/Gui/Camera.h | 10 +- src/Gui/Clipping.h | 14 +- src/Gui/CoinRiftWidget.cpp | 333 +- src/Gui/CoinRiftWidget.h | 98 +- src/Gui/ComboLinks.cpp | 328 +- src/Gui/ComboLinks.h | 232 +- src/Gui/ComboView.cpp | 18 +- src/Gui/ComboView.h | 54 +- src/Gui/Command.cpp | 1052 +++-- src/Gui/Command.h | 815 ++-- src/Gui/Command.pyi | 1 - src/Gui/CommandActionPy.h | 6 +- src/Gui/CommandCompleter.cpp | 211 +- src/Gui/CommandCompleter.h | 17 +- src/Gui/CommandDoc.cpp | 1319 ++++--- src/Gui/CommandFeat.cpp | 124 +- src/Gui/CommandLink.cpp | 830 ++-- src/Gui/CommandMacro.cpp | 216 +- src/Gui/CommandPyImp.cpp | 185 +- src/Gui/CommandStd.cpp | 617 +-- src/Gui/CommandStructure.cpp | 149 +- src/Gui/CommandT.h | 221 +- src/Gui/CommandTest.cpp | 464 +-- src/Gui/CommandView.cpp | 2810 +++++++------ src/Gui/CommandWindow.cpp | 270 +- src/Gui/Control.cpp | 79 +- src/Gui/Control.h | 43 +- src/Gui/CornerCrossLetters.h | 624 ++- src/Gui/DAGView/DAGModel.cpp | 1886 ++++----- src/Gui/DAGView/DAGModel.h | 211 +- src/Gui/DAGView/DAGModelGraph.cpp | 132 +- src/Gui/DAGView/DAGModelGraph.h | 493 +-- src/Gui/DAGView/DAGRectItem.cpp | 64 +- src/Gui/DAGView/DAGRectItem.h | 99 +- src/Gui/DAGView/DAGView.cpp | 134 +- src/Gui/DAGView/DAGView.h | 66 +- src/Gui/DemoMode.cpp | 8 +- src/Gui/DemoMode.h | 24 +- src/Gui/Dialogs/DlgAbout.cpp | 48 +- src/Gui/Dialogs/DlgActionsImp.cpp | 54 +- src/Gui/Dialogs/DlgActionsImp.h | 34 +- src/Gui/Dialogs/DlgActivateWindowImp.cpp | 23 +- src/Gui/Dialogs/DlgActivateWindowImp.h | 14 +- src/Gui/Dialogs/DlgAddProperty.cpp | 211 +- src/Gui/Dialogs/DlgAddProperty.h | 67 +- src/Gui/Dialogs/DlgCheckableMessageBox.cpp | 124 +- src/Gui/Dialogs/DlgCheckableMessageBox.h | 99 +- .../Dialogs/DlgCreateNewPreferencePackImp.cpp | 69 +- .../Dialogs/DlgCreateNewPreferencePackImp.h | 23 +- src/Gui/Dialogs/DlgCustomizeImp.cpp | 50 +- src/Gui/Dialogs/DlgCustomizeImp.h | 28 +- src/Gui/Dialogs/DlgCustomizeSpNavSettings.cpp | 12 +- src/Gui/Dialogs/DlgCustomizeSpNavSettings.h | 104 +- src/Gui/Dialogs/DlgCustomizeSpaceball.cpp | 758 ++-- src/Gui/Dialogs/DlgCustomizeSpaceball.h | 261 +- .../DlgEditFileIncludePropertyExternal.cpp | 18 +- .../DlgEditFileIncludePropertyExternal.h | 20 +- src/Gui/Dialogs/DlgExpressionInput.cpp | 306 +- src/Gui/Dialogs/DlgExpressionInput.h | 55 +- src/Gui/Dialogs/DlgInputDialogImp.cpp | 74 +- src/Gui/Dialogs/DlgInputDialogImp.h | 51 +- src/Gui/Dialogs/DlgKeyboardImp.cpp | 126 +- src/Gui/Dialogs/DlgKeyboardImp.h | 65 +- src/Gui/Dialogs/DlgMacroExecuteImp.cpp | 221 +- src/Gui/Dialogs/DlgMacroExecuteImp.h | 14 +- src/Gui/Dialogs/DlgMacroRecordImp.cpp | 28 +- src/Gui/Dialogs/DlgMacroRecordImp.h | 20 +- src/Gui/Dialogs/DlgMaterialPropertiesImp.h | 3 +- src/Gui/Dialogs/DlgObjectSelection.cpp | 410 +- src/Gui/Dialogs/DlgObjectSelection.h | 59 +- src/Gui/Dialogs/DlgOnlineHelpImp.cpp | 27 +- src/Gui/Dialogs/DlgOnlineHelpImp.h | 18 +- src/Gui/Dialogs/DlgParameterFind.cpp | 4 +- src/Gui/Dialogs/DlgParameterFind.h | 17 +- src/Gui/Dialogs/DlgParameterImp.cpp | 536 +-- src/Gui/Dialogs/DlgParameterImp.h | 117 +- .../DlgPreferencePackManagementImp.cpp | 127 +- .../Dialogs/DlgPreferencePackManagementImp.h | 29 +- src/Gui/Dialogs/DlgPreferencesImp.cpp | 725 ++-- src/Gui/Dialogs/DlgPreferencesImp.h | 146 +- src/Gui/Dialogs/DlgProjectInformationImp.cpp | 30 +- src/Gui/Dialogs/DlgProjectInformationImp.h | 24 +- src/Gui/Dialogs/DlgProjectUtility.cpp | 14 +- src/Gui/Dialogs/DlgProjectUtility.h | 14 +- src/Gui/Dialogs/DlgPropertyLink.cpp | 153 +- src/Gui/Dialogs/DlgPropertyLink.h | 71 +- .../Dialogs/DlgRevertToBackupConfigImp.cpp | 29 +- src/Gui/Dialogs/DlgRevertToBackupConfigImp.h | 18 +- src/Gui/Dialogs/DlgRunExternal.h | 16 +- .../Dialogs/DlgSettingsColorGradientImp.cpp | 19 +- src/Gui/Dialogs/DlgSettingsColorGradientImp.h | 28 +- src/Gui/Dialogs/DlgSettingsImageImp.cpp | 5 +- src/Gui/Dialogs/DlgSettingsImageImp.h | 26 +- src/Gui/Dialogs/DlgThemeEditor.cpp | 120 +- src/Gui/Dialogs/DlgThemeEditor.h | 27 +- src/Gui/Dialogs/DlgToolbarsImp.cpp | 76 +- src/Gui/Dialogs/DlgToolbarsImp.h | 33 +- src/Gui/Dialogs/DlgUndoRedo.cpp | 20 +- src/Gui/Dialogs/DlgUndoRedo.h | 32 +- src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp | 23 +- src/Gui/Dialogs/DlgUnitsCalculatorImp.h | 14 +- src/Gui/Dialogs/DlgVersionMigrator.cpp | 165 +- src/Gui/Dialogs/DlgVersionMigrator.h | 56 +- src/Gui/DockWindow.cpp | 8 +- src/Gui/DockWindow.h | 76 +- src/Gui/DockWindowManager.cpp | 246 +- src/Gui/DockWindowManager.h | 31 +- src/Gui/Document.cpp | 1565 +++++--- src/Gui/Document.h | 161 +- src/Gui/Document.pyi | 6 +- src/Gui/DocumentModel.cpp | 746 ++-- src/Gui/DocumentModel.h | 43 +- src/Gui/DocumentObserver.cpp | 212 +- src/Gui/DocumentObserver.h | 70 +- src/Gui/DocumentObserverPython.cpp | 97 +- src/Gui/DocumentObserverPython.h | 23 +- src/Gui/DocumentPyImp.cpp | 343 +- src/Gui/DocumentRecovery.cpp | 383 +- src/Gui/DocumentRecovery.h | 26 +- src/Gui/DownloadItem.cpp | 81 +- src/Gui/DownloadItem.h | 60 +- src/Gui/DownloadManager.cpp | 118 +- src/Gui/DownloadManager.h | 62 +- src/Gui/EditableDatumLabel.cpp | 133 +- src/Gui/EditableDatumLabel.h | 80 +- src/Gui/EditorView.cpp | 64 +- src/Gui/EditorView.h | 52 +- src/Gui/ElideCheckBox.cpp | 34 +- src/Gui/ElideCheckBox.h | 13 +- src/Gui/ElideLabel.cpp | 20 +- src/Gui/ElideLabel.h | 12 +- src/Gui/ExpressionBinding.cpp | 172 +- src/Gui/ExpressionBinding.h | 54 +- src/Gui/ExpressionBindingPy.cpp | 6 +- src/Gui/ExpressionBindingPy.h | 11 +- src/Gui/ExpressionCompleter.cpp | 182 +- src/Gui/ExpressionCompleter.h | 100 +- src/Gui/FileDialog.cpp | 366 +- src/Gui/FileDialog.h | 161 +- src/Gui/FileHandler.cpp | 41 +- src/Gui/FileHandler.h | 10 +- src/Gui/Flag.cpp | 146 +- src/Gui/Flag.h | 60 +- src/Gui/FontScaledSVG.cpp | 23 +- src/Gui/FontScaledSVG.h | 18 +- src/Gui/FreeCADGuiInit.py | 257 +- src/Gui/GLBuffer.cpp | 84 +- src/Gui/GLBuffer.h | 19 +- src/Gui/GLPainter.cpp | 70 +- src/Gui/GLPainter.h | 38 +- src/Gui/GraphicsViewZoom.cpp | 93 +- src/Gui/GraphicsViewZoom.h | 34 +- src/Gui/GraphvizView.cpp | 358 +- src/Gui/GraphvizView.h | 14 +- src/Gui/GuiApplication.cpp | 141 +- src/Gui/GuiApplication.h | 26 +- src/Gui/GuiApplicationNativeEventAware.cpp | 157 +- src/Gui/GuiApplicationNativeEventAware.h | 53 +- src/Gui/GuiConsole.cpp | 104 +- src/Gui/GuiConsole.h | 36 +- src/Gui/Icons/applications-accessories.svg | 2 +- src/Gui/ImageView.cpp | 75 +- src/Gui/ImageView.h | 20 +- src/Gui/InputField.cpp | 343 +- src/Gui/InputField.h | 104 +- src/Gui/InputHint.h | 15 +- src/Gui/InputHintPy.h | 6 +- src/Gui/InputHintWidget.cpp | 28 +- src/Gui/InputHintWidget.h | 8 +- src/Gui/InputVector.cpp | 95 +- src/Gui/InputVector.h | 286 +- src/Gui/Inventor/Draggers/Gizmo.cpp | 130 +- src/Gui/Inventor/Draggers/Gizmo.h | 4 +- .../Inventor/Draggers/GizmoStyleParameters.h | 15 +- src/Gui/Inventor/Draggers/SoLinearDragger.cpp | 42 +- src/Gui/Inventor/Draggers/SoLinearDragger.h | 38 +- .../Draggers/SoLinearDraggerGeometry.cpp | 14 +- .../Draggers/SoLinearDraggerGeometry.h | 8 +- src/Gui/Inventor/Draggers/SoPlanarDragger.cpp | 39 +- src/Gui/Inventor/Draggers/SoPlanarDragger.h | 27 +- .../Inventor/Draggers/SoRotationDragger.cpp | 55 +- src/Gui/Inventor/Draggers/SoRotationDragger.h | 32 +- .../Draggers/SoRotationDraggerGeometry.cpp | 24 +- .../Draggers/SoRotationDraggerGeometry.h | 18 +- .../Inventor/Draggers/SoTransformDragger.cpp | 249 +- .../Inventor/Draggers/SoTransformDragger.h | 127 +- src/Gui/Inventor/MarkerBitmaps.cpp | 2116 +++++----- src/Gui/Inventor/MarkerBitmaps.h | 15 +- src/Gui/Inventor/SmSwitchboard.cpp | 169 +- src/Gui/Inventor/SmSwitchboard.h | 36 +- src/Gui/Inventor/So3DAnnotation.cpp | 56 +- src/Gui/Inventor/So3DAnnotation.h | 16 +- src/Gui/Inventor/SoAutoZoomTranslation.cpp | 71 +- src/Gui/Inventor/SoAutoZoomTranslation.h | 25 +- src/Gui/Inventor/SoAxisCrossKit.cpp | 268 +- src/Gui/Inventor/SoAxisCrossKit.h | 30 +- src/Gui/Inventor/SoDrawingGrid.cpp | 148 +- src/Gui/Inventor/SoDrawingGrid.h | 28 +- src/Gui/Inventor/SoFCBackgroundGradient.cpp | 115 +- src/Gui/Inventor/SoFCBackgroundGradient.h | 23 +- src/Gui/Inventor/SoFCBoundingBox.cpp | 98 +- src/Gui/Inventor/SoFCBoundingBox.h | 42 +- .../Inventor/SoFCPlacementIndicatorKit.cpp | 29 +- src/Gui/Inventor/SoFCPlacementIndicatorKit.h | 10 +- src/Gui/Inventor/SoFCTransform.cpp | 24 +- src/Gui/Inventor/SoFCTransform.h | 18 +- src/Gui/Inventor/SoMouseWheelEvent.cpp | 2 +- src/Gui/Inventor/SoMouseWheelEvent.h | 33 +- src/Gui/Inventor/SoToggleSwitch.cpp | 2 +- src/Gui/InventorAll.h | 6 +- src/Gui/Language/Translator.cpp | 138 +- src/Gui/Language/Translator.h | 18 +- src/Gui/Language/translation.qrc | 2 +- src/Gui/LinkView.pyi | 18 +- src/Gui/LinkViewPyImp.cpp | 377 +- src/Gui/MDIView.cpp | 159 +- src/Gui/MDIView.h | 52 +- src/Gui/MDIViewPy.cpp | 135 +- src/Gui/MDIViewPy.h | 22 +- src/Gui/MDIViewPyWrap.cpp | 39 +- src/Gui/MDIViewPyWrap.h | 17 +- src/Gui/Macro.cpp | 123 +- src/Gui/Macro.h | 73 +- src/Gui/MainWindow.cpp | 1294 +++--- src/Gui/MainWindow.h | 135 +- src/Gui/MainWindowPy.cpp | 47 +- src/Gui/MainWindowPy.h | 17 +- src/Gui/ManualAlignment.cpp | 543 +-- src/Gui/ManualAlignment.h | 43 +- src/Gui/MenuManager.cpp | 52 +- src/Gui/MenuManager.h | 17 +- src/Gui/MergeDocuments.cpp | 61 +- src/Gui/MergeDocuments.h | 33 +- src/Gui/MetaTypes.h | 2 +- src/Gui/ModuleIO.cpp | 9 +- src/Gui/ModuleIO.h | 7 +- src/Gui/MouseSelection.h | 70 +- src/Gui/Multisample.cpp | 10 +- src/Gui/Multisample.h | 12 +- src/Gui/Namespace.h | 10 +- src/Gui/NaviCube.cpp | 553 +-- src/Gui/NaviCube.h | 9 +- src/Gui/Navigation/BlenderNavigationStyle.cpp | 327 +- src/Gui/Navigation/CADNavigationStyle.cpp | 372 +- src/Gui/Navigation/GestureNavigationStyle.cpp | 872 ++-- src/Gui/Navigation/GestureNavigationStyle.h | 58 +- .../Navigation/InventorNavigationStyle.cpp | 315 +- .../Navigation/MayaGestureNavigationStyle.cpp | 932 +++-- src/Gui/Navigation/NavigationAnimation.cpp | 24 +- src/Gui/Navigation/NavigationAnimation.h | 25 +- src/Gui/Navigation/NavigationAnimator.h | 6 +- src/Gui/Navigation/NavigationStateChart.cpp | 45 +- src/Gui/Navigation/NavigationStateChart.h | 66 +- src/Gui/Navigation/NavigationStyle.cpp | 591 +-- src/Gui/Navigation/NavigationStyle.h | 219 +- src/Gui/Navigation/NavigationStyle.pyi | 2 +- .../Navigation/OpenCascadeNavigationStyle.cpp | 271 +- .../Navigation/OpenSCADNavigationStyle.cpp | 254 +- src/Gui/Navigation/RevitNavigationStyle.cpp | 323 +- .../Navigation/SiemensNXNavigationStyle.cpp | 204 +- src/Gui/Navigation/SiemensNXNavigationStyle.h | 5 +- .../Navigation/SolidWorksNavigationStyle.cpp | 316 +- .../Navigation/TinkerCADNavigationStyle.cpp | 236 +- .../Navigation/TouchpadNavigationStyle.cpp | 272 +- src/Gui/NetworkRetriever.cpp | 309 +- src/Gui/NetworkRetriever.h | 37 +- src/Gui/NotificationArea.cpp | 483 ++- src/Gui/NotificationArea.h | 13 +- src/Gui/NotificationBox.cpp | 107 +- src/Gui/NotificationBox.h | 28 +- src/Gui/Notifications.h | 404 +- src/Gui/OnlineDocumentation.cpp | 67 +- src/Gui/OnlineDocumentation.h | 19 +- src/Gui/OverlayManager.cpp | 1832 +++++---- src/Gui/OverlayManager.h | 59 +- src/Gui/OverlayParams.cpp | 773 ++-- src/Gui/OverlayParams.h | 230 +- src/Gui/OverlayParams.py | 308 +- src/Gui/OverlayWidgets.cpp | 1904 +++++---- src/Gui/OverlayWidgets.h | 309 +- src/Gui/ParamHandler.cpp | 60 +- src/Gui/ParamHandler.h | 171 +- src/Gui/Placement.cpp | 376 +- src/Gui/Placement.h | 59 +- src/Gui/PreCompiled.h | 10 +- src/Gui/PrefWidgets.cpp | 709 ++-- src/Gui/PrefWidgets.h | 379 +- src/Gui/PreferencePackManager.cpp | 232 +- src/Gui/PreferencePackManager.h | 372 +- src/Gui/PreferencePacks/CMakeLists.txt | 2 +- .../PreferencePages/DlgSettings3DViewImp.cpp | 61 +- .../PreferencePages/DlgSettings3DViewImp.h | 16 +- .../PreferencePages/DlgSettingsAdvanced.cpp | 126 +- src/Gui/PreferencePages/DlgSettingsAdvanced.h | 112 +- .../PreferencePages/DlgSettingsAdvanced.py | 76 +- .../DlgSettingsCacheDirectory.cpp | 96 +- .../DlgSettingsCacheDirectory.h | 21 +- .../DlgSettingsDocumentImp.cpp | 35 +- .../PreferencePages/DlgSettingsDocumentImp.h | 18 +- src/Gui/PreferencePages/DlgSettingsEditor.cpp | 81 +- src/Gui/PreferencePages/DlgSettingsEditor.h | 24 +- .../PreferencePages/DlgSettingsGeneral.cpp | 342 +- src/Gui/PreferencePages/DlgSettingsGeneral.h | 64 +- .../DlgSettingsLightSources.cpp | 237 +- .../PreferencePages/DlgSettingsLightSources.h | 22 +- .../PreferencePages/DlgSettingsMacroImp.cpp | 18 +- src/Gui/PreferencePages/DlgSettingsMacroImp.h | 18 +- .../PreferencePages/DlgSettingsNavigation.cpp | 138 +- .../PreferencePages/DlgSettingsNavigation.h | 20 +- .../DlgSettingsNotificationArea.cpp | 15 +- .../DlgSettingsNotificationArea.h | 16 +- src/Gui/PreferencePages/DlgSettingsPDF.cpp | 51 +- src/Gui/PreferencePages/DlgSettingsPDF.h | 42 +- .../DlgSettingsPythonConsole.cpp | 4 +- .../DlgSettingsPythonConsole.h | 16 +- .../PreferencePages/DlgSettingsReportView.cpp | 8 +- .../PreferencePages/DlgSettingsReportView.h | 18 +- .../PreferencePages/DlgSettingsSelection.cpp | 2 +- .../PreferencePages/DlgSettingsSelection.h | 16 +- src/Gui/PreferencePages/DlgSettingsUI.cpp | 24 +- src/Gui/PreferencePages/DlgSettingsUI.h | 45 +- .../PreferencePages/DlgSettingsViewColor.h | 40 +- .../DlgSettingsWorkbenchesImp.cpp | 218 +- .../DlgSettingsWorkbenchesImp.h | 58 +- .../PreferencePages/ListWidgetDragBugFix.cpp | 55 +- .../PreferencePages/ListWidgetDragBugFix.h | 60 +- src/Gui/ProgressBar.cpp | 304 +- src/Gui/ProgressBar.h | 45 +- src/Gui/ProgressDialog.cpp | 163 +- src/Gui/ProgressDialog.h | 25 +- src/Gui/PropertyPage.cpp | 163 +- src/Gui/PropertyPage.h | 93 +- src/Gui/PropertyView.cpp | 318 +- src/Gui/PropertyView.h | 51 +- src/Gui/PythonConsole.cpp | 703 ++-- src/Gui/PythonConsole.h | 82 +- src/Gui/PythonConsolePy.cpp | 84 +- src/Gui/PythonConsolePy.h | 43 +- src/Gui/PythonDebugger.cpp | 229 +- src/Gui/PythonDebugger.h | 52 +- src/Gui/PythonEditor.cpp | 534 ++- src/Gui/PythonEditor.h | 23 +- src/Gui/PythonTracing.cpp | 16 +- src/Gui/PythonTracing.h | 26 +- src/Gui/PythonWorkbench.pyi | 1 - src/Gui/PythonWorkbenchPyImp.cpp | 213 +- src/Gui/PythonWrapper.cpp | 304 +- src/Gui/PythonWrapper.h | 15 +- src/Gui/QuantitySpinBox.cpp | 301 +- src/Gui/QuantitySpinBox.h | 73 +- src/Gui/QuantitySpinBox_p.h | 28 +- src/Gui/RemoteDebugger.py | 12 +- src/Gui/ReportView.cpp | 299 +- src/Gui/ReportView.h | 85 +- src/Gui/SceneInspector.cpp | 245 +- src/Gui/SceneInspector.h | 31 +- src/Gui/Selection/Selection.cpp | 1981 ++++++---- src/Gui/Selection/Selection.h | 450 ++- src/Gui/Selection/SelectionFilter.cpp | 141 +- src/Gui/Selection/SelectionFilter.h | 57 +- src/Gui/Selection/SelectionFilter.l | 4 - src/Gui/Selection/SelectionFilter.lex.cpp | 1530 ++++--- src/Gui/Selection/SelectionFilter.tab.c | 1672 ++++---- src/Gui/Selection/SelectionFilterPy.cpp | 45 +- src/Gui/Selection/SelectionFilterPy.h | 14 +- src/Gui/Selection/SelectionObject.cpp | 20 +- src/Gui/Selection/SelectionObject.h | 70 +- src/Gui/Selection/SelectionObject.pyi | 2 - src/Gui/Selection/SelectionObjectPyImp.cpp | 54 +- src/Gui/Selection/SelectionObserverPython.cpp | 108 +- src/Gui/Selection/SelectionObserverPython.h | 13 +- src/Gui/Selection/SelectionView.cpp | 350 +- src/Gui/Selection/SelectionView.h | 117 +- src/Gui/Selection/SoFCSelection.cpp | 559 +-- src/Gui/Selection/SoFCSelection.h | 75 +- src/Gui/Selection/SoFCSelectionAction.cpp | 1009 +++-- src/Gui/Selection/SoFCSelectionAction.h | 136 +- src/Gui/Selection/SoFCSelectionContext.cpp | 227 +- src/Gui/Selection/SoFCSelectionContext.h | 82 +- src/Gui/Selection/SoFCUnifiedSelection.cpp | 1252 +++--- src/Gui/Selection/SoFCUnifiedSelection.h | 313 +- src/Gui/ShortcutManager.cpp | 308 +- src/Gui/ShortcutManager.h | 67 +- src/Gui/SoDatumLabel.cpp | 586 +-- src/Gui/SoDatumLabel.h | 213 +- src/Gui/SoDevicePixelRatioElement.cpp | 63 +- src/Gui/SoDevicePixelRatioElement.h | 47 +- src/Gui/SoFCColorBar.cpp | 116 +- src/Gui/SoFCColorBar.h | 325 +- src/Gui/SoFCColorBarNotifier.cpp | 4 +- src/Gui/SoFCColorBarNotifier.h | 7 +- src/Gui/SoFCColorGradient.cpp | 96 +- src/Gui/SoFCColorGradient.h | 153 +- src/Gui/SoFCColorLegend.cpp | 93 +- src/Gui/SoFCColorLegend.h | 113 +- src/Gui/SoFCDB.cpp | 459 ++- src/Gui/SoFCDB.h | 28 +- src/Gui/SoFCInteractiveElement.cpp | 147 +- src/Gui/SoFCInteractiveElement.h | 120 +- src/Gui/SoFCOffscreenRenderer.cpp | 360 +- src/Gui/SoFCOffscreenRenderer.h | 129 +- src/Gui/SoFCVectorizeSVGAction.cpp | 242 +- src/Gui/SoFCVectorizeSVGAction.h | 57 +- src/Gui/SoFCVectorizeU3DAction.cpp | 239 +- src/Gui/SoFCVectorizeU3DAction.h | 27 +- src/Gui/SoQtOffscreenRendererPy.cpp | 33 +- src/Gui/SoQtOffscreenRendererPy.h | 9 +- src/Gui/SoTextLabel.cpp | 186 +- src/Gui/SoTextLabel.h | 69 +- src/Gui/SoTouchEvents.cpp | 102 +- src/Gui/SoTouchEvents.h | 75 +- src/Gui/SpaceballEvent.cpp | 80 +- src/Gui/SpaceballEvent.h | 135 +- src/Gui/SpinBox.cpp | 189 +- src/Gui/SpinBox.h | 107 +- src/Gui/SplashScreen.cpp | 62 +- src/Gui/SplitView3DInventor.cpp | 241 +- src/Gui/SplitView3DInventor.h | 43 +- src/Gui/StartupProcess.cpp | 133 +- src/Gui/StartupProcess.h | 7 +- src/Gui/StatusBarLabel.cpp | 26 +- src/Gui/StatusBarLabel.h | 12 +- src/Gui/StyleParameters/ParameterManager.cpp | 23 +- src/Gui/StyleParameters/ParameterManager.h | 45 +- src/Gui/StyleParameters/Parser.cpp | 89 +- src/Gui/StyleParameters/Parser.h | 2 +- src/Gui/Stylesheets/FreeCAD Dark.qss | 3 +- src/Gui/Stylesheets/FreeCAD Light.qss | 2 +- src/Gui/Stylesheets/FreeCAD.qss | 2 +- .../overlay/Dark Theme + Dark Background.qss | 1 - .../overlay/Light Theme + Dark Background.qss | 2 - src/Gui/Stylesheets/overlay/icons/mode.svg | 2 +- src/Gui/SyntaxHighlighter.cpp | 127 +- src/Gui/SyntaxHighlighter.h | 22 +- src/Gui/TaskDlgRelocation.cpp | 23 +- src/Gui/TaskDlgRelocation.h | 25 +- src/Gui/TaskElementColors.cpp | 83 +- src/Gui/TaskElementColors.h | 30 +- src/Gui/TaskTransform.cpp | 252 +- src/Gui/TaskTransform.h | 56 +- src/Gui/TaskView/TaskAppearance.cpp | 18 +- src/Gui/TaskView/TaskAppearance.h | 27 +- src/Gui/TaskView/TaskDialog.cpp | 55 +- src/Gui/TaskView/TaskDialog.h | 116 +- src/Gui/TaskView/TaskDialogPython.cpp | 406 +- src/Gui/TaskView/TaskDialogPython.h | 33 +- src/Gui/TaskView/TaskEditControl.cpp | 4 +- src/Gui/TaskView/TaskEditControl.h | 24 +- src/Gui/TaskView/TaskImage.cpp | 56 +- src/Gui/TaskView/TaskImage.h | 25 +- src/Gui/TaskView/TaskOrientation.cpp | 6 +- src/Gui/TaskView/TaskOrientation.h | 14 +- src/Gui/TaskView/TaskSelectLinkProperty.cpp | 19 +- src/Gui/TaskView/TaskSelectLinkProperty.h | 48 +- src/Gui/TaskView/TaskSolverMessages.cpp | 86 +- src/Gui/TaskView/TaskSolverMessages.h | 8 +- src/Gui/TaskView/TaskSolverMessages.ui | 2 +- src/Gui/TaskView/TaskView.cpp | 316 +- src/Gui/TaskView/TaskView.h | 97 +- src/Gui/TaskView/TaskWatcher.cpp | 59 +- src/Gui/TaskView/TaskWatcher.h | 44 +- src/Gui/TextDocumentEditorView.cpp | 12 +- src/Gui/TextDocumentEditorView.h | 4 +- src/Gui/TextEdit.cpp | 252 +- src/Gui/TextEdit.h | 61 +- src/Gui/TextureMapping.cpp | 54 +- src/Gui/TextureMapping.h | 24 +- src/Gui/Thumbnail.cpp | 54 +- src/Gui/Thumbnail.h | 21 +- src/Gui/ToolBarAreaWidget.cpp | 20 +- src/Gui/ToolBarAreaWidget.h | 39 +- src/Gui/ToolBarManager.cpp | 301 +- src/Gui/ToolBarManager.h | 77 +- src/Gui/ToolBox.cpp | 144 +- src/Gui/ToolBox.h | 92 +- src/Gui/ToolBoxManager.cpp | 47 +- src/Gui/ToolBoxManager.h | 13 +- src/Gui/ToolHandler.cpp | 23 +- src/Gui/ToolHandler.h | 11 +- src/Gui/Tools.h | 14 +- src/Gui/TransactionObject.cpp | 1 - src/Gui/TransactionObject.h | 6 +- src/Gui/Transform.cpp | 180 +- src/Gui/Transform.h | 27 +- src/Gui/Tree.cpp | 2991 ++++++++------ src/Gui/Tree.h | 346 +- src/Gui/TreeItemMode.h | 45 +- src/Gui/TreeParams.cpp | 886 +++-- src/Gui/TreeParams.h | 337 +- src/Gui/TreeParams.py | 171 +- src/Gui/TreeView.cpp | 27 +- src/Gui/TreeView.h | 16 +- src/Gui/UiLoader.cpp | 177 +- src/Gui/UiLoader.h | 54 +- src/Gui/Utilities.cpp | 78 +- src/Gui/Utilities.h | 201 +- src/Gui/VectorListEditor.cpp | 127 +- src/Gui/VectorListEditor.h | 52 +- src/Gui/View.cpp | 32 +- src/Gui/View.h | 48 +- src/Gui/View3DInventor.cpp | 369 +- src/Gui/View3DInventor.h | 60 +- src/Gui/View3DInventorRiftViewer.cpp | 157 +- src/Gui/View3DInventorRiftViewer.h | 27 +- src/Gui/View3DInventorSelection.cpp | 162 +- src/Gui/View3DInventorSelection.h | 21 +- src/Gui/View3DInventorViewer.cpp | 1272 +++--- src/Gui/View3DInventorViewer.h | 218 +- src/Gui/View3DPy.cpp | 1054 +++-- src/Gui/View3DPy.h | 33 +- src/Gui/View3DSettings.cpp | 298 +- src/Gui/View3DViewerPy.cpp | 338 +- src/Gui/View3DViewerPy.h | 35 +- src/Gui/ViewParams.cpp | 32 +- src/Gui/ViewParams.h | 91 +- src/Gui/ViewProvider.cpp | 621 +-- src/Gui/ViewProvider.h | 356 +- src/Gui/ViewProvider.pyi | 17 +- src/Gui/ViewProviderAnnotation.cpp | 184 +- src/Gui/ViewProviderAnnotation.h | 66 +- src/Gui/ViewProviderBuilder.cpp | 10 +- src/Gui/ViewProviderBuilder.h | 11 +- src/Gui/ViewProviderCoordinateSystem.cpp | 63 +- src/Gui/ViewProviderCoordinateSystem.h | 28 +- src/Gui/ViewProviderDatum.cpp | 41 +- src/Gui/ViewProviderDatum.h | 73 +- src/Gui/ViewProviderDocumentObject.cpp | 436 +- src/Gui/ViewProviderDocumentObject.h | 85 +- src/Gui/ViewProviderDocumentObject.pyi | 2 - src/Gui/ViewProviderDocumentObjectGroup.cpp | 26 +- src/Gui/ViewProviderDocumentObjectGroup.h | 20 +- src/Gui/ViewProviderDocumentObjectPyImp.cpp | 29 +- src/Gui/ViewProviderDragger.cpp | 63 +- src/Gui/ViewProviderDragger.h | 45 +- src/Gui/ViewProviderExtension.cpp | 27 +- src/Gui/ViewProviderExtension.h | 173 +- src/Gui/ViewProviderExtension.pyi | 1 - src/Gui/ViewProviderExtensionPyImp.cpp | 26 +- src/Gui/ViewProviderExtensionPython.h | 18 +- src/Gui/ViewProviderExtern.cpp | 36 +- src/Gui/ViewProviderExtern.h | 15 +- src/Gui/ViewProviderFeature.cpp | 5 +- src/Gui/ViewProviderFeature.h | 14 +- src/Gui/ViewProviderFeaturePython.cpp | 544 +-- src/Gui/ViewProviderFeaturePython.h | 549 +-- src/Gui/ViewProviderGeoFeatureGroup.cpp | 6 +- src/Gui/ViewProviderGeoFeatureGroup.h | 12 +- .../ViewProviderGeoFeatureGroupExtension.cpp | 63 +- .../ViewProviderGeoFeatureGroupExtension.h | 44 +- src/Gui/ViewProviderGeometryObject.cpp | 85 +- src/Gui/ViewProviderGeometryObject.h | 16 +- src/Gui/ViewProviderGeometryObject.pyi | 1 - src/Gui/ViewProviderGeometryObjectPyImp.cpp | 1 - src/Gui/ViewProviderGroupExtension.cpp | 197 +- src/Gui/ViewProviderGroupExtension.h | 12 +- src/Gui/ViewProviderImagePlane.cpp | 76 +- src/Gui/ViewProviderImagePlane.h | 16 +- src/Gui/ViewProviderInventorObject.cpp | 50 +- src/Gui/ViewProviderInventorObject.h | 17 +- src/Gui/ViewProviderLine.cpp | 21 +- src/Gui/ViewProviderLine.h | 7 +- src/Gui/ViewProviderLink.cpp | 3116 +++++++++------ src/Gui/ViewProviderLink.h | 238 +- src/Gui/ViewProviderLink.pyi | 1 - src/Gui/ViewProviderLinkPyImp.cpp | 27 +- src/Gui/ViewProviderMaterialObject.cpp | 24 +- src/Gui/ViewProviderMaterialObject.h | 16 +- src/Gui/ViewProviderOriginGroup.cpp | 5 +- src/Gui/ViewProviderOriginGroup.h | 10 +- src/Gui/ViewProviderOriginGroupExtension.cpp | 41 +- src/Gui/ViewProviderOriginGroupExtension.h | 18 +- src/Gui/ViewProviderPart.cpp | 66 +- src/Gui/ViewProviderPart.h | 17 +- src/Gui/ViewProviderPlacement.cpp | 46 +- src/Gui/ViewProviderPlacement.h | 18 +- src/Gui/ViewProviderPlane.cpp | 46 +- src/Gui/ViewProviderPlane.h | 13 +- src/Gui/ViewProviderPoint.cpp | 20 +- src/Gui/ViewProviderPoint.h | 12 +- src/Gui/ViewProviderPyImp.cpp | 512 ++- src/Gui/ViewProviderSuppressibleExtension.cpp | 36 +- src/Gui/ViewProviderSuppressibleExtension.h | 13 +- src/Gui/ViewProviderTextDocument.cpp | 78 +- src/Gui/ViewProviderTextDocument.h | 17 +- src/Gui/ViewProviderTextureExtension.cpp | 25 +- src/Gui/ViewProviderTextureExtension.h | 11 +- src/Gui/ViewProviderVRMLObject.cpp | 86 +- src/Gui/ViewProviderVRMLObject.h | 13 +- src/Gui/ViewProviderVarSet.cpp | 2 +- src/Gui/ViewProviderVarSet.h | 13 +- src/Gui/WaitCursor.cpp | 76 +- src/Gui/WaitCursor.h | 11 +- src/Gui/WhatsThis.cpp | 61 +- src/Gui/WhatsThis.h | 27 +- src/Gui/WidgetFactory.cpp | 275 +- src/Gui/WidgetFactory.h | 103 +- src/Gui/Widgets.cpp | 644 +-- src/Gui/Widgets.h | 335 +- src/Gui/Window.cpp | 15 +- src/Gui/Window.h | 18 +- src/Gui/Workbench.cpp | 377 +- src/Gui/Workbench.h | 60 +- src/Gui/Workbench.pyi | 1 - src/Gui/WorkbenchFactory.cpp | 19 +- src/Gui/WorkbenchFactory.h | 51 +- src/Gui/WorkbenchManager.cpp | 24 +- src/Gui/WorkbenchManager.h | 13 +- src/Gui/WorkbenchManipulator.cpp | 21 +- src/Gui/WorkbenchManipulator.h | 19 +- src/Gui/WorkbenchManipulatorPython.cpp | 22 +- src/Gui/WorkbenchManipulatorPython.h | 13 +- src/Gui/WorkbenchPyImp.cpp | 95 +- src/Gui/WorkbenchSelector.cpp | 77 +- src/Gui/WorkbenchSelector.h | 59 +- src/Gui/cet_lut.hpp | 2675 ++++++++++++- src/Gui/propertyeditor/PropertyEditor.cpp | 181 +- src/Gui/propertyeditor/PropertyEditor.h | 23 +- src/Gui/propertyeditor/PropertyItem.cpp | 657 ++-- src/Gui/propertyeditor/PropertyItem.h | 248 +- .../propertyeditor/PropertyItemDelegate.cpp | 118 +- src/Gui/propertyeditor/PropertyItemDelegate.h | 39 +- src/Gui/propertyeditor/PropertyModel.cpp | 14 +- src/Gui/propertyeditor/PropertyModel.h | 59 +- src/Gui/resource.cpp | 6 +- src/Main/FreeCADGuiPy.cpp | 43 +- src/Main/MainCmd.cpp | 8 +- src/Main/MainGui.cpp | 114 +- src/Main/MainPy.cpp | 20 +- src/Mod/Assembly/App/AssemblyLink.cpp | 100 +- src/Mod/Assembly/App/AssemblyLink.h | 8 +- src/Mod/Assembly/App/AssemblyObject.cpp | 221 +- src/Mod/Assembly/App/AssemblyObject.h | 79 +- src/Mod/Assembly/App/AssemblyObjectPyImp.cpp | 18 +- src/Mod/Assembly/App/AssemblyUtils.cpp | 37 +- src/Mod/Assembly/App/AssemblyUtils.h | 64 +- src/Mod/Assembly/App/BomObject.cpp | 47 +- src/Mod/Assembly/App/BomObject.h | 3 +- src/Mod/Assembly/AssemblyGlobal.h | 30 +- src/Mod/Assembly/Gui/TaskAssemblyMessages.cpp | 9 +- src/Mod/Assembly/Gui/ViewProviderAssembly.cpp | 324 +- src/Mod/Assembly/Gui/ViewProviderAssembly.h | 46 +- .../Assembly/Gui/ViewProviderAssemblyLink.cpp | 36 +- src/Mod/CAM/App/AppPathPy.cpp | 245 +- src/Mod/CAM/App/Area.cpp | 671 ++-- src/Mod/CAM/App/Area.h | 126 +- src/Mod/CAM/App/AreaParams.h | 352 +- src/Mod/CAM/App/AreaPyImp.cpp | 262 +- src/Mod/CAM/App/Command.cpp | 9 +- src/Mod/CAM/App/Command.h | 29 +- src/Mod/CAM/App/CommandPyImp.cpp | 30 +- src/Mod/CAM/App/FeatureArea.cpp | 15 +- src/Mod/CAM/App/FeatureAreaPyImp.cpp | 30 +- src/Mod/CAM/App/FeaturePath.cpp | 6 +- src/Mod/CAM/App/FeaturePathCompound.cpp | 19 +- src/Mod/CAM/App/FeaturePathCompoundPyImp.cpp | 24 +- src/Mod/CAM/App/FeaturePathShape.cpp | 18 +- src/Mod/CAM/App/ParamsHelper.h | 198 +- src/Mod/CAM/App/Path.cpp | 52 +- src/Mod/CAM/App/Path.h | 5 +- src/Mod/CAM/App/PathPyImp.cpp | 6 +- src/Mod/CAM/App/PathSegmentWalker.cpp | 80 +- src/Mod/CAM/App/PathSegmentWalker.h | 46 +- src/Mod/CAM/App/Voronoi.cpp | 39 +- src/Mod/CAM/App/VoronoiCellPyImp.cpp | 6 +- src/Mod/CAM/App/VoronoiEdgePyImp.cpp | 41 +- src/Mod/CAM/App/VoronoiPyImp.cpp | 21 +- src/Mod/CAM/App/VoronoiVertexPyImp.cpp | 12 +- src/Mod/CAM/Gui/AppPathGuiPy.cpp | 46 +- src/Mod/CAM/Gui/Command.cpp | 79 +- src/Mod/CAM/Gui/TaskDlgPathCompound.cpp | 8 +- src/Mod/CAM/Gui/TaskDlgPathCompound.h | 3 +- src/Mod/CAM/Gui/ViewProviderArea.cpp | 13 +- src/Mod/CAM/Gui/ViewProviderPath.cpp | 161 +- src/Mod/CAM/Gui/ViewProviderPathShape.cpp | 10 +- src/Mod/CAM/PathGlobal.h | 58 +- src/Mod/CAM/PathSimulator/App/PathSim.cpp | 16 +- .../CAM/PathSimulator/App/PathSimPyImp.cpp | 38 +- src/Mod/CAM/PathSimulator/App/VolSim.cpp | 20 +- src/Mod/CAM/PathSimulator/App/VolSim.h | 14 +- src/Mod/CAM/PathSimulator/AppGL/CAMSim.cpp | 10 +- src/Mod/CAM/PathSimulator/AppGL/CAMSim.h | 10 +- .../CAM/PathSimulator/AppGL/CAMSimPyImp.cpp | 61 +- .../PathSimulator/AppGL/DlgCAMSimulator.cpp | 20 +- .../CAM/PathSimulator/AppGL/DlgCAMSimulator.h | 22 +- src/Mod/CAM/PathSimulator/AppGL/EndMill.cpp | 11 +- .../CAM/PathSimulator/AppGL/GCodeParser.cpp | 6 +- src/Mod/CAM/PathSimulator/AppGL/GlUtils.h | 22 +- .../CAM/PathSimulator/AppGL/GuiDisplay.cpp | 100 +- .../CAM/PathSimulator/AppGL/MillPathLine.cpp | 26 +- .../PathSimulator/AppGL/MillPathSegment.cpp | 30 +- .../PathSimulator/AppGL/MillSimulation.cpp | 4 +- src/Mod/CAM/PathSimulator/AppGL/Shader.cpp | 10 +- .../CAM/PathSimulator/AppGL/SimDisplay.cpp | 32 +- src/Mod/CAM/PathSimulator/AppGL/SimShapes.cpp | 108 +- src/Mod/CAM/PathSimulator/AppGL/SimShapes.h | 96 +- .../CAM/PathSimulator/AppGL/TextureLoader.cpp | 13 +- src/Mod/CAM/PathSimulator/AppGL/linmath.h | 116 +- src/Mod/CAM/libarea/Adaptive.cpp | 664 ++-- src/Mod/CAM/libarea/Adaptive.hpp | 145 +- src/Mod/CAM/libarea/Arc.h | 5 +- src/Mod/CAM/libarea/Area.cpp | 102 +- src/Mod/CAM/libarea/Area.h | 43 +- src/Mod/CAM/libarea/AreaClipper.cpp | 37 +- src/Mod/CAM/libarea/AreaDxf.cpp | 21 +- src/Mod/CAM/libarea/AreaDxf.h | 15 +- src/Mod/CAM/libarea/AreaPocket.cpp | 90 +- src/Mod/CAM/libarea/Curve.cpp | 68 +- src/Mod/CAM/libarea/Curve.h | 36 +- src/Mod/CAM/libarea/clipper.cpp | 185 +- src/Mod/CAM/libarea/clipper.hpp | 27 +- src/Mod/CAM/libarea/kurve/Construction.cpp | 23 +- src/Mod/CAM/libarea/kurve/Finite.cpp | 7 +- src/Mod/CAM/libarea/kurve/Matrix.cpp | 17 +- src/Mod/CAM/libarea/kurve/geometry.h | 479 ++- src/Mod/CAM/libarea/kurve/kurve.cpp | 25 +- src/Mod/CAM/libarea/kurve/offset.cpp | 25 +- src/Mod/CAM/libarea/pyarea.cpp | 64 +- src/Mod/Cloud/App/AppCloud.cpp | 476 +-- src/Mod/Cloud/App/AppCloud.h | 126 +- src/Mod/Cloud/CloudGlobal.h | 20 +- src/Mod/Cloud/Gui/PreCompiled.h | 2 +- src/Mod/Draft/App/AppDraftUtilsPy.cpp | 29 +- src/Mod/Draft/DraftGlobal.h | 16 +- src/Mod/Fem/App/AppFem.cpp | 10 +- src/Mod/Fem/App/AppFemPy.cpp | 135 +- src/Mod/Fem/App/FemAnalysis.cpp | 8 +- src/Mod/Fem/App/FemAnalysis.h | 8 +- src/Mod/Fem/App/FemConstraint.cpp | 102 +- src/Mod/Fem/App/FemConstraint.h | 26 +- src/Mod/Fem/App/FemConstraintBearing.cpp | 36 +- src/Mod/Fem/App/FemConstraintContact.cpp | 98 +- src/Mod/Fem/App/FemConstraintContact.h | 8 +- src/Mod/Fem/App/FemConstraintDisplacement.cpp | 260 +- src/Mod/Fem/App/FemConstraintDisplacement.h | 8 +- .../Fem/App/FemConstraintFluidBoundary.cpp | 3 +- src/Mod/Fem/App/FemConstraintForce.cpp | 59 +- src/Mod/Fem/App/FemConstraintForce.h | 8 +- src/Mod/Fem/App/FemConstraintGear.cpp | 24 +- src/Mod/Fem/App/FemConstraintHeatflux.cpp | 56 +- src/Mod/Fem/App/FemConstraintHeatflux.h | 8 +- .../App/FemConstraintInitialTemperature.cpp | 32 +- .../Fem/App/FemConstraintInitialTemperature.h | 8 +- src/Mod/Fem/App/FemConstraintPressure.cpp | 32 +- src/Mod/Fem/App/FemConstraintPressure.h | 8 +- src/Mod/Fem/App/FemConstraintPulley.cpp | 41 +- src/Mod/Fem/App/FemConstraintRigidBody.cpp | 186 +- src/Mod/Fem/App/FemConstraintTemperature.cpp | 44 +- src/Mod/Fem/App/FemConstraintTemperature.h | 8 +- src/Mod/Fem/App/FemConstraintTransform.cpp | 80 +- src/Mod/Fem/App/FemConstraintTransform.h | 8 +- src/Mod/Fem/App/FemMesh.cpp | 313 +- src/Mod/Fem/App/FemMesh.h | 24 +- src/Mod/Fem/App/FemMeshPyImp.cpp | 780 ++-- src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp | 26 +- src/Mod/Fem/App/FemMeshShapeObject.cpp | 3 +- src/Mod/Fem/App/FemPostBranchFilter.cpp | 19 +- src/Mod/Fem/App/FemPostFilter.cpp | 375 +- src/Mod/Fem/App/FemPostFilter.h | 8 +- src/Mod/Fem/App/FemPostFilterPyImp.cpp | 9 +- src/Mod/Fem/App/FemPostFunction.cpp | 22 +- src/Mod/Fem/App/FemPostFunction.h | 8 +- src/Mod/Fem/App/FemPostGroupExtension.cpp | 19 +- src/Mod/Fem/App/FemPostObjectPyImp.cpp | 4 +- src/Mod/Fem/App/FemPostPipeline.cpp | 72 +- src/Mod/Fem/App/FemPostPipeline.h | 32 +- src/Mod/Fem/App/FemPostPipelinePyImp.cpp | 39 +- src/Mod/Fem/App/FemSetElementNodesObject.cpp | 6 +- src/Mod/Fem/App/FemSolverObject.cpp | 24 +- src/Mod/Fem/App/FemTools.cpp | 43 +- src/Mod/Fem/App/FemTools.h | 26 +- src/Mod/Fem/App/FemVTKTools.cpp | 422 +- src/Mod/Fem/App/FemVTKTools.h | 19 +- src/Mod/Fem/App/HypothesisPy.cpp | 279 +- src/Mod/Fem/App/HypothesisPy.h | 18 +- src/Mod/Fem/App/PreCompiled.h | 12 +- src/Mod/Fem/App/PropertyPostDataObject.cpp | 31 +- .../vtkCleanUnstructuredGrid.cxx | 202 +- .../VTKExtensions/vtkCleanUnstructuredGrid.h | 8 +- .../vtkFemFrameSourceAlgorithm.cpp | 43 +- .../vtkFemFrameSourceAlgorithm.h | 16 +- src/Mod/Fem/App/VTKExtensions/vtkSMPTools.h | 60 +- src/Mod/Fem/FemGlobal.h | 30 +- src/Mod/Fem/Gui/ActiveAnalysisObserver.cpp | 3 +- src/Mod/Fem/Gui/AppFemGui.cpp | 10 +- src/Mod/Fem/Gui/AppFemGuiPy.cpp | 57 +- src/Mod/Fem/Gui/Command.cpp | 1176 +++--- src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp | 16 +- src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp | 20 +- .../Fem/Gui/DlgSettingsFemExportAbaqusImp.cpp | 6 +- src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.cpp | 3 +- src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp | 35 +- src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.cpp | 9 +- src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp | 10 +- src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.cpp | 16 +- src/Mod/Fem/Gui/FemGuiTools.cpp | 33 +- src/Mod/Fem/Gui/FemGuiTools.h | 29 +- src/Mod/Fem/Gui/FemSelectionGate.cpp | 4 +- src/Mod/Fem/Gui/FemSettings.cpp | 5 +- src/Mod/Fem/Gui/PreCompiled.h | 2 +- src/Mod/Fem/Gui/PropertyFemMeshItem.cpp | 29 +- src/Mod/Fem/Gui/PropertyFemMeshItem.h | 8 +- src/Mod/Fem/Gui/TaskCreateElementSet.cpp | 471 ++- src/Mod/Fem/Gui/TaskCreateElementSet.h | 3 +- src/Mod/Fem/Gui/TaskCreateNodeSet.cpp | 45 +- src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp | 3 +- src/Mod/Fem/Gui/TaskFemConstraint.cpp | 50 +- src/Mod/Fem/Gui/TaskFemConstraint.h | 8 +- src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp | 117 +- src/Mod/Fem/Gui/TaskFemConstraintBearing.h | 8 +- src/Mod/Fem/Gui/TaskFemConstraintContact.cpp | 293 +- src/Mod/Fem/Gui/TaskFemConstraintContact.h | 6 +- .../Fem/Gui/TaskFemConstraintDisplacement.cpp | 310 +- .../Fem/Gui/TaskFemConstraintDisplacement.h | 9 +- src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp | 70 +- src/Mod/Fem/Gui/TaskFemConstraintFixed.h | 6 +- .../Gui/TaskFemConstraintFluidBoundary.cpp | 480 ++- .../Fem/Gui/TaskFemConstraintFluidBoundary.h | 9 +- src/Mod/Fem/Gui/TaskFemConstraintForce.cpp | 121 +- src/Mod/Fem/Gui/TaskFemConstraintForce.h | 11 +- src/Mod/Fem/Gui/TaskFemConstraintGear.cpp | 132 +- src/Mod/Fem/Gui/TaskFemConstraintGear.h | 8 +- src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp | 207 +- src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h | 6 +- .../TaskFemConstraintInitialTemperature.cpp | 24 +- .../Gui/TaskFemConstraintInitialTemperature.h | 6 +- .../Fem/Gui/TaskFemConstraintOnBoundary.cpp | 18 +- src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h | 8 +- .../Gui/TaskFemConstraintPlaneRotation.cpp | 133 +- .../Fem/Gui/TaskFemConstraintPlaneRotation.h | 9 +- src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp | 114 +- src/Mod/Fem/Gui/TaskFemConstraintPressure.h | 6 +- src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp | 89 +- src/Mod/Fem/Gui/TaskFemConstraintPulley.h | 6 +- .../Fem/Gui/TaskFemConstraintRigidBody.cpp | 357 +- src/Mod/Fem/Gui/TaskFemConstraintRigidBody.h | 6 +- src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp | 110 +- src/Mod/Fem/Gui/TaskFemConstraintSpring.h | 6 +- .../Fem/Gui/TaskFemConstraintTemperature.cpp | 170 +- .../Fem/Gui/TaskFemConstraintTemperature.h | 6 +- .../Fem/Gui/TaskFemConstraintTransform.cpp | 279 +- src/Mod/Fem/Gui/TaskFemConstraintTransform.h | 6 +- src/Mod/Fem/Gui/TaskObjectName.cpp | 10 +- src/Mod/Fem/Gui/TaskPostBoxes.cpp | 774 ++-- src/Mod/Fem/Gui/TaskPostBoxes.h | 21 +- src/Mod/Fem/Gui/TaskTetParameter.cpp | 95 +- src/Mod/Fem/Gui/ViewProviderAnalysis.cpp | 50 +- src/Mod/Fem/Gui/ViewProviderAnalysis.h | 8 +- src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp | 40 +- src/Mod/Fem/Gui/ViewProviderFemConstraint.h | 15 +- .../Gui/ViewProviderFemConstraintBearing.cpp | 18 +- .../ViewProviderFemConstraintDisplacement.cpp | 3 +- .../Fem/Gui/ViewProviderFemConstraintFixed.h | 3 +- ...ViewProviderFemConstraintFluidBoundary.cpp | 18 +- .../Gui/ViewProviderFemConstraintForce.cpp | 28 +- .../Fem/Gui/ViewProviderFemConstraintForce.h | 11 +- .../Fem/Gui/ViewProviderFemConstraintGear.cpp | 31 +- .../Gui/ViewProviderFemConstraintHeatflux.cpp | 3 +- ...roviderFemConstraintInitialTemperature.cpp | 6 +- .../ViewProviderFemConstraintOnBoundary.cpp | 21 +- .../Gui/ViewProviderFemConstraintPressure.cpp | 31 +- .../Gui/ViewProviderFemConstraintPressure.h | 8 +- .../Gui/ViewProviderFemConstraintPulley.cpp | 136 +- .../Gui/ViewProviderFemConstraintPyImp.cpp | 8 +- .../ViewProviderFemConstraintRigidBody.cpp | 3 +- .../Gui/ViewProviderFemConstraintSpring.cpp | 3 +- .../Fem/Gui/ViewProviderFemConstraintSpring.h | 3 +- .../ViewProviderFemConstraintTemperature.cpp | 3 +- .../ViewProviderFemConstraintTransform.cpp | 32 +- .../Gui/ViewProviderFemConstraintTransform.h | 8 +- src/Mod/Fem/Gui/ViewProviderFemMesh.cpp | 1281 +++--- src/Mod/Fem/Gui/ViewProviderFemMesh.h | 45 +- src/Mod/Fem/Gui/ViewProviderFemMeshShape.cpp | 3 +- src/Mod/Fem/Gui/ViewProviderFemMeshShape.h | 4 +- .../Gui/ViewProviderFemMeshShapeNetgen.cpp | 11 +- .../Gui/ViewProviderFemPostBranchFilter.cpp | 9 +- .../Fem/Gui/ViewProviderFemPostBranchFilter.h | 3 +- src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp | 15 +- src/Mod/Fem/Gui/ViewProviderFemPostFilter.h | 4 +- .../Fem/Gui/ViewProviderFemPostFunction.cpp | 376 +- src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp | 80 +- src/Mod/Fem/Gui/ViewProviderFemPostObject.h | 8 +- .../Fem/Gui/ViewProviderFemPostPipeline.cpp | 23 +- src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h | 3 +- .../Fem/Gui/ViewProviderSetElementNodes.cpp | 5 +- src/Mod/Fem/Gui/Workbench.cpp | 16 +- ...lectrostatics_capacitance_two_balls_ccx.py | 422 +- src/Mod/Import/App/AppImportPy.cpp | 225 +- src/Mod/Import/App/ExportOCAF.cpp | 80 +- src/Mod/Import/App/ExportOCAF.h | 72 +- src/Mod/Import/App/ExportOCAF2.cpp | 66 +- src/Mod/Import/App/ExportOCAF2.h | 31 +- src/Mod/Import/App/ImportOCAF.cpp | 70 +- src/Mod/Import/App/ImportOCAF.h | 36 +- src/Mod/Import/App/ImportOCAF2.cpp | 98 +- src/Mod/Import/App/ImportOCAF2.h | 90 +- src/Mod/Import/App/ImportOCAFAssembly.cpp | 74 +- src/Mod/Import/App/ImportOCAFAssembly.h | 24 +- src/Mod/Import/App/ReaderGltf.cpp | 6 +- src/Mod/Import/App/ReaderGltf.h | 3 +- src/Mod/Import/App/SketchExportHelper.cpp | 11 +- src/Mod/Import/App/Tools.cpp | 30 +- src/Mod/Import/App/Tools.h | 20 +- src/Mod/Import/App/WriterStep.cpp | 10 +- src/Mod/Import/App/dxf/ImpExpDxf.cpp | 410 +- src/Mod/Import/App/dxf/ImpExpDxf.h | 193 +- src/Mod/Import/App/dxf/dxf.cpp | 464 ++- src/Mod/Import/App/dxf/dxf.h | 287 +- src/Mod/Import/Gui/AppImportGuiPy.cpp | 174 +- src/Mod/Import/Gui/Command.cpp | 30 +- src/Mod/Import/Gui/ImportOCAFGui.cpp | 19 +- src/Mod/Import/Gui/ImportOCAFGui.h | 6 +- src/Mod/Import/Gui/OCAFBrowser.cpp | 4 +- src/Mod/Import/Gui/PreCompiled.h | 2 +- src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp | 5 +- src/Mod/Import/ImportGlobal.h | 30 +- src/Mod/Inspection/App/InspectionFeature.cpp | 72 +- src/Mod/Inspection/Gui/Command.cpp | 9 +- .../Inspection/Gui/ViewProviderInspection.cpp | 129 +- src/Mod/Inspection/Gui/VisualInspection.cpp | 73 +- src/Mod/Inspection/InspectionGlobal.h | 30 +- src/Mod/JtReader/App/AppJtReaderPy.cpp | 36 +- src/Mod/JtReader/App/JrJt/GUID.h | 24 +- src/Mod/JtReader/App/JrJt/JtReader.cpp | 24 +- src/Mod/JtReader/App/JtReader.cpp | 48 +- src/Mod/JtReader/App/TKJtReader.cpp | 10 +- src/Mod/JtReader/App/TKJtReader.h | 24 +- src/Mod/JtReader/App/TestJtReader.cpp | 3 +- src/Mod/Measure/App/AppMeasure.cpp | 120 +- src/Mod/Measure/App/AppMeasurePy.cpp | 3 +- src/Mod/Measure/App/MeasureAngle.cpp | 30 +- src/Mod/Measure/App/MeasureArea.cpp | 18 +- src/Mod/Measure/App/MeasureBase.cpp | 6 +- src/Mod/Measure/App/MeasureBase.h | 9 +- src/Mod/Measure/App/MeasureDistance.cpp | 175 +- src/Mod/Measure/App/MeasureDistance.h | 11 +- src/Mod/Measure/App/MeasureLength.cpp | 18 +- src/Mod/Measure/App/MeasurePosition.cpp | 24 +- src/Mod/Measure/App/MeasurePosition.h | 3 +- src/Mod/Measure/App/MeasureRadius.cpp | 18 +- src/Mod/Measure/App/Measurement.cpp | 63 +- src/Mod/Measure/App/Measurement.h | 11 +- src/Mod/Measure/App/Preferences.cpp | 9 +- src/Mod/Measure/App/ShapeFinder.cpp | 78 +- src/Mod/Measure/App/ShapeFinder.h | 85 +- src/Mod/Measure/Gui/AppMeasureGui.cpp | 3 +- src/Mod/Measure/Gui/PreCompiled.h | 28 +- src/Mod/Measure/Gui/QuickMeasure.cpp | 64 +- src/Mod/Measure/Gui/TaskMeasure.cpp | 50 +- .../Measure/Gui/ViewProviderMeasureAngle.cpp | 74 +- .../Measure/Gui/ViewProviderMeasureBase.cpp | 83 +- src/Mod/Measure/Gui/ViewProviderMeasureBase.h | 6 +- .../Gui/ViewProviderMeasureDistance.cpp | 90 +- .../Measure/Gui/ViewProviderMeasureDistance.h | 6 +- src/Mod/Measure/MeasureGlobal.h | 30 +- src/Mod/Mesh/App/AppMesh.cpp | 3 +- src/Mod/Mesh/App/AppMeshPy.cpp | 197 +- src/Mod/Mesh/App/Core/Algorithm.cpp | 424 +- src/Mod/Mesh/App/Core/Algorithm.h | 321 +- src/Mod/Mesh/App/Core/Approximation.cpp | 156 +- src/Mod/Mesh/App/Core/Approximation.h | 117 +- src/Mod/Mesh/App/Core/Builder.cpp | 31 +- src/Mod/Mesh/App/Core/Builder.h | 14 +- src/Mod/Mesh/App/Core/Curvature.cpp | 44 +- src/Mod/Mesh/App/Core/Curvature.h | 5 +- src/Mod/Mesh/App/Core/CylinderFit.cpp | 62 +- src/Mod/Mesh/App/Core/CylinderFit.h | 51 +- src/Mod/Mesh/App/Core/Definitions.h | 2 +- src/Mod/Mesh/App/Core/Degeneration.cpp | 29 +- src/Mod/Mesh/App/Core/Degeneration.h | 14 +- src/Mod/Mesh/App/Core/Elements.cpp | 98 +- src/Mod/Mesh/App/Core/Elements.h | 112 +- src/Mod/Mesh/App/Core/Evaluation.cpp | 51 +- src/Mod/Mesh/App/Core/Evaluation.h | 15 +- src/Mod/Mesh/App/Core/Functional.h | 22 +- src/Mod/Mesh/App/Core/Grid.cpp | 437 +- src/Mod/Mesh/App/Core/Grid.h | 222 +- src/Mod/Mesh/App/Core/Helpers.h | 14 +- src/Mod/Mesh/App/Core/IO/Reader3MF.cpp | 44 +- src/Mod/Mesh/App/Core/IO/ReaderPLY.cpp | 60 +- src/Mod/Mesh/App/Core/IO/WriterInventor.cpp | 12 +- src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp | 30 +- src/Mod/Mesh/App/Core/Info.cpp | 8 +- src/Mod/Mesh/App/Core/Iterator.h | 16 +- src/Mod/Mesh/App/Core/KDTree.cpp | 25 +- src/Mod/Mesh/App/Core/KDTree.h | 3 +- src/Mod/Mesh/App/Core/MeshIO.cpp | 285 +- src/Mod/Mesh/App/Core/MeshKernel.cpp | 88 +- src/Mod/Mesh/App/Core/MeshKernel.h | 126 +- src/Mod/Mesh/App/Core/Projection.cpp | 44 +- src/Mod/Mesh/App/Core/Projection.h | 44 +- src/Mod/Mesh/App/Core/Segmentation.cpp | 35 +- src/Mod/Mesh/App/Core/Segmentation.h | 70 +- src/Mod/Mesh/App/Core/SetOperations.cpp | 115 +- src/Mod/Mesh/App/Core/SetOperations.h | 48 +- src/Mod/Mesh/App/Core/Smoothing.cpp | 46 +- src/Mod/Mesh/App/Core/Smoothing.h | 18 +- src/Mod/Mesh/App/Core/SphereFit.cpp | 64 +- src/Mod/Mesh/App/Core/SphereFit.h | 40 +- src/Mod/Mesh/App/Core/Tools.cpp | 39 +- src/Mod/Mesh/App/Core/Tools.h | 42 +- src/Mod/Mesh/App/Core/TopoAlgorithm.cpp | 255 +- src/Mod/Mesh/App/Core/TopoAlgorithm.h | 45 +- src/Mod/Mesh/App/Core/Triangulation.cpp | 153 +- src/Mod/Mesh/App/Core/Triangulation.h | 44 +- src/Mod/Mesh/App/Core/Trim.cpp | 81 +- src/Mod/Mesh/App/Core/Trim.h | 33 +- src/Mod/Mesh/App/Core/TrimByPlane.cpp | 49 +- src/Mod/Mesh/App/Core/TrimByPlane.h | 46 +- src/Mod/Mesh/App/Core/Visitor.cpp | 60 +- src/Mod/Mesh/App/Core/Visitor.h | 83 +- src/Mod/Mesh/App/EdgePyImp.cpp | 17 +- src/Mod/Mesh/App/Exporter.cpp | 13 +- src/Mod/Mesh/App/Exporter.h | 8 +- src/Mod/Mesh/App/Facet.cpp | 8 +- src/Mod/Mesh/App/Facet.h | 8 +- src/Mod/Mesh/App/FeatureMeshExport.h | 2 +- src/Mod/Mesh/App/FeatureMeshSetOperations.cpp | 18 +- src/Mod/Mesh/App/FeatureMeshSolid.cpp | 87 +- src/Mod/Mesh/App/FeatureMeshSolid.h | 48 +- src/Mod/Mesh/App/Importer.cpp | 15 +- src/Mod/Mesh/App/Mesh.cpp | 309 +- src/Mod/Mesh/App/Mesh.h | 95 +- src/Mod/Mesh/App/MeshFeaturePyImp.cpp | 6 +- src/Mod/Mesh/App/MeshPoint.h | 10 +- src/Mod/Mesh/App/MeshPointPyImp.cpp | 8 +- src/Mod/Mesh/App/MeshProperties.cpp | 11 +- src/Mod/Mesh/App/MeshPyImp.cpp | 237 +- src/Mod/Mesh/App/MeshTexture.cpp | 33 +- src/Mod/Mesh/App/MeshTexture.h | 30 +- src/Mod/Mesh/App/Segment.cpp | 12 +- src/Mod/Mesh/Gui/AppMeshGui.cpp | 6 +- src/Mod/Mesh/Gui/Command.cpp | 476 ++- src/Mod/Mesh/Gui/DlgDecimating.cpp | 53 +- src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp | 93 +- .../Mesh/Gui/DlgSettingsImportExportImp.cpp | 18 +- src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h | 2 +- src/Mod/Mesh/Gui/DlgSettingsMeshView.h | 2 +- src/Mod/Mesh/Gui/DlgSmoothing.cpp | 3 +- src/Mod/Mesh/Gui/DlgSmoothing.h | 2 +- src/Mod/Mesh/Gui/MeshEditor.cpp | 48 +- src/Mod/Mesh/Gui/MeshEditor.h | 18 +- src/Mod/Mesh/Gui/MeshSelection.cpp | 16 +- src/Mod/Mesh/Gui/MeshSelection.h | 2 +- src/Mod/Mesh/Gui/PreCompiled.h | 2 +- src/Mod/Mesh/Gui/PropertyEditorMesh.cpp | 17 +- src/Mod/Mesh/Gui/PropertyEditorMesh.h | 2 +- src/Mod/Mesh/Gui/RemeshGmsh.cpp | 5 +- src/Mod/Mesh/Gui/RemeshGmsh.h | 8 +- src/Mod/Mesh/Gui/RemoveComponents.h | 3 +- src/Mod/Mesh/Gui/Segmentation.cpp | 48 +- src/Mod/Mesh/Gui/Segmentation.h | 10 +- src/Mod/Mesh/Gui/SegmentationBestFit.cpp | 72 +- src/Mod/Mesh/Gui/SegmentationBestFit.h | 20 +- src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp | 203 +- src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h | 34 +- src/Mod/Mesh/Gui/SoFCMeshObject.cpp | 107 +- src/Mod/Mesh/Gui/SoFCMeshObject.h | 44 +- src/Mod/Mesh/Gui/SoPolygon.cpp | 6 +- src/Mod/Mesh/Gui/SoPolygon.h | 2 +- src/Mod/Mesh/Gui/ThumbnailExtension.cpp | 4 +- src/Mod/Mesh/Gui/ViewProvider.cpp | 354 +- src/Mod/Mesh/Gui/ViewProvider.h | 62 +- src/Mod/Mesh/Gui/ViewProviderCurvature.cpp | 37 +- src/Mod/Mesh/Gui/ViewProviderDefects.cpp | 23 +- src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.cpp | 5 +- .../Gui/ViewProviderTransformDemolding.cpp | 21 +- src/Mod/Mesh/Gui/Workbench.h | 2 +- src/Mod/Mesh/MeshGlobal.h | 30 +- src/Mod/MeshPart/App/CurveProjector.cpp | 249 +- src/Mod/MeshPart/App/CurveProjector.h | 101 +- src/Mod/MeshPart/App/MeshAlgos.cpp | 56 +- src/Mod/MeshPart/App/MeshAlgos.h | 44 +- src/Mod/MeshPart/App/MeshFlattening.cpp | 16 +- src/Mod/MeshPart/App/Mesher.cpp | 200 +- src/Mod/MeshPart/App/Mesher.h | 2 +- src/Mod/MeshPart/Gui/Command.cpp | 42 +- src/Mod/MeshPart/Gui/CrossSections.cpp | 37 +- src/Mod/MeshPart/Gui/CrossSections.h | 8 +- src/Mod/MeshPart/Gui/CurveOnMesh.cpp | 34 +- src/Mod/MeshPart/Gui/TaskCurveOnMesh.cpp | 10 +- src/Mod/MeshPart/Gui/Tessellation.cpp | 140 +- src/Mod/MeshPart/MeshPartGlobal.h | 30 +- src/Mod/Part/App/AppPart.cpp | 11 +- src/Mod/Part/App/AppPartPy.cpp | 1893 +++++---- src/Mod/Part/App/Arc.pyi | 2 - src/Mod/Part/App/ArcOfCircle.pyi | 1 - src/Mod/Part/App/ArcOfCirclePyImp.cpp | 62 +- src/Mod/Part/App/ArcOfConic.pyi | 1 - src/Mod/Part/App/ArcOfConicPyImp.cpp | 54 +- src/Mod/Part/App/ArcOfEllipse.pyi | 1 - src/Mod/Part/App/ArcOfEllipsePyImp.cpp | 47 +- src/Mod/Part/App/ArcOfHyperbola.pyi | 1 - src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp | 47 +- src/Mod/Part/App/ArcOfParabola.pyi | 1 - src/Mod/Part/App/ArcOfParabolaPyImp.cpp | 45 +- src/Mod/Part/App/ArcPyImp.cpp | 63 +- src/Mod/Part/App/AttachEngine.pyi | 4 +- src/Mod/Part/App/AttachEnginePyImp.cpp | 377 +- src/Mod/Part/App/AttachExtension.cpp | 353 +- src/Mod/Part/App/AttachExtension.h | 18 +- src/Mod/Part/App/AttachExtension.pyi | 1 - src/Mod/Part/App/AttachExtensionPyImp.cpp | 47 +- src/Mod/Part/App/Attacher.cpp | 1544 ++++---- src/Mod/Part/App/Attacher.h | 291 +- src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp | 190 +- src/Mod/Part/App/BRepMesh.cpp | 52 +- src/Mod/Part/App/BRepMesh.h | 13 +- .../Part/App/BRepOffsetAPI_MakeFilling.pyi | 60 +- .../App/BRepOffsetAPI_MakeFillingPyImp.cpp | 261 +- .../Part/App/BRepOffsetAPI_MakeOffsetFix.cpp | 66 +- .../Part/App/BRepOffsetAPI_MakeOffsetFix.h | 32 +- .../Part/App/BRepOffsetAPI_MakePipeShell.pyi | 19 +- .../App/BRepOffsetAPI_MakePipeShellPyImp.cpp | 255 +- src/Mod/Part/App/BSplineCurve.pyi | 15 +- src/Mod/Part/App/BSplineCurveBiArcs.cpp | 157 +- src/Mod/Part/App/BSplineCurveBiArcs.h | 39 +- src/Mod/Part/App/BSplineCurvePyImp.cpp | 892 +++-- src/Mod/Part/App/BSplineSurface.pyi | 9 +- src/Mod/Part/App/BSplineSurfacePyImp.cpp | 1188 +++--- src/Mod/Part/App/BezierCurve.pyi | 5 +- src/Mod/Part/App/BezierCurvePyImp.cpp | 266 +- src/Mod/Part/App/BezierSurface.pyi | 1 - src/Mod/Part/App/BezierSurfacePyImp.cpp | 424 +- src/Mod/Part/App/BodyBase.cpp | 57 +- src/Mod/Part/App/BodyBase.h | 32 +- src/Mod/Part/App/BodyBase.pyi | 1 - src/Mod/Part/App/BodyBasePyImp.cpp | 4 +- src/Mod/Part/App/BoundedCurve.pyi | 1 - src/Mod/Part/App/BoundedCurvePyImp.cpp | 12 +- .../App/ChFi2d/ChFi2d_AnaFilletAlgoPyImp.cpp | 95 +- .../App/ChFi2d/ChFi2d_ChamferAPIPyImp.cpp | 56 +- src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPI.pyi | 5 +- .../Part/App/ChFi2d/ChFi2d_FilletAPIPyImp.cpp | 107 +- src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgo.pyi | 1 - .../App/ChFi2d/ChFi2d_FilletAlgoPyImp.cpp | 109 +- src/Mod/Part/App/Circle.pyi | 5 - src/Mod/Part/App/CirclePyImp.cpp | 89 +- src/Mod/Part/App/Cone.pyi | 1 - src/Mod/Part/App/ConePyImp.cpp | 151 +- src/Mod/Part/App/Conic.pyi | 1 - src/Mod/Part/App/ConicPyImp.cpp | 27 +- src/Mod/Part/App/CrossSection.cpp | 165 +- src/Mod/Part/App/CrossSection.h | 11 +- src/Mod/Part/App/CustomFeature.cpp | 12 +- src/Mod/Part/App/CustomFeature.h | 11 +- src/Mod/Part/App/Cylinder.pyi | 5 - src/Mod/Part/App/CylinderPyImp.cpp | 146 +- src/Mod/Part/App/DatumFeature.cpp | 31 +- src/Mod/Part/App/DatumFeature.h | 20 +- src/Mod/Part/App/Datums.h | 24 +- src/Mod/Part/App/Ellipse.pyi | 1 - src/Mod/Part/App/EllipsePyImp.cpp | 75 +- src/Mod/Part/App/ExtrusionHelper.cpp | 307 +- src/Mod/Part/App/ExtrusionHelper.h | 64 +- .../App/FCBRepAlgoAPI_BooleanOperation.cpp | 70 +- .../Part/App/FCBRepAlgoAPI_BooleanOperation.h | 38 +- src/Mod/Part/App/FCBRepAlgoAPI_Common.cpp | 13 +- src/Mod/Part/App/FCBRepAlgoAPI_Common.h | 15 +- src/Mod/Part/App/FCBRepAlgoAPI_Cut.cpp | 13 +- src/Mod/Part/App/FCBRepAlgoAPI_Cut.h | 15 +- src/Mod/Part/App/FCBRepAlgoAPI_Fuse.cpp | 13 +- src/Mod/Part/App/FCBRepAlgoAPI_Fuse.h | 15 +- src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp | 38 +- src/Mod/Part/App/FCBRepAlgoAPI_Section.h | 23 +- src/Mod/Part/App/FT2FC.cpp | 475 +-- src/Mod/Part/App/FT2FC.h | 28 +- src/Mod/Part/App/FaceMaker.cpp | 154 +- src/Mod/Part/App/FaceMaker.h | 51 +- src/Mod/Part/App/FaceMakerBullseye.cpp | 55 +- src/Mod/Part/App/FaceMakerBullseye.h | 21 +- src/Mod/Part/App/FaceMakerCheese.cpp | 102 +- src/Mod/Part/App/FaceMakerCheese.h | 12 +- src/Mod/Part/App/FeatureChamfer.cpp | 58 +- src/Mod/Part/App/FeatureChamfer.h | 12 +- src/Mod/Part/App/FeatureCompound.cpp | 25 +- src/Mod/Part/App/FeatureCompound.h | 16 +- src/Mod/Part/App/FeatureExtrusion.cpp | 287 +- src/Mod/Part/App/FeatureExtrusion.h | 40 +- src/Mod/Part/App/FeatureFace.cpp | 45 +- src/Mod/Part/App/FeatureFace.h | 13 +- src/Mod/Part/App/FeatureFillet.cpp | 57 +- src/Mod/Part/App/FeatureFillet.h | 11 +- src/Mod/Part/App/FeatureGeometrySet.cpp | 8 +- src/Mod/Part/App/FeatureGeometrySet.h | 14 +- src/Mod/Part/App/FeatureMirroring.cpp | 219 +- src/Mod/Part/App/FeatureMirroring.h | 20 +- src/Mod/Part/App/FeatureOffset.cpp | 91 +- src/Mod/Part/App/FeatureOffset.h | 21 +- src/Mod/Part/App/FeaturePartBoolean.cpp | 51 +- src/Mod/Part/App/FeaturePartBoolean.h | 16 +- src/Mod/Part/App/FeaturePartBox.cpp | 93 +- src/Mod/Part/App/FeaturePartBox.h | 18 +- src/Mod/Part/App/FeaturePartCircle.cpp | 44 +- src/Mod/Part/App/FeaturePartCircle.h | 19 +- src/Mod/Part/App/FeaturePartCommon.cpp | 44 +- src/Mod/Part/App/FeaturePartCommon.h | 16 +- src/Mod/Part/App/FeaturePartCurveNet.cpp | 9 +- src/Mod/Part/App/FeaturePartCurveNet.h | 11 +- src/Mod/Part/App/FeaturePartCut.cpp | 4 +- src/Mod/Part/App/FeaturePartCut.h | 8 +- src/Mod/Part/App/FeaturePartFuse.cpp | 72 +- src/Mod/Part/App/FeaturePartFuse.h | 16 +- src/Mod/Part/App/FeaturePartImportBrep.cpp | 12 +- src/Mod/Part/App/FeaturePartImportBrep.h | 11 +- src/Mod/Part/App/FeaturePartImportIges.cpp | 13 +- src/Mod/Part/App/FeaturePartImportIges.h | 11 +- src/Mod/Part/App/FeaturePartImportStep.cpp | 13 +- src/Mod/Part/App/FeaturePartImportStep.h | 11 +- src/Mod/Part/App/FeaturePartPolygon.cpp | 23 +- src/Mod/Part/App/FeaturePartPolygon.h | 10 +- src/Mod/Part/App/FeaturePartSection.cpp | 19 +- src/Mod/Part/App/FeaturePartSection.h | 11 +- src/Mod/Part/App/FeaturePartSpline.cpp | 2 - src/Mod/Part/App/FeaturePartSpline.h | 10 +- src/Mod/Part/App/FeatureProjectOnSurface.cpp | 110 +- src/Mod/Part/App/FeatureProjectOnSurface.h | 54 +- src/Mod/Part/App/FeatureRevolution.cpp | 169 +- src/Mod/Part/App/FeatureRevolution.h | 23 +- src/Mod/Part/App/FeatureScale.cpp | 79 +- src/Mod/Part/App/FeatureScale.h | 25 +- src/Mod/Part/App/FuzzyHelper.cpp | 14 +- src/Mod/Part/App/FuzzyHelper.h | 12 +- src/Mod/Part/App/Geom2d/ArcOfCircle2d.pyi | 2 +- .../Part/App/Geom2d/ArcOfCircle2dPyImp.cpp | 50 +- src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp | 42 +- src/Mod/Part/App/Geom2d/ArcOfEllipse2d.pyi | 3 +- .../Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp | 35 +- src/Mod/Part/App/Geom2d/ArcOfHyperbola2d.pyi | 3 +- .../Part/App/Geom2d/ArcOfHyperbola2dPyImp.cpp | 36 +- src/Mod/Part/App/Geom2d/ArcOfParabola2d.pyi | 3 +- .../Part/App/Geom2d/ArcOfParabola2dPyImp.cpp | 34 +- src/Mod/Part/App/Geom2d/BSplineCurve2d.pyi | 42 +- .../Part/App/Geom2d/BSplineCurve2dPyImp.cpp | 809 ++-- .../Part/App/Geom2d/BezierCurve2dPyImp.cpp | 234 +- src/Mod/Part/App/Geom2d/Circle2d.pyi | 11 +- src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp | 108 +- src/Mod/Part/App/Geom2d/Conic2d.pyi | 2 +- src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp | 17 +- src/Mod/Part/App/Geom2d/Curve2d.pyi | 62 +- src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp | 529 +-- src/Mod/Part/App/Geom2d/Ellipse2d.pyi | 7 +- src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp | 89 +- src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp | 62 +- src/Mod/Part/App/Geom2d/Hyperbola2d.pyi | 2 +- src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp | 117 +- src/Mod/Part/App/Geom2d/Line2dPyImp.cpp | 72 +- src/Mod/Part/App/Geom2d/Line2dSegment.pyi | 19 +- .../Part/App/Geom2d/Line2dSegmentPyImp.cpp | 138 +- src/Mod/Part/App/Geom2d/OffsetCurve2d.pyi | 2 +- .../Part/App/Geom2d/OffsetCurve2dPyImp.cpp | 42 +- src/Mod/Part/App/Geom2d/Parabola2d.pyi | 1 - src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp | 9 +- .../App/GeomPlate/BuildPlateSurfacePyImp.cpp | 175 +- .../App/GeomPlate/CurveConstraintPyImp.cpp | 119 +- .../App/GeomPlate/PointConstraintPyImp.cpp | 79 +- src/Mod/Part/App/Geometry.cpp | 3498 +++++++++-------- src/Mod/Part/App/Geometry.h | 877 +++-- src/Mod/Part/App/Geometry.pyi | 1 - src/Mod/Part/App/Geometry2d.cpp | 938 +++-- src/Mod/Part/App/Geometry2d.h | 348 +- src/Mod/Part/App/GeometryBoolExtension.pyi | 1 - .../Part/App/GeometryBoolExtensionPyImp.cpp | 24 +- src/Mod/Part/App/GeometryCurve.pyi | 35 +- src/Mod/Part/App/GeometryCurvePyImp.cpp | 708 ++-- src/Mod/Part/App/GeometryDefaultExtension.cpp | 81 +- src/Mod/Part/App/GeometryDefaultExtension.h | 176 +- src/Mod/Part/App/GeometryDoubleExtension.pyi | 1 - .../Part/App/GeometryDoubleExtensionPyImp.cpp | 26 +- src/Mod/Part/App/GeometryExtension.cpp | 33 +- src/Mod/Part/App/GeometryExtension.h | 44 +- src/Mod/Part/App/GeometryExtension.pyi | 1 - src/Mod/Part/App/GeometryExtensionPyImp.cpp | 22 +- src/Mod/Part/App/GeometryIntExtension.pyi | 1 - .../Part/App/GeometryIntExtensionPyImp.cpp | 25 +- .../Part/App/GeometryMigrationExtension.cpp | 19 +- src/Mod/Part/App/GeometryMigrationExtension.h | 94 +- src/Mod/Part/App/GeometryPyImp.cpp | 186 +- src/Mod/Part/App/GeometryStringExtension.pyi | 1 - .../Part/App/GeometryStringExtensionPyImp.cpp | 26 +- src/Mod/Part/App/GeometrySurface.pyi | 16 +- src/Mod/Part/App/GeometrySurfacePyImp.cpp | 477 ++- src/Mod/Part/App/GizmoHelper.cpp | 39 +- src/Mod/Part/App/GizmoHelper.h | 15 +- src/Mod/Part/App/HLRBRep/HLRBRep_Algo.pyi | 10 +- .../Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp | 157 +- src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgo.pyi | 29 +- .../App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp | 126 +- src/Mod/Part/App/HLRBRep/HLRToShape.pyi | 6 +- src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp | 99 +- src/Mod/Part/App/HLRBRep/PolyHLRToShape.pyi | 6 +- .../Part/App/HLRBRep/PolyHLRToShapePyImp.cpp | 62 +- src/Mod/Part/App/Hyperbola.pyi | 8 +- src/Mod/Part/App/HyperbolaPyImp.cpp | 119 +- .../Part/App/IGES/ImportExportSettings.cpp | 16 +- src/Mod/Part/App/IGES/ImportExportSettings.h | 7 +- src/Mod/Part/App/ImportIges.cpp | 56 +- src/Mod/Part/App/ImportIges.h | 9 +- src/Mod/Part/App/ImportStep.cpp | 85 +- src/Mod/Part/App/ImportStep.h | 11 +- src/Mod/Part/App/Interface.cpp | 26 +- src/Mod/Part/App/Interface.h | 8 +- src/Mod/Part/App/Line.pyi | 3 - src/Mod/Part/App/LinePyImp.cpp | 55 +- src/Mod/Part/App/LineSegment.pyi | 4 - src/Mod/Part/App/LineSegmentPyImp.cpp | 132 +- src/Mod/Part/App/MeasureClient.cpp | 202 +- src/Mod/Part/App/MeasureClient.h | 4 +- src/Mod/Part/App/MeasureInfo.h | 108 +- .../Part/App/OCAF/ImportExportSettings.cpp | 78 +- src/Mod/Part/App/OCAF/ImportExportSettings.h | 20 +- src/Mod/Part/App/OCCError.h | 39 +- src/Mod/Part/App/OCCTProgressIndicator.h | 31 +- src/Mod/Part/App/OffsetCurve.pyi | 1 - src/Mod/Part/App/OffsetCurvePyImp.cpp | 42 +- src/Mod/Part/App/OffsetSurface.pyi | 1 - src/Mod/Part/App/OffsetSurfacePyImp.cpp | 31 +- src/Mod/Part/App/OpenCascadeAll.h | 20 +- src/Mod/Part/App/Parabola.pyi | 1 - src/Mod/Part/App/ParabolaPyImp.cpp | 109 +- src/Mod/Part/App/Part2DObject.cpp | 153 +- src/Mod/Part/App/Part2DObject.h | 66 +- src/Mod/Part/App/Part2DObject.pyi | 2 +- src/Mod/Part/App/Part2DObjectPyImp.cpp | 4 +- src/Mod/Part/App/PartFeature.cpp | 745 ++-- src/Mod/Part/App/PartFeature.h | 192 +- src/Mod/Part/App/PartFeature.pyi | 1 - src/Mod/Part/App/PartFeaturePyImp.cpp | 59 +- src/Mod/Part/App/PartFeatureReference.cpp | 10 +- src/Mod/Part/App/PartFeatureReference.h | 15 +- src/Mod/Part/App/PartFeatures.cpp | 94 +- src/Mod/Part/App/PartFeatures.h | 56 +- src/Mod/Part/App/PartPyCXX.cpp | 30 +- src/Mod/Part/App/PartPyCXX.h | 26 +- src/Mod/Part/App/Plane.pyi | 1 - src/Mod/Part/App/PlanePyImp.cpp | 111 +- src/Mod/Part/App/PlateSurface.pyi | 1 - src/Mod/Part/App/PlateSurfacePyImp.cpp | 162 +- src/Mod/Part/App/Point.pyi | 5 - src/Mod/Part/App/PointPyImp.cpp | 80 +- src/Mod/Part/App/PreCompiled.h | 2 +- src/Mod/Part/App/PrimitiveFeature.cpp | 793 ++-- src/Mod/Part/App/PrimitiveFeature.h | 134 +- src/Mod/Part/App/PrismExtension.cpp | 25 +- src/Mod/Part/App/PrismExtension.h | 9 +- src/Mod/Part/App/PropertyGeometryList.cpp | 100 +- src/Mod/Part/App/PropertyGeometryList.h | 33 +- src/Mod/Part/App/PropertyTopoShape.cpp | 700 ++-- src/Mod/Part/App/PropertyTopoShape.h | 181 +- src/Mod/Part/App/PropertyTopoShapeList.cpp | 21 +- src/Mod/Part/App/PropertyTopoShapeList.h | 35 +- .../Part/App/RectangularTrimmedSurface.pyi | 1 - .../App/RectangularTrimmedSurfacePyImp.cpp | 79 +- .../Part/App/STEP/ImportExportSettings.cpp | 24 +- src/Mod/Part/App/STEP/ImportExportSettings.h | 4 +- src/Mod/Part/App/Services.cpp | 10 +- src/Mod/Part/App/ShapeFix/ShapeFix_Edge.pyi | 6 +- .../App/ShapeFix/ShapeFix_EdgeConnect.pyi | 2 - .../ShapeFix/ShapeFix_EdgeConnectPyImp.cpp | 31 +- .../Part/App/ShapeFix/ShapeFix_EdgePyImp.cpp | 166 +- .../App/ShapeFix/ShapeFix_FaceConnect.pyi | 1 - .../ShapeFix/ShapeFix_FaceConnectPyImp.cpp | 27 +- .../Part/App/ShapeFix/ShapeFix_FacePyImp.cpp | 108 +- .../App/ShapeFix/ShapeFix_FixSmallFace.pyi | 2 +- .../ShapeFix/ShapeFix_FixSmallFacePyImp.cpp | 90 +- .../ShapeFix/ShapeFix_FixSmallSolidPyImp.cpp | 44 +- .../Part/App/ShapeFix/ShapeFix_FreeBounds.pyi | 2 +- .../App/ShapeFix/ShapeFix_FreeBoundsPyImp.cpp | 76 +- src/Mod/Part/App/ShapeFix/ShapeFix_Root.pyi | 6 +- .../Part/App/ShapeFix/ShapeFix_RootPyImp.cpp | 14 +- src/Mod/Part/App/ShapeFix/ShapeFix_Shape.pyi | 1 - .../Part/App/ShapeFix/ShapeFix_ShapePyImp.cpp | 47 +- .../App/ShapeFix/ShapeFix_ShapeTolerance.pyi | 12 +- .../ShapeFix/ShapeFix_ShapeTolerancePyImp.cpp | 21 +- src/Mod/Part/App/ShapeFix/ShapeFix_Shell.pyi | 2 +- .../Part/App/ShapeFix/ShapeFix_ShellPyImp.cpp | 80 +- .../Part/App/ShapeFix/ShapeFix_SolidPyImp.cpp | 53 +- .../ShapeFix_SplitCommonVertexPyImp.cpp | 31 +- .../Part/App/ShapeFix/ShapeFix_SplitTool.pyi | 3 +- .../App/ShapeFix/ShapeFix_SplitToolPyImp.cpp | 101 +- src/Mod/Part/App/ShapeFix/ShapeFix_Wire.pyi | 1 - .../Part/App/ShapeFix/ShapeFix_WirePyImp.cpp | 197 +- .../App/ShapeFix/ShapeFix_WireVertexPyImp.cpp | 29 +- .../Part/App/ShapeFix/ShapeFix_Wireframe.pyi | 3 +- .../App/ShapeFix/ShapeFix_WireframePyImp.cpp | 36 +- src/Mod/Part/App/ShapeMapHasher.h | 9 +- .../App/ShapeUpgrade/UnifySameDomainPyImp.cpp | 126 +- src/Mod/Part/App/Sphere.pyi | 1 - src/Mod/Part/App/SpherePyImp.cpp | 71 +- src/Mod/Part/App/SurfaceOfExtrusion.pyi | 1 - src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp | 63 +- src/Mod/Part/App/SurfaceOfRevolution.pyi | 1 - src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp | 99 +- src/Mod/Part/App/Tools.cpp | 479 ++- src/Mod/Part/App/Tools.h | 158 +- src/Mod/Part/App/TopoShape.cpp | 2775 +++++++------ src/Mod/Part/App/TopoShape.h | 1350 ++++--- src/Mod/Part/App/TopoShape.pyi | 99 +- src/Mod/Part/App/TopoShapeCache.cpp | 16 +- src/Mod/Part/App/TopoShapeCache.h | 10 +- src/Mod/Part/App/TopoShapeCompSolid.pyi | 1 - src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp | 12 +- src/Mod/Part/App/TopoShapeCompound.pyi | 5 +- src/Mod/Part/App/TopoShapeCompoundPyImp.cpp | 61 +- src/Mod/Part/App/TopoShapeEdge.pyi | 11 +- src/Mod/Part/App/TopoShapeEdgePyImp.cpp | 569 +-- src/Mod/Part/App/TopoShapeExpansion.cpp | 1335 ++++--- src/Mod/Part/App/TopoShapeFace.pyi | 13 +- src/Mod/Part/App/TopoShapeFacePyImp.cpp | 557 +-- src/Mod/Part/App/TopoShapeMapper.cpp | 20 +- src/Mod/Part/App/TopoShapeMapper.h | 29 +- src/Mod/Part/App/TopoShapeOpCode.h | 98 +- src/Mod/Part/App/TopoShapePyImp.cpp | 1292 +++--- src/Mod/Part/App/TopoShapeShell.pyi | 1 - src/Mod/Part/App/TopoShapeShellPyImp.cpp | 102 +- src/Mod/Part/App/TopoShapeSolid.pyi | 7 +- src/Mod/Part/App/TopoShapeSolidPyImp.cpp | 148 +- src/Mod/Part/App/TopoShapeVertex.pyi | 1 - src/Mod/Part/App/TopoShapeVertexPyImp.cpp | 51 +- src/Mod/Part/App/TopoShapeWire.pyi | 26 +- src/Mod/Part/App/TopoShapeWirePyImp.cpp | 460 ++- src/Mod/Part/App/Toroid.pyi | 1 - src/Mod/Part/App/ToroidPyImp.cpp | 65 +- src/Mod/Part/App/TrimmedCurve.pyi | 1 - src/Mod/Part/App/TrimmedCurvePyImp.cpp | 25 +- src/Mod/Part/App/VectorAdapter.cpp | 38 +- src/Mod/Part/App/VectorAdapter.h | 34 +- src/Mod/Part/App/WireJoiner.cpp | 923 +++-- src/Mod/Part/App/WireJoiner.h | 36 +- src/Mod/Part/App/edgecluster.cpp | 135 +- src/Mod/Part/App/edgecluster.h | 33 +- src/Mod/Part/App/encodeFilename.h | 4 +- src/Mod/Part/App/modelRefine.cpp | 1098 +++--- src/Mod/Part/App/modelRefine.h | 282 +- src/Mod/Part/AttachmentEditor/Commands.py | 61 +- src/Mod/Part/AttachmentEditor/FrozenClass.py | 12 +- .../AttachmentEditor/TaskAttachmentEditor.py | 489 ++- src/Mod/Part/AttachmentEditor/__init__.py | 2 +- src/Mod/Part/BOPTools/BOPFeatures.py | 1 + src/Mod/Part/BOPTools/GeneralFuseResult.py | 131 +- src/Mod/Part/BOPTools/JoinAPI.py | 70 +- src/Mod/Part/BOPTools/JoinFeatures.py | 255 +- src/Mod/Part/BOPTools/ShapeMerge.py | 96 +- src/Mod/Part/BOPTools/SplitAPI.py | 37 +- src/Mod/Part/BOPTools/SplitFeatures.py | 400 +- src/Mod/Part/BOPTools/ToleranceFeatures.py | 129 +- src/Mod/Part/BOPTools/Utils.py | 58 +- src/Mod/Part/BOPTools/__init__.py | 23 +- src/Mod/Part/BasicShapes/CommandShapes.py | 20 +- src/Mod/Part/BasicShapes/ShapeContent.py | 53 +- src/Mod/Part/BasicShapes/Shapes.py | 13 +- src/Mod/Part/BasicShapes/Utils.py | 6 +- .../Part/BasicShapes/ViewProviderShapes.py | 17 +- src/Mod/Part/CompoundTools/CompoundFilter.py | 182 +- src/Mod/Part/CompoundTools/Explode.py | 25 +- .../CompoundTools/_CommandCompoundFilter.py | 71 +- .../CompoundTools/_CommandExplodeCompound.py | 43 +- src/Mod/Part/Gui/AttacherTexts.cpp | 1108 ++++-- src/Mod/Part/Gui/AttacherTexts.h | 22 +- src/Mod/Part/Gui/BoxSelection.cpp | 91 +- src/Mod/Part/Gui/BoxSelection.h | 34 +- src/Mod/Part/Gui/Command.cpp | 1530 ++++--- src/Mod/Part/Gui/CommandFilter.cpp | 152 +- src/Mod/Part/Gui/CommandParametric.cpp | 175 +- src/Mod/Part/Gui/CommandSimple.cpp | 328 +- src/Mod/Part/Gui/CrossSections.cpp | 230 +- src/Mod/Part/Gui/CrossSections.h | 35 +- src/Mod/Part/Gui/DlgBooleanOperation.cpp | 241 +- src/Mod/Part/Gui/DlgBooleanOperation.h | 30 +- src/Mod/Part/Gui/DlgExportStep.cpp | 45 +- src/Mod/Part/Gui/DlgExportStep.h | 17 +- src/Mod/Part/Gui/DlgExtrusion.cpp | 507 ++- src/Mod/Part/Gui/DlgExtrusion.h | 30 +- src/Mod/Part/Gui/DlgFilletEdges.cpp | 659 ++-- src/Mod/Part/Gui/DlgFilletEdges.h | 109 +- src/Mod/Part/Gui/DlgImportStep.cpp | 12 +- src/Mod/Part/Gui/DlgImportStep.h | 13 +- src/Mod/Part/Gui/DlgPartBoxImp.cpp | 3 +- src/Mod/Part/Gui/DlgPartBoxImp.h | 9 +- src/Mod/Part/Gui/DlgPartCylinderImp.cpp | 7 +- src/Mod/Part/Gui/DlgPartCylinderImp.h | 9 +- src/Mod/Part/Gui/DlgPartImportIgesImp.cpp | 15 +- src/Mod/Part/Gui/DlgPartImportIgesImp.h | 19 +- src/Mod/Part/Gui/DlgPartImportStepImp.cpp | 17 +- src/Mod/Part/Gui/DlgPartImportStepImp.h | 19 +- src/Mod/Part/Gui/DlgPrimitives.cpp | 1712 +++++--- src/Mod/Part/Gui/DlgPrimitives.h | 72 +- src/Mod/Part/Gui/DlgProjectionOnSurface.cpp | 203 +- src/Mod/Part/Gui/DlgProjectionOnSurface.h | 39 +- src/Mod/Part/Gui/DlgRevolution.cpp | 346 +- src/Mod/Part/Gui/DlgRevolution.h | 25 +- src/Mod/Part/Gui/DlgScale.cpp | 186 +- src/Mod/Part/Gui/DlgScale.h | 19 +- src/Mod/Part/Gui/DlgSettings3DViewPartImp.cpp | 46 +- src/Mod/Part/Gui/DlgSettings3DViewPartImp.h | 11 +- src/Mod/Part/Gui/DlgSettingsGeneral.cpp | 40 +- src/Mod/Part/Gui/DlgSettingsGeneral.h | 19 +- src/Mod/Part/Gui/DlgSettingsObjectColor.cpp | 3 +- src/Mod/Part/Gui/DlgSettingsObjectColor.h | 23 +- src/Mod/Part/Gui/Mirroring.cpp | 230 +- src/Mod/Part/Gui/Mirroring.h | 30 +- src/Mod/Part/Gui/PatternParametersWidget.cpp | 174 +- src/Mod/Part/Gui/PatternParametersWidget.h | 308 +- src/Mod/Part/Gui/PatternParametersWidget.ui | 1 - src/Mod/Part/Gui/PreCompiled.h | 10 +- src/Mod/Part/Gui/PropertyEnumAttacherItem.cpp | 18 +- src/Mod/Part/Gui/PropertyEnumAttacherItem.h | 16 +- src/Mod/Part/Gui/ReferenceHighlighter.cpp | 105 +- src/Mod/Part/Gui/ReferenceHighlighter.h | 40 +- src/Mod/Part/Gui/SectionCutting.cpp | 659 ++-- src/Mod/Part/Gui/SectionCutting.h | 50 +- src/Mod/Part/Gui/ShapeFromMesh.cpp | 15 +- src/Mod/Part/Gui/ShapeFromMesh.h | 9 +- src/Mod/Part/Gui/SoBrepEdgeSet.cpp | 489 ++- src/Mod/Part/Gui/SoBrepEdgeSet.h | 50 +- src/Mod/Part/Gui/SoBrepFaceSet.cpp | 1810 +++++---- src/Mod/Part/Gui/SoBrepFaceSet.h | 133 +- src/Mod/Part/Gui/SoBrepPointSet.cpp | 384 +- src/Mod/Part/Gui/SoBrepPointSet.h | 32 +- src/Mod/Part/Gui/SoFCShapeObject.cpp | 139 +- src/Mod/Part/Gui/SoFCShapeObject.h | 27 +- src/Mod/Part/Gui/TaskAttacher.cpp | 548 ++- src/Mod/Part/Gui/TaskAttacher.h | 83 +- src/Mod/Part/Gui/TaskCheckGeometry.cpp | 1492 ++++--- src/Mod/Part/Gui/TaskCheckGeometry.h | 176 +- src/Mod/Part/Gui/TaskFaceAppearances.cpp | 167 +- src/Mod/Part/Gui/TaskFaceAppearances.h | 33 +- src/Mod/Part/Gui/TaskLoft.cpp | 123 +- src/Mod/Part/Gui/TaskLoft.h | 17 +- src/Mod/Part/Gui/TaskOffset.cpp | 81 +- src/Mod/Part/Gui/TaskOffset.h | 22 +- src/Mod/Part/Gui/TaskShapeBuilder.cpp | 261 +- src/Mod/Part/Gui/TaskShapeBuilder.h | 18 +- src/Mod/Part/Gui/TaskSweep.cpp | 251 +- src/Mod/Part/Gui/TaskSweep.h | 22 +- src/Mod/Part/Gui/TaskThickness.cpp | 111 +- src/Mod/Part/Gui/TaskThickness.h | 27 +- src/Mod/Part/Gui/ViewProvider.cpp | 16 +- src/Mod/Part/Gui/ViewProvider.h | 33 +- src/Mod/Part/Gui/ViewProvider2DObject.cpp | 218 +- src/Mod/Part/Gui/ViewProvider2DObject.h | 28 +- .../Part/Gui/ViewProviderAttachExtension.cpp | 69 +- .../Part/Gui/ViewProviderAttachExtension.h | 11 +- src/Mod/Part/Gui/ViewProviderBoolean.cpp | 289 +- src/Mod/Part/Gui/ViewProviderBoolean.h | 19 +- src/Mod/Part/Gui/ViewProviderBox.cpp | 19 +- src/Mod/Part/Gui/ViewProviderBox.h | 11 +- .../Part/Gui/ViewProviderCircleParametric.cpp | 15 +- .../Part/Gui/ViewProviderCircleParametric.h | 11 +- src/Mod/Part/Gui/ViewProviderCompound.cpp | 52 +- src/Mod/Part/Gui/ViewProviderCompound.h | 11 +- .../Part/Gui/ViewProviderConeParametric.cpp | 19 +- src/Mod/Part/Gui/ViewProviderConeParametric.h | 11 +- src/Mod/Part/Gui/ViewProviderCurveNet.cpp | 148 +- src/Mod/Part/Gui/ViewProviderCurveNet.h | 43 +- .../Gui/ViewProviderCylinderParametric.cpp | 19 +- .../Part/Gui/ViewProviderCylinderParametric.h | 11 +- src/Mod/Part/Gui/ViewProviderDatum.h | 19 +- .../Gui/ViewProviderEllipseParametric.cpp | 15 +- .../Part/Gui/ViewProviderEllipseParametric.h | 11 +- src/Mod/Part/Gui/ViewProviderExt.cpp | 624 +-- src/Mod/Part/Gui/ViewProviderExt.h | 117 +- src/Mod/Part/Gui/ViewProviderExtrusion.cpp | 5 +- src/Mod/Part/Gui/ViewProviderExtrusion.h | 9 +- .../Part/Gui/ViewProviderGridExtension.cpp | 242 +- src/Mod/Part/Gui/ViewProviderGridExtension.h | 31 +- .../Part/Gui/ViewProviderHelixParametric.cpp | 3 +- .../Part/Gui/ViewProviderHelixParametric.h | 12 +- src/Mod/Part/Gui/ViewProviderImport.cpp | 2 +- src/Mod/Part/Gui/ViewProviderImport.h | 10 +- .../Part/Gui/ViewProviderLineParametric.cpp | 15 +- src/Mod/Part/Gui/ViewProviderLineParametric.h | 11 +- src/Mod/Part/Gui/ViewProviderMirror.cpp | 230 +- src/Mod/Part/Gui/ViewProviderMirror.h | 64 +- src/Mod/Part/Gui/ViewProviderPartExt.pyi | 2 +- .../Part/Gui/ViewProviderPlaneParametric.h | 13 +- .../Part/Gui/ViewProviderPointParametric.cpp | 19 +- .../Part/Gui/ViewProviderPointParametric.h | 11 +- .../Part/Gui/ViewProviderPreviewExtension.cpp | 47 +- .../Part/Gui/ViewProviderPreviewExtension.h | 24 +- src/Mod/Part/Gui/ViewProviderPrimitive.cpp | 20 +- src/Mod/Part/Gui/ViewProviderPrimitive.h | 10 +- src/Mod/Part/Gui/ViewProviderPrism.h | 14 +- .../Part/Gui/ViewProviderProjectOnSurface.h | 10 +- src/Mod/Part/Gui/ViewProviderPython.cpp | 12 +- src/Mod/Part/Gui/ViewProviderPython.h | 10 +- src/Mod/Part/Gui/ViewProviderReference.cpp | 240 +- src/Mod/Part/Gui/ViewProviderReference.h | 55 +- .../Part/Gui/ViewProviderRegularPolygon.cpp | 2 +- src/Mod/Part/Gui/ViewProviderRegularPolygon.h | 11 +- src/Mod/Part/Gui/ViewProviderRuledSurface.cpp | 44 +- src/Mod/Part/Gui/ViewProviderRuledSurface.h | 12 +- src/Mod/Part/Gui/ViewProviderScale.cpp | 5 +- src/Mod/Part/Gui/ViewProviderScale.h | 9 +- .../Part/Gui/ViewProviderSphereParametric.cpp | 30 +- .../Part/Gui/ViewProviderSphereParametric.h | 13 +- src/Mod/Part/Gui/ViewProviderSpline.cpp | 175 +- src/Mod/Part/Gui/ViewProviderSpline.h | 14 +- .../Part/Gui/ViewProviderTorusParametric.cpp | 18 +- .../Part/Gui/ViewProviderTorusParametric.h | 11 +- src/Mod/Part/Gui/Workbench.cpp | 28 +- src/Mod/Part/Gui/Workbench.h | 21 +- src/Mod/Part/Gui/WorkbenchManipulator.cpp | 10 +- src/Mod/Part/Gui/WorkbenchManipulator.h | 7 +- src/Mod/Part/Init.py | 62 +- src/Mod/Part/InitGui.py | 22 +- src/Mod/Part/JoinFeatures.py | 23 +- src/Mod/Part/MakeBottle.py | 207 +- src/Mod/Part/PartEnums.py | 10 +- src/Mod/Part/PartGlobal.h | 38 +- src/Mod/Part/TestPartApp.py | 179 +- src/Mod/Part/TestPartGui.py | 15 +- src/Mod/Part/part.dox | 1 - src/Mod/Part/parttests/BRep_tests.py | 1 + src/Mod/Part/parttests/ColorPerFaceTest.py | 73 +- .../Part/parttests/ColorTransparencyTest.py | 56 +- src/Mod/Part/parttests/Geom2d_tests.py | 2 + src/Mod/Part/parttests/TopoShapeListTest.py | 32 +- src/Mod/Part/parttests/TopoShapeTest.py | 262 +- src/Mod/Part/parttests/__init__.py | 2 +- src/Mod/Part/parttests/part_test_objects.py | 22 +- src/Mod/Part/parttests/regression_tests.py | 57 +- src/Mod/PartDesign/App/AppPartDesignPy.cpp | 69 +- src/Mod/PartDesign/App/Body.cpp | 398 +- src/Mod/PartDesign/App/Body.h | 85 +- src/Mod/PartDesign/App/BodyPyImp.cpp | 36 +- src/Mod/PartDesign/App/CMakeLists.txt | 1 - src/Mod/PartDesign/App/DatumCS.cpp | 65 +- src/Mod/PartDesign/App/DatumCS.h | 18 +- src/Mod/PartDesign/App/DatumLine.cpp | 32 +- src/Mod/PartDesign/App/DatumLine.h | 11 +- src/Mod/PartDesign/App/DatumPlane.cpp | 34 +- src/Mod/PartDesign/App/DatumPlane.h | 11 +- src/Mod/PartDesign/App/DatumPoint.cpp | 25 +- src/Mod/PartDesign/App/DatumPoint.h | 10 +- src/Mod/PartDesign/App/Feature.cpp | 201 +- src/Mod/PartDesign/App/Feature.h | 43 +- src/Mod/PartDesign/App/FeatureAddSub.cpp | 46 +- src/Mod/PartDesign/App/FeatureAddSub.h | 21 +- src/Mod/PartDesign/App/FeatureBase.cpp | 44 +- src/Mod/PartDesign/App/FeatureBase.h | 11 +- src/Mod/PartDesign/App/FeatureBoolean.cpp | 145 +- src/Mod/PartDesign/App/FeatureBoolean.h | 22 +- src/Mod/PartDesign/App/FeatureChamfer.cpp | 159 +- src/Mod/PartDesign/App/FeatureChamfer.h | 19 +- src/Mod/PartDesign/App/FeatureDraft.cpp | 170 +- src/Mod/PartDesign/App/FeatureDraft.h | 17 +- src/Mod/PartDesign/App/FeatureDressUp.cpp | 126 +- src/Mod/PartDesign/App/FeatureDressUp.h | 18 +- src/Mod/PartDesign/App/FeatureExtrude.cpp | 482 ++- src/Mod/PartDesign/App/FeatureExtrude.h | 37 +- src/Mod/PartDesign/App/FeatureFillet.cpp | 74 +- src/Mod/PartDesign/App/FeatureFillet.h | 19 +- src/Mod/PartDesign/App/FeatureGroove.cpp | 229 +- src/Mod/PartDesign/App/FeatureGroove.h | 73 +- src/Mod/PartDesign/App/FeatureHelix.cpp | 582 ++- src/Mod/PartDesign/App/FeatureHelix.h | 50 +- src/Mod/PartDesign/App/FeatureHole.cpp | 1980 +++++----- src/Mod/PartDesign/App/FeatureHole.h | 169 +- .../PartDesign/App/FeatureLinearPattern.cpp | 243 +- src/Mod/PartDesign/App/FeatureLinearPattern.h | 77 +- src/Mod/PartDesign/App/FeatureLoft.cpp | 239 +- src/Mod/PartDesign/App/FeatureLoft.h | 39 +- src/Mod/PartDesign/App/FeatureMirrored.cpp | 41 +- src/Mod/PartDesign/App/FeatureMirrored.h | 21 +- .../PartDesign/App/FeatureMultiTransform.cpp | 20 +- .../PartDesign/App/FeatureMultiTransform.h | 5 +- src/Mod/PartDesign/App/FeaturePad.cpp | 48 +- src/Mod/PartDesign/App/FeaturePad.h | 31 +- src/Mod/PartDesign/App/FeaturePipe.cpp | 403 +- src/Mod/PartDesign/App/FeaturePipe.h | 66 +- src/Mod/PartDesign/App/FeaturePocket.cpp | 69 +- src/Mod/PartDesign/App/FeaturePocket.h | 29 +- .../PartDesign/App/FeaturePolarPattern.cpp | 187 +- src/Mod/PartDesign/App/FeaturePolarPattern.h | 70 +- src/Mod/PartDesign/App/FeaturePrimitive.cpp | 549 ++- src/Mod/PartDesign/App/FeaturePrimitive.h | 178 +- src/Mod/PartDesign/App/FeaturePyImp.cpp | 13 +- src/Mod/PartDesign/App/FeatureRefine.cpp | 21 +- src/Mod/PartDesign/App/FeatureRefine.h | 17 +- src/Mod/PartDesign/App/FeatureRevolution.cpp | 236 +- src/Mod/PartDesign/App/FeatureRevolution.h | 73 +- src/Mod/PartDesign/App/FeatureScaled.cpp | 3 +- src/Mod/PartDesign/App/FeatureScaled.h | 5 +- src/Mod/PartDesign/App/FeatureSketchBased.cpp | 579 +-- src/Mod/PartDesign/App/FeatureSketchBased.h | 89 +- src/Mod/PartDesign/App/FeatureSolid.cpp | 9 +- src/Mod/PartDesign/App/FeatureSolid.h | 9 +- src/Mod/PartDesign/App/FeatureThickness.cpp | 74 +- src/Mod/PartDesign/App/FeatureThickness.h | 21 +- src/Mod/PartDesign/App/FeatureTransformed.cpp | 40 +- src/Mod/PartDesign/App/FeatureTransformed.h | 11 +- src/Mod/PartDesign/App/Measure.cpp | 5 +- src/Mod/PartDesign/App/Measure.h | 5 +- src/Mod/PartDesign/App/PreCompiled.h | 1 - src/Mod/PartDesign/App/ShapeBinder.cpp | 638 +-- src/Mod/PartDesign/App/ShapeBinder.h | 67 +- src/Mod/PartDesign/Gui/Command.cpp | 1597 ++++---- src/Mod/PartDesign/Gui/CommandBody.cpp | 872 ++-- src/Mod/PartDesign/Gui/CommandPrimitive.cpp | 272 +- src/Mod/PartDesign/Gui/DlgActiveBody.cpp | 25 +- src/Mod/PartDesign/Gui/DlgActiveBody.h | 19 +- src/Mod/PartDesign/Gui/EnumFlags.h | 26 +- src/Mod/PartDesign/Gui/PreCompiled.h | 8 +- src/Mod/PartDesign/Gui/ReferenceSelection.cpp | 166 +- src/Mod/PartDesign/Gui/ReferenceSelection.h | 82 +- src/Mod/PartDesign/Gui/SketchWorkflow.cpp | 319 +- src/Mod/PartDesign/Gui/SketchWorkflow.h | 60 +- src/Mod/PartDesign/Gui/StyleParameters.h | 29 +- .../PartDesign/Gui/TaskBooleanParameters.cpp | 63 +- .../PartDesign/Gui/TaskBooleanParameters.h | 49 +- .../PartDesign/Gui/TaskChamferParameters.cpp | 14 +- .../PartDesign/Gui/TaskChamferParameters.h | 25 +- .../PartDesign/Gui/TaskDatumParameters.cpp | 83 +- src/Mod/PartDesign/Gui/TaskDatumParameters.h | 22 +- .../PartDesign/Gui/TaskDraftParameters.cpp | 7 +- src/Mod/PartDesign/Gui/TaskDraftParameters.h | 17 +- .../PartDesign/Gui/TaskDressUpParameters.cpp | 120 +- .../PartDesign/Gui/TaskDressUpParameters.h | 42 +- .../PartDesign/Gui/TaskExtrudeParameters.cpp | 221 +- .../PartDesign/Gui/TaskExtrudeParameters.h | 91 +- .../PartDesign/Gui/TaskFeatureParameters.cpp | 118 +- .../PartDesign/Gui/TaskFeatureParameters.h | 51 +- src/Mod/PartDesign/Gui/TaskFeaturePick.cpp | 77 +- src/Mod/PartDesign/Gui/TaskFeaturePick.h | 60 +- .../PartDesign/Gui/TaskFilletParameters.cpp | 6 +- src/Mod/PartDesign/Gui/TaskFilletParameters.h | 20 +- .../PartDesign/Gui/TaskHelixParameters.cpp | 49 +- src/Mod/PartDesign/Gui/TaskHelixParameters.h | 40 +- src/Mod/PartDesign/Gui/TaskHoleParameters.cpp | 156 +- src/Mod/PartDesign/Gui/TaskHoleParameters.h | 71 +- src/Mod/PartDesign/Gui/TaskLoftParameters.cpp | 21 +- src/Mod/PartDesign/Gui/TaskLoftParameters.h | 41 +- .../PartDesign/Gui/TaskMirroredParameters.cpp | 32 +- .../PartDesign/Gui/TaskMirroredParameters.h | 3 +- .../Gui/TaskMultiTransformParameters.cpp | 155 +- .../Gui/TaskMultiTransformParameters.h | 6 +- src/Mod/PartDesign/Gui/TaskPadParameters.cpp | 9 +- src/Mod/PartDesign/Gui/TaskPadParameters.h | 21 +- .../PartDesign/Gui/TaskPatternParameters.cpp | 125 +- .../PartDesign/Gui/TaskPatternParameters.h | 19 +- src/Mod/PartDesign/Gui/TaskPipeParameters.cpp | 207 +- src/Mod/PartDesign/Gui/TaskPipeParameters.h | 76 +- .../PartDesign/Gui/TaskPocketParameters.cpp | 17 +- src/Mod/PartDesign/Gui/TaskPocketParameters.h | 25 +- .../Gui/TaskPrimitiveParameters.cpp | 235 +- .../PartDesign/Gui/TaskPrimitiveParameters.h | 27 +- .../Gui/TaskRevolutionParameters.cpp | 172 +- .../PartDesign/Gui/TaskRevolutionParameters.h | 53 +- .../PartDesign/Gui/TaskScaledParameters.cpp | 29 +- src/Mod/PartDesign/Gui/TaskScaledParameters.h | 3 +- src/Mod/PartDesign/Gui/TaskShapeBinder.cpp | 145 +- src/Mod/PartDesign/Gui/TaskShapeBinder.h | 46 +- .../Gui/TaskSketchBasedParameters.cpp | 54 +- .../Gui/TaskSketchBasedParameters.h | 33 +- .../Gui/TaskThicknessParameters.cpp | 6 +- .../PartDesign/Gui/TaskThicknessParameters.h | 5 +- .../Gui/TaskTransformedMessages.cpp | 14 +- .../PartDesign/Gui/TaskTransformedMessages.h | 16 +- .../Gui/TaskTransformedParameters.cpp | 74 +- .../Gui/TaskTransformedParameters.h | 13 +- src/Mod/PartDesign/Gui/Utils.cpp | 510 ++- src/Mod/PartDesign/Gui/Utils.h | 85 +- src/Mod/PartDesign/Gui/ViewProvider.cpp | 140 +- src/Mod/PartDesign/Gui/ViewProvider.h | 41 +- src/Mod/PartDesign/Gui/ViewProvider.pyi | 2 +- src/Mod/PartDesign/Gui/ViewProviderBase.cpp | 21 +- src/Mod/PartDesign/Gui/ViewProviderBase.h | 9 +- src/Mod/PartDesign/Gui/ViewProviderBody.cpp | 202 +- src/Mod/PartDesign/Gui/ViewProviderBody.h | 27 +- .../PartDesign/Gui/ViewProviderBoolean.cpp | 30 +- src/Mod/PartDesign/Gui/ViewProviderBoolean.h | 13 +- .../PartDesign/Gui/ViewProviderChamfer.cpp | 11 +- src/Mod/PartDesign/Gui/ViewProviderChamfer.h | 20 +- src/Mod/PartDesign/Gui/ViewProviderDatum.cpp | 248 +- src/Mod/PartDesign/Gui/ViewProviderDatum.h | 53 +- .../PartDesign/Gui/ViewProviderDatumCS.cpp | 183 +- src/Mod/PartDesign/Gui/ViewProviderDatumCS.h | 28 +- .../PartDesign/Gui/ViewProviderDatumLine.cpp | 59 +- .../PartDesign/Gui/ViewProviderDatumLine.h | 15 +- .../PartDesign/Gui/ViewProviderDatumPlane.cpp | 73 +- .../PartDesign/Gui/ViewProviderDatumPlane.h | 15 +- .../PartDesign/Gui/ViewProviderDatumPoint.cpp | 41 +- .../PartDesign/Gui/ViewProviderDatumPoint.h | 11 +- src/Mod/PartDesign/Gui/ViewProviderDraft.cpp | 11 +- src/Mod/PartDesign/Gui/ViewProviderDraft.h | 19 +- .../PartDesign/Gui/ViewProviderDressUp.cpp | 71 +- src/Mod/PartDesign/Gui/ViewProviderDressUp.h | 14 +- .../PartDesign/Gui/ViewProviderExtrude.cpp | 8 +- src/Mod/PartDesign/Gui/ViewProviderExtrude.h | 10 +- src/Mod/PartDesign/Gui/ViewProviderFillet.cpp | 11 +- src/Mod/PartDesign/Gui/ViewProviderFillet.h | 19 +- src/Mod/PartDesign/Gui/ViewProviderGroove.cpp | 9 +- src/Mod/PartDesign/Gui/ViewProviderGroove.h | 12 +- src/Mod/PartDesign/Gui/ViewProviderHelix.cpp | 29 +- src/Mod/PartDesign/Gui/ViewProviderHelix.h | 11 +- src/Mod/PartDesign/Gui/ViewProviderHole.cpp | 7 +- src/Mod/PartDesign/Gui/ViewProviderHole.h | 14 +- .../Gui/ViewProviderLinearPattern.cpp | 10 +- .../Gui/ViewProviderLinearPattern.h | 21 +- src/Mod/PartDesign/Gui/ViewProviderLoft.cpp | 76 +- src/Mod/PartDesign/Gui/ViewProviderLoft.h | 12 +- .../PartDesign/Gui/ViewProviderMainPart.cpp | 13 +- src/Mod/PartDesign/Gui/ViewProviderMainPart.h | 11 +- .../PartDesign/Gui/ViewProviderMirrored.cpp | 10 +- src/Mod/PartDesign/Gui/ViewProviderMirrored.h | 15 +- .../Gui/ViewProviderMultiTransform.cpp | 27 +- .../Gui/ViewProviderMultiTransform.h | 19 +- src/Mod/PartDesign/Gui/ViewProviderPad.cpp | 7 +- src/Mod/PartDesign/Gui/ViewProviderPad.h | 12 +- src/Mod/PartDesign/Gui/ViewProviderPipe.cpp | 102 +- src/Mod/PartDesign/Gui/ViewProviderPipe.h | 16 +- src/Mod/PartDesign/Gui/ViewProviderPocket.cpp | 7 +- src/Mod/PartDesign/Gui/ViewProviderPocket.h | 13 +- .../Gui/ViewProviderPolarPattern.cpp | 7 +- .../PartDesign/Gui/ViewProviderPolarPattern.h | 18 +- .../PartDesign/Gui/ViewProviderPrimitive.cpp | 69 +- .../PartDesign/Gui/ViewProviderPrimitive.h | 13 +- src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp | 5 +- .../PartDesign/Gui/ViewProviderRevolution.cpp | 9 +- .../PartDesign/Gui/ViewProviderRevolution.h | 13 +- src/Mod/PartDesign/Gui/ViewProviderScaled.cpp | 10 +- src/Mod/PartDesign/Gui/ViewProviderScaled.h | 18 +- .../Gui/ViewProviderShapeBinder.cpp | 245 +- .../PartDesign/Gui/ViewProviderShapeBinder.h | 47 +- .../Gui/ViewProviderSketchBased.cpp | 27 +- .../PartDesign/Gui/ViewProviderSketchBased.h | 10 +- .../PartDesign/Gui/ViewProviderThickness.cpp | 11 +- .../PartDesign/Gui/ViewProviderThickness.h | 19 +- .../Gui/ViewProviderTransformed.cpp | 43 +- .../PartDesign/Gui/ViewProviderTransformed.h | 29 +- src/Mod/PartDesign/Gui/Workbench.cpp | 161 +- src/Mod/PartDesign/Gui/Workbench.h | 12 +- src/Mod/PartDesign/Gui/WorkflowManager.cpp | 184 +- src/Mod/PartDesign/Gui/WorkflowManager.h | 71 +- src/Mod/PartDesign/Init.py | 46 +- src/Mod/PartDesign/InitGui.py | 63 +- src/Mod/PartDesign/InvoluteGearFeature.py | 264 +- src/Mod/PartDesign/PartDesignGlobal.h | 22 +- .../PartDesignTests/TestActiveObject.py | 62 +- .../PartDesign/PartDesignTests/TestBoolean.py | 171 +- .../PartDesign/PartDesignTests/TestChamfer.py | 67 +- .../PartDesign/PartDesignTests/TestDatum.py | 84 +- .../PartDesign/PartDesignTests/TestDraft.py | 85 +- .../PartDesign/PartDesignTests/TestFillet.py | 74 +- .../PartDesign/PartDesignTests/TestHelix.py | 340 +- .../PartDesign/PartDesignTests/TestHole.py | 602 ++- .../PartDesignTests/TestInvoluteGear.py | 316 +- .../PartDesignTests/TestLinearPattern.py | 110 +- .../PartDesign/PartDesignTests/TestLoft.py | 327 +- .../PartDesignTests/TestMaterial.py | 113 +- .../PartDesignTests/TestMirrored.py | 71 +- .../PartDesignTests/TestMultiTransform.py | 120 +- src/Mod/PartDesign/PartDesignTests/TestPad.py | 146 +- .../PartDesign/PartDesignTests/TestPipe.py | 92 +- .../PartDesign/PartDesignTests/TestPocket.py | 95 +- .../PartDesignTests/TestPolarPattern.py | 110 +- .../PartDesignTests/TestPrimitive.py | 108 +- .../PartDesign/PartDesignTests/TestRevolve.py | 72 +- .../PartDesignTests/TestShapeBinder.py | 178 +- .../PartDesign/PartDesignTests/TestSketch.py | 77 +- .../PartDesignTests/TestThickness.py | 55 +- .../TestTopologicalNamingProblem.py | 273 +- .../PartDesign/Resources/Hole/din7984.json | 96 +- .../Resources/Hole/iso10642-fine.json | 85 +- .../PartDesign/Resources/Hole/iso10642.json | 60 +- .../Resources/Hole/iso12474-fine.json | 96 +- .../PartDesign/Resources/Hole/iso14583.json | 54 +- .../Resources/Hole/iso14583part.json | 54 +- .../PartDesign/Resources/Hole/iso2009.json | 45 +- .../Resources/Hole/iso4762-fine.json | 168 +- .../PartDesign/Resources/Hole/iso4762.json | 144 +- .../Resources/Hole/iso4762_7089.json | 120 +- .../PartDesign/Resources/Hole/iso7046.json | 50 +- src/Mod/PartDesign/Scripts/DistanceBolt.py | 40 +- src/Mod/PartDesign/Scripts/Epitrochoid.py | 89 +- src/Mod/PartDesign/Scripts/FilletArc.py | 34 +- src/Mod/PartDesign/Scripts/Gear.py | 131 +- src/Mod/PartDesign/Scripts/Parallelepiped.py | 77 +- src/Mod/PartDesign/Scripts/RadialCopy.py | 27 +- src/Mod/PartDesign/Scripts/Spring.py | 84 +- src/Mod/PartDesign/SprocketFeature.py | 95 +- src/Mod/PartDesign/TestPartDesignApp.py | 8 +- src/Mod/PartDesign/TestPartDesignGui.py | 246 +- .../PartDesign/WizardShaft/SegmentFunction.py | 144 +- src/Mod/PartDesign/WizardShaft/Shaft.py | 500 ++- .../PartDesign/WizardShaft/ShaftDiagram.py | 14 +- .../PartDesign/WizardShaft/ShaftFeature.py | 107 +- src/Mod/PartDesign/WizardShaft/WizardShaft.py | 111 +- .../WizardShaft/WizardShaftTable.py | 111 +- src/Mod/PartDesign/WizardShaft/__init__.py | 2 +- src/Mod/PartDesign/__init__.py | 2 +- src/Mod/PartDesign/fcgear/fcgear.py | 29 +- src/Mod/PartDesign/fcgear/involute.py | 176 +- src/Mod/PartDesign/fcgear/svggear.py | 116 +- src/Mod/PartDesign/fcsprocket/__init__.py | 1 - src/Mod/PartDesign/fcsprocket/fcsprocket.py | 31 +- .../PartDesign/fcsprocket/fcsprocketdialog.py | 25 +- src/Mod/PartDesign/fcsprocket/sprocket.py | 89 +- src/Mod/PartDesign/partdesign.dox | 1 - src/Mod/Points/App/AppPointsPy.cpp | 108 +- src/Mod/Points/App/Points.cpp | 86 +- src/Mod/Points/App/Points.h | 10 +- src/Mod/Points/App/PointsAlgos.cpp | 267 +- src/Mod/Points/App/PointsAlgos.h | 52 +- src/Mod/Points/App/PointsGrid.cpp | 198 +- src/Mod/Points/App/PointsGrid.h | 127 +- src/Mod/Points/App/PointsPyImp.cpp | 10 +- src/Mod/Points/App/Properties.cpp | 16 +- src/Mod/Points/App/Tools.h | 11 +- src/Mod/Points/Gui/AppPointsGui.cpp | 6 +- src/Mod/Points/Gui/Command.cpp | 92 +- src/Mod/Points/Gui/DlgPointsReadImp.h | 8 +- src/Mod/Points/Gui/ViewProvider.cpp | 90 +- src/Mod/Points/PointsGlobal.h | 30 +- .../App/AppReverseEngineering.cpp | 6 +- .../ReverseEngineering/App/ApproxSurface.cpp | 145 +- .../ReverseEngineering/App/ApproxSurface.h | 75 +- .../ReverseEngineering/App/BSplineFitting.cpp | 50 +- .../ReverseEngineering/App/BSplineFitting.h | 6 +- src/Mod/ReverseEngineering/App/PreCompiled.h | 2 +- .../ReverseEngineering/App/RegionGrowing.cpp | 23 +- .../App/SampleConsensus.cpp | 37 +- .../ReverseEngineering/App/Segmentation.cpp | 22 +- .../App/SurfaceTriangulation.cpp | 73 +- src/Mod/ReverseEngineering/Gui/Command.cpp | 75 +- .../Gui/FitBSplineCurve.cpp | 9 +- .../Gui/FitBSplineSurface.cpp | 100 +- src/Mod/ReverseEngineering/Gui/Poisson.cpp | 16 +- .../ReverseEngineering/Gui/Segmentation.cpp | 53 +- src/Mod/ReverseEngineering/Gui/Segmentation.h | 8 +- .../Gui/SegmentationManual.cpp | 66 +- .../ReverseEngineeringGlobal.h | 30 +- src/Mod/Robot/App/AppRobot.cpp | 28 +- src/Mod/Robot/App/Edge2TracObject.cpp | 33 +- src/Mod/Robot/App/Robot6Axis.cpp | 68 +- src/Mod/Robot/App/Robot6AxisPyImp.cpp | 3 +- src/Mod/Robot/App/RobotAlgos.cpp | 12 +- src/Mod/Robot/App/RobotAlgos.h | 14 +- src/Mod/Robot/App/RobotObject.cpp | 108 +- src/Mod/Robot/App/Trajectory.cpp | 43 +- src/Mod/Robot/App/TrajectoryCompound.cpp | 7 +- src/Mod/Robot/App/TrajectoryDressUpObject.cpp | 72 +- src/Mod/Robot/App/TrajectoryObject.cpp | 12 +- src/Mod/Robot/App/TrajectoryPyImp.cpp | 11 +- src/Mod/Robot/App/Waypoint.cpp | 38 +- src/Mod/Robot/App/Waypoint.h | 18 +- src/Mod/Robot/App/WaypointPyImp.cpp | 28 +- src/Mod/Robot/Gui/Command.cpp | 77 +- src/Mod/Robot/Gui/CommandExport.cpp | 60 +- src/Mod/Robot/Gui/CommandInsertRobot.cpp | 133 +- src/Mod/Robot/Gui/CommandTrajectory.cpp | 209 +- src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp | 10 +- src/Mod/Robot/Gui/TaskDlgSimulate.cpp | 6 +- .../Robot/Gui/TaskDlgTrajectoryCompound.cpp | 6 +- src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp | 5 +- src/Mod/Robot/Gui/TaskRobot6Axis.cpp | 32 +- src/Mod/Robot/Gui/TaskRobot6Axis.h | 3 +- src/Mod/Robot/Gui/TaskRobotControl.cpp | 5 +- src/Mod/Robot/Gui/TaskTrajectory.cpp | 47 +- src/Mod/Robot/Gui/TaskTrajectory.h | 22 +- .../Gui/TaskTrajectoryDressUpParameter.cpp | 21 +- .../Gui/TaskTrajectoryDressUpParameter.h | 6 +- src/Mod/Robot/Gui/TrajectorySimulate.cpp | 31 +- src/Mod/Robot/Gui/TrajectorySimulate.h | 8 +- src/Mod/Robot/Gui/ViewProviderRobotObject.cpp | 139 +- src/Mod/Robot/Gui/ViewProviderRobotObject.h | 8 +- src/Mod/Robot/Gui/ViewProviderTrajectory.cpp | 3 +- .../Gui/ViewProviderTrajectoryCompound.cpp | 5 +- .../Gui/ViewProviderTrajectoryDressUp.cpp | 5 +- src/Mod/Robot/Gui/Workbench.cpp | 87 +- src/Mod/Robot/RobotGlobal.h | 20 +- src/Mod/Sketcher/App/AppSketcher.cpp | 28 +- src/Mod/Sketcher/App/Constraint.cpp | 46 +- src/Mod/Sketcher/App/Constraint.h | 26 +- src/Mod/Sketcher/App/ConstraintPyImp.cpp | 224 +- .../App/ExternalGeometryExtension.cpp | 13 +- .../Sketcher/App/ExternalGeometryExtension.h | 3 +- .../App/ExternalGeometryExtensionPyImp.cpp | 11 +- .../Sketcher/App/ExternalGeometryFacade.cpp | 32 +- .../App/ExternalGeometryFacadePyImp.cpp | 116 +- src/Mod/Sketcher/App/GeoList.cpp | 75 +- src/Mod/Sketcher/App/GeoList.h | 24 +- src/Mod/Sketcher/App/GeometryFacade.cpp | 17 +- src/Mod/Sketcher/App/GeometryFacade.h | 31 +- src/Mod/Sketcher/App/GeometryFacadePyImp.cpp | 85 +- src/Mod/Sketcher/App/PreCompiled.h | 148 +- .../Sketcher/App/PropertyConstraintList.cpp | 18 +- src/Mod/Sketcher/App/PythonConverter.cpp | 306 +- src/Mod/Sketcher/App/PythonConverter.h | 28 +- src/Mod/Sketcher/App/Sketch.cpp | 1041 ++--- src/Mod/Sketcher/App/Sketch.h | 221 +- src/Mod/Sketcher/App/SketchAnalysis.cpp | 127 +- src/Mod/Sketcher/App/SketchAnalysis.h | 14 +- .../Sketcher/App/SketchGeometryExtension.cpp | 26 +- .../Sketcher/App/SketchGeometryExtension.h | 34 +- .../App/SketchGeometryExtensionPyImp.cpp | 19 +- src/Mod/Sketcher/App/SketchObject.cpp | 418 +- src/Mod/Sketcher/App/SketchObject.h | 409 +- src/Mod/Sketcher/App/SketchObjectPyImp.cpp | 533 +-- src/Mod/Sketcher/App/SketchObjectSF.cpp | 15 +- src/Mod/Sketcher/App/SketchPyImp.cpp | 20 +- .../Sketcher/App/SolverGeometryExtension.cpp | 14 +- .../Sketcher/App/SolverGeometryExtension.h | 10 +- src/Mod/Sketcher/App/planegcs/Constraints.cpp | 193 +- src/Mod/Sketcher/App/planegcs/Constraints.h | 80 +- src/Mod/Sketcher/App/planegcs/GCS.cpp | 1123 +++--- src/Mod/Sketcher/App/planegcs/GCS.h | 591 +-- src/Mod/Sketcher/App/planegcs/Geo.cpp | 70 +- src/Mod/Sketcher/App/planegcs/Geo.h | 64 +- src/Mod/Sketcher/App/planegcs/SubSystem.cpp | 26 +- src/Mod/Sketcher/App/planegcs/qp_eq.cpp | 2 +- src/Mod/Sketcher/App/planegcs/qp_eq.h | 16 +- src/Mod/Sketcher/Gui/AppSketcherGui.cpp | 20 +- src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp | 25 +- src/Mod/Sketcher/Gui/CommandConstraints.h | 89 +- src/Mod/Sketcher/Gui/CommandCreateGeo.cpp | 254 +- .../Sketcher/Gui/CommandSketcherBSpline.cpp | 307 +- .../Sketcher/Gui/CommandSketcherOverlay.cpp | 125 +- .../Gui/CommandSketcherVirtualSpace.cpp | 53 +- src/Mod/Sketcher/Gui/ConstraintFilters.h | 106 +- .../Gui/DrawSketchControllableHandler.h | 19 +- src/Mod/Sketcher/Gui/DrawSketchController.h | 117 +- .../Sketcher/Gui/DrawSketchDefaultHandler.h | 201 +- .../Gui/DrawSketchDefaultWidgetController.h | 71 +- src/Mod/Sketcher/Gui/DrawSketchHandler.cpp | 244 +- src/Mod/Sketcher/Gui/DrawSketchHandler.h | 118 +- src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h | 223 +- .../Gui/DrawSketchHandlerArcOfEllipse.h | 139 +- .../Gui/DrawSketchHandlerArcOfHyperbola.h | 117 +- .../Gui/DrawSketchHandlerArcOfParabola.h | 75 +- .../Sketcher/Gui/DrawSketchHandlerArcSlot.h | 429 +- .../Sketcher/Gui/DrawSketchHandlerBSpline.h | 221 +- .../Gui/DrawSketchHandlerCarbonCopy.h | 69 +- .../Sketcher/Gui/DrawSketchHandlerCircle.h | 182 +- .../Sketcher/Gui/DrawSketchHandlerEllipse.h | 262 +- .../Sketcher/Gui/DrawSketchHandlerExtend.h | 91 +- .../Sketcher/Gui/DrawSketchHandlerExternal.h | 39 +- .../Sketcher/Gui/DrawSketchHandlerFillet.h | 105 +- src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h | 215 +- .../Sketcher/Gui/DrawSketchHandlerLineSet.h | 182 +- .../Sketcher/Gui/DrawSketchHandlerOffset.h | 133 +- src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h | 89 +- .../Sketcher/Gui/DrawSketchHandlerPolygon.h | 135 +- .../Sketcher/Gui/DrawSketchHandlerRectangle.h | 1650 ++++---- .../Sketcher/Gui/DrawSketchHandlerRotate.h | 96 +- src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h | 116 +- src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h | 254 +- .../Sketcher/Gui/DrawSketchHandlerSplitting.h | 34 +- .../Sketcher/Gui/DrawSketchHandlerSymmetry.h | 59 +- .../Sketcher/Gui/DrawSketchHandlerTranslate.h | 150 +- .../Sketcher/Gui/DrawSketchHandlerTrimming.h | 34 +- .../Gui/DrawSketchKeyboardManager.cpp | 4 +- src/Mod/Sketcher/Gui/EditDatumDialog.cpp | 106 +- src/Mod/Sketcher/Gui/EditModeCoinManager.cpp | 469 ++- src/Mod/Sketcher/Gui/EditModeCoinManager.h | 12 +- .../Gui/EditModeCoinManagerParameters.cpp | 52 +- .../Gui/EditModeCoinManagerParameters.h | 45 +- .../Gui/EditModeConstraintCoinManager.cpp | 899 +++-- .../Gui/EditModeConstraintCoinManager.h | 72 +- .../Gui/EditModeGeometryCoinConverter.cpp | 187 +- .../Gui/EditModeGeometryCoinConverter.h | 24 +- .../Gui/EditModeGeometryCoinManager.cpp | 218 +- .../Gui/EditModeGeometryCoinManager.h | 14 +- ...ditModeInformationOverlayCoinConverter.cpp | 113 +- .../EditModeInformationOverlayCoinConverter.h | 10 +- src/Mod/Sketcher/Gui/GeometryCreationMode.h | 2 +- src/Mod/Sketcher/Gui/PreCompiled.h | 2 +- .../Gui/PropertyConstraintListItem.cpp | 48 +- .../Sketcher/Gui/PropertyConstraintListItem.h | 8 +- .../Sketcher/Gui/SketchOrientationDialog.cpp | 6 +- src/Mod/Sketcher/Gui/SketcherSettings.cpp | 80 +- .../Gui/SketcherToolDefaultWidget.cpp | 193 +- .../Sketcher/Gui/SketcherToolDefaultWidget.h | 3 +- ...SketcherTransformationExpressionHelper.cpp | 71 +- .../SketcherTransformationExpressionHelper.h | 44 +- src/Mod/Sketcher/Gui/SnapManager.cpp | 45 +- src/Mod/Sketcher/Gui/StyleParameters.h | 6 +- src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp | 17 +- .../Sketcher/Gui/TaskSketcherConstraints.h | 16 +- .../Gui/TaskSketcherCreateCommands.cpp | 12 +- .../Sketcher/Gui/TaskSketcherCreateCommands.h | 6 +- src/Mod/Sketcher/Gui/TaskSketcherElements.cpp | 79 +- .../Gui/TaskSketcherSolverAdvanced.cpp | 368 +- .../Sketcher/Gui/TaskSketcherValidation.cpp | 75 +- src/Mod/Sketcher/Gui/Utils.cpp | 288 +- src/Mod/Sketcher/Gui/Utils.h | 89 +- src/Mod/Sketcher/Gui/ViewProviderPython.cpp | 3 +- src/Mod/Sketcher/Gui/ViewProviderSketch.cpp | 10 +- src/Mod/Sketcher/Gui/ViewProviderSketch.h | 104 +- .../Gui/ViewProviderSketchCoinAttorney.h | 75 +- .../ViewProviderSketchGeometryExtension.cpp | 10 +- .../Gui/ViewProviderSketchGeometryExtension.h | 3 +- ...ewProviderSketchGeometryExtensionPyImp.cpp | 21 +- src/Mod/Sketcher/Gui/VisualLayer.cpp | 3 +- src/Mod/Sketcher/Gui/VisualLayer.h | 4 +- src/Mod/Sketcher/Gui/Workbench.cpp | 100 +- src/Mod/Sketcher/SketcherGlobal.h | 30 +- src/Mod/Spreadsheet/App/Cell.cpp | 103 +- src/Mod/Spreadsheet/App/Cell.h | 3 +- src/Mod/Spreadsheet/App/DisplayUnit.h | 8 +- .../Spreadsheet/App/PropertyColumnWidths.cpp | 8 +- .../App/PropertyColumnWidthsPyImp.cpp | 3 +- .../Spreadsheet/App/PropertyRowHeights.cpp | 9 +- src/Mod/Spreadsheet/App/PropertySheet.cpp | 298 +- src/Mod/Spreadsheet/App/PropertySheet.h | 77 +- src/Mod/Spreadsheet/App/Sheet.cpp | 146 +- src/Mod/Spreadsheet/App/Sheet.h | 40 +- src/Mod/Spreadsheet/App/SheetObserver.cpp | 3 +- src/Mod/Spreadsheet/App/SheetPyImp.cpp | 43 +- src/Mod/Spreadsheet/App/Utils.cpp | 6 +- src/Mod/Spreadsheet/App/Utils.h | 7 +- src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp | 8 +- src/Mod/Spreadsheet/Gui/Command.cpp | 139 +- src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp | 89 +- src/Mod/Spreadsheet/Gui/DlgBindSheet.h | 8 +- src/Mod/Spreadsheet/Gui/DlgSettingsImp.cpp | 6 +- src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp | 84 +- src/Mod/Spreadsheet/Gui/DlgSheetConf.h | 12 +- src/Mod/Spreadsheet/Gui/LineEdit.cpp | 11 +- src/Mod/Spreadsheet/Gui/PreCompiled.h | 2 +- src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp | 113 +- src/Mod/Spreadsheet/Gui/PropertiesDialog.h | 8 +- src/Mod/Spreadsheet/Gui/SheetModel.cpp | 115 +- src/Mod/Spreadsheet/Gui/SheetTableView.cpp | 111 +- src/Mod/Spreadsheet/Gui/SheetTableView.h | 7 +- .../Gui/SheetTableViewAccessibleInterface.cpp | 6 +- .../Spreadsheet/Gui/SpreadsheetDelegate.cpp | 46 +- src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h | 20 +- src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp | 168 +- src/Mod/Spreadsheet/Gui/SpreadsheetView.h | 8 +- .../Gui/ViewProviderSpreadsheet.cpp | 12 +- src/Mod/Spreadsheet/Gui/Workbench.cpp | 72 +- src/Mod/Spreadsheet/Gui/ZoomableView.cpp | 48 +- src/Mod/Spreadsheet/Gui/ZoomableView.h | 5 +- src/Mod/Spreadsheet/SpreadsheetGlobal.h | 20 +- src/Mod/Start/App/CustomFolderModel.cpp | 15 +- src/Mod/Start/App/DisplayedFilesModel.cpp | 39 +- src/Mod/Start/App/ExamplesModel.cpp | 12 +- src/Mod/Start/App/FileUtilities.h | 3 +- src/Mod/Start/App/RecentFilesModel.cpp | 3 +- src/Mod/Start/App/ThumbnailSource.cpp | 17 +- src/Mod/Start/Gui/AppStartGui.cpp | 14 +- src/Mod/Start/Gui/FileCardDelegate.cpp | 72 +- src/Mod/Start/Gui/FileCardDelegate.h | 8 +- src/Mod/Start/Gui/FileCardView.cpp | 17 +- src/Mod/Start/Gui/FirstStartWidget.cpp | 8 +- src/Mod/Start/Gui/FlowLayout.cpp | 28 +- src/Mod/Start/Gui/FlowLayout.h | 5 +- src/Mod/Start/Gui/GeneralSettingsWidget.cpp | 67 +- src/Mod/Start/Gui/NewFileButton.cpp | 3 +- src/Mod/Start/Gui/StartView.cpp | 111 +- src/Mod/Start/Gui/ThemeSelectorWidget.cpp | 57 +- src/Mod/Start/StartGlobal.h | 30 +- src/Mod/Surface/App/Blending/BlendCurve.cpp | 16 +- .../Surface/App/Blending/BlendCurvePyImp.cpp | 14 +- .../Surface/App/Blending/BlendPointPyImp.cpp | 15 +- .../App/Blending/FeatureBlendCurve.cpp | 88 +- .../Surface/App/Blending/FeatureBlendCurve.h | 8 +- src/Mod/Surface/App/FeatureCut.cpp | 3 +- src/Mod/Surface/App/FeatureExtend.cpp | 16 +- src/Mod/Surface/App/FeatureExtend.h | 8 +- src/Mod/Surface/App/FeatureFilling.cpp | 41 +- src/Mod/Surface/App/FeatureFilling.h | 24 +- .../Surface/App/FeatureGeomFillSurface.cpp | 37 +- src/Mod/Surface/App/FeatureGeomFillSurface.h | 8 +- src/Mod/Surface/App/FeatureSections.cpp | 9 +- src/Mod/Surface/App/FeatureSewing.cpp | 12 +- .../Surface/Gui/Blending/TaskBlendCurve.cpp | 6 +- .../Gui/Blending/ViewProviderBlendCurve.cpp | 7 +- src/Mod/Surface/Gui/Command.cpp | 89 +- src/Mod/Surface/Gui/TaskFilling.cpp | 155 +- src/Mod/Surface/Gui/TaskFillingEdge.cpp | 165 +- src/Mod/Surface/Gui/TaskFillingVertex.cpp | 92 +- src/Mod/Surface/Gui/TaskFillingVertex.h | 4 +- src/Mod/Surface/Gui/TaskGeomFillSurface.cpp | 96 +- src/Mod/Surface/Gui/TaskSections.cpp | 99 +- src/Mod/Surface/SurfaceGlobal.h | 30 +- src/Mod/Test/Gui/AppTestGui.cpp | 46 +- src/Mod/Test/Gui/UnitTestImp.cpp | 46 +- src/Mod/Test/Gui/UnitTestPy.cpp | 7 +- src/Mod/Web/App/AppWeb.cpp | 30 +- src/Mod/Web/WebGlobal.h | 30 +- src/Tools/ThumbnailProvider/Common.h | 26 +- src/Tools/ThumbnailProvider/FCConfig.h | 152 +- src/Tools/ThumbnailProvider/Main.cpp | 17 +- .../ThumbnailProvider/ThumbnailProvider.cpp | 12 +- src/Tools/_TEMPLATE_/App/PreCompiled.h | 4 +- src/Tools/_TEMPLATE_/Gui/PreCompiled.h | 10 +- src/Tools/_TEMPLATE_/_TEMPLATE_Global.h | 30 +- src/Tools/embedded/Qt/cxx/PreCompiled.h | 16 +- src/Tools/embedded/Qt/mainwindow.cpp | 2 +- .../Win32/FreeCAD_widget/FreeCAD_widget.cpp | 24 +- .../embedded/Win32/FreeCAD_widget/resource.h | 14 +- .../embedded/Win32/FreeCAD_widget/targetver.h | 16 +- src/Tools/embedded/glib/main.c | 38 +- src/Tools/plugins/widget/customwidgets.cpp | 29 +- src/Tools/plugins/widget/plugin.cpp | 844 ++-- src/Tools/plugins/widget/wizard.cpp | 3 +- src/Tools/xmlformat/main.cpp | 20 +- tests/src/App/ApplicationDirectories.cpp | 88 +- tests/src/App/BackupPolicy.cpp | 89 +- tests/src/App/DocumentObserver.cpp | 35 +- tests/src/App/ElementMap.cpp | 95 +- tests/src/App/ElementNamingUtils.cpp | 14 +- tests/src/App/IndexedName.cpp | 20 +- tests/src/App/License.cpp | 8 +- tests/src/App/MappedElement.cpp | 11 +- tests/src/App/MappedName.cpp | 31 +- tests/src/App/Property.cpp | 24 +- tests/src/App/Property.h | 3 +- tests/src/App/StringHasher.cpp | 18 +- tests/src/App/VarSet.cpp | 3 +- tests/src/Base/Base64.cpp | 21 +- tests/src/Base/BoundBox.cpp | 26 +- tests/src/Base/Reader.cpp | 17 +- tests/src/Base/SchemaTests.cpp | 27 +- tests/src/Base/Stream.cpp | 2 +- tests/src/Base/UnlimitedUnsigned.cpp | 16 +- tests/src/Base/Vector3D.cpp | 8 +- tests/src/Gui/InputHintTest.cpp | 9 +- .../StyleParameters/ParameterManagerTest.cpp | 18 +- tests/src/Gui/StyleParameters/ParserTest.cpp | 36 +- .../StyleParametersApplicationTest.cpp | 3 +- .../Material/App/TestMaterialProperties.cpp | 92 +- tests/src/Mod/Material/App/TestMaterials.cpp | 2 +- tests/src/Mod/Mesh/App/Core/KDTree.cpp | 6 +- tests/src/Mod/Part/App/Attacher.cpp | 24 +- tests/src/Mod/Part/App/FeatureChamfer.cpp | 23 +- tests/src/Mod/Part/App/FeatureExtrusion.cpp | 68 +- tests/src/Mod/Part/App/FeatureFillet.cpp | 21 +- tests/src/Mod/Part/App/FeatureMirroring.cpp | 127 +- tests/src/Mod/Part/App/FeaturePartCommon.cpp | 34 +- tests/src/Mod/Part/App/FeaturePartFuse.cpp | 4 +- tests/src/Mod/Part/App/FeatureRevolution.cpp | 6 +- tests/src/Mod/Part/App/FuzzyBoolean.cpp | 20 +- tests/src/Mod/Part/App/Geometry.cpp | 44 +- tests/src/Mod/Part/App/PartFeature.cpp | 32 +- tests/src/Mod/Part/App/PartTestHelpers.cpp | 76 +- tests/src/Mod/Part/App/PartTestHelpers.h | 33 +- tests/src/Mod/Part/App/PropertyTopoShape.cpp | 4 +- tests/src/Mod/Part/App/TopoShapeCache.cpp | 3 +- tests/src/Mod/Part/App/TopoShapeExpansion.cpp | 2435 ++++++------ tests/src/Mod/Part/App/TopoShapeMakeShape.cpp | 67 +- .../App/TopoShapeMakeShapeWithElementMap.cpp | 119 +- tests/src/Mod/Part/App/WireJoiner.cpp | 23 +- .../PartDesign/App/BackwardCompatibility.cpp | 18 +- tests/src/Mod/PartDesign/App/ShapeBinder.cpp | 3 +- tests/src/Mod/Sketcher/App/Constraint.cpp | 252 +- tests/src/Mod/Sketcher/App/SketchObject.cpp | 196 +- .../Mod/Sketcher/App/SketchObjectChanges.cpp | 34 +- .../Mod/Sketcher/App/SketcherTestHelpers.cpp | 33 +- .../Mod/Sketcher/App/SketcherTestHelpers.h | 8 +- .../Mod/Sketcher/App/planegcs/Constraints.cpp | 77 +- .../src/Mod/Spreadsheet/App/PropertySheet.cpp | 17 +- tests/src/Mod/Start/App/FileUtilities.cpp | 14 +- tests/src/zipios++/collectioncollection.cpp | 12 +- tests/src/zipios++/zipfile.cpp | 24 +- 2390 files changed, 154630 insertions(+), 115818 deletions(-) diff --git a/.github/problemMatcher/msvc.json b/.github/problemMatcher/msvc.json index 17d984da6d..0bc787a8b6 100644 --- a/.github/problemMatcher/msvc.json +++ b/.github/problemMatcher/msvc.json @@ -6,8 +6,7 @@ "owner": "msvc-problem-matcher", "pattern": [ { - "regexp": - "^(?:\\s+\\d+\\>)?([^\\s].*)\\((\\d+),?(\\d+)?(?:,\\d+,\\d+)?\\)\\s*:\\s+(error|warning|info)\\s+(\\w{1,2}\\d+)\\s*:\\s*(.*)$", + "regexp": "^(?:\\s+\\d+\\>)?([^\\s].*)\\((\\d+),?(\\d+)?(?:,\\d+,\\d+)?\\)\\s*:\\s+(error|warning|info)\\s+(\\w{1,2}\\d+)\\s*:\\s*(.*)$", "file": 1, "line": 2, "column": 3, diff --git a/src/Base/AxisPyImp.cpp b/src/Base/AxisPyImp.cpp index a71894b3bd..3979001ec0 100644 --- a/src/Base/AxisPyImp.cpp +++ b/src/Base/AxisPyImp.cpp @@ -72,8 +72,7 @@ int AxisPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyObject* d {}; if (PyArg_ParseTuple(args, "O!O!", &(VectorPy::Type), &o, &(VectorPy::Type), &d)) { // NOTE: The first parameter defines the base (origin) and the second the direction. - *getAxisPtr() = - Axis(static_cast(o)->value(), static_cast(d)->value()); + *getAxisPtr() = Axis(static_cast(o)->value(), static_cast(d)->value()); return 0; } diff --git a/src/Base/Base64.cpp b/src/Base/Base64.cpp index af4dbe3514..8240c5716b 100644 --- a/src/Base/Base64.cpp +++ b/src/Base/Base64.cpp @@ -113,8 +113,7 @@ std::size_t Base::base64_encode(char* out, void const* in, std::size_t in_len) return ret - out; } -std::pair -Base::base64_decode(void* _out, char const* in, std::size_t in_len) +std::pair Base::base64_decode(void* _out, char const* in, std::size_t in_len) { auto* out = reinterpret_cast(_out); // NOLINT unsigned char* ret = out; diff --git a/src/Base/Base64.h b/src/Base/Base64.h index 812c5c2b15..6153fe5064 100644 --- a/src/Base/Base64.h +++ b/src/Base/Base64.h @@ -85,8 +85,7 @@ BaseExport std::array base64_decode_ta * @return Return a pair of output size and input read size. Compare the * read size to input size to check for error. */ -BaseExport std::pair -base64_decode(void* out, char const*, std::size_t len); +BaseExport std::pair base64_decode(void* out, char const*, std::size_t len); /** Encode input binary into base64 string * @param out: output string. Note that the string is not cleared before diff --git a/src/Base/Base64Filter.h b/src/Base/Base64Filter.h index a254e1d88d..306630ce68 100644 --- a/src/Base/Base64Filter.h +++ b/src/Base/Base64Filter.h @@ -59,9 +59,7 @@ struct base64_encoder { using char_type = char; - struct category: bio::multichar_output_filter_tag, - bio::closable_tag, - bio::optimally_buffered_tag + struct category: bio::multichar_output_filter_tag, bio::closable_tag, bio::optimally_buffered_tag { }; @@ -77,7 +75,8 @@ struct base64_encoder { static constexpr int defaultBufferSize {1024}; return static_cast( - base64_encode_size(line_size != 0U ? line_size : defaultBufferSize)); + base64_encode_size(line_size != 0U ? line_size : defaultBufferSize) + ); } template @@ -174,7 +173,8 @@ struct base64_decoder { static constexpr int defaultBufferSize {1024}; return static_cast( - base64_encode_size(line_size != 0U ? line_size : defaultBufferSize)); + base64_encode_size(line_size != 0U ? line_size : defaultBufferSize) + ); } template @@ -226,12 +226,15 @@ struct base64_decoder } if (pending_in == 4) { pending_out = pending_in = 0; - char_array_3[0] = - static_cast((char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4)); - char_array_3[1] = static_cast(((char_array_4[1] & 0xf) << 4) - + ((char_array_4[2] & 0x3c) >> 2)); - char_array_3[2] = - static_cast(((char_array_4[2] & 0x3) << 6) + char_array_4[3]); + char_array_3[0] = static_cast( + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4) + ); + char_array_3[1] = static_cast( + ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2) + ); + char_array_3[2] = static_cast( + ((char_array_4[2] & 0x3) << 6) + char_array_4[3] + ); break; } } @@ -256,8 +259,10 @@ struct base64_decoder * @return A unique pointer to an output stream that can transforms the * input binary data to base64 strings. */ -inline std::unique_ptr -create_base64_encoder(std::ostream& out, std::size_t line_size = base64DefaultBufferSize) +inline std::unique_ptr create_base64_encoder( + std::ostream& out, + std::size_t line_size = base64DefaultBufferSize +) { std::unique_ptr res(new bio::filtering_ostream); auto* filteringStream = dynamic_cast(res.get()); @@ -274,8 +279,10 @@ create_base64_encoder(std::ostream& out, std::size_t line_size = base64DefaultBu * @return A unique pointer to an output stream that can transforms the * input binary data to base64 strings. */ -inline std::unique_ptr -create_base64_encoder(const std::string& filepath, std::size_t line_size = base64DefaultBufferSize) +inline std::unique_ptr create_base64_encoder( + const std::string& filepath, + std::size_t line_size = base64DefaultBufferSize +) { std::unique_ptr res(new bio::filtering_ostream); auto* filteringStream = dynamic_cast(res.get()); @@ -294,10 +301,11 @@ create_base64_encoder(const std::string& filepath, std::size_t line_size = base6 * @return A unique pointer to an input stream that read from the given * upstream and transform the read base64 strings into binary data. */ -inline std::unique_ptr -create_base64_decoder(std::istream& in, - std::size_t line_size = base64DefaultBufferSize, - Base64ErrorHandling errHandling = Base64ErrorHandling::silent) +inline std::unique_ptr create_base64_decoder( + std::istream& in, + std::size_t line_size = base64DefaultBufferSize, + Base64ErrorHandling errHandling = Base64ErrorHandling::silent +) { std::unique_ptr res(new bio::filtering_istream); auto* filteringStream = dynamic_cast(res.get()); @@ -320,10 +328,11 @@ create_base64_decoder(std::istream& in, * @return A unique pointer to an input stream that read from the given * file and transform the read base64 strings into binary data. */ -inline std::unique_ptr -create_base64_decoder(const std::string& filepath, - std::size_t line_size = base64DefaultBufferSize, - Base64ErrorHandling errHandling = Base64ErrorHandling::silent) +inline std::unique_ptr create_base64_decoder( + const std::string& filepath, + std::size_t line_size = base64DefaultBufferSize, + Base64ErrorHandling errHandling = Base64ErrorHandling::silent +) { std::unique_ptr res(new bio::filtering_istream); auto* filteringStream = dynamic_cast(res.get()); diff --git a/src/Base/BaseClass.cpp b/src/Base/BaseClass.cpp index 2c85d3effe..0c05b6005f 100644 --- a/src/Base/BaseClass.cpp +++ b/src/Base/BaseClass.cpp @@ -74,10 +74,12 @@ Type BaseClass::getTypeId() const } -void BaseClass::initSubclass(Base::Type& toInit, - const char* ClassName, - const char* ParentName, - Type::instantiationMethod method) +void BaseClass::initSubclass( + Base::Type& toInit, + const char* ClassName, + const char* ParentName, + Type::instantiationMethod method +) { // don't init twice! assert(toInit.isBad()); diff --git a/src/Base/BaseClass.h b/src/Base/BaseClass.h index f3f0602f12..3ba1d92a0e 100644 --- a/src/Base/BaseClass.h +++ b/src/Base/BaseClass.h @@ -34,103 +34,103 @@ using PyObject = struct _object; // NOLINTBEGIN(cppcoreguidelines-macro-usage) /// define for subclassing Base::BaseClass -#define TYPESYSTEM_HEADER() \ -public: \ - static Base::Type getClassTypeId(void); \ - virtual Base::Type getTypeId(void) const; \ - static void init(void); \ - static void* create(void); \ - \ -private: \ +#define TYPESYSTEM_HEADER() \ +public: \ + static Base::Type getClassTypeId(void); \ + virtual Base::Type getTypeId(void) const; \ + static void init(void); \ + static void* create(void); \ +\ +private: \ static Base::Type classTypeId /// Like TYPESYSTEM_HEADER, but declare getTypeId as 'override' -#define TYPESYSTEM_HEADER_WITH_OVERRIDE() \ -public: \ - static Base::Type getClassTypeId(void); \ - Base::Type getTypeId(void) const override; \ - static void init(void); \ - static void* create(void); \ - \ -private: \ +#define TYPESYSTEM_HEADER_WITH_OVERRIDE() \ +public: \ + static Base::Type getClassTypeId(void); \ + Base::Type getTypeId(void) const override; \ + static void init(void); \ + static void* create(void); \ +\ +private: \ static Base::Type classTypeId /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_P(_class_) \ - Base::Type _class_::getClassTypeId(void) \ - { \ - return _class_::classTypeId; \ - } \ - Base::Type _class_::getTypeId(void) const \ - { \ - return _class_::classTypeId; \ - } \ - Base::Type _class_::classTypeId = Base::Type::BadType; \ - void* _class_::create(void) \ - { \ - return new _class_(); \ +#define TYPESYSTEM_SOURCE_P(_class_) \ + Base::Type _class_::getClassTypeId(void) \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::getTypeId(void) const \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::classTypeId = Base::Type::BadType; \ + void* _class_::create(void) \ + { \ + return new _class_(); \ } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ - template<> \ - Base::Type _class_::getClassTypeId(void) \ - { \ - return _class_::classTypeId; \ - } \ - template<> \ - Base::Type _class_::getTypeId(void) const \ - { \ - return _class_::classTypeId; \ - } \ - template<> \ - void* _class_::create(void) \ - { \ - return new _class_(); \ +#define TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ + template<> \ + Base::Type _class_::getClassTypeId(void) \ + { \ + return _class_::classTypeId; \ + } \ + template<> \ + Base::Type _class_::getTypeId(void) const \ + { \ + return _class_::classTypeId; \ + } \ + template<> \ + void* _class_::create(void) \ + { \ + return new _class_(); \ } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ - Base::Type _class_::getClassTypeId(void) \ - { \ - return _class_::classTypeId; \ - } \ - Base::Type _class_::getTypeId(void) const \ - { \ - return _class_::classTypeId; \ - } \ - Base::Type _class_::classTypeId = Base::Type::BadType; \ - void* _class_::create(void) \ - { \ - return nullptr; \ +#define TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ + Base::Type _class_::getClassTypeId(void) \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::getTypeId(void) const \ + { \ + return _class_::classTypeId; \ + } \ + Base::Type _class_::classTypeId = Base::Type::BadType; \ + void* _class_::create(void) \ + { \ + return nullptr; \ } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE(_class_, _parentclass_) \ - TYPESYSTEM_SOURCE_P(_class_) \ - void _class_::init(void) \ - { \ - initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ +#define TYPESYSTEM_SOURCE(_class_, _parentclass_) \ + TYPESYSTEM_SOURCE_P(_class_) \ + void _class_::init(void) \ + { \ + initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_TEMPLATE_T(_class_, _parentclass_) \ - TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ - template<> \ - void _class_::init(void) \ - { \ - initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ +#define TYPESYSTEM_SOURCE_TEMPLATE_T(_class_, _parentclass_) \ + TYPESYSTEM_SOURCE_TEMPLATE_P(_class_) \ + template<> \ + void _class_::init(void) \ + { \ + initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ } /// define to implement a subclass of Base::BaseClass -#define TYPESYSTEM_SOURCE_ABSTRACT(_class_, _parentclass_) \ - TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ - void _class_::init(void) \ - { \ - initSubclass(_class_::classTypeId, #_class_, #_parentclass_, nullptr); \ +#define TYPESYSTEM_SOURCE_ABSTRACT(_class_, _parentclass_) \ + TYPESYSTEM_SOURCE_ABSTRACT_P(_class_) \ + void _class_::init(void) \ + { \ + initSubclass(_class_::classTypeId, #_class_, #_parentclass_, nullptr); \ } // NOLINTEND(cppcoreguidelines-macro-usage) @@ -167,10 +167,12 @@ private: static Type classTypeId; // NOLINT protected: - static void initSubclass(Base::Type& toInit, - const char* ClassName, - const char* ParentName, - Type::instantiationMethod method = nullptr); + static void initSubclass( + Base::Type& toInit, + const char* ClassName, + const char* ParentName, + Type::instantiationMethod method = nullptr + ); public: /// Construction diff --git a/src/Base/BoundBox.h b/src/Base/BoundBox.h index 1be222b428..1da2c8ebfb 100644 --- a/src/Base/BoundBox.h +++ b/src/Base/BoundBox.h @@ -61,12 +61,14 @@ public: //@} /** Builds box from pairs of x,y,z values. */ - inline explicit BoundBox3(Precision fMinX = std::numeric_limits::max(), - Precision fMinY = std::numeric_limits::max(), - Precision fMinZ = std::numeric_limits::max(), - Precision fMaxX = -std::numeric_limits::max(), - Precision fMaxY = -std::numeric_limits::max(), - Precision fMaxZ = -std::numeric_limits::max()); + inline explicit BoundBox3( + Precision fMinX = std::numeric_limits::max(), + Precision fMinY = std::numeric_limits::max(), + Precision fMinZ = std::numeric_limits::max(), + Precision fMaxX = -std::numeric_limits::max(), + Precision fMaxY = -std::numeric_limits::max(), + Precision fMaxZ = -std::numeric_limits::max() + ); BoundBox3(const BoundBox3& rcBB) = default; BoundBox3(BoundBox3&& rcBB) noexcept = default; /** Builds box from an array of points. */ @@ -178,8 +180,7 @@ public: */ inline Vector3 CalcPoint(unsigned short usPoint) const; /** Returns the plane of the given side. */ - void - CalcPlane(unsigned short usPlane, Vector3& rBase, Vector3& rNormal) const; + void CalcPlane(unsigned short usPlane, Vector3& rBase, Vector3& rNormal) const; /** Calculates the two points of an edge. */ bool CalcEdge(unsigned short usEdge, Vector3& rcP0, Vector3& rcP1) const; @@ -187,36 +188,47 @@ public: * the base \a rcVct and the direction \a rcVctDir. \a rcVct must lie inside the * bounding box. */ - bool IntersectionPoint(const Vector3& rcVct, - const Vector3& rcVctDir, - Vector3& cVctRes, - Precision epsilon) const; + bool IntersectionPoint( + const Vector3& rcVct, + const Vector3& rcVctDir, + Vector3& cVctRes, + Precision epsilon + ) const; /** Checks for intersection with line incl. search tolerance. */ - bool IsCutLine(const Vector3& rcBase, - const Vector3& rcDir, - Precision fTolerance = 0.0F) const; + bool IsCutLine( + const Vector3& rcBase, + const Vector3& rcDir, + Precision fTolerance = 0.0F + ) const; /** Checks if this plane specified by (point,normal) cuts this box. * @note It's up to the client programmer to make sure that this bounding box is valid. */ - inline bool IsCutPlane(const Vector3& rclBase, - const Vector3& rclNormal) const; + inline bool IsCutPlane(const Vector3& rclBase, const Vector3& rclNormal) const; /** Computes the intersection points of line and bounding box. */ - bool IntersectWithLine(const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0, - Vector3& rcP1) const; + bool IntersectWithLine( + const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0, + Vector3& rcP1 + ) const; /** Computes the intersection point of line and a plane of the bounding box. */ - bool IntersectPlaneWithLine(unsigned short usSide, - const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0) const; + bool IntersectPlaneWithLine( + unsigned short usSide, + const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0 + ) const; /** Returns the side of the bounding box the ray exits. */ - typename BoundBox3::SIDE GetSideFromRay(const Vector3& rclPt, - const Vector3& rclDir) const; + typename BoundBox3::SIDE GetSideFromRay( + const Vector3& rclPt, + const Vector3& rclDir + ) const; /** Returns the side of the bounding box the ray exits. */ - typename BoundBox3::SIDE GetSideFromRay(const Vector3& rclPt, - const Vector3& rclDir, - Vector3& rcInt) const; + typename BoundBox3::SIDE GetSideFromRay( + const Vector3& rclPt, + const Vector3& rclDir, + Vector3& rcInt + ) const; /** * Searches for the closest point of the bounding box. @@ -288,12 +300,14 @@ bool BoundBox3::isOnRayS(Precision min, Precision max, Precision val) // NOLINTBEGIN(bugprone-easily-swappable-parameters) template -inline BoundBox3::BoundBox3(Precision fMinX, - Precision fMinY, - Precision fMinZ, - Precision fMaxX, - Precision fMaxY, - Precision fMaxZ) +inline BoundBox3::BoundBox3( + Precision fMinX, + Precision fMinY, + Precision fMinZ, + Precision fMaxX, + Precision fMaxY, + Precision fMaxZ +) : MinX(fMinX) , MinY(fMinY) , MinZ(fMinZ) @@ -377,8 +391,7 @@ inline bool BoundBox3::operator&&(const BoundBox2d& rcBB) const } template -inline BoundBox3 -BoundBox3::Intersected(const BoundBox3& rcBB) const +inline BoundBox3 BoundBox3::Intersected(const BoundBox3& rcBB) const { BoundBox3 cBBRes; @@ -478,8 +491,10 @@ inline bool BoundBox3::IsValid() const } template -inline bool BoundBox3::GetOctantFromVector(const Vector3& rclVct, - OCTANT& rclOctant) const +inline bool BoundBox3::GetOctantFromVector( + const Vector3& rclVct, + OCTANT& rclOctant +) const { if (!IsInBox(rclVct)) { return false; @@ -500,8 +515,9 @@ inline bool BoundBox3::GetOctantFromVector(const Vector3& } template -inline BoundBox3 -BoundBox3::CalcOctant(typename BoundBox3::OCTANT Octant) const +inline BoundBox3 BoundBox3::CalcOctant( + typename BoundBox3::OCTANT Octant +) const { BoundBox3 cOct(*this); @@ -584,9 +600,11 @@ inline Vector3 BoundBox3::CalcPoint(unsigned short usPoint // NOLINTBEGIN(bugprone-easily-swappable-parameters) template -inline void BoundBox3::CalcPlane(unsigned short usPlane, - Vector3& rBase, - Vector3& rNormal) const +inline void BoundBox3::CalcPlane( + unsigned short usPlane, + Vector3& rBase, + Vector3& rNormal +) const // NOLINTEND(bugprone-easily-swappable-parameters) { switch (usPlane) { @@ -625,9 +643,11 @@ inline void BoundBox3::CalcPlane(unsigned short usPlane, } template -inline bool BoundBox3::CalcEdge(unsigned short usEdge, - Vector3& rcP0, - Vector3& rcP1) const +inline bool BoundBox3::CalcEdge( + unsigned short usEdge, + Vector3& rcP0, + Vector3& rcP1 +) const { switch (usEdge) { case TLB_TLF: @@ -686,10 +706,12 @@ inline bool BoundBox3::CalcEdge(unsigned short usEdge, } template -inline bool BoundBox3::IntersectionPoint(const Vector3& rcVct, - const Vector3& rcVctDir, - Vector3& cVctRes, - Precision epsilon) const +inline bool BoundBox3::IntersectionPoint( + const Vector3& rcVct, + const Vector3& rcVctDir, + Vector3& cVctRes, + Precision epsilon +) const { const unsigned short num = 6; bool rc = false; @@ -721,9 +743,11 @@ inline bool BoundBox3::IntersectionPoint(const Vector3& rc } template -inline bool BoundBox3::IsCutLine(const Vector3& rcBase, - const Vector3& rcDir, - Precision fTolerance) const +inline bool BoundBox3::IsCutLine( + const Vector3& rcBase, + const Vector3& rcDir, + Precision fTolerance +) const { const unsigned short num = 6; Precision fDist; @@ -777,8 +801,10 @@ inline bool BoundBox3::IsCutLine(const Vector3& rcBase, } template -inline bool BoundBox3::IsCutPlane(const Vector3& rclBase, - const Vector3& rclNormal) const +inline bool BoundBox3::IsCutPlane( + const Vector3& rclBase, + const Vector3& rclNormal +) const { const unsigned short num = 8; if (fabs(GetCenter().DistanceToPlane(rclBase, rclNormal)) < CalcDiagonalLength()) { @@ -794,10 +820,12 @@ inline bool BoundBox3::IsCutPlane(const Vector3& rclBase, // NOLINTBEGIN(bugprone-easily-swappable-parameters) template -inline bool BoundBox3::IntersectWithLine(const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0, - Vector3& rcP1) const +inline bool BoundBox3::IntersectWithLine( + const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0, + Vector3& rcP1 +) const // NOLINTEND(bugprone-easily-swappable-parameters) { const unsigned short num = 6; @@ -819,18 +847,24 @@ inline bool BoundBox3::IntersectWithLine(const Vector3& rc switch (i) { case LEFT: // left and right plane case RIGHT: - checkIntersect(Vector3 {MinY, MaxY, clVectRes.y}, - Vector3 {MinZ, MaxZ, clVectRes.z}); + checkIntersect( + Vector3 {MinY, MaxY, clVectRes.y}, + Vector3 {MinZ, MaxZ, clVectRes.z} + ); break; case TOP: // top and bottom plane case BOTTOM: - checkIntersect(Vector3 {MinX, MaxX, clVectRes.x}, - Vector3 {MinZ, MaxZ, clVectRes.z}); + checkIntersect( + Vector3 {MinX, MaxX, clVectRes.x}, + Vector3 {MinZ, MaxZ, clVectRes.z} + ); break; case FRONT: // front and back plane case BACK: - checkIntersect(Vector3 {MinX, MaxX, clVectRes.x}, - Vector3 {MinY, MaxY, clVectRes.y}); + checkIntersect( + Vector3 {MinX, MaxX, clVectRes.x}, + Vector3 {MinY, MaxY, clVectRes.y} + ); break; } } @@ -857,10 +891,12 @@ inline bool BoundBox3::IntersectWithLine(const Vector3& rc // NOLINTBEGIN(bugprone-easily-swappable-parameters) template -inline bool BoundBox3::IntersectPlaneWithLine(unsigned short usSide, - const Vector3& rcBase, - const Vector3& rcDir, - Vector3& rcP0) const +inline bool BoundBox3::IntersectPlaneWithLine( + unsigned short usSide, + const Vector3& rcBase, + const Vector3& rcDir, + Vector3& rcP0 +) const // NOLINTEND(bugprone-easily-swappable-parameters) { Precision value; @@ -880,19 +916,21 @@ inline bool BoundBox3::IntersectPlaneWithLine(unsigned short usSide, } template -inline typename BoundBox3::SIDE -BoundBox3::GetSideFromRay(const Vector3& rclPt, - const Vector3& rclDir) const +inline typename BoundBox3::SIDE BoundBox3::GetSideFromRay( + const Vector3& rclPt, + const Vector3& rclDir +) const { Vector3 cIntersection; return GetSideFromRay(rclPt, rclDir, cIntersection); } template -inline typename BoundBox3::SIDE -BoundBox3::GetSideFromRay(const Vector3& rclPt, - const Vector3& rclDir, - Vector3& rcInt) const +inline typename BoundBox3::SIDE BoundBox3::GetSideFromRay( + const Vector3& rclPt, + const Vector3& rclDir, + Vector3& rcInt +) const { Vector3 cP0; Vector3 cP1; @@ -1027,9 +1065,10 @@ inline Vector3 BoundBox3::GetMaximum() const template inline Precision BoundBox3::CalcDiagonalLength() const { - return static_cast(sqrt(((MaxX - MinX) * (MaxX - MinX)) - + ((MaxY - MinY) * (MaxY - MinY)) - + ((MaxZ - MinZ) * (MaxZ - MinZ)))); + return static_cast(sqrt( + ((MaxX - MinX) * (MaxX - MinX)) + ((MaxY - MinY) * (MaxY - MinY)) + + ((MaxZ - MinZ) * (MaxZ - MinZ)) + )); } template diff --git a/src/Base/BoundBoxPyImp.cpp b/src/Base/BoundBoxPyImp.cpp index 156eadec03..887988de09 100644 --- a/src/Base/BoundBoxPyImp.cpp +++ b/src/Base/BoundBoxPyImp.cpp @@ -103,9 +103,11 @@ int BoundBoxPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, - "Either six floats, two instances of " - "Vector/Tuple or instance of BoundBox expected"); + PyErr_SetString( + PyExc_TypeError, + "Either six floats, two instances of " + "Vector/Tuple or instance of BoundBox expected" + ); return -1; } @@ -152,16 +154,20 @@ PyObject* BoundBoxPy::add(PyObject* args) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "O!;Need a Vector, BoundBox or three floats as argument", - &(BoundBoxPy::Type), - &object)) { + if (PyArg_ParseTuple( + args, + "O!;Need a Vector, BoundBox or three floats as argument", + &(BoundBoxPy::Type), + &object + )) { getBoundBoxPtr()->Add(*(static_cast(object)->getBoundBoxPtr())); Py_Return; } - PyErr_SetString(PyExc_TypeError, - "Either three floats, instance of Vector or instance of BoundBox expected"); + PyErr_SetString( + PyExc_TypeError, + "Either three floats, instance of Vector or instance of BoundBox expected" + ); return nullptr; } @@ -248,15 +254,11 @@ PyObject* BoundBoxPy::intersect(PyObject* args) } do { - if (PyArg_ParseTuple(args, - "O!O!", - &(VectorPy::Type), - &object1, - &(VectorPy::Type), - &object2)) { - retVal = - getBoundBoxPtr()->IsCutLine(*(static_cast(object1)->getVectorPtr()), - *(static_cast(object2)->getVectorPtr())); + if (PyArg_ParseTuple(args, "O!O!", &(VectorPy::Type), &object1, &(VectorPy::Type), &object2)) { + retVal = getBoundBoxPtr()->IsCutLine( + *(static_cast(object1)->getVectorPtr()), + *(static_cast(object2)->getVectorPtr()) + ); break; } @@ -266,8 +268,9 @@ PyObject* BoundBoxPy::intersect(PyObject* args) PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } - retVal = - getBoundBoxPtr()->Intersect(*(static_cast(object1)->getBoundBoxPtr())); + retVal = getBoundBoxPtr()->Intersect( + *(static_cast(object1)->getBoundBoxPtr()) + ); break; } @@ -294,8 +297,9 @@ PyObject* BoundBoxPy::intersected(PyObject* args) return nullptr; } - BoundBox3d bbox = - getBoundBoxPtr()->Intersected(*static_cast(object)->getBoundBoxPtr()); + BoundBox3d bbox = getBoundBoxPtr()->Intersected( + *static_cast(object)->getBoundBoxPtr() + ); return new BoundBoxPy(new BoundBox3d(bbox)); } @@ -334,22 +338,25 @@ PyObject* BoundBoxPy::getIntersectionPoint(PyObject* args) PyObject* object1 {}; PyObject* object2 {}; double epsilon = 0.0001; - if (!PyArg_ParseTuple(args, - "O!O!|d;Need base and direction vector", - &(VectorPy::Type), - &object1, - &(VectorPy::Type), - &object2, - &epsilon)) { + if (!PyArg_ParseTuple( + args, + "O!O!|d;Need base and direction vector", + &(VectorPy::Type), + &object1, + &(VectorPy::Type), + &object2, + &epsilon + )) { return nullptr; } Vector3d point; - bool ok = - getBoundBoxPtr()->IntersectionPoint(*(static_cast(object1)->getVectorPtr()), - *(static_cast(object2)->getVectorPtr()), - point, - epsilon); + bool ok = getBoundBoxPtr()->IntersectionPoint( + *(static_cast(object1)->getVectorPtr()), + *(static_cast(object2)->getVectorPtr()), + point, + epsilon + ); if (ok) { return new VectorPy(point); } @@ -460,17 +467,21 @@ PyObject* BoundBoxPy::isCutPlane(PyObject* args) return nullptr; } - if (!PyArg_ParseTuple(args, - "O!O!;Need base and normal vector of a plane", - &(VectorPy::Type), - &object, - &(VectorPy::Type), - &object2)) { + if (!PyArg_ParseTuple( + args, + "O!O!;Need base and normal vector of a plane", + &(VectorPy::Type), + &object, + &(VectorPy::Type), + &object2 + )) { return nullptr; } - retVal = getBoundBoxPtr()->IsCutPlane(*(static_cast(object)->getVectorPtr()), - *(static_cast(object2)->getVectorPtr())); + retVal = getBoundBoxPtr()->IsCutPlane( + *(static_cast(object)->getVectorPtr()), + *(static_cast(object2)->getVectorPtr()) + ); return Py::new_reference_to(retVal); } @@ -512,8 +523,7 @@ PyObject* BoundBoxPy::isInside(PyObject* args) PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } - retVal = - getBoundBoxPtr()->IsInBox(*(static_cast(object)->getBoundBoxPtr())); + retVal = getBoundBoxPtr()->IsInBox(*(static_cast(object)->getBoundBoxPtr())); break; } diff --git a/src/Base/Builder3D.cpp b/src/Base/Builder3D.cpp index aa42fbf88b..c4d5327ccb 100644 --- a/src/Base/Builder3D.cpp +++ b/src/Base/Builder3D.cpp @@ -248,9 +248,11 @@ public: }; template -void InventorFieldWriter::write(const char* fieldName, - const std::vector& fieldData, - InventorOutput& out) const +void InventorFieldWriter::write( + const char* fieldName, + const std::vector& fieldData, + InventorOutput& out +) const { if (fieldData.empty()) { return; @@ -273,9 +275,11 @@ void InventorFieldWriter::write(const char* fieldName, } template<> -void InventorFieldWriter::write(const char* fieldName, - const std::vector& fieldData, - InventorOutput& out) const +void InventorFieldWriter::write( + const char* fieldName, + const std::vector& fieldData, + InventorOutput& out +) const { if (fieldData.empty()) { return; @@ -472,10 +476,12 @@ void ArrowItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -BoundingBoxItem::BoundingBoxItem(const Vector3f& pt1, - const Vector3f& pt2, - DrawStyle drawStyle, - const ColorRGB& rgb) +BoundingBoxItem::BoundingBoxItem( + const Vector3f& pt1, + const Vector3f& pt2, + DrawStyle drawStyle, + const ColorRGB& rgb +) : pt1 {pt1} , pt2 {pt2} , drawStyle {drawStyle} @@ -871,8 +877,7 @@ void NurbsSurfaceItem::setControlPoints(int numU, int numV) numVControlPoints = numV; } -void NurbsSurfaceItem::setKnotVector(const std::vector& uKnots, - const std::vector& vKnots) +void NurbsSurfaceItem::setKnotVector(const std::vector& uKnots, const std::vector& vKnots) { uKnotVector = uKnots; vKnotVector = vKnots; @@ -1010,11 +1015,13 @@ void Builder3D::saveToLog() { ILogger* obs = Base::Console().get("StatusBar"); if (obs) { - obs->sendLog("Builder3D", - result.str(), - Base::LogStyle::Log, - Base::IntendedRecipient::Developer, - Base::ContentType::Untranslatable); + obs->sendLog( + "Builder3D", + result.str(), + Base::LogStyle::Log, + Base::IntendedRecipient::Developer, + Base::ContentType::Untranslatable + ); } } @@ -1152,8 +1159,9 @@ std::vector> InventorLoader::split(const std::vector -InventorLoader::convert(const std::vector>& coordIndex) const +std::vector InventorLoader::convert( + const std::vector>& coordIndex +) const { std::vector faces; faces.reserve(coordIndex.size()); diff --git a/src/Base/Builder3D.h b/src/Base/Builder3D.h index 8c08ea0462..0323bac366 100644 --- a/src/Base/Builder3D.h +++ b/src/Base/Builder3D.h @@ -33,7 +33,7 @@ #include #include #ifndef FC_GLOBAL_H -#include +# include #endif #include "Placement.h" @@ -167,9 +167,7 @@ public: class BaseExport Triangle { public: - explicit Triangle(const Base::Vector3f& pt1, - const Base::Vector3f& pt2, - const Base::Vector3f& pt3) + explicit Triangle(const Base::Vector3f& pt1, const Base::Vector3f& pt2, const Base::Vector3f& pt3) : pt1(pt1) , pt2(pt2) , pt3(pt3) @@ -297,9 +295,11 @@ private: class BaseExport PointItem: public NodeItem { public: - explicit PointItem(const Base::Vector3f& point, - DrawStyle drawStyle, - const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); + explicit PointItem( + const Base::Vector3f& point, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F} + ); void write(InventorOutput& out) const override; private: @@ -311,9 +311,11 @@ private: class BaseExport LineItem: public NodeItem { public: - explicit LineItem(const Base::Line3f& line, - DrawStyle drawStyle, - const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); + explicit LineItem( + const Base::Line3f& line, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F} + ); void write(InventorOutput& out) const override; private: @@ -327,9 +329,11 @@ class BaseExport MultiLineItem: public NodeItem public: /// add a line defined by a list of points whereat always a pair (i.e. a point and the following /// point) builds a line. - explicit MultiLineItem(std::vector points, - DrawStyle drawStyle, - const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); + explicit MultiLineItem( + std::vector points, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F} + ); void write(InventorOutput& out) const override; private: @@ -341,9 +345,11 @@ private: class BaseExport ArrowItem: public NodeItem { public: - explicit ArrowItem(const Base::Line3f& line, - DrawStyle drawStyle, - const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); + explicit ArrowItem( + const Base::Line3f& line, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F} + ); void write(InventorOutput& out) const override; private: @@ -355,10 +361,12 @@ private: class BaseExport BoundingBoxItem: public NodeItem { public: - explicit BoundingBoxItem(const Vector3f& pt1, - const Vector3f& pt2, - DrawStyle drawStyle, - const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F}); + explicit BoundingBoxItem( + const Vector3f& pt1, + const Vector3f& pt2, + DrawStyle drawStyle, + const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F} + ); void write(InventorOutput& out) const override; private: diff --git a/src/Base/Color.h b/src/Base/Color.h index 18108aa291..7913260ce3 100644 --- a/src/Base/Color.h +++ b/src/Base/Color.h @@ -27,7 +27,7 @@ #define APP_COLOR_H #ifdef __GNUC__ -#include +# include #endif #include #include @@ -165,10 +165,12 @@ public: template static T fromPackedRGBA(uint32_t color) { - return color_traits::makeColor((color >> 24) & 0xff, - (color >> 16) & 0xff, - (color >> 8) & 0xff, - (color & 0xff)); + return color_traits::makeColor( + (color >> 24) & 0xff, + (color >> 16) & 0xff, + (color >> 8) & 0xff, + (color & 0xff) + ); } template @@ -181,9 +183,7 @@ public: template static T fromPackedRGB(uint32_t color) { - return color_traits::makeColor((color >> 24) & 0xff, - (color >> 16) & 0xff, - (color >> 8) & 0xff); + return color_traits::makeColor((color >> 24) & 0xff, (color >> 16) & 0xff, (color >> 8) & 0xff); } /** * creates FC Color from template type, e.g. Qt QColor @@ -308,10 +308,12 @@ struct color_traits } static color_type makeColor(int red, int green, int blue, int alpha = 255) { - return color_type {static_cast(red) / 255.0F, - static_cast(green) / 255.0F, - static_cast(blue) / 255.0F, - static_cast(alpha) / 255.0F}; + return color_type { + static_cast(red) / 255.0F, + static_cast(green) / 255.0F, + static_cast(blue) / 255.0F, + static_cast(alpha) / 255.0F + }; } private: diff --git a/src/Base/Console.cpp b/src/Base/Console.cpp index 7c876bb464..8afc336b0a 100644 --- a/src/Base/Console.cpp +++ b/src/Base/Console.cpp @@ -26,9 +26,9 @@ #include #if defined(FC_OS_WIN32) -#include +# include #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) -#include +# include #endif #include #include @@ -55,11 +55,13 @@ public: std::string notifier; std::string msg; - ConsoleEvent(const ConsoleSingleton::FreeCAD_ConsoleMsgType type, - const IntendedRecipient recipient, - const ContentType content, - const std::string& notifier, - const std::string& msg) + ConsoleEvent( + const ConsoleSingleton::FreeCAD_ConsoleMsgType type, + const IntendedRecipient recipient, + const ContentType content, + const std::string& notifier, + const std::string& msg + ) : QEvent(QEvent::User) // NOLINT , msgtype(type) , recipient(recipient) @@ -90,46 +92,58 @@ public: if (ev->type() == QEvent::User) { switch (const auto ce = static_cast(ev); ce->msgtype) { case ConsoleSingleton::MsgType_Txt: - Console().notifyPrivate(LogStyle::Message, - ce->recipient, - ce->content, - ce->notifier, - ce->msg); + Console().notifyPrivate( + LogStyle::Message, + ce->recipient, + ce->content, + ce->notifier, + ce->msg + ); break; case ConsoleSingleton::MsgType_Log: - Console().notifyPrivate(LogStyle::Log, - ce->recipient, - ce->content, - ce->notifier, - ce->msg); + Console().notifyPrivate( + LogStyle::Log, + ce->recipient, + ce->content, + ce->notifier, + ce->msg + ); break; case ConsoleSingleton::MsgType_Wrn: - Console().notifyPrivate(LogStyle::Warning, - ce->recipient, - ce->content, - ce->notifier, - ce->msg); + Console().notifyPrivate( + LogStyle::Warning, + ce->recipient, + ce->content, + ce->notifier, + ce->msg + ); break; case ConsoleSingleton::MsgType_Err: - Console().notifyPrivate(LogStyle::Error, - ce->recipient, - ce->content, - ce->notifier, - ce->msg); + Console().notifyPrivate( + LogStyle::Error, + ce->recipient, + ce->content, + ce->notifier, + ce->msg + ); break; case ConsoleSingleton::MsgType_Critical: - Console().notifyPrivate(LogStyle::Critical, - ce->recipient, - ce->content, - ce->notifier, - ce->msg); + Console().notifyPrivate( + LogStyle::Critical, + ce->recipient, + ce->content, + ce->notifier, + ce->msg + ); break; case ConsoleSingleton::MsgType_Notification: - Console().notifyPrivate(LogStyle::Notification, - ce->recipient, - ce->content, - ce->notifier, - ce->msg); + Console().notifyPrivate( + LogStyle::Notification, + ce->recipient, + ce->content, + ce->notifier, + ce->msg + ); break; } } @@ -185,9 +199,11 @@ ConsoleSingleton::~ConsoleSingleton() * switches off warnings and error messages and restore the state before the modification. * If the observer \a sObs doesn't exist then nothing happens. */ -ConsoleMsgFlags ConsoleSingleton::setEnabledMsgType(const char* sObs, - const ConsoleMsgFlags type, - const bool on) const +ConsoleMsgFlags ConsoleSingleton::setEnabledMsgType( + const char* sObs, + const ConsoleMsgFlags type, + const bool on +) const { if (ILogger* pObs = get(sObs)) { ConsoleMsgFlags flags = 0; @@ -296,31 +312,39 @@ void ConsoleSingleton::detachObserver(ILogger* pcObserver) _aclObservers.erase(pcObserver); } -void ConsoleSingleton::notifyPrivate(const LogStyle category, - const IntendedRecipient recipient, - const ContentType content, - const std::string& notifiername, - const std::string& msg) const +void ConsoleSingleton::notifyPrivate( + const LogStyle category, + const IntendedRecipient recipient, + const ContentType content, + const std::string& notifiername, + const std::string& msg +) const { for (ILogger* Iter : _aclObservers) { if (Iter->isActive(category)) { - Iter->sendLog(notifiername, - msg, - category, - recipient, - content); // send string to the listener + Iter->sendLog( + notifiername, + msg, + category, + recipient, + content + ); // send string to the listener } } } -void ConsoleSingleton::postEvent(const FreeCAD_ConsoleMsgType type, - const IntendedRecipient recipient, - const ContentType content, - const std::string& notifiername, - const std::string& msg) +void ConsoleSingleton::postEvent( + const FreeCAD_ConsoleMsgType type, + const IntendedRecipient recipient, + const ContentType content, + const std::string& notifiername, + const std::string& msg +) { - QCoreApplication::postEvent(ConsoleOutput::getInstance(), - new ConsoleEvent(type, recipient, content, notifiername, msg)); + QCoreApplication::postEvent( + ConsoleOutput::getInstance(), + new ConsoleEvent(type, recipient, content, notifiername, msg) + ); } ILogger* ConsoleSingleton::get(const char* Name) const @@ -552,35 +576,36 @@ PyObject* ConsoleSingleton::sPyMessage(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - instance() - .send( - notifier, - "%s", - msg); + instance().send( + notifier, + "%s", + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyWarning(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( - [](const std::string& notifier, const char* msg) { - instance().warning(notifier, "%s", msg); - }, - args); + [](const std::string& notifier, const char* msg) { instance().warning(notifier, "%s", msg); }, + args + ); } PyObject* ConsoleSingleton::sPyDeveloperWarning(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - instance() - .send( - notifier, - "%s", - msg); + instance().send( + notifier, + "%s", + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyUserWarning(PyObject* /*self*/, PyObject* args) @@ -590,9 +615,11 @@ PyObject* ConsoleSingleton::sPyUserWarning(PyObject* /*self*/, PyObject* args) instance().send( notifier, "%s", - msg); + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyTranslatedUserWarning(PyObject* /*self*/, PyObject* args) @@ -602,9 +629,11 @@ PyObject* ConsoleSingleton::sPyTranslatedUserWarning(PyObject* /*self*/, PyObjec instance().send( notifier, "%s", - msg); + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyError(PyObject* /*self*/, PyObject* args) @@ -614,22 +643,25 @@ PyObject* ConsoleSingleton::sPyError(PyObject* /*self*/, PyObject* args) instance().send( notifier, "%s", - msg); + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyDeveloperError(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - instance() - .send( - notifier, - "%s", - msg); + instance().send( + notifier, + "%s", + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyUserError(PyObject* /*self*/, PyObject* args) @@ -639,9 +671,11 @@ PyObject* ConsoleSingleton::sPyUserError(PyObject* /*self*/, PyObject* args) instance().send( notifier, "%s", - msg); + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyTranslatedUserError(PyObject* /*self*/, PyObject* args) @@ -651,22 +685,25 @@ PyObject* ConsoleSingleton::sPyTranslatedUserError(PyObject* /*self*/, PyObject* instance().send( notifier, "%s", - msg); + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyLog(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - instance() - .send( - notifier, - "%s", - msg); + instance().send( + notifier, + "%s", + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyCritical(PyObject* /*self*/, PyObject* args) @@ -676,35 +713,39 @@ PyObject* ConsoleSingleton::sPyCritical(PyObject* /*self*/, PyObject* args) instance().send( notifier, "%s", - msg); + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyNotification(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - instance() - .send( - notifier, - "%s", - msg); + instance().send( + notifier, + "%s", + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyTranslatedNotification(PyObject* /*self*/, PyObject* args) { return FC_PYCONSOLE_MSG( [](const std::string& notifier, const char* msg) { - instance() - .send( - notifier, - "%s", - msg); + instance().send( + notifier, + "%s", + msg + ); }, - args); + args + ); } PyObject* ConsoleSingleton::sPyGetStatus(PyObject* /*self*/, PyObject* args) @@ -742,9 +783,11 @@ PyObject* ConsoleSingleton::sPyGetStatus(PyObject* /*self*/, PyObject* args) b = pObs->bNotification; } else { - Py_Error(Base::PyExc_FC_GeneralError, - "Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or " - "'Notification')"); + Py_Error( + Base::PyExc_FC_GeneralError, + "Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or " + "'Notification')" + ); } return PyBool_FromLong(b ? 1 : 0); @@ -784,9 +827,11 @@ PyObject* ConsoleSingleton::sPySetStatus(PyObject* /*self*/, PyObject* args) pObs->bNotification = status; } else { - Py_Error(Base::PyExc_FC_GeneralError, - "Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or " - "'Notification')"); + Py_Error( + Base::PyExc_FC_GeneralError, + "Unknown message type (use 'Log', 'Err', 'Wrn', 'Msg', 'Critical' or " + "'Notification')" + ); } Py_Return; diff --git a/src/Base/Console.h b/src/Base/Console.h index 2f331bb7a1..cb6df0b161 100644 --- a/src/Base/Console.h +++ b/src/Base/Console.h @@ -44,8 +44,8 @@ using PyMethodDef = struct PyMethodDef; // FIXME: Even with parameter packs this is necessary for MSYS2 #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif //************************************************************************** @@ -53,11 +53,11 @@ using PyMethodDef = struct PyMethodDef; #ifdef FC_DEBUG /// switch on the logging of python object creation and destruction -#undef FC_LOGPYOBJECTS +# undef FC_LOGPYOBJECTS /// switch on the logging of Feature update and execution -#define FC_LOGFEATUREUPDATE +# define FC_LOGFEATUREUPDATE /// switch on the logging of the Update execution through Doc, App, GuiApp and GuiDoc -#undef FC_LOGUPDATECHAIN +# undef FC_LOGUPDATECHAIN #endif ///////////////////////////////////////////////////////////////////////////////////// @@ -572,11 +572,13 @@ public: * translated (are untranslatable). Or conversely, may decide not to process already translated * notifications. It is up to the intended behaviour of the observer. */ - virtual void sendLog(const std::string& notifiername, - const std::string& msg, - LogStyle level, - IntendedRecipient recipient, - ContentType content) = 0; + virtual void sendLog( + const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content + ) = 0; /** * Returns whether a LogStyle category is active or not @@ -713,10 +715,7 @@ public: Notification can be direct or via queue. */ - template + template void send(const std::string& notifiername, const char* pMsg, Args&&... args); /// Prints a Message @@ -781,9 +780,7 @@ public: void userTranslatedNotification(const std::string& notifier, const char* pMsg, Args&&... args); // Notify a message directly to observers - template + template void notify(const std::string& notifiername, const std::string& msg); /// Attaches an Observer to FCConsole @@ -877,16 +874,20 @@ public: ConsoleSingleton& operator=(ConsoleSingleton&&) = delete; private: - void postEvent(FreeCAD_ConsoleMsgType type, - IntendedRecipient recipient, - ContentType content, - const std::string& notifiername, - const std::string& msg); - void notifyPrivate(LogStyle category, - IntendedRecipient recipient, - ContentType content, - const std::string& notifiername, - const std::string& msg) const; + void postEvent( + FreeCAD_ConsoleMsgType type, + IntendedRecipient recipient, + ContentType content, + const std::string& notifiername, + const std::string& msg + ); + void notifyPrivate( + LogStyle category, + IntendedRecipient recipient, + ContentType content, + const std::string& notifiername, + const std::string& msg + ) const; // singleton static void Destruct(); @@ -912,13 +913,15 @@ inline ConsoleSingleton& Console() constexpr ConsoleSingleton::FreeCAD_ConsoleMsgType ConsoleSingleton::getConsoleMsg(LogStyle style) { - constexpr std::array msgTypes {// In order of LogStyle - MsgType_Wrn, - MsgType_Txt, - MsgType_Err, - MsgType_Log, - MsgType_Critical, - MsgType_Notification}; + constexpr std::array msgTypes { + // In order of LogStyle + MsgType_Wrn, + MsgType_Txt, + MsgType_Err, + MsgType_Log, + MsgType_Critical, + MsgType_Notification + }; return msgTypes.at(static_cast(style)); } @@ -955,12 +958,14 @@ public: bool add_eol; bool refresh; - LogLevel(const char* tag, - const bool print_tag = true, - const int print_src = 0, - const bool print_time = false, - const bool add_eol = true, - const bool refresh = false) + LogLevel( + const char* tag, + const bool print_tag = true, + const int print_src = 0, + const bool print_time = false, + const bool add_eol = true, + const bool refresh = false + ) : tag(tag) , lvl(*Console().getLogLevel(tag)) , print_tag(print_tag) @@ -1026,36 +1031,37 @@ void Base::ConsoleSingleton::warning(const std::string& notifier, const char* pM } template -void Base::ConsoleSingleton::developerWarning(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::developerWarning(const std::string& notifier, const char* pMsg, Args&&... args) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template -void Base::ConsoleSingleton::userWarning(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::userWarning(const std::string& notifier, const char* pMsg, Args&&... args) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template -void Base::ConsoleSingleton::translatedUserWarning(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::translatedUserWarning( + const std::string& notifier, + const char* pMsg, + Args&&... args +) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template @@ -1071,26 +1077,28 @@ void Base::ConsoleSingleton::error(const std::string& notifier, const char* pMsg } template -void Base::ConsoleSingleton::developerError(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::developerError(const std::string& notifier, const char* pMsg, Args&&... args) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template -void Base::ConsoleSingleton::destructorError(const std::string& notifier, - const char* pMsg, - Args&&... args) noexcept +void Base::ConsoleSingleton::destructorError( + const std::string& notifier, + const char* pMsg, + Args&&... args +) noexcept { try { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } catch (...) { assert("An exception was thrown while attempting console output in a destructor" && false); @@ -1098,25 +1106,27 @@ void Base::ConsoleSingleton::destructorError(const std::string& notifier, } template -void Base::ConsoleSingleton::userError(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::userError(const std::string& notifier, const char* pMsg, Args&&... args) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template -void Base::ConsoleSingleton::translatedUserError(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::translatedUserError( + const std::string& notifier, + const char* pMsg, + Args&&... args +) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template @@ -1138,14 +1148,13 @@ void Base::ConsoleSingleton::userNotification(const char* pMsg, Args&&... args) } template -void Base::ConsoleSingleton::userNotification(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::userNotification(const std::string& notifier, const char* pMsg, Args&&... args) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template @@ -1155,14 +1164,17 @@ void Base::ConsoleSingleton::userTranslatedNotification(const char* pMsg, Args&& } template -void Base::ConsoleSingleton::userTranslatedNotification(const std::string& notifier, - const char* pMsg, - Args&&... args) +void Base::ConsoleSingleton::userTranslatedNotification( + const std::string& notifier, + const char* pMsg, + Args&&... args +) { send( notifier, pMsg, - std::forward(args)...); + std::forward(args)... + ); } template @@ -1177,10 +1189,11 @@ void Base::ConsoleSingleton::log(const std::string& notifier, const char* pMsg, send(notifier, pMsg, std::forward(args)...); } -template +template< + Base::LogStyle category, + Base::IntendedRecipient recipient /*= Base::IntendedRecipient::All*/, + Base::ContentType contenttype /*= Base::ContentType::Untranslated*/, + typename... Args> void Base::ConsoleSingleton::send(const std::string& notifiername, const char* pMsg, Args&&... args) { std::string format; @@ -1206,16 +1219,17 @@ void Base::ConsoleSingleton::send(const std::string& notifiername, const char* p } } -template +template< + Base::LogStyle category, + Base::IntendedRecipient recipient /*= Base::IntendedRecipient::All*/, + Base::ContentType contenttype /*= Base::ContentType::Untranslated*/> void Base::ConsoleSingleton::notify(const std::string& notifiername, const std::string& msg) { notifyPrivate(category, recipient, contenttype, notifiername, msg); } #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif #endif // BASE_CONSOLE_H diff --git a/src/Base/ConsoleObserver.cpp b/src/Base/ConsoleObserver.cpp index 6a09286a59..111e814b0e 100644 --- a/src/Base/ConsoleObserver.cpp +++ b/src/Base/ConsoleObserver.cpp @@ -26,7 +26,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif #include #include @@ -60,11 +60,13 @@ ConsoleObserverFile::~ConsoleObserverFile() cFileStream.close(); } -void ConsoleObserverFile::sendLog(const std::string& notifiername, - const std::string& msg, - LogStyle level, - IntendedRecipient recipient, - ContentType content) +void ConsoleObserverFile::sendLog( + const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content +) { (void)notifiername; @@ -113,11 +115,13 @@ ConsoleObserverStd::ConsoleObserverStd() ConsoleObserverStd::~ConsoleObserverStd() = default; -void ConsoleObserverStd::sendLog(const std::string& notifiername, - const std::string& msg, - LogStyle level, - IntendedRecipient recipient, - ContentType content) +void ConsoleObserverStd::sendLog( + const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content +) { (void)notifiername; @@ -156,8 +160,7 @@ void ConsoleObserverStd::Warning(const char* sWarn) { if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_GREEN | FOREGROUND_BLUE); + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;33m"); #endif @@ -167,8 +170,10 @@ void ConsoleObserverStd::Warning(const char* sWarn) if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); + ::SetConsoleTextAttribute( + ::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + ); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); #endif @@ -179,8 +184,10 @@ void ConsoleObserverStd::Error(const char* sErr) { if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_RED | FOREGROUND_INTENSITY); + ::SetConsoleTextAttribute( + ::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_INTENSITY + ); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;31m"); #endif @@ -190,8 +197,10 @@ void ConsoleObserverStd::Error(const char* sErr) if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); + ::SetConsoleTextAttribute( + ::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + ); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); #endif @@ -202,8 +211,7 @@ void ConsoleObserverStd::Log(const char* sLog) { if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_RED | FOREGROUND_GREEN); + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;36m"); #endif @@ -213,8 +221,10 @@ void ConsoleObserverStd::Log(const char* sLog) if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); + ::SetConsoleTextAttribute( + ::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + ); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); #endif @@ -225,8 +235,7 @@ void ConsoleObserverStd::Critical(const char* sCritical) { if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_GREEN | FOREGROUND_BLUE); + ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[1;33m"); #endif @@ -236,8 +245,10 @@ void ConsoleObserverStd::Critical(const char* sCritical) if (useColorStderr) { #if defined(FC_OS_WIN32) - ::SetConsoleTextAttribute(::GetStdHandle(STD_ERROR_HANDLE), - FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); + ::SetConsoleTextAttribute( + ::GetStdHandle(STD_ERROR_HANDLE), + FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE + ); #elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) fprintf(stderr, "\033[0m"); #endif diff --git a/src/Base/ConsoleObserver.h b/src/Base/ConsoleObserver.h index a0e01f276d..84d2b4df8e 100644 --- a/src/Base/ConsoleObserver.h +++ b/src/Base/ConsoleObserver.h @@ -45,11 +45,13 @@ public: explicit ConsoleObserverFile(const char* sFileName); ~ConsoleObserverFile() override; - void sendLog(const std::string& notifiername, - const std::string& msg, - LogStyle level, - IntendedRecipient recipient, - ContentType content) override; + void sendLog( + const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content + ) override; const char* name() override { return "File"; @@ -72,11 +74,13 @@ class BaseExport ConsoleObserverStd: public ILogger public: ConsoleObserverStd(); ~ConsoleObserverStd() override; - void sendLog(const std::string& notifiername, - const std::string& msg, - LogStyle level, - IntendedRecipient recipient, - ContentType content) override; + void sendLog( + const std::string& notifiername, + const std::string& msg, + LogStyle level, + IntendedRecipient recipient, + ContentType content + ) override; const char* name() override { return "Console"; @@ -105,13 +109,12 @@ class BaseExport ILoggerBlocker public: // Constructor that will block message types passed as parameter. By default, all types are // blocked. - inline explicit ILoggerBlocker(const char* co, - ConsoleMsgFlags msgTypes = ConsoleSingleton::MsgType_Txt - | ConsoleSingleton::MsgType_Log - | ConsoleSingleton::MsgType_Wrn - | ConsoleSingleton::MsgType_Err - | ConsoleSingleton::MsgType_Critical - | ConsoleSingleton::MsgType_Notification); + inline explicit ILoggerBlocker( + const char* co, + ConsoleMsgFlags msgTypes = ConsoleSingleton::MsgType_Txt | ConsoleSingleton::MsgType_Log + | ConsoleSingleton::MsgType_Wrn | ConsoleSingleton::MsgType_Err + | ConsoleSingleton::MsgType_Critical | ConsoleSingleton::MsgType_Notification + ); // Disable copy & move constructors ILoggerBlocker(ILoggerBlocker const&) = delete; ILoggerBlocker(ILoggerBlocker const&&) = delete; @@ -138,8 +141,7 @@ ILoggerBlocker::~ILoggerBlocker() #ifdef FC_DEBUG auto debug = Console().setEnabledMsgType(conObs, msgTypesBlocked, true); if (debug != msgTypesBlocked) { - Console().warning( - "Enabled message types have been changed while ILoggerBlocker was set\n"); + Console().warning("Enabled message types have been changed while ILoggerBlocker was set\n"); } #else Console().setEnabledMsgType(conObs, msgTypesBlocked, true); diff --git a/src/Base/Converter.h b/src/Base/Converter.h index bdc67d0ff5..0e5e798f20 100644 --- a/src/Base/Converter.h +++ b/src/Base/Converter.h @@ -101,9 +101,11 @@ Vec make_vec(const std::tuple&& ft) { using traits_type = vec_traits; using float_traits_type = typename traits_type::float_type; - return Vec(float_traits_type(std::get<0>(ft)), - float_traits_type(std::get<1>(ft)), - float_traits_type(std::get<2>(ft))); + return Vec( + float_traits_type(std::get<0>(ft)), + float_traits_type(std::get<1>(ft)), + float_traits_type(std::get<2>(ft)) + ); } // type with four floats @@ -112,10 +114,12 @@ Vec make_vec(const std::tuple&& { using traits_type = vec_traits; using float_traits_type = typename traits_type::float_type; - return Vec(float_traits_type(std::get<0>(ft)), - float_traits_type(std::get<1>(ft)), - float_traits_type(std::get<2>(ft)), - float_traits_type(std::get<3>(ft))); + return Vec( + float_traits_type(std::get<0>(ft)), + float_traits_type(std::get<1>(ft)), + float_traits_type(std::get<2>(ft)), + float_traits_type(std::get<3>(ft)) + ); } template diff --git a/src/Base/CoordinateSystemPyImp.cpp b/src/Base/CoordinateSystemPyImp.cpp index 17136ffe9f..8b0d2349a3 100644 --- a/src/Base/CoordinateSystemPyImp.cpp +++ b/src/Base/CoordinateSystemPyImp.cpp @@ -41,8 +41,7 @@ std::string CoordinateSystemPy::representation() const return {""}; } -PyObject* -CoordinateSystemPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) +PyObject* CoordinateSystemPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of CoordinateSystemPy and the Twin object return new CoordinateSystemPy(new CoordinateSystem); @@ -59,15 +58,19 @@ PyObject* CoordinateSystemPy::setAxes(PyObject* args) PyObject* axis {}; PyObject* xdir {}; if (PyArg_ParseTuple(args, "O!O!", &(AxisPy::Type), &axis, &(VectorPy::Type), &xdir)) { - getCoordinateSystemPtr()->setAxes(*static_cast(axis)->getAxisPtr(), - *static_cast(xdir)->getVectorPtr()); + getCoordinateSystemPtr()->setAxes( + *static_cast(axis)->getAxisPtr(), + *static_cast(xdir)->getVectorPtr() + ); Py_Return; } PyErr_Clear(); if (PyArg_ParseTuple(args, "O!O!", &(VectorPy::Type), &axis, &(VectorPy::Type), &xdir)) { - getCoordinateSystemPtr()->setAxes(*static_cast(axis)->getVectorPtr(), - *static_cast(xdir)->getVectorPtr()); + getCoordinateSystemPtr()->setAxes( + *static_cast(axis)->getVectorPtr(), + *static_cast(xdir)->getVectorPtr() + ); Py_Return; } @@ -82,7 +85,8 @@ PyObject* CoordinateSystemPy::displacement(PyObject* args) const return nullptr; } Placement plm = getCoordinateSystemPtr()->displacement( - *static_cast(cs)->getCoordinateSystemPtr()); + *static_cast(cs)->getCoordinateSystemPtr() + ); return new PlacementPy(new Placement(plm)); } diff --git a/src/Base/Debugger.h b/src/Base/Debugger.h index fcdb357115..8353c99de2 100644 --- a/src/Base/Debugger.h +++ b/src/Base/Debugger.h @@ -29,7 +29,7 @@ #include #include #ifndef FC_GLOBAL_H -#include +# include #endif namespace Base diff --git a/src/Base/DualQuaternion.cpp b/src/Base/DualQuaternion.cpp index 5d26d97f07..29657cb181 100644 --- a/src/Base/DualQuaternion.cpp +++ b/src/Base/DualQuaternion.cpp @@ -39,10 +39,12 @@ Base::DualQuat Base::operator-(Base::DualQuat a, Base::DualQuat b) Base::DualQuat Base::operator*(Base::DualQuat a, Base::DualQuat b) { - return {a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, - a.w * b.y + a.y * b.w + a.z * b.x - a.x * b.z, - a.w * b.z + a.z * b.w + a.x * b.y - a.y * b.x, - a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z}; + return { + a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, + a.w * b.y + a.y * b.w + a.z * b.x - a.x * b.z, + a.w * b.z + a.z * b.w + a.x * b.y - a.y * b.x, + a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z + }; } Base::DualQuat Base::operator*(Base::DualQuat a, double b) @@ -109,9 +111,9 @@ Base::DualQuat Base::DualQuat::pow(double t, bool shorten) const DualQuat self = *this; if (shorten) { - if (dot(self, identity()) - < -1e-12) { // using negative tolerance instead of zero, for stability in situations - // the choice is ambiguous (180-degree rotations) + if (dot(self, identity()) < -1e-12) { // using negative tolerance instead of zero, for + // stability in situations the choice is ambiguous + // (180-degree rotations) self = -self; } } @@ -128,8 +130,10 @@ Base::DualQuat Base::DualQuat::pow(double t, bool shorten) const pitch *= t; // back to quaternion - return {l * sin(theta / 2) + DualQuat(0, 0, 0, cos(theta / 2)), - m * sin(theta / 2) + pitch / 2 * cos(theta / 2) * l - + DualQuat(0, 0, 0, -pitch / 2 * sin(theta / 2))}; + return { + l * sin(theta / 2) + DualQuat(0, 0, 0, cos(theta / 2)), + m * sin(theta / 2) + pitch / 2 * cos(theta / 2) * l + + DualQuat(0, 0, 0, -pitch / 2 * sin(theta / 2)) + }; } // NOLINTEND(readability-identifier-length) diff --git a/src/Base/Exception.cpp b/src/Base/Exception.cpp index 982c1d9c54..c90c41ae65 100644 --- a/src/Base/Exception.cpp +++ b/src/Base/Exception.cpp @@ -590,9 +590,9 @@ PyObject* RestoreError::getPyExceptionType() const // --------------------------------------------------------- #if defined(__GNUC__) && defined(FC_OS_LINUX) -#include -#include -#include +# include +# include +# include SignalException::SignalException() { @@ -601,17 +601,17 @@ SignalException::SignalException() sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; ok = (sigaction(SIGSEGV, &new_action, &old_action) < 0); -#ifdef _DEBUG +# ifdef _DEBUG std::cout << "Set new signal handler" << std::endl; -#endif +# endif } SignalException::~SignalException() { sigaction(SIGSEGV, &old_action, nullptr); -#ifdef _DEBUG +# ifdef _DEBUG std::cout << "Restore old signal handler" << std::endl; -#endif +# endif } void SignalException::throw_signal(const int signum) diff --git a/src/Base/Exception.h b/src/Base/Exception.h index d24988b7d7..d7e48d329b 100644 --- a/src/Base/Exception.h +++ b/src/Base/Exception.h @@ -39,13 +39,13 @@ using PyObject = struct _object; // NOLINT // Remove once all used compilers support this #if defined(__cpp_lib_source_location) -#define HAVE_STD_SOURCE_LOCATION 1 +# define HAVE_STD_SOURCE_LOCATION 1 #else -#undef HAVE_STD_SOURCE_LOCATION +# undef HAVE_STD_SOURCE_LOCATION #endif // std::source_location is implemented, but buggy in Clang 15 #if defined(__clang__) && __clang_major__ <= 15 -#undef HAVE_STD_SOURCE_LOCATION +# undef HAVE_STD_SOURCE_LOCATION #endif /// The macros do NOT mark any message for translation @@ -62,23 +62,25 @@ using PyObject = struct _object; // NOLINT #if defined(HAVE_STD_SOURCE_LOCATION) // NOLINTBEGIN(*-macro-usage) -#define THROWM(exc, msg) Base::setupAndThrowException((msg), std::source_location::current()); -#define THROWMT(exc, msg) \ - Base::setupAndThrowException((msg), std::source_location::current(), true); -#define FC_THROWM(exception, msg) \ - do { \ - std::stringstream ss; \ - ss << msg; \ - THROWM(exception, ss.str()); \ - } while (0) +# define THROWM(exc, msg) Base::setupAndThrowException((msg), std::source_location::current()); +# define THROWMT(exc, msg) \ + Base::setupAndThrowException((msg), std::source_location::current(), true); +# define FC_THROWM(exception, msg) \ + do { \ + std::stringstream ss; \ + ss << msg; \ + THROWM(exception, ss.str()); \ + } while (0) // NOLINTEND(*-macro-usage) namespace Base { template -[[noreturn]] void setupAndThrowException(const std::string message, - const std::source_location location, - const bool translatable = false) +[[noreturn]] void setupAndThrowException( + const std::string message, + const std::source_location location, + const bool translatable = false +) { ExceptionType exception {message}; exception.setTranslatable(translatable); @@ -89,30 +91,32 @@ template #else // HAVE_STD_SOURCE_LOCATION -#ifdef _MSC_VER -#define FC_THROW_INFO __FILE__, __LINE__, __FUNCSIG__ -#elif __GNUC__ -#define FC_THROW_INFO __FILE__, __LINE__, __PRETTY_FUNCTION__ -#else -#define FC_THROW_INFO __FILE__, __LINE__, __func__ -#endif +# ifdef _MSC_VER +# define FC_THROW_INFO __FILE__, __LINE__, __FUNCSIG__ +# elif __GNUC__ +# define FC_THROW_INFO __FILE__, __LINE__, __PRETTY_FUNCTION__ +# else +# define FC_THROW_INFO __FILE__, __LINE__, __func__ +# endif -#define THROWM(exc, msg) Base::setupAndThrowException(msg, FC_THROW_INFO); -#define THROWMT(exc, msg) Base::setupAndThrowException(msg, FC_THROW_INFO, true); -#define FC_THROWM(exception, msg) \ - do { \ - std::stringstream ss; \ - ss << msg; \ - THROWM(exception, ss.str()); \ - } while (0) +# define THROWM(exc, msg) Base::setupAndThrowException(msg, FC_THROW_INFO); +# define THROWMT(exc, msg) Base::setupAndThrowException(msg, FC_THROW_INFO, true); +# define FC_THROWM(exception, msg) \ + do { \ + std::stringstream ss; \ + ss << msg; \ + THROWM(exception, ss.str()); \ + } while (0) namespace Base { template -[[noreturn]] void setupAndThrowException(const std::string message, - const char* file, - const int line, - const char* func, - const bool translatable = false) +[[noreturn]] void setupAndThrowException( + const std::string message, + const char* file, + const int line, + const char* func, + const bool translatable = false +) { ExceptionType exception {message}; exception.setTranslatable(translatable); @@ -126,22 +130,28 @@ template //-------------------------------------------------------------------------------------------------- template -constexpr void THROWM_(const std::string& msg, - const std::source_location location = std::source_location::current()) +constexpr void THROWM_( + const std::string& msg, + const std::source_location location = std::source_location::current() +) { Base::setupAndThrowException(msg, location); } template -constexpr void THROWMT_(const std::string& msg, - const std::source_location location = std::source_location::current()) +constexpr void THROWMT_( + const std::string& msg, + const std::source_location location = std::source_location::current() +) { Base::setupAndThrowException(msg, location, true); } template -constexpr void FC_THROWM_(const std::string& raw_msg, - const std::source_location location = std::source_location::current()) +constexpr void FC_THROWM_( + const std::string& raw_msg, + const std::source_location location = std::source_location::current() +) { THROWM_(raw_msg, location); } @@ -241,8 +251,10 @@ public: class BaseExport FileException: public Exception { public: - explicit FileException(const std::string& message = "Unknown file exception happened", - const std::string& fileName = ""); + explicit FileException( + const std::string& message = "Unknown file exception happened", + const std::string& fileName = "" + ); FileException(const std::string& message, const FileInfo& File); const char* what() const noexcept override; @@ -319,8 +331,7 @@ public: class BaseExport AbnormalProgramTermination: public Exception { public: - explicit AbnormalProgramTermination( - const std::string& message = "Abnormal program termination"); + explicit AbnormalProgramTermination(const std::string& message = "Abnormal program termination"); PyObject* getPyExceptionType() const override; }; diff --git a/src/Base/Factory.h b/src/Base/Factory.h index d63027015a..7f96ad8a78 100644 --- a/src/Base/Factory.h +++ b/src/Base/Factory.h @@ -31,7 +31,7 @@ #include #include #ifndef FC_GLOBAL_H -#include +# include #endif diff --git a/src/Base/FileInfo.cpp b/src/Base/FileInfo.cpp index dacfd33619..1258d5bdf8 100644 --- a/src/Base/FileInfo.cpp +++ b/src/Base/FileInfo.cpp @@ -32,9 +32,9 @@ #include #include #ifdef FC_OS_WIN32 -#include +# include #else -#include +# include #endif #include "FileInfo.h" @@ -285,9 +285,7 @@ bool FileInfo::hasExtension(const char* Ext) const bool FileInfo::hasExtension(std::initializer_list Exts) const { - return std::ranges::any_of(Exts, [this](const char* ext) { - return hasExtension(ext); - }); + return std::ranges::any_of(Exts, [this](const char* ext) { return hasExtension(ext); }); } bool FileInfo::exists() const @@ -404,8 +402,7 @@ template std::time_t to_time_t(TP tp) { using namespace std::chrono; - auto sctp = - time_point_cast(tp - TP::clock::now() + system_clock::now()); + auto sctp = time_point_cast(tp - TP::clock::now() + system_clock::now()); return system_clock::to_time_t(sctp); } diff --git a/src/Base/GeometryPyCXX.cpp b/src/Base/GeometryPyCXX.cpp index c36fe3e2aa..d9e210b608 100644 --- a/src/Base/GeometryPyCXX.cpp +++ b/src/Base/GeometryPyCXX.cpp @@ -117,8 +117,9 @@ Py::PythonClassObject Vector2dPy::create(double vx, double vy) Py::Tuple arg(2); arg.setItem(0, Py::Float(vx)); arg.setItem(1, Py::Float(vy)); - Py::PythonClassObject py = - Py::PythonClassObject(class_type.apply(arg, Py::Dict())); + Py::PythonClassObject py = Py::PythonClassObject( + class_type.apply(arg, Py::Dict()) + ); return py; } diff --git a/src/Base/GeometryPyCXX.h b/src/Base/GeometryPyCXX.h index 964dc108a5..5b8165d442 100644 --- a/src/Base/GeometryPyCXX.h +++ b/src/Base/GeometryPyCXX.h @@ -284,12 +284,10 @@ private: }; // PyCXX wrapper classes Py::Matrix, Py::Rotation, Py::Placement, ... -using BoundingBox = - GeometryT; +using BoundingBox = GeometryT; using Matrix = GeometryT; using Rotation = GeometryT; -using Placement = - GeometryT; +using Placement = GeometryT; } // namespace Py diff --git a/src/Base/Handle.h b/src/Base/Handle.h index 2f5a809023..107e735aa5 100644 --- a/src/Base/Handle.h +++ b/src/Base/Handle.h @@ -28,7 +28,7 @@ #define BASE_HANDLE_H #ifndef FC_GLOBAL_H -#include +# include #endif diff --git a/src/Base/InputSource.cpp b/src/Base/InputSource.cpp index 573dbd6a7e..19cfa8f8bb 100644 --- a/src/Base/InputSource.cpp +++ b/src/Base/InputSource.cpp @@ -26,18 +26,18 @@ #include #if QT_VERSION < 0x060000 -#include +# include #else -#include -#include -#include +# include +# include +# include #endif #include "InputSource.h" #include "XMLTools.h" #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER using namespace XERCES_CPP_NAMESPACE; #else XERCES_CPP_NAMESPACE_USE @@ -66,9 +66,8 @@ struct StdInputStream::TextCodec QTextCodec* textCodec = QTextCodec::codecForName("UTF-8"); if (textCodec) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - const QString text = textCodec->toUnicode(reinterpret_cast(toFill), - static_cast(len), - &state); + const QString text + = textCodec->toUnicode(reinterpret_cast(toFill), static_cast(len), &state); if (state.invalidChars > 0) { // In case invalid characters were found decode back to 'utf-8' and replace // them with '?' @@ -114,8 +113,10 @@ struct StdInputStream::TextCodec }; #endif -StdInputStream::StdInputStream(std::istream& Stream, - XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager) +StdInputStream::StdInputStream( + std::istream& Stream, + XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager +) : stream(Stream) , codec(new TextCodec) { @@ -153,9 +154,11 @@ XMLSize_t StdInputStream::readBytes(XMLByte* const toFill, const XMLSize_t maxTo // --------------------------------------------------------------------------- // StdInputSource: Constructors and Destructor // --------------------------------------------------------------------------- -StdInputSource::StdInputSource(std::istream& Stream, - const char* filePath, - XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager) +StdInputSource::StdInputSource( + std::istream& Stream, + const char* filePath, + XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager +) : InputSource(manager) , stream(Stream) { diff --git a/src/Base/InputSource.h b/src/Base/InputSource.h index de8dee01ba..3144802625 100644 --- a/src/Base/InputSource.h +++ b/src/Base/InputSource.h @@ -31,11 +31,11 @@ #include #include #ifndef FC_GLOBAL_H -#include +# include #endif #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER namespace XERCES_CPP_NAMESPACE { class BinInputStream; @@ -95,10 +95,12 @@ private: class BaseExport StdInputSource: public XERCES_CPP_NAMESPACE_QUALIFIER InputSource { public: - StdInputSource(std::istream& Stream, - const char* filePath, - XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = - XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager); + StdInputSource( + std::istream& Stream, + const char* filePath, + XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager + = XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager + ); ~StdInputSource() override; XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream* makeStream() const override; diff --git a/src/Base/Interpreter.cpp b/src/Base/Interpreter.cpp index 3bce2f8a4d..f18e50fe8d 100644 --- a/src/Base/Interpreter.cpp +++ b/src/Base/Interpreter.cpp @@ -127,11 +127,13 @@ void PyException::reportException() const // set sys.last_vars to make post-mortem debugging work PyGILStateLocker locker; PySys_SetObject("last_traceback", PP_last_traceback); - Console().developerError("pyException", - "%s%s: %s\n", - _stackTrace.c_str(), - _errorType.c_str(), - what()); + Console().developerError( + "pyException", + "%s%s: %s\n", + _stackTrace.c_str(), + _errorType.c_str(), + what() + ); } } @@ -275,9 +277,11 @@ std::string InterpreterSingleton::runString(const char* sCmd) * if the error occurs after changing it inside the script. */ -std::string InterpreterSingleton::runStringWithKey(const char* psCmd, - const char* key, - const char* key_initial_value) +std::string InterpreterSingleton::runStringWithKey( + const char* psCmd, + const char* key, + const char* key_initial_value +) { PyGILStateLocker locker; Py::Module module("__main__"); @@ -286,8 +290,8 @@ std::string InterpreterSingleton::runStringWithKey(const char* psCmd, Py::String initial_value(key_initial_value); localDictionary.setItem(key, initial_value); - PyObject* presult = - PyRun_String(psCmd, Py_file_input, globalDictionary.ptr(), localDictionary.ptr()); + PyObject* presult + = PyRun_String(psCmd, Py_file_input, globalDictionary.ptr(), localDictionary.ptr()); if (!presult) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); @@ -508,12 +512,12 @@ void InterpreterSingleton::cleanupModules() { // This is only needed to make the address sanitizer happy #if defined(__has_feature) -#if __has_feature(address_sanitizer) +# if __has_feature(address_sanitizer) for (auto it : _modules) { delete it; } _modules.clear(); -#endif +# endif #endif } @@ -587,7 +591,8 @@ std::string InterpreterSingleton::init(int argc, char* argv[]) "base_path = os.getenv(\"VIRTUAL_ENV\")\n" "if not base_path is None:\n" " activate_this = os.path.join(base_path, \"bin\", \"activate_this.py\")\n" - " exec(open(activate_this).read(), {'__file__':activate_this})\n"); + " exec(open(activate_this).read(), {'__file__':activate_this})\n" + ); } size_t size = argc; @@ -734,11 +739,13 @@ int InterpreterSingleton::runCommandLine(const char* prompt) void InterpreterSingleton::runMethodVoid(PyObject* pobject, const char* method) { PyGILStateLocker locker; - if (PP_Run_Method(pobject, // object - method, // run method - nullptr, // no return type - nullptr, // so no return object - "()") // no arguments + if (PP_Run_Method( + pobject, // object + method, // run method + nullptr, // no return type + nullptr, // so no return object + "()" + ) // no arguments != 0) { throw PyException(/*"Error running InterpreterSingleton::RunMethodVoid()"*/); } @@ -749,11 +756,13 @@ PyObject* InterpreterSingleton::runMethodObject(PyObject* pobject, const char* m PyObject* pcO {}; PyGILStateLocker locker; - if (PP_Run_Method(pobject, // object - method, // run method - "O", // return type - &pcO, // return object - "()") // no arguments + if (PP_Run_Method( + pobject, // object + method, // run method + "O", // return type + &pcO, // return object + "()" + ) // no arguments != 0) { throw PyException(); } @@ -761,12 +770,14 @@ PyObject* InterpreterSingleton::runMethodObject(PyObject* pobject, const char* m return pcO; } -void InterpreterSingleton::runMethod(PyObject* pobject, - const char* method, - const char* resfmt, - void* cresult, /* convert to c/c++ */ - const char* argfmt, - ...) /* convert to python */ +void InterpreterSingleton::runMethod( + PyObject* pobject, + const char* method, + const char* resfmt, + void* cresult, /* convert to c/c++ */ + const char* argfmt, + ... +) /* convert to python */ { PyObject* pmeth {}; PyObject* pargs {}; @@ -779,8 +790,9 @@ void InterpreterSingleton::runMethod(PyObject* pobject, if (!pmeth) { /* get callable object */ va_end(argslist); throw AttributeError( - "Error running InterpreterSingleton::RunMethod() method not defined"); /* bound method? - has self */ + "Error running InterpreterSingleton::RunMethod() method not defined" + ); /* bound method? + has self */ } pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */ @@ -800,7 +812,8 @@ void InterpreterSingleton::runMethod(PyObject* pobject, PyErr_Print(); } throw RuntimeError( - "Error running InterpreterSingleton::RunMethod() exception in called method"); + "Error running InterpreterSingleton::RunMethod() exception in called method" + ); } } @@ -925,10 +938,12 @@ extern int getSWIGPointerTypeObj_T(const char* TypeName, PyTypeObject** ptr); } // namespace Swig_python #endif -PyObject* InterpreterSingleton::createSWIGPointerObj(const char* Module, - const char* TypeName, - void* Pointer, - int own) +PyObject* InterpreterSingleton::createSWIGPointerObj( + const char* Module, + const char* TypeName, + void* Pointer, + int own +) { int result = 0; PyObject* proxy = nullptr; @@ -951,11 +966,13 @@ PyObject* InterpreterSingleton::createSWIGPointerObj(const char* Module, throw Base::RuntimeError("No SWIG wrapped library loaded"); } -bool InterpreterSingleton::convertSWIGPointerObj(const char* Module, - const char* TypeName, - PyObject* obj, - void** ptr, - int flags) +bool InterpreterSingleton::convertSWIGPointerObj( + const char* Module, + const char* TypeName, + PyObject* obj, + void** ptr, + int flags +) { int result = 0; PyGILStateLocker locker; diff --git a/src/Base/Interpreter.h b/src/Base/Interpreter.h index 1b8a36155c..555f60f9c4 100644 --- a/src/Base/Interpreter.h +++ b/src/Base/Interpreter.h @@ -27,22 +27,22 @@ #define BASE_INTERPRETER_H #if defined(_POSIX_C_SOURCE) -#undef _POSIX_C_SOURCE +# undef _POSIX_C_SOURCE #endif // (re-)defined in pyconfig.h #if defined(_XOPEN_SOURCE) -#undef _XOPEN_SOURCE +# undef _XOPEN_SOURCE #endif // (re-)defined in pyconfig.h #include #ifdef FC_OS_MACOSX -#undef toupper -#undef tolower -#undef isupper -#undef islower -#undef isspace -#undef isalpha -#undef isalnum +# undef toupper +# undef tolower +# undef isupper +# undef islower +# undef isspace +# undef isalpha +# undef isalnum #endif #include @@ -60,14 +60,14 @@ * * See FeaturePythonImp::init() for example usage */ -#define FC_PY_GetCallable(_pyobj, _name, _var) \ - do { \ - _var = Py::Object(); \ - if (PyObject_HasAttrString(_pyobj, _name)) { \ - Py::Object _obj(PyObject_GetAttrString(_pyobj, _name), true); \ - if (_obj.isCallable()) \ - _var = _obj; \ - } \ +#define FC_PY_GetCallable(_pyobj, _name, _var) \ + do { \ + _var = Py::Object(); \ + if (PyObject_HasAttrString(_pyobj, _name)) { \ + Py::Object _obj(PyObject_GetAttrString(_pyobj, _name), true); \ + if (_obj.isCallable()) \ + _var = _obj; \ + } \ } while (0) /** Helper macro to obtain attribute from an object @@ -78,11 +78,11 @@ * * See FeaturePythonImp::init() for example usage */ -#define FC_PY_GetObject(_pyobj, _name, _var) \ - do { \ - _var = Py::Object(); \ - if (PyObject_HasAttrString(_pyobj, _name)) \ - _var = Py::asObject(PyObject_GetAttrString(_pyobj, _name)); \ +#define FC_PY_GetObject(_pyobj, _name, _var) \ + do { \ + _var = Py::Object(); \ + if (PyObject_HasAttrString(_pyobj, _name)) \ + _var = Py::asObject(PyObject_GetAttrString(_pyobj, _name)); \ } while (0) // NOLINTEND @@ -257,8 +257,7 @@ public: /// the result. std::string runString(const char* psCmd); /// Run a statement on the python interpreter with a key for exchanging strings - std::string - runStringWithKey(const char* psCmd, const char* key, const char* key_initial_value = ""); + std::string runStringWithKey(const char* psCmd, const char* key, const char* key_initial_value = ""); /// Run a statement on the python interpreter and return back the result object. Py::Object runStringObject(const char* sCmd); /// Run a statement on the python interpreter and gives back a string with the representation of @@ -273,12 +272,14 @@ public: /// runs a python object method which returns a arbitrary object PyObject* runMethodObject(PyObject* pobject, const char* method); /// runs a python method with arbitrary params - void runMethod(PyObject* pobject, - const char* method, - const char* resfmt = nullptr, - void* cresult = nullptr, - const char* argfmt = "()", - ...); + void runMethod( + PyObject* pobject, + const char* method, + const char* resfmt = nullptr, + void* cresult = nullptr, + const char* argfmt = "()", + ... + ); //@} /** @name Module handling @@ -332,13 +333,14 @@ public: */ //@{ /// generate a SWIG object - PyObject* - createSWIGPointerObj(const char* Module, const char* TypeName, void* Pointer, int own); - bool convertSWIGPointerObj(const char* Module, - const char* TypeName, - PyObject* obj, - void** ptr, - int flags); + PyObject* createSWIGPointerObj(const char* Module, const char* TypeName, void* Pointer, int own); + bool convertSWIGPointerObj( + const char* Module, + const char* TypeName, + PyObject* obj, + void** ptr, + int flags + ); void cleanupSWIG(const char* TypeName); PyTypeObject* getSWIGPointerTypeObj(const char* Module, const char* TypeName); //@} diff --git a/src/Base/Matrix.cpp b/src/Base/Matrix.cpp index fc26d18c88..da47f610d8 100644 --- a/src/Base/Matrix.cpp +++ b/src/Base/Matrix.cpp @@ -349,10 +349,7 @@ void Matrix4D::rotLine(const Vector3f& rclBase, const Vector3f& rclDir, float fA * Note: In case the \a fTranslation part is zero then passing \a rclBase, \a rclDir and \a rfAngle * to a new matrix object creates an identical matrix. */ -bool Matrix4D::toAxisAngle(Vector3f& rclBase, - Vector3f& rclDir, - float& rfAngle, - float& fTranslation) const +bool Matrix4D::toAxisAngle(Vector3f& rclBase, Vector3f& rclDir, float& rfAngle, float& fTranslation) const { Vector3d pnt = convertTo(rclBase); Vector3d dir = convertTo(rclDir); @@ -370,22 +367,23 @@ bool Matrix4D::toAxisAngle(Vector3f& rclBase, return ok; } -bool Matrix4D::toAxisAngle(Vector3d& rclBase, - Vector3d& rclDir, - double& rfAngle, - double& fTranslation) const +bool Matrix4D::toAxisAngle(Vector3d& rclBase, Vector3d& rclDir, double& rfAngle, double& fTranslation) const { // First check if the 3x3 submatrix is orthogonal for (int i = 0; i < 3; i++) { // length must be one - if (fabs(dMtrx4D[0][i] * dMtrx4D[0][i] + dMtrx4D[1][i] * dMtrx4D[1][i] - + dMtrx4D[2][i] * dMtrx4D[2][i] - 1.0) + if (fabs( + dMtrx4D[0][i] * dMtrx4D[0][i] + dMtrx4D[1][i] * dMtrx4D[1][i] + + dMtrx4D[2][i] * dMtrx4D[2][i] - 1.0 + ) > 0.01) { return false; } // scalar product with other rows must be zero - if (fabs(dMtrx4D[0][i] * dMtrx4D[0][(i + 1) % 3] + dMtrx4D[1][i] * dMtrx4D[1][(i + 1) % 3] - + dMtrx4D[2][i] * dMtrx4D[2][(i + 1) % 3]) + if (fabs( + dMtrx4D[0][i] * dMtrx4D[0][(i + 1) % 3] + dMtrx4D[1][i] * dMtrx4D[1][(i + 1) % 3] + + dMtrx4D[2][i] * dMtrx4D[2][(i + 1) % 3] + ) > 0.01) { return false; } @@ -688,11 +686,7 @@ void Matrix4D::Print() const { // NOLINTBEGIN for (int i = 0; i < 4; i++) { - printf("%9.3f %9.3f %9.3f %9.3f\n", - dMtrx4D[i][0], - dMtrx4D[i][1], - dMtrx4D[i][2], - dMtrx4D[i][3]); + printf("%9.3f %9.3f %9.3f %9.3f\n", dMtrx4D[i][0], dMtrx4D[i][1], dMtrx4D[i][2], dMtrx4D[i][3]); } // NOLINTEND } @@ -957,9 +951,7 @@ std::array Matrix4D::decompose() const residualMatrix.setCol(3, Vector3d()); // find and extract rotation int prim_dir = -1; - std::array dirs = {Vector3d(1., 0., 0.), - Vector3d(0., 1., 0.), - Vector3d(0., 0., 1.)}; + std::array dirs = {Vector3d(1., 0., 0.), Vector3d(0., 1., 0.), Vector3d(0., 0., 1.)}; for (int i = 0; i < 3; i++) { if (residualMatrix.getCol(i).IsNull()) { continue; @@ -1016,9 +1008,11 @@ std::array Matrix4D::decompose() const scaleMatrix.dMtrx4D[1][1] = yScale; scaleMatrix.dMtrx4D[2][2] = zScale; // The remaining shear - residualMatrix.scale(xScale != 0 ? 1.0 / xScale : 1.0, - yScale != 0 ? 1.0 / yScale : 1.0, - zScale != 0 ? 1.0 / zScale : 1.0); + residualMatrix.scale( + xScale != 0 ? 1.0 / xScale : 1.0, + yScale != 0 ? 1.0 / yScale : 1.0, + zScale != 0 ? 1.0 / zScale : 1.0 + ); // Restore trace in shear matrix residualMatrix.setDiagonal(Vector3d(1.0, 1.0, 1.0)); // Remove values close to zero diff --git a/src/Base/Matrix.h b/src/Base/Matrix.h index 9517b12be0..6a95d2a64e 100644 --- a/src/Base/Matrix.h +++ b/src/Base/Matrix.h @@ -32,7 +32,7 @@ #include "Vector3D.h" #ifndef FC_GLOBAL_H -#include +# include #endif @@ -215,8 +215,7 @@ public: void rotLine(const Vector3d& rclBase, const Vector3d& rclDir, double fAngle); /// Extract the rotation axis and angle. Therefore the 3x3 submatrix must be orthogonal. bool toAxisAngle(Vector3f& rclBase, Vector3f& rclDir, float& fAngle, float& fTranslation) const; - bool - toAxisAngle(Vector3d& rclBase, Vector3d& rclDir, double& fAngle, double& fTranslation) const; + bool toAxisAngle(Vector3d& rclBase, Vector3d& rclDir, double& fAngle, double& fTranslation) const; /// transform (move,scale,rotate) around a point void transform(const Vector3f& vec, const Matrix4D& mat); void transform(const Vector3d& vec, const Matrix4D& mat); diff --git a/src/Base/MatrixPyImp.cpp b/src/Base/MatrixPyImp.cpp index 29bcd8f726..82359bcbdf 100644 --- a/src/Base/MatrixPyImp.cpp +++ b/src/Base/MatrixPyImp.cpp @@ -286,10 +286,12 @@ PyObject* MatrixPy::move(PyObject* args) } // clears the error from previous PyArg_ParseTuple() PyErr_Clear(); - if (PyArg_ParseTuple(args, - "O!;three floats, or a tuple, or a vector is needed", - &(VectorPy::Type), - &pcVecObj)) { + if (PyArg_ParseTuple( + args, + "O!;three floats, or a tuple, or a vector is needed", + &(VectorPy::Type), + &pcVecObj + )) { VectorPy* pcObject = static_cast(pcVecObj); Vector3d* val = pcObject->getVectorPtr(); vec.Set(val->x, val->y, val->z); @@ -335,10 +337,12 @@ PyObject* MatrixPy::scale(PyObject* args) } // clears the error from previous PyArg_ParseTuple() PyErr_Clear(); - if (PyArg_ParseTuple(args, - "O!;one or three floats, or a tuple, or a vector is needed", - &(VectorPy::Type), - &pcVecObj)) { + if (PyArg_ParseTuple( + args, + "O!;one or three floats, or a tuple, or a vector is needed", + &(VectorPy::Type), + &pcVecObj + )) { VectorPy* pcObject = static_cast(pcVecObj); Vector3d* val = pcObject->getVectorPtr(); vec.Set(val->x, val->y, val->z); @@ -365,7 +369,8 @@ PyObject* MatrixPy::hasScale(PyObject* args) const ScaleType type = getMatrixPtr()->hasScale(tol); Py::Module mod("FreeCAD"); return Py::new_reference_to( - mod.callMemberFunction("ScaleType", Py::TupleN(Py::Long(static_cast(type))))); + mod.callMemberFunction("ScaleType", Py::TupleN(Py::Long(static_cast(type)))) + ); } PyObject* MatrixPy::decompose(PyObject* args) const @@ -440,7 +445,8 @@ PyObject* MatrixPy::transform(PyObject* args) &(VectorPy::Type), &pcVecObj, &(MatrixPy::Type), - &pcMatObj)) { + &pcMatObj + )) { return nullptr; } diff --git a/src/Base/Observer.h b/src/Base/Observer.h index 6048cb243f..b378853510 100644 --- a/src/Base/Observer.h +++ b/src/Base/Observer.h @@ -124,8 +124,10 @@ public: virtual ~Subject() { if (_ObserverSet.size() > 0) { - Base::Console().developerWarning(std::string("~Subject()"), - "Not detached all observers yet\n"); + Base::Console().developerWarning( + std::string("~Subject()"), + "Not detached all observers yet\n" + ); } } @@ -141,9 +143,11 @@ public: size_t count = _ObserverSet.size(); _ObserverSet.insert(ToObserv); if (_ObserverSet.size() == count) { - Base::Console().developerWarning(std::string("Subject::Attach"), - "Observer %p already attached\n", - static_cast(ToObserv)); + Base::Console().developerWarning( + std::string("Subject::Attach"), + "Observer %p already attached\n", + static_cast(ToObserv) + ); } #else _ObserverSet.insert(ToObserv); @@ -162,9 +166,11 @@ public: size_t count = _ObserverSet.size(); _ObserverSet.erase(ToObserv); if (_ObserverSet.size() == count) { - Base::Console().developerWarning(std::string("Subject::Detach"), - "Observer %p already detached\n", - static_cast(ToObserv)); + Base::Console().developerWarning( + std::string("Subject::Detach"), + "Observer %p already detached\n", + static_cast(ToObserv) + ); } #else _ObserverSet.erase(ToObserv); @@ -186,18 +192,23 @@ public: (*Iter)->OnChange(*this, rcReason); // send OnChange-signal } catch (Base::Exception& e) { - Base::Console().error("Unhandled Base::Exception caught when notifying observer.\n" - "The error message is: %s\n", - e.what()); + Base::Console().error( + "Unhandled Base::Exception caught when notifying observer.\n" + "The error message is: %s\n", + e.what() + ); } catch (std::exception& e) { - Base::Console().error("Unhandled std::exception caught when notifying observer\n" - "The error message is: %s\n", - e.what()); + Base::Console().error( + "Unhandled std::exception caught when notifying observer\n" + "The error message is: %s\n", + e.what() + ); } catch (...) { Base::Console().error( - "Unhandled unknown exception caught in when notifying observer.\n"); + "Unhandled unknown exception caught in when notifying observer.\n" + ); } } } @@ -239,9 +250,9 @@ private: // Workaround for MSVC #if defined(FreeCADBase_EXPORTS) && defined(_MSC_VER) -#define Base_EXPORT +# define Base_EXPORT #else -#define Base_EXPORT BaseExport +# define Base_EXPORT BaseExport #endif #if !defined(__MINGW32__) diff --git a/src/Base/Parameter.cpp b/src/Base/Parameter.cpp index 0ab5a24c80..75c7a52c1e 100644 --- a/src/Base/Parameter.cpp +++ b/src/Base/Parameter.cpp @@ -47,7 +47,7 @@ #include #ifdef FC_OS_LINUX -#include +# include #endif #include @@ -62,7 +62,7 @@ FC_LOG_LEVEL_INIT("Parameter", true, true) #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER using namespace XERCES_CPP_NAMESPACE; #else XERCES_CPP_NAMESPACE_USE @@ -176,9 +176,11 @@ inline bool DOMTreeErrorReporter::getSawErrors() const /** Default construction */ -ParameterGrp::ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* GroupNode, - const char* sName, - ParameterGrp* Parent) +ParameterGrp::ParameterGrp( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* GroupNode, + const char* sName, + ParameterGrp* Parent +) : _pGroupNode(GroupNode) , _Parent(Parent) { @@ -358,19 +360,21 @@ void ParameterGrp::revert(const Base::Reference& Grp) } } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* -ParameterGrp::CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, - const char* Type, - const char* Name) +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* ParameterGrp::CreateElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name +) { - if (XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParamGroup").unicodeForm()) - != 0 + if (XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParamGroup").unicodeForm()) != 0 && XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParameters").unicodeForm()) != 0) { - Base::Console().warning("CreateElement: %s cannot have the element %s of type %s\n", - StrX(Start->getNodeName()).c_str(), - Name, - Type); + Base::Console().warning( + "CreateElement: %s cannot have the element %s of type %s\n", + StrX(Start->getNodeName()).c_str(), + Name, + Type + ); return nullptr; } @@ -610,10 +614,12 @@ void ParameterGrp::RemoveAttribute(ParamType Type, const char* Name) } } -const char* ParameterGrp::GetAttribute(ParamType Type, - const char* Name, - std::string& Value, - const char* Default) const +const char* ParameterGrp::GetAttribute( + ParamType Type, + const char* Name, + std::string& Value, + const char* Default +) const { if (!_pGroupNode) { return Default; @@ -638,8 +644,10 @@ const char* ParameterGrp::GetAttribute(ParamType Type, return Value.c_str(); } -std::vector> -ParameterGrp::GetAttributeMap(ParamType Type, const char* sFilter) const +std::vector> ParameterGrp::GetAttributeMap( + ParamType Type, + const char* sFilter +) const { std::vector> res; if (!_pGroupNode) { @@ -655,10 +663,12 @@ ParameterGrp::GetAttributeMap(ParamType Type, const char* sFilter) const DOMElement* pcTemp = FindElement(_pGroupNode, T); while (pcTemp) { - Name = StrX(static_cast(pcTemp) - ->getAttributes() - ->getNamedItem(XStrLiteral("Name").unicodeForm()) - ->getNodeValue()) + Name = StrX( + static_cast(pcTemp) + ->getAttributes() + ->getNamedItem(XStrLiteral("Name").unicodeForm()) + ->getNodeValue() + ) .c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { @@ -666,10 +676,11 @@ ParameterGrp::GetAttributeMap(ParamType Type, const char* sFilter) const res.emplace_back(Name, std::string()); } else { - res.emplace_back(Name, - StrX(static_cast(pcTemp)->getAttribute( - XStrLiteral("Value").unicodeForm())) - .c_str()); + res.emplace_back( + Name, + StrX(static_cast(pcTemp)->getAttribute(XStrLiteral("Value").unicodeForm())) + .c_str() + ); } } pcTemp = FindNextElement(pcTemp, T); @@ -692,8 +703,7 @@ void ParameterGrp::_SetAttribute(ParamType T, const char* Name, const char* Valu } if (!_pGroupNode) { if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { - FC_WARN("Setting attribute " << Type << ":" << Name << " in an orphan group " - << _cName); + FC_WARN("Setting attribute " << Type << ":" << Name << " in an orphan group " << _cName); } return; } @@ -734,8 +744,7 @@ bool ParameterGrp::GetBool(const char* Name, bool bPreset) const } // if yes check the value and return - return (strcmp(StrX(pcElem->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), "1") - == 0); + return (strcmp(StrX(pcElem->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), "1") == 0); } void ParameterGrp::SetBool(const char* Name, bool bValue) @@ -836,7 +845,8 @@ std::vector ParameterGrp::GetInts(const char* sFilter) const // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.push_back( - atol(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str())); + atol(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str()) + ); } pcTemp = FindNextElement(pcTemp, "FCInt"); } @@ -860,7 +870,8 @@ std::vector> ParameterGrp::GetIntMap(const char* sF if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.emplace_back( Name, - (atol(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str()))); + (atol(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str())) + ); } pcTemp = FindNextElement(pcTemp, "FCInt"); } @@ -883,9 +894,7 @@ unsigned long ParameterGrp::GetUnsigned(const char* Name, unsigned long lPreset) // if yes check the value and return const int base = 10; - return strtoul(StrX(pcElem->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), - nullptr, - base); + return strtoul(StrX(pcElem->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), nullptr, base); } void ParameterGrp::SetUnsigned(const char* Name, unsigned long lValue) @@ -909,10 +918,11 @@ std::vector ParameterGrp::GetUnsigneds(const char* sFilter) const Name = StrX(pcTemp->getAttribute(XStrLiteral("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - vrValues.push_back( - strtoul(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), - nullptr, - base)); + vrValues.push_back(strtoul( + StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), + nullptr, + base + )); } pcTemp = FindNextElement(pcTemp, "FCUInt"); } @@ -920,8 +930,7 @@ std::vector ParameterGrp::GetUnsigneds(const char* sFilter) const return vrValues; } -std::vector> -ParameterGrp::GetUnsignedMap(const char* sFilter) const +std::vector> ParameterGrp::GetUnsignedMap(const char* sFilter) const { std::vector> vrValues; if (!_pGroupNode) { @@ -938,9 +947,12 @@ ParameterGrp::GetUnsignedMap(const char* sFilter) const if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.emplace_back( Name, - (strtoul(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), - nullptr, - base))); + (strtoul( + StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str(), + nullptr, + base + )) + ); } pcTemp = FindNextElement(pcTemp, "FCUInt"); } @@ -986,7 +998,8 @@ std::vector ParameterGrp::GetFloats(const char* sFilter) const // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.push_back( - atof(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str())); + atof(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str()) + ); } pcTemp = FindNextElement(pcTemp, "FCFloat"); } @@ -1010,7 +1023,8 @@ std::vector> ParameterGrp::GetFloatMap(const char if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.emplace_back( Name, - (atof(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str()))); + (atof(StrX(pcTemp->getAttribute(XStrLiteral("Value").unicodeForm())).c_str())) + ); } pcTemp = FindNextElement(pcTemp, "FCFloat"); } @@ -1112,8 +1126,7 @@ std::vector ParameterGrp::GetASCIIs(const char* sFilter) const return vrValues; } -std::vector> -ParameterGrp::GetASCIIMap(const char* sFilter) const +std::vector> ParameterGrp::GetASCIIMap(const char* sFilter) const { std::vector> vrValues; if (!_pGroupNode) { @@ -1135,7 +1148,8 @@ ParameterGrp::GetASCIIMap(const char* sFilter) const else { vrValues.emplace_back( Name, - std::string()); // For a string, an empty value is possible and allowed + std::string() + ); // For a string, an empty value is possible and allowed } } pcTemp = FindNextElement(pcTemp, "FCText"); @@ -1270,29 +1284,29 @@ std::vector ParameterGrp::GetColors(const char* sFilter) const auto packed = GetUnsigneds(sFilter); std::vector result; - std::transform(packed.begin(), - packed.end(), - std::back_inserter(result), - [](const unsigned long lValue) { - return Color(static_cast(lValue)); - }); + std::transform( + packed.begin(), + packed.end(), + std::back_inserter(result), + [](const unsigned long lValue) { return Color(static_cast(lValue)); } + ); return result; } -std::vector> -ParameterGrp::GetColorMap(const char* sFilter) const +std::vector> ParameterGrp::GetColorMap(const char* sFilter) const { auto packed = GetUnsignedMap(sFilter); std::vector> result; - std::transform(packed.begin(), - packed.end(), - std::back_inserter(result), - [](const std::pair& lValue) { - return std::make_pair(lValue.first, - Color(static_cast(lValue.second))); - }); + std::transform( + packed.begin(), + packed.end(), + std::back_inserter(result), + [](const std::pair& lValue) { + return std::make_pair(lValue.first, Color(static_cast(lValue.second))); + } + ); return result; } @@ -1404,11 +1418,11 @@ void ParameterGrp::Clear(bool notify) next = next->getNextSibling(); ParamType type = TypeValue(StrX(child->getNodeName()).c_str()); if (type != ParamType::FCInvalid && type != ParamType::FCGroup) { - params.emplace_back(type, - StrX(child->getAttributes() - ->getNamedItem(XStrLiteral("Name").unicodeForm()) - ->getNodeValue()) - .c_str()); + params.emplace_back( + type, + StrX(child->getAttributes()->getNamedItem(XStrLiteral("Name").unicodeForm())->getNodeValue()) + .c_str() + ); } DOMNode* node = _pGroupNode->removeChild(child); node->release(); @@ -1439,19 +1453,21 @@ bool ParameterGrp::ShouldRemove() const }); } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* -ParameterGrp::FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, - const char* Type, - const char* Name) const +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* ParameterGrp::FindElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name +) const { - if (XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParamGroup").unicodeForm()) - != 0 + if (XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParamGroup").unicodeForm()) != 0 && XMLString::compareString(Start->getNodeName(), XStrLiteral("FCParameters").unicodeForm()) != 0) { - Base::Console().warning("FindElement: %s cannot have the element %s of type %s\n", - StrX(Start->getNodeName()).c_str(), - Name, - Type); + Base::Console().warning( + "FindElement: %s cannot have the element %s of type %s\n", + StrX(Start->getNodeName()).c_str(), + Name, + Type + ); return nullptr; } const XStr xType(Type); @@ -1466,8 +1482,7 @@ ParameterGrp::FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, if (Name) { DOMNode* attr = attrs->getNamedItem(XStrLiteral("Name").unicodeForm()); if (attr - && !XMLString::compareString(xName.unicodeForm(), - attr->getNodeValue())) { + && !XMLString::compareString(xName.unicodeForm(), attr->getNodeValue())) { return dynamic_cast(clChild); } } @@ -1481,8 +1496,10 @@ ParameterGrp::FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, return nullptr; } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* -ParameterGrp::FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, const char* Type) const +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* ParameterGrp::FindNextElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, + const char* Type +) const { DOMNode* clChild = Prev; if (!clChild) { @@ -1501,10 +1518,11 @@ ParameterGrp::FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, cons return nullptr; } -XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* -ParameterGrp::FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, - const char* Type, - const char* Name) +XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* ParameterGrp::FindOrCreateElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name +) { // first try to find it DOMElement* pcElem = FindElement(Start, Type, Name); @@ -1515,8 +1533,10 @@ ParameterGrp::FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Sta return CreateElement(Start, Type, Name); } -XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* -ParameterGrp::FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, const char* Name) const +XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* ParameterGrp::FindAttribute( + XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, + const char* Name +) const { DOMNamedNodeMap* attr = Node->getAttributes(); if (attr) { @@ -1525,8 +1545,9 @@ ParameterGrp::FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, const return nullptr; } -std::vector> -ParameterGrp::GetParameterNames(const char* sFilter) const +std::vector> ParameterGrp::GetParameterNames( + const char* sFilter +) const { std::vector> res; if (!_pGroupNode) { @@ -1900,13 +1921,11 @@ int ParameterManager::LoadDocument(const XERCES_CPP_NAMESPACE_QUALIFIER InputSou parser->parse(inputSource); } catch (const XMLException& e) { - std::cerr << "An error occurred during parsing\n Message: " << StrX(e.getMessage()) - << "\n"; + std::cerr << "An error occurred during parsing\n Message: " << StrX(e.getMessage()) << "\n"; errorsOccurred = true; } catch (const DOMException& e) { - std::cerr << "A DOM error occurred during parsing\n DOMException code: " << e.code - << "\n"; + std::cerr << "A DOM error occurred during parsing\n DOMException code: " << e.code << "\n"; errorsOccurred = true; } catch (...) { @@ -1982,8 +2001,7 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const XMLCh tempStr[100]; XMLString::transcode("LS", tempStr, 99); DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr); - DOMLSSerializer* theSerializer = - static_cast(impl)->createLSSerializer(); + DOMLSSerializer* theSerializer = static_cast(impl)->createLSSerializer(); // NOLINTEND // set user specified end of line sequence and output encoding @@ -2000,7 +2018,8 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const if (gUseFilter) { myFilter = std::make_unique( DOMNodeFilter::SHOW_ELEMENT | DOMNodeFilter::SHOW_ATTRIBUTE - | DOMNodeFilter::SHOW_DOCUMENT_TYPE | DOMNodeFilter::SHOW_TEXT); + | DOMNodeFilter::SHOW_DOCUMENT_TYPE | DOMNodeFilter::SHOW_TEXT + ); theSerializer->setFilter(myFilter.get()); } @@ -2016,8 +2035,7 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const config->setParameter(XMLUni::fgDOMWRTSplitCdataSections, gSplitCdataSections); } - if (config->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, - gDiscardDefaultContent)) { + if (config->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent)) { config->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, gDiscardDefaultContent); } @@ -2043,13 +2061,15 @@ void ParameterManager::SaveDocument(XMLFormatTarget* pFormatTarget) const void ParameterManager::CreateDocument() { // creating a document from screatch - DOMImplementation* impl = - DOMImplementationRegistry::getDOMImplementation(XStrLiteral("Core").unicodeForm()); + DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation( + XStrLiteral("Core").unicodeForm() + ); delete _pDocument; - _pDocument = - impl->createDocument(nullptr, // root element namespace URI. - XStrLiteral("FCParameters").unicodeForm(), // root element name - nullptr); // document type object (DTD). + _pDocument = impl->createDocument( + nullptr, // root element namespace URI. + XStrLiteral("FCParameters").unicodeForm(), // root element name + nullptr + ); // document type object (DTD). // creating the node for the root group DOMElement* rootElem = _pDocument->getDocumentElement(); @@ -2083,9 +2103,11 @@ void ParameterManager::CheckDocument() const // const char* xsdFile = "..."; std::string xsdStr(xmlSchemeString); // NOLINT // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - MemBufInputSource xsdFile(reinterpret_cast(xsdStr.c_str()), - xsdStr.size(), - "Parameter.xsd"); + MemBufInputSource xsdFile( + reinterpret_cast(xsdStr.c_str()), + xsdStr.size(), + "Parameter.xsd" + ); // See // http://apache-xml-project.6118.n7.nabble.com/validating-xml-with-xsd-schema-td17515.html @@ -2111,8 +2133,10 @@ void ParameterManager::CheckDocument() const parser.parse(xmlFile); if (parser.getErrorCount() > 0) { - Base::Console().error("Unexpected XML structure detected: %zu errors\n", - parser.getErrorCount()); + Base::Console().error( + "Unexpected XML structure detected: %zu errors\n", + parser.getErrorCount() + ); } } catch (XMLException& e) { diff --git a/src/Base/Parameter.h b/src/Base/Parameter.h index b78fe0b317..4b16b4ddd4 100644 --- a/src/Base/Parameter.h +++ b/src/Base/Parameter.h @@ -40,13 +40,13 @@ using PyObject = struct _object; #include #ifdef FC_OS_MACOSX -#undef toupper -#undef tolower -#undef isupper -#undef islower -#undef isspace -#undef isalpha -#undef isalnum +# undef toupper +# undef tolower +# undef isupper +# undef islower +# undef isspace +# undef isalpha +# undef isalnum #endif #include @@ -59,15 +59,15 @@ using PyObject = struct _object; #include "Color.h" #ifdef _MSC_VER -#pragma warning(disable : 4251) -#pragma warning(disable : 4503) -#pragma warning(disable : 4786) // specifier longer then 255 chars -#pragma warning(disable : 4290) // not implemented throw specification -#pragma warning(disable : 4275) +# pragma warning(disable : 4251) +# pragma warning(disable : 4503) +# pragma warning(disable : 4786) // specifier longer then 255 chars +# pragma warning(disable : 4290) // not implemented throw specification +# pragma warning(disable : 4275) #endif #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER namespace XERCES_CPP_NAMESPACE { class DOMNode; @@ -280,8 +280,7 @@ public: * @param[out] Value The value of attribute or the fallback value. * @param[in] Default The fallback value. */ - const char* - GetAttribute(ParamType Type, const char* Name, std::string& Value, const char* Default) const; + const char* GetAttribute(ParamType Type, const char* Name, std::string& Value, const char* Default) const; /** * Returns all attributes with the given type. @@ -293,8 +292,10 @@ public: * @param[in] sFilter String that has to be present in the names of the attributes. * @returns Vector of attribute name & value pairs. */ - std::vector> - GetAttributeMap(ParamType Type, const char* sFilter = nullptr) const; + std::vector> GetAttributeMap( + ParamType Type, + const char* sFilter = nullptr + ) const; /** @@ -306,8 +307,9 @@ public: * @param[in] sFilter String that has to be present in the names of the attributes. * @returns Vector of attribute type & name pairs. */ - std::vector> - GetParameterNames(const char* sFilter = nullptr) const; + std::vector> GetParameterNames( + const char* sFilter = nullptr + ) const; //@} @@ -348,8 +350,9 @@ public: /// get a vector of all uint values in this group std::vector GetUnsigneds(const char* sFilter = nullptr) const; /// get a map with all uint values and the keys of this group - std::vector> - GetUnsignedMap(const char* sFilter = nullptr) const; + std::vector> GetUnsignedMap( + const char* sFilter = nullptr + ) const; /// remove a uint value from this group void RemoveUnsigned(const char* Name); //@} @@ -363,8 +366,7 @@ public: /// get a vector of all color values in this group std::vector GetColors(const char* sFilter = nullptr) const; /// get a map with all color values and the keys of this group - std::vector> - GetColorMap(const char* sFilter = nullptr) const; + std::vector> GetColorMap(const char* sFilter = nullptr) const; /// remove a color value from this group void RemoveColor(const char* Name); //@} @@ -405,8 +407,7 @@ public: */ std::vector GetASCIIs(const char* sFilter = nullptr) const; /// Same as GetASCIIs() but with key,value map - std::vector> - GetASCIIMap(const char* sFilter = nullptr) const; + std::vector> GetASCIIMap(const char* sFilter = nullptr) const; //@} friend class ParameterManager; @@ -436,9 +437,11 @@ public: protected: /// constructor is protected (handle concept) - ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* GroupNode = nullptr, - const char* sName = nullptr, - ParameterGrp* Parent = nullptr); + ParameterGrp( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* GroupNode = nullptr, + const char* sName = nullptr, + ParameterGrp* Parent = nullptr + ); /// destructor is protected (handle concept) ~ParameterGrp() override; /// helper function for GetGroup @@ -450,8 +453,10 @@ protected: void _SetAttribute(ParamType Type, const char* Name, const char* Value); void _Notify(ParamType Type, const char* Name, const char* Value); - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* - FindNextElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, const char* Type) const; + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* FindNextElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Prev, + const char* Type + ) const; /** Find an element specified by Type and Name * Search in the parent element Start for the first occurrence of an @@ -459,30 +464,35 @@ protected: * the pointer to that element, otherwise NULL * If the names not given it returns the first occurrence of Type. */ - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* - FindElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, - const char* Type, - const char* Name = nullptr) const; + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* FindElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name = nullptr + ) const; /** Find an element specified by Type and Name or create it if not found * Search in the parent element Start for the first occurrence of an * element of Type and with the attribute Name=Name. On success it returns * the pointer to that element, otherwise it creates the element and returns the pointer. */ - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* - FindOrCreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, - const char* Type, - const char* Name); + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* FindOrCreateElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name + ); - XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* - CreateElement(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, - const char* Type, - const char* Name); + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* CreateElement( + XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* Start, + const char* Type, + const char* Name + ); /** Find an attribute specified by Name */ - XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* - FindAttribute(XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, const char* Name) const; + XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* FindAttribute( + XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* Node, + const char* Name + ) const; /// DOM Node of the Base node of this group XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* _pGroupNode; @@ -566,10 +576,8 @@ public: * - Group removal: both 'name' and 'value' are empty * - Group rename: 'name' is the new name, and 'value' is the old name */ - boost::signals2::signal + boost::signals2::signal< + void(ParameterGrp* /*param*/, ParamType /*type*/, const char* /*name*/, const char* /*value*/)> signalParamChanged; int LoadDocument(const char* sFileName); diff --git a/src/Base/ParameterPy.cpp b/src/Base/ParameterPy.cpp index a20cdc561b..ab1eaf14bf 100644 --- a/src/Base/ParameterPy.cpp +++ b/src/Base/ParameterPy.cpp @@ -26,7 +26,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif #include #include @@ -34,7 +34,7 @@ #include #ifdef FC_OS_LINUX -#include +# include #endif #include "Parameter.h" @@ -166,11 +166,13 @@ public: // NOLINTEND private: - void tryCall(ParameterGrpObserver* obs, - ParameterGrp* Param, - ParameterGrp::ParamType Type, - const char* Name, - const char* Value); + void tryCall( + ParameterGrpObserver* obs, + ParameterGrp* Param, + ParameterGrp::ParamType Type, + const char* Name, + const char* Value + ); private: ParameterGrp::handle _cParamGrp; @@ -223,7 +225,8 @@ void ParameterGrpPy::init_type() "For 'FCParamGroup' type, the observer will be notified in the following events.\n" "* Group creation: both 'name' and 'value' contain the name of the new group\n" "* Group removal: both 'name' and 'value' are empty\n" - "* Group rename: 'name' is the new name, and 'value' is the old name"); + "* Group rename: 'name' is the new name, and 'value' is the old name" + ); add_varargs_method("Detach", &ParameterGrpPy::detach, "Detach()"); add_varargs_method("Notify", &ParameterGrpPy::notify, "Notify()"); add_varargs_method("NotifyAll", &ParameterGrpPy::notifyAll, "NotifyAll()"); @@ -760,17 +763,21 @@ Py::Object ParameterGrpPy::attach(const Py::Tuple& args) return Py::None(); } -void ParameterGrpPy::tryCall(ParameterGrpObserver* obs, - ParameterGrp* Param, - ParameterGrp::ParamType Type, - const char* Name, - const char* Value) +void ParameterGrpPy::tryCall( + ParameterGrpObserver* obs, + ParameterGrp* Param, + ParameterGrp::ParamType Type, + const char* Name, + const char* Value +) { Base::PyGILStateLocker lock; - Py::TupleN args(Py::asObject(new ParameterGrpPy(Param)), - Py::String(ParameterGrp::TypeName(Type)), - Py::String(Name ? Name : ""), - Py::String(Value ? Value : "")); + Py::TupleN args( + Py::asObject(new ParameterGrpPy(Param)), + Py::String(ParameterGrp::TypeName(Type)), + Py::String(Name ? Name : ""), + Py::String(Value ? Value : "") + ); try { Py::Callable(obs->callable).apply(args); } @@ -809,20 +816,20 @@ Py::Object ParameterGrpPy::attachManager(const Py::Tuple& args) auto obs = new ParameterGrpObserver(o, attr, _cParamGrp); ParameterManager* man = _cParamGrp->Manager(); - obs->conn = man->signalParamChanged.connect([obs, this](ParameterGrp* Param, - ParameterGrp::ParamType Type, - const char* Name, - const char* Value) { - if (!Param) { - return; - } - for (auto p = Param; p; p = p->Parent()) { - if (p == obs->_target) { - tryCall(obs, Param, Type, Name, Value); - break; + obs->conn = man->signalParamChanged.connect( + [obs, + this](ParameterGrp* Param, ParameterGrp::ParamType Type, const char* Name, const char* Value) { + if (!Param) { + return; + } + for (auto p = Param; p; p = p->Parent()) { + if (p == obs->_target) { + tryCall(obs, Param, Type, Name, Value); + break; + } } } - }); + ); _observers.push_back(obs); return Py::None(); diff --git a/src/Base/PersistencePyImp.cpp b/src/Base/PersistencePyImp.cpp index f83e3b8442..0c0dea49ca 100644 --- a/src/Base/PersistencePyImp.cpp +++ b/src/Base/PersistencePyImp.cpp @@ -66,14 +66,17 @@ PyObject* PersistencePy::dumpContent(PyObject* args, PyObject* kwds) const } // setup the stream. the in flag is needed to make "read" work - std::stringstream stream(std::stringstream::out | std::stringstream::in - | std::stringstream::binary); + std::stringstream stream( + std::stringstream::out | std::stringstream::in | std::stringstream::binary + ); try { getPersistencePtr()->dumpToStream(stream, compression); } catch (NotImplementedError&) { - PyErr_SetString(PyExc_NotImplementedError, - "Dumping content of this object type is not implemented"); + PyErr_SetString( + PyExc_NotImplementedError, + "Dumping content of this object type is not implemented" + ); return nullptr; } catch (...) { diff --git a/src/Base/Placement.h b/src/Base/Placement.h index 985d5fe7ef..e805bbb46f 100644 --- a/src/Base/Placement.h +++ b/src/Base/Placement.h @@ -109,8 +109,7 @@ public: //@} static Placement slerp(const Placement& p0, const Placement& p1, double t); - static Placement - sclerp(const Placement& p0, const Placement& p1, double t, bool shorten = true); + static Placement sclerp(const Placement& p0, const Placement& p1, double t, bool shorten = true); /// Returns string representation of the placement, useful for debugging std::string toString() const; diff --git a/src/Base/PlacementPyImp.cpp b/src/Base/PlacementPyImp.cpp index bdd5ba99ca..241ef5b650 100644 --- a/src/Base/PlacementPyImp.cpp +++ b/src/Base/PlacementPyImp.cpp @@ -139,8 +139,7 @@ int PlacementPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyObject* PlacementPy::richCompare(PyObject* v, PyObject* w, int op) { - if (PyObject_TypeCheck(v, &(PlacementPy::Type)) - && PyObject_TypeCheck(w, &(PlacementPy::Type))) { + if (PyObject_TypeCheck(v, &(PlacementPy::Type)) && PyObject_TypeCheck(w, &(PlacementPy::Type))) { Placement p1 = *static_cast(v)->getPlacementPtr(); Placement p2 = *static_cast(w)->getPlacementPtr(); @@ -287,13 +286,7 @@ PyObject* PlacementPy::sclerp(PyObject* args) const PyObject* pyplm2 {}; double t {}; PyObject* shorten = Py_True; - if (!PyArg_ParseTuple(args, - "O!d|O!", - &(PlacementPy::Type), - &pyplm2, - &t, - &(PyBool_Type), - &shorten)) { + if (!PyArg_ParseTuple(args, "O!d|O!", &(PlacementPy::Type), &pyplm2, &t, &(PyBool_Type), &shorten)) { return nullptr; } Placement plm2 = static_cast(pyplm2)->value(); @@ -362,10 +355,12 @@ void PlacementPy::setRotation(Py::Object arg) Py::Tuple tuple; if (tuple.accepts(arg.ptr())) { tuple = arg; - getPlacementPtr()->setRotation(Rotation(static_cast(Py::Float(tuple[0])), - static_cast(Py::Float(tuple[1])), - static_cast(Py::Float(tuple[2])), - static_cast(Py::Float(tuple[3])))); + getPlacementPtr()->setRotation(Rotation( + static_cast(Py::Float(tuple[0])), + static_cast(Py::Float(tuple[1])), + static_cast(Py::Float(tuple[2])), + static_cast(Py::Float(tuple[3])) + )); return; } diff --git a/src/Base/PreCompiled.h b/src/Base/PreCompiled.h index ca43aae768..5dad791b45 100644 --- a/src/Base/PreCompiled.h +++ b/src/Base/PreCompiled.h @@ -44,17 +44,17 @@ #include #ifdef FC_OS_WIN32 -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include #endif #if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) -#include -#include -#include +# include +# include +# include #endif // STL diff --git a/src/Base/Profiler.h b/src/Base/Profiler.h index 3a517c2e97..eaa39bf641 100644 --- a/src/Base/Profiler.h +++ b/src/Base/Profiler.h @@ -22,113 +22,113 @@ ***************************************************************************/ #ifdef TRACY_ENABLE -#include +# include #else -#define TracyNoop +# define TracyNoop -#define ZoneNamed(x, y) -#define ZoneNamedN(x, y, z) -#define ZoneNamedC(x, y, z) -#define ZoneNamedNC(x, y, z, w) +# define ZoneNamed(x, y) +# define ZoneNamedN(x, y, z) +# define ZoneNamedC(x, y, z) +# define ZoneNamedNC(x, y, z, w) -#define ZoneTransient(x, y) -#define ZoneTransientN(x, y, z) +# define ZoneTransient(x, y) +# define ZoneTransientN(x, y, z) -#define ZoneScoped -#define ZoneScopedN(x) -#define ZoneScopedC(x) -#define ZoneScopedNC(x, y) +# define ZoneScoped +# define ZoneScopedN(x) +# define ZoneScopedC(x) +# define ZoneScopedNC(x, y) -#define ZoneText(x, y) -#define ZoneTextV(x, y, z) -#define ZoneTextF(x, ...) -#define ZoneTextVF(x, y, ...) -#define ZoneName(x, y) -#define ZoneNameV(x, y, z) -#define ZoneNameF(x, ...) -#define ZoneNameVF(x, y, ...) -#define ZoneColor(x) -#define ZoneColorV(x, y) -#define ZoneValue(x) -#define ZoneValueV(x, y) -#define ZoneIsActive false -#define ZoneIsActiveV(x) false +# define ZoneText(x, y) +# define ZoneTextV(x, y, z) +# define ZoneTextF(x, ...) +# define ZoneTextVF(x, y, ...) +# define ZoneName(x, y) +# define ZoneNameV(x, y, z) +# define ZoneNameF(x, ...) +# define ZoneNameVF(x, y, ...) +# define ZoneColor(x) +# define ZoneColorV(x, y) +# define ZoneValue(x) +# define ZoneValueV(x, y) +# define ZoneIsActive false +# define ZoneIsActiveV(x) false -#define FrameMark -#define FrameMarkNamed(x) -#define FrameMarkStart(x) -#define FrameMarkEnd(x) +# define FrameMark +# define FrameMarkNamed(x) +# define FrameMarkStart(x) +# define FrameMarkEnd(x) -#define FrameImage(x, y, z, w, a) +# define FrameImage(x, y, z, w, a) -#define TracyLockable(type, varname) type varname -#define TracyLockableN(type, varname, desc) type varname -#define TracySharedLockable(type, varname) type varname -#define TracySharedLockableN(type, varname, desc) type varname -#define LockableBase(type) type -#define SharedLockableBase(type) type -#define LockMark(x) (void)x -#define LockableName(x, y, z) +# define TracyLockable(type, varname) type varname +# define TracyLockableN(type, varname, desc) type varname +# define TracySharedLockable(type, varname) type varname +# define TracySharedLockableN(type, varname, desc) type varname +# define LockableBase(type) type +# define SharedLockableBase(type) type +# define LockMark(x) (void)x +# define LockableName(x, y, z) -#define TracyPlot(x, y) -#define TracyPlotConfig(x, y, z, w, a) +# define TracyPlot(x, y) +# define TracyPlotConfig(x, y, z, w, a) -#define TracyMessage(x, y) -#define TracyMessageL(x) -#define TracyMessageC(x, y, z) -#define TracyMessageLC(x, y) -#define TracyAppInfo(x, y) +# define TracyMessage(x, y) +# define TracyMessageL(x) +# define TracyMessageC(x, y, z) +# define TracyMessageLC(x, y) +# define TracyAppInfo(x, y) -#define TracyAlloc(x, y) -#define TracyFree(x) -#define TracyMemoryDiscard(x) -#define TracySecureAlloc(x, y) -#define TracySecureFree(x) -#define TracySecureMemoryDiscard(x) +# define TracyAlloc(x, y) +# define TracyFree(x) +# define TracyMemoryDiscard(x) +# define TracySecureAlloc(x, y) +# define TracySecureFree(x) +# define TracySecureMemoryDiscard(x) -#define TracyAllocN(x, y, z) -#define TracyFreeN(x, y) -#define TracySecureAllocN(x, y, z) -#define TracySecureFreeN(x, y) +# define TracyAllocN(x, y, z) +# define TracyFreeN(x, y) +# define TracySecureAllocN(x, y, z) +# define TracySecureFreeN(x, y) -#define ZoneNamedS(x, y, z) -#define ZoneNamedNS(x, y, z, w) -#define ZoneNamedCS(x, y, z, w) -#define ZoneNamedNCS(x, y, z, w, a) +# define ZoneNamedS(x, y, z) +# define ZoneNamedNS(x, y, z, w) +# define ZoneNamedCS(x, y, z, w) +# define ZoneNamedNCS(x, y, z, w, a) -#define ZoneTransientS(x, y, z) -#define ZoneTransientNS(x, y, z, w) +# define ZoneTransientS(x, y, z) +# define ZoneTransientNS(x, y, z, w) -#define ZoneScopedS(x) -#define ZoneScopedNS(x, y) -#define ZoneScopedCS(x, y) -#define ZoneScopedNCS(x, y, z) +# define ZoneScopedS(x) +# define ZoneScopedNS(x, y) +# define ZoneScopedCS(x, y) +# define ZoneScopedNCS(x, y, z) -#define TracyAllocS(x, y, z) -#define TracyFreeS(x, y) -#define TracyMemoryDiscardS(x, y) -#define TracySecureAllocS(x, y, z) -#define TracySecureFreeS(x, y) -#define TracySecureMemoryDiscardS(x, y) +# define TracyAllocS(x, y, z) +# define TracyFreeS(x, y) +# define TracyMemoryDiscardS(x, y) +# define TracySecureAllocS(x, y, z) +# define TracySecureFreeS(x, y) +# define TracySecureMemoryDiscardS(x, y) -#define TracyAllocNS(x, y, z, w) -#define TracyFreeNS(x, y, z) -#define TracySecureAllocNS(x, y, z, w) -#define TracySecureFreeNS(x, y, z) +# define TracyAllocNS(x, y, z, w) +# define TracyFreeNS(x, y, z) +# define TracySecureAllocNS(x, y, z, w) +# define TracySecureFreeNS(x, y, z) -#define TracyMessageS(x, y, z) -#define TracyMessageLS(x, y) -#define TracyMessageCS(x, y, z, w) -#define TracyMessageLCS(x, y, z) +# define TracyMessageS(x, y, z) +# define TracyMessageLS(x, y) +# define TracyMessageCS(x, y, z, w) +# define TracyMessageLCS(x, y, z) -#define TracySourceCallbackRegister(x, y) -#define TracyParameterRegister(x, y) -#define TracyParameterSetup(x, y, z, w) -#define TracyIsConnected false -#define TracyIsStarted false -#define TracySetProgramName(x) +# define TracySourceCallbackRegister(x, y) +# define TracyParameterRegister(x, y) +# define TracyParameterSetup(x, y, z, w) +# define TracyIsConnected false +# define TracyIsStarted false +# define TracySetProgramName(x) -#define TracyFiberEnter(x) -#define TracyFiberEnterHint(x, y) -#define TracyFiberLeave +# define TracyFiberEnter(x) +# define TracyFiberEnterHint(x, y) +# define TracyFiberLeave #endif diff --git a/src/Base/ProgressIndicator.h b/src/Base/ProgressIndicator.h index 1f156cc27f..3d700a4d3a 100644 --- a/src/Base/ProgressIndicator.h +++ b/src/Base/ProgressIndicator.h @@ -87,8 +87,7 @@ public: * @param isForce If true, indicates a forced update even if the change threshold (≈1%) hasn’t * been met. */ - virtual void show([[maybe_unused]] float position, - [[maybe_unused]] ShowFlags flags = ShowFlags::None) + virtual void show([[maybe_unused]] float position, [[maybe_unused]] ShowFlags flags = ShowFlags::None) {} }; diff --git a/src/Base/ProgressIndicatorPy.cpp b/src/Base/ProgressIndicatorPy.cpp index 5090f7ebf4..b418e463ef 100644 --- a/src/Base/ProgressIndicatorPy.cpp +++ b/src/Base/ProgressIndicatorPy.cpp @@ -58,8 +58,7 @@ bool ProgressIndicatorPy::check(PyObject* py) return Py::PythonExtension::check(py); } -PyObject* -ProgressIndicatorPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) +PyObject* ProgressIndicatorPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { return new ProgressIndicatorPy(); } diff --git a/src/Base/PyExport.h b/src/Base/PyExport.h index 14cb14e77e..f7bdc21f82 100644 --- a/src/Base/PyExport.h +++ b/src/Base/PyExport.h @@ -35,10 +35,10 @@ // (re-)defined in pyconfig.h #if defined(_POSIX_C_SOURCE) -#undef _POSIX_C_SOURCE +# undef _POSIX_C_SOURCE #endif #if defined(_XOPEN_SOURCE) -#undef _XOPEN_SOURCE +# undef _XOPEN_SOURCE #endif #include @@ -46,13 +46,13 @@ #include #ifdef FC_OS_MACOSX -#undef toupper -#undef tolower -#undef isupper -#undef islower -#undef isspace -#undef isalpha -#undef isalnum +# undef toupper +# undef tolower +# undef isupper +# undef islower +# undef isspace +# undef isalpha +# undef isalnum #endif namespace Base diff --git a/src/Base/PyWrapParseTupleAndKeywords.h b/src/Base/PyWrapParseTupleAndKeywords.h index cc89265edf..b3f5fe6df6 100644 --- a/src/Base/PyWrapParseTupleAndKeywords.h +++ b/src/Base/PyWrapParseTupleAndKeywords.h @@ -36,11 +36,13 @@ namespace Base /// terminated by a nullptr (required by CPython) \arg (variadic) Pointers to the storage locations /// for the parameters \returns boolean true on success, or false on failure template -bool Wrapped_ParseTupleAndKeywords(PyObject* args, - PyObject* kw, - const char* format, - const std::array keywords, - ...) +bool Wrapped_ParseTupleAndKeywords( + PyObject* args, + PyObject* kw, + const char* format, + const std::array keywords, + ... +) { static_assert(arraySize > 0, "keywords array must have at least a single nullptr in it"); if (keywords.back()) { @@ -60,8 +62,8 @@ bool Wrapped_ParseTupleAndKeywords(PyObject* args, va_list va; // NOLINT va_start(va, keywords); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) - int retval = - PyArg_VaParseTupleAndKeywords(args, kw, format, const_cast(keywords.data()), va); + int retval + = PyArg_VaParseTupleAndKeywords(args, kw, format, const_cast(keywords.data()), va); va_end(va); return retval != 0; // Convert to a true C++ boolean } diff --git a/src/Base/PythonTypeExt.cpp b/src/Base/PythonTypeExt.cpp index ef939a11e2..12e876c8c8 100644 --- a/src/Base/PythonTypeExt.cpp +++ b/src/Base/PythonTypeExt.cpp @@ -33,17 +33,18 @@ PythonTypeExt::PythonTypeExt(Py::PythonType& type) : pytype(type) {} -Py::PythonType& PythonTypeExt::set_tp_descr_get(PyObject* (*tp_descr_get)(PyObject* self, - PyObject* obj, - PyObject* type)) +Py::PythonType& PythonTypeExt::set_tp_descr_get( + PyObject* (*tp_descr_get)(PyObject* self, PyObject* obj, PyObject* type) +) { pytype.type_object()->tp_descr_get = tp_descr_get; return pytype; } -Py::PythonType& -PythonTypeExt::set_tp_descr_set(int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value)) +Py::PythonType& PythonTypeExt::set_tp_descr_set( + int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value) +) { pytype.type_object()->tp_descr_set = tp_descr_set; diff --git a/src/Base/PythonTypeExt.h b/src/Base/PythonTypeExt.h index 905657f00c..f1f69d5aaa 100644 --- a/src/Base/PythonTypeExt.h +++ b/src/Base/PythonTypeExt.h @@ -43,10 +43,12 @@ class BaseExport PythonTypeExt public: explicit PythonTypeExt(Py::PythonType& type); - Py::PythonType& - set_tp_descr_get(PyObject* (*tp_descr_get)(PyObject* self, PyObject* obj, PyObject* type)); - Py::PythonType& - set_tp_descr_set(int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value)); + Py::PythonType& set_tp_descr_get( + PyObject* (*tp_descr_get)(PyObject* self, PyObject* obj, PyObject* type) + ); + Py::PythonType& set_tp_descr_set( + int (*tp_descr_set)(PyObject* self, PyObject* obj, PyObject* value) + ); private: Py::PythonType& pytype; diff --git a/src/Base/Quantity.cpp b/src/Base/Quantity.cpp index 20b25f2a36..58c3f15fe3 100644 --- a/src/Base/Quantity.cpp +++ b/src/Base/Quantity.cpp @@ -46,11 +46,11 @@ // suppress annoying warnings from generated source files #ifdef _MSC_VER -#pragma warning(disable : 4003) -#pragma warning(disable : 4018) -#pragma warning(disable : 4065) -#pragma warning(disable : 4273) -#pragma warning(disable : 4335) // disable MAC file format warning on VC +# pragma warning(disable : 4003) +# pragma warning(disable : 4018) +# pragma warning(disable : 4065) +# pragma warning(disable : 4273) +# pragma warning(disable : 4335) // disable MAC file format warning on VC #endif using Base::Quantity; @@ -130,7 +130,8 @@ bool Quantity::operator<(const Quantity& that) const { if (myUnit != that.myUnit) { throw Base::UnitsMismatchError( - "Quantity::operator <(): quantities need to have same unit to compare"); + "Quantity::operator <(): quantities need to have same unit to compare" + ); } return (myValue < that.myValue); @@ -140,7 +141,8 @@ bool Quantity::operator>(const Quantity& that) const { if (myUnit != that.myUnit) { throw Base::UnitsMismatchError( - "Quantity::operator >(): quantities need to have same unit to compare"); + "Quantity::operator >(): quantities need to have same unit to compare" + ); } return (myValue > that.myValue); @@ -150,7 +152,8 @@ bool Quantity::operator<=(const Quantity& that) const { if (myUnit != that.myUnit) { throw Base::UnitsMismatchError( - "Quantity::operator <=(): quantities need to have same unit to compare"); + "Quantity::operator <=(): quantities need to have same unit to compare" + ); } return (myValue <= that.myValue); @@ -160,7 +163,8 @@ bool Quantity::operator>=(const Quantity& that) const { if (myUnit != that.myUnit) { throw Base::UnitsMismatchError( - "Quantity::operator >=(): quantities need to have same unit to compare"); + "Quantity::operator >=(): quantities need to have same unit to compare" + ); } return (myValue >= that.myValue); @@ -192,8 +196,10 @@ Quantity Quantity::pow(const Quantity& other) const throw Base::UnitsMismatchError("Quantity::pow(): exponent must not have a unit"); } - return Quantity(std::pow(myValue, other.myValue), - myUnit.pow(static_cast(other.myValue))); + return Quantity( + std::pow(myValue, other.myValue), + myUnit.pow(static_cast(other.myValue)) + ); } Quantity Quantity::pow(double exp) const @@ -282,8 +288,7 @@ std::string Quantity::getUserString(double& factor, std::string& unitString) con return Base::UnitsApi::schemaTranslate(*this, factor, unitString); } -std::string -Quantity::getUserString(UnitsSchema* schema, double& factor, std::string& unitString) const +std::string Quantity::getUserString(UnitsSchema* schema, double& factor, std::string& unitString) const { return schema->translate(*this, factor, unitString); } @@ -512,8 +517,8 @@ double num_change(char* yytext, char dez_delim, char grp_delim) // NOLINTEND #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wmissing-noreturn" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wmissing-noreturn" #endif // error func @@ -523,18 +528,18 @@ void Quantity_yyerror(const char* errorinfo) } #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wsign-compare" -#pragma clang diagnostic ignored "-Wunneeded-internal-declaration" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wsign-compare" +# pragma clang diagnostic ignored "-Wunneeded-internal-declaration" #elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wsign-compare" -#pragma GCC diagnostic ignored "-Wfree-nonheap-object" +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wsign-compare" +# pragma GCC diagnostic ignored "-Wfree-nonheap-object" #endif namespace QuantityParser @@ -553,7 +558,7 @@ int QuantityLexer(); #ifndef DOXYGEN_SHOULD_SKIP_THIS // Scanner, defined in Quantity.l // NOLINTNEXTLINE -#include "Quantity.lex.c" +# include "Quantity.lex.c" #endif // DOXYGEN_SHOULD_SKIP_THIS class StringBufferCleaner @@ -580,16 +585,15 @@ private: } // namespace QuantityParser #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #elif defined(__GNUC__) -#pragma GCC diagnostic pop +# pragma GCC diagnostic pop #endif Quantity Quantity::parse(const std::string& string) { // parse from buffer - QuantityParser::YY_BUFFER_STATE my_string_buffer = - QuantityParser::yy_scan_string(string.c_str()); + QuantityParser::YY_BUFFER_STATE my_string_buffer = QuantityParser::yy_scan_string(string.c_str()); QuantityParser::StringBufferCleaner cleaner(my_string_buffer); // set the global return variables QuantResult = Quantity(std::numeric_limits::min()); diff --git a/src/Base/Quantity.h b/src/Base/Quantity.h index c3bebe0687..c4f8a07b49 100644 --- a/src/Base/Quantity.h +++ b/src/Base/Quantity.h @@ -148,11 +148,9 @@ public: myFormat = fmt; } - std::string - toString(const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)) const; + std::string toString(const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)) const; - std::string - toNumber(const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)) const; + std::string toNumber(const QuantityFormat& format = QuantityFormat(QuantityFormat::Default)) const; std::string getUserString() const; /// transfer to user preferred unit/potence diff --git a/src/Base/QuantityPyImp.cpp b/src/Base/QuantityPyImp.cpp index 945a7a09c3..b6701aef73 100644 --- a/src/Base/QuantityPyImp.cpp +++ b/src/Base/QuantityPyImp.cpp @@ -229,11 +229,8 @@ PyObject* QuantityPy::getValueAs(PyObject* args) const return Quantity::parse(str); }; - const std::vector()>> funcs = {tryQuantity, - tryUnit, - tryUnitAndValue, - tryUnitPartsAndValue, - tryString}; + const std::vector()>> funcs + = {tryQuantity, tryUnit, tryUnitAndValue, tryUnitPartsAndValue, tryString}; auto tryFuncs = [&]() -> std::optional { for (const auto& func : funcs) { diff --git a/src/Base/Reader.cpp b/src/Base/Reader.cpp index b6396bcb46..19e4e1c75c 100644 --- a/src/Base/Reader.cpp +++ b/src/Base/Reader.cpp @@ -43,13 +43,13 @@ #include "XMLTools.h" #ifdef _MSC_VER -#include +# include #endif #include #include #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER using namespace XERCES_CPP_NAMESPACE; #else XERCES_CPP_NAMESPACE_USE @@ -168,27 +168,35 @@ T Base::XMLReader::getAttribute(const char* AttrName) const } // Explicit template instantiation -template BaseExport bool Base::XMLReader::getAttribute(const char* AttrName, - bool defaultValue) const; +template BaseExport bool Base::XMLReader::getAttribute( + const char* AttrName, + bool defaultValue +) const; template BaseExport bool Base::XMLReader::getAttribute(const char* AttrName) const; -template BaseExport const char* -Base::XMLReader::getAttribute(const char* AttrName, const char* defaultValue) const; -template BaseExport const char* -Base::XMLReader::getAttribute(const char* AttrName) const; -template BaseExport double Base::XMLReader::getAttribute(const char* AttrName, - double defaultValue) const; +template BaseExport const char* Base::XMLReader::getAttribute( + const char* AttrName, + const char* defaultValue +) const; +template BaseExport const char* Base::XMLReader::getAttribute(const char* AttrName) const; +template BaseExport double Base::XMLReader::getAttribute( + const char* AttrName, + double defaultValue +) const; template BaseExport double Base::XMLReader::getAttribute(const char* AttrName) const; -template BaseExport int Base::XMLReader::getAttribute(const char* AttrName, - int defaultValue) const; +template BaseExport int Base::XMLReader::getAttribute(const char* AttrName, int defaultValue) const; template BaseExport int Base::XMLReader::getAttribute(const char* AttrName) const; -template BaseExport long Base::XMLReader::getAttribute(const char* AttrName, - long defaultValue) const; +template BaseExport long Base::XMLReader::getAttribute( + const char* AttrName, + long defaultValue +) const; template BaseExport long Base::XMLReader::getAttribute(const char* AttrName) const; -template BaseExport unsigned long -Base::XMLReader::getAttribute(const char* AttrName, - unsigned long defaultValue) const; -template BaseExport unsigned long -Base::XMLReader::getAttribute(const char* AttrName) const; +template BaseExport unsigned long Base::XMLReader::getAttribute( + const char* AttrName, + unsigned long defaultValue +) const; +template BaseExport unsigned long Base::XMLReader::getAttribute( + const char* AttrName +) const; bool Base::XMLReader::hasAttribute(const char* AttrName) const { @@ -341,8 +349,7 @@ std::streamsize Base::XMLReader::read(char_type* s, std::streamsize n) } for (;;) { - std::streamsize copy_size = - static_cast(Characters.size()) - CharacterOffset; + std::streamsize copy_size = static_cast(Characters.size()) - CharacterOffset; if (n < copy_size) { copy_size = n; } @@ -409,7 +416,8 @@ std::istream& Base::XMLReader::beginCharStream(CharStreamFormat format) auto* filteringStream = dynamic_cast(CharStream.get()); if (format == CharStreamFormat::Base64Encoded) { filteringStream->push( - base64_decoder(Base::base64DefaultBufferSize, Base64ErrorHandling::silent)); + base64_decoder(Base::base64DefaultBufferSize, Base64ErrorHandling::silent) + ); } filteringStream->push(boost::ref(*this)); return *CharStream; @@ -479,8 +487,10 @@ void Base::XMLReader::readFiles(zipios::ZipInputStream& zipstream) const // less data than the file size would allow. // All what we need to do is to notify the user about the // failure. - Base::Console().error("Reading failed from embedded file: %s\n", - entry->toString().c_str()); + Base::Console().error( + "Reading failed from embedded file: %s\n", + entry->toString().c_str() + ); FailedFiles.push_back(jt->FileName); } // Go to the next registered file name @@ -560,10 +570,12 @@ void Base::XMLReader::endDocument() ReadType = EndDocument; } -void Base::XMLReader::startElement(const XMLCh* const /*uri*/, - const XMLCh* const localname, - const XMLCh* const /*qname*/, - const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) +void Base::XMLReader::startElement( + const XMLCh* const /*uri*/, + const XMLCh* const localname, + const XMLCh* const /*qname*/, + const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs +) { Level++; // new scope LocalName = StrX(localname).c_str(); @@ -577,9 +589,7 @@ void Base::XMLReader::startElement(const XMLCh* const /*uri*/, ReadType = StartElement; } -void Base::XMLReader::endElement(const XMLCh* const /*uri*/, - const XMLCh* const localname, - const XMLCh* const /*qname*/) +void Base::XMLReader::endElement(const XMLCh* const /*uri*/, const XMLCh* const localname, const XMLCh* const /*qname*/) { Level--; // end of scope LocalName = StrX(localname).c_str(); diff --git a/src/Base/Reader.h b/src/Base/Reader.h index e0b4931801..2b6be93143 100644 --- a/src/Base/Reader.h +++ b/src/Base/Reader.h @@ -44,7 +44,7 @@ namespace zipios class ZipInputStream; } #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER namespace XERCES_CPP_NAMESPACE { class Attributes; @@ -133,8 +133,8 @@ class BaseExport XMLReader: public XERCES_CPP_NAMESPACE_QUALIFIER DefaultHandler public: enum ReaderStatus { - PartialRestore = - 0, // This bit indicates that a partial restore took place somewhere in this Document + PartialRestore = 0, // This bit indicates that a partial restore took place somewhere in + // this Document PartialRestoreInDocumentObject = 1, // This bit is local to the DocumentObject being read // indicating a partial restore therein PartialRestoreInProperty = 2, // Local to the Property @@ -233,9 +233,9 @@ private: // all explicit template instantiations - this is for getting // a compile error, rather than linker error. template - static constexpr bool instantiated = - std::is_same_v || std::is_same_v || std::is_same_v - || std::is_same_v || std::is_same_v || std::is_same_v; + static constexpr bool instantiated = std::is_same_v || std::is_same_v + || std::is_same_v || std::is_same_v || std::is_same_v + || std::is_same_v; public: /// return the named attribute as T (does type checking); if missing return defaultValue. @@ -271,7 +271,8 @@ public: T getAttribute(const char* AttrName, T defaultValue) const { return static_cast( - getAttribute(AttrName, static_cast(defaultValue))); + getAttribute(AttrName, static_cast(defaultValue)) + ); } /// Enum classes template @@ -327,13 +328,13 @@ protected: //@{ void startDocument() override; void endDocument() override; - void startElement(const XMLCh* const uri, - const XMLCh* const localname, - const XMLCh* const qname, - const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) override; - void endElement(const XMLCh* const uri, - const XMLCh* const localname, - const XMLCh* const qname) override; + void startElement( + const XMLCh* const uri, + const XMLCh* const localname, + const XMLCh* const qname, + const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs + ) override; + void endElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname) override; void characters(const XMLCh* const chars, const XMLSize_t length) override; void ignorableWhitespace(const XMLCh* const chars, const XMLSize_t length) override; //@} diff --git a/src/Base/Rotation.cpp b/src/Base/Rotation.cpp index 9693dbea2c..e9f43cf9d4 100644 --- a/src/Base/Rotation.cpp +++ b/src/Base/Rotation.cpp @@ -167,8 +167,10 @@ void Rotation::getValue(Matrix4D& matrix) const { // Taken from // - const double l = sqrt(this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1] - + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3]); + const double l = sqrt( + this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1] + + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3] + ); const double x = this->quat[0] / l; const double y = this->quat[1] / l; const double z = this->quat[2] / l; @@ -311,8 +313,10 @@ void Rotation::setValue(const Vector3d& rotateFrom, const Vector3d& rotateTo) void Rotation::normalize() { - double len = sqrt(this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1] - + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3]); + double len = sqrt( + this->quat[0] * this->quat[0] + this->quat[1] * this->quat[1] + + this->quat[2] * this->quat[2] + this->quat[3] * this->quat[3] + ); if (len > 0.0) { this->quat[0] /= len; this->quat[1] /= len; @@ -388,10 +392,12 @@ Rotation& Rotation::multRight(const Base::Rotation& q) double w1 {}; q.getValue(x1, y1, z1, w1); - this->setValue(w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, - w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, - w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, - w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1); + this->setValue( + w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, + w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, + w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, + w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1 + ); return *this; } @@ -416,10 +422,12 @@ Rotation& Rotation::multLeft(const Base::Rotation& q) double w1 {}; this->getValue(x1, y1, z1, w1); - this->setValue(w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, - w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, - w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, - w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1); + this->setValue( + w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, + w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1, + w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1, + w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1 + ); return *this; } @@ -451,12 +459,12 @@ void Rotation::multVec(const Vector3d& src, Vector3d& dst) const double z2 = z * z; double w2 = w * w; - double dx = - (x2 + w2 - y2 - z2) * src.x + 2.0 * (x * y - z * w) * src.y + 2.0 * (x * z + y * w) * src.z; - double dy = - 2.0 * (x * y + z * w) * src.x + (w2 - x2 + y2 - z2) * src.y + 2.0 * (y * z - x * w) * src.z; - double dz = - 2.0 * (x * z - y * w) * src.x + 2.0 * (x * w + y * z) * src.y + (w2 - x2 - y2 + z2) * src.z; + double dx = (x2 + w2 - y2 - z2) * src.x + 2.0 * (x * y - z * w) * src.y + + 2.0 * (x * z + y * w) * src.z; + double dy = 2.0 * (x * y + z * w) * src.x + (w2 - x2 + y2 - z2) * src.y + + 2.0 * (y * z - x * w) * src.z; + double dz = 2.0 * (x * z - y * w) * src.x + 2.0 * (x * w + y * z) * src.y + + (w2 - x2 - y2 + z2) * src.z; dst.x = dx; dst.y = dy; dst.z = dz; @@ -530,8 +538,7 @@ Rotation Rotation::identity() return {0.0, 0.0, 0.0, 1.0}; } -Rotation -Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder) +Rotation Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder) { const double tol = Precision::Confusion(); enum dirIndex @@ -549,9 +556,11 @@ Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const for (int i = 0; i < 3; ++i) { order[i] = priorityOrder[i] - 'X'; if (order[i] < 0 || order[i] > 2) { - THROWM(ValueError, - "makeRotationByAxes: characters in priorityOrder must be uppercase X, Y, or Z. " - "Some other character encountered.") + THROWM( + ValueError, + "makeRotationByAxes: characters in priorityOrder must be uppercase X, Y, or Z. " + "Some other character encountered." + ) } } @@ -705,10 +714,12 @@ void Rotation::setYawPitchRoll(double y, double p, double r) double c3 = cos(r / 2.0); double s3 = sin(r / 2.0); - this->setValue(c1 * c2 * s3 - s1 * s2 * c3, - c1 * s2 * c3 + s1 * c2 * s3, - s1 * c2 * c3 - c1 * s2 * s3, - c1 * c2 * c3 + s1 * s2 * s3); + this->setValue( + c1 * c2 * s3 - s1 * s2 * c3, + c1 * s2 * c3 + s1 * c2 * s3, + s1 * c2 * c3 - c1 * s2 * s3, + c1 * c2 * c3 + s1 * s2 * s3 + ); } void Rotation::getYawPitchRoll(double& y, double& p, double& r) const @@ -779,15 +790,17 @@ bool Rotation::isSame(const Rotation& q, double tol) const // Is it safe to assume that? // Because a quaternion (x1,x2,x3,x4) is equal to (-x1,-x2,-x3,-x4) we use the // absolute value of the scalar product - double dot = - q.quat[0] * quat[0] + q.quat[1] * quat[1] + q.quat[2] * quat[2] + q.quat[3] * quat[3]; + double dot = q.quat[0] * quat[0] + q.quat[1] * quat[1] + q.quat[2] * quat[2] + + q.quat[3] * quat[3]; return fabs(dot) >= 1.0 - tol / 2; } bool Rotation::isIdentity() const { - return ((this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0) - && (this->quat[3] == 1.0 || this->quat[3] == -1.0)); + return ( + (this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0) + && (this->quat[3] == 1.0 || this->quat[3] == -1.0) + ); } bool Rotation::isIdentity(double tol) const @@ -797,8 +810,9 @@ bool Rotation::isIdentity(double tol) const bool Rotation::isNull() const { - return (this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0 - && this->quat[3] == 0.0); + return ( + this->quat[0] == 0.0 && this->quat[1] == 0.0 && this->quat[2] == 0.0 && this->quat[3] == 0.0 + ); } //======================================================================= @@ -979,10 +993,7 @@ Rotation::EulerSequence Rotation::eulerSequenceFromName(const char* name) return Invalid; } -void Rotation::setEulerAngles(EulerSequence theOrder, - double theAlpha, - double theBeta, - double theGamma) +void Rotation::setEulerAngles(EulerSequence theOrder, double theAlpha, double theBeta, double theGamma) { using std::numbers::pi; @@ -1045,10 +1056,7 @@ void Rotation::setEulerAngles(EulerSequence theOrder, this->evaluateVector(); } -void Rotation::getEulerAngles(EulerSequence theOrder, - double& theAlpha, - double& theBeta, - double& theGamma) const +void Rotation::getEulerAngles(EulerSequence theOrder, double& theAlpha, double& theBeta, double& theGamma) const { Mat M; getValue(M); diff --git a/src/Base/Rotation.h b/src/Base/Rotation.h index da63cf2aa0..d1659cf80d 100644 --- a/src/Base/Rotation.h +++ b/src/Base/Rotation.h @@ -28,7 +28,7 @@ #include "Vector3D.h" #ifndef FC_GLOBAL_H -#include +# include #endif namespace Base @@ -99,8 +99,7 @@ public: /// Z base vector is assumed to represent the normal vector static Rotation fromNormalVector(const Vector3d& normal); /// Utility function to create Rotation based on euler angles - static Rotation - fromEulerAngles(EulerSequence theOrder, double alpha, double beta, double gamma); + static Rotation fromEulerAngles(EulerSequence theOrder, double alpha, double beta, double gamma); //@} /** Methods to get or set rotations. */ @@ -184,10 +183,12 @@ public: * * If only one vector provided is nonzero, the other two directions are picked automatically. */ - static Rotation makeRotationByAxes(Vector3d xdir, - Vector3d ydir, - Vector3d zdir, - const char* priorityOrder = "ZXY"); + static Rotation makeRotationByAxes( + Vector3d xdir, + Vector3d ydir, + Vector3d zdir, + const char* priorityOrder = "ZXY" + ); private: void normalize(); diff --git a/src/Base/RotationPyImp.cpp b/src/Base/RotationPyImp.cpp index b65830b998..252ee65723 100644 --- a/src/Base/RotationPyImp.cpp +++ b/src/Base/RotationPyImp.cpp @@ -44,9 +44,8 @@ std::string RotationPy::representation() const Py::Float q3(ptr->getValue()[3]); std::stringstream str; str << "Rotation ("; - str << static_cast(q0.repr()) << ", " << static_cast(q1.repr()) - << ", " << static_cast(q2.repr()) << ", " - << static_cast(q3.repr()); + str << static_cast(q0.repr()) << ", " << static_cast(q1.repr()) << ", " + << static_cast(q2.repr()) << ", " << static_cast(q3.repr()); str << ")"; return str.str(); diff --git a/src/Base/ServiceProvider.h b/src/Base/ServiceProvider.h index 8746de7baa..d3caf040f8 100644 --- a/src/Base/ServiceProvider.h +++ b/src/Base/ServiceProvider.h @@ -130,12 +130,12 @@ public: std::list result(source.size()); - std::transform(source.begin(), - source.end(), - result.begin(), - [](const ServiceDescriptor& descriptor) { - return descriptor.get(); - }); + std::transform( + source.begin(), + source.end(), + result.begin(), + [](const ServiceDescriptor& descriptor) { return descriptor.get(); } + ); return result; } diff --git a/src/Base/StackWalker.cpp b/src/Base/StackWalker.cpp index b179891d47..cea122528a 100644 --- a/src/Base/StackWalker.cpp +++ b/src/Base/StackWalker.cpp @@ -232,16 +232,16 @@ typedef DWORD64(__stdcall* PTRANSLATE_ADDRESS_ROUTINE64)(HANDLE hProcess, // Some missing defines (for VC5/6): #ifndef INVALID_FILE_ATTRIBUTES -#define INVALID_FILE_ATTRIBUTES ((DWORD) - 1) +# define INVALID_FILE_ATTRIBUTES ((DWORD) - 1) #endif // secure-CRT_functions are only available starting with VC8 #if _MSC_VER < 1400 -#define strcpy_s(dst, len, src) strcpy(dst, src) -#define strncpy_s(dst, len, src, maxLen) strncpy(dst, len, src) -#define strcat_s(dst, len, src) strcat(dst, src) -#define _snprintf_s _snprintf -#define _tcscat_s _tcscat +# define strcpy_s(dst, len, src) strcpy(dst, src) +# define strncpy_s(dst, len, src, maxLen) strncpy(dst, len, src) +# define strcat_s(dst, len, src) strcat(dst, src) +# define _snprintf_s _snprintf +# define _tcscat_s _tcscat #endif static void MyStrCpy(char* szDest, size_t nMaxDestSize, const char* szSrc) @@ -478,10 +478,12 @@ public: tSFTA pSFTA; // SymGetLineFromAddr64() - typedef BOOL(__stdcall* tSGLFA)(IN HANDLE hProcess, - IN DWORD64 dwAddr, - OUT PDWORD pdwDisplacement, - OUT PIMAGEHLP_LINE64 Line); + typedef BOOL(__stdcall* tSGLFA)( + IN HANDLE hProcess, + IN DWORD64 dwAddr, + OUT PDWORD pdwDisplacement, + OUT PIMAGEHLP_LINE64 Line + ); tSGLFA pSGLFA; // SymGetModuleBase64() @@ -489,9 +491,11 @@ public: tSGMB pSGMB; // SymGetModuleInfo64() - typedef BOOL(__stdcall* tSGMI)(IN HANDLE hProcess, - IN DWORD64 dwAddr, - OUT IMAGEHLP_MODULE64_V3* ModuleInfo); + typedef BOOL(__stdcall* tSGMI)( + IN HANDLE hProcess, + IN DWORD64 dwAddr, + OUT IMAGEHLP_MODULE64_V3* ModuleInfo + ); tSGMI pSGMI; // SymGetOptions() @@ -499,25 +503,27 @@ public: tSGO pSGO; // SymGetSymFromAddr64() - typedef BOOL(__stdcall* tSGSFA)(IN HANDLE hProcess, - IN DWORD64 dwAddr, - OUT PDWORD64 pdwDisplacement, - OUT PIMAGEHLP_SYMBOL64 Symbol); + typedef BOOL(__stdcall* tSGSFA)( + IN HANDLE hProcess, + IN DWORD64 dwAddr, + OUT PDWORD64 pdwDisplacement, + OUT PIMAGEHLP_SYMBOL64 Symbol + ); tSGSFA pSGSFA; // SymInitialize() - typedef BOOL(__stdcall* tSI)(IN HANDLE hProcess, - IN LPCSTR UserSearchPath, - IN BOOL fInvadeProcess); + typedef BOOL(__stdcall* tSI)(IN HANDLE hProcess, IN LPCSTR UserSearchPath, IN BOOL fInvadeProcess); tSI pSI; // SymLoadModule64() - typedef DWORD64(__stdcall* tSLM)(IN HANDLE hProcess, - IN HANDLE hFile, - IN LPCSTR ImageName, - IN LPCSTR ModuleName, - IN DWORD64 BaseOfDll, - IN DWORD SizeOfDll); + typedef DWORD64(__stdcall* tSLM)( + IN HANDLE hProcess, + IN HANDLE hFile, + IN LPCSTR ImageName, + IN LPCSTR ModuleName, + IN DWORD64 BaseOfDll, + IN DWORD SizeOfDll + ); tSLM pSLM; // SymSetOptions() @@ -525,22 +531,26 @@ public: tSSO pSSO; // StackWalk64() - typedef BOOL(__stdcall* tSW)(DWORD MachineType, - HANDLE hProcess, - HANDLE hThread, - LPSTACKFRAME64 StackFrame, - PVOID ContextRecord, - PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, - PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, - PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, - PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress); + typedef BOOL(__stdcall* tSW)( + DWORD MachineType, + HANDLE hProcess, + HANDLE hThread, + LPSTACKFRAME64 StackFrame, + PVOID ContextRecord, + PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, + PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, + PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, + PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress + ); tSW pSW; // UnDecorateSymbolName() - typedef DWORD(__stdcall WINAPI* tUDSN)(PCSTR DecoratedName, - PSTR UnDecoratedName, - DWORD UndecoratedLength, - DWORD Flags); + typedef DWORD(__stdcall WINAPI* tUDSN)( + PCSTR DecoratedName, + PSTR UnDecoratedName, + DWORD UndecoratedLength, + DWORD Flags + ); tUDSN pUDSN; typedef BOOL(__stdcall WINAPI* tSGSP)(HANDLE hProcess, PSTR SearchPath, DWORD SearchPathLength); @@ -618,11 +628,7 @@ private: keepGoing = !!pM32F(hSnap, &me); int cnt = 0; while (keepGoing) { - this->LoadModule(hProcess, - me.szExePath, - me.szModule, - (DWORD64)me.modBaseAddr, - me.modBaseSize); + this->LoadModule(hProcess, me.szExePath, me.szModule, (DWORD64)me.modBaseAddr, me.modBaseSize); cnt++; keepGoing = !!pM32N(hSnap, &me); } @@ -645,17 +651,13 @@ private: BOOL GetModuleListPSAPI(HANDLE hProcess) { // EnumProcessModules() - typedef BOOL(__stdcall - * tEPM)(HANDLE hProcess, HMODULE * lphModule, DWORD cb, LPDWORD lpcbNeeded); + typedef BOOL(__stdcall * tEPM)(HANDLE hProcess, HMODULE * lphModule, DWORD cb, LPDWORD lpcbNeeded); // GetModuleFileNameEx() - typedef DWORD(__stdcall - * tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize); + typedef DWORD(__stdcall * tGMFNE)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize); // GetModuleBaseName() - typedef DWORD(__stdcall - * tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize); + typedef DWORD(__stdcall * tGMBN)(HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize); // GetModuleInformation() - typedef BOOL(__stdcall - * tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize); + typedef BOOL(__stdcall * tGMI)(HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize); HINSTANCE hPsapi; tEPM pEPM; @@ -716,8 +718,7 @@ private: tt2[0] = 0; pGMBN(hProcess, hMods[i], tt2, TTBUFLEN); - DWORD dwRes = - this->LoadModule(hProcess, tt, tt2, (DWORD64)mi.lpBaseOfDll, mi.SizeOfImage); + DWORD dwRes = this->LoadModule(hProcess, tt, tt2, (DWORD64)mi.lpBaseOfDll, mi.SizeOfImage); if (dwRes != ERROR_SUCCESS) { this->m_parent->OnDbgHelpErr("LoadModule", dwRes, 0); } @@ -913,12 +914,14 @@ static PCONTEXT get_current_exception_context() return pctx ? *pctx : NULL; } -bool StackWalker::Init(ExceptType extype, - int options, - LPCSTR szSymPath, - DWORD dwProcessId, - HANDLE hProcess, - PEXCEPTION_POINTERS exp) +bool StackWalker::Init( + ExceptType extype, + int options, + LPCSTR szSymPath, + DWORD dwProcessId, + HANDLE hProcess, + PEXCEPTION_POINTERS exp +) { PCONTEXT ctx = NULL; if (extype == AfterCatch) { @@ -1081,9 +1084,11 @@ BOOL StackWalker::LoadModules() strcat_s(szSymPath, nSymPathLen, "*https://msdl.microsoft.com/download/symbols;"); } else { - strcat_s(szSymPath, - nSymPathLen, - "SRV*c:\\websymbols*https://msdl.microsoft.com/download/symbols;"); + strcat_s( + szSymPath, + nSymPathLen, + "SRV*c:\\websymbols*https://msdl.microsoft.com/download/symbols;" + ); } } } // if SymBuildPath @@ -1114,10 +1119,12 @@ BOOL StackWalker::LoadModules() static StackWalker::PReadProcessMemoryRoutine s_readMemoryFunction = NULL; static LPVOID s_readMemoryFunction_UserData = NULL; -BOOL StackWalker::ShowCallstack(HANDLE hThread, - const CONTEXT* context, - PReadProcessMemoryRoutine readMemoryFunction, - LPVOID pUserData) +BOOL StackWalker::ShowCallstack( + HANDLE hThread, + const CONTEXT* context, + PReadProcessMemoryRoutine readMemoryFunction, + LPVOID pUserData +) { CONTEXT c; CallstackEntry csEntry; @@ -1218,7 +1225,7 @@ BOOL StackWalker::ShowCallstack(HANDLE hThread, s.AddrStack.Offset = c.Sp; s.AddrStack.Mode = AddrModeFlat; #else -#error "Platform not supported!" +# error "Platform not supported!" #endif pSym = (IMAGEHLP_SYMBOL64*)malloc(sizeof(IMAGEHLP_SYMBOL64) + STACKWALK_MAX_NAMELEN); @@ -1241,15 +1248,17 @@ BOOL StackWalker::ShowCallstack(HANDLE hThread, // assume that either you are done, or that the stack is so hosed that the next // deeper frame could not be found. // CONTEXT need not to be supplied if imageTyp is IMAGE_FILE_MACHINE_I386! - if (!this->m_sw->pSW(imageType, - this->m_hProcess, - hThread, - &s, - &c, - myReadProcMem, - this->m_sw->pSFTA, - this->m_sw->pSGMB, - NULL)) { + if (!this->m_sw->pSW( + imageType, + this->m_hProcess, + hThread, + &s, + &c, + myReadProcMem, + this->m_sw->pSFTA, + this->m_sw->pSGMB, + NULL + )) { // INFO: "StackWalk64" does not set "GetLastError"... this->OnDbgHelpErr("StackWalk64", 0, s.AddrPC.Offset); break; @@ -1278,21 +1287,12 @@ BOOL StackWalker::ShowCallstack(HANDLE hThread, if (s.AddrPC.Offset != 0) { // we seem to have a valid PC // show procedure info (SymGetSymFromAddr64()) - if (this->m_sw->pSGSFA(this->m_hProcess, - s.AddrPC.Offset, - &(csEntry.offsetFromSmybol), - pSym) + if (this->m_sw->pSGSFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromSmybol), pSym) != FALSE) { MyStrCpy(csEntry.name, STACKWALK_MAX_NAMELEN, pSym->Name); // UnDecorateSymbolName() - this->m_sw->pUDSN(pSym->Name, - csEntry.undName, - STACKWALK_MAX_NAMELEN, - UNDNAME_NAME_ONLY); - this->m_sw->pUDSN(pSym->Name, - csEntry.undFullName, - STACKWALK_MAX_NAMELEN, - UNDNAME_COMPLETE); + this->m_sw->pUDSN(pSym->Name, csEntry.undName, STACKWALK_MAX_NAMELEN, UNDNAME_NAME_ONLY); + this->m_sw->pUDSN(pSym->Name, csEntry.undFullName, STACKWALK_MAX_NAMELEN, UNDNAME_COMPLETE); } else { this->OnDbgHelpErr("SymGetSymFromAddr64", GetLastError(), s.AddrPC.Offset); @@ -1300,10 +1300,7 @@ BOOL StackWalker::ShowCallstack(HANDLE hThread, // show line number info, NT5.0-method (SymGetLineFromAddr64()) if (this->m_sw->pSGLFA != NULL) { // yes, we have SymGetLineFromAddr64() - if (this->m_sw->pSGLFA(this->m_hProcess, - s.AddrPC.Offset, - &(csEntry.offsetFromLine), - &Line) + if (this->m_sw->pSGLFA(this->m_hProcess, s.AddrPC.Offset, &(csEntry.offsetFromLine), &Line) != FALSE) { csEntry.lineNumber = Line.LineNumber; MyStrCpy(csEntry.lineFileName, STACKWALK_MAX_NAMELEN, Line.FileName); @@ -1432,11 +1429,13 @@ BOOL StackWalker::ShowObject(LPVOID pObject) return TRUE; }; -BOOL __stdcall StackWalker::myReadProcMem(HANDLE hProcess, - DWORD64 qwBaseAddress, - PVOID lpBuffer, - DWORD nSize, - LPDWORD lpNumberOfBytesRead) +BOOL __stdcall StackWalker::myReadProcMem( + HANDLE hProcess, + DWORD64 qwBaseAddress, + PVOID lpBuffer, + DWORD nSize, + LPDWORD lpNumberOfBytesRead +) { if (s_readMemoryFunction == NULL) { SIZE_T st; @@ -1447,23 +1446,27 @@ BOOL __stdcall StackWalker::myReadProcMem(HANDLE hProcess, return bRet; } else { - return s_readMemoryFunction(hProcess, - qwBaseAddress, - lpBuffer, - nSize, - lpNumberOfBytesRead, - s_readMemoryFunction_UserData); + return s_readMemoryFunction( + hProcess, + qwBaseAddress, + lpBuffer, + nSize, + lpNumberOfBytesRead, + s_readMemoryFunction_UserData + ); } } -void StackWalker::OnLoadModule(LPCSTR img, - LPCSTR mod, - DWORD64 baseAddr, - DWORD size, - DWORD result, - LPCSTR symType, - LPCSTR pdbName, - ULONGLONG fileVersion) +void StackWalker::OnLoadModule( + LPCSTR img, + LPCSTR mod, + DWORD64 baseAddr, + DWORD size, + DWORD result, + LPCSTR symType, + LPCSTR pdbName, + ULONGLONG fileVersion +) { CHAR buffer[STACKWALK_MAX_NAMELEN]; size_t maxLen = STACKWALK_MAX_NAMELEN; @@ -1471,37 +1474,41 @@ void StackWalker::OnLoadModule(LPCSTR img, maxLen = _TRUNCATE; #endif if (fileVersion == 0) { - _snprintf_s(buffer, - maxLen, - "%s:%s (%p), size: %ld (result: %ld), SymType: '%s', PDB: '%s'\n", - img, - mod, - (LPVOID)baseAddr, - size, - result, - symType, - pdbName); + _snprintf_s( + buffer, + maxLen, + "%s:%s (%p), size: %ld (result: %ld), SymType: '%s', PDB: '%s'\n", + img, + mod, + (LPVOID)baseAddr, + size, + result, + symType, + pdbName + ); } else { DWORD v4 = (DWORD)(fileVersion & 0xFFFF); DWORD v3 = (DWORD)((fileVersion >> 16) & 0xFFFF); DWORD v2 = (DWORD)((fileVersion >> 32) & 0xFFFF); DWORD v1 = (DWORD)((fileVersion >> 48) & 0xFFFF); - _snprintf_s(buffer, - maxLen, - "%s:%s (%p), size: %ld (result: %ld), SymType: '%s', PDB: '%s', fileVersion: " - "%ld.%ld.%ld.%ld\n", - img, - mod, - (LPVOID)baseAddr, - size, - result, - symType, - pdbName, - v1, - v2, - v3, - v4); + _snprintf_s( + buffer, + maxLen, + "%s:%s (%p), size: %ld (result: %ld), SymType: '%s', PDB: '%s', fileVersion: " + "%ld.%ld.%ld.%ld\n", + img, + mod, + (LPVOID)baseAddr, + size, + result, + symType, + pdbName, + v1, + v2, + v3, + v4 + ); } buffer[STACKWALK_MAX_NAMELEN - 1] = 0; // be sure it is NULL terminated OnOutput(buffer); @@ -1529,21 +1536,25 @@ void StackWalker::OnCallstackEntry(CallstackEntryType eType, CallstackEntry& ent if (entry.moduleName[0] == 0) { MyStrCpy(entry.moduleName, STACKWALK_MAX_NAMELEN, "(module-name not available)"); } - _snprintf_s(buffer, - maxLen, - "%p (%s): %s: %s\n", - (LPVOID)entry.offset, - entry.moduleName, - entry.lineFileName, - entry.name); + _snprintf_s( + buffer, + maxLen, + "%p (%s): %s: %s\n", + (LPVOID)entry.offset, + entry.moduleName, + entry.lineFileName, + entry.name + ); } else { - _snprintf_s(buffer, - maxLen, - "%s (%ld): %s\n", - entry.lineFileName, - entry.lineNumber, - entry.name); + _snprintf_s( + buffer, + maxLen, + "%s (%ld): %s\n", + entry.lineFileName, + entry.lineNumber, + entry.name + ); } buffer[STACKWALK_MAX_NAMELEN - 1] = 0; OnOutput(buffer); @@ -1557,12 +1568,14 @@ void StackWalker::OnDbgHelpErr(LPCSTR szFuncName, DWORD gle, DWORD64 addr) #if _MSC_VER >= 1400 maxLen = _TRUNCATE; #endif - _snprintf_s(buffer, - maxLen, - "ERROR: %s, GetLastError: %ld (Address: %p)\n", - szFuncName, - gle, - (LPVOID)addr); + _snprintf_s( + buffer, + maxLen, + "ERROR: %s, GetLastError: %ld (Address: %p)\n", + szFuncName, + gle, + (LPVOID)addr + ); buffer[STACKWALK_MAX_NAMELEN - 1] = 0; OnOutput(buffer); } @@ -1574,12 +1587,14 @@ void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUser #if _MSC_VER >= 1400 maxLen = _TRUNCATE; #endif - _snprintf_s(buffer, - maxLen, - "SymInit: Symbol-SearchPath: '%s', symOptions: %ld, UserName: '%s'\n", - szSearchPath, - symOptions, - szUserName); + _snprintf_s( + buffer, + maxLen, + "SymInit: Symbol-SearchPath: '%s', symOptions: %ld, UserName: '%s'\n", + szSearchPath, + symOptions, + szUserName + ); buffer[STACKWALK_MAX_NAMELEN - 1] = 0; OnOutput(buffer); // Also display the OS-version @@ -1588,13 +1603,15 @@ void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUser ZeroMemory(&ver, sizeof(OSVERSIONINFOA)); ver.dwOSVersionInfoSize = sizeof(ver); if (GetVersionExA(&ver) != FALSE) { - _snprintf_s(buffer, - maxLen, - "OS-Version: %d.%d.%d (%s)\n", - ver.dwMajorVersion, - ver.dwMinorVersion, - ver.dwBuildNumber, - ver.szCSDVersion); + _snprintf_s( + buffer, + maxLen, + "OS-Version: %d.%d.%d (%s)\n", + ver.dwMajorVersion, + ver.dwMinorVersion, + ver.dwBuildNumber, + ver.szCSDVersion + ); buffer[STACKWALK_MAX_NAMELEN - 1] = 0; OnOutput(buffer); } @@ -1602,26 +1619,28 @@ void StackWalker::OnSymInit(LPCSTR szSearchPath, DWORD symOptions, LPCSTR szUser OSVERSIONINFOEXA ver; ZeroMemory(&ver, sizeof(OSVERSIONINFOEXA)); ver.dwOSVersionInfoSize = sizeof(ver); -#if _MSC_VER >= 1900 -#pragma warning(push) -#pragma warning(disable : 4996) -#endif +# if _MSC_VER >= 1900 +# pragma warning(push) +# pragma warning(disable : 4996) +# endif if (GetVersionExA((OSVERSIONINFOA*)&ver) != FALSE) { - _snprintf_s(buffer, - maxLen, - "OS-Version: %ld.%ld.%ld (%s) 0x%x-0x%x\n", - ver.dwMajorVersion, - ver.dwMinorVersion, - ver.dwBuildNumber, - ver.szCSDVersion, - ver.wSuiteMask, - ver.wProductType); + _snprintf_s( + buffer, + maxLen, + "OS-Version: %ld.%ld.%ld (%s) 0x%x-0x%x\n", + ver.dwMajorVersion, + ver.dwMinorVersion, + ver.dwBuildNumber, + ver.szCSDVersion, + ver.wSuiteMask, + ver.wProductType + ); buffer[STACKWALK_MAX_NAMELEN - 1] = 0; OnOutput(buffer); } -#if _MSC_VER >= 1900 -#pragma warning(pop) -#endif +# if _MSC_VER >= 1900 +# pragma warning(pop) +# endif #endif } diff --git a/src/Base/StackWalker.h b/src/Base/StackWalker.h index c8c9f9574d..d703c3dfe1 100644 --- a/src/Base/StackWalker.h +++ b/src/Base/StackWalker.h @@ -261,20 +261,20 @@ protected: __asm mov c.Esp, esp \ } while (0) // clang-format on -#endif +# endif -#else +# else // The following is defined for x86 (XP and higher), x64 and IA64: -#define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, contextFlags) \ - do { \ - memset(&c, 0, sizeof(CONTEXT)); \ - c.ContextFlags = contextFlags; \ - RtlCaptureContext(&c); \ - } while (0); -#endif +# define GET_CURRENT_CONTEXT_STACKWALKER_CODEPLEX(c, contextFlags) \ + do { \ + memset(&c, 0, sizeof(CONTEXT)); \ + c.ContextFlags = contextFlags; \ + RtlCaptureContext(&c); \ + } while (0); +# endif -#endif // defined(_MSC_VER) +# endif // defined(_MSC_VER) #endif // __STACKWALKER_H__ // NOLINTEND diff --git a/src/Base/Stream.cpp b/src/Base/Stream.cpp index 3489d91132..84a5722aaa 100644 --- a/src/Base/Stream.cpp +++ b/src/Base/Stream.cpp @@ -25,7 +25,7 @@ #include #include #ifdef __GNUC__ -#include +# include #endif #include "Stream.h" @@ -283,9 +283,8 @@ std::streamsize ByteArrayOStreambuf::xsputn(const char* s, std::streamsize num) return _buffer->write(s, num); } -std::streambuf::pos_type ByteArrayOStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayOStreambuf:: + seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode /*mode*/) { off_type endpos = 0; off_type curpos = _buffer->pos(); @@ -312,8 +311,7 @@ std::streambuf::pos_type ByteArrayOStreambuf::seekoff(std::streambuf::off_type o return {endpos}; } -std::streambuf::pos_type ByteArrayOStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayOStreambuf::seekpos(std::streambuf::pos_type pos, std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } @@ -361,9 +359,8 @@ std::streamsize ByteArrayIStreambuf::showmanyc() return _end - _cur; } -std::streambuf::pos_type ByteArrayIStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayIStreambuf:: + seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode /*mode*/) { int p_pos = -1; if (way == std::ios_base::beg) { @@ -389,8 +386,7 @@ std::streambuf::pos_type ByteArrayIStreambuf::seekoff(std::streambuf::off_type o return ((p_pos + off) - _beg); } -std::streambuf::pos_type ByteArrayIStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type ByteArrayIStreambuf::seekpos(std::streambuf::pos_type pos, std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } @@ -419,9 +415,8 @@ std::streamsize IODeviceOStreambuf::xsputn(const char* s, std::streamsize num) return device->write(s, num); } -std::streambuf::pos_type IODeviceOStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceOStreambuf:: + seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode /*mode*/) { off_type endpos = 0; off_type curpos = device->pos(); @@ -448,8 +443,7 @@ std::streambuf::pos_type IODeviceOStreambuf::seekoff(std::streambuf::off_type of return {endpos}; } -std::streambuf::pos_type IODeviceOStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceOStreambuf::seekpos(std::streambuf::pos_type pos, std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } @@ -459,9 +453,11 @@ std::streambuf::pos_type IODeviceOStreambuf::seekpos(std::streambuf::pos_type po IODeviceIStreambuf::IODeviceIStreambuf(QIODevice* dev) : device(dev) { - setg(buffer + pbSize, // beginning of putback area - buffer + pbSize, // read position - buffer + pbSize); // end position + setg( + buffer + pbSize, // beginning of putback area + buffer + pbSize, // read position + buffer + pbSize + ); // end position } IODeviceIStreambuf::~IODeviceIStreambuf() = default; @@ -501,17 +497,18 @@ std::streambuf::int_type IODeviceIStreambuf::underflow() } // reset buffer pointers - setg(buffer + (pbSize - numPutback), // beginning of putback area - buffer + pbSize, // read position - buffer + pbSize + num); // end of buffer + setg( + buffer + (pbSize - numPutback), // beginning of putback area + buffer + pbSize, // read position + buffer + pbSize + num + ); // end of buffer // return next character return *gptr(); } -std::streambuf::pos_type IODeviceIStreambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceIStreambuf:: + seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode /*mode*/) { off_type endpos = 0; off_type curpos = device->pos(); @@ -538,8 +535,7 @@ std::streambuf::pos_type IODeviceIStreambuf::seekoff(std::streambuf::off_type of return {endpos}; } -std::streambuf::pos_type IODeviceIStreambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type IODeviceIStreambuf::seekpos(std::streambuf::pos_type pos, std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } @@ -718,9 +714,8 @@ std::streamsize PyStreambuf::xsputn(const char* s, std::streamsize num) #endif } -PyStreambuf::pos_type PyStreambuf::seekoff(PyStreambuf::off_type offset, - PyStreambuf::seekdir dir, - PyStreambuf::openmode /*mode*/) +PyStreambuf::pos_type PyStreambuf:: + seekoff(PyStreambuf::off_type offset, PyStreambuf::seekdir dir, PyStreambuf::openmode /*mode*/) { int whence = 0; switch (dir) { @@ -806,9 +801,8 @@ std::streamsize Streambuf::showmanyc() return _end - _cur; } -std::streambuf::pos_type Streambuf::seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type Streambuf:: + seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode /*mode*/) { std::string::const_iterator p_pos; if (way == std::ios_base::beg) { @@ -834,8 +828,7 @@ std::streambuf::pos_type Streambuf::seekoff(std::streambuf::off_type off, return ((p_pos + off) - _beg); } -std::streambuf::pos_type Streambuf::seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode /*mode*/) +std::streambuf::pos_type Streambuf::seekpos(std::streambuf::pos_type pos, std::ios_base::openmode /*mode*/) { return seekoff(pos, std::ios_base::beg); } diff --git a/src/Base/Stream.h b/src/Base/Stream.h index f984e7cbd3..122ffe2ade 100644 --- a/src/Base/Stream.h +++ b/src/Base/Stream.h @@ -27,7 +27,7 @@ #define BASE_STREAM_H #ifdef __GNUC__ -#include +# include #endif #include @@ -368,11 +368,15 @@ public: protected: int_type overflow(std::streambuf::int_type c) override; std::streamsize xsputn(const char* s, std::streamsize num) override; - pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; + pos_type seekoff( + std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; + pos_type seekpos( + std::streambuf::pos_type pos, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; public: ByteArrayOStreambuf(const ByteArrayOStreambuf&) = delete; @@ -400,11 +404,15 @@ protected: int_type underflow() override; int_type pbackfail(int_type ch) override; std::streamsize showmanyc() override; - pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; + pos_type seekoff( + std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; + pos_type seekpos( + std::streambuf::pos_type pos, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; public: ByteArrayIStreambuf(const ByteArrayIStreambuf&) = delete; @@ -431,11 +439,15 @@ public: protected: int_type overflow(std::streambuf::int_type c) override; std::streamsize xsputn(const char* s, std::streamsize num) override; - pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; + pos_type seekoff( + std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; + pos_type seekpos( + std::streambuf::pos_type pos, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; public: IODeviceOStreambuf(const IODeviceOStreambuf&) = delete; @@ -460,11 +472,15 @@ public: protected: int_type underflow() override; - pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; + pos_type seekoff( + std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; + pos_type seekpos( + std::streambuf::pos_type pos, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; public: IODeviceIStreambuf(const IODeviceIStreambuf&) = delete; @@ -542,11 +558,15 @@ protected: int_type underflow() override; int_type pbackfail(int_type ch) override; std::streamsize showmanyc() override; - pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = std::ios::in | std::ios::out) override; + pos_type seekoff( + std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; + pos_type seekpos( + std::streambuf::pos_type pos, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override; public: Streambuf(const Streambuf&) = delete; @@ -581,9 +601,11 @@ public: : std::ofstream(fi.toStdWString().c_str(), mode) {} #else : std::ofstream(fi.filePath().c_str(), mode) - {} + { + } #endif - ~ofstream() override = default; + ~ofstream() override + = default; void open(const FileInfo& fi, ios_base::openmode mode = std::ios::out | std::ios::trunc) { #ifdef _MSC_VER @@ -614,9 +636,11 @@ public: : std::ifstream(fi.toStdWString().c_str(), mode) {} #else : std::ifstream(fi.filePath().c_str(), mode) - {} + { + } #endif - ~ifstream() override = default; + ~ifstream() override + = default; void open(const FileInfo& fi, ios_base::openmode mode = std::ios::in) { #ifdef _MSC_VER diff --git a/src/Base/Tools.cpp b/src/Base/Tools.cpp index ecf359fe09..ba2e715033 100644 --- a/src/Base/Tools.cpp +++ b/src/Base/Tools.cpp @@ -152,8 +152,8 @@ std::string Base::Tools::escapedUnicodeToUtf8(const std::string& s) Base::PyGILStateLocker lock; std::string string; - PyObject* unicode = - PyUnicode_DecodeUnicodeEscape(s.c_str(), static_cast(s.size()), "strict"); + PyObject* unicode + = PyUnicode_DecodeUnicodeEscape(s.c_str(), static_cast(s.size()), "strict"); if (!unicode) { return string; } diff --git a/src/Base/Tools.h b/src/Base/Tools.h index 6dae25f75d..f13862b089 100644 --- a/src/Base/Tools.h +++ b/src/Base/Tools.h @@ -27,7 +27,7 @@ #define SRC_BASE_TOOLS_H_ #ifndef FC_GLOBAL_H -#include +# include #endif #include #include diff --git a/src/Base/Tools2D.cpp b/src/Base/Tools2D.cpp index a0b57e337a..bda61377ad 100644 --- a/src/Base/Tools2D.cpp +++ b/src/Base/Tools2D.cpp @@ -335,8 +335,7 @@ bool Polygon2d::Contains(const Vector2d& rclV) const return sTorsion != 0; } -void Polygon2d::Intersect(const Polygon2d& rclPolygon, - std::list& rclResultPolygonList) const +void Polygon2d::Intersect(const Polygon2d& rclPolygon, std::list& rclResultPolygonList) const { // trim the passed polygon with the current one, the result is a list of polygons (subset of the // passed polygon) your own (trim) polygon is closed diff --git a/src/Base/Tools2D.h b/src/Base/Tools2D.h index 836c7c7cfb..72bc272a05 100644 --- a/src/Base/Tools2D.h +++ b/src/Base/Tools2D.h @@ -32,7 +32,7 @@ #include #ifndef FC_GLOBAL_H -#include +# include #endif diff --git a/src/Base/Tools3D.h b/src/Base/Tools3D.h index a42da67050..a5a5a1fe3c 100644 --- a/src/Base/Tools3D.h +++ b/src/Base/Tools3D.h @@ -27,7 +27,7 @@ #define BASE_TOOLS3D_H #ifndef FC_GLOBAL_H -#include +# include #endif #include diff --git a/src/Base/Translate.cpp b/src/Base/Translate.cpp index ca1207c073..dca66ad3d3 100644 --- a/src/Base/Translate.cpp +++ b/src/Base/Translate.cpp @@ -33,49 +33,61 @@ using namespace Base; Translate::Translate() : Py::ExtensionModule("__Translate__") { - add_varargs_method("translate", - &Translate::translate, - "translate(context, sourcetext, disambiguation = None, n=-1)\n" - "-- Returns the translation text for sourceText, by querying\n" - "the installed translation files. The translation files are\n" - "searched from the most recently installed file back to the\n" - "first installed file."); - add_varargs_method("QT_TRANSLATE_NOOP", - &Translate::translateNoop, - "QT_TRANSLATE_NOOP(context, sourcetext)\n" - "Marks the UTF-8 encoded string literal sourcetext for delayed translation " - "in the given context.\n" - "The context is typically a class name and also needs to be specified as a " - "string literal."); - add_varargs_method("QT_TRANSLATE_NOOP3", - &Translate::translateNoop3, - "QT_TRANSLATE_NOOP3(context, sourcetext, disambiguation)\n" - "Marks the UTF-8 encoded string literal sourceText for delayed translation " - "in the given context\n" - "with the given disambiguation. The context is typically a class and also " - "needs to be specified\n" - "as a string literal. The string literal disambiguation should be a short " - "semantic tag to tell\n" - "apart otherwise identical strings."); - add_varargs_method("QT_TRANSLATE_NOOP_UTF8", - &Translate::translateNoop, - "QT_TRANSLATE_NOOP_UTF8(context, sourcetext)\n" - "Same as QT_TRANSLATE_NOOP"); - add_varargs_method("QT_TR_NOOP", - &Translate::trNoop, - "QT_TR_NOOP(sourcetext)\n" - "Marks the UTF-8 encoded string literal sourcetext for delayed translation " - "in the current context"); - add_varargs_method("QT_TR_NOOP_UTF8", - &Translate::trNoop, - "QT_TR_NOOP_UTF8(sourcetext)\n" - "Same as QT_TR_NOOP"); - add_varargs_method("installTranslator", - &Translate::installTranslator, - "Install a translator for testing purposes"); - add_varargs_method("removeTranslators", - &Translate::removeTranslators, - "Remove test translators"); + add_varargs_method( + "translate", + &Translate::translate, + "translate(context, sourcetext, disambiguation = None, n=-1)\n" + "-- Returns the translation text for sourceText, by querying\n" + "the installed translation files. The translation files are\n" + "searched from the most recently installed file back to the\n" + "first installed file." + ); + add_varargs_method( + "QT_TRANSLATE_NOOP", + &Translate::translateNoop, + "QT_TRANSLATE_NOOP(context, sourcetext)\n" + "Marks the UTF-8 encoded string literal sourcetext for delayed translation " + "in the given context.\n" + "The context is typically a class name and also needs to be specified as a " + "string literal." + ); + add_varargs_method( + "QT_TRANSLATE_NOOP3", + &Translate::translateNoop3, + "QT_TRANSLATE_NOOP3(context, sourcetext, disambiguation)\n" + "Marks the UTF-8 encoded string literal sourceText for delayed translation " + "in the given context\n" + "with the given disambiguation. The context is typically a class and also " + "needs to be specified\n" + "as a string literal. The string literal disambiguation should be a short " + "semantic tag to tell\n" + "apart otherwise identical strings." + ); + add_varargs_method( + "QT_TRANSLATE_NOOP_UTF8", + &Translate::translateNoop, + "QT_TRANSLATE_NOOP_UTF8(context, sourcetext)\n" + "Same as QT_TRANSLATE_NOOP" + ); + add_varargs_method( + "QT_TR_NOOP", + &Translate::trNoop, + "QT_TR_NOOP(sourcetext)\n" + "Marks the UTF-8 encoded string literal sourcetext for delayed translation " + "in the current context" + ); + add_varargs_method( + "QT_TR_NOOP_UTF8", + &Translate::trNoop, + "QT_TR_NOOP_UTF8(sourcetext)\n" + "Same as QT_TR_NOOP" + ); + add_varargs_method( + "installTranslator", + &Translate::installTranslator, + "Install a translator for testing purposes" + ); + add_varargs_method("removeTranslators", &Translate::removeTranslators, "Remove test translators"); initialize("This module is the Translate module"); // register with Python } diff --git a/src/Base/Translate.h b/src/Base/Translate.h index bba3f316da..b7c6d4c09b 100644 --- a/src/Base/Translate.h +++ b/src/Base/Translate.h @@ -31,7 +31,7 @@ #include #include #ifndef FC_GLOBAL_H -#include +# include #endif namespace Py diff --git a/src/Base/Type.cpp b/src/Base/Type.cpp index ef4406926f..0297d7fbcf 100644 --- a/src/Base/Type.cpp +++ b/src/Base/Type.cpp @@ -31,22 +31,22 @@ using namespace Base; -static_assert(sizeof(Base::Type) == sizeof(Type::TypeId), - "Base::Type has been designed to be small to be passed around by value efficiently. " - "The size of Base::Type has changed. Be careful when adding more data members."); +static_assert( + sizeof(Base::Type) == sizeof(Type::TypeId), + "Base::Type has been designed to be small to be passed around by value efficiently. " + "The size of Base::Type has changed. Be careful when adding more data members." +); static_assert( sizeof(Base::Type) <= 2 * sizeof(void*), "Base::Type has been designed to be small to be passed around by value efficiently. " "When the size grows larger than ~2 words, consider passing by const reference instead. " - "Exact limit depends on the architecture and ABI."); + "Exact limit depends on the architecture and ABI." +); struct Base::TypeData { - TypeData(const char* name, - const Type type, - const Type parent, - const Type::instantiationMethod instMethod) + TypeData(const char* name, const Type type, const Type parent, const Type::instantiationMethod instMethod) : name(name) , parent(parent) , type(type) @@ -133,8 +133,7 @@ const std::string Type::getModuleName(const char* className) std::string_view classNameView(className); auto pos = classNameView.find("::"); - return pos != std::string_view::npos ? std::string(classNameView.substr(0, pos)) - : std::string(); + return pos != std::string_view::npos ? std::string(classNameView.substr(0, pos)) : std::string(); } @@ -191,15 +190,17 @@ const Type Type::fromKey(TypeId key) const char* Type::getName() const { - assert(typedata.size() >= 1 - && "Type::init() must be called before fetching names, even for bad types"); + assert( + typedata.size() >= 1 && "Type::init() must be called before fetching names, even for bad types" + ); return typedata[index]->name.c_str(); } const Type Type::getParent() const { - assert(typedata.size() >= 1 - && "Type::init() must be called before fetching parents, even for bad types"); + assert( + typedata.size() >= 1 && "Type::init() must be called before fetching parents, even for bad types" + ); return typedata[index]->parent; } diff --git a/src/Base/Type.h b/src/Base/Type.h index 05a9b121f0..75f0e2375d 100644 --- a/src/Base/Type.h +++ b/src/Base/Type.h @@ -33,7 +33,7 @@ #include #include #ifndef FC_GLOBAL_H -#include +# include #endif namespace Base @@ -112,13 +112,19 @@ public: /// Returns all descendants from the given type static int getAllDerivedFrom(const Type type, std::vector& list); /// Returns the given named type if is derived from parent type, otherwise return bad type - [[nodiscard]] static const Type - getTypeIfDerivedFrom(const char* name, const Type parent, bool loadModule = false); + [[nodiscard]] static const Type getTypeIfDerivedFrom( + const char* name, + const Type parent, + bool loadModule = false + ); /// Returns the number of types created so far [[nodiscard]] static int getNumTypes(); /// Creates a new type with the given name, parent and instantiation method - [[nodiscard]] static const Type - createType(const Type parent, const char* name, instantiationMethod method = nullptr); + [[nodiscard]] static const Type createType( + const Type parent, + const char* name, + instantiationMethod method = nullptr + ); /// Returns the inner index of the type [[nodiscard]] TypeId getKey() const; /// Checks if the type is invalid diff --git a/src/Base/UniqueNameManager.cpp b/src/Base/UniqueNameManager.cpp index 8b675518fa..30aafd9f29 100644 --- a/src/Base/UniqueNameManager.cpp +++ b/src/Base/UniqueNameManager.cpp @@ -29,8 +29,9 @@ #include "UniqueNameManager.h" -std::tuple -Base::UniqueNameManager::decomposeName(const std::string& name) const +std::tuple Base::UniqueNameManager::decomposeName( + const std::string& name +) const { auto suffixStart = getNameSuffixStartPosition(name); auto digitsStart = std::find_if_not(suffixStart, name.crend(), [](char c) { @@ -41,10 +42,10 @@ Base::UniqueNameManager::decomposeName(const std::string& name) const name.substr(0, name.crend() - digitsStart), name.substr(name.crend() - suffixStart), digitCount, - UnlimitedUnsigned::fromString(name.substr(name.crend() - digitsStart, digitCount))}; + UnlimitedUnsigned::fromString(name.substr(name.crend() - digitsStart, digitCount)) + }; } -bool Base::UniqueNameManager::haveSameBaseName(const std::string& first, - const std::string& second) const +bool Base::UniqueNameManager::haveSameBaseName(const std::string& first, const std::string& second) const { auto firstSuffixStart = getNameSuffixStartPosition(first); auto secondSuffixStart = getNameSuffixStartPosition(second); @@ -68,17 +69,17 @@ void Base::UniqueNameManager::addExactName(const std::string& name) auto baseNameEntry = uniqueSeeds.find(baseName); if (baseNameEntry == uniqueSeeds.end()) { // First use of baseName - baseNameEntry = - uniqueSeeds - .emplace(baseName, std::vector>()) - .first; + baseNameEntry + = uniqueSeeds + .emplace(baseName, std::vector>()) + .first; } if (digitCount >= baseNameEntry->second.size()) { // First use of this digitCount baseNameEntry->second.resize(digitCount + 1); } - PiecewiseSparseIntegerSet& baseNameAndDigitCountEntry = - baseNameEntry->second[digitCount]; + PiecewiseSparseIntegerSet& baseNameAndDigitCountEntry + = baseNameEntry->second[digitCount]; if (baseNameAndDigitCountEntry.contains(digitsValue)) { // We already have at least one instance of the name. @@ -90,8 +91,10 @@ void Base::UniqueNameManager::addExactName(const std::string& name) } baseNameAndDigitCountEntry.add(digitsValue); } -std::string Base::UniqueNameManager::makeUniqueName(const std::string& modelName, - std::size_t minDigits) const +std::string Base::UniqueNameManager::makeUniqueName( + const std::string& modelName, + std::size_t minDigits +) const { auto [namePrefix, nameSuffix, digitCount, digitsValue] = decomposeName(modelName); std::string baseName = namePrefix + nameSuffix; @@ -147,10 +150,10 @@ void Base::UniqueNameManager::removeExactName(const std::string& name) digitValueSets[digitCount].remove(digitsValue); // an element of digitValueSets may now be newly empty and so may other elements below it // Prune off all such trailing empty entries. - auto lastNonemptyEntry = - std::find_if(digitValueSets.crbegin(), digitValueSets.crend(), [](auto& it) { - return !it.empty(); - }); + auto lastNonemptyEntry + = std::find_if(digitValueSets.crbegin(), digitValueSets.crend(), [](auto& it) { + return !it.empty(); + }); if (lastNonemptyEntry == digitValueSets.crend()) { // All entries are empty, so the entire baseName can be forgotten. uniqueSeeds.erase(baseName); diff --git a/src/Base/UniqueNameManager.h b/src/Base/UniqueNameManager.h index 2f1981cfaa..99b0f6680e 100644 --- a/src/Base/UniqueNameManager.h +++ b/src/Base/UniqueNameManager.h @@ -26,7 +26,7 @@ #define SRC_BASE_UNIQUENAMEMANAGER_H_ #ifndef FC_GLOBAL_H -#include +# include #endif #include #include @@ -57,8 +57,7 @@ protected: // of the start of the suffix (or name.crbegin() if no suffix). // It must return the same suffix length (name.crbegin() - returnValue) for both // unique names (one containing digits) and the corresponding base name (with no digits). - virtual std::string::const_reverse_iterator - getNameSuffixStartPosition(const std::string& name) const + virtual std::string::const_reverse_iterator getNameSuffixStartPosition(const std::string& name) const { return name.crbegin(); } @@ -212,8 +211,9 @@ private: /// @param name The name to break up /// @return a tuple(basePrefix, nameSuffix, uniqueDigitCount, uniqueDigitsValue); /// The two latter values will be (0,0) if name is a base name without uniquifying digits. - std::tuple - decomposeName(const std::string& name) const; + std::tuple decomposeName( + const std::string& name + ) const; public: UniqueNameManager() = default; diff --git a/src/Base/Unit.cpp b/src/Base/Unit.cpp index 5eb4b5c1f7..c276b99166 100644 --- a/src/Base/Unit.cpp +++ b/src/Base/Unit.cpp @@ -110,20 +110,24 @@ constexpr auto unitSpecs = std::to_array({ { "YoungsModulus" , { -1, 1, -2 } }, }); // clang-format on -Unit::Unit(const int length, // NOLINT - const int mass, - const int time, - const int electricCurrent, - const int thermodynamicTemperature, - const int amountOfSubstance, - const int luminousIntensity, - const int angle) +Unit::Unit( + const int length, // NOLINT + const int mass, + const int time, + const int electricCurrent, + const int thermodynamicTemperature, + const int amountOfSubstance, + const int luminousIntensity, + const int angle +) : _name {""} { auto cast = [](auto val) { - return static_cast(std::clamp(val, - std::numeric_limits::min(), - std::numeric_limits::max())); + return static_cast(std::clamp( + val, + std::numeric_limits::min(), + std::numeric_limits::max() + )); }; _exps[0] = cast(length); @@ -257,10 +261,11 @@ std::string Unit::getString() const auto denominatorStr = buildStr(negValIndexes); - return fmt::format("{}/{}", - numeratorStr.empty() ? "1" : numeratorStr, - negValIndexes.size() > 1 ? fmt::format("({})", denominatorStr) - : denominatorStr); + return fmt::format( + "{}/{}", + numeratorStr.empty() ? "1" : numeratorStr, + negValIndexes.size() > 1 ? fmt::format("({})", denominatorStr) : denominatorStr + ); } std::string Unit::representation() const diff --git a/src/Base/Unit.h b/src/Base/Unit.h index 36d93d6e45..1716d3cb41 100644 --- a/src/Base/Unit.h +++ b/src/Base/Unit.h @@ -36,8 +36,9 @@ namespace Base { -constexpr auto unitSymbols = - std::to_array({"mm", "kg", "s", "A", "K", "mol", "cd", "deg"}); +constexpr auto unitSymbols = std::to_array( + {"mm", "kg", "s", "A", "K", "mol", "cd", "deg"} +); constexpr auto unitNumExponents {unitSymbols.size()}; using UnitExponents = std::array; @@ -57,14 +58,16 @@ public: } /// helper constructor to ease Unit construction from Python - explicit Unit(const int length, - const int mass = 0, - const int time = 0, - const int electricCurrent = 0, - const int thermodynamicTemperature = 0, - const int amountOfSubstance = 0, - const int luminousIntensity = 0, - const int angle = 0); + explicit Unit( + const int length, + const int mass = 0, + const int time = 0, + const int electricCurrent = 0, + const int thermodynamicTemperature = 0, + const int amountOfSubstance = 0, + const int luminousIntensity = 0, + const int angle = 0 + ); bool operator==(const Unit&) const; bool operator!=(const Unit& that) const; diff --git a/src/Base/UnitPyImp.cpp b/src/Base/UnitPyImp.cpp index bfb4eba674..5c6634adb8 100644 --- a/src/Base/UnitPyImp.cpp +++ b/src/Base/UnitPyImp.cpp @@ -238,8 +238,7 @@ PyObject* UnitPy::number_divmod_handler(PyObject* /*self*/, PyObject* /*other*/) return nullptr; } -PyObject* -UnitPy::number_power_handler(PyObject* /*self*/, PyObject* /*other*/, PyObject* /*modulo*/) +PyObject* UnitPy::number_power_handler(PyObject* /*self*/, PyObject* /*other*/, PyObject* /*modulo*/) { PyErr_SetString(PyExc_NotImplementedError, "Not implemented"); return nullptr; diff --git a/src/Base/UnitsApi.cpp b/src/Base/UnitsApi.cpp index 14ed7719fa..21e912c6de 100644 --- a/src/Base/UnitsApi.cpp +++ b/src/Base/UnitsApi.cpp @@ -128,8 +128,7 @@ double UnitsApi::toDouble(PyObject* args, const Base::Unit& u) throw Base::UnitsMismatchError("Wrong parameter type!"); } -std::string -UnitsApi::schemaTranslate(const Quantity& quant, double& factor, std::string& unitString) +std::string UnitsApi::schemaTranslate(const Quantity& quant, double& factor, std::string& unitString) { return schemas->currentSchema()->translate(quant, factor, unitString); } diff --git a/src/Base/UnitsApi.h b/src/Base/UnitsApi.h index 42a7f4684b..af2c9a9257 100644 --- a/src/Base/UnitsApi.h +++ b/src/Base/UnitsApi.h @@ -47,8 +47,7 @@ public: static void setSchema(const std::string& name); static void setSchema(std::size_t num); - static std::string - schemaTranslate(const Quantity& quant, double& factor, std::string& unitString); + static std::string schemaTranslate(const Quantity& quant, double& factor, std::string& unitString); static std::string schemaTranslate(const Quantity& quant); @@ -78,8 +77,7 @@ public: static PyMethodDef Methods[]; protected: - static inline auto schemas = - std::make_unique(UnitsSchemasData::unitSchemasDataPack); + static inline auto schemas = std::make_unique(UnitsSchemasData::unitSchemasDataPack); static inline int decimals {-1}; static inline int denominator {-1}; diff --git a/src/Base/UnitsApiPy.cpp b/src/Base/UnitsApiPy.cpp index 83331fe2d4..44c8401efa 100644 --- a/src/Base/UnitsApiPy.cpp +++ b/src/Base/UnitsApiPy.cpp @@ -160,8 +160,10 @@ PyObject* UnitsApi::sSchemaTranslate(PyObject* /*self*/, PyObject* args) } if (index < 0 || index >= static_cast(count())) { - PyErr_SetString(PyExc_ValueError, - std::string {"invalid schema index: " + std::to_string(index)}.c_str()); + PyErr_SetString( + PyExc_ValueError, + std::string {"invalid schema index: " + std::to_string(index)}.c_str() + ); return nullptr; } diff --git a/src/Base/UnitsSchema.cpp b/src/Base/UnitsSchema.cpp index 7eaabf80cd..76261749df 100644 --- a/src/Base/UnitsSchema.cpp +++ b/src/Base/UnitsSchema.cpp @@ -52,8 +52,7 @@ std::string UnitsSchema::translate(const Quantity& quant) const return translate(quant, dummy1, dummy2); } -std::string -UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitString) const +std::string UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitString) const { // Use defaults without schema-level translation. factor = 1.0; @@ -76,18 +75,21 @@ UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitS auto unitSpecs = spec.translationSpecs.at(unitName); const auto unitSpec = std::find_if(unitSpecs.begin(), unitSpecs.end(), isSuitable); if (unitSpec == unitSpecs.end()) { - throw RuntimeError("Suitable threshold not found. Schema: " + spec.name - + " value: " + std::to_string(value)); + throw RuntimeError( + "Suitable threshold not found. Schema: " + spec.name + " value: " + std::to_string(value) + ); } if (unitSpec->factor == 0) { const QuantityFormat& format = quant.getFormat(); - return UnitsSchemasData::runSpecial(unitSpec->unitString, - value, - format.getPrecision(), - format.getDenominator(), - factor, - unitString); + return UnitsSchemasData::runSpecial( + unitSpec->unitString, + value, + format.getPrecision(), + format.getDenominator(), + factor, + unitString + ); } factor = unitSpec->factor; @@ -96,8 +98,7 @@ UnitsSchema::translate(const Quantity& quant, double& factor, std::string& unitS return toLocale(quant, factor, unitString); } -std::string -UnitsSchema::toLocale(const Quantity& quant, const double factor, const std::string& unitString) +std::string UnitsSchema::toLocale(const Quantity& quant, const double factor, const std::string& unitString) { QLocale Lc; const QuantityFormat& format = quant.getFormat(); @@ -105,9 +106,8 @@ UnitsSchema::toLocale(const Quantity& quant, const double factor, const std::str Lc.setNumberOptions(static_cast(format.option)); } - auto valueString = - Lc.toString(quant.getValue() / factor, format.toFormat(), format.getPrecision()) - .toStdString(); + auto valueString = Lc.toString(quant.getValue() / factor, format.toFormat(), format.getPrecision()) + .toStdString(); auto notUnit = [](auto s) { return s.empty() || s == "°" || s == "″" || s == "′" || s == "\"" || s == "'"; @@ -157,9 +157,7 @@ std::string UnitsSchema::getUnitText(const Base::Quantity& quant) const // TODO: some common code here with translate() if (!spec.translationSpecs.contains(typeString)) { - Base::Console().log("Schema %s has no entry for %s\n", - getName().c_str(), - typeString.c_str()); + Base::Console().log("Schema %s has no entry for %s\n", getName().c_str(), typeString.c_str()); return {}; } auto unitSpecs = spec.translationSpecs.at(typeString); @@ -170,8 +168,10 @@ std::string UnitsSchema::getUnitText(const Base::Quantity& quant) const const auto unitSpec = std::ranges::find_if(unitSpecs, isSuitable); if (unitSpec == unitSpecs.end()) { - throw RuntimeError("Suitable threshold not found (2). Schema: " + spec.name - + " value: " + std::to_string(value)); + throw RuntimeError( + "Suitable threshold not found (2). Schema: " + spec.name + + " value: " + std::to_string(value) + ); } return unitSpec->unitString; diff --git a/src/Base/UnitsSchema.h b/src/Base/UnitsSchema.h index c823740fff..2b42131413 100644 --- a/src/Base/UnitsSchema.h +++ b/src/Base/UnitsSchema.h @@ -56,8 +56,11 @@ public: std::string translate(const Quantity& quant, double& factor, std::string& unitString) const; private: - [[nodiscard]] static std::string - toLocale(const Quantity& quant, double factor, const std::string& unitString); + [[nodiscard]] static std::string toLocale( + const Quantity& quant, + double factor, + const std::string& unitString + ); UnitsSchemaSpec spec; }; diff --git a/src/Base/UnitsSchemas.cpp b/src/Base/UnitsSchemas.cpp index c6cd3601b3..ec4c9abe8a 100644 --- a/src/Base/UnitsSchemas.cpp +++ b/src/Base/UnitsSchemas.cpp @@ -66,9 +66,7 @@ std::vector UnitsSchemas::getVec(const std::function UnitsSchemas::names() { - return getVec([](const UnitsSchemaSpec& spec) { - return spec.name; - }); + return getVec([](const UnitsSchemaSpec& spec) { return spec.name; }); } std::vector UnitsSchemas::descriptions() @@ -131,21 +129,15 @@ UnitsSchemaSpec UnitsSchemas::findSpec(const std::function(std::round(std::abs(value) / mmPerInch * denominator)); + auto numFractUnits = static_cast( + std::round(std::abs(value) / mmPerInch * denominator) + ); if (numFractUnits == 0) { return "0"; } - const auto feet = - static_cast(std::floor(numFractUnits / (inchPerFoot * denominator))); + const auto feet = static_cast(std::floor(numFractUnits / (inchPerFoot * denominator))); numFractUnits -= inchPerFoot * denominator * feet; const auto inches = static_cast(std::floor(numFractUnits / denominator)); @@ -773,12 +773,14 @@ inline const std::map +# include #endif #include #include @@ -52,8 +52,8 @@ private: // calculate the corresponding maxPartPlusOne in a static const initializer, so we just wire // in the values for 4-byte PartType. static const size_t partDigitCount = 9; - static const PartType maxPartPlusOne = - 1000000000; // (PartType)pow(10, partDigitCount); but can't call pow in a const ctor. + static const PartType maxPartPlusOne = 1000000000; // (PartType)pow(10, partDigitCount); but + // can't call pow in a const ctor. public: explicit UnlimitedUnsigned(SmallDeltaType value) @@ -75,7 +75,8 @@ public: else { lastStartPosition -= partDigitCount; result[i] = static_cast( - std::stoul(text.substr(lastStartPosition, partDigitCount))); + std::stoul(text.substr(lastStartPosition, partDigitCount)) + ); } if (result[i] != 0) { minimumSize = i + 1; @@ -211,10 +212,12 @@ public: // invert the result to get <= and we compare the most significant chunks first. return parts.size() < right.parts.size() || (parts.size() == right.parts.size() - && !std::lexicographical_compare(right.parts.rbegin(), - right.parts.rend(), - parts.rbegin(), - parts.rend())); + && !std::lexicographical_compare( + right.parts.rbegin(), + right.parts.rend(), + parts.rbegin(), + parts.rend() + )); } bool operator>(const UnlimitedUnsigned& right) const { diff --git a/src/Base/Uuid.h b/src/Base/Uuid.h index afd2290800..fb4da3d410 100644 --- a/src/Base/Uuid.h +++ b/src/Base/Uuid.h @@ -30,7 +30,7 @@ #include #ifndef FC_GLOBAL_H -#include +# include #endif namespace Base diff --git a/src/Base/Vector3D.cpp b/src/Base/Vector3D.cpp index 6072b51044..d1e625c48a 100644 --- a/src/Base/Vector3D.cpp +++ b/src/Base/Vector3D.cpp @@ -185,8 +185,10 @@ Vector3 Vector3::Cross(const Vector3& rcVct) } template -bool Vector3::IsOnLineSegment(const Vector3& startVct, - const Vector3& endVct) const +bool Vector3::IsOnLineSegment( + const Vector3& startVct, + const Vector3& endVct +) const { Vector3 vectorAB = endVct - startVct; Vector3 vectorAC = *this - startVct; @@ -252,8 +254,10 @@ bool Vector3::IsNormal(const Vector3& rclDir, float_type } template -Vector3& Vector3::ProjectToPlane(const Vector3& rclBase, - const Vector3& rclNorm) +Vector3& Vector3::ProjectToPlane( + const Vector3& rclBase, + const Vector3& rclNorm +) { Vector3 clTemp(rclNorm); *this = *this - (clTemp *= ((*this - rclBase) * clTemp) / clTemp.Sqr()); @@ -261,17 +265,21 @@ Vector3& Vector3::ProjectToPlane(const Vector3 -void Vector3::ProjectToPlane(const Vector3& rclBase, - const Vector3& rclNorm, - Vector3& rclProj) const +void Vector3::ProjectToPlane( + const Vector3& rclBase, + const Vector3& rclNorm, + Vector3& rclProj +) const { Vector3 clTemp(rclNorm); rclProj = *this - (clTemp *= ((*this - rclBase) * clTemp) / clTemp.Sqr()); } template -float_type Vector3::DistanceToPlane(const Vector3& rclBase, - const Vector3& rclNorm) const +float_type Vector3::DistanceToPlane( + const Vector3& rclBase, + const Vector3& rclNorm +) const { return ((*this - rclBase) * rclNorm) / rclNorm.Length(); } @@ -283,8 +291,10 @@ float_type Vector3::Length() const } template -float_type Vector3::DistanceToLine(const Vector3& base, - const Vector3& dir) const +float_type Vector3::DistanceToLine( + const Vector3& base, + const Vector3& dir +) const { // clang-format off return static_cast(std::fabs((dir % Vector3(*this - base)).Length() / dir.Length())); @@ -292,8 +302,10 @@ float_type Vector3::DistanceToLine(const Vector3& base, } template -Vector3 Vector3::DistanceToLineSegment(const Vector3& rclP1, - const Vector3& rclP2) const +Vector3 Vector3::DistanceToLineSegment( + const Vector3& rclP1, + const Vector3& rclP2 +) const { float_type len2 = Base::DistanceP2(rclP1, rclP2); if (len2 == 0) { @@ -309,15 +321,19 @@ Vector3 Vector3::DistanceToLineSegment(const Vector3& rc } template -Vector3& Vector3::ProjectToLine(const Vector3& rclPoint, - const Vector3& rclLine) +Vector3& Vector3::ProjectToLine( + const Vector3& rclPoint, + const Vector3& rclLine +) { return (*this = ((((rclPoint * rclLine) / rclLine.Sqr()) * rclLine) - rclPoint)); } template -Vector3 Vector3::Perpendicular(const Vector3& rclBase, - const Vector3& rclDir) const +Vector3 Vector3::Perpendicular( + const Vector3& rclBase, + const Vector3& rclDir +) const { float_type t = ((*this - rclBase) * rclDir) / (rclDir * rclDir); return rclBase + t * rclDir; @@ -490,9 +506,11 @@ float_type Vector3::GetAngleOriented(const Vector3& rcVect, const Ve } template -void Vector3::TransformToCoordinateSystem(const Vector3& rclBase, - const Vector3& rclDirX, - const Vector3& rclDirY) +void Vector3::TransformToCoordinateSystem( + const Vector3& rclBase, + const Vector3& rclDirX, + const Vector3& rclDirY +) { Vector3 clVectX; Vector3 clVectY; diff --git a/src/Base/Vector3D.h b/src/Base/Vector3D.h index af93a5404d..61cdaee86d 100644 --- a/src/Base/Vector3D.h +++ b/src/Base/Vector3D.h @@ -144,8 +144,10 @@ public: //@} /// Check if Vector is on a line segment - [[nodiscard]] bool IsOnLineSegment(const Vector3& startVct, - const Vector3& endVct) const; + [[nodiscard]] bool IsOnLineSegment( + const Vector3& startVct, + const Vector3& endVct + ) const; /** @name Modification */ //@{ @@ -184,9 +186,11 @@ public: * vector \a vector rclDirX and vector \a vector rclDirY. * \note \a rclDirX must be perpendicular to \a rclDirY, i.e. \a rclDirX * \a rclDirY = 0.. */ - void TransformToCoordinateSystem(const Vector3& rclBase, - const Vector3& rclDirX, - const Vector3& rclDirY); + void TransformToCoordinateSystem( + const Vector3& rclBase, + const Vector3& rclDirX, + const Vector3& rclDirY + ); /** * @brief IsEqual * @param rclPnt @@ -248,8 +252,7 @@ Vector3 const Vector3::UnitZ(0.0, 0.0, 1.0); /// Returns the distance between two points template -[[nodiscard]] inline float_type Distance(const Vector3& v1, - const Vector3& v2) +[[nodiscard]] inline float_type Distance(const Vector3& v1, const Vector3& v2) { float_type x = v1.x - v2.x; float_type y = v1.y - v2.y; @@ -259,8 +262,7 @@ template /// Returns the squared distance between two points template -[[nodiscard]] inline float_type DistanceP2(const Vector3& v1, - const Vector3& v2) +[[nodiscard]] inline float_type DistanceP2(const Vector3& v1, const Vector3& v2) { float_type x = v1.x - v2.x; float_type y = v1.y - v2.y; @@ -270,8 +272,7 @@ template /// Multiplication of scalar with vector. template -[[nodiscard]] inline Vector3 operator*(float_type fFac, - const Vector3& rcVct) +[[nodiscard]] inline Vector3 operator*(float_type fFac, const Vector3& rcVct) { return Vector3(rcVct.x * fFac, rcVct.y * fFac, rcVct.z * fFac); } diff --git a/src/Base/VectorPyImp.cpp b/src/Base/VectorPyImp.cpp index 4fd0611b2e..d59383e2cb 100644 --- a/src/Base/VectorPyImp.cpp +++ b/src/Base/VectorPyImp.cpp @@ -268,9 +268,11 @@ PyObject* VectorPy::mapping_subscript(PyObject* self, PyObject* item) } } - PyErr_Format(PyExc_TypeError, - "Vector indices must be integers or slices, not %.200s", - Py_TYPE(item)->tp_name); + PyErr_Format( + PyExc_TypeError, + "Vector indices must be integers or slices, not %.200s", + Py_TYPE(item)->tp_name + ); return nullptr; } @@ -740,10 +742,12 @@ PyObject* VectorPy::number_divide_handler(PyObject* self, PyObject* other) // slots of the PyNumberMethods structure. So, it must be explicitly // filered out here. if (PyObject_TypeCheck(other, &(VectorPy::Type))) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for /: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for /: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } @@ -758,44 +762,51 @@ PyObject* VectorPy::number_divide_handler(PyObject* self, PyObject* other) return new VectorPy(vec); } - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for /: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for /: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_remainder_handler(PyObject* self, PyObject* other) { - if (PyObject_TypeCheck(self, &(VectorPy::Type)) - && PyObject_TypeCheck(other, &(VectorPy::Type))) { + if (PyObject_TypeCheck(self, &(VectorPy::Type)) && PyObject_TypeCheck(other, &(VectorPy::Type))) { Vector3d a = static_cast(self)->value(); Vector3d b = static_cast(other)->value(); return new VectorPy(a % b); } - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for %%: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for %%: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_divmod_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for divmod(): '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for divmod(): '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_power_handler(PyObject* self, PyObject* other, PyObject* /*arg*/) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for ** or pow(): '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for ** or pow(): '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } @@ -848,61 +859,75 @@ PyObject* VectorPy::number_invert_handler(PyObject* self) PyObject* VectorPy::number_lshift_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for <<: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for <<: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_rshift_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for >>: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for >>: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_and_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for &: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for &: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_xor_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for ^: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for ^: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_or_handler(PyObject* self, PyObject* other) { - PyErr_Format(PyExc_TypeError, - "unsupported operand type(s) for |: '%s' and '%s'", - Py_TYPE(self)->tp_name, - Py_TYPE(other)->tp_name); + PyErr_Format( + PyExc_TypeError, + "unsupported operand type(s) for |: '%s' and '%s'", + Py_TYPE(self)->tp_name, + Py_TYPE(other)->tp_name + ); return nullptr; } PyObject* VectorPy::number_int_handler(PyObject* self) { - PyErr_Format(PyExc_TypeError, - "int() argument must be a string or a number, not '%s'", - Py_TYPE(self)->tp_name); + PyErr_Format( + PyExc_TypeError, + "int() argument must be a string or a number, not '%s'", + Py_TYPE(self)->tp_name + ); return nullptr; } PyObject* VectorPy::number_float_handler(PyObject* self) { - PyErr_Format(PyExc_TypeError, - "float() argument must be a string or a number, not '%s'", - Py_TYPE(self)->tp_name); + PyErr_Format( + PyExc_TypeError, + "float() argument must be a string or a number, not '%s'", + Py_TYPE(self)->tp_name + ); return nullptr; } diff --git a/src/Base/ViewProj.cpp b/src/Base/ViewProj.cpp index 298de448eb..8475d8d75b 100644 --- a/src/Base/ViewProj.cpp +++ b/src/Base/ViewProj.cpp @@ -121,8 +121,9 @@ void perspectiveTransform(const Base::Matrix4D& mat, Vec& pnt) double m31 = mat[3][1]; double m32 = mat[3][2]; double m33 = mat[3][3]; - double ww = (static_cast(pnt.x) * m30 + static_cast(pnt.y) * m31 - + static_cast(pnt.z) * m32 + m33); + double ww + = (static_cast(pnt.x) * m30 + static_cast(pnt.y) * m31 + + static_cast(pnt.z) * m32 + m33); mat.multVec(pnt, pnt); pnt /= static_cast(ww); diff --git a/src/Base/Writer.h b/src/Base/Writer.h index 73bce3791c..9ae1031f7b 100644 --- a/src/Base/Writer.h +++ b/src/Base/Writer.h @@ -59,8 +59,9 @@ private: class UniqueFileNameManager: public UniqueNameManager { protected: - std::string::const_reverse_iterator - getNameSuffixStartPosition(const std::string& name) const override + std::string::const_reverse_iterator getNameSuffixStartPosition( + const std::string& name + ) const override { // This is an awkward way to do this, because the FileInfo class only yields pieces of // the path, not delimiter positions. We can't just use fi.extension().size() because diff --git a/src/Base/XMLTools.cpp b/src/Base/XMLTools.cpp index 5d287c01b1..1f76cc55dc 100644 --- a/src/Base/XMLTools.cpp +++ b/src/Base/XMLTools.cpp @@ -30,7 +30,7 @@ #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER using namespace XERCES_CPP_NAMESPACE; #else XERCES_CPP_NAMESPACE_USE @@ -42,11 +42,10 @@ void XMLTools::initialize() { if (!transcoder) { XMLTransService::Codes res {}; - transcoder.reset(XMLPlatformUtils::fgTransService->makeNewTranscoderFor( - XMLRecognizer::UTF_8, - res, - 4096, - XMLPlatformUtils::fgMemoryManager)); + transcoder.reset( + XMLPlatformUtils::fgTransService + ->makeNewTranscoderFor(XMLRecognizer::UTF_8, res, 4096, XMLPlatformUtils::fgMemoryManager) + ); if (res != XMLTransService::Ok) { throw Base::UnicodeError("Can't create transcoder"); } @@ -67,12 +66,14 @@ std::string XMLTools::toStdString(const XMLCh* const toTranscode) XMLSize_t inputLength = XMLString::stringLen(toTranscode); while (inputLength) { - outputLength = transcoder->transcodeTo(toTranscode + offset, - inputLength, - outBuff, - 128, - eaten, - XMLTranscoder::UnRep_RepChar); + outputLength = transcoder->transcodeTo( + toTranscode + offset, + inputLength, + outBuff, + 128, + eaten, + XMLTranscoder::UnRep_RepChar + ); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) str.append(reinterpret_cast(outBuff), outputLength); offset += eaten; @@ -106,12 +107,8 @@ std::basic_string XMLTools::toXMLString(const char* const fromTranscode) unsigned char* charSizes = new unsigned char[inputLength]; while (inputLength) { - outputLength = transcoder->transcodeFrom(xmlBytes + offset, - inputLength, - outBuff, - 128, - eaten, - charSizes); + outputLength + = transcoder->transcodeFrom(xmlBytes + offset, inputLength, outBuff, 128, eaten, charSizes); str.append(outBuff, outputLength); offset += eaten; inputLength -= eaten; @@ -133,9 +130,11 @@ void XMLTools::terminate() void* XStrMemoryManager::allocate(XMLSize_t size) { - auto ptr = ::operator new(static_cast(size), - static_cast(alignof(XMLCh)), - std::nothrow); + auto ptr = ::operator new( + static_cast(size), + static_cast(alignof(XMLCh)), + std::nothrow + ); if (ptr == nullptr && size != 0) { throw XERCES_CPP_NAMESPACE::OutOfMemoryException(); } diff --git a/src/Base/XMLTools.h b/src/Base/XMLTools.h index 414aac5dd6..066174baa1 100644 --- a/src/Base/XMLTools.h +++ b/src/Base/XMLTools.h @@ -35,7 +35,7 @@ #include #ifndef XERCES_CPP_NAMESPACE_BEGIN -#define XERCES_CPP_NAMESPACE_QUALIFIER +# define XERCES_CPP_NAMESPACE_QUALIFIER namespace XERCES_CPP_NAMESPACE { class DOMNode; @@ -171,8 +171,7 @@ class XStr public: /// Constructors and Destructor explicit XStr(const char* const toTranscode); - explicit XStr(const char* const toTranscode, - XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* memMgr); + explicit XStr(const char* const toTranscode, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* memMgr); ~XStr(); @@ -191,8 +190,7 @@ inline XStr::XStr(const char* const toTranscode) : XStr(toTranscode, XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager) {} -inline XStr::XStr(const char* const toTranscode, - XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* memMgr) +inline XStr::XStr(const char* const toTranscode, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* memMgr) : fUnicodeForm(XERCES_CPP_NAMESPACE_QUALIFIER XMLString::transcode(toTranscode, memMgr)) , memMgr(memMgr) {} @@ -208,11 +206,11 @@ inline XStr::~XStr() // XStrLiteral macro use local memory manager instance to prevent segfault on releasing cached // string because xerces default memory manager is already deleted when destructing local static // variable. -#define XStrLiteral(literal) \ - ([]() -> const XStr& { \ - static XStrMemoryManager memMgr; \ - static const XStr str {literal, &memMgr}; \ - return str; \ +#define XStrLiteral(literal) \ + ([]() -> const XStr& { \ + static XStrMemoryManager memMgr; \ + static const XStr str {literal, &memMgr}; \ + return str; \ }()) @@ -254,10 +252,10 @@ inline XUTF8Str::~XUTF8Str() = default; // Uses the compiler to create a cache of transcoded string literals so that each subsequent call // can reuse the data from the lambda's initial creation. Permits the same usage as // XStr("literal").unicodeForm() -#define XUTF8StrLiteral(literal) \ - ([]() -> const XUTF8Str& { \ - static const XUTF8Str str {literal}; \ - return str; \ +#define XUTF8StrLiteral(literal) \ + ([]() -> const XUTF8Str& { \ + static const XUTF8Str str {literal}; \ + return str; \ }()) // ----------------------------------------------------------------------- diff --git a/src/Base/ZipHeader.cpp b/src/Base/ZipHeader.cpp index 24a4fe9c5c..188052b35a 100644 --- a/src/Base/ZipHeader.cpp +++ b/src/Base/ZipHeader.cpp @@ -72,8 +72,8 @@ std::istream* ZipHeader::getInputStream(const std::string& entry_name, MatchPath return new zipios::ZipInputStream( _input, - static_cast(ent.get())->getLocalHeaderOffset() - + _vs.startOffset()); + static_cast(ent.get())->getLocalHeaderOffset() + _vs.startOffset() + ); } bool ZipHeader::init(std::istream& _zipfile) @@ -108,15 +108,19 @@ bool ZipHeader::readCentralDirectory(std::istream& _zipfile) if (!_zipfile) { if (_zipfile.bad()) { throw zipios::IOException( - "Error reading zip file while reading zip file central directory"); + "Error reading zip file while reading zip file central directory" + ); } if (_zipfile.fail()) { - throw zipios::FCollException("Zip file consistency problem. Failure while reading " - "zip file central directory"); + throw zipios::FCollException( + "Zip file consistency problem. Failure while reading " + "zip file central directory" + ); } if (_zipfile.eof()) { throw zipios::IOException( - "Premature end of file while reading zip file central directory"); + "Premature end of file while reading zip file central directory" + ); } } ++entry_num; @@ -128,15 +132,19 @@ bool ZipHeader::readCentralDirectory(std::istream& _zipfile) _vs.vseekg(_zipfile, 0, std::ios::end); int remaining = static_cast(_vs.vtellg(_zipfile)) - pos; if (remaining != _eocd.eocdOffSetFromEnd()) { - throw zipios::FCollException("Zip file consistency problem. Zip file data fields are " - "inconsistent with zip file layout"); + throw zipios::FCollException( + "Zip file consistency problem. Zip file data fields are " + "inconsistent with zip file layout" + ); } // Consistency check 2, are local headers consistent with // cd headers if (!confirmLocalHeaders(_zipfile)) { - throw zipios::FCollException("Zip file consistency problem. Zip file data fields are " - "inconsistent with zip file layout"); + throw zipios::FCollException( + "Zip file consistency problem. Zip file data fields are " + "inconsistent with zip file layout" + ); } return true; diff --git a/src/Base/swigpyrun.cpp b/src/Base/swigpyrun.cpp index ba5efd87fe..fa43c9df96 100644 --- a/src/Base/swigpyrun.cpp +++ b/src/Base/swigpyrun.cpp @@ -25,26 +25,26 @@ #include #if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-register" -#pragma clang diagnostic ignored "-Wdeprecated-declarations" -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#pragma GCC diagnostic ignored "-Wcast-function-type" -#endif -#include "PyExport.h" -#include "Exception.h" +# if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wdeprecated-register" +# pragma clang diagnostic ignored "-Wdeprecated-declarations" +# elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmissing-field-initializers" +# pragma GCC diagnostic ignored "-Wcast-function-type" +# endif +# include "PyExport.h" +# include "Exception.h" namespace Swig_python { -#define SWIG_PYTHON_NO_BUILD_NONE -#include -#include "swigpyrun.inl" +# define SWIG_PYTHON_NO_BUILD_NONE +# include +# include "swigpyrun.inl" } // namespace Swig_python -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif +# if defined(__clang__) +# pragma clang diagnostic pop +# elif defined(__GNUC__) +# pragma GCC diagnostic pop +# endif #endif // HAVE_SWIG diff --git a/src/Gui/3Dconnexion/GuiAbstractNativeEvent.cpp b/src/Gui/3Dconnexion/GuiAbstractNativeEvent.cpp index f14e8a1f9c..0edf2703c7 100644 --- a/src/Gui/3Dconnexion/GuiAbstractNativeEvent.cpp +++ b/src/Gui/3Dconnexion/GuiAbstractNativeEvent.cpp @@ -24,13 +24,13 @@ #include "GuiApplicationNativeEventAware.h" -std::vector Gui::GuiAbstractNativeEvent::motionDataArray(6,0); +std::vector Gui::GuiAbstractNativeEvent::motionDataArray(6, 0); Gui::GUIApplicationNativeEventAware* Gui::GuiAbstractNativeEvent::mainApp; -Gui::GuiAbstractNativeEvent::GuiAbstractNativeEvent(GUIApplicationNativeEventAware *app) - : QObject(app) +Gui::GuiAbstractNativeEvent::GuiAbstractNativeEvent(GUIApplicationNativeEventAware* app) + : QObject(app) { - mainApp = app; + mainApp = app; } Gui::GuiAbstractNativeEvent::~GuiAbstractNativeEvent() diff --git a/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h b/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h index 1c0c5534c2..abc572073a 100644 --- a/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h +++ b/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h @@ -30,24 +30,26 @@ class QMainWindow; namespace Gui { - class GUIApplicationNativeEventAware; +class GUIApplicationNativeEventAware; - class GuiAbstractNativeEvent : public QObject - { +class GuiAbstractNativeEvent: public QObject +{ Q_OBJECT - public: - explicit GuiAbstractNativeEvent(GUIApplicationNativeEventAware *app); - ~GuiAbstractNativeEvent() override =0; - virtual void initSpaceball(QMainWindow *window)=0; - private: - GuiAbstractNativeEvent(); - GuiAbstractNativeEvent(const GuiAbstractNativeEvent&); - GuiAbstractNativeEvent& operator=(const GuiAbstractNativeEvent&); - protected: - static GUIApplicationNativeEventAware *mainApp; - static std::vectormotionDataArray; - }; -} +public: + explicit GuiAbstractNativeEvent(GUIApplicationNativeEventAware* app); + ~GuiAbstractNativeEvent() override = 0; + virtual void initSpaceball(QMainWindow* window) = 0; + +private: + GuiAbstractNativeEvent(); + GuiAbstractNativeEvent(const GuiAbstractNativeEvent&); + GuiAbstractNativeEvent& operator=(const GuiAbstractNativeEvent&); + +protected: + static GUIApplicationNativeEventAware* mainApp; + static std::vector motionDataArray; +}; +} // namespace Gui -#endif //GUIABSTRACTNATIVEEVENT_H +#endif // GUIABSTRACTNATIVEEVENT_H diff --git a/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp b/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp index 6cec21e5d0..8a93dfd233 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventLinux.cpp @@ -32,27 +32,32 @@ #include -Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware *app) -: GuiAbstractNativeEvent(app) -{ -} +Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware* app) + : GuiAbstractNativeEvent(app) +{} Gui::GuiNativeEvent::~GuiNativeEvent() { - if (spnav_close()) + if (spnav_close()) { Base::Console().log("Couldn't disconnect from spacenav daemon\n"); - else + } + else { Base::Console().log("Disconnected from spacenav daemon\n"); + } } -void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) +void Gui::GuiNativeEvent::initSpaceball(QMainWindow* window) { Q_UNUSED(window) if (spnav_open() == -1) { - Base::Console().log("Couldn't connect to spacenav daemon. Please ignore if you don't have a spacemouse.\n"); - } else { + Base::Console().log( + "Couldn't connect to spacenav daemon. Please ignore if you don't have a spacemouse.\n" + ); + } + else { Base::Console().log("Connected to spacenav daemon\n"); - QSocketNotifier* SpacenavNotifier = new QSocketNotifier(spnav_fd(), QSocketNotifier::Read, this); + QSocketNotifier* SpacenavNotifier + = new QSocketNotifier(spnav_fd(), QSocketNotifier::Read, this); connect(SpacenavNotifier, SIGNAL(activated(int)), this, SLOT(pollSpacenav())); mainApp->setSpaceballPresent(true); } @@ -61,12 +66,9 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) void Gui::GuiNativeEvent::pollSpacenav() { spnav_event ev; - while(spnav_poll_event(&ev)) - { - switch (ev.type) - { - case SPNAV_EVENT_MOTION: - { + while (spnav_poll_event(&ev)) { + switch (ev.type) { + case SPNAV_EVENT_MOTION: { motionDataArray[0] = -ev.motion.x; motionDataArray[1] = -ev.motion.z; motionDataArray[2] = -ev.motion.y; @@ -76,8 +78,7 @@ void Gui::GuiNativeEvent::pollSpacenav() mainApp->postMotionEvent(motionDataArray); break; } - case SPNAV_EVENT_BUTTON: - { + case SPNAV_EVENT_BUTTON: { mainApp->postButtonEvent(ev.button.bnum, ev.button.press); break; } diff --git a/src/Gui/3Dconnexion/GuiNativeEventLinux.h b/src/Gui/3Dconnexion/GuiNativeEventLinux.h index d609e7ae55..d82ee12b24 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventLinux.h +++ b/src/Gui/3Dconnexion/GuiNativeEventLinux.h @@ -29,23 +29,23 @@ class QMainWindow; namespace Gui { - class GUIApplicationNativeEventAware; +class GUIApplicationNativeEventAware; - class GuiNativeEvent : public GuiAbstractNativeEvent - { +class GuiNativeEvent: public GuiAbstractNativeEvent +{ Q_OBJECT - public: - GuiNativeEvent(GUIApplicationNativeEventAware *app); - ~GuiNativeEvent() override; - void initSpaceball(QMainWindow *window) override final; - private: - GuiNativeEvent(); - GuiNativeEvent(const GuiNativeEvent&); - GuiNativeEvent& operator=(const GuiNativeEvent&); - private Q_SLOTS: - void pollSpacenav(); - }; -} +public: + GuiNativeEvent(GUIApplicationNativeEventAware* app); + ~GuiNativeEvent() override; + void initSpaceball(QMainWindow* window) override final; -#endif //GUINATIVEEVENT_H +private: + GuiNativeEvent(); + GuiNativeEvent(const GuiNativeEvent&); + GuiNativeEvent& operator=(const GuiNativeEvent&); +private Q_SLOTS: + void pollSpacenav(); +}; +} // namespace Gui +#endif // GUINATIVEEVENT_H diff --git a/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp b/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp index 97d2cbb153..83b218c571 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.cpp @@ -50,40 +50,44 @@ #undef Complex -Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware *app) -: GuiAbstractNativeEvent(app) -{ -} +Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware* app) + : GuiAbstractNativeEvent(app) +{} Gui::GuiNativeEvent::~GuiNativeEvent() { - if (spnav_close()) + if (spnav_close()) { Base::Console().log("Couldn't disconnect from spacenav daemon\n"); - else + } + else { Base::Console().log("Disconnected from spacenav daemon\n"); + } } -void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) +void Gui::GuiNativeEvent::initSpaceball(QMainWindow* window) { if (!QX11Info::isPlatformX11()) { Base::Console().log("Application is not running on X11\n"); return; } if (spnav_x11_open(QX11Info::display(), window->winId()) == -1) { - Base::Console().log("Couldn't connect to spacenav daemon on X11. Please ignore if you don't have a spacemouse.\n"); - } else { + Base::Console() + .log("Couldn't connect to spacenav daemon on X11. Please ignore if you don't have a spacemouse.\n"); + } + else { Base::Console().log("Connected to spacenav daemon on X11\n"); mainApp->setSpaceballPresent(true); mainApp->installNativeEventFilter(new Gui::RawInputEventFilter(&xcbEventFilter)); } } -bool Gui::GuiNativeEvent::xcbEventFilter(void *xcb_void, long* result) +bool Gui::GuiNativeEvent::xcbEventFilter(void* xcb_void, long* result) { Q_UNUSED(result); - auto inst(dynamic_cast(QApplication::instance())); - if (!inst) - return false; + auto inst(dynamic_cast(QApplication::instance())); + if (!inst) { + return false; + } spnav_event navEvent; @@ -97,23 +101,23 @@ bool Gui::GuiNativeEvent::xcbEventFilter(void *xcb_void, long* result) xev.type = ClientMessage; xev.message_type = xcb_ev->type; memcpy(xev.data.b, xcb_ev->data.data8, sizeof(xev.data.b)); - xev.serial = 0; // These are just to squash warnings... + xev.serial = 0; // These are just to squash warnings... xev.send_event = 0; xev.display = 0; xev.window = 0; xev.format = 0; - if (!spnav_x11_event(reinterpret_cast(&xev), &navEvent)) { + if (!spnav_x11_event(reinterpret_cast(&xev), &navEvent)) { return false; } - } else { + } + else { return false; } // navEvent is now initialised switch (navEvent.type) { - case SPNAV_EVENT_MOTION: - { + case SPNAV_EVENT_MOTION: { motionDataArray[0] = -navEvent.motion.x; motionDataArray[1] = -navEvent.motion.z; motionDataArray[2] = -navEvent.motion.y; @@ -125,13 +129,13 @@ bool Gui::GuiNativeEvent::xcbEventFilter(void *xcb_void, long* result) return true; } - case SPNAV_EVENT_BUTTON: - { + case SPNAV_EVENT_BUTTON: { auto buttonEvent(new Spaceball::ButtonEvent()); buttonEvent->setButtonNumber(navEvent.button.bnum); if (navEvent.button.press) { buttonEvent->setButtonStatus(Spaceball::BUTTON_PRESSED); - } else { + } + else { buttonEvent->setButtonStatus(Spaceball::BUTTON_RELEASED); } inst->postButtonEvent(navEvent.button.bnum, navEvent.button.press); @@ -140,7 +144,7 @@ bool Gui::GuiNativeEvent::xcbEventFilter(void *xcb_void, long* result) default: Base::Console().log("Unknown spaceball event\n"); return true; - } // end switch (navEvent.type) { + } // end switch (navEvent.type) { } #include "3Dconnexion/moc_GuiNativeEventLinuxX11.cpp" diff --git a/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.h b/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.h index e3456cedb0..925b729a25 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.h +++ b/src/Gui/3Dconnexion/GuiNativeEventLinuxX11.h @@ -35,23 +35,24 @@ class GUIApplicationNativeEventAware; namespace Gui { - class GUIApplicationNativeEventAware; +class GUIApplicationNativeEventAware; - class GuiNativeEvent : public GuiAbstractNativeEvent - { +class GuiNativeEvent: public GuiAbstractNativeEvent +{ Q_OBJECT - public: - GuiNativeEvent(GUIApplicationNativeEventAware *app); - ~GuiNativeEvent() override; - void initSpaceball(QMainWindow *window) override final; - private: - GuiNativeEvent(); - GuiNativeEvent(const GuiNativeEvent&); - GuiNativeEvent& operator=(const GuiNativeEvent&); - public: - static bool xcbEventFilter(void *message, long* result); - }; -} +public: + GuiNativeEvent(GUIApplicationNativeEventAware* app); + ~GuiNativeEvent() override; + void initSpaceball(QMainWindow* window) override final; -#endif //GUINATIVEEVENT_H +private: + GuiNativeEvent(); + GuiNativeEvent(const GuiNativeEvent&); + GuiNativeEvent& operator=(const GuiNativeEvent&); +public: + static bool xcbEventFilter(void* message, long* result); +}; +} // namespace Gui + +#endif // GUINATIVEEVENT_H diff --git a/src/Gui/3Dconnexion/GuiNativeEventMac.cpp b/src/Gui/3Dconnexion/GuiNativeEventMac.cpp index 776a05b9c3..e0c2109509 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventMac.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventMac.cpp @@ -25,9 +25,9 @@ Development tools and related technology provided under license from 3Dconnexion (c) 1992 - 2012 3Dconnexion. All rights reserved */ - /* +/* With special thanks to marcxs for making the first steps - */ +*/ #include #include "GuiNativeEventMac.h" @@ -51,10 +51,11 @@ uint32_t Gui::GuiNativeEvent::lastButtons = 0; them directly, (3) write the event info in a shared memory location for usage by reader threads. */ -void -Gui::GuiNativeEvent::tdx_drv_handler(io_connect_t connection, - natural_t messageType, - void *messageArgument) +void Gui::GuiNativeEvent::tdx_drv_handler( + io_connect_t connection, + natural_t messageType, + void* messageArgument +) { static bool firstTime = true; if (firstTime) { @@ -62,113 +63,114 @@ Gui::GuiNativeEvent::tdx_drv_handler(io_connect_t connection, Base::Console().log("Call connexion handler\n"); } Q_UNUSED(connection) - //printf("tdx_drv_handler\n"); - //printf("connection: %X\n", connection); - //printf("messageType %c%c%c%c\n", messageType/0x1000000, messageType/0x10000, messageType/0x100, messageType); + // printf("tdx_drv_handler\n"); + // printf("connection: %X\n", connection); + // printf("messageType %c%c%c%c\n", messageType/0x1000000, messageType/0x10000, + // messageType/0x100, messageType); auto msg = (ConnexionDeviceStatePtr)messageArgument; - switch(messageType) { - case kConnexionMsgDeviceState: - /* Device state messages are broadcast to all clients. It is up to - * the client to figure out if the message is meant for them. This - * is done by comparing the "client" id sent in the message to our - * assigned id when the connection to the driver was established. - */ - //printf("msg->client: %d, tdxClientID: %d\n", msg->client, tdxClientID); - Base::Console().log("msg->client: %d, msg->command: %d\n", msg->client, msg->command); + switch (messageType) { + case kConnexionMsgDeviceState: + /* Device state messages are broadcast to all clients. It is up to + * the client to figure out if the message is meant for them. This + * is done by comparing the "client" id sent in the message to our + * assigned id when the connection to the driver was established. + */ + // printf("msg->client: %d, tdxClientID: %d\n", msg->client, tdxClientID); + Base::Console().log("msg->client: %d, msg->command: %d\n", msg->client, msg->command); - if (msg->client == tdxClientID) { - switch (msg->command) { - case kConnexionCmdHandleAxis: - { - motionDataArray[0] = -msg->axis[0]; - motionDataArray[1] = msg->axis[1]; - motionDataArray[2] = msg->axis[2]; - motionDataArray[3] = -msg->axis[3]; - motionDataArray[4] = msg->axis[4]; - motionDataArray[5] = msg->axis[5]; - mainApp->postMotionEvent(motionDataArray); - break; + if (msg->client == tdxClientID) { + switch (msg->command) { + case kConnexionCmdHandleAxis: { + motionDataArray[0] = -msg->axis[0]; + motionDataArray[1] = msg->axis[1]; + motionDataArray[2] = msg->axis[2]; + motionDataArray[3] = -msg->axis[3]; + motionDataArray[4] = msg->axis[4]; + motionDataArray[5] = msg->axis[5]; + mainApp->postMotionEvent(motionDataArray); + break; + } + + case kConnexionCmdHandleButtons: { + // printf("value: %d\n", msg->value); + // printf("buttons: %u\n", msg->buttons); + uint32_t changedButtons = msg->buttons ^ lastButtons; + uint32_t pressedButtons = msg->buttons & changedButtons; + uint32_t releasedButtons = lastButtons & changedButtons; + for (uint8_t bt = 0; bt < 32; bt++) { + if (pressedButtons & 1) { + mainApp->postButtonEvent(bt, 1); + } + pressedButtons = pressedButtons >> 1; + } + for (uint8_t bt = 0; bt < 32; bt++) { + if (releasedButtons & 1) { + mainApp->postButtonEvent(bt, 0); + } + releasedButtons = releasedButtons >> 1; + } + + lastButtons = msg->buttons; + break; + } + + default: + break; + + } /* switch */ } + break; - case kConnexionCmdHandleButtons: - { - //printf("value: %d\n", msg->value); - //printf("buttons: %u\n", msg->buttons); - uint32_t changedButtons = msg->buttons ^ lastButtons; - uint32_t pressedButtons = msg->buttons & changedButtons; - uint32_t releasedButtons = lastButtons & changedButtons; - for (uint8_t bt = 0; bt < 32; bt++) { - if (pressedButtons & 1) - mainApp->postButtonEvent(bt, 1); - pressedButtons = pressedButtons >> 1; - } - for (uint8_t bt = 0; bt < 32; bt++) { - if (releasedButtons & 1) - mainApp->postButtonEvent(bt, 0); - releasedButtons = releasedButtons >> 1; - } - - lastButtons = msg->buttons; - break; - } - - default: - break; - - } /* switch */ - } - break; - - default: - /* other messageTypes can happen and should be ignored */ - break; + default: + /* other messageTypes can happen and should be ignored */ + break; } } -Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware *app) -: GuiAbstractNativeEvent(app) -{ -} +Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware* app) + : GuiAbstractNativeEvent(app) +{} Gui::GuiNativeEvent::~GuiNativeEvent() { // if 3Dconnexion library was loaded at runtime if (InstallConnexionHandlers) { // Close our connection with the 3dx driver - if (tdxClientID) + if (tdxClientID) { UnregisterConnexionClient(tdxClientID); + } CleanupConnexionHandlers(); Base::Console().log("Disconnected from 3Dconnexion driver\n"); } } -void Gui::GuiNativeEvent::initSpaceball(QMainWindow *window) +void Gui::GuiNativeEvent::initSpaceball(QMainWindow* window) { Q_UNUSED(window) OSStatus err; /* make sure the framework is installed */ - if (SetConnexionHandlers == NULL) - { + if (SetConnexionHandlers == NULL) { Base::Console().log("3Dconnexion framework not found!\n"); return; } /* install 3dx message handler in order to receive driver events */ err = SetConnexionHandlers(tdx_drv_handler, 0L, 0L, false); assert(err == 0); - if (err) - { + if (err) { Base::Console().log("Error installing 3Dconnexion handler\n"); return; } /* register our app with the driver */ // Pascal string Application name required to register driver for application - UInt8 tdxAppName[] = {7,'F','r','e','e','C','A','D'}; - tdxClientID = RegisterConnexionClient( kConnexionClientWildcard, tdxAppName, - kConnexionClientModeTakeOver, - kConnexionMaskAll ); - if (tdxClientID == 0) - { + UInt8 tdxAppName[] = {7, 'F', 'r', 'e', 'e', 'C', 'A', 'D'}; + tdxClientID = RegisterConnexionClient( + kConnexionClientWildcard, + tdxAppName, + kConnexionClientModeTakeOver, + kConnexionMaskAll + ); + if (tdxClientID == 0) { Base::Console().log("Couldn't connect to 3Dconnexion driver\n"); return; } diff --git a/src/Gui/3Dconnexion/GuiNativeEventMac.h b/src/Gui/3Dconnexion/GuiNativeEventMac.h index 6158856f4e..b43d8bf6e8 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventMac.h +++ b/src/Gui/3Dconnexion/GuiNativeEventMac.h @@ -29,53 +29,54 @@ class QMainWindow; #include #include -extern int16_t SetConnexionHandlers(ConnexionMessageHandlerProc messageHandler, - ConnexionAddedHandlerProc addedHandler, - ConnexionRemovedHandlerProc removedHandler, - bool useSeparateThread) __attribute__((weak_import)); +extern int16_t SetConnexionHandlers( + ConnexionMessageHandlerProc messageHandler, + ConnexionAddedHandlerProc addedHandler, + ConnexionRemovedHandlerProc removedHandler, + bool useSeparateThread +) __attribute__((weak_import)); // Note that InstallConnexionHandlers will be replaced with // SetConnexionHandlers "in the future". -extern OSErr InstallConnexionHandlers(ConnexionMessageHandlerProc messageHandler, - ConnexionAddedHandlerProc addedHandler, - ConnexionRemovedHandlerProc removedHandler) - __attribute__((weak_import)); -extern UInt16 RegisterConnexionClient(UInt32 signature, UInt8 *name, UInt16 mode, - UInt32 mask) __attribute__((weak_import)); -extern void SetConnexionClientMask(uint16_t clientID, uint32_t mask) - __attribute__((weak_import)); +extern OSErr InstallConnexionHandlers( + ConnexionMessageHandlerProc messageHandler, + ConnexionAddedHandlerProc addedHandler, + ConnexionRemovedHandlerProc removedHandler +) __attribute__((weak_import)); +extern UInt16 RegisterConnexionClient(UInt32 signature, UInt8* name, UInt16 mode, UInt32 mask) + __attribute__((weak_import)); +extern void SetConnexionClientMask(uint16_t clientID, uint32_t mask) __attribute__((weak_import)); extern void SetConnexionClientButtonMask(uint16_t clientID, uint32_t buttonMask) - __attribute__((weak_import)); + __attribute__((weak_import)); extern void UnregisterConnexionClient(UInt16 clientID) __attribute__((weak_import)); extern void CleanupConnexionHandlers(void) __attribute__((weak_import)); -extern int16_t ConnexionControl(uint32_t message, int32_t param, int32_t *result); -extern int16_t ConnexionClientControl(uint16_t clientID, uint32_t message, int32_t param, int32_t *result); -extern int16_t ConnexionGetCurrentDevicePrefs(uint32_t deviceID, ConnexionDevicePrefs *prefs); -extern int16_t ConnexionSetButtonLabels(uint8_t *labels, uint16_t size); +extern int16_t ConnexionControl(uint32_t message, int32_t param, int32_t* result); +extern int16_t ConnexionClientControl(uint16_t clientID, uint32_t message, int32_t param, int32_t* result); +extern int16_t ConnexionGetCurrentDevicePrefs(uint32_t deviceID, ConnexionDevicePrefs* prefs); +extern int16_t ConnexionSetButtonLabels(uint8_t* labels, uint16_t size); namespace Gui { - class GUIApplicationNativeEventAware; +class GUIApplicationNativeEventAware; - class GuiNativeEvent : public GuiAbstractNativeEvent - { - Q_OBJECT - public: - explicit GuiNativeEvent(GUIApplicationNativeEventAware *app); - ~GuiNativeEvent() override; - void initSpaceball(QMainWindow *window) final; - private: - GuiNativeEvent(); - GuiNativeEvent(const GuiNativeEvent&); - GuiNativeEvent& operator=(const GuiNativeEvent&); - private: - static UInt16 tdxClientID; /* ID assigned by the driver */ - static uint32_t lastButtons; - static void tdx_drv_handler( io_connect_t connection, - natural_t messageType, - void *messageArgument ); - }; -} +class GuiNativeEvent: public GuiAbstractNativeEvent +{ + Q_OBJECT +public: + explicit GuiNativeEvent(GUIApplicationNativeEventAware* app); + ~GuiNativeEvent() override; + void initSpaceball(QMainWindow* window) final; -#endif //GUINATIVEEVENT_H +private: + GuiNativeEvent(); + GuiNativeEvent(const GuiNativeEvent&); + GuiNativeEvent& operator=(const GuiNativeEvent&); +private: + static UInt16 tdxClientID; /* ID assigned by the driver */ + static uint32_t lastButtons; + static void tdx_drv_handler(io_connect_t connection, natural_t messageType, void* messageArgument); +}; +} // namespace Gui + +#endif // GUINATIVEEVENT_H diff --git a/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp b/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp index 8de57e1846..9068622165 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp +++ b/src/Gui/3Dconnexion/GuiNativeEventWin32.cpp @@ -57,11 +57,11 @@ Gui::GuiNativeEvent* Gui::GuiNativeEvent::gMouseInput = 0; #include #define LOGITECH_VENDOR_ID 0x46d -#define CONNEXION_VENDOR_ID 0x256f +#define CONNEXION_VENDOR_ID 0x256f #define _CONSTANT_INPUT_PERIOD 0 #ifndef RIDEV_DEVNOTIFY -#define RIDEV_DEVNOTIFY 0x00002000 +# define RIDEV_DEVNOTIFY 0x00002000 #endif #define _TRACE_WM_INPUT_PERIOD 0 @@ -73,7 +73,7 @@ Gui::GuiNativeEvent* Gui::GuiNativeEvent::gMouseInput = 0; #ifdef _WIN64 typedef unsigned __int64 QWORD; -#endif // _WIN64 +#endif // _WIN64 static const int kTimeToLive = 5; @@ -115,145 +115,221 @@ static const int kTimeToLive = 5; Universal Receiver: USB\0x256f:0xc652 */ -enum e3dconnexion_pid { - eSpaceMousePlusXT = 0xc603, - eSpacePilot = 0xc625, - eSpaceNavigator = 0xc626, - eSpaceExplorer = 0xc627, - eSpaceNavigatorForNotebooks = 0xc628, - eSpacePilotPRO = 0xc629, - eSpaceMouseWireless = 0xc62e, - eSpaceMouseWirelessReceiver = 0xc62f, - eSpaceMousePROWireless = 0xc631, - eSpaceMousePROWirelessReceiver = 0xc632, - eSpaceMouseEnterprise = 0xc633, - eSpaceMouseCompact = 0xc635 +enum e3dconnexion_pid +{ + eSpaceMousePlusXT = 0xc603, + eSpacePilot = 0xc625, + eSpaceNavigator = 0xc626, + eSpaceExplorer = 0xc627, + eSpaceNavigatorForNotebooks = 0xc628, + eSpacePilotPRO = 0xc629, + eSpaceMouseWireless = 0xc62e, + eSpaceMouseWirelessReceiver = 0xc62f, + eSpaceMousePROWireless = 0xc631, + eSpaceMousePROWirelessReceiver = 0xc632, + eSpaceMouseEnterprise = 0xc633, + eSpaceMouseCompact = 0xc635 }; enum e3dmouse_virtual_key { - V3DK_INVALID=0 - , V3DK_MENU=1, V3DK_FIT - , V3DK_TOP, V3DK_LEFT, V3DK_RIGHT, V3DK_FRONT, V3DK_BOTTOM, V3DK_BACK - , V3DK_CW, V3DK_CCW - , V3DK_ISO1, V3DK_ISO2 - , V3DK_1, V3DK_2, V3DK_3, V3DK_4, V3DK_5, V3DK_6, V3DK_7, V3DK_8, V3DK_9, V3DK_10 - , V3DK_ESC, V3DK_ALT, V3DK_SHIFT, V3DK_CTRL - , V3DK_ROTATE, V3DK_PANZOOM, V3DK_DOMINANT - , V3DK_PLUS, V3DK_MINUS + V3DK_INVALID = 0, + V3DK_MENU = 1, + V3DK_FIT, + V3DK_TOP, + V3DK_LEFT, + V3DK_RIGHT, + V3DK_FRONT, + V3DK_BOTTOM, + V3DK_BACK, + V3DK_CW, + V3DK_CCW, + V3DK_ISO1, + V3DK_ISO2, + V3DK_1, + V3DK_2, + V3DK_3, + V3DK_4, + V3DK_5, + V3DK_6, + V3DK_7, + V3DK_8, + V3DK_9, + V3DK_10, + V3DK_ESC, + V3DK_ALT, + V3DK_SHIFT, + V3DK_CTRL, + V3DK_ROTATE, + V3DK_PANZOOM, + V3DK_DOMINANT, + V3DK_PLUS, + V3DK_MINUS }; // SpaceMouse Enterprise: map to virtual keycodes std::map mapEnterpriseKey = { - {0x0002, 0x01} // V3DK_MENU - , {0x0004, 0x02} // V3DK_FIT - , {0x0006, 0x03} // V3DK_TOP - , {0x0007, 0x04} // V3DK_BOTTOM - , {0x000A, 0x05} // V3DK_RIGHT - , {0x000B, 0x06} // V3DK_LEFT - , {0x000C, 0x07} // V3DK_FRONT - , {0x000D, 0x08} // V3DK_BACK - , {0x0012, 0x09} // V3DK_CW - , {0x0013, 0x0a} // V3DK_CCW - , {0x0016, 0x0b} // V3DK_ISO1 - , {0x0017, 0x0c} // V3DK_ISO2 - , {0x001a, 0x0d} // V3DK_1 - , {0x001c, 0x0e} // V3DK_2 - , {0x001e, 0x0f} // V3DK_3 - , {0x0020, 0x10} // V3DK_4 - , {0x0022, 0x11} // V3DK_5 - , {0x0024, 0x12} // V3DK_6 - , {0x0026, 0x13} // V3DK_7 - , {0x0028, 0x14} // V3DK_8 - , {0x002a, 0x15} // V3DK_9 - , {0x002c, 0x16} // V3DK_10 - , {0x0090, 0x17} // V3DK_11 - , {0x0092, 0x18} // V3DK_12 - , {0x002e, 0x19} // V3DK_ESC - , {0x0030, 0x1a} // V3DK_ALT - , {0x0032, 0x1b} // V3DK_SHIFT - , {0x0034, 0x1c} // V3DK_CTRL - , {0x0048, 0x1d} // V3DK_ENTER - , {0x004a, 0x1e} // V3DK_DEL - , {0x015e, 0x1f} // V3DK_TAB - , {0x0160, 0x20} // V3DK_SPACE + {0x0002, 0x01} // V3DK_MENU + , + {0x0004, 0x02} // V3DK_FIT + , + {0x0006, 0x03} // V3DK_TOP + , + {0x0007, 0x04} // V3DK_BOTTOM + , + {0x000A, 0x05} // V3DK_RIGHT + , + {0x000B, 0x06} // V3DK_LEFT + , + {0x000C, 0x07} // V3DK_FRONT + , + {0x000D, 0x08} // V3DK_BACK + , + {0x0012, 0x09} // V3DK_CW + , + {0x0013, 0x0a} // V3DK_CCW + , + {0x0016, 0x0b} // V3DK_ISO1 + , + {0x0017, 0x0c} // V3DK_ISO2 + , + {0x001a, 0x0d} // V3DK_1 + , + {0x001c, 0x0e} // V3DK_2 + , + {0x001e, 0x0f} // V3DK_3 + , + {0x0020, 0x10} // V3DK_4 + , + {0x0022, 0x11} // V3DK_5 + , + {0x0024, 0x12} // V3DK_6 + , + {0x0026, 0x13} // V3DK_7 + , + {0x0028, 0x14} // V3DK_8 + , + {0x002a, 0x15} // V3DK_9 + , + {0x002c, 0x16} // V3DK_10 + , + {0x0090, 0x17} // V3DK_11 + , + {0x0092, 0x18} // V3DK_12 + , + {0x002e, 0x19} // V3DK_ESC + , + {0x0030, 0x1a} // V3DK_ALT + , + {0x0032, 0x1b} // V3DK_SHIFT + , + {0x0034, 0x1c} // V3DK_CTRL + , + {0x0048, 0x1d} // V3DK_ENTER + , + {0x004a, 0x1e} // V3DK_DEL + , + {0x015e, 0x1f} // V3DK_TAB + , + {0x0160, 0x20} // V3DK_SPACE }; struct tag_VirtualKeys { - e3dconnexion_pid pid; - size_t nKeys; - e3dmouse_virtual_key *vkeys; + e3dconnexion_pid pid; + size_t nKeys; + e3dmouse_virtual_key* vkeys; }; -static const e3dmouse_virtual_key SpaceMouseWirelessKeys [] = -{ - V3DK_INVALID // there is no button 0 - , V3DK_1, V3DK_2 - , V3DK_TOP, V3DK_LEFT, V3DK_RIGHT, V3DK_FRONT - , V3DK_ESC, V3DK_ALT, V3DK_SHIFT, V3DK_CTRL - , V3DK_FIT, V3DK_MENU - , V3DK_PLUS, V3DK_MINUS - , V3DK_ROTATE +static const e3dmouse_virtual_key SpaceMouseWirelessKeys[] = { + V3DK_INVALID // there is no button 0 + , + V3DK_1, + V3DK_2, + V3DK_TOP, + V3DK_LEFT, + V3DK_RIGHT, + V3DK_FRONT, + V3DK_ESC, + V3DK_ALT, + V3DK_SHIFT, + V3DK_CTRL, + V3DK_FIT, + V3DK_MENU, + V3DK_PLUS, + V3DK_MINUS, + V3DK_ROTATE }; -static const e3dmouse_virtual_key SpaceMouseWirelessReceiverKeys [] = -{ - V3DK_INVALID // there is no button 0 - , V3DK_1, V3DK_2 - , V3DK_TOP, V3DK_LEFT, V3DK_RIGHT, V3DK_FRONT - , V3DK_ESC, V3DK_ALT, V3DK_SHIFT, V3DK_CTRL - , V3DK_FIT, V3DK_MENU - , V3DK_PLUS, V3DK_MINUS - , V3DK_ROTATE +static const e3dmouse_virtual_key SpaceMouseWirelessReceiverKeys[] = { + V3DK_INVALID // there is no button 0 + , + V3DK_1, + V3DK_2, + V3DK_TOP, + V3DK_LEFT, + V3DK_RIGHT, + V3DK_FRONT, + V3DK_ESC, + V3DK_ALT, + V3DK_SHIFT, + V3DK_CTRL, + V3DK_FIT, + V3DK_MENU, + V3DK_PLUS, + V3DK_MINUS, + V3DK_ROTATE }; -static const e3dmouse_virtual_key SpaceExplorerKeys [] = -{ - V3DK_INVALID // there is no button 0 - , V3DK_1, V3DK_2 - , V3DK_TOP, V3DK_LEFT, V3DK_RIGHT, V3DK_FRONT - , V3DK_ESC, V3DK_ALT, V3DK_SHIFT, V3DK_CTRL - , V3DK_FIT, V3DK_MENU - , V3DK_PLUS, V3DK_MINUS - , V3DK_ROTATE +static const e3dmouse_virtual_key SpaceExplorerKeys[] = { + V3DK_INVALID // there is no button 0 + , + V3DK_1, + V3DK_2, + V3DK_TOP, + V3DK_LEFT, + V3DK_RIGHT, + V3DK_FRONT, + V3DK_ESC, + V3DK_ALT, + V3DK_SHIFT, + V3DK_CTRL, + V3DK_FIT, + V3DK_MENU, + V3DK_PLUS, + V3DK_MINUS, + V3DK_ROTATE }; -static const e3dmouse_virtual_key SpacePilotKeys [] = -{ - V3DK_INVALID - , V3DK_1, V3DK_2, V3DK_3, V3DK_4, V3DK_5, V3DK_6 - , V3DK_TOP, V3DK_LEFT, V3DK_RIGHT, V3DK_FRONT - , V3DK_ESC, V3DK_ALT, V3DK_SHIFT, V3DK_CTRL - , V3DK_FIT, V3DK_MENU - , V3DK_PLUS, V3DK_MINUS - , V3DK_DOMINANT, V3DK_ROTATE +static const e3dmouse_virtual_key SpacePilotKeys[] = { + V3DK_INVALID, V3DK_1, V3DK_2, V3DK_3, V3DK_4, V3DK_5, V3DK_6, + V3DK_TOP, V3DK_LEFT, V3DK_RIGHT, V3DK_FRONT, V3DK_ESC, V3DK_ALT, V3DK_SHIFT, + V3DK_CTRL, V3DK_FIT, V3DK_MENU, V3DK_PLUS, V3DK_MINUS, V3DK_DOMINANT, V3DK_ROTATE }; -static const struct tag_VirtualKeys _3dmouseVirtualKeys[]= -{ - eSpacePilot - , sizeof(SpacePilotKeys)/sizeof(SpacePilotKeys[0]) - , const_cast(SpacePilotKeys), - eSpaceExplorer - , sizeof(SpaceExplorerKeys)/sizeof(SpaceExplorerKeys[0]) - , const_cast(SpaceExplorerKeys), - eSpaceMouseWireless - , sizeof(SpaceMouseWirelessKeys)/sizeof(SpaceMouseWirelessKeys[0]) - , const_cast(SpaceMouseWirelessKeys), - eSpaceMouseWirelessReceiver - , sizeof(SpaceMouseWirelessReceiverKeys)/sizeof(SpaceMouseWirelessReceiverKeys[0]) - , const_cast(SpaceMouseWirelessReceiverKeys), - eSpaceMousePROWireless - , sizeof(SpaceMouseWirelessKeys)/sizeof(SpaceMouseWirelessKeys[0]) - , const_cast(SpaceMouseWirelessKeys), - eSpaceMousePROWirelessReceiver - , sizeof(SpaceMouseWirelessReceiverKeys)/sizeof(SpaceMouseWirelessReceiverKeys[0]) - , const_cast(SpaceMouseWirelessReceiverKeys) +static const struct tag_VirtualKeys _3dmouseVirtualKeys[] = { + eSpacePilot, + sizeof(SpacePilotKeys) / sizeof(SpacePilotKeys[0]), + const_cast(SpacePilotKeys), + eSpaceExplorer, + sizeof(SpaceExplorerKeys) / sizeof(SpaceExplorerKeys[0]), + const_cast(SpaceExplorerKeys), + eSpaceMouseWireless, + sizeof(SpaceMouseWirelessKeys) / sizeof(SpaceMouseWirelessKeys[0]), + const_cast(SpaceMouseWirelessKeys), + eSpaceMouseWirelessReceiver, + sizeof(SpaceMouseWirelessReceiverKeys) / sizeof(SpaceMouseWirelessReceiverKeys[0]), + const_cast(SpaceMouseWirelessReceiverKeys), + eSpaceMousePROWireless, + sizeof(SpaceMouseWirelessKeys) / sizeof(SpaceMouseWirelessKeys[0]), + const_cast(SpaceMouseWirelessKeys), + eSpaceMousePROWirelessReceiver, + sizeof(SpaceMouseWirelessReceiverKeys) / sizeof(SpaceMouseWirelessReceiverKeys[0]), + const_cast(SpaceMouseWirelessReceiverKeys) }; -Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware *app) +Gui::GuiNativeEvent::GuiNativeEvent(Gui::GUIApplicationNativeEventAware* app) : GuiAbstractNativeEvent(app) {} @@ -265,7 +341,7 @@ Gui::GuiNativeEvent::~GuiNativeEvent() } } -void Gui::GuiNativeEvent::initSpaceball(QMainWindow *mainWindow) +void Gui::GuiNativeEvent::initSpaceball(QMainWindow* mainWindow) { mainApp->setSpaceballPresent(Is3dmouseAttached()); @@ -275,7 +351,8 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *mainWindow) if (InitializeRawInput((HWND)mainWindow->winId())) { gMouseInput = this; qApp->installNativeEventFilter( - new Gui::RawInputEventFilter(Gui::GuiNativeEvent::RawInputEventFilter)); + new Gui::RawInputEventFilter(Gui::GuiNativeEvent::RawInputEventFilter) + ); Base::Console().log("3Dconnexion device initialized.\n"); } else { @@ -290,7 +367,8 @@ void Gui::GuiNativeEvent::initSpaceball(QMainWindow *mainWindow) // Methods for windows events /*! - Converts a hid device keycode (button identifier) of a pre-2009 3Dconnexion USB device to the standard 3d mouse virtual key definition. + Converts a hid device keycode (button identifier) of a pre-2009 3Dconnexion USB device to the + standard 3d mouse virtual key definition. \a pid USB Product ID (PID) of 3D mouse device \a hidKeyCode Hid keycode as retrieved from a Raw Input packet @@ -306,10 +384,12 @@ unsigned short HidToVirtualKey(unsigned long pid, unsigned short hidKeyCode) unsigned short virtualkey = hidKeyCode; for (size_t i = 0; i < sizeof(_3dmouseVirtualKeys) / sizeof(_3dmouseVirtualKeys[0]); ++i) { if (pid == _3dmouseVirtualKeys[i].pid) { - if (hidKeyCode < _3dmouseVirtualKeys[i].nKeys) + if (hidKeyCode < _3dmouseVirtualKeys[i].nKeys) { virtualkey = _3dmouseVirtualKeys[i].vkeys[hidKeyCode]; - else + } + else { virtualkey = V3DK_INVALID; + } break; } } @@ -317,16 +397,17 @@ unsigned short HidToVirtualKey(unsigned long pid, unsigned short hidKeyCode) return virtualkey; } -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) -bool Gui::GuiNativeEvent::RawInputEventFilter(void *msg, long *result) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +bool Gui::GuiNativeEvent::RawInputEventFilter(void* msg, long* result) #else -bool Gui::GuiNativeEvent::RawInputEventFilter(void *msg, qintptr *result) +bool Gui::GuiNativeEvent::RawInputEventFilter(void* msg, qintptr* result) #endif { - if (gMouseInput == 0) + if (gMouseInput == 0) { return false; + } - MSG *message = (MSG *)(msg); + MSG* message = (MSG*)(msg); if (message->message == WM_INPUT) { HRAWINPUT hRawInput = reinterpret_cast(message->lParam); @@ -405,13 +486,16 @@ void Gui::GuiNativeEvent::On3dmouseKeyUp(HANDLE device, int virtualKeyCode) pNumDevices returns the number of devices to register. Currently this is always 1. */ -static PRAWINPUTDEVICE GetDevicesToRegister(unsigned int *pNumDevices) +static PRAWINPUTDEVICE GetDevicesToRegister(unsigned int* pNumDevices) { // Array of raw input devices to register static RAWINPUTDEVICE sRawInputDevices[] = { - {0x01, 0x08, 0x00, 0x00} // Usage Page = 0x01 Generic Desktop Page, Usage Id= 0x08 Multi-axis Controller - ,{0x01, 0x05, 0x00, 0x00} // game pad - ,{0x01, 0x04, 0x00, 0x00} // joystick + {0x01, 0x08, 0x00, 0x00} + // Usage Page = 0x01 Generic Desktop Page, Usage Id= 0x08 Multi-axis Controller + , + {0x01, 0x05, 0x00, 0x00} // game pad + , + {0x01, 0x04, 0x00, 0x00} // joystick }; if (pNumDevices) { @@ -435,8 +519,9 @@ bool Gui::GuiNativeEvent::Is3dmouseAttached() return false; } - if (nDevices == 0) + if (nDevices == 0) { return false; + } std::vector rawInputDeviceList(nDevices); if (::GetRawInputDeviceList(&rawInputDeviceList[0], &nDevices, sizeof(RAWINPUTDEVICELIST)) @@ -448,16 +533,15 @@ bool Gui::GuiNativeEvent::Is3dmouseAttached() RID_DEVICE_INFO rdi = {sizeof(rdi)}; unsigned int cbSize = sizeof(rdi); - if (GetRawInputDeviceInfo(rawInputDeviceList[i].hDevice, RIDI_DEVICEINFO, &rdi, &cbSize) - > 0) { - //skip non HID and non logitec (3DConnexion) devices + if (GetRawInputDeviceInfo(rawInputDeviceList[i].hDevice, RIDI_DEVICEINFO, &rdi, &cbSize) > 0) { + // skip non HID and non logitec (3DConnexion) devices if (!(rdi.dwType == RIM_TYPEHID && (rdi.hid.dwVendorId == LOGITECH_VENDOR_ID || rdi.hid.dwVendorId == CONNEXION_VENDOR_ID))) { continue; } - //check if devices matches Multi-axis Controller + // check if devices matches Multi-axis Controller for (unsigned int j = 0; j < numDevicesOfInterest; ++j) { if (devicesToRegister[j].usUsage == rdi.hid.usUsage && devicesToRegister[j].usUsagePage == rdi.hid.usUsagePage) { @@ -473,21 +557,24 @@ bool Gui::GuiNativeEvent::Is3dmouseAttached() /*! Initialize the window to receive raw-input messages - This needs to be called initially so that Windows will send the messages from the 3D mouse to the window. + This needs to be called initially so that Windows will send the messages from the 3D mouse to + the window. */ bool Gui::GuiNativeEvent::InitializeRawInput(HWND hwndTarget) { fWindow = hwndTarget; // Simply fail if there is no window - if (!hwndTarget) + if (!hwndTarget) { return false; + } unsigned int numDevices = 0; PRAWINPUTDEVICE devicesToRegister = GetDevicesToRegister(&numDevices); - if (numDevices == 0) + if (numDevices == 0) { return false; + } // Get OS version. OSVERSIONINFO osvi = {sizeof(OSVERSIONINFO), 0}; @@ -496,7 +583,7 @@ bool Gui::GuiNativeEvent::InitializeRawInput(HWND hwndTarget) unsigned int cbSize = sizeof(devicesToRegister[0]); for (size_t i = 0; i < numDevices; i++) { // Set the target window to use - //devicesToRegister[i].hwndTarget = hwndTarget; + // devicesToRegister[i].hwndTarget = hwndTarget; // If Vista or newer, enable receiving the WM_INPUT_DEVICE_CHANGE message. if (osvi.dwMajorVersion >= 6) { @@ -524,8 +611,8 @@ UINT Gui::GuiNativeEvent::GetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT //::IsWow64Process(GetCurrentProcess(), &bIsWow64); typedef BOOL(WINAPI * LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); - LPFN_ISWOW64PROCESS fnIsWow64Process = - (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); + LPFN_ISWOW64PROCESS fnIsWow64Process + = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process"); if (NULL != fnIsWow64Process) { fnIsWow64Process(GetCurrentProcess(), &bIsWow64); @@ -534,7 +621,7 @@ UINT Gui::GuiNativeEvent::GetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT return ::GetRawInputBuffer(pData, pcbSize, cbSizeHeader); } else { - HWND hwndTarget = fWindow;//fParent->winId(); + HWND hwndTarget = fWindow; // fParent->winId(); size_t cbDataSize = 0; UINT nCount = 0; @@ -584,17 +671,18 @@ void Gui::GuiNativeEvent::On3dmouseInput() if (!bIsForeground) { // set all cached data to zero so that a zero event is seen and the cached data deleted for (std::map::iterator it = fDevice2Data.begin(); - it != fDevice2Data.end(); it++) { + it != fDevice2Data.end(); + it++) { it->second.fAxes.assign(6, .0); it->second.fIsDirty = true; } } - DWORD dwNow = ::GetTickCount();// Current time; - DWORD dwElapsedTime; // Elapsed time since we were last here + DWORD dwNow = ::GetTickCount(); // Current time; + DWORD dwElapsedTime; // Elapsed time since we were last here if (0 == fLast3dmouseInputTime) { - dwElapsedTime = 10;// System timer resolution + dwElapsedTime = 10; // System timer resolution } else { dwElapsedTime = dwNow - fLast3dmouseInputTime; @@ -619,13 +707,14 @@ void Gui::GuiNativeEvent::On3dmouseInput() float mouseData2PanZoom; // Grab the I3dmouseParam interface - I3dMouseParam &i3dmouseParam = f3dMouseParams; + I3dMouseParam& i3dmouseParam = f3dMouseParams; // Take a look at the users preferred speed setting and adjust the sensitivity accordingly I3dMouseSensor::ESpeed speedSetting = i3dmouseParam.GetSpeed(); // See "Programming for the 3D Mouse", Section 5.1.3 - float speed = (speedSetting == I3dMouseSensor::kLowSpeed ? 0.25f - : speedSetting == I3dMouseSensor::kHighSpeed ? 4.f - : 1.f); + float speed + = (speedSetting == I3dMouseSensor::kLowSpeed ? 0.25f + : speedSetting == I3dMouseSensor::kHighSpeed ? 4.f + : 1.f); // Multiplying by the following will convert the 3d mouse data to real world units mouseData2PanZoom = speed; @@ -668,14 +757,20 @@ void Gui::GuiNativeEvent::On3dmouseInput() } // convert the translation vector into physical data - for (int axis = 0; axis < 3; axis++) { motionData[axis] *= mouseData2PanZoom; } + for (int axis = 0; axis < 3; axis++) { + motionData[axis] *= mouseData2PanZoom; + } // convert the directed Rotate vector into physical data // See "Programming for the 3D Mouse", Section 7.2.2 - for (int axis = 3; axis < 6; axis++) { motionData[axis] *= mouseData2Rotation; } + for (int axis = 3; axis < 6; axis++) { + motionData[axis] *= mouseData2Rotation; + } // Now that the data has had the filters and sensitivity settings applied // calculate the displacements since the last view update - for (int axis = 0; axis < 6; axis++) { motionData[axis] *= dwElapsedTime; } + for (int axis = 0; axis < 6; axis++) { + motionData[axis] *= dwElapsedTime; + } // Now a bit of book keeping before passing on the data @@ -761,18 +856,21 @@ bool Gui::GuiNativeEvent::TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawI qDebug("Rawinput.header.dwType=0x%x\n", pRawInput->header.dwType); #endif // We are not interested in keyboard or mouse data received via raw input - if (pRawInput->header.dwType != RIM_TYPEHID) + if (pRawInput->header.dwType != RIM_TYPEHID) { return false; + } #if _TRACE_RIDI_DEVICENAME UINT dwSize = 0; if (::GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_DEVICENAME, NULL, &dwSize) == 0) { std::vector szDeviceName(dwSize + 1); - if (::GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_DEVICENAME, &szDeviceName[0], - &dwSize) + if (::GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_DEVICENAME, &szDeviceName[0], &dwSize) > 0) { - qDebug("Device Name = %s\nDevice handle = 0x%x\n", &szDeviceName[0], - pRawInput->header.hDevice); + qDebug( + "Device Name = %s\nDevice handle = 0x%x\n", + &szDeviceName[0], + pRawInput->header.hDevice + ); } } #endif @@ -781,20 +879,25 @@ bool Gui::GuiNativeEvent::TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawI sRidDeviceInfo.cbSize = sizeof(RID_DEVICE_INFO); UINT cbSize = sizeof(RID_DEVICE_INFO); - if (::GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_DEVICEINFO, &sRidDeviceInfo, - &cbSize) + if (::GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_DEVICEINFO, &sRidDeviceInfo, &cbSize) == cbSize) { #if _TRACE_RIDI_DEVICEINFO switch (sRidDeviceInfo.dwType) { - case RIM_TYPEMOUSE: qDebug("\tsRidDeviceInfo.dwType=RIM_TYPEMOUSE\n"); break; - case RIM_TYPEKEYBOARD: qDebug("\tsRidDeviceInfo.dwType=RIM_TYPEKEYBOARD\n"); break; + case RIM_TYPEMOUSE: + qDebug("\tsRidDeviceInfo.dwType=RIM_TYPEMOUSE\n"); + break; + case RIM_TYPEKEYBOARD: + qDebug("\tsRidDeviceInfo.dwType=RIM_TYPEKEYBOARD\n"); + break; case RIM_TYPEHID: qDebug("\tsRidDeviceInfo.dwType=RIM_TYPEHID\n"); - qDebug("\tVendor=0x%x\n\tProduct=0x%x\n\tUsagePage=0x%x\n\tUsage=0x%x\n", - sRidDeviceInfo.hid.dwVendorId, - sRidDeviceInfo.hid.dwProductId, - sRidDeviceInfo.hid.usUsagePage, - sRidDeviceInfo.hid.usUsage); + qDebug( + "\tVendor=0x%x\n\tProduct=0x%x\n\tUsagePage=0x%x\n\tUsage=0x%x\n", + sRidDeviceInfo.hid.dwVendorId, + sRidDeviceInfo.hid.dwProductId, + sRidDeviceInfo.hid.usUsagePage, + sRidDeviceInfo.hid.usUsage + ); break; } #endif @@ -804,16 +907,25 @@ bool Gui::GuiNativeEvent::TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawI switch (sRidDeviceInfo.hid.dwProductId) { case eSpaceMousePlusXT: if (pRawInput->data.hid.bRawData[0] != 0x00) { - return TranslateSpaceMouseNewGeneric(nInputCode, pRawInput, - sRidDeviceInfo.hid.dwProductId); + return TranslateSpaceMouseNewGeneric( + nInputCode, + pRawInput, + sRidDeviceInfo.hid.dwProductId + ); } else { - return TranslateSpaceMouseOldGeneric(nInputCode, pRawInput, - sRidDeviceInfo.hid.dwProductId); + return TranslateSpaceMouseOldGeneric( + nInputCode, + pRawInput, + sRidDeviceInfo.hid.dwProductId + ); } case eSpaceMouseEnterprise: - return TranslateSpaceMouseEnterprise(nInputCode, pRawInput, - sRidDeviceInfo.hid.dwProductId); + return TranslateSpaceMouseEnterprise( + nInputCode, + pRawInput, + sRidDeviceInfo.hid.dwProductId + ); case eSpacePilot: case eSpaceNavigator: case eSpaceExplorer: @@ -822,8 +934,11 @@ bool Gui::GuiNativeEvent::TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawI case eSpaceMouseWireless: case eSpaceMousePROWireless: default: - return TranslateSpaceMouseNewGeneric(nInputCode, pRawInput, - sRidDeviceInfo.hid.dwProductId); + return TranslateSpaceMouseNewGeneric( + nInputCode, + pRawInput, + sRidDeviceInfo.hid.dwProductId + ); } } } @@ -831,51 +946,57 @@ bool Gui::GuiNativeEvent::TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawI return false; } -bool Gui::GuiNativeEvent::TranslateSpaceMouseNewGeneric(UINT nInputCode, PRAWINPUT pRawInput, - DWORD dwProductId) +bool Gui::GuiNativeEvent::TranslateSpaceMouseNewGeneric( + UINT nInputCode, + PRAWINPUT pRawInput, + DWORD dwProductId +) { bool bIsForeground = (nInputCode == RIM_INPUT); - if (pRawInput->data.hid.bRawData[0] == 0x01) {// Translation vector + if (pRawInput->data.hid.bRawData[0] == 0x01) { // Translation vector - TInputData &deviceData = fDevice2Data[pRawInput->header.hDevice]; + TInputData& deviceData = fDevice2Data[pRawInput->header.hDevice]; deviceData.fTimeToLive = kTimeToLive; if (bIsForeground) { - short *pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); + short* pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); // Cache the pan zoom data deviceData.fAxes[0] = static_cast(pnRawData[0]); deviceData.fAxes[1] = static_cast(pnRawData[1]); deviceData.fAxes[2] = static_cast(pnRawData[2]); #if _TRACE_RI_RAWDATA - qDebug("Pan/Zoom RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], - pnRawData[2]); + qDebug("Pan/Zoom RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], pnRawData[2]); #endif - if (pRawInput->data.hid.dwSizeHid >= 13) {// Highspeed package + if (pRawInput->data.hid.dwSizeHid >= 13) { // Highspeed package // Cache the rotation data deviceData.fAxes[3] = static_cast(pnRawData[3]); deviceData.fAxes[4] = static_cast(pnRawData[4]); deviceData.fAxes[5] = static_cast(pnRawData[5]); deviceData.fIsDirty = true; #if _TRACE_RI_RAWDATA - qDebug("Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[3], pnRawData[4], - pnRawData[5]); + qDebug( + "Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", + pnRawData[3], + pnRawData[4], + pnRawData[5] + ); #endif return true; } } - else {// Zero out the data if the app is not in foreground + else { // Zero out the data if the app is not in foreground deviceData.fAxes.assign(6, 0.f); } } - else if (pRawInput->data.hid.bRawData[0] == 0x02) {// Rotation vector + else if (pRawInput->data.hid.bRawData[0] == 0x02) { // Rotation vector // If we are not in foreground do nothing // The rotation vector was zeroed out with the translation vector in the previous message if (bIsForeground) { - TInputData &deviceData = fDevice2Data[pRawInput->header.hDevice]; + TInputData& deviceData = fDevice2Data[pRawInput->header.hDevice]; deviceData.fTimeToLive = kTimeToLive; - short *pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); + short* pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); // Cache the rotation data deviceData.fAxes[3] = static_cast(pnRawData[0]); deviceData.fAxes[4] = static_cast(pnRawData[1]); @@ -883,19 +1004,17 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseNewGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; #if _TRACE_RI_RAWDATA - qDebug("Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], - pnRawData[2]); + qDebug("Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], pnRawData[2]); #endif return true; } } - else if (pRawInput->data.hid.bRawData[0] == 0x03) {// Keystate change + else if (pRawInput->data.hid.bRawData[0] == 0x03) { // Keystate change // this is a package that contains 3d mouse keystate information // bit0=key1, bit=key2 etc. - unsigned long dwKeystate = - *reinterpret_cast(&pRawInput->data.hid.bRawData[1]); + unsigned long dwKeystate = *reinterpret_cast(&pRawInput->data.hid.bRawData[1]); #if _TRACE_RI_RAWDATA qDebug("pRawInput->data.hid.bRawData[0] = 0x%x", pRawInput->data.hid.bRawData[0]); qDebug("ButtonData =0x%x\n", dwKeystate); @@ -934,51 +1053,57 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseNewGeneric(UINT nInputCode, PRAWINP return false; } -bool Gui::GuiNativeEvent::TranslateSpaceMouseEnterprise(UINT nInputCode, PRAWINPUT pRawInput, - DWORD dwProductId) +bool Gui::GuiNativeEvent::TranslateSpaceMouseEnterprise( + UINT nInputCode, + PRAWINPUT pRawInput, + DWORD dwProductId +) { bool bIsForeground = (nInputCode == RIM_INPUT); - if (pRawInput->data.hid.bRawData[0] == 0x01) {// Translation vector + if (pRawInput->data.hid.bRawData[0] == 0x01) { // Translation vector - TInputData &deviceData = fDevice2Data[pRawInput->header.hDevice]; + TInputData& deviceData = fDevice2Data[pRawInput->header.hDevice]; deviceData.fTimeToLive = kTimeToLive; if (bIsForeground) { - short *pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); + short* pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); // Cache the pan zoom data deviceData.fAxes[0] = static_cast(pnRawData[0]); deviceData.fAxes[1] = static_cast(pnRawData[1]); deviceData.fAxes[2] = static_cast(pnRawData[2]); #if _TRACE_RI_RAWDATA - qDebug("Pan/Zoom RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], - pnRawData[2]); + qDebug("Pan/Zoom RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], pnRawData[2]); #endif - if (pRawInput->data.hid.dwSizeHid >= 13) {// Highspeed package + if (pRawInput->data.hid.dwSizeHid >= 13) { // Highspeed package // Cache the rotation data deviceData.fAxes[3] = static_cast(pnRawData[3]); deviceData.fAxes[4] = static_cast(pnRawData[4]); deviceData.fAxes[5] = static_cast(pnRawData[5]); deviceData.fIsDirty = true; #if _TRACE_RI_RAWDATA - qDebug("Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[3], pnRawData[4], - pnRawData[5]); + qDebug( + "Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", + pnRawData[3], + pnRawData[4], + pnRawData[5] + ); #endif return true; } } - else {// Zero out the data if the app is not in foreground + else { // Zero out the data if the app is not in foreground deviceData.fAxes.assign(6, 0.f); } } - else if (pRawInput->data.hid.bRawData[0] == 0x02) {// Rotation vector + else if (pRawInput->data.hid.bRawData[0] == 0x02) { // Rotation vector // If we are not in foreground do nothing // The rotation vector was zeroed out with the translation vector in the previous message if (bIsForeground) { - TInputData &deviceData = fDevice2Data[pRawInput->header.hDevice]; + TInputData& deviceData = fDevice2Data[pRawInput->header.hDevice]; deviceData.fTimeToLive = kTimeToLive; - short *pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); + short* pnRawData = reinterpret_cast(&pRawInput->data.hid.bRawData[1]); // Cache the rotation data deviceData.fAxes[3] = static_cast(pnRawData[0]); deviceData.fAxes[4] = static_cast(pnRawData[1]); @@ -986,19 +1111,19 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseEnterprise(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; #if _TRACE_RI_RAWDATA - qDebug("Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], - pnRawData[2]); + qDebug("Rotation RI Data =\t0x%x,\t0x%x,\t0x%x\n", pnRawData[0], pnRawData[1], pnRawData[2]); #endif return true; } } - else if ((pRawInput->data.hid.bRawData[0] == 0x1c) - || (pRawInput->data.hid.bRawData[0] == 0x1d)) { + else if ((pRawInput->data.hid.bRawData[0] == 0x1c) || (pRawInput->data.hid.bRawData[0] == 0x1d)) { #if _TRACE_RI_RAWDATA qDebug("pRawInput->data.hid.bRawData[0] = 0x%x", pRawInput->data.hid.bRawData[0]); - qDebug("ButtonData = 0x%x\n", - *reinterpret_cast(&pRawInput->data.hid.bRawData[1])); + qDebug( + "ButtonData = 0x%x\n", + *reinterpret_cast(&pRawInput->data.hid.bRawData[1]) + ); #endif // calculate a KeyCode unsigned long dwKeyCode = pRawInput->data.hid.bRawData[1] << 1; @@ -1060,15 +1185,24 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseEnterprise(UINT nInputCode, PRAWINP #include #include -//#pragma comment(lib, "user32.lib") -//#pragma comment(lib, "hid.lib") +// #pragma comment(lib, "user32.lib") +// #pragma comment(lib, "hid.lib") -#define MAX_BUTTONS 128 -#define CHECK(exp) { if(!(exp)) goto Error; } -#define SAFE_FREE(p) { if(p) { HeapFree(hHeap, 0, p); (p) = NULL; } } +#define MAX_BUTTONS 128 +#define CHECK(exp) \ + { \ + if (!(exp)) \ + goto Error; \ + } +#define SAFE_FREE(p) \ + { \ + if (p) { \ + HeapFree(hHeap, 0, p); \ + (p) = NULL; \ + } \ + } -bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINPUT pRawInput, - DWORD /*dwProductId*/) +bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINPUT pRawInput, DWORD /*dwProductId*/) { bool processed = false; bool bIsForeground = (nInputCode == RIM_INPUT); @@ -1077,24 +1211,24 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP if (fDevice2Data.empty()) { return false; } - TInputData &deviceData = fDevice2Data.begin()->second; + TInputData& deviceData = fDevice2Data.begin()->second; PHIDP_PREPARSED_DATA pPreparsedData; - HIDP_CAPS Caps; - PHIDP_BUTTON_CAPS pButtonCaps; - PHIDP_VALUE_CAPS pValueCaps; - USHORT capsLength; - UINT bufferSize; - HANDLE hHeap; - USAGE usage[MAX_BUTTONS]; - ULONG i, usageLength, value; + HIDP_CAPS Caps; + PHIDP_BUTTON_CAPS pButtonCaps; + PHIDP_VALUE_CAPS pValueCaps; + USHORT capsLength; + UINT bufferSize; + HANDLE hHeap; + USAGE usage[MAX_BUTTONS]; + ULONG i, usageLength, value; BOOL bButtonStates[MAX_BUTTONS]; pPreparsedData = NULL; - pButtonCaps = NULL; - pValueCaps = NULL; - hHeap = GetProcessHeap(); + pButtonCaps = NULL; + pValueCaps = NULL; + hHeap = GetProcessHeap(); #ifdef _TRACE_RI_RAWDATA qDebug("pRawInput->data.hid.bRawData[0] = 0x%x", pRawInput->data.hid.bRawData[0]); @@ -1104,12 +1238,12 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP // Get the preparsed data block // - CHECK(GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_PREPARSEDDATA, NULL, &bufferSize) - == 0); + CHECK(GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_PREPARSEDDATA, NULL, &bufferSize) == 0); CHECK(pPreparsedData = (PHIDP_PREPARSED_DATA)HeapAlloc(hHeap, 0, bufferSize)); - CHECK((int)GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_PREPARSEDDATA, pPreparsedData, - &bufferSize) - >= 0); + CHECK( + (int)GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_PREPARSEDDATA, pPreparsedData, &bufferSize) + >= 0 + ); // // Get the joystick's capabilities @@ -1117,20 +1251,22 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP // Button caps CHECK(HidP_GetCaps(pPreparsedData, &Caps) == HIDP_STATUS_SUCCESS) - CHECK(pButtonCaps = (PHIDP_BUTTON_CAPS)HeapAlloc( - hHeap, 0, sizeof(HIDP_BUTTON_CAPS) * Caps.NumberInputButtonCaps)); + CHECK( + pButtonCaps = (PHIDP_BUTTON_CAPS) + HeapAlloc(hHeap, 0, sizeof(HIDP_BUTTON_CAPS) * Caps.NumberInputButtonCaps) + ); capsLength = Caps.NumberInputButtonCaps; - CHECK(HidP_GetButtonCaps(HidP_Input, pButtonCaps, &capsLength, pPreparsedData) - == HIDP_STATUS_SUCCESS) + CHECK(HidP_GetButtonCaps(HidP_Input, pButtonCaps, &capsLength, pPreparsedData) == HIDP_STATUS_SUCCESS) usageLength = pButtonCaps->Range.UsageMax - pButtonCaps->Range.UsageMin + 1; // Value caps - CHECK(pValueCaps = (PHIDP_VALUE_CAPS)HeapAlloc( - hHeap, 0, sizeof(HIDP_VALUE_CAPS) * Caps.NumberInputValueCaps)); + CHECK( + pValueCaps + = (PHIDP_VALUE_CAPS)HeapAlloc(hHeap, 0, sizeof(HIDP_VALUE_CAPS) * Caps.NumberInputValueCaps) + ); capsLength = Caps.NumberInputValueCaps; - CHECK(HidP_GetValueCaps(HidP_Input, pValueCaps, &capsLength, pPreparsedData) - == HIDP_STATUS_SUCCESS) + CHECK(HidP_GetValueCaps(HidP_Input, pValueCaps, &capsLength, pPreparsedData) == HIDP_STATUS_SUCCESS) processed = true; @@ -1138,12 +1274,24 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP // Get the pressed buttons // - CHECK(HidP_GetUsages(HidP_Input, pButtonCaps->UsagePage, 0, usage, &usageLength, pPreparsedData, - (PCHAR)pRawInput->data.hid.bRawData, pRawInput->data.hid.dwSizeHid) - == HIDP_STATUS_SUCCESS); + CHECK( + HidP_GetUsages( + HidP_Input, + pButtonCaps->UsagePage, + 0, + usage, + &usageLength, + pPreparsedData, + (PCHAR)pRawInput->data.hid.bRawData, + pRawInput->data.hid.dwSizeHid + ) + == HIDP_STATUS_SUCCESS + ); ZeroMemory(bButtonStates, sizeof(bButtonStates)); - for (i = 0; i < usageLength; i++) bButtonStates[usage[i] - pButtonCaps->Range.UsageMin] = TRUE; + for (i = 0; i < usageLength; i++) { + bButtonStates[usage[i] - pButtonCaps->Range.UsageMin] = TRUE; + } // // Get the state of discrete-valued-controls @@ -1153,13 +1301,20 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fTimeToLive = kTimeToLive; if (bIsForeground) { for (i = 0; i < Caps.NumberInputValueCaps; i++) { - HidP_GetUsageValue(HidP_Input, pValueCaps[i].UsagePage, 0, pValueCaps[i].Range.UsageMin, - &value, pPreparsedData, (PCHAR)pRawInput->data.hid.bRawData, - pRawInput->data.hid.dwSizeHid); + HidP_GetUsageValue( + HidP_Input, + pValueCaps[i].UsagePage, + 0, + pValueCaps[i].Range.UsageMin, + &value, + pPreparsedData, + (PCHAR)pRawInput->data.hid.bRawData, + pRawInput->data.hid.dwSizeHid + ); short svalue = static_cast(value); switch (pValueCaps[i].Range.UsageMin) { - case HID_USAGE_GENERIC_X:// X-axis + case HID_USAGE_GENERIC_X: // X-axis #ifdef _TRACE_RI_RAWDATA qDebug("X-Axis: %d\n", svalue); #endif @@ -1167,7 +1322,7 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; break; - case HID_USAGE_GENERIC_Y:// Y-axis + case HID_USAGE_GENERIC_Y: // Y-axis #ifdef _TRACE_RI_RAWDATA qDebug("Y-Axis: %d\n", svalue); #endif @@ -1175,7 +1330,7 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; break; - case HID_USAGE_GENERIC_Z:// Z-axis + case HID_USAGE_GENERIC_Z: // Z-axis #ifdef _TRACE_RI_RAWDATA qDebug("Z-Axis: %d\n", svalue); #endif @@ -1183,7 +1338,7 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; break; - case HID_USAGE_GENERIC_RX:// Rotate-X + case HID_USAGE_GENERIC_RX: // Rotate-X #ifdef _TRACE_RI_RAWDATA qDebug("X-Rotate: %d\n", svalue); #endif @@ -1191,7 +1346,7 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; break; - case HID_USAGE_GENERIC_RY:// Rotate-Y + case HID_USAGE_GENERIC_RY: // Rotate-Y #ifdef _TRACE_RI_RAWDATA qDebug("Y-Rotate: %d\n", svalue); #endif @@ -1199,7 +1354,7 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; break; - case HID_USAGE_GENERIC_RZ:// Rotate-Z + case HID_USAGE_GENERIC_RZ: // Rotate-Z #ifdef _TRACE_RI_RAWDATA qDebug("Z-Rotate: %d\n", svalue); #endif @@ -1207,7 +1362,8 @@ bool Gui::GuiNativeEvent::TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINP deviceData.fIsDirty = true; break; - default: break; + default: + break; } } } diff --git a/src/Gui/3Dconnexion/GuiNativeEventWin32.h b/src/Gui/3Dconnexion/GuiNativeEventWin32.h index e330decbee..f1030388c4 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventWin32.h +++ b/src/Gui/3Dconnexion/GuiNativeEventWin32.h @@ -37,71 +37,77 @@ class GUIApplicationNativeEventAware; namespace Gui { - class GUIApplicationNativeEventAware; +class GUIApplicationNativeEventAware; - class GuiNativeEvent : public GuiAbstractNativeEvent - { +class GuiNativeEvent: public GuiAbstractNativeEvent +{ Q_OBJECT - public: - GuiNativeEvent(GUIApplicationNativeEventAware *app); - ~GuiNativeEvent() override; - void initSpaceball(QMainWindow *window) override final; - private: - GuiNativeEvent(); - GuiNativeEvent(const GuiNativeEvent&); - GuiNativeEvent& operator=(const GuiNativeEvent&); - public: - static bool Is3dmouseAttached(); +public: + GuiNativeEvent(GUIApplicationNativeEventAware* app); + ~GuiNativeEvent() override; + void initSpaceball(QMainWindow* window) override final; - I3dMouseParam& MouseParams(); - const I3dMouseParam& MouseParams() const; +private: + GuiNativeEvent(); + GuiNativeEvent(const GuiNativeEvent&); + GuiNativeEvent& operator=(const GuiNativeEvent&); - virtual void Move3d(HANDLE device, std::vector& motionData); - virtual void On3dmouseKeyDown(HANDLE device, int virtualKeyCode); - virtual void On3dmouseKeyUp(HANDLE device, int virtualKeyCode); +public: + static bool Is3dmouseAttached(); - private: - bool InitializeRawInput(HWND hwndTarget); + I3dMouseParam& MouseParams(); + const I3dMouseParam& MouseParams() const; + + virtual void Move3d(HANDLE device, std::vector& motionData); + virtual void On3dmouseKeyDown(HANDLE device, int virtualKeyCode); + virtual void On3dmouseKeyUp(HANDLE device, int virtualKeyCode); + +private: + bool InitializeRawInput(HWND hwndTarget); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - static bool RawInputEventFilter(void* msg, long* result); + static bool RawInputEventFilter(void* msg, long* result); #else - static bool RawInputEventFilter(void* msg, qintptr* result); + static bool RawInputEventFilter(void* msg, qintptr* result); #endif - void OnRawInput(UINT nInputCode, HRAWINPUT hRawInput); - UINT GetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT cbSizeHeader); - bool TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawInput); - bool TranslateSpaceMouseNewGeneric(UINT nInputCode, PRAWINPUT pRawInput, DWORD dwProductId); - bool TranslateSpaceMouseEnterprise(UINT nInputCode, PRAWINPUT pRawInput, DWORD dwProductId); - bool TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINPUT pRawInput, DWORD dwProductId); - void On3dmouseInput(); + void OnRawInput(UINT nInputCode, HRAWINPUT hRawInput); + UINT GetRawInputBuffer(PRAWINPUT pData, PUINT pcbSize, UINT cbSizeHeader); + bool TranslateRawInputData(UINT nInputCode, PRAWINPUT pRawInput); + bool TranslateSpaceMouseNewGeneric(UINT nInputCode, PRAWINPUT pRawInput, DWORD dwProductId); + bool TranslateSpaceMouseEnterprise(UINT nInputCode, PRAWINPUT pRawInput, DWORD dwProductId); + bool TranslateSpaceMouseOldGeneric(UINT nInputCode, PRAWINPUT pRawInput, DWORD dwProductId); + void On3dmouseInput(); - class TInputData + class TInputData + { + public: + TInputData() + : fAxes(6) + {} + + bool IsZero() { - public: - TInputData() : fAxes(6) {} + return ( + 0. == fAxes[0] && 0. == fAxes[1] && 0. == fAxes[2] && 0. == fAxes[3] + && 0. == fAxes[4] && 0. == fAxes[5] + ); + } - bool IsZero() { - return (0.==fAxes[0] && 0.==fAxes[1] && 0.==fAxes[2] && - 0.==fAxes[3] && 0.==fAxes[4] && 0.==fAxes[5]); - } - - int fTimeToLive; // For telling if the device was unplugged while sending data - bool fIsDirty; - std::vector fAxes; - }; - - HWND fWindow; - - // Data cache to handle multiple rawinput devices - std::map< HANDLE, TInputData> fDevice2Data; - std::map< HANDLE, unsigned long> fDevice2Keystate; - // 3dmouse parameters - MouseParameters f3dMouseParams; // Rotate, Pan Zoom etc. - // use to calculate distance traveled since last event - DWORD fLast3dmouseInputTime; - static Gui::GuiNativeEvent* gMouseInput; + int fTimeToLive; // For telling if the device was unplugged while sending data + bool fIsDirty; + std::vector fAxes; }; -} -#endif //GUINATIVEEVENT_H + HWND fWindow; + // Data cache to handle multiple rawinput devices + std::map fDevice2Data; + std::map fDevice2Keystate; + // 3dmouse parameters + MouseParameters f3dMouseParams; // Rotate, Pan Zoom etc. + // use to calculate distance traveled since last event + DWORD fLast3dmouseInputTime; + static Gui::GuiNativeEvent* gMouseInput; +}; +} // namespace Gui + +#endif // GUINATIVEEVENT_H diff --git a/src/Gui/3Dconnexion/GuiRawInputEventFilter.h b/src/Gui/3Dconnexion/GuiRawInputEventFilter.h index 5a8e8c6f68..c80ca0e830 100644 --- a/src/Gui/3Dconnexion/GuiRawInputEventFilter.h +++ b/src/Gui/3Dconnexion/GuiRawInputEventFilter.h @@ -27,32 +27,35 @@ namespace Gui { - class RawInputEventFilter : public QAbstractNativeEventFilter +class RawInputEventFilter: public QAbstractNativeEventFilter +{ +public: +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + using EventFilter = bool (*)(void* message, long* result); +#else + using EventFilter = bool (*)(void* message, qintptr* result); +#endif + RawInputEventFilter(EventFilter filter) + : eventFilter(filter) + {} + virtual ~RawInputEventFilter() + {} + +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + virtual bool nativeEventFilter(const QByteArray& /*eventType*/, void* message, long* result) { - public: - #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - using EventFilter = bool (*)(void *message, long *result); - #else - using EventFilter = bool (*)(void *message, qintptr *result); - #endif - RawInputEventFilter(EventFilter filter) : eventFilter(filter) { - } - virtual ~RawInputEventFilter() { - } + return eventFilter(message, result); + } +#else + virtual bool nativeEventFilter(const QByteArray& /*eventType*/, void* message, qintptr* result) + { + return eventFilter(message, result); + } +#endif - #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) - virtual bool nativeEventFilter(const QByteArray & /*eventType*/, void *message, long *result) { - return eventFilter(message, result); - } - #else - virtual bool nativeEventFilter(const QByteArray & /*eventType*/, void *message, qintptr *result) { - return eventFilter(message, result); - } - #endif +private: + EventFilter eventFilter; +}; +} // namespace Gui - private: - EventFilter eventFilter; - }; -} //namespace Gui - -#endif //GUIRAWNATIVEINPUTEVENTFILTER_H +#endif // GUIRAWNATIVEINPUTEVENTFILTER_H diff --git a/src/Gui/3Dconnexion/I3dMouseParams.h b/src/Gui/3Dconnexion/I3dMouseParams.h index 346a047b08..07eb3a6776 100644 --- a/src/Gui/3Dconnexion/I3dMouseParams.h +++ b/src/Gui/3Dconnexion/I3dMouseParams.h @@ -14,78 +14,75 @@ Development tools and related technology provided under license from 3Dconnexion class I3dMouseSensor { public: - - enum ESpeed { - kLowSpeed = 0, - kMidSpeed, - kHighSpeed + enum ESpeed + { + kLowSpeed = 0, + kMidSpeed, + kHighSpeed }; -virtual bool IsPanZoom() const = 0; -virtual bool IsRotate() const = 0; -virtual ESpeed GetSpeed() const = 0; + virtual bool IsPanZoom() const = 0; + virtual bool IsRotate() const = 0; + virtual ESpeed GetSpeed() const = 0; -virtual void SetPanZoom(bool isPanZoom) = 0; -virtual void SetRotate(bool isRotate) = 0; -virtual void SetSpeed(ESpeed speed) = 0; + virtual void SetPanZoom(bool isPanZoom) = 0; + virtual void SetRotate(bool isRotate) = 0; + virtual void SetSpeed(ESpeed speed) = 0; protected: - -virtual ~I3dMouseSensor() {} - + virtual ~I3dMouseSensor() + {} }; class I3dMouseNavigation { public: + enum EPivot + { + kManualPivot = 0, + kAutoPivot, + kAutoPivotOverride + }; - enum EPivot { - kManualPivot = 0, - kAutoPivot, - kAutoPivotOverride - }; + enum ENavigation + { + kObjectMode = 0, + kCameraMode, + kFlyMode, + kWalkMode, + kHelicopterMode + }; - enum ENavigation { - kObjectMode = 0, - kCameraMode, - kFlyMode, - kWalkMode, - kHelicopterMode - }; - - enum EPivotVisibility { - kHidePivot = 0, - kShowPivot, - kShowMovingPivot - }; + enum EPivotVisibility + { + kHidePivot = 0, + kShowPivot, + kShowMovingPivot + }; -virtual ENavigation GetNavigationMode() const = 0; -virtual EPivot GetPivotMode() const = 0; -virtual EPivotVisibility GetPivotVisibility() const = 0; -virtual bool IsLockHorizon() const = 0; + virtual ENavigation GetNavigationMode() const = 0; + virtual EPivot GetPivotMode() const = 0; + virtual EPivotVisibility GetPivotVisibility() const = 0; + virtual bool IsLockHorizon() const = 0; -virtual void SetLockHorizon(bool bOn) = 0; -virtual void SetNavigationMode(ENavigation navigation) = 0; -virtual void SetPivotMode(EPivot pivot) = 0; -virtual void SetPivotVisibility(EPivotVisibility visibility) = 0; + virtual void SetLockHorizon(bool bOn) = 0; + virtual void SetNavigationMode(ENavigation navigation) = 0; + virtual void SetPivotMode(EPivot pivot) = 0; + virtual void SetPivotVisibility(EPivotVisibility visibility) = 0; protected: - -virtual ~I3dMouseNavigation(){} - - + virtual ~I3dMouseNavigation() + {} }; -class I3dMouseParam : public I3dMouseSensor, public I3dMouseNavigation +class I3dMouseParam: public I3dMouseSensor, public I3dMouseNavigation { public: - -virtual ~I3dMouseParam() {} - + virtual ~I3dMouseParam() + {} }; -#endif // I3D_MOUSE_PARAMS_H - +#endif // I3D_MOUSE_PARAMS_H diff --git a/src/Gui/3Dconnexion/MouseParameters.cpp b/src/Gui/3Dconnexion/MouseParameters.cpp index ecc832caea..1ed0aadc23 100644 --- a/src/Gui/3Dconnexion/MouseParameters.cpp +++ b/src/Gui/3Dconnexion/MouseParameters.cpp @@ -7,88 +7,88 @@ Development tools and related technology provided under license from 3Dconnexion #include "MouseParameters.h" -MouseParameters::MouseParameters(): fNavigation(kObjectMode) - , fPivot(kAutoPivot) - , fPivotVisibility(kShowPivot) - , fIsLockHorizon(true) - , fIsPanZoom(true) - , fIsRotate(true) - , fSpeed(kLowSpeed) -{ -} +MouseParameters::MouseParameters() + : fNavigation(kObjectMode) + , fPivot(kAutoPivot) + , fPivotVisibility(kShowPivot) + , fIsLockHorizon(true) + , fIsPanZoom(true) + , fIsRotate(true) + , fSpeed(kLowSpeed) +{} MouseParameters::~MouseParameters() +{} + +bool MouseParameters::IsPanZoom() const { + return fIsPanZoom; } -bool MouseParameters::IsPanZoom() const +bool MouseParameters::IsRotate() const { - return fIsPanZoom; + return fIsRotate; } -bool MouseParameters::IsRotate() const +MouseParameters::ESpeed MouseParameters::GetSpeed() const { - return fIsRotate; -} - -MouseParameters::ESpeed MouseParameters::GetSpeed() const -{ - return fSpeed; + return fSpeed; } void MouseParameters::SetPanZoom(bool isPanZoom) { - fIsPanZoom=isPanZoom; + fIsPanZoom = isPanZoom; } void MouseParameters::SetRotate(bool isRotate) { - fIsRotate=isRotate; + fIsRotate = isRotate; } void MouseParameters::SetSpeed(ESpeed speed) { - fSpeed=speed; + fSpeed = speed; } -MouseParameters::ENavigation MouseParameters::GetNavigationMode() const +MouseParameters::ENavigation MouseParameters::GetNavigationMode() const { - return fNavigation; + return fNavigation; } -MouseParameters::EPivot MouseParameters::GetPivotMode() const +MouseParameters::EPivot MouseParameters::GetPivotMode() const { - return fPivot; + return fPivot; } -MouseParameters::EPivotVisibility MouseParameters::GetPivotVisibility() const +MouseParameters::EPivotVisibility MouseParameters::GetPivotVisibility() const { - return fPivotVisibility; + return fPivotVisibility; } -bool MouseParameters::IsLockHorizon() const +bool MouseParameters::IsLockHorizon() const { - return fIsLockHorizon; + return fIsLockHorizon; } void MouseParameters::SetLockHorizon(bool bOn) { - fIsLockHorizon=bOn; + fIsLockHorizon = bOn; } void MouseParameters::SetNavigationMode(ENavigation navigation) { - fNavigation=navigation; + fNavigation = navigation; } void MouseParameters::SetPivotMode(EPivot pivot) { - if (fPivot!=kManualPivot || pivot!=kAutoPivotOverride) - fPivot = pivot; + if (fPivot != kManualPivot || pivot != kAutoPivotOverride) { + fPivot = pivot; + } } void MouseParameters::SetPivotVisibility(EPivotVisibility visibility) { - fPivotVisibility = visibility; + fPivotVisibility = visibility; } diff --git a/src/Gui/3Dconnexion/MouseParameters.h b/src/Gui/3Dconnexion/MouseParameters.h index 3e00701bfa..b52764c5d4 100644 --- a/src/Gui/3Dconnexion/MouseParameters.h +++ b/src/Gui/3Dconnexion/MouseParameters.h @@ -11,46 +11,44 @@ Development tools and related technology provided under license from 3Dconnexion #include "I3dMouseParams.h" -class MouseParameters : public I3dMouseParam +class MouseParameters: public I3dMouseParam { public: - MouseParameters(); - ~MouseParameters(); + MouseParameters(); + ~MouseParameters(); - // I3dmouseSensor interface - bool IsPanZoom() const; - bool IsRotate() const; - ESpeed GetSpeed() const; + // I3dmouseSensor interface + bool IsPanZoom() const; + bool IsRotate() const; + ESpeed GetSpeed() const; - void SetPanZoom(bool isPanZoom); - void SetRotate(bool isRotate); - void SetSpeed(ESpeed speed); + void SetPanZoom(bool isPanZoom); + void SetRotate(bool isRotate); + void SetSpeed(ESpeed speed); - // I3dmouseNavigation interface - ENavigation GetNavigationMode() const; - EPivot GetPivotMode() const; - EPivotVisibility GetPivotVisibility() const; - bool IsLockHorizon() const; + // I3dmouseNavigation interface + ENavigation GetNavigationMode() const; + EPivot GetPivotMode() const; + EPivotVisibility GetPivotVisibility() const; + bool IsLockHorizon() const; - void SetLockHorizon(bool bOn); - void SetNavigationMode(ENavigation navigation); - void SetPivotMode(EPivot pivot); - void SetPivotVisibility(EPivotVisibility visibility); + void SetLockHorizon(bool bOn); + void SetNavigationMode(ENavigation navigation); + void SetPivotMode(EPivot pivot); + void SetPivotVisibility(EPivotVisibility visibility); private: + MouseParameters(const MouseParameters&); + const MouseParameters& operator=(const MouseParameters&); - MouseParameters (const MouseParameters&); - const MouseParameters& operator =(const MouseParameters&); + ENavigation fNavigation; + EPivot fPivot; + EPivotVisibility fPivotVisibility; + bool fIsLockHorizon; - ENavigation fNavigation; - EPivot fPivot; - EPivotVisibility fPivotVisibility; - bool fIsLockHorizon; - - bool fIsPanZoom; - bool fIsRotate; - ESpeed fSpeed; + bool fIsPanZoom; + bool fIsRotate; + ESpeed fSpeed; }; -#endif // T3D_MOUSE_PARAMS_H - +#endif // T3D_MOUSE_PARAMS_H diff --git a/src/Gui/Action.cpp b/src/Gui/Action.cpp index 4d095e8e3e..3287070114 100644 --- a/src/Gui/Action.cpp +++ b/src/Gui/Action.cpp @@ -20,18 +20,18 @@ * * ***************************************************************************/ -# 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 @@ -66,19 +66,19 @@ namespace sp = std::placeholders; * Constructs an action called \a name with parent \a parent. It also stores a pointer * to the command object. */ -Action::Action (Command* pcCmd, QObject * parent) - : QObject(parent) - , _action(new QAction( this )) - , _pcCmd(pcCmd) +Action::Action(Command* pcCmd, QObject* parent) + : QObject(parent) + , _action(new QAction(this)) + , _pcCmd(pcCmd) { _action->setObjectName(QString::fromLatin1(_pcCmd->getName())); _connection = connect(_action, &QAction::triggered, this, &Action::onActivated); } -Action::Action (Command* pcCmd, QAction* action, QObject * parent) - : QObject(parent) - , _action(action) - , _pcCmd(pcCmd) +Action::Action(Command* pcCmd, QAction* action, QObject* parent) + : QObject(parent) + , _action(action) + , _pcCmd(pcCmd) { _action->setParent(this); _action->setObjectName(QString::fromLatin1(_pcCmd->getName())); @@ -93,7 +93,7 @@ Action::~Action() /** * Adds this action to widget \a widget. */ -void Action::addTo(QWidget *widget) +void Action::addTo(QWidget* widget) { widget->addAction(_action); } @@ -101,7 +101,7 @@ void Action::addTo(QWidget *widget) /** * Activates the command. */ -void Action::onActivated () +void Action::onActivated() { command()->invoke(0, Command::TriggerAction); } @@ -172,7 +172,7 @@ void Action::setVisible(bool visible) _action->setVisible(visible); } -void Action::setShortcut(const QString & key) +void Action::setShortcut(const QString& key) { _action->setShortcut(key); setToolTip(_tooltip, _title); @@ -183,17 +183,17 @@ QKeySequence Action::shortcut() const return _action->shortcut(); } -void Action::setIcon (const QIcon & icon) +void Action::setIcon(const QIcon& icon) { _action->setIcon(icon); } -QIcon Action::icon () const +QIcon Action::icon() const { return _action->icon(); } -void Action::setStatusTip(const QString & text) +void Action::setStatusTip(const QString& text) { _action->setStatusTip(text); } @@ -203,7 +203,7 @@ QString Action::statusTip() const return _action->statusTip(); } -void Action::setText(const QString & text) +void Action::setText(const QString& text) { _action->setText(text); if (_title.isEmpty()) { @@ -216,18 +216,20 @@ QString Action::text() const return _action->text(); } -void Action::setToolTip(const QString & text, const QString & title) +void Action::setToolTip(const QString& text, const QString& title) { _tooltip = text; _title = title; - _action->setToolTip(createToolTip(text, - title.isEmpty() ? _action->text() : title, - _action->font(), - _action->shortcut().toString(QKeySequence::NativeText), - command())); + _action->setToolTip(createToolTip( + text, + title.isEmpty() ? _action->text() : title, + _action->font(), + _action->shortcut().toString(QKeySequence::NativeText), + command() + )); } -QString Action::cleanTitle(const QString & title) +QString Action::cleanTitle(const QString& title) { QString text(title); // Deal with QAction title mnemonic @@ -243,7 +245,7 @@ QString Action::cleanTitle(const QString & title) return text; } -QString Action::commandToolTip(const Command *cmd, bool richFormat) +QString Action::commandToolTip(const Command* cmd, bool richFormat) { if (!cmd) { return {}; @@ -263,7 +265,8 @@ QString Action::commandToolTip(const Command *cmd, bool richFormat) if (auto txt = cmd->getToolTipText()) { tooltip = QString::fromUtf8(txt); } - } else { + } + else { if (auto txt = cmd->getMenuText()) { title = qApp->translate(cmd->className(), txt); } @@ -278,7 +281,7 @@ QString Action::commandToolTip(const Command *cmd, bool richFormat) return createToolTip(tooltip, title, QFont(), cmd->getShortcut(), cmd); } -QString Action::commandMenuText(const Command *cmd) +QString Action::commandMenuText(const Command* cmd) { if (!cmd) { return {}; @@ -292,7 +295,8 @@ QString Action::commandMenuText(const Command *cmd) if (auto txt = cmd->getMenuText()) { title = QString::fromUtf8(txt); } - } else { + } + else { if (auto txt = cmd->getMenuText()) { title = qApp->translate(cmd->className(), txt); } @@ -306,11 +310,13 @@ QString Action::commandMenuText(const Command *cmd) return title; } -QString Action::createToolTip(QString helpText, - const QString & title, - const QFont &font, - const QString &shortCut, - const Command *command) +QString Action::createToolTip( + QString helpText, + const QString& title, + const QFont& font, + const QString& shortCut, + const Command* command +) { QString text = cleanTitle(title); @@ -334,9 +340,8 @@ QString Action::createToolTip(QString helpText, shortcut = QStringLiteral(" (%1)").arg(shortcut); } - QString tooltip = QStringLiteral( - "

%1%2

").arg( - text.toHtmlEscaped(), shortcut.toHtmlEscaped()); + QString tooltip = QStringLiteral("

%1%2

") + .arg(text.toHtmlEscaped(), shortcut.toHtmlEscaped()); QString cmdName; if (command && command->getName()) { @@ -347,23 +352,20 @@ QString Action::createToolTip(QString helpText, auto cmd = groupcmd->getCommand(idx); if (cmd && cmd->getName()) { cmdName = QStringLiteral("%1 (%2:%3)") - .arg(QString::fromLatin1(cmd->getName()), cmdName) - .arg(idx); + .arg(QString::fromLatin1(cmd->getName()), cmdName) + .arg(idx); } } } cmdName = QStringLiteral("

%1

") - .arg(cmdName.toHtmlEscaped()); + .arg(cmdName.toHtmlEscaped()); } if (!shortcut.isEmpty() && helpText.endsWith(shortcut)) { helpText.resize(helpText.size() - shortcut.size()); } - if (helpText.isEmpty() - || helpText == text - || helpText == title) - { + if (helpText.isEmpty() || helpText == text || helpText == title) { return tooltip + cmdName; } if (Qt::mightBeRichText(helpText)) { @@ -375,7 +377,7 @@ QString Action::createToolTip(QString helpText, // If the user supplied tooltip contains line break, we shall honour it. if (helpText.indexOf(QLatin1Char('\n')) >= 0) { - tooltip += helpText.toHtmlEscaped() + QStringLiteral("

") ; + tooltip += helpText.toHtmlEscaped() + QStringLiteral("

"); } else { // If not, try to end the non wrapping paragraph at some pre defined @@ -384,19 +386,18 @@ QString Action::createToolTip(QString helpText, QFontMetrics fm(font); int width = QtTools::horizontalAdvance(fm, helpText); if (width <= tipWidth) { - tooltip += helpText.toHtmlEscaped() + QStringLiteral("

") ; + tooltip += helpText.toHtmlEscaped() + QStringLiteral("

"); } else { int index = tipWidth / width * helpText.size(); // Try to only break at white space - for(int i=0; i<50 && index") - + helpText.right(helpText.size()-index).trimmed().toHtmlEscaped(); + tooltip += helpText.left(index).toHtmlEscaped() + QStringLiteral("

") + + helpText.right(helpText.size() - index).trimmed().toHtmlEscaped(); } } return tooltip + cmdName; @@ -407,7 +408,7 @@ QString Action::toolTip() const return _tooltip; } -void Action::setWhatsThis(const QString & text) +void Action::setWhatsThis(const QString& text) { _action->setWhatsThis(text); } @@ -448,7 +449,7 @@ ActionGroup::~ActionGroup() /** * Adds this action to widget \a w. */ -void ActionGroup::addTo(QWidget *widget) +void ActionGroup::addTo(QWidget* widget) { // When adding an action that has defined a menu then shortcuts // of the menu actions don't work. To make this working we must @@ -462,13 +463,9 @@ void ActionGroup::addTo(QWidget *widget) menu->setTitle(action()->text()); menu->addActions(groupAction()->actions()); - QObject::connect(menu, &QMenu::aboutToShow, [this, menu]() { - Q_EMIT aboutToShow(menu); - }); + QObject::connect(menu, &QMenu::aboutToShow, [this, menu]() { Q_EMIT aboutToShow(menu); }); - QObject::connect(menu, &QMenu::aboutToHide, [this, menu]() { - Q_EMIT aboutToHide(menu); - }); + QObject::connect(menu, &QMenu::aboutToHide, [this, menu]() { Q_EMIT aboutToHide(menu); }); } else if (widget->inherits("QToolBar")) { widget->addAction(action()); @@ -480,16 +477,12 @@ void ActionGroup::addTo(QWidget *widget) menu->addActions(acts); tb->setMenu(menu); - QObject::connect(menu, &QMenu::aboutToShow, [this, menu]() { - Q_EMIT aboutToShow(menu); - }); + QObject::connect(menu, &QMenu::aboutToShow, [this, menu]() { Q_EMIT aboutToShow(menu); }); - QObject::connect(menu, &QMenu::aboutToHide, [this, menu]() { - Q_EMIT aboutToHide(menu); - }); + QObject::connect(menu, &QMenu::aboutToHide, [this, menu]() { Q_EMIT aboutToHide(menu); }); } else { - widget->addActions(groupAction()->actions()); // no drop-down + widget->addActions(groupAction()->actions()); // no drop-down } } else { @@ -497,19 +490,19 @@ void ActionGroup::addTo(QWidget *widget) } } -void ActionGroup::setEnabled( bool check ) +void ActionGroup::setEnabled(bool check) { Action::setEnabled(check); groupAction()->setEnabled(check); } -void ActionGroup::setDisabled (bool check) +void ActionGroup::setDisabled(bool check) { Action::setEnabled(!check); groupAction()->setDisabled(check); } -void ActionGroup::setExclusive (bool check) +void ActionGroup::setExclusive(bool check) { groupAction()->setExclusive(check); } @@ -519,7 +512,7 @@ bool ActionGroup::isExclusive() const return groupAction()->isExclusive(); } -void ActionGroup::setVisible( bool check ) +void ActionGroup::setVisible(bool check) { Action::setVisible(check); groupAction()->setVisible(check); @@ -573,7 +566,7 @@ void ActionGroup::setCheckedAction(int index) /** * Activates the command. */ -void ActionGroup::onActivated () +void ActionGroup::onActivated() { command()->invoke(this->property("defaultAction").toInt(), Command::TriggerAction); } @@ -587,7 +580,7 @@ void ActionGroup::onToggled(bool check) /** * Activates the command. */ -void ActionGroup::onActivated (QAction* act) +void ActionGroup::onActivated(QAction* act) { if (_rememberLast) { int index = groupAction()->actions().indexOf(act); @@ -604,7 +597,7 @@ void ActionGroup::onActivated (QAction* act) /** * Shows tooltip at the right side when hovered. */ -void ActionGroup::onHovered(QAction *act) +void ActionGroup::onHovered(QAction* act) { const auto topLevelWidgets = QApplication::topLevelWidgets(); QMenu* foundMenu = nullptr; @@ -622,31 +615,32 @@ void ActionGroup::onHovered(QAction *act) if (foundMenu) { break; } - } if (foundMenu) { QRect actionRect = foundMenu->actionGeometry(act); QPoint globalPos = foundMenu->mapToGlobal(actionRect.topRight()); QToolTip::showText(globalPos, act->toolTip(), foundMenu, actionRect); - } else { + } + else { QToolTip::showText(QCursor::pos(), act->toolTip()); } } /* TRANSLATOR Gui::WorkbenchGroup */ -WorkbenchGroup::WorkbenchGroup ( Command* pcCmd, QObject * parent ) - : ActionGroup( pcCmd, parent ) +WorkbenchGroup::WorkbenchGroup(Command* pcCmd, QObject* parent) + : ActionGroup(pcCmd, parent) { refreshWorkbenchList(); - //NOLINTBEGIN - Application::Instance->signalRefreshWorkbenches.connect(std::bind(&WorkbenchGroup::refreshWorkbenchList, this)); - //NOLINTEND + // NOLINTBEGIN + Application::Instance->signalRefreshWorkbenches.connect( + std::bind(&WorkbenchGroup::refreshWorkbenchList, this) + ); + // NOLINTEND - connect(getMainWindow(), &MainWindow::workbenchActivated, - this, &WorkbenchGroup::onWorkbenchActivated); + connect(getMainWindow(), &MainWindow::workbenchActivated, this, &WorkbenchGroup::onWorkbenchActivated); } QAction* WorkbenchGroup::getOrCreateAction(const QString& wbName) @@ -658,11 +652,13 @@ QAction* WorkbenchGroup::getOrCreateAction(const QString& wbName) return actionByWorkbenchName[wbName]; } -void WorkbenchGroup::addTo(QWidget *widget) +void WorkbenchGroup::addTo(QWidget* widget) { if (widget->inherits("QToolBar")) { ParameterGrp::handle hGrp; - hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Workbenches"); + hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Workbenches" + ); QWidget* workbenchSelectorWidget; if (hGrp->GetInt("WorkbenchSelectorType", 0) == 0) { @@ -713,7 +709,7 @@ void WorkbenchGroup::refreshWorkbenchList() action->setText(name); action->setCheckable(true); - action->setData(QVariant(index)); // set the index + action->setData(QVariant(index)); // set the index action->setObjectName(wbName); action->setIcon(px); action->setToolTip(tip); @@ -741,7 +737,7 @@ void WorkbenchGroup::refreshWorkbenchList() action->setText(name); action->setCheckable(true); - action->setData(QVariant(index)); // set the index + action->setData(QVariant(index)); // set the index action->setObjectName(wbName); action->setIcon(px); action->setToolTip(tip); @@ -768,7 +764,7 @@ void WorkbenchGroup::onWorkbenchActivated(const QString& name) // To avoid to recursively (but only one recursion level) call Application:: // activateWorkbench the method refreshWorkbenchList() shouldn't set the // checked item. - //QVariant item = itemData(currentIndex()); + // QVariant item = itemData(currentIndex()); for (QAction* action : actions()) { if (action->objectName() == name) { @@ -797,10 +793,11 @@ class RecentFilesAction::Private: public ParameterGrp::ObserverType public: Private(const Private&) = delete; Private(Private&&) = delete; - void operator= (const Private&) = delete; - void operator= (Private&&) = delete; + void operator=(const Private&) = delete; + void operator=(Private&&) = delete; - Private(RecentFilesAction *master, const char *path):master(master) + Private(RecentFilesAction* master, const char* path) + : master(master) { handle = App::GetApplication().GetParameterGroupByPath(path); handle->Attach(this); @@ -811,10 +808,10 @@ public: handle->Detach(this); } - void OnChange(Base::Subject & sub, const char *reason) override + void OnChange(Base::Subject& sub, const char* reason) override { Q_UNUSED(sub) - if (!updating && reason && strcmp(reason, "RecentFiles")==0) { + if (!updating && reason && strcmp(reason, "RecentFiles") == 0) { Base::StateLocker guard(updating); master->restore(); } @@ -823,8 +820,9 @@ public: void trySaveUserParameter() { // update the XML structure and save the user parameter to disk (#0001989) - bool saveParameter = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/General")->GetBool("SaveUserParameter", true); + bool saveParameter = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetBool("SaveUserParameter", true); if (saveParameter) { saveUserParameter(); } @@ -837,7 +835,7 @@ public: } public: - RecentFilesAction *master; + RecentFilesAction* master; ParameterGrp::handle handle; bool updating = false; }; @@ -846,10 +844,10 @@ public: /* TRANSLATOR Gui::RecentFilesAction */ -RecentFilesAction::RecentFilesAction ( Command* pcCmd, QObject * parent ) - : ActionGroup( pcCmd, parent ) - , visibleItems(4) - , maximumItems(20) +RecentFilesAction::RecentFilesAction(Command* pcCmd, QObject* parent) + : ActionGroup(pcCmd, parent) + , visibleItems(4) + , maximumItems(20) { _pimpl = std::make_unique(this, "User parameter:BaseApp/Preferences/RecentFiles"); restore(); @@ -863,10 +861,9 @@ RecentFilesAction::RecentFilesAction ( Command* pcCmd, QObject * parent ) clearRecentFilesListAction.setToolTip({}); this->groupAction()->addAction(&clearRecentFilesListAction); - auto clearFun = [this, hGrp = _pimpl->handle](){ + auto clearFun = [this, hGrp = _pimpl->handle]() { const size_t recentFilesListSize = hGrp->GetASCIIs("MRU").size(); - for (size_t i = 0; i < recentFilesListSize; i++) - { + for (size_t i = 0; i < recentFilesListSize; i++) { const QByteArray key = QStringLiteral("MRU%1").arg(i).toLocal8Bit(); hGrp->SetASCII(key.data(), ""); } @@ -874,11 +871,14 @@ RecentFilesAction::RecentFilesAction ( Command* pcCmd, QObject * parent ) clearRecentFilesListAction.setEnabled(false); }; - connect(&clearRecentFilesListAction, &QAction::triggered, - this, clearFun); + connect(&clearRecentFilesListAction, &QAction::triggered, this, clearFun); - connect(&clearRecentFilesListAction, &QAction::triggered, - this, &RecentFilesAction::recentFilesListModified); + connect( + &clearRecentFilesListAction, + &QAction::triggered, + this, + &RecentFilesAction::recentFilesListModified + ); } RecentFilesAction::~RecentFilesAction() @@ -905,11 +905,12 @@ void RecentFilesAction::appendFile(const QString& filename) Q_EMIT recentFilesListModified(); } -static QString numberToLabel(int number) { - if (number > 0 && number < 10) { // NOLINT: *-magic-numbers +static QString numberToLabel(int number) +{ + if (number > 0 && number < 10) { // NOLINT: *-magic-numbers return QStringLiteral("&%1").arg(number); } - if (number == 10) { // NOLINT: *-magic-numbers + if (number == 10) { // NOLINT: *-magic-numbers return QStringLiteral("1&0"); } // If we have a number greater than 10, we start using the alphabet. @@ -938,7 +939,7 @@ void RecentFilesAction::setFiles(const QStringList& files) QFileInfo fi(files[index]); recentFiles[index]->setText(QStringLiteral("%1 %2").arg(numberLabel).arg(fi.fileName())); recentFiles[index]->setStatusTip(tr("Open file %1").arg(files[index])); - recentFiles[index]->setToolTip(files[index]); // set the full name that we need later for saving + recentFiles[index]->setToolTip(files[index]); // set the full name that we need later for saving recentFiles[index]->setData(QVariant(index)); recentFiles[index]->setVisible(true); } @@ -978,7 +979,7 @@ void RecentFilesAction::activateFile(int id) // restore the list of recent files QStringList files = this->files(); if (id < 0 || id >= files.count()) { - return; // no valid item + return; // no valid item } QString filename = files[id]; @@ -997,7 +998,7 @@ void RecentFilesAction::resizeList(int size) this->visibleItems = size; int diff = this->visibleItems - this->maximumItems; // create new items if needed - for (int i=0; iaddAction(QLatin1String(""))->setVisible(false); } setFiles(files()); @@ -1012,12 +1013,12 @@ void RecentFilesAction::restore() this->visibleItems = hGrp->GetInt("RecentFiles", this->visibleItems); int count = std::max(this->maximumItems, this->visibleItems); - for (int i=0; iaddAction(QLatin1String(""))->setVisible(false); } std::vector MRU = hGrp->GetASCIIs("MRU"); QStringList files; - for(const auto& it : MRU) { + for (const auto& it : MRU) { auto filePath = QString::fromUtf8(it.c_str()); if (QFileInfo::exists(filePath)) { files.append(filePath); @@ -1030,7 +1031,7 @@ void RecentFilesAction::restore() void RecentFilesAction::save() { ParameterGrp::handle hGrp = _pimpl->handle; - int count = hGrp->GetInt("RecentFiles", this->visibleItems); // save number of files + int count = hGrp->GetInt("RecentFiles", this->visibleItems); // save number of files hGrp->Clear(); // count all set items @@ -1046,17 +1047,17 @@ void RecentFilesAction::save() } Base::StateLocker guard(_pimpl->updating); - hGrp->SetInt("RecentFiles", count); // restore + hGrp->SetInt("RecentFiles", count); // restore } // -------------------------------------------------------------------- /* TRANSLATOR Gui::RecentMacrosAction */ -RecentMacrosAction::RecentMacrosAction ( Command* pcCmd, QObject * parent ) - : ActionGroup( pcCmd, parent ) - , visibleItems(4) - , maximumItems(20) +RecentMacrosAction::RecentMacrosAction(Command* pcCmd, QObject* parent) + : ActionGroup(pcCmd, parent) + , visibleItems(4) + , maximumItems(20) { restore(); } @@ -1074,8 +1075,9 @@ void RecentMacrosAction::appendFile(const QString& filename) save(); // update the XML structure and save the user parameter to disk (#0001989) - bool saveParameter = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/General")->GetBool("SaveUserParameter", true); + bool saveParameter = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetBool("SaveUserParameter", true); if (saveParameter) { ParameterManager* parmgr = App::GetApplication().GetParameterSet("User parameter"); parmgr->SaveDocument(App::Application::Config()["UserParameter"].c_str()); @@ -1088,11 +1090,15 @@ void RecentMacrosAction::appendFile(const QString& filename) */ void RecentMacrosAction::setFiles(const QStringList& files) { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences")->GetGroup("RecentMacros"); - this->shortcut_modifiers = hGrp->GetASCII("ShortcutModifiers","Ctrl+Shift+"); - this->shortcut_count = std::min(hGrp->GetInt("ShortcutCount",3),9);//max = 9, e.g. Ctrl+Shift+9 - this->visibleItems = hGrp->GetInt("RecentMacros",12); + ParameterGrp::handle hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("RecentMacros"); + this->shortcut_modifiers = hGrp->GetASCII("ShortcutModifiers", "Ctrl+Shift+"); + this->shortcut_count = std::min(hGrp->GetInt("ShortcutCount", 3), 9); // max = 9, e.g. + // Ctrl+Shift+9 + this->visibleItems = hGrp->GetInt("RecentMacros", 12); QList recentFiles = groupAction()->actions(); int numRecentFiles = std::min(recentFiles.count(), files.count()); @@ -1101,14 +1107,18 @@ void RecentMacrosAction::setFiles(const QStringList& files) for (int index = 0; index < numRecentFiles; index++) { QFileInfo fi(files[index]); QString numberLabel = numberToLabel(index + 1); - recentFiles[index]->setText(QStringLiteral("%1 %2").arg(numberLabel).arg(fi.completeBaseName())); - recentFiles[index]->setToolTip(files[index]); // set the full name that we need later for saving + recentFiles[index]->setText( + QStringLiteral("%1 %2").arg(numberLabel).arg(fi.completeBaseName()) + ); + recentFiles[index]->setToolTip(files[index]); // set the full name that we need later for saving recentFiles[index]->setData(QVariant(index)); QString accel(tr("none")); - if (index < shortcut_count){ + if (index < shortcut_count) { auto accel_tmp = QString::fromStdString(shortcut_modifiers); - accel_tmp.append(QString::number(index+1,10)).toStdString(); - auto check = Application::Instance->commandManager().checkAcceleratorForConflicts(qPrintable(accel_tmp)); + accel_tmp.append(QString::number(index + 1, 10)).toStdString(); + auto check = Application::Instance->commandManager().checkAcceleratorForConflicts( + qPrintable(accel_tmp) + ); if (check) { recentFiles[index]->setShortcut(QKeySequence()); accel_col.append(accel_tmp); @@ -1119,7 +1129,9 @@ void RecentMacrosAction::setFiles(const QStringList& files) recentFiles[index]->setShortcut(accel); } } - recentFiles[index]->setStatusTip(tr("Run macro %1 (Shift+click to edit) keyboard shortcut: %2").arg(files[index], accel)); + recentFiles[index]->setStatusTip( + tr("Run macro %1 (Shift+click to edit) keyboard shortcut: %2").arg(files[index], accel) + ); recentFiles[index]->setVisible(true); } @@ -1140,11 +1152,12 @@ void RecentMacrosAction::setFiles(const QStringList& files) for (int index = 0; index < existingCommands.count(); index++) { msgMain += QStringLiteral(" %1").arg(existingCommands[index]); } - msgMain += - QStringLiteral(" respectively.\nHint: In Preferences → Python → Macro →" - " Recent Macros menu → Keyboard Modifiers this should be Ctrl+Shift+" - " by default, if this is now blank then you should revert it back to" - " Ctrl+Shift+ by pressing both keys at the same time."); + msgMain += QStringLiteral( + " respectively.\nHint: In Preferences → Python → Macro →" + " Recent Macros menu → Keyboard Modifiers this should be Ctrl+Shift+" + " by default, if this is now blank then you should revert it back to" + " Ctrl+Shift+ by pressing both keys at the same time." + ); Base::Console().warning("%s\n", qPrintable(msgMain)); } } @@ -1172,7 +1185,7 @@ void RecentMacrosAction::activateFile(int id) // restore the list of recent files QStringList files = this->files(); if (id < 0 || id >= files.count()) { - return; // no valid item + return; // no valid item } QString filename = files[id]; @@ -1182,7 +1195,8 @@ void RecentMacrosAction::activateFile(int id) setFiles(files); } else { - if (QApplication::keyboardModifiers() == Qt::ShiftModifier){ //open for editing on Shift+click + if (QApplication::keyboardModifiers() + == Qt::ShiftModifier) { // open for editing on Shift+click auto editor = new PythonEditor(); editor->setWindowIcon(Gui::BitmapFactory().iconFromTheme("applications-python")); auto edit = new PythonEditorView(editor, getMainWindow()); @@ -1192,10 +1206,14 @@ void RecentMacrosAction::activateFile(int id) getMainWindow()->addWindow(edit); getMainWindow()->appendRecentMacro(filename); edit->setWindowTitle(fi.fileName()); - } else { //execute macro on normal (non-shifted) click + } + else { // execute macro on normal (non-shifted) click try { getMainWindow()->appendRecentMacro(fi.filePath()); - Application::Instance->macroManager()->run(Gui::MacroManager::File, fi.filePath().toUtf8()); + Application::Instance->macroManager()->run( + Gui::MacroManager::File, + fi.filePath().toUtf8() + ); // after macro run recalculate the document if (Application::Instance->activeDocument()) { Application::Instance->activeDocument()->getDocument()->recompute(); @@ -1216,7 +1234,7 @@ void RecentMacrosAction::resizeList(int size) this->visibleItems = size; int diff = this->visibleItems - this->maximumItems; // create new items if needed - for (int i=0; iaddAction(QLatin1String(""))->setVisible(false); } setFiles(files()); @@ -1225,10 +1243,13 @@ void RecentMacrosAction::resizeList(int size) /** Loads all recent files from the preferences. */ void RecentMacrosAction::restore() { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences")->GetGroup("RecentMacros"); + ParameterGrp::handle hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("RecentMacros"); - for (int i=groupAction()->actions().size(); imaximumItems; i++) { + for (int i = groupAction()->actions().size(); i < this->maximumItems; i++) { groupAction()->addAction(QLatin1String(""))->setVisible(false); } resizeList(hGrp->GetInt("RecentMacros")); @@ -1244,9 +1265,12 @@ void RecentMacrosAction::restore() /** Saves all recent files to the preferences. */ void RecentMacrosAction::save() { - ParameterGrp::handle hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences")->GetGroup("RecentMacros"); - int count = hGrp->GetInt("RecentMacros", this->visibleItems); // save number of files + ParameterGrp::handle hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("RecentMacros"); + int count = hGrp->GetInt("RecentMacros", this->visibleItems); // save number of files hGrp->Clear(); // count all set items @@ -1261,15 +1285,15 @@ void RecentMacrosAction::save() hGrp->SetASCII(key.toLatin1(), value.toUtf8()); } - hGrp->SetInt("RecentMacros", count); // restore + hGrp->SetInt("RecentMacros", count); // restore hGrp->SetInt("ShortcutCount", this->shortcut_count); - hGrp->SetASCII("ShortcutModifiers",this->shortcut_modifiers.c_str()); + hGrp->SetASCII("ShortcutModifiers", this->shortcut_modifiers.c_str()); } // -------------------------------------------------------------------- -UndoAction::UndoAction (Command* pcCmd,QObject * parent) - : Action(pcCmd, parent) +UndoAction::UndoAction(Command* pcCmd, QObject* parent) + : Action(pcCmd, parent) { _toolAction = new QAction(this); _toolAction->setMenu(new UndoDialog()); @@ -1283,7 +1307,7 @@ UndoAction::~UndoAction() delete _toolAction; } -void UndoAction::addTo (QWidget * widget) +void UndoAction::addTo(QWidget* widget) { if (widget->inherits("QToolBar")) { actionChanged(); @@ -1321,8 +1345,8 @@ void UndoAction::setVisible(bool check) // -------------------------------------------------------------------- -RedoAction::RedoAction ( Command* pcCmd,QObject * parent ) - : Action(pcCmd, parent) +RedoAction::RedoAction(Command* pcCmd, QObject* parent) + : Action(pcCmd, parent) { _toolAction = new QAction(this); _toolAction->setMenu(new RedoDialog()); @@ -1336,7 +1360,7 @@ RedoAction::~RedoAction() delete _toolAction; } -void RedoAction::addTo ( QWidget * widget ) +void RedoAction::addTo(QWidget* widget) { if (widget->inherits("QToolBar")) { actionChanged(); @@ -1360,13 +1384,13 @@ void RedoAction::actionChanged() _toolAction->setIcon(action()->icon()); } -void RedoAction::setEnabled ( bool check ) +void RedoAction::setEnabled(bool check) { Action::setEnabled(check); _toolAction->setEnabled(check); } -void RedoAction::setVisible ( bool check ) +void RedoAction::setVisible(bool check) { Action::setVisible(check); _toolAction->setVisible(check); @@ -1374,18 +1398,17 @@ void RedoAction::setVisible ( bool check ) // -------------------------------------------------------------------- -DockWidgetAction::DockWidgetAction ( Command* pcCmd, QObject * parent ) - : Action(pcCmd, parent) - , _menu(nullptr) -{ -} +DockWidgetAction::DockWidgetAction(Command* pcCmd, QObject* parent) + : Action(pcCmd, parent) + , _menu(nullptr) +{} DockWidgetAction::~DockWidgetAction() { delete _menu; } -void DockWidgetAction::addTo ( QWidget * widget ) +void DockWidgetAction::addTo(QWidget* widget) { if (!_menu) { _menu = new QMenu(); @@ -1398,23 +1421,22 @@ void DockWidgetAction::addTo ( QWidget * widget ) // -------------------------------------------------------------------- -ToolBarAction::ToolBarAction ( Command* pcCmd, QObject * parent ) - : Action(pcCmd, parent) - , _menu(nullptr) -{ -} +ToolBarAction::ToolBarAction(Command* pcCmd, QObject* parent) + : Action(pcCmd, parent) + , _menu(nullptr) +{} ToolBarAction::~ToolBarAction() { delete _menu; } -void ToolBarAction::addTo ( QWidget * widget ) +void ToolBarAction::addTo(QWidget* widget) { if (!_menu) { - _menu = new QMenu(); - action()->setMenu(_menu); - getMainWindow()->setToolBarMenu(_menu); + _menu = new QMenu(); + action()->setMenu(_menu); + getMainWindow()->setToolBarMenu(_menu); } widget->addAction(action()); @@ -1422,13 +1444,12 @@ void ToolBarAction::addTo ( QWidget * widget ) // -------------------------------------------------------------------- -WindowAction::WindowAction ( Command* pcCmd, QObject * parent ) - : ActionGroup(pcCmd, parent) - , _menu(nullptr) -{ -} +WindowAction::WindowAction(Command* pcCmd, QObject* parent) + : ActionGroup(pcCmd, parent) + , _menu(nullptr) +{} -void WindowAction::addTo ( QWidget * widget ) +void WindowAction::addTo(QWidget* widget) { auto menu = qobject_cast(widget); if (!menu) { diff --git a/src/Gui/Action.h b/src/Gui/Action.h index 6f9b55c395..b52ab61076 100644 --- a/src/Gui/Action.h +++ b/src/Gui/Action.h @@ -42,17 +42,17 @@ class Command; * methods in the class @ref MainWindow. * @author Werner Mayer */ -class GuiExport Action : public QObject +class GuiExport Action: public QObject { Q_OBJECT public: - explicit Action (Command* pcCmd, QObject * parent = nullptr); + explicit Action(Command* pcCmd, QObject* parent = nullptr); /// Action takes ownership of the 'action' object. - Action (Command* pcCmd, QAction* action, QObject * parent); + Action(Command* pcCmd, QAction* action, QObject* parent); ~Action() override; - virtual void addTo (QWidget * widget); + virtual void addTo(QWidget* widget); virtual void setEnabled(bool); virtual void setVisible(bool); @@ -62,56 +62,60 @@ public: bool isChecked() const; bool isEnabled() const; - void setShortcut (const QString &); + void setShortcut(const QString&); QKeySequence shortcut() const; - void setIcon (const QIcon &); + void setIcon(const QIcon&); QIcon icon() const; - void setStatusTip (const QString &); + void setStatusTip(const QString&); QString statusTip() const; - void setText (const QString &); + void setText(const QString&); QString text() const; - void setToolTip (const QString &, const QString &title = QString()); + void setToolTip(const QString&, const QString& title = QString()); QString toolTip() const; - void setWhatsThis (const QString &); + void setWhatsThis(const QString&); QString whatsThis() const; void setMenuRole(QAction::MenuRole menuRole); - QAction *action() const { + QAction* action() const + { return _action; } - static QString createToolTip(QString helpText, - const QString &title, - const QFont &font, - const QString &shortCut, - const Command *command = nullptr); + static QString createToolTip( + QString helpText, + const QString& title, + const QFont& font, + const QString& shortCut, + const Command* command = nullptr + ); /** Obtain tool tip of a given command * @param cmd: input command * @param richFormat: whether to output rich text formatted tooltip */ - static QString commandToolTip(const Command *cmd, bool richFormat = true); + static QString commandToolTip(const Command* cmd, bool richFormat = true); /** Obtain the menu text of a given command * @param cmd: input command * @return Return the command menu text that is stripped with its mnemonic * symbol '&' and ending punctuation */ - static QString commandMenuText(const Command *cmd); + static QString commandMenuText(const Command* cmd); /// Clean the title by stripping the mnemonic symbol '&' and ending punctuation - static QString cleanTitle(const QString &title); + static QString cleanTitle(const QString& title); - Command *command() const { + Command* command() const + { return _pcCmd; } public Q_SLOTS: - virtual void onActivated (); - virtual void onToggled (bool); + virtual void onActivated(); + virtual void onToggled(bool); private: QAction* _action; - Command *_pcCmd; + Command* _pcCmd; QString _tooltip; QString _title; QMetaObject::Connection _connection; @@ -129,41 +133,48 @@ private: * of toggable actions where e.g. one is set exclusive. * @author Werner Mayer */ -class GuiExport ActionGroup : public Action +class GuiExport ActionGroup: public Action { Q_OBJECT public: - explicit ActionGroup (Command* pcCmd, QObject * parent = nullptr); + explicit ActionGroup(Command* pcCmd, QObject* parent = nullptr); ~ActionGroup() override; - void addTo (QWidget * widget) override; - void setEnabled (bool) override; - void setDisabled (bool); - void setExclusive (bool); + void addTo(QWidget* widget) override; + void setEnabled(bool) override; + void setDisabled(bool); + void setExclusive(bool); bool isExclusive() const; - void setVisible (bool) override; - void setIsMode(bool check) { _isMode = check; } + void setVisible(bool) override; + void setIsMode(bool check) + { + _isMode = check; + } void setRememberLast(bool); bool doesRememberLast() const; - void setDropDownMenu(bool check) { _dropDown = check; } + void setDropDownMenu(bool check) + { + _dropDown = check; + } QAction* addAction(QAction*); QAction* addAction(const QString&); QList actions() const; int checkedAction() const; void setCheckedAction(int); - QActionGroup* groupAction() const { + QActionGroup* groupAction() const + { return _group; } public Q_SLOTS: - void onActivated () override; + void onActivated() override; void onToggled(bool) override; - void onActivated (QAction*); - void onHovered (QAction*); + void onActivated(QAction*); + void onHovered(QAction*); Q_SIGNALS: /// When drop down menu is enabled, the signal is triggered just before hiding the menu @@ -186,7 +197,7 @@ private: * to a menu a submenu gets created, if added to a toolbar a combo box gets created. * @author Werner Mayer */ -class GuiExport WorkbenchGroup : public ActionGroup +class GuiExport WorkbenchGroup: public ActionGroup { Q_OBJECT @@ -199,7 +210,7 @@ public: */ WorkbenchGroup(Command* pcCmd, QObject* parent); - void addTo(QWidget * widget) override; + void addTo(QWidget* widget) override; void refreshWorkbenchList(); void slotActivateWorkbench(const char*); @@ -228,12 +239,12 @@ private: * The RecentFilesAction class holds a menu listed with the recent files. * @author Werner Mayer */ -class GuiExport RecentFilesAction : public ActionGroup +class GuiExport RecentFilesAction: public ActionGroup { Q_OBJECT public: - explicit RecentFilesAction (Command* pcCmd, QObject * parent = nullptr); + explicit RecentFilesAction(Command* pcCmd, QObject* parent = nullptr); ~RecentFilesAction() override; void appendFile(const QString&); @@ -268,12 +279,12 @@ private: * The RecentMacrosAction class holds a menu listed with the recent macros * that were executed, edited, or created */ -class GuiExport RecentMacrosAction : public ActionGroup +class GuiExport RecentMacrosAction: public ActionGroup { Q_OBJECT public: - explicit RecentMacrosAction (Command* pcCmd, QObject * parent = nullptr); + explicit RecentMacrosAction(Command* pcCmd, QObject* parent = nullptr); void appendFile(const QString&); void activateFile(int); @@ -286,10 +297,10 @@ private: void save(); private: - int visibleItems; /**< Number of visible items */ - int maximumItems; /**< Number of maximum items */ + int visibleItems; /**< Number of visible items */ + int maximumItems; /**< Number of maximum items */ std::string shortcut_modifiers; /**< default = "Ctrl+Shift+" */ - int shortcut_count; /**< Number of dynamic shortcuts to create -- default = 3*/ + int shortcut_count; /**< Number of dynamic shortcuts to create -- default = 3*/ Q_DISABLE_COPY(RecentMacrosAction) }; @@ -302,14 +313,14 @@ private: * appearing when the button with the arrow is clicked. * @author Werner Mayer */ -class GuiExport UndoAction : public Action +class GuiExport UndoAction: public Action { Q_OBJECT public: - explicit UndoAction (Command* pcCmd,QObject * parent = nullptr); + explicit UndoAction(Command* pcCmd, QObject* parent = nullptr); ~UndoAction() override; - void addTo (QWidget * widget) override; + void addTo(QWidget* widget) override; void setEnabled(bool) override; void setVisible(bool) override; @@ -329,14 +340,14 @@ private: * appearing when the button with the arrow is clicked. * @author Werner Mayer */ -class GuiExport RedoAction : public Action +class GuiExport RedoAction: public Action { Q_OBJECT public: - explicit RedoAction (Command* pcCmd,QObject * parent = nullptr); + explicit RedoAction(Command* pcCmd, QObject* parent = nullptr); ~RedoAction() override; - void addTo ( QWidget * widget ) override; + void addTo(QWidget* widget) override; void setEnabled(bool) override; void setVisible(bool) override; @@ -355,14 +366,14 @@ private: * Special action to show all dockable views -- except of toolbars -- in an own popup menu. * @author Werner Mayer */ -class GuiExport DockWidgetAction : public Action +class GuiExport DockWidgetAction: public Action { Q_OBJECT public: - explicit DockWidgetAction (Command* pcCmd, QObject * parent = nullptr); + explicit DockWidgetAction(Command* pcCmd, QObject* parent = nullptr); ~DockWidgetAction() override; - void addTo (QWidget * widget) override; + void addTo(QWidget* widget) override; private: QMenu* _menu; @@ -376,14 +387,14 @@ private: * Special action to show all toolbars in an own popup menu. * @author Werner Mayer */ -class GuiExport ToolBarAction : public Action +class GuiExport ToolBarAction: public Action { Q_OBJECT public: - explicit ToolBarAction (Command* pcCmd, QObject * parent = nullptr); + explicit ToolBarAction(Command* pcCmd, QObject* parent = nullptr); ~ToolBarAction() override; - void addTo (QWidget * widget) override; + void addTo(QWidget* widget) override; private: QMenu* _menu; @@ -396,13 +407,13 @@ private: /** * @author Werner Mayer */ -class GuiExport WindowAction : public ActionGroup +class GuiExport WindowAction: public ActionGroup { Q_OBJECT public: - explicit WindowAction (Command* pcCmd, QObject * parent = nullptr); - void addTo (QWidget * widget) override; + explicit WindowAction(Command* pcCmd, QObject* parent = nullptr); + void addTo(QWidget* widget) override; private: QMenu* _menu; @@ -410,6 +421,6 @@ private: Q_DISABLE_COPY(WindowAction) }; -} // namespace Gui +} // namespace Gui -#endif // GUI_ACTION_H +#endif // GUI_ACTION_H diff --git a/src/Gui/ActionFunction.cpp b/src/Gui/ActionFunction.cpp index 9264c327c4..5df0a1d5ef 100644 --- a/src/Gui/ActionFunction.cpp +++ b/src/Gui/ActionFunction.cpp @@ -20,10 +20,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "ActionFunction.h" @@ -31,20 +31,21 @@ using namespace Gui; -namespace Gui { +namespace Gui +{ class ActionFunctionPrivate { public: - QMap > triggerMap; - QMap > toggleMap; - QMap > hoverMap; + QMap> triggerMap; + QMap> toggleMap; + QMap> hoverMap; }; -} +} // namespace Gui ActionFunction::ActionFunction(QObject* parent) - : QObject(parent), d_ptr(new ActionFunctionPrivate()) -{ -} + : QObject(parent) + , d_ptr(new ActionFunctionPrivate()) +{} ActionFunction::~ActionFunction() = default; @@ -61,7 +62,7 @@ void ActionFunction::triggered() Q_D(ActionFunction); auto a = qobject_cast(sender()); - QMap >::iterator it = d->triggerMap.find(a); + QMap>::iterator it = d->triggerMap.find(a); if (it != d->triggerMap.end()) { // invoke the class function here it.value()(); @@ -81,7 +82,7 @@ void ActionFunction::toggled(bool on) Q_D(ActionFunction); auto a = qobject_cast(sender()); - QMap >::iterator it = d->toggleMap.find(a); + QMap>::iterator it = d->toggleMap.find(a); if (it != d->toggleMap.end()) { // invoke the class function here it.value()(on); @@ -101,7 +102,7 @@ void ActionFunction::hovered() Q_D(ActionFunction); auto a = qobject_cast(sender()); - QMap >::iterator it = d->hoverMap.find(a); + QMap>::iterator it = d->hoverMap.find(a); if (it != d->hoverMap.end()) { // invoke the class function here it.value()(); @@ -110,7 +111,8 @@ void ActionFunction::hovered() // ---------------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ class TimerFunctionPrivate { public: @@ -121,10 +123,11 @@ public: QPointer argQObject; QVariant argQVariant; }; -} +} // namespace Gui TimerFunction::TimerFunction(QObject* parent) - : QObject(parent), d_ptr(new TimerFunctionPrivate()) + : QObject(parent) + , d_ptr(new TimerFunctionPrivate()) { d_ptr->autoDelete = false; } @@ -160,14 +163,18 @@ void TimerFunction::setAutoDelete(bool on) void TimerFunction::timeout() { Q_D(TimerFunction); - if (d->timeoutFunc) + if (d->timeoutFunc) { d->timeoutFunc(); - else if (d->timeoutFuncQObject) + } + else if (d->timeoutFuncQObject) { d->timeoutFuncQObject(d->argQObject); - else if (d->timeoutFuncQVariant) + } + else if (d->timeoutFuncQVariant) { d->timeoutFuncQVariant(d->argQVariant); - if (d->autoDelete) + } + if (d->autoDelete) { deleteLater(); + } } void TimerFunction::singleShot(int ms) diff --git a/src/Gui/ActionFunction.h b/src/Gui/ActionFunction.h index 76f46c5f21..0e8a8b5665 100644 --- a/src/Gui/ActionFunction.h +++ b/src/Gui/ActionFunction.h @@ -61,7 +61,7 @@ class ActionFunctionPrivate; http://www.boost.org/doc/libs/1_57_0/libs/bind/bind.html#with_boost_function */ -class GuiExport ActionFunction : public QObject +class GuiExport ActionFunction: public QObject { Q_OBJECT @@ -90,7 +90,7 @@ private: class TimerFunctionPrivate; -class GuiExport TimerFunction : public QObject +class GuiExport TimerFunction: public QObject { Q_OBJECT @@ -114,7 +114,7 @@ private: Q_DECLARE_PRIVATE(TimerFunction) }; -} //namespace Gui +} // namespace Gui -#endif // GUI_ACTIONFUNCTION_H +#endif // GUI_ACTIONFUNCTION_H diff --git a/src/Gui/ActiveObjectList.cpp b/src/Gui/ActiveObjectList.cpp index b8e158124a..612e0a0aff 100644 --- a/src/Gui/ActiveObjectList.cpp +++ b/src/Gui/ActiveObjectList.cpp @@ -1,25 +1,25 @@ /************************************************************************** -* Copyright (c) 2014 Jürgen Riegel * -* * -* This file is part of the FreeCAD CAx development system. * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License (LGPL) * -* as published by the Free Software Foundation; either version 2 of * -* the License, or (at your option) any later version. * -* for detail see the LICENCE text file. * -* * -* FreeCAD 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 FreeCAD; if not, write to the Free Software * -* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -* USA * -* * -***************************************************************************/ + * Copyright (c) 2014 Jürgen Riegel * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU Library General Public License (LGPL) * + * as published by the Free Software Foundation; either version 2 of * + * the License, or (at your option) any later version. * + * for detail see the LICENCE text file. * + * * + * FreeCAD 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 FreeCAD; if not, write to the Free Software * + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * + * USA * + * * + ***************************************************************************/ #include #include @@ -35,49 +35,66 @@ FC_LOG_LEVEL_INIT("MDIView", true, true) using namespace Gui; -App::DocumentObject *ActiveObjectList::getObject(const ObjectInfo &info, bool resolve, - App::DocumentObject **parent, - std::string *subname) const +App::DocumentObject* ActiveObjectList::getObject( + const ObjectInfo& info, + bool resolve, + App::DocumentObject** parent, + std::string* subname +) const { - if (parent) + if (parent) { *parent = info.obj; - if (subname) + } + if (subname) { *subname = info.subname; + } auto obj = info.obj; - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return nullptr; + } if (!info.subname.empty()) { obj = obj->getSubObject(info.subname.c_str()); - if (!obj) + if (!obj) { return nullptr; + } } return resolve ? obj->getLinkedObject(true) : obj; } -void ActiveObjectList::setHighlight(const ObjectInfo &info, HighlightMode mode, bool enable) +void ActiveObjectList::setHighlight(const ObjectInfo& info, HighlightMode mode, bool enable) { auto obj = getObject(info, false); - if (!obj) + if (!obj) { return; + } auto vp = freecad_cast(Application::Instance->getViewProvider(obj)); - if (!vp) + if (!vp) { return; + } if (TreeParams::getTreeActiveAutoExpand()) { - vp->getDocument()->signalExpandObject(*vp, enable ? TreeItemMode::ExpandPath : TreeItemMode::CollapseItem, - info.obj, info.subname.c_str()); + vp->getDocument()->signalExpandObject( + *vp, + enable ? TreeItemMode::ExpandPath : TreeItemMode::CollapseItem, + info.obj, + info.subname.c_str() + ); } vp->getDocument()->signalHighlightObject(*vp, mode, enable, info.obj, info.subname.c_str()); } -Gui::ActiveObjectList::ObjectInfo Gui::ActiveObjectList::getObjectInfo(App::DocumentObject *obj, const char *subname) const +Gui::ActiveObjectList::ObjectInfo Gui::ActiveObjectList::getObjectInfo( + App::DocumentObject* obj, + const char* subname +) const { ObjectInfo info; info.obj = nullptr; - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return info; + } if (subname) { info.obj = obj; @@ -87,18 +104,20 @@ Gui::ActiveObjectList::ObjectInfo Gui::ActiveObjectList::getObjectInfo(App::Docu // If the input object is not from this document, it must be brought in // by some link type object of this document. We only accept the object // if we can find such object in the current selection. - auto sels = Gui::Selection().getSelection(_Doc->getDocument()->getName(), ResolveMode::NoResolve); - for (auto &sel : sels) { - if (sel.pObject == obj || sel.pObject->getLinkedObject(true)==obj) { + auto sels + = Gui::Selection().getSelection(_Doc->getDocument()->getName(), ResolveMode::NoResolve); + for (auto& sel : sels) { + if (sel.pObject == obj || sel.pObject->getLinkedObject(true) == obj) { info.obj = sel.pObject; break; } - for (auto dot=strchr(sel.SubName,'.');dot;dot=strchr(dot+1,'.')) { - std::string subname(sel.SubName,dot-sel.SubName+1); + for (auto dot = strchr(sel.SubName, '.'); dot; dot = strchr(dot + 1, '.')) { + std::string subname(sel.SubName, dot - sel.SubName + 1); auto sobj = sel.pObject->getSubObject(subname.c_str()); - if (!sobj) + if (!sobj) { break; + } if (sobj == obj || sobj->getLinkedObject(true) == obj) { info.obj = sel.pObject; info.subname = subname; @@ -106,32 +125,36 @@ Gui::ActiveObjectList::ObjectInfo Gui::ActiveObjectList::getObjectInfo(App::Docu } } - if (info.obj) + if (info.obj) { break; + } } - if(!info.obj) { + if (!info.obj) { // No selection is found, try to obtain the object hierarchy using // DocumentObject::getParents() unsigned long count = 0xffffffff; - for(auto &v : obj->getParents()) { - if(v.first->getDocument() != _Doc->getDocument()) + for (auto& v : obj->getParents()) { + if (v.first->getDocument() != _Doc->getDocument()) { continue; + } // We prioritize on non-linked group object having the least // hierarchies. unsigned long cnt = v.first->getSubObjectList(v.second.c_str()).size(); - if(v.first->getLinkedObject(false) != v.first) + if (v.first->getLinkedObject(false) != v.first) { cnt &= 0x8000000; - if(cnt < count) { + } + if (cnt < count) { count = cnt; info.obj = v.first; info.subname = v.second; } } - if(!info.obj) { - if (obj->getDocument()!=_Doc->getDocument()) + if (!info.obj) { + if (obj->getDocument() != _Doc->getDocument()) { return info; + } info.obj = obj; } } @@ -140,34 +163,40 @@ Gui::ActiveObjectList::ObjectInfo Gui::ActiveObjectList::getObjectInfo(App::Docu return info; } -bool Gui::ActiveObjectList::hasObject(App::DocumentObject *obj, - const char *name, const char *subname) const +bool Gui::ActiveObjectList::hasObject(App::DocumentObject* obj, const char* name, const char* subname) const { auto it = _ObjectMap.find(name); - if (it == _ObjectMap.end()) + if (it == _ObjectMap.end()) { return false; + } auto info = getObjectInfo(obj, subname); return info.obj == it->second.obj && info.subname == it->second.subname; } -void Gui::ActiveObjectList::setObject(App::DocumentObject* obj, const char* name, - const char *subname, const Gui::HighlightMode& mode) +void Gui::ActiveObjectList::setObject( + App::DocumentObject* obj, + const char* name, + const char* subname, + const Gui::HighlightMode& mode +) { auto it = _ObjectMap.find(name); - if (it!=_ObjectMap.end()) { + if (it != _ObjectMap.end()) { setHighlight(it->second, mode, false); _ObjectMap.erase(it); } - if (!obj) + if (!obj) { return; + } - auto info = getObjectInfo(obj,subname); + auto info = getObjectInfo(obj, subname); if (!info.obj) { - FC_ERR("Cannot set active object " - << obj->getFullName() << '.' << (subname?subname:"") - << " in document '" << _Doc->getDocument()->getName() - << "'. Not found in current selection"); + FC_ERR( + "Cannot set active object " << obj->getFullName() << '.' << (subname ? subname : "") + << " in document '" << _Doc->getDocument()->getName() + << "'. Not found in current selection" + ); return; } @@ -175,12 +204,12 @@ void Gui::ActiveObjectList::setObject(App::DocumentObject* obj, const char* name setHighlight(info, mode, true); } -bool Gui::ActiveObjectList::hasObject(const char*name)const +bool Gui::ActiveObjectList::hasObject(const char* name) const { return _ObjectMap.find(name) != _ObjectMap.end(); } -void ActiveObjectList::objectDeleted(const ViewProviderDocumentObject &vp) +void ActiveObjectList::objectDeleted(const ViewProviderDocumentObject& vp) { // Hint: With C++20 std::erase_if for containers can be used auto isEqual = [&vp](const auto& item) { diff --git a/src/Gui/ActiveObjectList.h b/src/Gui/ActiveObjectList.h index bd058d0607..fee647cae4 100644 --- a/src/Gui/ActiveObjectList.h +++ b/src/Gui/ActiveObjectList.h @@ -1,25 +1,25 @@ /************************************************************************** -* Copyright (c) 2014 Jürgen Riegel * -* * -* This file is part of the FreeCAD CAx development system. * -* * -* This program is free software; you can redistribute it and/or modify * -* it under the terms of the GNU Library General Public License (LGPL) * -* as published by the Free Software Foundation; either version 2 of * -* the License, or (at your option) any later version. * -* for detail see the LICENCE text file. * -* * -* FreeCAD 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 FreeCAD; if not, write to the Free Software * -* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -* USA * -* * -***************************************************************************/ + * Copyright (c) 2014 Jürgen Riegel * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU Library General Public License (LGPL) * + * as published by the Free Software Foundation; either version 2 of * + * the License, or (at your option) any later version. * + * for detail see the LICENCE text file. * + * * + * FreeCAD 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 FreeCAD; if not, write to the Free Software * + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * + * USA * + * * + ***************************************************************************/ #ifndef GUI_ActiveObjectList_H @@ -32,61 +32,77 @@ #include -namespace App { - class DocumentObject; +namespace App +{ +class DocumentObject; } namespace Gui { - class Document; - class ViewProviderDocumentObject; +class Document; +class ViewProviderDocumentObject; - /** List of active or special objects - * This class holds a list of objects with a special name. - * Its mainly used to points to something like the active Body or Part in a edit session. - * The class is used the viewer (editor) of a document. - * @see Gui::MDIViewer - * @author Jürgen Riegel - */ - class GuiExport ActiveObjectList +/** List of active or special objects + * This class holds a list of objects with a special name. + * Its mainly used to points to something like the active Body or Part in a edit session. + * The class is used the viewer (editor) of a document. + * @see Gui::MDIViewer + * @author Jürgen Riegel + */ +class GuiExport ActiveObjectList +{ +public: + explicit ActiveObjectList(Document* doc) + : _Doc(doc) + {} + + template + inline _T getObject( + const char* name, + App::DocumentObject** parent = nullptr, + std::string* subname = nullptr + ) const { - public: - explicit ActiveObjectList(Document *doc) - :_Doc(doc) - {} - - template - inline _T getObject(const char* name, App::DocumentObject **parent=nullptr, std::string *subname=nullptr) const { - auto it = _ObjectMap.find(name); - if(it==_ObjectMap.end()) - return 0; - return dynamic_cast<_T>(getObject(it->second,true,parent,subname)); + auto it = _ObjectMap.find(name); + if (it == _ObjectMap.end()) { + return 0; } - void setObject(App::DocumentObject*, const char*, const char *subname=nullptr, - const Gui::HighlightMode& m = HighlightMode::UserDefined); - bool hasObject(const char*)const; - void objectDeleted(const ViewProviderDocumentObject& viewProviderIn); - bool hasObject(App::DocumentObject *obj, const char *, const char *subname=nullptr) const; + return dynamic_cast<_T>(getObject(it->second, true, parent, subname)); + } + void setObject( + App::DocumentObject*, + const char*, + const char* subname = nullptr, + const Gui::HighlightMode& m = HighlightMode::UserDefined + ); + bool hasObject(const char*) const; + void objectDeleted(const ViewProviderDocumentObject& viewProviderIn); + bool hasObject(App::DocumentObject* obj, const char*, const char* subname = nullptr) const; - App::DocumentObject* getObjectWithExtension(Base::Type extensionTypeId) const; + App::DocumentObject* getObjectWithExtension(Base::Type extensionTypeId) const; - private: - struct ObjectInfo; - void setHighlight(const ObjectInfo &info, Gui::HighlightMode mode, bool enable); - App::DocumentObject *getObject(const ObjectInfo &info, bool resolve, - App::DocumentObject **parent=nullptr, std::string *subname=nullptr) const; - ObjectInfo getObjectInfo(App::DocumentObject *obj, const char *subname) const; +private: + struct ObjectInfo; + void setHighlight(const ObjectInfo& info, Gui::HighlightMode mode, bool enable); + App::DocumentObject* getObject( + const ObjectInfo& info, + bool resolve, + App::DocumentObject** parent = nullptr, + std::string* subname = nullptr + ) const; + ObjectInfo getObjectInfo(App::DocumentObject* obj, const char* subname) const; - private: - struct ObjectInfo { - App::DocumentObject *obj; - std::string subname; - }; - std::map _ObjectMap; - Document *_Doc; +private: + struct ObjectInfo + { + App::DocumentObject* obj; + std::string subname; }; + std::map _ObjectMap; + Document* _Doc; +}; -} //namespace Gui +} // namespace Gui static const char PDBODYKEY[] = "pdbody"; static const char PARTKEY[] = "part"; diff --git a/src/Gui/Application.cpp b/src/Gui/Application.cpp index a6f49ddddb..b83539f006 100644 --- a/src/Gui/Application.cpp +++ b/src/Gui/Application.cpp @@ -146,7 +146,7 @@ #include #ifdef BUILD_TRACY_FRAME_PROFILER -#include +# include #endif using namespace Gui; @@ -168,16 +168,14 @@ class ViewProviderMap public: void newObject(const ViewProvider& vp) { - auto vpd = - freecad_cast(const_cast(&vp)); + auto vpd = freecad_cast(const_cast(&vp)); if (vpd && vpd->getObject()) { map[vpd->getObject()] = vpd; } } void deleteObject(const ViewProvider& vp) { - auto vpd = - freecad_cast(const_cast(&vp)); + auto vpd = freecad_cast(const_cast(&vp)); if (vpd && vpd->getObject()) { map.erase(vpd->getObject()); } @@ -253,11 +251,11 @@ static PyObject* FreeCADGui_subgraphFromObject(PyObject* /*self*/, PyObject* arg std::string vp = obj->getViewProviderName(); SoNode* node = nullptr; try { - auto base = - static_cast(Base::Type::createInstanceByName(vp.c_str(), true)); + auto base = static_cast(Base::Type::createInstanceByName(vp.c_str(), true)); if (base && base->isDerivedFrom()) { std::unique_ptr vp( - static_cast(base)); + static_cast(base) + ); std::map Map; obj->getPropertyMap(Map); vp->attach(obj); @@ -290,10 +288,8 @@ static PyObject* FreeCADGui_subgraphFromObject(PyObject* /*self*/, PyObject* arg type += " *"; PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", - type.c_str(), - static_cast(node), - 1); + proxy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", type.c_str(), static_cast(node), 1); return Py::new_reference_to(Py::Object(proxy, true)); } } @@ -387,7 +383,9 @@ void Application::initStyleParameterManager() static ParamHandlers handlers; const auto deduceParametersFilePath = []() -> std::string { - const auto hMainWindowGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow"); + const auto hMainWindowGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/MainWindow" + ); if (const std::string& path = hMainWindowGrp->GetASCII("ThemeStyleParametersFile"); !path.empty()) { @@ -400,7 +398,8 @@ void Application::initStyleParameterManager() auto themeParametersSource = new StyleParameters::YamlParameterSource( deduceParametersFilePath(), {.name = QT_TR_NOOP("Theme Parameters"), - .options = StyleParameters::ParameterSourceOption::UserEditable}); + .options = StyleParameters::ParameterSourceOption::UserEditable} + ); auto reloadStylesheetHandler = handlers.addDelayedHandler( "BaseApp/Preferences/MainWindow", @@ -413,31 +412,41 @@ void Application::initStyleParameterManager() bool tiledBG = hGrp->GetBool("TiledBackground", false); setStyleSheet(QString::fromStdString(sheet), tiledBG); - }); + } + ); - handlers.addHandler("BaseApp/Preferences/Themes", - {"ThemeAccentColor1", "ThemeAccentColor2", "ThemeAccentColor2"}, - reloadStylesheetHandler); + handlers.addHandler( + "BaseApp/Preferences/Themes", + {"ThemeAccentColor1", "ThemeAccentColor2", "ThemeAccentColor2"}, + reloadStylesheetHandler + ); Base::registerServiceImplementation( - new StyleParameters::BuiltInParameterSource({.name = QT_TR_NOOP("Built-in Parameters")})); + new StyleParameters::BuiltInParameterSource({.name = QT_TR_NOOP("Built-in Parameters")}) + ); // todo: left for compatibility with older theme versions, to be removed before release Base::registerServiceImplementation( new StyleParameters::UserParameterSource( App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Themes/UserTokens"), + "User parameter:BaseApp/Preferences/Themes/UserTokens" + ), {.name = QT_TR_NOOP("Theme Parameters - Fallback"), - .options = StyleParameters::ParameterSourceOption::ReadOnly})); + .options = StyleParameters::ParameterSourceOption::ReadOnly} + ) + ); Base::registerServiceImplementation(themeParametersSource); Base::registerServiceImplementation( new StyleParameters::UserParameterSource( App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Themes/UserParameters"), + "User parameter:BaseApp/Preferences/Themes/UserParameters" + ), {.name = QT_TR_NOOP("User Parameters"), - .options = StyleParameters::ParameterSource::UserEditable})); + .options = StyleParameters::ParameterSource::UserEditable} + ) + ); const auto sources = Base::provideServiceImplementations(); for (auto* source : std::views::all(sources) | std::views::reverse) { @@ -666,7 +675,8 @@ Application::Application(bool GUIenabled) #ifdef USE_3DCONNEXION_NAVLIB ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); if (!hViewGrp->GetBool("LegacySpaceMouseDevices", false)) { // Instantiate the 3Dconnexion controller pNavlibInterface = new NavlibInterface(); @@ -751,22 +761,25 @@ void Application::open(const char* FileName, const char* Module) } if (!handled) { - Command::doCommand(Command::App, - "FreeCAD.openDocument('%s')", - unicodepath.c_str()); + Command::doCommand(Command::App, "FreeCAD.openDocument('%s')", unicodepath.c_str()); Gui::Application::checkForRecomputes(); } } else { - std::string code = fmt::format("from freecad import module_io\n" - "module_io.OpenInsertObject(\"{}\", \"{}\", \"{}\")\n", - Module, unicodepath, "open"); + std::string code = fmt::format( + "from freecad import module_io\n" + "module_io.OpenInsertObject(\"{}\", \"{}\", \"{}\")\n", + Module, + unicodepath, + "open" + ); Gui::Command::runCommand(Gui::Command::App, code.c_str()); // ViewFit if (sendHasMsgToActiveView("ViewFit")) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); if (hGrp->GetBool("AutoFitToView", true)) { Command::doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")"); } @@ -788,7 +801,8 @@ void Application::open(const char* FileName, const char* Module) QMessageBox::warning( getMainWindow(), QObject::tr("Unknown filetype"), - QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str()))); + QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str())) + ); wc.setWaitCursor(); return; } @@ -831,9 +845,14 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch } } - std::string code = fmt::format("from freecad import module_io\n" - "module_io.OpenInsertObject(\"{}\", \"{}\", \"{}\", \"{}\")\n", - Module, unicodepath, "insert", DocName); + std::string code = fmt::format( + "from freecad import module_io\n" + "module_io.OpenInsertObject(\"{}\", \"{}\", \"{}\", \"{}\")\n", + Module, + unicodepath, + "insert", + DocName + ); Gui::Command::runCommand(Gui::Command::App, code.c_str()); // Commit the transaction @@ -852,7 +871,8 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch doc->setModified(true); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); if (hGrp->GetBool("AutoFitToView", true)) { MDIView* view = doc->getActiveView(); if (view) { @@ -868,10 +888,13 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch // the original file name is required QString filename = QString::fromUtf8(File.filePath().c_str()); auto parameterGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/General"); + "User parameter:BaseApp/Preferences/General" + ); bool addToRecent = parameterGroup->GetBool("RecentIncludesImported", true); - parameterGroup->SetBool("RecentIncludesImported", - addToRecent); // Make sure it gets added to the parameter list + parameterGroup->SetBool( + "RecentIncludesImported", + addToRecent + ); // Make sure it gets added to the parameter list if (addToRecent) { getMainWindow()->appendRecentFile(filename); } @@ -887,7 +910,8 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch QMessageBox::warning( getMainWindow(), QObject::tr("Unknown filetype"), - QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str()))); + QObject::tr("Cannot open unknown filetype: %1").arg(QLatin1String(te.c_str())) + ); wc.setWaitCursor(); } } @@ -907,8 +931,8 @@ void Application::exportTo(const char* FileName, const char* DocName, const char if (Module) { try { - std::vector sel = - Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId(), DocName); + std::vector sel + = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId(), DocName); if (sel.empty()) { App::Document* doc = App::GetApplication().getDocument(DocName); sel = doc->getObjectsOfType(App::DocumentObject::getClassTypeId()); @@ -937,15 +961,18 @@ void Application::exportTo(const char* FileName, const char* DocName, const char Gui::Command::runCommand(Gui::Command::App, code.c_str()); auto parameterGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/General"); + "User parameter:BaseApp/Preferences/General" + ); bool addToRecent = parameterGroup->GetBool("RecentIncludesExported", false); - parameterGroup->SetBool("RecentIncludesExported", - addToRecent); // Make sure it gets added to the parameter list + parameterGroup->SetBool( + "RecentIncludesExported", + addToRecent + ); // Make sure it gets added to the parameter list if (addToRecent) { // search for a module that is able to open the exported file because otherwise // it doesn't need to be added to the recent files list (#0002047) - std::map importMap = - App::GetApplication().getImportFilters(te.c_str()); + std::map importMap + = App::GetApplication().getImportFilters(te.c_str()); if (!importMap.empty()) { getMainWindow()->appendRecentFile(QString::fromUtf8(File.filePath().c_str())); } @@ -957,9 +984,11 @@ void Application::exportTo(const char* FileName, const char* DocName, const char // Usually thrown if the file is invalid somehow e.reportException(); wc.restoreCursor(); - QMessageBox::critical(getMainWindow(), - QObject::tr("Export failed"), - QString::fromUtf8(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Export failed"), + QString::fromUtf8(e.what()) + ); wc.setWaitCursor(); } } @@ -968,7 +997,8 @@ void Application::exportTo(const char* FileName, const char* DocName, const char QMessageBox::warning( getMainWindow(), QObject::tr("Unknown filetype"), - QObject::tr("Cannot save to unknown filetype: %1").arg(QLatin1String(te.c_str()))); + QObject::tr("Cannot save to unknown filetype: %1").arg(QLatin1String(te.c_str())) + ); wc.setWaitCursor(); } } @@ -998,14 +1028,14 @@ void Application::slotNewDocument(const App::Document& Doc, bool isMainDoc) // NOLINTBEGIN // connect the signals to the application for the new document pDoc->signalNewObject.connect(std::bind(&Gui::Application::slotNewObject, this, sp::_1)); - pDoc->signalDeletedObject.connect( - std::bind(&Gui::Application::slotDeletedObject, this, sp::_1)); + pDoc->signalDeletedObject.connect(std::bind(&Gui::Application::slotDeletedObject, this, sp::_1)); pDoc->signalChangedObject.connect( - std::bind(&Gui::Application::slotChangedObject, this, sp::_1, sp::_2)); - pDoc->signalRelabelObject.connect( - std::bind(&Gui::Application::slotRelabelObject, this, sp::_1)); + std::bind(&Gui::Application::slotChangedObject, this, sp::_1, sp::_2) + ); + pDoc->signalRelabelObject.connect(std::bind(&Gui::Application::slotRelabelObject, this, sp::_1)); pDoc->signalActivatedObject.connect( - std::bind(&Gui::Application::slotActivatedObject, this, sp::_1)); + std::bind(&Gui::Application::slotActivatedObject, this, sp::_1) + ); pDoc->signalInEdit.connect(std::bind(&Gui::Application::slotInEdit, this, sp::_1)); pDoc->signalResetEdit.connect(std::bind(&Gui::Application::slotResetEdit, this, sp::_1)); // NOLINTEND @@ -1080,44 +1110,60 @@ void Application::slotShowHidden(const App::Document& Doc) signalShowHidden(*doc->second); } -void Application::checkForRecomputes() { - std::vector docs; - for (auto doc: App::GetApplication().getDocuments()) { +void Application::checkForRecomputes() +{ + std::vector docs; + for (auto doc : App::GetApplication().getDocuments()) { if (doc->testStatus(App::Document::RecomputeOnRestore)) { docs.push_back(doc); doc->setStatus(App::Document::RecomputeOnRestore, false); } } - // Certain tests want to use very old .FCStd files. We should not prompt during those tests, so this - // allows them to 'FreeCAD.ConfigSet("SuppressRecomputeRequiredDialog", "True")` + // Certain tests want to use very old .FCStd files. We should not prompt during those tests, so + // this allows them to 'FreeCAD.ConfigSet("SuppressRecomputeRequiredDialog", "True")` const std::map& Map = App::Application::Config(); auto value = Map.find("SuppressRecomputeRequiredDialog"); - bool skip = value != Map.end() && ! value->second.empty(); // Any non empty string is true. - if (docs.empty() || skip ) + bool skip = value != Map.end() && !value->second.empty(); // Any non empty string is true. + if (docs.empty() || skip) { return; + } WaitCursor wc; wc.restoreCursor(); - auto res = QMessageBox::warning(getMainWindow(), QObject::tr("Recomputation required"), - QObject::tr("Some documents require recomputation for migration purposes. " - "It is highly recommended to perform a recomputation before " - "any modification to avoid compatibility problems.\n\n" - "Recompute now?"), - QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); - if (res != QMessageBox::Yes) + auto res = QMessageBox::warning( + getMainWindow(), + QObject::tr("Recomputation required"), + QObject::tr( + "Some documents require recomputation for migration purposes. " + "It is highly recommended to perform a recomputation before " + "any modification to avoid compatibility problems.\n\n" + "Recompute now?" + ), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes + ); + if (res != QMessageBox::Yes) { return; + } bool hasError = false; - for (auto doc: App::Document::getDependentDocuments(docs, true)) { + for (auto doc : App::Document::getDependentDocuments(docs, true)) { try { doc->recompute({}, false, &hasError); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); hasError = true; } } - if (hasError) - QMessageBox::critical(getMainWindow(), QObject::tr("Recompute error"), - QObject::tr("Failed to recompute some documents.\n" - "Check the report view for more details.")); + if (hasError) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Recompute error"), + QObject::tr( + "Failed to recompute some documents.\n" + "Check the report view for more details." + ) + ); + } } void Application::checkPartialRestore(App::Document* doc) @@ -1126,9 +1172,12 @@ void Application::checkPartialRestore(App::Document* doc) QMessageBox::critical( getMainWindow(), QObject::tr("Error"), - QObject::tr("There were errors while loading the file. Some data might have been " - "modified or not recovered at all. Look in the report view for more " - "specific information about the objects involved.")); + QObject::tr( + "There were errors while loading the file. Some data might have been " + "modified or not recovered at all. Look in the report view for more " + "specific information about the objects involved." + ) + ); } } @@ -1138,9 +1187,12 @@ void Application::checkRestoreError(App::Document* doc) QMessageBox::critical( getMainWindow(), QObject::tr("Error"), - QObject::tr("There were serious errors while loading the file. Some data might have " - "been modified or not recovered at all. Saving the project will most " - "likely result in loss of data.")); + QObject::tr( + "There were serious errors while loading the file. Some data might have " + "been modified or not recovered at all. Saving the project will most " + "likely result in loss of data." + ) + ); } } @@ -1172,7 +1224,8 @@ void Application::slotActiveDocument(const App::Document& Doc) // Update the application to show the unit change ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Units"); + "User parameter:BaseApp/Preferences/Units" + ); if (!hGrp->GetBool("IgnoreProjectSchema")) { int userSchema = Doc.UnitSystem.getValue(); Base::UnitsApi::setSchema(userSchema); @@ -1233,9 +1286,11 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) if (!d->isClosing && pcDoc) { // Call the closing mechanism from Python. This also checks whether pcDoc is the last // open document. - Command::doCommand(Command::Doc, - "App.closeDocument(\"%s\")", - pcDoc->getDocument()->getName()); + Command::doCommand( + Command::Doc, + "App.closeDocument(\"%s\")", + pcDoc->getDocument()->getName() + ); if (!d->activeDocument && !d->documents.empty()) { Document* gdoc = nullptr; for (auto& v : d->documents) { @@ -1272,11 +1327,13 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) Base::Console().error( "Unhandled std::exception caught in Application::onLastWindowClosed.\n" "The error message is: %s\n", - e.what()); + e.what() + ); } catch (...) { Base::Console().error( - "Unhandled unknown exception caught in Application::onLastWindowClosed.\n"); + "Unhandled unknown exception caught in Application::onLastWindowClosed.\n" + ); } } @@ -1382,7 +1439,8 @@ void Application::setEditDocument(Gui::Document* doc) { if (!doc) { d->editDocument = nullptr; - } else if (doc == d->editDocument) { + } + else if (doc == d->editDocument) { return; } for (auto& v : d->documents) { @@ -1449,9 +1507,7 @@ void Application::setActiveDocument(Gui::Document* pcDocument) // May be useful for error detection if (d->activeDocument) { App::Document* doc = d->activeDocument->getDocument(); - Base::Console().log("Active document is %s (at %p)\n", - doc->getName(), - static_cast(doc)); + Base::Console().log("Active document is %s (at %p)\n", doc->getName(), static_cast(doc)); } else { Base::Console().log("No active document\n"); @@ -1537,9 +1593,11 @@ void Application::viewActivated(MDIView* pcView) { #ifdef FC_DEBUG // May be useful for error detection - Base::Console().log("Active view is %s (at %p)\n", - (const char*)pcView->windowTitle().toUtf8(), - static_cast(pcView)); + Base::Console().log( + "Active view is %s (at %p)\n", + (const char*)pcView->windowTitle().toUtf8(), + static_cast(pcView) + ); #endif signalActivateView(pcView); @@ -1580,8 +1638,7 @@ void Application::tryClose(QCloseEvent* e) } // ask all passive views if closable - for (std::list::iterator It = d->passive.begin(); It != d->passive.end(); - ++It) { + for (std::list::iterator It = d->passive.begin(); It != d->passive.end(); ++It) { e->setAccepted((*It)->canClose()); if (!e->isAccepted()) { return; @@ -1795,9 +1852,11 @@ bool Application::activateWorkbench(const char* name) if (!d->startingUp) { wc.restoreCursor(); - QMessageBox::critical(getMainWindow(), - QObject::tr("Workbench failure"), - QObject::tr("%1").arg(msg)); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Workbench failure"), + QObject::tr("%1").arg(msg) + ); wc.setWaitCursor(); } } @@ -2126,11 +2185,11 @@ void messageHandlerCoin(const SoError* error, void* /*userdata*/) Base::Console().error("%s\n", msg); break; } -#ifdef FC_OS_WIN32 +# ifdef FC_OS_WIN32 if (old_qtmsg_handler) { (*old_qtmsg_handler)(QtDebugMsg, QMessageLogContext(), QString::fromLatin1(msg)); } -#endif +# endif } else if (error) { const char* msg = error->getDebugString().getString(); @@ -2306,23 +2365,20 @@ void setAppNameAndIcon() QApplication::setApplicationName(QString::fromUtf8(it->second.c_str())); } else { - QApplication::setApplicationName( - QString::fromStdString(App::Application::getExecutableName())); + QApplication::setApplicationName(QString::fromStdString(App::Application::getExecutableName())); } #ifndef Q_OS_MACOS QApplication::setWindowIcon( - Gui::BitmapFactory().pixmap(App::Application::Config()["AppIcon"].c_str())); + Gui::BitmapFactory().pixmap(App::Application::Config()["AppIcon"].c_str()) + ); #endif } void tryRunEventLoop(GUISingleApplication& mainApp) { std::stringstream out; - out << App::Application::getUserCachePath() - << App::Application::getExecutableName() - << "_" - << App::Application::applicationPid() - << ".lock"; + out << App::Application::getUserCachePath() << App::Application::getExecutableName() << "_" + << App::Application::applicationPid() << ".lock"; // open a lock file with the PID Base::FileInfo fi(out.str()); @@ -2353,14 +2409,18 @@ void tryRunEventLoop(GUISingleApplication& mainApp) fi.deleteFile(); } else { - Base::Console().warning("Failed to create a file lock for the IPC.\n" - "The application will be terminated\n"); + Base::Console().warning( + "Failed to create a file lock for the IPC.\n" + "The application will be terminated\n" + ); } } catch (const boost::interprocess::interprocess_exception& e) { QString msg = QString::fromLocal8Bit(e.what()); - Base::Console().warning("Failed to create a file lock for the IPC: %s\n", - msg.toUtf8().constData()); + Base::Console().warning( + "Failed to create a file lock for the IPC: %s\n", + msg.toUtf8().constData() + ); } } @@ -2423,7 +2483,8 @@ void Application::runApplication() int argc = App::Application::GetARGC(); GUISingleApplication mainApp(argc, App::Application::GetARGV()); -#if (COIN_MAJOR_VERSION * 100 + COIN_MINOR_VERSION * 10 + COIN_MICRO_VERSION < 406) && (defined(FC_OS_LINUX) || defined(FC_OS_BSD)) +#if (COIN_MAJOR_VERSION * 100 + COIN_MINOR_VERSION * 10 + COIN_MICRO_VERSION < 406) \ + && (defined(FC_OS_LINUX) || defined(FC_OS_BSD)) // If QT is running with native Wayland then inform Coin to use EGL if (QGuiApplication::platformName() == QString::fromStdString("wayland")) { setenv("COIN_EGL", "1", 1); @@ -2486,7 +2547,7 @@ void Application::runApplication() bool Application::hiddenMainWindow() { - const std::map& cfg = App::Application::Config(); + const std::map& cfg = App::Application::Config(); auto it = cfg.find("StartHidden"); return it != cfg.end(); @@ -2638,16 +2699,19 @@ void Application::checkForDeprecatedSettings() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") ->GetBool("CreateBackupFiles", true); if (makeBackups) { - bool useFCBakExtension = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") - ->GetBool("UseFCBakExtension", true); + bool useFCBakExtension = App::GetApplication() + .GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Document" + ) + ->GetBool("UseFCBakExtension", true); if (!useFCBakExtension) { // TODO: This should be translated - Base::Console().warning("The `.FCStd#` backup format is deprecated and may " - "be removed in future versions.\n" - "To update, check the 'Preferences->General->Document->Use " - "date and FCBak extension' option.\n"); + Base::Console().warning( + "The `.FCStd#` backup format is deprecated and may " + "be removed in future versions.\n" + "To update, check the 'Preferences->General->Document->Use " + "date and FCBak extension' option.\n" + ); } } } @@ -2669,8 +2733,10 @@ void Application::checkForPreviousCrashes() } catch (const boost::interprocess::interprocess_exception& e) { QString msg = QString::fromLocal8Bit(e.what()); - Base::Console().warning("Failed check for previous crashes because of IPC error: %s\n", - msg.toUtf8().constData()); + Base::Console().warning( + "Failed check for previous crashes because of IPC error: %s\n", + msg.toUtf8().constData() + ); } } @@ -2690,8 +2756,7 @@ App::Document* Application::reopen(App::Document* doc) WaitCursor wc; wc.setIgnoreEvents(WaitCursor::NoEvents); - if (doc->testStatus(App::Document::PartialDoc) - || doc->testStatus(App::Document::PartialRestore)) { + if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::PartialRestore)) { App::GetApplication().openDocument(name.c_str()); } else { @@ -2715,9 +2780,7 @@ App::Document* Application::reopen(App::Document* doc) } for (auto& file : docs) { - App::DocumentInitFlags initFlags { - .createView = false - }; + App::DocumentInitFlags initFlags {.createView = false}; App::GetApplication().openDocument(file.c_str(), initFlags); } } @@ -2758,23 +2821,23 @@ App::Document* Application::reopen(App::Document* doc) return doc; } -void Application::getVerboseDPIStyleInfo(QTextStream& str) { +void Application::getVerboseDPIStyleInfo(QTextStream& str) +{ // Add Stylesheet/Theme/Qtstyle information - std::string styleSheet = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow") - ->GetASCII("StyleSheet"); - std::string theme = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow") - ->GetASCII("Theme"); + std::string styleSheet = App::GetApplication() + .GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/MainWindow" + ) + ->GetASCII("StyleSheet"); + std::string theme = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow") + ->GetASCII("Theme"); #if QT_VERSION >= QT_VERSION_CHECK(6, 1, 0) std::string style = qApp->style()->name().toStdString(); #else - std::string style = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow") - ->GetASCII("QtStyle"); + std::string style = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/MainWindow") + ->GetASCII("QtStyle"); if (style.empty()) { style = "Qt default"; } @@ -2791,10 +2854,7 @@ void Application::getVerboseDPIStyleInfo(QTextStream& str) { // Add DPI information str << "Logical DPI/Physical DPI/Pixel Ratio: " - << QApplication::primaryScreen()->logicalDotsPerInch() - << "/" - << QApplication::primaryScreen()->physicalDotsPerInch() - << "/" - << QApplication::primaryScreen()->devicePixelRatio() - << "\n"; + << QApplication::primaryScreen()->logicalDotsPerInch() << "/" + << QApplication::primaryScreen()->physicalDotsPerInch() << "/" + << QApplication::primaryScreen()->devicePixelRatio() << "\n"; } diff --git a/src/Gui/Application.h b/src/Gui/Application.h index 522ab8e205..8a2c634f84 100644 --- a/src/Gui/Application.h +++ b/src/Gui/Application.h @@ -36,7 +36,8 @@ class QCloseEvent; class SoNode; class NavlibInterface; -namespace Gui{ +namespace Gui +{ class ApplicationPy; class BaseView; class CommandManager; @@ -56,7 +57,8 @@ class ViewProviderDocumentObject; class GuiExport Application { public: - enum Status { + enum Status + { UserInitiatedOpenDocument = 0 }; @@ -77,7 +79,7 @@ public: /// Export objects from the document DocName to a single file void exportTo(const char* FileName, const char* DocName, const char* Module); /// Reload a partial opened document - App::Document *reopen(App::Document *doc); + App::Document* reopen(App::Document* doc); /// Prompt about recomputing if needed static void checkForRecomputes(); /// Prompt about PartialRestore @@ -90,11 +92,11 @@ public: /** @name methods for View handling */ //@{ /// send Messages to the active view - bool sendMsgToActiveView(const char* pMsg, const char** ppReturn=nullptr); + bool sendMsgToActiveView(const char* pMsg, const char** ppReturn = nullptr); /// send Messages test to the active view bool sendHasMsgToActiveView(const char* pMsg); /// send Messages to the focused view - bool sendMsgToFocusView(const char* pMsg, const char** ppReturn=nullptr); + bool sendMsgToFocusView(const char* pMsg, const char** ppReturn = nullptr); /// send Messages test to the focused view bool sendHasMsgToFocusView(const char* pMsg); /// Attach a view (get called by the FCView constructor) @@ -116,50 +118,50 @@ public: /** @name Signals of the Application */ //@{ /// signal on new Document - boost::signals2::signal signalNewDocument; + boost::signals2::signal signalNewDocument; /// signal on deleted Document - boost::signals2::signal signalDeleteDocument; + boost::signals2::signal signalDeleteDocument; /// signal on relabeling Document - boost::signals2::signal signalRelabelDocument; + boost::signals2::signal signalRelabelDocument; /// signal on renaming Document - boost::signals2::signal signalRenameDocument; + boost::signals2::signal signalRenameDocument; /// signal on activating Document - boost::signals2::signal signalActiveDocument; + boost::signals2::signal signalActiveDocument; /// signal on new Object - boost::signals2::signal signalNewObject; + boost::signals2::signal signalNewObject; /// signal on deleted Object - boost::signals2::signal signalDeletedObject; + boost::signals2::signal signalDeletedObject; /// signal on changed Object - boost::signals2::signal signalBeforeChangeObject; + boost::signals2::signal signalBeforeChangeObject; /// signal on changed object property - boost::signals2::signal signalChangedObject; + boost::signals2::signal signalChangedObject; /// signal on renamed Object - boost::signals2::signal signalRelabelObject; + boost::signals2::signal signalRelabelObject; /// signal on activated Object - boost::signals2::signal signalActivatedObject; + boost::signals2::signal signalActivatedObject; /// signal on activated workbench - boost::signals2::signal signalActivateWorkbench; + boost::signals2::signal signalActivateWorkbench; /// signal on added/removed workbench - boost::signals2::signal signalRefreshWorkbenches; + boost::signals2::signal signalRefreshWorkbenches; /// signal on show hidden items - boost::signals2::signal signalShowHidden; + boost::signals2::signal signalShowHidden; /// signal on activating view - boost::signals2::signal signalActivateView; + boost::signals2::signal signalActivateView; /// signal on closing view - boost::signals2::signal signalCloseView; + boost::signals2::signal signalCloseView; /// signal on entering in edit mode - boost::signals2::signal signalInEdit; + boost::signals2::signal signalInEdit; /// signal on leaving edit mode - boost::signals2::signal signalResetEdit; + boost::signals2::signal signalResetEdit; /// signal on changing user edit mode - boost::signals2::signal signalUserEditModeChanged; + boost::signals2::signal signalUserEditModeChanged; //@} /** @name methods for Document handling */ //@{ protected: /// Observer message from the Application - void slotNewDocument(const App::Document&,bool); + void slotNewDocument(const App::Document&, bool); void slotDeleteDocument(const App::Document&); void slotRelabelDocument(const App::Document&); void slotRenameDocument(const App::Document&); @@ -182,21 +184,21 @@ public: void setActiveDocument(Gui::Document* pcDocument); /// Getter for the editing document Gui::Document* editDocument() const; - Gui::MDIView* editViewOfNode(SoNode *node) const; + Gui::MDIView* editViewOfNode(SoNode* node) const; /// Set editing document, which will reset editing of all other document void setEditDocument(Gui::Document* pcDocument); /** Retrieves a pointer to the Gui::Document whose App::Document has the name \a name. - * If no such document exists 0 is returned. - */ + * If no such document exists 0 is returned. + */ Gui::Document* getDocument(const char* name) const; /** Retrieves a pointer to the Gui::Document whose App::Document matches to \a pDoc. - * If no such document exists 0 is returned. - */ + * If no such document exists 0 is returned. + */ Gui::Document* getDocument(const App::Document* pDoc) const; /// Getter for the active view of the active document or null Gui::MDIView* activeView() const; /// Activate a view of the given type of the active document - void activateView(const Base::Type&, bool create=false); + void activateView(const Base::Type&, bool create = false); /// Shows the associated view provider of the given object void showViewProvider(const App::DocumentObject*); /// Hides the associated view provider of the given object @@ -204,7 +206,7 @@ public: /// Get the view provider of the given object Gui::ViewProvider* getViewProvider(const App::DocumentObject*) const; /// Get the type safe view provider of the given object - template + template T* getViewProvider(const App::DocumentObject* obj) const { return freecad_cast(getViewProvider(obj)); @@ -239,9 +241,9 @@ public: /** @name User Commands */ //@{ /// Get macro manager - Gui::MacroManager *macroManager(); + Gui::MacroManager* macroManager(); /// Reference to the command manager - Gui::CommandManager &commandManager(); + Gui::CommandManager& commandManager(); /// helper which create the commands void createStandardOperations(); //@} @@ -258,7 +260,7 @@ public: static void initOpenInventor(); static void runInitGuiScript(); static void runApplication(); - void tryClose( QCloseEvent * e ); + void tryClose(QCloseEvent* e); //@} /// get verbose DPI and style info @@ -281,33 +283,51 @@ protected: {0, std::make_pair( QT_TRANSLATE_NOOP("EditMode", "&Default"), - QT_TRANSLATE_NOOP("EditMode", - "The object will be edited using the mode defined internally to be " - "the most appropriate for the object type"))}, + QT_TRANSLATE_NOOP( + "EditMode", + "The object will be edited using the mode defined internally to be " + "the most appropriate for the object type" + ) + )}, {1, - std::make_pair(QT_TRANSLATE_NOOP("EditMode", "Trans&form"), - QT_TRANSLATE_NOOP("EditMode", - "The object will have its placement editable with the " - "Std TransformManip command"))}, + std::make_pair( + QT_TRANSLATE_NOOP("EditMode", "Trans&form"), + QT_TRANSLATE_NOOP( + "EditMode", + "The object will have its placement editable with the " + "Std TransformManip command" + ) + )}, {2, - std::make_pair(QT_TRANSLATE_NOOP("EditMode", "Cu&tting"), - QT_TRANSLATE_NOOP("EditMode", - "This edit mode is implemented as available but " - "currently does not seem to be used by any object"))}, + std::make_pair( + QT_TRANSLATE_NOOP("EditMode", "Cu&tting"), + QT_TRANSLATE_NOOP( + "EditMode", + "This edit mode is implemented as available but " + "currently does not seem to be used by any object" + ) + )}, {3, - std::make_pair(QT_TRANSLATE_NOOP("EditMode", "&Color"), - QT_TRANSLATE_NOOP("EditMode", - "The object will have the color of its individual faces " - "editable with the Appearance per Face command"))}, + std::make_pair( + QT_TRANSLATE_NOOP("EditMode", "&Color"), + QT_TRANSLATE_NOOP( + "EditMode", + "The object will have the color of its individual faces " + "editable with the Appearance per Face command" + ) + )}, }; int userEditMode = userEditModes.begin()->first; public: - std::map > listUserEditModes() const { return userEditModes; } - int getUserEditMode(const std::string &mode = "") const; - std::pair getUserEditModeUIStrings(int mode = -1) const; + std::map> listUserEditModes() const + { + return userEditModes; + } + int getUserEditMode(const std::string& mode = "") const; + std::pair getUserEditModeUIStrings(int mode = -1) const; bool setUserEditMode(int mode); - bool setUserEditMode(const std::string &mode); + bool setUserEditMode(const std::string& mode); //@} private: @@ -319,6 +339,6 @@ private: friend class ApplicationPy; }; -} //namespace Gui +} // namespace Gui #endif diff --git a/src/Gui/ApplicationPy.cpp b/src/Gui/ApplicationPy.cpp index 5f4f1700ee..8dc2373baf 100644 --- a/src/Gui/ApplicationPy.cpp +++ b/src/Gui/ApplicationPy.cpp @@ -20,15 +20,15 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -74,374 +74,492 @@ using namespace Gui; // Application methods structure PyMethodDef ApplicationPy::Methods[] = { - {"activateWorkbench",(PyCFunction) ApplicationPy::sActivateWorkbenchHandler, METH_VARARGS, - "activateWorkbench(name) -> bool\n" - "\n" - "Activate workbench by its name. Return False if the workbench is\n" - "already active.\n" - "\n" - "name : str\n Name of the workbench to activate."}, - {"addWorkbench", (PyCFunction) ApplicationPy::sAddWorkbenchHandler, METH_VARARGS, - "addWorkbench(workbench) -> None\n" - "\n" - "Add a workbench.\n" - "\n" - "workbench : Workbench, Workbench type\n" - " Instance of a Workbench subclass or subclass of the\n" - " Workbench class."}, - {"removeWorkbench", (PyCFunction) ApplicationPy::sRemoveWorkbenchHandler, METH_VARARGS, - "removeWorkbench(name) -> None\n" - "\n" - "Remove a workbench.\n" - "\n" - "name : str\n Name of the workbench to remove."}, - {"getWorkbench", (PyCFunction) ApplicationPy::sGetWorkbenchHandler, METH_VARARGS, - "getWorkbench(name) -> Workbench\n" - "\n" - "Get the workbench by its name.\n" - "\n" - "name : str\n Name of the workbench to return."}, - {"listWorkbenches", (PyCFunction) ApplicationPy::sListWorkbenchHandlers, METH_VARARGS, - "listWorkbenches() -> dict\n" - "\n" - "Get a dictionary with all workbenches."}, - {"activeWorkbench", (PyCFunction) ApplicationPy::sActiveWorkbenchHandler, METH_VARARGS, - "activeWorkbench() -> Workbench\n" - "\n" - "Return the active workbench object."}, - {"addResourcePath", (PyCFunction) ApplicationPy::sAddResPath, METH_VARARGS, - "addResourcePath(path) -> None\n" - "\n" - "Add a new path to the system where to find resource files\n" - "like icons or localization files.\n" - "\n" - "path : str, bytes, bytearray\n Path to resource files."}, - {"addLanguagePath", (PyCFunction) ApplicationPy::sAddLangPath, METH_VARARGS, - "addLanguagePath(path) -> None\n" - "\n" - "Add a new path to the system where to find language files.\n" - "\n" - "path : str, bytes, bytearray\n Path to language files."}, - {"addIconPath", (PyCFunction) ApplicationPy::sAddIconPath, METH_VARARGS, - "addIconPath(path) -> None\n" - "\n" - "Add a new path to the system where to find icon files.\n" - "\n" - "path : str, bytes, bytearray\n Path to icon files."}, - {"addIcon", (PyCFunction) ApplicationPy::sAddIcon, METH_VARARGS, - "addIcon(name, content, format='XPM') -> None\n" - "\n" - "Add an icon to the system.\n" - "\n" - "name : str\n Name of the icon.\n" - "content : str, bytes-like\n Content of the icon.\n" - "format : str\n Format of the icon."}, - {"getIcon", (PyCFunction) ApplicationPy::sGetIcon, METH_VARARGS, - "getIcon(name) -> QIcon or None\n" - "\n" - "Get an icon in the system. If the pixmap is null, return None.\n" - "\n" - "name : str\n Name of the icon."}, - {"isIconCached", (PyCFunction) ApplicationPy::sIsIconCached, METH_VARARGS, - "isIconCached(name) -> Bool\n" - "\n" - "Check if an icon with the given name is cached.\n" - "\n" - "name : str\n Name of the icon."}, - {"getMainWindow", (PyCFunction) ApplicationPy::sGetMainWindow, METH_VARARGS, - "getMainWindow() -> QMainWindow\n" - "\n" - "Return the main window instance."}, - {"updateGui", (PyCFunction) ApplicationPy::sUpdateGui, METH_VARARGS, - "updateGui() -> None\n" - "\n" - "Update the main window and all its windows."}, - {"updateLocale", (PyCFunction) ApplicationPy::sUpdateLocale, METH_VARARGS, - "updateLocale() -> None\n" - "\n" - "Update the localization."}, - {"getLocale", (PyCFunction) ApplicationPy::sGetLocale, METH_VARARGS, - "getLocale() -> str\n" - "\n" - "Returns the locale currently used by FreeCAD."}, - {"setLocale", (PyCFunction) ApplicationPy::sSetLocale, METH_VARARGS, - "setLocale(name) -> None\n" - "\n" - "Sets the locale used by FreeCAD. Can be set by top-level\n" - "domain (e.g. \"de\") or the language name (e.g. \"German\").\n" - "\n" - "name : str\n Locale name."}, - {"supportedLocales", (PyCFunction) ApplicationPy::sSupportedLocales, METH_VARARGS, - "supportedLocales() -> dict\n" - "\n" - "Returns a dict of all supported locales. The keys are the language\n" - "names and the values the top-level domains."}, - {"createDialog", (PyCFunction) ApplicationPy::sCreateDialog, METH_VARARGS, - "createDialog(path) -> PyResource\n" - "\n" - "Open a UI file.\n" - "\n" - "path : str\n UI file path."}, - {"addPreferencePage", (PyCFunction) ApplicationPy::sAddPreferencePage, METH_VARARGS, - "addPreferencePage(path, group) -> None\n" - "addPreferencePage(dialog, group) -> None\n" - "\n" - "Add a UI form to the preferences dialog in the specified group.\n" - "\n" - "path : str\n UI file path.\n" - "group : str\n Group name.\n" - "dialog : type\n Preference page."}, - {"addCommand", (PyCFunction) ApplicationPy::sAddCommand, METH_VARARGS, - "addCommand(name, cmd, activation) -> None\n" - "\n" - "Add a command object.\n" - "\n" - "name : str\n Name of the command.\n" - "cmd : object\n Command instance.\n" - "activation : str\n Activation sequence. Optional."}, - {"runCommand", (PyCFunction) ApplicationPy::sRunCommand, METH_VARARGS, - "runCommand(name, index=0) -> None\n" - "\n" - "Run command by its name.\n" - "\n" - "name : str\n Name of the command.\n" - "index : int\n Index of the child command."}, - {"SendMsgToActiveView", (PyCFunction) ApplicationPy::sSendActiveView, METH_VARARGS, - "SendMsgToActiveView(name, suppress=False) -> str or None\n" - "\n" - "Send message to the active view. Deprecated, use class View.\n" - "\n" - "name : str\n Name of the view command.\n" - "suppress : bool\n If the sent message fail, suppress warning message."}, - {"sendMsgToFocusView", (PyCFunction) ApplicationPy::sSendFocusView, METH_VARARGS, - "sendMsgToFocusView(name, suppress=False) -> str or None\n" - "\n" - "Send message to the focused view.\n" - "\n" - "name : str\n Name of the view command.\n" - "suppress : bool\n If send message fail, suppress warning message."}, - {"hide", (PyCFunction) ApplicationPy::sHide, METH_VARARGS, - "hide(name) -> None\n" - "\n" - "Hide the given feature. Deprecated.\n" - "\n" - "name : str\n Feature name."}, - {"show", (PyCFunction) ApplicationPy::sShow, METH_VARARGS, - "show(name) -> None\n" - "\n" - "Show the given feature. Deprecated.\n" - "\n" - "name : str\n Feature name."}, - {"hideObject", (PyCFunction) ApplicationPy::sHideObject, METH_VARARGS, - "hideObject(obj) -> None\n" - "\n" - "Hide the view provider of the given object.\n" - "\n" - "obj : App.DocumentObject"}, - {"showObject", (PyCFunction) ApplicationPy::sShowObject, METH_VARARGS, - "showObject(obj) -> None\n" - "\n" - "Show the view provider of the given object.\n" - "\n" - "obj : App.DocumentObject"}, - {"open", (PyCFunction) ApplicationPy::sOpen, METH_VARARGS, - "open(fileName) -> None\n" - "\n" - "Open a macro, Inventor or VRML file.\n" - "\n" - "fileName : str, bytes, bytearray\n File name."}, - {"insert", (PyCFunction) ApplicationPy::sInsert, METH_VARARGS, - "insert(fileName, docName) -> None\n" - "\n" - "Insert a macro, Inventor or VRML file. If no document name\n" - "is given the active document is used.\n" - "\n" - "fileName : str, bytes, bytearray\n File name.\n" - "docName : str\n Document name."}, - {"export", (PyCFunction) ApplicationPy::sExport, METH_VARARGS, - "export(objs, fileName) -> None\n" - "\n" - "Save scene to Inventor or VRML file.\n" - "\n" - "objs : sequence of App.DocumentObject\n Sequence of objects to save.\n" - "fileName : str, bytes, bytearray\n File name."}, - {"activeDocument", (PyCFunction) ApplicationPy::sActiveDocument, METH_VARARGS, - "activeDocument() -> Gui.Document or None\n" - "\n" - "Return the active document. If no one exists, return None."}, - {"setActiveDocument", (PyCFunction) ApplicationPy::sSetActiveDocument, METH_VARARGS, - "setActiveDocument(doc) -> None\n" - "\n" - "Activate the specified document.\n" - "\n" - "doc : str, App.Document\n Document to activate."}, - {"activeView", (PyCFunction)ApplicationPy::sActiveView, METH_VARARGS, - "activeView(typeName) -> object or None\n" - "\n" - "Return the active view of the active document. If no one\n" - "exists, return None.\n" - "\n" - "typeName : str\n Type name."}, - {"activateView", (PyCFunction)ApplicationPy::sActivateView, METH_VARARGS, - "activateView(typeName, create=False) -> None\n" - "\n" - "Activate a view of the given type in the active document.\n" - "If a view of this type doesn't exist and create is True, a\n" - "new view of this type is created.\n" - "\n" - "type : str\n Type name.\n" - "create : bool"}, - {"editDocument", (PyCFunction)ApplicationPy::sEditDocument, METH_VARARGS, - "editDocument() -> Gui.Document or None\n" - "\n" - "Return the current editing document. If no one exists,\n" - "return None."}, - {"getDocument", (PyCFunction) ApplicationPy::sGetDocument, METH_VARARGS, - "getDocument(doc) -> Gui.Document\n" - "\n" - "Get a document.\n" - "\n" - "doc : str, App.Document\n `App.Document` name or `App.Document` object."}, - {"doCommand", (PyCFunction) ApplicationPy::sDoCommand, METH_VARARGS, - "doCommand(cmd) -> None\n" - "\n" - "Prints the given string in the python console and runs it.\n" - "\n" - "cmd : str"}, - {"doCommandGui", (PyCFunction) ApplicationPy::sDoCommandGui, METH_VARARGS, - "doCommandGui(cmd) -> None\n" - "\n" - "Prints the given string in the python console and runs it\n" - "but doesn't record it in macros.\n" - "\n" - "cmd : str"}, - {"doCommandEval", (PyCFunction) ApplicationPy::sDoCommandEval, METH_VARARGS, - "doCommandEval(cmd) -> PyObject\n" - "\n" - "Runs the given string without showing in the python console or recording in\n" - "macros, and returns the result.\n" - "\n" - "cmd : str"}, - {"doCommandSkip", (PyCFunction) ApplicationPy::sDoCommandSkip, METH_VARARGS, - "doCommandSkip(cmd) -> None\n" - "\n" - "Record the given string in the Macro but comment it out in the console\n" - "\n" - "cmd : str"}, - {"addModule", (PyCFunction) ApplicationPy::sAddModule, METH_VARARGS, - "addModule(mod) -> None\n" - "\n" - "Prints the given module import only once in the macro recording.\n" - "\n" - "mod : str"}, - {"showDownloads", (PyCFunction) ApplicationPy::sShowDownloads, METH_VARARGS, - "showDownloads() -> None\n\n" - "Show the downloads manager window."}, - {"showPreferences", (PyCFunction) ApplicationPy::sShowPreferences, METH_VARARGS, - "showPreferences(grp, index=0) -> None\n" - "\n" - "Show the preferences window.\n" - "\n" - "grp: str\n Group to show.\n" - "index : int\n Page index."}, - {"showPreferencesByName", (PyCFunction) ApplicationPy::sShowPreferencesByName, METH_VARARGS, - "showPreferencesByName(grp, pagename) -> None\n" - "\n" - "Show the preferences window.\n" - "\n" - "grp: str\n Group to show.\n" - "pagename : str\n Page to show."}, - {"createViewer", (PyCFunction) ApplicationPy::sCreateViewer, METH_VARARGS, - "createViewer(views=1, name) -> View3DInventorPy or AbstractSplitViewPy\n" - "\n" - "Show and returns a viewer.\n" - "\n" - "views : int\n If > 1 a `AbstractSplitViewPy` object is returned.\n" - "name : str\n Viewer title."}, - {"getMarkerIndex", (PyCFunction) ApplicationPy::sGetMarkerIndex, METH_VARARGS, - "getMarkerIndex(marker, size=9) -> int\n" - "\n" - "Get marker index according to marker name and size.\n" - "\n" - "marker : str\n Marker style name.\n" - "size : int\n Marker size."}, - {"addDocumentObserver", (PyCFunction) ApplicationPy::sAddDocObserver, METH_VARARGS, - "addDocumentObserver(obj) -> None\n" - "\n" - "Add an observer to get notifications about changes on documents.\n" - "\n" - "obj : object"}, - {"removeDocumentObserver", (PyCFunction) ApplicationPy::sRemoveDocObserver, METH_VARARGS, - "removeDocumentObserver(obj) -> None\n" - "\n" - "Remove an added document observer.\n" - "\n" - "obj : object"}, - {"addWorkbenchManipulator", (PyCFunction) ApplicationPy::sAddWbManipulator, METH_VARARGS, - "addWorkbenchManipulator(obj) -> None\n" - "\n" - "Add a workbench manipulator to modify a workbench when it is activated.\n" - "\n" - "obj : object"}, - {"removeWorkbenchManipulator", (PyCFunction) ApplicationPy::sRemoveWbManipulator, METH_VARARGS, - "removeWorkbenchManipulator(obj) -> None\n" - "\n" - "Remove an added workbench manipulator.\n" - "\n" - "obj : object"}, - {"listUserEditModes", (PyCFunction) ApplicationPy::sListUserEditModes, METH_VARARGS, - "listUserEditModes() -> list\n" - "\n" - "List available user edit modes."}, - {"getUserEditMode", (PyCFunction) ApplicationPy::sGetUserEditMode, METH_VARARGS, - "getUserEditMode() -> str\n" - "\n" - "Get current user edit mode."}, - {"setUserEditMode", (PyCFunction) ApplicationPy::sSetUserEditMode, METH_VARARGS, - "setUserEditMode(mode) -> bool\n" - "\n" - "Set user edit mode. Returns True if exists, False otherwise.\n" - "\n" - "mode : str"}, - {"reload", (PyCFunction) ApplicationPy::sReload, METH_VARARGS, - "reload(name) -> App.Document or None\n" - "\n" - "Reload a partial opened document. If the document is not open,\n" - "return None.\n" - "\n" - "name : str\n `App.Document` name."}, - {"loadFile", (PyCFunction) ApplicationPy::sLoadFile, METH_VARARGS, - "loadFile(fileName, module) -> None\n" - "\n" - "Loads an arbitrary file by delegating to the given Python module.\n" - "If no module is given it will be determined by the file extension.\n" - "If more than one module can load a file the first one will be taken.\n" - "If no module exists to load the file an exception will be raised.\n" - "\n" - "fileName : str\n" - "module : str"}, - {"coinRemoveAllChildren", (PyCFunction) ApplicationPy::sCoinRemoveAllChildren, METH_VARARGS, - "coinRemoveAllChildren(node) -> None\n" - "\n" - "Remove all children from a group node.\n" - "\n" - "node : object"}, - {"suspendWaitCursor", (PyCFunction) ApplicationPy::sSuspendWaitCursor, METH_VARARGS, - "suspendWaitCursor() -> None\n\n" - "Temporarily suspends the application's wait cursor and event filter."}, - {"resumeWaitCursor", (PyCFunction) ApplicationPy::sResumeWaitCursor, METH_VARARGS, - "resumeWaitCursor() -> None\n\n" - "Resumes the application's wait cursor and event filter."}, - {nullptr, nullptr, 0, nullptr} /* Sentinel */ + {"activateWorkbench", + (PyCFunction)ApplicationPy::sActivateWorkbenchHandler, + METH_VARARGS, + "activateWorkbench(name) -> bool\n" + "\n" + "Activate workbench by its name. Return False if the workbench is\n" + "already active.\n" + "\n" + "name : str\n Name of the workbench to activate."}, + {"addWorkbench", + (PyCFunction)ApplicationPy::sAddWorkbenchHandler, + METH_VARARGS, + "addWorkbench(workbench) -> None\n" + "\n" + "Add a workbench.\n" + "\n" + "workbench : Workbench, Workbench type\n" + " Instance of a Workbench subclass or subclass of the\n" + " Workbench class."}, + {"removeWorkbench", + (PyCFunction)ApplicationPy::sRemoveWorkbenchHandler, + METH_VARARGS, + "removeWorkbench(name) -> None\n" + "\n" + "Remove a workbench.\n" + "\n" + "name : str\n Name of the workbench to remove."}, + {"getWorkbench", + (PyCFunction)ApplicationPy::sGetWorkbenchHandler, + METH_VARARGS, + "getWorkbench(name) -> Workbench\n" + "\n" + "Get the workbench by its name.\n" + "\n" + "name : str\n Name of the workbench to return."}, + {"listWorkbenches", + (PyCFunction)ApplicationPy::sListWorkbenchHandlers, + METH_VARARGS, + "listWorkbenches() -> dict\n" + "\n" + "Get a dictionary with all workbenches."}, + {"activeWorkbench", + (PyCFunction)ApplicationPy::sActiveWorkbenchHandler, + METH_VARARGS, + "activeWorkbench() -> Workbench\n" + "\n" + "Return the active workbench object."}, + {"addResourcePath", + (PyCFunction)ApplicationPy::sAddResPath, + METH_VARARGS, + "addResourcePath(path) -> None\n" + "\n" + "Add a new path to the system where to find resource files\n" + "like icons or localization files.\n" + "\n" + "path : str, bytes, bytearray\n Path to resource files."}, + {"addLanguagePath", + (PyCFunction)ApplicationPy::sAddLangPath, + METH_VARARGS, + "addLanguagePath(path) -> None\n" + "\n" + "Add a new path to the system where to find language files.\n" + "\n" + "path : str, bytes, bytearray\n Path to language files."}, + {"addIconPath", + (PyCFunction)ApplicationPy::sAddIconPath, + METH_VARARGS, + "addIconPath(path) -> None\n" + "\n" + "Add a new path to the system where to find icon files.\n" + "\n" + "path : str, bytes, bytearray\n Path to icon files."}, + {"addIcon", + (PyCFunction)ApplicationPy::sAddIcon, + METH_VARARGS, + "addIcon(name, content, format='XPM') -> None\n" + "\n" + "Add an icon to the system.\n" + "\n" + "name : str\n Name of the icon.\n" + "content : str, bytes-like\n Content of the icon.\n" + "format : str\n Format of the icon."}, + {"getIcon", + (PyCFunction)ApplicationPy::sGetIcon, + METH_VARARGS, + "getIcon(name) -> QIcon or None\n" + "\n" + "Get an icon in the system. If the pixmap is null, return None.\n" + "\n" + "name : str\n Name of the icon."}, + {"isIconCached", + (PyCFunction)ApplicationPy::sIsIconCached, + METH_VARARGS, + "isIconCached(name) -> Bool\n" + "\n" + "Check if an icon with the given name is cached.\n" + "\n" + "name : str\n Name of the icon."}, + {"getMainWindow", + (PyCFunction)ApplicationPy::sGetMainWindow, + METH_VARARGS, + "getMainWindow() -> QMainWindow\n" + "\n" + "Return the main window instance."}, + {"updateGui", + (PyCFunction)ApplicationPy::sUpdateGui, + METH_VARARGS, + "updateGui() -> None\n" + "\n" + "Update the main window and all its windows."}, + {"updateLocale", + (PyCFunction)ApplicationPy::sUpdateLocale, + METH_VARARGS, + "updateLocale() -> None\n" + "\n" + "Update the localization."}, + {"getLocale", + (PyCFunction)ApplicationPy::sGetLocale, + METH_VARARGS, + "getLocale() -> str\n" + "\n" + "Returns the locale currently used by FreeCAD."}, + {"setLocale", + (PyCFunction)ApplicationPy::sSetLocale, + METH_VARARGS, + "setLocale(name) -> None\n" + "\n" + "Sets the locale used by FreeCAD. Can be set by top-level\n" + "domain (e.g. \"de\") or the language name (e.g. \"German\").\n" + "\n" + "name : str\n Locale name."}, + {"supportedLocales", + (PyCFunction)ApplicationPy::sSupportedLocales, + METH_VARARGS, + "supportedLocales() -> dict\n" + "\n" + "Returns a dict of all supported locales. The keys are the language\n" + "names and the values the top-level domains."}, + {"createDialog", + (PyCFunction)ApplicationPy::sCreateDialog, + METH_VARARGS, + "createDialog(path) -> PyResource\n" + "\n" + "Open a UI file.\n" + "\n" + "path : str\n UI file path."}, + {"addPreferencePage", + (PyCFunction)ApplicationPy::sAddPreferencePage, + METH_VARARGS, + "addPreferencePage(path, group) -> None\n" + "addPreferencePage(dialog, group) -> None\n" + "\n" + "Add a UI form to the preferences dialog in the specified group.\n" + "\n" + "path : str\n UI file path.\n" + "group : str\n Group name.\n" + "dialog : type\n Preference page."}, + {"addCommand", + (PyCFunction)ApplicationPy::sAddCommand, + METH_VARARGS, + "addCommand(name, cmd, activation) -> None\n" + "\n" + "Add a command object.\n" + "\n" + "name : str\n Name of the command.\n" + "cmd : object\n Command instance.\n" + "activation : str\n Activation sequence. Optional."}, + {"runCommand", + (PyCFunction)ApplicationPy::sRunCommand, + METH_VARARGS, + "runCommand(name, index=0) -> None\n" + "\n" + "Run command by its name.\n" + "\n" + "name : str\n Name of the command.\n" + "index : int\n Index of the child command."}, + {"SendMsgToActiveView", + (PyCFunction)ApplicationPy::sSendActiveView, + METH_VARARGS, + "SendMsgToActiveView(name, suppress=False) -> str or None\n" + "\n" + "Send message to the active view. Deprecated, use class View.\n" + "\n" + "name : str\n Name of the view command.\n" + "suppress : bool\n If the sent message fail, suppress warning message."}, + {"sendMsgToFocusView", + (PyCFunction)ApplicationPy::sSendFocusView, + METH_VARARGS, + "sendMsgToFocusView(name, suppress=False) -> str or None\n" + "\n" + "Send message to the focused view.\n" + "\n" + "name : str\n Name of the view command.\n" + "suppress : bool\n If send message fail, suppress warning message."}, + {"hide", + (PyCFunction)ApplicationPy::sHide, + METH_VARARGS, + "hide(name) -> None\n" + "\n" + "Hide the given feature. Deprecated.\n" + "\n" + "name : str\n Feature name."}, + {"show", + (PyCFunction)ApplicationPy::sShow, + METH_VARARGS, + "show(name) -> None\n" + "\n" + "Show the given feature. Deprecated.\n" + "\n" + "name : str\n Feature name."}, + {"hideObject", + (PyCFunction)ApplicationPy::sHideObject, + METH_VARARGS, + "hideObject(obj) -> None\n" + "\n" + "Hide the view provider of the given object.\n" + "\n" + "obj : App.DocumentObject"}, + {"showObject", + (PyCFunction)ApplicationPy::sShowObject, + METH_VARARGS, + "showObject(obj) -> None\n" + "\n" + "Show the view provider of the given object.\n" + "\n" + "obj : App.DocumentObject"}, + {"open", + (PyCFunction)ApplicationPy::sOpen, + METH_VARARGS, + "open(fileName) -> None\n" + "\n" + "Open a macro, Inventor or VRML file.\n" + "\n" + "fileName : str, bytes, bytearray\n File name."}, + {"insert", + (PyCFunction)ApplicationPy::sInsert, + METH_VARARGS, + "insert(fileName, docName) -> None\n" + "\n" + "Insert a macro, Inventor or VRML file. If no document name\n" + "is given the active document is used.\n" + "\n" + "fileName : str, bytes, bytearray\n File name.\n" + "docName : str\n Document name."}, + {"export", + (PyCFunction)ApplicationPy::sExport, + METH_VARARGS, + "export(objs, fileName) -> None\n" + "\n" + "Save scene to Inventor or VRML file.\n" + "\n" + "objs : sequence of App.DocumentObject\n Sequence of objects to save.\n" + "fileName : str, bytes, bytearray\n File name."}, + {"activeDocument", + (PyCFunction)ApplicationPy::sActiveDocument, + METH_VARARGS, + "activeDocument() -> Gui.Document or None\n" + "\n" + "Return the active document. If no one exists, return None."}, + {"setActiveDocument", + (PyCFunction)ApplicationPy::sSetActiveDocument, + METH_VARARGS, + "setActiveDocument(doc) -> None\n" + "\n" + "Activate the specified document.\n" + "\n" + "doc : str, App.Document\n Document to activate."}, + {"activeView", + (PyCFunction)ApplicationPy::sActiveView, + METH_VARARGS, + "activeView(typeName) -> object or None\n" + "\n" + "Return the active view of the active document. If no one\n" + "exists, return None.\n" + "\n" + "typeName : str\n Type name."}, + {"activateView", + (PyCFunction)ApplicationPy::sActivateView, + METH_VARARGS, + "activateView(typeName, create=False) -> None\n" + "\n" + "Activate a view of the given type in the active document.\n" + "If a view of this type doesn't exist and create is True, a\n" + "new view of this type is created.\n" + "\n" + "type : str\n Type name.\n" + "create : bool"}, + {"editDocument", + (PyCFunction)ApplicationPy::sEditDocument, + METH_VARARGS, + "editDocument() -> Gui.Document or None\n" + "\n" + "Return the current editing document. If no one exists,\n" + "return None."}, + {"getDocument", + (PyCFunction)ApplicationPy::sGetDocument, + METH_VARARGS, + "getDocument(doc) -> Gui.Document\n" + "\n" + "Get a document.\n" + "\n" + "doc : str, App.Document\n `App.Document` name or `App.Document` object."}, + {"doCommand", + (PyCFunction)ApplicationPy::sDoCommand, + METH_VARARGS, + "doCommand(cmd) -> None\n" + "\n" + "Prints the given string in the python console and runs it.\n" + "\n" + "cmd : str"}, + {"doCommandGui", + (PyCFunction)ApplicationPy::sDoCommandGui, + METH_VARARGS, + "doCommandGui(cmd) -> None\n" + "\n" + "Prints the given string in the python console and runs it\n" + "but doesn't record it in macros.\n" + "\n" + "cmd : str"}, + {"doCommandEval", + (PyCFunction)ApplicationPy::sDoCommandEval, + METH_VARARGS, + "doCommandEval(cmd) -> PyObject\n" + "\n" + "Runs the given string without showing in the python console or recording in\n" + "macros, and returns the result.\n" + "\n" + "cmd : str"}, + {"doCommandSkip", + (PyCFunction)ApplicationPy::sDoCommandSkip, + METH_VARARGS, + "doCommandSkip(cmd) -> None\n" + "\n" + "Record the given string in the Macro but comment it out in the console\n" + "\n" + "cmd : str"}, + {"addModule", + (PyCFunction)ApplicationPy::sAddModule, + METH_VARARGS, + "addModule(mod) -> None\n" + "\n" + "Prints the given module import only once in the macro recording.\n" + "\n" + "mod : str"}, + {"showDownloads", + (PyCFunction)ApplicationPy::sShowDownloads, + METH_VARARGS, + "showDownloads() -> None\n\n" + "Show the downloads manager window."}, + {"showPreferences", + (PyCFunction)ApplicationPy::sShowPreferences, + METH_VARARGS, + "showPreferences(grp, index=0) -> None\n" + "\n" + "Show the preferences window.\n" + "\n" + "grp: str\n Group to show.\n" + "index : int\n Page index."}, + {"showPreferencesByName", + (PyCFunction)ApplicationPy::sShowPreferencesByName, + METH_VARARGS, + "showPreferencesByName(grp, pagename) -> None\n" + "\n" + "Show the preferences window.\n" + "\n" + "grp: str\n Group to show.\n" + "pagename : str\n Page to show."}, + {"createViewer", + (PyCFunction)ApplicationPy::sCreateViewer, + METH_VARARGS, + "createViewer(views=1, name) -> View3DInventorPy or AbstractSplitViewPy\n" + "\n" + "Show and returns a viewer.\n" + "\n" + "views : int\n If > 1 a `AbstractSplitViewPy` object is returned.\n" + "name : str\n Viewer title."}, + {"getMarkerIndex", + (PyCFunction)ApplicationPy::sGetMarkerIndex, + METH_VARARGS, + "getMarkerIndex(marker, size=9) -> int\n" + "\n" + "Get marker index according to marker name and size.\n" + "\n" + "marker : str\n Marker style name.\n" + "size : int\n Marker size."}, + {"addDocumentObserver", + (PyCFunction)ApplicationPy::sAddDocObserver, + METH_VARARGS, + "addDocumentObserver(obj) -> None\n" + "\n" + "Add an observer to get notifications about changes on documents.\n" + "\n" + "obj : object"}, + {"removeDocumentObserver", + (PyCFunction)ApplicationPy::sRemoveDocObserver, + METH_VARARGS, + "removeDocumentObserver(obj) -> None\n" + "\n" + "Remove an added document observer.\n" + "\n" + "obj : object"}, + {"addWorkbenchManipulator", + (PyCFunction)ApplicationPy::sAddWbManipulator, + METH_VARARGS, + "addWorkbenchManipulator(obj) -> None\n" + "\n" + "Add a workbench manipulator to modify a workbench when it is activated.\n" + "\n" + "obj : object"}, + {"removeWorkbenchManipulator", + (PyCFunction)ApplicationPy::sRemoveWbManipulator, + METH_VARARGS, + "removeWorkbenchManipulator(obj) -> None\n" + "\n" + "Remove an added workbench manipulator.\n" + "\n" + "obj : object"}, + {"listUserEditModes", + (PyCFunction)ApplicationPy::sListUserEditModes, + METH_VARARGS, + "listUserEditModes() -> list\n" + "\n" + "List available user edit modes."}, + {"getUserEditMode", + (PyCFunction)ApplicationPy::sGetUserEditMode, + METH_VARARGS, + "getUserEditMode() -> str\n" + "\n" + "Get current user edit mode."}, + {"setUserEditMode", + (PyCFunction)ApplicationPy::sSetUserEditMode, + METH_VARARGS, + "setUserEditMode(mode) -> bool\n" + "\n" + "Set user edit mode. Returns True if exists, False otherwise.\n" + "\n" + "mode : str"}, + {"reload", + (PyCFunction)ApplicationPy::sReload, + METH_VARARGS, + "reload(name) -> App.Document or None\n" + "\n" + "Reload a partial opened document. If the document is not open,\n" + "return None.\n" + "\n" + "name : str\n `App.Document` name."}, + {"loadFile", + (PyCFunction)ApplicationPy::sLoadFile, + METH_VARARGS, + "loadFile(fileName, module) -> None\n" + "\n" + "Loads an arbitrary file by delegating to the given Python module.\n" + "If no module is given it will be determined by the file extension.\n" + "If more than one module can load a file the first one will be taken.\n" + "If no module exists to load the file an exception will be raised.\n" + "\n" + "fileName : str\n" + "module : str"}, + {"coinRemoveAllChildren", + (PyCFunction)ApplicationPy::sCoinRemoveAllChildren, + METH_VARARGS, + "coinRemoveAllChildren(node) -> None\n" + "\n" + "Remove all children from a group node.\n" + "\n" + "node : object"}, + {"suspendWaitCursor", + (PyCFunction)ApplicationPy::sSuspendWaitCursor, + METH_VARARGS, + "suspendWaitCursor() -> None\n\n" + "Temporarily suspends the application's wait cursor and event filter."}, + {"resumeWaitCursor", + (PyCFunction)ApplicationPy::sResumeWaitCursor, + METH_VARARGS, + "resumeWaitCursor() -> None\n\n" + "Resumes the application's wait cursor and event filter."}, + {nullptr, nullptr, 0, nullptr} /* Sentinel */ }; -PyObject* Gui::ApplicationPy::sEditDocument(PyObject * /*self*/, PyObject *args) +PyObject* Gui::ApplicationPy::sEditDocument(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; } - Document *pcDoc = Application::Instance->editDocument(); + Document* pcDoc = Application::Instance->editDocument(); if (pcDoc) { return pcDoc->getPyObject(); } @@ -449,13 +567,13 @@ PyObject* Gui::ApplicationPy::sEditDocument(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* Gui::ApplicationPy::sActiveDocument(PyObject * /*self*/, PyObject *args) +PyObject* Gui::ApplicationPy::sActiveDocument(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; } - Document *pcDoc = Application::Instance->activeDocument(); + Document* pcDoc = Application::Instance->activeDocument(); if (pcDoc) { return pcDoc->getPyObject(); } @@ -463,14 +581,15 @@ PyObject* Gui::ApplicationPy::sActiveDocument(PyObject * /*self*/, PyObject *arg Py_Return; } -PyObject* Gui::ApplicationPy::sActiveView(PyObject * /*self*/, PyObject *args) +PyObject* Gui::ApplicationPy::sActiveView(PyObject* /*self*/, PyObject* args) { - const char *typeName = nullptr; + const char* typeName = nullptr; if (!PyArg_ParseTuple(args, "|s", &typeName)) { return nullptr; } - PY_TRY { + PY_TRY + { Base::Type type; if (typeName) { type = Base::Type::fromName(typeName); @@ -483,7 +602,7 @@ PyObject* Gui::ApplicationPy::sActiveView(PyObject * /*self*/, PyObject *args) Gui::MDIView* mdiView = Application::Instance->activeView(); if (mdiView && (type.isBad() || mdiView->isDerivedFrom(type))) { auto res = Py::asObject(mdiView->getPyObject()); - if(!res.isNone() || !type.isBad()) { + if (!res.isNone() || !type.isBad()) { return Py::new_reference_to(res); } } @@ -498,16 +617,15 @@ PyObject* Gui::ApplicationPy::sActiveView(PyObject * /*self*/, PyObject *args) } Py_Return; - } PY_CATCH } -PyObject* Gui::ApplicationPy::sActivateView(PyObject * /*self*/, PyObject *args) +PyObject* Gui::ApplicationPy::sActivateView(PyObject* /*self*/, PyObject* args) { char* typeStr = nullptr; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) - PyObject *create = Py_False; + PyObject* create = Py_False; if (!PyArg_ParseTuple(args, "sO!", &typeStr, &PyBool_Type, &create)) { return nullptr; } @@ -518,12 +636,12 @@ PyObject* Gui::ApplicationPy::sActivateView(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* Gui::ApplicationPy::sSetActiveDocument(PyObject * /*self*/, PyObject *args) +PyObject* Gui::ApplicationPy::sSetActiveDocument(PyObject* /*self*/, PyObject* args) { - Document *pcDoc = nullptr; + Document* pcDoc = nullptr; do { - char *pstr = nullptr; + char* pstr = nullptr; if (PyArg_ParseTuple(args, "s", &pstr)) { pcDoc = Application::Instance->getDocument(pstr); if (!pcDoc) { @@ -537,15 +655,16 @@ PyObject* Gui::ApplicationPy::sSetActiveDocument(PyObject * /*self*/, PyObject * PyObject* doc = nullptr; if (PyArg_ParseTuple(args, "O!", &(App::DocumentPy::Type), &doc)) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) - pcDoc = Application::Instance->getDocument(static_cast(doc)->getDocumentPtr()); + pcDoc = Application::Instance->getDocument( + static_cast(doc)->getDocumentPtr() + ); if (!pcDoc) { PyErr_Format(PyExc_KeyError, "Unknown document instance"); return nullptr; } break; } - } - while(false); + } while (false); if (!pcDoc) { PyErr_SetString(PyExc_TypeError, "Either string or App.Document expected"); @@ -560,11 +679,11 @@ PyObject* Gui::ApplicationPy::sSetActiveDocument(PyObject * /*self*/, PyObject * Py_Return; } -PyObject* ApplicationPy::sGetDocument(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetDocument(PyObject* /*self*/, PyObject* args) { - char *pstr = nullptr; + char* pstr = nullptr; if (PyArg_ParseTuple(args, "s", &pstr)) { - Document *pcDoc = Application::Instance->getDocument(pstr); + Document* pcDoc = Application::Instance->getDocument(pstr); if (!pcDoc) { PyErr_Format(PyExc_NameError, "Unknown document '%s'", pstr); return nullptr; @@ -576,7 +695,9 @@ PyObject* ApplicationPy::sGetDocument(PyObject * /*self*/, PyObject *args) PyObject* doc = nullptr; if (PyArg_ParseTuple(args, "O!", &(App::DocumentPy::Type), &doc)) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) - Document *pcDoc = Application::Instance->getDocument(static_cast(doc)->getDocumentPtr()); + Document* pcDoc = Application::Instance->getDocument( + static_cast(doc)->getDocumentPtr() + ); if (!pcDoc) { PyErr_Format(PyExc_KeyError, "Unknown document instance"); return nullptr; @@ -588,14 +709,14 @@ PyObject* ApplicationPy::sGetDocument(PyObject * /*self*/, PyObject *args) return nullptr; } -PyObject* ApplicationPy::sHide(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sHide(PyObject* /*self*/, PyObject* args) { - char *psFeatStr = nullptr; - if (!PyArg_ParseTuple(args, "s;Name of the object to hide has to be given!",&psFeatStr)) { + char* psFeatStr = nullptr; + if (!PyArg_ParseTuple(args, "s;Name of the object to hide has to be given!", &psFeatStr)) { return nullptr; } - Document *pcDoc = Application::Instance->activeDocument(); + Document* pcDoc = Application::Instance->activeDocument(); if (pcDoc) { pcDoc->setHide(psFeatStr); @@ -604,14 +725,14 @@ PyObject* ApplicationPy::sHide(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sShow(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sShow(PyObject* /*self*/, PyObject* args) { - char *psFeatStr = nullptr; - if (!PyArg_ParseTuple(args, "s;Name of the object to show has to be given!",&psFeatStr)) { + char* psFeatStr = nullptr; + if (!PyArg_ParseTuple(args, "s;Name of the object to show has to be given!", &psFeatStr)) { return nullptr; } - Document *pcDoc = Application::Instance->activeDocument(); + Document* pcDoc = Application::Instance->activeDocument(); if (pcDoc) { pcDoc->setShow(psFeatStr); @@ -620,10 +741,10 @@ PyObject* ApplicationPy::sShow(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sHideObject(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sHideObject(PyObject* /*self*/, PyObject* args) { - PyObject *object = nullptr; - if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type),&object)) { + PyObject* object = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &object)) { return nullptr; } @@ -634,10 +755,10 @@ PyObject* ApplicationPy::sHideObject(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sShowObject(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sShowObject(PyObject* /*self*/, PyObject* args) { - PyObject *object = nullptr; - if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type),&object)) { + PyObject* object = nullptr; + if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &object)) { return nullptr; } @@ -648,17 +769,18 @@ PyObject* ApplicationPy::sShowObject(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sOpen(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sOpen(PyObject* /*self*/, PyObject* args) { // only used to open Python files char* Name = nullptr; - if (!PyArg_ParseTuple(args, "et","utf-8",&Name)) { + if (!PyArg_ParseTuple(args, "et", "utf-8", &Name)) { return nullptr; } std::string Utf8Name = std::string(Name); PyMem_Free(Name); - PY_TRY { + PY_TRY + { QString fileName = QString::fromUtf8(Utf8Name.c_str()); FileHandler handler(fileName); if (!handler.openFile()) { @@ -671,48 +793,52 @@ PyObject* ApplicationPy::sOpen(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sInsert(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sInsert(PyObject* /*self*/, PyObject* args) { char* Name = nullptr; char* DocName = nullptr; - if (!PyArg_ParseTuple(args, "et|s","utf-8",&Name,&DocName)) { + if (!PyArg_ParseTuple(args, "et|s", "utf-8", &Name, &DocName)) { return nullptr; } std::string Utf8Name = std::string(Name); PyMem_Free(Name); - PY_TRY { + PY_TRY + { QString fileName = QString::fromUtf8(Utf8Name.c_str()); FileHandler handler(fileName); if (!handler.importFile(std::string(DocName ? DocName : ""))) { QString ext = handler.extension(); Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData()); } - } PY_CATCH; + } + PY_CATCH; Py_Return; } -PyObject* ApplicationPy::sExport(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sExport(PyObject* /*self*/, PyObject* args) { PyObject* object = nullptr; char* Name = nullptr; - if (!PyArg_ParseTuple(args, "Oet",&object,"utf-8",&Name)) { + if (!PyArg_ParseTuple(args, "Oet", &object, "utf-8", &Name)) { return nullptr; } std::string Utf8Name = std::string(Name); PyMem_Free(Name); - PY_TRY { + PY_TRY + { App::Document* doc = nullptr; Py::Sequence list(object); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) - App::DocumentObject* obj = static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); doc = obj->getDocument(); break; } @@ -722,13 +848,9 @@ PyObject* ApplicationPy::sExport(PyObject * /*self*/, PyObject *args) QFileInfo fi; fi.setFile(fileName); QString ext = fi.suffix().toLower(); - if (ext == QLatin1String("iv") || - ext == QLatin1String("wrl") || - ext == QLatin1String("vrml") || - ext == QLatin1String("wrz") || - ext == QLatin1String("x3d") || - ext == QLatin1String("x3dz") || - ext == QLatin1String("xhtml")) { + if (ext == QLatin1String("iv") || ext == QLatin1String("wrl") || ext == QLatin1String("vrml") + || ext == QLatin1String("wrz") || ext == QLatin1String("x3d") + || ext == QLatin1String("x3dz") || ext == QLatin1String("xhtml")) { // build up the graph auto sep = new SoSeparator(); @@ -738,7 +860,8 @@ PyObject* ApplicationPy::sExport(PyObject * /*self*/, PyObject *args) PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) - App::DocumentObject* obj = static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(obj); if (vp) { @@ -757,9 +880,8 @@ PyObject* ApplicationPy::sExport(PyObject * /*self*/, PyObject *args) constexpr const int lineLimit = 10000; bool binary = false; - if (action.getTriangleCount() > triangleLimit || - action.getPointCount() > pointLimit || - action.getLineCount() > lineLimit) { + if (action.getTriangleCount() > triangleLimit || action.getPointCount() > pointLimit + || action.getLineCount() > lineLimit) { binary = true; } @@ -791,60 +913,61 @@ PyObject* ApplicationPy::sExport(PyObject * /*self*/, PyObject *args) else { Base::Console().error("File type '%s' not supported\n", ext.toLatin1().constData()); } - } PY_CATCH; + } + PY_CATCH; Py_Return; } -PyObject* ApplicationPy::sSendActiveView(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sSendActiveView(PyObject* /*self*/, PyObject* args) { - char *psCommandStr = nullptr; + char* psCommandStr = nullptr; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) - PyObject *suppress = Py_False; - if (!PyArg_ParseTuple(args, "s|O!",&psCommandStr,&PyBool_Type,&suppress)) { + PyObject* suppress = Py_False; + if (!PyArg_ParseTuple(args, "s|O!", &psCommandStr, &PyBool_Type, &suppress)) { return nullptr; } const char* ppReturn = nullptr; - if (!Application::Instance->sendMsgToActiveView(psCommandStr,&ppReturn)) { + if (!Application::Instance->sendMsgToActiveView(psCommandStr, &ppReturn)) { if (!Base::asBoolean(suppress)) { - Base::Console().warning("Unknown view command: %s\n",psCommandStr); + Base::Console().warning("Unknown view command: %s\n", psCommandStr); } } // Print the return value to the output if (ppReturn) { - return Py_BuildValue("s",ppReturn); + return Py_BuildValue("s", ppReturn); } Py_Return; } -PyObject* ApplicationPy::sSendFocusView(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sSendFocusView(PyObject* /*self*/, PyObject* args) { - char *psCommandStr = nullptr; + char* psCommandStr = nullptr; // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) - PyObject *suppress = Py_False; - if (!PyArg_ParseTuple(args, "s|O!",&psCommandStr,&PyBool_Type,&suppress)) { + PyObject* suppress = Py_False; + if (!PyArg_ParseTuple(args, "s|O!", &psCommandStr, &PyBool_Type, &suppress)) { return nullptr; } const char* ppReturn = nullptr; - if (!Application::Instance->sendMsgToFocusView(psCommandStr,&ppReturn)) { + if (!Application::Instance->sendMsgToFocusView(psCommandStr, &ppReturn)) { if (!Base::asBoolean(suppress)) { - Base::Console().warning("Unknown view command: %s\n",psCommandStr); + Base::Console().warning("Unknown view command: %s\n", psCommandStr); } } // Print the return value to the output if (ppReturn) { - return Py_BuildValue("s",ppReturn); + return Py_BuildValue("s", ppReturn); } Py_Return; } -PyObject* ApplicationPy::sGetMainWindow(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetMainWindow(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -858,7 +981,7 @@ PyObject* ApplicationPy::sGetMainWindow(PyObject * /*self*/, PyObject *args) } } -PyObject* ApplicationPy::sUpdateGui(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sUpdateGui(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -869,7 +992,7 @@ PyObject* ApplicationPy::sUpdateGui(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sUpdateLocale(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sUpdateLocale(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -880,7 +1003,7 @@ PyObject* ApplicationPy::sUpdateLocale(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sGetLocale(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetLocale(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -890,7 +1013,7 @@ PyObject* ApplicationPy::sGetLocale(PyObject * /*self*/, PyObject *args) return PyUnicode_FromString(locale.c_str()); } -PyObject* ApplicationPy::sSetLocale(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sSetLocale(PyObject* /*self*/, PyObject* args) { char* name = nullptr; if (!PyArg_ParseTuple(args, "s", &name)) { @@ -910,7 +1033,7 @@ PyObject* ApplicationPy::sSetLocale(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sSupportedLocales(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sSupportedLocales(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -927,7 +1050,7 @@ PyObject* ApplicationPy::sSupportedLocales(PyObject * /*self*/, PyObject *args) return Py::new_reference_to(dict); } -PyObject* ApplicationPy::sCreateDialog(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sCreateDialog(PyObject* /*self*/, PyObject* args) { char* fn = nullptr; if (!PyArg_ParseTuple(args, "s", &fn)) { @@ -935,7 +1058,7 @@ PyObject* ApplicationPy::sCreateDialog(PyObject * /*self*/, PyObject *args) } PyObject* pPyResource = nullptr; - try{ + try { pPyResource = new PyResource(); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) static_cast(pPyResource)->load(fn); @@ -948,11 +1071,11 @@ PyObject* ApplicationPy::sCreateDialog(PyObject * /*self*/, PyObject *args) return pPyResource; } -PyObject* ApplicationPy::sAddPreferencePage(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddPreferencePage(PyObject* /*self*/, PyObject* args) { char* fn = nullptr; char* grp = nullptr; - if (PyArg_ParseTuple(args, "ss", &fn,&grp)) { + if (PyArg_ParseTuple(args, "ss", &fn, &grp)) { QFileInfo fi(QString::fromUtf8(fn)); if (!fi.exists()) { PyErr_SetString(PyExc_RuntimeError, "UI file does not exist"); @@ -976,7 +1099,7 @@ PyObject* ApplicationPy::sAddPreferencePage(PyObject * /*self*/, PyObject *args) return nullptr; } -PyObject* ApplicationPy::sActivateWorkbenchHandler(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sActivateWorkbenchHandler(PyObject* /*self*/, PyObject* args) { char* psKey = nullptr; if (!PyArg_ParseTuple(args, "s", &psKey)) { @@ -1002,12 +1125,11 @@ PyObject* ApplicationPy::sActivateWorkbenchHandler(PyObject * /*self*/, PyObject } catch (const XERCES_CPP_NAMESPACE_QUALIFIER TranscodingException& e) { std::stringstream err; - char *pMsg = XERCES_CPP_NAMESPACE_QUALIFIER XMLString::transcode(e.getMessage()); + char* pMsg = XERCES_CPP_NAMESPACE_QUALIFIER XMLString::transcode(e.getMessage()); err << "Transcoding exception in Xerces-c:\n\n" << "Transcoding exception raised in activateWorkbench.\n" << "Check if your user configuration file is valid.\n" - << " Exception message:" - << pMsg; + << " Exception message:" << pMsg; XERCES_CPP_NAMESPACE_QUALIFIER XMLString::release(&pMsg); PyErr_SetString(PyExc_RuntimeError, err.str().c_str()); return nullptr; @@ -1020,7 +1142,7 @@ PyObject* ApplicationPy::sActivateWorkbenchHandler(PyObject * /*self*/, PyObject } } -PyObject* ApplicationPy::sAddWorkbenchHandler(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddWorkbenchHandler(PyObject* /*self*/, PyObject* args) { PyObject* pcObject = nullptr; if (!PyArg_ParseTuple(args, "O", &pcObject)) { @@ -1046,13 +1168,16 @@ PyObject* ApplicationPy::sAddWorkbenchHandler(PyObject * /*self*/, PyObject *arg } else if (PyObject_IsInstance(object.ptr(), baseclass.ptr()) == 1) { // extract the class name of the instance - PyErr_Clear(); // PyObject_IsSubclass set an exception + PyErr_Clear(); // PyObject_IsSubclass set an exception Py::Object classobj = object.getAttr(std::string("__class__")); name = classobj.getAttr(std::string("__name__")); } else { - PyErr_SetString(PyExc_TypeError, "arg must be a subclass or an instance of " - "a subclass of 'Workbench'"); + PyErr_SetString( + PyExc_TypeError, + "arg must be a subclass or an instance of " + "a subclass of 'Workbench'" + ); return nullptr; } @@ -1063,13 +1188,14 @@ PyObject* ApplicationPy::sAddWorkbenchHandler(PyObject * /*self*/, PyObject *arg // NOLINTEND(bugprone-unused-raii) std::string item = name.as_std_string("ascii"); - PyObject* wb = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary,item.c_str()); + PyObject* wb + = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, item.c_str()); if (wb) { PyErr_Format(PyExc_KeyError, "'%s' already exists.", item.c_str()); return nullptr; } - PyDict_SetItemString(Application::Instance->_pcWorkbenchDictionary,item.c_str(),object.ptr()); + PyDict_SetItemString(Application::Instance->_pcWorkbenchDictionary, item.c_str(), object.ptr()); Application::Instance->signalRefreshWorkbenches(); } catch (const Py::Exception&) { @@ -1079,27 +1205,27 @@ PyObject* ApplicationPy::sAddWorkbenchHandler(PyObject * /*self*/, PyObject *arg Py_Return; } -PyObject* ApplicationPy::sRemoveWorkbenchHandler(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sRemoveWorkbenchHandler(PyObject* /*self*/, PyObject* args) { char* psKey = nullptr; if (!PyArg_ParseTuple(args, "s", &psKey)) { return nullptr; } - PyObject* wb = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary,psKey); + PyObject* wb = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, psKey); if (!wb) { PyErr_Format(PyExc_KeyError, "No such workbench '%s'", psKey); return nullptr; } WorkbenchManager::instance()->removeWorkbench(psKey); - PyDict_DelItemString(Application::Instance->_pcWorkbenchDictionary,psKey); + PyDict_DelItemString(Application::Instance->_pcWorkbenchDictionary, psKey); Application::Instance->signalRefreshWorkbenches(); Py_Return; } -PyObject* ApplicationPy::sGetWorkbenchHandler(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetWorkbenchHandler(PyObject* /*self*/, PyObject* args) { char* psKey = nullptr; if (!PyArg_ParseTuple(args, "s", &psKey)) { @@ -1117,7 +1243,7 @@ PyObject* ApplicationPy::sGetWorkbenchHandler(PyObject * /*self*/, PyObject *arg return pcWorkbench; } -PyObject* ApplicationPy::sListWorkbenchHandlers(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sListWorkbenchHandlers(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1127,7 +1253,7 @@ PyObject* ApplicationPy::sListWorkbenchHandlers(PyObject * /*self*/, PyObject *a return Application::Instance->_pcWorkbenchDictionary; } -PyObject* ApplicationPy::sActiveWorkbenchHandler(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sActiveWorkbenchHandler(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1141,7 +1267,8 @@ PyObject* ApplicationPy::sActiveWorkbenchHandler(PyObject * /*self*/, PyObject * // get the python workbench object from the dictionary std::string key = actWb->name(); - PyObject* pcWorkbench = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, key.c_str()); + PyObject* pcWorkbench + = PyDict_GetItemString(Application::Instance->_pcWorkbenchDictionary, key.c_str()); if (!pcWorkbench) { PyErr_Format(PyExc_KeyError, "No such workbench '%s'", key.c_str()); return nullptr; @@ -1152,7 +1279,7 @@ PyObject* ApplicationPy::sActiveWorkbenchHandler(PyObject * /*self*/, PyObject * return pcWorkbench; } -PyObject* ApplicationPy::sAddResPath(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddResPath(PyObject* /*self*/, PyObject* args) { char* filePath = nullptr; if (!PyArg_ParseTuple(args, "et", "utf-8", &filePath)) { @@ -1173,7 +1300,7 @@ PyObject* ApplicationPy::sAddResPath(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sAddLangPath(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddLangPath(PyObject* /*self*/, PyObject* args) { char* filePath = nullptr; if (!PyArg_ParseTuple(args, "et", "utf-8", &filePath)) { @@ -1193,7 +1320,7 @@ PyObject* ApplicationPy::sAddLangPath(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sAddIconPath(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddIconPath(PyObject* /*self*/, PyObject* args) { char* filePath = nullptr; if (!PyArg_ParseTuple(args, "et", "utf-8", &filePath)) { @@ -1213,11 +1340,11 @@ PyObject* ApplicationPy::sAddIconPath(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sAddIcon(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddIcon(PyObject* /*self*/, PyObject* args) { - const char *iconName = nullptr; + const char* iconName = nullptr; Py_buffer content; - const char *format = "XPM"; + const char* format = "XPM"; if (!PyArg_ParseTuple(args, "ss*|s", &iconName, &content, &format)) { return nullptr; } @@ -1233,7 +1360,7 @@ PyObject* ApplicationPy::sAddIcon(PyObject * /*self*/, PyObject *args) QByteArray ary(contentStr, static_cast(content.len)); icon.loadFromData(ary, format); - if (icon.isNull()){ + if (icon.isNull()) { QString file = QString::fromUtf8(contentStr, static_cast(content.len)); icon.load(file); } @@ -1250,9 +1377,9 @@ PyObject* ApplicationPy::sAddIcon(PyObject * /*self*/, PyObject *args) Py_Return; } -PyObject* ApplicationPy::sGetIcon(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetIcon(PyObject* /*self*/, PyObject* args) { - char *iconName = nullptr; + char* iconName = nullptr; if (!PyArg_ParseTuple(args, "s", &iconName)) { return nullptr; } @@ -1261,16 +1388,16 @@ PyObject* ApplicationPy::sGetIcon(PyObject * /*self*/, PyObject *args) wrap.loadGuiModule(); wrap.loadWidgetsModule(); auto pixmap = BitmapFactory().pixmap(iconName); - if(!pixmap.isNull()) { + if (!pixmap.isNull()) { return Py::new_reference_to(wrap.fromQIcon(new QIcon(pixmap))); } Py_Return; } -PyObject* ApplicationPy::sIsIconCached(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sIsIconCached(PyObject* /*self*/, PyObject* args) { - char *iconName = nullptr; + char* iconName = nullptr; if (!PyArg_ParseTuple(args, "s", &iconName)) { return nullptr; } @@ -1280,12 +1407,12 @@ PyObject* ApplicationPy::sIsIconCached(PyObject * /*self*/, PyObject *args) return Py::new_reference_to(Py::Boolean(BitmapFactory().findPixmapInCache(iconName, icon))); } -PyObject* ApplicationPy::sAddCommand(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddCommand(PyObject* /*self*/, PyObject* args) { char* pName = nullptr; char* pSource = nullptr; PyObject* pcCmdObj = nullptr; - if (!PyArg_ParseTuple(args, "sO|s", &pName,&pcCmdObj,&pSource)) { + if (!PyArg_ParseTuple(args, "sO|s", &pName, &pcCmdObj, &pSource)) { return nullptr; } @@ -1310,10 +1437,10 @@ PyObject* ApplicationPy::sAddCommand(PyObject * /*self*/, PyObject *args) getFrameArgs[0] = Py::Long(0); callerFrame = getFrame.apply(getFrameArgs); - Py::Object codeObj (callerFrame.getAttr("f_code")); + Py::Object codeObj(callerFrame.getAttr("f_code")); - Py::Object filenameObj (codeObj.getAttr("co_filename")); - std::string filename (Py::String(filenameObj).as_std_string()); + Py::Object filenameObj(codeObj.getAttr("co_filename")); + std::string filename(Py::String(filenameObj).as_std_string()); Base::FileInfo fi(filename); // convert backslashes to slashes @@ -1329,7 +1456,8 @@ PyObject* ApplicationPy::sAddCommand(PyObject * /*self*/, PyObject *args) rx = "/Ext/freecad/(\\w+)/"; if (boost::regex_search(filename, what, rx)) { group = what[1]; - } else { + } + else { group = module; } } @@ -1367,14 +1495,17 @@ PyObject* ApplicationPy::sAddCommand(PyObject * /*self*/, PyObject *args) return nullptr; } catch (...) { - PyErr_SetString(Base::PyExc_FC_GeneralError, "Unknown C++ exception raised in ApplicationPy::sAddCommand()"); + PyErr_SetString( + Base::PyExc_FC_GeneralError, + "Unknown C++ exception raised in ApplicationPy::sAddCommand()" + ); return nullptr; } Py_Return; } -PyObject* ApplicationPy::sRunCommand(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sRunCommand(PyObject* /*self*/, PyObject* args) { char* pName = nullptr; int item = 0; @@ -1395,9 +1526,9 @@ PyObject* ApplicationPy::sRunCommand(PyObject * /*self*/, PyObject *args) return nullptr; } -PyObject* ApplicationPy::sDoCommand(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sDoCommand(PyObject* /*self*/, PyObject* args) { - char *sCmd = nullptr; + char* sCmd = nullptr; if (!PyArg_ParseTuple(args, "s", &sCmd)) { return nullptr; } @@ -1425,9 +1556,9 @@ PyObject* ApplicationPy::sDoCommand(PyObject * /*self*/, PyObject *args) return PyRun_String(sCmd, Py_file_input, dict, dict); } -PyObject* ApplicationPy::sDoCommandGui(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sDoCommandGui(PyObject* /*self*/, PyObject* args) { - char *sCmd = nullptr; + char* sCmd = nullptr; if (!PyArg_ParseTuple(args, "s", &sCmd)) { return nullptr; } @@ -1455,9 +1586,9 @@ PyObject* ApplicationPy::sDoCommandGui(PyObject * /*self*/, PyObject *args) return PyRun_String(sCmd, Py_file_input, dict, dict); } -PyObject* ApplicationPy::sDoCommandEval(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sDoCommandEval(PyObject* /*self*/, PyObject* args) { - char *sCmd = nullptr; + char* sCmd = nullptr; if (!PyArg_ParseTuple(args, "s", &sCmd)) { return nullptr; } @@ -1472,7 +1603,7 @@ PyObject* ApplicationPy::sDoCommandEval(PyObject * /*self*/, PyObject *args) module = PyImport_AddModule("__main__"); if (!module) { return nullptr; -} + } dict = PyModule_GetDict(module); if (!dict) { @@ -1482,9 +1613,9 @@ PyObject* ApplicationPy::sDoCommandEval(PyObject * /*self*/, PyObject *args) return PyRun_String(sCmd, Py_eval_input, dict, dict); } -PyObject* ApplicationPy::sDoCommandSkip(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sDoCommandSkip(PyObject* /*self*/, PyObject* args) { - char *sCmd = nullptr; + char* sCmd = nullptr; if (!PyArg_ParseTuple(args, "s", &sCmd)) { return nullptr; } @@ -1497,15 +1628,15 @@ PyObject* ApplicationPy::sDoCommandSkip(PyObject * /*self*/, PyObject *args) return Py::None().ptr(); } -PyObject* ApplicationPy::sAddModule(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddModule(PyObject* /*self*/, PyObject* args) { - char *pstr = nullptr; + char* pstr = nullptr; if (!PyArg_ParseTuple(args, "s", &pstr)) { return nullptr; } try { - Command::addModule(Command::Doc,pstr); + Command::addModule(Command::Doc, pstr); Py_Return; } catch (const Base::Exception& e) { @@ -1514,7 +1645,7 @@ PyObject* ApplicationPy::sAddModule(PyObject * /*self*/, PyObject *args) } } -PyObject* ApplicationPy::sShowDownloads(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sShowDownloads(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1567,7 +1698,7 @@ PyObject* ApplicationPy::sShowPreferencesByName(PyObject* /*self*/, PyObject* ar Py_Return; } -PyObject* ApplicationPy::sCreateViewer(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sCreateViewer(PyObject* /*self*/, PyObject* args) { int num_of_views = 1; char* title = nullptr; @@ -1598,22 +1729,25 @@ PyObject* ApplicationPy::sCreateViewer(PyObject * /*self*/, PyObject *args) } } -PyObject* ApplicationPy::sGetMarkerIndex(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetMarkerIndex(PyObject* /*self*/, PyObject* args) { constexpr const int defaultSize = 9; - char *pstr {}; - int defSize = defaultSize; + char* pstr {}; + int defSize = defaultSize; if (!PyArg_ParseTuple(args, "s|i", &pstr, &defSize)) { return nullptr; } - PY_TRY { - ParameterGrp::handle const hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + PY_TRY + { + ParameterGrp::handle const hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); - //find the appropriate marker style string token + // find the appropriate marker style string token std::string marker_arg = pstr; - std::list > markerList = { + std::list> markerList = { {"square", "DIAMOND_FILLED"}, {"cross", "CROSS"}, {"hourglass", "HOURGLASS_FILLED"}, @@ -1631,7 +1765,7 @@ PyObject* ApplicationPy::sGetMarkerIndex(PyObject * /*self*/, PyObject *args) marker_arg = (findIt != markerList.end() ? findIt->second : "CIRCLE_FILLED"); - //get the marker size + // get the marker size auto sizeList = Gui::Inventor::MarkerBitmaps::getSupportedSizes(marker_arg); if (std::ranges::find(sizeList, defSize) == std::end(sizeList)) { @@ -1643,16 +1777,17 @@ PyObject* ApplicationPy::sGetMarkerIndex(PyObject * /*self*/, PyObject *args) PY_CATCH; } -PyObject* ApplicationPy::sReload(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sReload(PyObject* /*self*/, PyObject* args) { - const char *name = nullptr; + const char* name = nullptr; if (!PyArg_ParseTuple(args, "s", &name)) { return nullptr; } - PY_TRY { + PY_TRY + { auto doc = Application::Instance->reopen(App::GetApplication().getDocument(name)); - if(doc) { + if (doc) { return doc->getPyObject(); } Py_Return; @@ -1660,15 +1795,16 @@ PyObject* ApplicationPy::sReload(PyObject * /*self*/, PyObject *args) PY_CATCH; } -PyObject* ApplicationPy::sLoadFile(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sLoadFile(PyObject* /*self*/, PyObject* args) { - const char *path = ""; - const char *mod = ""; + const char* path = ""; + const char* mod = ""; if (!PyArg_ParseTuple(args, "s|s", &path, &mod)) { return nullptr; } - PY_TRY { + PY_TRY + { Base::FileInfo fi(path); if (!fi.isFile() || !fi.exists()) { PyErr_Format(PyExc_IOError, "File %s doesn't exist.", path); @@ -1687,79 +1823,84 @@ PyObject* ApplicationPy::sLoadFile(PyObject * /*self*/, PyObject *args) module = modules.front(); } - Application::Instance->open(path,module.c_str()); + Application::Instance->open(path, module.c_str()); Py_Return; } PY_CATCH } -PyObject* ApplicationPy::sAddDocObserver(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddDocObserver(PyObject* /*self*/, PyObject* args) { PyObject* o = nullptr; - if (!PyArg_ParseTuple(args, "O",&o)) { + if (!PyArg_ParseTuple(args, "O", &o)) { return nullptr; } - PY_TRY { + PY_TRY + { DocumentObserverPython::addObserver(Py::Object(o)); Py_Return; } PY_CATCH; } -PyObject* ApplicationPy::sRemoveDocObserver(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sRemoveDocObserver(PyObject* /*self*/, PyObject* args) { PyObject* o = nullptr; - if (!PyArg_ParseTuple(args, "O",&o)) { + if (!PyArg_ParseTuple(args, "O", &o)) { return nullptr; } - PY_TRY { + PY_TRY + { DocumentObserverPython::removeObserver(Py::Object(o)); Py_Return; } PY_CATCH; } -PyObject* ApplicationPy::sAddWbManipulator(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sAddWbManipulator(PyObject* /*self*/, PyObject* args) { PyObject* o = nullptr; - if (!PyArg_ParseTuple(args, "O",&o)) { + if (!PyArg_ParseTuple(args, "O", &o)) { return nullptr; } - PY_TRY { + PY_TRY + { WorkbenchManipulatorPython::installManipulator(Py::Object(o)); Py_Return; } PY_CATCH; } -PyObject* ApplicationPy::sRemoveWbManipulator(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sRemoveWbManipulator(PyObject* /*self*/, PyObject* args) { PyObject* o = nullptr; - if (!PyArg_ParseTuple(args, "O",&o)) { + if (!PyArg_ParseTuple(args, "O", &o)) { return nullptr; } - PY_TRY { + PY_TRY + { WorkbenchManipulatorPython::removeManipulator(Py::Object(o)); Py_Return; } PY_CATCH; } -PyObject* ApplicationPy::sCoinRemoveAllChildren(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sCoinRemoveAllChildren(PyObject* /*self*/, PyObject* args) { - PyObject *pynode = nullptr; + PyObject* pynode = nullptr; if (!PyArg_ParseTuple(args, "O", &pynode)) { return nullptr; } - PY_TRY { + PY_TRY + { void* ptr = nullptr; - Base::Interpreter().convertSWIGPointerObj("pivy.coin","_p_SoGroup", pynode, &ptr, 0); + Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoGroup", pynode, &ptr, 0); if (!ptr) { PyErr_SetString(PyExc_RuntimeError, "Conversion of coin.SoGroup failed"); return nullptr; @@ -1771,21 +1912,21 @@ PyObject* ApplicationPy::sCoinRemoveAllChildren(PyObject * /*self*/, PyObject *a PY_CATCH; } -PyObject* ApplicationPy::sListUserEditModes(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sListUserEditModes(PyObject* /*self*/, PyObject* args) { Py::List ret; if (!PyArg_ParseTuple(args, "")) { return nullptr; } - for (auto const &uem : Application::Instance->listUserEditModes()) { + for (auto const& uem : Application::Instance->listUserEditModes()) { ret.append(Py::String(uem.second.first)); } return Py::new_reference_to(ret); } -PyObject* ApplicationPy::sGetUserEditMode(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sGetUserEditMode(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1794,9 +1935,9 @@ PyObject* ApplicationPy::sGetUserEditMode(PyObject * /*self*/, PyObject *args) return Py::new_reference_to(Py::String(Application::Instance->getUserEditModeUIStrings().first)); } -PyObject* ApplicationPy::sSetUserEditMode(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sSetUserEditMode(PyObject* /*self*/, PyObject* args) { - const char *mode = ""; + const char* mode = ""; if (!PyArg_ParseTuple(args, "s", &mode)) { return nullptr; } @@ -1806,7 +1947,7 @@ PyObject* ApplicationPy::sSetUserEditMode(PyObject * /*self*/, PyObject *args) return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ApplicationPy::sSuspendWaitCursor(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sSuspendWaitCursor(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1816,7 +1957,7 @@ PyObject* ApplicationPy::sSuspendWaitCursor(PyObject * /*self*/, PyObject *args) Py_RETURN_NONE; } -PyObject* ApplicationPy::sResumeWaitCursor(PyObject * /*self*/, PyObject *args) +PyObject* ApplicationPy::sResumeWaitCursor(PyObject* /*self*/, PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; diff --git a/src/Gui/ApplicationPy.h b/src/Gui/ApplicationPy.h index e12bf388d4..203c346b51 100644 --- a/src/Gui/ApplicationPy.h +++ b/src/Gui/ApplicationPy.h @@ -26,7 +26,8 @@ #include -namespace Gui{ +namespace Gui +{ /** The ApplicationPy class * This is the Python wrapper class of Application. @@ -118,6 +119,6 @@ public: // clang-format on }; -} //namespace Gui +} // namespace Gui #endif diff --git a/src/Gui/ArcEngine.cpp b/src/Gui/ArcEngine.cpp index 6140962f19..6cf8eb195c 100644 --- a/src/Gui/ArcEngine.cpp +++ b/src/Gui/ArcEngine.cpp @@ -24,111 +24,107 @@ #include #include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include using namespace Gui; - SO_ENGINE_SOURCE(ArcEngine) ArcEngine::ArcEngine() { - SO_ENGINE_CONSTRUCTOR(ArcEngine); + SO_ENGINE_CONSTRUCTOR(ArcEngine); - SO_ENGINE_ADD_INPUT(radius, (10.0)); - SO_ENGINE_ADD_INPUT(angle, (1.0)); - SO_ENGINE_ADD_INPUT(deviation, (0.25)); + SO_ENGINE_ADD_INPUT(radius, (10.0)); + SO_ENGINE_ADD_INPUT(angle, (1.0)); + SO_ENGINE_ADD_INPUT(deviation, (0.25)); - SO_ENGINE_ADD_OUTPUT(points, SoMFVec3f); - SO_ENGINE_ADD_OUTPUT(pointCount, SoSFInt32); - SO_ENGINE_ADD_OUTPUT(midpoint, SoSFVec3f); + SO_ENGINE_ADD_OUTPUT(points, SoMFVec3f); + SO_ENGINE_ADD_OUTPUT(pointCount, SoSFInt32); + SO_ENGINE_ADD_OUTPUT(midpoint, SoSFVec3f); } void ArcEngine::initClass() { - SO_ENGINE_INIT_CLASS(ArcEngine, SoEngine, "Engine"); + SO_ENGINE_INIT_CLASS(ArcEngine, SoEngine, "Engine"); } void ArcEngine::evaluate() { - float angle = abs(this->angle.getValue()); + float angle = abs(this->angle.getValue()); - if (radius.getValue() < std::numeric_limits::epsilon() || - deviation.getValue() < std::numeric_limits::epsilon()) - { - defaultValues(); - return; - } - - float deviationAngle(acos((radius.getValue() - deviation.getValue()) / radius.getValue())); - std::vector tempPoints; - int segmentCount; - if (deviationAngle >= angle) { - segmentCount = 1; - } - else { - segmentCount = static_cast(angle / deviationAngle) + 1; - if (segmentCount < 2) { - defaultValues(); - return; + if (radius.getValue() < std::numeric_limits::epsilon() + || deviation.getValue() < std::numeric_limits::epsilon()) { + defaultValues(); + return; } - } - float angleIncrement = (this->angle.getValue() > 0 ? angle : -angle) / static_cast(segmentCount); - for (int index = 0; index < segmentCount + 1; ++index) - { - SbVec3f currentNormal(1.0, 0.0, 0.0); - float currentAngle = index * angleIncrement; - SbRotation rotation(SbVec3f(0.0, 0.0, 1.0), currentAngle); - rotation.multVec(currentNormal, currentNormal); - tempPoints.push_back(currentNormal * radius.getValue()); - } - int tempCount = tempPoints.size(); //for macro. - SO_ENGINE_OUTPUT(points, SoMFVec3f, setNum(tempCount)); - SO_ENGINE_OUTPUT(pointCount, SoSFInt32, setValue(tempCount)); - std::vector::const_iterator it; - for (it = tempPoints.begin(); it != tempPoints.end(); ++it) - { - int currentIndex = it-tempPoints.begin(); //for macro. - SbVec3f temp(*it); //for macro - SO_ENGINE_OUTPUT(points, SoMFVec3f, set1Value(currentIndex, temp)); - } - // Get Midpoint - float a = angle / 2; - SbRotation rot(SbVec3f(0.0, 0.0, 1.0), a); - SbVec3f midPnt(1.0, 0.0, 0.0); - rot.multVec(midPnt, midPnt); - midPnt = midPnt * radius.getValue(); + float deviationAngle(acos((radius.getValue() - deviation.getValue()) / radius.getValue())); + std::vector tempPoints; + int segmentCount; + if (deviationAngle >= angle) { + segmentCount = 1; + } + else { + segmentCount = static_cast(angle / deviationAngle) + 1; + if (segmentCount < 2) { + defaultValues(); + return; + } + } + float angleIncrement = (this->angle.getValue() > 0 ? angle : -angle) + / static_cast(segmentCount); + for (int index = 0; index < segmentCount + 1; ++index) { + SbVec3f currentNormal(1.0, 0.0, 0.0); + float currentAngle = index * angleIncrement; + SbRotation rotation(SbVec3f(0.0, 0.0, 1.0), currentAngle); + rotation.multVec(currentNormal, currentNormal); + tempPoints.push_back(currentNormal * radius.getValue()); + } + int tempCount = tempPoints.size(); // for macro. + SO_ENGINE_OUTPUT(points, SoMFVec3f, setNum(tempCount)); + SO_ENGINE_OUTPUT(pointCount, SoSFInt32, setValue(tempCount)); + std::vector::const_iterator it; + for (it = tempPoints.begin(); it != tempPoints.end(); ++it) { + int currentIndex = it - tempPoints.begin(); // for macro. + SbVec3f temp(*it); // for macro + SO_ENGINE_OUTPUT(points, SoMFVec3f, set1Value(currentIndex, temp)); + } - SO_ENGINE_OUTPUT(midpoint, SoSFVec3f, setValue(midPnt)); + // Get Midpoint + float a = angle / 2; + SbRotation rot(SbVec3f(0.0, 0.0, 1.0), a); + SbVec3f midPnt(1.0, 0.0, 0.0); + rot.multVec(midPnt, midPnt); + midPnt = midPnt * radius.getValue(); + SO_ENGINE_OUTPUT(midpoint, SoSFVec3f, setValue(midPnt)); } void ArcEngine::defaultValues() { - //just some non-failing info. - SO_ENGINE_OUTPUT(points, SoMFVec3f, setNum(2)); - SbVec3f point1(10.0, 0.0, 0.0); - SO_ENGINE_OUTPUT(points, SoMFVec3f, set1Value(0, point1)); - SbVec3f point2(7.07f, 7.07f, 0.0); - SO_ENGINE_OUTPUT(points, SoMFVec3f, set1Value(1, point2)); - SO_ENGINE_OUTPUT(pointCount, SoSFInt32, setValue(2)); - SbVec3f point3(7.07f, 7.07f, 0.0); - SO_ENGINE_OUTPUT(midpoint, SoSFVec3f, setValue(point3)); + // just some non-failing info. + SO_ENGINE_OUTPUT(points, SoMFVec3f, setNum(2)); + SbVec3f point1(10.0, 0.0, 0.0); + SO_ENGINE_OUTPUT(points, SoMFVec3f, set1Value(0, point1)); + SbVec3f point2(7.07f, 7.07f, 0.0); + SO_ENGINE_OUTPUT(points, SoMFVec3f, set1Value(1, point2)); + SO_ENGINE_OUTPUT(pointCount, SoSFInt32, setValue(2)); + SbVec3f point3(7.07f, 7.07f, 0.0); + SO_ENGINE_OUTPUT(midpoint, SoSFVec3f, setValue(point3)); } diff --git a/src/Gui/ArcEngine.h b/src/Gui/ArcEngine.h index b153e8b756..b5f7ff4bf6 100644 --- a/src/Gui/ArcEngine.h +++ b/src/Gui/ArcEngine.h @@ -42,13 +42,15 @@ class SoTranslation; class SoCoordinate3; class SoIndexedLineSet; -namespace Gui { +namespace Gui +{ // /*used for generating points for arc display*/ -class GuiExport ArcEngine : public SoEngine +class GuiExport ArcEngine: public SoEngine { SO_ENGINE_HEADER(ArcEngine); + public: ArcEngine(); static void initClass(); @@ -63,11 +65,13 @@ public: protected: void evaluate() override; + private: - ~ArcEngine() override{} - void defaultValues(); //some non error values if something goes wrong. + ~ArcEngine() override + {} + void defaultValues(); // some non error values if something goes wrong. }; -} // namespace Gui +} // namespace Gui -#endif // GUI_ARCENGINE_H \ No newline at end of file +#endif // GUI_ARCENGINE_H diff --git a/src/Gui/Assistant.cpp b/src/Gui/Assistant.cpp index db9e53d2f1..39e3f2fdd1 100644 --- a/src/Gui/Assistant.cpp +++ b/src/Gui/Assistant.cpp @@ -20,13 +20,13 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -38,8 +38,7 @@ using namespace Gui; Assistant::Assistant() : proc(nullptr) -{ -} +{} Assistant::~Assistant() { @@ -49,14 +48,15 @@ Assistant::~Assistant() } } -void Assistant::showDocumentation(const QString &page) +void Assistant::showDocumentation(const QString& page) { - if (!startAssistant()) + if (!startAssistant()) { return; + } if (!page.isEmpty()) { QTextStream str(proc); - str << QLatin1String("setSource qthelp://org.freecad.usermanual/doc/") - << page << QLatin1String("\n\n"); + str << QLatin1String("setSource qthelp://org.freecad.usermanual/doc/") << page + << QLatin1String("\n\n"); } } @@ -64,25 +64,24 @@ bool Assistant::startAssistant() { if (!proc) { proc = new QProcess(); - connect(proc, &QProcess::readyReadStandardOutput, - this, &Assistant::readyReadStandardOutput); - connect(proc, &QProcess::readyReadStandardError, - this, &Assistant::readyReadStandardError); + connect(proc, &QProcess::readyReadStandardOutput, this, &Assistant::readyReadStandardOutput); + connect(proc, &QProcess::readyReadStandardError, this, &Assistant::readyReadStandardError); } if (proc->state() != QProcess::Running) { #ifdef Q_OS_WIN QString app; - app = QDir::toNativeSeparators(QString::fromStdString - (App::Application::getHomePath()) + QLatin1String("bin/")); + app = QDir::toNativeSeparators( + QString::fromStdString(App::Application::getHomePath()) + QLatin1String("bin/") + ); #elif defined(Q_OS_MACOS) QString app = QCoreApplication::applicationDirPath() + QDir::separator(); #else -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +# if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator(); -#else +# else QString app = QLibraryInfo::path(QLibraryInfo::BinariesPath) + QDir::separator(); -#endif +# endif #endif app += QLatin1String("assistant"); @@ -94,8 +93,13 @@ bool Assistant::startAssistant() QFileInfo fi(qhc); if (!fi.isReadable()) { - QMessageBox::critical(nullptr, tr("%1 Help").arg(exe), - tr("%1 help files not found (%2). You might need to install the %1 documentation package.").arg(exe, qhc)); + QMessageBox::critical( + nullptr, + tr("%1 Help").arg(exe), + tr("%1 help files not found (%2). You might need to install the %1 documentation " + "package.") + .arg(exe, qhc) + ); return false; } @@ -120,28 +124,34 @@ bool Assistant::startAssistant() // Unregister qch file (path) from previous AppImage run QStringList args; - args << QLatin1String("-collectionFile") << qhc - << QLatin1String("-unregister") << qch; + args << QLatin1String("-collectionFile") << qhc << QLatin1String("-unregister") + << qch; proc->start(app, args); if (!proc->waitForFinished(50000)) { - QMessageBox::critical(nullptr, tr("%1 Help").arg(exe), - tr("Unable to launch Qt Assistant (%1)").arg(app)); + QMessageBox::critical( + nullptr, + tr("%1 Help").arg(exe), + tr("Unable to launch Qt Assistant (%1)").arg(app) + ); return false; } // Register qch file (path) for current AppImage run args.clear(); - args << QLatin1String("-collectionFile") << qhc - << QLatin1String("-register") << qch; + args << QLatin1String("-collectionFile") << qhc << QLatin1String("-register") + << qch; proc->start(app, args); if (!proc->waitForFinished(50000)) { - QMessageBox::critical(nullptr, tr("%1 Help").arg(exe), - tr("Unable to launch Qt Assistant (%1)").arg(app)); + QMessageBox::critical( + nullptr, + tr("%1 Help").arg(exe), + tr("Unable to launch Qt Assistant (%1)").arg(app) + ); return false; } } @@ -152,14 +162,16 @@ bool Assistant::startAssistant() QStringList args; - args << QLatin1String("-collectionFile") << qhc - << QLatin1String("-enableRemoteControl"); + args << QLatin1String("-collectionFile") << qhc << QLatin1String("-enableRemoteControl"); proc->start(app, args); if (!proc->waitForStarted()) { - QMessageBox::critical(nullptr, tr("%1 Help").arg(exe), - tr("Unable to launch Qt Assistant (%1)").arg(app)); + QMessageBox::critical( + nullptr, + tr("%1 Help").arg(exe), + tr("Unable to launch Qt Assistant (%1)").arg(app) + ); return false; } } diff --git a/src/Gui/Assistant.h b/src/Gui/Assistant.h index 9ce2469f03..60b381cf8c 100644 --- a/src/Gui/Assistant.h +++ b/src/Gui/Assistant.h @@ -28,16 +28,17 @@ class QProcess; -namespace Gui { +namespace Gui +{ -class Assistant : public QObject +class Assistant: public QObject { Q_OBJECT public: Assistant(); ~Assistant() override; - void showDocumentation(const QString &file); + void showDocumentation(const QString& file); private Q_SLOTS: void readyReadStandardOutput(); @@ -45,9 +46,9 @@ private Q_SLOTS: private: bool startAssistant(); - QProcess *proc; + QProcess* proc; }; -} +} // namespace Gui -#endif // GUI_ASSISTANT_H +#endif // GUI_ASSISTANT_H diff --git a/src/Gui/AutoSaver.cpp b/src/Gui/AutoSaver.cpp index 6604d3a7b3..1f729305e7 100644 --- a/src/Gui/AutoSaver.cpp +++ b/src/Gui/AutoSaver.cpp @@ -20,12 +20,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include #include @@ -43,7 +43,7 @@ #include "ViewProvider.h" #include "WaitCursor.h" -FC_LOG_LEVEL_INIT("App",true,true) +FC_LOG_LEVEL_INIT("App", true, true) using namespace Gui; namespace sp = std::placeholders; @@ -52,14 +52,18 @@ AutoSaver* AutoSaver::self = nullptr; const int AutoSaveTimeout = 900000; AutoSaver::AutoSaver(QObject* parent) - : QObject(parent) - , timeout(AutoSaveTimeout) - , compressed(true) + : QObject(parent) + , timeout(AutoSaveTimeout) + , compressed(true) { - //NOLINTBEGIN - App::GetApplication().signalNewDocument.connect(std::bind(&AutoSaver::slotCreateDocument, this, sp::_1)); - App::GetApplication().signalDeleteDocument.connect(std::bind(&AutoSaver::slotDeleteDocument, this, sp::_1)); - //NOLINTEND + // NOLINTBEGIN + App::GetApplication().signalNewDocument.connect( + std::bind(&AutoSaver::slotCreateDocument, this, sp::_1) + ); + App::GetApplication().signalDeleteDocument.connect( + std::bind(&AutoSaver::slotDeleteDocument, this, sp::_1) + ); + // NOLINTEND } AutoSaver::~AutoSaver() = default; @@ -74,23 +78,26 @@ AutoSaver* AutoSaver::instance() void AutoSaver::renameFile(QString dirName, QString file, QString tmpFile) { - FC_LOG("auto saver rename " << tmpFile.toUtf8().constData() - << " -> " << file.toUtf8().constData()); + FC_LOG("auto saver rename " << tmpFile.toUtf8().constData() << " -> " << file.toUtf8().constData()); QDir dir(dirName); dir.remove(file); - if (!dir.rename(tmpFile,file)) { - FC_ERR("Failed to rename autosave file " << tmpFile.toStdString() << " to " << file.toStdString() << "\n"); + if (!dir.rename(tmpFile, file)) { + FC_ERR( + "Failed to rename autosave file " << tmpFile.toStdString() << " to " + << file.toStdString() << "\n" + ); } } void AutoSaver::setTimeout(int ms) { - timeout = Base::clamp(ms, 0, 3600000); // between 0 and 60 min + timeout = Base::clamp(ms, 0, 3600000); // between 0 and 60 min // go through the attached documents and apply the new timeout - for (auto & it : saverMap) { - if (it.second->timerId > 0) + for (auto& it : saverMap) { + if (it.second->timerId > 0) { killTimer(it.second->timerId); + } int id = timeout > 0 ? startTimer(timeout) : 0; it.second->timerId = id; } @@ -123,8 +130,9 @@ void AutoSaver::slotDeleteDocument(const App::Document& Doc) std::string name = Doc.getName(); std::map::iterator it = saverMap.find(name); if (it != saverMap.end()) { - if (it->second->timerId > 0) + if (it->second->timerId > 0) { killTimer(it->second->timerId); + } delete it->second; saverMap.erase(it); } @@ -135,8 +143,7 @@ void AutoSaver::saveDocument(const std::string& name, AutoSaveProperty& saver) Gui::WaitCursor wc; App::Document* doc = App::GetApplication().getDocument(name.c_str()); if (doc && !doc->testStatus(App::Document::PartialDoc) - && !doc->testStatus(App::Document::TempDoc)) - { + && !doc->testStatus(App::Document::TempDoc)) { // Set the document's current transient directory std::string dirName = doc->TransientDir.getValue(); dirName += "/fc_recovery_files"; @@ -144,30 +151,33 @@ void AutoSaver::saveDocument(const std::string& name, AutoSaveProperty& saver) // Write recovery meta file QFile file(QStringLiteral("%1/fc_recovery_file.xml") - .arg(QString::fromUtf8(doc->TransientDir.getValue()))); + .arg(QString::fromUtf8(doc->TransientDir.getValue()))); if (file.open(QFile::WriteOnly)) { QTextStream str(&file); -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) str.setCodec("UTF-8"); #endif str << "\n" << "\n"; str << " Created\n"; - str << " \n"; // store the document's current label - str << " " << QString::fromUtf8(doc->FileName.getValue()) << "\n"; // store the document's current filename + str << " \n"; // store the document's current label + str << " " << QString::fromUtf8(doc->FileName.getValue()) + << "\n"; // store the document's current filename str << "\n"; file.close(); } // make sure to tmp. disable saving thumbnails because this causes trouble if the // associated 3d view is not active - Base::Reference hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Document"); - bool save = hGrp->GetBool("SaveThumbnail",true); - hGrp->SetBool("SaveThumbnail",false); + Base::Reference hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Document" + ); + bool save = hGrp->GetBool("SaveThumbnail", true); + hGrp->SetBool("SaveThumbnail", false); getMainWindow()->showMessage(tr("Wait until the auto-recovery file has been saved…"), 5000); - //qApp->processEvents(); + // qApp->processEvents(); Base::TimeElapsed startTime; // open extra scope to close ZipWriter properly @@ -196,14 +206,14 @@ void AutoSaver::saveDocument(const std::string& name, AutoSaveProperty& saver) fn += "/fc_recovery_file.fcstd"; Base::FileInfo tmp(fn); Base::ofstream file(tmp, std::ios::out | std::ios::binary); - if (file.is_open()) - { + if (file.is_open()) { Base::ZipWriter writer(file); - if (hGrp->GetBool("SaveBinaryBrep", true)) + if (hGrp->GetBool("SaveBinaryBrep", true)) { writer.setMode("BinaryBrep"); + } writer.setComment("AutoRecovery file"); - writer.setLevel(1); // apparently the fastest compression + writer.setLevel(1); // apparently the fastest compression writer.putNextEntry("Document.xml"); doc->Save(writer); @@ -217,15 +227,18 @@ void AutoSaver::saveDocument(const std::string& name, AutoSaveProperty& saver) } } - Base::Console().log("Save auto-recovery file in %fs\n", Base::TimeElapsed::diffTimeF(startTime,Base::TimeElapsed())); - hGrp->SetBool("SaveThumbnail",save); + Base::Console().log( + "Save auto-recovery file in %fs\n", + Base::TimeElapsed::diffTimeF(startTime, Base::TimeElapsed()) + ); + hGrp->SetBool("SaveThumbnail", save); } } -void AutoSaver::timerEvent(QTimerEvent * event) +void AutoSaver::timerEvent(QTimerEvent* event) { int id = event->timerId(); - for (auto & it : saverMap) { + for (auto& it : saverMap) { if (it.second->timerId == id) { try { saveDocument(it.first, *it.second); @@ -241,14 +254,17 @@ void AutoSaver::timerEvent(QTimerEvent * event) // ---------------------------------------------------------------------------- -AutoSaveProperty::AutoSaveProperty(const App::Document* doc) : timerId(-1) +AutoSaveProperty::AutoSaveProperty(const App::Document* doc) + : timerId(-1) { - //NOLINTBEGIN - documentNew = const_cast(doc)->signalNewObject.connect - (std::bind(&AutoSaveProperty::slotNewObject, this, sp::_1)); - documentMod = const_cast(doc)->signalChangedObject.connect - (std::bind(&AutoSaveProperty::slotChangePropertyData, this, sp::_2)); - //NOLINTEND + // NOLINTBEGIN + documentNew = const_cast(doc)->signalNewObject.connect( + std::bind(&AutoSaveProperty::slotNewObject, this, sp::_1) + ); + documentMod = const_cast(doc)->signalChangedObject.connect( + std::bind(&AutoSaveProperty::slotChangePropertyData, this, sp::_2) + ); + // NOLINTEND } AutoSaveProperty::~AutoSaveProperty() @@ -264,7 +280,7 @@ void AutoSaveProperty::slotNewObject(const App::DocumentObject& obj) // if an object was deleted and then restored by an undo then add all properties // because this might be the data files which we may want to re-write - for (const auto & prop : props) { + for (const auto& prop : props) { slotChangePropertyData(*prop); } } @@ -272,7 +288,7 @@ void AutoSaveProperty::slotNewObject(const App::DocumentObject& obj) void AutoSaveProperty::slotChangePropertyData(const App::Property& prop) { std::stringstream str; - str << static_cast(&prop) << std::ends; + str << static_cast(&prop) << std::ends; std::string address = str.str(); this->touched.insert(address); } @@ -280,21 +296,22 @@ void AutoSaveProperty::slotChangePropertyData(const App::Property& prop) // ---------------------------------------------------------------------------- RecoveryWriter::RecoveryWriter(AutoSaveProperty& saver) - : Base::FileWriter(saver.dirName.c_str()), saver(saver) -{ -} + : Base::FileWriter(saver.dirName.c_str()) + , saver(saver) +{} RecoveryWriter::~RecoveryWriter() = default; -bool RecoveryWriter::shouldWrite(const std::string& name, const Base::Persistence *object) const +bool RecoveryWriter::shouldWrite(const std::string& name, const Base::Persistence* object) const { // Property files of a view provider can always be written because // these are rather small files. if (object->isDerivedFrom()) { const auto* prop = static_cast(object); const App::PropertyContainer* parent = prop->getContainer(); - if (parent && parent->isDerivedFrom()) + if (parent && parent->isDerivedFrom()) { return true; + } } else if (object->isDerivedFrom()) { return true; @@ -302,11 +319,11 @@ bool RecoveryWriter::shouldWrite(const std::string& name, const Base::Persistenc // These are the addresses of touched properties of a document object. std::stringstream str; - str << static_cast(object) << std::ends; + str << static_cast(object) << std::ends; std::string address = str.str(); - // Check if the property will be exported to the same file. If the file has changed or if the property hasn't been - // yet exported then (re-)write the file. + // Check if the property will be exported to the same file. If the file has changed or if the + // property hasn't been yet exported then (re-)write the file. std::map::iterator it = saver.fileMap.find(address); if (it == saver.fileMap.end() || it->second != name) { saver.fileMap[address] = name; @@ -317,12 +334,18 @@ bool RecoveryWriter::shouldWrite(const std::string& name, const Base::Persistenc return (jt != saver.touched.end()); } -namespace Gui { +namespace Gui +{ -class RecoveryRunnable : public QRunnable +class RecoveryRunnable: public QRunnable { public: - RecoveryRunnable(const std::set& modes, const char* dir, const char* file, const App::Property* p) + RecoveryRunnable( + const std::set& modes, + const char* dir, + const char* file, + const App::Property* p + ) : prop(p->Copy()) , writer(dir) { @@ -348,9 +371,14 @@ public: // the new file. So we ask the main thread to do it. There is still // possibility of crash caused by thread other than the main, but // that's the best we can do for now. - QMetaObject::invokeMethod(AutoSaver::instance(), "renameFile", - Qt::QueuedConnection, Q_ARG(QString,dirName) - ,Q_ARG(QString,fileName),Q_ARG(QString,tmpName)); + QMetaObject::invokeMethod( + AutoSaver::instance(), + "renameFile", + Qt::QueuedConnection, + Q_ARG(QString, dirName), + Q_ARG(QString, fileName), + Q_ARG(QString, tmpName) + ); } catch (const Base::Exception& e) { Base::Console().warning("Exception in auto-saving: %s\n", e.what()); @@ -371,7 +399,7 @@ private: QString tmpName; }; -} +} // namespace Gui void RecoveryWriter::writeFiles() { @@ -395,7 +423,9 @@ void RecoveryWriter::writeFiles() // For properties a copy can be created and then this can be written to disk in a thread if (entry.Object->isDerivedFrom()) { const auto* prop = static_cast(entry.Object); - QThreadPool::globalInstance()->start(new RecoveryRunnable(getModes(), DirName.c_str(), entry.FileName.c_str(), prop)); + QThreadPool::globalInstance()->start( + new RecoveryRunnable(getModes(), DirName.c_str(), entry.FileName.c_str(), prop) + ); } else { std::string fileName = DirName + "/" + entry.FileName; diff --git a/src/Gui/AutoSaver.h b/src/Gui/AutoSaver.h index a143215359..5298693380 100644 --- a/src/Gui/AutoSaver.h +++ b/src/Gui/AutoSaver.h @@ -32,13 +32,15 @@ #include #include -namespace App { +namespace App +{ class Document; class DocumentObject; class Property; -} +} // namespace App -namespace Gui { +namespace Gui +{ class ViewProvider; class AutoSaveProperty @@ -63,7 +65,7 @@ private: The class AutoSaver is used to automatically save a document to a temporary file. @author Werner Mayer */ -class AutoSaver : public QObject +class AutoSaver: public QObject { Q_OBJECT @@ -86,7 +88,7 @@ public: protected: void slotCreateDocument(const App::Document& Doc); void slotDeleteDocument(const App::Document& Doc); - void timerEvent(QTimerEvent * event) override; + void timerEvent(QTimerEvent* event) override; void saveDocument(const std::string&, AutoSaveProperty&); public Q_SLOTS: @@ -98,7 +100,7 @@ private: std::map saverMap; }; -class RecoveryWriter : public Base::FileWriter +class RecoveryWriter: public Base::FileWriter { public: RecoveryWriter(AutoSaveProperty&); @@ -109,14 +111,14 @@ public: to write out certain objects. The default implementation always returns true. */ - bool shouldWrite(const std::string&, const Base::Persistence *) const override; + bool shouldWrite(const std::string&, const Base::Persistence*) const override; void writeFiles() override; private: AutoSaveProperty& saver; }; -} //namespace Gui +} // namespace Gui -#endif //GUI_AUTOSAVER_H +#endif // GUI_AUTOSAVER_H diff --git a/src/Gui/AxisOrigin.cpp b/src/Gui/AxisOrigin.cpp index b45b1c4212..eedd7b60d5 100644 --- a/src/Gui/AxisOrigin.cpp +++ b/src/Gui/AxisOrigin.cpp @@ -20,17 +20,17 @@ * * ****************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "Inventor/SoAutoZoomTranslation.h" #include "SoFCSelection.h" @@ -39,36 +39,38 @@ using namespace Gui; -TYPESYSTEM_SOURCE(Gui::AxisOrigin,Base::BaseClass) +TYPESYSTEM_SOURCE(Gui::AxisOrigin, Base::BaseClass) AxisOrigin::AxisOrigin() = default; -SoGroup *AxisOrigin::getNode() { - if(node) +SoGroup* AxisOrigin::getNode() +{ + if (node) { return node; + } node.reset(new SoGroup); auto pMat = new SoMaterial(); - const SbVec3f verts[13] = - { - SbVec3f(0,0,0), SbVec3f(size,0,0), - SbVec3f(0,size,0), SbVec3f(0,0,size), - SbVec3f(dist,dist,0), SbVec3f(dist,pSize,0), SbVec3f(pSize,dist,0), // XY Plane - SbVec3f(dist,0,dist), SbVec3f(dist,0,pSize), SbVec3f(pSize,0,dist), // XY Plane - SbVec3f(0,dist,dist), SbVec3f(0,pSize,dist), SbVec3f(0,dist,pSize) // XY Plane + const SbVec3f verts[13] = { + SbVec3f(0, 0, 0), + SbVec3f(size, 0, 0), + SbVec3f(0, size, 0), + SbVec3f(0, 0, size), + SbVec3f(dist, dist, 0), + SbVec3f(dist, pSize, 0), + SbVec3f(pSize, dist, 0), // XY Plane + SbVec3f(dist, 0, dist), + SbVec3f(dist, 0, pSize), + SbVec3f(pSize, 0, dist), // XY Plane + SbVec3f(0, dist, dist), + SbVec3f(0, pSize, dist), + SbVec3f(0, dist, pSize) // XY Plane }; // indexes used to create the edges - const int32_t lines[21] = - { - 0,1,-1, - 0,2,-1, - 0,3,-1, - 5,4,6,-1, - 8,7,9,-1, - 11,10,12,-1 - }; + const int32_t lines[21] = {0, 1, -1, 0, 2, -1, 0, 3, -1, 5, 4, + 6, -1, 8, 7, 9, -1, 11, 10, 12, -1}; pMat->diffuseColor.setNum(3); pMat->diffuseColor.set1Value(0, SbColor(1.0f, 0.2f, 0.2f)); @@ -96,92 +98,104 @@ SoGroup *AxisOrigin::getNode() { node->addChild(pMat); node->addChild(pCoords); -#define CREATE_AXIS(_type,_key,_count,_offset,_mat) do{\ - const char *label=_key;\ - if(labels.size()){\ - auto iter = labels.find(_key);\ - if(iter == labels.end())\ - break;\ - else if(iter->second.size())\ - label = iter->second.c_str();\ - }\ - auto pAxis = new SoFCSelection;\ - pAxis->applySettings();\ - pAxis->style = SoFCSelection::EMISSIVE_DIFFUSE;\ - pAxis->subElementName = label;\ - nodeMap[label].reset(pAxis);\ - node->addChild(pAxis);\ - auto _type = new SoIndexed##_type##Set;\ - pAxis->addChild(_type);\ - _type->coordIndex.setNum(_count);\ - _type->coordIndex.setValues(0,_count,lines+_offset);\ - _type->materialIndex.setValue(_mat);\ - }while(0) +#define CREATE_AXIS(_type, _key, _count, _offset, _mat) \ + do { \ + const char* label = _key; \ + if (labels.size()) { \ + auto iter = labels.find(_key); \ + if (iter == labels.end()) \ + break; \ + else if (iter->second.size()) \ + label = iter->second.c_str(); \ + } \ + auto pAxis = new SoFCSelection; \ + pAxis->applySettings(); \ + pAxis->style = SoFCSelection::EMISSIVE_DIFFUSE; \ + pAxis->subElementName = label; \ + nodeMap[label].reset(pAxis); \ + node->addChild(pAxis); \ + auto _type = new SoIndexed##_type##Set; \ + pAxis->addChild(_type); \ + _type->coordIndex.setNum(_count); \ + _type->coordIndex.setValues(0, _count, lines + _offset); \ + _type->materialIndex.setValue(_mat); \ + } while (0) - CREATE_AXIS(Point,"O",1,0,4); - CREATE_AXIS(Line,"X",3,0,0); - CREATE_AXIS(Line,"Y",3,3,1); - CREATE_AXIS(Line,"Z",3,6,2); - CREATE_AXIS(Line,"XY",4,9,2); - CREATE_AXIS(Line,"XZ",4,13,1); - CREATE_AXIS(Line,"YZ",4,17,0); + CREATE_AXIS(Point, "O", 1, 0, 4); + CREATE_AXIS(Line, "X", 3, 0, 0); + CREATE_AXIS(Line, "Y", 3, 3, 1); + CREATE_AXIS(Line, "Z", 3, 6, 2); + CREATE_AXIS(Line, "XY", 4, 9, 2); + CREATE_AXIS(Line, "XZ", 4, 13, 1); + CREATE_AXIS(Line, "YZ", 4, 17, 0); return node; } -bool AxisOrigin::getElementPicked(const SoPickedPoint *pp, std::string &subname) const { - SoPath *path = pp->getPath(); +bool AxisOrigin::getElementPicked(const SoPickedPoint* pp, std::string& subname) const +{ + SoPath* path = pp->getPath(); int length = path->getLength(); - for(int i=0;igetNodeFromTail(i); - if(node->isOfType(SoFCSelection::getClassTypeId())) { + if (node->isOfType(SoFCSelection::getClassTypeId())) { subname = static_cast(node)->subElementName.getValue().getString(); return true; - } else if(node->isOfType(SoFCSelectionRoot::getClassTypeId())) + } + else if (node->isOfType(SoFCSelectionRoot::getClassTypeId())) { break; + } } return false; } -bool AxisOrigin::getDetailPath(const char *subname, SoFullPath *pPath, SoDetail *&) const { - if(!node) +bool AxisOrigin::getDetailPath(const char* subname, SoFullPath* pPath, SoDetail*&) const +{ + if (!node) { return false; - if(!subname || !subname[0]) + } + if (!subname || !subname[0]) { return true; + } auto it = nodeMap.find(subname); - if(it == nodeMap.end()) + if (it == nodeMap.end()) { return false; + } pPath->append(node); pPath->append(it->second); return true; } -void AxisOrigin::setLineWidth(float size) { - if(size!=lineSize) { +void AxisOrigin::setLineWidth(float size) +{ + if (size != lineSize) { node.reset(); nodeMap.clear(); lineSize = size; } } -void AxisOrigin::setPointSize(float size) { - if(pointSize!=size) { +void AxisOrigin::setPointSize(float size) +{ + if (pointSize != size) { pointSize = size; node.reset(); nodeMap.clear(); } } -void AxisOrigin::setAxisLength(float size) { - if(this->size!=size) { +void AxisOrigin::setAxisLength(float size) +{ + if (this->size != size) { this->size = size; node.reset(); nodeMap.clear(); } } -void AxisOrigin::setPlane(float size, float dist) { - if(pSize!=size || this->dist!=dist) { +void AxisOrigin::setPlane(float size, float dist) +{ + if (pSize != size || this->dist != dist) { pSize = size; this->dist = dist; node.reset(); @@ -189,15 +203,17 @@ void AxisOrigin::setPlane(float size, float dist) { } } -void AxisOrigin::setScale(float scale) { - if(this->scale!=scale) { +void AxisOrigin::setScale(float scale) +{ + if (this->scale != scale) { this->scale = scale; node.reset(); nodeMap.clear(); } } -void AxisOrigin::setLabels(const std::map &labels) { +void AxisOrigin::setLabels(const std::map& labels) +{ this->labels = labels; node.reset(); nodeMap.clear(); diff --git a/src/Gui/AxisOrigin.h b/src/Gui/AxisOrigin.h index c6aea015ea..5e05b1005d 100644 --- a/src/Gui/AxisOrigin.h +++ b/src/Gui/AxisOrigin.h @@ -25,10 +25,12 @@ #include "ViewProvider.h" -namespace Gui { +namespace Gui +{ /// A class to create a Coin3D node representation of an coordinate system -class GuiExport AxisOrigin : public Base::BaseClass { +class GuiExport AxisOrigin: public Base::BaseClass +{ TYPESYSTEM_HEADER(); public: @@ -38,31 +40,46 @@ public: void setLineWidth(float size); /// Get axis line width - float getLineWidth() const { return lineSize; } + float getLineWidth() const + { + return lineSize; + } /// Set origin point size void setPointSize(float size); /// Get origin point size - float getPointSize() const { return pointSize; } + float getPointSize() const + { + return pointSize; + } /// Set the axis line length void setAxisLength(float size); /// Get axis base line length - float getAxisLength() const { return size; } + float getAxisLength() const + { + return size; + } /// Set the origin plane size and distance from the axis void setPlane(float size, float dist); /// Get the origin plane size and distance from the axis - std::pair getPlane() const {return std::make_pair(pSize,dist);} + std::pair getPlane() const + { + return std::make_pair(pSize, dist); + } /// Set the auto scale factor, 0 to disable it void setScale(float scale); /// Get the auto scale factor - float getScale() const { return scale; } + float getScale() const + { + return scale; + } /** Set customized names for axis components * @@ -74,23 +91,26 @@ public: * this function to choose which components are hidden, by not * include the key in the input labels. */ - void setLabels(const std::map &labels); + void setLabels(const std::map& labels); /// Obtain the axis component names - const std::map &getLabels() const { return labels; } + const std::map& getLabels() const + { + return labels; + } /// Obtain the constructed Coin3D representation - SoGroup *getNode(); + SoGroup* getNode(); /** Return the name of picked element * @sa ViewProvider::getElementPicked() */ - bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const; + bool getElementPicked(const SoPickedPoint* pp, std::string& subname) const; /** Return the coin path of a named element * @sa ViewProvider::getDetailPath() */ - bool getDetailPath(const char *subname, SoFullPath *pPath, SoDetail *&det) const; + bool getDetailPath(const char* subname, SoFullPath* pPath, SoDetail*& det) const; private: float size = 6; @@ -101,9 +121,9 @@ private: float pointSize = 4; std::map labels; CoinPtr node; - std::map > nodeMap; + std::map> nodeMap; }; -} // namespace Gui +} // namespace Gui -#endif //GUI_AxisOrigin_H +#endif // GUI_AxisOrigin_H diff --git a/src/Gui/AxisOrigin.pyi b/src/Gui/AxisOrigin.pyi index adece2cfd0..0f8d75a50b 100644 --- a/src/Gui/AxisOrigin.pyi +++ b/src/Gui/AxisOrigin.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from Base.BaseClass import BaseClass from typing import Any, Final, Tuple, Dict - @export( Constructor=True, Delete=True, @@ -42,7 +41,6 @@ class AxisOrigin(BaseClass): Output Coin path leading to the returned element detail. """ ... - AxisLength: float = 0.0 """Get/set the axis length.""" diff --git a/src/Gui/AxisOriginPyImp.cpp b/src/Gui/AxisOriginPyImp.cpp index 38ac1d89ea..170c415eaa 100644 --- a/src/Gui/AxisOriginPyImp.cpp +++ b/src/Gui/AxisOriginPyImp.cpp @@ -20,9 +20,9 @@ * * ****************************************************************************/ -# include -# include -# include +#include +#include +#include #include "AxisOriginPy.h" #include "AxisOriginPy.cpp" @@ -30,7 +30,7 @@ using namespace Gui; -PyObject *AxisOriginPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* AxisOriginPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new AxisOriginPy(new AxisOrigin); } @@ -49,11 +49,12 @@ std::string AxisOriginPy::representation() const PyObject* AxisOriginPy::getElementPicked(PyObject* args) const { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } - void *ptr = nullptr; + void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoPickedPoint", obj, &ptr, 0); if (!ptr) { PyErr_SetString(PyExc_TypeError, "'pickedPoint' must be a coin.SoPickedPoint"); @@ -62,20 +63,22 @@ PyObject* AxisOriginPy::getElementPicked(PyObject* args) const auto pp = static_cast(ptr); std::string name; - if (!getAxisOriginPtr()->getElementPicked(pp,name)) + if (!getAxisOriginPtr()->getElementPicked(pp, name)) { Py_Return; + } return Py::new_reference_to(Py::String(name)); } PyObject* AxisOriginPy::getDetailPath(PyObject* args) const { - const char *sub; - PyObject *path; - if (!PyArg_ParseTuple(args, "sO", &sub,&path)) + const char* sub; + PyObject* path; + if (!PyArg_ParseTuple(args, "sO", &sub, &path)) { return nullptr; + } - void *ptr = nullptr; + void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoPath", path, &ptr, 0); if (!ptr) { PyErr_SetString(PyExc_TypeError, "'path' must be a coin.SoPath"); @@ -83,15 +86,17 @@ PyObject* AxisOriginPy::getDetailPath(PyObject* args) const } auto pPath = static_cast(ptr); - SoDetail *det = nullptr; + SoDetail* det = nullptr; if (!getAxisOriginPtr()->getDetailPath(sub, static_cast(pPath), det)) { delete det; Py_Return; } - if (!det) + if (!det) { Py_Return; + } - return Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoDetail", static_cast(det), 0); + return Base::Interpreter() + .createSWIGPointerObj("pivy.coin", "_p_SoDetail", static_cast(det), 0); } Py::Float AxisOriginPy::getAxisLength() const @@ -138,35 +143,37 @@ Py::Tuple AxisOriginPy::getPlane() const { auto info = getAxisOriginPtr()->getPlane(); Py::Tuple ret(2); - ret.setItem(0,Py::Float(info.first)); - ret.setItem(1,Py::Float(info.second)); + ret.setItem(0, Py::Float(info.first)); + ret.setItem(1, Py::Float(info.second)); return ret; } void AxisOriginPy::setPlane(Py::Tuple tuple) { - float s,d; - if (!PyArg_ParseTuple(*tuple, "ff",&s,&d)) + float s, d; + if (!PyArg_ParseTuple(*tuple, "ff", &s, &d)) { throw Py::Exception(); + } - getAxisOriginPtr()->setPlane(s,d); + getAxisOriginPtr()->setPlane(s, d); } Py::Dict AxisOriginPy::getLabels() const { Py::Dict dict; - for (auto &v : getAxisOriginPtr()->getLabels()) - dict.setItem(Py::String(v.first),Py::String(v.second)); + for (auto& v : getAxisOriginPtr()->getLabels()) { + dict.setItem(Py::String(v.first), Py::String(v.second)); + } return dict; } void AxisOriginPy::setLabels(Py::Dict dict) { - std::map labels; - for (auto it=dict.begin(); it!=dict.end(); ++it) { - const auto &value = *it; + std::map labels; + for (auto it = dict.begin(); it != dict.end(); ++it) { + const auto& value = *it; labels[value.first.as_string()] = Py::Object(value.second).as_string(); } getAxisOriginPtr()->setLabels(labels); @@ -175,12 +182,12 @@ void AxisOriginPy::setLabels(Py::Dict dict) Py::Object AxisOriginPy::getNode() const { SoGroup* node = getAxisOriginPtr()->getNode(); - PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin","SoGroup *", node, 1); + PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoGroup *", node, 1); node->ref(); return Py::Object(Ptr, true); } -PyObject *AxisOriginPy::getCustomAttributes(const char* /*attr*/) const +PyObject* AxisOriginPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Gui/BitmapFactory.cpp b/src/Gui/BitmapFactory.cpp index b6657bac0f..154d9cbc7f 100644 --- a/src/Gui/BitmapFactory.cpp +++ b/src/Gui/BitmapFactory.cpp @@ -20,19 +20,19 @@ * * ***************************************************************************/ -# 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 @@ -45,7 +45,8 @@ using namespace Gui; -namespace Gui { +namespace Gui +{ class BitmapFactoryInstP { public: @@ -53,16 +54,15 @@ public: bool useIconTheme; }; -} +} // namespace Gui BitmapFactoryInst* BitmapFactoryInst::_pcSingleton = nullptr; BitmapFactoryInst& BitmapFactoryInst::instance() { - if (!_pcSingleton) - { + if (!_pcSingleton) { _pcSingleton = new BitmapFactoryInst; - std::map::const_iterator it; + std::map::const_iterator it; it = App::GetApplication().Config().find("ProgramIcons"); if (it != App::GetApplication().Config().end()) { QString home = QString::fromStdString(App::Application::getHomePath()); @@ -72,8 +72,12 @@ BitmapFactoryInst& BitmapFactoryInst::instance() } _pcSingleton->addPath(path); } - _pcSingleton->addPath(QStringLiteral("%1/icons").arg(QString::fromStdString(App::Application::getHomePath()))); - _pcSingleton->addPath(QStringLiteral("%1/icons").arg(QString::fromStdString(App::Application::getUserAppDataDir()))); + _pcSingleton->addPath( + QStringLiteral("%1/icons").arg(QString::fromStdString(App::Application::getHomePath())) + ); + _pcSingleton->addPath( + QStringLiteral("%1/icons").arg(QString::fromStdString(App::Application::getUserAppDataDir())) + ); _pcSingleton->addPath(QLatin1String(":/icons/")); _pcSingleton->addPath(QLatin1String(":/Icons/")); } @@ -81,10 +85,11 @@ BitmapFactoryInst& BitmapFactoryInst::instance() return *_pcSingleton; } -void BitmapFactoryInst::destruct () +void BitmapFactoryInst::destruct() { - if (_pcSingleton) - delete _pcSingleton; + if (_pcSingleton) { + delete _pcSingleton; + } _pcSingleton = nullptr; } @@ -103,18 +108,20 @@ BitmapFactoryInst::~BitmapFactoryInst() void BitmapFactoryInst::restoreCustomPaths() { - Base::Reference group = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Bitmaps"); + Base::Reference group = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Bitmaps" + ); std::vector paths = group->GetASCIIs("CustomPath"); - for (auto & path : paths) { + for (auto& path : paths) { addPath(QString::fromUtf8(path.c_str())); } } void Gui::BitmapFactoryInst::configureUseIconTheme() { - Base::Reference group = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Bitmaps/Theme"); + Base::Reference group = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Bitmaps/Theme" + ); d->useIconTheme = group->GetBool("UseIconTheme", group->GetBool("ThemeSearchPaths", false)); } @@ -143,8 +150,9 @@ QStringList BitmapFactoryInst::findIconFiles() const { QStringList files, filters; QList formats = QImageReader::supportedImageFormats(); - for (QList::iterator it = formats.begin(); it != formats.end(); ++it) + for (QList::iterator it = formats.begin(); it != formats.end(); ++it) { filters << QStringLiteral("*.%1").arg(QString::fromLatin1(*it).toLower()); + } QStringList paths = QDir::searchPaths(QStringLiteral("icons")); paths.removeDuplicates(); @@ -152,8 +160,9 @@ QStringList BitmapFactoryInst::findIconFiles() const QDir d(*pt); d.setNameFilters(filters); QFileInfoList fi = d.entryInfoList(); - for (QFileInfoList::iterator it = fi.begin(); it != fi.end(); ++it) + for (QFileInfoList::iterator it = fi.begin(); it != fi.end(); ++it) { files << it->absoluteFilePath(); + } } files.removeDuplicates(); @@ -185,8 +194,9 @@ QIcon BitmapFactoryInst::iconFromTheme(const char* name, const QIcon& fallback) QIcon icon = QIcon::fromTheme(iconName, fallback); if (icon.isNull()) { QPixmap px = pixmap(name); - if (!px.isNull()) + if (!px.isNull()) { icon.addPixmap(px); + } } return icon; @@ -201,7 +211,7 @@ bool BitmapFactoryInst::loadPixmap(const QString& filename, QPixmap& icon) const QFile svgFile(fi.filePath()); if (svgFile.open(QFile::ReadOnly | QFile::Text)) { QByteArray content = svgFile.readAll(); - icon = pixmapFromSvg(content, QSize(64,64)); + icon = pixmapFromSvg(content, QSize(64, 64)); } } else { @@ -221,7 +231,8 @@ QIcon Gui::BitmapFactoryInst::iconFromDefaultTheme(const char* name, const QIcon if (!px.isNull()) { icon.addPixmap(px); return icon; - } else { + } + else { return fallback; } @@ -230,13 +241,15 @@ QIcon Gui::BitmapFactoryInst::iconFromDefaultTheme(const char* name, const QIcon QPixmap BitmapFactoryInst::pixmap(const char* name) const { - if (!name || *name == '\0') + if (!name || *name == '\0') { return {}; + } // as very first test check whether the pixmap is in the cache QMap::Iterator it = d->xpmCache.find(name); - if (it != d->xpmCache.end()) + if (it != d->xpmCache.end()) { return it.value(); + } QPixmap icon; @@ -247,14 +260,16 @@ QPixmap BitmapFactoryInst::pixmap(const char* name) const // try to find it in the 'icons' search paths if (icon.isNull()) { QList formats = QImageReader::supportedImageFormats(); - formats.prepend("SVG"); // check first for SVG to use special import mechanism + formats.prepend("SVG"); // check first for SVG to use special import mechanism QString fileName = QStringLiteral("icons:") + fn; if (!loadPixmap(fileName, icon)) { // Go through supported file formats for (QList::iterator fm = formats.begin(); fm != formats.end(); ++fm) { - QString path = QStringLiteral("%1.%2").arg(fileName, - QString::fromLatin1((*fm).toLower().constData())); + QString path = QStringLiteral("%1.%2").arg( + fileName, + QString::fromLatin1((*fm).toLower().constData()) + ); if (loadPixmap(path, icon)) { break; } @@ -271,17 +286,21 @@ QPixmap BitmapFactoryInst::pixmap(const char* name) const return QPixmap(Gui::BitmapFactory().pixmapFromSvg("help-browser", QSize(16, 16))); } -QPixmap BitmapFactoryInst::pixmapFromSvg(const char* name, const QSizeF& size, - const ColorMap& colorMapping) const +QPixmap BitmapFactoryInst::pixmapFromSvg( + const char* name, + const QSizeF& size, + const ColorMap& colorMapping +) const { static qreal dpr = getMaximumDPR(); - + // If an absolute path is given QPixmap icon; QString iconPath; QString fn = QString::fromUtf8(name); - if (QFile(fn).exists()) + if (QFile(fn).exists()) { iconPath = fn; + } // try to find it in the 'icons' search paths if (iconPath.isEmpty()) { @@ -314,15 +333,18 @@ QPixmap BitmapFactoryInst::pixmapFromSvg(const char* name, const QSizeF& size, return icon; } -QPixmap BitmapFactoryInst::pixmapFromSvg(const QByteArray& originalContents, const QSizeF& size, - const ColorMap& colorMapping) const +QPixmap BitmapFactoryInst::pixmapFromSvg( + const QByteArray& originalContents, + const QSizeF& size, + const ColorMap& colorMapping +) const { QString stringContents = QString::fromUtf8(originalContents); - for ( const auto &colorToColor : colorMapping ) { + for (const auto& colorToColor : colorMapping) { ulong fromColor = colorToColor.first; ulong toColor = colorToColor.second; - QString fromColorString = QStringLiteral("#%1").arg(fromColor, 6, 16, QChar::fromLatin1('0')); - QString toColorString = QStringLiteral("#%1").arg(toColor, 6, 16, QChar::fromLatin1('0')); + QString fromColorString = QStringLiteral("#%1").arg(fromColor, 6, 16, QChar::fromLatin1('0')); + QString toColorString = QStringLiteral("#%1").arg(toColor, 6, 16, QChar::fromLatin1('0')); stringContents = stringContents.replace(fromColorString, toColorString); } QByteArray contents = stringContents.toUtf8(); @@ -346,10 +368,12 @@ QPixmap BitmapFactoryInst::pixmapFromSvg(const QByteArray& originalContents, con QStringList BitmapFactoryInst::pixmapNames() const { QStringList names; - for (QMap::Iterator It = d->xpmCache.begin(); It != d->xpmCache.end(); ++It) { + for (QMap::Iterator It = d->xpmCache.begin(); It != d->xpmCache.end(); + ++It) { QString item = QString::fromUtf8(It.key().c_str()); - if (!names.contains(item)) + if (!names.contains(item)) { names << item; + } } return names; } @@ -357,56 +381,58 @@ QStringList BitmapFactoryInst::pixmapNames() const QPixmap BitmapFactoryInst::resize(int w, int h, const QPixmap& p, Qt::BGMode bgmode) const { if (bgmode == Qt::TransparentMode) { - if (p.width() == 0 || p.height() == 0) + if (p.width() == 0 || p.height() == 0) { w = 1; + } QPixmap pix = p; - int x = pix.width () > w ? 0 : (w - pix.width ())/2; - int y = pix.height() > h ? 0 : (h - pix.height())/2; + int x = pix.width() > w ? 0 : (w - pix.width()) / 2; + int y = pix.height() > h ? 0 : (h - pix.height()) / 2; - if (x == 0 && y == 0) + if (x == 0 && y == 0) { return pix; + } - QPixmap pm (w,h); - QBitmap mask (w,h); + QPixmap pm(w, h); + QBitmap mask(w, h); mask.fill(Qt::color0); QBitmap bm = pix.mask(); - if (!bm.isNull()) - { + if (!bm.isNull()) { QPainter painter(&mask); painter.drawPixmap(QPoint(x, y), bm, QRect(0, 0, pix.width(), pix.height())); pm.setMask(mask); } - else - { + else { pm.setMask(mask); pm = fillRect(x, y, pix.width(), pix.height(), pm, Qt::OpaqueMode); } QPainter pt; - pt.begin( &pm ); + pt.begin(&pm); pt.drawPixmap(x, y, pix); pt.end(); return pm; - } else { // Qt::OpaqueMode + } + else { // Qt::OpaqueMode QPixmap pix = p; - if (pix.width() == 0 || pix.height() == 0) - return pix; // do not resize a null pixmap + if (pix.width() == 0 || pix.height() == 0) { + return pix; // do not resize a null pixmap + } QPalette pal = qApp->palette(); QColor dl = pal.color(QPalette::Disabled, QPalette::Light); QColor dt = pal.color(QPalette::Disabled, QPalette::Text); - QPixmap pm(w,h); + QPixmap pm(w, h); pm.fill(dl); QPainter pt; - pt.begin( &pm ); - pt.setPen( dl ); + pt.begin(&pm); + pt.setPen(dl); pt.drawPixmap(1, 1, pix); - pt.setPen( dt ); + pt.setPen(dt); pt.drawPixmap(0, 0, pix); pt.end(); return pm; @@ -416,18 +442,21 @@ QPixmap BitmapFactoryInst::resize(int w, int h, const QPixmap& p, Qt::BGMode bgm QPixmap BitmapFactoryInst::fillRect(int x, int y, int w, int h, const QPixmap& p, Qt::BGMode bgmode) const { QBitmap b = p.mask(); - if (b.isNull()) - return p; // sorry, but cannot do anything + if (b.isNull()) { + return p; // sorry, but cannot do anything + } QPixmap pix = p; // modify the mask QPainter pt; pt.begin(&b); - if (bgmode == Qt::OpaqueMode) - pt.fillRect(x, y, w, h, Qt::color1); // make opaque - else // Qt::TransparentMode - pt.fillRect(x, y, w, h, Qt::color0); // make transparent + if (bgmode == Qt::OpaqueMode) { + pt.fillRect(x, y, w, h, Qt::color1); // make opaque + } + else { // Qt::TransparentMode + pt.fillRect(x, y, w, h, Qt::color0); // make transparent + } pt.end(); pix.setMask(b); @@ -446,19 +475,20 @@ QPixmap BitmapFactoryInst::merge(const QPixmap& p1, const QPixmap& p2, bool vert // get the size for the new pixmap if (vertical) { y = p1.height(); - width = qMax( p1.width(), p2.width() ); + width = qMax(p1.width(), p2.width()); height = p1.height() + p2.height(); - } else { + } + else { x = p1.width(); - width = p1.width() + p2.width(); - height = qMax( p1.height(), p2.height() ); + width = p1.width() + p2.width(); + height = qMax(p1.height(), p2.height()); } - QPixmap res( width, height ); - QBitmap mask( width, height ); + QPixmap res(width, height); + QBitmap mask(width, height); QBitmap mask1 = p1.mask(); QBitmap mask2 = p2.mask(); - mask.fill( Qt::color0 ); + mask.fill(Qt::color0); auto* pt1 = new QPainter(&res); pt1->drawPixmap(0, 0, p1); @@ -481,27 +511,26 @@ QPixmap BitmapFactoryInst::merge(const QPixmap& p1, const QPixmap& p2, Position qreal dpr1 = p1.devicePixelRatio(); qreal dpr2 = p2.devicePixelRatio(); - switch (pos) - { - case TopLeft: - break; - case TopRight: - x = p1.width ()/dpr1 - p2.width ()/dpr2; - break; - case BottomLeft: - y = p1.height()/dpr1 - p2.height()/dpr2; - break; - case BottomRight: - x = p1.width ()/dpr1 - p2.width ()/dpr2; - y = p1.height()/dpr1 - p2.height()/dpr2; - break; + switch (pos) { + case TopLeft: + break; + case TopRight: + x = p1.width() / dpr1 - p2.width() / dpr2; + break; + case BottomLeft: + y = p1.height() / dpr1 - p2.height() / dpr2; + break; + case BottomRight: + x = p1.width() / dpr1 - p2.width() / dpr2; + y = p1.height() / dpr1 - p2.height() / dpr2; + break; } QPixmap p = p1; p = fillRect(x, y, p2.width(), p2.height(), p, Qt::OpaqueMode); QPainter pt; - pt.begin( &p ); + pt.begin(&p); pt.setPen(Qt::NoPen); pt.drawRect(x, y, p2.width(), p2.height()); pt.drawPixmap(x, y, p2); @@ -578,44 +607,39 @@ void BitmapFactoryInst::convert(const QImage& p, SoSFImage& img) const for (int y = 0; y < height; y++) { unsigned char* line = &bytes[width * numcomponents * (height - (y + 1))]; for (int x = 0; x < width; x++) { - QColor col = p.pixelColor(x,y); + QColor col = p.pixelColor(x, y); switch (depth) { default: break; - case 1: - { + case 1: { QRgb rgb = col.rgb(); line[0] = qGray(rgb); - } break; - case 2: - { + } break; + case 2: { QRgb rgb = col.rgba(); line[0] = qGray(rgb); line[1] = qAlpha(rgb); - } break; - case 3: - { + } break; + case 3: { QRgb rgb = col.rgb(); line[0] = qRed(rgb); line[1] = qGreen(rgb); line[2] = qBlue(rgb); - } break; - case 4: - { + } break; + case 4: { QRgb rgb = col.rgba(); line[0] = qRed(rgb); line[1] = qGreen(rgb); line[2] = qBlue(rgb); line[3] = qAlpha(rgb); - } break; - case 8: - { + } break; + case 8: { QRgba64 rgb = col.rgba64(); line[0] = qRed(rgb); line[1] = qGreen(rgb); line[2] = qBlue(rgb); line[3] = qAlpha(rgb); - } break; + } break; } line += numcomponents; @@ -630,36 +654,34 @@ void BitmapFactoryInst::convert(const SoSFImage& p, QImage& img) const SbVec2s size; int numcomponents; - const unsigned char * bytes = p.getValue(size, numcomponents); - if (!bytes) + const unsigned char* bytes = p.getValue(size, numcomponents); + if (!bytes) { return; + } - int width = (int)size[0]; + int width = (int)size[0]; int height = (int)size[1]; img = QImage(width, height, QImage::Format_RGB32); - QRgb * bits = (QRgb*) img.bits(); + QRgb* bits = (QRgb*)img.bits(); - for (int y = 0; y < height; y++) - { - const unsigned char * line = &bytes[width*numcomponents*(height-(y+1))]; - for (int x = 0; x < width; x++) - { - switch (numcomponents) - { - default: - case 1: - *bits++ = qRgb(line[0], line[0], line[0]); - break; - case 2: - *bits++ = qRgba(line[0], line[0], line[0], line[1]); - break; - case 3: - *bits++ = qRgb(line[0], line[1], line[2]); - break; - case 4: - *bits++ = qRgba(line[0], line[1], line[2], line[3]); - break; + for (int y = 0; y < height; y++) { + const unsigned char* line = &bytes[width * numcomponents * (height - (y + 1))]; + for (int x = 0; x < width; x++) { + switch (numcomponents) { + default: + case 1: + *bits++ = qRgb(line[0], line[0], line[0]); + break; + case 2: + *bits++ = qRgba(line[0], line[0], line[0], line[1]); + break; + case 3: + *bits++ = qRgb(line[0], line[1], line[2]); + break; + case 4: + *bits++ = qRgba(line[0], line[1], line[2], line[3]); + break; } line += numcomponents; @@ -667,17 +689,27 @@ void BitmapFactoryInst::convert(const SoSFImage& p, QImage& img) const } } -QIcon BitmapFactoryInst::mergePixmap (const QIcon &base, const QPixmap &px, Gui::BitmapFactoryInst::Position position) +QIcon BitmapFactoryInst::mergePixmap( + const QIcon& base, + const QPixmap& px, + Gui::BitmapFactoryInst::Position position +) { QIcon overlayedIcon; int w = QApplication::style()->pixelMetric(QStyle::PM_ListViewIconSize); - overlayedIcon.addPixmap(Gui::BitmapFactory().merge(base.pixmap(w, w, QIcon::Normal, QIcon::Off), - px,position), QIcon::Normal, QIcon::Off); + overlayedIcon.addPixmap( + Gui::BitmapFactory().merge(base.pixmap(w, w, QIcon::Normal, QIcon::Off), px, position), + QIcon::Normal, + QIcon::Off + ); - overlayedIcon.addPixmap(Gui::BitmapFactory().merge(base.pixmap(w, w, QIcon::Normal, QIcon::On ), - px,position), QIcon::Normal, QIcon::Off); + overlayedIcon.addPixmap( + Gui::BitmapFactory().merge(base.pixmap(w, w, QIcon::Normal, QIcon::On), px, position), + QIcon::Normal, + QIcon::Off + ); return overlayedIcon; } @@ -686,7 +718,7 @@ qreal BitmapFactoryInst::getMaximumDPR() { qreal dpr = 1.0F; - for (QScreen* screen: QGuiApplication::screens()) { + for (QScreen* screen : QGuiApplication::screens()) { dpr = std::max(screen->devicePixelRatio(), dpr); } diff --git a/src/Gui/BitmapFactory.h b/src/Gui/BitmapFactory.h index 4c1ecd1b68..34219f5f34 100644 --- a/src/Gui/BitmapFactory.h +++ b/src/Gui/BitmapFactory.h @@ -32,30 +32,31 @@ class SoSFImage; class QImage; -namespace Gui { +namespace Gui +{ using ColorMap = std::map; /** The Bitmap Factory - * the main purpose is to collect all build in Bitmaps and - * hold all paths for the extern bitmaps (files) to serve - * as a single point of accessing bitmaps in FreeCAD - * \author Werner Mayer, Jürgen Riegel - */ + * the main purpose is to collect all build in Bitmaps and + * hold all paths for the extern bitmaps (files) to serve + * as a single point of accessing bitmaps in FreeCAD + * \author Werner Mayer, Jürgen Riegel + */ class BitmapFactoryInstP; -class GuiExport BitmapFactoryInst : public Base::Factory +class GuiExport BitmapFactoryInst: public Base::Factory { public: enum Position { - TopLeft, /**< Place to the top left corner */ - TopRight, /**< Place to the top right corner */ + TopLeft, /**< Place to the top left corner */ + TopRight, /**< Place to the top right corner */ BottomLeft, /**< Place to the bottom left corner */ BottomRight /**< Place to the bottom right corner */ }; static BitmapFactoryInst& instance(); - static void destruct (); + static void destruct(); /// Adds a path where pixmaps can be found void addPath(const QString& path); @@ -85,18 +86,24 @@ public: * @param colorMapping - a dictionary of substitute colors. * Can be used to customize icon color scheme, e.g. crosshair color */ - QPixmap pixmapFromSvg(const char* name, const QSizeF& size, - const ColorMap& colorMapping = ColorMap()) const; + QPixmap pixmapFromSvg( + const char* name, + const QSizeF& size, + const ColorMap& colorMapping = ColorMap() + ) const; /** This method is provided for convenience and does the same * as the method above except that it creates the pixmap from * a byte array. * @param colorMapping - see above. */ - QPixmap pixmapFromSvg(const QByteArray& contents, const QSizeF& size, - const ColorMap& colorMapping = ColorMap()) const; + QPixmap pixmapFromSvg( + const QByteArray& contents, + const QSizeF& size, + const ColorMap& colorMapping = ColorMap() + ) const; /** Returns the names of all registered pixmaps. - * To get the appropriate pixmaps call pixmap() for each name. - */ + * To get the appropriate pixmaps call pixmap() for each name. + */ QStringList pixmapNames() const; /** Resizes the area of a pixmap * If the new size is greater than the old one the pixmap @@ -144,7 +151,11 @@ public: void convert(const SoSFImage& img, QImage& out) const; /// Helper method to merge a pixmap into one corner of a QIcon - static QIcon mergePixmap (const QIcon &base, const QPixmap &px, Gui::BitmapFactoryInst::Position position); + static QIcon mergePixmap( + const QIcon& base, + const QPixmap& px, + Gui::BitmapFactoryInst::Position position + ); static qreal getMaximumDPR(); @@ -166,6 +177,6 @@ inline BitmapFactoryInst& BitmapFactory() return BitmapFactoryInst::instance(); } -} // namespace Gui +} // namespace Gui -#endif // GUI_BITMAPFACTORY_H +#endif // GUI_BITMAPFACTORY_H diff --git a/src/Gui/CallTips.cpp b/src/Gui/CallTips.cpp index 321fc728b9..1cb9d36367 100644 --- a/src/Gui/CallTips.cpp +++ b/src/Gui/CallTips.cpp @@ -20,16 +20,16 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -47,7 +47,7 @@ #include "CallTips.h" -Q_DECLARE_METATYPE( Gui::CallTip ) //< allows use of QVariant +Q_DECLARE_METATYPE(Gui::CallTip) //< allows use of QVariant namespace Gui { @@ -56,20 +56,25 @@ namespace Gui * template class Temporary. * Allows variable changes limited to a scope. */ -template +template class Temporary { public: - Temporary( TYPE &var, const TYPE tmpVal ) - : _var(var), _saveVal(var) - { var = tmpVal; } + Temporary(TYPE& var, const TYPE tmpVal) + : _var(var) + , _saveVal(var) + { + var = tmpVal; + } - ~Temporary( ) - { _var = _saveVal; } + ~Temporary() + { + _var = _saveVal; + } private: - TYPE &_var; - TYPE _saveVal; + TYPE& _var; + TYPE _saveVal; }; } /* namespace Gui */ @@ -77,13 +82,25 @@ private: using namespace Gui; CallTipsList::CallTipsList(QPlainTextEdit* parent) - : QListWidget(parent), textEdit(parent), cursorPos(0), validObject(true), doCallCompletion(false) + : QListWidget(parent) + , textEdit(parent) + , cursorPos(0) + , validObject(true) + , doCallCompletion(false) { // make the user assume that the widget is active QPalette pal = parent->palette(); - pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Active, QPalette::Highlight)); - pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Active, QPalette::HighlightedText)); - parent->setPalette( pal ); + pal.setColor( + QPalette::Inactive, + QPalette::Highlight, + pal.color(QPalette::Active, QPalette::Highlight) + ); + pal.setColor( + QPalette::Inactive, + QPalette::HighlightedText, + pal.color(QPalette::Active, QPalette::HighlightedText) + ); + parent->setPalette(pal); connect(this, &QListWidget::itemActivated, this, &CallTipsList::callTipItemActivated); @@ -123,7 +140,7 @@ CallTipsList::~CallTipsList() = default; void CallTipsList::keyboardSearch(const QString& wordPrefix) { // first search for the item that matches perfectly - for (int i=0; itext(); if (text.startsWith(wordPrefix)) { setCurrentRow(i); @@ -132,7 +149,7 @@ void CallTipsList::keyboardSearch(const QString& wordPrefix) } // now do a case insensitive comparison - for (int i=0; itext(); if (text.startsWith(wordPrefix, Qt::CaseInsensitive)) { setCurrentRow(i); @@ -140,8 +157,9 @@ void CallTipsList::keyboardSearch(const QString& wordPrefix) } } - if (currentItem()) + if (currentItem()) { currentItem()->setSelected(false); + } } void CallTipsList::validateCursor() @@ -157,15 +175,16 @@ void CallTipsList::validateCursor() QString word = cursor.selectedText(); if (!word.isEmpty()) { // the following text might be an operator, brackets, ... - const QChar underscore = QLatin1Char('_'); + const QChar underscore = QLatin1Char('_'); const QChar ch = word.at(0); - if (!ch.isLetterOrNumber() && ch != underscore) + if (!ch.isLetterOrNumber() && ch != underscore) { word.clear(); + } } - if (currentPos > this->cursorPos+word.length()) { + if (currentPos > this->cursorPos + word.length()) { hide(); } - else if (!word.isEmpty()){ + else if (!word.isEmpty()) { // If the word is empty we should not allow one to do a search, // otherwise we may select the next item which is not okay in this // context. This might happen if e.g. Shift is pressed. @@ -177,18 +196,20 @@ void CallTipsList::validateCursor() QString CallTipsList::extractContext(const QString& line) const { int len = line.size(); - int index = len-1; - for (int i=0; i= 48 && ch <= 57) || // Numbers - (ch >= 65 && ch <= 90) || // Uppercase letters - (ch >= 97 && ch <= 122) || // Lowercase letters - (ch == '.') || (ch == '_') || // dot or underscore - (ch == ' ') || (ch == '\t')) // whitespace (between dot and text) + if ((ch >= 48 && ch <= 57) || // Numbers + (ch >= 65 && ch <= 90) || // Uppercase letters + (ch >= 97 && ch <= 122) || // Lowercase letters + (ch == '.') || (ch == '_') || // dot or underscore + (ch == ' ') || (ch == '\t')) { // whitespace (between dot and text) index = pos; - else + } + else { break; + } } return line.mid(index); @@ -198,8 +219,9 @@ QMap CallTipsList::extractTips(const QString& context) const { Base::PyGILStateLocker lock; QMap tips; - if (context.isEmpty()) + if (context.isEmpty()) { return tips; + } try { PyErr_Clear(); @@ -213,10 +235,16 @@ QMap CallTipsList::extractTips(const QString& context) const QStringList items = context.split(QLatin1Char('.')); QString modname = items.front(); items.pop_front(); - if (!dict.hasKey(std::string(modname.toLatin1()))) - return tips; // unknown object - // Don't use hasattr & getattr because if a property is bound to a method this will be executed twice. - PyObject* code = Py_CompileString(static_cast(context.toLatin1()), "", Py_eval_input); + if (!dict.hasKey(std::string(modname.toLatin1()))) { + return tips; // unknown object + } + // Don't use hasattr & getattr because if a property is bound to a method this will be + // executed twice. + PyObject* code = Py_CompileString( + static_cast(context.toLatin1()), + "", + Py_eval_input + ); if (!code) { PyErr_Clear(); return tips; @@ -239,9 +267,9 @@ QMap CallTipsList::extractTips(const QString& context) const // Note: 3rd party libraries may use their own type object classes so that we cannot // reliably use Py::Type. To be on the safe side we should use Py::Object to assign // the used type object to. - //Py::Object type = obj.type(); + // Py::Object type = obj.type(); Py::Object type(PyObject_Type(obj.ptr()), true); - Py::Object inst = obj; // the object instance + Py::Object inst = obj; // the object instance PyObject* typeobj = Base::getTypeAsObject(&Base::PyObjectBase::Type); PyObject* typedoc = Base::getTypeAsObject(&App::DocumentObjectPy::Type); PyObject* basetype = Base::getTypeAsObject(&PyBaseObject_Type); @@ -250,8 +278,8 @@ QMap CallTipsList::extractTips(const QString& context) const // From the template Python object we don't query its type object because there we keep // a list of additional methods that we won't see otherwise. But to get the correct doc // strings we query the type's dict in the class itself. - // To see if we have a template Python object we check for the existence of '__fc_template__' - // See also: FeaturePythonPyT + // To see if we have a template Python object we check for the existence of + // '__fc_template__' See also: FeaturePythonPyT if (!obj.hasAttr("__fc_template__")) { obj = type; } @@ -270,7 +298,8 @@ QMap CallTipsList::extractTips(const QString& context) const // this should be now a user-defined Python class // http://stackoverflow.com/questions/12233103/in-python-at-runtime-determine-if-an-object-is-a-class-old-and-new-type-instan - if (!typestr.startsWith(QLatin1String("PySide")) && Py_TYPE(obj.ptr())->tp_flags & Py_TPFLAGS_HEAPTYPE) { + if (!typestr.startsWith(QLatin1String("PySide")) + && Py_TYPE(obj.ptr())->tp_flags & Py_TPFLAGS_HEAPTYPE) { obj = type; } } @@ -307,8 +336,9 @@ QMap CallTipsList::extractTips(const QString& context) const if (document) { std::vector objects = document->getObjects(); Py::List list; - for (const auto & object : objects) + for (const auto& object : objects) { list.append(Py::String(object->getNameInDocument())); + } extractTipsFromObject(inst, list, tips); } } @@ -324,8 +354,9 @@ QMap CallTipsList::extractTips(const QString& context) const if (document) { std::vector objects = document->getObjects(); Py::List list; - for (const auto & object : objects) + for (const auto& object : objects) { list.append(Py::String(object->getNameInDocument())); + } extractTipsFromObject(inst, list, tips); } } @@ -362,8 +393,7 @@ bool shibokenMayCrash(void) Py::Object CallTipsList::getAttrWorkaround(Py::Object& obj, Py::String& name) const { QString typestr(QLatin1String(Py_TYPE(obj.ptr())->tp_name)); - bool hasWorkingGetAttr = - !(typestr == QLatin1String("Shiboken.ObjectType") && shibokenMayCrash()); + bool hasWorkingGetAttr = !(typestr == QLatin1String("Shiboken.ObjectType") && shibokenMayCrash()); if (hasWorkingGetAttr) { return obj.getAttr(name.as_string()); @@ -403,7 +433,7 @@ void CallTipsList::extractTipsFromObject(Py::Object& obj, Py::List& list, QMap::iterator pos = tips.find(str); - if (pos == tips.end()) + if (pos == tips.end()) { tips[str] = tip; + } } catch (Py::Exception& e) { // Just clear the Python exception @@ -458,12 +491,13 @@ void CallTipsList::extractTipsFromProperties(Py::Object& obj, QMap(obj.ptr()); App::PropertyContainer* container = cont->getPropertyContainerPtr(); // Make sure that the C++ object is alive - if (!container) + if (!container) { return; - std::map Map; + } + std::map Map; container->getPropertyMap(Map); - for (const auto & It : Map) { + for (const auto& It : Map) { CallTip tip; QString str = QString::fromLatin1(It.first.c_str()); tip.name = str; @@ -483,8 +517,9 @@ void CallTipsList::extractTipsFromProperties(Py::Object& obj, QMapvalidObject = true; QString context = extractContext(line); @@ -516,38 +558,33 @@ void CallTipsList::showTips(const QString& line) clear(); for (QMap::Iterator it = tips.begin(); it != tips.end(); ++it) { addItem(it.key()); - QListWidgetItem *item = this->item(this->count()-1); + QListWidgetItem* item = this->item(this->count() - 1); item->setData(Qt::ToolTipRole, QVariant(it.value().description)); - item->setData(Qt::UserRole, QVariant::fromValue( it.value() )); //< store full CallTip data - switch (it.value().type) - { - case CallTip::Module: - { + item->setData(Qt::UserRole, QVariant::fromValue(it.value())); //< store full CallTip data + switch (it.value().type) { + case CallTip::Module: { item->setIcon((this->validObject ? type_module_icon : forbidden_type_module_icon)); - } break; - case CallTip::Class: - { + } break; + case CallTip::Class: { item->setIcon((this->validObject ? type_class_icon : forbidden_type_class_icon)); - } break; - case CallTip::Method: - { + } break; + case CallTip::Method: { item->setIcon((this->validObject ? method_icon : forbidden_method_icon)); - } break; - case CallTip::Member: - { + } break; + case CallTip::Member: { item->setIcon((this->validObject ? member_icon : forbidden_member_icon)); - } break; - case CallTip::Property: - { + } break; + case CallTip::Property: { item->setIcon((this->validObject ? property_icon : forbidden_property_icon)); - } break; - default: - break; + } break; + default: + break; } } - if (count()==0) - return; // nothing found + if (count() == 0) { + return; // nothing found + } // get the minimum width and height of the box int h = 0; @@ -559,8 +596,8 @@ void CallTipsList::showTips(const QString& line) } // Add an offset - w += 2*frameWidth(); - h += 2*frameWidth(); + w += 2 * frameWidth(); + h += 2 * frameWidth(); // get the start position of the word prefix QTextCursor cursor = textEdit->textCursor(); @@ -571,17 +608,19 @@ void CallTipsList::showTips(const QString& line) int boxH = h; // Decide whether to show downstairs or upstairs - if (posY > textEdit->viewport()->height()/2) { - h = qMin(qMin(h,posY), 250); - if (h < boxH) + if (posY > textEdit->viewport()->height() / 2) { + h = qMin(qMin(h, posY), 250); + if (h < boxH) { w += textEdit->style()->pixelMetric(QStyle::PM_ScrollBarExtent); - setGeometry(posX,posY-h, w, h); + } + setGeometry(posX, posY - h, w, h); } else { - h = qMin(qMin(h,textEdit->viewport()->height()-fontMetrics().height()-posY), 250); - if (h < boxH) + h = qMin(qMin(h, textEdit->viewport()->height() - fontMetrics().height() - posY), 250); + if (h < boxH) { w += textEdit->style()->pixelMetric(QStyle::PM_ScrollBarExtent); - setGeometry(posX, posY+fontMetrics().height(), w, h); + } + setGeometry(posX, posY + fontMetrics().height(), w, h); } setCurrentRow(0); @@ -605,19 +644,21 @@ void CallTipsList::hideEvent(QHideEvent* e) * Get all incoming events of the text edit and redirect some of them, like key up and * down, mouse press events, ... to the widget itself. */ -bool CallTipsList::eventFilter(QObject * watched, QEvent * event) +bool CallTipsList::eventFilter(QObject* watched, QEvent* event) { // This is a trick to avoid to hide the tooltip window after the defined time span // of 10 seconds. We just filter out all timer events to keep the label visible. if (watched->inherits("QLabel")) { auto label = qobject_cast(watched); // Ignore the timer events to prevent from being closed - if (label->windowFlags() & Qt::ToolTip && event->type() == QEvent::Timer) + if (label->windowFlags() & Qt::ToolTip && event->type() == QEvent::Timer) { return true; + } } if (isVisible() && watched == textEdit->viewport()) { - if (event->type() == QEvent::MouseButtonPress) + if (event->type() == QEvent::MouseButtonPress) { hide(); + } } else if (isVisible() && watched == textEdit) { if (event->type() == QEvent::KeyPress) { @@ -648,32 +689,34 @@ bool CallTipsList::eventFilter(QObject * watched, QEvent * event) } else if (ke->key() == Qt::Key_Tab) { // enable call completion for activating items - Temporary tmp( this->doCallCompletion, true ); //< previous state restored on scope exit - Q_EMIT itemActivated( currentItem() ); + Temporary tmp(this->doCallCompletion, true); //< previous state restored on + // scope exit + Q_EMIT itemActivated(currentItem()); return true; } else if (this->compKeys.indexOf(ke->key()) > -1) { Q_EMIT itemActivated(currentItem()); return false; } - else if (ke->key() == Qt::Key_Shift || ke->key() == Qt::Key_Control || - ke->key() == Qt::Key_Meta || ke->key() == Qt::Key_Alt || - ke->key() == Qt::Key_AltGr) { + else if (ke->key() == Qt::Key_Shift || ke->key() == Qt::Key_Control + || ke->key() == Qt::Key_Meta || ke->key() == Qt::Key_Alt + || ke->key() == Qt::Key_AltGr) { // filter these meta keys to avoid to call keyboardSearch() return true; } } else if (event->type() == QEvent::KeyRelease) { auto ke = static_cast(event); - if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down || - ke->key() == Qt::Key_PageUp || ke->key() == Qt::Key_PageDown) { - QList items = selectedItems(); + if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down || ke->key() == Qt::Key_PageUp + || ke->key() == Qt::Key_PageDown) { + QList items = selectedItems(); if (!items.isEmpty()) { QPoint p(width(), 0); QString text = items.front()->toolTip(); - if (!text.isEmpty()){ + if (!text.isEmpty()) { QToolTip::showText(mapToGlobal(p), text); - } else { + } + else { QToolTip::showText(p, QString()); } } @@ -681,19 +724,21 @@ bool CallTipsList::eventFilter(QObject * watched, QEvent * event) } } else if (event->type() == QEvent::FocusOut) { - if (!hasFocus()) + if (!hasFocus()) { hide(); + } } } return QListWidget::eventFilter(watched, event); } -void CallTipsList::callTipItemActivated(QListWidgetItem *item) +void CallTipsList::callTipItemActivated(QListWidgetItem* item) { hide(); - if (!item->isSelected()) + if (!item->isSelected()) { return; + } QString text = item->text(); QTextCursor cursor = textEdit->textCursor(); @@ -702,34 +747,37 @@ void CallTipsList::callTipItemActivated(QListWidgetItem *item) QString sel = cursor.selectedText(); if (!sel.isEmpty()) { // in case the cursor moved too far on the right side - const QChar underscore = QLatin1Char('_'); - const QChar ch = sel.at(sel.size()-1); - if (!ch.isLetterOrNumber() && ch != underscore) + const QChar underscore = QLatin1Char('_'); + const QChar ch = sel.at(sel.size() - 1); + if (!ch.isLetterOrNumber() && ch != underscore) { cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor); + } } - cursor.insertText( text ); + cursor.insertText(text); // get CallTip from item's UserRole-data auto callTip = item->data(Qt::UserRole).value(); // if call completion enabled and we've something callable (method or class constructor) ... if (this->doCallCompletion - && (callTip.type == CallTip::Method || callTip.type == CallTip::Class)) - { - cursor.insertText( QLatin1String("()") ); //< just append parenthesis to identifier even inserted. + && (callTip.type == CallTip::Method || callTip.type == CallTip::Class)) { + cursor.insertText(QLatin1String("()")); //< just append parenthesis to identifier even inserted. - /** - * Try to find out if call needs arguments. - * For this we search the description for appropriate hints ... - */ - QRegularExpression argumentMatcher( QRegularExpression::escape( callTip.name ) + QLatin1String(R"(\s*\(\s*\w+.*\))") ); - argumentMatcher.setPatternOptions( QRegularExpression::InvertedGreedinessOption ); //< set regex non-greedy! - if (argumentMatcher.match( callTip.description ).hasMatch()) - { - // if arguments are needed, we just move the cursor one left, to between the parentheses. - cursor.movePosition( QTextCursor::Left, QTextCursor::MoveAnchor, 1 ); - textEdit->setTextCursor( cursor ); - } + /** + * Try to find out if call needs arguments. + * For this we search the description for appropriate hints ... + */ + QRegularExpression argumentMatcher( + QRegularExpression::escape(callTip.name) + QLatin1String(R"(\s*\(\s*\w+.*\))") + ); + argumentMatcher.setPatternOptions( + QRegularExpression::InvertedGreedinessOption + ); //< set regex non-greedy! + if (argumentMatcher.match(callTip.description).hasMatch()) { + // if arguments are needed, we just move the cursor one left, to between the parentheses. + cursor.movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, 1); + textEdit->setTextCursor(cursor); + } } textEdit->ensureCursorVisible(); @@ -739,33 +787,36 @@ void CallTipsList::callTipItemActivated(QListWidgetItem *item) QPoint p(posX, posY); p = textEdit->mapToGlobal(p); - QToolTip::showText( p, callTip.parameter ); + QToolTip::showText(p, callTip.parameter); } QString CallTipsList::stripWhiteSpace(const QString& str) const { QString stripped = str; QStringList lines = str.split(QLatin1String("\n")); - int minspace=std::numeric_limits::max(); - int line=0; + int minspace = std::numeric_limits::max(); + int line = 0; for (QStringList::iterator it = lines.begin(); it != lines.end(); ++it, ++line) { if (it->size() > 0 && line > 0) { int space = 0; - for (int i=0; isize(); i++) { - if ((*it)[i] == QLatin1Char('\t')) + for (int i = 0; i < it->size(); i++) { + if ((*it)[i] == QLatin1Char('\t')) { space++; - else + } + else { break; + } } - if (it->size() > space) + if (it->size() > space) { minspace = std::min(minspace, space); + } } } // remove all leading tabs from each line if (minspace > 0 && minspace < std::numeric_limits::max()) { - int line=0; + int line = 0; QStringList strippedlines; for (QStringList::iterator it = lines.begin(); it != lines.end(); ++it, ++line) { if (line == 0 && !it->isEmpty()) { diff --git a/src/Gui/CallTips.h b/src/Gui/CallTips.h index a94a875847..6ab336f4aa 100644 --- a/src/Gui/CallTips.h +++ b/src/Gui/CallTips.h @@ -28,27 +28,37 @@ class QPlainTextEdit; -namespace Py { +namespace Py +{ class Object; class List; class String; -} -namespace Gui { +} // namespace Py +namespace Gui +{ class CallTip { public: - enum Type {Unknown, Module, Class, Method, Member, Property}; + enum Type + { + Unknown, + Module, + Class, + Method, + Member, + Property + }; QString name; QString description; QString parameter; - Type type{Unknown}; + Type type {Unknown}; }; /** * @author Werner Mayer */ -class CallTipsList : public QListWidget +class CallTipsList: public QListWidget { Q_OBJECT @@ -58,17 +68,17 @@ public: /// Destruction ~CallTipsList() override; - void keyboardSearch (const QString&) override; + void keyboardSearch(const QString&) override; void showTips(const QString&); void validateCursor(); protected: - bool eventFilter(QObject *, QEvent *) override; + bool eventFilter(QObject*, QEvent*) override; void showEvent(QShowEvent*) override; void hideEvent(QHideEvent*) override; private Q_SLOTS: - void callTipItemActivated(QListWidgetItem *item); + void callTipItemActivated(QListWidgetItem* item); private: QString extractContext(const QString&) const; @@ -87,6 +97,6 @@ private: QList compKeys; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_CALLTIPS_H +#endif // GUI_CALLTIPS_H diff --git a/src/Gui/Camera.cpp b/src/Gui/Camera.cpp index 5060e6fdc4..363cc35ea7 100644 --- a/src/Gui/Camera.cpp +++ b/src/Gui/Camera.cpp @@ -39,13 +39,13 @@ SbRotation Camera::bottom() SbRotation Camera::front() { - auto root = sqrtf(2.0)/2.0f; + auto root = sqrtf(2.0) / 2.0f; return {root, 0, 0, root}; } SbRotation Camera::rear() { - auto root = sqrtf(2.0)/2.0f; + auto root = sqrtf(2.0) / 2.0f; return {0, root, root, 0}; } @@ -92,26 +92,26 @@ SbRotation Camera::trimetric() SbRotation Camera::rotation(Camera::Orientation view) { switch (view) { - case Top: - return top(); - case Bottom: - return bottom(); - case Front: - return front(); - case Rear: - return rear(); - case Right: - return right(); - case Left: - return left(); - case Isometric: - return isometric(); - case Dimetric: - return dimetric(); - case Trimetric: - return trimetric(); - default: - return top(); + case Top: + return top(); + case Bottom: + return bottom(); + case Front: + return front(); + case Rear: + return rear(); + case Right: + return right(); + case Left: + return left(); + case Isometric: + return isometric(); + case Dimetric: + return dimetric(); + case Trimetric: + return trimetric(); + default: + return top(); } } diff --git a/src/Gui/Camera.h b/src/Gui/Camera.h index 9e7a733d56..4907b90e19 100644 --- a/src/Gui/Camera.h +++ b/src/Gui/Camera.h @@ -28,12 +28,14 @@ #include #include -namespace Gui { +namespace Gui +{ class GuiExport Camera { public: - enum Orientation { + enum Orientation + { Top, Bottom, Front, @@ -61,6 +63,6 @@ public: static SbRotation convert(const Base::Rotation&); }; -} +} // namespace Gui -#endif // GUI_CAMERA_H +#endif // GUI_CAMERA_H diff --git a/src/Gui/Clipping.h b/src/Gui/Clipping.h index 6b5b0653be..17142e3be1 100644 --- a/src/Gui/Clipping.h +++ b/src/Gui/Clipping.h @@ -27,14 +27,16 @@ #include #include -namespace Gui { +namespace Gui +{ class View3DInventor; -namespace Dialog { +namespace Dialog +{ /** * @author Werner Mayer */ -class GuiExport Clipping : public QDialog +class GuiExport Clipping: public QDialog { Q_OBJECT @@ -70,7 +72,7 @@ private: Private* d; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_CLIPPING_H +#endif // GUI_DIALOG_CLIPPING_H diff --git a/src/Gui/CoinRiftWidget.cpp b/src/Gui/CoinRiftWidget.cpp index 8143395043..90c3acae48 100644 --- a/src/Gui/CoinRiftWidget.cpp +++ b/src/Gui/CoinRiftWidget.cpp @@ -40,20 +40,18 @@ #if BUILD_VR - -#undef max +# undef max - - -CoinRiftWidget::CoinRiftWidget() : QGLWidget() +CoinRiftWidget::CoinRiftWidget() + : QGLWidget() { for (int eye = 0; eye < 2; eye++) { reinterpret_cast(&eyeTexture[eye])->TexId = 0; -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER frameBufferID[eye] = 0; depthBufferID[eye] = 0; -#endif +# endif } // OVR will do the swapping. @@ -65,13 +63,11 @@ CoinRiftWidget::CoinRiftWidget() : QGLWidget() throw; } - if (!ovrHmd_ConfigureTracking (hmd, ovrTrackingCap_Orientation | - ovrTrackingCap_MagYawCorrection | - ovrTrackingCap_Position, - ovrTrackingCap_Orientation | - ovrTrackingCap_MagYawCorrection | - ovrTrackingCap_Position - )) { // Capabilities we require. + if (!ovrHmd_ConfigureTracking( + hmd, + ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, + ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position + )) { // Capabilities we require. qDebug() << "Could not start Rift motion sensor."; throw; } @@ -79,37 +75,41 @@ CoinRiftWidget::CoinRiftWidget() : QGLWidget() resize(hmd->Resolution.w, hmd->Resolution.h); // Configure stereo settings. - ovrSizei recommenedTex0Size = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, - hmd->DefaultEyeFov[0], 1.0f); - ovrSizei recommenedTex1Size = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, - hmd->DefaultEyeFov[1], 1.0f); + ovrSizei recommenedTex0Size + = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1.0f); + ovrSizei recommenedTex1Size + = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1.0f); -#ifdef USE_SO_OFFSCREEN_RENDERER - renderer = new SoOffscreenRenderer(SbViewportRegion(std::max(recommenedTex0Size.w, recommenedTex0Size.w), - std::max(recommenedTex1Size.h, recommenedTex1Size.h))); +# ifdef USE_SO_OFFSCREEN_RENDERER + renderer = new SoOffscreenRenderer(SbViewportRegion( + std::max(recommenedTex0Size.w, recommenedTex0Size.w), + std::max(recommenedTex1Size.h, recommenedTex1Size.h) + )); renderer->setComponents(SoOffscreenRenderer::RGB_TRANSPARENCY); BackgroundColor = SbColor(.0f, .0f, .8f); renderer->setBackgroundColor(BackgroundColor); -#endif -#ifdef USE_FRAMEBUFFER +# endif +# ifdef USE_FRAMEBUFFER m_sceneManager = new SoSceneManager(); - m_sceneManager->setViewportRegion(SbViewportRegion(std::max(recommenedTex0Size.w, recommenedTex0Size.w), - std::max(recommenedTex1Size.h, recommenedTex1Size.h))); + m_sceneManager->setViewportRegion(SbViewportRegion( + std::max(recommenedTex0Size.w, recommenedTex0Size.w), + std::max(recommenedTex1Size.h, recommenedTex1Size.h) + )); m_sceneManager->setBackgroundColor(SbColor(.0f, .0f, .8f)); -#endif +# endif basePosition = SbVec3f(0.0f, 0.0f, -2.0f); // light handling - SoDirectionalLight *light = new SoDirectionalLight(); - light->direction.setValue(1,-1,-1); + SoDirectionalLight* light = new SoDirectionalLight(); + light->direction.setValue(1, -1, -1); - SoDirectionalLight *light2 = new SoDirectionalLight(); - light2->direction.setValue(-1,-1,-1); + SoDirectionalLight* light2 = new SoDirectionalLight(); + light2->direction.setValue(-1, -1, -1); light2->intensity.setValue(0.6); - light2->color.setValue(0.8,0.8,1); + light2->color.setValue(0.8, 0.8, 1); - scene = new SoSeparator(0); // Placeholder. + scene = new SoSeparator(0); // Placeholder. for (int eye = 0; eye < 2; eye++) { rootScene[eye] = new SoSeparator(); rootScene[eye]->ref(); @@ -128,55 +128,62 @@ CoinRiftWidget::CoinRiftWidget() : QGLWidget() eyeRenderDesc[1].Eye = ovrEye_Right; eyeRenderDesc[0].Fov = hmd->DefaultEyeFov[0]; eyeRenderDesc[1].Fov = hmd->DefaultEyeFov[1]; -#ifdef USE_SO_OFFSCREEN_RENDERER - eyeTexture[0].Header.TextureSize.w = renderer->getViewportRegion().getViewportSizePixels().getValue()[0]; - eyeTexture[0].Header.TextureSize.h = renderer->getViewportRegion().getViewportSizePixels().getValue()[1]; +# ifdef USE_SO_OFFSCREEN_RENDERER + eyeTexture[0].Header.TextureSize.w + = renderer->getViewportRegion().getViewportSizePixels().getValue()[0]; + eyeTexture[0].Header.TextureSize.h + = renderer->getViewportRegion().getViewportSizePixels().getValue()[1]; eyeTexture[1].Header.TextureSize = eyeTexture[0].Header.TextureSize; -#endif -#ifdef USE_FRAMEBUFFER +# endif +# ifdef USE_FRAMEBUFFER eyeTexture[0].Header.TextureSize = recommenedTex0Size; eyeTexture[1].Header.TextureSize = recommenedTex1Size; -#endif +# endif eyeTexture[0].Header.RenderViewport.Pos.x = 0; eyeTexture[0].Header.RenderViewport.Pos.y = 0; eyeTexture[0].Header.RenderViewport.Size = eyeTexture[0].Header.TextureSize; eyeTexture[1].Header.RenderViewport.Pos = eyeTexture[0].Header.RenderViewport.Pos; eyeTexture[1].Header.RenderViewport.Size = eyeTexture[1].Header.TextureSize; - const int backBufferMultisample = 0; // TODO This is a guess? + const int backBufferMultisample = 0; // TODO This is a guess? ovrGLConfig cfg; cfg.OGL.Header.API = ovrRenderAPI_OpenGL; cfg.OGL.Header.RTSize = hmd->Resolution; cfg.OGL.Header.Multisample = backBufferMultisample; cfg.OGL.Window = reinterpret_cast(winId()); makeCurrent(); - //cfg.OGL.WglContext = wglGetCurrentContext(); // http://stackoverflow.com/questions/17532033/qglwidget-get-gl-contextes-for-windows + // cfg.OGL.WglContext = wglGetCurrentContext(); // + // http://stackoverflow.com/questions/17532033/qglwidget-get-gl-contextes-for-windows cfg.OGL.DC = wglGetCurrentDC(); qDebug() << "Window:" << cfg.OGL.Window; - //qDebug() << "Context:" << cfg.OGL.WglContext; + // qDebug() << "Context:" << cfg.OGL.WglContext; qDebug() << "DC:" << cfg.OGL.DC; int DistortionCaps = 0; DistortionCaps |= ovrDistortionCap_Chromatic; -// DistortionCaps |= ovrDistortionCap_TimeWarp; // Produces black screen... + // DistortionCaps |= ovrDistortionCap_TimeWarp; // Produces black screen... DistortionCaps |= ovrDistortionCap_Vignette; DistortionCaps |= ovrDistortionCap_HqDistortion; - bool VSyncEnabled(false); // TODO This is a guess. - if (!ovrHmd_ConfigureRendering( hmd, - &cfg.Config, - /*(VSyncEnabled ? 0 : ovrHmdCap_NoVSync),*/ - DistortionCaps, - hmd->DefaultEyeFov,//eyes, - eyeRenderDesc)) { + bool VSyncEnabled(false); // TODO This is a guess. + if (!ovrHmd_ConfigureRendering( + hmd, + &cfg.Config, + /*(VSyncEnabled ? 0 : ovrHmdCap_NoVSync),*/ + DistortionCaps, + hmd->DefaultEyeFov, // eyes, + eyeRenderDesc + )) { qDebug() << "Could not configure OVR rendering."; throw; } static const float nearPlane = 0.01; for (int eye = 0; eye < 2; eye++) { - camera[eye]->aspectRatio.setValue((eyeRenderDesc[eye].Fov.LeftTan + eyeRenderDesc[eye].Fov.RightTan) / - (eyeRenderDesc[eye].Fov.UpTan + eyeRenderDesc[eye].Fov.DownTan)); + camera[eye]->aspectRatio.setValue( + (eyeRenderDesc[eye].Fov.LeftTan + eyeRenderDesc[eye].Fov.RightTan) + / (eyeRenderDesc[eye].Fov.UpTan + eyeRenderDesc[eye].Fov.DownTan) + ); camera[eye]->nearDistance.setValue(nearPlane); camera[eye]->farDistance.setValue(10000.0f); camera[eye]->left.setValue(-eyeRenderDesc[eye].Fov.LeftTan * nearPlane); @@ -189,41 +196,41 @@ CoinRiftWidget::CoinRiftWidget() : QGLWidget() CoinRiftWidget::~CoinRiftWidget() { -#ifdef USE_SO_OFFSCREEN_RENDERER +# ifdef USE_SO_OFFSCREEN_RENDERER delete renderer; -#endif +# endif for (int eye = 0; eye < 2; eye++) { rootScene[eye]->unref(); - ovrGLTextureData *texData = reinterpret_cast(&eyeTexture[eye]); + ovrGLTextureData* texData = reinterpret_cast(&eyeTexture[eye]); if (texData->TexId) { glDeleteTextures(1, &texData->TexId); texData->TexId = 0; } -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER if (frameBufferID[eye] != 0) { -// OVR::CAPI::GL::glDeleteFramebuffersExt(1, &frameBufferID[eye]); // TODO + // OVR::CAPI::GL::glDeleteFramebuffersExt(1, &frameBufferID[eye]); // TODO frameBufferID[eye] = 0; } if (depthBufferID[eye] != 0) { -// OVR::CAPI::GL::glDeleteRenderbuffersExt(1, &depthBufferID[eye]); // TODO + // OVR::CAPI::GL::glDeleteRenderbuffersExt(1, &depthBufferID[eye]); // TODO depthBufferID[eye] = 0; } -#endif +# endif } scene = 0; - //ovrHmd_StopSensor(hmd); + // ovrHmd_StopSensor(hmd); ovrHmd_Destroy(hmd); } -void CoinRiftWidget::setBackgroundColor(const SbColor &Col) +void CoinRiftWidget::setBackgroundColor(const SbColor& Col) { BackgroundColor = Col; renderer->setBackgroundColor(BackgroundColor); } -void CoinRiftWidget::setSceneGraph(SoNode *sceneGraph) +void CoinRiftWidget::setSceneGraph(SoNode* sceneGraph) { rootScene[0]->replaceChild(scene, sceneGraph); rootScene[1]->replaceChild(scene, sceneGraph); @@ -231,7 +238,8 @@ void CoinRiftWidget::setSceneGraph(SoNode *sceneGraph) } -void CoinRiftWidget::resizeGL(int width, int height) { +void CoinRiftWidget::resizeGL(int width, int height) +{ int side = qMin(width, height); glViewport((width - side) / 2, (height - side) / 2, side, side); @@ -245,7 +253,7 @@ void CoinRiftWidget::initializeGL() { makeCurrent(); // Infer hardware capabilities. -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER OVR::CAPI::GL::InitGLExtensions(); if (OVR::CAPI::GL::glBindFramebuffer == NULL) { qDebug() << "No GL extensions found."; @@ -255,29 +263,33 @@ void CoinRiftWidget::initializeGL() // Store old framebuffer. GLint oldfb; glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb); -#endif +# endif // Create rendering target textures. glEnable(GL_TEXTURE_2D); for (int eye = 0; eye < 2; eye++) { -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER OVR::CAPI::GL::glGenFramebuffers(1, &frameBufferID[eye]); OVR::CAPI::GL::glBindFramebuffer(GL_FRAMEBUFFER_EXT, frameBufferID[eye]); // Create the render buffer. // TODO: need to check for OpenGl 3 or higher and load the functions JR 2014 - /*OVR::CAPI::GL::*/glGenRenderbuffers(1, &depthBufferID[eye]); - /*OVR::CAPI::GL::*/glBindRenderbuffer(GL_RENDERBUFFER_EXT, depthBufferID[eye]); - /*OVR::CAPI::GL::*/glRenderbufferStorage(GL_RENDERBUFFER_EXT, - GL_DEPTH_COMPONENT16, - eyeTexture[eye].Header.TextureSize.w, - eyeTexture[eye].Header.TextureSize.h); + /*OVR::CAPI::GL::*/ glGenRenderbuffers(1, &depthBufferID[eye]); + /*OVR::CAPI::GL::*/ glBindRenderbuffer(GL_RENDERBUFFER_EXT, depthBufferID[eye]); + /*OVR::CAPI::GL::*/ glRenderbufferStorage( + GL_RENDERBUFFER_EXT, + GL_DEPTH_COMPONENT16, + eyeTexture[eye].Header.TextureSize.w, + eyeTexture[eye].Header.TextureSize.h + ); // Attach renderbuffer to framebuffer. - OVR::CAPI::GL::glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, - GL_DEPTH_ATTACHMENT_EXT, - GL_RENDERBUFFER_EXT, - depthBufferID[eye]); -#endif - ovrGLTextureData *texData = reinterpret_cast(&eyeTexture[eye]); + OVR::CAPI::GL::glFramebufferRenderbuffer( + GL_FRAMEBUFFER_EXT, + GL_DEPTH_ATTACHMENT_EXT, + GL_RENDERBUFFER_EXT, + depthBufferID[eye] + ); +# endif + ovrGLTextureData* texData = reinterpret_cast(&eyeTexture[eye]); texData->Header.API = ovrRenderAPI_OpenGL; texData->Header.TextureSize = eyeTexture[eye].Header.TextureSize; texData->Header.RenderViewport = eyeTexture[eye].Header.RenderViewport; @@ -285,31 +297,45 @@ void CoinRiftWidget::initializeGL() glBindTexture(GL_TEXTURE_2D, texData->TexId); Q_ASSERT(!glGetError()); // Allocate storage for the texture. - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, eyeTexture[eye].Header.TextureSize.w, eyeTexture[eye].Header.TextureSize.h, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA, + eyeTexture[eye].Header.TextureSize.w, + eyeTexture[eye].Header.TextureSize.h, + 0, + GL_BGRA, + GL_UNSIGNED_BYTE, + NULL + ); + // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); Q_ASSERT(!glGetError()); -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER // Attach texture to framebuffer color object. - OVR::CAPI::GL::glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, - GL_COLOR_ATTACHMENT0_EXT, - GL_TEXTURE_2D, texData->TexId, 0); - if (OVR::CAPI::GL::glCheckFramebufferStatus(GL_FRAMEBUFFER) != - GL_FRAMEBUFFER_COMPLETE) + OVR::CAPI::GL::glFramebufferTexture2D( + GL_FRAMEBUFFER_EXT, + GL_COLOR_ATTACHMENT0_EXT, + GL_TEXTURE_2D, + texData->TexId, + 0 + ); + if (OVR::CAPI::GL::glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { qDebug() << "ERROR: FrameBuffer is not operational!"; -#endif + } +# endif } glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER // Continue rendering to the original frame buffer (likely 0, the onscreen buffer). OVR::CAPI::GL::glBindFramebuffer(GL_FRAMEBUFFER_EXT, oldfb); -#endif +# endif doneCurrent(); } @@ -334,50 +360,62 @@ void CoinRiftWidget::paintGL() eyePose[eye] = ovrHmd_GetEyePose(hmd, eye); - SbRotation riftOrientation( eyePose[eye].Orientation.x, - eyePose[eye].Orientation.y, - eyePose[eye].Orientation.z, - eyePose[eye].Orientation.w); + SbRotation riftOrientation( + eyePose[eye].Orientation.x, + eyePose[eye].Orientation.y, + eyePose[eye].Orientation.z, + eyePose[eye].Orientation.w + ); camera[eye]->orientation.setValue(riftOrientation); - SbVec3f riftPosition = SbVec3f(eyePose[eye].Position.x, - eyePose[eye].Position.y, - eyePose[eye].Position.z); + SbVec3f riftPosition + = SbVec3f(eyePose[eye].Position.x, eyePose[eye].Position.y, eyePose[eye].Position.z); - //SbVec3f originalPosition(camera[eye]->position.getValue()); - SbVec3f viewAdjust(eyeRenderDesc[eye].ViewAdjust.x, - eyeRenderDesc[eye].ViewAdjust.y, - eyeRenderDesc[eye].ViewAdjust.z); + // SbVec3f originalPosition(camera[eye]->position.getValue()); + SbVec3f viewAdjust( + eyeRenderDesc[eye].ViewAdjust.x, + eyeRenderDesc[eye].ViewAdjust.y, + eyeRenderDesc[eye].ViewAdjust.z + ); - riftOrientation.multVec(viewAdjust,viewAdjust); + riftOrientation.multVec(viewAdjust, viewAdjust); camera[eye]->position.setValue(basePosition - viewAdjust + riftPosition); - //Base::Console().log("Eye(%d) Pos: %f, %f, %f ViewAdjust: %f, %f, %f \n",eye, eyePose[eye].Position.x, - // eyePose[eye].Position.y, - // eyePose[eye].Position.z, - // eyeRenderDesc[eye].ViewAdjust.x, - // eyeRenderDesc[eye].ViewAdjust.y, - // eyeRenderDesc[eye].ViewAdjust.z); + // Base::Console().log("Eye(%d) Pos: %f, %f, %f ViewAdjust: %f, %f, %f \n",eye, + // eyePose[eye].Position.x, + // eyePose[eye].Position.y, + // eyePose[eye].Position.z, + // eyeRenderDesc[eye].ViewAdjust.x, + // eyeRenderDesc[eye].ViewAdjust.y, + // eyeRenderDesc[eye].ViewAdjust.z); -#ifdef USE_SO_OFFSCREEN_RENDERER - ovrGLTextureData *texData = reinterpret_cast(&eyeTexture[eye]); +# ifdef USE_SO_OFFSCREEN_RENDERER + ovrGLTextureData* texData = reinterpret_cast(&eyeTexture[eye]); glBindTexture(GL_TEXTURE_2D, texData->TexId); renderer->render(rootScene[eye]); Q_ASSERT(!glGetError()); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, - eyeTexture[eye].Header.TextureSize.w, - eyeTexture[eye].Header.TextureSize.h, - 0, GL_RGBA /*GL_BGRA*/, GL_UNSIGNED_BYTE, renderer->getBuffer()); + glTexImage2D( + GL_TEXTURE_2D, + 0, + GL_RGBA, + eyeTexture[eye].Header.TextureSize.w, + eyeTexture[eye].Header.TextureSize.h, + 0, + GL_RGBA /*GL_BGRA*/, + GL_UNSIGNED_BYTE, + renderer->getBuffer() + ); Q_ASSERT(!glGetError()); glBindTexture(GL_TEXTURE_2D, 0); -#endif -#ifdef USE_FRAMEBUFFER +# endif +# ifdef USE_FRAMEBUFFER // Clear state pollution from OVR SDK. - glBindTexture(GL_TEXTURE_2D, 0); // You need this, at least if (hmdDesc.DistortionCaps & ovrDistortion_Chromatic). - OVR::CAPI::GL::glUseProgram(0); // You need this even more. + glBindTexture(GL_TEXTURE_2D, 0); // You need this, at least if (hmdDesc.DistortionCaps & + // ovrDistortion_Chromatic). + OVR::CAPI::GL::glUseProgram(0); // You need this even more. GLint oldfb; glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &oldfb); @@ -385,16 +423,15 @@ void CoinRiftWidget::paintGL() OVR::CAPI::GL::glBindFramebuffer(GL_FRAMEBUFFER_EXT, frameBufferID[eye]); m_sceneManager->setSceneGraph(rootScene[eye]); -// m_sceneManager->setCamera(camera[eye]); // SoSceneManager does this implicitly. + // m_sceneManager->setCamera(camera[eye]); // SoSceneManager does this implicitly. m_sceneManager->render(); // Continue rendering to the original frame buffer (likely 0, the onscreen buffer). OVR::CAPI::GL::glBindFramebuffer(GL_FRAMEBUFFER_EXT, oldfb); Q_ASSERT(!glGetError()); -#endif - - //camera[eye]->position.setValue(originalPosition); +# endif + // camera[eye]->position.setValue(originalPosition); } // Submit the texture for distortion. @@ -403,7 +440,7 @@ void CoinRiftWidget::paintGL() // Swap buffers. glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); - //ovrHmd_EndFrame(hmd); + // ovrHmd_EndFrame(hmd); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClearDepth(1.0); @@ -416,43 +453,41 @@ void CoinRiftWidget::handlingSafetyWarning(void) // Health and Safety Warning display state. ovrHSWDisplayState hswDisplayState; ovrHmd_GetHSWDisplayState(hmd, &hswDisplayState); - if (hswDisplayState.Displayed) - { + if (hswDisplayState.Displayed) { // Dismiss the warning if the user pressed the appropriate key or if the user // is tapping the side of the HMD. // If the user has requested to dismiss the warning via keyboard or controller input... - //if (Util_GetAndResetHSWDismissedState()) - ovrHmd_DismissHSWDisplay(hmd); - //else + // if (Util_GetAndResetHSWDismissedState()) + ovrHmd_DismissHSWDisplay(hmd); + // else //{ - // // Detect a moderate tap on the side of the HMD. - // ovrTrackingState ts = ovrHmd_GetTrackingState(hmd, ovr_GetTimeInSeconds()); - // if (ts.StatusFlags & ovrStatus_OrientationTracked) - // { - // const OVR::Vector3f v(ts.RawSensorData.Accelerometer.x, - // ts.RawSensorData.Accelerometer.y, - // ts.RawSensorData.Accelerometer.z); - // // Arbitrary value and representing moderate tap on the side of the DK2 Rift. - // if (v.LengthSq() > 250.f) - // ovrHmd_DismissHSWDisplay(hmd); - // } - //} + // // Detect a moderate tap on the side of the HMD. + // ovrTrackingState ts = ovrHmd_GetTrackingState(hmd, ovr_GetTimeInSeconds()); + // if (ts.StatusFlags & ovrStatus_OrientationTracked) + // { + // const OVR::Vector3f v(ts.RawSensorData.Accelerometer.x, + // ts.RawSensorData.Accelerometer.y, + // ts.RawSensorData.Accelerometer.z); + // // Arbitrary value and representing moderate tap on the side of the DK2 Rift. + // if (v.LengthSq() > 250.f) + // ovrHmd_DismissHSWDisplay(hmd); + // } + // } } - } -#ifdef BUILD_RIFT_TEST_MAIN +# ifdef BUILD_RIFT_TEST_MAIN -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { SoDB::init(); QApplication app(argc, argv); qAddPostRoutine(cleanup); - // Moved here because of https://developer.oculusvr.com/forums/viewtopic.php?f=17&t=7915&p=108503#p108503 - // Init libovr. + // Moved here because of + // https://developer.oculusvr.com/forums/viewtopic.php?f=17&t=7915&p=108503#p108503 Init libovr. if (!ovr_Initialize()) { qDebug() << "Could not initialize Oculus SDK."; exit(1); @@ -462,7 +497,7 @@ int main(int argc, char *argv[]) window.show(); // An example scene. - static const char * inlineSceneGraph[] = { + static const char* inlineSceneGraph[] = { "#Inventor V2.1 ascii\n", "\n", "Separator {\n", @@ -502,6 +537,6 @@ int main(int argc, char *argv[]) return app.exec(); } -#endif //BUILD_RIFT_TEST_MAIN +# endif // BUILD_RIFT_TEST_MAIN -#endif //BUILD_VR +#endif // BUILD_VR diff --git a/src/Gui/CoinRiftWidget.h b/src/Gui/CoinRiftWidget.h index 2dd1880d85..baa2d379ba 100644 --- a/src/Gui/CoinRiftWidget.h +++ b/src/Gui/CoinRiftWidget.h @@ -37,67 +37,71 @@ #if BUILD_VR // defines which method to use to render -#define USE_SO_OFFSCREEN_RENDERER +# define USE_SO_OFFSCREEN_RENDERER -#ifdef USE_SO_OFFSCREEN_RENDERER -# ifdef USE_FRAMEBUFFER -# error "Mutually exclusive options defined." +# ifdef USE_SO_OFFSCREEN_RENDERER +# ifdef USE_FRAMEBUFFER +# error "Mutually exclusive options defined." +# endif # endif -#endif -#include -#include -#include -#include -#include -#include -#include -#ifdef USE_SO_OFFSCREEN_RENDERER -# include -#endif -#ifdef USE_FRAMEBUFFER -# include -#endif -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# ifdef USE_SO_OFFSCREEN_RENDERER +# include +# endif +# ifdef USE_FRAMEBUFFER +# include +# endif +# include +# include +# include -#include -#include -#include -#include <../Src/OVR_CAPI_GL.h> -#include <../Src/CAPI/GL/CAPI_GL_Util.h> // For framebuffer functions. +# include +# include +# include +# include <../Src/OVR_CAPI_GL.h> +# include <../Src/CAPI/GL/CAPI_GL_Util.h> // For framebuffer functions. - -class CoinRiftWidget : public QGLWidget +class CoinRiftWidget: public QGLWidget { ovrHmd hmd; ovrEyeRenderDesc eyeRenderDesc[2]; ovrTexture eyeTexture[2]; -#ifdef USE_FRAMEBUFFER +# ifdef USE_FRAMEBUFFER GLuint frameBufferID[2], depthBufferID[2]; - // A SoSceneManager has a SoRenderManager to do the rendering -- should we not use SoRenderManager instead? - // We are probably not that interested in events. SoSceneManager::setSceneGraph() searches for the camera - // and sets it in SoRenderManager, but its is actually only used for built-in stereo rendering. + // A SoSceneManager has a SoRenderManager to do the rendering -- should we not use + // SoRenderManager instead? We are probably not that interested in events. + // SoSceneManager::setSceneGraph() searches for the camera and sets it in SoRenderManager, but + // its is actually only used for built-in stereo rendering. // FIXME: We should probably eliminate that search... - SoSceneManager *m_sceneManager; -#endif -#ifdef USE_SO_OFFSCREEN_RENDERER - SoOffscreenRenderer *renderer; -#endif - SoSeparator *rootScene[2]; - SoFrustumCamera *camera[2]; - SoNode *scene; + SoSceneManager* m_sceneManager; +# endif +# ifdef USE_SO_OFFSCREEN_RENDERER + SoOffscreenRenderer* renderer; +# endif + SoSeparator* rootScene[2]; + SoFrustumCamera* camera[2]; + SoNode* scene; + public: explicit CoinRiftWidget(); ~CoinRiftWidget(); - virtual void setSceneGraph(SoNode *sceneGraph); - void setBase(const SbVec3f &pos){basePosition=pos;} - void setBackgroundColor(const SbColor &Col); + virtual void setSceneGraph(SoNode* sceneGraph); + void setBase(const SbVec3f& pos) + { + basePosition = pos; + } + void setBackgroundColor(const SbColor& Col); - SbVec3f basePosition; + SbVec3f basePosition; SbRotation baseOrientation; protected: @@ -107,10 +111,10 @@ protected: void resizeGL(int width, int height); SbColor BackgroundColor; - SoTranslation *lightTranslation; + SoTranslation* lightTranslation; }; -#endif //BUILD_VR +#endif // BUILD_VR -#endif // GUI_CoinRiftWidget +#endif // GUI_CoinRiftWidget diff --git a/src/Gui/ComboLinks.cpp b/src/Gui/ComboLinks.cpp index 23aea6c42b..29a6b30281 100644 --- a/src/Gui/ComboLinks.cpp +++ b/src/Gui/ComboLinks.cpp @@ -30,181 +30,191 @@ #include #include -namespace Gui { +namespace Gui +{ - ComboLinks::ComboLinks(QComboBox* combo) - : combo(combo) - { - if (combo) { - combo->clear(); +ComboLinks::ComboLinks(QComboBox* combo) + : combo(combo) +{ + if (combo) { + combo->clear(); + } +} + +ComboLinks::~ComboLinks() +{ + clear(); // Deletes owned pointers in linksInList +} + +void ComboLinks::setCombo(QComboBox* combobox) +{ + clear(); // Clear old state if any + combo = combobox; + if (combo) { + combo->clear(); + } +} + +int ComboLinks::addLink(const App::PropertyLinkSub& lnk, const QString& itemText, int userData) +{ + if (!combo) { + return -1; + } + int newIndex = combo->count(); + int finalUserData = (userData == -1) ? newIndex : userData; + + // Store link internally (create a copy) + auto* newLink = new App::PropertyLinkSub(); + newLink->Paste(lnk); + linksInList.push_back(newLink); + + // Add to combo box + combo->addItem(itemText, QVariant(finalUserData)); + + // Track document context from the first valid object link + if (!doc && newLink->getValue()) { + doc = newLink->getValue()->getDocument(); + } + return newIndex; +} + +int ComboLinks::addLink( + App::DocumentObject* linkObj, + const std::string& linkSubname, + const QString& itemText, + int userData +) +{ + App::PropertyLinkSub lnk; + std::vector sub = {linkSubname}; + lnk.setValue(linkObj, sub); + return addLink(lnk, itemText, userData); +} + +int ComboLinks::addLinkBefore( + const App::PropertyLinkSub& lnk, + const QString& itemText, + int targetUserData, + int userData +) +{ + if (!combo) { + return -1; + } + + int insertPos = -1; + for (int i = 0; i < combo->count(); ++i) { + if (combo->itemData(i).toInt() == targetUserData) { + insertPos = i; + break; } } - ComboLinks::~ComboLinks() - { - clear(); // Deletes owned pointers in linksInList + // Store link internally (create a copy) + auto* newLink = new App::PropertyLinkSub(); + newLink->Paste(lnk); + + int finalUserData = (userData == -1) ? ((insertPos == -1) ? count() : insertPos) : userData; + + if (insertPos != -1) { + linksInList.insert(linksInList.begin() + insertPos, newLink); + combo->insertItem(insertPos, itemText, QVariant(finalUserData)); } - - void ComboLinks::setCombo(QComboBox* combobox) - { - clear(); // Clear old state if any - combo = combobox; - if (combo) { - combo->clear(); - } - } - - int ComboLinks::addLink(const App::PropertyLinkSub& lnk, const QString& itemText, int userData) - { - if (!combo) { - return -1; - } - int newIndex = combo->count(); - int finalUserData = (userData == -1) ? newIndex : userData; - - // Store link internally (create a copy) - auto* newLink = new App::PropertyLinkSub(); - newLink->Paste(lnk); + else { + // Target not found, append to end + insertPos = combo->count(); linksInList.push_back(newLink); - - // Add to combo box combo->addItem(itemText, QVariant(finalUserData)); - - // Track document context from the first valid object link - if (!doc && newLink->getValue()) { - doc = newLink->getValue()->getDocument(); - } - return newIndex; } - int ComboLinks::addLink(App::DocumentObject* linkObj, const std::string& linkSubname, const QString& itemText, int userData) - { - App::PropertyLinkSub lnk; - std::vector sub = { linkSubname }; - lnk.setValue(linkObj, sub); - return addLink(lnk, itemText, userData); - } - - int ComboLinks::addLinkBefore(const App::PropertyLinkSub& lnk, const QString& itemText, int targetUserData, int userData) - { - if (!combo) { - return -1; - } - - int insertPos = -1; - for (int i = 0; i < combo->count(); ++i) { - if (combo->itemData(i).toInt() == targetUserData) { - insertPos = i; - break; + // Update user data for subsequent items if default (-1) was used and inserting + if (userData == -1 && insertPos != -1 && insertPos < count() - 1) { + for (int i = insertPos + 1; i < count(); ++i) { + if (combo->itemData(i).toInt() == i - 1) { // Check if it was using default index + combo->setItemData(i, QVariant(i)); } } - - // Store link internally (create a copy) - auto* newLink = new App::PropertyLinkSub(); - newLink->Paste(lnk); - - int finalUserData = (userData == -1) ? ((insertPos == -1) ? count() : insertPos) : userData; - - if (insertPos != -1) { - linksInList.insert(linksInList.begin() + insertPos, newLink); - combo->insertItem(insertPos, itemText, QVariant(finalUserData)); - } - else { - // Target not found, append to end - insertPos = combo->count(); - linksInList.push_back(newLink); - combo->addItem(itemText, QVariant(finalUserData)); - } - - // Update user data for subsequent items if default (-1) was used and inserting - if (userData == -1 && insertPos != -1 && insertPos < count() - 1) { - for (int i = insertPos + 1; i < count(); ++i) { - if (combo->itemData(i).toInt() == i - 1) { // Check if it was using default index - combo->setItemData(i, QVariant(i)); - } - } - } - - - // Track document context - if (!doc && newLink->getValue()) { - doc = newLink->getValue()->getDocument(); - } - return insertPos; } - void ComboLinks::clear() - { - if (combo) { - // Block signals while clearing to prevent issues if connected elsewhere + // Track document context + if (!doc && newLink->getValue()) { + doc = newLink->getValue()->getDocument(); + } + return insertPos; +} + + +void ComboLinks::clear() +{ + if (combo) { + // Block signals while clearing to prevent issues if connected elsewhere + QSignalBlocker blocker(combo); + combo->clear(); + } + for (App::PropertyLinkSub* linkPtr : linksInList) { + delete linkPtr; // Delete the objects pointed to + } + linksInList.clear(); // Clear the vector itself + doc = nullptr; // Reset document context +} + +App::PropertyLinkSub& ComboLinks::getLink(int index) const +{ + if (index < 0 || static_cast(index) >= linksInList.size()) { + throw Base::IndexError("ComboLinks::getLink: Index out of range"); + } + App::PropertyLinkSub* linkPtr = linksInList[static_cast(index)]; + // Perform validity check only if we have a document context and a linked object + if (doc && linkPtr->getValue() && !(doc->isIn(linkPtr->getValue()))) { + throw Base::ValueError("Linked object is not in the document; it may have been deleted"); + } + return *linkPtr; +} + +App::PropertyLinkSub& ComboLinks::getCurrentLink() const +{ + assert(combo); + return getLink(combo->currentIndex()); +} + +int ComboLinks::getUserData(int index) const +{ + if (!combo || index < 0 || index >= combo->count()) { + return -1; // Indicate invalid index or no combo + } + return combo->itemData(index).toInt(); +} + +int ComboLinks::getCurrentUserData() const +{ + if (!combo) { + return -1; + } + return combo->currentData().toInt(); +} + + +int ComboLinks::setCurrentLink(const App::PropertyLinkSub& lnk) +{ + if (!combo) { + return -1; + } + for (size_t i = 0; i < linksInList.size(); ++i) { + const App::PropertyLinkSub* it = linksInList[i]; + // Compare object pointer and sub-values vector + if (lnk.getValue() == it->getValue() && lnk.getSubValues() == it->getSubValues()) { QSignalBlocker blocker(combo); - combo->clear(); + combo->setCurrentIndex(static_cast(i)); + return static_cast(i); } - for (App::PropertyLinkSub* linkPtr : linksInList) { - delete linkPtr; // Delete the objects pointed to - } - linksInList.clear(); // Clear the vector itself - doc = nullptr; // Reset document context } + return -1; // Not found +} - App::PropertyLinkSub& ComboLinks::getLink(int index) const - { - if (index < 0 || static_cast(index) >= linksInList.size()) { - throw Base::IndexError("ComboLinks::getLink: Index out of range"); - } - App::PropertyLinkSub* linkPtr = linksInList[static_cast(index)]; - // Perform validity check only if we have a document context and a linked object - if (doc && linkPtr->getValue() && !(doc->isIn(linkPtr->getValue()))) { - throw Base::ValueError("Linked object is not in the document; it may have been deleted"); - } - return *linkPtr; - } +int ComboLinks::count() const +{ + return combo ? combo->count() : 0; +} - App::PropertyLinkSub& ComboLinks::getCurrentLink() const - { - assert(combo); - return getLink(combo->currentIndex()); - - } - - int ComboLinks::getUserData(int index) const - { - if (!combo || index < 0 || index >= combo->count()) { - return -1; // Indicate invalid index or no combo - } - return combo->itemData(index).toInt(); - } - - int ComboLinks::getCurrentUserData() const - { - if (!combo) { - return -1; - } - return combo->currentData().toInt(); - } - - - int ComboLinks::setCurrentLink(const App::PropertyLinkSub& lnk) - { - if (!combo) { - return -1; - } - for (size_t i = 0; i < linksInList.size(); ++i) { - const App::PropertyLinkSub* it = linksInList[i]; - // Compare object pointer and sub-values vector - if (lnk.getValue() == it->getValue() && lnk.getSubValues() == it->getSubValues()) { - QSignalBlocker blocker(combo); - combo->setCurrentIndex(static_cast(i)); - return static_cast(i); - } - } - return -1; // Not found - } - - int ComboLinks::count() const - { - return combo ? combo->count() : 0; - } - -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/ComboLinks.h b/src/Gui/ComboLinks.h index b3361fa4d9..c5a30af315 100644 --- a/src/Gui/ComboLinks.h +++ b/src/Gui/ComboLinks.h @@ -33,136 +33,148 @@ // Forward declarations class QComboBox; class QString; -namespace App { - class Document; - class DocumentObject; -} +namespace App +{ +class Document; +class DocumentObject; +} // namespace App -namespace Gui { +namespace Gui +{ + +/** + * @brief The ComboLinks class is a helper class that binds to a QComboBox and + * provides an interface to add App::PropertyLinkSub items, retrieve links, + * and select items by link value. + */ +class GuiExport ComboLinks +{ +public: + /** + * @brief Constructor. Binds to an existing QComboBox. + * @param combo The combo box to manage. It will be cleared upon binding. + * Do not add/remove items directly to/from the combo after binding. + */ + explicit ComboLinks(QComboBox* combo); /** - * @brief The ComboLinks class is a helper class that binds to a QComboBox and - * provides an interface to add App::PropertyLinkSub items, retrieve links, - * and select items by link value. + * @brief Default constructor. Use setCombo() later. */ - class GuiExport ComboLinks - { - public: - /** - * @brief Constructor. Binds to an existing QComboBox. - * @param combo The combo box to manage. It will be cleared upon binding. - * Do not add/remove items directly to/from the combo after binding. - */ - explicit ComboLinks(QComboBox* combo); + ComboLinks() = default; - /** - * @brief Default constructor. Use setCombo() later. - */ - ComboLinks() = default; + /** + * @brief Destructor. Clears internal resources. + */ + ~ComboLinks(); - /** - * @brief Destructor. Clears internal resources. - */ - ~ComboLinks(); + FC_DISABLE_COPY_MOVE(ComboLinks) - FC_DISABLE_COPY_MOVE(ComboLinks) + /** + * @brief Binds the helper to a QComboBox. Clears the combo box. + * @param combo The combo box to manage. + */ + void setCombo(QComboBox* combo); - /** - * @brief Binds the helper to a QComboBox. Clears the combo box. - * @param combo The combo box to manage. - */ - void setCombo(QComboBox* combo); + /** + * @brief Adds an item to the combo box associated with a PropertyLinkSub. + * @param lnk The link data. Can point to nullptr (e.g., for "Select reference..."). + * @param itemText The text to display in the combo box. + * @param userData Optional integer data associated with the item (default: item index). + * @return The index of the added item. + */ + int addLink(const App::PropertyLinkSub& lnk, const QString& itemText, int userData = -1); - /** - * @brief Adds an item to the combo box associated with a PropertyLinkSub. - * @param lnk The link data. Can point to nullptr (e.g., for "Select reference..."). - * @param itemText The text to display in the combo box. - * @param userData Optional integer data associated with the item (default: item index). - * @return The index of the added item. - */ - int addLink(const App::PropertyLinkSub& lnk, const QString& itemText, int userData = -1); - - /** - * @brief Adds an item to the combo box associated with specific object and subname. - * @param linkObj The document object (can be nullptr). - * @param linkSubname The sub-element name (e.g., "Edge1", "Face2", "X_Axis"). - * @param itemText The text to display in the combo box. - * @param userData Optional integer data associated with the item (default: item index). - * @return The index of the added item. - */ - int addLink(App::DocumentObject* linkObj, const std::string& linkSubname, const QString& itemText, int userData = -1); + /** + * @brief Adds an item to the combo box associated with specific object and subname. + * @param linkObj The document object (can be nullptr). + * @param linkSubname The sub-element name (e.g., "Edge1", "Face2", "X_Axis"). + * @param itemText The text to display in the combo box. + * @param userData Optional integer data associated with the item (default: item index). + * @return The index of the added item. + */ + int addLink( + App::DocumentObject* linkObj, + const std::string& linkSubname, + const QString& itemText, + int userData = -1 + ); - /** - * @brief Adds an item *before* an item identified by its user data. - * Useful for inserting custom items before a standard item like "Select reference...". - * If targetUserData is not found, appends to the end. - * - * @param lnk The link data. - * @param itemText The text to display. - * @param targetUserData The user data of the item to insert before. - * @param userData Optional integer data for the new item (default: item index). - * @return The index of the inserted item. - */ - int addLinkBefore(const App::PropertyLinkSub& lnk, const QString& itemText, int targetUserData, int userData = -1); + /** + * @brief Adds an item *before* an item identified by its user data. + * Useful for inserting custom items before a standard item like "Select reference...". + * If targetUserData is not found, appends to the end. + * + * @param lnk The link data. + * @param itemText The text to display. + * @param targetUserData The user data of the item to insert before. + * @param userData Optional integer data for the new item (default: item index). + * @return The index of the inserted item. + */ + int addLinkBefore( + const App::PropertyLinkSub& lnk, + const QString& itemText, + int targetUserData, + int userData = -1 + ); - /** - * @brief Clears all items from the combo box and the internal list. - */ - void clear(); + /** + * @brief Clears all items from the combo box and the internal list. + */ + void clear(); - /** - * @brief Gets the PropertyLinkSub associated with the item at the given index. - * @param index The index of the item. - * @return A reference to the stored PropertyLinkSub. - * @throws Base::IndexError if index is out of range. - * @throws Base::ValueError if the linked object exists but is not in the tracked document. - */ - App::PropertyLinkSub& getLink(int index) const; + /** + * @brief Gets the PropertyLinkSub associated with the item at the given index. + * @param index The index of the item. + * @return A reference to the stored PropertyLinkSub. + * @throws Base::IndexError if index is out of range. + * @throws Base::ValueError if the linked object exists but is not in the tracked document. + */ + App::PropertyLinkSub& getLink(int index) const; - /** - * @brief Gets the PropertyLinkSub associated with the currently selected item. - * @return A reference to the stored PropertyLinkSub. - * @throws Base::IndexError if no item is selected or combo is invalid. - * @throws Base::ValueError if linked object validity check fails. - */ - App::PropertyLinkSub& getCurrentLink() const; + /** + * @brief Gets the PropertyLinkSub associated with the currently selected item. + * @return A reference to the stored PropertyLinkSub. + * @throws Base::IndexError if no item is selected or combo is invalid. + * @throws Base::ValueError if linked object validity check fails. + */ + App::PropertyLinkSub& getCurrentLink() const; - /** - * @brief Gets the user data associated with the item at the given index. - * @param index The index of the item. - * @return The user data. Returns -1 if index is invalid. - */ - int getUserData(int index) const; + /** + * @brief Gets the user data associated with the item at the given index. + * @param index The index of the item. + * @return The user data. Returns -1 if index is invalid. + */ + int getUserData(int index) const; - /** - * @brief Gets the user data associated with the currently selected item. - * @return The user data. Returns -1 if no item is selected or combo is invalid. - */ - int getCurrentUserData() const; + /** + * @brief Gets the user data associated with the currently selected item. + * @return The user data. Returns -1 if no item is selected or combo is invalid. + */ + int getCurrentUserData() const; - /** - * @brief Selects the item whose PropertyLinkSub matches the provided link. - * Blocks combo box signals during the operation. - * @param lnk The link to match. - * @return The index of the selected item, or -1 if no match is found. - */ - int setCurrentLink(const App::PropertyLinkSub& lnk); + /** + * @brief Selects the item whose PropertyLinkSub matches the provided link. + * Blocks combo box signals during the operation. + * @param lnk The link to match. + * @return The index of the selected item, or -1 if no match is found. + */ + int setCurrentLink(const App::PropertyLinkSub& lnk); - /** - * @brief Gets the number of items in the combo box. - * @return Item count. - */ - int count() const; + /** + * @brief Gets the number of items in the combo box. + * @return Item count. + */ + int count() const; - private: - QComboBox* combo = nullptr; - App::Document* doc = nullptr; // Document context for validation - std::vector linksInList; // Owned pointers - }; +private: + QComboBox* combo = nullptr; + App::Document* doc = nullptr; // Document context for validation + std::vector linksInList; // Owned pointers +}; -} // namespace Gui +} // namespace Gui -#endif // GUI_COMBOLINKS_H \ No newline at end of file +#endif // GUI_COMBOLINKS_H diff --git a/src/Gui/ComboView.cpp b/src/Gui/ComboView.cpp index 6d43933a88..f3f8ab7faa 100644 --- a/src/Gui/ComboView.cpp +++ b/src/Gui/ComboView.cpp @@ -20,9 +20,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "ComboView.h" #include "PropertyView.h" @@ -35,21 +35,21 @@ using namespace Gui::DockWnd; /* TRANSLATOR Gui::DockWnd::ComboView */ -ComboView::ComboView(Gui::Document* pcDocument, QWidget *parent) - : DockWindow(pcDocument, parent) +ComboView::ComboView(Gui::Document* pcDocument, QWidget* parent) + : DockWindow(pcDocument, parent) { auto pLayout = new QGridLayout(this); - pLayout->setSpacing( 0 ); - pLayout->setContentsMargins ( 0, 0, 0, 0 ); + pLayout->setSpacing(0); + pLayout->setContentsMargins(0, 0, 0, 0); // tabs to switch between Tree/Properties and TaskPanel auto splitter = new QSplitter(); - pLayout->addWidget( splitter, 0, 0 ); + pLayout->addWidget(splitter, 0, 0); // splitter between tree and property view splitter->setOrientation(Qt::Vertical); - tree = new TreePanel("ComboView", this); + tree = new TreePanel("ComboView", this); splitter->addWidget(tree); // property view diff --git a/src/Gui/ComboView.h b/src/Gui/ComboView.h index b5b0072b23..452b2e2eae 100644 --- a/src/Gui/ComboView.h +++ b/src/Gui/ComboView.h @@ -29,36 +29,42 @@ class QTabWidget; class QTreeView; -namespace App { - class PropertyContainer; +namespace App +{ +class PropertyContainer; } -namespace Gui { - class TreeWidget; - class PropertyView; - class TreePanel; -namespace PropertyEditor { +namespace Gui +{ +class TreeWidget; +class PropertyView; +class TreePanel; +namespace PropertyEditor +{ class EditableListView; class EditableItem; class PropertyEditor; -} // namespace PropertyEditor +} // namespace PropertyEditor -namespace TaskView { +namespace TaskView +{ class TaskView; class TaskDialog; -} // namespace TaskView -} // namespace Gui +} // namespace TaskView +} // namespace Gui -namespace Gui { - class ControlSingleton; -namespace DockWnd { +namespace Gui +{ +class ControlSingleton; +namespace DockWnd +{ /** Combo View - * is a combination of a tree and property view for - * integrated user action. + * is a combination of a tree and property view for + * integrated user action. */ -class GuiExport ComboView : public Gui::DockWindow +class GuiExport ComboView: public Gui::DockWindow { Q_OBJECT @@ -67,24 +73,24 @@ public: * A constructor. * A more elaborate description of the constructor. */ - ComboView(Gui::Document* pcDocument, QWidget *parent=nullptr); + ComboView(Gui::Document* pcDocument, QWidget* parent = nullptr); void setShowModel(bool); /** * A destructor. * A more elaborate description of the destructor. - */ + */ ~ComboView() override; friend class Gui::ControlSingleton; private: - Gui::PropertyView * prop; - Gui::TreePanel * tree; + Gui::PropertyView* prop; + Gui::TreePanel* tree; }; -} // namespace DockWnd -} // namespace Gui +} // namespace DockWnd +} // namespace Gui -#endif // GUI_DOCKWND_SELECTIONVIEW_H +#endif // GUI_DOCKWND_SELECTIONVIEW_H diff --git a/src/Gui/Command.cpp b/src/Gui/Command.cpp index 72f730ea77..437ab10afe 100644 --- a/src/Gui/Command.cpp +++ b/src/Gui/Command.cpp @@ -20,15 +20,15 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -76,27 +76,38 @@ using namespace Gui::DockWnd; \ingroup GUI \brief Structure for registering commands to the FreeCAD system * \section Overview - * In GUI applications many commands can be invoked via a menu item, a toolbar button or an accelerator key. The answer of Qt to master this - * challenge is the class \a QAction. A QAction object can be added to a popup menu or a toolbar and keep the state of the menu item and + * In GUI applications many commands can be invoked via a menu item, a toolbar button or an + accelerator key. The answer of Qt to master this + * challenge is the class \a QAction. A QAction object can be added to a popup menu or a toolbar and + keep the state of the menu item and * the toolbar button synchronized. * - * For example, if the user clicks the menu item of a toggle action then the toolbar button gets also pressed + * For example, if the user clicks the menu item of a toggle action then the toolbar button gets + also pressed * and vice versa. For more details refer to your Qt documentation. * * \section Drawbacks - * Since QAction inherits QObject and emits the \a triggered() signal or \a toggled() signal for toggle actions it is very convenient to connect - * these signals e.g. with slots of your MainWindow class. But this means that for every action an appropriate slot of MainWindow is necessary - * and leads to an inflated MainWindow class. Furthermore, it's simply impossible to provide plugins that may also need special slots -- without + * Since QAction inherits QObject and emits the \a triggered() signal or \a toggled() signal for + toggle actions it is very convenient to connect + * these signals e.g. with slots of your MainWindow class. But this means that for every action an + appropriate slot of MainWindow is necessary + * and leads to an inflated MainWindow class. Furthermore, it's simply impossible to provide plugins + that may also need special slots -- without * changing the MainWindow class. * * \section wayout Way out - * To solve these problems we have introduced the command framework to decouple QAction and MainWindow. The base classes of the framework are - * \a Gui::CommandBase and \a Gui::Action that represent the link between Qt's QAction world and the FreeCAD's command world. + * To solve these problems we have introduced the command framework to decouple QAction and + MainWindow. The base classes of the framework are + * \a Gui::CommandBase and \a Gui::Action that represent the link between Qt's QAction world and the + FreeCAD's command world. * - * The Action class holds a pointer to QAction and CommandBase and acts as a mediator and -- to save memory -- that gets created - * (@ref Gui::CommandBase::createAction()) not before it is added (@ref Gui::Command::addTo()) to a menu or toolbar. + * The Action class holds a pointer to QAction and CommandBase and acts as a mediator and -- to save + memory -- that gets created + * (@ref Gui::CommandBase::createAction()) not before it is added (@ref Gui::Command::addTo()) to a + menu or toolbar. * - * Now, the implementation of the slots of MainWindow can be done in the method \a activated() of subclasses of Command instead. + * Now, the implementation of the slots of MainWindow can be done in the method \a activated() of + subclasses of Command instead. * * For example, the implementation of the "Open file" command can be done as follows. * \code @@ -124,7 +135,8 @@ using namespace Gui::DockWnd; * } * }; * \endcode - * An instance of \a OpenCommand must be created and added to the \ref Gui::CommandManager to make the class known to FreeCAD. + * An instance of \a OpenCommand must be created and added to the \ref Gui::CommandManager to make + the class known to FreeCAD. * To see how menus and toolbars can be built go to the @ref workbench. * * @see Gui::Command, Gui::CommandManager @@ -133,9 +145,11 @@ using namespace Gui::DockWnd; // list of modules already loaded by a command (not issue again for macro cleanness) std::set alreadyLoadedModule; -class StringCache { +class StringCache +{ public: - static const char* New(const char* str) { + static const char* New(const char* str) + { using StringList = std::list; static StringList strings; strings.emplace_back(str); @@ -143,28 +157,34 @@ public: } }; -CommandBase::CommandBase(const char* sMenu, const char* sToolTip, const char* sWhat, - const char* sStatus, const char* sPixmap, const char* sAcc) - : sMenuText(sMenu) - , sToolTipText(sToolTip) - , sWhatsThis(sWhat ? sWhat : sToolTip) - , sStatusTip(sStatus ? sStatus : sToolTip) - , sPixmap(sPixmap) - , sAccel(sAcc) - , _pcAction(nullptr) -{ -} +CommandBase::CommandBase( + const char* sMenu, + const char* sToolTip, + const char* sWhat, + const char* sStatus, + const char* sPixmap, + const char* sAcc +) + : sMenuText(sMenu) + , sToolTipText(sToolTip) + , sWhatsThis(sWhat ? sWhat : sToolTip) + , sStatusTip(sStatus ? sStatus : sToolTip) + , sPixmap(sPixmap) + , sAccel(sAcc) + , _pcAction(nullptr) +{} CommandBase::~CommandBase() { - //Note: The Action object becomes a children of MainWindow which gets destroyed _before_ the - //command manager hence before any command object. So the action pointer is a dangling pointer - //at this state. + // Note: The Action object becomes a children of MainWindow which gets destroyed _before_ the + // command manager hence before any command object. So the action pointer is a dangling pointer + // at this state. // Command can be destroyed before the MainWindow, for example, dynamic // command created (and later deleted) by user for a pie menu. - if (getMainWindow()) + if (getMainWindow()) { delete _pcAction; + } } Action* CommandBase::getAction() const @@ -172,7 +192,7 @@ Action* CommandBase::getAction() const return _pcAction; } -Action * CommandBase::createAction() +Action* CommandBase::createAction() { // does nothing return nullptr; @@ -219,40 +239,46 @@ Command::Command(const char* name) , sName(name) , sHelpUrl(nullptr) { - sAppModule = "FreeCAD"; - sGroup = "Standard"; - eType = AlterDoc | Alter3DView | AlterSelection; - bEnabled = true; - bCanLog = true; + sAppModule = "FreeCAD"; + sGroup = "Standard"; + eType = AlterDoc | Alter3DView | AlterSelection; + bEnabled = true; + bCanLog = true; } Command::~Command() = default; -void Command::setShortcut(const QString &shortcut) +void Command::setShortcut(const QString& shortcut) { - if (_pcAction) + if (_pcAction) { _pcAction->setShortcut(shortcut); + } } QString Command::getShortcut() const { - if (_pcAction) + if (_pcAction) { return _pcAction->shortcut().toString(); + } return ShortcutManager::instance()->getShortcut(getName()); } bool Command::isViewOfType(Base::Type t) const { - Gui::Document *d = getGuiApplication()->activeDocument(); - if (!d) + Gui::Document* d = getGuiApplication()->activeDocument(); + if (!d) { return false; - Gui::BaseView *v = d->getActiveView(); - if (!v) + } + Gui::BaseView* v = d->getActiveView(); + if (!v) { return false; - if (v->isDerivedFrom(t)) + } + if (v->isDerivedFrom(t)) { return true; - else + } + else { return false; + } } void Command::initAction() @@ -269,7 +295,7 @@ void Command::initAction() } } -void Command::addTo(QWidget *pcWidget) +void Command::addTo(QWidget* pcWidget) { initAction(); _pcAction->addTo(pcWidget); @@ -287,7 +313,7 @@ void Command::addToGroup(ActionGroup* group) group->addAction(_pcAction->findChild()); } -Application *Command::getGuiApplication() +Application* Command::getGuiApplication() { return Application::Instance; } @@ -320,85 +346,98 @@ App::DocumentObject* Command::getObject(const char* Name) const int Command::_busy; -class PendingLine { +class PendingLine +{ public: - PendingLine(MacroManager::LineType type, const char *line) { + PendingLine(MacroManager::LineType type, const char* line) + { Application::Instance->macroManager()->addPendingLine(type, line); } - ~PendingLine() { + ~PendingLine() + { cancel(); } - void cancel() { + void cancel() + { Application::Instance->macroManager()->addPendingLine(MacroManager::Cmt, nullptr); } }; -class CommandTrigger { +class CommandTrigger +{ public: - CommandTrigger(Command::TriggerSource &trigger, Command::TriggerSource source) - :trigger(trigger),saved(trigger) + CommandTrigger(Command::TriggerSource& trigger, Command::TriggerSource source) + : trigger(trigger) + , saved(trigger) { trigger = source; } - ~CommandTrigger() { + ~CommandTrigger() + { trigger = saved; } + private: - Command::TriggerSource &trigger; + Command::TriggerSource& trigger; Command::TriggerSource saved; }; -void Command::setupCheckable(int iMsg) { - QAction *action = nullptr; +void Command::setupCheckable(int iMsg) +{ + QAction* action = nullptr; auto pcActionGroup = qobject_cast(_pcAction); - if(pcActionGroup) { + if (pcActionGroup) { QList a = pcActionGroup->actions(); assert(iMsg < a.size()); action = a[iMsg]; - }else + } + else { action = _pcAction->action(); + } - if(!action) + if (!action) { return; + } bool checkable = action->isCheckable(); _pcAction->setCheckable(checkable); - if(checkable) { + if (checkable) { bool checked = false; - switch(triggerSource()) { - case TriggerNone: - checked = !action->isChecked(); - break; - case TriggerAction: - checked = _pcAction->isChecked(); - break; - case TriggerChildAction: - checked = action->isChecked(); - break; + switch (triggerSource()) { + case TriggerNone: + checked = !action->isChecked(); + break; + case TriggerAction: + checked = _pcAction->isChecked(); + break; + case TriggerChildAction: + checked = action->isChecked(); + break; } bool blocked = action->blockSignals(true); action->setChecked(checked); action->blockSignals(blocked); - if(action!=_pcAction->action()) + if (action != _pcAction->action()) { _pcAction->setBlockedChecked(checked); + } } - } void Command::invoke(int i, TriggerSource trigger) { - CommandTrigger cmdTrigger(_trigger,trigger); + CommandTrigger cmdTrigger(_trigger, trigger); if (displayText.empty()) { displayText = getMenuText() ? getMenuText() : ""; - boost::replace_all(displayText,"&",""); - if (displayText.empty()) + boost::replace_all(displayText, "&", ""); + if (displayText.empty()) { displayText = getName(); + } } // Do not query _pcAction since it isn't created necessarily #ifdef FC_LOGUSERACTION - Base::Console().log("CmdG: %s\n",sName); + Base::Console().log("CmdG: %s\n", sName); #endif _invoke(i, bCanLog && !_busy); @@ -461,14 +500,15 @@ void Command::_invoke(int id, bool disablelog) getMainWindow()->updateActions(); // If this command starts an editing, let the transaction persist - if (!editDoc && getGuiApplication()->editDocument()) + if (!editDoc && getGuiApplication()->editDocument()) { committer.setEnable(false); + } } } catch (const Base::SystemExitException&) { throw; } - catch (Base::PyException &e) { + catch (Base::PyException& e) { e.reportException(); } catch (Py::Exception&) { @@ -478,12 +518,12 @@ void Command::_invoke(int id, bool disablelog) } catch (Base::AbortException&) { } - catch (Base::Exception &e) { + catch (Base::Exception& e) { e.reportException(); // Pop-up a dialog for FreeCAD-specific exceptions QMessageBox::critical(Gui::getMainWindow(), QObject::tr("Exception"), QLatin1String(e.what())); } - catch (std::exception &e) { + catch (std::exception& e) { Base::Console().error("C++ exception thrown (%s)\n", e.what()); } catch (const char* e) { @@ -498,35 +538,38 @@ void Command::_invoke(int id, bool disablelog) void Command::testActive() { - if (!_pcAction) + if (!_pcAction) { return; + } if (_blockCmd || !bEnabled) { _pcAction->setEnabled(false); return; } - if (!(eType & ForEdit)) { // special case for commands which are only in some edit modes active + if (!(eType & ForEdit)) { // special case for commands which are only in some edit modes active - if ((!Gui::Control().isAllowedAlterDocument() && eType & AlterDoc) || - (!Gui::Control().isAllowedAlterView() && eType & Alter3DView) || - (!Gui::Control().isAllowedAlterSelection() && eType & AlterSelection)) { - _pcAction->setEnabled(false); + if ((!Gui::Control().isAllowedAlterDocument() && eType & AlterDoc) + || (!Gui::Control().isAllowedAlterView() && eType & Alter3DView) + || (!Gui::Control().isAllowedAlterSelection() && eType & AlterSelection)) { + _pcAction->setEnabled(false); return; } } auto pcAction = qobject_cast(_pcAction); - if(pcAction) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + if (pcAction) { + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); const auto actions = pcAction->actions(); - for(auto action : actions) { + for (auto action : actions) { auto name = action->property("CommandName").toByteArray(); - if(!name.size()) + if (!name.size()) { continue; + } Command* cmd = rcCmdMgr.getCommandByName(name); - if(cmd) + if (cmd) { action->setEnabled(cmd->isActive()); + } } } @@ -556,40 +599,55 @@ bool Command::hasObject(const char* Name) return getDocument() != nullptr && getDocument()->getObject(Name) != nullptr; } -Gui::SelectionSingleton& Command::getSelection() +Gui::SelectionSingleton& Command::getSelection() { return Gui::Selection(); } -std::string Command::getUniqueObjectName(const char *BaseName, const App::DocumentObject *obj) const +std::string Command::getUniqueObjectName(const char* BaseName, const App::DocumentObject* obj) const { - auto doc = obj?obj->getDocument():App::GetApplication().getActiveDocument(); + auto doc = obj ? obj->getDocument() : App::GetApplication().getActiveDocument(); assert(doc); return doc->getUniqueObjectName(BaseName); } -std::string Command::getObjectCmd(const char *Name, const App::Document *doc, - const char *prefix, const char *postfix, bool gui) +std::string Command::getObjectCmd( + const char* Name, + const App::Document* doc, + const char* prefix, + const char* postfix, + bool gui +) { - if(!doc) doc = App::GetApplication().getActiveDocument(); - if(!doc || !Name) + if (!doc) { + doc = App::GetApplication().getActiveDocument(); + } + if (!doc || !Name) { return {"None"}; + } std::ostringstream str; - if(prefix) + if (prefix) { str << prefix; - str << (gui?"Gui":"App") << ".getDocument('" << doc->getName() - << "').getObject('" << Name << "')"; - if(postfix) + } + str << (gui ? "Gui" : "App") << ".getDocument('" << doc->getName() << "').getObject('" << Name + << "')"; + if (postfix) { str << postfix; + } return str.str(); } -std::string Command::getObjectCmd(const App::DocumentObject *obj, - const char *prefix, const char *postfix, bool gui) +std::string Command::getObjectCmd( + const App::DocumentObject* obj, + const char* prefix, + const char* postfix, + bool gui +) { - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return {"None"}; - return getObjectCmd(obj->getNameInDocument(), obj->getDocument(), prefix, postfix,gui); + } + return getObjectCmd(obj->getNameInDocument(), obj->getDocument(), prefix, postfix, gui); } void Command::setAppModuleName(const char* s) @@ -605,8 +663,9 @@ void Command::setGroupName(const char* s) QString Command::translatedGroupName() const { QString text = qApp->translate(className(), getGroupName()); - if (text == QString::fromLatin1(getGroupName())) + if (text == QString::fromLatin1(getGroupName())) { text = qApp->translate("CommandGroup", getGroupName()); + } return text; } @@ -623,8 +682,9 @@ QString Command::translatedGroupName() const */ void Command::openCommand(const char* sCmdName) { - if (!sCmdName) + if (!sCmdName) { sCmdName = "Command"; + } App::GetApplication().setActiveTransaction(sCmdName); } @@ -651,7 +711,7 @@ void Command::blockCommand(bool block) } /// Run a App level Action -void Command::_doCommand(const char *file, int line, DoCmd_Type eType, const char* sCmd, ...) +void Command::_doCommand(const char* file, int line, DoCmd_Type eType, const char* sCmd, ...) { va_list ap; va_start(ap, sCmd); @@ -666,151 +726,200 @@ void Command::_doCommand(const char *file, int line, DoCmd_Type eType, const cha Base::Console().log("CmdC: %s\n", format.constData()); #endif - _runCommand(file,line,eType,format.constData()); + _runCommand(file, line, eType, format.constData()); } -void Command::printPyCaller() { - if(!FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) +void Command::printPyCaller() +{ + if (!FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { return; + } PyFrameObject* frame = PyEval_GetFrame(); - if(!frame) + if (!frame) { return; + } int line = PyFrame_GetLineNumber(frame); #if PY_VERSION_HEX < 0x030b0000 - const char *file = PyUnicode_AsUTF8(frame->f_code->co_filename); - printCaller(file?file:"",line); + const char* file = PyUnicode_AsUTF8(frame->f_code->co_filename); + printCaller(file ? file : "", line); #else PyCodeObject* code = PyFrame_GetCode(frame); const char* file = PyUnicode_AsUTF8(code->co_filename); - printCaller(file?file:"",line); + printCaller(file ? file : "", line); Py_DECREF(code); #endif } -void Command::printCaller(const char *file, int line) { - if(!FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) +void Command::printCaller(const char* file, int line) +{ + if (!FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { return; + } std::ostringstream str; #ifdef FC_OS_WIN32 - const char *_f = std::strstr(file, "\\src\\"); + const char* _f = std::strstr(file, "\\src\\"); #else - const char *_f = std::strstr(file, "/src/"); + const char* _f = std::strstr(file, "/src/"); #endif - str << "## " << (_f?_f+5:file)<<'('<macroManager()->addLine(MacroManager::Cmt,str.str().c_str()); + str << "## " << (_f ? _f + 5 : file) << '(' << line << ')'; + Gui::Application::Instance->macroManager()->addLine(MacroManager::Cmt, str.str().c_str()); } /// Run a App level Action -void Command::_runCommand(const char *file, int line, DoCmd_Type eType, const char* sCmd) +void Command::_runCommand(const char* file, int line, DoCmd_Type eType, const char* sCmd) { LogDisabler d1; SelectionLogDisabler d2; Base::PyGILStateLocker lock; - printCaller(file,line); - if (eType == Gui) - Gui::Application::Instance->macroManager()->addLine(MacroManager::Gui,sCmd); - else - Gui::Application::Instance->macroManager()->addLine(MacroManager::App,sCmd); + printCaller(file, line); + if (eType == Gui) { + Gui::Application::Instance->macroManager()->addLine(MacroManager::Gui, sCmd); + } + else { + Gui::Application::Instance->macroManager()->addLine(MacroManager::App, sCmd); + } try { Base::Interpreter().runString(sCmd); } - catch(Py::Exception &) { + catch (Py::Exception&) { Base::PyException::throwException(); } } /// Run a App level Action -void Command::_runCommand(const char *file, int line, DoCmd_Type eType, const QByteArray& sCmd) +void Command::_runCommand(const char* file, int line, DoCmd_Type eType, const QByteArray& sCmd) { - _runCommand(file,line,eType,sCmd.constData()); + _runCommand(file, line, eType, sCmd.constData()); } -void Command::addModule(DoCmd_Type eType,const char* sModuleName) +void Command::addModule(DoCmd_Type eType, const char* sModuleName) { - if(alreadyLoadedModule.find(sModuleName) == alreadyLoadedModule.end()) { + if (alreadyLoadedModule.find(sModuleName) == alreadyLoadedModule.end()) { LogDisabler d1; SelectionLogDisabler d2; std::string sCmd("import "); sCmd += sModuleName; - if (eType == Gui) - Gui::Application::Instance->macroManager()->addLine(MacroManager::Gui,sCmd.c_str()); - else - Gui::Application::Instance->macroManager()->addLine(MacroManager::App,sCmd.c_str()); + if (eType == Gui) { + Gui::Application::Instance->macroManager()->addLine(MacroManager::Gui, sCmd.c_str()); + } + else { + Gui::Application::Instance->macroManager()->addLine(MacroManager::App, sCmd.c_str()); + } Base::Interpreter().runString(sCmd.c_str()); alreadyLoadedModule.insert(sModuleName); } } -std::string Command::_assureWorkbench(const char *file, int line, const char * sName) +std::string Command::_assureWorkbench(const char* file, int line, const char* sName) { // check if the WB is already open? std::string actName = WorkbenchManager::instance()->active()->name(); // if yes, do nothing - if(actName == sName) + if (actName == sName) { return actName; + } // else - switch to new WB - _doCommand(file,line,Gui,"Gui.activateWorkbench('%s')",sName); + _doCommand(file, line, Gui, "Gui.activateWorkbench('%s')", sName); return actName; - } -void Command::_copyVisual(const char *file, int line, const char* to, const char* attr, const char* from) +void Command::_copyVisual(const char* file, int line, const char* to, const char* attr, const char* from) { - _copyVisual(file,line,to,attr,from,attr); + _copyVisual(file, line, to, attr, from, attr); } -void Command::_copyVisual(const char *file, int line, const char* to, const char* attr_to, const char* from, const char* attr_from) +void Command::_copyVisual( + const char* file, + int line, + const char* to, + const char* attr_to, + const char* from, + const char* attr_from +) { auto doc = App::GetApplication().getActiveDocument(); - if(!doc) + if (!doc) { return; - return _copyVisual(file,line,doc->getObject(to),attr_to, - doc->getObject(from),attr_from); + } + return _copyVisual(file, line, doc->getObject(to), attr_to, doc->getObject(from), attr_from); } -void Command::_copyVisual(const char *file, int line, const App::DocumentObject *to, const char* attr_to, const App::DocumentObject *from, const char *attr_from) +void Command::_copyVisual( + const char* file, + int line, + const App::DocumentObject* to, + const char* attr_to, + const App::DocumentObject* from, + const char* attr_from +) { - if(!from || !from->isAttachedToDocument() || !to || !to->isAttachedToDocument()) + if (!from || !from->isAttachedToDocument() || !to || !to->isAttachedToDocument()) { return; - static std::map attrMap = { + } + static std::map attrMap = { {"ShapeAppearance", "ShapeMaterial"}, - {"Transparency","Transparency"}, + {"Transparency", "Transparency"}, }; auto it = attrMap.find(attr_to); auto objCmd = getObjectCmd(to); - if(it!=attrMap.end()) { + if (it != attrMap.end()) { auto obj = from; - for(int depth=0;;++depth) { + for (int depth = 0;; ++depth) { auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(obj)); - if(vp && vp->OverrideMaterial.getValue()) { - _doCommand(file,line,Gui,"%s.ViewObject.%s=%s.ViewObject.%s", - objCmd.c_str(),attr_to,getObjectCmd(obj).c_str(),it->second.c_str()); + Gui::Application::Instance->getViewProvider(obj) + ); + if (vp && vp->OverrideMaterial.getValue()) { + _doCommand( + file, + line, + Gui, + "%s.ViewObject.%s=%s.ViewObject.%s", + objCmd.c_str(), + attr_to, + getObjectCmd(obj).c_str(), + it->second.c_str() + ); return; } - auto linked = obj->getLinkedObject(false,nullptr,false,depth); - if(!linked || linked==obj) + auto linked = obj->getLinkedObject(false, nullptr, false, depth); + if (!linked || linked == obj) { break; + } obj = linked; } } try { - _doCommand(file,line,Gui, - "%s.ViewObject.%s=getattr(%s.getLinkedObject(True).ViewObject,'%s',%s.ViewObject.%s)", - objCmd.c_str(),attr_to,getObjectCmd(from).c_str(),attr_from,objCmd.c_str(),attr_to); + _doCommand( + file, + line, + Gui, + "%s.ViewObject.%s=getattr(%s.getLinkedObject(True).ViewObject,'%s',%s.ViewObject.%s)", + objCmd.c_str(), + attr_to, + getObjectCmd(from).c_str(), + attr_from, + objCmd.c_str(), + attr_to + ); } - catch(Base::Exception& /*e*/) { + catch (Base::Exception& /*e*/) { } } -void Command::_copyVisual(const char *file, int line, const App::DocumentObject *to, const char* attr, const App::DocumentObject *from) +void Command::_copyVisual( + const char* file, + int line, + const App::DocumentObject* to, + const char* attr, + const App::DocumentObject* from +) { - _copyVisual(file,line,to,attr,from,attr); + _copyVisual(file, line, to, attr, from, attr); } std::string Command::getPythonTuple(const std::string& name, const std::vector& subnames) @@ -818,10 +927,11 @@ std::string Command::getPythonTuple(const std::string& name, const std::vector\n" - "\n" - "\n" - "\n" - "FreeCAD Main Index\n" - "\n" - "\n\n"; + return "\n" + "\n" + "\n" + "\n" + "FreeCAD Main Index\n" + "\n" + "\n\n"; } /// returns the end of a online help page -const char * Command::endCmdHelp() +const char* Command::endCmdHelp() { return "\n\n"; } void Command::applyCommandData(const char* context, Action* action) { - action->setText(QCoreApplication::translate( - context, getMenuText())); - action->setToolTip(QCoreApplication::translate( - context, getToolTipText())); - action->setWhatsThis(QCoreApplication::translate( - context, getWhatsThis())); - if (sStatusTip) - action->setStatusTip(QCoreApplication::translate( - context, getStatusTip())); - else - action->setStatusTip(QCoreApplication::translate( - context, getToolTipText())); + action->setText(QCoreApplication::translate(context, getMenuText())); + action->setToolTip(QCoreApplication::translate(context, getToolTipText())); + action->setWhatsThis(QCoreApplication::translate(context, getWhatsThis())); + if (sStatusTip) { + action->setStatusTip(QCoreApplication::translate(context, getStatusTip())); + } + else { + action->setStatusTip(QCoreApplication::translate(context, getToolTipText())); + } // Default to QAction::NoRole instead of QAction::TextHeuristicRole to stop collisions with // e.g. "Preferences" and "Copy" @@ -921,17 +1028,25 @@ const char* Command::keySequenceToAccel(int sk) const void Command::printConflictingAccelerators() const { auto cmd = Application::Instance->commandManager().checkAcceleratorForConflicts(sAccel, this); - if (cmd) - Base::Console().warning("Accelerator conflict between %s (%s) and %s (%s)\n", sName, sAccel, cmd->sName, cmd->sAccel); + if (cmd) { + Base::Console().warning( + "Accelerator conflict between %s (%s) and %s (%s)\n", + sName, + sAccel, + cmd->sName, + cmd->sAccel + ); + } } -Action * Command::createAction() +Action* Command::createAction() { - Action *pcAction; - pcAction = new Action(this,getMainWindow()); + Action* pcAction; + pcAction = new Action(this, getMainWindow()); applyCommandData(this->className(), pcAction); - if (sPixmap) + if (sPixmap) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(sPixmap)); + } return pcAction; } @@ -943,15 +1058,14 @@ void Command::languageChange() } void Command::updateAction(int) -{ -} +{} //=========================================================================== // GroupCommand //=========================================================================== -GroupCommand::GroupCommand(const char *name) - :Command(name) +GroupCommand::GroupCommand(const char* name) + : Command(name) {} bool GroupCommand::isCheckable() const @@ -994,28 +1108,34 @@ void GroupCommand::setDropDownMenu(bool on) dropDownMenu = on; } -int GroupCommand::addCommand(Command *cmd, bool reg) { - cmds.emplace_back(cmd,cmds.size()); - if(cmd && reg) +int GroupCommand::addCommand(Command* cmd, bool reg) +{ + cmds.emplace_back(cmd, cmds.size()); + if (cmd && reg) { Application::Instance->commandManager().addCommand(cmd); - return (int)cmds.size()-1; + } + return (int)cmds.size() - 1; } -Command *GroupCommand::addCommand(const char *name) { +Command* GroupCommand::addCommand(const char* name) +{ auto cmd = Application::Instance->commandManager().getCommandByName(name); - if(cmd) - addCommand(cmd,false); + if (cmd) { + addCommand(cmd, false); + } return cmd; } -Command *GroupCommand::getCommand(int idx) const +Command* GroupCommand::getCommand(int idx) const { - if (idx >= 0 && idx < (int)cmds.size()) + if (idx >= 0 && idx < (int)cmds.size()) { return cmds[idx].first; + } return nullptr; } -Action * GroupCommand::createAction() { +Action* GroupCommand::createAction() +{ auto* pcAction = new ActionGroup(this, getMainWindow()); pcAction->setMenuRole(QAction::NoRole); pcAction->setDropDownMenu(hasDropDownMenu()); @@ -1024,11 +1144,13 @@ Action * GroupCommand::createAction() { pcAction->setRememberLast(doesRememberLast()); pcAction->setWhatsThis(QString::fromLatin1(sWhatsThis)); - for(auto &v : cmds) { - if(!v.first) + for (auto& v : cmds) { + if (!v.first) { pcAction->addAction(QStringLiteral(""))->setSeparator(true); - else + } + else { v.first->addToGroup(pcAction); + } } pcAction->setProperty("defaultAction", QVariant(0)); @@ -1038,57 +1160,70 @@ Action * GroupCommand::createAction() { void GroupCommand::activated(int iMsg) { - if(iMsg<0 || iMsg>=(int)cmds.size()) + if (iMsg < 0 || iMsg >= (int)cmds.size()) { return; + } - auto &v = cmds[iMsg]; - if(!v.first) + auto& v = cmds[iMsg]; + if (!v.first) { return; + } - if(triggerSource()!=TriggerChildAction) + if (triggerSource() != TriggerChildAction) { v.first->invoke(0); + } Action* cmdAction = v.first->getAction(); - if(_pcAction && cmdAction) { + if (_pcAction && cmdAction) { _pcAction->setProperty("defaultAction", QVariant((int)v.second)); setup(_pcAction); } } -void GroupCommand::languageChange() { +void GroupCommand::languageChange() +{ Command::languageChange(); - if (_pcAction) + if (_pcAction) { setup(_pcAction); + } } -void GroupCommand::setup(Action *pcAction) { +void GroupCommand::setup(Action* pcAction) +{ // The tooltip for the group is the tooltip of the active tool (that is, the tool that will // be activated when the main portion of the button is clicked). int idx = pcAction->property("defaultAction").toInt(); - if(idx>=0 && idx<(int)cmds.size() && cmds[idx].first) { + if (idx >= 0 && idx < (int)cmds.size() && cmds[idx].first) { auto cmd = cmds[idx].first; QString shortcut = cmd->getShortcut(); pcAction->setShortcut(shortcut); pcAction->setText(QCoreApplication::translate(className(), getMenuText())); QIcon icon; - if (auto childAction = cmd->getAction()) + if (auto childAction = cmd->getAction()) { icon = childAction->icon(); - if (icon.isNull()) + } + if (icon.isNull()) { icon = BitmapFactory().iconFromTheme(cmd->getPixmap()); + } pcAction->setIcon(icon); - const char *context = dynamic_cast(cmd) ? cmd->getName() : cmd->className(); - const char *tooltip = cmd->getToolTipText(); - const char *statustip = cmd->getStatusTip(); - if (!statustip || '\0' == *statustip) + const char* context = dynamic_cast(cmd) ? cmd->getName() : cmd->className(); + const char* tooltip = cmd->getToolTipText(); + const char* statustip = cmd->getStatusTip(); + if (!statustip || '\0' == *statustip) { statustip = tooltip; - pcAction->setToolTip(QCoreApplication::translate(context,tooltip), - QCoreApplication::translate(cmd->className(), cmd->getMenuText())); - pcAction->setStatusTip(QCoreApplication::translate(context,statustip)); - } else { + } + pcAction->setToolTip( + QCoreApplication::translate(context, tooltip), + QCoreApplication::translate(cmd->className(), cmd->getMenuText()) + ); + pcAction->setStatusTip(QCoreApplication::translate(context, statustip)); + } + else { applyCommandData(this->className(), pcAction); - if (sPixmap) + if (sPixmap) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(sPixmap)); + } } } @@ -1099,11 +1234,11 @@ void GroupCommand::setup(Action *pcAction) { /* TRANSLATOR Gui::MacroCommand */ MacroCommand::MacroCommand(const char* name, bool system) - : Command(StringCache::New(name)) - , systemMacro(system) + : Command(StringCache::New(name)) + , systemMacro(system) { sGroup = "Macros"; - eType = 0; + eType = 0; sScriptName = nullptr; } @@ -1117,93 +1252,104 @@ void MacroCommand::activated(int iMsg) if (!systemMacro) { std::string cMacroPath; - cMacroPath = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Macro")->GetASCII("MacroPath", - App::Application::getUserMacroDir().c_str()); + cMacroPath = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); d = QDir(QString::fromUtf8(cMacroPath.c_str())); } else { - QString dirstr = QString::fromStdString(App::Application::getHomePath()) + QStringLiteral("Macro"); + QString dirstr = QString::fromStdString(App::Application::getHomePath()) + + QStringLiteral("Macro"); d = QDir(dirstr); } QFileInfo fi(d, QString::fromUtf8(sScriptName)); if (!fi.exists()) { - QMessageBox::critical(Gui::getMainWindow(), + QMessageBox::critical( + Gui::getMainWindow(), qApp->translate("Gui::MacroCommand", "Macro file doesn't exist"), - qApp->translate("Gui::MacroCommand", "No such macro file: '%1'").arg(fi.absoluteFilePath())); + qApp->translate("Gui::MacroCommand", "No such macro file: '%1'").arg(fi.absoluteFilePath()) + ); } else { Application::Instance->macroManager()->run(MacroManager::File, fi.filePath().toUtf8()); // after macro run recalculate the document - if (Application::Instance->activeDocument()) + if (Application::Instance->activeDocument()) { Application::Instance->activeDocument()->getDocument()->recompute(); + } } } -Action * MacroCommand::createAction() +Action* MacroCommand::createAction() { - Action *pcAction; - pcAction = new Action(this,getMainWindow()); + Action* pcAction; + pcAction = new Action(this, getMainWindow()); pcAction->setText(QString::fromUtf8(sMenuText)); pcAction->setToolTip(QString::fromUtf8(sToolTipText)); pcAction->setStatusTip(QString::fromUtf8(sStatusTip)); - if (pcAction->statusTip().isEmpty()) + if (pcAction->statusTip().isEmpty()) { pcAction->setStatusTip(pcAction->toolTip()); + } pcAction->setWhatsThis(QString::fromUtf8(sWhatsThis)); - if (sPixmap) + if (sPixmap) { pcAction->setIcon(Gui::BitmapFactory().pixmap(sPixmap)); + } return pcAction; } -void MacroCommand::setScriptName( const char* s ) +void MacroCommand::setScriptName(const char* s) { this->sScriptName = StringCache::New(s); } void MacroCommand::load() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Macro"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Macro" + ); if (hGrp->HasGroup("Macros")) { hGrp = hGrp->GetGroup("Macros"); - std::vector > macros = hGrp->GetGroups(); - for (const auto & it : macros) { + std::vector> macros = hGrp->GetGroups(); + for (const auto& it : macros) { auto macro = new MacroCommand(it->GetGroupName()); - macro->setScriptName ( it->GetASCII( "Script" ).c_str() ); - macro->setMenuText ( it->GetASCII( "Menu" ).c_str() ); - macro->setToolTipText ( it->GetASCII( "Tooltip" ).c_str() ); - macro->setWhatsThis ( it->GetASCII( "WhatsThis" ).c_str() ); - macro->setStatusTip ( it->GetASCII( "Statustip" ).c_str() ); - if (it->GetASCII("Pixmap", "nix") != "nix") - macro->setPixmap ( it->GetASCII( "Pixmap" ).c_str() ); - macro->setAccel ( it->GetASCII( "Accel",nullptr ).c_str() ); + macro->setScriptName(it->GetASCII("Script").c_str()); + macro->setMenuText(it->GetASCII("Menu").c_str()); + macro->setToolTipText(it->GetASCII("Tooltip").c_str()); + macro->setWhatsThis(it->GetASCII("WhatsThis").c_str()); + macro->setStatusTip(it->GetASCII("Statustip").c_str()); + if (it->GetASCII("Pixmap", "nix") != "nix") { + macro->setPixmap(it->GetASCII("Pixmap").c_str()); + } + macro->setAccel(it->GetASCII("Accel", nullptr).c_str()); macro->systemMacro = it->GetBool("System", false); - Application::Instance->commandManager().addCommand( macro ); + Application::Instance->commandManager().addCommand(macro); } } } void MacroCommand::save() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Macro")->GetGroup("Macros"); + ParameterGrp::handle hGrp = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Macro") + ->GetGroup("Macros"); hGrp->Clear(); std::vector macros = Application::Instance->commandManager().getGroupCommands("Macros"); - if ( !macros.empty() ) { - for (const auto & it : macros) { + if (!macros.empty()) { + for (const auto& it : macros) { auto macro = (MacroCommand*)it; ParameterGrp::handle hMacro = hGrp->GetGroup(macro->getName()); - hMacro->SetASCII( "Script", macro->getScriptName () ); - hMacro->SetASCII( "Menu", macro->getMenuText () ); - hMacro->SetASCII( "Tooltip", macro->getToolTipText() ); - hMacro->SetASCII( "WhatsThis", macro->getWhatsThis () ); - hMacro->SetASCII( "Statustip", macro->getStatusTip () ); - hMacro->SetASCII( "Pixmap", macro->getPixmap () ); - hMacro->SetASCII( "Accel", macro->getAccel () ); - hMacro->SetBool( "System", macro->systemMacro ); + hMacro->SetASCII("Script", macro->getScriptName()); + hMacro->SetASCII("Menu", macro->getMenuText()); + hMacro->SetASCII("Tooltip", macro->getToolTipText()); + hMacro->SetASCII("WhatsThis", macro->getWhatsThis()); + hMacro->SetASCII("Statustip", macro->getStatusTip()); + hMacro->SetASCII("Pixmap", macro->getPixmap()); + hMacro->SetASCII("Accel", macro->getAccel()); + hMacro->SetBool("System", macro->systemMacro); } } } @@ -1212,12 +1358,13 @@ void MacroCommand::save() // PythonCommand //=========================================================================== -PythonCommand::PythonCommand(const char* name, PyObject * pcPyCommand, const char* pActivationString) - : Command(StringCache::New(name)) - ,_pcPyCommand(pcPyCommand) +PythonCommand::PythonCommand(const char* name, PyObject* pcPyCommand, const char* pActivationString) + : Command(StringCache::New(name)) + , _pcPyCommand(pcPyCommand) { - if (pActivationString) + if (pActivationString) { Activation = pActivationString; + } sGroup = "Python"; @@ -1227,32 +1374,37 @@ PythonCommand::PythonCommand(const char* name, PyObject * pcPyCommand, const cha _pcPyResourceDict = Interpreter().runMethodObject(_pcPyCommand, "GetResources"); // check if the "GetResources()" method returns a Dict object if (!PyDict_Check(_pcPyResourceDict)) { - throw Base::TypeError("PythonCommand::PythonCommand(): Method GetResources() of the Python " - "command object returns the wrong type (has to be dict)"); + throw Base::TypeError( + "PythonCommand::PythonCommand(): Method GetResources() of the Python " + "command object returns the wrong type (has to be dict)" + ); } // check for command type std::string cmdType = getResource("CmdType"); if (!cmdType.empty()) { int type = 0; - if (cmdType.find("AlterDoc") != std::string::npos) + if (cmdType.find("AlterDoc") != std::string::npos) { type += int(AlterDoc); - if (cmdType.find("Alter3DView") != std::string::npos) + } + if (cmdType.find("Alter3DView") != std::string::npos) { type += int(Alter3DView); - if (cmdType.find("AlterSelection") != std::string::npos) + } + if (cmdType.find("AlterSelection") != std::string::npos) { type += int(AlterSelection); - if (cmdType.find("ForEdit") != std::string::npos) + } + if (cmdType.find("ForEdit") != std::string::npos) { type += int(ForEdit); - if (cmdType.find("NoTransaction") != std::string::npos) + } + if (cmdType.find("NoTransaction") != std::string::npos) { type += int(NoTransaction); + } eType = type; } auto& rcCmdMgr = Gui::Application::Instance->commandManager(); - connPyCmdInitialized = rcCmdMgr.signalPyCmdInitialized.connect([this]() { - this->onActionInit(); - }); + connPyCmdInitialized = rcCmdMgr.signalPyCmdInitialized.connect([this]() { this->onActionInit(); }); } PythonCommand::~PythonCommand() @@ -1267,12 +1419,15 @@ const char* PythonCommand::getResource(const char* sName) const PyObject* pcTemp; // get the "MenuText" resource string - pcTemp = PyDict_GetItemString(_pcPyResourceDict,sName); - if (!pcTemp) + pcTemp = PyDict_GetItemString(_pcPyResourceDict, sName); + if (!pcTemp) { return ""; + } if (!PyUnicode_Check(pcTemp)) { - throw Base::TypeError("PythonCommand::getResource(): Method GetResources() of the Python " - "command object returns a dictionary which holds not only strings"); + throw Base::TypeError( + "PythonCommand::getResource(): Method GetResources() of the Python " + "command object returns a dictionary which holds not only strings" + ); } return PyUnicode_AsUTF8(pcTemp); } @@ -1289,15 +1444,19 @@ void PythonCommand::activated(int iMsg) } } catch (const Base::PyException& e) { - Base::Console().error("Running the Python command '%s' failed:\n%s\n%s", - sName, e.getStackTrace().c_str(), e.what()); + Base::Console().error( + "Running the Python command '%s' failed:\n%s\n%s", + sName, + e.getStackTrace().c_str(), + e.what() + ); } catch (const Base::Exception&) { - Base::Console().error("Running the Python command '%s' failed, try to resume",sName); + Base::Console().error("Running the Python command '%s' failed, try to resume", sName); } } else { - runCommand(Doc,Activation.c_str()); + runCommand(Doc, Activation.c_str()); } } @@ -1311,11 +1470,12 @@ bool PythonCommand::isActive() Py::Tuple args; Py::Object ret = call.apply(args); // if return type is not boolean or not true - if (!PyBool_Check(ret.ptr()) || ret.ptr() != Py_True) + if (!PyBool_Check(ret.ptr()) || ret.ptr() != Py_True) { return false; + } } } - catch(Py::Exception& e) { + catch (Py::Exception& e) { Base::PyGILStateLocker lock; e.clear(); return false; @@ -1335,22 +1495,25 @@ const char* PythonCommand::getHelpUrl() const { PyObject* pcTemp; pcTemp = Interpreter().runMethodObject(_pcPyCommand, "CmdHelpURL"); - if (! pcTemp ) + if (!pcTemp) { return ""; - if (! PyUnicode_Check(pcTemp) ) + } + if (!PyUnicode_Check(pcTemp)) { throw Base::TypeError("PythonCommand::CmdHelpURL(): Method CmdHelpURL() of the Python command object returns no string"); + } return PyUnicode_AsUTF8(pcTemp); } -Action * PythonCommand::createAction() +Action* PythonCommand::createAction() { auto qtAction = new QAction(nullptr); - Action *pcAction; + Action* pcAction; pcAction = new Action(this, qtAction, getMainWindow()); applyCommandData(this->getName(), pcAction); - if (strcmp(getResource("Pixmap"),"") != 0) + if (strcmp(getResource("Pixmap"), "") != 0) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getResource("Pixmap"))); + } try { if (isCheckable()) { @@ -1371,8 +1534,9 @@ Action * PythonCommand::createAction() const char* PythonCommand::getWhatsThis() const { const char* whatsthis = getResource("WhatsThis"); - if (Base::Tools::isNullOrEmpty(whatsthis)) + if (Base::Tools::isNullOrEmpty(whatsthis)) { whatsthis = this->getName(); + } return whatsthis; } @@ -1405,25 +1569,29 @@ const char* PythonCommand::getAccel() const bool PythonCommand::isCheckable() const { Base::PyGILStateLocker lock; - PyObject* item = PyDict_GetItemString(_pcPyResourceDict,"Checkable"); + PyObject* item = PyDict_GetItemString(_pcPyResourceDict, "Checkable"); return item ? true : false; } bool PythonCommand::isChecked() const { Base::PyGILStateLocker lock; - PyObject* item = PyDict_GetItemString(_pcPyResourceDict,"Checkable"); + PyObject* item = PyDict_GetItemString(_pcPyResourceDict, "Checkable"); if (!item) { - throw Base::ValueError("PythonCommand::isChecked(): Method GetResources() of the Python " - "command object doesn't contain the key 'Checkable'"); + throw Base::ValueError( + "PythonCommand::isChecked(): Method GetResources() of the Python " + "command object doesn't contain the key 'Checkable'" + ); } if (PyBool_Check(item)) { return Base::asBoolean(item); } else { - throw Base::ValueError("PythonCommand::isChecked(): Method GetResources() of the Python " - "command object contains the key 'Checkable' which is not a boolean"); + throw Base::ValueError( + "PythonCommand::isChecked(): Method GetResources() of the Python " + "command object contains the key 'Checkable' which is not a boolean" + ); } } @@ -1438,7 +1606,7 @@ void PythonCommand::onActionInit() const Py::Object ret = call.apply(args); } } - catch(Py::Exception& e) { + catch (Py::Exception& e) { Base::PyGILStateLocker lock; e.clear(); } @@ -1450,9 +1618,9 @@ void PythonCommand::onActionInit() const // PythonGroupCommand //=========================================================================== -PythonGroupCommand::PythonGroupCommand(const char* name, PyObject * pcPyCommand) - : Command(StringCache::New(name)) - ,_pcPyCommand(pcPyCommand) +PythonGroupCommand::PythonGroupCommand(const char* name, PyObject* pcPyCommand) + : Command(StringCache::New(name)) + , _pcPyCommand(pcPyCommand) { sGroup = "Python"; @@ -1462,30 +1630,34 @@ PythonGroupCommand::PythonGroupCommand(const char* name, PyObject * pcPyCommand) _pcPyResource = Interpreter().runMethodObject(_pcPyCommand, "GetResources"); // check if the "GetResources()" method returns a Dict object if (!PyDict_Check(_pcPyResource)) { - throw Base::TypeError("PythonGroupCommand::PythonGroupCommand(): Method GetResources() of the Python " - "command object returns the wrong type (has to be dict)"); + throw Base::TypeError( + "PythonGroupCommand::PythonGroupCommand(): Method GetResources() of the Python " + "command object returns the wrong type (has to be dict)" + ); } // check for command type std::string cmdType = getResource("CmdType"); if (!cmdType.empty()) { int type = 0; - if (cmdType.find("AlterDoc") != std::string::npos) + if (cmdType.find("AlterDoc") != std::string::npos) { type += int(AlterDoc); - if (cmdType.find("Alter3DView") != std::string::npos) + } + if (cmdType.find("Alter3DView") != std::string::npos) { type += int(Alter3DView); - if (cmdType.find("AlterSelection") != std::string::npos) + } + if (cmdType.find("AlterSelection") != std::string::npos) { type += int(AlterSelection); - if (cmdType.find("ForEdit") != std::string::npos) + } + if (cmdType.find("ForEdit") != std::string::npos) { type += int(ForEdit); + } eType = type; } auto& rcCmdMgr = Gui::Application::Instance->commandManager(); - connPyCmdInitialized = rcCmdMgr.signalPyCmdInitialized.connect([this]() { - this->onActionInit(); - }); + connPyCmdInitialized = rcCmdMgr.signalPyCmdInitialized.connect([this]() { this->onActionInit(); }); } PythonGroupCommand::~PythonGroupCommand() @@ -1514,20 +1686,23 @@ void PythonGroupCommand::activated(int iMsg) } // If the command group doesn't implement the 'Activated' method then invoke the command directly else { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); auto cmd = rcCmdMgr.getCommandByName(act->property("CommandName").toByteArray()); - if(cmd) { + if (cmd) { bool checked = act->isCheckable() && act->isChecked(); - cmd->invoke(checked?1:0,TriggerAction); + cmd->invoke(checked ? 1 : 0, TriggerAction); } } - } - catch(Py::Exception&) { + catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException e; - Base::Console().error("Running the Python command '%s' failed:\n%s\n%s", - sName, e.getStackTrace().c_str(), e.what()); + Base::Console().error( + "Running the Python command '%s' failed:\n%s\n%s", + sName, + e.getStackTrace().c_str(), + e.what() + ); } } @@ -1542,11 +1717,12 @@ bool PythonGroupCommand::isActive() Py::Tuple args; Py::Object ret = call.apply(args); // if return type is not boolean or not true - if (!PyBool_Check(ret.ptr()) || ret.ptr() != Py_True) + if (!PyBool_Check(ret.ptr()) || ret.ptr() != Py_True) { return false; + } } } - catch(Py::Exception& e) { + catch (Py::Exception& e) { Base::PyGILStateLocker lock; e.clear(); return false; @@ -1555,7 +1731,7 @@ bool PythonGroupCommand::isActive() return true; } -Action * PythonGroupCommand::createAction() +Action* PythonGroupCommand::createAction() { auto pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(hasDropDownMenu()); @@ -1568,7 +1744,7 @@ Action * PythonGroupCommand::createAction() try { Base::PyGILStateLocker lock; Py::Object cmd(_pcPyCommand); - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); Py::Callable call(cmd.getAttr("GetCommands")); Py::Sequence args; @@ -1578,14 +1754,18 @@ Action * PythonGroupCommand::createAction() QAction* cmd = pcAction->addAction(QString()); cmd->setProperty("CommandName", QByteArray(static_cast(str).c_str())); - PythonCommand* pycmd = dynamic_cast(rcCmdMgr.getCommandByName(cmd->property("CommandName").toByteArray())); + PythonCommand* pycmd = dynamic_cast( + rcCmdMgr.getCommandByName(cmd->property("CommandName").toByteArray()) + ); if (pycmd && pycmd->isCheckable()) { cmd->setCheckable(true); cmd->blockSignals(true); cmd->setChecked(pycmd->isChecked()); cmd->blockSignals(false); } - cmd->setShortcut(ShortcutManager::instance()->getShortcut(cmd->property("CommandName").toByteArray())); + cmd->setShortcut( + ShortcutManager::instance()->getShortcut(cmd->property("CommandName").toByteArray()) + ); } if (cmd.hasAttr("GetDefaultCommand")) { @@ -1603,33 +1783,40 @@ Action * PythonGroupCommand::createAction() qtAction->blockSignals(true); qtAction->setChecked(true); qtAction->blockSignals(false); - }else if(qtAction->isCheckable()){ + } + else if (qtAction->isCheckable()) { pcAction->setCheckable(true); pcAction->setBlockedChecked(qtAction->isChecked()); } } } } - catch(Py::Exception&) { + catch (Py::Exception&) { Base::PyGILStateLocker lock; Base::PyException e; - Base::Console().error("createAction() of the Python command '%s' failed:\n%s\n%s", - sName, e.getStackTrace().c_str(), e.what()); + Base::Console().error( + "createAction() of the Python command '%s' failed:\n%s\n%s", + sName, + e.getStackTrace().c_str(), + e.what() + ); } _pcAction = pcAction; languageChange(); - if (strcmp(getResource("Pixmap"),"") != 0) { + if (strcmp(getResource("Pixmap"), "") != 0) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getResource("Pixmap"))); } else { QList a = pcAction->actions(); // if out of range then set to 0 - if (defaultId < 0 || defaultId >= a.size()) + if (defaultId < 0 || defaultId >= a.size()) { defaultId = 0; - if (a.size() > defaultId) + } + if (a.size() > defaultId) { pcAction->setIcon(a[defaultId]->icon()); + } } pcAction->setProperty("defaultAction", QVariant(defaultId)); @@ -1639,12 +1826,13 @@ Action * PythonGroupCommand::createAction() void PythonGroupCommand::languageChange() { - if (!_pcAction) + if (!_pcAction) { return; + } applyCommandData(this->getName(), _pcAction); - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); // Reapply setup to ensure group action tooltip includes shortcut auto* pcActionGroup = qobject_cast(_pcAction); @@ -1652,24 +1840,33 @@ void PythonGroupCommand::languageChange() int idx = _pcAction->property("defaultAction").toInt(); if (idx >= 0 && idx < groupActions.size()) { QAction* defaultAction = groupActions[idx]; - Gui::Command* cmd = rcCmdMgr.getCommandByName(defaultAction->property("CommandName").toByteArray()); + Gui::Command* cmd = rcCmdMgr.getCommandByName( + defaultAction->property("CommandName").toByteArray() + ); if (cmd) { - const char *context = cmd->getName(); + const char* context = cmd->getName(); QString tip = QApplication::translate(context, cmd->getToolTipText()); _pcAction->setShortcut(cmd->getShortcut()); - QString newTip = Gui::Action::createToolTip(tip, _pcAction->text(), _pcAction->action()->font(), _pcAction->shortcut().toString(), cmd); + QString newTip = Gui::Action::createToolTip( + tip, + _pcAction->text(), + _pcAction->action()->font(), + _pcAction->shortcut().toString(), + cmd + ); _pcAction->setToolTip(newTip); } } auto* pcAction = qobject_cast(_pcAction); QList actions = pcAction->actions(); - for (const auto & it : actions) { + for (const auto& it : actions) { Gui::Command* cmd = rcCmdMgr.getCommandByName(it->property("CommandName").toByteArray()); if (cmd) { // Python command use getName as context - const char *context = dynamic_cast(cmd) ? cmd->getName() : cmd->className(); - const char *tooltip = cmd->getToolTipText(); - const char *statustip = cmd->getStatusTip(); + const char* context = dynamic_cast(cmd) ? cmd->getName() + : cmd->className(); + const char* tooltip = cmd->getToolTipText(); + const char* statustip = cmd->getStatusTip(); if (!statustip || '\0' == *statustip) { statustip = tooltip; } @@ -1699,11 +1896,14 @@ const char* PythonGroupCommand::getResource(const char* sName) const // get the "MenuText" resource string pcTemp = PyDict_GetItemString(_pcPyResource, sName); - if (!pcTemp) + if (!pcTemp) { return ""; + } if (!PyUnicode_Check(pcTemp)) { - throw Base::ValueError("PythonGroupCommand::getResource(): Method GetResources() of the Python " - "group command object returns a dictionary which holds not only strings"); + throw Base::ValueError( + "PythonGroupCommand::getResource(): Method GetResources() of the Python " + "group command object returns a dictionary which holds not only strings" + ); } return PyUnicode_AsUTF8(pcTemp); } @@ -1711,8 +1911,9 @@ const char* PythonGroupCommand::getResource(const char* sName) const const char* PythonGroupCommand::getWhatsThis() const { const char* whatsthis = getResource("WhatsThis"); - if (Base::Tools::isNullOrEmpty(whatsthis)) + if (Base::Tools::isNullOrEmpty(whatsthis)) { whatsthis = this->getName(); + } return whatsthis; } @@ -1744,7 +1945,7 @@ const char* PythonGroupCommand::getAccel() const bool PythonGroupCommand::isExclusive() const { - PyObject* item = PyDict_GetItemString(_pcPyResource,"Exclusive"); + PyObject* item = PyDict_GetItemString(_pcPyResource, "Exclusive"); if (!item) { return false; } @@ -1753,14 +1954,16 @@ bool PythonGroupCommand::isExclusive() const return Base::asBoolean(item); } else { - throw Base::TypeError("PythonGroupCommand::isExclusive(): Method GetResources() of the Python " - "command object contains the key 'Exclusive' which is not a boolean"); + throw Base::TypeError( + "PythonGroupCommand::isExclusive(): Method GetResources() of the Python " + "command object contains the key 'Exclusive' which is not a boolean" + ); } } bool PythonGroupCommand::hasDropDownMenu() const { - PyObject* item = PyDict_GetItemString(_pcPyResource,"DropDownMenu"); + PyObject* item = PyDict_GetItemString(_pcPyResource, "DropDownMenu"); if (!item) { return true; } @@ -1769,8 +1972,10 @@ bool PythonGroupCommand::hasDropDownMenu() const return Base::asBoolean(item); } else { - throw Base::TypeError("PythonGroupCommand::hasDropDownMenu(): Method GetResources() of the Python " - "command object contains the key 'DropDownMenu' which is not a boolean"); + throw Base::TypeError( + "PythonGroupCommand::hasDropDownMenu(): Method GetResources() of the Python " + "command object contains the key 'DropDownMenu' which is not a boolean" + ); } } @@ -1785,7 +1990,7 @@ void PythonGroupCommand::onActionInit() const Py::Object ret = call.apply(args); } } - catch(Py::Exception& e) { + catch (Py::Exception& e) { Base::PyGILStateLocker lock; e.clear(); } @@ -1806,10 +2011,11 @@ CommandManager::~CommandManager() void CommandManager::addCommand(Command* pCom) { - auto &cmd = _sCommands[pCom->getName()]; + auto& cmd = _sCommands[pCom->getName()]; if (cmd) { - if(FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) + if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { FC_ERR("duplicate command " << pCom->getName()); + } return; } ++_revision; @@ -1819,7 +2025,7 @@ void CommandManager::addCommand(Command* pCom) void CommandManager::removeCommand(Command* pCom) { - std::map ::iterator It = _sCommands.find(pCom->getName()); + std::map::iterator It = _sCommands.find(pCom->getName()); if (It != _sCommands.end()) { ++_revision; delete It->second; @@ -1847,29 +2053,36 @@ std::string CommandManager::newMacroName() const break; } } - if (!used) + if (!used) { name = test_name.str(); + } } return name; } void CommandManager::clearCommands() { - for ( std::map::iterator it = _sCommands.begin(); it != _sCommands.end(); ++it ) + for (std::map::iterator it = _sCommands.begin(); it != _sCommands.end(); + ++it) { delete it->second; + } _sCommands.clear(); ++_revision; signalChanged(); } -bool CommandManager::addTo(const char* Name, QWidget *pcWidget) +bool CommandManager::addTo(const char* Name, QWidget* pcWidget) { if (_sCommands.find(Name) == _sCommands.end()) { - // Print in release mode only a log message instead of an error message to avoid to annoy the user + // Print in release mode only a log message instead of an error message to avoid to annoy + // the user #ifdef FC_DEBUG - Base::Console().error("CommandManager::addTo() try to add an unknown command (%s) to a widget!\n",Name); + Base::Console().error( + "CommandManager::addTo() try to add an unknown command (%s) to a widget!\n", + Name + ); #else - Base::Console().warning("Unknown command '%s'\n",Name); + Base::Console().warning("Unknown command '%s'\n", Name); #endif return false; } @@ -1880,36 +2093,44 @@ bool CommandManager::addTo(const char* Name, QWidget *pcWidget) } } -std::vector CommandManager::getModuleCommands(const char *sModName) const +std::vector CommandManager::getModuleCommands(const char* sModName) const { - std::vector vCmds; + std::vector vCmds; - for ( std::map::const_iterator It= _sCommands.begin();It!=_sCommands.end();++It) { - if ( strcmp(It->second->getAppModuleName(),sModName) == 0) + for (std::map::const_iterator It = _sCommands.begin(); + It != _sCommands.end(); + ++It) { + if (strcmp(It->second->getAppModuleName(), sModName) == 0) { vCmds.push_back(It->second); + } } return vCmds; } -std::vector CommandManager::getAllCommands() const +std::vector CommandManager::getAllCommands() const { - std::vector vCmds; + std::vector vCmds; - for ( std::map::const_iterator It= _sCommands.begin();It!=_sCommands.end();++It) { + for (std::map::const_iterator It = _sCommands.begin(); + It != _sCommands.end(); + ++It) { vCmds.push_back(It->second); } return vCmds; } -std::vector CommandManager::getGroupCommands(const char *sGrpName) const +std::vector CommandManager::getGroupCommands(const char* sGrpName) const { - std::vector vCmds; + std::vector vCmds; - for ( std::map::const_iterator It= _sCommands.begin();It!=_sCommands.end();++It) { - if ( strcmp(It->second->getGroupName(),sGrpName) == 0) + for (std::map::const_iterator It = _sCommands.begin(); + It != _sCommands.end(); + ++It) { + if (strcmp(It->second->getGroupName(), sGrpName) == 0) { vCmds.push_back(It->second); + } } return vCmds; @@ -1917,21 +2138,23 @@ std::vector CommandManager::getGroupCommands(const char *sGrpName) co Command* CommandManager::getCommandByName(const char* sName) const { - std::map::const_iterator it = _sCommands.find( sName ); - return ( it != _sCommands.end() ) ? it->second : 0; + std::map::const_iterator it = _sCommands.find(sName); + return (it != _sCommands.end()) ? it->second : 0; } -void CommandManager::runCommandByName (const char* sName) const +void CommandManager::runCommandByName(const char* sName) const { Command* pCmd = getCommandByName(sName); - if (pCmd) + if (pCmd) { pCmd->invoke(0); + } } void CommandManager::testActive() { - for ( std::map::iterator It= _sCommands.begin();It!=_sCommands.end();++It) { + for (std::map::iterator It = _sCommands.begin(); It != _sCommands.end(); + ++It) { It->second->testActive(); } } @@ -1943,40 +2166,49 @@ void CommandManager::addCommandMode(const char* sContext, const char* sName) void CommandManager::updateCommands(const char* sContext, int mode) { - std::map >::iterator it = _sCommandModes.find(sContext); + std::map>::iterator it = _sCommandModes.find(sContext); int rev = _revision; if (it != _sCommandModes.end()) { - for (const auto & jt : it->second) { + for (const auto& jt : it->second) { Command* cmd = getCommandByName(jt.c_str()); if (cmd) { cmd->updateAction(mode); } } } - if (rev != _revision) + if (rev != _revision) { signalChanged(); + } } -const Command* Gui::CommandManager::checkAcceleratorForConflicts(const char* accel, const Command* ignore) const +const Command* Gui::CommandManager::checkAcceleratorForConflicts( + const char* accel, + const Command* ignore +) const { - if (Base::Tools::isNullOrEmpty(accel)) + if (Base::Tools::isNullOrEmpty(accel)) { return nullptr; + } QString newCombo = QString::fromLatin1(accel); - if (newCombo.isEmpty()) + if (newCombo.isEmpty()) { return nullptr; + } auto newSequence = QKeySequence::fromString(newCombo); - if (newSequence.isEmpty()) + if (newSequence.isEmpty()) { return nullptr; + } // Does this command shortcut conflict with other commands already defined? auto commands = Application::Instance->commandManager().getAllCommands(); for (const auto& cmd : commands) { - if (cmd == ignore) + if (cmd == ignore) { continue; + } auto existingAccel = cmd->getAccel(); - if (Base::Tools::isNullOrEmpty(existingAccel)) + if (Base::Tools::isNullOrEmpty(existingAccel)) { continue; + } // Three possible conflict scenarios: // 1) Exactly the same combo as another command @@ -1984,15 +2216,18 @@ const Command* Gui::CommandManager::checkAcceleratorForConflicts(const char* acc // 3) The old command is a one-char combo that overrides the new command QString existingCombo = QString::fromLatin1(existingAccel); - if (existingCombo.isEmpty()) + if (existingCombo.isEmpty()) { continue; + } auto existingSequence = QKeySequence::fromString(existingCombo); - if (existingSequence.isEmpty()) + if (existingSequence.isEmpty()) { continue; + } // Exact match - if (existingSequence == newSequence) + if (existingSequence == newSequence) { return cmd; + } // If it's not exact, then see if one of the sequences is a partial match for // the beginning of the other sequence @@ -2004,8 +2239,9 @@ const Command* Gui::CommandManager::checkAcceleratorForConflicts(const char* acc break; } } - if (firstNMatch) + if (firstNMatch) { return cmd; + } } return nullptr; diff --git a/src/Gui/Command.h b/src/Gui/Command.h index ca644a9fba..950bfbb112 100644 --- a/src/Gui/Command.h +++ b/src/Gui/Command.h @@ -52,14 +52,15 @@ * Gui.getDocument('DocName').getObject('ObjName') * @endcode */ -#define _FCMD_DOC_CMD(_type,_doc,_cmd) do{\ - auto __doc = _doc;\ - if(__doc && __doc->getName()) {\ - std::ostringstream _str;\ - _str << #_type ".getDocument('" << __doc->getName() << "')." << _cmd;\ - Gui::Command::runCommand(Gui::Command::Doc,_str.str().c_str());\ - }\ -}while(0) +#define _FCMD_DOC_CMD(_type, _doc, _cmd) \ + do { \ + auto __doc = _doc; \ + if (__doc && __doc->getName()) { \ + std::ostringstream _str; \ + _str << #_type ".getDocument('" << __doc->getName() << "')." << _cmd; \ + Gui::Command::runCommand(Gui::Command::Doc, _str.str().c_str()); \ + } \ + } while (0) /** Runs a command for accessing App.Document attribute or method * @@ -67,30 +68,31 @@ * @param _cmd: command string, streamable * @sa _FCMD_DOC_CMD() */ -#define FCMD_DOC_CMD(_doc,_cmd) _FCMD_DOC_CMD(App,_doc,_cmd) +#define FCMD_DOC_CMD(_doc, _cmd) _FCMD_DOC_CMD(App, _doc, _cmd) /** Runs a command for accessing an object's document attribute or method * @param _type: type of the document, Gui or App * @param _obj: pointer to a DocumentObject * @param _cmd: command string, streamable */ -#define _FCMD_OBJ_DOC_CMD(_type,_obj,_cmd) do{\ - auto __obj = _obj;\ - if(__obj)\ - _FCMD_DOC_CMD(_type,__obj->getDocument(),_cmd);\ -}while(0) +#define _FCMD_OBJ_DOC_CMD(_type, _obj, _cmd) \ + do { \ + auto __obj = _obj; \ + if (__obj) \ + _FCMD_DOC_CMD(_type, __obj->getDocument(), _cmd); \ + } while (0) /** Runs a command for accessing an object's App::Document attribute or method * @param _obj: pointer to a DocumentObject * @param _cmd: command string, streamable */ -#define FCMD_OBJ_DOC_CMD(_obj,_cmd) _FCMD_OBJ_DOC_CMD(App,_obj,_cmd) +#define FCMD_OBJ_DOC_CMD(_obj, _cmd) _FCMD_OBJ_DOC_CMD(App, _obj, _cmd) /** Runs a command for accessing an object's Gui::Document attribute or method * @param _obj: pointer to a DocumentObject * @param _cmd: command string, streamable */ -#define FCMD_VOBJ_DOC_CMD(_obj,_cmd) _FCMD_OBJ_DOC_CMD(Gui,_obj,_cmd) +#define FCMD_VOBJ_DOC_CMD(_obj, _cmd) _FCMD_OBJ_DOC_CMD(Gui, _obj, _cmd) /** Runs a command for accessing a document/view object's attribute or method * @param _type: type of the object, Gui or App @@ -108,29 +110,30 @@ * Gui.getDocument('DocName').getObject('ObjName').Visibility = True * @endcode */ -#define _FCMD_OBJ_CMD(_type,_cmd_type,_obj,_cmd) do{\ - auto __obj = _obj;\ - if(__obj && __obj->isAttachedToDocument()) {\ - std::ostringstream _str;\ - _str << #_type ".getDocument('" << __obj->getDocument()->getName() \ - << "').getObject('" << __obj->getNameInDocument() << "')." << _cmd;\ - Gui::Command::runCommand(Gui::Command::_cmd_type,_str.str().c_str());\ - }\ -}while(0) +#define _FCMD_OBJ_CMD(_type, _cmd_type, _obj, _cmd) \ + do { \ + auto __obj = _obj; \ + if (__obj && __obj->isAttachedToDocument()) { \ + std::ostringstream _str; \ + _str << #_type ".getDocument('" << __obj->getDocument()->getName() << "').getObject('" \ + << __obj->getNameInDocument() << "')." << _cmd; \ + Gui::Command::runCommand(Gui::Command::_cmd_type, _str.str().c_str()); \ + } \ + } while (0) /** Runs a command for accessing an document object's attribute or method * @param _obj: pointer to a DocumentObject * @param _cmd: command string, streamable * @sa _FCMD_OBJ_CMD() */ -#define FCMD_OBJ_CMD(_obj,_cmd) _FCMD_OBJ_CMD(App,Doc,_obj,_cmd) +#define FCMD_OBJ_CMD(_obj, _cmd) _FCMD_OBJ_CMD(App, Doc, _obj, _cmd) /** Runs a command for accessing an view object's attribute or method * @param _obj: pointer to a DocumentObject * @param _cmd: command string, streamable * @sa _FCMD_OBJ_CMD() */ -#define FCMD_VOBJ_CMD(_obj,_cmd) _FCMD_OBJ_CMD(Gui,Gui,_obj,_cmd) +#define FCMD_VOBJ_CMD(_obj, _cmd) _FCMD_OBJ_CMD(Gui, Gui, _obj, _cmd) /** Runs a command for accessing a document object's attribute or method * @param _cmd: command string, supporting printf like formatter @@ -147,26 +150,38 @@ * App.getDocument('DocName').getObject('ObjName').Visibility = True * @endcode */ -#define FCMD_OBJ_CMD2(_cmd,_obj,...) do{\ - auto __obj = _obj;\ - if(__obj && __obj->isAttachedToDocument()) {\ - Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument('%s').getObject('%s')." _cmd,\ - __obj->getDocument()->getName(),__obj->getNameInDocument(),## __VA_ARGS__);\ - }\ -}while(0) +#define FCMD_OBJ_CMD2(_cmd, _obj, ...) \ + do { \ + auto __obj = _obj; \ + if (__obj && __obj->isAttachedToDocument()) { \ + Gui::Command::doCommand( \ + Gui::Command::Doc, \ + "App.getDocument('%s').getObject('%s')." _cmd, \ + __obj->getDocument()->getName(), \ + __obj->getNameInDocument(), \ + ##__VA_ARGS__ \ + ); \ + } \ + } while (0) /** Runs a command for accessing a view object's attribute or method * @param _cmd: command string, supporting printf like formatter * @param _obj: pointer to a DocumentObject * @sa FCMD_OBJ_CMD2() */ -#define FCMD_VOBJ_CMD2(_cmd,_obj,...) do{\ - auto __obj = _obj;\ - if(__obj && __obj->isAttachedToDocument()) {\ - Gui::Command::doCommand(Gui::Command::Gui,"Gui.getDocument('%s').getObject('%s')." _cmd,\ - __obj->getDocument()->getName(),__obj->getNameInDocument(),## __VA_ARGS__);\ - }\ -}while(0) +#define FCMD_VOBJ_CMD2(_cmd, _obj, ...) \ + do { \ + auto __obj = _obj; \ + if (__obj && __obj->isAttachedToDocument()) { \ + Gui::Command::doCommand( \ + Gui::Command::Gui, \ + "Gui.getDocument('%s').getObject('%s')." _cmd, \ + __obj->getDocument()->getName(), \ + __obj->getNameInDocument(), \ + ##__VA_ARGS__ \ + ); \ + } \ + } while (0) /** Runs a command to start editing a give object * @param _obj: pointer to a DocumentObject @@ -176,21 +191,26 @@ * in-place editing an object, which may be brought in through linking to an * external group. */ -#define FCMD_SET_EDIT(_obj) do{\ - auto __obj = _obj;\ - if(__obj && __obj->isAttachedToDocument()) {\ - Gui::Command::doCommand(Gui::Command::Gui,\ - "Gui.ActiveDocument.setEdit(App.getDocument('%s').getObject('%s'), %i)",\ - __obj->getDocument()->getName(), __obj->getNameInDocument(), 0);\ - }\ -}while(0) +#define FCMD_SET_EDIT(_obj) \ + do { \ + auto __obj = _obj; \ + if (__obj && __obj->isAttachedToDocument()) { \ + Gui::Command::doCommand( \ + Gui::Command::Gui, \ + "Gui.ActiveDocument.setEdit(App.getDocument('%s').getObject('%s'), %i)", \ + __obj->getDocument()->getName(), \ + __obj->getNameInDocument(), \ + 0 \ + ); \ + } \ + } while (0) /// Hides an object -#define FCMD_OBJ_HIDE(_obj) FCMD_OBJ_CMD(_obj,"Visibility = False") +#define FCMD_OBJ_HIDE(_obj) FCMD_OBJ_CMD(_obj, "Visibility = False") /// Shows an object -#define FCMD_OBJ_SHOW(_obj) FCMD_OBJ_CMD(_obj,"Visibility = True") +#define FCMD_OBJ_SHOW(_obj) FCMD_OBJ_CMD(_obj, "Visibility = True") //@} @@ -201,11 +221,12 @@ using PyObject = struct _object; namespace App { - class Document; - class DocumentObject; -} +class Document; +class DocumentObject; +} // namespace App -namespace Gui { +namespace Gui +{ class Action; class Application; @@ -229,28 +250,34 @@ void CreateLinkCommands(); /** The CommandBase class - * This lightweight class is the base class of all commands in FreeCAD. It represents the link between the FreeCAD - * command framework and the QAction world of Qt. + * This lightweight class is the base class of all commands in FreeCAD. It represents the link + * between the FreeCAD command framework and the QAction world of Qt. * @author Werner Mayer */ class GuiExport CommandBase { protected: - explicit CommandBase(const char* sMenu, const char* sToolTip=nullptr, const char* sWhat=nullptr, - const char* sStatus=nullptr, const char* sPixmap=nullptr, const char* sAccel=nullptr); + explicit CommandBase( + const char* sMenu, + const char* sToolTip = nullptr, + const char* sWhat = nullptr, + const char* sStatus = nullptr, + const char* sPixmap = nullptr, + const char* sAccel = nullptr + ); virtual ~CommandBase(); public: /** * Returns the Action object of this command, or 0 if it doesn't exist. */ - Action* getAction() const; + Action* getAction() const; /** @name Methods to override when creating a new command */ //@{ protected: /// Creates the used Action when adding to a widget. The default implementation does nothing. - virtual Action * createAction(); + virtual Action* createAction(); public: /// Reassigns QAction stuff after the language has changed. @@ -263,22 +290,40 @@ public: /** @name Methods to get the properties of the command */ //@{ - virtual const char* getMenuText () const { return sMenuText; } - virtual const char* getToolTipText() const { return sToolTipText; } - virtual const char* getStatusTip () const { return sStatusTip; } - virtual const char* getWhatsThis () const { return sWhatsThis; } - virtual const char* getPixmap () const { return sPixmap; } - virtual const char* getAccel () const { return sAccel; } + virtual const char* getMenuText() const + { + return sMenuText; + } + virtual const char* getToolTipText() const + { + return sToolTipText; + } + virtual const char* getStatusTip() const + { + return sStatusTip; + } + virtual const char* getWhatsThis() const + { + return sWhatsThis; + } + virtual const char* getPixmap() const + { + return sPixmap; + } + virtual const char* getAccel() const + { + return sAccel; + } //@} /** @name Methods to set the properties of the command */ //@{ - void setWhatsThis (const char*); - void setMenuText (const char*); + void setWhatsThis(const char*); + void setMenuText(const char*); void setToolTipText(const char*); - void setStatusTip (const char*); - void setPixmap (const char*); - void setAccel (const char*); + void setStatusTip(const char*); + void setPixmap(const char*); + void setAccel(const char*); //@} protected: @@ -297,24 +342,26 @@ protected: const char* sAccel; //@} protected: - Action *_pcAction; /**< The Action item. */ + Action* _pcAction; /**< The Action item. */ std::string displayText; }; /** The Command class. * * This class is mostly used for commands implemented directly in C++ (see PythonCommand). - * It contains also a lot of helper methods to make implementing commands for FreeCAD as easy as possible. + * It contains also a lot of helper methods to make implementing commands for FreeCAD as easy as + * possible. * * @note This class is intended to handle the GUI interaction like: * - starting a dialog * - doing view and window stuff - * - anything else, especially altering the document must be done on application level. See doCommand() for details. + * - anything else, especially altering the document must be done on application level. See + * doCommand() for details. * * @see CommandManager * @author Jürgen Riegel */ -class GuiExport Command : public CommandBase +class GuiExport Command: public CommandBase { protected: explicit Command(const char* name); @@ -325,11 +372,11 @@ protected: */ //@{ /// Methods which gets called when activated, needs to be reimplemented! - virtual void activated(int iMsg)=0; + virtual void activated(int iMsg) = 0; /// Creates the used Action - Action * createAction() override; + Action* createAction() override; /// Applies the menu text, tool and status tip to the passed action object - void applyCommandData(const char* context, Action* ); + void applyCommandData(const char* context, Action*); const char* keySequenceToAccel(int) const; void printConflictingAccelerators() const; //@} @@ -340,13 +387,17 @@ public: /// CommandManager is a friend friend class CommandManager; /// Override this method if your Cmd is not always active - virtual bool isActive(){return true;} + virtual bool isActive() + { + return true; + } /// Get somtile called to check the state of the command void testActive(); /// Enables or disables the command void setEnabled(bool); /// Command trigger source - enum TriggerSource { + enum TriggerSource + { /// No external trigger, e.g. invoked through Python TriggerNone, /// Command triggered by an action @@ -355,7 +406,10 @@ public: TriggerChildAction, }; /// Return the current command trigger source - TriggerSource triggerSource() const {return _trigger;} + TriggerSource triggerSource() const + { + return _trigger; + } /** Called to invoke the command * * @param index: in case of group command, this is the index of the child @@ -363,11 +417,11 @@ public: * checkable state. * @param trigger: indicate the command triggering source, see TriggerSource. */ - void invoke (int index, TriggerSource trigger=TriggerNone); + void invoke(int index, TriggerSource trigger = TriggerNone); /// adds this command to arbitrary widgets - void addTo(QWidget *); - void addToGroup(ActionGroup *, bool checkable); - void addToGroup(ActionGroup *); + void addTo(QWidget*); + void addToGroup(ActionGroup*, bool checkable); + void addToGroup(ActionGroup*); /// Create the action if not exist void initAction(); //@} @@ -376,42 +430,51 @@ public: /** @name Helper methods to get important classes */ //@{ /// Get pointer to the Application Window - static Application* getGuiApplication(); + static Application* getGuiApplication(); /// Get a reference to the selection - static Gui::SelectionSingleton& getSelection(); + static Gui::SelectionSingleton& getSelection(); /// Get pointer to the active app document - App::Document* getActiveDocument() const; + App::Document* getActiveDocument() const; /// Get pointer to the active gui document - Gui::Document* getActiveGuiDocument() const; + Gui::Document* getActiveGuiDocument() const; /** Get pointer to the named or active App document * Returns a pointer to the named document or the active * document when no name is given. NULL is returned * when the name does not exist or no document is active! */ - App::Document* getDocument(const char* Name=nullptr) const; + App::Document* getDocument(const char* Name = nullptr) const; /// checks if the active view is of a special type or derived bool isViewOfType(Base::Type t) const; /// returns the named feature or the active one from the active document or NULL - App::DocumentObject* getObject(const char* Name) const; + App::DocumentObject* getObject(const char* Name) const; /// returns a python command string to retrieve an object from a document - static std::string getObjectCmd(const char *Name, const App::Document *doc=nullptr, - const char *prefix=nullptr, const char *postfix=nullptr, bool gui=false); + static std::string getObjectCmd( + const char* Name, + const App::Document* doc = nullptr, + const char* prefix = nullptr, + const char* postfix = nullptr, + bool gui = false + ); /// returns a python command string to retrieve the given object - static std::string getObjectCmd(const App::DocumentObject *obj, - const char *prefix=nullptr, const char *postfix=nullptr, bool gui=false); + static std::string getObjectCmd( + const App::DocumentObject* obj, + const char* prefix = nullptr, + const char* postfix = nullptr, + bool gui = false + ); /** Get unique Feature name from the active document * * @param BaseName: the base name * @param obj: if not zero, then request the unique name in the document of * the given object. */ - std::string getUniqueObjectName(const char *BaseName, const App::DocumentObject *obj=nullptr) const; + std::string getUniqueObjectName(const char* BaseName, const App::DocumentObject* obj = nullptr) const; //@} /** @name Helper methods for the Undo/Redo and Update handling */ //@{ /// Open a new Undo transaction on the active document - static void openCommand(const char* sName=nullptr); + static void openCommand(const char* sName = nullptr); /// Commit the Undo transaction on the active document static void commitCommand(); /// Abort the Undo transaction on the active document @@ -433,7 +496,8 @@ public: /** @name Helper methods for issuing commands to the Python interpreter */ //@{ /// types of application level actions for DoCommand() - enum DoCmd_Type { + enum DoCmd_Type + { /// Action alters the document Doc, /// Action alters only the application @@ -446,7 +510,7 @@ public: /// Print to Python console the current Python calling source file and line number static void printPyCaller(); /// Print to Python console the current calling source file and line number - static void printCaller(const char *file, int line); + static void printCaller(const char* file, int line); // ISO C++11 requires at least one argument for the "..." in a variadic macro // https://en.wikipedia.org/wiki/Variadic_macro#Example @@ -455,9 +519,9 @@ public: * @sa Command::_doCommand() */ #ifdef _MSC_VER -#define doCommand(_type,...) _doCommand(__FILE__,__LINE__,_type,##__VA_ARGS__) +# define doCommand(_type, ...) _doCommand(__FILE__, __LINE__, _type, ##__VA_ARGS__) #else -#define doCommand(...) _doCommand(__FILE__,__LINE__,__VA_ARGS__) +# define doCommand(...) _doCommand(__FILE__, __LINE__, __VA_ARGS__) #endif /** Run a command with printf like formatter @@ -470,13 +534,13 @@ public: * You can use the convenience macro doCommand() to automate \c file and \c * line arguments. You may also want to use various helper @ref CommandMacros. */ - static void _doCommand(const char *file, int line, DoCmd_Type eType,const char* sCmd,...); + static void _doCommand(const char* file, int line, DoCmd_Type eType, const char* sCmd, ...); /** Convenience macro to run a command * * @sa Command::_runCommand() */ -#define runCommand(_type,_cmd) _runCommand(__FILE__,__LINE__,_type,_cmd) +#define runCommand(_type, _cmd) _runCommand(__FILE__, __LINE__, _type, _cmd) /** Run a command * @@ -487,7 +551,7 @@ public: * * @sa _doCommand() */ - static void _runCommand(const char *file, int line, DoCmd_Type eType,const char* sCmd); + static void _runCommand(const char* file, int line, DoCmd_Type eType, const char* sCmd); /** Run a command * @@ -498,16 +562,16 @@ public: * * @sa _doCommand() */ - static void _runCommand(const char *file, int line, DoCmd_Type eType,const QByteArray& sCmd); + static void _runCommand(const char* file, int line, DoCmd_Type eType, const QByteArray& sCmd); /// import an external (or own) module only once - static void addModule(DoCmd_Type eType,const char* sModuleName); + static void addModule(DoCmd_Type eType, const char* sModuleName); /** Convenience macro to assure the switch to a certain workbench * * @sa _assureWorkbench() */ -#define assureWorkbench(_name) _assureWorkbench(__FILE__,__LINE__,_name) +#define assureWorkbench(_name) _assureWorkbench(__FILE__, __LINE__, _name) /** Assures the switch to a certain workbench * @@ -519,35 +583,59 @@ public: * * If already in the workbench, does nothing. */ - static std::string _assureWorkbench(const char *file, int line, const char * sName); + static std::string _assureWorkbench(const char* file, int line, const char* sName); //@} /** @name Methods for copying visiual properties */ //@{ /// Convenience macro to copy visual properties -#define copyVisual(...) _copyVisual(__FILE__,__LINE__,__VA_ARGS__) - static void _copyVisual(const char *file, int line, const char* to, const char* attr, const char* from); - static void _copyVisual(const char *file, int line, const char* to, const char* attr_to, const char* from, const char* attr_from); - static void _copyVisual(const char *file, int line, const App::DocumentObject *to, const char *attr, const App::DocumentObject *from); - static void _copyVisual(const char *file, int line, const App::DocumentObject *to, const char *attr_to, const App::DocumentObject *from, const char *attr_from); +#define copyVisual(...) _copyVisual(__FILE__, __LINE__, __VA_ARGS__) + static void _copyVisual(const char* file, int line, const char* to, const char* attr, const char* from); + static void _copyVisual( + const char* file, + int line, + const char* to, + const char* attr_to, + const char* from, + const char* attr_from + ); + static void _copyVisual( + const char* file, + int line, + const App::DocumentObject* to, + const char* attr, + const App::DocumentObject* from + ); + static void _copyVisual( + const char* file, + int line, + const App::DocumentObject* to, + const char* attr_to, + const App::DocumentObject* from, + const char* attr_from + ); //@} /// Get Python tuple from object and sub-elements static std::string getPythonTuple(const std::string& name, const std::vector& subnames); /// translate a string to a python string literal (needed e.g. in file names for windows...) const std::string strToPython(const char* Str); - const std::string strToPython(const std::string &Str){ + const std::string strToPython(const std::string& Str) + { return strToPython(Str.c_str()); } /** @name Helper methods to generate help pages */ //@{ /// returns the begin of a online help page - const char * beginCmdHelp(); + const char* beginCmdHelp(); /// returns the end of a online help page - const char * endCmdHelp(); + const char* endCmdHelp(); /// Get the help URL - virtual const char* getHelpUrl() const { return sHelpUrl; } + virtual const char* getHelpUrl() const + { + return sHelpUrl; + } //@} /** @name Helper methods for the Active tests */ @@ -561,29 +649,41 @@ public: /** @name checking of internal state */ //@{ /// returns the name to which the command belongs - const char* getAppModuleName() const {return sAppModule;} + const char* getAppModuleName() const + { + return sAppModule; + } void setAppModuleName(const char*); /// Get the command name - const char* getName() const { return sName; } + const char* getName() const + { + return sName; + } /// Get the name of the grouping of the command - const char* getGroupName() const { return sGroup; } + const char* getGroupName() const + { + return sGroup; + } void setGroupName(const char*); QString translatedGroupName() const; //@} /// Override shortcut of this command - virtual void setShortcut (const QString &); + virtual void setShortcut(const QString&); /// Obtain the current shortcut of this command virtual QString getShortcut() const; /// Helper class to disable python console log - class LogDisabler { + class LogDisabler + { public: - LogDisabler() { + LogDisabler() + { ++Command::_busy; } - ~LogDisabler() { + ~LogDisabler() + { --Command::_busy; } }; @@ -593,12 +693,13 @@ private: void _invoke(int, bool disablelog); protected: - enum CmdType { - AlterDoc = 1, /**< Command change the Document */ - Alter3DView = 2, /**< Command change the Gui */ - AlterSelection = 4, /**< Command change the Selection */ - ForEdit = 8, /**< Command is in a special edit mode active */ - NoTransaction = 16, /**< Do not setup auto transaction */ + enum CmdType + { + AlterDoc = 1, /**< Command change the Document */ + Alter3DView = 2, /**< Command change the Gui */ + AlterSelection = 4, /**< Command change the Selection */ + ForEdit = 8, /**< Command is in a special edit mode active */ + NoTransaction = 16, /**< Do not setup auto transaction */ }; /** @name Attributes @@ -611,9 +712,9 @@ protected: const char* sGroup; const char* sName; const char* sHelpUrl; - int eType; + int eType; /// Indicate if the command shall log to MacroManager - bool bCanLog; + bool bCanLog; //@} private: static int _busy; @@ -628,24 +729,26 @@ private: * To use this class, simply add children command in the constructor of your * derived class by calling addCommand(); */ -class GuiExport GroupCommand : public Command { +class GuiExport GroupCommand: public Command +{ public: /// Constructor - explicit GroupCommand(const char *name); + explicit GroupCommand(const char* name); /** Add child command * @param cmd: child command. Pass null pointer to add a separator. * @param reg: whether to register the command with CommandManager * @return Return the command index. */ - int addCommand(Command *cmd = nullptr, bool reg=true); + int addCommand(Command* cmd = nullptr, bool reg = true); /** Add child command * @param cmd: child command name. * @return Return the found command, or NULL if not found. */ - Command *addCommand(const char *cmdName); + Command* addCommand(const char* cmdName); + + Command* getCommand(int idx) const; - Command *getCommand(int idx) const; protected: bool isCheckable() const; void setCheckable(bool); @@ -656,32 +759,32 @@ protected: bool hasDropDownMenu() const; void setDropDownMenu(bool); void activated(int iMsg) override; - Gui::Action * createAction() override; + Gui::Action* createAction() override; void languageChange() override; - void setup(Action *); + void setup(Action*); protected: bool checkable = true; bool exclusive = false; bool rememberLast = true; bool dropDownMenu = true; - std::vector > cmds; + std::vector> cmds; }; /** The Python command class * This is a special type of command class. It's used to bind a Python command class into the * FreeCAD command framework. * An object of this class gets a reference to the Python command object and manages all the - * passing between the C++ and the Python world. This includes everything like setting resources such as - * bitmaps, activation or bindings to the user interface. + * passing between the C++ and the Python world. This includes everything like setting resources + * such as bitmaps, activation or bindings to the user interface. * @see CommandManager * @author Jürgen Riegel */ class PythonCommand: public Command { public: - PythonCommand(const char* name, PyObject * pcPyCommand, const char* pActivationString); + PythonCommand(const char* name, PyObject* pcPyCommand, const char* pActivationString); ~PythonCommand() override; protected: @@ -701,26 +804,28 @@ public: /// Reassigns QAction stuff after the language has changed. void languageChange() override; const char* className() const override - { return "PythonCommand"; } - const char* getWhatsThis () const override; - const char* getMenuText () const override; + { + return "PythonCommand"; + } + const char* getWhatsThis() const override; + const char* getMenuText() const override; const char* getToolTipText() const override; - const char* getStatusTip () const override; - const char* getPixmap () const override; - const char* getAccel () const override; - bool isCheckable () const; - bool isChecked () const; + const char* getStatusTip() const override; + const char* getPixmap() const override; + const char* getAccel() const override; + bool isCheckable() const; + bool isChecked() const; //@} protected: /// Returns the resource values const char* getResource(const char* sName) const; /// Creates the used Action - Action * createAction() override; + Action* createAction() override; /// a pointer to the Python command object - PyObject * _pcPyCommand; + PyObject* _pcPyCommand; /// the command object resource dictionary - PyObject * _pcPyResourceDict; + PyObject* _pcPyResourceDict; /// the activation sequence std::string Activation; //// set the parameters on action creation @@ -736,7 +841,7 @@ protected: class PythonGroupCommand: public Command { public: - PythonGroupCommand(const char* name, PyObject * pcPyCommand); + PythonGroupCommand(const char* name, PyObject* pcPyCommand); ~PythonGroupCommand() override; protected: @@ -749,7 +854,7 @@ protected: /// Get the help URL const char* getHelpUrl() const override; /// Creates the used Action - Action * createAction() override; + Action* createAction() override; //@} public: @@ -758,15 +863,17 @@ public: /// Reassigns QAction stuff after the language has changed. void languageChange() override; const char* className() const override - { return "PythonGroupCommand"; } - const char* getWhatsThis () const override; - const char* getMenuText () const override; + { + return "PythonGroupCommand"; + } + const char* getWhatsThis() const override; + const char* getMenuText() const override; const char* getToolTipText() const override; - const char* getStatusTip () const override; - const char* getPixmap () const override; - const char* getAccel () const override; - bool isExclusive () const; - bool hasDropDownMenu () const; + const char* getStatusTip() const override; + const char* getPixmap() const override; + const char* getAccel() const override; + bool isExclusive() const; + bool hasDropDownMenu() const; //@} protected: @@ -775,9 +882,9 @@ protected: //// set the parameters on action creation void onActionInit() const; /// a pointer to the Python command object - PyObject * _pcPyCommand; + PyObject* _pcPyCommand; /// the command object resources - PyObject * _pcPyResource; + PyObject* _pcPyResource; boost::signals2::connection connPyCmdInitialized; }; @@ -804,21 +911,27 @@ protected: /// Method which get called when activated void activated(int iMsg) override; /// Creates the used Action - Action * createAction() override; + Action* createAction() override; //@} public: /// Returns the script name - const char* getScriptName () const { return sScriptName; } + const char* getScriptName() const + { + return sScriptName; + } /// Ignore when language has changed. - void languageChange() override {} + void languageChange() override + {} const char* className() const override - { return "Gui::MacroCommand"; } + { + return "Gui::MacroCommand"; + } /** @name Methods to set the properties of the Script Command */ //@{ /// Sets the script name - void setScriptName ( const char* ); + void setScriptName(const char*); //@} /** @name Methods to load and save macro commands. */ @@ -863,19 +976,19 @@ public: * name is given the standard commands (build in ) are returned. * @see Command */ - std::vector getModuleCommands(const char *sModName) const; + std::vector getModuleCommands(const char* sModName) const; /** Returns all commands registered in the manager * delivers a vector of all commands. If you intereted in commands of * of a special app module use GetModuleCommands() * @see Command */ - std::vector getAllCommands() const; + std::vector getAllCommands() const; /** Returns all commands of a group * delivers a vector of all commands in the given group. */ - std::vector getGroupCommands(const char *sGrpName) const; + std::vector getGroupCommands(const char* sGrpName) const; /** Returns the command registered in the manager with the name sName * If nothing is found it returns a null pointer @@ -886,10 +999,13 @@ public: /** * Runs the command */ - void runCommandByName (const char* sName) const; + void runCommandByName(const char* sName) const; /// method is OBSOLETE use GetModuleCommands() or GetAllCommands() - const std::map& getCommands() const { return _sCommands; } + const std::map& getCommands() const + { + return _sCommands; + } /// get frequently called by the AppWnd to check the commands are active. void testActive(); @@ -897,21 +1013,24 @@ public: void updateCommands(const char* sContext, int mode); /// Return a revision number to check for addition or removal of any command - int getRevision() const { return _revision; } + int getRevision() const + { + return _revision; + } /// Signal on any addition or removal of command - boost::signals2::signal signalChanged; + boost::signals2::signal signalChanged; /// Signal to Python command on first workbench activation - boost::signals2::signal signalPyCmdInitialized; + boost::signals2::signal signalPyCmdInitialized; - /** + /** * Returns a pointer to a conflicting command, or nullptr if there is no conflict. - * In the case of multiple conflicts, only the first is returned. + * In the case of multiple conflicts, only the first is returned. * \param accel The accelerator to check * \param ignore (optional) A command to ignore matches with */ - const Command* checkAcceleratorForConflicts(const char* accel, const Command *ignore = nullptr) const; + const Command* checkAcceleratorForConflicts(const char* accel, const Command* ignore = nullptr) const; /** * Returns the first available command name for a new macro (e.g. starting from 1, @@ -924,12 +1043,12 @@ private: /// Destroys all commands in the manager and empties the list. void clearCommands(); std::map _sCommands; - std::map > _sCommandModes; + std::map> _sCommandModes; int _revision = 0; }; -} // namespace Gui +} // namespace Gui /** The Command Macro Standard @@ -937,111 +1056,141 @@ private: * The parameters are the class name. * @author Jürgen Riegel */ -#define DEF_STD_CMD(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro Standard + isActive() * This macro makes it easier to define a new command. * The parameters are the class name * @author Jürgen Riegel */ -#define DEF_STD_CMD_A(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual bool isActive(void);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD_A(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual bool isActive(void); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro Standard + createAction() * This macro makes it easier to define a new command. * The parameters are the class name * @author Jürgen Riegel */ -#define DEF_STD_CMD_C(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual Gui::Action * createAction(void);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD_C(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual Gui::Action* createAction(void); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro Standard + isActive() + createAction() * This macro makes it easier to define a new command. * The parameters are the class name * @author Werner Mayer */ -#define DEF_STD_CMD_AC(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual bool isActive(void);\ - virtual Gui::Action * createAction(void);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD_AC(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual bool isActive(void); \ + virtual Gui::Action* createAction(void); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro Standard + isActive() + updateAction() * This macro makes it easier to define a new command. * The parameters are the class name * @author Werner Mayer */ -#define DEF_STD_CMD_AU(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual void updateAction(int mode); \ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual bool isActive(void);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD_AU(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual void updateAction(int mode); \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual bool isActive(void); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro Standard + isActive() + createAction() * + languageChange() @@ -1049,24 +1198,30 @@ private:\ * The parameters are the class name * @author Werner Mayer */ -#define DEF_STD_CMD_ACL(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual void languageChange(); \ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual bool isActive(void);\ - virtual Gui::Action * createAction(void);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD_ACL(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual void languageChange(); \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual bool isActive(void); \ + virtual Gui::Action* createAction(void); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro Standard + isActive() + createAction() * + languageChange() + updateAction() @@ -1074,25 +1229,31 @@ private:\ * The parameters are the class name * @author Werner Mayer */ -#define DEF_STD_CMD_ACLU(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual void languageChange(); \ - virtual void updateAction(int mode); \ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual bool isActive(void);\ - virtual Gui::Action * createAction(void);\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_STD_CMD_ACLU(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual void languageChange(); \ + virtual void updateAction(int mode); \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual bool isActive(void); \ + virtual Gui::Action* createAction(void); \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; /** The Command Macro view * This macro makes it easier to define a new command for the 3D View @@ -1100,25 +1261,31 @@ private:\ * The parameters are the class name * @author Jürgen Riegel */ -#define DEF_3DV_CMD(X) class X : public Gui::Command \ -{\ -public:\ - X();\ - virtual ~X(){}\ - virtual const char* className() const\ - { return #X; }\ -protected: \ - virtual void activated(int iMsg);\ - virtual bool isActive(void)\ - {\ - Gui::MDIView* view = Gui::getMainWindow()->activeWindow();\ - return view && view->isDerivedFrom();\ - }\ -private:\ - X(const X&) = delete;\ - X(X&&) = delete;\ - X& operator= (const X&) = delete;\ - X& operator= (X&&) = delete;\ -}; +#define DEF_3DV_CMD(X) \ + class X: public Gui::Command \ + { \ + public: \ + X(); \ + virtual ~X() \ + {} \ + virtual const char* className() const \ + { \ + return #X; \ + } \ +\ + protected: \ + virtual void activated(int iMsg); \ + virtual bool isActive(void) \ + { \ + Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); \ + return view && view->isDerivedFrom(); \ + } \ +\ + private: \ + X(const X&) = delete; \ + X(X&&) = delete; \ + X& operator=(const X&) = delete; \ + X& operator=(X&&) = delete; \ + }; -#endif // GUI_COMMAND_H +#endif // GUI_COMMAND_H diff --git a/src/Gui/Command.pyi b/src/Gui/Command.pyi index 3ff64ae94d..33e6d0788e 100644 --- a/src/Gui/Command.pyi +++ b/src/Gui/Command.pyi @@ -2,7 +2,6 @@ from Base.Metadata import constmethod from Base.PyObjectBase import PyObjectBase from typing import Any, Dict, List, Optional - class Command(PyObjectBase): """ FreeCAD Python wrapper of Command functions diff --git a/src/Gui/CommandActionPy.h b/src/Gui/CommandActionPy.h index 62756560ee..5ddacb620a 100644 --- a/src/Gui/CommandActionPy.h +++ b/src/Gui/CommandActionPy.h @@ -31,7 +31,7 @@ namespace Gui { class Command; -class CommandActionPy : public Py::PythonClass +class CommandActionPy: public Py::PythonClass { public: static void init_type(); @@ -55,6 +55,6 @@ private: Command* cmd = nullptr; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_COMMANDACTIONPY_H +#endif // GUI_COMMANDACTIONPY_H diff --git a/src/Gui/CommandCompleter.cpp b/src/Gui/CommandCompleter.cpp index 4027601b4c..cfcbc69311 100644 --- a/src/Gui/CommandCompleter.cpp +++ b/src/Gui/CommandCompleter.cpp @@ -20,10 +20,10 @@ * * ****************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Application.h" #include "ShortcutManager.h" @@ -34,10 +34,12 @@ using namespace Gui; -namespace { +namespace +{ -struct CmdInfo { - Command *cmd = nullptr; +struct CmdInfo +{ + Command* cmd = nullptr; QIcon icon; bool iconChecked = false; }; @@ -46,7 +48,7 @@ int _CommandRevision; const int CommandNameRole = Qt::UserRole; bool _ShortcutSignalConnected = false; -class CommandModel : public QAbstractItemModel +class CommandModel: public QAbstractItemModel { int revision = 0; @@ -57,94 +59,101 @@ public: update(); if (!_ShortcutSignalConnected) { _ShortcutSignalConnected = true; - QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, []{_CommandRevision = 0;}); + QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, [] { + _CommandRevision = 0; + }); } } void update() { - auto &manager = Application::Instance->commandManager(); - if (revision == _CommandRevision && _CommandRevision == manager.getRevision()) + auto& manager = Application::Instance->commandManager(); + if (revision == _CommandRevision && _CommandRevision == manager.getRevision()) { return; + } beginResetModel(); revision = manager.getRevision(); if (revision != _CommandRevision) { _CommandRevision = revision; _CommandRevision = manager.getRevision(); _Commands.clear(); - for (auto &v : manager.getCommands()) { + for (auto& v : manager.getCommands()) { _Commands.emplace_back(); - auto &info = _Commands.back(); + auto& info = _Commands.back(); info.cmd = v.second; } } endResetModel(); } - QModelIndex parent(const QModelIndex &) const override + QModelIndex parent(const QModelIndex&) const override { return {}; } - QVariant data(const QModelIndex & index, int role) const override + QVariant data(const QModelIndex& index, int role) const override { - if (index.row() < 0 || index.row() >= (int)_Commands.size()) + if (index.row() < 0 || index.row() >= (int)_Commands.size()) { return {}; - - auto &info = _Commands[index.row()]; - - switch(role) { - case Qt::DisplayRole: - case Qt::EditRole: { - QString title = QStringLiteral("%1 (%2)").arg( - Action::commandMenuText(info.cmd), - QString::fromUtf8(info.cmd->getName())); - QString shortcut = info.cmd->getShortcut(); - if (!shortcut.isEmpty()) - title += QStringLiteral(" (%1)").arg(shortcut); - return title; } - case Qt::ToolTipRole: - return Action::commandToolTip(info.cmd); - case Qt::DecorationRole: - if (!info.iconChecked) { - info.iconChecked = true; - if(info.cmd->getPixmap()) - info.icon = BitmapFactory().iconFromTheme(info.cmd->getPixmap()); + auto& info = _Commands[index.row()]; + + switch (role) { + case Qt::DisplayRole: + case Qt::EditRole: { + QString title = QStringLiteral("%1 (%2)").arg( + Action::commandMenuText(info.cmd), + QString::fromUtf8(info.cmd->getName()) + ); + QString shortcut = info.cmd->getShortcut(); + if (!shortcut.isEmpty()) { + title += QStringLiteral(" (%1)").arg(shortcut); + } + return title; } - return info.icon; + case Qt::ToolTipRole: + return Action::commandToolTip(info.cmd); - case CommandNameRole: - return QByteArray(info.cmd->getName()); + case Qt::DecorationRole: + if (!info.iconChecked) { + info.iconChecked = true; + if (info.cmd->getPixmap()) { + info.icon = BitmapFactory().iconFromTheme(info.cmd->getPixmap()); + } + } + return info.icon; - default: - break; + case CommandNameRole: + return QByteArray(info.cmd->getName()); + + default: + break; } return {}; } - QModelIndex index(int row, int, const QModelIndex &) const override + QModelIndex index(int row, int, const QModelIndex&) const override { return this->createIndex(row, 0); } - int rowCount(const QModelIndex &) const override + int rowCount(const QModelIndex&) const override { return (int)(_Commands.size()); } - int columnCount(const QModelIndex &) const override + int columnCount(const QModelIndex&) const override { return 1; } }; -} // anonymous namespace +} // anonymous namespace // -------------------------------------------------------------------- -CommandCompleter::CommandCompleter(QLineEdit *lineedit, QObject *parent) +CommandCompleter::CommandCompleter(QLineEdit* lineedit, QObject* parent) : QCompleter(parent) { this->setModel(new CommandModel(this)); @@ -153,84 +162,90 @@ CommandCompleter::CommandCompleter(QLineEdit *lineedit, QObject *parent) this->setCompletionMode(QCompleter::PopupCompletion); this->setWidget(lineedit); connect(lineedit, &QLineEdit::textEdited, this, &CommandCompleter::onTextChanged); - connect(this, qOverload(&CommandCompleter::activated), - this, &CommandCompleter::onCommandActivated); - connect(this, qOverload(&CommandCompleter::highlighted), - lineedit, &QLineEdit::setText); + connect( + this, + qOverload(&CommandCompleter::activated), + this, + &CommandCompleter::onCommandActivated + ); + connect(this, qOverload(&CommandCompleter::highlighted), lineedit, &QLineEdit::setText); } -bool CommandCompleter::eventFilter(QObject *o, QEvent *ev) +bool CommandCompleter::eventFilter(QObject* o, QEvent* ev) { - if (ev->type() == QEvent::KeyPress - && (o == this->widget() || o == this->popup())) - { - QKeyEvent * ke = static_cast(ev); - switch(ke->key()) { - case Qt::Key_Escape: { - auto edit = qobject_cast(this->widget()); - if (edit && edit->text().size()) { - edit->setText(QString()); - popup()->hide(); - return true; - } else if (popup()->isVisible()) { - popup()->hide(); - return true; + if (ev->type() == QEvent::KeyPress && (o == this->widget() || o == this->popup())) { + QKeyEvent* ke = static_cast(ev); + switch (ke->key()) { + case Qt::Key_Escape: { + auto edit = qobject_cast(this->widget()); + if (edit && edit->text().size()) { + edit->setText(QString()); + popup()->hide(); + return true; + } + else if (popup()->isVisible()) { + popup()->hide(); + return true; + } + break; } - break; - } - case Qt::Key_Tab: { - if (this->popup()->isVisible()) { - QKeyEvent kevent(ke->type(), Qt::Key_Down, Qt::NoModifier); - qApp->sendEvent(this->popup(), &kevent); - return true; + case Qt::Key_Tab: { + if (this->popup()->isVisible()) { + QKeyEvent kevent(ke->type(), Qt::Key_Down, Qt::NoModifier); + qApp->sendEvent(this->popup(), &kevent); + return true; + } + break; } - break; - } - case Qt::Key_Backtab: { - if (this->popup()->isVisible()) { - QKeyEvent kevent(ke->type(), Qt::Key_Up, Qt::NoModifier); - qApp->sendEvent(this->popup(), &kevent); - return true; + case Qt::Key_Backtab: { + if (this->popup()->isVisible()) { + QKeyEvent kevent(ke->type(), Qt::Key_Up, Qt::NoModifier); + qApp->sendEvent(this->popup(), &kevent); + return true; + } + break; } - break; - } - case Qt::Key_Enter: - case Qt::Key_Return: - if (o == this->widget()) { - auto index = currentIndex(); - if (index.isValid()) - onCommandActivated(index); - else - complete(); - ev->setAccepted(true); - return true; - } - default: - break; + case Qt::Key_Enter: + case Qt::Key_Return: + if (o == this->widget()) { + auto index = currentIndex(); + if (index.isValid()) { + onCommandActivated(index); + } + else { + complete(); + } + ev->setAccepted(true); + return true; + } + default: + break; } } return QCompleter::eventFilter(o, ev); } -void CommandCompleter::onCommandActivated(const QModelIndex &index) +void CommandCompleter::onCommandActivated(const QModelIndex& index) { QByteArray name = completionModel()->data(index, CommandNameRole).toByteArray(); Q_EMIT commandActivated(name); } -void CommandCompleter::onTextChanged(const QString &txt) +void CommandCompleter::onTextChanged(const QString& txt) { // Do not activate completer if less than 3 characters for better // performance. - if (txt.size() < 3 || !widget()) + if (txt.size() < 3 || !widget()) { return; + } static_cast(this->model())->update(); this->setCompletionPrefix(txt); QRect rect = widget()->rect(); - if (rect.width() < 300) + if (rect.width() < 300) { rect.setWidth(300); + } this->complete(rect); } diff --git a/src/Gui/CommandCompleter.h b/src/Gui/CommandCompleter.h index 0537055032..77311b2465 100644 --- a/src/Gui/CommandCompleter.h +++ b/src/Gui/CommandCompleter.h @@ -28,7 +28,8 @@ class QLineEdit; -namespace Gui { +namespace Gui +{ /** * Command name auto completer. @@ -37,24 +38,24 @@ namespace Gui { * completer supports keyword search in command title, internal name, and * shortcut. */ -class GuiExport CommandCompleter : public QCompleter +class GuiExport CommandCompleter: public QCompleter { Q_OBJECT public: - explicit CommandCompleter(QLineEdit *edit, QObject *parent = nullptr); + explicit CommandCompleter(QLineEdit* edit, QObject* parent = nullptr); Q_SIGNALS: /// Triggered when a command is selected in the completer - void commandActivated(const QByteArray &name); + void commandActivated(const QByteArray& name); protected Q_SLOTS: - void onTextChanged(const QString &); - void onCommandActivated(const QModelIndex &); + void onTextChanged(const QString&); + void onCommandActivated(const QModelIndex&); protected: - bool eventFilter(QObject *, QEvent *ev) override; + bool eventFilter(QObject*, QEvent* ev) override; }; -} // namespace Gui +} // namespace Gui #endif diff --git a/src/Gui/CommandDoc.cpp b/src/Gui/CommandDoc.cpp index 870cecff0d..7993916936 100644 --- a/src/Gui/CommandDoc.cpp +++ b/src/Gui/CommandDoc.cpp @@ -20,14 +20,14 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -78,17 +78,17 @@ using namespace Gui; DEF_STD_CMD(StdCmdOpen) StdCmdOpen::StdCmdOpen() - : Command("Std_Open") + : Command("Std_Open") { // setting the - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Open…"); - sToolTipText = QT_TR_NOOP("Opens a document or imports files"); - sWhatsThis = "Std_Open"; - sStatusTip = sToolTipText; - sPixmap = "document-open"; - sAccel = keySequenceToAccel(QKeySequence::Open); - eType = NoTransaction; + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Open…"); + sToolTipText = QT_TR_NOOP("Opens a document or imports files"); + sWhatsThis = "Std_Open"; + sStatusTip = sToolTipText; + sPixmap = "document-open"; + sAccel = keySequenceToAccel(QKeySequence::Open); + eType = NoTransaction; } void StdCmdOpen::activated(int iMsg) @@ -109,7 +109,7 @@ void StdCmdOpen::activated(int iMsg) filetypes.erase(it); filetypes.insert(filetypes.begin(), "FCStd"); } - for (it=filetypes.begin();it != filetypes.end();++it) { + for (it = filetypes.begin(); it != filetypes.end(); ++it) { formatList += QLatin1String(" *."); formatList += QLatin1String(it->c_str()); } @@ -119,7 +119,7 @@ void StdCmdOpen::activated(int iMsg) std::map FilterList = App::GetApplication().getImportFilters(); std::map::iterator jt; // Make sure the format name for FCStd is the very first in the list - for (jt=FilterList.begin();jt != FilterList.end();++jt) { + for (jt = FilterList.begin(); jt != FilterList.end(); ++jt) { if (jt->first.find("*.FCStd") != std::string::npos) { formatList += QLatin1String(jt->first.c_str()); formatList += QLatin1String(";;"); @@ -127,15 +127,20 @@ void StdCmdOpen::activated(int iMsg) break; } } - for (jt=FilterList.begin();jt != FilterList.end();++jt) { + for (jt = FilterList.begin(); jt != FilterList.end(); ++jt) { formatList += QLatin1String(jt->first.c_str()); formatList += QLatin1String(";;"); } formatList += QObject::tr(allFiles); QString selectedFilter; - QStringList fileList = FileDialog::getOpenFileNames(getMainWindow(), - QObject::tr("Open document"), QString(), formatList, &selectedFilter); + QStringList fileList = FileDialog::getOpenFileNames( + getMainWindow(), + QObject::tr("Open document"), + QString(), + formatList, + &selectedFilter + ); if (fileList.isEmpty()) { return; } @@ -143,9 +148,11 @@ void StdCmdOpen::activated(int iMsg) // load the files with the associated modules SelectModule::Dict dict = SelectModule::importHandler(fileList, selectedFilter); if (dict.isEmpty()) { - QMessageBox::critical(getMainWindow(), + QMessageBox::critical( + getMainWindow(), qApp->translate("StdCmdOpen", "Cannot open file"), - qApp->translate("StdCmdOpen", "Loading the file %1 is not supported").arg(fileList.front())); + qApp->translate("StdCmdOpen", "Loading the file %1 is not supported").arg(fileList.front()) + ); } else { for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) { @@ -157,7 +164,7 @@ void StdCmdOpen::activated(int iMsg) getGuiApplication()->setStatus(Gui::Application::UserInitiatedOpenDocument, false); - App::Document *doc = App::GetApplication().getActiveDocument(); + App::Document* doc = App::GetApplication().getActiveDocument(); getGuiApplication()->checkPartialRestore(doc); getGuiApplication()->checkRestoreError(doc); @@ -172,16 +179,16 @@ void StdCmdOpen::activated(int iMsg) DEF_STD_CMD_A(StdCmdImport) StdCmdImport::StdCmdImport() - : Command("Std_Import") + : Command("Std_Import") { // setting the - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Import…"); - sToolTipText = QT_TR_NOOP("Imports a file into the active document"); - sWhatsThis = "Std_Import"; - sStatusTip = sToolTipText; - sPixmap = "Std_Import"; - sAccel = "Ctrl+Shift+I"; + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Import…"); + sToolTipText = QT_TR_NOOP("Imports a file into the active document"); + sWhatsThis = "Std_Import"; + sStatusTip = sToolTipText; + sPixmap = "Std_Import"; + sAccel = "Ctrl+Shift+I"; } void StdCmdImport::activated(int iMsg) @@ -197,7 +204,7 @@ void StdCmdImport::activated(int iMsg) std::vector filetypes = App::GetApplication().getImportTypes(); std::vector::const_iterator it; - for (it=filetypes.begin();it != filetypes.end();++it) { + for (it = filetypes.begin(); it != filetypes.end(); ++it) { if (*it != "FCStd") { // ignore the project file format formatList += QLatin1String(" *."); @@ -209,7 +216,7 @@ void StdCmdImport::activated(int iMsg) std::map FilterList = App::GetApplication().getImportFilters(); std::map::const_iterator jt; - for (jt=FilterList.begin();jt != FilterList.end();++jt) { + for (jt = FilterList.begin(); jt != FilterList.end(); ++jt) { // ignore the project file format if (jt->first.find("(*.FCStd)") == std::string::npos) { formatList += QLatin1String(jt->first.c_str()); @@ -218,11 +225,19 @@ void StdCmdImport::activated(int iMsg) } formatList += QObject::tr(allFiles); - Base::Reference hPath = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences")->GetGroup("General"); + Base::Reference hPath = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("General"); QString selectedFilter = QString::fromStdString(hPath->GetASCII("FileImportFilter")); - QStringList fileList = FileDialog::getOpenFileNames(getMainWindow(), - QObject::tr("Import file"), QString(), formatList, &selectedFilter); + QStringList fileList = FileDialog::getOpenFileNames( + getMainWindow(), + QObject::tr("Import file"), + QString(), + formatList, + &selectedFilter + ); if (!fileList.isEmpty()) { hPath->SetASCII("FileImportFilter", selectedFilter.toLatin1().constData()); SelectModule::Dict dict = SelectModule::importHandler(fileList, selectedFilter); @@ -230,15 +245,20 @@ void StdCmdImport::activated(int iMsg) bool emptyDoc = (getActiveGuiDocument()->getDocument()->countObjects() == 0); // load the files with the associated modules for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) { - getGuiApplication()->importFrom(it.key().toUtf8(), + getGuiApplication()->importFrom( + it.key().toUtf8(), getActiveGuiDocument()->getDocument()->getName(), - it.value().toLatin1()); + it.value().toLatin1() + ); } if (emptyDoc) { - // only do a view fit if the document was empty before. See also parameter 'AutoFitToView' in importFrom() - std::list views = getActiveGuiDocument()->getMDIViewsOfType(Gui::View3DInventor::getClassTypeId()); - for (const auto & view : views) { + // only do a view fit if the document was empty before. See also parameter + // 'AutoFitToView' in importFrom() + std::list views = getActiveGuiDocument()->getMDIViewsOfType( + Gui::View3DInventor::getClassTypeId() + ); + for (const auto& view : views) { view->viewAll(); } } @@ -258,17 +278,17 @@ bool StdCmdImport::isActive() DEF_STD_CMD_A(StdCmdExport) StdCmdExport::StdCmdExport() - : Command("Std_Export") + : Command("Std_Export") { // setting the - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Export…"); - sToolTipText = QT_TR_NOOP("Exports an object in the active document"); - sWhatsThis = "Std_Export"; - sStatusTip = sToolTipText; - sAccel = "Ctrl+E"; - sPixmap = "Std_Export"; - eType = 0; + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Export…"); + sToolTipText = QT_TR_NOOP("Exports an object in the active document"); + sWhatsThis = "Std_Export"; + sStatusTip = sToolTipText; + sAccel = "Ctrl+E"; + sPixmap = "Std_Export"; + eType = 0; } /** @@ -294,12 +314,18 @@ QString createDefaultExportBasename() auto selection = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); QString exportFormatString; if (selection.size() == 1) { - exportFormatString = QString::fromStdString (App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> - GetASCII("ExportDefaultFilenameSingle", "%F-%P-")); + exportFormatString = QString::fromStdString( + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetASCII("ExportDefaultFilenameSingle", "%F-%P-") + ); } else { - exportFormatString = QString::fromStdString (App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> - GetASCII("ExportDefaultFilenameMultiple", "%F")); + exportFormatString = QString::fromStdString( + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetASCII("ExportDefaultFilenameMultiple", "%F") + ); } // For code simplicity, pull all values we might need @@ -308,21 +334,26 @@ QString createDefaultExportBasename() QString docFilename = QString::fromUtf8(App::GetApplication().getActiveDocument()->getFileName()); QFileInfo fi(docFilename); QString fcstdBasename = fi.completeBaseName(); - if (fcstdBasename.isEmpty()) - fcstdBasename = QString::fromStdString(App::GetApplication().getActiveDocument()->Label.getStrValue()); + if (fcstdBasename.isEmpty()) { + fcstdBasename = QString::fromStdString( + App::GetApplication().getActiveDocument()->Label.getStrValue() + ); + } // %L - the label of the selected object(s) QStringList objectLabels; - for (const auto& object : selection) + for (const auto& object : selection) { objectLabels.push_back(QString::fromStdString(object->Label.getStrValue())); + } // %P - the label of the selected objects and their first parent QStringList parentLabels; for (const auto& object : selection) { auto parents = object->getParents(); QString firstParent; - if (!parents.empty()) + if (!parents.empty()) { firstParent = QString::fromStdString(parents.front().first->Label.getStrValue()); + } parentLabels.append(firstParent + QString::fromStdString(object->Label.getStrValue())); } @@ -350,8 +381,7 @@ QString createDefaultExportBasename() QChar separatorChar = QLatin1Char('-'); // If this format type requires an additional char, read that now (or default to // '-' if the format string ends) - if (formatChar == QLatin1Char('L') || - formatChar == QLatin1Char('P')) { + if (formatChar == QLatin1Char('L') || formatChar == QLatin1Char('P')) { if (i < exportFormatString.size() - 1) { ++i; separatorChar = exportFormatString.at(i); @@ -375,9 +405,10 @@ QString createDefaultExportBasename() defaultFilename.append(localISO8601); } else { - FC_WARN("When parsing default export filename format string, %" - << QString(formatChar).toStdString() - << " is not a known format string."); + FC_WARN( + "When parsing default export filename format string, %" + << QString(formatChar).toStdString() << " is not a known format string." + ); } } } @@ -385,8 +416,9 @@ QString createDefaultExportBasename() // Finally, clean the string so it's valid for all operating systems: QString invalidCharacters = QLatin1String("/\\?%*:|\"<>"); - for (const auto &c : invalidCharacters) - defaultFilename.replace(c,QLatin1String("_")); + for (const auto& c : invalidCharacters) { + defaultFilename.replace(c, QLatin1String("_")); + } return defaultFilename; } @@ -397,9 +429,14 @@ void StdCmdExport::activated(int iMsg) auto selection = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); if (selection.empty()) { - QMessageBox::warning(Gui::getMainWindow(), + QMessageBox::warning( + Gui::getMainWindow(), QCoreApplication::translate("StdCmdExport", "No selection"), - QCoreApplication::translate("StdCmdExport", "Select objects to export before using the Export command.")); + QCoreApplication::translate( + "StdCmdExport", + "Select objects to export before using the Export command." + ) + ); return; } @@ -411,20 +448,24 @@ void StdCmdExport::activated(int iMsg) // fill the list of registered suffixes QStringList filterList; std::map filterMap = App::GetApplication().getExportFilters(); - for (const auto &filter : filterMap) { + for (const auto& filter : filterMap) { // ignore the project file format if (filter.first.find("(*.FCStd)") == std::string::npos) { filterList << QString::fromStdString(filter.first); } } QString formatList = filterList.join(QLatin1String(";;")); - Base::Reference hPath = - App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("General"); + Base::Reference hPath = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("General"); QString selectedFilter; if (!exportInfo.filter.empty()) { selectedFilter = QString::fromStdString(exportInfo.filter); - } else { + } + else { selectedFilter = QString::fromStdString(hPath->GetASCII("FileExportFilter")); } @@ -454,32 +495,38 @@ void StdCmdExport::activated(int iMsg) exportPath = Gui::FileDialog::getWorkingDirectory(); } - if (exportInfo.generatedName || exportInfo.object != toExport) { /*<- static, true on first call*/ + if (exportInfo.generatedName + || exportInfo.object != toExport) { /*<- static, true on first call*/ defaultFilename = exportPath + QLatin1Char('/') + createDefaultExportBasename(); // Append the last extension used, if there is one. if (!exportInfo.filename.empty()) { QFileInfo lastExportFile(QString::fromStdString(exportInfo.filename)); - if (!lastExportFile.suffix().isEmpty()) + if (!lastExportFile.suffix().isEmpty()) { defaultFilename += QLatin1String(".") + lastExportFile.suffix(); + } } filenameWasGenerated = true; } - } else { + } + else { defaultFilename = QString::fromStdString(exportInfo.filename); } - // Launch the file selection modal dialog - QString filename = FileDialog::getSaveFileName(getMainWindow(), - QObject::tr("Export file"), defaultFilename, formatList, &selectedFilter); + // Launch the file selection modal dialog + QString filename = FileDialog::getSaveFileName( + getMainWindow(), + QObject::tr("Export file"), + defaultFilename, + formatList, + &selectedFilter + ); if (!filename.isEmpty()) { hPath->SetASCII("FileExportFilter", selectedFilter.toLatin1().constData()); SelectModule::Dict dict = SelectModule::exportHandler(filename, selectedFilter); // export the files with the associated modules for (SelectModule::Dict::iterator it = dict.begin(); it != dict.end(); ++it) { - getGuiApplication()->exportTo(it.key().toUtf8(), - doc->getName(), - it.value().toLatin1()); + getGuiApplication()->exportTo(it.key().toUtf8(), doc->getName(), it.value().toLatin1()); } // Keep a record of if the user used our suggested generated filename. If they @@ -487,8 +534,9 @@ void StdCmdExport::activated(int iMsg) // there is one. QFileInfo defaultExportFI(defaultFilename); QFileInfo thisExportFI(filename); - - if (filenameWasGenerated && thisExportFI.completeBaseName() != defaultExportFI.completeBaseName()) { + + if (filenameWasGenerated + && thisExportFI.completeBaseName() != defaultExportFI.completeBaseName()) { filenameWasGenerated = false; } @@ -513,17 +561,17 @@ bool StdCmdExport::isActive() DEF_STD_CMD_A(StdCmdMergeProjects) StdCmdMergeProjects::StdCmdMergeProjects() - : Command("Std_MergeProjects") + : Command("Std_MergeProjects") { - sAppModule = "File"; - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Merge Document"); + sAppModule = "File"; + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Merge Document"); - sToolTipText = QT_TR_NOOP("Merges another FreeCAD document into the active one"); + sToolTipText = QT_TR_NOOP("Merges another FreeCAD document into the active one"); - sWhatsThis = "Std_MergeProjects"; - sStatusTip = sToolTipText; - sPixmap = "Std_MergeProjects"; + sWhatsThis = "Std_MergeProjects"; + sStatusTip = sToolTipText; + sPixmap = "Std_MergeProjects"; } void StdCmdMergeProjects::activated(int iMsg) @@ -531,18 +579,23 @@ void StdCmdMergeProjects::activated(int iMsg) Q_UNUSED(iMsg); QString exe = qApp->applicationName(); - QString project = FileDialog::getOpenFileName(Gui::getMainWindow(), - QString::fromUtf8(QT_TR_NOOP("Merge document")), FileDialog::getWorkingDirectory(), - QString::fromUtf8(QT_TR_NOOP("%1 document (*.FCStd)")).arg(exe)); + QString project = FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString::fromUtf8(QT_TR_NOOP("Merge document")), + FileDialog::getWorkingDirectory(), + QString::fromUtf8(QT_TR_NOOP("%1 document (*.FCStd)")).arg(exe) + ); if (!project.isEmpty()) { FileDialog::setWorkingDirectory(project); App::Document* doc = App::GetApplication().getActiveDocument(); QFileInfo info(QString::fromUtf8(doc->FileName.getValue())); QFileInfo proj(project); if (proj == info) { - QMessageBox::critical(Gui::getMainWindow(), + QMessageBox::critical( + Gui::getMainWindow(), QString::fromUtf8(QT_TR_NOOP("Merge document")), - QString::fromUtf8(QT_TR_NOOP("Cannot merge document with itself."))); + QString::fromUtf8(QT_TR_NOOP("Cannot merge document with itself.")) + ); return; } @@ -568,17 +621,17 @@ bool StdCmdMergeProjects::isActive() DEF_STD_CMD_A(StdCmdDependencyGraph) StdCmdDependencyGraph::StdCmdDependencyGraph() - : Command("Std_DependencyGraph") + : Command("Std_DependencyGraph") { // setting the - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Dependency Gra&ph"); + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Dependency Gra&ph"); - sToolTipText = QT_TR_NOOP("Shows the dependency graph of the objects in the active document"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_DependencyGraph"; - eType = 0; - sPixmap = "Std_DependencyGraph"; + sToolTipText = QT_TR_NOOP("Shows the dependency graph of the objects in the active document"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_DependencyGraph"; + eType = 0; + sPixmap = "Std_DependencyGraph"; } void StdCmdDependencyGraph::activated(int iMsg) @@ -586,7 +639,7 @@ void StdCmdDependencyGraph::activated(int iMsg) Q_UNUSED(iMsg); App::Document* doc = App::GetApplication().getActiveDocument(); auto view = new Gui::GraphvizView(*doc); - view->setWindowTitle(qApp->translate("Std_DependencyGraph","Dependency Graph")); + view->setWindowTitle(qApp->translate("Std_DependencyGraph", "Dependency Graph")); getMainWindow()->addWindow(view); } @@ -602,15 +655,15 @@ bool StdCmdDependencyGraph::isActive() DEF_STD_CMD_A(StdCmdExportDependencyGraph) StdCmdExportDependencyGraph::StdCmdExportDependencyGraph() - : Command("Std_ExportDependencyGraph") + : Command("Std_ExportDependencyGraph") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Export Dependency &Graph"); - sToolTipText = QT_TR_NOOP("Exports the dependency graph as a Graphviz (.gv) file"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ExportDependencyGraph"; - eType = 0; - //sPixmap = "Std_ExportDependencyGraph"; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Export Dependency &Graph"); + sToolTipText = QT_TR_NOOP("Exports the dependency graph as a Graphviz (.gv) file"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ExportDependencyGraph"; + eType = 0; + // sPixmap = "Std_ExportDependencyGraph"; } void StdCmdExportDependencyGraph::activated(int iMsg) @@ -618,7 +671,12 @@ void StdCmdExportDependencyGraph::activated(int iMsg) Q_UNUSED(iMsg); App::Document* doc = App::GetApplication().getActiveDocument(); QString format = QStringLiteral("%1 (*.gv)").arg(Gui::GraphvizView::tr("Graphviz format")); - QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), Gui::GraphvizView::tr("Export graph"), QString(), format); + QString fn = Gui::FileDialog::getSaveFileName( + Gui::getMainWindow(), + Gui::GraphvizView::tr("Export graph"), + QString(), + format + ); if (!fn.isEmpty()) { QFile file(fn); if (file.open(QFile::WriteOnly)) { @@ -643,15 +701,15 @@ bool StdCmdExportDependencyGraph::isActive() DEF_STD_CMD(StdCmdNew) StdCmdNew::StdCmdNew() - :Command("Std_New") + : Command("Std_New") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("&New Document"); - sToolTipText = QT_TR_NOOP("Creates a new empty document"); - sWhatsThis = "Std_New"; - sStatusTip = sToolTipText; - sPixmap = "document-new"; - sAccel = keySequenceToAccel(QKeySequence::New); + sGroup = "File"; + sMenuText = QT_TR_NOOP("&New Document"); + sToolTipText = QT_TR_NOOP("Creates a new empty document"); + sWhatsThis = "Std_New"; + sStatusTip = sToolTipText; + sPixmap = "document-new"; + sAccel = keySequenceToAccel(QKeySequence::New); } void StdCmdNew::activated(int iMsg) @@ -659,12 +717,15 @@ void StdCmdNew::activated(int iMsg) Q_UNUSED(iMsg); QString cmd; cmd = QStringLiteral("App.newDocument()"); - runCommand(Command::Doc,cmd.toUtf8()); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewDefaultOrientation()"); + runCommand(Command::Doc, cmd.toUtf8()); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewDefaultOrientation()"); - ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - if (hViewGrp->GetBool("ShowAxisCross")) - doCommand(Command::Gui,"Gui.ActiveDocument.ActiveView.setAxisCross(True)"); + ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + if (hViewGrp->GetBool("ShowAxisCross")) { + doCommand(Command::Gui, "Gui.ActiveDocument.ActiveView.setAxisCross(True)"); + } } //=========================================================================== @@ -673,22 +734,22 @@ void StdCmdNew::activated(int iMsg) DEF_STD_CMD_A(StdCmdSave) StdCmdSave::StdCmdSave() - :Command("Std_Save") + : Command("Std_Save") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Save"); - sToolTipText = QT_TR_NOOP("Saves the active document"); - sWhatsThis = "Std_Save"; - sStatusTip = sToolTipText; - sPixmap = "document-save"; - sAccel = keySequenceToAccel(QKeySequence::Save); - eType = 0; + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Save"); + sToolTipText = QT_TR_NOOP("Saves the active document"); + sWhatsThis = "Std_Save"; + sStatusTip = sToolTipText; + sPixmap = "document-save"; + sAccel = keySequenceToAccel(QKeySequence::Save); + eType = 0; } void StdCmdSave::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Save\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"Save\")"); } bool StdCmdSave::isActive() @@ -702,22 +763,22 @@ bool StdCmdSave::isActive() DEF_STD_CMD_A(StdCmdSaveAs) StdCmdSaveAs::StdCmdSaveAs() - :Command("Std_SaveAs") + : Command("Std_SaveAs") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Save &As…"); - sToolTipText = QT_TR_NOOP("Saves the active document under a new file name"); - sWhatsThis = "Std_SaveAs"; - sStatusTip = sToolTipText; - sPixmap = "document-save-as"; - sAccel = keySequenceToAccel(QKeySequence::SaveAs); - eType = 0; + sGroup = "File"; + sMenuText = QT_TR_NOOP("Save &As…"); + sToolTipText = QT_TR_NOOP("Saves the active document under a new file name"); + sWhatsThis = "Std_SaveAs"; + sStatusTip = sToolTipText; + sPixmap = "document-save-as"; + sAccel = keySequenceToAccel(QKeySequence::SaveAs); + eType = 0; } void StdCmdSaveAs::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"SaveAs\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"SaveAs\")"); } bool StdCmdSaveAs::isActive() @@ -731,26 +792,26 @@ bool StdCmdSaveAs::isActive() DEF_STD_CMD_A(StdCmdSaveCopy) StdCmdSaveCopy::StdCmdSaveCopy() - :Command("Std_SaveCopy") + : Command("Std_SaveCopy") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Save Cop&y"); + sGroup = "File"; + sMenuText = QT_TR_NOOP("Save Cop&y"); - sToolTipText = QT_TR_NOOP("Saves a copy of the active document under a new file name"); - sWhatsThis = "Std_SaveCopy"; - sStatusTip = sToolTipText; - sPixmap = "Std_SaveCopy"; + sToolTipText = QT_TR_NOOP("Saves a copy of the active document under a new file name"); + sWhatsThis = "Std_SaveCopy"; + sStatusTip = sToolTipText; + sPixmap = "Std_SaveCopy"; } void StdCmdSaveCopy::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"SaveCopy\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"SaveCopy\")"); } bool StdCmdSaveCopy::isActive() { - return ( getActiveGuiDocument() ? true : false ); + return (getActiveGuiDocument() ? true : false); } //=========================================================================== @@ -759,14 +820,14 @@ bool StdCmdSaveCopy::isActive() DEF_STD_CMD_A(StdCmdSaveAll) StdCmdSaveAll::StdCmdSaveAll() - :Command("Std_SaveAll") + : Command("Std_SaveAll") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Sa&ve All"); - sToolTipText = QT_TR_NOOP("Saves all open documents"); - sWhatsThis = "Std_SaveAll"; - sStatusTip = sToolTipText; - sPixmap = "Std_SaveAll"; + sGroup = "File"; + sMenuText = QT_TR_NOOP("Sa&ve All"); + sToolTipText = QT_TR_NOOP("Saves all open documents"); + sWhatsThis = "Std_SaveAll"; + sStatusTip = sToolTipText; + sPixmap = "Std_SaveAll"; } void StdCmdSaveAll::activated(int iMsg) @@ -777,7 +838,7 @@ void StdCmdSaveAll::activated(int iMsg) bool StdCmdSaveAll::isActive() { - return ( getActiveGuiDocument() ? true : false ); + return (getActiveGuiDocument() ? true : false); } @@ -787,15 +848,15 @@ bool StdCmdSaveAll::isActive() DEF_STD_CMD_A(StdCmdRevert) StdCmdRevert::StdCmdRevert() - :Command("Std_Revert") + : Command("Std_Revert") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Rever&t"); - sToolTipText = QT_TR_NOOP("Reverts to the saved version of this file"); - sWhatsThis = "Std_Revert"; - sStatusTip = sToolTipText; - sPixmap = "Std_Revert"; - eType = NoTransaction; + sGroup = "File"; + sMenuText = QT_TR_NOOP("Rever&t"); + sToolTipText = QT_TR_NOOP("Reverts to the saved version of this file"); + sWhatsThis = "Std_Revert"; + sStatusTip = sToolTipText; + sPixmap = "Std_Revert"; + eType = NoTransaction; } void StdCmdRevert::activated(int iMsg) @@ -803,19 +864,22 @@ void StdCmdRevert::activated(int iMsg) Q_UNUSED(iMsg); QMessageBox msgBox(Gui::getMainWindow()); msgBox.setIcon(QMessageBox::Question); - msgBox.setWindowTitle(qApp->translate("Std_Revert","Revert Document")); - msgBox.setText(qApp->translate("Std_Revert","This will discard all the changes since the last file save.")); - msgBox.setInformativeText(qApp->translate("Std_Revert","Continue?")); + msgBox.setWindowTitle(qApp->translate("Std_Revert", "Revert Document")); + msgBox.setText( + qApp->translate("Std_Revert", "This will discard all the changes since the last file save.") + ); + msgBox.setInformativeText(qApp->translate("Std_Revert", "Continue?")); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); - if (ret == QMessageBox::Yes) - doCommand(Command::App,"App.ActiveDocument.restore()"); + if (ret == QMessageBox::Yes) { + doCommand(Command::App, "App.ActiveDocument.restore()"); + } } bool StdCmdRevert::isActive() { - return ( getActiveGuiDocument() ? true : false ); + return (getActiveGuiDocument() ? true : false); } //=========================================================================== @@ -825,16 +889,16 @@ bool StdCmdRevert::isActive() DEF_STD_CMD_A(StdCmdProjectInfo) StdCmdProjectInfo::StdCmdProjectInfo() - :Command("Std_ProjectInfo") + : Command("Std_ProjectInfo") { - // setting the - sGroup = "File"; - sMenuText = QT_TR_NOOP("Doc&ument Information"); + // setting the + sGroup = "File"; + sMenuText = QT_TR_NOOP("Doc&ument Information"); - sToolTipText = QT_TR_NOOP("Shows information about the active document"); - sWhatsThis = "Std_ProjectInfo"; - sStatusTip = sToolTipText; - sPixmap = "document-properties"; + sToolTipText = QT_TR_NOOP("Shows information about the active document"); + sWhatsThis = "Std_ProjectInfo"; + sStatusTip = sToolTipText; + sPixmap = "document-properties"; } void StdCmdProjectInfo::activated(int iMsg) @@ -846,7 +910,7 @@ void StdCmdProjectInfo::activated(int iMsg) bool StdCmdProjectInfo::isActive() { - return ( getActiveGuiDocument() ? true : false ); + return (getActiveGuiDocument() ? true : false); } //=========================================================================== @@ -856,16 +920,16 @@ bool StdCmdProjectInfo::isActive() DEF_STD_CMD_A(StdCmdProjectUtil) StdCmdProjectUtil::StdCmdProjectUtil() - :Command("Std_ProjectUtil") + : Command("Std_ProjectUtil") { // setting the - sGroup = "Tools"; - sWhatsThis = "Std_ProjectUtil"; - sMenuText = QT_TR_NOOP("Do&cument Utility"); + sGroup = "Tools"; + sWhatsThis = "Std_ProjectUtil"; + sMenuText = QT_TR_NOOP("Do&cument Utility"); - sToolTipText = QT_TR_NOOP("Extracts or creates document files"); - sStatusTip = sToolTipText; - sPixmap = "Std_ProjectUtil"; + sToolTipText = QT_TR_NOOP("Extracts or creates document files"); + sStatusTip = sToolTipText; + sPixmap = "Std_ProjectUtil"; } void StdCmdProjectUtil::activated(int iMsg) @@ -886,17 +950,17 @@ bool StdCmdProjectUtil::isActive() DEF_STD_CMD_A(StdCmdPrint) StdCmdPrint::StdCmdPrint() - :Command("Std_Print") + : Command("Std_Print") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Print"); + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Print"); - sToolTipText = QT_TR_NOOP("Prints the active document"); - sWhatsThis = "Std_Print"; - sStatusTip = sToolTipText; - sPixmap = "document-print"; - sAccel = keySequenceToAccel(QKeySequence::Print); - eType = 0; + sToolTipText = QT_TR_NOOP("Prints the active document"); + sWhatsThis = "Std_Print"; + sStatusTip = sToolTipText; + sPixmap = "document-print"; + sAccel = keySequenceToAccel(QKeySequence::Print); + eType = 0; } void StdCmdPrint::activated(int iMsg) @@ -919,16 +983,16 @@ bool StdCmdPrint::isActive() DEF_STD_CMD_A(StdCmdPrintPreview) StdCmdPrintPreview::StdCmdPrintPreview() - :Command("Std_PrintPreview") + : Command("Std_PrintPreview") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Print Previe&w"); + sGroup = "File"; + sMenuText = QT_TR_NOOP("Print Previe&w"); - sToolTipText = QT_TR_NOOP("Previews the active document before printing"); - sWhatsThis = "Std_PrintPreview"; - sStatusTip = sToolTipText; - sPixmap = "document-print-preview"; - eType = 0; + sToolTipText = QT_TR_NOOP("Previews the active document before printing"); + sWhatsThis = "Std_PrintPreview"; + sStatusTip = sToolTipText; + sPixmap = "document-print-preview"; + eType = 0; } void StdCmdPrintPreview::activated(int iMsg) @@ -950,16 +1014,16 @@ bool StdCmdPrintPreview::isActive() DEF_STD_CMD_A(StdCmdPrintPdf) StdCmdPrintPdf::StdCmdPrintPdf() - :Command("Std_PrintPdf") + : Command("Std_PrintPdf") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Export P&DF"); + sGroup = "File"; + sMenuText = QT_TR_NOOP("Export P&DF"); - sToolTipText = QT_TR_NOOP("Exports the active document as a PDF file"); - sWhatsThis = "Std_PrintPdf"; - sStatusTip = sToolTipText; - sPixmap = "Std_PrintPdf"; - eType = 0; + sToolTipText = QT_TR_NOOP("Exports the active document as a PDF file"); + sWhatsThis = "Std_PrintPdf"; + sStatusTip = sToolTipText; + sPixmap = "Std_PrintPdf"; + eType = 0; } void StdCmdPrintPdf::activated(int iMsg) @@ -983,21 +1047,21 @@ bool StdCmdPrintPdf::isActive() DEF_STD_CMD_C(StdCmdQuit) StdCmdQuit::StdCmdQuit() - :Command("Std_Quit") + : Command("Std_Quit") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("E&xit"); - sToolTipText = QT_TR_NOOP("Quits the application"); - sWhatsThis = "Std_Quit"; - sStatusTip = sToolTipText; - sPixmap = "application-exit"; - sAccel = keySequenceToAccel(QKeySequence::Quit); - eType = NoTransaction; + sGroup = "File"; + sMenuText = QT_TR_NOOP("E&xit"); + sToolTipText = QT_TR_NOOP("Quits the application"); + sWhatsThis = "Std_Quit"; + sStatusTip = sToolTipText; + sPixmap = "application-exit"; + sAccel = keySequenceToAccel(QKeySequence::Quit); + eType = NoTransaction; } -Action * StdCmdQuit::createAction() +Action* StdCmdQuit::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); pcAction->setMenuRole(QAction::QuitRole); return pcAction; @@ -1017,39 +1081,40 @@ void StdCmdQuit::activated(int iMsg) DEF_STD_CMD_AC(StdCmdUndo) StdCmdUndo::StdCmdUndo() - :Command("Std_Undo") + : Command("Std_Undo") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("&Undo"); - sToolTipText = QT_TR_NOOP("Undoes the previous action"); - sWhatsThis = "Std_Undo"; - sStatusTip = sToolTipText; - sPixmap = "edit-undo"; - sAccel = keySequenceToAccel(QKeySequence::Undo); - eType = ForEdit|NoTransaction; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("&Undo"); + sToolTipText = QT_TR_NOOP("Undoes the previous action"); + sWhatsThis = "Std_Undo"; + sStatusTip = sToolTipText; + sPixmap = "edit-undo"; + sAccel = keySequenceToAccel(QKeySequence::Undo); + eType = ForEdit | NoTransaction; } void StdCmdUndo::activated(int iMsg) { Q_UNUSED(iMsg); -// Application::Instance->slotUndo(); + // Application::Instance->slotUndo(); getGuiApplication()->sendMsgToActiveView("Undo"); } bool StdCmdUndo::isActive() { - return getGuiApplication()->sendHasMsgToActiveView("Undo"); + return getGuiApplication()->sendHasMsgToActiveView("Undo"); } -Action * StdCmdUndo::createAction() +Action* StdCmdUndo::createAction() { - Action *pcAction; + Action* pcAction; - pcAction = new UndoAction(this,getMainWindow()); + pcAction = new UndoAction(this, getMainWindow()); pcAction->setShortcut(QString::fromLatin1(getAccel())); applyCommandData(this->className(), pcAction); - if (getPixmap()) + if (getPixmap()) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getPixmap())); + } return pcAction; } @@ -1061,39 +1126,40 @@ Action * StdCmdUndo::createAction() DEF_STD_CMD_AC(StdCmdRedo) StdCmdRedo::StdCmdRedo() - :Command("Std_Redo") + : Command("Std_Redo") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("&Redo"); - sToolTipText = QT_TR_NOOP("Redoes a previously undone action"); - sWhatsThis = "Std_Redo"; - sStatusTip = sToolTipText; - sPixmap = "edit-redo"; - sAccel = keySequenceToAccel(QKeySequence::Redo); - eType = ForEdit|NoTransaction; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("&Redo"); + sToolTipText = QT_TR_NOOP("Redoes a previously undone action"); + sWhatsThis = "Std_Redo"; + sStatusTip = sToolTipText; + sPixmap = "edit-redo"; + sAccel = keySequenceToAccel(QKeySequence::Redo); + eType = ForEdit | NoTransaction; } void StdCmdRedo::activated(int iMsg) { Q_UNUSED(iMsg); -// Application::Instance->slotRedo(); + // Application::Instance->slotRedo(); getGuiApplication()->sendMsgToActiveView("Redo"); } bool StdCmdRedo::isActive() { - return getGuiApplication()->sendHasMsgToActiveView("Redo"); + return getGuiApplication()->sendHasMsgToActiveView("Redo"); } -Action * StdCmdRedo::createAction() +Action* StdCmdRedo::createAction() { - Action *pcAction; + Action* pcAction; - pcAction = new RedoAction(this,getMainWindow()); + pcAction = new RedoAction(this, getMainWindow()); pcAction->setShortcut(QString::fromLatin1(getAccel())); applyCommandData(this->className(), pcAction); - if (getPixmap()) + if (getPixmap()) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getPixmap())); + } return pcAction; } @@ -1104,15 +1170,15 @@ Action * StdCmdRedo::createAction() DEF_STD_CMD_A(StdCmdCut) StdCmdCut::StdCmdCut() - : Command("Std_Cut") + : Command("Std_Cut") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Cu&t"); - sToolTipText = QT_TR_NOOP("Removes the selection and copies it to the clipboard"); - sWhatsThis = "Std_Cut"; - sStatusTip = sToolTipText; - sPixmap = "edit-cut"; - sAccel = keySequenceToAccel(QKeySequence::Cut); + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Cu&t"); + sToolTipText = QT_TR_NOOP("Removes the selection and copies it to the clipboard"); + sWhatsThis = "Std_Cut"; + sStatusTip = sToolTipText; + sPixmap = "edit-cut"; + sAccel = keySequenceToAccel(QKeySequence::Cut); } void StdCmdCut::activated(int iMsg) @@ -1132,15 +1198,15 @@ bool StdCmdCut::isActive() DEF_STD_CMD_A(StdCmdCopy) StdCmdCopy::StdCmdCopy() - : Command("Std_Copy") + : Command("Std_Copy") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("&Copy"); - sToolTipText = QT_TR_NOOP("Copies the selection to the clipboard"); - sWhatsThis = "Std_Copy"; - sStatusTip = sToolTipText; - sPixmap = "edit-copy"; - sAccel = keySequenceToAccel(QKeySequence::Copy); + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("&Copy"); + sToolTipText = QT_TR_NOOP("Copies the selection to the clipboard"); + sWhatsThis = "Std_Copy"; + sStatusTip = sToolTipText; + sPixmap = "edit-copy"; + sAccel = keySequenceToAccel(QKeySequence::Copy); } void StdCmdCopy::activated(int iMsg) @@ -1148,7 +1214,7 @@ void StdCmdCopy::activated(int iMsg) Q_UNUSED(iMsg); bool done = getGuiApplication()->sendMsgToFocusView("Copy"); if (!done) { - QMimeData * mimeData = getMainWindow()->createMimeDataFromSelection(); + QMimeData* mimeData = getMainWindow()->createMimeDataFromSelection(); QClipboard* cb = QApplication::clipboard(); cb->setMimeData(mimeData); } @@ -1156,8 +1222,9 @@ void StdCmdCopy::activated(int iMsg) bool StdCmdCopy::isActive() { - if (getGuiApplication()->sendHasMsgToFocusView("Copy")) + if (getGuiApplication()->sendHasMsgToFocusView("Copy")) { return true; + } return Selection().hasSelection(); } @@ -1167,15 +1234,15 @@ bool StdCmdCopy::isActive() DEF_STD_CMD_A(StdCmdPaste) StdCmdPaste::StdCmdPaste() - : Command("Std_Paste") + : Command("Std_Paste") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("&Paste"); - sToolTipText = QT_TR_NOOP("Pastes the contents of the clipboard"); - sWhatsThis = "Std_Paste"; - sStatusTip = sToolTipText; - sPixmap = "edit-paste"; - sAccel = keySequenceToAccel(QKeySequence::Paste); + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("&Paste"); + sToolTipText = QT_TR_NOOP("Pastes the contents of the clipboard"); + sWhatsThis = "Std_Paste"; + sStatusTip = sToolTipText; + sPixmap = "edit-paste"; + sAccel = keySequenceToAccel(QKeySequence::Paste); } void StdCmdPaste::activated(int iMsg) @@ -1194,27 +1261,29 @@ void StdCmdPaste::activated(int iMsg) bool StdCmdPaste::isActive() { - if (getGuiApplication()->sendHasMsgToFocusView("Paste")) + if (getGuiApplication()->sendHasMsgToFocusView("Paste")) { return true; + } QClipboard* cb = QApplication::clipboard(); const QMimeData* mime = cb->mimeData(); - if (!mime) + if (!mime) { return false; + } return getMainWindow()->canInsertFromMimeData(mime); } DEF_STD_CMD_A(StdCmdDuplicateSelection) StdCmdDuplicateSelection::StdCmdDuplicateSelection() - :Command("Std_DuplicateSelection") + : Command("Std_DuplicateSelection") { - sAppModule = "Edit"; - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Duplicate Selecti&on"); - sToolTipText = QT_TR_NOOP("Duplicates the selected objects to the active document"); - sWhatsThis = "Std_DuplicateSelection"; - sStatusTip = sToolTipText; - sPixmap = "Std_DuplicateSelection"; + sAppModule = "Edit"; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Duplicate Selecti&on"); + sToolTipText = QT_TR_NOOP("Duplicates the selected objects to the active document"); + sWhatsThis = "Std_DuplicateSelection"; + sStatusTip = sToolTipText; + sPixmap = "Std_DuplicateSelection"; } void StdCmdDuplicateSelection::activated(int iMsg) @@ -1222,31 +1291,40 @@ void StdCmdDuplicateSelection::activated(int iMsg) Q_UNUSED(iMsg); std::vector sel; std::set objSet; - for(auto &s : Selection().getCompleteSelection()) { - if(s.pObject && s.pObject->isAttachedToDocument() && objSet.insert(s.pObject).second) + for (auto& s : Selection().getCompleteSelection()) { + if (s.pObject && s.pObject->isAttachedToDocument() && objSet.insert(s.pObject).second) { sel.push_back(s.pObject); + } } - if(sel.empty()) + if (sel.empty()) { return; + } bool hasXLink = false; Base::FileInfo fi(App::Application::getTempFileName()); { auto all = App::Document::getDependencyList(sel); if (all.size() > sel.size()) { - DlgObjectSelection dlg(sel,getMainWindow()); - if(dlg.exec()!=QDialog::Accepted) + DlgObjectSelection dlg(sel, getMainWindow()); + if (dlg.exec() != QDialog::Accepted) { return; + } sel = dlg.getSelections(); - if(sel.empty()) + if (sel.empty()) { return; + } } std::vector unsaved; - hasXLink = App::PropertyXLink::hasXLink(sel,&unsaved); - if(!unsaved.empty()) { - QMessageBox::critical(getMainWindow(), QObject::tr("Unsaved document"), - QObject::tr("The exported object contains an external link. Save the document." - "at least once before exporting.")); + hasXLink = App::PropertyXLink::hasXLink(sel, &unsaved); + if (!unsaved.empty()) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Unsaved document"), + QObject::tr( + "The exported object contains an external link. Save the document." + "at least once before exporting." + ) + ); return; } @@ -1260,17 +1338,23 @@ void StdCmdDuplicateSelection::activated(int iMsg) App::Document* doc = App::GetApplication().getActiveDocument(); if (doc) { bool proceed = true; - if(hasXLink && !doc->isSaved()) { - auto ret = QMessageBox::question(getMainWindow(), - qApp->translate("Std_DuplicateSelection","Object dependencies"), - qApp->translate("Std_DuplicateSelection", - "To link to external objects, the document must be saved at least once.\n" - "Save the document now?"), - QMessageBox::Yes,QMessageBox::No); - if(ret == QMessageBox::Yes) + if (hasXLink && !doc->isSaved()) { + auto ret = QMessageBox::question( + getMainWindow(), + qApp->translate("Std_DuplicateSelection", "Object dependencies"), + qApp->translate( + "Std_DuplicateSelection", + "To link to external objects, the document must be saved at least once.\n" + "Save the document now?" + ), + QMessageBox::Yes, + QMessageBox::No + ); + if (ret == QMessageBox::Yes) { proceed = Application::Instance->getDocument(doc)->saveAs(); + } } - if(proceed) { + if (proceed) { doc->openTransaction("Duplicate"); // restore objects from file and add to active document Base::ifstream str(fi, std::ios::in | std::ios::binary); @@ -1295,24 +1379,24 @@ bool StdCmdDuplicateSelection::isActive() DEF_STD_CMD_A(StdCmdSelectAll) StdCmdSelectAll::StdCmdSelectAll() - : Command("Std_SelectAll") + : Command("Std_SelectAll") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Select &All"); - sToolTipText = QT_TR_NOOP("Selects all objects in the active document"); - sWhatsThis = "Std_SelectAll"; - sStatusTip = sToolTipText; - sPixmap = "edit-select-all"; - sAccel = "Ctrl+A"; // supersedes shortcuts for text edits - + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Select &All"); + sToolTipText = QT_TR_NOOP("Selects all objects in the active document"); + sWhatsThis = "Std_SelectAll"; + sStatusTip = sToolTipText; + sPixmap = "edit-select-all"; + sAccel = "Ctrl+A"; // supersedes shortcuts for text edits + // this cmd only alters selection, not doc or 3d view - eType = AlterSelection; + eType = AlterSelection; } void StdCmdSelectAll::activated(int iMsg) { Q_UNUSED(iMsg); - + auto* activeDoc = Application::Instance->activeDocument(); if (activeDoc) { auto* editingVP = activeDoc->getInEdit(); @@ -1320,12 +1404,14 @@ void StdCmdSelectAll::activated(int iMsg) return; } } - + // fallback to doc level select SelectionSingleton& rSel = Selection(); App::Document* doc = App::GetApplication().getActiveDocument(); if (doc) { - std::vector objs = doc->getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector objs = doc->getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); rSel.setSelection(doc->getName(), objs); } } @@ -1341,16 +1427,16 @@ bool StdCmdSelectAll::isActive() DEF_STD_CMD_A(StdCmdDelete) StdCmdDelete::StdCmdDelete() - :Command("Std_Delete") + : Command("Std_Delete") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("&Delete"); - sToolTipText = QT_TR_NOOP("Deletes the selected objects"); - sWhatsThis = "Std_Delete"; - sStatusTip = sToolTipText; - sPixmap = "edit-delete"; - sAccel = keySequenceToAccel(QtTools::deleteKeySequence()); - eType = ForEdit; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("&Delete"); + sToolTipText = QT_TR_NOOP("Deletes the selected objects"); + sWhatsThis = "Std_Delete"; + sStatusTip = sToolTipText; + sPixmap = "edit-delete"; + sAccel = keySequenceToAccel(QtTools::deleteKeySequence()); + eType = ForEdit; } void StdCmdDelete::activated(int iMsg) @@ -1369,12 +1455,13 @@ void StdCmdDelete::activated(int iMsg) Gui::getMainWindow()->setUpdatesEnabled(false); auto editDoc = Application::Instance->editDocument(); - ViewProviderDocumentObject *vpedit = nullptr; - if(editDoc) + ViewProviderDocumentObject* vpedit = nullptr; + if (editDoc) { vpedit = freecad_cast(editDoc->getInEdit()); - if(vpedit && !vpedit->acceptDeletionsInEdit()) { - for(auto &sel : Selection().getSelectionEx(editDoc->getDocument()->getName())) { - if(sel.getObject() == vpedit->getObject()) { + } + if (vpedit && !vpedit->acceptDeletionsInEdit()) { + for (auto& sel : Selection().getSelectionEx(editDoc->getDocument()->getName())) { + if (sel.getObject() == vpedit->getObject()) { if (!sel.getSubNames().empty()) { vpedit->onDelete(sel.getSubNames()); docs.insert(editDoc->getDocument()); @@ -1382,96 +1469,122 @@ void StdCmdDelete::activated(int iMsg) break; } } - } else { + } + else { std::set affectedLabels; bool more = false; auto sels = Selection().getSelectionEx(); bool autoDeletion = true; - for(auto &sel : sels) { + for (auto& sel : sels) { auto obj = sel.getObject(); - if (obj == nullptr){ - Base::Console().developerWarning("StdCmdDelete::activated", - "App::DocumentObject pointer is nullptr\n"); + if (obj == nullptr) { + Base::Console().developerWarning( + "StdCmdDelete::activated", + "App::DocumentObject pointer is nullptr\n" + ); continue; } - for(auto parent : obj->getInList()) { - if(!Selection().isSelected(parent)) { + for (auto parent : obj->getInList()) { + if (!Selection().isSelected(parent)) { ViewProvider* vp = Application::Instance->getViewProvider(parent); if (vp && !vp->canDelete(obj)) { autoDeletion = false; QString label; - if(parent->getDocument() != obj->getDocument()) + if (parent->getDocument() != obj->getDocument()) { label = QLatin1String(parent->getFullName().c_str()); - else + } + else { label = QLatin1String(parent->getNameInDocument()); - if(parent->Label.getStrValue() != parent->getNameInDocument()) + } + if (parent->Label.getStrValue() != parent->getNameInDocument()) { label += QStringLiteral(" (%1)").arg( - QString::fromUtf8(parent->Label.getValue())); + QString::fromUtf8(parent->Label.getValue()) + ); + } affectedLabels.insert(label); - if(affectedLabels.size()>=10) { + if (affectedLabels.size() >= 10) { more = true; break; } } } } - if(more) + if (more) { break; + } } if (!autoDeletion) { QString bodyMessage; QTextStream bodyMessageStream(&bodyMessage); - bodyMessageStream << qApp->translate("Std_Delete", - "The following referencing objects might break.\n\n" - "Continue?\n"); - for (const auto ¤tLabel : affectedLabels) + bodyMessageStream << qApp->translate( + "Std_Delete", + "The following referencing objects might break.\n\n" + "Continue?\n" + ); + for (const auto& currentLabel : affectedLabels) { bodyMessageStream << '\n' << currentLabel; - if(more) + } + if (more) { bodyMessageStream << "\n..."; + } - auto ret = QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Std_Delete", "Object dependencies"), bodyMessage, - QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::Yes) + auto ret = QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Std_Delete", "Object dependencies"), + bodyMessage, + QMessageBox::Yes, + QMessageBox::No + ); + if (ret == QMessageBox::Yes) { autoDeletion = true; + } } if (autoDeletion) { - for(auto &sel : sels) { + for (auto& sel : sels) { auto obj = sel.getObject(); Gui::ViewProvider* vp = Application::Instance->getViewProvider(obj); if (vp) { // ask the ViewProvider if it wants to do some clean up if (vp->onDelete(sel.getSubNames())) { docs.insert(obj->getDocument()); - FCMD_OBJ_DOC_CMD(obj,"removeObject('" << obj->getNameInDocument() << "')"); + FCMD_OBJ_DOC_CMD(obj, "removeObject('" << obj->getNameInDocument() << "')"); } } } } } - if(!docs.empty()) { - const auto &outList = App::PropertyXLink::getDocumentOutList(); - for(auto it=docs.begin();it!=docs.end();++it) { + if (!docs.empty()) { + const auto& outList = App::PropertyXLink::getDocumentOutList(); + for (auto it = docs.begin(); it != docs.end(); ++it) { auto itd = outList.find(*it); - if(itd!=outList.end()) { - for(auto doc : itd->second) { - if(doc != *it) + if (itd != outList.end()) { + for (auto doc : itd->second) { + if (doc != *it) { docs.erase(doc); + } } } } - for(auto doc : docs) { - FCMD_DOC_CMD(doc,"recompute()"); + for (auto doc : docs) { + FCMD_DOC_CMD(doc, "recompute()"); } } - } catch (const Base::Exception& e) { - QMessageBox::critical(getMainWindow(), QObject::tr("Delete failed"), - QString::fromLatin1(e.what())); + } + catch (const Base::Exception& e) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Delete failed"), + QString::fromLatin1(e.what()) + ); e.reportException(); - } catch (...) { - QMessageBox::critical(getMainWindow(), QObject::tr("Delete failed"), - QStringLiteral("Unknown error")); + } + catch (...) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Delete failed"), + QStringLiteral("Unknown error") + ); } commitCommand(); Gui::getMainWindow()->setUpdatesEnabled(true); @@ -1489,26 +1602,28 @@ bool StdCmdDelete::isActive() DEF_STD_CMD_A(StdCmdRefresh) StdCmdRefresh::StdCmdRefresh() - : Command("Std_Refresh") + : Command("Std_Refresh") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Recompute"); - sToolTipText = QT_TR_NOOP("Recomputes the active document"); - sWhatsThis = "Std_Refresh"; - sStatusTip = sToolTipText; - sPixmap = "view-refresh"; - sAccel = keySequenceToAccel(QKeySequence::Refresh); - eType = AlterDoc | Alter3DView | AlterSelection | ForEdit; - bCanLog = false; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Recompute"); + sToolTipText = QT_TR_NOOP("Recomputes the active document"); + sWhatsThis = "Std_Refresh"; + sStatusTip = sToolTipText; + sPixmap = "view-refresh"; + sAccel = keySequenceToAccel(QKeySequence::Refresh); + eType = AlterDoc | Alter3DView | AlterSelection | ForEdit; + bCanLog = false; // Make it optional to create a transaction for a recompute. // The new default behaviour is quite cumbersome in some cases because when // undoing the last transaction the manual recompute will clear the redo stack. ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Document"); + "User parameter:BaseApp/Preferences/Document" + ); bool create = hGrp->GetBool("TransactionOnRecompute", false); - if (!create) + if (!create) { eType = eType | NoTransaction; + } } void StdCmdRefresh::activated([[maybe_unused]] int iMsg) @@ -1519,17 +1634,25 @@ void StdCmdRefresh::activated([[maybe_unused]] int iMsg) App::AutoTransaction trans((eType & NoTransaction) ? nullptr : "Recompute"); try { - doCommand(Doc,"App.activeDocument().recompute(None,True,True)"); + doCommand(Doc, "App.activeDocument().recompute(None,True,True)"); } catch (Base::Exception& /*e*/) { - auto ret = QMessageBox::warning(getMainWindow(), QObject::tr("Dependency error"), - qApp->translate("Std_Refresh", "The document contains dependency cycles.\n" - "Check the report view for more details.\n\n" - "Proceed?"), - QMessageBox::Yes, QMessageBox::No); - if(ret == QMessageBox::No) + auto ret = QMessageBox::warning( + getMainWindow(), + QObject::tr("Dependency error"), + qApp->translate( + "Std_Refresh", + "The document contains dependency cycles.\n" + "Check the report view for more details.\n\n" + "Proceed?" + ), + QMessageBox::Yes, + QMessageBox::No + ); + if (ret == QMessageBox::No) { return; - doCommand(Doc,"App.activeDocument().recompute(None,True)"); + } + doCommand(Doc, "App.activeDocument().recompute(None,True)"); } } @@ -1544,14 +1667,14 @@ bool StdCmdRefresh::isActive() DEF_STD_CMD_A(StdCmdTransform) StdCmdTransform::StdCmdTransform() - : Command("Std_Transform") + : Command("Std_Transform") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Transform"); + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Transform"); - sToolTipText = QT_TR_NOOP("Transforms the selected object"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_Transform"; + sToolTipText = QT_TR_NOOP("Transforms the selected object"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_Transform"; } void StdCmdTransform::activated(int iMsg) @@ -1571,22 +1694,26 @@ bool StdCmdTransform::isActive() DEF_STD_CMD_A(StdCmdPlacement) StdCmdPlacement::StdCmdPlacement() - : Command("Std_Placement") + : Command("Std_Placement") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("P&lacement"); + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("P&lacement"); - sToolTipText = QT_TR_NOOP("Opens the placement editor to adjust the placement of the selected object"); + sToolTipText = QT_TR_NOOP( + "Opens the placement editor to adjust the placement of the selected object" + ); - sStatusTip = sToolTipText; - sWhatsThis = "Std_Placement"; - sPixmap = "Std_Placement"; + sStatusTip = sToolTipText; + sWhatsThis = "Std_Placement"; + sPixmap = "Std_Placement"; } void StdCmdPlacement::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector sel = Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); + std::vector sel = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); auto plm = new Gui::Dialog::TaskPlacement(); if (!sel.empty()) { App::Property* prop = sel.front()->getPropertyByName("Placement"); @@ -1595,9 +1722,12 @@ void StdCmdPlacement::activated(int iMsg) std::vector selection; selection.reserve(sel.size()); - std::transform(sel.cbegin(), sel.cend(), std::back_inserter(selection), [](App::DocumentObject* obj) { - return Gui::SelectionObject(obj); - }); + std::transform( + sel.cbegin(), + sel.cend(), + std::back_inserter(selection), + [](App::DocumentObject* obj) { return Gui::SelectionObject(obj); } + ); plm->setPropertyName(QLatin1String("Placement")); plm->setSelection(selection); @@ -1610,8 +1740,10 @@ void StdCmdPlacement::activated(int iMsg) bool StdCmdPlacement::isActive() { - std::vector sel = Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); - return !(sel.empty() || std::ranges::any_of(sel, [](auto obj){return obj->isFreezed();})); + std::vector sel = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); + return !(sel.empty() || std::ranges::any_of(sel, [](auto obj) { return obj->isFreezed(); })); } //=========================================================================== @@ -1620,33 +1752,39 @@ bool StdCmdPlacement::isActive() DEF_STD_CMD_A(StdCmdTransformManip) StdCmdTransformManip::StdCmdTransformManip() - : Command("Std_TransformManip") + : Command("Std_TransformManip") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Trans&form"); - sToolTipText = QT_TR_NOOP("Transforms the selected object in the 3D view"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TransformManip"; - sPixmap = "Std_TransformManip"; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Trans&form"); + sToolTipText = QT_TR_NOOP("Transforms the selected object in the 3D view"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_TransformManip"; + sPixmap = "Std_TransformManip"; } void StdCmdTransformManip::activated(int iMsg) { Q_UNUSED(iMsg); - if (getActiveGuiDocument()->getInEdit()) + if (getActiveGuiDocument()->getInEdit()) { getActiveGuiDocument()->resetEdit(); - std::vector sel = Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); + } + std::vector sel = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); Gui::ViewProvider* vp = Application::Instance->getViewProvider(sel.front()); // FIXME: Need a way to force 'Transform' edit mode // #0000477: Proper interface for edit modes of view provider - if (vp) + if (vp) { getActiveGuiDocument()->setEdit(vp, Gui::ViewProvider::Transform); + } } bool StdCmdTransformManip::isActive() { - std::vector sel = Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); - return (sel.size() == 1 && ! sel.front()->isFreezed()); + std::vector sel = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); + return (sel.size() == 1 && !sel.front()->isFreezed()); } //=========================================================================== @@ -1655,22 +1793,23 @@ bool StdCmdTransformManip::isActive() DEF_STD_CMD_A(StdCmdAlignment) StdCmdAlignment::StdCmdAlignment() - : Command("Std_Alignment") + : Command("Std_Alignment") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Ali&gn To…"); + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Ali&gn To…"); - sToolTipText = QT_TR_NOOP("Aligns the selected objects"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_Alignment"; - sPixmap = "Std_Alignment"; + sToolTipText = QT_TR_NOOP("Aligns the selected objects"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_Alignment"; + sPixmap = "Std_Alignment"; } void StdCmdAlignment::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector sel = Gui::Selection().getObjectsOfType - (App::GeoFeature::getClassTypeId()); + std::vector sel = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); ManualAlignment* align = ManualAlignment::instance(); QObject::connect(align, &ManualAlignment::emitCanceled, align, &QObject::deleteLater); QObject::connect(align, &ManualAlignment::emitFinished, align, &QObject::deleteLater); @@ -1689,7 +1828,7 @@ void StdCmdAlignment::activated(int iMsg) model.addGroups(groupMap); align->setModel(model); Base::Type style = Base::Type::fromName("Gui::CADNavigationStyle"); - Base::Vector3d upDir(0,1,0), viewDir(0,0,-1); + Base::Vector3d upDir(0, 1, 0), viewDir(0, 0, -1); Gui::Document* doc = Application::Instance->activeDocument(); if (doc) { auto mdi = qobject_cast(doc->getActiveView()); @@ -1697,11 +1836,11 @@ void StdCmdAlignment::activated(int iMsg) View3DInventorViewer* viewer = mdi->getViewer(); SoCamera* camera = viewer->getSoRenderManager()->getCamera(); if (camera) { - SbVec3f up(0,1,0), dir(0,0,-1); + SbVec3f up(0, 1, 0), dir(0, 0, -1); camera->orientation.getValue().multVec(dir, dir); - viewDir.Set(dir[0],dir[1],dir[2]); + viewDir.Set(dir[0], dir[1], dir[2]); camera->orientation.getValue().multVec(up, up); - upDir.Set(up[0],up[1],up[2]); + upDir.Set(up[0], up[1], up[2]); } style = viewer->navigationStyle()->getTypeId(); } @@ -1709,14 +1848,15 @@ void StdCmdAlignment::activated(int iMsg) align->setMinPoints(1); align->startAlignment(style); - align->setViewingDirections(viewDir,upDir, viewDir,upDir); + align->setViewingDirections(viewDir, upDir, viewDir, upDir); Gui::Selection().clearSelection(); } bool StdCmdAlignment::isActive() { - if (ManualAlignment::hasInstance()) + if (ManualAlignment::hasInstance()) { return false; + } return Gui::Selection().countObjectsOfType() == 2; } @@ -1726,16 +1866,16 @@ bool StdCmdAlignment::isActive() DEF_STD_CMD_A(StdCmdEdit) StdCmdEdit::StdCmdEdit() - : Command("Std_Edit") + : Command("Std_Edit") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Toggle &Edit Mode"); - sToolTipText = QT_TR_NOOP("Toggles the selected object's edit mode"); - sWhatsThis = "Std_Edit"; - sStatusTip = sToolTipText; - sAccel = ""; - sPixmap = "edit-edit"; - eType = ForEdit; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Toggle &Edit Mode"); + sToolTipText = QT_TR_NOOP("Toggles the selected object's edit mode"); + sWhatsThis = "Std_Edit"; + sStatusTip = sToolTipText; + sAccel = ""; + sPixmap = "edit-edit"; + eType = ForEdit; } void StdCmdEdit::activated(int iMsg) @@ -1745,11 +1885,12 @@ void StdCmdEdit::activated(int iMsg) if (view && view->isDerivedFrom()) { Gui::View3DInventorViewer* viewer = static_cast(view)->getViewer(); if (viewer->isEditingViewProvider()) { - doCommand(Command::Gui,"Gui.activeDocument().resetEdit()"); - } else { + doCommand(Command::Gui, "Gui.activeDocument().resetEdit()"); + } + else { if (!Selection().getCompleteSelection().empty()) { SelectionSingleton::SelObj obj = Selection().getCompleteSelection()[0]; - doCommand(Command::Gui,"Gui.activeDocument().setEdit(\"%s\",0)",obj.FeatName); + doCommand(Command::Gui, "Gui.activeDocument().setEdit(\"%s\",0)", obj.FeatName); } } } @@ -1757,7 +1898,8 @@ void StdCmdEdit::activated(int iMsg) bool StdCmdEdit::isActive() { - return (!Selection().getCompleteSelection().empty()) || (Gui::Control().activeDialog() != nullptr); + return (!Selection().getCompleteSelection().empty()) + || (Gui::Control().activeDialog() != nullptr); } //=========================================================================== @@ -1768,14 +1910,16 @@ DEF_STD_CMD_A(StdCmdProperties) StdCmdProperties::StdCmdProperties() : Command("Std_Properties") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Propert&ies"); - sToolTipText = QT_TR_NOOP("Shows the property view, which displays the properties of the selected object."); - sWhatsThis = "Std_Properties"; - sStatusTip = sToolTipText; - sAccel = "Alt+Return"; - sPixmap = "document-properties"; - eType = Alter3DView; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Propert&ies"); + sToolTipText = QT_TR_NOOP( + "Shows the property view, which displays the properties of the selected object." + ); + sWhatsThis = "Std_Properties"; + sStatusTip = sToolTipText; + sAccel = "Alt+Return"; + sPixmap = "document-properties"; + eType = Alter3DView; } void StdCmdProperties::activated(int iMsg) @@ -1800,52 +1944,59 @@ bool StdCmdProperties::isActive() //====================================================================== // StdCmdExpression //=========================================================================== -class StdCmdExpression : public Gui::Command +class StdCmdExpression: public Gui::Command { public: - StdCmdExpression() : Command("Std_Expressions") + StdCmdExpression() + : Command("Std_Expressions") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Expression Actions"); - sToolTipText = QT_TR_NOOP("Actions that apply to expressions"); - sWhatsThis = "Std_Expressions"; - sStatusTip = sToolTipText; - eType = ForEdit; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Expression Actions"); + sToolTipText = QT_TR_NOOP("Actions that apply to expressions"); + sWhatsThis = "Std_Expressions"; + sStatusTip = sToolTipText; + eType = ForEdit; } - const char* className() const override {return "StdCmdExpression";} -protected: + const char* className() const override + { + return "StdCmdExpression"; + } - void activated(int iMsg) override { - std::map > objs; - switch(iMsg) { - case 0: - for(auto &sel : Selection().getCompleteSelection()) - objs[sel.pObject->getDocument()].insert(sel.pObject); - break; - case 1: - if(App::GetApplication().getActiveDocument()) { - auto doc = App::GetApplication().getActiveDocument(); - auto array = doc->getObjects(); - auto &set = objs[doc]; - set.insert(array.begin(),array.end()); - } - break; - case 2: - for(auto doc : App::GetApplication().getDocuments()) { - auto &set = objs[doc]; - auto array = doc->getObjects(); - set.insert(array.begin(),array.end()); - } - break; - case 3: - pasteExpressions(); - break; +protected: + void activated(int iMsg) override + { + std::map> objs; + switch (iMsg) { + case 0: + for (auto& sel : Selection().getCompleteSelection()) { + objs[sel.pObject->getDocument()].insert(sel.pObject); + } + break; + case 1: + if (App::GetApplication().getActiveDocument()) { + auto doc = App::GetApplication().getActiveDocument(); + auto array = doc->getObjects(); + auto& set = objs[doc]; + set.insert(array.begin(), array.end()); + } + break; + case 2: + for (auto doc : App::GetApplication().getDocuments()) { + auto& set = objs[doc]; + auto array = doc->getObjects(); + set.insert(array.begin(), array.end()); + } + break; + case 3: + pasteExpressions(); + break; } copyExpressions(objs); } - Gui::Action * createAction() override { + Gui::Action* createAction() override + { auto pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); applyCommandData(this->className(), pcAction); @@ -1858,33 +2009,36 @@ protected: return pcAction; } - void copyExpressions(const std::map > &objs) { + void copyExpressions(const std::map>& objs) + { std::ostringstream ss; std::vector props; - for(auto &v : objs) { - for(auto obj : v.second) { + for (auto& v : objs) { + for (auto obj : v.second) { props.clear(); obj->getPropertyList(props); - for(auto prop : props) { + for (auto prop : props) { auto p = dynamic_cast(prop); - if(!p) continue; - for(auto &v : p->getExpressions()) { - ss << "##@@ " << v.first.toString() << ' ' - << obj->getFullName() << '.' << p->getName() - << " (" << obj->Label.getValue() << ')' << std::endl; + if (!p) { + continue; + } + for (auto& v : p->getExpressions()) { + ss << "##@@ " << v.first.toString() << ' ' << obj->getFullName() << '.' + << p->getName() << " (" << obj->Label.getValue() << ')' << std::endl; ss << "##@@"; - if(!v.second->comment.empty()) { - if(v.second->comment[0] == '&' - || v.second->comment.find('\n') != std::string::npos - || v.second->comment.find('\r') != std::string::npos) - { + if (!v.second->comment.empty()) { + if (v.second->comment[0] == '&' + || v.second->comment.find('\n') != std::string::npos + || v.second->comment.find('\r') != std::string::npos) { std::string comment = v.second->comment; - boost::replace_all(comment,"&","&"); - boost::replace_all(comment,"\n"," "); - boost::replace_all(comment,"\r"," "); + boost::replace_all(comment, "&", "&"); + boost::replace_all(comment, "\n", " "); + boost::replace_all(comment, "\r", " "); ss << '&' << comment; - }else + } + else { ss << v.second->comment; + } } ss << std::endl << v.second->toString(true) << std::endl << std::endl; } @@ -1894,25 +2048,28 @@ protected: QApplication::clipboard()->setText(QString::fromUtf8(ss.str().c_str())); } - void pasteExpressions() { - std::map > > exprs; + void pasteExpressions() + { + std::map< + App::Document*, + std::map>> + exprs; bool failed = false; std::string txt = QApplication::clipboard()->text().toUtf8().constData(); - const char *tstart = txt.c_str(); - const char *tend = tstart + txt.size(); + const char* tstart = txt.c_str(); + const char* tend = tstart + txt.size(); static boost::regex rule("^##@@ ([^ ]+) (\\w+)#(\\w+)\\.(\\w+) [^\n]+\n##@@([^\n]*)\n"); boost::cmatch m; - if(!boost::regex_search(tstart,m,rule)) { + if (!boost::regex_search(tstart, m, rule)) { FC_WARN("No expression header found"); return; } boost::cmatch m2; bool found = true; - for(;found;m=m2) { - found = boost::regex_search(m[0].second,tend,m2,rule); + for (; found; m = m2) { + found = boost::regex_search(m[0].second, tend, m2, rule); auto pathName = m.str(1); auto docName = m.str(2); @@ -1920,77 +2077,94 @@ protected: auto propName = m.str(4); auto comment = m.str(5); - App::Document *doc = App::GetApplication().getDocument(docName.c_str()); - if(!doc) { + App::Document* doc = App::GetApplication().getDocument(docName.c_str()); + if (!doc) { FC_WARN("Cannot find document '" << docName << "'"); continue; } auto obj = doc->getObject(objName.c_str()); - if(!obj) { + if (!obj) { FC_WARN("Cannot find object '" << docName << '#' << objName << "'"); continue; } auto prop = dynamic_cast( - obj->getPropertyByName(propName.c_str())); - if(!prop) { + obj->getPropertyByName(propName.c_str()) + ); + if (!prop) { FC_WARN("Invalid property '" << docName << '#' << objName << '.' << propName << "'"); continue; } - size_t len = (found?m2[0].first:tend) - m[0].second; + size_t len = (found ? m2[0].first : tend) - m[0].second; try { - App::ExpressionPtr expr(App::Expression::parse(obj,std::string(m[0].second,len))); - if(expr && !comment.empty()) { - if(comment[0] == '&') { - expr->comment = comment.c_str()+1; - boost::replace_all(expr->comment,"&","&"); - boost::replace_all(expr->comment," ","\n"); - boost::replace_all(expr->comment," ","\r"); - } else + App::ExpressionPtr expr(App::Expression::parse(obj, std::string(m[0].second, len))); + if (expr && !comment.empty()) { + if (comment[0] == '&') { + expr->comment = comment.c_str() + 1; + boost::replace_all(expr->comment, "&", "&"); + boost::replace_all(expr->comment, " ", "\n"); + boost::replace_all(expr->comment, " ", "\r"); + } + else { expr->comment = comment; + } } - exprs[doc][prop][App::ObjectIdentifier::parse(obj,pathName)] = std::move(expr); - } catch(Base::Exception &e) { + exprs[doc][prop][App::ObjectIdentifier::parse(obj, pathName)] = std::move(expr); + } + catch (Base::Exception& e) { FC_ERR(e.what() << std::endl << m[0].str()); failed = true; } } - if(failed) { - QMessageBox::critical(getMainWindow(), QObject::tr("Expression error"), - QObject::tr("Failed to parse some of the expressions.\n" - "Check the report view for more details.")); + if (failed) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Expression error"), + QObject::tr( + "Failed to parse some of the expressions.\n" + "Check the report view for more details." + ) + ); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Paste expressions")); try { - for(auto &v : exprs) { - for(auto &v2 : v.second) { - auto &expressions = v2.second; + for (auto& v : exprs) { + for (auto& v2 : v.second) { + auto& expressions = v2.second; auto old = v2.first->getExpressions(); - for(auto it=expressions.begin(),itNext=it;it!=expressions.end();it=itNext) { + for (auto it = expressions.begin(), itNext = it; it != expressions.end(); + it = itNext) { ++itNext; auto iter = old.find(it->first); - if(iter != old.end() && it->second->isSame(*iter->second)) + if (iter != old.end() && it->second->isSame(*iter->second)) { expressions.erase(it); + } } - if(!expressions.empty()) + if (!expressions.empty()) { v2.first->setExpressions(std::move(expressions)); + } } } commitCommand(); - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { abortCommand(); - QMessageBox::critical(getMainWindow(), QObject::tr("Failed to paste expressions"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Failed to paste expressions"), + QString::fromLatin1(e.what()) + ); e.reportException(); } } - bool isActive() override { - if(!App::GetApplication().getActiveDocument()) { + bool isActive() override + { + if (!App::GetApplication().getActiveDocument()) { pcActionCopyAll->setEnabled(false); pcActionCopySel->setEnabled(false); pcActionCopyActive->setEnabled(false); @@ -2001,22 +2175,22 @@ protected: pcActionCopyAll->setEnabled(true); pcActionCopySel->setEnabled(Selection().hasSelection()); - pcActionPaste->setEnabled( - QApplication::clipboard()->text().startsWith(QLatin1String("##@@ "))); + pcActionPaste->setEnabled(QApplication::clipboard()->text().startsWith(QLatin1String("##@@ "))); return true; } - QAction *pcActionCopyAll{nullptr}; - QAction *pcActionCopySel{nullptr}; - QAction *pcActionCopyActive{nullptr}; - QAction *pcActionPaste{nullptr}; + QAction* pcActionCopyAll {nullptr}; + QAction* pcActionCopySel {nullptr}; + QAction* pcActionCopyActive {nullptr}; + QAction* pcActionPaste {nullptr}; }; -namespace Gui { +namespace Gui +{ void CreateDocCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdNew()); rcCmdMgr.addCommand(new StdCmdOpen()); @@ -2055,5 +2229,4 @@ void CreateDocCommands() rcCmdMgr.addCommand(new StdCmdExpression()); } -} // namespace Gui - +} // namespace Gui diff --git a/src/Gui/CommandFeat.cpp b/src/Gui/CommandFeat.cpp index 3029b426a3..47c9d30b57 100644 --- a/src/Gui/CommandFeat.cpp +++ b/src/Gui/CommandFeat.cpp @@ -40,7 +40,6 @@ using namespace Gui; - //=========================================================================== // Std_Recompute //=========================================================================== @@ -48,16 +47,16 @@ using namespace Gui; DEF_STD_CMD(StdCmdFeatRecompute) StdCmdFeatRecompute::StdCmdFeatRecompute() - :Command("Std_Recompute") + : Command("Std_Recompute") { // setting the - sGroup = "File"; - sMenuText = QT_TR_NOOP("&Recompute"); - sToolTipText = QT_TR_NOOP("Recomputes a feature or document"); - sWhatsThis = "Std_Recompute"; - sStatusTip = sToolTipText; - sPixmap = "view-refresh"; - sAccel = "Ctrl+R"; + sGroup = "File"; + sMenuText = QT_TR_NOOP("&Recompute"); + sToolTipText = QT_TR_NOOP("Recomputes a feature or document"); + sWhatsThis = "Std_Recompute"; + sStatusTip = sToolTipText; + sPixmap = "view-refresh"; + sAccel = "Ctrl+R"; } void StdCmdFeatRecompute::activated(int iMsg) @@ -72,14 +71,14 @@ void StdCmdFeatRecompute::activated(int iMsg) DEF_STD_CMD_A(StdCmdRandomColor) StdCmdRandomColor::StdCmdRandomColor() - :Command("Std_RandomColor") + : Command("Std_RandomColor") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Random &Color"); - sToolTipText = QT_TR_NOOP("Assigns random diffuse colors for the selected objects"); - sWhatsThis = "Std_RandomColor"; - sStatusTip = sToolTipText; - sPixmap = "Std_RandomColor"; + sGroup = "File"; + sMenuText = QT_TR_NOOP("Random &Color"); + sToolTipText = QT_TR_NOOP("Assigns random diffuse colors for the selected objects"); + sWhatsThis = "Std_RandomColor"; + sStatusTip = sToolTipText; + sPixmap = "Std_RandomColor"; } void StdCmdRandomColor::activated(int iMsg) @@ -123,7 +122,7 @@ void StdCmdRandomColor::activated(int iMsg) std::vector sel = Selection().getCompleteSelection(); Command::openCommand(QT_TRANSLATE_NOOP("Command", "Set Random Color")); - for (const auto & it : sel) { + for (const auto& it : sel) { ViewProvider* view = Application::Instance->getViewProvider(it.pObject); setRandomColor(view); @@ -156,7 +155,8 @@ StdCmdToggleFreeze::StdCmdToggleFreeze() { sGroup = "File"; sMenuText = QT_TR_NOOP("Toggle Freeze"); - static std::string toolTip = std::string("

") + static std::string toolTip + = std::string("

") + QT_TR_NOOP("Toggles freeze state of the selected objects. A frozen object is not recomputed when its parents change.") + "

"; sToolTipText = toolTip.c_str(); @@ -180,12 +180,12 @@ void StdCmdToggleFreeze::activated(int iMsg) continue; } - if (obj->isFreezed()){ + if (obj->isFreezed()) { obj->unfreeze(); - } else { + } + else { obj->freeze(); } - } Command::commitCommand(); } @@ -196,8 +196,6 @@ bool StdCmdToggleFreeze::isActive() } - - //=========================================================================== // Std_SendToPythonConsole //=========================================================================== @@ -205,69 +203,79 @@ bool StdCmdToggleFreeze::isActive() DEF_STD_CMD_A(StdCmdSendToPythonConsole) StdCmdSendToPythonConsole::StdCmdSendToPythonConsole() - :Command("Std_SendToPythonConsole") + : Command("Std_SendToPythonConsole") { // setting the - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("&Send to Python Console"); - sToolTipText = QT_TR_NOOP("Sends the selected object to the Python console"); - sWhatsThis = "Std_SendToPythonConsole"; - sStatusTip = sToolTipText; - sPixmap = "applications-python"; - sAccel = "Ctrl+Shift+P"; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("&Send to Python Console"); + sToolTipText = QT_TR_NOOP("Sends the selected object to the Python console"); + sWhatsThis = "Std_SendToPythonConsole"; + sStatusTip = sToolTipText; + sPixmap = "applications-python"; + sAccel = "Ctrl+Shift+P"; } bool StdCmdSendToPythonConsole::isActive() { - //active only if either 1 object is selected or multiple subobjects from the same object + // active only if either 1 object is selected or multiple subobjects from the same object return Gui::Selection().getSelectionEx().size() == 1; } void StdCmdSendToPythonConsole::activated(int iMsg) { Q_UNUSED(iMsg); - const std::vector &sels = Gui::Selection().getSelectionEx("*", App::DocumentObject::getClassTypeId(), - ResolveMode::OldStyleElement, false); - if (sels.empty()) + const std::vector& sels = Gui::Selection().getSelectionEx( + "*", + App::DocumentObject::getClassTypeId(), + ResolveMode::OldStyleElement, + false + ); + if (sels.empty()) { return; - const App::DocumentObject *obj = sels[0].getObject(); - if (!obj) + } + const App::DocumentObject* obj = sels[0].getObject(); + if (!obj) { return; + } QString docname = QString::fromLatin1(obj->getDocument()->getName()); QString objname = QString::fromLatin1(obj->getNameInDocument()); try { // clear variables from previous run, if any - QString cmd = QLatin1String("try:\n del(doc,lnk,obj,shp,sub,subs)\nexcept Exception:\n pass\n"); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + QString cmd = QLatin1String( + "try:\n del(doc,lnk,obj,shp,sub,subs)\nexcept Exception:\n pass\n" + ); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); cmd = QStringLiteral("doc = App.getDocument(\"%1\")").arg(docname); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); - //support links + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); + // support links if (obj->isDerivedFrom()) { cmd = QStringLiteral("lnk = doc.getObject(\"%1\")").arg(objname); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); cmd = QStringLiteral("obj = lnk.getLinkedObject()"); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); const auto link = static_cast(obj); obj = link->getLinkedObject(); - } else { + } + else { cmd = QStringLiteral("obj = doc.getObject(\"%1\")").arg(objname); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); } if (obj->isDerivedFrom()) { const auto geoObj = static_cast(obj); const App::PropertyGeometry* geo = geoObj->getPropertyOfGeometry(); - if (geo){ - cmd = QStringLiteral("shp = obj.") + QLatin1String(geo->getName()); //"Shape", "Mesh", "Points", etc. + if (geo) { + cmd = QStringLiteral("shp = obj.") + + QLatin1String(geo->getName()); //"Shape", "Mesh", "Points", etc. Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); if (sels[0].hasSubNames()) { std::vector subnames = sels[0].getSubNames(); QString subname = QString::fromLatin1(subnames[0].c_str()); cmd = QStringLiteral("sub = obj.getSubObject(\"%1\")").arg(subname); - Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); + Gui::Command::runCommand(Gui::Command::Gui, cmd.toLatin1()); if (subnames.size() > 1) { std::ostringstream strm; strm << "subs = ["; - for (const auto & subname : subnames) { + for (const auto& subname : subnames) { strm << "obj.getSubObject(\"" << subname << "\"),"; } strm << "]"; @@ -276,7 +284,7 @@ void StdCmdSendToPythonConsole::activated(int iMsg) } } } - //show the python console if it's not already visible, and set the keyboard focus to it + // show the python console if it's not already visible, and set the keyboard focus to it QWidget* pc = DockWindowManager::instance()->getDockWindow("Python console"); auto pcPython = qobject_cast(pc); if (pcPython) { @@ -287,7 +295,6 @@ void StdCmdSendToPythonConsole::activated(int iMsg) catch (const Base::Exception& e) { e.reportException(); } - } //=========================================================================== @@ -301,7 +308,7 @@ StdCmdToggleSkipRecompute::StdCmdToggleSkipRecompute() { sGroup = "File"; sMenuText = QT_TR_NOOP("Skip Recomputes"); - + static std::string toolTip = QT_TR_NOOP("Enables or disables the recomputations of the document"); sToolTipText = toolTip.c_str(); @@ -328,11 +335,11 @@ void StdCmdToggleSkipRecompute::activated(int iMsg) } Command::openCommand(QT_TRANSLATE_NOOP("Command", "Skip recomputes")); - doc->setStatus(App::Document::SkipRecompute, (bool) iMsg); + doc->setStatus(App::Document::SkipRecompute, (bool)iMsg); if (_pcAction) { - _pcAction->setChecked((bool) iMsg); + _pcAction->setChecked((bool)iMsg); } - Command::commitCommand(); + Command::commitCommand(); } bool StdCmdToggleSkipRecompute::isActive() @@ -349,11 +356,12 @@ bool StdCmdToggleSkipRecompute::isActive() return true; } -namespace Gui { +namespace Gui +{ void CreateFeatCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdFeatRecompute()); rcCmdMgr.addCommand(new StdCmdToggleFreeze()); @@ -362,4 +370,4 @@ void CreateFeatCommands() rcCmdMgr.addCommand(new StdCmdToggleSkipRecompute()); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/CommandLink.cpp b/src/Gui/CommandLink.cpp index b49d33bbb6..bd9e25e002 100644 --- a/src/Gui/CommandLink.cpp +++ b/src/Gui/CommandLink.cpp @@ -20,8 +20,8 @@ * * ****************************************************************************/ -# include -# include +#include +#include #include #include @@ -46,45 +46,55 @@ FC_LOG_LEVEL_INIT("CommandLink", true, true) using namespace Gui; -static void setLinkLabel(App::DocumentObject *obj, const char *doc, const char *name) { +static void setLinkLabel(App::DocumentObject* obj, const char* doc, const char* name) +{ std::string label = obj->Label.getValue(); label = Base::Tools::escapeEncodeString(label); - Command::doCommand(Command::Doc,"App.getDocument('%s').getObject('%s').Label='%s'",doc,name,label.c_str()); + Command::doCommand( + Command::Doc, + "App.getDocument('%s').getObject('%s').Label='%s'", + doc, + name, + label.c_str() + ); } //////////////////////////////////////////////////////////////////////////////////////////// -class StdCmdLinkMakeGroup : public Gui::Command +class StdCmdLinkMakeGroup: public Gui::Command { public: StdCmdLinkMakeGroup(); const char* className() const override - { return "StdCmdLinkMakeGroup"; } + { + return "StdCmdLinkMakeGroup"; + } protected: void activated(int iMsg) override; bool isActive() override; - Action * createAction() override; + Action* createAction() override; void languageChange() override; }; StdCmdLinkMakeGroup::StdCmdLinkMakeGroup() - : Command("Std_LinkMakeGroup") + : Command("Std_LinkMakeGroup") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Link Group"); - sToolTipText = QT_TR_NOOP("Creates a group of links"); - sWhatsThis = "Std_LinkMakeGroup"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "LinkGroup"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Link Group"); + sToolTipText = QT_TR_NOOP("Creates a group of links"); + sWhatsThis = "Std_LinkMakeGroup"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "LinkGroup"; } -bool StdCmdLinkMakeGroup::isActive() { +bool StdCmdLinkMakeGroup::isActive() +{ return !!App::GetApplication().getActiveDocument(); } -Action * StdCmdLinkMakeGroup::createAction() +Action* StdCmdLinkMakeGroup::createAction() { auto pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); @@ -105,8 +115,9 @@ void StdCmdLinkMakeGroup::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } auto pcAction = qobject_cast(_pcAction); QList acts = pcAction->actions(); acts[0]->setText(QObject::tr("Simple Group")); @@ -115,21 +126,22 @@ void StdCmdLinkMakeGroup::languageChange() } -void StdCmdLinkMakeGroup::activated(int option) { +void StdCmdLinkMakeGroup::activated(int option) +{ std::vector objs; std::set objset; auto doc = App::GetApplication().getActiveDocument(); - if(!doc) { + if (!doc) { FC_ERR("no active document"); return; } - for(auto &sel : Selection().getCompleteSelection()) { - if(sel.pObject && sel.pObject->isAttachedToDocument() && - objset.insert(sel.pObject).second) + for (auto& sel : Selection().getCompleteSelection()) { + if (sel.pObject && sel.pObject->isAttachedToDocument() && objset.insert(sel.pObject).second) { objs.push_back(sel.pObject); + } } Selection().selStackPush(); @@ -138,58 +150,98 @@ void StdCmdLinkMakeGroup::activated(int option) { Command::openCommand(QT_TRANSLATE_NOOP("Command", "Make link group")); try { std::string groupName = doc->getUniqueObjectName("LinkGroup"); - Command::doCommand(Command::Doc, - "App.getDocument('%s').addObject('App::LinkGroup','%s')",doc->getName(),groupName.c_str()); - if(objs.empty()) { - Selection().addSelection(doc->getName(),groupName.c_str()); + Command::doCommand( + Command::Doc, + "App.getDocument('%s').addObject('App::LinkGroup','%s')", + doc->getName(), + groupName.c_str() + ); + if (objs.empty()) { + Selection().addSelection(doc->getName(), groupName.c_str()); Selection().selStackPush(); - }else{ - Command::doCommand(Command::Doc,"__objs__ = []"); - for(auto obj : objs) { + } + else { + Command::doCommand(Command::Doc, "__objs__ = []"); + for (auto obj : objs) { std::string name; - if(option!=0 || doc!=obj->getDocument()) { + if (option != 0 || doc != obj->getDocument()) { name = doc->getUniqueObjectName("Link"); - Command::doCommand(Command::Doc, + Command::doCommand( + Command::Doc, "App.getDocument('%s').addObject('App::Link','%s').setLink(" - "App.getDocument('%s').getObject('%s'))", - doc->getName(),name.c_str(),obj->getDocument()->getName(),obj->getNameInDocument()); - setLinkLabel(obj,doc->getName(),name.c_str()); - if(option==2) - Command::doCommand(Command::Doc, + "App.getDocument('%s').getObject('%s'))", + doc->getName(), + name.c_str(), + obj->getDocument()->getName(), + obj->getNameInDocument() + ); + setLinkLabel(obj, doc->getName(), name.c_str()); + if (option == 2) { + Command::doCommand( + Command::Doc, "App.getDocument('%s').getObject('%s').LinkTransform = True", - doc->getName(),name.c_str()); - else if(obj->getPropertyByName("Placement")) - Command::doCommand(Command::Doc, + doc->getName(), + name.c_str() + ); + } + else if (obj->getPropertyByName("Placement")) { + Command::doCommand( + Command::Doc, "App.getDocument('%s').getObject('%s').Placement = " - "App.getDocument('%s').getObject('%s').Placement", - doc->getName(),name.c_str(),obj->getDocument()->getName(),obj->getNameInDocument()); - }else + "App.getDocument('%s').getObject('%s').Placement", + doc->getName(), + name.c_str(), + obj->getDocument()->getName(), + obj->getNameInDocument() + ); + } + } + else { name = obj->getNameInDocument(); - Command::doCommand(Command::Doc,"__objs__.append(App.getDocument('%s').getObject('%s'))", - doc->getName(),name.c_str()); - Command::doCommand(Command::Doc, - "App.getDocument('%s').getObject('%s').ViewObject.Visibility=False", - doc->getName(),name.c_str()); + } + Command::doCommand( + Command::Doc, + "__objs__.append(App.getDocument('%s').getObject('%s'))", + doc->getName(), + name.c_str() + ); + Command::doCommand( + Command::Doc, + "App.getDocument('%s').getObject('%s').ViewObject.Visibility=False", + doc->getName(), + name.c_str() + ); } - Command::doCommand(Command::Doc,"App.getDocument('%s').getObject('%s').setLink(__objs__)", - doc->getName(),groupName.c_str()); - Command::doCommand(Command::Doc,"del __objs__"); + Command::doCommand( + Command::Doc, + "App.getDocument('%s').getObject('%s').setLink(__objs__)", + doc->getName(), + groupName.c_str() + ); + Command::doCommand(Command::Doc, "del __objs__"); - for(size_t i=0;igetName(),groupName.c_str(),name.c_str()); + for (size_t i = 0; i < objs.size(); ++i) { + auto name = std::to_string(i) + "."; + Selection().addSelection(doc->getName(), groupName.c_str(), name.c_str()); } Selection().selStackPush(); } - if(option!=0) { - Command::doCommand(Command::Doc, - "App.getDocument('%s').getObject('%s').LinkMode = 'Auto Delete'", - doc->getName(),groupName.c_str()); + if (option != 0) { + Command::doCommand( + Command::Doc, + "App.getDocument('%s').getObject('%s').LinkMode = 'Auto Delete'", + doc->getName(), + groupName.c_str() + ); } Command::commitCommand(); - } catch (const Base::Exception& e) { - QMessageBox::critical(getMainWindow(), QObject::tr("Create link group failed"), - QString::fromLatin1(e.what())); + } + catch (const Base::Exception& e) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Create link group failed"), + QString::fromLatin1(e.what()) + ); Command::abortCommand(); e.reportException(); } @@ -200,34 +252,39 @@ void StdCmdLinkMakeGroup::activated(int option) { DEF_STD_CMD_A(StdCmdLinkMake) StdCmdLinkMake::StdCmdLinkMake() - : Command("Std_LinkMake") + : Command("Std_LinkMake") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Make Link"); - sToolTipText = QT_TR_NOOP("A link is an object that references another object, either within the same " - "or in another document. Unlike clones, links reference the original shape directly, " - "making them more memory-efficient, which helps with the creation of complex assemblies."); - sWhatsThis = "Std_LinkMake"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "Link"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Make Link"); + sToolTipText = QT_TR_NOOP( + "A link is an object that references another object, either within the same " + "or in another document. Unlike clones, links reference the original shape directly, " + "making them more memory-efficient, which helps with the creation of complex assemblies." + ); + sWhatsThis = "Std_LinkMake"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "Link"; } -bool StdCmdLinkMake::isActive() { +bool StdCmdLinkMake::isActive() +{ return App::GetApplication().getActiveDocument(); } -void StdCmdLinkMake::activated(int) { +void StdCmdLinkMake::activated(int) +{ auto doc = App::GetApplication().getActiveDocument(); - if(!doc) { + if (!doc) { FC_ERR("no active document"); return; } std::set objs; - for(auto &sel : Selection().getCompleteSelection()) { - if(sel.pObject && sel.pObject->isAttachedToDocument()) - objs.insert(sel.pObject); + for (auto& sel : Selection().getCompleteSelection()) { + if (sel.pObject && sel.pObject->isAttachedToDocument()) { + objs.insert(sel.pObject); + } } Selection().selStackPush(); @@ -235,27 +292,42 @@ void StdCmdLinkMake::activated(int) { Command::openCommand(QT_TRANSLATE_NOOP("Command", "Make link")); try { - if(objs.empty()) { + if (objs.empty()) { std::string name = doc->getUniqueObjectName("Link"); - Command::doCommand(Command::Doc, "App.getDocument('%s').addObject('App::Link','%s')", - doc->getName(),name.c_str()); - Selection().addSelection(doc->getName(),name.c_str()); - }else{ - for(auto obj : objs) { + Command::doCommand( + Command::Doc, + "App.getDocument('%s').addObject('App::Link','%s')", + doc->getName(), + name.c_str() + ); + Selection().addSelection(doc->getName(), name.c_str()); + } + else { + for (auto obj : objs) { std::string name = doc->getUniqueObjectName("Link"); - Command::doCommand(Command::Doc, - "App.getDocument('%s').addObject('App::Link','%s').setLink(App.getDocument('%s').%s)", - doc->getName(),name.c_str(),obj->getDocument()->getName(),obj->getNameInDocument()); - setLinkLabel(obj,doc->getName(),name.c_str()); - Selection().addSelection(doc->getName(),name.c_str()); + Command::doCommand( + Command::Doc, + "App.getDocument('%s').addObject('App::Link','%s').setLink(App.getDocument('%s'" + ").%s)", + doc->getName(), + name.c_str(), + obj->getDocument()->getName(), + obj->getNameInDocument() + ); + setLinkLabel(obj, doc->getName(), name.c_str()); + Selection().addSelection(doc->getName(), name.c_str()); } } Selection().selStackPush(); Command::commitCommand(); - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { Command::abortCommand(); - QMessageBox::critical(getMainWindow(), QObject::tr("Create link failed"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Create link failed"), + QString::fromLatin1(e.what()) + ); e.reportException(); } } @@ -265,72 +337,84 @@ void StdCmdLinkMake::activated(int) { DEF_STD_CMD_A(StdCmdLinkMakeRelative) StdCmdLinkMakeRelative::StdCmdLinkMakeRelative() - : Command("Std_LinkMakeRelative") + : Command("Std_LinkMakeRelative") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Make Sub-Link"); - sToolTipText = QT_TR_NOOP("Creates a sub-object or sub-element link"); - sWhatsThis = "Std_LinkMakeRelative"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "LinkSub"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Make Sub-Link"); + sToolTipText = QT_TR_NOOP("Creates a sub-object or sub-element link"); + sWhatsThis = "Std_LinkMakeRelative"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "LinkSub"; } -bool StdCmdLinkMakeRelative::isActive() { - return Selection().hasSubSelection(nullptr,true); +bool StdCmdLinkMakeRelative::isActive() +{ + return Selection().hasSubSelection(nullptr, true); } -void StdCmdLinkMakeRelative::activated(int) { +void StdCmdLinkMakeRelative::activated(int) +{ auto doc = App::GetApplication().getActiveDocument(); - if(!doc) { + if (!doc) { FC_ERR("no active document"); return; } Command::openCommand(QT_TRANSLATE_NOOP("Command", "Make sub-link")); try { - std::map, - std::pair > > linkInfo; - for(auto &sel : Selection().getCompleteSelection(ResolveMode::NoResolve)) { - if(!sel.pObject || !sel.pObject->isAttachedToDocument()) + std::map< + std::pair, + std::pair>> + linkInfo; + for (auto& sel : Selection().getCompleteSelection(ResolveMode::NoResolve)) { + if (!sel.pObject || !sel.pObject->isAttachedToDocument()) { continue; - auto key = std::make_pair(sel.pObject, - Data::noElementName(sel.SubName)); + } + auto key = std::make_pair(sel.pObject, Data::noElementName(sel.SubName)); auto element = Data::findElementName(sel.SubName); - auto &info = linkInfo[key]; + auto& info = linkInfo[key]; info.first = sel.pResolvedObject; - if(!Base::Tools::isNullOrEmpty(element)) + if (!Base::Tools::isNullOrEmpty(element)) { info.second.emplace_back(element); + } } Selection().selStackPush(); Selection().clearCompleteSelection(); - for(auto &v : linkInfo) { - auto &key = v.first; - auto &info = v.second; + for (auto& v : linkInfo) { + auto& key = v.first; + auto& info = v.second; std::string name = doc->getUniqueObjectName("Link"); std::ostringstream ss; ss << '['; - for(auto &s : info.second) + for (auto& s : info.second) { ss << "'" << s << "',"; + } ss << ']'; - FCMD_DOC_CMD(doc,"addObject('App::Link','" << name << "').setLink(" - << getObjectCmd(key.first) << ",'" << key.second - << "'," << ss.str() << ")"); + FCMD_DOC_CMD( + doc, + "addObject('App::Link','" << name << "').setLink(" << getObjectCmd(key.first) + << ",'" << key.second << "'," << ss.str() << ")" + ); auto link = doc->getObject(name.c_str()); - FCMD_OBJ_CMD(link,"LinkTransform = True"); - setLinkLabel(info.first,doc->getName(),name.c_str()); + FCMD_OBJ_CMD(link, "LinkTransform = True"); + setLinkLabel(info.first, doc->getName(), name.c_str()); - Selection().addSelection(doc->getName(),name.c_str()); + Selection().addSelection(doc->getName(), name.c_str()); } Selection().selStackPush(); Command::commitCommand(); - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { Command::abortCommand(); - QMessageBox::critical(getMainWindow(), QObject::tr("Failed to create relative link"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Failed to create relative link"), + QString::fromLatin1(e.what()) + ); e.reportException(); } return; @@ -338,7 +422,8 @@ void StdCmdLinkMakeRelative::activated(int) { ///////////////////////////////////////////////////////////////////////////////////// -struct Info { +struct Info +{ bool inited = false; App::DocumentObjectT topParent; std::string subname; @@ -346,7 +431,8 @@ struct Info { App::DocumentObjectT obj; }; -static void linkConvert(bool unlink) { +static void linkConvert(bool unlink) +{ // We are trying to replace an object with a link (App::Link), or replace a // link back to its linked object (i.e. unlink). This is a very complex // operation. It works by reassign the link property of the parent of the @@ -355,22 +441,23 @@ static void linkConvert(bool unlink) { // by ViewProviderDocumentObject::replaceObject(), which in turn relies on // PropertyLinkBase::CopyOnLinkReplace(). - std::map, Info> infos; - for(const auto& sel : TreeWidget::getSelection()) { + std::map, Info> infos; + for (const auto& sel : TreeWidget::getSelection()) { auto obj = sel.vp->getObject(); auto parent = sel.parentVp; - if(!parent) { + if (!parent) { FC_WARN("skip '" << obj->getFullName() << "' with no parent"); continue; } auto parentObj = parent->getObject(); - auto &info = infos[std::make_pair(parentObj,obj)]; - if(info.inited) + auto& info = infos[std::make_pair(parentObj, obj)]; + if (info.inited) { continue; + } info.inited = true; - if(unlink) { + if (unlink) { auto linked = obj->getLinkedObject(false); - if(!linked || !linked->isAttachedToDocument() || linked == obj) { + if (!linked || !linked->isAttachedToDocument() || linked == obj) { FC_WARN("skip non link"); continue; } @@ -380,105 +467,120 @@ static void linkConvert(bool unlink) { info.obj = obj; } - if(infos.empty()) + if (infos.empty()) { return; + } Selection().selStackPush(); Selection().clearCompleteSelection(); // now, do actual operation - const char *transactionName = unlink?"Unlink":"Replace with link"; + const char* transactionName = unlink ? "Unlink" : "Replace with link"; Command::openCommand(transactionName); try { - std::unordered_map recomputeSet; - for(auto &v : infos) { - auto &info = v.second; + std::unordered_map recomputeSet; + for (auto& v : infos) { + auto& info = v.second; auto parent = info.parent.getObject(); auto parentVp = freecad_cast( - Application::Instance->getViewProvider(parent)); + Application::Instance->getViewProvider(parent) + ); auto obj = info.obj.getObject(); - if(!parent || !obj || !parentVp) + if (!parent || !obj || !parentVp) { continue; - if(!recomputeSet.contains(parent)) - recomputeSet.emplace(parent,parent); + } + if (!recomputeSet.contains(parent)) { + recomputeSet.emplace(parent, parent); + } auto doc = parent->getDocument(); - App::DocumentObject *replaceObj; - if(unlink) { + App::DocumentObject* replaceObj; + if (unlink) { replaceObj = obj->getLinkedObject(false); - if(!replaceObj || !replaceObj->isAttachedToDocument() || replaceObj == obj) + if (!replaceObj || !replaceObj->isAttachedToDocument() || replaceObj == obj) { continue; - }else{ + } + } + else { auto name = doc->getUniqueObjectName("Link"); auto link = doc->addObject(name.c_str()); - if(!link) - FC_THROWM(Base::RuntimeError,"Failed to create link"); - link->setLink(-1,obj); + if (!link) { + FC_THROWM(Base::RuntimeError, "Failed to create link"); + } + link->setLink(-1, obj); link->Label.setValue(obj->Label.getValue()); - auto pla = freecad_cast( - obj->getPropertyByName("Placement")); - if(pla) + auto pla = freecad_cast(obj->getPropertyByName("Placement")); + if (pla) { link->Placement.setValue(pla->getValue()); - else + } + else { link->LinkTransform.setValue(true); + } replaceObj = link; } // adjust subname for the new object auto pos = info.subname.rfind('.'); - if(pos==std::string::npos && pos) + if (pos == std::string::npos && pos) { info.subname.clear(); + } else { - pos = info.subname.rfind('.',pos-1); - if(pos==std::string::npos) + pos = info.subname.rfind('.', pos - 1); + if (pos == std::string::npos) { info.subname.clear(); + } else { - info.subname.resize(pos+1); + info.subname.resize(pos + 1); info.subname += replaceObj->getNameInDocument(); info.subname += "."; } } // do the replacement operation - if(parentVp->replaceObject(obj,replaceObj)<=0) - FC_THROWM(Base::RuntimeError, - "Failed to change link for " << parent->getFullName()); + if (parentVp->replaceObject(obj, replaceObj) <= 0) { + FC_THROWM(Base::RuntimeError, "Failed to change link for " << parent->getFullName()); + } } - std::vector recomputes; - for(auto &v : recomputeSet) { + std::vector recomputes; + for (auto& v : recomputeSet) { auto obj = v.second.getObject(); - if(obj) + if (obj) { recomputes.push_back(obj); + } } - if(!recomputes.empty()) + if (!recomputes.empty()) { recomputes.front()->getDocument()->recompute(recomputes); + } Command::commitCommand(); - - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { Command::abortCommand(); - auto title = unlink?QObject::tr("Unlink failed"):QObject::tr("Replace link failed"); + auto title = unlink ? QObject::tr("Unlink failed") : QObject::tr("Replace link failed"); QMessageBox::critical(getMainWindow(), title, QString::fromLatin1(e.what())); e.reportException(); return; } } -static bool linkConvertible(bool unlink) { +static bool linkConvertible(bool unlink) +{ int count = 0; - for(auto &sel : TreeWidget::getSelection()) { + for (auto& sel : TreeWidget::getSelection()) { auto parent = sel.parentVp; - if(!parent) + if (!parent) { return false; + } auto obj = sel.vp->getObject(); - if(unlink) { + if (unlink) { auto linked = obj->getLinkedObject(false); - if(!linked || linked == obj) + if (!linked || linked == obj) { return false; + } } ++count; } - return count!=0; + return count != 0; } //////////////////////////////////////////////////////////////////////////////////////////// @@ -486,22 +588,24 @@ static bool linkConvertible(bool unlink) { DEF_STD_CMD_A(StdCmdLinkReplace) StdCmdLinkReplace::StdCmdLinkReplace() - : Command("Std_LinkReplace") + : Command("Std_LinkReplace") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Replace With Link"); - sToolTipText = QT_TR_NOOP("Replaces the selected objects with links"); - sWhatsThis = "Std_LinkReplace"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "LinkReplace"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Replace With Link"); + sToolTipText = QT_TR_NOOP("Replaces the selected objects with links"); + sWhatsThis = "Std_LinkReplace"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "LinkReplace"; } -bool StdCmdLinkReplace::isActive() { +bool StdCmdLinkReplace::isActive() +{ return linkConvertible(false); } -void StdCmdLinkReplace::activated(int) { +void StdCmdLinkReplace::activated(int) +{ linkConvert(false); } @@ -510,22 +614,24 @@ void StdCmdLinkReplace::activated(int) { DEF_STD_CMD_A(StdCmdLinkUnlink) StdCmdLinkUnlink::StdCmdLinkUnlink() - : Command("Std_LinkUnlink") + : Command("Std_LinkUnlink") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Unlink"); - sToolTipText = QT_TR_NOOP("Unlinks the object by placing it directly in the container"); - sWhatsThis = "Std_LinkUnlink"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "Unlink"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Unlink"); + sToolTipText = QT_TR_NOOP("Unlinks the object by placing it directly in the container"); + sWhatsThis = "Std_LinkUnlink"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "Unlink"; } -bool StdCmdLinkUnlink::isActive() { +bool StdCmdLinkUnlink::isActive() +{ return linkConvertible(true); } -void StdCmdLinkUnlink::activated(int) { +void StdCmdLinkUnlink::activated(int) +{ linkConvert(true); } @@ -534,26 +640,27 @@ void StdCmdLinkUnlink::activated(int) { DEF_STD_CMD_A(StdCmdLinkImport) StdCmdLinkImport::StdCmdLinkImport() - : Command("Std_LinkImport") + : Command("Std_LinkImport") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Import Links"); - sToolTipText = QT_TR_NOOP("Imports selected external links"); - sWhatsThis = "Std_LinkImport"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "LinkImport"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Import Links"); + sToolTipText = QT_TR_NOOP("Imports selected external links"); + sWhatsThis = "Std_LinkImport"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "LinkImport"; } -static std::map > getLinkImportSelections() +static std::map> getLinkImportSelections() { - std::map > objMap; - for(auto &sel : Selection().getCompleteSelection(ResolveMode::NoResolve)) { + std::map> objMap; + for (auto& sel : Selection().getCompleteSelection(ResolveMode::NoResolve)) { auto obj = sel.pObject->resolve(sel.SubName); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { continue; - for(auto o : obj->getOutList()) { - if(o && o->isAttachedToDocument() && o->getDocument()!=obj->getDocument()) { + } + for (auto o : obj->getOutList()) { + if (o && o->isAttachedToDocument() && o->getDocument() != obj->getDocument()) { objMap[obj->getDocument()].push_back(obj); break; } @@ -562,33 +669,42 @@ static std::map > getLinkImpor return objMap; } -bool StdCmdLinkImport::isActive() { +bool StdCmdLinkImport::isActive() +{ auto links = getLinkImportSelections(); - if(links.empty()) + if (links.empty()) { return false; - for(auto &v : links) { - if(v.first->testStatus(App::Document::PartialDoc)) + } + for (auto& v : links) { + if (v.first->testStatus(App::Document::PartialDoc)) { return false; + } } return true; } -void StdCmdLinkImport::activated(int) { +void StdCmdLinkImport::activated(int) +{ Command::openCommand(QT_TRANSLATE_NOOP("Command", "Import links")); try { WaitCursor wc; wc.setIgnoreEvents(WaitCursor::NoEvents); - for(auto &v : getLinkImportSelections()) { + for (auto& v : getLinkImportSelections()) { auto doc = v.first; // TODO: Is it possible to do this using interpreter? - for(auto obj : doc->importLinks(v.second)) + for (auto obj : doc->importLinks(v.second)) { obj->Visibility.setValue(false); + } } Command::commitCommand(); - }catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { Command::abortCommand(); - QMessageBox::critical(getMainWindow(), QObject::tr("Failed to import links"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Failed to import links"), + QString::fromLatin1(e.what()) + ); e.reportException(); } } @@ -598,36 +714,43 @@ void StdCmdLinkImport::activated(int) { DEF_STD_CMD_A(StdCmdLinkImportAll) StdCmdLinkImportAll::StdCmdLinkImportAll() - : Command("Std_LinkImportAll") + : Command("Std_LinkImportAll") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Import All Links"); - sToolTipText = QT_TR_NOOP("Imports all links of the active document"); - sWhatsThis = "Std_LinkImportAll"; - sStatusTip = sToolTipText; - eType = AlterDoc; - sPixmap = "LinkImportAll"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Import All Links"); + sToolTipText = QT_TR_NOOP("Imports all links of the active document"); + sWhatsThis = "Std_LinkImportAll"; + sStatusTip = sToolTipText; + eType = AlterDoc; + sPixmap = "LinkImportAll"; } -bool StdCmdLinkImportAll::isActive() { +bool StdCmdLinkImportAll::isActive() +{ auto doc = App::GetApplication().getActiveDocument(); return doc && !doc->testStatus(App::Document::PartialDoc) && App::PropertyXLink::hasXLink(doc); } -void StdCmdLinkImportAll::activated(int) { +void StdCmdLinkImportAll::activated(int) +{ Command::openCommand(QT_TRANSLATE_NOOP("Command", "Import all links")); try { WaitCursor wc; wc.setIgnoreEvents(WaitCursor::NoEvents); auto doc = App::GetApplication().getActiveDocument(); - if(doc) { - for(auto obj : doc->importLinks()) + if (doc) { + for (auto obj : doc->importLinks()) { obj->Visibility.setValue(false); + } } Command::commitCommand(); - } catch (const Base::Exception& e) { - QMessageBox::critical(getMainWindow(), QObject::tr("Failed to import all links"), - QString::fromLatin1(e.what())); + } + catch (const Base::Exception& e) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Failed to import all links"), + QString::fromLatin1(e.what()) + ); Command::abortCommand(); e.reportException(); } @@ -639,125 +762,145 @@ void StdCmdLinkImportAll::activated(int) { DEF_STD_CMD_A(StdCmdLinkSelectLinked) StdCmdLinkSelectLinked::StdCmdLinkSelectLinked() - : Command("Std_LinkSelectLinked") + : Command("Std_LinkSelectLinked") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("&Go to Linked Object"); - sToolTipText = QT_TR_NOOP("Selects the linked object and switches to its original document"); - sWhatsThis = "Std_LinkSelectLinked"; - sStatusTip = sToolTipText; - eType = AlterSelection; - sPixmap = "LinkSelect"; - sAccel = "S, G"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("&Go to Linked Object"); + sToolTipText = QT_TR_NOOP("Selects the linked object and switches to its original document"); + sWhatsThis = "Std_LinkSelectLinked"; + sStatusTip = sToolTipText; + eType = AlterSelection; + sPixmap = "LinkSelect"; + sAccel = "S, G"; } -static App::DocumentObject *getSelectedLink(bool finalLink, std::string *subname=nullptr) { - const auto &sels = Selection().getSelection("*", ResolveMode::NoResolve, true); - if(sels.empty()) +static App::DocumentObject* getSelectedLink(bool finalLink, std::string* subname = nullptr) +{ + const auto& sels = Selection().getSelection("*", ResolveMode::NoResolve, true); + if (sels.empty()) { return nullptr; + } auto sobj = sels[0].pObject->getSubObject(sels[0].SubName); - if(!sobj) + if (!sobj) { return nullptr; - auto vp = freecad_cast( - Application::Instance->getViewProvider(sobj)); - if(!vp) + } + auto vp = freecad_cast(Application::Instance->getViewProvider(sobj)); + if (!vp) { return nullptr; + } - auto linkedVp = vp->getLinkedViewProvider(subname,finalLink); - if(!linkedVp || linkedVp==vp) { - if(sobj->getDocument()==sels[0].pObject->getDocument()) + auto linkedVp = vp->getLinkedViewProvider(subname, finalLink); + if (!linkedVp || linkedVp == vp) { + if (sobj->getDocument() == sels[0].pObject->getDocument()) { return nullptr; - for(const char *dot=strchr(sels[0].SubName,'.');dot;dot=strchr(dot+1,'.')) { - std::string sub(sels[0].SubName,dot+1-sels[0].SubName); + } + for (const char* dot = strchr(sels[0].SubName, '.'); dot; dot = strchr(dot + 1, '.')) { + std::string sub(sels[0].SubName, dot + 1 - sels[0].SubName); auto obj = sels[0].pObject->getSubObject(sub.c_str()); - if(!obj) + if (!obj) { break; + } obj = obj->getLinkedObject(true); - if(obj->getDocument()!=sels[0].pObject->getDocument()) { - if(finalLink) - return sobj==obj?nullptr:sobj; - if(subname) - *subname = std::string(dot+1); + if (obj->getDocument() != sels[0].pObject->getDocument()) { + if (finalLink) { + return sobj == obj ? nullptr : sobj; + } + if (subname) { + *subname = std::string(dot + 1); + } return obj; } } - return finalLink?nullptr:sobj; + return finalLink ? nullptr : sobj; } - if(finalLink && linkedVp == vp->getLinkedViewProvider()) + if (finalLink && linkedVp == vp->getLinkedViewProvider()) { return nullptr; + } auto linked = linkedVp->getObject(); - if(!linked || !linked->isAttachedToDocument()) + if (!linked || !linked->isAttachedToDocument()) { return nullptr; + } - if(subname && sels[0].pObject!=sobj && sels[0].SubName) { + if (subname && sels[0].pObject != sobj && sels[0].SubName) { bool found = false; - int pre_len=0; - std::size_t post_len=0; + int pre_len = 0; + std::size_t post_len = 0; std::string prefix; std::string prefix2; // An object can be claimed by multiple objects. Let's try select one // that causes minimum jump in tree view, and prefer upper over lower // hierarchy (because of less depth/complexity of tree expansion) - for(auto &v : linked->getParents()) { - if(v.first != sels[0].pObject) + for (auto& v : linked->getParents()) { + if (v.first != sels[0].pObject) { continue; + } - const char *sub = v.second.c_str(); - const char *dot = sub; - for(const char *s=sels[0].SubName; *s && *sub==*s; ++s,++sub) { - if(*sub == '.') + const char* sub = v.second.c_str(); + const char* dot = sub; + for (const char* s = sels[0].SubName; *s && *sub == *s; ++s, ++sub) { + if (*sub == '.') { dot = sub; + } } found = true; - if(dot-v.second.c_str() > pre_len - || (dot-v.second.c_str()==pre_len - && v.second.size() pre_len + || (dot - v.second.c_str() == pre_len && v.second.size() < post_len)) { + pre_len = dot - v.second.c_str(); + prefix = std::string(sels[0].SubName, pre_len) + (v.second.c_str() + pre_len); post_len = v.second.size(); - }else if(!pre_len) { - if(prefix2.empty() || prefix2.size() > v.second.size()) + } + else if (!pre_len) { + if (prefix2.empty() || prefix2.size() > v.second.size()) { prefix2 = v.second; + } } } - if(found) { + if (found) { linked = sels[0].pObject; - *subname = !prefix.empty()?prefix:prefix2 + *subname; + *subname = !prefix.empty() ? prefix : prefix2 + *subname; } } return linked; } -bool StdCmdLinkSelectLinked::isActive() { +bool StdCmdLinkSelectLinked::isActive() +{ return getSelectedLink(false) != nullptr; } void StdCmdLinkSelectLinked::activated(int) { std::string subname; - auto linked = getSelectedLink(false,&subname); - if(!linked){ + auto linked = getSelectedLink(false, &subname); + if (!linked) { FC_WARN("invalid selection"); return; } Selection().selStackPush(); Selection().clearCompleteSelection(); - if(!subname.empty()) { - Selection().addSelection(linked->getDocument()->getName(),linked->getNameInDocument(),subname.c_str()); + if (!subname.empty()) { + Selection().addSelection( + linked->getDocument()->getName(), + linked->getNameInDocument(), + subname.c_str() + ); auto doc = Application::Instance->getDocument(linked->getDocument()); - if(doc) { - auto vp = freecad_cast(Application::Instance->getViewProvider(linked)); + if (doc) { + auto vp = freecad_cast( + Application::Instance->getViewProvider(linked) + ); doc->setActiveView(vp); } - } else { + } + else { const auto trees = getMainWindow()->findChildren(); - for(auto tree : trees) + for (auto tree : trees) { tree->selectLinkedObject(linked); + } } Selection().selStackPush(); } @@ -767,33 +910,38 @@ void StdCmdLinkSelectLinked::activated(int) DEF_STD_CMD_A(StdCmdLinkSelectLinkedFinal) StdCmdLinkSelectLinkedFinal::StdCmdLinkSelectLinkedFinal() - : Command("Std_LinkSelectLinkedFinal") + : Command("Std_LinkSelectLinkedFinal") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Go to &Deepest Linked Object"); - sToolTipText = QT_TR_NOOP("Selects the deepest linked object and switches to its original document"); - sWhatsThis = "Std_LinkSelectLinkedFinal"; - sStatusTip = sToolTipText; - eType = AlterSelection; - sPixmap = "LinkSelectFinal"; - sAccel = "S, D"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Go to &Deepest Linked Object"); + sToolTipText = QT_TR_NOOP( + "Selects the deepest linked object and switches to its original document" + ); + sWhatsThis = "Std_LinkSelectLinkedFinal"; + sStatusTip = sToolTipText; + eType = AlterSelection; + sPixmap = "LinkSelectFinal"; + sAccel = "S, D"; } -bool StdCmdLinkSelectLinkedFinal::isActive() { +bool StdCmdLinkSelectLinkedFinal::isActive() +{ return getSelectedLink(true) != nullptr; } -void StdCmdLinkSelectLinkedFinal::activated(int) { +void StdCmdLinkSelectLinkedFinal::activated(int) +{ auto linked = getSelectedLink(true); - if(!linked){ + if (!linked) { FC_WARN("invalid selection"); return; } Selection().selStackPush(); Selection().clearCompleteSelection(); const auto trees = getMainWindow()->findChildren(); - for(auto tree : trees) + for (auto tree : trees) { tree->selectLinkedObject(linked); + } Selection().selStackPush(); } @@ -802,34 +950,38 @@ void StdCmdLinkSelectLinkedFinal::activated(int) { DEF_STD_CMD_A(StdCmdLinkSelectAllLinks) StdCmdLinkSelectAllLinks::StdCmdLinkSelectAllLinks() - : Command("Std_LinkSelectAllLinks") + : Command("Std_LinkSelectAllLinks") { - sGroup = "Link"; - sMenuText = QT_TR_NOOP("Select &All Links"); - sToolTipText = QT_TR_NOOP("Selects all links to the current selected object"); - sWhatsThis = "Std_LinkSelectAllLinks"; - sStatusTip = sToolTipText; - eType = AlterSelection; - sPixmap = "LinkSelectAll"; + sGroup = "Link"; + sMenuText = QT_TR_NOOP("Select &All Links"); + sToolTipText = QT_TR_NOOP("Selects all links to the current selected object"); + sWhatsThis = "Std_LinkSelectAllLinks"; + sStatusTip = sToolTipText; + eType = AlterSelection; + sPixmap = "LinkSelectAll"; } -bool StdCmdLinkSelectAllLinks::isActive() { - const auto &sels = Selection().getSelection("*", ResolveMode::OldStyleElement, true); - if(sels.empty()) +bool StdCmdLinkSelectAllLinks::isActive() +{ + const auto& sels = Selection().getSelection("*", ResolveMode::OldStyleElement, true); + if (sels.empty()) { return false; + } return App::GetApplication().hasLinksTo(sels[0].pObject); } void StdCmdLinkSelectAllLinks::activated(int) { auto sels = Selection().getSelection("*", ResolveMode::OldStyleElement, true); - if(sels.empty()) + if (sels.empty()) { return; + } Selection().selStackPush(); Selection().clearCompleteSelection(); const auto trees = getMainWindow()->findChildren(); - for(auto tree : trees) + for (auto tree : trees) { tree->selectAllLinks(sels[0].pObject); + } Selection().selStackPush(); } @@ -838,45 +990,48 @@ void StdCmdLinkSelectAllLinks::activated(int) // Std_LinkSelectActions //=========================================================================== -class StdCmdLinkSelectActions : public GroupCommand +class StdCmdLinkSelectActions: public GroupCommand { public: StdCmdLinkSelectActions() : GroupCommand("Std_LinkSelectActions") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Link Navigation"); - sToolTipText = QT_TR_NOOP("Link navigation actions"); - sWhatsThis = "Std_LinkSelectActions"; - sStatusTip = sToolTipText; - eType = AlterSelection; - bCanLog = false; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Link Navigation"); + sToolTipText = QT_TR_NOOP("Link navigation actions"); + sWhatsThis = "Std_LinkSelectActions"; + sStatusTip = sToolTipText; + eType = AlterSelection; + bCanLog = false; addCommand(new StdCmdLinkSelectLinked()); addCommand(new StdCmdLinkSelectLinkedFinal()); addCommand(new StdCmdLinkSelectAllLinks()); } - const char* className() const override {return "StdCmdLinkSelectActions";} + const char* className() const override + { + return "StdCmdLinkSelectActions"; + } }; //====================================================================== // Std_LinkActions //=========================================================================== -class StdCmdLinkActions : public GroupCommand +class StdCmdLinkActions: public GroupCommand { public: StdCmdLinkActions() : GroupCommand("Std_LinkActions") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Link Actions"); - sToolTipText = QT_TR_NOOP("Commands that operate on link objects"); - sWhatsThis = "Std_LinkActions"; - sStatusTip = sToolTipText; - eType = AlterDoc; - bCanLog = false; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Link Actions"); + sToolTipText = QT_TR_NOOP("Commands that operate on link objects"); + sWhatsThis = "Std_LinkActions"; + sStatusTip = sToolTipText; + eType = AlterDoc; + bCanLog = false; setCheckable(false); @@ -904,16 +1059,15 @@ public: //=========================================================================== -namespace Gui { +namespace Gui +{ void CreateLinkCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdLinkActions()); rcCmdMgr.addCommand(new StdCmdLinkMakeGroup()); rcCmdMgr.addCommand(new StdCmdLinkSelectActions()); - } -} // namespace Gui - +} // namespace Gui diff --git a/src/Gui/CommandMacro.cpp b/src/Gui/CommandMacro.cpp index 30f1031c7d..0fea7e6c9e 100644 --- a/src/Gui/CommandMacro.cpp +++ b/src/Gui/CommandMacro.cpp @@ -20,9 +20,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "Command.h" #include "Action.h" @@ -44,27 +44,31 @@ using namespace Gui; DEF_STD_CMD_A(StdCmdDlgMacroRecord) StdCmdDlgMacroRecord::StdCmdDlgMacroRecord() - : Command("Std_DlgMacroRecord") + : Command("Std_DlgMacroRecord") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("Record &Macro"); + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("Record &Macro"); - sToolTipText = QT_TR_NOOP("Opens a dialog to record a macro"); - sWhatsThis = "Std_DlgMacroRecord"; - sStatusTip = sToolTipText; - sPixmap = "media-record"; - eType = 0; + sToolTipText = QT_TR_NOOP("Opens a dialog to record a macro"); + sWhatsThis = "Std_DlgMacroRecord"; + sStatusTip = sToolTipText; + sPixmap = "media-record"; + eType = 0; } void StdCmdDlgMacroRecord::activated(int iMsg) { Q_UNUSED(iMsg); - if (!getGuiApplication()->macroManager()->isOpen()){ + if (!getGuiApplication()->macroManager()->isOpen()) { Gui::Dialog::DlgMacroRecordImp cDlg(getMainWindow()); if (cDlg.exec() && getAction()) { getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("media-playback-stop")); - getAction()->setText(QCoreApplication::translate("StdCmdDlgMacroRecord", "S&top macro recording")); - getAction()->setToolTip(QCoreApplication::translate("StdCmdDlgMacroRecord", "Stop the macro recording session")); + getAction()->setText( + QCoreApplication::translate("StdCmdDlgMacroRecord", "S&top macro recording") + ); + getAction()->setToolTip( + QCoreApplication::translate("StdCmdDlgMacroRecord", "Stop the macro recording session") + ); } } else { @@ -88,16 +92,16 @@ bool StdCmdDlgMacroRecord::isActive() DEF_STD_CMD_A(StdCmdDlgMacroExecute) StdCmdDlgMacroExecute::StdCmdDlgMacroExecute() - : Command("Std_DlgMacroExecute") + : Command("Std_DlgMacroExecute") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("Ma&cros"); + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("Ma&cros"); - sToolTipText = QT_TR_NOOP("Opens a dialog to execute a recorded macro"); - sWhatsThis = "Std_DlgMacroExecute"; - sStatusTip = sToolTipText; - sPixmap = "accessories-text-editor"; - eType = 0; + sToolTipText = QT_TR_NOOP("Opens a dialog to execute a recorded macro"); + sWhatsThis = "Std_DlgMacroExecute"; + sStatusTip = sToolTipText; + sPixmap = "accessories-text-editor"; + eType = 0; } void StdCmdDlgMacroExecute::activated(int iMsg) @@ -109,7 +113,7 @@ void StdCmdDlgMacroExecute::activated(int iMsg) bool StdCmdDlgMacroExecute::isActive() { - return ! (getGuiApplication()->macroManager()->isOpen()); + return !(getGuiApplication()->macroManager()->isOpen()); } //=========================================================================== @@ -118,22 +122,22 @@ bool StdCmdDlgMacroExecute::isActive() DEF_STD_CMD_A(StdCmdDlgMacroExecuteDirect) StdCmdDlgMacroExecuteDirect::StdCmdDlgMacroExecuteDirect() - : Command("Std_DlgMacroExecuteDirect") + : Command("Std_DlgMacroExecuteDirect") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("&Execute Macro"); - sToolTipText = QT_TR_NOOP("Executes the macro in the editor"); - sWhatsThis = "Std_DlgMacroExecuteDirect"; - sStatusTip = sToolTipText; - sPixmap = "media-playback-start"; - sAccel = "Ctrl+F6"; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("&Execute Macro"); + sToolTipText = QT_TR_NOOP("Executes the macro in the editor"); + sWhatsThis = "Std_DlgMacroExecuteDirect"; + sStatusTip = sToolTipText; + sPixmap = "media-playback-start"; + sAccel = "Ctrl+F6"; + eType = 0; } void StdCmdDlgMacroExecuteDirect::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Run\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"Run\")"); } bool StdCmdDlgMacroExecuteDirect::isActive() @@ -144,22 +148,25 @@ bool StdCmdDlgMacroExecuteDirect::isActive() DEF_STD_CMD_A(StdCmdMacroAttachDebugger) StdCmdMacroAttachDebugger::StdCmdMacroAttachDebugger() - : Command("Std_MacroAttachDebugger") + : Command("Std_MacroAttachDebugger") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("&Attach to Remote Debugger"); + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("&Attach to Remote Debugger"); - sToolTipText = QT_TR_NOOP("Attaches to a remotely running debugger"); - sWhatsThis = "Std_MacroAttachDebugger"; - sStatusTip = sToolTipText; - eType = 0; + sToolTipText = QT_TR_NOOP("Attaches to a remotely running debugger"); + sWhatsThis = "Std_MacroAttachDebugger"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdMacroAttachDebugger::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Gui, "from freecad.gui import RemoteDebugger\n" - "RemoteDebugger.attachToRemoteDebugger()"); + doCommand( + Gui, + "from freecad.gui import RemoteDebugger\n" + "RemoteDebugger.attachToRemoteDebugger()" + ); } bool StdCmdMacroAttachDebugger::isActive() @@ -170,26 +177,28 @@ bool StdCmdMacroAttachDebugger::isActive() DEF_STD_CMD_A(StdCmdMacroStartDebug) StdCmdMacroStartDebug::StdCmdMacroStartDebug() - : Command("Std_MacroStartDebug") + : Command("Std_MacroStartDebug") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("&Debug Macro"); - sToolTipText = QT_TR_NOOP("Starts the debugging of macros"); - sWhatsThis = "Std_MacroStartDebug"; - sStatusTip = sToolTipText; - sPixmap = "debug-start"; - sAccel = "F6"; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("&Debug Macro"); + sToolTipText = QT_TR_NOOP("Starts the debugging of macros"); + sWhatsThis = "Std_MacroStartDebug"; + sStatusTip = sToolTipText; + sPixmap = "debug-start"; + sAccel = "F6"; + eType = 0; } void StdCmdMacroStartDebug::activated(int iMsg) { Q_UNUSED(iMsg); PythonDebugger* dbg = Application::Instance->macroManager()->debugger(); - if (!dbg->isRunning()) - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"StartDebug\")"); - else + if (!dbg->isRunning()) { + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"StartDebug\")"); + } + else { dbg->stepRun(); + } } bool StdCmdMacroStartDebug::isActive() @@ -200,16 +209,16 @@ bool StdCmdMacroStartDebug::isActive() DEF_STD_CMD_A(StdCmdMacroStopDebug) StdCmdMacroStopDebug::StdCmdMacroStopDebug() - : Command("Std_MacroStopDebug") + : Command("Std_MacroStopDebug") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("&Stop Debugging"); - sToolTipText = QT_TR_NOOP("Stops the debugging of macros"); - sWhatsThis = "Std_MacroStopDebug"; - sStatusTip = sToolTipText; - sPixmap = "debug-stop"; - sAccel = "Shift+F6"; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("&Stop Debugging"); + sToolTipText = QT_TR_NOOP("Stops the debugging of macros"); + sWhatsThis = "Std_MacroStopDebug"; + sStatusTip = sToolTipText; + sPixmap = "debug-stop"; + sAccel = "Shift+F6"; + eType = 0; } void StdCmdMacroStopDebug::activated(int iMsg) @@ -227,16 +236,16 @@ bool StdCmdMacroStopDebug::isActive() DEF_STD_CMD_A(StdCmdMacroStepOver) StdCmdMacroStepOver::StdCmdMacroStepOver() - : Command("Std_MacroStepOver") + : Command("Std_MacroStepOver") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("Step &Over"); - sToolTipText = QT_TR_NOOP("Steps to the next line in this file"); - sWhatsThis = "Std_MacroStepOver"; - sStatusTip = sToolTipText; - sPixmap = nullptr; - sAccel = "F10"; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("Step &Over"); + sToolTipText = QT_TR_NOOP("Steps to the next line in this file"); + sWhatsThis = "Std_MacroStepOver"; + sStatusTip = sToolTipText; + sPixmap = nullptr; + sAccel = "F10"; + eType = 0; } void StdCmdMacroStepOver::activated(int iMsg) @@ -254,16 +263,16 @@ bool StdCmdMacroStepOver::isActive() DEF_STD_CMD_A(StdCmdMacroStepInto) StdCmdMacroStepInto::StdCmdMacroStepInto() - : Command("Std_MacroStepInto") + : Command("Std_MacroStepInto") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("Step &Into"); - sToolTipText = QT_TR_NOOP("Steps to the next line executed"); - sWhatsThis = "Std_MacroStepInto"; - sStatusTip = sToolTipText; - sPixmap = nullptr; - sAccel = "F11"; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("Step &Into"); + sToolTipText = QT_TR_NOOP("Steps to the next line executed"); + sWhatsThis = "Std_MacroStepInto"; + sStatusTip = sToolTipText; + sPixmap = nullptr; + sAccel = "F11"; + eType = 0; } void StdCmdMacroStepInto::activated(int iMsg) @@ -281,22 +290,22 @@ bool StdCmdMacroStepInto::isActive() DEF_STD_CMD_A(StdCmdToggleBreakpoint) StdCmdToggleBreakpoint::StdCmdToggleBreakpoint() - : Command("Std_ToggleBreakpoint") + : Command("Std_ToggleBreakpoint") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("Toggle &Breakpoint"); - sToolTipText = QT_TR_NOOP("Adds or removes a breakpoint at this position"); - sWhatsThis = "Std_ToggleBreakpoint"; - sStatusTip = sToolTipText; - sPixmap = nullptr; - sAccel = "F9"; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("Toggle &Breakpoint"); + sToolTipText = QT_TR_NOOP("Adds or removes a breakpoint at this position"); + sWhatsThis = "Std_ToggleBreakpoint"; + sStatusTip = sToolTipText; + sPixmap = nullptr; + sAccel = "F9"; + eType = 0; } void StdCmdToggleBreakpoint::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ToggleBreakpoint\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ToggleBreakpoint\")"); } bool StdCmdToggleBreakpoint::isActive() @@ -307,16 +316,16 @@ bool StdCmdToggleBreakpoint::isActive() DEF_STD_CMD_A(StdCmdMacrosFolder) StdCmdMacrosFolder::StdCmdMacrosFolder() -: Command("Std_OpenMacrosFolder") + : Command("Std_OpenMacrosFolder") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("Open Macro Folder"); - sToolTipText = QT_TR_NOOP("Opens the macros folder in the system file manager"); - sWhatsThis = "Std_OpenMacrosFolder"; - sStatusTip = sToolTipText; - sPixmap = "MacroFolder"; - sAccel = ""; - eType = 0; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("Open Macro Folder"); + sToolTipText = QT_TR_NOOP("Opens the macros folder in the system file manager"); + sWhatsThis = "Std_OpenMacrosFolder"; + sStatusTip = sToolTipText; + sPixmap = "MacroFolder"; + sAccel = ""; + eType = 0; } void StdCmdMacrosFolder::activated(int iMsg) @@ -333,11 +342,12 @@ bool StdCmdMacrosFolder::isActive() return true; } -namespace Gui { +namespace Gui +{ void CreateMacroCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdDlgMacroRecord()); rcCmdMgr.addCommand(new StdCmdDlgMacroExecute()); rcCmdMgr.addCommand(new StdCmdMacrosFolder()); @@ -350,4 +360,4 @@ void CreateMacroCommands() rcCmdMgr.addCommand(new StdCmdToggleBreakpoint()); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/CommandPyImp.cpp b/src/Gui/CommandPyImp.cpp index ed71d9d21d..d2f5a4f2ce 100644 --- a/src/Gui/CommandPyImp.cpp +++ b/src/Gui/CommandPyImp.cpp @@ -20,9 +20,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -46,11 +46,12 @@ std::string CommandPy::representation() const return {""}; } -PyObject* CommandPy::get(PyObject *args) +PyObject* CommandPy::get(PyObject* args) { char* pName; - if (!PyArg_ParseTuple(args, "s", &pName)) + if (!PyArg_ParseTuple(args, "s", &pName)) { return nullptr; + } Command* cmd = Application::Instance->commandManager().getCommandByName(pName); if (cmd) { @@ -61,64 +62,70 @@ PyObject* CommandPy::get(PyObject *args) Py_Return; } -PyObject* CommandPy::update(PyObject *args) +PyObject* CommandPy::update(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getMainWindow()->updateActions(); Py_Return; } -PyObject* CommandPy::listAll(PyObject *args) +PyObject* CommandPy::listAll(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - std::vector cmds = Application::Instance->commandManager().getAllCommands(); + std::vector cmds = Application::Instance->commandManager().getAllCommands(); PyObject* pyList = PyList_New(cmds.size()); - int i=0; - for (const auto & cmd : cmds) { + int i = 0; + for (const auto& cmd : cmds) { PyObject* str = PyUnicode_FromString(cmd->getName()); PyList_SetItem(pyList, i++, str); } return pyList; } -PyObject* CommandPy::listByShortcut(PyObject *args) +PyObject* CommandPy::listByShortcut(PyObject* args) { char* shortcut_to_find; PyObject* bIsRegularExp = Py_False; - if (!PyArg_ParseTuple(args, "s|O!", &shortcut_to_find, &PyBool_Type, &bIsRegularExp)) + if (!PyArg_ParseTuple(args, "s|O!", &shortcut_to_find, &PyBool_Type, &bIsRegularExp)) { return nullptr; + } - std::vector cmds = Application::Instance->commandManager().getAllCommands(); - std::vector matches; + std::vector cmds = Application::Instance->commandManager().getAllCommands(); + std::vector matches; for (Command* c : cmds) { Action* action = c->getAction(); if (action) { QString spc = QStringLiteral(" "); if (Base::asBoolean(bIsRegularExp)) { - QRegularExpression re(QString::fromLatin1(shortcut_to_find), QRegularExpression::CaseInsensitiveOption); - if (!re.isValid()) { - std::stringstream str; - str << "Invalid regular expression:" << ' ' << shortcut_to_find; - throw Py::RuntimeError(str.str()); - } + QRegularExpression re( + QString::fromLatin1(shortcut_to_find), + QRegularExpression::CaseInsensitiveOption + ); + if (!re.isValid()) { + std::stringstream str; + str << "Invalid regular expression:" << ' ' << shortcut_to_find; + throw Py::RuntimeError(str.str()); + } - if (re.match(action->shortcut().toString().remove(spc).toUpper()).hasMatch()) { - matches.emplace_back(c->getName()); - } + if (re.match(action->shortcut().toString().remove(spc).toUpper()).hasMatch()) { + matches.emplace_back(c->getName()); + } } - else if (action->shortcut().toString().remove(spc).toUpper() == - QString::fromLatin1(shortcut_to_find).remove(spc).toUpper()) { + else if (action->shortcut().toString().remove(spc).toUpper() + == QString::fromLatin1(shortcut_to_find).remove(spc).toUpper()) { matches.emplace_back(c->getName()); } } } PyObject* pyList = PyList_New(matches.size()); - int i=0; + int i = 0; for (const std::string& match : matches) { PyObject* str = PyUnicode_FromString(match.c_str()); PyList_SetItem(pyList, i++, str); @@ -126,11 +133,12 @@ PyObject* CommandPy::listByShortcut(PyObject *args) return pyList; } -PyObject* CommandPy::run(PyObject *args) +PyObject* CommandPy::run(PyObject* args) { int item = 0; - if (!PyArg_ParseTuple(args, "|i", &item)) + if (!PyArg_ParseTuple(args, "|i", &item)) { return nullptr; + } Gui::Command::LogDisabler d1; Gui::SelectionLogDisabler d2; @@ -146,14 +154,16 @@ PyObject* CommandPy::run(PyObject *args) } } -PyObject* CommandPy::isActive(PyObject *args) const +PyObject* CommandPy::isActive(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Command* cmd = this->getCommandPtr(); if (cmd) { - PY_TRY { + PY_TRY + { return Py::new_reference_to(Py::Boolean(cmd->isActive())); } PY_CATCH; @@ -164,14 +174,17 @@ PyObject* CommandPy::isActive(PyObject *args) const } } -PyObject* CommandPy::getShortcut(PyObject *args) +PyObject* CommandPy::getShortcut(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Command* cmd = this->getCommandPtr(); if (cmd) { - PyObject* str = PyUnicode_FromString(cmd->getAction() ? cmd->getAction()->shortcut().toString().toStdString().c_str() : ""); + PyObject* str = PyUnicode_FromString( + cmd->getAction() ? cmd->getAction()->shortcut().toString().toStdString().c_str() : "" + ); return str; } else { @@ -180,11 +193,12 @@ PyObject* CommandPy::getShortcut(PyObject *args) } } -PyObject* CommandPy::setShortcut(PyObject *args) +PyObject* CommandPy::setShortcut(PyObject* args) { char* pShortcut; - if (!PyArg_ParseTuple(args, "s", &pShortcut)) + if (!PyArg_ParseTuple(args, "s", &pShortcut)) { return nullptr; + } Command* cmd = this->getCommandPtr(); if (cmd) { @@ -197,26 +211,29 @@ PyObject* CommandPy::setShortcut(PyObject *args) } } -PyObject* CommandPy::resetShortcut(PyObject *args) +PyObject* CommandPy::resetShortcut(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Command* cmd = this->getCommandPtr(); if (cmd) { ShortcutManager::instance()->reset(cmd->getName()); return Py::new_reference_to(Py::Boolean(true)); - } else { + } + else { PyErr_Format(Base::PyExc_FC_GeneralError, "No such command"); return nullptr; } } -PyObject* CommandPy::getInfo(PyObject *args) +PyObject* CommandPy::getInfo(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Command* cmd = this->getCommandPtr(); if (cmd) { @@ -229,8 +246,9 @@ PyObject* CommandPy::getInfo(PyObject *args) const char* statustipTxt = cmd->getStatusTip(); const char* pixMapTxt = cmd->getPixmap(); std::string shortcutTxt; - if (action) + if (action) { shortcutTxt = action->shortcut().toString().toStdString(); + } PyObject* strCmdName = PyUnicode_FromString(cmdName); PyObject* strMenuTxt = PyUnicode_FromString(menuTxt ? menuTxt : ""); @@ -238,7 +256,9 @@ PyObject* CommandPy::getInfo(PyObject *args) PyObject* strWhatsThisTxt = PyUnicode_FromString(whatsThisTxt ? whatsThisTxt : ""); PyObject* strStatustipTxt = PyUnicode_FromString(statustipTxt ? statustipTxt : ""); PyObject* strPixMapTxt = PyUnicode_FromString(pixMapTxt ? pixMapTxt : ""); - PyObject* strShortcutTxt = PyUnicode_FromString(!shortcutTxt.empty() ? shortcutTxt.c_str() : ""); + PyObject* strShortcutTxt = PyUnicode_FromString( + !shortcutTxt.empty() ? shortcutTxt.c_str() : "" + ); PyDict_SetItemString(pyDict, "name", strCmdName); PyDict_SetItemString(pyDict, "menuText", strMenuTxt); PyDict_SetItemString(pyDict, "toolTip", strTooltipTxt); @@ -254,10 +274,11 @@ PyObject* CommandPy::getInfo(PyObject *args) } } -PyObject* CommandPy::getAction(PyObject *args) +PyObject* CommandPy::getAction(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Command* cmd = this->getCommandPtr(); if (cmd) { @@ -270,8 +291,9 @@ PyObject* CommandPy::getAction(PyObject *args) Py::List list; if (group) { const auto actions = group->actions(); - for (auto a : actions) + for (auto a : actions) { list.append(wrap.fromQAction(a)); + } } else if (action) { list.append(wrap.fromQAction(action->action())); @@ -295,10 +317,29 @@ PyObject* CommandPy::createCustomCommand(PyObject* args, PyObject* kw) const char* statustipTxt = nullptr; const char* pixmapTxt = nullptr; const char* shortcutTxt = nullptr; - static std::array kwlist {"macroFile", "menuText", "toolTip", "whatsThis", - "statusTip", "pixmap", "shortcut", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kw, "s|zzzzzz", kwlist, ¯oFile, &menuTxt, - &tooltipTxt, &whatsthisTxt, &statustipTxt, &pixmapTxt, &shortcutTxt)) { + static std::array kwlist { + "macroFile", + "menuText", + "toolTip", + "whatsThis", + "statusTip", + "pixmap", + "shortcut", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kw, + "s|zzzzzz", + kwlist, + ¯oFile, + &menuTxt, + &tooltipTxt, + &whatsthisTxt, + &statustipTxt, + &pixmapTxt, + &shortcutTxt + )) { return nullptr; } @@ -309,23 +350,29 @@ PyObject* CommandPy::createCustomCommand(PyObject* args, PyObject* kw) macro->setScriptName(macroFile); - if (menuTxt) + if (menuTxt) { macro->setMenuText(menuTxt); + } - if (tooltipTxt) + if (tooltipTxt) { macro->setToolTipText(tooltipTxt); + } - if (whatsthisTxt) + if (whatsthisTxt) { macro->setWhatsThis(whatsthisTxt); + } - if (statustipTxt) + if (statustipTxt) { macro->setStatusTip(statustipTxt); + } - if (pixmapTxt) + if (pixmapTxt) { macro->setPixmap(pixmapTxt); + } - if (shortcutTxt) + if (shortcutTxt) { macro->setAccel(shortcutTxt); + } return PyUnicode_FromString(name.c_str()); } @@ -333,8 +380,9 @@ PyObject* CommandPy::createCustomCommand(PyObject* args, PyObject* kw) PyObject* CommandPy::removeCustomCommand(PyObject* args) { const char* actionName = nullptr; - if (!PyArg_ParseTuple(args, "s", &actionName)) + if (!PyArg_ParseTuple(args, "s", &actionName)) { return nullptr; + } CommandManager& commandManager = Application::Instance->commandManager(); std::vector macros = commandManager.getGroupCommands("Macros"); @@ -355,26 +403,31 @@ PyObject* CommandPy::removeCustomCommand(PyObject* args) PyObject* CommandPy::findCustomCommand(PyObject* args) { const char* macroScriptName = nullptr; - if (!PyArg_ParseTuple(args, "s", ¯oScriptName)) + if (!PyArg_ParseTuple(args, "s", ¯oScriptName)) { return nullptr; + } CommandManager& commandManager = Application::Instance->commandManager(); std::vector macros = commandManager.getGroupCommands("Macros"); auto action = std::find_if(macros.begin(), macros.end(), [macroScriptName](const Command* c) { - if (auto mc = dynamic_cast(c)) - if (std::string(mc->getScriptName()) == std::string(macroScriptName)) + if (auto mc = dynamic_cast(c)) { + if (std::string(mc->getScriptName()) == std::string(macroScriptName)) { return true; + } + } return false; - }); + }); - if (action != macros.end()) + if (action != macros.end()) { return PyUnicode_FromString((*action)->getName()); - else + } + else { Py_Return; + } } -PyObject *CommandPy::getCustomAttributes(const char* /*attr*/) const +PyObject* CommandPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Gui/CommandStd.cpp b/src/Gui/CommandStd.cpp index aecf061e14..377b811027 100644 --- a/src/Gui/CommandStd.cpp +++ b/src/Gui/CommandStd.cpp @@ -1,35 +1,35 @@ - // SPDX-License-Identifier: LGPL-2.1-or-later +// SPDX-License-Identifier: LGPL-2.1-or-later - /**************************************************************************** - * Copyright (c) 2002 Jürgen Riegel * - * Copyright (c) 2023 FreeCAD Project Association * - * * - * This file is part of FreeCAD. * - * * - * FreeCAD is free software: you can redistribute it and/or modify it * - * under the terms of the GNU Lesser General Public License as * - * published by the Free Software Foundation, either version 2.1 of the * - * License, or (at your option) any later version. * - * * - * FreeCAD 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 * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with FreeCAD. If not, see * - * . * - * * - ***************************************************************************/ +/**************************************************************************** + * Copyright (c) 2002 Jürgen Riegel * + * Copyright (c) 2023 FreeCAD Project Association * + * * + * This file is part of FreeCAD. * + * * + * FreeCAD is free software: you can redistribute it and/or modify it * + * under the terms of the GNU Lesser General Public License as * + * published by the Free Software Foundation, either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * FreeCAD 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 * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with FreeCAD. If not, see * + * . * + * * + ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -66,15 +66,15 @@ namespace sp = std::placeholders; DEF_STD_CMD_AC(StdCmdWorkbench) StdCmdWorkbench::StdCmdWorkbench() - : Command("Std_Workbench") + : Command("Std_Workbench") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Workbench"); - sToolTipText = QT_TR_NOOP("Switches between workbenches"); - sWhatsThis = "Std_Workbench"; - sStatusTip = sToolTipText; - sPixmap = "freecad"; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Workbench"); + sToolTipText = QT_TR_NOOP("Switches between workbenches"); + sWhatsThis = "Std_Workbench"; + sStatusTip = sToolTipText; + sPixmap = "freecad"; + eType = 0; } void StdCmdWorkbench::activated(int i) @@ -85,24 +85,29 @@ void StdCmdWorkbench::activated(int i) std::string switch_to = (const char*)items[i]->objectName().toLatin1(); if (w) { std::string current_w = w->name(); - if (switch_to == current_w) + if (switch_to == current_w) { return; + } } doCommand(Gui, "Gui.activateWorkbench(\"%s\")", switch_to.c_str()); } - catch(const Base::PyException& e) { + catch (const Base::PyException& e) { QString msg(QLatin1String(e.what())); // ignore '' prefixes QRegularExpression rx; rx.setPattern(QLatin1String(R"(^\s*:\s*)")); auto match = rx.match(msg); - if (match.hasMatch()) + if (match.hasMatch()) { msg = msg.mid(match.capturedLength()); + } QMessageBox::critical(getMainWindow(), QObject::tr("Cannot load workbench"), msg); } - catch(...) { - QMessageBox::critical(getMainWindow(), QObject::tr("Cannot load workbench"), - QObject::tr("A general error occurred while loading the workbench")); + catch (...) { + QMessageBox::critical( + getMainWindow(), + QObject::tr("Cannot load workbench"), + QObject::tr("A general error occurred while loading the workbench") + ); } } @@ -111,15 +116,16 @@ bool StdCmdWorkbench::isActive() return true; } -Action * StdCmdWorkbench::createAction() +Action* StdCmdWorkbench::createAction() { - Action *pcAction; + Action* pcAction; - pcAction = new WorkbenchGroup(this,getMainWindow()); + pcAction = new WorkbenchGroup(this, getMainWindow()); pcAction->setShortcut(QString::fromLatin1(getAccel())); applyCommandData(this->className(), pcAction); - if (getPixmap()) + if (getPixmap()) { pcAction->setIcon(Gui::BitmapFactory().iconFromTheme(getPixmap())); + } return pcAction; } @@ -131,15 +137,15 @@ Action * StdCmdWorkbench::createAction() DEF_STD_CMD_C(StdCmdRecentFiles) StdCmdRecentFiles::StdCmdRecentFiles() - :Command("Std_RecentFiles") + : Command("Std_RecentFiles") { - sGroup = "File"; - sMenuText = QT_TR_NOOP("Open &Recent"); - sToolTipText = QT_TR_NOOP("Displays the list of recently opened files"); - sWhatsThis = "Std_RecentFiles"; - sStatusTip = sToolTipText; - sPixmap = "Std_RecentFiles"; - eType = NoTransaction; + sGroup = "File"; + sMenuText = QT_TR_NOOP("Open &Recent"); + sToolTipText = QT_TR_NOOP("Displays the list of recently opened files"); + sWhatsThis = "Std_RecentFiles"; + sStatusTip = sToolTipText; + sPixmap = "Std_RecentFiles"; + eType = NoTransaction; } /** @@ -150,13 +156,15 @@ StdCmdRecentFiles::StdCmdRecentFiles() void StdCmdRecentFiles::activated(int iMsg) { auto act = qobject_cast(_pcAction); - if (act) act->activateFile( iMsg ); + if (act) { + act->activateFile(iMsg); + } } /** * Creates the QAction object containing the recent files. */ -Action * StdCmdRecentFiles::createAction() +Action* StdCmdRecentFiles::createAction() { auto pcAction = new RecentFilesAction(this, getMainWindow()); pcAction->setObjectName(QLatin1String("recentFiles")); @@ -172,15 +180,15 @@ Action * StdCmdRecentFiles::createAction() DEF_STD_CMD_C(StdCmdRecentMacros) StdCmdRecentMacros::StdCmdRecentMacros() - :Command("Std_RecentMacros") + : Command("Std_RecentMacros") { - sGroup = "Macro"; - sMenuText = QT_TR_NOOP("&Recent Macros"); - sToolTipText = QT_TR_NOOP("Displays the list of recently used macros"); - sWhatsThis = "Std_RecentMacros"; + sGroup = "Macro"; + sMenuText = QT_TR_NOOP("&Recent Macros"); + sToolTipText = QT_TR_NOOP("Displays the list of recently used macros"); + sWhatsThis = "Std_RecentMacros"; sStatusTip = sToolTipText; - sPixmap = "Std_RecentMacros"; - eType = NoTransaction; + sPixmap = "Std_RecentMacros"; + eType = NoTransaction; } /** @@ -191,13 +199,15 @@ StdCmdRecentMacros::StdCmdRecentMacros() void StdCmdRecentMacros::activated(int iMsg) { auto act = qobject_cast(_pcAction); - if (act) act->activateFile( iMsg ); + if (act) { + act->activateFile(iMsg); + } } /** * Creates the QAction object containing the recent macros. */ -Action * StdCmdRecentMacros::createAction() +Action* StdCmdRecentMacros::createAction() { auto pcAction = new RecentMacrosAction(this, getMainWindow()); pcAction->setObjectName(QLatin1String("recentMacros")); @@ -213,28 +223,25 @@ Action * StdCmdRecentMacros::createAction() DEF_STD_CMD_ACL(StdCmdAbout) StdCmdAbout::StdCmdAbout() - :Command("Std_About") + : Command("Std_About") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("&About %1"); - sToolTipText = QT_TR_NOOP("Displays information about %1"); - sWhatsThis = "Std_About"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("&About %1"); + sToolTipText = QT_TR_NOOP("Displays information about %1"); + sWhatsThis = "Std_About"; + sStatusTip = sToolTipText; + eType = 0; } -Action * StdCmdAbout::createAction() +Action* StdCmdAbout::createAction() { - Action *pcAction; + Action* pcAction; QString exe = qApp->applicationName(); pcAction = new Action(this, getMainWindow()); - pcAction->setText(QCoreApplication::translate( - this->className(), getMenuText()).arg(exe)); - pcAction->setToolTip(QCoreApplication::translate( - this->className(), getToolTipText()).arg(exe)); - pcAction->setStatusTip(QCoreApplication::translate( - this->className(), getStatusTip()).arg(exe)); + pcAction->setText(QCoreApplication::translate(this->className(), getMenuText()).arg(exe)); + pcAction->setToolTip(QCoreApplication::translate(this->className(), getToolTipText()).arg(exe)); + pcAction->setStatusTip(QCoreApplication::translate(this->className(), getStatusTip()).arg(exe)); pcAction->setWhatsThis(QLatin1String(getWhatsThis())); pcAction->setIcon(QApplication::windowIcon()); pcAction->setShortcut(QString::fromLatin1(getAccel())); @@ -263,12 +270,13 @@ void StdCmdAbout::languageChange() { if (_pcAction) { QString exe = qApp->applicationName(); - _pcAction->setText(QCoreApplication::translate( - this->className(), getMenuText()).arg(exe)); - _pcAction->setToolTip(QCoreApplication::translate( - this->className(), getToolTipText()).arg(exe)); - _pcAction->setStatusTip(QCoreApplication::translate( - this->className(), getStatusTip()).arg(exe)); + _pcAction->setText(QCoreApplication::translate(this->className(), getMenuText()).arg(exe)); + _pcAction->setToolTip( + QCoreApplication::translate(this->className(), getToolTipText()).arg(exe) + ); + _pcAction->setStatusTip( + QCoreApplication::translate(this->className(), getStatusTip()).arg(exe) + ); _pcAction->setWhatsThis(QLatin1String(getWhatsThis())); } } @@ -279,14 +287,14 @@ void StdCmdAbout::languageChange() DEF_STD_CMD(StdCmdAboutQt) StdCmdAboutQt::StdCmdAboutQt() - :Command("Std_AboutQt") + : Command("Std_AboutQt") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("About &Qt"); - sToolTipText = QT_TR_NOOP("Displays information about Qt"); - sWhatsThis = "Std_AboutQt"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("About &Qt"); + sToolTipText = QT_TR_NOOP("Displays information about Qt"); + sWhatsThis = "Std_AboutQt"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdAboutQt::activated(int iMsg) @@ -301,16 +309,16 @@ void StdCmdAboutQt::activated(int iMsg) DEF_STD_CMD(StdCmdWhatsThis) StdCmdWhatsThis::StdCmdWhatsThis() - :Command("Std_WhatsThis") + : Command("Std_WhatsThis") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("&What's This?"); - sToolTipText = QT_TR_NOOP("Opens the documentation for the selected command"); - sWhatsThis = "Std_WhatsThis"; - sStatusTip = sToolTipText; - sAccel = keySequenceToAccel(QKeySequence::WhatsThis); - sPixmap = "WhatsThis"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("&What's This?"); + sToolTipText = QT_TR_NOOP("Opens the documentation for the selected command"); + sWhatsThis = "Std_WhatsThis"; + sStatusTip = sToolTipText; + sAccel = keySequenceToAccel(QKeySequence::WhatsThis); + sPixmap = "WhatsThis"; + eType = 0; } void StdCmdWhatsThis::activated(int iMsg) @@ -325,15 +333,15 @@ void StdCmdWhatsThis::activated(int iMsg) DEF_STD_CMD(StdCmdRestartInSafeMode) StdCmdRestartInSafeMode::StdCmdRestartInSafeMode() - :Command("Std_RestartInSafeMode") + : Command("Std_RestartInSafeMode") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("Restart in Safe Mode"); - sToolTipText = QT_TR_NOOP("Starts FreeCAD without any modules or plugins loaded"); - sWhatsThis = "Std_RestartInSafeMode"; - sStatusTip = sToolTipText; - sPixmap = "safe-mode-restart"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("Restart in Safe Mode"); + sToolTipText = QT_TR_NOOP("Starts FreeCAD without any modules or plugins loaded"); + sWhatsThis = "Std_RestartInSafeMode"; + sStatusTip = sToolTipText; + sPixmap = "safe-mode-restart"; + eType = 0; } void StdCmdRestartInSafeMode::activated(int iMsg) @@ -344,15 +352,16 @@ void StdCmdRestartInSafeMode::activated(int iMsg) restartBox.setIcon(QMessageBox::Warning); restartBox.setWindowTitle(QObject::tr("Restart in Safe Mode")); restartBox.setText(QObject::tr("Restart FreeCAD and enter safe mode?")); - restartBox.setInformativeText(QObject::tr("Safe mode temporarily disables the configuration and addons.")); + restartBox.setInformativeText( + QObject::tr("Safe mode temporarily disables the configuration and addons.") + ); restartBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); restartBox.setDefaultButton(QMessageBox::No); if (restartBox.exec() == QMessageBox::Yes) { - //restart FreeCAD after a delay to give time to this dialog to close + // restart FreeCAD after a delay to give time to this dialog to close const int ms = 1000; - QTimer::singleShot(ms, []() - { + QTimer::singleShot(ms, []() { QStringList args = QApplication::arguments(); args.pop_front(); auto const safeModeArgument = QStringLiteral("--safe-mode"); @@ -372,16 +381,16 @@ void StdCmdRestartInSafeMode::activated(int iMsg) DEF_STD_CMD(StdCmdDlgParameter) StdCmdDlgParameter::StdCmdDlgParameter() - :Command("Std_DlgParameter") + : Command("Std_DlgParameter") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("E&dit Parameters"); + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("E&dit Parameters"); - sToolTipText = QT_TR_NOOP("Opens a dialog to edit the parameters"); - sWhatsThis = "Std_DlgParameter"; - sStatusTip = sToolTipText; - sPixmap = "Std_DlgParameter"; - eType = 0; + sToolTipText = QT_TR_NOOP("Opens a dialog to edit the parameters"); + sWhatsThis = "Std_DlgParameter"; + sStatusTip = sToolTipText; + sPixmap = "Std_DlgParameter"; + eType = 0; } void StdCmdDlgParameter::activated(int iMsg) @@ -398,22 +407,22 @@ void StdCmdDlgParameter::activated(int iMsg) DEF_STD_CMD_C(StdCmdDlgPreferences) StdCmdDlgPreferences::StdCmdDlgPreferences() - :Command("Std_DlgPreferences") + : Command("Std_DlgPreferences") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Prefere&nces"); + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Prefere&nces"); - sToolTipText = QT_TR_NOOP("Opens a dialog to edit the preferences"); - sWhatsThis = "Std_DlgPreferences"; - sStatusTip = sToolTipText; - sPixmap = "preferences-system"; - eType = 0; - sAccel = "Ctrl+,"; + sToolTipText = QT_TR_NOOP("Opens a dialog to edit the preferences"); + sWhatsThis = "Std_DlgPreferences"; + sStatusTip = sToolTipText; + sPixmap = "preferences-system"; + eType = 0; + sAccel = "Ctrl+,"; } -Action * StdCmdDlgPreferences::createAction() +Action* StdCmdDlgPreferences::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); pcAction->setMenuRole(QAction::PreferencesRole); return pcAction; @@ -423,11 +432,13 @@ void StdCmdDlgPreferences::activated(int iMsg) { Q_UNUSED(iMsg); - static QString groupName{}; - static int index{}; + static QString groupName {}; + static int index {}; Gui::Dialog::DlgPreferencesImp cDlg(getMainWindow()); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences" + ); if (hGrp->GetBool("RestoreGroupPage", true)) { cDlg.activateGroupPage(groupName, index); } @@ -443,23 +454,24 @@ void StdCmdDlgPreferences::activated(int iMsg) DEF_STD_CMD(StdCmdDlgCustomize) StdCmdDlgCustomize::StdCmdDlgCustomize() - :Command("Std_DlgCustomize") + : Command("Std_DlgCustomize") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Cu&stomize…"); - sToolTipText = QT_TR_NOOP("Opens a dialog to edit toolbars, shortcuts, and macros"); - sWhatsThis = "Std_DlgCustomize"; - sStatusTip = sToolTipText; - sPixmap = "applications-accessories"; - eType = 0; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Cu&stomize…"); + sToolTipText = QT_TR_NOOP("Opens a dialog to edit toolbars, shortcuts, and macros"); + sWhatsThis = "Std_DlgCustomize"; + sStatusTip = sToolTipText; + sPixmap = "applications-accessories"; + eType = 0; } void StdCmdDlgCustomize::activated(int iMsg) { Q_UNUSED(iMsg); static QPointer dlg = nullptr; - if (!dlg) + if (!dlg) { dlg = new Gui::Dialog::DlgCustomizeImp(getMainWindow()); + } dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->show(); } @@ -470,33 +482,33 @@ void StdCmdDlgCustomize::activated(int iMsg) DEF_STD_CMD(StdCmdCommandLine) StdCmdCommandLine::StdCmdCommandLine() - :Command("Std_CommandLine") + : Command("Std_CommandLine") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Command &Line"); + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Command &Line"); - sToolTipText = QT_TR_NOOP("Opens a command line interface in the console"); - sWhatsThis = "Std_CommandLine"; - sStatusTip = sToolTipText; - sPixmap = "utilities-terminal"; - eType = 0; + sToolTipText = QT_TR_NOOP("Opens a command line interface in the console"); + sWhatsThis = "Std_CommandLine"; + sStatusTip = sToolTipText; + sPixmap = "utilities-terminal"; + eType = 0; } void StdCmdCommandLine::activated(int iMsg) { Q_UNUSED(iMsg); - bool show = getMainWindow()->isMaximized (); + bool show = getMainWindow()->isMaximized(); // pop up the Gui command window GUIConsole Wnd; - getMainWindow()->showMinimized () ; + getMainWindow()->showMinimized(); qApp->processEvents(); // create temporary console sequencer { - Base::ConsoleSequencer seq; - Base::Interpreter().runCommandLine("Console mode"); + Base::ConsoleSequencer seq; + Base::Interpreter().runCommandLine("Console mode"); } #ifdef Q_WS_X11 @@ -508,7 +520,7 @@ void StdCmdCommandLine::activated(int iMsg) #endif // pop up the main window - show ? getMainWindow()->showMaximized () : getMainWindow()->showNormal () ; + show ? getMainWindow()->showMaximized() : getMainWindow()->showNormal(); qApp->processEvents(); } @@ -519,16 +531,16 @@ void StdCmdCommandLine::activated(int iMsg) DEF_STD_CMD(StdCmdOnlineHelp) StdCmdOnlineHelp::StdCmdOnlineHelp() - :Command("Std_OnlineHelp") + : Command("Std_OnlineHelp") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("&Help"); - sToolTipText = QT_TR_NOOP("Opens the Help documentation"); - sWhatsThis = "Std_OnlineHelp"; - sStatusTip = sToolTipText; - sPixmap = "help-browser"; - sAccel = keySequenceToAccel(QKeySequence::HelpContents); - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("&Help"); + sToolTipText = QT_TR_NOOP("Opens the Help documentation"); + sWhatsThis = "Std_OnlineHelp"; + sStatusTip = sToolTipText; + sPixmap = "help-browser"; + sAccel = keySequenceToAccel(QKeySequence::HelpContents); + eType = 0; } void StdCmdOnlineHelp::activated(int iMsg) @@ -544,21 +556,25 @@ void StdCmdOnlineHelp::activated(int iMsg) DEF_STD_CMD(StdCmdOnlineHelpWebsite) StdCmdOnlineHelpWebsite::StdCmdOnlineHelpWebsite() - :Command("Std_OnlineHelpWebsite") + : Command("Std_OnlineHelpWebsite") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("Help Website"); - sToolTipText = QT_TR_NOOP("Opens the help documentation"); - sWhatsThis = "Std_OnlineHelpWebsite"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("Help Website"); + sToolTipText = QT_TR_NOOP("Opens the help documentation"); + sWhatsThis = "Std_OnlineHelpWebsite"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdOnlineHelpWebsite::activated(int iMsg) { Q_UNUSED(iMsg); - std::string defaulturl = QCoreApplication::translate(this->className(),"https://wiki.freecad.org/Online_Help_Toc").toStdString(); - ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites"); + std::string defaulturl + = QCoreApplication::translate(this->className(), "https://wiki.freecad.org/Online_Help_Toc") + .toStdString(); + ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("OnlineHelp", defaulturl.c_str()); hURLGrp->SetASCII("OnlineHelp", url.c_str()); OpenURLInBrowser(url.c_str()); @@ -571,21 +587,23 @@ void StdCmdOnlineHelpWebsite::activated(int iMsg) DEF_STD_CMD(StdCmdFreeCADDonation) StdCmdFreeCADDonation::StdCmdFreeCADDonation() - :Command("Std_FreeCADDonation") + : Command("Std_FreeCADDonation") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("Donate to FreeCA&D"); - sToolTipText = QT_TR_NOOP("Support the FreeCAD development"); - sWhatsThis = "Std_FreeCADDonation"; - sStatusTip = sToolTipText; - sPixmap = "internet-web-browser"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("Donate to FreeCA&D"); + sToolTipText = QT_TR_NOOP("Support the FreeCAD development"); + sWhatsThis = "Std_FreeCADDonation"; + sStatusTip = sToolTipText; + sPixmap = "internet-web-browser"; + eType = 0; } void StdCmdFreeCADDonation::activated(int iMsg) { Q_UNUSED(iMsg); - ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites"); + ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("DonatePage", "https://www.freecad.org/sponsor"); hURLGrp->SetASCII("DonatePage", url.c_str()); OpenURLInBrowser(url.c_str()); @@ -618,7 +636,8 @@ void StdCmdDevHandbook::activated(int iMsg) { Q_UNUSED(iMsg); ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Websites"); + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("DevHandbook", "https://freecad.github.io/DevelopersHandbook/"); hURLGrp->SetASCII("DevHandbook", url.c_str()); @@ -632,22 +651,25 @@ void StdCmdDevHandbook::activated(int iMsg) DEF_STD_CMD(StdCmdFreeCADWebsite) StdCmdFreeCADWebsite::StdCmdFreeCADWebsite() - :Command("Std_FreeCADWebsite") + : Command("Std_FreeCADWebsite") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("FreeCAD W&ebsite"); - sToolTipText = QT_TR_NOOP("Navigates to the official FreeCAD website"); - sWhatsThis = "Std_FreeCADWebsite"; - sStatusTip = sToolTipText; - sPixmap = "internet-web-browser"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("FreeCAD W&ebsite"); + sToolTipText = QT_TR_NOOP("Navigates to the official FreeCAD website"); + sWhatsThis = "Std_FreeCADWebsite"; + sStatusTip = sToolTipText; + sPixmap = "internet-web-browser"; + eType = 0; } void StdCmdFreeCADWebsite::activated(int iMsg) { Q_UNUSED(iMsg); - std::string defaulturl = QCoreApplication::translate(this->className(),"https://www.freecad.org").toStdString(); - ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites"); + std::string defaulturl + = QCoreApplication::translate(this->className(), "https://www.freecad.org").toStdString(); + ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("WebPage", defaulturl.c_str()); hURLGrp->SetASCII("WebPage", url.c_str()); OpenURLInBrowser(url.c_str()); @@ -660,22 +682,26 @@ void StdCmdFreeCADWebsite::activated(int iMsg) DEF_STD_CMD(StdCmdFreeCADUserHub) StdCmdFreeCADUserHub::StdCmdFreeCADUserHub() - :Command("Std_FreeCADUserHub") + : Command("Std_FreeCADUserHub") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("&User Documentation"); - sToolTipText = QT_TR_NOOP("Opens the documentation for users"); - sWhatsThis = "Std_FreeCADUserHub"; - sStatusTip = sToolTipText; - sPixmap = "internet-web-browser"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("&User Documentation"); + sToolTipText = QT_TR_NOOP("Opens the documentation for users"); + sWhatsThis = "Std_FreeCADUserHub"; + sStatusTip = sToolTipText; + sPixmap = "internet-web-browser"; + eType = 0; } void StdCmdFreeCADUserHub::activated(int iMsg) { Q_UNUSED(iMsg); - std::string defaulturl = QCoreApplication::translate(this->className(),"https://wiki.freecad.org/User_hub").toStdString(); - ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites"); + std::string defaulturl + = QCoreApplication::translate(this->className(), "https://wiki.freecad.org/User_hub") + .toStdString(); + ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("Documentation", defaulturl.c_str()); hURLGrp->SetASCII("Documentation", url.c_str()); OpenURLInBrowser(url.c_str()); @@ -688,22 +714,25 @@ void StdCmdFreeCADUserHub::activated(int iMsg) DEF_STD_CMD(StdCmdFreeCADForum) StdCmdFreeCADForum::StdCmdFreeCADForum() - :Command("Std_FreeCADForum") + : Command("Std_FreeCADForum") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("FreeCAD &Forum"); - sToolTipText = QT_TR_NOOP("The FreeCAD forum, where you can find help from other users"); - sWhatsThis = "Std_FreeCADForum"; - sStatusTip = sToolTipText; - sPixmap = "internet-web-browser"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("FreeCAD &Forum"); + sToolTipText = QT_TR_NOOP("The FreeCAD forum, where you can find help from other users"); + sWhatsThis = "Std_FreeCADForum"; + sStatusTip = sToolTipText; + sPixmap = "internet-web-browser"; + eType = 0; } void StdCmdFreeCADForum::activated(int iMsg) { Q_UNUSED(iMsg); - std::string defaulturl = QCoreApplication::translate(this->className(),"https://forum.freecad.org").toStdString(); - ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites"); + std::string defaulturl + = QCoreApplication::translate(this->className(), "https://forum.freecad.org").toStdString(); + ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("UserForum", defaulturl.c_str()); hURLGrp->SetASCII("UserForum", url.c_str()); OpenURLInBrowser(url.c_str()); @@ -716,21 +745,23 @@ void StdCmdFreeCADForum::activated(int iMsg) DEF_STD_CMD(StdCmdReportBug) StdCmdReportBug::StdCmdReportBug() - :Command("Std_ReportBug") + : Command("Std_ReportBug") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("Report an &Issue"); - sToolTipText = QT_TR_NOOP("Opens the bugtracker to report an issue"); - sWhatsThis = "Std_ReportBug"; - sStatusTip = sToolTipText; - sPixmap = "internet-web-browser"; - eType = 0; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("Report an &Issue"); + sToolTipText = QT_TR_NOOP("Opens the bugtracker to report an issue"); + sWhatsThis = "Std_ReportBug"; + sStatusTip = sToolTipText; + sPixmap = "internet-web-browser"; + eType = 0; } void StdCmdReportBug::activated(int iMsg) { Q_UNUSED(iMsg); - ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Websites"); + ParameterGrp::handle hURLGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Websites" + ); std::string url = hURLGrp->GetASCII("IssuesPage", "https://github.com/FreeCAD/FreeCAD/issues"); hURLGrp->SetASCII("IssuesPage", url.c_str()); OpenURLInBrowser(url.c_str()); @@ -743,15 +774,15 @@ void StdCmdReportBug::activated(int iMsg) DEF_STD_CMD_A(StdCmdTextDocument) StdCmdTextDocument::StdCmdTextDocument() - :Command("Std_TextDocument") + : Command("Std_TextDocument") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Te&xt Document"); - sToolTipText = QT_TR_NOOP("Adds a text document to the active document"); - sWhatsThis = "Std_TextDocument"; - sStatusTip = sToolTipText; - sPixmap = "TextDocument"; - eType = 0; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Te&xt Document"); + sToolTipText = QT_TR_NOOP("Adds a text document to the active document"); + sWhatsThis = "Std_TextDocument"; + sStatusTip = sToolTipText; + sPixmap = "TextDocument"; + eType = 0; } void StdCmdTextDocument::activated(int iMsg) @@ -759,7 +790,12 @@ void StdCmdTextDocument::activated(int iMsg) Q_UNUSED(iMsg); openCommand(QT_TRANSLATE_NOOP("Command", "Insert text document")); - doCommand(Doc, "App.ActiveDocument.addObject(\"App::TextDocument\",\"%s\").Label=\"%s\"","Text document","Text document"); + doCommand( + Doc, + "App.ActiveDocument.addObject(\"App::TextDocument\",\"%s\").Label=\"%s\"", + "Text document", + "Text document" + ); doCommand(Gui, "Gui.ActiveDocument.ActiveObject.doubleClicked()"); updateActive(); commitCommand(); @@ -776,71 +812,77 @@ bool StdCmdTextDocument::isActive() DEF_STD_CMD(StdCmdUnitsCalculator) StdCmdUnitsCalculator::StdCmdUnitsCalculator() - : Command("Std_UnitsCalculator") + : Command("Std_UnitsCalculator") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("&Units Converter"); + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("&Units Converter"); - sToolTipText = QT_TR_NOOP("Starts the units converter"); - sWhatsThis = "Std_UnitsCalculator"; - sStatusTip = sToolTipText; - sPixmap = "accessories-calculator"; - eType = 0; + sToolTipText = QT_TR_NOOP("Starts the units converter"); + sWhatsThis = "Std_UnitsCalculator"; + sStatusTip = sToolTipText; + sPixmap = "accessories-calculator"; + eType = 0; } void StdCmdUnitsCalculator::activated(int iMsg) { Q_UNUSED(iMsg); - auto dlg = new Gui::Dialog::DlgUnitsCalculator( getMainWindow() ); + auto dlg = new Gui::Dialog::DlgUnitsCalculator(getMainWindow()); dlg->show(); } //=========================================================================== // StdCmdUserEditMode //=========================================================================== -class StdCmdUserEditMode : public Gui::Command +class StdCmdUserEditMode: public Gui::Command { public: StdCmdUserEditMode(); ~StdCmdUserEditMode() override = default; void languageChange() override; - const char* className() const override {return "StdCmdUserEditMode";} + const char* className() const override + { + return "StdCmdUserEditMode"; + } void updateIcon(int mode); + protected: void activated(int iMsg) override; bool isActive() override; - Gui::Action * createAction() override; + Gui::Action* createAction() override; }; StdCmdUserEditMode::StdCmdUserEditMode() - : Command("Std_UserEditMode") + : Command("Std_UserEditMode") { - sGroup = "Edit"; - sMenuText = QT_TR_NOOP("Edit &Mode"); - sToolTipText = QT_TR_NOOP("Defines behavior when editing an object from the tree view"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_UserEditMode"; - sPixmap = "Std_UserEditModeDefault"; - eType = ForEdit; + sGroup = "Edit"; + sMenuText = QT_TR_NOOP("Edit &Mode"); + sToolTipText = QT_TR_NOOP("Defines behavior when editing an object from the tree view"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_UserEditMode"; + sPixmap = "Std_UserEditModeDefault"; + eType = ForEdit; this->getGuiApplication()->signalUserEditModeChanged.connect([this](int mode) { this->updateIcon(mode); }); } -Gui::Action * StdCmdUserEditMode::createAction() +Gui::Action* StdCmdUserEditMode::createAction() { auto pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); pcAction->setIsMode(true); applyCommandData(this->className(), pcAction); - for (auto const &uem : Gui::Application::Instance->listUserEditModes()) { + for (auto const& uem : Gui::Application::Instance->listUserEditModes()) { QAction* act = pcAction->addAction(QString()); auto modeName = QString::fromStdString(uem.second.first).remove(QChar::fromLatin1('&')); act->setCheckable(true); - act->setIcon(BitmapFactory().iconFromTheme(qPrintable(QStringLiteral("Std_UserEditMode")+modeName))); - act->setObjectName(QStringLiteral("Std_UserEditMode")+modeName); + act->setIcon( + BitmapFactory().iconFromTheme(qPrintable(QStringLiteral("Std_UserEditMode") + modeName)) + ); + act->setObjectName(QStringLiteral("Std_UserEditMode") + modeName); act->setWhatsThis(QString::fromLatin1(getWhatsThis())); act->setToolTip(QString::fromStdString(uem.second.second)); @@ -852,8 +894,9 @@ Gui::Action * StdCmdUserEditMode::createAction() _pcAction = pcAction; - int lastMode = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> - GetInt("UserEditMode", 0); + int lastMode = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetInt("UserEditMode", 0); Gui::Application::Instance->setUserEditMode(lastMode); languageChange(); @@ -864,33 +907,34 @@ void StdCmdUserEditMode::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } auto pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); - for (int i = 0 ; i < a.count() ; i++) { + for (int i = 0; i < a.count(); i++) { auto modeName = Gui::Application::Instance->getUserEditModeUIStrings(i); - a[i]->setText(QCoreApplication::translate( - "EditMode", modeName.first.c_str())); - a[i]->setToolTip(QCoreApplication::translate( - "EditMode", modeName.second.c_str())); + a[i]->setText(QCoreApplication::translate("EditMode", modeName.first.c_str())); + a[i]->setToolTip(QCoreApplication::translate("EditMode", modeName.second.c_str())); } } void StdCmdUserEditMode::updateIcon(int mode) { - auto actionGroup = dynamic_cast(_pcAction); - if (!actionGroup) + auto actionGroup = dynamic_cast(_pcAction); + if (!actionGroup) { return; + } actionGroup->setCheckedAction(mode); } void StdCmdUserEditMode::activated(int iMsg) { - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> - SetInt("UserEditMode", iMsg); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->SetInt("UserEditMode", iMsg); Gui::Application::Instance->setUserEditMode(iMsg); } @@ -905,27 +949,28 @@ bool StdCmdUserEditMode::isActive() DEF_STD_CMD(StdCmdReloadStyleSheet) StdCmdReloadStyleSheet::StdCmdReloadStyleSheet() - : Command("Std_ReloadStyleSheet") + : Command("Std_ReloadStyleSheet") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Reload Stylesheet"); - sToolTipText = QT_TR_NOOP("Reloads the current stylesheet"); - sWhatsThis = "Std_ReloadStyleSheet"; - sStatusTip = sToolTipText; - sPixmap = "view-refresh"; - sWhatsThis = "Std_ReloadStyleSheet"; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Reload Stylesheet"); + sToolTipText = QT_TR_NOOP("Reloads the current stylesheet"); + sWhatsThis = "Std_ReloadStyleSheet"; + sStatusTip = sToolTipText; + sPixmap = "view-refresh"; + sWhatsThis = "Std_ReloadStyleSheet"; } -void StdCmdReloadStyleSheet::activated(int ) +void StdCmdReloadStyleSheet::activated(int) { Application::Instance->reloadStyleSheet(); } -namespace Gui { +namespace Gui +{ void CreateStdCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdAbout()); rcCmdMgr.addCommand(new StdCmdAboutQt()); @@ -952,8 +997,8 @@ void CreateStdCommands() rcCmdMgr.addCommand(new StdCmdUserEditMode()); rcCmdMgr.addCommand(new StdCmdReloadStyleSheet()); rcCmdMgr.addCommand(new StdCmdDevHandbook()); - //rcCmdMgr.addCommand(new StdCmdDownloadOnlineHelp()); - //rcCmdMgr.addCommand(new StdCmdDescription()); + // rcCmdMgr.addCommand(new StdCmdDownloadOnlineHelp()); + // rcCmdMgr.addCommand(new StdCmdDescription()); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/CommandStructure.cpp b/src/Gui/CommandStructure.cpp index 3d56c3782c..194f3629dc 100644 --- a/src/Gui/CommandStructure.cpp +++ b/src/Gui/CommandStructure.cpp @@ -43,16 +43,18 @@ using namespace Gui; DEF_STD_CMD_A(StdCmdPart) StdCmdPart::StdCmdPart() - : Command("Std_Part") + : Command("Std_Part") { - sGroup = "Structure"; - sMenuText = QT_TR_NOOP("New Part"); - sToolTipText = QT_TR_NOOP("Creates a part, which is a general-purpose container to group objects so they " - "act as a unit in the 3D view. It is intended to arrange objects that have a part " - "TopoShape, like part primitives, Part Design bodies, and other parts."); - sWhatsThis = "Std_Part"; - sStatusTip = sToolTipText; - sPixmap = "Geofeaturegroup"; + sGroup = "Structure"; + sMenuText = QT_TR_NOOP("New Part"); + sToolTipText = QT_TR_NOOP( + "Creates a part, which is a general-purpose container to group objects so they " + "act as a unit in the 3D view. It is intended to arrange objects that have a part " + "TopoShape, like part primitives, Part Design bodies, and other parts." + ); + sWhatsThis = "Std_Part"; + sStatusTip = sToolTipText; + sPixmap = "Geofeaturegroup"; } void StdCmdPart::activated(int iMsg) @@ -64,25 +66,40 @@ void StdCmdPart::activated(int iMsg) std::string PartName; PartName = getUniqueObjectName("Part"); - doCommand(Doc,"App.activeDocument().Tip = App.activeDocument().addObject('App::Part','%s')",PartName.c_str()); + doCommand( + Doc, + "App.activeDocument().Tip = App.activeDocument().addObject('App::Part','%s')", + PartName.c_str() + ); // TODO We really must set label ourselves? (2015-08-17, Fat-Zer) - doCommand(Doc,"App.activeDocument().%s.Label = '%s'", PartName.c_str(), - QObject::tr(PartName.c_str()).toUtf8().data()); + doCommand( + Doc, + "App.activeDocument().%s.Label = '%s'", + PartName.c_str(), + QObject::tr(PartName.c_str()).toUtf8().data() + ); - doCommand(Doc, - "selected_objects = Gui.Selection.getSelection()\n" - "if len(selected_objects) > 1:\n" - " for obj in selected_objects:\n" - " # Add subobjects if obj is a container\n" - " if hasattr(obj, 'OutList') and len(obj.OutList) > 0:\n" - " for child in obj.OutList:\n" - " App.activeDocument().%s.addObject(child)\n" - " App.activeDocument().%s.addObject(obj)\n", - PartName.c_str(), PartName.c_str()); + doCommand( + Doc, + "selected_objects = Gui.Selection.getSelection()\n" + "if len(selected_objects) > 1:\n" + " for obj in selected_objects:\n" + " # Add subobjects if obj is a container\n" + " if hasattr(obj, 'OutList') and len(obj.OutList) > 0:\n" + " for child in obj.OutList:\n" + " App.activeDocument().%s.addObject(child)\n" + " App.activeDocument().%s.addObject(obj)\n", + PartName.c_str(), + PartName.c_str() + ); - doCommand(Gui::Command::Gui, "Gui.activateView('Gui::View3DInventor', True)\n" - "Gui.activeView().setActiveObject('%s', App.activeDocument().%s)", - PARTKEY, PartName.c_str()); + doCommand( + Gui::Command::Gui, + "Gui.activateView('Gui::View3DInventor', True)\n" + "Gui.activeView().setActiveObject('%s', App.activeDocument().%s)", + PARTKEY, + PartName.c_str() + ); updateActive(); } @@ -98,16 +115,18 @@ bool StdCmdPart::isActive() DEF_STD_CMD_A(StdCmdGroup) StdCmdGroup::StdCmdGroup() - : Command("Std_Group") + : Command("Std_Group") { - sGroup = "Structure"; - sMenuText = QT_TR_NOOP("New Group"); - sToolTipText = QT_TR_NOOP("Creates a group, which is a general-purpose container to group objects in the " - "tree view, regardless of their data type. It is a simple folder to organize " - "the objects in a model."); - sWhatsThis = "Std_Group"; - sStatusTip = sToolTipText; - sPixmap = "folder"; + sGroup = "Structure"; + sMenuText = QT_TR_NOOP("New Group"); + sToolTipText = QT_TR_NOOP( + "Creates a group, which is a general-purpose container to group objects in the " + "tree view, regardless of their data type. It is a simple folder to organize " + "the objects in a model." + ); + sWhatsThis = "Std_Group"; + sStatusTip = sToolTipText; + sPixmap = "folder"; } void StdCmdGroup::activated(int iMsg) @@ -121,32 +140,40 @@ void StdCmdGroup::activated(int iMsg) QString label = QApplication::translate("Std_Group", "Group"); // create a group - doCommand(Doc,"group = App.activeDocument().addObject('App::DocumentObjectGroup','%s')",GroupName.c_str()); - doCommand(Doc,"group.Label = '%s'", label.toUtf8().data()); - doCommand(Doc,"App.activeDocument().Tip = group"); + doCommand( + Doc, + "group = App.activeDocument().addObject('App::DocumentObjectGroup','%s')", + GroupName.c_str() + ); + doCommand(Doc, "group.Label = '%s'", label.toUtf8().data()); + doCommand(Doc, "App.activeDocument().Tip = group"); // try to add the group to any active object that supports grouping (has GroupExtension) if (auto* activeDoc = Gui::Application::Instance->activeDocument()) { if (auto* activeView = activeDoc->getActiveView()) { // find the first active object with GroupExtension if (auto* activeObj = activeView->getActiveObjectWithExtension( - App::GroupExtension::getExtensionClassTypeId())) { - doCommand(Doc, - "active_obj = App.activeDocument().getObject('%s')\n" - "if active_obj and active_obj.allowObject(group):\n" - " active_obj.Group += [group]", - activeObj->getNameInDocument()); + App::GroupExtension::getExtensionClassTypeId() + )) { + doCommand( + Doc, + "active_obj = App.activeDocument().getObject('%s')\n" + "if active_obj and active_obj.allowObject(group):\n" + " active_obj.Group += [group]", + activeObj->getNameInDocument() + ); } } - } // if we have no active object, group will be added to root doc + } // if we have no active object, group will be added to root doc commitCommand(); Gui::Document* gui = Application::Instance->activeDocument(); App::Document* app = gui->getDocument(); ViewProvider* vp = gui->getViewProvider(app->getActiveObject()); - if (vp && vp->isDerivedFrom()) + if (vp && vp->isDerivedFrom()) { gui->signalScrollToObject(*static_cast(vp)); + } } bool StdCmdGroup::isActive() @@ -160,14 +187,15 @@ bool StdCmdGroup::isActive() DEF_STD_CMD_A(StdCmdVarSet) StdCmdVarSet::StdCmdVarSet() - : Command("Std_VarSet") + : Command("Std_VarSet") { - sGroup = "Structure"; - sMenuText = QT_TR_NOOP("Variable Set"); - sToolTipText = QT_TR_NOOP("Creates a variable set, which is an object that maintains a set of properties to be used as variables"); - sWhatsThis = "Std_VarSet"; - sStatusTip = sToolTipText; - sPixmap = "VarSet"; + sGroup = "Structure"; + sMenuText = QT_TR_NOOP("Variable Set"); + sToolTipText + = QT_TR_NOOP("Creates a variable set, which is an object that maintains a set of properties to be used as variables"); + sWhatsThis = "Std_VarSet"; + sStatusTip = sToolTipText; + sPixmap = "VarSet"; } void StdCmdVarSet::activated(int iMsg) @@ -178,14 +206,18 @@ void StdCmdVarSet::activated(int iMsg) std::string VarSetName; VarSetName = getUniqueObjectName("VarSet"); - doCommand(Doc,"App.activeDocument().addObject('App::VarSet','%s')",VarSetName.c_str()); + doCommand(Doc, "App.activeDocument().addObject('App::VarSet','%s')", VarSetName.c_str()); Gui::Document* docGui = Application::Instance->activeDocument(); App::Document* doc = docGui->getDocument(); // add the varset to a group if it is selected - auto sels = Selection().getSelectionEx(nullptr, App::DocumentObject::getClassTypeId(), - ResolveMode::OldStyleElement, true); + auto sels = Selection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + ResolveMode::OldStyleElement, + true + ); if (sels.size() == 1) { App::DocumentObject* obj = sels[0].getObject(); auto group = obj->getExtension(); @@ -208,15 +240,16 @@ bool StdCmdVarSet::isActive() return hasActiveDocument(); } -namespace Gui { +namespace Gui +{ void CreateStructureCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdPart()); rcCmdMgr.addCommand(new StdCmdGroup()); rcCmdMgr.addCommand(new StdCmdVarSet()); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/CommandT.h b/src/Gui/CommandT.h index 5715c48dfb..e1bd0b60d4 100644 --- a/src/Gui/CommandT.h +++ b/src/Gui/CommandT.h @@ -33,39 +33,50 @@ #include -namespace Gui { +namespace Gui +{ class FormatString { public: - static std::string str(const std::string& s) { + static std::string str(const std::string& s) + { return s; } - static std::string str(const char* s) { + static std::string str(const char* s) + { return s; } - static std::string str(const QString& s) { + static std::string str(const QString& s) + { return s.toStdString(); } - static std::string str(const std::stringstream& s) { + static std::string str(const std::stringstream& s) + { return s.str(); } - static std::string str(const std::ostringstream& s) { + static std::string str(const std::ostringstream& s) + { return s.str(); } - static std::string str(const std::ostream& s) { - if (typeid(s) == typeid(std::ostringstream)) + static std::string str(const std::ostream& s) + { + if (typeid(s) == typeid(std::ostringstream)) { return dynamic_cast(s).str(); - else if (typeid(s) == typeid(std::stringstream)) + } + else if (typeid(s) == typeid(std::stringstream)) { return dynamic_cast(s).str(); + } throw Base::TypeError("Not a std::stringstream or std::ostringstream"); } - static std::string toStr(boost::format& f) { + static std::string toStr(boost::format& f) + { return f.str(); } template - static std::string toStr(boost::format& f, T&& t, Args&&... args) { + static std::string toStr(boost::format& f, T&& t, Args&&... args) + { return toStr(f % std::forward(t), std::forward(args)...); } }; @@ -81,7 +92,8 @@ public: * * Example: * @code{.cpp} - * _cmdDocument(Gui::Command::Gui, doc, "Gui", std::stringstream() << "getObject('" << objName << "')"); + * _cmdDocument(Gui::Command::Gui, doc, "Gui", std::stringstream() << "getObject('" << objName + * << "')"); * @endcode * * Translates to command (assuming doc's name is 'DocName', and @@ -91,11 +103,16 @@ public: * @endcode */ template -void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const App::Document* doc, const std::string& mod, T&& cmd) { +void _cmdDocument( + Gui::Command::DoCmd_Type cmdType, + const App::Document* doc, + const std::string& mod, + T&& cmd +) +{ if (doc && doc->getName()) { std::stringstream str; - str << mod << ".getDocument('" << doc->getName() << "')." - << FormatString::str(cmd); + str << mod << ".getDocument('" << doc->getName() << "')." << FormatString::str(cmd); Gui::Command::runCommand(cmdType, str.str().c_str()); } } @@ -108,7 +125,8 @@ void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const App::Document* doc, co * * Example: * @code{.cpp} - * _cmdDocument(Gui::Command::Gui, doc, "Gui", std::stringstream() << "getObject('" << objName << "')"); + * _cmdDocument(Gui::Command::Gui, doc, "Gui", std::stringstream() << "getObject('" << objName + * << "')"); * @endcode * * Translates to command (assuming doc's name is 'DocName', and @@ -118,11 +136,11 @@ void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const App::Document* doc, co * @endcode */ template -void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const std::string& doc, const std::string& mod, T&& cmd) { +void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const std::string& doc, const std::string& mod, T&& cmd) +{ if (!doc.empty()) { std::stringstream str; - str << mod << ".getDocument('" << doc << "')." - << FormatString::str(cmd); + str << mod << ".getDocument('" << doc << "')." << FormatString::str(cmd); Gui::Command::runCommand(cmdType, str.str().c_str()); } } @@ -146,7 +164,8 @@ void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const std::string& doc, cons * @endcode */ template -inline void cmdAppDocument(const App::Document* doc, T&& cmd) { +inline void cmdAppDocument(const App::Document* doc, T&& cmd) +{ _cmdDocument(Gui::Command::Doc, doc, "App", std::forward(cmd)); } @@ -169,7 +188,8 @@ inline void cmdAppDocument(const App::Document* doc, T&& cmd) { * @endcode */ template -inline void cmdAppDocument(const std::string& doc, T&& cmd) { +inline void cmdAppDocument(const std::string& doc, T&& cmd) +{ _cmdDocument(Gui::Command::Doc, doc, "App", std::forward(cmd)); } @@ -191,7 +211,8 @@ inline void cmdAppDocument(const std::string& doc, T&& cmd) { * @endcode */ template -inline void cmdGuiDocument(const App::Document* doc, T&& cmd) { +inline void cmdGuiDocument(const App::Document* doc, T&& cmd) +{ _cmdDocument(Gui::Command::Gui, doc, "Gui", std::forward(cmd)); } @@ -213,7 +234,8 @@ inline void cmdGuiDocument(const App::Document* doc, T&& cmd) { * @endcode */ template -inline void cmdGuiDocument(const std::string& doc, T&& cmd) { +inline void cmdGuiDocument(const std::string& doc, T&& cmd) +{ _cmdDocument(Gui::Command::Gui, doc, "Gui", std::forward(cmd)); } @@ -224,8 +246,16 @@ inline void cmdGuiDocument(const std::string& doc, T&& cmd) { * @param cmd: command string, streamable */ template -inline void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const App::DocumentObject* obj, const std::string& mod, T&& cmd) { - if (obj) _cmdDocument(cmdType, obj->getDocument(), mod, std::forward(cmd)); +inline void _cmdDocument( + Gui::Command::DoCmd_Type cmdType, + const App::DocumentObject* obj, + const std::string& mod, + T&& cmd +) +{ + if (obj) { + _cmdDocument(cmdType, obj->getDocument(), mod, std::forward(cmd)); + } } /** Runs a command for accessing an object's App::Document attribute or method @@ -234,7 +264,8 @@ inline void _cmdDocument(Gui::Command::DoCmd_Type cmdType, const App::DocumentOb * @param cmd: command string, streamable */ template -inline void cmdAppDocument(const App::DocumentObject* obj, T&& cmd) { +inline void cmdAppDocument(const App::DocumentObject* obj, T&& cmd) +{ _cmdDocument(Gui::Command::Doc, obj, "App", std::forward(cmd)); } @@ -252,21 +283,30 @@ inline void cmdAppDocument(const App::DocumentObject* obj, T&& cmd) { * App.getDocument('DocName').addObject('Part::Feature') * @endcode */ -template -void cmdAppDocumentArgs(const App::Document* doc, const std::string& cmd, Args&&... args) { +template +void cmdAppDocumentArgs(const App::Document* doc, const std::string& cmd, Args&&... args) +{ std::string _cmd; try { boost::format fmt(cmd); _cmd = FormatString::toStr(fmt, std::forward(args)...); - Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument('%s').%s", - doc->getName(), _cmd.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').%s", + doc->getName(), + _cmd.c_str() + ); } catch (const std::exception& e) { - Base::Console().developerError(doc->Label.getStrValue(),"%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError(doc->Label.getStrValue(), "%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().developerError(doc->Label.getStrValue(),"App.getDocument('%s').%s\n", - doc->getName(), _cmd.c_str()); + Base::Console().developerError( + doc->Label.getStrValue(), + "App.getDocument('%s').%s\n", + doc->getName(), + _cmd.c_str() + ); throw; } } @@ -277,7 +317,8 @@ void cmdAppDocumentArgs(const App::Document* doc, const std::string& cmd, Args&& * @param cmd: command string, streamable */ template -inline void cmdGuiDocument(const App::DocumentObject* obj, T&& cmd) { +inline void cmdGuiDocument(const App::DocumentObject* obj, T&& cmd) +{ _cmdDocument(Gui::Command::Gui, obj, "Gui", std::forward(cmd)); } @@ -300,12 +341,19 @@ inline void cmdGuiDocument(const App::DocumentObject* obj, T&& cmd) { * @endcode */ template -void _cmdObject(Gui::Command::DoCmd_Type cmdType, const App::DocumentObject* obj, const std::string& mod, T&& cmd) { +void _cmdObject( + Gui::Command::DoCmd_Type cmdType, + const App::DocumentObject* obj, + const std::string& mod, + T&& cmd +) +{ if (obj && obj->isAttachedToDocument()) { std::ostringstream str; - str << mod << ".getDocument('" << obj->getDocument()->getName() << "')" - ".getObject('" << obj->getNameInDocument() << "')." - << FormatString::str(cmd); + str << mod << ".getDocument('" << obj->getDocument()->getName() + << "')" + ".getObject('" + << obj->getNameInDocument() << "')." << FormatString::str(cmd); Gui::Command::runCommand(cmdType, str.str().c_str()); } } @@ -317,7 +365,8 @@ void _cmdObject(Gui::Command::DoCmd_Type cmdType, const App::DocumentObject* obj * @sa _cmdObject() */ template -inline void cmdAppObject(const App::DocumentObject* obj, T&& cmd) { +inline void cmdAppObject(const App::DocumentObject* obj, T&& cmd) +{ _cmdObject(Gui::Command::Doc, obj, "App", std::forward(cmd)); } @@ -328,17 +377,20 @@ inline void cmdAppObject(const App::DocumentObject* obj, T&& cmd) { * @sa _cmdObject() */ template -inline void cmdGuiObject(const App::DocumentObject* obj, T&& cmd) { +inline void cmdGuiObject(const App::DocumentObject* obj, T&& cmd) +{ _cmdObject(Gui::Command::Gui, obj, "Gui", std::forward(cmd)); } /// Hides an object -inline void cmdAppObjectHide(const App::DocumentObject* obj) { +inline void cmdAppObjectHide(const App::DocumentObject* obj) +{ cmdAppObject(obj, "Visibility = False"); } /// Shows an object -inline void cmdAppObjectShow(const App::DocumentObject* obj) { +inline void cmdAppObjectShow(const App::DocumentObject* obj) +{ cmdAppObject(obj, "Visibility = True"); } @@ -351,11 +403,16 @@ inline void cmdAppObjectShow(const App::DocumentObject* obj) { * in-place editing an object, which may be brought in through linking to an * external group. */ -inline void cmdSetEdit(const App::DocumentObject* obj, int mod = 0) { +inline void cmdSetEdit(const App::DocumentObject* obj, int mod = 0) +{ if (obj && obj->isAttachedToDocument()) { - Gui::Command::doCommand(Gui::Command::Gui, + Gui::Command::doCommand( + Gui::Command::Gui, "Gui.ActiveDocument.setEdit(App.getDocument('%s').getObject('%s'), %d)", - obj->getDocument()->getName(), obj->getNameInDocument(), mod); + obj->getDocument()->getName(), + obj->getNameInDocument(), + mod + ); } } @@ -375,21 +432,32 @@ inline void cmdSetEdit(const App::DocumentObject* obj, int mod = 0) { * App.getDocument('DocName').getObject('ObjName').Visibility = True * @endcode */ -template -void cmdAppObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Args&&... args) { +template +void cmdAppObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Args&&... args) +{ std::string _cmd; try { boost::format fmt(cmd); _cmd = FormatString::toStr(fmt, std::forward(args)...); - Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument('%s').getObject('%s').%s", - obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').getObject('%s').%s", + obj->getDocument()->getName(), + obj->getNameInDocument(), + _cmd.c_str() + ); } catch (const std::exception& e) { - Base::Console().developerError(obj->getFullLabel(),"%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError(obj->getFullLabel(), "%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().developerError(obj->getFullLabel(),"App.getDocument('%s').getObject('%s').%s\n", - obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); + Base::Console().developerError( + obj->getFullLabel(), + "App.getDocument('%s').getObject('%s').%s\n", + obj->getDocument()->getName(), + obj->getNameInDocument(), + _cmd.c_str() + ); throw; } } @@ -400,21 +468,32 @@ void cmdAppObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Ar * @param obj: pointer to a DocumentObject * @sa cmdAppObjectArgs() */ -template -void cmdGuiObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Args&&... args) { +template +void cmdGuiObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Args&&... args) +{ std::string _cmd; try { boost::format fmt(cmd); _cmd = FormatString::toStr(fmt, std::forward(args)...); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.getDocument('%s').getObject('%s').%s", - obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); + Gui::Command::doCommand( + Gui::Command::Gui, + "Gui.getDocument('%s').getObject('%s').%s", + obj->getDocument()->getName(), + obj->getNameInDocument(), + _cmd.c_str() + ); } catch (const std::exception& e) { - Base::Console().developerError(obj->getFullLabel(),"%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError(obj->getFullLabel(), "%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().developerError(obj->getFullLabel(),"Gui.getDocument('%s').getObject('%s').%s\n", - obj->getDocument()->getName(), obj->getNameInDocument(), _cmd.c_str()); + Base::Console().developerError( + obj->getFullLabel(), + "Gui.getDocument('%s').getObject('%s').%s\n", + obj->getDocument()->getName(), + obj->getNameInDocument(), + _cmd.c_str() + ); throw; } } @@ -425,7 +504,8 @@ void cmdGuiObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Ar * * Example: * @code{.cpp} - * doCommandT(Gui::Command::Gui, "Gui.getDocument(%s).getObject(%s).Visibility = %s", "DocName", "ObjName", visible?"True":"False"); + * doCommandT(Gui::Command::Gui, "Gui.getDocument(%s).getObject(%s).Visibility = %s", + * "DocName", "ObjName", visible?"True":"False"); * @endcode * * Translates to command (assuming obj's document name is 'DocName', obj's name @@ -434,34 +514,35 @@ void cmdGuiObjectArgs(const App::DocumentObject* obj, const std::string& cmd, Ar * Gui.getDocument('DocName').getObject('ObjName').Visibility = True * @endcode */ -template -void doCommandT(Gui::Command::DoCmd_Type cmdType, const std::string& cmd, Args&&... args) { +template +void doCommandT(Gui::Command::DoCmd_Type cmdType, const std::string& cmd, Args&&... args) +{ std::string _cmd; try { boost::format fmt(cmd); _cmd = FormatString::toStr(fmt, std::forward(args)...); - Gui::Command::doCommand(cmdType,"%s", _cmd.c_str()); + Gui::Command::doCommand(cmdType, "%s", _cmd.c_str()); } catch (const std::exception& e) { - Base::Console().developerError("doCommandT","%s: %s\n", e.what(), cmd.c_str()); + Base::Console().developerError("doCommandT", "%s: %s\n", e.what(), cmd.c_str()); } catch (const Base::Exception&) { - Base::Console().developerError("doCommandT","%s\n", _cmd.c_str()); + Base::Console().developerError("doCommandT", "%s\n", _cmd.c_str()); throw; } } /** Copy visual attributes from a source to a target object */ -template -void copyVisualT(Args&&... args) { +template +void copyVisualT(Args&&... args) +{ // file and line number is useless here. Check C++'s source location function once available Gui::Command::_copyVisual(__FILE__, __LINE__, std::forward(args)...); } //@} -}; - -#endif // GUI_COMMAND_T_H +}; // namespace Gui +#endif // GUI_COMMAND_T_H diff --git a/src/Gui/CommandTest.cpp b/src/Gui/CommandTest.cpp index 803860c4b6..7bed0acdbf 100644 --- a/src/Gui/CommandTest.cpp +++ b/src/Gui/CommandTest.cpp @@ -20,19 +20,19 @@ * * ***************************************************************************/ -# 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 @@ -53,27 +53,31 @@ using namespace Gui; DEF_STD_CMD(Std_TestQM) Std_TestQM::Std_TestQM() - : Command("Std_TestQM") + : Command("Std_TestQM") { - sGroup = "Standard-Test"; + sGroup = "Standard-Test"; sMenuText = "Test Translation Files"; - sToolTipText = "Runs a test to verify .qm translation files"; - sWhatsThis = "Std_TestQM"; - sStatusTip = sToolTipText; + sToolTipText = "Runs a test to verify .qm translation files"; + sWhatsThis = "Std_TestQM"; + sStatusTip = sToolTipText; } void Std_TestQM::activated(int iMsg) { Q_UNUSED(iMsg); - QStringList files = QFileDialog::getOpenFileNames(getMainWindow(), - QStringLiteral("Test translation"), QString(), - QStringLiteral("Translation (*.qm)")); + QStringList files = QFileDialog::getOpenFileNames( + getMainWindow(), + QStringLiteral("Test translation"), + QString(), + QStringLiteral("Translation (*.qm)") + ); if (!files.empty()) { Translator::instance()->activateLanguage("English"); QList i18n = qApp->findChildren(); - for (QTranslator* it : i18n) + for (QTranslator* it : i18n) { qApp->removeTranslator(it); + } for (const QString& it : files) { auto translator = new QTranslator(qApp); if (translator->load(it)) { @@ -92,13 +96,13 @@ void Std_TestQM::activated(int iMsg) DEF_STD_CMD(Std_TestReloadQM) Std_TestReloadQM::Std_TestReloadQM() - : Command("Std_TestReloadQM") + : Command("Std_TestReloadQM") { - sGroup = "Standard-Test"; - sMenuText = "Reload Translation Files"; - sToolTipText = "Reloads the translation files"; - sWhatsThis = "Std_TestReloadQM"; - sStatusTip = sToolTipText; + sGroup = "Standard-Test"; + sMenuText = "Reload Translation Files"; + sToolTipText = "Reloads the translation files"; + sWhatsThis = "Std_TestReloadQM"; + sStatusTip = sToolTipText; } void Std_TestReloadQM::activated(int iMsg) @@ -113,15 +117,15 @@ void Std_TestReloadQM::activated(int iMsg) DEF_STD_CMD_A(FCCmdTest1) FCCmdTest1::FCCmdTest1() - : Command("Std_Test1") + : Command("Std_Test1") { - sGroup = "Standard-Test"; - sMenuText = "Test1"; - sToolTipText = "Test function 1"; - sWhatsThis = "Std_Test1"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool1"; - sAccel = "Ctrl+T"; + sGroup = "Standard-Test"; + sMenuText = "Test1"; + sToolTipText = "Test function 1"; + sWhatsThis = "Std_Test1"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool1"; + sAccel = "Ctrl+T"; } void FCCmdTest1::activated(int iMsg) @@ -131,7 +135,7 @@ void FCCmdTest1::activated(int iMsg) bool FCCmdTest1::isActive() { - //return (GetActiveOCCDocument()!=NULL); + // return (GetActiveOCCDocument()!=NULL); return true; } @@ -141,14 +145,14 @@ bool FCCmdTest1::isActive() DEF_STD_CMD_A(FCCmdTest2) FCCmdTest2::FCCmdTest2() - : Command("Std_Test2") + : Command("Std_Test2") { - sGroup = "Standard-Test"; - sMenuText = "Test2"; - sToolTipText = "Test function 2"; - sWhatsThis = "Std_Test2"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool2"; + sGroup = "Standard-Test"; + sMenuText = "Test2"; + sToolTipText = "Test function 2"; + sWhatsThis = "Std_Test2"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool2"; } @@ -168,22 +172,23 @@ bool FCCmdTest2::isActive() DEF_STD_CMD_A(FCCmdTest3) FCCmdTest3::FCCmdTest3() - : Command("Std_Test3") + : Command("Std_Test3") { - sGroup = "Standard-Test"; - sMenuText = "Test3"; - sToolTipText = "Test function 3"; - sWhatsThis = "Std_Test3"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool3"; + sGroup = "Standard-Test"; + sMenuText = "Test3"; + sToolTipText = "Test function 3"; + sWhatsThis = "Std_Test3"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool3"; } void FCCmdTest3::activated(int iMsg) { Q_UNUSED(iMsg); - App::Document *pcDoc = getDocument(); - if (!pcDoc) + App::Document* pcDoc = getDocument(); + if (!pcDoc) { return; + } } @@ -199,22 +204,23 @@ bool FCCmdTest3::isActive() DEF_STD_CMD_A(FCCmdTest4) FCCmdTest4::FCCmdTest4() - : Command("Std_Test4") + : Command("Std_Test4") { - sGroup = "Standard-Test"; - sMenuText = "Test4"; - sToolTipText = "Test function 4"; - sWhatsThis = "Std_Test4"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool4"; + sGroup = "Standard-Test"; + sMenuText = "Test4"; + sToolTipText = "Test function 4"; + sWhatsThis = "Std_Test4"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool4"; } void FCCmdTest4::activated(int iMsg) { Q_UNUSED(iMsg); - App::Document *pcDoc = getDocument(); - if(!pcDoc) + App::Document* pcDoc = getDocument(); + if (!pcDoc) { return; + } } @@ -229,27 +235,28 @@ bool FCCmdTest4::isActive() DEF_STD_CMD_A(FCCmdTest5) FCCmdTest5::FCCmdTest5() - : Command("Std_Test5") + : Command("Std_Test5") { - sGroup = "Standard-Test"; - sMenuText = "Test5"; - sToolTipText = "Test function 5"; - sWhatsThis = "Std_Test5"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool5"; + sGroup = "Standard-Test"; + sMenuText = "Test5"; + sToolTipText = "Test function 5"; + sWhatsThis = "Std_Test5"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool5"; } void FCCmdTest5::activated(int iMsg) { Q_UNUSED(iMsg); - App::Document *pcDoc = getDocument(); - if(!pcDoc) + App::Document* pcDoc = getDocument(); + if (!pcDoc) { return; + } } bool FCCmdTest5::isActive() { - return (getDocument() != nullptr); + return (getDocument() != nullptr); } @@ -259,22 +266,23 @@ bool FCCmdTest5::isActive() DEF_STD_CMD_A(FCCmdTest6) FCCmdTest6::FCCmdTest6() - : Command("Std_Test6") + : Command("Std_Test6") { - sGroup = "Standard-Test"; - sMenuText = "Test6"; - sToolTipText = "Test function 6"; - sWhatsThis = "Std_Test6"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool6"; + sGroup = "Standard-Test"; + sMenuText = "Test6"; + sToolTipText = "Test function 6"; + sWhatsThis = "Std_Test6"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool6"; } void FCCmdTest6::activated(int iMsg) { Q_UNUSED(iMsg); - App::Document *pcDoc = getDocument(); - if(!pcDoc) + App::Document* pcDoc = getDocument(); + if (!pcDoc) { return; + } } bool FCCmdTest6::isActive() @@ -288,27 +296,30 @@ bool FCCmdTest6::isActive() DEF_STD_CMD_A(CmdTestCmdFuncs) CmdTestCmdFuncs::CmdTestCmdFuncs() - : Command("Std_TestCmdFuncs") + : Command("Std_TestCmdFuncs") { - sGroup = "Standard-Test"; - sMenuText = "Test Functions"; - sToolTipText = "Test functions"; - sWhatsThis = "Std_TestCmdFuncs"; - sStatusTip = sToolTipText; + sGroup = "Standard-Test"; + sMenuText = "Test Functions"; + sToolTipText = "Test functions"; + sWhatsThis = "Std_TestCmdFuncs"; + sStatusTip = sToolTipText; } void CmdTestCmdFuncs::activated(int iMsg) { Q_UNUSED(iMsg); - App::Document *doc = getDocument(); + App::Document* doc = getDocument(); auto obj = doc->addObject("App::Annotation", "obj"); - if (!obj) + if (!obj) { return; + } std::string objName = obj->getNameInDocument(); Gui::cmdAppDocument(doc, std::ostringstream() << "getObject('" << objName << "')"); - std::string cmd = "getObject('"; cmd += objName; cmd += "')"; + std::string cmd = "getObject('"; + cmd += objName; + cmd += "')"; Gui::cmdAppDocument(doc, cmd); Gui::cmdAppDocument(doc, std::ostringstream() << "getObject('" << objName << "')"); @@ -338,14 +349,14 @@ bool CmdTestCmdFuncs::isActive() DEF_STD_CMD_A(CmdTestProgress1) CmdTestProgress1::CmdTestProgress1() - : Command("Std_TestProgress1") + : Command("Std_TestProgress1") { - sGroup = "Standard-Test"; - sMenuText = "Breakable Bar"; - sToolTipText = "Test a breakable progress bar"; - sWhatsThis = "Std_TestProgress1"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool7"; + sGroup = "Standard-Test"; + sMenuText = "Breakable Bar"; + sToolTipText = "Test a breakable progress bar"; + sWhatsThis = "Std_TestProgress1"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool7"; } void CmdTestProgress1::activated(int iMsg) @@ -353,19 +364,16 @@ void CmdTestProgress1::activated(int iMsg) Q_UNUSED(iMsg); QMutex mutex; QMutexLocker ml(&mutex); - try - { + try { unsigned long steps = 1000; Base::SequencerLauncher seq("Starting progress bar", steps); - for (unsigned long i=0; inext(false); } Base::SequencerLauncher seq2("Starting second progress bar", steps); - for (unsigned long j=0; jsteps;i++) - { + for (unsigned long i = 0; i < this->steps; i++) { seq.next(true); QWaitCondition().wait(&mutex, 5); } } - catch (...) - { + catch (...) { } this->deleteLater(); - Base::Console().message("Thread with %d steps finished\n",this->steps); + Base::Console().message("Thread with %d steps finished\n", this->steps); } private: @@ -608,7 +600,7 @@ void CmdTestProgress5::activated(int iMsg) timer.setSingleShot(true); QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); thr2->start(); - timer.start(2000); // 2s timeout + timer.start(2000); // 2s timeout loop.exec(); auto thr3 = new BarThread(1000); @@ -626,13 +618,13 @@ bool CmdTestProgress5::isActive() DEF_STD_CMD_A(CmdTestMDI1) CmdTestMDI1::CmdTestMDI1() - : Command("Std_MDITest1") + : Command("Std_MDITest1") { - sGroup = "Standard-Test"; - sMenuText = "Remove MDI 1"; - sToolTipText = "Remove MDI from main window"; - sWhatsThis = "Std_MDITest1"; - sStatusTip = sToolTipText; + sGroup = "Standard-Test"; + sMenuText = "Remove MDI 1"; + sToolTipText = "Remove MDI from main window"; + sWhatsThis = "Std_MDITest1"; + sStatusTip = sToolTipText; } void CmdTestMDI1::activated(int iMsg) @@ -650,13 +642,13 @@ bool CmdTestMDI1::isActive() DEF_STD_CMD_A(CmdTestMDI2) CmdTestMDI2::CmdTestMDI2() - : Command("Std_MDITest2") + : Command("Std_MDITest2") { - sGroup = "Standard-Test"; - sMenuText = "Remove MDI 2"; - sToolTipText = "Remove view from MDI area"; - sWhatsThis = "Std_MDITest2"; - sStatusTip = sToolTipText; + sGroup = "Standard-Test"; + sMenuText = "Remove MDI 2"; + sToolTipText = "Remove view from MDI area"; + sWhatsThis = "Std_MDITest2"; + sStatusTip = sToolTipText; } void CmdTestMDI2::activated(int iMsg) @@ -678,13 +670,13 @@ bool CmdTestMDI2::isActive() DEF_STD_CMD_A(CmdTestMDI3) CmdTestMDI3::CmdTestMDI3() - : Command("Std_MDITest3") + : Command("Std_MDITest3") { - sGroup = "Standard-Test"; - sMenuText = "Remove MDI 3"; - sToolTipText = "Unset parent and remove from main window"; - sWhatsThis = "Std_MDITest3"; - sStatusTip = sToolTipText; + sGroup = "Standard-Test"; + sMenuText = "Remove MDI 3"; + sToolTipText = "Unset parent and remove from main window"; + sWhatsThis = "Std_MDITest3"; + sStatusTip = sToolTipText; } void CmdTestMDI3::activated(int iMsg) @@ -692,9 +684,10 @@ void CmdTestMDI3::activated(int iMsg) Q_UNUSED(iMsg); MDIView* mdi = getMainWindow()->activeWindow(); getMainWindow()->removeWindow(mdi); - mdi->setParent(nullptr, Qt::Window | Qt::WindowTitleHint | - Qt::WindowSystemMenuHint | - Qt::WindowMinMaxButtonsHint); + mdi->setParent( + nullptr, + Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint + ); mdi->show(); } @@ -706,35 +699,43 @@ bool CmdTestMDI3::isActive() DEF_STD_CMD(CmdTestConsoleOutput) CmdTestConsoleOutput::CmdTestConsoleOutput() - : Command("Std_TestConsoleOutput") + : Command("Std_TestConsoleOutput") { - sGroup = "Standard-Test"; - sMenuText = QT_TR_NOOP("Test Console Output"); - sToolTipText= QT_TR_NOOP("Run test cases to verify console messages"); - sStatusTip = sToolTipText; + sGroup = "Standard-Test"; + sMenuText = QT_TR_NOOP("Test Console Output"); + sToolTipText = QT_TR_NOOP("Run test cases to verify console messages"); + sStatusTip = sToolTipText; } -namespace Gui { -class TestConsoleObserver : public Base::ILogger +namespace Gui +{ +class TestConsoleObserver: public Base::ILogger { QMutex mutex; -public: - int matchMsg{0}; - int matchWrn{0}; - int matchErr{0}; - int matchLog{0}; - int matchCritical{0}; - TestConsoleObserver() = default; - void sendLog(const std::string& notifiername, const std::string& msg, Base::LogStyle level, - Base::IntendedRecipient recipient, Base::ContentType content) override{ - (void) notifiername; - (void) recipient; - (void) content; +public: + int matchMsg {0}; + int matchWrn {0}; + int matchErr {0}; + int matchLog {0}; + int matchCritical {0}; + TestConsoleObserver() = default; + void sendLog( + const std::string& notifiername, + const std::string& msg, + Base::LogStyle level, + Base::IntendedRecipient recipient, + Base::ContentType content + ) override + { + + (void)notifiername; + (void)recipient; + (void)content; QMutexLocker ml(&mutex); - switch(level){ + switch (level) { case Base::LogStyle::Warning: matchWrn += strcmp(msg.c_str(), "Write a warning to the console output.\n"); break; @@ -756,57 +757,62 @@ public: } }; -class ConsoleMessageTask : public QRunnable +class ConsoleMessageTask: public QRunnable { public: void run() override { - for (int i=0; i<10; i++) + for (int i = 0; i < 10; i++) { Base::Console().message("Write a message to the console output.\n"); + } } }; -class ConsoleWarningTask : public QRunnable +class ConsoleWarningTask: public QRunnable { public: void run() override { - for (int i=0; i<10; i++) + for (int i = 0; i < 10; i++) { Base::Console().warning("Write a warning to the console output.\n"); + } } }; -class ConsoleErrorTask : public QRunnable +class ConsoleErrorTask: public QRunnable { public: void run() override { - for (int i=0; i<10; i++) + for (int i = 0; i < 10; i++) { Base::Console().error("Write an error to the console output.\n"); + } } }; -class ConsoleLogTask : public QRunnable +class ConsoleLogTask: public QRunnable { public: void run() override { - for (int i=0; i<10; i++) + for (int i = 0; i < 10; i++) { Base::Console().log("Write a log to the console output.\n"); + } } }; -class ConsoleCriticalTask : public QRunnable +class ConsoleCriticalTask: public QRunnable { public: void run() override { - for (int i=0; i<10; i++) + for (int i = 0; i < 10; i++) { Base::Console().critical("Write a critical message to the console output.\n"); + } } }; -} +} // namespace Gui void CmdTestConsoleOutput::activated(int iMsg) { @@ -821,17 +827,19 @@ void CmdTestConsoleOutput::activated(int iMsg) QThreadPool::globalInstance()->waitForDone(); Base::Console().detachObserver(&obs); - if (obs.matchMsg > 0 || obs.matchWrn > 0 || obs.matchErr > 0 || obs.matchLog > 0 || obs.matchCritical > 0) { + if (obs.matchMsg > 0 || obs.matchWrn > 0 || obs.matchErr > 0 || obs.matchLog > 0 + || obs.matchCritical > 0) { Base::Console().error("Race condition in Console class\n"); } } -namespace Gui { +namespace Gui +{ void CreateTestCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new Std_TestQM()); rcCmdMgr.addCommand(new Std_TestReloadQM()); @@ -853,4 +861,4 @@ void CreateTestCommands() rcCmdMgr.addCommand(new CmdTestConsoleOutput()); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/CommandView.cpp b/src/Gui/CommandView.cpp index 12f35edfa0..85840c69be 100644 --- a/src/Gui/CommandView.cpp +++ b/src/Gui/CommandView.cpp @@ -20,24 +20,24 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -88,16 +88,20 @@ using namespace Gui; using Gui::Dialog::DlgSettingsImageImp; namespace sp = std::placeholders; -namespace { +namespace +{ // A helper class to open a transaction when changing properties of view providers. // It uses the same parameter key as the PropertyView to control the behaviour. -class TransactionView { +class TransactionView +{ Gui::Document* document; public: - static bool getDefault() { + static bool getDefault() + { auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/PropertyView"); + "User parameter:BaseApp/Preferences/PropertyView" + ); return hGrp->GetBool("AutoTransactionView", false); } TransactionView(Gui::Document* doc, const char* name, bool enable = getDefault()) @@ -111,29 +115,30 @@ public: } } - ~TransactionView() { + ~TransactionView() + { if (document) { document->commitCommand(); } } }; -} +} // namespace //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DEF_STD_CMD_AC(StdOrthographicCamera) StdOrthographicCamera::StdOrthographicCamera() - : Command("Std_OrthographicCamera") + : Command("Std_OrthographicCamera") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Orthographic View"); - sToolTipText = QT_TR_NOOP("Switches to orthographic view mode"); - sWhatsThis = "Std_OrthographicCamera"; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Orthographic View"); + sToolTipText = QT_TR_NOOP("Switches to orthographic view mode"); + sWhatsThis = "Std_OrthographicCamera"; sStatusTip = sToolTipText; - sPixmap = "view-isometric"; - sAccel = "V, O"; - eType = Alter3DView; + sPixmap = "view-isometric"; + sAccel = "V, O"; + eType = Alter3DView; } void StdOrthographicCamera::activated(int iMsg) @@ -141,9 +146,10 @@ void StdOrthographicCamera::activated(int iMsg) if (iMsg == 1) { auto view = qobject_cast(getMainWindow()->activeWindow()); SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); - if (!cam || cam->getTypeId() != SoOrthographicCamera::getClassTypeId()) + if (!cam || cam->getTypeId() != SoOrthographicCamera::getClassTypeId()) { - doCommand(Command::Gui,"Gui.activeDocument().activeView().setCameraType(\"Orthographic\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setCameraType(\"Orthographic\")"); + } } } @@ -156,17 +162,18 @@ bool StdOrthographicCamera::isActive() SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); bool mode = cam ? cam->getTypeId() == SoOrthographicCamera::getClassTypeId() : false; - if (mode != check) + if (mode != check) { _pcAction->setChecked(mode); + } return true; } return false; } -Action * StdOrthographicCamera::createAction() +Action* StdOrthographicCamera::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); pcAction->setCheckable(true); return pcAction; } @@ -174,16 +181,16 @@ Action * StdOrthographicCamera::createAction() DEF_STD_CMD_AC(StdPerspectiveCamera) StdPerspectiveCamera::StdPerspectiveCamera() - : Command("Std_PerspectiveCamera") + : Command("Std_PerspectiveCamera") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Perspective View"); - sToolTipText = QT_TR_NOOP("Switches to perspective view mode"); - sWhatsThis = "Std_PerspectiveCamera"; - sStatusTip = sToolTipText; - sPixmap = "view-perspective"; - sAccel = "V, P"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Perspective View"); + sToolTipText = QT_TR_NOOP("Switches to perspective view mode"); + sWhatsThis = "Std_PerspectiveCamera"; + sStatusTip = sToolTipText; + sPixmap = "view-perspective"; + sAccel = "V, P"; + eType = Alter3DView; } void StdPerspectiveCamera::activated(int iMsg) @@ -191,9 +198,10 @@ void StdPerspectiveCamera::activated(int iMsg) if (iMsg == 1) { auto view = qobject_cast(getMainWindow()->activeWindow()); SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); - if (!cam || cam->getTypeId() != SoPerspectiveCamera::getClassTypeId()) + if (!cam || cam->getTypeId() != SoPerspectiveCamera::getClassTypeId()) { - doCommand(Command::Gui,"Gui.activeDocument().activeView().setCameraType(\"Perspective\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setCameraType(\"Perspective\")"); + } } } @@ -206,8 +214,9 @@ bool StdPerspectiveCamera::isActive() SoCamera* cam = view->getViewer()->getSoRenderManager()->getCamera(); bool mode = cam ? cam->getTypeId() == SoPerspectiveCamera::getClassTypeId() : false; - if (mode != check) + if (mode != check) { _pcAction->setChecked(mode); + } return true; } @@ -215,9 +224,9 @@ bool StdPerspectiveCamera::isActive() return false; } -Action * StdPerspectiveCamera::createAction() +Action* StdPerspectiveCamera::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); pcAction->setCheckable(true); return pcAction; } @@ -234,14 +243,14 @@ Action * StdPerspectiveCamera::createAction() DEF_3DV_CMD(StdCmdViewSaveCamera) StdCmdViewSaveCamera::StdCmdViewSaveCamera() - : Command("Std_ViewSaveCamera") + : Command("Std_ViewSaveCamera") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Save Current Camera"); - sToolTipText = QT_TR_NOOP("Saves the current camera settings"); + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Save Current Camera"); + sToolTipText = QT_TR_NOOP("Saves the current camera settings"); sStatusTip = sToolTipText; - sWhatsThis = "Std_ViewSaveCamera"; - eType = Alter3DView; + sWhatsThis = "Std_ViewSaveCamera"; + eType = Alter3DView; } void StdCmdViewSaveCamera::activated(int iMsg) @@ -260,14 +269,14 @@ void StdCmdViewSaveCamera::activated(int iMsg) DEF_3DV_CMD(StdCmdViewRestoreCamera) StdCmdViewRestoreCamera::StdCmdViewRestoreCamera() - : Command("Std_ViewRestoreCamera") + : Command("Std_ViewRestoreCamera") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Restore Saved Camera"); - sToolTipText = QT_TR_NOOP("Restores the saved camera settings"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ViewRestoreCamera"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Restore Saved Camera"); + sToolTipText = QT_TR_NOOP("Restores the saved camera settings"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ViewRestoreCamera"; + eType = Alter3DView; } void StdCmdViewRestoreCamera::activated(int iMsg) @@ -283,21 +292,23 @@ void StdCmdViewRestoreCamera::activated(int iMsg) //=========================================================================== // Std_FreezeViews //=========================================================================== -class StdCmdFreezeViews : public Gui::Command +class StdCmdFreezeViews: public Gui::Command { public: StdCmdFreezeViews(); ~StdCmdFreezeViews() override = default; const char* className() const override - { return "StdCmdFreezeViews"; } + { + return "StdCmdFreezeViews"; + } - void setShortcut (const QString &) override; + void setShortcut(const QString&) override; QString getShortcut() const override; protected: void activated(int iMsg) override; bool isActive() override; - Action * createAction() override; + Action* createAction() override; void languageChange() override; private: @@ -305,28 +316,28 @@ private: void onRestoreViews(); private: - const int maxViews{50}; - int savedViews{0}; - int offset{0}; - QAction* saveView{nullptr}; - QAction* freezeView{nullptr}; - QAction* clearView{nullptr}; - QAction* separator{nullptr}; + const int maxViews {50}; + int savedViews {0}; + int offset {0}; + QAction* saveView {nullptr}; + QAction* freezeView {nullptr}; + QAction* clearView {nullptr}; + QAction* separator {nullptr}; }; StdCmdFreezeViews::StdCmdFreezeViews() - : Command("Std_FreezeViews") + : Command("Std_FreezeViews") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("F&reeze Display"); - sToolTipText = QT_TR_NOOP("Freezes the current view position"); - sWhatsThis = "Std_FreezeViews"; - sStatusTip = sToolTipText; - sAccel = "Shift+F"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("F&reeze Display"); + sToolTipText = QT_TR_NOOP("Freezes the current view position"); + sWhatsThis = "Std_FreezeViews"; + sStatusTip = sToolTipText; + sAccel = "Shift+F"; + eType = Alter3DView; } -Action * StdCmdFreezeViews::createAction() +Action* StdCmdFreezeViews::createAction() { auto pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); @@ -348,22 +359,25 @@ Action * StdCmdFreezeViews::createAction() offset = pcAction->actions().count(); // allow up to 50 views - for (int i=0; iaddAction(QStringLiteral(""))->setVisible(false); + } return pcAction; } -void StdCmdFreezeViews::setShortcut(const QString &shortcut) +void StdCmdFreezeViews::setShortcut(const QString& shortcut) { - if (freezeView) + if (freezeView) { freezeView->setShortcut(shortcut); + } } QString StdCmdFreezeViews::getShortcut() const { - if (freezeView) + if (freezeView) { return freezeView->shortcut().toString(); + } return Command::getShortcut(); } @@ -379,12 +393,12 @@ void StdCmdFreezeViews::activated(int iMsg) } else if (iMsg == 3) { // Create a new view - const char* ppReturn=nullptr; - getGuiApplication()->sendMsgToActiveView("GetCamera",&ppReturn); + const char* ppReturn = nullptr; + getGuiApplication()->sendMsgToActiveView("GetCamera", &ppReturn); QList acts = pcAction->actions(); int index = 1; - for (QList::Iterator it = acts.begin()+offset; it != acts.end(); ++it, index++) { + for (QList::Iterator it = acts.begin() + offset; it != acts.end(); ++it, index++) { if (!(*it)->isVisible()) { savedViews++; QString viewnr = QString(QObject::tr("Restore view &%1")).arg(index); @@ -401,8 +415,9 @@ void StdCmdFreezeViews::activated(int iMsg) else if (iMsg == 4) { savedViews = 0; QList acts = pcAction->actions(); - for (QList::Iterator it = acts.begin()+offset; it != acts.end(); ++it) + for (QList::Iterator it = acts.begin() + offset; it != acts.end(); ++it) { (*it)->setVisible(false); + } } else if (iMsg >= offset) { // Activate a view @@ -416,23 +431,28 @@ void StdCmdFreezeViews::activated(int iMsg) void StdCmdFreezeViews::onSaveViews() { // Save the views to an XML file - QString fn = FileDialog::getSaveFileName(getMainWindow(), QObject::tr("Save frozen views"), - QString(), QStringLiteral("%1 (*.cam)").arg(QObject::tr("Frozen views"))); - if (fn.isEmpty()) + QString fn = FileDialog::getSaveFileName( + getMainWindow(), + QObject::tr("Save frozen views"), + QString(), + QStringLiteral("%1 (*.cam)").arg(QObject::tr("Frozen views")) + ); + if (fn.isEmpty()) { return; + } QFile file(fn); - if (file.open(QFile::WriteOnly)) - { + if (file.open(QFile::WriteOnly)) { QTextStream str(&file); auto pcAction = qobject_cast(_pcAction); QList acts = pcAction->actions(); str << "\n" << "\n"; - str << " \n"; + str << " \n"; - for (QList::Iterator it = acts.begin()+offset; it != acts.end(); ++it) { - if ( !(*it)->isVisible() ) + for (QList::Iterator it = acts.begin() + offset; it != acts.end(); ++it) { + if (!(*it)->isVisible()) { break; + } QString data = (*it)->toolTip(); // remove the first line because it's a comment like '#Inventor V2.1 ascii' @@ -457,33 +477,49 @@ void StdCmdFreezeViews::onRestoreViews() { // Should we clear the already saved views if (savedViews > 0) { - auto ret = QMessageBox::question(getMainWindow(), QObject::tr("Restore views"), - QObject::tr("Importing the restored views would clear the already stored views.\n" - "Continue?"), QMessageBox::Yes | QMessageBox::No, - QMessageBox::Yes); - if (ret != QMessageBox::Yes) + auto ret = QMessageBox::question( + getMainWindow(), + QObject::tr("Restore views"), + QObject::tr( + "Importing the restored views would clear the already stored views.\n" + "Continue?" + ), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::Yes + ); + if (ret != QMessageBox::Yes) { return; + } } // Restore the views from an XML file - QString fn = FileDialog::getOpenFileName(getMainWindow(), QObject::tr("Restore frozen views"), - QString(), QStringLiteral("%1 (*.cam)").arg(QObject::tr("Frozen views"))); - if (fn.isEmpty()) + QString fn = FileDialog::getOpenFileName( + getMainWindow(), + QObject::tr("Restore frozen views"), + QString(), + QStringLiteral("%1 (*.cam)").arg(QObject::tr("Frozen views")) + ); + if (fn.isEmpty()) { return; + } QFile file(fn); if (!file.open(QFile::ReadOnly)) { - QMessageBox::critical(getMainWindow(), QObject::tr("Restore views"), - QObject::tr("Cannot open file '%1'.").arg(fn)); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Restore views"), + QObject::tr("Cannot open file '%1'.").arg(fn) + ); return; } QDomDocument xmlDocument; -#if QT_VERSION >= QT_VERSION_CHECK(6,5,0) - if (const auto result = xmlDocument.setContent(&file, QDomDocument::ParseOption::UseNamespaceProcessing); !result) { - std::cerr << "Parse error in XML content at line " << result.errorLine - << ", column " << result.errorColumn << ": " - << qPrintable(result.errorMessage) << std::endl; +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) + if (const auto result + = xmlDocument.setContent(&file, QDomDocument::ParseOption::UseNamespaceProcessing); + !result) { + std::cerr << "Parse error in XML content at line " << result.errorLine << ", column " + << result.errorColumn << ": " << qPrintable(result.errorMessage) << std::endl; return; } #else @@ -493,9 +529,8 @@ void StdCmdFreezeViews::onRestoreViews() // evaluate the XML content if (!xmlDocument.setContent(&file, true, &errorStr, &errorLine, &errorColumn)) { - std::cerr << "Parse error in XML content at line " << errorLine - << ", column " << errorColumn << ": " - << (const char*)errorStr.toLatin1() << std::endl; + std::cerr << "Parse error in XML content at line " << errorLine << ", column " + << errorColumn << ": " << (const char*)errorStr.toLatin1() << std::endl; return; } #endif @@ -509,8 +544,9 @@ void StdCmdFreezeViews::onRestoreViews() bool ok; int scheme = root.attribute(QStringLiteral("SchemaVersion")).toInt(&ok); - if (!ok) + if (!ok) { return; + } // SchemeVersion "1" if (scheme == 1) { // read the views, ignore the attribute 'Count' @@ -529,25 +565,27 @@ void StdCmdFreezeViews::onRestoreViews() auto pcAction = qobject_cast(_pcAction); QList acts = pcAction->actions(); - int numRestoredViews = std::min(ct, acts.size()-offset); + int numRestoredViews = std::min(ct, acts.size() - offset); savedViews = numRestoredViews; - if (numRestoredViews > 0) + if (numRestoredViews > 0) { separator->setVisible(true); - for(int i=0; isetText(viewnr); - acts[i+offset]->setToolTip(setting); - acts[i+offset]->setVisible(true); + QString viewnr = QString(QObject::tr("Restore view &%1")).arg(i + 1); + acts[i + offset]->setText(viewnr); + acts[i + offset]->setToolTip(setting); + acts[i + offset]->setVisible(true); if (i < 9) { - acts[i+offset]->setShortcut(QKeySequence(QStringLiteral("CTRL+%1").arg(i+1))); + acts[i + offset]->setShortcut(QKeySequence(QStringLiteral("CTRL+%1").arg(i + 1))); } } // if less views than actions - for (int index = numRestoredViews+offset; index < acts.count(); index++) + for (int index = numRestoredViews + offset; index < acts.count(); index++) { acts[index]->setVisible(false); + } } } @@ -572,16 +610,17 @@ void StdCmdFreezeViews::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } auto pcAction = qobject_cast(_pcAction); QList acts = pcAction->actions(); acts[0]->setText(QObject::tr("&Save Views…")); acts[1]->setText(QObject::tr("&Load Views…")); acts[3]->setText(QObject::tr("F&reeze View")); acts[4]->setText(QObject::tr("&Clear Views")); - int index=1; - for (QList::Iterator it = acts.begin()+5; it != acts.end(); ++it, index++) { + int index = 1; + for (QList::Iterator it = acts.begin() + 5; it != acts.end(); ++it, index++) { if ((*it)->isVisible()) { QString viewnr = QString(QObject::tr("Restore View &%1")).arg(index); (*it)->setText(viewnr); @@ -597,20 +636,20 @@ void StdCmdFreezeViews::languageChange() DEF_STD_CMD_AC(StdCmdToggleClipPlane) StdCmdToggleClipPlane::StdCmdToggleClipPlane() - : Command("Std_ToggleClipPlane") + : Command("Std_ToggleClipPlane") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Clippin&g View"); - sToolTipText = QT_TR_NOOP("Toggles clipping of the active view"); - sWhatsThis = "Std_ToggleClipPlane"; - sStatusTip = sToolTipText; - sPixmap = "Std_ToggleClipPlane"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Clippin&g View"); + sToolTipText = QT_TR_NOOP("Toggles clipping of the active view"); + sWhatsThis = "Std_ToggleClipPlane"; + sStatusTip = sToolTipText; + sPixmap = "Std_ToggleClipPlane"; + eType = Alter3DView; } -Action * StdCmdToggleClipPlane::createAction() +Action* StdCmdToggleClipPlane::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); return pcAction; } @@ -635,37 +674,41 @@ bool StdCmdToggleClipPlane::isActive() //=========================================================================== // StdCmdDrawStyle //=========================================================================== -class StdCmdDrawStyle : public Gui::Command +class StdCmdDrawStyle: public Gui::Command { public: StdCmdDrawStyle(); ~StdCmdDrawStyle() override = default; void languageChange() override; - const char* className() const override {return "StdCmdDrawStyle";} + const char* className() const override + { + return "StdCmdDrawStyle"; + } void updateIcon(const Gui::MDIView* view); + protected: void activated(int iMsg) override; bool isActive() override; - Gui::Action * createAction() override; + Gui::Action* createAction() override; }; StdCmdDrawStyle::StdCmdDrawStyle() - : Command("Std_DrawStyle") + : Command("Std_DrawStyle") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Draw Style"); - sToolTipText = QT_TR_NOOP("Changes the draw style of the objects"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_DrawStyle"; - sPixmap = "DrawStyleAsIs"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Draw Style"); + sToolTipText = QT_TR_NOOP("Changes the draw style of the objects"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_DrawStyle"; + sPixmap = "DrawStyleAsIs"; + eType = Alter3DView; this->getGuiApplication()->signalActivateView.connect([this](auto view) { this->updateIcon(view); }); } -Gui::Action * StdCmdDrawStyle::createAction() +Gui::Action* StdCmdDrawStyle::createAction() { auto pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -727,87 +770,71 @@ void StdCmdDrawStyle::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } auto pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); - a[0]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&1 As is")); - a[0]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "Normal mode")); + a[0]->setText(QCoreApplication::translate("Std_DrawStyle", "&1 As is")); + a[0]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "Normal mode")); - a[1]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&2 Points")); - a[1]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "Points mode")); + a[1]->setText(QCoreApplication::translate("Std_DrawStyle", "&2 Points")); + a[1]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "Points mode")); - a[2]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&3 Wireframe")); - a[2]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "Wireframe mode")); + a[2]->setText(QCoreApplication::translate("Std_DrawStyle", "&3 Wireframe")); + a[2]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "Wireframe mode")); - a[3]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&4 Hidden line")); - a[3]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "Hidden line mode")); + a[3]->setText(QCoreApplication::translate("Std_DrawStyle", "&4 Hidden line")); + a[3]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "Hidden line mode")); - a[4]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&5 No shading")); - a[4]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "No shading mode")); + a[4]->setText(QCoreApplication::translate("Std_DrawStyle", "&5 No shading")); + a[4]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "No shading mode")); - a[5]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&6 Shaded")); - a[5]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "Shaded mode")); + a[5]->setText(QCoreApplication::translate("Std_DrawStyle", "&6 Shaded")); + a[5]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "Shaded mode")); - a[6]->setText(QCoreApplication::translate( - "Std_DrawStyle", "&7 Flat lines")); - a[6]->setToolTip(QCoreApplication::translate( - "Std_DrawStyle", "Flat lines mode")); + a[6]->setText(QCoreApplication::translate("Std_DrawStyle", "&7 Flat lines")); + a[6]->setToolTip(QCoreApplication::translate("Std_DrawStyle", "Flat lines mode")); } -void StdCmdDrawStyle::updateIcon(const MDIView *view) +void StdCmdDrawStyle::updateIcon(const MDIView* view) { - const auto view3d = dynamic_cast(view); - if (!view3d) + const auto view3d = dynamic_cast(view); + if (!view3d) { return; - Gui::View3DInventorViewer *viewer = view3d->getViewer(); - if (!viewer) + } + Gui::View3DInventorViewer* viewer = view3d->getViewer(); + if (!viewer) { return; + } std::string mode(viewer->getOverrideMode()); - auto actionGroup = dynamic_cast(_pcAction); - if (!actionGroup) + auto actionGroup = dynamic_cast(_pcAction); + if (!actionGroup) { return; + } - if (mode == "Point") - { + if (mode == "Point") { actionGroup->setCheckedAction(1); return; } - if (mode == "Wireframe") - { + if (mode == "Wireframe") { actionGroup->setCheckedAction(2); return; } - if (mode == "Hidden Line") - { + if (mode == "Hidden Line") { actionGroup->setCheckedAction(3); return; } - if (mode == "No shading") - { + if (mode == "No shading") { actionGroup->setCheckedAction(4); return; } - if (mode == "Shaded") - { + if (mode == "Shaded") { actionGroup->setCheckedAction(5); return; } - if (mode == "Flat Lines") - { + if (mode == "Flat Lines") { actionGroup->setCheckedAction(6); return; } @@ -816,42 +843,45 @@ void StdCmdDrawStyle::updateIcon(const MDIView *view) void StdCmdDrawStyle::activated(int iMsg) { - Gui::Document *doc = this->getActiveGuiDocument(); + Gui::Document* doc = this->getActiveGuiDocument(); std::list views = doc->getMDIViews(); std::list::iterator viewIt; bool oneChangedSignal(false); - for (viewIt = views.begin(); viewIt != views.end(); ++viewIt) - { + for (viewIt = views.begin(); viewIt != views.end(); ++viewIt) { auto view = qobject_cast(*viewIt); - if (view) - { + if (view) { View3DInventorViewer* viewer; viewer = view->getViewer(); - if (viewer) - { - switch (iMsg) - { - case 1: - (oneChangedSignal) ? viewer->updateOverrideMode("Point") : viewer->setOverrideMode("Point"); - break; - case 2: - (oneChangedSignal) ? viewer->updateOverrideMode("Wireframe") : viewer->setOverrideMode("Wireframe"); - break; - case 3: - (oneChangedSignal) ? viewer->updateOverrideMode("Hidden Line") : viewer->setOverrideMode("Hidden Line"); - break; - case 4: - (oneChangedSignal) ? viewer->updateOverrideMode("No Shading") : viewer->setOverrideMode("No Shading"); - break; - case 5: - (oneChangedSignal) ? viewer->updateOverrideMode("Shaded") : viewer->setOverrideMode("Shaded"); - break; - case 6: - (oneChangedSignal) ? viewer->updateOverrideMode("Flat Lines") : viewer->setOverrideMode("Flat Lines"); - break; - default: - (oneChangedSignal) ? viewer->updateOverrideMode("As Is") : viewer->setOverrideMode("As Is"); - break; + if (viewer) { + switch (iMsg) { + case 1: + (oneChangedSignal) ? viewer->updateOverrideMode("Point") + : viewer->setOverrideMode("Point"); + break; + case 2: + (oneChangedSignal) ? viewer->updateOverrideMode("Wireframe") + : viewer->setOverrideMode("Wireframe"); + break; + case 3: + (oneChangedSignal) ? viewer->updateOverrideMode("Hidden Line") + : viewer->setOverrideMode("Hidden Line"); + break; + case 4: + (oneChangedSignal) ? viewer->updateOverrideMode("No Shading") + : viewer->setOverrideMode("No Shading"); + break; + case 5: + (oneChangedSignal) ? viewer->updateOverrideMode("Shaded") + : viewer->setOverrideMode("Shaded"); + break; + case 6: + (oneChangedSignal) ? viewer->updateOverrideMode("Flat Lines") + : viewer->setOverrideMode("Flat Lines"); + break; + default: + (oneChangedSignal) ? viewer->updateOverrideMode("As Is") + : viewer->setOverrideMode("As Is"); + break; } oneChangedSignal = true; } @@ -870,23 +900,26 @@ bool StdCmdDrawStyle::isActive() DEF_STD_CMD_A(StdCmdToggleVisibility) StdCmdToggleVisibility::StdCmdToggleVisibility() - : Command("Std_ToggleVisibility") + : Command("Std_ToggleVisibility") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle &Visibility"); - sToolTipText = QT_TR_NOOP("Toggles the visibility of the selection"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ToggleVisibility"; - sPixmap = "Std_ToggleVisibility"; - sAccel = "Space"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle &Visibility"); + sToolTipText = QT_TR_NOOP("Toggles the visibility of the selection"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ToggleVisibility"; + sPixmap = "Std_ToggleVisibility"; + sAccel = "Space"; + eType = Alter3DView; } void StdCmdToggleVisibility::activated(int iMsg) { Q_UNUSED(iMsg); - TransactionView transaction(getActiveGuiDocument(), QT_TRANSLATE_NOOP("Command", "Toggle Visibility")); + TransactionView transaction( + getActiveGuiDocument(), + QT_TRANSLATE_NOOP("Command", "Toggle Visibility") + ); Selection().setVisible(SelectionSingleton::VisToggle); } @@ -907,7 +940,7 @@ StdCmdToggleTransparency::StdCmdToggleTransparency() sMenuText = QT_TR_NOOP("Toggle Transparenc&y"); static std::string toolTip = std::string("

") + QT_TR_NOOP("Toggles the transparency of the selected objects. Transparency " - "can be fine-tuned in the appearance task dialog") + "can be fine-tuned in the appearance task dialog") + "

"; sToolTipText = toolTip.c_str(); sStatusTip = sToolTipText; @@ -928,24 +961,25 @@ void StdCmdToggleTransparency::activated(int iMsg) for (Gui::SelectionSingleton::SelObj& sel : sels) { App::DocumentObject* obj = sel.pObject; - if (!obj) + if (!obj) { continue; + } - bool isGroup = dynamic_cast(obj) - || dynamic_cast(obj) - || dynamic_cast(obj); + bool isGroup = dynamic_cast(obj) || dynamic_cast(obj) + || dynamic_cast(obj); auto addObjects = [](App::DocumentObject* obj, std::vector& views) { App::Document* doc = obj->getDocument(); Gui::ViewProvider* view = Application::Instance->getDocument(doc)->getViewProvider(obj); App::Property* prop = view->getPropertyByName("Transparency"); if (prop && prop->isDerivedFrom()) { - // To prevent toggling the tip of a PD body (see #11353), we check if the parent has a - // Tip prop. + // To prevent toggling the tip of a PD body (see #11353), we check if the parent has + // a Tip prop. const std::vector parents = obj->getInList(); if (!parents.empty()) { App::Document* parentDoc = parents[0]->getDocument(); - Gui::ViewProvider* parentView = Application::Instance->getDocument(parentDoc)->getViewProvider(parents[0]); + Gui::ViewProvider* parentView + = Application::Instance->getDocument(parentDoc)->getViewProvider(parents[0]); App::Property* parentProp = parents[0]->getPropertyByName("Tip"); if (parentProp) { // Make sure it has a transparency prop too @@ -984,8 +1018,9 @@ void StdCmdToggleTransparency::activated(int iMsg) } } - auto hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); int userTransparency = hGrp->GetInt("ToggleTransparency", 70); int transparency = oneTransparent ? 0 : userTransparency; @@ -1012,15 +1047,15 @@ bool StdCmdToggleTransparency::isActive() DEF_STD_CMD_A(StdCmdToggleSelectability) StdCmdToggleSelectability::StdCmdToggleSelectability() - : Command("Std_ToggleSelectability") + : Command("Std_ToggleSelectability") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle Se&lectability"); - sToolTipText = QT_TR_NOOP("Toggles the property of the objects to get selected in the 3D view"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ToggleSelectability"; - sPixmap = "view-unselectable"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle Se&lectability"); + sToolTipText = QT_TR_NOOP("Toggles the property of the objects to get selected in the 3D view"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ToggleSelectability"; + sPixmap = "view-unselectable"; + eType = Alter3DView; } void StdCmdToggleSelectability::activated(int iMsg) @@ -1028,10 +1063,10 @@ void StdCmdToggleSelectability::activated(int iMsg) Q_UNUSED(iMsg); // go through all documents const std::vector docs = App::GetApplication().getDocuments(); - for (const auto & doc : docs) { - Document *pcDoc = Application::Instance->getDocument(doc); - std::vector sel = Selection().getObjectsOfType - (App::DocumentObject::getClassTypeId(), doc->getName()); + for (const auto& doc : docs) { + Document* pcDoc = Application::Instance->getDocument(doc); + std::vector sel + = Selection().getObjectsOfType(App::DocumentObject::getClassTypeId(), doc->getName()); if (sel.empty()) { continue; @@ -1039,15 +1074,25 @@ void StdCmdToggleSelectability::activated(int iMsg) TransactionView transaction(pcDoc, QT_TRANSLATE_NOOP("Command", "Toggle Selectability")); - for (const auto & ft : sel) { - ViewProvider *pr = pcDoc->getViewProviderByName(ft->getNameInDocument()); - if (pr && pr->isDerivedFrom()){ - if (static_cast(pr)->Selectable.getValue()) - doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Selectable=False" - , doc->getName(), ft->getNameInDocument()); - else - doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Selectable=True" - , doc->getName(), ft->getNameInDocument()); + for (const auto& ft : sel) { + ViewProvider* pr = pcDoc->getViewProviderByName(ft->getNameInDocument()); + if (pr && pr->isDerivedFrom()) { + if (static_cast(pr)->Selectable.getValue()) { + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Selectable=False", + doc->getName(), + ft->getNameInDocument() + ); + } + else { + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Selectable=True", + doc->getName(), + ft->getNameInDocument() + ); + } } } } @@ -1064,15 +1109,15 @@ bool StdCmdToggleSelectability::isActive() DEF_STD_CMD_A(StdCmdShowSelection) StdCmdShowSelection::StdCmdShowSelection() - : Command("Std_ShowSelection") + : Command("Std_ShowSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Sho&w Selection"); - sToolTipText = QT_TR_NOOP("Shows all selected objects"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ShowSelection"; - sPixmap = "Std_ShowSelection"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Sho&w Selection"); + sToolTipText = QT_TR_NOOP("Shows all selected objects"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ShowSelection"; + sPixmap = "Std_ShowSelection"; + eType = Alter3DView; } void StdCmdShowSelection::activated(int iMsg) @@ -1092,15 +1137,15 @@ bool StdCmdShowSelection::isActive() DEF_STD_CMD_A(StdCmdHideSelection) StdCmdHideSelection::StdCmdHideSelection() - : Command("Std_HideSelection") + : Command("Std_HideSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Hide Selection"); - sToolTipText = QT_TR_NOOP("Hides all selected objects"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_HideSelection"; - sPixmap = "Std_HideSelection"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Hide Selection"); + sToolTipText = QT_TR_NOOP("Hides all selected objects"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_HideSelection"; + sPixmap = "Std_HideSelection"; + eType = Alter3DView; } void StdCmdHideSelection::activated(int iMsg) @@ -1120,15 +1165,15 @@ bool StdCmdHideSelection::isActive() DEF_STD_CMD_A(StdCmdSelectVisibleObjects) StdCmdSelectVisibleObjects::StdCmdSelectVisibleObjects() - : Command("Std_SelectVisibleObjects") + : Command("Std_SelectVisibleObjects") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Select Visible Objects"); - sToolTipText = QT_TR_NOOP("Selects all visible objects in the active document"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_SelectVisibleObjects"; - sPixmap = "Std_SelectVisibleObjects"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Select Visible Objects"); + sToolTipText = QT_TR_NOOP("Selects all visible objects in the active document"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_SelectVisibleObjects"; + sPixmap = "Std_SelectVisibleObjects"; + eType = Alter3DView; } void StdCmdSelectVisibleObjects::activated(int iMsg) @@ -1137,14 +1182,16 @@ void StdCmdSelectVisibleObjects::activated(int iMsg) // go through active document Gui::Document* doc = Application::Instance->activeDocument(); App::Document* app = doc->getDocument(); - const std::vector obj = app->getObjectsOfType - (App::DocumentObject::getClassTypeId()); + const std::vector obj = app->getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); std::vector visible; visible.reserve(obj.size()); - for (const auto & it : obj) { - if (doc->isShow(it->getNameInDocument())) + for (const auto& it : obj) { + if (doc->isShow(it->getNameInDocument())) { visible.push_back(it); + } } SelectionSingleton& rSel = Selection(); @@ -1162,15 +1209,15 @@ bool StdCmdSelectVisibleObjects::isActive() DEF_STD_CMD_A(StdCmdToggleObjects) StdCmdToggleObjects::StdCmdToggleObjects() - : Command("Std_ToggleObjects") + : Command("Std_ToggleObjects") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("To&ggle All Objects"); - sToolTipText = QT_TR_NOOP("Toggles the visibility of all objects in the active document"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ToggleObjects"; - sPixmap = "Std_ToggleObjects"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("To&ggle All Objects"); + sToolTipText = QT_TR_NOOP("Toggles the visibility of all objects in the active document"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ToggleObjects"; + sPixmap = "Std_ToggleObjects"; + eType = Alter3DView; } void StdCmdToggleObjects::activated(int iMsg) @@ -1179,16 +1226,27 @@ void StdCmdToggleObjects::activated(int iMsg) // go through active document Gui::Document* doc = Application::Instance->activeDocument(); App::Document* app = doc->getDocument(); - const std::vector obj = app->getObjectsOfType - (App::DocumentObject::getClassTypeId()); + const std::vector obj = app->getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); - for (const auto & it : obj) { - if (doc->isShow(it->getNameInDocument())) - doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=False" - , app->getName(), it->getNameInDocument()); - else - doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=True" - , app->getName(), it->getNameInDocument()); + for (const auto& it : obj) { + if (doc->isShow(it->getNameInDocument())) { + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=False", + app->getName(), + it->getNameInDocument() + ); + } + else { + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=True", + app->getName(), + it->getNameInDocument() + ); + } } } @@ -1203,15 +1261,15 @@ bool StdCmdToggleObjects::isActive() DEF_STD_CMD_A(StdCmdShowObjects) StdCmdShowObjects::StdCmdShowObjects() - : Command("Std_ShowObjects") + : Command("Std_ShowObjects") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Show &All Objects"); - sToolTipText = QT_TR_NOOP("Shows all objects in the document"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ShowObjects"; - sPixmap = "Std_ShowObjects"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Show &All Objects"); + sToolTipText = QT_TR_NOOP("Shows all objects in the document"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ShowObjects"; + sPixmap = "Std_ShowObjects"; + eType = Alter3DView; } void StdCmdShowObjects::activated(int iMsg) @@ -1220,12 +1278,17 @@ void StdCmdShowObjects::activated(int iMsg) // go through active document Gui::Document* doc = Application::Instance->activeDocument(); App::Document* app = doc->getDocument(); - const std::vector obj = app->getObjectsOfType - (App::DocumentObject::getClassTypeId()); + const std::vector obj = app->getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); - for (const auto & it : obj) { - doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=True" - , app->getName(), it->getNameInDocument()); + for (const auto& it : obj) { + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=True", + app->getName(), + it->getNameInDocument() + ); } } @@ -1240,15 +1303,15 @@ bool StdCmdShowObjects::isActive() DEF_STD_CMD_A(StdCmdHideObjects) StdCmdHideObjects::StdCmdHideObjects() - : Command("Std_HideObjects") + : Command("Std_HideObjects") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Hide All &Objects"); - sToolTipText = QT_TR_NOOP("Hides all objects in the document"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_HideObjects"; - sPixmap = "Std_HideObjects"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Hide All &Objects"); + sToolTipText = QT_TR_NOOP("Hides all objects in the document"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_HideObjects"; + sPixmap = "Std_HideObjects"; + eType = Alter3DView; } void StdCmdHideObjects::activated(int iMsg) @@ -1257,12 +1320,17 @@ void StdCmdHideObjects::activated(int iMsg) // go through active document Gui::Document* doc = Application::Instance->activeDocument(); App::Document* app = doc->getDocument(); - const std::vector obj = app->getObjectsOfType - (App::DocumentObject::getClassTypeId()); + const std::vector obj = app->getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); - for (const auto & it : obj) { - doCommand(Gui,"Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=False" - , app->getName(), it->getNameInDocument()); + for (const auto& it : obj) { + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=False", + app->getName(), + it->getNameInDocument() + ); } } @@ -1277,26 +1345,32 @@ bool StdCmdHideObjects::isActive() DEF_3DV_CMD(StdCmdViewHome) StdCmdViewHome::StdCmdViewHome() - : Command("Std_ViewHome") + : Command("Std_ViewHome") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Home"); - sToolTipText = QT_TR_NOOP("Sets the camera to the default home view"); - sWhatsThis = "Std_ViewHome"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewHome"; - sAccel = "Home"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Home"); + sToolTipText = QT_TR_NOOP("Sets the camera to the default home view"); + sWhatsThis = "Std_ViewHome"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewHome"; + sAccel = "Home"; + eType = Alter3DView; } void StdCmdViewHome::activated(int iMsg) { Q_UNUSED(iMsg); - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - std::string default_view = hGrp->GetASCII("NewDocumentCameraOrientation","Top"); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewDefaultOrientation('%s',0)",default_view.c_str()); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewFit\")"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + std::string default_view = hGrp->GetASCII("NewDocumentCameraOrientation", "Top"); + doCommand( + Command::Gui, + "Gui.activeDocument().activeView().viewDefaultOrientation('%s',0)", + default_view.c_str() + ); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")"); } //=========================================================================== @@ -1305,22 +1379,22 @@ void StdCmdViewHome::activated(int iMsg) DEF_3DV_CMD(StdCmdViewBottom) StdCmdViewBottom::StdCmdViewBottom() - : Command("Std_ViewBottom") + : Command("Std_ViewBottom") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&5 Bottom"); - sToolTipText = QT_TR_NOOP("Sets the camera to the bottom view"); - sWhatsThis = "Std_ViewBottom"; - sStatusTip = sToolTipText; - sPixmap = "view-bottom"; - sAccel = "5"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&5 Bottom"); + sToolTipText = QT_TR_NOOP("Sets the camera to the bottom view"); + sWhatsThis = "Std_ViewBottom"; + sStatusTip = sToolTipText; + sPixmap = "view-bottom"; + sAccel = "5"; + eType = Alter3DView; } void StdCmdViewBottom::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewBottom()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewBottom()"); } //=========================================================================== @@ -1329,22 +1403,22 @@ void StdCmdViewBottom::activated(int iMsg) DEF_3DV_CMD(StdCmdViewFront) StdCmdViewFront::StdCmdViewFront() - : Command("Std_ViewFront") + : Command("Std_ViewFront") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&1 Front"); - sToolTipText = QT_TR_NOOP("Sets the camera to the front view"); - sWhatsThis = "Std_ViewFront"; - sStatusTip = sToolTipText; - sPixmap = "view-front"; - sAccel = "1"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&1 Front"); + sToolTipText = QT_TR_NOOP("Sets the camera to the front view"); + sWhatsThis = "Std_ViewFront"; + sStatusTip = sToolTipText; + sPixmap = "view-front"; + sAccel = "1"; + eType = Alter3DView; } void StdCmdViewFront::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewFront()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewFront()"); } //=========================================================================== @@ -1353,22 +1427,22 @@ void StdCmdViewFront::activated(int iMsg) DEF_3DV_CMD(StdCmdViewLeft) StdCmdViewLeft::StdCmdViewLeft() - : Command("Std_ViewLeft") + : Command("Std_ViewLeft") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&6 Left"); - sToolTipText = QT_TR_NOOP("Sets the camera to the left view"); - sWhatsThis = "Std_ViewLeft"; - sStatusTip = sToolTipText; - sPixmap = "view-left"; - sAccel = "6"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&6 Left"); + sToolTipText = QT_TR_NOOP("Sets the camera to the left view"); + sWhatsThis = "Std_ViewLeft"; + sStatusTip = sToolTipText; + sPixmap = "view-left"; + sAccel = "6"; + eType = Alter3DView; } void StdCmdViewLeft::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewLeft()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewLeft()"); } //=========================================================================== @@ -1377,22 +1451,22 @@ void StdCmdViewLeft::activated(int iMsg) DEF_3DV_CMD(StdCmdViewRear) StdCmdViewRear::StdCmdViewRear() - : Command("Std_ViewRear") + : Command("Std_ViewRear") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&4 Rear"); - sToolTipText = QT_TR_NOOP("Sets the camera to the rear view"); - sWhatsThis = "Std_ViewRear"; - sStatusTip = sToolTipText; - sPixmap = "view-rear"; - sAccel = "4"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&4 Rear"); + sToolTipText = QT_TR_NOOP("Sets the camera to the rear view"); + sWhatsThis = "Std_ViewRear"; + sStatusTip = sToolTipText; + sPixmap = "view-rear"; + sAccel = "4"; + eType = Alter3DView; } void StdCmdViewRear::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewRear()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewRear()"); } //=========================================================================== @@ -1401,22 +1475,22 @@ void StdCmdViewRear::activated(int iMsg) DEF_3DV_CMD(StdCmdViewRight) StdCmdViewRight::StdCmdViewRight() - : Command("Std_ViewRight") + : Command("Std_ViewRight") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&3 Right"); - sToolTipText = QT_TR_NOOP("Sets the camera to the right view"); - sWhatsThis = "Std_ViewRight"; - sStatusTip = sToolTipText; - sPixmap = "view-right"; - sAccel = "3"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&3 Right"); + sToolTipText = QT_TR_NOOP("Sets the camera to the right view"); + sWhatsThis = "Std_ViewRight"; + sStatusTip = sToolTipText; + sPixmap = "view-right"; + sAccel = "3"; + eType = Alter3DView; } void StdCmdViewRight::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewRight()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewRight()"); } //=========================================================================== @@ -1425,22 +1499,22 @@ void StdCmdViewRight::activated(int iMsg) DEF_3DV_CMD(StdCmdViewTop) StdCmdViewTop::StdCmdViewTop() - : Command("Std_ViewTop") + : Command("Std_ViewTop") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&2 Top"); - sToolTipText = QT_TR_NOOP("Sets the camera to the top view"); - sWhatsThis = "Std_ViewTop"; - sStatusTip = sToolTipText; - sPixmap = "view-top"; - sAccel = "2"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&2 Top"); + sToolTipText = QT_TR_NOOP("Sets the camera to the top view"); + sWhatsThis = "Std_ViewTop"; + sStatusTip = sToolTipText; + sPixmap = "view-top"; + sAccel = "2"; + eType = Alter3DView; } void StdCmdViewTop::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewTop()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewTop()"); } @@ -1450,22 +1524,22 @@ void StdCmdViewTop::activated(int iMsg) DEF_3DV_CMD(StdCmdViewIsometric) StdCmdViewIsometric::StdCmdViewIsometric() - : Command("Std_ViewIsometric") + : Command("Std_ViewIsometric") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Isometric"); - sToolTipText = QT_TR_NOOP("Sets the camera to the isometric view"); - sWhatsThis = "Std_ViewIsometric"; - sStatusTip = sToolTipText; - sPixmap = "view-axonometric"; - sAccel = "0"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Isometric"); + sToolTipText = QT_TR_NOOP("Sets the camera to the isometric view"); + sWhatsThis = "Std_ViewIsometric"; + sStatusTip = sToolTipText; + sPixmap = "view-axonometric"; + sAccel = "0"; + eType = Alter3DView; } void StdCmdViewIsometric::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewIsometric()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewIsometric()"); } //=========================================================================== @@ -1474,21 +1548,21 @@ void StdCmdViewIsometric::activated(int iMsg) DEF_3DV_CMD(StdCmdViewDimetric) StdCmdViewDimetric::StdCmdViewDimetric() - : Command("Std_ViewDimetric") + : Command("Std_ViewDimetric") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Dimetric"); - sToolTipText = QT_TR_NOOP("Sets the camera to the dimetric view"); - sWhatsThis = "Std_ViewDimetric"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewDimetric"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Dimetric"); + sToolTipText = QT_TR_NOOP("Sets the camera to the dimetric view"); + sWhatsThis = "Std_ViewDimetric"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewDimetric"; + eType = Alter3DView; } void StdCmdViewDimetric::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewDimetric()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewDimetric()"); } //=========================================================================== @@ -1497,21 +1571,21 @@ void StdCmdViewDimetric::activated(int iMsg) DEF_3DV_CMD(StdCmdViewTrimetric) StdCmdViewTrimetric::StdCmdViewTrimetric() - : Command("Std_ViewTrimetric") + : Command("Std_ViewTrimetric") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Trimetric"); - sToolTipText = QT_TR_NOOP("Sets the camera to the trimetric view"); - sWhatsThis = "Std_ViewTrimetric"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewTrimetric"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Trimetric"); + sToolTipText = QT_TR_NOOP("Sets the camera to the trimetric view"); + sWhatsThis = "Std_ViewTrimetric"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewTrimetric"; + eType = Alter3DView; } void StdCmdViewTrimetric::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewTrimetric()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewTrimetric()"); } //=========================================================================== @@ -1520,22 +1594,22 @@ void StdCmdViewTrimetric::activated(int iMsg) DEF_3DV_CMD(StdCmdViewRotateLeft) StdCmdViewRotateLeft::StdCmdViewRotateLeft() - : Command("Std_ViewRotateLeft") + : Command("Std_ViewRotateLeft") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Rotate &Left"); - sToolTipText = QT_TR_NOOP("Rotates the view by 90\xc2\xb0 counter-clockwise"); - sWhatsThis = "Std_ViewRotateLeft"; - sStatusTip = sToolTipText; - sPixmap = "view-rotate-left"; - sAccel = "Shift+Left"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Rotate &Left"); + sToolTipText = QT_TR_NOOP("Rotates the view by 90\xc2\xb0 counter-clockwise"); + sWhatsThis = "Std_ViewRotateLeft"; + sStatusTip = sToolTipText; + sPixmap = "view-rotate-left"; + sAccel = "Shift+Left"; + eType = Alter3DView; } void StdCmdViewRotateLeft::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewRotateLeft()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewRotateLeft()"); } @@ -1545,22 +1619,22 @@ void StdCmdViewRotateLeft::activated(int iMsg) DEF_3DV_CMD(StdCmdViewRotateRight) StdCmdViewRotateRight::StdCmdViewRotateRight() - : Command("Std_ViewRotateRight") + : Command("Std_ViewRotateRight") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Rotates &Right"); - sToolTipText = QT_TR_NOOP("Rotates the view by 90\xc2\xb0 clockwise"); - sWhatsThis = "Std_ViewRotateRight"; - sStatusTip = sToolTipText; - sPixmap = "view-rotate-right"; - sAccel = "Shift+Right"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Rotates &Right"); + sToolTipText = QT_TR_NOOP("Rotates the view by 90\xc2\xb0 clockwise"); + sWhatsThis = "Std_ViewRotateRight"; + sStatusTip = sToolTipText; + sPixmap = "view-rotate-right"; + sAccel = "Shift+Right"; + eType = Alter3DView; } void StdCmdViewRotateRight::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().viewRotateRight()"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().viewRotateRight()"); } @@ -1570,28 +1644,28 @@ void StdCmdViewRotateRight::activated(int iMsg) DEF_STD_CMD_A(StdCmdViewFitAll) StdCmdViewFitAll::StdCmdViewFitAll() - : Command("Std_ViewFitAll") + : Command("Std_ViewFitAll") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Fit All"); - sToolTipText = QT_TR_NOOP("Fits all content into the 3D view"); - sWhatsThis = "Std_ViewFitAll"; - sStatusTip = sToolTipText; - sPixmap = "zoom-all"; - sAccel = "V, F"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Fit All"); + sToolTipText = QT_TR_NOOP("Fits all content into the 3D view"); + sWhatsThis = "Std_ViewFitAll"; + sStatusTip = sToolTipText; + sPixmap = "zoom-all"; + sAccel = "V, F"; + eType = Alter3DView; } void StdCmdViewFitAll::activated(int iMsg) { Q_UNUSED(iMsg); - //doCommand(Command::Gui,"Gui.activeDocument().activeView().fitAll()"); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewFit\")"); + // doCommand(Command::Gui,"Gui.activeDocument().activeView().fitAll()"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewFit\")"); } bool StdCmdViewFitAll::isActive() { - //return isViewOfType(Gui::View3DInventor::getClassTypeId()); + // return isViewOfType(Gui::View3DInventor::getClassTypeId()); return getGuiApplication()->sendHasMsgToActiveView("ViewFit"); } @@ -1601,27 +1675,27 @@ bool StdCmdViewFitAll::isActive() DEF_STD_CMD_A(StdCmdViewFitSelection) StdCmdViewFitSelection::StdCmdViewFitSelection() - : Command("Std_ViewFitSelection") + : Command("Std_ViewFitSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Fit &Selection"); - sToolTipText = QT_TR_NOOP("Fits the selected content into the 3D view"); - sWhatsThis = "Std_ViewFitSelection"; - sStatusTip = sToolTipText; - sAccel = "V, S"; - sPixmap = "zoom-selection"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Fit &Selection"); + sToolTipText = QT_TR_NOOP("Fits the selected content into the 3D view"); + sWhatsThis = "Std_ViewFitSelection"; + sStatusTip = sToolTipText; + sAccel = "V, S"; + sPixmap = "zoom-selection"; + eType = Alter3DView; } void StdCmdViewFitSelection::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewSelection\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewSelection\")"); } bool StdCmdViewFitSelection::isActive() { - return getGuiApplication()->sendHasMsgToActiveView("ViewSelection"); + return getGuiApplication()->sendHasMsgToActiveView("ViewSelection"); } //=========================================================================== @@ -1670,16 +1744,18 @@ public: DEF_STD_CMD_A(StdViewDock) StdViewDock::StdViewDock() - : Command("Std_ViewDock") + : Command("Std_ViewDock") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Docked"); - sToolTipText = QT_TR_NOOP("Displays the active view either in fullscreen, undocked, or docked mode"); - sWhatsThis = "Std_ViewDock"; - sStatusTip = sToolTipText; - sAccel = "V, D"; - eType = Alter3DView; - bCanLog = false; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Docked"); + sToolTipText = QT_TR_NOOP( + "Displays the active view either in fullscreen, undocked, or docked mode" + ); + sWhatsThis = "Std_ViewDock"; + sStatusTip = sToolTipText; + sAccel = "V, D"; + eType = Alter3DView; + bCanLog = false; } void StdViewDock::activated(int iMsg) @@ -1699,16 +1775,18 @@ bool StdViewDock::isActive() DEF_STD_CMD_A(StdViewUndock) StdViewUndock::StdViewUndock() - : Command("Std_ViewUndock") + : Command("Std_ViewUndock") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Undocked"); - sToolTipText = QT_TR_NOOP("Displays the active view either in fullscreen, undocked, or docked mode"); - sWhatsThis = "Std_ViewUndock"; - sStatusTip = sToolTipText; - sAccel = "V, U"; - eType = Alter3DView; - bCanLog = false; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Undocked"); + sToolTipText = QT_TR_NOOP( + "Displays the active view either in fullscreen, undocked, or docked mode" + ); + sWhatsThis = "Std_ViewUndock"; + sStatusTip = sToolTipText; + sAccel = "V, U"; + eType = Alter3DView; + bCanLog = false; } void StdViewUndock::activated(int iMsg) @@ -1728,16 +1806,16 @@ bool StdViewUndock::isActive() DEF_STD_CMD(StdMainFullscreen) StdMainFullscreen::StdMainFullscreen() - : Command("Std_MainFullscreen") + : Command("Std_MainFullscreen") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Fullscreen"); + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Fullscreen"); sToolTipText = QT_TR_NOOP("Displays the main window in fullscreen mode"); - sWhatsThis = "Std_MainFullscreen"; - sStatusTip = sToolTipText; - sPixmap = "view-fullscreen"; - sAccel = "Alt+F11"; - eType = Alter3DView; + sWhatsThis = "Std_MainFullscreen"; + sStatusTip = sToolTipText; + sPixmap = "view-fullscreen"; + sAccel = "Alt+F11"; + eType = Alter3DView; } void StdMainFullscreen::activated(int iMsg) @@ -1745,13 +1823,16 @@ void StdMainFullscreen::activated(int iMsg) Q_UNUSED(iMsg); MDIView* view = getMainWindow()->activeWindow(); - if (view) + if (view) { view->setCurrentViewMode(MDIView::Child); + } - if (getMainWindow()->isFullScreen()) + if (getMainWindow()->isFullScreen()) { getMainWindow()->showNormal(); - else + } + else { getMainWindow()->showFullScreen(); + } } //=========================================================================== @@ -1760,17 +1841,19 @@ void StdMainFullscreen::activated(int iMsg) DEF_STD_CMD_A(StdViewFullscreen) StdViewFullscreen::StdViewFullscreen() - : Command("Std_ViewFullscreen") + : Command("Std_ViewFullscreen") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Fullscreen"); - sToolTipText = QT_TR_NOOP("Displays the active view either in fullscreen, undocked, or docked mode"); - sWhatsThis = "Std_ViewFullscreen"; - sStatusTip = sToolTipText; - sPixmap = "view-fullscreen"; - sAccel = "F11"; - eType = Alter3DView; - bCanLog = false; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Fullscreen"); + sToolTipText = QT_TR_NOOP( + "Displays the active view either in fullscreen, undocked, or docked mode" + ); + sWhatsThis = "Std_ViewFullscreen"; + sStatusTip = sToolTipText; + sPixmap = "view-fullscreen"; + sAccel = "F11"; + eType = Alter3DView; + bCanLog = false; } void StdViewFullscreen::activated(int iMsg) @@ -1790,29 +1873,30 @@ bool StdViewFullscreen::isActive() DEF_STD_CMD_AC(StdViewDockUndockFullscreen) StdViewDockUndockFullscreen::StdViewDockUndockFullscreen() - : Command("Std_ViewDockUndockFullscreen") + : Command("Std_ViewDockUndockFullscreen") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("D&ocument Window"); - sToolTipText = QT_TR_NOOP("Displays the active view either in fullscreen, undocked, or docked mode"); - sWhatsThis = "Std_ViewDockUndockFullscreen"; - sStatusTip = sToolTipText; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("D&ocument Window"); + sToolTipText = QT_TR_NOOP( + "Displays the active view either in fullscreen, undocked, or docked mode" + ); + sWhatsThis = "Std_ViewDockUndockFullscreen"; + sStatusTip = sToolTipText; + eType = Alter3DView; - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdViewDock()); rcCmdMgr.addCommand(new StdViewUndock()); rcCmdMgr.addCommand(new StdViewFullscreen()); } -Action * StdViewDockUndockFullscreen::createAction() +Action* StdViewDockUndockFullscreen::createAction() { auto pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); - pcAction->setText(QCoreApplication::translate( - this->className(), getMenuText())); + pcAction->setText(QCoreApplication::translate(this->className(), getMenuText())); - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); Command* cmdD = rcCmdMgr.getCommandByName("Std_ViewDock"); Command* cmdU = rcCmdMgr.getCommandByName("Std_ViewUndock"); Command* cmdF = rcCmdMgr.getCommandByName("Std_ViewFullscreen"); @@ -1826,12 +1910,14 @@ Action * StdViewDockUndockFullscreen::createAction() void StdViewDockUndockFullscreen::activated(int iMsg) { // Check if main window is in fullscreen mode. - if (getMainWindow()->isFullScreen()) + if (getMainWindow()->isFullScreen()) { getMainWindow()->showNormal(); + } MDIView* view = getMainWindow()->activeWindow(); - if (!view) // no active view + if (!view) { // no active view return; + } const auto oldmode = view->currentViewMode(); auto mode = (MDIView::ViewMode)iMsg; @@ -1873,8 +1959,9 @@ void StdViewDockUndockFullscreen::activated(int iMsg) bool StdViewDockUndockFullscreen::isActive() { MDIView* view = getMainWindow()->activeWindow(); - if (!view) + if (!view) { return false; + } // update the action group if needed auto pActGrp = qobject_cast(_pcAction); @@ -1897,44 +1984,43 @@ bool StdViewDockUndockFullscreen::isActive() DEF_STD_CMD_A(StdCmdViewVR) StdCmdViewVR::StdCmdViewVR() - : Command("Std_ViewVR") + : Command("Std_ViewVR") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("FreeCAD VR"); - sToolTipText = QT_TR_NOOP("Extends the FreeCAD 3D Window to a VR device"); - sWhatsThis = "Std_ViewVR"; - sStatusTip = sToolTipText; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("FreeCAD VR"); + sToolTipText = QT_TR_NOOP("Extends the FreeCAD 3D Window to a VR device"); + sWhatsThis = "Std_ViewVR"; + sStatusTip = sToolTipText; + eType = Alter3DView; } void StdCmdViewVR::activated(int iMsg) { - Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewVR\")"); + Q_UNUSED(iMsg); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"ViewVR\")"); } bool StdCmdViewVR::isActive() { - return getGuiApplication()->sendHasMsgToActiveView("ViewVR"); + return getGuiApplication()->sendHasMsgToActiveView("ViewVR"); } - //=========================================================================== // Std_ViewScreenShot //=========================================================================== DEF_STD_CMD_A(StdViewScreenShot) StdViewScreenShot::StdViewScreenShot() - : Command("Std_ViewScreenShot") + : Command("Std_ViewScreenShot") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Save &Image…"); - sToolTipText= QT_TR_NOOP("Creates a screenshot of the active view"); - sWhatsThis = "Std_ViewScreenShot"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewScreenShot"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Save &Image…"); + sToolTipText = QT_TR_NOOP("Creates a screenshot of the active view"); + sWhatsThis = "Std_ViewScreenShot"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewScreenShot"; + eType = Alter3DView; } void StdViewScreenShot::activated(int iMsg) @@ -1949,22 +2035,27 @@ void StdViewScreenShot::activated(int iMsg) formats = rd.getWriteImageFiletypeInfo(); } - Base::Reference hExt = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences")->GetGroup("General"); + Base::Reference hExt = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("General"); QString ext = QString::fromLatin1(hExt->GetASCII("OffscreenImageFormat").c_str()); int backtype = hExt->GetInt("OffscreenImageBackground", 0); - Base::Reference methodGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); + Base::Reference methodGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); QByteArray method = methodGrp->GetASCII("SavePicture").c_str(); QStringList filter; QString selFilter; for (QStringList::Iterator it = formats.begin(); it != formats.end(); ++it) { - filter << QStringLiteral("%1 %2 (*.%3)").arg((*it).toUpper(), - QObject::tr("files"), (*it).toLower()); - if (ext == *it) + filter << QStringLiteral("%1 %2 (*.%3)") + .arg((*it).toUpper(), QObject::tr("files"), (*it).toLower()); + if (ext == *it) { selFilter = filter.last(); + } } FileOptionsDialog fd(getMainWindow(), Qt::WindowFlags()); @@ -1972,8 +2063,9 @@ void StdViewScreenShot::activated(int iMsg) fd.setAcceptMode(QFileDialog::AcceptSave); fd.setWindowTitle(QObject::tr("Save Image")); fd.setNameFilters(filter); - if (!selFilter.isEmpty()) + if (!selFilter.isEmpty()) { fd.selectNameFilter(selFilter); + } // create the image options widget auto opt = new DlgSettingsImageImp(&fd); @@ -1985,8 +2077,12 @@ void StdViewScreenShot::activated(int iMsg) fd.setOptionsWidget(FileOptionsDialog::ExtensionRight, opt); fd.setOption(QFileDialog::DontConfirmOverwrite, false); opt->onSelectedFilter(fd.selectedNameFilter()); - QObject::connect(&fd, &FileOptionsDialog::filterSelected, - opt, &DlgSettingsImageImp::onSelectedFilter); + QObject::connect( + &fd, + &FileOptionsDialog::filterSelected, + opt, + &DlgSettingsImageImp::onSelectedFilter + ); if (fd.exec() == QDialog::Accepted) { selFilter = fd.selectedNameFilter(); @@ -2002,7 +2098,7 @@ void StdViewScreenShot::activated(int iMsg) int h = opt->imageHeight(); // search for the matching format - QString format = formats.front(); // take the first as default + QString format = formats.front(); // take the first as default for (QStringList::Iterator it = formats.begin(); it != formats.end(); ++it) { if (selFilter.startsWith((*it).toUpper())) { format = *it; @@ -2018,11 +2114,21 @@ void StdViewScreenShot::activated(int iMsg) // which background chosen const char* background; switch (opt->backgroundType()) { - case 0: background = "Current"; break; - case 1: background = "White"; break; - case 2: background = "Black"; break; - case 3: background = "Transparent"; break; - default: background = "Current"; break; + case 0: + background = "Current"; + break; + case 1: + background = "White"; + break; + case 2: + background = "Black"; + break; + case 3: + background = "Transparent"; + break; + default: + background = "Current"; + break; } hExt->SetInt("OffscreenImageBackground", opt->backgroundType()); @@ -2034,12 +2140,25 @@ void StdViewScreenShot::activated(int iMsg) QStringList lines = comment.split(QLatin1String("\n"), Qt::KeepEmptyParts); comment = lines.join(QLatin1String("\\n")); - doCommand(Gui, "Gui.activeDocument().activeView().saveImage('%s',%d,%d,'%s','%s')", - fn.toUtf8().constData(), w, h, background, comment.toUtf8().constData()); + doCommand( + Gui, + "Gui.activeDocument().activeView().saveImage('%s',%d,%d,'%s','%s')", + fn.toUtf8().constData(), + w, + h, + background, + comment.toUtf8().constData() + ); } else { - doCommand(Gui, "Gui.activeDocument().activeView().saveImage('%s',%d,%d,'%s')", - fn.toUtf8().constData(), w, h, background); + doCommand( + Gui, + "Gui.activeDocument().activeView().saveImage('%s',%d,%d,'%s')", + fn.toUtf8().constData(), + w, + h, + background + ); } // When adding a watermark check if the image could be created @@ -2094,15 +2213,15 @@ bool StdViewScreenShot::isActive() DEF_STD_CMD(StdViewLoadImage) StdViewLoadImage::StdViewLoadImage() - : Command("Std_ViewLoadImage") + : Command("Std_ViewLoadImage") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Load Image…"); - sToolTipText= QT_TR_NOOP("Loads an image"); - sWhatsThis = "Std_ViewLoadImage"; - sStatusTip = sToolTipText; - sPixmap = "image-open"; - eType = 0; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Load Image…"); + sToolTipText = QT_TR_NOOP("Loads an image"); + sWhatsThis = "Std_ViewLoadImage"; + sStatusTip = sToolTipText; + sPixmap = "image-open"; + eType = 0; } void StdViewLoadImage::activated(int iMsg) @@ -2140,15 +2259,15 @@ void StdViewLoadImage::activated(int iMsg) DEF_STD_CMD_A(StdCmdViewCreate) StdCmdViewCreate::StdCmdViewCreate() - : Command("Std_ViewCreate") + : Command("Std_ViewCreate") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("New 3D View"); - sToolTipText= QT_TR_NOOP("Opens a new 3D view window for the active document"); - sWhatsThis = "Std_ViewCreate"; - sStatusTip = sToolTipText; - sPixmap = "window-new"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("New 3D View"); + sToolTipText = QT_TR_NOOP("Opens a new 3D view window for the active document"); + sWhatsThis = "Std_ViewCreate"; + sStatusTip = sToolTipText; + sPixmap = "window-new"; + eType = Alter3DView; } void StdCmdViewCreate::activated(int iMsg) @@ -2169,17 +2288,17 @@ bool StdCmdViewCreate::isActive() DEF_STD_CMD_A(StdCmdToggleNavigation) StdCmdToggleNavigation::StdCmdToggleNavigation() - : Command("Std_ToggleNavigation") + : Command("Std_ToggleNavigation") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle Navigation/&Edit Mode"); - sToolTipText = QT_TR_NOOP("Toggles between navigation and edit mode"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_ToggleNavigation"; - //iAccel = Qt::SHIFT+Qt::Key_Space; - sAccel = "Esc"; - sPixmap = "Std_ToggleNavigation"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle Navigation/&Edit Mode"); + sToolTipText = QT_TR_NOOP("Toggles between navigation and edit mode"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_ToggleNavigation"; + // iAccel = Qt::SHIFT+Qt::Key_Space; + sAccel = "Esc"; + sPixmap = "Std_ToggleNavigation"; + eType = Alter3DView; } void StdCmdToggleNavigation::activated(int iMsg) @@ -2195,12 +2314,13 @@ void StdCmdToggleNavigation::activated(int iMsg) bool StdCmdToggleNavigation::isActive() { - //#0001087: Inventor Navigation continues with released Mouse Button - //This happens because 'Esc' is also used to close the task dialog. - //Add also new method 'isRedirectToSceneGraphEnabled' to explicitly - //check if this is allowed. - if (Gui::Control().activeDialog()) + // #0001087: Inventor Navigation continues with released Mouse Button + // This happens because 'Esc' is also used to close the task dialog. + // Add also new method 'isRedirectToSceneGraphEnabled' to explicitly + // check if this is allowed. + if (Gui::Control().activeDialog()) { return false; + } Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom()) { Gui::View3DInventorViewer* viewer = static_cast(view)->getViewer(); @@ -2210,23 +2330,21 @@ bool StdCmdToggleNavigation::isActive() } - - //=========================================================================== // Std_ViewExample1 //=========================================================================== DEF_STD_CMD_A(StdCmdAxisCross) StdCmdAxisCross::StdCmdAxisCross() - : Command("Std_AxisCross") + : Command("Std_AxisCross") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle A&xis Cross"); - sToolTipText = QT_TR_NOOP("Toggles the axis cross at the origin"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_AxisCross"; - sPixmap = "Std_AxisCross"; - sAccel = "A,C"; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle A&xis Cross"); + sToolTipText = QT_TR_NOOP("Toggles the axis cross at the origin"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_AxisCross"; + sPixmap = "Std_AxisCross"; + sAccel = "A,C"; } void StdCmdAxisCross::activated(int iMsg) @@ -2234,10 +2352,12 @@ void StdCmdAxisCross::activated(int iMsg) Q_UNUSED(iMsg); auto view = qobject_cast(Gui::getMainWindow()->activeWindow()); if (view) { - if (!view->getViewer()->hasAxisCross()) - doCommand(Command::Gui,"Gui.ActiveDocument.ActiveView.setAxisCross(True)"); - else - doCommand(Command::Gui,"Gui.ActiveDocument.ActiveView.setAxisCross(False)"); + if (!view->getViewer()->hasAxisCross()) { + doCommand(Command::Gui, "Gui.ActiveDocument.ActiveView.setAxisCross(True)"); + } + else { + doCommand(Command::Gui, "Gui.ActiveDocument.ActiveView.setAxisCross(False)"); + } } } @@ -2245,17 +2365,19 @@ bool StdCmdAxisCross::isActive() { auto view = qobject_cast(Gui::getMainWindow()->activeWindow()); if (view && view->getViewer()->hasAxisCross()) { - if (!_pcAction->isChecked()) + if (!_pcAction->isChecked()) { _pcAction->setChecked(true); + } } else { - if (_pcAction->isChecked()) + if (_pcAction->isChecked()) { _pcAction->setChecked(false); + } } - if (view) + if (view) { return true; + } return false; - } //=========================================================================== @@ -2264,21 +2386,21 @@ bool StdCmdAxisCross::isActive() DEF_STD_CMD_A(StdCmdViewExample1) StdCmdViewExample1::StdCmdViewExample1() - : Command("Std_ViewExample1") + : Command("Std_ViewExample1") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Inventor Example #1"); - sToolTipText = QT_TR_NOOP("Shows a 3D texture with manipulator"); - sWhatsThis = "Std_ViewExample1"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool1"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Inventor Example #1"); + sToolTipText = QT_TR_NOOP("Shows a 3D texture with manipulator"); + sWhatsThis = "Std_ViewExample1"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool1"; + eType = Alter3DView; } void StdCmdViewExample1::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Example1\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"Example1\")"); } bool StdCmdViewExample1::isActive() @@ -2292,21 +2414,21 @@ bool StdCmdViewExample1::isActive() DEF_STD_CMD_A(StdCmdViewExample2) StdCmdViewExample2::StdCmdViewExample2() - : Command("Std_ViewExample2") + : Command("Std_ViewExample2") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Inventor Example #2"); - sToolTipText = QT_TR_NOOP("Shows spheres and drag-lights"); - sWhatsThis = "Std_ViewExample2"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool2"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Inventor Example #2"); + sToolTipText = QT_TR_NOOP("Shows spheres and drag-lights"); + sWhatsThis = "Std_ViewExample2"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool2"; + eType = Alter3DView; } void StdCmdViewExample2::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Example2\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"Example2\")"); } bool StdCmdViewExample2::isActive() @@ -2320,21 +2442,21 @@ bool StdCmdViewExample2::isActive() DEF_STD_CMD_A(StdCmdViewExample3) StdCmdViewExample3::StdCmdViewExample3() - : Command("Std_ViewExample3") + : Command("Std_ViewExample3") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Inventor Example #3"); - sToolTipText = QT_TR_NOOP("Shows an animated texture"); - sWhatsThis = "Std_ViewExample3"; - sStatusTip = sToolTipText; - sPixmap = "Std_Tool3"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Inventor Example #3"); + sToolTipText = QT_TR_NOOP("Shows an animated texture"); + sWhatsThis = "Std_ViewExample3"; + sStatusTip = sToolTipText; + sPixmap = "Std_Tool3"; + eType = Alter3DView; } void StdCmdViewExample3::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Example3\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"Example3\")"); } bool StdCmdViewExample3::isActive() @@ -2349,21 +2471,21 @@ bool StdCmdViewExample3::isActive() DEF_STD_CMD_A(StdCmdViewIvStereoOff) StdCmdViewIvStereoOff::StdCmdViewIvStereoOff() - : Command("Std_ViewIvStereoOff") + : Command("Std_ViewIvStereoOff") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Stereo &Off"); - sToolTipText = QT_TR_NOOP("Switches stereo viewing off"); - sWhatsThis = "Std_ViewIvStereoOff"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewIvStereoOff"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Stereo &Off"); + sToolTipText = QT_TR_NOOP("Switches stereo viewing off"); + sWhatsThis = "Std_ViewIvStereoOff"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewIvStereoOff"; + eType = Alter3DView; } void StdCmdViewIvStereoOff::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"Mono\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setStereoType(\"Mono\")"); } bool StdCmdViewIvStereoOff::isActive() @@ -2378,21 +2500,21 @@ bool StdCmdViewIvStereoOff::isActive() DEF_STD_CMD_A(StdCmdViewIvStereoRedGreen) StdCmdViewIvStereoRedGreen::StdCmdViewIvStereoRedGreen() - : Command("Std_ViewIvStereoRedGreen") + : Command("Std_ViewIvStereoRedGreen") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Stereo Re&d/Cyan"); - sToolTipText = QT_TR_NOOP("Switches stereo viewing to red/cyan"); - sWhatsThis = "Std_ViewIvStereoRedGreen"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewIvStereoRedGreen"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Stereo Re&d/Cyan"); + sToolTipText = QT_TR_NOOP("Switches stereo viewing to red/cyan"); + sWhatsThis = "Std_ViewIvStereoRedGreen"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewIvStereoRedGreen"; + eType = Alter3DView; } void StdCmdViewIvStereoRedGreen::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"Anaglyph\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setStereoType(\"Anaglyph\")"); } bool StdCmdViewIvStereoRedGreen::isActive() @@ -2406,21 +2528,21 @@ bool StdCmdViewIvStereoRedGreen::isActive() DEF_STD_CMD_A(StdCmdViewIvStereoQuadBuff) StdCmdViewIvStereoQuadBuff::StdCmdViewIvStereoQuadBuff() - : Command("Std_ViewIvStereoQuadBuff") + : Command("Std_ViewIvStereoQuadBuff") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Stereo &Quad Buffer"); - sToolTipText = QT_TR_NOOP("Switches stereo viewing to quad buffer"); - sWhatsThis = "Std_ViewIvStereoQuadBuff"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewIvStereoQuadBuff"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Stereo &Quad Buffer"); + sToolTipText = QT_TR_NOOP("Switches stereo viewing to quad buffer"); + sWhatsThis = "Std_ViewIvStereoQuadBuff"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewIvStereoQuadBuff"; + eType = Alter3DView; } void StdCmdViewIvStereoQuadBuff::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"QuadBuffer\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setStereoType(\"QuadBuffer\")"); } bool StdCmdViewIvStereoQuadBuff::isActive() @@ -2434,21 +2556,21 @@ bool StdCmdViewIvStereoQuadBuff::isActive() DEF_STD_CMD_A(StdCmdViewIvStereoInterleavedRows) StdCmdViewIvStereoInterleavedRows::StdCmdViewIvStereoInterleavedRows() - : Command("Std_ViewIvStereoInterleavedRows") + : Command("Std_ViewIvStereoInterleavedRows") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Stereo Interleaved &Rows"); - sToolTipText = QT_TR_NOOP("Switches stereo viewing to interleaved rows"); - sWhatsThis = "Std_ViewIvStereoInterleavedRows"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewIvStereoInterleavedRows"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Stereo Interleaved &Rows"); + sToolTipText = QT_TR_NOOP("Switches stereo viewing to interleaved rows"); + sWhatsThis = "Std_ViewIvStereoInterleavedRows"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewIvStereoInterleavedRows"; + eType = Alter3DView; } void StdCmdViewIvStereoInterleavedRows::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"InterleavedRows\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setStereoType(\"InterleavedRows\")"); } bool StdCmdViewIvStereoInterleavedRows::isActive() @@ -2462,21 +2584,21 @@ bool StdCmdViewIvStereoInterleavedRows::isActive() DEF_STD_CMD_A(StdCmdViewIvStereoInterleavedColumns) StdCmdViewIvStereoInterleavedColumns::StdCmdViewIvStereoInterleavedColumns() - : Command("Std_ViewIvStereoInterleavedColumns") + : Command("Std_ViewIvStereoInterleavedColumns") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Stereo Interleaved &Columns"); - sToolTipText = QT_TR_NOOP("Switches stereo viewing to interleaved columns"); - sWhatsThis = "Std_ViewIvStereoInterleavedColumns"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewIvStereoInterleavedColumns"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Stereo Interleaved &Columns"); + sToolTipText = QT_TR_NOOP("Switches stereo viewing to interleaved columns"); + sWhatsThis = "Std_ViewIvStereoInterleavedColumns"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewIvStereoInterleavedColumns"; + eType = Alter3DView; } void StdCmdViewIvStereoInterleavedColumns::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"InterleavedColumns\")"); + doCommand(Command::Gui, "Gui.activeDocument().activeView().setStereoType(\"InterleavedColumns\")"); } bool StdCmdViewIvStereoInterleavedColumns::isActive() @@ -2491,42 +2613,45 @@ bool StdCmdViewIvStereoInterleavedColumns::isActive() DEF_STD_CMD_A(StdCmdViewIvIssueCamPos) StdCmdViewIvIssueCamPos::StdCmdViewIvIssueCamPos() - : Command("Std_ViewIvIssueCamPos") + : Command("Std_ViewIvIssueCamPos") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Issue Camera &Position"); - sToolTipText = QT_TR_NOOP("Issues the camera position to the console and to a macro, to easily recall this position"); - sWhatsThis = "Std_ViewIvIssueCamPos"; - sStatusTip = sToolTipText; - sPixmap = "Std_ViewIvIssueCamPos"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Issue Camera &Position"); + sToolTipText = QT_TR_NOOP( + "Issues the camera position to the console and to a macro, to easily recall this position" + ); + sWhatsThis = "Std_ViewIvIssueCamPos"; + sStatusTip = sToolTipText; + sPixmap = "Std_ViewIvIssueCamPos"; + eType = Alter3DView; } void StdCmdViewIvIssueCamPos::activated(int iMsg) { Q_UNUSED(iMsg); - std::string Temp,Temp2; + std::string Temp, Temp2; std::string::size_type pos; - const char* ppReturn=nullptr; - getGuiApplication()->sendMsgToActiveView("GetCamera",&ppReturn); + const char* ppReturn = nullptr; + getGuiApplication()->sendMsgToActiveView("GetCamera", &ppReturn); // remove the #inventor line... Temp2 = ppReturn; pos = Temp2.find_first_of("\n"); - Temp2.erase(0,pos); + Temp2.erase(0, pos); // remove all returns - while((pos=Temp2.find('\n')) != std::string::npos) - Temp2.replace(pos,1," "); + while ((pos = Temp2.find('\n')) != std::string::npos) { + Temp2.replace(pos, 1, " "); + } // build up the command string Temp += "Gui.SendMsgToActiveView(\"SetCamera "; Temp += Temp2; Temp += "\")"; - Base::Console().message("%s\n",Temp2.c_str()); - getGuiApplication()->macroManager()->addLine(MacroManager::Gui,Temp.c_str()); + Base::Console().message("%s\n", Temp2.c_str()); + getGuiApplication()->macroManager()->addLine(MacroManager::Gui, Temp.c_str()); } bool StdCmdViewIvIssueCamPos::isActive() @@ -2541,16 +2666,16 @@ bool StdCmdViewIvIssueCamPos::isActive() DEF_STD_CMD_A(StdViewZoomIn) StdViewZoomIn::StdViewZoomIn() - : Command("Std_ViewZoomIn") + : Command("Std_ViewZoomIn") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Zoom &In"); - sToolTipText = QT_TR_NOOP("Increases the zoom factor by a fixed amount"); - sWhatsThis = "Std_ViewZoomIn"; - sStatusTip = sToolTipText; - sPixmap = "zoom-in"; - sAccel = keySequenceToAccel(QKeySequence::ZoomIn); - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Zoom &In"); + sToolTipText = QT_TR_NOOP("Increases the zoom factor by a fixed amount"); + sWhatsThis = "Std_ViewZoomIn"; + sStatusTip = sToolTipText; + sPixmap = "zoom-in"; + sAccel = keySequenceToAccel(QKeySequence::ZoomIn); + eType = Alter3DView; } void StdViewZoomIn::activated(int iMsg) @@ -2570,16 +2695,16 @@ bool StdViewZoomIn::isActive() DEF_STD_CMD_A(StdViewZoomOut) StdViewZoomOut::StdViewZoomOut() - : Command("Std_ViewZoomOut") + : Command("Std_ViewZoomOut") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Zoom &Out"); - sToolTipText = QT_TR_NOOP("Decreases the zoom factor by a fixed amount"); - sWhatsThis = "Std_ViewZoomOut"; - sStatusTip = sToolTipText; - sPixmap = "zoom-out"; - sAccel = keySequenceToAccel(QKeySequence::ZoomOut); - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Zoom &Out"); + sToolTipText = QT_TR_NOOP("Decreases the zoom factor by a fixed amount"); + sWhatsThis = "Std_ViewZoomOut"; + sStatusTip = sToolTipText; + sPixmap = "zoom-out"; + sAccel = keySequenceToAccel(QKeySequence::ZoomOut); + eType = Alter3DView; } void StdViewZoomOut::activated(int iMsg) @@ -2593,53 +2718,64 @@ bool StdViewZoomOut::isActive() return getGuiApplication()->sendHasMsgToActiveView("ZoomOut"); } -namespace { -class SelectionCallbackHandler { +namespace +{ +class SelectionCallbackHandler +{ private: static std::unique_ptr currentSelectionHandler; QCursor prevSelectionCursor; - using FnCb = void (*)(void * userdata, SoEventCallback * node); + using FnCb = void (*)(void* userdata, SoEventCallback* node); FnCb fnCb; void* userData; bool prevSelectionEn; public: - // Creates a selection handler used to implement the common behaviour of BoxZoom, BoxSelection and BoxElementSelection. - // Takes the viewer, a selection mode, a cursor, a function pointer to be called on success and a void pointer for user data to be passed to the given function. - // The selection handler class stores all necessary previous states, registers a event callback and starts the selection in the given mode. - // If there is still a selection handler active, this call will generate a message and returns. - static void Create(View3DInventorViewer* viewer, View3DInventorViewer::SelectionMode selectionMode, - const QCursor& cursor, FnCb doFunction= nullptr, void* ud=nullptr) + // Creates a selection handler used to implement the common behaviour of BoxZoom, BoxSelection + // and BoxElementSelection. Takes the viewer, a selection mode, a cursor, a function pointer to + // be called on success and a void pointer for user data to be passed to the given function. The + // selection handler class stores all necessary previous states, registers a event callback and + // starts the selection in the given mode. If there is still a selection handler active, this + // call will generate a message and returns. + static void Create( + View3DInventorViewer* viewer, + View3DInventorViewer::SelectionMode selectionMode, + const QCursor& cursor, + FnCb doFunction = nullptr, + void* ud = nullptr + ) { - if (currentSelectionHandler) - { + if (currentSelectionHandler) { Base::Console().message("SelectionCallbackHandler: A selection handler already active."); return; } currentSelectionHandler = std::make_unique(); - if (viewer) - { + if (viewer) { currentSelectionHandler->userData = ud; currentSelectionHandler->fnCb = doFunction; currentSelectionHandler->prevSelectionCursor = viewer->cursor(); viewer->setEditingCursor(cursor); - viewer->addEventCallback(SoEvent::getClassTypeId(), - SelectionCallbackHandler::selectionCallback, currentSelectionHandler.get()); + viewer->addEventCallback( + SoEvent::getClassTypeId(), + SelectionCallbackHandler::selectionCallback, + currentSelectionHandler.get() + ); currentSelectionHandler->prevSelectionEn = viewer->isSelectionEnabled(); viewer->setSelectionEnabled(false); viewer->startSelection(selectionMode); } } - void* getUserData() const { + void* getUserData() const + { return userData; } // Implements the event handler. In the normal case the provided function is called. // Also supports aborting the selection mode by pressing (releasing) the Escape key. - static void selectionCallback(void * ud, SoEventCallback * n) + static void selectionCallback(void* ud, SoEventCallback* n) { auto selectionHandler = static_cast(ud); auto view = static_cast(n->getUserData()); @@ -2662,33 +2798,44 @@ public: else if (ev->isOfType(SoMouseButtonEvent::getClassTypeId())) { const auto mbe = static_cast(ev); - // Mark all incoming mouse button events as handled, especially, to deactivate the selection node + // Mark all incoming mouse button events as handled, especially, to deactivate the + // selection node n->getAction()->setHandled(); - if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::UP) - { - if (selectionHandler && selectionHandler->fnCb) + if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 + && mbe->getState() == SoButtonEvent::UP) { + if (selectionHandler && selectionHandler->fnCb) { selectionHandler->fnCb(selectionHandler->getUserData(), n); + } restoreState(selectionHandler, view); } // No other mouse events available from Coin3D to implement right mouse up abort } } - static void restoreState(SelectionCallbackHandler * selectionHandler, View3DInventorViewer* view) + static void restoreState(SelectionCallbackHandler* selectionHandler, View3DInventorViewer* view) { - if (selectionHandler) - { + if (selectionHandler) { selectionHandler->fnCb = nullptr; view->setEditingCursor(selectionHandler->prevSelectionCursor); - view->removeEventCallback(SoEvent::getClassTypeId(), SelectionCallbackHandler::selectionCallback, selectionHandler); + view->removeEventCallback( + SoEvent::getClassTypeId(), + SelectionCallbackHandler::selectionCallback, + selectionHandler + ); view->setSelectionEnabled(selectionHandler->prevSelectionEn); } Application::Instance->commandManager().testActive(); currentSelectionHandler = nullptr; } - static QCursor makeCursor([[maybe_unused]] QWidget* widget, const QSize& size, const char* svgFile, int hotX, int hotY) + static QCursor makeCursor( + [[maybe_unused]] QWidget* widget, + const QSize& size, + const char* svgFile, + int hotX, + int hotY + ) { qreal hotXF = hotX; qreal hotYF = hotY; @@ -2703,9 +2850,10 @@ public: return QCursor(px, static_cast(hotXF), static_cast(hotYF)); } }; -} +} // namespace -std::unique_ptr SelectionCallbackHandler::currentSelectionHandler = std::unique_ptr(); +std::unique_ptr SelectionCallbackHandler::currentSelectionHandler + = std::unique_ptr(); //=========================================================================== // Std_ViewBoxZoom //=========================================================================== @@ -2713,28 +2861,28 @@ std::unique_ptr SelectionCallbackHandler::currentSelec DEF_3DV_CMD(StdViewBoxZoom) StdViewBoxZoom::StdViewBoxZoom() - : Command("Std_ViewBoxZoom") + : Command("Std_ViewBoxZoom") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Box Zoom"); - sToolTipText = QT_TR_NOOP("Activates the box zoom tool"); - sWhatsThis = "Std_ViewBoxZoom"; - sStatusTip = sToolTipText; - sPixmap = "zoom-border"; - sAccel = "Ctrl+B"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Box Zoom"); + sToolTipText = QT_TR_NOOP("Activates the box zoom tool"); + sWhatsThis = "Std_ViewBoxZoom"; + sStatusTip = sToolTipText; + sPixmap = "zoom-border"; + sAccel = "Ctrl+B"; + eType = Alter3DView; } void StdViewBoxZoom::activated(int iMsg) { Q_UNUSED(iMsg); auto view = qobject_cast(getMainWindow()->activeWindow()); - if ( view ) { + if (view) { View3DInventorViewer* viewer = view->getViewer(); if (!viewer->isSelecting()) { // NOLINTBEGIN - QCursor cursor = SelectionCallbackHandler::makeCursor(viewer, QSize(32, 32), - "zoom-border-cross", 6, 6); + QCursor cursor + = SelectionCallbackHandler::makeCursor(viewer, QSize(32, 32), "zoom-border-cross", 6, 6); SelectionCallbackHandler::Create(viewer, View3DInventorViewer::BoxZoom, cursor); // NOLINTEND } @@ -2747,104 +2895,125 @@ void StdViewBoxZoom::activated(int iMsg) DEF_3DV_CMD(StdBoxSelection) StdBoxSelection::StdBoxSelection() - : Command("Std_BoxSelection") + : Command("Std_BoxSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("&Box Selection"); - sToolTipText = QT_TR_NOOP("Activates the box selection tool"); - sWhatsThis = "Std_BoxSelection"; - sStatusTip = sToolTipText; - sPixmap = "edit-select-box"; - sAccel = "Shift+B"; - eType = AlterSelection; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("&Box Selection"); + sToolTipText = QT_TR_NOOP("Activates the box selection tool"); + sWhatsThis = "Std_BoxSelection"; + sStatusTip = sToolTipText; + sPixmap = "edit-select-box"; + sAccel = "Shift+B"; + eType = AlterSelection; } -using SelectionMode = enum { CENTER, INTERSECT }; +using SelectionMode = enum +{ + CENTER, + INTERSECT +}; static std::vector getBoxSelection( - ViewProviderDocumentObject *vp, SelectionMode mode, bool selectElement, - const Base::ViewProjMethod &proj, const Base::Polygon2d &polygon, - const Base::Matrix4D &mat, bool transform=true, int depth=0) + ViewProviderDocumentObject* vp, + SelectionMode mode, + bool selectElement, + const Base::ViewProjMethod& proj, + const Base::Polygon2d& polygon, + const Base::Matrix4D& mat, + bool transform = true, + int depth = 0 +) { std::vector ret; auto obj = vp->getObject(); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return ret; + } // DO NOT check this view object Visibility, let the caller do this. Because // we may be called by upper object hierarchy that manages our visibility. - auto bbox3 = vp->getBoundingBox(nullptr,transform); - if(!bbox3.IsValid()) + auto bbox3 = vp->getBoundingBox(nullptr, transform); + if (!bbox3.IsValid()) { return ret; + } auto bbox = bbox3.Transformed(mat).ProjectBox(&proj); // check if both two boundary points are inside polygon, only // valid since we know the given polygon is a box. - if(polygon.Contains(Base::Vector2d(bbox.MinX,bbox.MinY)) && - polygon.Contains(Base::Vector2d(bbox.MaxX,bbox.MaxY))) - { + if (polygon.Contains(Base::Vector2d(bbox.MinX, bbox.MinY)) + && polygon.Contains(Base::Vector2d(bbox.MaxX, bbox.MaxY))) { ret.emplace_back(""); return ret; } - if(!bbox.Intersect(polygon)) + if (!bbox.Intersect(polygon)) { return ret; + } - const auto &subs = obj->getSubObjects(App::DocumentObject::GS_SELECT); - if(subs.empty()) { - if(!selectElement) { - if(mode==INTERSECT || polygon.Contains(bbox.GetCenter())) + const auto& subs = obj->getSubObjects(App::DocumentObject::GS_SELECT); + if (subs.empty()) { + if (!selectElement) { + if (mode == INTERSECT || polygon.Contains(bbox.GetCenter())) { ret.emplace_back(""); + } return ret; } Base::PyGILStateLocker lock; - PyObject *pyobj = nullptr; + PyObject* pyobj = nullptr; Base::Matrix4D matCopy(mat); - obj->getSubObject(nullptr,&pyobj,&matCopy,transform,depth); - if(!pyobj) + obj->getSubObject(nullptr, &pyobj, &matCopy, transform, depth); + if (!pyobj) { return ret; - Py::Object pyobject(pyobj,true); - if(!PyObject_TypeCheck(pyobj,&Data::ComplexGeoDataPy::Type)) + } + Py::Object pyobject(pyobj, true); + if (!PyObject_TypeCheck(pyobj, &Data::ComplexGeoDataPy::Type)) { return ret; + } auto data = static_cast(pyobj)->getComplexGeoDataPtr(); - for(auto type : data->getElementTypes()) { + for (auto type : data->getElementTypes()) { size_t count = data->countSubElements(type); - if(!count) + if (!count) { continue; - for(size_t i=1;i<=count;++i) { + } + for (size_t i = 1; i <= count; ++i) { std::string element(type); element += std::to_string(i); std::unique_ptr segment(data->getSubElementByName(element.c_str())); - if(!segment) + if (!segment) { continue; + } std::vector points; std::vector lines; - data->getLinesFromSubElement(segment.get(),points,lines); - if(lines.empty()) { - if(points.empty()) + data->getLinesFromSubElement(segment.get(), points, lines); + if (lines.empty()) { + if (points.empty()) { continue; + } auto v = proj(points[0]); - if(polygon.Contains(Base::Vector2d(v.x,v.y))) + if (polygon.Contains(Base::Vector2d(v.x, v.y))) { ret.push_back(element); + } continue; } Base::Polygon2d loop; // TODO: can we assume the line returned above are in proper // order if the element is a face? auto v = proj(points[lines.front().I1]); - loop.Add(Base::Vector2d(v.x,v.y)); - for(auto &line : lines) { - for(auto i=line.I1;i getBoxSelection( } size_t count = 0; - for(auto &sub : subs) { - App::DocumentObject *parent = nullptr; + for (auto& sub : subs) { + App::DocumentObject* parent = nullptr; std::string childName; Base::Matrix4D smat(mat); - auto sobj = obj->resolve(sub.c_str(),&parent,&childName,nullptr,nullptr,&smat,transform,depth+1); - if(!sobj) + auto sobj + = obj->resolve(sub.c_str(), &parent, &childName, nullptr, nullptr, &smat, transform, depth + 1); + if (!sobj) { continue; + } int vis; - if(!parent || (vis=parent->isElementVisible(childName.c_str()))<0) - vis = sobj->Visibility.getValue()?1:0; + if (!parent || (vis = parent->isElementVisible(childName.c_str())) < 0) { + vis = sobj->Visibility.getValue() ? 1 : 0; + } - if(!vis) + if (!vis) { continue; + } - auto svp = freecad_cast(Application::Instance->getViewProvider(sobj)); - if(!svp) + auto svp = freecad_cast( + Application::Instance->getViewProvider(sobj) + ); + if (!svp) { continue; + } - const auto &sels = getBoxSelection(svp,mode,selectElement,proj,polygon,smat,false,depth+1); - if(sels.size()==1 && sels[0].empty()) + const auto& sels + = getBoxSelection(svp, mode, selectElement, proj, polygon, smat, false, depth + 1); + if (sels.size() == 1 && sels[0].empty()) { ++count; - for(auto &sel : sels) - ret.emplace_back(sub+sel); + } + for (auto& sel : sels) { + ret.emplace_back(sub + sel); + } } - if(count==subs.size()) { + if (count == subs.size()) { ret.resize(1); ret[0].clear(); } return ret; } -static void doSelect(void* ud, SoEventCallback * cb) +static void doSelect(void* ud, SoEventCallback* cb) { bool selectElement = ud ? true : false; auto viewer = static_cast(cb->getUserData()); @@ -2908,12 +3087,14 @@ static void doSelect(void* ud, SoEventCallback * cb) // when selecting from right to left then select by intersection // otherwise if the center is inside the rectangle - if (picked[0][0] > picked[1][0]) + if (picked[0][0] > picked[1][0]) { selectionMode = INTERSECT; + } } else { - for (const auto & it : picked) - polygon.Add(Base::Vector2d(it[0],it[1])); + for (const auto& it : picked) { + polygon.Add(Base::Vector2d(it[0], it[1])); + } } App::Document* doc = App::GetApplication().getActiveDocument(); @@ -2926,17 +3107,22 @@ static void doSelect(void* ud, SoEventCallback * cb) } const std::vector objects = doc->getObjects(); - for(auto obj : objects) { - if(App::GeoFeatureGroupExtension::getGroupOfObject(obj)) + for (auto obj : objects) { + if (App::GeoFeatureGroupExtension::getGroupOfObject(obj)) { continue; + } - auto vp = freecad_cast(Application::Instance->getViewProvider(obj)); - if (!vp || !vp->isVisible()) + auto vp = freecad_cast( + Application::Instance->getViewProvider(obj) + ); + if (!vp || !vp->isVisible()) { continue; + } Base::Matrix4D mat; - for(auto &sub : getBoxSelection(vp,selectionMode,selectElement,proj,polygon,mat)) + for (auto& sub : getBoxSelection(vp, selectionMode, selectElement, proj, polygon, mat)) { Gui::Selection().addSelection(doc->getName(), obj->getNameInDocument(), sub.c_str()); + } } } } @@ -2957,9 +3143,20 @@ void StdBoxSelection::activated(int iMsg) } // NOLINTBEGIN - QCursor cursor = SelectionCallbackHandler::makeCursor(viewer, QSize(32, 32), - "edit-select-box-cross", 6, 6); - SelectionCallbackHandler::Create(viewer, View3DInventorViewer::Rubberband, cursor, doSelect, nullptr); + QCursor cursor = SelectionCallbackHandler::makeCursor( + viewer, + QSize(32, 32), + "edit-select-box-cross", + 6, + 6 + ); + SelectionCallbackHandler::Create( + viewer, + View3DInventorViewer::Rubberband, + cursor, + doSelect, + nullptr + ); viewer->setSelectionEnabled(false); // NOLINTEND } @@ -2973,16 +3170,16 @@ void StdBoxSelection::activated(int iMsg) DEF_3DV_CMD(StdBoxElementSelection) StdBoxElementSelection::StdBoxElementSelection() - : Command("Std_BoxElementSelection") + : Command("Std_BoxElementSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Bo&x Element Selection"); - sToolTipText = QT_TR_NOOP("Activates box element selection"); - sWhatsThis = "Std_BoxElementSelection"; - sStatusTip = sToolTipText; - sPixmap = "edit-element-select-box"; - sAccel = "Shift+E"; - eType = AlterSelection; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Bo&x Element Selection"); + sToolTipText = QT_TR_NOOP("Activates box element selection"); + sWhatsThis = "Std_BoxElementSelection"; + sStatusTip = sToolTipText; + sPixmap = "edit-element-select-box"; + sAccel = "Shift+E"; + eType = AlterSelection; } void StdBoxElementSelection::activated(int iMsg) @@ -3001,9 +3198,20 @@ void StdBoxElementSelection::activated(int iMsg) } // NOLINTBEGIN - QCursor cursor = SelectionCallbackHandler::makeCursor(viewer, QSize(32, 32), - "edit-element-select-box-cross", 6, 6); - SelectionCallbackHandler::Create(viewer, View3DInventorViewer::Rubberband, cursor, doSelect, this); + QCursor cursor = SelectionCallbackHandler::makeCursor( + viewer, + QSize(32, 32), + "edit-element-select-box-cross", + 6, + 6 + ); + SelectionCallbackHandler::Create( + viewer, + View3DInventorViewer::Rubberband, + cursor, + doSelect, + this + ); viewer->setSelectionEnabled(false); // NOLINTEND } @@ -3018,16 +3226,16 @@ void StdBoxElementSelection::activated(int iMsg) DEF_STD_CMD(StdTreeSelection) StdTreeSelection::StdTreeSelection() - : Command("Std_TreeSelection") + : Command("Std_TreeSelection") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&Go to Selection"); - sToolTipText = QT_TR_NOOP("Scrolls to the first selected item"); - sWhatsThis = "Std_TreeSelection"; - sStatusTip = sToolTipText; - eType = Alter3DView; - sPixmap = "tree-goto-sel"; - sAccel = "T,G"; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&Go to Selection"); + sToolTipText = QT_TR_NOOP("Scrolls to the first selected item"); + sWhatsThis = "Std_TreeSelection"; + sStatusTip = sToolTipText; + eType = Alter3DView; + sPixmap = "tree-goto-sel"; + sAccel = "T,G"; } void StdTreeSelection::activated(int iMsg) @@ -3043,22 +3251,23 @@ void StdTreeSelection::activated(int iMsg) DEF_STD_CMD(StdCmdTreeCollapse) StdCmdTreeCollapse::StdCmdTreeCollapse() - : Command("Std_TreeCollapse") + : Command("Std_TreeCollapse") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Collapse Selected Items"); - sToolTipText = QT_TR_NOOP("Collapses the currently selected tree items"); - sWhatsThis = "Std_TreeCollapse"; - sStatusTip = sToolTipText; - eType = Alter3DView; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Collapse Selected Items"); + sToolTipText = QT_TR_NOOP("Collapses the currently selected tree items"); + sWhatsThis = "Std_TreeCollapse"; + sStatusTip = sToolTipText; + eType = Alter3DView; } void StdCmdTreeCollapse::activated(int iMsg) { Q_UNUSED(iMsg); QList tree = Gui::getMainWindow()->findChildren(); - for (QList::iterator it = tree.begin(); it != tree.end(); ++it) + for (QList::iterator it = tree.begin(); it != tree.end(); ++it) { (*it)->expandSelectedItems(TreeItemMode::CollapseItem); + } } //=========================================================================== @@ -3068,22 +3277,23 @@ void StdCmdTreeCollapse::activated(int iMsg) DEF_STD_CMD(StdCmdTreeExpand) StdCmdTreeExpand::StdCmdTreeExpand() - : Command("Std_TreeExpand") + : Command("Std_TreeExpand") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Expand Selected Items"); - sToolTipText = QT_TR_NOOP("Expands the currently selected tree items"); - sWhatsThis = "Std_TreeExpand"; - sStatusTip = sToolTipText; - eType = Alter3DView; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Expand Selected Items"); + sToolTipText = QT_TR_NOOP("Expands the currently selected tree items"); + sWhatsThis = "Std_TreeExpand"; + sStatusTip = sToolTipText; + eType = Alter3DView; } void StdCmdTreeExpand::activated(int iMsg) { Q_UNUSED(iMsg); QList tree = Gui::getMainWindow()->findChildren(); - for (QList::iterator it = tree.begin(); it != tree.end(); ++it) + for (QList::iterator it = tree.begin(); it != tree.end(); ++it) { (*it)->expandSelectedItems(TreeItemMode::ExpandItem); + } } //=========================================================================== @@ -3093,47 +3303,62 @@ void StdCmdTreeExpand::activated(int iMsg) DEF_STD_CMD_A(StdCmdTreeSelectAllInstances) StdCmdTreeSelectAllInstances::StdCmdTreeSelectAllInstances() - : Command("Std_TreeSelectAllInstances") + : Command("Std_TreeSelectAllInstances") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Select All Instances"); - sToolTipText = QT_TR_NOOP("Selects all instances of the currently selected object"); - sWhatsThis = "Std_TreeSelectAllInstances"; - sStatusTip = sToolTipText; - sPixmap = "sel-instance"; - eType = AlterSelection; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Select All Instances"); + sToolTipText = QT_TR_NOOP("Selects all instances of the currently selected object"); + sWhatsThis = "Std_TreeSelectAllInstances"; + sStatusTip = sToolTipText; + sPixmap = "sel-instance"; + eType = AlterSelection; } bool StdCmdTreeSelectAllInstances::isActive() { - const auto &sels = Selection().getSelectionEx("*",App::DocumentObject::getClassTypeId(), ResolveMode::OldStyleElement, true); - if(sels.empty()) + const auto& sels = Selection().getSelectionEx( + "*", + App::DocumentObject::getClassTypeId(), + ResolveMode::OldStyleElement, + true + ); + if (sels.empty()) { return false; + } auto obj = sels[0].getObject(); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return false; - return freecad_cast( - Application::Instance->getViewProvider(obj)) != nullptr; + } + return freecad_cast(Application::Instance->getViewProvider(obj)) + != nullptr; } void StdCmdTreeSelectAllInstances::activated(int iMsg) { Q_UNUSED(iMsg); - const auto &sels = Selection().getSelectionEx("*",App::DocumentObject::getClassTypeId(), ResolveMode::OldStyleElement, true); - if(sels.empty()) + const auto& sels = Selection().getSelectionEx( + "*", + App::DocumentObject::getClassTypeId(), + ResolveMode::OldStyleElement, + true + ); + if (sels.empty()) { return; + } auto obj = sels[0].getObject(); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return; - auto vpd = freecad_cast( - Application::Instance->getViewProvider(obj)); - if(!vpd) + } + auto vpd = freecad_cast(Application::Instance->getViewProvider(obj)); + if (!vpd) { return; + } Selection().selStackPush(); Selection().clearCompleteSelection(); const auto trees = getMainWindow()->findChildren(); - for(auto tree : trees) + for (auto tree : trees) { tree->selectAllInstances(*vpd); + } Selection().selStackPush(); } @@ -3145,16 +3370,16 @@ void StdCmdTreeSelectAllInstances::activated(int iMsg) DEF_3DV_CMD(StdCmdSceneInspector) StdCmdSceneInspector::StdCmdSceneInspector() - : Command("Std_SceneInspector") + : Command("Std_SceneInspector") { // setting the - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Scene I&nspector"); - sToolTipText = QT_TR_NOOP("Opens the scene inspector"); - sWhatsThis = "Std_SceneInspector"; - sStatusTip = sToolTipText; - eType = Alter3DView; - sPixmap = "Std_SceneInspector"; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Scene I&nspector"); + sToolTipText = QT_TR_NOOP("Opens the scene inspector"); + sWhatsThis = "Std_SceneInspector"; + sStatusTip = sToolTipText; + eType = Alter3DView; + sPixmap = "Std_SceneInspector"; } void StdCmdSceneInspector::activated(int iMsg) @@ -3163,8 +3388,9 @@ void StdCmdSceneInspector::activated(int iMsg) Gui::Document* doc = Application::Instance->activeDocument(); if (doc) { static QPointer dlg = nullptr; - if (!dlg) + if (!dlg) { dlg = new Gui::Dialog::DlgInspector(getMainWindow()); + } dlg->setDocument(doc); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->show(); @@ -3178,16 +3404,16 @@ void StdCmdSceneInspector::activated(int iMsg) DEF_STD_CMD_A(StdCmdTextureMapping) StdCmdTextureMapping::StdCmdTextureMapping() - : Command("Std_TextureMapping") + : Command("Std_TextureMapping") { // setting the - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Text&ure Mapping"); - sToolTipText = QT_TR_NOOP("Maps textures to shapes"); - sWhatsThis = "Std_TextureMapping"; - sStatusTip = sToolTipText; - sPixmap = "Std_TextureMapping"; - eType = Alter3DView; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Text&ure Mapping"); + sToolTipText = QT_TR_NOOP("Maps textures to shapes"); + sWhatsThis = "Std_TextureMapping"; + sStatusTip = sToolTipText; + sPixmap = "Std_TextureMapping"; + eType = Alter3DView; } void StdCmdTextureMapping::activated(int iMsg) @@ -3199,30 +3425,30 @@ void StdCmdTextureMapping::activated(int iMsg) bool StdCmdTextureMapping::isActive() { Gui::MDIView* view = getMainWindow()->activeWindow(); - return view && view->isDerivedFrom() - && (!(Gui::Control().activeDialog())); + return view && view->isDerivedFrom() && (!(Gui::Control().activeDialog())); } DEF_STD_CMD(StdCmdDemoMode) StdCmdDemoMode::StdCmdDemoMode() - : Command("Std_DemoMode") + : Command("Std_DemoMode") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("View &Turntable"); - sToolTipText = QT_TR_NOOP("Opens a turntable view"); - sWhatsThis = "Std_DemoMode"; - sStatusTip = sToolTipText; - eType = Alter3DView; - sPixmap = "Std_DemoMode"; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("View &Turntable"); + sToolTipText = QT_TR_NOOP("Opens a turntable view"); + sWhatsThis = "Std_DemoMode"; + sStatusTip = sToolTipText; + eType = Alter3DView; + sPixmap = "Std_DemoMode"; } void StdCmdDemoMode::activated(int iMsg) { Q_UNUSED(iMsg); static QPointer dlg = nullptr; - if (!dlg) + if (!dlg) { dlg = new Gui::Dialog::DemoMode(getMainWindow()); + } dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->show(); } @@ -3235,20 +3461,20 @@ void StdCmdDemoMode::activated(int iMsg) DEF_STD_CMD_A(StdCmdSelBack) StdCmdSelBack::StdCmdSelBack() - :Command("Std_SelBack") + : Command("Std_SelBack") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Selection &Back"); - static std::string toolTip = std::string("

") - + QT_TR_NOOP("Restores the previous tree view selection. " - "Only works if tree RecordSelection mode is switched on.") - + "

"; - sToolTipText = toolTip.c_str(); - sWhatsThis = "Std_SelBack"; - sStatusTip = sToolTipText; - sPixmap = "sel-back"; - sAccel = "S, B"; - eType = AlterSelection; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Selection &Back"); + static std::string toolTip = std::string("

") + + QT_TR_NOOP("Restores the previous tree view selection. " + "Only works if tree RecordSelection mode is switched on.") + + "

"; + sToolTipText = toolTip.c_str(); + sWhatsThis = "Std_SelBack"; + sStatusTip = sToolTipText; + sPixmap = "sel-back"; + sAccel = "S, B"; + eType = AlterSelection; } void StdCmdSelBack::activated(int iMsg) @@ -3259,7 +3485,7 @@ void StdCmdSelBack::activated(int iMsg) bool StdCmdSelBack::isActive() { - return Selection().selStackBackSize()>1; + return Selection().selStackBackSize() > 1; } //=========================================================================== @@ -3269,20 +3495,20 @@ bool StdCmdSelBack::isActive() DEF_STD_CMD_A(StdCmdSelForward) StdCmdSelForward::StdCmdSelForward() - :Command("Std_SelForward") + : Command("Std_SelForward") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Selection &Forward"); - static std::string toolTip = std::string("

") - + QT_TR_NOOP("Restores the next tree view selection. " - "Only works if tree RecordSelection mode is switched on.") - + "

"; - sToolTipText = toolTip.c_str(); - sWhatsThis = "Std_SelForward"; - sStatusTip = sToolTipText; - sPixmap = "sel-forward"; - sAccel = "S, F"; - eType = AlterSelection; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Selection &Forward"); + static std::string toolTip = std::string("

") + + QT_TR_NOOP("Restores the next tree view selection. " + "Only works if tree RecordSelection mode is switched on.") + + "

"; + sToolTipText = toolTip.c_str(); + sWhatsThis = "Std_SelForward"; + sStatusTip = sToolTipText; + sPixmap = "sel-forward"; + sAccel = "S, F"; + eType = AlterSelection; } void StdCmdSelForward::activated(int iMsg) @@ -3293,119 +3519,129 @@ void StdCmdSelForward::activated(int iMsg) bool StdCmdSelForward::isActive() { - return !!Selection().selStackForwardSize(); + return !!Selection().selStackForwardSize(); } //======================================================================= // Std_TreeSingleDocument //=========================================================================== -#define TREEVIEW_DOC_CMD_DEF(_name,_v) \ -DEF_STD_CMD_AC(StdTree##_name) \ -void StdTree##_name::activated(int){ \ - TreeParams::setDocumentMode(_v);\ - if(_pcAction) _pcAction->setBlockedChecked(true);\ -}\ -Action * StdTree##_name::createAction(void) {\ - Action *pcAction = Command::createAction();\ - pcAction->setCheckable(true);\ - pcAction->setIcon(QIcon());\ - _pcAction = pcAction;\ - isActive();\ - return pcAction;\ -}\ -bool StdTree##_name::isActive() {\ - bool checked = TreeParams::getDocumentMode()==_v;\ - if(_pcAction && _pcAction->isChecked()!=checked)\ - _pcAction->setBlockedChecked(checked);\ - return true;\ -} +#define TREEVIEW_DOC_CMD_DEF(_name, _v) \ + DEF_STD_CMD_AC(StdTree##_name) \ + void StdTree##_name::activated(int) \ + { \ + TreeParams::setDocumentMode(_v); \ + if (_pcAction) \ + _pcAction->setBlockedChecked(true); \ + } \ + Action* StdTree##_name::createAction(void) \ + { \ + Action* pcAction = Command::createAction(); \ + pcAction->setCheckable(true); \ + pcAction->setIcon(QIcon()); \ + _pcAction = pcAction; \ + isActive(); \ + return pcAction; \ + } \ + bool StdTree##_name::isActive() \ + { \ + bool checked = TreeParams::getDocumentMode() == _v; \ + if (_pcAction && _pcAction->isChecked() != checked) \ + _pcAction->setBlockedChecked(checked); \ + return true; \ + } -TREEVIEW_DOC_CMD_DEF(SingleDocument,0) +TREEVIEW_DOC_CMD_DEF(SingleDocument, 0) StdTreeSingleDocument::StdTreeSingleDocument() - : Command("Std_TreeSingleDocument") + : Command("Std_TreeSingleDocument") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&Single Document"); + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&Single Document"); sToolTipText = QT_TR_NOOP("Displays only the active document in the tree view"); - sWhatsThis = "Std_TreeSingleDocument"; + sWhatsThis = "Std_TreeSingleDocument"; sStatusTip = sToolTipText; - sPixmap = "tree-doc-single"; - eType = 0; + sPixmap = "tree-doc-single"; + eType = 0; } //=========================================================================== // Std_TreeMultiDocument //=========================================================================== -TREEVIEW_DOC_CMD_DEF(MultiDocument,1) +TREEVIEW_DOC_CMD_DEF(MultiDocument, 1) StdTreeMultiDocument::StdTreeMultiDocument() - : Command("Std_TreeMultiDocument") + : Command("Std_TreeMultiDocument") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&Multi Document"); + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&Multi Document"); sToolTipText = QT_TR_NOOP("Displays all documents in the tree view"); - sWhatsThis = "Std_TreeMultiDocument"; - sStatusTip = sToolTipText; - sPixmap = "tree-doc-multi"; - eType = 0; + sWhatsThis = "Std_TreeMultiDocument"; + sStatusTip = sToolTipText; + sPixmap = "tree-doc-multi"; + eType = 0; } //=========================================================================== // Std_TreeCollapseDocument //=========================================================================== -TREEVIEW_DOC_CMD_DEF(CollapseDocument,2) +TREEVIEW_DOC_CMD_DEF(CollapseDocument, 2) StdTreeCollapseDocument::StdTreeCollapseDocument() - : Command("Std_TreeCollapseDocument") + : Command("Std_TreeCollapseDocument") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("Collapse/E&xpand"); + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("Collapse/E&xpand"); sToolTipText = QT_TR_NOOP("Expands the active document and collapses all others"); - sWhatsThis = "Std_TreeCollapseDocument"; - sStatusTip = sToolTipText; - sPixmap = "tree-doc-collapse"; - eType = 0; + sWhatsThis = "Std_TreeCollapseDocument"; + sStatusTip = sToolTipText; + sPixmap = "tree-doc-collapse"; + eType = 0; } //=========================================================================== // Std_TreeSyncView //=========================================================================== #define TREEVIEW_CMD_DEF(_name) \ -DEF_STD_CMD_AC(StdTree##_name) \ -void StdTree##_name::activated(int){ \ - auto checked = !TreeParams::get##_name();\ - TreeParams::set##_name(checked);\ - if(_pcAction) _pcAction->setBlockedChecked(checked);\ -}\ -Action * StdTree##_name::createAction() {\ - Action *pcAction = Command::createAction();\ - pcAction->setCheckable(true);\ - pcAction->setIcon(QIcon());\ - _pcAction = pcAction;\ - isActive();\ - return pcAction;\ -}\ -bool StdTree##_name::isActive() {\ - bool checked = TreeParams::get##_name();\ - if(_pcAction && _pcAction->isChecked()!=checked)\ - _pcAction->setBlockedChecked(checked);\ - return true;\ -} + DEF_STD_CMD_AC(StdTree##_name) \ + void StdTree##_name::activated(int) \ + { \ + auto checked = !TreeParams::get##_name(); \ + TreeParams::set##_name(checked); \ + if (_pcAction) \ + _pcAction->setBlockedChecked(checked); \ + } \ + Action* StdTree##_name::createAction() \ + { \ + Action* pcAction = Command::createAction(); \ + pcAction->setCheckable(true); \ + pcAction->setIcon(QIcon()); \ + _pcAction = pcAction; \ + isActive(); \ + return pcAction; \ + } \ + bool StdTree##_name::isActive() \ + { \ + bool checked = TreeParams::get##_name(); \ + if (_pcAction && _pcAction->isChecked() != checked) \ + _pcAction->setBlockedChecked(checked); \ + return true; \ + } TREEVIEW_CMD_DEF(SyncView) StdTreeSyncView::StdTreeSyncView() - : Command("Std_TreeSyncView") + : Command("Std_TreeSyncView") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&1 Sync View"); - sToolTipText = QT_TR_NOOP("Switches to the 3D view containing the selected item from the tree view"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TreeSyncView"; - sPixmap = "tree-sync-view"; - sAccel = "T,1"; - eType = 0; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&1 Sync View"); + sToolTipText = QT_TR_NOOP( + "Switches to the 3D view containing the selected item from the tree view" + ); + sStatusTip = sToolTipText; + sWhatsThis = "Std_TreeSyncView"; + sPixmap = "tree-sync-view"; + sAccel = "T,1"; + eType = 0; } //=========================================================================== @@ -3414,16 +3650,18 @@ StdTreeSyncView::StdTreeSyncView() TREEVIEW_CMD_DEF(SyncSelection) StdTreeSyncSelection::StdTreeSyncSelection() - : Command("Std_TreeSyncSelection") + : Command("Std_TreeSyncSelection") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&2 Sync Selection"); - sToolTipText = QT_TR_NOOP("Expands the tree item when the corresponding object is selected in the 3D view"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TreeSyncSelection"; - sPixmap = "tree-sync-sel"; - sAccel = "T,2"; - eType = 0; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&2 Sync Selection"); + sToolTipText = QT_TR_NOOP( + "Expands the tree item when the corresponding object is selected in the 3D view" + ); + sStatusTip = sToolTipText; + sWhatsThis = "Std_TreeSyncSelection"; + sPixmap = "tree-sync-sel"; + sAccel = "T,2"; + eType = 0; } //=========================================================================== @@ -3432,16 +3670,17 @@ StdTreeSyncSelection::StdTreeSyncSelection() TREEVIEW_CMD_DEF(SyncPlacement) StdTreeSyncPlacement::StdTreeSyncPlacement() - : Command("Std_TreeSyncPlacement") + : Command("Std_TreeSyncPlacement") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&3 Sync Placement"); - sToolTipText = QT_TR_NOOP("Adjusts the placement on drag-and-drop of objects across coordinate systems (e.g. in part containers)"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TreeSyncPlacement"; - sPixmap = "tree-sync-pla"; - sAccel = "T,3"; - eType = 0; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&3 Sync Placement"); + sToolTipText + = QT_TR_NOOP("Adjusts the placement on drag-and-drop of objects across coordinate systems (e.g. in part containers)"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_TreeSyncPlacement"; + sPixmap = "tree-sync-pla"; + sAccel = "T,3"; + eType = 0; } //=========================================================================== @@ -3450,16 +3689,18 @@ StdTreeSyncPlacement::StdTreeSyncPlacement() TREEVIEW_CMD_DEF(PreSelection) StdTreePreSelection::StdTreePreSelection() - : Command("Std_TreePreSelection") + : Command("Std_TreePreSelection") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&4 Preselection"); - sToolTipText = QT_TR_NOOP("Preselects the object in 3D view when hovering the cursor over the tree item"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TreePreSelection"; - sPixmap = "tree-pre-sel"; - sAccel = "T,4"; - eType = 0; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&4 Preselection"); + sToolTipText = QT_TR_NOOP( + "Preselects the object in 3D view when hovering the cursor over the tree item" + ); + sStatusTip = sToolTipText; + sWhatsThis = "Std_TreePreSelection"; + sPixmap = "tree-pre-sel"; + sAccel = "T,4"; + eType = 0; } //=========================================================================== @@ -3468,16 +3709,17 @@ StdTreePreSelection::StdTreePreSelection() TREEVIEW_CMD_DEF(RecordSelection) StdTreeRecordSelection::StdTreeRecordSelection() - : Command("Std_TreeRecordSelection") + : Command("Std_TreeRecordSelection") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("&5 Record Selection"); - sToolTipText = QT_TR_NOOP("Records the selection in the tree view in order to go back/forward using the navigation buttons"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TreeRecordSelection"; - sPixmap = "tree-rec-sel"; - sAccel = "T,5"; - eType = 0; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("&5 Record Selection"); + sToolTipText + = QT_TR_NOOP("Records the selection in the tree view in order to go back/forward using the navigation buttons"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_TreeRecordSelection"; + sPixmap = "tree-rec-sel"; + sAccel = "T,5"; + eType = 0; } //=========================================================================== @@ -3486,24 +3728,24 @@ StdTreeRecordSelection::StdTreeRecordSelection() DEF_STD_CMD(StdTreeDrag) StdTreeDrag::StdTreeDrag() - : Command("Std_TreeDrag") + : Command("Std_TreeDrag") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("Initiate &Dragging"); + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("Initiate &Dragging"); sToolTipText = QT_TR_NOOP("Initiates dragging of the currently selected tree items"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_TreeDrag"; - sPixmap = "tree-item-drag"; - sAccel = "T,D"; - eType = 0; + sStatusTip = sToolTipText; + sWhatsThis = "Std_TreeDrag"; + sPixmap = "tree-item-drag"; + sAccel = "T,D"; + eType = 0; } void StdTreeDrag::activated(int) { - if(Gui::Selection().hasSelection()) { + if (Gui::Selection().hasSelection()) { const auto trees = getMainWindow()->findChildren(); - for(auto tree : trees) { - if(tree->isVisible()) { + for (auto tree : trees) { + if (tree->isVisible()) { tree->startDragging(); break; } @@ -3515,19 +3757,19 @@ void StdTreeDrag::activated(int) // Std_TreeViewActions //=========================================================================== // -class StdCmdTreeViewActions : public GroupCommand +class StdCmdTreeViewActions: public GroupCommand { public: StdCmdTreeViewActions() - :GroupCommand("Std_TreeViewActions") + : GroupCommand("Std_TreeViewActions") { - sGroup = "TreeView"; - sMenuText = QT_TR_NOOP("Tree View Actions"); - sToolTipText = QT_TR_NOOP("Tree view behavior options and actions"); - sWhatsThis = "Std_TreeViewActions"; - sStatusTip = sToolTipText; - eType = 0; - bCanLog = false; + sGroup = "TreeView"; + sMenuText = QT_TR_NOOP("Tree View Actions"); + sToolTipText = QT_TR_NOOP("Tree view behavior options and actions"); + sWhatsThis = "Std_TreeViewActions"; + sStatusTip = sToolTipText; + eType = 0; + bCanLog = false; addCommand(new StdTreeSyncView()); addCommand(new StdTreeSyncSelection()); @@ -3543,15 +3785,18 @@ public: addCommand(); - addCommand(new StdTreeDrag(),!cmds.empty()); - addCommand(new StdTreeSelection(),!cmds.empty()); + addCommand(new StdTreeDrag(), !cmds.empty()); + addCommand(new StdTreeSelection(), !cmds.empty()); addCommand(); addCommand(new StdCmdSelBack()); addCommand(new StdCmdSelForward()); } - const char* className() const override {return "StdCmdTreeViewActions";} + const char* className() const override + { + return "StdCmdTreeViewActions"; + } }; @@ -3561,40 +3806,42 @@ public: DEF_STD_CMD_AC(StdCmdSelBoundingBox) StdCmdSelBoundingBox::StdCmdSelBoundingBox() - :Command("Std_SelBoundingBox") + : Command("Std_SelBoundingBox") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Bounding Box"); - sToolTipText = QT_TR_NOOP("Shows selection bounding box"); - sWhatsThis = "Std_SelBoundingBox"; - sStatusTip = sToolTipText; - sPixmap = "sel-bbox"; - eType = Alter3DView; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Bounding Box"); + sToolTipText = QT_TR_NOOP("Shows selection bounding box"); + sWhatsThis = "Std_SelBoundingBox"; + sStatusTip = sToolTipText; + sPixmap = "sel-bbox"; + eType = Alter3DView; } void StdCmdSelBoundingBox::activated(int iMsg) { bool checked = !!iMsg; - if(checked != ViewParams::instance()->getShowSelectionBoundingBox()) { + if (checked != ViewParams::instance()->getShowSelectionBoundingBox()) { ViewParams::instance()->setShowSelectionBoundingBox(checked); - if(_pcAction) + if (_pcAction) { _pcAction->setBlockedChecked(checked); + } } } bool StdCmdSelBoundingBox::isActive() { - if(_pcAction) { + if (_pcAction) { bool checked = _pcAction->isChecked(); - if(checked != ViewParams::instance()->getShowSelectionBoundingBox()) + if (checked != ViewParams::instance()->getShowSelectionBoundingBox()) { _pcAction->setBlockedChecked(!checked); + } } return true; } -Action * StdCmdSelBoundingBox::createAction() +Action* StdCmdSelBoundingBox::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); pcAction->setCheckable(true); return pcAction; } @@ -3606,15 +3853,15 @@ Action * StdCmdSelBoundingBox::createAction() DEF_STD_CMD(StdCmdDockOverlayAll) StdCmdDockOverlayAll::StdCmdDockOverlayAll() - :Command("Std_DockOverlayAll") + : Command("Std_DockOverlayAll") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Toggle Overl&ay for All Panels"); - sToolTipText = QT_TR_NOOP("Toggled overlay mode for all docked panels"); - sWhatsThis = "Std_DockOverlayAll"; - sStatusTip = sToolTipText; - sAccel = "F4"; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Toggle Overl&ay for All Panels"); + sToolTipText = QT_TR_NOOP("Toggled overlay mode for all docked panels"); + sWhatsThis = "Std_DockOverlayAll"; + sStatusTip = sToolTipText; + sAccel = "F4"; + eType = 0; } void StdCmdDockOverlayAll::activated(int iMsg) @@ -3630,16 +3877,18 @@ void StdCmdDockOverlayAll::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayTransparentAll) StdCmdDockOverlayTransparentAll::StdCmdDockOverlayTransparentAll() - :Command("Std_DockOverlayTransparentAll") + : Command("Std_DockOverlayTransparentAll") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Toggle Tra&nsparent Panels"); - sToolTipText = QT_TR_NOOP("Toggles transparent mode for all docked overlay panels.\n" - "This makes the docked panels stay transparent at all times."); - sWhatsThis = "Std_DockOverlayTransparentAll"; - sStatusTip = sToolTipText; - sAccel = "SHIFT+F4"; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Toggle Tra&nsparent Panels"); + sToolTipText = QT_TR_NOOP( + "Toggles transparent mode for all docked overlay panels.\n" + "This makes the docked panels stay transparent at all times." + ); + sWhatsThis = "Std_DockOverlayTransparentAll"; + sStatusTip = sToolTipText; + sAccel = "SHIFT+F4"; + eType = 0; } void StdCmdDockOverlayTransparentAll::activated(int iMsg) @@ -3655,15 +3904,15 @@ void StdCmdDockOverlayTransparentAll::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayToggle) StdCmdDockOverlayToggle::StdCmdDockOverlayToggle() - :Command("Std_DockOverlayToggle") + : Command("Std_DockOverlayToggle") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Toggle &Overlay"); - sToolTipText = QT_TR_NOOP("Toggles overlay mode for the docked window under the cursor"); - sWhatsThis = "Std_DockOverlayToggle"; - sStatusTip = sToolTipText; - sAccel = "F3"; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Toggle &Overlay"); + sToolTipText = QT_TR_NOOP("Toggles overlay mode for the docked window under the cursor"); + sWhatsThis = "Std_DockOverlayToggle"; + sStatusTip = sToolTipText; + sAccel = "F3"; + eType = 0; } void StdCmdDockOverlayToggle::activated(int iMsg) @@ -3679,16 +3928,18 @@ void StdCmdDockOverlayToggle::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayToggleTransparent) StdCmdDockOverlayToggleTransparent::StdCmdDockOverlayToggleTransparent() - :Command("Std_DockOverlayToggleTransparent") + : Command("Std_DockOverlayToggleTransparent") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle Tran&sparent Mode"); - sToolTipText = QT_TR_NOOP("Toggles transparent mode for the docked panel under cursor.\n" - "This makes the docked panel stay transparent at all times."); - sWhatsThis = "Std_DockOverlayToggleTransparent"; - sStatusTip = sToolTipText; - sAccel = "SHIFT+F3"; - eType = 0; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle Tran&sparent Mode"); + sToolTipText = QT_TR_NOOP( + "Toggles transparent mode for the docked panel under cursor.\n" + "This makes the docked panel stay transparent at all times." + ); + sWhatsThis = "Std_DockOverlayToggleTransparent"; + sStatusTip = sToolTipText; + sAccel = "SHIFT+F3"; + eType = 0; } void StdCmdDockOverlayToggleTransparent::activated(int iMsg) @@ -3704,16 +3955,16 @@ void StdCmdDockOverlayToggleTransparent::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayToggleLeft) StdCmdDockOverlayToggleLeft::StdCmdDockOverlayToggleLeft() - :Command("Std_DockOverlayToggleLeft") + : Command("Std_DockOverlayToggleLeft") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle &Left"); - sToolTipText = QT_TR_NOOP("Toggles the visibility of the left overlay panel"); - sWhatsThis = "Std_DockOverlayToggleLeft"; - sStatusTip = sToolTipText; - sAccel = "Ctrl+Left"; - sPixmap = "Std_DockOverlayToggleLeft"; - eType = 0; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle &Left"); + sToolTipText = QT_TR_NOOP("Toggles the visibility of the left overlay panel"); + sWhatsThis = "Std_DockOverlayToggleLeft"; + sStatusTip = sToolTipText; + sAccel = "Ctrl+Left"; + sPixmap = "Std_DockOverlayToggleLeft"; + eType = 0; } void StdCmdDockOverlayToggleLeft::activated(int iMsg) @@ -3729,16 +3980,16 @@ void StdCmdDockOverlayToggleLeft::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayToggleRight) StdCmdDockOverlayToggleRight::StdCmdDockOverlayToggleRight() - :Command("Std_DockOverlayToggleRight") + : Command("Std_DockOverlayToggleRight") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle &Right"); - sToolTipText = QT_TR_NOOP("Toggles the visibility of the right overlay panel"); - sWhatsThis = "Std_DockOverlayToggleRight"; - sStatusTip = sToolTipText; - sAccel = "Ctrl+Right"; - sPixmap = "Std_DockOverlayToggleRight"; - eType = 0; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle &Right"); + sToolTipText = QT_TR_NOOP("Toggles the visibility of the right overlay panel"); + sWhatsThis = "Std_DockOverlayToggleRight"; + sStatusTip = sToolTipText; + sAccel = "Ctrl+Right"; + sPixmap = "Std_DockOverlayToggleRight"; + eType = 0; } void StdCmdDockOverlayToggleRight::activated(int iMsg) @@ -3754,16 +4005,16 @@ void StdCmdDockOverlayToggleRight::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayToggleTop) StdCmdDockOverlayToggleTop::StdCmdDockOverlayToggleTop() - :Command("Std_DockOverlayToggleTop") + : Command("Std_DockOverlayToggleTop") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle &Top"); - sToolTipText = QT_TR_NOOP("Toggles the visibility of the top overlay panel"); - sWhatsThis = "Std_DockOverlayToggleTop"; - sStatusTip = sToolTipText; - sAccel = "Ctrl+Up"; - sPixmap = "Std_DockOverlayToggleTop"; - eType = 0; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle &Top"); + sToolTipText = QT_TR_NOOP("Toggles the visibility of the top overlay panel"); + sWhatsThis = "Std_DockOverlayToggleTop"; + sStatusTip = sToolTipText; + sAccel = "Ctrl+Up"; + sPixmap = "Std_DockOverlayToggleTop"; + eType = 0; } void StdCmdDockOverlayToggleTop::activated(int iMsg) @@ -3779,16 +4030,16 @@ void StdCmdDockOverlayToggleTop::activated(int iMsg) DEF_STD_CMD(StdCmdDockOverlayToggleBottom) StdCmdDockOverlayToggleBottom::StdCmdDockOverlayToggleBottom() - :Command("Std_DockOverlayToggleBottom") + : Command("Std_DockOverlayToggleBottom") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle &Bottom"); - sToolTipText = QT_TR_NOOP("Toggles the visibility of the bottom overlay panel"); - sWhatsThis = "Std_DockOverlayToggleBottom"; - sStatusTip = sToolTipText; - sAccel = "Ctrl+Down"; - sPixmap = "Std_DockOverlayToggleBottom"; - eType = 0; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Toggle &Bottom"); + sToolTipText = QT_TR_NOOP("Toggles the visibility of the bottom overlay panel"); + sWhatsThis = "Std_DockOverlayToggleBottom"; + sStatusTip = sToolTipText; + sAccel = "Ctrl+Down"; + sPixmap = "Std_DockOverlayToggleBottom"; + eType = 0; } void StdCmdDockOverlayToggleBottom::activated(int iMsg) @@ -3804,15 +4055,15 @@ void StdCmdDockOverlayToggleBottom::activated(int iMsg) DEF_STD_CMD_AC(StdCmdDockOverlayMouseTransparent) StdCmdDockOverlayMouseTransparent::StdCmdDockOverlayMouseTransparent() - :Command("Std_DockOverlayMouseTransparent") + : Command("Std_DockOverlayMouseTransparent") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Bypass &Mouse Events in Overlay Panels"); - sToolTipText = QT_TR_NOOP("Bypasses all mouse events in docked overlay panels"); - sWhatsThis = "Std_DockOverlayMouseTransparent"; - sStatusTip = sToolTipText; - sAccel = "T, T"; - eType = NoTransaction; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Bypass &Mouse Events in Overlay Panels"); + sToolTipText = QT_TR_NOOP("Bypasses all mouse events in docked overlay panels"); + sWhatsThis = "Std_DockOverlayMouseTransparent"; + sStatusTip = sToolTipText; + sAccel = "T, T"; + eType = NoTransaction; } void StdCmdDockOverlayMouseTransparent::activated(int iMsg) @@ -3820,12 +4071,14 @@ void StdCmdDockOverlayMouseTransparent::activated(int iMsg) (void)iMsg; bool checked = !OverlayManager::instance()->isMouseTransparent(); OverlayManager::instance()->setMouseTransparent(checked); - if(_pcAction) + if (_pcAction) { _pcAction->setBlockedChecked(checked); + } } -Action * StdCmdDockOverlayMouseTransparent::createAction() { - Action *pcAction = Command::createAction(); +Action* StdCmdDockOverlayMouseTransparent::createAction() +{ + Action* pcAction = Command::createAction(); pcAction->setCheckable(true); pcAction->setIcon(QIcon()); _pcAction = pcAction; @@ -3833,28 +4086,30 @@ Action * StdCmdDockOverlayMouseTransparent::createAction() { return pcAction; } -bool StdCmdDockOverlayMouseTransparent::isActive() { +bool StdCmdDockOverlayMouseTransparent::isActive() +{ bool checked = OverlayManager::instance()->isMouseTransparent(); - if(_pcAction && _pcAction->isChecked()!=checked) + if (_pcAction && _pcAction->isChecked() != checked) { _pcAction->setBlockedChecked(checked); + } return true; } // ============================================================================ -class StdCmdDockOverlay : public GroupCommand +class StdCmdDockOverlay: public GroupCommand { public: StdCmdDockOverlay() - :GroupCommand("Std_DockOverlay") + : GroupCommand("Std_DockOverlay") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Overlay Docked Panel"); - sToolTipText = QT_TR_NOOP("Sets the docked panel in overlay mode"); - sWhatsThis = "Std_DockOverlay"; - sStatusTip = sToolTipText; - eType = 0; - bCanLog = false; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Overlay Docked Panel"); + sToolTipText = QT_TR_NOOP("Sets the docked panel in overlay mode"); + sWhatsThis = "Std_DockOverlay"; + sStatusTip = sToolTipText; + eType = 0; + bCanLog = false; addCommand(new StdCmdDockOverlayAll()); addCommand(new StdCmdDockOverlayTransparentAll()); @@ -3869,7 +4124,10 @@ public: addCommand(new StdCmdDockOverlayToggleTop()); addCommand(new StdCmdDockOverlayToggleBottom()); }; - virtual const char* className() const {return "StdCmdDockOverlay";} + virtual const char* className() const + { + return "StdCmdDockOverlay"; + } }; //=========================================================================== @@ -3878,15 +4136,15 @@ public: DEF_STD_CMD_A(StdStoreWorkingView) StdStoreWorkingView::StdStoreWorkingView() - : Command("Std_StoreWorkingView") + : Command("Std_StoreWorkingView") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("St&ore Working View"); - sToolTipText = QT_TR_NOOP("Stores a temporary working view for the current document"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_StoreWorkingView"; - sAccel = "Shift+End"; - eType = NoTransaction; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("St&ore Working View"); + sToolTipText = QT_TR_NOOP("Stores a temporary working view for the current document"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_StoreWorkingView"; + sAccel = "Shift+End"; + eType = NoTransaction; } void StdStoreWorkingView::activated(int iMsg) @@ -3908,23 +4166,24 @@ bool StdStoreWorkingView::isActive() DEF_STD_CMD_A(StdRecallWorkingView) StdRecallWorkingView::StdRecallWorkingView() - : Command("Std_RecallWorkingView") + : Command("Std_RecallWorkingView") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("R&ecall Working View"); - sToolTipText = QT_TR_NOOP("Recalls a previously stored temporary working view"); - sStatusTip = sToolTipText; - sWhatsThis = "Std_RecallWorkingView"; - sAccel = "End"; - eType = NoTransaction; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("R&ecall Working View"); + sToolTipText = QT_TR_NOOP("Recalls a previously stored temporary working view"); + sStatusTip = sToolTipText; + sWhatsThis = "Std_RecallWorkingView"; + sAccel = "End"; + eType = NoTransaction; } void StdRecallWorkingView::activated(int iMsg) { Q_UNUSED(iMsg); if (auto view = dynamic_cast(Gui::getMainWindow()->activeWindow())) { - if (view->getViewer()->hasHomePosition()) + if (view->getViewer()->hasHomePosition()) { view->getViewer()->resetToHomePosition(); + } } } @@ -3940,20 +4199,20 @@ bool StdRecallWorkingView::isActive() DEF_STD_CMD_A(StdCmdAlignToSelection) StdCmdAlignToSelection::StdCmdAlignToSelection() - : Command("Std_AlignToSelection") + : Command("Std_AlignToSelection") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Align to Selection"); - sToolTipText = QT_TR_NOOP("Aligns the camera view to the selected elements in the 3D view"); - sWhatsThis = "Std_AlignToSelection"; - sPixmap = "align-to-selection"; - eType = Alter3DView; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Align to Selection"); + sToolTipText = QT_TR_NOOP("Aligns the camera view to the selected elements in the 3D view"); + sWhatsThis = "Std_AlignToSelection"; + sPixmap = "align-to-selection"; + eType = Alter3DView; } void StdCmdAlignToSelection::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"AlignToSelection\")"); + doCommand(Command::Gui, "Gui.SendMsgToActiveView(\"AlignToSelection\")"); } bool StdCmdAlignToSelection::isActive() @@ -3968,23 +4227,25 @@ bool StdCmdAlignToSelection::isActive() DEF_STD_CMD_A(StdCmdClarifySelection) StdCmdClarifySelection::StdCmdClarifySelection() - : Command("Std_ClarifySelection") + : Command("Std_ClarifySelection") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Clarify Selection"); - sToolTipText = QT_TR_NOOP("Displays a context menu at the mouse cursor to select overlapping " - "or obstructed geometry in the 3D view.\n"); - sWhatsThis = "Std_ClarifySelection"; - sStatusTip = sToolTipText; - sAccel = "G, G"; - eType = NoTransaction | AlterSelection; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Clarify Selection"); + sToolTipText = QT_TR_NOOP( + "Displays a context menu at the mouse cursor to select overlapping " + "or obstructed geometry in the 3D view.\n" + ); + sWhatsThis = "Std_ClarifySelection"; + sStatusTip = sToolTipText; + sAccel = "G, G"; + eType = NoTransaction | AlterSelection; } void StdCmdClarifySelection::activated(int iMsg) { Q_UNUSED(iMsg); - - // Get the active view + + // Get the active view auto view3d = freecad_cast(Application::Instance->activeView()); if (!view3d) { return; @@ -4000,58 +4261,63 @@ void StdCmdClarifySelection::activated(int iMsg) return; } - // check if we have a stored right-click position (context menu) or should use current cursor position (keyboard shortcut) + // check if we have a stored right-click position (context menu) or should use current cursor + // position (keyboard shortcut) SbVec2s point; auto& storedPosition = viewer->navigationStyle()->getRightClickPosition(); if (storedPosition.has_value()) { point = storedPosition.value(); - } else { + } + else { QPoint pos = QCursor::pos(); QPoint local = widget->mapFromGlobal(pos); qreal devicePixelRatio = widget->devicePixelRatioF(); - point = SbVec2s(static_cast(local.x() * devicePixelRatio), - static_cast((widget->height() - local.y() - 1) * devicePixelRatio)); + point = SbVec2s( + static_cast(local.x() * devicePixelRatio), + static_cast((widget->height() - local.y() - 1) * devicePixelRatio) + ); } - + // Use ray picking to get all objects under cursor SoRayPickAction pickAction(viewer->getSoRenderManager()->getViewportRegion()); pickAction.setPoint(point); constexpr double defaultMultiplier = 5.0F; - double clarifyRadiusMultiplier = App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetFloat("ClarifySelectionRadiusMultiplier", defaultMultiplier); + double clarifyRadiusMultiplier + = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetFloat("ClarifySelectionRadiusMultiplier", defaultMultiplier); pickAction.setRadius(viewer->getPickRadius() * clarifyRadiusMultiplier); pickAction.setPickAll(static_cast(true)); // Get all objects under cursor pickAction.apply(viewer->getSoRenderManager()->getSceneGraph()); - + const SoPickedPointList& pplist = pickAction.getPickedPointList(); if (pplist.getLength() == 0) { return; } - + // Convert picked points to PickData list std::vector selections; - + for (int i = 0; i < pplist.getLength(); ++i) { SoPickedPoint* pp = pplist[i]; if (!pp || !pp->getPath()) { continue; } - + ViewProvider* vp = viewer->getViewProviderByPath(pp->getPath()); if (!vp) { continue; } - + // Cast to ViewProviderDocumentObject to get the object auto vpDoc = freecad_cast(vp); if (!vpDoc) { continue; } - + App::DocumentObject* obj = vpDoc->getObject(); if (!obj) { continue; @@ -4060,35 +4326,40 @@ void StdCmdClarifySelection::activated(int iMsg) // Get element information - handle sub-objects like Assembly parts std::string elementName = vp->getElement(pp->getDetail()); std::string subName; - + // Try to get more detailed sub-object information bool hasSubObject = false; if (vp->getElementPicked(pp, subName)) { hasSubObject = true; } - + // Create PickData with selection information - PickData pickData {.obj = obj, - .element = elementName, - .docName = obj->getDocument()->getName(), - .objName = obj->getNameInDocument(), - .subName = hasSubObject ? subName : elementName}; - + PickData pickData { + .obj = obj, + .element = elementName, + .docName = obj->getDocument()->getName(), + .objName = obj->getNameInDocument(), + .subName = hasSubObject ? subName : elementName + }; + selections.push_back(pickData); } - + if (selections.empty()) { return; } - + QPoint globalPos; if (storedPosition.has_value()) { qreal devicePixelRatio = widget->devicePixelRatioF(); int logicalHeight = static_cast(widget->height()); - QPoint localPos(static_cast(point[0] / devicePixelRatio), - logicalHeight - static_cast(point[1] / devicePixelRatio) - 1); + QPoint localPos( + static_cast(point[0] / devicePixelRatio), + logicalHeight - static_cast(point[1] / devicePixelRatio) - 1 + ); globalPos = widget->mapToGlobal(localPos); - } else { + } + else { globalPos = QCursor::pos(); } @@ -4107,12 +4378,13 @@ bool StdCmdClarifySelection::isActive() //=========================================================================== -namespace Gui { +namespace Gui +{ void CreateViewStdCommands() { // NOLINTBEGIN - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); // views rcCmdMgr.addCommand(new StdCmdViewBottom()); @@ -4186,12 +4458,16 @@ void CreateViewStdCommands() rcCmdMgr.addCommand(new StdCmdTreeViewActions()); rcCmdMgr.addCommand(new StdCmdDockOverlay()); - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - if(hGrp->GetASCII("GestureRollFwdCommand").empty()) - hGrp->SetASCII("GestureRollFwdCommand","Std_SelForward"); - if(hGrp->GetASCII("GestureRollBackCommand").empty()) - hGrp->SetASCII("GestureRollBackCommand","Std_SelBack"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + if (hGrp->GetASCII("GestureRollFwdCommand").empty()) { + hGrp->SetASCII("GestureRollFwdCommand", "Std_SelForward"); + } + if (hGrp->GetASCII("GestureRollBackCommand").empty()) { + hGrp->SetASCII("GestureRollBackCommand", "Std_SelBack"); + } // NOLINTEND } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/CommandWindow.cpp b/src/Gui/CommandWindow.cpp index 836e97398a..994b284f86 100644 --- a/src/Gui/CommandWindow.cpp +++ b/src/Gui/CommandWindow.cpp @@ -20,9 +20,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "Command.h" #include "Action.h" @@ -46,15 +46,15 @@ using namespace Gui; DEF_STD_CMD_A(StdCmdTileWindows) StdCmdTileWindows::StdCmdTileWindows() - : Command("Std_TileWindows") + : Command("Std_TileWindows") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("&Tile"); - sToolTipText = QT_TR_NOOP("Tiles the windows"); - sWhatsThis = "Std_TileWindows"; - sStatusTip = sToolTipText; - sPixmap = "Std_WindowTileVer"; - eType = 0; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("&Tile"); + sToolTipText = QT_TR_NOOP("Tiles the windows"); + sWhatsThis = "Std_TileWindows"; + sStatusTip = sToolTipText; + sPixmap = "Std_WindowTileVer"; + eType = 0; } void StdCmdTileWindows::activated(int iMsg) @@ -74,15 +74,15 @@ bool StdCmdTileWindows::isActive() DEF_STD_CMD_A(StdCmdCascadeWindows) StdCmdCascadeWindows::StdCmdCascadeWindows() - : Command("Std_CascadeWindows") + : Command("Std_CascadeWindows") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("&Cascade"); - sToolTipText = QT_TR_NOOP("Tiles pragmatic"); - sWhatsThis = "Std_CascadeWindows"; - sStatusTip = sToolTipText; - sPixmap = "Std_WindowCascade"; - eType = 0; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("&Cascade"); + sToolTipText = QT_TR_NOOP("Tiles pragmatic"); + sWhatsThis = "Std_CascadeWindows"; + sStatusTip = sToolTipText; + sPixmap = "Std_WindowCascade"; + eType = 0; } void StdCmdCascadeWindows::activated(int iMsg) @@ -102,19 +102,19 @@ bool StdCmdCascadeWindows::isActive() DEF_STD_CMD_A(StdCmdCloseActiveWindow) StdCmdCloseActiveWindow::StdCmdCloseActiveWindow() - : Command("Std_CloseActiveWindow") + : Command("Std_CloseActiveWindow") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("&Close"); - sToolTipText = QT_TR_NOOP("Closes the active window"); - sWhatsThis = "Std_CloseActiveWindow"; - sStatusTip = sToolTipText; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("&Close"); + sToolTipText = QT_TR_NOOP("Closes the active window"); + sWhatsThis = "Std_CloseActiveWindow"; + sStatusTip = sToolTipText; // In QMdiSubWindow the 'QKeySequence::Close' shortcut is set which will // collide with this shortcut. Thus the shortcut of QMdiSubWindow will be // reset in MainWindow::addWindow() (#0002631) - sAccel = keySequenceToAccel(QKeySequence::Close); - sPixmap = "Std_CloseActiveWindow"; - eType = NoTransaction; + sAccel = keySequenceToAccel(QKeySequence::Close); + sPixmap = "Std_CloseActiveWindow"; + eType = NoTransaction; } void StdCmdCloseActiveWindow::activated(int iMsg) @@ -134,15 +134,15 @@ bool StdCmdCloseActiveWindow::isActive() DEF_STD_CMD_A(StdCmdCloseAllWindows) StdCmdCloseAllWindows::StdCmdCloseAllWindows() - : Command("Std_CloseAllWindows") + : Command("Std_CloseAllWindows") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("Close A&ll"); - sToolTipText = QT_TR_NOOP("Closes all windows"); - sWhatsThis = "Std_CloseAllWindows"; - sStatusTip = sToolTipText; - sPixmap = "Std_CloseAllWindows"; - eType = NoTransaction; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("Close A&ll"); + sToolTipText = QT_TR_NOOP("Closes all windows"); + sWhatsThis = "Std_CloseAllWindows"; + sStatusTip = sToolTipText; + sPixmap = "Std_CloseAllWindows"; + eType = NoTransaction; } void StdCmdCloseAllWindows::activated(int iMsg) @@ -162,16 +162,16 @@ bool StdCmdCloseAllWindows::isActive() DEF_STD_CMD_A(StdCmdActivateNextWindow) StdCmdActivateNextWindow::StdCmdActivateNextWindow() - : Command("Std_ActivateNextWindow") + : Command("Std_ActivateNextWindow") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("&Next"); - sToolTipText = QT_TR_NOOP("Activates the next window"); - sWhatsThis = "Std_ActivateNextWindow"; - sStatusTip = sToolTipText; - sPixmap = "Std_WindowNext"; - sAccel = keySequenceToAccel(QKeySequence::NextChild); - eType = 0; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("&Next"); + sToolTipText = QT_TR_NOOP("Activates the next window"); + sWhatsThis = "Std_ActivateNextWindow"; + sStatusTip = sToolTipText; + sPixmap = "Std_WindowNext"; + sAccel = keySequenceToAccel(QKeySequence::NextChild); + eType = 0; } void StdCmdActivateNextWindow::activated(int iMsg) @@ -191,21 +191,22 @@ bool StdCmdActivateNextWindow::isActive() DEF_STD_CMD_A(StdCmdActivatePrevWindow) StdCmdActivatePrevWindow::StdCmdActivatePrevWindow() - : Command("Std_ActivatePrevWindow") + : Command("Std_ActivatePrevWindow") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("&Previous"); - sToolTipText = QT_TR_NOOP("Switches to the previously active window"); - sWhatsThis = "Std_ActivatePrevWindow"; - sStatusTip = sToolTipText; - sPixmap = "Std_WindowPrev"; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("&Previous"); + sToolTipText = QT_TR_NOOP("Switches to the previously active window"); + sWhatsThis = "Std_ActivatePrevWindow"; + sStatusTip = sToolTipText; + sPixmap = "Std_WindowPrev"; // Depending on the OS 'QKeySequence::PreviousChild' gives // Ctrl+Shift+Backtab instead of Ctrl+Shift+Tab which leads // to a strange behaviour when using it. // A workaround is to create a shortcut as Shift + QKeySequence::NextChild - static std::string previousChild = std::string("Shift+") + keySequenceToAccel(QKeySequence::NextChild); - sAccel = previousChild.c_str(); - eType = 0; + static std::string previousChild = std::string("Shift+") + + keySequenceToAccel(QKeySequence::NextChild); + sAccel = previousChild.c_str(); + eType = 0; } void StdCmdActivatePrevWindow::activated(int iMsg) @@ -225,22 +226,22 @@ bool StdCmdActivatePrevWindow::isActive() DEF_STD_CMD(StdCmdWindows) StdCmdWindows::StdCmdWindows() - : Command("Std_Windows") + : Command("Std_Windows") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("Choose Open &Window"); + sGroup = "Window"; + sMenuText = QT_TR_NOOP("Choose Open &Window"); - sToolTipText = QT_TR_NOOP("Displays the open windows"); - sWhatsThis = "Std_Windows"; - sStatusTip = sToolTipText; - sPixmap = "Std_Windows"; - eType = 0; + sToolTipText = QT_TR_NOOP("Displays the open windows"); + sWhatsThis = "Std_Windows"; + sStatusTip = sToolTipText; + sPixmap = "Std_Windows"; + eType = 0; } void StdCmdWindows::activated(int iMsg) { Q_UNUSED(iMsg); - Gui::Dialog::DlgActivateWindowImp dlg( getMainWindow() ); + Gui::Dialog::DlgActivateWindowImp dlg(getMainWindow()); dlg.exec(); } @@ -250,14 +251,14 @@ void StdCmdWindows::activated(int iMsg) DEF_STD_CMD(StdCmdUserInterface) StdCmdUserInterface::StdCmdUserInterface() - : Command("Std_UserInterface") + : Command("Std_UserInterface") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Dock Views"); - sToolTipText = QT_TR_NOOP("Docks all top-level views"); - sWhatsThis = "Std_UserInterface"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Dock Views"); + sToolTipText = QT_TR_NOOP("Docks all top-level views"); + sWhatsThis = "Std_UserInterface"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdUserInterface::activated(int) @@ -272,14 +273,14 @@ void StdCmdUserInterface::activated(int) DEF_STD_CMD_AC(StdCmdDockViewMenu) StdCmdDockViewMenu::StdCmdDockViewMenu() - : Command("Std_DockViewMenu") + : Command("Std_DockViewMenu") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Panels"); - sToolTipText = QT_TR_NOOP("Lists available dock panels"); - sWhatsThis = "Std_DockViewMenu"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Panels"); + sToolTipText = QT_TR_NOOP("Lists available dock panels"); + sWhatsThis = "Std_DockViewMenu"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdDockViewMenu::activated(int iMsg) @@ -293,9 +294,9 @@ bool StdCmdDockViewMenu::isActive() return true; } -Action * StdCmdDockViewMenu::createAction() +Action* StdCmdDockViewMenu::createAction() { - Action *pcAction; + Action* pcAction; pcAction = new DockWidgetAction(this, getMainWindow()); applyCommandData(this->className(), pcAction); return pcAction; @@ -308,14 +309,14 @@ Action * StdCmdDockViewMenu::createAction() DEF_STD_CMD_AC(StdCmdToolBarMenu) StdCmdToolBarMenu::StdCmdToolBarMenu() - : Command("Std_ToolBarMenu") + : Command("Std_ToolBarMenu") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("&Toolbars"); - sToolTipText = QT_TR_NOOP("Toggles this window"); - sWhatsThis = "Std_ToolBarMenu"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("&Toolbars"); + sToolTipText = QT_TR_NOOP("Toggles this window"); + sWhatsThis = "Std_ToolBarMenu"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdToolBarMenu::activated(int iMsg) @@ -329,9 +330,9 @@ bool StdCmdToolBarMenu::isActive() return true; } -Action * StdCmdToolBarMenu::createAction() +Action* StdCmdToolBarMenu::createAction() { - Action *pcAction; + Action* pcAction; pcAction = new ToolBarAction(this, getMainWindow()); applyCommandData(this->className(), pcAction); return pcAction; @@ -343,14 +344,14 @@ Action * StdCmdToolBarMenu::createAction() DEF_STD_CMD_C(StdCmdToggleToolBarLock) StdCmdToggleToolBarLock::StdCmdToggleToolBarLock() - :Command("Std_ToggleToolBarLock") + : Command("Std_ToggleToolBarLock") { - sGroup = "Tools"; - sMenuText = QT_TR_NOOP("Lock Toolbars"); - sToolTipText = QT_TR_NOOP("Locks toolbars so they are no longer moveable"); - sWhatsThis = "Std_ToggleToolBarLock"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "Tools"; + sMenuText = QT_TR_NOOP("Lock Toolbars"); + sToolTipText = QT_TR_NOOP("Locks toolbars so they are no longer moveable"); + sWhatsThis = "Std_ToggleToolBarLock"; + sStatusTip = sToolTipText; + eType = 0; } @@ -381,19 +382,24 @@ void StdCmdToggleToolBarLock::activated(int iMsg) // Std_ViewStatusBar //=========================================================================== -class FilterStatusBar : public QObject +class FilterStatusBar: public QObject { -// Q_OBJECT + // Q_OBJECT public: - FilterStatusBar(Action * action):QObject(action) {this->action = action;} -// virtual ~FilterStatusBar() {} -protected: - Action * action; - bool eventFilter(QObject *obj, QEvent *event) override + FilterStatusBar(Action* action) + : QObject(action) { - if (getMainWindow() && getMainWindow()->findChild() && obj == getMainWindow()->statusBar() && - ((event->type() == QEvent::Hide) || (event->type() == QEvent::Show))) { + this->action = action; + } + // virtual ~FilterStatusBar() {} +protected: + Action* action; + bool eventFilter(QObject* obj, QEvent* event) override + { + if (getMainWindow() && getMainWindow()->findChild() + && obj == getMainWindow()->statusBar() + && ((event->type() == QEvent::Hide) || (event->type() == QEvent::Show))) { this->action->setChecked(getMainWindow()->statusBar()->isVisible()); } return false; @@ -403,19 +409,19 @@ protected: DEF_STD_CMD_AC(StdCmdStatusBar) StdCmdStatusBar::StdCmdStatusBar() - : Command("Std_ViewStatusBar") + : Command("Std_ViewStatusBar") { - sGroup = "View"; - sMenuText = QT_TR_NOOP("Status Bar"); - sToolTipText = QT_TR_NOOP("Toggles the status bar"); - sWhatsThis = "Std_ViewStatusBar"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "View"; + sMenuText = QT_TR_NOOP("Status Bar"); + sToolTipText = QT_TR_NOOP("Toggles the status bar"); + sWhatsThis = "Std_ViewStatusBar"; + sStatusTip = sToolTipText; + eType = 0; } -Action * StdCmdStatusBar::createAction() +Action* StdCmdStatusBar::createAction() { - Action *pcAction = Command::createAction(); + Action* pcAction = Command::createAction(); pcAction->setCheckable(true); pcAction->setBlockedChecked(false); auto fsb = new FilterStatusBar(pcAction); @@ -449,14 +455,14 @@ bool StdCmdStatusBar::isActive() DEF_STD_CMD_AC(StdCmdWindowsMenu) StdCmdWindowsMenu::StdCmdWindowsMenu() - : Command("Std_WindowsMenu") + : Command("Std_WindowsMenu") { - sGroup = "Window"; - sMenuText = QT_TR_NOOP("Activate Window"); // Replaced with the name of the window - sToolTipText = QT_TR_NOOP("Activates this window"); - sWhatsThis = "Std_WindowsMenu"; - sStatusTip = sToolTipText; - eType = 0; + sGroup = "Window"; + sMenuText = QT_TR_NOOP("Activate Window"); // Replaced with the name of the window + sToolTipText = QT_TR_NOOP("Activates this window"); + sWhatsThis = "Std_WindowsMenu"; + sStatusTip = sToolTipText; + eType = 0; } void StdCmdWindowsMenu::activated(int iMsg) @@ -470,21 +476,18 @@ bool StdCmdWindowsMenu::isActive() return true; } -Action * StdCmdWindowsMenu::createAction() +Action* StdCmdWindowsMenu::createAction() { // Allow one to show 10 menu items in the 'Window' menu and one separator. // If we have more windows then the user can use the 'Windows...' item. - WindowAction *pcAction; + WindowAction* pcAction; pcAction = new WindowAction(this, getMainWindow()); - for ( int i=0; i<10; i++ ) { + for (int i = 0; i < 10; i++) { QAction* window = pcAction->addAction(QObject::tr(getToolTipText())); window->setCheckable(true); - window->setToolTip(QCoreApplication::translate( - this->className(), getToolTipText())); - window->setStatusTip(QCoreApplication::translate( - this->className(), getStatusTip())); - window->setWhatsThis(QCoreApplication::translate( - this->className(), getWhatsThis())); + window->setToolTip(QCoreApplication::translate(this->className(), getToolTipText())); + window->setStatusTip(QCoreApplication::translate(this->className(), getStatusTip())); + window->setWhatsThis(QCoreApplication::translate(this->className(), getWhatsThis())); } QAction* sep = pcAction->addAction(QLatin1String("")); @@ -498,11 +501,12 @@ Action * StdCmdWindowsMenu::createAction() //=========================================================================== -namespace Gui { +namespace Gui +{ void CreateWindowStdCommands() { - CommandManager &rcCmdMgr = Application::Instance->commandManager(); + CommandManager& rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdTileWindows()); rcCmdMgr.addCommand(new StdCmdCascadeWindows()); @@ -519,4 +523,4 @@ void CreateWindowStdCommands() rcCmdMgr.addCommand(new StdCmdUserInterface()); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/Control.cpp b/src/Gui/Control.cpp index 3732dc45ab..ea1ca91c91 100644 --- a/src/Gui/Control.cpp +++ b/src/Gui/Control.cpp @@ -20,11 +20,11 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include #include @@ -45,18 +45,17 @@ using namespace std; ControlSingleton* ControlSingleton::_pcSingleton = nullptr; ControlSingleton::ControlSingleton() - : ActiveDialog(nullptr) - , oldTabIndex(-1) -{ - -} + : ActiveDialog(nullptr) + , oldTabIndex(-1) +{} ControlSingleton::~ControlSingleton() = default; Gui::TaskView::TaskView* ControlSingleton::taskPanel() const { - auto taskView = qobject_cast - (Gui::DockWindowManager::instance()->getDockWindow("Tasks")); + auto taskView = qobject_cast( + Gui::DockWindowManager::instance()->getDockWindow("Tasks") + ); return taskView; } @@ -130,21 +129,23 @@ void ControlSingleton::showTaskView() void ControlSingleton::showModelView() { - auto treeView = qobject_cast - (Gui::DockWindowManager::instance()->getDockWindow("Tree view")); + auto treeView = qobject_cast( + Gui::DockWindowManager::instance()->getDockWindow("Tree view") + ); if (treeView) { showDockWidget(treeView); } else { - auto comboView = qobject_cast - (Gui::DockWindowManager::instance()->getDockWindow("Model")); + auto comboView = qobject_cast( + Gui::DockWindowManager::instance()->getDockWindow("Model") + ); if (comboView) { showDockWidget(comboView); } } } -void ControlSingleton::showDialog(Gui::TaskView::TaskDialog *dlg) +void ControlSingleton::showDialog(Gui::TaskView::TaskDialog* dlg) { // only one dialog at a time, print a warning instead of raising an assert if (ActiveDialog && ActiveDialog != dlg) { @@ -177,14 +178,14 @@ void ControlSingleton::showDialog(Gui::TaskView::TaskDialog *dlg) aboutToShowDialog(dw); dw->setVisible(true); dw->toggleViewAction()->setVisible(true); - dw->setFeatures(QDockWidget::DockWidgetMovable|QDockWidget::DockWidgetFloatable); + dw->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); } - if (ActiveDialog == dlg) - return; // dialog is already defined + if (ActiveDialog == dlg) { + return; // dialog is already defined + } ActiveDialog = dlg; - connect(dlg, &TaskView::TaskDialog::aboutToBeDestroyed, - this, &ControlSingleton::closedDialog); + connect(dlg, &TaskView::TaskDialog::aboutToBeDestroyed, this, &ControlSingleton::closedDialog); } } @@ -198,8 +199,7 @@ void ControlSingleton::accept() Gui::TaskView::TaskView* taskView = taskPanel(); if (taskView) { taskView->accept(); - qApp->processEvents(QEventLoop::ExcludeUserInputEvents | - QEventLoop::ExcludeSocketNotifiers); + qApp->processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers); } } @@ -208,16 +208,16 @@ void ControlSingleton::reject() Gui::TaskView::TaskView* taskView = taskPanel(); if (taskView) { taskView->reject(); - qApp->processEvents(QEventLoop::ExcludeUserInputEvents | - QEventLoop::ExcludeSocketNotifiers); + qApp->processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers); } } void ControlSingleton::closeDialog() { Gui::TaskView::TaskView* taskView = taskPanel(); - if (taskView) + if (taskView) { taskView->removeDialog(); + } } void ControlSingleton::closedDialog() @@ -230,31 +230,35 @@ void ControlSingleton::closedDialog() auto dw = qobject_cast(taskView->parentWidget()); if (dw) { aboutToHideDialog(dw); - dw->setFeatures(QDockWidget::DockWidgetClosable - | QDockWidget::DockWidgetMovable - | QDockWidget::DockWidgetFloatable); + dw->setFeatures( + QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable + | QDockWidget::DockWidgetFloatable + ); } } bool ControlSingleton::isAllowedAlterDocument() const { - if (ActiveDialog) + if (ActiveDialog) { return ActiveDialog->isAllowedAlterDocument(); + } return true; } bool ControlSingleton::isAllowedAlterView() const { - if (ActiveDialog) + if (ActiveDialog) { return ActiveDialog->isAllowedAlterView(); + } return true; } bool ControlSingleton::isAllowedAlterSelection() const { - if (ActiveDialog) + if (ActiveDialog) { return ActiveDialog->isAllowedAlterSelection(); + } return true; } @@ -262,15 +266,17 @@ bool ControlSingleton::isAllowedAlterSelection() const ControlSingleton& ControlSingleton::instance() { - if (!_pcSingleton) + if (!_pcSingleton) { _pcSingleton = new ControlSingleton; + } return *_pcSingleton; } -void ControlSingleton::destruct () +void ControlSingleton::destruct() { - if (_pcSingleton) + if (_pcSingleton) { delete _pcSingleton; + } _pcSingleton = nullptr; } @@ -279,4 +285,3 @@ void ControlSingleton::destruct () #include "moc_Control.cpp" - diff --git a/src/Gui/Control.h b/src/Gui/Control.h index fd4d3ed838..796aa01a7c 100644 --- a/src/Gui/Control.h +++ b/src/Gui/Control.h @@ -37,37 +37,37 @@ class QTabBar; namespace App { - class DocumentObject; - class Document; -} +class DocumentObject; +class Document; +} // namespace App namespace Gui { namespace TaskView { - class TaskDialog; - class TaskView; -} +class TaskDialog; +class TaskView; +} // namespace TaskView /** The control class */ -class GuiExport ControlSingleton : public QObject +class GuiExport ControlSingleton: public QObject { - Q_OBJECT + Q_OBJECT public: static ControlSingleton& instance(); - static void destruct (); + static void destruct(); /** @name dialog handling * These methods are used to control the TaskDialog stuff. */ //@{ /// This method starts a task dialog in the task view - void showDialog(Gui::TaskView::TaskDialog *dlg); + void showDialog(Gui::TaskView::TaskDialog* dlg); Gui::TaskView::TaskDialog* activeDialog() const; - //void closeDialog(); + // void closeDialog(); //@} /** @name task view handling @@ -79,18 +79,18 @@ public: //@} /*! - If a task dialog is open then it indicates whether this task dialog allows other commands to modify - the document while it is open. If no task dialog is open true is returned. + If a task dialog is open then it indicates whether this task dialog allows other commands to + modify the document while it is open. If no task dialog is open true is returned. */ bool isAllowedAlterDocument() const; /*! - If a task dialog is open then it indicates whether this task dialog allows other commands to modify - the 3d view while it is open. If no task dialog is open true is returned. + If a task dialog is open then it indicates whether this task dialog allows other commands to + modify the 3d view while it is open. If no task dialog is open true is returned. */ bool isAllowedAlterView() const; /*! - If a task dialog is open then it indicates whether this task dialog allows other commands to modify - the selection while it is open. If no task dialog is open true is returned. + If a task dialog is open then it indicates whether this task dialog allows other commands to + modify the selection while it is open. If no task dialog is open true is returned. */ bool isAllowedAlterSelection() const; @@ -106,13 +106,14 @@ private Q_SLOTS: void closedDialog(); private: - struct status { + struct status + { std::bitset<32> StatusBits; } CurrentStatus; std::stack StatusStack; - Gui::TaskView::TaskDialog *ActiveDialog; + Gui::TaskView::TaskDialog* ActiveDialog; int oldTabIndex; private: @@ -134,6 +135,6 @@ inline ControlSingleton& Control() return ControlSingleton::instance(); } -} //namespace Gui +} // namespace Gui -#endif // GUI_CONTROL_H +#endif // GUI_CONTROL_H diff --git a/src/Gui/CornerCrossLetters.h b/src/Gui/CornerCrossLetters.h index d60c6d35dd..997d22cefc 100644 --- a/src/Gui/CornerCrossLetters.h +++ b/src/Gui/CornerCrossLetters.h @@ -1,7 +1,8 @@ #ifndef GUI_CORNERCROSSLETTERS_H #define GUI_CORNERCROSSLETTERS_H -namespace Gui { +namespace Gui +{ //**************************************************************************** @@ -10,226 +11,429 @@ namespace Gui { // 21x27 is 3x a standard 5x7 representation with 1px margin // This allows good anti-aliasing aspect at any usable size // It is generated with Gimp using Bitstream Charter Bold font, 28 px, on transparent background -// It is then directly exported as C source type after image is vertically flipped for direct GL usage -// With enabled options "Use macros instead of struct" and "Save alpha channel" +// It is then directly exported as C source type after image is vertically flipped for direct GL +// usage With enabled options "Use macros instead of struct" and "Save alpha channel" #define XPM_WIDTH (21) #define XPM_HEIGHT (27) #define XPM_BYTES_PER_PIXEL (4) /* 2:RGB16, 3:RGB, 4:RGBA */ -#define XPM_PIXEL_MASK ((unsigned char*) ::XPM_pixel_mask) -static const unsigned char XPM_pixel_mask[21 * 27 * 4 + 1] = -("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\261\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\320\000\000\000\003\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000w\000\000\000\377\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000Y\000\000\000\000\000\000\000\000\000\000\000\036\000\000\000\364\000\000\000\377\000\000\000\377\000\000" - "\000\377\000\000\000j\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\032\000\000" - "\000\363\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\264\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000u\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\355\000\000\000\023\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\245\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\363" - "\000\000\000\035\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\322\000\000\000\377\000\000" - "\000\377\000\000\000\377\000\000\000\230\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000<\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000l\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000:\000\000\000\376\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000\062\000\000\000" - "\000\000\000\000\000\000\000\000\002\000\000\000\317\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\306\000\000\000" - "\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\233\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\305\000\000\000\001\000\000\000\000\000\000\000h\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\371\000\000\000*\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\021\000\000\000\352\000\000\000\377\000\000\000\377\000\000\000\377\000" - "\000\000]\000\000\000\022\000\000\000\354\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\177\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000^\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\347\000\000\000\241\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\325\000\000\000\006\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\277\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000\071\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000(\000\000\000\371\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\222\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\215\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000\026\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\003\000\000\000\315\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" - "\202\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000l\000\000\000\377\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\370\000\000\000$\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\027\000\000" - "\000\360\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\305\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\265\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\243\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\302" - "\000\000\000\015\000\000\000\351\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000N\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000>\000\000\000\377\000" - "\000\000\377\000\000\000\377\000\000\000\376\000\000\000\063\000\000\000\000\000\000\000i\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000\337\000\000\000\011\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\004\000\000\000\324\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\241\000\000\000" - "\000\000\000\000\000\000\000\000\003\000\000\000\326\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\201\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000u\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\365\000\000\000\033\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000M\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\367\000\000\000#\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\034\000\000\000\363\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\200\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\276\000\000\000\377\000\000\000\377\000\000\000\377\000\000" - "\000\264\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\253\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\345\000\000\000\012\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\062\000\000\000\376\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000M\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000G\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000_\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\243\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000\336\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000"); +#define XPM_PIXEL_MASK ((unsigned char*)::XPM_pixel_mask) +static const unsigned char XPM_pixel_mask[21 * 27 * 4 + 1] + = ("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\261\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\320\000\000\000\003\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000w\000\000" + "\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000Y\000\000\000\000\000\000\000\000\000\000\000\036\000\000\000\364" + "\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000j\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\032\000\000" + "\000\363\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\264\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000u\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\355\000" + "\000\000\023\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\245\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\363" + "\000\000\000\035\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\004\000\000\000\322\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000\000\230\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000<\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000l\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000:" + "\000\000\000\376\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000\062\000\000" + "\000" + "\000\000\000\000\000\000\000\000\002\000\000\000\317\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\306\000\000\000" + "\002\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\233\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\305\000\000\000\001\000\000\000\000\000" + "\000\000h\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\371\000\000\000*" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\021\000\000\000\352\000\000\000" + "\377\000\000\000\377\000\000\000\377\000" + "\000\000]" + "\000\000\000\022\000\000\000\354\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\177\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000^" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\347\000\000\000\241\000\000" + "\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\325\000\000\000\006\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\277\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000" + "\071\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000(" + "\000\000\000\371\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\377" + "\000\000\000\222\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\215\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000\026\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\003\000\000\000\315\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000\000" + "\202\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000l\000\000" + "\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\370\000\000\000$" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\027\000\000" + "\000\360\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\305\000\000\000\377" + "\000\000\000\377\000\000\000\377" + "\000\000\000\265\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\243\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000\000\302" + "\000\000\000\015\000\000\000\351\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000N\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000>\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\376\000\000\000\063\000\000\000\000\000\000\000i" + "\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\337\000\000\000\011\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\004\000\000\000\324\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\241\000\000\000" + "\000\000\000\000\000\000\000\000\003\000\000\000\326\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\201\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000u\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\365\000\000\000\033\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000M\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\367\000\000\000#" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\034\000\000\000\363\000\000\000\377\000\000\000\377\000\000\000\377" + "\000\000\000\200\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\276\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000" + "\000\264\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\253\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\345\000\000\000\012\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\062\000\000\000\376\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000M\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000G\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000_\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\243\000\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\336\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000"); #define YPM_WIDTH (21) #define YPM_HEIGHT (27) #define YPM_BYTES_PER_PIXEL (4) /* 2:RGB16, 3:RGB, 4:RGBA */ -#define YPM_PIXEL_MASK ((unsigned char*) ::YPM_pixel_mask) -static const unsigned char YPM_pixel_mask[21 * 27 * 4 + 1] = -("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000" - "\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000" - "\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\242\000\000\000\377\000" - "\000\000\377\000\000\000\377\000\000\000\365\000\000\000\026\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000'\000\000\000\374\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\216\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\246\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\367\000\000\000\033\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000+\000\000" - "\000\375\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\225" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\253\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\371\000" - "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\371\000\000\000\037\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000/\000\000\000\376\000" - "\000\000\377\000\000\000\377\000\000\000\377\000\000\000d\000\000\000\340\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\235\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\260\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\332\000\000\000\003" - "\000\000\000e\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\373\000\000\000$\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\063\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\\\000\000\000\000\000\000\000\004\000\000\000\335\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\244\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\265\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\003\000\000\000" - "\000\000\000\000\000\000\000\000a\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\375\000\000\000*\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\070\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000Z\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\003\000\000\000\332\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\253\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\272\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\327\000\000\000\002\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000]\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\376\000\000\000" - "\060\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000<\000\000\000\377\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000X\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\327" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\262\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\277\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\325\000\000\000\002\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000Y\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000\066\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000"); +#define YPM_PIXEL_MASK ((unsigned char*)::YPM_pixel_mask) +static const unsigned char YPM_pixel_mask[21 * 27 * 4 + 1] + = ("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\\\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000" + "\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000\377\000\000\000\377" + "\000\000\000\330\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\\\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\330\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\\\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\330\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\330\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\242\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\365\000\000\000\026\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000'" + "\000\000\000\374\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\216\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\246\000" + "\000\000\377\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\367\000\000\000\033\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000+\000\000" + "\000\375\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\225" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\253\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\371\000" + "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\371\000\000\000\037\000\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000/\000\000\000\376\000" + "\000\000\377\000\000\000\377\000\000\000\377\000\000\000d\000\000\000\340\000\000\000\377" + "\000\000\000\377\000\000\000\377" + "\000\000\000\235\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\260\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\332\000\000\000\003" + "\000\000\000e\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\373\000\000\000$" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\063\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\\\000\000\000\000\000\000\000\004\000\000\000" + "\335\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\244\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\265\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\330\000\000\000\003\000\000\000" + "\000\000\000\000\000\000\000\000a\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\375\000\000\000*\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\070\000\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000Z\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\003\000\000\000\332\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\253\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\272\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\327" + "\000\000\000\002\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000]" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\376\000\000\000" + "\060\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000<" + "\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000X\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\002\000\000\000\327" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\262\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\277\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\325\000\000\000" + "\002\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000Y\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\066\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000"); #define ZPM_WIDTH (21) #define ZPM_HEIGHT (27) #define ZPM_BYTES_PER_PIXEL (4) /* 2:RGB16, 3:RGB, 4:RGBA */ -#define ZPM_PIXEL_MASK ((unsigned char*) ::ZPM_pixel_mask) -static const unsigned char ZPM_pixel_mask[21 * 27 * 4 + 1] = -("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000T\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\214\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000T\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\214\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000L\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" - "\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\214\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\003\000\000\000\312\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\360\000\000" - "\000u\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000?\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000.\000\000\000\372\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000d\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\204\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\357\000\000\000\031\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\007\000\000\000\327\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000\255\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000;\000\000\000\376\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000R\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\225\000\000\000\377\000\000\000\377\000\000\000\377\000" - "\000\000\346\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\015" - "\000\000\000\342\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\233\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000K\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000A\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\246" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\334\000\000\000\011\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\025\000\000\000\353\000\000\000\377\000\000\000\377\000\000\000\377\000" - "\000\000\212\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000" - "\000\377\000\000\000\377\000\000\000\377\000\000\000\374\000\000\000\062\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\266\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\317" - "\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\036\000\000\000\363" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000x\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000m\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\367\000\000\000%\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\011\000\000\000t\000\000\000t\000\000" - "\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000v\000\000\000\363\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\300\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\024\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" - "\000?\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\024\000\000\000\377\000\000\000\377\000" - "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000H\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\024\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" - "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377" - "\000\000\000\377\000\000\000\377\000\000\000H\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"); +#define ZPM_PIXEL_MASK ((unsigned char*)::ZPM_pixel_mask) +static const unsigned char ZPM_pixel_mask[21 * 27 * 4 + 1] + = ("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000T\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\214\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000T\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\214\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000L\000" + "\000\000\377\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\214\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\003\000\000\000\312\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\360\000\000" + "\000u\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000" + "\000t\000\000\000t\000\000\000?\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000.\000\000\000\372\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000d\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\204\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\357\000" + "\000\000\031\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\007\000" + "\000\000\327\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\255\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000;" + "\000\000\000\376\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000R\000\000\000" + "\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\225\000\000" + "\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\346\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\015" + "\000\000\000\342\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\233\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000K\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000A\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\246" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\334\000\000\000\011\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\025\000\000\000\353\000\000\000" + "\377\000\000\000\377\000\000\000\377\000" + "\000\000\212\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\\\000\000" + "\000\377\000\000\000\377\000\000\000\377\000\000\000\374\000\000\000\062\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\266\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\317" + "\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\036\000\000\000\363" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000x\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000m\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\367\000\000\000%\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\011\000\000\000t\000\000\000t\000\000" + "\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000t\000\000\000v\000\000" + "\000\363\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\300\000\000\000\001\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\024\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000" + "\000\377\000\000\000\377\000\000" + "\000?" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\024\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000H\000\000" + "\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\024\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000H\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000" + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"); -} +} // namespace Gui -#endif //GUI_CORNERCROSSLETTERS_H +#endif // GUI_CORNERCROSSLETTERS_H diff --git a/src/Gui/DAGView/DAGModel.cpp b/src/Gui/DAGView/DAGModel.cpp index 73e8335611..5b4af951d7 100644 --- a/src/Gui/DAGView/DAGModel.cpp +++ b/src/Gui/DAGView/DAGModel.cpp @@ -55,1126 +55,1162 @@ using namespace Gui; using namespace DAG; namespace sp = std::placeholders; -LineEdit::LineEdit(QWidget* parentIn): QLineEdit(parentIn) -{ +LineEdit::LineEdit(QWidget* parentIn) + : QLineEdit(parentIn) +{} +void LineEdit::keyPressEvent(QKeyEvent* eventIn) +{ + if (eventIn->key() == Qt::Key_Escape) { + Q_EMIT rejectedSignal(); + eventIn->accept(); + return; + } + if ((eventIn->key() == Qt::Key_Enter) || (eventIn->key() == Qt::Key_Return)) { + Q_EMIT acceptedSignal(); + eventIn->accept(); + return; + } + + QLineEdit::keyPressEvent(eventIn); } -void LineEdit::keyPressEvent(QKeyEvent *eventIn) +// I don't think I should have to call invalidate +// and definitely not on the whole scene! +// if we have performance problems, this will definitely +// be something to re-visit. I am not wasting anymore time on +// this right now. +// this->scene()->invalidate(); +// this->scene()->invalidate(this->sceneTransform().inverted().mapRect(this->boundingRect())); +// update(boundingRect()); +// note: I haven't tried this again since I turned BSP off. + +Model::Model(QObject* parentIn, const Gui::Document& documentIn) + : QGraphicsScene(parentIn) { - if (eventIn->key() == Qt::Key_Escape) - { - Q_EMIT rejectedSignal(); - eventIn->accept(); - return; - } - if ( - (eventIn->key() == Qt::Key_Enter) || - (eventIn->key() == Qt::Key_Return) - ) - { - Q_EMIT acceptedSignal(); - eventIn->accept(); - return; - } + // turned off BSP as it was giving inconsistent discovery of items + // underneath cursor. + this->setItemIndexMethod(QGraphicsScene::NoIndex); - QLineEdit::keyPressEvent(eventIn); -} + theGraph = std::make_shared(); + graphLink = std::make_shared(); + setupViewConstants(); -//I don't think I should have to call invalidate -//and definitely not on the whole scene! -//if we have performance problems, this will definitely -//be something to re-visit. I am not wasting anymore time on -//this right now. -// this->scene()->invalidate(); -// this->scene()->invalidate(this->sceneTransform().inverted().mapRect(this->boundingRect())); -// update(boundingRect()); -//note: I haven't tried this again since I turned BSP off. + graphDirty = false; + currentPrehighlight = nullptr; -Model::Model(QObject *parentIn, const Gui::Document &documentIn) : QGraphicsScene(parentIn) -{ - //turned off BSP as it was giving inconsistent discovery of items - //underneath cursor. - this->setItemIndexMethod(QGraphicsScene::NoIndex); - - theGraph = std::make_shared(); - graphLink = std::make_shared(); - setupViewConstants(); - - graphDirty = false; - currentPrehighlight = nullptr; - - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("DAGView"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("DAGView"); selectionMode = static_cast(group->GetInt("SelectionMode", 0)); - group->SetInt("SelectionMode", static_cast(selectionMode)); //ensure entry exists. + group->SetInt("SelectionMode", static_cast(selectionMode)); // ensure entry exists. - QIcon temp(Gui::BitmapFactory().iconFromTheme("dagViewVisible")); - visiblePixmapEnabled = temp.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::On); - visiblePixmapDisabled = temp.pixmap(iconSize, iconSize, QIcon::Disabled, QIcon::Off); + QIcon temp(Gui::BitmapFactory().iconFromTheme("dagViewVisible")); + visiblePixmapEnabled = temp.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::On); + visiblePixmapDisabled = temp.pixmap(iconSize, iconSize, QIcon::Disabled, QIcon::Off); - QIcon passIcon(Gui::BitmapFactory().iconFromTheme("dagViewPass")); - passPixmap = passIcon.pixmap(iconSize, iconSize); - QIcon failIcon(Gui::BitmapFactory().iconFromTheme("dagViewFail")); - failPixmap = failIcon.pixmap(iconSize, iconSize); - QIcon pendingIcon(Gui::BitmapFactory().iconFromTheme("dagViewPending")); - pendingPixmap = pendingIcon.pixmap(iconSize, iconSize); + QIcon passIcon(Gui::BitmapFactory().iconFromTheme("dagViewPass")); + passPixmap = passIcon.pixmap(iconSize, iconSize); + QIcon failIcon(Gui::BitmapFactory().iconFromTheme("dagViewFail")); + failPixmap = failIcon.pixmap(iconSize, iconSize); + QIcon pendingIcon(Gui::BitmapFactory().iconFromTheme("dagViewPending")); + pendingPixmap = pendingIcon.pixmap(iconSize, iconSize); - renameAction = new QAction(this); - renameAction->setText(tr("Rename")); - renameAction->setStatusTip(tr("Renames the object")); + renameAction = new QAction(this); + renameAction->setText(tr("Rename")); + renameAction->setStatusTip(tr("Renames the object")); #ifndef Q_OS_MAC - renameAction->setShortcut(Qt::Key_F2); + renameAction->setShortcut(Qt::Key_F2); #endif - connect(renameAction, &QAction::triggered, this, &Model::renameAcceptedSlot); + connect(renameAction, &QAction::triggered, this, &Model::renameAcceptedSlot); - editingFinishedAction = new QAction(this); - editingFinishedAction->setText(tr("Finish Editing")); - editingFinishedAction->setStatusTip(tr("Finishes editing the object")); - connect(this->editingFinishedAction, &QAction::triggered, - this, &Model::editingFinishedSlot); + editingFinishedAction = new QAction(this); + editingFinishedAction->setText(tr("Finish Editing")); + editingFinishedAction->setStatusTip(tr("Finishes editing the object")); + connect(this->editingFinishedAction, &QAction::triggered, this, &Model::editingFinishedSlot); - //NOLINTBEGIN - connectNewObject = documentIn.signalNewObject.connect(std::bind(&Model::slotNewObject, this, sp::_1)); - connectDelObject = documentIn.signalDeletedObject.connect(std::bind(&Model::slotDeleteObject, this, sp::_1)); - connectChgObject = documentIn.signalChangedObject.connect(std::bind(&Model::slotChangeObject, this, sp::_1, sp::_2)); - connectEdtObject = documentIn.signalInEdit.connect(std::bind(&Model::slotInEdit, this, sp::_1)); - connectResObject = documentIn.signalResetEdit.connect(std::bind(&Model::slotResetEdit, this, sp::_1)); - //NOLINTEND + // NOLINTBEGIN + connectNewObject = documentIn.signalNewObject.connect( + std::bind(&Model::slotNewObject, this, sp::_1) + ); + connectDelObject = documentIn.signalDeletedObject.connect( + std::bind(&Model::slotDeleteObject, this, sp::_1) + ); + connectChgObject = documentIn.signalChangedObject.connect( + std::bind(&Model::slotChangeObject, this, sp::_1, sp::_2) + ); + connectEdtObject = documentIn.signalInEdit.connect(std::bind(&Model::slotInEdit, this, sp::_1)); + connectResObject = documentIn.signalResetEdit.connect( + std::bind(&Model::slotResetEdit, this, sp::_1) + ); + // NOLINTEND - for (auto obj : documentIn.getDocument()->getObjects()) { - auto vpd = freecad_cast(documentIn.getViewProvider(obj)); - if (vpd) - slotNewObject(*vpd); - } + for (auto obj : documentIn.getDocument()->getObjects()) { + auto vpd = freecad_cast(documentIn.getViewProvider(obj)); + if (vpd) { + slotNewObject(*vpd); + } + } } Model::~Model() { - if (connectNewObject.connected()) - connectNewObject.disconnect(); - if (connectDelObject.connected()) - connectDelObject.disconnect(); - if (connectChgObject.connected()) - connectChgObject.disconnect(); - if(connectEdtObject.connected()) - connectEdtObject.disconnect(); - if(connectResObject.connected()) - connectResObject.disconnect(); + if (connectNewObject.connected()) { + connectNewObject.disconnect(); + } + if (connectDelObject.connected()) { + connectDelObject.disconnect(); + } + if (connectChgObject.connected()) { + connectChgObject.disconnect(); + } + if (connectEdtObject.connected()) { + connectEdtObject.disconnect(); + } + if (connectResObject.connected()) { + connectResObject.disconnect(); + } - removeAllItems(); + removeAllItems(); } void Model::setupViewConstants() { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("DAGView"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("DAGView"); - //get font point size. - int fontPointSize = group->GetInt("FontPointSize", 0); - group->SetInt("FontPointSize", fontPointSize); //ensure entry exists. - if (fontPointSize != 0) - { - QFont tempFont(this->font()); - tempFont.setPointSize(fontPointSize); - this->setFont(tempFont); - } + // get font point size. + int fontPointSize = group->GetInt("FontPointSize", 0); + group->SetInt("FontPointSize", fontPointSize); // ensure entry exists. + if (fontPointSize != 0) { + QFont tempFont(this->font()); + tempFont.setPointSize(fontPointSize); + this->setFont(tempFont); + } - //get direction - direction = group->GetFloat("Direction", 1.0); - if (direction != -1.0 && direction != 1.0) - direction = 1.0; - group->SetFloat("Direction", direction); //ensure entry exists. + // get direction + direction = group->GetFloat("Direction", 1.0); + if (direction != -1.0 && direction != 1.0) { + direction = 1.0; + } + group->SetFloat("Direction", direction); // ensure entry exists. - QFontMetrics fontMetric(this->font()); - fontHeight = fontMetric.height(); - verticalSpacing = 1.0; - rowHeight = (fontHeight + 2.0 * verticalSpacing) * direction; //pixel space top and bottom. - iconSize = fontHeight; - pointSize = fontHeight / 2.0; - pointSpacing = pointSize; - pointToIcon = iconSize; - iconToIcon = iconSize * 0.25; - iconToText = iconSize / 2.0; - rowPadding = fontHeight; - backgroundBrushes = {this->palette().base(), this->palette().alternateBase()}; - forgroundBrushes = - { - QBrush(Qt::red), - QBrush(Qt::darkRed), - QBrush(Qt::green), - QBrush(Qt::darkGreen), - QBrush(Qt::blue), - QBrush(Qt::darkBlue), - QBrush(Qt::cyan), - QBrush(Qt::darkCyan), - QBrush(Qt::magenta), - QBrush(Qt::darkMagenta), -// QBrush(Qt::yellow), can't read - QBrush(Qt::darkYellow), - QBrush(Qt::gray), - QBrush(Qt::darkGray), - QBrush(Qt::lightGray) - }; //reserve some of the these for highlight stuff. + QFontMetrics fontMetric(this->font()); + fontHeight = fontMetric.height(); + verticalSpacing = 1.0; + rowHeight = (fontHeight + 2.0 * verticalSpacing) * direction; // pixel space top and bottom. + iconSize = fontHeight; + pointSize = fontHeight / 2.0; + pointSpacing = pointSize; + pointToIcon = iconSize; + iconToIcon = iconSize * 0.25; + iconToText = iconSize / 2.0; + rowPadding = fontHeight; + backgroundBrushes = {this->palette().base(), this->palette().alternateBase()}; + forgroundBrushes = { + QBrush(Qt::red), + QBrush(Qt::darkRed), + QBrush(Qt::green), + QBrush(Qt::darkGreen), + QBrush(Qt::blue), + QBrush(Qt::darkBlue), + QBrush(Qt::cyan), + QBrush(Qt::darkCyan), + QBrush(Qt::magenta), + QBrush(Qt::darkMagenta), + // QBrush(Qt::yellow), can't read + QBrush(Qt::darkYellow), + QBrush(Qt::gray), + QBrush(Qt::darkGray), + QBrush(Qt::lightGray) + }; // reserve some of the these for highlight stuff. } -void Model::slotNewObject(const ViewProviderDocumentObject &VPDObjectIn) +void Model::slotNewObject(const ViewProviderDocumentObject& VPDObjectIn) { - Vertex virginVertex = boost::add_vertex(*theGraph); + Vertex virginVertex = boost::add_vertex(*theGraph); - addVertexItemsToScene(virginVertex); + addVertexItemsToScene(virginVertex); - GraphLinkRecord virginRecord; - virginRecord.DObject = VPDObjectIn.getObject(); - virginRecord.VPDObject = &VPDObjectIn; - virginRecord.rectItem = (*theGraph)[virginVertex].rectangle.get(); - virginRecord.uniqueName = std::string(virginRecord.DObject->getNameInDocument()); - virginRecord.vertex = virginVertex; - graphLink->insert(virginRecord); + GraphLinkRecord virginRecord; + virginRecord.DObject = VPDObjectIn.getObject(); + virginRecord.VPDObject = &VPDObjectIn; + virginRecord.rectItem = (*theGraph)[virginVertex].rectangle.get(); + virginRecord.uniqueName = std::string(virginRecord.DObject->getNameInDocument()); + virginRecord.vertex = virginVertex; + graphLink->insert(virginRecord); - //setup rectangle. - auto rectangle = (*theGraph)[virginVertex].rectangle.get(); - rectangle->setEditingBrush(QBrush(Qt::yellow)); + // setup rectangle. + auto rectangle = (*theGraph)[virginVertex].rectangle.get(); + rectangle->setEditingBrush(QBrush(Qt::yellow)); - auto icon = (*theGraph)[virginVertex].icon; - icon->setPixmap(VPDObjectIn.getIcon().pixmap(iconSize, iconSize)); - (*theGraph)[virginVertex].stateIcon->setPixmap(passPixmap); - (*theGraph)[virginVertex].text->setFont(this->font()); - //NOLINTBEGIN - (*theGraph)[virginVertex].connChangeIcon = - const_cast(VPDObjectIn).signalChangeIcon.connect( - std::bind(&Model::slotChangeIcon, this, boost::cref(VPDObjectIn), icon)); - //NOLINTEND + auto icon = (*theGraph)[virginVertex].icon; + icon->setPixmap(VPDObjectIn.getIcon().pixmap(iconSize, iconSize)); + (*theGraph)[virginVertex].stateIcon->setPixmap(passPixmap); + (*theGraph)[virginVertex].text->setFont(this->font()); + // NOLINTBEGIN + (*theGraph)[virginVertex].connChangeIcon + = const_cast(VPDObjectIn) + .signalChangeIcon.connect( + std::bind(&Model::slotChangeIcon, this, boost::cref(VPDObjectIn), icon) + ); + // NOLINTEND - graphDirty = true; - lastAddedVertex = Graph::null_vertex(); -} - -void Model::slotChangeIcon(const ViewProviderDocumentObject &VPDObjectIn, std::shared_ptr icon) -{ - icon->setPixmap(VPDObjectIn.getIcon().pixmap(iconSize, iconSize)); - this->invalidate(); -} - -void Model::slotDeleteObject(const ViewProviderDocumentObject &VPDObjectIn) -{ - Vertex vertex = findRecord(&VPDObjectIn, *graphLink).vertex; - - //remove items from scene. - removeVertexItemsFromScene(vertex); - - //remove connector items - auto outRange = boost::out_edges(vertex, *theGraph); - for (auto outEdgeIt = outRange.first; outEdgeIt != outRange.second; ++outEdgeIt) - this->removeItem((*theGraph)[*outEdgeIt].connector.get()); - auto inRange = boost::in_edges(vertex, *theGraph); - for (auto inEdgeIt = inRange.first; inEdgeIt != inRange.second; ++inEdgeIt) - this->removeItem((*theGraph)[*inEdgeIt].connector.get()); - - if (vertex == lastAddedVertex) + graphDirty = true; lastAddedVertex = Graph::null_vertex(); - - (*theGraph)[vertex].connChangeIcon.disconnect(); - - //remove the actual vertex. - boost::clear_vertex(vertex, *theGraph); - boost::remove_vertex(vertex, *theGraph); - - eraseRecord(&VPDObjectIn, *graphLink); - graphDirty = true; } -void Model::slotChangeObject(const ViewProviderDocumentObject &VPDObjectIn, const App::Property& propertyIn) +void Model::slotChangeIcon( + const ViewProviderDocumentObject& VPDObjectIn, + std::shared_ptr icon +) { - std::string name("Empty Name"); - if (propertyIn.hasName()) - name = propertyIn.getName(); - assert(!name.empty()); + icon->setPixmap(VPDObjectIn.getIcon().pixmap(iconSize, iconSize)); + this->invalidate(); +} -// std::cout << std::endl << "inside changed object." << std::endl << -// "Property name is: " << name << std::endl << -// "Property type is: " << propertyIn.getTypeId().getName() << std::endl << std::endl; +void Model::slotDeleteObject(const ViewProviderDocumentObject& VPDObjectIn) +{ + Vertex vertex = findRecord(&VPDObjectIn, *graphLink).vertex; - //renaming of objects. - if (std::string("Label") == name) - { - if (hasRecord(&VPDObjectIn, *graphLink)) - { - const GraphLinkRecord &record = findRecord(&VPDObjectIn, *graphLink); - auto text = (*theGraph)[record.vertex].text.get(); - text->setPlainText(QString::fromUtf8(record.DObject->Label.getValue())); + // remove items from scene. + removeVertexItemsFromScene(vertex); + + // remove connector items + auto outRange = boost::out_edges(vertex, *theGraph); + for (auto outEdgeIt = outRange.first; outEdgeIt != outRange.second; ++outEdgeIt) { + this->removeItem((*theGraph)[*outEdgeIt].connector.get()); } - } - else if (propertyIn.isDerivedFrom()) - { - if (hasRecord(&VPDObjectIn, *graphLink)) - { - const GraphLinkRecord &record = findRecord(&VPDObjectIn, *graphLink); - boost::clear_vertex(record.vertex, *theGraph); - graphDirty = true; + auto inRange = boost::in_edges(vertex, *theGraph); + for (auto inEdgeIt = inRange.first; inEdgeIt != inRange.second; ++inEdgeIt) { + this->removeItem((*theGraph)[*inEdgeIt].connector.get()); + } + + if (vertex == lastAddedVertex) { + lastAddedVertex = Graph::null_vertex(); + } + + (*theGraph)[vertex].connChangeIcon.disconnect(); + + // remove the actual vertex. + boost::clear_vertex(vertex, *theGraph); + boost::remove_vertex(vertex, *theGraph); + + eraseRecord(&VPDObjectIn, *graphLink); + graphDirty = true; +} + +void Model::slotChangeObject(const ViewProviderDocumentObject& VPDObjectIn, const App::Property& propertyIn) +{ + std::string name("Empty Name"); + if (propertyIn.hasName()) { + name = propertyIn.getName(); + } + assert(!name.empty()); + + // std::cout << std::endl << "inside changed object." << std::endl << + // "Property name is: " << name << std::endl << + // "Property type is: " << propertyIn.getTypeId().getName() << std::endl << std::endl; + + // renaming of objects. + if (std::string("Label") == name) { + if (hasRecord(&VPDObjectIn, *graphLink)) { + const GraphLinkRecord& record = findRecord(&VPDObjectIn, *graphLink); + auto text = (*theGraph)[record.vertex].text.get(); + text->setPlainText(QString::fromUtf8(record.DObject->Label.getValue())); + } + } + else if (propertyIn.isDerivedFrom()) { + if (hasRecord(&VPDObjectIn, *graphLink)) { + const GraphLinkRecord& record = findRecord(&VPDObjectIn, *graphLink); + boost::clear_vertex(record.vertex, *theGraph); + graphDirty = true; + } } - } } void Model::slotInEdit(const ViewProviderDocumentObject& VPDObjectIn) { - RectItem *rect = (*theGraph)[findRecord(&VPDObjectIn, *graphLink).vertex].rectangle.get(); - rect->editingStart(); - this->invalidate(); + RectItem* rect = (*theGraph)[findRecord(&VPDObjectIn, *graphLink).vertex].rectangle.get(); + rect->editingStart(); + this->invalidate(); } void Model::slotResetEdit(const ViewProviderDocumentObject& VPDObjectIn) { - RectItem *rect = (*theGraph)[findRecord(&VPDObjectIn, *graphLink).vertex].rectangle.get(); - rect->editingFinished(); - this->invalidate(); + RectItem* rect = (*theGraph)[findRecord(&VPDObjectIn, *graphLink).vertex].rectangle.get(); + rect->editingFinished(); + this->invalidate(); } void Model::selectionChanged(const SelectionChanges& msg) { - //TODO: note that treeview uses set selection which sends a message with just a document name - //and no object name. Have to explore further. + // TODO: note that treeview uses set selection which sends a message with just a document name + // and no object name. Have to explore further. - auto getAllEdges = [this](const Vertex &vertexIn) - { - //is there really no function to get both in and out edges? - std::vector out; + auto getAllEdges = [this](const Vertex& vertexIn) { + // is there really no function to get both in and out edges? + std::vector out; - OutEdgeIterator outIt, outItEnd; - for (boost::tie(outIt, outItEnd) = boost::out_edges(vertexIn, *theGraph); outIt != outItEnd; ++outIt) - out.push_back(*outIt); + OutEdgeIterator outIt, outItEnd; + for (boost::tie(outIt, outItEnd) = boost::out_edges(vertexIn, *theGraph); outIt != outItEnd; + ++outIt) { + out.push_back(*outIt); + } - InEdgeIterator inIt, inItEnd; - for (boost::tie(inIt, inItEnd) = boost::in_edges(vertexIn, *theGraph); inIt != inItEnd; ++inIt) - out.push_back(*inIt); + InEdgeIterator inIt, inItEnd; + for (boost::tie(inIt, inItEnd) = boost::in_edges(vertexIn, *theGraph); inIt != inItEnd; + ++inIt) { + out.push_back(*inIt); + } - return out; - }; + return out; + }; - auto highlightConnectorOn = [this, getAllEdges](const Vertex &vertexIn) - { - QColor color = (*theGraph)[vertexIn].text->defaultTextColor(); - QPen pen(color); - pen.setWidth(3.0); - auto edges = getAllEdges(vertexIn); - for (auto edge : edges) - { - (*theGraph)[edge].connector->setPen(pen); - (*theGraph)[edge].connector->setZValue(1.0); + auto highlightConnectorOn = [this, getAllEdges](const Vertex& vertexIn) { + QColor color = (*theGraph)[vertexIn].text->defaultTextColor(); + QPen pen(color); + pen.setWidth(3.0); + auto edges = getAllEdges(vertexIn); + for (auto edge : edges) { + (*theGraph)[edge].connector->setPen(pen); + (*theGraph)[edge].connector->setZValue(1.0); + } + }; + + auto highlightConnectorOff = [this, getAllEdges](const Vertex& vertexIn) { + auto edges = getAllEdges(vertexIn); + for (auto edge : edges) { + (*theGraph)[edge].connector->setPen(QPen()); + (*theGraph)[edge].connector->setZValue(0.0); + } + }; + + // lambda for clearing selections. + auto clearSelection = [this, highlightConnectorOff]() { + BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) + { + RectItem* rect = (*theGraph)[currentVertex].rectangle.get(); + assert(rect); + rect->selectionOff(); + highlightConnectorOff(currentVertex); + } + }; + + // lambda for getting rectangle. + auto getRectangle = [this](const char* in) { + assert(in); + std::string name(in); + assert(!name.empty()); + const GraphLinkRecord& record = findRecord(name, *graphLink); + RectItem* rect = (*theGraph)[record.vertex].rectangle.get(); + assert(rect); + return rect; + }; + + if (msg.Type == SelectionChanges::AddSelection) { + if (msg.pObjectName) { + RectItem* rect = getRectangle(msg.pObjectName); + rect->selectionOn(); + highlightConnectorOn(findRecord(std::string(msg.pObjectName), *graphLink).vertex); + } } - }; - - auto highlightConnectorOff = [this, getAllEdges](const Vertex &vertexIn) - { - auto edges = getAllEdges(vertexIn); - for (auto edge : edges) - { - (*theGraph)[edge].connector->setPen(QPen()); - (*theGraph)[edge].connector->setZValue(0.0); + else if (msg.Type == SelectionChanges::RmvSelection) { + if (msg.pObjectName) { + RectItem* rect = getRectangle(msg.pObjectName); + rect->selectionOff(); + highlightConnectorOff(findRecord(std::string(msg.pObjectName), *graphLink).vertex); + } } - }; + else if (msg.Type == SelectionChanges::SetSelection) { + clearSelection(); - //lambda for clearing selections. - auto clearSelection = [this, highlightConnectorOff]() - { - BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) - { - RectItem *rect = (*theGraph)[currentVertex].rectangle.get(); - assert(rect); - rect->selectionOff(); - highlightConnectorOff(currentVertex); + auto selections = Gui::Selection().getSelection(msg.pDocName); + for (const auto& selection : selections) { + assert(selection.FeatName); + RectItem* rect = getRectangle(selection.FeatName); + rect->selectionOn(); + highlightConnectorOn(findRecord(selection.FeatName, *graphLink).vertex); + } } - }; - - //lambda for getting rectangle. - auto getRectangle = [this](const char *in) - { - assert(in); - std::string name(in); - assert(!name.empty()); - const GraphLinkRecord &record = findRecord(name, *graphLink); - RectItem *rect = (*theGraph)[record.vertex].rectangle.get(); - assert(rect); - return rect; - }; - - if (msg.Type == SelectionChanges::AddSelection) - { - if (msg.pObjectName) - { - RectItem *rect = getRectangle(msg.pObjectName); - rect->selectionOn(); - highlightConnectorOn(findRecord(std::string(msg.pObjectName), *graphLink).vertex); + else if (msg.Type == SelectionChanges::ClrSelection) { + clearSelection(); } - } - else if(msg.Type == SelectionChanges::RmvSelection) - { - if (msg.pObjectName) - { - RectItem *rect = getRectangle(msg.pObjectName); - rect->selectionOff(); - highlightConnectorOff(findRecord(std::string(msg.pObjectName), *graphLink).vertex); - } - } - else if(msg.Type == SelectionChanges::SetSelection) - { - clearSelection(); - auto selections = Gui::Selection().getSelection(msg.pDocName); - for (const auto &selection : selections) - { - assert(selection.FeatName); - RectItem *rect = getRectangle(selection.FeatName); - rect->selectionOn(); - highlightConnectorOn(findRecord(selection.FeatName, *graphLink).vertex); - } - } - else if(msg.Type == SelectionChanges::ClrSelection) - { - clearSelection(); - } - - this->invalidate(); + this->invalidate(); } void Model::awake() { - if (graphDirty) - { - updateSlot(); - this->invalidate(); - } - updateStates(); + if (graphDirty) { + updateSlot(); + this->invalidate(); + } + updateStates(); } void Model::updateSlot() { - //empty outList means it is a root. - //empty inList means it is a leaf. + // empty outList means it is a root. + // empty inList means it is a leaf. - //NOTE: some of the following loops can/should be combined - //for speed. Not doing yet, as I want a simple algorithm until - //a more complete picture is formed. + // NOTE: some of the following loops can/should be combined + // for speed. Not doing yet, as I want a simple algorithm until + // a more complete picture is formed. - Base::TimeElapsed startTime; + Base::TimeElapsed startTime; - //here we will cycle through the graph updating edges. - //we have to do this first and in isolation because everything is dependent on an up to date graph. - BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) - { - const App::DocumentObject *currentDObject = findRecord(currentVertex, *graphLink).DObject; - std::vector otherDObjects = currentDObject->getOutList(); - for (auto ¤tOtherDObject : otherDObjects) + // here we will cycle through the graph updating edges. + // we have to do this first and in isolation because everything is dependent on an up to date graph. + BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) { - if (!hasRecord(currentOtherDObject, *graphLink)) - continue; - Vertex otherVertex = findRecord(currentOtherDObject, *graphLink).vertex; - bool result; - Edge edge; - boost::tie(edge, result) = boost::add_edge(currentVertex, otherVertex, *theGraph); - if (result) - { - (*theGraph)[edge].connector = std::make_shared(); - (*theGraph)[edge].connector->setZValue(0.0); - } + const App::DocumentObject* currentDObject = findRecord(currentVertex, *graphLink).DObject; + std::vector otherDObjects = currentDObject->getOutList(); + for (auto& currentOtherDObject : otherDObjects) { + if (!hasRecord(currentOtherDObject, *graphLink)) { + continue; + } + Vertex otherVertex = findRecord(currentOtherDObject, *graphLink).vertex; + bool result; + Edge edge; + boost::tie(edge, result) = boost::add_edge(currentVertex, otherVertex, *theGraph); + if (result) { + (*theGraph)[edge].connector = std::make_shared(); + (*theGraph)[edge].connector->setZValue(0.0); + } + } } - } - BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) - { - if (!(*theGraph)[currentVertex].rectangle->scene()) - addVertexItemsToScene(currentVertex); - } + BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) + { + if (!(*theGraph)[currentVertex].rectangle->scene()) { + addVertexItemsToScene(currentVertex); + } + } - //sync scene items for graph edge. - BGL_FORALL_EDGES(currentEdge, *theGraph, Graph) - { - Vertex source = boost::source(currentEdge, *theGraph); - Vertex target = boost::target(currentEdge, *theGraph); + // sync scene items for graph edge. + BGL_FORALL_EDGES(currentEdge, *theGraph, Graph) + { + Vertex source = boost::source(currentEdge, *theGraph); + Vertex target = boost::target(currentEdge, *theGraph); - if (!(*theGraph)[currentEdge].connector->scene()) - this->addItem((*theGraph)[currentEdge].connector.get()); - } + if (!(*theGraph)[currentEdge].connector->scene()) { + this->addItem((*theGraph)[currentEdge].connector.get()); + } + } - indexVerticesEdges(); - Path sorted; - try - { - boost::topological_sort(*theGraph, std::back_inserter(sorted)); - } - catch(const boost::not_a_dag &) - { - Base::Console().error("not a dag exception in DAGView::Model::updateSlot()\n"); - //do not continuously report an error for cyclic graphs + indexVerticesEdges(); + Path sorted; + try { + boost::topological_sort(*theGraph, std::back_inserter(sorted)); + } + catch (const boost::not_a_dag&) { + Base::Console().error("not a dag exception in DAGView::Model::updateSlot()\n"); + // do not continuously report an error for cyclic graphs + graphDirty = false; + return; + } + // index the vertices in sort order. + int tempIndex = 0; + for (const auto& currentVertex : sorted) { + (*theGraph)[currentVertex].topoSortIndex = tempIndex; + tempIndex++; + } + + // draw graph(nodes and connectors). + int currentRow = 0; + int currentColumn = -1; // we know first column is going to be root so will be kicked up to 0. + int maxColumn = currentColumn; // used for determining offset of icons and text. + qreal maxTextLength = 0; + for (const auto& currentVertex : sorted) { + if (boost::out_degree(currentVertex, *theGraph) == 0) { + currentColumn = 0; + } + else { + // loop parents and find an acceptable column. + int farthestParentIndex = sorted.size(); + ColumnMask columnMask; + Path parentVertices; + OutEdgeIterator it, itEnd; + boost::tie(it, itEnd) = boost::out_edges(currentVertex, *theGraph); + for (; it != itEnd; ++it) { + // std::cout << std::endl << "name: " << findRecord(currentVertex, + // *graphLink).DObject->Label.getValue() << std::endl; + + Vertex target = boost::target(*it, *theGraph); + parentVertices.push_back(target); + int currentParentIndex = (*theGraph)[target].topoSortIndex; + if (currentParentIndex < farthestParentIndex) { + Path::const_iterator start = sorted.begin() + currentParentIndex + 1; // 1 after + Path::const_iterator end = sorted.begin() + + (*theGraph)[currentVertex].topoSortIndex; // 1 before + Path::const_iterator it; + for (it = start; it != end; ++it) { + // std::cout << " parent: " << findRecord(*it, + // *graphLink).DObject->Label.getValue() << std::endl; + + columnMask |= (*theGraph)[*it].column; + } + farthestParentIndex = currentParentIndex; + } + } + + // have to create a smaller subset to get through std::cout. + // std::bitset<8> testSet; + // for (unsigned int index = 0; index < testSet.size(); ++index) + // testSet[index]= columnMask[index]; + // std::cout << "mask for " << findRecord(currentVertex, + // *graphLink).DObject->Label.getValue() << " " << + // testSet.to_string() << std::endl; + + // now we should have a mask representing the columns that are being used. + // this is from the lowest parent, in the topo sort, to last entry. + + // try to use the same column as one of the parents.(*theGraph)[*it].column + int destinationColumn = 0; // default to first column + for (const auto& currentParent : parentVertices) { + if (((*theGraph)[currentParent].column & columnMask).none()) { + // go with first visible parent for now. + destinationColumn = static_cast( + columnFromMask((*theGraph)[currentParent].column) + ); + break; + } + } + // if destination not valid look for the first open column. + if (columnMask.test(destinationColumn)) { + for (std::size_t index = 0; index < columnMask.size(); ++index) { + if (!columnMask.test(index)) { + destinationColumn = index; + break; + } + } + } + + currentColumn = destinationColumn; + } + + assert(currentColumn < static_cast(ColumnMask().size())); // temp limitation. + + maxColumn = std::max(currentColumn, maxColumn); + QBrush currentBrush(forgroundBrushes.at(currentColumn % forgroundBrushes.size())); + + auto rectangle = (*theGraph)[currentVertex].rectangle.get(); + rectangle->setRect(-rowPadding, 0.0, rowPadding, rowHeight); // calculate actual length later. + rectangle->setTransform(QTransform::fromTranslate(0, rowHeight * currentRow)); + rectangle->setBackgroundBrush(backgroundBrushes[currentRow % backgroundBrushes.size()]); + + auto point = (*theGraph)[currentVertex].point.get(); + point->setRect(0.0, 0.0, pointSize, pointSize); + point->setTransform( + QTransform::fromTranslate( + pointSpacing * static_cast(currentColumn), + rowHeight * currentRow + rowHeight / 2.0 - pointSize / 2.0 + ) + ); + point->setBrush(currentBrush); + + qreal cheat = 0.0; + if (direction == -1) { + cheat = rowHeight; + } + + auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get(); + visiblePixmap->setTransform( + QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat) + ); // calculate x location later. + + auto statePixmap = (*theGraph)[currentVertex].stateIcon.get(); + statePixmap->setTransform( + QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat) + ); // calculate x location later. + + auto pixmap = (*theGraph)[currentVertex].icon.get(); + pixmap->setTransform( + QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat) + ); // calculate x location later. + + auto text = (*theGraph)[currentVertex].text.get(); + text->setPlainText( + QString::fromUtf8(findRecord(currentVertex, *graphLink).DObject->Label.getValue()) + ); + text->setDefaultTextColor(currentBrush.color()); + maxTextLength = std::max(maxTextLength, text->boundingRect().width()); + text->setTransform( + QTransform::fromTranslate(0.0, rowHeight * currentRow - verticalSpacing * 2.0 + cheat) + ); // calculate x location later. + (*theGraph)[currentVertex].lastVisibleState = VisibilityState::None; // force visual update + // for color. + + // store column and row int the graph. use for connectors later. + (*theGraph)[currentVertex].row = currentRow; + (*theGraph)[currentVertex].column.reset().set((currentColumn)); + + // our list is topo sorted so all dependents should be located, so we can build the + // connectors. will have some more logic for connector path, simple for now. + qreal currentX = pointSpacing * currentColumn + pointSize / 2.0; + qreal currentY = rowHeight * currentRow + rowHeight / 2.0; + OutEdgeIterator it, itEnd; + boost::tie(it, itEnd) = boost::out_edges(currentVertex, *theGraph); + for (; it != itEnd; ++it) { + Vertex target = boost::target(*it, *theGraph); + qreal dependentX = pointSpacing + * static_cast(columnFromMask((*theGraph)[target].column)) + + pointSize / 2.0; // on center. + columnFromMask((*theGraph)[target].column); + qreal dependentY = rowHeight * (*theGraph)[target].row + rowHeight / 2.0; + + QGraphicsPathItem* pathItem = (*theGraph)[*it].connector.get(); + pathItem->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo(currentX, currentY); + if (currentColumn == static_cast(columnFromMask((*theGraph)[target].column))) { + path.lineTo(currentX, dependentY); // straight connector in y. + } + else { + // connector with bend. + qreal radius = pointSpacing / 1.9; // no zero length line. + + path.lineTo(currentX, dependentY + radius * direction); + + qreal yPosition; + if (direction == -1.0) { + yPosition = dependentY - 2.0 * radius; + } + else { + yPosition = dependentY; + } + qreal width = 2.0 * radius; + qreal height = width; + if (dependentX > currentX) // radius to the right. + { + QRectF arcRect(currentX, yPosition, width, height); + path.arcTo(arcRect, 180.0, 90.0 * -direction); + } + else // radius to the left. + { + QRectF arcRect(currentX - 2.0 * radius, yPosition, width, height); + path.arcTo(arcRect, 0.0, 90.0 * direction); + } + path.lineTo(dependentX, dependentY); + } + pathItem->setPath(path); + } + + currentRow++; + } + + // now that we have the graph drawn we know where to place icons and text. + qreal columnSpacing = (maxColumn * pointSpacing); + for (const auto& currentVertex : sorted) { + qreal localCurrentX = columnSpacing; + localCurrentX += pointToIcon; + auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get(); + QTransform visibleIconTransform = QTransform::fromTranslate(localCurrentX, 0.0); + visiblePixmap->setTransform(visiblePixmap->transform() * visibleIconTransform); + + localCurrentX += iconSize + iconToIcon; + auto statePixmap = (*theGraph)[currentVertex].stateIcon.get(); + QTransform stateIconTransform = QTransform::fromTranslate(localCurrentX, 0.0); + statePixmap->setTransform(statePixmap->transform() * stateIconTransform); + + localCurrentX += iconSize + iconToIcon; + auto pixmap = (*theGraph)[currentVertex].icon.get(); + QTransform iconTransform = QTransform::fromTranslate(localCurrentX, 0.0); + pixmap->setTransform(pixmap->transform() * iconTransform); + + localCurrentX += iconSize + iconToText; + auto text = (*theGraph)[currentVertex].text.get(); + QTransform textTransform = QTransform::fromTranslate(localCurrentX, 0.0); + text->setTransform(text->transform() * textTransform); + + auto rectangle = (*theGraph)[currentVertex].rectangle.get(); + QRectF rect = rectangle->rect(); + rect.setWidth(localCurrentX + maxTextLength + 2.0 * rowPadding); + rectangle->setRect(rect); + } + + // Modeling_Challenge_Casting_ta4 with 59 features: "Initialize DAG View time: 0.007" + // keeping algo simple with extra loops only added 0.002 to above number. + // std::cout << "Initialize DAG View time: " << Base::TimeElapsed::diffTimeF(startTime, + // Base::TimeElapsed()) << std::endl; + + // outputGraphviz(*theGraph, "./graphviz.dot"); graphDirty = false; - return; - } - //index the vertices in sort order. - int tempIndex = 0; - for (const auto ¤tVertex : sorted) - { - (*theGraph)[currentVertex].topoSortIndex = tempIndex; - tempIndex++; - } - - //draw graph(nodes and connectors). - int currentRow = 0; - int currentColumn = -1; //we know first column is going to be root so will be kicked up to 0. - int maxColumn = currentColumn; //used for determining offset of icons and text. - qreal maxTextLength = 0; - for (const auto ¤tVertex : sorted) - { - if (boost::out_degree(currentVertex, *theGraph) == 0) - currentColumn = 0; - else - { - //loop parents and find an acceptable column. - int farthestParentIndex = sorted.size(); - ColumnMask columnMask; - Path parentVertices; - OutEdgeIterator it, itEnd; - boost::tie(it, itEnd) = boost::out_edges(currentVertex, *theGraph); - for (;it != itEnd; ++it) - { -// std::cout << std::endl << "name: " << findRecord(currentVertex, *graphLink).DObject->Label.getValue() << std::endl; - - Vertex target = boost::target(*it, *theGraph); - parentVertices.push_back(target); - int currentParentIndex = (*theGraph)[target].topoSortIndex; - if (currentParentIndex < farthestParentIndex) - { - Path::const_iterator start = sorted.begin() + currentParentIndex + 1; // 1 after - Path::const_iterator end = sorted.begin() + (*theGraph)[currentVertex].topoSortIndex; // 1 before - Path::const_iterator it; - for (it = start; it != end; ++it) - { -// std::cout << " parent: " << findRecord(*it, *graphLink).DObject->Label.getValue() << std::endl; - - columnMask |= (*theGraph)[*it].column; - } - farthestParentIndex = currentParentIndex; - } - } - - //have to create a smaller subset to get through std::cout. -// std::bitset<8> testSet; -// for (unsigned int index = 0; index < testSet.size(); ++index) -// testSet[index]= columnMask[index]; -// std::cout << "mask for " << findRecord(currentVertex, *graphLink).DObject->Label.getValue() << " " << -// testSet.to_string() << std::endl; - - //now we should have a mask representing the columns that are being used. - //this is from the lowest parent, in the topo sort, to last entry. - - //try to use the same column as one of the parents.(*theGraph)[*it].column - int destinationColumn = 0; //default to first column - for (const auto ¤tParent : parentVertices) - { - if (((*theGraph)[currentParent].column & columnMask).none()) - { - //go with first visible parent for now. - destinationColumn = static_cast(columnFromMask((*theGraph)[currentParent].column)); - break; - } - } - //if destination not valid look for the first open column. - if (columnMask.test(destinationColumn)) - { - for (std::size_t index = 0; index < columnMask.size(); ++index) - { - if (! columnMask.test(index)) - { - destinationColumn = index; - break; - } - } - } - - currentColumn = destinationColumn; - } - - assert(currentColumn < static_cast(ColumnMask().size())); //temp limitation. - - maxColumn = std::max(currentColumn, maxColumn); - QBrush currentBrush(forgroundBrushes.at(currentColumn % forgroundBrushes.size())); - - auto rectangle = (*theGraph)[currentVertex].rectangle.get(); - rectangle->setRect(-rowPadding, 0.0, rowPadding, rowHeight); //calculate actual length later. - rectangle->setTransform(QTransform::fromTranslate(0, rowHeight * currentRow)); - rectangle->setBackgroundBrush(backgroundBrushes[currentRow % backgroundBrushes.size()]); - - auto point = (*theGraph)[currentVertex].point.get(); - point->setRect(0.0, 0.0, pointSize, pointSize); - point->setTransform(QTransform::fromTranslate(pointSpacing * static_cast(currentColumn), - rowHeight * currentRow + rowHeight / 2.0 - pointSize / 2.0)); - point->setBrush(currentBrush); - - qreal cheat = 0.0; - if (direction == -1) - cheat = rowHeight; - - auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get(); - visiblePixmap->setTransform(QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat)); //calculate x location later. - - auto statePixmap = (*theGraph)[currentVertex].stateIcon.get(); - statePixmap->setTransform(QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat)); //calculate x location later. - - auto pixmap = (*theGraph)[currentVertex].icon.get(); - pixmap->setTransform(QTransform::fromTranslate(0.0, rowHeight * currentRow + cheat)); //calculate x location later. - - auto text = (*theGraph)[currentVertex].text.get(); - text->setPlainText(QString::fromUtf8(findRecord(currentVertex, *graphLink).DObject->Label.getValue())); - text->setDefaultTextColor(currentBrush.color()); - maxTextLength = std::max(maxTextLength, text->boundingRect().width()); - text->setTransform(QTransform::fromTranslate - (0.0, rowHeight * currentRow - verticalSpacing * 2.0 + cheat)); //calculate x location later. - (*theGraph)[currentVertex].lastVisibleState = VisibilityState::None; //force visual update for color. - - //store column and row int the graph. use for connectors later. - (*theGraph)[currentVertex].row = currentRow; - (*theGraph)[currentVertex].column.reset().set((currentColumn)); - - //our list is topo sorted so all dependents should be located, so we can build the connectors. - //will have some more logic for connector path, simple for now. - qreal currentX = pointSpacing * currentColumn + pointSize / 2.0; - qreal currentY = rowHeight * currentRow + rowHeight / 2.0; - OutEdgeIterator it, itEnd; - boost::tie(it, itEnd) = boost::out_edges(currentVertex, *theGraph); - for (; it != itEnd; ++it) - { - Vertex target = boost::target(*it, *theGraph); - qreal dependentX = pointSpacing * static_cast(columnFromMask((*theGraph)[target].column)) + pointSize / 2.0; //on center. - columnFromMask((*theGraph)[target].column); - qreal dependentY = rowHeight * (*theGraph)[target].row + rowHeight / 2.0; - - QGraphicsPathItem *pathItem = (*theGraph)[*it].connector.get(); - pathItem->setBrush(Qt::NoBrush); - QPainterPath path; - path.moveTo(currentX, currentY); - if (currentColumn == static_cast(columnFromMask((*theGraph)[target].column))) - path.lineTo(currentX, dependentY); //straight connector in y. - else - { - //connector with bend. - qreal radius = pointSpacing / 1.9; //no zero length line. - - path.lineTo(currentX, dependentY + radius * direction); - - qreal yPosition; - if (direction == -1.0) - yPosition = dependentY - 2.0 * radius; - else - yPosition = dependentY; - qreal width = 2.0 * radius; - qreal height = width; - if (dependentX > currentX) //radius to the right. - { - QRectF arcRect(currentX, yPosition, width, height); - path.arcTo(arcRect, 180.0, 90.0 * -direction); - } - else //radius to the left. - { - QRectF arcRect(currentX - 2.0 * radius, yPosition, width, height); - path.arcTo(arcRect, 0.0, 90.0 * direction); - } - path.lineTo(dependentX, dependentY); - } - pathItem->setPath(path); - } - - currentRow++; - } - - //now that we have the graph drawn we know where to place icons and text. - qreal columnSpacing = (maxColumn * pointSpacing); - for (const auto ¤tVertex : sorted) - { - qreal localCurrentX = columnSpacing; - localCurrentX += pointToIcon; - auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get(); - QTransform visibleIconTransform = QTransform::fromTranslate(localCurrentX, 0.0); - visiblePixmap->setTransform(visiblePixmap->transform() * visibleIconTransform); - - localCurrentX += iconSize + iconToIcon; - auto statePixmap = (*theGraph)[currentVertex].stateIcon.get(); - QTransform stateIconTransform = QTransform::fromTranslate(localCurrentX, 0.0); - statePixmap->setTransform(statePixmap->transform() * stateIconTransform); - - localCurrentX += iconSize + iconToIcon; - auto pixmap = (*theGraph)[currentVertex].icon.get(); - QTransform iconTransform = QTransform::fromTranslate(localCurrentX, 0.0); - pixmap->setTransform(pixmap->transform() * iconTransform); - - localCurrentX += iconSize + iconToText; - auto text = (*theGraph)[currentVertex].text.get(); - QTransform textTransform = QTransform::fromTranslate(localCurrentX, 0.0); - text->setTransform(text->transform() * textTransform); - - auto rectangle = (*theGraph)[currentVertex].rectangle.get(); - QRectF rect = rectangle->rect(); - rect.setWidth(localCurrentX + maxTextLength + 2.0 * rowPadding); - rectangle->setRect(rect); - } - - //Modeling_Challenge_Casting_ta4 with 59 features: "Initialize DAG View time: 0.007" - //keeping algo simple with extra loops only added 0.002 to above number. -// std::cout << "Initialize DAG View time: " << Base::TimeElapsed::diffTimeF(startTime, Base::TimeElapsed()) << std::endl; - -// outputGraphviz(*theGraph, "./graphviz.dot"); - graphDirty = false; } void Model::indexVerticesEdges() { - std::size_t index = 0; + std::size_t index = 0; - //index vertices. - VertexIterator it, itEnd; - for(boost::tie(it, itEnd) = boost::vertices(*theGraph); it != itEnd; ++it) - { - boost::put(boost::vertex_index, *theGraph, *it, index); - index++; - } + // index vertices. + VertexIterator it, itEnd; + for (boost::tie(it, itEnd) = boost::vertices(*theGraph); it != itEnd; ++it) { + boost::put(boost::vertex_index, *theGraph, *it, index); + index++; + } - //index edges. didn't need this when I put it in. - EdgeIterator eit, eitEnd; - index = 0; - for(boost::tie(eit, eitEnd) = boost::edges(*theGraph); eit != eitEnd; ++eit) - { - boost::put(boost::edge_index, *theGraph, *eit, index); - index++; - } + // index edges. didn't need this when I put it in. + EdgeIterator eit, eitEnd; + index = 0; + for (boost::tie(eit, eitEnd) = boost::edges(*theGraph); eit != eitEnd; ++eit) { + boost::put(boost::edge_index, *theGraph, *eit, index); + index++; + } } void Model::removeAllItems() { - if (theGraph) - { - BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) - removeVertexItemsFromScene(currentVertex); + if (theGraph) { + BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) + removeVertexItemsFromScene(currentVertex); - BGL_FORALL_EDGES(currentEdge, *theGraph, Graph) - { - if ((*theGraph)[currentEdge].connector->scene()) - this->removeItem((*theGraph)[currentEdge].connector.get()); + BGL_FORALL_EDGES(currentEdge, *theGraph, Graph) + { + if ((*theGraph)[currentEdge].connector->scene()) { + this->removeItem((*theGraph)[currentEdge].connector.get()); + } + } } - } } void Model::addVertexItemsToScene(const Gui::DAG::Vertex& vertexIn) { - //these are either all in or all out. so just test rectangle. - if ((*theGraph)[vertexIn].rectangle->scene()) //already in the scene. - return; - this->addItem((*theGraph)[vertexIn].rectangle.get()); - this->addItem((*theGraph)[vertexIn].point.get()); - this->addItem((*theGraph)[vertexIn].visibleIcon.get()); - this->addItem((*theGraph)[vertexIn].stateIcon.get()); - this->addItem((*theGraph)[vertexIn].icon.get()); - this->addItem((*theGraph)[vertexIn].text.get()); + // these are either all in or all out. so just test rectangle. + if ((*theGraph)[vertexIn].rectangle->scene()) { // already in the scene. + return; + } + this->addItem((*theGraph)[vertexIn].rectangle.get()); + this->addItem((*theGraph)[vertexIn].point.get()); + this->addItem((*theGraph)[vertexIn].visibleIcon.get()); + this->addItem((*theGraph)[vertexIn].stateIcon.get()); + this->addItem((*theGraph)[vertexIn].icon.get()); + this->addItem((*theGraph)[vertexIn].text.get()); } void Model::removeVertexItemsFromScene(const Gui::DAG::Vertex& vertexIn) { - //these are either all in or all out. so just test rectangle. - if (!(*theGraph)[vertexIn].rectangle->scene()) //not in the scene. - return; - this->removeItem((*theGraph)[vertexIn].rectangle.get()); - this->removeItem((*theGraph)[vertexIn].point.get()); - this->removeItem((*theGraph)[vertexIn].visibleIcon.get()); - this->removeItem((*theGraph)[vertexIn].stateIcon.get()); - this->removeItem((*theGraph)[vertexIn].text.get()); - this->removeItem((*theGraph)[vertexIn].icon.get()); + // these are either all in or all out. so just test rectangle. + if (!(*theGraph)[vertexIn].rectangle->scene()) { // not in the scene. + return; + } + this->removeItem((*theGraph)[vertexIn].rectangle.get()); + this->removeItem((*theGraph)[vertexIn].point.get()); + this->removeItem((*theGraph)[vertexIn].visibleIcon.get()); + this->removeItem((*theGraph)[vertexIn].stateIcon.get()); + this->removeItem((*theGraph)[vertexIn].text.get()); + this->removeItem((*theGraph)[vertexIn].icon.get()); } void Model::updateStates() { - //not sure I want to use the same pixmap merge for failing feature icons. - //thinking maybe red background or another column of icons for state? + // not sure I want to use the same pixmap merge for failing feature icons. + // thinking maybe red background or another column of icons for state? - BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) - { - const GraphLinkRecord &record = findRecord(currentVertex, *graphLink); - - auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get(); - VisibilityState currentVisibilityState = (record.VPDObject->isShow()) ? (VisibilityState::On) : (VisibilityState::Off); - if - ( - (currentVisibilityState != (*theGraph)[currentVertex].lastVisibleState) || - ((*theGraph)[currentVertex].lastVisibleState == VisibilityState::None) - ) + BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) { - if (record.VPDObject->isShow()) - visiblePixmap->setPixmap(visiblePixmapEnabled); - else - visiblePixmap->setPixmap(visiblePixmapDisabled); - (*theGraph)[currentVertex].lastVisibleState = currentVisibilityState; - } + const GraphLinkRecord& record = findRecord(currentVertex, *graphLink); - FeatureState currentFeatureState = FeatureState::Pass; - if (record.DObject->isError()) - currentFeatureState = FeatureState::Fail; - else if ((record.DObject->mustExecute() == 1)) - currentFeatureState = FeatureState::Pending; - if (currentFeatureState != (*theGraph)[currentVertex].lastFeatureState) - { - if (currentFeatureState == FeatureState::Pass) - { - (*theGraph)[currentVertex].stateIcon->setPixmap(passPixmap); - } - else - { - if (currentFeatureState == FeatureState::Fail) - (*theGraph)[currentVertex].stateIcon->setPixmap(failPixmap); - else - (*theGraph)[currentVertex].stateIcon->setPixmap(pendingPixmap); - } - (*theGraph)[currentVertex].stateIcon->setToolTip(QString::fromLatin1(record.DObject->getStatusString())); - (*theGraph)[currentVertex].lastFeatureState = currentFeatureState; + auto visiblePixmap = (*theGraph)[currentVertex].visibleIcon.get(); + VisibilityState currentVisibilityState = (record.VPDObject->isShow()) + ? (VisibilityState::On) + : (VisibilityState::Off); + if ((currentVisibilityState != (*theGraph)[currentVertex].lastVisibleState) + || ((*theGraph)[currentVertex].lastVisibleState == VisibilityState::None)) { + if (record.VPDObject->isShow()) { + visiblePixmap->setPixmap(visiblePixmapEnabled); + } + else { + visiblePixmap->setPixmap(visiblePixmapDisabled); + } + (*theGraph)[currentVertex].lastVisibleState = currentVisibilityState; + } + + FeatureState currentFeatureState = FeatureState::Pass; + if (record.DObject->isError()) { + currentFeatureState = FeatureState::Fail; + } + else if ((record.DObject->mustExecute() == 1)) { + currentFeatureState = FeatureState::Pending; + } + if (currentFeatureState != (*theGraph)[currentVertex].lastFeatureState) { + if (currentFeatureState == FeatureState::Pass) { + (*theGraph)[currentVertex].stateIcon->setPixmap(passPixmap); + } + else { + if (currentFeatureState == FeatureState::Fail) { + (*theGraph)[currentVertex].stateIcon->setPixmap(failPixmap); + } + else { + (*theGraph)[currentVertex].stateIcon->setPixmap(pendingPixmap); + } + } + (*theGraph)[currentVertex].stateIcon->setToolTip( + QString::fromLatin1(record.DObject->getStatusString()) + ); + (*theGraph)[currentVertex].lastFeatureState = currentFeatureState; + } } - } } -std::size_t Model::columnFromMask(const ColumnMask &maskIn) +std::size_t Model::columnFromMask(const ColumnMask& maskIn) { - std::string maskString = maskIn.to_string(); - return maskString.size() - maskString.find('1') - 1; + std::string maskString = maskIn.to_string(); + return maskString.size() - maskString.find('1') - 1; } RectItem* Model::getRectFromPosition(const QPointF& position) { - RectItem *rect = nullptr; - auto theItems = this->items(position, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder); - for (auto currentItem : theItems) - { - rect = dynamic_cast(currentItem); - if (rect) break; - } + RectItem* rect = nullptr; + auto theItems = this->items(position, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder); + for (auto currentItem : theItems) { + rect = dynamic_cast(currentItem); + if (rect) { + break; + } + } - return rect; + return rect; } void Model::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { - auto clearPrehighlight = [this]() - { - if (currentPrehighlight) - { - currentPrehighlight->preHighlightOff(); - currentPrehighlight = nullptr; + auto clearPrehighlight = [this]() { + if (currentPrehighlight) { + currentPrehighlight->preHighlightOff(); + currentPrehighlight = nullptr; + } + }; + + RectItem* rect = getRectFromPosition(event->scenePos()); + if (!rect) { + clearPrehighlight(); + return; + } + + if (rect == currentPrehighlight) { + return; } - }; - RectItem *rect = getRectFromPosition(event->scenePos()); - if (!rect) - { clearPrehighlight(); - return; - } + rect->preHighlightOn(); + currentPrehighlight = rect; + invalidate(); - if (rect == currentPrehighlight) - return; - - clearPrehighlight(); - rect->preHighlightOn(); - currentPrehighlight = rect; - invalidate(); - - QGraphicsScene::mouseMoveEvent(event); + QGraphicsScene::mouseMoveEvent(event); } void Model::mousePressEvent(QGraphicsSceneMouseEvent* event) { - auto goShiftSelect = [this, event]() - { - QPointF currentPickPoint = event->scenePos(); - QGraphicsLineItem intersectionLine(QLineF(lastPick, currentPickPoint)); - QListselection = collidingItems(&intersectionLine); - for (auto currentItem : selection) - { - auto rect = dynamic_cast(currentItem); - if (!rect) continue; - const GraphLinkRecord &selectionRecord = findRecord(rect, *graphLink); - Gui::Selection().addSelection(selectionRecord.DObject->getDocument()->getName(), - selectionRecord.DObject->getNameInDocument()); - } - }; - - auto toggleSelect = [](const App::DocumentObject *dObjectIn, RectItem *rectIn) - { - if (rectIn->isSelected()) - Gui::Selection().rmvSelection(dObjectIn->getDocument()->getName(), dObjectIn->getNameInDocument()); - else - Gui::Selection().addSelection(dObjectIn->getDocument()->getName(), dObjectIn->getNameInDocument()); - }; - - if (proxy) - renameAcceptedSlot(); - - if (event->button() == Qt::LeftButton) - { - RectItem *rect = getRectFromPosition(event->scenePos()); - if (rect) - { - const GraphLinkRecord &record = findRecord(rect, *graphLink); - - //don't like that I am doing this again here after getRectFromPosition call. - QGraphicsItem *item = itemAt(event->scenePos(), QTransform()); - auto pixmapItem = dynamic_cast(item); - if (pixmapItem && (pixmapItem == (*theGraph)[record.vertex].visibleIcon.get())) - { - //get all selections, but for now just the current pick. - if ((*theGraph)[record.vertex].lastVisibleState == VisibilityState::Off) - const_cast(record.VPDObject)->show(); //const hack - else - const_cast(record.VPDObject)->hide(); //const hack - - return; + auto goShiftSelect = [this, event]() { + QPointF currentPickPoint = event->scenePos(); + QGraphicsLineItem intersectionLine(QLineF(lastPick, currentPickPoint)); + QList selection = collidingItems(&intersectionLine); + for (auto currentItem : selection) { + auto rect = dynamic_cast(currentItem); + if (!rect) { + continue; + } + const GraphLinkRecord& selectionRecord = findRecord(rect, *graphLink); + Gui::Selection().addSelection( + selectionRecord.DObject->getDocument()->getName(), + selectionRecord.DObject->getNameInDocument() + ); } + }; - const App::DocumentObject *dObject = record.DObject; - if (selectionMode == SelectionMode::Single) - { - if (event->modifiers() & Qt::ControlModifier) - { - toggleSelect(dObject, rect); - } - else if((event->modifiers() & Qt::ShiftModifier) && lastPickValid) - { - goShiftSelect(); - } - else - { - Gui::Selection().clearSelection(dObject->getDocument()->getName()); - Gui::Selection().addSelection(dObject->getDocument()->getName(), dObject->getNameInDocument()); - } + auto toggleSelect = [](const App::DocumentObject* dObjectIn, RectItem* rectIn) { + if (rectIn->isSelected()) { + Gui::Selection().rmvSelection( + dObjectIn->getDocument()->getName(), + dObjectIn->getNameInDocument() + ); } - if (selectionMode == SelectionMode::Multiple) - { - if((event->modifiers() & Qt::ShiftModifier) && lastPickValid) - { - goShiftSelect(); - } - else - { - toggleSelect(dObject, rect); - } + else { + Gui::Selection().addSelection( + dObjectIn->getDocument()->getName(), + dObjectIn->getNameInDocument() + ); } - lastPickValid = true; - lastPick = event->scenePos(); - } - else - { - lastPickValid = false; - Gui::Selection().clearSelection(); //get document name? - } - } + }; - QGraphicsScene::mousePressEvent(event); + if (proxy) { + renameAcceptedSlot(); + } + + if (event->button() == Qt::LeftButton) { + RectItem* rect = getRectFromPosition(event->scenePos()); + if (rect) { + const GraphLinkRecord& record = findRecord(rect, *graphLink); + + // don't like that I am doing this again here after getRectFromPosition call. + QGraphicsItem* item = itemAt(event->scenePos(), QTransform()); + auto pixmapItem = dynamic_cast(item); + if (pixmapItem && (pixmapItem == (*theGraph)[record.vertex].visibleIcon.get())) { + // get all selections, but for now just the current pick. + if ((*theGraph)[record.vertex].lastVisibleState == VisibilityState::Off) { + const_cast(record.VPDObject)->show(); // const hack + } + else { + const_cast(record.VPDObject)->hide(); // const hack + } + + return; + } + + const App::DocumentObject* dObject = record.DObject; + if (selectionMode == SelectionMode::Single) { + if (event->modifiers() & Qt::ControlModifier) { + toggleSelect(dObject, rect); + } + else if ((event->modifiers() & Qt::ShiftModifier) && lastPickValid) { + goShiftSelect(); + } + else { + Gui::Selection().clearSelection(dObject->getDocument()->getName()); + Gui::Selection().addSelection( + dObject->getDocument()->getName(), + dObject->getNameInDocument() + ); + } + } + if (selectionMode == SelectionMode::Multiple) { + if ((event->modifiers() & Qt::ShiftModifier) && lastPickValid) { + goShiftSelect(); + } + else { + toggleSelect(dObject, rect); + } + } + lastPickValid = true; + lastPick = event->scenePos(); + } + else { + lastPickValid = false; + Gui::Selection().clearSelection(); // get document name? + } + } + + QGraphicsScene::mousePressEvent(event); } void Model::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { - if (event->button() == Qt::LeftButton) - { - auto selections = getAllSelected(); - if(selections.size() != 1) - return; - const GraphLinkRecord &record = findRecord(selections.front(), *graphLink); - Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument()); - MDIView *view = doc->getActiveView(); - if (view) - getMainWindow()->setActiveWindow(view); - const_cast(record.VPDObject)->doubleClicked(); - } + if (event->button() == Qt::LeftButton) { + auto selections = getAllSelected(); + if (selections.size() != 1) { + return; + } + const GraphLinkRecord& record = findRecord(selections.front(), *graphLink); + Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument()); + MDIView* view = doc->getActiveView(); + if (view) { + getMainWindow()->setActiveWindow(view); + } + const_cast(record.VPDObject)->doubleClicked(); + } - QGraphicsScene::mouseDoubleClickEvent(event); + QGraphicsScene::mouseDoubleClickEvent(event); } std::vector Model::getAllSelected() { - std::vector out; + std::vector out; - BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) - { - if ((*theGraph)[currentVertex].rectangle->isSelected()) - out.push_back(currentVertex); - } + BGL_FORALL_VERTICES(currentVertex, *theGraph, Graph) + { + if ((*theGraph)[currentVertex].rectangle->isSelected()) { + out.push_back(currentVertex); + } + } - return out; + return out; } void Model::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) { - RectItem *rect = getRectFromPosition(event->scenePos()); - if (rect) - { - const GraphLinkRecord &record = findRecord(rect, *graphLink); + RectItem* rect = getRectFromPosition(event->scenePos()); + if (rect) { + const GraphLinkRecord& record = findRecord(rect, *graphLink); - //don't like that I am doing this again here after getRectFromPosition call. - QGraphicsItem *item = itemAt(event->scenePos(), QTransform()); - auto pixmapItem = dynamic_cast(item); - if (pixmapItem && (pixmapItem == (*theGraph)[record.vertex].visibleIcon.get())) - { - visiblyIsolate(record.vertex); - return; + // don't like that I am doing this again here after getRectFromPosition call. + QGraphicsItem* item = itemAt(event->scenePos(), QTransform()); + auto pixmapItem = dynamic_cast(item); + if (pixmapItem && (pixmapItem == (*theGraph)[record.vertex].visibleIcon.get())) { + visiblyIsolate(record.vertex); + return; + } + + if (!rect->isSelected()) { + Gui::Selection().clearSelection(record.DObject->getDocument()->getName()); + Gui::Selection().addSelection( + record.DObject->getDocument()->getName(), + record.DObject->getNameInDocument() + ); + lastPickValid = true; + lastPick = event->scenePos(); + } + + MenuItem view; + Gui::Application::Instance->setupContextMenu("Tree", &view); + QMenu contextMenu; + MenuManager::getInstance()->setupContextMenu(&view, contextMenu); + + // actions for only one selection. + std::vector selections = getAllSelected(); + if (selections.size() == 1) { + contextMenu.addAction(renameAction); + // when we have only one selection then we know it is rect from above. + if (!rect->isEditing()) { + const_cast(record.VPDObject) + ->setupContextMenu(&contextMenu, this, SLOT(editingStartSlot())); // const hack. + } + else { + contextMenu.addAction(editingFinishedAction); + } + } + + if (!contextMenu.actions().isEmpty()) { + contextMenu.exec(event->screenPos()); + } } - if (!rect->isSelected()) - { - Gui::Selection().clearSelection(record.DObject->getDocument()->getName()); - Gui::Selection().addSelection(record.DObject->getDocument()->getName(), record.DObject->getNameInDocument()); - lastPickValid = true; - lastPick = event->scenePos(); - } - - MenuItem view; - Gui::Application::Instance->setupContextMenu("Tree", &view); - QMenu contextMenu; - MenuManager::getInstance()->setupContextMenu(&view, contextMenu); - - //actions for only one selection. - std::vector selections = getAllSelected(); - if (selections.size() == 1) - { - contextMenu.addAction(renameAction); - //when we have only one selection then we know it is rect from above. - if (!rect->isEditing()) - const_cast(record.VPDObject)->setupContextMenu - (&contextMenu, this, SLOT(editingStartSlot())); //const hack. - else - contextMenu.addAction(editingFinishedAction); - } - - if (!contextMenu.actions().isEmpty()) - contextMenu.exec(event->screenPos()); - } - - QGraphicsScene::contextMenuEvent(event); + QGraphicsScene::contextMenuEvent(event); } void Model::onRenameSlot() { - assert(!proxy); - std::vector selections = getAllSelected(); - assert(selections.size() == 1); + assert(!proxy); + std::vector selections = getAllSelected(); + assert(selections.size() == 1); - auto lineEdit = new LineEdit(); - auto text = (*theGraph)[selections.front()].text.get(); - lineEdit->setText(text->toPlainText()); - connect(lineEdit, &LineEdit::acceptedSignal, this, &Model::renameAcceptedSlot); - connect(lineEdit, &LineEdit::rejectedSignal, this, &Model::renameRejectedSlot); + auto lineEdit = new LineEdit(); + auto text = (*theGraph)[selections.front()].text.get(); + lineEdit->setText(text->toPlainText()); + connect(lineEdit, &LineEdit::acceptedSignal, this, &Model::renameAcceptedSlot); + connect(lineEdit, &LineEdit::rejectedSignal, this, &Model::renameRejectedSlot); - proxy = this->addWidget(lineEdit); - proxy->setGeometry(text->sceneBoundingRect()); + proxy = this->addWidget(lineEdit); + proxy->setGeometry(text->sceneBoundingRect()); - lineEdit->selectAll(); - QTimer::singleShot(0, lineEdit, qOverload<>(&QLineEdit::setFocus)); + lineEdit->selectAll(); + QTimer::singleShot(0, lineEdit, qOverload<>(&QLineEdit::setFocus)); } void Model::renameAcceptedSlot() { - assert(proxy); + assert(proxy); - std::vector selections = getAllSelected(); - assert(selections.size() == 1); - const GraphLinkRecord &record = findRecord(selections.front(), *graphLink); + std::vector selections = getAllSelected(); + assert(selections.size() == 1); + const GraphLinkRecord& record = findRecord(selections.front(), *graphLink); - auto lineEdit = qobject_cast(proxy->widget()); - assert(lineEdit); - const_cast(record.DObject)->Label.setValue(lineEdit->text().toUtf8().constData()); //const hack + auto lineEdit = qobject_cast(proxy->widget()); + assert(lineEdit); + const_cast(record.DObject) + ->Label.setValue(lineEdit->text().toUtf8().constData()); // const hack - finishRename(); + finishRename(); } void Model::renameRejectedSlot() { - finishRename(); + finishRename(); } void Model::finishRename() { - assert(proxy); - this->removeItem(proxy); - proxy->deleteLater(); - proxy = nullptr; - this->invalidate(); + assert(proxy); + this->removeItem(proxy); + proxy->deleteLater(); + proxy = nullptr; + this->invalidate(); } void Model::editingStartSlot() { - auto action = qobject_cast(sender()); - if (action) - { - int edit = action->data().toInt(); - auto selections = getAllSelected(); - assert(selections.size() == 1); - const GraphLinkRecord &record = findRecord(selections.front(), *graphLink); - Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument()); - MDIView *view = doc->getActiveView(); - if (view) - getMainWindow()->setActiveWindow(view); - doc->setEdit(const_cast(record.VPDObject), edit); - } + auto action = qobject_cast(sender()); + if (action) { + int edit = action->data().toInt(); + auto selections = getAllSelected(); + assert(selections.size() == 1); + const GraphLinkRecord& record = findRecord(selections.front(), *graphLink); + Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument()); + MDIView* view = doc->getActiveView(); + if (view) { + getMainWindow()->setActiveWindow(view); + } + doc->setEdit(const_cast(record.VPDObject), edit); + } } void Model::editingFinishedSlot() { - auto selections = getAllSelected(); - assert(selections.size() == 1); - const GraphLinkRecord &record = findRecord(selections.front(), *graphLink); - Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument()); - doc->commitCommand(); - doc->resetEdit(); - doc->getDocument()->recompute(); + auto selections = getAllSelected(); + assert(selections.size() == 1); + const GraphLinkRecord& record = findRecord(selections.front(), *graphLink); + Gui::Document* doc = Gui::Application::Instance->getDocument(record.DObject->getDocument()); + doc->commitCommand(); + doc->resetEdit(); + doc->getDocument()->recompute(); } void Model::visiblyIsolate(Gui::DAG::Vertex sourceIn) { - auto buildSkipTypes = []() - { - std::vector out; - Base::Type type; - type = Base::Type::fromName("App::DocumentObjectGroup"); - if (!type.isBad()) out.push_back(type); - type = Base::Type::fromName("App::Part"); - if (!type.isBad()) out.push_back(type); - type = Base::Type::fromName("PartDesign::Body"); - if (!type.isBad()) out.push_back(type); + auto buildSkipTypes = []() { + std::vector out; + Base::Type type; + type = Base::Type::fromName("App::DocumentObjectGroup"); + if (!type.isBad()) { + out.push_back(type); + } + type = Base::Type::fromName("App::Part"); + if (!type.isBad()) { + out.push_back(type); + } + type = Base::Type::fromName("PartDesign::Body"); + if (!type.isBad()) { + out.push_back(type); + } - return out; - }; + return out; + }; - auto testSkipType = [](const App::DocumentObject *dObject, const std::vector &types) - { - for (const auto ¤tType : types) - { - if (dObject->isDerivedFrom(currentType)) - return true; + auto testSkipType = [](const App::DocumentObject* dObject, const std::vector& types) { + for (const auto& currentType : types) { + if (dObject->isDerivedFrom(currentType)) { + return true; + } + } + return false; + }; + + indexVerticesEdges(); + Path connectedVertices; + ConnectionVisitor visitor(connectedVertices); + boost::breadth_first_search(*theGraph, sourceIn, boost::visitor(visitor)); + boost::breadth_first_search(boost::make_reverse_graph(*theGraph), sourceIn, boost::visitor(visitor)); + + // note source vertex is added twice to Path. Once for each search. + static std::vector skipTypes = buildSkipTypes(); + for (const auto& currentVertex : connectedVertices) { + const GraphLinkRecord& record = findRecord(currentVertex, *graphLink); + if (testSkipType(record.DObject, skipTypes)) { + continue; + } + const_cast(record.VPDObject)->hide(); // const hack } - return false; - }; - indexVerticesEdges(); - Path connectedVertices; - ConnectionVisitor visitor(connectedVertices); - boost::breadth_first_search(*theGraph, sourceIn, boost::visitor(visitor)); - boost::breadth_first_search(boost::make_reverse_graph(*theGraph), sourceIn, boost::visitor(visitor)); - - //note source vertex is added twice to Path. Once for each search. - static std::vector skipTypes = buildSkipTypes(); - for (const auto ¤tVertex : connectedVertices) - { - const GraphLinkRecord &record = findRecord(currentVertex, *graphLink); - if (testSkipType(record.DObject, skipTypes)) - continue; - const_cast(record.VPDObject)->hide(); //const hack - } - - const GraphLinkRecord &sourceRecord = findRecord(sourceIn, *graphLink); - if (!testSkipType(sourceRecord.DObject, skipTypes)) - const_cast(sourceRecord.VPDObject)->show(); //const hack + const GraphLinkRecord& sourceRecord = findRecord(sourceIn, *graphLink); + if (!testSkipType(sourceRecord.DObject, skipTypes)) { + const_cast(sourceRecord.VPDObject)->show(); // const hack + } } diff --git a/src/Gui/DAGView/DAGModel.h b/src/Gui/DAGView/DAGModel.h index 1a32cc39d0..d0425814e4 100644 --- a/src/Gui/DAGView/DAGModel.h +++ b/src/Gui/DAGView/DAGModel.h @@ -42,125 +42,132 @@ class QGraphicsProxyWidget; namespace Gui { - class Document; - class ViewProviderDocumentObject; - class SelectionChanges; +class Document; +class ViewProviderDocumentObject; +class SelectionChanges; - namespace DAG - { - class LineEdit : public QLineEdit - { +namespace DAG +{ +class LineEdit: public QLineEdit +{ Q_OBJECT - public: - explicit LineEdit(QWidget *parentIn = nullptr); - Q_SIGNALS: - void acceptedSignal(); - void rejectedSignal(); - protected: +public: + explicit LineEdit(QWidget* parentIn = nullptr); +Q_SIGNALS: + void acceptedSignal(); + void rejectedSignal(); + +protected: void keyPressEvent(QKeyEvent*) override; - }; +}; - class Model : public QGraphicsScene - { - Q_OBJECT - public: - Model(QObject *parentIn, const Gui::Document &documentIn); - ~Model() override; - void awake(); //!< hooked up to event dispatcher for update when idle. - void selectionChanged(const SelectionChanges& msg); +class Model: public QGraphicsScene +{ + Q_OBJECT +public: + Model(QObject* parentIn, const Gui::Document& documentIn); + ~Model() override; + void awake(); //!< hooked up to event dispatcher for update when idle. + void selectionChanged(const SelectionChanges& msg); - protected: - void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; - void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override; +protected: + void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; + void mousePressEvent(QGraphicsSceneMouseEvent* event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; + void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override; - private Q_SLOTS: - void updateSlot(); - void onRenameSlot(); - void renameAcceptedSlot(); - void renameRejectedSlot(); - void editingStartSlot(); - void editingFinishedSlot(); +private Q_SLOTS: + void updateSlot(); + void onRenameSlot(); + void renameAcceptedSlot(); + void renameRejectedSlot(); + void editingStartSlot(); + void editingFinishedSlot(); - private: - Model() = default; - //documentObject slots. - using Connection = boost::signals2::connection; - Connection connectNewObject; - Connection connectDelObject; - Connection connectChgObject; - Connection connectRenObject; - Connection connectActObject; - Connection connectEdtObject; - Connection connectResObject; - Connection connectHltObject; - Connection connectExpObject; - void slotNewObject(const Gui::ViewProviderDocumentObject &VPDObjectIn); - void slotDeleteObject(const Gui::ViewProviderDocumentObject &VPDObjectIn); - void slotChangeObject(const Gui::ViewProviderDocumentObject &VPDObjectIn, const App::Property& propertyIn); - void slotInEdit(const Gui::ViewProviderDocumentObject &VPDObjectIn); - void slotResetEdit(const Gui::ViewProviderDocumentObject &VPDObjectIn); - void slotChangeIcon(const Gui::ViewProviderDocumentObject &VPDObjectIn, std::shared_ptr icon); +private: + Model() = default; + // documentObject slots. + using Connection = boost::signals2::connection; + Connection connectNewObject; + Connection connectDelObject; + Connection connectChgObject; + Connection connectRenObject; + Connection connectActObject; + Connection connectEdtObject; + Connection connectResObject; + Connection connectHltObject; + Connection connectExpObject; + void slotNewObject(const Gui::ViewProviderDocumentObject& VPDObjectIn); + void slotDeleteObject(const Gui::ViewProviderDocumentObject& VPDObjectIn); + void slotChangeObject( + const Gui::ViewProviderDocumentObject& VPDObjectIn, + const App::Property& propertyIn + ); + void slotInEdit(const Gui::ViewProviderDocumentObject& VPDObjectIn); + void slotResetEdit(const Gui::ViewProviderDocumentObject& VPDObjectIn); + void slotChangeIcon( + const Gui::ViewProviderDocumentObject& VPDObjectIn, + std::shared_ptr icon + ); - std::shared_ptr graphLink; - std::shared_ptr theGraph; - bool graphDirty; + std::shared_ptr graphLink; + std::shared_ptr theGraph; + bool graphDirty; - void indexVerticesEdges(); - void removeAllItems(); - void addVertexItemsToScene(const Vertex &vertexIn); - void removeVertexItemsFromScene(const Vertex &vertexIn); - void updateStates(); - std::size_t columnFromMask(const ColumnMask&); + void indexVerticesEdges(); + void removeAllItems(); + void addVertexItemsToScene(const Vertex& vertexIn); + void removeVertexItemsFromScene(const Vertex& vertexIn); + void updateStates(); + std::size_t columnFromMask(const ColumnMask&); - RectItem* getRectFromPosition(const QPointF &position); //!< can be nullptr + RectItem* getRectFromPosition(const QPointF& position); //!< can be nullptr //! @name View Constants for spacing //@{ - qreal fontHeight; //!< height of the current qApp default font. - qreal direction; //!< controls top to bottom or bottom to top direction. - qreal verticalSpacing; //!< pixels between top and bottom of text to background rectangle. - qreal rowHeight; //!< height of background rectangle. - qreal iconSize; //!< size of icon to match font. - qreal pointSize; //!< size of the connection point. - qreal pointSpacing; //!< spacing between pofloat columns. - qreal pointToIcon; //!< spacing from last column points to first icon. - qreal iconToIcon; //!< spacing between icons. - qreal iconToText; //!< spacing between last icon and text. - qreal rowPadding; //!< spaces added to rectangle background width ends. - std::vector backgroundBrushes; //!< brushes to paint background rectangles. - std::vector forgroundBrushes; //!< brushes to paint points, connectors, text. - void setupViewConstants(); + qreal fontHeight; //!< height of the current qApp default font. + qreal direction; //!< controls top to bottom or bottom to top direction. + qreal verticalSpacing; //!< pixels between top and bottom of text to background rectangle. + qreal rowHeight; //!< height of background rectangle. + qreal iconSize; //!< size of icon to match font. + qreal pointSize; //!< size of the connection point. + qreal pointSpacing; //!< spacing between pofloat columns. + qreal pointToIcon; //!< spacing from last column points to first icon. + qreal iconToIcon; //!< spacing between icons. + qreal iconToText; //!< spacing between last icon and text. + qreal rowPadding; //!< spaces added to rectangle background width ends. + std::vector backgroundBrushes; //!< brushes to paint background rectangles. + std::vector forgroundBrushes; //!< brushes to paint points, connectors, text. + void setupViewConstants(); //@} - RectItem *currentPrehighlight; + RectItem* currentPrehighlight; - enum class SelectionMode - { + enum class SelectionMode + { Single, Multiple - }; - SelectionMode selectionMode; - std::vector getAllSelected(); - void visiblyIsolate(Vertex sourceIn); //!< hide any connected feature and turn on sourceIn. - - QPointF lastPick; - bool lastPickValid = false; - - QPixmap visiblePixmapEnabled; - QPixmap visiblePixmapDisabled; - QPixmap passPixmap; - QPixmap failPixmap; - QPixmap pendingPixmap; - Vertex lastAddedVertex = Graph::null_vertex(); //!< needed because python objects are not ready. - - QAction *renameAction; - QAction *editingFinishedAction; - QGraphicsProxyWidget *proxy = nullptr; - void finishRename(); }; - } -} + SelectionMode selectionMode; + std::vector getAllSelected(); + void visiblyIsolate(Vertex sourceIn); //!< hide any connected feature and turn on sourceIn. -#endif // DAGMODEL_H + QPointF lastPick; + bool lastPickValid = false; + + QPixmap visiblePixmapEnabled; + QPixmap visiblePixmapDisabled; + QPixmap passPixmap; + QPixmap failPixmap; + QPixmap pendingPixmap; + Vertex lastAddedVertex = Graph::null_vertex(); //!< needed because python objects are not ready. + + QAction* renameAction; + QAction* editingFinishedAction; + QGraphicsProxyWidget* proxy = nullptr; + void finishRename(); +}; +} // namespace DAG +} // namespace Gui + +#endif // DAGMODEL_H diff --git a/src/Gui/DAGView/DAGModelGraph.cpp b/src/Gui/DAGView/DAGModelGraph.cpp index 55eeaa0487..f1af0df778 100644 --- a/src/Gui/DAGView/DAGModelGraph.cpp +++ b/src/Gui/DAGView/DAGModelGraph.cpp @@ -28,91 +28,103 @@ using namespace Gui; using namespace DAG; -VertexProperty::VertexProperty() : - rectangle(new RectItem()), - point(new QGraphicsEllipseItem()), - visibleIcon(new QGraphicsPixmapItem()), - stateIcon(new QGraphicsPixmapItem()), - icon(new QGraphicsPixmapItem()), - text(new QGraphicsTextItem()) +VertexProperty::VertexProperty() + : rectangle(new RectItem()) + , point(new QGraphicsEllipseItem()) + , visibleIcon(new QGraphicsPixmapItem()) + , stateIcon(new QGraphicsPixmapItem()) + , icon(new QGraphicsPixmapItem()) + , text(new QGraphicsTextItem()) { - //set z values. - this->rectangle->setZValue(-1000.0); - this->point->setZValue(1000.0); - this->visibleIcon->setZValue(0.0); - this->stateIcon->setZValue(0.0); - this->icon->setZValue(0.0); - this->text->setZValue(0.0); + // set z values. + this->rectangle->setZValue(-1000.0); + this->point->setZValue(1000.0); + this->visibleIcon->setZValue(0.0); + this->stateIcon->setZValue(0.0); + this->icon->setZValue(0.0); + this->text->setZValue(0.0); } EdgeProperty::EdgeProperty() = default; -bool Gui::DAG::hasRecord(const App::DocumentObject* dObjectIn, const GraphLinkContainer &containerIn) +bool Gui::DAG::hasRecord(const App::DocumentObject* dObjectIn, const GraphLinkContainer& containerIn) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(dObjectIn); - return it != list.end(); + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(dObjectIn); + return it != list.end(); } -bool Gui::DAG::hasRecord(const ViewProviderDocumentObject* VPDObjectIn, const GraphLinkContainer &containerIn) +bool Gui::DAG::hasRecord( + const ViewProviderDocumentObject* VPDObjectIn, + const GraphLinkContainer& containerIn +) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(VPDObjectIn); - return it != list.end(); + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(VPDObjectIn); + return it != list.end(); } -const GraphLinkRecord& Gui::DAG::findRecord(Vertex vertexIn, const GraphLinkContainer &containerIn) +const GraphLinkRecord& Gui::DAG::findRecord(Vertex vertexIn, const GraphLinkContainer& containerIn) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(vertexIn); - assert(it != list.end()); - return *it; + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(vertexIn); + assert(it != list.end()); + return *it; } -const GraphLinkRecord& Gui::DAG::findRecord(const App::DocumentObject* dObjectIn, const GraphLinkContainer &containerIn) +const GraphLinkRecord& Gui::DAG::findRecord( + const App::DocumentObject* dObjectIn, + const GraphLinkContainer& containerIn +) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(dObjectIn); - assert(it != list.end()); - return *it; + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(dObjectIn); + assert(it != list.end()); + return *it; } -const GraphLinkRecord& Gui::DAG::findRecord(const ViewProviderDocumentObject* VPDObjectIn, const GraphLinkContainer &containerIn) +const GraphLinkRecord& Gui::DAG::findRecord( + const ViewProviderDocumentObject* VPDObjectIn, + const GraphLinkContainer& containerIn +) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(VPDObjectIn); - assert(it != list.end()); - return *it; + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(VPDObjectIn); + assert(it != list.end()); + return *it; } -const GraphLinkRecord& Gui::DAG::findRecord(const RectItem* rectIn, const GraphLinkContainer &containerIn) +const GraphLinkRecord& Gui::DAG::findRecord(const RectItem* rectIn, const GraphLinkContainer& containerIn) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(rectIn); - assert(it != list.end()); - return *it; + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(rectIn); + assert(it != list.end()); + return *it; } -const GraphLinkRecord& Gui::DAG::findRecord(const std::string &stringIn, const GraphLinkContainer &containerIn) +const GraphLinkRecord& Gui::DAG::findRecord( + const std::string& stringIn, + const GraphLinkContainer& containerIn +) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::const_iterator it = list.find(stringIn); - assert(it != list.end()); - return *it; + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::const_iterator it = list.find(stringIn); + assert(it != list.end()); + return *it; } -void Gui::DAG::eraseRecord(const ViewProviderDocumentObject* VPDObjectIn, GraphLinkContainer &containerIn) +void Gui::DAG::eraseRecord(const ViewProviderDocumentObject* VPDObjectIn, GraphLinkContainer& containerIn) { - using List = GraphLinkContainer::index::type; - const List &list = containerIn.get(); - List::iterator it = list.find(VPDObjectIn); - assert(it != list.end()); - containerIn.get().erase(it); + using List = GraphLinkContainer::index::type; + const List& list = containerIn.get(); + List::iterator it = list.find(VPDObjectIn); + assert(it != list.end()); + containerIn.get().erase(it); } diff --git a/src/Gui/DAGView/DAGModelGraph.h b/src/Gui/DAGView/DAGModelGraph.h index d1b0886187..ed19d7a7c1 100644 --- a/src/Gui/DAGView/DAGModelGraph.h +++ b/src/Gui/DAGView/DAGModelGraph.h @@ -41,257 +41,282 @@ #include "DAGRectItem.h" -namespace App{class DocumentObject;} +namespace App +{ +class DocumentObject; +} namespace Gui { - class ViewProviderDocumentObject; +class ViewProviderDocumentObject; - namespace DAG - { - enum class VisibilityState +namespace DAG +{ +enum class VisibilityState +{ + None = 0, //; + +/*! @brief Graph vertex information + * + * My data stored for each vertex; + */ +struct VertexProperty +{ + VertexProperty(); + std::shared_ptr rectangle; //!< background + std::shared_ptr point; //!< point + std::shared_ptr visibleIcon; //!< visible Icon + std::shared_ptr stateIcon; //!< visible Icon + std::shared_ptr icon; //!< icon + std::shared_ptr text; //!< text + boost::signals2::connection connChangeIcon; + int row = 0; //!< row for this entry. + ColumnMask column = 0; //!< column number containing the point. + int topoSortIndex = 0; + VisibilityState lastVisibleState = VisibilityState::None; //!< visibility test. + FeatureState lastFeatureState = FeatureState::None; //!< feature state test. +}; +/*! @brief boost data for each vertex. + * + * needed to create an internal index for vertex. needed for listS. + * color is needed by some algorithms */ +using vertex_prop = boost::property< + boost::vertex_index_t, + std::size_t, + boost::property>; + +/*! @brief Graph edge information + * + * My data stored for each edge; + */ +struct EdgeProperty +{ + //! Feature relation meta data. Not used right now. + enum class BranchTag { - None = 0, // connector; //!< line representing link between nodes. +}; +/*! @brief needed to create an internal index for graph edges. needed for setS.*/ +using edge_prop = boost::property; - enum class FeatureState +using Graph + = boost::adjacency_list; +using Vertex = boost::graph_traits::vertex_descriptor; +using Edge = boost::graph_traits::edge_descriptor; +using VertexIterator = boost::graph_traits::vertex_iterator; +using EdgeIterator = boost::graph_traits::edge_iterator; +using InEdgeIterator = boost::graph_traits::in_edge_iterator; +using OutEdgeIterator = boost::graph_traits::out_edge_iterator; +using VertexAdjacencyIterator = boost::graph_traits::adjacency_iterator; +using GraphReversed = boost::reverse_graph; +using Path = std::vector; //!< a path or any array of vertices + +template +class Edge_writer +{ +public: + explicit Edge_writer(const GraphEW& graphEWIn) + : graphEW(graphEWIn) + {} + template + void operator()(std::ostream& out, const EdgeW& /*edgeW*/) const { - None = 0, //; - - /*! @brief Graph vertex information - * - * My data stored for each vertex; - */ - struct VertexProperty - { - VertexProperty(); - std::shared_ptr rectangle; //!< background - std::shared_ptr point; //!< point - std::shared_ptr visibleIcon; //!< visible Icon - std::shared_ptr stateIcon; //!< visible Icon - std::shared_ptr icon; //!< icon - std::shared_ptr text; //!< text - boost::signals2::connection connChangeIcon; - int row = 0; //!< row for this entry. - ColumnMask column = 0; //!< column number containing the point. - int topoSortIndex = 0; - VisibilityState lastVisibleState = VisibilityState::None; //!< visibility test. - FeatureState lastFeatureState = FeatureState::None; //!< feature state test. - }; - /*! @brief boost data for each vertex. - * - * needed to create an internal index for vertex. needed for listS. - * color is needed by some algorithms */ - using vertex_prop = boost::property - < - boost::vertex_index_t, std::size_t, - boost::property - >; - - /*! @brief Graph edge information - * - * My data stored for each edge; - */ - struct EdgeProperty - { - //! Feature relation meta data. Not used right now. - enum class BranchTag - { - None = 0, //!< not defined. - Create, //!< create a new branch. - Continue, //!< continue a branch. - Terminate //!< terminate a branch. - }; - EdgeProperty(); - BranchTag relation = BranchTag::None; - std::shared_ptr connector; //!< line representing link between nodes. - }; - /*! @brief needed to create an internal index for graph edges. needed for setS.*/ - using edge_prop = boost::property; - - using Graph = boost::adjacency_list; - using Vertex = boost::graph_traits::vertex_descriptor; - using Edge = boost::graph_traits::edge_descriptor; - using VertexIterator = boost::graph_traits::vertex_iterator; - using EdgeIterator = boost::graph_traits::edge_iterator; - using InEdgeIterator = boost::graph_traits::in_edge_iterator; - using OutEdgeIterator = boost::graph_traits::out_edge_iterator; - using VertexAdjacencyIterator = boost::graph_traits::adjacency_iterator; - using GraphReversed = boost::reverse_graph; - using Path = std::vector; //!< a path or any array of vertices - - template - class Edge_writer { - public: - explicit Edge_writer(const GraphEW &graphEWIn) : graphEW(graphEWIn) {} - template - void operator()(std::ostream& out, const EdgeW& /*edgeW*/) const - { out << "[label=\""; out << "edge"; out << "\"]"; - } - private: - const GraphEW &graphEW; - }; + } - template - class Vertex_writer { - public: - explicit Vertex_writer(const GraphVW &graphVWIn) : graphVW(graphVWIn) {} - template - void operator()(std::ostream& out, const VertexW& vertexW) const - { +private: + const GraphEW& graphEW; +}; + +template +class Vertex_writer +{ +public: + explicit Vertex_writer(const GraphVW& graphVWIn) + : graphVW(graphVWIn) + {} + template + void operator()(std::ostream& out, const VertexW& vertexW) const + { out << "[label=\""; out << graphVW[vertexW].text->toPlainText().toLatin1().data(); out << "\"]"; - } - private: - const GraphVW &graphVW; - }; - - template - void outputGraphviz(const GraphIn &graphIn, const std::string &filePath) - { - std::ofstream file(filePath.c_str()); - boost::write_graphviz(file, graphIn, Vertex_writer(graphIn), - Edge_writer(graphIn)); } - //! get all the leaves of the templated graph. Not used right now. - template - class RakeLeaves - { - using GraphInVertex = boost::graph_traits::vertex_descriptor; - using GraphInVertices = std::vector; - public: - explicit RakeLeaves(const GraphIn &graphIn) : graph(graphIn) {} - GraphInVertices operator()() const - { - GraphInVertices out; - BGL_FORALL_VERTICES_T(currentVertex, graph, GraphIn) - { - if (boost::out_degree(currentVertex, graph) == 0) - out.push_back(currentVertex); - } - return out; - } - private: - const GraphIn &graph; - }; +private: + const GraphVW& graphVW; +}; - //! get all the roots of the templated graph. Not used right now. - template - class DigRoots - { - using GraphInVertex = boost::graph_traits::vertex_descriptor; - using GraphInVertices = std::vector; - public: - explicit DigRoots(const GraphIn &graphIn) : graph(graphIn) {} - GraphInVertices operator()() const - { - GraphInVertices out; - BGL_FORALL_VERTICES_T(currentVertex, graph, GraphIn) - { - if (boost::in_degree(currentVertex, graph) == 0) - out.push_back(currentVertex); - } - return out; - } - private: - const GraphIn &graph; - }; - - /*! @brief Get connected components. - */ - class ConnectionVisitor : public boost::default_bfs_visitor - { - public: - explicit ConnectionVisitor(std::vector &verticesIn) : vertices(verticesIn){} - - template - void discover_vertex(TVertex vertex, TGraph &graph) - { - Q_UNUSED(graph); - vertices.push_back(vertex); - } - private: - std::vector &vertices; - }; - - /*! Multi_index record. */ - struct GraphLinkRecord - { - const App::DocumentObject *DObject; //!< document object - const Gui::ViewProviderDocumentObject *VPDObject; //!< view provider - const RectItem *rectItem; //!< qgraphics item. - std::string uniqueName; //!< name for document object. - Vertex vertex; //!< vertex in graph. - - //@{ - //! used as tags. - struct ByDObject{}; - struct ByVPDObject{}; - struct ByRectItem{}; - struct ByUniqueName{}; - struct ByVertex{}; - //@} - }; - - namespace BMI = boost::multi_index; - using GraphLinkContainer = boost::multi_index_container - < - GraphLinkRecord, - BMI::indexed_by - < - BMI::ordered_unique - < - BMI::tag, - BMI::member - >, - BMI::ordered_unique - < - BMI::tag, - BMI::member - >, - BMI::ordered_unique - < - BMI::tag, - BMI::member - >, - BMI::ordered_unique - < - BMI::tag, - BMI::member - >, - BMI::ordered_unique - < - BMI::tag, - BMI::member - > - > - >; - - bool hasRecord(const App::DocumentObject* dObjectIn, const GraphLinkContainer &containerIn); - bool hasRecord(const ViewProviderDocumentObject* VPDObjectIn, const GraphLinkContainer &containerIn); - const GraphLinkRecord& findRecord(Vertex vertexIn, const GraphLinkContainer &containerIn); - const GraphLinkRecord& findRecord(const App::DocumentObject* dObjectIn, const GraphLinkContainer &containerIn); - const GraphLinkRecord& findRecord(const Gui::ViewProviderDocumentObject* VPDObjectIn, const GraphLinkContainer &containerIn); - const GraphLinkRecord& findRecord(const RectItem* rectIn, const GraphLinkContainer &containerIn); - const GraphLinkRecord& findRecord(const std::string &stringIn, const GraphLinkContainer &containerIn); - void eraseRecord(const Gui::ViewProviderDocumentObject* VPDObjectIn, GraphLinkContainer &containerIn); - } +template +void outputGraphviz(const GraphIn& graphIn, const std::string& filePath) +{ + std::ofstream file(filePath.c_str()); + boost::write_graphviz(file, graphIn, Vertex_writer(graphIn), Edge_writer(graphIn)); } -#endif // DAGMODELGRAPH_H +//! get all the leaves of the templated graph. Not used right now. +template +class RakeLeaves +{ + using GraphInVertex = boost::graph_traits::vertex_descriptor; + using GraphInVertices = std::vector; + +public: + explicit RakeLeaves(const GraphIn& graphIn) + : graph(graphIn) + {} + GraphInVertices operator()() const + { + GraphInVertices out; + BGL_FORALL_VERTICES_T(currentVertex, graph, GraphIn) + { + if (boost::out_degree(currentVertex, graph) == 0) { + out.push_back(currentVertex); + } + } + return out; + } + +private: + const GraphIn& graph; +}; + +//! get all the roots of the templated graph. Not used right now. +template +class DigRoots +{ + using GraphInVertex = boost::graph_traits::vertex_descriptor; + using GraphInVertices = std::vector; + +public: + explicit DigRoots(const GraphIn& graphIn) + : graph(graphIn) + {} + GraphInVertices operator()() const + { + GraphInVertices out; + BGL_FORALL_VERTICES_T(currentVertex, graph, GraphIn) + { + if (boost::in_degree(currentVertex, graph) == 0) { + out.push_back(currentVertex); + } + } + return out; + } + +private: + const GraphIn& graph; +}; + +/*! @brief Get connected components. + */ +class ConnectionVisitor: public boost::default_bfs_visitor +{ +public: + explicit ConnectionVisitor(std::vector& verticesIn) + : vertices(verticesIn) + {} + + template + void discover_vertex(TVertex vertex, TGraph& graph) + { + Q_UNUSED(graph); + vertices.push_back(vertex); + } + +private: + std::vector& vertices; +}; + +/*! Multi_index record. */ +struct GraphLinkRecord +{ + const App::DocumentObject* DObject; //!< document object + const Gui::ViewProviderDocumentObject* VPDObject; //!< view provider + const RectItem* rectItem; //!< qgraphics item. + std::string uniqueName; //!< name for document object. + Vertex vertex; //!< vertex in graph. + + //@{ + //! used as tags. + struct ByDObject + { + }; + struct ByVPDObject + { + }; + struct ByRectItem + { + }; + struct ByUniqueName + { + }; + struct ByVertex + { + }; + //@} +}; + +namespace BMI = boost::multi_index; +using GraphLinkContainer = boost::multi_index_container< + GraphLinkRecord, + BMI::indexed_by< + BMI::ordered_unique< + BMI::tag, + BMI::member>, + BMI::ordered_unique< + BMI::tag, + BMI::member>, + BMI::ordered_unique< + BMI::tag, + BMI::member>, + BMI::ordered_unique< + BMI::tag, + BMI::member>, + BMI::ordered_unique< + BMI::tag, + BMI::member>>>; + +bool hasRecord(const App::DocumentObject* dObjectIn, const GraphLinkContainer& containerIn); +bool hasRecord(const ViewProviderDocumentObject* VPDObjectIn, const GraphLinkContainer& containerIn); +const GraphLinkRecord& findRecord(Vertex vertexIn, const GraphLinkContainer& containerIn); +const GraphLinkRecord& findRecord( + const App::DocumentObject* dObjectIn, + const GraphLinkContainer& containerIn +); +const GraphLinkRecord& findRecord( + const Gui::ViewProviderDocumentObject* VPDObjectIn, + const GraphLinkContainer& containerIn +); +const GraphLinkRecord& findRecord(const RectItem* rectIn, const GraphLinkContainer& containerIn); +const GraphLinkRecord& findRecord(const std::string& stringIn, const GraphLinkContainer& containerIn); +void eraseRecord(const Gui::ViewProviderDocumentObject* VPDObjectIn, GraphLinkContainer& containerIn); +} // namespace DAG +} // namespace Gui + +#endif // DAGMODELGRAPH_H diff --git a/src/Gui/DAGView/DAGRectItem.cpp b/src/Gui/DAGView/DAGRectItem.cpp index 6db9b592d5..93074c1a73 100644 --- a/src/Gui/DAGView/DAGRectItem.cpp +++ b/src/Gui/DAGView/DAGRectItem.cpp @@ -33,46 +33,46 @@ using namespace Gui; using namespace DAG; -RectItem::RectItem(QGraphicsItem* parent) : QGraphicsRectItem(parent) +RectItem::RectItem(QGraphicsItem* parent) + : QGraphicsRectItem(parent) { - selected = false; - preSelected = false; - editing = false; + selected = false; + preSelected = false; + editing = false; } void RectItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) { - Q_UNUSED(option); - Q_UNUSED(widget); - painter->save(); + Q_UNUSED(option); + Q_UNUSED(widget); + painter->save(); - QStyleOptionViewItem styleOption; + QStyleOptionViewItem styleOption; - styleOption.backgroundBrush = backgroundBrush; - if (editing) - styleOption.backgroundBrush = editBrush; - else - { - styleOption.state |= QStyle::State_Enabled; - if (selected) - styleOption.state |= QStyle::State_Selected; - if (preSelected) - { - if (!selected) - { - styleOption.state |= QStyle::State_Selected; - QPalette palette = styleOption.palette; - QColor tempColor = palette.color(QPalette::Active, QPalette::Highlight); - tempColor.setAlphaF(0.15F); - palette.setColor(QPalette::Inactive, QPalette::Highlight, tempColor); - styleOption.palette = palette; - } - styleOption.state |= QStyle::State_MouseOver; + styleOption.backgroundBrush = backgroundBrush; + if (editing) { + styleOption.backgroundBrush = editBrush; } - } - styleOption.rect = this->rect().toRect(); + else { + styleOption.state |= QStyle::State_Enabled; + if (selected) { + styleOption.state |= QStyle::State_Selected; + } + if (preSelected) { + if (!selected) { + styleOption.state |= QStyle::State_Selected; + QPalette palette = styleOption.palette; + QColor tempColor = palette.color(QPalette::Active, QPalette::Highlight); + tempColor.setAlphaF(0.15F); + palette.setColor(QPalette::Inactive, QPalette::Highlight, tempColor); + styleOption.palette = palette; + } + styleOption.state |= QStyle::State_MouseOver; + } + } + styleOption.rect = this->rect().toRect(); - QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &styleOption, painter); + QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &styleOption, painter); - painter->restore(); + painter->restore(); } diff --git a/src/Gui/DAGView/DAGRectItem.h b/src/Gui/DAGView/DAGRectItem.h index 4bbd1c04c3..844bc8908c 100644 --- a/src/Gui/DAGView/DAGRectItem.h +++ b/src/Gui/DAGView/DAGRectItem.h @@ -30,37 +30,72 @@ namespace Gui { - namespace DAG - { - /*all right I give up! the parenting combined with the zvalues is fubar! - * you can't control any kind of layering between children of separate parents - */ - class RectItem : public QGraphicsRectItem +namespace DAG +{ +/*all right I give up! the parenting combined with the zvalues is fubar! + * you can't control any kind of layering between children of separate parents + */ +class RectItem: public QGraphicsRectItem +{ +public: + explicit RectItem(QGraphicsItem* parent = nullptr); + void setBackgroundBrush(const QBrush& brushIn) { - public: - explicit RectItem(QGraphicsItem* parent = nullptr); - void setBackgroundBrush(const QBrush &brushIn){backgroundBrush = brushIn;} - void setEditingBrush(const QBrush &brushIn){editBrush = brushIn;} - void preHighlightOn(){preSelected = true;} - void preHighlightOff(){preSelected = false;} - void selectionOn(){selected = true;} - void selectionOff(){selected = false;} - bool isSelected(){return selected;} - bool isPreSelected(){return preSelected;} - void editingStart(){editing = true;} - void editingFinished(){editing = false;} - bool isEditing(){return editing;} - protected: - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; - private: - QBrush backgroundBrush; //!< brush used for background. not used yet. - QBrush editBrush; //!< brush used when object is in edit mode. - //start with booleans, may expand to state. - bool selected; - bool preSelected; - bool editing; - }; - } -} + backgroundBrush = brushIn; + } + void setEditingBrush(const QBrush& brushIn) + { + editBrush = brushIn; + } + void preHighlightOn() + { + preSelected = true; + } + void preHighlightOff() + { + preSelected = false; + } + void selectionOn() + { + selected = true; + } + void selectionOff() + { + selected = false; + } + bool isSelected() + { + return selected; + } + bool isPreSelected() + { + return preSelected; + } + void editingStart() + { + editing = true; + } + void editingFinished() + { + editing = false; + } + bool isEditing() + { + return editing; + } -#endif // DAGRECTITEM_H +protected: + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; + +private: + QBrush backgroundBrush; //!< brush used for background. not used yet. + QBrush editBrush; //!< brush used when object is in edit mode. + // start with booleans, may expand to state. + bool selected; + bool preSelected; + bool editing; +}; +} // namespace DAG +} // namespace Gui + +#endif // DAGRECTITEM_H diff --git a/src/Gui/DAGView/DAGView.cpp b/src/Gui/DAGView/DAGView.cpp index b263c9d914..405983a53f 100644 --- a/src/Gui/DAGView/DAGView.cpp +++ b/src/Gui/DAGView/DAGView.cpp @@ -36,91 +36,101 @@ using namespace Gui; using namespace DAG; namespace sp = std::placeholders; -DAG::DockWindow::DockWindow(Gui::Document* gDocumentIn, QWidget* parent): Gui::DockWindow(gDocumentIn, parent) +DAG::DockWindow::DockWindow(Gui::Document* gDocumentIn, QWidget* parent) + : Gui::DockWindow(gDocumentIn, parent) { - dagView = new View(this); - auto layout = new QVBoxLayout(); - layout->addWidget(dagView); - this->setLayout(layout); + dagView = new View(this); + auto layout = new QVBoxLayout(); + layout->addWidget(dagView); + this->setLayout(layout); } -View::View(QWidget* parentIn): QGraphicsView(parentIn) +View::View(QWidget* parentIn) + : QGraphicsView(parentIn) { - this->setRenderHint(QPainter::Antialiasing, true); - this->setRenderHint(QPainter::TextAntialiasing, true); - //NOLINTBEGIN - conActive = Application::Instance->signalActiveDocument.connect(std::bind(&View::slotActiveDocument, this, sp::_1)); - conDelete = Application::Instance->signalDeleteDocument.connect(std::bind(&View::slotDeleteDocument, this, sp::_1)); - //NOLINTEND + this->setRenderHint(QPainter::Antialiasing, true); + this->setRenderHint(QPainter::TextAntialiasing, true); + // NOLINTBEGIN + conActive = Application::Instance->signalActiveDocument.connect( + std::bind(&View::slotActiveDocument, this, sp::_1) + ); + conDelete = Application::Instance->signalDeleteDocument.connect( + std::bind(&View::slotDeleteDocument, this, sp::_1) + ); + // NOLINTEND - //just update the dagview when the gui process is idle. - connect(QAbstractEventDispatcher::instance(), &QAbstractEventDispatcher::awake, - this, &View::awakeSlot); + // just update the dagview when the gui process is idle. + connect(QAbstractEventDispatcher::instance(), &QAbstractEventDispatcher::awake, this, &View::awakeSlot); } View::~View() = default; -void View::slotActiveDocument(const Document &documentIn) +void View::slotActiveDocument(const Document& documentIn) { - if (Gui::Selection().hasSelection()) - return; - ModelMap::const_iterator it = modelMap.find(&documentIn); - if (it == modelMap.end()) - { - ModelMap::value_type entry(std::make_pair(&documentIn, std::make_shared(this, documentIn))); - modelMap.insert(entry); - this->setScene(entry.second.get()); - } - else - { - this->setScene(it->second.get()); - } + if (Gui::Selection().hasSelection()) { + return; + } + ModelMap::const_iterator it = modelMap.find(&documentIn); + if (it == modelMap.end()) { + ModelMap::value_type entry( + std::make_pair(&documentIn, std::make_shared(this, documentIn)) + ); + modelMap.insert(entry); + this->setScene(entry.second.get()); + } + else { + this->setScene(it->second.get()); + } } -void View::slotDeleteDocument(const Document &documentIn) +void View::slotDeleteDocument(const Document& documentIn) { - ModelMap::const_iterator it = modelMap.find(&documentIn); - if (it != modelMap.end()) - modelMap.erase(it); + ModelMap::const_iterator it = modelMap.find(&documentIn); + if (it != modelMap.end()) { + modelMap.erase(it); + } } void View::awakeSlot() { - Model *model = dynamic_cast(this->scene()); - if (model) - model->awake(); + Model* model = dynamic_cast(this->scene()); + if (model) { + model->awake(); + } } void View::onSelectionChanged(const SelectionChanges& msg) { - switch(msg.Type) { - case SelectionChanges::AddSelection: - case SelectionChanges::RmvSelection: - case SelectionChanges::SetSelection: - if (!msg.pDocName || !msg.pDocName[0]) - return; - break; - case SelectionChanges::ClrSelection: - if (!msg.pDocName || !msg.pDocName[0]) { - for (auto &v : modelMap) { - v.second->selectionChanged(msg); - } - return; + switch (msg.Type) { + case SelectionChanges::AddSelection: + case SelectionChanges::RmvSelection: + case SelectionChanges::SetSelection: + if (!msg.pDocName || !msg.pDocName[0]) { + return; + } + break; + case SelectionChanges::ClrSelection: + if (!msg.pDocName || !msg.pDocName[0]) { + for (auto& v : modelMap) { + v.second->selectionChanged(msg); + } + return; + } + break; + default: + return; } - break; - default: - return; - } - auto doc = Gui::Application::Instance->getDocument(msg.pDocName); - if (!doc) - return; - auto &model = modelMap[doc]; - if(!model) - model = std::make_shared(this, *doc); - this->setScene(model.get()); - model->selectionChanged(msg); + auto doc = Gui::Application::Instance->getDocument(msg.pDocName); + if (!doc) { + return; + } + auto& model = modelMap[doc]; + if (!model) { + model = std::make_shared(this, *doc); + } + this->setScene(model.get()); + model->selectionChanged(msg); } - #include "moc_DAGView.cpp" diff --git a/src/Gui/DAGView/DAGView.h b/src/Gui/DAGView/DAGView.h index f6ceb31e5d..7aab7e685c 100644 --- a/src/Gui/DAGView/DAGView.h +++ b/src/Gui/DAGView/DAGView.h @@ -37,43 +37,43 @@ namespace Gui { - namespace DAG - { - //! @brief view for DAG viewer - class View : public QGraphicsView, public SelectionObserver - { - Q_OBJECT - public: - explicit View(QWidget *parentIn = nullptr); - ~View() override; +namespace DAG +{ +//! @brief view for DAG viewer +class View: public QGraphicsView, public SelectionObserver +{ + Q_OBJECT +public: + explicit View(QWidget* parentIn = nullptr); + ~View() override; - public Q_SLOTS: - void awakeSlot(); //!< hooked up to event dispatcher for update when idle. +public Q_SLOTS: + void awakeSlot(); //!< hooked up to event dispatcher for update when idle. - private: - void onSelectionChanged(const SelectionChanges& msg) override; +private: + void onSelectionChanged(const SelectionChanges& msg) override; - void slotActiveDocument(const Gui::Document &documentIn); - void slotDeleteDocument(const Gui::Document &documentIn); + void slotActiveDocument(const Gui::Document& documentIn); + void slotDeleteDocument(const Gui::Document& documentIn); - using ModelMap = std::map >; - ModelMap modelMap; - boost::signals2::scoped_connection conActive; - boost::signals2::scoped_connection conDelete; - }; + using ModelMap = std::map>; + ModelMap modelMap; + boost::signals2::scoped_connection conActive; + boost::signals2::scoped_connection conDelete; +}; - //! @brief dock window for DAG viewer - class DockWindow : public Gui::DockWindow - { - Q_OBJECT - public: - explicit DockWindow(Gui::Document* gDocumentIn = nullptr, QWidget *parent = nullptr); - ~DockWindow() override = default; +//! @brief dock window for DAG viewer +class DockWindow: public Gui::DockWindow +{ + Q_OBJECT +public: + explicit DockWindow(Gui::Document* gDocumentIn = nullptr, QWidget* parent = nullptr); + ~DockWindow() override = default; - private: - View *dagView; - }; - } -} +private: + View* dagView; +}; +} // namespace DAG +} // namespace Gui -#endif // DAGVIEW_H +#endif // DAGVIEW_H diff --git a/src/Gui/DemoMode.cpp b/src/Gui/DemoMode.cpp index 2e37427206..285ab0ac32 100644 --- a/src/Gui/DemoMode.cpp +++ b/src/Gui/DemoMode.cpp @@ -93,8 +93,9 @@ void DemoMode::reset() if (view) { view->getViewer()->stopAnimating(); } - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); hGrp->Notify("UseNavigationAnimations"); } @@ -276,8 +277,7 @@ void DemoMode::onAutoPlay() void DemoMode::startAnimation(Gui::View3DInventor* view) { - view->getViewer()->startSpinningAnimation(getDirection(view), - getSpeed(ui->speedSlider->value())); + view->getViewer()->startSpinningAnimation(getDirection(view), getSpeed(ui->speedSlider->value())); } void DemoMode::onTimerCheckToggled(bool on) diff --git a/src/Gui/DemoMode.h b/src/Gui/DemoMode.h index 75f7627454..f3dad33b2d 100644 --- a/src/Gui/DemoMode.h +++ b/src/Gui/DemoMode.h @@ -33,15 +33,17 @@ class SoCamera; class SbVec3f; class SbRotation; -namespace Gui { +namespace Gui +{ class View3DInventor; -namespace Dialog { +namespace Dialog +{ /** * @author Werner Mayer */ class Ui_DemoMode; -class GuiExport DemoMode : public QDialog +class GuiExport DemoMode: public QDialog { Q_OBJECT @@ -65,14 +67,14 @@ protected: private: void reset(); float getSpeed(int) const; - void reorientCamera(SoCamera * cam, const SbRotation & rot); + void reorientCamera(SoCamera* cam, const SbRotation& rot); SbVec3f getDirection(Gui::View3DInventor*) const; Gui::View3DInventor* activeView() const; void startAnimation(Gui::View3DInventor*); - void changeEvent(QEvent *e) override; - bool eventFilter(QObject *, QEvent *) override; - void showEvent(QShowEvent *) override; - void hideEvent(QHideEvent *) override; + void changeEvent(QEvent* e) override; + bool eventFilter(QObject*, QEvent*) override; + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; private: int oldvalue; @@ -85,7 +87,7 @@ private: QTimer* showHideTimer; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DEMOMODE_H +#endif // GUI_DIALOG_DEMOMODE_H diff --git a/src/Gui/Dialogs/DlgAbout.cpp b/src/Gui/Dialogs/DlgAbout.cpp index dac5655161..bd38ef57ce 100644 --- a/src/Gui/Dialogs/DlgAbout.cpp +++ b/src/Gui/Dialogs/DlgAbout.cpp @@ -195,8 +195,9 @@ void AboutDialog::setupLabels() #endif // avoid overriding user set style sheet if (qApp->styleSheet().isEmpty()) { - setStyleSheet(QStringLiteral("Gui--Dialog--AboutDialog QLabel {font-size: %1pt;}") - .arg(fontSize)); + setStyleSheet( + QStringLiteral("Gui--Dialog--AboutDialog QLabel {font-size: %1pt;}").arg(fontSize) + ); } QString exeName = qApp->applicationName(); @@ -223,12 +224,15 @@ void AboutDialog::setupLabels() if (qApp->styleSheet().isEmpty()) { ui->labelAuthor->setStyleSheet(QStringLiteral( - "Gui--UrlLabel {color: #0000FF;text-decoration: underline;font-weight: 600;}")); + "Gui--UrlLabel {color: #0000FF;text-decoration: underline;font-weight: 600;}" + )); } QString version = ui->labelBuildVersion->text(); - version.replace(QStringLiteral("Unknown"), - QStringLiteral("%1.%2.%3%4").arg(major, minor, point, suffix)); + version.replace( + QStringLiteral("Unknown"), + QStringLiteral("%1.%2.%3%4").arg(major, minor, point, suffix) + ); ui->labelBuildVersion->setText(version); QString revision = ui->labelBuildRevision->text(); @@ -251,7 +255,8 @@ void AboutDialog::setupLabels() architecture.replace( QStringLiteral("Unknown"), QStringLiteral("%1 (running on: %2)") - .arg(QSysInfo::buildCpuArchitecture(), QSysInfo::currentCpuArchitecture())); + .arg(QSysInfo::buildCpuArchitecture(), QSysInfo::currentCpuArchitecture()) + ); } ui->labelBuildRunArchitecture->setText(architecture); @@ -273,7 +278,8 @@ void AboutDialog::setupLabels() QString hash = ui->labelBuildHash->text(); hash.replace( QStringLiteral("Unknown"), - QString::fromStdString(it->second).left(7)); // Use the 7-char abbreviated hash + QString::fromStdString(it->second).left(7) + ); // Use the 7-char abbreviated hash ui->labelBuildHash->setText(hash); if (auto url_itr = config.find("BuildRepositoryURL"); url_itr != config.end()) { auto url = QString::fromStdString(url_itr->second); @@ -290,8 +296,9 @@ void AboutDialog::setupLabels() // so give it a shot... auto https = url.replace(QStringLiteral("git://"), QStringLiteral("https://")); https.replace(QStringLiteral(".git"), QStringLiteral("")); - ui->labelBuildHash->setUrl(https + QStringLiteral("/commit/") - + QString::fromStdString(it->second)); + ui->labelBuildHash->setUrl( + https + QStringLiteral("/commit/") + QString::fromStdString(it->second) + ); } } else { @@ -318,12 +325,11 @@ void AboutDialog::showCredits() hlayout->addWidget(textField); //: Header for the Credits tab of the About screen - QString creditsHTML = - QStringLiteral("

%1

%2

%3

    ") - .arg(tr("Credits", "Header for the Credits tab of the About screen")) - .arg(tr("FreeCAD would not be possible without the contributions of:")) - .arg( - tr("Individuals", "Header for the list of individual people in the Credits list.")); + QString creditsHTML + = QStringLiteral("

    %1

    %2

    %3

      ") + .arg(tr("Credits", "Header for the Credits tab of the About screen")) + .arg(tr("FreeCAD would not be possible without the contributions of:")) + .arg(tr("Individuals", "Header for the list of individual people in the Credits list.")); QTextStream stream(&creditsFile); #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) @@ -355,8 +361,9 @@ void AboutDialog::showLicenseInformation() if (licenseFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QString licenseHTML = QString::fromUtf8(licenseFile.readAll()); - const auto placeholder = - QStringLiteral(""); + const auto placeholder = QStringLiteral( + "" + ); licenseHTML.replace(placeholder, getAdditionalLicenseInformation()); ui->tabWidget->removeTab(1); // Hide the license placeholder widget @@ -391,7 +398,8 @@ QString AboutDialog::getAdditionalLicenseInformation() const "

      3D Mouse Support

      " "

      Development tools and related technology provided under license from 3Dconnexion.
      " "Copyright © 1992–2012 3Dconnexion. All rights reserved.

      " - "
      "); + "
      " + ); #endif return info; } @@ -480,9 +488,7 @@ void AboutDialog::copyToClipboard() auto copytext = ui->copyButton->text(); ui->copyButton->setText(tr("Copied!")); const int timeout = 2000; - QTimer::singleShot(timeout, this, [this, copytext]() { - ui->copyButton->setText(copytext); - }); + QTimer::singleShot(timeout, this, [this, copytext]() { ui->copyButton->setText(copytext); }); } // ---------------------------------------------------------------------------- diff --git a/src/Gui/Dialogs/DlgActionsImp.cpp b/src/Gui/Dialogs/DlgActionsImp.cpp index df2f6b8f7b..60d0c95783 100644 --- a/src/Gui/Dialogs/DlgActionsImp.cpp +++ b/src/Gui/Dialogs/DlgActionsImp.cpp @@ -59,18 +59,17 @@ DlgCustomActionsImp::DlgCustomActionsImp(QWidget* parent) setupConnections(); // search for all macros - std::string cMacroPath = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") - ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); + std::string cMacroPath = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); QDir d(QString::fromUtf8(cMacroPath.c_str()), QLatin1String("*.FCMacro *.py")); for (unsigned int i = 0; i < d.count(); i++) { ui->actionMacros->insertItem(0, d[i], QVariant(false)); } - QString systemMacroDirStr = - QString::fromStdString(App::Application::getHomePath()) + QStringLiteral("Macro"); + QString systemMacroDirStr = QString::fromStdString(App::Application::getHomePath()) + + QStringLiteral("Macro"); d = QDir(systemMacroDirStr, QLatin1String("*.FCMacro *.py")); if (d.exists()) { for (unsigned int i = 0; i < d.count(); i++) { @@ -206,9 +205,11 @@ void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem* item) } if (!bFound) { - QMessageBox::critical(this, - tr("Macro not found"), - tr("Could not find macro file '%1'").arg(scriptName)); + QMessageBox::critical( + this, + tr("Macro not found"), + tr("Could not find macro file '%1'").arg(scriptName) + ); } // fill up labels with the command's data @@ -217,7 +218,8 @@ void DlgCustomActionsImp::onActionListWidgetItemActivated(QTreeWidgetItem* item) ui->actionToolTip->setText(QString::fromUtf8(pScript->getToolTipText())); ui->actionStatus->setText(QString::fromUtf8(pScript->getStatusTip())); ui->actionAccel->setKeySequence(QKeySequence( - ShortcutManager::instance()->getShortcut(actionName.constData(), pScript->getAccel()))); + ShortcutManager::instance()->getShortcut(actionName.constData(), pScript->getAccel()) + )); ui->pixmapLabel->clear(); m_sPixmap.clear(); const char* name = pScript->getPixmap(); @@ -244,9 +246,10 @@ void DlgCustomActionsImp::onButtonAddActionClicked() // search for the command in the manager CommandManager& rclMan = Application::Instance->commandManager(); QByteArray actionName = QString::fromStdString(rclMan.newMacroName()).toLatin1(); - auto macro = - new MacroCommand(actionName, - ui->actionMacros->itemData(ui->actionMacros->currentIndex()).toBool()); + auto macro = new MacroCommand( + actionName, + ui->actionMacros->itemData(ui->actionMacros->currentIndex()).toBool() + ); rclMan.addCommand(macro); // add new action @@ -289,8 +292,7 @@ void DlgCustomActionsImp::onButtonAddActionClicked() if (!ui->actionAccel->isEmpty()) { QString text = ui->actionAccel->text(); - ShortcutManager::instance()->setShortcut(actionName.constData(), - text.toLatin1().constData()); + ShortcutManager::instance()->setShortcut(actionName.constData(), text.toLatin1().constData()); } ui->actionAccel->clear(); @@ -369,7 +371,8 @@ void DlgCustomActionsImp::onButtonReplaceActionClicked() action->setIcon(Gui::BitmapFactory().pixmap(macro->getPixmap())); } action->setShortcut( - ShortcutManager::instance()->getShortcut(actionName.constData(), macro->getAccel())); + ShortcutManager::instance()->getShortcut(actionName.constData(), macro->getAccel()) + ); } // emit signal to notify the container widget @@ -445,8 +448,9 @@ void IconDialog::resizeEvent(QResizeEvent*) void IconDialog::onAddIconPath() { // Add the user defined paths - Base::Reference group = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Bitmaps"); + Base::Reference group = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Bitmaps" + ); std::vector paths = group->GetASCIIs("CustomPath"); QStringList pathList; for (const auto& path : paths) { @@ -476,8 +480,7 @@ void IconDialog::onAddIconPath() QStringList filters; QList formats = QImageReader::supportedImageFormats(); for (const auto& format : formats) { - filters << QStringLiteral("*.%1").arg( - QString::fromLatin1(format).toLower()); + filters << QStringLiteral("*.%1").arg(QString::fromLatin1(format).toLower()); } QDir d(path); d.setNameFilters(filters); @@ -590,9 +593,11 @@ void IconFolders::addFolder() if (it.first->isHidden()) { countHidden++; if (countHidden == 0) { - QString dir = QFileDialog::getExistingDirectory(this, - IconDialog::tr("Add icon folder"), - QString()); + QString dir = QFileDialog::getExistingDirectory( + this, + IconDialog::tr("Add icon folder"), + QString() + ); if (!dir.isEmpty() && paths.indexOf(dir) < 0) { QLineEdit* edit = it.first; edit->setVisible(true); @@ -619,7 +624,8 @@ void IconFolders::removeFolder() QMessageBox::information( this, tr("Remove folder"), - tr("Removing a folder only takes effect after an application restart")); + tr("Removing a folder only takes effect after an application restart") + ); } addButton->setEnabled(true); diff --git a/src/Gui/Dialogs/DlgActionsImp.h b/src/Gui/Dialogs/DlgActionsImp.h index 01cd04085a..d61c7c9116 100644 --- a/src/Gui/Dialogs/DlgActionsImp.h +++ b/src/Gui/Dialogs/DlgActionsImp.h @@ -36,8 +36,10 @@ class QLabel; class QGridLayout; class QLineEdit; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgCustomActions; @@ -48,28 +50,28 @@ class Ui_DlgCustomActions; * @see Command * \author Werner Mayer */ -class DlgCustomActionsImp : public CustomizeActionPage +class DlgCustomActionsImp: public CustomizeActionPage { Q_OBJECT public: - explicit DlgCustomActionsImp( QWidget* parent = nullptr ); + explicit DlgCustomActionsImp(QWidget* parent = nullptr); ~DlgCustomActionsImp() override; Q_SIGNALS: - void addMacroAction( const QByteArray& ); - void removeMacroAction( const QByteArray& ); - void modifyMacroAction( const QByteArray& ); + void addMacroAction(const QByteArray&); + void removeMacroAction(const QByteArray&); + void modifyMacroAction(const QByteArray&); protected: /** Trigger for reparent event. */ bool event(QEvent* e) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; protected: void setupConnections(); /** Enables/disables buttons for deletion */ - void onActionListWidgetItemActivated( QTreeWidgetItem *i ); + void onActionListWidgetItemActivated(QTreeWidgetItem* i); /** Opens a iconview to select a pixmap */ void onButtonChoosePixmapClicked(); /** Adds a custom action */ @@ -95,7 +97,7 @@ private: }; class Ui_DlgChooseIcon; -class IconDialog : public QDialog +class IconDialog: public QDialog { Q_OBJECT @@ -109,10 +111,10 @@ private: void onAddIconPath(); private: - Ui_DlgChooseIcon *ui; + Ui_DlgChooseIcon* ui; }; -class IconFolders : public QDialog +class IconFolders: public QDialog { Q_OBJECT @@ -131,10 +133,10 @@ private: QGridLayout* gridLayout; QLabel* textLabel; QPushButton* addButton; - QList< QPair > buttonMap; + QList> buttonMap; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGACTIONS_IMP_H +#endif // GUI_DIALOG_DLGACTIONS_IMP_H diff --git a/src/Gui/Dialogs/DlgActivateWindowImp.cpp b/src/Gui/Dialogs/DlgActivateWindowImp.cpp index 872e0da646..8f09af71e3 100644 --- a/src/Gui/Dialogs/DlgActivateWindowImp.cpp +++ b/src/Gui/Dialogs/DlgActivateWindowImp.cpp @@ -20,8 +20,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include "Dialogs/DlgActivateWindowImp.h" #include "ui_DlgActivateWindow.h" @@ -41,14 +41,16 @@ using namespace Gui::Dialog; * true to construct a modal dialog. */ DlgActivateWindowImp::DlgActivateWindowImp(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), ui(new Ui_DlgActivateWindow) + : QDialog(parent, fl) + , ui(new Ui_DlgActivateWindow) { // create widgets ui->setupUi(this); QPushButton* buttonOk = ui->buttonBox->button(QDialogButtonBox::Ok); buttonOk->setText(QApplication::translate("Gui::Dialog::DlgActivateWindow", "&Activate")); - QTreeWidgetItem* active=nullptr; - QStringList labels; labels << tr("Windows"); + QTreeWidgetItem* active = nullptr; + QStringList labels; + labels << tr("Windows"); ui->treeWidget->setHeaderLabels(labels); ui->treeWidget->header()->hide(); @@ -64,15 +66,18 @@ DlgActivateWindowImp::DlgActivateWindowImp(QWidget* parent, Qt::WindowFlags fl) auto item = new QTreeWidgetItem(ui->treeWidget); QString title = it->windowTitle(); title.replace(QLatin1String("[*]"), QLatin1String("")); - if (it->isWindowModified()) + if (it->isWindowModified()) { title += QLatin1String("*"); + } item->setText(0, title); - if (it == activeWnd) + if (it == activeWnd) { active = item; + } } - if (active) - ui->treeWidget->setCurrentItem( active ); + if (active) { + ui->treeWidget->setCurrentItem(active); + } ui->treeWidget->setFocus(); } diff --git a/src/Gui/Dialogs/DlgActivateWindowImp.h b/src/Gui/Dialogs/DlgActivateWindowImp.h index 6cdb3f4097..40ce837271 100644 --- a/src/Gui/Dialogs/DlgActivateWindowImp.h +++ b/src/Gui/Dialogs/DlgActivateWindowImp.h @@ -26,8 +26,10 @@ #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgActivateWindow; /** * The DlgActivateWindowImp class provides a dialog to activate the MDI window @@ -35,7 +37,7 @@ class Ui_DlgActivateWindow; * an application you cannot put all of them into the "Windows" popup menu. * \author Werner Mayer */ -class DlgActivateWindowImp : public QDialog +class DlgActivateWindowImp: public QDialog { Q_OBJECT @@ -50,7 +52,7 @@ private: Ui_DlgActivateWindow* ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGACTIVATEWINDOW_IMP_H +#endif // GUI_DIALOG_DLGACTIVATEWINDOW_IMP_H diff --git a/src/Gui/Dialogs/DlgAddProperty.cpp b/src/Gui/Dialogs/DlgAddProperty.cpp index 79b6bc61f0..6b0d5f77c2 100644 --- a/src/Gui/Dialogs/DlgAddProperty.cpp +++ b/src/Gui/Dialogs/DlgAddProperty.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include #include @@ -132,24 +132,24 @@ const std::string DlgAddProperty::GroupBase = "Base"; * situation. */ -DlgAddProperty::DlgAddProperty(QWidget* parent, - App::PropertyContainer* container) +DlgAddProperty::DlgAddProperty(QWidget* parent, App::PropertyContainer* container) : DlgAddProperty(parent, container, nullptr) -{ -} +{} -DlgAddProperty::DlgAddProperty(QWidget* parent, - ViewProviderVarSet* viewProvider) - : DlgAddProperty(parent, - viewProvider ? viewProvider->getObject() : nullptr, - viewProvider) -{ -} +DlgAddProperty::DlgAddProperty(QWidget* parent, ViewProviderVarSet* viewProvider) + : DlgAddProperty( + parent, + viewProvider ? viewProvider->getObject() : nullptr, + viewProvider + ) +{} -DlgAddProperty::DlgAddProperty(QWidget* parent, - App::PropertyContainer* container, - ViewProviderVarSet* viewProvider) +DlgAddProperty::DlgAddProperty( + QWidget* parent, + App::PropertyContainer* container, + ViewProviderVarSet* viewProvider +) : QDialog(parent) , container(container) , ui(new Ui_DlgAddProperty) @@ -167,10 +167,9 @@ DlgAddProperty::~DlgAddProperty() = default; void DlgAddProperty::setupMacroRedirector() { - setValueRedirector = std::make_unique([this](MacroManager::LineType /*type*/, - const char* line) { - this->setValueCommand = line; - }); + setValueRedirector = std::make_unique( + [this](MacroManager::LineType /*type*/, const char* line) { this->setValueCommand = line; } + ); } int DlgAddProperty::findLabelRow(const char* labelName, QFormLayout* layout) @@ -193,7 +192,7 @@ int DlgAddProperty::findLabelRow(const char* labelName, QFormLayout* layout) void DlgAddProperty::removeExistingWidget(QFormLayout* formLayout, int labelRow) { if (QLayoutItem* existingItem = formLayout->itemAt(labelRow, QFormLayout::FieldRole)) { - if (QWidget *existingWidget = existingItem->widget()) { + if (QWidget* existingWidget = existingItem->widget()) { formLayout->removeWidget(existingWidget); existingWidget->deleteLater(); } @@ -201,8 +200,7 @@ void DlgAddProperty::removeExistingWidget(QFormLayout* formLayout, int labelRow) } -void DlgAddProperty::setWidgetForLabel(const char* labelName, QWidget* widget, - QLayout* layout) +void DlgAddProperty::setWidgetForLabel(const char* labelName, QWidget* widget, QLayout* layout) { auto formLayout = qobject_cast(layout); if (formLayout == nullptr) { @@ -220,11 +218,11 @@ void DlgAddProperty::setWidgetForLabel(const char* labelName, QWidget* widget, formLayout->setWidget(labelRow, QFormLayout::FieldRole, widget); } -void DlgAddProperty::populateGroup(EditFinishedComboBox& comboBox, - const App::PropertyContainer* container) +void DlgAddProperty::populateGroup(EditFinishedComboBox& comboBox, const App::PropertyContainer* container) { auto paramGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/PropertyView"); + "User parameter:BaseApp/Preferences/PropertyView" + ); std::string lastGroup = paramGroup->GetASCII("NewPropertyGroup"); std::vector properties; @@ -252,8 +250,7 @@ void DlgAddProperty::populateGroup(EditFinishedComboBox& comboBox, comboBox.addItem(QString::fromStdString(groupName)); } - if (!lastGroup.empty() && - std::ranges::find(groupNames, lastGroup) != groupNames.end()) { + if (!lastGroup.empty() && std::ranges::find(groupNames, lastGroup) != groupNames.end()) { comboBox.setEditText(QString::fromStdString(lastGroup)); } else { @@ -270,8 +267,12 @@ void DlgAddProperty::initializeGroup() setWidgetForLabel("labelGroup", &comboBoxGroup, layout()); populateGroup(comboBoxGroup, container); - connComboBoxGroup = connect(&comboBoxGroup, &EditFinishedComboBox::editFinished, - this, &DlgAddProperty::onGroupFinished); + connComboBoxGroup = connect( + &comboBoxGroup, + &EditFinishedComboBox::editFinished, + this, + &DlgAddProperty::onGroupFinished + ); } std::vector DlgAddProperty::getSupportedTypes() @@ -280,10 +281,9 @@ std::vector DlgAddProperty::getSupportedTypes() std::vector allTypes; Base::Type::getAllDerivedFrom(Base::Type::fromName("App::Property"), allTypes); - std::ranges::copy_if(allTypes, std::back_inserter(supportedTypes), - [&](const Base::Type& type) { - return type.canInstantiate() && isTypeWithEditor(type); - }); + std::ranges::copy_if(allTypes, std::back_inserter(supportedTypes), [&](const Base::Type& type) { + return type.canInstantiate() && isTypeWithEditor(type); + }); std::ranges::sort(supportedTypes, [](Base::Type a, Base::Type b) { return strcmp(a.getName(), b.getName()) < 0; @@ -295,19 +295,21 @@ std::vector DlgAddProperty::getSupportedTypes() void DlgAddProperty::initializeTypes() { auto paramGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/PropertyView"); + "User parameter:BaseApp/Preferences/PropertyView" + ); auto lastType = Base::Type::fromName( - paramGroup->GetASCII("NewPropertyType", "App::PropertyLength").c_str()); + paramGroup->GetASCII("NewPropertyType", "App::PropertyLength").c_str() + ); if (lastType.isBad()) { lastType = App::PropertyLength::getClassTypeId(); } std::vector types = getSupportedTypes(); - for(const auto& type : types) { + for (const auto& type : types) { ui->comboBoxType->addItem(QString::fromLatin1(type.getName())); if (type == lastType) { - ui->comboBoxType->setCurrentIndex(ui->comboBoxType->count()-1); + ui->comboBoxType->setCurrentIndex(ui->comboBoxType->count() - 1); } } @@ -317,8 +319,12 @@ void DlgAddProperty::initializeTypes() ui->comboBoxType->setCompleter(&completerType); ui->comboBoxType->setInsertPolicy(QComboBox::NoInsert); - connComboBoxType = connect(ui->comboBoxType, &QComboBox::currentTextChanged, - this, &DlgAddProperty::onTypeChanged); + connComboBoxType = connect( + ui->comboBoxType, + &QComboBox::currentTextChanged, + this, + &DlgAddProperty::onTypeChanged + ); } void DlgAddProperty::removeSelectionEditor() @@ -334,8 +340,7 @@ void DlgAddProperty::removeSelectionEditor() void DlgAddProperty::addEnumEditor(PropertyItem* propertyItem) { - auto* values = - static_cast(PropertyStringListItem::create()); + auto* values = static_cast(PropertyStringListItem::create()); values->setParent(propertyItem); values->setPropertyName(QLatin1String(QT_TRANSLATE_NOOP("App::Property", "Enum"))); if (propertyItem->childCount() > 0) { @@ -343,16 +348,16 @@ void DlgAddProperty::addEnumEditor(PropertyItem* propertyItem) delete child; } propertyItem->appendChild(values); - editor.reset(values->createEditor(this, [this]() { - this->valueChangedEnum(); - }, FrameOption::WithFrame)); + editor.reset( + values->createEditor(this, [this]() { this->valueChangedEnum(); }, FrameOption::WithFrame) + ); } void DlgAddProperty::addNormalEditor(PropertyItem* propertyItem) { - editor.reset(propertyItem->createEditor(this, [this]() { - this->valueChanged(); - }, FrameOption::WithFrame)); + editor.reset( + propertyItem->createEditor(this, [this]() { this->valueChanged(); }, FrameOption::WithFrame) + ); } void DlgAddProperty::addEditor(PropertyItem* propertyItem) @@ -433,20 +438,20 @@ bool DlgAddProperty::isTypeWithEditor(const Base::Type& type) return type.isDerivedFrom(t); }; - return std::ranges::find(typesWithEditor, type) != typesWithEditor.end() || - std::ranges::any_of(subTypesWithEditor, isDerivedFromType); + return std::ranges::find(typesWithEditor, type) != typesWithEditor.end() + || std::ranges::any_of(subTypesWithEditor, isDerivedFromType); } bool DlgAddProperty::isTypeWithEditor(const std::string& type) { - Base::Type propType = - Base::Type::getTypeIfDerivedFrom(type.c_str(), App::Property::getClassTypeId(), true); + Base::Type propType + = Base::Type::getTypeIfDerivedFrom(type.c_str(), App::Property::getClassTypeId(), true); return isTypeWithEditor(propType); } -static PropertyItem *createPropertyItem(App::Property *prop) +static PropertyItem* createPropertyItem(App::Property* prop) { - const char *editor = prop->getEditorName(); + const char* editor = prop->getEditorName(); if (Base::Tools::isNullOrEmpty(editor)) { return nullptr; } @@ -466,9 +471,10 @@ void DlgAddProperty::createEditorForType(const Base::Type& type) // When prop goes out of scope, it can be deleted because we obtained the // propertyItem (if applicable) and we initialized the editor with the data // from the property. - std::unique_ptr prop( - static_cast(propInstance), - [](App::Property* p) { delete p; }); + std::unique_ptr prop( + static_cast(propInstance), + [](App::Property* p) { delete p; } + ); prop->setContainer(container); propertyItem.reset(createPropertyItem(prop.get())); @@ -484,8 +490,8 @@ void DlgAddProperty::initializeValue() { std::string type = ui->comboBoxType->currentText().toStdString(); - Base::Type propType = - Base::Type::getTypeIfDerivedFrom(type.c_str(), App::Property::getClassTypeId(), true); + Base::Type propType + = Base::Type::getTypeIfDerivedFrom(type.c_str(), App::Property::getClassTypeId(), true); if (propType.isBad()) { return; } @@ -505,8 +511,8 @@ void DlgAddProperty::setTitle() void DlgAddProperty::setAddEnabled(bool enabled) { - QPushButton *addButton = ui->buttonBox->button(QDialogButtonBox::Ok); - QPushButton *cancelButton = ui->buttonBox->button(QDialogButtonBox::Cancel); + QPushButton* addButton = ui->buttonBox->button(QDialogButtonBox::Ok); + QPushButton* cancelButton = ui->buttonBox->button(QDialogButtonBox::Cancel); cancelButton->setDefault(!enabled); addButton->setDefault(enabled); addButton->setEnabled(enabled); @@ -519,14 +525,15 @@ void DlgAddProperty::initializeWidgets(ViewProviderVarSet* viewProvider) initializeValue(); if (viewProvider) { - connect(this, &QDialog::finished, - this, [viewProvider](int result) { viewProvider->onFinished(result); }); + connect(this, &QDialog::finished, this, [viewProvider](int result) { + viewProvider->onFinished(result); + }); } - connLineEditNameTextChanged = connect(ui->lineEditName, &QLineEdit::textChanged, - this, &DlgAddProperty::onNameChanged); + connLineEditNameTextChanged + = connect(ui->lineEditName, &QLineEdit::textChanged, this, &DlgAddProperty::onNameChanged); setTitle(); - QPushButton *addButton = ui->buttonBox->button(QDialogButtonBox::Ok); + QPushButton* addButton = ui->buttonBox->button(QDialogButtonBox::Ok); addButton->setText(tr("Add")); setAddEnabled(false); @@ -541,19 +548,17 @@ void DlgAddProperty::initializeWidgets(ViewProviderVarSet* viewProvider) bool DlgAddProperty::propertyExists(const std::string& name) { App::Property* prop = container->getPropertyByName(name.c_str()); - return prop && prop->getContainer() == container && - !(propertyItem && propertyItem->getFirstProperty() == prop); + return prop && prop->getContainer() == container + && !(propertyItem && propertyItem->getFirstProperty() == prop); } bool DlgAddProperty::isNameValid() { std::string name = ui->lineEditName->text().toStdString(); - return !name.empty() && - name == Base::Tools::getIdentifier(name) && - !App::ExpressionParser::isTokenAConstant(name) && - !App::ExpressionParser::isTokenAUnit(name) && - !propertyExists(name); + return !name.empty() && name == Base::Tools::getIdentifier(name) + && !App::ExpressionParser::isTokenAConstant(name) + && !App::ExpressionParser::isTokenAUnit(name) && !propertyExists(name); } bool DlgAddProperty::isGroupValid() @@ -565,8 +570,8 @@ bool DlgAddProperty::isGroupValid() bool DlgAddProperty::isTypeValid() { std::string type = ui->comboBoxType->currentText().toStdString(); - return Base::Type::fromName(type.c_str()).isDerivedFrom(App::Property::getClassTypeId()) && - type != "App::Property"; + return Base::Type::fromName(type.c_str()).isDerivedFrom(App::Property::getClassTypeId()) + && type != "App::Property"; } bool DlgAddProperty::isDocument() const @@ -633,8 +638,8 @@ void DlgAddProperty::removeEditor() bool DlgAddProperty::isEnumPropertyItem() const { - return ui->comboBoxType->currentText() == - QString::fromLatin1(App::PropertyEnumeration::getClassTypeId().getName()); + return ui->comboBoxType->currentText() + == QString::fromLatin1(App::PropertyEnumeration::getClassTypeId().getName()); } bool DlgAddProperty::isSubLinkPropertyItem() const @@ -769,7 +774,7 @@ bool DlgAddProperty::clear(FieldChange fieldChange) return valueNeedsReset; } -void DlgAddProperty::onNameChanged([[maybe_unused]]const QString& text) +void DlgAddProperty::onNameChanged([[maybe_unused]] const QString& text) { bool valueNeedsReset = clear(FieldChange::Name); if (isNameValid() && isTypeValid()) { @@ -828,8 +833,7 @@ void DlgAddProperty::changeEvent(QEvent* e) void DlgAddProperty::valueChangedEnum() { - auto* propEnum = - static_cast(propertyItem->getFirstProperty()); + auto* propEnum = static_cast(propertyItem->getFirstProperty()); if (propEnum == nullptr || propertyItem->childCount() == 0) { return; } @@ -839,8 +843,9 @@ void DlgAddProperty::valueChangedEnum() QStringList enumValues = data.toStringList(); // convert to std::vector std::vector enumValuesVec; - std::ranges::transform(enumValues, std::back_inserter(enumValuesVec), - [](const QString& value) { return value.toStdString(); }); + std::ranges::transform(enumValues, std::back_inserter(enumValuesVec), [](const QString& value) { + return value.toStdString(); + }); propEnum->setEnums(enumValuesVec); } @@ -862,7 +867,8 @@ void DlgAddProperty::openTransaction() transactionID = App::GetApplication().setActiveTransaction("Add property"); } -void DlgAddProperty::critical(const QString& title, const QString& text) { +void DlgAddProperty::critical(const QString& title, const QString& text) +{ static bool criticalDialogShown = false; if (!criticalDialogShown) { Base::StateLocker locker(criticalDialogShown); @@ -870,9 +876,13 @@ void DlgAddProperty::critical(const QString& title, const QString& text) { } } -void DlgAddProperty::recordMacroAdd(const App::PropertyContainer* container, - const std::string& type, const std::string& name, - const std::string& group, const std::string& doc) const +void DlgAddProperty::recordMacroAdd( + const App::PropertyContainer* container, + const std::string& type, + const std::string& name, + const std::string& group, + const std::string& doc +) const { std::ostringstream command; command << "App.getDocument('"; @@ -888,8 +898,7 @@ void DlgAddProperty::recordMacroAdd(const App::PropertyContainer* container, FC_ERR("Cannot record macro for container of type " << container->getTypeId().getName()); return; } - command << ".addProperty('" << type << "', '" << name << "', '" << - group << "', '" << doc + "')"; + command << ".addProperty('" << type << "', '" << name << "', '" << group << "', '" << doc + "')"; Application::Instance->macroManager()->addLine(Gui::MacroManager::App, command.str().c_str()); } @@ -905,18 +914,19 @@ App::Property* DlgAddProperty::createProperty() }; try { - App::Property* prop = container->addDynamicProperty(type.c_str(), name.c_str(), - group.c_str(), doc.c_str()); + App::Property* prop + = container->addDynamicProperty(type.c_str(), name.c_str(), group.c_str(), doc.c_str()); MacroManager::MacroRedirector redirector(recordAddCommand); recordMacroAdd(container, type, name, group, doc); return prop; } catch (Base::Exception& e) { e.reportException(); - critical(QObject::tr("Add property"), - QObject::tr("Failed to add property to '%1': %2").arg( - QString::fromLatin1(container->getFullName().c_str()), - QString::fromUtf8(e.what()))); + critical( + QObject::tr("Add property"), + QObject::tr("Failed to add property to '%1': %2") + .arg(QString::fromLatin1(container->getFullName().c_str()), QString::fromUtf8(e.what())) + ); return nullptr; } } @@ -942,7 +952,8 @@ void DlgAddProperty::clearFields() setAddEnabled(false); } -void DlgAddProperty::addDocumentation() { +void DlgAddProperty::addDocumentation() +{ /* Since there is no check on documentation (we accept any string), there * is no signal handler for the documentation field. This method updates * the property that is being added with the text inserted as @@ -976,14 +987,14 @@ void DlgAddProperty::accept() setValueRedirector = nullptr; Application::Instance->macroManager()->addLine(MacroManager::LineType::App, addCommand.c_str()); - Application::Instance->macroManager()->addLine(MacroManager::LineType::App, - setValueCommand.c_str()); + Application::Instance->macroManager()->addLine(MacroManager::LineType::App, setValueCommand.c_str()); setupMacroRedirector(); std::string group = comboBoxGroup.currentText().toStdString(); std::string type = ui->comboBoxType->currentText().toStdString(); auto paramGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/PropertyView"); + "User parameter:BaseApp/Preferences/PropertyView" + ); paramGroup->SetASCII("NewPropertyType", type.c_str()); paramGroup->SetASCII("NewPropertyGroup", group.c_str()); diff --git a/src/Gui/Dialogs/DlgAddProperty.h b/src/Gui/Dialogs/DlgAddProperty.h index 6fc72c7a76..717eb74a72 100644 --- a/src/Gui/Dialogs/DlgAddProperty.h +++ b/src/Gui/Dialogs/DlgAddProperty.h @@ -38,37 +38,54 @@ #include "propertyeditor/PropertyItem.h" #include "Macro.h" -namespace Gui { +namespace Gui +{ class ViewProviderVarSet; -namespace Dialog { +namespace Dialog +{ -class EditFinishedComboBox : public QComboBox { +class EditFinishedComboBox: public QComboBox +{ Q_OBJECT public: - explicit EditFinishedComboBox(QWidget *parent = nullptr) : QComboBox(parent) { + explicit EditFinishedComboBox(QWidget* parent = nullptr) + : QComboBox(parent) + { setEditable(true); - connect(this, QOverload::of(&QComboBox::currentIndexChanged), this, &EditFinishedComboBox::onIndexChanged); - connect(this->lineEdit(), &QLineEdit::editingFinished, this, &EditFinishedComboBox::onEditingFinished); + connect( + this, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &EditFinishedComboBox::onIndexChanged + ); + connect( + this->lineEdit(), + &QLineEdit::editingFinished, + this, + &EditFinishedComboBox::onEditingFinished + ); } Q_SIGNALS: void editFinished(); private: - void onEditingFinished() { + void onEditingFinished() + { Q_EMIT editFinished(); } - void onIndexChanged() { + void onIndexChanged() + { Q_EMIT editFinished(); } }; class Ui_DlgAddProperty; -class GuiExport DlgAddProperty : public QDialog +class GuiExport DlgAddProperty: public QDialog { Q_OBJECT @@ -89,29 +106,27 @@ public: void changeEvent(QEvent* e) override; void accept() override; void reject() override; - static void populateGroup(EditFinishedComboBox& comboBox, - const App::PropertyContainer* container); - static void setWidgetForLabel(const char* labelName, QWidget* widget, - QLayout* layout); + static void populateGroup(EditFinishedComboBox& comboBox, const App::PropertyContainer* container); + static void setWidgetForLabel(const char* labelName, QWidget* widget, QLayout* layout); public Q_SLOTS: void valueChanged(); void valueChangedEnum(); private: - enum class TransactionOption : bool { + enum class TransactionOption : bool + { Commit = false, Abort = true }; - enum class FieldChange : std::uint8_t { + enum class FieldChange : std::uint8_t + { Name, Type }; - DlgAddProperty(QWidget* parent, - App::PropertyContainer* container, - ViewProviderVarSet* viewProvider); + DlgAddProperty(QWidget* parent, App::PropertyContainer* container, ViewProviderVarSet* viewProvider); void setupMacroRedirector(); @@ -161,9 +176,13 @@ private: void openTransaction(); void critical(const QString& title, const QString& text); - void recordMacroAdd(const App::PropertyContainer* container, - const std::string& type, const std::string& name, - const std::string& group, const std::string& doc) const; + void recordMacroAdd( + const App::PropertyContainer* container, + const std::string& type, + const std::string& name, + const std::string& group, + const std::string& doc + ) const; App::Property* createProperty(); void closeTransaction(TransactionOption option); void clearFields(); @@ -195,7 +214,7 @@ private: std::string setValueCommand; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLG_ADD_PROPERTY_H +#endif // GUI_DIALOG_DLG_ADD_PROPERTY_H diff --git a/src/Gui/Dialogs/DlgCheckableMessageBox.cpp b/src/Gui/Dialogs/DlgCheckableMessageBox.cpp index 203f91c9c4..fd48b22186 100644 --- a/src/Gui/Dialogs/DlgCheckableMessageBox.cpp +++ b/src/Gui/Dialogs/DlgCheckableMessageBox.cpp @@ -27,8 +27,8 @@ ** **************************************************************************/ -# include -# include +#include +#include #include @@ -37,8 +37,10 @@ #include "MainWindow.h" -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ QByteArray toParamEntry(QString name) { name.replace(QStringLiteral(" "), QStringLiteral("_")); @@ -50,7 +52,7 @@ QPixmap getStandardIcon(QWidget* widget, QStyle::StandardPixmap standardPixmap) int iconSize = widget->style()->pixelMetric(QStyle::PM_MessageBoxIconSize, nullptr, widget); QIcon icon = widget->style()->standardIcon(standardPixmap); if (!icon.isNull()) { -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) return icon.pixmap(QSize(iconSize, iconSize)); #else qreal dpr = widget->devicePixelRatio(); @@ -61,9 +63,16 @@ QPixmap getStandardIcon(QWidget* widget, QStyle::StandardPixmap standardPixmap) return {}; } -void DlgCheckableMessageBox::showMessage(const QString& header, const QString& message, bool check, const QString& checkText) +void DlgCheckableMessageBox::showMessage( + const QString& header, + const QString& message, + bool check, + const QString& checkText +) { - bool checked = App::GetApplication().GetParameterGroupByPath(QByteArray("User parameter:BaseApp/CheckMessages"))->GetBool(toParamEntry(header)); + bool checked = App::GetApplication() + .GetParameterGroupByPath(QByteArray("User parameter:BaseApp/CheckMessages")) + ->GetBool(toParamEntry(header)); if (!checked) { auto mb = new DlgCheckableMessageBox(Gui::getMainWindow()); @@ -80,12 +89,21 @@ void DlgCheckableMessageBox::showMessage(const QString& header, const QString& m } } -void DlgCheckableMessageBox::showMessage(const QString& header, const QString& message, const QString& prefPath, const QString& paramEntry, - bool entryDefault, bool check, const QString& checkText) +void DlgCheckableMessageBox::showMessage( + const QString& header, + const QString& message, + const QString& prefPath, + const QString& paramEntry, + bool entryDefault, + bool check, + const QString& checkText +) { - bool checked = App::GetApplication().GetParameterGroupByPath(prefPath.toLatin1())->GetBool(paramEntry.toLatin1(), entryDefault); + bool checked = App::GetApplication() + .GetParameterGroupByPath(prefPath.toLatin1()) + ->GetBool(paramEntry.toLatin1(), entryDefault); - if(checked == entryDefault) { + if (checked == entryDefault) { auto mb = new Gui::Dialog::DlgCheckableMessageBox(Gui::getMainWindow()); mb->setWindowTitle(header); @@ -101,17 +119,18 @@ void DlgCheckableMessageBox::showMessage(const QString& header, const QString& m } } -struct DlgCheckableMessageBoxPrivate { +struct DlgCheckableMessageBoxPrivate +{ DlgCheckableMessageBoxPrivate() = default; Ui::DlgCheckableMessageBox ui; - QAbstractButton *clickedButton{nullptr}; + QAbstractButton* clickedButton {nullptr}; }; -DlgCheckableMessageBox::DlgCheckableMessageBox(QWidget *parent) : - QDialog(parent), - m_d(new DlgCheckableMessageBoxPrivate), - prefPath(QLatin1String("User parameter:BaseApp/CheckMessages")) +DlgCheckableMessageBox::DlgCheckableMessageBox(QWidget* parent) + : QDialog(parent) + , m_d(new DlgCheckableMessageBoxPrivate) + , prefPath(QLatin1String("User parameter:BaseApp/CheckMessages")) { setModal(true); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); @@ -119,8 +138,7 @@ DlgCheckableMessageBox::DlgCheckableMessageBox(QWidget *parent) : m_d->ui.pixmapLabel->setVisible(false); connect(m_d->ui.buttonBox, &QDialogButtonBox::accepted, this, &DlgCheckableMessageBox::accept); connect(m_d->ui.buttonBox, &QDialogButtonBox::rejected, this, &DlgCheckableMessageBox::reject); - connect(m_d->ui.buttonBox, &QDialogButtonBox::clicked, - this, &DlgCheckableMessageBox::slotClicked); + connect(m_d->ui.buttonBox, &QDialogButtonBox::clicked, this, &DlgCheckableMessageBox::slotClicked); } DlgCheckableMessageBox::~DlgCheckableMessageBox() @@ -131,7 +149,8 @@ DlgCheckableMessageBox::~DlgCheckableMessageBox() void DlgCheckableMessageBox::setPrefEntry(const QString& entry) { paramEntry = toParamEntry(entry); - bool checked = App::GetApplication().GetParameterGroupByPath(prefPath.toLatin1())->GetBool(paramEntry); + bool checked + = App::GetApplication().GetParameterGroupByPath(prefPath.toLatin1())->GetBool(paramEntry); setChecked(checked); } @@ -140,20 +159,21 @@ void DlgCheckableMessageBox::setPrefPath(const QString& path) prefPath = path; } -void DlgCheckableMessageBox::slotClicked(QAbstractButton *b) +void DlgCheckableMessageBox::slotClicked(QAbstractButton* b) { m_d->clickedButton = b; } -QAbstractButton *DlgCheckableMessageBox::clickedButton() const +QAbstractButton* DlgCheckableMessageBox::clickedButton() const { return m_d->clickedButton; } QDialogButtonBox::StandardButton DlgCheckableMessageBox::clickedStandardButton() const { - if (m_d->clickedButton) + if (m_d->clickedButton) { return m_d->ui.buttonBox->standardButton(m_d->clickedButton); + } return QDialogButtonBox::NoButton; } @@ -162,7 +182,7 @@ QString DlgCheckableMessageBox::text() const return m_d->ui.messageLabel->text(); } -void DlgCheckableMessageBox::setText(const QString &t) +void DlgCheckableMessageBox::setText(const QString& t) { m_d->ui.messageLabel->setText(t); } @@ -172,7 +192,7 @@ QPixmap DlgCheckableMessageBox::iconPixmap() const return m_d->ui.pixmapLabel->pixmap(Qt::ReturnByValue); } -void DlgCheckableMessageBox::setIconPixmap(const QPixmap &p) +void DlgCheckableMessageBox::setIconPixmap(const QPixmap& p) { m_d->ui.pixmapLabel->setPixmap(p); m_d->ui.pixmapLabel->setVisible(!p.isNull()); @@ -193,7 +213,7 @@ QString DlgCheckableMessageBox::checkBoxText() const return m_d->ui.checkBox->text(); } -void DlgCheckableMessageBox::setCheckBoxText(const QString &t) +void DlgCheckableMessageBox::setCheckBoxText(const QString& t) { m_d->ui.checkBox->setText(t); } @@ -210,16 +230,19 @@ void DlgCheckableMessageBox::setStandardButtons(QDialogButtonBox::StandardButton QDialogButtonBox::StandardButton DlgCheckableMessageBox::defaultButton() const { - Q_FOREACH (QAbstractButton *b, m_d->ui.buttonBox->buttons()) - if (auto pb = qobject_cast(b)) - if (pb->isDefault()) - return m_d->ui.buttonBox->standardButton(pb); + Q_FOREACH (QAbstractButton* b, m_d->ui.buttonBox->buttons()) { + if (auto pb = qobject_cast(b)) { + if (pb->isDefault()) { + return m_d->ui.buttonBox->standardButton(pb); + } + } + } return QDialogButtonBox::NoButton; } void DlgCheckableMessageBox::setDefaultButton(QDialogButtonBox::StandardButton s) { - if (QPushButton *b = m_d->ui.buttonBox->button(s)) { + if (QPushButton* b = m_d->ui.buttonBox->button(s)) { b->setDefault(true); b->setFocus(); } @@ -227,26 +250,33 @@ void DlgCheckableMessageBox::setDefaultButton(QDialogButtonBox::StandardButton s void DlgCheckableMessageBox::accept() { - if(!paramEntry.isEmpty()) - App::GetApplication().GetParameterGroupByPath(prefPath.toLatin1())->SetBool(paramEntry,isChecked()); + if (!paramEntry.isEmpty()) { + App::GetApplication() + .GetParameterGroupByPath(prefPath.toLatin1()) + ->SetBool(paramEntry, isChecked()); + } QDialog::accept(); } void DlgCheckableMessageBox::reject() { - if(!paramEntry.isEmpty()) - App::GetApplication().GetParameterGroupByPath(prefPath.toLatin1())->SetBool(paramEntry,isChecked()); + if (!paramEntry.isEmpty()) { + App::GetApplication() + .GetParameterGroupByPath(prefPath.toLatin1()) + ->SetBool(paramEntry, isChecked()); + } QDialog::reject(); } -QDialogButtonBox::StandardButton - DlgCheckableMessageBox::question(QWidget *parent, - const QString &title, - const QString &question, - const QString &checkBoxText, - bool *checkBoxSetting, - QDialogButtonBox::StandardButtons buttons, - QDialogButtonBox::StandardButton defaultButton) +QDialogButtonBox::StandardButton DlgCheckableMessageBox::question( + QWidget* parent, + const QString& title, + const QString& question, + const QString& checkBoxText, + bool* checkBoxSetting, + QDialogButtonBox::StandardButtons buttons, + QDialogButtonBox::StandardButton defaultButton +) { DlgCheckableMessageBox mb(parent); mb.setWindowTitle(title); @@ -261,12 +291,14 @@ QDialogButtonBox::StandardButton return mb.clickedStandardButton(); } -QMessageBox::StandardButton DlgCheckableMessageBox::dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton db) +QMessageBox::StandardButton DlgCheckableMessageBox::dialogButtonBoxToMessageBoxButton( + QDialogButtonBox::StandardButton db +) { return static_cast(int(db)); } -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui #include "moc_DlgCheckableMessageBox.cpp" diff --git a/src/Gui/Dialogs/DlgCheckableMessageBox.h b/src/Gui/Dialogs/DlgCheckableMessageBox.h index 443bf54ba7..c07f91f394 100644 --- a/src/Gui/Dialogs/DlgCheckableMessageBox.h +++ b/src/Gui/Dialogs/DlgCheckableMessageBox.h @@ -35,8 +35,10 @@ #include #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ struct DlgCheckableMessageBoxPrivate; @@ -44,31 +46,40 @@ struct DlgCheckableMessageBoxPrivate; * "Do not ask me again" checkbox. Emulates the QMessageBox API with * static conveniences. */ -class GuiExport DlgCheckableMessageBox : public QDialog +class GuiExport DlgCheckableMessageBox: public QDialog { Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText) // clazy:exclude=qproperty-without-notify - Q_PROPERTY(QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap) // clazy:exclude=qproperty-without-notify - Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) // clazy:exclude=qproperty-without-notify - //Q_PROPERTY(QString prefEntry WRITE setPrefEntry) // Must have a READ accessor! - Q_PROPERTY(QString checkBoxText READ checkBoxText WRITE setCheckBoxText) // clazy:exclude=qproperty-without-notify - Q_PROPERTY(QDialogButtonBox::StandardButtons buttons READ standardButtons WRITE setStandardButtons) // clazy:exclude=qproperty-without-notify - Q_PROPERTY(QDialogButtonBox::StandardButton defaultButton READ defaultButton WRITE setDefaultButton) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QString text READ text WRITE setText) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( + QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap + ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) // clazy:exclude=qproperty-without-notify + // Q_PROPERTY(QString prefEntry WRITE setPrefEntry) // Must have a READ accessor! + Q_PROPERTY( + QString checkBoxText READ checkBoxText WRITE setCheckBoxText + ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( + QDialogButtonBox::StandardButtons buttons READ standardButtons WRITE setStandardButtons + ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( + QDialogButtonBox::StandardButton defaultButton READ defaultButton WRITE setDefaultButton + ) // clazy:exclude=qproperty-without-notify public: - explicit DlgCheckableMessageBox(QWidget *parent); + explicit DlgCheckableMessageBox(QWidget* parent); ~DlgCheckableMessageBox() override; - static QDialogButtonBox::StandardButton - question(QWidget *parent, - const QString &title, - const QString &question, - const QString &checkBoxText, - bool *checkBoxSetting, - QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Yes|QDialogButtonBox::No, - QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::No); + static QDialogButtonBox::StandardButton question( + QWidget* parent, + const QString& title, + const QString& question, + const QString& checkBoxText, + bool* checkBoxSetting, + QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Yes | QDialogButtonBox::No, + QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::No + ); QString text() const; - void setText(const QString &); + void setText(const QString&); void setPrefEntry(const QString& entry); @@ -81,7 +92,7 @@ public: void setChecked(bool s); QString checkBoxText() const; - void setCheckBoxText(const QString &); + void setCheckBoxText(const QString&); QDialogButtonBox::StandardButtons standardButtons() const; void setStandardButtons(QDialogButtonBox::StandardButtons s); @@ -91,35 +102,51 @@ public: // see static QMessageBox::standardPixmap() QPixmap iconPixmap() const; - void setIconPixmap (const QPixmap &p); + void setIconPixmap(const QPixmap& p); // Query the result - QAbstractButton *clickedButton() const; + QAbstractButton* clickedButton() const; QDialogButtonBox::StandardButton clickedStandardButton() const; // Conversion convenience - static QMessageBox::StandardButton dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton); + static QMessageBox::StandardButton dialogButtonBoxToMessageBoxButton( + QDialogButtonBox::StandardButton + ); /// convenient show method - /// It shows a dialog with header and message provided and a checkbox in check state with the message provided. - /// It uses a parameter in path "User parameter:BaseApp/CheckMessages" derived from the header test, defaulting to false, - /// to store the status of the checkbox, when the user exits the modal dialog. - static void showMessage(const QString& header, const QString& message, bool check = false, const QString& checkText = QStringLiteral("Don't show me again")); + /// It shows a dialog with header and message provided and a checkbox in check state with the + /// message provided. It uses a parameter in path "User parameter:BaseApp/CheckMessages" derived + /// from the header test, defaulting to false, to store the status of the checkbox, when the + /// user exits the modal dialog. + static void showMessage( + const QString& header, + const QString& message, + bool check = false, + const QString& checkText = QStringLiteral("Don't show me again") + ); - /// Same as showMessage above, but it checks the specific preference path and parameter provided, defaulting to entryDefault value if the parameter is not present. - static void showMessage(const QString& header, const QString& message, const QString& prefPath, const QString& paramEntry, bool entryDefault = false, - bool check = false, const QString& checkText = QStringLiteral("Don't show me again")); + /// Same as showMessage above, but it checks the specific preference path and parameter + /// provided, defaulting to entryDefault value if the parameter is not present. + static void showMessage( + const QString& header, + const QString& message, + const QString& prefPath, + const QString& paramEntry, + bool entryDefault = false, + bool check = false, + const QString& checkText = QStringLiteral("Don't show me again") + ); private Q_SLOTS: - void slotClicked(QAbstractButton *b); + void slotClicked(QAbstractButton* b); private: - DlgCheckableMessageBoxPrivate *m_d; + DlgCheckableMessageBoxPrivate* m_d; QByteArray paramEntry; QString prefPath; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // CHECKABLEMESSAGEBOX_H +#endif // CHECKABLEMESSAGEBOX_H diff --git a/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.cpp b/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.cpp index 63439472b2..14d4ddefdb 100644 --- a/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.cpp +++ b/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.cpp @@ -20,10 +20,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Dialogs/DlgCreateNewPreferencePackImp.h" #include "ui_DlgCreateNewPreferencePack.h" @@ -50,14 +50,26 @@ DlgCreateNewPreferencePackImp::DlgCreateNewPreferencePackImp(QWidget* parent) ui->lineEdit->setValidator(&_nameValidator); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(ui->treeWidget, &QTreeWidget::itemChanged, this, &DlgCreateNewPreferencePackImp::onItemChanged); - connect(ui->lineEdit, &QLineEdit::textEdited, this, &DlgCreateNewPreferencePackImp::onLineEditTextEdited); - connect(ui->pushButton, &QPushButton::clicked, this, &DlgCreateNewPreferencePackImp::onBrowseButtonClicked); + connect( + ui->lineEdit, + &QLineEdit::textEdited, + this, + &DlgCreateNewPreferencePackImp::onLineEditTextEdited + ); + connect( + ui->pushButton, + &QPushButton::clicked, + this, + &DlgCreateNewPreferencePackImp::onBrowseButtonClicked + ); } DlgCreateNewPreferencePackImp::~DlgCreateNewPreferencePackImp() = default; -void DlgCreateNewPreferencePackImp::setPreferencePackTemplates(const std::vector& availableTemplates) +void DlgCreateNewPreferencePackImp::setPreferencePackTemplates( + const std::vector& availableTemplates +) { ui->treeWidget->clear(); _groups.clear(); @@ -65,7 +77,7 @@ void DlgCreateNewPreferencePackImp::setPreferencePackTemplates(const std::vector ui->treeWidget->header()->setDefaultSectionSize(250); _templates = availableTemplates; - for (const auto &t : _templates) { + for (const auto& t : _templates) { QTreeWidgetItem* group; if (auto foundGroup = _groups.find(t.group); foundGroup != _groups.end()) { @@ -82,14 +94,17 @@ void DlgCreateNewPreferencePackImp::setPreferencePackTemplates(const std::vector itemColumns.push_back(QString::fromStdString(t.name)); auto newItem = new QTreeWidgetItem(group, itemColumns); newItem->setCheckState(0, Qt::Checked); - if (group->checkState(0) != newItem->checkState(0)) + if (group->checkState(0) != newItem->checkState(0)) { group->setCheckState(0, Qt::PartiallyChecked); + } newItem->setData(0, TemplateRole, QVariant::fromValue(t)); group->addChild(newItem); } } -void Gui::Dialog::DlgCreateNewPreferencePackImp::setPreferencePackNames(const std::vector& usedNames) +void Gui::Dialog::DlgCreateNewPreferencePackImp::setPreferencePackNames( + const std::vector& usedNames +) { _existingPackNames = usedNames; } @@ -98,11 +113,17 @@ std::vector DlgCreateNewPreferencePack { std::vector results; - for (const auto& group : _groups) - for (int childIndex = 0; childIndex < group.second->childCount(); ++childIndex) - if (auto child = group.second->child(childIndex); child->checkState(0) == Qt::Checked) - if (child->data(0, TemplateRole).canConvert()) - results.push_back(child->data(0, TemplateRole).value()); + for (const auto& group : _groups) { + for (int childIndex = 0; childIndex < group.second->childCount(); ++childIndex) { + if (auto child = group.second->child(childIndex); child->checkState(0) == Qt::Checked) { + if (child->data(0, TemplateRole).canConvert()) { + results.push_back( + child->data(0, TemplateRole).value() + ); + } + } + } + } return results; } @@ -156,19 +177,25 @@ void DlgCreateNewPreferencePackImp::onLineEditTextEdited(const QString& text) void DlgCreateNewPreferencePackImp::onBrowseButtonClicked() { - _cfgFileDirectory = FileDialog::getExistingDirectory(this, tr("Export configuration"), _cfgFileDirectory); + _cfgFileDirectory + = FileDialog::getExistingDirectory(this, tr("Export configuration"), _cfgFileDirectory); } void Gui::Dialog::DlgCreateNewPreferencePackImp::accept() { - // Ensure that the chosen name is either unique, or that the user actually wants to overwrite the old one + // Ensure that the chosen name is either unique, or that the user actually wants to overwrite + // the old one if (const auto chosenName = ui->lineEdit->text().toStdString(); std::ranges::find(_existingPackNames, chosenName) != _existingPackNames.end()) { - const auto result = QMessageBox::warning(this, tr("Pack already exists"), - tr("A preference pack with that name already exists. Overwrite it?"), - QMessageBox::Yes | QMessageBox::Cancel); - if (result == QMessageBox::Cancel) + const auto result = QMessageBox::warning( + this, + tr("Pack already exists"), + tr("A preference pack with that name already exists. Overwrite it?"), + QMessageBox::Yes | QMessageBox::Cancel + ); + if (result == QMessageBox::Cancel) { return; + } } QDialog::accept(); } diff --git a/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.h b/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.h index bf3b390c48..ca3d96f06c 100644 --- a/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.h +++ b/src/Gui/Dialogs/DlgCreateNewPreferencePackImp.h @@ -32,9 +32,11 @@ class QTreeWidgetItem; -namespace Gui { +namespace Gui +{ -namespace Dialog { +namespace Dialog +{ class Ui_DlgCreateNewPreferencePack; @@ -45,16 +47,17 @@ class Ui_DlgCreateNewPreferencePack; * * \author Chris Hennes */ -class GuiExport DlgCreateNewPreferencePackImp : public QDialog +class GuiExport DlgCreateNewPreferencePackImp: public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit DlgCreateNewPreferencePackImp(QWidget* parent = nullptr); ~DlgCreateNewPreferencePackImp() override; - void setPreferencePackTemplates(const std::vector &availableTemplates); + void setPreferencePackTemplates( + const std::vector& availableTemplates + ); void setPreferencePackNames(const std::vector& usedNames); std::vector selectedTemplates() const; @@ -65,7 +68,7 @@ protected Q_SLOTS: void onItemChanged(QTreeWidgetItem* item, int column); - void onLineEditTextEdited(const QString &text); + void onLineEditTextEdited(const QString& text); void onBrowseButtonClicked(); @@ -80,7 +83,7 @@ private: QString _cfgFileDirectory; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGCREATENEWTHEMEIMP_H +#endif // GUI_DIALOG_DLGCREATENEWTHEMEIMP_H diff --git a/src/Gui/Dialogs/DlgCustomizeImp.cpp b/src/Gui/Dialogs/DlgCustomizeImp.cpp index ca94bc7587..6584afe357 100644 --- a/src/Gui/Dialogs/DlgCustomizeImp.cpp +++ b/src/Gui/Dialogs/DlgCustomizeImp.cpp @@ -20,10 +20,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Dialogs/DlgCustomizeImp.h" #include "MainWindow.h" @@ -44,43 +44,43 @@ QList DlgCustomizeImp::_pages; * true to construct a modal dialog. */ DlgCustomizeImp::DlgCustomizeImp(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) + : QDialog(parent, fl) { setModal(false); setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - resize( 690, 365 ); + resize(690, 365); setWindowTitle(tr("Customize")); - setSizeGripEnabled( true ); + setSizeGripEnabled(true); - customLayout = new QGridLayout( this ); - customLayout->setSpacing( 6 ); - customLayout->setContentsMargins( 11, 11, 11, 11 ); + customLayout = new QGridLayout(this); + customLayout->setSpacing(6); + customLayout->setContentsMargins(11, 11, 11, 11); layout = new QHBoxLayout; - layout->setSpacing( 6 ); - layout->setContentsMargins( 0, 0, 0, 0 ); + layout->setSpacing(6); + layout->setContentsMargins(0, 0, 0, 0); - buttonHelp = new QPushButton( this ); + buttonHelp = new QPushButton(this); buttonHelp->setText(tr("&Help")); - layout->addWidget( buttonHelp ); + layout->addWidget(buttonHelp); - auto spacer = new QSpacerItem( 20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ); + auto spacer = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); layout->addItem(spacer); - buttonClose = new QPushButton( this ); + buttonClose = new QPushButton(this); buttonClose->setText(tr("&Close")); layout->addWidget(buttonClose); - customLayout->addLayout( layout, 1, 0 ); + customLayout->addLayout(layout, 1, 0); - tabWidget = new QTabWidget( this ); - tabWidget->setObjectName(QStringLiteral("Gui__Dialog__TabWidget"));//so we can find it in DlgMacroExecuteImp + tabWidget = new QTabWidget(this); + tabWidget->setObjectName(QStringLiteral("Gui__Dialog__TabWidget")); // so we can find it in + // DlgMacroExecuteImp // make sure that pages are ready to create GetWidgetFactorySupplier(); - for (const QByteArray& it : _pages) - { + for (const QByteArray& it : _pages) { addPage(WidgetFactory().createWidget(it.constData())); } @@ -93,7 +93,7 @@ DlgCustomizeImp::DlgCustomizeImp(QWidget* parent, Qt::WindowFlags fl) // connections // - connect(buttonHelp, &QPushButton::clicked, getMainWindow(), &MainWindow::whatsThis); + connect(buttonHelp, &QPushButton::clicked, getMainWindow(), &MainWindow::whatsThis); connect(buttonClose, &QPushButton::clicked, this, &QDialog::close); } @@ -114,19 +114,19 @@ void DlgCustomizeImp::addPage(const char* className) } /** Inserts a new tab page with its caption */ -void DlgCustomizeImp::addPage (QWidget* w) +void DlgCustomizeImp::addPage(QWidget* w) { tabWidget->addTab(w, w->windowTitle()); } -void DlgCustomizeImp::changeEvent(QEvent *e) +void DlgCustomizeImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { setWindowTitle(tr("Customize")); buttonHelp->setText(tr("&Help")); buttonClose->setText(tr("&Close")); int count = tabWidget->count(); - for (int i=0; iwidget(i); tabWidget->setTabText(i, w->windowTitle()); } diff --git a/src/Gui/Dialogs/DlgCustomizeImp.h b/src/Gui/Dialogs/DlgCustomizeImp.h index 320ca849cb..8f14b9c04b 100644 --- a/src/Gui/Dialogs/DlgCustomizeImp.h +++ b/src/Gui/Dialogs/DlgCustomizeImp.h @@ -30,8 +30,10 @@ class QTabWidget; class QGridLayout; class QHBoxLayout; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ /** * Dialog which contains several tab pages to customize @@ -46,7 +48,7 @@ namespace Dialog { * @see DlgCustomActionsImp * \author Werner Mayer */ -class DlgCustomizeImp : public QDialog +class DlgCustomizeImp: public QDialog { Q_OBJECT @@ -55,7 +57,7 @@ public: ~DlgCustomizeImp() override; static void addPage(const char* className); - void addPage (QWidget* w); + void addPage(QWidget* w); Q_SIGNALS: void addMacroAction(const QByteArray&); @@ -63,21 +65,21 @@ Q_SIGNALS: void modifyMacroAction(const QByteArray&); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: /** @name for internal use only */ //@{ - QPushButton* buttonHelp; /**< the help button */ - QPushButton* buttonClose; /**< the cancel button */ - QTabWidget* tabWidget; /**< tab widgets containing all pages */ - QGridLayout* customLayout; /**< layout */ - QHBoxLayout* layout; /** horizontal layout */ + QPushButton* buttonHelp; /**< the help button */ + QPushButton* buttonClose; /**< the cancel button */ + QTabWidget* tabWidget; /**< tab widgets containing all pages */ + QGridLayout* customLayout; /**< layout */ + QHBoxLayout* layout; /** horizontal layout */ static QList _pages; /**< Name of all registered preference pages */ //@} }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGCUSTOMIZE_IMP_H +#endif // GUI_DIALOG_DLGCUSTOMIZE_IMP_H diff --git a/src/Gui/Dialogs/DlgCustomizeSpNavSettings.cpp b/src/Gui/Dialogs/DlgCustomizeSpNavSettings.cpp index f87597e476..4592d3b129 100644 --- a/src/Gui/Dialogs/DlgCustomizeSpNavSettings.cpp +++ b/src/Gui/Dialogs/DlgCustomizeSpNavSettings.cpp @@ -195,12 +195,10 @@ void DlgCustomizeSpNavSettings::initialize() ui->SliderSpin->setEnabled(ui->CBRotations->isChecked() && ui->CBEnableSpin->isChecked()); ui->CBEnablePanLR->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() - && ui->CBEnablePanLR->isChecked()); + ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); ui->SliderPanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); ui->CBEnablePanUD->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() - && ui->CBEnablePanUD->isChecked()); + ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); ui->SliderPanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); ui->CBEnableZoom->setEnabled(ui->CBTranslations->isChecked()); ui->CBReverseZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); @@ -243,12 +241,10 @@ void DlgCustomizeSpNavSettings::on_CBTranslations_clicked() spaceballMotionGroup()->SetBool("Translations", ui->CBTranslations->isChecked()); ui->CBEnablePanLR->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() - && ui->CBEnablePanLR->isChecked()); + ui->CBReversePanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); ui->SliderPanLR->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanLR->isChecked()); ui->CBEnablePanUD->setEnabled(ui->CBTranslations->isChecked()); - ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() - && ui->CBEnablePanUD->isChecked()); + ui->CBReversePanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); ui->SliderPanUD->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnablePanUD->isChecked()); ui->CBEnableZoom->setEnabled(ui->CBTranslations->isChecked()); ui->CBReverseZoom->setEnabled(ui->CBTranslations->isChecked() && ui->CBEnableZoom->isChecked()); diff --git a/src/Gui/Dialogs/DlgCustomizeSpNavSettings.h b/src/Gui/Dialogs/DlgCustomizeSpNavSettings.h index a2bf9c121c..95eecfadf3 100644 --- a/src/Gui/Dialogs/DlgCustomizeSpNavSettings.h +++ b/src/Gui/Dialogs/DlgCustomizeSpNavSettings.h @@ -32,62 +32,62 @@ class Ui_DlgCustomizeSpNavSettings; namespace Gui { - namespace Dialog - { - class DlgCustomizeSpNavSettings : public CustomizeActionPage - { - Q_OBJECT +namespace Dialog +{ +class DlgCustomizeSpNavSettings: public CustomizeActionPage +{ + Q_OBJECT - public: - explicit DlgCustomizeSpNavSettings(QWidget *parent = nullptr); - ~DlgCustomizeSpNavSettings() override; +public: + explicit DlgCustomizeSpNavSettings(QWidget* parent = nullptr); + ~DlgCustomizeSpNavSettings() override; - protected Q_SLOTS: - void onAddMacroAction(const QByteArray&) override; - void onRemoveMacroAction(const QByteArray&) override; - void onModifyMacroAction(const QByteArray&) override; +protected Q_SLOTS: + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; - protected: - void setupConnections(); - void on_CBDominant_clicked(); - void on_CBFlipYZ_clicked(); - void on_CBRotations_clicked(); - void on_CBTranslations_clicked(); - void on_SliderGlobal_sliderReleased(); - void on_CBEnablePanLR_clicked(); - void on_CBReversePanLR_clicked(); - void on_SliderPanLR_sliderReleased(); - void on_CBEnablePanUD_clicked(); - void on_CBReversePanUD_clicked(); - void on_SliderPanUD_sliderReleased(); - void on_CBEnableZoom_clicked(); - void on_CBReverseZoom_clicked(); - void on_SliderZoom_sliderReleased(); - void on_CBEnableTilt_clicked(); - void on_CBReverseTilt_clicked(); - void on_SliderTilt_sliderReleased(); - void on_CBEnableRoll_clicked(); - void on_CBReverseRoll_clicked(); - void on_SliderRoll_sliderReleased(); - void on_CBEnableSpin_clicked(); - void on_CBReverseSpin_clicked(); - void on_SliderSpin_sliderReleased(); - void on_ButtonDefaultSpNavMotions_clicked(); - void on_ButtonCalibrate_clicked(); +protected: + void setupConnections(); + void on_CBDominant_clicked(); + void on_CBFlipYZ_clicked(); + void on_CBRotations_clicked(); + void on_CBTranslations_clicked(); + void on_SliderGlobal_sliderReleased(); + void on_CBEnablePanLR_clicked(); + void on_CBReversePanLR_clicked(); + void on_SliderPanLR_sliderReleased(); + void on_CBEnablePanUD_clicked(); + void on_CBReversePanUD_clicked(); + void on_SliderPanUD_sliderReleased(); + void on_CBEnableZoom_clicked(); + void on_CBReverseZoom_clicked(); + void on_SliderZoom_sliderReleased(); + void on_CBEnableTilt_clicked(); + void on_CBReverseTilt_clicked(); + void on_SliderTilt_sliderReleased(); + void on_CBEnableRoll_clicked(); + void on_CBReverseRoll_clicked(); + void on_SliderRoll_sliderReleased(); + void on_CBEnableSpin_clicked(); + void on_CBReverseSpin_clicked(); + void on_SliderSpin_sliderReleased(); + void on_ButtonDefaultSpNavMotions_clicked(); + void on_ButtonCalibrate_clicked(); - protected: - void changeEvent(QEvent *e) override; +protected: + void changeEvent(QEvent* e) override; - private: - ParameterGrp::handle spaceballMotionGroup() const; - void setMessage(const QString& message); - void initialize(); +private: + ParameterGrp::handle spaceballMotionGroup() const; + void setMessage(const QString& message); + void initialize(); - private: - std::unique_ptr ui; - bool init; - }; - } -} +private: + std::unique_ptr ui; + bool init; +}; +} // namespace Dialog +} // namespace Gui -#endif // DLGCUSTOMIZESPNAVSETTINGS_H +#endif // DLGCUSTOMIZESPNAVSETTINGS_H diff --git a/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp b/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp index 16606bd4a7..1e30d90a9c 100644 --- a/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp +++ b/src/Gui/Dialogs/DlgCustomizeSpaceball.cpp @@ -42,14 +42,13 @@ #include "SpaceballEvent.h" -using GroupVector = std::vector >; +using GroupVector = std::vector>; using namespace Gui::Dialog; -ButtonView::ButtonView(QWidget *parent) : QListView(parent) -{ - -} +ButtonView::ButtonView(QWidget* parent) + : QListView(parent) +{} void ButtonView::selectButton(int number) { @@ -57,11 +56,12 @@ void ButtonView::selectButton(int number) this->scrollTo(this->model()->index(number, 0), QAbstractItemView::EnsureVisible); } -void ButtonView::goSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) +void ButtonView::goSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { Q_UNUSED(deselected); - if (selected.indexes().isEmpty()) + if (selected.indexes().isEmpty()) { return; + } QModelIndex select(selected.indexes().at(0)); Q_EMIT changeCommandSelection(this->model()->data(select, Qt::UserRole).toString()); } @@ -70,160 +70,161 @@ void ButtonView::goChangedCommand(const QString& commandName) { QModelIndex index(this->currentIndex()); auto model = dynamic_cast(this->model()); - if (model && index.isValid()) + if (model && index.isValid()) { model->setCommand(index.row(), commandName); + } } /////////////////////////////////////////////////////////////////////////////////////// -ButtonModel::ButtonModel(QObject *parent) : QAbstractListModel(parent) +ButtonModel::ButtonModel(QObject* parent) + : QAbstractListModel(parent) { - //load3DConnexionButtons("SpacePilot Pro"); + // load3DConnexionButtons("SpacePilot Pro"); } // Process the given Mapping tree to load in the Button mappings. void ButtonModel::load3DConnexionButtonMapping(boost::property_tree::ptree ButtonMapTree) { - spaceballButtonGroup()->Clear(); + spaceballButtonGroup()->Clear(); - BOOST_FOREACH(const boost::property_tree::ptree::value_type &Map, ButtonMapTree.get_child("Mapping")) - { - if ("Map" == Map.first) - { - std::string ButtonDescription; - std::string ButtonCode; - std::string ButtonCommand; - std::string ButtonDownTime; + BOOST_FOREACH ( + const boost::property_tree::ptree::value_type& Map, + ButtonMapTree.get_child("Mapping") + ) { + if ("Map" == Map.first) { + std::string ButtonDescription; + std::string ButtonCode; + std::string ButtonCommand; + std::string ButtonDownTime; - // Inspect Map attributes - BOOST_FOREACH(const boost::property_tree::ptree::value_type &kv, Map.second.get_child("")) - { - std::string Attribute; - std::string Value; + // Inspect Map attributes + BOOST_FOREACH ( + const boost::property_tree::ptree::value_type& kv, + Map.second.get_child("") + ) { + std::string Attribute; + std::string Value; - Attribute = kv.first.data(); - Value = kv.second.data(); + Attribute = kv.first.data(); + Value = kv.second.data(); - if (0 == Attribute.compare("Description")) - { - ButtonDescription = Value; + if (0 == Attribute.compare("Description")) { + ButtonDescription = Value; + } + if (0 == Attribute.compare("KeyCode")) { + ButtonCode = Value; + } + if (0 == Attribute.compare("DownTime")) { + ButtonDownTime = Value; + } + if (0 == Attribute.compare("Command")) { + ButtonCommand = Value; + } } - if (0 == Attribute.compare("KeyCode")) - { - ButtonCode = Value; - } - if (0 == Attribute.compare("DownTime")) - { - ButtonDownTime = Value; - } - if (0 == Attribute.compare("Command")) - { - ButtonCommand = Value; - } - } - // ButtonCode is mandatory, the remaining attributes optional. - if (!ButtonCode.empty()) - { - Base::Reference newGroup; + // ButtonCode is mandatory, the remaining attributes optional. + if (!ButtonCode.empty()) { + Base::Reference newGroup; - newGroup = spaceballButtonGroup()->GetGroup(ButtonCode.c_str()); - newGroup->SetASCII("Command", ButtonCommand.c_str()); - newGroup->SetASCII("Description", ButtonDescription.c_str()); - } - } - } + newGroup = spaceballButtonGroup()->GetGroup(ButtonCode.c_str()); + newGroup->SetASCII("Command", ButtonCommand.c_str()); + newGroup->SetASCII("Description", ButtonDescription.c_str()); + } + } + } } // Optionally preload Button model with 3DConnexion configuration to match Solidworks // For now the Button mapping file (3DConnexion.xml) is held the same folder as the FreeCAD executable. -void ButtonModel::load3DConnexionButtons(const char *RequiredDeviceName) +void ButtonModel::load3DConnexionButtons(const char* RequiredDeviceName) { - try - { - boost::property_tree::ptree tree; - boost::property_tree::ptree DeviceTree; + try { + boost::property_tree::ptree tree; + boost::property_tree::ptree DeviceTree; - // exception thrown if no file found - std::string path = App::Application::getResourceDir(); - path += "3Dconnexion/3DConnexion.xml"; - read_xml(path.c_str(), tree); + // exception thrown if no file found + std::string path = App::Application::getResourceDir(); + path += "3Dconnexion/3DConnexion.xml"; + read_xml(path.c_str(), tree); - BOOST_FOREACH(const boost::property_tree::ptree::value_type &ButtonMap, tree.get_child("")) - { - if ("ButtonMap" == ButtonMap.first) - { - // Inspect ButtonMap attributes for DeviceName - BOOST_FOREACH(const boost::property_tree::ptree::value_type &kv, ButtonMap.second.get_child("")) - { - std::string Attribute; - std::string Value; + BOOST_FOREACH (const boost::property_tree::ptree::value_type& ButtonMap, tree.get_child("")) { + if ("ButtonMap" == ButtonMap.first) { + // Inspect ButtonMap attributes for DeviceName + BOOST_FOREACH ( + const boost::property_tree::ptree::value_type& kv, + ButtonMap.second.get_child("") + ) { + std::string Attribute; + std::string Value; - Attribute = kv.first.data(); - Value = kv.second.data(); + Attribute = kv.first.data(); + Value = kv.second.data(); - if (0 == Attribute.compare("DeviceName")) - { - if (0 == Value.compare(RequiredDeviceName)) - { - // We found the ButtonMap we want to load up - DeviceTree = ButtonMap.second; - } - } + if (0 == Attribute.compare("DeviceName")) { + if (0 == Value.compare(RequiredDeviceName)) { + // We found the ButtonMap we want to load up + DeviceTree = ButtonMap.second; + } + } + } } - } - } - // If we found the required devices ButtonMap - if (!DeviceTree.empty()) - { - load3DConnexionButtonMapping(DeviceTree); - } - } - catch (const std::exception& e) - { - // We don't mind not finding the file to be opened - Base::Console().warning("%s\n", e.what()); - } + } + // If we found the required devices ButtonMap + if (!DeviceTree.empty()) { + load3DConnexionButtonMapping(DeviceTree); + } + } + catch (const std::exception& e) { + // We don't mind not finding the file to be opened + Base::Console().warning("%s\n", e.what()); + } } -int ButtonModel::rowCount (const QModelIndex &parent) const +int ButtonModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return spaceballButtonGroup()->GetGroups().size(); } -QVariant ButtonModel::data (const QModelIndex &index, int role) const +QVariant ButtonModel::data(const QModelIndex& index, int role) const { GroupVector groupVector = spaceballButtonGroup()->GetGroups(); - if (index.row() >= (int)groupVector.size()) - { + if (index.row() >= (int)groupVector.size()) { Base::Console().log("index error in ButtonModel::data\n"); return {}; } - if (role == Qt::DisplayRole) + if (role == Qt::DisplayRole) { return {getLabel(index.row())}; - if (role == Qt::DecorationRole) - { - static QPixmap icon(BitmapFactory().pixmap("spaceball_button").scaled - (32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); - return QVariant(QIcon(icon)); // Cannot make a QPixmap into a QVariant, so convert to a QIcon first } - if (role == Qt::UserRole) + if (role == Qt::DecorationRole) { + static QPixmap icon( + BitmapFactory() + .pixmap("spaceball_button") + .scaled(32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) + ); + return QVariant(QIcon(icon)); // Cannot make a QPixmap into a QVariant, so convert to a + // QIcon first + } + if (role == Qt::UserRole) { return {QString::fromStdString(groupVector.at(index.row())->GetASCII("Command"))}; - if (role == Qt::SizeHintRole) + } + if (role == Qt::SizeHintRole) { return {QSize(32, 32)}; + } return {}; } void ButtonModel::insertButtonRows(int number) { int buttonCount = spaceballButtonGroup()->GetGroups().size(); - beginInsertRows(QModelIndex(), buttonCount, number-buttonCount+1); - for (int index = buttonCount; index < number + 1; ++index) - { + beginInsertRows(QModelIndex(), buttonCount, number - buttonCount + 1); + for (int index = buttonCount; index < number + 1; ++index) { QString groupName; groupName.setNum(index); - Base::Reference newGroup = spaceballButtonGroup()->GetGroup(groupName.toLatin1());//builds the group. + Base::Reference newGroup = spaceballButtonGroup()->GetGroup( + groupName.toLatin1() + ); // builds the group. newGroup->SetASCII("Command", ""); newGroup->SetASCII("Description", ""); } @@ -241,50 +242,60 @@ void ButtonModel::goButtonPress(int number) { QString numberString; numberString.setNum(number); - if (!spaceballButtonGroup()->HasGroup(numberString.toLatin1())) + if (!spaceballButtonGroup()->HasGroup(numberString.toLatin1())) { insertButtonRows(number); + } } void ButtonModel::goMacroRemoved(const QByteArray& macroName) { GroupVector groupVector = spaceballButtonGroup()->GetGroups(); - for (auto & it : groupVector) - if (std::string(macroName.data()) == it->GetASCII("Command")) + for (auto& it : groupVector) { + if (std::string(macroName.data()) == it->GetASCII("Command")) { it->SetASCII("Command", ""); + } + } } void ButtonModel::goClear() { - if (this->rowCount() < 1) + if (this->rowCount() < 1) { return; - this->beginRemoveRows(QModelIndex(), 0, this->rowCount()-1); + } + this->beginRemoveRows(QModelIndex(), 0, this->rowCount() - 1); spaceballButtonGroup()->Clear(); this->endRemoveRows(); } ParameterGrp::handle ButtonModel::spaceballButtonGroup() const { - static ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> - GetGroup("Spaceball")->GetGroup("Buttons"); + static ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Spaceball") + ->GetGroup("Buttons"); return group; } -QString ButtonModel::getLabel(const int &number) const +QString ButtonModel::getLabel(const int& number) const { if (number > -1 && number < 32) { QString numberString; numberString.setNum(number); - QString desc = QString::fromStdString(spaceballButtonGroup()-> - GetGroup(numberString.toLatin1())-> - GetASCII("Description","")); - if (desc.length()) + QString desc = QString::fromStdString( + spaceballButtonGroup()->GetGroup(numberString.toLatin1())->GetASCII("Description", "") + ); + if (desc.length()) { desc = QStringLiteral(" \"") + desc + QStringLiteral("\""); + } return tr("Button %1").arg(number + 1) + desc; - } else + } + else { return tr("Out of range"); + } } -void ButtonModel::loadConfig(const char *RequiredDeviceName) +void ButtonModel::loadConfig(const char* RequiredDeviceName) { goClear(); if (!RequiredDeviceName) { @@ -295,7 +306,8 @@ void ButtonModel::loadConfig(const char *RequiredDeviceName) ////////////////////////////////////////////////////////////////////////////////////////// -CommandView::CommandView(QWidget *parent) : QTreeView(parent) +CommandView::CommandView(QWidget* parent) + : QTreeView(parent) { this->setEnabled(false); connect(this, &QTreeView::clicked, this, &CommandView::goClicked); @@ -303,27 +315,35 @@ CommandView::CommandView(QWidget *parent) : QTreeView(parent) void CommandView::goChangeCommandSelection(const QString& commandName) { - if (!this->isEnabled()) + if (!this->isEnabled()) { this->setEnabled(true); + } this->selectionModel()->clear(); this->collapseAll(); - if (commandName.isEmpty()) + if (commandName.isEmpty()) { return; - QModelIndexList index(this->model()->match(this->model()->index(0,0), Qt::UserRole, QVariant(commandName), 1, - Qt::MatchWrap | Qt::MatchRecursive)); - if (index.empty()) + } + QModelIndexList index(this->model()->match( + this->model()->index(0, 0), + Qt::UserRole, + QVariant(commandName), + 1, + Qt::MatchWrap | Qt::MatchRecursive + )); + if (index.empty()) { return; + } this->expand(index.at(0)); this->setCurrentIndex(index.at(0)); } -void CommandView::goClicked(const QModelIndex &index) +void CommandView::goClicked(const QModelIndex& index) { - if (index.flags() & Qt::ItemIsSelectable) - { + if (index.flags() & Qt::ItemIsSelectable) { QString commandName = this->model()->data(index, Qt::UserRole).toString(); - if (commandName.isEmpty()) + if (commandName.isEmpty()) { return; + } Q_EMIT changedCommand(commandName); } } @@ -332,12 +352,12 @@ void CommandView::goClicked(const QModelIndex &index) CommandNode::CommandNode(NodeType typeIn) { - //NOLINTBEGIN + // NOLINTBEGIN nodeType = typeIn; parent = nullptr; children.clear(); aCommand = nullptr; - //NOLINTEND + // NOLINTEND } CommandNode::~CommandNode() @@ -347,12 +367,13 @@ CommandNode::~CommandNode() ///////////////////////////////////////////////////////////////////////////////////////// -CommandModel::CommandModel(QObject *parent) : QAbstractItemModel(parent) +CommandModel::CommandModel(QObject* parent) + : QAbstractItemModel(parent) { - //NOLINTBEGIN + // NOLINTBEGIN rootNode = nullptr; initialize(); - //NOLINTEND + // NOLINTEND } CommandModel::~CommandModel() @@ -361,145 +382,171 @@ CommandModel::~CommandModel() rootNode = nullptr; } -QModelIndex CommandModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex CommandModel::index(int row, int column, const QModelIndex& parent) const { - if (!rootNode) + if (!rootNode) { return {}; - if (!parent.isValid()) + } + if (!parent.isValid()) { return createIndex(row, column, rootNode->children.at(row)); + } - CommandNode *parentNode = nodeFromIndex(parent); - if (!parentNode) + CommandNode* parentNode = nodeFromIndex(parent); + if (!parentNode) { return {}; + } return createIndex(row, column, parentNode->children.at(row)); } -QModelIndex CommandModel::parent(const QModelIndex &index) const +QModelIndex CommandModel::parent(const QModelIndex& index) const { - CommandNode *base = nodeFromIndex(index); - if (!base) + CommandNode* base = nodeFromIndex(index); + if (!base) { return {}; - CommandNode *parentNode = base->parent; - if (!parentNode) + } + CommandNode* parentNode = base->parent; + if (!parentNode) { return {}; - CommandNode *grandParentNode = parentNode->parent; - if (!grandParentNode) + } + CommandNode* grandParentNode = parentNode->parent; + if (!grandParentNode) { return {}; + } int row = grandParentNode->children.indexOf(parentNode); - if (row == -1) + if (row == -1) { return {}; + } return createIndex(row, index.column(), parentNode); } -int CommandModel::rowCount(const QModelIndex &parent) const +int CommandModel::rowCount(const QModelIndex& parent) const { - if (!parent.isValid()) + if (!parent.isValid()) { return rootNode->children.size(); + } - CommandNode *parentNode = nodeFromIndex(parent); - if (!parentNode) + CommandNode* parentNode = nodeFromIndex(parent); + if (!parentNode) { return 0; + } return parentNode->children.count(); } -int CommandModel::columnCount(const QModelIndex &parent) const +int CommandModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 1; } -QVariant CommandModel::data(const QModelIndex &index, int role) const +QVariant CommandModel::data(const QModelIndex& index, int role) const { - CommandNode *node = nodeFromIndex(index); - if (!node) + CommandNode* node = nodeFromIndex(index); + if (!node) { return {}; - if (role == Qt::DisplayRole) - { - if (node->nodeType == CommandNode::CommandType) + } + if (role == Qt::DisplayRole) { + if (node->nodeType == CommandNode::CommandType) { return {qApp->translate(node->aCommand->className(), node->aCommand->getMenuText())}; - if (node->nodeType == CommandNode::GroupType) - { - if (node->children.empty()) + } + if (node->nodeType == CommandNode::GroupType) { + if (node->children.empty()) { return {}; - CommandNode *childNode = node->children.at(0); - return {qApp->translate(childNode->aCommand->className(), childNode->aCommand->getGroupName())}; + } + CommandNode* childNode = node->children.at(0); + return { + qApp->translate(childNode->aCommand->className(), childNode->aCommand->getGroupName()) + }; } return {}; } - if (role == Qt::DecorationRole) - { - if (node->nodeType == CommandNode::CommandType) - { - if (node->aCommand->getPixmap()) - return QVariant(BitmapFactory().pixmap(node->aCommand->getPixmap()).scaled - (32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + if (role == Qt::DecorationRole) { + if (node->nodeType == CommandNode::CommandType) { + if (node->aCommand->getPixmap()) { + return QVariant( + BitmapFactory() + .pixmap(node->aCommand->getPixmap()) + .scaled(32, 32, Qt::IgnoreAspectRatio, Qt::SmoothTransformation) + ); + } } } if (role == Qt::SizeHintRole) { - if (node->nodeType == CommandNode::CommandType) + if (node->nodeType == CommandNode::CommandType) { return {QSize(32, 32)}; + } } - if (role == Qt::UserRole) - { - if (node->nodeType == CommandNode::CommandType) + if (role == Qt::UserRole) { + if (node->nodeType == CommandNode::CommandType) { return {QString::fromLatin1(node->aCommand->getName())}; - if (node->nodeType == CommandNode::GroupType) - { - if (node->children.empty()) + } + if (node->nodeType == CommandNode::GroupType) { + if (node->children.empty()) { return {}; - CommandNode *childNode = node->children.at(0); + } + CommandNode* childNode = node->children.at(0); return {QString::fromLatin1(childNode->aCommand->getGroupName())}; } return {}; } if (role == Qt::ToolTipRole) { - if (node->nodeType == CommandNode::CommandType) + if (node->nodeType == CommandNode::CommandType) { return {QString::fromLatin1(node->aCommand->getToolTipText())}; + } } return {}; } QVariant CommandModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section == 0) + if (role == Qt::DisplayRole && orientation == Qt::Horizontal && section == 0) { return {tr("Commands")}; + } return {}; } -Qt::ItemFlags CommandModel::flags (const QModelIndex &index) const +Qt::ItemFlags CommandModel::flags(const QModelIndex& index) const { - if (!index.isValid()) + if (!index.isValid()) { return Qt::NoItemFlags; - CommandNode *node = nodeFromIndex(index); - if (!node) + } + CommandNode* node = nodeFromIndex(index); + if (!node) { return Qt::NoItemFlags; - if (node->nodeType == CommandNode::CommandType) + } + if (node->nodeType == CommandNode::CommandType) { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; + } return Qt::NoItemFlags; } -CommandNode* CommandModel::nodeFromIndex(const QModelIndex &index) const +CommandNode* CommandModel::nodeFromIndex(const QModelIndex& index) const { - if (index.isValid()) - return static_cast(index.internalPointer()); + if (index.isValid()) { + return static_cast(index.internalPointer()); + } return rootNode; } -void CommandModel::goAddMacro(const QByteArray ¯oName) +void CommandModel::goAddMacro(const QByteArray& macroName) { - QModelIndexList indexList(this->match(this->index(0,0), Qt::UserRole, QVariant(QStringLiteral("Macros")), - 1, Qt::MatchWrap | Qt::MatchRecursive)); + QModelIndexList indexList(this->match( + this->index(0, 0), + Qt::UserRole, + QVariant(QStringLiteral("Macros")), + 1, + Qt::MatchWrap | Qt::MatchRecursive + )); QModelIndex macrosIndex; - if (indexList.empty()) - { - //this is the first macro and we have to add the Macros item. - //figure out where to insert it. Should be in the command groups now. + if (indexList.empty()) { + // this is the first macro and we have to add the Macros item. + // figure out where to insert it. Should be in the command groups now. QStringList groups = orderedGroups(); int location(groups.indexOf(QStringLiteral("Macros"))); - if (location == -1) + if (location == -1) { location = groups.size(); - //add row + } + // add row this->beginInsertRows(QModelIndex(), location, location); auto macroNode = new CommandNode(CommandNode::GroupType); macroNode->parent = rootNode; @@ -507,17 +554,20 @@ void CommandModel::goAddMacro(const QByteArray ¯oName) this->endInsertRows(); macrosIndex = this->index(location, 0); } - else + else { macrosIndex = indexList.at(0); + } - Command *command = nullptr; + Command* command = nullptr; command = Application::Instance->commandManager().getCommandByName(macroName); - if (!command) + if (!command) { return; + } - CommandNode *parentNode = nodeFromIndex(macrosIndex); - if (!parentNode) + CommandNode* parentNode = nodeFromIndex(macrosIndex); + if (!parentNode) { return; + } this->beginInsertRows(macrosIndex, parentNode->children.size(), parentNode->children.size()); auto childNode = new CommandNode(CommandNode::CommandType); @@ -527,29 +577,36 @@ void CommandModel::goAddMacro(const QByteArray ¯oName) this->endInsertRows(); } -void CommandModel::goRemoveMacro(const QByteArray ¯oName) +void CommandModel::goRemoveMacro(const QByteArray& macroName) { - QModelIndexList macroList(this->match(this->index(0,0), Qt::UserRole, QVariant(QString::fromLatin1(macroName.data())), - 1, Qt::MatchWrap | Qt::MatchRecursive)); - if (macroList.isEmpty()) + QModelIndexList macroList(this->match( + this->index(0, 0), + Qt::UserRole, + QVariant(QString::fromLatin1(macroName.data())), + 1, + Qt::MatchWrap | Qt::MatchRecursive + )); + if (macroList.isEmpty()) { return; + } QModelIndex childIndex(macroList.at(0)); QModelIndex parentIndex(this->parent(childIndex)); - if (!childIndex.isValid() || !parentIndex.isValid()) + if (!childIndex.isValid() || !parentIndex.isValid()) { return; + } - CommandNode *parentNode = nodeFromIndex(parentIndex); - if (!parentNode) + CommandNode* parentNode = nodeFromIndex(parentIndex); + if (!parentNode) { return; + } this->beginRemoveRows(parentIndex, childIndex.row(), childIndex.row()); delete parentNode->children.takeAt(childIndex.row()); this->endRemoveRows(); - if (parentNode->children.isEmpty()) - { - QModelIndex grandParentIndex(this->parent(parentIndex));//this should be root. - CommandNode *grandParentNode = nodeFromIndex(grandParentIndex); + if (parentNode->children.isEmpty()) { + QModelIndex grandParentIndex(this->parent(parentIndex)); // this should be root. + CommandNode* grandParentNode = nodeFromIndex(grandParentIndex); this->beginRemoveRows(grandParentIndex, parentIndex.row(), parentIndex.row()); delete grandParentNode->children.takeAt(parentIndex.row()); this->endRemoveRows(); @@ -560,8 +617,9 @@ void CommandModel::initialize() { rootNode = new CommandNode(CommandNode::RootType); QStringList groups(orderedGroups()); - for (const auto & group : groups) + for (const auto& group : groups) { groupCommands(group); + } } void CommandModel::groupCommands(const QString& groupName) @@ -569,9 +627,10 @@ void CommandModel::groupCommands(const QString& groupName) auto parentNode = new CommandNode(CommandNode::GroupType); parentNode->parent = rootNode; rootNode->children.push_back(parentNode); - std::vector commands = Application::Instance->commandManager().getGroupCommands(groupName.toLatin1()); - for (const auto & command : commands) - { + std::vector commands = Application::Instance->commandManager().getGroupCommands( + groupName.toLatin1() + ); + for (const auto& command : commands) { auto childNode = new CommandNode(CommandNode::CommandType); childNode->parent = parentNode; parentNode->children.push_back(childNode); @@ -582,59 +641,67 @@ void CommandModel::groupCommands(const QString& groupName) QStringList CommandModel::orderedGroups() { QStringList groups; - std::vector commands = Application::Instance->commandManager().getAllCommands(); - for (const auto & command : commands) - { + std::vector commands = Application::Instance->commandManager().getAllCommands(); + for (const auto& command : commands) { QString groupName(QString::fromLatin1(command->getGroupName())); - if (!groups.contains(groupName)) + if (!groups.contains(groupName)) { groups << groupName; + } } - //how to sort? + // how to sort? groups.sort(); return groups; } /////////////////////////////////////////////////////////////////////////////////////// -PrintModel::PrintModel(QObject *parent, ButtonModel *buttonModelIn, CommandModel *commandModelIn) : QAbstractTableModel(parent) +PrintModel::PrintModel(QObject* parent, ButtonModel* buttonModelIn, CommandModel* commandModelIn) + : QAbstractTableModel(parent) { - //NOLINTBEGIN + // NOLINTBEGIN buttonModel = buttonModelIn; commandModel = commandModelIn; - //NOLINTEND + // NOLINTEND } -int PrintModel::rowCount(const QModelIndex &parent) const +int PrintModel::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return buttonModel->rowCount(); } -int PrintModel::columnCount(const QModelIndex &parent) const +int PrintModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 2; } -QVariant PrintModel::data(const QModelIndex &index, int role) const +QVariant PrintModel::data(const QModelIndex& index, int role) const { - if (index.column() == 0) - { - //button column; + if (index.column() == 0) { + // button column; return buttonModel->data(buttonModel->index(index.row(), 0), role); } - if (index.column() == 1) - { - //command column; - QString commandName(buttonModel->data(buttonModel->index(index.row(), 0), Qt::UserRole).toString()); - if (commandName.isEmpty()) + if (index.column() == 1) { + // command column; + QString commandName( + buttonModel->data(buttonModel->index(index.row(), 0), Qt::UserRole).toString() + ); + if (commandName.isEmpty()) { return {}; + } - QModelIndexList indexList(commandModel->match(commandModel->index(0,0), Qt::UserRole, QVariant(commandName), 1, - Qt::MatchWrap | Qt::MatchRecursive)); - if (indexList.isEmpty()) + QModelIndexList indexList(commandModel->match( + commandModel->index(0, 0), + Qt::UserRole, + QVariant(commandName), + 1, + Qt::MatchWrap | Qt::MatchRecursive + )); + if (indexList.isEmpty()) { return {}; + } return commandModel->data(indexList.at(0), role); } @@ -643,44 +710,51 @@ QVariant PrintModel::data(const QModelIndex &index, int role) const QVariant PrintModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role != Qt::DisplayRole || orientation != Qt::Horizontal) + if (role != Qt::DisplayRole || orientation != Qt::Horizontal) { return {}; - if (section == 0) + } + if (section == 0) { return {tr("Button")}; - if (section == 1) + } + if (section == 1) { return {tr("Command")}; - else + } + else { return {}; + } } /////////////////////////////////////////////////////////////////////////////////////// -DlgCustomizeSpaceball::DlgCustomizeSpaceball(QWidget *parent) - : CustomizeActionPage(parent) - , buttonView(nullptr) - , buttonModel(nullptr) - , commandView(nullptr) - , commandModel(nullptr) - , clearButton(nullptr) - , printReference(nullptr) - , devModel(nullptr) +DlgCustomizeSpaceball::DlgCustomizeSpaceball(QWidget* parent) + : CustomizeActionPage(parent) + , buttonView(nullptr) + , buttonModel(nullptr) + , commandView(nullptr) + , commandModel(nullptr) + , clearButton(nullptr) + , printReference(nullptr) + , devModel(nullptr) { this->setWindowTitle(tr("Spaceball Buttons")); - auto app = qobject_cast(QApplication::instance()); - if (!app) + auto app = qobject_cast(QApplication::instance()); + if (!app) { return; - if (!app->isSpaceballPresent()) - { + } + if (!app->isSpaceballPresent()) { this->setMessage(tr("No Spaceball present")); return; } setupButtonModelView(); setupCommandModelView(); - connect(buttonView, &ButtonView::changeCommandSelection, - commandView, &CommandView::goChangeCommandSelection); - connect(commandView, &CommandView::changedCommand, - buttonView, &ButtonView::goChangedCommand); + connect( + buttonView, + &ButtonView::changeCommandSelection, + commandView, + &CommandView::goChangeCommandSelection + ); + connect(commandView, &CommandView::changedCommand, buttonView, &ButtonView::goChangedCommand); setupLayout(); connect(clearButton, &QPushButton::clicked, this, &DlgCustomizeSpaceball::goClear); connect(printReference, &QPushButton::clicked, this, &DlgCustomizeSpaceball::goPrint); @@ -690,7 +764,7 @@ DlgCustomizeSpaceball::~DlgCustomizeSpaceball() = default; void DlgCustomizeSpaceball::setMessage(const QString& message) { - auto messageLabel = new QLabel(message,this); + auto messageLabel = new QLabel(message, this); auto layout = new QVBoxLayout(); auto layout2 = new QHBoxLayout(); layout2->addStretch(); @@ -706,9 +780,13 @@ void DlgCustomizeSpaceball::setupButtonModelView() buttonView = new ButtonView(this); buttonView->setModel(buttonModel); - //had to do this here as the views default selection model is not created until after construction. - connect(buttonView->selectionModel(), &QItemSelectionModel::selectionChanged, - buttonView, &ButtonView::goSelectionChanged); + // had to do this here as the views default selection model is not created until after construction. + connect( + buttonView->selectionModel(), + &QItemSelectionModel::selectionChanged, + buttonView, + &ButtonView::goSelectionChanged + ); } void DlgCustomizeSpaceball::setupCommandModelView() @@ -728,11 +806,17 @@ void DlgCustomizeSpaceball::setupLayout() devModel->addItems(getModels()); // Select the current preference or the first entry - QString model = QString::fromStdString(App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> - GetGroup("Spaceball")->GetASCII("Model","")); + QString model = QString::fromStdString( + App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Spaceball") + ->GetASCII("Model", "") + ); if (model.length() > 0) { devModel->setCurrentIndex(devModel->findText(model)); - } else { + } + else { devModel->setCurrentIndex(0); } @@ -763,8 +847,8 @@ void DlgCustomizeSpaceball::setupLayout() this->setLayout(layout); QList sizes; - sizes << this->size().width()*0.40; - sizes << this->size().width()-sizes.at(0); + sizes << this->size().width() * 0.40; + sizes << this->size().width() - sizes.at(0); splitter->setSizes(sizes); } @@ -773,11 +857,14 @@ void DlgCustomizeSpaceball::goClear() commandView->clearSelection(); commandView->collapseAll(); commandView->setDisabled(true); - //buttonModel->goClear(); + // buttonModel->goClear(); QByteArray currentDevice = devModel->currentText().toLocal8Bit(); - App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> - GetGroup("Spaceball")->SetASCII("Model", currentDevice.data()); + App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Spaceball") + ->SetASCII("Model", currentDevice.data()); buttonModel->loadConfig(currentDevice.data()); } @@ -793,35 +880,38 @@ void DlgCustomizeSpaceball::goPrint() QPrinter printer; QPrintDialog printDialog(&printer, this); - if (printDialog.exec() == QDialog::Accepted) - { + if (printDialog.exec() == QDialog::Accepted) { QPainter p(&printer); view->render(&p); } } -bool DlgCustomizeSpaceball::event(QEvent *event) +bool DlgCustomizeSpaceball::event(QEvent* event) { - if (event->type() != Spaceball::ButtonEvent::ButtonEventType) + if (event->type() != Spaceball::ButtonEvent::ButtonEventType) { return CustomizeActionPage::event(event); - auto buttonEvent = dynamic_cast(event); - if (!buttonEvent) + } + auto buttonEvent = dynamic_cast(event); + if (!buttonEvent) { return true; + } buttonEvent->setHandled(true); - if (buttonEvent->buttonStatus() == Spaceball::BUTTON_PRESSED) + if (buttonEvent->buttonStatus() == Spaceball::BUTTON_PRESSED) { buttonModel->goButtonPress(buttonEvent->buttonNumber()); + } buttonView->selectButton(buttonEvent->buttonNumber()); return true; } -void DlgCustomizeSpaceball::hideEvent(QHideEvent *event) +void DlgCustomizeSpaceball::hideEvent(QHideEvent* event) { - //having a crash with the last item of the macro command list - //being selected and that macro is removed from the macro tab. Hopefully - //clearing the selection will cure the problem. - if (buttonView) + // having a crash with the last item of the macro command list + // being selected and that macro is removed from the macro tab. Hopefully + // clearing the selection will cure the problem. + if (buttonView) { buttonView->selectionModel()->clear(); + } if (commandView) { commandView->selectionModel()->clear(); commandView->collapseAll(); @@ -831,85 +921,85 @@ void DlgCustomizeSpaceball::hideEvent(QHideEvent *event) CustomizeActionPage::hideEvent(event); } -void DlgCustomizeSpaceball::showEvent (QShowEvent *event) +void DlgCustomizeSpaceball::showEvent(QShowEvent* event) { - if (buttonView) + if (buttonView) { buttonView->setFocus(); + } CustomizeActionPage::showEvent(event); } -void DlgCustomizeSpaceball::changeEvent(QEvent *e) +void DlgCustomizeSpaceball::changeEvent(QEvent* e) { - if (e->type() == QEvent::LanguageChange) - { - //I don't think I need do anything here. Qt should take care of it? -// this->setWindowTitle(tr("Spaceball")); + if (e->type() == QEvent::LanguageChange) { + // I don't think I need do anything here. Qt should take care of it? + // this->setWindowTitle(tr("Spaceball")); } QWidget::changeEvent(e); } -void DlgCustomizeSpaceball::onAddMacroAction(const QByteArray ¯oName) +void DlgCustomizeSpaceball::onAddMacroAction(const QByteArray& macroName) { - //need to get the new macro to model. - if (commandModel) + // need to get the new macro to model. + if (commandModel) { commandModel->goAddMacro(macroName); + } } -void DlgCustomizeSpaceball::onRemoveMacroAction(const QByteArray ¯oName) +void DlgCustomizeSpaceball::onRemoveMacroAction(const QByteArray& macroName) { - //need to remove macro from model. - if (commandModel) + // need to remove macro from model. + if (commandModel) { commandModel->goRemoveMacro(macroName); - //need to change any button mapped to macro to an empty string. - if (buttonModel) + } + // need to change any button mapped to macro to an empty string. + if (buttonModel) { buttonModel->goMacroRemoved(macroName); + } } -void DlgCustomizeSpaceball::onModifyMacroAction(const QByteArray ¯oName) +void DlgCustomizeSpaceball::onModifyMacroAction(const QByteArray& macroName) { - //don't think I need to do anything here. + // don't think I need to do anything here. Q_UNUSED(macroName); } QStringList DlgCustomizeSpaceball::getModels() { QStringList modelList; - try - { - boost::property_tree::ptree tree; - boost::property_tree::ptree DeviceTree; + try { + boost::property_tree::ptree tree; + boost::property_tree::ptree DeviceTree; - // exception thrown if no file found - std::string path = App::Application::getResourceDir(); - path += "3Dconnexion/3DConnexion.xml"; - read_xml(path.c_str(), tree); + // exception thrown if no file found + std::string path = App::Application::getResourceDir(); + path += "3Dconnexion/3DConnexion.xml"; + read_xml(path.c_str(), tree); - BOOST_FOREACH(const boost::property_tree::ptree::value_type &ButtonMap, tree.get_child("")) - { - if ("ButtonMap" == ButtonMap.first) - { - // Inspect ButtonMap attributes for DeviceName - BOOST_FOREACH(const boost::property_tree::ptree::value_type &kv, ButtonMap.second.get_child("")) - { - std::string Attribute; - std::string Value; + BOOST_FOREACH (const boost::property_tree::ptree::value_type& ButtonMap, tree.get_child("")) { + if ("ButtonMap" == ButtonMap.first) { + // Inspect ButtonMap attributes for DeviceName + BOOST_FOREACH ( + const boost::property_tree::ptree::value_type& kv, + ButtonMap.second.get_child("") + ) { + std::string Attribute; + std::string Value; - Attribute = kv.first.data(); - Value = kv.second.data(); + Attribute = kv.first.data(); + Value = kv.second.data(); - if (0 == Attribute.compare("DeviceName")) - { - modelList << QString::fromStdString(Value); + if (0 == Attribute.compare("DeviceName")) { + modelList << QString::fromStdString(Value); + } } - } - } - } + } + } } - catch (const std::exception& e) - { - // We don't mind not finding the file to be opened - Base::Console().warning("%s\n", e.what()); + catch (const std::exception& e) { + // We don't mind not finding the file to be opened + Base::Console().warning("%s\n", e.what()); } return modelList; diff --git a/src/Gui/Dialogs/DlgCustomizeSpaceball.h b/src/Gui/Dialogs/DlgCustomizeSpaceball.h index b5850def45..30cf8f114e 100644 --- a/src/Gui/Dialogs/DlgCustomizeSpaceball.h +++ b/src/Gui/Dialogs/DlgCustomizeSpaceball.h @@ -38,143 +38,152 @@ class QPushButton; namespace Gui { - namespace Dialog +namespace Dialog +{ +class ButtonView: public QListView +{ + Q_OBJECT +public: + explicit ButtonView(QWidget* parent = nullptr); + void selectButton(int number); +Q_SIGNALS: + void changeCommandSelection(const QString& commandName); +public Q_SLOTS: + void goSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); + void goChangedCommand(const QString& commandName); +}; + +class ButtonModel: public QAbstractListModel +{ + Q_OBJECT +public: + explicit ButtonModel(QObject* parent); + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + void insertButtonRows(int number); + void setCommand(int row, QString command); + void goButtonPress(int number); + void goMacroRemoved(const QByteArray& macroName); + void goClear(); + void loadConfig(const char* RequiredDeviceName); + +private: + void load3DConnexionButtonMapping(boost::property_tree::ptree ButtonMapTree); + void load3DConnexionButtons(const char* RequiredDeviceName); + ParameterGrp::handle spaceballButtonGroup() const; + QString getLabel(const int& number) const; +}; + +class CommandView: public QTreeView +{ + Q_OBJECT +public: + explicit CommandView(QWidget* parent = nullptr); +public Q_SLOTS: + void goChangeCommandSelection(const QString& commandName); +private Q_SLOTS: + void goClicked(const QModelIndex& index); +Q_SIGNALS: + void changedCommand(const QString& commandName); +}; + +class CommandNode +{ +public: + enum NodeType { - class ButtonView : public QListView - { - Q_OBJECT - public: - explicit ButtonView(QWidget *parent = nullptr); - void selectButton(int number); - Q_SIGNALS: - void changeCommandSelection(const QString& commandName); - public Q_SLOTS: - void goSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected); - void goChangedCommand(const QString& commandName); - }; + RootType, + GroupType, + CommandType + }; - class ButtonModel : public QAbstractListModel - { - Q_OBJECT - public: - explicit ButtonModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - void insertButtonRows(int number); - void setCommand(int row, QString command); - void goButtonPress(int number); - void goMacroRemoved(const QByteArray& macroName); - void goClear(); - void loadConfig(const char *RequiredDeviceName); - private: - void load3DConnexionButtonMapping(boost::property_tree::ptree ButtonMapTree); - void load3DConnexionButtons(const char *RequiredDeviceName); - ParameterGrp::handle spaceballButtonGroup() const; - QString getLabel(const int &number) const; - }; + explicit CommandNode(NodeType typeIn); + ~CommandNode(); - class CommandView : public QTreeView - { - Q_OBJECT - public: - explicit CommandView(QWidget *parent = nullptr); - public Q_SLOTS: - void goChangeCommandSelection(const QString& commandName); - private Q_SLOTS: - void goClicked(const QModelIndex &index); - Q_SIGNALS: - void changedCommand(const QString& commandName); - }; + NodeType nodeType; + Command* aCommand; + QString labelText; + CommandNode* parent; + QList children; +}; - class CommandNode - { - public: - enum NodeType {RootType, GroupType, CommandType}; +class CommandModel: public QAbstractItemModel +{ + Q_OBJECT +public: + explicit CommandModel(QObject* parent = nullptr); + ~CommandModel() override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex& index) const override; + int rowCount(const QModelIndex& parent) const override; + int columnCount(const QModelIndex& parent) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + void goAddMacro(const QByteArray& macroName); + void goRemoveMacro(const QByteArray& macroName); - explicit CommandNode(NodeType typeIn); - ~CommandNode(); +private: + CommandNode* rootNode; + CommandNode* nodeFromIndex(const QModelIndex& index) const; + void initialize(); + void groupCommands(const QString& groupName); + QStringList orderedGroups(); +}; - NodeType nodeType; - Command *aCommand; - QString labelText; - CommandNode *parent; - QList children; - }; +class PrintModel: public QAbstractTableModel +{ + Q_OBJECT +public: + PrintModel(QObject* parent, ButtonModel* buttonModelIn, CommandModel* commandModelIn); + int rowCount(const QModelIndex& parent) const override; + int columnCount(const QModelIndex& parent) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - class CommandModel : public QAbstractItemModel - { - Q_OBJECT - public: - explicit CommandModel(QObject *parent = nullptr); - ~CommandModel() override; - QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; - QModelIndex parent(const QModelIndex &index) const override; - int rowCount(const QModelIndex &parent) const override; - int columnCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - Qt::ItemFlags flags (const QModelIndex &index) const override; - void goAddMacro(const QByteArray ¯oName); - void goRemoveMacro(const QByteArray ¯oName); - private: - CommandNode *rootNode; - CommandNode* nodeFromIndex(const QModelIndex &index) const; - void initialize(); - void groupCommands(const QString& groupName); - QStringList orderedGroups(); - }; +private: + ButtonModel* buttonModel; + CommandModel* commandModel; +}; - class PrintModel : public QAbstractTableModel - { - Q_OBJECT - public: - PrintModel(QObject *parent, ButtonModel *buttonModelIn, CommandModel *commandModelIn); - int rowCount(const QModelIndex &parent) const override; - int columnCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - private: - ButtonModel *buttonModel; - CommandModel *commandModel; - }; +class DlgCustomizeSpaceball: public CustomizeActionPage +{ + Q_OBJECT +public: + explicit DlgCustomizeSpaceball(QWidget* parent = nullptr); + ~DlgCustomizeSpaceball() override; - class DlgCustomizeSpaceball : public CustomizeActionPage - { - Q_OBJECT - public: - explicit DlgCustomizeSpaceball(QWidget *parent = nullptr); - ~DlgCustomizeSpaceball() override; - protected: - void changeEvent(QEvent *e) override; - bool event(QEvent *event) override; - void hideEvent(QHideEvent *event) override; - void showEvent (QShowEvent *event) override; +protected: + void changeEvent(QEvent* e) override; + bool event(QEvent* event) override; + void hideEvent(QHideEvent* event) override; + void showEvent(QShowEvent* event) override; - protected Q_SLOTS: - void onAddMacroAction(const QByteArray ¯oName) override; - void onRemoveMacroAction(const QByteArray ¯oName) override; - void onModifyMacroAction(const QByteArray ¯oName) override; +protected Q_SLOTS: + void onAddMacroAction(const QByteArray& macroName) override; + void onRemoveMacroAction(const QByteArray& macroName) override; + void onModifyMacroAction(const QByteArray& macroName) override; - private Q_SLOTS: - void goClear(); - void goPrint(); +private Q_SLOTS: + void goClear(); + void goPrint(); - private: - void setupButtonModelView(); - void setupCommandModelView(); - void setupLayout(); - void setMessage(const QString& message); - QStringList getModels(); +private: + void setupButtonModelView(); + void setupCommandModelView(); + void setupLayout(); + void setMessage(const QString& message); + QStringList getModels(); - ButtonView *buttonView; - ButtonModel *buttonModel; - CommandView *commandView; - CommandModel *commandModel; - QPushButton *clearButton; - QPushButton *printReference; - QComboBox *devModel; - }; - } -} + ButtonView* buttonView; + ButtonModel* buttonModel; + CommandView* commandView; + CommandModel* commandModel; + QPushButton* clearButton; + QPushButton* printReference; + QComboBox* devModel; +}; +} // namespace Dialog +} // namespace Gui -#endif //GUI_DIALOG_DLGCUSTOMIZESPACEBALL_H +#endif // GUI_DIALOG_DLGCUSTOMIZESPACEBALL_H diff --git a/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.cpp b/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.cpp index 4069deae99..d97b1f1c0d 100644 --- a/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.cpp +++ b/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.cpp @@ -36,13 +36,14 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgEditFileIncludePropertyExternal:: -DlgEditFileIncludePropertyExternal(App::PropertyFileIncluded& Prop, - QWidget* parent, Qt::WindowFlags fl) - : DlgRunExternal(parent, fl), Prop(Prop) -{ - -} +DlgEditFileIncludePropertyExternal::DlgEditFileIncludePropertyExternal( + App::PropertyFileIncluded& Prop, + QWidget* parent, + Qt::WindowFlags fl +) + : DlgRunExternal(parent, fl) + , Prop(Prop) +{} /** * Destroys the object and frees any allocated resources @@ -64,8 +65,9 @@ int DlgEditFileIncludePropertyExternal::processFile() int ret = DlgRunExternal::runProcess(); - if (ret == QDialog::Accepted) + if (ret == QDialog::Accepted) { Prop.setValue(TempFile.toUtf8()); + } QFile::remove(TempFile); return ret; diff --git a/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.h b/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.h index d31101ce5b..858e47b78f 100644 --- a/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.h +++ b/src/Gui/Dialogs/DlgEditFileIncludePropertyExternal.h @@ -27,19 +27,25 @@ #include "Dialogs/DlgRunExternal.h" #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ /** * * \author Jürgen Riegel */ -class GuiExport DlgEditFileIncludePropertyExternal : public DlgRunExternal +class GuiExport DlgEditFileIncludePropertyExternal: public DlgRunExternal { Q_OBJECT public: - DlgEditFileIncludePropertyExternal(App::PropertyFileIncluded& Prop, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + DlgEditFileIncludePropertyExternal( + App::PropertyFileIncluded& Prop, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~DlgEditFileIncludePropertyExternal() override; int processFile(); @@ -48,7 +54,7 @@ private: App::PropertyFileIncluded& Prop; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DlgEditFileIncludePropertyExternal_H +#endif // GUI_DIALOG_DlgEditFileIncludePropertyExternal_H diff --git a/src/Gui/Dialogs/DlgExpressionInput.cpp b/src/Gui/Dialogs/DlgExpressionInput.cpp index 0db9b29f90..e3bc97ab5e 100644 --- a/src/Gui/Dialogs/DlgExpressionInput.cpp +++ b/src/Gui/Dialogs/DlgExpressionInput.cpp @@ -53,17 +53,20 @@ using namespace Gui::Dialog; FC_LOG_LEVEL_INIT("DlgExpressionInput", true, true) -DlgExpressionInput::DlgExpressionInput(const App::ObjectIdentifier & _path, - std::shared_ptr _expression, - const Base::Unit & _impliedUnit, QWidget *parent) - : QDialog(parent) - , ui(new Ui::DlgExpressionInput) - , expression(_expression ? _expression->copy() : nullptr) - , path(_path) - , discarded(false) - , impliedUnit(_impliedUnit) - , varSetsVisible(false) - , comboBoxGroup(this) +DlgExpressionInput::DlgExpressionInput( + const App::ObjectIdentifier& _path, + std::shared_ptr _expression, + const Base::Unit& _impliedUnit, + QWidget* parent +) + : QDialog(parent) + , ui(new Ui::DlgExpressionInput) + , expression(_expression ? _expression->copy() : nullptr) + , path(_path) + , discarded(false) + , impliedUnit(_impliedUnit) + , varSetsVisible(false) + , comboBoxGroup(this) { assert(path.getDocumentObject()); @@ -76,10 +79,8 @@ DlgExpressionInput::DlgExpressionInput(const App::ObjectIdentifier & _path, initializeVarSets(); // Connect signal(s) - connect(ui->expression, &ExpressionTextEdit::textChanged, - this, &DlgExpressionInput::textChanged); - connect(discardBtn, &QPushButton::clicked, - this, &DlgExpressionInput::setDiscarded); + connect(ui->expression, &ExpressionTextEdit::textChanged, this, &DlgExpressionInput::textChanged); + connect(discardBtn, &QPushButton::clicked, this, &DlgExpressionInput::setDiscarded); if (expression) { ui->expression->setPlainText(QString::fromStdString(expression->toString())); @@ -92,14 +93,15 @@ DlgExpressionInput::DlgExpressionInput(const App::ObjectIdentifier & _path, } // Set document object on text edit to create auto completer - DocumentObject * docObj = path.getDocumentObject(); + DocumentObject* docObj = path.getDocumentObject(); ui->expression->setDocumentObject(docObj); // There are some platforms where setting no system background causes a black // rectangle to appear. To avoid this the 'NoSystemBackground' parameter can be // set to false. Then a normal non-modal dialog will be shown instead (#0002440). - bool noBackground = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Expression")->GetBool("NoSystemBackground", false); + bool noBackground = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Expression") + ->GetBool("NoSystemBackground", false); if (noBackground) { #if defined(Q_OS_MACOS) @@ -121,32 +123,44 @@ DlgExpressionInput::DlgExpressionInput(const App::ObjectIdentifier & _path, // It is strange that (at least on Linux) DlgExpressionInput will shrink // to be narrower than ui->expression after calling adjustSize() above. // Why? - if(this->width() < ui->expression->width() + 18) - this->resize(ui->expression->width()+18,this->height()); + if (this->width() < ui->expression->width() + 18) { + this->resize(ui->expression->width() + 18, this->height()); + } } ui->expression->setFocus(); } DlgExpressionInput::~DlgExpressionInput() { -#if QT_VERSION >= QT_VERSION_CHECK(6,7,0) - disconnect(ui->checkBoxVarSets, &QCheckBox::checkStateChanged, - this, &DlgExpressionInput::onCheckVarSets); +#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) + disconnect( + ui->checkBoxVarSets, + &QCheckBox::checkStateChanged, + this, + &DlgExpressionInput::onCheckVarSets + ); #else - disconnect(ui->checkBoxVarSets, &QCheckBox::stateChanged, - this, &DlgExpressionInput::onCheckVarSets); + disconnect(ui->checkBoxVarSets, &QCheckBox::stateChanged, this, &DlgExpressionInput::onCheckVarSets); #endif - disconnect(ui->comboBoxVarSet, qOverload(&QComboBox::currentIndexChanged), - this, &DlgExpressionInput::onVarSetSelected); - disconnect(&comboBoxGroup, &EditFinishedComboBox::currentTextChanged, - this, &DlgExpressionInput::onTextChangedGroup); - disconnect(ui->lineEditPropNew, &QLineEdit::textChanged, - this, &DlgExpressionInput::namePropChanged); + disconnect( + ui->comboBoxVarSet, + qOverload(&QComboBox::currentIndexChanged), + this, + &DlgExpressionInput::onVarSetSelected + ); + disconnect( + &comboBoxGroup, + &EditFinishedComboBox::currentTextChanged, + this, + &DlgExpressionInput::onTextChangedGroup + ); + disconnect(ui->lineEditPropNew, &QLineEdit::textChanged, this, &DlgExpressionInput::namePropChanged); delete ui; } -static void getVarSetsDocument(std::vector& varSets, App::Document* doc) { +static void getVarSetsDocument(std::vector& varSets, App::Document* doc) +{ for (auto obj : doc->getObjects()) { auto varSet = dynamic_cast(obj); if (varSet) { @@ -178,9 +192,9 @@ Base::Type DlgExpressionInput::determineTypeVarSet() // The type of the path is leading. If it is one of the types below, we // can create a property in the varset. - if (typePath == App::PropertyString::getClassTypeId() || - typePath.isDerivedFrom(App::PropertyFloat::getClassTypeId()) || - typePath.isDerivedFrom(App::PropertyInteger::getClassTypeId())) { + if (typePath == App::PropertyString::getClassTypeId() + || typePath.isDerivedFrom(App::PropertyFloat::getClassTypeId()) + || typePath.isDerivedFrom(App::PropertyInteger::getClassTypeId())) { return typePath; } @@ -220,19 +234,24 @@ void DlgExpressionInput::initializeErrorFrame() void DlgExpressionInput::initializeVarSets() { -#if QT_VERSION >= QT_VERSION_CHECK(6,7,0) - connect(ui->checkBoxVarSets, &QCheckBox::checkStateChanged, - this, &DlgExpressionInput::onCheckVarSets); +#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) + connect(ui->checkBoxVarSets, &QCheckBox::checkStateChanged, this, &DlgExpressionInput::onCheckVarSets); #else - connect(ui->checkBoxVarSets, &QCheckBox::stateChanged, - this, &DlgExpressionInput::onCheckVarSets); + connect(ui->checkBoxVarSets, &QCheckBox::stateChanged, this, &DlgExpressionInput::onCheckVarSets); #endif - connect(ui->comboBoxVarSet, qOverload(&QComboBox::currentIndexChanged), - this, &DlgExpressionInput::onVarSetSelected); - connect(&comboBoxGroup, &EditFinishedComboBox::currentTextChanged, - this, &DlgExpressionInput::onTextChangedGroup); - connect(ui->lineEditPropNew, &QLineEdit::textChanged, - this, &DlgExpressionInput::namePropChanged); + connect( + ui->comboBoxVarSet, + qOverload(&QComboBox::currentIndexChanged), + this, + &DlgExpressionInput::onVarSetSelected + ); + connect( + &comboBoxGroup, + &EditFinishedComboBox::currentTextChanged, + this, + &DlgExpressionInput::onTextChangedGroup + ); + connect(ui->lineEditPropNew, &QLineEdit::textChanged, this, &DlgExpressionInput::namePropChanged); comboBoxGroup.setObjectName(QStringLiteral("comboBoxGroup")); comboBoxGroup.setInsertPolicy(QComboBox::InsertAtTop); @@ -269,8 +288,9 @@ void NumberRange::clearRange() void NumberRange::throwIfOutOfRange(const Base::Quantity& value) const { - if (!defined) + if (!defined) { return; + } auto toQString = [](const Base::Quantity& v) { return QString::fromStdString(v.getUserString()); @@ -280,9 +300,8 @@ void NumberRange::throwIfOutOfRange(const Base::Quantity& value) const Base::Quantity minVal(minimum, value.getUnit()); Base::Quantity maxVal(maximum, value.getUnit()); - const QString fmt = QCoreApplication::translate( - "Exceptions", - "Value out of range (%1 out of [%2, %3])"); + const QString fmt + = QCoreApplication::translate("Exceptions", "Value out of range (%1 out of [%2, %3])"); const QString msg = fmt.arg(toQString(value), toQString(minVal), toQString(maxVal)); THROWM(Base::ValueError, msg.toStdString()); } @@ -305,8 +324,9 @@ QPoint DlgExpressionInput::expressionPosition() const bool DlgExpressionInput::checkCyclicDependencyVarSet(const QString& text) { - std::shared_ptr - expr(ExpressionParser::parse(path.getDocumentObject(), text.toUtf8().constData())); + std::shared_ptr expr( + ExpressionParser::parse(path.getDocumentObject(), text.toUtf8().constData()) + ); if (expr) { DocumentObject* obj = path.getDocumentObject(); @@ -317,8 +337,9 @@ bool DlgExpressionInput::checkCyclicDependencyVarSet(const QString& text) // This string is not translated. It is based on a string that // originates from the expression validator in App that is also // not translated. - ui->msg->setText(QString::fromStdString( - id.first.toString() + " reference causes a cyclic dependency")); + ui->msg->setText( + QString::fromStdString(id.first.toString() + " reference causes a cyclic dependency") + ); return true; } } @@ -329,15 +350,17 @@ bool DlgExpressionInput::checkCyclicDependencyVarSet(const QString& text) void DlgExpressionInput::checkExpression(const QString& text) { - //now handle expression - std::shared_ptr - expr(ExpressionParser::parse(path.getDocumentObject(), text.toUtf8().constData())); + // now handle expression + std::shared_ptr expr( + ExpressionParser::parse(path.getDocumentObject(), text.toUtf8().constData()) + ); if (expr) { std::string error = path.getDocumentObject()->ExpressionEngine.validateExpression(path, expr); - if (!error.empty()) + if (!error.empty()) { throw Base::RuntimeError(error.c_str()); + } std::unique_ptr result(expr->eval()); @@ -345,10 +368,10 @@ void DlgExpressionInput::checkExpression(const QString& text) okBtn->setEnabled(true); ui->msg->clear(); - //set default palette as we may have read text right now + // set default palette as we may have read text right now ui->msg->setPalette(okBtn->palette()); - auto * n = freecad_cast(result.get()); + auto* n = freecad_cast(result.get()); if (n) { Base::Quantity value = n->getQuantity(); if (!value.isValid()) { @@ -357,12 +380,14 @@ void DlgExpressionInput::checkExpression(const QString& text) QString msg = QString::fromStdString(value.getUserString()); if (impliedUnit != Base::Unit::One) { - if (!value.isDimensionless() && value.getUnit() != impliedUnit) - THROWMT(Base::UnitsMismatchError, - QT_TRANSLATE_NOOP("Exceptions", "Unit mismatch between result and required unit")); + if (!value.isDimensionless() && value.getUnit() != impliedUnit) { + THROWMT( + Base::UnitsMismatchError, + QT_TRANSLATE_NOOP("Exceptions", "Unit mismatch between result and required unit") + ); + } value.setUnit(impliedUnit); - } else if (!value.isDimensionless()) { msg += tr(" (Warning: unit discarded)"); @@ -379,7 +404,6 @@ void DlgExpressionInput::checkExpression(const QString& text) message = result->toString(); } setMsgText(); - } } @@ -406,7 +430,7 @@ void DlgExpressionInput::textChanged() updateVarSetInfo(NoCheckExpr); } } - catch (Base::Exception & e) { + catch (Base::Exception& e) { message = e.what(); setMsgText(); QPalette p(ui->msg->palette()); @@ -433,8 +457,8 @@ void DlgExpressionInput::mousePressEvent(QMouseEvent* event) // The 'FramelessWindowHint' is also set when the background is transparent. if (windowFlags() & Qt::FramelessWindowHint) { - //we need to reject the dialog when clicked on the background. As the background is transparent - //this is the expected behaviour for the user + // we need to reject the dialog when clicked on the background. As the background is + // transparent this is the expected behaviour for the user bool on = ui->expression->completerActive(); if (!on) { this->reject(); @@ -449,7 +473,7 @@ void DlgExpressionInput::show() ui->expression->selectAll(); } -class Binding : public Gui::ExpressionBinding +class Binding: public Gui::ExpressionBinding { // helper class to compensate for the fact that // ExpressionBinding::setExpression is protected. @@ -462,12 +486,15 @@ public: } }; -static constexpr const char* InvalidIdentifierMessage = - QT_TR_NOOP("must contain only alphanumeric characters, underscore, and must not start with a digit"); +static constexpr const char* InvalidIdentifierMessage = QT_TR_NOOP( + "must contain only alphanumeric characters, underscore, and must not start with a digit" +); -bool DlgExpressionInput::isPropertyNameValid(const QString& nameProp, - const App::DocumentObject* obj, - QString& message) const +bool DlgExpressionInput::isPropertyNameValid( + const QString& nameProp, + const App::DocumentObject* obj, + QString& message +) const { auto withPrefix = [&](const QString& detail) { return tr("Invalid property name: %1").arg(detail); @@ -519,12 +546,15 @@ static QString getValue(QComboBox* comboBox, int role) return variant.toString(); } -static void storePreferences(const std::string& nameDoc, - const std::string& nameVarSet, - const std::string& nameGroup) +static void storePreferences( + const std::string& nameDoc, + const std::string& nameVarSet, + const std::string& nameGroup +) { auto paramExpressionEditor = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/ExpressionEditor"); + "User parameter:BaseApp/Preferences/ExpressionEditor" + ); paramExpressionEditor->SetASCII("LastDocument", nameDoc); paramExpressionEditor->SetASCII("LastVarSet", nameVarSet); paramExpressionEditor->SetASCII("LastGroup", nameGroup); @@ -543,8 +573,8 @@ static const App::StringExpression* toStringExpr(const App::Expression* expr) static const App::OperatorExpression* toUnitNumberExpr(const App::Expression* expr) { auto* opExpr = freecad_cast(expr); - if (opExpr && opExpr->getOperator() == App::OperatorExpression::Operator::UNIT && - toNumberExpr(opExpr->getLeft())) { + if (opExpr && opExpr->getOperator() == App::OperatorExpression::Operator::UNIT + && toNumberExpr(opExpr->getLeft())) { return opExpr; } return nullptr; @@ -599,24 +629,36 @@ void DlgExpressionInput::acceptWithVarSet() if (const NumberExpression* ne = toNumberExpr(expr)) { // the value is a number: directly assign it to the property instead of // making it an expression in the variable set - Gui::Command::doCommand(Gui::Command::Doc, "App.getDocument('%s').getObject('%s').%s = %f", - obj->getDocument()->getName(), - obj->getNameInDocument(), - prop->getName(), ne->getValue()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').getObject('%s').%s = %f", + obj->getDocument()->getName(), + obj->getNameInDocument(), + prop->getName(), + ne->getValue() + ); } else if (const StringExpression* se = toStringExpr(expr)) { // the value is a string: directly assign it to the property. - Gui::Command::doCommand(Gui::Command::Doc, "App.getDocument('%s').getObject('%s').%s = \"%s\"", - obj->getDocument()->getName(), - obj->getNameInDocument(), - prop->getName(), se->getText().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').getObject('%s').%s = \"%s\"", + obj->getDocument()->getName(), + obj->getNameInDocument(), + prop->getName(), + se->getText().c_str() + ); } else if (const OperatorExpression* une = toUnitNumberExpr(expr)) { // the value is a unit number: directly assign it to the property. - Gui::Command::doCommand(Gui::Command::Doc, "App.getDocument('%s').getObject('%s').%s = \"%s\"", - obj->getDocument()->getName(), - obj->getNameInDocument(), - prop->getName(), une->toString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').getObject('%s').%s = \"%s\"", + obj->getDocument()->getName(), + obj->getNameInDocument(), + prop->getName(), + une->toString().c_str() + ); } else { // the value is an expression: make an expression binding in the VarSet @@ -625,13 +667,13 @@ void DlgExpressionInput::acceptWithVarSet() // Create a new expression that refers to the property in the VarSet // for the original property that is the target of this dialog. - expression.reset(ExpressionParser::parse(path.getDocumentObject(), - prop->getFullName().c_str())); + expression.reset(ExpressionParser::parse(path.getDocumentObject(), prop->getFullName().c_str())); storePreferences(nameDoc.toStdString(), nameVarSet.toStdString(), group); } -void DlgExpressionInput::accept() { +void DlgExpressionInput::accept() +{ if (varSetsVisible) { if (needReportOnVarSet()) { return; @@ -644,7 +686,8 @@ void DlgExpressionInput::accept() { static App::Document* getPreselectedDocument() { auto paramExpressionEditor = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/ExpressionEditor"); + "User parameter:BaseApp/Preferences/ExpressionEditor" + ); std::string lastDoc = paramExpressionEditor->GetASCII("LastDocument", ""); if (lastDoc.empty()) { @@ -663,14 +706,15 @@ static App::Document* getPreselectedDocument() int DlgExpressionInput::getVarSetIndex(const App::Document* doc) const { auto paramExpressionEditor = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/ExpressionEditor"); + "User parameter:BaseApp/Preferences/ExpressionEditor" + ); std::string lastVarSet = paramExpressionEditor->GetASCII("LastVarSet", "VarSet"); auto* model = qobject_cast(ui->comboBoxVarSet->model()); for (int i = 0; i < model->rowCount(); ++i) { QStandardItem* item = model->item(i); - if (item->data(DocRole).toString() == QString::fromUtf8(doc->getName()) && - item->data(VarSetNameRole).toString() == QString::fromStdString(lastVarSet)) { + if (item->data(DocRole).toString() == QString::fromUtf8(doc->getName()) + && item->data(VarSetNameRole).toString() == QString::fromStdString(lastVarSet)) { return i; } } @@ -689,11 +733,15 @@ void DlgExpressionInput::preselectVarSet() } // Custom delegate to add indentation -class IndentedItemDelegate : public QStyledItemDelegate { +class IndentedItemDelegate: public QStyledItemDelegate +{ public: - explicit IndentedItemDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} + explicit IndentedItemDelegate(QObject* parent = nullptr) + : QStyledItemDelegate(parent) + {} - void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override { + void initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const override + { QStyledItemDelegate::initStyleOption(option, index); if (index.data(LevelRole) == 1) { @@ -703,12 +751,16 @@ public: } }; -static void addVarSetsVarSetComboBox(std::vector& varSets, - QStandardItem* docItem, QStandardItemModel* model) +static void addVarSetsVarSetComboBox( + std::vector& varSets, + QStandardItem* docItem, + QStandardItemModel* model +) { for (auto* varSet : varSets) { auto* vp = freecad_cast( - Gui::Application::Instance->getViewProvider(varSet)); + Gui::Application::Instance->getViewProvider(varSet) + ); if (vp == nullptr) { FC_ERR("No ViewProvider found for VarSet: " << varSet->getNameInDocument()); continue; @@ -726,8 +778,7 @@ static void addVarSetsVarSetComboBox(std::vector& varSets, } } -static void addDocVarSetComboBox(App::Document* doc, QPixmap& docIcon, - QStandardItemModel* model) +static void addDocVarSetComboBox(App::Document* doc, QPixmap& docIcon, QStandardItemModel* model) { if (doc->testStatus(App::Document::TempDoc)) { // Do not add temporary documents to the VarSet combo box @@ -745,7 +796,7 @@ static void addDocVarSetComboBox(App::Document* doc, QPixmap& docIcon, item->setIcon(docIcon); item->setText(QString::fromUtf8(doc->Label.getValue())); item->setData(QByteArray(doc->getName()), DocRole); - item->setFlags(Qt::ItemIsEnabled); // Make sure this item cannot be selected + item->setFlags(Qt::ItemIsEnabled); // Make sure this item cannot be selected item->setData(0, LevelRole); model->appendRow(item); @@ -792,7 +843,8 @@ std::string DlgExpressionInput::getType() return determineTypeVarSet().getName(); } -void DlgExpressionInput::onCheckVarSets(int state) { +void DlgExpressionInput::onCheckVarSets(int state) +{ varSetsVisible = state == Qt::Checked; ui->groupBoxVarSets->setVisible(varSetsVisible); if (varSetsVisible) { @@ -812,7 +864,8 @@ void DlgExpressionInput::onCheckVarSets(int state) { void DlgExpressionInput::preselectGroup() { auto paramExpressionEditor = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/ExpressionEditor"); + "User parameter:BaseApp/Preferences/ExpressionEditor" + ); std::string lastGroup = paramExpressionEditor->GetASCII("LastGroup", ""); if (lastGroup.empty()) { @@ -861,14 +914,13 @@ void DlgExpressionInput::namePropChanged(const QString&) updateVarSetInfo(); } -bool DlgExpressionInput::isGroupNameValid(const QString& nameGroup, - QString& message) const +bool DlgExpressionInput::isGroupNameValid(const QString& nameGroup, QString& message) const { auto withPrefix = [&](const QString& detail) { return tr("Invalid group name: %1").arg(detail); }; - if(nameGroup.isEmpty()) { + if (nameGroup.isEmpty()) { message = withPrefix(tr("the name cannot be empty")); return false; } @@ -966,13 +1018,13 @@ bool DlgExpressionInput::needReportOnVarSet() return reportGroup(comboBoxGroup.currentText()) || reportName(); } -void DlgExpressionInput::resizeEvent(QResizeEvent *event) +void DlgExpressionInput::resizeEvent(QResizeEvent* event) { // When the dialog is resized, message text may need to be re-wrapped if (!this->message.empty() && event->size() != event->oldSize()) { setMsgText(); } - QDialog::resizeEvent(event); + QDialog::resizeEvent(event); } void DlgExpressionInput::setMsgText() @@ -981,17 +1033,17 @@ void DlgExpressionInput::setMsgText() return; } - const QFontMetrics msgFontMetrics{ ui->msg->font() }; + const QFontMetrics msgFontMetrics {ui->msg->font()}; // find words longer than length of msg widget // then insert newline to wrap it - std::string wrappedMsg{}; - const int msgContentWidth = ui->msg->width() * 0.85; // 0.85 is a magic number for some padding - const int maxWordLength = msgContentWidth / msgFontMetrics.averageCharWidth(); + std::string wrappedMsg {}; + const int msgContentWidth = ui->msg->width() * 0.85; // 0.85 is a magic number for some padding + const int maxWordLength = msgContentWidth / msgFontMetrics.averageCharWidth(); - const auto wrappableWordPattern = std::regex{ "\\S{" + std::to_string(maxWordLength) + "}" }; - auto it = std::sregex_iterator{ this->message.cbegin(), this->message.cend(), wrappableWordPattern }; - const auto itEnd = std::sregex_iterator{}; + const auto wrappableWordPattern = std::regex {"\\S{" + std::to_string(maxWordLength) + "}"}; + auto it = std::sregex_iterator {this->message.cbegin(), this->message.cend(), wrappableWordPattern}; + const auto itEnd = std::sregex_iterator {}; int lastPos = 0; for (; it != itEnd; ++it) { @@ -1002,12 +1054,16 @@ void DlgExpressionInput::setMsgText() wrappedMsg += this->message.substr(lastPos); ui->msg->setText(QString::fromStdString(wrappedMsg)); - - // elide text if it is going out of widget bounds + + // elide text if it is going out of widget bounds // note: this is only 'rough elide', as this text is usually not very long; const int msgLinesLimit = 3; if (wrappedMsg.size() > msgContentWidth / msgFontMetrics.averageCharWidth() * msgLinesLimit) { - const QString elidedMsg = msgFontMetrics.elidedText(QString::fromStdString(wrappedMsg), Qt::ElideRight, msgContentWidth * msgLinesLimit); + const QString elidedMsg = msgFontMetrics.elidedText( + QString::fromStdString(wrappedMsg), + Qt::ElideRight, + msgContentWidth * msgLinesLimit + ); ui->msg->setText(elidedMsg); } } diff --git a/src/Gui/Dialogs/DlgExpressionInput.h b/src/Gui/Dialogs/DlgExpressionInput.h index 0a54df85f9..092df0d3e1 100644 --- a/src/Gui/Dialogs/DlgExpressionInput.h +++ b/src/Gui/Dialogs/DlgExpressionInput.h @@ -33,21 +33,25 @@ #include "Dialogs/DlgAddProperty.h" -namespace Ui { +namespace Ui +{ class DlgExpressionInput; } -namespace Base { +namespace Base +{ class Quantity; } -namespace App { +namespace App +{ class Path; class Expression; class DocumentObject; -} +} // namespace App -namespace Gui::Dialog { +namespace Gui::Dialog +{ class GuiExport NumberRange { @@ -57,24 +61,35 @@ public: void throwIfOutOfRange(const Base::Quantity&) const; private: - double minimum{}; - double maximum{}; - bool defined{false}; + double minimum {}; + double maximum {}; + bool defined {false}; }; -class GuiExport DlgExpressionInput : public QDialog +class GuiExport DlgExpressionInput: public QDialog { Q_OBJECT public: - explicit DlgExpressionInput(const App::ObjectIdentifier & _path, std::shared_ptr _expression, const Base::Unit &_impliedUnit, QWidget *parent = nullptr); + explicit DlgExpressionInput( + const App::ObjectIdentifier& _path, + std::shared_ptr _expression, + const Base::Unit& _impliedUnit, + QWidget* parent = nullptr + ); ~DlgExpressionInput() override; void setRange(double minimum, double maximum); void clearRange(); - std::shared_ptr getExpression() const { return expression; } + std::shared_ptr getExpression() const + { + return expression; + } - bool discardedFormula() const { return discarded; } + bool discardedFormula() const + { + return discarded; + } QPoint expressionPosition() const; @@ -107,10 +122,12 @@ private: void updateVarSetInfo(bool checkExpr = true); void createBindingVarSet(App::Property* propVarSet, App::DocumentObject* varSet); void acceptWithVarSet(); - bool isPropertyNameValid(const QString& nameProp, - const App::DocumentObject* obj, QString& message) const; - bool isGroupNameValid(const QString& nameGroup, - QString& message) const; + bool isPropertyNameValid( + const QString& nameProp, + const App::DocumentObject* obj, + QString& message + ) const; + bool isGroupNameValid(const QString& nameGroup, QString& message) const; void setMsgText(); private Q_SLOTS: @@ -123,7 +140,7 @@ private Q_SLOTS: bool needReportOnVarSet(); private: - ::Ui::DlgExpressionInput *ui; + ::Ui::DlgExpressionInput* ui; std::shared_ptr expression; App::ObjectIdentifier path; bool discarded; @@ -139,7 +156,7 @@ private: EditFinishedComboBox comboBoxGroup; }; -} +} // namespace Gui::Dialog -#endif // GUI_DIALOG_EXPRESSIONINPUT_H +#endif // GUI_DIALOG_EXPRESSIONINPUT_H diff --git a/src/Gui/Dialogs/DlgInputDialogImp.cpp b/src/Gui/Dialogs/DlgInputDialogImp.cpp index 49988c22aa..c2aef03097 100644 --- a/src/Gui/Dialogs/DlgInputDialogImp.cpp +++ b/src/Gui/Dialogs/DlgInputDialogImp.cpp @@ -20,7 +20,7 @@ * * ***************************************************************************/ -# include +#include #include "Dialogs/DlgInputDialogImp.h" #include "ui_DlgInputDialog.h" @@ -38,9 +38,9 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgInputDialogImp::DlgInputDialogImp( const QString& labelTxt, QWidget* parent, bool modal, Type type ) - : QDialog(parent) - , ui(new Ui_DlgInputDialog) +DlgInputDialogImp::DlgInputDialogImp(const QString& labelTxt, QWidget* parent, bool modal, Type type) + : QDialog(parent) + , ui(new Ui_DlgInputDialog) { this->setModal(modal); ui->setupUi(this); @@ -59,59 +59,59 @@ DlgInputDialogImp::DlgInputDialogImp( const QString& labelTxt, QWidget* parent, */ DlgInputDialogImp::~DlgInputDialogImp() = default; -void DlgInputDialogImp::textChanged( const QString &s ) +void DlgInputDialogImp::textChanged(const QString& s) { bool on = true; if (ui->lineEdit->validator()) { QString str = ui->lineEdit->text(); int index = ui->lineEdit->cursorPosition(); - on = ( ui->lineEdit->validator()->validate(str, index) == QValidator::Acceptable ); + on = (ui->lineEdit->validator()->validate(str, index) == QValidator::Acceptable); } - else if ( type() != LineEdit ) { + else if (type() != LineEdit) { on = !s.isEmpty(); } - ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled( on ); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(on); } void DlgInputDialogImp::tryAccept() { - if (!ui->lineEdit->text().isEmpty()) + if (!ui->lineEdit->text().isEmpty()) { accept(); + } } -void DlgInputDialogImp::setType( DlgInputDialogImp::Type t ) +void DlgInputDialogImp::setType(DlgInputDialogImp::Type t) { inputtype = t; - QWidget *input = nullptr; - switch (inputtype) - { - case LineEdit: - input = ui->lineEdit; - break; - case SpinBox: - input = ui->spinBox; - break; - case UIntBox: - input = ui->uIntSpinBox; - break; - case FloatSpinBox: - input = ui->floatSpinBox; - break; - case ComboBox: - input = ui->comboBox; - break; - default: - break; + QWidget* input = nullptr; + switch (inputtype) { + case LineEdit: + input = ui->lineEdit; + break; + case SpinBox: + input = ui->spinBox; + break; + case UIntBox: + input = ui->uIntSpinBox; + break; + case FloatSpinBox: + input = ui->floatSpinBox; + break; + case ComboBox: + input = ui->comboBox; + break; + default: + break; } if (input) { ui->stack->setCurrentWidget(input->parentWidget()); - ui->stack->setFixedHeight( input->sizeHint().height() ); + ui->stack->setFixedHeight(input->sizeHint().height()); input->setFocus(); - ui->label->setBuddy( input ); + ui->label->setBuddy(input); } } @@ -120,27 +120,27 @@ DlgInputDialogImp::Type DlgInputDialogImp::type() const return inputtype; } -QSpinBox *DlgInputDialogImp::getSpinBox() const +QSpinBox* DlgInputDialogImp::getSpinBox() const { return ui->spinBox; } -Gui::UIntSpinBox *DlgInputDialogImp::getUIntBox() const +Gui::UIntSpinBox* DlgInputDialogImp::getUIntBox() const { return ui->uIntSpinBox; } -QDoubleSpinBox *DlgInputDialogImp::getFloatSpinBox() const +QDoubleSpinBox* DlgInputDialogImp::getFloatSpinBox() const { return ui->floatSpinBox; } -QLineEdit *DlgInputDialogImp::getLineEdit() const +QLineEdit* DlgInputDialogImp::getLineEdit() const { return ui->lineEdit; } -QComboBox *DlgInputDialogImp::getComboBox() const +QComboBox* DlgInputDialogImp::getComboBox() const { return ui->comboBox; } diff --git a/src/Gui/Dialogs/DlgInputDialogImp.h b/src/Gui/Dialogs/DlgInputDialogImp.h index f79d6f04ee..eacfb15ef8 100644 --- a/src/Gui/Dialogs/DlgInputDialogImp.h +++ b/src/Gui/Dialogs/DlgInputDialogImp.h @@ -33,10 +33,12 @@ class QDoubleSpinBox; class QLineEdit; class QComboBox; -namespace Gui { +namespace Gui +{ class UIntSpinBox; -namespace Dialog { +namespace Dialog +{ class Ui_DlgInputDialog; /** @@ -46,37 +48,44 @@ class Ui_DlgInputDialog; * the flexibility. * \author Werner Mayer */ -class GuiExport DlgInputDialogImp : public QDialog +class GuiExport DlgInputDialogImp: public QDialog { - Q_OBJECT + Q_OBJECT public: - enum Type { LineEdit, SpinBox, UIntBox, FloatSpinBox, ComboBox }; + enum Type + { + LineEdit, + SpinBox, + UIntBox, + FloatSpinBox, + ComboBox + }; - DlgInputDialogImp( const QString& label, QWidget* parent = nullptr, bool modal = true, Type = LineEdit ); - ~DlgInputDialogImp() override; + DlgInputDialogImp(const QString& label, QWidget* parent = nullptr, bool modal = true, Type = LineEdit); + ~DlgInputDialogImp() override; - void setType( Type t ); - Type type() const; + void setType(Type t); + Type type() const; - QSpinBox *getSpinBox() const; - Gui::UIntSpinBox *getUIntBox() const; - QDoubleSpinBox *getFloatSpinBox() const; - QLineEdit *getLineEdit() const; - QComboBox *getComboBox() const; + QSpinBox* getSpinBox() const; + Gui::UIntSpinBox* getUIntBox() const; + QDoubleSpinBox* getFloatSpinBox() const; + QLineEdit* getLineEdit() const; + QComboBox* getComboBox() const; protected Q_SLOTS: - void textChanged( const QString &s ); - void tryAccept(); + void textChanged(const QString& s); + void tryAccept(); protected: - Type inputtype; + Type inputtype; private: - std::unique_ptr ui; + std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGINPUTDIALOGIMP_H +#endif // GUI_DIALOG_DLGINPUTDIALOGIMP_H diff --git a/src/Gui/Dialogs/DlgKeyboardImp.cpp b/src/Gui/Dialogs/DlgKeyboardImp.cpp index a006570aca..c3c5ded9ba 100644 --- a/src/Gui/Dialogs/DlgKeyboardImp.cpp +++ b/src/Gui/Dialogs/DlgKeyboardImp.cpp @@ -96,26 +96,27 @@ DlgCustomKeyboardImp::DlgCustomKeyboardImp(QWidget* parent) if (auto cmd = Application::Instance->commandManager().getCommandByName(cmdName)) { cmd->initAction(); } - }); + } + ); - conn = initCommandWidgets(ui->commandTreeWidget, - nullptr, - ui->categoryBox, - ui->editCommand, - ui->assignedTreeWidget, - ui->buttonUp, - ui->buttonDown, - ui->editShortcut, - ui->accelLineEditShortcut); + conn = initCommandWidgets( + ui->commandTreeWidget, + nullptr, + ui->categoryBox, + ui->editCommand, + ui->assignedTreeWidget, + ui->buttonUp, + ui->buttonDown, + ui->editShortcut, + ui->accelLineEditShortcut + ); ui->shortcutTimeout->onRestore(); QTimer* timer = new QTimer(this); QObject::connect(ui->shortcutTimeout, qOverload(&QSpinBox::valueChanged), timer, [=](int) { timer->start(100); }); - QObject::connect(timer, &QTimer::timeout, [this]() { - ui->shortcutTimeout->onSave(); - }); + QObject::connect(timer, &QTimer::timeout, [this]() { ui->shortcutTimeout->onSave(); }); } /** Destroys the object and frees any allocated resources */ @@ -141,10 +142,12 @@ void DlgCustomKeyboardImp::setupConnections() // clang-format on } -void DlgCustomKeyboardImp::initCommandCompleter(QLineEdit* edit, - QComboBox* combo, - QTreeWidget* commandTreeWidget, - QTreeWidgetItem* separatorItem) +void DlgCustomKeyboardImp::initCommandCompleter( + QLineEdit* edit, + QComboBox* combo, + QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem +) { edit->setPlaceholderText(tr("Type to search…")); auto completer = new CommandCompleter(edit, edit); @@ -176,9 +179,11 @@ void DlgCustomKeyboardImp::initCommandCompleter(QLineEdit* edit, }); } -void DlgCustomKeyboardImp::populateCommandList(QTreeWidget* commandTreeWidget, - QTreeWidgetItem* separatorItem, - QComboBox* combo) +void DlgCustomKeyboardImp::populateCommandList( + QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* combo +) { QByteArray current; if (auto item = commandTreeWidget->currentItem()) { @@ -195,8 +200,8 @@ void DlgCustomKeyboardImp::populateCommandList(QTreeWidget* commandTreeWidget, CommandManager& cCmdMgr = Application::Instance->commandManager(); auto group = combo->itemData(combo->currentIndex(), Qt::UserRole).toByteArray(); - auto cmds = - group == "All" ? cCmdMgr.getAllCommands() : cCmdMgr.getGroupCommands(group.constData()); + auto cmds = group == "All" ? cCmdMgr.getAllCommands() + : cCmdMgr.getGroupCommands(group.constData()); QTreeWidgetItem* currentItem = nullptr; for (const Command* cmd : cmds) { QTreeWidgetItem* item = new QTreeWidgetItem(commandTreeWidget); @@ -223,9 +228,11 @@ void DlgCustomKeyboardImp::populateCommandList(QTreeWidget* commandTreeWidget, commandTreeWidget->resizeColumnToContents(3); } -boost::signals2::connection DlgCustomKeyboardImp::initCommandList(QTreeWidget* commandTreeWidget, - QTreeWidgetItem* separatorItem, - QComboBox* combo) +boost::signals2::connection DlgCustomKeyboardImp::initCommandList( + QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* combo +) { QStringList labels; labels << tr("Icon") << tr("Command") << tr("Shortcut") << tr("Default"); @@ -248,12 +255,9 @@ boost::signals2::connection DlgCustomKeyboardImp::initCommandList(QTreeWidget* c populateCommandList(commandTreeWidget, separatorItem, combo); }); - QObject::connect(ShortcutManager::instance(), - &ShortcutManager::shortcutChanged, - timer, - [timer]() { - timer->start(100); - }); + QObject::connect(ShortcutManager::instance(), &ShortcutManager::shortcutChanged, timer, [timer]() { + timer->start(100); + }); QObject::connect(combo, qOverload(&QComboBox::activated), timer, [timer]() { timer->start(100); @@ -264,9 +268,11 @@ boost::signals2::connection DlgCustomKeyboardImp::initCommandList(QTreeWidget* c }); } -void DlgCustomKeyboardImp::initPriorityList(QTreeWidget* priorityList, - QAbstractButton* buttonUp, - QAbstractButton* buttonDown) +void DlgCustomKeyboardImp::initPriorityList( + QTreeWidget* priorityList, + QAbstractButton* buttonUp, + QAbstractButton* buttonDown +) { QStringList labels; labels << tr("Name") << tr("Title"); @@ -301,28 +307,25 @@ void DlgCustomKeyboardImp::initPriorityList(QTreeWidget* priorityList, ShortcutManager::instance()->setPriorities(actions); }; - QObject::connect(buttonUp, &QAbstractButton::clicked, [=]() { - updatePriorityList(true); - }); - QObject::connect(buttonDown, &QAbstractButton::clicked, [=]() { - updatePriorityList(false); - }); + QObject::connect(buttonUp, &QAbstractButton::clicked, [=]() { updatePriorityList(true); }); + QObject::connect(buttonDown, &QAbstractButton::clicked, [=]() { updatePriorityList(false); }); QObject::connect(priorityList, &QTreeWidget::currentItemChanged, [=](QTreeWidgetItem* item) { buttonUp->setEnabled(item != nullptr); buttonDown->setEnabled(item != nullptr); }); } -boost::signals2::connection -DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget* commandTreeWidget, - QTreeWidgetItem* separatorItem, - QComboBox* comboGroups, - QLineEdit* editCommand, - QTreeWidget* priorityList, - QAbstractButton* buttonUp, - QAbstractButton* buttonDown, - Gui::AccelLineEdit* editShortcut, - Gui::AccelLineEdit* currentShortcut) +boost::signals2::connection DlgCustomKeyboardImp::initCommandWidgets( + QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* comboGroups, + QLineEdit* editCommand, + QTreeWidget* priorityList, + QAbstractButton* buttonUp, + QAbstractButton* buttonDown, + Gui::AccelLineEdit* editShortcut, + Gui::AccelLineEdit* currentShortcut +) { initCommandCompleter(editCommand, comboGroups, commandTreeWidget, separatorItem); auto conn = initCommandList(commandTreeWidget, separatorItem, comboGroups); @@ -340,12 +343,12 @@ DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget* commandTreeWidget, QObject::connect(editShortcut, &AccelLineEdit::keySequenceChanged, timer, [timer]() { timer->start(200); }); - QObject::connect(ShortcutManager::instance(), - &ShortcutManager::priorityChanged, - timer, - [timer]() { - timer->start(200); - }); + QObject::connect( + ShortcutManager::instance(), + &ShortcutManager::priorityChanged, + timer, + [timer]() { timer->start(200); } + ); QObject::connect(timer, &QTimer::timeout, [=]() { populatePriorityList(priorityList, editShortcut, currentShortcut); }); @@ -354,9 +357,11 @@ DlgCustomKeyboardImp::initCommandWidgets(QTreeWidget* commandTreeWidget, return conn; } -void DlgCustomKeyboardImp::populatePriorityList(QTreeWidget* priorityList, - Gui::AccelLineEdit* editor, - Gui::AccelLineEdit* curShortcut) +void DlgCustomKeyboardImp::populatePriorityList( + QTreeWidget* priorityList, + Gui::AccelLineEdit* editor, + Gui::AccelLineEdit* curShortcut +) { QByteArray current; if (auto currentItem = priorityList->currentItem()) { @@ -409,7 +414,8 @@ void DlgCustomKeyboardImp::populateCommandGroups(QComboBox* combo) groupMap.push_back(std::make_pair(QLatin1String("Window"), QString())); groupMap.push_back(std::make_pair(QLatin1String("Help"), QString())); groupMap.push_back( - std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros"))); + std::make_pair(QLatin1String("Macros"), qApp->translate("Gui::MacroCommand", "Macros")) + ); for (const auto& sCommand : sCommands) { QLatin1String group(sCommand.second->getGroupName()); diff --git a/src/Gui/Dialogs/DlgKeyboardImp.h b/src/Gui/Dialogs/DlgKeyboardImp.h index 62bae929eb..e460eff2aa 100644 --- a/src/Gui/Dialogs/DlgKeyboardImp.h +++ b/src/Gui/Dialogs/DlgKeyboardImp.h @@ -36,11 +36,13 @@ class QComboBox; class QLineEdit; class QAbstractButton; -namespace Gui { +namespace Gui +{ class AccelLineEdit; -namespace Dialog { +namespace Dialog +{ class Ui_DlgCustomKeyboard; /** Shows an overview of all available commands of all groups and modules. @@ -50,12 +52,12 @@ class Ui_DlgCustomKeyboard; * customize your own toolbars or commandbars. * \author Werner Mayer */ -class DlgCustomKeyboardImp : public CustomizeActionPage +class DlgCustomKeyboardImp: public CustomizeActionPage { Q_OBJECT public: - explicit DlgCustomKeyboardImp( QWidget* parent = nullptr ); + explicit DlgCustomKeyboardImp(QWidget* parent = nullptr); ~DlgCustomKeyboardImp() override; /** Public helper function for handling command widgets @@ -73,32 +75,37 @@ public: * @return Return a boost signal connection for monitoring command changes. * Most disconnect the signal before widgets gets destroyed. */ - static boost::signals2::connection - initCommandWidgets(QTreeWidget *commandTreeWidget, - QTreeWidgetItem *separatorItem, - QComboBox *comboGroups, - QLineEdit *editCommand, - QTreeWidget *priorityList = nullptr, - QAbstractButton *buttonUp = nullptr, - QAbstractButton *buttonDown = nullptr, - Gui::AccelLineEdit *editShortcut = nullptr, - Gui::AccelLineEdit *currentShortcut = nullptr); + static boost::signals2::connection initCommandWidgets( + QTreeWidget* commandTreeWidget, + QTreeWidgetItem* separatorItem, + QComboBox* comboGroups, + QLineEdit* editCommand, + QTreeWidget* priorityList = nullptr, + QAbstractButton* buttonUp = nullptr, + QAbstractButton* buttonDown = nullptr, + Gui::AccelLineEdit* editShortcut = nullptr, + Gui::AccelLineEdit* currentShortcut = nullptr + ); protected: /** @name Internal helper function for handling command list widgets */ //@{ - static void initCommandCompleter(QLineEdit *, - QComboBox *combo, - QTreeWidget *treeWidget, - QTreeWidgetItem *separatorItem); - static boost::signals2::connection initCommandList(QTreeWidget *, QTreeWidgetItem *, QComboBox *combo); - static void initPriorityList(QTreeWidget *, QAbstractButton *buttonUp, QAbstractButton *buttonDown); - static void populateCommandGroups(QComboBox *); - static void populateCommandList(QTreeWidget *, QTreeWidgetItem *, QComboBox *); - static void populatePriorityList(QTreeWidget *priorityList, - AccelLineEdit *editor, - AccelLineEdit *current); + static void initCommandCompleter( + QLineEdit*, + QComboBox* combo, + QTreeWidget* treeWidget, + QTreeWidgetItem* separatorItem + ); + static boost::signals2::connection initCommandList(QTreeWidget*, QTreeWidgetItem*, QComboBox* combo); + static void initPriorityList(QTreeWidget*, QAbstractButton* buttonUp, QAbstractButton* buttonDown); + static void populateCommandGroups(QComboBox*); + static void populateCommandList(QTreeWidget*, QTreeWidgetItem*, QComboBox*); + static void populatePriorityList( + QTreeWidget* priorityList, + AccelLineEdit* editor, + AccelLineEdit* current + ); //@} protected: void setupConnections(); @@ -117,7 +124,7 @@ protected Q_SLOTS: protected: void showEvent(QShowEvent* e) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void setShortcutOfCurrentAction(const QString&); private: @@ -126,7 +133,7 @@ private: boost::signals2::scoped_connection conn; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGKEYBOARD_IMP_H +#endif // GUI_DIALOG_DLGKEYBOARD_IMP_H diff --git a/src/Gui/Dialogs/DlgMacroExecuteImp.cpp b/src/Gui/Dialogs/DlgMacroExecuteImp.cpp index c92d7f2585..d6810a9577 100644 --- a/src/Gui/Dialogs/DlgMacroExecuteImp.cpp +++ b/src/Gui/Dialogs/DlgMacroExecuteImp.cpp @@ -108,9 +108,10 @@ DlgMacroExecuteImp::DlgMacroExecuteImp(QWidget* parent, Qt::WindowFlags fl) // retrieve the macro path from parameter or use the user data as default { QSignalBlocker blocker(ui->fileChooser); - std::string path = - getWindowParameter()->GetASCII("MacroPath", - App::Application::getUserMacroDir().c_str()); + std::string path = getWindowParameter()->GetASCII( + "MacroPath", + App::Application::getUserMacroDir().c_str() + ); this->macroPath = QString::fromUtf8(path.c_str()); ui->fileChooser->setFileName(this->macroPath); } @@ -125,7 +126,8 @@ DlgMacroExecuteImp::DlgMacroExecuteImp(QWidget* parent, Qt::WindowFlags fl) fillUpList(); ui->LineEditFind->setFocus(); ui->addonsButton->setEnabled( - Application::Instance->commandManager().getCommandByName("Std_AddonMgr") != nullptr); + Application::Instance->commandManager().getCommandByName("Std_AddonMgr") != nullptr + ); } /** @@ -266,8 +268,8 @@ void DlgMacroExecuteImp::fillUpList() { fillUpListForDir(this->macroPath, false); - QString dirstr = - QString::fromStdString(App::Application::getHomePath()) + QStringLiteral("Macro"); + QString dirstr = QString::fromStdString(App::Application::getHomePath()) + + QStringLiteral("Macro"); fillUpListForDir(dirstr, true); auto& config = App::Application::Config(); @@ -464,13 +466,15 @@ void DlgMacroExecuteImp::onCreateButtonClicked() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") ->SetBool("ReplaceSpaces", replaceSpaces); // create parameter - QString fn = QInputDialog::getText(this, - tr("Macro file"), - tr("Enter a file name:"), - QLineEdit::Normal, - QString(), - nullptr, - Qt::MSWindowsFixedSizeDialogHint); + QString fn = QInputDialog::getText( + this, + tr("Macro file"), + tr("Enter a file name:"), + QLineEdit::Normal, + QString(), + nullptr, + Qt::MSWindowsFixedSizeDialogHint + ); if (replaceSpaces) { fn = fn.replace(QStringLiteral(" "), QStringLiteral("_")); @@ -488,9 +492,11 @@ void DlgMacroExecuteImp::onCreateButtonClicked() } QFileInfo fi(dir, fn); if (fi.exists() && fi.isFile()) { - QMessageBox::warning(this, - tr("Existing file"), - tr("'%1'.\nThis file already exists.").arg(fi.fileName())); + QMessageBox::warning( + this, + tr("Existing file"), + tr("'%1'.\nThis file already exists.").arg(fi.fileName()) + ); } else { QFile file(fi.absoluteFilePath()); @@ -498,7 +504,8 @@ void DlgMacroExecuteImp::onCreateButtonClicked() QMessageBox::warning( this, tr("Cannot create file"), - tr("Creation of file '%1' failed.").arg(fi.absoluteFilePath())); + tr("Creation of file '%1' failed.").arg(fi.absoluteFilePath()) + ); return; } file.close(); @@ -527,18 +534,22 @@ void DlgMacroExecuteImp::onDeleteButtonClicked() } if (item->systemWide) { - QMessageBox::critical(Gui::getMainWindow(), - QObject::tr("Delete macro"), - QObject::tr("Not allowed to delete system-wide macros")); + QMessageBox::critical( + Gui::getMainWindow(), + QObject::tr("Delete macro"), + QObject::tr("Not allowed to delete system-wide macros") + ); return; } QString fn = item->text(0); - auto ret = QMessageBox::question(this, - tr("Delete macro"), - tr("Delete the macro '%1'?").arg(fn), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + auto ret = QMessageBox::question( + this, + tr("Delete macro"), + tr("Delete the macro '%1'?").arg(fn), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No + ); if (ret == QMessageBox::Yes) { QDir dir(this->macroPath); dir.remove(fn); @@ -568,8 +579,8 @@ void DlgMacroExecuteImp::onToolbarButtonClicked() ->GetBool("ShowWalkthroughMessage", true); if (showAgain) { QMessageBox msgBox(this); - QAbstractButton* doNotShowAgainButton = - msgBox.addButton(tr("Do not show again"), QMessageBox::YesRole); + QAbstractButton* doNotShowAgainButton + = msgBox.addButton(tr("Do not show again"), QMessageBox::YesRole); msgBox.setText(tr("Guided Walkthrough")); msgBox.setObjectName(QStringLiteral("macroGuideWalkthrough")); msgBox.setInformativeText(tr("This will guide you in setting up this macro in a custom \ @@ -595,8 +606,8 @@ Note: your changes will be applied when you next switch workbenches\n")); } QString fn = item->text(0); - QString bareFileName = - QFileInfo(fn).baseName(); // for use as default menu text (filename without extension) + QString bareFileName = QFileInfo(fn).baseName(); // for use as default menu text (filename + // without extension) /** check if user already has custom toolbar, so we can tailor instructions accordingly **/ bool hasCustomToolbar = true; @@ -635,8 +646,9 @@ Note: your changes will be applied when you next switch workbenches\n")); return; } - auto setupCustomMacrosPage = - tabWidget->findChild(QStringLiteral("Gui__Dialog__DlgCustomActions")); + auto setupCustomMacrosPage = tabWidget->findChild( + QStringLiteral("Gui__Dialog__DlgCustomActions") + ); if (!setupCustomMacrosPage) { std::cerr << "Toolbar walkthrough error: Unable to find setupCustomMacrosPage" << std::endl; @@ -644,21 +656,23 @@ Note: your changes will be applied when you next switch workbenches\n")); } tabWidget->setCurrentWidget(setupCustomMacrosPage); - auto groupBox7 = - setupCustomMacrosPage->findChild(QStringLiteral("GroupBox7")); + auto groupBox7 = setupCustomMacrosPage->findChild(QStringLiteral("GroupBox7")); if (!groupBox7) { Base::Console().warning("Toolbar walkthrough: Unable to find groupBox7\n"); // just warn when not a fatal error } else { /** normally the groupbox title is "Setup Custom Macros", but we change it here **/ - groupBox7->setTitle(tr("Walkthrough instructions: Fill in missing fields (optional) " - "then click Add, then Close")); + groupBox7->setTitle( + tr("Walkthrough instructions: Fill in missing fields (optional) " + "then click Add, then Close") + ); groupBox7->setStyleSheet(QStringLiteral("QGroupBox::title {color:red}")); } - auto buttonAddAction = - setupCustomMacrosPage->findChild(QStringLiteral("buttonAddAction")); + auto buttonAddAction = setupCustomMacrosPage->findChild( + QStringLiteral("buttonAddAction") + ); if (!buttonAddAction) { Base::Console().warning("Toolbar walkthrough: Unable to find buttonAddAction\n"); } @@ -666,19 +680,18 @@ Note: your changes will be applied when you next switch workbenches\n")); buttonAddAction->setStyleSheet(QStringLiteral("color:red")); } - auto macroListBox = - setupCustomMacrosPage->findChild(QStringLiteral("actionMacros")); + auto macroListBox = setupCustomMacrosPage->findChild( + QStringLiteral("actionMacros") + ); if (!macroListBox) { Base::Console().warning("Toolbar walkthrough: Unable to find actionMacros combo box\n"); } else { int macroIndex = macroListBox->findText(fn); // fn is the macro filename - macroListBox->setCurrentIndex( - macroIndex); // select it for the user so they don't have to + macroListBox->setCurrentIndex(macroIndex); // select it for the user so they don't have to } - auto menuText = - setupCustomMacrosPage->findChild(QStringLiteral("actionMenu")); + auto menuText = setupCustomMacrosPage->findChild(QStringLiteral("actionMenu")); if (!menuText) { Base::Console().warning("Toolbar walkthrough: Unable to find actionMenu menuText\n"); } @@ -692,8 +705,9 @@ Note: your changes will be applied when you next switch workbenches\n")); /** now for the toolbar selection dialog **/ Gui::Dialog::DlgCustomizeImp dlg(this); - dlg.setWindowTitle(hasMacroCommand ? tr("Walkthrough, Dialog 1 of 1") - : tr("Walkthrough, Dialog 2 of 2")); + dlg.setWindowTitle( + hasMacroCommand ? tr("Walkthrough, Dialog 1 of 1") : tr("Walkthrough, Dialog 2 of 2") + ); tabWidget = nullptr; tabWidget = dlg.findChild(QStringLiteral("Gui__Dialog__TabWidget")); @@ -704,7 +718,8 @@ Note: your changes will be applied when you next switch workbenches\n")); } auto setupToolbarPage = tabWidget->findChild( - QStringLiteral("Gui__Dialog__DlgCustomToolbars")); + QStringLiteral("Gui__Dialog__DlgCustomToolbars") + ); if (!setupToolbarPage) { std::cerr << "Toolbar walkthrough: Unable to find setupToolbarPage Gui__Dialog__DlgCustomToolbars" @@ -713,8 +728,9 @@ Note: your changes will be applied when you next switch workbenches\n")); } tabWidget->setCurrentWidget(setupToolbarPage); - auto moveActionRightButton = - setupToolbarPage->findChild(QStringLiteral("moveActionRightButton")); + auto moveActionRightButton = setupToolbarPage->findChild( + QStringLiteral("moveActionRightButton") + ); if (!moveActionRightButton) { Base::Console().warning("Toolbar walkthrough: Unable to find moveActionRightButton\n"); } @@ -725,10 +741,9 @@ Note: your changes will be applied when you next switch workbenches\n")); * if not, they need to click New button to create one first **/ - QString instructions2 = - tr("Walkthrough instructions: Select macro from list, then click right arrow button (->), then Close."); - auto workbenchBox = - setupToolbarPage->findChild(QStringLiteral("workbenchBox")); + QString instructions2 + = tr("Walkthrough instructions: Select macro from list, then click right arrow button (->), then Close."); + auto workbenchBox = setupToolbarPage->findChild(QStringLiteral("workbenchBox")); if (!workbenchBox) { Base::Console().warning("Toolbar walkthrough: Unable to find workbenchBox\n"); } @@ -745,15 +760,16 @@ Note: your changes will be applied when you next switch workbenches\n")); } if (!hasCustomToolbar) { - auto newButton = - setupToolbarPage->findChild(QStringLiteral("newButton")); + auto newButton = setupToolbarPage->findChild(QStringLiteral("newButton")); if (!newButton) { Base::Console().warning("Toolbar walkthrough: Unable to find newButton\n"); } else { newButton->setStyleSheet(QStringLiteral("color:red")); - instructions2 = tr("Walkthrough instructions: Click New, select macro, then right arrow (->) " - "button, then Close."); + instructions2 = tr( + "Walkthrough instructions: Click New, select macro, then right arrow (->) " + "button, then Close." + ); } } } @@ -785,8 +801,9 @@ Note: your changes will be applied when you next switch workbenches\n")); } /** expand custom toolbar items **/ - auto toolbarTreeWidget = - setupToolbarPage->findChild(QStringLiteral("toolbarTreeWidget")); + auto toolbarTreeWidget = setupToolbarPage->findChild( + QStringLiteral("toolbarTreeWidget") + ); if (!toolbarTreeWidget) { Base::Console().warning("Toolbar walkthrough: Unable to find toolbarTreeWidget\n"); } @@ -798,22 +815,25 @@ Note: your changes will be applied when you next switch workbenches\n")); tree widget to populate all the actions **/ QTimer::singleShot(500, [=]() { - auto commandTreeWidget = - setupToolbarPage->findChild(QStringLiteral("commandTreeWidget")); + auto commandTreeWidget = setupToolbarPage->findChild( + QStringLiteral("commandTreeWidget") + ); if (!commandTreeWidget) { Base::Console().warning("Toolbar walkthrough: Unable to find commandTreeWidget\n"); } else { if (!hasMacroCommand) { // will be the last in the list, the one just created commandTreeWidget->setCurrentItem( - commandTreeWidget->topLevelItem(commandTreeWidget->topLevelItemCount() - 1)); + commandTreeWidget->topLevelItem(commandTreeWidget->topLevelItemCount() - 1) + ); commandTreeWidget->scrollToItem(commandTreeWidget->currentItem()); } else { // preselect it for the user (will be the macro menu text) - QList items = - commandTreeWidget->findItems(macroMenuText, - Qt::MatchFixedString | Qt::MatchWrap, - 1); + QList items = commandTreeWidget->findItems( + macroMenuText, + Qt::MatchFixedString | Qt::MatchWrap, + 1 + ); if (!items.empty()) { commandTreeWidget->setCurrentItem(items[0]); commandTreeWidget->scrollToItem(commandTreeWidget->currentItem()); @@ -860,13 +880,15 @@ void DlgMacroExecuteImp::onRenameButtonClicked() QFile oldfile(oldfi.absoluteFilePath()); // query new name - QString fn = QInputDialog::getText(this, - tr("Renaming Macro File"), - tr("Enter new name"), - QLineEdit::Normal, - oldName, - nullptr, - Qt::MSWindowsFixedSizeDialogHint); + QString fn = QInputDialog::getText( + this, + tr("Renaming Macro File"), + tr("Enter new name"), + QLineEdit::Normal, + oldName, + nullptr, + Qt::MSWindowsFixedSizeDialogHint + ); if (replaceSpaces) { fn = fn.replace(QStringLiteral(" "), QStringLiteral("_")); @@ -880,15 +902,19 @@ void DlgMacroExecuteImp::onRenameButtonClicked() QFileInfo fi(dir, fn); // check if new name exists if (fi.exists()) { - QMessageBox::warning(this, - tr("Existing file"), - tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); + QMessageBox::warning( + this, + tr("Existing file"), + tr("'%1'\n already exists.").arg(fi.absoluteFilePath()) + ); } else if (!oldfile.rename(fi.absoluteFilePath())) { - QMessageBox::warning(this, - tr("Rename Failed"), - tr("Failed to rename to '%1'.\nPerhaps a file permission error?") - .arg(fi.absoluteFilePath())); + QMessageBox::warning( + this, + tr("Rename Failed"), + tr("Failed to rename to '%1'.\nPerhaps a file permission error?") + .arg(fi.absoluteFilePath()) + ); } else { // keep the item selected although it's not necessarily in alphabetic order @@ -972,8 +998,7 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() } baseName = baseName.left(baseName.size() - 3); // strip digits if (baseName.endsWith(neutralSymbol)) { - baseName = - baseName.left(baseName.size() - 1); // trim the "@", will be added back later + baseName = baseName.left(baseName.size() - 1); // trim the "@", will be added back later } } } @@ -994,8 +1019,8 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() } - QString oldNameDigitized = - baseName + neutralSymbol + last3 + QStringLiteral(".") + completeSuffix; + QString oldNameDigitized = baseName + neutralSymbol + last3 + QStringLiteral(".") + + completeSuffix; QFileInfo fi(dir, oldNameDigitized); @@ -1011,8 +1036,7 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() while (last3.size() < 3) { last3.prepend(QStringLiteral("0")); // pad 0's if needed } - oldNameDigitized = - baseName + neutralSymbol + last3 + QStringLiteral(".") + completeSuffix; + oldNameDigitized = baseName + neutralSymbol + last3 + QStringLiteral(".") + completeSuffix; fi = QFileInfo(dir, oldNameDigitized); } @@ -1021,13 +1045,15 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() } // give user a chance to pick a different name from digitized name suggested - QString fn = QInputDialog::getText(this, - tr("Duplicate Macro"), - tr("Enter new name"), - QLineEdit::Normal, - oldNameDigitized, - nullptr, - Qt::MSWindowsFixedSizeDialogHint); + QString fn = QInputDialog::getText( + this, + tr("Duplicate Macro"), + tr("Enter new name"), + QLineEdit::Normal, + oldNameDigitized, + nullptr, + Qt::MSWindowsFixedSizeDialogHint + ); if (replaceSpaces) { fn = fn.replace(QStringLiteral(" "), QStringLiteral("_")); } @@ -1039,16 +1065,19 @@ void DlgMacroExecuteImp::onDuplicateButtonClicked() QFileInfo fi(dir, fn); // check again if new name exists in case user changed it if (fi.exists()) { - QMessageBox::warning(this, - tr("Existing file"), - tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); + QMessageBox::warning( + this, + tr("Existing file"), + tr("'%1'\n already exists.").arg(fi.absoluteFilePath()) + ); } else if (!oldfile.copy(fi.absoluteFilePath())) { QMessageBox::warning( this, tr("Duplicate Failed"), tr("Failed to duplicate to '%1'.\nPerhaps a file permission error?") - .arg(fi.absoluteFilePath())); + .arg(fi.absoluteFilePath()) + ); } this->fillUpList(); // repopulate list to show new file diff --git a/src/Gui/Dialogs/DlgMacroExecuteImp.h b/src/Gui/Dialogs/DlgMacroExecuteImp.h index cf12d5add1..80a219f104 100644 --- a/src/Gui/Dialogs/DlgMacroExecuteImp.h +++ b/src/Gui/Dialogs/DlgMacroExecuteImp.h @@ -31,8 +31,10 @@ class QTreeWidgetItem; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgMacroExecute; /** @@ -40,7 +42,7 @@ class Ui_DlgMacroExecute; * recorded macro. * \author Jürgen Riegel */ -class DlgMacroExecuteImp : public QDialog, public Gui::WindowParameter +class DlgMacroExecuteImp: public QDialog, public Gui::WindowParameter { Q_OBJECT @@ -81,7 +83,7 @@ private: std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGMACROEXECUTEIMP_H +#endif // GUI_DIALOG_DLGMACROEXECUTEIMP_H diff --git a/src/Gui/Dialogs/DlgMacroRecordImp.cpp b/src/Gui/Dialogs/DlgMacroRecordImp.cpp index 307a9eae79..3c3c405ec9 100644 --- a/src/Gui/Dialogs/DlgMacroRecordImp.cpp +++ b/src/Gui/Dialogs/DlgMacroRecordImp.cpp @@ -53,10 +53,9 @@ DlgMacroRecordImp::DlgMacroRecordImp(QWidget* parent, Qt::WindowFlags fl) setupConnections(); // get the macro home path - this->macroPath = - QString::fromUtf8(getWindowParameter() - ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()) - .c_str()); + this->macroPath = QString::fromUtf8( + getWindowParameter()->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()).c_str() + ); this->macroPath = QDir::toNativeSeparators(QDir(this->macroPath).path() + QDir::separator()); // set the edit fields @@ -98,9 +97,11 @@ void DlgMacroRecordImp::onButtonStartClicked() { // test if the path already set if (ui->lineEditPath->text().isEmpty()) { - QMessageBox::information(getMainWindow(), - tr("Macro recorder"), - tr("Specify a place to save first.")); + QMessageBox::information( + getMainWindow(), + tr("Macro recorder"), + tr("Specify a place to save first.") + ); return; } @@ -109,7 +110,8 @@ void DlgMacroRecordImp::onButtonStartClicked() QMessageBox::information( getMainWindow(), tr("Macro recorder"), - tr("The macro directory does not exist. Choose another one.")); + tr("The macro directory does not exist. Choose another one.") + ); return; } @@ -126,7 +128,8 @@ void DlgMacroRecordImp::onButtonStartClicked() tr("Existing macro"), tr("The macro '%1' already exists. Overwrite it?").arg(fn), QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) + QMessageBox::No + ) == QMessageBox::No) { return; } @@ -137,7 +140,8 @@ void DlgMacroRecordImp::onButtonStartClicked() QMessageBox::information( getMainWindow(), tr("Macro recorder"), - tr("You have no write permission for the directory. Choose another one.")); + tr("You have no write permission for the directory. Choose another one.") + ); return; } file.close(); @@ -181,8 +185,8 @@ void DlgMacroRecordImp::onButtonStopClicked() void DlgMacroRecordImp::onButtonChooseDirClicked() { - QString newDir = - QFileDialog::getExistingDirectory(nullptr, tr("Choose macro directory"), macroPath); + QString newDir + = QFileDialog::getExistingDirectory(nullptr, tr("Choose macro directory"), macroPath); if (!newDir.isEmpty()) { macroPath = QDir::toNativeSeparators(newDir + QDir::separator()); ui->lineEditMacroPath->setText(macroPath); diff --git a/src/Gui/Dialogs/DlgMacroRecordImp.h b/src/Gui/Dialogs/DlgMacroRecordImp.h index 5568fc6749..94b9479c0d 100644 --- a/src/Gui/Dialogs/DlgMacroRecordImp.h +++ b/src/Gui/Dialogs/DlgMacroRecordImp.h @@ -28,21 +28,23 @@ #include #include "Window.h" -namespace Gui { +namespace Gui +{ class MacroManager; -namespace Dialog { +namespace Dialog +{ class Ui_DlgMacroRecord; /** * The DlgMacroRecordImp class implements a dialog to record a macro. * \author Jürgen Riegel */ -class DlgMacroRecordImp : public QDialog, public Gui::WindowParameter +class DlgMacroRecordImp: public QDialog, public Gui::WindowParameter { Q_OBJECT public: - explicit DlgMacroRecordImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + explicit DlgMacroRecordImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); ~DlgMacroRecordImp() override; protected: @@ -51,16 +53,16 @@ protected: void onButtonStopClicked(); void onButtonCloseClicked(); void onButtonChooseDirClicked(); - void onMacroPathTextChanged ( const QString & ); + void onMacroPathTextChanged(const QString&); private: std::unique_ptr ui; /// convenience pointer MacroManager* macroManager; - QString macroPath; // Macro file to save in + QString macroPath; // Macro file to save in }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGMACRORECORDIMP_H +#endif // GUI_DIALOG_DLGMACRORECORDIMP_H diff --git a/src/Gui/Dialogs/DlgMaterialPropertiesImp.h b/src/Gui/Dialogs/DlgMaterialPropertiesImp.h index be12ff28a5..3289f02dde 100644 --- a/src/Gui/Dialogs/DlgMaterialPropertiesImp.h +++ b/src/Gui/Dialogs/DlgMaterialPropertiesImp.h @@ -52,8 +52,7 @@ class GuiExport DlgMaterialPropertiesImp: public QDialog Q_OBJECT public: - explicit DlgMaterialPropertiesImp(QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit DlgMaterialPropertiesImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); ~DlgMaterialPropertiesImp() override; App::Material getCustomMaterial() const; void setCustomMaterial(const App::Material& mat); diff --git a/src/Gui/Dialogs/DlgObjectSelection.cpp b/src/Gui/Dialogs/DlgObjectSelection.cpp index 76d368376c..47d7329d4b 100644 --- a/src/Gui/Dialogs/DlgObjectSelection.cpp +++ b/src/Gui/Dialogs/DlgObjectSelection.cpp @@ -20,9 +20,9 @@ * * ****************************************************************************/ -# include -# include -# include +#include +#include +#include #include #include @@ -35,38 +35,44 @@ #include "MetaTypes.h" #include "ViewParams.h" -FC_LOG_LEVEL_INIT("Gui",true,true) +FC_LOG_LEVEL_INIT("Gui", true, true) using namespace Gui; /* TRANSLATOR Gui::DlgObjectSelection */ DlgObjectSelection::DlgObjectSelection( - const std::vector &objs, QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) + const std::vector& objs, + QWidget* parent, + Qt::WindowFlags fl +) + : QDialog(parent, fl) { init(objs, {}); } DlgObjectSelection::DlgObjectSelection( - const std::vector &objs, - const std::vector &excludes, - QWidget* parent, - Qt::WindowFlags fl) - : QDialog(parent, fl) + const std::vector& objs, + const std::vector& excludes, + QWidget* parent, + Qt::WindowFlags fl +) + : QDialog(parent, fl) { init(objs, excludes); } -static bool inline setCheckState(QTreeWidgetItem *item, Qt::CheckState state, bool forced=true) +static bool inline setCheckState(QTreeWidgetItem* item, Qt::CheckState state, bool forced = true) { if (!forced) { if (item->isSelected()) { - if (state == Qt::Unchecked || item->checkState(0) == Qt::Unchecked) + if (state == Qt::Unchecked || item->checkState(0) == Qt::Unchecked) { return false; + } } - if (item->checkState(0) == state) + if (item->checkState(0) == state) { return false; + } } // auto objT = qvariant_cast(item->data(0, Qt::UserRole)); // FC_MSG(objT.getObjectFullName() << (state == Qt::Unchecked ? " unchecked" : @@ -75,8 +81,10 @@ static bool inline setCheckState(QTreeWidgetItem *item, Qt::CheckState state, bo return true; } -void DlgObjectSelection::init(const std::vector &objs, - const std::vector &excludes) +void DlgObjectSelection::init( + const std::vector& objs, + const std::vector& excludes +) { initSels = objs; @@ -93,11 +101,10 @@ void DlgObjectSelection::init(const std::vector &objs, connect(ui->checkBoxAutoDeps, &QCheckBox::toggled, this, &DlgObjectSelection::onAutoDeps); ui->checkBoxShowDeps->setChecked(hGrp->GetBool("ObjectSelectionShowDeps", false)); - QObject::connect(ui->checkBoxShowDeps, &QCheckBox::toggled, - [this](bool checked) { - hGrp->SetBool("ObjectSelectionShowDeps", checked); - onShowDeps(); - }); + QObject::connect(ui->checkBoxShowDeps, &QCheckBox::toggled, [this](bool checked) { + hGrp->SetBool("ObjectSelectionShowDeps", checked); + onShowDeps(); + }); QMetaObject::invokeMethod(this, "onShowDeps", Qt::QueuedConnection); // make sure to show a horizontal scrollbar if needed @@ -120,29 +127,31 @@ void DlgObjectSelection::init(const std::vector &objs, ui->treeWidget->headerItem()->setText(0, tr("Selections")); ui->treeWidget->header()->setStretchLastSection(false); - connect(ui->treeWidget, &QTreeWidget::itemExpanded, - this, &DlgObjectSelection::onItemExpanded); + connect(ui->treeWidget, &QTreeWidget::itemExpanded, this, &DlgObjectSelection::onItemExpanded); allItem = new QTreeWidgetItem(ui->treeWidget); allItem->setText(0, QStringLiteral("<%1>").arg(tr("All"))); QFont font = allItem->font(0); font.setBold(true); allItem->setFont(0, font); - allItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); + allItem->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); allItem->setCheckState(0, Qt::Checked); - for(auto obj : initSels) + for (auto obj : initSels) { getItem(obj)->setCheckState(0, Qt::Checked); + } - for(auto obj : deps) + for (auto obj : deps) { getItem(obj)->setCheckState(0, Qt::Checked); + } auto filter = excludes; std::sort(filter.begin(), filter.end()); for (auto obj : deps) { auto it = std::lower_bound(filter.begin(), filter.end(), obj); - if (it != filter.end() && *it == obj) + if (it != filter.end() && *it == obj) { setItemState(obj, Qt::Unchecked); + } } onItemSelectionChanged(); @@ -152,16 +161,22 @@ void DlgObjectSelection::init(const std::vector &objs, * formatting exactly the way I wanted it. -- */ useOriginalsBtn = new QPushButton(tr("&Use Original Selection")); - useOriginalsBtn->setToolTip(tr("Ignore dependencies and proceed with the objects\noriginally selected prior to opening this dialog")); + useOriginalsBtn->setToolTip( + tr("Ignore dependencies and proceed with the objects\noriginally selected prior to opening " + "this dialog") + ); ui->buttonBox->addButton(useOriginalsBtn, QDialogButtonBox::ResetRole); connect(ui->treeWidget, &QTreeWidget::itemChanged, this, &DlgObjectSelection::onObjItemChanged); connect(ui->depList, &QTreeWidget::itemChanged, this, &DlgObjectSelection::onDepItemChanged); connect(ui->inList, &QTreeWidget::itemChanged, this, &DlgObjectSelection::onDepItemChanged); - connect(ui->treeWidget, &QTreeWidget::itemSelectionChanged, - this, &DlgObjectSelection::onItemSelectionChanged); - connect(useOriginalsBtn, &QPushButton::clicked, - this, &DlgObjectSelection::onUseOriginalsBtnClicked); + connect( + ui->treeWidget, + &QTreeWidget::itemSelectionChanged, + this, + &DlgObjectSelection::onItemSelectionChanged + ); + connect(useOriginalsBtn, &QPushButton::clicked, this, &DlgObjectSelection::onUseOriginalsBtnClicked); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &DlgObjectSelection::accept); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &DlgObjectSelection::reject); @@ -179,21 +194,28 @@ DlgObjectSelection::~DlgObjectSelection() delete ui; } -QTreeWidgetItem *DlgObjectSelection::getItem(App::DocumentObject *obj, - std::vector **pitems, - QTreeWidgetItem *parent) +QTreeWidgetItem* DlgObjectSelection::getItem( + App::DocumentObject* obj, + std::vector** pitems, + QTreeWidgetItem* parent +) { - auto &items = itemMap[App::SubObjectT(obj, "")]; - if (pitems) + auto& items = itemMap[App::SubObjectT(obj, "")]; + if (pitems) { *pitems = &items; - QTreeWidgetItem *item; + } + QTreeWidgetItem* item; if (!parent) { - if (!items.empty()) + if (!items.empty()) { return items[0]; + } item = new QTreeWidgetItem(ui->treeWidget); auto vp = freecad_cast( - Gui::Application::Instance->getViewProvider(obj)); - if (vp) item->setIcon(0, vp->getIcon()); + Gui::Application::Instance->getViewProvider(obj) + ); + if (vp) { + item->setIcon(0, vp->getIcon()); + } App::SubObjectT objT(obj, ""); item->setText(0, QString::fromUtf8((obj)->Label.getValue())); if (std::binary_search(initSels.begin(), initSels.end(), obj)) { @@ -204,9 +226,12 @@ QTreeWidgetItem *DlgObjectSelection::getItem(App::DocumentObject *obj, } item->setToolTip(0, QString::fromUtf8(objT.getObjectFullName().c_str())); item->setData(0, Qt::UserRole, QVariant::fromValue(objT)); - item->setChildIndicatorPolicy(obj->getOutList().empty() ? - QTreeWidgetItem::DontShowIndicator : QTreeWidgetItem::ShowIndicator); - } else if (!items.empty()) { + item->setChildIndicatorPolicy( + obj->getOutList().empty() ? QTreeWidgetItem::DontShowIndicator + : QTreeWidgetItem::ShowIndicator + ); + } + else if (!items.empty()) { item = new QTreeWidgetItem(parent); item->setIcon(0, items[0]->icon(0)); item->setText(0, items[0]->text(0)); @@ -215,23 +240,27 @@ QTreeWidgetItem *DlgObjectSelection::getItem(App::DocumentObject *obj, item->setData(0, Qt::UserRole, items[0]->data(0, Qt::UserRole)); item->setChildIndicatorPolicy(items[0]->childIndicatorPolicy()); item->setCheckState(0, items[0]->checkState(0)); - } else + } + else { return nullptr; + } items.push_back(item); - item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); return item; } -void DlgObjectSelection::onItemExpanded(QTreeWidgetItem *item) +void DlgObjectSelection::onItemExpanded(QTreeWidgetItem* item) { - if (item->childCount()) + if (item->childCount()) { return; + } if (auto obj = qvariant_cast(item->data(0, Qt::UserRole)).getObject()) { QSignalBlocker blocker(ui->treeWidget); std::set set; for (auto child : obj->getOutList()) { - if (child && set.insert(child).second) + if (child && set.insert(child).second) { getItem(child, nullptr, item); + } } } } @@ -239,14 +268,15 @@ void DlgObjectSelection::onItemExpanded(QTreeWidgetItem *item) void DlgObjectSelection::updateAllItemState() { int count = 0; - for (const auto &v : itemMap) { + for (const auto& v : itemMap) { auto state = v.second[0]->checkState(0); if (state == Qt::Unchecked) { if (count) { allItem->setCheckState(0, Qt::PartiallyChecked); return; } - } else { + } + else { if (state == Qt::PartiallyChecked) { allItem->setCheckState(0, Qt::PartiallyChecked); return; @@ -254,70 +284,82 @@ void DlgObjectSelection::updateAllItemState() ++count; } } - if (count && count == (int)itemMap.size()) + if (count && count == (int)itemMap.size()) { allItem->setCheckState(0, Qt::Checked); - else if (!count) + } + else if (!count) { allItem->setCheckState(0, Qt::Unchecked); + } } -void DlgObjectSelection::setItemState(App::DocumentObject *obj, - Qt::CheckState state, - bool forced) +void DlgObjectSelection::setItemState(App::DocumentObject* obj, Qt::CheckState state, bool forced) { - std::vector *items = nullptr; + std::vector* items = nullptr; auto item = getItem(obj, &items); - if (!setCheckState(item, state, forced)) + if (!setCheckState(item, state, forced)) { return; + } - for (size_t i=1; isize(); ++i) + for (size_t i = 1; i < items->size(); ++i) { setCheckState(items->at(i), state, true); + } std::vector objs = {obj}; if (ui->checkBoxAutoDeps->isChecked() && state == Qt::Checked) { // If an object is newly checked, check all its dependencies for (auto o : obj->getOutListRecursive()) { - if (!depSet.contains(o) || itemChanged.contains(o)) + if (!depSet.contains(o) || itemChanged.contains(o)) { continue; + } auto itItem = itemMap.find(o); - if (itItem == itemMap.end() || itItem->second[0]->checkState(0) == state) + if (itItem == itemMap.end() || itItem->second[0]->checkState(0) == state) { continue; + } - for (auto i : itItem->second) + for (auto i : itItem->second) { setCheckState(i, state, true); + } objs.push_back(o); } } - for(auto obj : objs) { + for (auto obj : objs) { auto it = inMap.find(obj); - if (it != inMap.end()) + if (it != inMap.end()) { setCheckState(it->second, state); + } auto itDep = depMap.find(obj); - if (itDep != depMap.end()) + if (itDep != depMap.end()) { setCheckState(itDep->second, state); + } // If an object toggles state, we need to revisit all its in-list // object to update the partial/full checked state. for (auto o : obj->getInList()) { - if (!depSet.contains(o) || itemChanged.contains(o)) + if (!depSet.contains(o) || itemChanged.contains(o)) { continue; + } auto it = itemMap.find(o); - if (it == itemMap.end() || it->second[0]->checkState(0) == state) + if (it == itemMap.end() || it->second[0]->checkState(0) == state) { continue; + } int count = 0; int selcount = 0; for (auto sibling : o->getOutList()) { - if (!depSet.contains(sibling)) + if (!depSet.contains(sibling)) { continue; + } ++count; auto it = itemMap.find(sibling); - if (it == itemMap.end()) + if (it == itemMap.end()) { continue; + } auto s = it->second[0]->checkState(0); - if (s == Qt::Unchecked) + if (s == Qt::Unchecked) { continue; + } if (it->second[0]->checkState(0) == Qt::PartiallyChecked) { selcount = -1; break; @@ -325,43 +367,54 @@ void DlgObjectSelection::setItemState(App::DocumentObject *obj, ++selcount; } auto state = it->second[0]->checkState(0); - if (state == Qt::Checked && selcount != count) + if (state == Qt::Checked && selcount != count) { setItemState(o, Qt::PartiallyChecked, true); - else if (state == Qt::PartiallyChecked && selcount == count) + } + else if (state == Qt::PartiallyChecked && selcount == count) { setItemState(o, Qt::Checked, true); + } } } } -std::vector DlgObjectSelection::getSelections(SelectionOptions options) const { +std::vector DlgObjectSelection::getSelections(SelectionOptions options) const +{ - if (returnOriginals) + if (returnOriginals) { return initSels; + } std::vector res; Base::Flags flags(options); if (!flags.testFlag(SelectionOptions::Invert)) { - for (const auto &v : itemMap) { - if (v.second[0]->checkState(0) == Qt::Unchecked) + for (const auto& v : itemMap) { + if (v.second[0]->checkState(0) == Qt::Unchecked) { continue; - if (auto obj = v.first.getObject()) - res.push_back(obj); - } - } else { - for (auto obj : deps) { - auto it = itemMap.find(obj); - if (it == itemMap.end() || it->second[0]->checkState(0) == Qt::Unchecked) + } + if (auto obj = v.first.getObject()) { res.push_back(obj); + } } } - if (flags.testFlag(SelectionOptions::Sort)) + else { + for (auto obj : deps) { + auto it = itemMap.find(obj); + if (it == itemMap.end() || it->second[0]->checkState(0) == Qt::Unchecked) { + res.push_back(obj); + } + } + } + if (flags.testFlag(SelectionOptions::Sort)) { std::sort(res.begin(), res.end()); + } return res; } -void DlgObjectSelection::onDepItemChanged(QTreeWidgetItem * depItem, int column) { - if(column) +void DlgObjectSelection::onDepItemChanged(QTreeWidgetItem* depItem, int column) +{ + if (column) { return; + } QSignalBlocker blocker(ui->depList); QSignalBlocker blocker2(ui->inList); QSignalBlocker blocker3(ui->treeWidget); @@ -371,60 +424,74 @@ void DlgObjectSelection::onDepItemChanged(QTreeWidgetItem * depItem, int column) for (auto item : items) { auto objT = qvariant_cast(item->data(0, Qt::UserRole)); auto it = itemMap.find(objT); - if (it == itemMap.end()) + if (it == itemMap.end()) { continue; + } setCheckState(item, state); - for (auto i : it->second) + for (auto i : it->second) { setCheckState(i, state); + } itemChanged[objT] = state; } - } else { + } + else { auto objT = qvariant_cast(depItem->data(0, Qt::UserRole)); auto it = itemMap.find(objT); if (it != itemMap.end()) { itemChanged[objT] = state; - for (auto i : it->second) + for (auto i : it->second) { setCheckState(i, state); + } } } timer.start(10); } -void DlgObjectSelection::onObjItemChanged(QTreeWidgetItem * objItem, int column) { - if(column != 0) +void DlgObjectSelection::onObjItemChanged(QTreeWidgetItem* objItem, int column) +{ + if (column != 0) { return; + } QSignalBlocker blocker3(ui->treeWidget); auto state = objItem->checkState(0); if (objItem == allItem) { - if (state == Qt::PartiallyChecked) + if (state == Qt::PartiallyChecked) { return; + } ui->treeWidget->selectionModel()->clearSelection(); itemChanged.clear(); timer.stop(); onItemSelectionChanged(); if (state == Qt::Unchecked) { - for (const auto &v : itemMap) { - for (auto i : v.second) + for (const auto& v : itemMap) { + for (auto i : v.second) { setCheckState(i, Qt::Unchecked); + } auto it = depMap.find(v.first); - if (it != depMap.end()) + if (it != depMap.end()) { setCheckState(it->second, Qt::Unchecked); + } it = inMap.find(v.first); - if (it != inMap.end()) + if (it != inMap.end()) { setCheckState(it->second, Qt::Unchecked); + } } - } else { - for (auto obj : initSels) + } + else { + for (auto obj : initSels) { setCheckState(getItem(obj), Qt::Checked); + } for (auto obj : deps) { setCheckState(getItem(obj), Qt::Checked); auto it = depMap.find(obj); - if (it != depMap.end()) + if (it != depMap.end()) { setCheckState(it->second, Qt::Checked); + } it = inMap.find(obj); - if (it != inMap.end()) + if (it != inMap.end()) { setCheckState(it->second, Qt::Checked); + } } } return; @@ -450,21 +517,26 @@ void DlgObjectSelection::onObjItemChanged(QTreeWidgetItem * objItem, int column) } -static bool getOutList(App::DocumentObject *obj, - std::set &visited, - std::vector &result) +static bool getOutList( + App::DocumentObject* obj, + std::set& visited, + std::vector& result +) { - if (!visited.insert(obj).second) + if (!visited.insert(obj).second) { return false; + } for (auto o : obj->getOutList()) { - if (getOutList(o, visited, result)) + if (getOutList(o, visited, result)) { result.push_back(o); + } } return true; } -void DlgObjectSelection::checkItemChanged() { +void DlgObjectSelection::checkItemChanged() +{ QSignalBlocker blocker(ui->depList); QSignalBlocker blocker2(ui->inList); @@ -472,15 +544,17 @@ void DlgObjectSelection::checkItemChanged() { std::set unchecked; - for (const auto &v : itemChanged) { - const auto &objT = v.first; + for (const auto& v : itemChanged) { + const auto& objT = v.first; Qt::CheckState state = v.second; if (auto obj = objT.getObject()) { if (state == Qt::Unchecked) { // We'll deal with unchecked item later - if (ui->checkBoxAutoDeps->isChecked()) + if (ui->checkBoxAutoDeps->isChecked()) { unchecked.insert(obj); - } else { + } + } + else { // For checked item, setItemState will auto select its // dependency setItemState(obj, state, true); @@ -494,25 +568,29 @@ void DlgObjectSelection::checkItemChanged() { // currently unchecked object. And then uncheck any item that does not // appear in the returned outlist. - for (const auto &v : itemMap) { + for (const auto& v : itemMap) { auto item = v.second[0]; if (item->checkState(0) == Qt::Unchecked) { - if (auto obj = qvariant_cast(item->data(0, Qt::UserRole)).getObject()) + if (auto obj = qvariant_cast(item->data(0, Qt::UserRole)).getObject()) { unchecked.insert(obj); + } } } auto outlist = initSels; - for (auto obj : initSels) + for (auto obj : initSels) { getOutList(obj, unchecked, outlist); + } std::sort(outlist.begin(), outlist.end()); - for (const auto &v : itemMap) { - if (!itemChanged.contains(v.first) && v.second[0]->checkState(0) == Qt::Unchecked) + for (const auto& v : itemMap) { + if (!itemChanged.contains(v.first) && v.second[0]->checkState(0) == Qt::Unchecked) { continue; + } if (auto obj = v.first.getObject()) { - if (!std::binary_search(outlist.begin(), outlist.end(), obj)) + if (!std::binary_search(outlist.begin(), outlist.end(), obj)) { setItemState(obj, Qt::Unchecked, true); + } } } } @@ -521,16 +599,20 @@ void DlgObjectSelection::checkItemChanged() { updateAllItemState(); } -QTreeWidgetItem *DlgObjectSelection::createDepItem(QTreeWidget *parent, App::DocumentObject *obj) +QTreeWidgetItem* DlgObjectSelection::createDepItem(QTreeWidget* parent, App::DocumentObject* obj) { auto item = new QTreeWidgetItem(parent); - if (parent == ui->depList) + if (parent == ui->depList) { depMap[obj] = item; - else + } + else { inMap[obj] = item; + } App::SubObjectT objT(obj); auto vp = Gui::Application::Instance->getViewProvider(obj); - if(vp) item->setIcon(0, vp->getIcon()); + if (vp) { + item->setIcon(0, vp->getIcon()); + } item->setData(0, Qt::UserRole, QVariant::fromValue(objT)); item->setToolTip(0, QString::fromUtf8(objT.getObjectFullName().c_str())); item->setText(0, QString::fromUtf8((obj)->Label.getValue())); @@ -542,20 +624,22 @@ QTreeWidgetItem *DlgObjectSelection::createDepItem(QTreeWidget *parent, App::Doc } item->setText(1, QString::fromUtf8(obj->getDocument()->getName())); item->setText(2, QString::fromUtf8(obj->getNameInDocument())); - item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); auto it = itemMap.find(obj); - if (it != itemMap.end()) + if (it != itemMap.end()) { setCheckState(item, it->second[0]->checkState(0)); + } return item; } -void DlgObjectSelection::onItemSelectionChanged() { +void DlgObjectSelection::onItemSelectionChanged() +{ ui->depList->clear(); depMap.clear(); ui->inList->clear(); inMap.clear(); - std::vector sels; + std::vector sels; const auto items = ui->treeWidget->selectedItems(); for (auto item : items) { if (item == allItem) { @@ -563,102 +647,123 @@ void DlgObjectSelection::onItemSelectionChanged() { break; } auto obj = qvariant_cast(item->data(0, Qt::UserRole)).getObject(); - if (obj) + if (obj) { sels.push_back(obj); + } } std::vector _deps; if (!sels.empty()) { std::sort(sels.begin(), sels.end()); for (auto dep : App::Document::getDependencyList(sels, App::Document::DepSort)) { - if (!std::binary_search(sels.begin(), sels.end(), dep)) + if (!std::binary_search(sels.begin(), sels.end(), dep)) { _deps.push_back(dep); + } } } bool enabled = ui->depList->isSortingEnabled(); - if (enabled) + if (enabled) { ui->depList->setSortingEnabled(false); + } bool enabled2 = ui->inList->isSortingEnabled(); - if (enabled2) + if (enabled2) { ui->inList->setSortingEnabled(false); + } { QSignalBlocker blocker(ui->depList); - auto &objs = !sels.empty() ? _deps : deps; - for (auto it = objs.rbegin(); it != objs.rend(); ++it) + auto& objs = !sels.empty() ? _deps : deps; + for (auto it = objs.rbegin(); it != objs.rend(); ++it) { createDepItem(ui->depList, *it); + } } std::set inlist; - for (auto obj : sels) + for (auto obj : sels) { obj->getInListEx(inlist, true); + } for (auto it = inlist.begin(); it != inlist.end();) { - if (!depSet.contains(*it) || std::binary_search(sels.begin(), sels.end(), *it)) + if (!depSet.contains(*it) || std::binary_search(sels.begin(), sels.end(), *it)) { it = inlist.erase(it); - else + } + else { ++it; + } } { QSignalBlocker blocker2(ui->inList); - for (auto obj : inlist) + for (auto obj : inlist) { createDepItem(ui->inList, obj); + } } - if (enabled) + if (enabled) { ui->depList->setSortingEnabled(true); - if (enabled2) + } + if (enabled2) { ui->inList->setSortingEnabled(true); + } } -void DlgObjectSelection::onUseOriginalsBtnClicked() { +void DlgObjectSelection::onUseOriginalsBtnClicked() +{ returnOriginals = true; QDialog::accept(); } -void DlgObjectSelection::accept() { +void DlgObjectSelection::accept() +{ QDialog::accept(); } -void DlgObjectSelection::reject() { +void DlgObjectSelection::reject() +{ QDialog::reject(); } -void DlgObjectSelection::addCheckBox(QCheckBox *box) { +void DlgObjectSelection::addCheckBox(QCheckBox* box) +{ ui->horizontalLayout->insertWidget(0, box); } -void DlgObjectSelection::setMessage(const QString &msg) { +void DlgObjectSelection::setMessage(const QString& msg) +{ ui->label->setText(msg); } void DlgObjectSelection::onAutoDeps(bool checked) { hGrp->SetBool("ObjectSelectionAutoDeps", checked); - if (!checked) + if (!checked) { return; + } QSignalBlocker blocker(ui->treeWidget); for (auto obj : deps) { auto it = itemMap.find(obj); - if (it == itemMap.end()) + if (it == itemMap.end()) { continue; + } auto item = it->second[0]; - if (item->checkState(0) == Qt::Unchecked) + if (item->checkState(0) == Qt::Unchecked) { continue; + } Qt::CheckState state = Qt::Checked; for (auto o : obj->getOutList()) { auto it = itemMap.find(o); - if (it == itemMap.end()) + if (it == itemMap.end()) { continue; + } if (it->second[0]->checkState(0) != Qt::Checked) { state = Qt::PartiallyChecked; break; } } - for (auto i : it->second) + for (auto i : it->second) { setCheckState(i, state); + } } onItemSelectionChanged(); } @@ -667,12 +772,15 @@ void DlgObjectSelection::onShowDeps() { bool checked = ui->checkBoxShowDeps->isChecked(); auto sizes = ui->vsplitter->sizes(); - if (!checked && sizes[1] > 0) + if (!checked && sizes[1] > 0) { sizes[1] = 0; - else if (checked && (sizes[0] == 0 || sizes[1] == 0)) - sizes[0] = sizes[1] = this->width()/2; - else + } + else if (checked && (sizes[0] == 0 || sizes[1] == 0)) { + sizes[0] = sizes[1] = this->width() / 2; + } + else { return; + } ui->vsplitter->setSizes(sizes); } diff --git a/src/Gui/Dialogs/DlgObjectSelection.h b/src/Gui/Dialogs/DlgObjectSelection.h index fb1abf136a..f993a29dbd 100644 --- a/src/Gui/Dialogs/DlgObjectSelection.h +++ b/src/Gui/Dialogs/DlgObjectSelection.h @@ -32,13 +32,14 @@ class QCheckBox; class QTreeWidgetItem; class QTreeWidget; -namespace Gui { +namespace Gui +{ class Ui_DlgObjectSelection; /** Dialog for object dependency selection */ -class GuiExport DlgObjectSelection : public QDialog +class GuiExport DlgObjectSelection: public QDialog { Q_OBJECT @@ -52,8 +53,11 @@ public: * @param parent: optional parent widget * @param fl: optional window flags */ - DlgObjectSelection(const std::vector &objs, - QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + DlgObjectSelection( + const std::vector& objs, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); /** Constructor * @@ -66,15 +70,19 @@ public: * @param parent: optional parent widget * @param fl: optional window flags */ - DlgObjectSelection(const std::vector &objs, - const std::vector &excludes, - QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + DlgObjectSelection( + const std::vector& objs, + const std::vector& excludes, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); /// Destructor ~DlgObjectSelection() override; /// Options for getSelections() - enum class SelectionOptions { + enum class SelectionOptions + { /// Invert the selection, i.e. return the unselected objects Invert = 1, /// Sort the returned object in depending order @@ -86,35 +94,39 @@ public: std::vector getSelections(SelectionOptions options = SelectionOptions()) const; /// Add a user defined checkbox at the bottom of the dialog - void addCheckBox(QCheckBox *box); + void addCheckBox(QCheckBox* box); /// Override the prompt message - void setMessage(const QString &); + void setMessage(const QString&); void accept() override; void reject() override; private Q_SLOTS: - void onDepItemChanged(QTreeWidgetItem * item, int); - void onObjItemChanged(QTreeWidgetItem * item, int); + void onDepItemChanged(QTreeWidgetItem* item, int); + void onObjItemChanged(QTreeWidgetItem* item, int); void onItemSelectionChanged(); void checkItemChanged(); void onAutoDeps(bool); - void onItemExpanded(QTreeWidgetItem *item); + void onItemExpanded(QTreeWidgetItem* item); void onUseOriginalsBtnClicked(); void onShowDeps(); private: - QTreeWidgetItem *getItem(App::DocumentObject *obj, - std::vector **items = nullptr, - QTreeWidgetItem *parent = nullptr); + QTreeWidgetItem* getItem( + App::DocumentObject* obj, + std::vector** items = nullptr, + QTreeWidgetItem* parent = nullptr + ); - QTreeWidgetItem *createDepItem(QTreeWidget *parent, App::DocumentObject *obj); + QTreeWidgetItem* createDepItem(QTreeWidget* parent, App::DocumentObject* obj); - void init(const std::vector &objs, - const std::vector &excludes); + void init( + const std::vector& objs, + const std::vector& excludes + ); - void setItemState(App::DocumentObject *obj, Qt::CheckState state, bool forced = false); + void setItemState(App::DocumentObject* obj, Qt::CheckState state, bool forced = false); void updateAllItemState(); private: @@ -126,7 +138,7 @@ private: std::map depMap; std::map inMap; std::map itemChanged; - QTreeWidgetItem *allItem = nullptr; + QTreeWidgetItem* allItem = nullptr; QPushButton* useOriginalsBtn; bool returnOriginals = false; @@ -135,9 +147,8 @@ private: ParameterGrp::handle hGrp; }; -} // namespace Gui +} // namespace Gui ENABLE_BITMASK_OPERATORS(Gui::DlgObjectSelection::SelectionOptions); -#endif // GUI_DLGOBJECTSELECTION_H - +#endif // GUI_DLGOBJECTSELECTION_H diff --git a/src/Gui/Dialogs/DlgOnlineHelpImp.cpp b/src/Gui/Dialogs/DlgOnlineHelpImp.cpp index 562ed0076a..3c9f239d6c 100644 --- a/src/Gui/Dialogs/DlgOnlineHelpImp.cpp +++ b/src/Gui/Dialogs/DlgOnlineHelpImp.cpp @@ -20,8 +20,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -40,9 +40,9 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgOnlineHelpImp::DlgOnlineHelpImp( QWidget* parent ) - : PreferencePage(parent) - , ui(new Ui_DlgOnlineHelp) +DlgOnlineHelpImp::DlgOnlineHelpImp(QWidget* parent) + : PreferencePage(parent) + , ui(new Ui_DlgOnlineHelp) { ui->setupUi(this); @@ -58,8 +58,8 @@ DlgOnlineHelpImp::DlgOnlineHelpImp( QWidget* parent ) DlgOnlineHelpImp::~DlgOnlineHelpImp() = default; /** - * Returns the start page for the HelpView. If none is defined the default - * start page "/doc/free-cad.sourceforge.net/wiki/index.php.html" + * Returns the start page for the HelpView. If none is defined the default + * start page "/doc/free-cad.sourceforge.net/wiki/index.php.html" * is returned. * \remark It is not checked if the returned page really exists. */ @@ -82,7 +82,7 @@ void DlgOnlineHelpImp::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void DlgOnlineHelpImp::changeEvent(QEvent *e) +void DlgOnlineHelpImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -92,12 +92,17 @@ void DlgOnlineHelpImp::changeEvent(QEvent *e) } } -void DlgOnlineHelpImp::onLineEditDownloadFileNameSelected( const QString& url ) +void DlgOnlineHelpImp::onLineEditDownloadFileNameSelected(const QString& url) { QDir dir(url); if (dir.exists() && dir.isEmpty()) { - QMessageBox::critical(this, tr("Access denied"), tr("Access denied to '%1'\n\n" - "Specify another directory.").arg(url)); + QMessageBox::critical( + this, + tr("Access denied"), + tr("Access denied to '%1'\n\n" + "Specify another directory.") + .arg(url) + ); } } diff --git a/src/Gui/Dialogs/DlgOnlineHelpImp.h b/src/Gui/Dialogs/DlgOnlineHelpImp.h index b57b6cc53d..7ec774c5db 100644 --- a/src/Gui/Dialogs/DlgOnlineHelpImp.h +++ b/src/Gui/Dialogs/DlgOnlineHelpImp.h @@ -27,8 +27,10 @@ #include "PropertyPage.h" #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgOnlineHelp; /** This class implements the dialog for downloading the online documentation. @@ -36,12 +38,12 @@ class Ui_DlgOnlineHelp; * Here you can specify to use a proxy if necessary and some more stuff. * \author Werner Mayer */ -class DlgOnlineHelpImp : public PreferencePage +class DlgOnlineHelpImp: public PreferencePage { Q_OBJECT public: - DlgOnlineHelpImp( QWidget* parent = nullptr ); + DlgOnlineHelpImp(QWidget* parent = nullptr); ~DlgOnlineHelpImp() override; static QString getStartpage(); @@ -50,7 +52,7 @@ public: void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; protected: void onLineEditDownloadFileNameSelected(const QString&); @@ -59,7 +61,7 @@ private: std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif //GUI_DIALOG_DLGONLINEHELP_IMP_H +#endif // GUI_DIALOG_DLGONLINEHELP_IMP_H diff --git a/src/Gui/Dialogs/DlgParameterFind.cpp b/src/Gui/Dialogs/DlgParameterFind.cpp index 5c2bb967b8..4f7464d3c9 100644 --- a/src/Gui/Dialogs/DlgParameterFind.cpp +++ b/src/Gui/Dialogs/DlgParameterFind.cpp @@ -303,9 +303,7 @@ void DlgParameterFind::accept() groupTree->setCurrentItem(next); } else { - QMessageBox::warning(this, - tr("Not found"), - tr("Cannot find the text: %1").arg(opt.text)); + QMessageBox::warning(this, tr("Not found"), tr("Cannot find the text: %1").arg(opt.text)); } } } diff --git a/src/Gui/Dialogs/DlgParameterFind.h b/src/Gui/Dialogs/DlgParameterFind.h index f192c10027..c5bb15ba4e 100644 --- a/src/Gui/Dialogs/DlgParameterFind.h +++ b/src/Gui/Dialogs/DlgParameterFind.h @@ -29,13 +29,15 @@ class QTreeWidgetItem; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgParameterFind; class DlgParameterImp; -class GuiExport DlgParameterFind : public QDialog +class GuiExport DlgParameterFind: public QDialog { Q_OBJECT @@ -54,7 +56,8 @@ private: void onCheckValuesToggled(bool); private: - struct Options { + struct Options + { QString text; bool group = true; bool name = true; @@ -69,7 +72,7 @@ private: DlgParameterImp* dialog; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGPARAMETERFIND_H +#endif // GUI_DIALOG_DLGPARAMETERFIND_H diff --git a/src/Gui/Dialogs/DlgParameterImp.cpp b/src/Gui/Dialogs/DlgParameterImp.cpp index 8308a16aa4..95f9f2d417 100644 --- a/src/Gui/Dialogs/DlgParameterImp.cpp +++ b/src/Gui/Dialogs/DlgParameterImp.cpp @@ -107,10 +107,12 @@ DlgParameterImp::DlgParameterImp(QWidget* parent, Qt::WindowFlags fl) ui->parameterSet->hide(); } - connect(ui->parameterSet, - qOverload(&QComboBox::activated), - this, - &DlgParameterImp::onChangeParameterSet); + connect( + ui->parameterSet, + qOverload(&QComboBox::activated), + this, + &DlgParameterImp::onChangeParameterSet + ); connect(paramGroup, &QTreeWidget::currentItemChanged, this, &DlgParameterImp::onGroupSelected); onGroupSelected(paramGroup->currentItem()); @@ -223,9 +225,11 @@ void DlgParameterImp::onFindGroupTtextChanged(const QString& SearchStr) } else { // Set red background to indicate no matching - QString styleSheet = QStringLiteral(" QLineEdit {\n" - " background-color: rgb(221,144,161);\n" - " }\n"); + QString styleSheet = QStringLiteral( + " QLineEdit {\n" + " background-color: rgb(221,144,161);\n" + " }\n" + ); ui->findGroupLE->setStyleSheet(styleSheet); } } @@ -276,8 +280,8 @@ void DlgParameterImp::reject() void DlgParameterImp::showEvent(QShowEvent*) { - ParameterGrp::handle hGrp = - App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); + ParameterGrp::handle hGrp + = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); hGrp = hGrp->GetGroup("ParameterEditor"); std::string buf = hGrp->GetASCII("Geometry", ""); if (!buf.empty()) { @@ -293,8 +297,8 @@ void DlgParameterImp::showEvent(QShowEvent*) void DlgParameterImp::closeEvent(QCloseEvent*) { - ParameterGrp::handle hGrp = - App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); + ParameterGrp::handle hGrp + = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); hGrp = hGrp->GetGroup("ParameterEditor"); QTreeWidgetItem* current = paramGroup->currentItem(); if (current) { @@ -327,46 +331,44 @@ void DlgParameterImp::onGroupSelected(QTreeWidgetItem* item) // filling up Text nodes std::vector> mcTextMap = _hcGrp->GetASCIIMap(); for (const auto& It2 : mcTextMap) { - (void)new ParameterText(paramValue, - QString::fromUtf8(It2.first.c_str()), - It2.second.c_str(), - _hcGrp); + (void)new ParameterText( + paramValue, + QString::fromUtf8(It2.first.c_str()), + It2.second.c_str(), + _hcGrp + ); } // filling up Int nodes std::vector> mcIntMap = _hcGrp->GetIntMap(); for (const auto& It3 : mcIntMap) { - (void)new ParameterInt(paramValue, - QString::fromUtf8(It3.first.c_str()), - It3.second, - _hcGrp); + ( + void + )new ParameterInt(paramValue, QString::fromUtf8(It3.first.c_str()), It3.second, _hcGrp); } // filling up Float nodes std::vector> mcFloatMap = _hcGrp->GetFloatMap(); for (const auto& It4 : mcFloatMap) { - (void)new ParameterFloat(paramValue, - QString::fromUtf8(It4.first.c_str()), - It4.second, - _hcGrp); + ( + void + )new ParameterFloat(paramValue, QString::fromUtf8(It4.first.c_str()), It4.second, _hcGrp); } // filling up bool nodes std::vector> mcBoolMap = _hcGrp->GetBoolMap(); for (const auto& It5 : mcBoolMap) { - (void)new ParameterBool(paramValue, - QString::fromUtf8(It5.first.c_str()), - It5.second, - _hcGrp); + ( + void + )new ParameterBool(paramValue, QString::fromUtf8(It5.first.c_str()), It5.second, _hcGrp); } // filling up UInt nodes std::vector> mcUIntMap = _hcGrp->GetUnsignedMap(); for (const auto& It6 : mcUIntMap) { - (void)new ParameterUInt(paramValue, - QString::fromUtf8(It6.first.c_str()), - It6.second, - _hcGrp); + ( + void + )new ParameterUInt(paramValue, QString::fromUtf8(It6.first.c_str()), It6.second, _hcGrp); } paramValue->setSortingEnabled(sortingEnabled); } @@ -385,8 +387,9 @@ void DlgParameterImp::activateParameterSet(const char* config) /** Switches the type of parameters either to user or system parameters. */ void DlgParameterImp::onChangeParameterSet(int itemPos) { - ParameterManager* rcParMngr = - App::GetApplication().GetParameterSet(ui->parameterSet->itemData(itemPos).toByteArray()); + ParameterManager* rcParMngr = App::GetApplication().GetParameterSet( + ui->parameterSet->itemData(itemPos).toByteArray() + ); if (!rcParMngr) { return; } @@ -407,8 +410,8 @@ void DlgParameterImp::onChangeParameterSet(int itemPos) } // get the path of the last selected group in the editor - ParameterGrp::handle hGrp = - App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); + ParameterGrp::handle hGrp + = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); hGrp = hGrp->GetGroup("ParameterEditor"); QString path = QString::fromUtf8(hGrp->GetASCII("LastParameterGroup").c_str()); QStringList paths = path.split(QLatin1String("."), Qt::SkipEmptyParts); @@ -447,8 +450,9 @@ void DlgParameterImp::onChangeParameterSet(int itemPos) void DlgParameterImp::onButtonSaveToDiskClicked() { int index = ui->parameterSet->currentIndex(); - ParameterManager* parmgr = - App::GetApplication().GetParameterSet(ui->parameterSet->itemData(index).toByteArray()); + ParameterManager* parmgr = App::GetApplication().GetParameterSet( + ui->parameterSet->itemData(index).toByteArray() + ); if (!parmgr) { return; } @@ -469,9 +473,11 @@ bool validateInput(QWidget* parent, const QString& input) (c < 'A' || c > 'Z') && // Uppercase letters (c < 'a' || c > 'z') && // Lowercase letters (c != ' ')) { // Space - QMessageBox::warning(parent, - DlgParameterImp::tr("Invalid input"), - DlgParameterImp::tr("Invalid key name '%1'").arg(input)); + QMessageBox::warning( + parent, + DlgParameterImp::tr("Invalid input"), + DlgParameterImp::tr("Invalid key name '%1'").arg(input) + ); return false; } } @@ -490,14 +496,11 @@ ParameterGroup::ParameterGroup(QWidget* parent) expandAct = menuEdit->addAction(tr("Expand"), this, &ParameterGroup::onToggleSelectedItem); menuEdit->addSeparator(); subGrpAct = menuEdit->addAction(tr("Add Sub-Group"), this, &ParameterGroup::onCreateSubgroup); - removeAct = - menuEdit->addAction(tr("Remove Group"), this, &ParameterGroup::onDeleteSelectedItem); - renameAct = - menuEdit->addAction(tr("Rename Group"), this, &ParameterGroup::onRenameSelectedItem); + removeAct = menuEdit->addAction(tr("Remove Group"), this, &ParameterGroup::onDeleteSelectedItem); + renameAct = menuEdit->addAction(tr("Rename Group"), this, &ParameterGroup::onRenameSelectedItem); menuEdit->addSeparator(); exportAct = menuEdit->addAction(tr("Export Parameter"), this, &ParameterGroup::onExportToFile); - importAct = - menuEdit->addAction(tr("Import Parameter"), this, &ParameterGroup::onImportFromFile); + importAct = menuEdit->addAction(tr("Import Parameter"), this, &ParameterGroup::onImportFromFile); menuEdit->setDefaultAction(expandAct); } @@ -535,11 +538,13 @@ void ParameterGroup::onDeleteSelectedItem() { QTreeWidgetItem* sel = currentItem(); if (sel && sel->isSelected() && sel->parent()) { - if (QMessageBox::question(this, - tr("Remove group"), - tr("Remove this parameter group?"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) + if (QMessageBox::question( + this, + tr("Remove group"), + tr("Remove this parameter group?"), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::No + ) == QMessageBox::Yes) { QTreeWidgetItem* parent = sel->parent(); int index = parent->indexOfChild(sel); @@ -572,13 +577,15 @@ void ParameterGroup::onToggleSelectedItem() void ParameterGroup::onCreateSubgroup() { bool ok; - QString name = QInputDialog::getText(this, - QObject::tr("New sub-group"), - QObject::tr("Enter the name:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText( + this, + QObject::tr("New sub-group"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok && Gui::validateInput(this, name)) { QTreeWidgetItem* item = currentItem(); @@ -587,9 +594,11 @@ void ParameterGroup::onCreateSubgroup() Base::Reference hGrp = para->_hcGrp; if (hGrp->HasGroup(name.toLatin1())) { - QMessageBox::critical(this, - tr("Existing sub-group"), - tr("The sub-group '%1' already exists.").arg(name)); + QMessageBox::critical( + this, + tr("Existing sub-group"), + tr("The sub-group '%1' already exists.").arg(name) + ); return; } @@ -602,10 +611,12 @@ void ParameterGroup::onCreateSubgroup() void ParameterGroup::onExportToFile() { - QString file = FileDialog::getSaveFileName(this, - tr("Export parameter to file"), - QString(), - QStringLiteral("XML (*.FCParam)")); + QString file = FileDialog::getSaveFileName( + this, + tr("Export parameter to file"), + QString(), + QStringLiteral("XML (*.FCParam)") + ); if (!file.isEmpty()) { QTreeWidgetItem* item = currentItem(); if (item && item->isSelected()) { @@ -618,10 +629,12 @@ void ParameterGroup::onExportToFile() void ParameterGroup::onImportFromFile() { - QString file = FileDialog::getOpenFileName(this, - tr("Import parameter from file"), - QString(), - QStringLiteral("XML (*.FCParam)")); + QString file = FileDialog::getOpenFileName( + this, + tr("Import parameter from file"), + QString(), + QStringLiteral("XML (*.FCParam)") + ); if (!file.isEmpty()) { QTreeWidgetItem* item = currentItem(); if (item && item->isSelected()) { @@ -644,9 +657,11 @@ void ParameterGroup::onImportFromFile() para->setExpanded(para->childCount()); } catch (const Base::Exception&) { - QMessageBox::critical(this, - tr("Import error"), - tr("Reading from '%1' failed.").arg(file)); + QMessageBox::critical( + this, + tr("Import error"), + tr("Reading from '%1' failed.").arg(file) + ); } } } @@ -683,9 +698,11 @@ ParameterValue::ParameterValue(QWidget* parent) : QTreeWidget(parent) { menuEdit = new QMenu(this); - changeAct = menuEdit->addAction(tr("Change Value"), - this, - qOverload<>(&ParameterValue::onChangeSelectedItem)); + changeAct = menuEdit->addAction( + tr("Change Value"), + this, + qOverload<>(&ParameterValue::onChangeSelectedItem) + ); menuEdit->addSeparator(); removeAct = menuEdit->addAction(tr("Remove Key"), this, &ParameterValue::onDeleteSelectedItem); renameAct = menuEdit->addAction(tr("Rename Key"), this, &ParameterValue::onRenameSelectedItem); @@ -696,14 +713,15 @@ ParameterValue::ParameterValue(QWidget* parent) newStrAct = menuNew->addAction(tr("New String Item"), this, &ParameterValue::onCreateTextItem); newFltAct = menuNew->addAction(tr("New Float Item"), this, &ParameterValue::onCreateFloatItem); newIntAct = menuNew->addAction(tr("New Integer Item"), this, &ParameterValue::onCreateIntItem); - newUlgAct = - menuNew->addAction(tr("New Unsigned Item"), this, &ParameterValue::onCreateUIntItem); + newUlgAct = menuNew->addAction(tr("New Unsigned Item"), this, &ParameterValue::onCreateUIntItem); newBlnAct = menuNew->addAction(tr("New Boolean Item"), this, &ParameterValue::onCreateBoolItem); - connect(this, - &ParameterValue::itemDoubleClicked, - this, - qOverload(&ParameterValue::onChangeSelectedItem)); + connect( + this, + &ParameterValue::itemDoubleClicked, + this, + qOverload(&ParameterValue::onChangeSelectedItem) + ); } ParameterValue::~ParameterValue() = default; @@ -795,13 +813,15 @@ void ParameterValue::onRenameSelectedItem() void ParameterValue::onCreateTextItem() { bool ok; - QString name = QInputDialog::getText(this, - QObject::tr("New text item"), - QObject::tr("Enter the name:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText( + this, + QObject::tr("New text item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok || !Gui::validateInput(this, name)) { return; @@ -810,20 +830,24 @@ void ParameterValue::onCreateTextItem() std::vector> smap = _hcGrp->GetASCIIMap(); for (const auto& it : smap) { if (name == QLatin1String(it.first.c_str())) { - QMessageBox::critical(this, - tr("Existing item"), - tr("The item '%1' already exists.").arg(name)); + QMessageBox::critical( + this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name) + ); return; } } - QString val = QInputDialog::getText(this, - QObject::tr("New text item"), - QObject::tr("Enter text:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString val = QInputDialog::getText( + this, + QObject::tr("New text item"), + QObject::tr("Enter text:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok && !val.isEmpty()) { ParameterValueItem* pcItem; pcItem = new ParameterText(this, name, val.toUtf8(), _hcGrp); @@ -834,13 +858,15 @@ void ParameterValue::onCreateTextItem() void ParameterValue::onCreateIntItem() { bool ok; - QString name = QInputDialog::getText(this, - QObject::tr("New integer item"), - QObject::tr("Enter the name:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText( + this, + QObject::tr("New integer item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok || !Gui::validateInput(this, name)) { return; @@ -849,22 +875,26 @@ void ParameterValue::onCreateIntItem() std::vector> lmap = _hcGrp->GetIntMap(); for (const auto& it : lmap) { if (name == QLatin1String(it.first.c_str())) { - QMessageBox::critical(this, - tr("Existing item"), - tr("The item '%1' already exists.").arg(name)); + QMessageBox::critical( + this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name) + ); return; } } - int val = QInputDialog::getInt(this, - QObject::tr("New integer item"), - QObject::tr("Enter number:"), - 0, - -2147483647, - 2147483647, - 1, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + int val = QInputDialog::getInt( + this, + QObject::tr("New integer item"), + QObject::tr("Enter number:"), + 0, + -2147483647, + 2147483647, + 1, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { ParameterValueItem* pcItem; @@ -876,13 +906,15 @@ void ParameterValue::onCreateIntItem() void ParameterValue::onCreateUIntItem() { bool ok; - QString name = QInputDialog::getText(this, - QObject::tr("New unsigned item"), - QObject::tr("Enter the name:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText( + this, + QObject::tr("New unsigned item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok || !Gui::validateInput(this, name)) { return; @@ -891,17 +923,16 @@ void ParameterValue::onCreateUIntItem() std::vector> lmap = _hcGrp->GetUnsignedMap(); for (const auto& it : lmap) { if (name == QLatin1String(it.first.c_str())) { - QMessageBox::critical(this, - tr("Existing item"), - tr("The item '%1' already exists.").arg(name)); + QMessageBox::critical( + this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name) + ); return; } } - DlgInputDialogImp dlg(QObject::tr("Enter number:"), - this, - true, - DlgInputDialogImp::UIntBox); + DlgInputDialogImp dlg(QObject::tr("Enter number:"), this, true, DlgInputDialogImp::UIntBox); dlg.setWindowTitle(QObject::tr("New Unsigned Item")); UIntSpinBox* edit = dlg.getUIntBox(); edit->setRange(0, std::numeric_limits::max()); @@ -920,13 +951,15 @@ void ParameterValue::onCreateUIntItem() void ParameterValue::onCreateFloatItem() { bool ok; - QString name = QInputDialog::getText(this, - QObject::tr("New float item"), - QObject::tr("Enter the name:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText( + this, + QObject::tr("New float item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok || !Gui::validateInput(this, name)) { return; @@ -935,22 +968,26 @@ void ParameterValue::onCreateFloatItem() std::vector> fmap = _hcGrp->GetFloatMap(); for (const auto& it : fmap) { if (name == QLatin1String(it.first.c_str())) { - QMessageBox::critical(this, - tr("Existing item"), - tr("The item '%1' already exists.").arg(name)); + QMessageBox::critical( + this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name) + ); return; } } - double val = QInputDialog::getDouble(this, - QObject::tr("New float item"), - QObject::tr("Enter number:"), - 0, - -2147483647, - 2147483647, - 12, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + double val = QInputDialog::getDouble( + this, + QObject::tr("New float item"), + QObject::tr("Enter number:"), + 0, + -2147483647, + 2147483647, + 12, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { ParameterValueItem* pcItem; pcItem = new ParameterFloat(this, name, val, _hcGrp); @@ -961,13 +998,15 @@ void ParameterValue::onCreateFloatItem() void ParameterValue::onCreateBoolItem() { bool ok; - QString name = QInputDialog::getText(this, - QObject::tr("New boolean item"), - QObject::tr("Enter the name:"), - QLineEdit::Normal, - QString(), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString name = QInputDialog::getText( + this, + QObject::tr("New boolean item"), + QObject::tr("Enter the name:"), + QLineEdit::Normal, + QString(), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok || !Gui::validateInput(this, name)) { return; @@ -976,23 +1015,27 @@ void ParameterValue::onCreateBoolItem() std::vector> bmap = _hcGrp->GetBoolMap(); for (const auto& it : bmap) { if (name == QLatin1String(it.first.c_str())) { - QMessageBox::critical(this, - tr("Existing item"), - tr("The item '%1' already exists.").arg(name)); + QMessageBox::critical( + this, + tr("Existing item"), + tr("The item '%1' already exists.").arg(name) + ); return; } } QStringList list; list << QStringLiteral("true") << QStringLiteral("false"); - QString val = QInputDialog::getItem(this, - QObject::tr("New boolean item"), - QObject::tr("Choose an item:"), - list, - 0, - false, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString val = QInputDialog::getItem( + this, + QObject::tr("New boolean item"), + QObject::tr("Choose an item:"), + list, + 0, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { ParameterValueItem* pcItem; pcItem = new ParameterBool(this, name, (val == list[0] ? true : false), _hcGrp); @@ -1002,8 +1045,10 @@ void ParameterValue::onCreateBoolItem() // --------------------------------------------------------------------------- -ParameterGroupItem::ParameterGroupItem(ParameterGroupItem* parent, - const Base::Reference& hcGrp) +ParameterGroupItem::ParameterGroupItem( + ParameterGroupItem* parent, + const Base::Reference& hcGrp +) : QTreeWidgetItem(parent, QTreeWidgetItem::UserType + 1) , _hcGrp(hcGrp) { @@ -1011,8 +1056,7 @@ ParameterGroupItem::ParameterGroupItem(ParameterGroupItem* parent, fillUp(); } -ParameterGroupItem::ParameterGroupItem(QTreeWidget* parent, - const Base::Reference& hcGrp) +ParameterGroupItem::ParameterGroupItem(QTreeWidget* parent, const Base::Reference& hcGrp) : QTreeWidgetItem(parent, QTreeWidgetItem::UserType + 1) , _hcGrp(hcGrp) { @@ -1056,15 +1100,19 @@ void ParameterGroupItem::setData(int column, int role, const QVariant& value) // first check if there is already a group with name "newName" auto item = static_cast(parent()); if (!item) { - QMessageBox::critical(treeWidget(), - QObject::tr("Rename group"), - QObject::tr("The group '%1' cannot be renamed.").arg(oldName)); + QMessageBox::critical( + treeWidget(), + QObject::tr("Rename group"), + QObject::tr("The group '%1' cannot be renamed.").arg(oldName) + ); return; } if (item->_hcGrp->HasGroup(newName.toLatin1())) { - QMessageBox::critical(treeWidget(), - QObject::tr("Existing group"), - QObject::tr("The group '%1' already exists.").arg(newName)); + QMessageBox::critical( + treeWidget(), + QObject::tr("Existing group"), + QObject::tr("The group '%1' already exists.").arg(newName) + ); return; } else { @@ -1094,8 +1142,7 @@ QVariant ParameterGroupItem::data(int column, int role) const // -------------------------------------------------------------------- -ParameterValueItem::ParameterValueItem(QTreeWidget* parent, - const Base::Reference& hcGrp) +ParameterValueItem::ParameterValueItem(QTreeWidget* parent, const Base::Reference& hcGrp) : QTreeWidgetItem(parent) , _hcGrp(hcGrp) { @@ -1125,10 +1172,12 @@ void ParameterValueItem::setData(int column, int role, const QVariant& value) // -------------------------------------------------------------------- -ParameterText::ParameterText(QTreeWidget* parent, - QString label, - const char* value, - const Base::Reference& hcGrp) +ParameterText::ParameterText( + QTreeWidget* parent, + QString label, + const char* value, + const Base::Reference& hcGrp +) : ParameterValueItem(parent, hcGrp) { setIcon(0, BitmapFactory().iconFromTheme("Param_Text")); @@ -1142,13 +1191,15 @@ ParameterText::~ParameterText() = default; void ParameterText::changeValue() { bool ok; - QString txt = QInputDialog::getText(treeWidget(), - QObject::tr("Change value"), - QObject::tr("Enter text:"), - QLineEdit::Normal, - text(2), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString txt = QInputDialog::getText( + treeWidget(), + QObject::tr("Change value"), + QObject::tr("Enter text:"), + QLineEdit::Normal, + text(2), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { setText(2, txt); _hcGrp->SetASCII(text(0).toLatin1(), txt.toUtf8()); @@ -1174,10 +1225,12 @@ void ParameterText::appendToGroup() // -------------------------------------------------------------------- -ParameterInt::ParameterInt(QTreeWidget* parent, - QString label, - long value, - const Base::Reference& hcGrp) +ParameterInt::ParameterInt( + QTreeWidget* parent, + QString label, + long value, + const Base::Reference& hcGrp +) : ParameterValueItem(parent, hcGrp) { setIcon(0, BitmapFactory().iconFromTheme("Param_Int")); @@ -1191,15 +1244,17 @@ ParameterInt::~ParameterInt() = default; void ParameterInt::changeValue() { bool ok; - int num = QInputDialog::getInt(treeWidget(), - QObject::tr("Change value"), - QObject::tr("Enter number:"), - text(2).toInt(), - -2147483647, - 2147483647, - 1, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + int num = QInputDialog::getInt( + treeWidget(), + QObject::tr("Change value"), + QObject::tr("Enter number:"), + text(2).toInt(), + -2147483647, + 2147483647, + 1, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { setText(2, QStringLiteral("%1").arg(num)); _hcGrp->SetInt(text(0).toLatin1(), (long)num); @@ -1225,10 +1280,12 @@ void ParameterInt::appendToGroup() // -------------------------------------------------------------------- -ParameterUInt::ParameterUInt(QTreeWidget* parent, - QString label, - unsigned long value, - const Base::Reference& hcGrp) +ParameterUInt::ParameterUInt( + QTreeWidget* parent, + QString label, + unsigned long value, + const Base::Reference& hcGrp +) : ParameterValueItem(parent, hcGrp) { setIcon(0, BitmapFactory().iconFromTheme("Param_UInt")); @@ -1242,10 +1299,7 @@ ParameterUInt::~ParameterUInt() = default; void ParameterUInt::changeValue() { bool ok; - DlgInputDialogImp dlg(QObject::tr("Enter number:"), - treeWidget(), - true, - DlgInputDialogImp::UIntBox); + DlgInputDialogImp dlg(QObject::tr("Enter number:"), treeWidget(), true, DlgInputDialogImp::UIntBox); dlg.setWindowTitle(QObject::tr("Change Value")); UIntSpinBox* edit = dlg.getUIntBox(); edit->setRange(0, std::numeric_limits::max()); @@ -1280,10 +1334,12 @@ void ParameterUInt::appendToGroup() // -------------------------------------------------------------------- -ParameterFloat::ParameterFloat(QTreeWidget* parent, - QString label, - double value, - const Base::Reference& hcGrp) +ParameterFloat::ParameterFloat( + QTreeWidget* parent, + QString label, + double value, + const Base::Reference& hcGrp +) : ParameterValueItem(parent, hcGrp) { setIcon(0, BitmapFactory().iconFromTheme("Param_Float")); @@ -1297,15 +1353,17 @@ ParameterFloat::~ParameterFloat() = default; void ParameterFloat::changeValue() { bool ok; - double num = QInputDialog::getDouble(treeWidget(), - QObject::tr("Change value"), - QObject::tr("Enter number:"), - text(2).toDouble(), - -2147483647, - 2147483647, - 12, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + double num = QInputDialog::getDouble( + treeWidget(), + QObject::tr("Change value"), + QObject::tr("Enter number:"), + text(2).toDouble(), + -2147483647, + 2147483647, + 12, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { setText(2, QStringLiteral("%1").arg(num)); _hcGrp->SetFloat(text(0).toLatin1(), num); @@ -1331,10 +1389,12 @@ void ParameterFloat::appendToGroup() // -------------------------------------------------------------------- -ParameterBool::ParameterBool(QTreeWidget* parent, - QString label, - bool value, - const Base::Reference& hcGrp) +ParameterBool::ParameterBool( + QTreeWidget* parent, + QString label, + bool value, + const Base::Reference& hcGrp +) : ParameterValueItem(parent, hcGrp) { setIcon(0, BitmapFactory().iconFromTheme("Param_Bool")); @@ -1352,14 +1412,16 @@ void ParameterBool::changeValue() list << QStringLiteral("true") << QStringLiteral("false"); int pos = (text(2) == list[0] ? 0 : 1); - QString txt = QInputDialog::getItem(treeWidget(), - QObject::tr("Change value"), - QObject::tr("Choose an item:"), - list, - pos, - false, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString txt = QInputDialog::getItem( + treeWidget(), + QObject::tr("Change value"), + QObject::tr("Choose an item:"), + list, + pos, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { setText(2, txt); _hcGrp->SetBool(text(0).toLatin1(), (txt == list[0] ? true : false)); diff --git a/src/Gui/Dialogs/DlgParameterImp.h b/src/Gui/Dialogs/DlgParameterImp.h index f8046a6086..04dc5fbec0 100644 --- a/src/Gui/Dialogs/DlgParameterImp.h +++ b/src/Gui/Dialogs/DlgParameterImp.h @@ -32,8 +32,10 @@ #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgParameter; class DlgParameterFind; @@ -42,12 +44,12 @@ class DlgParameterFind; * The DlgParameterImp class implements a dialog showing all parameters in a list view. * \author Jürgen Riegel */ -class GuiExport DlgParameterImp : public QDialog +class GuiExport DlgParameterImp: public QDialog { Q_OBJECT public: - explicit DlgParameterImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + explicit DlgParameterImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); ~DlgParameterImp() override; void accept() override; @@ -59,15 +61,15 @@ protected: void setupConnections(); void onChangeParameterSet(int); void onButtonFindClicked(); - void onFindGroupTtextChanged(const QString &SearchStr); + void onFindGroupTtextChanged(const QString& SearchStr); void onButtonSaveToDiskClicked(); - void onGroupSelected(QTreeWidgetItem *); + void onGroupSelected(QTreeWidgetItem*); void onCloseButtonClicked(); void onCheckSortToggled(bool); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void showEvent(QShowEvent*) override; void closeEvent(QCloseEvent*) override; @@ -91,19 +93,19 @@ private: * The leaves represented by ParameterValueItem are displayed in ParameterValue. * @author Werner Mayer */ -class ParameterGroup : public QTreeWidget +class ParameterGroup: public QTreeWidget { Q_OBJECT public: - explicit ParameterGroup( QWidget * parent = nullptr ); + explicit ParameterGroup(QWidget* parent = nullptr); ~ParameterGroup() override; protected: /** Shows the context menu. */ - void contextMenuEvent ( QContextMenuEvent* event ) override; + void contextMenuEvent(QContextMenuEvent* event) override; /** Triggers the "Del" key. */ - void keyPressEvent (QKeyEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; protected Q_SLOTS: /** Removes the underlying parameter group and its sub-groups from the @@ -124,7 +126,7 @@ protected Q_SLOTS: void onRenameSelectedItem(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: QMenu* menuEdit; @@ -143,24 +145,24 @@ private: * by the ParameterValueItem class. * @author Werner Mayer */ -class ParameterValue : public QTreeWidget +class ParameterValue: public QTreeWidget { Q_OBJECT public: - explicit ParameterValue( QWidget * parent = nullptr ); + explicit ParameterValue(QWidget* parent = nullptr); ~ParameterValue() override; /** Sets the current parameter group that is displayed. */ - void setCurrentGroup( const Base::Reference& _hcGrp ); + void setCurrentGroup(const Base::Reference& _hcGrp); /** Returns the current parameter group that is displayed. */ Base::Reference currentGroup() const; protected: /** Shows the context menu. */ - void contextMenuEvent ( QContextMenuEvent* event ) override; + void contextMenuEvent(QContextMenuEvent* event) override; /** Invokes onDeleteSelectedItem() if the "Del" key was pressed. */ - void keyPressEvent (QKeyEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; void resizeEvent(QResizeEvent*) override; protected Q_SLOTS: @@ -187,7 +189,7 @@ protected Q_SLOTS: * @note We need to reimplement this method as QTreeWidgetItem::flags() * doesn't have an int parameter. */ - bool edit ( const QModelIndex & index, QAbstractItemView::EditTrigger trigger, QEvent * event ) override; + bool edit(const QModelIndex& index, QAbstractItemView::EditTrigger trigger, QEvent* event) override; private: QMenu* menuEdit; @@ -210,16 +212,16 @@ private: * * \author Jürgen Riegel */ -class ParameterGroupItem : public QTreeWidgetItem +class ParameterGroupItem: public QTreeWidgetItem { public: /// Constructor - ParameterGroupItem( ParameterGroupItem * parent, const Base::Reference &hcGrp ); - ParameterGroupItem( QTreeWidget* parent, const Base::Reference &hcGrp); + ParameterGroupItem(ParameterGroupItem* parent, const Base::Reference& hcGrp); + ParameterGroupItem(QTreeWidget* parent, const Base::Reference& hcGrp); ~ParameterGroupItem() override; - void setData ( int column, int role, const QVariant & value ) override; - QVariant data ( int column, int role ) const override; + void setData(int column, int role, const QVariant& value) override; + QVariant data(int column, int role) const override; void fillUp(); Base::Reference _hcGrp; @@ -234,15 +236,15 @@ public: * parameter group. * @author Werner Mayer */ -class ParameterValueItem : public QTreeWidgetItem +class ParameterValueItem: public QTreeWidgetItem { public: /// Constructor - ParameterValueItem ( QTreeWidget* parent, const Base::Reference &hcGrp); + ParameterValueItem(QTreeWidget* parent, const Base::Reference& hcGrp); ~ParameterValueItem() override; /** If the name of the item has changed replace() is invoked. */ - void setData ( int column, int role, const QVariant & value ) override; + void setData(int column, int role, const QVariant& value) override; /** Opens an input dialog to change the value. */ virtual void changeValue() = 0; /** Append this item as leaf to the parameter group. */ @@ -252,7 +254,7 @@ public: protected: /** Replaces the name of the leaf from \a oldName to \a newName. */ - virtual void replace( const QString& oldName, const QString& newName ) = 0; + virtual void replace(const QString& oldName, const QString& newName) = 0; protected: Base::Reference _hcGrp; @@ -262,11 +264,16 @@ protected: * The ParameterText class allows interaction with "text" parameter leaves. * @author Werner Mayer */ -class ParameterText : public ParameterValueItem +class ParameterText: public ParameterValueItem { public: /// Constructor - ParameterText ( QTreeWidget * parent, QString label1, const char* value, const Base::Reference &hcGrp); + ParameterText( + QTreeWidget* parent, + QString label1, + const char* value, + const Base::Reference& hcGrp + ); ~ParameterText() override; void changeValue() override; @@ -274,18 +281,23 @@ public: void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ) override; + void replace(const QString& oldName, const QString& newName) override; }; /** * The ParameterInt class allows interaction with "integer" parameter leaves. * @author Werner Mayer */ -class ParameterInt : public ParameterValueItem +class ParameterInt: public ParameterValueItem { public: /// Constructor - ParameterInt ( QTreeWidget * parent, QString label1, long value, const Base::Reference &hcGrp); + ParameterInt( + QTreeWidget* parent, + QString label1, + long value, + const Base::Reference& hcGrp + ); ~ParameterInt() override; void changeValue() override; @@ -293,18 +305,23 @@ public: void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ) override; + void replace(const QString& oldName, const QString& newName) override; }; /** * The ParameterUInt class allows interaction with "unsigned integer" parameter leaves. * @author Werner Mayer */ -class ParameterUInt : public ParameterValueItem +class ParameterUInt: public ParameterValueItem { public: /// Constructor - ParameterUInt ( QTreeWidget * parent, QString label1, unsigned long value, const Base::Reference &hcGrp); + ParameterUInt( + QTreeWidget* parent, + QString label1, + unsigned long value, + const Base::Reference& hcGrp + ); ~ParameterUInt() override; void changeValue() override; @@ -312,18 +329,23 @@ public: void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ) override; + void replace(const QString& oldName, const QString& newName) override; }; /** * The ParameterFloat class allows interaction with "float" parameter leaves. * @author Werner Mayer */ -class ParameterFloat : public ParameterValueItem +class ParameterFloat: public ParameterValueItem { public: /// Constructor - ParameterFloat ( QTreeWidget * parent, QString label1, double value, const Base::Reference &hcGrp); + ParameterFloat( + QTreeWidget* parent, + QString label1, + double value, + const Base::Reference& hcGrp + ); ~ParameterFloat() override; void changeValue() override; @@ -331,18 +353,23 @@ public: void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ) override; + void replace(const QString& oldName, const QString& newName) override; }; /** * The ParameterBool class allows interaction with "boolean" parameter leaves. * @author Werner Mayer */ -class ParameterBool : public ParameterValueItem +class ParameterBool: public ParameterValueItem { public: /// Constructor - ParameterBool ( QTreeWidget * parent, QString label1, bool value, const Base::Reference &hcGrp); + ParameterBool( + QTreeWidget* parent, + QString label1, + bool value, + const Base::Reference& hcGrp + ); ~ParameterBool() override; void changeValue() override; @@ -350,10 +377,10 @@ public: void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ) override; + void replace(const QString& oldName, const QString& newName) override; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGPARAMETER_H +#endif // GUI_DIALOG_DLGPARAMETER_H diff --git a/src/Gui/Dialogs/DlgPreferencePackManagementImp.cpp b/src/Gui/Dialogs/DlgPreferencePackManagementImp.cpp index 14c0482c9b..4f9c954717 100644 --- a/src/Gui/Dialogs/DlgPreferencePackManagementImp.cpp +++ b/src/Gui/Dialogs/DlgPreferencePackManagementImp.cpp @@ -20,7 +20,7 @@ * * ***************************************************************************/ -# include +#include #include "Dialogs/DlgPreferencePackManagementImp.h" #include "ui_DlgPreferencePackManagement.h" @@ -43,29 +43,42 @@ DlgPreferencePackManagementImp::DlgPreferencePackManagementImp(QWidget* parent) { ui->setupUi(this); if (Application::Instance->commandManager().getCommandByName("Std_AddonMgr")) { - connect(ui->pushButtonOpenAddonManager, &QPushButton::clicked, this, &DlgPreferencePackManagementImp::showAddonManager); + connect( + ui->pushButtonOpenAddonManager, + &QPushButton::clicked, + this, + &DlgPreferencePackManagementImp::showAddonManager + ); } else { ui->pushButtonOpenAddonManager->setDisabled(true); } - connect(this, &DlgPreferencePackManagementImp::packVisibilityChanged, this, &DlgPreferencePackManagementImp::updateTree); + connect( + this, + &DlgPreferencePackManagementImp::packVisibilityChanged, + this, + &DlgPreferencePackManagementImp::updateTree + ); updateTree(); } void DlgPreferencePackManagementImp::updateTree() { - // Separate out user-saved packs from installed packs: we can remove individual user-saved packs, - // but can only disable individual installed packs (though we can completely uninstall the pack's - // containing Addon by redirecting to the Addon Manager). - auto savedPreferencePacksDirectory = Application::Instance->prefPackManager()->getSavedPreferencePacksPath(); + // Separate out user-saved packs from installed packs: we can remove individual user-saved + // packs, but can only disable individual installed packs (though we can completely uninstall + // the pack's containing Addon by redirecting to the Addon Manager). + auto savedPreferencePacksDirectory + = Application::Instance->prefPackManager()->getSavedPreferencePacksPath(); auto modDirectories = Application::Instance->prefPackManager()->modPaths(); auto resourcePath = Application::Instance->prefPackManager()->getResourcePreferencePacksPath(); // The displayed tree has two levels: at the toplevel is either "User-Saved Packs" or the name - // of the addon containing the pack. Beneath those are the individual packs themselves. The tree view shows - // "Hide"/"Show" for packs installed as a Mod, and "Delete" for packs in the user-saved pack - // section. - auto userPacks = Application::Instance->prefPackManager()->getPacksFromDirectory(savedPreferencePacksDirectory); + // of the addon containing the pack. Beneath those are the individual packs themselves. The tree + // view shows "Hide"/"Show" for packs installed as a Mod, and "Delete" for packs in the + // user-saved pack section. + auto userPacks = Application::Instance->prefPackManager()->getPacksFromDirectory( + savedPreferencePacksDirectory + ); auto builtinPacks = Application::Instance->prefPackManager()->getPacksFromDirectory(resourcePath); @@ -82,7 +95,7 @@ void DlgPreferencePackManagementImp::updateTree() } } - ui->treeWidget->clear(); // Begin by clearing whatever is there + ui->treeWidget->clear(); // Begin by clearing whatever is there ui->treeWidget->header()->setDefaultAlignment(Qt::AlignLeft); ui->treeWidget->setColumnCount(2); ui->treeWidget->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection); @@ -103,7 +116,11 @@ void DlgPreferencePackManagementImp::updateTree() } } -void DlgPreferencePackManagementImp::addTreeNode(const std::string &name, const std::vector &contents, TreeWidgetType twt) +void DlgPreferencePackManagementImp::addTreeNode( + const std::string& name, + const std::vector& contents, + TreeWidgetType twt +) { static const auto iconIsVisible = QIcon(QLatin1String(":/icons/dagViewVisible.svg")); static const auto iconIsInvisible = QIcon(QLatin1String(":/icons/Invisible.svg")); @@ -121,32 +138,47 @@ void DlgPreferencePackManagementImp::addTreeNode(const std::string &name, const auto button = new QPushButton(); button->setFlat(true); switch (twt) { - break; case TreeWidgetType::BUILTIN: - // The button is a "hide" button - if (Application::Instance->prefPackManager()->isVisible("##BUILT_IN##", item->text(0).toStdString())) - button->setIcon(iconIsVisible); - else - button->setIcon(iconIsInvisible); - button->setToolTip(tr("Toggle visibility of built-in preference pack '%1'").arg(item->text(0))); - connect(button, &QPushButton::clicked, [this, item]() { - this->hideBuiltInPack(item->text(0).toStdString()); + break; + case TreeWidgetType::BUILTIN: + // The button is a "hide" button + if (Application::Instance->prefPackManager() + ->isVisible("##BUILT_IN##", item->text(0).toStdString())) { + button->setIcon(iconIsVisible); + } + else { + button->setIcon(iconIsInvisible); + } + button->setToolTip( + tr("Toggle visibility of built-in preference pack '%1'").arg(item->text(0)) + ); + connect(button, &QPushButton::clicked, [this, item]() { + this->hideBuiltInPack(item->text(0).toStdString()); }); - break; case TreeWidgetType::USER: - // The button is a "delete" button - button->setIcon(QIcon(QLatin1String(":/icons/delete.svg"))); - button->setToolTip(tr("Deletes the user-saved preference pack '%1'").arg(item->text(0))); - connect(button, &QPushButton::clicked, [this, item]() { - this->deleteUserPack(item->text(0).toStdString()); + break; + case TreeWidgetType::USER: + // The button is a "delete" button + button->setIcon(QIcon(QLatin1String(":/icons/delete.svg"))); + button->setToolTip( + tr("Deletes the user-saved preference pack '%1'").arg(item->text(0)) + ); + connect(button, &QPushButton::clicked, [this, item]() { + this->deleteUserPack(item->text(0).toStdString()); }); - break; case TreeWidgetType::ADDON: - // The button is a "hide" button - if (Application::Instance->prefPackManager()->isVisible(name, item->text(0).toStdString())) - button->setIcon(iconIsVisible); - else - button->setIcon(iconIsInvisible); - button->setToolTip(tr("Toggles the visibility of the addon preference pack '%1' (use the Addon Manager to remove permanently)").arg(item->text(0))); - connect(button, &QPushButton::clicked, [this, name, item]() { - this->hideInstalledPack(name, item->text(0).toStdString()); + break; + case TreeWidgetType::ADDON: + // The button is a "hide" button + if (Application::Instance->prefPackManager() + ->isVisible(name, item->text(0).toStdString())) { + button->setIcon(iconIsVisible); + } + else { + button->setIcon(iconIsInvisible); + } + button->setToolTip(tr("Toggles the visibility of the addon preference pack '%1' " + "(use the Addon Manager to remove permanently)") + .arg(item->text(0))); + connect(button, &QPushButton::clicked, [this, name, item]() { + this->hideInstalledPack(name, item->text(0).toStdString()); }); } ui->treeWidget->setItemWidget(item, 1, button); @@ -156,9 +188,14 @@ void DlgPreferencePackManagementImp::addTreeNode(const std::string &name, const void DlgPreferencePackManagementImp::deleteUserPack(const std::string& name) { // Do the deletion here... - auto result = QMessageBox::warning(this, tr("Delete saved preference pack?"), - tr("Delete the preference pack named '%1'? This cannot be undone.").arg(QString::fromStdString(name)), - QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); + auto result = QMessageBox::warning( + this, + tr("Delete saved preference pack?"), + tr("Delete the preference pack named '%1'? This cannot be undone.") + .arg(QString::fromStdString(name)), + QMessageBox::Yes | QMessageBox::Cancel, + QMessageBox::Cancel + ); if (result == QMessageBox::Yes) { Application::Instance->prefPackManager()->deleteUserPack(name); Q_EMIT packVisibilityChanged(); @@ -171,7 +208,10 @@ void DlgPreferencePackManagementImp::hideBuiltInPack(const std::string& prefPack Q_EMIT packVisibilityChanged(); } -void DlgPreferencePackManagementImp::hideInstalledPack(const std::string& addonName, const std::string& prefPackName) +void DlgPreferencePackManagementImp::hideInstalledPack( + const std::string& addonName, + const std::string& prefPackName +) { Application::Instance->prefPackManager()->toggleVisibility(addonName, prefPackName); Q_EMIT packVisibilityChanged(); @@ -180,7 +220,9 @@ void DlgPreferencePackManagementImp::hideInstalledPack(const std::string& addonN void DlgPreferencePackManagementImp::showAddonManager() { // Configure the view to show all preference packs (installed and uninstalled) - auto pref = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Addons"); + auto pref = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Addons" + ); pref->SetInt("PackageTypeSelection", 3); pref->SetInt("StatusSelection", 0); @@ -192,5 +234,4 @@ void DlgPreferencePackManagementImp::showAddonManager() DlgPreferencePackManagementImp::~DlgPreferencePackManagementImp() = default; - #include "moc_DlgPreferencePackManagementImp.cpp" diff --git a/src/Gui/Dialogs/DlgPreferencePackManagementImp.h b/src/Gui/Dialogs/DlgPreferencePackManagementImp.h index 49bd8c7d4d..421996b727 100644 --- a/src/Gui/Dialogs/DlgPreferencePackManagementImp.h +++ b/src/Gui/Dialogs/DlgPreferencePackManagementImp.h @@ -32,9 +32,11 @@ class QTreeWidgetItem; -namespace Gui { +namespace Gui +{ -namespace Dialog { +namespace Dialog +{ class Ui_DlgPreferencePackManagement; @@ -45,12 +47,11 @@ class Ui_DlgPreferencePackManagement; * * \author Chris Hennes */ -class GuiExport DlgPreferencePackManagementImp : public QDialog +class GuiExport DlgPreferencePackManagementImp: public QDialog { - Q_OBJECT + Q_OBJECT public: - DlgPreferencePackManagementImp(QWidget* parent = nullptr); ~DlgPreferencePackManagementImp() override; @@ -59,14 +60,14 @@ Q_SIGNALS: protected Q_SLOTS: - void deleteUserPack(const std::string & prefPackName); + void deleteUserPack(const std::string& prefPackName); void hideBuiltInPack(const std::string& prefPackName); void hideInstalledPack(const std::string& addonName, const std::string& prefPackName); void showAddonManager(); private: - - enum class TreeWidgetType { + enum class TreeWidgetType + { BUILTIN, USER, ADDON @@ -74,11 +75,15 @@ private: std::unique_ptr ui; - void addTreeNode(const std::string& name, const std::vector& contents, TreeWidgetType twt); + void addTreeNode( + const std::string& name, + const std::vector& contents, + TreeWidgetType twt + ); void updateTree(); }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGPREFERENCEPACKMANAGEMENTIMP_H +#endif // GUI_DIALOG_DLGPREFERENCEPACKMANAGEMENTIMP_H diff --git a/src/Gui/Dialogs/DlgPreferencesImp.cpp b/src/Gui/Dialogs/DlgPreferencesImp.cpp index 82620bc29b..1b63965393 100644 --- a/src/Gui/Dialogs/DlgPreferencesImp.cpp +++ b/src/Gui/Dialogs/DlgPreferencesImp.cpp @@ -1,60 +1,60 @@ // SPDX-License-Identifier: LGPL-2.1-or-later - /**************************************************************************** - * Copyright (c) 2002 Jürgen Riegel * - * Copyright (c) 2023 FreeCAD Project Association * - * * - * This file is part of FreeCAD. * - * * - * FreeCAD is free software: you can redistribute it and/or modify it * - * under the terms of the GNU Lesser General Public License as * - * published by the Free Software Foundation, either version 2.1 of the * - * License, or (at your option) any later version. * - * * - * FreeCAD 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 * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with FreeCAD. If not, see * - * . * - * * - ***************************************************************************/ +/**************************************************************************** + * Copyright (c) 2002 Jürgen Riegel * + * Copyright (c) 2023 FreeCAD Project Association * + * * + * This file is part of FreeCAD. * + * * + * FreeCAD is free software: you can redistribute it and/or modify it * + * under the terms of the GNU Lesser General Public License as * + * published by the Free Software Foundation, either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * FreeCAD 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 * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with FreeCAD. If not, see * + * . * + * * + ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -72,66 +72,75 @@ using namespace Gui::Dialog; // Simple delegate to render first line bold, second line normal // used by search box -class MixedFontDelegate : public QStyledItemDelegate +class MixedFontDelegate: public QStyledItemDelegate { static constexpr int horizontalPadding = 12; static constexpr int verticalPadding = 4; public: - explicit MixedFontDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {} - + explicit MixedFontDelegate(QObject* parent = nullptr) + : QStyledItemDelegate(parent) + {} + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { if (!index.isValid()) { QStyledItemDelegate::paint(painter, option, index); return; } - + QString pathText, widgetText; extractTextData(index, pathText, widgetText); - + if (pathText.isEmpty()) { QStyledItemDelegate::paint(painter, option, index); return; } - + QFont boldFont, normalFont; createFonts(option.font, boldFont, normalFont); - LayoutInfo layout = calculateLayout(pathText, widgetText, boldFont, normalFont, option.rect.width()); + LayoutInfo layout + = calculateLayout(pathText, widgetText, boldFont, normalFont, option.rect.width()); painter->save(); - + // draw selection background if selected if (option.state & QStyle::State_Selected) { painter->fillRect(option.rect, option.palette.highlight()); } - + // Set text color based on selection - QColor textColor = (option.state & QStyle::State_Selected) - ? option.palette.highlightedText().color() - : option.palette.text().color(); + QColor textColor = (option.state & QStyle::State_Selected) + ? option.palette.highlightedText().color() + : option.palette.text().color(); painter->setPen(textColor); - + // draw path in bold (Tab/Page) with wrapping painter->setFont(boldFont); - QRect boldRect(option.rect.left() + horizontalPadding, option.rect.top() + verticalPadding, - layout.availableWidth, layout.pathHeight); + QRect boldRect( + option.rect.left() + horizontalPadding, + option.rect.top() + verticalPadding, + layout.availableWidth, + layout.pathHeight + ); painter->drawText(boldRect, Qt::TextWordWrap | Qt::AlignTop, pathText); - + // draw widget text in normal font (if present) if (!widgetText.isEmpty()) { painter->setFont(normalFont); - QRect normalRect(option.rect.left() + horizontalPadding, - option.rect.top() + verticalPadding + layout.pathHeight, - layout.availableWidth, - layout.widgetHeight); + QRect normalRect( + option.rect.left() + horizontalPadding, + option.rect.top() + verticalPadding + layout.pathHeight, + layout.availableWidth, + layout.widgetHeight + ); painter->drawText(normalRect, Qt::TextWordWrap | Qt::AlignTop, widgetText); } - + painter->restore(); } - + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override { if (!index.isValid()) { @@ -140,7 +149,7 @@ public: QString pathText, widgetText; extractTextData(index, pathText, widgetText); - + if (pathText.isEmpty()) { return QStyledItemDelegate::sizeHint(option, index); } @@ -148,13 +157,15 @@ public: QFont boldFont, normalFont; createFonts(option.font, boldFont, normalFont); - LayoutInfo layout = calculateLayout(pathText, widgetText, boldFont, normalFont, option.rect.width()); + LayoutInfo layout + = calculateLayout(pathText, widgetText, boldFont, normalFont, option.rect.width()); return {layout.totalWidth, layout.totalHeight}; } private: - struct LayoutInfo { + struct LayoutInfo + { int availableWidth; int pathHeight; int widgetHeight; @@ -173,40 +184,51 @@ private: { boldFont = baseFont; boldFont.setBold(true); - boldFont.setPointSize(boldFont.pointSize() - 1); // make header smaller like a subtitle - - normalFont = baseFont; // keep widget text at normal size + boldFont.setPointSize(boldFont.pointSize() - 1); // make header smaller like a subtitle + + normalFont = baseFont; // keep widget text at normal size } - LayoutInfo calculateLayout(const QString& pathText, const QString& widgetText, - const QFont& boldFont, const QFont& normalFont, int containerWidth) const + LayoutInfo calculateLayout( + const QString& pathText, + const QString& widgetText, + const QFont& boldFont, + const QFont& normalFont, + int containerWidth + ) const { QFontMetrics boldFm(boldFont); QFontMetrics normalFm(normalFont); - - int availableWidth = containerWidth - horizontalPadding * 2; // account for left and right padding + + int availableWidth = containerWidth + - horizontalPadding * 2; // account for left and right padding if (availableWidth <= 0) { constexpr int defaultPopupWidth = 300; - availableWidth = defaultPopupWidth - horizontalPadding * 2; // Fallback to popup width minus padding + availableWidth = defaultPopupWidth + - horizontalPadding * 2; // Fallback to popup width minus padding } - + // Calculate dimensions for path text (bold) - QRect pathBoundingRect = boldFm.boundingRect(QRect(0, 0, availableWidth, 0), Qt::TextWordWrap, pathText); + QRect pathBoundingRect + = boldFm.boundingRect(QRect(0, 0, availableWidth, 0), Qt::TextWordWrap, pathText); int pathHeight = pathBoundingRect.height(); int pathWidth = pathBoundingRect.width(); - + // Calculate dimensions for widget text (normal font, if present) int widgetHeight = 0; int widgetWidth = 0; if (!widgetText.isEmpty()) { - QRect widgetBoundingRect = normalFm.boundingRect(QRect(0, 0, availableWidth, 0), Qt::TextWordWrap, widgetText); + QRect widgetBoundingRect + = normalFm.boundingRect(QRect(0, 0, availableWidth, 0), Qt::TextWordWrap, widgetText); widgetHeight = widgetBoundingRect.height(); widgetWidth = widgetBoundingRect.width(); } - - int totalWidth = qMax(pathWidth, widgetWidth) + horizontalPadding * 2; // +24 horizontal padding - int totalHeight = verticalPadding * 2 + pathHeight + widgetHeight; // 8 vertical padding + content heights + + int totalWidth = qMax(pathWidth, widgetWidth) + + horizontalPadding * 2; // +24 horizontal padding + int totalHeight = verticalPadding * 2 + pathHeight + + widgetHeight; // 8 vertical padding + content heights LayoutInfo layout; layout.availableWidth = availableWidth; @@ -250,7 +272,7 @@ void PreferencesPageItem::setWidget(QWidget* widget) if (_widget) { _widget->setProperty(PropertyName, QVariant::fromValue(nullptr)); } - + _widget = widget; _widget->setProperty(PropertyName, QVariant::fromValue(this)); } @@ -287,8 +309,11 @@ DlgPreferencesImp* DlgPreferencesImp::_activeDialog = nullptr; * true to construct a modal dialog. */ DlgPreferencesImp::DlgPreferencesImp(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), ui(new Ui_DlgPreferences), - invalidParameter(false), canEmbedScrollArea(true), restartRequired(false) + : QDialog(parent, fl) + , ui(new Ui_DlgPreferences) + , invalidParameter(false) + , canEmbedScrollArea(true) + , restartRequired(false) { ui->setupUi(this); @@ -297,11 +322,11 @@ DlgPreferencesImp::DlgPreferencesImp(QWidget* parent, Qt::WindowFlags fl) // Initialize search controller m_searchController = std::make_unique(this, this); - + setupConnections(); ui->groupsTreeView->setModel(&_model); - + // Configure search controller after UI setup m_searchController->setPreferencesModel(&_model); m_searchController->setGroupNameRole(GroupNameRole); @@ -322,7 +347,7 @@ DlgPreferencesImp::~DlgPreferencesImp() { // Remove global event filter qApp->removeEventFilter(this); - + if (DlgPreferencesImp::_activeDialog == this) { DlgPreferencesImp::_activeDialog = nullptr; } @@ -330,49 +355,37 @@ DlgPreferencesImp::~DlgPreferencesImp() void DlgPreferencesImp::setupConnections() { - connect(ui->buttonBox, - &QDialogButtonBox::clicked, - this, - &DlgPreferencesImp::onButtonBoxClicked); - connect(ui->buttonBox, - &QDialogButtonBox::helpRequested, - getMainWindow(), - &MainWindow::whatsThis); - connect(ui->groupsTreeView, - &QTreeView::clicked, - this, - &DlgPreferencesImp::onPageSelected); - connect(ui->groupsTreeView, - &QTreeView::expanded, - this, - &DlgPreferencesImp::onGroupExpanded); - connect(ui->groupsTreeView, - &QTreeView::collapsed, - this, - &DlgPreferencesImp::onGroupCollapsed); - connect(ui->buttonReset, - &QPushButton::clicked, - this, - &DlgPreferencesImp::showResetOptions); - connect(ui->groupWidgetStack, - &QStackedWidget::currentChanged, - this, - &DlgPreferencesImp::onStackWidgetChange); + connect(ui->buttonBox, &QDialogButtonBox::clicked, this, &DlgPreferencesImp::onButtonBoxClicked); + connect(ui->buttonBox, &QDialogButtonBox::helpRequested, getMainWindow(), &MainWindow::whatsThis); + connect(ui->groupsTreeView, &QTreeView::clicked, this, &DlgPreferencesImp::onPageSelected); + connect(ui->groupsTreeView, &QTreeView::expanded, this, &DlgPreferencesImp::onGroupExpanded); + connect(ui->groupsTreeView, &QTreeView::collapsed, this, &DlgPreferencesImp::onGroupCollapsed); + connect(ui->buttonReset, &QPushButton::clicked, this, &DlgPreferencesImp::showResetOptions); + connect( + ui->groupWidgetStack, + &QStackedWidget::currentChanged, + this, + &DlgPreferencesImp::onStackWidgetChange + ); // Connect search functionality to controller - connect(ui->searchBox, - &QLineEdit::textChanged, - m_searchController.get(), - &PreferencesSearchController::onSearchTextChanged); - + connect( + ui->searchBox, + &QLineEdit::textChanged, + m_searchController.get(), + &PreferencesSearchController::onSearchTextChanged + ); + // Connect navigation signal from controller to dialog - connect(m_searchController.get(), - &PreferencesSearchController::navigationRequested, - this, - &DlgPreferencesImp::onNavigationRequested); - + connect( + m_searchController.get(), + &PreferencesSearchController::navigationRequested, + this, + &DlgPreferencesImp::onNavigationRequested + ); + // Install event filter on search box for arrow key navigation ui->searchBox->installEventFilter(this); - + // Install global event filter to handle clicks outside popup qApp->installEventFilter(this); } @@ -382,10 +395,10 @@ void DlgPreferencesImp::setupPages() // make sure that pages are ready to create GetWidgetFactorySupplier(); - for (const auto &[name, pages] : _pages) { + for (const auto& [name, pages] : _pages) { auto* group = createGroup(name); - for (const auto &page : pages) { + for (const auto& page : pages) { createPageInGroup(group, page); } } @@ -393,12 +406,11 @@ void DlgPreferencesImp::setupPages() updatePageDependentWidgets(); } -QPixmap DlgPreferencesImp::loadIconForGroup(const std::string &name) const +QPixmap DlgPreferencesImp::loadIconForGroup(const std::string& name) const { // normalize file name auto normalizeName = [](std::string str) { - std::transform(str.begin(), str.end(), str.begin(), - [](unsigned char ch) { + std::transform(str.begin(), str.end(), str.begin(), [](unsigned char ch) { return ch == ' ' ? '_' : std::tolower(ch); }); return str; @@ -425,26 +437,23 @@ QPixmap DlgPreferencesImp::loadIconForGroup(const std::string &name) const } /** - * Create the necessary widgets for a new group named \a groupName. Returns a - * pointer to the group's SettingsPageItem: that widget's lifetime is managed by the + * Create the necessary widgets for a new group named \a groupName. Returns a + * pointer to the group's SettingsPageItem: that widget's lifetime is managed by the * QStandardItemModel, do not manually deallocate. */ -PreferencesPageItem* DlgPreferencesImp::createGroup(const std::string &groupName) +PreferencesPageItem* DlgPreferencesImp::createGroup(const std::string& groupName) { QString groupNameQString = QString::fromStdString(groupName); std::string iconName; - + QString tooltip; getGroupData(groupName, iconName, tooltip); auto groupPages = new QStackedWidget; groupPages->setProperty(GroupNameProperty, QVariant(groupNameQString)); - connect(groupPages, - &QStackedWidget::currentChanged, - this, - &DlgPreferencesImp::onStackWidgetChange); + connect(groupPages, &QStackedWidget::currentChanged, this, &DlgPreferencesImp::onStackWidgetChange); if (ui->groupWidgetStack->count() > 0) { @@ -469,7 +478,10 @@ PreferencesPageItem* DlgPreferencesImp::createGroup(const std::string &groupName } -PreferencePage* DlgPreferencesImp::createPreferencePage(const std::string& pageName, const std::string& groupName) +PreferencePage* DlgPreferencesImp::createPreferencePage( + const std::string& pageName, + const std::string& groupName +) { PreferencePage* page = WidgetFactory().createPreferencePage(pageName.c_str()); @@ -501,10 +513,11 @@ PreferencePage* DlgPreferencesImp::createPreferencePage(const std::string& pageN /** * Create a new preference page called \a pageName in the group \a groupItem. */ -void DlgPreferencesImp::createPageInGroup(PreferencesPageItem *groupItem, const std::string &pageName) +void DlgPreferencesImp::createPageInGroup(PreferencesPageItem* groupItem, const std::string& pageName) { try { - PreferencePage* page = createPreferencePage(pageName, groupItem->data(GroupNameRole).toString().toStdString()); + PreferencePage* page + = createPreferencePage(pageName, groupItem->data(GroupNameRole).toString().toStdString()); if (!page) { Base::Console().warning("%s is not a preference page\n", pageName.c_str()); @@ -679,7 +692,7 @@ void DlgPreferencesImp::activateGroupPage(const QString& group, int index) pageStackWidget->setCurrentIndex(index); updatePageDependentWidgets(); - + return; } } @@ -735,7 +748,7 @@ void DlgPreferencesImp::accept() this->invalidParameter = false; applyChanges(); - + if (!this->invalidParameter) { QDialog::accept(); restartIfRequired(); @@ -748,7 +761,7 @@ void DlgPreferencesImp::reject() restartIfRequired(); } -void DlgPreferencesImp::onButtonBoxClicked(QAbstractButton* btn) +void DlgPreferencesImp::onButtonBoxClicked(QAbstractButton* btn) { if (ui->buttonBox->standardButton(btn) == QDialogButtonBox::Apply) { applyChanges(); @@ -767,21 +780,21 @@ void DlgPreferencesImp::showResetOptions() // Reset per page QAction* pageAction = menu.addAction(tr("Reset Page '%1'").arg(pageText), this, [&] { - restorePageDefaults(currentPageItem); }); pageAction->setToolTip(tr("Resets the user settings for the page '%1'").arg(pageText)); // Reset per group - QAction* groupAction = menu.addAction(tr("Reset Group '%1'").arg(groupText), + QAction* groupAction = menu.addAction( + tr("Reset Group '%1'").arg(groupText), - this, - [&] { restorePageDefaults(static_cast(currentPageItem->parent())); }); + this, + [&] { restorePageDefaults(static_cast(currentPageItem->parent())); } + ); groupAction->setToolTip(tr("Resets the user settings for the group '%1'").arg(groupText)); // Reset all - QAction* allAction = - menu.addAction(tr("Reset All"), this, &DlgPreferencesImp::restoreDefaults); + QAction* allAction = menu.addAction(tr("Reset All"), this, &DlgPreferencesImp::restoreDefaults); allAction->setToolTip(tr("Resets the user settings entirely")); @@ -807,20 +820,22 @@ void DlgPreferencesImp::restoreDefaults() if (box.exec() == QMessageBox::Yes) { // keep this parameter - bool saveParameter = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> - GetBool("SaveUserParameter", true); + bool saveParameter = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetBool("SaveUserParameter", true); ParameterManager* mgr = App::GetApplication().GetParameterSet("User parameter"); mgr->Clear(); - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> - SetBool("SaveUserParameter", saveParameter); + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->SetBool("SaveUserParameter", saveParameter); reject(); } } /** - * If the dialog is currently showing and the static variable _pages changed, this function + * If the dialog is currently showing and the static variable _pages changed, this function * will rescan that list of pages and add any that are new to the current dialog. It will not * remove any pages that are no longer in the list, and will not change the user's current * active page. @@ -830,7 +845,7 @@ void DlgPreferencesImp::reloadPages() // Make sure that pages are ready to create GetWidgetFactorySupplier(); - for (const auto &[ group, pages ] : _pages) { + for (const auto& [group, pages] : _pages) { QString groupName = QString::fromStdString(group); // First, does this group already exist? @@ -847,7 +862,7 @@ void DlgPreferencesImp::reloadPages() } } - // This is a new group that wasn't there when we started this instance of the dialog: + // This is a new group that wasn't there when we started this instance of the dialog: if (!groupItem) { groupItem = createGroup(group); } @@ -900,9 +915,7 @@ void DlgPreferencesImp::applyChanges() ui->groupWidgetStack->setCurrentIndex(i); pagesStackWidget->setCurrentIndex(j); - QMessageBox::warning(this, - tr("Wrong parameter"), - QString::fromLatin1(e.what())); + QMessageBox::warning(this, tr("Wrong parameter"), QString::fromLatin1(e.what())); this->invalidParameter = true; @@ -920,7 +933,7 @@ void DlgPreferencesImp::applyChanges() for (int j = 0; j < pageStackWidget->count(); j++) { auto page = qobject_cast(pageStackWidget->widget(j)); - + if (page) { page->saveSettings(); restartRequired = restartRequired || page->isRestartRequired(); @@ -931,7 +944,7 @@ void DlgPreferencesImp::applyChanges() bool saveParameter = App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") ->GetBool("SaveUserParameter", true); - + if (saveParameter) { ParameterManager* parmgr = App::GetApplication().GetParameterSet("User parameter"); parmgr->SaveDocument(App::Application::Config()["UserParameter"].c_str()); @@ -941,7 +954,8 @@ void DlgPreferencesImp::applyChanges() void DlgPreferencesImp::restartIfRequired() { if (restartRequired) { - QMessageBox restartBox(parentWidget()); // current window likely already closed, cant parent to it + QMessageBox restartBox(parentWidget()); // current window likely already closed, cant + // parent to it restartBox.setIcon(QMessageBox::Warning); restartBox.setWindowTitle(tr("Restart Required")); @@ -956,10 +970,9 @@ void DlgPreferencesImp::restartIfRequired() int exec = restartBox.exec(); if (exec == QMessageBox::Ok) { - //restart FreeCAD after a delay to give time to this dialog to close + // restart FreeCAD after a delay to give time to this dialog to close const int ms = 1000; - QTimer::singleShot(ms, []() - { + QTimer::singleShot(ms, []() { QStringList args = QApplication::arguments(); args.pop_front(); if (getMainWindow()->close()) { @@ -1107,34 +1120,40 @@ void DlgPreferencesImp::navigateToSearchResult(const QString& groupName, const Q for (int i = 0; i < root->rowCount(); i++) { auto groupItem = static_cast(root->child(i)); if (groupItem->data(GroupNameRole).toString() == groupName) { - + // Find the specific page for (int j = 0; j < groupItem->rowCount(); j++) { auto pageItem = static_cast(groupItem->child(j)); if (pageItem->data(PageNameRole).toString() == pageName) { - + // Expand the group if needed ui->groupsTreeView->expand(groupItem->index()); - + // Select the page - ui->groupsTreeView->selectionModel()->select(pageItem->index(), QItemSelectionModel::ClearAndSelect); - + ui->groupsTreeView->selectionModel()->select( + pageItem->index(), + QItemSelectionModel::ClearAndSelect + ); + // Navigate to the page onPageSelected(pageItem->index()); - + return; } } - + // If no specific page found, just navigate to the group - ui->groupsTreeView->selectionModel()->select(groupItem->index(), QItemSelectionModel::ClearAndSelect); + ui->groupsTreeView->selectionModel()->select( + groupItem->index(), + QItemSelectionModel::ClearAndSelect + ); onPageSelected(groupItem->index()); return; } } } -void DlgPreferencesImp::changeEvent(QEvent *e) +void DlgPreferencesImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -1198,7 +1217,7 @@ void DlgPreferencesImp::restorePageDefaults(PreferencesPageItem* item) * the newPage object (which has restartRequired initialized to false) */ restartRequired = restartRequired || page->isRestartRequired(); - + std::string pageName = page->property(PageNameProperty).toString().toStdString(); std::string groupName = page->property(GroupNameProperty).toString().toStdString(); @@ -1250,40 +1269,50 @@ PreferencesSearchController::PreferencesSearchController(DlgPreferencesImp* pare { // Get reference to search box from parent dialog's UI m_searchBox = m_parentDialog->ui->searchBox; - + // Create the search results popup list m_searchResultsList = new QListWidget(m_parentDialog); - m_searchResultsList->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint); + m_searchResultsList->setWindowFlags( + Qt::Tool | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint + ); m_searchResultsList->setVisible(false); m_searchResultsList->setMinimumWidth(300); - m_searchResultsList->setMaximumHeight(400); // Increased max height + m_searchResultsList->setMaximumHeight(400); // Increased max height m_searchResultsList->setFrameStyle(QFrame::Box | QFrame::Raised); m_searchResultsList->setLineWidth(1); - m_searchResultsList->setFocusPolicy(Qt::NoFocus); // Don't steal focus from search box - m_searchResultsList->setAttribute(Qt::WA_ShowWithoutActivating); // Show without activating/stealing focus - m_searchResultsList->setWordWrap(true); // Enable word wrapping - m_searchResultsList->setTextElideMode(Qt::ElideNone); // Don't elide text, let it wrap instead - m_searchResultsList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Disable horizontal scrollbar - m_searchResultsList->setSpacing(0); // Remove spacing between items - m_searchResultsList->setContentsMargins(0, 0, 0, 0); // Remove margins - + m_searchResultsList->setFocusPolicy(Qt::NoFocus); // Don't steal focus from search box + m_searchResultsList->setAttribute(Qt::WA_ShowWithoutActivating); // Show without + // activating/stealing focus + m_searchResultsList->setWordWrap(true); // Enable word wrapping + m_searchResultsList->setTextElideMode(Qt::ElideNone); // Don't elide text, let it wrap instead + m_searchResultsList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Disable horizontal + // scrollbar + m_searchResultsList->setSpacing(0); // Remove spacing between items + m_searchResultsList->setContentsMargins(0, 0, 0, 0); // Remove margins + // Set custom delegate for mixed font rendering (bold first line, normal second line) m_searchResultsList->setItemDelegate(new MixedFontDelegate(m_searchResultsList)); - + // Connect search results list signals - connect(m_searchResultsList, - &QListWidget::itemSelectionChanged, - this, - &PreferencesSearchController::onSearchResultSelected); - connect(m_searchResultsList, - &QListWidget::itemDoubleClicked, - this, - &PreferencesSearchController::onSearchResultDoubleClicked); - connect(m_searchResultsList, - &QListWidget::itemClicked, - this, - &PreferencesSearchController::onSearchResultClicked); - + connect( + m_searchResultsList, + &QListWidget::itemSelectionChanged, + this, + &PreferencesSearchController::onSearchResultSelected + ); + connect( + m_searchResultsList, + &QListWidget::itemDoubleClicked, + this, + &PreferencesSearchController::onSearchResultDoubleClicked + ); + connect( + m_searchResultsList, + &QListWidget::itemClicked, + this, + &PreferencesSearchController::onSearchResultClicked + ); + // Install event filter for keyboard navigation in search results m_searchResultsList->installEventFilter(m_parentDialog); } @@ -1332,7 +1361,7 @@ void PreferencesSearchController::onSearchTextChanged(const QString& text) hideSearchResultsList(); return; } - + // Only perform new search if text changed if (text != m_lastSearchText) { performSearch(text); @@ -1344,49 +1373,58 @@ void PreferencesSearchController::performSearch(const QString& searchText) { clearHighlights(); m_searchResults.clear(); - + if (searchText.length() < 2) { hideSearchResultsList(); return; } - + // Search through all groups and pages to collect ALL results auto root = m_preferencesModel->invisibleRootItem(); for (int i = 0; i < root->rowCount(); i++) { auto groupItem = static_cast(root->child(i)); auto groupName = groupItem->data(m_groupNameRole).toString(); auto groupStack = qobject_cast(groupItem->getWidget()); - + if (!groupStack) { continue; } - + // Search in each page of the group for (int j = 0; j < groupItem->rowCount(); j++) { auto pageItem = static_cast(groupItem->child(j)); auto pageName = pageItem->data(m_pageNameRole).toString(); auto pageWidget = qobject_cast(pageItem->getWidget()); - + if (!pageWidget) { continue; } - + // Collect all matching widgets in this page - collectSearchResults(pageWidget, searchText, groupName, pageName, pageItem->text(), groupItem->text()); + collectSearchResults( + pageWidget, + searchText, + groupName, + pageName, + pageItem->text(), + groupItem->text() + ); } } - + // Sort results by score (highest first) - std::sort(m_searchResults.begin(), m_searchResults.end(), - [](const SearchResult& a, const SearchResult& b) { - return a.score > b.score; - }); - + std::sort( + m_searchResults.begin(), + m_searchResults.end(), + [](const SearchResult& a, const SearchResult& b) { return a.score > b.score; } + ); + // Update UI with search results if (!m_searchResults.isEmpty()) { populateSearchResultsList(); showSearchResultsList(); - } else { + } + else { hideSearchResultsList(); } } @@ -1404,20 +1442,25 @@ void PreferencesSearchController::clearHighlights() m_originalStyles.clear(); } -void PreferencesSearchController::collectSearchResults(QWidget* widget, const QString& searchText, const QString& groupName, - const QString& pageName, const QString& pageDisplayName, const QString& tabName) +void PreferencesSearchController::collectSearchResults( + QWidget* widget, + const QString& searchText, + const QString& groupName, + const QString& pageName, + const QString& pageDisplayName, + const QString& tabName +) { if (!widget) { return; } - + const QString lowerSearchText = searchText.toLower(); - + // First, check if the page display name itself matches (highest priority) int pageScore = 0; if (fuzzyMatch(searchText, pageDisplayName, pageScore)) { - SearchResult result - { + SearchResult result { .groupName = groupName, .pageName = pageName, .widget = widget, // Use the page widget itself @@ -1425,13 +1468,13 @@ void PreferencesSearchController::collectSearchResults(QWidget* widget, const QS .groupBoxName = QString(), // No groupbox for page-level match .tabName = tabName, .pageDisplayName = pageDisplayName, - .isPageLevelMatch = true, // Mark as page-level match + .isPageLevelMatch = true, // Mark as page-level match .score = pageScore + 2000 // Boost page-level matches }; m_searchResults.append(result); // Continue searching for individual items even if page matches } - + // Search different widget types using the template method searchWidgetType(widget, searchText, groupName, pageName, pageDisplayName, tabName); searchWidgetType(widget, searchText, groupName, pageName, pageDisplayName, tabName); @@ -1446,7 +1489,7 @@ void PreferencesSearchController::onSearchResultSelected() if (m_searchResultsList && m_searchResultsList->currentItem()) { navigateToCurrentSearchResult(PopupAction::KeepOpen); } - + ensureSearchBoxFocus(); } @@ -1456,7 +1499,7 @@ void PreferencesSearchController::onSearchResultClicked() if (m_searchResultsList && m_searchResultsList->currentItem()) { navigateToCurrentSearchResult(PopupAction::KeepOpen); } - + ensureSearchBoxFocus(); } @@ -1471,31 +1514,31 @@ void PreferencesSearchController::onSearchResultDoubleClicked() void PreferencesSearchController::navigateToCurrentSearchResult(PopupAction action) { QListWidgetItem* currentItem = m_searchResultsList->currentItem(); - + // Skip if it's a separator (non-selectable item) or no item selected if (!currentItem || !(currentItem->flags() & Qt::ItemIsSelectable)) { return; } - + // Get the result index directly from the item data bool ok; int resultIndex = currentItem->data(Qt::UserRole).toInt(&ok); - + if (ok && resultIndex >= 0 && resultIndex < m_searchResults.size()) { const SearchResult& result = m_searchResults.at(resultIndex); - + // Emit signal to request navigation Q_EMIT navigationRequested(result.groupName, result.pageName); - + // Clear any existing highlights clearHighlights(); - + // Only highlight specific widgets for non-page-level matches if (!result.isPageLevelMatch && !result.widget.isNull()) { applyHighlightToWidget(result.widget); } // For page-level matches, we just navigate without highlighting anything - + // Close popup only if requested (double-click or Enter) if (action == PopupAction::CloseAfter) { hideSearchResultsList(); @@ -1506,7 +1549,7 @@ void PreferencesSearchController::navigateToCurrentSearchResult(PopupAction acti void PreferencesSearchController::populateSearchResultsList() { m_searchResultsList->clear(); - + for (int i = 0; i < m_searchResults.size(); ++i) { const SearchResult& result = m_searchResults.at(i); @@ -1518,17 +1561,18 @@ void PreferencesSearchController::populateSearchResultsList() // For page matches: parent group as header, page name as content item->setData(PathRole, result.tabName); item->setData(WidgetTextRole, result.pageDisplayName); - } else { + } + else { // For widget matches: full path as header, widget text as content QString pathText = result.tabName + QStringLiteral("/") + result.pageDisplayName; item->setData(PathRole, pathText); item->setData(WidgetTextRole, result.matchText); } - item->setData(Qt::UserRole, i); // Keep existing index storage + item->setData(Qt::UserRole, i); // Keep existing index storage m_searchResultsList->addItem(item); } - + // Select first actual item (not separator) if (!m_searchResults.isEmpty()) { m_searchResultsList->setCurrentRow(0); @@ -1544,11 +1588,11 @@ void PreferencesSearchController::showSearchResultsList() { // Configure popup size and position configurePopupSize(); - + // Show the popup m_searchResultsList->setVisible(true); m_searchResultsList->raise(); - + // Use QTimer to ensure focus returns to search box after Qt finishes processing the popup show event QTimer::singleShot(0, this, [this]() { if (m_searchBox) { @@ -1563,7 +1607,7 @@ QString PreferencesSearchController::findGroupBoxForWidget(QWidget* widget) if (!widget) { return QString(); } - + // Walk up the parent hierarchy to find a QGroupBox QWidget* parent = widget->parentWidget(); while (parent) { @@ -1573,37 +1617,44 @@ QString PreferencesSearchController::findGroupBoxForWidget(QWidget* widget) } parent = parent->parentWidget(); } - + return QString(); } - template -void PreferencesSearchController::searchWidgetType(QWidget* parentWidget, const QString& searchText, const QString& groupName, - const QString& pageName, const QString& pageDisplayName, const QString& tabName) +void PreferencesSearchController::searchWidgetType( + QWidget* parentWidget, + const QString& searchText, + const QString& groupName, + const QString& pageName, + const QString& pageDisplayName, + const QString& tabName +) { const QList widgets = parentWidget->findChildren(); - + for (WidgetType* widget : widgets) { QString widgetText; - + // Get text based on widget type if constexpr (std::is_same_v) { widgetText = widget->text(); - } else if constexpr (std::is_same_v) { - widgetText = widget->text(); - } else if constexpr (std::is_same_v) { - widgetText = widget->text(); - } else if constexpr (std::is_same_v) { + } + else if constexpr (std::is_same_v) { widgetText = widget->text(); } - + else if constexpr (std::is_same_v) { + widgetText = widget->text(); + } + else if constexpr (std::is_same_v) { + widgetText = widget->text(); + } + // Use fuzzy matching instead of simple contains int score = 0; if (fuzzyMatch(searchText, widgetText, score)) { - SearchResult result - { + SearchResult result { .groupName = groupName, .pageName = pageName, .widget = widget, @@ -1625,28 +1676,34 @@ int PreferencesSearchController::calculatePopupHeight(int popupWidth) int itemCount = m_searchResultsList->count(); int visibleItemCount = 0; const int maxVisibleItems = 4; - + for (int i = 0; i < itemCount && visibleItemCount < maxVisibleItems; ++i) { QListWidgetItem* item = m_searchResultsList->item(i); - if (!item) continue; - + if (!item) { + continue; + } + // For separator items, use their widget height if (m_searchResultsList->itemWidget(item)) { totalHeight += m_searchResultsList->itemWidget(item)->sizeHint().height(); - } else { + } + else { // For text items, use the delegate's size hint instead of calculating manually QStyleOptionViewItem option; - option.rect = QRect(0, 0, popupWidth, 100); // Temporary rect for calculation + option.rect = QRect(0, 0, popupWidth, 100); // Temporary rect for calculation option.font = m_searchResultsList->font(); - - QSize delegateSize = m_searchResultsList->itemDelegate()->sizeHint(option, m_searchResultsList->model()->index(i, 0)); + + QSize delegateSize = m_searchResultsList->itemDelegate()->sizeHint( + option, + m_searchResultsList->model()->index(i, 0) + ); totalHeight += delegateSize.height(); - - visibleItemCount++; // Only count actual items, not separators + + visibleItemCount++; // Only count actual items, not separators } } - - return qMax(50, totalHeight); // Minimum 50px height + + return qMax(50, totalHeight); // Minimum 50px height } void PreferencesSearchController::configurePopupSize() @@ -1655,30 +1712,30 @@ void PreferencesSearchController::configurePopupSize() hideSearchResultsList(); return; } - + // Set a fixed width to prevent flashing when content changes - int popupWidth = 300; // Fixed width for consistent appearance + int popupWidth = 300; // Fixed width for consistent appearance m_searchResultsList->setFixedWidth(popupWidth); - + // Calculate and set the height int finalHeight = calculatePopupHeight(popupWidth); m_searchResultsList->setFixedHeight(finalHeight); - + // Position the popup's upper-left corner at the upper-right corner of the search box QPoint globalPos = m_searchBox->mapToGlobal(QPoint(m_searchBox->width(), 0)); - + // Check if popup would go off-screen to the right QScreen* screen = QApplication::screenAt(globalPos); if (!screen) { screen = QApplication::primaryScreen(); } QRect screenGeometry = screen->availableGeometry(); - + // If popup would extend beyond right edge of screen, position it below the search box instead if (globalPos.x() + popupWidth > screenGeometry.right()) { globalPos = m_searchBox->mapToGlobal(QPoint(0, m_searchBox->height())); } - + m_searchResultsList->move(globalPos); } @@ -1689,31 +1746,35 @@ bool PreferencesSearchController::isExactMatch(const QString& searchText, const return targetText.toLower().contains(searchText.toLower()); } -bool PreferencesSearchController::fuzzyMatch(const QString& searchText, const QString& targetText, int& score) +bool PreferencesSearchController::fuzzyMatch( + const QString& searchText, + const QString& targetText, + int& score +) { if (searchText.isEmpty()) { score = 0; return true; } - + const QString lowerSearch = searchText.toLower(); const QString lowerTarget = targetText.toLower(); - + // First check for exact substring match (highest score) if (lowerTarget.contains(lowerSearch)) { // Score based on how early the match appears and how much of the string it covers int matchIndex = lowerTarget.indexOf(lowerSearch); - int coverage = (lowerSearch.length() * 100) / lowerTarget.length(); // Percentage coverage - score = 1000 - matchIndex + coverage; // Higher score for earlier matches and better coverage + int coverage = (lowerSearch.length() * 100) / lowerTarget.length(); // Percentage coverage + score = 1000 - matchIndex + coverage; // Higher score for earlier matches and better coverage return true; } - + // For fuzzy matching, require minimum search length to avoid too many false positives if (lowerSearch.length() < 3) { score = 0; return false; } - + // Fuzzy matching: check if all characters appear in order int searchIndex = 0; int targetIndex = 0; @@ -1721,7 +1782,7 @@ bool PreferencesSearchController::fuzzyMatch(const QString& searchText, const QS int maxConsecutive = 0; int firstMatchIndex = -1; int lastMatchIndex = -1; - + while (searchIndex < lowerSearch.length() && targetIndex < lowerTarget.length()) { if (lowerSearch[searchIndex] == lowerTarget[targetIndex]) { if (firstMatchIndex == -1) { @@ -1731,52 +1792,53 @@ bool PreferencesSearchController::fuzzyMatch(const QString& searchText, const QS searchIndex++; consecutiveMatches++; maxConsecutive = qMax(maxConsecutive, consecutiveMatches); - } else { + } + else { consecutiveMatches = 0; } targetIndex++; } - + // Check if all search characters were found if (searchIndex == lowerSearch.length()) { // Calculate match density - how spread out are the matches? int matchSpan = lastMatchIndex - firstMatchIndex + 1; - int density = (lowerSearch.length() * 100) / matchSpan; // Characters per span - + int density = (lowerSearch.length() * 100) / matchSpan; // Characters per span + // Require minimum density - matches shouldn't be too spread out - if (density < 20) { // Less than 20% density is too sparse + if (density < 20) { // Less than 20% density is too sparse score = 0; return false; } - + // Require minimum coverage of search term int coverage = (lowerSearch.length() * 100) / lowerTarget.length(); - if (coverage < 15 && lowerTarget.length() > 20) { // For long strings, require better coverage + if (coverage < 15 && lowerTarget.length() > 20) { // For long strings, require better coverage score = 0; return false; } - + // Calculate score based on: // - Match density (how compact the matches are) // - Consecutive matches bonus // - Coverage (how much of target string is the search term) // - Position bonus (earlier matches are better) - int densityScore = qMin(density, 100); // Cap at 100 + int densityScore = qMin(density, 100); // Cap at 100 int consecutiveBonus = (maxConsecutive * 30) / lowerSearch.length(); - int coverageScore = qMin(coverage * 2, 100); // Coverage is important - int positionBonus = qMax(0, 50 - firstMatchIndex); // Earlier is better - + int coverageScore = qMin(coverage * 2, 100); // Coverage is important + int positionBonus = qMax(0, 50 - firstMatchIndex); // Earlier is better + score = densityScore + consecutiveBonus + coverageScore + positionBonus; - + // Minimum score threshold for fuzzy matches if (score < 80) { score = 0; return false; } - + return true; } - + score = 0; return false; } @@ -1790,19 +1852,26 @@ void PreferencesSearchController::ensureSearchBoxFocus() QString PreferencesSearchController::getHighlightStyleForWidget(QWidget* widget) { - const QString baseStyle = QStringLiteral("background-color: #E3F2FD; color: #1565C0; border: 2px solid #2196F3; border-radius: 3px;"); - + const QString baseStyle = QStringLiteral( + "background-color: #E3F2FD; color: #1565C0; border: 2px solid #2196F3; border-radius: 3px;" + ); + if (qobject_cast(widget)) { return QStringLiteral("QLabel { ") + baseStyle + QStringLiteral(" padding: 2px; }"); - } else if (qobject_cast(widget)) { + } + else if (qobject_cast(widget)) { return QStringLiteral("QCheckBox { ") + baseStyle + QStringLiteral(" padding: 2px; }"); - } else if (qobject_cast(widget)) { + } + else if (qobject_cast(widget)) { return QStringLiteral("QRadioButton { ") + baseStyle + QStringLiteral(" padding: 2px; }"); - } else if (qobject_cast(widget)) { + } + else if (qobject_cast(widget)) { return QStringLiteral("QGroupBox::title { ") + baseStyle + QStringLiteral(" padding: 2px; }"); - } else if (qobject_cast(widget)) { + } + else if (qobject_cast(widget)) { return QStringLiteral("QPushButton { ") + baseStyle + QStringLiteral(" }"); - } else { + } + else { return QStringLiteral("QWidget { ") + baseStyle + QStringLiteral(" padding: 2px; }"); } } @@ -1812,7 +1881,7 @@ void PreferencesSearchController::applyHighlightToWidget(QWidget* widget) if (!widget) { return; } - + m_originalStyles[widget] = widget->styleSheet(); widget->setStyleSheet(getHighlightStyleForWidget(widget)); m_highlightedWidgets.append(widget); @@ -1823,7 +1892,7 @@ bool PreferencesSearchController::handleSearchBoxKeyPress(QKeyEvent* keyEvent) if (!m_searchResultsList->isVisible() || m_searchResults.isEmpty()) { return false; } - + switch (keyEvent->key()) { case Qt::Key_Down: { // Move selection down in popup, skipping separators @@ -1883,14 +1952,15 @@ bool PreferencesSearchController::handlePopupKeyPress(QKeyEvent* keyEvent) bool PreferencesSearchController::isClickOutsidePopup(QMouseEvent* mouseEvent) { -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QPoint globalPos = mouseEvent->globalPos(); #else QPoint globalPos = mouseEvent->globalPosition().toPoint(); #endif QRect searchBoxRect = QRect(m_searchBox->mapToGlobal(QPoint(0, 0)), m_searchBox->size()); - QRect popupRect = QRect(m_searchResultsList->mapToGlobal(QPoint(0, 0)), m_searchResultsList->size()); - + QRect popupRect + = QRect(m_searchResultsList->mapToGlobal(QPoint(0, 0)), m_searchResultsList->size()); + return !searchBoxRect.contains(globalPos) && !popupRect.contains(globalPos); } @@ -1917,8 +1987,8 @@ bool DlgPreferencesImp::eventFilter(QObject* obj, QEvent* event) // Handle search box focus loss if (obj == ui->searchBox && event->type() == QEvent::FocusOut) { QFocusEvent* focusEvent = static_cast(event); - if (focusEvent->reason() != Qt::PopupFocusReason && - focusEvent->reason() != Qt::MouseFocusReason) { + if (focusEvent->reason() != Qt::PopupFocusReason + && focusEvent->reason() != Qt::MouseFocusReason) { // Only hide if focus is going somewhere else, not due to popup interaction QTimer::singleShot(100, this, [this]() { if (!ui->searchBox->hasFocus() && !m_searchController->isPopupUnderMouse()) { @@ -1934,12 +2004,9 @@ bool DlgPreferencesImp::eventFilter(QObject* obj, QEvent* event) QWidget* widget = qobject_cast(obj); // Check if click is outside search area - if (m_searchController->isPopupVisible() && - obj != m_searchController->getSearchResultsList() && - obj != ui->searchBox && - widget && // Only check if obj is actually a QWidget - !m_searchController->isPopupAncestorOf(widget) && - !ui->searchBox->isAncestorOf(widget)) { + if (m_searchController->isPopupVisible() && obj != m_searchController->getSearchResultsList() + && obj != ui->searchBox && widget && // Only check if obj is actually a QWidget + !m_searchController->isPopupAncestorOf(widget) && !ui->searchBox->isAncestorOf(widget)) { if (m_searchController->isClickOutsidePopup(mouseEvent)) { m_searchController->hideSearchResultsList(); diff --git a/src/Gui/Dialogs/DlgPreferencesImp.h b/src/Gui/Dialogs/DlgPreferencesImp.h index 57c9d367ed..59ce7242fb 100644 --- a/src/Gui/Dialogs/DlgPreferencesImp.h +++ b/src/Gui/Dialogs/DlgPreferencesImp.h @@ -1,26 +1,26 @@ - // SPDX-License-Identifier: LGPL-2.1-or-later +// SPDX-License-Identifier: LGPL-2.1-or-later - /**************************************************************************** - * Copyright (c) 2002 Jürgen Riegel * - * Copyright (c) 2023 FreeCAD Project Association * - * * - * This file is part of FreeCAD. * - * * - * FreeCAD is free software: you can redistribute it and/or modify it * - * under the terms of the GNU Lesser General Public License as * - * published by the Free Software Foundation, either version 2.1 of the * - * License, or (at your option) any later version. * - * * - * FreeCAD 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 * - * Lesser General Public License for more details. * - * * - * You should have received a copy of the GNU Lesser General Public * - * License along with FreeCAD. If not, see * - * . * - * * - ***************************************************************************/ +/**************************************************************************** + * Copyright (c) 2002 Jürgen Riegel * + * Copyright (c) 2023 FreeCAD Project Association * + * * + * This file is part of FreeCAD. * + * * + * FreeCAD is free software: you can redistribute it and/or modify it * + * under the terms of the GNU Lesser General Public License as * + * published by the Free Software Foundation, either version 2.1 of the * + * License, or (at your option) any later version. * + * * + * FreeCAD 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 * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with FreeCAD. If not, see * + * . * + * * + ***************************************************************************/ #ifndef GUI_DIALOG_DLGPREFERENCESIMP_H @@ -41,39 +41,43 @@ class QTabWidget; class QKeyEvent; class QMouseEvent; -namespace Gui::Dialog { +namespace Gui::Dialog +{ class PreferencePage; class Ui_DlgPreferences; class DlgPreferencesImp; -class GuiExport PreferencesSearchController : public QObject +class GuiExport PreferencesSearchController: public QObject { Q_OBJECT private: - enum class PopupAction { - KeepOpen, // don't close popup (used for keyboard navigation) - CloseAfter // close popup (used for mouse clicks and Enter/Return) + enum class PopupAction + { + KeepOpen, // don't close popup (used for keyboard navigation) + CloseAfter // close popup (used for mouse clicks and Enter/Return) }; public: // Custom data roles for separating path and widget text - enum SearchDataRole { - PathRole = Qt::UserRole + 10, // Path to page (e.g., "Display/3D View") - WidgetTextRole = Qt::UserRole + 11 // Text from the widget (e.g., "Enable anti-aliasing") + enum SearchDataRole + { + PathRole = Qt::UserRole + 10, // Path to page (e.g., "Display/3D View") + WidgetTextRole = Qt::UserRole + 11 // Text from the widget (e.g., "Enable anti-aliasing") }; // Search results structure - struct SearchResult { + struct SearchResult + { QString groupName; QString pageName; QPointer widget; QString matchText; QString groupBoxName; - QString tabName; // The tab name (like "Display") - QString pageDisplayName; // The page display name (like "3D View") - bool isPageLevelMatch = false; // True if this is a page title match - int score = 0; // Fuzzy search score for sorting + QString tabName; // The tab name (like "Display") + QString pageDisplayName; // The page display name (like "3D View") + bool isPageLevelMatch = false; // True if this is a page title match + int score = 0; // Fuzzy search score for sorting }; explicit PreferencesSearchController(DlgPreferencesImp* parentDialog, QObject* parent = nullptr); @@ -118,24 +122,36 @@ public Q_SLOTS: private: // Search implementation - void collectSearchResults(QWidget* widget, const QString& searchText, const QString& groupName, - const QString& pageName, const QString& pageDisplayName, const QString& tabName); + void collectSearchResults( + QWidget* widget, + const QString& searchText, + const QString& groupName, + const QString& pageName, + const QString& pageDisplayName, + const QString& tabName + ); void populateSearchResultsList(); - + template - void searchWidgetType(QWidget* parentWidget, const QString& searchText, const QString& groupName, - const QString& pageName, const QString& pageDisplayName, const QString& tabName); + void searchWidgetType( + QWidget* parentWidget, + const QString& searchText, + const QString& groupName, + const QString& pageName, + const QString& pageDisplayName, + const QString& tabName + ); // UI helpers void configurePopupSize(); int calculatePopupHeight(int popupWidth); void applyHighlightToWidget(QWidget* widget); QString getHighlightStyleForWidget(QWidget* widget); - + // Search result navigation void selectNextSearchResult(); void selectPreviousSearchResult(); - + // Utility methods QString findGroupBoxForWidget(QWidget* widget); bool fuzzyMatch(const QString& searchText, const QString& targetText, int& score); @@ -146,11 +162,11 @@ private: QStandardItemModel* m_preferencesModel; int m_groupNameRole; int m_pageNameRole; - + // UI components QLineEdit* m_searchBox; QListWidget* m_searchResultsList; - + // Search state QList m_searchResults; QString m_lastSearchText; @@ -158,7 +174,7 @@ private: QMap m_originalStyles; }; -class PreferencesPageItem : public QStandardItem +class PreferencesPageItem: public QStandardItem { public: QWidget* getWidget() const; @@ -187,8 +203,8 @@ private: * PrefSpinBox, PrefLineEdit, PrefComboBox, PrefListBox, PrefCheckBox, PrefRadioButton and * PrefSlider. If you have compiled and installed the library under src/Tools/plugins/widgets * to QTDIR/plugins/designer you should see the new category "Preferences". - * Moreover you have to make sure to have specified the "prefEntry" and "prefPath" properties for each - * preference widget you have used inside your form in Qt Designer. + * Moreover you have to make sure to have specified the "prefEntry" and "prefPath" properties for + * each preference widget you have used inside your form in Qt Designer. * * \li For each widget inside your page - you want to save or load - you have to call * \->onSave() or \->onRestore(). The best way to this is either to @@ -244,12 +260,13 @@ private: * \see PrefWidget * \author Werner Mayer, Jürgen Riegel */ -class GuiExport DlgPreferencesImp : public QDialog +class GuiExport DlgPreferencesImp: public QDialog { Q_OBJECT - static constexpr double maxScreenWidthCoveragePercent = 0.8; // maximum % of screen width taken by the dialog - static constexpr int minVerticalEmptySpace = 100; // px of vertical space to leave + static constexpr double maxScreenWidthCoveragePercent = 0.8; // maximum % of screen width taken + // by the dialog + static constexpr int minVerticalEmptySpace = 100; // px of vertical space to leave public: static void addPage(const std::string& className, const std::string& group); @@ -258,7 +275,10 @@ public: static void getGroupData(const std::string& group, std::string& icon, QString& tip); static void reloadSettings(); - static PreferencePage* createPreferencePage(const std::string& pageName, const std::string& groupName); + static PreferencePage* createPreferencePage( + const std::string& pageName, + const std::string& groupName + ); explicit DlgPreferencesImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); ~DlgPreferencesImp() override; @@ -271,18 +291,18 @@ public: void activeGroupPage(QString& group, int& index) const; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void showEvent(QShowEvent*) override; bool eventFilter(QObject* obj, QEvent* event) override; protected Q_SLOTS: void onButtonBoxClicked(QAbstractButton*); - void onPageSelected(const QModelIndex &index); + void onPageSelected(const QModelIndex& index); void onStackWidgetChange(int index); - void onGroupExpanded(const QModelIndex &index); - void onGroupCollapsed(const QModelIndex &index); - + void onGroupExpanded(const QModelIndex& index); + void onGroupCollapsed(const QModelIndex& index); + void onNavigationRequested(const QString& groupName, const QString& pageName); private: @@ -311,7 +331,7 @@ private: int minimumPageWidth() const; int minimumDialogWidth(int) const; void expandToMinimumDialogWidth(); - + // Navigation helper for search controller void navigateToSearchResult(const QString& groupName, const QString& pageName); //@} @@ -324,7 +344,8 @@ private: QStandardItemModel _model; QSize _sizeHintOfPages; - struct Group { + struct Group + { std::string iconName; QString tooltip; }; @@ -334,7 +355,7 @@ private: bool invalidParameter; bool canEmbedScrollArea; bool restartRequired; - + // Search controller std::unique_ptr m_searchController; @@ -345,12 +366,13 @@ private: static constexpr char const* GroupNameProperty = "GroupName"; static constexpr char const* PageNameProperty = "PageName"; - static DlgPreferencesImp* _activeDialog; /**< Defaults to the nullptr, points to the current instance if there is one */ + static DlgPreferencesImp* _activeDialog; /**< Defaults to the nullptr, points to the current + instance if there is one */ // Friend class to allow search controller access to UI friend class PreferencesSearchController; }; -} // namespace Gui +} // namespace Gui::Dialog -#endif // GUI_DIALOG_DLGPREFERENCESIMP_H +#endif // GUI_DIALOG_DLGPREFERENCESIMP_H diff --git a/src/Gui/Dialogs/DlgProjectInformationImp.cpp b/src/Gui/Dialogs/DlgProjectInformationImp.cpp index e8844e2631..dd9fc8cef5 100644 --- a/src/Gui/Dialogs/DlgProjectInformationImp.cpp +++ b/src/Gui/Dialogs/DlgProjectInformationImp.cpp @@ -63,9 +63,7 @@ using namespace Gui::Dialog; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, - QWidget* parent, - Qt::WindowFlags fl) +DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, QWidget* parent, Qt::WindowFlags fl) : QDialog(parent, fl) , _doc(doc) , ui(new Ui_DlgProjectInformation) @@ -129,14 +127,13 @@ DlgProjectInformationImp::DlgProjectInformationImp(App::Document* doc, QString text = lines.join(QLatin1String("\n")); ui->textEditComment->setPlainText(text); - connect(ui->pushButtonOpenURL, - &QPushButton::clicked, - this, - &DlgProjectInformationImp::open_url); - connect(ui->comboLicense, - qOverload(&QComboBox::currentIndexChanged), - this, - &DlgProjectInformationImp::onLicenseTypeChanged); + connect(ui->pushButtonOpenURL, &QPushButton::clicked, this, &DlgProjectInformationImp::open_url); + connect( + ui->comboLicense, + qOverload(&QComboBox::currentIndexChanged), + this, + &DlgProjectInformationImp::onLicenseTypeChanged + ); } /** @@ -166,8 +163,8 @@ void DlgProjectInformationImp::accept() _doc->LicenseURL.setValue(ui->lineEditLicenseURL->text().toUtf8()); // Replace newline escape sequence through '\\n' string - QStringList lines = - ui->textEditComment->toPlainText().split(QLatin1String("\n"), Qt::KeepEmptyParts); + QStringList lines + = ui->textEditComment->toPlainText().split(QLatin1String("\n"), Qt::KeepEmptyParts); QString text = lines.join(QLatin1String("\\n")); _doc->Comment.setValue(text.isEmpty() ? QByteArray() : text.toUtf8()); @@ -177,9 +174,10 @@ void DlgProjectInformationImp::accept() void DlgProjectInformationImp::onLicenseTypeChanged(int index) { - const char* url {index >= 0 && index < App::countOfLicenses - ? App::licenseItems.at(index).at(App::posnOfUrl) - : _doc->LicenseURL.getValue()}; + const char* url { + index >= 0 && index < App::countOfLicenses ? App::licenseItems.at(index).at(App::posnOfUrl) + : _doc->LicenseURL.getValue() + }; ui->lineEditLicenseURL->setText(QString::fromLatin1(url)); } diff --git a/src/Gui/Dialogs/DlgProjectInformationImp.h b/src/Gui/Dialogs/DlgProjectInformationImp.h index 235d8f0fc2..32b64779f6 100644 --- a/src/Gui/Dialogs/DlgProjectInformationImp.h +++ b/src/Gui/Dialogs/DlgProjectInformationImp.h @@ -26,21 +26,28 @@ #include -namespace App { +namespace App +{ class Document; } -namespace Gui { +namespace Gui +{ -namespace Dialog { +namespace Dialog +{ class Ui_DlgProjectInformation; -class DlgProjectInformationImp : public QDialog +class DlgProjectInformationImp: public QDialog { Q_OBJECT public: - DlgProjectInformationImp(App::Document* doc, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + DlgProjectInformationImp( + App::Document* doc, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~DlgProjectInformationImp() override; void accept() override; @@ -53,9 +60,8 @@ private: Ui_DlgProjectInformation* ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGPROJECTINFORMATIONIMP_H - +#endif // GUI_DIALOG_DLGPROJECTINFORMATIONIMP_H diff --git a/src/Gui/Dialogs/DlgProjectUtility.cpp b/src/Gui/Dialogs/DlgProjectUtility.cpp index 0a2123c7ee..81926e0e2c 100644 --- a/src/Gui/Dialogs/DlgProjectUtility.cpp +++ b/src/Gui/Dialogs/DlgProjectUtility.cpp @@ -38,8 +38,8 @@ using namespace Gui::Dialog; /* TRANSLATOR Gui::Dialog::DlgProjectUtility */ DlgProjectUtility::DlgProjectUtility(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) - , ui(new Ui_DlgProjectUtility) + : QDialog(parent, fl) + , ui(new Ui_DlgProjectUtility) { ui->setupUi(this); connect(ui->extractButton, &QPushButton::clicked, this, &DlgProjectUtility::extractButton); @@ -93,8 +93,8 @@ void DlgProjectUtility::tryExtractArchive(const QString& source, const QString& try { std::stringstream str; str << "from freecad import project_utility\n"; - str << "project_utility.extractDocument(\"" << (const char*)source.toUtf8() - << "\", \"" << (const char*)target.toUtf8() << "\")"; + str << "project_utility.extractDocument(\"" << (const char*)source.toUtf8() << "\", \"" + << (const char*)target.toUtf8() << "\")"; Gui::Command::runCommand(Gui::Command::App, str.str().c_str()); } catch (const Base::Exception& e) { @@ -107,11 +107,11 @@ void DlgProjectUtility::tryCreateArchive(const QString& source, const QString& t try { std::stringstream str; str << "from freecad import project_utility\n"; - str << "project_utility.createDocument(\"" << (const char*)source.toUtf8() - << "\", \"" << (const char*)target.toUtf8() << "\")"; + str << "project_utility.createDocument(\"" << (const char*)source.toUtf8() << "\", \"" + << (const char*)target.toUtf8() << "\")"; Gui::Command::runCommand(Gui::Command::App, str.str().c_str()); if (openFile) { - Application::Instance->open((const char*)target.toUtf8(),"FreeCAD"); + Application::Instance->open((const char*)target.toUtf8(), "FreeCAD"); } } catch (const Base::Exception& e) { diff --git a/src/Gui/Dialogs/DlgProjectUtility.h b/src/Gui/Dialogs/DlgProjectUtility.h index 3408bcd987..4580f5b08c 100644 --- a/src/Gui/Dialogs/DlgProjectUtility.h +++ b/src/Gui/Dialogs/DlgProjectUtility.h @@ -28,10 +28,13 @@ #include #include -namespace Gui { namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgProjectUtility; -class DlgProjectUtility : public QDialog +class DlgProjectUtility: public QDialog { Q_OBJECT @@ -49,9 +52,8 @@ protected: std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGPROJECTUTILITY_H - +#endif // GUI_DIALOG_DLGPROJECTUTILITY_H diff --git a/src/Gui/Dialogs/DlgPropertyLink.cpp b/src/Gui/Dialogs/DlgPropertyLink.cpp index b135c14347..955c4d2b54 100644 --- a/src/Gui/Dialogs/DlgPropertyLink.cpp +++ b/src/Gui/Dialogs/DlgPropertyLink.cpp @@ -55,9 +55,11 @@ public: : QStyledItemDelegate(parent) {} - QWidget* createEditor(QWidget* parent, - const QStyleOptionViewItem& option, - const QModelIndex& index) const override + QWidget* createEditor( + QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override { if (index.column() != 1) { return nullptr; @@ -152,8 +154,7 @@ QList DlgPropertyLink::getLinksFromProperty(const App::Property return res; } -QString -DlgPropertyLink::formatObject(App::Document* ownerDoc, App::DocumentObject* obj, const char* sub) +QString DlgPropertyLink::formatObject(App::Document* ownerDoc, App::DocumentObject* obj, const char* sub) { if (!obj || !obj->isAttachedToDocument()) { return QLatin1String("?"); @@ -170,8 +171,10 @@ DlgPropertyLink::formatObject(App::Document* ownerDoc, App::DocumentObject* obj, if (obj->Label.getStrValue() == obj->getNameInDocument()) { return QLatin1String(objName); } - return QStringLiteral("%1 (%2)").arg(QString::fromUtf8(obj->Label.getValue()), - QLatin1String(objName)); + return QStringLiteral("%1 (%2)").arg( + QString::fromUtf8(obj->Label.getValue()), + QLatin1String(objName) + ); } auto sobj = obj->getSubObject(sub); @@ -180,9 +183,7 @@ DlgPropertyLink::formatObject(App::Document* ownerDoc, App::DocumentObject* obj, } return QStringLiteral("%1 (%2.%3)") - .arg(QString::fromUtf8(sobj->Label.getValue()), - QLatin1String(objName), - QString::fromUtf8(sub)); + .arg(QString::fromUtf8(sobj->Label.getValue()), QLatin1String(objName), QString::fromUtf8(sub)); } static inline bool isLinkSub(const QList& links) @@ -224,9 +225,11 @@ QString DlgPropertyLink::formatLinks(App::Document* ownerDoc, QList 3 ? " ..." : "")); + .arg( + formatObject(ownerDoc, obj, nullptr), + list.join(QLatin1String(", ")), + QLatin1String(links.size() > 3 ? " ..." : "") + ); } int i = 0; @@ -236,8 +239,10 @@ QString DlgPropertyLink::formatLinks(App::Document* ownerDoc, QList 3 ? " ..." : "")); + return QStringLiteral("[%1%2]").arg( + list.join(QLatin1String(", ")), + QLatin1String(links.size() > 3 ? " ..." : "") + ); } void DlgPropertyLink::init(const App::DocumentObjectT& prop, bool tryFilter) @@ -387,10 +392,14 @@ void DlgPropertyLink::init(const App::DocumentObjectT& prop, bool tryFilter) QSignalBlocker blockTree(ui->treeWidget); QSignalBlocker blockSelectionModel(ui->treeWidget->selectionModel()); for (auto& link : oldLinks) { - onSelectionChanged(Gui::SelectionChanges(SelectionChanges::AddSelection, - link.getDocumentName(), - link.getObjectName(), - link.getSubName())); + onSelectionChanged( + Gui::SelectionChanges( + SelectionChanges::AddSelection, + link.getDocumentName(), + link.getObjectName(), + link.getSubName() + ) + ); } } @@ -406,8 +415,7 @@ void DlgPropertyLink::init(const App::DocumentObjectT& prop, bool tryFilter) objType = obj->getTypeId(); continue; } - for (; objType != App::DocumentObject::getClassTypeId(); - objType = objType.getParent()) { + for (; objType != App::DocumentObject::getClassTypeId(); objType = objType.getParent()) { if (obj->isDerivedFrom(objType)) { break; } @@ -538,9 +546,11 @@ void DlgPropertyLink::detachObserver() } for (auto& sel : savedSelections) { if (sel.getSubObject()) { - Gui::Selection().addSelection(sel.getDocumentName().c_str(), - sel.getObjectName().c_str(), - sel.getSubName().c_str()); + Gui::Selection().addSelection( + sel.getDocumentName().c_str(), + sel.getObjectName().c_str(), + sel.getSubName().c_str() + ); } } savedSelections.clear(); @@ -579,8 +589,7 @@ void DlgPropertyLink::onItemSelectionChanged() focus = ui->treeWidget->hasFocus(); auto doc = Gui::Application::Instance->getDocument(sobjs.front().getDocumentName().c_str()); if (doc) { - auto vp = freecad_cast( - doc->getViewProvider(obj)); + auto vp = freecad_cast(doc->getViewProvider(obj)); if (vp) { // If the view provider uses a special window for rendering, switch to it MDIView* view = vp->getMDIView(); @@ -599,9 +608,11 @@ void DlgPropertyLink::onItemSelectionChanged() bool blocked = blockSelection(true); Gui::Selection().clearSelection(); for (auto& sobj : sobjs) { - Gui::Selection().addSelection(sobj.getDocumentName().c_str(), - sobj.getObjectName().c_str(), - sobj.getSubName().c_str()); + Gui::Selection().addSelection( + sobj.getDocumentName().c_str(), + sobj.getObjectName().c_str(), + sobj.getSubName().c_str() + ); } blockSelection(blocked); @@ -627,8 +638,7 @@ void DlgPropertyLink::onItemSelectionChanged() } } -QTreeWidgetItem* -DlgPropertyLink::findItem(App::DocumentObject* obj, const char* subname, bool* pfound) +QTreeWidgetItem* DlgPropertyLink::findItem(App::DocumentObject* obj, const char* subname, bool* pfound) { if (pfound) { *pfound = false; @@ -681,8 +691,7 @@ DlgPropertyLink::findItem(App::DocumentObject* obj, const char* subname, bool* p bool found = false; for (int i = 0, count = item->childCount(); i < count; ++i) { auto child = item->child(i); - if (strcmp(o->getNameInDocument(), - child->data(0, Qt::UserRole).toByteArray().constData()) + if (strcmp(o->getNameInDocument(), child->data(0, Qt::UserRole).toByteArray().constData()) == 0) { item = child; found = true; @@ -760,8 +769,7 @@ void DlgPropertyLink::accept() QDialog::accept(); } -static QTreeWidgetItem* -_getLinkFromItem(std::ostringstream& ss, QTreeWidgetItem* item, const char* objName) +static QTreeWidgetItem* _getLinkFromItem(std::ostringstream& ss, QTreeWidgetItem* item, const char* objName) { auto parent = item->parent(); assert(parent); @@ -775,8 +783,7 @@ _getLinkFromItem(std::ostringstream& ss, QTreeWidgetItem* item, const char* objN return item; } -QList DlgPropertyLink::getLinkFromItem(QTreeWidgetItem* item, - bool needSubName) const +QList DlgPropertyLink::getLinkFromItem(QTreeWidgetItem* item, bool needSubName) const { QList res; @@ -786,12 +793,13 @@ QList DlgPropertyLink::getLinkFromItem(QTreeWidgetItem* item, } std::ostringstream ss; - auto parentItem = - _getLinkFromItem(ss, item, item->data(0, Qt::UserRole).toByteArray().constData()); + auto parentItem = _getLinkFromItem(ss, item, item->data(0, Qt::UserRole).toByteArray().constData()); - App::SubObjectT sobj(parentItem->data(0, Qt::UserRole + 1).toByteArray().constData(), - parentItem->data(0, Qt::UserRole).toByteArray().constData(), - ss.str().c_str()); + App::SubObjectT sobj( + parentItem->data(0, Qt::UserRole + 1).toByteArray().constData(), + parentItem->data(0, Qt::UserRole).toByteArray().constData(), + ss.str().c_str() + ); QString elements; if (needSubName && allowSubObject) { @@ -807,9 +815,11 @@ QList DlgPropertyLink::getLinkFromItem(QTreeWidgetItem* item, const auto split = elements.split(QLatin1Char(',')); for (const QString& element : split) { res.append(App::SubObjectT()); - res.last() = App::SubObjectT(sobj.getDocumentName().c_str(), - sobj.getObjectName().c_str(), - (sobj.getSubName() + element.toLatin1().constData()).c_str()); + res.last() = App::SubObjectT( + sobj.getDocumentName().c_str(), + sobj.getObjectName().c_str(), + (sobj.getSubName() + element.toLatin1().constData()).c_str() + ); } return res; } @@ -825,13 +835,15 @@ void DlgPropertyLink::onTimer() return; } const auto& sobj = sobjs.front(); - Gui::Selection().setPreselect(sobj.getDocumentName().c_str(), - sobj.getObjectName().c_str(), - sobj.getSubName().c_str(), - 0, - 0, - 0, - Gui::SelectionChanges::MsgSource::TreeView); + Gui::Selection().setPreselect( + sobj.getDocumentName().c_str(), + sobj.getObjectName().c_str(), + sobj.getSubName().c_str(), + 0, + 0, + 0, + Gui::SelectionChanges::MsgSource::TreeView + ); } QList DlgPropertyLink::currentLinks() const @@ -983,18 +995,19 @@ void DlgPropertyLink::itemSearch(const QString& text, bool select) if (!found) { return; } - Gui::Selection().addSelection(obj->getDocument()->getName(), - obj->getNameInDocument(), - subname); + Gui::Selection() + .addSelection(obj->getDocument()->getName(), obj->getNameInDocument(), subname); } else { - Selection().setPreselect(obj->getDocument()->getName(), - obj->getNameInDocument(), - subname, - 0, - 0, - 0, - Gui::SelectionChanges::MsgSource::TreeView); + Selection().setPreselect( + obj->getDocument()->getName(), + obj->getNameInDocument(), + subname, + 0, + 0, + 0, + Gui::SelectionChanges::MsgSource::TreeView + ); searchItem = item; ui->treeWidget->scrollToItem(searchItem); bgBrush = searchItem->background(0); @@ -1015,8 +1028,7 @@ QTreeWidgetItem* DlgPropertyLink::createItem(App::DocumentObject* obj, QTreeWidg return nullptr; } - auto vp = freecad_cast( - Application::Instance->getViewProvider(obj)); + auto vp = freecad_cast(Application::Instance->getViewProvider(obj)); if (!vp) { return nullptr; } @@ -1034,9 +1046,10 @@ QTreeWidgetItem* DlgPropertyLink::createItem(App::DocumentObject* obj, QTreeWidg item->setData(0, Qt::UserRole + 1, QByteArray(obj->getDocument()->getName())); if (allowSubObject) { - item->setChildIndicatorPolicy(!obj->getLinkedObject(true)->getOutList().empty() - ? QTreeWidgetItem::ShowIndicator - : QTreeWidgetItem::DontShowIndicator); + item->setChildIndicatorPolicy( + !obj->getLinkedObject(true)->getOutList().empty() ? QTreeWidgetItem::ShowIndicator + : QTreeWidgetItem::DontShowIndicator + ); item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable); } @@ -1045,8 +1058,7 @@ QTreeWidgetItem* DlgPropertyLink::createItem(App::DocumentObject* obj, QTreeWidg item->setData(0, Qt::UserRole + 2, typeData); QByteArray proxyType; - auto prop = - freecad_cast(obj->getPropertyByName("Proxy")); + auto prop = freecad_cast(obj->getPropertyByName("Proxy")); if (prop) { Base::PyGILStateLocker lock; Py::Object proxy = prop->getValue(); @@ -1151,8 +1163,7 @@ bool DlgPropertyLink::filterType(QTreeWidgetItem* item) return false; } - for (auto t = type; !t.isBad() && t != App::DocumentObject::getClassTypeId(); - t = t.getParent()) { + for (auto t = type; !t.isBad() && t != App::DocumentObject::getClassTypeId(); t = t.getParent()) { const char* name = t.getName(); if (selectedTypes.count(QByteArray::fromRawData(name, strlen(name) + 1))) { return false; diff --git a/src/Gui/Dialogs/DlgPropertyLink.h b/src/Gui/Dialogs/DlgPropertyLink.h index 49bdb57c30..2cb6b9daa1 100644 --- a/src/Gui/Dialogs/DlgPropertyLink.h +++ b/src/Gui/Dialogs/DlgPropertyLink.h @@ -33,10 +33,13 @@ class QTreeWidgetItem; -namespace Gui { namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgPropertyLink; -class DlgPropertyLink : public QDialog, public Gui::SelectionObserver +class DlgPropertyLink: public QDialog, public Gui::SelectionObserver { Q_OBJECT @@ -49,27 +52,28 @@ public: QList currentLinks() const; QList originalLinks() const; - void init(const App::DocumentObjectT &prop, bool tryFilter=true); + void init(const App::DocumentObjectT& prop, bool tryFilter = true); static QString linksToPython(const QList& links); - static QList getLinksFromProperty(const App::PropertyLinkBase *prop); + static QList getLinksFromProperty(const App::PropertyLinkBase* prop); - static QString formatObject(App::Document *ownerDoc, App::DocumentObject *obj, const char *sub); + static QString formatObject(App::Document* ownerDoc, App::DocumentObject* obj, const char* sub); - static inline QString formatObject(App::Document *ownerDoc, const App::SubObjectT &sobj) { + static inline QString formatObject(App::Document* ownerDoc, const App::SubObjectT& sobj) + { return formatObject(ownerDoc, sobj.getObject(), sobj.getSubName().c_str()); } - static QString formatLinks(App::Document *ownerDoc, QList links); + static QString formatLinks(App::Document* ownerDoc, QList links); protected: - void showEvent(QShowEvent *) override; - void hideEvent(QHideEvent *) override; - void closeEvent (QCloseEvent * e) override; - void leaveEvent(QEvent *) override; - bool eventFilter(QObject *obj, QEvent *ev) override; - void keyPressEvent(QKeyEvent *ev) override; + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; + void closeEvent(QCloseEvent* e) override; + void leaveEvent(QEvent*) override; + bool eventFilter(QObject* obj, QEvent* ev) override; + void keyPressEvent(QKeyEvent* ev) override; void detachObserver(); void attachObserver(); @@ -80,28 +84,32 @@ private: void onObjectTypeToggled(bool); void onTypeTreeItemSelectionChanged(); void onSearchBoxTextChanged(const QString&); - void onItemExpanded(QTreeWidgetItem * item); + void onItemExpanded(QTreeWidgetItem* item); void onItemSelectionChanged(); - void onItemEntered(QTreeWidgetItem *item); + void onItemEntered(QTreeWidgetItem* item); void onItemSearch(); void onTimer(); - void onClicked(QAbstractButton *); + void onClicked(QAbstractButton*); private: - QTreeWidgetItem *createItem(App::DocumentObject *obj, QTreeWidgetItem *parent); - QTreeWidgetItem *createTypeItem(Base::Type type); + QTreeWidgetItem* createItem(App::DocumentObject* obj, QTreeWidgetItem* parent); + QTreeWidgetItem* createTypeItem(Base::Type type); void filterObjects(); - void filterItem(QTreeWidgetItem *item); - bool filterType(QTreeWidgetItem *item); - QTreeWidgetItem *findItem(App::DocumentObject *obj, const char *subname=nullptr, bool *found=nullptr); - void itemSearch(const QString &text, bool select); - QList getLinkFromItem(QTreeWidgetItem *, bool needSubName=true) const; + void filterItem(QTreeWidgetItem* item); + bool filterType(QTreeWidgetItem* item); + QTreeWidgetItem* findItem( + App::DocumentObject* obj, + const char* subname = nullptr, + bool* found = nullptr + ); + void itemSearch(const QString& text, bool select); + QList getLinkFromItem(QTreeWidgetItem*, bool needSubName = true) const; private: Ui_DlgPropertyLink* ui; - QTimer *timer; - QPushButton *resetButton; - QPushButton *refreshButton; + QTimer* timer; + QPushButton* resetButton; + QPushButton* refreshButton; QPointer parentView; std::vector savedSelections; @@ -118,14 +126,13 @@ private: bool allowSubObject = false; bool singleSelect = false; bool singleParent = false; - App::DocumentObject *currentObj = nullptr; - QTreeWidgetItem *searchItem = nullptr; + App::DocumentObject* currentObj = nullptr; + QTreeWidgetItem* searchItem = nullptr; QBrush bgBrush; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGPROPERTYLINK_H - +#endif // GUI_DIALOG_DLGPROPERTYLINK_H diff --git a/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp b/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp index 8c1f208b48..cb254df312 100644 --- a/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp +++ b/src/Gui/Dialogs/DlgRevertToBackupConfigImp.cpp @@ -20,8 +20,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include "Dialogs/DlgRevertToBackupConfigImp.h" #include "ui_DlgRevertToBackupConfig.h" @@ -40,7 +40,12 @@ DlgRevertToBackupConfigImp::DlgRevertToBackupConfigImp(QWidget* parent) , ui(new Ui_DlgRevertToBackupConfig) { ui->setupUi(this); - connect(ui->listWidget, &QListWidget::itemSelectionChanged, this, &DlgRevertToBackupConfigImp::onItemSelectionChanged); + connect( + ui->listWidget, + &QListWidget::itemSelectionChanged, + this, + &DlgRevertToBackupConfigImp::onItemSelectionChanged + ); } DlgRevertToBackupConfigImp::~DlgRevertToBackupConfigImp() = default; @@ -48,17 +53,18 @@ DlgRevertToBackupConfigImp::~DlgRevertToBackupConfigImp() = default; void Gui::Dialog::DlgRevertToBackupConfigImp::onItemSelectionChanged() { auto items = ui->listWidget->selectedItems(); - if (items.count() == 1) + if (items.count() == 1) { ui->buttonBox->button(QDialogButtonBox::StandardButton::Ok)->setEnabled(true); - else + } + else { ui->buttonBox->button(QDialogButtonBox::StandardButton::Ok)->setEnabled(false); - + } } /** * Sets the strings of the subwidgets using the current language. */ -void DlgRevertToBackupConfigImp::changeEvent(QEvent *e) +void DlgRevertToBackupConfigImp::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -69,12 +75,11 @@ void DlgRevertToBackupConfigImp::changeEvent(QEvent *e) } // FIXME: Replace with more accurate C++20 solution once its usable: https://stackoverflow.com/a/68593141 -template +template static std::time_t to_time_t(TP tp) { using namespace std::chrono; - auto sctp = time_point_cast(tp - TP::clock::now() - + system_clock::now()); + auto sctp = time_point_cast(tp - TP::clock::now() + system_clock::now()); return system_clock::to_time_t(sctp); } @@ -96,7 +101,9 @@ void DlgRevertToBackupConfigImp::accept() { auto items = ui->listWidget->selectedItems(); if (items.count() != 1) { - Base::Console().error(tr("No selection in dialog, cannot load backup file").toStdString().c_str()); + Base::Console().error( + tr("No selection in dialog, cannot load backup file").toStdString().c_str() + ); return; } auto item = items[0]; diff --git a/src/Gui/Dialogs/DlgRevertToBackupConfigImp.h b/src/Gui/Dialogs/DlgRevertToBackupConfigImp.h index 0728304014..f3ff3a1cb8 100644 --- a/src/Gui/Dialogs/DlgRevertToBackupConfigImp.h +++ b/src/Gui/Dialogs/DlgRevertToBackupConfigImp.h @@ -27,19 +27,21 @@ #include #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgRevertToBackupConfig; /** The DlgRevertToBackupConfigImp class * \author Chris Hennes */ -class DlgRevertToBackupConfigImp : public QDialog +class DlgRevertToBackupConfigImp: public QDialog { Q_OBJECT public: - explicit DlgRevertToBackupConfigImp( QWidget* parent = nullptr ); + explicit DlgRevertToBackupConfigImp(QWidget* parent = nullptr); ~DlgRevertToBackupConfigImp() override; public Q_SLOTS: @@ -47,14 +49,14 @@ public Q_SLOTS: void onItemSelectionChanged(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void showEvent(QShowEvent* event) override; private: std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif //GUI_DIALOG_DLG_REVERT_TO_BACKUP_CONFIG_IMP +#endif // GUI_DIALOG_DLG_REVERT_TO_BACKUP_CONFIG_IMP diff --git a/src/Gui/Dialogs/DlgRunExternal.h b/src/Gui/Dialogs/DlgRunExternal.h index 8ce3eb6b26..3f06f63f62 100644 --- a/src/Gui/Dialogs/DlgRunExternal.h +++ b/src/Gui/Dialogs/DlgRunExternal.h @@ -28,8 +28,10 @@ #include #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgRunExternal; /** @@ -37,7 +39,7 @@ class Ui_DlgRunExternal; * programs to edit FreeCAD controlled content. * \author Jürgen Riegel */ -class GuiExport DlgRunExternal : public QDialog +class GuiExport DlgRunExternal: public QDialog { Q_OBJECT @@ -53,7 +55,7 @@ protected Q_SLOTS: void accept() override; virtual void abort(); virtual void advanced(); - void finished (int exitCode, QProcess::ExitStatus exitStatus); + void finished(int exitCode, QProcess::ExitStatus exitStatus); void onChooseProgramClicked(); private: @@ -64,7 +66,7 @@ private: std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DlgRunExternal_H +#endif // GUI_DIALOG_DlgRunExternal_H diff --git a/src/Gui/Dialogs/DlgSettingsColorGradientImp.cpp b/src/Gui/Dialogs/DlgSettingsColorGradientImp.cpp index 98a77b6895..04f34b2fc0 100644 --- a/src/Gui/Dialogs/DlgSettingsColorGradientImp.cpp +++ b/src/Gui/Dialogs/DlgSettingsColorGradientImp.cpp @@ -42,9 +42,11 @@ using namespace Gui::Dialog; * Constructs a DlgSettingsColorGradientImp as a child of 'parent', with the * name 'name' and widget flags set to 'f'. */ -DlgSettingsColorGradientImp::DlgSettingsColorGradientImp(const App::ColorGradient& cg, - QWidget* parent, - Qt::WindowFlags fl) +DlgSettingsColorGradientImp::DlgSettingsColorGradientImp( + const App::ColorGradient& cg, + QWidget* parent, + Qt::WindowFlags fl +) : QDialog(parent, fl) , validator(nullptr) , ui(new Ui_DlgSettingsColorGradient) @@ -66,7 +68,8 @@ DlgSettingsColorGradientImp::DlgSettingsColorGradientImp(const App::ColorGradien // assure that the LineEdit is as wide to contain numbers with 4 digits and 6 decimals QFontMetrics fm(ui->floatLineEditMax->font()); ui->floatLineEditMax->setMinimumWidth( - QtTools::horizontalAdvance(fm, QStringLiteral("-8000.000000"))); + QtTools::horizontalAdvance(fm, QStringLiteral("-8000.000000")) + ); setColorModelNames(cg.getColorModelNames()); setProfile(cg.getProfile()); @@ -246,9 +249,11 @@ void DlgSettingsColorGradientImp::accept() double fMin = QLocale().toDouble(ui->floatLineEditMin->text()); if (fMax <= fMin) { - QMessageBox::warning(this, - tr("Wrong parameter"), - tr("The maximum value must be higher than the minimum value.")); + QMessageBox::warning( + this, + tr("Wrong parameter"), + tr("The maximum value must be higher than the minimum value.") + ); } else { QDialog::accept(); diff --git a/src/Gui/Dialogs/DlgSettingsColorGradientImp.h b/src/Gui/Dialogs/DlgSettingsColorGradientImp.h index 3f39463738..00077e8093 100644 --- a/src/Gui/Dialogs/DlgSettingsColorGradientImp.h +++ b/src/Gui/Dialogs/DlgSettingsColorGradientImp.h @@ -30,8 +30,10 @@ class QDoubleValidator; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgSettingsColorGradient; /** @@ -39,14 +41,16 @@ class Ui_DlgSettingsColorGradient; * for the color gradient bar. * @author Werner Mayer */ -class DlgSettingsColorGradientImp : public QDialog +class DlgSettingsColorGradientImp: public QDialog { Q_OBJECT public: - explicit DlgSettingsColorGradientImp(const App::ColorGradient& cg, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit DlgSettingsColorGradientImp( + const App::ColorGradient& cg, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~DlgSettingsColorGradientImp() override; void accept() override; @@ -73,14 +77,14 @@ private: //@} /** @name Color style */ //@{ - void setColorStyle( App::ColorBarStyle tStyle ); + void setColorStyle(App::ColorBarStyle tStyle); App::ColorBarStyle colorStyle() const; //@} /** @name Display mode */ //@{ - void setOutGrayed( bool grayed ); + void setOutGrayed(bool grayed); bool isOutGrayed() const; - void setOutInvisible( bool invisible ); + void setOutInvisible(bool invisible); bool isOutInvisible() const; //@} /** @name Parameter range and scale */ @@ -99,7 +103,7 @@ private: std::unique_ptr ui; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGSETTINGSCOLORGRADIENT_IMP_H +#endif // GUI_DIALOG_DLGSETTINGSCOLORGRADIENT_IMP_H diff --git a/src/Gui/Dialogs/DlgSettingsImageImp.cpp b/src/Gui/Dialogs/DlgSettingsImageImp.cpp index ca85affcc8..112ca223d6 100644 --- a/src/Gui/Dialogs/DlgSettingsImageImp.cpp +++ b/src/Gui/Dialogs/DlgSettingsImageImp.cpp @@ -182,8 +182,9 @@ bool DlgSettingsImageImp::addWatermark() const void DlgSettingsImageImp::onSelectedFilter(const QString& filter) { - bool ok = (filter.startsWith(QLatin1String("JPG")) || filter.startsWith(QLatin1String("JPEG")) - || filter.startsWith(QLatin1String("PNG"))); + bool ok + = (filter.startsWith(QLatin1String("JPG")) || filter.startsWith(QLatin1String("JPEG")) + || filter.startsWith(QLatin1String("PNG"))); ui->buttonGroupComment->setEnabled(ok); } diff --git a/src/Gui/Dialogs/DlgSettingsImageImp.h b/src/Gui/Dialogs/DlgSettingsImageImp.h index 520c6a73f2..f54a2ac869 100644 --- a/src/Gui/Dialogs/DlgSettingsImageImp.h +++ b/src/Gui/Dialogs/DlgSettingsImageImp.h @@ -29,8 +29,10 @@ #include #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgSettingsImage; /** @@ -38,18 +40,18 @@ class Ui_DlgSettingsImage; * for the Inventor viewer. * @author Werner Mayer */ -class DlgSettingsImageImp : public QWidget +class DlgSettingsImageImp: public QWidget { Q_OBJECT public: - explicit DlgSettingsImageImp( QWidget* parent = nullptr ); + explicit DlgSettingsImageImp(QWidget* parent = nullptr); ~DlgSettingsImageImp() override; /** @name Image dimensions */ //@{ - void setImageSize( int, int ); - void setImageSize( const QSize& ); + void setImageSize(int, int); + void setImageSize(const QSize&); QSize imageSize() const; int imageWidth() const; int imageHeight() const; @@ -61,12 +63,12 @@ public: QByteArray method() const; QString comment() const; int backgroundType() const; - void setBackgroundType( int ); + void setBackgroundType(int); bool addWatermark() const; //@} public Q_SLOTS: - void onSelectedFilter( const QString& ); + void onSelectedFilter(const QString&); protected: void setupConnections(); @@ -80,7 +82,7 @@ protected: protected: // helper to force an aspect ratio void adjustImageSize(float fRatio); - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: @@ -90,7 +92,7 @@ private: SbMatrix _Matrix; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGSETTINGSIMAGE_IMP_H +#endif // GUI_DIALOG_DLGSETTINGSIMAGE_IMP_H diff --git a/src/Gui/Dialogs/DlgThemeEditor.cpp b/src/Gui/Dialogs/DlgThemeEditor.cpp index 75bcb26505..a0e50c083d 100644 --- a/src/Gui/Dialogs/DlgThemeEditor.cpp +++ b/src/Gui/Dialogs/DlgThemeEditor.cpp @@ -32,23 +32,23 @@ #include #include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include QPixmap colorPreview(const QColor& color) { constexpr qsizetype size = 16; - QPixmap preview = Gui::BitmapFactory().empty({ size, size }); + QPixmap preview = Gui::BitmapFactory().empty({size, size}); QPainter painter(&preview); painter.setRenderHint(QPainter::Antialiasing); painter.setPen(Qt::NoPen); painter.setBrush(color); - painter.drawEllipse(QRect { 0, 0, size, size }); + painter.drawEllipse(QRect {0, 0, size, size}); return preview; } @@ -204,7 +204,7 @@ class DlgThemeEditor::Delegate: public QStyledItemDelegate { Q_OBJECT - QRegularExpression validNameRegExp { QStringLiteral("^[A-Z][a-zA-Z0-9]*$") }; + QRegularExpression validNameRegExp {QStringLiteral("^[A-Z][a-zA-Z0-9]*$")}; QRegularExpressionValidator* nameValidator; public: @@ -213,9 +213,11 @@ public: , nameValidator(new QRegularExpressionValidator(validNameRegExp, this)) {} - QWidget* createEditor(QWidget* parent, - [[maybe_unused]] const QStyleOptionViewItem& option, - const QModelIndex& index) const override + QWidget* createEditor( + QWidget* parent, + [[maybe_unused]] const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override { auto model = dynamic_cast(index.model()); if (!model) { @@ -243,18 +245,18 @@ public: } } - void setModelData(QWidget* editor, - QAbstractItemModel* model, - const QModelIndex& index) const override + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override { if (auto* lineEdit = qobject_cast(editor)) { model->setData(index, lineEdit->text(), Qt::EditRole); } } - void updateEditorGeometry(QWidget* editor, - const QStyleOptionViewItem& option, - [[maybe_unused]] const QModelIndex& index) const override + void updateEditorGeometry( + QWidget* editor, + const QStyleOptionViewItem& option, + [[maybe_unused]] const QModelIndex& index + ) const override { editor->setGeometry(option.rect); } @@ -279,9 +281,7 @@ public: painter->drawText(rect, Qt::AlignLeft | Qt::AlignVCenter, tr("New parameter...")); } - void paint(QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex& index) const override + void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override { auto model = dynamic_cast(index.model()); @@ -302,9 +302,8 @@ public: const QColor headerBackgroundColor = QtTools::valueOr( option.widget->property("headerBackgroundColor"), - isLightTheme - ? option.palette.color(QPalette::AlternateBase).darker(headerContrast) - : option.palette.color(QPalette::AlternateBase).lighter(headerContrast) + isLightTheme ? option.palette.color(QPalette::AlternateBase).darker(headerContrast) + : option.palette.color(QPalette::AlternateBase).lighter(headerContrast) ); painter->fillRect(option.rect, headerBackgroundColor); @@ -320,11 +319,13 @@ public: void TokenTreeView::keyPressEvent(QKeyEvent* event) { - static constexpr auto expressionEditKeys = { Qt::Key_Return, Qt::Key_Enter, Qt::Key_Space }; - static constexpr auto nameEditKeys = { Qt::Key_F2 }; - static constexpr auto deleteKeys = { Qt::Key_Delete }; + static constexpr auto expressionEditKeys = {Qt::Key_Return, Qt::Key_Enter, Qt::Key_Space}; + static constexpr auto nameEditKeys = {Qt::Key_F2}; + static constexpr auto deleteKeys = {Qt::Key_Delete}; - const auto isCorrectKey = [&event](auto key) { return event->key() == key; }; + const auto isCorrectKey = [&event](auto key) { + return event->key() == key; + }; if (QModelIndex index = currentIndex(); index.isValid()) { if (std::ranges::any_of(expressionEditKeys, isCorrectKey)) { @@ -348,9 +349,10 @@ void TokenTreeView::keyPressEvent(QKeyEvent* event) StyleParametersModel::StyleParametersModel( const std::list& sources, - QObject* parent) + QObject* parent +) : QAbstractItemModel(parent) - , ParameterSource({ .name = QT_TR_NOOP("All Theme Editor Parameters") }) + , ParameterSource({.name = QT_TR_NOOP("All Theme Editor Parameters")}) , sources(sources) , manager(new StyleParameters::ParameterManager()) { @@ -424,11 +426,13 @@ void StyleParametersModel::reset() for (auto* source : sources) { auto groupNode = std::make_unique( - std::make_unique(tr(source->metadata.name.c_str()), source)); + std::make_unique(tr(source->metadata.name.c_str()), source) + ); for (const auto& parameter : source->all()) { auto item = std::make_unique( - std::make_unique(QString::fromStdString(parameter.name), parameter)); + std::make_unique(QString::fromStdString(parameter.name), parameter) + ); if (source->metadata.options.testFlag(ReadOnly)) { item->data()->flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; @@ -549,9 +553,11 @@ QVariant StyleParametersModel::data(const QModelIndex& index, int role) const return {}; } -bool StyleParametersModel::setData(const QModelIndex& index, - const QVariant& value, - [[maybe_unused]] int role) +bool StyleParametersModel::setData( + const QModelIndex& index, + const QVariant& value, + [[maybe_unused]] int role +) { if (auto parameterItem = item(index)) { auto groupItem = item(index.parent()); @@ -587,20 +593,17 @@ bool StyleParametersModel::setData(const QModelIndex& index, return false; } - StyleParameters::Parameter token { .name = newName.toStdString(), .value = "" }; + StyleParameters::Parameter token {.name = newName.toStdString(), .value = ""}; int start = rowCount(index.parent()); beginInsertRows(index.parent(), start, start + 1); - auto item = std::make_unique( - std::make_unique(newName, token)); + auto item = std::make_unique(std::make_unique(newName, token)); node(index.parent())->appendChild(std::move(item)); endInsertRows(); // this must be queued to basically next frame so widget has a chance to update - QTimer::singleShot(0, [this, index]() { - this->newParameterAdded(index); - }); + QTimer::singleShot(0, [this, index]() { this->newParameterAdded(index); }); } } @@ -679,9 +682,12 @@ StyleParametersModel::Item* StyleParametersModel::item(const QModelIndex& index) DlgThemeEditor::DlgThemeEditor(QWidget* parent) : QDialog(parent) , ui(new Ui::DlgThemeEditor) - , model(std::make_unique( - Base::provideServiceImplementations(), - this)) + , model( + std::make_unique( + Base::provideServiceImplementations(), + this + ) + ) { ui->setupUi(this); @@ -722,25 +728,25 @@ DlgThemeEditor::DlgThemeEditor(QWidget* parent) connect(ui->buttonBox, &QDialogButtonBox::clicked, this, &DlgThemeEditor::handleButtonClick); - connect(ui->tokensTreeView, - &TokenTreeView::requestRemove, - model.get(), - qOverload(&StyleParametersModel::removeItem)); + connect( + ui->tokensTreeView, + &TokenTreeView::requestRemove, + model.get(), + qOverload(&StyleParametersModel::removeItem) + ); connect(model.get(), &StyleParametersModel::modelReset, ui->tokensTreeView, [this] { ui->tokensTreeView->expandAll(); }); - connect(model.get(), - &StyleParametersModel::newParameterAdded, - this, - [this](const QModelIndex& index) { - const auto newParameterExpressionIndex = - index.siblingAtColumn(StyleParametersModel::ParameterExpression); + connect(model.get(), &StyleParametersModel::newParameterAdded, this, [this](const QModelIndex& index) { + const auto newParameterExpressionIndex = index.siblingAtColumn( + StyleParametersModel::ParameterExpression + ); - ui->tokensTreeView->scrollTo(newParameterExpressionIndex); - ui->tokensTreeView->setCurrentIndex(newParameterExpressionIndex); - ui->tokensTreeView->edit(newParameterExpressionIndex); - }); + ui->tokensTreeView->scrollTo(newParameterExpressionIndex); + ui->tokensTreeView->setCurrentIndex(newParameterExpressionIndex); + ui->tokensTreeView->edit(newParameterExpressionIndex); + }); } DlgThemeEditor::~DlgThemeEditor() = default; diff --git a/src/Gui/Dialogs/DlgThemeEditor.h b/src/Gui/Dialogs/DlgThemeEditor.h index 6964742c6f..b0c634f8ac 100644 --- a/src/Gui/Dialogs/DlgThemeEditor.h +++ b/src/Gui/Dialogs/DlgThemeEditor.h @@ -35,7 +35,8 @@ QT_BEGIN_NAMESPACE class QAbstractButton; QT_END_NAMESPACE -namespace Gui { +namespace Gui +{ namespace StyleParameters { @@ -43,10 +44,13 @@ class ParameterManager; } QT_BEGIN_NAMESPACE -namespace Ui { class DlgThemeEditor; } +namespace Ui +{ +class DlgThemeEditor; +} QT_END_NAMESPACE -class GuiExport TokenTreeView : public QTreeView +class GuiExport TokenTreeView: public QTreeView { Q_OBJECT public: @@ -59,7 +63,8 @@ Q_SIGNALS: void requestRemove(const QModelIndex& index); }; -class GuiExport StyleParametersModel: public QAbstractItemModel, public StyleParameters::ParameterSource +class GuiExport StyleParametersModel: public QAbstractItemModel, + public StyleParameters::ParameterSource { Q_OBJECT @@ -81,8 +86,7 @@ public: FC_DISABLE_COPY_MOVE(StyleParametersModel); - explicit StyleParametersModel(const std::list& sources, - QObject* parent = nullptr); + explicit StyleParametersModel(const std::list& sources, QObject* parent = nullptr); ~StyleParametersModel() override; @@ -107,7 +111,7 @@ public: Node* node(const QModelIndex& index) const; Item* item(const QModelIndex& index) const; - template + template T* item(const QModelIndex& index) const { return dynamic_cast(item(index)); @@ -127,7 +131,8 @@ private: std::unique_ptr root; }; -class GuiExport DlgThemeEditor : public QDialog { +class GuiExport DlgThemeEditor: public QDialog +{ Q_OBJECT class Delegate; @@ -135,7 +140,7 @@ class GuiExport DlgThemeEditor : public QDialog { public: FC_DISABLE_COPY_MOVE(DlgThemeEditor); - explicit DlgThemeEditor(QWidget *parent = nullptr); + explicit DlgThemeEditor(QWidget* parent = nullptr); ~DlgThemeEditor() override; @@ -147,6 +152,6 @@ private: std::unique_ptr manager; std::unique_ptr model; }; -} // Gui +} // namespace Gui -#endif //DLGTHEMEEDITOR_H +#endif // DLGTHEMEEDITOR_H diff --git a/src/Gui/Dialogs/DlgToolbarsImp.cpp b/src/Gui/Dialogs/DlgToolbarsImp.cpp index 89f203405f..3aaf5d652c 100644 --- a/src/Gui/Dialogs/DlgToolbarsImp.cpp +++ b/src/Gui/Dialogs/DlgToolbarsImp.cpp @@ -71,10 +71,12 @@ DlgCustomToolbars::DlgCustomToolbars(DlgCustomToolbars::Type t, QWidget* parent) sepItem->setData(1, Qt::UserRole, QByteArray("Separator")); sepItem->setSizeHint(0, QSize(32, 32)); - conn = DlgCustomKeyboardImp::initCommandWidgets(ui->commandTreeWidget, - sepItem, - ui->categoryBox, - ui->editCommand); + conn = DlgCustomKeyboardImp::initCommandWidgets( + ui->commandTreeWidget, + sepItem, + ui->categoryBox, + ui->editCommand + ); // fills the combo box with all available workbenches QStringList workbenches = Application::Instance->workbenches(); @@ -170,7 +172,8 @@ void DlgCustomToolbars::onActivateCategoryBox() {} // called from DlgMacroExecuteImp toolbar walkthrough function -void DlgCustomToolbars::activateWorkbenchBox(int index) { +void DlgCustomToolbars::activateWorkbenchBox(int index) +{ onWorkbenchBoxActivated(index); } @@ -186,8 +189,8 @@ void DlgCustomToolbars::onWorkbenchBoxActivated(int index) void DlgCustomToolbars::importCustomToolbars(const QByteArray& name) { - ParameterGrp::handle hGrp = - App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); + ParameterGrp::handle hGrp + = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); const char* subgroup = (type == Toolbar ? "Toolbar" : "Toolboxbar"); if (!hGrp->HasGroup(name.constData())) { return; @@ -239,9 +242,7 @@ void DlgCustomToolbars::importCustomToolbars(const QByteArray& name) else { // If corresponding module is not yet loaded do not lose the entry auto item = new QTreeWidgetItem(toplevel); - item->setText( - 0, - tr("%1 module not loaded").arg(QString::fromStdString(it2.second))); + item->setText(0, tr("%1 module not loaded").arg(QString::fromStdString(it2.second))); item->setData(0, Qt::UserRole, QByteArray(it2.first.c_str())); item->setData(0, Qt::WhatsThisPropertyRole, QByteArray(it2.second.c_str())); item->setSizeHint(0, QSize(32, 32)); @@ -253,8 +254,8 @@ void DlgCustomToolbars::importCustomToolbars(const QByteArray& name) void DlgCustomToolbars::exportCustomToolbars(const QByteArray& workbench) { - ParameterGrp::handle hGrp = - App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); + ParameterGrp::handle hGrp + = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Workbench"); const char* subgroup = (type == Toolbar ? "Toolbar" : "Toolboxbar"); hGrp = hGrp->GetGroup(workbench.constData())->GetGroup(subgroup); hGrp->Clear(); @@ -435,24 +436,27 @@ void DlgCustomToolbars::onMoveActionDownButtonClicked() void DlgCustomToolbars::onNewButtonClicked() { bool ok; - QString text = - QStringLiteral("Custom%1").arg(ui->toolbarTreeWidget->topLevelItemCount() + 1); - text = QInputDialog::getText(this, - tr("New toolbar"), - tr("Toolbar name:"), - QLineEdit::Normal, - text, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString text = QStringLiteral("Custom%1").arg(ui->toolbarTreeWidget->topLevelItemCount() + 1); + text = QInputDialog::getText( + this, + tr("New toolbar"), + tr("Toolbar name:"), + QLineEdit::Normal, + text, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok) { // Check for duplicated name for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i); QString groupName = toplevel->text(0); if (groupName == text) { - QMessageBox::warning(this, - tr("Duplicated name"), - tr("The toolbar name '%1' is already used").arg(text)); + QMessageBox::warning( + this, + tr("Duplicated name"), + tr("The toolbar name '%1' is already used").arg(text) + ); return; } } @@ -491,22 +495,26 @@ void DlgCustomToolbars::onRenameButtonClicked() if (item && !item->parent() && item->isSelected()) { bool ok; QString old_text = item->text(0); - QString text = QInputDialog::getText(this, - tr("Rename toolbar"), - tr("Toolbar name:"), - QLineEdit::Normal, - old_text, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString text = QInputDialog::getText( + this, + tr("Rename toolbar"), + tr("Toolbar name:"), + QLineEdit::Normal, + old_text, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok && text != old_text) { // Check for duplicated name for (int i = 0; i < ui->toolbarTreeWidget->topLevelItemCount(); i++) { QTreeWidgetItem* toplevel = ui->toolbarTreeWidget->topLevelItem(i); QString groupName = toplevel->text(0); if (groupName == text && toplevel != item) { - QMessageBox::warning(this, - tr("Duplicated name"), - tr("The toolbar name '%1' is already used").arg(text)); + QMessageBox::warning( + this, + tr("Duplicated name"), + tr("The toolbar name '%1' is already used").arg(text) + ); return; } } diff --git a/src/Gui/Dialogs/DlgToolbarsImp.h b/src/Gui/Dialogs/DlgToolbarsImp.h index 5b5cfa430f..ff73ee03b3 100644 --- a/src/Gui/Dialogs/DlgToolbarsImp.h +++ b/src/Gui/Dialogs/DlgToolbarsImp.h @@ -30,8 +30,10 @@ class QTreeWidgetItem; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgCustomToolbars; /** This class implements the creation of user defined toolbars. @@ -42,12 +44,16 @@ class Ui_DlgCustomToolbars; * * \author Werner Mayer */ -class DlgCustomToolbars : public CustomizeActionPage +class DlgCustomToolbars: public CustomizeActionPage { Q_OBJECT protected: - enum Type { Toolbar, Toolboxbar }; + enum Type + { + Toolbar, + Toolboxbar + }; explicit DlgCustomToolbars(Type, QWidget* parent = nullptr); ~DlgCustomToolbars() override; @@ -72,8 +78,8 @@ protected Q_SLOTS: void onModifyMacroAction(const QByteArray&) override; protected: - void changeEvent(QEvent *e) override; - void hideEvent(QHideEvent * event) override; + void changeEvent(QEvent* e) override; + void hideEvent(QHideEvent* event) override; virtual void addCustomToolbar(const QString&); virtual void removeCustomToolbar(const QString&); virtual void renameCustomToolbar(const QString&, const QString&); @@ -89,6 +95,7 @@ private: protected: std::unique_ptr ui; + private: Type type; boost::signals2::scoped_connection conn; @@ -99,7 +106,7 @@ private: * @see DlgCustomCmdbarsImp * \author Werner Mayer */ -class DlgCustomToolbarsImp : public DlgCustomToolbars +class DlgCustomToolbarsImp: public DlgCustomToolbars { Q_OBJECT @@ -109,7 +116,7 @@ public: protected: void showEvent(QShowEvent* e) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void addCustomToolbar(const QString&) override; void removeCustomToolbar(const QString&) override; void renameCustomToolbar(const QString&, const QString&) override; @@ -133,7 +140,7 @@ private: * @see DlgCustomToolbarsImp * \author Werner Mayer */ -class DlgCustomToolBoxbarsImp : public DlgCustomToolbars +class DlgCustomToolBoxbarsImp: public DlgCustomToolbars { Q_OBJECT @@ -142,10 +149,10 @@ public: ~DlgCustomToolBoxbarsImp() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGTOOLBARS_IMP_H +#endif // GUI_DIALOG_DLGTOOLBARS_IMP_H diff --git a/src/Gui/Dialogs/DlgUndoRedo.cpp b/src/Gui/Dialogs/DlgUndoRedo.cpp index 3f56249286..f575d3e949 100644 --- a/src/Gui/Dialogs/DlgUndoRedo.cpp +++ b/src/Gui/Dialogs/DlgUndoRedo.cpp @@ -37,8 +37,8 @@ using namespace Gui::Dialog; * Constructs a UndoRedoDialog which is a child of 'parent', with the * name 'name'.' */ -UndoDialog::UndoDialog( QWidget* parent ) - : QMenu( parent ) +UndoDialog::UndoDialog(QWidget* parent) + : QMenu(parent) { connect(this, &QMenu::aboutToShow, this, &UndoDialog::onFetchInfo); } @@ -54,9 +54,9 @@ UndoDialog::~UndoDialog() = default; */ void UndoDialog::onFetchInfo() { - clear(); // Remove first all items + clear(); // Remove first all items - MDIView* mdi = getMainWindow()->activeWindow(); + MDIView* mdi = getMainWindow()->activeWindow(); if (mdi) { QStringList vecUndos = mdi->undoActions(); for (QStringList::Iterator i = vecUndos.begin(); i != vecUndos.end(); ++i) { @@ -72,8 +72,9 @@ void UndoDialog::onSelected() QList acts = this->actions(); for (QList::Iterator it = acts.begin(); it != acts.end(); ++it) { Gui::Application::Instance->sendMsgToActiveView("Undo"); - if (*it == a) + if (*it == a) { break; + } } } @@ -83,8 +84,8 @@ void UndoDialog::onSelected() * Constructs a UndoRedoDialog which is a child of 'parent', with the * name 'name'.' */ -RedoDialog::RedoDialog( QWidget* parent ) - : QMenu( parent ) +RedoDialog::RedoDialog(QWidget* parent) + : QMenu(parent) { connect(this, &QMenu::aboutToShow, this, &RedoDialog::onFetchInfo); } @@ -100,7 +101,7 @@ RedoDialog::~RedoDialog() = default; */ void RedoDialog::onFetchInfo() { - clear(); // Remove first all items + clear(); // Remove first all items MDIView* mdi = getMainWindow()->activeWindow(); if (mdi) { @@ -118,8 +119,9 @@ void RedoDialog::onSelected() QList acts = this->actions(); for (QList::Iterator it = acts.begin(); it != acts.end(); ++it) { Gui::Application::Instance->sendMsgToActiveView("Redo"); - if (*it == a) + if (*it == a) { break; + } } } diff --git a/src/Gui/Dialogs/DlgUndoRedo.h b/src/Gui/Dialogs/DlgUndoRedo.h index e35714a2a9..c56f8caefc 100644 --- a/src/Gui/Dialogs/DlgUndoRedo.h +++ b/src/Gui/Dialogs/DlgUndoRedo.h @@ -26,42 +26,44 @@ #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ /** This class implements the undo dialog. * \author Werner Mayer */ -class UndoDialog : public QMenu +class UndoDialog: public QMenu { Q_OBJECT public: - explicit UndoDialog( QWidget* parent = nullptr ); - ~UndoDialog() override; + explicit UndoDialog(QWidget* parent = nullptr); + ~UndoDialog() override; protected Q_SLOTS: - void onSelected(); - void onFetchInfo(); + void onSelected(); + void onFetchInfo(); }; /** This class implements the redo dialog. * \author Werner Mayer */ -class RedoDialog : public QMenu +class RedoDialog: public QMenu { Q_OBJECT public: - explicit RedoDialog( QWidget* parent = nullptr ); - ~RedoDialog() override; + explicit RedoDialog(QWidget* parent = nullptr); + ~RedoDialog() override; protected Q_SLOTS: - void onSelected(); - void onFetchInfo(); + void onSelected(); + void onFetchInfo(); }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DLGUNDOREDO_H +#endif // GUI_DIALOG_DLGUNDOREDO_H diff --git a/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp b/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp index e3744c139d..cdf2e4d8dc 100644 --- a/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp +++ b/src/Gui/Dialogs/DlgUnitsCalculatorImp.cpp @@ -87,12 +87,11 @@ DlgUnitsCalculator::DlgUnitsCalculator(QWidget* parent, Qt::WindowFlags fl) ui->UnitInput->setText(QStringLiteral("in")); units << Unit::Acceleration << Unit::AmountOfSubstance << Unit::Angle << Unit::Area - << Unit::Density << Unit::CurrentDensity << Unit::DissipationRate - << Unit::DynamicViscosity << Unit::ElectricalCapacitance << Unit::ElectricalInductance - << Unit::ElectricalConductance << Unit::ElectricalResistance - << Unit::ElectricalConductivity << Unit::ElectricCharge << Unit::ElectricCurrent - << Unit::ElectricPotential << Unit::Force << Unit::Frequency << Unit::HeatFlux - << Unit::InverseArea << Unit::InverseLength << Unit::InverseVolume + << Unit::Density << Unit::CurrentDensity << Unit::DissipationRate << Unit::DynamicViscosity + << Unit::ElectricalCapacitance << Unit::ElectricalInductance << Unit::ElectricalConductance + << Unit::ElectricalResistance << Unit::ElectricalConductivity << Unit::ElectricCharge + << Unit::ElectricCurrent << Unit::ElectricPotential << Unit::Force << Unit::Frequency + << Unit::HeatFlux << Unit::InverseArea << Unit::InverseLength << Unit::InverseVolume << Unit::KinematicViscosity << Unit::Length << Unit::LuminousIntensity << Unit::Mass << Unit::MagneticFieldStrength << Unit::MagneticFlux << Unit::MagneticFluxDensity << Unit::Magnetization << Unit::Power << Unit::Pressure << Unit::SpecificEnergy @@ -132,8 +131,7 @@ void DlgUnitsCalculator::valueChanged(const Quantity& quant) { std::string unitTypeStr; try { - unitTypeStr = - Quantity::parse(ui->UnitInput->text().toStdString()).getUnit().getTypeString(); + unitTypeStr = Quantity::parse(ui->UnitInput->text().toStdString()).getUnit().getTypeString(); } catch (const Base::ParserError&) { } @@ -142,7 +140,8 @@ void DlgUnitsCalculator::valueChanged(const Quantity& quant) // since it expects then a scientific notation number like "1e3" if ((ui->UnitInput->text().mid(0, 2) == QStringLiteral("ee")) || unitTypeStr.empty()) { ui->ValueOutput->setText( - QStringLiteral("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text())); + QStringLiteral("%1 %2").arg(tr("unknown unit:"), ui->UnitInput->text()) + ); ui->pushButton_Copy->setEnabled(false); } else { // the unit is valid @@ -152,8 +151,7 @@ void DlgUnitsCalculator::valueChanged(const Quantity& quant) ui->pushButton_Copy->setEnabled(false); } else { // the unit is valid and has the same type - double convertValue = - Quantity::parse("1" + ui->UnitInput->text().toStdString()).getValue(); + double convertValue = Quantity::parse("1" + ui->UnitInput->text().toStdString()).getValue(); // we got now e.g. for "1 in" the value '25.4' because 1 in = 25.4 mm // the result is now just quant / convertValue because the input is always in a base // unit (an input of "1 cm" will immediately be converted to "10 mm" by Gui::InputField @@ -192,8 +190,7 @@ void DlgUnitsCalculator::copy() void DlgUnitsCalculator::returnPressed() { if (ui->pushButton_Copy->isEnabled()) { - ui->textEdit->append(ui->ValueInput->text() + QStringLiteral(" = ") - + ui->ValueOutput->text()); + ui->textEdit->append(ui->ValueInput->text() + QStringLiteral(" = ") + ui->ValueOutput->text()); ui->ValueInput->pushToHistory(); } } diff --git a/src/Gui/Dialogs/DlgUnitsCalculatorImp.h b/src/Gui/Dialogs/DlgUnitsCalculatorImp.h index 7ba5d75d3a..a88d3b3494 100644 --- a/src/Gui/Dialogs/DlgUnitsCalculatorImp.h +++ b/src/Gui/Dialogs/DlgUnitsCalculatorImp.h @@ -29,15 +29,17 @@ #include #include -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_DlgUnitCalculator; /** * The DlgUnitsCalculator provides a unit conversion dialog * \author Juergen Riegel */ -class DlgUnitsCalculator : public QDialog +class DlgUnitsCalculator: public QDialog { Q_OBJECT @@ -67,7 +69,7 @@ private: QList units; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_DlgActivateWindowImp_H +#endif // GUI_DIALOG_DlgActivateWindowImp_H diff --git a/src/Gui/Dialogs/DlgVersionMigrator.cpp b/src/Gui/Dialogs/DlgVersionMigrator.cpp index fe7be5227e..8ea3072507 100644 --- a/src/Gui/Dialogs/DlgVersionMigrator.cpp +++ b/src/Gui/Dialogs/DlgVersionMigrator.cpp @@ -55,13 +55,14 @@ namespace fs = std::filesystem; bool isCurrentVersionKnown() { std::set paths = { - App::Application::directories()->getUserAppDataDir(), - App::Application::directories()->getUserConfigPath() + App::Application::directories()->getUserAppDataDir(), + App::Application::directories()->getUserConfigPath() }; int major = std::stoi(App::Application::Config()["BuildVersionMajor"]); int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]); - std::string currentVersionedDirName = App::ApplicationDirectories::versionStringForPath(major, minor); - for (auto &path : paths) { + std::string currentVersionedDirName + = App::ApplicationDirectories::versionStringForPath(major, minor); + for (auto& path : paths) { if (App::Application::directories()->usingCurrentVersionConfig(path)) { return true; } @@ -77,15 +78,17 @@ bool isCurrentVersionKnown() return false; } -void markCurrentVersionAsDoNotMigrate() { +void markCurrentVersionAsDoNotMigrate() +{ std::set paths = { - App::Application::directories()->getUserAppDataDir(), - App::Application::directories()->getUserConfigPath() + App::Application::directories()->getUserAppDataDir(), + App::Application::directories()->getUserConfigPath() }; int major = std::stoi(App::Application::Config()["BuildVersionMajor"]); int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]); - std::string currentVersionedDirName = App::ApplicationDirectories::versionStringForPath(major, minor); - for (auto &path : paths) { + std::string currentVersionedDirName + = App::ApplicationDirectories::versionStringForPath(major, minor); + for (auto& path : paths) { if (App::Application::directories()->usingCurrentVersionConfig(path)) { // No action to take: the migration is done, so this call doesn't need to do anything continue; @@ -97,7 +100,10 @@ void markCurrentVersionAsDoNotMigrate() { markerPath /= currentVersionedDirName + ".do_not_migrate"; std::ofstream markerFile(markerPath); if (!markerFile.is_open()) { - Base::Console().error("Unable to open marker file %s\n", Base::FileInfo::pathToString(markerPath).c_str()); + Base::Console().error( + "Unable to open marker file %s\n", + Base::FileInfo::pathToString(markerPath).c_str() + ); continue; } markerFile << "Migration to version " << currentVersionedDirName << " was declined. " @@ -107,8 +113,8 @@ void markCurrentVersionAsDoNotMigrate() { } -DlgVersionMigrator::DlgVersionMigrator(MainWindow *mw) : - QDialog(mw) +DlgVersionMigrator::DlgVersionMigrator(MainWindow* mw) + : QDialog(mw) , mainWindow(mw) , sizeCalculationWorkerThread(nullptr) , ui(std::make_unique()) @@ -116,24 +122,26 @@ DlgVersionMigrator::DlgVersionMigrator(MainWindow *mw) : ui->setupUi(this); auto prefGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Migration"); + "User parameter:BaseApp/Preferences/Migration" + ); int major = std::stoi(App::Application::Config()["BuildVersionMajor"]); int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]); auto programName = QString::fromStdString(App::Application::getExecutableName()); - // NOTE: All rich-text strings are generated programmatically so that translators don't have to deal with the - // markup. The two strings in the middle of the dialog are set in the UI file. + // NOTE: All rich-text strings are generated programmatically so that translators don't have to + // deal with the markup. The two strings in the middle of the dialog are set in the UI file. - auto programNameString = tr("Welcome to %1 %2.%3\n\n").arg( - programName, QString::number(major), QString::number(minor)); + auto programNameString = tr("Welcome to %1 %2.%3\n\n") + .arg(programName, QString::number(major), QString::number(minor)); auto welcomeString = QStringLiteral("") + programNameString + QStringLiteral(""); - auto calculatingSizeString = QStringLiteral("") + tr("Calculating size…") + QStringLiteral(""); + auto calculatingSizeString = QStringLiteral("") + tr("Calculating size…") + + QStringLiteral(""); - auto shareConfigurationString = QStringLiteral("") + - tr("Share configuration between versions") + QStringLiteral(""); + auto shareConfigurationString = QStringLiteral("") + + tr("Share configuration between versions") + QStringLiteral(""); setWindowTitle(programNameString); #ifdef Q_OS_MACOS @@ -148,12 +156,14 @@ DlgVersionMigrator::DlgVersionMigrator(MainWindow *mw) : connect(ui->helpButton, &QPushButton::clicked, this, &DlgVersionMigrator::help); // Set up the menu actions for the two hidden options - auto *menu = new QMenu(ui->menuButton); - QAction *share = menu->addAction(tr("Share configuration with previous version")); - QAction *reset = menu->addAction(tr("Use a new default configuration")); + auto* menu = new QMenu(ui->menuButton); + QAction* share = menu->addAction(tr("Share configuration with previous version")); + QAction* reset = menu->addAction(tr("Use a new default configuration")); ui->menuButton->setMenu(menu); ui->menuButton->setPopupMode(QToolButton::InstantPopup); - ui->menuButton->setStyleSheet(QStringLiteral("QToolButton::menu-indicator { image: none; width: 0px; }")); + ui->menuButton->setStyleSheet( + QStringLiteral("QToolButton::menu-indicator { image: none; width: 0px; }") + ); ui->menuButton->setProperty("flat", true); connect(share, &QAction::triggered, this, &DlgVersionMigrator::share); connect(reset, &QAction::triggered, this, &DlgVersionMigrator::freshStart); @@ -161,7 +171,8 @@ DlgVersionMigrator::DlgVersionMigrator(MainWindow *mw) : DlgVersionMigrator::~DlgVersionMigrator() = default; -int DlgVersionMigrator::exec() { +int DlgVersionMigrator::exec() +{ // If the user is running a custom directory set, there is no migration to versioned directories if (App::Application::directories()->usingCustomDirectories()) { return 0; @@ -177,15 +188,17 @@ int DlgVersionMigrator::exec() { } -class DirectorySizeCalculationWorker : public QObject { +class DirectorySizeCalculationWorker: public QObject +{ Q_OBJECT public: - void run() { + void run() + { auto dir = App::Application::directories()->getUserAppDataDir(); uintmax_t size = 0; auto thisThread = QThread::currentThread(); - for (auto &entry: fs::recursive_directory_iterator(dir)) { + for (auto& entry : fs::recursive_directory_iterator(dir)) { if (thisThread->isInterruptionRequested()) { Q_EMIT(cancelled()); Q_EMIT(finished()); @@ -207,26 +220,30 @@ Q_SIGNALS: void cancelled(); }; -class PathMigrationWorker : public QObject { +class PathMigrationWorker: public QObject +{ Q_OBJECT public: - void run() { + void run() + { try { App::GetApplication().GetUserParameter().SaveDocument(); App::Application::directories()->migrateAllPaths( - { - App::Application::directories()->getUserAppDataDir(), - App::Application::directories()->getUserConfigPath() - }); + {App::Application::directories()->getUserAppDataDir(), + App::Application::directories()->getUserConfigPath()} + ); Q_EMIT(complete()); - } catch (const Base::Exception &e) { + } + catch (const Base::Exception& e) { Base::Console().error("Error migrating configuration data: %s\n", e.what()); Q_EMIT(failed()); - } catch (const std::exception &e) { + } + catch (const std::exception& e) { Base::Console().error("Unrecognized error migrating configuration data: %s\n", e.what()); Q_EMIT(failed()); - } catch (...) { + } + catch (...) { Base::Console().error("Error migrating configuration data\n"); Q_EMIT(failed()); } @@ -241,16 +258,27 @@ Q_SIGNALS: void failed(); }; -void DlgVersionMigrator::calculateMigrationSize() { +void DlgVersionMigrator::calculateMigrationSize() +{ sizeCalculationWorkerThread = new QThread(mainWindow); - auto *worker = new DirectorySizeCalculationWorker(); + auto* worker = new DirectorySizeCalculationWorker(); worker->moveToThread(sizeCalculationWorkerThread); connect(sizeCalculationWorkerThread, &QThread::started, worker, &DirectorySizeCalculationWorker::run); - connect(worker, &DirectorySizeCalculationWorker::sizeFound, this, &DlgVersionMigrator::showSizeOfMigration); + connect( + worker, + &DirectorySizeCalculationWorker::sizeFound, + this, + &DlgVersionMigrator::showSizeOfMigration + ); connect(worker, &DirectorySizeCalculationWorker::finished, sizeCalculationWorkerThread, &QThread::quit); connect(worker, &DirectorySizeCalculationWorker::finished, worker, &QObject::deleteLater); - connect(sizeCalculationWorkerThread, &QThread::finished, sizeCalculationWorkerThread, &QObject::deleteLater); + connect( + sizeCalculationWorkerThread, + &QThread::finished, + sizeCalculationWorkerThread, + &QObject::deleteLater + ); sizeCalculationWorkerThread->start(); } @@ -264,19 +292,20 @@ void DlgVersionMigrator::share() close(); } -void DlgVersionMigrator::showSizeOfMigration(uintmax_t size) { +void DlgVersionMigrator::showSizeOfMigration(uintmax_t size) +{ auto sizeString = QLocale().formattedDataSize(static_cast(size)); - auto sizeMessage = QStringLiteral("") + - QObject::tr("Estimated size of data to copy: %1").arg(sizeString) + - QStringLiteral(""); + auto sizeMessage = QStringLiteral("") + + QObject::tr("Estimated size of data to copy: %1").arg(sizeString) + QStringLiteral(""); ui->sizeLabel->setText(sizeMessage); - sizeCalculationWorkerThread = nullptr; // Deleted via a previously-configured deleteLater() + sizeCalculationWorkerThread = nullptr; // Deleted via a previously-configured deleteLater() } -void DlgVersionMigrator::migrate() { +void DlgVersionMigrator::migrate() +{ hide(); - auto *workerThread = new QThread(mainWindow); - auto *worker = new PathMigrationWorker(); + auto* workerThread = new QThread(mainWindow); + auto* worker = new PathMigrationWorker(); worker->moveToThread(workerThread); connect(workerThread, &QThread::started, worker, &PathMigrationWorker::run); connect(worker, &PathMigrationWorker::finished, workerThread, &QThread::quit); @@ -295,14 +324,17 @@ void DlgVersionMigrator::migrate() { if (migrationRunning->result() == QDialog::Accepted) { restart(tr("Migration complete")); - } else { - QMessageBox::critical(mainWindow, QObject::tr("Migration failed"), - QObject::tr("Migration failed. See the Report View for details.")); + } + else { + QMessageBox::critical( + mainWindow, + QObject::tr("Migration failed"), + QObject::tr("Migration failed. See the Report View for details.") + ); } } - void DlgVersionMigrator::freshStart() { // Create the versioned directories, but don't put anything in them @@ -312,8 +344,9 @@ void DlgVersionMigrator::freshStart() }; int major = std::stoi(App::Application::Config()["BuildVersionMajor"]); int minor = std::stoi(App::Application::Config()["BuildVersionMinor"]); - std::string currentVersionedDirName = App::ApplicationDirectories::versionStringForPath(major, minor); - for (auto &path : paths) { + std::string currentVersionedDirName + = App::ApplicationDirectories::versionStringForPath(major, minor); + for (auto& path : paths) { if (App::Application::directories()->usingCurrentVersionConfig(path)) { continue; } @@ -336,12 +369,11 @@ void DlgVersionMigrator::help() QDesktopServices::openUrl(QUrl(helpPage)); } -void DlgVersionMigrator::restart(const QString &message) +void DlgVersionMigrator::restart(const QString& message) { - App::GetApplication().GetUserParameter().SaveDocument(); // Flush to disk before restarting - auto *restarting = new QMessageBox(this); - restarting->setText( - message + QObject::tr(" → Restarting…")); + App::GetApplication().GetUserParameter().SaveDocument(); // Flush to disk before restarting + auto* restarting = new QMessageBox(this); + restarting->setText(message + QObject::tr(" → Restarting…")); restarting->setWindowTitle(QObject::tr("Restarting")); restarting->setStandardButtons(QMessageBox::NoButton); auto closeNotice = [restarting]() { @@ -350,7 +382,7 @@ void DlgVersionMigrator::restart(const QString &message) // Insert a short delay before restart so the user can see the success message and // knows it's a restart and not a crash... - constexpr int delayRestartMillis{2000}; + constexpr int delayRestartMillis {2000}; QTimer::singleShot(delayRestartMillis, closeNotice); restarting->exec(); @@ -358,15 +390,16 @@ void DlgVersionMigrator::restart(const QString &message) if (getMainWindow()->close()) { auto args = QApplication::arguments(); args.removeFirst(); - QProcess::startDetached(QApplication::applicationFilePath(), - args, - QApplication::applicationDirPath()); + QProcess::startDetached( + QApplication::applicationFilePath(), + args, + QApplication::applicationDirPath() + ); } }); QCoreApplication::exit(0); - _Exit(0); // No really. Die. + _Exit(0); // No really. Die. } - #include "DlgVersionMigrator.moc" diff --git a/src/Gui/Dialogs/DlgVersionMigrator.h b/src/Gui/Dialogs/DlgVersionMigrator.h index 90b76e7853..2f9a8f2109 100644 --- a/src/Gui/Dialogs/DlgVersionMigrator.h +++ b/src/Gui/Dialogs/DlgVersionMigrator.h @@ -30,41 +30,43 @@ #include -namespace Gui { +namespace Gui +{ - class MainWindow; +class MainWindow; - namespace Dialog { +namespace Dialog +{ - class GuiExport DlgVersionMigrator final : public QDialog - { - Q_OBJECT +class GuiExport DlgVersionMigrator final: public QDialog +{ + Q_OBJECT - public: - explicit DlgVersionMigrator(MainWindow *mw); - ~DlgVersionMigrator() override; - Q_DISABLE_COPY_MOVE(DlgVersionMigrator) +public: + explicit DlgVersionMigrator(MainWindow* mw); + ~DlgVersionMigrator() override; + Q_DISABLE_COPY_MOVE(DlgVersionMigrator) - int exec() override; + int exec() override; - protected Q_SLOTS: +protected Q_SLOTS: - void calculateMigrationSize(); // Async -> this starts the process and immediately returns - void showSizeOfMigration(uintmax_t size); - void migrate(); - void share(); - void freshStart(); - void help(); + void calculateMigrationSize(); // Async -> this starts the process and immediately returns + void showSizeOfMigration(uintmax_t size); + void migrate(); + void share(); + void freshStart(); + void help(); - private: - MainWindow* mainWindow; - QThread* sizeCalculationWorkerThread; - std::unique_ptr ui; +private: + MainWindow* mainWindow; + QThread* sizeCalculationWorkerThread; + std::unique_ptr ui; - void restart(const QString &message); - }; + void restart(const QString& message); +}; - } -} +} // namespace Dialog +} // namespace Gui -#endif // GUI_DIALOG_VERSIONMIGRATOR_H +#endif // GUI_DIALOG_VERSIONMIGRATOR_H diff --git a/src/Gui/DockWindow.cpp b/src/Gui/DockWindow.cpp index 91d5ca07fc..597ce83835 100644 --- a/src/Gui/DockWindow.cpp +++ b/src/Gui/DockWindow.cpp @@ -25,10 +25,10 @@ using namespace Gui; -DockWindow::DockWindow( Gui::Document* pcDocument, QWidget *parent) - : QWidget( parent ), BaseView( pcDocument ) -{ -} +DockWindow::DockWindow(Gui::Document* pcDocument, QWidget* parent) + : QWidget(parent) + , BaseView(pcDocument) +{} DockWindow::~DockWindow() = default; diff --git a/src/Gui/DockWindow.h b/src/Gui/DockWindow.h index 68db73da26..92d6763588 100644 --- a/src/Gui/DockWindow.h +++ b/src/Gui/DockWindow.h @@ -28,7 +28,8 @@ #include -namespace Gui { +namespace Gui +{ class MDIView; class Application; @@ -43,42 +44,55 @@ class Application; * @see Application * @author Jürgen Riegel */ -class GuiExport DockWindow : public QWidget, public BaseView +class GuiExport DockWindow: public QWidget, public BaseView { - Q_OBJECT + Q_OBJECT public: - /** View constructor - * Attach the view to the given document. If the document is 0 - * the view will attach to the active document. Be aware there isn't - * always an active document available! - */ - explicit DockWindow ( Gui::Document* pcDocument=nullptr, QWidget *parent=nullptr ); - /** View destructor - * Detach the view from the document, if attached. - */ - ~DockWindow() override; + /** View constructor + * Attach the view to the given document. If the document is 0 + * the view will attach to the active document. Be aware there isn't + * always an active document available! + */ + explicit DockWindow(Gui::Document* pcDocument = nullptr, QWidget* parent = nullptr); + /** View destructor + * Detach the view from the document, if attached. + */ + ~DockWindow() override; - /** @name methods to override - */ - //@{ - /// get called when the document is updated - void onUpdate() override{} - /// returns the name of the view (important for messages) - const char *getName() const override { return "DockWindow"; } - /// Message handler - bool onMsg(const char* ,const char** ) override{ return false; } - /// Message handler test - bool onHasMsg(const char*) const override { return false; } - /// overwrite when checking on close state - bool canClose() override{return true;} - //@} + /** @name methods to override + */ + //@{ + /// get called when the document is updated + void onUpdate() override + {} + /// returns the name of the view (important for messages) + const char* getName() const override + { + return "DockWindow"; + } + /// Message handler + bool onMsg(const char*, const char**) override + { + return false; + } + /// Message handler test + bool onHasMsg(const char*) const override + { + return false; + } + /// overwrite when checking on close state + bool canClose() override + { + return true; + } + //@} Q_SIGNALS: - /// sends a message to the document - void sendCloseView(Gui::MDIView* theView); + /// sends a message to the document + void sendCloseView(Gui::MDIView* theView); }; -} // namespace Gui +} // namespace Gui -#endif // GUI_DOCKWINDOW_H +#endif // GUI_DOCKWINDOW_H diff --git a/src/Gui/DockWindowManager.cpp b/src/Gui/DockWindowManager.cpp index 2b9acdb143..0477117707 100644 --- a/src/Gui/DockWindowManager.cpp +++ b/src/Gui/DockWindowManager.cpp @@ -20,14 +20,14 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -89,13 +89,17 @@ const QList& DockWindowItems::dockWidgets() const // ----------------------------------------------------------- -namespace Gui { +namespace Gui +{ -class DockWidgetEventFilter: public QObject { +class DockWidgetEventFilter: public QObject +{ public: - bool eventFilter(QObject *o, QEvent *e) { - if (!o->isWidgetType() || e->type() != QEvent::MouseMove) + bool eventFilter(QObject* o, QEvent* e) + { + if (!o->isWidgetType() || e->type() != QEvent::MouseMove) { return false; + } auto widget = qobject_cast(o); if (!widget || !widget->isFloating()) { if (overridden) { @@ -104,32 +108,39 @@ public: } return false; } - if (static_cast(e)->buttons() != Qt::NoButton) + if (static_cast(e)->buttons() != Qt::NoButton) { return false; + } auto pos = QCursor::pos(); QPoint topLeft = widget->mapToGlobal(QPoint(cursorMargin, cursorMargin)); int h = widget->frameGeometry().height(); int w = widget->frameGeometry().width(); - QPoint bottomRight = widget->mapToGlobal(QPoint(w-cursorMargin, h-cursorMargin)); - bool left = QRect(topLeft - QPoint(cursorMargin,cursorMargin), QSize(cursorMargin, h)).contains(pos); + QPoint bottomRight = widget->mapToGlobal(QPoint(w - cursorMargin, h - cursorMargin)); + bool left = QRect(topLeft - QPoint(cursorMargin, cursorMargin), QSize(cursorMargin, h)) + .contains(pos); bool right = QRect(bottomRight.x(), topLeft.y(), cursorMargin, h).contains(pos); - bool bottom = QRect(topLeft.x()-cursorMargin, bottomRight.y(), w, cursorMargin).contains(pos); + bool bottom = QRect(topLeft.x() - cursorMargin, bottomRight.y(), w, cursorMargin).contains(pos); auto cursor = Qt::ArrowCursor; - if (left && bottom) + if (left && bottom) { cursor = Qt::SizeBDiagCursor; - else if (right && bottom) + } + else if (right && bottom) { cursor = Qt::SizeFDiagCursor; - else if (bottom) + } + else if (bottom) { cursor = Qt::SizeVerCursor; - else if (left || right) + } + else if (left || right) { cursor = Qt::SizeHorCursor; + } else if (overridden) { overridden = false; QApplication::restoreOverrideCursor(); return false; } - if (overridden) + if (overridden) { QApplication::changeOverrideCursor(cursor); + } else { overridden = true; QApplication::setOverrideCursor(cursor); @@ -144,7 +155,7 @@ public: struct DockWindowManagerP { QList _dockedWindows; - QMap > _dockWindows; + QMap> _dockWindows; DockWindowItems _dockWindowItems; ParameterGrp::handle _hPref; boost::signals2::scoped_connection _connParam; @@ -152,14 +163,15 @@ struct DockWindowManagerP DockWidgetEventFilter _dockWidgetEventFilter; QPointer overlayManager; }; -} // namespace Gui +} // namespace Gui DockWindowManager* DockWindowManager::_instance = nullptr; DockWindowManager* DockWindowManager::instance() { - if (!_instance) + if (!_instance) { _instance = new DockWindowManager; + } return _instance; } @@ -199,27 +211,30 @@ void DockWindowManager::setupOverlayManagement() d->_dockWidgetEventFilter.cursorMargin = d->_hPref->GetInt("CursorMargin", 5); d->_connParam = d->_hPref->Manager()->signalParamChanged.connect( - [this](ParameterGrp *Param, ParameterGrp::ParamType Type, const char *name, const char *) { - if(Param == d->_hPref) { - switch(Type) { - case ParameterGrp::ParamType::FCBool: - // For batch process UI setting changes, e.g. loading new preferences - d->_timer.start(100); - break; - case ParameterGrp::ParamType::FCInt: - if (name && boost::equals(name, "CursorMargin")) - d->_dockWidgetEventFilter.cursorMargin = d->_hPref->GetInt("CursorMargin", 5); - break; - default: - break; + [this](ParameterGrp* Param, ParameterGrp::ParamType Type, const char* name, const char*) { + if (Param == d->_hPref) { + switch (Type) { + case ParameterGrp::ParamType::FCBool: + // For batch process UI setting changes, e.g. loading new preferences + d->_timer.start(100); + break; + case ParameterGrp::ParamType::FCInt: + if (name && boost::equals(name, "CursorMargin")) { + d->_dockWidgetEventFilter.cursorMargin + = d->_hPref->GetInt("CursorMargin", 5); + } + break; + default: + break; } } - }); + } + ); d->_timer.setSingleShot(true); - connect(&d->_timer, &QTimer::timeout, [this](){ - for(auto w : this->getDockWindows()) { + connect(&d->_timer, &QTimer::timeout, [this]() { + for (auto w : this->getDockWindows()) { if (auto dw = qobject_cast(w)) { QSignalBlocker blocker(dw); QByteArray dockName = dw->toggleViewAction()->data().toByteArray(); @@ -234,11 +249,13 @@ void DockWindowManager::setupOverlayManagement() */ QDockWidget* DockWindowManager::addDockWindow(const char* name, QWidget* widget, Qt::DockWidgetArea pos) { - if(!widget) + if (!widget) { return nullptr; - QDockWidget *dw = qobject_cast(widget->parentWidget()); - if(dw) + } + QDockWidget* dw = qobject_cast(widget->parentWidget()); + if (dw) { return dw; + } // creates the dock widget as container to embed this widget MainWindow* mw = getMainWindow(); @@ -248,23 +265,21 @@ QDockWidget* DockWindowManager::addDockWindow(const char* name, QWidget* widget, d->overlayManager->setupTitleBar(dw); } - // Note: By default all dock widgets are hidden but the user can show them manually in the view menu. - // First, hide immediately the dock widget to avoid flickering, after setting up the dock widgets - // MainWindow::loadLayoutSettings() is called to restore the layout. + // Note: By default all dock widgets are hidden but the user can show them manually in the view + // menu. First, hide immediately the dock widget to avoid flickering, after setting up the dock + // widgets MainWindow::loadLayoutSettings() is called to restore the layout. dw->hide(); switch (pos) { - case Qt::LeftDockWidgetArea: - case Qt::RightDockWidgetArea: - case Qt::TopDockWidgetArea: - case Qt::BottomDockWidgetArea: - mw->addDockWidget(pos, dw); - default: - break; + case Qt::LeftDockWidgetArea: + case Qt::RightDockWidgetArea: + case Qt::TopDockWidgetArea: + case Qt::BottomDockWidgetArea: + mw->addDockWidget(pos, dw); + default: + break; } - connect(dw, &QObject::destroyed, - this, &DockWindowManager::onDockWidgetDestroyed); - connect(widget, &QObject::destroyed, - this, &DockWindowManager::onWidgetDestroyed); + connect(dw, &QObject::destroyed, this, &DockWindowManager::onDockWidgetDestroyed); + connect(widget, &QObject::destroyed, this, &DockWindowManager::onWidgetDestroyed); // add the widget to the dock widget widget->setParent(dw); @@ -273,9 +288,10 @@ QDockWidget* DockWindowManager::addDockWindow(const char* name, QWidget* widget, // set object name and window title needed for i18n stuff dw->setObjectName(QString::fromUtf8(name)); dw->setWindowTitle(widget->windowTitle()); - dw->setFeatures(QDockWidget::DockWidgetClosable - | QDockWidget::DockWidgetMovable - | QDockWidget::DockWidgetFloatable); + dw->setFeatures( + QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable + | QDockWidget::DockWidgetFloatable + ); d->_dockedWindows.push_back(dw); @@ -283,13 +299,15 @@ QDockWidget* DockWindowManager::addDockWindow(const char* name, QWidget* widget, d->overlayManager->initDockWidget(dw); } - connect(dw->toggleViewAction(), &QAction::triggered, [this, dw](){ + connect(dw->toggleViewAction(), &QAction::triggered, [this, dw]() { Base::ConnectionBlocker block(d->_connParam); QByteArray dockName = dw->toggleViewAction()->data().toByteArray(); d->_hPref->SetBool(dockName.constData(), dw->isVisible()); }); - auto cb = []() {getMainWindow()->saveWindowSettings(true);}; + auto cb = []() { + getMainWindow()->saveWindowSettings(true); + }; connect(dw, &QDockWidget::topLevelChanged, cb); connect(dw, &QDockWidget::dockLocationChanged, cb); return dw; @@ -301,9 +319,11 @@ QDockWidget* DockWindowManager::addDockWindow(const char* name, QWidget* widget, */ QWidget* DockWindowManager::getDockWindow(const char* name) const { - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { - if ((*it)->objectName() == QString::fromUtf8(name)) + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { + if ((*it)->objectName() == QString::fromUtf8(name)) { return (*it)->widget(); + } } return nullptr; @@ -315,9 +335,11 @@ QWidget* DockWindowManager::getDockWindow(const char* name) const */ QDockWidget* DockWindowManager::getDockContainer(const char* name) const { - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { - if ((*it)->objectName() == QLatin1String(name)) + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { + if ((*it)->objectName() == QLatin1String(name)) { return (*it); + } } return nullptr; @@ -329,8 +351,10 @@ QDockWidget* DockWindowManager::getDockContainer(const char* name) const QList DockWindowManager::getDockWindows() const { QList docked; - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { docked.push_back((*it)->widget()); + } return docked; } @@ -339,8 +363,9 @@ QList DockWindowManager::getDockWindows() const */ QWidget* DockWindowManager::removeDockWindow(const char* name) { - QWidget* widget=nullptr; - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { + QWidget* widget = nullptr; + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { if ((*it)->objectName() == QString::fromUtf8(name)) { QDockWidget* dw = *it; d->_dockedWindows.erase(it); @@ -354,11 +379,9 @@ QWidget* DockWindowManager::removeDockWindow(const char* name) widget = dw->widget(); widget->setParent(nullptr); dw->setWidget(nullptr); - disconnect(dw, &QObject::destroyed, - this, &DockWindowManager::onDockWidgetDestroyed); - disconnect(widget, &QObject::destroyed, - this, &DockWindowManager::onWidgetDestroyed); - delete dw; // destruct the QDockWidget, i.e. the parent of the widget + disconnect(dw, &QObject::destroyed, this, &DockWindowManager::onDockWidgetDestroyed); + disconnect(widget, &QObject::destroyed, this, &DockWindowManager::onWidgetDestroyed); + delete dw; // destruct the QDockWidget, i.e. the parent of the widget break; } } @@ -372,9 +395,11 @@ QWidget* DockWindowManager::removeDockWindow(const char* name) */ void DockWindowManager::removeDockWindow(QWidget* widget) { - if (!widget) + if (!widget) { return; - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { + } + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { if ((*it)->widget() == widget) { QDockWidget* dw = *it; d->_dockedWindows.erase(it); @@ -385,11 +410,9 @@ void DockWindowManager::removeDockWindow(QWidget* widget) // avoid to destruct the embedded widget widget->setParent(nullptr); dw->setWidget(nullptr); - disconnect(dw, &QObject::destroyed, - this, &DockWindowManager::onDockWidgetDestroyed); - disconnect(widget, &QObject::destroyed, - this, &DockWindowManager::onWidgetDestroyed); - delete dw; // destruct the QDockWidget, i.e. the parent of the widget + disconnect(dw, &QObject::destroyed, this, &DockWindowManager::onDockWidgetDestroyed); + disconnect(widget, &QObject::destroyed, this, &DockWindowManager::onWidgetDestroyed); + delete dw; // destruct the QDockWidget, i.e. the parent of the widget break; } } @@ -410,8 +433,9 @@ void DockWindowManager::activate(QWidget* widget) par = par->parentWidget(); } - if (!dw) + if (!dw) { return; + } if (!dw->toggleViewAction()->isChecked()) { dw->toggleViewAction()->activate(QAction::Trigger); @@ -425,19 +449,22 @@ void DockWindowManager::activate(QWidget* widget) */ void DockWindowManager::retranslate() { - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { QString title = (*it)->windowTitle(); - if (title.isEmpty()) + if (title.isEmpty()) { (*it)->setWindowTitle(QDockWidget::tr((*it)->objectName().toUtf8())); - else + } + else { (*it)->setWindowTitle(title); + } } } /** - * Appends a new \a widget with \a name to the list of available dock widgets. The caller must make sure that - * the name is unique. If a widget with this name is already registered nothing is done but false is returned, - * otherwise it is appended and true is returned. + * Appends a new \a widget with \a name to the list of available dock widgets. The caller must make + * sure that the name is unique. If a widget with this name is already registered nothing is done + * but false is returned, otherwise it is appended and true is returned. * * As default the following widgets are already registered: * \li Std_TreeView @@ -447,26 +474,27 @@ void DockWindowManager::retranslate() * \li Std_ComboView * \li Std_SelectionView * - * To avoid name clashes the caller should use names of the form \a module_widgettype, i. e. if a analyse dialog for - * the mesh module is added the name must then be Mesh_AnalyzeDialog. + * To avoid name clashes the caller should use names of the form \a module_widgettype, i. e. if a + * analyse dialog for the mesh module is added the name must then be Mesh_AnalyzeDialog. * - * To make use of dock windows when a workbench gets loaded the method setupDockWindows() must reimplemented in a - * subclass of Gui::Workbench. + * To make use of dock windows when a workbench gets loaded the method setupDockWindows() must + * reimplemented in a subclass of Gui::Workbench. */ bool DockWindowManager::registerDockWindow(const char* name, QWidget* widget) { - QMap >::Iterator it = d->_dockWindows.find(QString::fromUtf8(name)); - if (it != d->_dockWindows.end() || !widget) + QMap>::Iterator it = d->_dockWindows.find(QString::fromUtf8(name)); + if (it != d->_dockWindows.end() || !widget) { return false; + } d->_dockWindows[QString::fromUtf8(name)] = widget; - widget->hide(); // hide the widget if not used + widget->hide(); // hide the widget if not used return true; } QWidget* DockWindowManager::unregisterDockWindow(const char* name) { QWidget* widget = nullptr; - QMap >::Iterator it = d->_dockWindows.find(QString::fromUtf8(name)); + QMap>::Iterator it = d->_dockWindows.find(QString::fromUtf8(name)); if (it != d->_dockWindows.end()) { widget = d->_dockWindows.take(QString::fromUtf8(name)); } @@ -476,9 +504,10 @@ QWidget* DockWindowManager::unregisterDockWindow(const char* name) QWidget* DockWindowManager::findRegisteredDockWindow(const char* name) { - QMap >::Iterator it = d->_dockWindows.find(QString::fromUtf8(name)); - if (it != d->_dockWindows.end()) + QMap>::Iterator it = d->_dockWindows.find(QString::fromUtf8(name)); + if (it != d->_dockWindows.end()) { return it.value(); + } return nullptr; } @@ -497,7 +526,7 @@ void DockWindowManager::setup(DockWindowItems* items) bool visible = d->_hPref->GetBool(dockName.constData(), it.visibility); if (!dw) { - QMap >::Iterator jt = d->_dockWindows.find(it.name); + QMap>::Iterator jt = d->_dockWindows.find(it.name); if (jt != d->_dockWindows.end()) { dw = addDockWindow(jt.value()->objectName().toUtf8(), jt.value(), it.pos); jt.value()->show(); @@ -586,8 +615,11 @@ void DockWindowManager::saveState() void DockWindowManager::loadState() { - ParameterGrp::handle hPref = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("MainWindow")->GetGroup("DockWindows"); + ParameterGrp::handle hPref = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("MainWindow") + ->GetGroup("DockWindows"); const QList& dockItems = d->_dockWindowItems.dockWidgets(); for (QList::ConstIterator it = dockItems.begin(); it != dockItems.end(); ++it) { QDockWidget* dw = findDockWidget(d->_dockedWindows, it->name); @@ -602,8 +634,9 @@ void DockWindowManager::loadState() QDockWidget* DockWindowManager::findDockWidget(const QList& dw, const QString& name) const { for (QList::ConstIterator it = dw.begin(); it != dw.end(); ++it) { - if ((*it)->toggleViewAction()->data().toString() == name) + if ((*it)->toggleViewAction()->data().toString() == name) { return *it; + } } return nullptr; @@ -611,7 +644,8 @@ QDockWidget* DockWindowManager::findDockWidget(const QList& dw, co void DockWindowManager::onDockWidgetDestroyed(QObject* dw) { - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { if (*it == dw) { d->_dockedWindows.erase(it); break; @@ -621,11 +655,11 @@ void DockWindowManager::onDockWidgetDestroyed(QObject* dw) void DockWindowManager::onWidgetDestroyed(QObject* widget) { - for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); ++it) { + for (QList::Iterator it = d->_dockedWindows.begin(); it != d->_dockedWindows.end(); + ++it) { // make sure that the dock widget is not about to being deleted if ((*it)->metaObject() != &QDockWidget::staticMetaObject) { - disconnect(*it, &QObject::destroyed, - this, &DockWindowManager::onDockWidgetDestroyed); + disconnect(*it, &QObject::destroyed, this, &DockWindowManager::onDockWidgetDestroyed); d->_dockedWindows.erase(it); break; } diff --git a/src/Gui/DockWindowManager.h b/src/Gui/DockWindowManager.h index 19cf6fe230..d6dae97bca 100644 --- a/src/Gui/DockWindowManager.h +++ b/src/Gui/DockWindowManager.h @@ -30,7 +30,8 @@ class QDockWidget; class QWidget; -namespace Gui { +namespace Gui +{ enum class DockWindowOption { @@ -44,7 +45,8 @@ enum class DockWindowOption using DockWindowOptions = Base::Flags; -struct DockWindowItem { +struct DockWindowItem +{ QString name; Qt::DockWidgetArea pos; bool visibility; @@ -71,7 +73,7 @@ private: * Class that manages the widgets inside a QDockWidget. * \author Werner Mayer */ -class GuiExport DockWindowManager : public QObject +class GuiExport DockWindowManager: public QObject { Q_OBJECT @@ -86,8 +88,11 @@ public: void setup(DockWindowItems*); /// Adds a QDockWidget to the main window and sets \a widget as its widget - QDockWidget* addDockWindow(const char* name, QWidget* widget, - Qt::DockWidgetArea pos = Qt::AllDockWidgetAreas); + QDockWidget* addDockWindow( + const char* name, + QWidget* widget, + Qt::DockWidgetArea pos = Qt::AllDockWidgetAreas + ); /// Removes and destroys the QDockWidget and returns the widget /// with name \a name added with @ref addDockWindow. QWidget* removeDockWindow(const char* name); @@ -113,13 +118,13 @@ public: bool isOverlayActivated() const; private Q_SLOTS: - /** - * \internal - */ + /** + * \internal + */ void onDockWidgetDestroyed(QObject*); - /** - * \internal - */ + /** + * \internal + */ void onWidgetDestroyed(QObject*); private: @@ -133,8 +138,8 @@ private: struct DockWindowManagerP* d; }; -} // namespace Gui +} // namespace Gui ENABLE_BITMASK_OPERATORS(Gui::DockWindowOption) -#endif // GUI_DOCKWINDOWMANAGER_H +#endif // GUI_DOCKWINDOWMANAGER_H diff --git a/src/Gui/Document.cpp b/src/Gui/Document.cpp index 497f54f18d..42855bdf8f 100644 --- a/src/Gui/Document.cpp +++ b/src/Gui/Document.cpp @@ -20,26 +20,26 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -78,42 +78,43 @@ FC_LOG_LEVEL_INIT("Gui", true, true) using namespace Gui; namespace sp = std::placeholders; -namespace Gui { +namespace Gui +{ // Pimpl class struct DocumentP { Thumbnail thumb; - int _iWinCount; - int _iDocId; - bool _isClosing; - bool _isModified; - bool _isTransacting; - bool _changeViewTouchDocument; - bool _editWantsRestore; - bool _editWantsRestorePrevious; - int _editMode; - int _editModePrevious; - ViewProvider* _editViewProvider; - ViewProvider* _editViewProviderPrevious; - App::DocumentObject* _editingObject; + int _iWinCount; + int _iDocId; + bool _isClosing; + bool _isModified; + bool _isTransacting; + bool _changeViewTouchDocument; + bool _editWantsRestore; + bool _editWantsRestorePrevious; + int _editMode; + int _editModePrevious; + ViewProvider* _editViewProvider; + ViewProvider* _editViewProviderPrevious; + App::DocumentObject* _editingObject; ViewProviderDocumentObject* _editViewProviderParent; - std::string _editSubname; - std::string _editSubElement; - Base::Matrix4D _editingTransform; - View3DInventorViewer* _editingViewer; + std::string _editSubname; + std::string _editSubElement; + Base::Matrix4D _editingTransform; + View3DInventorViewer* _editingViewer; std::set _editObjs; - Application* _pcAppWnd; + Application* _pcAppWnd; // the doc/Document - App::Document* _pcDocument; + App::Document* _pcDocument; /// List of all registered views std::list baseViews; /// List of all registered views std::list passiveViews; - std::map _ViewProviderMap; - std::map _CoinMap; - std::map _ViewProviderMapAnnotation; + std::map _ViewProviderMap; + std::map _CoinMap; + std::map _ViewProviderMapAnnotation; std::list _redoViewProviders; using Connection = boost::signals2::connection; @@ -188,25 +189,19 @@ struct DocumentP // and make sure you get the document right. // std::stringstream str; - str << "cannot edit object '" - << obj->getNameInDocument() - << "': not found in document " - << "'" - << doc->getName() - << "'"; + str << "cannot edit object '" << obj->getNameInDocument() << "': not found in document " + << "'" << doc->getName() << "'"; throw Base::RuntimeError(str.str()); } } - App::DocumentObject* tryGetSubObject(App::DocumentObject* obj, const char *subname) + App::DocumentObject* tryGetSubObject(App::DocumentObject* obj, const char* subname) { _editingTransform = Base::Matrix4D(); auto sobj = obj->getSubObject(subname, nullptr, &_editingTransform); if (!sobj || !sobj->isAttachedToDocument()) { std::stringstream str; - str << "Invalid sub object '" - << obj->getFullName() - << '.' << (subname ? subname : "") + str << "Invalid sub object '" << obj->getFullName() << '.' << (subname ? subname : "") << "'"; throw Base::RuntimeError(str.str()); } @@ -214,19 +209,20 @@ struct DocumentP return sobj; } - ViewProviderDocumentObject* tryGetSubViewProvider(ViewProviderDocumentObject* vp, - App::DocumentObject* obj, - App::DocumentObject* sobj) const + ViewProviderDocumentObject* tryGetSubViewProvider( + ViewProviderDocumentObject* vp, + App::DocumentObject* obj, + App::DocumentObject* sobj + ) const { auto svp = vp; if (sobj != obj) { svp = freecad_cast( - Application::Instance->getViewProvider(sobj)); + Application::Instance->getViewProvider(sobj) + ); if (!svp) { std::stringstream str; - str << "Cannot edit '" - << sobj->getFullName() - << "' without view provider"; + str << "Cannot edit '" << sobj->getFullName() << "' without view provider"; throw Base::RuntimeError(str.str()); } } @@ -248,7 +244,7 @@ struct DocumentP void findElementName(const char* subname) { if (subname) { - const char *element = Data::findElementName(subname); + const char* element = Data::findElementName(subname); if (element) { _editSubname = std::string(subname, element - subname); _editSubElement = element; @@ -266,10 +262,12 @@ struct DocumentP _editObjs.insert(sobjs.begin(), sobjs.end()); } - bool tryStartEditing(ViewProviderDocumentObject* vp, - App::DocumentObject* obj, - const char* subname, - int ModNum) + bool tryStartEditing( + ViewProviderDocumentObject* vp, + App::DocumentObject* obj, + const char* subname, + int ModNum + ) { auto sobj = tryGetSubObject(obj, subname); auto svp = tryGetSubViewProvider(vp, obj, sobj); @@ -324,12 +322,10 @@ struct DocumentP class ParentFinder { public: - ParentFinder(App::DocumentObject* obj, - ViewProviderDocumentObject* vp, - const std::string& subname) - : obj{obj} - , vp{vp} - , subname{subname} + ParentFinder(App::DocumentObject* obj, ViewProviderDocumentObject* vp, const std::string& subname) + : obj {obj} + , vp {vp} + , subname {subname} {} App::DocumentObject* getObject() const @@ -363,15 +359,14 @@ public: } private: - static std::tuple - findParentAndSubName(App::DocumentObject* obj) + static std::tuple findParentAndSubName(App::DocumentObject* obj) { // No subname reference is given, we try to extract one from the current // selection in order to obtain the correct transformation matrix below auto sels = Gui::Selection().getCompleteSelection(ResolveMode::NoResolve); App::DocumentObject* parentObj = nullptr; std::string _subname; - for (auto &sel : sels) { + for (auto& sel : sels) { if (!sel.pObject || !sel.pObject->isAttachedToDocument()) { continue; } @@ -397,12 +392,15 @@ private: return std::make_tuple(parentObj, _subname); } - static Gui::ViewProviderDocumentObject* findParentObject(App::DocumentObject* parentObj, - const char* subname) + static Gui::ViewProviderDocumentObject* findParentObject( + App::DocumentObject* parentObj, + const char* subname + ) { FC_LOG("deduced editing reference " << parentObj->getFullName() << '.' << subname); auto vp = freecad_cast( - Application::Instance->getViewProvider(parentObj)); + Application::Instance->getViewProvider(parentObj) + ); if (!vp || !vp->getDocument()) { throw Base::RuntimeError("invalid view provider for parent object"); } @@ -416,7 +414,7 @@ private: std::string subname; }; -} // namespace Gui +} // namespace Gui /* TRANSLATOR Gui::Document */ @@ -424,7 +422,7 @@ private: int Document::_iDocCount = 0; -Document::Document(App::Document* pcDocument,Application * app) +Document::Document(App::Document* pcDocument, Application* app) { d = new DocumentP; d->_iWinCount = 1; @@ -445,62 +443,84 @@ Document::Document(App::Document* pcDocument,Application * app) d->_editWantsRestore = false; d->_editWantsRestorePrevious = false; - //NOLINTBEGIN - // Setup the connections - d->connectNewObject = pcDocument->signalNewObject.connect - (std::bind(&Gui::Document::slotNewObject, this, sp::_1)); - d->connectDelObject = pcDocument->signalDeletedObject.connect - (std::bind(&Gui::Document::slotDeletedObject, this, sp::_1)); - d->connectCngObject = pcDocument->signalChangedObject.connect - (std::bind(&Gui::Document::slotChangedObject, this, sp::_1, sp::_2)); - d->connectRenObject = pcDocument->signalRelabelObject.connect - (std::bind(&Gui::Document::slotRelabelObject, this, sp::_1)); - d->connectActObject = pcDocument->signalActivatedObject.connect - (std::bind(&Gui::Document::slotActivatedObject, this, sp::_1)); - d->connectActObjectBlocker = boost::signals2::shared_connection_block - (d->connectActObject, false); - d->connectSaveDocument = pcDocument->signalSaveDocument.connect - (std::bind(&Gui::Document::Save, this, sp::_1)); - d->connectRestDocument = pcDocument->signalRestoreDocument.connect - (std::bind(&Gui::Document::Restore, this, sp::_1)); - d->connectStartLoadDocument = App::GetApplication().signalStartRestoreDocument.connect - (std::bind(&Gui::Document::slotStartRestoreDocument, this, sp::_1)); - d->connectFinishLoadDocument = App::GetApplication().signalFinishRestoreDocument.connect - (std::bind(&Gui::Document::slotFinishRestoreDocument, this, sp::_1)); - d->connectShowHidden = App::GetApplication().signalShowHidden.connect - (std::bind(&Gui::Document::slotShowHidden, this, sp::_1)); + // NOLINTBEGIN + // Setup the connections + d->connectNewObject = pcDocument->signalNewObject.connect( + std::bind(&Gui::Document::slotNewObject, this, sp::_1) + ); + d->connectDelObject = pcDocument->signalDeletedObject.connect( + std::bind(&Gui::Document::slotDeletedObject, this, sp::_1) + ); + d->connectCngObject = pcDocument->signalChangedObject.connect( + std::bind(&Gui::Document::slotChangedObject, this, sp::_1, sp::_2) + ); + d->connectRenObject = pcDocument->signalRelabelObject.connect( + std::bind(&Gui::Document::slotRelabelObject, this, sp::_1) + ); + d->connectActObject = pcDocument->signalActivatedObject.connect( + std::bind(&Gui::Document::slotActivatedObject, this, sp::_1) + ); + d->connectActObjectBlocker = boost::signals2::shared_connection_block(d->connectActObject, false); + d->connectSaveDocument = pcDocument->signalSaveDocument.connect( + std::bind(&Gui::Document::Save, this, sp::_1) + ); + d->connectRestDocument = pcDocument->signalRestoreDocument.connect( + std::bind(&Gui::Document::Restore, this, sp::_1) + ); + d->connectStartLoadDocument = App::GetApplication().signalStartRestoreDocument.connect( + std::bind(&Gui::Document::slotStartRestoreDocument, this, sp::_1) + ); + d->connectFinishLoadDocument = App::GetApplication().signalFinishRestoreDocument.connect( + std::bind(&Gui::Document::slotFinishRestoreDocument, this, sp::_1) + ); + d->connectShowHidden = App::GetApplication().signalShowHidden.connect( + std::bind(&Gui::Document::slotShowHidden, this, sp::_1) + ); - d->connectChangePropertyEditor = pcDocument->signalChangePropertyEditor.connect - (std::bind(&Gui::Document::slotChangePropertyEditor, this, sp::_1, sp::_2)); - d->connectChangeDocument = d->_pcDocument->signalChanged.connect // use the same slot function - (std::bind(&Gui::Document::slotChangePropertyEditor, this, sp::_1, sp::_2)); - d->connectChangeDocumentBlocker = boost::signals2::shared_connection_block - (d->connectChangeDocument, true); - d->connectFinishRestoreObject = pcDocument->signalFinishRestoreObject.connect - (std::bind(&Gui::Document::slotFinishRestoreObject, this, sp::_1)); - d->connectExportObjects = pcDocument->signalExportViewObjects.connect - (std::bind(&Gui::Document::exportObjects, this, sp::_1, sp::_2)); - d->connectImportObjects = pcDocument->signalImportViewObjects.connect - (std::bind(&Gui::Document::importObjects, this, sp::_1, sp::_2, sp::_3)); - d->connectFinishImportObjects = pcDocument->signalFinishImportObjects.connect - (std::bind(&Gui::Document::slotFinishImportObjects, this, sp::_1)); + d->connectChangePropertyEditor = pcDocument->signalChangePropertyEditor.connect( + std::bind(&Gui::Document::slotChangePropertyEditor, this, sp::_1, sp::_2) + ); + d->connectChangeDocument + = d->_pcDocument->signalChanged.connect // use the same slot function + (std::bind(&Gui::Document::slotChangePropertyEditor, this, sp::_1, sp::_2)); + d->connectChangeDocumentBlocker + = boost::signals2::shared_connection_block(d->connectChangeDocument, true); + d->connectFinishRestoreObject = pcDocument->signalFinishRestoreObject.connect( + std::bind(&Gui::Document::slotFinishRestoreObject, this, sp::_1) + ); + d->connectExportObjects = pcDocument->signalExportViewObjects.connect( + std::bind(&Gui::Document::exportObjects, this, sp::_1, sp::_2) + ); + d->connectImportObjects = pcDocument->signalImportViewObjects.connect( + std::bind(&Gui::Document::importObjects, this, sp::_1, sp::_2, sp::_3) + ); + d->connectFinishImportObjects = pcDocument->signalFinishImportObjects.connect( + std::bind(&Gui::Document::slotFinishImportObjects, this, sp::_1) + ); - d->connectUndoDocument = pcDocument->signalUndo.connect - (std::bind(&Gui::Document::slotUndoDocument, this, sp::_1)); - d->connectRedoDocument = pcDocument->signalRedo.connect - (std::bind(&Gui::Document::slotRedoDocument, this, sp::_1)); - d->connectRecomputed = pcDocument->signalRecomputed.connect - (std::bind(&Gui::Document::slotRecomputed, this, sp::_1)); - d->connectSkipRecompute = pcDocument->signalSkipRecompute.connect - (std::bind(&Gui::Document::slotSkipRecompute, this, sp::_1, sp::_2)); - d->connectTouchedObject = pcDocument->signalTouchedObject.connect - (std::bind(&Gui::Document::slotTouchedObject, this, sp::_1)); + d->connectUndoDocument = pcDocument->signalUndo.connect( + std::bind(&Gui::Document::slotUndoDocument, this, sp::_1) + ); + d->connectRedoDocument = pcDocument->signalRedo.connect( + std::bind(&Gui::Document::slotRedoDocument, this, sp::_1) + ); + d->connectRecomputed = pcDocument->signalRecomputed.connect( + std::bind(&Gui::Document::slotRecomputed, this, sp::_1) + ); + d->connectSkipRecompute = pcDocument->signalSkipRecompute.connect( + std::bind(&Gui::Document::slotSkipRecompute, this, sp::_1, sp::_2) + ); + d->connectTouchedObject = pcDocument->signalTouchedObject.connect( + std::bind(&Gui::Document::slotTouchedObject, this, sp::_1) + ); - d->connectTransactionAppend = pcDocument->signalTransactionAppend.connect - (std::bind(&Gui::Document::slotTransactionAppend, this, sp::_1, sp::_2)); - d->connectTransactionRemove = pcDocument->signalTransactionRemove.connect - (std::bind(&Gui::Document::slotTransactionRemove, this, sp::_1, sp::_2)); - //NOLINTEND + d->connectTransactionAppend = pcDocument->signalTransactionAppend.connect( + std::bind(&Gui::Document::slotTransactionAppend, this, sp::_1, sp::_2) + ); + d->connectTransactionRemove = pcDocument->signalTransactionRemove.connect( + std::bind(&Gui::Document::slotTransactionRemove, this, sp::_1, sp::_2) + ); + // NOLINTEND pcDocument->setPreRecomputeHook([this] { callSignalBeforeRecompute(); }); @@ -510,11 +530,13 @@ Document::Document(App::Document* pcDocument,Application * app) Base::PyGILStateLocker lock; _pcDocPy = new Gui::DocumentPy(this); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document"); - if (hGrp->GetBool("UsingUndo",true)) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Document" + ); + if (hGrp->GetBool("UsingUndo", true)) { d->_pcDocument->setUndoMode(1); // set the maximum stack size - d->_pcDocument->setMaxUndoStackSize(hGrp->GetInt("MaxUndoSize",20)); + d->_pcDocument->setMaxUndoStackSize(hGrp->GetInt("MaxUndoSize", 20)); } d->_changeViewTouchDocument = hGrp->GetBool("ChangeViewProviderTouchDocument", true); @@ -552,15 +574,19 @@ Document::~Document() d->_isClosing = true; // calls Document::detachView() and alter the view list std::list temp = d->baseViews; - for(auto & it : temp) + for (auto& it : temp) { it->deleteSelf(); + } - std::map::iterator jt; - for (jt = d->_ViewProviderMap.begin();jt != d->_ViewProviderMap.end(); ++jt) + std::map::iterator jt; + for (jt = d->_ViewProviderMap.begin(); jt != d->_ViewProviderMap.end(); ++jt) { delete jt->second; - std::map::iterator it2; - for (it2 = d->_ViewProviderMapAnnotation.begin();it2 != d->_ViewProviderMapAnnotation.end(); ++it2) + } + std::map::iterator it2; + for (it2 = d->_ViewProviderMapAnnotation.begin(); it2 != d->_ViewProviderMapAnnotation.end(); + ++it2) { delete it2->second; + } // remove the reference from the object Base::PyGILStateLocker lock; @@ -573,7 +599,7 @@ Document::~Document() // 3D viewer handling //***************************************************************************************************** -bool Document::setEdit(Gui::ViewProvider* p, int ModNum, const char *subname) +bool Document::setEdit(Gui::ViewProvider* p, int ModNum, const char* subname) { try { return trySetEdit(p, ModNum, subname); @@ -596,13 +622,13 @@ void Document::resetIfEditing() View3DInventor* Document::openEditingView3D(const ViewProviderDocumentObject* vp) { - auto view3d = dynamic_cast(getActiveView()); + auto view3d = dynamic_cast(getActiveView()); // if the currently active view is not the 3d view search for it and activate it if (view3d) { getMainWindow()->setActiveWindow(view3d); } else { - view3d = dynamic_cast(setActiveView(vp)); + view3d = dynamic_cast(setActiveView(vp)); } return view3d; @@ -610,15 +636,15 @@ View3DInventor* Document::openEditingView3D(const ViewProviderDocumentObject* vp View3DInventor* Document::openEditingView3D(const App::DocumentObject* obj) { - if (auto vp = freecad_cast( - Application::Instance->getViewProvider(obj))) { + if (auto vp + = freecad_cast(Application::Instance->getViewProvider(obj))) { return openEditingView3D(vp); } return nullptr; } -bool Document::trySetEdit(Gui::ViewProvider* p, int ModNum, const char *subname) +bool Document::trySetEdit(Gui::ViewProvider* p, int ModNum, const char* subname) { auto vp = DocumentP::throwIfCastFails(p); @@ -658,19 +684,23 @@ bool Document::trySetEdit(Gui::ViewProvider* p, int ModNum, const char *subname) return true; } -const Base::Matrix4D &Document::getEditingTransform() const { +const Base::Matrix4D& Document::getEditingTransform() const +{ return d->_editingTransform; } -void Document::setEditingTransform(const Base::Matrix4D &mat) { +void Document::setEditingTransform(const Base::Matrix4D& mat) +{ d->_editObjs.clear(); d->_editingTransform = mat; - auto activeView = dynamic_cast(getActiveView()); - if (activeView) + auto activeView = dynamic_cast(getActiveView()); + if (activeView) { activeView->getViewer()->setEditingTransform(mat); + } } -void Document::resetEdit() { +void Document::resetEdit() +{ bool vpIsNotNull = d->_editViewProvider != nullptr; bool vpHasChanged = d->_editViewProvider != d->_editViewProviderPrevious; int modeToRestore = d->_editModePrevious; @@ -688,10 +718,11 @@ void Document::_resetEdit() { std::list::iterator it; if (d->_editViewProvider) { - for (it = d->baseViews.begin();it != d->baseViews.end();++it) { - auto activeView = dynamic_cast(*it); - if (activeView) + for (it = d->baseViews.begin(); it != d->baseViews.end(); ++it) { + auto activeView = dynamic_cast(*it); + if (activeView) { activeView->getViewer()->resetEditingViewProvider(); + } } d->_editViewProvider->finishEditing(); @@ -705,7 +736,8 @@ void Document::_resetEdit() // the editing object gets deleted inside the above call to // 'finishEditing()', which will trigger our slotDeletedObject(), which // nullifies _editViewProvider. - if (d->_editViewProvider && d->_editViewProvider->isDerivedFrom()) { + if (d->_editViewProvider + && d->_editViewProvider->isDerivedFrom()) { auto vpd = static_cast(d->_editViewProvider); vpd->getDocument()->signalResetEdit(*vpd); } @@ -727,48 +759,64 @@ void Document::_resetEdit() } } -ViewProvider *Document::getInEdit(ViewProviderDocumentObject **parentVp, - std::string *subname, int *mode, std::string *subelement) const +ViewProvider* Document::getInEdit( + ViewProviderDocumentObject** parentVp, + std::string* subname, + int* mode, + std::string* subelement +) const { - if(parentVp) *parentVp = d->_editViewProviderParent; - if(subname) *subname = d->_editSubname; - if(subelement) *subelement = d->_editSubElement; - if(mode) *mode = d->_editMode; + if (parentVp) { + *parentVp = d->_editViewProviderParent; + } + if (subname) { + *subname = d->_editSubname; + } + if (subelement) { + *subelement = d->_editSubElement; + } + if (mode) { + *mode = d->_editMode; + } if (d->_editViewProvider) { // there is only one 3d view which is in edit mode - auto activeView = dynamic_cast(getActiveView()); - if (activeView && activeView->getViewer()->isEditingViewProvider()) + auto activeView = dynamic_cast(getActiveView()); + if (activeView && activeView->getViewer()->isEditingViewProvider()) { return d->_editViewProvider; + } } return nullptr; } -void Document::setInEdit(ViewProviderDocumentObject *parentVp, const char *subname) { +void Document::setInEdit(ViewProviderDocumentObject* parentVp, const char* subname) +{ if (d->_editViewProvider) { d->_editViewProviderParent = parentVp; - d->_editSubname = subname?subname:""; + d->_editSubname = subname ? subname : ""; } } -void Document::setAnnotationViewProvider(const char* name, ViewProvider *pcProvider) +void Document::setAnnotationViewProvider(const char* name, ViewProvider* pcProvider) { std::list::iterator vIt; // already in ? - std::map::iterator it = d->_ViewProviderMapAnnotation.find(name); - if (it != d->_ViewProviderMapAnnotation.end()) + std::map::iterator it = d->_ViewProviderMapAnnotation.find(name); + if (it != d->_ViewProviderMapAnnotation.end()) { removeAnnotationViewProvider(name); + } // add d->_ViewProviderMapAnnotation[name] = pcProvider; // cycling to all views of the document - for (vIt = d->baseViews.begin();vIt != d->baseViews.end();++vIt) { - auto activeView = dynamic_cast(*vIt); - if (activeView) + for (vIt = d->baseViews.begin(); vIt != d->baseViews.end(); ++vIt) { + auto activeView = dynamic_cast(*vIt); + if (activeView) { activeView->getViewer()->addViewProvider(pcProvider); + } } } @@ -777,18 +825,19 @@ void Document::setEditRestore(bool askRestore) d->_editWantsRestore = askRestore; } -ViewProvider * Document::getAnnotationViewProvider(const char* name) const +ViewProvider* Document::getAnnotationViewProvider(const char* name) const { - std::map::const_iterator it = d->_ViewProviderMapAnnotation.find(name); - return ( (it != d->_ViewProviderMapAnnotation.end()) ? it->second : 0 ); + std::map::const_iterator it = d->_ViewProviderMapAnnotation.find(name); + return ((it != d->_ViewProviderMapAnnotation.end()) ? it->second : 0); } bool Document::isAnnotationViewProvider(const ViewProvider* vp) const { - std::map::const_iterator it; + std::map::const_iterator it; for (it = d->_ViewProviderMapAnnotation.begin(); it != d->_ViewProviderMapAnnotation.end(); ++it) { - if (it->second == vp) + if (it->second == vp) { return true; + } } return false; } @@ -806,7 +855,7 @@ ViewProvider* Document::takeAnnotationViewProvider(const char* name) // cycling to all views of the document for (auto vIt : d->baseViews) { - if (auto activeView = dynamic_cast(vIt)) { + if (auto activeView = dynamic_cast(vIt)) { activeView->getViewer()->removeViewProvider(vp); } } @@ -823,40 +872,46 @@ void Document::removeAnnotationViewProvider(const char* name) ViewProvider* Document::getViewProvider(const App::DocumentObject* Feat) const { - std::map::const_iterator - it = d->_ViewProviderMap.find( Feat ); - return ( (it != d->_ViewProviderMap.end()) ? it->second : 0 ); + std::map::const_iterator it + = d->_ViewProviderMap.find(Feat); + return ((it != d->_ViewProviderMap.end()) ? it->second : 0); } std::vector Document::getViewProvidersOfType(const Base::Type& typeId) const { std::vector Objects; - for (std::map::const_iterator it = - d->_ViewProviderMap.begin(); it != d->_ViewProviderMap.end(); ++it ) { - if (it->second->isDerivedFrom(typeId)) + for (std::map::const_iterator it + = d->_ViewProviderMap.begin(); + it != d->_ViewProviderMap.end(); + ++it) { + if (it->second->isDerivedFrom(typeId)) { Objects.push_back(it->second); + } } return Objects; } -ViewProvider *Document::getViewProviderByName(const char* name) const +ViewProvider* Document::getViewProviderByName(const char* name) const { // first check on feature name - App::DocumentObject *pcFeat = getDocument()->getObject(name); + App::DocumentObject* pcFeat = getDocument()->getObject(name); - if (pcFeat) - { - std::map::const_iterator - it = d->_ViewProviderMap.find( pcFeat ); + if (pcFeat) { + std::map::const_iterator it + = d->_ViewProviderMap.find(pcFeat); - if (it != d->_ViewProviderMap.end()) + if (it != d->_ViewProviderMap.end()) { return it->second; - } else { + } + } + else { // then try annotation name - std::map::const_iterator it2 = d->_ViewProviderMapAnnotation.find( name ); + std::map::const_iterator it2 + = d->_ViewProviderMapAnnotation.find(name); - if (it2 != d->_ViewProviderMapAnnotation.end()) + if (it2 != d->_ViewProviderMapAnnotation.end()) { return it2->second; + } } return nullptr; @@ -892,9 +947,9 @@ void Document::setHide(const char* name) void Document::setPos(const char* name, const Base::Matrix4D& rclMtrx) { ViewProvider* pcProv = getViewProviderByName(name); - if (pcProv) + if (pcProv) { pcProv->setTransformation(rclMtrx); - + } } //***************************************************************************************************** @@ -905,13 +960,17 @@ void Document::slotNewObject(const App::DocumentObject& Obj) auto pcProvider = static_cast(getViewProvider(&Obj)); if (!pcProvider) { std::string cName = Obj.getViewProviderNameStored(); - for(;;) { + for (;;) { if (cName.empty()) { // handle document object with no view provider specified FC_LOG(Obj.getFullName() << " has no view provider specified"); return; } - Base::Type type = Base::Type::getTypeIfDerivedFrom(cName.c_str(), ViewProviderDocumentObject::getClassTypeId(), true); + Base::Type type = Base::Type::getTypeIfDerivedFrom( + cName.c_str(), + ViewProviderDocumentObject::getClassTypeId(), + true + ); pcProvider = static_cast(type.createInstance()); // createInstance could return a null pointer if (!pcProvider) { @@ -919,7 +978,7 @@ void Document::slotNewObject(const App::DocumentObject& Obj) FC_ERR("Invalid view provider type '" << cName << "' for " << Obj.getFullName()); return; } - else if (cName!=Obj.getViewProviderName() && !pcProvider->allowOverride(Obj)) { + else if (cName != Obj.getViewProviderName() && !pcProvider->allowOverride(Obj)) { FC_WARN("View provider type '" << cName << "' does not support " << Obj.getFullName()); delete pcProvider; pcProvider = nullptr; @@ -937,26 +996,28 @@ void Document::slotNewObject(const App::DocumentObject& Obj) try { // if successfully created set the right name and calculate the view - //FIXME: Consider to change argument of attach() to const pointer + // FIXME: Consider to change argument of attach() to const pointer pcProvider->attach(const_cast(&Obj)); pcProvider->updateView(); pcProvider->setActiveMode(); } - catch(const Base::MemoryException& e){ + catch (const Base::MemoryException& e) { FC_ERR("Memory exception in " << Obj.getFullName() << " thrown: " << e.what()); } - catch(Base::Exception &e){ + catch (Base::Exception& e) { e.reportException(); } #ifndef FC_DEBUG - catch(...){ + catch (...) { FC_ERR("Unknown exception in Feature " << Obj.getFullName() << " thrown"); } #endif - }else{ + } + else { try { pcProvider->reattach(const_cast(&Obj)); - } catch(Base::Exception &e){ + } + catch (Base::Exception& e) { e.reportException(); } } @@ -964,10 +1025,11 @@ void Document::slotNewObject(const App::DocumentObject& Obj) if (pcProvider) { std::list::iterator vIt; // cycling to all views of the document - for (vIt = d->baseViews.begin();vIt != d->baseViews.end();++vIt) { - auto activeView = dynamic_cast(*vIt); - if (activeView) + for (vIt = d->baseViews.begin(); vIt != d->baseViews.end(); ++vIt) { + auto activeView = dynamic_cast(*vIt); + if (activeView) { activeView->getViewer()->addViewProvider(pcProvider); + } } // adding to the tree @@ -989,27 +1051,30 @@ void Document::slotDeletedObject(const App::DocumentObject& Obj) // cycling to all views of the document ViewProvider* viewProvider = getViewProvider(&Obj); - if(!viewProvider) + if (!viewProvider) { return; - - if (d->_editViewProvider==viewProvider || d->_editViewProviderParent==viewProvider) - _resetEdit(); - else if(Application::Instance->editDocument()) { - auto editDoc = Application::Instance->editDocument(); - if(editDoc->d->_editViewProvider==viewProvider || - editDoc->d->_editViewProviderParent==viewProvider) - Application::Instance->setEditDocument(nullptr); } - handleChildren3D(viewProvider,true); + if (d->_editViewProvider == viewProvider || d->_editViewProviderParent == viewProvider) { + _resetEdit(); + } + else if (Application::Instance->editDocument()) { + auto editDoc = Application::Instance->editDocument(); + if (editDoc->d->_editViewProvider == viewProvider + || editDoc->d->_editViewProviderParent == viewProvider) { + Application::Instance->setEditDocument(nullptr); + } + } - if (viewProvider && viewProvider->isDerivedFrom - (ViewProviderDocumentObject::getClassTypeId())) { + handleChildren3D(viewProvider, true); + + if (viewProvider && viewProvider->isDerivedFrom(ViewProviderDocumentObject::getClassTypeId())) { // go through the views - for (vIt = d->baseViews.begin();vIt != d->baseViews.end();++vIt) { - auto activeView = dynamic_cast(*vIt); - if (activeView) + for (vIt = d->baseViews.begin(); vIt != d->baseViews.end(); ++vIt) { + auto activeView = dynamic_cast(*vIt); + if (activeView) { activeView->getViewer()->removeViewProvider(viewProvider); + } } // removing from tree @@ -1019,20 +1084,20 @@ void Document::slotDeletedObject(const App::DocumentObject& Obj) viewProvider->beforeDelete(); } -void Document::beforeDelete() { +void Document::beforeDelete() +{ auto editDoc = Application::Instance->editDocument(); - if(editDoc) { + if (editDoc) { auto vp = freecad_cast(editDoc->d->_editViewProvider); auto vpp = freecad_cast(editDoc->d->_editViewProviderParent); - if(editDoc == this || - (vp && vp->getDocument()==this) || - (vpp && vpp->getDocument()==this)) - { + if (editDoc == this || (vp && vp->getDocument() == this) + || (vpp && vpp->getDocument() == this)) { Application::Instance->setEditDocument(nullptr); } } - for(auto &v : d->_ViewProviderMap) + for (auto& v : d->_ViewProviderMap) { v.second->beforeDelete(); + } } void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) @@ -1041,30 +1106,27 @@ void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Prop if (viewProvider) { try { viewProvider->update(&Prop); - if(d->_editingViewer - && d->_editingObject - && d->_editViewProviderParent - && (Prop.isDerivedFrom() - // Issue ID 0004230 : getName() can return null in which case strstr() crashes - || (Prop.getName() && strstr(Prop.getName(),"Scale"))) - && d->_editObjs.contains(&Obj)) - { + if (d->_editingViewer && d->_editingObject && d->_editViewProviderParent + && (Prop.isDerivedFrom() + // Issue ID 0004230 : getName() can return null in which case strstr() crashes + || (Prop.getName() && strstr(Prop.getName(), "Scale"))) + && d->_editObjs.contains(&Obj)) { Base::Matrix4D mat; - auto sobj = d->_editViewProviderParent->getObject()->getSubObject( - d->_editSubname.c_str(),nullptr,&mat); - if(sobj == d->_editingObject && d->_editingTransform!=mat) { + auto sobj = d->_editViewProviderParent->getObject() + ->getSubObject(d->_editSubname.c_str(), nullptr, &mat); + if (sobj == d->_editingObject && d->_editingTransform != mat) { d->_editingTransform = mat; d->_editingViewer->setEditingTransform(d->_editingTransform); } } } - catch(const Base::MemoryException& e) { + catch (const Base::MemoryException& e) { FC_ERR("Memory exception in " << Obj.getFullName() << " thrown: " << e.what()); } - catch(Base::Exception& e){ + catch (Base::Exception& e) { e.reportException(); } - catch(const std::exception& e){ + catch (const std::exception& e) { FC_ERR("C++ exception in " << Obj.getFullName() << " thrown " << e.what()); } catch (...) { @@ -1073,12 +1135,13 @@ void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Prop handleChildren3D(viewProvider); - if (viewProvider->isDerivedFrom()) + if (viewProvider->isDerivedFrom()) { signalChangedObject(static_cast(*viewProvider), Prop); + } } // a property of an object has changed - if(!Prop.testStatus(App::Property::NoModify) && !isModified()) { + if (!Prop.testStatus(App::Property::NoModify) && !isModified()) { FC_LOG(Prop.getFullName() << " modified"); setModified(true); } @@ -1104,22 +1167,25 @@ void Document::slotTransactionAppend(const App::DocumentObject& obj, App::Transa void Document::slotTransactionRemove(const App::DocumentObject& obj, App::Transaction* transaction) { - std::map::const_iterator - it = d->_ViewProviderMap.find(&obj); + std::map::const_iterator it + = d->_ViewProviderMap.find(&obj); if (it != d->_ViewProviderMap.end()) { ViewProvider* viewProvider = it->second; auto itC = d->_CoinMap.find(viewProvider->getRoot()); - if(itC != d->_CoinMap.end()) + if (itC != d->_CoinMap.end()) { d->_CoinMap.erase(itC); + } d->_ViewProviderMap.erase(&obj); // transaction being a nullptr indicates that undo/redo is off and the object // can be safely deleted - if (transaction) + if (transaction) { transaction->addObjectNew(viewProvider); - else + } + else { delete viewProvider; + } } } @@ -1133,8 +1199,9 @@ void Document::slotActivatedObject(const App::DocumentObject& Obj) void Document::slotUndoDocument(const App::Document& doc) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; + } signalUndoDocument(*this); getMainWindow()->updateActions(); @@ -1142,8 +1209,9 @@ void Document::slotUndoDocument(const App::Document& doc) void Document::slotRedoDocument(const App::Document& doc) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; + } signalRedoDocument(*this); getMainWindow()->updateActions(); @@ -1151,8 +1219,9 @@ void Document::slotRedoDocument(const App::Document& doc) void Document::slotRecomputed(const App::Document& doc) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; + } getMainWindow()->updateActions(); TreeWidget::updateStatus(); } @@ -1162,32 +1231,36 @@ void Document::slotRecomputed(const App::Document& doc) // not given an explicit recomputing object list, or the given single object is // the eidting object or the active object. If the conditions are met, we'll // force recompute only that object and all its dependent objects. -void Document::slotSkipRecompute(const App::Document& doc, const std::vector &objs) +void Document::slotSkipRecompute(const App::Document& doc, const std::vector& objs) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; - if(objs.size()>1 || - App::GetApplication().getActiveDocument()!=&doc || - !doc.testStatus(App::Document::AllowPartialRecompute)) - return; - App::DocumentObject *obj = nullptr; - auto editDoc = Application::Instance->editDocument(); - if(editDoc) { - auto vp = freecad_cast(editDoc->getInEdit()); - if(vp) - obj = vp->getObject(); } - if(!obj) - obj = doc.getActiveObject(); - if(!obj || !obj->isAttachedToDocument() || (!objs.empty() && objs.front()!=obj)) + if (objs.size() > 1 || App::GetApplication().getActiveDocument() != &doc + || !doc.testStatus(App::Document::AllowPartialRecompute)) { return; + } + App::DocumentObject* obj = nullptr; + auto editDoc = Application::Instance->editDocument(); + if (editDoc) { + auto vp = freecad_cast(editDoc->getInEdit()); + if (vp) { + obj = vp->getObject(); + } + } + if (!obj) { + obj = doc.getActiveObject(); + } + if (!obj || !obj->isAttachedToDocument() || (!objs.empty() && objs.front() != obj)) { + return; + } obj->recomputeFeature(true); } -void Document::slotTouchedObject(const App::DocumentObject &Obj) +void Document::slotTouchedObject(const App::DocumentObject& Obj) { getMainWindow()->updateActions(true); - if(!isModified()) { + if (!isModified()) { FC_LOG(Obj.getFullName() << " touched"); setModified(true); } @@ -1197,7 +1270,7 @@ void Document::slotTouchedObject(const App::DocumentObject &Obj) // that the worker waits until it finishes void Document::callSignalBeforeRecompute() { - auto invokeSignalBeforeRecompute = [this]{ + auto invokeSignalBeforeRecompute = [this] { // this runs in the GUI thread this->getDocument()->signalBeforeRecompute(*this->getDocument()); }; @@ -1205,10 +1278,14 @@ void Document::callSignalBeforeRecompute() if (QThread::currentThread() == qApp->thread()) { // already on GUI thread – no hop, just call it invokeSignalBeforeRecompute(); - } else { + } + else { // hop to GUI and *block* until it returns - QMetaObject::invokeMethod(qApp, std::move(invokeSignalBeforeRecompute), - Qt::BlockingQueuedConnection); + QMetaObject::invokeMethod( + qApp, + std::move(invokeSignalBeforeRecompute), + Qt::BlockingQueuedConnection + ); } } @@ -1227,12 +1304,13 @@ void Document::addViewProvider(Gui::ViewProviderDocumentObject* vp) void Document::setModified(bool b) { - if(d->_isModified == b) + if (d->_isModified == b) { return; + } d->_isModified = b; std::list mdis = getMDIViews(); - for (auto & mdi : mdis) { + for (auto& mdi : mdis) { mdi->setWindowModified(b); } } @@ -1247,53 +1325,61 @@ bool Document::isAboutToClose() const return d->_isClosing; } -ViewProviderDocumentObject* Document::getViewProviderByPathFromTail(SoPath * path) const +ViewProviderDocumentObject* Document::getViewProviderByPathFromTail(SoPath* path) const { // Get the lowest root node in the pick path! for (int i = 0; i < path->getLength(); i++) { - SoNode *node = path->getNodeFromTail(i); + SoNode* node = path->getNodeFromTail(i); if (node->isOfType(SoSeparator::getClassTypeId())) { auto it = d->_CoinMap.find(static_cast(node)); - if(it!=d->_CoinMap.end()) + if (it != d->_CoinMap.end()) { return it->second; + } } } return nullptr; } -ViewProviderDocumentObject* Document::getViewProviderByPathFromHead(SoPath * path) const +ViewProviderDocumentObject* Document::getViewProviderByPathFromHead(SoPath* path) const { for (int i = 0; i < path->getLength(); i++) { - SoNode *node = path->getNode(i); + SoNode* node = path->getNode(i); if (node->isOfType(SoSeparator::getClassTypeId())) { auto it = d->_CoinMap.find(static_cast(node)); - if(it!=d->_CoinMap.end()) + if (it != d->_CoinMap.end()) { return it->second; + } } } return nullptr; } -ViewProviderDocumentObject *Document::getViewProvider(SoNode *node) const { - if(!node || !node->isOfType(SoSeparator::getClassTypeId())) +ViewProviderDocumentObject* Document::getViewProvider(SoNode* node) const +{ + if (!node || !node->isOfType(SoSeparator::getClassTypeId())) { return nullptr; + } auto it = d->_CoinMap.find(static_cast(node)); - if(it!=d->_CoinMap.end()) + if (it != d->_CoinMap.end()) { return it->second; + } return nullptr; } -std::vector > Document::getViewProvidersByPath(SoPath * path) const +std::vector> Document::getViewProvidersByPath( + SoPath* path +) const { - std::vector > ret; + std::vector> ret; for (int i = 0; i < path->getLength(); i++) { - SoNode *node = path->getNodeFromTail(i); + SoNode* node = path->getNodeFromTail(i); if (node->isOfType(SoSeparator::getClassTypeId())) { auto it = d->_CoinMap.find(static_cast(node)); - if(it!=d->_CoinMap.end()) - ret.emplace_back(it->second,i); + if (it != d->_CoinMap.end()) { + ret.emplace_back(it->second, i); + } } } return ret; @@ -1304,56 +1390,67 @@ App::Document* Document::getDocument() const return d->_pcDocument; } -static bool checkCanonicalPath(const std::map &docs) +static bool checkCanonicalPath(const std::map& docs) { - std::map > paths; + std::map> paths; bool warn = false; for (auto doc : App::GetApplication().getDocuments()) { QFileInfo info(QString::fromUtf8(doc->FileName.getValue())); - auto &d = paths[info.canonicalFilePath()]; + auto& d = paths[info.canonicalFilePath()]; d.push_back(doc); if (!warn && d.size() > 1) { - if (docs.contains(d.front()) || docs.contains(d.back())) + if (docs.contains(d.front()) || docs.contains(d.back())) { warn = true; + } } } - if (!warn) + if (!warn) { return true; + } QString msg; QTextStream ts(&msg); ts << QObject::tr("Identical physical path detected. It may cause unwanted overwrite of existing document!\n\n") << QObject::tr("Are you sure you want to continue?"); - auto docName = [](App::Document *doc) -> QString { - if (doc->Label.getStrValue() == doc->getName()) + auto docName = [](App::Document* doc) -> QString { + if (doc->Label.getStrValue() == doc->getName()) { return QString::fromLatin1(doc->getName()); - return QStringLiteral("%1 (%2)").arg(QString::fromUtf8(doc->Label.getValue()), - QString::fromLatin1(doc->getName())); + } + return QStringLiteral("%1 (%2)").arg( + QString::fromUtf8(doc->Label.getValue()), + QString::fromLatin1(doc->getName()) + ); }; int count = 0; - for (auto &v : paths) { - if (v.second.size() <= 1) continue; + for (auto& v : paths) { + if (v.second.size() <= 1) { + continue; + } for (auto doc : v.second) { if (docs.contains(doc)) { FC_WARN("Physical path: " << v.first.toUtf8().constData()); - for (auto d : v.second) - FC_WARN(" Document: " << docName(d).toUtf8().constData() - << ": " << d->FileName.getValue()); + for (auto d : v.second) { + FC_WARN( + " Document: " << docName(d).toUtf8().constData() << ": " + << d->FileName.getValue() + ); + } if (count == 3) { ts << "\n\n" << QObject::tr("Check report view for more…"); - } else if (count < 3) { + } + else if (count < 3) { ts << "\n\n" - << QObject::tr("Physical path:") << ' ' << v.first - << "\n" - << QObject::tr("Document:") << ' ' << docName(doc) - << "\n " - << QObject::tr("Path:") << ' ' << QString::fromUtf8(doc->FileName.getValue()); + << QObject::tr("Physical path:") << ' ' << v.first << "\n" + << QObject::tr("Document:") << ' ' << docName(doc) << "\n " + << QObject::tr("Path:") << ' ' << QString::fromUtf8(doc->FileName.getValue()); for (auto d : v.second) { - if (d == doc) continue; + if (d == doc) { + continue; + } ts << "\n" - << QObject::tr("Document:") << ' ' << docName(d) - << "\n " - << QObject::tr("Path:") << ' ' << QString::fromUtf8(d->FileName.getValue()); + << QObject::tr("Document:") << ' ' << docName(d) << "\n " + << QObject::tr("Path:") << ' ' + << QString::fromUtf8(d->FileName.getValue()); } } ++count; @@ -1361,8 +1458,13 @@ static bool checkCanonicalPath(const std::map &docs) } } } - int ret = QMessageBox::warning(getMainWindow(), - QObject::tr("Identical physical path"), msg, QMessageBox::Yes, QMessageBox::No); + int ret = QMessageBox::warning( + getMainWindow(), + QObject::tr("Identical physical path"), + msg, + QMessageBox::Yes, + QMessageBox::No + ); return ret == QMessageBox::Yes; } @@ -1371,13 +1473,17 @@ bool Document::askIfSavingFailed(const QString& error) int ret = QMessageBox::question( getMainWindow(), QObject::tr("Could not save document"), - QObject::tr("There was an issue trying to save the file. " - "This may be because some of the parent folders do not exist, " - "or you do not have sufficient permissions, " - "or for other reasons. Error details:\n\n\"%1\"\n\n" - "Would you like to save the file with a different name?") - .arg(error), - QMessageBox::Yes, QMessageBox::No); + QObject::tr( + "There was an issue trying to save the file. " + "This may be because some of the parent folders do not exist, " + "or you do not have sufficient permissions, " + "or for other reasons. Error details:\n\n\"%1\"\n\n" + "Would you like to save the file with a different name?" + ) + .arg(error), + QMessageBox::Yes, + QMessageBox::No + ); if (ret == QMessageBox::No) { // TODO: Understand what exactly is supposed to be returned here @@ -1397,21 +1503,19 @@ bool Document::save() if (d->_pcDocument->isSaved()) { try { std::vector docs; - std::map dmap; + std::map dmap; try { docs = getDocument()->getDependentDocuments(); - for (auto it=docs.begin(); it!=docs.end();) { - App::Document *doc = *it; + for (auto it = docs.begin(); it != docs.end();) { + App::Document* doc = *it; if (doc == getDocument()) { dmap[doc] = doc->mustExecute(); ++it; continue; } auto gdoc = Application::Instance->getDocument(doc); - if ((gdoc && !gdoc->isModified()) - || doc->testStatus(App::Document::PartialDoc) - || doc->testStatus(App::Document::TempDoc)) - { + if ((gdoc && !gdoc->isModified()) || doc->testStatus(App::Document::PartialDoc) + || doc->testStatus(App::Document::TempDoc)) { it = docs.erase(it); continue; } @@ -1419,19 +1523,24 @@ bool Document::save() ++it; } } - catch (const Base::RuntimeError &e) { + catch (const Base::RuntimeError& e) { FC_ERR(e.what()); docs = {getDocument()}; dmap.clear(); dmap[getDocument()] = getDocument()->mustExecute(); } - if (docs.size()>1) { - int ret = QMessageBox::question(getMainWindow(), - QObject::tr("Save dependent files"), - QObject::tr("The file contains external dependencies. " - "Do you want to save the dependent files, too?"), - QMessageBox::Yes,QMessageBox::No); + if (docs.size() > 1) { + int ret = QMessageBox::question( + getMainWindow(), + QObject::tr("Save dependent files"), + QObject::tr( + "The file contains external dependencies. " + "Do you want to save the dependent files, too?" + ), + QMessageBox::Yes, + QMessageBox::No + ); if (ret != QMessageBox::Yes) { docs = {getDocument()}; @@ -1440,8 +1549,9 @@ bool Document::save() } } - if (!checkCanonicalPath(dmap)) + if (!checkCanonicalPath(dmap)) { return false; + } Gui::WaitCursor wc; // save all documents @@ -1449,13 +1559,18 @@ bool Document::save() // Changed 'mustExecute' status may be triggered by saving external document if (!dmap[doc] && doc->mustExecute()) { App::AutoTransaction trans("Recompute"); - Command::doCommand(Command::Doc,"App.getDocument(\"%s\").recompute()",doc->getName()); + Command::doCommand( + Command::Doc, + "App.getDocument(\"%s\").recompute()", + doc->getName() + ); } - Command::doCommand(Command::Doc,"App.getDocument(\"%s\").save()",doc->getName()); + Command::doCommand(Command::Doc, "App.getDocument(\"%s\").save()", doc->getName()); auto gdoc = Application::Instance->getDocument(doc); - if (gdoc) + if (gdoc) { gdoc->setModified(false); + } } } catch (const Base::FileException& e) { @@ -1463,8 +1578,11 @@ bool Document::save() return askIfSavingFailed(QString::fromUtf8(e.what())); } catch (const Base::Exception& e) { - QMessageBox::critical(getMainWindow(), QObject::tr("Saving document failed"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Saving document failed"), + QString::fromLatin1(e.what()) + ); return false; } return true; @@ -1481,26 +1599,33 @@ bool Document::saveAs() QString exe = qApp->applicationName(); QString name = QString::fromUtf8(getDocument()->FileName.getValue()); - if(name.isEmpty()){ + if (name.isEmpty()) { name = QString::fromUtf8(getDocument()->Label.getValue()); } - QString fn = FileDialog::getSaveFileName(getMainWindow(), QObject::tr("Save %1 Document").arg(exe), + QString fn = FileDialog::getSaveFileName( + getMainWindow(), + QObject::tr("Save %1 Document").arg(exe), name, - QStringLiteral("%1 %2 (*.FCStd)").arg(exe, QObject::tr("Document"))); + QStringLiteral("%1 %2 (*.FCStd)").arg(exe, QObject::tr("Document")) + ); if (!fn.isEmpty()) { QFileInfo fi; fi.setFile(fn); - const char * DocName = App::GetApplication().getDocumentName(getDocument()); + const char* DocName = App::GetApplication().getDocumentName(getDocument()); // save as new file name try { Gui::WaitCursor wc; std::string escapedstr = Base::Tools::escapedUnicodeFromUtf8(fn.toUtf8()); escapedstr = Base::Tools::escapeEncodeFilename(escapedstr); - Command::doCommand(Command::Doc,"App.getDocument(\"%s\").saveAs(u\"%s\")" - , DocName, escapedstr.c_str()); + Command::doCommand( + Command::Doc, + "App.getDocument(\"%s\").saveAs(u\"%s\")", + DocName, + escapedstr.c_str() + ); // App::Document::saveAs() may modify the passed file name fi.setFile(QString::fromUtf8(d->_pcDocument->FileName.getValue())); setModified(false); @@ -1511,8 +1636,11 @@ bool Document::saveAs() return askIfSavingFailed(QString::fromUtf8(e.what())); } catch (const Base::Exception& e) { - QMessageBox::critical(getMainWindow(), QObject::tr("Saving document failed"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Saving document failed"), + QString::fromLatin1(e.what()) + ); } return true; } @@ -1526,54 +1654,66 @@ void Document::saveAll() { std::vector docs; try { - docs = App::Document::getDependentDocuments(App::GetApplication().getDocuments(),true); + docs = App::Document::getDependentDocuments(App::GetApplication().getDocuments(), true); } - catch(Base::Exception &e) { + catch (Base::Exception& e) { e.reportException(); - int ret = QMessageBox::critical(getMainWindow(), QObject::tr("Failed to save document"), - QObject::tr("Documents contains cyclic dependencies. Do you still want to save them?"), - QMessageBox::Yes,QMessageBox::No); - if (ret != QMessageBox::Yes) + int ret = QMessageBox::critical( + getMainWindow(), + QObject::tr("Failed to save document"), + QObject::tr("Documents contains cyclic dependencies. Do you still want to save them?"), + QMessageBox::Yes, + QMessageBox::No + ); + if (ret != QMessageBox::Yes) { return; + } docs = App::GetApplication().getDocuments(); } - std::map dmap; - for(auto doc : docs) { - if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::TempDoc)) + std::map dmap; + for (auto doc : docs) { + if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::TempDoc)) { continue; + } dmap[doc] = doc->mustExecute(); } - if (!checkCanonicalPath(dmap)) + if (!checkCanonicalPath(dmap)) { return; + } - for(auto doc : docs) { - if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::TempDoc)) + for (auto doc : docs) { + if (doc->testStatus(App::Document::PartialDoc) || doc->testStatus(App::Document::TempDoc)) { continue; + } auto gdoc = Application::Instance->getDocument(doc); - if(!gdoc) + if (!gdoc) { continue; - if(!doc->isSaved()) { - if(!gdoc->saveAs()) + } + if (!doc->isSaved()) { + if (!gdoc->saveAs()) { break; + } } Gui::WaitCursor wc; try { // Changed 'mustExecute' status may be triggered by saving external document - if(!dmap[doc] && doc->mustExecute()) { + if (!dmap[doc] && doc->mustExecute()) { App::AutoTransaction trans("Recompute"); - Command::doCommand(Command::Doc,"App.getDocument('%s').recompute()",doc->getName()); + Command::doCommand(Command::Doc, "App.getDocument('%s').recompute()", doc->getName()); } - Command::doCommand(Command::Doc,"App.getDocument('%s').save()",doc->getName()); + Command::doCommand(Command::Doc, "App.getDocument('%s').save()", doc->getName()); gdoc->setModified(false); } catch (const Base::Exception& e) { - QMessageBox::critical(getMainWindow(), - QObject::tr("Failed to save document") + - QStringLiteral(": %1").arg(QString::fromUtf8(doc->getName())), - QString::fromLatin1(e.what())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Failed to save document") + + QStringLiteral(": %1").arg(QString::fromUtf8(doc->getName())), + QString::fromLatin1(e.what()) + ); break; } } @@ -1585,17 +1725,24 @@ bool Document::saveCopy() getMainWindow()->showMessage(QObject::tr("Save a copy of the document under new filename…")); QString exe = qApp->applicationName(); - QString fn = FileDialog::getSaveFileName(getMainWindow(), QObject::tr("Save %1 Document").arg(exe), - QString::fromUtf8(getDocument()->FileName.getValue()), - QObject::tr("%1 document (*.FCStd)").arg(exe)); + QString fn = FileDialog::getSaveFileName( + getMainWindow(), + QObject::tr("Save %1 Document").arg(exe), + QString::fromUtf8(getDocument()->FileName.getValue()), + QObject::tr("%1 document (*.FCStd)").arg(exe) + ); if (!fn.isEmpty()) { - const char * DocName = App::GetApplication().getDocumentName(getDocument()); + const char* DocName = App::GetApplication().getDocumentName(getDocument()); // save as new file name Gui::WaitCursor wc; QString pyfn = Base::Tools::escapeEncodeFilename(fn); - Command::doCommand(Command::Doc,"App.getDocument(\"%s\").saveCopy(\"%s\")" - , DocName, (const char*)pyfn.toUtf8()); + Command::doCommand( + Command::Doc, + "App.getDocument(\"%s\").saveCopy(\"%s\")", + DocName, + (const char*)pyfn.toUtf8() + ); return true; } @@ -1605,32 +1752,35 @@ bool Document::saveCopy() } } -unsigned int Document::getMemSize () const +unsigned int Document::getMemSize() const { unsigned int size = 0; // size of the view providers in the document - std::map::const_iterator it; - for (it = d->_ViewProviderMap.begin(); it != d->_ViewProviderMap.end(); ++it) + std::map::const_iterator it; + for (it = d->_ViewProviderMap.begin(); it != d->_ViewProviderMap.end(); ++it) { size += it->second->getMemSize(); + } return size; } /** * Adds a separate XML file to the projects file that contains information about the view providers. */ -void Document::Save (Base::Writer &writer) const +void Document::Save(Base::Writer& writer) const { // It's only possible to add extra information if force of XML is disabled if (!writer.isForceXML()) { writer.addFile("GuiDocument.xml", this); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Document" + ); if (hGrp->GetBool("SaveThumbnail", true)) { int size = hGrp->GetInt("ThumbnailSize", 256); size = Base::clamp(size, 64, 512); std::list mdi = getMDIViews(); - for (const auto & it : mdi) { + for (const auto& it : mdi) { if (it->isDerivedFrom()) { View3DInventorViewer* view = static_cast(it)->getViewer(); d->thumb.setFileName(d->_pcDocument->FileName.getValue()); @@ -1647,26 +1797,27 @@ void Document::Save (Base::Writer &writer) const /** * Loads a separate XML file from the projects file with information about the view providers. */ -void Document::Restore(Base::XMLReader &reader) +void Document::Restore(Base::XMLReader& reader) { - reader.addFile("GuiDocument.xml",this); + reader.addFile("GuiDocument.xml", this); // hide all elements to avoid to update the 3d view when loading data files // RestoreDocFile then restores the visibility status again - std::map::iterator it; + std::map::iterator it; for (it = d->_ViewProviderMap.begin(); it != d->_ViewProviderMap.end(); ++it) { it->second->startRestoring(); - it->second->setStatus(Gui::isRestoring,true); + it->second->setStatus(Gui::isRestoring, true); } } /** * Restores the properties of the view providers. */ -void Document::RestoreDocFile(Base::Reader &reader) +void Document::RestoreDocFile(Base::Reader& reader) { // We must create an XML parser to read from the input stream - std::shared_ptr localreader = std::make_shared("GuiDocument.xml", reader); + std::shared_ptr localreader + = std::make_shared("GuiDocument.xml", reader); localreader->FileVersion = reader.getFileVersion(); localreader->readElement("Document"); @@ -1674,12 +1825,13 @@ void Document::RestoreDocFile(Base::Reader &reader) localreader->DocumentSchema = scheme; bool hasExpansion = localreader->hasAttribute("HasExpansion"); - if(hasExpansion) { + if (hasExpansion) { auto tree = TreeWidget::instance(); - if(tree) { + if (tree) { auto docItem = tree->getDocumentItem(this); - if(docItem) + if (docItem) { docItem->Restore(*localreader); + } } } @@ -1691,14 +1843,14 @@ void Document::RestoreDocFile(Base::Reader &reader) // read the viewproviders itself localreader->readElement("ViewProviderData"); int Cnt = localreader->getAttribute("Count"); - for (int i=0; ireadElement("ViewProvider"); std::string name = localreader->getAttribute("name"); bool expanded = false; if (!hasExpansion && localreader->hasAttribute("expanded")) { const char* attr = localreader->getAttribute("expanded"); - if (strcmp(attr,"1") == 0) { + if (strcmp(attr, "1") == 0) { expanded = true; } } @@ -1729,14 +1881,15 @@ void Document::RestoreDocFile(Base::Reader &reader) localreader->readElement("Camera"); const char* ppReturn = localreader->getAttribute("settings"); cameraSettings.clear(); - if(!Base::Tools::isNullOrEmpty(ppReturn)) { + if (!Base::Tools::isNullOrEmpty(ppReturn)) { saveCameraSettings(ppReturn); try { - const char** pReturnIgnore=nullptr; + const char** pReturnIgnore = nullptr; std::list mdi = getMDIViews(); - for (const auto & it : mdi) { - if (it->onHasMsg("SetCamera")) + for (const auto& it : mdi) { + if (it->onHasMsg("SetCamera")) { it->onMsg(cameraSettings.c_str(), pReturnIgnore); + } } } catch (const Base::Exception& e) { @@ -1753,26 +1906,30 @@ void Document::RestoreDocFile(Base::Reader &reader) void Document::slotStartRestoreDocument(const App::Document& doc) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; + } // disable this signal while loading a document d->connectActObjectBlocker.block(); } -void Document::slotFinishRestoreObject(const App::DocumentObject &obj) { +void Document::slotFinishRestoreObject(const App::DocumentObject& obj) +{ auto vpd = freecad_cast(getViewProvider(&obj)); - if(vpd) { - vpd->setStatus(Gui::isRestoring,false); + if (vpd) { + vpd->setStatus(Gui::isRestoring, false); vpd->finishRestoring(); - if(!vpd->canAddToSceneGraph()) + if (!vpd->canAddToSceneGraph()) { toggleInSceneGraph(vpd); + } } } void Document::slotFinishRestoreDocument(const App::Document& doc) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; + } d->connectActObjectBlocker.unblock(); App::DocumentObject* act = doc.getActiveObject(); if (act) { @@ -1788,8 +1945,9 @@ void Document::slotFinishRestoreDocument(const App::Document& doc) void Document::slotShowHidden(const App::Document& doc) { - if (d->_pcDocument != &doc) + if (d->_pcDocument != &doc) { return; + } Application::Instance->signalShowHidden(*this); } @@ -1797,7 +1955,7 @@ void Document::slotShowHidden(const App::Document& doc) /** * Saves the properties of the view providers. */ -void Document::SaveDocFile (Base::Writer &writer) const +void Document::SaveDocFile(Base::Writer& writer) const { writer.Stream() << "" << std::endl << "" << std::endl; str << "getOrientation() == LANDSCAPE) { SbSwap(size[0], size[1]); } if (getUseMM()) { - str << " width=\"" << size[0] << "mm\" height=\"" << size[1] << "mm\""<< std::endl; + str << " width=\"" << size[0] << "mm\" height=\"" << size[1] << "mm\"" << std::endl; str << " viewBox=\"0 0 " << size[0] << " " << size[1] << "\">" << std::endl; - } else { //original code used px + } + else { // original code used px str << " width=\"" << size[0] << "\" height=\"" << size[1] << "\">" << std::endl; } str << "" << std::endl; @@ -423,8 +438,7 @@ void SoFCVectorizeSVGAction::printFooter() const } void SoFCVectorizeSVGAction::printViewport() const -{ -} +{} void SoFCVectorizeSVGAction::printBackground() const { @@ -434,7 +448,7 @@ void SoFCVectorizeSVGAction::printBackground() const SbVec2f mul = getRotatedViewportSize(); SbVec2f add = getRotatedViewportStartpos(); - float x[2],y[2]; + float x[2], y[2]; x[0] = add[0]; x[1] = mul[0] - add[0]; y[0] = add[1]; @@ -447,40 +461,38 @@ void SoFCVectorizeSVGAction::printBackground() const std::ostream& str = this->getSVGOutput()->getFileStream(); str << "" << std::endl; str << "> 8) + str << " d=\"M " << x[0] << "," << y[0] << " L " << x[1] << "," << y[0] << " L " << x[1] + << "," << y[1] << " L " << x[0] << "," << y[1] << " L " << x[0] << "," << y[0] << " z \"" + << std::endl; + str << " style=\"fill:#" << std::hex << std::setw(6) << std::setfill('0') << (cc >> 8) << ";fill-opacity:1;fill-rule:evenodd;stroke:none;" - "stroke-width:" << getLineWidth() << ";stroke-linecap:butt;stroke-linejoin:" + "stroke-width:" + << getLineWidth() + << ";stroke-linecap:butt;stroke-linejoin:" "miter;stroke-opacity:1\" />\n"; str << "" << std::endl; } -void SoFCVectorizeSVGAction::printItem(const SoVectorizeItem * item) const +void SoFCVectorizeSVGAction::printItem(const SoVectorizeItem* item) const { switch (item->type) { - case SoVectorizeItem::TRIANGLE: - this->p->printTriangle(static_cast(item)); - break; - case SoVectorizeItem::LINE: - this->p->printLine(static_cast(item)); - break; - case SoVectorizeItem::POINT: - this->p->printPoint(static_cast(item)); - break; - case SoVectorizeItem::TEXT: - this->p->printText(static_cast(item)); - break; - case SoVectorizeItem::IMAGE: - this->p->printImage(static_cast(item)); - break; - default: - assert(0 && "unsupported item"); - break; + case SoVectorizeItem::TRIANGLE: + this->p->printTriangle(static_cast(item)); + break; + case SoVectorizeItem::LINE: + this->p->printLine(static_cast(item)); + break; + case SoVectorizeItem::POINT: + this->p->printPoint(static_cast(item)); + break; + case SoVectorizeItem::TEXT: + this->p->printText(static_cast(item)); + break; + case SoVectorizeItem::IMAGE: + this->p->printImage(static_cast(item)); + break; + default: + assert(0 && "unsupported item"); + break; } } diff --git a/src/Gui/SoFCVectorizeSVGAction.h b/src/Gui/SoFCVectorizeSVGAction.h index fdc3e6873d..98768d9a66 100644 --- a/src/Gui/SoFCVectorizeSVGAction.h +++ b/src/Gui/SoFCVectorizeSVGAction.h @@ -30,15 +30,17 @@ #include -namespace Gui { +namespace Gui +{ -class GuiExport SoSVGVectorOutput : public SoVectorOutput { +class GuiExport SoSVGVectorOutput: public SoVectorOutput +{ public: SoSVGVectorOutput(); ~SoSVGVectorOutput() override; - SbBool openFile (const char *filename) override; - void closeFile () override; + SbBool openFile(const char* filename) override; + void closeFile() override; std::fstream& getFileStream(); private: @@ -49,7 +51,8 @@ private: * @author Werner Mayer */ class SoFCVectorizeSVGActionP; -class GuiExport SoFCVectorizeSVGAction : public SoVectorizeAction { +class GuiExport SoFCVectorizeSVGAction: public SoVectorizeAction +{ using inherited = SoReplacedElement; SO_ACTION_HEADER(SoFCVectorizeSVGAction); @@ -59,30 +62,48 @@ public: ~SoFCVectorizeSVGAction() override; static void initClass(); - SoSVGVectorOutput * getSVGOutput() const; + SoSVGVectorOutput* getSVGOutput() const; - virtual void setBackgroundState(bool b) { m_backgroundState = b; } - virtual bool getBackgroundState() const { return m_backgroundState; } - virtual void setLineWidth(double w) { m_lineWidth = w; } - virtual double getLineWidth() const { return m_lineWidth; } - virtual void setUseMM(bool b) { m_usemm = b; } - virtual bool getUseMM() const { return m_usemm; } + virtual void setBackgroundState(bool b) + { + m_backgroundState = b; + } + virtual bool getBackgroundState() const + { + return m_backgroundState; + } + virtual void setLineWidth(double w) + { + m_lineWidth = w; + } + virtual double getLineWidth() const + { + return m_lineWidth; + } + virtual void setUseMM(bool b) + { + m_usemm = b; + } + virtual bool getUseMM() const + { + return m_usemm; + } protected: void printHeader() const override; void printFooter() const override; void printBackground() const override; - void printItem(const SoVectorizeItem * item) const override; + void printItem(const SoVectorizeItem* item) const override; void printViewport() const override; private: SoFCVectorizeSVGActionP* p; friend class SoFCVectorizeSVGActionP; - bool m_backgroundState{true}; - double m_lineWidth{1.0}; - bool m_usemm{false}; + bool m_backgroundState {true}; + double m_lineWidth {1.0}; + bool m_usemm {false}; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_SOFCVECTORIZESVGACTION_H +#endif // GUI_SOFCVECTORIZESVGACTION_H diff --git a/src/Gui/SoFCVectorizeU3DAction.cpp b/src/Gui/SoFCVectorizeU3DAction.cpp index d294b2ab2d..e37955af1c 100644 --- a/src/Gui/SoFCVectorizeU3DAction.cpp +++ b/src/Gui/SoFCVectorizeU3DAction.cpp @@ -21,11 +21,10 @@ ***************************************************************************/ - -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -36,14 +35,17 @@ using namespace Gui; -class SoVectorizeItem { +class SoVectorizeItem +{ public: - SoVectorizeItem() { + SoVectorizeItem() + { this->type = UNDEFINED; this->depth = 0.0f; } // quick and easy type system - enum Type { + enum Type + { UNDEFINED, LINE, TRIANGLE, @@ -52,34 +54,40 @@ public: IMAGE }; int type; - float depth; // for depth sorting + float depth; // for depth sorting }; -class SoVectorizePoint : public SoVectorizeItem { +class SoVectorizePoint: public SoVectorizeItem +{ public: - SoVectorizePoint() { + SoVectorizePoint() + { this->type = POINT; this->vidx = 0; this->size = 1.0f; this->col = 0; } - int vidx; // index to BSPtree coordinate - float size; // Coin size (pixels) + int vidx; // index to BSPtree coordinate + float size; // Coin size (pixels) uint32_t col; }; -class SoVectorizeTriangle : public SoVectorizeItem { +class SoVectorizeTriangle: public SoVectorizeItem +{ public: - SoVectorizeTriangle() { + SoVectorizeTriangle() + { this->type = TRIANGLE; } - int vidx[3]; // indices to BSPtree coordinates + int vidx[3]; // indices to BSPtree coordinates uint32_t col[3]; }; -class SoVectorizeLine : public SoVectorizeItem { +class SoVectorizeLine: public SoVectorizeItem +{ public: - SoVectorizeLine() { + SoVectorizeLine() + { this->type = LINE; vidx[0] = 0; vidx[1] = 0; @@ -88,48 +96,54 @@ public: this->pattern = 0xffff; this->width = 1.0f; } - int vidx[2]; // indices to BSPtree coordinates + int vidx[2]; // indices to BSPtree coordinates uint32_t col[2]; uint16_t pattern; // Coin line pattern float width; // Coin line width (pixels) }; -class SoVectorizeText : public SoVectorizeItem { +class SoVectorizeText: public SoVectorizeItem +{ public: - SoVectorizeText() { + SoVectorizeText() + { this->type = TEXT; this->fontsize = 10; this->col = 0; this->justification = LEFT; } - enum Justification { + enum Justification + { LEFT, RIGHT, CENTER }; SbName fontname; - float fontsize; // size in normalized coordinates + float fontsize; // size in normalized coordinates SbString string; - SbVec2f pos; // pos in normalized coordinates + SbVec2f pos; // pos in normalized coordinates uint32_t col; Justification justification; }; -class SoVectorizeImage : public SoVectorizeItem { +class SoVectorizeImage: public SoVectorizeItem +{ public: - SoVectorizeImage() { + SoVectorizeImage() + { this->type = IMAGE; this->image.data = nullptr; this->image.nc = 0; } - SbVec2f pos; // pos in normalized coordinates - SbVec2f size; // size in normalized coordinates + SbVec2f pos; // pos in normalized coordinates + SbVec2f size; // size in normalized coordinates - struct Image { - const unsigned char * data; + struct Image + { + const unsigned char* data; SbVec2s size; int nc; } image; @@ -144,7 +158,7 @@ SoU3DVectorOutput::~SoU3DVectorOutput() closeFile(); } -SbBool SoU3DVectorOutput::openFile (const char *filename) +SbBool SoU3DVectorOutput::openFile(const char* filename) { Base::FileInfo fi(filename); #ifdef _MSC_VER @@ -156,10 +170,11 @@ SbBool SoU3DVectorOutput::openFile (const char *filename) return this->file.is_open(); } -void SoU3DVectorOutput::closeFile () +void SoU3DVectorOutput::closeFile() { - if (this->file.is_open()) + if (this->file.is_open()) { this->file.close(); + } } std::fstream& SoU3DVectorOutput::getFileStream() @@ -169,46 +184,48 @@ std::fstream& SoU3DVectorOutput::getFileStream() // ---------------------------------------------------------------- -namespace Gui { +namespace Gui +{ class SoFCVectorizeU3DActionP { public: - explicit SoFCVectorizeU3DActionP(SoFCVectorizeU3DAction * p) { + explicit SoFCVectorizeU3DActionP(SoFCVectorizeU3DAction* p) + { this->publ = p; } - void printCircle(const SbVec3f & v, const SbColor & c, const float radius) const; - void printSquare(const SbVec3f & v, const SbColor & c, const float size) const; - void printTriangle(const SbVec3f * v, const SbColor * c) const; - void printTriangle(const SoVectorizeTriangle * item) const; - void printLine(const SoVectorizeLine * item) const; - void printPoint(const SoVectorizePoint * item) const; - void printText(const SoVectorizeText * item) const; - void printImage(const SoVectorizeImage * item) const; + void printCircle(const SbVec3f& v, const SbColor& c, const float radius) const; + void printSquare(const SbVec3f& v, const SbColor& c, const float size) const; + void printTriangle(const SbVec3f* v, const SbColor* c) const; + void printTriangle(const SoVectorizeTriangle* item) const; + void printLine(const SoVectorizeLine* item) const; + void printPoint(const SoVectorizePoint* item) const; + void printText(const SoVectorizeText* item) const; + void printImage(const SoVectorizeImage* item) const; private: - SoFCVectorizeU3DAction * publ; + SoFCVectorizeU3DAction* publ; }; -} +} // namespace Gui -void SoFCVectorizeU3DActionP::printText(const SoVectorizeText * item) const +void SoFCVectorizeU3DActionP::printText(const SoVectorizeText* item) const { - //SbVec2f mul = publ->getRotatedViewportSize(); - //SbVec2f add = publ->getRotatedViewportStartpos(); - //float posx = item->pos[0]*mul[0]+add[0]; - //float posy = item->pos[1]*mul[1]+add[1]; + // SbVec2f mul = publ->getRotatedViewportSize(); + // SbVec2f add = publ->getRotatedViewportStartpos(); + // float posx = item->pos[0]*mul[0]+add[0]; + // float posy = item->pos[1]*mul[1]+add[1]; - //std::ostream& str = publ->getU3DOutput()->getFileStream(); - // todo + // std::ostream& str = publ->getU3DOutput()->getFileStream(); + // todo Q_UNUSED(item); } -void SoFCVectorizeU3DActionP::printTriangle(const SoVectorizeTriangle * item) const +void SoFCVectorizeU3DActionP::printTriangle(const SoVectorizeTriangle* item) const { SbVec2f mul = publ->getRotatedViewportSize(); SbVec2f add = publ->getRotatedViewportStartpos(); - const SbBSPTree & bsp = publ->getBSPTree(); + const SbBSPTree& bsp = publ->getBSPTree(); SbVec3f v[3]; SbColor c[3]; @@ -217,24 +234,25 @@ void SoFCVectorizeU3DActionP::printTriangle(const SoVectorizeTriangle * item) co for (int i = 0; i < 3; i++) { v[i] = bsp.getPoint(item->vidx[i]); v[i][0] = (v[i][0] * mul[0]) + add[0]; - v[i][1] = ((1.0f-v[i][1]) * mul[1]) + add[1]; + v[i][1] = ((1.0f - v[i][1]) * mul[1]) + add[1]; c[i].setPackedValue(item->col[i], t[i]); } this->printTriangle((SbVec3f*)v, (SbColor*)c); } -void SoFCVectorizeU3DActionP::printTriangle(const SbVec3f * v, const SbColor * c) const +void SoFCVectorizeU3DActionP::printTriangle(const SbVec3f* v, const SbColor* c) const { - if (v[0] == v[1] || v[1] == v[2] || v[0] == v[2]) + if (v[0] == v[1] || v[1] == v[2] || v[0] == v[2]) { return; - //uint32_t cc = c->getPackedValue(); + } + // uint32_t cc = c->getPackedValue(); - //std::ostream& str = publ->getU3DOutput()->getFileStream(); - // todo + // std::ostream& str = publ->getU3DOutput()->getFileStream(); + // todo Q_UNUSED(c); } -void SoFCVectorizeU3DActionP::printCircle(const SbVec3f & v, const SbColor & c, const float radius) const +void SoFCVectorizeU3DActionP::printCircle(const SbVec3f& v, const SbColor& c, const float radius) const { // todo Q_UNUSED(v); @@ -242,7 +260,7 @@ void SoFCVectorizeU3DActionP::printCircle(const SbVec3f & v, const SbColor & c, Q_UNUSED(radius); } -void SoFCVectorizeU3DActionP::printSquare(const SbVec3f & v, const SbColor & c, const float size) const +void SoFCVectorizeU3DActionP::printSquare(const SbVec3f& v, const SbColor& c, const float size) const { // todo Q_UNUSED(v); @@ -250,12 +268,12 @@ void SoFCVectorizeU3DActionP::printSquare(const SbVec3f & v, const SbColor & c, Q_UNUSED(size); } -void SoFCVectorizeU3DActionP::printLine(const SoVectorizeLine * item) const +void SoFCVectorizeU3DActionP::printLine(const SoVectorizeLine* item) const { SbVec2f mul = publ->getRotatedViewportSize(); SbVec2f add = publ->getRotatedViewportStartpos(); - const SbBSPTree & bsp = publ->getBSPTree(); + const SbBSPTree& bsp = publ->getBSPTree(); SbVec3f v[2]; SbColor c[2]; @@ -264,23 +282,23 @@ void SoFCVectorizeU3DActionP::printLine(const SoVectorizeLine * item) const for (int i = 0; i < 2; i++) { v[i] = bsp.getPoint(item->vidx[i]); v[i][0] = (v[i][0] * mul[0]) + add[0]; - v[i][1] = ((1.0f-v[i][1]) * mul[1]) + add[1]; + v[i][1] = ((1.0f - v[i][1]) * mul[1]) + add[1]; c[i].setPackedValue(item->col[i], t[i]); } - //uint32_t cc = c->getPackedValue(); + // uint32_t cc = c->getPackedValue(); - //std::ostream& str = publ->getU3DOutput()->getFileStream(); - // todo + // std::ostream& str = publ->getU3DOutput()->getFileStream(); + // todo Q_UNUSED(item); } -void SoFCVectorizeU3DActionP::printPoint(const SoVectorizePoint * item) const +void SoFCVectorizeU3DActionP::printPoint(const SoVectorizePoint* item) const { // todo Q_UNUSED(item); } -void SoFCVectorizeU3DActionP::printImage(const SoVectorizeImage * item) const +void SoFCVectorizeU3DActionP::printImage(const SoVectorizeImage* item) const { // todo Q_UNUSED(item); @@ -293,7 +311,7 @@ SO_ACTION_SOURCE(SoFCVectorizeU3DAction) void SoFCVectorizeU3DAction::initClass() { SO_ACTION_INIT_CLASS(SoFCVectorizeU3DAction, SoVectorizeAction); - //SO_ACTION_ADD_METHOD(SoNode, SoFCVectorizeU3DAction::actionMethod); + // SO_ACTION_ADD_METHOD(SoNode, SoFCVectorizeU3DAction::actionMethod); } SoFCVectorizeU3DAction::SoFCVectorizeU3DAction() @@ -308,25 +326,23 @@ SoFCVectorizeU3DAction::~SoFCVectorizeU3DAction() delete this->p; } -SoU3DVectorOutput * -SoFCVectorizeU3DAction::getU3DOutput() const +SoU3DVectorOutput* SoFCVectorizeU3DAction::getU3DOutput() const { return static_cast(SoVectorizeAction::getOutput()); } -void -SoFCVectorizeU3DAction::actionMethod(SoAction * a, SoNode * n) +void SoFCVectorizeU3DAction::actionMethod(SoAction* a, SoNode* n) { Q_UNUSED(a); Q_UNUSED(n); } -void SoFCVectorizeU3DAction::beginTraversal(SoNode * node) +void SoFCVectorizeU3DAction::beginTraversal(SoNode* node) { inherited::beginTraversal(node); } -void SoFCVectorizeU3DAction::endTraversal(SoNode * node) +void SoFCVectorizeU3DAction::endTraversal(SoNode* node) { inherited::endTraversal(node); } @@ -334,8 +350,7 @@ void SoFCVectorizeU3DAction::endTraversal(SoNode * node) void SoFCVectorizeU3DAction::printHeader() const { std::ostream& str = this->getU3DOutput()->getFileStream(); - str << "FILE_FORMAT \"IDTF\"" << std::endl - << "FORMAT_VERSION 100" << std::endl; + str << "FILE_FORMAT \"IDTF\"" << std::endl << "FORMAT_VERSION 100" << std::endl; str << Base::tabs(0) << "NODE \"MODEL\" {" << std::endl; str << Base::tabs(1) << "NODE_NAME \"FreeCAD\"" << std::endl; @@ -356,52 +371,50 @@ void SoFCVectorizeU3DAction::printHeader() const } void SoFCVectorizeU3DAction::printFooter() const -{ -} +{} void SoFCVectorizeU3DAction::printViewport() const -{ -} +{} void SoFCVectorizeU3DAction::printBackground() const { - //SbVec2f mul = getRotatedViewportSize(); - //SbVec2f add = getRotatedViewportStartpos(); + // SbVec2f mul = getRotatedViewportSize(); + // SbVec2f add = getRotatedViewportStartpos(); - //float x[2],y[2]; - //x[0] = add[0]; - //x[1] = mul[0] - add[0]; - //y[0] = add[1]; - //y[1] = mul[1] - add[1]; + // float x[2],y[2]; + // x[0] = add[0]; + // x[1] = mul[0] - add[0]; + // y[0] = add[1]; + // y[1] = mul[1] - add[1]; - //SbColor bg; + // SbColor bg; //(void)this->getBackgroundColor(bg); - //uint32_t cc = bg.getPackedValue(); + // uint32_t cc = bg.getPackedValue(); - //std::ostream& str = this->getU3DOutput()->getFileStream(); - // todo + // std::ostream& str = this->getU3DOutput()->getFileStream(); + // todo } -void SoFCVectorizeU3DAction::printItem(const SoVectorizeItem * item) const +void SoFCVectorizeU3DAction::printItem(const SoVectorizeItem* item) const { switch (item->type) { - case SoVectorizeItem::TRIANGLE: - this->p->printTriangle(static_cast(item)); - break; - case SoVectorizeItem::LINE: - this->p->printLine(static_cast(item)); - break; - case SoVectorizeItem::POINT: - this->p->printPoint(static_cast(item)); - break; - case SoVectorizeItem::TEXT: - this->p->printText(static_cast(item)); - break; - case SoVectorizeItem::IMAGE: - this->p->printImage(static_cast(item)); - break; - default: - assert(0 && "unsupported item"); - break; + case SoVectorizeItem::TRIANGLE: + this->p->printTriangle(static_cast(item)); + break; + case SoVectorizeItem::LINE: + this->p->printLine(static_cast(item)); + break; + case SoVectorizeItem::POINT: + this->p->printPoint(static_cast(item)); + break; + case SoVectorizeItem::TEXT: + this->p->printText(static_cast(item)); + break; + case SoVectorizeItem::IMAGE: + this->p->printImage(static_cast(item)); + break; + default: + assert(0 && "unsupported item"); + break; } } diff --git a/src/Gui/SoFCVectorizeU3DAction.h b/src/Gui/SoFCVectorizeU3DAction.h index de7e40eb9a..2a3f59b55e 100644 --- a/src/Gui/SoFCVectorizeU3DAction.h +++ b/src/Gui/SoFCVectorizeU3DAction.h @@ -30,15 +30,17 @@ #include -namespace Gui { +namespace Gui +{ -class GuiExport SoU3DVectorOutput : public SoVectorOutput { +class GuiExport SoU3DVectorOutput: public SoVectorOutput +{ public: SoU3DVectorOutput(); ~SoU3DVectorOutput() override; - SbBool openFile (const char *filename) override; - void closeFile () override; + SbBool openFile(const char* filename) override; + void closeFile() override; std::fstream& getFileStream(); private: @@ -49,7 +51,8 @@ private: * @author Werner Mayer */ class SoFCVectorizeU3DActionP; -class GuiExport SoFCVectorizeU3DAction : public SoVectorizeAction { +class GuiExport SoFCVectorizeU3DAction: public SoVectorizeAction +{ using inherited = SoVectorizeAction; SO_ACTION_HEADER(SoFCVectorizeU3DAction); @@ -59,25 +62,25 @@ public: ~SoFCVectorizeU3DAction() override; static void initClass(); - SoU3DVectorOutput * getU3DOutput() const; + SoU3DVectorOutput* getU3DOutput() const; protected: - void beginTraversal(SoNode * node) override; - void endTraversal(SoNode *node) override; + void beginTraversal(SoNode* node) override; + void endTraversal(SoNode* node) override; void printHeader() const override; void printFooter() const override; void printBackground() const override; - void printItem(const SoVectorizeItem * item) const override; + void printItem(const SoVectorizeItem* item) const override; void printViewport() const override; private: - static void actionMethod(SoAction *, SoNode *); + static void actionMethod(SoAction*, SoNode*); private: SoFCVectorizeU3DActionP* p; friend class SoFCVectorizeU3DActionP; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_SOFCVECTORIZEU3DACTION_H +#endif // GUI_SOFCVECTORIZEU3DACTION_H diff --git a/src/Gui/SoQtOffscreenRendererPy.cpp b/src/Gui/SoQtOffscreenRendererPy.cpp index a1b101a9f0..adaff6d9b1 100644 --- a/src/Gui/SoQtOffscreenRendererPy.cpp +++ b/src/Gui/SoQtOffscreenRendererPy.cpp @@ -28,8 +28,13 @@ using namespace Gui; -SoQtOffscreenRendererPy::SoQtOffscreenRendererPy(Py::PythonClassInstance* self, Py::Tuple& args, Py::Dict& kwds) - : Py::PythonClass(self, args, kwds), renderer(SbViewportRegion()) +SoQtOffscreenRendererPy::SoQtOffscreenRendererPy( + Py::PythonClassInstance* self, + Py::Tuple& args, + Py::Dict& kwds +) + : Py::PythonClass(self, args, kwds) + , renderer(SbViewportRegion()) { this->setViewportRegion(args); } @@ -184,15 +189,31 @@ void SoQtOffscreenRendererPy::init_type() PYCXX_ADD_VARARGS_METHOD(setViewportRegion, setViewportRegion, "setViewportRegion(int, int)"); PYCXX_ADD_NOARGS_METHOD(getViewportRegion, getViewportRegion, "getViewportRegion() -> tuple"); - PYCXX_ADD_VARARGS_METHOD(setBackgroundColor, setBackgroundColor, "setBackgroundColor(float, float, float, [float])"); + PYCXX_ADD_VARARGS_METHOD( + setBackgroundColor, + setBackgroundColor, + "setBackgroundColor(float, float, float, [float])" + ); PYCXX_ADD_NOARGS_METHOD(getBackgroundColor, getBackgroundColor, "getBackgroundColor() -> tuple"); PYCXX_ADD_VARARGS_METHOD(setNumPasses, setNumPasses, "setNumPasses(int)"); PYCXX_ADD_NOARGS_METHOD(getNumPasses, getNumPasses, "getNumPasses() -> int"); - PYCXX_ADD_VARARGS_METHOD(setInternalTextureFormat, setInternalTextureFormat, "setInternalTextureFormat(int)"); - PYCXX_ADD_NOARGS_METHOD(getInternalTextureFormat, getInternalTextureFormat, "getInternalTextureFormat() -> int"); + PYCXX_ADD_VARARGS_METHOD( + setInternalTextureFormat, + setInternalTextureFormat, + "setInternalTextureFormat(int)" + ); + PYCXX_ADD_NOARGS_METHOD( + getInternalTextureFormat, + getInternalTextureFormat, + "getInternalTextureFormat() -> int" + ); PYCXX_ADD_VARARGS_METHOD(render, render, "render(node)"); PYCXX_ADD_VARARGS_METHOD(writeToImage, writeToImage, "writeToImage(string)"); - PYCXX_ADD_NOARGS_METHOD(getWriteImageFiletypeInfo, getWriteImageFiletypeInfo, "getWriteImageFiletypeInfo() -> tuple"); + PYCXX_ADD_NOARGS_METHOD( + getWriteImageFiletypeInfo, + getWriteImageFiletypeInfo, + "getWriteImageFiletypeInfo() -> tuple" + ); behaviors().readyType(); } diff --git a/src/Gui/SoQtOffscreenRendererPy.h b/src/Gui/SoQtOffscreenRendererPy.h index 90384835a0..878bddf83d 100644 --- a/src/Gui/SoQtOffscreenRendererPy.h +++ b/src/Gui/SoQtOffscreenRendererPy.h @@ -28,9 +28,10 @@ #include "SoFCOffscreenRenderer.h" -namespace Gui { +namespace Gui +{ -class SoQtOffscreenRendererPy : public Py::PythonClass +class SoQtOffscreenRendererPy: public Py::PythonClass { public: static void init_type(); @@ -61,6 +62,6 @@ private: SoQtOffscreenRenderer renderer; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_SOQTOFFSCREENRENDERERPY_H +#endif // GUI_SOQTOFFSCREENRENDERERPY_H diff --git a/src/Gui/SoTextLabel.cpp b/src/Gui/SoTextLabel.cpp index fbd27669ac..599c919449 100644 --- a/src/Gui/SoTextLabel.cpp +++ b/src/Gui/SoTextLabel.cpp @@ -22,21 +22,21 @@ #include -# ifdef FC_OS_WIN32 +#ifdef FC_OS_WIN32 # include -# endif -# ifdef FC_OS_MACOSX +#endif +#ifdef FC_OS_MACOSX # include -# else +#else # include -# endif -# include -# include -# include -# include -# include -# include -# include +#endif +#include +#include +#include +#include +#include +#include +#include #include #include @@ -68,7 +68,7 @@ void SoTextLabel::initClass() SoTextLabel::SoTextLabel() { SO_NODE_CONSTRUCTOR(SoTextLabel); - SO_NODE_ADD_FIELD(backgroundColor, (SbVec3f(1.0f,1.0f,1.0f))); + SO_NODE_ADD_FIELD(backgroundColor, (SbVec3f(1.0f, 1.0f, 1.0f))); SO_NODE_ADD_FIELD(background, (true)); SO_NODE_ADD_FIELD(frameSize, (10.0f)); } @@ -76,10 +76,11 @@ SoTextLabel::SoTextLabel() /** * Renders the label. */ -void SoTextLabel::GLRender(SoGLRenderAction *action) +void SoTextLabel::GLRender(SoGLRenderAction* action) { - if (!this->shouldGLRender(action)) + if (!this->shouldGLRender(action)) { return; + } // only draw text without background if (!this->background.getValue()) { @@ -87,7 +88,7 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) return; } - SoState * state = action->getState(); + SoState* state = action->getState(); state->push(); SoLazyElement::setLightModel(state, SoLazyElement::BASE_COLOR); @@ -99,10 +100,10 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) if (!SoCullElement::cullTest(state, box, true)) { SoMaterialBundle mb(action); mb.sendFirst(); - const SbMatrix & mat = SoModelMatrixElement::get(state); - const SbMatrix & projmatrix = (mat * SoViewingMatrixElement::get(state) * - SoProjectionMatrixElement::get(state)); - const SbViewportRegion & vp = SoViewportRegionElement::get(state); + const SbMatrix& mat = SoModelMatrixElement::get(state); + const SbMatrix& projmatrix + = (mat * SoViewingMatrixElement::get(state) * SoProjectionMatrixElement::get(state)); + const SbViewportRegion& vp = SoViewportRegionElement::get(state); SbVec2s vpsize = vp.getViewportSizePixels(); // font stuff @@ -123,45 +124,45 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) // returns the sizes in form of the bounding box. These values can be // reverse-engineered to get width and height. state->push(); - SoModelMatrixElement::set(state,this,SbMatrix::identity()); - SoViewingMatrixElement::set(state,this,SbMatrix::identity()); - SoProjectionMatrixElement::set(state,this,SbMatrix::identity()); + SoModelMatrixElement::set(state, this, SbMatrix::identity()); + SoViewingMatrixElement::set(state, this, SbMatrix::identity()); + SoProjectionMatrixElement::set(state, this, SbMatrix::identity()); SbViewVolume vv; - vv.ortho(-1,1,-1,1,-1,1); - SoViewVolumeElement::set(state,this,vv); + vv.ortho(-1, 1, -1, 1, -1, 1); + SoViewVolumeElement::set(state, this, vv); SbBox3f box; SbVec3f center; this->computeBBox(action, box, center); state->pop(); - float xmin,ymin,zmin,xmax,ymax,zmax; - box.getBounds(xmin,ymin,zmin,xmax,ymax,zmax); - SbVec3f v0(xmin,ymax,zmax); - SbVec3f v1(xmax,ymax,zmax); - SbVec3f v2(xmax,ymin,zmax); - SbVec3f v3(xmin,ymin,zmax); - vv.projectToScreen(v0,v0); - vv.projectToScreen(v1,v1); - vv.projectToScreen(v2,v2); - vv.projectToScreen(v3,v3); + float xmin, ymin, zmin, xmax, ymax, zmax; + box.getBounds(xmin, ymin, zmin, xmax, ymax, zmax); + SbVec3f v0(xmin, ymax, zmax); + SbVec3f v1(xmax, ymax, zmax); + SbVec3f v2(xmax, ymin, zmax); + SbVec3f v3(xmin, ymin, zmax); + vv.projectToScreen(v0, v0); + vv.projectToScreen(v1, v1); + vv.projectToScreen(v2, v2); + vv.projectToScreen(v3, v3); - float width,height; - width = (v1[0]-v0[0])*vpsize[0]; - height = (v1[1]-v3[1])*vpsize[1]; + float width, height; + width = (v1[0] - v0[0]) * vpsize[0]; + height = (v1[1] - v3[1]) * vpsize[1]; switch (this->justification.getValue()) { - case SoText2::RIGHT: - nilpoint[0] -= width; - break; - case SoText2::CENTER: - nilpoint[0] -= 0.5f*width; - break; - default: - break; + case SoText2::RIGHT: + nilpoint[0] -= width; + break; + case SoText2::CENTER: + nilpoint[0] -= 0.5f * width; + break; + default: + break; } if (lines > 1) { - nilpoint[1] -= (float(lines-1)/(float)lines*height); + nilpoint[1] -= (float(lines - 1) / (float)lines * height); } SbVec3f toppoint = nilpoint; @@ -176,7 +177,7 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) glPushMatrix(); glLoadIdentity(); glOrtho(0, vpsize[0], 0, vpsize[1], -1.0f, 1.0f); - glPixelStorei(GL_UNPACK_ALIGNMENT,1); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); state->push(); @@ -194,10 +195,10 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) // draw background glColor3f(color[0], color[1], color[2]); glBegin(GL_QUADS); - glVertex3f(nilpoint[0]-fs,nilpoint[1]-fs,0.0f); - glVertex3f(toppoint[0]+fs,nilpoint[1]-fs,0.0f); - glVertex3f(toppoint[0]+fs,toppoint[1]+fs,0.0f); - glVertex3f(nilpoint[0]-fs,toppoint[1]+fs,0.0f); + glVertex3f(nilpoint[0] - fs, nilpoint[1] - fs, 0.0f); + glVertex3f(toppoint[0] + fs, nilpoint[1] - fs, 0.0f); + glVertex3f(toppoint[0] + fs, toppoint[1] + fs, 0.0f); + glVertex3f(nilpoint[0] - fs, toppoint[1] + fs, 0.0f); glEnd(); // pop old state @@ -205,7 +206,7 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) glPopAttrib(); state->pop(); - glPixelStorei(GL_UNPACK_ALIGNMENT,4); + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // Pop old GL matrix state. glMatrixMode(GL_PROJECTION); glPopMatrix(); @@ -232,7 +233,7 @@ SoColorBarLabel::SoColorBarLabel() SO_NODE_CONSTRUCTOR(SoColorBarLabel); } -void SoColorBarLabel::computeBBox(SoAction * action, SbBox3f & box, SbVec3f & center) +void SoColorBarLabel::computeBBox(SoAction* action, SbBox3f& box, SbVec3f& center) { inherited::computeBBox(action, box, center); if (!box.hasVolume()) { @@ -258,7 +259,7 @@ SoStringLabel::SoStringLabel() { SO_NODE_CONSTRUCTOR(SoStringLabel); SO_NODE_ADD_FIELD(string, ("")); - SO_NODE_ADD_FIELD(textColor, (SbVec3f(1.0f,1.0f,1.0f))); + SO_NODE_ADD_FIELD(textColor, (SbVec3f(1.0f, 1.0f, 1.0f))); SO_NODE_ADD_FIELD(name, ("Helvetica")); SO_NODE_ADD_FIELD(size, (12)); } @@ -266,10 +267,10 @@ SoStringLabel::SoStringLabel() /** * Renders the open edges only. */ -void SoStringLabel::GLRender(SoGLRenderAction *action) +void SoStringLabel::GLRender(SoGLRenderAction* action) { QOpenGLWidget* window; - SoState * state = action->getState(); + SoState* state = action->getState(); state->push(); SoLazyElement::setLightModel(state, SoLazyElement::BASE_COLOR); SoGLWidgetElement::get(state, window); @@ -282,7 +283,7 @@ void SoStringLabel::GLRender(SoGLRenderAction *action) glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); - glOrtho(-1,1,-1,1,-1,1); + glOrtho(-1, 1, -1, 1, -1, 1); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); @@ -297,19 +298,20 @@ void SoStringLabel::GLRender(SoGLRenderAction *action) font.setFamily(QLatin1String(this->name.getValue())); font.setPixelSize(this->size.getValue()); - glBlendFunc(GL_ONE,GL_SRC_ALPHA); + glBlendFunc(GL_ONE, GL_SRC_ALPHA); // text color SbColor color = this->textColor.getValue(); glColor4f(color[0], color[1], color[2], 1); - const SbMatrix & mat = SoModelMatrixElement::get(state); - const SbMatrix & projmatrix = (mat * SoViewingMatrixElement::get(state) * - SoProjectionMatrixElement::get(state)); + const SbMatrix& mat = SoModelMatrixElement::get(state); + const SbMatrix& projmatrix + = (mat * SoViewingMatrixElement::get(state) * SoProjectionMatrixElement::get(state)); SbVec3f nil(0.0f, 0.0f, 0.0f); projmatrix.multVecMatrix(nil, nil); QStringList list; - for (int i=0; istring.getNum(); i++) + for (int i = 0; i < this->string.getNum(); i++) { list << QLatin1String(this->string[i].getString()); + } // Leave 2D screen mode glPopAttrib(); @@ -334,8 +336,8 @@ SoFrameLabel::SoFrameLabel() { SO_NODE_CONSTRUCTOR(SoFrameLabel); SO_NODE_ADD_FIELD(string, ("")); - SO_NODE_ADD_FIELD(textColor, (SbVec3f(1.0f,1.0f,1.0f))); - SO_NODE_ADD_FIELD(backgroundColor, (SbVec3f(0.0f,0.333f,1.0f))); + SO_NODE_ADD_FIELD(textColor, (SbVec3f(1.0f, 1.0f, 1.0f))); + SO_NODE_ADD_FIELD(backgroundColor, (SbVec3f(0.0f, 0.333f, 1.0f))); SO_NODE_ADD_FIELD(justification, (LEFT)); SO_NODE_ADD_FIELD(name, ("Helvetica")); SO_NODE_ADD_FIELD(size, (12)); @@ -343,26 +345,21 @@ SoFrameLabel::SoFrameLabel() SO_NODE_ADD_FIELD(border, (true)); SO_NODE_ADD_FIELD(backgroundUseBaseColor, (false)); SO_NODE_ADD_FIELD(textUseBaseColor, (false)); - //SO_NODE_ADD_FIELD(image, (SbVec2s(0,0), 0, NULL)); + // SO_NODE_ADD_FIELD(image, (SbVec2s(0,0), 0, NULL)); } -void SoFrameLabel::setIcon(const QPixmap &pixMap) +void SoFrameLabel::setIcon(const QPixmap& pixMap) { iconPixmap = pixMap; drawImage(); } -void SoFrameLabel::notify(SoNotList * list) +void SoFrameLabel::notify(SoNotList* list) { - SoField *f = list->getLastField(); - if (f == &this->string || - f == &this->textColor || - f == &this->backgroundColor || - f == &this->justification || - f == &this->name || - f == &this->size || - f == &this->frame || - f == &this->border) { + SoField* f = list->getLastField(); + if (f == &this->string || f == &this->textColor || f == &this->backgroundColor + || f == &this->justification || f == &this->name || f == &this->size || f == &this->frame + || f == &this->border) { drawImage(); } @@ -384,14 +381,14 @@ void SoFrameLabel::drawImage() int h = fm.height() * num; const SbColor& b = backgroundColor.getValue(); QColor backgroundBrush; - backgroundBrush.setRgbF(b[0],b[1],b[2]); + backgroundBrush.setRgbF(b[0], b[1], b[2]); const SbColor& t = textColor.getValue(); QColor front; - front.setRgbF(t[0],t[1],t[2]); - const QPen borderPen(QColor(0,0,127), 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); + front.setRgbF(t[0], t[1], t[2]); + const QPen borderPen(QColor(0, 0, 127), 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin); QStringList lines; - for (int i=0; i(w, QtTools::horizontalAdvance(fm, line)); lines << line; @@ -406,12 +403,12 @@ void SoFrameLabel::drawImage() if (!iconPixmap.isNull()) { drawIcon = true; iconImg = iconPixmap.toImage(); - widthIcon = iconImg.width() + 2*padding; - heightIcon = iconImg.height() + 2*padding; + widthIcon = iconImg.width() + 2 * padding; + heightIcon = iconImg.height() + 2 * padding; } - int widthText = w + 2*padding; - int heightText = h + 2*padding; + int widthText = w + 2 * padding; + int heightText = h + 2 * padding; int widthTotal = widthText + widthIcon; int heightTotal = heightText > heightIcon ? heightText : heightIcon; int paddingTextV = (heightTotal - h) / 2; @@ -433,18 +430,21 @@ void SoFrameLabel::drawImage() } if (drawIcon) { - painter.drawImage(QPoint(padding, paddingIconV), iconImg); + painter.drawImage(QPoint(padding, paddingIconV), iconImg); } painter.setPen(front); Qt::Alignment align = Qt::AlignVCenter; - if (justification.getValue() == 0) + if (justification.getValue() == 0) { align = Qt::AlignVCenter | Qt::AlignLeft; - else if (justification.getValue() == 1) + } + else if (justification.getValue() == 1) { align = Qt::AlignVCenter | Qt::AlignRight; - else + } + else { align = Qt::AlignVCenter | Qt::AlignHCenter; + } QString text = lines.join(QLatin1String("\n")); painter.setFont(font); painter.drawText(widthIcon + padding, paddingTextV, w, h, align, text); @@ -458,7 +458,7 @@ void SoFrameLabel::drawImage() /** * Renders the open edges only. */ -void SoFrameLabel::GLRender(SoGLRenderAction *action) +void SoFrameLabel::GLRender(SoGLRenderAction* action) { if (backgroundUseBaseColor.getValue()) { @@ -486,11 +486,9 @@ void SoFrameLabel::GLRender(SoGLRenderAction *action) SO_NODE_SOURCE(TranslateManip) -void -TranslateManip::initClass() +void TranslateManip::initClass() { - SO_NODE_INIT_CLASS(TranslateManip, SoTransformManip, - "TransformManip"); + SO_NODE_INIT_CLASS(TranslateManip, SoTransformManip, "TransformManip"); } TranslateManip::TranslateManip() diff --git a/src/Gui/SoTextLabel.h b/src/Gui/SoTextLabel.h index d2dcf43b91..e1240e13fb 100644 --- a/src/Gui/SoTextLabel.h +++ b/src/Gui/SoTextLabel.h @@ -37,13 +37,15 @@ #include "BitmapFactory.h" -namespace Gui { +namespace Gui +{ /** * A text label with a background color. * @author Werner Mayer */ -class GuiExport SoTextLabel : public SoText2 { +class GuiExport SoTextLabel: public SoText2 +{ using inherited = SoText2; SO_NODE_HEADER(SoTextLabel); @@ -58,14 +60,15 @@ public: protected: ~SoTextLabel() override = default; - void GLRender(SoGLRenderAction *action) override; + void GLRender(SoGLRenderAction* action) override; }; /** * A text label for the color bar. * @author Werner Mayer */ -class GuiExport SoColorBarLabel : public SoText2 { +class GuiExport SoColorBarLabel: public SoText2 +{ using inherited = SoText2; SO_NODE_HEADER(SoColorBarLabel); @@ -75,10 +78,11 @@ public: SoColorBarLabel(); protected: - void computeBBox(SoAction * action, SbBox3f & box, SbVec3f & center) override; + void computeBBox(SoAction* action, SbBox3f& box, SbVec3f& center) override; }; -class GuiExport SoStringLabel : public SoNode { +class GuiExport SoStringLabel: public SoNode +{ using inherited = SoNode; SO_NODE_HEADER(SoStringLabel); @@ -88,52 +92,56 @@ public: SoStringLabel(); SoMFString string; - SoSFColor textColor; - SoSFName name; - SoSFInt32 size; + SoSFColor textColor; + SoSFName name; + SoSFInt32 size; protected: ~SoStringLabel() override = default; - void GLRender(SoGLRenderAction *action) override; + void GLRender(SoGLRenderAction* action) override; }; -class GuiExport SoFrameLabel : public SoImage { +class GuiExport SoFrameLabel: public SoImage +{ using inherited = SoImage; SO_NODE_HEADER(SoFrameLabel); public: - enum Justification { - LEFT, RIGHT, CENTER + enum Justification + { + LEFT, + RIGHT, + CENTER }; static void initClass(); SoFrameLabel(); - void setIcon(const QPixmap &pixMap); + void setIcon(const QPixmap& pixMap); SoMFString string; - SoSFColor textColor; - SoSFColor backgroundColor; - SoSFEnum justification; - SoSFName name; - SoSFInt32 size; - SoSFBool frame; - SoSFBool border; - SoSFBool backgroundUseBaseColor; - SoSFBool textUseBaseColor; - //SoSFImage image; - QPixmap iconPixmap; + SoSFColor textColor; + SoSFColor backgroundColor; + SoSFEnum justification; + SoSFName name; + SoSFInt32 size; + SoSFBool frame; + SoSFBool border; + SoSFBool backgroundUseBaseColor; + SoSFBool textUseBaseColor; + // SoSFImage image; + QPixmap iconPixmap; protected: ~SoFrameLabel() override = default; - void notify(SoNotList * list) override; - void GLRender(SoGLRenderAction *action) override; + void notify(SoNotList* list) override; + void GLRender(SoGLRenderAction* action) override; private: void drawImage(); }; -class GuiExport TranslateManip : public SoTransformManip +class GuiExport TranslateManip: public SoTransformManip { SO_NODE_HEADER(TranslateManip); @@ -147,7 +155,6 @@ private: ~TranslateManip() override; }; -} // namespace Gui - -#endif // GUI_SOTEXTLABEL_H +} // namespace Gui +#endif // GUI_SOTEXTLABEL_H diff --git a/src/Gui/SoTouchEvents.cpp b/src/Gui/SoTouchEvents.cpp index baa6a164b8..3a886769d0 100644 --- a/src/Gui/SoTouchEvents.cpp +++ b/src/Gui/SoTouchEvents.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include @@ -36,7 +35,7 @@ SO_EVENT_SOURCE(SoGestureEvent); -SbBool SoGestureEvent::isSoGestureEvent(const SoEvent *ev) const +SbBool SoGestureEvent::isSoGestureEvent(const SoEvent* ev) const { return ev->isOfType(SoGestureEvent::getClassTypeId()); } @@ -45,7 +44,7 @@ SbBool SoGestureEvent::isSoGestureEvent(const SoEvent *ev) const SO_EVENT_SOURCE(SoGesturePanEvent); -SoGesturePanEvent::SoGesturePanEvent(QPanGesture* qpan, QWidget *widget) +SoGesturePanEvent::SoGesturePanEvent(QPanGesture* qpan, QWidget* widget) { Q_UNUSED(widget); totalOffset = SbVec2f(qpan->offset().x(), -qpan->offset().y()); @@ -59,7 +58,7 @@ SoGesturePanEvent::SoGesturePanEvent(QPanGesture* qpan, QWidget *widget) this->setTime(SbTime::getTimeOfDay()); } -SbBool SoGesturePanEvent::isSoGesturePanEvent(const SoEvent *ev) const +SbBool SoGesturePanEvent::isSoGesturePanEvent(const SoEvent* ev) const { return ev->isOfType(SoGesturePanEvent::getClassTypeId()); } @@ -68,28 +67,29 @@ SbBool SoGesturePanEvent::isSoGesturePanEvent(const SoEvent *ev) const SO_EVENT_SOURCE(SoGesturePinchEvent); -SoGesturePinchEvent::SoGesturePinchEvent(QPinchGesture* qpinch, QWidget *widget) +SoGesturePinchEvent::SoGesturePinchEvent(QPinchGesture* qpinch, QWidget* widget) { int h = widget->height(); - QPointF widgetCorner = QPointF(widget->mapToGlobal(QPoint(0,0))); - qreal scaleToWidget = (widget->mapFromGlobal(QPoint(800,800))-widget->mapFromGlobal(QPoint(0,0))).x()/800.0; - QPointF pnt;//temporary + QPointF widgetCorner = QPointF(widget->mapToGlobal(QPoint(0, 0))); + qreal scaleToWidget + = (widget->mapFromGlobal(QPoint(800, 800)) - widget->mapFromGlobal(QPoint(0, 0))).x() / 800.0; + QPointF pnt; // temporary pnt = qpinch->startCenterPoint(); - pnt = (pnt-widgetCorner)*scaleToWidget;//translate screen coord. into widget coord. + pnt = (pnt - widgetCorner) * scaleToWidget; // translate screen coord. into widget coord. startCenter = SbVec2f(pnt.x(), h - pnt.y()); pnt = qpinch->centerPoint(); - pnt = (pnt-widgetCorner)*scaleToWidget; + pnt = (pnt - widgetCorner) * scaleToWidget; curCenter = SbVec2f(pnt.x(), h - pnt.y()); pnt = qpinch->lastCenterPoint(); - pnt = (pnt-widgetCorner)*scaleToWidget; + pnt = (pnt - widgetCorner) * scaleToWidget; deltaCenter = curCenter - SbVec2f(pnt.x(), h - pnt.y()); deltaZoom = qpinch->scaleFactor(); totalZoom = qpinch->totalScaleFactor(); - deltaAngle = -unbranchAngle(Base::toRadians(qpinch->rotationAngle()-qpinch->lastRotationAngle())); + deltaAngle = -unbranchAngle(Base::toRadians(qpinch->rotationAngle() - qpinch->lastRotationAngle())); totalAngle = Base::toRadians(-qpinch->totalRotationAngle()); state = SbGestureState(qpinch->state()); @@ -102,7 +102,7 @@ SoGesturePinchEvent::SoGesturePinchEvent(QPinchGesture* qpinch, QWidget *widget) this->setTime(SbTime::getTimeOfDay()); } -SbBool SoGesturePinchEvent::isSoGesturePinchEvent(const SoEvent *ev) const +SbBool SoGesturePinchEvent::isSoGesturePinchEvent(const SoEvent* ev) const { return ev->isOfType(SoGesturePinchEvent::getClassTypeId()); } @@ -124,31 +124,31 @@ double SoGesturePinchEvent::unbranchAngle(double ang) SO_EVENT_SOURCE(SoGestureSwipeEvent); -SoGestureSwipeEvent::SoGestureSwipeEvent(QSwipeGesture *qwsipe, QWidget *widget) +SoGestureSwipeEvent::SoGestureSwipeEvent(QSwipeGesture* qwsipe, QWidget* widget) { Q_UNUSED(widget); angle = qwsipe->swipeAngle(); - switch (qwsipe->verticalDirection()){ - case QSwipeGesture::Up : - vertDir = +1; - break; - case QSwipeGesture::Down : - vertDir = -1; - break; - default: - vertDir = 0; - break; + switch (qwsipe->verticalDirection()) { + case QSwipeGesture::Up: + vertDir = +1; + break; + case QSwipeGesture::Down: + vertDir = -1; + break; + default: + vertDir = 0; + break; } - switch (qwsipe->horizontalDirection()){ - case QSwipeGesture::Right : - horzDir = +1; - break; - case QSwipeGesture::Left : - horzDir = -1; - break; - default: - horzDir = 0; - break; + switch (qwsipe->horizontalDirection()) { + case QSwipeGesture::Right: + horzDir = +1; + break; + case QSwipeGesture::Left: + horzDir = -1; + break; + default: + horzDir = 0; + break; } state = SbGestureState(qwsipe->state()); @@ -160,7 +160,7 @@ SoGestureSwipeEvent::SoGestureSwipeEvent(QSwipeGesture *qwsipe, QWidget *widget) this->setTime(SbTime::getTimeOfDay()); } -SbBool SoGestureSwipeEvent::isSoGestureSwipeEvent(const SoEvent *ev) const +SbBool SoGestureSwipeEvent::isSoGestureSwipeEvent(const SoEvent* ev) const { return ev->isOfType(SoGestureSwipeEvent::getClassTypeId()); } @@ -169,41 +169,43 @@ SbBool SoGestureSwipeEvent::isSoGestureSwipeEvent(const SoEvent *ev) const //----------------------------GesturesDevice------------------------------- GesturesDevice::GesturesDevice(QWidget* widget) - : InputDevice(nullptr) + : InputDevice(nullptr) { - if (SoGestureEvent::getClassTypeId().isBad()){ + if (SoGestureEvent::getClassTypeId().isBad()) { SoGestureEvent::initClass(); SoGesturePanEvent::initClass(); SoGesturePinchEvent::initClass(); SoGestureSwipeEvent::initClass(); } - if (! widget) - throw Base::ValueError("Can't create a gestures quarter input device without widget (null pointer was passed)."); + if (!widget) { + throw Base::ValueError( + "Can't create a gestures quarter input device without widget (null pointer was passed)." + ); + } this->widget = widget; } const SoEvent* GesturesDevice::translateEvent(QEvent* event) { - if (event->type() == QEvent::Gesture - || event->type() == QEvent::GestureOverride) { + if (event->type() == QEvent::Gesture || event->type() == QEvent::GestureOverride) { auto gevent = static_cast(event); auto zg = static_cast(gevent->gesture(Qt::PinchGesture)); - if(zg){ - gevent->setAccepted(Qt::PinchGesture,true);//prefer it over pan - return new SoGesturePinchEvent(zg,this->widget); + if (zg) { + gevent->setAccepted(Qt::PinchGesture, true); // prefer it over pan + return new SoGesturePinchEvent(zg, this->widget); } auto pg = static_cast(gevent->gesture(Qt::PanGesture)); - if(pg){ - gevent->setAccepted(Qt::PanGesture,true); - return new SoGesturePanEvent(pg,this->widget); + if (pg) { + gevent->setAccepted(Qt::PanGesture, true); + return new SoGesturePanEvent(pg, this->widget); } auto sg = static_cast(gevent->gesture(Qt::SwipeGesture)); - if(sg){ - gevent->setAccepted(Qt::SwipeGesture,true); - return new SoGesturePanEvent(pg,this->widget); + if (sg) { + gevent->setAccepted(Qt::SwipeGesture, true); + return new SoGesturePanEvent(pg, this->widget); } } return nullptr; diff --git a/src/Gui/SoTouchEvents.h b/src/Gui/SoTouchEvents.h index 3df1dc96ea..80af47814e 100644 --- a/src/Gui/SoTouchEvents.h +++ b/src/Gui/SoTouchEvents.h @@ -33,34 +33,41 @@ class QWidget; namespace Quarter = SIM::Coin3D::Quarter; -class SoGestureEvent : public SoEvent { +class SoGestureEvent: public SoEvent +{ SO_EVENT_HEADER(); + public: - static void initClass(){ + static void initClass() + { SO_EVENT_INIT_CLASS(SoGestureEvent, SoEvent); } SoGestureEvent() = default; ~SoGestureEvent() override = default; SbBool isSoGestureEvent(const SoEvent* ev) const; - enum SbGestureState { + enum SbGestureState + { SbGSNoGesture = Qt::NoGesture, SbGSStart = Qt::GestureStarted, SbGSUpdate = Qt::GestureUpdated, SbGSEnd = Qt::GestureFinished, SbGsCanceled = Qt::GestureCanceled }; - SbGestureState state{SbGSNoGesture}; + SbGestureState state {SbGSNoGesture}; }; -class SoGesturePanEvent : public SoGestureEvent { +class SoGesturePanEvent: public SoGestureEvent +{ SO_EVENT_HEADER(); + public: - static void initClass(){//needs to be called before the class can be used. Initializes type IDs of the class. + static void initClass() + { // needs to be called before the class can be used. Initializes type IDs of the class. SO_EVENT_INIT_CLASS(SoGesturePanEvent, SoGestureEvent); } SoGesturePanEvent() = default; - SoGesturePanEvent(QPanGesture *qpan, QWidget *widget); + SoGesturePanEvent(QPanGesture* qpan, QWidget* widget); ~SoGesturePanEvent() override = default; SbBool isSoGesturePanEvent(const SoEvent* ev) const; @@ -68,59 +75,71 @@ public: SbVec2f totalOffset; }; -class SoGesturePinchEvent : public SoGestureEvent { +class SoGesturePinchEvent: public SoGestureEvent +{ SO_EVENT_HEADER(); + public: - static void initClass(){ + static void initClass() + { SO_EVENT_INIT_CLASS(SoGesturePinchEvent, SoGestureEvent); } - SoGesturePinchEvent() : deltaZoom(0), totalZoom(0), - deltaAngle(0), totalAngle(0) - { - } + SoGesturePinchEvent() + : deltaZoom(0) + , totalZoom(0) + , deltaAngle(0) + , totalAngle(0) + {} SoGesturePinchEvent(QPinchGesture* qpinch, QWidget* widget); ~SoGesturePinchEvent() override = default; SbBool isSoGesturePinchEvent(const SoEvent* ev) const; - SbVec2f startCenter;//in GL pixel coordinates (from bottom left corner of view area) + SbVec2f startCenter; // in GL pixel coordinates (from bottom left corner of view area) SbVec2f curCenter; SbVec2f deltaCenter; - double deltaZoom;//change of zoom factor (1.0 = no change, >1 - zoom in, 0..1 - zoom out) - double totalZoom;//zoom factor accumulated since start of gesture. + double deltaZoom; // change of zoom factor (1.0 = no change, >1 - zoom in, 0..1 - zoom out) + double totalZoom; // zoom factor accumulated since start of gesture. double deltaAngle; double totalAngle; static double unbranchAngle(double ang); - }; -class SoGestureSwipeEvent : public SoGestureEvent { +class SoGestureSwipeEvent: public SoGestureEvent +{ SO_EVENT_HEADER(); + public: - static void initClass(){ + static void initClass() + { SO_EVENT_INIT_CLASS(SoGestureSwipeEvent, SoGestureEvent); } - SoGestureSwipeEvent() : angle(0), vertDir(0), horzDir(0) - { - } - SoGestureSwipeEvent(QSwipeGesture* qwsipe, QWidget *widget); + SoGestureSwipeEvent() + : angle(0) + , vertDir(0) + , horzDir(0) + {} + SoGestureSwipeEvent(QSwipeGesture* qwsipe, QWidget* widget); ~SoGestureSwipeEvent() override = default; SbBool isSoGestureSwipeEvent(const SoEvent* ev) const; double angle; - int vertDir;//+1,0,-1 up/none/down - int horzDir;//+1,0,-1 right/none/left + int vertDir; //+1,0,-1 up/none/down + int horzDir; //+1,0,-1 right/none/left }; -class GesturesDevice : public Quarter::InputDevice { +class GesturesDevice: public Quarter::InputDevice +{ public: - explicit GesturesDevice(QWidget* widget);//it needs to know the widget to do coordinate translation + explicit GesturesDevice(QWidget* widget); // it needs to know the widget to do coordinate + // translation ~GesturesDevice() override = default; const SoEvent* translateEvent(QEvent* event) override; + protected: QWidget* widget; }; -#endif // SOTOUCHEVENTS_H +#endif // SOTOUCHEVENTS_H diff --git a/src/Gui/SpaceballEvent.cpp b/src/Gui/SpaceballEvent.cpp index 27c9f12c87..dd03767589 100644 --- a/src/Gui/SpaceballEvent.cpp +++ b/src/Gui/SpaceballEvent.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include "SpaceballEvent.h" @@ -30,67 +29,69 @@ using namespace Spaceball; int MotionEvent::MotionEventType = -1; int ButtonEvent::ButtonEventType = -1; -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) -EventBase::EventBase(QEvent::Type event) : QInputEvent(static_cast(event)) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) +EventBase::EventBase(QEvent::Type event) + : QInputEvent(static_cast(event)) #else -EventBase::EventBase(QEvent::Type event) : QInputEvent(static_cast(event), QPointingDevice::primaryPointingDevice()) +EventBase::EventBase(QEvent::Type event) + : QInputEvent(static_cast(event), QPointingDevice::primaryPointingDevice()) #endif -{ +{} -} +MotionEvent::MotionEvent() + : EventBase(static_cast(MotionEventType)) +{} -MotionEvent::MotionEvent() : EventBase(static_cast(MotionEventType)) +MotionEvent::MotionEvent(const MotionEvent& in) + : EventBase(static_cast(MotionEventType)) { -} - -MotionEvent::MotionEvent(const MotionEvent& in) : EventBase(static_cast(MotionEventType)) -{ - xTrans = in.xTrans; - yTrans = in.yTrans; - zTrans = in.zTrans; - xRot = in.xRot; - yRot = in.yRot; - zRot = in.zRot; + xTrans = in.xTrans; + yTrans = in.yTrans; + zTrans = in.zTrans; + xRot = in.xRot; + yRot = in.yRot; + zRot = in.zRot; handled = in.handled; } -MotionEvent& MotionEvent::operator= (const MotionEvent& in) +MotionEvent& MotionEvent::operator=(const MotionEvent& in) { - if (this == &in) + if (this == &in) { return *this; + } - xTrans = in.xTrans; - yTrans = in.yTrans; - zTrans = in.zTrans; - xRot = in.xRot; - yRot = in.yRot; - zRot = in.zRot; + xTrans = in.xTrans; + yTrans = in.yTrans; + zTrans = in.zTrans; + xRot = in.xRot; + yRot = in.yRot; + zRot = in.zRot; handled = in.handled; return *this; } -void MotionEvent::translations(int &xTransOut, int &yTransOut, int &zTransOut) +void MotionEvent::translations(int& xTransOut, int& yTransOut, int& zTransOut) { xTransOut = xTrans; yTransOut = yTrans; zTransOut = zTrans; } -void MotionEvent::setTranslations(const int &xTransIn, const int &yTransIn, const int &zTransIn) +void MotionEvent::setTranslations(const int& xTransIn, const int& yTransIn, const int& zTransIn) { xTrans = xTransIn; yTrans = yTransIn; zTrans = zTransIn; } -void MotionEvent::rotations(int &xRotOut, int &yRotOut, int &zRotOut) +void MotionEvent::rotations(int& xRotOut, int& yRotOut, int& zRotOut) { xRotOut = xRot; yRotOut = yRot; zRotOut = zRot; } -void MotionEvent::setRotations(const int &xRotIn, const int &yRotIn, const int &zRotIn) +void MotionEvent::setRotations(const int& xRotIn, const int& yRotIn, const int& zRotIn) { xRot = xRotIn; yRot = yRotIn; @@ -98,22 +99,25 @@ void MotionEvent::setRotations(const int &xRotIn, const int &yRotIn, const int & } -ButtonEvent::ButtonEvent() : EventBase(static_cast(ButtonEventType)), - buttonState(BUTTON_NONE), button(0) -{ -} +ButtonEvent::ButtonEvent() + : EventBase(static_cast(ButtonEventType)) + , buttonState(BUTTON_NONE) + , button(0) +{} -ButtonEvent::ButtonEvent(const ButtonEvent& in) : EventBase(static_cast(ButtonEventType)) +ButtonEvent::ButtonEvent(const ButtonEvent& in) + : EventBase(static_cast(ButtonEventType)) { buttonState = in.buttonState; button = in.button; handled = in.handled; } -ButtonEvent& ButtonEvent::operator= (const ButtonEvent& in) +ButtonEvent& ButtonEvent::operator=(const ButtonEvent& in) { - if (this == &in) + if (this == &in) { return *this; + } buttonState = in.buttonState; button = in.button; @@ -126,7 +130,7 @@ ButtonStateType ButtonEvent::buttonStatus() return buttonState; } -void ButtonEvent::setButtonStatus(const ButtonStateType &buttonStatusIn) +void ButtonEvent::setButtonStatus(const ButtonStateType& buttonStatusIn) { buttonState = buttonStatusIn; } @@ -136,7 +140,7 @@ int ButtonEvent::buttonNumber() return button; } -void ButtonEvent::setButtonNumber(const int &buttonNumberIn) +void ButtonEvent::setButtonNumber(const int& buttonNumberIn) { button = buttonNumberIn; } diff --git a/src/Gui/SpaceballEvent.h b/src/Gui/SpaceballEvent.h index 32f16a1bc3..12fd18b7dc 100644 --- a/src/Gui/SpaceballEvent.h +++ b/src/Gui/SpaceballEvent.h @@ -27,64 +27,93 @@ namespace Spaceball { - enum ButtonStateType {BUTTON_NONE = 0, BUTTON_PRESSED, BUTTON_RELEASED}; +enum ButtonStateType +{ + BUTTON_NONE = 0, + BUTTON_PRESSED, + BUTTON_RELEASED +}; - class EventBase : public QInputEvent +class EventBase: public QInputEvent +{ +public: + bool isHandled() { - public: - bool isHandled(){return handled;} - void setHandled(bool sig){handled = sig;} - - protected: - explicit EventBase(QEvent::Type event); - bool handled{false}; - }; - - class MotionEvent : public EventBase + return handled; + } + void setHandled(bool sig) { - public: - MotionEvent(); - MotionEvent(const MotionEvent& in); - MotionEvent& operator= (const MotionEvent& in); - void translations(int &xTransOut, int &yTransOut, int &zTransOut); - void setTranslations(const int &xTransIn, const int &yTransIn, const int &zTransIn); - int translationX(){return xTrans;} - int translationY(){return yTrans;} - int translationZ(){return zTrans;} + handled = sig; + } - void rotations(int &xRotOut, int &yRotOut, int &zRotOut); - void setRotations(const int &xRotIn, const int &yRotIn, const int &zRotIn); - int rotationX(){return xRot;} - int rotationY(){return yRot;} - int rotationZ(){return zRot;} +protected: + explicit EventBase(QEvent::Type event); + bool handled {false}; +}; - static int MotionEventType; - - private: - int xTrans{0}; - int yTrans{0}; - int zTrans{0}; - int xRot{0}; - int yRot{0}; - int zRot{0}; - }; - - class ButtonEvent : public EventBase +class MotionEvent: public EventBase +{ +public: + MotionEvent(); + MotionEvent(const MotionEvent& in); + MotionEvent& operator=(const MotionEvent& in); + void translations(int& xTransOut, int& yTransOut, int& zTransOut); + void setTranslations(const int& xTransIn, const int& yTransIn, const int& zTransIn); + int translationX() { - public: - ButtonEvent(); - ButtonEvent(const ButtonEvent& in); - ButtonEvent& operator= (const ButtonEvent& in); - ButtonStateType buttonStatus(); - void setButtonStatus(const ButtonStateType &buttonStatusIn); - int buttonNumber(); - void setButtonNumber(const int &buttonNumberIn); + return xTrans; + } + int translationY() + { + return yTrans; + } + int translationZ() + { + return zTrans; + } - static int ButtonEventType; + void rotations(int& xRotOut, int& yRotOut, int& zRotOut); + void setRotations(const int& xRotIn, const int& yRotIn, const int& zRotIn); + int rotationX() + { + return xRot; + } + int rotationY() + { + return yRot; + } + int rotationZ() + { + return zRot; + } - private: - ButtonStateType buttonState; - int button; - }; -} -#endif // SPACEBALLEVENT_H + static int MotionEventType; + +private: + int xTrans {0}; + int yTrans {0}; + int zTrans {0}; + int xRot {0}; + int yRot {0}; + int zRot {0}; +}; + +class ButtonEvent: public EventBase +{ +public: + ButtonEvent(); + ButtonEvent(const ButtonEvent& in); + ButtonEvent& operator=(const ButtonEvent& in); + ButtonStateType buttonStatus(); + void setButtonStatus(const ButtonStateType& buttonStatusIn); + int buttonNumber(); + void setButtonNumber(const int& buttonNumberIn); + + static int ButtonEventType; + +private: + ButtonStateType buttonState; + int button; +}; +} // namespace Spaceball +#endif // SPACEBALLEVENT_H diff --git a/src/Gui/SpinBox.cpp b/src/Gui/SpinBox.cpp index 94df2f339f..f0eb50e2a6 100644 --- a/src/Gui/SpinBox.cpp +++ b/src/Gui/SpinBox.cpp @@ -20,12 +20,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -44,7 +44,7 @@ using namespace App; using namespace Base; ExpressionSpinBox::ExpressionSpinBox(QAbstractSpinBox* sb) - : spinbox(sb) + : spinbox(sb) { lineedit = spinbox->findChild(); // Set Margins @@ -55,9 +55,7 @@ ExpressionSpinBox::ExpressionSpinBox(QAbstractSpinBox* sb) lineedit->setAlignment(Qt::AlignVCenter); makeLabel(lineedit); - QObject::connect(iconLabel, &ExpressionLabel::clicked, [this]() { - this->openFormulaDialog(); - }); + QObject::connect(iconLabel, &ExpressionLabel::clicked, [this]() { this->openFormulaDialog(); }); } ExpressionSpinBox::~ExpressionSpinBox() = default; @@ -71,7 +69,7 @@ int ExpressionSpinBox::getMargin() #endif } -void ExpressionSpinBox::bind(const App::ObjectIdentifier &_path) +void ExpressionSpinBox::bind(const App::ObjectIdentifier& _path) { ExpressionBinding::bind(_path); @@ -84,8 +82,7 @@ void ExpressionSpinBox::showIcon() } void ExpressionSpinBox::validateInput() -{ -} +{} void ExpressionSpinBox::showInvalidExpression(const QString& tip) { @@ -99,15 +96,15 @@ void ExpressionSpinBox::showInvalidExpression(const QString& tip) void ExpressionSpinBox::showValidExpression(ExpressionSpinBox::Number number) { std::unique_ptr result(getExpression()->eval()); - auto * value = freecad_cast(result.get()); + auto* value = freecad_cast(result.get()); if (value) { switch (number) { - case Number::SetIfNumber: - setNumberExpression(value); - break; - case Number::KeepCurrent: - break; + case Number::SetIfNumber: + setNumberExpression(value); + break; + case Number::KeepCurrent: + break; } spinbox->setReadOnly(true); @@ -142,7 +139,7 @@ void ExpressionSpinBox::updateExpression() clearExpression(); } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { showInvalidExpression(QString::fromLatin1(e.what())); } } @@ -155,7 +152,7 @@ void ExpressionSpinBox::setExpression(std::shared_ptr expr) ExpressionBinding::setExpression(expr); validateInput(); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { showInvalidExpression(QString::fromLatin1(e.what())); } } @@ -183,26 +180,29 @@ void ExpressionSpinBox::openFormulaDialog() { Q_ASSERT(isBound()); - auto * qprop = freecad_cast(getPath().getProperty()); + auto* qprop = freecad_cast(getPath().getProperty()); Unit unit; - if (qprop) + if (qprop) { unit = qprop->getUnit(); + } auto box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), unit, spinbox); QObject::connect(box, &Gui::Dialog::DlgExpressionInput::finished, [this, box]() { - if (box->result() == QDialog::Accepted) + if (box->result() == QDialog::Accepted) { setExpression(box->getExpression()); - else if (box->discardedFormula()) + } + else if (box->discardedFormula()) { setExpression(std::shared_ptr()); + } updateExpression(); box->deleteLater(); }); box->show(); - QPoint pos = spinbox->mapToGlobal(QPoint(0,0)); - box->move(pos-box->expressionPosition()); + QPoint pos = spinbox->mapToGlobal(QPoint(0, 0)); + box->move(pos - box->expressionPosition()); Gui::adjustDialogPosition(box); } @@ -231,15 +231,15 @@ void ExpressionSpinBox::drawControl(QStyleOptionSpinBox& opt) // ---------------------------------------------------------------------------- -UnsignedValidator::UnsignedValidator( QObject * parent ) - : QValidator( parent ) +UnsignedValidator::UnsignedValidator(QObject* parent) + : QValidator(parent) { - b = 0; - t = std::numeric_limits::max(); + b = 0; + t = std::numeric_limits::max(); } -UnsignedValidator::UnsignedValidator( uint minimum, uint maximum, QObject * parent ) - : QValidator( parent ) +UnsignedValidator::UnsignedValidator(uint minimum, uint maximum, QObject* parent) + : QValidator(parent) { b = minimum; t = maximum; @@ -247,94 +247,108 @@ UnsignedValidator::UnsignedValidator( uint minimum, uint maximum, QObject * pare UnsignedValidator::~UnsignedValidator() = default; -QValidator::State UnsignedValidator::validate( QString & input, int & ) const +QValidator::State UnsignedValidator::validate(QString& input, int&) const { QString stripped = input.trimmed(); - if ( stripped.isEmpty() ) + if (stripped.isEmpty()) { return Intermediate; + } bool ok; - uint entered = input.toUInt( &ok ); - if ( !ok ) + uint entered = input.toUInt(&ok); + if (!ok) { return Invalid; - else if ( entered < b ) + } + else if (entered < b) { return Intermediate; - else if ( entered > t ) + } + else if (entered > t) { return Invalid; + } // else if ( entered < b || entered > t ) // return Invalid; - else + else { return Acceptable; + } } -void UnsignedValidator::setRange( uint minimum, uint maximum ) +void UnsignedValidator::setRange(uint minimum, uint maximum) { b = minimum; t = maximum; } -void UnsignedValidator::setBottom( uint bottom ) +void UnsignedValidator::setBottom(uint bottom) { - setRange( bottom, top() ); + setRange(bottom, top()); } -void UnsignedValidator::setTop( uint top ) +void UnsignedValidator::setTop(uint top) { - setRange( bottom(), top ); + setRange(bottom(), top); } -namespace Gui { +namespace Gui +{ class UIntSpinBoxPrivate { public: - UnsignedValidator * mValidator{nullptr}; + UnsignedValidator* mValidator {nullptr}; UIntSpinBoxPrivate() = default; - unsigned mapToUInt( int v ) const + unsigned mapToUInt(int v) const { using int_limits = std::numeric_limits; using uint_limits = std::numeric_limits; unsigned ui; - if ( v == int_limits::min() ) { + if (v == int_limits::min()) { ui = 0; - } else if ( v == int_limits::max() ) { + } + else if (v == int_limits::max()) { ui = uint_limits::max(); - } else if ( v < 0 ) { + } + else if (v < 0) { v -= int_limits::min(); ui = static_cast(v); - } else { + } + else { ui = static_cast(v); ui -= int_limits::min(); - } return ui; + } + return ui; } - int mapToInt( unsigned v ) const + int mapToInt(unsigned v) const { using int_limits = std::numeric_limits; using uint_limits = std::numeric_limits; int in; - if ( v == uint_limits::max() ) { + if (v == uint_limits::max()) { in = int_limits::max(); - } else if ( v == 0 ) { + } + else if (v == 0) { in = int_limits::min(); - } else if ( v > static_cast(int_limits::max()) ) { + } + else if (v > static_cast(int_limits::max())) { v += int_limits::min(); in = static_cast(v); - } else { + } + else { in = v; in += int_limits::min(); - } return in; + } + return in; } }; -} // namespace Gui +} // namespace Gui -UIntSpinBox::UIntSpinBox (QWidget* parent) - : QSpinBox (parent) - , ExpressionSpinBox(this) +UIntSpinBox::UIntSpinBox(QWidget* parent) + : QSpinBox(parent) + , ExpressionSpinBox(this) { d = new UIntSpinBoxPrivate; - d->mValidator = new UnsignedValidator(this->minimum(), this->maximum(), this); + d->mValidator = new UnsignedValidator(this->minimum(), this->maximum(), this); connect(this, qOverload(&QSpinBox::valueChanged), this, &UIntSpinBox::valueChange); setRange(0, 99); setValue(0); @@ -344,7 +358,8 @@ UIntSpinBox::UIntSpinBox (QWidget* parent) UIntSpinBox::~UIntSpinBox() { delete d->mValidator; - delete d; d = nullptr; + delete d; + d = nullptr; } void UIntSpinBox::setRange(uint minVal, uint maxVal) @@ -355,7 +370,7 @@ void UIntSpinBox::setRange(uint minVal, uint maxVal) updateValidator(); } -QValidator::State UIntSpinBox::validate (QString & input, int & pos) const +QValidator::State UIntSpinBox::validate(QString& input, int& pos) const { return d->mValidator->validate(input, pos); } @@ -383,8 +398,9 @@ uint UIntSpinBox::minimum() const void UIntSpinBox::setMinimum(uint minVal) { uint maxVal = maximum(); - if (maxVal < minVal) + if (maxVal < minVal) { maxVal = minVal; + } setRange(minVal, maxVal); } @@ -396,12 +412,13 @@ uint UIntSpinBox::maximum() const void UIntSpinBox::setMaximum(uint maxVal) { uint minVal = minimum(); - if (minVal > maxVal) + if (minVal > maxVal) { minVal = maxVal; + } setRange(minVal, maxVal); } -QString UIntSpinBox::textFromValue (int v) const +QString UIntSpinBox::textFromValue(int v) const { uint val = d->mapToUInt(v); QString s; @@ -409,7 +426,7 @@ QString UIntSpinBox::textFromValue (int v) const return s; } -int UIntSpinBox::valueFromText (const QString & text) const +int UIntSpinBox::valueFromText(const QString& text) const { bool ok; QString s = text; @@ -427,7 +444,7 @@ void UIntSpinBox::updateValidator() d->mValidator->setRange(this->minimum(), this->maximum()); } -bool UIntSpinBox::apply(const std::string & propName) +bool UIntSpinBox::apply(const std::string& propName) { if (!ExpressionBinding::apply(propName)) { Gui::Command::doCommand(Gui::Command::Doc, "%s = %u", propName.c_str(), value()); @@ -442,16 +459,17 @@ void UIntSpinBox::setNumberExpression(App::NumberExpression* expr) setValue(boost::math::round(expr->getValue())); } -void UIntSpinBox::resizeEvent(QResizeEvent * event) +void UIntSpinBox::resizeEvent(QResizeEvent* event) { QAbstractSpinBox::resizeEvent(event); resizeWidget(); } -void UIntSpinBox::keyPressEvent(QKeyEvent *event) +void UIntSpinBox::keyPressEvent(QKeyEvent* event) { - if (!handleKeyEvent(event->text())) + if (!handleKeyEvent(event->text())) { QAbstractSpinBox::keyPressEvent(event); + } } void UIntSpinBox::paintEvent(QPaintEvent*) @@ -466,8 +484,7 @@ void UIntSpinBox::paintEvent(QPaintEvent*) IntSpinBox::IntSpinBox(QWidget* parent) : QSpinBox(parent) , ExpressionSpinBox(this) -{ -} +{} IntSpinBox::~IntSpinBox() = default; @@ -477,8 +494,9 @@ bool IntSpinBox::apply(const std::string& propName) Gui::Command::doCommand(Gui::Command::Doc, "%s = %d", propName.c_str(), value()); return true; } - else + else { return false; + } } void IntSpinBox::setNumberExpression(App::NumberExpression* expr) @@ -486,16 +504,17 @@ void IntSpinBox::setNumberExpression(App::NumberExpression* expr) setValue(boost::math::round(expr->getValue())); } -void IntSpinBox::resizeEvent(QResizeEvent * event) +void IntSpinBox::resizeEvent(QResizeEvent* event) { QAbstractSpinBox::resizeEvent(event); resizeWidget(); } -void IntSpinBox::keyPressEvent(QKeyEvent *event) +void IntSpinBox::keyPressEvent(QKeyEvent* event) { - if (!handleKeyEvent(event->text())) + if (!handleKeyEvent(event->text())) { QAbstractSpinBox::keyPressEvent(event); + } } void IntSpinBox::paintEvent(QPaintEvent*) @@ -510,8 +529,7 @@ void IntSpinBox::paintEvent(QPaintEvent*) DoubleSpinBox::DoubleSpinBox(QWidget* parent) : QDoubleSpinBox(parent) , ExpressionSpinBox(this) -{ -} +{} DoubleSpinBox::~DoubleSpinBox() = default; @@ -530,16 +548,17 @@ void DoubleSpinBox::setNumberExpression(App::NumberExpression* expr) setValue(expr->getValue()); } -void DoubleSpinBox::resizeEvent(QResizeEvent * event) +void DoubleSpinBox::resizeEvent(QResizeEvent* event) { QAbstractSpinBox::resizeEvent(event); resizeWidget(); } -void DoubleSpinBox::keyPressEvent(QKeyEvent *event) +void DoubleSpinBox::keyPressEvent(QKeyEvent* event) { - if (!handleKeyEvent(event->text())) + if (!handleKeyEvent(event->text())) { QDoubleSpinBox::keyPressEvent(event); + } } void DoubleSpinBox::paintEvent(QPaintEvent*) diff --git a/src/Gui/SpinBox.h b/src/Gui/SpinBox.h index 2ba27f9b36..14d12c50ca 100644 --- a/src/Gui/SpinBox.h +++ b/src/Gui/SpinBox.h @@ -30,25 +30,28 @@ class QStyleOptionSpinBox; -namespace App { +namespace App +{ class NumberExpression; } -namespace Gui { +namespace Gui +{ -class GuiExport ExpressionSpinBox : public ExpressionWidget +class GuiExport ExpressionSpinBox: public ExpressionWidget { public: explicit ExpressionSpinBox(QAbstractSpinBox*); ~ExpressionSpinBox() override; - void bind(const App::ObjectIdentifier &_path) override; + void bind(const App::ObjectIdentifier& _path) override; void setExpression(std::shared_ptr expr) override; protected: /*! Expression handling */ //@{ - enum class Number { + enum class Number + { KeepCurrent = 0, SetIfNumber = 1 }; @@ -79,25 +82,31 @@ protected: * A validator that allows only input of unsigned int values in the range * from 0 to UINT_MAX. */ -class GuiExport UnsignedValidator : public QValidator +class GuiExport UnsignedValidator: public QValidator { Q_OBJECT - Q_PROPERTY( uint bottom READ bottom WRITE setBottom ) // clazy:exclude=qproperty-without-notify - Q_PROPERTY( uint top READ top WRITE setTop ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(uint bottom READ bottom WRITE setBottom) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(uint top READ top WRITE setTop) // clazy:exclude=qproperty-without-notify public: - explicit UnsignedValidator( QObject * parent ); - UnsignedValidator( uint bottom, uint top, QObject * parent ); + explicit UnsignedValidator(QObject* parent); + UnsignedValidator(uint bottom, uint top, QObject* parent); ~UnsignedValidator() override; - QValidator::State validate( QString &, int & ) const override; + QValidator::State validate(QString&, int&) const override; - void setBottom( uint ); - void setTop( uint ); - virtual void setRange( uint bottom, uint top ); + void setBottom(uint); + void setTop(uint); + virtual void setRange(uint bottom, uint top); - uint bottom() const { return b; } - uint top() const { return t; } + uint bottom() const + { + return b; + } + uint top() const + { + return t; + } private: uint b, t; @@ -110,49 +119,49 @@ class UIntSpinBoxPrivate; * This allows one to use numbers in the range of [0, UINT_MAX] * @author Werner Mayer */ -class GuiExport UIntSpinBox : public QSpinBox, public ExpressionSpinBox +class GuiExport UIntSpinBox: public QSpinBox, public ExpressionSpinBox { Q_OBJECT - Q_OVERRIDE( uint maximum READ maximum WRITE setMaximum ) - Q_OVERRIDE( uint minimum READ minimum WRITE setMinimum ) - Q_OVERRIDE( uint value READ value WRITE setValue ) + Q_OVERRIDE(uint maximum READ maximum WRITE setMaximum) + Q_OVERRIDE(uint minimum READ minimum WRITE setMinimum) + Q_OVERRIDE(uint value READ value WRITE setValue) public: - explicit UIntSpinBox ( QWidget* parent=nullptr ); + explicit UIntSpinBox(QWidget* parent = nullptr); ~UIntSpinBox() override; - void setRange( uint minVal, uint maxVal ); + void setRange(uint minVal, uint maxVal); uint value() const; - QValidator::State validate ( QString & input, int & pos ) const override; + QValidator::State validate(QString& input, int& pos) const override; uint minimum() const; - void setMinimum( uint value ); + void setMinimum(uint value); uint maximum() const; - void setMaximum( uint value ); + void setMaximum(uint value); - bool apply(const std::string &propName) override; + bool apply(const std::string& propName) override; using ExpressionSpinBox::apply; - void keyPressEvent(QKeyEvent *event) override; - void resizeEvent(QResizeEvent *event) override; - void paintEvent(QPaintEvent *event) override; + void keyPressEvent(QKeyEvent* event) override; + void resizeEvent(QResizeEvent* event) override; + void paintEvent(QPaintEvent* event) override; Q_SIGNALS: - void unsignedChanged( uint value ); + void unsignedChanged(uint value); public Q_SLOTS: - void setValue( uint value ); + void setValue(uint value); private Q_SLOTS: - void valueChange( int value ); + void valueChange(int value); protected: - QString textFromValue ( int v ) const override; - int valueFromText ( const QString & text ) const override; + QString textFromValue(int v) const override; + int valueFromText(const QString& text) const override; void setNumberExpression(App::NumberExpression*) override; private: void updateValidator(); - UIntSpinBoxPrivate * d; + UIntSpinBoxPrivate* d; }; @@ -160,21 +169,21 @@ private: * The IntSpinBox class does exactly the same as Qt's QSpinBox but has expression support * @author Stefan Tröger */ -class GuiExport IntSpinBox : public QSpinBox, public ExpressionSpinBox +class GuiExport IntSpinBox: public QSpinBox, public ExpressionSpinBox { Q_OBJECT public: - explicit IntSpinBox ( QWidget* parent=nullptr ); + explicit IntSpinBox(QWidget* parent = nullptr); ~IntSpinBox() override; - bool apply(const std::string &propName) override; + bool apply(const std::string& propName) override; using ExpressionSpinBox::apply; void setNumberExpression(App::NumberExpression*) override; - void keyPressEvent(QKeyEvent *event) override; - void resizeEvent(QResizeEvent *event) override; - void paintEvent(QPaintEvent *event) override; + void keyPressEvent(QKeyEvent* event) override; + void resizeEvent(QResizeEvent* event) override; + void paintEvent(QPaintEvent* event) override; }; /** @@ -182,23 +191,23 @@ public: * support * @author Stefan Tröger */ -class GuiExport DoubleSpinBox : public QDoubleSpinBox, public ExpressionSpinBox +class GuiExport DoubleSpinBox: public QDoubleSpinBox, public ExpressionSpinBox { Q_OBJECT public: - explicit DoubleSpinBox ( QWidget* parent=nullptr ); + explicit DoubleSpinBox(QWidget* parent = nullptr); ~DoubleSpinBox() override; - bool apply(const std::string &propName) override; + bool apply(const std::string& propName) override; using ExpressionSpinBox::apply; void setNumberExpression(App::NumberExpression*) override; - void keyPressEvent(QKeyEvent *event) override; - void resizeEvent(QResizeEvent *event) override; - void paintEvent(QPaintEvent *event) override; + void keyPressEvent(QKeyEvent* event) override; + void resizeEvent(QResizeEvent* event) override; + void paintEvent(QPaintEvent* event) override; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_SPINBOX_H +#endif // GUI_SPINBOX_H diff --git a/src/Gui/SplashScreen.cpp b/src/Gui/SplashScreen.cpp index 614c055666..7006911058 100644 --- a/src/Gui/SplashScreen.cpp +++ b/src/Gui/SplashScreen.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -112,11 +111,13 @@ public: { return "SplashObserver"; } - void sendLog(const std::string& notifiername, - const std::string& msg, - Base::LogStyle level, - Base::IntendedRecipient recipient, - Base::ContentType content) override + void sendLog( + const std::string& notifiername, + const std::string& msg, + Base::LogStyle level, + Base::IntendedRecipient recipient, + Base::ContentType content + ) override { Q_UNUSED(notifiername) Q_UNUSED(recipient) @@ -172,10 +173,12 @@ private: * displayed as two lines, regardless of the length of the text (e.g. no wrapping is done). Only the * width is considered, the height simply follows from the font size. */ -static void renderDevBuildWarning(QPainter& painter, - const QPoint startPosition, - const QSize maxSize, - QColor color) +static void renderDevBuildWarning( + QPainter& painter, + const QPoint startPosition, + const QSize maxSize, + QColor color +) { // Create a background box that fades out the artwork for better legibility QColor fader(Qt::white); @@ -213,9 +216,7 @@ static void renderDevBuildWarning(QPainter& painter, painter.setPen(color); painter.drawRect(startPosition.x(), startPosition.y(), boxWidth, boxHeight); painter.drawText(startPosition.x() + padding, startPosition.y() + lineHeight, devWarningLine1); - painter.drawText(startPosition.x() + padding, - startPosition.y() + 2 * lineHeight, - devWarningLine2); + painter.drawText(startPosition.x() + padding, startPosition.y() + 2 * lineHeight, devWarningLine2); } } // namespace Gui @@ -280,8 +281,9 @@ QPixmap SplashScreen::splashImage() float pixelRatio(1.0); if (splash_image.isNull()) { // determine the count of splashes - QStringList pixmaps = - Gui::BitmapFactory().findIconFiles().filter(QString::fromStdString(splash_path)); + QStringList pixmaps = Gui::BitmapFactory().findIconFiles().filter( + QString::fromStdString(splash_path) + ); // divide by 2 since there's two sets (normal and 2x) // minus 1 to ignore the default splash that isn't numbered int splash_count = pixmaps.count() / 2 - 1; @@ -305,10 +307,12 @@ QPixmap SplashScreen::splashImage() } // include application name and version number - std::map::const_iterator tc = - App::Application::Config().find("SplashInfoColor"); - std::map::const_iterator wc = - App::Application::Config().find("SplashWarningColor"); + std::map::const_iterator tc = App::Application::Config().find( + "SplashInfoColor" + ); + std::map::const_iterator wc = App::Application::Config().find( + "SplashWarningColor" + ); if (tc != App::Application::Config().end() && wc != App::Application::Config().end()) { QString title = qApp->applicationName(); QString major = QString::fromStdString(App::Application::Config()["BuildVersionMajor"]); @@ -318,14 +322,18 @@ QPixmap SplashScreen::splashImage() QString version = QStringLiteral("%1.%2.%3%4").arg(major, minor, point, suffix); QString position, fontFamily; - std::map::const_iterator te = - App::Application::Config().find("SplashInfoExeName"); - std::map::const_iterator tv = - App::Application::Config().find("SplashInfoVersion"); - std::map::const_iterator tp = - App::Application::Config().find("SplashInfoPosition"); - std::map::const_iterator tf = - App::Application::Config().find("SplashInfoFont"); + std::map::const_iterator te = App::Application::Config().find( + "SplashInfoExeName" + ); + std::map::const_iterator tv = App::Application::Config().find( + "SplashInfoVersion" + ); + std::map::const_iterator tp = App::Application::Config().find( + "SplashInfoPosition" + ); + std::map::const_iterator tf = App::Application::Config().find( + "SplashInfoFont" + ); if (te != App::Application::Config().end()) { title = QString::fromStdString(te->second); } diff --git a/src/Gui/SplitView3DInventor.cpp b/src/Gui/SplitView3DInventor.cpp index 9b821a0206..b4bff60ab0 100644 --- a/src/Gui/SplitView3DInventor.cpp +++ b/src/Gui/SplitView3DInventor.cpp @@ -21,12 +21,11 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -45,10 +44,10 @@ using namespace Gui; -TYPESYSTEM_SOURCE_ABSTRACT(Gui::AbstractSplitView,Gui::MDIView) +TYPESYSTEM_SOURCE_ABSTRACT(Gui::AbstractSplitView, Gui::MDIView) AbstractSplitView::AbstractSplitView(Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags) - : MDIView(pcDocument,parent, wflags) + : MDIView(pcDocument, parent, wflags) { _viewerPy = nullptr; // important for highlighting @@ -57,7 +56,8 @@ AbstractSplitView::AbstractSplitView(Gui::Document* pcDocument, QWidget* parent, AbstractSplitView::~AbstractSplitView() { - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { delete *it; } if (_viewerPy) { @@ -68,7 +68,8 @@ AbstractSplitView::~AbstractSplitView() void AbstractSplitView::deleteSelf() { - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { (*it)->setSceneGraph(nullptr); } MDIView::deleteSelf(); @@ -83,15 +84,18 @@ void AbstractSplitView::setDocumentOfViewers(Gui::Document* document) void AbstractSplitView::viewAll() { - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { (*it)->viewAll(); + } } bool AbstractSplitView::containsViewProvider(const ViewProvider* vp) const { for (auto it = _viewer.begin(); it != _viewer.end(); ++it) { - if ((*it)->containsViewProvider(vp)) + if ((*it)->containsViewProvider(vp)) { return true; + } } return false; @@ -99,8 +103,10 @@ bool AbstractSplitView::containsViewProvider(const ViewProvider* vp) const void AbstractSplitView::setupSettings() { - viewSettings = std::make_unique(App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"), _viewer); + viewSettings = std::make_unique( + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"), + _viewer + ); // tmp. disabled will be activated after redesign of 3d viewer // check whether the simple or the Full Mouse model is used viewSettings->ignoreNavigationStyle = true; @@ -112,8 +118,10 @@ void AbstractSplitView::setupSettings() viewSettings->applySettings(); for (auto view : _viewer) { - NaviCubeSettings naviSettings(App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/NaviCube"), view); + NaviCubeSettings naviSettings( + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/NaviCube"), + view + ); naviSettings.applySettings(); } } @@ -128,74 +136,81 @@ void AbstractSplitView::onUpdate() update(); } -const char *AbstractSplitView::getName() const +const char* AbstractSplitView::getName() const { return "SplitView3DInventor"; } bool AbstractSplitView::onMsg(const char* pMsg, const char**) { - if (strcmp("ViewFit",pMsg) == 0 ) { + if (strcmp("ViewFit", pMsg) == 0) { viewAll(); return true; } - else if (strcmp("ViewBottom",pMsg) == 0) { + else if (strcmp("ViewBottom", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Bottom)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); } return true; } - else if (strcmp("ViewFront",pMsg) == 0) { + else if (strcmp("ViewFront", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Front)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); } return true; } - else if (strcmp("ViewLeft",pMsg) == 0) { + else if (strcmp("ViewLeft", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Left)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); } return true; } - else if (strcmp("ViewRear",pMsg) == 0) { + else if (strcmp("ViewRear", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Rear)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); } return true; } - else if (strcmp("ViewRight",pMsg) == 0) { + else if (strcmp("ViewRight", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Right)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); } return true; } - else if (strcmp("ViewTop",pMsg) == 0) { + else if (strcmp("ViewTop", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Top)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); } return true; } - else if (strcmp("ViewAxo",pMsg) == 0) { + else if (strcmp("ViewAxo", pMsg) == 0) { SbRotation rot(Camera::rotation(Camera::Isometric)); - for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); ++it) { + for (std::vector::iterator it = _viewer.begin(); it != _viewer.end(); + ++it) { SoCamera* cam = (*it)->getSoRenderManager()->getCamera(); cam->orientation.setValue(rot); (*it)->viewAll(); @@ -208,31 +223,31 @@ bool AbstractSplitView::onMsg(const char* pMsg, const char**) bool AbstractSplitView::onHasMsg(const char* pMsg) const { - if (strcmp("CanPan",pMsg) == 0) { + if (strcmp("CanPan", pMsg) == 0) { return true; } - else if (strcmp("ViewFit",pMsg) == 0) { + else if (strcmp("ViewFit", pMsg) == 0) { return true; } - else if (strcmp("ViewBottom",pMsg) == 0) { + else if (strcmp("ViewBottom", pMsg) == 0) { return true; } - else if (strcmp("ViewFront",pMsg) == 0) { + else if (strcmp("ViewFront", pMsg) == 0) { return true; } - else if (strcmp("ViewLeft",pMsg) == 0) { + else if (strcmp("ViewLeft", pMsg) == 0) { return true; } - else if (strcmp("ViewRear",pMsg) == 0) { + else if (strcmp("ViewRear", pMsg) == 0) { return true; } - else if (strcmp("ViewRight",pMsg) == 0) { + else if (strcmp("ViewRight", pMsg) == 0) { return true; } - else if (strcmp("ViewTop",pMsg) == 0) { + else if (strcmp("ViewTop", pMsg) == 0) { return true; } - else if (strcmp("ViewAxo",pMsg) == 0) { + else if (strcmp("ViewAxo", pMsg) == 0) { return true; } else if (strcmp("AllowsOverlayOnHover", pMsg) == 0) { @@ -247,15 +262,16 @@ void AbstractSplitView::setOverrideCursor(const QCursor& aCursor) //_viewer->getWidget()->setCursor(aCursor); } -PyObject *AbstractSplitView::getPyObject() +PyObject* AbstractSplitView::getPyObject() { - if (!_viewerPy) + if (!_viewerPy) { _viewerPy = new AbstractSplitViewPy(this); + } Py_INCREF(_viewerPy); return _viewerPy; } -void AbstractSplitView::setPyObject(PyObject *) +void AbstractSplitView::setPyObject(PyObject*) { throw Base::AttributeError("Attribute is read-only"); } @@ -277,25 +293,28 @@ void AbstractSplitViewPy::init_type() behaviors().supportSetattr(); behaviors().supportSequenceType(); - add_varargs_method("fitAll",&AbstractSplitViewPy::fitAll,"fitAll()"); - add_varargs_method("viewBottom",&AbstractSplitViewPy::viewBottom,"viewBottom()"); - add_varargs_method("viewFront",&AbstractSplitViewPy::viewFront,"viewFront()"); - add_varargs_method("viewLeft",&AbstractSplitViewPy::viewLeft,"viewLeft()"); - add_varargs_method("viewRear",&AbstractSplitViewPy::viewRear,"viewRear()"); - add_varargs_method("viewRight",&AbstractSplitViewPy::viewRight,"viewRight()"); - add_varargs_method("viewTop",&AbstractSplitViewPy::viewTop,"viewTop()"); - add_varargs_method("viewAxometric",&AbstractSplitViewPy::viewIsometric,"viewAxometric()"); - add_varargs_method("viewIsometric",&AbstractSplitViewPy::viewIsometric,"viewIsometric()"); - add_varargs_method("getViewer",&AbstractSplitViewPy::getViewer,"getViewer(index)"); - add_varargs_method("close",&AbstractSplitViewPy::close,"close()"); - add_varargs_method("cast_to_base", &AbstractSplitViewPy::cast_to_base, "cast_to_base() cast to MDIView class"); + add_varargs_method("fitAll", &AbstractSplitViewPy::fitAll, "fitAll()"); + add_varargs_method("viewBottom", &AbstractSplitViewPy::viewBottom, "viewBottom()"); + add_varargs_method("viewFront", &AbstractSplitViewPy::viewFront, "viewFront()"); + add_varargs_method("viewLeft", &AbstractSplitViewPy::viewLeft, "viewLeft()"); + add_varargs_method("viewRear", &AbstractSplitViewPy::viewRear, "viewRear()"); + add_varargs_method("viewRight", &AbstractSplitViewPy::viewRight, "viewRight()"); + add_varargs_method("viewTop", &AbstractSplitViewPy::viewTop, "viewTop()"); + add_varargs_method("viewAxometric", &AbstractSplitViewPy::viewIsometric, "viewAxometric()"); + add_varargs_method("viewIsometric", &AbstractSplitViewPy::viewIsometric, "viewIsometric()"); + add_varargs_method("getViewer", &AbstractSplitViewPy::getViewer, "getViewer(index)"); + add_varargs_method("close", &AbstractSplitViewPy::close, "close()"); + add_varargs_method( + "cast_to_base", + &AbstractSplitViewPy::cast_to_base, + "cast_to_base() cast to MDIView class" + ); behaviors().readyType(); } -AbstractSplitViewPy::AbstractSplitViewPy(AbstractSplitView *vi) - : base(vi) -{ -} +AbstractSplitViewPy::AbstractSplitViewPy(AbstractSplitView* vi) + : base(vi) +{} AbstractSplitViewPy::~AbstractSplitViewPy() = default; @@ -306,8 +325,9 @@ Py::Object AbstractSplitViewPy::cast_to_base(const Py::Tuple&) Py::Object AbstractSplitViewPy::repr() { - if (!getSplitViewPtr()) + if (!getSplitViewPtr()) { throw Py::RuntimeError("Cannot print representation of deleted object"); + } return Py::String("AbstractSplitView"); } @@ -316,10 +336,10 @@ Py::Object AbstractSplitViewPy::repr() // a trick is to use MDIViewPy as class member and override getattr() to // join the attributes of both classes. This way all methods of MDIViewPy // appear for SheetViewPy, too. -Py::Object AbstractSplitViewPy::getattr(const char * attr) +Py::Object AbstractSplitViewPy::getattr(const char* attr) { getSplitViewPtr(); - std::string name( attr ); + std::string name(attr); if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); @@ -341,15 +361,17 @@ Py::Object AbstractSplitViewPy::getattr(const char * attr) AbstractSplitView* AbstractSplitViewPy::getSplitViewPtr() { auto view = qobject_cast(base.getMDIViewPtr()); - if (!(view && view->getViewer(0))) + if (!(view && view->getViewer(0))) { throw Py::RuntimeError("Object already deleted"); + } return view; } Py::Object AbstractSplitViewPy::fitAll(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewFit", nullptr); @@ -360,7 +382,7 @@ Py::Object AbstractSplitViewPy::fitAll(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } return Py::None(); @@ -368,8 +390,9 @@ Py::Object AbstractSplitViewPy::fitAll(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewBottom(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewBottom", nullptr); @@ -380,7 +403,7 @@ Py::Object AbstractSplitViewPy::viewBottom(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -389,8 +412,9 @@ Py::Object AbstractSplitViewPy::viewBottom(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewFront(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewFront", nullptr); @@ -401,7 +425,7 @@ Py::Object AbstractSplitViewPy::viewFront(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -410,8 +434,9 @@ Py::Object AbstractSplitViewPy::viewFront(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewLeft(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewLeft", nullptr); @@ -422,7 +447,7 @@ Py::Object AbstractSplitViewPy::viewLeft(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -431,8 +456,9 @@ Py::Object AbstractSplitViewPy::viewLeft(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewRear(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewRear", nullptr); @@ -443,7 +469,7 @@ Py::Object AbstractSplitViewPy::viewRear(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -452,8 +478,9 @@ Py::Object AbstractSplitViewPy::viewRear(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewRight(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewRight", nullptr); @@ -464,7 +491,7 @@ Py::Object AbstractSplitViewPy::viewRight(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -473,8 +500,9 @@ Py::Object AbstractSplitViewPy::viewRight(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewTop(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewTop", nullptr); @@ -485,7 +513,7 @@ Py::Object AbstractSplitViewPy::viewTop(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -494,8 +522,9 @@ Py::Object AbstractSplitViewPy::viewTop(const Py::Tuple& args) Py::Object AbstractSplitViewPy::viewIsometric(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { getSplitViewPtr()->onMsg("ViewAxo", nullptr); @@ -506,7 +535,7 @@ Py::Object AbstractSplitViewPy::viewIsometric(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -516,13 +545,15 @@ Py::Object AbstractSplitViewPy::viewIsometric(const Py::Tuple& args) Py::Object AbstractSplitViewPy::getViewer(const Py::Tuple& args) { int viewIndex; - if (!PyArg_ParseTuple(args.ptr(), "i", &viewIndex)) + if (!PyArg_ParseTuple(args.ptr(), "i", &viewIndex)) { throw Py::Exception(); + } try { Gui::View3DInventorViewer* view = getSplitViewPtr()->getViewer(viewIndex); - if (!view) + if (!view) { throw Py::IndexError("Index out of range"); + } return Py::asObject(view->getPyObject()); } catch (const Base::Exception& e) { @@ -535,7 +566,7 @@ Py::Object AbstractSplitViewPy::getViewer(const Py::Tuple& args) // re-throw throw; } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -543,8 +574,9 @@ Py::Object AbstractSplitViewPy::getViewer(const Py::Tuple& args) Py::Object AbstractSplitViewPy::sequence_item(Py_ssize_t viewIndex) { AbstractSplitView* view = getSplitViewPtr(); - if (viewIndex >= view->getSize() || viewIndex < 0) + if (viewIndex >= view->getSize() || viewIndex < 0) { throw Py::IndexError("Index out of range"); + } PyObject* viewer = view->getViewer(viewIndex)->getPyObject(); return Py::asObject(viewer); } @@ -557,13 +589,15 @@ PyCxx_ssize_t AbstractSplitViewPy::sequence_length() Py::Object AbstractSplitViewPy::close(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } AbstractSplitView* view = getSplitViewPtr(); view->close(); - if (view->parentWidget()) + if (view->parentWidget()) { view->parentWidget()->deleteLater(); + } return Py::None(); } @@ -572,10 +606,15 @@ Py::Object AbstractSplitViewPy::close(const Py::Tuple& args) TYPESYSTEM_SOURCE_ABSTRACT(Gui::SplitView3DInventor, Gui::AbstractSplitView) -SplitView3DInventor::SplitView3DInventor(int views, Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags) - : AbstractSplitView(pcDocument,parent, wflags) +SplitView3DInventor::SplitView3DInventor( + int views, + Gui::Document* pcDocument, + QWidget* parent, + Qt::WindowFlags wflags +) + : AbstractSplitView(pcDocument, parent, wflags) { - //anti-aliasing settings + // anti-aliasing settings bool smoothing = false; bool glformat = false; int samples = View3DInventorViewer::getNumSamples(); @@ -590,19 +629,22 @@ SplitView3DInventor::SplitView3DInventor(int views, Gui::Document* pcDocument, Q } // minimal 2 views - while (views < 2) - views ++; + while (views < 2) { + views++; + } QSplitter* mainSplitter = nullptr; // if views < 3 show them as a row if (views <= 3) { mainSplitter = new QSplitter(Qt::Horizontal, this); - for (int i=0; i < views; i++) { - if (glformat) + for (int i = 0; i < views; i++) { + if (glformat) { _viewer.push_back(new View3DInventorViewer(f, mainSplitter)); - else + } + else { _viewer.push_back(new View3DInventorViewer(mainSplitter)); + } } } else { @@ -619,11 +661,13 @@ SplitView3DInventor::SplitView3DInventor(int views, Gui::Document* pcDocument, Q _viewer.push_back(new View3DInventorViewer(topSplitter)); } - for (int i=2;isetOpaqueResize(true); @@ -631,8 +675,9 @@ SplitView3DInventor::SplitView3DInventor(int views, Gui::Document* pcDocument, Q } if (smoothing) { - for (std::vector::size_type i = 0; i != _viewer.size(); i++) + for (std::vector::size_type i = 0; i != _viewer.size(); i++) { _viewer[i]->getSoRenderManager()->getGLRenderAction()->setSmoothing(true); + } } mainSplitter->show(); diff --git a/src/Gui/SplitView3DInventor.h b/src/Gui/SplitView3DInventor.h index 846e3bca37..8854573576 100644 --- a/src/Gui/SplitView3DInventor.h +++ b/src/Gui/SplitView3DInventor.h @@ -30,7 +30,8 @@ #include -namespace Gui { +namespace Gui +{ class View3DInventorViewer; class AbstractSplitViewPy; class View3DSettings; @@ -38,17 +39,21 @@ class View3DSettings; /** The SplitView3DInventor class allows one to create a window with two or more Inventor views. * \author Werner Mayer */ -class GuiExport AbstractSplitView : public MDIView +class GuiExport AbstractSplitView: public MDIView { Q_OBJECT TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - AbstractSplitView(Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags=Qt::WindowFlags()); + AbstractSplitView( + Gui::Document* pcDocument, + QWidget* parent, + Qt::WindowFlags wflags = Qt::WindowFlags() + ); ~AbstractSplitView() override; - const char *getName() const override; + const char* getName() const override; /// Message handler bool onMsg(const char* pMsg, const char** ppReturn) override; @@ -57,12 +62,12 @@ public: void deleteSelf() override; void viewAll() override; - View3DInventorViewer *getViewer(unsigned int) const; + View3DInventorViewer* getViewer(unsigned int) const; void setOverrideCursor(const QCursor&) override; bool containsViewProvider(const ViewProvider*) const override; - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; int getSize(); protected: @@ -71,22 +76,22 @@ protected: protected: std::vector _viewer; - PyObject *_viewerPy; + PyObject* _viewerPy; std::unique_ptr viewSettings; }; -class AbstractSplitViewPy : public Py::PythonExtension +class AbstractSplitViewPy: public Py::PythonExtension { public: using BaseType = Py::PythonExtension; - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods - AbstractSplitViewPy(AbstractSplitView *vi); + AbstractSplitViewPy(AbstractSplitView* vi); ~AbstractSplitViewPy() override; AbstractSplitView* getSplitViewPtr(); Py::Object repr() override; - Py::Object getattr(const char *) override; + Py::Object getattr(const char*) override; Py::Object cast_to_base(const Py::Tuple&); Py::Object fitAll(const Py::Tuple&); @@ -109,16 +114,20 @@ private: /** The SplitView3DInventor class allows one to create a window with two or more Inventor views. * \author Werner Mayer */ -class GuiExport SplitView3DInventor : public AbstractSplitView +class GuiExport SplitView3DInventor: public AbstractSplitView { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - SplitView3DInventor(int views, Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags=Qt::WindowFlags()); + SplitView3DInventor( + int views, + Gui::Document* pcDocument, + QWidget* parent, + Qt::WindowFlags wflags = Qt::WindowFlags() + ); ~SplitView3DInventor() override; }; -} // namespace Gui - -#endif //GUI_SPLITVIEW3DINVENTOR_H +} // namespace Gui +#endif // GUI_SPLITVIEW3DINVENTOR_H diff --git a/src/Gui/StartupProcess.cpp b/src/Gui/StartupProcess.cpp index 5d9974b0f0..4f1e95c44b 100644 --- a/src/Gui/StartupProcess.cpp +++ b/src/Gui/StartupProcess.cpp @@ -24,7 +24,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif #include @@ -67,35 +67,39 @@ void StartupProcess::setupApplication() QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); // Automatic scaling for legacy apps (disable once all parts of GUI are aware of HiDpi) - ParameterGrp::handle hDPI = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/HighDPI"); + ParameterGrp::handle hDPI = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/HighDPI" + ); bool disableDpiScaling = hDPI->GetBool("DisableDpiScaling", false); if (disableDpiScaling) { #ifdef FC_OS_WIN32 - SetProcessDPIAware(); // call before the main event loop + SetProcessDPIAware(); // call before the main event loop #endif -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QApplication::setAttribute(Qt::AA_DisableHighDpiScaling); #endif } else { // Enable automatic scaling based on pixel density of display (added in Qt 5.6) -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #if defined(Q_OS_WIN) - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + QGuiApplication::setHighDpiScaleFactorRoundingPolicy( + Qt::HighDpiScaleFactorRoundingPolicy::PassThrough + ); #endif } -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) - //Enable support for highres images (added in Qt 5.1, but off by default) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + // Enable support for highres images (added in Qt 5.1, but off by default) QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif // Use software rendering for OpenGL - ParameterGrp::handle hOpenGL = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/OpenGL"); + ParameterGrp::handle hOpenGL = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/OpenGL" + ); bool useSoftwareOpenGL = hOpenGL->GetBool("UseSoftwareOpenGL", false); if (useSoftwareOpenGL) { QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL); @@ -135,17 +139,15 @@ void StartupProcess::setStyleSheetPaths() { // setup the search paths for Qt style sheets QStringList qssPaths; - qssPaths << QString::fromUtf8( - (App::Application::getUserAppDataDir() + "Gui/Stylesheets/").c_str()) - << QString::fromUtf8((App::Application::getResourceDir() + "Gui/Stylesheets/").c_str()) - << QLatin1String(":/stylesheets"); + qssPaths << QString::fromUtf8((App::Application::getUserAppDataDir() + "Gui/Stylesheets/").c_str()) + << QString::fromUtf8((App::Application::getResourceDir() + "Gui/Stylesheets/").c_str()) + << QLatin1String(":/stylesheets"); QDir::setSearchPaths(QStringLiteral("qss"), qssPaths); // setup the search paths for Qt overlay style sheets QStringList qssOverlayPaths; - qssOverlayPaths << QString::fromUtf8((App::Application::getUserAppDataDir() - + "Gui/Stylesheets/overlay").c_str()) - << QString::fromUtf8((App::Application::getResourceDir() - + "Gui/Stylesheets/overlay").c_str()); + qssOverlayPaths << QString::fromUtf8( + (App::Application::getUserAppDataDir() + "Gui/Stylesheets/overlay").c_str() + ) << QString::fromUtf8((App::Application::getResourceDir() + "Gui/Stylesheets/overlay").c_str()); QDir::setSearchPaths(QStringLiteral("overlay"), qssOverlayPaths); } @@ -154,8 +156,8 @@ void StartupProcess::setImagePaths() // set search paths for images QStringList imagePaths; imagePaths << QString::fromUtf8((App::Application::getUserAppDataDir() + "Gui/images").c_str()) - << QString::fromUtf8((App::Application::getUserAppDataDir() + "pixmaps").c_str()) - << QLatin1String(":/icons"); + << QString::fromUtf8((App::Application::getUserAppDataDir() + "pixmaps").c_str()) + << QLatin1String(":/icons"); QDir::setSearchPaths(QStringLiteral("images"), imagePaths); } @@ -168,12 +170,12 @@ void StartupProcess::registerEventType() void StartupProcess::setThemePaths() { #if !defined(Q_OS_LINUX) - QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() - << QStringLiteral(":/icons/FreeCAD-default")); + QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() << QStringLiteral(":/icons/FreeCAD-default")); #endif ParameterGrp::handle hTheme = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Bitmaps/Theme"); + "User parameter:BaseApp/Preferences/Bitmaps/Theme" + ); std::string searchpath = hTheme->GetASCII("SearchPath"); if (!searchpath.empty()) { @@ -203,11 +205,10 @@ void StartupProcess::setupFileDialog() // ------------------------------------------------------------------------------------------------ StartupPostProcess::StartupPostProcess(MainWindow* mw, Application& guiApp, QApplication* app) - : mainWindow{mw} - , guiApp{guiApp} + : mainWindow {mw} + , guiApp {guiApp} , qtApp(app) -{ -} +{} void StartupPostProcess::setLoadFromPythonModule(bool value) { @@ -242,15 +243,19 @@ void StartupPostProcess::setWindowTitle() void StartupPostProcess::setProcessMessages() { if (!loadFromPythonModule) { - QObject::connect(qtApp, SIGNAL(messageReceived(const QList &)), - mainWindow, SLOT(processMessages(const QList &))); + QObject::connect( + qtApp, + SIGNAL(messageReceived(const QList&)), + mainWindow, + SLOT(processMessages(const QList&)) + ); } } void StartupPostProcess::setAutoSaving() { ParameterGrp::handle hDocGrp = WindowParameter::getDefaultParameter()->GetGroup("Document"); - int timeout = int(hDocGrp->GetInt("AutoSaveTimeout", 15L)); // 15 min + int timeout = int(hDocGrp->GetInt("AutoSaveTimeout", 15L)); // 15 min if (!hDocGrp->GetBool("AutoSaveEnabled", true)) { timeout = 0; } @@ -266,7 +271,7 @@ void StartupPostProcess::setToolBarIconSize() int size = int(hGrp->GetInt("ToolbarIconSize", 0)); // must not be lower than this if (size >= 16) { // NOLINT - mainWindow->setIconSize(QSize(size,size)); + mainWindow->setIconSize(QSize(size, size)); } } @@ -287,7 +292,8 @@ void StartupPostProcess::setLocale() auto localeFormat = hGrp->GetInt("UseLocaleFormatting", 0); if (localeFormat == 1) { Translator::instance()->setLocale( - hGrp->GetASCII("Language", Translator::instance()->activeLanguage().c_str())); + hGrp->GetASCII("Language", Translator::instance()->activeLanguage().c_str()) + ); } else if (localeFormat == 2) { Translator::instance()->setLocale("C.UTF-8"); @@ -309,12 +315,12 @@ void StartupPostProcess::setQtStyle() if (qtStyle.empty()) { qtStyle = "Fusion"; hGrp->SetASCII("QtStyle", qtStyle); - } else if (qtStyle == "System") { + } + else if (qtStyle == "System") { // Special value to not set a QtStyle explicitly return; } QApplication::setStyle(QString::fromStdString(qtStyle)); - } void StartupPostProcess::checkOpenGL() @@ -340,18 +346,20 @@ void StartupPostProcess::checkOpenGL() // In release mode, issue a warning to users that their version of OpenGL is // potentially going to cause problems if (major < 2) { - auto message = - QObject::tr("This system is running OpenGL %1.%2. " - "FreeCAD requires OpenGL 2.0 or above. " - "Upgrade the graphics driver and/or card as required.") - .arg(major) - .arg(minor) + auto message = QObject::tr( + "This system is running OpenGL %1.%2. " + "FreeCAD requires OpenGL 2.0 or above. " + "Upgrade the graphics driver and/or card as required." + ) + .arg(major) + .arg(minor) + QStringLiteral("\n"); Base::Console().warning(message.toStdString().c_str()); Dialog::DlgCheckableMessageBox::showMessage( QCoreApplication::applicationName() + QStringLiteral(" - ") + QObject::tr("Invalid OpenGL Version"), - message); + message + ); } #endif const char* glVersion = reinterpret_cast(glGetString(GL_VERSION)); @@ -376,8 +384,8 @@ void StartupPostProcess::setBranding() { QString home = QString::fromStdString(App::Application::getHomePath()); - const std::map& cfg = App::Application::Config(); - std::map::const_iterator it; + const std::map& cfg = App::Application::Config(); + std::map::const_iterator it; it = cfg.find("WindowTitle"); if (it != cfg.end()) { QString title = QString::fromUtf8(it->second.c_str()); @@ -438,7 +446,6 @@ void StartupPostProcess::showMainWindow() Base::Console().error("Error in FreeCADGuiInit.py: %s\n", e.what()); mainWindow->stopSplasher(); throw; - } // stop splash screen and set immediately the active window that may be of interest @@ -452,10 +459,9 @@ void StartupPostProcess::activateWorkbench() // Activate the correct workbench std::string start = App::Application::Config()["StartWorkbench"]; Base::Console().log("Init: Activating default workbench %s\n", start.c_str()); - std::string autoload = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") - ->GetASCII("AutoloadModule", start.c_str()); + std::string autoload = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetASCII("AutoloadModule", start.c_str()); if ("$LastModule" == autoload) { start = App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") @@ -492,7 +498,7 @@ void StartupPostProcess::activateWorkbench() mainWindow->loadWindowSettings(); } - //initialize spaceball. + // initialize spaceball. if (auto fcApp = qobject_cast(qtApp)) { fcApp->initSpaceball(mainWindow); } @@ -510,7 +516,8 @@ void StartupPostProcess::activateWorkbench() void StartupPostProcess::setStyleSheet() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/MainWindow"); + "User parameter:BaseApp/Preferences/MainWindow" + ); std::string style = hGrp->GetASCII("StyleSheet"); if (style.empty()) { // check the branding settings @@ -528,10 +535,9 @@ void StartupPostProcess::autoloadModules(const QStringList& wb) { // Now run the background autoload, for workbenches that should be loaded at startup, but not // displayed to the user immediately - std::string autoloadCSV = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") - ->GetASCII("BackgroundAutoloadModules", ""); + std::string autoloadCSV = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General") + ->GetASCII("BackgroundAutoloadModules", ""); // Tokenize the comma-separated list and load the requested workbenches if they exist in this // installation @@ -547,17 +553,22 @@ void StartupPostProcess::autoloadModules(const QStringList& wb) void StartupPostProcess::checkParameters() { if (App::GetApplication().GetSystemParameter().IgnoreSave()) { - Base::Console().warning("System parameter file couldn't be opened.\n" - "Continue with an empty configuration that won't be saved.\n"); + Base::Console().warning( + "System parameter file couldn't be opened.\n" + "Continue with an empty configuration that won't be saved.\n" + ); } if (App::GetApplication().GetUserParameter().IgnoreSave()) { - Base::Console().warning("User parameter file couldn't be opened.\n" - "Continue with an empty configuration that won't be saved.\n"); + Base::Console().warning( + "User parameter file couldn't be opened.\n" + "Continue with an empty configuration that won't be saved.\n" + ); } } -void StartupPostProcess::checkVersionMigration() const { - auto migrator = new Dialog::DlgVersionMigrator (mainWindow); +void StartupPostProcess::checkVersionMigration() const +{ + auto migrator = new Dialog::DlgVersionMigrator(mainWindow); migrator->exec(); migrator->deleteLater(); } diff --git a/src/Gui/StartupProcess.h b/src/Gui/StartupProcess.h index 82408c725b..8ffb3eb226 100644 --- a/src/Gui/StartupProcess.h +++ b/src/Gui/StartupProcess.h @@ -30,7 +30,8 @@ class QApplication; class QMessageBox; -namespace Gui { +namespace Gui +{ class Application; class MainWindow; @@ -86,6 +87,6 @@ private: }; -} +} // namespace Gui -#endif // GUI_STARTUPPROCESS_H +#endif // GUI_STARTUPPROCESS_H diff --git a/src/Gui/StatusBarLabel.cpp b/src/Gui/StatusBarLabel.cpp index 960a5728a7..641d473928 100644 --- a/src/Gui/StatusBarLabel.cpp +++ b/src/Gui/StatusBarLabel.cpp @@ -32,14 +32,16 @@ #include "StatusBarLabel.h" #include -namespace Gui { +namespace Gui +{ -StatusBarLabel::StatusBarLabel(QWidget *parent, const std::string& parameterName) +StatusBarLabel::StatusBarLabel(QWidget* parent, const std::string& parameterName) : QLabel(parent) { if (!parameterName.empty()) { hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/MainWindow"); + "User parameter:BaseApp/Preferences/MainWindow" + ); // set visibility before storing parameterName to avoid saving it immediately setVisible(hGrp->GetBool(parameterName.c_str(), true)); @@ -49,14 +51,14 @@ StatusBarLabel::StatusBarLabel(QWidget *parent, const std::string& parameterName } } -void StatusBarLabel::contextMenuEvent(QContextMenuEvent *event) +void StatusBarLabel::contextMenuEvent(QContextMenuEvent* event) { QMenu menu(this); // Reproduce standard status bar widget menu - if (auto *statusBar = qobject_cast(parentWidget())) { - for (QObject *child : statusBar->children()) { - QWidget *widget = qobject_cast(child); + if (auto* statusBar = qobject_cast(parentWidget())) { + for (QObject* child : statusBar->children()) { + QWidget* widget = qobject_cast(child); if (!widget) { continue; } @@ -65,7 +67,7 @@ void StatusBarLabel::contextMenuEvent(QContextMenuEvent *event) continue; } - QAction *action = menu.addAction(title); + QAction* action = menu.addAction(title); action->setCheckable(true); action->setChecked(widget->isVisible()); QObject::connect(action, &QAction::toggled, widget, &QWidget::setVisible); @@ -73,15 +75,13 @@ void StatusBarLabel::contextMenuEvent(QContextMenuEvent *event) } if (textInteractionFlags() & Qt::TextSelectableByMouse) { - menu.addSeparator(); // ---------- + menu.addSeparator(); // ---------- // Copy + Select All menu.addAction(tr("Copy"), [this]() { QApplication::clipboard()->setText(this->selectedText()); }); - menu.addAction(tr("Select All"), [this]() { - this->setSelection(0, this->text().length()); - }); + menu.addAction(tr("Select All"), [this]() { this->setSelection(0, this->text().length()); }); } menu.exec(event->globalPos()); @@ -98,4 +98,4 @@ void StatusBarLabel::setVisible(bool visible) QLabel::setVisible(visible); } -} // namespace Gui +} // namespace Gui diff --git a/src/Gui/StatusBarLabel.h b/src/Gui/StatusBarLabel.h index 33d0b0e7ca..18524d70a4 100644 --- a/src/Gui/StatusBarLabel.h +++ b/src/Gui/StatusBarLabel.h @@ -46,18 +46,20 @@ namespace Gui * A QLabel subclass that provides a context menu with additional actions * similar to the standard status bar widgets. */ -class GuiExport StatusBarLabel : public QLabel +class GuiExport StatusBarLabel: public QLabel { Q_OBJECT public: - explicit StatusBarLabel(QWidget *parent, const std::string& parameterName = {}); + explicit StatusBarLabel(QWidget* parent, const std::string& parameterName = {}); + protected: - void contextMenuEvent(QContextMenuEvent *event) override; + void contextMenuEvent(QContextMenuEvent* event) override; void setVisible(bool visible) override; + private: ParameterGrp::handle hGrp; std::string parameterName; }; -} // Namespace Gui -#endif //STATUSBARLABEL_H +} // Namespace Gui +#endif // STATUSBARLABEL_H diff --git a/src/Gui/StyleParameters/ParameterManager.cpp b/src/Gui/StyleParameters/ParameterManager.cpp index 27d04f3e77..c1579c895a 100644 --- a/src/Gui/StyleParameters/ParameterManager.cpp +++ b/src/Gui/StyleParameters/ParameterManager.cpp @@ -86,10 +86,10 @@ Numeric Numeric::operator*(const Numeric& rhs) const void Numeric::ensureEqualUnits(const Numeric& rhs) const { if (unit != rhs.unit) { - THROWM(Base::RuntimeError, - fmt::format("Units mismatch left expression is '{}', right expression is '{}'", - unit, - rhs.unit)); + THROWM( + Base::RuntimeError, + fmt::format("Units mismatch left expression is '{}', right expression is '{}'", unit, rhs.unit) + ); } } @@ -112,8 +112,10 @@ ParameterSource::ParameterSource(const Metadata& metadata) : metadata(metadata) {} -InMemoryParameterSource::InMemoryParameterSource(const std::list& parameters, - const Metadata& metadata) +InMemoryParameterSource::InMemoryParameterSource( + const std::list& parameters, + const Metadata& metadata +) : ParameterSource(metadata) { for (const auto& parameter : parameters) { @@ -312,8 +314,10 @@ void ParameterManager::reload() _resolved.clear(); } -std::string ParameterManager::replacePlaceholders(const std::string& expression, - ResolveContext context) const +std::string ParameterManager::replacePlaceholders( + const std::string& expression, + ResolveContext context +) const { static const QRegularExpression regex(QStringLiteral("@(\\w+)")); @@ -387,8 +391,7 @@ std::optional ParameterManager::expression(const std::string& name) return {}; } -std::optional ParameterManager::resolve(const std::string& name, - ResolveContext context) const +std::optional ParameterManager::resolve(const std::string& name, ResolveContext context) const { std::optional maybeParameter = this->parameter(name); diff --git a/src/Gui/StyleParameters/ParameterManager.h b/src/Gui/StyleParameters/ParameterManager.h index fb13994494..ddebc31ede 100644 --- a/src/Gui/StyleParameters/ParameterManager.h +++ b/src/Gui/StyleParameters/ParameterManager.h @@ -40,9 +40,9 @@ // That macro uses inline const because some older compilers to not properly support constexpr // for std::string. It should be changed into static constepxr once we migrate to newer compiler. #define DEFINE_STYLE_PARAMETER(_name_, _defaultValue_) \ - static inline const Gui::StyleParameters::ParameterDefinition _name_ { \ - .name = #_name_, \ - .defaultValue = (_defaultValue_), \ + static inline const Gui::StyleParameters::ParameterDefinition _name_ \ + { \ + .name = #_name_, .defaultValue = (_defaultValue_), \ } namespace Gui::StyleParameters @@ -115,7 +115,7 @@ private: * * As a rule, operations can be only performed over values of the same type. */ -struct Value : std::variant +struct Value: std::variant { using std::variant::variant; @@ -145,7 +145,7 @@ struct Value : std::variant * DEFINE_STYLE_PARAMETER(TextColor, Base::Color(0.5F, 0.2F, 0.8F)); * @endcode */ -template +template struct ParameterDefinition { /// The name of the parameter, must be unique. @@ -160,8 +160,8 @@ struct ParameterDefinition * @brief Represents a named, dynamic expression-based parameter. * * The Parameter structure is used to define reusable named variables in styling or layout systems. - * Each parameter consists of a `name` and a `value` string, where the value is a CSS-like expression - * that supports numbers, units, arithmetic, colors, functions, and parameter references. + * Each parameter consists of a `name` and a `value` string, where the value is a CSS-like + * expression that supports numbers, units, arithmetic, colors, functions, and parameter references. * * ### Naming Convention * Parameter names must be unique and follow **CamelCase**. @@ -295,7 +295,8 @@ public: * * @param[in] parameter The `Parameter` object to define or update in the source. */ - virtual void define([[maybe_unused]] const Parameter& parameter) {} + virtual void define([[maybe_unused]] const Parameter& parameter) + {} /** * @brief Removes a parameter from the source by its name. @@ -305,12 +306,14 @@ public: * * @param[in] name The name of the parameter to remove. */ - virtual void remove([[maybe_unused]] const std::string& name) {} + virtual void remove([[maybe_unused]] const std::string& name) + {} /** * @brief Flushes buffered changes into more persistent storage. */ - virtual void flush() {} + virtual void flush() + {} }; /** @@ -319,7 +322,7 @@ public: * This source is useful for temporary parameter storage or when you need to * define parameters programmatically without persisting them to disk. */ -class GuiExport InMemoryParameterSource : public ParameterSource +class GuiExport InMemoryParameterSource: public ParameterSource { std::map parameters; @@ -339,7 +342,7 @@ public: * FreeCAD's global parameter system. These parameters are typically defined * by the application and are read-only. */ -class GuiExport BuiltInParameterSource : public ParameterSource +class GuiExport BuiltInParameterSource: public ParameterSource { public: explicit BuiltInParameterSource(const Metadata& metadata = {}); @@ -348,10 +351,12 @@ public: std::optional get(const std::string& name) const override; private: - ParameterGrp::handle hGrpThemes = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Themes"); - ParameterGrp::handle hGrpView = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrpThemes = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Themes" + ); + ParameterGrp::handle hGrpView = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); std::map params = { {"ThemeAccentColor1", hGrpThemes}, @@ -368,7 +373,7 @@ private: * in the user's preference file. These parameters can be modified by the * user and persist across application sessions. */ -class GuiExport UserParameterSource : public ParameterSource +class GuiExport UserParameterSource: public ParameterSource { ParameterGrp::handle hGrp; @@ -389,7 +394,7 @@ public: * This class maintains an in-memory map of parameters loaded from a YAML file. * Any changes through define() or remove() will also update the file. */ -class GuiExport YamlParameterSource : public ParameterSource +class GuiExport YamlParameterSource: public ParameterSource { public: /** @@ -502,7 +507,7 @@ public: * @param context Resolution context for handling circular references * @return The resolved value */ - template + template T resolve(const ParameterDefinition& definition, ResolveContext context = {}) const { auto value = resolve(definition.name, std::move(context)); @@ -553,4 +558,4 @@ public: ENABLE_BITMASK_OPERATORS(Gui::StyleParameters::ParameterSourceOption); -#endif // STYLEPARAMETERS_PARAMETERMANAGER_H \ No newline at end of file +#endif // STYLEPARAMETERS_PARAMETERMANAGER_H diff --git a/src/Gui/StyleParameters/Parser.cpp b/src/Gui/StyleParameters/Parser.cpp index aceeed940e..008308601c 100644 --- a/src/Gui/StyleParameters/Parser.cpp +++ b/src/Gui/StyleParameters/Parser.cpp @@ -55,18 +55,17 @@ Value FunctionCall::evaluate(const EvaluationContext& context) const { const auto lightenOrDarken = [this](const EvaluationContext& context) -> Value { if (arguments.size() != 2) { - THROWM(Base::ExpressionError, - fmt::format("Function '{}' expects 2 arguments, got {}", - functionName, - arguments.size())); + THROWM( + Base::ExpressionError, + fmt::format("Function '{}' expects 2 arguments, got {}", functionName, arguments.size()) + ); } auto colorArg = arguments[0]->evaluate(context); auto amountArg = arguments[1]->evaluate(context); if (!std::holds_alternative(colorArg)) { - THROWM(Base::ExpressionError, - fmt::format("'{}' is not supported for colors", functionName)); + THROWM(Base::ExpressionError, fmt::format("'{}' is not supported for colors", functionName)); } auto color = std::get(colorArg).asValue(); @@ -91,10 +90,10 @@ Value FunctionCall::evaluate(const EvaluationContext& context) const const auto blend = [this](const EvaluationContext& context) -> Value { if (arguments.size() != 3) { - THROWM(Base::ExpressionError, - fmt::format("Function '{}' expects 3 arguments, got {}", - functionName, - arguments.size())); + THROWM( + Base::ExpressionError, + fmt::format("Function '{}' expects 3 arguments, got {}", functionName, arguments.size()) + ); } auto firstColorArg = arguments[0]->evaluate(context); @@ -102,13 +101,17 @@ Value FunctionCall::evaluate(const EvaluationContext& context) const auto amountArg = arguments[2]->evaluate(context); if (!std::holds_alternative(firstColorArg)) { - THROWM(Base::ExpressionError, - fmt::format("first argument of '{}' must be color", functionName)); + THROWM( + Base::ExpressionError, + fmt::format("first argument of '{}' must be color", functionName) + ); } if (!std::holds_alternative(secondColorArg)) { - THROWM(Base::ExpressionError, - fmt::format("second argument of '{}' must be color", functionName)); + THROWM( + Base::ExpressionError, + fmt::format("second argument of '{}' must be color", functionName) + ); } auto firstColor = std::get(firstColorArg); @@ -186,8 +189,10 @@ std::unique_ptr Parser::parse() auto expr = parseExpression(); skipWhitespace(); if (pos != input.size()) { - THROWM(Base::ParserError, - fmt::format("Unexpected characters at end of input: {}", input.substr(pos))); + THROWM( + Base::ParserError, + fmt::format("Unexpected characters at end of input: {}", input.substr(pos)) + ); } return expr; } @@ -274,16 +279,16 @@ std::unique_ptr Parser::parseColor() const auto parseHexadecimalColor = [&]() { constexpr int hexadecimalBase = 16; - // Format is #RRGGBB - pos++; - int r = std::stoi(input.substr(pos, 2), nullptr, hexadecimalBase); - pos += 2; - int g = std::stoi(input.substr(pos, 2), nullptr, hexadecimalBase); - pos += 2; - int b = std::stoi(input.substr(pos, 2), nullptr, hexadecimalBase); - pos += 2; + // Format is #RRGGBB + pos++; + int r = std::stoi(input.substr(pos, 2), nullptr, hexadecimalBase); + pos += 2; + int g = std::stoi(input.substr(pos, 2), nullptr, hexadecimalBase); + pos += 2; + int b = std::stoi(input.substr(pos, 2), nullptr, hexadecimalBase); + pos += 2; - return std::make_unique(Base::Color(r / 255.0, g / 255.0, b / 255.0)); + return std::make_unique(Base::Color(r / 255.0, g / 255.0, b / 255.0)); }; const auto parseFunctionStyleColor = [&]() { @@ -293,11 +298,11 @@ std::unique_ptr Parser::parseColor() int r = parseInt(); if (!match(',')) { - THROWM(Base::ParserError, fmt::format("Expected ',' after red, got '{}'", input[pos])); + THROWM(Base::ParserError, fmt::format("Expected ',' after red, got '{}'", input[pos])); } int g = parseInt(); if (!match(',')) { - THROWM(Base::ParserError, fmt::format("Expected ',' after green, got '{}'", input[pos])); + THROWM(Base::ParserError, fmt::format("Expected ',' after green, got '{}'", input[pos])); } int b = parseInt(); int a = 255; // NOLINT(*-magic-numbers) @@ -308,7 +313,10 @@ std::unique_ptr Parser::parseColor() a = parseInt(); } if (!match(')')) { - THROWM(Base::ParserError, fmt::format("Expected ')' after color arguments, got '{}'", input[pos])); + THROWM( + Base::ParserError, + fmt::format("Expected ')' after color arguments, got '{}'", input[pos]) + ); } return std::make_unique(Base::Color(r / 255.0, g / 255.0, b / 255.0, a / 255.0)); }; @@ -323,8 +331,12 @@ std::unique_ptr Parser::parseColor() if (peekString(rgbFunction) || peekString(rgbaFunction)) { return parseFunctionStyleColor(); } - } catch (std::invalid_argument&) { - THROWM(Base::ParserError, "Invalid color format, expected #RRGGBB or rgb(r,g,b) or rgba(r,g,b,a)"); + } + catch (std::invalid_argument&) { + THROWM( + Base::ParserError, + "Invalid color format, expected #RRGGBB or rgb(r,g,b) or rgba(r,g,b,a)" + ); } THROWM(Base::ParserError, "Unknown color format"); @@ -347,8 +359,10 @@ std::unique_ptr Parser::parseParameter() ++pos; } if (start == pos) { - THROWM(Base::ParserError, - fmt::format("Expected parameter name after '@', got '{}'", input[pos])); + THROWM( + Base::ParserError, + fmt::format("Expected parameter name after '@', got '{}'", input[pos]) + ); } return std::make_unique(input.substr(start, pos - start)); } @@ -369,8 +383,7 @@ std::unique_ptr Parser::parseFunctionCall() std::string functionName = input.substr(start, pos - start); if (!match('(')) { - THROWM(Base::ParserError, - fmt::format("Expected '(' after function name, got '{}'", input[pos])); + THROWM(Base::ParserError, fmt::format("Expected '(' after function name, got '{}'", input[pos])); } std::vector> arguments; @@ -380,8 +393,10 @@ std::unique_ptr Parser::parseFunctionCall() } while (match(',')); if (!match(')')) { - THROWM(Base::ParserError, - fmt::format("Expected ')' after function arguments, got '{}'", input[pos])); + THROWM( + Base::ParserError, + fmt::format("Expected ')' after function arguments, got '{}'", input[pos]) + ); } } @@ -448,4 +463,4 @@ void Parser::skipWhitespace() } } -} // namespace Gui::StyleParameters \ No newline at end of file +} // namespace Gui::StyleParameters diff --git a/src/Gui/StyleParameters/Parser.h b/src/Gui/StyleParameters/Parser.h index 8d2ad27ecc..f962ac52f9 100644 --- a/src/Gui/StyleParameters/Parser.h +++ b/src/Gui/StyleParameters/Parser.h @@ -167,4 +167,4 @@ private: } // namespace Gui::StyleParameters -#endif // STYLEPARAMETERS_PARSER_H \ No newline at end of file +#endif // STYLEPARAMETERS_PARSER_H diff --git a/src/Gui/Stylesheets/FreeCAD Dark.qss b/src/Gui/Stylesheets/FreeCAD Dark.qss index 1fe521f19e..60f7897279 100644 --- a/src/Gui/Stylesheets/FreeCAD Dark.qss +++ b/src/Gui/Stylesheets/FreeCAD Dark.qss @@ -1684,7 +1684,7 @@ color: white; background-color: #252525; } -/* Fix for tables inside task panels, see https://github.com/FreeCAD/FreeCAD/issues/22957 +/* Fix for tables inside task panels, see https://github.com/FreeCAD/FreeCAD/issues/22957 Reverted due to regression https://github.com/FreeCAD/FreeCAD/issues/24604 QSint--ActionGroup QFrame[class="content"] QTableView { min-height: 300px; @@ -2892,4 +2892,3 @@ QTreeView::item:!selected:hover#groupsTreeView { background-color: @ThemeAccentColor1; margin-left:-8px; } */ - diff --git a/src/Gui/Stylesheets/FreeCAD Light.qss b/src/Gui/Stylesheets/FreeCAD Light.qss index 7baf85ac9e..d7cf47899c 100644 --- a/src/Gui/Stylesheets/FreeCAD Light.qss +++ b/src/Gui/Stylesheets/FreeCAD Light.qss @@ -1682,7 +1682,7 @@ color: black; background-color: #f0f0f0; } -/* Fix for tables inside task panels, see https://github.com/FreeCAD/FreeCAD/issues/22957 +/* Fix for tables inside task panels, see https://github.com/FreeCAD/FreeCAD/issues/22957 Reverted due to regression https://github.com/FreeCAD/FreeCAD/issues/24604 QSint--ActionGroup QFrame[class="content"] QTableView { min-height: 300px; diff --git a/src/Gui/Stylesheets/FreeCAD.qss b/src/Gui/Stylesheets/FreeCAD.qss index 94d81c7fa3..451907f19b 100644 --- a/src/Gui/Stylesheets/FreeCAD.qss +++ b/src/Gui/Stylesheets/FreeCAD.qss @@ -1572,7 +1572,7 @@ QSint--ActionGroup QFrame[class="content"] QTableView { background-color: @PrimaryColor; } -/* Fix for tables inside task panels, see https://github.com/FreeCAD/FreeCAD/issues/22957 +/* Fix for tables inside task panels, see https://github.com/FreeCAD/FreeCAD/issues/22957 Reverted due to regression https://github.com/FreeCAD/FreeCAD/issues/24604 QSint--ActionGroup QFrame[class="content"] QTableView { min-height: 300px; diff --git a/src/Gui/Stylesheets/overlay/Dark Theme + Dark Background.qss b/src/Gui/Stylesheets/overlay/Dark Theme + Dark Background.qss index 21c8f555f4..cb788eda74 100644 --- a/src/Gui/Stylesheets/overlay/Dark Theme + Dark Background.qss +++ b/src/Gui/Stylesheets/overlay/Dark Theme + Dark Background.qss @@ -125,4 +125,3 @@ Gui--OverlayToolButton[objectName="OBTN AutoMode"] { Gui--OverlayToolButton[objectName="OBTN AutoMode"]:hover { image: url(qss:images_classic/mode-white.png) ; } - diff --git a/src/Gui/Stylesheets/overlay/Light Theme + Dark Background.qss b/src/Gui/Stylesheets/overlay/Light Theme + Dark Background.qss index 6e1ee866c6..f713e0d809 100644 --- a/src/Gui/Stylesheets/overlay/Light Theme + Dark Background.qss +++ b/src/Gui/Stylesheets/overlay/Light Theme + Dark Background.qss @@ -186,5 +186,3 @@ QTreeView::branch:has-children:!has-siblings:closed { border-image: none; image: url(qss:images_classic/Arrow-right-white.png); } - - diff --git a/src/Gui/Stylesheets/overlay/icons/mode.svg b/src/Gui/Stylesheets/overlay/icons/mode.svg index 1853f1670d..8a62490e54 100644 --- a/src/Gui/Stylesheets/overlay/icons/mode.svg +++ b/src/Gui/Stylesheets/overlay/icons/mode.svg @@ -427,4 +427,4 @@ style="fill:#000000;fill-opacity:0.50196081;stroke:none" d="m 5.3088424,0.99999985 c -0.1655795,0 -0.2988797,0.13330005 -0.2988797,0.29887945 l 0,0.7596513 C 4.6233539,2.1545047 4.2512452,2.3089734 3.901619,2.5193031 L 3.3661272,1.9838109 c -0.1170822,-0.1170822 -0.3063302,-0.1170822 -0.4234123,0 L 1.9713574,2.9551681 c -0.117082,0.1170825 -0.117082,0.30633 0,0.4234126 L 2.5068493,3.9140729 C 2.298166,4.2626775 2.1534641,4.6390057 2.0585306,5.022416 l -0.7596513,0 C 1.1333002,5.022416 1,5.155716 1,5.3212942 L 1,6.6911576 C 1,6.8567371 1.1333002,6.990037 1.2988793,6.990037 l 0.747198,0 c 0.095958,0.3869534 0.250266,0.7584235 0.460772,1.1083435 L 1.9713574,8.6338727 c -0.117082,0.1170816 -0.117082,0.3063301 0,0.4234133 l 0.9713575,0.971357 c 0.1170821,0.117082 0.3063301,0.117082 0.4234123,0 L 3.901619,9.49315 c 0.3511539,0.211788 0.721667,0.35231 1.1083437,0.448319 l 0,0.759652 C 5.0099627,10.8667 5.1432629,11 5.3088424,11 l 1.3698634,0 C 6.844284,11 6.977584,10.8667 6.977584,10.701121 l 0,-0.759652 C 7.3650872,9.845969 7.7354543,9.703417 8.0859277,9.49315 L 8.62142,10.028643 c 0.1170825,0.117082 0.30633,0.117082 0.4234125,0 L 10.01619,9.057286 c 0.117082,-0.1170832 0.117082,-0.3063317 0,-0.4234133 L 9.4806975,8.0983805 C 9.6914638,7.7490936 9.8452748,7.374642 9.9414697,6.9900373 l 0.7596523,0 C 10.8667,6.990037 11,6.8567371 11,6.6911576 L 11,5.3212954 C 11,5.155716 10.8667,5.022416 10.701122,5.022416 l -0.7596523,0 C 9.8460744,4.6381401 9.6890735,4.2618923 9.4806975,3.9140729 L 10.01619,3.3785807 c 0.117082,-0.1170826 0.117082,-0.3063301 0,-0.4234126 L 9.0448325,1.9838109 c -0.1170825,-0.1170822 -0.30633,-0.1170822 -0.4234125,0 L 8.0859277,2.5193031 C 7.7359781,2.3092543 7.3626909,2.1538256 6.977584,2.0585306 l 0,-0.7596513 c 0,-0.1655794 -0.1333,-0.29887945 -0.2988782,-0.29887945 l -1.3698634,0 z M 5.9439602,4.1133251 C 6.428224,4.1004688 6.9220833,4.2642341 7.3013702,4.62391 8.0599431,5.343262 8.0954412,6.5427967 7.37609,7.3013699 6.6585136,8.0580702 5.4578324,8.091019 4.6986301,7.3760895 3.9400574,6.6567376 3.9045588,5.4572029 4.6239105,4.6986298 4.9835867,4.3193435 5.4596967,4.1261769 5.9439602,4.1133253 Z" id="rect3381-0" - inkscape:connector-curvature="0" /> \ No newline at end of file + inkscape:connector-curvature="0" /> diff --git a/src/Gui/SyntaxHighlighter.cpp b/src/Gui/SyntaxHighlighter.cpp index 7b37f4cac9..d0c25aa259 100644 --- a/src/Gui/SyntaxHighlighter.cpp +++ b/src/Gui/SyntaxHighlighter.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include @@ -30,7 +29,8 @@ using namespace Gui; -namespace Gui { +namespace Gui +{ class SyntaxHighlighterP { public: @@ -49,10 +49,10 @@ public: cError.setRgb(255, 0, 0); } - QColor cNormalText, cComment, cBlockcomment, cLiteral, cNumber, - cOperator, cKeyword, cClassName, cDefineName, cOutput, cError; + QColor cNormalText, cComment, cBlockcomment, cLiteral, cNumber, cOperator, cKeyword, cClassName, + cDefineName, cOutput, cError; }; -} // namespace Gui +} // namespace Gui /** * Constructs a syntax highlighter. @@ -77,89 +77,126 @@ void SyntaxHighlighter::setColor(const QString& type, const QColor& col) { // Rehighlighting is very expensive, thus avoid it if this color is already set QColor old = color(type); - if (!old.isValid()) - return; // no such type - if (old == col) + if (!old.isValid()) { + return; // no such type + } + if (old == col) { return; - if (type == QLatin1String("Text")) + } + if (type == QLatin1String("Text")) { d->cNormalText = col; - else if (type == QLatin1String("Comment")) + } + else if (type == QLatin1String("Comment")) { d->cComment = col; - else if (type == QLatin1String("Block comment")) + } + else if (type == QLatin1String("Block comment")) { d->cBlockcomment = col; - else if (type == QLatin1String("Number")) + } + else if (type == QLatin1String("Number")) { d->cNumber = col; - else if (type == QLatin1String("String")) + } + else if (type == QLatin1String("String")) { d->cLiteral = col; - else if (type == QLatin1String("Keyword")) + } + else if (type == QLatin1String("Keyword")) { d->cKeyword = col; - else if (type == QLatin1String("Class name")) + } + else if (type == QLatin1String("Class name")) { d->cClassName = col; - else if (type == QLatin1String("Define name")) + } + else if (type == QLatin1String("Define name")) { d->cDefineName = col; - else if (type == QLatin1String("Operator")) + } + else if (type == QLatin1String("Operator")) { d->cOperator = col; - else if (type == QLatin1String("Python output")) + } + else if (type == QLatin1String("Python output")) { d->cOutput = col; - else if (type == QLatin1String("Python error")) + } + else if (type == QLatin1String("Python error")) { d->cError = col; + } colorChanged(type, col); } QColor SyntaxHighlighter::color(const QString& type) { - if (type == QLatin1String("Text")) + if (type == QLatin1String("Text")) { return d->cNormalText; - else if (type == QLatin1String("Comment")) + } + else if (type == QLatin1String("Comment")) { return d->cComment; - else if (type == QLatin1String("Block comment")) + } + else if (type == QLatin1String("Block comment")) { return d->cBlockcomment; - else if (type == QLatin1String("Number")) + } + else if (type == QLatin1String("Number")) { return d->cNumber; - else if (type == QLatin1String("String")) + } + else if (type == QLatin1String("String")) { return d->cLiteral; - else if (type == QLatin1String("Keyword")) + } + else if (type == QLatin1String("Keyword")) { return d->cKeyword; - else if (type == QLatin1String("Class name")) + } + else if (type == QLatin1String("Class name")) { return d->cClassName; - else if (type == QLatin1String("Define name")) + } + else if (type == QLatin1String("Define name")) { return d->cDefineName; - else if (type == QLatin1String("Operator")) + } + else if (type == QLatin1String("Operator")) { return d->cOperator; - else if (type == QLatin1String("Python output")) + } + else if (type == QLatin1String("Python output")) { return d->cOutput; - else if (type == QLatin1String("Python error")) + } + else if (type == QLatin1String("Python error")) { return d->cError; - else - return {}; // not found + } + else { + return {}; // not found + } } QColor SyntaxHighlighter::colorByType(SyntaxHighlighter::TColor type) { - if (type == SyntaxHighlighter::Text) + if (type == SyntaxHighlighter::Text) { return d->cNormalText; - else if (type == SyntaxHighlighter::Comment) + } + else if (type == SyntaxHighlighter::Comment) { return d->cComment; - else if (type == SyntaxHighlighter::BlockComment) + } + else if (type == SyntaxHighlighter::BlockComment) { return d->cBlockcomment; - else if (type == SyntaxHighlighter::Number) + } + else if (type == SyntaxHighlighter::Number) { return d->cNumber; - else if (type == SyntaxHighlighter::String) + } + else if (type == SyntaxHighlighter::String) { return d->cLiteral; - else if (type == SyntaxHighlighter::Keyword) + } + else if (type == SyntaxHighlighter::Keyword) { return d->cKeyword; - else if (type == SyntaxHighlighter::Classname) + } + else if (type == SyntaxHighlighter::Classname) { return d->cClassName; - else if (type == SyntaxHighlighter::Defname) + } + else if (type == SyntaxHighlighter::Defname) { return d->cDefineName; - else if (type == SyntaxHighlighter::Operator) + } + else if (type == SyntaxHighlighter::Operator) { return d->cOperator; - else if (type == SyntaxHighlighter::Output) + } + else if (type == SyntaxHighlighter::Output) { return d->cOutput; - else if (type == SyntaxHighlighter::Error) + } + else if (type == SyntaxHighlighter::Error) { return d->cError; - else - return {}; // not found + } + else { + return {}; // not found + } } void SyntaxHighlighter::colorChanged(const QString& type, const QColor& col) diff --git a/src/Gui/SyntaxHighlighter.h b/src/Gui/SyntaxHighlighter.h index 8d208a4b89..17fb728d93 100644 --- a/src/Gui/SyntaxHighlighter.h +++ b/src/Gui/SyntaxHighlighter.h @@ -27,7 +27,8 @@ #include #include -namespace Gui { +namespace Gui +{ class SyntaxHighlighterP; class TextEditor; @@ -35,7 +36,7 @@ class TextEditor; * Abstract Syntax highlighter. * @author Werner Mayer */ -class GuiExport SyntaxHighlighter : public QSyntaxHighlighter +class GuiExport SyntaxHighlighter: public QSyntaxHighlighter { public: SyntaxHighlighter(QObject* parent); @@ -52,8 +53,17 @@ protected: protected: enum TColor { - Text = 0, Comment = 1, BlockComment = 2, Number = 3, String = 4, Keyword = 5, - Classname = 6, Defname = 7, Operator = 8, Output = 9, Error = 10 + Text = 0, + Comment = 1, + BlockComment = 2, + Number = 3, + String = 4, + Keyword = 5, + Classname = 6, + Defname = 7, + Operator = 8, + Output = 9, + Error = 10 }; QColor colorByType(TColor type); @@ -63,6 +73,6 @@ private: SyntaxHighlighterP* d; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_SYNTAXHIGHLIGHTER_H +#endif // GUI_SYNTAXHIGHLIGHTER_H diff --git a/src/Gui/TaskDlgRelocation.cpp b/src/Gui/TaskDlgRelocation.cpp index c72260dc43..e4a0e68bd8 100644 --- a/src/Gui/TaskDlgRelocation.cpp +++ b/src/Gui/TaskDlgRelocation.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include "Dialogs/ui_DlgLocationAngle.h" #include "Dialogs/ui_DlgLocationPos.h" @@ -38,8 +37,8 @@ using namespace Gui; /* TRANSLATOR Gui::TaskBoxPosition */ -TaskBoxPosition::TaskBoxPosition(QWidget *parent) - : TaskBox(Gui::BitmapFactory().pixmap("Robot_CreateRobot"),tr("Position"),true, parent) +TaskBoxPosition::TaskBoxPosition(QWidget* parent) + : TaskBox(Gui::BitmapFactory().pixmap("Robot_CreateRobot"), tr("Position"), true, parent) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -63,8 +62,8 @@ TaskBoxPosition::~TaskBoxPosition() /* TRANSLATOR Gui::TaskBoxAngle */ -TaskBoxAngle::TaskBoxAngle(QWidget *parent) - : TaskBox(Gui::BitmapFactory().pixmap("Robot_CreateRobot"),tr("Angle"),true, parent) +TaskBoxAngle::TaskBoxAngle(QWidget* parent) + : TaskBox(Gui::BitmapFactory().pixmap("Robot_CreateRobot"), tr("Angle"), true, parent) { // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -90,8 +89,7 @@ TaskBoxAngle::~TaskBoxAngle() TaskDlgRelocation::TaskDlgRelocation() : TaskDialog() -{ -} +{} TaskDlgRelocation::~TaskDlgRelocation() = default; @@ -99,13 +97,10 @@ TaskDlgRelocation::~TaskDlgRelocation() = default; void TaskDlgRelocation::open() -{ -} +{} void TaskDlgRelocation::clicked(int) -{ - -} +{} bool TaskDlgRelocation::accept() { @@ -118,9 +113,7 @@ bool TaskDlgRelocation::reject() } void TaskDlgRelocation::helpRequested() -{ - -} +{} #include "moc_TaskDlgRelocation.cpp" diff --git a/src/Gui/TaskDlgRelocation.h b/src/Gui/TaskDlgRelocation.h index b9bd164559..bbd712eeef 100644 --- a/src/Gui/TaskDlgRelocation.h +++ b/src/Gui/TaskDlgRelocation.h @@ -32,39 +32,38 @@ class Ui_Position; class Ui_Angle; -namespace Gui { +namespace Gui +{ -class TaskBoxPosition : public Gui::TaskView::TaskBox +class TaskBoxPosition: public Gui::TaskView::TaskBox { Q_OBJECT public: - explicit TaskBoxPosition(QWidget *parent = nullptr); + explicit TaskBoxPosition(QWidget* parent = nullptr); ~TaskBoxPosition() override; private Q_SLOTS: protected: - private: QWidget* proxy; Ui_Position* ui; }; -class TaskBoxAngle : public Gui::TaskView::TaskBox +class TaskBoxAngle: public Gui::TaskView::TaskBox { Q_OBJECT public: - explicit TaskBoxAngle(QWidget *parent = nullptr); + explicit TaskBoxAngle(QWidget* parent = nullptr); ~TaskBoxAngle() override; private Q_SLOTS: protected: - private: QWidget* proxy; Ui_Angle* ui; @@ -72,7 +71,7 @@ private: /// -class GuiExport TaskDlgRelocation : public Gui::TaskView::TaskDialog +class GuiExport TaskDlgRelocation: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -94,14 +93,14 @@ public: /// returns for Close and Help button QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } protected: - }; +} // namespace Gui -} //namespace Gui - -#endif // ROBOTGUI_TASKDLGSIMULATE_H +#endif // ROBOTGUI_TASKDLGSIMULATE_H diff --git a/src/Gui/TaskElementColors.cpp b/src/Gui/TaskElementColors.cpp index c8e7bc3b65..8b1601f799 100644 --- a/src/Gui/TaskElementColors.cpp +++ b/src/Gui/TaskElementColors.cpp @@ -21,7 +21,6 @@ ****************************************************************************/ - #include #include #include @@ -152,10 +151,11 @@ public: const char* marker = ViewProvider::hasHiddenMarker(sub); if (marker) { auto icon = BitmapFactory().pixmap("Invisible"); - auto item = - new QListWidgetItem(icon, - QString::fromLatin1(std::string(sub, marker - sub).c_str()), - ui->elementList); + auto item = new QListWidgetItem( + icon, + QString::fromLatin1(std::string(sub, marker - sub).c_str()), + ui->elementList + ); item->setData(Qt::UserRole, QColor()); item->setData(Qt::UserRole + 1, QString::fromLatin1(sub)); elements.emplace(sub, item); @@ -177,7 +177,8 @@ public: auto item = new QListWidgetItem( QIcon(px), QString::fromLatin1(Data::oldElementName(v.first.c_str()).c_str()), - ui->elementList); + ui->elementList + ); item->setData(Qt::UserRole, c); item->setData(Qt::UserRole + 1, QString::fromLatin1(v.first.c_str())); if (push) { @@ -287,7 +288,8 @@ public: && boost::starts_with(msg.pSubName, editSub)) { const auto items = ui->elementList->findItems( QString::fromLatin1(msg.pSubName - editSub.size()), - Qt::MatchExactly); + Qt::MatchExactly + ); for (auto item : items) { item->setSelected(msg.Type == SelectionChanges::AddSelection); } @@ -306,9 +308,11 @@ public: } busy = true; std::map sels; - for (auto& sel : Selection().getSelectionEx(editDoc.c_str(), - App::DocumentObject::getClassTypeId(), - ResolveMode::NoResolve)) { + for (auto& sel : Selection().getSelectionEx( + editDoc.c_str(), + App::DocumentObject::getClassTypeId(), + ResolveMode::NoResolve + )) { if (sel.getFeatName() != editObj) { continue; } @@ -327,17 +331,13 @@ public: } auto& v = sels[name]; if (!v) { - Selection().addSelection(editDoc.c_str(), - editObj.c_str(), - (editSub + name).c_str()); + Selection().addSelection(editDoc.c_str(), editObj.c_str(), (editSub + name).c_str()); } v = 2; } for (auto& v : sels) { if (v.second != 2) { - Selection().rmvSelection(editDoc.c_str(), - editObj.c_str(), - (editSub + v.first).c_str()); + Selection().rmvSelection(editDoc.c_str(), editObj.c_str(), (editSub + v.first).c_str()); } } busy = false; @@ -359,8 +359,9 @@ ElementColors::ElementColors(ViewProviderDocumentObject* vp, bool noHide) d->ui->hideSelection->setVisible(false); } - ParameterGrp::handle hPart = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); d->ui->recompute->setChecked(hPart->GetBool("ColorRecompute", true)); d->ui->onTop->setChecked(hPart->GetBool("ColorOnTop", true)); if (d->ui->onTop->isChecked()) { @@ -416,15 +417,17 @@ void ElementColors::setupConnections() void ElementColors::onRecomputeClicked(bool checked) { - ParameterGrp::handle hPart = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); hPart->SetBool("ColorRecompute", checked); } void ElementColors::onTopClicked(bool checked) { - ParameterGrp::handle hPart = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); hPart->SetBool("ColorOnTop", checked); d->vpParent->OnTopWhenSelected.setValue(checked ? 3 : d->onTopMode); } @@ -458,9 +461,11 @@ void ElementColors::onBoxSelectClicked() void ElementColors::onHideSelectionClicked() { - auto sels = Selection().getSelectionEx(d->editDoc.c_str(), - App::DocumentObject::getClassTypeId(), - ResolveMode::NoResolve); + auto sels = Selection().getSelectionEx( + d->editDoc.c_str(), + App::DocumentObject::getClassTypeId(), + ResolveMode::NoResolve + ); for (auto& sel : sels) { if (d->editObj != sel.getFeatName()) { continue; @@ -482,9 +487,11 @@ void ElementColors::onHideSelectionClicked() void ElementColors::onAddSelectionClicked() { - auto sels = Selection().getSelectionEx(d->editDoc.c_str(), - App::DocumentObject::getClassTypeId(), - ResolveMode::NoResolve); + auto sels = Selection().getSelectionEx( + d->editDoc.c_str(), + App::DocumentObject::getClassTypeId(), + ResolveMode::NoResolve + ); d->items.clear(); if (sels.empty()) { d->addItem(-1, "Face", true); @@ -580,15 +587,16 @@ void ElementColors::onElementListItemEntered(QListWidgetItem* item) name.resize(name.size() - ViewProvider::hiddenMarker().size()); } - Selection().setPreselect(d->editDoc.c_str(), - d->editObj.c_str(), - (d->editSub + name).c_str(), - 0, - 0, - 0, - d->ui->onTop->isChecked() - ? Gui::SelectionChanges::MsgSource::TreeView - : Gui::SelectionChanges::MsgSource::Internal); + Selection().setPreselect( + d->editDoc.c_str(), + d->editObj.c_str(), + (d->editSub + name).c_str(), + 0, + 0, + 0, + d->ui->onTop->isChecked() ? Gui::SelectionChanges::MsgSource::TreeView + : Gui::SelectionChanges::MsgSource::Internal + ); } void ElementColors::onElementListItemSelectionChanged() @@ -635,4 +643,3 @@ bool TaskElementColors::reject() } #include "moc_TaskElementColors.cpp" - diff --git a/src/Gui/TaskElementColors.h b/src/Gui/TaskElementColors.h index 3abbe755d5..3cad829145 100644 --- a/src/Gui/TaskElementColors.h +++ b/src/Gui/TaskElementColors.h @@ -28,17 +28,18 @@ #include "TaskView/TaskView.h" -namespace Gui { +namespace Gui +{ class Document; class ViewProvider; class ViewProviderDocumentObject; -class GuiExport ElementColors : public QWidget, public SelectionObserver +class GuiExport ElementColors: public QWidget, public SelectionObserver { Q_OBJECT public: - explicit ElementColors(ViewProviderDocumentObject* vp, bool noHide=false); + explicit ElementColors(ViewProviderDocumentObject* vp, bool noHide = false); ~ElementColors() override; bool accept(); @@ -49,9 +50,9 @@ private: void onRemoveSelectionClicked(); void onAddSelectionClicked(); void onRemoveAllClicked(); - void onElementListItemDoubleClicked(QListWidgetItem *item); + void onElementListItemDoubleClicked(QListWidgetItem* item); void onElementListItemSelectionChanged(); - void onElementListItemEntered(QListWidgetItem *item); + void onElementListItemEntered(QListWidgetItem* item); void onRecomputeClicked(bool checked); void onTopClicked(bool checked); void onHideSelectionClicked(); @@ -59,21 +60,22 @@ private: protected: void onSelectionChanged(const SelectionChanges& msg) override; - void changeEvent(QEvent *e) override; - void leaveEvent(QEvent *) override; + void changeEvent(QEvent* e) override; + void leaveEvent(QEvent*) override; void slotDeleteDocument(const Document&); void slotDeleteObject(const ViewProvider&); + private: class Private; - Private *d; + Private* d; }; -class GuiExport TaskElementColors : public TaskView::TaskDialog +class GuiExport TaskElementColors: public TaskView::TaskDialog { Q_OBJECT public: - explicit TaskElementColors(ViewProviderDocumentObject* vp, bool noHide=false); + explicit TaskElementColors(ViewProviderDocumentObject* vp, bool noHide = false); ~TaskElementColors() override; public: @@ -83,12 +85,14 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } private: ElementColors* widget; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_TASKELEMENTCOLORS_H +#endif // GUI_TASKELEMENTCOLORS_H diff --git a/src/Gui/TaskTransform.cpp b/src/Gui/TaskTransform.cpp index 3d60702d56..ceec188946 100644 --- a/src/Gui/TaskTransform.cpp +++ b/src/Gui/TaskTransform.cpp @@ -77,11 +77,13 @@ void alignGridLayoutColumns(const std::list& layouts, unsigned col } // namespace -TaskTransform::TaskTransform(Gui::ViewProviderDragger* vp, - Gui::SoTransformDragger* dragger, - QWidget* parent, - App::SubObjectPlacementProvider* subObjectPlacementProvider, - App::CenterOfMassProvider* centerOfMassProvider) +TaskTransform::TaskTransform( + Gui::ViewProviderDragger* vp, + Gui::SoTransformDragger* dragger, + QWidget* parent, + App::SubObjectPlacementProvider* subObjectPlacementProvider, + App::CenterOfMassProvider* centerOfMassProvider +) : TaskBox(Gui::BitmapFactory().pixmap("Std_TransformManip.svg"), tr("Transform"), false, parent) , vp(vp) , subObjectPlacementProvider(subObjectPlacementProvider) @@ -99,7 +101,8 @@ TaskTransform::TaskTransform(Gui::ViewProviderDragger* vp, referencePlacement = vp->getObjectPlacement(); referenceRotation = referencePlacement.getRotation(); - globalOrigin = vp->getObjectPlacement() * App::GeoFeature::getGlobalPlacement(vp->getObject()).inverse(); + globalOrigin = vp->getObjectPlacement() + * App::GeoFeature::getGlobalPlacement(vp->getObject()).inverse(); setupGui(); } @@ -117,13 +120,13 @@ TaskTransform::~TaskTransform() savePreferences(); } -void TaskTransform::dragStartCallback([[maybe_unused]] void* data, - [[maybe_unused]] SoDragger* dragger) +void TaskTransform::dragStartCallback([[maybe_unused]] void* data, [[maybe_unused]] SoDragger* dragger) { // This is called when a manipulator is about to manipulating if (firstDrag) { Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Transform")); + QT_TRANSLATE_NOOP("Command", "Transform") + ); firstDrag = false; } } @@ -165,12 +168,16 @@ void TaskTransform::loadPlacementModeItems() const { ui->placementComboBox->clear(); - ui->placementComboBox->addItem(tr("Object origin"), - QVariant::fromValue(PlacementMode::ObjectOrigin)); + ui->placementComboBox->addItem( + tr("Object origin"), + QVariant::fromValue(PlacementMode::ObjectOrigin) + ); if (centerOfMassProvider->ofDocumentObject(vp->getObject()).has_value()) { - ui->placementComboBox->addItem(tr("Center of mass / centroid"), - QVariant::fromValue(PlacementMode::Centroid)); + ui->placementComboBox->addItem( + tr("Center of mass / centroid"), + QVariant::fromValue(PlacementMode::Centroid) + ); } if (subObjectPlacementProvider) { @@ -197,52 +204,54 @@ void TaskTransform::setupGui() ui->referencePickerWidget->hide(); ui->alignRotationCheckBox->hide(); - for (auto positionSpinBox : {ui->translationIncrementSpinBox, - ui->xPositionSpinBox, - ui->yPositionSpinBox, - ui->zPositionSpinBox}) { + for (auto positionSpinBox : + {ui->translationIncrementSpinBox, + ui->xPositionSpinBox, + ui->yPositionSpinBox, + ui->zPositionSpinBox}) { positionSpinBox->setUnit(Base::Unit::Length); } - for (auto rotationSpinBox : {ui->rotationIncrementSpinBox, - ui->xRotationSpinBox, - ui->yRotationSpinBox, - ui->zRotationSpinBox}) { + for (auto rotationSpinBox : + {ui->rotationIncrementSpinBox, + ui->xRotationSpinBox, + ui->yRotationSpinBox, + ui->zRotationSpinBox}) { rotationSpinBox->setUnit(Base::Unit::Angle); } - connect(ui->translationIncrementSpinBox, - qOverload(&QuantitySpinBox::valueChanged), - this, - [this](double) { - updateIncrements(); - }); - connect(ui->rotationIncrementSpinBox, - qOverload(&QuantitySpinBox::valueChanged), - this, - [this](double) { - updateIncrements(); - }); - connect(ui->positionModeComboBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskTransform::onCoordinateSystemChange); - connect(ui->placementComboBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskTransform::onPlacementModeChange); - connect(ui->pickTransformOriginButton, - &QPushButton::clicked, - this, - &TaskTransform::onPickTransformOrigin); - connect(ui->alignToOtherObjectButton, - &QPushButton::clicked, - this, - &TaskTransform::onAlignToOtherObject); - connect(ui->moveOptionsButton, - &QPushButton::toggled, - ui->frameMoveOptions, - &QWidget::setVisible); + connect( + ui->translationIncrementSpinBox, + qOverload(&QuantitySpinBox::valueChanged), + this, + [this](double) { updateIncrements(); } + ); + connect( + ui->rotationIncrementSpinBox, + qOverload(&QuantitySpinBox::valueChanged), + this, + [this](double) { updateIncrements(); } + ); + connect( + ui->positionModeComboBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskTransform::onCoordinateSystemChange + ); + connect( + ui->placementComboBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskTransform::onPlacementModeChange + ); + connect( + ui->pickTransformOriginButton, + &QPushButton::clicked, + this, + &TaskTransform::onPickTransformOrigin + ); + connect(ui->alignToOtherObjectButton, &QPushButton::clicked, this, &TaskTransform::onAlignToOtherObject); + connect(ui->moveOptionsButton, &QPushButton::toggled, ui->frameMoveOptions, &QWidget::setVisible); connect(ui->translateCheckbox, &QCheckBox::toggled, this, [this](bool translateChecked) { ui->matchXcheckbox->setEnabled(translateChecked); ui->matchYcheckbox->setEnabled(translateChecked); @@ -256,35 +265,29 @@ void TaskTransform::setupGui() connect(ui->flipPartButton, &QPushButton::clicked, this, &TaskTransform::onFlip); - connect(ui->alignRotationCheckBox, - &QCheckBox::clicked, + connect(ui->alignRotationCheckBox, &QCheckBox::clicked, this, &TaskTransform::onAlignRotationChanged); + + for (auto positionSpinBox : {ui->xPositionSpinBox, ui->yPositionSpinBox, ui->zPositionSpinBox}) { + connect(positionSpinBox, qOverload(&QuantitySpinBox::valueChanged), this, [this](double) { + onPositionChange(); + }); + } + + for (auto rotationSpinBox : {ui->xRotationSpinBox, ui->yRotationSpinBox, ui->zRotationSpinBox}) { + connect( + rotationSpinBox, + qOverload(&QuantitySpinBox::valueChanged), this, - &TaskTransform::onAlignRotationChanged); - - for (auto positionSpinBox : - {ui->xPositionSpinBox, ui->yPositionSpinBox, ui->zPositionSpinBox}) { - connect(positionSpinBox, - qOverload(&QuantitySpinBox::valueChanged), - this, - [this](double) { - onPositionChange(); - }); + [this, rotationSpinBox](double) { onRotationChange(rotationSpinBox); } + ); } - for (auto rotationSpinBox : - {ui->xRotationSpinBox, ui->yRotationSpinBox, ui->zRotationSpinBox}) { - connect(rotationSpinBox, - qOverload(&QuantitySpinBox::valueChanged), - this, - [this,rotationSpinBox](double) { - onRotationChange(rotationSpinBox); - }); - } - - alignGridLayoutColumns({ui->absolutePositionLayout, - ui->absoluteRotationLayout, - ui->transformOriginLayout, - ui->referencePickerLayout}); + alignGridLayoutColumns( + {ui->absolutePositionLayout, + ui->absoluteRotationLayout, + ui->transformOriginLayout, + ui->referencePickerLayout} + ); loadPreferences(); @@ -323,7 +326,8 @@ void TaskTransform::updatePositionAndRotationUi() const auto setPositionValues = [&](const Base::Vector3d& vec, auto* x, auto* y, auto* z) { [[maybe_unused]] - auto blockers = {QSignalBlocker(x), QSignalBlocker(y), QSignalBlocker(z)}; + auto blockers + = {QSignalBlocker(x), QSignalBlocker(y), QSignalBlocker(z)}; x->setValue(fixNegativeZero(vec.x)); y->setValue(fixNegativeZero(vec.y)); @@ -332,7 +336,8 @@ void TaskTransform::updatePositionAndRotationUi() const auto setRotationValues = [&](const Base::Rotation& rot, auto* x, auto* y, auto* z) { [[maybe_unused]] - auto blockers = {QSignalBlocker(x), QSignalBlocker(y), QSignalBlocker(z)}; + auto blockers + = {QSignalBlocker(x), QSignalBlocker(y), QSignalBlocker(z)}; double alpha, beta, gamma; rot.getEulerAngles(eulerSequence(), alpha, beta, gamma); @@ -342,17 +347,20 @@ void TaskTransform::updatePositionAndRotationUi() const z->setValue(fixNegativeZero(gamma)); }; - setPositionValues(uvwPlacement.getPosition(), - ui->xPositionSpinBox, - ui->yPositionSpinBox, - ui->zPositionSpinBox); + setPositionValues( + uvwPlacement.getPosition(), + ui->xPositionSpinBox, + ui->yPositionSpinBox, + ui->zPositionSpinBox + ); - setRotationValues(positionMode == PositionMode::Local - ? referenceRotation.inverse() * xyzPlacement.getRotation() - : uvwPlacement.getRotation(), - ui->xRotationSpinBox, - ui->yRotationSpinBox, - ui->zRotationSpinBox); + setRotationValues( + positionMode == PositionMode::Local ? referenceRotation.inverse() * xyzPlacement.getRotation() + : uvwPlacement.getRotation(), + ui->xRotationSpinBox, + ui->yRotationSpinBox, + ui->zRotationSpinBox + ); } void TaskTransform::updateInputLabels() const @@ -370,8 +378,8 @@ void TaskTransform::updateInputLabels() const void TaskTransform::updateDraggerLabels() const { - auto coordinateSystem = - isDraggerAlignedToCoordinateSystem() ? globalCoordinateSystem() : localCoordinateSystem(); + auto coordinateSystem = isDraggerAlignedToCoordinateSystem() ? globalCoordinateSystem() + : localCoordinateSystem(); auto [xLabel, yLabel, zLabel] = coordinateSystem.labels; @@ -383,9 +391,11 @@ void TaskTransform::updateDraggerLabels() const void TaskTransform::updateIncrements() const { dragger->translationIncrement.setValue( - std::max(ui->translationIncrementSpinBox->rawValue(), 0.001)); + std::max(ui->translationIncrementSpinBox->rawValue(), 0.001) + ); dragger->rotationIncrement.setValue( - Base::toRadians(std::max(ui->rotationIncrementSpinBox->rawValue(), 0.01))); + Base::toRadians(std::max(ui->rotationIncrementSpinBox->rawValue(), 0.01)) + ); } void TaskTransform::setSelectionMode(SelectionMode mode) @@ -460,8 +470,8 @@ Base::Rotation::EulerSequence TaskTransform::eulerSequence() const void TaskTransform::onSelectionChanged(const SelectionChanges& msg) { - const auto isSupportedMessage = - msg.Type == SelectionChanges::AddSelection || msg.Type == SelectionChanges::SetPreselect; + const auto isSupportedMessage = msg.Type == SelectionChanges::AddSelection + || msg.Type == SelectionChanges::SetPreselect; if (!isSupportedMessage) { return; @@ -490,9 +500,11 @@ void TaskTransform::onSelectionChanged(const SelectionChanges& msg) auto selectedObjectPlacement = rootPlacement.inverse() * globalPlacement * attachedPlacement; auto label = QStringLiteral("%1#%2.%3") - .arg(QLatin1String(msg.pOriginalMsg->pObjectName), - QLatin1String(msg.pObjectName), - QLatin1String(msg.pSubName)); + .arg( + QLatin1String(msg.pOriginalMsg->pObjectName), + QLatin1String(msg.pObjectName), + QLatin1String(msg.pSubName) + ); switch (selectionMode) { case SelectionMode::SelectTransformOrigin: { @@ -501,7 +513,8 @@ void TaskTransform::onSelectionChanged(const SelectionChanges& msg) customTransformOrigin = selectedObjectPlacement; updateTransformOrigin(); setSelectionMode(SelectionMode::None); - } else { + } + else { vp->setTransformOrigin(selectedObjectPlacement); } @@ -594,8 +607,9 @@ void TaskTransform::onFlip() { auto placement = vp->getDraggerPlacement(); - placement.setRotation(placement.getRotation() - * Base::Rotation::fromNormalVector(Base::Vector3d(0, 0, -1))); + placement.setRotation( + placement.getRotation() * Base::Rotation::fromNormalVector(Base::Vector3d(0, 0, -1)) + ); vp->setDraggerPlacement(placement); @@ -604,8 +618,10 @@ void TaskTransform::onFlip() void TaskTransform::onPickTransformOrigin() { - setSelectionMode(selectionMode == SelectionMode::None ? SelectionMode::SelectTransformOrigin - : SelectionMode::None); + setSelectionMode( + selectionMode == SelectionMode::None ? SelectionMode::SelectTransformOrigin + : SelectionMode::None + ); } void TaskTransform::onPlacementModeChange([[maybe_unused]] int index) @@ -643,7 +659,8 @@ void TaskTransform::updateTransformOrigin() auto transformOrigin = getTransformOrigin(placementMode); if (isDraggerAlignedToCoordinateSystem()) { transformOrigin.setRotation( - (vp->getObjectPlacement().inverse() * globalCoordinateSystem().origin).getRotation()); + (vp->getObjectPlacement().inverse() * globalCoordinateSystem().origin).getRotation() + ); } vp->setTransformOrigin(transformOrigin); @@ -706,9 +723,11 @@ void TaskTransform::onCoordinateSystemChange([[maybe_unused]] int mode) void TaskTransform::onPositionChange() { - const auto uvwPosition = Base::Vector3d(ui->xPositionSpinBox->rawValue(), - ui->yPositionSpinBox->rawValue(), - ui->zPositionSpinBox->rawValue()); + const auto uvwPosition = Base::Vector3d( + ui->xPositionSpinBox->rawValue(), + ui->yPositionSpinBox->rawValue(), + ui->zPositionSpinBox->rawValue() + ); const auto xyzPosition = currentCoordinateSystem().origin.getPosition() + currentCoordinateSystem().origin.getRotation().multVec(uvwPosition); @@ -724,9 +743,8 @@ void TaskTransform::onPositionChange() void TaskTransform::onRotationChange(QuantitySpinBox* changed) { if (positionMode == PositionMode::Local) { - for (auto rotationSpinBox : {ui->xRotationSpinBox, - ui->yRotationSpinBox, - ui->zRotationSpinBox}) { + for (auto rotationSpinBox : + {ui->xRotationSpinBox, ui->yRotationSpinBox, ui->zRotationSpinBox}) { QSignalBlocker blocker(rotationSpinBox); // if any other spinbox contains non-zero value we need to reset rotation reference first @@ -737,10 +755,12 @@ void TaskTransform::onRotationChange(QuantitySpinBox* changed) } } - const auto uvwRotation = Base::Rotation::fromEulerAngles(eulerSequence(), - ui->xRotationSpinBox->rawValue(), - ui->yRotationSpinBox->rawValue(), - ui->zRotationSpinBox->rawValue()); + const auto uvwRotation = Base::Rotation::fromEulerAngles( + eulerSequence(), + ui->xRotationSpinBox->rawValue(), + ui->yRotationSpinBox->rawValue(), + ui->zRotationSpinBox->rawValue() + ); auto referenceRotation = positionMode == PositionMode::Local ? this->referenceRotation diff --git a/src/Gui/TaskTransform.h b/src/Gui/TaskTransform.h index 171ce1f37d..ea4e1f58b5 100644 --- a/src/Gui/TaskTransform.h +++ b/src/Gui/TaskTransform.h @@ -42,16 +42,30 @@ class SoTransformDragger; class ViewProviderDragger; class Ui_TaskTransformDialog; -class TaskTransform : public Gui::TaskView::TaskBox, public Gui::SelectionObserver +class TaskTransform: public Gui::TaskView::TaskBox, public Gui::SelectionObserver { Q_OBJECT static constexpr double tolerance = 1e-7; public: - enum class SelectionMode { None, SelectTransformOrigin, SelectAlignTarget }; - enum class PlacementMode { ObjectOrigin, Centroid, Custom }; - enum class PositionMode { Local, Global }; + enum class SelectionMode + { + None, + SelectTransformOrigin, + SelectAlignTarget + }; + enum class PlacementMode + { + ObjectOrigin, + Centroid, + Custom + }; + enum class PositionMode + { + Local, + Global + }; struct CoordinateSystem { @@ -63,13 +77,15 @@ public: Q_ENUM(PlacementMode) Q_ENUM(PositionMode) - TaskTransform(Gui::ViewProviderDragger* vp, - Gui::SoTransformDragger* dragger, - QWidget* parent = nullptr, - App::SubObjectPlacementProvider* subObjectPlacementProvider = - Base::provideService(), - App::CenterOfMassProvider* centerOfMassProvider = - Base::provideService()); + TaskTransform( + Gui::ViewProviderDragger* vp, + Gui::SoTransformDragger* dragger, + QWidget* parent = nullptr, + App::SubObjectPlacementProvider* subObjectPlacementProvider + = Base::provideService(), + App::CenterOfMassProvider* centerOfMassProvider + = Base::provideService() + ); ~TaskTransform() override; private: @@ -123,29 +139,33 @@ private: void resetReferenceRotation(); ViewProviderDragger::DraggerComponents getRelevantComponents(); - void moveObjectToDragger(ViewProviderDragger::DraggerComponents components = ViewProviderDragger::DraggerComponent::All); + void moveObjectToDragger( + ViewProviderDragger::DraggerComponents components = ViewProviderDragger::DraggerComponent::All + ); bool isDraggerAlignedToCoordinateSystem() const; ViewProviderDragger* vp; const App::SubObjectPlacementProvider* subObjectPlacementProvider; - const App::CenterOfMassProvider *centerOfMassProvider; + const App::CenterOfMassProvider* centerOfMassProvider; CoinPtr dragger; - Ui_TaskTransformDialog *ui; + Ui_TaskTransformDialog* ui; - SelectionMode selectionMode { SelectionMode::None }; - PlacementMode placementMode { PlacementMode::ObjectOrigin }; - PositionMode positionMode { PositionMode::Local }; + SelectionMode selectionMode {SelectionMode::None}; + PlacementMode placementMode {PlacementMode::ObjectOrigin}; + PositionMode positionMode {PositionMode::Local}; std::optional customTransformOrigin {}; Base::Placement referencePlacement {}; Base::Placement globalOrigin {}; Base::Rotation referenceRotation {}; - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/History/Dragger"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/History/Dragger" + ); }; class TaskTransformDialog: public Gui::TaskView::TaskDialog diff --git a/src/Gui/TaskView/TaskAppearance.cpp b/src/Gui/TaskView/TaskAppearance.cpp index f31bceb064..a33508751e 100644 --- a/src/Gui/TaskView/TaskAppearance.cpp +++ b/src/Gui/TaskView/TaskAppearance.cpp @@ -22,7 +22,6 @@ ***************************************************************************/ - #include #include #include @@ -57,7 +56,8 @@ TaskAppearance::TaskAppearance(QWidget* parent) // NOLINTBEGIN this->connectChangedObject = Gui::Application::Instance->signalChangedObject.connect( - std::bind(&TaskAppearance::slotChangedObject, this, sp::_1, sp::_2)); + std::bind(&TaskAppearance::slotChangedObject, this, sp::_1, sp::_2) + ); // NOLINTEND } @@ -93,12 +93,13 @@ void TaskAppearance::changeEvent(QEvent* e) } /// @cond DOXERR -void TaskAppearance::OnChange(Gui::SelectionSingleton::SubjectType& rCaller, - Gui::SelectionSingleton::MessageType Reason) +void TaskAppearance::OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason +) { Q_UNUSED(rCaller); - if (Reason.Type == SelectionChanges::AddSelection - || Reason.Type == SelectionChanges::RmvSelection + if (Reason.Type == SelectionChanges::AddSelection || Reason.Type == SelectionChanges::RmvSelection || Reason.Type == SelectionChanges::SetSelection || Reason.Type == SelectionChanges::ClrSelection) { std::vector views = getSelection(); @@ -321,8 +322,9 @@ std::vector TaskAppearance::getSelection() const // get the complete selection std::vector sel = Selection().getCompleteSelection(); for (const auto& it : sel) { - Gui::ViewProvider* view = - Application::Instance->getDocument(it.pDoc)->getViewProvider(it.pObject); + Gui::ViewProvider* view = Application::Instance->getDocument(it.pDoc)->getViewProvider( + it.pObject + ); if (view) { views.push_back(view); } diff --git a/src/Gui/TaskView/TaskAppearance.h b/src/Gui/TaskView/TaskAppearance.h index 00100bacc3..992325c675 100644 --- a/src/Gui/TaskView/TaskAppearance.h +++ b/src/Gui/TaskView/TaskAppearance.h @@ -29,28 +29,33 @@ #include "TaskView.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; -namespace TaskView { +namespace TaskView +{ using TaskAppearance_Connection = boost::signals2::connection; class Ui_TaskAppearance; -class TaskAppearance : public TaskBox, public Gui::SelectionSingleton::ObserverType +class TaskAppearance: public TaskBox, public Gui::SelectionSingleton::ObserverType { Q_OBJECT public: - explicit TaskAppearance(QWidget *parent = nullptr); + explicit TaskAppearance(QWidget* parent = nullptr); ~TaskAppearance() override; /// Observer message from the Selection - void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason) override; + void OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason + ) override; private Q_SLOTS: void setupConnections(); @@ -61,7 +66,7 @@ private Q_SLOTS: void onLineWidthValueChanged(int); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void slotChangedObject(const Gui::ViewProvider&, const App::Property& Prop); @@ -77,7 +82,7 @@ private: TaskAppearance_Connection connectChangedObject; }; -} //namespace TaskView -} //namespace Gui +} // namespace TaskView +} // namespace Gui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Gui/TaskView/TaskDialog.cpp b/src/Gui/TaskView/TaskDialog.cpp index da5f172663..f6d613c09b 100644 --- a/src/Gui/TaskView/TaskDialog.cpp +++ b/src/Gui/TaskView/TaskDialog.cpp @@ -22,8 +22,7 @@ ***************************************************************************/ - -# include +#include #include @@ -46,14 +45,13 @@ using namespace Gui::TaskView; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDialog::TaskDialog() - : QObject(nullptr), pos(North) + : QObject(nullptr) + , pos(North) , escapeButton(true) , autoCloseTransaction(false) , autoCloseDeletedDocument(false) , autoCloseClosedView(false) -{ - -} +{} TaskDialog::~TaskDialog() { @@ -70,10 +68,7 @@ QWidget* TaskDialog::addTaskBox(QWidget* widget, bool expandable, QWidget* paren return addTaskBox(QPixmap(), widget, expandable, parent); } -QWidget* TaskDialog::addTaskBox(const QPixmap& icon, - QWidget* widget, - bool expandable, - QWidget* parent) +QWidget* TaskDialog::addTaskBox(const QPixmap& icon, QWidget* widget, bool expandable, QWidget* parent) { auto taskbox = new Gui::TaskView::TaskBox(icon, widget->windowTitle(), expandable, parent); taskbox->groupLayout()->addWidget(widget); @@ -89,7 +84,7 @@ QWidget* TaskDialog::addTaskBoxWithoutHeader(QWidget* widget) return taskbox; } -const std::vector &TaskDialog::getDialogContent() const +const std::vector& TaskDialog::getDialogContent() const { return Content; } @@ -127,34 +122,22 @@ void TaskDialog::associateToObject3dView(App::DocumentObject* obj) //==== calls from the TaskView =============================================================== void TaskDialog::open() -{ - -} +{} void TaskDialog::closed() -{ - -} +{} void TaskDialog::autoClosedOnTransactionChange() -{ - -} +{} void TaskDialog::autoClosedOnDeletedDocument() -{ - -} +{} void TaskDialog::autoClosedOnClosedView() -{ - -} +{} void TaskDialog::clicked(int) -{ - -} +{} bool TaskDialog::accept() { @@ -167,21 +150,13 @@ bool TaskDialog::reject() } void TaskDialog::helpRequested() -{ - -} +{} void TaskDialog::onUndo() -{ - -} +{} void TaskDialog::onRedo() -{ - -} - - +{} #include "moc_TaskDialog.cpp" diff --git a/src/Gui/TaskView/TaskDialog.h b/src/Gui/TaskView/TaskDialog.h index db126b46bb..9c05f68776 100644 --- a/src/Gui/TaskView/TaskDialog.h +++ b/src/Gui/TaskView/TaskDialog.h @@ -33,13 +33,16 @@ #include -namespace App { +namespace App +{ class DocumentObject; } -namespace Gui { +namespace Gui +{ class MDIView; -namespace TaskView { +namespace TaskView +{ class TaskContent; class TaskDialogAttorney; @@ -47,101 +50,138 @@ class TaskDialogPy; class TaskView; /// Father class of content with header and Icon -class GuiExport TaskDialog : public QObject +class GuiExport TaskDialog: public QObject { Q_OBJECT public: - enum ButtonPosition { - North, South + enum ButtonPosition + { + North, + South }; TaskDialog(); ~TaskDialog() override; QWidget* addTaskBox(QWidget* widget, bool expandable = true, QWidget* parent = nullptr); - QWidget* addTaskBox(const QPixmap& icon, QWidget* widget, bool expandable = true, QWidget* parent = nullptr); + QWidget* addTaskBox( + const QPixmap& icon, + QWidget* widget, + bool expandable = true, + QWidget* parent = nullptr + ); QWidget* addTaskBoxWithoutHeader(QWidget* widget); void setButtonPosition(ButtonPosition p) - { pos = p; } + { + pos = p; + } ButtonPosition buttonPosition() const - { return pos; } - const std::vector &getDialogContent() const; + { + return pos; + } + const std::vector& getDialogContent() const; bool canClose() const; /// tells the framework which buttons are wished for the dialog virtual QDialogButtonBox::StandardButtons getStandardButtons() const - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } virtual void modifyStandardButtons(QDialogButtonBox*) {} /// Defines whether a task dialog can be rejected by pressing Esc - void setEscapeButtonEnabled(bool on) { + void setEscapeButtonEnabled(bool on) + { escapeButton = on; } - bool isEscapeButtonEnabled() const { + bool isEscapeButtonEnabled() const + { return escapeButton; } /// Defines whether a task dialog must be closed if the document changed the /// active transaction. - void setAutoCloseOnTransactionChange(bool on) { + void setAutoCloseOnTransactionChange(bool on) + { autoCloseTransaction = on; } - bool isAutoCloseOnTransactionChange() const { + bool isAutoCloseOnTransactionChange() const + { return autoCloseTransaction; } /// Defines whether a task dialog must be closed if the document is /// deleted. - void setAutoCloseOnDeletedDocument(bool on) { + void setAutoCloseOnDeletedDocument(bool on) + { autoCloseDeletedDocument = on; } - bool isAutoCloseOnDeletedDocument() const { + bool isAutoCloseOnDeletedDocument() const + { return autoCloseDeletedDocument; } const std::string& getDocumentName() const - { return documentName; } + { + return documentName; + } void setDocumentName(const std::string& doc) - { documentName = doc; } + { + documentName = doc; + } /// Defines whether a task dialog must be closed if the associated view /// is deleted. - void setAutoCloseOnClosedView(bool on) { + void setAutoCloseOnClosedView(bool on) + { autoCloseClosedView = on; } - bool isAutoCloseOnClosedView() const { + bool isAutoCloseOnClosedView() const + { return autoCloseClosedView; } void associateToObject3dView(App::DocumentObject* obj); const Gui::MDIView* getAssociatedView() const - { return associatedView; } + { + return associatedView; + } void setAssociatedView(const Gui::MDIView* view) - { associatedView = view; } + { + associatedView = view; + } /*! Indicates whether this task dialog allows other commands to modify the document while it is open. */ virtual bool isAllowedAlterDocument() const - { return false; } + { + return false; + } /*! Indicates whether this task dialog allows other commands to modify the 3d view while it is open. */ virtual bool isAllowedAlterView() const - { return true; } + { + return true; + } /*! Indicates whether this task dialog allows other commands to modify the selection while it is open. */ virtual bool isAllowedAlterSelection() const - { return true; } + { + return true; + } virtual bool needsFullSpace() const - { return false; } + { + return false; + } public: /// is called by the framework when the dialog is opened @@ -170,13 +210,14 @@ public: /// is called by the framework if the user press the redo button virtual void onRedo(); - void emitDestructionSignal() { + void emitDestructionSignal() + { Q_EMIT aboutToBeDestroyed(); } - + Q_SIGNALS: void aboutToBeDestroyed(); - + protected: QPointer buttonBox; /// List of TaskBoxes of that dialog @@ -194,12 +235,15 @@ private: friend class TaskDialogAttorney; }; -class TaskDialogAttorney { +class TaskDialogAttorney +{ private: - static void setButtonBox(TaskDialog* dlg, QDialogButtonBox* box) { + static void setButtonBox(TaskDialog* dlg, QDialogButtonBox* box) + { dlg->buttonBox = box; } - static QDialogButtonBox* getButtonBox(TaskDialog* dlg) { + static QDialogButtonBox* getButtonBox(TaskDialog* dlg) + { return dlg->buttonBox; } @@ -207,7 +251,7 @@ private: friend class TaskView; }; -} //namespace TaskView -} //namespace Gui +} // namespace TaskView +} // namespace Gui -#endif // GUI_TASKVIEW_TASKDIALOG_H +#endif // GUI_TASKVIEW_TASKDIALOG_H diff --git a/src/Gui/TaskView/TaskDialogPython.cpp b/src/Gui/TaskView/TaskDialogPython.cpp index 3779ed9fff..e1d11927e7 100644 --- a/src/Gui/TaskView/TaskDialogPython.cpp +++ b/src/Gui/TaskView/TaskDialogPython.cpp @@ -22,10 +22,10 @@ ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -47,8 +47,9 @@ ControlPy* ControlPy::instance = nullptr; ControlPy* ControlPy::getInstance() { - if (!instance) + if (!instance) { instance = new ControlPy(); + } return instance; } @@ -60,41 +61,74 @@ void ControlPy::init_type() behaviors().supportRepr(); behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("showDialog",&ControlPy::showDialog, - "show the given dialog in the task panel\n" - "showDialog(dialog)\n" - "--\n" - "if a task is already active a RuntimeError is raised"); - add_varargs_method("activeDialog",&ControlPy::activeDialog, - "check if a dialog is active in the task panel\n" - "activeDialog() --> bool"); - add_varargs_method("activeTaskDialog",&ControlPy::activeTaskDialog, - "return the active task dialog if there is one\n" - "activeTaskDialog() --> TaskDialog or None"); - add_varargs_method("closeDialog",&ControlPy::closeDialog, - "close the active dialog\n" - "closeDialog()"); - add_varargs_method("addTaskWatcher",&ControlPy::addTaskWatcher, - "install a (list of) TaskWatcher\n" - "addTaskWatcher(TaskWatcher | list)"); - add_varargs_method("clearTaskWatcher",&ControlPy::clearTaskWatcher, - "remove all TaskWatchers\n" - "clearTaskWatcher()"); - add_varargs_method("isAllowedAlterDocument",&ControlPy::isAllowedAlterDocument, - "return the permission to alter the current Document\n" - "isAllowedAlterDocument() --> bool"); - add_varargs_method("isAllowedAlterView",&ControlPy::isAllowedAlterView, - "return the permission to alter the current View\n" - "isAllowedAlterView() --> bool"); - add_varargs_method("isAllowedAlterSelection",&ControlPy::isAllowedAlterSelection, - "return the permission to alter the current Selection\n" - "isAllowedAlterSelection() --> bool"); - add_varargs_method("showTaskView",&ControlPy::showTaskView, - "show the Task panel\n" - "showTaskView()"); - add_varargs_method("showModelView",&ControlPy::showModelView, - "show the Model panel\n" - "showModelView()"); + add_varargs_method( + "showDialog", + &ControlPy::showDialog, + "show the given dialog in the task panel\n" + "showDialog(dialog)\n" + "--\n" + "if a task is already active a RuntimeError is raised" + ); + add_varargs_method( + "activeDialog", + &ControlPy::activeDialog, + "check if a dialog is active in the task panel\n" + "activeDialog() --> bool" + ); + add_varargs_method( + "activeTaskDialog", + &ControlPy::activeTaskDialog, + "return the active task dialog if there is one\n" + "activeTaskDialog() --> TaskDialog or None" + ); + add_varargs_method( + "closeDialog", + &ControlPy::closeDialog, + "close the active dialog\n" + "closeDialog()" + ); + add_varargs_method( + "addTaskWatcher", + &ControlPy::addTaskWatcher, + "install a (list of) TaskWatcher\n" + "addTaskWatcher(TaskWatcher | list)" + ); + add_varargs_method( + "clearTaskWatcher", + &ControlPy::clearTaskWatcher, + "remove all TaskWatchers\n" + "clearTaskWatcher()" + ); + add_varargs_method( + "isAllowedAlterDocument", + &ControlPy::isAllowedAlterDocument, + "return the permission to alter the current Document\n" + "isAllowedAlterDocument() --> bool" + ); + add_varargs_method( + "isAllowedAlterView", + &ControlPy::isAllowedAlterView, + "return the permission to alter the current View\n" + "isAllowedAlterView() --> bool" + ); + add_varargs_method( + "isAllowedAlterSelection", + &ControlPy::isAllowedAlterSelection, + "return the permission to alter the current Selection\n" + "isAllowedAlterSelection() --> bool" + ); + add_varargs_method( + "showTaskView", + &ControlPy::showTaskView, + "show the Task panel\n" + "showTaskView()" + ); + add_varargs_method( + "showModelView", + &ControlPy::showModelView, + "show the Model panel\n" + "showModelView()" + ); } ControlPy::ControlPy() = default; @@ -109,11 +143,13 @@ Py::Object ControlPy::repr() Py::Object ControlPy::showDialog(const Py::Tuple& args) { PyObject* arg0; - if (!PyArg_ParseTuple(args.ptr(), "O", &arg0)) + if (!PyArg_ParseTuple(args.ptr(), "O", &arg0)) { throw Py::Exception(); + } Gui::TaskView::TaskDialog* act = Gui::Control().activeDialog(); - if (act) + if (act) { throw Py::RuntimeError("Active task dialog found"); + } auto dlg = new TaskDialogPython(Py::Object(arg0)); Gui::Control().showDialog(dlg); return (Py::asObject(new TaskDialogPy(dlg))); @@ -121,24 +157,27 @@ Py::Object ControlPy::showDialog(const Py::Tuple& args) Py::Object ControlPy::activeDialog(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); return Py::Boolean(dlg != nullptr); } Py::Object ControlPy::activeTaskDialog(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); return (dlg ? Py::asObject(new TaskDialogPy(dlg)) : Py::None()); } Py::Object ControlPy::closeDialog(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Gui::Control().closeDialog(); return Py::None(); } @@ -146,8 +185,9 @@ Py::Object ControlPy::closeDialog(const Py::Tuple& args) Py::Object ControlPy::addTaskWatcher(const Py::Tuple& args) { PyObject* arg0; - if (!PyArg_ParseTuple(args.ptr(), "O", &arg0)) + if (!PyArg_ParseTuple(args.ptr(), "O", &arg0)) { throw Py::Exception(); + } std::vector watcher; Py::Sequence list(arg0); @@ -157,57 +197,65 @@ Py::Object ControlPy::addTaskWatcher(const Py::Tuple& args) } Gui::TaskView::TaskView* taskView = Gui::Control().taskPanel(); - if (taskView) + if (taskView) { taskView->addTaskWatcher(watcher); + } return Py::None(); } Py::Object ControlPy::clearTaskWatcher(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Gui::TaskView::TaskView* taskView = Gui::Control().taskPanel(); - if (taskView) + if (taskView) { taskView->clearTaskWatcher(); + } return Py::None(); } Py::Object ControlPy::isAllowedAlterDocument(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } bool ok = Gui::Control().isAllowedAlterDocument(); return Py::Boolean(ok); } Py::Object ControlPy::isAllowedAlterView(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } bool ok = Gui::Control().isAllowedAlterView(); return Py::Boolean(ok); } Py::Object ControlPy::isAllowedAlterSelection(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } bool ok = Gui::Control().isAllowedAlterSelection(); return Py::Boolean(ok); } Py::Object ControlPy::showTaskView(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Gui::Control().showTaskView(); return Py::None(); } Py::Object ControlPy::showModelView(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Gui::Control().showModelView(); return Py::None(); } @@ -215,7 +263,8 @@ Py::Object ControlPy::showModelView(const Py::Tuple& args) // ------------------------------------------------------------------ TaskWatcherPython::TaskWatcherPython(const Py::Object& o) - : TaskWatcher(nullptr), watcher(o) + : TaskWatcher(nullptr) + , watcher(o) { QString title; if (watcher.hasAttr(std::string("title"))) { @@ -231,23 +280,25 @@ TaskWatcherPython::TaskWatcherPython(const Py::Object& o) icon = BitmapFactory().pixmap(s.c_str()); } - Gui::TaskView::TaskBox *tb = nullptr; + Gui::TaskView::TaskBox* tb = nullptr; if (watcher.hasAttr(std::string("commands"))) { tb = new Gui::TaskView::TaskBox(icon, title, true, nullptr); Py::Sequence cmds(watcher.getAttr(std::string("commands"))); - CommandManager &mgr = Gui::Application::Instance->commandManager(); + CommandManager& mgr = Gui::Application::Instance->commandManager(); for (Py::Sequence::iterator it = cmds.begin(); it != cmds.end(); ++it) { Py::String name(*it); std::string s = static_cast(name); - Command *c = mgr.getCommandByName(s.c_str()); - if (c) + Command* c = mgr.getCommandByName(s.c_str()); + if (c) { c->addTo(tb); + } } } if (watcher.hasAttr(std::string("widgets"))) { - if (!tb && !title.isEmpty()) + if (!tb && !title.isEmpty()) { tb = new Gui::TaskView::TaskBox(icon, title, true, nullptr); + } Py::Sequence list(watcher.getAttr(std::string("widgets"))); Gui::PythonWrapper wrap; @@ -257,17 +308,21 @@ TaskWatcherPython::TaskWatcherPython(const Py::Object& o) if (object) { QWidget* w = qobject_cast(object); if (w) { - if (tb) + if (tb) { tb->groupLayout()->addWidget(w); - else + } + else { Content.push_back(w); + } } } } } } - if (tb) Content.push_back(tb); + if (tb) { + Content.push_back(tb); + } if (watcher.hasAttr(std::string("filter"))) { Py::String name(watcher.getAttr(std::string("filter"))); @@ -278,7 +333,7 @@ TaskWatcherPython::TaskWatcherPython(const Py::Object& o) TaskWatcherPython::~TaskWatcherPython() { - std::vector< QPointer > guarded; + std::vector> guarded; guarded.insert(guarded.begin(), Content.begin(), Content.end()); Content.clear(); Base::PyGILStateLocker lock; @@ -298,14 +353,16 @@ bool TaskWatcherPython::shouldShow() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } - if (!this->Filter.empty()) + if (!this->Filter.empty()) { return match(); - else + } + else { return TaskWatcher::shouldShow(); + } } // ------------------------------------------------------------------ @@ -318,48 +375,87 @@ void TaskDialogPy::init_type() behaviors().supportRepr(); behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("getDialogContent",&TaskDialogPy::getDialogContent, - "Returns the widgets of the task dialog -> list"); - add_varargs_method("getStandardButtons",&TaskDialogPy::getStandardButtons, - "Get the standard buttons of the box -> flags"); - add_varargs_method("setEscapeButtonEnabled",&TaskDialogPy::setEscapeButtonEnabled, - "Defines whether the task dialog can be rejected by pressing Esc"); - add_varargs_method("isEscapeButtonEnabled",&TaskDialogPy::isEscapeButtonEnabled, - "Checks if the task dialog can be rejected by pressing Esc -> bool"); - add_varargs_method("setAutoCloseOnTransactionChange",&TaskDialogPy::setAutoCloseOnTransactionChange, - "Defines whether a task dialog must be closed if the document changes the\n" - "active transaction"); - add_varargs_method("isAutoCloseOnTransactionChange",&TaskDialogPy::isAutoCloseOnTransactionChange, - "Checks if the task dialog will be closed when the active transaction has changed -> bool"); - add_varargs_method("setAutoCloseOnDeletedDocument",&TaskDialogPy::setAutoCloseOnDeletedDocument, - "Defines whether a task dialog must be closed if the document is deleted"); - add_varargs_method("isAutoCloseOnDeletedDocument",&TaskDialogPy::isAutoCloseOnDeletedDocument, - "Checks if the task dialog will be closed if the document is deleted -> bool"); - add_varargs_method("getDocumentName",&TaskDialogPy::getDocumentName, - "Get the name of the document the task dialog is attached to -> str"); - add_varargs_method("setDocumentName",&TaskDialogPy::setDocumentName, - "Set the name of the document the task dialog is attached to"); - add_varargs_method("isAllowedAlterDocument",&TaskDialogPy::isAllowedAlterDocument, - "Indicates whether this task dialog allows other commands to modify\n" - "the document while it is open -> bool"); - add_varargs_method("isAllowedAlterView",&TaskDialogPy::isAllowedAlterView, - "Indicates whether this task dialog allows other commands to modify\n" - "the 3d view while it is open -> bool"); - add_varargs_method("isAllowedAlterSelection",&TaskDialogPy::isAllowedAlterSelection, - "Indicates whether this task dialog allows other commands to modify\n" - "the selection while it is open -> bool"); - add_varargs_method("needsFullSpace",&TaskDialogPy::needsFullSpace, - "Indicates whether the task dialog fully requires the available space -> bool"); - add_varargs_method("accept",&TaskDialogPy::accept, - "Accept the task dialog"); - add_varargs_method("reject",&TaskDialogPy::reject, - "Reject the task dialog"); + add_varargs_method( + "getDialogContent", + &TaskDialogPy::getDialogContent, + "Returns the widgets of the task dialog -> list" + ); + add_varargs_method( + "getStandardButtons", + &TaskDialogPy::getStandardButtons, + "Get the standard buttons of the box -> flags" + ); + add_varargs_method( + "setEscapeButtonEnabled", + &TaskDialogPy::setEscapeButtonEnabled, + "Defines whether the task dialog can be rejected by pressing Esc" + ); + add_varargs_method( + "isEscapeButtonEnabled", + &TaskDialogPy::isEscapeButtonEnabled, + "Checks if the task dialog can be rejected by pressing Esc -> bool" + ); + add_varargs_method( + "setAutoCloseOnTransactionChange", + &TaskDialogPy::setAutoCloseOnTransactionChange, + "Defines whether a task dialog must be closed if the document changes the\n" + "active transaction" + ); + add_varargs_method( + "isAutoCloseOnTransactionChange", + &TaskDialogPy::isAutoCloseOnTransactionChange, + "Checks if the task dialog will be closed when the active transaction has changed -> bool" + ); + add_varargs_method( + "setAutoCloseOnDeletedDocument", + &TaskDialogPy::setAutoCloseOnDeletedDocument, + "Defines whether a task dialog must be closed if the document is deleted" + ); + add_varargs_method( + "isAutoCloseOnDeletedDocument", + &TaskDialogPy::isAutoCloseOnDeletedDocument, + "Checks if the task dialog will be closed if the document is deleted -> bool" + ); + add_varargs_method( + "getDocumentName", + &TaskDialogPy::getDocumentName, + "Get the name of the document the task dialog is attached to -> str" + ); + add_varargs_method( + "setDocumentName", + &TaskDialogPy::setDocumentName, + "Set the name of the document the task dialog is attached to" + ); + add_varargs_method( + "isAllowedAlterDocument", + &TaskDialogPy::isAllowedAlterDocument, + "Indicates whether this task dialog allows other commands to modify\n" + "the document while it is open -> bool" + ); + add_varargs_method( + "isAllowedAlterView", + &TaskDialogPy::isAllowedAlterView, + "Indicates whether this task dialog allows other commands to modify\n" + "the 3d view while it is open -> bool" + ); + add_varargs_method( + "isAllowedAlterSelection", + &TaskDialogPy::isAllowedAlterSelection, + "Indicates whether this task dialog allows other commands to modify\n" + "the selection while it is open -> bool" + ); + add_varargs_method( + "needsFullSpace", + &TaskDialogPy::needsFullSpace, + "Indicates whether the task dialog fully requires the available space -> bool" + ); + add_varargs_method("accept", &TaskDialogPy::accept, "Accept the task dialog"); + add_varargs_method("reject", &TaskDialogPy::reject, "Reject the task dialog"); } TaskDialogPy::TaskDialogPy(TaskDialog* dlg) - : dialog(dlg) -{ -} + : dialog(dlg) +{} TaskDialogPy::~TaskDialogPy() = default; @@ -367,10 +463,10 @@ Py::Object TaskDialogPy::repr() { std::stringstream str; str << "getDocumentName() << "' >"; - return Py::String( str.str() ); + return Py::String(str.str()); } -Py::Object TaskDialogPy::getattr(const char * attr) +Py::Object TaskDialogPy::getattr(const char* attr) { if (!dialog) { std::ostringstream s_out; @@ -380,7 +476,7 @@ Py::Object TaskDialogPy::getattr(const char * attr) return BaseType::getattr(attr); } -int TaskDialogPy::setattr(const char *attr, const Py::Object &value) +int TaskDialogPy::setattr(const char* attr, const Py::Object& value) { if (!dialog) { std::ostringstream s_out; @@ -392,8 +488,9 @@ int TaskDialogPy::setattr(const char *attr, const Py::Object &value) Py::Object TaskDialogPy::getDialogContent(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } PythonWrapper wrap; wrap.loadWidgetsModule(); @@ -409,8 +506,9 @@ Py::Object TaskDialogPy::getDialogContent(const Py::Tuple& args) Py::Object TaskDialogPy::getStandardButtons(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } auto buttons = dialog->getStandardButtons(); return Py::Long(static_cast(buttons)); } @@ -424,8 +522,9 @@ Py::Object TaskDialogPy::setEscapeButtonEnabled(const Py::Tuple& args) Py::Object TaskDialogPy::isEscapeButtonEnabled(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->isEscapeButtonEnabled()); } @@ -438,8 +537,9 @@ Py::Object TaskDialogPy::setAutoCloseOnTransactionChange(const Py::Tuple& args) Py::Object TaskDialogPy::isAutoCloseOnTransactionChange(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->isAutoCloseOnTransactionChange()); } @@ -452,56 +552,64 @@ Py::Object TaskDialogPy::setAutoCloseOnDeletedDocument(const Py::Tuple& args) Py::Object TaskDialogPy::isAutoCloseOnDeletedDocument(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->isAutoCloseOnDeletedDocument()); } Py::Object TaskDialogPy::getDocumentName(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::String(dialog->getDocumentName()); } Py::Object TaskDialogPy::setDocumentName(const Py::Tuple& args) { const char* name {""}; - if (!PyArg_ParseTuple(args.ptr(), "s", &name)) + if (!PyArg_ParseTuple(args.ptr(), "s", &name)) { throw Py::Exception(); + } dialog->setDocumentName(name); return Py::None(); } Py::Object TaskDialogPy::isAllowedAlterDocument(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->isAllowedAlterDocument()); } Py::Object TaskDialogPy::isAllowedAlterView(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->isAllowedAlterView()); } Py::Object TaskDialogPy::isAllowedAlterSelection(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->isAllowedAlterSelection()); } Py::Object TaskDialogPy::needsFullSpace(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } return Py::Boolean(dialog->needsFullSpace()); } -namespace { +namespace +{ auto clickButton = [](QDialogButtonBox* buttonBox, QDialogButtonBox::ButtonRole role) { if (buttonBox) { QList list = buttonBox->buttons(); @@ -515,12 +623,13 @@ auto clickButton = [](QDialogButtonBox* buttonBox, QDialogButtonBox::ButtonRole } } }; -} +} // namespace Py::Object TaskDialogPy::accept(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } auto buttonBox = TaskDialogAttorney::getButtonBox(dialog); clickButton(buttonBox, QDialogButtonBox::AcceptRole); return Py::None(); @@ -528,8 +637,9 @@ Py::Object TaskDialogPy::accept(const Py::Tuple& args) Py::Object TaskDialogPy::reject(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } auto buttonBox = TaskDialogAttorney::getButtonBox(dialog); clickButton(buttonBox, QDialogButtonBox::RejectRole); return Py::None(); @@ -537,7 +647,8 @@ Py::Object TaskDialogPy::reject(const Py::Tuple& args) // ------------------------------------------------------------------ -TaskDialogPython::TaskDialogPython(const Py::Object& o) : dlg(o) +TaskDialogPython::TaskDialogPython(const Py::Object& o) + : dlg(o) { if (!tryLoadUiFile()) { tryLoadForm(); @@ -546,7 +657,7 @@ TaskDialogPython::TaskDialogPython(const Py::Object& o) : dlg(o) TaskDialogPython::~TaskDialogPython() { - std::vector< QPointer > guarded; + std::vector> guarded; guarded.insert(guarded.begin(), Content.begin(), Content.end()); Content.clear(); @@ -570,15 +681,15 @@ bool TaskDialogPython::tryLoadUiFile() QFile file(fn); QWidget* form = nullptr; - if (file.open(QFile::ReadOnly)) + if (file.open(QFile::ReadOnly)) { form = loader->load(&file, nullptr); + } file.close(); if (form) { appendForm(form, QPixmap(icon)); } else { - Base::Console().error("Failed to load UI file from '%s'\n", - (const char*)fn.toUtf8()); + Base::Console().error("Failed to load UI file from '%s'\n", (const char*)fn.toUtf8()); } return true; @@ -621,8 +732,7 @@ bool TaskDialogPython::tryLoadForm() void TaskDialogPython::appendForm(QWidget* form, const QPixmap& icon) { form->installEventFilter(this); - auto taskbox = new Gui::TaskView::TaskBox( - icon, form->windowTitle(), true, nullptr); + auto taskbox = new Gui::TaskView::TaskBox(icon, form->windowTitle(), true, nullptr); taskbox->groupLayout()->addWidget(form); Content.push_back(taskbox); } @@ -655,7 +765,7 @@ void TaskDialogPython::open() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -673,7 +783,7 @@ void TaskDialogPython::clicked(int i) } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -690,7 +800,7 @@ bool TaskDialogPython::accept() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -709,7 +819,7 @@ bool TaskDialogPython::reject() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -727,25 +837,25 @@ void TaskDialogPython::helpRequested() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } -bool TaskDialogPython::eventFilter(QObject *watched, QEvent *event) +bool TaskDialogPython::eventFilter(QObject* watched, QEvent* event) { if (event->type() == QEvent::LanguageChange) { Base::PyGILStateLocker lock; try { if (dlg.hasAttr(std::string("changeEvent"))) { Py::Callable method(dlg.getAttr(std::string("changeEvent"))); - Py::Tuple args{1}; + Py::Tuple args {1}; args.setItem(0, Py::Long(static_cast(event->type()))); method.apply(args); } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -767,14 +877,14 @@ QDialogButtonBox::StandardButtons TaskDialogPython::getStandardButtons() const } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return TaskDialog::getStandardButtons(); } -void TaskDialogPython::modifyStandardButtons(QDialogButtonBox *buttonBox) +void TaskDialogPython::modifyStandardButtons(QDialogButtonBox* buttonBox) { Base::PyGILStateLocker lock; try { @@ -789,7 +899,7 @@ void TaskDialogPython::modifyStandardButtons(QDialogButtonBox *buttonBox) } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -806,7 +916,7 @@ bool TaskDialogPython::isAllowedAlterDocument() const } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -825,7 +935,7 @@ bool TaskDialogPython::isAllowedAlterView() const } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -844,7 +954,7 @@ bool TaskDialogPython::isAllowedAlterSelection() const } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -863,7 +973,7 @@ bool TaskDialogPython::needsFullSpace() const } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -881,7 +991,7 @@ void TaskDialogPython::autoClosedOnTransactionChange() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -897,7 +1007,7 @@ void TaskDialogPython::autoClosedOnDeletedDocument() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } diff --git a/src/Gui/TaskView/TaskDialogPython.h b/src/Gui/TaskView/TaskDialogPython.h index b7c0f35533..158f47168f 100644 --- a/src/Gui/TaskView/TaskDialogPython.h +++ b/src/Gui/TaskView/TaskDialogPython.h @@ -29,13 +29,15 @@ #include "TaskWatcher.h" -namespace Gui { -namespace TaskView { +namespace Gui +{ +namespace TaskView +{ -class ControlPy : public Py::PythonExtension +class ControlPy: public Py::PythonExtension { public: - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods static ControlPy* getInstance(); ControlPy(); @@ -58,7 +60,7 @@ private: static ControlPy* instance; }; -class GuiExport TaskWatcherPython : public TaskWatcher +class GuiExport TaskWatcherPython: public TaskWatcher { public: explicit TaskWatcherPython(const Py::Object&); @@ -73,18 +75,18 @@ private: * @brief The TaskDialogPy class * This class exposes a TaskDialog written in C++ to Python. */ -class TaskDialogPy : public Py::PythonExtension +class TaskDialogPy: public Py::PythonExtension { public: using BaseType = Py::PythonExtension; - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods explicit TaskDialogPy(TaskDialog*); ~TaskDialogPy() override; Py::Object repr() override; - Py::Object getattr(const char *) override; - int setattr(const char *, const Py::Object &) override; + Py::Object getattr(const char*) override; + int setattr(const char*, const Py::Object&) override; public: Py::Object getDialogContent(const Py::Tuple&); @@ -138,7 +140,7 @@ private: * @brief The TaskDialogPython class * This wraps a task dialog that is written in Python. */ -class GuiExport TaskDialogPython : public TaskDialog +class GuiExport TaskDialogPython: public TaskDialog { public: explicit TaskDialogPython(const Py::Object&); @@ -176,11 +178,11 @@ public: bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) bool reject() override; - /// is called by the framework if the user press the help button + /// is called by the framework if the user press the help button void helpRequested() override; /// event handling - bool eventFilter(QObject *watched, QEvent *event) override; + bool eventFilter(QObject* watched, QEvent* event) override; private: bool tryLoadUiFile(); @@ -192,8 +194,7 @@ private: Py::Object dlg; }; -} //namespace TaskView -} //namespace Gui - -#endif // GUI_TASKVIEW_TASKDIALOGPYTHON_H +} // namespace TaskView +} // namespace Gui +#endif // GUI_TASKVIEW_TASKDIALOGPYTHON_H diff --git a/src/Gui/TaskView/TaskEditControl.cpp b/src/Gui/TaskView/TaskEditControl.cpp index e6f9c0b81a..03437fcf36 100644 --- a/src/Gui/TaskView/TaskEditControl.cpp +++ b/src/Gui/TaskView/TaskEditControl.cpp @@ -30,12 +30,12 @@ using namespace Gui::TaskView; -TaskEditControl::TaskEditControl(QWidget *parent) +TaskEditControl::TaskEditControl(QWidget* parent) : TaskWidget(parent) { hboxLayout = new QHBoxLayout(this); buttonBox = new QDialogButtonBox(this); - buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); + buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); buttonBox->setCenterButtons(true); hboxLayout->addWidget(buttonBox); diff --git a/src/Gui/TaskView/TaskEditControl.h b/src/Gui/TaskView/TaskEditControl.h index 6cd63c514a..f38ae6c93f 100644 --- a/src/Gui/TaskView/TaskEditControl.h +++ b/src/Gui/TaskView/TaskEditControl.h @@ -32,32 +32,34 @@ class Ui_TaskEditControl; class QHBoxLayout; class QDialogButtonBox; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; -namespace TaskView { +namespace TaskView +{ - -class TaskEditControl : public TaskWidget +class TaskEditControl: public TaskWidget { Q_OBJECT public: - explicit TaskEditControl(QWidget *parent = nullptr); + explicit TaskEditControl(QWidget* parent = nullptr); ~TaskEditControl() override; QDialogButtonBox* standardButtons() const; friend class TaskView; protected: - QHBoxLayout *hboxLayout; - QDialogButtonBox *buttonBox; + QHBoxLayout* hboxLayout; + QDialogButtonBox* buttonBox; }; -} //namespace TaskView -} //namespace Gui +} // namespace TaskView +} // namespace Gui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Gui/TaskView/TaskImage.cpp b/src/Gui/TaskView/TaskImage.cpp index 5337a3f128..4804cb180e 100644 --- a/src/Gui/TaskView/TaskImage.cpp +++ b/src/Gui/TaskView/TaskImage.cpp @@ -419,9 +419,11 @@ void TaskImage::updatePlacement() } // NOLINTEND - Base::Vector3d offset = Base::Vector3d(ui->spinBoxX->value().getValue(), - ui->spinBoxY->value().getValue(), - ui->spinBoxZ->value().getValue()); + Base::Vector3d offset = Base::Vector3d( + ui->spinBoxX->value().getValue(), + ui->spinBoxY->value().getValue(), + ui->spinBoxZ->value().getValue() + ); offset = rot.multVec(offset); Pos = Base::Placement(offset, rot); @@ -448,22 +450,24 @@ void TaskImage::updateIcon() } ui->previewLabel->setPixmap( - Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size())); + Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size()) + ); } // ---------------------------------------------------------------------------- -InteractiveScale::InteractiveScale(View3DInventorViewer* view, - ViewProvider* vp, - const Base::Placement& plc) // NOLINT +InteractiveScale::InteractiveScale( + View3DInventorViewer* view, + ViewProvider* vp, + const Base::Placement& plc +) // NOLINT : active(false) , placement(plc) , viewer(view) , viewProv(vp) , midPoint(SbVec3f(0, 0, 0)) { - measureLabel = - new EditableDatumLabel(viewer, placement, SbColor(1.0F, 0.149F, 0.0F)); // NOLINT + measureLabel = new EditableDatumLabel(viewer, placement, SbColor(1.0F, 0.149F, 0.0F)); // NOLINT } InteractiveScale::~InteractiveScale() @@ -475,12 +479,12 @@ void InteractiveScale::activate() { if (viewer) { viewer->setEditing(true); - viewer->addEventCallback(SoLocation2Event::getClassTypeId(), - InteractiveScale::getMousePosition, - this); - viewer->addEventCallback(SoButtonEvent::getClassTypeId(), - InteractiveScale::soEventFilter, - this); + viewer->addEventCallback( + SoLocation2Event::getClassTypeId(), + InteractiveScale::getMousePosition, + this + ); + viewer->addEventCallback(SoButtonEvent::getClassTypeId(), InteractiveScale::soEventFilter, this); viewer->setSelectionEnabled(false); viewer->getWidget()->setCursor(QCursor(Qt::CrossCursor)); active = true; @@ -493,12 +497,16 @@ void InteractiveScale::deactivate() points.clear(); measureLabel->deactivate(); viewer->setEditing(false); - viewer->removeEventCallback(SoLocation2Event::getClassTypeId(), - InteractiveScale::getMousePosition, - this); - viewer->removeEventCallback(SoButtonEvent::getClassTypeId(), - InteractiveScale::soEventFilter, - this); + viewer->removeEventCallback( + SoLocation2Event::getClassTypeId(), + InteractiveScale::getMousePosition, + this + ); + viewer->removeEventCallback( + SoButtonEvent::getClassTypeId(), + InteractiveScale::soEventFilter, + this + ); viewer->setSelectionEnabled(true); viewer->getWidget()->setCursor(QCursor(Qt::ArrowCursor)); active = false; @@ -570,8 +578,10 @@ void InteractiveScale::collectPoint(const SbVec3f& pos3d) Q_EMIT enableApplyBtn(); } else { - Base::Console().warning(std::string("Image scale"), - "The second point is too close. Retry!\n"); + Base::Console().warning( + std::string("Image scale"), + "The second point is too close. Retry!\n" + ); } } } diff --git a/src/Gui/TaskView/TaskImage.h b/src/Gui/TaskView/TaskImage.h index e4dbca966c..81b21b6fe7 100644 --- a/src/Gui/TaskView/TaskImage.h +++ b/src/Gui/TaskView/TaskImage.h @@ -36,11 +36,12 @@ class SbVec3f; class SoEventCallback; class EditableDatumLabel; -namespace Gui { +namespace Gui +{ class View3DInventorViewer; class ViewProvider; -class InteractiveScale : public QObject +class InteractiveScale: public QObject { Q_OBJECT Q_DISABLE_COPY(InteractiveScale) @@ -52,7 +53,8 @@ public: bool eventFilter(QObject* object, QEvent* event) override; void activate(); void deactivate(); - bool isActive() const { + bool isActive() const + { return active; } double getScaleFactor() const; @@ -60,9 +62,9 @@ public: void setPlacement(const Base::Placement& plc); private: - static void soEventFilter(void * ud, SoEventCallback * ecb); - static void getMousePosition(void * ud, SoEventCallback * ecb); - void findPointOnImagePlane(SoEventCallback * ecb); + static void soEventFilter(void* ud, SoEventCallback* ecb); + static void getMousePosition(void* ud, SoEventCallback* ecb); + void findPointOnImagePlane(SoEventCallback* ecb); void collectPoint(const SbVec3f&); void setDistance(const SbVec3f&); @@ -85,7 +87,7 @@ private: }; class Ui_TaskImage; -class TaskImage : public QWidget +class TaskImage: public QWidget { Q_OBJECT Q_DISABLE_COPY(TaskImage) @@ -128,7 +130,7 @@ private: double aspectRatio; }; -class TaskImageDialog : public Gui::TaskView::TaskDialog +class TaskImageDialog: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -140,7 +142,8 @@ public: bool accept() override; bool reject() override; - QDialogButtonBox::StandardButtons getStandardButtons() const override { + QDialogButtonBox::StandardButtons getStandardButtons() const override + { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } @@ -148,6 +151,6 @@ private: TaskImage* widget; }; -} +} // namespace Gui -#endif // GUI_TASKIMAGE_H +#endif // GUI_TASKIMAGE_H diff --git a/src/Gui/TaskView/TaskOrientation.cpp b/src/Gui/TaskView/TaskOrientation.cpp index 79cd125683..269f60cee6 100644 --- a/src/Gui/TaskView/TaskOrientation.cpp +++ b/src/Gui/TaskView/TaskOrientation.cpp @@ -103,7 +103,8 @@ void TaskOrientation::restore(const Base::Placement& plm) {Camera::Front, Camera::convert(Camera::Front)}, {Camera::Rear, Camera::convert(Camera::Rear)}, {Camera::Right, Camera::convert(Camera::Right)}, - {Camera::Left, Camera::convert(Camera::Left)}}; + {Camera::Left, Camera::convert(Camera::Left)} + }; Base::Rotation rot = plm.getRotation(); Base::Vector3d pos = plm.getPosition(); @@ -183,7 +184,8 @@ void TaskOrientation::updateIcon() } ui->previewLabel->setPixmap( - Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size())); + Gui::BitmapFactory().pixmapFromSvg(icon.c_str(), ui->previewLabel->size()) + ); } // ---------------------------------------------------------------------------- diff --git a/src/Gui/TaskView/TaskOrientation.h b/src/Gui/TaskView/TaskOrientation.h index ac25492372..414ceb2b9f 100644 --- a/src/Gui/TaskView/TaskOrientation.h +++ b/src/Gui/TaskView/TaskOrientation.h @@ -29,10 +29,11 @@ #include #include -namespace Gui { +namespace Gui +{ class Ui_TaskOrientation; -class TaskOrientation : public QWidget +class TaskOrientation: public QWidget { Q_OBJECT @@ -55,7 +56,7 @@ private: App::WeakPtrT feature; }; -class TaskOrientationDialog : public Gui::TaskView::TaskDialog +class TaskOrientationDialog: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -67,7 +68,8 @@ public: bool accept() override; bool reject() override; - QDialogButtonBox::StandardButtons getStandardButtons() const override { + QDialogButtonBox::StandardButtons getStandardButtons() const override + { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } @@ -75,6 +77,6 @@ private: TaskOrientation* widget; }; -} +} // namespace Gui -#endif // GUI_TASKORIENTATION_H +#endif // GUI_TASKORIENTATION_H diff --git a/src/Gui/TaskView/TaskSelectLinkProperty.cpp b/src/Gui/TaskView/TaskSelectLinkProperty.cpp index d6c9113761..9944ff9426 100644 --- a/src/Gui/TaskView/TaskSelectLinkProperty.cpp +++ b/src/Gui/TaskView/TaskSelectLinkProperty.cpp @@ -37,9 +37,7 @@ using namespace Gui::TaskView; /* TRANSLATOR Gui::TaskView::TaskSelectLinkProperty */ -TaskSelectLinkProperty::TaskSelectLinkProperty(const char* sFilter, - App::Property* prop, - QWidget* parent) +TaskSelectLinkProperty::TaskSelectLinkProperty(const char* sFilter, App::Property* prop, QWidget* parent) : TaskBox(Gui::BitmapFactory().pixmap("mouse_pointer"), tr("edit selection"), true, parent) , Filter(nullptr) , LinkSub(nullptr) @@ -75,8 +73,10 @@ TaskSelectLinkProperty::TaskSelectLinkProperty(const char* sFilter, LinkList = dynamic_cast(prop); } else { - Base::Console().warning("Unknown Link property type in " - "Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()"); + Base::Console().warning( + "Unknown Link property type in " + "Gui::TaskView::TaskSelectLinkProperty::TaskSelectLinkProperty()" + ); } setFilter(sFilter); @@ -213,12 +213,13 @@ void TaskSelectLinkProperty::checkSelectionStatus() ui->listWidget->setPalette(palette); } -void TaskSelectLinkProperty::OnChange(Gui::SelectionSingleton::SubjectType& rCaller, - Gui::SelectionSingleton::MessageType Reason) +void TaskSelectLinkProperty::OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason +) { Q_UNUSED(rCaller); - if (Reason.Type == SelectionChanges::AddSelection - || Reason.Type == SelectionChanges::RmvSelection + if (Reason.Type == SelectionChanges::AddSelection || Reason.Type == SelectionChanges::RmvSelection || Reason.Type == SelectionChanges::SetSelection || Reason.Type == SelectionChanges::ClrSelection) { ui->listWidget->clear(); diff --git a/src/Gui/TaskView/TaskSelectLinkProperty.h b/src/Gui/TaskView/TaskSelectLinkProperty.h index bdbf63f451..88d17c47d2 100644 --- a/src/Gui/TaskView/TaskSelectLinkProperty.h +++ b/src/Gui/TaskView/TaskSelectLinkProperty.h @@ -32,36 +32,41 @@ class Ui_TaskSelectLinkProperty; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; -namespace TaskView { +namespace TaskView +{ /** General Link/Selection editor for the Task view * This can be used as part of a TaskDialog to alter * the content of a LinkProperty by user input/selection. - * If set active it reflects the selection to the Property - * given and acts due the selection filter given to the constructor. + * If set active it reflects the selection to the Property + * given and acts due the selection filter given to the constructor. * It will allow only allowed elements to be selected (SelectionFilter) - * and shows by the background color if the selection criterion is met. + * and shows by the background color if the selection criterion is met. * With the call of accept() or reject() the result gets permanent or * discarded in the given Property. */ -class GuiExport TaskSelectLinkProperty : public TaskBox, public Gui::SelectionSingleton::ObserverType +class GuiExport TaskSelectLinkProperty: public TaskBox, public Gui::SelectionSingleton::ObserverType { Q_OBJECT public: - TaskSelectLinkProperty(const char *,App::Property *,QWidget *parent = nullptr); + TaskSelectLinkProperty(const char*, App::Property*, QWidget* parent = nullptr); ~TaskSelectLinkProperty() override; /// Observer message from the Selection - void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason) override; + void OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason + ) override; /// set the filter criterion (same as in constructor) bool setFilter(const char*); @@ -76,7 +81,10 @@ public: /// send the selection to the Property for e.g. forced recomputation of a feature void sendSelection2Property(); /// checks if the filter is currently met - inline bool isSelectionValid() const {return Filter->match();} + inline bool isSelectionValid() const + { + return Filter->match(); + } private: void setupConnections(); @@ -90,7 +98,7 @@ Q_SIGNALS: void emitSelectionMisfit(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: // checks for selection and set background color and signals @@ -99,19 +107,19 @@ private: QWidget* proxy; Ui_TaskSelectLinkProperty* ui; - // selection filter for the session - Gui::SelectionFilter *Filter; + // selection filter for the session + Gui::SelectionFilter* Filter; // possible used property types, only one is used - App::PropertyLinkSub *LinkSub; - App::PropertyLinkList *LinkList; + App::PropertyLinkSub* LinkSub; + App::PropertyLinkList* LinkList; // string stores the Property at the beginning (for Cancel) std::vector StartValueBuffer; - App::DocumentObject *StartObject; + App::DocumentObject* StartObject; }; -} //namespace TaskView -} //namespace Gui +} // namespace TaskView +} // namespace Gui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Gui/TaskView/TaskSolverMessages.cpp b/src/Gui/TaskView/TaskSolverMessages.cpp index ca1ed596fe..957b16ced8 100644 --- a/src/Gui/TaskView/TaskSolverMessages.cpp +++ b/src/Gui/TaskView/TaskSolverMessages.cpp @@ -37,8 +37,7 @@ using namespace Gui; using namespace Gui::TaskView; namespace sp = std::placeholders; -TaskSolverMessages::TaskSolverMessages(const QPixmap& icon, - const QString& title) +TaskSolverMessages::TaskSolverMessages(const QPixmap& icon, const QString& title) : TaskBox(icon, title, true, nullptr) , ui(new Ui_TaskSolverMessages) { @@ -52,32 +51,47 @@ TaskSolverMessages::TaskSolverMessages(const QPixmap& icon, ui->labelStatus->setOpenExternalLinks(false); // Set up the possible state values for the status label - ui->labelStatus->setParameterGroup( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); - ui->labelStatus->registerState(QStringLiteral("empty"), - palette().windowText().color(), - std::string("EmptySketchMessageColor")); - ui->labelStatus->registerState(QStringLiteral("under_constrained"), - palette().windowText().color(), - std::string("UnderconstrainedMessageColor")); - ui->labelStatus->registerState(QStringLiteral("malformed_constraints"), - QColor("red"), - std::string("MalformedConstraintMessageColor")); - ui->labelStatus->registerState(QStringLiteral("conflicting_constraints"), - QColor("orangered"), - std::string("ConflictingConstraintMessageColor")); - ui->labelStatus->registerState(QStringLiteral("redundant_constraints"), - QColor("red"), - std::string("RedundantConstraintMessageColor")); + ui->labelStatus->setParameterGroup("User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + ui->labelStatus->registerState( + QStringLiteral("empty"), + palette().windowText().color(), + std::string("EmptySketchMessageColor") + ); + ui->labelStatus->registerState( + QStringLiteral("under_constrained"), + palette().windowText().color(), + std::string("UnderconstrainedMessageColor") + ); + ui->labelStatus->registerState( + QStringLiteral("malformed_constraints"), + QColor("red"), + std::string("MalformedConstraintMessageColor") + ); + ui->labelStatus->registerState( + QStringLiteral("conflicting_constraints"), + QColor("orangered"), + std::string("ConflictingConstraintMessageColor") + ); + ui->labelStatus->registerState( + QStringLiteral("redundant_constraints"), + QColor("red"), + std::string("RedundantConstraintMessageColor") + ); ui->labelStatus->registerState( QStringLiteral("partially_redundant_constraints"), QColor("royalblue"), - std::string("PartiallyRedundantConstraintMessageColor")); + std::string("PartiallyRedundantConstraintMessageColor") + ); ui->labelStatus->registerState( - QStringLiteral("solver_failed"), QColor("red"), std::string("SolverFailedMessageColor")); - ui->labelStatus->registerState(QStringLiteral("fully_constrained"), - QColor("green"), - std::string("FullyConstrainedMessageColor")); + QStringLiteral("solver_failed"), + QColor("red"), + std::string("SolverFailedMessageColor") + ); + ui->labelStatus->registerState( + QStringLiteral("fully_constrained"), + QColor("green"), + std::string("FullyConstrainedMessageColor") + ); ui->labelStatusLink->setLaunchExternal(false); @@ -88,18 +102,21 @@ TaskSolverMessages::~TaskSolverMessages() = default; void TaskSolverMessages::setupConnections() { - connect(ui->labelStatusLink, - &Gui::UrlLabel::linkClicked, - this, - &TaskSolverMessages::onLabelStatusLinkClicked); - connect(ui->manualUpdate, - &QToolButton::clicked, - this, - &TaskSolverMessages::onManualUpdateClicked); + connect( + ui->labelStatusLink, + &Gui::UrlLabel::linkClicked, + this, + &TaskSolverMessages::onLabelStatusLinkClicked + ); + connect(ui->manualUpdate, &QToolButton::clicked, this, &TaskSolverMessages::onManualUpdateClicked); } -void TaskSolverMessages::slotSetUp(const QString& state, const QString& msg, const QString& link, - const QString& linkText) +void TaskSolverMessages::slotSetUp( + const QString& state, + const QString& msg, + const QString& link, + const QString& linkText +) { ui->labelStatus->setState(state); ui->labelStatus->setText(msg); @@ -130,4 +147,3 @@ void TaskSolverMessages::createSettingsButtonActions() } #include "moc_TaskSolverMessages.cpp" - diff --git a/src/Gui/TaskView/TaskSolverMessages.h b/src/Gui/TaskView/TaskSolverMessages.h index f79077ab3c..816c209709 100644 --- a/src/Gui/TaskView/TaskSolverMessages.h +++ b/src/Gui/TaskView/TaskSolverMessages.h @@ -44,15 +44,11 @@ class GuiExport TaskSolverMessages: public Gui::TaskView::TaskBox Q_OBJECT public: - explicit TaskSolverMessages(const QPixmap& icon, - const QString& title); + explicit TaskSolverMessages(const QPixmap& icon, const QString& title); ~TaskSolverMessages() override; FC_DISABLE_COPY_MOVE(TaskSolverMessages) - 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(); diff --git a/src/Gui/TaskView/TaskSolverMessages.ui b/src/Gui/TaskView/TaskSolverMessages.ui index e49af60ad3..cfecfbed90 100644 --- a/src/Gui/TaskView/TaskSolverMessages.ui +++ b/src/Gui/TaskView/TaskSolverMessages.ui @@ -99,4 +99,4 @@ - \ No newline at end of file + diff --git a/src/Gui/TaskView/TaskView.cpp b/src/Gui/TaskView/TaskView.cpp index 6f51ae5b98..f103e0b3e1 100644 --- a/src/Gui/TaskView/TaskView.cpp +++ b/src/Gui/TaskView/TaskView.cpp @@ -21,16 +21,16 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -60,11 +60,9 @@ namespace sp = std::placeholders; // TaskWidget //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskWidget::TaskWidget( QWidget *parent) +TaskWidget::TaskWidget(QWidget* parent) : QWidget(parent) -{ - -} +{} TaskWidget::~TaskWidget() = default; @@ -73,43 +71,37 @@ TaskWidget::~TaskWidget() = default; // TaskGroup //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskGroup::TaskGroup(QWidget *parent) +TaskGroup::TaskGroup(QWidget* parent) : QSint::ActionBox(parent) -{ -} +{} -TaskGroup::TaskGroup(const QString & headerText, QWidget *parent) +TaskGroup::TaskGroup(const QString& headerText, QWidget* parent) : QSint::ActionBox(headerText, parent) -{ -} +{} -TaskGroup::TaskGroup(const QPixmap & icon, const QString & headerText, QWidget *parent) +TaskGroup::TaskGroup(const QPixmap& icon, const QString& headerText, QWidget* parent) : QSint::ActionBox(icon, headerText, parent) -{ -} +{} TaskGroup::~TaskGroup() = default; -void TaskGroup::actionEvent (QActionEvent* e) +void TaskGroup::actionEvent(QActionEvent* e) { - QAction *action = e->action(); + QAction* action = e->action(); switch (e->type()) { - case QEvent::ActionAdded: - { + case QEvent::ActionAdded: { this->createItem(action); break; } - case QEvent::ActionChanged: - { + case QEvent::ActionChanged: { break; } - case QEvent::ActionRemoved: - { + case QEvent::ActionRemoved: { // cannot change anything break; } - default: - break; + default: + break; } } @@ -118,24 +110,27 @@ void TaskGroup::actionEvent (QActionEvent* e) // TaskBox //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskBox::TaskBox(QWidget *parent) - : QSint::ActionGroup(parent), wasShown(false) +TaskBox::TaskBox(QWidget* parent) + : QSint::ActionGroup(parent) + , wasShown(false) { // override vertical size policy because otherwise task dialogs // whose needsFullSpace() returns true won't take full space. myGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); } -TaskBox::TaskBox(const QString &title, bool expandable, QWidget *parent) - : QSint::ActionGroup(title, expandable, parent), wasShown(false) +TaskBox::TaskBox(const QString& title, bool expandable, QWidget* parent) + : QSint::ActionGroup(title, expandable, parent) + , wasShown(false) { // override vertical size policy because otherwise task dialogs // whose needsFullSpace() returns true won't take full space. myGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); } -TaskBox::TaskBox(const QPixmap &icon, const QString &title, bool expandable, QWidget *parent) - : QSint::ActionGroup(icon, title, expandable, parent), wasShown(false) +TaskBox::TaskBox(const QPixmap& icon, const QString& title, bool expandable, QWidget* parent) + : QSint::ActionGroup(icon, title, expandable, parent) + , wasShown(false) { // override vertical size policy because otherwise task dialogs // whose needsFullSpace() returns true won't take full space. @@ -168,9 +163,9 @@ void TaskBox::hideGroupBox() { if (!wasShown) { // get approximate height - int h=0; + int h = 0; int ct = groupLayout()->count(); - for (int i=0; iitemAt(i); if (item && item->widget()) { QWidget* w = item->widget(); @@ -211,27 +206,24 @@ bool TaskBox::isGroupVisible() const return myGroup->isVisible(); } -void TaskBox::actionEvent (QActionEvent* e) +void TaskBox::actionEvent(QActionEvent* e) { - QAction *action = e->action(); + QAction* action = e->action(); switch (e->type()) { - case QEvent::ActionAdded: - { + case QEvent::ActionAdded: { auto label = new QSint::ActionLabel(action, this); this->addActionLabel(label, true, false); break; } - case QEvent::ActionChanged: - { + case QEvent::ActionChanged: { break; } - case QEvent::ActionRemoved: - { + case QEvent::ActionRemoved: { // cannot change anything break; } - default: - break; + default: + break; } } @@ -240,10 +232,9 @@ void TaskBox::actionEvent (QActionEvent* e) // TaskPanel //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskPanel::TaskPanel(QWidget *parent) - : QSint::ActionPanel(parent) -{ -} +TaskPanel::TaskPanel(QWidget* parent) + : QSint::ActionPanel(parent) +{} TaskPanel::~TaskPanel() = default; @@ -268,7 +259,7 @@ QSize TaskPanel::minimumSizeHint() const // TaskView //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskView::TaskView(QWidget *parent) +TaskView::TaskView(QWidget* parent) : QWidget(parent) , ActiveDialog(nullptr) , ActiveCtrl(nullptr) @@ -304,34 +295,36 @@ TaskView::TaskView(QWidget *parent) Gui::Selection().Attach(this); - //NOLINTBEGIN - connectApplicationActiveDocument = - App::GetApplication().signalActiveDocument.connect - (std::bind(&Gui::TaskView::TaskView::slotActiveDocument, this, sp::_1)); - connectApplicationDeleteDocument = - App::GetApplication().signalDeleteDocument.connect - (std::bind(&Gui::TaskView::TaskView::slotDeletedDocument, this, sp::_1)); - connectApplicationClosedView = - Gui::Application::Instance->signalCloseView.connect - (std::bind(&Gui::TaskView::TaskView::slotViewClosed, this, sp::_1)); - connectApplicationUndoDocument = - App::GetApplication().signalUndoDocument.connect - (std::bind(&Gui::TaskView::TaskView::slotUndoDocument, this, sp::_1)); - connectApplicationRedoDocument = - App::GetApplication().signalRedoDocument.connect - (std::bind(&Gui::TaskView::TaskView::slotRedoDocument, this, sp::_1)); - connectApplicationInEdit = - Gui::Application::Instance->signalInEdit.connect( - std::bind(&Gui::TaskView::TaskView::slotInEdit, this, sp::_1)); - //NOLINTEND + // NOLINTBEGIN + connectApplicationActiveDocument = App::GetApplication().signalActiveDocument.connect( + std::bind(&Gui::TaskView::TaskView::slotActiveDocument, this, sp::_1) + ); + connectApplicationDeleteDocument = App::GetApplication().signalDeleteDocument.connect( + std::bind(&Gui::TaskView::TaskView::slotDeletedDocument, this, sp::_1) + ); + connectApplicationClosedView = Gui::Application::Instance->signalCloseView.connect( + std::bind(&Gui::TaskView::TaskView::slotViewClosed, this, sp::_1) + ); + connectApplicationUndoDocument = App::GetApplication().signalUndoDocument.connect( + std::bind(&Gui::TaskView::TaskView::slotUndoDocument, this, sp::_1) + ); + connectApplicationRedoDocument = App::GetApplication().signalRedoDocument.connect( + std::bind(&Gui::TaskView::TaskView::slotRedoDocument, this, sp::_1) + ); + connectApplicationInEdit = Gui::Application::Instance->signalInEdit.connect( + std::bind(&Gui::TaskView::TaskView::slotInEdit, this, sp::_1) + ); + // NOLINTEND setShowTaskWatcher(hGrp->GetBool("ShowTaskWatcher", true)); connectShowTaskWatcherSetting = hGrp->Manager()->signalParamChanged.connect( - [this](ParameterGrp *Param, ParameterGrp::ParamType Type, const char *name, const char * value) { - if(Param == hGrp && Type == ParameterGrp::ParamType::FCBool && name && strcmp(name, "ShowTaskWatcher") == 0) { + [this](ParameterGrp* Param, ParameterGrp::ParamType Type, const char* name, const char* value) { + if (Param == hGrp && Type == ParameterGrp::ParamType::FCBool && name + && strcmp(name, "ShowTaskWatcher") == 0) { setShowTaskWatcher(value && *value == '1'); } - }); + } + ); updateWatcher(); } @@ -354,13 +347,15 @@ TaskView::~TaskView() bool TaskView::isEmpty(bool includeWatcher) const { - if (ActiveCtrl || ActiveDialog) + if (ActiveCtrl || ActiveDialog) { return false; + } if (includeWatcher) { - for (auto * watcher : ActiveWatcher) { - if (watcher->shouldShow()) + for (auto* watcher : ActiveWatcher) { + if (watcher->shouldShow()) { return false; + } } } return true; @@ -379,20 +374,19 @@ bool TaskView::event(QEvent* event) if (isLineEdit || isSpinBox) { auto kevent = static_cast(event); Qt::KeyboardModifiers ShiftKeypadModifier = Qt::ShiftModifier | Qt::KeypadModifier; - if (kevent->modifiers() == Qt::NoModifier || - kevent->modifiers() == Qt::ShiftModifier || - kevent->modifiers() == Qt::KeypadModifier || - kevent->modifiers() == ShiftKeypadModifier) { + if (kevent->modifiers() == Qt::NoModifier || kevent->modifiers() == Qt::ShiftModifier + || kevent->modifiers() == Qt::KeypadModifier + || kevent->modifiers() == ShiftKeypadModifier) { switch (kevent->key()) { - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: - kevent->accept(); - default: - break; + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: + kevent->accept(); + default: + break; } } } @@ -410,7 +404,8 @@ void TaskView::keyPressEvent(QKeyEvent* ke) if (pb->isDefault() && pb->isVisible()) { if (pb->isEnabled()) { #if defined(FC_OS_MACOSX) - // #0001354: Crash on using Enter-Key for confirmation of chamfer or fillet entries + // #0001354: Crash on using Enter-Key for confirmation of chamfer or fillet + // entries QPoint pos = QCursor::pos(); QCursor::setPos(pb->parentWidget()->mapToGlobal(pb->pos())); #endif @@ -431,7 +426,8 @@ void TaskView::keyPressEvent(QKeyEvent* ke) if (box->buttonRole(pb) == QDialogButtonBox::RejectRole) { if (pb->isEnabled()) { #if defined(FC_OS_MACOSX) - // #0001354: Crash on using Enter-Key for confirmation of chamfer or fillet entries + // #0001354: Crash on using Enter-Key for confirmation of chamfer or fillet + // entries QPoint pos = QCursor::pos(); QCursor::setPos(pb->parentWidget()->mapToGlobal(pb->pos())); #endif @@ -449,11 +445,11 @@ void TaskView::keyPressEvent(QKeyEvent* ke) // See also ViewProvider::eventCallback auto func = new Gui::TimerFunction(); func->setAutoDelete(true); - Gui::Document* doc = Gui::Application::Instance->getDocument(ActiveDialog->getDocumentName().c_str()); + Gui::Document* doc = Gui::Application::Instance->getDocument( + ActiveDialog->getDocumentName().c_str() + ); if (doc) { - func->setFunction([doc](){ - doc->resetEdit(); - }); + func->setFunction([doc]() { doc->resetEdit(); }); func->singleShot(0); } } @@ -512,8 +508,10 @@ void TaskView::slotDeletedDocument(const App::Document& doc) if (ActiveDialog->isAutoCloseOnDeletedDocument()) { std::string name = ActiveDialog->getDocumentName(); if (name.empty()) { - Base::Console().warning(std::string("TaskView::slotDeletedDocument"), - "No document name set\n"); + Base::Console().warning( + std::string("TaskView::slotDeletedDocument"), + "No document name set\n" + ); } if (name == doc.getName()) { @@ -535,8 +533,7 @@ void TaskView::slotViewClosed(const Gui::MDIView* view) if (ActiveDialog->isAutoCloseOnClosedView()) { const Gui::MDIView* associatedView = ActiveDialog->getAssociatedView(); if (!associatedView) { - Base::Console().warning(std::string("TaskView::slotViewClosed"), - "No view associated\n"); + Base::Console().warning(std::string("TaskView::slotViewClosed"), "No view associated\n"); } if (associatedView == view) { @@ -561,8 +558,10 @@ void TaskView::transactionChangeOnDocument(const App::Document& doc, bool undo) if (ActiveDialog->isAutoCloseOnTransactionChange()) { if (name.empty()) { - Base::Console().warning(std::string("TaskView::transactionChangeOnDocument"), - "No document name set\n"); + Base::Console().warning( + std::string("TaskView::transactionChangeOnDocument"), + "No document name set\n" + ); } if (name == doc.getName()) { @@ -588,29 +587,31 @@ void TaskView::slotRedoDocument(const App::Document& doc) } /// @cond DOXERR -void TaskView::OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason) +void TaskView::OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason +) { Q_UNUSED(rCaller); std::string temp; - if (Reason.Type == SelectionChanges::AddSelection || - Reason.Type == SelectionChanges::ClrSelection || - Reason.Type == SelectionChanges::SetSelection || - Reason.Type == SelectionChanges::RmvSelection) { + if (Reason.Type == SelectionChanges::AddSelection || Reason.Type == SelectionChanges::ClrSelection + || Reason.Type == SelectionChanges::SetSelection + || Reason.Type == SelectionChanges::RmvSelection) { - if (!ActiveDialog) + if (!ActiveDialog) { updateWatcher(); + } } - } /// @endcond -void TaskView::showDialog(TaskDialog *dlg) +void TaskView::showDialog(TaskDialog* dlg) { // if trying to open the same dialog twice nothing needs to be done - if (ActiveDialog == dlg) + if (ActiveDialog == dlg) { return; + } assert(!ActiveDialog); assert(!ActiveCtrl); @@ -642,12 +643,12 @@ void TaskView::showDialog(TaskDialog *dlg) if (dlg->buttonPosition() == TaskDialog::North) { // Add button box to the top of the main layout dialogLayout->insertWidget(0, ActiveCtrl); - for (const auto & it : cont){ + for (const auto& it : cont) { taskPanel->addWidget(it); } } else { - for (const auto & it : cont){ + for (const auto& it : cont) { taskPanel->addWidget(it); } // Add button box to the bottom of the main layout @@ -656,8 +657,9 @@ void TaskView::showDialog(TaskDialog *dlg) taskPanel->setScheme(QSint::ActionPanelScheme::defaultScheme()); - if (!dlg->needsFullSpace()) + if (!dlg->needsFullSpace()) { taskPanel->addStretch(); + } // set as active Dialog ActiveDialog = dlg; @@ -686,8 +688,8 @@ void TaskView::removeDialog() if (ActiveDialog) { // See 'accept' and 'reject' if (ActiveDialog->property("taskview_accept_or_reject").isNull()) { - const std::vector &cont = ActiveDialog->getDialogContent(); - for(const auto & it : cont){ + const std::vector& cont = ActiveDialog->getDialogContent(); + for (const auto& it : cont) { taskPanel->removeWidget(it); } remove = ActiveDialog; @@ -717,7 +719,8 @@ void TaskView::setShowTaskWatcher(bool show) showTaskWatcher = show; if (show) { addTaskWatcher(); - } else { + } + else { clearTaskWatcher(); } } @@ -729,8 +732,9 @@ void TaskView::updateWatcher() if (ActiveWatcher.empty()) { auto panel = Gui::Control().taskPanel(); - if (panel && panel->ActiveWatcher.size()) + if (panel && panel->ActiveWatcher.size()) { takeTaskWatcher(panel); + } } // In case a child of the TaskView has the focus and get hidden we have @@ -738,11 +742,12 @@ void TaskView::updateWatcher() // deleted because otherwise Qt may forward the focus via focusNextPrevChild() // to the mdi area which may switch to another mdi view which is not an // acceptable behaviour. - QWidget *fw = QApplication::focusWidget(); - if (!fw) + QWidget* fw = QApplication::focusWidget(); + if (!fw) { this->setFocus(); + } QPointer fwp = fw; - while (fw && !fw->isWindow()) { + while (fw && !fw->isWindow()) { if (fw == this) { this->setFocus(); break; @@ -751,45 +756,51 @@ void TaskView::updateWatcher() } // add all widgets for all watcher to the task view - for (const auto & it : ActiveWatcher) { + for (const auto& it : ActiveWatcher) { bool match = it->shouldShow(); - std::vector &cont = it->getWatcherContent(); - for (auto & it2 : cont) { - if (match) + std::vector& cont = it->getWatcherContent(); + for (auto& it2 : cont) { + if (match) { it2->show(); - else + } + else { it2->hide(); + } } } // In case the previous widget that had the focus is still visible // give it the focus back. - if (fwp && fwp->isVisible()) + if (fwp && fwp->isVisible()) { fwp->setFocus(); + } triggerMinimumSizeHint(); Q_EMIT taskUpdate(); } -void TaskView::addTaskWatcher(const std::vector &Watcher) +void TaskView::addTaskWatcher(const std::vector& Watcher) { // remove and delete the old set of TaskWatcher - for (TaskWatcher* tw : ActiveWatcher) + for (TaskWatcher* tw : ActiveWatcher) { delete tw; + } ActiveWatcher = Watcher; - if (!ActiveCtrl && !ActiveDialog) + if (!ActiveCtrl && !ActiveDialog) { addTaskWatcher(); + } } -void TaskView::takeTaskWatcher(TaskView *other) +void TaskView::takeTaskWatcher(TaskView* other) { clearTaskWatcher(); ActiveWatcher.swap(other->ActiveWatcher); other->clearTaskWatcher(); - if (isEmpty(false)) + if (isEmpty(false)) { addTaskWatcher(); + } } void TaskView::clearTaskWatcher() @@ -807,14 +818,15 @@ void TaskView::addTaskWatcher() } // add all widgets for all watcher to the task view for (TaskWatcher* tw : ActiveWatcher) { - std::vector &cont = tw->getWatcherContent(); + std::vector& cont = tw->getWatcherContent(); for (QWidget* w : cont) { taskPanel->addWidget(w); } } - if (!ActiveWatcher.empty()) + if (!ActiveWatcher.empty()) { taskPanel->addStretch(); + } updateWatcher(); // Workaround to avoid a crash in Qt. See also @@ -866,10 +878,11 @@ void TaskView::removeTaskWatcher() // deleted because otherwise Qt may forward the focus via focusNextPrevChild() // to the mdi area which may switch to another mdi view which is not an // acceptable behaviour. - QWidget *fw = QApplication::focusWidget(); - if (!fw) + QWidget* fw = QApplication::focusWidget(); + if (!fw) { this->setFocus(); - while (fw && !fw->isWindow()) { + } + while (fw && !fw->isWindow()) { if (fw == this) { this->setFocus(); break; @@ -879,7 +892,7 @@ void TaskView::removeTaskWatcher() // remove all widgets for (TaskWatcher* tw : ActiveWatcher) { - std::vector &cont = tw->getWatcherContent(); + std::vector& cont = tw->getWatcherContent(); for (QWidget* w : cont) { w->hide(); taskPanel->removeWidget(w); @@ -891,7 +904,7 @@ void TaskView::removeTaskWatcher() void TaskView::accept() { - if (!ActiveDialog) { // Protect against segfaults due to out-of-order deletions + if (!ActiveDialog) { // Protect against segfaults due to out-of-order deletions Base::Console().warning("ActiveDialog was null in call to TaskView::accept()\n"); return; } @@ -901,13 +914,14 @@ void TaskView::accept() ActiveDialog->setProperty("taskview_accept_or_reject", true); bool success = ActiveDialog->accept(); ActiveDialog->setProperty("taskview_accept_or_reject", QVariant()); - if (success || ActiveDialog->property("taskview_remove_dialog").isValid()) + if (success || ActiveDialog->property("taskview_remove_dialog").isValid()) { removeDialog(); + } } void TaskView::reject() { - if (!ActiveDialog) { // Protect against segfaults due to out-of-order deletions + if (!ActiveDialog) { // Protect against segfaults due to out-of-order deletions Base::Console().warning("ActiveDialog was null in call to TaskView::reject()\n"); return; } @@ -917,8 +931,9 @@ void TaskView::reject() ActiveDialog->setProperty("taskview_accept_or_reject", true); bool success = ActiveDialog->reject(); ActiveDialog->setProperty("taskview_accept_or_reject", QVariant()); - if (success || ActiveDialog->property("taskview_remove_dialog").isValid()) + if (success || ActiveDialog->property("taskview_remove_dialog").isValid()) { removeDialog(); + } } void TaskView::helpRequested() @@ -926,7 +941,7 @@ void TaskView::helpRequested() ActiveDialog->helpRequested(); } -void TaskView::clicked (QAbstractButton * button) +void TaskView::clicked(QAbstractButton* button) { int id = ActiveCtrl->buttonBox->standardButton(button); ActiveDialog->clicked(id); @@ -940,7 +955,8 @@ void TaskView::clearActionStyle() void TaskView::restoreActionStyle() { - static_cast(QSint::ActionPanelScheme::defaultScheme())->restoreActionStyle(); + static_cast(QSint::ActionPanelScheme::defaultScheme()) + ->restoreActionStyle(); taskPanel->setScheme(QSint::ActionPanelScheme::defaultScheme()); } diff --git a/src/Gui/TaskView/TaskView.h b/src/Gui/TaskView/TaskView.h index ccb79a5392..43767b258b 100644 --- a/src/Gui/TaskView/TaskView.h +++ b/src/Gui/TaskView/TaskView.h @@ -34,74 +34,77 @@ #include "TaskWatcher.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class MDIView; class ControlSingleton; class ViewProviderDocumentObject; -namespace DockWnd{ +namespace DockWnd +{ class ComboView; } -namespace TaskView { +namespace TaskView +{ using Connection = boost::signals2::connection; class TaskEditControl; class TaskDialog; /// Father class of all content in TaskView -class GuiExport TaskContent -{ +class GuiExport TaskContent { -public: - //TaskContent(); - //~TaskContent(); + public : + // TaskContent(); + //~TaskContent(); }; -class GuiExport TaskGroup : public QSint::ActionBox, public TaskContent +class GuiExport TaskGroup: public QSint::ActionBox, public TaskContent { Q_OBJECT public: - explicit TaskGroup(QWidget *parent = nullptr); - explicit TaskGroup(const QString & headerText, QWidget *parent = nullptr); - explicit TaskGroup(const QPixmap & icon, const QString & headerText, QWidget *parent = nullptr); + explicit TaskGroup(QWidget* parent = nullptr); + explicit TaskGroup(const QString& headerText, QWidget* parent = nullptr); + explicit TaskGroup(const QPixmap& icon, const QString& headerText, QWidget* parent = nullptr); ~TaskGroup() override; protected: - void actionEvent (QActionEvent*) override; + void actionEvent(QActionEvent*) override; }; /// Father class of content with header and Icon -class GuiExport TaskBox : public QSint::ActionGroup, public TaskContent +class GuiExport TaskBox: public QSint::ActionGroup, public TaskContent { Q_OBJECT public: /** Constructor. Creates TaskBox without header. - */ - explicit TaskBox(QWidget *parent = nullptr); + */ + explicit TaskBox(QWidget* parent = nullptr); /** Constructor. Creates TaskBox with header's text set to \a title, but with no icon. If \a expandable set to \a true (default), the group can be expanded/collapsed by the user. */ - explicit TaskBox(const QString& title, - bool expandable = true, - QWidget *parent = nullptr); + explicit TaskBox(const QString& title, bool expandable = true, QWidget* parent = nullptr); /** Constructor. Creates TaskBox with header's text set to \a title and icon set to \a icon. If \a expandable set to \a true (default), the group can be expanded/collapsed by the user. */ - explicit TaskBox(const QPixmap& icon, - const QString& title, - bool expandable = true, - QWidget *parent = nullptr); + explicit TaskBox( + const QPixmap& icon, + const QString& title, + bool expandable = true, + QWidget* parent = nullptr + ); QSize minimumSizeHint() const override; ~TaskBox() override; @@ -110,55 +113,57 @@ public: protected: void showEvent(QShowEvent*) override; - void actionEvent (QActionEvent*) override; + void actionEvent(QActionEvent*) override; private: bool wasShown; }; -class GuiExport TaskPanel : public QSint::ActionPanel +class GuiExport TaskPanel: public QSint::ActionPanel { Q_OBJECT public: - explicit TaskPanel(QWidget *parent = nullptr); + explicit TaskPanel(QWidget* parent = nullptr); ~TaskPanel() override; QSize minimumSizeHint() const override; }; /// Father class of content of a Free widget (without header and Icon), shut be an exception! -class GuiExport TaskWidget : public QWidget, public TaskContent +class GuiExport TaskWidget: public QWidget, public TaskContent { Q_OBJECT public: - explicit TaskWidget(QWidget *parent=nullptr); + explicit TaskWidget(QWidget* parent = nullptr); ~TaskWidget() override; }; /** TaskView class - * handles the FreeCAD task view panel. Keeps track of the inserted content elements. - * This elements get injected mostly by the ViewProvider classes of the selected - * DocumentObjects. - */ -class GuiExport TaskView : public QWidget, public Gui::SelectionSingleton::ObserverType + * handles the FreeCAD task view panel. Keeps track of the inserted content elements. + * This elements get injected mostly by the ViewProvider classes of the selected + * DocumentObjects. + */ +class GuiExport TaskView: public QWidget, public Gui::SelectionSingleton::ObserverType { Q_OBJECT public: - explicit TaskView(QWidget *parent = nullptr); + explicit TaskView(QWidget* parent = nullptr); ~TaskView() override; /// Observer message from the Selection - void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason) override; + void OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason + ) override; friend class Gui::DockWnd::ComboView; friend class Gui::ControlSingleton; - void addTaskWatcher(const std::vector &Watcher); + void addTaskWatcher(const std::vector& Watcher); void clearTaskWatcher(); - void takeTaskWatcher(TaskView *other); + void takeTaskWatcher(TaskView* other); bool isEmpty(bool includeWatcher = true) const; @@ -182,7 +187,7 @@ protected Q_SLOTS: void accept(); void reject(); void helpRequested(); - void clicked (QAbstractButton * button); + void clicked(QAbstractButton* button); private: void triggerMinimumSizeHint(); @@ -211,7 +216,7 @@ protected: /// update the visibility of the TaskWatcher accordant to the selection void updateWatcher(); /// used by Gui::Control to register Dialogs - void showDialog(TaskDialog *dlg); + void showDialog(TaskDialog* dlg); // removes the running dialog after accept() or reject() from the TaskView void removeDialog(); @@ -220,8 +225,8 @@ protected: std::vector ActiveWatcher; QSint::ActionPanel* taskPanel; - TaskDialog *ActiveDialog; - TaskEditControl *ActiveCtrl; + TaskDialog* ActiveDialog; + TaskEditControl* ActiveCtrl; bool restoreWidth = false; int currentWidth = 0; ParameterGrp::handle hGrp; @@ -236,7 +241,7 @@ protected: Connection connectShowTaskWatcherSetting; }; -} //namespace TaskView -} //namespace Gui +} // namespace TaskView +} // namespace Gui -#endif // GUI_TASKVIEW_TASKVIEW_H +#endif // GUI_TASKVIEW_TASKVIEW_H diff --git a/src/Gui/TaskView/TaskWatcher.cpp b/src/Gui/TaskView/TaskWatcher.cpp index 699acd99b7..e9b7a0de93 100644 --- a/src/Gui/TaskView/TaskWatcher.cpp +++ b/src/Gui/TaskView/TaskWatcher.cpp @@ -22,7 +22,6 @@ ***************************************************************************/ - #include #include #include @@ -43,10 +42,9 @@ using namespace Gui::TaskView; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskWatcher::TaskWatcher(const char* Filter) - : QObject(nullptr),SelectionFilter(Filter) -{ - -} + : QObject(nullptr) + , SelectionFilter(Filter) +{} TaskWatcher::~TaskWatcher() { @@ -63,10 +61,7 @@ QWidget* TaskWatcher::addTaskBox(QWidget* widget, bool expandable, QWidget* pare return addTaskBox(QPixmap(), widget, expandable, parent); } -QWidget* TaskWatcher::addTaskBox(const QPixmap& icon, - QWidget* widget, - bool expandable, - QWidget* parent) +QWidget* TaskWatcher::addTaskBox(const QPixmap& icon, QWidget* widget, bool expandable, QWidget* parent) { auto taskbox = new Gui::TaskView::TaskBox(icon, widget->windowTitle(), expandable, parent); taskbox->groupLayout()->addWidget(widget); @@ -82,7 +77,7 @@ QWidget* TaskWatcher::addTaskBoxWithoutHeader(QWidget* widget) return taskbox; } -std::vector &TaskWatcher::getWatcherContent() +std::vector& TaskWatcher::getWatcherContent() { return Content; } @@ -99,17 +94,20 @@ bool TaskWatcher::shouldShow() // TaskWatcherCommands //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskWatcherCommands::TaskWatcherCommands(const char* Filter,const char* commands[], - const char* name, const char* pixmap) +TaskWatcherCommands::TaskWatcherCommands( + const char* Filter, + const char* commands[], + const char* name, + const char* pixmap +) : TaskWatcher(Filter) { if (commands) { - CommandManager &mgr = Gui::Application::Instance->commandManager(); - auto tb = new Gui::TaskView::TaskBox - (BitmapFactory().pixmap(pixmap), tr(name), true, nullptr); + CommandManager& mgr = Gui::Application::Instance->commandManager(); + auto tb = new Gui::TaskView::TaskBox(BitmapFactory().pixmap(pixmap), tr(name), true, nullptr); - for (const char** i=commands;*i;i++) { - Command *c = mgr.getCommandByName(*i); + for (const char** i = commands; *i; i++) { + Command* c = mgr.getCommandByName(*i); if (c) { // handled in TaskBox::actionEvent() c->addTo(tb); @@ -136,13 +134,13 @@ bool TaskWatcherCommands::shouldShow() // TaskWatcherCommandsEmptyDoc //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskWatcherCommandsEmptyDoc::TaskWatcherCommandsEmptyDoc(const char* commands[], - const char* name, - const char* pixmap ) - : TaskWatcherCommands(nullptr,commands,name,pixmap) -{ -} - +TaskWatcherCommandsEmptyDoc::TaskWatcherCommandsEmptyDoc( + const char* commands[], + const char* name, + const char* pixmap +) + : TaskWatcherCommands(nullptr, commands, name, pixmap) +{} //==== implementer =========================================================================== @@ -161,12 +159,13 @@ bool TaskWatcherCommandsEmptyDoc::shouldShow() // TaskWatcherCommandsEmptySelection //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskWatcherCommandsEmptySelection::TaskWatcherCommandsEmptySelection(const char* commands[], - const char* name, - const char* pixmap ) - : TaskWatcherCommands(nullptr,commands,name,pixmap) -{ -} +TaskWatcherCommandsEmptySelection::TaskWatcherCommandsEmptySelection( + const char* commands[], + const char* name, + const char* pixmap +) + : TaskWatcherCommands(nullptr, commands, name, pixmap) +{} TaskWatcherCommandsEmptySelection::~TaskWatcherCommandsEmptySelection() = default; diff --git a/src/Gui/TaskView/TaskWatcher.h b/src/Gui/TaskView/TaskWatcher.h index 7c1f627a69..34fd48d52b 100644 --- a/src/Gui/TaskView/TaskWatcher.h +++ b/src/Gui/TaskView/TaskWatcher.h @@ -31,13 +31,15 @@ #include -namespace Gui { -namespace TaskView { +namespace Gui +{ +namespace TaskView +{ class TaskContent; /// Father class of watcher classes -class GuiExport TaskWatcher : public QObject, public Gui::SelectionFilter +class GuiExport TaskWatcher: public QObject, public Gui::SelectionFilter { Q_OBJECT @@ -46,41 +48,44 @@ public: ~TaskWatcher() override; QWidget* addTaskBox(QWidget* widget, bool expandable = true, QWidget* parent = nullptr); - QWidget* addTaskBox(const QPixmap& icon, QWidget* widget, bool expandable = true, QWidget* parent = nullptr); + QWidget* addTaskBox( + const QPixmap& icon, + QWidget* widget, + bool expandable = true, + QWidget* parent = nullptr + ); QWidget* addTaskBoxWithoutHeader(QWidget* widget); - std::vector &getWatcherContent(); + std::vector& getWatcherContent(); public: - /// is called wenn the document or the Selection changes. + /// is called wenn the document or the Selection changes. virtual bool shouldShow(); protected: /// List of TaskBoxes of that dialog std::vector Content; - }; // -------------------------------------------------------------------------- /// Special watcher class for showing commands dependene on the selection -class GuiExport TaskWatcherCommands : public TaskWatcher +class GuiExport TaskWatcherCommands: public TaskWatcher { Q_OBJECT public: - TaskWatcherCommands(const char* Filter,const char* commands[], const char* name, const char* pixmap); + TaskWatcherCommands(const char* Filter, const char* commands[], const char* name, const char* pixmap); public: - /// is called wenn the document or the Selection changes. + /// is called wenn the document or the Selection changes. bool shouldShow() override; - }; // -------------------------------------------------------------------------- /// Special watcher class for showing commands when active document is empty -class GuiExport TaskWatcherCommandsEmptyDoc : public TaskWatcherCommands +class GuiExport TaskWatcherCommandsEmptyDoc: public TaskWatcherCommands { Q_OBJECT @@ -88,15 +93,14 @@ public: TaskWatcherCommandsEmptyDoc(const char* commands[], const char* name, const char* pixmap); public: - /// is called wenn the document or the Selection changes. + /// is called wenn the document or the Selection changes. bool shouldShow() override; - }; // -------------------------------------------------------------------------- /// Special watcher class for showing commands when there is nothing selected -class GuiExport TaskWatcherCommandsEmptySelection : public TaskWatcherCommands +class GuiExport TaskWatcherCommandsEmptySelection: public TaskWatcherCommands { Q_OBJECT @@ -105,14 +109,12 @@ public: ~TaskWatcherCommandsEmptySelection() override; public: - /// is called wenn the document or the Selection changes. + /// is called wenn the document or the Selection changes. bool shouldShow() override; - }; +} // namespace TaskView +} // namespace Gui -} //namespace TaskView -} //namespace Gui - -#endif // GUI_TASKVIEW_TASKWATCHER_H +#endif // GUI_TASKVIEW_TASKWATCHER_H diff --git a/src/Gui/TextDocumentEditorView.cpp b/src/Gui/TextDocumentEditorView.cpp index 040ecbf0a9..d0799c318d 100644 --- a/src/Gui/TextDocumentEditorView.cpp +++ b/src/Gui/TextDocumentEditorView.cpp @@ -39,9 +39,7 @@ using namespace Gui; TYPESYSTEM_SOURCE_ABSTRACT(Gui::TextDocumentEditorView, Gui::MDIView) // NOLINT -TextDocumentEditorView::TextDocumentEditorView(App::TextDocument* txtDoc, - QPlainTextEdit* e, - QWidget* parent) +TextDocumentEditorView::TextDocumentEditorView(App::TextDocument* txtDoc, QPlainTextEdit* e, QWidget* parent) : MDIView(Application::Instance->getDocument(txtDoc->getDocument()), parent) , editor {e} , textDocument {txtDoc} @@ -97,10 +95,10 @@ void TextDocumentEditorView::setupEditor() void TextDocumentEditorView::setupConnection() { // NOLINTBEGIN - textConnection = - textDocument->connectText(std::bind(&TextDocumentEditorView::sourceChanged, this)); - labelConnection = - textDocument->connectLabel(std::bind(&TextDocumentEditorView::labelChanged, this)); + textConnection = textDocument->connectText(std::bind(&TextDocumentEditorView::sourceChanged, this)); + labelConnection = textDocument->connectLabel( + std::bind(&TextDocumentEditorView::labelChanged, this) + ); // NOLINTEND } diff --git a/src/Gui/TextDocumentEditorView.h b/src/Gui/TextDocumentEditorView.h index 689b294193..5a8bbb097a 100644 --- a/src/Gui/TextDocumentEditorView.h +++ b/src/Gui/TextDocumentEditorView.h @@ -39,9 +39,7 @@ class GuiExport TextDocumentEditorView: public MDIView TYPESYSTEM_HEADER_WITH_OVERRIDE(); // NOLINT public: - TextDocumentEditorView(App::TextDocument* textDocument, - QPlainTextEdit* editor, - QWidget* parent); + TextDocumentEditorView(App::TextDocument* textDocument, QPlainTextEdit* editor, QWidget* parent); ~TextDocumentEditorView() override; const char* getName() const override { diff --git a/src/Gui/TextEdit.cpp b/src/Gui/TextEdit.cpp index 49663b9b0f..beaa6170e3 100644 --- a/src/Gui/TextEdit.cpp +++ b/src/Gui/TextEdit.cpp @@ -21,14 +21,13 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -45,7 +44,9 @@ using namespace Gui; * Constructs a TextEdit which is a child of 'parent'. */ TextEdit::TextEdit(QWidget* parent) - : QPlainTextEdit(parent), cursorPosition(0), listBox(nullptr) + : QPlainTextEdit(parent) + , cursorPosition(0) + , listBox(nullptr) { // create the window for call tips callTipsList = new CallTipsList(this); @@ -54,11 +55,11 @@ TextEdit::TextEdit(QWidget* parent) callTipsList->setLineWidth(2); installEventFilter(callTipsList); viewport()->installEventFilter(callTipsList); - callTipsList->setSelectionMode( QAbstractItemView::SingleSelection ); + callTipsList->setSelectionMode(QAbstractItemView::SingleSelection); callTipsList->hide(); - //Note: Set the correct context to this shortcut as we may use several instances of this - //class at a time + // Note: Set the correct context to this shortcut as we may use several instances of this + // class at a time auto shortcut = new QShortcut(this); shortcut->setKey(QKeySequence(QStringLiteral("CTRL+Space"))); shortcut->setContext(Qt::WidgetShortcut); @@ -98,8 +99,8 @@ void TextEdit::keyPressEvent(QKeyEvent* e) QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfWord); // the cursor has moved to outside the word prefix - if (cursor.position() < cursorPosition-wordPrefix.length() || - cursor.position() > cursorPosition) { + if (cursor.position() < cursorPosition - wordPrefix.length() + || cursor.position() > cursorPosition) { listBox->hide(); return; } @@ -109,17 +110,17 @@ void TextEdit::keyPressEvent(QKeyEvent* e) } - if (e->key() == Qt::Key_Period) - { + if (e->key() == Qt::Key_Period) { // QTextCursor cursor = this->textCursor(); // In Qt 4.8 there is a strange behaviour because when pressing ":" // then key is also set to 'Period' instead of 'Colon'. So we have // to make sure we only handle the period. if (e->text() == QLatin1String(".")) { // analyse context and show available call tips - // TODO: idk why we need to remove the . from the input string (- 1). This shouldn't be needed + // TODO: idk why we need to remove the . from the input string (- 1). This shouldn't be + // needed QString textToBeCompleted = getInputString().left(getInputStringPosition() - 1); - callTipsList->showTips( textToBeCompleted ); + callTipsList->showTips(textToBeCompleted); } } @@ -130,11 +131,13 @@ void TextEdit::keyPressEvent(QKeyEvent* e) } } -int TextEdit::getInputStringPosition() { +int TextEdit::getInputStringPosition() +{ return textCursor().positionInBlock(); } -QString TextEdit::getInputString() { +QString TextEdit::getInputString() +{ return textCursor().block().text(); } @@ -155,31 +158,37 @@ void TextEdit::wheelEvent(QWheelEvent* e) void TextEdit::complete() { QTextBlock block = textCursor().block(); - if (!block.isValid()) + if (!block.isValid()) { return; - int cursorPos = textCursor().position()-block.position(); + } + int cursorPos = textCursor().position() - block.position(); QString para = block.text(); int wordStart = cursorPos; - while (wordStart > 0 && para[wordStart - 1].isLetterOrNumber()) + while (wordStart > 0 && para[wordStart - 1].isLetterOrNumber()) { --wordStart; + } wordPrefix = para.mid(wordStart, cursorPos - wordStart); - if (wordPrefix.isEmpty()) + if (wordPrefix.isEmpty()) { return; + } QStringList list = toPlainText().split(QRegularExpression(QLatin1String("\\W+"))); QMap map; QStringList::Iterator it = list.begin(); while (it != list.end()) { - if ((*it).startsWith(wordPrefix) && (*it).length() > wordPrefix.length()) + if ((*it).startsWith(wordPrefix) && (*it).length() > wordPrefix.length()) { map[(*it).toLower()] = *it; + } ++it; } if (map.count() == 1) { insertPlainText((*map.begin()).mid(wordPrefix.length())); - } else if (map.count() > 1) { - if (!listBox) + } + else if (map.count() > 1) { + if (!listBox) { createListBox(); + } listBox->clear(); listBox->addItems(map.values()); listBox->setFont(QFont(font().family(), 8)); @@ -196,8 +205,8 @@ void TextEdit::complete() } // Add an offset - w += 2*listBox->frameWidth(); - h += 2*listBox->frameWidth(); + w += 2 * listBox->frameWidth(); + h += 2 * listBox->frameWidth(); // get the start position of the word prefix QTextCursor cursor = textCursor(); @@ -208,16 +217,19 @@ void TextEdit::complete() int boxH = h; // Decide whether to show downstairs or upstairs - if (posY > viewport()->height()/2) { - h = qMin(qMin(h,posY), 250); - if (h < boxH) + if (posY > viewport()->height() / 2) { + h = qMin(qMin(h, posY), 250); + if (h < boxH) { w += style()->pixelMetric(QStyle::PM_ScrollBarExtent); - listBox->setGeometry(posX,posY-h, w, h); - } else { - h = qMin(qMin(h,viewport()->height()-fontMetrics().height()-posY), 250); - if (h < boxH) + } + listBox->setGeometry(posX, posY - h, w, h); + } + else { + h = qMin(qMin(h, viewport()->height() - fontMetrics().height() - posY), 250); + if (h < boxH) { w += style()->pixelMetric(QStyle::PM_ScrollBarExtent); - listBox->setGeometry(posX, posY+fontMetrics().height(), w, h); + } + listBox->setGeometry(posX, posY + fontMetrics().height(), w, h); } listBox->setCurrentRow(0); @@ -238,18 +250,19 @@ void TextEdit::createListBox() listBox->setLineWidth(2); installEventFilter(listBox); viewport()->installEventFilter(listBox); - listBox->setSelectionMode( QAbstractItemView::SingleSelection ); + listBox->setSelectionMode(QAbstractItemView::SingleSelection); listBox->hide(); } // ------------------------------------------------------------------------------ -namespace Gui { +namespace Gui +{ struct TextEditorP { bool highlightLine = true; bool visibleMarker = true; - QMap colormap; // Color map + QMap colormap; // Color map TextEditorP() { colormap[QLatin1String("Text")] = qApp->palette().windowText().color(); @@ -266,17 +279,19 @@ struct TextEditorP colormap[QLatin1String("Operator")] = QColor(160, 160, 164); colormap[QLatin1String("Python output")] = QColor(170, 170, 127); colormap[QLatin1String("Python error")] = Qt::red; - colormap[QLatin1String("Current line highlight")] = QColor(224,224,224); + colormap[QLatin1String("Current line highlight")] = QColor(224, 224, 224); } }; -} // namespace Gui +} // namespace Gui /** * Constructs a TextEditor which is a child of 'parent' and does the * syntax highlighting for the Python language. */ TextEditor::TextEditor(QWidget* parent) - : TextEdit(parent), WindowParameter("Editor"), highlighter(nullptr) + : TextEdit(parent) + , WindowParameter("Editor") + , highlighter(nullptr) { d = new TextEditorP(); lineNumberArea = new LineMarker(this); @@ -286,17 +301,14 @@ TextEditor::TextEditor(QWidget* parent) setFont(serifFont); ParameterGrp::handle hPrefGrp = getWindowParameter(); - hPrefGrp->Attach( this ); + hPrefGrp->Attach(this); // set colors and font hPrefGrp->NotifyAll(); - connect(this, &QPlainTextEdit::cursorPositionChanged, - this, &TextEditor::highlightCurrentLine); - connect(this, &QPlainTextEdit::blockCountChanged, - this, &TextEditor::updateLineNumberAreaWidth); - connect(this, &QPlainTextEdit::updateRequest, - this, &TextEditor::updateLineNumberArea); + connect(this, &QPlainTextEdit::cursorPositionChanged, this, &TextEditor::highlightCurrentLine); + connect(this, &QPlainTextEdit::blockCountChanged, this, &TextEditor::updateLineNumberAreaWidth); + connect(this, &QPlainTextEdit::updateRequest, this, &TextEditor::updateLineNumberArea); updateLineNumberAreaWidth(0); highlightCurrentLine(); @@ -342,7 +354,7 @@ void TextEditor::updateLineNumberAreaWidth(int /* newBlockCount */) setViewportMargins(left, 0, 0, 0); } -void TextEditor::updateLineNumberArea(const QRect &rect, int dy) +void TextEditor::updateLineNumberArea(const QRect& rect, int dy) { if (isVisibleLineNumbers()) { if (dy) { @@ -358,7 +370,7 @@ void TextEditor::updateLineNumberArea(const QRect &rect, int dy) } } -void TextEditor::resizeEvent(QResizeEvent *e) +void TextEditor::resizeEvent(QResizeEvent* e) { QPlainTextEdit::resizeEvent(e); @@ -379,9 +391,9 @@ void TextEditor::highlightCurrentLine() unsigned int col = Base::Color::asPackedRGB(lineColor); ParameterGrp::handle hPrefGrp = getWindowParameter(); auto value = static_cast(col); - value = hPrefGrp->GetUnsigned( "Current line highlight", value); + value = hPrefGrp->GetUnsigned("Current line highlight", value); col = static_cast(value); - lineColor.setRgb((col>>24)&0xff, (col>>16)&0xff, (col>>8)&0xff); + lineColor.setRgb((col >> 24) & 0xff, (col >> 16) & 0xff, (col >> 8) & 0xff); selection.format.setBackground(lineColor); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = textCursor(); @@ -400,18 +412,18 @@ void TextEditor::drawMarker(int line, int x, int y, QPainter* p) Q_UNUSED(p); } -void TextEditor::lineNumberAreaPaintEvent(QPaintEvent *event) +void TextEditor::lineNumberAreaPaintEvent(QPaintEvent* event) { if (!isVisibleLineNumbers()) { return; } QPainter painter(lineNumberArea); - //painter.fillRect(event->rect(), Qt::lightGray); + // painter.fillRect(event->rect(), Qt::lightGray); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); - int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); - int bottom = top + (int) blockBoundingRect(block).height(); + int top = (int)blockBoundingGeometry(block).translated(contentOffset()).top(); + int bottom = top + (int)blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { @@ -419,14 +431,13 @@ void TextEditor::lineNumberAreaPaintEvent(QPaintEvent *event) QPalette pal = palette(); QColor color = pal.windowText().color(); painter.setPen(color); - painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), - Qt::AlignRight, number); + painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number); drawMarker(blockNumber + 1, 1, top, &painter); } block = block.next(); top = bottom; - bottom = top + (int) blockBoundingRect(block).height(); + bottom = top + (int)blockBoundingRect(block).height(); ++blockNumber; } } @@ -438,7 +449,7 @@ void TextEditor::setSyntaxHighlighter(SyntaxHighlighter* sh) } /** Sets the font, font size and tab size of the editor. */ -void TextEditor::OnChange(Base::Subject &rCaller,const char* sReason) +void TextEditor::OnChange(Base::Subject& rCaller, const char* sReason) { Q_UNUSED(rCaller); ParameterGrp::handle hPrefGrp = getWindowParameter(); @@ -455,7 +466,7 @@ void TextEditor::OnChange(Base::Subject &rCaller,const char* sReaso font.setPointSize(fontSize); } else { - font = QFont (QString::fromStdString(fontName), fontSize); + font = QFont(QString::fromStdString(fontName), fontSize); } setFont(font); lineNumberArea->setFont(font); @@ -468,9 +479,10 @@ void TextEditor::OnChange(Base::Subject &rCaller,const char* sReaso auto value = static_cast(col); value = hPrefGrp->GetUnsigned(sReason, value); col = static_cast(value); - color.setRgb((col>>24)&0xff, (col>>16)&0xff, (col>>8)&0xff); - if (this->highlighter) + color.setRgb((col >> 24) & 0xff, (col >> 16) & 0xff, (col >> 8) & 0xff); + if (this->highlighter) { this->highlighter->setColor(QLatin1String(sReason), color); + } } } @@ -494,11 +506,9 @@ void TextEditor::OnChange(Base::Subject &rCaller,const char* sReaso // ------------------------------------------------------------------------------ -PythonTextEditor::PythonTextEditor(QWidget *parent) +PythonTextEditor::PythonTextEditor(QWidget* parent) : TextEditor(parent) -{ - -} +{} PythonTextEditor::~PythonTextEditor() = default; @@ -512,11 +522,12 @@ void PythonTextEditor::prepend(const QString& str) cursor.beginEditBlock(); for (block = document()->begin(); block.isValid(); block = block.next()) { int pos = block.position(); - int off = block.length()-1; + int off = block.length() - 1; // at least one char of the block is part of the selection - if ( pos >= selStart || pos+off >= selStart) { - if ( pos+1 > selEnd ) - break; // end of selection reached + if (pos >= selStart || pos + off >= selStart) { + if (pos + 1 > selEnd) { + break; // end of selection reached + } cursor.setPosition(block.position()); cursor.insertText(str); selEnd += str.length(); @@ -535,11 +546,12 @@ void PythonTextEditor::remove(const QString& str) cursor.beginEditBlock(); for (block = document()->begin(); block.isValid(); block = block.next()) { int pos = block.position(); - int off = block.length()-1; + int off = block.length() - 1; // at least one char of the block is part of the selection - if ( pos >= selStart || pos+off >= selStart) { - if ( pos+1 > selEnd ) - break; // end of selection reached + if (pos >= selStart || pos + off >= selStart) { + if (pos + 1 > selEnd) { + break; // end of selection reached + } QString text = block.text(); if (text.startsWith(str)) { cursor.setPosition(block.position()); @@ -554,14 +566,13 @@ void PythonTextEditor::remove(const QString& str) cursor.endEditBlock(); } -void PythonTextEditor::keyPressEvent (QKeyEvent * e) +void PythonTextEditor::keyPressEvent(QKeyEvent* e) { - if ( e->key() == Qt::Key_Tab ) { + if (e->key() == Qt::Key_Tab) { ParameterGrp::handle hPrefGrp = getWindowParameter(); bool space = hPrefGrp->GetBool("Spaces", true); - int indent = hPrefGrp->GetInt( "IndentSize", 4 ); - QString ch = space ? QString(indent, QLatin1Char(' ')) - : QStringLiteral("\t"); + int indent = hPrefGrp->GetInt("IndentSize", 4); + QString ch = space ? QString(indent, QLatin1Char(' ')) : QStringLiteral("\t"); QTextCursor cursor = textCursor(); if (!cursor.hasSelection()) { @@ -569,7 +580,8 @@ void PythonTextEditor::keyPressEvent (QKeyEvent * e) cursor.beginEditBlock(); cursor.insertText(ch); cursor.endEditBlock(); - } else { + } + else { prepend(ch); } @@ -577,30 +589,29 @@ void PythonTextEditor::keyPressEvent (QKeyEvent * e) } else if (e->key() == Qt::Key_Backtab) { QTextCursor cursor = textCursor(); - if (!cursor.hasSelection()) - return; // Shift+Tab should not do anything + if (!cursor.hasSelection()) { + return; // Shift+Tab should not do anything + } // If some text is selected we remove a leading tab or // spaces from each selected block ParameterGrp::handle hPrefGrp = getWindowParameter(); bool space = hPrefGrp->GetBool("Spaces", true); - int indent = hPrefGrp->GetInt( "IndentSize", 4 ); - QString ch = space ? QString(indent, QLatin1Char(' ')) - : QStringLiteral("\t"); + int indent = hPrefGrp->GetInt("IndentSize", 4); + QString ch = space ? QString(indent, QLatin1Char(' ')) : QStringLiteral("\t"); // if possible remove one tab or several spaces remove(ch); return; } - TextEditor::keyPressEvent( e ); + TextEditor::keyPressEvent(e); } - LineMarker::LineMarker(TextEditor* editor) - : QWidget(editor), textEditor(editor) -{ -} + : QWidget(editor) + , textEditor(editor) +{} LineMarker::~LineMarker() = default; @@ -617,23 +628,31 @@ void LineMarker::paintEvent(QPaintEvent* e) // ------------------------------------------------------------------------------ CompletionList::CompletionList(QPlainTextEdit* parent) - : QListWidget(parent), textEdit(parent) + : QListWidget(parent) + , textEdit(parent) { // make the user assume that the widget is active QPalette pal = parent->palette(); - pal.setColor(QPalette::Inactive, QPalette::Highlight, pal.color(QPalette::Active, QPalette::Highlight)); - pal.setColor(QPalette::Inactive, QPalette::HighlightedText, pal.color(QPalette::Active, QPalette::HighlightedText)); - parent->setPalette( pal ); + pal.setColor( + QPalette::Inactive, + QPalette::Highlight, + pal.color(QPalette::Active, QPalette::Highlight) + ); + pal.setColor( + QPalette::Inactive, + QPalette::HighlightedText, + pal.color(QPalette::Active, QPalette::HighlightedText) + ); + parent->setPalette(pal); - connect(this, &CompletionList::itemActivated, - this, &CompletionList::completionItem); + connect(this, &CompletionList::itemActivated, this, &CompletionList::completionItem); } CompletionList::~CompletionList() = default; void CompletionList::findCurrentWord(const QString& wordPrefix) { - for (int i=0; itext(); if (text.startsWith(wordPrefix)) { setCurrentRow(i); @@ -641,41 +660,50 @@ void CompletionList::findCurrentWord(const QString& wordPrefix) } } - if (currentItem()) + if (currentItem()) { currentItem()->setSelected(false); + } } /** * Get all incoming events of the text edit and redirect some of them, like key up and * down, mouse press events, ... to the widget itself. */ -bool CompletionList::eventFilter(QObject * watched, QEvent * event) +bool CompletionList::eventFilter(QObject* watched, QEvent* event) { if (isVisible() && watched == textEdit->viewport()) { - if (event->type() == QEvent::MouseButtonPress) + if (event->type() == QEvent::MouseButtonPress) { hide(); - } else if (isVisible() && watched == textEdit) { + } + } + else if (isVisible() && watched == textEdit) { if (event->type() == QEvent::KeyPress) { auto ke = static_cast(event); if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) { keyPressEvent(ke); return true; - } else if (ke->key() == Qt::Key_PageUp || ke->key() == Qt::Key_PageDown) { + } + else if (ke->key() == Qt::Key_PageUp || ke->key() == Qt::Key_PageDown) { keyPressEvent(ke); return true; - } else if (ke->key() == Qt::Key_Escape) { + } + else if (ke->key() == Qt::Key_Escape) { hide(); return true; - } else if (ke->key() == Qt::Key_Space) { + } + else if (ke->key() == Qt::Key_Space) { hide(); return false; - } else if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) { + } + else if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) { Q_EMIT itemActivated(currentItem()); return true; } - } else if (event->type() == QEvent::FocusOut) { - if (!hasFocus()) + } + else if (event->type() == QEvent::FocusOut) { + if (!hasFocus()) { hide(); + } } } @@ -686,14 +714,14 @@ bool CompletionList::eventFilter(QObject * watched, QEvent * event) * If an item was chosen (either by clicking or pressing enter) the rest of the word is completed. * The listbox is closed without destroying it. */ -void CompletionList::completionItem(QListWidgetItem *item) +void CompletionList::completionItem(QListWidgetItem* item) { hide(); QString text = item->text(); QTextCursor cursor = textEdit->textCursor(); cursor.movePosition(QTextCursor::StartOfWord); cursor.movePosition(QTextCursor::EndOfWord, QTextCursor::KeepAnchor); - cursor.insertText( text ); + cursor.insertText(text); textEdit->ensureCursorVisible(); } diff --git a/src/Gui/TextEdit.h b/src/Gui/TextEdit.h index 748ce8c986..8ba230b6b4 100644 --- a/src/Gui/TextEdit.h +++ b/src/Gui/TextEdit.h @@ -32,20 +32,21 @@ #include "Window.h" -namespace Gui { +namespace Gui +{ class CompletionBox; class SyntaxHighlighter; /** * Completion is a means by which an editor automatically completes words that the user is typing. - * For example, in a code editor, a programmer might type "sur", then Tab, and the editor will complete - * the word the programmer was typing so that "sur" is replaced by "surnameLineEdit". This is very - * useful for text that contains long words or variable names. The completion mechanism usually works - * by looking at the existing text to see if any words begin with what the user has typed, and in most - * editors completion is invoked by a special key sequence. + * For example, in a code editor, a programmer might type "sur", then Tab, and the editor will + * complete the word the programmer was typing so that "sur" is replaced by "surnameLineEdit". This + * is very useful for text that contains long words or variable names. The completion mechanism + * usually works by looking at the existing text to see if any words begin with what the user has + * typed, and in most editors completion is invoked by a special key sequence. * - * TextEdit can detect a special key sequence to invoke the completion mechanism, and can handle three - * different situations: + * TextEdit can detect a special key sequence to invoke the completion mechanism, and can handle + * three different situations: * \li There are no possible completions. * \li There is a single possible completion. * \li There are two or more possible completions. @@ -54,12 +55,12 @@ class SyntaxHighlighter; * @author Werner Mayer */ class CompletionList; -class GuiExport TextEdit : public QPlainTextEdit +class GuiExport TextEdit: public QPlainTextEdit { Q_OBJECT public: - explicit TextEdit(QWidget *parent = nullptr); + explicit TextEdit(QWidget* parent = nullptr); ~TextEdit() override; //! Get the cursor position of the current line being edited @@ -76,7 +77,7 @@ Q_SIGNALS: void findPrevious(); protected: - void keyPressEvent(QKeyEvent *) override; + void keyPressEvent(QKeyEvent*) override; void wheelEvent(QWheelEvent* e) override; CallTipsList* callTipsList = nullptr; @@ -86,23 +87,23 @@ private: private: QString wordPrefix; int cursorPosition; - CompletionList *listBox; + CompletionList* listBox; }; class SyntaxHighlighter; -class GuiExport TextEditor : public TextEdit, public WindowParameter +class GuiExport TextEditor: public TextEdit, public WindowParameter { Q_OBJECT public: - explicit TextEditor(QWidget *parent = nullptr); + explicit TextEditor(QWidget* parent = nullptr); ~TextEditor() override; void setSyntaxHighlighter(SyntaxHighlighter*); - void OnChange(Base::Subject &rCaller,const char* rcReason) override; + void OnChange(Base::Subject& rCaller, const char* rcReason) override; /** Draw a beam in the line where the cursor is. */ - void lineNumberAreaPaintEvent(QPaintEvent* ); + void lineNumberAreaPaintEvent(QPaintEvent*); int lineNumberAreaWidth(); void setVisibleLineNumbers(bool value); bool isVisibleLineNumbers() const; @@ -111,13 +112,15 @@ public: private Q_SLOTS: void updateLineNumberAreaWidth(int newBlockCount); - void updateLineNumberArea(const QRect &, int); + void updateLineNumberArea(const QRect&, int); void highlightCurrentLine(); protected: void resizeEvent(QResizeEvent* e) override; QWidget* getMarker() const - { return lineNumberArea; } + { + return lineNumberArea; + } virtual void drawMarker(int line, int x, int y, QPainter*); private: @@ -132,11 +135,11 @@ private: * python editor and the python console where we handle * the tab key conversion to spaces, depending on user settings */ -class GuiExport PythonTextEditor : public TextEditor +class GuiExport PythonTextEditor: public TextEditor { Q_OBJECT public: - explicit PythonTextEditor(QWidget *parent = nullptr); + explicit PythonTextEditor(QWidget* parent = nullptr); ~PythonTextEditor() override; public Q_SLOTS: @@ -150,11 +153,11 @@ public Q_SLOTS: void remove(const QString& str); protected: - void keyPressEvent(QKeyEvent *) override; + void keyPressEvent(QKeyEvent*) override; }; -class LineMarker : public QWidget +class LineMarker: public QWidget { Q_OBJECT @@ -165,10 +168,10 @@ public: QSize sizeHint() const override; protected: - void paintEvent (QPaintEvent *) override; + void paintEvent(QPaintEvent*) override; private: - TextEditor *textEditor; + TextEditor* textEditor; }; /** @@ -176,7 +179,7 @@ private: * an accelerator to complete the current word they are typing in. * @author Werner Mayer */ -class CompletionList : public QListWidget +class CompletionList: public QListWidget { Q_OBJECT @@ -189,15 +192,15 @@ public: void findCurrentWord(const QString&); protected: - bool eventFilter(QObject *, QEvent *) override; + bool eventFilter(QObject*, QEvent*) override; private Q_SLOTS: - void completionItem(QListWidgetItem *item); + void completionItem(QListWidgetItem* item); private: QPlainTextEdit* textEdit; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_TEXTEDIT_H +#endif // GUI_TEXTEDIT_H diff --git a/src/Gui/TextureMapping.cpp b/src/Gui/TextureMapping.cpp index f56bc735a8..ae4d04c030 100644 --- a/src/Gui/TextureMapping.cpp +++ b/src/Gui/TextureMapping.cpp @@ -21,13 +21,12 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -46,14 +45,20 @@ using namespace Gui::Dialog; /* TRANSLATOR Gui::Dialog::TextureMapping */ TextureMapping::TextureMapping(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), grp(nullptr), tex(nullptr), env(nullptr) + : QDialog(parent, fl) + , grp(nullptr) + , tex(nullptr) + , env(nullptr) { ui = new Ui_TextureMapping(); ui->setupUi(this); - connect(ui->fileChooser, &FileChooser::fileNameSelected, - this, &TextureMapping::onFileChooserFileNameSelected); - connect(ui->checkEnv, &QCheckBox::toggled, - this, &TextureMapping::onCheckEnvToggled); + connect( + ui->fileChooser, + &FileChooser::fileNameSelected, + this, + &TextureMapping::onFileChooserFileNameSelected + ); + connect(ui->checkEnv, &QCheckBox::toggled, this, &TextureMapping::onCheckEnvToggled); ui->checkGlobal->hide(); @@ -63,7 +68,7 @@ TextureMapping::TextureMapping(QWidget* parent, Qt::WindowFlags fl) // add all supported QImage formats QStringList formats; QList qtformats = QImageReader::supportedImageFormats(); - for (const auto & it : qtformats) { + for (const auto& it : qtformats) { formats << QStringLiteral("*.%1").arg(QLatin1String(it)); } @@ -98,15 +103,16 @@ void TextureMapping::reject() { if (this->grp) { this->grp->removeChild(this->tex); - if (this->grp->findChild(this->env) > -1) + if (this->grp->findChild(this->env) > -1) { this->grp->removeChild(this->env); + } this->grp->unref(); } QDialog::reject(); } -void TextureMapping::changeEvent(QEvent *e) +void TextureMapping::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -116,7 +122,7 @@ void TextureMapping::changeEvent(QEvent *e) } } -void TextureMapping::keyPressEvent(QKeyEvent *e) +void TextureMapping::keyPressEvent(QKeyEvent* e) { // The texture mapping dialog is embedded into a task panel // which is a parent widget and will handle the event @@ -132,7 +138,11 @@ void TextureMapping::onFileChooserFileNameSelected(const QString& s) // there is a check to report the last selected file name (which might // be an empty string) only once. if (fileName != s) { - QMessageBox::warning(this, tr("No image"), tr("The specified file is not a valid image file.")); + QMessageBox::warning( + this, + tr("No image"), + tr("The specified file is not a valid image file.") + ); fileName = s; } return; @@ -146,8 +156,9 @@ void TextureMapping::onFileChooserFileNameSelected(const QString& s) this->grp = static_cast(view->getViewer()->getSceneGraph()); this->grp->ref(); this->grp->insertChild(this->tex, 1); - if (ui->checkEnv->isChecked()) + if (ui->checkEnv->isChecked()) { this->grp->insertChild(this->env, 2); + } } } } @@ -160,16 +171,17 @@ void TextureMapping::onFileChooserFileNameSelected(const QString& s) SoSFImage texture; Gui::BitmapFactory().convert(image, texture); this->tex->image = texture; - //this->tex->filename = (const char*)s.toUtf8(); + // this->tex->filename = (const char*)s.toUtf8(); App::GetApplication().Config()["TextureImage"] = (const char*)s.toUtf8(); } void TextureMapping::onCheckEnvToggled(bool b) { - if (!this->grp) + if (!this->grp) { return; + } if (b) { - this->grp->insertChild(this->env,2); + this->grp->insertChild(this->env, 2); } else { this->grp->removeChild(this->env); diff --git a/src/Gui/TextureMapping.h b/src/Gui/TextureMapping.h index 4d379a6a95..dc893b0d44 100644 --- a/src/Gui/TextureMapping.h +++ b/src/Gui/TextureMapping.h @@ -31,11 +31,13 @@ class SoGroup; class SoTexture2; class SoTextureCoordinateEnvironment; -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class Ui_TextureMapping; -class GuiExport TextureMapping : public QDialog +class GuiExport TextureMapping: public QDialog { Q_OBJECT @@ -50,8 +52,8 @@ private: void onCheckEnvToggled(bool); protected: - void changeEvent(QEvent *e) override; - void keyPressEvent(QKeyEvent *e) override; + void changeEvent(QEvent* e) override; + void keyPressEvent(QKeyEvent* e) override; private: SoGroup* grp; @@ -61,7 +63,7 @@ private: Ui_TextureMapping* ui; }; -class TaskTextureMapping : public Gui::TaskView::TaskDialog +class TaskTextureMapping: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -74,13 +76,15 @@ public: bool reject() override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Close; } + { + return QDialogButtonBox::Close; + } private: TextureMapping* dialog; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_TEXTUREMAPPING_H +#endif // GUI_TEXTUREMAPPING_H diff --git a/src/Gui/Thumbnail.cpp b/src/Gui/Thumbnail.cpp index 32f54dc8a3..9c324dfc45 100644 --- a/src/Gui/Thumbnail.cpp +++ b/src/Gui/Thumbnail.cpp @@ -21,13 +21,12 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -41,9 +40,9 @@ using namespace Gui; -Thumbnail::Thumbnail(int s) : size(s) -{ -} +Thumbnail::Thumbnail(int s) + : size(s) +{} Thumbnail::~Thumbnail() = default; @@ -62,28 +61,30 @@ void Thumbnail::setFileName(const char* fn) this->uri = QUrl::fromLocalFile(QString::fromUtf8(fn)); } -unsigned int Thumbnail::getMemSize () const +unsigned int Thumbnail::getMemSize() const { return 0; } -void Thumbnail::Save (Base::Writer &writer) const +void Thumbnail::Save(Base::Writer& writer) const { // It's only possible to add extra information if force of XML is disabled - if (!writer.isForceXML()) + if (!writer.isForceXML()) { writer.addFile("thumbnails/Thumbnail.png", this); + } } -void Thumbnail::Restore(Base::XMLReader &reader) +void Thumbnail::Restore(Base::XMLReader& reader) { Q_UNUSED(reader); - //reader.addFile("Thumbnail.png",this); + // reader.addFile("Thumbnail.png",this); } -void Thumbnail::SaveDocFile (Base::Writer &writer) const +void Thumbnail::SaveDocFile(Base::Writer& writer) const { - if (!this->viewer) + if (!this->viewer) { return; + } QImage img; if (this->viewer->thread() != QThread::currentThread()) { qWarning("Cannot create a thumbnail from non-GUI thread"); @@ -93,15 +94,22 @@ void Thumbnail::SaveDocFile (Base::Writer &writer) const QColor invalid; this->viewer->imageFromFramebuffer(this->size, this->size, 4, invalid, img); - // Get app icon and resize to half size to insert in topbottom position over the current view snapshot + // Get app icon and resize to half size to insert in topbottom position over the current view + // snapshot QPixmap appIcon = Gui::BitmapFactory().pixmap(App::Application::Config()["AppIcon"].c_str()); - QPixmap px = appIcon; + QPixmap px = appIcon; if (!img.isNull()) { // Create a small "Fc" Application icon in the bottom right of the thumbnail - if (App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Document")->GetBool("AddThumbnailLogo",false)) { + if (App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") + ->GetBool("AddThumbnailLogo", false)) { // only scale app icon if an offscreen image could be created - appIcon = appIcon.scaled(this->size / 4, this->size /4, Qt::KeepAspectRatio, Qt::SmoothTransformation); + appIcon = appIcon.scaled( + this->size / 4, + this->size / 4, + Qt::KeepAspectRatio, + Qt::SmoothTransformation + ); px = BitmapFactory().merge(QPixmap::fromImage(img), appIcon, BitmapFactoryInst::BottomRight); } else { @@ -126,7 +134,7 @@ void Thumbnail::SaveDocFile (Base::Writer &writer) const } } -void Thumbnail::RestoreDocFile(Base::Reader &reader) +void Thumbnail::RestoreDocFile(Base::Reader& reader) { Q_UNUSED(reader); } diff --git a/src/Gui/Thumbnail.h b/src/Gui/Thumbnail.h index 54176b13a1..6b057458c2 100644 --- a/src/Gui/Thumbnail.h +++ b/src/Gui/Thumbnail.h @@ -29,10 +29,11 @@ class QImage; -namespace Gui { +namespace Gui +{ class View3DInventorViewer; -class Thumbnail : public Base::Persistence +class Thumbnail: public Base::Persistence { public: Thumbnail(int s = 128); @@ -44,23 +45,23 @@ public: /** @name I/O of the document */ //@{ - unsigned int getMemSize () const override; + unsigned int getMemSize() const override; /// This method is used to save properties or very small amounts of data to an XML document. - void Save (Base::Writer &writer) const override; + void Save(Base::Writer& writer) const override; /// This method is used to restore properties from an XML document. - void Restore(Base::XMLReader &reader) override; + void Restore(Base::XMLReader& reader) override; /// This method is used to save large amounts of data to a binary file. - void SaveDocFile (Base::Writer &writer) const override; + void SaveDocFile(Base::Writer& writer) const override; /// This method is used to restore large amounts of data from a binary file. - void RestoreDocFile(Base::Reader &reader) override; + void RestoreDocFile(Base::Reader& reader) override; //@} private: QUrl uri; - View3DInventorViewer* viewer{nullptr}; + View3DInventorViewer* viewer {nullptr}; int size; }; -} +} // namespace Gui -#endif // GUI_THUMBNAIL_H +#endif // GUI_THUMBNAIL_H diff --git a/src/Gui/ToolBarAreaWidget.cpp b/src/Gui/ToolBarAreaWidget.cpp index 24ee8c1095..335e010369 100644 --- a/src/Gui/ToolBarAreaWidget.cpp +++ b/src/Gui/ToolBarAreaWidget.cpp @@ -31,11 +31,13 @@ using namespace Gui; -ToolBarAreaWidget::ToolBarAreaWidget(QWidget* parent, - ToolBarArea area, - const ParameterGrp::handle& hParam, - boost::signals2::scoped_connection& conn, - QTimer* timer) +ToolBarAreaWidget::ToolBarAreaWidget( + QWidget* parent, + ToolBarArea area, + const ParameterGrp::handle& hParam, + boost::signals2::scoped_connection& conn, + QTimer* timer +) : QWidget(parent) , _sizingTimer(timer) , _hParam(hParam) @@ -120,18 +122,18 @@ void ToolBarAreaWidget::saveState() { Base::ConnectionBlocker block(_conn); - for (auto &v : _hParam->GetIntMap()) { + for (auto& v : _hParam->GetIntMap()) { _hParam->RemoveInt(v.first.c_str()); } - foreachToolBar([this](QToolBar *toolbar, int idx, ToolBarAreaWidget*) { + foreachToolBar([this](QToolBar* toolbar, int idx, ToolBarAreaWidget*) { _hParam->SetInt(toolbar->objectName().toUtf8().constData(), idx); }); } void ToolBarAreaWidget::restoreState(const std::map& toolbars) { - for (const auto &[index, toolbar] : toolbars) { + for (const auto& [index, toolbar] : toolbars) { bool visible = toolbar->isVisible(); getMainWindow()->removeToolBar(toolbar); toolbar->setOrientation(Qt::Horizontal); @@ -139,7 +141,7 @@ void ToolBarAreaWidget::restoreState(const std::map& toolbars) toolbar->setVisible(visible); } - for (const auto &[name, visible] : _hParam->GetBoolMap()) { + for (const auto& [name, visible] : _hParam->GetBoolMap()) { auto widget = findChild(QString::fromUtf8(name.c_str())); if (widget) { diff --git a/src/Gui/ToolBarAreaWidget.h b/src/Gui/ToolBarAreaWidget.h index 690459ac50..0f80cbb0eb 100644 --- a/src/Gui/ToolBarAreaWidget.h +++ b/src/Gui/ToolBarAreaWidget.h @@ -34,7 +34,8 @@ namespace Gui // Qt treats area as Flag so in theory toolbar could be in multiple areas at once. // We don't do that here so simple enum should suffice. -enum class ToolBarArea { +enum class ToolBarArea +{ NoToolBarArea, LeftToolBarArea, RightToolBarArea, @@ -45,25 +46,27 @@ enum class ToolBarArea { StatusBarToolBarArea, }; -class ToolBarAreaWidget : public QWidget +class ToolBarAreaWidget: public QWidget { Q_OBJECT using inherited = QWidget; public: - ToolBarAreaWidget(QWidget *parent, - ToolBarArea area, - const ParameterGrp::handle& hParam, - boost::signals2::scoped_connection &conn, - QTimer *timer = nullptr); + ToolBarAreaWidget( + QWidget* parent, + ToolBarArea area, + const ParameterGrp::handle& hParam, + boost::signals2::scoped_connection& conn, + QTimer* timer = nullptr + ); - void addWidget(QWidget *widget); - void insertWidget(int index, QWidget *widget); - void removeWidget(QWidget *widget); + void addWidget(QWidget* widget); + void insertWidget(int index, QWidget* widget); + void removeWidget(QWidget* widget); void adjustParent(); - QWidget *widgetAt(int index) const + QWidget* widgetAt(int index) const { auto item = _layout->itemAt(index); @@ -75,7 +78,7 @@ public: return _layout->count(); } - int indexOf(QWidget *widget) const + int indexOf(QWidget* widget) const { return _layout->indexOf(widget); } @@ -86,13 +89,13 @@ public: } template - void foreachToolBar(FuncT &&func) + void foreachToolBar(FuncT&& func) { for (int i = 0, count = _layout->count(); i < count; ++i) { auto toolbar = qobject_cast(widgetAt(i)); if (!toolbar || toolbar->objectName().isEmpty() - || toolbar->objectName().startsWith(QStringLiteral("*"))) { + || toolbar->objectName().startsWith(QStringLiteral("*"))) { continue; } @@ -101,16 +104,16 @@ public: } void saveState(); - void restoreState(const std::map &toolbars); + void restoreState(const std::map& toolbars); private: - QHBoxLayout *_layout; + QHBoxLayout* _layout; QPointer _sizingTimer; ParameterGrp::handle _hParam; - boost::signals2::scoped_connection &_conn; + boost::signals2::scoped_connection& _conn; ToolBarArea _area; }; -} +} // namespace Gui #endif // GUI_TOOLBARAREAWIDGET_H diff --git a/src/Gui/ToolBarManager.cpp b/src/Gui/ToolBarManager.cpp index 45076fd7bf..c5e588a832 100644 --- a/src/Gui/ToolBarManager.cpp +++ b/src/Gui/ToolBarManager.cpp @@ -21,17 +21,17 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -49,11 +49,12 @@ using namespace Gui; -ToolBarItem::ToolBarItem() : visibilityPolicy(DefaultVisibility::Visible) -{ -} +ToolBarItem::ToolBarItem() + : visibilityPolicy(DefaultVisibility::Visible) +{} -ToolBarItem::ToolBarItem(ToolBarItem* item, DefaultVisibility visibilityPolicy) : visibilityPolicy(visibilityPolicy) +ToolBarItem::ToolBarItem(ToolBarItem* item, DefaultVisibility visibilityPolicy) + : visibilityPolicy(visibilityPolicy) { if (item) { item->appendItem(this); @@ -70,7 +71,7 @@ void ToolBarItem::setCommand(const std::string& name) _name = name; } -const std::string & ToolBarItem::command() const +const std::string& ToolBarItem::command() const { return _name; } @@ -82,7 +83,7 @@ bool ToolBarItem::hasItems() const ToolBarItem* ToolBarItem::findItem(const std::string& name) { - if ( _name == name ) { + if (_name == name) { return this; } @@ -98,7 +99,7 @@ ToolBarItem* ToolBarItem::findItem(const std::string& name) ToolBarItem* ToolBarItem::copy() const { auto root = new ToolBarItem; - root->setCommand( command() ); + root->setCommand(command()); QList items = getItems(); for (auto it : items) { @@ -115,10 +116,10 @@ uint ToolBarItem::count() const void ToolBarItem::appendItem(ToolBarItem* item) { - _items.push_back( item ); + _items.push_back(item); } -bool ToolBarItem::insertItem( ToolBarItem* before, ToolBarItem* item) +bool ToolBarItem::insertItem(ToolBarItem* before, ToolBarItem* item) { int pos = _items.indexOf(before); if (pos != -1) { @@ -146,13 +147,13 @@ void ToolBarItem::clear() _items.clear(); } -ToolBarItem& ToolBarItem::operator << (ToolBarItem* item) +ToolBarItem& ToolBarItem::operator<<(ToolBarItem* item) { appendItem(item); return *this; } -ToolBarItem& ToolBarItem::operator << (const std::string& command) +ToolBarItem& ToolBarItem::operator<<(const std::string& command) { auto item = new ToolBarItem(this); item->setCommand(command); @@ -189,9 +190,7 @@ void ToolBar::undock() getMainWindow()->addToolBar(this); } - setWindowFlags(Qt::Tool - | Qt::FramelessWindowHint - | Qt::X11BypassWindowManagerHint); + setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint); adjustSize(); setVisible(true); } @@ -209,10 +208,12 @@ void ToolBar::updateCustomGripVisibility() if (grip && !customGripIsRequired) { grip->detach(); grip->deleteLater(); - } else if (!grip && customGripIsRequired) { + } + else if (!grip && customGripIsRequired) { grip = new ToolBarGrip(this); grip->attach(); - } else { + } + else { // either grip is present and should be present // or is not present and should not be - nothing to do return; @@ -227,7 +228,7 @@ void Gui::ToolBar::setupConnections() // ----------------------------------------------------------- -ToolBarGrip::ToolBarGrip(QToolBar * parent) +ToolBarGrip::ToolBarGrip(QToolBar* parent) : QWidget(parent) { updateSize(); @@ -283,7 +284,7 @@ void ToolBarGrip::paintEvent(QPaintEvent*) QPainter painter(this); if (auto toolbar = qobject_cast(parentWidget())) { - QStyle *style = toolbar->style(); + QStyle* style = toolbar->style(); QStyleOptionToolBar opt; toolbar->initStyleOption(&opt); @@ -295,7 +296,7 @@ void ToolBarGrip::paintEvent(QPaintEvent*) } } -void ToolBarGrip::mouseMoveEvent(QMouseEvent *me) +void ToolBarGrip::mouseMoveEvent(QMouseEvent* me) { auto toolbar = qobject_cast(parentWidget()); if (!toolbar) { @@ -307,12 +308,12 @@ void ToolBarGrip::mouseMoveEvent(QMouseEvent *me) return; } -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QPoint pos = me->globalPos(); #else QPoint pos = me->globalPosition().toPoint(); #endif - QRect rect(toolbar->mapToGlobal(QPoint(0,0)), toolbar->size()); + QRect rect(toolbar->mapToGlobal(QPoint(0, 0)), toolbar->size()); // if mouse did not leave the area of toolbar do not continue with undocking it if (rect.contains(pos)) { @@ -329,37 +330,37 @@ void ToolBarGrip::mouseMoveEvent(QMouseEvent *me) QTimer::singleShot(0, [tb] { auto modifiers = QApplication::queryKeyboardModifiers(); auto buttons = QApplication::mouseButtons(); - if (buttons != Qt::LeftButton - || QWidget::mouseGrabber() - || modifiers != Qt::NoModifier - || !tb) { + if (buttons != Qt::LeftButton || QWidget::mouseGrabber() || modifiers != Qt::NoModifier + || !tb) { return; } QPoint pos(10, 10); QPoint globalPos(tb->mapToGlobal(pos)); - QMouseEvent mouseEvent( - QEvent::MouseButtonPress, - pos, globalPos, Qt::LeftButton, buttons, modifiers); + QMouseEvent mouseEvent(QEvent::MouseButtonPress, pos, globalPos, Qt::LeftButton, buttons, modifiers); QApplication::sendEvent(tb, &mouseEvent); // Mouse follow the mouse press event with mouse move with some offset // in order to activate toolbar dragging. QPoint offset(30, 30); QMouseEvent mouseMoveEvent( - QEvent::MouseMove, - pos+offset, globalPos+offset, - Qt::LeftButton, buttons, modifiers); + QEvent::MouseMove, + pos + offset, + globalPos + offset, + Qt::LeftButton, + buttons, + modifiers + ); QApplication::sendEvent(tb, &mouseMoveEvent); }); } -void ToolBarGrip::mousePressEvent(QMouseEvent *) +void ToolBarGrip::mousePressEvent(QMouseEvent*) { setCursor(Qt::ClosedHandCursor); } -void ToolBarGrip::mouseReleaseEvent(QMouseEvent *) +void ToolBarGrip::mouseReleaseEvent(QMouseEvent*) { setCursor(Qt::OpenHandCursor); } @@ -372,7 +373,7 @@ void ToolBarGrip::updateSize() return; } - QStyle *style = parent->style(); + QStyle* style = parent->style(); QStyleOptionToolBar opt; parent->initStyleOption(&opt); @@ -430,7 +431,8 @@ void ToolBarManager::setupStatusBar() { if (auto sb = getMainWindow()->statusBar()) { sb->installEventFilter(this); - statusBarAreaWidget = new ToolBarAreaWidget(sb, ToolBarArea::StatusBarToolBarArea, hStatusBar, connParam); + statusBarAreaWidget + = new ToolBarAreaWidget(sb, ToolBarArea::StatusBarToolBarArea, hStatusBar, connParam); statusBarAreaWidget->setObjectName(QStringLiteral("StatusBarArea")); sb->insertPermanentWidget(2, statusBarAreaWidget); statusBarAreaWidget->show(); @@ -441,11 +443,23 @@ void ToolBarManager::setupMenuBar() { if (auto mb = getMainWindow()->menuBar()) { mb->installEventFilter(this); - menuBarLeftAreaWidget = new ToolBarAreaWidget(mb, ToolBarArea::LeftMenuToolBarArea, hMenuBarLeft, connParam, &menuBarTimer); + menuBarLeftAreaWidget = new ToolBarAreaWidget( + mb, + ToolBarArea::LeftMenuToolBarArea, + hMenuBarLeft, + connParam, + &menuBarTimer + ); menuBarLeftAreaWidget->setObjectName(QStringLiteral("MenuBarLeftArea")); mb->setCornerWidget(menuBarLeftAreaWidget, Qt::TopLeftCorner); menuBarLeftAreaWidget->show(); - menuBarRightAreaWidget = new ToolBarAreaWidget(mb, ToolBarArea::RightMenuToolBarArea, hMenuBarRight, connParam, &menuBarTimer); + menuBarRightAreaWidget = new ToolBarAreaWidget( + mb, + ToolBarArea::RightMenuToolBarArea, + hMenuBarRight, + connParam, + &menuBarTimer + ); menuBarRightAreaWidget->setObjectName(QStringLiteral("MenuBarRightArea")); mb->setCornerWidget(menuBarRightAreaWidget, Qt::TopRightCorner); menuBarRightAreaWidget->show(); @@ -454,7 +468,7 @@ void ToolBarManager::setupMenuBar() void ToolBarManager::setupConnection() { - auto refreshParams = [this](const char *name) { + auto refreshParams = [this](const char* name) { bool sizeChanged = false; if (!name || boost::equals(name, "ToolbarIconSize")) { _toolBarIconSize = hGeneral->GetInt("ToolbarIconSize", 24); @@ -475,14 +489,13 @@ void ToolBarManager::setupConnection() refreshParams(nullptr); connParam = App::GetApplication().GetUserParameter().signalParamChanged.connect( - [this, refreshParams](ParameterGrp *hParam, ParameterGrp::ParamType, const char *name, const char *) { + [this, + refreshParams](ParameterGrp* hParam, ParameterGrp::ParamType, const char* name, const char*) { if (hParam == hGeneral && name) { refreshParams(name); } - if (hParam == hPref - || hParam == hStatusBar - || hParam == hMenuBarRight - || hParam == hMenuBarLeft) { + if (hParam == hPref || hParam == hStatusBar || hParam == hMenuBarRight + || hParam == hMenuBarLeft) { if (blockRestore) { blockRestore = false; } @@ -490,30 +503,27 @@ void ToolBarManager::setupConnection() timer.start(100); } } - }); + } + ); } void ToolBarManager::setupTimer() { timer.setSingleShot(true); - connect(&timer, &QTimer::timeout, [this]{ - onTimer(); - }); + connect(&timer, &QTimer::timeout, [this] { onTimer(); }); } void ToolBarManager::setupSizeTimer() { sizeTimer.setSingleShot(true); - connect(&sizeTimer, &QTimer::timeout, [this]{ - setupToolBarIconSize(); - }); + connect(&sizeTimer, &QTimer::timeout, [this] { setupToolBarIconSize(); }); } void ToolBarManager::setupResizeTimer() { resizeTimer.setSingleShot(true); - connect(&resizeTimer, &QTimer::timeout, [this]{ - for (const auto &[toolbar, guard] : resizingToolbars) { + connect(&resizeTimer, &QTimer::timeout, [this] { + for (const auto& [toolbar, guard] : resizingToolbars) { if (guard) { setToolBarIconSize(toolbar); } @@ -537,7 +547,7 @@ void Gui::ToolBarManager::setupWidgetProducers() new WidgetProducer; } -ToolBarArea ToolBarManager::toolBarArea(QWidget *widget) const +ToolBarArea ToolBarManager::toolBarArea(QWidget* widget) const { if (auto toolBar = qobject_cast(widget)) { if (toolBar->isFloating()) { @@ -569,7 +579,7 @@ ToolBarArea ToolBarManager::toolBarArea(QWidget *widget) const ToolBarAreaWidget* ToolBarManager::toolBarAreaWidget(QWidget* widget) const { - for (auto &areaWidget : { statusBarAreaWidget, menuBarLeftAreaWidget, menuBarRightAreaWidget }) { + for (auto& areaWidget : {statusBarAreaWidget, menuBarLeftAreaWidget, menuBarRightAreaWidget}) { if (areaWidget->indexOf(widget) >= 0) { return areaWidget; } @@ -578,7 +588,8 @@ ToolBarAreaWidget* ToolBarManager::toolBarAreaWidget(QWidget* widget) const return nullptr; } -namespace { +namespace +{ QPointer createActionWidget() { static QPointer actionWidget; @@ -591,7 +602,7 @@ QPointer createActionWidget() 'phantom' size without any visible content and will block the top left tool buttons and menus of the application main window. Therefore it is moved out of the way. */ - actionWidget->move(QPoint(-100,-100)); + actionWidget->move(QPoint(-100, -100)); } else { auto actions = actionWidget->actions(); @@ -602,9 +613,9 @@ QPointer createActionWidget() return actionWidget; } -} +} // namespace -int ToolBarManager::toolBarIconSize(QWidget *widget) const +int ToolBarManager::toolBarIconSize(QWidget* widget) const { int s = _toolBarIconSize; if (widget) { @@ -617,7 +628,7 @@ int ToolBarManager::toolBarIconSize(QWidget *widget) const } } else if (widget->parentWidget() == menuBarLeftAreaWidget - || widget->parentWidget() == menuBarRightAreaWidget) { + || widget->parentWidget() == menuBarRightAreaWidget) { if (_menuBarIconSize > 0) { s = _menuBarIconSize; } @@ -642,7 +653,7 @@ void ToolBarManager::setupToolBarIconSize() } } -void ToolBarManager::setToolBarIconSize(QToolBar *toolbar) +void ToolBarManager::setToolBarIconSize(QToolBar* toolbar) { int s = toolBarIconSize(toolbar); toolbar->setIconSize(QSize(s, s)); @@ -657,7 +668,7 @@ void ToolBarManager::setToolBarIconSize(QToolBar *toolbar) void ToolBarManager::setup(ToolBarItem* toolBarItems) { if (!toolBarItems) { - return; // empty menu bar + return; // empty menu bar } QPointer actionWidget = createActionWidget(); @@ -668,10 +679,12 @@ void ToolBarManager::setup(ToolBarItem* toolBarItems) int max_width = getMainWindow()->width(); int top_width = 0; - bool nameAsToolTip = App::GetApplication().GetUserParameter().GetGroup("BaseApp") - ->GetGroup("Preferences") - ->GetGroup("MainWindow") - ->GetBool("ToolBarNameAsToolTip", true); + bool nameAsToolTip = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("MainWindow") + ->GetBool("ToolBarNameAsToolTip", true); QList items = toolBarItems->getItems(); QList toolbars = toolBars(); @@ -759,8 +772,8 @@ void ToolBarManager::setup(ToolBarItem* toolBarItems) for (QToolBar* it : std::as_const(toolbars)) { // make sure that the main window has the focus when hiding the toolbar with // the combo box inside - QWidget *fw = QApplication::focusWidget(); - while (fw && !fw->isWindow()) { + QWidget* fw = QApplication::focusWidget(); + while (fw && !fw->isWindow()) { if (fw == it) { getMainWindow()->setFocus(); break; @@ -768,11 +781,11 @@ void ToolBarManager::setup(ToolBarItem* toolBarItems) fw = fw->parentWidget(); } // ignore toolbars which do not belong to the previously active workbench - //QByteArray toolbarName = it->objectName().toUtf8(); + // QByteArray toolbarName = it->objectName().toUtf8(); if (!it->toggleViewAction()->isVisible()) { continue; } - //hPref->SetBool(toolbarName.constData(), it->isVisible()); + // hPref->SetBool(toolbarName.constData(), it->isVisible()); it->hide(); it->toggleViewAction()->setVisible(false); } @@ -901,7 +914,7 @@ void ToolBarManager::restoreState() const menuBarLeftAreaWidget->restoreState(mbLeftToolBars); } -bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) +bool ToolBarManager::addToolBarToArea(QObject* source, QMouseEvent* ev) { auto statusBar = getMainWindow()->statusBar(); if (!statusBar || !statusBar->isVisible()) { @@ -925,8 +938,7 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) static QPointer lastArea; static int tbIndex = -1; if (ev->type() == QEvent::MouseMove) { - if (tb->orientation() != Qt::Horizontal - || ev->buttons() != Qt::LeftButton) { + if (tb->orientation() != Qt::Horizontal || ev->buttons() != Qt::LeftButton) { if (tbIndex >= 0) { if (lastArea) { lastArea->removeWidget(tbPlaceholder); @@ -944,9 +956,9 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) } QPoint pos = QCursor::pos(); - ToolBarAreaWidget *area = nullptr; + ToolBarAreaWidget* area = nullptr; if (statusBar) { - QRect rect(statusBar->mapToGlobal(QPoint(0,0)), statusBar->size()); + QRect rect(statusBar->mapToGlobal(QPoint(0, 0)), statusBar->size()); if (rect.contains(pos)) { area = statusBarAreaWidget; } @@ -955,9 +967,9 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) if (!menuBar) { return false; } - QRect rect(menuBar->mapToGlobal(QPoint(0,0)), menuBar->size()); + QRect rect(menuBar->mapToGlobal(QPoint(0, 0)), menuBar->size()); if (rect.contains(pos)) { - if (pos.x() - rect.left() < menuBar->width()/2) { + if (pos.x() - rect.left() < menuBar->width() / 2) { area = menuBarLeftAreaWidget; } else { @@ -978,7 +990,7 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) } int idx = 0; - for (int c = area->count(); idx < c ;++idx) { + for (int c = area->count(); idx < c; ++idx) { auto widget = area->widgetAt(idx); if (!widget || widget->isHidden()) { continue; @@ -988,7 +1000,7 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) break; } } - if (tbIndex >= 0 && tbIndex == idx-1) { + if (tbIndex >= 0 && tbIndex == idx - 1) { idx = tbIndex; } if (ev->type() == QEvent::MouseMove) { @@ -1007,7 +1019,8 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) tbPlaceholder->adjustSize(); tbPlaceholder->show(); } - } else { + } + else { tbIndex = idx; QTimer::singleShot(10, tb, [tb]() { if (!lastArea) { @@ -1032,7 +1045,7 @@ bool ToolBarManager::addToolBarToArea(QObject *source, QMouseEvent *ev) return false; } -bool ToolBarManager::showContextMenu(QObject *source) +bool ToolBarManager::showContextMenu(QObject* source) { QMenu menu; QLayout* layout = nullptr; @@ -1051,7 +1064,7 @@ bool ToolBarManager::showContextMenu(QObject *source) return false; } - auto addMenuVisibleItem = [&](QToolBar *toolbar, int, ToolBarAreaWidget *) { + auto addMenuVisibleItem = [&](QToolBar* toolbar, int, ToolBarAreaWidget*) { auto action = toolbar->toggleViewAction(); if ((action->isVisible() || toolbar->isVisible()) && action->text().size()) { action->setVisible(true); @@ -1087,12 +1100,12 @@ ToolBarAreaWidget* ToolBarManager::findToolBarAreaWidget() const ToolBarAreaWidget* area = nullptr; QPoint pos = QCursor::pos(); - QRect rect(menuBarLeftAreaWidget->mapToGlobal(QPoint(0,0)), menuBarLeftAreaWidget->size()); + QRect rect(menuBarLeftAreaWidget->mapToGlobal(QPoint(0, 0)), menuBarLeftAreaWidget->size()); if (rect.contains(pos)) { area = menuBarLeftAreaWidget; } else { - rect = QRect(menuBarRightAreaWidget->mapToGlobal(QPoint(0,0)), menuBarRightAreaWidget->size()); + rect = QRect(menuBarRightAreaWidget->mapToGlobal(QPoint(0, 0)), menuBarRightAreaWidget->size()); if (rect.contains(pos)) { area = menuBarRightAreaWidget; } @@ -1105,10 +1118,8 @@ void ToolBarManager::addToMenu(QLayout* layout, QWidget* area, QMenu* menu) { for (int i = 0, c = layout->count(); i < c; ++i) { auto widget = layout->itemAt(i)->widget(); - if (!widget || widget == area - || widget->objectName().isEmpty() - || widget->objectName().startsWith(QStringLiteral("*"))) - { + if (!widget || widget == area || widget->objectName().isEmpty() + || widget->objectName().startsWith(QStringLiteral("*"))) { continue; } QString name = widget->windowTitle(); @@ -1131,46 +1142,46 @@ void ToolBarManager::addToMenu(QLayout* layout, QWidget* area, QMenu* menu) } } -void ToolBarManager::onToggleStatusBarWidget(QWidget *widget, bool visible) +void ToolBarManager::onToggleStatusBarWidget(QWidget* widget, bool visible) { Base::ConnectionBlocker block(connParam); widget->setVisible(visible); hStatusBar->SetBool(widget->objectName().toUtf8().constData(), widget->isVisible()); } -bool ToolBarManager::eventFilter(QObject *source, QEvent *ev) +bool ToolBarManager::eventFilter(QObject* source, QEvent* ev) { bool res = false; - switch(ev->type()) { - case QEvent::Show: - case QEvent::Hide: - if (auto toolbar = qobject_cast(source)) { - auto parent = toolbar->parentWidget(); - if (parent == menuBarLeftAreaWidget || parent == menuBarRightAreaWidget) { - menuBarTimer.start(10); + switch (ev->type()) { + case QEvent::Show: + case QEvent::Hide: + if (auto toolbar = qobject_cast(source)) { + auto parent = toolbar->parentWidget(); + if (parent == menuBarLeftAreaWidget || parent == menuBarRightAreaWidget) { + menuBarTimer.start(10); + } + } + break; + case QEvent::MouseButtonRelease: { + auto mev = static_cast(ev); + if (mev->button() == Qt::RightButton) { + if (showContextMenu(source)) { + return true; + } } } - break; - case QEvent::MouseButtonRelease: { - auto mev = static_cast(ev); - if (mev->button() == Qt::RightButton) { - if (showContextMenu(source)) { - return true; + // fall through + case QEvent::MouseMove: + res = addToolBarToArea(source, static_cast(ev)); + break; + case QEvent::ParentChange: + if (auto toolbar = qobject_cast(source)) { + resizingToolbars[toolbar] = toolbar; + resizeTimer.start(100); } - } - } - // fall through - case QEvent::MouseMove: - res = addToolBarToArea(source, static_cast(ev)); - break; - case QEvent::ParentChange: - if (auto toolbar = qobject_cast(source)) { - resizingToolbars[toolbar] = toolbar; - resizeTimer.start(100); - } - break; - default: - break; + break; + default: + break; } return res; } @@ -1212,7 +1223,7 @@ ToolBar* ToolBarManager::findToolBar(const QList& toolbars, const QStr } } - return nullptr; // no item with the user data found + return nullptr; // no item with the user data found } QAction* ToolBarManager::findAction(const QList& acts, const QString& item) const @@ -1223,7 +1234,7 @@ QAction* ToolBarManager::findAction(const QList& acts, const QString& } } - return nullptr; // no item with the user data found + return nullptr; // no item with the user data found } QList ToolBarManager::toolBars() const @@ -1235,11 +1246,8 @@ QList ToolBarManager::toolBars() const for (ToolBar* it : bars) { auto parent = it->parentWidget(); - if (parent == mw - || parent == mw->statusBar() - || parent == statusBarAreaWidget - || parent == menuBarLeftAreaWidget - || parent == menuBarRightAreaWidget) { + if (parent == mw || parent == mw->statusBar() || parent == statusBarAreaWidget + || parent == menuBarLeftAreaWidget || parent == menuBarRightAreaWidget) { tb.push_back(it); it->installEventFilter(const_cast(this)); } @@ -1273,8 +1281,7 @@ void ToolBarManager::setState(const QString& name, State state) return hPref->GetBool(name.toStdString().c_str(), defaultvalue); }; - auto saveVisibility = [this, visibility, name](bool value, - ToolBarItem::DefaultVisibility policy) { + auto saveVisibility = [this, visibility, name](bool value, ToolBarItem::DefaultVisibility policy) { auto show = visibility(policy == ToolBarItem::DefaultVisibility::Visible); if (show != value) { @@ -1284,10 +1291,9 @@ void ToolBarManager::setState(const QString& name, State state) }; auto showhide = [visibility](QToolBar* toolbar, ToolBarItem::DefaultVisibility policy) { + auto show = visibility(policy == ToolBarItem::DefaultVisibility::Visible); - auto show = visibility( policy == ToolBarItem::DefaultVisibility::Visible ); - - if(show) { + if (show) { toolbar->show(); } else { @@ -1301,11 +1307,11 @@ void ToolBarManager::setState(const QString& name, State state) auto policy = getToolbarPolicy(tb); if (state == State::RestoreDefault) { - if(policy == ToolBarItem::DefaultVisibility::Unavailable) { + if (policy == ToolBarItem::DefaultVisibility::Unavailable) { tb->hide(); tb->toggleViewAction()->setVisible(false); } - else { + else { tb->toggleViewAction()->setVisible(true); showhide(tb, policy); @@ -1315,10 +1321,12 @@ void ToolBarManager::setState(const QString& name, State state) tb->toggleViewAction()->setVisible(true); // Unavailable policy defaults to a Visible toolbars when made available - auto show = visibility( policy == ToolBarItem::DefaultVisibility::Visible || - policy == ToolBarItem::DefaultVisibility::Unavailable); + auto show = visibility( + policy == ToolBarItem::DefaultVisibility::Visible + || policy == ToolBarItem::DefaultVisibility::Unavailable + ); - if(show) { + if (show) { tb->show(); } else { @@ -1326,9 +1334,8 @@ void ToolBarManager::setState(const QString& name, State state) } } else if (state == State::ForceHidden) { - tb->toggleViewAction()->setVisible(false); // not visible in context menus - tb->hide(); // toolbar not visible - + tb->toggleViewAction()->setVisible(false); // not visible in context menus + tb->hide(); // toolbar not visible } else if (state == State::SaveState) { auto show = tb->isVisible(); diff --git a/src/Gui/ToolBarManager.h b/src/Gui/ToolBarManager.h index 9fbe141c9d..08587acdb0 100644 --- a/src/Gui/ToolBarManager.h +++ b/src/Gui/ToolBarManager.h @@ -41,7 +41,8 @@ class QLayout; class QMenu; class QMouseEvent; -namespace Gui { +namespace Gui +{ class ToolBarAreaWidget; enum class ToolBarArea; @@ -51,22 +52,26 @@ class GuiExport ToolBarItem public: /** Manages the default visibility status of a toolbar item, as well as the default status * of the toggleViewAction usable by the contextual menu to enable and disable its visibility - */ - enum class DefaultVisibility { - Visible, // toolbar is hidden by default, visibility toggle action is enabled - Hidden, // toolbar hidden by default, visibility toggle action is enabled - Unavailable, // toolbar visibility is managed independently by client code and defaults to - // hidden, visibility toggle action is disabled by default (it is unavailable - // to the UI). Upon being forced to be available, these toolbars default to - // visible. + */ + enum class DefaultVisibility + { + Visible, // toolbar is hidden by default, visibility toggle action is enabled + Hidden, // toolbar hidden by default, visibility toggle action is enabled + Unavailable, // toolbar visibility is managed independently by client code and defaults to + // hidden, visibility toggle action is disabled by default (it is unavailable + // to the UI). Upon being forced to be available, these toolbars default to + // visible. }; ToolBarItem(); - explicit ToolBarItem(ToolBarItem* item, DefaultVisibility visibilityPolicy = DefaultVisibility::Visible); + explicit ToolBarItem( + ToolBarItem* item, + DefaultVisibility visibilityPolicy = DefaultVisibility::Visible + ); ~ToolBarItem(); void setCommand(const std::string&); - const std::string &command() const; + const std::string& command() const; bool hasItems() const; ToolBarItem* findItem(const std::string&); @@ -78,8 +83,8 @@ public: void removeItem(ToolBarItem* item); void clear(); - ToolBarItem& operator << (ToolBarItem* item); - ToolBarItem& operator << (const std::string& command); + ToolBarItem& operator<<(ToolBarItem* item); + ToolBarItem& operator<<(const std::string& command); QList getItems() const; DefaultVisibility visibilityPolicy; @@ -94,7 +99,7 @@ class ToolBarGrip: public QWidget Q_OBJECT public: - explicit ToolBarGrip(QToolBar *); + explicit ToolBarGrip(QToolBar*); void attach(); void detach(); @@ -103,9 +108,9 @@ public: protected: void paintEvent(QPaintEvent*); - void mouseMoveEvent(QMouseEvent *); - void mousePressEvent(QMouseEvent *); - void mouseReleaseEvent(QMouseEvent *); + void mouseMoveEvent(QMouseEvent*); + void mousePressEvent(QMouseEvent*); + void mouseReleaseEvent(QMouseEvent*); void updateSize(); @@ -143,16 +148,16 @@ protected: * @see MenuManager * @author Werner Mayer */ -class GuiExport ToolBarManager : public QObject +class GuiExport ToolBarManager: public QObject { Q_OBJECT public: - - enum class State { - ForceHidden, // Forces a toolbar to hide and hides the toggle action - ForceAvailable, // Forces a toolbar toggle action to show, visibility depends on user config - RestoreDefault, // Restores a toolbar toggle action default, visibility as user config - SaveState, // Saves the state of the toolbars + enum class State + { + ForceHidden, // Forces a toolbar to hide and hides the toggle action + ForceAvailable, // Forces a toolbar toggle action to show, visibility depends on user config + RestoreDefault, // Restores a toolbar toggle action default, visibility as user config + SaveState, // Saves the state of the toolbars }; /// The one and only instance. @@ -170,7 +175,7 @@ public: void setState(const QList& names, State state); void setState(const QString& name, State state); - int toolBarIconSize(QWidget *widget = nullptr) const; + int toolBarIconSize(QWidget* widget = nullptr) const; void setupToolBarIconSize(); ToolBarArea toolBarArea(QWidget* toolBar) const; @@ -181,15 +186,15 @@ protected: void setMovable(bool movable) const; - ToolBarItem::DefaultVisibility getToolbarPolicy(const QToolBar *) const; + ToolBarItem::DefaultVisibility getToolbarPolicy(const QToolBar*) const; - bool addToolBarToArea(QObject *source, QMouseEvent *ev); - bool showContextMenu(QObject *source); - void onToggleStatusBarWidget(QWidget *widget, bool visible); - void setToolBarIconSize(QToolBar *toolbar); + bool addToolBarToArea(QObject* source, QMouseEvent* ev); + bool showContextMenu(QObject* source); + void onToggleStatusBarWidget(QWidget* widget, bool visible); + void setToolBarIconSize(QToolBar* toolbar); void onTimer(); - bool eventFilter(QObject *source, QEvent *ev) override; + bool eventFilter(QObject* source, QEvent* ev) override; /** Returns a list of all currently existing toolbars. */ QList toolBars() const; @@ -222,9 +227,9 @@ private: QTimer sizeTimer; QTimer resizeTimer; boost::signals2::scoped_connection connParam; - ToolBarAreaWidget *statusBarAreaWidget = nullptr; - ToolBarAreaWidget *menuBarLeftAreaWidget = nullptr; - ToolBarAreaWidget *menuBarRightAreaWidget = nullptr; + ToolBarAreaWidget* statusBarAreaWidget = nullptr; + ToolBarAreaWidget* menuBarLeftAreaWidget = nullptr; + ToolBarAreaWidget* menuBarRightAreaWidget = nullptr; ParameterGrp::handle hGeneral; ParameterGrp::handle hPref; ParameterGrp::handle hStatusBar; @@ -237,7 +242,7 @@ private: bool blockRestore = false; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_TOOLBARMANAGER_H +#endif // GUI_TOOLBARMANAGER_H diff --git a/src/Gui/ToolBox.cpp b/src/Gui/ToolBox.cpp index e5c719940f..91c7d3fdef 100644 --- a/src/Gui/ToolBox.cpp +++ b/src/Gui/ToolBox.cpp @@ -21,9 +21,9 @@ ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "ToolBox.h" @@ -34,205 +34,209 @@ using namespace Gui::DockWnd; /** * Constructs a toolbox called \a name with parent \a parent and flags \a f. */ -ToolBox::ToolBox( QWidget *parent ) - : QWidget(parent) +ToolBox::ToolBox(QWidget* parent) + : QWidget(parent) { - _pToolBox = new QToolBox( this ); - connect(_pToolBox, &QToolBox::currentChanged, this, &ToolBox::currentChanged); + _pToolBox = new QToolBox(this); + connect(_pToolBox, &QToolBox::currentChanged, this, &ToolBox::currentChanged); - auto pGrid = new QGridLayout(this); - pGrid->addWidget(_pToolBox, 0, 0); + auto pGrid = new QGridLayout(this); + pGrid->addWidget(_pToolBox, 0, 0); } ToolBox::~ToolBox() { - delete _pToolBox; + delete _pToolBox; } /** * Adds the widget w in a new tab at bottom of the toolbox. The new tab's label is set to \a label. * Returns the new tab's index. */ -int ToolBox::addItem ( QWidget * w, const QString & label ) +int ToolBox::addItem(QWidget* w, const QString& label) { - return _pToolBox->addItem( w, label ); + return _pToolBox->addItem(w, label); } /** - * Adds the widget \a item in a new tab at bottom of the toolbox. The new tab's label is set to \a label, and - * the \a iconSet is displayed to the left of the \a label. Returns the new tab's index. + * Adds the widget \a item in a new tab at bottom of the toolbox. The new tab's label is set to \a + * label, and the \a iconSet is displayed to the left of the \a label. Returns the new tab's index. */ -int ToolBox::addItem ( QWidget * item, const QIcon & iconSet, const QString & label ) +int ToolBox::addItem(QWidget* item, const QIcon& iconSet, const QString& label) { - return _pToolBox->addItem( item, iconSet, label ); + return _pToolBox->addItem(item, iconSet, label); } /** - * This is an overloaded member function, provided for convenience. It behaves essentially like the above function. + * This is an overloaded member function, provided for convenience. It behaves essentially like the + * above function. * - * Inserts the widget \a item at position \a index, or at the bottom of the toolbox if \a index is out of range. - * The new item's label is set to \a label. Returns the new item's index. + * Inserts the widget \a item at position \a index, or at the bottom of the toolbox if \a index is + * out of range. The new item's label is set to \a label. Returns the new item's index. */ -int ToolBox::insertItem ( int index, QWidget * item, const QString & label ) +int ToolBox::insertItem(int index, QWidget* item, const QString& label) { - return _pToolBox->insertItem( index, item, label ); + return _pToolBox->insertItem(index, item, label); } /** - * Inserts the widget \a item at position \a index, or at the bottom of the toolbox if \a index is out of range. - * The new item's label is set to \a label, and the \a iconSet is displayed to the left of the \a label. - * Returns the new item's index. + * Inserts the widget \a item at position \a index, or at the bottom of the toolbox if \a index is + * out of range. The new item's label is set to \a label, and the \a iconSet is displayed to the + * left of the \a label. Returns the new item's index. */ -int ToolBox::insertItem ( int index, QWidget * item, const QIcon & iconSet, const QString & label ) +int ToolBox::insertItem(int index, QWidget* item, const QIcon& iconSet, const QString& label) { - return _pToolBox->insertItem( index, item, iconSet, label ); + return _pToolBox->insertItem(index, item, iconSet, label); } /** * Removes the widget \a item from the toolbox. * Returns the removed widget's index, or -1 if the widget was not in this tool box. */ -void ToolBox::removeItem ( int index ) +void ToolBox::removeItem(int index) { - _pToolBox->removeItem( index ); + _pToolBox->removeItem(index); } /** - * If \a enabled is true then the item at position \a index is enabled; otherwise item \a index is disabled. + * If \a enabled is true then the item at position \a index is enabled; otherwise item \a index is + * disabled. */ -void ToolBox::setItemEnabled ( int index, bool enabled ) +void ToolBox::setItemEnabled(int index, bool enabled) { - _pToolBox->setItemEnabled( index, enabled ); + _pToolBox->setItemEnabled(index, enabled); } /** * Returns true if the item at position \a index is enabled; otherwise returns false. */ -bool ToolBox::isItemEnabled ( int index ) const +bool ToolBox::isItemEnabled(int index) const { - return _pToolBox->isItemEnabled( index ); + return _pToolBox->isItemEnabled(index); } /** * Sets the label of the item at position \a index to \a label. */ -void ToolBox::setItemText ( int index, const QString & label ) +void ToolBox::setItemText(int index, const QString& label) { - _pToolBox->setItemText( index, label ); + _pToolBox->setItemText(index, label); } /** * Returns the label of the item at position \a index, or a null string if \a index is out of range. */ -QString ToolBox::itemText ( int index ) const +QString ToolBox::itemText(int index) const { - return _pToolBox->itemText( index ); + return _pToolBox->itemText(index); } /** * Sets the icon of the item at position \a index to \a iconSet. */ -void ToolBox::setItemIcon ( int index, const QIcon & iconSet ) +void ToolBox::setItemIcon(int index, const QIcon& iconSet) { - _pToolBox->setItemIcon( index, iconSet ); + _pToolBox->setItemIcon(index, iconSet); } /** * Returns the icon of the item at position \a index, or a null icon if \a index is out of range. */ -QIcon ToolBox::itemIcon ( int index ) const +QIcon ToolBox::itemIcon(int index) const { - return _pToolBox->itemIcon( index ); + return _pToolBox->itemIcon(index); } /** * Sets the tooltip of the item at position \a index to \a toolTip. */ -void ToolBox::setItemToolTip ( int index, const QString & toolTip ) +void ToolBox::setItemToolTip(int index, const QString& toolTip) { - _pToolBox->setItemToolTip( index, toolTip ); + _pToolBox->setItemToolTip(index, toolTip); } /** * Returns the tooltip of the item at position \a index, or a null string if \a index is out of range. */ -QString ToolBox::itemToolTip ( int index ) const +QString ToolBox::itemToolTip(int index) const { - return _pToolBox->itemToolTip( index ); + return _pToolBox->itemToolTip(index); } /** * Returns the toolbox's current item, or 0 if the toolbox is empty. */ -QWidget * ToolBox::currentWidget () const +QWidget* ToolBox::currentWidget() const { - return _pToolBox->currentWidget(); + return _pToolBox->currentWidget(); } /** * Sets the current item to be \a item. */ -void ToolBox::setCurrentWidget ( QWidget * item ) +void ToolBox::setCurrentWidget(QWidget* item) { - _pToolBox->setCurrentWidget( item ); + _pToolBox->setCurrentWidget(item); } /** * Returns the index of the current item, or -1 if the toolbox is empty. */ -int ToolBox::currentIndex () const +int ToolBox::currentIndex() const { - return _pToolBox->currentIndex(); + return _pToolBox->currentIndex(); } /** * Returns the item at position \a index, or 0 if there is no such item. */ -QWidget * ToolBox::widget ( int index ) const +QWidget* ToolBox::widget(int index) const { - return _pToolBox->widget( index ); + return _pToolBox->widget(index); } /** * Returns the index of item \a item, or -1 if the item does not exist. */ -int ToolBox::indexOf ( QWidget * item ) const +int ToolBox::indexOf(QWidget* item) const { - return _pToolBox->indexOf ( item ); + return _pToolBox->indexOf(item); } /** * Returns the number of items contained in the toolbox. */ -int ToolBox::count () const +int ToolBox::count() const { - return _pToolBox->count(); + return _pToolBox->count(); } /** * Sets the index of the current item, or -1 if the toolbox is empty to \a index. */ -void ToolBox::setCurrentIndex ( int index ) +void ToolBox::setCurrentIndex(int index) { - _pToolBox->setCurrentIndex( index ); + _pToolBox->setCurrentIndex(index); } /** * If to a new language is switched this method gets called. */ -void ToolBox::changeEvent(QEvent *e) +void ToolBox::changeEvent(QEvent* e) { - if (e->type() == QEvent::LanguageChange) { - QWidget::changeEvent(e); - int ct = count(); - for ( int i=0; iwindowTitle() ); + if (e->type() == QEvent::LanguageChange) { + QWidget::changeEvent(e); + int ct = count(); + for (int i = 0; i < ct; i++) { + QWidget* w = widget(i); + if (w) { + setItemText(i, w->windowTitle()); + } + } + } + else { + QWidget::changeEvent(e); } - } else { - QWidget::changeEvent(e); - } } #include "moc_ToolBox.cpp" diff --git a/src/Gui/ToolBox.h b/src/Gui/ToolBox.h index 64e54307a8..087873a4ce 100644 --- a/src/Gui/ToolBox.h +++ b/src/Gui/ToolBox.h @@ -35,78 +35,80 @@ namespace DockWnd { /** The ToolBox class provides a column of tabbed widget items. - * A toolbox is a widget that displays a column of tabs one above the other, with the current item displayed - * below the current tab. Every tab has an index position within the column of tabs. A tab's item is a QWidget. + * A toolbox is a widget that displays a column of tabs one above the other, with the current item + * displayed below the current tab. Every tab has an index position within the column of tabs. A + * tab's item is a QWidget. * - * Each item has an itemLabel(), an optional icon, itemIconSet(), an optional itemToolTip(), and a widget. - * The item's attributes can be changed with setItemLabel(), setItemIconSet() and setItemToolTip(). + * Each item has an itemLabel(), an optional icon, itemIconSet(), an optional itemToolTip(), and a + * widget. The item's attributes can be changed with setItemLabel(), setItemIconSet() and + * setItemToolTip(). * - * Items are added using addItem(), or inserted at particular positions using insertItem(). The total number of - * items is given by count(). Items can be deleted with delete, or removed from the toolbox with removeItem(). - * Combining removeItem() and insertItem() allows one to move items to different positions. + * Items are added using addItem(), or inserted at particular positions using insertItem(). The + * total number of items is given by count(). Items can be deleted with delete, or removed from the + * toolbox with removeItem(). Combining removeItem() and insertItem() allows one to move items to + * different positions. * - * The current item widget is returned by currentItem() and set with setCurrentItem(). If you prefer you can - * work in terms of indexes using currentIndex(), setCurrentIndex(), indexOf() and item(). + * The current item widget is returned by currentItem() and set with setCurrentItem(). If you prefer + * you can work in terms of indexes using currentIndex(), setCurrentIndex(), indexOf() and item(). * * The currentChanged() signal is emitted when the current item is changed. * - * \a Note: This class implements the same API as the QToolBox does provided by Qt unless removeItem(), - * which also deletes the item to be removed. + * \a Note: This class implements the same API as the QToolBox does provided by Qt unless + * removeItem(), which also deletes the item to be removed. * \author Werner Mayer */ -class GuiExport ToolBox : public QWidget +class GuiExport ToolBox: public QWidget { - Q_OBJECT + Q_OBJECT public: - ToolBox( QWidget *parent=nullptr ); - ~ToolBox() override; + ToolBox(QWidget* parent = nullptr); + ~ToolBox() override; - int addItem ( QWidget * w, const QString & label ); - int addItem ( QWidget * item, const QIcon & iconSet, const QString & label ); - int insertItem ( int index, QWidget * item, const QString & label ); - int insertItem ( int index, QWidget * item, const QIcon & iconSet, const QString & label ); + int addItem(QWidget* w, const QString& label); + int addItem(QWidget* item, const QIcon& iconSet, const QString& label); + int insertItem(int index, QWidget* item, const QString& label); + int insertItem(int index, QWidget* item, const QIcon& iconSet, const QString& label); - void removeItem ( int index ); + void removeItem(int index); - void setItemEnabled ( int index, bool enabled ); - bool isItemEnabled ( int index ) const; + void setItemEnabled(int index, bool enabled); + bool isItemEnabled(int index) const; - void setItemText ( int index, const QString & label ); - QString itemText ( int index ) const; + void setItemText(int index, const QString& label); + QString itemText(int index) const; - void setItemIcon ( int index, const QIcon & iconSet ); - QIcon itemIcon ( int index ) const; + void setItemIcon(int index, const QIcon& iconSet); + QIcon itemIcon(int index) const; - void setItemToolTip ( int index, const QString & toolTip ); - QString itemToolTip ( int index ) const; + void setItemToolTip(int index, const QString& toolTip); + QString itemToolTip(int index) const; - QWidget * currentWidget () const; + QWidget* currentWidget() const; - int currentIndex () const; - QWidget * widget ( int index ) const; - int indexOf ( QWidget * item ) const; - int count () const; + int currentIndex() const; + QWidget* widget(int index) const; + int indexOf(QWidget* item) const; + int count() const; public Q_SLOTS: - void setCurrentIndex ( int index ); - void setCurrentWidget ( QWidget * item ); + void setCurrentIndex(int index); + void setCurrentWidget(QWidget* item); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; Q_SIGNALS: - /** This signal is emitted when the current item changed. - * The new current item's index is passed in index, or -1 if there is no current item. - */ - void currentChanged ( int index ); + /** This signal is emitted when the current item changed. + * The new current item's index is passed in index, or -1 if there is no current item. + */ + void currentChanged(int index); private: - QToolBox* _pToolBox; + QToolBox* _pToolBox; }; -} // namespace DockWnd -} // namespace Gui - -#endif // GUI_DOCKWND_TOOLBOX_H +} // namespace DockWnd +} // namespace Gui +#endif // GUI_DOCKWND_TOOLBOX_H diff --git a/src/Gui/ToolBoxManager.cpp b/src/Gui/ToolBoxManager.cpp index 718af4613e..4389dac834 100644 --- a/src/Gui/ToolBoxManager.cpp +++ b/src/Gui/ToolBoxManager.cpp @@ -21,10 +21,10 @@ ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "ToolBoxManager.h" @@ -37,12 +37,13 @@ using namespace Gui; using DockWnd::ToolBox; -ToolBoxManager* ToolBoxManager::_instance=nullptr; +ToolBoxManager* ToolBoxManager::_instance = nullptr; ToolBoxManager* ToolBoxManager::getInstance() { - if ( !_instance ) + if (!_instance) { _instance = new ToolBoxManager; + } return _instance; } @@ -56,19 +57,19 @@ ToolBoxManager::ToolBoxManager() = default; ToolBoxManager::~ToolBoxManager() = default; -void ToolBoxManager::setToolBox( DockWnd::ToolBox* tb ) +void ToolBoxManager::setToolBox(DockWnd::ToolBox* tb) { _toolBox = tb; } -void ToolBoxManager::setup( ToolBarItem* toolBar ) const +void ToolBoxManager::setup(ToolBarItem* toolBar) const { - if ( !toolBar || !_toolBox ) - return; // empty tool bar + if (!toolBar || !_toolBox) { + return; // empty tool bar + } int ct = _toolBox->count(); - for ( int i=0; iwidget(0); _toolBox->removeItem(0); @@ -78,22 +79,21 @@ void ToolBoxManager::setup( ToolBarItem* toolBar ) const CommandManager& mgr = Application::Instance->commandManager(); QList items = toolBar->getItems(); - for ( auto item : items ) - { + for (auto item : items) { auto bar = new QToolBar(); bar->setOrientation(Qt::Vertical); bar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); std::string toolbarName = item->command(); bar->setObjectName(QString::fromLatin1(item->command().c_str())); - bar->setWindowTitle(QObject::tr(toolbarName.c_str())); // i18n - _toolBox->addItem( bar, bar->windowTitle() ); + bar->setWindowTitle(QObject::tr(toolbarName.c_str())); // i18n + _toolBox->addItem(bar, bar->windowTitle()); QList subitems = item->getItems(); - for (auto subitem : subitems) - { - if ( subitem->command() == "Separator" ) { - //bar->addSeparator(); - } else { + for (auto subitem : subitems) { + if (subitem->command() == "Separator") { + // bar->addSeparator(); + } + else { mgr.addTo(subitem->command().c_str(), bar); } } @@ -105,8 +105,7 @@ void ToolBoxManager::setup( ToolBarItem* toolBar ) const // When setting the horizontal size policy but no icon is set we use the following trick // to make the button text left aligned. QIcon icon = it->icon(); - if (icon.isNull()) - { + if (icon.isNull()) { // Create an icon filled with the button color int size = QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize); QPixmap p(size, size); @@ -120,7 +119,7 @@ void ToolBoxManager::setup( ToolBarItem* toolBar ) const void ToolBoxManager::retranslate() const { int ct = _toolBox->count(); - for (int i=0; iwidget(i); QByteArray toolbarName = w->objectName().toUtf8(); diff --git a/src/Gui/ToolBoxManager.h b/src/Gui/ToolBoxManager.h index 2c527f2ce4..7aa1b4c1f2 100644 --- a/src/Gui/ToolBoxManager.h +++ b/src/Gui/ToolBoxManager.h @@ -26,13 +26,16 @@ #include -namespace Gui { +namespace Gui +{ class ToolBarItem; namespace DockWnd -{ class ToolBox;} +{ +class ToolBox; +} /** * The ToolBoxManager class is responsible for the creation of command bars and appending them @@ -57,11 +60,11 @@ protected: ~ToolBoxManager(); private: - DockWnd::ToolBox* _toolBox{nullptr}; + DockWnd::ToolBox* _toolBox {nullptr}; static ToolBoxManager* _instance; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_TOOLBOXMANAGER_H +#endif // GUI_TOOLBOXMANAGER_H diff --git a/src/Gui/ToolHandler.cpp b/src/Gui/ToolHandler.cpp index 5207070e48..fcdf08a493 100644 --- a/src/Gui/ToolHandler.cpp +++ b/src/Gui/ToolHandler.cpp @@ -83,8 +83,9 @@ void ToolHandler::deactivate() unsigned long ToolHandler::getCrosshairColor() { unsigned long color = 0xFFFFFFFF; // white - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); color = hGrp->GetUnsigned("CursorCrosshairColor", color); // from rgba to rgb color = (color >> 8) & 0xFFFFFF; @@ -109,10 +110,12 @@ void ToolHandler::setCrosshairCursor(const char* svgName) setCrosshairCursor(cursorName); } -void ToolHandler::setSvgCursor(const QString& cursorName, - int x, - int y, - const std::map& colorMapping) +void ToolHandler::setSvgCursor( + const QString& cursorName, + int x, + int y, + const std::map& colorMapping +) { // The TechDraw_Pointer_*.svg icons have a default size of 64x64. When directly creating // them with a size of 32x32 they look very bad. @@ -131,9 +134,11 @@ void ToolHandler::setSvgCursor(const QString& cursorName, } #endif - 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); } diff --git a/src/Gui/ToolHandler.h b/src/Gui/ToolHandler.h index 88189c8b0c..33985ec732 100644 --- a/src/Gui/ToolHandler.h +++ b/src/Gui/ToolHandler.h @@ -106,9 +106,13 @@ protected: virtual void setWidgetCursor(QCursor cursor); 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 applyCursor(QCursor& newCursor); @@ -117,7 +121,6 @@ private: void setCrosshairCursor(const char* svgName); protected: - QCursor oldCursor; QCursor actCursor; QPixmap actCursorPixmap; diff --git a/src/Gui/Tools.h b/src/Gui/Tools.h index 24f8e90d3e..e6ed5060f1 100644 --- a/src/Gui/Tools.h +++ b/src/Gui/Tools.h @@ -51,12 +51,12 @@ inline int horizontalAdvance(const QFontMetrics& fm, const QString& text, int le inline bool matches(QKeyEvent* ke, const QKeySequence& ks) { - uint searchkey = - (ke->modifiers() | ke->key()) & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier); + uint searchkey = (ke->modifiers() | ke->key()) & ~(Qt::KeypadModifier | Qt::GroupSwitchModifier); return ks == QKeySequence(searchkey); } -inline QKeySequence::StandardKey deleteKeySequence() { +inline QKeySequence::StandardKey deleteKeySequence() +{ #ifdef FC_OS_MACOSX return QKeySequence::Backspace; #else @@ -91,9 +91,11 @@ concept TreeWalkCallable = * return `void` or `bool` (for stopping logic). * @param[in] index The starting index for traversal. If omitted, defaults to the root. */ -void walkTreeModel(const QAbstractItemModel* model, - TreeWalkCallable auto&& func, - const QModelIndex& index = {}) +void walkTreeModel( + const QAbstractItemModel* model, + TreeWalkCallable auto&& func, + const QModelIndex& index = {} +) { using ReturnType = std::invoke_result_t; diff --git a/src/Gui/TransactionObject.cpp b/src/Gui/TransactionObject.cpp index 053a104ca5..44ebc1923f 100644 --- a/src/Gui/TransactionObject.cpp +++ b/src/Gui/TransactionObject.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include "Application.h" #include "Document.h" #include "TransactionObject.h" diff --git a/src/Gui/TransactionObject.h b/src/Gui/TransactionObject.h index c5a00c6859..cc302f024a 100644 --- a/src/Gui/TransactionObject.h +++ b/src/Gui/TransactionObject.h @@ -28,7 +28,7 @@ namespace Gui { -class TransactionViewProvider : public App::TransactionObject +class TransactionViewProvider: public App::TransactionObject { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -40,7 +40,7 @@ public: void applyDel(App::Document& Doc, App::TransactionalObject* pcObj) override; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_TRANSACTIONOBJECT_H +#endif // GUI_TRANSACTIONOBJECT_H diff --git a/src/Gui/Transform.cpp b/src/Gui/Transform.cpp index 3d3e1b3d6b..c1635e3fcf 100644 --- a/src/Gui/Transform.cpp +++ b/src/Gui/Transform.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -41,22 +40,24 @@ using namespace Gui::Dialog; -namespace Gui { namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class find_transform { public: - bool operator () (const std::pair& elem) const + bool operator()(const std::pair& elem) const { if (elem.first == "Placement") { - return elem.second->isDerivedFrom - (Base::Type::fromName("App::PropertyPlacement")); + return elem.second->isDerivedFrom(Base::Type::fromName("App::PropertyPlacement")); } return false; } }; -} -} +} // namespace Dialog +} // namespace Gui // ---------------------------------------------------------------------------- @@ -71,24 +72,29 @@ Base::Vector3d TransformStrategy::getRotationCenter() const std::set objects = transformObjects(); if (!objects.empty()) { Base::BoundBox3d bbox; - bool first=true; - for (const auto & object : objects) { + bool first = true; + for (const auto& object : objects) { if (object->isDerivedFrom()) { // search for a data property - const App::PropertyGeometry* geo = static_cast(object)->getPropertyOfGeometry(); + const App::PropertyGeometry* geo + = static_cast(object)->getPropertyOfGeometry(); if (geo) { - if (first) + if (first) { bbox = geo->getBoundingBox(); - else + } + else { bbox.Add(geo->getBoundingBox()); + } first = false; } } } - return Base::Vector3d((bbox.MinX+bbox.MaxX)/2, - (bbox.MinY+bbox.MaxY)/2, - (bbox.MinZ+bbox.MaxZ)/2); + return Base::Vector3d( + (bbox.MinX + bbox.MaxX) / 2, + (bbox.MinY + bbox.MaxY) / 2, + (bbox.MinZ + bbox.MaxZ) / 2 + ); } return Base::Vector3d(); @@ -100,7 +106,7 @@ void TransformStrategy::commitTransform(const Base::Matrix4D& mat) Gui::Document* doc = Gui::Application::Instance->activeDocument(); if (doc) { doc->openCommand(QT_TRANSLATE_NOOP("Command", "Transform")); - for (const auto & object : objects) { + for (const auto& object : objects) { acceptDataTransform(mat, object); } doc->commitCommand(); @@ -110,20 +116,24 @@ void TransformStrategy::commitTransform(const Base::Matrix4D& mat) void TransformStrategy::acceptDataTransform(const Base::Matrix4D& mat, App::DocumentObject* obj) { Gui::Document* doc = Gui::Application::Instance->getDocument(obj->getDocument()); - std::map props; + std::map props; obj->getPropertyMap(props); // search for the placement property - std::map::iterator jt; + std::map::iterator jt; jt = std::find_if(props.begin(), props.end(), find_transform()); if (jt != props.end()) { Base::Placement local = static_cast(jt->second)->getValue(); Gui::ViewProvider* vp = doc->getViewProvider(obj); - if (vp) vp->setTransformation(local.toMatrix()); + if (vp) { + vp->setTransformation(local.toMatrix()); + } } else { // No placement found Gui::ViewProvider* vp = doc->getViewProvider(obj); - if (vp) vp->setTransformation(Base::Matrix4D()); + if (vp) { + vp->setTransformation(Base::Matrix4D()); + } } // Apply the transformation @@ -139,7 +149,7 @@ void TransformStrategy::acceptDataTransform(const Base::Matrix4D& mat, App::Docu void TransformStrategy::applyTransform(const Base::Placement& plm) { std::set objects = transformObjects(); - for (const auto & object : objects) { + for (const auto& object : objects) { applyViewTransform(plm, object); } } @@ -147,7 +157,7 @@ void TransformStrategy::applyTransform(const Base::Placement& plm) void TransformStrategy::resetTransform() { std::set objects = transformObjects(); - for (const auto & object : objects) { + for (const auto& object : objects) { resetViewTransform(object); } } @@ -155,47 +165,56 @@ void TransformStrategy::resetTransform() void TransformStrategy::applyViewTransform(const Base::Placement& plm, App::DocumentObject* obj) { Gui::Document* doc = Gui::Application::Instance->getDocument(obj->getDocument()); - std::map props; + std::map props; obj->getPropertyMap(props); // search for the placement property - std::map::iterator jt; + std::map::iterator jt; jt = std::find_if(props.begin(), props.end(), find_transform()); if (jt != props.end()) { Base::Placement local = static_cast(jt->second)->getValue(); - local *= plm; // in case a placement is already set + local *= plm; // in case a placement is already set Gui::ViewProvider* vp = doc->getViewProvider(obj); - if (vp) vp->setTransformation(local.toMatrix()); + if (vp) { + vp->setTransformation(local.toMatrix()); + } } else { // No placement found, so apply the transformation directly Gui::ViewProvider* vp = doc->getViewProvider(obj); - if (vp) vp->setTransformation(plm.toMatrix()); + if (vp) { + vp->setTransformation(plm.toMatrix()); + } } } void TransformStrategy::resetViewTransform(App::DocumentObject* obj) { Gui::Document* doc = Gui::Application::Instance->getDocument(obj->getDocument()); - std::map props; + std::map props; obj->getPropertyMap(props); // search for the placement property - std::map::iterator jt; + std::map::iterator jt; jt = std::find_if(props.begin(), props.end(), find_transform()); if (jt != props.end()) { Base::Placement local = static_cast(jt->second)->getValue(); Gui::ViewProvider* vp = doc->getViewProvider(obj); - if (vp) vp->setTransformation(local.toMatrix()); + if (vp) { + vp->setTransformation(local.toMatrix()); + } } else { // No placement found Gui::ViewProvider* vp = doc->getViewProvider(obj); - if (vp) vp->setTransformation(Base::Matrix4D()); + if (vp) { + vp->setTransformation(Base::Matrix4D()); + } } } // ---------------------------------------------------------------------------- -DefaultTransformStrategy::DefaultTransformStrategy(QWidget* w) : widget(w) +DefaultTransformStrategy::DefaultTransformStrategy(QWidget* w) + : widget(w) { Gui::SelectionChanges mod; mod.Type = Gui::SelectionChanges::SetSelection; @@ -211,24 +230,27 @@ std::set DefaultTransformStrategy::transformObjects() cons void DefaultTransformStrategy::onSelectionChanged(const Gui::SelectionChanges& msg) { - if (msg.Type == SelectionChanges::SetPreselect || - msg.Type == SelectionChanges::RmvPreselect) - return; // nothing to do + if (msg.Type == SelectionChanges::SetPreselect || msg.Type == SelectionChanges::RmvPreselect) { + return; // nothing to do + } if (msg.Type == SelectionChanges::ClrSelection) { widget->setDisabled(true); - for (const auto & it : selection) - resetViewTransform(it); + for (const auto& it : selection) { + resetViewTransform(it); + } selection.clear(); return; } std::set update_selection; - std::vector sel = Gui::Selection().getObjectsOfType - (App::DocumentObject::getClassTypeId()); - for (const auto & it : sel) { + std::vector sel = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); + for (const auto& it : sel) { if (it->isDerivedFrom()) { // search for a data property - const App::PropertyGeometry* geo = static_cast(it)->getPropertyOfGeometry(); + const App::PropertyGeometry* geo + = static_cast(it)->getPropertyOfGeometry(); if (geo) { update_selection.insert(it); } @@ -253,19 +275,30 @@ void DefaultTransformStrategy::onSelectionChanged(const Gui::SelectionChanges& m if (!filter.empty()) { std::set diff; - std::insert_iterator< std::set > biit(diff, diff.begin()); - std::set_difference(update_selection.begin(), update_selection.end(), - filter.begin(), filter.end(), biit); + std::insert_iterator> biit(diff, diff.begin()); + std::set_difference( + update_selection.begin(), + update_selection.end(), + filter.begin(), + filter.end(), + biit + ); update_selection = diff; } // reset transform for all deselected objects std::vector diff; - std::back_insert_iterator< std::vector > biit(diff); - std::set_difference(selection.begin(), selection.end(), - update_selection.begin(), update_selection.end(), biit); - for (const auto & it : diff) - resetViewTransform(it); + std::back_insert_iterator> biit(diff); + std::set_difference( + selection.begin(), + selection.end(), + update_selection.begin(), + update_selection.end(), + biit + ); + for (const auto& it : diff) { + resetViewTransform(it); + } selection = update_selection; widget->setDisabled(selection.empty()); @@ -276,13 +309,13 @@ void DefaultTransformStrategy::onSelectionChanged(const Gui::SelectionChanges& m /* TRANSLATOR Gui::Dialog::Transform */ Transform::Transform(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), strategy(nullptr) + : QDialog(parent, fl) + , strategy(nullptr) { ui = new Ui_Placement(); ui->setupUi(this); QPushButton* applyButton = ui->buttonBox->button(QDialogButtonBox::Apply); - connect(applyButton, &QPushButton::clicked, - this, &Transform::onApplyButtonClicked); + connect(applyButton, &QPushButton::clicked, this, &Transform::onApplyButtonClicked); ui->resetButton->hide(); ui->applyIncrementalPlacement->hide(); @@ -294,13 +327,17 @@ Transform::Transform(QWidget* parent, Qt::WindowFlags fl) int id = 1; QList sb = this->findChildren(); - for (const auto & it : sb) { - connect(it, qOverload(&QuantitySpinBox::valueChanged), signalMapper, qOverload<>(&QSignalMapper::map)); + for (const auto& it : sb) { + connect( + it, + qOverload(&QuantitySpinBox::valueChanged), + signalMapper, + qOverload<>(&QSignalMapper::map) + ); signalMapper->setMapping(it, id++); } - connect(signalMapper, &QSignalMapper::mappedInt, - this, &Transform::onTransformChanged); + connect(signalMapper, &QSignalMapper::mappedInt, this, &Transform::onTransformChanged); setTransformStrategy(new DefaultTransformStrategy(this)); } @@ -313,10 +350,12 @@ Transform::~Transform() void Transform::setTransformStrategy(TransformStrategy* ts) { - if (!ts || ts == strategy) + if (!ts || ts == strategy) { return; - if (strategy) + } + if (strategy) { delete strategy; + } strategy = ts; Base::Vector3d cnt = strategy->getRotationCenter(); ui->xCnt->setValue(Base::Quantity(cnt.x, Base::Unit::Length)); @@ -357,7 +396,7 @@ void Transform::onApplyButtonClicked() // nullify the values QList sb = this->findChildren(); - for (auto & it : sb) { + for (auto& it : sb) { it->blockSignals(true); it->setValue(0.0); it->blockSignals(false); @@ -384,26 +423,37 @@ Base::Placement Transform::getPlacementData() const Base::Vector3d pos; Base::Vector3d cnt; - pos = Base::Vector3d(ui->xPos->value().getValue(),ui->yPos->value().getValue(),ui->zPos->value().getValue()); - cnt = Base::Vector3d(ui->xCnt->value().getValue(),ui->yCnt->value().getValue(),ui->zCnt->value().getValue()); + pos = Base::Vector3d( + ui->xPos->value().getValue(), + ui->yPos->value().getValue(), + ui->zPos->value().getValue() + ); + cnt = Base::Vector3d( + ui->xCnt->value().getValue(), + ui->yCnt->value().getValue(), + ui->zCnt->value().getValue() + ); if (index == 0) { Base::Vector3d dir = getDirection(); - rot.setValue(Base::Vector3d(dir.x,dir.y,dir.z), - Base::toRadians(ui->angle->value().getValue())); + rot.setValue( + Base::Vector3d(dir.x, dir.y, dir.z), + Base::toRadians(ui->angle->value().getValue()) + ); } else if (index == 1) { rot.setYawPitchRoll( ui->yawAngle->value().getValue(), ui->pitchAngle->value().getValue(), - ui->rollAngle->value().getValue()); + ui->rollAngle->value().getValue() + ); } Base::Placement p(pos, rot, cnt); return p; } -void Transform::changeEvent(QEvent *e) +void Transform::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); diff --git a/src/Gui/Transform.h b/src/Gui/Transform.h index 5b7771ee5a..eb69afee8b 100644 --- a/src/Gui/Transform.h +++ b/src/Gui/Transform.h @@ -32,8 +32,10 @@ #include "TaskView/TaskView.h" -namespace Gui { -namespace Dialog { +namespace Gui +{ +namespace Dialog +{ class GuiExport TransformStrategy { @@ -51,8 +53,7 @@ public: virtual std::set transformObjects() const = 0; }; -class GuiExport DefaultTransformStrategy : public TransformStrategy, - public Gui::SelectionObserver +class GuiExport DefaultTransformStrategy: public TransformStrategy, public Gui::SelectionObserver { public: DefaultTransformStrategy(QWidget* widget); @@ -68,7 +69,7 @@ private: }; class Ui_Placement; -class GuiExport Transform : public QDialog +class GuiExport Transform: public QDialog { Q_OBJECT @@ -82,7 +83,7 @@ public: protected: Base::Vector3d getDirection() const; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; public: void onApplyButtonClicked(); @@ -98,7 +99,7 @@ private: TransformStrategy* strategy; }; -class GuiExport TaskTransform : public Gui::TaskView::TaskDialog +class GuiExport TaskTransform: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -113,15 +114,15 @@ public: void setTransformStrategy(TransformStrategy* ts); QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok | - QDialogButtonBox::Apply | - QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; + } private: Transform* dialog; }; -} // namespace Dialog -} // namespace Gui +} // namespace Dialog +} // namespace Gui -#endif // GUI_TRANSFORM_H +#endif // GUI_TRANSFORM_H diff --git a/src/Gui/Tree.cpp b/src/Gui/Tree.cpp index 664eafc1ec..96df7570a3 100644 --- a/src/Gui/Tree.cpp +++ b/src/Gui/Tree.cpp @@ -21,25 +21,23 @@ ***************************************************************************/ - - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -72,21 +70,21 @@ FC_LOG_LEVEL_INIT("Tree", false, true, true) -#define _TREE_PRINT(_level,_func,_msg) \ - _FC_PRINT(FC_LOG_INSTANCE,_level,_func, '['<,_msg) -#define TREE_WARN(_msg) _TREE_PRINT(FC_LOGLEVEL_WARN,notify,_msg) -#define TREE_ERR(_msg) _TREE_PRINT(FC_LOGLEVEL_ERR,notify,_msg) -#define TREE_LOG(_msg) _TREE_PRINT(FC_LOGLEVEL_LOG,notify,_msg) -#define TREE_TRACE(_msg) _TREE_PRINT(FC_LOGLEVEL_TRACE,notify,_msg) +#define _TREE_PRINT(_level, _func, _msg) \ + _FC_PRINT(FC_LOG_INSTANCE, _level, _func, '[' << getTreeName() << "] " << _msg) +#define TREE_MSG(_msg) _TREE_PRINT(FC_LOGLEVEL_MSG, notify, _msg) +#define TREE_WARN(_msg) _TREE_PRINT(FC_LOGLEVEL_WARN, notify, _msg) +#define TREE_ERR(_msg) _TREE_PRINT(FC_LOGLEVEL_ERR, notify, _msg) +#define TREE_LOG(_msg) _TREE_PRINT(FC_LOGLEVEL_LOG, notify, _msg) +#define TREE_TRACE(_msg) _TREE_PRINT(FC_LOGLEVEL_TRACE, notify, _msg) using namespace Gui; namespace sp = std::placeholders; ///////////////////////////////////////////////////////////////////////////////// -std::unique_ptr TreeWidget::documentPixmap; -std::unique_ptr TreeWidget::documentPartialPixmap; +std::unique_ptr TreeWidget::documentPixmap; +std::unique_ptr TreeWidget::documentPartialPixmap; static QBrush _TreeItemBackground; std::set TreeWidget::Instances; static TreeWidget* _LastSelectedTreeWidget; @@ -95,16 +93,18 @@ const int TreeWidget::ObjectType = 1001; static bool _DraggingActive; static bool _DragEventFilter; -static bool isVisibilityIconEnabled() { +static bool isVisibilityIconEnabled() +{ return TreeParams::getVisibilityIcon(); } -static bool isOnlyNameColumnDisplayed() { - return TreeParams::getHideInternalNames() - && TreeParams::getHideColumn(); +static bool isOnlyNameColumnDisplayed() +{ + return TreeParams::getHideInternalNames() && TreeParams::getHideColumn(); } -static bool isSelectionCheckBoxesEnabled() { +static bool isSelectionCheckBoxesEnabled() +{ return TreeParams::getCheckBoxesSelection(); } @@ -119,36 +119,41 @@ void TreeParams::onItemBackgroundChanged() col.setBlueF(color.b); col.setAlphaF(color.a); _TreeItemBackground = QBrush(col); - } else + } + else { _TreeItemBackground = QBrush(); + } refreshTreeViews(); } ////////////////////////////////////////////////////////////////////////////////////// -struct Stats { +struct Stats +{ #define DEFINE_STATS \ DEFINE_STAT(testStatus1) \ DEFINE_STAT(testStatus2) \ DEFINE_STAT(testStatus3) \ DEFINE_STAT(getIcon) \ - DEFINE_STAT(setIcon) \ + DEFINE_STAT(setIcon) #define DEFINE_STAT(_name) \ - FC_DURATION_DECLARE(_name);\ + FC_DURATION_DECLARE(_name); \ int _name##_count; DEFINE_STATS - void init() { + void init() + { #undef DEFINE_STAT #define DEFINE_STAT(_name) \ - FC_DURATION_INIT(_name);\ - _name##_count = 0; + FC_DURATION_INIT(_name); \ + _name##_count = 0; DEFINE_STATS } - void print() { + void print() + { #undef DEFINE_STAT #define DEFINE_STAT(_name) FC_DURATION_MSG(_name, #_name " count: " << _name##_count); DEFINE_STATS @@ -156,35 +161,40 @@ struct Stats { #undef DEFINE_STAT #define DEFINE_STAT(_name) \ - void time_##_name(FC_TIME_POINT &t) {\ - ++_name##_count;\ - FC_DURATION_PLUS(_name,t);\ + void time_##_name(FC_TIME_POINT& t) \ + { \ + ++_name##_count; \ + FC_DURATION_PLUS(_name, t); \ } DEFINE_STATS }; -//static Stats _Stats; +// static Stats _Stats; -struct TimingInfo { +struct TimingInfo +{ bool timed = false; FC_TIME_POINT t; FC_DURATION& d; explicit TimingInfo(FC_DURATION& d) - :d(d) + : d(d) { _FC_TIME_INIT(t); } - ~TimingInfo() { + ~TimingInfo() + { stop(); } - void stop() { + void stop() + { if (!timed) { timed = true; FC_DURATION_PLUS(d, t); } } - void reset() { + void reset() + { stop(); _FC_TIME_INIT(t); } @@ -192,32 +202,47 @@ struct TimingInfo { // #define DO_TIMING #ifdef DO_TIMING -#define _Timing(_idx,_name) ++_Stats._name##_count; TimingInfo _tt##_idx(_Stats._name) -#define Timing(_name) _Timing(0,_name) -#define _TimingStop(_idx,_name) _tt##_idx.stop(); -#define TimingStop(_name) _TimingStop(0,_name); -#define TimingInit() _Stats.init(); -#define TimingPrint() _Stats.print(); +# define _Timing(_idx, _name) \ + ++_Stats._name##_count; \ + TimingInfo _tt##_idx(_Stats._name) +# define Timing(_name) _Timing(0, _name) +# define _TimingStop(_idx, _name) _tt##_idx.stop(); +# define TimingStop(_name) _TimingStop(0, _name); +# define TimingInit() _Stats.init(); +# define TimingPrint() _Stats.print(); #else -#define _Timing(...) do{}while(0) -#define Timing(...) do{}while(0) -#define TimingInit() do{}while(0) -#define TimingPrint() do{}while(0) -#define _TimingStop(...) do{}while(0); -#define TimingStop(...) do{}while(0); +# define _Timing(...) \ + do { \ + } while (0) +# define Timing(...) \ + do { \ + } while (0) +# define TimingInit() \ + do { \ + } while (0) +# define TimingPrint() \ + do { \ + } while (0) +# define _TimingStop(...) \ + do { \ + } while (0); +# define TimingStop(...) \ + do { \ + } while (0); #endif // --------------------------------------------------------------------------- using DocumentObjectItems = std::set; -class Gui::DocumentObjectData { +class Gui::DocumentObjectData +{ public: bool dirtyFlag {}; DocumentItem* docItem; DocumentObjectItems items; ViewProviderDocumentObject* viewObject; - DocumentObjectItem* rootItem{nullptr}; + DocumentObjectItem* rootItem {nullptr}; std::vector children; std::set childSet; bool removeChildrenFromRoot; @@ -237,17 +262,21 @@ public: : docItem(docItem) , viewObject(vpd) { - //NOLINTBEGIN - // Setup connections + // NOLINTBEGIN + // Setup connections connectIcon = viewObject->signalChangeIcon.connect( - std::bind(&DocumentObjectData::slotChangeIcon, this)); + std::bind(&DocumentObjectData::slotChangeIcon, this) + ); connectTool = viewObject->signalChangeToolTip.connect( - std::bind(&DocumentObjectData::slotChangeToolTip, this, sp::_1)); + std::bind(&DocumentObjectData::slotChangeToolTip, this, sp::_1) + ); connectStat = viewObject->signalChangeStatusTip.connect( - std::bind(&DocumentObjectData::slotChangeStatusTip, this, sp::_1)); + std::bind(&DocumentObjectData::slotChangeStatusTip, this, sp::_1) + ); connectHl = viewObject->signalChangeHighlight.connect( - std::bind(&DocumentObjectData::slotChangeHighlight, this, sp::_1, sp::_2)); - //NOLINTEND + std::bind(&DocumentObjectData::slotChangeHighlight, this, sp::_1, sp::_2) + ); + // NOLINTEND removeChildrenFromRoot = viewObject->canRemoveChildrenFromRoot(); itemHidden = !viewObject->showInTree(); @@ -274,42 +303,46 @@ public: } } - const char* getTreeName() const { + const char* getTreeName() const + { return docItem->getTreeName(); } - void updateChildren(DocumentObjectDataPtr other) { + void updateChildren(DocumentObjectDataPtr other) + { children = other->children; childSet = other->childSet; } - bool updateChildren(bool checkVisibility) { + bool updateChildren(bool checkVisibility) + { auto newChildren = viewObject->claimChildren(); auto obj = viewObject->getObject(); std::set newSet; bool updated = false; for (auto child : newChildren) { auto childVp = docItem->getViewProvider(child); - if (!childVp) + if (!childVp) { continue; + } if (child && child->isAttachedToDocument()) { if (!newSet.insert(child).second) { - TREE_WARN("duplicate child item " << obj->getFullName() - << '.' << child->getNameInDocument()); + TREE_WARN( + "duplicate child item " << obj->getFullName() << '.' + << child->getNameInDocument() + ); } else if (!childSet.erase(child)) { // this means new child detected updated = true; - if (child->getDocument() == obj->getDocument() && - child->getDocument() == docItem->document()->getDocument()) - { + if (child->getDocument() == obj->getDocument() + && child->getDocument() == docItem->document()->getDocument()) { auto& parents = docItem->_ParentMap[child]; if (parents.insert(obj).second && child->Visibility.getValue()) { bool showable = false; for (auto parent : parents) { if (!parent->hasChildElement() - && parent->getLinkedObject(false) == parent) - { + && parent->getLinkedObject(false) == parent) { showable = true; break; } @@ -332,8 +365,9 @@ public: docItem->_ParentMap[child].erase(obj); auto childVp = docItem->getViewProvider(child); - if (childVp && child->getDocument() == obj->getDocument()) + if (childVp && child->getDocument() == obj->getDocument()) { childVp->setShowable(docItem->isObjectShowable(child)); + } } } } @@ -345,53 +379,64 @@ public: if (updated && checkVisibility) { for (auto child : children) { auto childVp = docItem->getViewProvider(child); - if (childVp && child->getDocument() == obj->getDocument()) + if (childVp && child->getDocument() == obj->getDocument()) { childVp->setShowable(docItem->isObjectShowable(child)); + } } } return updated; } - void testStatus(bool resetStatus = false) { + void testStatus(bool resetStatus = false) + { QIcon icon, icon2; - for (auto item : items) + for (auto item : items) { item->testStatus(resetStatus, icon, icon2); + } } - void slotChangeIcon() { + void slotChangeIcon() + { testStatus(true); } - void slotChangeToolTip(const QString& tip) { - for (auto item : items) + void slotChangeToolTip(const QString& tip) + { + for (auto item : items) { item->setToolTip(0, tip); + } } - void slotChangeStatusTip(const QString& tip) { - for (auto item : items) + void slotChangeStatusTip(const QString& tip) + { + for (auto item : items) { item->setStatusTip(0, tip); + } } - void slotChangeHighlight(bool set, Gui::HighlightMode mode) { - for (auto item : items) + void slotChangeHighlight(bool set, Gui::HighlightMode mode) + { + for (auto item : items) { item->setHighlight(set, mode); + } } }; // --------------------------------------------------------------------------- -class DocumentItem::ExpandInfo : - public std::unordered_map +class DocumentItem::ExpandInfo: public std::unordered_map { public: - void restore(Base::XMLReader& reader) { + void restore(Base::XMLReader& reader) + { int level = reader.level(); int count = reader.getAttribute("count"); for (int i = 0; i < count; ++i) { reader.readElement("Expand"); auto& entry = (*this)[reader.getAttribute("name")]; - if (!reader.hasAttribute("count")) + if (!reader.hasAttribute("count")) { continue; + } entry.reset(new ExpandInfo); entry->restore(reader); } @@ -401,11 +446,13 @@ public: // --------------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /** * TreeWidget item delegate for editing */ -class TreeWidgetItemDelegate: public QStyledItemDelegate { +class TreeWidgetItemDelegate: public QStyledItemDelegate +{ typedef QStyledItemDelegate inherited; // Beware, big scary hack incoming! @@ -418,35 +465,42 @@ class TreeWidgetItemDelegate: public QStyledItemDelegate { // that will be for painter to read information and draw proper backgrounds only when asked. // // More information: https://github.com/FreeCAD/FreeCAD/pull/13807 - QTreeView *artificial; + QTreeView* artificial; - QRect calculateItemRect(const QStyleOptionViewItem &option) const; + QRect calculateItemRect(const QStyleOptionViewItem& option) const; public: - explicit TreeWidgetItemDelegate(QObject* parent=nullptr); + explicit TreeWidgetItemDelegate(QObject* parent = nullptr); - virtual QWidget* createEditor(QWidget *parent, - const QStyleOptionViewItem &, const QModelIndex &index) const; + virtual QWidget* createEditor( + QWidget* parent, + const QStyleOptionViewItem&, + const QModelIndex& index + ) const; - virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + virtual QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const; - virtual void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const; + virtual void initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const; - virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; + virtual void paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const; }; -} // namespace Gui +} // namespace Gui TreeWidgetItemDelegate::TreeWidgetItemDelegate(QObject* parent) : QStyledItemDelegate(parent) { artificial = new QTreeView(qobject_cast(parent)); artificial->setObjectName(QStringLiteral("DocumentTreeItems")); - artificial->setFixedSize(0, 0); // ensure that it does not render + artificial->setFixedSize(0, 0); // ensure that it does not render } -QRect TreeWidgetItemDelegate::calculateItemRect(const QStyleOptionViewItem &option) const +QRect TreeWidgetItemDelegate::calculateItemRect(const QStyleOptionViewItem& option) const { auto tree = static_cast(parent()); auto style = tree->style(); @@ -456,16 +510,12 @@ QRect TreeWidgetItemDelegate::calculateItemRect(const QStyleOptionViewItem &opti const int margin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, artificial) + 1; // 2 margin for text, 2 margin for decoration (icon) = 4 times margin - int width = 4 * margin - + option.fontMetrics.boundingRect(option.text).width() - + option.decorationSize.width() - + TreeParams::getItemBackgroundPadding() - ; + int width = 4 * margin + option.fontMetrics.boundingRect(option.text).width() + + option.decorationSize.width() + TreeParams::getItemBackgroundPadding(); if (TreeParams::getCheckBoxesSelection()) { // another 2 margin for checkbox - width += 2 * margin - + style->pixelMetric(QStyle::PM_IndicatorWidth) + width += 2 * margin + style->pixelMetric(QStyle::PM_IndicatorWidth) + style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); } @@ -476,8 +526,11 @@ QRect TreeWidgetItemDelegate::calculateItemRect(const QStyleOptionViewItem &opti return rect; } -void TreeWidgetItemDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, const QModelIndex &index) const +void TreeWidgetItemDelegate::paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index +) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); @@ -491,14 +544,15 @@ void TreeWidgetItemDelegate::paint(QPainter *painter, if (index.column() == 0) { if (tree->testAttribute(Qt::WA_NoSystemBackground) - && (trimColumnSize || (opt.backgroundBrush.style() == Qt::NoBrush - && _TreeItemBackground.style() != Qt::NoBrush))) - { + && (trimColumnSize + || (opt.backgroundBrush.style() == Qt::NoBrush + && _TreeItemBackground.style() != Qt::NoBrush))) { QRect rect = calculateItemRect(option); if (trimColumnSize && opt.backgroundBrush.style() == Qt::NoBrush) { painter->fillRect(rect, _TreeItemBackground); - } else if (!opt.state.testFlag(QStyle::State_Selected)) { + } + else if (!opt.state.testFlag(QStyle::State_Selected)) { painter->fillRect(rect, _TreeItemBackground); } } @@ -506,8 +560,7 @@ void TreeWidgetItemDelegate::paint(QPainter *painter, style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, artificial); } -void TreeWidgetItemDelegate::initStyleOption(QStyleOptionViewItem *option, - const QModelIndex &index) const +void TreeWidgetItemDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const { inherited::initStyleOption(option, index); @@ -528,10 +581,8 @@ void TreeWidgetItemDelegate::initStyleOption(QStyleOptionViewItem *option, QSize size = option->icon.actualSize(QSize(0xffff, 0xffff)); if (size.height() > 0) { - option->decorationSize = QSize( - size.width() * TreeWidget::iconSize() / size.height(), - TreeWidget::iconSize() - ); + option->decorationSize + = QSize(size.width() * TreeWidget::iconSize() / size.height(), TreeWidget::iconSize()); } if (isOnlyNameColumnDisplayed()) { @@ -543,57 +594,63 @@ void TreeWidgetItemDelegate::initStyleOption(QStyleOptionViewItem *option, } } -class DynamicQLineEdit : public ExpLineEdit +class DynamicQLineEdit: public ExpLineEdit { public: - DynamicQLineEdit(QWidget *parent = nullptr) : ExpLineEdit(parent) {} + DynamicQLineEdit(QWidget* parent = nullptr) + : ExpLineEdit(parent) + {} QSize sizeHint() const override { QSize size = QLineEdit::sizeHint(); QFontMetrics fm(font()); - int availableWidth = parentWidget()->width() - geometry().x(); // Calculate available width + int availableWidth = parentWidget()->width() - geometry().x(); // Calculate available width int margin = 2 * (style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1) - + 2 * style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing) - + TreeParams::getItemBackgroundPadding(); - size.setWidth(std::min(fm.horizontalAdvance(text()) + margin , availableWidth)); + + 2 * style()->pixelMetric(QStyle::PM_LayoutHorizontalSpacing) + + TreeParams::getItemBackgroundPadding(); + size.setWidth(std::min(fm.horizontalAdvance(text()) + margin, availableWidth)); return size; } // resize on key presses - void keyPressEvent(QKeyEvent *event) override + void keyPressEvent(QKeyEvent* event) override { ExpLineEdit::keyPressEvent(event); setMinimumWidth(sizeHint().width()); } - }; QWidget* TreeWidgetItemDelegate::createEditor( - QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const + QWidget* parent, + const QStyleOptionViewItem&, + const QModelIndex& index +) const { auto ti = static_cast(index.internalPointer()); - if (ti->type() != TreeWidget::ObjectType || index.column() > 1) + if (ti->type() != TreeWidget::ObjectType || index.column() > 1) { return nullptr; + } auto item = static_cast(ti); App::DocumentObject* obj = item->object()->getObject(); auto& prop = index.column() ? obj->Label2 : obj->Label; - DynamicQLineEdit *editor; - if(TreeParams::getLabelExpression()) { - DynamicQLineEdit *le = new DynamicQLineEdit(parent); + DynamicQLineEdit* editor; + if (TreeParams::getLabelExpression()) { + DynamicQLineEdit* le = new DynamicQLineEdit(parent); le->setAutoApply(true); le->setFrame(false); le->bind(App::ObjectIdentifier(prop)); editor = le; - } else { + } + else { editor = new DynamicQLineEdit(parent); } editor->setReadOnly(prop.isReadOnly()); return editor; } -QSize TreeWidgetItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +QSize TreeWidgetItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QSize size = QStyledItemDelegate::sizeHint(option, index); int spacing = std::max(0, static_cast(TreeParams::getItemSpacing())); @@ -603,7 +660,8 @@ QSize TreeWidgetItemDelegate::sizeHint(const QStyleOptionViewItem &option, const // --------------------------------------------------------------------------- TreeWidget::TreeWidget(const char* name, QWidget* parent) - : QTreeWidget(parent), SelectionObserver(true, ResolveMode::NoResolve) + : QTreeWidget(parent) + , SelectionObserver(true, ResolveMode::NoResolve) , contextItem(nullptr) , searchObject(nullptr) , searchDoc(nullptr) @@ -613,8 +671,9 @@ TreeWidget::TreeWidget(const char* name, QWidget* parent) , myName(name) { Instances.insert(this); - if (!_LastSelectedTreeWidget) + if (!_LastSelectedTreeWidget) { _LastSelectedTreeWidget = this; + } this->setDragEnabled(true); this->setAcceptDrops(true); @@ -624,93 +683,107 @@ TreeWidget::TreeWidget(const char* name, QWidget* parent) this->showHiddenAction = new QAction(this); this->showHiddenAction->setCheckable(true); - connect(this->showHiddenAction, &QAction::triggered, - this, &TreeWidget::onShowHidden); + connect(this->showHiddenAction, &QAction::triggered, this, &TreeWidget::onShowHidden); this->toggleVisibilityInTreeAction = new QAction(this); - connect(this->toggleVisibilityInTreeAction, &QAction::triggered, - this, &TreeWidget::onToggleVisibilityInTree); + connect( + this->toggleVisibilityInTreeAction, + &QAction::triggered, + this, + &TreeWidget::onToggleVisibilityInTree + ); this->createGroupAction = new QAction(this); - connect(this->createGroupAction, &QAction::triggered, - this, &TreeWidget::onCreateGroup); + connect(this->createGroupAction, &QAction::triggered, this, &TreeWidget::onCreateGroup); this->relabelObjectAction = new QAction(this); #ifndef Q_OS_MAC this->relabelObjectAction->setShortcut(Qt::Key_F2); #endif - connect(this->relabelObjectAction, &QAction::triggered, - this, &TreeWidget::onRelabelObject); + connect(this->relabelObjectAction, &QAction::triggered, this, &TreeWidget::onRelabelObject); this->finishEditingAction = new QAction(this); - connect(this->finishEditingAction, &QAction::triggered, - this, &TreeWidget::onFinishEditing); + connect(this->finishEditingAction, &QAction::triggered, this, &TreeWidget::onFinishEditing); this->selectDependentsAction = new QAction(this); - connect(this->selectDependentsAction, &QAction::triggered, - this, &TreeWidget::onSelectDependents); + connect(this->selectDependentsAction, &QAction::triggered, this, &TreeWidget::onSelectDependents); this->closeDocAction = new QAction(this); - connect(this->closeDocAction, &QAction::triggered, - this, &TreeWidget::onCloseDoc); + connect(this->closeDocAction, &QAction::triggered, this, &TreeWidget::onCloseDoc); this->reloadDocAction = new QAction(this); - connect(this->reloadDocAction, &QAction::triggered, - this, &TreeWidget::onReloadDoc); + connect(this->reloadDocAction, &QAction::triggered, this, &TreeWidget::onReloadDoc); this->skipRecomputeAction = new QAction(this); this->skipRecomputeAction->setCheckable(true); - connect(this->skipRecomputeAction, &QAction::toggled, - this, &TreeWidget::onSkipRecompute); - this->skipRecomputeCommand = Gui::Application::Instance->commandManager().getCommandByName("Std_ToggleSkipRecompute"); + connect(this->skipRecomputeAction, &QAction::toggled, this, &TreeWidget::onSkipRecompute); + this->skipRecomputeCommand = Gui::Application::Instance->commandManager().getCommandByName( + "Std_ToggleSkipRecompute" + ); this->allowPartialRecomputeAction = new QAction(this); this->allowPartialRecomputeAction->setCheckable(true); - connect(this->allowPartialRecomputeAction, &QAction::toggled, - this, &TreeWidget::onAllowPartialRecompute); + connect( + this->allowPartialRecomputeAction, + &QAction::toggled, + this, + &TreeWidget::onAllowPartialRecompute + ); this->markRecomputeAction = new QAction(this); - connect(this->markRecomputeAction, &QAction::triggered, - this, &TreeWidget::onMarkRecompute); + connect(this->markRecomputeAction, &QAction::triggered, this, &TreeWidget::onMarkRecompute); this->recomputeObjectAction = new QAction(this); - connect(this->recomputeObjectAction, &QAction::triggered, - this, &TreeWidget::onRecomputeObject); + connect(this->recomputeObjectAction, &QAction::triggered, this, &TreeWidget::onRecomputeObject); this->searchObjectsAction = new QAction(this); this->searchObjectsAction->setText(tr("Search Objects")); this->searchObjectsAction->setStatusTip(tr("Searches for objects in the tree")); - connect(this->searchObjectsAction, &QAction::triggered, - this, &TreeWidget::onSearchObjects); + connect(this->searchObjectsAction, &QAction::triggered, this, &TreeWidget::onSearchObjects); this->openFileLocationAction = new QAction(this); - connect(this->openFileLocationAction, &QAction::triggered, - this, &TreeWidget::onOpenFileLocation); + connect(this->openFileLocationAction, &QAction::triggered, this, &TreeWidget::onOpenFileLocation); - //NOLINTBEGIN - // Setup connections - connectNewDocument = Application::Instance->signalNewDocument.connect(std::bind(&TreeWidget::slotNewDocument, this, sp::_1, sp::_2)); - connectDelDocument = Application::Instance->signalDeleteDocument.connect(std::bind(&TreeWidget::slotDeleteDocument, this, sp::_1)); - connectRenDocument = Application::Instance->signalRenameDocument.connect(std::bind(&TreeWidget::slotRenameDocument, this, sp::_1)); - connectActDocument = Application::Instance->signalActiveDocument.connect(std::bind(&TreeWidget::slotActiveDocument, this, sp::_1)); - connectRelDocument = Application::Instance->signalRelabelDocument.connect(std::bind(&TreeWidget::slotRelabelDocument, this, sp::_1)); - connectShowHidden = Application::Instance->signalShowHidden.connect(std::bind(&TreeWidget::slotShowHidden, this, sp::_1)); + // NOLINTBEGIN + // Setup connections + connectNewDocument = Application::Instance->signalNewDocument.connect( + std::bind(&TreeWidget::slotNewDocument, this, sp::_1, sp::_2) + ); + connectDelDocument = Application::Instance->signalDeleteDocument.connect( + std::bind(&TreeWidget::slotDeleteDocument, this, sp::_1) + ); + connectRenDocument = Application::Instance->signalRenameDocument.connect( + std::bind(&TreeWidget::slotRenameDocument, this, sp::_1) + ); + connectActDocument = Application::Instance->signalActiveDocument.connect( + std::bind(&TreeWidget::slotActiveDocument, this, sp::_1) + ); + connectRelDocument = Application::Instance->signalRelabelDocument.connect( + std::bind(&TreeWidget::slotRelabelDocument, this, sp::_1) + ); + connectShowHidden = Application::Instance->signalShowHidden.connect( + std::bind(&TreeWidget::slotShowHidden, this, sp::_1) + ); // Gui::Document::signalChangedObject informs the App::Document property // change, not view provider's own property, which is what the signal below // for connectChangedViewObj = Application::Instance->signalChangedObject.connect( - std::bind(&TreeWidget::slotChangedViewObject, this, sp::_1, sp::_2)); - //NOLINTEND + std::bind(&TreeWidget::slotChangedViewObject, this, sp::_1, sp::_2) + ); + // NOLINTEND setupResizableColumn(this); this->header()->setStretchLastSection(true); QObject::connect(this->header(), &QHeaderView::sectionResized, [](int idx, int, int newSize) { - if (idx == 1) + if (idx == 1) { TreeParams::setColumnSize2(newSize); - else if (idx == 2) - TreeParams::setColumnSize3(newSize); - else - TreeParams::setColumnSize1(newSize); + } + else if (idx == 2) { + TreeParams::setColumnSize3(newSize); + } + else { + TreeParams::setColumnSize1(newSize); + } }); // Add the first main label @@ -718,7 +791,7 @@ TreeWidget::TreeWidget(const char* name, QWidget* parent) this->expandItem(this->rootItem); this->setSelectionMode(QAbstractItemView::ExtendedSelection); - this->setMouseTracking(true); // needed for itemEntered() to work + this->setMouseTracking(true); // needed for itemEntered() to work this->preselectTimer = new QTimer(this); @@ -734,8 +807,7 @@ TreeWidget::TreeWidget(const char* name, QWidget* parent) connect(this, &QTreeWidget::itemEntered, this, &TreeWidget::onItemEntered); connect(this, &QTreeWidget::itemCollapsed, this, &TreeWidget::onItemCollapsed); connect(this, &QTreeWidget::itemExpanded, this, &TreeWidget::onItemExpanded); - connect(this, &QTreeWidget::itemSelectionChanged, - this, &TreeWidget::onItemSelectionChanged); + connect(this, &QTreeWidget::itemSelectionChanged, this, &TreeWidget::onItemSelectionChanged); connect(this, &QTreeWidget::itemChanged, this, &TreeWidget::onItemChanged); connect(this->preselectTimer, &QTimer::timeout, this, &TreeWidget::onPreSelectTimer); connect(this->selectTimer, &QTimer::timeout, this, &TreeWidget::onSelectTimer); @@ -745,7 +817,9 @@ TreeWidget::TreeWidget(const char* name, QWidget* parent) if (!documentPixmap) { documentPixmap = std::make_unique(Gui::BitmapFactory().pixmap("Document")); QIcon icon(*documentPixmap); - documentPartialPixmap = std::make_unique(icon.pixmap(documentPixmap->size(), QIcon::Disabled)); + documentPartialPixmap = std::make_unique( + icon.pixmap(documentPixmap->size(), QIcon::Disabled) + ); } setColumnHidden(1, TreeParams::getHideColumn()); setColumnHidden(2, TreeParams::getHideInternalNames()); @@ -763,49 +837,61 @@ TreeWidget::~TreeWidget() connectShowHidden.disconnect(); connectChangedViewObj.disconnect(); Instances.erase(this); - if (_LastSelectedTreeWidget == this) + if (_LastSelectedTreeWidget == this) { _LastSelectedTreeWidget = nullptr; + } } -const char* TreeWidget::getTreeName() const { +const char* TreeWidget::getTreeName() const +{ return myName.c_str(); } // reimpelement to select only objects in the active document -void TreeWidget::selectAll() { - auto gdoc = Application::Instance->getDocument( - App::GetApplication().getActiveDocument()); - if (!gdoc) +void TreeWidget::selectAll() +{ + auto gdoc = Application::Instance->getDocument(App::GetApplication().getActiveDocument()); + if (!gdoc) { return; + } auto itDoc = DocumentMap.find(gdoc); - if (itDoc == DocumentMap.end()) + if (itDoc == DocumentMap.end()) { return; - if (TreeParams::getRecordSelection()) + } + if (TreeParams::getRecordSelection()) { Gui::Selection().selStackPush(); + } Gui::Selection().clearSelection(); Gui::Selection().setSelection(gdoc->getDocument()->getName(), gdoc->getDocument()->getObjects()); } -bool TreeWidget::isObjectShowable(App::DocumentObject* obj) { - if (!obj || !obj->isAttachedToDocument()) +bool TreeWidget::isObjectShowable(App::DocumentObject* obj) +{ + if (!obj || !obj->isAttachedToDocument()) { return true; + } Gui::Document* doc = Application::Instance->getDocument(obj->getDocument()); - if (!doc) + if (!doc) { return true; - if (Instances.empty()) + } + if (Instances.empty()) { return true; + } auto tree = *Instances.begin(); auto it = tree->DocumentMap.find(doc); - if (it != tree->DocumentMap.end()) + if (it != tree->DocumentMap.end()) { return it->second->isObjectShowable(obj); + } return true; } static bool _DisableCheckTopParent; -void TreeWidget::checkTopParent(App::DocumentObject*& obj, std::string& subname) { - if (_DisableCheckTopParent) +void TreeWidget::checkTopParent(App::DocumentObject*& obj, std::string& subname) +{ + if (_DisableCheckTopParent) { return; + } if (!Instances.empty() && obj && obj->isAttachedToDocument()) { auto tree = *Instances.begin(); auto it = tree->DocumentMap.find(Application::Instance->getDocument(obj->getDocument())); @@ -816,28 +902,34 @@ void TreeWidget::checkTopParent(App::DocumentObject*& obj, std::string& subname) tree->blockSelection(locked); } auto parent = it->second->getTopParent(obj, subname); - if (parent) + if (parent) { obj = parent; + } } } } -void TreeWidget::resetItemSearch() { - if (!searchObject) +void TreeWidget::resetItemSearch() +{ + if (!searchObject) { return; + } auto it = ObjectTable.find(searchObject); if (it != ObjectTable.end()) { for (auto& data : it->second) { - if (!data) + if (!data) { continue; - for (auto item : data->items) + } + for (auto item : data->items) { static_cast(item)->restoreBackground(); + } } } searchObject = nullptr; } -void TreeWidget::startItemSearch(QLineEdit* edit) { +void TreeWidget::startItemSearch(QLineEdit* edit) +{ resetItemSearch(); searchDoc = nullptr; searchContextDoc = nullptr; @@ -852,20 +944,25 @@ void TreeWidget::startItemSearch(QLineEdit* edit) { searchContextDoc = item->getOwnerDocument()->document(); } } - else + else { searchDoc = Application::Instance->activeDocument(); + } App::DocumentObject* obj = nullptr; - if (searchContextDoc && !searchContextDoc->getDocument()->getObjects().empty()) + if (searchContextDoc && !searchContextDoc->getDocument()->getObjects().empty()) { obj = searchContextDoc->getDocument()->getObjects().front(); - else if (searchDoc && !searchDoc->getDocument()->getObjects().empty()) + } + else if (searchDoc && !searchDoc->getDocument()->getObjects().empty()) { obj = searchDoc->getDocument()->getObjects().front(); + } - if (obj) + if (obj) { static_cast(edit)->setDocumentObject(obj); + } } -void TreeWidget::itemSearch(const QString& text, bool select) { +void TreeWidget::itemSearch(const QString& text, bool select) +{ resetItemSearch(); auto docItem = getDocumentItem(searchDoc); @@ -886,21 +983,25 @@ void TreeWidget::itemSearch(const QString& text, bool select) { } std::string txt(text.toUtf8().constData()); try { - if (txt.empty()) + if (txt.empty()) { return; + } if (txt.find("<<") == std::string::npos) { auto pos = txt.find('.'); - if (pos == std::string::npos) + if (pos == std::string::npos) { txt += '.'; + } else if (pos != txt.size() - 1) { txt.insert(pos + 1, "<<"); - if (txt.back() != '.') + if (txt.back() != '.') { txt += '.'; + } txt += ">>."; } } - else if (txt.back() != '.') + else if (txt.back() != '.') { txt += '.'; + } txt += "_self"; auto path = App::ObjectIdentifier::parse(objs.front(), txt); if (path.getPropertyName() != "_self") { @@ -934,8 +1035,9 @@ void TreeWidget::itemSearch(const QString& text, bool select) { return; } auto it = DocumentMap.find(Application::Instance->getDocument(obj->getDocument())); - if (it == DocumentMap.end()) + if (it == DocumentMap.end()) { return; + } docItem = it->second; parent = docItem->getTopParent(obj, subname); } @@ -947,14 +1049,23 @@ void TreeWidget::itemSearch(const QString& text, bool select) { return; } scrollToItem(item); - Selection().setPreselect(obj->getDocument()->getName(), - obj->getNameInDocument(), subname.c_str(), 0, 0, 0, - SelectionChanges::MsgSource::TreeView); + Selection().setPreselect( + obj->getDocument()->getName(), + obj->getNameInDocument(), + subname.c_str(), + 0, + 0, + 0, + SelectionChanges::MsgSource::TreeView + ); if (select) { Gui::Selection().selStackPush(); Gui::Selection().clearSelection(); - Gui::Selection().addSelection(obj->getDocument()->getName(), - obj->getNameInDocument(), subname.c_str()); + Gui::Selection().addSelection( + obj->getDocument()->getName(), + obj->getNameInDocument(), + subname.c_str() + ); Gui::Selection().selStackPush(); } else { @@ -963,29 +1074,34 @@ void TreeWidget::itemSearch(const QString& text, bool select) { } FC_TRACE("found item " << txt); } - catch (...) - { + catch (...) { FC_TRACE("item " << txt << " search exception in " << doc->getName()); } } -Gui::Document* TreeWidget::selectedDocument() { +Gui::Document* TreeWidget::selectedDocument() +{ for (auto tree : Instances) { - if (!tree->isVisible()) + if (!tree->isVisible()) { continue; + } auto sels = tree->selectedItems(); - if (sels.size() == 1 && sels[0]->type() == DocumentType) + if (sels.size() == 1 && sels[0]->type() == DocumentType) { return static_cast(sels[0])->document(); + } } return nullptr; } -void TreeWidget::updateStatus(bool delay) { - for (auto tree : Instances) +void TreeWidget::updateStatus(bool delay) +{ + for (auto tree : Instances) { tree->_updateStatus(delay); + } } -void TreeWidget::_updateStatus(bool delay) { +void TreeWidget::_updateStatus(bool delay) +{ // When running from a different thread Qt will raise a warning // when trying to start the QTimer if (Q_UNLIKELY(thread() != QThread::currentThread())) { @@ -993,13 +1109,15 @@ void TreeWidget::_updateStatus(bool delay) { } if (!delay) { - if (!ChangedObjects.empty() || !NewObjects.empty()) + if (!ChangedObjects.empty() || !NewObjects.empty()) { onUpdateStatus(); + } return; } int timeout = TreeParams::getStatusTimeout(); - if (timeout < 0) + if (timeout < 0) { timeout = 1; + } statusTimer->start(timeout); } @@ -1018,8 +1136,7 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) QMenu editMenu; QActionGroup subMenuGroup(&subMenu); subMenuGroup.setExclusive(true); - connect(&subMenuGroup, &QActionGroup::triggered, - this, &TreeWidget::onActivateDocument); + connect(&subMenuGroup, &QActionGroup::triggered, this, &TreeWidget::onActivateDocument); MenuManager::getInstance()->setupContextMenu(&view, contextMenu); // get the current item @@ -1038,8 +1155,9 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) contextMenu.addAction(this->openFileLocationAction); contextMenu.addAction(this->searchObjectsAction); contextMenu.addAction(this->closeDocAction); - if (doc->testStatus(App::Document::PartialDoc)) + if (doc->testStatus(App::Document::PartialDoc)) { contextMenu.addAction(this->reloadDocAction); + } else { for (auto d : doc->getDependentDocuments()) { if (d->testStatus(App::Document::PartialDoc)) { @@ -1048,25 +1166,29 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) } } contextMenu.addAction(this->selectDependentsAction); - if (doc == App::GetApplication().getActiveDocument() && this->skipRecomputeCommand != nullptr) { + if (doc == App::GetApplication().getActiveDocument() + && this->skipRecomputeCommand != nullptr) { // if active document is selected, use Command this->skipRecomputeCommand->addTo(&contextMenu); - } else { + } + else { // if other document is selected or Command load fails, edit selected Document directly this->skipRecomputeAction->setChecked(doc->testStatus(App::Document::SkipRecompute)); contextMenu.addAction(this->skipRecomputeAction); - } - this->allowPartialRecomputeAction->setChecked(doc->testStatus(App::Document::AllowPartialRecompute)); - if (doc->testStatus(App::Document::SkipRecompute)) + } + this->allowPartialRecomputeAction->setChecked( + doc->testStatus(App::Document::AllowPartialRecompute) + ); + if (doc->testStatus(App::Document::SkipRecompute)) { contextMenu.addAction(this->allowPartialRecomputeAction); + } contextMenu.addAction(this->markRecomputeAction); contextMenu.addAction(this->createGroupAction); } contextMenu.addSeparator(); } else if (this->contextItem && this->contextItem->type() == ObjectType) { - auto objitem = static_cast - (this->contextItem); + auto objitem = static_cast(this->contextItem); // check that the selection is not across several documents bool acrossDocuments = false; @@ -1084,12 +1206,14 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) contextMenu.addAction(this->showHiddenAction); contextMenu.addAction(this->toggleVisibilityInTreeAction); - if (!acrossDocuments) { // is only sensible for selections within one document - if (objitem->object()->getObject()->isDerivedFrom()) + if (!acrossDocuments) { // is only sensible for selections within one document + if (objitem->object()->getObject()->isDerivedFrom()) { contextMenu.addAction(this->createGroupAction); + } // if there are dependent objects in the selection, add context menu to add them to selection - if (CheckForDependents()) + if (CheckForDependents()) { contextMenu.addAction(this->selectDependentsAction); + } } contextMenu.addSeparator(); @@ -1098,8 +1222,9 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) contextMenu.addSeparator(); // relabeling is only possible for a single selected document - if (SelectedObjectsList.size() == 1) + if (SelectedObjectsList.size() == 1) { contextMenu.addAction(this->relabelObjectAction); + } auto selItems = this->selectedItems(); // if only one item is selected, setup the edit menu @@ -1108,12 +1233,14 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) QList editAct = editMenu.actions(); if (!editAct.isEmpty()) { QAction* topact = contextMenu.actions().constFirst(); - for (QList::iterator it = editAct.begin(); it != editAct.end(); ++it) + for (QList::iterator it = editAct.begin(); it != editAct.end(); ++it) { contextMenu.insertAction(topact, *it); + } QAction* first = editAct.front(); contextMenu.setDefaultAction(first); - if (objitem->object()->isEditing()) + if (objitem->object()->isEditing()) { contextMenu.insertAction(topact, this->finishEditingAction); + } contextMenu.insertSeparator(topact); } } @@ -1134,11 +1261,14 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) action->setCheckable(true); action->setStatusTip(tr("Activates document %1").arg(label)); action->setData(QByteArray((*it)->getName())); - if (*it == activeDoc) active = action; + if (*it == activeDoc) { + active = action; + } } - if (active) + if (active) { active->setChecked(true); + } subMenu.addActions(subMenuGroup.actions()); } @@ -1150,10 +1280,15 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) QAction* action = new QAction(tr("Show Description"), this); QAction* internalNameAction = new QAction(tr("Show Internal Name"), this); - action->setStatusTip(tr("Shows a description column for items. An item's description can be set by editing the 'label2' property.")); + action->setStatusTip( + tr("Shows a description column for items. An item's description can be set by editing the " + "'label2' property.") + ); action->setCheckable(true); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/TreeView"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/TreeView" + ); action->setChecked(!hGrp->GetBool("HideColumn", true)); settingsMenu.addAction(action); @@ -1161,7 +1296,7 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) bool show = action->isChecked(); hGrp->SetBool("HideColumn", !show); setColumnHidden(1, !show); - header()->setVisible(action->isChecked()||internalNameAction->isChecked()); + header()->setVisible(action->isChecked() || internalNameAction->isChecked()); }); @@ -1172,12 +1307,17 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) settingsMenu.addAction(internalNameAction); - QObject::connect(internalNameAction, &QAction::triggered, this, [this, action, internalNameAction, hGrp]() { - bool show = internalNameAction->isChecked(); - hGrp->SetBool("HideInternalNames", !show); - setColumnHidden(2, !show); - header()->setVisible(action->isChecked()||internalNameAction->isChecked()); - }); + QObject::connect( + internalNameAction, + &QAction::triggered, + this, + [this, action, internalNameAction, hGrp]() { + bool show = internalNameAction->isChecked(); + hGrp->SetBool("HideInternalNames", !show); + setColumnHidden(2, !show); + header()->setVisible(action->isChecked() || internalNameAction->isChecked()); + } + ); if (!contextMenu.actions().isEmpty()) { try { @@ -1196,11 +1336,13 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) } } -void TreeWidget::hideEvent(QHideEvent* ev) { +void TreeWidget::hideEvent(QHideEvent* ev) +{ QTreeWidget::hideEvent(ev); } -void TreeWidget::showEvent(QShowEvent* ev) { +void TreeWidget::showEvent(QShowEvent* ev) +{ QTreeWidget::showEvent(ev); } @@ -1211,21 +1353,26 @@ void TreeWidget::onCreateGroup() if (this->contextItem->type() == DocumentType) { auto docitem = static_cast(this->contextItem); App::Document* doc = docitem->document()->getDocument(); - QString cmd = QStringLiteral("App.getDocument(\"%1\").addObject" - "(\"App::DocumentObjectGroup\",\"Group\").Label=\"%2\"") - .arg(QString::fromLatin1(doc->getName()), name); + QString cmd = QStringLiteral( + "App.getDocument(\"%1\").addObject" + "(\"App::DocumentObjectGroup\",\"Group\").Label=\"%2\"" + ) + .arg(QString::fromLatin1(doc->getName()), name); Gui::Command::runCommand(Gui::Command::App, cmd.toUtf8()); } else if (this->contextItem->type() == ObjectType) { - auto objitem = static_cast - (this->contextItem); + auto objitem = static_cast(this->contextItem); App::DocumentObject* obj = objitem->object()->getObject(); App::Document* doc = obj->getDocument(); - QString cmd = QStringLiteral("App.getDocument(\"%1\").getObject(\"%2\")" - ".newObject(\"App::DocumentObjectGroup\",\"Group\").Label=\"%3\"") - .arg(QString::fromLatin1(doc->getName()), - QString::fromLatin1(obj->getNameInDocument()), - name); + QString cmd = QStringLiteral( + "App.getDocument(\"%1\").getObject(\"%2\")" + ".newObject(\"App::DocumentObjectGroup\",\"Group\").Label=\"%3\"" + ) + .arg( + QString::fromLatin1(doc->getName()), + QString::fromLatin1(obj->getNameInDocument()), + name + ); Gui::Command::runCommand(Gui::Command::App, cmd.toUtf8()); } } @@ -1233,8 +1380,9 @@ void TreeWidget::onCreateGroup() void TreeWidget::onRelabelObject() { QTreeWidgetItem* item = currentItem(); - if (item) + if (item) { editItem(item); + } } void TreeWidget::onStartEditing() @@ -1242,20 +1390,23 @@ void TreeWidget::onStartEditing() auto action = qobject_cast(sender()); if (action) { if (this->contextItem && this->contextItem->type() == ObjectType) { - auto objitem = static_cast - (this->contextItem); + auto objitem = static_cast(this->contextItem); int edit = action->data().toInt(); App::DocumentObject* obj = objitem->object()->getObject(); - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return; + } auto doc = const_cast(objitem->getOwnerDocument()->document()); MDIView* view = doc->getActiveView(); - if (view) getMainWindow()->setActiveWindow(view); + if (view) { + getMainWindow()->setActiveWindow(view); + } editingItem = objitem; - if (!doc->setEdit(objitem->object(), edit)) + if (!doc->setEdit(objitem->object(), edit)) { editingItem = nullptr; + } } } } @@ -1263,11 +1414,11 @@ void TreeWidget::onStartEditing() void TreeWidget::onFinishEditing() { if (this->contextItem && this->contextItem->type() == ObjectType) { - auto objitem = static_cast - (this->contextItem); + auto objitem = static_cast(this->contextItem); App::DocumentObject* obj = objitem->object()->getObject(); - if (!obj) + if (!obj) { return; + } Gui::Document* doc = Gui::Application::Instance->getDocument(obj->getDocument()); doc->commitCommand(); doc->resetEdit(); @@ -1291,8 +1442,9 @@ bool TreeWidget::CheckForDependents() App::DocumentObject* obj = objitem->object()->getObject(); // get dependents auto subObjectList = obj->getOutList(); - if (!subObjectList.empty()) + if (!subObjectList.empty()) { return true; + } } } } @@ -1326,8 +1478,9 @@ void TreeWidget::onSelectDependents() auto docitem = static_cast(this->contextItem); doc = docitem->document()->getDocument(); std::vector obj = doc->getObjects(); - for (auto it = obj.begin(); it != obj.end(); ++it) + for (auto it = obj.begin(); it != obj.end(); ++it) { Selection().addSelection(doc->getName(), (*it)->getNameInDocument()); + } } // it can be an object else { @@ -1371,8 +1524,9 @@ void TreeWidget::onMarkRecompute() auto docitem = static_cast(this->contextItem); App::Document* doc = docitem->document()->getDocument(); std::vector obj = doc->getObjects(); - for (auto it = obj.begin(); it != obj.end(); ++it) + for (auto it = obj.begin(); it != obj.end(); ++it) { (*it)->enforceRecompute(); + } } // mark all selected objects else { @@ -1387,7 +1541,8 @@ void TreeWidget::onMarkRecompute() } } -void TreeWidget::onRecomputeObject() { +void TreeWidget::onRecomputeObject() +{ std::vector objs; const auto items = selectedItems(); for (auto ti : items) { @@ -1397,39 +1552,48 @@ void TreeWidget::onRecomputeObject() { objs.back()->enforceRecompute(); } } - if (objs.empty()) + if (objs.empty()) { return; + } App::AutoTransaction committer("Recompute object"); objs.front()->getDocument()->recompute(objs, true); } -DocumentItem* TreeWidget::getDocumentItem(const Gui::Document* doc) const { +DocumentItem* TreeWidget::getDocumentItem(const Gui::Document* doc) const +{ auto it = DocumentMap.find(doc); - if (it != DocumentMap.end()) + if (it != DocumentMap.end()) { return it->second; + } return nullptr; } -void TreeWidget::selectAllInstances(const ViewProviderDocumentObject& vpd) { - if (!isSelectionAttached()) +void TreeWidget::selectAllInstances(const ViewProviderDocumentObject& vpd) +{ + if (!isSelectionAttached()) { return; + } - if (selectTimer->isActive()) + if (selectTimer->isActive()) { onSelectTimer(); - else + } + else { _updateStatus(false); + } - for (const auto& v : DocumentMap) + for (const auto& v : DocumentMap) { v.second->selectAllInstances(vpd); + } } -static int &treeIconSize() +static int& treeIconSize() { static int _treeIconSize = -1; - if (_treeIconSize < 0) + if (_treeIconSize < 0) { _treeIconSize = TreeParams::getIconSize(); + } return _treeIconSize; } @@ -1440,23 +1604,27 @@ int TreeWidget::iconHeight() const void TreeWidget::setIconHeight(int height) { - if (treeIconSize() == height) + if (treeIconSize() == height) { return; + } treeIconSize() = height; - if (treeIconSize() <= 0) + if (treeIconSize() <= 0) { treeIconSize() = std::max(10, iconSize()); + } - for(auto tree : Instances) + for (auto tree : Instances) { tree->setIconSize(QSize(treeIconSize(), treeIconSize())); + } } -int TreeWidget::iconSize() { +int TreeWidget::iconSize() +{ static int defaultSize; if (defaultSize == 0) { auto tree = instance(); - if(tree) { -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) + if (tree) { +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) defaultSize = tree->viewOptions().decorationSize.width(); #else QStyleOptionViewItem opt; @@ -1468,39 +1636,49 @@ int TreeWidget::iconSize() { defaultSize = QApplication::style()->pixelMetric(QStyle::PM_SmallIconSize); } } - if (treeIconSize() > 0) + if (treeIconSize() > 0) { return std::max(10, treeIconSize()); + } return defaultSize; } -TreeWidget* TreeWidget::instance() { +TreeWidget* TreeWidget::instance() +{ auto res = _LastSelectedTreeWidget; - if (res && res->isVisible()) + if (res && res->isVisible()) { return res; + } for (auto inst : Instances) { - if (!res) res = inst; - if (inst->isVisible()) + if (!res) { + res = inst; + } + if (inst->isVisible()) { return inst; + } } return res; } -void TreeWidget::setupResizableColumn(TreeWidget *tree) { - auto mode = TreeParams::getResizableColumn()? - QHeaderView::Interactive : QHeaderView::ResizeToContents; - for(auto inst : Instances) { - if(!tree || tree==inst) { +void TreeWidget::setupResizableColumn(TreeWidget* tree) +{ + auto mode = TreeParams::getResizableColumn() ? QHeaderView::Interactive + : QHeaderView::ResizeToContents; + for (auto inst : Instances) { + if (!tree || tree == inst) { inst->header()->setSectionResizeMode(0, mode); inst->header()->setSectionResizeMode(1, mode); inst->header()->setSectionResizeMode(2, mode); if (TreeParams::getResizableColumn()) { QSignalBlocker blocker(inst); - if (TreeParams::getColumnSize1() > 0) + if (TreeParams::getColumnSize1() > 0) { inst->header()->resizeSection(0, TreeParams::getColumnSize1()); - if (TreeParams::getColumnSize2() > 0) + } + if (TreeParams::getColumnSize2() > 0) { inst->header()->resizeSection(1, TreeParams::getColumnSize2()); - if (TreeParams::getColumnSize3() > 0) + } + if (TreeParams::getColumnSize3() > 0) { inst->header()->resizeSection(2, TreeParams::getColumnSize3()); + } } } } @@ -1510,11 +1688,12 @@ TreeWidget* TreeWidget::getTreeForSelection() { TreeWidget* tree = instance(); if (!tree || !tree->isSelectionAttached()) { - for (auto pTree : Instances) + for (auto pTree : Instances) { if (pTree->isSelectionAttached()) { tree = pTree; break; } + } } if (!tree) { return nullptr; @@ -1541,8 +1720,9 @@ std::vector TreeWidget::getSelectedDocuments() const auto items = tree->selectedItems(); for (auto ti : items) { - if (ti->type() != DocumentType) + if (ti->type() != DocumentType) { continue; + } auto item = static_cast(ti); auto doc = item->document(); if (!doc || !doc->getDocument()) { @@ -1565,8 +1745,9 @@ std::vector TreeWidget::getSelection(App::Document* doc) const auto items = tree->selectedItems(); for (auto ti : items) { - if (ti->type() != ObjectType) + if (ti->type() != ObjectType) { continue; + } auto item = static_cast(ti); auto vp = item->object(); auto obj = vp->getObject(); @@ -1592,10 +1773,12 @@ std::vector TreeWidget::getSelection(App::Document* doc) sel.topParent = nullptr; std::ostringstream ss; item->getSubName(ss, sel.topParent); - if (!sel.topParent) + if (!sel.topParent) { sel.topParent = obj; - else + } + else { ss << obj->getNameInDocument() << '.'; + } sel.subname = ss.str(); sel.parentVp = parentVp; sel.vp = vp; @@ -1603,34 +1786,39 @@ std::vector TreeWidget::getSelection(App::Document* doc) return ret; } -void TreeWidget::selectAllLinks(App::DocumentObject* obj) { - if (!isSelectionAttached()) +void TreeWidget::selectAllLinks(App::DocumentObject* obj) +{ + if (!isSelectionAttached()) { return; + } if (!obj || !obj->isAttachedToDocument()) { TREE_ERR("invalid object"); return; } - if (selectTimer->isActive()) + if (selectTimer->isActive()) { onSelectTimer(); - else + } + else { _updateStatus(false); + } - for (auto link : App::GetApplication().getLinksTo(obj, App::GetLinkRecursive)) - { + for (auto link : App::GetApplication().getLinksTo(obj, App::GetLinkRecursive)) { if (!link || !link->isAttachedToDocument()) { TREE_ERR("invalid linked object"); continue; } auto vp = freecad_cast( - Application::Instance->getViewProvider(link)); + Application::Instance->getViewProvider(link) + ); if (!vp) { TREE_ERR("invalid view provider of the linked object"); continue; } - for (auto& v : DocumentMap) + for (auto& v : DocumentMap) { v.second->selectAllInstances(*vp); + } } } @@ -1644,8 +1832,9 @@ void TreeWidget::onActivateDocument(QAction* active) // activate the specified document QByteArray docname = active->data().toByteArray(); Gui::Document* doc = Application::Instance->getDocument((const char*)docname); - if (doc && !doc->setActiveView()) + if (doc && !doc->setActiveView()) { doc->setActiveView(nullptr, View3DInventor::getClassTypeId()); + } } Qt::DropActions TreeWidget::supportedDropActions() const @@ -1658,35 +1847,42 @@ bool TreeWidget::event(QEvent* e) return QTreeWidget::event(e); } -bool TreeWidget::eventFilter(QObject*, QEvent* ev) { +bool TreeWidget::eventFilter(QObject*, QEvent* ev) +{ switch (ev->type()) { - case QEvent::KeyPress: - case QEvent::KeyRelease: { - auto ke = static_cast(ev); - if (ke->key() != Qt::Key_Escape) { - // Qt 5 only recheck key modifier on mouse move, so generate a fake - // event to trigger drag cursor change - auto mouseEvent = new QMouseEvent(QEvent::MouseMove, - mapFromGlobal(QCursor::pos()), QCursor::pos(), Qt::NoButton, - QApplication::mouseButtons(), QApplication::queryKeyboardModifiers()); - QApplication::postEvent(this, mouseEvent); + case QEvent::KeyPress: + case QEvent::KeyRelease: { + auto ke = static_cast(ev); + if (ke->key() != Qt::Key_Escape) { + // Qt 5 only recheck key modifier on mouse move, so generate a fake + // event to trigger drag cursor change + auto mouseEvent = new QMouseEvent( + QEvent::MouseMove, + mapFromGlobal(QCursor::pos()), + QCursor::pos(), + Qt::NoButton, + QApplication::mouseButtons(), + QApplication::queryKeyboardModifiers() + ); + QApplication::postEvent(this, mouseEvent); + } + break; } - break; - } - default: - break; + default: + break; } return false; } -namespace Gui { +namespace Gui +{ bool isTreeViewDragging() { return _DraggingActive; } -} // namespace Gui +} // namespace Gui void TreeWidget::keyPressEvent(QKeyEvent* event) { @@ -1754,7 +1950,7 @@ void TreeWidget::mousePressEvent(QMouseEvent* event) // and we have to compensate for its width. if (isSelectionCheckBoxesEnabled()) { int checkboxWidth = style->pixelMetric(QStyle::PM_IndicatorWidth) - + style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); + + style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); iconRect.adjust(checkboxWidth, 0, 0, 0); } @@ -1780,7 +1976,8 @@ void TreeWidget::mousePressEvent(QMouseEvent* event) } if (parent && visible >= 0) { parent->setElementVisible(objname, !visible); - } else { + } + else { visible = obj->Visibility.getValue(); obj->Visibility.setValue(!visible); } @@ -1798,21 +1995,24 @@ void TreeWidget::mousePressEvent(QMouseEvent* event) void TreeWidget::mouseDoubleClickEvent(QMouseEvent* event) { QTreeWidgetItem* item = itemAt(event->pos()); - if (!item) + if (!item) { return; + } try { if (item->type() == TreeWidget::DocumentType) { Gui::Document* doc = static_cast(item)->document(); - if (!doc) + if (!doc) { return; + } if (doc->getDocument()->testStatus(App::Document::PartialDoc)) { contextItem = item; onReloadDoc(); return; } - if (!doc->setActiveView()) + if (!doc->setActiveView()) { doc->setActiveView(nullptr, View3DInventor::getClassTypeId()); + } } else if (item->type() == TreeWidget::ObjectType) { auto objitem = static_cast(item); @@ -1823,28 +2023,32 @@ void TreeWidget::mouseDoubleClickEvent(QMouseEvent* event) auto lines = manager->getLines(); std::ostringstream ss; - ss << Command::getObjectCmd(vp->getObject()) - << ".ViewObject.doubleClicked()"; + ss << Command::getObjectCmd(vp->getObject()) << ".ViewObject.doubleClicked()"; const char* commandText = vp->getTransactionText(); if (commandText) { auto editDoc = Application::Instance->editDocument(); App::AutoTransaction committer(commandText, true); - if (!vp->doubleClicked()) + if (!vp->doubleClicked()) { QTreeWidget::mouseDoubleClickEvent(event); - else if (lines == manager->getLines()) + } + else if (lines == manager->getLines()) { manager->addLine(MacroManager::Gui, ss.str().c_str()); + } // If the double click starts an editing, let the transaction persist - if (!editDoc && Application::Instance->editDocument()) + if (!editDoc && Application::Instance->editDocument()) { committer.setEnable(false); + } } else { - if (!vp->doubleClicked()) + if (!vp->doubleClicked()) { QTreeWidget::mouseDoubleClickEvent(event); - else if (lines == manager->getLines()) + } + else if (lines == manager->getLines()) { manager->addLine(MacroManager::Gui, ss.str().c_str()); + } } } } @@ -1859,11 +2063,14 @@ void TreeWidget::mouseDoubleClickEvent(QMouseEvent* event) } } -void TreeWidget::startDragging() { - if (state() != NoState) +void TreeWidget::startDragging() +{ + if (state() != NoState) { return; - if (selectedItems().empty()) + } + if (selectedItems().empty()) { return; + } setState(DraggingState); startDrag(model()->supportedDragActions()); @@ -1881,8 +2088,7 @@ void TreeWidget::startDrag(Qt::DropActions supportedActions) } } -bool TreeWidget::dropMimeData(QTreeWidgetItem* parent, int index, - const QMimeData* data, Qt::DropAction action) +bool TreeWidget::dropMimeData(QTreeWidgetItem* parent, int index, const QMimeData* data, Qt::DropAction action) { return QTreeWidget::dropMimeData(parent, index, data, action); } @@ -1898,7 +2104,8 @@ void TreeWidget::dragLeaveEvent(QDragLeaveEvent* event) } -struct ItemInfo { +struct ItemInfo +{ std::string doc; std::string obj; std::string parentDoc; @@ -1913,7 +2120,8 @@ struct ItemInfo { bool dragging = false; }; -struct ItemInfo2 { +struct ItemInfo2 +{ std::string doc; std::string obj; std::string parentDoc; @@ -1923,93 +2131,106 @@ struct ItemInfo2 { std::string topSubname; }; -namespace { - class DropHandler +namespace +{ +class DropHandler +{ +public: + static std::vector>> filterItems( + const QList& sels, + QTreeWidgetItem* targetItem + ) { - public: - static std::vector > > filterItems(const QList& sels, QTreeWidgetItem* targetItem) - { - std::vector > > items; - items.reserve(sels.size()); - for (auto ti : sels) { - if (ti->type() != TreeWidget::ObjectType) - continue; - // ignore child elements if the parent is selected - if (sels.contains(ti->parent())) - continue; - if (ti == targetItem) - continue; - auto item = static_cast(ti); - items.emplace_back(); - auto& info = items.back(); - info.first = item; - const auto& subnames = item->getSubNames(); - info.second.insert(info.second.end(), subnames.begin(), subnames.end()); + std::vector>> items; + items.reserve(sels.size()); + for (auto ti : sels) { + if (ti->type() != TreeWidget::ObjectType) { + continue; } - - return items; + // ignore child elements if the parent is selected + if (sels.contains(ti->parent())) { + continue; + } + if (ti == targetItem) { + continue; + } + auto item = static_cast(ti); + items.emplace_back(); + auto& info = items.back(); + info.first = item; + const auto& subnames = item->getSubNames(); + info.second.insert(info.second.end(), subnames.begin(), subnames.end()); } - static App::PropertyPlacement* getPlacement(const ItemInfo& info, const App::DocumentObject* obj, Base::Matrix4D& mat) - { - App::PropertyPlacement* propPlacement = nullptr; - if (!info.topObj.empty()) { - auto doc = App::GetApplication().getDocument(info.topDoc.c_str()); - if (doc) { - auto topObj = doc->getObject(info.topObj.c_str()); - if (topObj) { - auto sobj = topObj->getSubObject(info.topSubname.c_str(), nullptr, &mat); - if (sobj == obj) { - propPlacement = freecad_cast( - obj->getPropertyByName("Placement")); - } + + return items; + } + static App::PropertyPlacement* getPlacement( + const ItemInfo& info, + const App::DocumentObject* obj, + Base::Matrix4D& mat + ) + { + App::PropertyPlacement* propPlacement = nullptr; + if (!info.topObj.empty()) { + auto doc = App::GetApplication().getDocument(info.topDoc.c_str()); + if (doc) { + auto topObj = doc->getObject(info.topObj.c_str()); + if (topObj) { + auto sobj = topObj->getSubObject(info.topSubname.c_str(), nullptr, &mat); + if (sobj == obj) { + propPlacement = freecad_cast( + obj->getPropertyByName("Placement") + ); } } } - else { - propPlacement = freecad_cast( - obj->getPropertyByName("Placement")); - if (propPlacement) - mat = propPlacement->getValue().toMatrix(); - } - - return propPlacement; - } - }; - - QPoint getPos(QEvent* event) { - if (auto* dragMoveEvent = dynamic_cast(event)) { -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) - return dragMoveEvent->pos(); -#else - return dragMoveEvent->position().toPoint(); -#endif - } - - else if (auto* dropEvent = dynamic_cast(event)) { -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) - return dropEvent->pos(); -#else - return dropEvent->position().toPoint(); -#endif - } - - // For unsupported event types or if casting fails - return QPoint(-1, -1); - } - - Qt::DropAction getDropAction(int size, const int type) - { - if (QApplication::keyboardModifiers() == Qt::ControlModifier) { - return Qt::CopyAction; - } - else if (QApplication::keyboardModifiers() == Qt::AltModifier - && (size == 1 || type == TreeWidget::DocumentType)) { - return Qt::LinkAction; } else { - return Qt::MoveAction; + propPlacement = freecad_cast(obj->getPropertyByName("Placement")); + if (propPlacement) { + mat = propPlacement->getValue().toMatrix(); + } } + + return propPlacement; } +}; + +QPoint getPos(QEvent* event) +{ + if (auto* dragMoveEvent = dynamic_cast(event)) { +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + return dragMoveEvent->pos(); +#else + return dragMoveEvent->position().toPoint(); +#endif + } + + else if (auto* dropEvent = dynamic_cast(event)) { +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) + return dropEvent->pos(); +#else + return dropEvent->position().toPoint(); +#endif + } + + // For unsupported event types or if casting fails + return QPoint(-1, -1); +} + +Qt::DropAction getDropAction(int size, const int type) +{ + if (QApplication::keyboardModifiers() == Qt::ControlModifier) { + return Qt::CopyAction; + } + else if (QApplication::keyboardModifiers() == Qt::AltModifier + && (size == 1 || type == TreeWidget::DocumentType)) { + return Qt::LinkAction; + } + else { + return Qt::MoveAction; + } +} } void TreeWidget::dragMoveEvent(QDragMoveEvent* event) @@ -2025,10 +2246,10 @@ void TreeWidget::dragMoveEvent(QDragMoveEvent* event) QTreeWidget::dragMoveEvent(event); if (!event->isAccepted()) { - //return; - // QTreeWidget::dragMoveEvent is rejecting the event when in between items - // at DocumentItem root level. Which is preventing reordering. To work around - // we accept for now, then reject below if targetItem not found. + // return; + // QTreeWidget::dragMoveEvent is rejecting the event when in between items + // at DocumentItem root level. Which is preventing reordering. To work around + // we accept for now, then reject below if targetItem not found. event->accept(); } @@ -2091,8 +2312,11 @@ void TreeWidget::dragMoveEvent(QDragMoveEvent* event) if (da == Qt::MoveAction) { // Check if item can be dragged from his parent auto parentItem = item->getParentItem(); - if (parentItem && !(parentItem->object()->canDragObjects() && parentItem->object()->canDragObject(obj))) - { + if (parentItem + && !( + parentItem->object()->canDragObjects() + && parentItem->object()->canDragObject(obj) + )) { TREE_TRACE("Cannot drag object"); event->ignore(); return; @@ -2104,8 +2328,13 @@ void TreeWidget::dragMoveEvent(QDragMoveEvent* event) auto subname = str.str(); // let the view provider decide to accept the object or ignore it - if (da != Qt::LinkAction && !vp->canDropObjectEx(obj, owner, subname.c_str(), item->mySubs)) { - TREE_TRACE("cannot drop " << obj->getFullName() << ' ' << (owner ? owner->getFullName() : "") << '.' << subname); + if (da != Qt::LinkAction + && !vp->canDropObjectEx(obj, owner, subname.c_str(), item->mySubs)) { + TREE_TRACE( + "cannot drop " << obj->getFullName() << ' ' + << (owner ? owner->getFullName() : "") << '.' + << subname + ); event->ignore(); return; } @@ -2136,7 +2365,7 @@ TreeWidget::TargetItemInfo TreeWidget::getTargetInfo(QEvent* ev) QPoint pos = getPos(ev); if (pos == QPoint(-1, -1)) { - return {}; // Return an empty struct + return {}; // Return an empty struct } targetInfo.targetItem = itemAt(pos); @@ -2162,16 +2391,20 @@ TreeWidget::TargetItemInfo TreeWidget::getTargetInfo(QEvent* ev) QRect itemRect = visualItemRect(targetInfo.targetItem); int mouseY = pos.y(); int itemMidPoint = itemRect.top() + itemRect.height() / 2; - int threshold = itemRect.height() * 0.20; // 20% of the item's height as threshold + int threshold = itemRect.height() * 0.20; // 20% of the item's height as threshold targetInfo.inBottomHalf = mouseY > itemMidPoint; - targetInfo.inThresholdZone = ((mouseY < itemRect.top() + threshold) && !targetInfo.targetItem->isExpanded()) + targetInfo.inThresholdZone = ((mouseY < itemRect.top() + threshold) + && !targetInfo.targetItem->isExpanded()) || (mouseY > itemRect.top() + itemRect.height() - threshold); return targetInfo; } -bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, - std::vector items) +bool TreeWidget::dropInDocument( + QDropEvent* event, + TargetItemInfo& targetInfo, + std::vector items +) { std::string errMsg; auto da = event->dropAction(); @@ -2182,8 +2415,10 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, bool syncPlacement = TreeParams::getSyncPlacement(); App::AutoTransaction committer( - da == Qt::LinkAction ? "Link object" : - da == Qt::CopyAction ? "Copy object" : "Move object"); + da == Qt::LinkAction ? "Link object" + : da == Qt::CopyAction ? "Copy object" + : "Move object" + ); // check if items can be dragged for (auto& v : items) { @@ -2193,9 +2428,13 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, if (parentItem) { bool allParentsOK = canDragFromParents(parentItem, obj, nullptr); - if (!allParentsOK || !parentItem->object()->canDragObjects() || !parentItem->object()->canDragObject(obj)) { + if (!allParentsOK || !parentItem->object()->canDragObjects() + || !parentItem->object()->canDragObject(obj)) { committer.close(true); - TREE_ERR("'" << obj->getFullName() << "' cannot be dragged out of '" << parentItem->object()->getObject()->getFullName() << "'"); + TREE_ERR( + "'" << obj->getFullName() << "' cannot be dragged out of '" + << parentItem->object()->getObject()->getFullName() << "'" + ); return false; } } @@ -2237,9 +2476,13 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, std::vector droppedObjs; for (auto& info : infos) { auto doc = App::GetApplication().getDocument(info.doc.c_str()); - if (!doc) continue; + if (!doc) { + continue; + } auto obj = doc->getObject(info.obj.c_str()); - auto vpc = freecad_cast(Application::Instance->getViewProvider(obj)); + auto vpc = freecad_cast( + Application::Instance->getViewProvider(obj) + ); if (!vpc) { FC_WARN("Cannot find dragging object " << info.obj); continue; @@ -2255,13 +2498,17 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, if (topObj) { auto sobj = topObj->getSubObject(info.topSubname.c_str(), nullptr, &mat); if (sobj == obj) { - propPlacement = dynamic_cast(obj->getPropertyByName("Placement")); + propPlacement = dynamic_cast( + obj->getPropertyByName("Placement") + ); } } } } else { - propPlacement = dynamic_cast(obj->getPropertyByName("Placement")); + propPlacement = dynamic_cast( + obj->getPropertyByName("Placement") + ); if (propPlacement) { mat = propPlacement->getValue().toMatrix(); } @@ -2270,15 +2517,22 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, if (da == Qt::LinkAction) { std::string name = targetInfo.targetDoc->getUniqueObjectName("Link"); - FCMD_DOC_CMD(targetInfo.targetDoc, "addObject('App::Link','" << name << "').setLink(" - << Command::getObjectCmd(obj) << ")"); + FCMD_DOC_CMD( + targetInfo.targetDoc, + "addObject('App::Link','" << name << "').setLink(" << Command::getObjectCmd(obj) + << ")" + ); auto link = targetInfo.targetDoc->getObject(name.c_str()); - if (!link) + if (!link) { continue; + } FCMD_OBJ_CMD(link, "Label='" << obj->getLinkedObject(true)->Label.getValue() << "'"); - propPlacement = dynamic_cast(link->getPropertyByName("Placement")); - if (propPlacement) + propPlacement = dynamic_cast( + link->getPropertyByName("Placement") + ); + if (propPlacement) { propPlacement->setValueIfChanged(Base::Placement(mat)); + } droppedObjs.push_back(link); } else if (!info.parent.empty()) { @@ -2288,23 +2542,26 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, continue; } auto parent = parentDoc->getObject(info.parent.c_str()); - auto vpp = freecad_cast(Application::Instance->getViewProvider(parent)); + auto vpp = freecad_cast( + Application::Instance->getViewProvider(parent) + ); if (!vpp) { FC_WARN("Cannot find dragging object's parent " << info.parent); continue; } std::ostringstream ss; - ss << Command::getObjectCmd(vpp->getObject()) << ".ViewObject.dragObject(" << Command::getObjectCmd(obj) << ')'; + ss << Command::getObjectCmd(vpp->getObject()) << ".ViewObject.dragObject(" + << Command::getObjectCmd(obj) << ')'; auto lines = manager->getLines(); vpp->dragObject(obj); if (manager->getLines() == lines) { manager->addLine(MacroManager::Gui, ss.str().c_str()); } - //make sure it is not part of a geofeaturegroup anymore. - //When this has happen we need to handle all removed - //objects + // make sure it is not part of a geofeaturegroup anymore. + // When this has happen we need to handle all removed + // objects auto grp = App::GeoFeatureGroupExtension::getGroupOfObject(obj); if (grp) { FCMD_OBJ_CMD(grp, "removeObject(" << Command::getObjectCmd(obj) << ")"); @@ -2323,11 +2580,11 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, else { std::ostringstream ss; ss << "App.getDocument('" << targetInfo.targetDoc->getName() << "')." - << (da == Qt::CopyAction ? "copyObject(" : "moveObject(") - << Command::getObjectCmd(obj) << ", True)"; + << (da == Qt::CopyAction ? "copyObject(" : "moveObject(") + << Command::getObjectCmd(obj) << ", True)"; App::DocumentObject* res = nullptr; if (da == Qt::CopyAction) { - auto copied = targetInfo.targetDoc->copyObject({ obj }, true); + auto copied = targetInfo.targetDoc->copyObject({obj}, true); if (!copied.empty()) { res = copied.back(); } @@ -2342,7 +2599,9 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, res = targetInfo.targetDoc->moveObject(obj, true); } if (res) { - propPlacement = dynamic_cast( res->getPropertyByName("Placement")); + propPlacement = dynamic_cast( + res->getPropertyByName("Placement") + ); if (propPlacement) { propPlacement->setValueIfChanged(Base::Placement(mat)); } @@ -2374,14 +2633,21 @@ bool TreeWidget::dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, } if (!errMsg.empty()) { committer.close(true); - QMessageBox::critical(getMainWindow(), QObject::tr("Drag & drop failed"), QString::fromUtf8(errMsg.c_str())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Drag & drop failed"), + QString::fromUtf8(errMsg.c_str()) + ); return false; } return touched; } -bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, - std::vector items) +bool TreeWidget::dropInObject( + QDropEvent* event, + TargetItemInfo& targetInfo, + std::vector items +) { std::string errMsg; auto da = event->dropAction(); @@ -2415,7 +2681,7 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, if (da != Qt::LinkAction && !vp->canDropObjects()) { if (!(event->possibleActions() & Qt::LinkAction) || items.size() != 1) { TREE_TRACE("Cannot drop objects"); - return false; // no group like object + return false; // no group like object } } @@ -2427,11 +2693,18 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, Selection().clearCompleteSelection(); if (targetParent) { targetSubname << vp->getObject()->getNameInDocument() << '.'; - Selection().addSelection(targetParent->getDocument()->getName(), targetParent->getNameInDocument(), targetSubname.str().c_str()); + Selection().addSelection( + targetParent->getDocument()->getName(), + targetParent->getNameInDocument(), + targetSubname.str().c_str() + ); } else { targetParent = targetObj; - Selection().addSelection(targetParent->getDocument()->getName(), targetParent->getNameInDocument()); + Selection().addSelection( + targetParent->getDocument()->getName(), + targetParent->getNameInDocument() + ); } // Open command @@ -2440,7 +2713,7 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, bool syncPlacement = TreeParams::getSyncPlacement() && targetItemObj->isGroup(); bool setSelection = true; std::vector draggedObjects; - std::vector > droppedObjects; + std::vector> droppedObjects; std::vector infos; // Only keep text names here, because you never know when doing drag // and drop some object may delete other objects. @@ -2469,7 +2742,8 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, info.subs.swap(v.second); // check if items can be dragged - if (da == Qt::MoveAction && item->myOwner == targetItemObj->myOwner && vp->canDragAndDropObject(obj)) { + if (da == Qt::MoveAction && item->myOwner == targetItemObj->myOwner + && vp->canDragAndDropObject(obj)) { auto parentItem = item->getParentItem(); if (!parentItem) { info.dragging = true; @@ -2492,8 +2766,7 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, } if (da != Qt::LinkAction - && !vp->canDropObjectEx(obj, owner, info.subname.c_str(), item->mySubs)) - { + && !vp->canDropObjectEx(obj, owner, info.subname.c_str(), item->mySubs)) { if (event->possibleActions() & Qt::LinkAction) { if (items.size() > 1) { committer.close(true); @@ -2525,7 +2798,9 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, for (auto& info : infos) { auto& subname = info.subname; targetObj = targetDoc->getObject(target.c_str()); - vp = freecad_cast( Application::Instance->getViewProvider(targetObj)); + vp = freecad_cast( + Application::Instance->getViewProvider(targetObj) + ); if (!vp) { FC_ERR("Cannot find drop target object " << target); break; @@ -2537,7 +2812,9 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, continue; } auto obj = doc->getObject(info.obj.c_str()); - auto vpc = freecad_cast(Application::Instance->getViewProvider(obj)); + auto vpc = freecad_cast( + Application::Instance->getViewProvider(obj) + ); if (!vpc) { FC_WARN("Cannot find dragging object " << info.obj); continue; @@ -2548,7 +2825,9 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, auto parentDoc = App::GetApplication().getDocument(info.parentDoc.c_str()); if (parentDoc) { auto parent = parentDoc->getObject(info.parent.c_str()); - vpp = freecad_cast(Application::Instance->getViewProvider(parent)); + vpp = freecad_cast( + Application::Instance->getViewProvider(parent) + ); } if (!vpp) { FC_WARN("Cannot find dragging object's parent " << info.parent); @@ -2559,8 +2838,9 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, App::DocumentObject* owner = nullptr; if (!info.ownerDoc.empty()) { auto ownerDoc = App::GetApplication().getDocument(info.ownerDoc.c_str()); - if (ownerDoc) + if (ownerDoc) { owner = ownerDoc->getObject(info.owner.c_str()); + } if (!owner) { FC_WARN("Cannot find dragging object's top parent " << info.owner); continue; @@ -2579,11 +2859,12 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, std::ostringstream ss; if (vpp) { auto lines = manager->getLines(); - ss << Command::getObjectCmd(vpp->getObject()) - << ".ViewObject.dragObject(" << Command::getObjectCmd(obj) << ')'; + ss << Command::getObjectCmd(vpp->getObject()) << ".ViewObject.dragObject(" + << Command::getObjectCmd(obj) << ')'; vpp->dragObject(obj); - if (manager->getLines() == lines) + if (manager->getLines() == lines) { manager->addLine(MacroManager::Gui, ss.str().c_str()); + } owner = nullptr; subname.clear(); ss.str(""); @@ -2600,7 +2881,7 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, // throw exception if failed ss.str(""); ss << Command::getObjectCmd(obj) << ".adjustRelativeLinks(" - << Command::getObjectCmd(targetObj) << ")"; + << Command::getObjectCmd(targetObj) << ")"; manager->addLine(MacroManager::Gui, ss.str().c_str()); std::set visited; @@ -2625,18 +2906,23 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, auto parentItem = targetItemObj->getParentItem(); if (parentItem) { ss << Command::getObjectCmd( - parentItem->object()->getObject(), nullptr, ".replaceObject(", true) - << Command::getObjectCmd(targetObj) << "," - << Command::getObjectCmd(obj) << ")"; + parentItem->object()->getObject(), + nullptr, + ".replaceObject(", + true + ) << Command::getObjectCmd(targetObj) + << "," << Command::getObjectCmd(obj) << ")"; std::ostringstream ss; dropParent = nullptr; parentItem->getSubName(ss, dropParent); - if (dropParent) + if (dropParent) { ss << parentItem->object()->getObject()->getNameInDocument() << '.'; - else + } + else { dropParent = parentItem->object()->getObject(); + } ss << obj->getNameInDocument() << '.'; dropName = ss.str(); } @@ -2646,26 +2932,28 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, } Gui::Command::runCommand(Gui::Command::App, ss.str().c_str()); - } else { - ss << Command::getObjectCmd(vp->getObject()) - << ".ViewObject.dropObject(" << Command::getObjectCmd(obj); + ss << Command::getObjectCmd(vp->getObject()) << ".ViewObject.dropObject(" + << Command::getObjectCmd(obj); if (owner) { - ss << "," << Command::getObjectCmd(owner) - << ",'" << subname << "',["; + ss << "," << Command::getObjectCmd(owner) << ",'" << subname << "',["; } - else + else { ss << ",None,'',["; - for (auto& sub : info.subs) + } + for (auto& sub : info.subs) { ss << "'" << sub << "',"; + } ss << "])"; auto lines = manager->getLines(); dropName = vp->dropObjectEx(obj, owner, subname.c_str(), info.subs); - if (manager->getLines() == lines) + if (manager->getLines() == lines) { manager->addLine(MacroManager::Gui, ss.str().c_str()); - if (!dropName.empty()) + } + if (!dropName.empty()) { dropName = targetSubname.str() + dropName; + } } touched = true; @@ -2681,20 +2969,22 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, Base::Matrix4D newMat; auto sobj = dropParent->getSubObject(dropName.c_str(), nullptr, &newMat); if (!sobj) { - FC_LOG("failed to find dropped object " - << dropParent->getFullName() << '.' << dropName); + FC_LOG( + "failed to find dropped object " << dropParent->getFullName() << '.' << dropName + ); setSelection = false; continue; } if (da != Qt::CopyAction && propPlacement) { // try to adjust placement - if ((info.dragging && sobj == obj) || - (!info.dragging && sobj->getLinkedObject(false) == obj)) - { - if (!info.dragging) + if ((info.dragging && sobj == obj) + || (!info.dragging && sobj->getLinkedObject(false) == obj)) { + if (!info.dragging) { propPlacement = freecad_cast( - sobj->getPropertyByName("Placement")); + sobj->getPropertyByName("Placement") + ); + } if (propPlacement) { newMat *= propPlacement->getValue().inverse().toMatrix(); newMat.inverseGauss(); @@ -2711,8 +3001,11 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, Selection().selStackPush(); Selection().clearCompleteSelection(); for (auto& v : droppedObjects) { - Selection().addSelection(v.first->getDocument()->getName(), - v.first->getNameInDocument(), v.second.c_str()); + Selection().addSelection( + v.first->getDocument()->getName(), + v.first->getNameInDocument(), + v.second.c_str() + ); } Selection().selStackPush(); } @@ -2736,14 +3029,21 @@ bool TreeWidget::dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, } if (!errMsg.empty()) { committer.close(true); - QMessageBox::critical(getMainWindow(), QObject::tr("Drag & drop failed"), - QString::fromUtf8(errMsg.c_str())); + QMessageBox::critical( + getMainWindow(), + QObject::tr("Drag & drop failed"), + QString::fromUtf8(errMsg.c_str()) + ); return false; } return touched; } -bool TreeWidget::canDragFromParents(DocumentObjectItem* parentItem, App::DocumentObject* obj, App::DocumentObject* target) +bool TreeWidget::canDragFromParents( + DocumentObjectItem* parentItem, + App::DocumentObject* obj, + App::DocumentObject* target +) { // We query all the parents recursively. (for cases like assembly/group/part) bool allParentsOK = true; @@ -2760,7 +3060,7 @@ bool TreeWidget::canDragFromParents(DocumentObjectItem* parentItem, App::Documen void TreeWidget::dropEvent(QDropEvent* event) { - //FIXME: This should actually be done inside dropMimeData + // FIXME: This should actually be done inside dropMimeData TargetItemInfo targetInfo = getTargetInfo(event); if (!targetInfo.targetItem) { @@ -2771,7 +3071,7 @@ void TreeWidget::dropEvent(QDropEvent* event) std::vector items; items = DropHandler::filterItems(selectedItems(), targetInfo.targetItem); if (items.empty()) { - return; // nothing needs to be done + return; // nothing needs to be done } event->setDropAction(getDropAction(items.size(), targetInfo.targetItem->type())); @@ -2789,12 +3089,16 @@ void TreeWidget::dropEvent(QDropEvent* event) } if (touched && TreeParams::getSyncView()) { auto gdoc = Application::Instance->getDocument(targetInfo.targetDoc); - if (gdoc) + if (gdoc) { gdoc->setActiveView(); + } } } -void TreeWidget::sortDroppedObjects(TargetItemInfo& targetInfo, std::vector draggedObjects) +void TreeWidget::sortDroppedObjects( + TargetItemInfo& targetInfo, + std::vector draggedObjects +) { if (targetInfo.targetItem == targetInfo.underMouseItem) { return; @@ -2804,7 +3108,9 @@ void TreeWidget::sortDroppedObjects(TargetItemInfo& targetInfo, std::vector sortedObjList; std::vector objList; - auto sortIntoList = [&sortedObjList, &draggedObjects, underMouseObj, &targetInfo](const std::vector& objects) { + auto sortIntoList = [&sortedObjList, &draggedObjects, underMouseObj, &targetInfo]( + const std::vector& objects + ) { for (auto* obj : objects) { if (obj == underMouseObj) { if (targetInfo.inBottomHalf) { @@ -2828,7 +3134,8 @@ void TreeWidget::sortDroppedObjects(TargetItemInfo& targetInfo, std::vectortype() == TreeWidget::ObjectType) { - // To update the order of items of groups such as App::Part, we just need to change the order in the Group property + // To update the order of items of groups such as App::Part, we just need to change the + // order in the Group property auto targetItemObj = static_cast(targetInfo.targetItem); App::DocumentObject* targetObj = targetItemObj->object()->getObject(); @@ -2838,21 +3145,26 @@ void TreeWidget::sortDroppedObjects(TargetItemInfo& targetInfo, std::vectorgetValue(); - sortIntoList(objList); // Move dropped objects to correct position + sortIntoList(objList); // Move dropped objects to correct position propGroup->setValue(sortedObjList); } else if (targetInfo.targetItem->type() == TreeWidget::DocumentType) { - Gui::Document* guiDoc = Gui::Application::Instance->getDocument(targetInfo.targetDoc->getName()); + Gui::Document* guiDoc = Gui::Application::Instance->getDocument( + targetInfo.targetDoc->getName() + ); objList = guiDoc->getTreeRootObjects(); // First we need to sort objList by treeRank. - std::sort(objList.begin(), objList.end(), - [](App::DocumentObject* a, App::DocumentObject* b) { - auto vpA = dynamic_cast(Gui::Application::Instance->getViewProvider(a)); - auto vpB = dynamic_cast(Gui::Application::Instance->getViewProvider(b)); + std::sort(objList.begin(), objList.end(), [](App::DocumentObject* a, App::DocumentObject* b) { + auto vpA = dynamic_cast( + Gui::Application::Instance->getViewProvider(a) + ); + auto vpB = dynamic_cast( + Gui::Application::Instance->getViewProvider(b) + ); if (vpA && vpB) { return vpA->getTreeRank() < vpB->getTreeRank(); } - return false; // Keep the original order if either vpA or vpB is nullptr + return false; // Keep the original order if either vpA or vpB is nullptr }); // Then we move dropped objects to their correct position @@ -2860,7 +3172,9 @@ void TreeWidget::sortDroppedObjects(TargetItemInfo& targetInfo, std::vector(Application::Instance->getViewProvider(sortedObjList[i])); + auto vp = freecad_cast( + Application::Instance->getViewProvider(sortedObjList[i]) + ); vp->setTreeRank(i); } @@ -2869,27 +3183,35 @@ void TreeWidget::sortDroppedObjects(TargetItemInfo& targetInfo, std::vectortestStatus(App::Document::TempDoc)) + if (Doc.getDocument()->testStatus(App::Document::TempDoc)) { return; + } auto item = new DocumentItem(&Doc, this->rootItem); - if (isMainDoc) + if (isMainDoc) { this->expandItem(item); + } item->setIcon(0, *documentPixmap); item->setText(0, QString::fromUtf8(Doc.getDocument()->Label.getValue())); DocumentMap[&Doc] = item; } -void TreeWidget::onReloadDoc() { - if (!this->contextItem || this->contextItem->type() != DocumentType) +void TreeWidget::onReloadDoc() +{ + if (!this->contextItem || this->contextItem->type() != DocumentType) { return; + } auto docitem = static_cast(this->contextItem); App::Document* doc = docitem->document()->getDocument(); std::string name = doc->FileName.getValue(); @@ -2905,14 +3227,16 @@ void TreeWidget::onReloadDoc() { void TreeWidget::onCloseDoc() { - if (!this->contextItem || this->contextItem->type() != DocumentType) + if (!this->contextItem || this->contextItem->type() != DocumentType) { return; + } try { auto docitem = static_cast(this->contextItem); Gui::Document* gui = docitem->document(); App::Document* doc = gui->getDocument(); - if (gui->canClose(true, true)) + if (gui->canClose(true, true)) { Command::doCommand(Command::Doc, "App.closeDocument(\"%s\")", doc->getName()); + } } catch (const Base::Exception& e) { e.reportException(); @@ -2966,9 +3290,7 @@ void TreeWidget::slotRenameDocument(const Gui::Document& Doc) void TreeWidget::slotChangedViewObject(const Gui::ViewProvider& vp, const App::Property& prop) { - if (!App::GetApplication().isRestoring() - && vp.isDerivedFrom()) - { + if (!App::GetApplication().isRestoring() && vp.isDerivedFrom()) { const auto& vpd = static_cast(vp); if (&prop == &vpd.ShowInTree) { ChangedObjects.emplace(vpd.getObject(), 0); @@ -2977,7 +3299,8 @@ void TreeWidget::slotChangedViewObject(const Gui::ViewProvider& vp, const App::P } } -void TreeWidget::slotTouchedObject(const App::DocumentObject& obj) { +void TreeWidget::slotTouchedObject(const App::DocumentObject& obj) +{ ChangedObjects.emplace(const_cast(&obj), 0); _updateStatus(); } @@ -2985,8 +3308,9 @@ void TreeWidget::slotTouchedObject(const App::DocumentObject& obj) { void TreeWidget::slotShowHidden(const Gui::Document& Doc) { auto it = DocumentMap.find(&Doc); - if (it != DocumentMap.end()) + if (it != DocumentMap.end()) { it->second->updateItemsVisibility(it->second, it->second->showHidden()); + } } void TreeWidget::slotRelabelDocument(const Gui::Document& Doc) @@ -3000,12 +3324,11 @@ void TreeWidget::slotRelabelDocument(const Gui::Document& Doc) void TreeWidget::slotActiveDocument(const Gui::Document& Doc) { auto jt = DocumentMap.find(&Doc); - if (jt == DocumentMap.end()) - return; // signal is emitted before the item gets created + if (jt == DocumentMap.end()) { + return; // signal is emitted before the item gets created + } int displayMode = TreeParams::getDocumentMode(); - for (auto it = DocumentMap.begin(); - it != DocumentMap.end(); ++it) - { + for (auto it = DocumentMap.begin(); it != DocumentMap.end(); ++it) { QFont f = it->second->font(0); f.setBold(it == jt); it->second->setHidden(0 == displayMode && it != jt); @@ -3017,19 +3340,22 @@ void TreeWidget::slotActiveDocument(const Gui::Document& Doc) } } -struct UpdateDisabler { +struct UpdateDisabler +{ QWidget& widget; int& blocked; - bool visible{false}; - bool focus{false}; + bool visible {false}; + bool focus {false}; // Note! DO NOT block signal here, or else // QTreeWidgetItem::setChildIndicatorPolicy() does not work UpdateDisabler(QWidget& w, int& blocked) - : widget(w), blocked(blocked) + : widget(w) + , blocked(blocked) { - if (++blocked > 1) + if (++blocked > 1) { return; + } focus = widget.hasFocus(); visible = widget.isVisible(); if (visible) { @@ -3042,14 +3368,17 @@ struct UpdateDisabler { widget.setVisible(false); } } - ~UpdateDisabler() { - if (blocked <= 0 || --blocked != 0) + ~UpdateDisabler() + { + if (blocked <= 0 || --blocked != 0) { return; + } if (visible) { widget.setVisible(true); - if (focus) + if (focus) { widget.setFocus(); + } } } }; @@ -3086,25 +3415,32 @@ void TreeWidget::onUpdateStatus() // Checking for new objects for (auto& v : localNewObjects) { auto doc = App::GetApplication().getDocument(v.first.c_str()); - if (!doc) + if (!doc) { continue; + } auto gdoc = Application::Instance->getDocument(doc); - if (!gdoc) + if (!gdoc) { continue; + } auto docItem = getDocumentItem(gdoc); - if (!docItem) + if (!docItem) { continue; + } for (auto id : v.second) { auto obj = doc->getObjectByID(id); - if (!obj) + if (!obj) { continue; - if (obj->isError()) + } + if (obj->isError()) { errors.push_back(obj); - if (docItem->ObjectMap.contains(obj)) + } + if (docItem->ObjectMap.contains(obj)) { continue; + } auto vpd = freecad_cast(gdoc->getViewProvider(obj)); - if (vpd) + if (vpd) { docItem->createNewItem(*vpd); + } } } @@ -3117,11 +3453,13 @@ void TreeWidget::onUpdateStatus() auto obj = v.first; auto iter = ObjectTable.find(obj); - if (iter == ObjectTable.end()) + if (iter == ObjectTable.end()) { continue; + } - if (v.second.test(CS_Error) && obj->isError()) + if (v.second.test(CS_Error) && obj->isError()) { errors.push_back(obj); + } if (!iter->second.empty()) { auto data = *iter->second.begin(); @@ -3129,10 +3467,12 @@ void TreeWidget::onUpdateStatus() if (data->itemHidden != itemHidden) { for (auto& data : iter->second) { data->itemHidden = itemHidden; - if (data->docItem->showHidden()) + if (data->docItem->showHidden()) { continue; - for (auto item : data->items) + } + for (auto item : data->items) { item->setHidden(itemHidden); + } } } } @@ -3151,37 +3491,45 @@ void TreeWidget::onUpdateStatus() for (auto& v : DocumentMap) { auto docItem = v.second; - for (auto obj : docItem->PopulateObjects) + for (auto obj : docItem->PopulateObjects) { docItem->populateObject(obj); + } docItem->PopulateObjects.clear(); auto doc = v.first->getDocument(); if (!docItem->connectChgObject.connected()) { - //NOLINTBEGIN + // NOLINTBEGIN docItem->connectChgObject = docItem->document()->signalChangedObject.connect( - std::bind(&TreeWidget::slotChangeObject, this, sp::_1, sp::_2)); + std::bind(&TreeWidget::slotChangeObject, this, sp::_1, sp::_2) + ); docItem->connectTouchedObject = doc->signalTouchedObject.connect( - std::bind(&TreeWidget::slotTouchedObject, this, sp::_1)); - //NOLINTEND + std::bind(&TreeWidget::slotTouchedObject, this, sp::_1) + ); + // NOLINTEND } - if (doc->testStatus(App::Document::PartialDoc)) + if (doc->testStatus(App::Document::PartialDoc)) { docItem->setIcon(0, *documentPartialPixmap); + } else if (docItem->_ExpandInfo) { for (auto& entry : *docItem->_ExpandInfo) { const char* name = entry.first.c_str(); bool legacy = name[0] == '*'; - if (legacy) + if (legacy) { ++name; + } auto obj = doc->getObject(name); - if (!obj) + if (!obj) { continue; + } auto iter = docItem->ObjectMap.find(obj); - if (iter == docItem->ObjectMap.end()) + if (iter == docItem->ObjectMap.end()) { continue; - if (iter->second->rootItem) + } + if (iter->second->rootItem) { docItem->restoreItemExpansion(entry.second, iter->second->rootItem); + } else if (legacy && !iter->second->items.empty()) { auto item = *iter->second->items.begin(); item->setExpanded(true); @@ -3208,16 +3556,17 @@ void TreeWidget::onUpdateStatus() DocumentObjectDataPtr data; if (activeDocItem) { auto it = activeDocItem->ObjectMap.find(obj); - if (it != activeDocItem->ObjectMap.end()) + if (it != activeDocItem->ObjectMap.end()) { data = it->second; + } } if (!data) { - auto docItem = getDocumentItem( - Application::Instance->getDocument(obj->getDocument())); + auto docItem = getDocumentItem(Application::Instance->getDocument(obj->getDocument())); if (docItem) { auto it = docItem->ObjectMap.find(obj); - if (it != docItem->ObjectMap.end()) + if (it != docItem->ObjectMap.end()) { data = it->second; + } } } if (data) { @@ -3226,12 +3575,14 @@ void TreeWidget::onUpdateStatus() item = *data->items.begin(); data->docItem->showItem(item, false, true); } - if (!errItem) + if (!errItem) { errItem = item; + } } } - if (errItem) + if (errItem) { scrollToItem(errItem); + } updateGeometries(); statusTimer->stop(); @@ -3247,21 +3598,25 @@ void TreeWidget::onItemEntered(QTreeWidgetItem* item) if (TreeParams::getPreSelection()) { int timeout = TreeParams::getPreSelectionDelay(); - if (timeout < 0) + if (timeout < 0) { timeout = 1; - if (preselectTime.elapsed() < timeout) + } + if (preselectTime.elapsed() < timeout) { onPreSelectTimer(); + } else { timeout = TreeParams::getPreSelectionTimeout(); - if (timeout < 0) + if (timeout < 0) { timeout = 1; + } preselectTimer->start(timeout); Selection().rmvPreselect(); } } } - else if (TreeParams::getPreSelection()) + else if (TreeParams::getPreSelection()) { Selection().rmvPreselect(); + } } void TreeWidget::leaveEvent(QEvent* event) @@ -3273,12 +3628,15 @@ void TreeWidget::leaveEvent(QEvent* event) } } -void TreeWidget::onPreSelectTimer() { - if (!TreeParams::getPreSelection()) +void TreeWidget::onPreSelectTimer() +{ + if (!TreeParams::getPreSelection()) { return; + } auto item = itemAt(viewport()->mapFromGlobal(QCursor::pos())); - if (!item || item->type() != TreeWidget::ObjectType) + if (!item || item->type() != TreeWidget::ObjectType) { return; + } preselectTime.restart(); auto objItem = static_cast(item); @@ -3287,12 +3645,21 @@ void TreeWidget::onPreSelectTimer() { std::ostringstream ss; App::DocumentObject* parent = nullptr; objItem->getSubName(ss, parent); - if (!parent) + if (!parent) { parent = obj; - else if (!obj->redirectSubName(ss, parent, nullptr)) + } + else if (!obj->redirectSubName(ss, parent, nullptr)) { ss << obj->getNameInDocument() << '.'; - Selection().setPreselect(parent->getDocument()->getName(), parent->getNameInDocument(), - ss.str().c_str(), 0, 0, 0, SelectionChanges::MsgSource::TreeView); + } + Selection().setPreselect( + parent->getDocument()->getName(), + parent->getNameInDocument(), + ss.str().c_str(), + 0, + 0, + 0, + SelectionChanges::MsgSource::TreeView + ); } void TreeWidget::onItemCollapsed(QTreeWidgetItem* item) @@ -3317,12 +3684,14 @@ void TreeWidget::scrollItemToTop() { auto doc = Application::Instance->activeDocument(); for (auto tree : Instances) { - if (!tree->isSelectionAttached() || tree->isSelectionBlocked()) + if (!tree->isSelectionAttached() || tree->isSelectionBlocked()) { continue; + } tree->_updateStatus(false); - if (doc && Gui::Selection().hasSelection(doc->getDocument()->getName(), ResolveMode::NoResolve)) { + if (doc + && Gui::Selection().hasSelection(doc->getDocument()->getName(), ResolveMode::NoResolve)) { auto it = tree->DocumentMap.find(doc); if (it != tree->DocumentMap.end()) { bool lock = tree->blockSelection(true); @@ -3334,8 +3703,9 @@ void TreeWidget::scrollItemToTop() tree->blockSelection(true); for (int i = 0; i < tree->rootItem->childCount(); i++) { auto docItem = dynamic_cast(tree->rootItem->child(i)); - if (!docItem) + if (!docItem) { continue; + } auto doc = docItem->document()->getDocument(); if (Gui::Selection().hasSelection(doc->getName())) { tree->currentDocItem = docItem; @@ -3353,33 +3723,36 @@ void TreeWidget::scrollItemToTop() void TreeWidget::expandSelectedItems(TreeItemMode mode) { - if (!isSelectionAttached()) + if (!isSelectionAttached()) { return; + } const auto items = selectedItems(); for (auto item : items) { switch (mode) { - case TreeItemMode::ExpandPath: { - QTreeWidgetItem* parentItem = item->parent(); - while (parentItem) { - parentItem->setExpanded(true); - parentItem = parentItem->parent(); - } - item->setExpanded(true); - break; - } - case TreeItemMode::ExpandItem: - item->setExpanded(true); - break; - case TreeItemMode::CollapseItem: - item->setExpanded(false); - break; - case TreeItemMode::ToggleItem: - if (item->isExpanded()) - item->setExpanded(false); - else + case TreeItemMode::ExpandPath: { + QTreeWidgetItem* parentItem = item->parent(); + while (parentItem) { + parentItem->setExpanded(true); + parentItem = parentItem->parent(); + } item->setExpanded(true); - break; + break; + } + case TreeItemMode::ExpandItem: + item->setExpanded(true); + break; + case TreeItemMode::CollapseItem: + item->setExpanded(false); + break; + case TreeItemMode::ToggleItem: + if (item->isExpanded()) { + item->setExpanded(false); + } + else { + item->setExpanded(true); + } + break; } } } @@ -3391,10 +3764,14 @@ void TreeWidget::setupText() this->headerItem()->setText(2, tr("Internal name")); this->showHiddenAction->setText(tr("Show Items Hidden in Tree View")); - this->showHiddenAction->setStatusTip(tr("Shows items that are marked as 'hidden' in the tree view")); + this->showHiddenAction->setStatusTip( + tr("Shows items that are marked as 'hidden' in the tree view") + ); this->toggleVisibilityInTreeAction->setText(tr("Toggle Visibility in Tree View")); - this->toggleVisibilityInTreeAction->setStatusTip(tr("Toggles the visibility of selected items in the tree view")); + this->toggleVisibilityInTreeAction->setStatusTip( + tr("Toggles the visibility of selected items in the tree view") + ); this->createGroupAction->setText(tr("Create Group")); this->createGroupAction->setStatusTip(tr("Creates a group")); @@ -3426,8 +3803,9 @@ void TreeWidget::setupText() this->skipRecomputeAction->setStatusTip(tr("Enables or disables the recomputations of document")); this->allowPartialRecomputeAction->setText(tr("Allow Partial Recomputes")); - this->allowPartialRecomputeAction->setStatusTip( - tr("Enables or disables the recomputating editing object when 'skip recomputation' is enabled")); + this->allowPartialRecomputeAction->setStatusTip(tr( + "Enables or disables the recomputating editing object when 'skip recomputation' is enabled" + )); this->markRecomputeAction->setText(tr("Mark to Recompute")); this->markRecomputeAction->setStatusTip(tr("Marks this object to be recomputed")); @@ -3443,22 +3821,27 @@ void TreeWidget::syncView(ViewProviderDocumentObject* vp) if (currentDocItem && TreeParams::getSyncView()) { bool focus = hasFocus(); currentDocItem->document()->setActiveView(vp); - if (focus) + if (focus) { setFocus(); + } } } void TreeWidget::onShowHidden() { - if (!this->contextItem) + if (!this->contextItem) { return; + } DocumentItem* docItem = nullptr; - if (this->contextItem->type() == DocumentType) + if (this->contextItem->type() == DocumentType) { docItem = static_cast(contextItem); - else if (this->contextItem->type() == ObjectType) + } + else if (this->contextItem->type() == ObjectType) { docItem = static_cast(contextItem)->getOwnerDocument(); - if (docItem) + } + if (docItem) { docItem->setShowHidden(showHiddenAction->isChecked()); + } } void TreeWidget::onToggleVisibilityInTree() @@ -3488,18 +3871,18 @@ void TreeWidget::onToggleVisibilityInTree() void TreeWidget::changeEvent(QEvent* e) { - if (e->type() == QEvent::LanguageChange) + if (e->type() == QEvent::LanguageChange) { setupText(); + } QTreeWidget::changeEvent(e); } void TreeWidget::onItemSelectionChanged() { - if (!this->isSelectionAttached() - || this->isSelectionBlocked() - || updateBlocked) + if (!this->isSelectionAttached() || this->isSelectionBlocked() || updateBlocked) { return; + } _LastSelectedTreeWidget = this; @@ -3511,10 +3894,12 @@ void TreeWidget::onItemSelectionChanged() preselectTimer->stop(); } - if (selectTimer->isActive()) + if (selectTimer->isActive()) { onSelectTimer(); - else + } + else { _updateStatus(false); + } auto selItems = selectedItems(); @@ -3524,19 +3909,20 @@ void TreeWidget::onItemSelectionChanged() for (auto it = selItems.begin(); it != selItems.end();) { auto item = *it; if ((firstType == ObjectType && item->type() != ObjectType) - || (firstType == DocumentType && item != selItems.back())) - { + || (firstType == DocumentType && item != selItems.back())) { item->setSelected(false); it = selItems.erase(it); } - else + else { ++it; + } } } if (selItems.size() <= 1) { - if (TreeParams::getRecordSelection()) + if (TreeParams::getRecordSelection()) { Gui::Selection().selStackPush(); + } // This special handling to deal with possible discrepancy of // Gui.Selection and Tree view selection because of newly added @@ -3544,15 +3930,17 @@ void TreeWidget::onItemSelectionChanged() Selection().clearCompleteSelection(); DocumentObjectItem* item = nullptr; if (!selItems.empty()) { - if (selItems.front()->type() == ObjectType) + if (selItems.front()->type() == ObjectType) { item = static_cast(selItems.front()); + } else if (selItems.front()->type() == DocumentType) { auto ditem = static_cast(selItems.front()); if (TreeParams::getSyncView()) { bool focus = hasFocus(); ditem->document()->setActiveView(); - if (focus) + if (focus) { setFocus(); + } } // For triggering property editor refresh Gui::Selection().signalSelectionChanged(SelectionChanges()); @@ -3563,8 +3951,9 @@ void TreeWidget::onItemSelectionChanged() v.second->clearSelection(item); currentDocItem = nullptr; } - if (TreeParams::getRecordSelection()) + if (TreeParams::getRecordSelection()) { Gui::Selection().selStackPush(); + } } else { for (auto pos = DocumentMap.begin(); pos != DocumentMap.end(); ++pos) { @@ -3572,31 +3961,36 @@ void TreeWidget::onItemSelectionChanged() pos->second->updateSelection(pos->second); currentDocItem = nullptr; } - if (TreeParams::getRecordSelection()) + if (TreeParams::getRecordSelection()) { Gui::Selection().selStackPush(true, true); + } } this->blockSelection(lock); } -void TreeWidget::synchronizeSelectionCheckBoxes() { +void TreeWidget::synchronizeSelectionCheckBoxes() +{ const bool useCheckBoxes = isSelectionCheckBoxesEnabled(); for (auto tree : TreeWidget::Instances) { QSignalBlocker blocker(tree); for (QTreeWidgetItemIterator it(tree); *it; ++it) { auto item = *it; if (item->type() == ObjectType) { - if (useCheckBoxes) + if (useCheckBoxes) { item->setCheckState(0, item->isSelected() ? Qt::Checked : Qt::Unchecked); - else + } + else { item->setData(0, Qt::CheckStateRole, QVariant()); + } } } tree->resizeColumnToContents(0); } } -void TreeWidget::updateVisibilityIcons() { +void TreeWidget::updateVisibilityIcons() +{ for (auto tree : TreeWidget::Instances) { QSignalBlocker blocker(tree); for (QTreeWidgetItemIterator it(tree); *it; ++it) { @@ -3610,12 +4004,14 @@ void TreeWidget::updateVisibilityIcons() { } } -QList TreeWidget::childrenOfItem(const QTreeWidgetItem& item) const { +QList TreeWidget::childrenOfItem(const QTreeWidgetItem& item) const +{ QList children = QList(); // check item is in this tree - if (!this->indexFromItem(&item).isValid()) + if (!this->indexFromItem(&item).isValid()) { return children; + } for (int i = 0; i < item.childCount(); i++) { children.append(item.child(i)); @@ -3623,7 +4019,8 @@ QList TreeWidget::childrenOfItem(const QTreeWidgetItem& item) return children; } -void TreeWidget::onItemChanged(QTreeWidgetItem* item, int column) { +void TreeWidget::onItemChanged(QTreeWidgetItem* item, int column) +{ if (column == 0 && isSelectionCheckBoxesEnabled()) { bool selected = item->isSelected(); bool checked = item->checkState(0) == Qt::Checked; @@ -3633,7 +4030,8 @@ void TreeWidget::onItemChanged(QTreeWidgetItem* item, int column) { } } -void TreeWidget::onSelectTimer() { +void TreeWidget::onSelectTimer() +{ _updateStatus(false); @@ -3648,8 +4046,9 @@ void TreeWidget::onSelectTimer() { } } else { - for (auto& v : DocumentMap) + for (auto& v : DocumentMap) { v.second->clearSelection(); + } } this->blockSelection(locked); selectTimer->stop(); @@ -3664,20 +4063,20 @@ void TreeWidget::onSelectionChanged(const SelectionChanges& msg) return; } - switch (msg.Type) - { - case SelectionChanges::AddSelection: - case SelectionChanges::RmvSelection: - case SelectionChanges::SetSelection: - case SelectionChanges::ClrSelection: { - int timeout = TreeParams::getSelectionTimeout(); - if (timeout <= 0) - timeout = 1; - selectTimer->start(timeout); - break; - } - default: - break; + switch (msg.Type) { + case SelectionChanges::AddSelection: + case SelectionChanges::RmvSelection: + case SelectionChanges::SetSelection: + case SelectionChanges::ClrSelection: { + int timeout = TreeParams::getSelectionTimeout(); + if (timeout <= 0) { + timeout = 1; + } + selectTimer->start(timeout); + break; + } + default: + break; } } @@ -3690,26 +4089,25 @@ TreePanel::TreePanel(const char* name, QWidget* parent) { this->treeWidget = new TreeWidget(name, this); int indent = TreeParams::getIndentation(); - if (indent) + if (indent) { this->treeWidget->setIndentation(indent); + } auto pLayout = new QVBoxLayout(this); pLayout->setSpacing(0); pLayout->setContentsMargins(0, 0, 0, 0); pLayout->addWidget(this->treeWidget); - connect(this->treeWidget, &TreeWidget::emitSearchObjects, - this, &TreePanel::showEditor); + connect(this->treeWidget, &TreeWidget::emitSearchObjects, this, &TreePanel::showEditor); this->searchBox = new Gui::ExpressionLineEdit(this, true); - static_cast(this->searchBox)->setExactMatch(Gui::ExpressionParameter::instance()->isExactMatch()); + static_cast(this->searchBox) + ->setExactMatch(Gui::ExpressionParameter::instance()->isExactMatch()); pLayout->addWidget(this->searchBox); this->searchBox->hide(); this->searchBox->installEventFilter(this); this->searchBox->setPlaceholderText(tr("Search")); - connect(this->searchBox, &QLineEdit::returnPressed, - this, &TreePanel::accept); - connect(this->searchBox, &QLineEdit::textChanged, - this, &TreePanel::itemSearch); + connect(this->searchBox, &QLineEdit::returnPressed, this, &TreePanel::accept); + connect(this->searchBox, &QLineEdit::textChanged, this, &TreePanel::itemSearch); } TreePanel::~TreePanel() = default; @@ -3724,21 +4122,22 @@ void TreePanel::accept() bool TreePanel::eventFilter(QObject* obj, QEvent* ev) { - if (obj != this->searchBox) + if (obj != this->searchBox) { return false; + } if (ev->type() == QEvent::KeyPress) { bool consumed = false; int key = static_cast(ev)->key(); switch (key) { - case Qt::Key_Escape: - hideEditor(); - consumed = true; - treeWidget->setFocus(); - break; + case Qt::Key_Escape: + hideEditor(); + consumed = true; + treeWidget->setFocus(); + break; - default: - break; + default: + break; } return consumed; @@ -3761,8 +4160,9 @@ void TreePanel::hideEditor() this->searchBox->hide(); this->treeWidget->resetItemSearch(); auto sels = this->treeWidget->selectedItems(); - if (!sels.empty()) + if (!sels.empty()) { this->treeWidget->scrollToItem(sels.front()); + } } void TreePanel::itemSearch(const QString& text) @@ -3787,12 +4187,15 @@ TreeDockWidget::TreeDockWidget(Gui::Document* pcDocument, QWidget* parent) TreeDockWidget::~TreeDockWidget() = default; -void TreeWidget::selectLinkedObject(App::DocumentObject* linked) { - if (!isSelectionAttached() || isSelectionBlocked()) +void TreeWidget::selectLinkedObject(App::DocumentObject* linked) +{ + if (!isSelectionAttached() || isSelectionBlocked()) { return; + } auto linkedVp = freecad_cast( - Application::Instance->getViewProvider(linked)); + Application::Instance->getViewProvider(linked) + ); if (!linkedVp) { TREE_ERR("invalid linked view provider"); return; @@ -3803,10 +4206,12 @@ void TreeWidget::selectLinkedObject(App::DocumentObject* linked) { return; } - if (selectTimer->isActive()) + if (selectTimer->isActive()) { onSelectTimer(); - else + } + else { _updateStatus(false); + } auto it = linkedDoc->ObjectMap.find(linked); if (it == linkedDoc->ObjectMap.end()) { @@ -3814,50 +4219,68 @@ void TreeWidget::selectLinkedObject(App::DocumentObject* linked) { return; } auto linkedItem = it->second->rootItem; - if (!linkedItem) + if (!linkedItem) { linkedItem = *it->second->items.begin(); + } - if (linkedDoc->showItem(linkedItem, true)) + if (linkedDoc->showItem(linkedItem, true)) { scrollToItem(linkedItem); + } if (linkedDoc->document()->getDocument() != App::GetApplication().getActiveDocument()) { bool focus = hasFocus(); linkedDoc->document()->setActiveView(linkedItem->object()); - if (focus) + if (focus) { setFocus(); + } } } // ---------------------------------------------------------------------------- DocumentItem::DocumentItem(const Gui::Document* doc, QTreeWidgetItem* parent) - : QTreeWidgetItem(parent, TreeWidget::DocumentType), pDocument(const_cast(doc)) + : QTreeWidgetItem(parent, TreeWidget::DocumentType) + , pDocument(const_cast(doc)) { - //NOLINTBEGIN - // Setup connections - connectNewObject = doc->signalNewObject.connect(std::bind(&DocumentItem::slotNewObject, this, sp::_1)); + // NOLINTBEGIN + // Setup connections + connectNewObject = doc->signalNewObject.connect( + std::bind(&DocumentItem::slotNewObject, this, sp::_1) + ); connectDelObject = doc->signalDeletedObject.connect( - std::bind(&TreeWidget::slotDeleteObject, getTree(), sp::_1)); + std::bind(&TreeWidget::slotDeleteObject, getTree(), sp::_1) + ); if (!App::GetApplication().isRestoring()) { connectChgObject = doc->signalChangedObject.connect( - std::bind(&TreeWidget::slotChangeObject, getTree(), sp::_1, sp::_2)); + std::bind(&TreeWidget::slotChangeObject, getTree(), sp::_1, sp::_2) + ); connectTouchedObject = doc->getDocument()->signalTouchedObject.connect( - std::bind(&TreeWidget::slotTouchedObject, getTree(), sp::_1)); + std::bind(&TreeWidget::slotTouchedObject, getTree(), sp::_1) + ); } connectEdtObject = doc->signalInEdit.connect(std::bind(&DocumentItem::slotInEdit, this, sp::_1)); - connectResObject = doc->signalResetEdit.connect(std::bind(&DocumentItem::slotResetEdit, this, sp::_1)); + connectResObject = doc->signalResetEdit.connect( + std::bind(&DocumentItem::slotResetEdit, this, sp::_1) + ); connectHltObject = doc->signalHighlightObject.connect( - std::bind(&DocumentItem::slotHighlightObject, this, sp::_1, sp::_2, sp::_3, sp::_4, sp::_5)); + std::bind(&DocumentItem::slotHighlightObject, this, sp::_1, sp::_2, sp::_3, sp::_4, sp::_5) + ); connectExpObject = doc->signalExpandObject.connect( - std::bind(&DocumentItem::slotExpandObject, this, sp::_1, sp::_2, sp::_3, sp::_4)); - connectScrObject = doc->signalScrollToObject.connect(std::bind(&DocumentItem::slotScrollToObject, this, sp::_1)); + std::bind(&DocumentItem::slotExpandObject, this, sp::_1, sp::_2, sp::_3, sp::_4) + ); + connectScrObject = doc->signalScrollToObject.connect( + std::bind(&DocumentItem::slotScrollToObject, this, sp::_1) + ); auto adoc = doc->getDocument(); - connectRecomputed = adoc->signalRecomputed.connect(std::bind(&DocumentItem::slotRecomputed, this, sp::_1, sp::_2)); + connectRecomputed = adoc->signalRecomputed.connect( + std::bind(&DocumentItem::slotRecomputed, this, sp::_1, sp::_2) + ); connectRecomputedObj = adoc->signalRecomputedObject.connect( - std::bind(&DocumentItem::slotRecomputedObject, this, sp::_1)); - //NOLINTEND + std::bind(&DocumentItem::slotRecomputedObject, this, sp::_1) + ); + // NOLINTEND - setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable/*|Qt::ItemIsEditable*/); + setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable /*|Qt::ItemIsEditable*/); treeName = getTree()->getTreeName(); } @@ -3877,26 +4300,30 @@ DocumentItem::~DocumentItem() connectRecomputedObj.disconnect(); } -TreeWidget* DocumentItem::getTree() const { +TreeWidget* DocumentItem::getTree() const +{ return static_cast(treeWidget()); } -const char* DocumentItem::getTreeName() const { +const char* DocumentItem::getTreeName() const +{ return treeName; } #define FOREACH_ITEM(_item, _obj) \ - auto _it = ObjectMap.end();\ - if(_obj.getObject() && _obj.getObject()->isAttachedToDocument())\ - _it = ObjectMap.find(_obj.getObject());\ - if(_it != ObjectMap.end()) {\ - for(auto _item : _it->second->items) { + auto _it = ObjectMap.end(); \ + if (_obj.getObject() && _obj.getObject()->isAttachedToDocument()) \ + _it = ObjectMap.find(_obj.getObject()); \ + if (_it != ObjectMap.end()) { \ + for (auto _item : _it->second->items) { #define FOREACH_ITEM_ALL(_item) \ - for(const auto& _v : ObjectMap) {\ - for(auto _item : _v.second->items) { + for (const auto& _v : ObjectMap) { \ + for (auto _item : _v.second->items) { -#define END_FOREACH_ITEM }} +#define END_FOREACH_ITEM \ + } \ + } void DocumentItem::slotInEdit(const Gui::ViewProviderDocumentObject& v) @@ -3904,28 +4331,33 @@ void DocumentItem::slotInEdit(const Gui::ViewProviderDocumentObject& v) (void)v; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/TreeView"); + "User parameter:BaseApp/Preferences/TreeView" + ); unsigned long col = hGrp->GetUnsigned("TreeEditColor", 563609599); QColor color(Base::Color::fromPackedRGB(col)); if (!getTree()->editingItem) { auto doc = Application::Instance->editDocument(); - if (!doc) + if (!doc) { return; + } ViewProviderDocumentObject* parentVp = nullptr; std::string subname; auto vp = doc->getInEdit(&parentVp, &subname); - if (!parentVp) + if (!parentVp) { parentVp = freecad_cast(vp); - if (parentVp) + } + if (parentVp) { getTree()->editingItem = findItemByObject(true, parentVp->getObject(), subname.c_str()); + } } - if (getTree()->editingItem) + if (getTree()->editingItem) { getTree()->editingItem->setBackground(0, color); + } else { FOREACH_ITEM(item, v) - item->setBackground(0, color); + item->setBackground(0, color); END_FOREACH_ITEM } } @@ -3934,19 +4366,21 @@ void DocumentItem::slotResetEdit(const Gui::ViewProviderDocumentObject& v) { auto tree = getTree(); FOREACH_ITEM_ALL(item) - if (tree->editingItem) { - if (item == tree->editingItem) { - item->setData(0, Qt::BackgroundRole, QVariant()); - break; - } - } - else if (item->object() == &v) + if (tree->editingItem) { + if (item == tree->editingItem) { item->setData(0, Qt::BackgroundRole, QVariant()); + break; + } + } + else if (item->object() == &v) { + item->setData(0, Qt::BackgroundRole, QVariant()); + } END_FOREACH_ITEM - tree->editingItem = nullptr; + tree->editingItem = nullptr; } -void DocumentItem::slotNewObject(const Gui::ViewProviderDocumentObject& obj) { +void DocumentItem::slotNewObject(const Gui::ViewProviderDocumentObject& obj) +{ if (!obj.getObject() || !obj.getObject()->isAttachedToDocument()) { FC_ERR("view provider not attached"); return; @@ -3955,24 +4389,32 @@ void DocumentItem::slotNewObject(const Gui::ViewProviderDocumentObject& obj) { getTree()->_updateStatus(); } -bool DocumentItem::createNewItem(const Gui::ViewProviderDocumentObject& obj, - QTreeWidgetItem* parent, int index, DocumentObjectDataPtr data) +bool DocumentItem::createNewItem( + const Gui::ViewProviderDocumentObject& obj, + QTreeWidgetItem* parent, + int index, + DocumentObjectDataPtr data +) { - if (!obj.getObject() || - !obj.getObject()->isAttachedToDocument() || - obj.getObject()->testStatus(App::PartialObject)) + if (!obj.getObject() || !obj.getObject()->isAttachedToDocument() + || obj.getObject()->testStatus(App::PartialObject)) { return false; + } if (!data) { auto& pdata = ObjectMap[obj.getObject()]; if (!pdata) { pdata = std::make_shared( - this, const_cast(&obj)); + this, + const_cast(&obj) + ); auto& entry = getTree()->ObjectTable[obj.getObject()]; - if (!entry.empty()) + if (!entry.empty()) { pdata->updateChildren(*entry.begin()); - else + } + else { pdata->updateChildren(true); + } entry.insert(pdata); } else if (pdata->rootItem && !parent) { @@ -3986,29 +4428,34 @@ bool DocumentItem::createNewItem(const Gui::ViewProviderDocumentObject& obj, if (!parent || parent == this) { parent = this; data->rootItem = item; - if (index < 0) + if (index < 0) { index = findRootIndex(obj.getObject()); + } } - if (index < 0) + if (index < 0) { parent->addChild(item); - else + } + else { parent->insertChild(index, item); + } assert(item->parent() == parent); item->setText(0, QString::fromUtf8(data->label.c_str())); - if (!data->label2.empty()) + if (!data->label2.empty()) { item->setText(1, QString::fromUtf8(data->label2.c_str())); + } item->setText(2, QString::fromUtf8(data->internalName.c_str())); - if (!obj.showInTree() && !showHidden()) + if (!obj.showInTree() && !showHidden()) { item->setHidden(true); + } item->testStatus(true); populateItem(item); return true; } -ViewProviderDocumentObject* DocumentItem::getViewProvider(App::DocumentObject* obj) { - return freecad_cast( - Application::Instance->getViewProvider(obj)); +ViewProviderDocumentObject* DocumentItem::getViewProvider(App::DocumentObject* obj) +{ + return freecad_cast(Application::Instance->getViewProvider(obj)); } void TreeWidget::slotDeleteDocument(const Gui::Document& Doc) @@ -4019,8 +4466,9 @@ void TreeWidget::slotDeleteDocument(const Gui::Document& Doc) UpdateDisabler disabler(*this, updateBlocked); auto docItem = it->second; for (auto& v : docItem->ObjectMap) { - for (auto item : v.second->items) + for (auto item : v.second->items) { item->myOwner = nullptr; + } auto obj = v.second->viewObject->getObject(); if (obj->getDocument() == Doc.getDocument()) { _slotDeleteObject(*v.second->viewObject, docItem); @@ -4037,7 +4485,8 @@ void TreeWidget::slotDeleteDocument(const Gui::Document& Doc) } } -void TreeWidget::slotDeleteObject(const Gui::ViewProviderDocumentObject& view) { +void TreeWidget::slotDeleteObject(const Gui::ViewProviderDocumentObject& view) +{ _slotDeleteObject(view, nullptr); } @@ -4045,8 +4494,9 @@ void TreeWidget::_slotDeleteObject(const Gui::ViewProviderDocumentObject& view, { auto obj = view.getObject(); auto itEntry = ObjectTable.find(obj); - if (itEntry == ObjectTable.end()) + if (itEntry == ObjectTable.end()) { return; + } if (itEntry->second.empty()) { ObjectTable.erase(itEntry); @@ -4064,14 +4514,16 @@ void TreeWidget::_slotDeleteObject(const Gui::ViewProviderDocumentObject& view, for (const auto& data : itEntry->second) { DocumentItem* docItem = data->docItem; - if (docItem == deletingDoc) + if (docItem == deletingDoc) { continue; + } auto doc = docItem->document()->getDocument(); auto& items = data->items; - if (obj->getDocument() == doc) + if (obj->getDocument() == doc) { docItem->_ParentMap.erase(obj); + } for (auto cit = items.begin(), citNext = cit; cit != items.end(); cit = citNext) { ++citNext; @@ -4084,9 +4536,11 @@ void TreeWidget::_slotDeleteObject(const Gui::ViewProviderDocumentObject& view, int index = parent->indexOfChild(itemToDelete); if (index > 0) { newFocusItem = parent->child(index - 1); - } else if (parent->childCount() > 1) { + } + else if (parent->childCount() > 1) { newFocusItem = parent->child(index + 1); - } else { + } + else { // no siblings, move to parent newFocusItem = parent; } @@ -4100,19 +4554,22 @@ void TreeWidget::_slotDeleteObject(const Gui::ViewProviderDocumentObject& view, // under document item. for (auto child : data->children) { auto childVp = docItem->getViewProvider(child); - if (!childVp || child->getDocument() != doc) + if (!childVp || child->getDocument() != doc) { continue; + } docItem->_ParentMap[child].erase(obj); auto cit = docItem->ObjectMap.find(child); if (cit == docItem->ObjectMap.end() || cit->second->items.empty()) { - if (docItem->createNewItem(*childVp)) + if (docItem->createNewItem(*childVp)) { needUpdate = true; + } } else { auto childItem = *cit->second->items.begin(); if (childItem->requiredAtRoot(false)) { - if (docItem->createNewItem(*childItem->object(), docItem, -1, childItem->myData)) + if (docItem->createNewItem(*childItem->object(), docItem, -1, childItem->myData)) { needUpdate = true; + } } } childVp->setShowable(docItem->isObjectShowable(child)); @@ -4138,21 +4595,26 @@ void TreeWidget::_slotDeleteObject(const Gui::ViewProviderDocumentObject& view, }); } - if (needUpdate) + if (needUpdate) { _updateStatus(); + } } -bool DocumentItem::populateObject(App::DocumentObject* obj) { +bool DocumentItem::populateObject(App::DocumentObject* obj) +{ // make sure at least one of the item corresponding to obj is populated auto it = ObjectMap.find(obj); - if (it == ObjectMap.end()) + if (it == ObjectMap.end()) { return false; + } auto& items = it->second->items; - if (items.empty()) + if (items.empty()) { return false; + } for (auto item : items) { - if (item->populated) + if (item->populated) { return true; + } } TREE_LOG("force populate object " << obj->getFullName()); auto item = *items.begin(); @@ -4165,31 +4627,38 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del { (void)delay; - if (item->populated && !refresh) + if (item->populated && !refresh) { return; + } // Lazy loading policy: We will create an item for each children object if // a) the item is expanded, or b) there is at least one free child, i.e. // child originally located at root. - item->setChildIndicatorPolicy(item->myData->children.empty() ? - QTreeWidgetItem::DontShowIndicator : QTreeWidgetItem::ShowIndicator); + item->setChildIndicatorPolicy( + item->myData->children.empty() ? QTreeWidgetItem::DontShowIndicator + : QTreeWidgetItem::ShowIndicator + ); if (!item->populated && !item->isExpanded()) { bool doPopulate = false; bool external = item->object()->getDocument() != item->getOwnerDocument()->document(); - if (external) + if (external) { return; + } auto obj = item->object()->getObject(); auto linked = obj->getLinkedObject(true); - if (linked && linked->getDocument() != obj->getDocument()) + if (linked && linked->getDocument() != obj->getDocument()) { return; + } for (auto child : item->myData->children) { auto it = ObjectMap.find(child); if (it == ObjectMap.end() || it->second->items.empty()) { auto vp = getViewProvider(child); - if (!vp) continue; + if (!vp) { + continue; + } doPopulate = true; break; } @@ -4201,8 +4670,9 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del } } - if (!doPopulate) + if (!doPopulate) { return; + } } item->populated = true; @@ -4215,26 +4685,29 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del int childCount = item->childCount(); for (auto child : item->myData->children) { - ++i; // the current index of the claimed child + ++i; // the current index of the claimed child bool found = false; for (int j = i; j < childCount; ++j) { QTreeWidgetItem* ci = item->child(j); - if (ci->type() != TreeWidget::ObjectType) + if (ci->type() != TreeWidget::ObjectType) { continue; + } auto childItem = static_cast(ci); - if (childItem->object()->getObject() != child) + if (childItem->object()->getObject() != child) { continue; + } found = true; - if (j != i) { // fix index if it is changed + if (j != i) { // fix index if it is changed childItem->setHighlight(false); item->removeChild(ci); item->insertChild(i, ci); assert(ci->parent() == item); - if (checkHidden) + if (checkHidden) { updateItemsVisibility(ci, false); + } } // Check if the item just changed its policy of whether to remove @@ -4254,8 +4727,9 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del break; } - if (found) + if (found) { continue; + } // This algo will be recursively applied to newly created child items // through slotNewObject -> populateItem @@ -4263,26 +4737,37 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del auto it = ObjectMap.find(child); if (it == ObjectMap.end() || it->second->items.empty()) { auto vp = getViewProvider(child); - if (!vp || !createNewItem(*vp, item, i, it == ObjectMap.end() ? DocumentObjectDataPtr() : it->second)) + if (!vp + || !createNewItem( + *vp, + item, + i, + it == ObjectMap.end() ? DocumentObjectDataPtr() : it->second + )) { --i; - else + } + else { updated = true; + } continue; } if (!item->myData->removeChildrenFromRoot || !it->second->rootItem) { DocumentObjectItem* childItem = *it->second->items.begin(); - if (!createNewItem(*childItem->object(), item, i, it->second)) + if (!createNewItem(*childItem->object(), item, i, it->second)) { --i; - else + } + else { updated = true; + } } else { DocumentObjectItem* childItem = it->second->rootItem; if (item == childItem || item->isChildOfItem(childItem)) { - TREE_ERR("Cyclic dependency in " - << item->object()->getObject()->getFullName() - << '.' << childItem->object()->getObject()->getFullName()); + TREE_ERR( + "Cyclic dependency in " << item->object()->getObject()->getFullName() << '.' + << childItem->object()->getObject()->getFullName() + ); --i; continue; } @@ -4291,8 +4776,9 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del this->removeChild(childItem); item->insertChild(i, childItem); assert(childItem->parent() == item); - if (checkHidden) + if (checkHidden) { updateItemsVisibility(childItem, false); + } } } @@ -4303,13 +4789,16 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del if (childItem->requiredAtRoot()) { item->removeChild(childItem); auto index = findRootIndex(childItem->object()->getObject()); - if (index >= 0) + if (index >= 0) { this->insertChild(index, childItem); - else + } + else { this->addChild(childItem); + } assert(childItem->parent() == this); - if (checkHidden) + if (checkHidden) { updateItemsVisibility(childItem, false); + } childItem->myData->rootItem = childItem; continue; } @@ -4319,19 +4808,23 @@ void DocumentItem::populateItem(DocumentObjectItem* item, bool refresh, bool del delete ci; getTree()->blockSelection(lock); } - if (updated) + if (updated) { getTree()->_updateStatus(); + } } -int DocumentItem::findRootIndex(App::DocumentObject* childObj) { - if (!TreeParams::getKeepRootOrder() || !childObj || !childObj->isAttachedToDocument()) +int DocumentItem::findRootIndex(App::DocumentObject* childObj) +{ + if (!TreeParams::getKeepRootOrder() || !childObj || !childObj->isAttachedToDocument()) { return -1; + } // Use view provider's tree rank to find correct place at the root level. int count = this->childCount(); - if (!count) + if (!count) { return -1; + } int first, last; @@ -4342,7 +4835,9 @@ int DocumentItem::findRootIndex(App::DocumentObject* childObj) { return vp->getTreeRank(); }; - auto vpc = freecad_cast(Application::Instance->getViewProvider(childObj)); + auto vpc = freecad_cast( + Application::Instance->getViewProvider(childObj) + ); int childTreeRank = getTreeRank(vpc); // find the last item @@ -4378,22 +4873,26 @@ int DocumentItem::findRootIndex(App::DocumentObject* childObj) { pos = first + step; for (; pos <= last; ++pos) { auto citem = this->child(pos); - if (citem->type() != TreeWidget::ObjectType) + if (citem->type() != TreeWidget::ObjectType) { continue; + } auto vp = static_cast(citem)->object(); if (vp->getTreeRank() < childTreeRank) { first = ++pos; count -= step + 1; } - else + else { count = step; + } break; } - if (pos > last) + if (pos > last) { return -1; + } } - if (first > last) + if (first > last) { return -1; + } return first; } @@ -4411,10 +4910,13 @@ void DocumentItem::sortObjectItems() } } - std::stable_sort(sortedItems.begin(), sortedItems.end(), + std::stable_sort( + sortedItems.begin(), + sortedItems.end(), [](DocumentObjectItem* a, DocumentObjectItem* b) { - return a->object()->getTreeRank() < b->object()->getTreeRank(); - }); + return a->object()->getTreeRank() < b->object()->getTreeRank(); + } + ); int sortedIndex = 0; std::vector expansion; @@ -4443,23 +4945,26 @@ void DocumentItem::sortObjectItems() } } -void TreeWidget::slotChangeObject( - const Gui::ViewProviderDocumentObject& view, const App::Property& prop) { +void TreeWidget::slotChangeObject(const Gui::ViewProviderDocumentObject& view, const App::Property& prop) +{ auto obj = view.getObject(); - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return; + } auto itEntry = ObjectTable.find(obj); - if (itEntry == ObjectTable.end() || itEntry->second.empty()) + if (itEntry == ObjectTable.end() || itEntry->second.empty()) { return; + } _updateStatus(); // Let's not waste time on the newly added Visibility property in // DocumentObject. - if (&prop == &obj->Visibility) + if (&prop == &obj->Visibility) { return; + } if (&prop == &obj->Label) { const char* label = obj->Label.getValue(); @@ -4468,8 +4973,9 @@ void TreeWidget::slotChangeObject( for (const auto& data : itEntry->second) { data->label = label; auto displayName = QString::fromUtf8(label); - for (auto item : data->items) + for (auto item : data->items) { item->setText(0, displayName); + } } } return; @@ -4482,23 +4988,26 @@ void TreeWidget::slotChangeObject( for (const auto& data : itEntry->second) { data->label2 = label; auto displayName = QString::fromUtf8(label); - for (auto item : data->items) + for (auto item : data->items) { item->setText(1, displayName); + } } } return; } auto& s = ChangedObjects[obj]; - if (prop.testStatus(App::Property::Output) - || prop.testStatus(App::Property::NoRecompute)) - { + if (prop.testStatus(App::Property::Output) || prop.testStatus(App::Property::NoRecompute)) { s.set(CS_Output); } } -void TreeWidget::updateChildren(App::DocumentObject* obj, - const std::set& dataSet, bool propOutput, bool force) +void TreeWidget::updateChildren( + App::DocumentObject* obj, + const std::set& dataSet, + bool propOutput, + bool force +) { bool childrenChanged = false; std::vector children; @@ -4510,113 +5019,140 @@ void TreeWidget::updateChildren(App::DocumentObject* obj, found = data; childrenChanged = found->updateChildren(force); removeChildrenFromRoot = found->viewObject->canRemoveChildrenFromRoot(); - if (!childrenChanged && found->removeChildrenFromRoot == removeChildrenFromRoot) + if (!childrenChanged && found->removeChildrenFromRoot == removeChildrenFromRoot) { return; + } } - else if (childrenChanged) + else if (childrenChanged) { data->updateChildren(found); + } data->removeChildrenFromRoot = removeChildrenFromRoot; DocumentItem* docItem = data->docItem; - for (auto item : data->items) + for (auto item : data->items) { docItem->populateItem(item, true); + } } - if (force) + if (force) { return; + } if (childrenChanged && propOutput) { // When a property is marked as output, it will not touch its object, // and thus, its property change will not be propagated through // recomputation. So we have to manually check for each links here. for (auto link : App::GetApplication().getLinksTo(obj, App::GetLinkRecursive)) { - if (ChangedObjects.contains(link)) + if (ChangedObjects.contains(link)) { continue; + } std::vector linkedChildren; DocumentObjectDataPtr found; auto it = ObjectTable.find(link); - if (it == ObjectTable.end()) + if (it == ObjectTable.end()) { continue; + } for (auto data : it->second) { if (!found) { found = data; - if (!found->updateChildren(false)) + if (!found->updateChildren(false)) { break; + } } data->updateChildren(found); DocumentItem* docItem = data->docItem; - for (auto item : data->items) + for (auto item : data->items) { docItem->populateItem(item, true); + } } } } if (childrenChanged) { - if (!selectTimer->isActive()) + if (!selectTimer->isActive()) { onSelectionChanged(SelectionChanges()); + } - //if the item is in a GeoFeatureGroup we may need to update that too, as the claim children - //of the geofeaturegroup depends on what the childs claim + // if the item is in a GeoFeatureGroup we may need to update that too, as the claim children + // of the geofeaturegroup depends on what the childs claim auto grp = App::GeoFeatureGroupExtension::getGroupOfObject(obj); if (grp && !ChangedObjects.contains(grp)) { auto iter = ObjectTable.find(grp); - if (iter != ObjectTable.end()) + if (iter != ObjectTable.end()) { updateChildren(grp, iter->second, true, false); + } } } } -void DocumentItem::slotHighlightObject(const Gui::ViewProviderDocumentObject& obj, - const Gui::HighlightMode& high, bool set, const App::DocumentObject* parent, const char* subname) +void DocumentItem::slotHighlightObject( + const Gui::ViewProviderDocumentObject& obj, + const Gui::HighlightMode& high, + bool set, + const App::DocumentObject* parent, + const char* subname +) { getTree()->_updateStatus(false); if (parent && parent->getDocument() != document()->getDocument()) { - auto it = getTree()->DocumentMap.find(Application::Instance->getDocument(parent->getDocument())); - if (it != getTree()->DocumentMap.end()) + auto it = getTree()->DocumentMap.find( + Application::Instance->getDocument(parent->getDocument()) + ); + if (it != getTree()->DocumentMap.end()) { it->second->slotHighlightObject(obj, high, set, parent, subname); + } return; } FOREACH_ITEM(item, obj) - if (parent) { - App::DocumentObject* topParent = nullptr; - std::ostringstream ss; - item->getSubName(ss, topParent); - if (!topParent) { - if (parent != obj.getObject()) - continue; + if (parent) { + App::DocumentObject* topParent = nullptr; + std::ostringstream ss; + item->getSubName(ss, topParent); + if (!topParent) { + if (parent != obj.getObject()) { + continue; } } + } item->setHighlight(set, high); - if (parent) + if (parent) { return; + } END_FOREACH_ITEM } -static unsigned int countExpandedItem(const QTreeWidgetItem* item) { +static unsigned int countExpandedItem(const QTreeWidgetItem* item) +{ unsigned int size = 0; for (int i = 0, count = item->childCount(); i < count; ++i) { auto citem = item->child(i); - if (citem->type() != TreeWidget::ObjectType || !citem->isExpanded()) + if (citem->type() != TreeWidget::ObjectType || !citem->isExpanded()) { continue; + } auto obj = static_cast(citem)->object()->getObject(); - if (obj->isAttachedToDocument()) + if (obj->isAttachedToDocument()) { size += strlen(obj->getNameInDocument()) + countExpandedItem(citem); + } } return size; } -unsigned int DocumentItem::getMemSize() const { +unsigned int DocumentItem::getMemSize() const +{ return countExpandedItem(this); } -static void saveExpandedItem(Base::Writer& writer, const QTreeWidgetItem* item) { +static void saveExpandedItem(Base::Writer& writer, const QTreeWidgetItem* item) +{ int itemCount = 0; for (int i = 0, count = item->childCount(); i < count; ++i) { auto citem = item->child(i); - if (citem->type() != TreeWidget::ObjectType || !citem->isExpanded()) + if (citem->type() != TreeWidget::ObjectType || !citem->isExpanded()) { continue; + } auto obj = static_cast(citem)->object()->getObject(); - if (obj->isAttachedToDocument()) + if (obj->isAttachedToDocument()) { ++itemCount; + } } if (!itemCount) { @@ -4628,12 +5164,12 @@ static void saveExpandedItem(Base::Writer& writer, const QTreeWidgetItem* item) writer.incInd(); for (int i = 0, count = item->childCount(); i < count; ++i) { auto citem = item->child(i); - if (citem->type() != TreeWidget::ObjectType || !citem->isExpanded()) + if (citem->type() != TreeWidget::ObjectType || !citem->isExpanded()) { continue; + } auto obj = static_cast(citem)->object()->getObject(); if (obj->isAttachedToDocument()) { - writer.Stream() << writer.ind() << "getNameInDocument() << "\""; + writer.Stream() << writer.ind() << "getNameInDocument() << "\""; saveExpandedItem(writer, static_cast(citem)); } } @@ -4641,149 +5177,180 @@ static void saveExpandedItem(Base::Writer& writer, const QTreeWidgetItem* item) writer.Stream() << writer.ind() << "" << std::endl; } -void DocumentItem::Save(Base::Writer& writer) const { +void DocumentItem::Save(Base::Writer& writer) const +{ writer.Stream() << writer.ind() << "restore(reader); for (auto inst : TreeWidget::Instances) { if (inst != getTree()) { auto docItem = inst->getDocumentItem(document()); - if (docItem) + if (docItem) { docItem->_ExpandInfo = _ExpandInfo; + } } } } -void DocumentItem::restoreItemExpansion(const ExpandInfoPtr& info, DocumentObjectItem* item) { +void DocumentItem::restoreItemExpansion(const ExpandInfoPtr& info, DocumentObjectItem* item) +{ item->setExpanded(true); - if (!info) + if (!info) { return; + } for (int i = 0, count = item->childCount(); i < count; ++i) { auto citem = item->child(i); - if (citem->type() != TreeWidget::ObjectType) + if (citem->type() != TreeWidget::ObjectType) { continue; + } auto obj = static_cast(citem)->object()->getObject(); - if (!obj->isAttachedToDocument()) + if (!obj->isAttachedToDocument()) { continue; + } auto it = info->find(obj->getNameInDocument()); - if (it != info->end()) + if (it != info->end()) { restoreItemExpansion(it->second, static_cast(citem)); + } } } -void DocumentItem::slotExpandObject(const Gui::ViewProviderDocumentObject& obj, - const Gui::TreeItemMode& mode, const App::DocumentObject* parent, const char* subname) +void DocumentItem::slotExpandObject( + const Gui::ViewProviderDocumentObject& obj, + const Gui::TreeItemMode& mode, + const App::DocumentObject* parent, + const char* subname +) { getTree()->_updateStatus(false); - if ((mode == TreeItemMode::ExpandItem || - mode == TreeItemMode::ExpandPath) && - obj.getDocument()->getDocument()->testStatus(App::Document::Restoring)) { - if (!_ExpandInfo) + if ((mode == TreeItemMode::ExpandItem || mode == TreeItemMode::ExpandPath) + && obj.getDocument()->getDocument()->testStatus(App::Document::Restoring)) { + if (!_ExpandInfo) { _ExpandInfo.reset(new ExpandInfo); + } _ExpandInfo->emplace(std::string("*") + obj.getObject()->getNameInDocument(), ExpandInfoPtr()); return; } if (parent && parent->getDocument() != document()->getDocument()) { - auto it = getTree()->DocumentMap.find(Application::Instance->getDocument(parent->getDocument())); - if (it != getTree()->DocumentMap.end()) + auto it = getTree()->DocumentMap.find( + Application::Instance->getDocument(parent->getDocument()) + ); + if (it != getTree()->DocumentMap.end()) { it->second->slotExpandObject(obj, mode, parent, subname); + } return; } FOREACH_ITEM(item, obj) - // All document object items must always have a parent, either another - // object item or document item. If not, then there is a bug somewhere - // else. - assert(item->parent()); + // All document object items must always have a parent, either another + // object item or document item. If not, then there is a bug somewhere + // else. + assert(item->parent()); switch (mode) { - case TreeItemMode::ExpandPath: - if (!parent) { - QTreeWidgetItem* parentItem = item->parent(); - while (parentItem) { - parentItem->setExpanded(true); - parentItem = parentItem->parent(); - } - item->setExpanded(true); - break; - } - // fall through - case TreeItemMode::ExpandItem: - if (!parent) { - if (item->parent()->isExpanded()) + case TreeItemMode::ExpandPath: + if (!parent) { + QTreeWidgetItem* parentItem = item->parent(); + while (parentItem) { + parentItem->setExpanded(true); + parentItem = parentItem->parent(); + } item->setExpanded(true); - } - else { - App::DocumentObject* topParent = nullptr; - std::ostringstream ss; - item->getSubName(ss, topParent); - if (!topParent) { - if (parent != obj.getObject()) - continue; + break; } - else if (topParent != parent) - continue; - showItem(item, false, true); - item->setExpanded(true); - } - break; - case TreeItemMode::CollapseItem: - item->setExpanded(false); - break; - case TreeItemMode::ToggleItem: - if (item->isExpanded()) + // fall through + case TreeItemMode::ExpandItem: + if (!parent) { + if (item->parent()->isExpanded()) { + item->setExpanded(true); + } + } + else { + App::DocumentObject* topParent = nullptr; + std::ostringstream ss; + item->getSubName(ss, topParent); + if (!topParent) { + if (parent != obj.getObject()) { + continue; + } + } + else if (topParent != parent) { + continue; + } + showItem(item, false, true); + item->setExpanded(true); + } + break; + case TreeItemMode::CollapseItem: item->setExpanded(false); - else - item->setExpanded(true); - break; + break; + case TreeItemMode::ToggleItem: + if (item->isExpanded()) { + item->setExpanded(false); + } + else { + item->setExpanded(true); + } + break; - default: - break; + default: + break; } - if (item->isExpanded()) + if (item->isExpanded()) { populateItem(item); - if (parent) + } + if (parent) { return; + } END_FOREACH_ITEM } void DocumentItem::slotScrollToObject(const Gui::ViewProviderDocumentObject& obj) { - if (!obj.getObject() || !obj.getObject()->isAttachedToDocument()) + if (!obj.getObject() || !obj.getObject()->isAttachedToDocument()) { return; + } auto it = ObjectMap.find(obj.getObject()); - if (it == ObjectMap.end() || it->second->items.empty()) + if (it == ObjectMap.end() || it->second->items.empty()) { return; + } auto item = it->second->rootItem; - if (!item) + if (!item) { item = *it->second->items.begin(); + } getTree()->_updateStatus(false); getTree()->scrollToItem(item); } -void DocumentItem::slotRecomputedObject(const App::DocumentObject& obj) { - if (obj.isValid()) +void DocumentItem::slotRecomputedObject(const App::DocumentObject& obj) +{ + if (obj.isValid()) { return; - slotRecomputed(*obj.getDocument(), { const_cast(&obj) }); + } + slotRecomputed(*obj.getDocument(), {const_cast(&obj)}); } -void DocumentItem::slotRecomputed(const App::Document&, const std::vector& objs) { +void DocumentItem::slotRecomputed(const App::Document&, const std::vector& objs) +{ auto tree = getTree(); for (auto obj : objs) { - if (!obj->isValid()) + if (!obj->isValid()) { tree->ChangedObjects[obj].set(TreeWidget::CS_Error); + } } - if (!tree->ChangedObjects.empty()) + if (!tree->ChangedObjects.empty()) { tree->_updateStatus(); + } } Gui::Document* DocumentItem::document() const @@ -4793,8 +5360,9 @@ Gui::Document* DocumentItem::document() const void DocumentItem::testStatus() { - for (const auto& v : ObjectMap) + for (const auto& v : ObjectMap) { v.second->testStatus(); + } } void DocumentItem::setData(int column, int role, const QVariant& value) @@ -4814,10 +5382,12 @@ void DocumentItem::clearSelection(DocumentObjectItem* exclude) FOREACH_ITEM_ALL(item); _v.second->dirtyFlag = false; if (item == exclude) { - if (item->selected > 0) + if (item->selected > 0) { item->selected = -1; - else + } + else { item->selected = 0; + } updateItemSelection(item); // The set has been changed while calling updateItemSelection // so that the iterator has become invalid -> Abort @@ -4835,7 +5405,8 @@ void DocumentItem::clearSelection(DocumentObjectItem* exclude) treeWidget()->blockSignals(ok); } -void DocumentItem::updateSelection(QTreeWidgetItem* ti, bool unselect) { +void DocumentItem::updateSelection(QTreeWidgetItem* ti, bool unselect) +{ for (int i = 0, count = ti->childCount(); i < count; ++i) { auto child = ti->child(i); if (child && child->type() == TreeWidget::ObjectType) { @@ -4854,10 +5425,12 @@ void DocumentItem::updateSelection(QTreeWidgetItem* ti, bool unselect) { } } - if (unselect) + if (unselect) { return; - for (int i = 0, count = ti->childCount(); i < count; ++i) + } + for (int i = 0, count = ti->childCount(); i < count; ++i) { updateSelection(ti->child(i)); + } } void DocumentItem::updateItemSelection(DocumentObjectItem* item) @@ -4870,29 +5443,34 @@ void DocumentItem::updateItemSelection(DocumentObjectItem* item) bool selected = item->isSelected(); bool checked = item->checkState(0) == Qt::Checked; - if (selected && !checked) + if (selected && !checked) { item->setCheckState(true); + } - if (!selected && checked) + if (!selected && checked) { item->setCheckState(false); + } if ((selected && item->selected > 0) || (!selected && !item->selected)) { return; } - if (item->selected != -1) + if (item->selected != -1) { item->mySubs.clear(); + } item->selected = selected; auto obj = item->object()->getObject(); - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return; + } std::ostringstream str; App::DocumentObject* topParent = nullptr; item->getSubName(str, topParent); if (topParent) { - if (!obj->redirectSubName(str, topParent, nullptr)) + if (!obj->redirectSubName(str, topParent, nullptr)) { str << obj->getNameInDocument() << '.'; + } obj = topParent; } const char* objname = obj->getNameInDocument(); @@ -4935,21 +5513,25 @@ void DocumentItem::updateItemSelection(DocumentObjectItem* item) getTree()->syncView(vobj); } -App::DocumentObject* DocumentItem::getTopParent(App::DocumentObject* obj, std::string& subname) { +App::DocumentObject* DocumentItem::getTopParent(App::DocumentObject* obj, std::string& subname) +{ auto it = ObjectMap.find(obj); - if (it == ObjectMap.end() || it->second->items.empty()) + if (it == ObjectMap.end() || it->second->items.empty()) { return nullptr; + } // already a top parent - if (it->second->rootItem) + if (it->second->rootItem) { return obj; + } for (auto item : it->second->items) { // non group object do not provide a coordinate system, hence its // claimed child is still in the global coordinate space, so the // child can still be considered a top level object - if (!item->isParentGroup()) + if (!item->isParentGroup()) { return obj; + } } // If no top level item, find an item that is closest to the top level @@ -4957,8 +5539,9 @@ App::DocumentObject* DocumentItem::getTopParent(App::DocumentObject* obj, std::s for (auto item : it->second->items) { int i = 0; for (auto parent = item->parent(); parent; ++i, parent = parent->parent()) { - if (parent->isHidden()) + if (parent->isHidden()) { i += 1000; + } ++i; } items.emplace(i, item); @@ -4973,13 +5556,15 @@ App::DocumentObject* DocumentItem::getTopParent(App::DocumentObject* obj, std::s return obj; } ss << obj->getNameInDocument() << '.' << subname; - FC_LOG("Subname correction " << obj->getFullName() << '.' << subname - << " -> " << topParent->getFullName() << '.' << ss.str()); + FC_LOG( + "Subname correction " << obj->getFullName() << '.' << subname << " -> " + << topParent->getFullName() << '.' << ss.str() + ); subname = ss.str(); return topParent; } -DocumentObjectItem *DocumentItem::findItem(App::DocumentObject* obj, const std::string& subname) const +DocumentObjectItem* DocumentItem::findItem(App::DocumentObject* obj, const std::string& subname) const { auto it = ObjectMap.find(obj); if (it == ObjectMap.end()) { @@ -5013,48 +5598,63 @@ DocumentObjectItem *DocumentItem::findItem(App::DocumentObject* obj, const std:: } DocumentObjectItem* DocumentItem::findItemByObject( - bool sync, App::DocumentObject* obj, const char* subname, bool select) + bool sync, + App::DocumentObject* obj, + const char* subname, + bool select +) { - if (!subname) + if (!subname) { subname = ""; + } auto it = ObjectMap.find(obj); - if (it == ObjectMap.end() || it->second->items.empty()) + if (it == ObjectMap.end() || it->second->items.empty()) { return nullptr; + } // prefer top level item of this object - if (it->second->rootItem) + if (it->second->rootItem) { return findItem(sync, it->second->rootItem, subname, select); + } for (auto item : it->second->items) { // non group object do not provide a coordinate system, hence its // claimed child is still in the global coordinate space, so the // child can still be considered a top level object - if (!item->isParentGroup()) + if (!item->isParentGroup()) { return findItem(sync, item, subname, select); + } } // If no top level item, find an item that is closest to the top level std::multimap items; for (auto item : it->second->items) { int i = 0; - for (auto parent = item->parent(); parent; ++i, parent = parent->parent()) + for (auto parent = item->parent(); parent; ++i, parent = parent->parent()) { ++i; + } items.emplace(i, item); } for (auto& v : items) { auto item = findItem(sync, v.second, subname, select); - if (item) + if (item) { return item; + } } return nullptr; } DocumentObjectItem* DocumentItem::findItem( - bool sync, DocumentObjectItem* item, const char* subname, bool select) + bool sync, + DocumentObjectItem* item, + const char* subname, + bool select +) { - if (item->isHidden()) + if (item->isHidden()) { item->setHidden(false); + } if (!subname || *subname == 0) { if (select) { @@ -5069,8 +5669,9 @@ DocumentObjectItem* DocumentItem::findItem( // try to find the next level object name const char* nextsub = nullptr; const char* dot = nullptr; - if ((dot = strchr(subname, '.'))) + if ((dot = strchr(subname, '.'))) { nextsub = dot + 1; + } else { if (select) { item->selected += 2; @@ -5085,32 +5686,38 @@ DocumentObjectItem* DocumentItem::findItem( auto obj = item->object()->getObject(); auto subObj = obj->getSubObject(name.c_str()); if (!subObj || subObj == obj) { - if (!subObj && !getTree()->searchDoc) + if (!subObj && !getTree()->searchDoc) { TREE_LOG("sub object not found " << item->getName() << '.' << name.c_str()); + } if (select) { item->selected += 2; - if (std::ranges::find(item->mySubs, subname) == item->mySubs.end()) + if (std::ranges::find(item->mySubs, subname) == item->mySubs.end()) { item->mySubs.emplace_back(subname); + } } return item; } - if (select) + if (select) { item->mySubs.clear(); + } if (!item->populated && sync) { - //force populate the item + // force populate the item item->populated = true; populateItem(item, true); } for (int i = 0, count = item->childCount(); i < count; ++i) { auto ti = item->child(i); - if (!ti || ti->type() != TreeWidget::ObjectType) continue; + if (!ti || ti->type() != TreeWidget::ObjectType) { + continue; + } auto child = static_cast(ti); - if (child->object()->getObject() == subObj) + if (child->object()->getObject() == subObj) { return findItem(sync, child, nextsub, select); + } } // The sub object is not found. This could happen for geo group, since its @@ -5123,8 +5730,9 @@ DocumentObjectItem* DocumentItem::findItem( if (child->isChildOfItem(item)) { found = true; res = findItem(sync, child, nextsub, select); - if (!select) + if (!select) { return res; + } } } } @@ -5134,75 +5742,87 @@ DocumentObjectItem* DocumentItem::findItem( // Select the current object instead. TREE_TRACE("element " << subname << " not found"); item->selected += 2; - if (std::ranges::find(item->mySubs, subname) == item->mySubs.end()) + if (std::ranges::find(item->mySubs, subname) == item->mySubs.end()) { item->mySubs.emplace_back(subname); + } } return res; } -void DocumentItem::selectItems(SelectionReason reason) { - const auto& sels = Selection().getSelection(pDocument->getDocument()->getName(), ResolveMode::NoResolve); +void DocumentItem::selectItems(SelectionReason reason) +{ + const auto& sels + = Selection().getSelection(pDocument->getDocument()->getName(), ResolveMode::NoResolve); bool sync = (sels.size() > 50 || reason == SR_SELECT) ? false : true; - for (const auto& sel : sels) + for (const auto& sel : sels) { findItemByObject(sync, sel.pObject, sel.SubName, true); + } DocumentObjectItem* newSelect = nullptr; DocumentObjectItem* oldSelect = nullptr; FOREACH_ITEM_ALL(item) - if (item->selected == 1) { - // this means it is the old selection and is not in the current - // selection - item->selected = 0; - item->mySubs.clear(); - item->setSelected(false); - item->setCheckState(false); - } - else if (item->selected) { - if (sync) { - if (item->selected == 2 && showItem(item, false, reason == SR_FORCE_EXPAND)) { - // This means newly selected and can auto expand - if (!newSelect) - newSelect = item; - } - if (!newSelect && !oldSelect && !item->isHidden()) { - bool visible = true; - for (auto parent = item->parent(); parent; parent = parent->parent()) { - if (!parent->isExpanded() || parent->isHidden()) { - visible = false; - break; - } - } - if (visible) - oldSelect = item; + if (item->selected == 1) { + // this means it is the old selection and is not in the current + // selection + item->selected = 0; + item->mySubs.clear(); + item->setSelected(false); + item->setCheckState(false); + } + else if (item->selected) { + if (sync) { + if (item->selected == 2 && showItem(item, false, reason == SR_FORCE_EXPAND)) { + // This means newly selected and can auto expand + if (!newSelect) { + newSelect = item; + } + } + if (!newSelect && !oldSelect && !item->isHidden()) { + bool visible = true; + for (auto parent = item->parent(); parent; parent = parent->parent()) { + if (!parent->isExpanded() || parent->isHidden()) { + visible = false; + break; + } + } + if (visible) { + oldSelect = item; } } - item->selected = 1; - item->setSelected(true); - item->setCheckState(true); } + item->selected = 1; + item->setSelected(true); + item->setCheckState(true); + } END_FOREACH_ITEM; if (sync) { - if (!newSelect) + if (!newSelect) { newSelect = oldSelect; - else + } + else { getTree()->syncView(newSelect->object()); - if (newSelect) + } + if (newSelect) { getTree()->scrollToItem(newSelect); + } } } -void DocumentItem::populateParents(const ViewProvider* vp, ViewParentMap& parentMap) { +void DocumentItem::populateParents(const ViewProvider* vp, ViewParentMap& parentMap) +{ auto it = parentMap.find(vp); - if (it == parentMap.end()) + if (it == parentMap.end()) { return; + } for (auto parent : it->second) { auto it = ObjectMap.find(parent->getObject()); - if (it == ObjectMap.end()) + if (it == ObjectMap.end()) { continue; + } populateParents(parent, parentMap); for (auto item : it->second->items) { @@ -5214,11 +5834,13 @@ void DocumentItem::populateParents(const ViewProvider* vp, ViewParentMap& parent } } -void DocumentItem::selectAllInstances(const ViewProviderDocumentObject& vpd) { +void DocumentItem::selectAllInstances(const ViewProviderDocumentObject& vpd) +{ ViewParentMap parentMap; auto pObject = vpd.getObject(); - if (ObjectMap.find(pObject) == ObjectMap.end()) + if (ObjectMap.find(pObject) == ObjectMap.end()) { return; + } bool lock = getTree()->blockSelection(true); @@ -5227,10 +5849,14 @@ void DocumentItem::selectAllInstances(const ViewProviderDocumentObject& vpd) { // // Build a map of object to all its parent for (auto& v : ObjectMap) { - if (v.second->viewObject == &vpd) continue; + if (v.second->viewObject == &vpd) { + continue; + } for (auto child : v.second->viewObject->claimChildren()) { auto vp = getViewProvider(child); - if (!vp) continue; + if (!vp) { + continue; + } parentMap[vp].push_back(v.second->viewObject); } } @@ -5241,8 +5867,9 @@ void DocumentItem::selectAllInstances(const ViewProviderDocumentObject& vpd) { DocumentObjectItem* first = nullptr; FOREACH_ITEM(item, vpd); - if (showItem(item, true) && !first) + if (showItem(item, true) && !first) { first = item; + } END_FOREACH_ITEM; getTree()->blockSelection(lock); @@ -5252,33 +5879,41 @@ void DocumentItem::selectAllInstances(const ViewProviderDocumentObject& vpd) { } } -bool DocumentItem::showHidden() const { +bool DocumentItem::showHidden() const +{ return pDocument->getDocument()->ShowHidden.getValue(); } -void DocumentItem::setShowHidden(bool show) { +void DocumentItem::setShowHidden(bool show) +{ pDocument->getDocument()->ShowHidden.setValue(show); } -bool DocumentItem::showItem(DocumentObjectItem* item, bool select, bool force) { +bool DocumentItem::showItem(DocumentObjectItem* item, bool select, bool force) +{ auto parent = item->parent(); if (item->isHidden()) { - if (!force) + if (!force) { return false; + } item->setHidden(false); } if (parent->type() == TreeWidget::ObjectType) { - if (!showItem(static_cast(parent), false)) + if (!showItem(static_cast(parent), false)) { return false; + } auto pitem = static_cast(parent); - if (force || !pitem->object()->getObject()->testStatus(App::NoAutoExpand)) + if (force || !pitem->object()->getObject()->testStatus(App::NoAutoExpand)) { parent->setExpanded(true); - else if (!select) + } + else if (!select) { return false; + } } - else + else { parent->setExpanded(true); + } if (select) { item->setSelected(true); @@ -5287,16 +5922,19 @@ bool DocumentItem::showItem(DocumentObjectItem* item, bool select, bool force) { return true; } -void DocumentItem::updateItemsVisibility(QTreeWidgetItem* item, bool show) { +void DocumentItem::updateItemsVisibility(QTreeWidgetItem* item, bool show) +{ if (item->type() == TreeWidget::ObjectType) { auto objitem = static_cast(item); objitem->setHidden(!show && !objitem->object()->showInTree()); } - for (int i = 0; i < item->childCount(); ++i) + for (int i = 0; i < item->childCount(); ++i) { updateItemsVisibility(item->child(i), show); + } } -void DocumentItem::updateSelection() { +void DocumentItem::updateSelection() +{ bool lock = getTree()->blockSelection(true); updateSelection(this, false); getTree()->blockSelection(lock); @@ -5308,7 +5946,11 @@ static int countItems; DocumentObjectItem::DocumentObjectItem(DocumentItem* ownerDocItem, DocumentObjectDataPtr data) : QTreeWidgetItem(TreeWidget::ObjectType) - , myOwner(ownerDocItem), myData(data), previousStatus(-1), selected(0), populated(false) + , myOwner(ownerDocItem) + , myData(data) + , previousStatus(-1) + , selected(0) + , populated(false) { setFlags(flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable); setCheckState(false); @@ -5324,8 +5966,9 @@ DocumentObjectItem::~DocumentObjectItem() TREE_LOG("Delete item: " << countItems << ", " << object()->getObject()->getFullName()); myData->removeItem(this); - if (myData->rootItem == this) + if (myData->rootItem == this) { myData->rootItem = nullptr; + } if (myOwner && myData->items.empty()) { auto it = myOwner->_ParentMap.find(object()->getObject()); @@ -5336,69 +5979,74 @@ DocumentObjectItem::~DocumentObjectItem() } } -void DocumentObjectItem::restoreBackground() { +void DocumentObjectItem::restoreBackground() +{ this->setBackground(0, this->bgBrush); } -void DocumentObjectItem::setHighlight(bool set, Gui::HighlightMode high) { +void DocumentObjectItem::setHighlight(bool set, Gui::HighlightMode high) +{ QFont f = this->font(0); auto highlight = [this, set](const QColor& col) { - if (set) + if (set) { this->setBackground(0, col); - else + } + else { this->setBackground(0, QBrush()); + } this->bgBrush = this->background(0); }; switch (high) { - case HighlightMode::Bold: - f.setBold(set); - break; - case HighlightMode::Italic: - f.setItalic(set); - break; - case HighlightMode::Underlined: - f.setUnderline(set); - break; - case HighlightMode::Overlined: - f.setOverline(set); - break; - case HighlightMode::StrikeOut: - f.setStrikeOut(set); - break; - case HighlightMode::Blue: - highlight(QColor(200, 200, 255)); - break; - case HighlightMode::LightBlue: - highlight(QColor(230, 230, 255)); - break; - case HighlightMode::UserDefined: - { - QColor color(230, 230, 255); - if (set) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/TreeView"); - bool bold = hGrp->GetBool("TreeActiveBold", true); - bool italic = hGrp->GetBool("TreeActiveItalic", false); - bool underlined = hGrp->GetBool("TreeActiveUnderlined", false); - bool overlined = hGrp->GetBool("TreeActiveOverlined", false); - f.setBold(bold); - f.setItalic(italic); - f.setUnderline(underlined); - f.setOverline(overlined); + case HighlightMode::Bold: + f.setBold(set); + break; + case HighlightMode::Italic: + f.setItalic(set); + break; + case HighlightMode::Underlined: + f.setUnderline(set); + break; + case HighlightMode::Overlined: + f.setOverline(set); + break; + case HighlightMode::StrikeOut: + f.setStrikeOut(set); + break; + case HighlightMode::Blue: + highlight(QColor(200, 200, 255)); + break; + case HighlightMode::LightBlue: + highlight(QColor(230, 230, 255)); + break; + case HighlightMode::UserDefined: { + QColor color(230, 230, 255); + if (set) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/TreeView" + ); + bool bold = hGrp->GetBool("TreeActiveBold", true); + bool italic = hGrp->GetBool("TreeActiveItalic", false); + bool underlined = hGrp->GetBool("TreeActiveUnderlined", false); + bool overlined = hGrp->GetBool("TreeActiveOverlined", false); + f.setBold(bold); + f.setItalic(italic); + f.setUnderline(underlined); + f.setOverline(overlined); - unsigned long col = hGrp->GetUnsigned("TreeActiveColor", 1538528255); - color = Base::Color::fromPackedRGB(col); - } - else { - f.setBold(false); - f.setItalic(false); - f.setUnderline(false); - f.setOverline(false); - } - highlight(color); - } break; - default: - break; + unsigned long col = hGrp->GetUnsigned("TreeActiveColor", 1538528255); + color = Base::Color::fromPackedRGB(col); + } + else { + f.setBold(false); + f.setItalic(false); + f.setUnderline(false); + f.setOverline(false); + } + highlight(color); + } break; + default: + break; } this->setFont(0, f); } @@ -5419,8 +6067,10 @@ void DocumentObjectItem::testStatus(bool resetStatus) testStatus(resetStatus, icon, icon2); } -namespace { -enum Status { +namespace +{ +enum Status +{ Visible = 1 << 0, Recompute = 1 << 1, Error = 1 << 2, @@ -5445,8 +6095,9 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 Timing(testStatus1); auto parent = parentItem->object()->getObject(); auto ext = parent->getExtensionByType(true, false); - if (!ext) + if (!ext) { visible = parent->isElementVisible(pObject->getNameInDocument()); + } else { // We are dealing with a plain group. It has special handling when // linked, which allows it to have indpenedent visibility control. @@ -5464,27 +6115,25 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 Timing(testStatus2); - if (visible < 0) + if (visible < 0) { visible = object()->isShow() ? 1 : 0; + } auto obj = object()->getObject(); auto linked = obj->getLinkedObject(false); - bool external = object()->getDocument() != getOwnerDocument()->document() || - (linked && linked->getDocument() != obj->getDocument()); + bool external = object()->getDocument() != getOwnerDocument()->document() + || (linked && linked->getDocument() != obj->getDocument()); bool freezed = pObject->isFreezed(); - int currentStatus = - ((freezed ? 1 : 0) << 5) | - ((external ? 1 : 0) << 4) | - ((object()->showInTree() ? 0 : 1) << 3) | - ((pObject->isError() ? 1 : 0) << 2) | - ((pObject->isTouched() || pObject->mustExecute() == 1 ? 1 : 0) << 1) | - (visible ? 1 : 0); + int currentStatus = ((freezed ? 1 : 0) << 5) | ((external ? 1 : 0) << 4) + | ((object()->showInTree() ? 0 : 1) << 3) | ((pObject->isError() ? 1 : 0) << 2) + | ((pObject->isTouched() || pObject->mustExecute() == 1 ? 1 : 0) << 1) | (visible ? 1 : 0); TimingStop(testStatus2); - if (!resetStatus && previousStatus == currentStatus) + if (!resetStatus && previousStatus == currentStatus) { return; + } _Timing(1, testStatus3); @@ -5504,11 +6153,12 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 this->setData(column, Qt::ForegroundRole, QVariant()); } } - else { // invisible + else { // invisible QStyleOptionViewItem opt; // it can happen that a tree item is not attached to the tree widget (#0003025) - if (this->treeWidget()) + if (this->treeWidget()) { opt.initFrom(this->treeWidget()); + } for (int column = 0; column < this->columnCount(); ++column) { this->setForeground(column, opt.palette.color(QPalette::Disabled, QPalette::Text)); } @@ -5542,7 +6192,7 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 // get the original icon set QIcon icon_org = object()->getIcon(); -#if QT_VERSION < QT_VERSION_CHECK(6,0,0) +#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) int w = getTree()->viewOptions().decorationSize.width(); #else QStyleOptionViewItem opt; @@ -5554,10 +6204,16 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 // if needed show small pixmap inside if (!px.isNull()) { - pxOff = BitmapFactory().merge(icon_org.pixmap(w, w, mode, QIcon::Off), - px, BitmapFactoryInst::TopRight); - pxOn = BitmapFactory().merge(icon_org.pixmap(w, w, mode, QIcon::On), - px, BitmapFactoryInst::TopRight); + pxOff = BitmapFactory().merge( + icon_org.pixmap(w, w, mode, QIcon::Off), + px, + BitmapFactoryInst::TopRight + ); + pxOn = BitmapFactory().merge( + icon_org.pixmap(w, w, mode, QIcon::On), + px, + BitmapFactoryInst::TopRight + ); } else { pxOff = icon_org.pixmap(w, w, mode, QIcon::Off); @@ -5577,8 +6233,7 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 static QPixmap pxExternal; constexpr int px = 12; if (pxExternal.isNull()) { - pxExternal = Gui::BitmapFactory().pixmapFromSvg("LinkOverlay", - QSize(px, px)); + pxExternal = Gui::BitmapFactory().pixmapFromSvg("LinkOverlay", QSize(px, px)); } pxOff = BitmapFactory().merge(pxOff, pxExternal, BitmapFactoryInst::BottomRight); pxOn = BitmapFactory().merge(pxOn, pxExternal, BitmapFactoryInst::BottomRight); @@ -5612,17 +6267,23 @@ void DocumentObjectItem::testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2 QIcon new_icon; auto style = this->getTree()->style(); int const spacing = style->pixelMetric(QStyle::PM_LayoutHorizontalSpacing); - for (auto state: {QIcon::On, QIcon::Off}) { + for (auto state : {QIcon::On, QIcon::Off}) { QPixmap px_org = icon.pixmap(0xFFFF, 0xFFFF, QIcon::Normal, state); - QPixmap px(2*px_org.width() + spacing, px_org.height()); + QPixmap px(2 * px_org.width() + spacing, px_org.height()); px.fill(Qt::transparent); QPainter pt; pt.begin(&px); pt.setPen(Qt::NoPen); if (object()->canToggleVisibility()) { - pt.drawPixmap(0, 0, px_org.width(), px_org.height(), (currentStatus & Status::Visible) ? pxVisible : pxInvisible); + pt.drawPixmap( + 0, + 0, + px_org.width(), + px_org.height(), + (currentStatus & Status::Visible) ? pxVisible : pxInvisible + ); } pt.drawPixmap(px_org.width() + spacing, 0, px_org.width(), px_org.height(), px_org); pt.end(); @@ -5643,14 +6304,16 @@ void DocumentObjectItem::displayStatusInfo() QString info = QApplication::translate(Obj->getTypeId().getName(), Obj->getStatusString()); - if (Obj->mustExecute() == 1 && !Obj->isError()) + if (Obj->mustExecute() == 1 && !Obj->isError()) { info += TreeWidget::tr(" (but must be executed)"); + } QString status = TreeWidget::tr("%1, Internal name: %2") - .arg(info, QString::fromLatin1(Obj->getNameInDocument())); + .arg(info, QString::fromLatin1(Obj->getNameInDocument())); - if (!Obj->isError()) + if (!Obj->isError()) { getMainWindow()->showMessage(status); + } else { getMainWindow()->showStatus(MainWindow::Err, status); QTreeWidget* tree = this->treeWidget(); @@ -5661,8 +6324,9 @@ void DocumentObjectItem::displayStatusInfo() void DocumentObjectItem::setExpandedStatus(bool on) { - if (getOwnerDocument()->document() == object()->getDocument()) + if (getOwnerDocument()->document() == object()->getDocument()) { object()->getObject()->setStatus(App::Expand, on); + } } void DocumentObjectItem::setData(int column, int role, const QVariant& value) @@ -5689,21 +6353,28 @@ void DocumentObjectItem::setData(int column, int role, const QVariant& value) bool DocumentObjectItem::isChildOfItem(DocumentObjectItem* item) { - for (auto pitem = parent(); pitem; pitem = pitem->parent()) - if (pitem == item) + for (auto pitem = parent(); pitem; pitem = pitem->parent()) { + if (pitem == item) { return true; + } + } return false; } -bool DocumentObjectItem::requiredAtRoot(bool excludeSelf) const { - if (myData->rootItem || object()->getDocument() != getOwnerDocument()->document()) +bool DocumentObjectItem::requiredAtRoot(bool excludeSelf) const +{ + if (myData->rootItem || object()->getDocument() != getOwnerDocument()->document()) { return false; + } bool checkMap = true; for (auto item : myData->items) { - if (excludeSelf && item == this) continue; + if (excludeSelf && item == this) { + continue; + } auto pi = item->getParentItem(); - if (!pi || pi->myData->removeChildrenFromRoot) + if (!pi || pi->myData->removeChildrenFromRoot) { return false; + } checkMap = false; } if (checkMap && myOwner) { @@ -5722,83 +6393,98 @@ bool DocumentObjectItem::requiredAtRoot(bool excludeSelf) const { // tree scroll to object command won't work properly. for (auto parent : it->second) { - if (getOwnerDocument()->populateObject(parent)) + if (getOwnerDocument()->populateObject(parent)) { return false; + } } } } return true; } -bool DocumentObjectItem::isLink() const { +bool DocumentObjectItem::isLink() const +{ auto obj = object()->getObject(); auto linked = obj->getLinkedObject(false); return linked && obj != linked; } -bool DocumentObjectItem::isLinkFinal() const { +bool DocumentObjectItem::isLinkFinal() const +{ auto obj = object()->getObject(); auto linked = obj->getLinkedObject(false); return linked && linked == linked->getLinkedObject(true); } -bool DocumentObjectItem::isParentLink() const { +bool DocumentObjectItem::isParentLink() const +{ auto pi = getParentItem(); return pi && pi->isLink(); } -enum GroupType { +enum GroupType +{ NotGroup = 0, LinkGroup = 1, PartGroup = 2, - SuperGroup = 3, //reversed for future + SuperGroup = 3, // reversed for future }; -int DocumentObjectItem::isGroup() const { +int DocumentObjectItem::isGroup() const +{ auto obj = object()->getObject(); auto linked = obj->getLinkedObject(true); - if (linked && linked->hasExtension( - App::GeoFeatureGroupExtension::getExtensionClassTypeId())) + if (linked && linked->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId())) { return PartGroup; - if (obj->hasChildElement()) + } + if (obj->hasChildElement()) { return LinkGroup; + } if (obj->hasExtension(App::GroupExtension::getExtensionClassTypeId(), false)) { for (auto parent = getParentItem(); parent; parent = parent->getParentItem()) { auto pobj = parent->object()->getObject(); - if (pobj->hasExtension(App::GroupExtension::getExtensionClassTypeId(), false)) + if (pobj->hasExtension(App::GroupExtension::getExtensionClassTypeId(), false)) { continue; - if (pobj->isElementVisible(obj->getNameInDocument()) >= 0) + } + if (pobj->isElementVisible(obj->getNameInDocument()) >= 0) { return LinkGroup; + } } } return NotGroup; } -bool DocumentItem::isObjectShowable(App::DocumentObject* obj) { +bool DocumentItem::isObjectShowable(App::DocumentObject* obj) +{ auto itParents = _ParentMap.find(obj); - if (itParents == _ParentMap.end() || itParents->second.empty()) + if (itParents == _ParentMap.end() || itParents->second.empty()) { return true; + } bool showable = true; for (auto parent : itParents->second) { - if (parent->getDocument() != obj->getDocument()) + if (parent->getDocument() != obj->getDocument()) { continue; - if (!parent->hasChildElement() - && parent->getLinkedObject(false) == parent) + } + if (!parent->hasChildElement() && parent->getLinkedObject(false) == parent) { return true; + } showable = false; } return showable; } -int DocumentObjectItem::isParentGroup() const { +int DocumentObjectItem::isParentGroup() const +{ auto pi = getParentItem(); return pi ? pi->isGroup() : 0; } -DocumentObjectItem* DocumentObjectItem::getParentItem() const { - if (parent()->type() != TreeWidget::ObjectType) +DocumentObjectItem* DocumentObjectItem::getParentItem() const +{ + if (parent()->type() != TreeWidget::ObjectType) { return nullptr; + } return static_cast(parent()); } @@ -5836,7 +6522,8 @@ DocumentObjectItem* DocumentObjectItem::getPreviousSibling() const return nullptr; } -const char* DocumentObjectItem::getName() const { +const char* DocumentObjectItem::getName() const +{ const char* name = object()->getObject()->getNameInDocument(); return name ? name : ""; } @@ -5844,8 +6531,9 @@ const char* DocumentObjectItem::getName() const { int DocumentObjectItem::getSubName(std::ostringstream& str, App::DocumentObject*& topParent) const { auto parent = getParentItem(); - if (!parent) + if (!parent) { return NotGroup; + } int ret = parent->getSubName(str, topParent); if (ret != SuperGroup) { int group = parent->isGroup(); @@ -5861,7 +6549,7 @@ int DocumentObjectItem::getSubName(std::ostringstream& str, App::DocumentObject* // non-group object 'PartExtrude', its following children should // not be grouped, so must reset any previous parents here. topParent = nullptr; - str.str(""); //reset the current subname + str.str(""); // reset the current subname return NotGroup; } group = PartGroup; @@ -5875,19 +6563,24 @@ int DocumentObjectItem::getSubName(std::ostringstream& str, App::DocumentObject* str.str(""); return NotGroup; } - if (!topParent) + if (!topParent) { topParent = obj; - else if (!obj->redirectSubName(str, topParent, object()->getObject())) + } + else if (!obj->redirectSubName(str, topParent, object()->getObject())) { str << obj->getNameInDocument() << '.'; + } return ret; } App::DocumentObject* DocumentObjectItem::getFullSubName( - std::ostringstream& str, DocumentObjectItem* parent) const + std::ostringstream& str, + DocumentObjectItem* parent +) const { auto pi = getParentItem(); - if (this == parent || !pi || (!parent && !pi->isGroup())) + if (this == parent || !pi || (!parent && !pi->isGroup())) { return object()->getObject(); + } auto ret = pi->getFullSubName(str, parent); str << getName() << '.'; @@ -5895,18 +6588,24 @@ App::DocumentObject* DocumentObjectItem::getFullSubName( } App::DocumentObject* DocumentObjectItem::getRelativeParent( - std::ostringstream& str, DocumentObjectItem* cousin, - App::DocumentObject** topParent, std::string* topSubname) const + std::ostringstream& str, + DocumentObjectItem* cousin, + App::DocumentObject** topParent, + std::string* topSubname +) const { std::ostringstream str2; - App::DocumentObject* top = nullptr, * top2 = nullptr; + App::DocumentObject *top = nullptr, *top2 = nullptr; getSubName(str, top); - if (topParent) + if (topParent) { *topParent = top; - if (!top) + } + if (!top) { return nullptr; - if (topSubname) + } + if (topSubname) { *topSubname = str.str() + getName() + '.'; + } cousin->getSubName(str2, top2); if (top != top2) { str << getName() << '.'; @@ -5943,22 +6642,28 @@ App::DocumentObject* DocumentObjectItem::getRelativeParent( return nullptr; } -void DocumentObjectItem::setCheckState(bool checked) { - if (isSelectionCheckBoxesEnabled()) +void DocumentObjectItem::setCheckState(bool checked) +{ + if (isSelectionCheckBoxesEnabled()) { QTreeWidgetItem::setCheckState(0, checked ? Qt::Checked : Qt::Unchecked); - else + } + else { setData(0, Qt::CheckStateRole, QVariant()); + } } -DocumentItem* DocumentObjectItem::getParentDocument() const { +DocumentItem* DocumentObjectItem::getParentDocument() const +{ return getTree()->getDocumentItem(object()->getDocument()); } -DocumentItem* DocumentObjectItem::getOwnerDocument() const { +DocumentItem* DocumentObjectItem::getOwnerDocument() const +{ return myOwner; } -TreeWidget* DocumentObjectItem::getTree() const { +TreeWidget* DocumentObjectItem::getTree() const +{ return static_cast(treeWidget()); } @@ -5971,7 +6676,10 @@ void DocumentObjectItem::getExpandedSnapshot(std::vector& snapshot) const } } -void DocumentObjectItem::applyExpandedSnapshot(const std::vector& snapshot, std::vector::const_iterator& from) +void DocumentObjectItem::applyExpandedSnapshot( + const std::vector& snapshot, + std::vector::const_iterator& from +) { setExpanded(*from++); @@ -5981,4 +6689,3 @@ void DocumentObjectItem::applyExpandedSnapshot(const std::vector& snapshot } #include "moc_Tree.cpp" - diff --git a/src/Gui/Tree.h b/src/Gui/Tree.h index dbcf0da88e..741adf7768 100644 --- a/src/Gui/Tree.h +++ b/src/Gui/Tree.h @@ -39,7 +39,8 @@ class QLineEdit; -namespace Gui { +namespace Gui +{ class TreeParams; class ViewProviderDocumentObject; @@ -56,19 +57,19 @@ GuiExport bool isTreeViewDragging(); /** Tree view that allows drag & drop of document objects. * @author Werner Mayer */ -class TreeWidget : public QTreeWidget, public SelectionObserver +class TreeWidget: public QTreeWidget, public SelectionObserver { Q_OBJECT public: - explicit TreeWidget(const char *name, QWidget* parent=nullptr); + explicit TreeWidget(const char* name, QWidget* parent = nullptr); ~TreeWidget() override; - static void setupResizableColumn(TreeWidget *tree=nullptr); + static void setupResizableColumn(TreeWidget* tree = nullptr); static void scrollItemToTop(); - void selectAllInstances(const ViewProviderDocumentObject &vpd); - void selectLinkedObject(App::DocumentObject *linked); - void selectAllLinks(App::DocumentObject *obj); + void selectAllInstances(const ViewProviderDocumentObject& vpd); + void selectLinkedObject(App::DocumentObject* linked); + void selectAllLinks(App::DocumentObject* obj); void expandSelectedItems(TreeItemMode mode); static int iconSize(); @@ -78,75 +79,81 @@ public: int itemSpacing() const; void setItemSpacing(int); - bool eventFilter(QObject *, QEvent *ev) override; + bool eventFilter(QObject*, QEvent* ev) override; - struct SelInfo { - App::DocumentObject *topParent; + struct SelInfo + { + App::DocumentObject* topParent; std::string subname; - ViewProviderDocumentObject *parentVp; - ViewProviderDocumentObject *vp; + ViewProviderDocumentObject* parentVp; + ViewProviderDocumentObject* vp; }; /* Return a list of selected object of a give document and their parent * * This function can return the non-group parent of the selected object, * which Gui::Selection() cannot provide. */ - static std::vector getSelection(App::Document *doc=nullptr); + static std::vector getSelection(App::Document* doc = nullptr); static std::vector getSelectedDocuments(); - static TreeWidget *instance(); + static TreeWidget* instance(); static const int DocumentType; static const int ObjectType; - void markItem(const App::DocumentObject* Obj,bool mark); - void syncView(ViewProviderDocumentObject *vp); + void markItem(const App::DocumentObject* Obj, bool mark); + void syncView(ViewProviderDocumentObject* vp); void selectAll() override; - const char *getTreeName() const; + const char* getTreeName() const; - static void updateStatus(bool delay=true); + static void updateStatus(bool delay = true); - static bool isObjectShowable(App::DocumentObject *obj); + static bool isObjectShowable(App::DocumentObject* obj); // Check if obj can be considered as a top level object - static void checkTopParent(App::DocumentObject *&obj, std::string &subname); + static void checkTopParent(App::DocumentObject*& obj, std::string& subname); - DocumentItem *getDocumentItem(const Gui::Document *) const; + DocumentItem* getDocumentItem(const Gui::Document*) const; - static Gui::Document *selectedDocument(); + static Gui::Document* selectedDocument(); void startDragging(); void resetItemSearch(); void startItemSearch(QLineEdit*); - void itemSearch(const QString &text, bool select); + void itemSearch(const QString& text, bool select); static void synchronizeSelectionCheckBoxes(); static void updateVisibilityIcons(); - QList childrenOfItem(const QTreeWidgetItem &item) const; + QList childrenOfItem(const QTreeWidgetItem& item) const; protected: /// Observer message from the Selection void onSelectionChanged(const SelectionChanges& msg) override; - void contextMenuEvent (QContextMenuEvent * e) override; - void drawRow(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const override; + void contextMenuEvent(QContextMenuEvent* e) override; + void drawRow(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const override; /** @name Drag and drop */ //@{ void startDrag(Qt::DropActions supportedActions) override; - bool dropMimeData(QTreeWidgetItem *parent, int index, const QMimeData *data, - Qt::DropAction action) override; - Qt::DropActions supportedDropActions () const override; - void dragEnterEvent(QDragEnterEvent * event) override; - void dragLeaveEvent(QDragLeaveEvent * event) override; - void dragMoveEvent(QDragMoveEvent *event) override; - void dropEvent(QDropEvent *event) override; + bool dropMimeData( + QTreeWidgetItem* parent, + int index, + const QMimeData* data, + Qt::DropAction action + ) override; + Qt::DropActions supportedDropActions() const override; + void dragEnterEvent(QDragEnterEvent* event) override; + void dragLeaveEvent(QDragLeaveEvent* event) override; + void dragMoveEvent(QDragMoveEvent* event) override; + void dropEvent(QDropEvent* event) override; private: - struct TargetItemInfo { - QTreeWidgetItem* targetItem = nullptr; //target may be the parent of underMouse + struct TargetItemInfo + { + QTreeWidgetItem* targetItem = nullptr; // target may be the parent of underMouse QTreeWidgetItem* underMouseItem = nullptr; App::Document* targetDoc = nullptr; QPoint pos; @@ -156,23 +163,31 @@ private: TargetItemInfo getTargetInfo(QEvent* ev); using ObjectItemSubname = std::pair>; bool dropInObject(QDropEvent* event, TargetItemInfo& targetInfo, std::vector items); - bool dropInDocument(QDropEvent* event, TargetItemInfo& targetInfo, std::vector items); - bool canDragFromParents(DocumentObjectItem* parentItem, App::DocumentObject* obj, App::DocumentObject* target); + bool dropInDocument( + QDropEvent* event, + TargetItemInfo& targetInfo, + std::vector items + ); + bool canDragFromParents( + DocumentObjectItem* parentItem, + App::DocumentObject* obj, + App::DocumentObject* target + ); void sortDroppedObjects(TargetItemInfo& targetInfo, std::vector draggedObjects); //@} protected: - bool event(QEvent *e) override; - void keyPressEvent(QKeyEvent *event) override; - void mousePressEvent(QMouseEvent * event) override; - void mouseDoubleClickEvent(QMouseEvent * event) override; + bool event(QEvent* e) override; + void keyPressEvent(QKeyEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; + void mouseDoubleClickEvent(QMouseEvent* event) override; - void showEvent(QShowEvent *ev) override; - void hideEvent(QHideEvent *ev) override; - void leaveEvent(QEvent *event) override; + void showEvent(QShowEvent* ev) override; + void hideEvent(QHideEvent* ev) override; + void leaveEvent(QEvent* event) override; private: - void _updateStatus(bool delay=true); + void _updateStatus(bool delay = true); protected Q_SLOTS: void onCreateGroup(); @@ -197,9 +212,9 @@ protected Q_SLOTS: private Q_SLOTS: void onItemSelectionChanged(); void onItemChanged(QTreeWidgetItem*, int); - void onItemEntered(QTreeWidgetItem * item); - void onItemCollapsed(QTreeWidgetItem * item); - void onItemExpanded(QTreeWidgetItem * item); + void onItemEntered(QTreeWidgetItem* item); + void onItemCollapsed(QTreeWidgetItem* item); + void onItemExpanded(QTreeWidgetItem* item); void onUpdateStatus(); Q_SIGNALS: @@ -211,20 +226,24 @@ private: void slotRenameDocument(const Gui::Document&); void slotActiveDocument(const Gui::Document&); void slotRelabelDocument(const Gui::Document&); - void slotShowHidden(const Gui::Document &); - void slotChangedViewObject(const Gui::ViewProvider &, const App::Property &); + void slotShowHidden(const Gui::Document&); + void slotChangedViewObject(const Gui::ViewProvider&, const App::Property&); void slotStartOpenDocument(); void slotFinishOpenDocument(); - void _slotDeleteObject(const Gui::ViewProviderDocumentObject&, DocumentItem *deletingDoc); + void _slotDeleteObject(const Gui::ViewProviderDocumentObject&, DocumentItem* deletingDoc); void slotDeleteObject(const Gui::ViewProviderDocumentObject&); - void slotChangeObject(const Gui::ViewProviderDocumentObject&, const App::Property &prop); + void slotChangeObject(const Gui::ViewProviderDocumentObject&, const App::Property& prop); void slotTouchedObject(const App::DocumentObject&); - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void setupText(); - void updateChildren(App::DocumentObject *obj, - const std::set &data, bool output, bool force); + void updateChildren( + App::DocumentObject* obj, + const std::set& data, + bool output, + bool force + ); bool CheckForDependents(); void addDependentToSelection(App::Document* doc, App::DocumentObject* docObject); @@ -246,12 +265,12 @@ private: QAction* searchObjectsAction; QAction* openFileLocationAction; Command* skipRecomputeCommand; - QTreeWidgetItem *contextItem; - App::DocumentObject *searchObject; - Gui::Document *searchDoc; - Gui::Document *searchContextDoc; - DocumentObjectItem *editingItem; - DocumentItem *currentDocItem; + QTreeWidgetItem* contextItem; + App::DocumentObject* searchObject; + Gui::Document* searchDoc; + Gui::Document* searchContextDoc; + DocumentObjectItem* editingItem; + DocumentItem* currentDocItem; QTreeWidgetItem* rootItem; QTimer* statusTimer; QTimer* selectTimer; @@ -259,20 +278,21 @@ private: QElapsedTimer preselectTime; static std::unique_ptr documentPixmap; static std::unique_ptr documentPartialPixmap; - std::unordered_map DocumentMap; - std::unordered_map > ObjectTable; + std::unordered_map DocumentMap; + std::unordered_map> ObjectTable; - enum ChangedObjectStatus { + enum ChangedObjectStatus + { CS_Output, CS_Error, }; - std::unordered_map > ChangedObjects; + std::unordered_map> ChangedObjects; - std::unordered_map > NewObjects; + std::unordered_map> NewObjects; static std::set Instances; - std::string myName; // for debugging purpose + std::string myName; // for debugging purpose int updateBlocked = 0; friend class DocumentItem; @@ -295,47 +315,48 @@ private: * the visibility and the functions of the document. * \author Jürgen Riegel */ -class DocumentItem : public QTreeWidgetItem, public Base::Persistence +class DocumentItem: public QTreeWidgetItem, public Base::Persistence { public: - DocumentItem(const Gui::Document* doc, QTreeWidgetItem * parent); + DocumentItem(const Gui::Document* doc, QTreeWidgetItem* parent); ~DocumentItem() override; Gui::Document* document() const; - void clearSelection(DocumentObjectItem *exclude=nullptr); - void updateSelection(QTreeWidgetItem *, bool unselect=false); + void clearSelection(DocumentObjectItem* exclude = nullptr); + void updateSelection(QTreeWidgetItem*, bool unselect = false); void updateSelection(); - void updateItemSelection(DocumentObjectItem *); + void updateItemSelection(DocumentObjectItem*); - enum SelectionReason { - SR_SELECT, // only select, no expansion - SR_EXPAND, // select and expand but respect ObjectStatus::NoAutoExpand - SR_FORCE_EXPAND, // select and force expansion + enum SelectionReason + { + SR_SELECT, // only select, no expansion + SR_EXPAND, // select and expand but respect ObjectStatus::NoAutoExpand + SR_FORCE_EXPAND, // select and force expansion }; - void selectItems(SelectionReason reason=SR_SELECT); + void selectItems(SelectionReason reason = SR_SELECT); void testStatus(); - void setData(int column, int role, const QVariant & value) override; - void populateItem(DocumentObjectItem *item, bool refresh=false, bool delayUpdate=true); - bool populateObject(App::DocumentObject *obj); + void setData(int column, int role, const QVariant& value) override; + void populateItem(DocumentObjectItem* item, bool refresh = false, bool delayUpdate = true); + bool populateObject(App::DocumentObject* obj); void sortObjectItems(); - void selectAllInstances(const ViewProviderDocumentObject &vpd); - bool showItem(DocumentObjectItem *item, bool select, bool force=false); - void updateItemsVisibility(QTreeWidgetItem *item, bool show); - void updateLinks(const ViewProviderDocumentObject &view); - ViewProviderDocumentObject *getViewProvider(App::DocumentObject *); + void selectAllInstances(const ViewProviderDocumentObject& vpd); + bool showItem(DocumentObjectItem* item, bool select, bool force = false); + void updateItemsVisibility(QTreeWidgetItem* item, bool show); + void updateLinks(const ViewProviderDocumentObject& view); + ViewProviderDocumentObject* getViewProvider(App::DocumentObject*); bool showHidden() const; void setShowHidden(bool show); - TreeWidget *getTree() const; - const char *getTreeName() const; + TreeWidget* getTree() const; + const char* getTreeName() const; - bool isObjectShowable(App::DocumentObject *obj); + bool isObjectShowable(App::DocumentObject* obj); - unsigned int getMemSize () const override; - void Save (Base::Writer &) const override; - void Restore(Base::XMLReader &) override; + unsigned int getMemSize() const override; + void Save(Base::Writer&) const override; + void Restore(Base::XMLReader&) override; class ExpandInfo; using ExpandInfoPtr = std::shared_ptr; @@ -348,44 +369,66 @@ protected: /** Removes a view provider from the document item. * If this view provider is not added nothing happens. */ - void slotInEdit (const Gui::ViewProviderDocumentObject&); - void slotResetEdit (const Gui::ViewProviderDocumentObject&); - void slotHighlightObject (const Gui::ViewProviderDocumentObject&,const Gui::HighlightMode&,bool, - const App::DocumentObject *parent, const char *subname); - void slotExpandObject (const Gui::ViewProviderDocumentObject&,const Gui::TreeItemMode&, - const App::DocumentObject *parent, const char *subname); - void slotScrollToObject (const Gui::ViewProviderDocumentObject&); - void slotRecomputed (const App::Document &doc, const std::vector &objs); - void slotRecomputedObject(const App::DocumentObject &); + void slotInEdit(const Gui::ViewProviderDocumentObject&); + void slotResetEdit(const Gui::ViewProviderDocumentObject&); + void slotHighlightObject( + const Gui::ViewProviderDocumentObject&, + const Gui::HighlightMode&, + bool, + const App::DocumentObject* parent, + const char* subname + ); + void slotExpandObject( + const Gui::ViewProviderDocumentObject&, + const Gui::TreeItemMode&, + const App::DocumentObject* parent, + const char* subname + ); + void slotScrollToObject(const Gui::ViewProviderDocumentObject&); + void slotRecomputed(const App::Document& doc, const std::vector& objs); + void slotRecomputedObject(const App::DocumentObject&); - bool updateObject(const Gui::ViewProviderDocumentObject&, const App::Property &prop); + bool updateObject(const Gui::ViewProviderDocumentObject&, const App::Property& prop); - bool createNewItem(const Gui::ViewProviderDocumentObject&, - QTreeWidgetItem *parent=nullptr, int index=-1, - DocumentObjectDataPtr ptrs = DocumentObjectDataPtr()); + bool createNewItem( + const Gui::ViewProviderDocumentObject&, + QTreeWidgetItem* parent = nullptr, + int index = -1, + DocumentObjectDataPtr ptrs = DocumentObjectDataPtr() + ); - int findRootIndex(App::DocumentObject *childObj); + int findRootIndex(App::DocumentObject* childObj); - DocumentObjectItem *findItemByObject(bool sync, - App::DocumentObject *obj, const char *subname, bool select=false); + DocumentObjectItem* findItemByObject( + bool sync, + App::DocumentObject* obj, + const char* subname, + bool select = false + ); - DocumentObjectItem *findItem(bool sync, DocumentObjectItem *item, const char *subname, bool select=true); - DocumentObjectItem *findItem(App::DocumentObject* obj, const std::string& subname) const; + DocumentObjectItem* findItem( + bool sync, + DocumentObjectItem* item, + const char* subname, + bool select = true + ); + DocumentObjectItem* findItem(App::DocumentObject* obj, const std::string& subname) const; - App::DocumentObject *getTopParent(App::DocumentObject *obj, std::string &subname); + App::DocumentObject* getTopParent(App::DocumentObject* obj, std::string& subname); - using ViewParentMap = std::unordered_map >; - void populateParents(const ViewProvider *vp, ViewParentMap &); + using ViewParentMap + = std::unordered_map>; + void populateParents(const ViewProvider* vp, ViewParentMap&); private: - const char *treeName; // for debugging purpose + const char* treeName; // for debugging purpose Gui::Document* pDocument; - std::unordered_map ObjectMap; - std::unordered_map > _ParentMap; + std::unordered_map ObjectMap; + std::unordered_map> _ParentMap; std::vector PopulateObjects; ExpandInfoPtr _ExpandInfo; - void restoreItemExpansion(const ExpandInfoPtr &, DocumentObjectItem *); + void restoreItemExpansion(const ExpandInfoPtr&, DocumentObjectItem*); using Connection = boost::signals2::connection; Connection connectNewObject; @@ -410,56 +453,60 @@ private: * the visibility and the functions of the object. * @author Werner Mayer */ -class DocumentObjectItem : public QTreeWidgetItem +class DocumentObjectItem: public QTreeWidgetItem { public: - DocumentObjectItem(DocumentItem *ownerDocItem, DocumentObjectDataPtr data); + DocumentObjectItem(DocumentItem* ownerDocItem, DocumentObjectDataPtr data); ~DocumentObjectItem() override; Gui::ViewProviderDocumentObject* object() const; - void testStatus(bool resetStatus, QIcon &icon1, QIcon &icon2); + void testStatus(bool resetStatus, QIcon& icon1, QIcon& icon2); void testStatus(bool resetStatus); void displayStatusInfo(); void setExpandedStatus(bool); - void setData(int column, int role, const QVariant & value) override; + void setData(int column, int role, const QVariant& value) override; bool isChildOfItem(DocumentObjectItem*); void restoreBackground(); // Get the parent document (where the object is stored) of this item - DocumentItem *getParentDocument() const; + DocumentItem* getParentDocument() const; // Get the owner document (where the object is displayed, either stored or // linked in) of this object - DocumentItem *getOwnerDocument() const; + DocumentItem* getOwnerDocument() const; // check if a new item is required at root - bool requiredAtRoot(bool excludeSelf=true) const; + bool requiredAtRoot(bool excludeSelf = true) const; // return the owner, and full qualified subname - App::DocumentObject *getFullSubName(std::ostringstream &str, - DocumentObjectItem *parent = nullptr) const; + App::DocumentObject* getFullSubName( + std::ostringstream& str, + DocumentObjectItem* parent = nullptr + ) const; // return the immediate descendent of the common ancestor of this item and // 'cousin'. - App::DocumentObject *getRelativeParent( - std::ostringstream &str, - DocumentObjectItem *cousin, - App::DocumentObject **topParent=nullptr, - std::string *topSubname=nullptr) const; + App::DocumentObject* getRelativeParent( + std::ostringstream& str, + DocumentObjectItem* cousin, + App::DocumentObject** topParent = nullptr, + std::string* topSubname = nullptr + ) const; // return the top most linked group owner's name, and subname. This method // is necessary despite have getFullSubName above is because native geo group // cannot handle selection with sub name. So only a linked group can have // subname in selection - int getSubName(std::ostringstream &str, App::DocumentObject *&topParent) const; - const std::vector& getSubNames() const { + int getSubName(std::ostringstream& str, App::DocumentObject*& topParent) const; + const std::vector& getSubNames() const + { return mySubs; } void setHighlight(bool set, HighlightMode mode = HighlightMode::LightBlue); - const char *getName() const; - const char *getTreeName() const; + const char* getName() const; + const char* getTreeName() const; bool isLink() const; bool isLinkFinal() const; @@ -467,18 +514,21 @@ public: int isGroup() const; int isParentGroup() const; - DocumentObjectItem *getParentItem() const; - DocumentObjectItem *getNextSibling() const; - DocumentObjectItem *getPreviousSibling() const; - TreeWidget *getTree() const; + DocumentObjectItem* getParentItem() const; + DocumentObjectItem* getNextSibling() const; + DocumentObjectItem* getPreviousSibling() const; + TreeWidget* getTree() const; private: void setCheckState(bool checked); void getExpandedSnapshot(std::vector& snapshot) const; - void applyExpandedSnapshot(const std::vector& snapshot, std::vector::const_iterator& from); + void applyExpandedSnapshot( + const std::vector& snapshot, + std::vector::const_iterator& from + ); QBrush bgBrush; - DocumentItem *myOwner; + DocumentItem* myOwner; DocumentObjectDataPtr myData; std::vector mySubs; using Connection = boost::signals2::connection; @@ -490,21 +540,21 @@ private: friend class DocumentItem; }; -class TreePanel : public QWidget +class TreePanel: public QWidget { Q_OBJECT public: - explicit TreePanel(const char *name, QWidget* parent=nullptr); + explicit TreePanel(const char* name, QWidget* parent = nullptr); ~TreePanel() override; - bool eventFilter(QObject *obj, QEvent *ev) override; + bool eventFilter(QObject* obj, QEvent* ev) override; private Q_SLOTS: void accept(); void showEditor(); void hideEditor(); - void itemSearch(const QString &text); + void itemSearch(const QString& text); private: QLineEdit* searchBox; @@ -515,15 +565,15 @@ private: * The dock window containing the tree view. * @author Werner Mayer */ -class TreeDockWidget : public Gui::DockWindow +class TreeDockWidget: public Gui::DockWindow { Q_OBJECT public: - explicit TreeDockWidget(Gui::Document* pcDocument,QWidget *parent=nullptr); + explicit TreeDockWidget(Gui::Document* pcDocument, QWidget* parent = nullptr); ~TreeDockWidget() override; }; -} +} // namespace Gui -#endif // GUI_TREE_H +#endif // GUI_TREE_H diff --git a/src/Gui/TreeItemMode.h b/src/Gui/TreeItemMode.h index 9b88f2251b..6504bbf431 100644 --- a/src/Gui/TreeItemMode.h +++ b/src/Gui/TreeItemMode.h @@ -24,27 +24,30 @@ #ifndef GUI_TREEITEMMODE_H #define GUI_TREEITEMMODE_H -namespace Gui { +namespace Gui +{ - /// highlight modes for the tree items - enum class HighlightMode { - Underlined, - Italic, - Overlined, - StrikeOut, - Bold, - Blue, - LightBlue, - UserDefined - }; +/// highlight modes for the tree items +enum class HighlightMode +{ + Underlined, + Italic, + Overlined, + StrikeOut, + Bold, + Blue, + LightBlue, + UserDefined +}; - /// highlight modes for the tree items - enum class TreeItemMode { - ExpandItem, - ExpandPath, - CollapseItem, - ToggleItem - }; -} +/// highlight modes for the tree items +enum class TreeItemMode +{ + ExpandItem, + ExpandPath, + CollapseItem, + ToggleItem +}; +} // namespace Gui -#endif // GUI_TREEITEMMODE_H +#endif // GUI_TREEITEMMODE_H diff --git a/src/Gui/TreeParams.cpp b/src/Gui/TreeParams.cpp index 23baad32dd..8049c17c85 100644 --- a/src/Gui/TreeParams.cpp +++ b/src/Gui/TreeParams.cpp @@ -36,11 +36,13 @@ TreeParams.define() using namespace Gui; // Auto generated code (Tools/params_utils.py:207) -namespace { -class TreeParamsP: public ParameterGrp::ObserverType { +namespace +{ +class TreeParamsP: public ParameterGrp::ObserverType +{ public: ParameterGrp::handle handle; - std::unordered_map funcs; + std::unordered_map funcs; bool SyncSelection; bool CheckBoxesSelection; @@ -83,8 +85,11 @@ public: bool VisibilityIcon; // Auto generated code (Tools/params_utils.py:245) - TreeParamsP() { - handle = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/TreeView"); + TreeParamsP() + { + handle = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/TreeView" + ); handle->Attach(this); SyncSelection = handle->GetBool("SyncSelection", true); @@ -168,23 +173,26 @@ public: } // Auto generated code (Tools/params_utils.py:263) - ~TreeParamsP() { - } + ~TreeParamsP() + {} // Auto generated code (Tools/params_utils.py:270) - void OnChange(Base::Subject &, const char* sReason) { - if(!sReason) + void OnChange(Base::Subject&, const char* sReason) + { + if (!sReason) { return; + } auto it = funcs.find(sReason); - if(it == funcs.end()) + if (it == funcs.end()) { return; + } it->second(this); - } // Auto generated code (Tools/params_utils.py:296) - static void updateSyncSelection(TreeParamsP *self) { + static void updateSyncSelection(TreeParamsP* self) + { auto v = self->handle->GetBool("SyncSelection", true); if (self->SyncSelection != v) { self->SyncSelection = v; @@ -192,7 +200,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateCheckBoxesSelection(TreeParamsP *self) { + static void updateCheckBoxesSelection(TreeParamsP* self) + { auto v = self->handle->GetBool("CheckBoxesSelection", false); if (self->CheckBoxesSelection != v) { self->CheckBoxesSelection = v; @@ -200,23 +209,28 @@ public: } } // Auto generated code (Tools/params_utils.py:288) - static void updateSyncView(TreeParamsP *self) { + static void updateSyncView(TreeParamsP* self) + { self->SyncView = self->handle->GetBool("SyncView", true); } // Auto generated code (Tools/params_utils.py:288) - static void updatePreSelection(TreeParamsP *self) { + static void updatePreSelection(TreeParamsP* self) + { self->PreSelection = self->handle->GetBool("PreSelection", true); } // Auto generated code (Tools/params_utils.py:288) - static void updateSyncPlacement(TreeParamsP *self) { + static void updateSyncPlacement(TreeParamsP* self) + { self->SyncPlacement = self->handle->GetBool("SyncPlacement", false); } // Auto generated code (Tools/params_utils.py:288) - static void updateRecordSelection(TreeParamsP *self) { + static void updateRecordSelection(TreeParamsP* self) + { self->RecordSelection = self->handle->GetBool("RecordSelection", true); } // Auto generated code (Tools/params_utils.py:296) - static void updateDocumentMode(TreeParamsP *self) { + static void updateDocumentMode(TreeParamsP* self) + { auto v = self->handle->GetInt("DocumentMode", 2); if (self->DocumentMode != v) { self->DocumentMode = v; @@ -224,39 +238,48 @@ public: } } // Auto generated code (Tools/params_utils.py:288) - static void updateStatusTimeout(TreeParamsP *self) { + static void updateStatusTimeout(TreeParamsP* self) + { self->StatusTimeout = self->handle->GetInt("StatusTimeout", 100); } // Auto generated code (Tools/params_utils.py:288) - static void updateSelectionTimeout(TreeParamsP *self) { + static void updateSelectionTimeout(TreeParamsP* self) + { self->SelectionTimeout = self->handle->GetInt("SelectionTimeout", 100); } // Auto generated code (Tools/params_utils.py:288) - static void updatePreSelectionTimeout(TreeParamsP *self) { + static void updatePreSelectionTimeout(TreeParamsP* self) + { self->PreSelectionTimeout = self->handle->GetInt("PreSelectionTimeout", 500); } // Auto generated code (Tools/params_utils.py:288) - static void updatePreSelectionDelay(TreeParamsP *self) { + static void updatePreSelectionDelay(TreeParamsP* self) + { self->PreSelectionDelay = self->handle->GetInt("PreSelectionDelay", 700); } // Auto generated code (Tools/params_utils.py:288) - static void updatePreSelectionMinDelay(TreeParamsP *self) { + static void updatePreSelectionMinDelay(TreeParamsP* self) + { self->PreSelectionMinDelay = self->handle->GetInt("PreSelectionMinDelay", 200); } // Auto generated code (Tools/params_utils.py:288) - static void updateRecomputeOnDrop(TreeParamsP *self) { + static void updateRecomputeOnDrop(TreeParamsP* self) + { self->RecomputeOnDrop = self->handle->GetBool("RecomputeOnDrop", true); } // Auto generated code (Tools/params_utils.py:288) - static void updateKeepRootOrder(TreeParamsP *self) { + static void updateKeepRootOrder(TreeParamsP* self) + { self->KeepRootOrder = self->handle->GetBool("KeepRootOrder", true); } // Auto generated code (Tools/params_utils.py:288) - static void updateTreeActiveAutoExpand(TreeParamsP *self) { + static void updateTreeActiveAutoExpand(TreeParamsP* self) + { self->TreeActiveAutoExpand = self->handle->GetBool("TreeActiveAutoExpand", true); } // Auto generated code (Tools/params_utils.py:296) - static void updateTreeActiveColor(TreeParamsP *self) { + static void updateTreeActiveColor(TreeParamsP* self) + { auto v = self->handle->GetUnsigned("TreeActiveColor", 3873898495); if (self->TreeActiveColor != v) { self->TreeActiveColor = v; @@ -264,7 +287,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateTreeEditColor(TreeParamsP *self) { + static void updateTreeEditColor(TreeParamsP* self) + { auto v = self->handle->GetUnsigned("TreeEditColor", 2459042047); if (self->TreeEditColor != v) { self->TreeEditColor = v; @@ -272,7 +296,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateSelectingGroupColor(TreeParamsP *self) { + static void updateSelectingGroupColor(TreeParamsP* self) + { auto v = self->handle->GetUnsigned("SelectingGroupColor", 1082163711); if (self->SelectingGroupColor != v) { self->SelectingGroupColor = v; @@ -280,7 +305,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateTreeActiveBold(TreeParamsP *self) { + static void updateTreeActiveBold(TreeParamsP* self) + { auto v = self->handle->GetBool("TreeActiveBold", true); if (self->TreeActiveBold != v) { self->TreeActiveBold = v; @@ -288,7 +314,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateTreeActiveItalic(TreeParamsP *self) { + static void updateTreeActiveItalic(TreeParamsP* self) + { auto v = self->handle->GetBool("TreeActiveItalic", false); if (self->TreeActiveItalic != v) { self->TreeActiveItalic = v; @@ -296,7 +323,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateTreeActiveUnderlined(TreeParamsP *self) { + static void updateTreeActiveUnderlined(TreeParamsP* self) + { auto v = self->handle->GetBool("TreeActiveUnderlined", false); if (self->TreeActiveUnderlined != v) { self->TreeActiveUnderlined = v; @@ -304,7 +332,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateTreeActiveOverlined(TreeParamsP *self) { + static void updateTreeActiveOverlined(TreeParamsP* self) + { auto v = self->handle->GetBool("TreeActiveOverlined", false); if (self->TreeActiveOverlined != v) { self->TreeActiveOverlined = v; @@ -312,7 +341,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateIndentation(TreeParamsP *self) { + static void updateIndentation(TreeParamsP* self) + { auto v = self->handle->GetInt("Indentation", 0); if (self->Indentation != v) { self->Indentation = v; @@ -320,11 +350,13 @@ public: } } // Auto generated code (Tools/params_utils.py:288) - static void updateLabelExpression(TreeParamsP *self) { + static void updateLabelExpression(TreeParamsP* self) + { self->LabelExpression = self->handle->GetBool("LabelExpression", false); } // Auto generated code (Tools/params_utils.py:296) - static void updateIconSize(TreeParamsP *self) { + static void updateIconSize(TreeParamsP* self) + { auto v = self->handle->GetInt("IconSize", 0); if (self->IconSize != v) { self->IconSize = v; @@ -332,7 +364,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateFontSize(TreeParamsP *self) { + static void updateFontSize(TreeParamsP* self) + { auto v = self->handle->GetInt("FontSize", 0); if (self->FontSize != v) { self->FontSize = v; @@ -340,7 +373,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateItemSpacing(TreeParamsP *self) { + static void updateItemSpacing(TreeParamsP* self) + { auto v = self->handle->GetInt("ItemSpacing", 0); if (self->ItemSpacing != v) { self->ItemSpacing = v; @@ -348,7 +382,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateItemBackground(TreeParamsP *self) { + static void updateItemBackground(TreeParamsP* self) + { auto v = self->handle->GetUnsigned("ItemBackground", 0x00000000); if (self->ItemBackground != v) { self->ItemBackground = v; @@ -356,7 +391,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateItemBackgroundPadding(TreeParamsP *self) { + static void updateItemBackgroundPadding(TreeParamsP* self) + { auto v = self->handle->GetInt("ItemBackgroundPadding", 0); if (self->ItemBackgroundPadding != v) { self->ItemBackgroundPadding = v; @@ -364,7 +400,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateHideColumn(TreeParamsP *self) { + static void updateHideColumn(TreeParamsP* self) + { auto v = self->handle->GetBool("HideColumn", true); if (self->HideColumn != v) { self->HideColumn = v; @@ -372,7 +409,8 @@ public: } } // Auto generated code (Tools/params_utils.py:296) - static void updateHideInternalNames(TreeParamsP *self) { + static void updateHideInternalNames(TreeParamsP* self) + { auto v = self->handle->GetBool("HideInternalNames", true); if (self->HideInternalNames != v) { self->HideInternalNames = v; @@ -380,15 +418,18 @@ public: } } // Auto generated code (Tools/params_utils.py:288) - static void updateHideScrollBar(TreeParamsP *self) { + static void updateHideScrollBar(TreeParamsP* self) + { self->HideScrollBar = self->handle->GetBool("HideScrollBar", true); } // Auto generated code (Tools/params_utils.py:288) - static void updateHideHeaderView(TreeParamsP *self) { + static void updateHideHeaderView(TreeParamsP* self) + { self->HideHeaderView = self->handle->GetBool("HideHeaderView", true); } // Auto generated code (Tools/params_utils.py:296) - static void updateResizableColumn(TreeParamsP *self) { + static void updateResizableColumn(TreeParamsP* self) + { auto v = self->handle->GetBool("ResizableColumn", false); if (self->ResizableColumn != v) { self->ResizableColumn = v; @@ -396,23 +437,28 @@ public: } } // Auto generated code (Tools/params_utils.py:288) - static void updateColumnSize1(TreeParamsP *self) { + static void updateColumnSize1(TreeParamsP* self) + { self->ColumnSize1 = self->handle->GetInt("ColumnSize1", 0); } // Auto generated code (Tools/params_utils.py:288) - static void updateColumnSize2(TreeParamsP *self) { + static void updateColumnSize2(TreeParamsP* self) + { self->ColumnSize2 = self->handle->GetInt("ColumnSize2", 0); } // Auto generated code (Tools/params_utils.py:288) - static void updateColumnSize3(TreeParamsP *self) { + static void updateColumnSize3(TreeParamsP* self) + { self->ColumnSize3 = self->handle->GetInt("ColumnSize3", 0); } // Auto generated code (Tools/params_utils.py:288) - static void updateTreeToolTipIcon(TreeParamsP *self) { + static void updateTreeToolTipIcon(TreeParamsP* self) + { self->TreeToolTipIcon = self->handle->GetBool("TreeToolTipIcon", false); } // Auto generated code (Tools/params_utils.py:296) - static void updateVisibilityIcon(TreeParamsP *self) { + static void updateVisibilityIcon(TreeParamsP* self) + { auto v = self->handle->GetBool("VisibilityIcon", true); if (self->VisibilityIcon != v) { self->VisibilityIcon = v; @@ -422,1083 +468,1278 @@ public: }; // Auto generated code (Tools/params_utils.py:310) -TreeParamsP *instance() { - static TreeParamsP *inst = new TreeParamsP; +TreeParamsP* instance() +{ + static TreeParamsP* inst = new TreeParamsP; return inst; } -} // Anonymous namespace +} // Anonymous namespace // Auto generated code (Tools/params_utils.py:321) -ParameterGrp::handle TreeParams::getHandle() { +ParameterGrp::handle TreeParams::getHandle() +{ return instance()->handle; } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docSyncSelection() { +const char* TreeParams::docSyncSelection() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getSyncSelection() { +const bool& TreeParams::getSyncSelection() +{ return instance()->SyncSelection; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultSyncSelection() { +const bool& TreeParams::defaultSyncSelection() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setSyncSelection(const bool &v) { - instance()->handle->SetBool("SyncSelection",v); +void TreeParams::setSyncSelection(const bool& v) +{ + instance()->handle->SetBool("SyncSelection", v); instance()->SyncSelection = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeSyncSelection() { +void TreeParams::removeSyncSelection() +{ instance()->handle->RemoveBool("SyncSelection"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docCheckBoxesSelection() { +const char* TreeParams::docCheckBoxesSelection() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getCheckBoxesSelection() { +const bool& TreeParams::getCheckBoxesSelection() +{ return instance()->CheckBoxesSelection; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultCheckBoxesSelection() { +const bool& TreeParams::defaultCheckBoxesSelection() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setCheckBoxesSelection(const bool &v) { - instance()->handle->SetBool("CheckBoxesSelection",v); +void TreeParams::setCheckBoxesSelection(const bool& v) +{ + instance()->handle->SetBool("CheckBoxesSelection", v); instance()->CheckBoxesSelection = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeCheckBoxesSelection() { +void TreeParams::removeCheckBoxesSelection() +{ instance()->handle->RemoveBool("CheckBoxesSelection"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docSyncView() { +const char* TreeParams::docSyncView() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getSyncView() { +const bool& TreeParams::getSyncView() +{ return instance()->SyncView; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultSyncView() { +const bool& TreeParams::defaultSyncView() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setSyncView(const bool &v) { - instance()->handle->SetBool("SyncView",v); +void TreeParams::setSyncView(const bool& v) +{ + instance()->handle->SetBool("SyncView", v); instance()->SyncView = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeSyncView() { +void TreeParams::removeSyncView() +{ instance()->handle->RemoveBool("SyncView"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docPreSelection() { +const char* TreeParams::docPreSelection() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getPreSelection() { +const bool& TreeParams::getPreSelection() +{ return instance()->PreSelection; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultPreSelection() { +const bool& TreeParams::defaultPreSelection() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setPreSelection(const bool &v) { - instance()->handle->SetBool("PreSelection",v); +void TreeParams::setPreSelection(const bool& v) +{ + instance()->handle->SetBool("PreSelection", v); instance()->PreSelection = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removePreSelection() { +void TreeParams::removePreSelection() +{ instance()->handle->RemoveBool("PreSelection"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docSyncPlacement() { +const char* TreeParams::docSyncPlacement() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getSyncPlacement() { +const bool& TreeParams::getSyncPlacement() +{ return instance()->SyncPlacement; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultSyncPlacement() { +const bool& TreeParams::defaultSyncPlacement() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setSyncPlacement(const bool &v) { - instance()->handle->SetBool("SyncPlacement",v); +void TreeParams::setSyncPlacement(const bool& v) +{ + instance()->handle->SetBool("SyncPlacement", v); instance()->SyncPlacement = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeSyncPlacement() { +void TreeParams::removeSyncPlacement() +{ instance()->handle->RemoveBool("SyncPlacement"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docRecordSelection() { +const char* TreeParams::docRecordSelection() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getRecordSelection() { +const bool& TreeParams::getRecordSelection() +{ return instance()->RecordSelection; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultRecordSelection() { +const bool& TreeParams::defaultRecordSelection() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setRecordSelection(const bool &v) { - instance()->handle->SetBool("RecordSelection",v); +void TreeParams::setRecordSelection(const bool& v) +{ + instance()->handle->SetBool("RecordSelection", v); instance()->RecordSelection = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeRecordSelection() { +void TreeParams::removeRecordSelection() +{ instance()->handle->RemoveBool("RecordSelection"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docDocumentMode() { +const char* TreeParams::docDocumentMode() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getDocumentMode() { +const long& TreeParams::getDocumentMode() +{ return instance()->DocumentMode; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultDocumentMode() { +const long& TreeParams::defaultDocumentMode() +{ const static long def = 2; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setDocumentMode(const long &v) { - instance()->handle->SetInt("DocumentMode",v); +void TreeParams::setDocumentMode(const long& v) +{ + instance()->handle->SetInt("DocumentMode", v); instance()->DocumentMode = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeDocumentMode() { +void TreeParams::removeDocumentMode() +{ instance()->handle->RemoveInt("DocumentMode"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docStatusTimeout() { +const char* TreeParams::docStatusTimeout() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getStatusTimeout() { +const long& TreeParams::getStatusTimeout() +{ return instance()->StatusTimeout; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultStatusTimeout() { +const long& TreeParams::defaultStatusTimeout() +{ const static long def = 100; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setStatusTimeout(const long &v) { - instance()->handle->SetInt("StatusTimeout",v); +void TreeParams::setStatusTimeout(const long& v) +{ + instance()->handle->SetInt("StatusTimeout", v); instance()->StatusTimeout = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeStatusTimeout() { +void TreeParams::removeStatusTimeout() +{ instance()->handle->RemoveInt("StatusTimeout"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docSelectionTimeout() { +const char* TreeParams::docSelectionTimeout() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getSelectionTimeout() { +const long& TreeParams::getSelectionTimeout() +{ return instance()->SelectionTimeout; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultSelectionTimeout() { +const long& TreeParams::defaultSelectionTimeout() +{ const static long def = 100; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setSelectionTimeout(const long &v) { - instance()->handle->SetInt("SelectionTimeout",v); +void TreeParams::setSelectionTimeout(const long& v) +{ + instance()->handle->SetInt("SelectionTimeout", v); instance()->SelectionTimeout = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeSelectionTimeout() { +void TreeParams::removeSelectionTimeout() +{ instance()->handle->RemoveInt("SelectionTimeout"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docPreSelectionTimeout() { +const char* TreeParams::docPreSelectionTimeout() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getPreSelectionTimeout() { +const long& TreeParams::getPreSelectionTimeout() +{ return instance()->PreSelectionTimeout; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultPreSelectionTimeout() { +const long& TreeParams::defaultPreSelectionTimeout() +{ const static long def = 500; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setPreSelectionTimeout(const long &v) { - instance()->handle->SetInt("PreSelectionTimeout",v); +void TreeParams::setPreSelectionTimeout(const long& v) +{ + instance()->handle->SetInt("PreSelectionTimeout", v); instance()->PreSelectionTimeout = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removePreSelectionTimeout() { +void TreeParams::removePreSelectionTimeout() +{ instance()->handle->RemoveInt("PreSelectionTimeout"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docPreSelectionDelay() { +const char* TreeParams::docPreSelectionDelay() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getPreSelectionDelay() { +const long& TreeParams::getPreSelectionDelay() +{ return instance()->PreSelectionDelay; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultPreSelectionDelay() { +const long& TreeParams::defaultPreSelectionDelay() +{ const static long def = 700; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setPreSelectionDelay(const long &v) { - instance()->handle->SetInt("PreSelectionDelay",v); +void TreeParams::setPreSelectionDelay(const long& v) +{ + instance()->handle->SetInt("PreSelectionDelay", v); instance()->PreSelectionDelay = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removePreSelectionDelay() { +void TreeParams::removePreSelectionDelay() +{ instance()->handle->RemoveInt("PreSelectionDelay"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docPreSelectionMinDelay() { +const char* TreeParams::docPreSelectionMinDelay() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getPreSelectionMinDelay() { +const long& TreeParams::getPreSelectionMinDelay() +{ return instance()->PreSelectionMinDelay; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultPreSelectionMinDelay() { +const long& TreeParams::defaultPreSelectionMinDelay() +{ const static long def = 200; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setPreSelectionMinDelay(const long &v) { - instance()->handle->SetInt("PreSelectionMinDelay",v); +void TreeParams::setPreSelectionMinDelay(const long& v) +{ + instance()->handle->SetInt("PreSelectionMinDelay", v); instance()->PreSelectionMinDelay = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removePreSelectionMinDelay() { +void TreeParams::removePreSelectionMinDelay() +{ instance()->handle->RemoveInt("PreSelectionMinDelay"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docRecomputeOnDrop() { +const char* TreeParams::docRecomputeOnDrop() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getRecomputeOnDrop() { +const bool& TreeParams::getRecomputeOnDrop() +{ return instance()->RecomputeOnDrop; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultRecomputeOnDrop() { +const bool& TreeParams::defaultRecomputeOnDrop() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setRecomputeOnDrop(const bool &v) { - instance()->handle->SetBool("RecomputeOnDrop",v); +void TreeParams::setRecomputeOnDrop(const bool& v) +{ + instance()->handle->SetBool("RecomputeOnDrop", v); instance()->RecomputeOnDrop = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeRecomputeOnDrop() { +void TreeParams::removeRecomputeOnDrop() +{ instance()->handle->RemoveBool("RecomputeOnDrop"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docKeepRootOrder() { +const char* TreeParams::docKeepRootOrder() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getKeepRootOrder() { +const bool& TreeParams::getKeepRootOrder() +{ return instance()->KeepRootOrder; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultKeepRootOrder() { +const bool& TreeParams::defaultKeepRootOrder() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setKeepRootOrder(const bool &v) { - instance()->handle->SetBool("KeepRootOrder",v); +void TreeParams::setKeepRootOrder(const bool& v) +{ + instance()->handle->SetBool("KeepRootOrder", v); instance()->KeepRootOrder = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeKeepRootOrder() { +void TreeParams::removeKeepRootOrder() +{ instance()->handle->RemoveBool("KeepRootOrder"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeActiveAutoExpand() { +const char* TreeParams::docTreeActiveAutoExpand() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getTreeActiveAutoExpand() { +const bool& TreeParams::getTreeActiveAutoExpand() +{ return instance()->TreeActiveAutoExpand; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultTreeActiveAutoExpand() { +const bool& TreeParams::defaultTreeActiveAutoExpand() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeActiveAutoExpand(const bool &v) { - instance()->handle->SetBool("TreeActiveAutoExpand",v); +void TreeParams::setTreeActiveAutoExpand(const bool& v) +{ + instance()->handle->SetBool("TreeActiveAutoExpand", v); instance()->TreeActiveAutoExpand = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeActiveAutoExpand() { +void TreeParams::removeTreeActiveAutoExpand() +{ instance()->handle->RemoveBool("TreeActiveAutoExpand"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeActiveColor() { +const char* TreeParams::docTreeActiveColor() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const unsigned long & TreeParams::getTreeActiveColor() { +const unsigned long& TreeParams::getTreeActiveColor() +{ return instance()->TreeActiveColor; } // Auto generated code (Tools/params_utils.py:366) -const unsigned long & TreeParams::defaultTreeActiveColor() { +const unsigned long& TreeParams::defaultTreeActiveColor() +{ const static unsigned long def = 3873898495; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeActiveColor(const unsigned long &v) { - instance()->handle->SetUnsigned("TreeActiveColor",v); +void TreeParams::setTreeActiveColor(const unsigned long& v) +{ + instance()->handle->SetUnsigned("TreeActiveColor", v); instance()->TreeActiveColor = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeActiveColor() { +void TreeParams::removeTreeActiveColor() +{ instance()->handle->RemoveUnsigned("TreeActiveColor"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeEditColor() { +const char* TreeParams::docTreeEditColor() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const unsigned long & TreeParams::getTreeEditColor() { +const unsigned long& TreeParams::getTreeEditColor() +{ return instance()->TreeEditColor; } // Auto generated code (Tools/params_utils.py:366) -const unsigned long & TreeParams::defaultTreeEditColor() { +const unsigned long& TreeParams::defaultTreeEditColor() +{ const static unsigned long def = 2459042047; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeEditColor(const unsigned long &v) { - instance()->handle->SetUnsigned("TreeEditColor",v); +void TreeParams::setTreeEditColor(const unsigned long& v) +{ + instance()->handle->SetUnsigned("TreeEditColor", v); instance()->TreeEditColor = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeEditColor() { +void TreeParams::removeTreeEditColor() +{ instance()->handle->RemoveUnsigned("TreeEditColor"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docSelectingGroupColor() { +const char* TreeParams::docSelectingGroupColor() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const unsigned long & TreeParams::getSelectingGroupColor() { +const unsigned long& TreeParams::getSelectingGroupColor() +{ return instance()->SelectingGroupColor; } // Auto generated code (Tools/params_utils.py:366) -const unsigned long & TreeParams::defaultSelectingGroupColor() { +const unsigned long& TreeParams::defaultSelectingGroupColor() +{ const static unsigned long def = 1082163711; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setSelectingGroupColor(const unsigned long &v) { - instance()->handle->SetUnsigned("SelectingGroupColor",v); +void TreeParams::setSelectingGroupColor(const unsigned long& v) +{ + instance()->handle->SetUnsigned("SelectingGroupColor", v); instance()->SelectingGroupColor = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeSelectingGroupColor() { +void TreeParams::removeSelectingGroupColor() +{ instance()->handle->RemoveUnsigned("SelectingGroupColor"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeActiveBold() { +const char* TreeParams::docTreeActiveBold() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getTreeActiveBold() { +const bool& TreeParams::getTreeActiveBold() +{ return instance()->TreeActiveBold; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultTreeActiveBold() { +const bool& TreeParams::defaultTreeActiveBold() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeActiveBold(const bool &v) { - instance()->handle->SetBool("TreeActiveBold",v); +void TreeParams::setTreeActiveBold(const bool& v) +{ + instance()->handle->SetBool("TreeActiveBold", v); instance()->TreeActiveBold = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeActiveBold() { +void TreeParams::removeTreeActiveBold() +{ instance()->handle->RemoveBool("TreeActiveBold"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeActiveItalic() { +const char* TreeParams::docTreeActiveItalic() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getTreeActiveItalic() { +const bool& TreeParams::getTreeActiveItalic() +{ return instance()->TreeActiveItalic; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultTreeActiveItalic() { +const bool& TreeParams::defaultTreeActiveItalic() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeActiveItalic(const bool &v) { - instance()->handle->SetBool("TreeActiveItalic",v); +void TreeParams::setTreeActiveItalic(const bool& v) +{ + instance()->handle->SetBool("TreeActiveItalic", v); instance()->TreeActiveItalic = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeActiveItalic() { +void TreeParams::removeTreeActiveItalic() +{ instance()->handle->RemoveBool("TreeActiveItalic"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeActiveUnderlined() { +const char* TreeParams::docTreeActiveUnderlined() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getTreeActiveUnderlined() { +const bool& TreeParams::getTreeActiveUnderlined() +{ return instance()->TreeActiveUnderlined; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultTreeActiveUnderlined() { +const bool& TreeParams::defaultTreeActiveUnderlined() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeActiveUnderlined(const bool &v) { - instance()->handle->SetBool("TreeActiveUnderlined",v); +void TreeParams::setTreeActiveUnderlined(const bool& v) +{ + instance()->handle->SetBool("TreeActiveUnderlined", v); instance()->TreeActiveUnderlined = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeActiveUnderlined() { +void TreeParams::removeTreeActiveUnderlined() +{ instance()->handle->RemoveBool("TreeActiveUnderlined"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeActiveOverlined() { +const char* TreeParams::docTreeActiveOverlined() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getTreeActiveOverlined() { +const bool& TreeParams::getTreeActiveOverlined() +{ return instance()->TreeActiveOverlined; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultTreeActiveOverlined() { +const bool& TreeParams::defaultTreeActiveOverlined() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeActiveOverlined(const bool &v) { - instance()->handle->SetBool("TreeActiveOverlined",v); +void TreeParams::setTreeActiveOverlined(const bool& v) +{ + instance()->handle->SetBool("TreeActiveOverlined", v); instance()->TreeActiveOverlined = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeActiveOverlined() { +void TreeParams::removeTreeActiveOverlined() +{ instance()->handle->RemoveBool("TreeActiveOverlined"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docIndentation() { +const char* TreeParams::docIndentation() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getIndentation() { +const long& TreeParams::getIndentation() +{ return instance()->Indentation; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultIndentation() { +const long& TreeParams::defaultIndentation() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setIndentation(const long &v) { - instance()->handle->SetInt("Indentation",v); +void TreeParams::setIndentation(const long& v) +{ + instance()->handle->SetInt("Indentation", v); instance()->Indentation = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeIndentation() { +void TreeParams::removeIndentation() +{ instance()->handle->RemoveInt("Indentation"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docLabelExpression() { +const char* TreeParams::docLabelExpression() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getLabelExpression() { +const bool& TreeParams::getLabelExpression() +{ return instance()->LabelExpression; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultLabelExpression() { +const bool& TreeParams::defaultLabelExpression() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setLabelExpression(const bool &v) { - instance()->handle->SetBool("LabelExpression",v); +void TreeParams::setLabelExpression(const bool& v) +{ + instance()->handle->SetBool("LabelExpression", v); instance()->LabelExpression = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeLabelExpression() { +void TreeParams::removeLabelExpression() +{ instance()->handle->RemoveBool("LabelExpression"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docIconSize() { +const char* TreeParams::docIconSize() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getIconSize() { +const long& TreeParams::getIconSize() +{ return instance()->IconSize; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultIconSize() { +const long& TreeParams::defaultIconSize() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setIconSize(const long &v) { - instance()->handle->SetInt("IconSize",v); +void TreeParams::setIconSize(const long& v) +{ + instance()->handle->SetInt("IconSize", v); instance()->IconSize = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeIconSize() { +void TreeParams::removeIconSize() +{ instance()->handle->RemoveInt("IconSize"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docFontSize() { +const char* TreeParams::docFontSize() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getFontSize() { +const long& TreeParams::getFontSize() +{ return instance()->FontSize; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultFontSize() { +const long& TreeParams::defaultFontSize() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setFontSize(const long &v) { - instance()->handle->SetInt("FontSize",v); +void TreeParams::setFontSize(const long& v) +{ + instance()->handle->SetInt("FontSize", v); instance()->FontSize = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeFontSize() { +void TreeParams::removeFontSize() +{ instance()->handle->RemoveInt("FontSize"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docItemSpacing() { +const char* TreeParams::docItemSpacing() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getItemSpacing() { +const long& TreeParams::getItemSpacing() +{ return instance()->ItemSpacing; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultItemSpacing() { +const long& TreeParams::defaultItemSpacing() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setItemSpacing(const long &v) { - instance()->handle->SetInt("ItemSpacing",v); +void TreeParams::setItemSpacing(const long& v) +{ + instance()->handle->SetInt("ItemSpacing", v); instance()->ItemSpacing = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeItemSpacing() { +void TreeParams::removeItemSpacing() +{ instance()->handle->RemoveInt("ItemSpacing"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docItemBackground() { - return QT_TRANSLATE_NOOP("TreeParams", -"Tree view item background. Only effective in overlay."); +const char* TreeParams::docItemBackground() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Tree view item background. Only effective in overlay."); } // Auto generated code (Tools/params_utils.py:358) -const unsigned long & TreeParams::getItemBackground() { +const unsigned long& TreeParams::getItemBackground() +{ return instance()->ItemBackground; } // Auto generated code (Tools/params_utils.py:366) -const unsigned long & TreeParams::defaultItemBackground() { +const unsigned long& TreeParams::defaultItemBackground() +{ const static unsigned long def = 0x00000000; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setItemBackground(const unsigned long &v) { - instance()->handle->SetUnsigned("ItemBackground",v); +void TreeParams::setItemBackground(const unsigned long& v) +{ + instance()->handle->SetUnsigned("ItemBackground", v); instance()->ItemBackground = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeItemBackground() { +void TreeParams::removeItemBackground() +{ instance()->handle->RemoveUnsigned("ItemBackground"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docItemBackgroundPadding() { - return QT_TRANSLATE_NOOP("TreeParams", -"Tree view item background padding."); +const char* TreeParams::docItemBackgroundPadding() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Tree view item background padding."); } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getItemBackgroundPadding() { +const long& TreeParams::getItemBackgroundPadding() +{ return instance()->ItemBackgroundPadding; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultItemBackgroundPadding() { +const long& TreeParams::defaultItemBackgroundPadding() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setItemBackgroundPadding(const long &v) { - instance()->handle->SetInt("ItemBackgroundPadding",v); +void TreeParams::setItemBackgroundPadding(const long& v) +{ + instance()->handle->SetInt("ItemBackgroundPadding", v); instance()->ItemBackgroundPadding = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeItemBackgroundPadding() { +void TreeParams::removeItemBackgroundPadding() +{ instance()->handle->RemoveInt("ItemBackgroundPadding"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docHideColumn() { - return QT_TRANSLATE_NOOP("TreeParams", -"Hide extra tree view column for item description."); +const char* TreeParams::docHideColumn() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Hide extra tree view column for item description."); } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getHideColumn() { +const bool& TreeParams::getHideColumn() +{ return instance()->HideColumn; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultHideColumn() { +const bool& TreeParams::defaultHideColumn() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setHideColumn(const bool &v) { - instance()->handle->SetBool("HideColumn",v); +void TreeParams::setHideColumn(const bool& v) +{ + instance()->handle->SetBool("HideColumn", v); instance()->HideColumn = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeHideColumn() { +void TreeParams::removeHideColumn() +{ instance()->handle->RemoveBool("HideColumn"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docHideInternalNames() { - return QT_TRANSLATE_NOOP("TreeParams", -"Hide extra tree view column - Internal Names."); +const char* TreeParams::docHideInternalNames() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Hide extra tree view column - Internal Names."); } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getHideInternalNames() { +const bool& TreeParams::getHideInternalNames() +{ return instance()->HideInternalNames; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultHideInternalNames() { +const bool& TreeParams::defaultHideInternalNames() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setHideInternalNames(const bool &v) { - instance()->handle->SetBool("HideInternalNames",v); +void TreeParams::setHideInternalNames(const bool& v) +{ + instance()->handle->SetBool("HideInternalNames", v); instance()->HideInternalNames = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeHideInternalNames() { +void TreeParams::removeHideInternalNames() +{ instance()->handle->RemoveBool("HideInternalNames"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docHideScrollBar() { - return QT_TRANSLATE_NOOP("TreeParams", -"Hide tree view scroll bar in dock overlay."); +const char* TreeParams::docHideScrollBar() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Hide tree view scroll bar in dock overlay."); } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getHideScrollBar() { +const bool& TreeParams::getHideScrollBar() +{ return instance()->HideScrollBar; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultHideScrollBar() { +const bool& TreeParams::defaultHideScrollBar() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setHideScrollBar(const bool &v) { - instance()->handle->SetBool("HideScrollBar",v); +void TreeParams::setHideScrollBar(const bool& v) +{ + instance()->handle->SetBool("HideScrollBar", v); instance()->HideScrollBar = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeHideScrollBar() { +void TreeParams::removeHideScrollBar() +{ instance()->handle->RemoveBool("HideScrollBar"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docHideHeaderView() { - return QT_TRANSLATE_NOOP("TreeParams", -"Hide tree view header view in dock overlay."); +const char* TreeParams::docHideHeaderView() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Hide tree view header view in dock overlay."); } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getHideHeaderView() { +const bool& TreeParams::getHideHeaderView() +{ return instance()->HideHeaderView; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultHideHeaderView() { +const bool& TreeParams::defaultHideHeaderView() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setHideHeaderView(const bool &v) { - instance()->handle->SetBool("HideHeaderView",v); +void TreeParams::setHideHeaderView(const bool& v) +{ + instance()->handle->SetBool("HideHeaderView", v); instance()->HideHeaderView = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeHideHeaderView() { +void TreeParams::removeHideHeaderView() +{ instance()->handle->RemoveBool("HideHeaderView"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docResizableColumn() { - return QT_TRANSLATE_NOOP("TreeParams", -"Allow tree view columns to be manually resized."); +const char* TreeParams::docResizableColumn() +{ + return QT_TRANSLATE_NOOP("TreeParams", "Allow tree view columns to be manually resized."); } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getResizableColumn() { +const bool& TreeParams::getResizableColumn() +{ return instance()->ResizableColumn; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultResizableColumn() { +const bool& TreeParams::defaultResizableColumn() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setResizableColumn(const bool &v) { - instance()->handle->SetBool("ResizableColumn",v); +void TreeParams::setResizableColumn(const bool& v) +{ + instance()->handle->SetBool("ResizableColumn", v); instance()->ResizableColumn = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeResizableColumn() { +void TreeParams::removeResizableColumn() +{ instance()->handle->RemoveBool("ResizableColumn"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docColumnSize1() { +const char* TreeParams::docColumnSize1() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getColumnSize1() { +const long& TreeParams::getColumnSize1() +{ return instance()->ColumnSize1; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultColumnSize1() { +const long& TreeParams::defaultColumnSize1() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setColumnSize1(const long &v) { - instance()->handle->SetInt("ColumnSize1",v); +void TreeParams::setColumnSize1(const long& v) +{ + instance()->handle->SetInt("ColumnSize1", v); instance()->ColumnSize1 = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeColumnSize1() { +void TreeParams::removeColumnSize1() +{ instance()->handle->RemoveInt("ColumnSize1"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docColumnSize2() { +const char* TreeParams::docColumnSize2() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getColumnSize2() { +const long& TreeParams::getColumnSize2() +{ return instance()->ColumnSize2; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultColumnSize2() { +const long& TreeParams::defaultColumnSize2() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setColumnSize2(const long &v) { - instance()->handle->SetInt("ColumnSize2",v); +void TreeParams::setColumnSize2(const long& v) +{ + instance()->handle->SetInt("ColumnSize2", v); instance()->ColumnSize2 = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeColumnSize2() { +void TreeParams::removeColumnSize2() +{ instance()->handle->RemoveInt("ColumnSize2"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docColumnSize3() { +const char* TreeParams::docColumnSize3() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const long & TreeParams::getColumnSize3() { +const long& TreeParams::getColumnSize3() +{ return instance()->ColumnSize3; } // Auto generated code (Tools/params_utils.py:366) -const long & TreeParams::defaultColumnSize3() { +const long& TreeParams::defaultColumnSize3() +{ const static long def = 0; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setColumnSize3(const long &v) { - instance()->handle->SetInt("ColumnSize3",v); +void TreeParams::setColumnSize3(const long& v) +{ + instance()->handle->SetInt("ColumnSize3", v); instance()->ColumnSize3 = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeColumnSize3() { +void TreeParams::removeColumnSize3() +{ instance()->handle->RemoveInt("ColumnSize3"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docTreeToolTipIcon() { +const char* TreeParams::docTreeToolTipIcon() +{ return ""; } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getTreeToolTipIcon() { +const bool& TreeParams::getTreeToolTipIcon() +{ return instance()->TreeToolTipIcon; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultTreeToolTipIcon() { +const bool& TreeParams::defaultTreeToolTipIcon() +{ const static bool def = false; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setTreeToolTipIcon(const bool &v) { - instance()->handle->SetBool("TreeToolTipIcon",v); +void TreeParams::setTreeToolTipIcon(const bool& v) +{ + instance()->handle->SetBool("TreeToolTipIcon", v); instance()->TreeToolTipIcon = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeTreeToolTipIcon() { +void TreeParams::removeTreeToolTipIcon() +{ instance()->handle->RemoveBool("TreeToolTipIcon"); } // Auto generated code (Tools/params_utils.py:350) -const char *TreeParams::docVisibilityIcon() { - return QT_TRANSLATE_NOOP("TreeParams", -"Displays an eye icon in front of the tree view items, showing the items visibility status. When clicked the visibility is toggled"); +const char* TreeParams::docVisibilityIcon() +{ + return QT_TRANSLATE_NOOP( + "TreeParams", + "Displays an eye icon in front of the tree view items, showing the items visibility " + "status. When clicked the visibility is toggled" + ); } // Auto generated code (Tools/params_utils.py:358) -const bool & TreeParams::getVisibilityIcon() { +const bool& TreeParams::getVisibilityIcon() +{ return instance()->VisibilityIcon; } // Auto generated code (Tools/params_utils.py:366) -const bool & TreeParams::defaultVisibilityIcon() { +const bool& TreeParams::defaultVisibilityIcon() +{ const static bool def = true; return def; } // Auto generated code (Tools/params_utils.py:375) -void TreeParams::setVisibilityIcon(const bool &v) { - instance()->handle->SetBool("VisibilityIcon",v); +void TreeParams::setVisibilityIcon(const bool& v) +{ + instance()->handle->SetBool("VisibilityIcon", v); instance()->VisibilityIcon = v; } // Auto generated code (Tools/params_utils.py:384) -void TreeParams::removeVisibilityIcon() { +void TreeParams::removeVisibilityIcon() +{ instance()->handle->RemoveBool("VisibilityIcon"); } //[[[end]]] -void TreeParams::onSyncSelectionChanged() { - if(!TreeParams::getSyncSelection() || !Gui::Selection().hasSelection()) +void TreeParams::onSyncSelectionChanged() +{ + if (!TreeParams::getSyncSelection() || !Gui::Selection().hasSelection()) { return; + } TreeWidget::scrollItemToTop(); } @@ -1507,27 +1748,33 @@ void TreeParams::onCheckBoxesSelectionChanged() TreeWidget::synchronizeSelectionCheckBoxes(); } -void TreeParams::onDocumentModeChanged() { +void TreeParams::onDocumentModeChanged() +{ App::GetApplication().setActiveDocument(App::GetApplication().getActiveDocument()); } -void TreeParams::onResizableColumnChanged() { +void TreeParams::onResizableColumnChanged() +{ TreeWidget::setupResizableColumn(); } -void TreeParams::onIconSizeChanged() { +void TreeParams::onIconSizeChanged() +{ auto tree = TreeWidget::instance(); - if (tree) + if (tree) { tree->setIconHeight(TreeParams::getIconSize()); + } } -void TreeParams::onFontSizeChanged() { +void TreeParams::onFontSizeChanged() +{ int fontSize = TreeParams::getFontSize(); - if (fontSize <= 0) + if (fontSize <= 0) { return; - for(auto tree : TreeWidget::Instances) { + } + for (auto tree : TreeWidget::Instances) { QFont font = tree->font(); - font.setPointSize(std::max(8,fontSize)); + font.setPointSize(std::max(8, fontSize)); tree->setFont(font); } } @@ -1539,7 +1786,7 @@ void TreeParams::onItemSpacingChanged() void TreeParams::refreshTreeViews() { - for(auto tree : TreeWidget::Instances) { + for (auto tree : TreeWidget::Instances) { tree->scheduleDelayedItemsLayout(); } } @@ -1586,20 +1833,23 @@ void TreeParams::onIndentationChanged() void TreeParams::onItemBackgroundPaddingChanged() { - if (getItemBackground()) + if (getItemBackground()) { refreshTreeViews(); + } } void TreeParams::onHideColumnChanged() { - for(auto tree : TreeWidget::Instances) + for (auto tree : TreeWidget::Instances) { tree->setColumnHidden(1, TreeParams::getHideColumn()); + } } void TreeParams::onHideInternalNamesChanged() { - for(auto tree : TreeWidget::Instances) + for (auto tree : TreeWidget::Instances) { tree->setColumnHidden(2, TreeParams::getHideInternalNames()); + } } void TreeParams::onVisibilityIconChanged() diff --git a/src/Gui/TreeParams.h b/src/Gui/TreeParams.h index 71dd0b5294..4ac814a2f2 100644 --- a/src/Gui/TreeParams.h +++ b/src/Gui/TreeParams.h @@ -33,7 +33,8 @@ TreeParams.declare_begin() // Auto generated code (Tools/params_utils.py:90) -namespace Gui { +namespace Gui +{ /** Convenient class to obtain tree view related parameters * The parameters are under group "User parameter:BaseApp/Preferences/TreeView" @@ -64,291 +65,292 @@ namespace Gui { * void TreeParams:onChanged() * @endcode */ -class GuiExport TreeParams { +class GuiExport TreeParams +{ public: static ParameterGrp::handle getHandle(); // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter SyncSelection - static const bool & getSyncSelection(); - static const bool & defaultSyncSelection(); + static const bool& getSyncSelection(); + static const bool& defaultSyncSelection(); static void removeSyncSelection(); - static void setSyncSelection(const bool &v); - static const char *docSyncSelection(); + static void setSyncSelection(const bool& v); + static const char* docSyncSelection(); static void onSyncSelectionChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter CheckBoxesSelection - static const bool & getCheckBoxesSelection(); - static const bool & defaultCheckBoxesSelection(); + static const bool& getCheckBoxesSelection(); + static const bool& defaultCheckBoxesSelection(); static void removeCheckBoxesSelection(); - static void setCheckBoxesSelection(const bool &v); - static const char *docCheckBoxesSelection(); + static void setCheckBoxesSelection(const bool& v); + static const char* docCheckBoxesSelection(); static void onCheckBoxesSelectionChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter SyncView - static const bool & getSyncView(); - static const bool & defaultSyncView(); + static const bool& getSyncView(); + static const bool& defaultSyncView(); static void removeSyncView(); - static void setSyncView(const bool &v); - static const char *docSyncView(); + static void setSyncView(const bool& v); + static const char* docSyncView(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter PreSelection - static const bool & getPreSelection(); - static const bool & defaultPreSelection(); + static const bool& getPreSelection(); + static const bool& defaultPreSelection(); static void removePreSelection(); - static void setPreSelection(const bool &v); - static const char *docPreSelection(); + static void setPreSelection(const bool& v); + static const char* docPreSelection(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter SyncPlacement - static const bool & getSyncPlacement(); - static const bool & defaultSyncPlacement(); + static const bool& getSyncPlacement(); + static const bool& defaultSyncPlacement(); static void removeSyncPlacement(); - static void setSyncPlacement(const bool &v); - static const char *docSyncPlacement(); + static void setSyncPlacement(const bool& v); + static const char* docSyncPlacement(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter RecordSelection - static const bool & getRecordSelection(); - static const bool & defaultRecordSelection(); + static const bool& getRecordSelection(); + static const bool& defaultRecordSelection(); static void removeRecordSelection(); - static void setRecordSelection(const bool &v); - static const char *docRecordSelection(); + static void setRecordSelection(const bool& v); + static const char* docRecordSelection(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter DocumentMode - static const long & getDocumentMode(); - static const long & defaultDocumentMode(); + static const long& getDocumentMode(); + static const long& defaultDocumentMode(); static void removeDocumentMode(); - static void setDocumentMode(const long &v); - static const char *docDocumentMode(); + static void setDocumentMode(const long& v); + static const char* docDocumentMode(); static void onDocumentModeChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter StatusTimeout - static const long & getStatusTimeout(); - static const long & defaultStatusTimeout(); + static const long& getStatusTimeout(); + static const long& defaultStatusTimeout(); static void removeStatusTimeout(); - static void setStatusTimeout(const long &v); - static const char *docStatusTimeout(); + static void setStatusTimeout(const long& v); + static const char* docStatusTimeout(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter SelectionTimeout - static const long & getSelectionTimeout(); - static const long & defaultSelectionTimeout(); + static const long& getSelectionTimeout(); + static const long& defaultSelectionTimeout(); static void removeSelectionTimeout(); - static void setSelectionTimeout(const long &v); - static const char *docSelectionTimeout(); + static void setSelectionTimeout(const long& v); + static const char* docSelectionTimeout(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter PreSelectionTimeout - static const long & getPreSelectionTimeout(); - static const long & defaultPreSelectionTimeout(); + static const long& getPreSelectionTimeout(); + static const long& defaultPreSelectionTimeout(); static void removePreSelectionTimeout(); - static void setPreSelectionTimeout(const long &v); - static const char *docPreSelectionTimeout(); + static void setPreSelectionTimeout(const long& v); + static const char* docPreSelectionTimeout(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter PreSelectionDelay - static const long & getPreSelectionDelay(); - static const long & defaultPreSelectionDelay(); + static const long& getPreSelectionDelay(); + static const long& defaultPreSelectionDelay(); static void removePreSelectionDelay(); - static void setPreSelectionDelay(const long &v); - static const char *docPreSelectionDelay(); + static void setPreSelectionDelay(const long& v); + static const char* docPreSelectionDelay(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter PreSelectionMinDelay - static const long & getPreSelectionMinDelay(); - static const long & defaultPreSelectionMinDelay(); + static const long& getPreSelectionMinDelay(); + static const long& defaultPreSelectionMinDelay(); static void removePreSelectionMinDelay(); - static void setPreSelectionMinDelay(const long &v); - static const char *docPreSelectionMinDelay(); + static void setPreSelectionMinDelay(const long& v); + static const char* docPreSelectionMinDelay(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter RecomputeOnDrop - static const bool & getRecomputeOnDrop(); - static const bool & defaultRecomputeOnDrop(); + static const bool& getRecomputeOnDrop(); + static const bool& defaultRecomputeOnDrop(); static void removeRecomputeOnDrop(); - static void setRecomputeOnDrop(const bool &v); - static const char *docRecomputeOnDrop(); + static void setRecomputeOnDrop(const bool& v); + static const char* docRecomputeOnDrop(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter KeepRootOrder - static const bool & getKeepRootOrder(); - static const bool & defaultKeepRootOrder(); + static const bool& getKeepRootOrder(); + static const bool& defaultKeepRootOrder(); static void removeKeepRootOrder(); - static void setKeepRootOrder(const bool &v); - static const char *docKeepRootOrder(); + static void setKeepRootOrder(const bool& v); + static const char* docKeepRootOrder(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeActiveAutoExpand - static const bool & getTreeActiveAutoExpand(); - static const bool & defaultTreeActiveAutoExpand(); + static const bool& getTreeActiveAutoExpand(); + static const bool& defaultTreeActiveAutoExpand(); static void removeTreeActiveAutoExpand(); - static void setTreeActiveAutoExpand(const bool &v); - static const char *docTreeActiveAutoExpand(); + static void setTreeActiveAutoExpand(const bool& v); + static const char* docTreeActiveAutoExpand(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeActiveColor - static const unsigned long & getTreeActiveColor(); - static const unsigned long & defaultTreeActiveColor(); + static const unsigned long& getTreeActiveColor(); + static const unsigned long& defaultTreeActiveColor(); static void removeTreeActiveColor(); - static void setTreeActiveColor(const unsigned long &v); - static const char *docTreeActiveColor(); + static void setTreeActiveColor(const unsigned long& v); + static const char* docTreeActiveColor(); static void onTreeActiveColorChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeEditColor - static const unsigned long & getTreeEditColor(); - static const unsigned long & defaultTreeEditColor(); + static const unsigned long& getTreeEditColor(); + static const unsigned long& defaultTreeEditColor(); static void removeTreeEditColor(); - static void setTreeEditColor(const unsigned long &v); - static const char *docTreeEditColor(); + static void setTreeEditColor(const unsigned long& v); + static const char* docTreeEditColor(); static void onTreeEditColorChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter SelectingGroupColor - static const unsigned long & getSelectingGroupColor(); - static const unsigned long & defaultSelectingGroupColor(); + static const unsigned long& getSelectingGroupColor(); + static const unsigned long& defaultSelectingGroupColor(); static void removeSelectingGroupColor(); - static void setSelectingGroupColor(const unsigned long &v); - static const char *docSelectingGroupColor(); + static void setSelectingGroupColor(const unsigned long& v); + static const char* docSelectingGroupColor(); static void onSelectingGroupColorChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeActiveBold - static const bool & getTreeActiveBold(); - static const bool & defaultTreeActiveBold(); + static const bool& getTreeActiveBold(); + static const bool& defaultTreeActiveBold(); static void removeTreeActiveBold(); - static void setTreeActiveBold(const bool &v); - static const char *docTreeActiveBold(); + static void setTreeActiveBold(const bool& v); + static const char* docTreeActiveBold(); static void onTreeActiveBoldChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeActiveItalic - static const bool & getTreeActiveItalic(); - static const bool & defaultTreeActiveItalic(); + static const bool& getTreeActiveItalic(); + static const bool& defaultTreeActiveItalic(); static void removeTreeActiveItalic(); - static void setTreeActiveItalic(const bool &v); - static const char *docTreeActiveItalic(); + static void setTreeActiveItalic(const bool& v); + static const char* docTreeActiveItalic(); static void onTreeActiveItalicChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeActiveUnderlined - static const bool & getTreeActiveUnderlined(); - static const bool & defaultTreeActiveUnderlined(); + static const bool& getTreeActiveUnderlined(); + static const bool& defaultTreeActiveUnderlined(); static void removeTreeActiveUnderlined(); - static void setTreeActiveUnderlined(const bool &v); - static const char *docTreeActiveUnderlined(); + static void setTreeActiveUnderlined(const bool& v); + static const char* docTreeActiveUnderlined(); static void onTreeActiveUnderlinedChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeActiveOverlined - static const bool & getTreeActiveOverlined(); - static const bool & defaultTreeActiveOverlined(); + static const bool& getTreeActiveOverlined(); + static const bool& defaultTreeActiveOverlined(); static void removeTreeActiveOverlined(); - static void setTreeActiveOverlined(const bool &v); - static const char *docTreeActiveOverlined(); + static void setTreeActiveOverlined(const bool& v); + static const char* docTreeActiveOverlined(); static void onTreeActiveOverlinedChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter Indentation - static const long & getIndentation(); - static const long & defaultIndentation(); + static const long& getIndentation(); + static const long& defaultIndentation(); static void removeIndentation(); - static void setIndentation(const long &v); - static const char *docIndentation(); + static void setIndentation(const long& v); + static const char* docIndentation(); static void onIndentationChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter LabelExpression - static const bool & getLabelExpression(); - static const bool & defaultLabelExpression(); + static const bool& getLabelExpression(); + static const bool& defaultLabelExpression(); static void removeLabelExpression(); - static void setLabelExpression(const bool &v); - static const char *docLabelExpression(); + static void setLabelExpression(const bool& v); + static const char* docLabelExpression(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter IconSize - static const long & getIconSize(); - static const long & defaultIconSize(); + static const long& getIconSize(); + static const long& defaultIconSize(); static void removeIconSize(); - static void setIconSize(const long &v); - static const char *docIconSize(); + static void setIconSize(const long& v); + static const char* docIconSize(); static void onIconSizeChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter FontSize - static const long & getFontSize(); - static const long & defaultFontSize(); + static const long& getFontSize(); + static const long& defaultFontSize(); static void removeFontSize(); - static void setFontSize(const long &v); - static const char *docFontSize(); + static void setFontSize(const long& v); + static const char* docFontSize(); static void onFontSizeChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter ItemSpacing - static const long & getItemSpacing(); - static const long & defaultItemSpacing(); + static const long& getItemSpacing(); + static const long& defaultItemSpacing(); static void removeItemSpacing(); - static void setItemSpacing(const long &v); - static const char *docItemSpacing(); + static void setItemSpacing(const long& v); + static const char* docItemSpacing(); static void onItemSpacingChanged(); //@} @@ -357,11 +359,11 @@ public: /// Accessor for parameter ItemBackground /// /// Tree view item background. Only effective in overlay. - static const unsigned long & getItemBackground(); - static const unsigned long & defaultItemBackground(); + static const unsigned long& getItemBackground(); + static const unsigned long& defaultItemBackground(); static void removeItemBackground(); - static void setItemBackground(const unsigned long &v); - static const char *docItemBackground(); + static void setItemBackground(const unsigned long& v); + static const char* docItemBackground(); static void onItemBackgroundChanged(); //@} @@ -370,11 +372,11 @@ public: /// Accessor for parameter ItemBackgroundPadding /// /// Tree view item background padding. - static const long & getItemBackgroundPadding(); - static const long & defaultItemBackgroundPadding(); + static const long& getItemBackgroundPadding(); + static const long& defaultItemBackgroundPadding(); static void removeItemBackgroundPadding(); - static void setItemBackgroundPadding(const long &v); - static const char *docItemBackgroundPadding(); + static void setItemBackgroundPadding(const long& v); + static const char* docItemBackgroundPadding(); static void onItemBackgroundPaddingChanged(); //@} @@ -383,11 +385,11 @@ public: /// Accessor for parameter HideColumn /// /// Hide extra tree view column for item description. - static const bool & getHideColumn(); - static const bool & defaultHideColumn(); + static const bool& getHideColumn(); + static const bool& defaultHideColumn(); static void removeHideColumn(); - static void setHideColumn(const bool &v); - static const char *docHideColumn(); + static void setHideColumn(const bool& v); + static const char* docHideColumn(); static void onHideColumnChanged(); //@} @@ -396,11 +398,11 @@ public: /// Accessor for parameter HideInternalNames /// /// Hide extra tree view column - Internal Names. - static const bool & getHideInternalNames(); - static const bool & defaultHideInternalNames(); + static const bool& getHideInternalNames(); + static const bool& defaultHideInternalNames(); static void removeHideInternalNames(); - static void setHideInternalNames(const bool &v); - static const char *docHideInternalNames(); + static void setHideInternalNames(const bool& v); + static const char* docHideInternalNames(); static void onHideInternalNamesChanged(); //@} @@ -409,11 +411,11 @@ public: /// Accessor for parameter HideScrollBar /// /// Hide tree view scroll bar in dock overlay. - static const bool & getHideScrollBar(); - static const bool & defaultHideScrollBar(); + static const bool& getHideScrollBar(); + static const bool& defaultHideScrollBar(); static void removeHideScrollBar(); - static void setHideScrollBar(const bool &v); - static const char *docHideScrollBar(); + static void setHideScrollBar(const bool& v); + static const char* docHideScrollBar(); //@} // Auto generated code (Tools/params_utils.py:138) @@ -421,11 +423,11 @@ public: /// Accessor for parameter HideHeaderView /// /// Hide tree view header view in dock overlay. - static const bool & getHideHeaderView(); - static const bool & defaultHideHeaderView(); + static const bool& getHideHeaderView(); + static const bool& defaultHideHeaderView(); static void removeHideHeaderView(); - static void setHideHeaderView(const bool &v); - static const char *docHideHeaderView(); + static void setHideHeaderView(const bool& v); + static const char* docHideHeaderView(); //@} // Auto generated code (Tools/params_utils.py:138) @@ -433,77 +435,78 @@ public: /// Accessor for parameter ResizableColumn /// /// Allow tree view columns to be manually resized. - static const bool & getResizableColumn(); - static const bool & defaultResizableColumn(); + static const bool& getResizableColumn(); + static const bool& defaultResizableColumn(); static void removeResizableColumn(); - static void setResizableColumn(const bool &v); - static const char *docResizableColumn(); + static void setResizableColumn(const bool& v); + static const char* docResizableColumn(); static void onResizableColumnChanged(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter ColumnSize1 - static const long & getColumnSize1(); - static const long & defaultColumnSize1(); + static const long& getColumnSize1(); + static const long& defaultColumnSize1(); static void removeColumnSize1(); - static void setColumnSize1(const long &v); - static const char *docColumnSize1(); + static void setColumnSize1(const long& v); + static const char* docColumnSize1(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter ColumnSize2 - static const long & getColumnSize2(); - static const long & defaultColumnSize2(); + static const long& getColumnSize2(); + static const long& defaultColumnSize2(); static void removeColumnSize2(); - static void setColumnSize2(const long &v); - static const char *docColumnSize2(); + static void setColumnSize2(const long& v); + static const char* docColumnSize2(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter ColumnSize3 - static const long & getColumnSize3(); - static const long & defaultColumnSize3(); + static const long& getColumnSize3(); + static const long& defaultColumnSize3(); static void removeColumnSize3(); - static void setColumnSize3(const long &v); - static const char *docColumnSize3(); + static void setColumnSize3(const long& v); + static const char* docColumnSize3(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter TreeToolTipIcon - static const bool & getTreeToolTipIcon(); - static const bool & defaultTreeToolTipIcon(); + static const bool& getTreeToolTipIcon(); + static const bool& defaultTreeToolTipIcon(); static void removeTreeToolTipIcon(); - static void setTreeToolTipIcon(const bool &v); - static const char *docTreeToolTipIcon(); + static void setTreeToolTipIcon(const bool& v); + static const char* docTreeToolTipIcon(); //@} // Auto generated code (Tools/params_utils.py:138) //@{ /// Accessor for parameter VisibilityIcon /// - /// If enabled, show an eye icon before the tree view items, showing the items visibility status. When clicked the visibility is toggled - static const bool & getVisibilityIcon(); - static const bool & defaultVisibilityIcon(); + /// If enabled, show an eye icon before the tree view items, showing the items visibility + /// status. When clicked the visibility is toggled + static const bool& getVisibilityIcon(); + static const bool& defaultVisibilityIcon(); static void removeVisibilityIcon(); - static void setVisibilityIcon(const bool &v); - static const char *docVisibilityIcon(); + static void setVisibilityIcon(const bool& v); + static const char* docVisibilityIcon(); static void onVisibilityIconChanged(); //@} -//[[[end]]] + //[[[end]]] static void refreshTreeViews(); -/*[[[cog -TreeParams.declare_end() -]]]*/ + /*[[[cog + TreeParams.declare_end() + ]]]*/ -// Auto generated code (Tools/params_utils.py:178) -}; // class TreeParams -} // namespace Gui + // Auto generated code (Tools/params_utils.py:178) +}; // class TreeParams +} // namespace Gui //[[[end]]] -#endif // GUI_TREE_PARAMS_H +#endif // GUI_TREE_PARAMS_H diff --git a/src/Gui/TreeParams.py b/src/Gui/TreeParams.py index 58442d5350..0465c251ed 100644 --- a/src/Gui/TreeParams.py +++ b/src/Gui/TreeParams.py @@ -18,81 +18,138 @@ # * USA * # * * # *************************************************************************** -'''Auto code generator for parameters in Preferences/TreeView -''' +"""Auto code generator for parameters in Preferences/TreeView""" import sys from os import sys, path # import Tools/params_utils.py -sys.path.append(path.join(path.dirname(path.dirname(path.abspath(__file__))), 'Tools')) +sys.path.append(path.join(path.dirname(path.dirname(path.abspath(__file__))), "Tools")) import params_utils -from params_utils import ParamBool, ParamInt, ParamString, ParamUInt,\ - ParamFloat, ParamSpinBox, ParamColor, ParamHex +from params_utils import ( + ParamBool, + ParamInt, + ParamString, + ParamUInt, + ParamFloat, + ParamSpinBox, + ParamColor, + ParamHex, +) -NameSpace = 'Gui' -ClassName = 'TreeParams' -ParamPath = 'User parameter:BaseApp/Preferences/TreeView' -ClassDoc = 'Convenient class to obtain tree view related parameters' -SourceFile = 'Tree.cpp' +NameSpace = "Gui" +ClassName = "TreeParams" +ParamPath = "User parameter:BaseApp/Preferences/TreeView" +ClassDoc = "Convenient class to obtain tree view related parameters" +SourceFile = "Tree.cpp" Params = [ - ParamBool('SyncSelection', True, on_change=True), - ParamBool('CheckBoxesSelection',False, on_change=True, title="Show item checkbox"), - ParamBool('SyncView', True), - ParamBool('PreSelection', True), - ParamBool('SyncPlacement', False), - ParamBool('RecordSelection', True), - ParamInt('DocumentMode', 2, on_change=True), - ParamInt('StatusTimeout', 100), - ParamInt('SelectionTimeout', 100), - ParamInt('PreSelectionTimeout', 500), - ParamInt('PreSelectionDelay', 700), - ParamInt('PreSelectionMinDelay', 200), - ParamBool('RecomputeOnDrop', True), - ParamBool('KeepRootOrder', True), - ParamBool('TreeActiveAutoExpand', True), - ParamUInt('TreeActiveColor', 0xe6e6ffff, on_change=True), - ParamUInt('TreeEditColor', 0x929200ff, on_change=True), - ParamUInt('SelectingGroupColor', 0x408081ff, on_change=True), - ParamBool('TreeActiveBold', True, on_change=True), - ParamBool('TreeActiveItalic', False, on_change=True), - ParamBool('TreeActiveUnderlined', False, on_change=True), - ParamBool('TreeActiveOverlined', False, on_change=True), - ParamInt('Indentation', 0, on_change=True), - ParamBool('LabelExpression', False), - ParamInt('IconSize', 0, on_change=True), - ParamInt('FontSize', 0, on_change=True, title='Font size', proxy=ParamSpinBox(0, 100, 1, suffix=" pt")), - ParamInt('ItemSpacing', 0, on_change=True), - ParamHex('ItemBackground', 0, on_change=True, title='Item background color', proxy=ParamColor(), - doc = "Tree view item background. Only effective in overlay."), - ParamInt('ItemBackgroundPadding', 0, on_change=True, title="Item background padding", proxy=ParamSpinBox(0, 100, 1, suffix=" px"), - doc = "Tree view item background padding."), - ParamBool('HideColumn', True, on_change=True, title="Hide Description", - doc = "Hide extra tree view column for item description."), - ParamBool('HideInternalNames', True, on_change=True, title="Hide Internal Names", - doc = "Hide extra tree view column - Internal Names."), - ParamBool('HideScrollBar', True, title="Hide scroll bar", - doc = "Hide tree view scroll bar in dock overlay."), - ParamBool('HideHeaderView', True, title="Hide header", - doc = "Hide tree view header view in dock overlay."), - ParamBool('ResizableColumn', False, on_change=True, title="Resizable columns", - doc = "Allow tree view columns to be manually resized."), - ParamInt('ColumnSize1', 0), - ParamInt('ColumnSize2', 0), - ParamInt('ColumnSize3', 0), - ParamBool('TreeToolTipIcon', False, title='Show icon in tool tip'), - ParamBool('VisibilityIcon', True, on_change=True, title='Show visibility icon', - doc = "Displays an eye icon in front of the tree view items, showing the items visibility status. When clicked the visibility is toggled"), + ParamBool("SyncSelection", True, on_change=True), + ParamBool("CheckBoxesSelection", False, on_change=True, title="Show item checkbox"), + ParamBool("SyncView", True), + ParamBool("PreSelection", True), + ParamBool("SyncPlacement", False), + ParamBool("RecordSelection", True), + ParamInt("DocumentMode", 2, on_change=True), + ParamInt("StatusTimeout", 100), + ParamInt("SelectionTimeout", 100), + ParamInt("PreSelectionTimeout", 500), + ParamInt("PreSelectionDelay", 700), + ParamInt("PreSelectionMinDelay", 200), + ParamBool("RecomputeOnDrop", True), + ParamBool("KeepRootOrder", True), + ParamBool("TreeActiveAutoExpand", True), + ParamUInt("TreeActiveColor", 0xE6E6FFFF, on_change=True), + ParamUInt("TreeEditColor", 0x929200FF, on_change=True), + ParamUInt("SelectingGroupColor", 0x408081FF, on_change=True), + ParamBool("TreeActiveBold", True, on_change=True), + ParamBool("TreeActiveItalic", False, on_change=True), + ParamBool("TreeActiveUnderlined", False, on_change=True), + ParamBool("TreeActiveOverlined", False, on_change=True), + ParamInt("Indentation", 0, on_change=True), + ParamBool("LabelExpression", False), + ParamInt("IconSize", 0, on_change=True), + ParamInt( + "FontSize", + 0, + on_change=True, + title="Font size", + proxy=ParamSpinBox(0, 100, 1, suffix=" pt"), + ), + ParamInt("ItemSpacing", 0, on_change=True), + ParamHex( + "ItemBackground", + 0, + on_change=True, + title="Item background color", + proxy=ParamColor(), + doc="Tree view item background. Only effective in overlay.", + ), + ParamInt( + "ItemBackgroundPadding", + 0, + on_change=True, + title="Item background padding", + proxy=ParamSpinBox(0, 100, 1, suffix=" px"), + doc="Tree view item background padding.", + ), + ParamBool( + "HideColumn", + True, + on_change=True, + title="Hide Description", + doc="Hide extra tree view column for item description.", + ), + ParamBool( + "HideInternalNames", + True, + on_change=True, + title="Hide Internal Names", + doc="Hide extra tree view column - Internal Names.", + ), + ParamBool( + "HideScrollBar", + True, + title="Hide scroll bar", + doc="Hide tree view scroll bar in dock overlay.", + ), + ParamBool( + "HideHeaderView", + True, + title="Hide header", + doc="Hide tree view header view in dock overlay.", + ), + ParamBool( + "ResizableColumn", + False, + on_change=True, + title="Resizable columns", + doc="Allow tree view columns to be manually resized.", + ), + ParamInt("ColumnSize1", 0), + ParamInt("ColumnSize2", 0), + ParamInt("ColumnSize3", 0), + ParamBool("TreeToolTipIcon", False, title="Show icon in tool tip"), + ParamBool( + "VisibilityIcon", + True, + on_change=True, + title="Show visibility icon", + doc="Displays an eye icon in front of the tree view items, showing the items visibility status. When clicked the visibility is toggled", + ), ] + def declare_begin(): params_utils.declare_begin(sys.modules[__name__]) + def declare_end(): params_utils.declare_end(sys.modules[__name__]) + def define(): params_utils.define(sys.modules[__name__]) + params_utils.init_params(Params, NameSpace, ClassName, ParamPath) diff --git a/src/Gui/TreeView.cpp b/src/Gui/TreeView.cpp index caeb8870bc..56b58cc163 100644 --- a/src/Gui/TreeView.cpp +++ b/src/Gui/TreeView.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include "TreeView.h" @@ -36,50 +35,53 @@ using namespace Gui; TreeView::TreeView(QWidget* parent) - : QTreeView(parent) + : QTreeView(parent) { setModel(new DocumentModel(this)); - QModelIndex root = this->model()->index(0,0,QModelIndex()); + QModelIndex root = this->model()->index(0, 0, QModelIndex()); this->setExpanded(root, true); this->setDragEnabled(true); this->setAcceptDrops(true); this->setDropIndicatorShown(false); this->setRootIsDecorated(false); this->setSelectionMode(QAbstractItemView::ExtendedSelection); - this->setMouseTracking(true); // needed for itemEntered() to work + this->setMouseTracking(true); // needed for itemEntered() to work } TreeView::~TreeView() = default; -void TreeView::mouseDoubleClickEvent (QMouseEvent * event) +void TreeView::mouseDoubleClickEvent(QMouseEvent* event) { QModelIndex index = indexAt(event->pos()); - if (!index.isValid() || index.internalPointer() == Application::Instance) + if (!index.isValid() || index.internalPointer() == Application::Instance) { return; + } Base::BaseClass* item = nullptr; item = static_cast(index.internalPointer()); if (item->is()) { QTreeView::mouseDoubleClickEvent(event); const Gui::Document* doc = static_cast(item); - MDIView *view = doc->getActiveView(); - if (!view) + MDIView* view = doc->getActiveView(); + if (!view) { return; + } getMainWindow()->setActiveWindow(view); } else if (item->isDerivedFrom()) { - if (!static_cast(item)->doubleClicked()) + if (!static_cast(item)->doubleClicked()) { QTreeView::mouseDoubleClickEvent(event); + } } } -void TreeView::rowsInserted (const QModelIndex & parent, int start, int end) +void TreeView::rowsInserted(const QModelIndex& parent, int start, int end) { QTreeView::rowsInserted(parent, start, end); if (parent.isValid()) { auto ptr = static_cast(parent.internalPointer()); // type is defined in DocumentModel.cpp if (ptr->getTypeId() == Base::Type::fromName("Gui::ApplicationIndex")) { - for (int i=start; i<=end;i++) { + for (int i = start; i <= end; i++) { QModelIndex document = this->model()->index(i, 0, parent); this->expand(document); } @@ -88,4 +90,3 @@ void TreeView::rowsInserted (const QModelIndex & parent, int start, int end) } #include "moc_TreeView.cpp" - diff --git a/src/Gui/TreeView.h b/src/Gui/TreeView.h index 778968855f..3c53de1237 100644 --- a/src/Gui/TreeView.h +++ b/src/Gui/TreeView.h @@ -27,23 +27,23 @@ #include #include -namespace Gui { +namespace Gui +{ -class GuiExport TreeView : public QTreeView +class GuiExport TreeView: public QTreeView { Q_OBJECT public: - TreeView(QWidget* parent=nullptr); + TreeView(QWidget* parent = nullptr); ~TreeView() override; protected: - void mouseDoubleClickEvent (QMouseEvent * ) override; - void rowsInserted (const QModelIndex & parent, int start, int end) override; + void mouseDoubleClickEvent(QMouseEvent*) override; + void rowsInserted(const QModelIndex& parent, int start, int end) override; }; -} +} // namespace Gui -#endif // GUI_TREEVIEW_H - +#endif // GUI_TREEVIEW_H diff --git a/src/Gui/UiLoader.cpp b/src/Gui/UiLoader.cpp index 7545176b0d..d5eeabb1eb 100644 --- a/src/Gui/UiLoader.cpp +++ b/src/Gui/UiLoader.cpp @@ -21,13 +21,13 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -40,19 +40,25 @@ using namespace Gui; -namespace { +namespace +{ -QWidget* createFromWidgetFactory(const QString & className, QWidget * parent, const QString& name) +QWidget* createFromWidgetFactory(const QString& className, QWidget* parent, const QString& name) { QWidget* widget = nullptr; - if (WidgetFactory().CanProduce((const char*)className.toLatin1())) + if (WidgetFactory().CanProduce((const char*)className.toLatin1())) { widget = WidgetFactory().createWidget((const char*)className.toLatin1(), parent); - if (widget) + } + if (widget) { widget->setObjectName(name); + } return widget; } -Py::Object wrapFromWidgetFactory(const Py::Tuple& args, const std::function & callableFunc) +Py::Object wrapFromWidgetFactory( + const Py::Tuple& args, + const std::function& callableFunc +) { Gui::PythonWrapper wrap; @@ -64,8 +70,9 @@ Py::Object wrapFromWidgetFactory(const Py::Tuple& args, const std::function 1) { QObject* object = wrap.toQObject(args[1]); - if (object) + if (object) { parent = qobject_cast(object); + } } // 3rd argument @@ -75,14 +82,17 @@ Py::Object wrapFromWidgetFactory(const Py::Tuple& args, const std::function("PySideUic") + : Py::ExtensionModule("PySideUic") { - add_varargs_method("loadUiType",&PySideUicModule::loadUiType, - "PySide lacks the \"loadUiType\" command, so we have to convert the ui file to py code in-memory first\n" - "and then execute it in a special frame to retrieve the form_class."); - add_varargs_method("loadUi",&PySideUicModule::loadUi, - "Addition of \"loadUi\" to PySide."); - add_varargs_method("createCustomWidget",&PySideUicModule::createCustomWidget, - "Create custom widgets."); - initialize("PySideUic helper module"); // register with Python + add_varargs_method( + "loadUiType", + &PySideUicModule::loadUiType, + "PySide lacks the \"loadUiType\" command, so we have to convert the ui file to py code " + "in-memory first\n" + "and then execute it in a special frame to retrieve the form_class." + ); + add_varargs_method("loadUi", &PySideUicModule::loadUi, "Addition of \"loadUi\" to PySide."); + add_varargs_method( + "createCustomWidget", + &PySideUicModule::createCustomWidget, + "Create custom widgets." + ); + initialize("PySideUic helper module"); // register with Python } Py::Object PySideUicModule::loadUiType(const Py::Tuple& args) @@ -165,10 +181,12 @@ Py::Object PySideUicModule::loadUi(const Py::Tuple& args) PyObject* dict = PyModule_GetDict(main); Py::Dict d(PyDict_Copy(dict), true); d.setItem("uiFile_", args[0]); - if (args.size() > 1) + if (args.size() > 1) { d.setItem("base_", args[1]); - else + } + else { d.setItem("base_", Py::None()); + } QString cmd; QTextStream str(&cmd); @@ -202,13 +220,13 @@ Py::Object PySideUicModule::createCustomWidget(const Py::Tuple& args) // ---------------------------------------------------- -#if !defined (HAVE_QT_UI_TOOLS) +#if !defined(HAVE_QT_UI_TOOLS) QUiLoader::QUiLoader(QObject* parent) { Base::PyGILStateLocker lock; PythonWrapper wrap; wrap.loadUiToolsModule(); - //PyObject* module = PyImport_ImportModule("PySide2.QtUiTools"); + // PyObject* module = PyImport_ImportModule("PySide2.QtUiTools"); PyObject* module = PyImport_ImportModule("freecad.UiTools"); if (module) { Py::Tuple args(1); @@ -407,8 +425,9 @@ QDir QUiLoader::workingDirectory() const PythonWrapper wrap; Py::Object dir((uiloader.callMemberFunction("workingDirectory"))); QDir* d = wrap.toQDir(dir.ptr()); - if (d) + if (d) { return *d; + } return QDir::current(); } catch (Py::Exception& e) { @@ -486,19 +505,20 @@ QString QUiLoader::errorString() const // ---------------------------------------------------- UiLoader::UiLoader(QObject* parent) - : QUiLoader(parent) + : QUiLoader(parent) { this->cw = availableWidgets(); setLanguageChangeEnabled(true); } -std::unique_ptr UiLoader::newInstance(QObject *parent) +std::unique_ptr UiLoader::newInstance(QObject* parent) { QCoreApplication* app = QCoreApplication::instance(); QStringList libPaths = app->libraryPaths(); - app->setLibraryPaths(QStringList{}); //< backup library paths, so QUiLoader won't load plugins by default - std::unique_ptr rv{new UiLoader{parent}}; + app->setLibraryPaths(QStringList {}); //< backup library paths, so QUiLoader won't load plugins + // by default + std::unique_ptr rv {new UiLoader {parent}}; app->setLibraryPaths(libPaths); return rv; @@ -506,21 +526,22 @@ std::unique_ptr UiLoader::newInstance(QObject *parent) UiLoader::~UiLoader() = default; -QWidget* UiLoader::createWidget(const QString & className, QWidget * parent, - const QString& name) +QWidget* UiLoader::createWidget(const QString& className, QWidget* parent, const QString& name) { - if (this->cw.contains(className)) + if (this->cw.contains(className)) { return QUiLoader::createWidget(className, parent, name); + } return createFromWidgetFactory(className, parent, name); } // ---------------------------------------------------- -PyObject *UiLoaderPy::PyMake(struct _typeobject * /*type*/, PyObject * args, PyObject * /*kwds*/) +PyObject* UiLoaderPy::PyMake(struct _typeobject* /*type*/, PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return new UiLoaderPy(); } @@ -533,28 +554,36 @@ void UiLoaderPy::init_type() behaviors().supportRepr(); behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("load",&UiLoaderPy::load,"load(string, QWidget parent=None) -> QWidget\n" - "load(QIODevice, QWidget parent=None) -> QWidget"); - add_varargs_method("createWidget",&UiLoaderPy::createWidget,"createWidget()"); + add_varargs_method( + "load", + &UiLoaderPy::load, + "load(string, QWidget parent=None) -> QWidget\n" + "load(QIODevice, QWidget parent=None) -> QWidget" + ); + add_varargs_method("createWidget", &UiLoaderPy::createWidget, "createWidget()"); - add_varargs_method("availableWidgets",&UiLoaderPy::availableWidgets,"availableWidgets()"); - add_varargs_method("clearPluginPaths",&UiLoaderPy::clearPluginPaths,"clearPluginPaths()"); - add_varargs_method("pluginPaths",&UiLoaderPy::pluginPaths,"pluginPaths()"); - add_varargs_method("addPluginPath",&UiLoaderPy::addPluginPath,"addPluginPath()"); - add_varargs_method("errorString",&UiLoaderPy::errorString,"errorString()"); - add_varargs_method("isLanguageChangeEnabled",&UiLoaderPy::isLanguageChangeEnabled, - "isLanguageChangeEnabled()"); - add_varargs_method("setLanguageChangeEnabled",&UiLoaderPy::setLanguageChangeEnabled, - "setLanguageChangeEnabled()"); - add_varargs_method("setWorkingDirectory",&UiLoaderPy::setWorkingDirectory, - "setWorkingDirectory()"); - add_varargs_method("workingDirectory",&UiLoaderPy::workingDirectory,"workingDirectory()"); + add_varargs_method("availableWidgets", &UiLoaderPy::availableWidgets, "availableWidgets()"); + add_varargs_method("clearPluginPaths", &UiLoaderPy::clearPluginPaths, "clearPluginPaths()"); + add_varargs_method("pluginPaths", &UiLoaderPy::pluginPaths, "pluginPaths()"); + add_varargs_method("addPluginPath", &UiLoaderPy::addPluginPath, "addPluginPath()"); + add_varargs_method("errorString", &UiLoaderPy::errorString, "errorString()"); + add_varargs_method( + "isLanguageChangeEnabled", + &UiLoaderPy::isLanguageChangeEnabled, + "isLanguageChangeEnabled()" + ); + add_varargs_method( + "setLanguageChangeEnabled", + &UiLoaderPy::setLanguageChangeEnabled, + "setLanguageChangeEnabled()" + ); + add_varargs_method("setWorkingDirectory", &UiLoaderPy::setWorkingDirectory, "setWorkingDirectory()"); + add_varargs_method("workingDirectory", &UiLoaderPy::workingDirectory, "workingDirectory()"); } UiLoaderPy::UiLoaderPy() - : loader{UiLoader::newInstance()} -{ -} + : loader {UiLoader::newInstance()} +{} UiLoaderPy::~UiLoaderPy() = default; @@ -573,15 +602,17 @@ Py::Object UiLoaderPy::load(const Py::Tuple& args) QWidget* parent = nullptr; if (wrap.toCString(args[0], fn)) { file.setFileName(QString::fromUtf8(fn.c_str())); - if (!file.open(QFile::ReadOnly)) + if (!file.open(QFile::ReadOnly)) { throw Py::RuntimeError("Cannot open file"); + } device = &file; } else if (args[0].isString()) { fn = static_cast(Py::String(args[0])); file.setFileName(QString::fromUtf8(fn.c_str())); - if (!file.open(QFile::ReadOnly)) + if (!file.open(QFile::ReadOnly)) { throw Py::RuntimeError("Cannot open file"); + } device = &file; } else { @@ -616,12 +647,18 @@ Py::Object UiLoaderPy::load(const Py::Tuple& args) Py::Object UiLoaderPy::createWidget(const Py::Tuple& args) { - //NOLINTBEGIN - return wrapFromWidgetFactory(args, std::bind(&UiLoader::createWidget, loader.get(), - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); - //NOLINTEND + // NOLINTBEGIN + return wrapFromWidgetFactory( + args, + std::bind( + &UiLoader::createWidget, + loader.get(), + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3 + ) + ); + // NOLINTEND } Py::Object UiLoaderPy::addPluginPath(const Py::Tuple& args) @@ -703,6 +740,6 @@ Py::Object UiLoaderPy::workingDirectory(const Py::Tuple& /*args*/) return Py::String(path.toStdString()); } -#if !defined (HAVE_QT_UI_TOOLS) +#if !defined(HAVE_QT_UI_TOOLS) # include "moc_UiLoader.cpp" #endif diff --git a/src/Gui/UiLoader.h b/src/Gui/UiLoader.h index 85428503bb..5df1d283ff 100644 --- a/src/Gui/UiLoader.h +++ b/src/Gui/UiLoader.h @@ -23,14 +23,14 @@ #ifndef GUI_UILOADER_H #define GUI_UILOADER_H -#if !defined (__MINGW32__) -#define HAVE_QT_UI_TOOLS +#if !defined(__MINGW32__) +# define HAVE_QT_UI_TOOLS #endif -#if defined (HAVE_QT_UI_TOOLS) -#include +#if defined(HAVE_QT_UI_TOOLS) +# include #else -#include +# include #endif #include @@ -47,8 +47,8 @@ class QWidget; QT_END_NAMESPACE -#if !defined (HAVE_QT_UI_TOOLS) -class QUiLoader : public QObject +#if !defined(HAVE_QT_UI_TOOLS) +class QUiLoader: public QObject { Q_OBJECT public: @@ -63,8 +63,16 @@ public: QStringList availableWidgets() const; QStringList availableLayouts() const; - virtual QWidget* createWidget(const QString& className, QWidget* parent = nullptr, const QString& name = QString()); - virtual QLayout* createLayout(const QString& className, QObject* parent = nullptr, const QString& name = QString()); + virtual QWidget* createWidget( + const QString& className, + QWidget* parent = nullptr, + const QString& name = QString() + ); + virtual QLayout* createLayout( + const QString& className, + QObject* parent = nullptr, + const QString& name = QString() + ); virtual QActionGroup* createActionGroup(QObject* parent = nullptr, const QString& name = QString()); virtual QAction* createAction(QObject* parent = nullptr, const QString& name = QString()); @@ -84,9 +92,10 @@ private: }; #endif -namespace Gui { +namespace Gui +{ -class PySideUicModule : public Py::ExtensionModule +class PySideUicModule: public Py::ExtensionModule { public: @@ -105,14 +114,14 @@ private: * extends QUiLoader by the creation of FreeCAD specific widgets. * @author Werner Mayer */ -class UiLoader : public QUiLoader +class UiLoader: public QUiLoader { protected: /** * A protected construct for UiLoader. * To create an instance of UiLoader @see UiLoader::newInstance() */ - explicit UiLoader(QObject* parent=nullptr); + explicit UiLoader(QObject* parent = nullptr); public: /** @@ -128,7 +137,7 @@ public: * * @see https://github.com/FreeCAD/FreeCAD/issues/8708 */ - static std::unique_ptr newInstance(QObject *parent=nullptr); + static std::unique_ptr newInstance(QObject* parent = nullptr); ~UiLoader() override; @@ -136,8 +145,11 @@ public: * Creates a widget of the type \a className with the parent \a parent. * For more details see the documentation to QWidgetFactory. */ - QWidget* createWidget(const QString & className, QWidget * parent=nullptr, - const QString& name = QString()) override; + QWidget* createWidget( + const QString& className, + QWidget* parent = nullptr, + const QString& name = QString() + ) override; private: QStringList cw; @@ -145,10 +157,10 @@ private: // -------------------------------------------------------------------- -class UiLoaderPy : public Py::PythonExtension +class UiLoaderPy: public Py::PythonExtension { public: - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods UiLoaderPy(); ~UiLoaderPy() override; @@ -168,12 +180,12 @@ public: Py::Object workingDirectory(const Py::Tuple&); private: - static PyObject *PyMake(struct _typeobject *, PyObject *, PyObject *); + static PyObject* PyMake(struct _typeobject*, PyObject*, PyObject*); private: std::unique_ptr loader; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_UILOADER_H +#endif // GUI_UILOADER_H diff --git a/src/Gui/Utilities.cpp b/src/Gui/Utilities.cpp index 0ca910fadf..c97a8504fd 100644 --- a/src/Gui/Utilities.cpp +++ b/src/Gui/Utilities.cpp @@ -21,11 +21,11 @@ ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -36,55 +36,56 @@ using namespace Gui; -ViewVolumeProjection::ViewVolumeProjection (const SbViewVolume &vv) - : viewVolume(vv) +ViewVolumeProjection::ViewVolumeProjection(const SbViewVolume& vv) + : viewVolume(vv) { matrix = viewVolume.getMatrix(); invert = matrix.inverse(); } -Base::Vector3f ViewVolumeProjection::operator()(const Base::Vector3f &pt) const +Base::Vector3f ViewVolumeProjection::operator()(const Base::Vector3f& pt) const { Base::Vector3f src; transformInput(pt, src); - SbVec3f pt3d(src.x,src.y,src.z); + SbVec3f pt3d(src.x, src.y, src.z); // See SbViewVolume::projectToScreen matrix.multVecMatrix(pt3d, pt3d); - return Base::Vector3f(0.5*pt3d[0]+0.5, 0.5*pt3d[1]+0.5, 0.5*pt3d[2]+0.5); + return Base::Vector3f(0.5 * pt3d[0] + 0.5, 0.5 * pt3d[1] + 0.5, 0.5 * pt3d[2] + 0.5); } -Base::Vector3d ViewVolumeProjection::operator()(const Base::Vector3d &pt) const +Base::Vector3d ViewVolumeProjection::operator()(const Base::Vector3d& pt) const { auto ptf = Base::convertTo(pt); ptf = operator()(ptf); return Base::convertTo(ptf); } -Base::Vector3f ViewVolumeProjection::inverse (const Base::Vector3f &pt) const +Base::Vector3f ViewVolumeProjection::inverse(const Base::Vector3f& pt) const { - SbVec3f pt3d(2.0f*pt.x-1.0f, 2.0f*pt.y-1.0f, 2.0f*pt.z-1.0f); + SbVec3f pt3d(2.0f * pt.x - 1.0f, 2.0f * pt.y - 1.0f, 2.0f * pt.z - 1.0f); invert.multVecMatrix(pt3d, pt3d); - return Base::Vector3f(pt3d[0],pt3d[1],pt3d[2]); + return Base::Vector3f(pt3d[0], pt3d[1], pt3d[2]); } -Base::Vector3d ViewVolumeProjection::inverse (const Base::Vector3d &pt) const +Base::Vector3d ViewVolumeProjection::inverse(const Base::Vector3d& pt) const { auto ptf = Base::convertTo(pt); ptf = inverse(ptf); return Base::convertTo(ptf); } -Base::Matrix4D ViewVolumeProjection::getProjectionMatrix () const +Base::Matrix4D ViewVolumeProjection::getProjectionMatrix() const { // Inventor stores the transposed matrix Base::Matrix4D mat; - for (int i=0; i<4; i++) { - for (int j=0; j<4; j++) + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 4; j++) { mat[i][j] = matrix[j][i]; + } } return mat; @@ -92,22 +93,22 @@ Base::Matrix4D ViewVolumeProjection::getProjectionMatrix () const // ---------------------------------------------------------------------------- -void Tessellator::tessCB(void * v0, void * v1, void * v2, void * cbdata) +void Tessellator::tessCB(void* v0, void* v1, void* v2, void* cbdata) { - int * vtx0 = (int *)v0; - int * vtx1 = (int *)v1; - int * vtx2 = (int *)v2; + int* vtx0 = (int*)v0; + int* vtx1 = (int*)v1; + int* vtx2 = (int*)v2; - auto array = (std::vector *)cbdata; + auto array = (std::vector*)cbdata; array->push_back(*vtx0); array->push_back(*vtx1); array->push_back(*vtx2); array->push_back(-1); } -Tessellator::Tessellator(const std::vector& poly) : polygon(poly) -{ -} +Tessellator::Tessellator(const std::vector& poly) + : polygon(poly) +{} std::vector Tessellator::tessellate() const { @@ -118,7 +119,8 @@ std::vector Tessellator::tessellate() const tessellator.beginPolygon(); int index = 0; - for (std::vector::const_iterator it = polygon.begin(); it != polygon.end(); ++it, index++) { + for (std::vector::const_iterator it = polygon.begin(); it != polygon.end(); + ++it, index++) { indices[index] = index; tessellator.addVertex(SbVec3f((*it)[0], (*it)[1], 0.0f), &(indices[index])); } @@ -130,34 +132,38 @@ std::vector Tessellator::tessellate() const // ---------------------------------------------------------------------------- -class ItemViewSelection::MatchName { +class ItemViewSelection::MatchName +{ public: - explicit MatchName(const QString& n) : name(n) + explicit MatchName(const QString& n) + : name(n) {} - bool operator() (const App::DocumentObject* obj) { + bool operator()(const App::DocumentObject* obj) + { return name == QLatin1String(obj->getNameInDocument()); } + private: QString name; }; ItemViewSelection::ItemViewSelection(QAbstractItemView* view) - : view(view) -{ -} + : view(view) +{} void ItemViewSelection::applyFrom(const std::vector objs) { QAbstractItemModel* model = view->model(); QItemSelection range; - for (int i=0; irowCount(); i++) { - QModelIndex item = model->index(i,0); + for (int i = 0; i < model->rowCount(); i++) { + QModelIndex item = model->index(i, 0); if (item.isValid()) { QVariant name = model->data(item, Qt::UserRole); std::vector::const_iterator it; it = std::find_if(objs.begin(), objs.end(), MatchName(name.toString())); - if (it != objs.end()) + if (it != objs.end()) { range.select(item, item); + } } } diff --git a/src/Gui/Utilities.h b/src/Gui/Utilities.h index 623165742d..957ea4c7ea 100644 --- a/src/Gui/Utilities.h +++ b/src/Gui/Utilities.h @@ -38,82 +38,113 @@ class SbViewVolume; class QAbstractItemView; -namespace Base { +namespace Base +{ // Specialization for SbVec3f -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = SbVec3f; using float_type = float; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v[0], v[1], v[2]); } + private: const vec_type& v; }; // Specialization for SbVec3d -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = SbVec3d; using float_type = double; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v[0], v[1], v[2]); } + private: const vec_type& v; }; // Specialization for SbRotation -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = SbRotation; using float_type = float; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { - float_type q1,q2,q3,q4; - v.getValue(q1,q2,q3,q4); + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { + float_type q1, q2, q3, q4; + v.getValue(q1, q2, q3, q4); return std::make_tuple(q1, q2, q3, q4); } + private: const vec_type& v; }; // Specialization for SbColor -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = SbColor; using float_type = float; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v[0], v[1], v[2]); } + private: const vec_type& v; }; // Specialization for Color -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = Base::Color; using float_type = float; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.r, v.g, v.b); } + private: const vec_type& v; }; -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = QColor; using float_type = float; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.redF(), v.greenF(), v.blueF()); } + private: const vec_type& v; }; @@ -194,9 +225,11 @@ struct color_traits static color_type makeColor(int red, int green, int blue, int alpha = 255) { (void)alpha; - return color_type{static_cast(red) / 255.0F, - static_cast(green) / 255.0F, - static_cast(blue) / 255.0F}; + return color_type { + static_cast(red) / 255.0F, + static_cast(green) / 255.0F, + static_cast(blue) / 255.0F + }; } private: @@ -278,10 +311,12 @@ struct color_traits } static color_type makeColor(int red, int green, int blue, int alpha = 255) { - return color_type{static_cast(red) / 255.0F, - static_cast(green) / 255.0F, - static_cast(blue) / 255.0F, - static_cast(alpha) / 255.0F}; + return color_type { + static_cast(red) / 255.0F, + static_cast(green) / 255.0F, + static_cast(blue) / 255.0F, + static_cast(alpha) / 255.0F + }; } private: @@ -363,53 +398,72 @@ struct color_traits } static color_type makeColor(int red, int green, int blue, int alpha = 255) { - return color_type{red, green, blue, alpha}; + return color_type {red, green, blue, alpha}; } private: color_type ct; }; -template <> +template<> inline SbMatrix convertTo(const Base::Matrix4D& vec2) { double dMtrx[16]; vec2.getGLMatrix(dMtrx); - return SbMatrix(dMtrx[0], dMtrx[1], dMtrx[2], dMtrx[3], // clazy:exclude=rule-of-two-soft - dMtrx[4], dMtrx[5], dMtrx[6], dMtrx[7], - dMtrx[8], dMtrx[9], dMtrx[10], dMtrx[11], - dMtrx[12],dMtrx[13],dMtrx[14], dMtrx[15]); + return SbMatrix( + dMtrx[0], + dMtrx[1], + dMtrx[2], + dMtrx[3], // clazy:exclude=rule-of-two-soft + dMtrx[4], + dMtrx[5], + dMtrx[6], + dMtrx[7], + dMtrx[8], + dMtrx[9], + dMtrx[10], + dMtrx[11], + dMtrx[12], + dMtrx[13], + dMtrx[14], + dMtrx[15] + ); } -template <> +template<> inline Base::Matrix4D convertTo(const SbMatrix& vec2) { Base::Matrix4D mat; - for(int i=0;i<4;++i) { - for(int j=0;j<4;++j) + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { mat[i][j] = vec2[j][i]; + } } return mat; } -} +} // namespace Base -namespace App{ class DocumentObject; } -namespace Gui { +namespace App +{ +class DocumentObject; +} +namespace Gui +{ /** */ -class GuiExport ViewVolumeProjection : public Base::ViewProjMethod +class GuiExport ViewVolumeProjection: public Base::ViewProjMethod { public: - explicit ViewVolumeProjection (const SbViewVolume &vv); + explicit ViewVolumeProjection(const SbViewVolume& vv); ~ViewVolumeProjection() override = default; - Base::Vector3f operator()(const Base::Vector3f &rclPt) const override; - Base::Vector3d operator()(const Base::Vector3d &rclPt) const override; - Base::Vector3f inverse (const Base::Vector3f &rclPt) const override; - Base::Vector3d inverse (const Base::Vector3d &rclPt) const override; + Base::Vector3f operator()(const Base::Vector3f& rclPt) const override; + Base::Vector3d operator()(const Base::Vector3d& rclPt) const override; + Base::Vector3f inverse(const Base::Vector3f& rclPt) const override; + Base::Vector3d inverse(const Base::Vector3d& rclPt) const override; - Base::Matrix4D getProjectionMatrix () const override; + Base::Matrix4D getProjectionMatrix() const override; protected: SbViewVolume viewVolume; @@ -424,7 +478,7 @@ public: std::vector tessellate() const; private: - static void tessCB(void * v0, void * v1, void * v2, void * cbdata); + static void tessCB(void* v0, void* v1, void* v2, void* cbdata); private: std::vector polygon; @@ -441,48 +495,53 @@ private: class MatchName; }; -#define FC_ADD_CATALOG_ENTRY(__part__, __partclass__, __parent__) SO_KIT_ADD_CATALOG_ENTRY(__part__, __partclass__, TRUE, __parent__, "", TRUE); +#define FC_ADD_CATALOG_ENTRY(__part__, __partclass__, __parent__) \ + SO_KIT_ADD_CATALOG_ENTRY(__part__, __partclass__, TRUE, __parent__, "", TRUE); #define FC_SET_SWITCH(__name__, __state__) \ -do { \ - SoSwitch* sw = SO_GET_ANY_PART(this, __name__, SoSwitch); \ - assert(sw); \ - sw->whichChild = __state__; \ -} while (0) + do { \ + SoSwitch* sw = SO_GET_ANY_PART(this, __name__, SoSwitch); \ + assert(sw); \ + sw->whichChild = __state__; \ + } while (0) #define FC_SET_TOGGLE_SWITCH(__name__, __state__) \ -do { \ - SoToggleSwitch* sw = SO_GET_ANY_PART(this, __name__, SoToggleSwitch); \ - assert(sw); \ - sw->on = __state__; \ -} while (0) + do { \ + SoToggleSwitch* sw = SO_GET_ANY_PART(this, __name__, SoToggleSwitch); \ + assert(sw); \ + sw->on = __state__; \ + } while (0) -struct RotationComponents { +struct RotationComponents +{ float angle; SbVec3f axis; }; -[[nodiscard]] inline RotationComponents getRotationComponents(const SbRotation &rotation) { +[[nodiscard]] inline RotationComponents getRotationComponents(const SbRotation& rotation) +{ RotationComponents comps; rotation.getValue(comps.axis, comps.angle); return comps; } -struct TransformComponents { +struct TransformComponents +{ SbVec3f translation; SbVec3f scale; SbRotation rotation; SbRotation scaleOrientation; }; -[[nodiscard]] inline TransformComponents getMatrixTransform(const SbMatrix &matrix) { +[[nodiscard]] inline TransformComponents getMatrixTransform(const SbMatrix& matrix) +{ TransformComponents comps; matrix.getTransform(comps.translation, comps.rotation, comps.scale, comps.scaleOrientation); return comps; } -} // namespace Gui +} // namespace Gui -#endif // GUI_UTILITIES_H +#endif // GUI_UTILITIES_H diff --git a/src/Gui/VectorListEditor.cpp b/src/Gui/VectorListEditor.cpp index 184eb9188d..d296ff227b 100644 --- a/src/Gui/VectorListEditor.cpp +++ b/src/Gui/VectorListEditor.cpp @@ -36,27 +36,32 @@ using namespace Gui; -VectorTableModel::VectorTableModel(int decimals, QObject *parent) +VectorTableModel::VectorTableModel(int decimals, QObject* parent) : QAbstractTableModel(parent) , decimals(decimals) -{ -} +{} QVariant VectorTableModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (role == Qt::DisplayRole && orientation == Qt::Vertical) + if (role == Qt::DisplayRole && orientation == Qt::Vertical) { return section + 1; + } - if (role != Qt::DisplayRole || orientation != Qt::Horizontal) + if (role != Qt::DisplayRole || orientation != Qt::Horizontal) { return {}; - if (section == 0) + } + if (section == 0) { return {QLatin1Char('x')}; - if (section == 1) + } + if (section == 1) { return {QLatin1Char('y')}; - if (section == 2) + } + if (section == 2) { return {QLatin1Char('z')}; - else + } + else { return {}; + } } int VectorTableModel::columnCount(const QModelIndex&) const @@ -64,19 +69,19 @@ int VectorTableModel::columnCount(const QModelIndex&) const return 3; } -int VectorTableModel::rowCount(const QModelIndex &) const +int VectorTableModel::rowCount(const QModelIndex&) const { return vectors.size(); } -Qt::ItemFlags VectorTableModel::flags (const QModelIndex & index) const +Qt::ItemFlags VectorTableModel::flags(const QModelIndex& index) const { Qt::ItemFlags fl = QAbstractTableModel::flags(index); fl = fl | Qt::ItemIsEditable; return fl; } -bool VectorTableModel::setData(const QModelIndex &index, const QVariant &value, int role) +bool VectorTableModel::setData(const QModelIndex& index, const QVariant& value, int role) { int r = index.row(); int c = index.column(); @@ -88,12 +93,15 @@ bool VectorTableModel::setData(const QModelIndex &index, const QVariant &value, } else if (c < 3) { double d = value.toDouble(); - if (c == 0) + if (c == 0) { vectors[r].x = d; - else if (c == 1) + } + else if (c == 1) { vectors[r].y = d; - else if (c == 2) + } + else if (c == 2) { vectors[r].z = d; + } Q_EMIT dataChanged(index, index); return true; } @@ -101,19 +109,22 @@ bool VectorTableModel::setData(const QModelIndex &index, const QVariant &value, return QAbstractTableModel::setData(index, value, role); } -QVariant VectorTableModel::data(const QModelIndex &index, int role) const +QVariant VectorTableModel::data(const QModelIndex& index, int role) const { if (role == Qt::DisplayRole || role == Qt::EditRole) { int r = index.row(); int c = index.column(); if (r < vectors.size() && c < 3) { double d = 0.0; - if (c == 0) + if (c == 0) { d = vectors[r].x; - else if (c == 1) + } + else if (c == 1) { d = vectors[r].y; - else if (c == 2) + } + else if (c == 2) { d = vectors[r].z; + } if (role == Qt::DisplayRole) { QString str = QStringLiteral("%1").arg(d, 0, 'f', decimals); @@ -127,7 +138,7 @@ QVariant VectorTableModel::data(const QModelIndex &index, int role) const return {}; } -QModelIndex VectorTableModel::parent(const QModelIndex &) const +QModelIndex VectorTableModel::parent(const QModelIndex&) const { return {}; } @@ -144,8 +155,8 @@ void Gui::VectorTableModel::copyToClipboard() const QString clipboardText; QTextStream stream(&clipboardText); int precision = App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units") - ->GetInt("PropertyVectorListCopyPrecision", 16); + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units") + ->GetInt("PropertyVectorListCopyPrecision", 16); for (const auto& vector : vectors) { stream << QString::number(vector.x, 'f', precision) << '\t' @@ -158,7 +169,7 @@ void Gui::VectorTableModel::copyToClipboard() const void Gui::VectorTableModel::pasteFromClipboard() { - QClipboard *clipboard = QApplication::clipboard(); + QClipboard* clipboard = QApplication::clipboard(); QStringList lines = clipboard->text().split(QLatin1Char('\n')); bool okAll = !lines.empty(); QList newVectors; @@ -171,9 +182,9 @@ void Gui::VectorTableModel::pasteFromClipboard() continue; } QChar delimiter = line.count(tab) == 2 ? tab - : line.count(semicolon) == 2 ? semicolon - : line.count(comma) == 2 ? comma - : QChar(QChar::Null); + : line.count(semicolon) == 2 ? semicolon + : line.count(comma) == 2 ? comma + : QChar(QChar::Null); if (delimiter.isNull()) { okAll = false; @@ -204,7 +215,11 @@ void Gui::VectorTableModel::pasteFromClipboard() setValues(newVectors); } else { - QString msg(tr("Unsupported format. Must be 3 values per row separated by tabs, semicolons, or commas:") + QLatin1String("\n")); + QString msg( + tr("Unsupported format. Must be 3 values per row separated by tabs, semicolons, or " + "commas:") + + QLatin1String("\n") + ); msg += clipboard->text(); Base::Console().error(msg.toStdString().c_str()); } @@ -215,13 +230,14 @@ const QList& VectorTableModel::values() const return vectors; } -bool VectorTableModel::insertRows(int row, int count, const QModelIndex &parent) +bool VectorTableModel::insertRows(int row, int count, const QModelIndex& parent) { if (vectors.size() >= row) { - beginInsertRows(parent, row, row+count-1); + beginInsertRows(parent, row, row + count - 1); Base::Vector3d v; - for (int i=0; i row) { - beginRemoveRows(parent, row, row+count-1); - for (int i=0; isetDecimals(decimals); @@ -262,7 +278,7 @@ QWidget *VectorTableDelegate::createEditor(QWidget *parent, const QStyleOptionVi return editor; } -void VectorTableDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +void VectorTableDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { double value = index.model()->data(index, Qt::EditRole).toDouble(); @@ -270,8 +286,11 @@ void VectorTableDelegate::setEditorData(QWidget *editor, const QModelIndex &inde spinBox->setValue(value); } -void VectorTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const +void VectorTableDelegate::setModelData( + QWidget* editor, + QAbstractItemModel* model, + const QModelIndex& index +) const { auto spinBox = static_cast(editor); spinBox->interpretText(); @@ -279,8 +298,8 @@ void VectorTableDelegate::setModelData(QWidget *editor, QAbstractItemModel *mode model->setData(index, value, Qt::EditRole); } -void VectorTableDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, - const QModelIndex &/* index */) const +void VectorTableDelegate:: + updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& /* index */) const { editor->setGeometry(option.rect); } @@ -290,23 +309,20 @@ void VectorTableDelegate::updateEditorGeometry(QWidget *editor, const QStyleOpti /* TRANSLATOR Gui::VectorListEditor */ VectorListEditor::VectorListEditor(int decimals, QWidget* parent) - : QDialog(parent) - , ui(new Ui_VectorListEditor) - , model(new VectorTableModel(decimals)) + : QDialog(parent) + , ui(new Ui_VectorListEditor) + , model(new VectorTableModel(decimals)) { ui->setupUi(this); ui->tableWidget->setItemDelegate(new VectorTableDelegate(decimals, this)); ui->tableWidget->setModel(model); ui->widget->hide(); - ui->coordX->setRange(std::numeric_limits::min(), - std::numeric_limits::max()); + ui->coordX->setRange(std::numeric_limits::min(), std::numeric_limits::max()); ui->coordX->setDecimals(decimals); - ui->coordY->setRange(std::numeric_limits::min(), - std::numeric_limits::max()); + ui->coordY->setRange(std::numeric_limits::min(), std::numeric_limits::max()); ui->coordY->setDecimals(decimals); - ui->coordZ->setRange(std::numeric_limits::min(), - std::numeric_limits::max()); + ui->coordZ->setRange(std::numeric_limits::min(), std::numeric_limits::max()); ui->coordZ->setDecimals(decimals); ui->toolButtonMouse->setDisabled(true); @@ -322,7 +338,6 @@ VectorListEditor::VectorListEditor(int decimals, QWidget* parent) ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->tableWidget, &QWidget::customContextMenuRequested, this, &VectorListEditor::showContextMenu); - } VectorListEditor::~VectorListEditor() = default; @@ -330,11 +345,11 @@ VectorListEditor::~VectorListEditor() = default; void VectorListEditor::showContextMenu(const QPoint& pos) { QMenu contextMenu(ui->tableWidget); - QAction *copyAction = contextMenu.addAction(tr("Copy Table")); + QAction* copyAction = contextMenu.addAction(tr("Copy Table")); connect(copyAction, &QAction::triggered, model, &VectorTableModel::copyToClipboard); copyAction->setEnabled(!data.empty()); - QAction *pasteAction = contextMenu.addAction(tr("Paste Table")); + QAction* pasteAction = contextMenu.addAction(tr("Paste Table")); connect(pasteAction, &QAction::triggered, model, &VectorTableModel::pasteFromClipboard); pasteAction->setEnabled(QApplication::clipboard()->mimeData()->hasText()); @@ -414,7 +429,7 @@ void VectorListEditor::addRow() ui->spinBox->setEnabled(true); ui->toolButtonRemove->setEnabled(true); ui->toolButtonAccept->setEnabled(true); - acceptCurrent(); // The new row gets the values from the spinboxes + acceptCurrent(); // The new row gets the values from the spinboxes } void VectorListEditor::removeRow() diff --git a/src/Gui/VectorListEditor.h b/src/Gui/VectorListEditor.h index c7b55d3cff..573ea6aa39 100644 --- a/src/Gui/VectorListEditor.h +++ b/src/Gui/VectorListEditor.h @@ -33,57 +33,63 @@ #include -namespace Gui { +namespace Gui +{ -class VectorTableModel : public QAbstractTableModel +class VectorTableModel: public QAbstractTableModel { Q_OBJECT public: - explicit VectorTableModel(int decimals, QObject *parent = nullptr); + explicit VectorTableModel(int decimals, QObject* parent = nullptr); QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - int columnCount(const QModelIndex &parent = QModelIndex()) const override; - int rowCount(const QModelIndex &parent = QModelIndex()) const override; - Qt::ItemFlags flags (const QModelIndex & index) const override; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; - QModelIndex parent(const QModelIndex &index) const override; + int columnCount(const QModelIndex& parent = QModelIndex()) const override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + QModelIndex parent(const QModelIndex& index) const override; void setValues(const QList& d); void copyToClipboard() const; void pasteFromClipboard(); const QList& values() const; - bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()) override; + bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) override; private: QList vectors; int decimals; }; -class VectorTableDelegate : public QItemDelegate +class VectorTableDelegate: public QItemDelegate { Q_OBJECT public: - explicit VectorTableDelegate(int decimals, QObject *parent = nullptr); + explicit VectorTableDelegate(int decimals, QObject* parent = nullptr); - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + QWidget* createEditor( + QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; + void setEditorData(QWidget* editor, const QModelIndex& index) const override; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void updateEditorGeometry( + QWidget* editor, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override; private: int decimals; }; class Ui_VectorListEditor; -class VectorListEditor : public QDialog +class VectorListEditor: public QDialog { Q_OBJECT @@ -111,6 +117,6 @@ private: QList data; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_VECTORLISTEDITOR_H +#endif // GUI_VECTORLISTEDITOR_H diff --git a/src/Gui/View.cpp b/src/Gui/View.cpp index 395a3fdd0e..19d9cd8e59 100644 --- a/src/Gui/View.cpp +++ b/src/Gui/View.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ - - #include "View.h" #include "Application.h" #include "Document.h" @@ -33,17 +31,17 @@ using namespace Gui; // BaseView //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TYPESYSTEM_SOURCE_ABSTRACT(Gui::BaseView,Base::BaseClass) +TYPESYSTEM_SOURCE_ABSTRACT(Gui::BaseView, Base::BaseClass) -BaseView::BaseView( Gui::Document* pcDocument) - :_pcDocument(pcDocument) +BaseView::BaseView(Gui::Document* pcDocument) + : _pcDocument(pcDocument) { - if (pcDocument){ + if (pcDocument) { pcDocument->attachView(this); bIsPassive = false; } - else{ + else { Application::Instance->attachView(this); bIsPassive = true; } @@ -56,17 +54,20 @@ BaseView::~BaseView() void BaseView::onClose() { - if (bIsDetached) + if (bIsDetached) { return; + } if (bIsPassive) { Application::Instance->detachView(this); - if (_pcDocument) + if (_pcDocument) { _pcDocument->detachView(this, true); + } } else { - if (_pcDocument) + if (_pcDocument) { _pcDocument->detachView(this); + } } _pcDocument = nullptr; @@ -80,13 +81,16 @@ void BaseView::deleteSelf() void BaseView::setDocument(Gui::Document* pcDocument) { - if (_pcDocument == pcDocument) + if (_pcDocument == pcDocument) { return; + } // detaches and attaches the observer - if (_pcDocument) + if (_pcDocument) { _pcDocument->detachView(this, true); - if (pcDocument) - pcDocument->attachView(this,true); + } + if (pcDocument) { + pcDocument->attachView(this, true); + } // set the new document as the active one _pcDocument = pcDocument; diff --git a/src/Gui/View.h b/src/Gui/View.h index c09bcdfd0d..4cf70dc3f3 100644 --- a/src/Gui/View.h +++ b/src/Gui/View.h @@ -48,7 +48,7 @@ class ViewProvider; * @see Application * @author Juergen Riegel */ -class GuiExport BaseView : public Base::BaseClass +class GuiExport BaseView: public Base::BaseClass { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -58,7 +58,7 @@ public: * the view will attach to the active document. Be aware! there isn't * always an active document! */ - BaseView(Gui::Document* pcDocument=nullptr); + BaseView(Gui::Document* pcDocument = nullptr); /** View destructor * Detach the view from the document, if attached! */ @@ -75,40 +75,54 @@ public: //@} /// returns the document the view is attached to - Gui::Document* getGuiDocument() const {return _pcDocument;} + Gui::Document* getGuiDocument() const + { + return _pcDocument; + } /// returns the document the view is attached to App::Document* getAppDocument() const; /// indicates if the view is in passive mode - bool isPassive() const {return bIsPassive;} + bool isPassive() const + { + return bIsPassive; + } /** @name methods to override */ //@{ /// get called when the document is updated - virtual void onUpdate(){} + virtual void onUpdate() + {} /// get called when the document is relabeled (change of its user name) - virtual void onRelabel(Gui::Document *){} + virtual void onRelabel(Gui::Document*) + {} /// get called when the document is renamed (change of its internal name) - virtual void onRename(Gui::Document *){} + virtual void onRename(Gui::Document*) + {} /// returns the name of the view (important for messages) - virtual const char *getName() const - { return "Base view"; } + virtual const char* getName() const + { + return "Base view"; + } /// Message handler - virtual bool onMsg(const char* pMsg, const char** ppReturn)=0; + virtual bool onMsg(const char* pMsg, const char** ppReturn) = 0; /// Message handler test - virtual bool onHasMsg(const char* pMsg) const=0; + virtual bool onHasMsg(const char* pMsg) const = 0; /// overwrite when checking on close state - virtual bool canClose(){return true;} + virtual bool canClose() + { + return true; + } /// delete itself virtual void deleteSelf(); //@} protected: - Gui::Document* _pcDocument; - bool bIsDetached{false}; - bool bIsPassive{false}; + Gui::Document* _pcDocument; + bool bIsDetached {false}; + bool bIsPassive {false}; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_VIEW_H +#endif // GUI_VIEW_H diff --git a/src/Gui/View3DInventor.cpp b/src/Gui/View3DInventor.cpp index 2919ec127e..2dab86ec05 100644 --- a/src/Gui/View3DInventor.cpp +++ b/src/Gui/View3DInventor.cpp @@ -21,33 +21,31 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -85,18 +83,20 @@ using namespace Gui; void GLOverlayWidget::paintEvent(QPaintEvent*) { QPainter paint(this); - paint.drawImage(0,0,image); + paint.drawImage(0, 0, image); paint.end(); } /* TRANSLATOR Gui::View3DInventor */ -TYPESYSTEM_SOURCE_ABSTRACT(Gui::View3DInventor,Gui::MDIView) +TYPESYSTEM_SOURCE_ABSTRACT(Gui::View3DInventor, Gui::MDIView) -View3DInventor::View3DInventor(Gui::Document* pcDocument, - QWidget* parent, - const QOpenGLWidget* sharewidget, - Qt::WindowFlags wflags) +View3DInventor::View3DInventor( + Gui::Document* pcDocument, + QWidget* parent, + const QOpenGLWidget* sharewidget, + Qt::WindowFlags wflags +) : MDIView(pcDocument, parent, wflags) , _viewerPy(nullptr) { @@ -106,7 +106,7 @@ View3DInventor::View3DInventor(Gui::Document* pcDocument, // accept drops on the window, get handled in dropEvent, dragEnterEvent setAcceptDrops(true); - //anti-aliasing settings + // anti-aliasing settings bool smoothing = false; bool glformat = false; int samples = View3DInventorViewer::getNumSamples(); @@ -120,13 +120,16 @@ View3DInventor::View3DInventor(Gui::Document* pcDocument, smoothing = true; } - if (glformat) + if (glformat) { _viewer = new View3DInventorViewer(f, this, sharewidget); - else + } + else { _viewer = new View3DInventorViewer(this, sharewidget); + } - if (smoothing) + if (smoothing) { _viewer->getSoRenderManager()->getGLRenderAction()->setSmoothing(true); + } // create the inventor widget and set the defaults _viewer->setDocument(this->_pcDocument); @@ -150,18 +153,19 @@ View3DInventor::View3DInventor(Gui::Document* pcDocument, View3DInventor::~View3DInventor() { - if(_pcDocument) { - SoCamera * Cam = _viewer->getSoRenderManager()->getCamera(); - if (Cam) + if (_pcDocument) { + SoCamera* Cam = _viewer->getSoRenderManager()->getCamera(); + if (Cam) { _pcDocument->saveCameraSettings(SoFCDB::writeNodesToString(Cam).c_str()); + } } viewSettings.reset(); - //If we destroy this viewer by calling 'delete' directly the focus proxy widget which is defined - //by a widget in SoQtViewer isn't reset. This widget becomes a dangling pointer and makes - //the application crash. (Probably it's better to destroy this viewer by calling close().) - //See also Gui::Document::~Document(). + // If we destroy this viewer by calling 'delete' directly the focus proxy widget which is + // defined by a widget in SoQtViewer isn't reset. This widget becomes a dangling pointer and + // makes the application crash. (Probably it's better to destroy this viewer by calling + // close().) See also Gui::Document::~Document(). QWidget* foc = qApp->focusWidget(); if (foc) { QWidget* par = foc->parentWidget(); @@ -212,10 +216,11 @@ View3DInventor* View3DInventor::clone() return view3D; } -PyObject *View3DInventor::getPyObject() +PyObject* View3DInventor::getPyObject() { - if (!_viewerPy) + if (!_viewerPy) { _viewerPy = new View3DInventorPy(this); + } Py_INCREF(_viewerPy); return _viewerPy; @@ -223,15 +228,19 @@ PyObject *View3DInventor::getPyObject() void View3DInventor::applySettings() { - viewSettings = std::make_unique(App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"), _viewer); - naviSettings = std::make_unique(App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/NaviCube"), _viewer); + viewSettings = std::make_unique( + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"), + _viewer + ); + naviSettings = std::make_unique( + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/NaviCube"), + _viewer + ); viewSettings->applySettings(); naviSettings->applySettings(); } -void View3DInventor::onRename(Gui::Document *pDoc) +void View3DInventor::onRename(Gui::Document* pDoc) { SoSFString name; name.setValue(pDoc->getDocument()->getName()); @@ -253,7 +262,7 @@ void View3DInventor::viewAll() _viewer->viewAll(); } -const char *View3DInventor::getName() const +const char* View3DInventor::getName() const { return "View3DInventor"; } @@ -274,13 +283,18 @@ void View3DInventor::print() void View3DInventor::printPdf() { - QString filename = FileDialog::getSaveFileName(this, tr("Export PDF"), QString(), - QStringLiteral("%1 (*.pdf)").arg(tr("PDF file"))); + QString filename = FileDialog::getSaveFileName( + this, + tr("Export PDF"), + QString(), + QStringLiteral("%1 (*.pdf)").arg(tr("PDF file")) + ); if (!filename.isEmpty()) { Gui::WaitCursor wc; QPrinter printer(QPrinter::ScreenResolution); - // setPdfVersion sets the printed PDF Version to what is chosen in Preferences/Import-Export/PDF - // more details under: https://www.kdab.com/creating-pdfa-documents-qt/ + // setPdfVersion sets the printed PDF Version to what is chosen in + // Preferences/Import-Export/PDF more details under: + // https://www.kdab.com/creating-pdfa-documents-qt/ printer.setPdfVersion(Gui::Dialog::DlgSettingsPDF::evaluatePDFVersion()); printer.setOutputFormat(QPrinter::PdfFormat); printer.setPageOrientation(QPageLayout::Landscape); @@ -297,8 +311,12 @@ void View3DInventor::printPreview() restorePrinterSettings(&printer); QPrintPreviewDialog dlg(&printer, this); - connect(&dlg, &QPrintPreviewDialog::paintRequested, - this, qOverload(&View3DInventor::print)); + connect( + &dlg, + &QPrintPreviewDialog::paintRequested, + this, + qOverload(&View3DInventor::print) + ); dlg.exec(); savePrinterSettings(&printer); } @@ -309,16 +327,19 @@ void View3DInventor::print(QPrinter* printer) p.setRenderHints(QPainter::Antialiasing); if (!p.isActive() && !printer->outputFileName().isEmpty()) { qApp->setOverrideCursor(Qt::ArrowCursor); - QMessageBox::critical(this, tr("Opening file failed"), - tr("Can't open file '%1' for writing.").arg(printer->outputFileName())); + QMessageBox::critical( + this, + tr("Opening file failed"), + tr("Can't open file '%1' for writing.").arg(printer->outputFileName()) + ); qApp->restoreOverrideCursor(); return; } QRect rect = printer->pageLayout().paintRectPixels(printer->resolution()); QImage img; - _viewer->imageFromFramebuffer(rect.width(), rect.height(), 8, QColor(255,255,255), img); - p.drawImage(0,0,img); + _viewer->imageFromFramebuffer(rect.width(), rect.height(), 8, QColor(255, 255, 255), img); + p.drawImage(0, 0, img); p.end(); } @@ -331,113 +352,114 @@ bool View3DInventor::containsViewProvider(const ViewProvider* vp) const bool View3DInventor::onMsg(const char* pMsg, const char** ppReturn) { - if (strcmp("ViewFit",pMsg) == 0) { + if (strcmp("ViewFit", pMsg) == 0) { _viewer->viewAll(); return true; } - else if (strcmp("ViewVR",pMsg) == 0) { + else if (strcmp("ViewVR", pMsg) == 0) { // call the VR portion of the viewer _viewer->viewVR(); return true; } - else if(strcmp("ViewSelection",pMsg) == 0) { + else if (strcmp("ViewSelection", pMsg) == 0) { _viewer->viewSelection(); return true; } - else if(strcmp("SetStereoRedGreen",pMsg) == 0 ) { + else if (strcmp("SetStereoRedGreen", pMsg) == 0) { _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::ANAGLYPH); return true; } - else if(strcmp("SetStereoQuadBuff",pMsg) == 0 ) { - _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::QUAD_BUFFER ); + else if (strcmp("SetStereoQuadBuff", pMsg) == 0) { + _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::QUAD_BUFFER); return true; } - else if(strcmp("SetStereoInterleavedRows",pMsg) == 0 ) { - _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::INTERLEAVED_ROWS ); + else if (strcmp("SetStereoInterleavedRows", pMsg) == 0) { + _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::INTERLEAVED_ROWS); return true; } - else if(strcmp("SetStereoInterleavedColumns",pMsg) == 0 ) { - _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::INTERLEAVED_COLUMNS ); + else if (strcmp("SetStereoInterleavedColumns", pMsg) == 0) { + _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::INTERLEAVED_COLUMNS); return true; } - else if(strcmp("SetStereoOff",pMsg) == 0 ) { - _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::MONO ); + else if (strcmp("SetStereoOff", pMsg) == 0) { + _viewer->setStereoMode(Quarter::SoQTQuarterAdaptor::MONO); return true; } - else if(strcmp("GetCamera",pMsg) == 0 ) { - SoCamera * Cam = _viewer->getSoRenderManager()->getCamera(); - if (!Cam) + else if (strcmp("GetCamera", pMsg) == 0) { + SoCamera* Cam = _viewer->getSoRenderManager()->getCamera(); + if (!Cam) { return false; + } *ppReturn = SoFCDB::writeNodesToString(Cam).c_str(); return true; } - else if(strncmp("SetCamera",pMsg,9) == 0 ) { - return setCamera(pMsg+10); + else if (strncmp("SetCamera", pMsg, 9) == 0) { + return setCamera(pMsg + 10); } - else if(strncmp("Dump",pMsg,4) == 0 ) { - dump(pMsg+5); + else if (strncmp("Dump", pMsg, 4) == 0) { + dump(pMsg + 5); return true; } - else if(strcmp("ViewBottom",pMsg) == 0 ) { + else if (strcmp("ViewBottom", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Bottom)); _viewer->viewAll(); return true; } - else if(strcmp("ViewFront",pMsg) == 0 ) { + else if (strcmp("ViewFront", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Front)); _viewer->viewAll(); return true; } - else if(strcmp("ViewLeft",pMsg) == 0 ) { + else if (strcmp("ViewLeft", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Left)); _viewer->viewAll(); return true; } - else if(strcmp("ViewRear",pMsg) == 0 ) { + else if (strcmp("ViewRear", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Rear)); _viewer->viewAll(); return true; } - else if(strcmp("ViewRight",pMsg) == 0 ) { + else if (strcmp("ViewRight", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Right)); _viewer->viewAll(); return true; } - else if(strcmp("ViewTop",pMsg) == 0 ) { + else if (strcmp("ViewTop", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Top)); _viewer->viewAll(); return true; } - else if(strcmp("ViewAxo",pMsg) == 0 ) { + else if (strcmp("ViewAxo", pMsg) == 0) { _viewer->setCameraOrientation(Camera::rotation(Camera::Isometric)); _viewer->viewAll(); return true; } - else if(strcmp("OrthographicCamera",pMsg) == 0 ) { + else if (strcmp("OrthographicCamera", pMsg) == 0) { _viewer->setCameraType(SoOrthographicCamera::getClassTypeId()); return true; } - else if(strcmp("PerspectiveCamera",pMsg) == 0 ) { + else if (strcmp("PerspectiveCamera", pMsg) == 0) { _viewer->setCameraType(SoPerspectiveCamera::getClassTypeId()); return true; } - else if(strcmp("Undo",pMsg) == 0 ) { + else if (strcmp("Undo", pMsg) == 0) { getGuiDocument()->undo(1); return true; } - else if(strcmp("Redo",pMsg) == 0 ) { + else if (strcmp("Redo", pMsg) == 0) { getGuiDocument()->redo(1); return true; } - else if (strcmp("Save",pMsg) == 0) { + else if (strcmp("Save", pMsg) == 0) { getGuiDocument()->save(); return true; } - else if (strcmp("SaveAs",pMsg) == 0) { + else if (strcmp("SaveAs", pMsg) == 0) { getGuiDocument()->saveAs(); return true; } - else if (strcmp("SaveCopy",pMsg) == 0) { + else if (strcmp("SaveCopy", pMsg) == 0) { getGuiDocument()->saveCopy(); return true; } @@ -464,88 +486,88 @@ bool View3DInventor::onHasMsg(const char* pMsg) const if (strcmp("CanPan", pMsg) == 0) { return true; } - else if (strcmp("Save",pMsg) == 0) { + else if (strcmp("Save", pMsg) == 0) { return true; } - else if (strcmp("SaveAs",pMsg) == 0) { + else if (strcmp("SaveAs", pMsg) == 0) { return true; } - else if (strcmp("SaveCopy",pMsg) == 0) { + else if (strcmp("SaveCopy", pMsg) == 0) { return true; } - else if (strcmp("Undo",pMsg) == 0) { + else if (strcmp("Undo", pMsg) == 0) { App::Document* doc = getAppDocument(); return doc && doc->getAvailableUndos() > 0; } - else if (strcmp("Redo",pMsg) == 0) { + else if (strcmp("Redo", pMsg) == 0) { App::Document* doc = getAppDocument(); return doc && doc->getAvailableRedos() > 0; } - else if (strcmp("Print",pMsg) == 0) { + else if (strcmp("Print", pMsg) == 0) { return true; } - else if (strcmp("PrintPreview",pMsg) == 0) { + else if (strcmp("PrintPreview", pMsg) == 0) { return true; } - else if (strcmp("PrintPdf",pMsg) == 0) { + else if (strcmp("PrintPdf", pMsg) == 0) { return true; } - else if(strcmp("SetStereoRedGreen",pMsg) == 0) { + else if (strcmp("SetStereoRedGreen", pMsg) == 0) { return true; } - else if(strcmp("SetStereoQuadBuff",pMsg) == 0) { + else if (strcmp("SetStereoQuadBuff", pMsg) == 0) { return true; } - else if(strcmp("SetStereoInterleavedRows",pMsg) == 0) { + else if (strcmp("SetStereoInterleavedRows", pMsg) == 0) { return true; } - else if(strcmp("SetStereoInterleavedColumns",pMsg) == 0) { + else if (strcmp("SetStereoInterleavedColumns", pMsg) == 0) { return true; } - else if(strcmp("SetStereoOff",pMsg) == 0) { + else if (strcmp("SetStereoOff", pMsg) == 0) { return true; } - else if(strcmp("ViewFit",pMsg) == 0) { + else if (strcmp("ViewFit", pMsg) == 0) { return true; } - else if(strcmp("ViewVR",pMsg) == 0) { + else if (strcmp("ViewVR", pMsg) == 0) { #ifdef BUILD_VR return true; #else return false; #endif } - else if(strcmp("ViewSelection",pMsg) == 0) { + else if (strcmp("ViewSelection", pMsg) == 0) { return true; } - else if(strcmp("ViewBottom",pMsg) == 0) { + else if (strcmp("ViewBottom", pMsg) == 0) { return true; } - else if(strcmp("ViewFront",pMsg) == 0) { + else if (strcmp("ViewFront", pMsg) == 0) { return true; } - else if(strcmp("ViewLeft",pMsg) == 0) { + else if (strcmp("ViewLeft", pMsg) == 0) { return true; } - else if(strcmp("ViewRear",pMsg) == 0) { + else if (strcmp("ViewRear", pMsg) == 0) { return true; } - else if(strcmp("ViewRight",pMsg) == 0) { + else if (strcmp("ViewRight", pMsg) == 0) { return true; } - else if(strcmp("ViewTop",pMsg) == 0) { + else if (strcmp("ViewTop", pMsg) == 0) { return true; } - else if(strcmp("ViewAxo",pMsg) == 0) { + else if (strcmp("ViewAxo", pMsg) == 0) { return true; } - else if(strcmp("GetCamera",pMsg) == 0) { + else if (strcmp("GetCamera", pMsg) == 0) { return true; } - else if(strncmp("SetCamera",pMsg,9) == 0) { + else if (strncmp("SetCamera", pMsg, 9) == 0) { return true; } - else if(strncmp("Dump",pMsg,4) == 0) { + else if (strncmp("Dump", pMsg, 4) == 0) { return true; } else if (strcmp("AlignToSelection", pMsg) == 0) { @@ -566,16 +588,16 @@ bool View3DInventor::onHasMsg(const char* pMsg) const bool View3DInventor::setCamera(const char* pCamera) { - SoCamera * CamViewer = _viewer->getSoRenderManager()->getCamera(); + SoCamera* CamViewer = _viewer->getSoRenderManager()->getCamera(); if (!CamViewer) { throw Base::RuntimeError("No camera set so far…"); } SoInput in; - in.setBuffer((void*)pCamera,std::strlen(pCamera)); + in.setBuffer((void*)pCamera, std::strlen(pCamera)); - SoNode * Cam; - SoDB::read(&in,Cam); + SoNode* Cam; + SoDB::read(&in, Cam); if (!Cam || !Cam->isOfType(SoCamera::getClassTypeId())) { throw Base::RuntimeError("Camera settings failed to read"); @@ -590,38 +612,39 @@ bool View3DInventor::setCamera(const char* pCamera) CamViewer = _viewer->getSoRenderManager()->getCamera(); } - SoPerspectiveCamera * CamViewerP = nullptr; - SoOrthographicCamera * CamViewerO = nullptr; + SoPerspectiveCamera* CamViewerP = nullptr; + SoOrthographicCamera* CamViewerO = nullptr; if (CamViewer->getTypeId() == SoPerspectiveCamera::getClassTypeId()) { - CamViewerP = static_cast(CamViewer); // safe downward cast, knows the type + CamViewerP = static_cast(CamViewer); // safe downward cast, knows the type } else if (CamViewer->getTypeId() == SoOrthographicCamera::getClassTypeId()) { - CamViewerO = static_cast(CamViewer); // safe downward cast, knows the type + CamViewerO = static_cast(CamViewer); // safe downward cast, knows + // the type } if (Cam->getTypeId() == SoPerspectiveCamera::getClassTypeId()) { - if (CamViewerP){ - CamViewerP->position = static_cast(Cam)->position; - CamViewerP->orientation = static_cast(Cam)->orientation; - CamViewerP->nearDistance = static_cast(Cam)->nearDistance; - CamViewerP->farDistance = static_cast(Cam)->farDistance; - CamViewerP->focalDistance = static_cast(Cam)->focalDistance; + if (CamViewerP) { + CamViewerP->position = static_cast(Cam)->position; + CamViewerP->orientation = static_cast(Cam)->orientation; + CamViewerP->nearDistance = static_cast(Cam)->nearDistance; + CamViewerP->farDistance = static_cast(Cam)->farDistance; + CamViewerP->focalDistance = static_cast(Cam)->focalDistance; } else { throw Base::TypeError("Camera type mismatch"); } } else if (Cam->getTypeId() == SoOrthographicCamera::getClassTypeId()) { - if (CamViewerO){ - CamViewerO->viewportMapping = static_cast(Cam)->viewportMapping; - CamViewerO->position = static_cast(Cam)->position; - CamViewerO->orientation = static_cast(Cam)->orientation; - CamViewerO->nearDistance = static_cast(Cam)->nearDistance; - CamViewerO->farDistance = static_cast(Cam)->farDistance; - CamViewerO->focalDistance = static_cast(Cam)->focalDistance; - CamViewerO->aspectRatio = static_cast(Cam)->aspectRatio ; - CamViewerO->height = static_cast(Cam)->height; + if (CamViewerO) { + CamViewerO->viewportMapping = static_cast(Cam)->viewportMapping; + CamViewerO->position = static_cast(Cam)->position; + CamViewerO->orientation = static_cast(Cam)->orientation; + CamViewerO->nearDistance = static_cast(Cam)->nearDistance; + CamViewerO->farDistance = static_cast(Cam)->farDistance; + CamViewerO->focalDistance = static_cast(Cam)->focalDistance; + CamViewerO->aspectRatio = static_cast(Cam)->aspectRatio; + CamViewerO->height = static_cast(Cam)->height; } else { throw Base::TypeError("Camera type mismatch"); @@ -652,7 +675,9 @@ void View3DInventor::removeOverlayWidget() { stack->setCurrentIndex(0); QWidget* overlay = stack->widget(1); - if (overlay) stack->removeWidget(overlay); + if (overlay) { + stack->removeWidget(overlay); + } } void View3DInventor::setOverrideCursor(const QCursor& aCursor) @@ -680,10 +705,13 @@ void View3DInventor::dump(const char* filename, bool onlyVisible) node->ref(); } - if ( action.getTriangleCount() > 100000 || action.getPointCount() > 30000 || action.getLineCount() > 10000 ) + if (action.getTriangleCount() > 100000 || action.getPointCount() > 30000 + || action.getLineCount() > 10000) { _viewer->dumpToFile(node, filename, true); - else + } + else { _viewer->dumpToFile(node, filename, false); + } if (onlyVisible) { node->unref(); @@ -699,18 +727,20 @@ void View3DInventor::windowStateChanged(QWidget* view) // Note: If view is top-level or fullscreen it doesn't necessarily hide the other view // e.g. if it is on a second monitor. canStartTimer = (!this->isWindow() && !view->isWindow() && view->isMaximized()); - } else if (isMinimized()) { + } + else if (isMinimized()) { // I am the active view but minimized canStartTimer = true; } if (canStartTimer) { int msecs = viewSettings->stopAnimatingIfDeactivated(); - if (!stopSpinTimer->isActive() && msecs >= 0) { // if < 0 do not stop rotation + if (!stopSpinTimer->isActive() && msecs >= 0) { // if < 0 do not stop rotation stopSpinTimer->setSingleShot(true); stopSpinTimer->start(msecs); } - } else if (stopSpinTimer->isActive()) { + } + else if (stopSpinTimer->isActive()) { // If this view may be visible again we can stop the timer stopSpinTimer->stop(); } @@ -724,7 +754,7 @@ void View3DInventor::stopAnimating() /** * Drops the event \a e and writes the right Python command. */ -void View3DInventor::dropEvent (QDropEvent * e) +void View3DInventor::dropEvent(QDropEvent* e) { const QMimeData* data = e->mimeData(); if (data->hasUrls()) { @@ -735,14 +765,16 @@ void View3DInventor::dropEvent (QDropEvent * e) } } -void View3DInventor::dragEnterEvent (QDragEnterEvent * e) +void View3DInventor::dragEnterEvent(QDragEnterEvent* e) { // Here we must allow uri drags and check them in dropEvent const QMimeData* data = e->mimeData(); - if (data->hasUrls()) + if (data->hasUrls()) { e->accept(); - else + } + else { e->ignore(); + } } void View3DInventor::setCurrentViewMode(ViewMode mode) @@ -805,13 +837,7 @@ RayPickInfo View3DInventor::getObjInfoRay(Base::Vector3d* startvec, Base::Vector // near plane clipping is required to avoid false intersections float nearClippingPlane = 0.1F; - RayPickInfo ret = {false, - Base::Vector3d(), - "", - "", - std::nullopt, - std::nullopt, - std::nullopt}; + RayPickInfo ret = {false, Base::Vector3d(), "", "", std::nullopt, std::nullopt, std::nullopt}; SoRayPickAction action(getViewer()->getSoRenderManager()->getViewportRegion()); action.setRay(SbVec3f(vsx, vsy, vsz), SbVec3f(vdx, vdy, vdz), nearClippingPlane); action.apply(getViewer()->getSoRenderManager()->getSceneGraph()); @@ -883,7 +909,7 @@ RayPickInfo View3DInventor::getObjInfoRay(Base::Vector3d* startvec, Base::Vector return ret; } -void View3DInventor::keyPressEvent (QKeyEvent* e) +void View3DInventor::keyPressEvent(QKeyEvent* e) { // See StdViewDockUndockFullscreen::activated() // With Qt5 one cannot directly use 'setCurrentViewMode' @@ -894,31 +920,34 @@ void View3DInventor::keyPressEvent (QKeyEvent* e) QMainWindow::keyPressEvent(e); } -void View3DInventor::keyReleaseEvent (QKeyEvent* e) +void View3DInventor::keyReleaseEvent(QKeyEvent* e) { QMainWindow::keyReleaseEvent(e); } -void View3DInventor::focusInEvent (QFocusEvent *) +void View3DInventor::focusInEvent(QFocusEvent*) { _viewer->getGLWidget()->setFocus(); } -void View3DInventor::contextMenuEvent (QContextMenuEvent*e) +void View3DInventor::contextMenuEvent(QContextMenuEvent* e) { MDIView::contextMenuEvent(e); } -void View3DInventor::customEvent(QEvent * e) +void View3DInventor::customEvent(QEvent* e) { if (e->type() == QEvent::User) { auto se = static_cast(e); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); - if (hGrp->GetBool("SameStyleForAllViews", true)) + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + if (hGrp->GetBool("SameStyleForAllViews", true)) { hGrp->SetASCII("NavigationStyle", se->style().getName()); - else + } + else { _viewer->setNavigationType(se->style()); + } } } diff --git a/src/Gui/View3DInventor.h b/src/Gui/View3DInventor.h index de36d6b1c9..c3afe5fdee 100644 --- a/src/Gui/View3DInventor.h +++ b/src/Gui/View3DInventor.h @@ -37,7 +37,8 @@ class QPrinter; class QOpenGLWidget; class QStackedWidget; -namespace Gui { +namespace Gui +{ class Document; class View3DInventorViewer; @@ -55,16 +56,19 @@ struct RayPickInfo std::optional component; std::optional subName; }; -class GuiExport GLOverlayWidget : public QWidget +class GuiExport GLOverlayWidget: public QWidget { Q_OBJECT public: - explicit GLOverlayWidget(QWidget* parent=nullptr) : QWidget(parent) + explicit GLOverlayWidget(QWidget* parent = nullptr) + : QWidget(parent) {} ~GLOverlayWidget() override = default; virtual void setImage(const QImage& img) - { image = img; } + { + image = img; + } void paintEvent(QPaintEvent*) override; protected: @@ -75,14 +79,19 @@ protected: * It consists out of the 3D view * \author Juergen Riegel */ -class GuiExport View3DInventor : public MDIView +class GuiExport View3DInventor: public MDIView { Q_OBJECT TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - View3DInventor(Gui::Document* pcDocument, QWidget* parent, const QOpenGLWidget* sharewidget = nullptr, Qt::WindowFlags wflags=Qt::WindowFlags()); + View3DInventor( + Gui::Document* pcDocument, + QWidget* parent, + const QOpenGLWidget* sharewidget = nullptr, + Qt::WindowFlags wflags = Qt::WindowFlags() + ); ~View3DInventor() override; View3DInventor* clone() override; @@ -92,10 +101,10 @@ public: bool onHasMsg(const char* pMsg) const override; void deleteSelf() override; /// get called when the document is updated - void onRename(Gui::Document *pDoc) override; + void onRename(Gui::Document* pDoc) override; void onUpdate() override; void viewAll() override; - const char *getName() const override; + const char* getName() const override; /// print function of the view void print() override; @@ -103,7 +112,7 @@ public: void printPreview() override; void print(QPrinter*) override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; /** * If \a b is set to \a FullScreen the MDI view is displayed in full screen mode, if \a b * is set to \a TopLevel then it is displayed as an own top-level window, otherwise (\a Normal) @@ -112,8 +121,7 @@ public: * GL widget to get all key events in \a TopLevel or \a Fullscreen mode. */ void setCurrentViewMode(ViewMode b) override; - RayPickInfo getObjInfoRay(Base::Vector3d* startvec, - Base::Vector3d* dirvec); + RayPickInfo getObjInfoRay(Base::Vector3d* startvec, Base::Vector3d* dirvec); bool setCamera(const char* pCamera); void toggleClippingPlane(); bool hasClippingPlane() const; @@ -121,7 +129,10 @@ public: void setOverlayWidget(QWidget*); void removeOverlayWidget(); - View3DInventorViewer *getViewer() const {return _viewer;} + View3DInventorViewer* getViewer() const + { + return _viewer; + } bool containsViewProvider(const ViewProvider*) const override; public Q_SLOTS: @@ -129,7 +140,7 @@ public Q_SLOTS: void setOverrideCursor(const QCursor&) override; void restoreOverrideCursor() override; - void dump(const char* filename, bool onlyVisible=false); + void dump(const char* filename, bool onlyVisible = false); protected Q_SLOTS: void stopAnimating(); @@ -139,18 +150,18 @@ private: protected: void windowStateChanged(QWidget* view) override; - void dropEvent (QDropEvent * e) override; - void dragEnterEvent (QDragEnterEvent * e) override; - void keyPressEvent (QKeyEvent * e) override; - void keyReleaseEvent (QKeyEvent * e) override; - void focusInEvent (QFocusEvent * e) override; - void customEvent (QEvent * e) override; - void contextMenuEvent (QContextMenuEvent*e) override; + void dropEvent(QDropEvent* e) override; + void dragEnterEvent(QDragEnterEvent* e) override; + void keyPressEvent(QKeyEvent* e) override; + void keyReleaseEvent(QKeyEvent* e) override; + void focusInEvent(QFocusEvent* e) override; + void customEvent(QEvent* e) override; + void contextMenuEvent(QContextMenuEvent* e) override; private: - View3DInventorViewer * _viewer; - PyObject *_viewerPy; - QTimer * stopSpinTimer; + View3DInventorViewer* _viewer; + PyObject* _viewerPy; + QTimer* stopSpinTimer; QStackedWidget* stack; std::unique_ptr viewSettings; std::unique_ptr naviSettings; @@ -159,7 +170,6 @@ private: friend class View3DPy; }; -} // namespace Gui +} // namespace Gui #endif // GUI_VIEW3DINVENTOR_H - diff --git a/src/Gui/View3DInventorRiftViewer.cpp b/src/Gui/View3DInventorRiftViewer.cpp index 03ee928869..a1bf561487 100644 --- a/src/Gui/View3DInventorRiftViewer.cpp +++ b/src/Gui/View3DInventorRiftViewer.cpp @@ -21,76 +21,80 @@ ***************************************************************************/ - - #if BUILD_VR -#include -#include +# include +# include -#include "View3DInventorRiftViewer.h" +# include "View3DInventorRiftViewer.h" using namespace Gui; -View3DInventorRiftViewer::View3DInventorRiftViewer() : CoinRiftWidget() +View3DInventorRiftViewer::View3DInventorRiftViewer() + : CoinRiftWidget() { workplace = new SoGroup(); - //translation = new SoTranslation ; - //translation->translation.setValue(0,-1,0); - //workplace->addChild(translation); + // translation = new SoTranslation ; + // translation->translation.setValue(0,-1,0); + // workplace->addChild(translation); - rotation1 = new SoRotationXYZ ; + rotation1 = new SoRotationXYZ; rotation1->axis.setValue(SoRotationXYZ::X); - rotation1->angle.setValue(-std::numbers::pi/2); + rotation1->angle.setValue(-std::numbers::pi / 2); workplace->addChild(rotation1); - rotation2 = new SoRotationXYZ ; + rotation2 = new SoRotationXYZ; rotation2->axis.setValue(SoRotationXYZ::Z); rotation2->angle.setValue(0); workplace->addChild(rotation2); - scale = new SoScale ; - scale->scaleFactor.setValue(0.001f,0.001f,0.001f); // scale from mm to m as needed by the Rift + scale = new SoScale; + scale->scaleFactor.setValue(0.001f, 0.001f, 0.001f); // scale from mm to m as needed by the Rift workplace->addChild(scale); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Oculus"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Oculus" + ); - this->setGeometry( hGrp->GetInt("RenderWindowPosX",100) , - hGrp->GetInt("RenderWindowPosY",100) , - hGrp->GetInt("RenderWindowSizeW",1920) , - hGrp->GetInt("RenderWindowSizeH",1080) - ); + this->setGeometry( + hGrp->GetInt("RenderWindowPosX", 100), + hGrp->GetInt("RenderWindowPosY", 100), + hGrp->GetInt("RenderWindowSizeW", 1920), + hGrp->GetInt("RenderWindowSizeH", 1080) + ); - setBackgroundColor(SbColor(51,51,101)); + setBackgroundColor(SbColor(51, 51, 101)); basePosition = SbVec3f(0.0f, 0.5f, 0.8f); } -//void saveWinPosition(void) +// void saveWinPosition(void) //{ // // // -//} +// } View3DInventorRiftViewer::~View3DInventorRiftViewer() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Oculus"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Oculus" + ); // remember last position on close - hGrp->SetInt("RenderWindowPosX",pos().x()); - hGrp->SetInt("RenderWindowPosY",pos().y()); - hGrp->SetInt("RenderWindowSizeW",size().width()); - hGrp->SetInt("RenderWindowSizeH",size().height()); + hGrp->SetInt("RenderWindowPosX", pos().x()); + hGrp->SetInt("RenderWindowPosY", pos().y()); + hGrp->SetInt("RenderWindowSizeW", size().width()); + hGrp->SetInt("RenderWindowSizeH", size().height()); - Base::Console().log("pos: %d %d size: %d %d \n",pos().x(),pos().y(), - size().width(),size().height()); + Base::Console() + .log("pos: %d %d size: %d %d \n", pos().x(), pos().y(), size().width(), size().height()); } -void View3DInventorRiftViewer::setSceneGraph(SoNode *sceneGraph) +void View3DInventorRiftViewer::setSceneGraph(SoNode* sceneGraph) { workplace->addChild(sceneGraph); @@ -99,51 +103,57 @@ void View3DInventorRiftViewer::setSceneGraph(SoNode *sceneGraph) } - - -void View3DInventorRiftViewer::keyPressEvent(QKeyEvent *event) +void View3DInventorRiftViewer::keyPressEvent(QKeyEvent* event) { - static const float increment = 0.02; // move two centimeter per key - static const float rotIncrement = std::numbers::pi / 4; // move two 90° per key + static const float increment = 0.02; // move two centimeter per key + static const float rotIncrement = std::numbers::pi / 4; // move two 90° per key if (event->key() == Qt::Key_Plus) { - scale->scaleFactor.setValue(scale->scaleFactor.getValue() * 2.0f) ; - } else if (event->key() == Qt::Key_Minus) { - scale->scaleFactor.setValue(scale->scaleFactor.getValue() * 0.2f) ; - } else if (event->key() == Qt::Key_S) { - basePosition += SbVec3f(0,0,increment) ; - } else if (event->key() == Qt::Key_W) { - basePosition += SbVec3f(0,0,-increment) ; - } else if (event->key() == Qt::Key_Up) { - basePosition += SbVec3f(0,-increment,0) ; - } else if (event->key() == Qt::Key_Down) { - basePosition += SbVec3f(0,increment,0) ; - } else if (event->key() == Qt::Key_Left) { - rotation2->angle.setValue( rotation2->angle.getValue() + rotIncrement); - } else if (event->key() == Qt::Key_Right) { - rotation2->angle.setValue( rotation2->angle.getValue() - rotIncrement); - } else if (event->key() == Qt::Key_A) { - basePosition += SbVec3f(-increment,0,0) ; - } else if (event->key() == Qt::Key_D) { - basePosition += SbVec3f(increment,0,0) ; - } else { + scale->scaleFactor.setValue(scale->scaleFactor.getValue() * 2.0f); + } + else if (event->key() == Qt::Key_Minus) { + scale->scaleFactor.setValue(scale->scaleFactor.getValue() * 0.2f); + } + else if (event->key() == Qt::Key_S) { + basePosition += SbVec3f(0, 0, increment); + } + else if (event->key() == Qt::Key_W) { + basePosition += SbVec3f(0, 0, -increment); + } + else if (event->key() == Qt::Key_Up) { + basePosition += SbVec3f(0, -increment, 0); + } + else if (event->key() == Qt::Key_Down) { + basePosition += SbVec3f(0, increment, 0); + } + else if (event->key() == Qt::Key_Left) { + rotation2->angle.setValue(rotation2->angle.getValue() + rotIncrement); + } + else if (event->key() == Qt::Key_Right) { + rotation2->angle.setValue(rotation2->angle.getValue() - rotIncrement); + } + else if (event->key() == Qt::Key_A) { + basePosition += SbVec3f(-increment, 0, 0); + } + else if (event->key() == Qt::Key_D) { + basePosition += SbVec3f(increment, 0, 0); + } + else { CoinRiftWidget::keyPressEvent(event); } } - - // static test code ================================================================================ -static View3DInventorRiftViewer *window=0; +static View3DInventorRiftViewer* window = 0; -void oculusSetTestScene(View3DInventorRiftViewer *window) +void oculusSetTestScene(View3DInventorRiftViewer* window) { assert(window); // An example scene. - static const char * inlineSceneGraph[] = { + static const char* inlineSceneGraph[] = { "#Inventor V2.1 ascii\n", "\n", "Separator {\n", @@ -184,44 +194,43 @@ void oculusSetTestScene(View3DInventorRiftViewer *window) void oculusStop() { - //SoDB::finish(); - if(window){ + // SoDB::finish(); + if (window) { delete window; window = 0; ovr_Shutdown(); } - } bool oculusUp(void) { - return window!=0; + return window != 0; } View3DInventorRiftViewer* oculusStart(void) { - //SoDB::init(); + // SoDB::init(); - //QApplication app(argc, argv); - //qAddPostRoutine(cleanup); + // QApplication app(argc, argv); + // qAddPostRoutine(cleanup); - // Moved here because of https://developer.oculusvr.com/forums/viewtopic.php?f=17&t=7915&p=108503#p108503 - // Init libovr. + // Moved here because of + // https://developer.oculusvr.com/forums/viewtopic.php?f=17&t=7915&p=108503#p108503 Init libovr. if (!ovr_Initialize()) { qDebug() << "Could not initialize Oculus SDK."; return 0; } - if(window) + if (window) { return window; + } window = new View3DInventorRiftViewer; window->show(); return window; - //return app.exec(); + // return app.exec(); } - -#endif //BUILD_VR +#endif // BUILD_VR diff --git a/src/Gui/View3DInventorRiftViewer.h b/src/Gui/View3DInventorRiftViewer.h index ed5ff528af..2357319153 100644 --- a/src/Gui/View3DInventorRiftViewer.h +++ b/src/Gui/View3DInventorRiftViewer.h @@ -25,32 +25,33 @@ #if BUILD_VR -#include "CoinRiftWidget.h" +# include "CoinRiftWidget.h" -namespace Gui { +namespace Gui +{ -class View3DInventorRiftViewer : public CoinRiftWidget +class View3DInventorRiftViewer: public CoinRiftWidget { public: View3DInventorRiftViewer(); ~View3DInventorRiftViewer(); - virtual void setSceneGraph(SoNode *sceneGraph); + virtual void setSceneGraph(SoNode* sceneGraph); protected: - SoGroup *workplace; - SoTranslation *translation; - SoRotationXYZ *rotation1; - SoRotationXYZ *rotation2; - SoScale *scale; + SoGroup* workplace; + SoTranslation* translation; + SoRotationXYZ* rotation1; + SoRotationXYZ* rotation2; + SoScale* scale; protected: - void keyPressEvent(QKeyEvent *); + void keyPressEvent(QKeyEvent*); }; -} //namespace Gui +} // namespace Gui -#endif //BUILD_VR +#endif // BUILD_VR -#endif //GUI_View3DInventorRiftViewer_H \ No newline at end of file +#endif // GUI_View3DInventorRiftViewer_H diff --git a/src/Gui/View3DInventorSelection.cpp b/src/Gui/View3DInventorSelection.cpp index c0e153087b..b9ffd01b30 100644 --- a/src/Gui/View3DInventorSelection.cpp +++ b/src/Gui/View3DInventorSelection.cpp @@ -21,10 +21,10 @@ ****************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Application.h" @@ -37,7 +37,7 @@ #include #include -FC_LOG_LEVEL_INIT("3DViewerSelection",true,true) +FC_LOG_LEVEL_INIT("3DViewerSelection", true, true) using namespace Gui; @@ -92,49 +92,56 @@ View3DInventorSelection::~View3DInventorSelection() pcGroupOnTopSel->unref(); } -void View3DInventorSelection::checkGroupOnTop(const SelectionChanges &Reason) +void View3DInventorSelection::checkGroupOnTop(const SelectionChanges& Reason) { - if (Reason.Type == SelectionChanges::SetSelection || Reason.Type == SelectionChanges::ClrSelection) { + if (Reason.Type == SelectionChanges::SetSelection + || Reason.Type == SelectionChanges::ClrSelection) { clearGroupOnTop(); - if(Reason.Type == SelectionChanges::ClrSelection) + if (Reason.Type == SelectionChanges::ClrSelection) { return; + } } - if(Reason.Type == SelectionChanges::RmvPreselect || - Reason.Type == SelectionChanges::RmvPreselectSignal) - { - SoSelectionElementAction action(SoSelectionElementAction::None,true); + if (Reason.Type == SelectionChanges::RmvPreselect + || Reason.Type == SelectionChanges::RmvPreselectSignal) { + SoSelectionElementAction action(SoSelectionElementAction::None, true); action.apply(pcGroupOnTopPreSel); coinRemoveAllChildren(pcGroupOnTopPreSel); objectsOnTopPreSel.clear(); return; } - if(!getDocument() || !Reason.pDocName || !Reason.pDocName[0] || !Reason.pObjectName) + if (!getDocument() || !Reason.pDocName || !Reason.pDocName[0] || !Reason.pObjectName) { return; + } auto obj = getDocument()->getDocument()->getObject(Reason.pObjectName); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return; + } std::string key(obj->getNameInDocument()); key += '.'; auto subname = Reason.pSubName; App::ElementNamePair element; App::GeoFeature::resolveElement(obj, Reason.pSubName, element); - if (Data::isMappedElement(subname) - && !element.oldName.empty()) { // If we have a shortened element name - subname = element.oldName.c_str(); // use if + if (Data::isMappedElement(subname) && !element.oldName.empty()) { // If we have a shortened + // element name + subname = element.oldName.c_str(); // use if } - if(subname) + if (subname) { key += subname; - if(Reason.Type == SelectionChanges::RmvSelection) { - auto &objs = objectsOnTop; + } + if (Reason.Type == SelectionChanges::RmvSelection) { + auto& objs = objectsOnTop; auto pcGroup = pcGroupOnTopSel; auto it = objs.find(key.c_str()); - if(it == objs.end()) + if (it == objs.end()) { return; + } int index = pcGroup->findChild(it->second); - if(index >= 0) { + if (index >= 0) { auto node = static_cast(it->second); - SoSelectionElementAction action(node->getDetail()? - SoSelectionElementAction::Remove:SoSelectionElementAction::None,true); + SoSelectionElementAction action( + node->getDetail() ? SoSelectionElementAction::Remove : SoSelectionElementAction::None, + true + ); auto path = node->getPath(); SoTempPath tmpPath(2 + (path ? path->getLength() : 0)); tmpPath.ref(); @@ -146,81 +153,98 @@ void View3DInventorSelection::checkGroupOnTop(const SelectionChanges &Reason) tmpPath.unrefNoDelete(); pcGroup->removeChild(index); FC_LOG("remove annotation " << Reason.Type << " " << key); - }else + } + else { FC_LOG("remove annotation object " << Reason.Type << " " << key); + } objs.erase(it); return; } - auto &objs = Reason.Type==SelectionChanges::SetPreselect?objectsOnTopPreSel:objectsOnTop; - auto pcGroup = Reason.Type==SelectionChanges::SetPreselect?pcGroupOnTopPreSel:pcGroupOnTopSel; + auto& objs = Reason.Type == SelectionChanges::SetPreselect ? objectsOnTopPreSel : objectsOnTop; + auto pcGroup = Reason.Type == SelectionChanges::SetPreselect ? pcGroupOnTopPreSel + : pcGroupOnTopSel; - if(objs.find(key.c_str())!=objs.end()) + if (objs.find(key.c_str()) != objs.end()) { return; - auto vp = freecad_cast( - Application::Instance->getViewProvider(obj)); - if(!vp || !vp->isSelectable() || !vp->isShow()) + } + auto vp = freecad_cast(Application::Instance->getViewProvider(obj)); + if (!vp || !vp->isSelectable() || !vp->isShow()) { return; + } auto svp = vp; - if(subname && *subname) { + if (subname && *subname) { auto sobj = obj->getSubObject(subname); - if(!sobj || !sobj->isAttachedToDocument()) + if (!sobj || !sobj->isAttachedToDocument()) { return; - if(sobj!=obj) { + } + if (sobj != obj) { svp = freecad_cast( - Application::Instance->getViewProvider(sobj)); - if(!svp || !svp->isSelectable()) + Application::Instance->getViewProvider(sobj) + ); + if (!svp || !svp->isSelectable()) { return; + } } } int onTop; // onTop==2 means on top only if whole object is selected, // onTop==3 means on top only if some sub-element is selected // onTop==1 means either - if(Gui::Selection().needPickedList()) + if (Gui::Selection().needPickedList()) { onTop = 1; - else if(vp->OnTopWhenSelected.getValue()) + } + else if (vp->OnTopWhenSelected.getValue()) { onTop = vp->OnTopWhenSelected.getValue(); - else + } + else { onTop = svp->OnTopWhenSelected.getValue(); - if(Reason.Type == SelectionChanges::SetPreselect) { + } + if (Reason.Type == SelectionChanges::SetPreselect) { SoHighlightElementAction action; action.setHighlighted(true); action.setColor(selectionRoot->colorHighlight.getValue()); action.apply(pcGroupOnTopPreSel); - if(!onTop) + if (!onTop) { onTop = 2; - }else { - if(!onTop) + } + } + else { + if (!onTop) { return; + } SoSelectionElementAction action(SoSelectionElementAction::All); action.setColor(selectionRoot->colorHighlight.getValue()); action.apply(pcGroupOnTopSel); } - if(onTop==2 || onTop==3) { - if(subname && *subname) { + if (onTop == 2 || onTop == 3) { + if (subname && *subname) { size_t len = strlen(subname); - if(subname[len-1]=='.') { + if (subname[len - 1] == '.') { // ending with '.' means whole object selection - if(onTop == 3) + if (onTop == 3) { return; - }else if(onTop==2) + } + } + else if (onTop == 2) { return; - }else if(onTop==3) + } + } + else if (onTop == 3) { return; + } } std::vector groups; auto grpVp = vp; std::set visited; - for(auto childVp=vp;;childVp=grpVp) { + for (auto childVp = vp;; childVp = grpVp) { auto grp = App::GeoFeatureGroupExtension::getGroupOfObject(childVp->getObject()); if (!grp || !grp->isAttachedToDocument()) { break; } - grpVp = freecad_cast( - Application::Instance->getViewProvider(grp)); + grpVp = freecad_cast(Application::Instance->getViewProvider(grp)); if (!grpVp) { break; } @@ -233,16 +257,18 @@ void View3DInventorSelection::checkGroupOnTop(const SelectionChanges &Reason) auto childRoot = grpVp->getChildRoot(); auto modeSwitch = grpVp->getModeSwitch(); auto idx = modeSwitch->whichChild.getValue(); - if(idx<0 || idx>=modeSwitch->getNumChildren() || - modeSwitch->getChild(idx)!=childRoot) - { - FC_LOG("skip " << obj->getFullName() << '.' << (subname?subname:"") - << ", hidden inside geo group"); + if (idx < 0 || idx >= modeSwitch->getNumChildren() || modeSwitch->getChild(idx) != childRoot) { + FC_LOG( + "skip " << obj->getFullName() << '.' << (subname ? subname : "") + << ", hidden inside geo group" + ); return; } - if(childRoot->findChild(childVp->getRoot())<0) { - FC_LOG("cannot find '" << childVp->getObject()->getFullName() - << "' in geo group '" << grp->getNameInDocument() << "'"); + if (childRoot->findChild(childVp->getRoot()) < 0) { + FC_LOG( + "cannot find '" << childVp->getObject()->getFullName() << "' in geo group '" + << grp->getNameInDocument() << "'" + ); break; } groups.push_back(grpVp); @@ -251,22 +277,22 @@ void View3DInventorSelection::checkGroupOnTop(const SelectionChanges &Reason) SoTempPath path(10); path.ref(); - for(auto it=groups.rbegin();it!=groups.rend();++it) { + for (auto it = groups.rbegin(); it != groups.rend(); ++it) { auto grpVp = *it; path.append(grpVp->getRoot()); path.append(grpVp->getModeSwitch()); path.append(grpVp->getChildRoot()); } - SoDetail *det = nullptr; - if(vp->getDetailPath(subname, &path,true,det) && path.getLength()) { + SoDetail* det = nullptr; + if (vp->getDetailPath(subname, &path, true, det) && path.getLength()) { auto node = new SoFCPathAnnotation; node->setPath(&path); pcGroup->addChild(node); - if(det) { - SoSelectionElementAction action(SoSelectionElementAction::Append,true); + if (det) { + SoSelectionElementAction action(SoSelectionElementAction::Append, true); action.setElement(det); - SoTempPath tmpPath(path.getLength()+2); + SoTempPath tmpPath(path.getLength() + 2); tmpPath.ref(); tmpPath.append(pcGroup); tmpPath.append(node); @@ -285,10 +311,10 @@ void View3DInventorSelection::checkGroupOnTop(const SelectionChanges &Reason) void View3DInventorSelection::clearGroupOnTop() { - if(!objectsOnTop.empty() || !objectsOnTopPreSel.empty()) { + if (!objectsOnTop.empty() || !objectsOnTopPreSel.empty()) { objectsOnTop.clear(); objectsOnTopPreSel.clear(); - SoSelectionElementAction action(SoSelectionElementAction::None,true); + SoSelectionElementAction action(SoSelectionElementAction::None, true); action.apply(pcGroupOnTopPreSel); action.apply(pcGroupOnTopSel); coinRemoveAllChildren(pcGroupOnTopSel); diff --git a/src/Gui/View3DInventorSelection.h b/src/Gui/View3DInventorSelection.h index 39f8c38f1d..229b6270d5 100644 --- a/src/Gui/View3DInventorSelection.h +++ b/src/Gui/View3DInventorSelection.h @@ -31,7 +31,8 @@ class SoGroup; class SoNode; class SoSeparator; -namespace Gui { +namespace Gui +{ class Document; class SoFCUnifiedSelection; @@ -42,26 +43,28 @@ public: View3DInventorSelection(SoFCUnifiedSelection* root); ~View3DInventorSelection(); - void setDocument(Gui::Document *pcDocument) { + void setDocument(Gui::Document* pcDocument) + { guiDocument = pcDocument; } - Gui::Document* getDocument() const { + Gui::Document* getDocument() const + { return guiDocument; } - void checkGroupOnTop(const SelectionChanges &Reason); + void checkGroupOnTop(const SelectionChanges& Reason); void clearGroupOnTop(); private: - SoGroup * pcGroupOnTop; - SoGroup * pcGroupOnTopSel; - SoGroup * pcGroupOnTopPreSel; + SoGroup* pcGroupOnTop; + SoGroup* pcGroupOnTopSel; + SoGroup* pcGroupOnTopPreSel; SoFCUnifiedSelection* selectionRoot; std::map objectsOnTop; std::map objectsOnTopPreSel; Gui::Document* guiDocument = nullptr; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEW3DINVENTORSELECTION_H +#endif // GUI_VIEW3DINVENTORSELECTION_H diff --git a/src/Gui/View3DInventorViewer.cpp b/src/Gui/View3DInventorViewer.cpp index 1043414914..62368359b7 100644 --- a/src/Gui/View3DInventorViewer.cpp +++ b/src/Gui/View3DInventorViewer.cpp @@ -24,71 +24,71 @@ #include -# ifdef FC_OS_WIN32 -# include -# endif -# ifdef FC_OS_MACOSX +#ifdef FC_OS_WIN32 +# include +#endif +#ifdef FC_OS_MACOSX # include -# else +#else # include # include # include -# endif +#endif -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -#if defined(Q_OS_LINUX) && QT_VERSION < QT_VERSION_CHECK(6,6,0) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(Q_OS_LINUX) && QT_VERSION < QT_VERSION_CHECK(6, 6, 0) # include # define HAS_QTBUG_95434 #endif -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -155,10 +155,12 @@ As ProgressBar has no chance to control the incoming Qt events of Quarter so we the event handling to prevent the scenegraph from being selected or deselected while the progress bar is running. */ -class Gui::ViewerEventFilter : public QObject +class Gui::ViewerEventFilter: public QObject { public: - ViewerEventFilter() : longPressTimer(new QTimer(this)) { + ViewerEventFilter() + : longPressTimer(new QTimer(this)) + { longPressTimer->setSingleShot(true); connect(longPressTimer, &QTimer::timeout, [this]() { if (currentViewer) { @@ -169,11 +171,13 @@ public: ~ViewerEventFilter() override = default; private: - void triggerClarifySelection() { + void triggerClarifySelection() + { Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand('Std_ClarifySelection')"); } - bool shouldEnableLongPress(View3DInventorViewer* viewer, const QPoint& pos, bool ctrlPressed) const { + bool shouldEnableLongPress(View3DInventorViewer* viewer, const QPoint& pos, bool ctrlPressed) const + { bool enabled = App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") ->GetBool("EnableLongPressClarifySelection", true); @@ -188,8 +192,9 @@ private: if (auto* navStyle = viewer->navigationStyle()) { // reject if navigation style requires ctrl and it's not pressed or we're under a dragger - if ((navStyle->clarifySelectionMode() == NavigationStyle::ClarifySelectionMode::Ctrl && !ctrlPressed) || - navStyle->isDraggerUnderCursor(SbVec2s(pos.x(), pos.y()))) { + if ((navStyle->clarifySelectionMode() == NavigationStyle::ClarifySelectionMode::Ctrl + && !ctrlPressed) + || navStyle->isDraggerUnderCursor(SbVec2s(pos.x(), pos.y()))) { return false; } } @@ -202,7 +207,8 @@ private: View3DInventorViewer* currentViewer = nullptr; public: - bool eventFilter(QObject* obj, QEvent* event) override { + bool eventFilter(QObject* obj, QEvent* event) override + { // Bug #0000607: Some mice also support horizontal scrolling which however might // lead to some unwanted zooming when pressing the MMB for panning. // Thus, we filter out horizontal scrolling. @@ -217,8 +223,7 @@ public: if (ke->matches(QKeySequence::SelectAll)) { auto* viewer3d = static_cast(obj); auto* editingVP = viewer3d->getEditingViewProvider(); - if(!editingVP || !editingVP->selectAll()) - { + if (!editingVP || !editingVP->selectAll()) { viewer3d->selectAll(); } return true; @@ -253,8 +258,10 @@ public: if (shouldEnableLongPress(currentViewer, pressPosition, ctrlPressed)) { double longPressTimeout = App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetFloat("LongPressTimeout", 1.0); + .GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ) + ->GetFloat("LongPressTimeout", 1.0); longPressTimer->setInterval(static_cast(longPressTimeout * 1000)); longPressTimer->start(); } @@ -282,11 +289,15 @@ public: } }; -class SpaceNavigatorDevice : public Quarter::InputDevice { +class SpaceNavigatorDevice: public Quarter::InputDevice +{ public: - SpaceNavigatorDevice() : InputDevice(nullptr) {} + SpaceNavigatorDevice() + : InputDevice(nullptr) + {} ~SpaceNavigatorDevice() override = default; - const SoEvent* translateEvent(QEvent* event) override { + const SoEvent* translateEvent(QEvent* event) override + { if (event->type() == Spaceball::MotionEvent::MotionEventType) { auto motionEvent = static_cast(event); // NOLINT @@ -297,9 +308,9 @@ public: motionEvent->setHandled(true); - float xTrans{}; - float yTrans{}; - float zTrans{}; + float xTrans {}; + float yTrans {}; + float zTrans {}; xTrans = static_cast(motionEvent->translationX()); yTrans = static_cast(motionEvent->translationY()); zTrans = static_cast(motionEvent->translationZ()); @@ -309,9 +320,18 @@ public: SbRotation xRot; SbRotation yRot; SbRotation zRot; - xRot.setValue(SbVec3f(1.0, 0.0, 0.0), static_cast(motionEvent->rotationX()) * rotationConstant); - yRot.setValue(SbVec3f(0.0, 1.0, 0.0), static_cast(motionEvent->rotationY()) * rotationConstant); - zRot.setValue(SbVec3f(0.0, 0.0, 1.0), static_cast(motionEvent->rotationZ()) * rotationConstant); + xRot.setValue( + SbVec3f(1.0, 0.0, 0.0), + static_cast(motionEvent->rotationX()) * rotationConstant + ); + yRot.setValue( + SbVec3f(0.0, 1.0, 0.0), + static_cast(motionEvent->rotationY()) * rotationConstant + ); + zRot.setValue( + SbVec3f(0.0, 0.0, 1.0), + static_cast(motionEvent->rotationZ()) * rotationConstant + ); auto motion3Event = new SoMotion3Event; motion3Event->setTranslation(translationVector); @@ -394,7 +414,11 @@ View3DInventorViewer::View3DInventorViewer(QWidget* parent, const QOpenGLWidget* init(); } -View3DInventorViewer::View3DInventorViewer(const QSurfaceFormat& format, QWidget* parent, const QOpenGLWidget* sharewidget) +View3DInventorViewer::View3DInventorViewer( + const QSurfaceFormat& format, + QWidget* parent, + const QOpenGLWidget* sharewidget +) : Quarter::SoQTQuarterAdaptor(format, parent, sharewidget) , SelectionObserver(false, ResolveMode::NoResolve) , editViewProvider(nullptr) @@ -460,7 +484,7 @@ void View3DInventorViewer::init() backlight->ref(); backlight->setName("backlight"); backlight->direction.setValue(-hl->direction.getValue()); - backlight->on.setValue(false); // by default off + backlight->on.setValue(false); // by default off fillLight = new SoDirectionalLight(); fillLight->ref(); @@ -468,7 +492,7 @@ void View3DInventorViewer::init() fillLight->direction.setValue(-0.60F, -0.35F, -0.79F); fillLight->intensity.setValue(0.6F); fillLight->color.setValue(0.95F, 0.95F, 1.0F); - fillLight->on.setValue(false); // by default off + fillLight->on.setValue(false); // by default off // Set up background scenegraph with image in it. backgroundroot = new SoSeparator; @@ -540,13 +564,13 @@ void View3DInventorViewer::init() pcViewProviderRoot->addChild(dimensionRoot); auto dimensions3d = new SoSwitch(); dimensions3d->setName("_3dDimensions"); - dimensionRoot->addChild(dimensions3d); //first one will be for the 3d dimensions. + dimensionRoot->addChild(dimensions3d); // first one will be for the 3d dimensions. auto dimensionsDelta = new SoSwitch(); dimensionsDelta->setName("DeltaDimensions"); - dimensionRoot->addChild(dimensionsDelta); //second one for the delta dimensions. + dimensionRoot->addChild(dimensionsDelta); // second one for the delta dimensions. // This is a callback node that logs all action that traverse the Inventor tree. -#if defined (FC_DEBUG) && defined(FC_LOGGING_CB) +#if defined(FC_DEBUG) && defined(FC_LOGGING_CB) SoCallback* cb = new SoCallback; cb->setCallback(interactionLoggerCB, this); pcViewProviderRoot->addChild(cb); @@ -587,11 +611,16 @@ void View3DInventorViewer::init() this->getSoRenderManager()->getGLRenderAction()->setCacheContext(id); #ifdef TRACY_ENABLE - boxSelectionAction->enableElement(SoProfilerElement::getClassTypeId(), SoProfilerElement::getClassStackIndex()); + boxSelectionAction->enableElement( + SoProfilerElement::getClassTypeId(), + SoProfilerElement::getClassStackIndex() + ); #endif // set the transparency and antialiasing settings - getSoRenderManager()->getGLRenderAction()->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND); + getSoRenderManager()->getGLRenderAction()->setTransparencyType( + SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND + ); // Settings setSeekTime(0.4F); // NOLINT @@ -610,12 +639,13 @@ void View3DInventorViewer::init() addStartCallback(interactionStartCB); addFinishCallback(interactionFinishCB); - //filter a few qt events + // filter a few qt events viewerEventFilter = new ViewerEventFilter; installEventFilter(viewerEventFilter); #if defined(USE_3DCONNEXION_NAVLIB) ParameterGrp::handle hViewGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); if (hViewGrp->GetBool("LegacySpaceMouseDevices", false)) { getEventFilter()->registerInputDevice(new SpaceNavigatorDevice); } @@ -624,19 +654,25 @@ void View3DInventorViewer::init() #endif getEventFilter()->registerInputDevice(new GesturesDevice(this)); - try{ + try { this->grabGesture(Qt::PanGesture); this->grabGesture(Qt::PinchGesture); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { Base::Console().warning("Failed to set up gestures. Error: %s\n", e.what()); - } catch (...) { + } + catch (...) { Base::Console().warning("Failed to set up gestures. Unknown error.\n"); } - //create the cursors + // create the cursors createStandardCursors(); - connect(this, &View3DInventorViewer::devicePixelRatioChanged, - this, &View3DInventorViewer::createStandardCursors); + connect( + this, + &View3DInventorViewer::devicePixelRatioChanged, + this, + &View3DInventorViewer::createStandardCursors + ); naviCube = new NaviCube(this); naviCubeEnabled = true; @@ -646,7 +682,8 @@ void View3DInventorViewer::init() View3DInventorViewer::~View3DInventorViewer() { - // to prevent following OpenGL error message: "Texture is not valid in the current context. Texture has not been destroyed" + // to prevent following OpenGL error message: "Texture is not valid in the current context. + // Texture has not been destroyed" aboutToDestroyGLContext(); // It can happen that a document has several MDI views and when the about to be @@ -721,9 +758,9 @@ View3DInventorViewer::~View3DInventorViewer() void View3DInventorViewer::createStandardCursors() { - QPixmap panPixmap = BitmapFactory().pixmapFromSvg("cursor-pan", QSize(16,16)); - QPixmap spinPixmap = BitmapFactory().pixmapFromSvg("cursor-rotate", QSize(16,16)); - QPixmap zoomPixmap = BitmapFactory().pixmapFromSvg("cursor-zoom", QSize(16,16)); + QPixmap panPixmap = BitmapFactory().pixmapFromSvg("cursor-pan", QSize(16, 16)); + QPixmap spinPixmap = BitmapFactory().pixmapFromSvg("cursor-rotate", QSize(16, 16)); + QPixmap zoomPixmap = BitmapFactory().pixmapFromSvg("cursor-zoom", QSize(16, 16)); this->panCursor = QCursor(panPixmap, 8, 8); this->spinCursor = QCursor(spinPixmap, 8, 8); @@ -749,17 +786,18 @@ void View3DInventorViewer::setDocument(Gui::Document* pcDocument) selectionRoot->pcDocument = pcDocument; inventorSelection->setDocument(pcDocument); - if(pcDocument) { - const auto &sels = Selection().getSelection(pcDocument->getDocument()->getName(), ResolveMode::NoResolve); - for(auto &sel : sels) { - SelectionChanges Chng(SelectionChanges::ShowSelection, - sel.DocName,sel.FeatName,sel.SubName); + if (pcDocument) { + const auto& sels + = Selection().getSelection(pcDocument->getDocument()->getName(), ResolveMode::NoResolve); + for (auto& sel : sels) { + SelectionChanges Chng(SelectionChanges::ShowSelection, sel.DocName, sel.FeatName, sel.SubName); onSelectionChanged(Chng); } } } -Document* View3DInventorViewer::getDocument() { +Document* View3DInventorViewer::getDocument() +{ return guiDocument; } @@ -774,55 +812,55 @@ void View3DInventorViewer::initialize() } /// @cond DOXERR -void View3DInventorViewer::onSelectionChanged(const SelectionChanges & reason) +void View3DInventorViewer::onSelectionChanged(const SelectionChanges& reason) { - if(!getDocument()) { + if (!getDocument()) { return; } SelectionChanges Reason(reason); - if(Reason.pDocName && *Reason.pDocName && - strcmp(getDocument()->getDocument()->getName(),Reason.pDocName)!=0) { + if (Reason.pDocName && *Reason.pDocName + && strcmp(getDocument()->getDocument()->getName(), Reason.pDocName) != 0) { return; } - switch(Reason.Type) { - case SelectionChanges::ShowSelection: - case SelectionChanges::HideSelection: - if (Reason.Type == SelectionChanges::ShowSelection) { - Reason.Type = SelectionChanges::AddSelection; - } - else { - Reason.Type = SelectionChanges::RmvSelection; - } - // fall through - case SelectionChanges::SetPreselect: - if(Reason.SubType != SelectionChanges::MsgSource::TreeView) { + switch (Reason.Type) { + case SelectionChanges::ShowSelection: + case SelectionChanges::HideSelection: + if (Reason.Type == SelectionChanges::ShowSelection) { + Reason.Type = SelectionChanges::AddSelection; + } + else { + Reason.Type = SelectionChanges::RmvSelection; + } + // fall through + case SelectionChanges::SetPreselect: + if (Reason.SubType != SelectionChanges::MsgSource::TreeView) { + break; + } + // fall through + case SelectionChanges::RmvPreselect: + case SelectionChanges::RmvPreselectSignal: + case SelectionChanges::SetSelection: + case SelectionChanges::AddSelection: + case SelectionChanges::RmvSelection: + case SelectionChanges::ClrSelection: + inventorSelection->checkGroupOnTop(Reason); break; - } - // fall through - case SelectionChanges::RmvPreselect: - case SelectionChanges::RmvPreselectSignal: - case SelectionChanges::SetSelection: - case SelectionChanges::AddSelection: - case SelectionChanges::RmvSelection: - case SelectionChanges::ClrSelection: - inventorSelection->checkGroupOnTop(Reason); - break; - case SelectionChanges::SetPreselectSignal: - break; - default: - return; + case SelectionChanges::SetPreselectSignal: + break; + default: + return; } - if(Reason.Type == SelectionChanges::RmvPreselect || - Reason.Type == SelectionChanges::RmvPreselectSignal || - Reason.Type == SelectionChanges::SetPreselect) - { + if (Reason.Type == SelectionChanges::RmvPreselect + || Reason.Type == SelectionChanges::RmvPreselectSignal + || Reason.Type == SelectionChanges::SetPreselect) { SoFCPreselectionAction preselectionAction(Reason); preselectionAction.apply(pcViewProviderRoot); - } else { + } + else { SoFCSelectionAction selectionAction(Reason); selectionAction.apply(pcViewProviderRoot); } @@ -860,7 +898,8 @@ void View3DInventorViewer::addViewProvider(ViewProvider* pcProvider) if (root) { if (pcProvider->canAddToSceneGraph()) { - // Add to the physical object group if related to the physical object otherwise add to the scene graph + // Add to the physical object group if related to the physical object otherwise add to + // the scene graph if (pcProvider->isPartOfPhysicalObject()) { objectGroup->addChild(root); } @@ -915,43 +954,57 @@ void View3DInventorViewer::removeViewProvider(ViewProvider* pcProvider) _ViewProviderSet.erase(pcProvider); } -void View3DInventorViewer::setEditingTransform(const Base::Matrix4D &mat) +void View3DInventorViewer::setEditingTransform(const Base::Matrix4D& mat) { // NOLINTBEGIN if (pcEditingTransform) { double dMtrx[16]; mat.getGLMatrix(dMtrx); pcEditingTransform->setMatrix(SbMatrix( - dMtrx[0], dMtrx[1], dMtrx[2], dMtrx[3], - dMtrx[4], dMtrx[5], dMtrx[6], dMtrx[7], - dMtrx[8], dMtrx[9], dMtrx[10], dMtrx[11], - dMtrx[12],dMtrx[13],dMtrx[14], dMtrx[15])); + dMtrx[0], + dMtrx[1], + dMtrx[2], + dMtrx[3], + dMtrx[4], + dMtrx[5], + dMtrx[6], + dMtrx[7], + dMtrx[8], + dMtrx[9], + dMtrx[10], + dMtrx[11], + dMtrx[12], + dMtrx[13], + dMtrx[14], + dMtrx[15] + )); } // NOLINTEND } -void View3DInventorViewer::setupEditingRoot(SoNode *node, const Base::Matrix4D *mat) { - if(!editViewProvider) { +void View3DInventorViewer::setupEditingRoot(SoNode* node, const Base::Matrix4D* mat) +{ + if (!editViewProvider) { return; } resetEditingRoot(false); - if(mat) { + if (mat) { setEditingTransform(*mat); } else { setEditingTransform(getDocument()->getEditingTransform()); } - if(node) { + if (node) { restoreEditingRoot = false; pcEditingRoot->addChild(node); return; } restoreEditingRoot = true; auto root = editViewProvider->getRoot(); - for(int i=0,count=root->getNumChildren();igetChild(i); - if(node != editViewProvider->getTransformNode()) { + for (int i = 0, count = root->getNumChildren(); i < count; ++i) { + SoNode* node = root->getChild(i); + if (node != editViewProvider->getTransformNode()) { pcEditingRoot->addChild(node); } } @@ -961,10 +1014,10 @@ void View3DInventorViewer::setupEditingRoot(SoNode *node, const Base::Matrix4D * void View3DInventorViewer::resetEditingRoot(bool updateLinks) { - if(!editViewProvider || pcEditingRoot->getNumChildren()<=1) { + if (!editViewProvider || pcEditingRoot->getNumChildren() <= 1) { return; } - if(!restoreEditingRoot) { + if (!restoreEditingRoot) { pcEditingRoot->getChildren()->truncate(1); return; } @@ -974,7 +1027,7 @@ void View3DInventorViewer::resetEditingRoot(bool updateLinks) FC_ERR("WARNING!!! Editing view provider root node is tampered"); } root->addChild(editViewProvider->getTransformNode()); - for (int i=1,count=pcEditingRoot->getNumChildren();igetNumChildren(); i < count; ++i) { root->addChild(pcEditingRoot->getChild(i)); } pcEditingRoot->getChildren()->truncate(1); @@ -1008,21 +1061,23 @@ void View3DInventorViewer::resetEditingRoot(bool updateLinks) } catch (Py::Exception& e) { e.clear(); - Base::Console().error("Unexpected exception raised in View3DInventorViewer::resetEditingRoot\n"); + Base::Console().error( + "Unexpected exception raised in View3DInventorViewer::resetEditingRoot\n" + ); } } } SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec2s& pos, const ViewProvider* vp) const { - SoPath *path{}; + SoPath* path {}; if (vp == editViewProvider && pcEditingRoot->getNumChildren() > 1) { path = new SoPath(1); path->ref(); path->append(pcEditingRoot); } else { - //first get the path to this node and calculate the current transformation + // first get the path to this node and calculate the current transformation SoSearchAction sa; sa.setNode(vp->getRoot()); sa.setSearchingAll(true); @@ -1048,7 +1103,7 @@ SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec2s& pos, const Vie root->addChild(trans); root->addChild(path->getTail()); - //get the picked point + // get the picked point SoRayPickAction rp(getSoRenderManager()->getViewportRegion()); rp.setPoint(pos); rp.setRadius(getPickRadius()); @@ -1061,19 +1116,23 @@ SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec2s& pos, const Vie return (pick ? new SoPickedPoint(*pick) : nullptr); } -SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec3f& pos, const SbVec3f& dir, const ViewProvider* vp) const +SoPickedPoint* View3DInventorViewer::getPointOnRay( + const SbVec3f& pos, + const SbVec3f& dir, + const ViewProvider* vp +) const { // Note: There seems to be a bug with setRay() which causes SoRayPickAction // to fail to get intersections between the ray and a line - SoPath *path{}; + SoPath* path {}; if (vp == editViewProvider && pcEditingRoot->getNumChildren() > 1) { path = new SoPath(1); path->ref(); path->append(pcEditingRoot); } else { - //first get the path to this node and calculate the current setTransformation + // first get the path to this node and calculate the current setTransformation SoSearchAction sa; sa.setNode(vp->getRoot()); sa.setSearchingAll(true); @@ -1099,9 +1158,9 @@ SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec3f& pos, const SbV root->addChild(trans); root->addChild(path->getTail()); - //get the picked point + // get the picked point SoRayPickAction rp(getSoRenderManager()->getViewportRegion()); - rp.setRay(pos,dir); + rp.setRay(pos, dir); rp.setRadius(getPickRadius()); rp.apply(root); root->unref(); @@ -1110,7 +1169,7 @@ SoPickedPoint* View3DInventorViewer::getPointOnRay(const SbVec3f& pos, const SbV // returns a copy of the point SoPickedPoint* pick = rp.getPickedPoint(); - //return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows + // return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows return (pick ? new SoPickedPoint(*pick) : nullptr); } @@ -1123,7 +1182,7 @@ void View3DInventorViewer::setEditingViewProvider(Gui::ViewProvider* vp, int Mod this->navigation->findBoundingSphere(); #endif - addEventCallback(SoEvent::getClassTypeId(), Gui::ViewProvider::eventCallback,this->editViewProvider); + addEventCallback(SoEvent::getClassTypeId(), Gui::ViewProvider::eventCallback, this->editViewProvider); } /// reset from edit mode @@ -1142,7 +1201,11 @@ void View3DInventorViewer::resetEditingViewProvider() resetEditingRoot(); this->editViewProvider->unsetEditViewer(this); - removeEventCallback(SoEvent::getClassTypeId(), Gui::ViewProvider::eventCallback,this->editViewProvider); + removeEventCallback( + SoEvent::getClassTypeId(), + Gui::ViewProvider::eventCallback, + this->editViewProvider + ); this->editViewProvider = nullptr; } } @@ -1245,9 +1308,9 @@ void View3DInventorViewer::clearBufferCB(void* ud, SoAction* action) void View3DInventorViewer::setGLWidgetCB(void* userdata, SoAction* action) { - //FIXME: This causes the Coin error message: - // Coin error in SoNode::GLRenderS(): GL error: 'GL_STACK_UNDERFLOW', nodetype: - // Separator (set envvar COIN_GLERROR_DEBUGGING=1 and re-run to get more information) + // FIXME: This causes the Coin error message: + // Coin error in SoNode::GLRenderS(): GL error: 'GL_STACK_UNDERFLOW', nodetype: + // Separator (set envvar COIN_GLERROR_DEBUGGING=1 and re-run to get more information) if (action->isOfType(SoGLRenderAction::getClassTypeId())) { auto gl = static_cast(userdata); SoGLWidgetElement::set(action->getState(), qobject_cast(gl)); @@ -1266,23 +1329,23 @@ void View3DInventorViewer::handleEventCB(void* userdata, SoEventCallback* n) void View3DInventorViewer::setGradientBackground(View3DInventorViewer::Background grad) { switch (grad) { - case Background::NoGradient: - if (backgroundroot->findChild(pcBackGround) != -1) { - backgroundroot->removeChild(pcBackGround); - } - break; - case Background::LinearGradient: - pcBackGround->setGradient(SoFCBackgroundGradient::LINEAR); - if (backgroundroot->findChild(pcBackGround) == -1) { - backgroundroot->addChild(pcBackGround); - } - break; - case Background::RadialGradient: - pcBackGround->setGradient(SoFCBackgroundGradient::RADIAL); - if (backgroundroot->findChild(pcBackGround) == -1) { - backgroundroot->addChild(pcBackGround); - } - break; + case Background::NoGradient: + if (backgroundroot->findChild(pcBackGround) != -1) { + backgroundroot->removeChild(pcBackGround); + } + break; + case Background::LinearGradient: + pcBackGround->setGradient(SoFCBackgroundGradient::LINEAR); + if (backgroundroot->findChild(pcBackGround) == -1) { + backgroundroot->addChild(pcBackGround); + } + break; + case Background::RadialGradient: + pcBackGround->setGradient(SoFCBackgroundGradient::RADIAL); + if (backgroundroot->findChild(pcBackGround) == -1) { + backgroundroot->addChild(pcBackGround); + } + break; } } @@ -1299,15 +1362,16 @@ View3DInventorViewer::Background View3DInventorViewer::getGradientBackground() c return Background::RadialGradient; } -void View3DInventorViewer::setGradientBackgroundColor(const SbColor& fromColor, - const SbColor& toColor) +void View3DInventorViewer::setGradientBackgroundColor(const SbColor& fromColor, const SbColor& toColor) { pcBackGround->setColorGradient(fromColor, toColor); } -void View3DInventorViewer::setGradientBackgroundColor(const SbColor& fromColor, - const SbColor& toColor, - const SbColor& midColor) +void View3DInventorViewer::setGradientBackgroundColor( + const SbColor& fromColor, + const SbColor& toColor, + const SbColor& midColor +) { pcBackGround->setColorGradient(fromColor, toColor, midColor); } @@ -1357,7 +1421,7 @@ void View3DInventorViewer::setRenderCache(int mode) } if (canAutoCache < 0) { - const char *env = coin_getenv("COIN_AUTO_CACHING"); + const char* env = coin_getenv("COIN_AUTO_CACHING"); canAutoCache = env ? atoi(env) : 1; } @@ -1367,9 +1431,7 @@ void View3DInventorViewer::setRenderCache(int mode) mode = 1; } - auto caching = mode == 0 ? SoSeparator::AUTO : - (mode == 1 ? SoSeparator::ON : - SoSeparator::OFF); + auto caching = mode == 0 ? SoSeparator::AUTO : (mode == 1 ? SoSeparator::ON : SoSeparator::OFF); SoFCSeparator::setCacheMode(caching); } @@ -1446,7 +1508,7 @@ void View3DInventorViewer::showRotationCenter(bool show) ->GetBool("ShowRotationCenter", true); if (show && showEnabled) { - SbBool found{}; + SbBool found {}; SbVec3f center = navigation->getRotationCenter(found); if (!found) { @@ -1458,10 +1520,10 @@ void View3DInventorViewer::showRotationCenter(bool show) .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") ->GetFloat("RotationCenterSize", 5.0); // NOLINT - unsigned long rotationCenterColor = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetUnsigned("RotationCenterColor", 4278190131); // NOLINT + unsigned long rotationCenterColor + = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetUnsigned("RotationCenterColor", 4278190131); // NOLINT QColor color = Base::Color::fromPackedRGBA(rotationCenterColor); @@ -1469,7 +1531,8 @@ void View3DInventorViewer::showRotationCenter(bool show) auto sphere = new SoSphere(); - // There needs to be a non-transparent object to ensure the transparent sphere works when opening an new empty document + // There needs to be a non-transparent object to ensure the transparent sphere works + // when opening an new empty document auto hidden = new SoSeparator(); auto hiddenScale = new SoScale(); hiddenScale->scaleFactor = SbVec3f(0, 0, 0); @@ -1480,9 +1543,8 @@ void View3DInventorViewer::showRotationCenter(bool show) complexity->value = 1; auto material = new SoMaterial(); - material->emissiveColor = SbColor(float(color.redF()), - float(color.greenF()), - float(color.blueF())); + material->emissiveColor + = SbColor(float(color.redF()), float(color.greenF()), float(color.blueF())); material->transparency = 1.0F - float(color.alphaF()); auto translation = new SoTranslation(); @@ -1514,12 +1576,15 @@ void View3DInventorViewer::showRotationCenter(bool show) } // Changes the position of the rotation center indicator -void View3DInventorViewer::changeRotationCenterPosition(const SbVec3f& newCenter) { +void View3DInventorViewer::changeRotationCenterPosition(const SbVec3f& newCenter) +{ if (!rotationCenterGroup) { return; } - SoTranslation* translation = dynamic_cast(rotationCenterGroup->getByName("translation")); + SoTranslation* translation = dynamic_cast( + rotationCenterGroup->getByName("translation") + ); if (!translation) { return; } @@ -1530,22 +1595,25 @@ void View3DInventorViewer::changeRotationCenterPosition(const SbVec3f& newCenter void View3DInventorViewer::setNavigationType(Base::Type type) { if (this->navigation && this->navigation->getTypeId() == type) { - return; // nothing to do + return; // nothing to do } - Base::Type navtype = Base::Type::getTypeIfDerivedFrom(type.getName(), NavigationStyle::getClassTypeId()); + Base::Type navtype + = Base::Type::getTypeIfDerivedFrom(type.getName(), NavigationStyle::getClassTypeId()); auto ns = static_cast(navtype.createInstance()); // createInstance could return a null pointer if (!ns) { #if FC_DEBUG - SoDebugError::postWarning("View3DInventorViewer::setNavigationType", - "Navigation object must be of type NavigationStyle."); -#endif // FC_DEBUG + SoDebugError::postWarning( + "View3DInventorViewer::setNavigationType", + "Navigation object must be of type NavigationStyle." + ); +#endif // FC_DEBUG return; } if (this->navigation) { - ns->operator = (*this->navigation); + ns->operator=(*this->navigation); delete this->navigation; } this->navigation = ns; @@ -1602,8 +1670,8 @@ void View3DInventorViewer::setSceneGraph(SoNode* root) SoSearchAction sa; sa.setNode(this->backlight); - //we want the rendered scene with all lights and cameras, viewer->getSceneGraph would return - //the geometry scene only + // we want the rendered scene with all lights and cameras, viewer->getSceneGraph would return + // the geometry scene only SoNode* scene = this->getSoRenderManager()->getSceneGraph(); if (scene && scene->getTypeId().isDerivedFrom(SoSeparator::getClassTypeId())) { sa.apply(scene); @@ -1623,8 +1691,9 @@ void View3DInventorViewer::savePicture(int width, int height, int sample, const // FramebufferObject -- viewer renders into FBO (no offscreen) // CoinOffscreenRenderer -- Coin's offscreen rendering method // Otherwise (Default) -- Qt's FBO used for offscreen rendering - std::string saveMethod = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View")->GetASCII("SavePicture"); + std::string saveMethod = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetASCII("SavePicture"); bool useFramebufferObject = false; bool useGrabFramebuffer = false; @@ -1661,10 +1730,10 @@ void View3DInventorViewer::savePicture(int width, int height, int sample, const vp.setWindowSize(short(width), short(height)); } - //NOTE: To support pixels per inch we must use SbViewportRegion::setPixelsPerInch( ppi ); - //The default value is 72.0. - //If we need to support grayscale images with must either use SoOffscreenRenderer::LUMINANCE or - //SoOffscreenRenderer::LUMINANCE_TRANSPARENCY. + // NOTE: To support pixels per inch we must use SbViewportRegion::setPixelsPerInch( ppi ); + // The default value is 72.0. + // If we need to support grayscale images with must either use SoOffscreenRenderer::LUMINANCE or + // SoOffscreenRenderer::LUMINANCE_TRANSPARENCY. SoCallback* cb = nullptr; @@ -1721,10 +1790,12 @@ void View3DInventorViewer::savePicture(int width, int height, int sample, const renderer.setNumPasses(sample); renderer.setInternalTextureFormat(getInternalTextureFormat()); if (bgColor.isValid()) { - renderer.setBackgroundColor(SbColor4f(float(bgColor.redF()), - float(bgColor.greenF()), - float(bgColor.blueF()), - float(bgColor.alphaF()))); + renderer.setBackgroundColor(SbColor4f( + float(bgColor.redF()), + float(bgColor.greenF()), + float(bgColor.blueF()), + float(bgColor.alphaF()) + )); } if (!renderer.render(root)) { throw Base::RuntimeError("Offscreen rendering failed"); @@ -1738,11 +1809,13 @@ void View3DInventorViewer::savePicture(int width, int height, int sample, const renderer.setViewportRegion(vp); renderer.getGLRenderAction()->setSmoothing(true); renderer.getGLRenderAction()->setNumPasses(sample); - renderer.getGLRenderAction()->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND); + renderer.getGLRenderAction()->setTransparencyType( + SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND + ); if (bgColor.isValid()) { - renderer.setBackgroundColor(SbColor(float(bgColor.redF()), - float(bgColor.greenF()), - float(bgColor.blueF()))); + renderer.setBackgroundColor( + SbColor(float(bgColor.redF()), float(bgColor.greenF()), float(bgColor.blueF())) + ); } if (!renderer.render(root)) { throw Base::RuntimeError("Offscreen rendering failed"); @@ -1763,16 +1836,17 @@ void View3DInventorViewer::savePicture(int width, int height, int sample, const } catch (...) { root->unref(); - throw; // re-throw exception + throw; // re-throw exception } } void View3DInventorViewer::saveGraphic(int pagesize, const QColor& bgcolor, SoVectorizeAction* va) const { if (bgcolor.isValid()) { - va->setBackgroundColor(true, SbColor(float(bgcolor.redF()), - float(bgcolor.greenF()), - float(bgcolor.blueF()))); + va->setBackgroundColor( + true, + SbColor(float(bgcolor.redF()), float(bgcolor.greenF()), float(bgcolor.blueF())) + ); } const float border = 10.0F; @@ -1793,8 +1867,8 @@ void View3DInventorViewer::saveGraphic(int pagesize, const QColor& bgcolor, SoVe SbVec2f size = va->getPageSize(); float pageratio = size[0] / size[1]; - float xsize{}; - float ysize{}; + float xsize {}; + float ysize {}; if (pageratio < vpratio) { xsize = size[0]; @@ -1805,8 +1879,8 @@ void View3DInventorViewer::saveGraphic(int pagesize, const QColor& bgcolor, SoVe xsize = ysize * vpratio; } - float offx = border + (size[0]-xsize) * 0.5F; // NOLINT - float offy = border + (size[1]-ysize) * 0.5F; // NOLINT + float offx = border + (size[0] - xsize) * 0.5F; // NOLINT + float offy = border + (size[1] - ysize) * 0.5F; // NOLINT va->beginViewport(SbVec2f(offx, offy), SbVec2f(xsize, ysize)); va->calibrate(this->getSoRenderManager()->getViewportRegion()); @@ -1869,7 +1943,7 @@ SbVec2f View3DInventorViewer::screenCoordsOfPath(SoPath* path) const // Now, project the object space coordinates of the object // into "normalized" screen coordinates. - SbViewVolume vol = getSoRenderManager()->getCamera()->getViewVolume(); + SbViewVolume vol = getSoRenderManager()->getCamera()->getViewVolume(); vol.projectToScreen(imageCoords, imageCoords); // Translate "normalized" screen coordinates to pixel coords. @@ -1886,15 +1960,14 @@ SbVec2f View3DInventorViewer::screenCoordsOfPath(SoPath* path) const if (width >= height) { // "Landscape" orientation, to square imageCoords[0] *= height; - imageCoords[0] += (width-height) / 2.0; // NOLINT + imageCoords[0] += (width - height) / 2.0; // NOLINT imageCoords[1] *= height; - } else { // "Portrait" orientation imageCoords[0] *= width; imageCoords[1] *= width; - imageCoords[1] += (height-width) / 2.0; // NOLINT + imageCoords[1] += (height - width) / 2.0; // NOLINT } return {imageCoords[0], imageCoords[1]}; @@ -1902,21 +1975,21 @@ SbVec2f View3DInventorViewer::screenCoordsOfPath(SoPath* path) const std::vector View3DInventorViewer::getGLPolygon(const std::vector& pnts) const { - const SbViewportRegion &vp = this->getSoRenderManager()->getViewportRegion(); - const SbVec2s &sp = vp.getViewportSizePixels(); - const SbVec2s &op = vp.getViewportOriginPixels(); - const SbVec2f &vpSize = vp.getViewportSize(); - float dX{}; - float dY{}; + const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion(); + const SbVec2s& sp = vp.getViewportSizePixels(); + const SbVec2s& op = vp.getViewportOriginPixels(); + const SbVec2f& vpSize = vp.getViewportSize(); + float dX {}; + float dY {}; vpSize.getValue(dX, dY); float fRatio = vp.getViewportAspectRatio(); std::vector poly; - for (const auto & pnt : pnts) { + for (const auto& pnt : pnts) { SbVec2s loc = pnt - op; SbVec2f pos((float)loc[0] / (float)sp[0], (float)loc[1] / (float)sp[1]); - float pX{}; - float pY{}; + float pX {}; + float pY {}; pos.getValue(pX, pY); // now calculate the real points respecting aspect ratio information @@ -2053,8 +2126,9 @@ int View3DInventorViewer::getNumSamples() GLenum View3DInventorViewer::getInternalTextureFormat() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); std::string format = hGrp->GetASCII("InternalTextureFormat", "Default"); // NOLINTBEGIN @@ -2106,39 +2180,37 @@ void View3DInventorViewer::setRenderType(RenderType type) } switch (type) { - case Native: - break; - case Framebuffer: - if (!framebuffer) { - const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion(); - SbVec2s size = vp.getViewportSizePixels(); - int width = size[0]; - int height = size[1]; + case Native: + break; + case Framebuffer: + if (!framebuffer) { + const SbViewportRegion vp = this->getSoRenderManager()->getViewportRegion(); + SbVec2s size = vp.getViewportSizePixels(); + int width = size[0]; + int height = size[1]; - auto gl = static_cast(this->viewport()); // NOLINT - gl->makeCurrent(); - QOpenGLFramebufferObjectFormat fboFormat; - fboFormat.setSamples(getNumSamples()); - fboFormat.setAttachment(QOpenGLFramebufferObject::Depth); - auto fbo = new QOpenGLFramebufferObject(width, height, fboFormat); - if (fbo->format().samples() > 0) { - renderToFramebuffer(fbo); - framebuffer = new QOpenGLFramebufferObject(fbo->size()); - // this is needed to be able to render the texture later - QOpenGLFramebufferObject::blitFramebuffer(framebuffer, fbo); - delete fbo; + auto gl = static_cast(this->viewport()); // NOLINT + gl->makeCurrent(); + QOpenGLFramebufferObjectFormat fboFormat; + fboFormat.setSamples(getNumSamples()); + fboFormat.setAttachment(QOpenGLFramebufferObject::Depth); + auto fbo = new QOpenGLFramebufferObject(width, height, fboFormat); + if (fbo->format().samples() > 0) { + renderToFramebuffer(fbo); + framebuffer = new QOpenGLFramebufferObject(fbo->size()); + // this is needed to be able to render the texture later + QOpenGLFramebufferObject::blitFramebuffer(framebuffer, fbo); + delete fbo; + } + else { + renderToFramebuffer(fbo); + framebuffer = fbo; + } } - else { - renderToFramebuffer(fbo); - framebuffer = fbo; - } - } - break; - case Image: - { + break; + case Image: { glImage = grabFramebuffer(); - } - break; + } break; } } @@ -2179,7 +2251,7 @@ QImage View3DInventorViewer::grabFramebuffer() QImage image(res.width(), res.height(), QImage::Format_RGB32); QPainter painter(&image); - painter.fillRect(image.rect(),Qt::black); + painter.fillRect(image.rect(), Qt::black); painter.drawImage(0, 0, res); painter.end(); res = image; @@ -2188,8 +2260,13 @@ QImage View3DInventorViewer::grabFramebuffer() return res; } -void View3DInventorViewer::imageFromFramebuffer(int width, int height, int samples, - const QColor& bgcolor, QImage& img) +void View3DInventorViewer::imageFromFramebuffer( + int width, + int height, + int samples, + const QColor& bgcolor, + QImage& img +) { auto gl = static_cast(this->viewport()); // NOLINT gl->makeCurrent(); @@ -2239,7 +2316,7 @@ void View3DInventorViewer::imageFromFramebuffer(int width, int height, int sampl img = image.copy(); QRgb rgba = bgcolor.rgba(); QRgb rgb = bgopaque.rgb(); - QRgb * bits = (QRgb*) img.bits(); + QRgb* bits = (QRgb*)img.bits(); for (int yy = 0; yy < height; yy++) { for (int xx = 0; xx < width; xx++) { if (*bits == rgb) { @@ -2252,7 +2329,7 @@ void View3DInventorViewer::imageFromFramebuffer(int width, int height, int sampl else if (alpha == maxAlpha) { QImage image(img.width(), img.height(), QImage::Format_RGB32); QPainter painter(&image); - painter.fillRect(image.rect(),Qt::black); + painter.fillRect(image.rect(), Qt::black); painter.drawImage(0, 0, img); painter.end(); img = image; @@ -2306,15 +2383,15 @@ void View3DInventorViewer::renderToFramebuffer(QOpenGLFramebufferObject* fbo) void View3DInventorViewer::actualRedraw() { switch (renderType) { - case Native: - renderScene(); - break; - case Framebuffer: - renderFramebuffer(); - break; - case Image: - renderGLImage(); - break; + case Native: + renderScene(); + break; + case Framebuffer: + renderFramebuffer(); + break; + case Image: + renderGLImage(); + break; } } @@ -2338,14 +2415,14 @@ void View3DInventorViewer::renderFramebuffer() glColor3f(1.0, 1.0, 1.0); glBegin(GL_QUADS); - glTexCoord2f(0.0F, 0.0F); - glVertex2f(-1.0, -1.0F); - glTexCoord2f(1.0F, 0.0F); - glVertex2f(1.0F, -1.0F); - glTexCoord2f(1.0F, 1.0F); - glVertex2f(1.0F, 1.0F); - glTexCoord2f(0.0F, 1.0F); - glVertex2f(-1.0F, 1.0F); + glTexCoord2f(0.0F, 0.0F); + glVertex2f(-1.0, -1.0F); + glTexCoord2f(1.0F, 0.0F); + glVertex2f(1.0F, -1.0F); + glTexCoord2f(1.0F, 1.0F); + glVertex2f(1.0F, 1.0F); + glTexCoord2f(0.0F, 1.0F); + glVertex2f(-1.0F, 1.0F); glEnd(); printDimension(); @@ -2378,8 +2455,8 @@ void View3DInventorViewer::renderGLImage() glDisable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT); - glRasterPos2f(0,0); - glDrawPixels(glImage.width(), glImage.height(), GL_BGRA,GL_UNSIGNED_BYTE, glImage.bits()); + glRasterPos2f(0, 0); + glDrawPixels(glImage.width(), glImage.height(), GL_BGRA, GL_UNSIGNED_BYTE, glImage.bits()); printDimension(); @@ -2396,7 +2473,8 @@ void View3DInventorViewer::renderGLImage() // #define ENABLE_GL_DEPTH_RANGE // The calls of glDepthRange inside renderScene() causes problems with transparent objects -// so that's why it is disabled now: https://forum.freecad.org/viewtopic.php?f=3&t=6037&hilit=transparency +// so that's why it is disabled now: +// https://forum.freecad.org/viewtopic.php?f=3&t=6037&hilit=transparency // Documented in superclass. Overrides this method to be able to draw // the axis cross, if selected, and to keep a continuous animation @@ -2421,7 +2499,7 @@ void View3DInventorViewer::renderScene() #if defined(ENABLE_GL_DEPTH_RANGE) // using 90% of the z-buffer for the background and the main node - glDepthRange(0.1,1.0); + glDepthRange(0.1, 1.0); #endif SoGLRenderAction* glra = this->getSoRenderManager()->getGLRenderAction(); @@ -2450,35 +2528,40 @@ void View3DInventorViewer::renderScene() So3DAnnotation::render = true; glClear(GL_DEPTH_BUFFER_BIT); - + // process delayed paths with priority support if (Gui::Selection().isClarifySelectionActive()) { Gui::SoDelayedAnnotationsElement::processDelayedPathsWithPriority(state, glra); - } else { + } + else { // standard processing for normal delayed annotations glra->apply(Gui::SoDelayedAnnotationsElement::getDelayedPaths(state)); } - + So3DAnnotation::render = false; } catch (const Base::MemoryException&) { - // FIXME: If this exception appears then the background and camera position get broken somehow. (Werner 2006-02-01) + // FIXME: If this exception appears then the background and camera position get broken + // somehow. (Werner 2006-02-01) for (auto it : _ViewProviderSet) { it->hide(); } inherited::actualRedraw(); - QMessageBox::warning(parentWidget(), QObject::tr("Out of memory"), - QObject::tr("Not enough memory available to display the data.")); + QMessageBox::warning( + parentWidget(), + QObject::tr("Out of memory"), + QObject::tr("Not enough memory available to display the data.") + ); } if (!this->shading) { state->pop(); } -#if defined (ENABLE_GL_DEPTH_RANGE) +#if defined(ENABLE_GL_DEPTH_RANGE) // using 10% of the z-buffer for the foreground node - glDepthRange(0.0,0.1); + glDepthRange(0.0, 0.1); #endif // Render overlay front scenegraph. @@ -2491,9 +2574,9 @@ void View3DInventorViewer::renderScene() this->drawAxisCross(); } -#if defined (ENABLE_GL_DEPTH_RANGE) +#if defined(ENABLE_GL_DEPTH_RANGE) // using the main portion of z-buffer again (for frontbuffer highlighting) - glDepthRange(0.1,1.0); + glDepthRange(0.1, 1.0); #endif // Immediately reschedule to get continuous animation. @@ -2510,23 +2593,27 @@ void View3DInventorViewer::renderScene() } } - //fps rendering + // fps rendering if (fpsEnabled) { std::stringstream stream; stream.precision(1); stream.setf(std::ios::fixed | std::ios::showpoint); stream << framesPerSecond[0] << " ms / " << framesPerSecond[1] << " fps"; ParameterGrp::handle hGrpOverlayL = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/MainWindow/DockWindows/OverlayLeft"); + "User parameter:BaseApp/MainWindow/DockWindows/OverlayLeft" + ); std::string overlayLeftWidgets = hGrpOverlayL->GetASCII("Widgets", ""); ParameterGrp::handle hGrpView = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); - unsigned long axisLetterColor = - hGrpView->GetUnsigned("AxisLetterColor", 4294902015); // default FPS color (yellow) - draw2DString(stream.str().c_str(), - SbVec2s(10, 10), - SbVec2f((overlayLeftWidgets.empty() ? 0.1f : 1.1f), 0.1f), - Base::Color(static_cast(axisLetterColor))); // NOLINT + "User parameter:BaseApp/Preferences/View" + ); + unsigned long axisLetterColor + = hGrpView->GetUnsigned("AxisLetterColor", 4294902015); // default FPS color (yellow) + draw2DString( + stream.str().c_str(), + SbVec2s(10, 10), + SbVec2f((overlayLeftWidgets.empty() ? 0.1f : 1.1f), 0.1f), + Base::Color(static_cast(axisLetterColor)) + ); // NOLINT } if (naviCubeEnabled) { @@ -2567,15 +2654,17 @@ void View3DInventorViewer::setSeekMode(bool on) } inherited::setSeekMode(on); - navigation->setViewingMode(on ? NavigationStyle::SEEK_WAIT_MODE : - (this->isViewing() ? - NavigationStyle::IDLE : NavigationStyle::INTERACT)); + navigation->setViewingMode( + on ? NavigationStyle::SEEK_WAIT_MODE + : (this->isViewing() ? NavigationStyle::IDLE : NavigationStyle::INTERACT) + ); } -SbVec3f View3DInventorViewer::getCenterPointOnFocalPlane() const { +SbVec3f View3DInventorViewer::getCenterPointOnFocalPlane() const +{ SoCamera* cam = getSoRenderManager()->getCamera(); if (!cam) { - return {0. ,0. ,0. }; + return {0., 0., 0.}; } SbVec3f direction; @@ -2583,7 +2672,8 @@ SbVec3f View3DInventorViewer::getCenterPointOnFocalPlane() const { return cam->position.getValue() + cam->focalDistance.getValue() * direction; } -float View3DInventorViewer::getMaxDimension() const { +float View3DInventorViewer::getMaxDimension() const +{ float fHeight = -1.0; float fWidth = -1.0; getDimensions(fHeight, fWidth); @@ -2689,11 +2779,11 @@ bool View3DInventorViewer::processSoEvent(const SoEvent* ev) const auto ke = static_cast(ev); // NOLINT switch (ke->getKey()) { - case SoKeyboardEvent::ESCAPE: - case SoKeyboardEvent::Q: // ignore 'Q' keys (to prevent app from being closed) - return inherited::processSoEvent(ev); - default: - break; + case SoKeyboardEvent::ESCAPE: + case SoKeyboardEvent::Q: // ignore 'Q' keys (to prevent app from being closed) + return inherited::processSoEvent(ev); + default: + break; } } @@ -2711,7 +2801,7 @@ SbVec3f View3DInventorViewer::getViewDirection() const if (!cam) { // this is the default - return {0,0,-1}; + return {0, 0, -1}; } SbVec3f projDir = cam->getViewVolume().getProjectionDirection(); @@ -2730,11 +2820,11 @@ SbVec3f View3DInventorViewer::getUpDirection() const SoCamera* cam = this->getSoRenderManager()->getCamera(); if (!cam) { - return {0,1,0}; + return {0, 1, 0}; } SbRotation camrot = cam->orientation.getValue(); - SbVec3f upvec(0, 1, 0); // init to default up vector + SbVec3f upvec(0, 1, 0); // init to default up vector camrot.multVec(upvec, upvec); return upvec; } @@ -2745,7 +2835,7 @@ SbRotation View3DInventorViewer::getCameraOrientation() const if (!cam) { // this is the default - return {0,0,0,1}; + return {0, 0, 0, 1}; } return cam->orientation.getValue(); @@ -2755,12 +2845,12 @@ SbVec2f View3DInventorViewer::getNormalizedPosition(const SbVec2s& pnt) const { const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion(); - short xpos{}; - short ypos{}; + short xpos {}; + short ypos {}; pnt.getValue(xpos, ypos); SbVec2f siz = vp.getViewportSize(); - float dX{}; - float dY{}; + float dX {}; + float dY {}; siz.getValue(dX, dY); float fRatio = vp.getViewportAspectRatio(); @@ -2813,26 +2903,25 @@ Base::BoundBox2d View3DInventorViewer::getViewportOnXYPlaneOfPlacement(Base::Pla vp.getViewportSize().getValue(dX, dY); // Projects a pair of normalized coordinates on the XY plane. - auto projectPoint = - [&](float x, float y) { - if (fRatio > 1.f) { - x = (x - 0.5f * dX) * fRatio + 0.5f * dX; - } - else if (fRatio < 1.f) { - y = (y - 0.5f * dY) / fRatio + 0.5f * dY; - } + auto projectPoint = [&](float x, float y) { + if (fRatio > 1.f) { + x = (x - 0.5f * dX) * fRatio + 0.5f * dX; + } + else if (fRatio < 1.f) { + y = (y - 0.5f * dY) / fRatio + 0.5f * dY; + } - SbLine line; - vol.projectPointToLine(SbVec2f(x, y), line); + SbLine line; + vol.projectPointToLine(SbVec2f(x, y), line); - SbVec3f pt; - // Intersection point on the XY plane. - if (!xyPlane.intersect(line, pt)) { - return; - } + SbVec3f pt; + // Intersection point on the XY plane. + if (!xyPlane.intersect(line, pt)) { + return; + } - projBBox.Add(Base::convertTo(pt)); - }; + projBBox.Add(Base::convertTo(pt)); + }; // Project the four corners of the viewport plane. projectPoint(0.f, 0.f); @@ -2850,7 +2939,10 @@ Base::BoundBox2d View3DInventorViewer::getViewportOnXYPlaneOfPlacement(Base::Pla return projBBox.ProjectBox(&proj); } -SbVec3f View3DInventorViewer::getPointOnXYPlaneOfPlacement(const SbVec2s& pnt, const Base::Placement& plc) const +SbVec3f View3DInventorViewer::getPointOnXYPlaneOfPlacement( + const SbVec2s& pnt, + const Base::Placement& plc +) const { SbVec2f pnt2d = getNormalizedPosition(pnt); SoCamera* pCam = this->getSoRenderManager()->getCamera(); @@ -2859,7 +2951,7 @@ SbVec3f View3DInventorViewer::getPointOnXYPlaneOfPlacement(const SbVec2s& pnt, c throw Base::RuntimeError("No camera node found"); } - SbViewVolume vol = pCam->getViewVolume(); + SbViewVolume vol = pCam->getViewVolume(); SbLine line; vol.projectPointToLine(pnt2d, line); @@ -2875,13 +2967,14 @@ SbVec3f View3DInventorViewer::getPointOnXYPlaneOfPlacement(const SbVec2s& pnt, c SbVec3f pt; if (xyPlane.intersect(line, pt)) { - return pt; // Intersection point on the XY plane + return pt; // Intersection point on the XY plane } throw Base::RuntimeError("No intersection found"); } -SbVec3f projectPointOntoPlane(const SbVec3f& point, const SbPlane& plane) { +SbVec3f projectPointOntoPlane(const SbVec3f& point, const SbPlane& plane) +{ SbVec3f planeNormal = plane.getNormal(); float d = plane.getDistanceFromOrigin(); float distance = planeNormal.dot(point) + d; @@ -2889,7 +2982,8 @@ SbVec3f projectPointOntoPlane(const SbVec3f& point, const SbPlane& plane) { } // Project a line onto a plane -SbLine projectLineOntoPlane(const SbVec3f& p1, const SbVec3f& p2, const SbPlane& plane) { +SbLine projectLineOntoPlane(const SbVec3f& p1, const SbVec3f& p2, const SbPlane& plane) +{ SbVec3f projectedPoint1 = projectPointOntoPlane(p1, plane); SbVec3f projectedPoint2 = projectPointOntoPlane(p2, plane); return SbLine(projectedPoint1, projectedPoint2); @@ -2905,7 +2999,11 @@ SbVec3f intersection(const SbVec3f& p11, const SbVec3f& p12, const SbVec3f& p21, return p11 + da * s; } -SbVec3f View3DInventorViewer::getPointOnLine(const SbVec2s& pnt, const SbVec3f& axisCenter, const SbVec3f& axis) const +SbVec3f View3DInventorViewer::getPointOnLine( + const SbVec2s& pnt, + const SbVec3f& axisCenter, + const SbVec3f& axis +) const { SbVec2f pnt2d = getNormalizedPosition(pnt); SoCamera* pCam = this->getSoRenderManager()->getCamera(); @@ -2916,7 +3014,7 @@ SbVec3f View3DInventorViewer::getPointOnLine(const SbVec2s& pnt, const SbVec3f& } // First we get pnt projection on the focal plane - SbViewVolume vol = pCam->getViewVolume(); + SbViewVolume vol = pCam->getViewVolume(); float nearDist = pCam->nearDistance.getValue(); float farDist = pCam->farDistance.getValue(); @@ -2949,7 +3047,12 @@ SbVec3f View3DInventorViewer::getPointOnLine(const SbVec2s& pnt, const SbVec3f& // Line normal to focal plane through ptOnFocalPlaneAndOnLine SbLine normalLine(ptOnFocalPlaneAndOnLine, ptOnFocalPlaneAndOnLine + focalPlaneNormal); SbLine axisLine(axisCenter, axisCenter + axis); - pt = intersection(ptOnFocalPlaneAndOnLine, ptOnFocalPlaneAndOnLine + focalPlaneNormal, axisCenter, axisCenter + axis); + pt = intersection( + ptOnFocalPlaneAndOnLine, + ptOnFocalPlaneAndOnLine + focalPlaneNormal, + axisCenter, + axisCenter + axis + ); return pt; } @@ -2964,7 +3067,7 @@ SbVec3f View3DInventorViewer::getPointOnFocalPlane(const SbVec2s& pnt) const return {}; } - SbViewVolume vol = pCam->getViewVolume(); + SbViewVolume vol = pCam->getViewVolume(); float nearDist = pCam->nearDistance.getValue(); float farDist = pCam->farDistance.getValue(); @@ -3042,9 +3145,9 @@ void View3DInventorViewer::getNearPlane(SbVec3f& rcPt, SbVec3f& rcNormal) const float dist = nearPlane.getDistanceFromOrigin(); rcNormal = nearPlane.getNormal(); rcNormal.normalize(); - float nx{}; - float ny{}; - float nz{}; + float nx {}; + float ny {}; + float nz {}; rcNormal.getValue(nx, ny, nz); rcPt.setValue(dist * rcNormal[0], dist * rcNormal[1], dist * rcNormal[2]); } @@ -3060,13 +3163,13 @@ void View3DInventorViewer::getFarPlane(SbVec3f& rcPt, SbVec3f& rcNormal) const SbViewVolume vol = pCam->getViewVolume(); // get the normal of the back clipping plane - SbPlane farPlane = vol.getPlane(vol.nearDist+vol.nearToFar); + SbPlane farPlane = vol.getPlane(vol.nearDist + vol.nearToFar); float dist = farPlane.getDistanceFromOrigin(); rcNormal = farPlane.getNormal(); rcNormal.normalize(); - float nx{}; - float ny{}; - float nz{}; + float nx {}; + float ny {}; + float nz {}; rcNormal.getValue(nx, ny, nz); rcPt.setValue(dist * rcNormal[0], dist * rcNormal[1], dist * rcNormal[2]); } @@ -3116,8 +3219,12 @@ void View3DInventorViewer::projectPointToLine(const SbVec2s& pt, SbVec3f& pt1, S vol.projectPointToLine(pnt2d, pt1, pt2); } -void View3DInventorViewer::toggleClippingPlane(int toggle, bool beforeEditing, - bool noManip, const Base::Placement &pla) +void View3DInventorViewer::toggleClippingPlane( + int toggle, + bool beforeEditing, + bool noManip, + const Base::Placement& pla +) { if (pcClipPlane) { if (toggle <= 0) { @@ -3150,15 +3257,13 @@ void View3DInventorViewer::toggleClippingPlane(int toggle, bool beforeEditing, pcClipPlane = new SoClipPlane; } - pcClipPlane->plane.setValue(SbPlane(Base::convertTo(dir), - Base::convertTo(base))); + pcClipPlane->plane.setValue(SbPlane(Base::convertTo(dir), Base::convertTo(base))); pcClipPlane->ref(); if (beforeEditing) { pcViewProviderRoot->insertChild(pcClipPlane, 0); } else { - pcViewProviderRoot->insertChild(pcClipPlane, - pcViewProviderRoot->findChild(pcEditingRoot) + 1); + pcViewProviderRoot->insertChild(pcClipPlane, pcViewProviderRoot->findChild(pcEditingRoot) + 1); } } @@ -3182,7 +3287,7 @@ bool View3DInventorViewer::pickPoint(const SbVec2s& pos, SbVec3f& point, SbVec3f if (Point) { point = Point->getObjectPoint(); - norm = Point->getObjectNormal(); + norm = Point->getObjectNormal(); return true; } @@ -3203,7 +3308,7 @@ SoPickedPoint* View3DInventorViewer::pickPoint(const SbVec2s& pos) const // returns a copy of the point SoPickedPoint* pick = rp.getPickedPoint(); - //return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows + // return (pick ? pick->copy() : 0); // needs the same instance of CRT under MS Windows return (pick ? new SoPickedPoint(*pick) : nullptr); } @@ -3229,7 +3334,10 @@ void View3DInventorViewer::pubSeekToPoint(const SbVec3f& pos) this->seekToPoint(pos); } -std::shared_ptr View3DInventorViewer::setCameraOrientation(const SbRotation& orientation, const bool moveToCenter) const +std::shared_ptr View3DInventorViewer::setCameraOrientation( + const SbRotation& orientation, + const bool moveToCenter +) const { return navigation->setCameraOrientation(orientation, moveToCenter); } @@ -3265,7 +3373,12 @@ void View3DInventorViewer::moveCameraTo(const SbRotation& orientation, const SbV if (isAnimationEnabled()) { startAnimation( - orientation, camera->position.getValue(), position - camera->position.getValue(), duration, true); + orientation, + camera->position.getValue(), + position - camera->position.getValue(), + duration, + true + ); } camera->orientation.setValue(orientation); @@ -3317,8 +3430,8 @@ void View3DInventorViewer::animatedViewAll(int steps, int ms) } else if (cam->isOfType(SoPerspectiveCamera::getClassTypeId())) { // NOLINTBEGIN - float movelength = sphere.getRadius()/float(tan(static_cast - (cam)->heightAngle.getValue() / 2.0)); + float movelength = sphere.getRadius() + / float(tan(static_cast(cam)->heightAngle.getValue() / 2.0)); // NOLINTEND pos = box.getCenter() - direction * movelength; } @@ -3328,8 +3441,8 @@ void View3DInventorViewer::animatedViewAll(int steps, int ms) timer.setSingleShot(true); QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit); - for (int i=0; igetSoRenderManager()->getCamera(); if (cam && cam->getTypeId().isDerivedFrom(SoPerspectiveCamera::getClassTypeId())) { - static_cast(cam)->heightAngle = - (float)(std::numbers::pi / 4.0); // NOLINT + static_cast(cam)->heightAngle = (float)(std::numbers::pi + / 4.0); // NOLINT } if (isAnimationEnabled()) { @@ -3417,8 +3530,10 @@ void View3DInventorViewer::viewAll() // make sure everything is visible if (cam) { - cam->viewAll(getSoRenderManager()->getSceneGraph(), - this->getSoRenderManager()->getViewportRegion()); + cam->viewAll( + getSoRenderManager()->getSceneGraph(), + this->getSoRenderManager()->getViewportRegion() + ); } } } @@ -3455,13 +3570,13 @@ void View3DInventorViewer::viewAll(float factor) } SbBox3f box = getBoundingBox(); - float minx{}; - float miny{}; - float minz{}; - float maxx{}; - float maxy{}; - float maxz{}; - box.getBounds(minx,miny,minz,maxx,maxy,maxz); + float minx {}; + float miny {}; + float minz {}; + float maxx {}; + float maxy {}; + float maxz {}; + box.getBounds(minx, miny, minz, maxx, maxy, maxz); for (int i = 0; i < pathlist.getLength(); i++) { SoPath* path = pathlist[i]; @@ -3470,9 +3585,9 @@ void View3DInventorViewer::viewAll(float factor) } auto cube = new SoCube(); - cube->width = factor*(maxx-minx); - cube->height = factor*(maxy-miny); - cube->depth = factor*(maxz-minz); + cube->width = factor * (maxx - minx); + cube->height = factor * (maxy - miny); + cube->depth = factor * (maxz - minz); // fake a scenegraph with the desired bounding size auto graph = new SoSeparator(); @@ -3493,22 +3608,24 @@ void View3DInventorViewer::viewAll(float factor) void View3DInventorViewer::viewSelection() { Base::BoundBox3d bbox; - for(auto &sel : Selection().getSelection(nullptr, ResolveMode::NoResolve)) { + for (auto& sel : Selection().getSelection(nullptr, ResolveMode::NoResolve)) { auto vp = Application::Instance->getViewProvider(sel.pObject); - if(!vp) { + if (!vp) { continue; } - bbox.Add(vp->getBoundingBox(sel.SubName,true)); + bbox.Add(vp->getBoundingBox(sel.SubName, true)); } SoCamera* cam = this->getSoRenderManager()->getCamera(); if (cam && bbox.IsValid()) { - SbBox3f box(float(bbox.MinX), - float(bbox.MinY), - float(bbox.MinZ), - float(bbox.MaxX), - float(bbox.MaxY), - float(bbox.MaxZ)); + SbBox3f box( + float(bbox.MinX), + float(bbox.MinY), + float(bbox.MinZ), + float(bbox.MaxX), + float(bbox.MaxY), + float(bbox.MaxZ) + ); float aspectratio = getSoRenderManager()->getViewportRegion().getViewportAspectRatio(); switch (cam->viewportMapping.getValue()) { case SoCamera::CROP_VIEWPORT_FILL_FRAME: @@ -3519,7 +3636,7 @@ void View3DInventorViewer::viewSelection() default: break; } - cam->viewBoundingBox(box,aspectratio,1.0); + cam->viewBoundingBox(box, aspectratio, 1.0); } } @@ -3544,22 +3661,36 @@ void View3DInventorViewer::alignToSelection() // Get the geo feature App::GeoFeature* geoFeature = nullptr; App::ElementNamePair elementName; - App::GeoFeature::resolveElement(selection[0].pObject, selection[0].SubName, elementName, true, App::GeoFeature::ElementNameType::Normal, nullptr, nullptr, &geoFeature); + App::GeoFeature::resolveElement( + selection[0].pObject, + selection[0].SubName, + elementName, + true, + App::GeoFeature::ElementNameType::Normal, + nullptr, + nullptr, + &geoFeature + ); if (!geoFeature) { return; } - const auto globalPlacement = App::GeoFeature::getGlobalPlacement(selection[0].pResolvedObject, selection[0].pObject, elementName.oldName); - const auto globalRotation = globalPlacement.getRotation() * geoFeature->Placement.getValue().getRotation().inverse(); + const auto globalPlacement = App::GeoFeature::getGlobalPlacement( + selection[0].pResolvedObject, + selection[0].pObject, + elementName.oldName + ); + const auto globalRotation = globalPlacement.getRotation() + * geoFeature->Placement.getValue().getRotation().inverse(); const auto splitSubName = Base::Tools::splitSubName(elementName.oldName); const auto geoFeatureSubName = !splitSubName.empty() ? splitSubName.back() : ""; Base::Vector3d alignmentZ; - Base::Vector3d alignmentX (0, 0, 0); + Base::Vector3d alignmentX(0, 0, 0); if (geoFeature->getCameraAlignmentDirection(alignmentZ, alignmentX, geoFeatureSubName.c_str())) { // Find a x alignment if the geoFeature did not suggest any - if (alignmentX == Base::Vector3d (0, 0, 0)) { + if (alignmentX == Base::Vector3d(0, 0, 0)) { Base::Rotation(-Base::Vector3d::UnitZ, alignmentZ).multVec(Base::Vector3d::UnitX, alignmentX); } @@ -3581,7 +3712,8 @@ void View3DInventorViewer::alignToSelection() } // Rotate the camera to align with directionZ by the smallest angle to align the z-axis - const SbRotation intermediateOrientation = cameraOrientation * SbRotation(cameraZ, directionZ); + const SbRotation intermediateOrientation = cameraOrientation + * SbRotation(cameraZ, directionZ); SbVec3f intermediateX; intermediateOrientation.multVec(SbVec3f(1, 0, 0), intermediateX); @@ -3605,20 +3737,21 @@ void View3DInventorViewer::alignToSelection() } // Find the angle to rotate to the nearest horizontal or vertical alignment with directionX. - // f is a small value used to get more deterministic behavior when the camera is at directionX +- 45 degrees. + // f is a small value used to get more deterministic behavior when the camera is at + // directionX +- 45 degrees. const float f = 0.00001F; - if (angle <= pi/4 + f) { + if (angle <= pi / 4 + f) { angle = 0; } - else if (angle <= 3 * pi/4 + f) { - angle = pi/2; + else if (angle <= 3 * pi / 4 + f) { + angle = pi / 2; } - else if (angle < pi + pi/4 - f) { + else if (angle < pi + pi / 4 - f) { angle = pi; } - else if (angle < pi + 3 * pi/4 - f) { - angle = pi + pi/2; + else if (angle < pi + 3 * pi / 4 - f) { + angle = pi + pi / 2; } else { angle = 0; @@ -3629,10 +3762,23 @@ void View3DInventorViewer::alignToSelection() const SbVec3f directionY = directionZ.cross(directionX); const auto orientation = SbRotation(SbMatrix( - directionX[0], directionX[1], directionX[2], 0, - directionY[0], directionY[1], directionY[2], 0, - directionZ[0], directionZ[1], directionZ[2], 0, - 0, 0, 0, 1)); + directionX[0], + directionX[1], + directionX[2], + 0, + directionY[0], + directionY[1], + directionY[2], + 0, + directionZ[0], + directionZ[1], + directionZ[2], + 0, + 0, + 0, + 0, + 1 + )); setCameraOrientation(orientation); } @@ -3649,7 +3795,8 @@ void View3DInventorViewer::setAnimationEnabled(bool enable) } /** - * @brief Decide if it should be possible to start a spin animation of the model in the viewer by releasing the mouse button while dragging + * @brief Decide if it should be possible to start a spin animation of the model in the viewer by + * releasing the mouse button while dragging * * If the enable flag is false and we're currently animating, the spin animation will be stopped */ @@ -3695,17 +3842,21 @@ bool View3DInventorViewer::isSpinning() const * * @param orientation The new orientation * @param rotationCenter The rotation center - * @param translation An additional translation on top of the translation caused by the rotation around the rotation center + * @param translation An additional translation on top of the translation caused by the rotation + * around the rotation center * @param duration The duration in milliseconds - * @param wait When false, start the animation and continue (asynchronous). When true, start the animation and wait for the animation to finish (synchronous) + * @param wait When false, start the animation and continue (asynchronous). When true, start the + * animation and wait for the animation to finish (synchronous) * * @return The started @class NavigationAnimation */ -std::shared_ptr View3DInventorViewer::startAnimation(const SbRotation& orientation, - const SbVec3f& rotationCenter, - const SbVec3f& translation, - int duration, - const bool wait) const +std::shared_ptr View3DInventorViewer::startAnimation( + const SbRotation& orientation, + const SbVec3f& rotationCenter, + const SbVec3f& translation, + int duration, + const bool wait +) const { // Currently starts a FixedTimeAnimation. If there is going to be an additional animation like // FixedVelocityAnimation, check the animation type from a parameter and start the right animation @@ -3717,12 +3868,20 @@ std::shared_ptr View3DInventorViewer::startAnimation(const ->GetInt("AnimationDuration", 500); } - QEasingCurve::Type easingCurve = static_cast(App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetInt("NavigationAnimationEasingCurve", QEasingCurve::Type::InOutCubic)); + QEasingCurve::Type easingCurve = static_cast( + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetInt("NavigationAnimationEasingCurve", QEasingCurve::Type::InOutCubic) + ); auto animation = std::make_shared( - navigation, orientation, rotationCenter, translation, duration, easingCurve); + navigation, + orientation, + rotationCenter, + translation, + duration, + easingCurve + ); navigation->startAnimating(animation, wait); @@ -3760,8 +3919,7 @@ bool View3DInventorViewer::isPopupMenuEnabled() const Set the flag deciding whether or not to show the axis cross. */ -void -View3DInventorViewer::setFeedbackVisibility(bool enable) +void View3DInventorViewer::setFeedbackVisibility(bool enable) { if (enable == this->axiscrossEnabled) { return; @@ -3778,8 +3936,7 @@ View3DInventorViewer::setFeedbackVisibility(bool enable) Check if the feedback axis cross is visible. */ -bool -View3DInventorViewer::isFeedbackVisible() const +bool View3DInventorViewer::isFeedbackVisible() const { return this->axiscrossEnabled; } @@ -3789,8 +3946,7 @@ View3DInventorViewer::isFeedbackVisible() const an approximate percentage chunk of the dimensions of the total canvas. */ -void -View3DInventorViewer::setFeedbackSize(int size) +void View3DInventorViewer::setFeedbackSize(int size) { if (size < 1) { return; @@ -3807,8 +3963,7 @@ View3DInventorViewer::setFeedbackSize(int size) Return the size of the feedback axis cross. Default is 10. */ -int -View3DInventorViewer::getFeedbackSize() const +int View3DInventorViewer::getFeedbackSize() const { return this->axiscrossSize; } @@ -3840,34 +3995,36 @@ void View3DInventorViewer::setViewing(bool enable) inherited::setViewing(enable); } -unsigned char View3DInventorViewer::XPM_pixel_data[XPM_WIDTH * XPM_HEIGHT * XPM_BYTES_PER_PIXEL + 1] = {}; -unsigned char View3DInventorViewer::YPM_pixel_data[YPM_WIDTH * YPM_HEIGHT * YPM_BYTES_PER_PIXEL + 1] = {}; -unsigned char View3DInventorViewer::ZPM_pixel_data[ZPM_WIDTH * ZPM_HEIGHT * ZPM_BYTES_PER_PIXEL + 1] = {}; +unsigned char View3DInventorViewer::XPM_pixel_data[XPM_WIDTH * XPM_HEIGHT * XPM_BYTES_PER_PIXEL + 1] + = {}; +unsigned char View3DInventorViewer::YPM_pixel_data[YPM_WIDTH * YPM_HEIGHT * YPM_BYTES_PER_PIXEL + 1] + = {}; +unsigned char View3DInventorViewer::ZPM_pixel_data[ZPM_WIDTH * ZPM_HEIGHT * ZPM_BYTES_PER_PIXEL + 1] + = {}; void View3DInventorViewer::setAxisLetterColor(const SbColor& color) { unsigned packed = color.getPackedValue(); - auto recolor = - [&](const unsigned char* mask, - unsigned char* data, - unsigned width, - unsigned height, - unsigned bitdepth) { - for (unsigned y = 0; y < height; y++) { - for (unsigned x = 0; x < width; x++) { - unsigned offset = (y * width + x) * bitdepth; + auto recolor = [&](const unsigned char* mask, + unsigned char* data, + unsigned width, + unsigned height, + unsigned bitdepth) { + for (unsigned y = 0; y < height; y++) { + for (unsigned x = 0; x < width; x++) { + unsigned offset = (y * width + x) * bitdepth; - const unsigned char* src = &mask[offset]; - unsigned char* dst = &data[offset]; + const unsigned char* src = &mask[offset]; + unsigned char* dst = &data[offset]; - dst[0] = (packed >> 24) & 0xFF; // RR - from color - dst[1] = (packed >> 16) & 0xFF; // GG - from color - dst[2] = (packed >> 8) & 0xFF; // BB - from color - dst[3] = src[3]; // AA - from mask - } + dst[0] = (packed >> 24) & 0xFF; // RR - from color + dst[1] = (packed >> 16) & 0xFF; // GG - from color + dst[2] = (packed >> 8) & 0xFF; // BB - from color + dst[3] = src[3]; // AA - from mask } - }; + } + }; recolor(XPM_PIXEL_MASK, XPM_pixel_data, XPM_WIDTH, XPM_HEIGHT, XPM_BYTES_PER_PIXEL); recolor(YPM_PIXEL_MASK, YPM_pixel_data, YPM_WIDTH, YPM_HEIGHT, YPM_BYTES_PER_PIXEL); @@ -3887,7 +4044,7 @@ void View3DInventorViewer::updateColors() naviCube->updateColors(); - if(hasAxisCross()) { + if (hasAxisCross()) { setAxisCross(false); // Force redraw setAxisCross(true); } @@ -3912,12 +4069,12 @@ void View3DInventorViewer::drawAxisCross() glEnable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); - glDisable(GL_BLEND); // Kills transparency. + glDisable(GL_BLEND); // Kills transparency. // Set the viewport in the OpenGL canvas. Dimensions are calculated // as a percentage of the total canvas size. SbVec2s view = this->getSoRenderManager()->getSize(); - const int pixelarea = int(float(this->axiscrossSize)/100.0F * std::min(view[0], view[1])); + const int pixelarea = int(float(this->axiscrossSize) / 100.0F * std::min(view[0], view[1])); SbVec2s origin(view[0] - pixelarea, 0); glViewport(origin[0], origin[1], pixelarea, pixelarea); @@ -3927,7 +4084,7 @@ void View3DInventorViewer::drawAxisCross() const float NEARVAL = 0.1F; const float FARVAL = 10.0F; - const float dim = NEARVAL * float(tan(std::numbers::pi / 8.0)); // FOV is 45 deg (45/360 = 1/8) + const float dim = NEARVAL * float(tan(std::numbers::pi / 8.0)); // FOV is 45 deg (45/360 = 1/8) glFrustum(-dim, dim, -dim, dim, NEARVAL, FARVAL); @@ -3947,36 +4104,41 @@ void View3DInventorViewer::drawAxisCross() } mx = mx.inverse(); - mx[3][2] = -3.5; // Translate away from the projection point (along z axis). + mx[3][2] = -3.5; // Translate away from the projection point (along z axis). glLoadMatrixf((float*)mx); // Find unit vector end points. SbMatrix px; glGetFloatv(GL_PROJECTION_MATRIX, (float*)px); - SbMatrix comb = mx.multRight(px); // clazy:exclude=rule-of-two-soft + SbMatrix comb = mx.multRight(px); // clazy:exclude=rule-of-two-soft SbVec3f xpos; - comb.multVecMatrix(SbVec3f(1,0,0), xpos); - xpos[0] = (1 + xpos[0]) * view[0]/2; - xpos[1] = (1 + xpos[1]) * view[1]/2; + comb.multVecMatrix(SbVec3f(1, 0, 0), xpos); + xpos[0] = (1 + xpos[0]) * view[0] / 2; + xpos[1] = (1 + xpos[1]) * view[1] / 2; SbVec3f ypos; - comb.multVecMatrix(SbVec3f(0,1,0), ypos); - ypos[0] = (1 + ypos[0]) * view[0]/2; - ypos[1] = (1 + ypos[1]) * view[1]/2; + comb.multVecMatrix(SbVec3f(0, 1, 0), ypos); + ypos[0] = (1 + ypos[0]) * view[0] / 2; + ypos[1] = (1 + ypos[1]) * view[1] / 2; SbVec3f zpos; - comb.multVecMatrix(SbVec3f(0,0,1), zpos); - zpos[0] = (1 + zpos[0]) * view[0]/2; - zpos[1] = (1 + zpos[1]) * view[1]/2; + comb.multVecMatrix(SbVec3f(0, 0, 1), zpos); + zpos[0] = (1 + zpos[0]) * view[0] / 2; + zpos[1] = (1 + zpos[1]) * view[1] / 2; // Render the cross. { glLineWidth(2.0); - enum { XAXIS, YAXIS, ZAXIS }; - int idx[3] = { XAXIS, YAXIS, ZAXIS }; - float val[3] = { xpos[2], ypos[2], zpos[2] }; + enum + { + XAXIS, + YAXIS, + ZAXIS + }; + int idx[3] = {XAXIS, YAXIS, ZAXIS}; + float val[3] = {xpos[2], ypos[2], zpos[2]}; // Bubble sort.. :-} if (val[0] < val[1]) { @@ -3994,32 +4156,38 @@ void View3DInventorViewer::drawAxisCross() std::swap(idx[0], idx[1]); } - assert((val[0] >= val[1]) && (val[1] >= val[2])); // Just checking.. + assert((val[0] >= val[1]) && (val[1] >= val[2])); // Just checking.. - for (const int & i : idx) { + for (const int& i : idx) { glPushMatrix(); - if (i == XAXIS) { // X axis. - if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) // What is this - glColor3f(0.500F, 0.5F, 0.5F); // Why different colors?? - else + if (i == XAXIS) { // X axis. + if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) { // What is this + glColor3f(0.500F, 0.5F, 0.5F); // Why different colors?? + } + else { glColor3f(m_xColor.r, m_xColor.g, m_xColor.b); + } } - else if (i == YAXIS) { // Y axis. + else if (i == YAXIS) { // Y axis. glRotatef(90, 0, 0, 1); - if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) + if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) { glColor3f(0.400F, 0.4F, 0.4F); - else + } + else { glColor3f(m_yColor.r, m_yColor.g, m_yColor.b); + } } - else { // Z axis. + else { // Z axis. glRotatef(-90, 0, 1, 0); - if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) + if (stereoMode() != Quarter::SoQTQuarterAdaptor::MONO) { glColor3f(0.300F, 0.3F, 0.3F); - else + } + else { glColor3f(m_zColor.r, m_zColor.g, m_zColor.b); + } } drawArrow(); @@ -4035,7 +4203,7 @@ void View3DInventorViewer::drawAxisCross() glMatrixMode(GL_MODELVIEW); glLoadIdentity(); - GLint unpack{}; + GLint unpack {}; glGetIntegerv(GL_UNPACK_ALIGNMENT, &unpack); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); @@ -4048,7 +4216,9 @@ void View3DInventorViewer::drawAxisCross() glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glPixelZoom((float)axiscrossSize / 30, (float)axiscrossSize / 30); // 30 = 3 (character pixmap ratio) * 10 (default axiscrossSize) + glPixelZoom((float)axiscrossSize / 30, (float)axiscrossSize / 30); // 30 = 3 (character pixmap + // ratio) * 10 (default + // axiscrossSize) glRasterPos2d(xpos[0], xpos[1]); glDrawPixels(XPM_WIDTH, XPM_HEIGHT, GL_RGBA, GL_UNSIGNED_BYTE, XPM_pixel_data); glRasterPos2d(ypos[0], ypos[1]); @@ -4179,42 +4349,42 @@ void View3DInventorViewer::setCursorRepresentation(int modearg) } switch (modearg) { - case NavigationStyle::IDLE: - case NavigationStyle::INTERACT: - if (isEditing()) { - this->getWidget()->setCursor(this->editCursor); - } - else { - this->getWidget()->setCursor(QCursor(Qt::ArrowCursor)); - } - break; + case NavigationStyle::IDLE: + case NavigationStyle::INTERACT: + if (isEditing()) { + this->getWidget()->setCursor(this->editCursor); + } + else { + this->getWidget()->setCursor(QCursor(Qt::ArrowCursor)); + } + break; - case NavigationStyle::DRAGGING: - case NavigationStyle::SPINNING: - this->getWidget()->setCursor(spinCursor); - break; + case NavigationStyle::DRAGGING: + case NavigationStyle::SPINNING: + this->getWidget()->setCursor(spinCursor); + break; - case NavigationStyle::ZOOMING: - this->getWidget()->setCursor(zoomCursor); - break; + case NavigationStyle::ZOOMING: + this->getWidget()->setCursor(zoomCursor); + break; - case NavigationStyle::SEEK_MODE: - case NavigationStyle::SEEK_WAIT_MODE: - case NavigationStyle::BOXZOOM: - this->getWidget()->setCursor(Qt::CrossCursor); - break; + case NavigationStyle::SEEK_MODE: + case NavigationStyle::SEEK_WAIT_MODE: + case NavigationStyle::BOXZOOM: + this->getWidget()->setCursor(Qt::CrossCursor); + break; - case NavigationStyle::PANNING: - this->getWidget()->setCursor(panCursor); - break; + case NavigationStyle::PANNING: + this->getWidget()->setCursor(panCursor); + break; - case NavigationStyle::SELECTION: - this->getWidget()->setCursor(Qt::PointingHandCursor); - break; + case NavigationStyle::SELECTION: + this->getWidget()->setCursor(Qt::PointingHandCursor); + break; - default: - assert(0); - break; + default: + assert(0); + break; } } @@ -4259,13 +4429,15 @@ SoPath* View3DInventorViewer::pickFilterCB(void* viewer, const SoPickedPoint* pp std::string str = vp->getElement(pp->getDetail()); vp->getSelectionShape(str.c_str()); static char buf[513]; - snprintf(buf, - sizeof(buf), - "Hovered: %s (%f,%f,%f)" - , str.c_str() - , pp->getPoint()[0] - , pp->getPoint()[1] - , pp->getPoint()[2]); + snprintf( + buf, + sizeof(buf), + "Hovered: %s (%f,%f,%f)", + str.c_str(), + pp->getPoint()[0], + pp->getPoint()[1], + pp->getPoint()[2] + ); getMainWindow()->showMessage(QString::fromLatin1(buf), 3000); } @@ -4295,7 +4467,9 @@ ViewProvider* View3DInventorViewer::getViewProviderByPath(SoPath* path) const ViewProvider* View3DInventorViewer::getViewProviderByPathFromTail(SoPath* path) const { if (!guiDocument) { - Base::Console().warning("View3DInventorViewer::getViewProviderByPathFromTail: No document set\n"); + Base::Console().warning( + "View3DInventorViewer::getViewProviderByPathFromTail: No document set\n" + ); return nullptr; } return guiDocument->getViewProviderByPathFromTail(path); @@ -4356,7 +4530,7 @@ void View3DInventorViewer::turnDeltaDimensionsOff() static_cast(dimensionRoot->getChild(1))->whichChild = SO_SWITCH_NONE; // NOLINT } -PyObject *View3DInventorViewer::getPyObject() +PyObject* View3DInventorViewer::getPyObject() { if (!_viewerPy) { _viewerPy = new View3DInventorViewerPy(this); @@ -4369,7 +4543,7 @@ PyObject *View3DInventorViewer::getPyObject() /** * Drops the event \a e and loads the files into the given document. */ -void View3DInventorViewer::dropEvent (QDropEvent* ev) +void View3DInventorViewer::dropEvent(QDropEvent* ev) { const QMimeData* data = ev->mimeData(); if (data->hasUrls() && selectionRoot && selectionRoot->pcDocument) { @@ -4380,7 +4554,7 @@ void View3DInventorViewer::dropEvent (QDropEvent* ev) } } -void View3DInventorViewer::dragEnterEvent (QDragEnterEvent* ev) +void View3DInventorViewer::dragEnterEvent(QDragEnterEvent* ev) { // Here we must allow uri drags and check them in dropEvent const QMimeData* data = ev->mimeData(); @@ -4408,4 +4582,4 @@ void View3DInventorViewer::dragLeaveEvent(QDragLeaveEvent* ev) inherited::dragLeaveEvent(ev); } -#include "moc_View3DInventorViewer.cpp" // NOLINT +#include "moc_View3DInventorViewer.cpp" // NOLINT diff --git a/src/Gui/View3DInventorViewer.h b/src/Gui/View3DInventorViewer.h index c720fbe37c..1392b9cf21 100644 --- a/src/Gui/View3DInventorViewer.h +++ b/src/Gui/View3DInventorViewer.h @@ -83,11 +83,13 @@ class SoClipPlane; namespace Quarter = SIM::Coin3D::Quarter; -namespace Base { - class BoundBox2d; +namespace Base +{ +class BoundBox2d; } -namespace Gui { +namespace Gui +{ class NavigationAnimation; class ViewProvider; class SoFCBackgroundGradient; @@ -101,39 +103,42 @@ class ViewerEventFilter; /** GUI view into a 3D scene provided by View3DInventor * */ -class GuiExport View3DInventorViewer : public Quarter::SoQTQuarterAdaptor, public SelectionObserver +class GuiExport View3DInventorViewer: public Quarter::SoQTQuarterAdaptor, public SelectionObserver { using inherited = Quarter::SoQTQuarterAdaptor; Q_OBJECT public: /// Pick modes for picking points in the scene - enum SelectionMode { - Lasso = 0, /**< Select objects using a lasso. */ - Rectangle = 1, /**< Select objects using a rectangle. */ - Rubberband = 2, /**< Select objects using a rubberband. */ - BoxZoom = 3, /**< Perform a box zoom. */ - Clip = 4, /**< Clip objects using a lasso. */ + enum SelectionMode + { + Lasso = 0, /**< Select objects using a lasso. */ + Rectangle = 1, /**< Select objects using a rectangle. */ + Rubberband = 2, /**< Select objects using a rubberband. */ + BoxZoom = 3, /**< Perform a box zoom. */ + Clip = 4, /**< Clip objects using a lasso. */ }; /** @name Modus handling of the viewer - * Here you can switch several features on/off - * and modes of the Viewer - */ + * Here you can switch several features on/off + * and modes of the Viewer + */ //@{ - enum ViewerMod { - ShowCoord=1, /**< Enables the Coordinate system in the corner. */ - ShowFPS =2, /**< Enables the Frames Per Second counter. */ - SimpleBackground=4,/**< switch to a simple background. */ - DisallowRotation=8,/**< switch off the rotation. */ - DisallowPanning=16,/**< switch off the panning. */ - DisallowZooming=32,/**< switch off the zooming. */ + enum ViewerMod + { + ShowCoord = 1, /**< Enables the Coordinate system in the corner. */ + ShowFPS = 2, /**< Enables the Frames Per Second counter. */ + SimpleBackground = 4, /**< switch to a simple background. */ + DisallowRotation = 8, /**< switch off the rotation. */ + DisallowPanning = 16, /**< switch off the panning. */ + DisallowZooming = 32, /**< switch off the zooming. */ }; //@} /** @name Render mode - */ + */ //@{ - enum RenderType { + enum RenderType + { Native, Framebuffer, Image @@ -141,23 +146,28 @@ public: //@} /** @name Background - */ + */ //@{ - enum Background { + enum Background + { NoGradient, LinearGradient, RadialGradient }; //@} - explicit View3DInventorViewer (QWidget *parent, const QOpenGLWidget* sharewidget = nullptr); - View3DInventorViewer (const QSurfaceFormat& format, QWidget *parent, const QOpenGLWidget* sharewidget = nullptr); + explicit View3DInventorViewer(QWidget* parent, const QOpenGLWidget* sharewidget = nullptr); + View3DInventorViewer( + const QSurfaceFormat& format, + QWidget* parent, + const QOpenGLWidget* sharewidget = nullptr + ); ~View3DInventorViewer() override; void init(); /// Observer message from the Selection - void onSelectionChanged(const SelectionChanges &Reason) override; + void onSelectionChanged(const SelectionChanges& Reason) override; SoDirectionalLight* getBacklight() const; void setBacklightEnabled(bool on); @@ -169,7 +179,7 @@ public: SoEnvironment* getEnvironment() const; - void setSceneGraph (SoNode *root) override; + void setSceneGraph(SoNode* root) override; bool searchNode(SoNode*) const; void setAnimationEnabled(bool enable); @@ -178,8 +188,13 @@ public: bool isSpinningAnimationEnabled() const; bool isAnimating() const; bool isSpinning() const; - std::shared_ptr startAnimation(const SbRotation& orientation, const SbVec3f& rotationCenter, - const SbVec3f& translation, int duration = -1, bool wait = false) const; + std::shared_ptr startAnimation( + const SbRotation& orientation, + const SbVec3f& rotationCenter, + const SbVec3f& translation, + int duration = -1, + bool wait = false + ) const; void startSpinningAnimation(const SbVec3f& axis, float velocity); void stopAnimating(); @@ -198,8 +213,7 @@ public: RenderType getRenderType() const; void renderToFramebuffer(QOpenGLFramebufferObject*); QImage grabFramebuffer(); - void imageFromFramebuffer(int width, int height, int samples, - const QColor& bgcolor, QImage& img); + void imageFromFramebuffer(int width, int height, int samples, const QColor& bgcolor, QImage& img); void setViewing(bool enable) override; virtual void setCursorEnabled(bool enable); @@ -235,9 +249,9 @@ public: ViewProvider* getEditingViewProvider() const; /// reset from edit mode void resetEditingViewProvider(); - void setupEditingRoot(SoNode *node=nullptr, const Base::Matrix4D *mat=nullptr); - void resetEditingRoot(bool updateLinks=true); - void setEditingTransform(const Base::Matrix4D &mat); + void setupEditingRoot(SoNode* node = nullptr, const Base::Matrix4D* mat = nullptr); + void resetEditingRoot(bool updateLinks = true); + void setEditingTransform(const Base::Matrix4D& mat); /** Helper method to get picked entities while editing. * It's in the responsibility of the caller to delete the returned instance. */ @@ -247,9 +261,12 @@ public: */ SoPickedPoint* getPointOnRay(const SbVec3f& pos, const SbVec3f& dir, const ViewProvider* vp) const; /// display override mode - void setOverrideMode(const std::string &mode); - void updateOverrideMode(const std::string &mode); - std::string getOverrideMode() const {return overrideMode;} + void setOverrideMode(const std::string& mode); + void updateOverrideMode(const std::string& mode); + std::string getOverrideMode() const + { + return overrideMode; + } //@} /** @name Making pictures */ @@ -272,35 +289,50 @@ public: void abortSelection(); void stopSelection(); bool isSelecting() const; - std::vector getGLPolygon(SelectionRole* role=nullptr) const; + std::vector getGLPolygon(SelectionRole* role = nullptr) const; std::vector getGLPolygon(const std::vector&) const; - const std::vector& getPolygon(SelectionRole* role=nullptr) const; + const std::vector& getPolygon(SelectionRole* role = nullptr) const; void setSelectionEnabled(bool enable); bool isSelectionEnabled() const; //@} /// Returns the screen coordinates of the origin of the path's tail object /*! Return value is in floating-point pixels, origin at bottom-left. */ - SbVec2f screenCoordsOfPath(SoPath *path) const; + SbVec2f screenCoordsOfPath(SoPath* path) const; /** @name Edit methods */ //@{ void setEditing(bool edit); - bool isEditing() const { return this->editing; } - void setEditingCursor (const QCursor& cursor); + bool isEditing() const + { + return this->editing; + } + void setEditingCursor(const QCursor& cursor); void setComponentCursor(const QCursor& cursor); - void setRedirectToSceneGraph(bool redirect) { this->redirected = redirect; } - bool isRedirectedToSceneGraph() const { return this->redirected; } - void setRedirectToSceneGraphEnabled(bool enable) { this->allowredir = enable; } - bool isRedirectToSceneGraphEnabled() const { return this->allowredir; } + void setRedirectToSceneGraph(bool redirect) + { + this->redirected = redirect; + } + bool isRedirectedToSceneGraph() const + { + return this->redirected; + } + void setRedirectToSceneGraphEnabled(bool enable) + { + this->allowredir = enable; + } + bool isRedirectToSceneGraphEnabled() const + { + return this->allowredir; + } //@} /** @name Pick actions */ //@{ // calls a PickAction on the scene graph - bool pickPoint(const SbVec2s& pos,SbVec3f &point,SbVec3f &norm) const; + bool pickPoint(const SbVec2s& pos, SbVec3f& point, SbVec3f& norm) const; SoPickedPoint* pickPoint(const SbVec2s& pos) const; - const SoPickedPoint* getPickedPoint(SoEventCallback * n) const; + const SoPickedPoint* getPickedPoint(SoEventCallback* n) const; bool pubSeekToPoint(const SbVec2s& pos); void pubSeekToPoint(const SbVec3f& pos); //@} @@ -309,11 +341,11 @@ public: * Set up a callback function \a cb which will be invoked for the given eventtype. * \a userdata will be given as the first argument to the callback function. */ - void addEventCallback(SoType eventtype, SoEventCallbackCB * cb, void* userdata = nullptr); + void addEventCallback(SoType eventtype, SoEventCallbackCB* cb, void* userdata = nullptr); /** * Unregister the given callback function \a cb. */ - void removeEventCallback(SoType eventtype, SoEventCallbackCB * cb, void* userdata = nullptr); + void removeEventCallback(SoType eventtype, SoEventCallbackCB* cb, void* userdata = nullptr); /** @name Clipping plane, near and far plane */ //@{ @@ -322,7 +354,7 @@ public: * The vector is normalized to length of 1. */ SbVec3f getViewDirection() const; - void setViewDirection(SbVec3f); + void setViewDirection(SbVec3f); /** Returns the up direction */ SbVec3f getUpDirection() const; @@ -361,8 +393,12 @@ public: void getFarPlane(SbVec3f& rcPt, SbVec3f& rcNormal) const; /** Adds or remove a manipulator to/from the scenegraph. */ - void toggleClippingPlane(int toggle=-1, bool beforeEditing=false, - bool noManip=false, const Base::Placement &pla = Base::Placement()); + void toggleClippingPlane( + int toggle = -1, + bool beforeEditing = false, + bool noManip = false, + const Base::Placement& pla = Base::Placement() + ); /** Checks whether a clipping plane is set or not. */ bool hasClippingPlane() const; @@ -393,8 +429,8 @@ public: void turnDeltaDimensionsOn(); void turnDeltaDimensionsOff(); void eraseAllDimensions(); - void addDimension3d(SoNode *node); - void addDimensionDelta(SoNode *node); + void addDimension3d(SoNode* node); + void addDimensionDelta(SoNode* node); //@} /** @@ -402,7 +438,10 @@ public: * \a true the reorientation is animated and the animation is returned, otherwise its directly * set. */ - std::shared_ptr setCameraOrientation(const SbRotation& orientation, bool moveToCenter = false) const; + std::shared_ptr setCameraOrientation( + const SbRotation& orientation, + bool moveToCenter = false + ) const; void setCameraType(SoType type) override; void moveCameraTo(const SbRotation& orientation, const SbVec3f& position, int duration = -1); /** @@ -438,11 +477,12 @@ public: void setGradientBackground(Background); Background getGradientBackground() const; - void setGradientBackgroundColor(const SbColor& fromColor, - const SbColor& toColor); - void setGradientBackgroundColor(const SbColor& fromColor, - const SbColor& toColor, - const SbColor& midColor); + void setGradientBackgroundColor(const SbColor& fromColor, const SbColor& toColor); + void setGradientBackgroundColor( + const SbColor& fromColor, + const SbColor& toColor, + const SbColor& midColor + ); void setNavigationType(Base::Type); void setAxisLetterColor(const SbColor& color); @@ -470,10 +510,10 @@ public: NavigationStyle* navigationStyle() const; - void setDocument(Gui::Document *pcDocument); + void setDocument(Gui::Document* pcDocument); Gui::Document* getDocument(); - virtual PyObject *getPyObject(); + virtual PyObject* getPyObject(); protected: static GLenum getInternalTextureFormat(); @@ -484,28 +524,28 @@ protected: void actualRedraw() override; void setSeekMode(bool on) override; void afterRealizeHook() override; - bool processSoEvent(const SoEvent * ev) override; - void dropEvent (QDropEvent * ev) override; - void dragEnterEvent (QDragEnterEvent * ev) override; + bool processSoEvent(const SoEvent* ev) override; + void dropEvent(QDropEvent* ev) override; + void dragEnterEvent(QDragEnterEvent* ev) override; void dragMoveEvent(QDragMoveEvent* ev) override; void dragLeaveEvent(QDragLeaveEvent* ev) override; - bool processSoEventBase(const SoEvent * const ev); + bool processSoEventBase(const SoEvent* const ev); void printDimension() const; void selectAll(); private: - static void setViewportCB(void * userdata, SoAction * action); - static void clearBufferCB(void * userdata, SoAction * action); - static void setGLWidgetCB(void * userdata, SoAction * action); - static void handleEventCB(void * userdata, SoEventCallback * n); - static void interactionStartCB(void * data, Quarter::SoQTQuarterAdaptor * viewer); - static void interactionFinishCB(void * data, Quarter::SoQTQuarterAdaptor * viewer); - static void interactionLoggerCB(void * ud, SoAction* action); + static void setViewportCB(void* userdata, SoAction* action); + static void clearBufferCB(void* userdata, SoAction* action); + static void setGLWidgetCB(void* userdata, SoAction* action); + static void handleEventCB(void* userdata, SoEventCallback* n); + static void interactionStartCB(void* data, Quarter::SoQTQuarterAdaptor* viewer); + static void interactionFinishCB(void* data, Quarter::SoQTQuarterAdaptor* viewer); + static void interactionLoggerCB(void* ud, SoAction* action); private: - static void selectCB(void * viewer, SoPath * path); - static void deselectCB(void * viewer, SoPath * path); - static SoPath * pickFilterCB(void * viewer, const SoPickedPoint * pp); + static void selectCB(void* viewer, SoPath* path); + static void deselectCB(void* viewer, SoPath* path); + static SoPath* pickFilterCB(void* viewer, const SoPickedPoint* pp); void initialize(); void drawAxisCross(); static void drawArrow(); @@ -517,12 +557,12 @@ private: private: NaviCube* naviCube; std::set _ViewProviderSet; - std::map _ViewProviderMap; + std::map _ViewProviderMap; std::list graphicsItems; ViewProvider* editViewProvider; - SoFCBackgroundGradient *pcBackGround; - SoSeparator * backgroundroot; - SoSeparator * foregroundroot; + SoFCBackgroundGradient* pcBackGround; + SoSeparator* backgroundroot; + SoSeparator* foregroundroot; SoDirectionalLight* backlight; SoDirectionalLight* fillLight; @@ -531,26 +571,26 @@ private: SoRotation* lightRotation; // Scene graph root - SoSeparator * pcViewProviderRoot; + SoSeparator* pcViewProviderRoot; // Child group in the scene graph that contains view providers related to the physical object SoGroup* objectGroup; std::unique_ptr inventorSelection; - SoSeparator * pcEditingRoot; - SoTransform * pcEditingTransform; + SoSeparator* pcEditingRoot; + SoTransform* pcEditingTransform; bool restoreEditingRoot; SoEventCallback* pEventCallback; NavigationStyle* navigation; SoFCUnifiedSelection* selectionRoot; - SoClipPlane *pcClipPlane; + SoClipPlane* pcClipPlane; RenderType renderType; QOpenGLFramebufferObject* framebuffer; QImage glImage; bool shading; - SoSwitch *dimensionRoot; + SoSwitch* dimensionRoot; // small axis cross in the corner bool axiscrossEnabled; @@ -561,7 +601,7 @@ private: SoGroup* rotationCenterGroup; - //stuff needed to draw the fps counter + // stuff needed to draw the fps counter bool fpsEnabled; bool vboEnabled; bool naviCubeEnabled; @@ -592,6 +632,6 @@ private: friend class ViewerEventFilter; }; -} // namespace Gui +} // namespace Gui #endif // GUI_VIEW3DINVENTORVIEWER_H diff --git a/src/Gui/View3DPy.cpp b/src/Gui/View3DPy.cpp index d80dcd5fb3..d10b656651 100644 --- a/src/Gui/View3DPy.cpp +++ b/src/Gui/View3DPy.cpp @@ -20,18 +20,18 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -77,170 +77,304 @@ void View3DInventorPy::init_type() behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("fitAll",&View3DInventorPy::fitAll,"fitAll()"); - add_keyword_method("boxZoom",&View3DInventorPy::boxZoom,"boxZoom()"); + add_varargs_method("fitAll", &View3DInventorPy::fitAll, "fitAll()"); + add_keyword_method("boxZoom", &View3DInventorPy::boxZoom, "boxZoom()"); - add_noargs_method("viewBottom",&View3DInventorPy::viewBottom,"viewBottom()"); - add_noargs_method("viewFront",&View3DInventorPy::viewFront,"viewFront()"); - add_noargs_method("viewLeft",&View3DInventorPy::viewLeft,"viewLeft()"); - add_noargs_method("viewRear",&View3DInventorPy::viewRear,"viewRear()"); - add_noargs_method("viewRight",&View3DInventorPy::viewRight,"viewRight()"); - add_noargs_method("viewTop",&View3DInventorPy::viewTop,"viewTop()"); - add_noargs_method("viewAxometric",&View3DInventorPy::viewIsometric,"viewAxonometric()"); // for backward compatibility - add_noargs_method("viewAxonometric",&View3DInventorPy::viewIsometric,"viewAxonometric()"); - add_noargs_method("viewIsometric",&View3DInventorPy::viewIsometric,"viewIsometric()"); - add_noargs_method("viewDimetric",&View3DInventorPy::viewDimetric,"viewDimetric()"); - add_noargs_method("viewTrimetric",&View3DInventorPy::viewTrimetric,"viewTrimetric()"); - add_varargs_method("viewDefaultOrientation",&View3DInventorPy::viewDefaultOrientation, - "viewDefaultOrientation(ori_str = '', scale = -1.0): sets camera rotation to a predefined one, \n" - "and camera position and zoom to show certain amount of model space. \n" - "ori_string can be 'Top', 'Bottom', 'Front', 'Rear', 'Left', 'Right', \n" - "'Isometric', 'Dimetric', 'Trimetric', 'Custom'. If empty, the value is \n" - "fetched from Parameters.\n" - "scale sets distance from camera to origin, and height of the screen in \n" - "model space, so that a sphere of diameter fits the height of the\n" - "viewport. If zero, scaling is not done. If negative, the value is \n" - "fetched from Parameters."); - add_noargs_method("viewRotateLeft",&View3DInventorPy::viewRotateLeft,"viewRotateLeft()"); - add_noargs_method("viewRotateRight",&View3DInventorPy::viewRotateRight,"viewRotateRight()"); - add_noargs_method("zoomIn",&View3DInventorPy::zoomIn,"zoomIn()"); - add_noargs_method("zoomOut",&View3DInventorPy::zoomOut,"zoomOut()"); - add_varargs_method("viewPosition",&View3DInventorPy::viewPosition,"viewPosition()"); - add_varargs_method("startAnimating",&View3DInventorPy::startAnimating,"startAnimating()"); - add_noargs_method("stopAnimating",&View3DInventorPy::stopAnimating,"stopAnimating()"); - add_varargs_method("setAnimationEnabled",&View3DInventorPy::setAnimationEnabled,"setAnimationEnabled()"); - add_noargs_method("isAnimationEnabled",&View3DInventorPy::isAnimationEnabled,"isAnimationEnabled()"); - add_varargs_method("setPopupMenuEnabled",&View3DInventorPy::setPopupMenuEnabled,"setPopupMenuEnabled()"); - add_noargs_method("isPopupMenuEnabled",&View3DInventorPy::isPopupMenuEnabled,"isPopupMenuEnabled()"); - add_varargs_method("dump",&View3DInventorPy::dump,"dump(filename, [onlyVisible=False])"); - add_varargs_method("dumpNode",&View3DInventorPy::dumpNode,"dumpNode(node)"); - add_varargs_method("setStereoType",&View3DInventorPy::setStereoType,"setStereoType()"); - add_noargs_method("getStereoType",&View3DInventorPy::getStereoType,"getStereoType()"); - add_noargs_method("listStereoTypes",&View3DInventorPy::listStereoTypes,"listStereoTypes()"); - add_varargs_method("saveImage",&View3DInventorPy::saveImage,"saveImage()"); - add_varargs_method("saveVectorGraphic",&View3DInventorPy::saveVectorGraphic,"saveVectorGraphic()"); - add_noargs_method("getCamera",&View3DInventorPy::getCamera,"getCamera()"); - add_noargs_method("getCameraNode",&View3DInventorPy::getCameraNode,"getCameraNode()"); - add_noargs_method("getViewDirection",&View3DInventorPy::getViewDirection,"getViewDirection() --> tuple of floats\n" + add_noargs_method("viewBottom", &View3DInventorPy::viewBottom, "viewBottom()"); + add_noargs_method("viewFront", &View3DInventorPy::viewFront, "viewFront()"); + add_noargs_method("viewLeft", &View3DInventorPy::viewLeft, "viewLeft()"); + add_noargs_method("viewRear", &View3DInventorPy::viewRear, "viewRear()"); + add_noargs_method("viewRight", &View3DInventorPy::viewRight, "viewRight()"); + add_noargs_method("viewTop", &View3DInventorPy::viewTop, "viewTop()"); + add_noargs_method( + "viewAxometric", + &View3DInventorPy::viewIsometric, + "viewAxonometric()" + ); // for backward compatibility + add_noargs_method("viewAxonometric", &View3DInventorPy::viewIsometric, "viewAxonometric()"); + add_noargs_method("viewIsometric", &View3DInventorPy::viewIsometric, "viewIsometric()"); + add_noargs_method("viewDimetric", &View3DInventorPy::viewDimetric, "viewDimetric()"); + add_noargs_method("viewTrimetric", &View3DInventorPy::viewTrimetric, "viewTrimetric()"); + add_varargs_method( + "viewDefaultOrientation", + &View3DInventorPy::viewDefaultOrientation, + "viewDefaultOrientation(ori_str = '', scale = -1.0): sets camera rotation to a predefined " + "one, \n" + "and camera position and zoom to show certain amount of model space. \n" + "ori_string can be 'Top', 'Bottom', 'Front', 'Rear', 'Left', 'Right', \n" + "'Isometric', 'Dimetric', 'Trimetric', 'Custom'. If empty, the value is \n" + "fetched from Parameters.\n" + "scale sets distance from camera to origin, and height of the screen in \n" + "model space, so that a sphere of diameter fits the height of the\n" + "viewport. If zero, scaling is not done. If negative, the value is \n" + "fetched from Parameters." + ); + add_noargs_method("viewRotateLeft", &View3DInventorPy::viewRotateLeft, "viewRotateLeft()"); + add_noargs_method("viewRotateRight", &View3DInventorPy::viewRotateRight, "viewRotateRight()"); + add_noargs_method("zoomIn", &View3DInventorPy::zoomIn, "zoomIn()"); + add_noargs_method("zoomOut", &View3DInventorPy::zoomOut, "zoomOut()"); + add_varargs_method("viewPosition", &View3DInventorPy::viewPosition, "viewPosition()"); + add_varargs_method("startAnimating", &View3DInventorPy::startAnimating, "startAnimating()"); + add_noargs_method("stopAnimating", &View3DInventorPy::stopAnimating, "stopAnimating()"); + add_varargs_method( + "setAnimationEnabled", + &View3DInventorPy::setAnimationEnabled, + "setAnimationEnabled()" + ); + add_noargs_method("isAnimationEnabled", &View3DInventorPy::isAnimationEnabled, "isAnimationEnabled()"); + add_varargs_method( + "setPopupMenuEnabled", + &View3DInventorPy::setPopupMenuEnabled, + "setPopupMenuEnabled()" + ); + add_noargs_method("isPopupMenuEnabled", &View3DInventorPy::isPopupMenuEnabled, "isPopupMenuEnabled()"); + add_varargs_method("dump", &View3DInventorPy::dump, "dump(filename, [onlyVisible=False])"); + add_varargs_method("dumpNode", &View3DInventorPy::dumpNode, "dumpNode(node)"); + add_varargs_method("setStereoType", &View3DInventorPy::setStereoType, "setStereoType()"); + add_noargs_method("getStereoType", &View3DInventorPy::getStereoType, "getStereoType()"); + add_noargs_method("listStereoTypes", &View3DInventorPy::listStereoTypes, "listStereoTypes()"); + add_varargs_method("saveImage", &View3DInventorPy::saveImage, "saveImage()"); + add_varargs_method("saveVectorGraphic", &View3DInventorPy::saveVectorGraphic, "saveVectorGraphic()"); + add_noargs_method("getCamera", &View3DInventorPy::getCamera, "getCamera()"); + add_noargs_method("getCameraNode", &View3DInventorPy::getCameraNode, "getCameraNode()"); + add_noargs_method( + "getViewDirection", + &View3DInventorPy::getViewDirection, + "getViewDirection() --> tuple of floats\n" "returns the direction vector the view is currently pointing at as tuple with xyz values\n" ); - add_noargs_method("getUpDirection",&View3DInventorPy::getUpDirection,"getUpDirection() --> tuple of integers\n" + add_noargs_method( + "getUpDirection", + &View3DInventorPy::getUpDirection, + "getUpDirection() --> tuple of integers\n" "Returns the up direction vector\n" ); - add_varargs_method("setViewDirection",&View3DInventorPy::setViewDirection,"setViewDirection(tuple) --> None\n" + add_varargs_method( + "setViewDirection", + &View3DInventorPy::setViewDirection, + "setViewDirection(tuple) --> None\n" "Sets the direction the view is pointing at. The direction must be given as tuple with\n" "three coordinates xyz" ); - add_varargs_method("setCamera",&View3DInventorPy::setCamera,"setCamera()"); - add_varargs_method("setCameraOrientation",&View3DInventorPy::setCameraOrientation,"setCameraOrientation()"); - add_noargs_method("getCameraOrientation",&View3DInventorPy::getCameraOrientation,"getCameraOrientation()"); - add_noargs_method("getCameraType",&View3DInventorPy::getCameraType,"getCameraType()"); - add_varargs_method("setCameraType",&View3DInventorPy::setCameraType,"setCameraType()"); - add_noargs_method("listCameraTypes",&View3DInventorPy::listCameraTypes,"listCameraTypes()"); - add_noargs_method("getCursorPos",&View3DInventorPy::getCursorPos, + add_varargs_method("setCamera", &View3DInventorPy::setCamera, "setCamera()"); + add_varargs_method( + "setCameraOrientation", + &View3DInventorPy::setCameraOrientation, + "setCameraOrientation()" + ); + add_noargs_method( + "getCameraOrientation", + &View3DInventorPy::getCameraOrientation, + "getCameraOrientation()" + ); + add_noargs_method("getCameraType", &View3DInventorPy::getCameraType, "getCameraType()"); + add_varargs_method("setCameraType", &View3DInventorPy::setCameraType, "setCameraType()"); + add_noargs_method("listCameraTypes", &View3DInventorPy::listCameraTypes, "listCameraTypes()"); + add_noargs_method( + "getCursorPos", + &View3DInventorPy::getCursorPos, "getCursorPos() -> tuple of integers\n" "\n" "Return the current cursor position relative to the coordinate system of the\n" - "viewport region.\n"); - add_varargs_method("getObjectInfo",&View3DInventorPy::getObjectInfo, + "viewport region.\n" + ); + add_varargs_method( + "getObjectInfo", + &View3DInventorPy::getObjectInfo, "getObjectInfo(tuple(int,int), [pick_radius]) -> dictionary or None\n" "\n" "Return a dictionary with the name of document, object and component. The\n" "dictionary also contains the coordinates of the appropriate 3d point of\n" "the underlying geometry in the scenegraph.\n" - "If no geometry was found 'None' is returned, instead.\n"); - add_varargs_method("getObjectsInfo",&View3DInventorPy::getObjectsInfo, + "If no geometry was found 'None' is returned, instead.\n" + ); + add_varargs_method( + "getObjectsInfo", + &View3DInventorPy::getObjectsInfo, "getObjectsInfo(tuple(int,int), [pick_radius]) -> dictionary or None\n" "\n" - "Does the same as getObjectInfo() but returns a list of dictionaries or None.\n"); - add_noargs_method("getSize",&View3DInventorPy::getSize,"getSize()"); - add_varargs_method("getObjectInfoRay",&View3DInventorPy::getObjectInfoRay, + "Does the same as getObjectInfo() but returns a list of dictionaries or None.\n" + ); + add_noargs_method("getSize", &View3DInventorPy::getSize, "getSize()"); + add_varargs_method( + "getObjectInfoRay", + &View3DInventorPy::getObjectInfoRay, "getObjectInfoRay(tuple(3D vector,3D vector) or tuple of 6 floats) -> dictionary or None\n" "\n" "Vectors represent start point and direction of intersection ray\n" "Return a dictionary with the name of document, object and component. The\n" "dictionary also contains the coordinates of the appropriate 3d point of\n" "the underlying geometry in the scenegraph.\n" - "If no geometry was found 'None' is returned, instead.\n"); - add_varargs_method("getPoint",&View3DInventorPy::getPointOnFocalPlane, - "Same as getPointOnFocalPlane"); - add_varargs_method("getPointOnFocalPlane",&View3DInventorPy::getPointOnFocalPlane, + "If no geometry was found 'None' is returned, instead.\n" + ); + add_varargs_method( + "getPoint", + &View3DInventorPy::getPointOnFocalPlane, + "Same as getPointOnFocalPlane" + ); + add_varargs_method( + "getPointOnFocalPlane", + &View3DInventorPy::getPointOnFocalPlane, "getPointOnFocalPlane(pixel coords (as integer)) -> 3D vector\n" "\n" "Return the according 3D point on the focal plane to the given 2D point (in\n" - "pixel coordinates).\n"); - add_varargs_method("getPointOnScreen",&View3DInventorPy::getPointOnViewport, - "Same as getPointOnViewport"); - add_varargs_method("getPointOnViewport",&View3DInventorPy::getPointOnViewport, + "pixel coordinates).\n" + ); + add_varargs_method( + "getPointOnScreen", + &View3DInventorPy::getPointOnViewport, + "Same as getPointOnViewport" + ); + add_varargs_method( + "getPointOnViewport", + &View3DInventorPy::getPointOnViewport, "getPointOnViewport(3D vector) -> pixel coords (as integer)\n" "\n" - "Return the projected 3D point (in pixel coordinates).\n"); - add_varargs_method("projectPointToLine",&View3DInventorPy::projectPointToLine, + "Return the projected 3D point (in pixel coordinates).\n" + ); + add_varargs_method( + "projectPointToLine", + &View3DInventorPy::projectPointToLine, "projectPointToLine(pixel coords (as integer)) -> line defined by two points\n" "\n" - "Return the projecting 3D line to the given 2D point"); - add_varargs_method("addEventCallback",&View3DInventorPy::addEventCallback,"addEventCallback()"); - add_varargs_method("removeEventCallback",&View3DInventorPy::removeEventCallback,"removeEventCallback()"); - add_varargs_method("setAnnotation",&View3DInventorPy::setAnnotation,"setAnnotation()"); - add_varargs_method("removeAnnotation",&View3DInventorPy::removeAnnotation,"removeAnnotation()"); - add_noargs_method("getSceneGraph",&View3DInventorPy::getSceneGraph,"getSceneGraph()"); - add_noargs_method("getViewer",&View3DInventorPy::getViewer,"getViewer()"); - add_varargs_method("addEventCallbackPivy",&View3DInventorPy::addEventCallbackPivy,"addEventCallbackPivy()"); - add_varargs_method("removeEventCallbackPivy",&View3DInventorPy::removeEventCallbackPivy,"removeEventCallbackPivy()"); - add_varargs_method("addEventCallbackSWIG",&View3DInventorPy::addEventCallbackPivy, - "Deprecated -- use addEventCallbackPivy()"); - add_varargs_method("removeEventCallbackSWIG",&View3DInventorPy::removeEventCallbackPivy, - "Deprecated -- use removeEventCallbackPivy()"); - add_noargs_method("listNavigationTypes",&View3DInventorPy::listNavigationTypes,"listNavigationTypes()"); - add_noargs_method("getNavigationType",&View3DInventorPy::getNavigationType,"getNavigationType()"); - add_varargs_method("setNavigationType",&View3DInventorPy::setNavigationType,"setNavigationType()"); - add_varargs_method("setAxisCross",&View3DInventorPy::setAxisCross,"switch the big axis-cross on and off"); - add_noargs_method("hasAxisCross",&View3DInventorPy::hasAxisCross,"check if the big axis-cross is on or off()"); - add_varargs_method("addDraggerCallback",&View3DInventorPy::addDraggerCallback, + "Return the projecting 3D line to the given 2D point" + ); + add_varargs_method("addEventCallback", &View3DInventorPy::addEventCallback, "addEventCallback()"); + add_varargs_method( + "removeEventCallback", + &View3DInventorPy::removeEventCallback, + "removeEventCallback()" + ); + add_varargs_method("setAnnotation", &View3DInventorPy::setAnnotation, "setAnnotation()"); + add_varargs_method("removeAnnotation", &View3DInventorPy::removeAnnotation, "removeAnnotation()"); + add_noargs_method("getSceneGraph", &View3DInventorPy::getSceneGraph, "getSceneGraph()"); + add_noargs_method("getViewer", &View3DInventorPy::getViewer, "getViewer()"); + add_varargs_method( + "addEventCallbackPivy", + &View3DInventorPy::addEventCallbackPivy, + "addEventCallbackPivy()" + ); + add_varargs_method( + "removeEventCallbackPivy", + &View3DInventorPy::removeEventCallbackPivy, + "removeEventCallbackPivy()" + ); + add_varargs_method( + "addEventCallbackSWIG", + &View3DInventorPy::addEventCallbackPivy, + "Deprecated -- use addEventCallbackPivy()" + ); + add_varargs_method( + "removeEventCallbackSWIG", + &View3DInventorPy::removeEventCallbackPivy, + "Deprecated -- use removeEventCallbackPivy()" + ); + add_noargs_method( + "listNavigationTypes", + &View3DInventorPy::listNavigationTypes, + "listNavigationTypes()" + ); + add_noargs_method("getNavigationType", &View3DInventorPy::getNavigationType, "getNavigationType()"); + add_varargs_method("setNavigationType", &View3DInventorPy::setNavigationType, "setNavigationType()"); + add_varargs_method( + "setAxisCross", + &View3DInventorPy::setAxisCross, + "switch the big axis-cross on and off" + ); + add_noargs_method( + "hasAxisCross", + &View3DInventorPy::hasAxisCross, + "check if the big axis-cross is on or off()" + ); + add_varargs_method( + "addDraggerCallback", + &View3DInventorPy::addDraggerCallback, "addDraggerCallback(SoDragger, String CallbackType, function)\n" "Add a DraggerCalback function to the coin node\n" "Possibles types :\n" - "'addFinishCallback','addStartCallback','addMotionCallback','addValueChangedCallback'\n"); - add_varargs_method("removeDraggerCallback",&View3DInventorPy::removeDraggerCallback, + "'addFinishCallback','addStartCallback','addMotionCallback','addValueChangedCallback'\n" + ); + add_varargs_method( + "removeDraggerCallback", + &View3DInventorPy::removeDraggerCallback, "removeDraggerCallback(SoDragger, String CallbackType, function)\n" "Remove the DraggerCalback function from the coin node\n" "Possibles types :\n" - "'addFinishCallback','addStartCallback','addMotionCallback','addValueChangedCallback'\n"); - add_varargs_method("getViewProvidersOfType", &View3DInventorPy::getViewProvidersOfType, "getViewProvidersOfType(name)\nreturns a list of view providers for the given type"); - add_noargs_method("redraw", &View3DInventorPy::redraw, "redraw(): renders the scene on screen (useful for animations)"); - add_varargs_method("setName",&View3DInventorPy::setName,"setName(str): sets a name to this viewer\nThe name sets the widget's windowTitle and appears on the viewer tab"); - add_keyword_method("toggleClippingPlane", &View3DInventorPy::toggleClippingPlane, + "'addFinishCallback','addStartCallback','addMotionCallback','addValueChangedCallback'\n" + ); + add_varargs_method( + "getViewProvidersOfType", + &View3DInventorPy::getViewProvidersOfType, + "getViewProvidersOfType(name)\nreturns a list of view providers for the given type" + ); + add_noargs_method( + "redraw", + &View3DInventorPy::redraw, + "redraw(): renders the scene on screen (useful for animations)" + ); + add_varargs_method( + "setName", + &View3DInventorPy::setName, + "setName(str): sets a name to this viewer\nThe name sets the widget's windowTitle and " + "appears on the viewer tab" + ); + add_keyword_method( + "toggleClippingPlane", + &View3DInventorPy::toggleClippingPlane, "toggleClippingPlane(toggle=-1, beforeEditing=False, noManip=True, pla=App.Placement()\n" "Toggle a global clipping plane\n\n" "toggle: -1 toggle, 1 show, 0 hide\n" "beforeEditing: whether to insert the clipping node before or after editing root node\n" "noManip: whether to create a manipulator\n" - "pla: clipping plane placement"); - add_noargs_method("hasClippingPlane",&View3DInventorPy::hasClippingPlane, - "hasClippingPlane(): check whether this clipping plane is active"); - add_noargs_method("graphicsView",&View3DInventorPy::graphicsView, - "graphicsView(): Access this view as QGraphicsView"); - add_varargs_method("setCornerCrossVisible",&View3DInventorPy::setCornerCrossVisible, - "setCornerCrossVisible(bool): Defines corner axis cross visibility"); - add_noargs_method("isCornerCrossVisible",&View3DInventorPy::isCornerCrossVisible, - "isCornerCrossVisible(): Returns current corner axis cross visibility"); - add_varargs_method("setCornerCrossSize",&View3DInventorPy::setCornerCrossSize, - "setCornerCrossSize(int): Defines corner axis cross size"); - add_noargs_method("getCornerCrossSize",&View3DInventorPy::getCornerCrossSize, - "getCornerCrossSize(): Returns current corner axis cross size"); - add_noargs_method("cast_to_base", &View3DInventorPy::cast_to_base, "cast_to_base() cast to MDIView class"); + "pla: clipping plane placement" + ); + add_noargs_method( + "hasClippingPlane", + &View3DInventorPy::hasClippingPlane, + "hasClippingPlane(): check whether this clipping plane is active" + ); + add_noargs_method( + "graphicsView", + &View3DInventorPy::graphicsView, + "graphicsView(): Access this view as QGraphicsView" + ); + add_varargs_method( + "setCornerCrossVisible", + &View3DInventorPy::setCornerCrossVisible, + "setCornerCrossVisible(bool): Defines corner axis cross visibility" + ); + add_noargs_method( + "isCornerCrossVisible", + &View3DInventorPy::isCornerCrossVisible, + "isCornerCrossVisible(): Returns current corner axis cross visibility" + ); + add_varargs_method( + "setCornerCrossSize", + &View3DInventorPy::setCornerCrossSize, + "setCornerCrossSize(int): Defines corner axis cross size" + ); + add_noargs_method( + "getCornerCrossSize", + &View3DInventorPy::getCornerCrossSize, + "getCornerCrossSize(): Returns current corner axis cross size" + ); + add_noargs_method( + "cast_to_base", + &View3DInventorPy::cast_to_base, + "cast_to_base() cast to MDIView class" + ); } -View3DInventorPy::View3DInventorPy(View3DInventor *vi) - : base(vi) -{ -} +View3DInventorPy::View3DInventorPy(View3DInventor* vi) + : base(vi) +{} View3DInventorPy::~View3DInventorPy() { Base::PyGILStateLocker lock; - for (auto it : callbacks) + for (auto it : callbacks) { Py_DECREF(it); + } } View3DInventor* View3DInventorPy::getView3DInventorPtr() @@ -250,15 +384,16 @@ View3DInventor* View3DInventorPy::getView3DInventorPtr() Py::Object View3DInventorPy::repr() { - if (!getView3DInventorPtr()) + if (!getView3DInventorPtr()) { throw Py::RuntimeError("Cannot print representation of deleted object"); + } return Py::String("View3DInventor"); } View3DInventorPy::method_varargs_handler View3DInventorPy::pycxx_handler = nullptr; -PyObject *View3DInventorPy::method_varargs_ext_handler(PyObject *_self_and_name_tuple, PyObject *_args) +PyObject* View3DInventorPy::method_varargs_ext_handler(PyObject* _self_and_name_tuple, PyObject* _args) { try { return pycxx_handler(_self_and_name_tuple, _args); @@ -281,11 +416,12 @@ PyObject *View3DInventorPy::method_varargs_ext_handler(PyObject *_self_and_name_ // a trick is to use MDIViewPy as class member and override getattr() to // join the attributes of both classes. This way all methods of MDIViewPy // appear for SheetViewPy, too. -Py::Object View3DInventorPy::getattribute(const char * attr) +Py::Object View3DInventorPy::getattribute(const char* attr) { - if (!getView3DInventorPtr()) + if (!getView3DInventorPtr()) { throw Py::RuntimeError("Cannot print representation of deleted object"); - std::string name( attr ); + } + std::string name(attr); if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); @@ -304,7 +440,7 @@ Py::Object View3DInventorPy::getattribute(const char * attr) } } -Py::Object View3DInventorPy::getattr(const char * attr) +Py::Object View3DInventorPy::getattr(const char* attr) { if (!getView3DInventorPtr()) { std::ostringstream s_out; @@ -313,9 +449,11 @@ Py::Object View3DInventorPy::getattr(const char * attr) } else { // see if an active object has the same name - App::DocumentObject *docObj = getView3DInventorPtr()->getActiveObject(attr); + App::DocumentObject* docObj = getView3DInventorPtr()->getActiveObject( + attr + ); if (docObj) { - return Py::Object(docObj->getPyObject(),true); + return Py::Object(docObj->getPyObject(), true); } else { // else looking for a method with the name and call it @@ -323,8 +461,9 @@ Py::Object View3DInventorPy::getattr(const char * attr) if (PyCFunction_Check(obj.ptr())) { auto op = reinterpret_cast(obj.ptr()); if (op->m_ml->ml_flags == METH_VARARGS) { - if (!pycxx_handler) + if (!pycxx_handler) { pycxx_handler = op->m_ml->ml_meth; + } op->m_ml->ml_meth = method_varargs_ext_handler; } } @@ -333,7 +472,7 @@ Py::Object View3DInventorPy::getattr(const char * attr) } } -int View3DInventorPy::setattr(const char * attr, const Py::Object & value) +int View3DInventorPy::setattr(const char* attr, const Py::Object& value) { if (!getView3DInventorPtr()) { std::string s; @@ -349,8 +488,9 @@ int View3DInventorPy::setattr(const char * attr, const Py::Object & value) Py::Object View3DInventorPy::fitAll(const Py::Tuple& args) { double factor = 1.0; - if (!PyArg_ParseTuple(args.ptr(), "|d", &factor)) + if (!PyArg_ParseTuple(args.ptr(), "|d", &factor)) { throw Py::Exception(); + } try { getView3DInventorPtr()->getViewer()->viewAll((float)factor); @@ -369,10 +509,18 @@ Py::Object View3DInventorPy::fitAll(const Py::Tuple& args) Py::Object View3DInventorPy::boxZoom(const Py::Tuple& args, const Py::Dict& kwds) { - static const std::array kwds_box{"XMin", "YMin", "XMax", "YMax", nullptr}; + static const std::array kwds_box {"XMin", "YMin", "XMax", "YMax", nullptr}; short xmin, ymin, xmax, ymax; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "hhhh", kwds_box, - &xmin, &ymin, &xmax, &ymax)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "hhhh", + kwds_box, + &xmin, + &ymin, + &xmax, + &ymax + )) { throw Py::Exception(); } @@ -547,17 +695,20 @@ Py::Object View3DInventorPy::viewDefaultOrientation(const Py::Tuple& args) { char* view = nullptr; double scale = -1.0; - if (!PyArg_ParseTuple(args.ptr(), "|zd", &view, &scale)) + if (!PyArg_ParseTuple(args.ptr(), "|zd", &view, &scale)) { throw Py::Exception(); + } try { std::string newDocView; - SbRotation rot(0,0,0,1); + SbRotation rot(0, 0, 0, 1); if (view) { newDocView = view; } else { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); newDocView = hGrp->GetASCII("NewDocumentCameraOrientation", "Trimetric"); } @@ -589,7 +740,9 @@ Py::Object View3DInventorPy::viewDefaultOrientation(const Py::Tuple& args) rot = Camera::rotation(Camera::Trimetric); } else if (newDocView == "Custom") { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View/Custom"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View/Custom" + ); auto q0 = static_cast(hGrp->GetFloat("Q0", 0)); auto q1 = static_cast(hGrp->GetFloat("Q1", 0)); auto q2 = static_cast(hGrp->GetFloat("Q2", 0)); @@ -600,9 +753,11 @@ Py::Object View3DInventorPy::viewDefaultOrientation(const Py::Tuple& args) SoCamera* cam = getView3DInventorPtr()->getViewer()->getCamera(); cam->orientation = rot; - if (scale < 0.0){ - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - scale = hGrp->GetFloat("NewDocumentCameraScale",100.0); + if (scale < 0.0) { + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + scale = hGrp->GetFloat("NewDocumentCameraScale", 100.0); } setDefaultCameraHeight(scale); @@ -626,19 +781,19 @@ void View3DInventorPy::setDefaultCameraHeight(float scale) SoCamera* cam = getView3DInventorPtr()->getViewer()->getCamera(); SbRotation rot = cam->orientation.getValue(); - double f = 0.0; //focal dist - if (cam->isOfType(SoOrthographicCamera::getClassTypeId())){ + double f = 0.0; // focal dist + if (cam->isOfType(SoOrthographicCamera::getClassTypeId())) { static_cast(cam)->height = scale; f = scale; } - else if (cam->isOfType(SoPerspectiveCamera::getClassTypeId())){ - //nothing to do + else if (cam->isOfType(SoPerspectiveCamera::getClassTypeId())) { + // nothing to do double ang = static_cast(cam)->heightAngle.getValue(); f = 0.5 * scale / sin(ang * 0.5); } SbVec3f lookDir; - rot.multVec(SbVec3f(0,0,-1), lookDir); + rot.multVec(SbVec3f(0, 0, -1), lookDir); SbVec3f pos = lookDir * -f; cam->focalDistance = f; cam->position = pos; @@ -648,12 +803,12 @@ void View3DInventorPy::setDefaultCameraHeight(float scale) Py::Object View3DInventorPy::viewRotateLeft() { try { - SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); - SbRotation rot = cam->orientation.getValue(); - SbVec3f vdir(0, 0, -1); - rot.multVec(vdir, vdir); - SbRotation nrot(vdir, (float)std::numbers::pi/2); - cam->orientation.setValue(rot*nrot); + SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); + SbRotation rot = cam->orientation.getValue(); + SbVec3f vdir(0, 0, -1); + rot.multVec(vdir, vdir); + SbRotation nrot(vdir, (float)std::numbers::pi / 2); + cam->orientation.setValue(rot * nrot); } catch (const Base::Exception& e) { throw Py::RuntimeError(e.what()); @@ -671,12 +826,12 @@ Py::Object View3DInventorPy::viewRotateLeft() Py::Object View3DInventorPy::viewRotateRight() { try { - SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); - SbRotation rot = cam->orientation.getValue(); - SbVec3f vdir(0, 0, -1); - rot.multVec(vdir, vdir); - SbRotation nrot(vdir, (float)-std::numbers::pi/2); - cam->orientation.setValue(rot*nrot); + SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); + SbRotation rot = cam->orientation.getValue(); + SbVec3f vdir(0, 0, -1); + rot.multVec(vdir, vdir); + SbRotation nrot(vdir, (float)-std::numbers::pi / 2); + cam->orientation.setValue(rot * nrot); } catch (const Base::Exception& e) { throw Py::RuntimeError(e.what()); @@ -730,9 +885,10 @@ Py::Object View3DInventorPy::zoomOut() Py::Object View3DInventorPy::setCameraOrientation(const Py::Tuple& args) { PyObject* o; - PyObject* m=Py_False; - if (!PyArg_ParseTuple(args.ptr(), "O|O!", &o, &PyBool_Type, &m)) + PyObject* m = Py_False; + if (!PyArg_ParseTuple(args.ptr(), "O|O!", &o, &PyBool_Type, &m)) { throw Py::Exception(); + } try { if (PyTuple_Check(o)) { @@ -741,20 +897,26 @@ Py::Object View3DInventorPy::setCameraOrientation(const Py::Tuple& args) float q1 = (float)Py::Float(tuple[1]); float q2 = (float)Py::Float(tuple[2]); float q3 = (float)Py::Float(tuple[3]); - getView3DInventorPtr()->getViewer()->setCameraOrientation(SbRotation(q0, q1, q2, q3), Base::asBoolean(m)); + getView3DInventorPtr()->getViewer()->setCameraOrientation( + SbRotation(q0, q1, q2, q3), + Base::asBoolean(m) + ); } else if (PyObject_TypeCheck(o, &Base::RotationPy::Type)) { - Base::Rotation r = static_cast(Py::Rotation(o,false)); + Base::Rotation r = static_cast(Py::Rotation(o, false)); double q0, q1, q2, q3; r.getValue(q0, q1, q2, q3); - getView3DInventorPtr()->getViewer()->setCameraOrientation(SbRotation((float)q0, (float)q1, (float)q2, (float)q3), Base::asBoolean(m)); + getView3DInventorPtr()->getViewer()->setCameraOrientation( + SbRotation((float)q0, (float)q1, (float)q2, (float)q3), + Base::asBoolean(m) + ); } else { throw Py::ValueError("Neither tuple nor rotation object"); } } catch (const Py::Exception&) { - throw; // re-throw + throw; // re-throw } catch (const Base::Exception& e) { throw Py::RuntimeError(e.what()); @@ -762,7 +924,7 @@ Py::Object View3DInventorPy::setCameraOrientation(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -772,41 +934,45 @@ Py::Object View3DInventorPy::setCameraOrientation(const Py::Tuple& args) Py::Object View3DInventorPy::getCameraOrientation() { SbRotation rot = getView3DInventorPtr()->getViewer()->getCameraOrientation(); - float q0,q1,q2,q3; - rot.getValue(q0,q1,q2,q3); - return Py::Rotation(Base::Rotation(q0,q1,q2,q3)); + float q0, q1, q2, q3; + rot.getValue(q0, q1, q2, q3); + return Py::Rotation(Base::Rotation(q0, q1, q2, q3)); } Py::Object View3DInventorPy::viewPosition(const Py::Tuple& args) { PyObject* p = nullptr; - int steps; // Unused but kept as parameter to not break the Python interface - int duration = -1; // Duration in ms, will be replaced with User parameter:BaseApp/Preferences/View/AnimationDuration when not explicitly provided - if (!PyArg_ParseTuple(args.ptr(), "|O!ii", &Base::PlacementPy::Type, &p, &steps, &duration)) + int steps; // Unused but kept as parameter to not break the Python interface + int duration = -1; // Duration in ms, will be replaced with User + // parameter:BaseApp/Preferences/View/AnimationDuration when not explicitly + // provided + if (!PyArg_ParseTuple(args.ptr(), "|O!ii", &Base::PlacementPy::Type, &p, &steps, &duration)) { throw Py::Exception(); + } if (p) { Base::Placement* plm = static_cast(p)->getPlacementPtr(); Base::Rotation rot = plm->getRotation(); Base::Vector3d pos = plm->getPosition(); - double q0,q1,q2,q3; - rot.getValue(q0,q1,q2,q3); + double q0, q1, q2, q3; + rot.getValue(q0, q1, q2, q3); getView3DInventorPtr()->getViewer()->moveCameraTo( SbRotation((float)q0, (float)q1, (float)q2, (float)q3), - SbVec3f((float)pos.x, (float)pos.y, (float)pos.z), duration); + SbVec3f((float)pos.x, (float)pos.y, (float)pos.z), + duration + ); } SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); - if (!cam) + if (!cam) { return Py::None(); + } SbRotation rot = cam->orientation.getValue(); SbVec3f pos = cam->position.getValue(); - float q0,q1,q2,q3; - rot.getValue(q0,q1,q2,q3); - Base::Placement plm( - Base::Vector3d(pos[0], pos[1], pos[2]), - Base::Rotation(q0, q1, q2, q3)); + float q0, q1, q2, q3; + rot.getValue(q0, q1, q2, q3); + Base::Placement plm(Base::Vector3d(pos[0], pos[1], pos[2]), Base::Rotation(q0, q1, q2, q3)); return Py::Placement(plm); } @@ -814,8 +980,9 @@ Py::Object View3DInventorPy::startAnimating(const Py::Tuple& args) { float x, y, z; float velocity; - if (!PyArg_ParseTuple(args.ptr(), "ffff", &x, &y, &z, &velocity)) + if (!PyArg_ParseTuple(args.ptr(), "ffff", &x, &y, &z, &velocity)) { throw Py::Exception(); + } getView3DInventorPtr()->getViewer()->startSpinningAnimation(SbVec3f(x, y, z), velocity); return Py::None(); } @@ -829,9 +996,10 @@ Py::Object View3DInventorPy::stopAnimating() Py::Object View3DInventorPy::setAnimationEnabled(const Py::Tuple& args) { int ok; - if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) + if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) { throw Py::Exception(); - getView3DInventorPtr()->getViewer()->setAnimationEnabled(ok!=0); + } + getView3DInventorPtr()->getViewer()->setAnimationEnabled(ok != 0); return Py::None(); } @@ -844,9 +1012,10 @@ Py::Object View3DInventorPy::isAnimationEnabled() Py::Object View3DInventorPy::setPopupMenuEnabled(const Py::Tuple& args) { int ok; - if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) + if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) { throw Py::Exception(); - getView3DInventorPtr()->getViewer()->setPopupMenuEnabled(ok!=0); + } + getView3DInventorPtr()->getViewer()->setPopupMenuEnabled(ok != 0); return Py::None(); } @@ -858,28 +1027,32 @@ Py::Object View3DInventorPy::isPopupMenuEnabled() Py::Object View3DInventorPy::saveImage(const Py::Tuple& args) { - char *cFileName = nullptr; - const char *cColor="Current"; - const char *cComment="$MIBA"; - int w=-1,h=-1; - int s=View3DInventorViewer::getNumSamples(); + char* cFileName = nullptr; + const char* cColor = "Current"; + const char* cComment = "$MIBA"; + int w = -1, h = -1; + int s = View3DInventorViewer::getNumSamples(); - if (!PyArg_ParseTuple(args.ptr(), "et|iissi","utf-8",&cFileName,&w,&h,&cColor,&cComment,&s)) + if (!PyArg_ParseTuple(args.ptr(), "et|iissi", "utf-8", &cFileName, &w, &h, &cColor, &cComment, &s)) { throw Py::Exception(); + } std::string encodedName = std::string(cFileName); PyMem_Free(cFileName); QFileInfo fi(QString::fromUtf8(encodedName.c_str())); - if (!fi.absoluteDir().exists()) + if (!fi.absoluteDir().exists()) { throw Py::RuntimeError("Directory where to save image doesn't exist"); + } QColor bg; QString colname = QString::fromLatin1(cColor); - if (colname.compare(QLatin1String("Current"), Qt::CaseInsensitive) == 0) - bg = QColor(); // assign an invalid color here - else + if (colname.compare(QLatin1String("Current"), Qt::CaseInsensitive) == 0) { + bg = QColor(); // assign an invalid color here + } + else { bg = QColor(colname); + } QImage img; getView3DInventorPtr()->getViewer()->savePicture(w, h, s, bg, img); @@ -894,17 +1067,18 @@ Py::Object View3DInventorPy::saveImage(const Py::Tuple& args) Py::Object View3DInventorPy::saveVectorGraphic(const Py::Tuple& args) { char* filename; - int ps=4; - const char* name="white"; + int ps = 4; + const char* name = "white"; - if (!PyArg_ParseTuple(args.ptr(), "s|is",&filename,&ps,&name)) + if (!PyArg_ParseTuple(args.ptr(), "s|is", &filename, &ps, &name)) { throw Py::Exception(); + } std::unique_ptr vo; Base::FileInfo fi(filename); if (fi.hasExtension({"ps", "eps"})) { vo = std::unique_ptr(new SoVectorizePSAction()); - //vo->setGouraudThreshold(0.0f); + // vo->setGouraudThreshold(0.0f); } else if (fi.hasExtension("svg")) { vo = std::unique_ptr(new SoFCVectorizeSVGAction()); @@ -916,7 +1090,7 @@ Py::Object View3DInventorPy::saveVectorGraphic(const Py::Tuple& args) throw Py::RuntimeError("Not supported vector graphic"); } - SoVectorOutput * out = vo->getOutput(); + SoVectorOutput* out = vo->getOutput(); if (!out || !out->openFile(filename)) { std::ostringstream a_out; a_out << "Cannot open file '" << filename << "'"; @@ -925,12 +1099,14 @@ Py::Object View3DInventorPy::saveVectorGraphic(const Py::Tuple& args) QColor bg; QString colname = QString::fromLatin1(name); - if (colname.compare(QLatin1String("Current"), Qt::CaseInsensitive) == 0) + if (colname.compare(QLatin1String("Current"), Qt::CaseInsensitive) == 0) { bg = getView3DInventorPtr()->getViewer()->backgroundColor(); - else + } + else { bg = QColor(colname); + } - getView3DInventorPtr()->getViewer()->saveGraphic(ps,bg,vo.get()); + getView3DInventorPtr()->getViewer()->saveGraphic(ps, bg, vo.get()); out->closeFile(); return Py::None(); } @@ -941,10 +1117,11 @@ Py::Object View3DInventorPy::getCameraNode() SoNode* camera = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); PyObject* proxy = nullptr; std::string type; - type = "So"; // seems that So prefix is missing in camera node + type = "So"; // seems that So prefix is missing in camera node type += camera->getTypeId().getName().getString(); type += " *"; - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", type.c_str(), static_cast(camera), 1); + proxy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", type.c_str(), static_cast(camera), 1); camera->ref(); return Py::Object(proxy, true); } @@ -961,9 +1138,13 @@ Py::Object View3DInventorPy::getCamera() try { SoWriteAction wa(&out); - SoCamera * cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); - if (cam) wa.apply(cam); - else buffer[0] = '\0'; + SoCamera* cam = getView3DInventorPtr()->getViewer()->getSoRenderManager()->getCamera(); + if (cam) { + wa.apply(cam); + } + else { + buffer[0] = '\0'; + } return Py::String(buffer); } catch (const Base::Exception& e) { @@ -1015,8 +1196,9 @@ Py::Object View3DInventorPy::getUpDirection() Py::Object View3DInventorPy::setViewDirection(const Py::Tuple& args) { PyObject* object; - if (!PyArg_ParseTuple(args.ptr(), "O", &object)) + if (!PyArg_ParseTuple(args.ptr(), "O", &object)) { throw Py::Exception(); + } try { if (PyTuple_Check(object)) { @@ -1026,14 +1208,15 @@ Py::Object View3DInventorPy::setViewDirection(const Py::Tuple& args) Py::Float z(tuple.getItem(2)); SbVec3f dir; dir.setValue((float)x, (float)y, (float)z); - if (dir.length() < 0.001f) + if (dir.length() < 0.001f) { throw Py::ValueError("Null vector cannot be used to set direction"); + } getView3DInventorPtr()->getViewer()->setViewDirection(dir); return Py::None(); } } catch (const Py::Exception&) { - throw; // re-throw + throw; // re-throw } catch (const Base::Exception& e) { throw Py::RuntimeError(e.what()); @@ -1046,15 +1229,15 @@ Py::Object View3DInventorPy::setViewDirection(const Py::Tuple& args) } return Py::None(); - } Py::Object View3DInventorPy::setCamera(const Py::Tuple& args) { char* buffer; - if (!PyArg_ParseTuple(args.ptr(), "s", &buffer)) + if (!PyArg_ParseTuple(args.ptr(), "s", &buffer)) { throw Py::Exception(); + } try { getView3DInventorPtr()->setCamera(buffer); @@ -1066,13 +1249,13 @@ Py::Object View3DInventorPy::setCamera(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } -//FIXME: Once View3DInventor inherits from PropertyContainer we can use PropertyEnumeration. -const char* CameraTypeEnums[]= {"Orthographic","Perspective",nullptr}; +// FIXME: Once View3DInventor inherits from PropertyContainer we can use PropertyEnumeration. +const char* CameraTypeEnums[] = {"Orthographic", "Perspective", nullptr}; Py::Object View3DInventorPy::getCameraType() { @@ -1093,14 +1276,15 @@ Py::Object View3DInventorPy::getCameraType() Py::Object View3DInventorPy::setCameraType(const Py::Tuple& args) { - int cameratype=-1; + int cameratype = -1; if (!PyArg_ParseTuple(args.ptr(), "i", &cameratype)) { char* modename; PyErr_Clear(); - if (!PyArg_ParseTuple(args.ptr(), "s", &modename)) + if (!PyArg_ParseTuple(args.ptr(), "s", &modename)) { throw Py::Exception(); - for (int i=0; i<2; i++ ) { - if (strncmp(CameraTypeEnums[i],modename,20) == 0 ) { + } + for (int i = 0; i < 2; i++) { + if (strncmp(CameraTypeEnums[i], modename, 20) == 0) { cameratype = i; break; } @@ -1114,12 +1298,15 @@ Py::Object View3DInventorPy::setCameraType(const Py::Tuple& args) } } - if (cameratype < 0 || cameratype > 1) + if (cameratype < 0 || cameratype > 1) { throw Py::IndexError("Out of range"); - if (cameratype==0) + } + if (cameratype == 0) { getView3DInventorPtr()->getViewer()->setCameraType(SoOrthographicCamera::getClassTypeId()); - else + } + else { getView3DInventorPtr()->getViewer()->setCameraType(SoPerspectiveCamera::getClassTypeId()); + } return Py::None(); } @@ -1127,7 +1314,7 @@ Py::Object View3DInventorPy::listCameraTypes() { try { Py::List list(2); - for (int i=0; i<2; i++) { + for (int i = 0; i < 2; i++) { list[i] = Py::String(CameraTypeEnums[i]); } return list; @@ -1138,7 +1325,7 @@ Py::Object View3DInventorPy::listCameraTypes() catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -1146,9 +1333,10 @@ Py::Object View3DInventorPy::listCameraTypes() Py::Object View3DInventorPy::dump(const Py::Tuple& args) { char* filename; - PyObject *onlyVisible = Py_False; - if (!PyArg_ParseTuple(args.ptr(), "s|O!", &filename, &PyBool_Type, &onlyVisible)) + PyObject* onlyVisible = Py_False; + if (!PyArg_ParseTuple(args.ptr(), "s|O!", &filename, &PyBool_Type, &onlyVisible)) { throw Py::Exception(); + } try { getView3DInventorPtr()->dump(filename, Base::asBoolean(onlyVisible)); @@ -1160,7 +1348,7 @@ Py::Object View3DInventorPy::dump(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -1168,8 +1356,9 @@ Py::Object View3DInventorPy::dump(const Py::Tuple& args) Py::Object View3DInventorPy::dumpNode(const Py::Tuple& args) { PyObject* object; - if (!PyArg_ParseTuple(args.ptr(), "O", &object)) + if (!PyArg_ParseTuple(args.ptr(), "O", &object)) { throw Py::Exception(); + } void* ptr = nullptr; try { @@ -1185,19 +1374,21 @@ Py::Object View3DInventorPy::dumpNode(const Py::Tuple& args) return Py::String(SoFCDB::writeNodesToString(node)); } -//FIXME: Once View3DInventor inherits from PropertyContainer we can use PropertyEnumeration. -const char* StereoTypeEnums[]= {"Mono","Anaglyph","QuadBuffer","InterleavedRows","InterleavedColumns",nullptr}; +// FIXME: Once View3DInventor inherits from PropertyContainer we can use PropertyEnumeration. +const char* StereoTypeEnums[] + = {"Mono", "Anaglyph", "QuadBuffer", "InterleavedRows", "InterleavedColumns", nullptr}; Py::Object View3DInventorPy::setStereoType(const Py::Tuple& args) { - int stereomode=-1; + int stereomode = -1; if (!PyArg_ParseTuple(args.ptr(), "i", &stereomode)) { char* modename; PyErr_Clear(); - if (!PyArg_ParseTuple(args.ptr(), "s", &modename)) + if (!PyArg_ParseTuple(args.ptr(), "s", &modename)) { throw Py::Exception(); - for (int i=0; i<5; i++) { - if (strncmp(StereoTypeEnums[i],modename,20) == 0) { + } + for (int i = 0; i < 5; i++) { + if (strncmp(StereoTypeEnums[i], modename, 20) == 0) { stereomode = i; break; } @@ -1212,9 +1403,12 @@ Py::Object View3DInventorPy::setStereoType(const Py::Tuple& args) } try { - if (stereomode < 0 || stereomode > 4) + if (stereomode < 0 || stereomode > 4) { throw Py::IndexError("Out of range"); - Quarter::SoQTQuarterAdaptor::StereoMode mode = Quarter::SoQTQuarterAdaptor::StereoMode(stereomode); + } + Quarter::SoQTQuarterAdaptor::StereoMode mode = Quarter::SoQTQuarterAdaptor::StereoMode( + stereomode + ); getView3DInventorPtr()->getViewer()->setStereoMode(mode); return Py::None(); } @@ -1224,7 +1418,7 @@ Py::Object View3DInventorPy::setStereoType(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -1233,8 +1427,9 @@ Py::Object View3DInventorPy::getStereoType() { try { int mode = int(getView3DInventorPtr()->getViewer()->stereoMode()); - if (mode < 0 || mode > 4) + if (mode < 0 || mode > 4) { throw Py::ValueError("Invalid stereo mode"); + } return Py::String(StereoTypeEnums[mode]); } catch (const Base::Exception& e) { @@ -1243,7 +1438,7 @@ Py::Object View3DInventorPy::getStereoType() catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -1252,7 +1447,7 @@ Py::Object View3DInventorPy::listStereoTypes() { try { Py::List list(5); - for (int i=0; i<5; i++) { + for (int i = 0; i < 5; i++) { list[i] = Py::String(StereoTypeEnums[i]); } @@ -1264,7 +1459,7 @@ Py::Object View3DInventorPy::listStereoTypes() catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -1289,15 +1484,16 @@ Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args) { PyObject* object; float r = getView3DInventorPtr()->getViewer()->getPickRadius(); - if (!PyArg_ParseTuple(args.ptr(), "O|f", &object, &r)) + if (!PyArg_ParseTuple(args.ptr(), "O|f", &object, &r)) { throw Py::Exception(); + } try { - //Note: For gcc (4.2) we need the 'const' keyword to avoid the compiler error: - //conversion from 'Py::seqref' to non-scalar type 'Py::Long' requested - //We should report this problem to the PyCXX project as in the documentation an - //example without the 'const' keyword is used. - //Or we can also write Py::Long x(tuple[0]); + // Note: For gcc (4.2) we need the 'const' keyword to avoid the compiler error: + // conversion from 'Py::seqref' to non-scalar type 'Py::Long' requested + // We should report this problem to the PyCXX project as in the documentation an + // example without the 'const' keyword is used. + // Or we can also write Py::Long x(tuple[0]); const Py::Tuple tuple(object); Py::Long x(tuple[0]); Py::Long y(tuple[1]); @@ -1306,11 +1502,13 @@ Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args) // graph traversal we must not use a second SoHandleEventAction as // we will get Coin warnings because of multiple scene graph traversals // which is regarded as error-prone. - SoRayPickAction action(getView3DInventorPtr()->getViewer()->getSoRenderManager()->getViewportRegion()); - action.setPoint(SbVec2s((long)x,(long)y)); + SoRayPickAction action( + getView3DInventorPtr()->getViewer()->getSoRenderManager()->getViewportRegion() + ); + action.setPoint(SbVec2s((long)x, (long)y)); action.setRadius(r); action.apply(getView3DInventorPtr()->getViewer()->getSoRenderManager()->getSceneGraph()); - SoPickedPoint *Point = action.getPickedPoint(); + SoPickedPoint* Point = action.getPickedPoint(); Py::Object ret = Py::None(); if (Point) { @@ -1320,47 +1518,49 @@ Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args) dict.setItem("y", Py::Float(pt[1])); dict.setItem("z", Py::Float(pt[2])); - ViewProvider *vp = getView3DInventorPtr()->getViewer()->getViewProviderByPath(Point->getPath()); + ViewProvider* vp = getView3DInventorPtr()->getViewer()->getViewProviderByPath( + Point->getPath() + ); if (vp && vp->isDerivedFrom()) { - if (!vp->isSelectable()) + if (!vp->isSelectable()) { return ret; + } auto vpd = static_cast(vp); if (vp->useNewSelectionModel()) { std::string subname; - if (!vp->getElementPicked(Point,subname)) + if (!vp->getElementPicked(Point, subname)) { return ret; + } auto obj = vpd->getObject(); - if (!obj) + if (!obj) { return ret; + } if (!subname.empty()) { App::ElementNamePair elementName; - auto sobj = App::GeoFeature::resolveElement(obj,subname.c_str(),elementName); - if (!sobj) + auto sobj = App::GeoFeature::resolveElement(obj, subname.c_str(), elementName); + if (!sobj) { return ret; + } if (sobj != obj) { - dict.setItem("ParentObject",Py::Object(obj->getPyObject(),true)); - dict.setItem("SubName",Py::String(subname)); + dict.setItem("ParentObject", Py::Object(obj->getPyObject(), true)); + dict.setItem("SubName", Py::String(subname)); obj = sobj; } - subname = !elementName.oldName.empty()?elementName.oldName:elementName.newName; + subname = !elementName.oldName.empty() ? elementName.oldName + : elementName.newName; } - dict.setItem("Document", - Py::String(obj->getDocument()->getName())); - dict.setItem("Object", - Py::String(obj->getNameInDocument())); - dict.setItem("Component",Py::String(subname)); + dict.setItem("Document", Py::String(obj->getDocument()->getName())); + dict.setItem("Object", Py::String(obj->getNameInDocument())); + dict.setItem("Component", Py::String(subname)); } else { - dict.setItem("Document", - Py::String(vpd->getObject()->getDocument()->getName())); - dict.setItem("Object", - Py::String(vpd->getObject()->getNameInDocument())); + dict.setItem("Document", Py::String(vpd->getObject()->getDocument()->getName())); + dict.setItem("Object", Py::String(vpd->getObject()->getNameInDocument())); // search for a SoFCSelection node SoFCDocumentObjectAction objaction; objaction.apply(Point->getPath()); if (objaction.isHandled()) { - dict.setItem("Component", - Py::String(objaction.componentName.getString())); + dict.setItem("Component", Py::String(objaction.componentName.getString())); } } @@ -1372,12 +1572,9 @@ Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args) SoFCDocumentObjectAction objaction; objaction.apply(Point->getPath()); if (objaction.isHandled()) { - dict.setItem("Document", - Py::String(objaction.documentName.getString())); - dict.setItem("Object", - Py::String(objaction.objectName.getString())); - dict.setItem("Component", - Py::String(objaction.componentName.getString())); + dict.setItem("Document", Py::String(objaction.documentName.getString())); + dict.setItem("Object", Py::String(objaction.objectName.getString())); + dict.setItem("Component", Py::String(objaction.componentName.getString())); // ok, found the node of interest ret = dict; } @@ -1395,15 +1592,16 @@ Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args) { PyObject* object; float r = getView3DInventorPtr()->getViewer()->getPickRadius(); - if (!PyArg_ParseTuple(args.ptr(), "O|f", &object, &r)) + if (!PyArg_ParseTuple(args.ptr(), "O|f", &object, &r)) { throw Py::Exception(); + } try { - //Note: For gcc (4.2) we need the 'const' keyword to avoid the compiler error: - //conversion from 'Py::seqref' to non-scalar type 'Py::Long' requested - //We should report this problem to the PyCXX project as in the documentation an - //example without the 'const' keyword is used. - //Or we can also write Py::Long x(tuple[0]); + // Note: For gcc (4.2) we need the 'const' keyword to avoid the compiler error: + // conversion from 'Py::seqref' to non-scalar type 'Py::Long' requested + // We should report this problem to the PyCXX project as in the documentation an + // example without the 'const' keyword is used. + // Or we can also write Py::Long x(tuple[0]); const Py::Tuple tuple(object); Py::Long x(tuple[0]); Py::Long y(tuple[1]); @@ -1412,17 +1610,19 @@ Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args) // graph traversal we must not use a second SoHandleEventAction as // we will get Coin warnings because of multiple scene graph traversals // which is regarded as error-prone. - SoRayPickAction action(getView3DInventorPtr()->getViewer()->getSoRenderManager()->getViewportRegion()); + SoRayPickAction action( + getView3DInventorPtr()->getViewer()->getSoRenderManager()->getViewportRegion() + ); action.setPickAll(true); action.setRadius(r); - action.setPoint(SbVec2s((long)x,(long)y)); + action.setPoint(SbVec2s((long)x, (long)y)); action.apply(getView3DInventorPtr()->getViewer()->getSoRenderManager()->getSceneGraph()); const SoPickedPointList& pp = action.getPickedPointList(); Py::Object ret = Py::None(); if (pp.getLength() > 0) { Py::List list; - for (int i=0; i(pp.get(i)); SbVec3f pt = point->getPoint(); @@ -1430,47 +1630,50 @@ Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args) dict.setItem("y", Py::Float(pt[1])); dict.setItem("z", Py::Float(pt[2])); - ViewProvider *vp = getView3DInventorPtr()->getViewer()->getViewProviderByPath(point->getPath()); - if(vp && vp->isDerivedFrom()) { - if(!vp->isSelectable()) + ViewProvider* vp = getView3DInventorPtr()->getViewer()->getViewProviderByPath( + point->getPath() + ); + if (vp && vp->isDerivedFrom()) { + if (!vp->isSelectable()) { continue; + } auto vpd = static_cast(vp); if (vp->useNewSelectionModel()) { std::string subname; - if (!vp->getElementPicked(point,subname)) + if (!vp->getElementPicked(point, subname)) { continue; + } auto obj = vpd->getObject(); - if (!obj) + if (!obj) { continue; + } if (!subname.empty()) { App::ElementNamePair elementName; - auto sobj = App::GeoFeature::resolveElement(obj,subname.c_str(),elementName); - if (!sobj) + auto sobj + = App::GeoFeature::resolveElement(obj, subname.c_str(), elementName); + if (!sobj) { continue; + } if (sobj != obj) { - dict.setItem("ParentObject",Py::Object(obj->getPyObject(),true)); - dict.setItem("SubName",Py::String(subname)); + dict.setItem("ParentObject", Py::Object(obj->getPyObject(), true)); + dict.setItem("SubName", Py::String(subname)); obj = sobj; } - subname = !elementName.oldName.empty()?elementName.oldName:elementName.newName; + subname = !elementName.oldName.empty() ? elementName.oldName + : elementName.newName; } - dict.setItem("Document", - Py::String(obj->getDocument()->getName())); - dict.setItem("Object", - Py::String(obj->getNameInDocument())); - dict.setItem("Component",Py::String(subname)); + dict.setItem("Document", Py::String(obj->getDocument()->getName())); + dict.setItem("Object", Py::String(obj->getNameInDocument())); + dict.setItem("Component", Py::String(subname)); } else { - dict.setItem("Document", - Py::String(vpd->getObject()->getDocument()->getName())); - dict.setItem("Object", - Py::String(vpd->getObject()->getNameInDocument())); + dict.setItem("Document", Py::String(vpd->getObject()->getDocument()->getName())); + dict.setItem("Object", Py::String(vpd->getObject()->getNameInDocument())); // search for a SoFCSelection node SoFCDocumentObjectAction objaction; objaction.apply(point->getPath()); if (objaction.isHandled()) { - dict.setItem("Component", - Py::String(objaction.componentName.getString())); + dict.setItem("Component", Py::String(objaction.componentName.getString())); } } // ok, found the node of interest @@ -1481,12 +1684,9 @@ Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args) SoFCDocumentObjectAction objaction; objaction.apply(point->getPath()); if (objaction.isHandled()) { - dict.setItem("Document", - Py::String(objaction.documentName.getString())); - dict.setItem("Object", - Py::String(objaction.objectName.getString())); - dict.setItem("Component", - Py::String(objaction.componentName.getString())); + dict.setItem("Document", Py::String(objaction.documentName.getString())); + dict.setItem("Object", Py::String(objaction.objectName.getString())); + dict.setItem("Component", Py::String(objaction.componentName.getString())); // ok, found the node of interest ret = dict; } @@ -1510,12 +1710,7 @@ Py::Object View3DInventorPy::getObjectInfoRay(const Py::Tuple& args) double vsx, vsy, vsz; double vdx, vdy, vdz; Py::Object ret = Py::None(); - if (PyArg_ParseTuple(args.ptr(), - "O!O!", - &Base::VectorPy::Type, - &vs, - &Base::VectorPy::Type, - &vd)) { + if (PyArg_ParseTuple(args.ptr(), "O!O!", &Base::VectorPy::Type, &vs, &Base::VectorPy::Type, &vd)) { Base::Vector3d* startvec = static_cast(vs)->getVectorPtr(); Base::Vector3d* dirvec = static_cast(vd)->getVectorPtr(); try { @@ -1567,7 +1762,7 @@ Py::Object View3DInventorPy::getSize() Py::Object View3DInventorPy::getPointOnFocalPlane(const Py::Tuple& args) { - short x,y; + short x, y; if (!PyArg_ParseTuple(args.ptr(), "hh", &x, &y)) { PyErr_Clear(); Py::Tuple t(args[0]); @@ -1575,7 +1770,7 @@ Py::Object View3DInventorPy::getPointOnFocalPlane(const Py::Tuple& args) y = (int)Py::Long(t[1]); } try { - SbVec3f pt = getView3DInventorPtr()->getViewer()->getPointOnFocalPlane(SbVec2s(x,y)); + SbVec3f pt = getView3DInventorPtr()->getViewer()->getPointOnFocalPlane(SbVec2s(x, y)); return Py::Vector(Base::Vector3f(pt[0], pt[1], pt[2])); } catch (const Base::Exception& e) { @@ -1589,7 +1784,7 @@ Py::Object View3DInventorPy::getPointOnFocalPlane(const Py::Tuple& args) Py::Object View3DInventorPy::getPointOnViewport(const Py::Tuple& args) { PyObject* v; - double vx,vy,vz; + double vx, vy, vz; if (PyArg_ParseTuple(args.ptr(), "O!", &Base::VectorPy::Type, &v)) { Base::Vector3d* vec = static_cast(v)->getVectorPtr(); vx = vec->x; @@ -1598,13 +1793,13 @@ Py::Object View3DInventorPy::getPointOnViewport(const Py::Tuple& args) } else { PyErr_Clear(); - if (!PyArg_ParseTuple(args.ptr(), "ddd", &vx,&vy,&vz)) { + if (!PyArg_ParseTuple(args.ptr(), "ddd", &vx, &vy, &vz)) { throw Py::TypeError("Wrong argument, Vector or three floats expected expected"); } } try { - SbVec2s pt = getView3DInventorPtr()->getViewer()->getPointOnViewport(SbVec3f(vx,vy,vz)); + SbVec2s pt = getView3DInventorPtr()->getViewer()->getPointOnViewport(SbVec3f(vx, vy, vz)); Py::Tuple tuple(2); tuple.setItem(0, Py::Long(pt[0])); tuple.setItem(1, Py::Long(pt[1])); @@ -1621,7 +1816,7 @@ Py::Object View3DInventorPy::getPointOnViewport(const Py::Tuple& args) Py::Object View3DInventorPy::projectPointToLine(const Py::Tuple& args) { - short x,y; + short x, y; if (!PyArg_ParseTuple(args.ptr(), "hh", &x, &y)) { PyErr_Clear(); Py::Tuple t(args[0]); @@ -1630,7 +1825,7 @@ Py::Object View3DInventorPy::projectPointToLine(const Py::Tuple& args) } try { SbVec3f pt1, pt2; - getView3DInventorPtr()->getViewer()->projectPointToLine(SbVec2s(x,y), pt1, pt2); + getView3DInventorPtr()->getViewer()->projectPointToLine(SbVec2s(x, y), pt1, pt2); Py::Tuple tuple(2); tuple.setItem(0, Py::Vector(Base::Vector3f(pt1[0], pt1[1], pt1[2]))); tuple.setItem(1, Py::Vector(Base::Vector3f(pt2[0], pt2[1], pt2[2]))); @@ -1664,25 +1859,30 @@ Py::Object View3DInventorPy::getNavigationType() Py::Object View3DInventorPy::setNavigationType(const Py::Tuple& args) { char* style; - if (!PyArg_ParseTuple(args.ptr(), "s", &style)) + if (!PyArg_ParseTuple(args.ptr(), "s", &style)) { throw Py::Exception(); + } Base::Type type = Base::Type::fromName(style); getView3DInventorPtr()->getViewer()->setNavigationType(type); return Py::None(); } -void View3DInventorPy::eventCallback(void * ud, SoEventCallback * n) +void View3DInventorPy::eventCallback(void* ud, SoEventCallback* n) { Base::PyGILStateLocker lock; try { Py::Dict dict; const SoEvent* e = n->getEvent(); - if (!e) // invalid event + if (!e) { // invalid event return; + } // Type dict.setItem("Type", Py::String(std::string(e->getTypeId().getName().getString()))); // Time - dict.setItem("Time", Py::String(std::string(e->getTime().formatDate("%Y-%m-%d %H:%M:%S").getString()))); + dict.setItem( + "Time", + Py::String(std::string(e->getTime().formatDate("%Y-%m-%d %H:%M:%S").getString())) + ); SbVec2s p = n->getEvent()->getPosition(); Py::Tuple pos(2); pos.setItem(0, Py::Long(p[0])); @@ -1691,8 +1891,8 @@ void View3DInventorPy::eventCallback(void * ud, SoEventCallback * n) dict.setItem("Position", pos); // Shift, Ctrl, Alt down dict.setItem("ShiftDown", Py::Object((e->wasShiftDown() ? Py_True : Py_False))); - dict.setItem("CtrlDown", Py::Object((e->wasCtrlDown() ? Py_True : Py_False))); - dict.setItem("AltDown", Py::Object((e->wasAltDown() ? Py_True : Py_False))); + dict.setItem("CtrlDown", Py::Object((e->wasCtrlDown() ? Py_True : Py_False))); + dict.setItem("AltDown", Py::Object((e->wasAltDown() ? Py_True : Py_False))); if (e->isOfType(SoButtonEvent::getClassTypeId())) { std::string state; const auto be = static_cast(e); @@ -1957,7 +2157,7 @@ void View3DInventorPy::eventCallback(void * ud, SoEventCallback * n) dict.setItem("Button", Py::String(button)); } - if (e->isOfType(SoMouseWheelEvent::getClassTypeId())){ + if (e->isOfType(SoMouseWheelEvent::getClassTypeId())) { const auto mwe = static_cast(e); dict.setItem("Delta", Py::Long(mwe->getDelta())); } @@ -2035,8 +2235,9 @@ Py::Object View3DInventorPy::addEventCallback(const Py::Tuple& args) { char* eventtype; PyObject* method; - if (!PyArg_ParseTuple(args.ptr(), "sO", &eventtype, &method)) + if (!PyArg_ParseTuple(args.ptr(), "sO", &eventtype, &method)) { throw Py::Exception(); + } try { if (PyCallable_Check(method) == 0) { throw Py::TypeError("object is not callable"); @@ -2049,7 +2250,11 @@ Py::Object View3DInventorPy::addEventCallback(const Py::Tuple& args) throw Py::TypeError(s_out.str()); } - getView3DInventorPtr()->getViewer()->addEventCallback(eventId, View3DInventorPy::eventCallback, method); + getView3DInventorPtr()->getViewer()->addEventCallback( + eventId, + View3DInventorPy::eventCallback, + method + ); callbacks.push_back(method); Py_INCREF(method); return Py::Callable(method, false); @@ -2063,8 +2268,9 @@ Py::Object View3DInventorPy::removeEventCallback(const Py::Tuple& args) { char* eventtype; PyObject* method; - if (!PyArg_ParseTuple(args.ptr(), "sO", &eventtype, &method)) + if (!PyArg_ParseTuple(args.ptr(), "sO", &eventtype, &method)) { throw Py::Exception(); + } try { if (PyCallable_Check(method) == 0) { throw Py::RuntimeError("object is not callable"); @@ -2077,7 +2283,11 @@ Py::Object View3DInventorPy::removeEventCallback(const Py::Tuple& args) throw Py::TypeError(s_out.str()); } - getView3DInventorPtr()->getViewer()->removeEventCallback(eventId, View3DInventorPy::eventCallback, method); + getView3DInventorPtr()->getViewer()->removeEventCallback( + eventId, + View3DInventorPy::eventCallback, + method + ); callbacks.remove(method); Py_DECREF(method); return Py::None(); @@ -2089,9 +2299,10 @@ Py::Object View3DInventorPy::removeEventCallback(const Py::Tuple& args) Py::Object View3DInventorPy::setAnnotation(const Py::Tuple& args) { - char *psAnnoName,*psBuffer; - if (!PyArg_ParseTuple(args.ptr(), "ss", &psAnnoName, &psBuffer)) + char *psAnnoName, *psBuffer; + if (!PyArg_ParseTuple(args.ptr(), "ss", &psAnnoName, &psBuffer)) { throw Py::Exception(); + } ViewProviderExtern* view = nullptr; try { view = new ViewProviderExtern(); @@ -2108,9 +2319,10 @@ Py::Object View3DInventorPy::setAnnotation(const Py::Tuple& args) Py::Object View3DInventorPy::removeAnnotation(const Py::Tuple& args) { - char *psAnnoName; - if (!PyArg_ParseTuple(args.ptr(), "s", &psAnnoName)) + char* psAnnoName; + if (!PyArg_ParseTuple(args.ptr(), "s", &psAnnoName)) { throw Py::Exception(); + } ViewProvider* view = nullptr; view = getView3DInventorPtr()->getGuiDocument()->getAnnotationViewProvider(psAnnoName); if (view) { @@ -2133,7 +2345,8 @@ Py::Object View3DInventorPy::getSceneGraph() return Py::None(); } PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoSeparator *", static_cast(scene), 1); + proxy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", "SoSeparator *", static_cast(scene), 1); scene->ref(); return Py::Object(proxy, true); } @@ -2148,7 +2361,7 @@ Py::Object View3DInventorPy::getViewer() return Py::Object(viewer->getPyObject(), true); } -void View3DInventorPy::eventCallbackPivy(void * ud, SoEventCallback * n) +void View3DInventorPy::eventCallbackPivy(void* ud, SoEventCallback* n) { Base::PyGILStateLocker lock; const SoEvent* e = n->getEvent(); @@ -2157,9 +2370,14 @@ void View3DInventorPy::eventCallbackPivy(void * ud, SoEventCallback * n) PyObject* proxy = nullptr; try { - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", type.c_str(), const_cast(static_cast(e)), 0); + proxy = Base::Interpreter().createSWIGPointerObj( + "pivy.coin", + type.c_str(), + const_cast(static_cast(e)), + 0 + ); // now run the method - Py::Object event(proxy,true); + Py::Object event(proxy, true); Py::Callable method(static_cast(ud)); Py::Tuple args(1); args.setItem(0, event); @@ -2183,16 +2401,17 @@ void View3DInventorPy::eventCallbackPivy(void * ud, SoEventCallback * n) } } -void View3DInventorPy::eventCallbackPivyEx(void * ud, SoEventCallback * n) +void View3DInventorPy::eventCallbackPivyEx(void* ud, SoEventCallback* n) { Base::PyGILStateLocker lock; std::string type = "SoEventCallback *"; PyObject* proxy = nullptr; try { - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", type.c_str(), static_cast(n), 0); + proxy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", type.c_str(), static_cast(n), 0); // now run the method - Py::Object event(proxy,true); + Py::Object event(proxy, true); Py::Callable method(reinterpret_cast(ud)); Py::Tuple args(1); args.setItem(0, event); @@ -2220,9 +2439,10 @@ Py::Object View3DInventorPy::addEventCallbackPivy(const Py::Tuple& args) { PyObject* proxy; PyObject* method; - int ex=1; // if 1, use eventCallbackPivyEx - if (!PyArg_ParseTuple(args.ptr(), "OO|i", &proxy, &method,&ex)) + int ex = 1; // if 1, use eventCallbackPivyEx + if (!PyArg_ParseTuple(args.ptr(), "OO|i", &proxy, &method, &ex)) { throw Py::Exception(); + } void* ptr = nullptr; try { @@ -2248,9 +2468,8 @@ Py::Object View3DInventorPy::addEventCallbackPivy(const Py::Tuple& args) throw Py::TypeError("object is not callable"); } - SoEventCallbackCB* callback = (ex == 1 ? - View3DInventorPy::eventCallbackPivyEx : - View3DInventorPy::eventCallbackPivy); + SoEventCallbackCB* callback + = (ex == 1 ? View3DInventorPy::eventCallbackPivyEx : View3DInventorPy::eventCallbackPivy); getView3DInventorPtr()->getViewer()->addEventCallback(*eventId, callback, method); callbacks.push_back(method); Py_INCREF(method); @@ -2265,9 +2484,10 @@ Py::Object View3DInventorPy::removeEventCallbackPivy(const Py::Tuple& args) { PyObject* proxy; PyObject* method; - int ex=1; // if 1, use eventCallbackPivyEx - if (!PyArg_ParseTuple(args.ptr(), "OO|i", &proxy, &method,&ex)) + int ex = 1; // if 1, use eventCallbackPivyEx + if (!PyArg_ParseTuple(args.ptr(), "OO|i", &proxy, &method, &ex)) { throw Py::Exception(); + } void* ptr = nullptr; try { @@ -2293,9 +2513,8 @@ Py::Object View3DInventorPy::removeEventCallbackPivy(const Py::Tuple& args) throw Py::TypeError("object is not callable"); } - SoEventCallbackCB* callback = (ex == 1 ? - View3DInventorPy::eventCallbackPivyEx : - View3DInventorPy::eventCallbackPivy); + SoEventCallbackCB* callback + = (ex == 1 ? View3DInventorPy::eventCallbackPivyEx : View3DInventorPy::eventCallbackPivy); getView3DInventorPtr()->getViewer()->removeEventCallback(*eventId, callback, method); callbacks.remove(method); Py_DECREF(method); @@ -2309,9 +2528,10 @@ Py::Object View3DInventorPy::removeEventCallbackPivy(const Py::Tuple& args) Py::Object View3DInventorPy::setAxisCross(const Py::Tuple& args) { int ok; - if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) + if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) { throw Py::Exception(); - getView3DInventorPtr()->getViewer()->setAxisCross(ok!=0); + } + getView3DInventorPtr()->getViewer()->setAxisCross(ok != 0); return Py::None(); } @@ -2321,14 +2541,15 @@ Py::Object View3DInventorPy::hasAxisCross() return Py::Boolean(ok ? true : false); } -void View3DInventorPy::draggerCallback(void * ud, SoDragger* n) +void View3DInventorPy::draggerCallback(void* ud, SoDragger* n) { Base::PyGILStateLocker lock; PyObject* proxy = nullptr; try { - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoDragger *", static_cast(n), 0); - //call the method - Py::Object dragger(proxy,true); + proxy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", "SoDragger *", static_cast(n), 0); + // call the method + Py::Object dragger(proxy, true); Py::Callable method(reinterpret_cast(ud)); Py::Tuple args(1); args.setItem(0, dragger); @@ -2357,11 +2578,12 @@ Py::Object View3DInventorPy::addDraggerCallback(const Py::Tuple& args) PyObject* dragger; char* type; PyObject* method; - if (!PyArg_ParseTuple(args.ptr(), "OsO", &dragger,&type, &method)) + if (!PyArg_ParseTuple(args.ptr(), "OsO", &dragger, &type, &method)) { throw Py::Exception(); + } - //Check if dragger is a SoDragger object and cast + // Check if dragger is a SoDragger object and cast void* ptr = nullptr; try { Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoDragger *", dragger, &ptr, 0); @@ -2374,23 +2596,23 @@ Py::Object View3DInventorPy::addDraggerCallback(const Py::Tuple& args) } auto drag = static_cast(ptr); - //Check if method is callable + // Check if method is callable if (PyCallable_Check(method) == 0) { throw Py::TypeError("the method is not callable"); } try { - if (strcmp(type,"addFinishCallback")==0) { - drag->addFinishCallback(draggerCallback,method); + if (strcmp(type, "addFinishCallback") == 0) { + drag->addFinishCallback(draggerCallback, method); } - else if (strcmp(type,"addStartCallback")==0) { - drag->addStartCallback(draggerCallback,method); + else if (strcmp(type, "addStartCallback") == 0) { + drag->addStartCallback(draggerCallback, method); } - else if (strcmp(type,"addMotionCallback")==0) { - drag->addMotionCallback(draggerCallback,method); + else if (strcmp(type, "addMotionCallback") == 0) { + drag->addMotionCallback(draggerCallback, method); } - else if (strcmp(type,"addValueChangedCallback")==0) { - drag->addValueChangedCallback(draggerCallback,method); + else if (strcmp(type, "addValueChangedCallback") == 0) { + drag->addValueChangedCallback(draggerCallback, method); } else { std::string s; @@ -2413,10 +2635,11 @@ Py::Object View3DInventorPy::removeDraggerCallback(const Py::Tuple& args) PyObject* dragger; char* type; PyObject* method; - if (!PyArg_ParseTuple(args.ptr(), "OsO", &dragger, &type, &method)) + if (!PyArg_ParseTuple(args.ptr(), "OsO", &dragger, &type, &method)) { throw Py::Exception(); + } - //Check if dragger is a SoDragger object and cast + // Check if dragger is a SoDragger object and cast void* ptr = nullptr; try { Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoDragger *", dragger, &ptr, 0); @@ -2461,12 +2684,15 @@ Py::Object View3DInventorPy::removeDraggerCallback(const Py::Tuple& args) Py::Object View3DInventorPy::getViewProvidersOfType(const Py::Tuple& args) { char* name; - if (!PyArg_ParseTuple(args.ptr(), "s", &name)) + if (!PyArg_ParseTuple(args.ptr(), "s", &name)) { throw Py::Exception(); + } - std::vector vps = getView3DInventorPtr()->getViewer()->getViewProvidersOfType(Base::Type::fromName(name)); + std::vector vps = getView3DInventorPtr()->getViewer()->getViewProvidersOfType( + Base::Type::fromName(name) + ); Py::List list; - for (const auto & vp : vps) { + for (const auto& vp : vps) { list.append(Py::asObject(vp->getPyObject())); } @@ -2482,8 +2708,9 @@ Py::Object View3DInventorPy::redraw() Py::Object View3DInventorPy::setName(const Py::Tuple& args) { char* buffer; - if (!PyArg_ParseTuple(args.ptr(), "s", &buffer)) + if (!PyArg_ParseTuple(args.ptr(), "s", &buffer)) { throw Py::Exception(); + } try { getView3DInventorPtr()->setWindowTitle(QString::fromUtf8(buffer)); @@ -2495,29 +2722,44 @@ Py::Object View3DInventorPy::setName(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } Py::Object View3DInventorPy::toggleClippingPlane(const Py::Tuple& args, const Py::Dict& kwds) { - static const std::array keywords {"toggle", "beforeEditing", "noManip", "pla", nullptr}; + static const std::array keywords {"toggle", "beforeEditing", "noManip", "pla", nullptr}; int toggle = -1; - PyObject *beforeEditing = Py_False; - PyObject *noManip = Py_True; - PyObject *pyPla = Py_None; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "|iO!O!O!", keywords, - &toggle, &PyBool_Type, &beforeEditing, &PyBool_Type, &noManip, - &Base::PlacementPy::Type, &pyPla)) { + PyObject* beforeEditing = Py_False; + PyObject* noManip = Py_True; + PyObject* pyPla = Py_None; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "|iO!O!O!", + keywords, + &toggle, + &PyBool_Type, + &beforeEditing, + &PyBool_Type, + &noManip, + &Base::PlacementPy::Type, + &pyPla + )) { throw Py::Exception(); } Base::Placement pla; - if(pyPla!=Py_None) + if (pyPla != Py_None) { pla = *static_cast(pyPla)->getPlacementPtr(); - getView3DInventorPtr()->getViewer()->toggleClippingPlane(toggle, Base::asBoolean(beforeEditing), - Base::asBoolean(noManip), pla); + } + getView3DInventorPtr()->getViewer()->toggleClippingPlane( + toggle, + Base::asBoolean(beforeEditing), + Base::asBoolean(noManip), + pla + ); return Py::None(); } @@ -2536,10 +2778,12 @@ Py::Object View3DInventorPy::graphicsView() Py::Object View3DInventorPy::setCornerCrossVisible(const Py::Tuple& args) { int ok; - if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) + if (!PyArg_ParseTuple(args.ptr(), "i", &ok)) { throw Py::Exception(); - getView3DInventorPtr()->getViewer()->setFeedbackVisibility(ok!=0); - getView3DInventorPtr()->getViewer()->redraw(); // added because isViewing() returns False when focus is in Python Console + } + getView3DInventorPtr()->getViewer()->setFeedbackVisibility(ok != 0); + getView3DInventorPtr()->getViewer()->redraw(); // added because isViewing() returns False when + // focus is in Python Console return Py::None(); } @@ -2551,11 +2795,13 @@ Py::Object View3DInventorPy::isCornerCrossVisible() Py::Object View3DInventorPy::setCornerCrossSize(const Py::Tuple& args) { - int size=0; - if (!PyArg_ParseTuple(args.ptr(), "i", &size)) + int size = 0; + if (!PyArg_ParseTuple(args.ptr(), "i", &size)) { throw Py::Exception(); + } getView3DInventorPtr()->getViewer()->setFeedbackSize(size); - getView3DInventorPtr()->getViewer()->redraw(); // added because isViewing() returns False when focus is in Python Console + getView3DInventorPtr()->getViewer()->redraw(); // added because isViewing() returns False when + // focus is in Python Console return Py::None(); } diff --git a/src/Gui/View3DPy.h b/src/Gui/View3DPy.h index 0ddf4521f9..a1673530ed 100644 --- a/src/Gui/View3DPy.h +++ b/src/Gui/View3DPy.h @@ -31,23 +31,24 @@ class SoEventCallback; class SoDragger; class QImage; -namespace Gui { +namespace Gui +{ class View3DInventor; -class View3DInventorPy : public Py::PythonExtension +class View3DInventorPy: public Py::PythonExtension { public: using BaseType = Py::PythonExtension; - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods - explicit View3DInventorPy(View3DInventor *vi); + explicit View3DInventorPy(View3DInventor* vi); ~View3DInventorPy() override; View3DInventor* getView3DInventorPtr(); Py::Object repr() override; - Py::Object getattr(const char *) override; - int setattr(const char *, const Py::Object &) override; + Py::Object getattr(const char*) override; + int setattr(const char*, const Py::Object&) override; Py::Object cast_to_base(); Py::Object fitAll(const Py::Tuple&); @@ -117,7 +118,7 @@ public: Py::Object getViewProvidersOfType(const Py::Tuple&); Py::Object redraw(); Py::Object setName(const Py::Tuple&); - Py::Object toggleClippingPlane(const Py::Tuple& args, const Py::Dict &); + Py::Object toggleClippingPlane(const Py::Tuple& args, const Py::Dict&); Py::Object hasClippingPlane(); Py::Object graphicsView(); Py::Object setCornerCrossVisible(const Py::Tuple& args); @@ -127,22 +128,22 @@ public: private: void setDefaultCameraHeight(float); - static void eventCallback(void * ud, SoEventCallback * n); - static void eventCallbackPivy(void * ud, SoEventCallback * n); - static void eventCallbackPivyEx(void * ud, SoEventCallback * n); - static void draggerCallback(void * ud, SoDragger* dragger); + static void eventCallback(void* ud, SoEventCallback* n); + static void eventCallbackPivy(void* ud, SoEventCallback* n); + static void eventCallbackPivyEx(void* ud, SoEventCallback* n); + static void draggerCallback(void* ud, SoDragger* dragger); private: - using method_varargs_handler = PyObject* (*)(PyObject *_self, PyObject *_args); + using method_varargs_handler = PyObject* (*)(PyObject * _self, PyObject* _args); static method_varargs_handler pycxx_handler; - static PyObject *method_varargs_ext_handler(PyObject *_self, PyObject *_args); - Py::Object getattribute(const char *); + static PyObject* method_varargs_ext_handler(PyObject* _self, PyObject* _args); + Py::Object getattribute(const char*); private: Gui::MDIViewPy base; std::list callbacks; }; -} // namespace Gui +} // namespace Gui -#endif //GUI_VIEW3DPY_H +#endif // GUI_VIEW3DPY_H diff --git a/src/Gui/View3DSettings.cpp b/src/Gui/View3DSettings.cpp index 5fc20ec315..f8181b04ec 100644 --- a/src/Gui/View3DSettings.cpp +++ b/src/Gui/View3DSettings.cpp @@ -21,11 +21,10 @@ ***************************************************************************/ - -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -41,18 +40,16 @@ using namespace Gui; -View3DSettings::View3DSettings(ParameterGrp::handle hGrp, - View3DInventorViewer* view) +View3DSettings::View3DSettings(ParameterGrp::handle hGrp, View3DInventorViewer* view) : hGrp(hGrp) , hLightSourcesGrp(hGrp->GetGroup("LightSources")) - , _viewers{view} + , _viewers {view} { hGrp->Attach(this); hLightSourcesGrp->Attach(this); } -View3DSettings::View3DSettings(ParameterGrp::handle hGrp, - const std::vector& view) +View3DSettings::View3DSettings(ParameterGrp::handle hGrp, const std::vector& view) : hGrp(hGrp) , hLightSourcesGrp(hGrp->GetGroup("LightSources")) , _viewers(view) @@ -76,44 +73,44 @@ int View3DSettings::stopAnimatingIfDeactivated() const void View3DSettings::applySettings() { // apply the user settings - OnChange(*hGrp,"EyeDistance"); - OnChange(*hGrp,"CornerCoordSystem"); - OnChange(*hGrp,"CornerCoordSystemSize"); - OnChange(*hGrp,"AxisLetterColor"); - OnChange(*hGrp,"ShowAxisCross"); - OnChange(*hGrp,"UseNavigationAnimations"); - OnChange(*hGrp,"UseSpinningAnimations"); - OnChange(*hGrp,"Gradient"); - OnChange(*hGrp,"RadialGradient"); - OnChange(*hGrp,"BackgroundColor"); - OnChange(*hGrp,"BackgroundColor2"); - OnChange(*hGrp,"BackgroundColor3"); - OnChange(*hGrp,"BackgroundColor4"); - OnChange(*hGrp,"UseBackgroundColorMid"); - OnChange(*hGrp,"ShowFPS"); - OnChange(*hGrp,"ShowNaviCube"); - OnChange(*hGrp,"AxisXColor"); - OnChange(*hGrp,"AxisYColor"); - OnChange(*hGrp,"AxisZColor"); - OnChange(*hGrp,"UseVBO"); - OnChange(*hGrp,"RenderCache"); - OnChange(*hGrp,"Orthographic"); + OnChange(*hGrp, "EyeDistance"); + OnChange(*hGrp, "CornerCoordSystem"); + OnChange(*hGrp, "CornerCoordSystemSize"); + OnChange(*hGrp, "AxisLetterColor"); + OnChange(*hGrp, "ShowAxisCross"); + OnChange(*hGrp, "UseNavigationAnimations"); + OnChange(*hGrp, "UseSpinningAnimations"); + OnChange(*hGrp, "Gradient"); + OnChange(*hGrp, "RadialGradient"); + OnChange(*hGrp, "BackgroundColor"); + OnChange(*hGrp, "BackgroundColor2"); + OnChange(*hGrp, "BackgroundColor3"); + OnChange(*hGrp, "BackgroundColor4"); + OnChange(*hGrp, "UseBackgroundColorMid"); + OnChange(*hGrp, "ShowFPS"); + OnChange(*hGrp, "ShowNaviCube"); + OnChange(*hGrp, "AxisXColor"); + OnChange(*hGrp, "AxisYColor"); + OnChange(*hGrp, "AxisZColor"); + OnChange(*hGrp, "UseVBO"); + OnChange(*hGrp, "RenderCache"); + OnChange(*hGrp, "Orthographic"); auto lightSourcesGrp = hGrp->GetGroup("LightSources"); - OnChange(*lightSourcesGrp,"EnableHeadlight"); - OnChange(*lightSourcesGrp,"HeadlightColor"); - OnChange(*lightSourcesGrp,"HeadlightDirection"); - OnChange(*lightSourcesGrp,"HeadlightIntensity"); - OnChange(*lightSourcesGrp,"EnableBacklight"); - OnChange(*lightSourcesGrp,"BacklightColor"); - OnChange(*lightSourcesGrp,"BacklightDirection"); - OnChange(*lightSourcesGrp,"BacklightIntensity"); - OnChange(*lightSourcesGrp,"EnableFillLight"); - OnChange(*lightSourcesGrp,"FillLightColor"); - OnChange(*lightSourcesGrp,"FillLightDirection"); - OnChange(*lightSourcesGrp,"FillLightIntensity"); - OnChange(*lightSourcesGrp,"AmbientLightColor"); - OnChange(*lightSourcesGrp,"AmbientLightIntensity"); + OnChange(*lightSourcesGrp, "EnableHeadlight"); + OnChange(*lightSourcesGrp, "HeadlightColor"); + OnChange(*lightSourcesGrp, "HeadlightDirection"); + OnChange(*lightSourcesGrp, "HeadlightIntensity"); + OnChange(*lightSourcesGrp, "EnableBacklight"); + OnChange(*lightSourcesGrp, "BacklightColor"); + OnChange(*lightSourcesGrp, "BacklightDirection"); + OnChange(*lightSourcesGrp, "BacklightIntensity"); + OnChange(*lightSourcesGrp, "EnableFillLight"); + OnChange(*lightSourcesGrp, "FillLightColor"); + OnChange(*lightSourcesGrp, "FillLightDirection"); + OnChange(*lightSourcesGrp, "FillLightIntensity"); + OnChange(*lightSourcesGrp, "AmbientLightColor"); + OnChange(*lightSourcesGrp, "AmbientLightIntensity"); // Workaround // Clear old settings that was used for a while in 1.1dev @@ -138,28 +135,29 @@ void View3DSettings::applySettings() } // End of workaround - OnChange(*hGrp,"NavigationStyle"); - OnChange(*hGrp,"OrbitStyle"); - OnChange(*hGrp,"Sensitivity"); - OnChange(*hGrp,"ResetCursorPosition"); - OnChange(*hGrp,"DimensionsVisible"); - OnChange(*hGrp,"Dimensions3dVisible"); - OnChange(*hGrp,"DimensionsDeltaVisible"); - OnChange(*hGrp,"PickRadius"); - OnChange(*hGrp,"TransparentObjectRenderType"); + OnChange(*hGrp, "NavigationStyle"); + OnChange(*hGrp, "OrbitStyle"); + OnChange(*hGrp, "Sensitivity"); + OnChange(*hGrp, "ResetCursorPosition"); + OnChange(*hGrp, "DimensionsVisible"); + OnChange(*hGrp, "Dimensions3dVisible"); + OnChange(*hGrp, "DimensionsDeltaVisible"); + OnChange(*hGrp, "PickRadius"); + OnChange(*hGrp, "TransparentObjectRenderType"); } -void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason) +void View3DSettings::OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp::MessageType Reason) { const ParameterGrp& rGrp = static_cast(rCaller); - if (strcmp(Reason,"EnableHeadlight") == 0) { + if (strcmp(Reason, "EnableHeadlight") == 0) { bool enable = rGrp.GetBool("EnableHeadlight", true); for (auto _viewer : _viewers) { _viewer->setHeadlightEnabled(enable); } } - else if (strcmp(Reason,"HeadlightColor") == 0) { - unsigned long headlight = rGrp.GetUnsigned("HeadlightColor", 0xFFFFFFFF); // default color (white) + else if (strcmp(Reason, "HeadlightColor") == 0) { + unsigned long headlight = rGrp.GetUnsigned("HeadlightColor", 0xFFFFFFFF); // default color + // (white) float transparency; SbColor headlightColor; headlightColor.setPackedValue((uint32_t)headlight, transparency); @@ -167,7 +165,7 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M _viewer->getHeadlight()->color.setValue(headlightColor); } } - else if (strcmp(Reason,"HeadlightDirection") == 0) { + else if (strcmp(Reason, "HeadlightDirection") == 0) { try { std::string pos = rGrp.GetASCII("HeadlightDirection", defaultHeadLightDirection); if (!pos.empty()) { @@ -181,18 +179,18 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M // ignore exception } } - else if (strcmp(Reason,"HeadlightIntensity") == 0) { + else if (strcmp(Reason, "HeadlightIntensity") == 0) { long value = rGrp.GetInt("HeadlightIntensity", 90); for (auto _viewer : _viewers) { _viewer->getHeadlight()->intensity.setValue(Base::fromPercent(value)); } } - else if (strcmp(Reason,"EnableBacklight") == 0) { + else if (strcmp(Reason, "EnableBacklight") == 0) { for (auto _viewer : _viewers) { _viewer->setBacklightEnabled(rGrp.GetBool("EnableBacklight", true)); } } - else if (strcmp(Reason,"BacklightColor") == 0) { + else if (strcmp(Reason, "BacklightColor") == 0) { unsigned long backlight = rGrp.GetUnsigned("BacklightColor", 0xF5F5EEFF); float transparency; SbColor backlightColor; @@ -201,7 +199,7 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M _viewer->getBacklight()->color.setValue(backlightColor); } } - else if (strcmp(Reason,"BacklightDirection") == 0) { + else if (strcmp(Reason, "BacklightDirection") == 0) { try { std::string pos = rGrp.GetASCII("BacklightDirection", defaultBackLightDirection); if (!pos.empty()) { @@ -215,19 +213,20 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M // ignore exception } } - else if (strcmp(Reason,"BacklightIntensity") == 0) { + else if (strcmp(Reason, "BacklightIntensity") == 0) { long value = rGrp.GetInt("BacklightIntensity", 60); for (auto _viewer : _viewers) { _viewer->getBacklight()->intensity.setValue(Base::fromPercent(value)); } } - else if (strcmp(Reason,"EnableFillLight") == 0) { + else if (strcmp(Reason, "EnableFillLight") == 0) { for (auto _viewer : _viewers) { _viewer->setFillLightEnabled(rGrp.GetBool("EnableFillLight", true)); } } - else if (strcmp(Reason,"FillLightColor") == 0) { - unsigned long backlight = rGrp.GetUnsigned("FillLightColor", 0xE6FAFFFF); // default color (white) + else if (strcmp(Reason, "FillLightColor") == 0) { + unsigned long backlight = rGrp.GetUnsigned("FillLightColor", 0xE6FAFFFF); // default color + // (white) float transparency; SbColor backlightColor; backlightColor.setPackedValue((uint32_t)backlight, transparency); @@ -235,7 +234,7 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M _viewer->getFillLight()->color.setValue(backlightColor); } } - else if (strcmp(Reason,"FillLightDirection") == 0) { + else if (strcmp(Reason, "FillLightDirection") == 0) { try { std::string pos = rGrp.GetASCII("FillLightDirection", defaultFillLightDirection); if (!pos.empty()) { @@ -249,13 +248,13 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M // ignore exception } } - else if (strcmp(Reason,"FillLightIntensity") == 0) { + else if (strcmp(Reason, "FillLightIntensity") == 0) { long value = rGrp.GetInt("FillLightIntensity", 40); for (auto _viewer : _viewers) { _viewer->getFillLight()->intensity.setValue(Base::fromPercent(value)); } } - else if (strcmp(Reason,"AmbientLightColor") == 0) { + else if (strcmp(Reason, "AmbientLightColor") == 0) { unsigned long color = rGrp.GetUnsigned("AmbientLightColor", 0xFFFFFFFF); float transparency; SbColor backlightColor; @@ -264,129 +263,139 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M _viewer->getEnvironment()->ambientColor.setValue(backlightColor); } } - else if (strcmp(Reason,"AmbientLightIntensity") == 0) { + else if (strcmp(Reason, "AmbientLightIntensity") == 0) { long value = rGrp.GetInt("AmbientLightIntensity", 20); for (auto _viewer : _viewers) { _viewer->getEnvironment()->ambientIntensity.setValue(Base::fromPercent(value)); } } - else if (strcmp(Reason,"EnablePreselection") == 0) { + else if (strcmp(Reason, "EnablePreselection") == 0) { const ParameterGrp& rclGrp = ((ParameterGrp&)rCaller); SoFCEnablePreselectionAction cAct(rclGrp.GetBool("EnablePreselection", true)); for (auto _viewer : _viewers) { cAct.apply(_viewer->getSceneGraph()); } } - else if (strcmp(Reason,"EnableSelection") == 0) { + else if (strcmp(Reason, "EnableSelection") == 0) { const ParameterGrp& rclGrp = ((ParameterGrp&)rCaller); SoFCEnableSelectionAction cAct(rclGrp.GetBool("EnableSelection", true)); for (auto _viewer : _viewers) { cAct.apply(_viewer->getSceneGraph()); } } - else if (strcmp(Reason,"HighlightColor") == 0) { + else if (strcmp(Reason, "HighlightColor") == 0) { float transparency; SbColor highlightColor(0.8f, 0.1f, 0.1f); auto highlight = (unsigned long)(highlightColor.getPackedValue()); highlight = rGrp.GetUnsigned("HighlightColor", highlight); highlightColor.setPackedValue((uint32_t)highlight, transparency); - SoSFColor col; col.setValue(highlightColor); + SoSFColor col; + col.setValue(highlightColor); SoFCHighlightColorAction cAct(col); for (auto _viewer : _viewers) { cAct.apply(_viewer->getSceneGraph()); } } - else if (strcmp(Reason,"SelectionColor") == 0) { + else if (strcmp(Reason, "SelectionColor") == 0) { float transparency; SbColor selectionColor(0.1f, 0.8f, 0.1f); auto selection = (unsigned long)(selectionColor.getPackedValue()); selection = rGrp.GetUnsigned("SelectionColor", selection); selectionColor.setPackedValue((uint32_t)selection, transparency); - SoSFColor col; col.setValue(selectionColor); + SoSFColor col; + col.setValue(selectionColor); SoFCSelectionColorAction cAct(col); for (auto _viewer : _viewers) { cAct.apply(_viewer->getSceneGraph()); } } - else if (strcmp(Reason,"NavigationStyle") == 0) { + else if (strcmp(Reason, "NavigationStyle") == 0) { if (!ignoreNavigationStyle) { // check whether the simple or the full mouse model is used - std::string model = rGrp.GetASCII("NavigationStyle",CADNavigationStyle::getClassTypeId().getName()); + std::string model + = rGrp.GetASCII("NavigationStyle", CADNavigationStyle::getClassTypeId().getName()); Base::Type type = Base::Type::fromName(model.c_str()); for (auto _viewer : _viewers) { _viewer->setNavigationType(type); } } } - else if (strcmp(Reason,"OrbitStyle") == 0) { - int style = rGrp.GetInt("OrbitStyle",4); + else if (strcmp(Reason, "OrbitStyle") == 0) { + int style = rGrp.GetInt("OrbitStyle", 4); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setOrbitStyle(NavigationStyle::OrbitStyle(style)); } } - else if (strcmp(Reason,"Sensitivity") == 0) { - float val = rGrp.GetFloat("Sensitivity",2.0f); + else if (strcmp(Reason, "Sensitivity") == 0) { + float val = rGrp.GetFloat("Sensitivity", 2.0f); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setSensitivity(val); } } - else if (strcmp(Reason,"ResetCursorPosition") == 0) { - bool on = rGrp.GetBool("ResetCursorPosition",false); + else if (strcmp(Reason, "ResetCursorPosition") == 0) { + bool on = rGrp.GetBool("ResetCursorPosition", false); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setResetCursorPosition(on); } } - else if (strcmp(Reason,"InvertZoom") == 0) { + else if (strcmp(Reason, "InvertZoom") == 0) { bool on = rGrp.GetBool("InvertZoom", true); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setZoomInverted(on); } } - else if (strcmp(Reason,"ZoomAtCursor") == 0) { + else if (strcmp(Reason, "ZoomAtCursor") == 0) { bool on = rGrp.GetBool("ZoomAtCursor", true); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setZoomAtCursor(on); } } - else if (strcmp(Reason,"ZoomStep") == 0) { + else if (strcmp(Reason, "ZoomStep") == 0) { float val = rGrp.GetFloat("ZoomStep", 0.0f); for (auto _viewer : _viewers) { _viewer->navigationStyle()->setZoomStep(val); } } - else if (strcmp(Reason,"RotationMode") == 0) { + else if (strcmp(Reason, "RotationMode") == 0) { long mode = rGrp.GetInt("RotationMode", 1); for (auto _viewer : _viewers) { if (mode == 0) { - _viewer->navigationStyle()->setRotationCenterMode(NavigationStyle::RotationCenterMode::WindowCenter); + _viewer->navigationStyle()->setRotationCenterMode( + NavigationStyle::RotationCenterMode::WindowCenter + ); } else if (mode == 1) { - _viewer->navigationStyle()->setRotationCenterMode(NavigationStyle::RotationCenterMode::ScenePointAtCursor | - NavigationStyle::RotationCenterMode::FocalPointAtCursor); + _viewer->navigationStyle()->setRotationCenterMode( + NavigationStyle::RotationCenterMode::ScenePointAtCursor + | NavigationStyle::RotationCenterMode::FocalPointAtCursor + ); } else if (mode == 2) { - _viewer->navigationStyle()->setRotationCenterMode(NavigationStyle::RotationCenterMode::ScenePointAtCursor | - NavigationStyle::RotationCenterMode::BoundingBoxCenter); + _viewer->navigationStyle()->setRotationCenterMode( + NavigationStyle::RotationCenterMode::ScenePointAtCursor + | NavigationStyle::RotationCenterMode::BoundingBoxCenter + ); } } } - else if (strcmp(Reason,"EyeDistance") == 0) { + else if (strcmp(Reason, "EyeDistance") == 0) { for (auto _viewer : _viewers) { _viewer->getSoRenderManager()->setStereoOffset(rGrp.GetFloat("EyeDistance", 5.0)); } } - else if (strcmp(Reason,"CornerCoordSystem") == 0) { + else if (strcmp(Reason, "CornerCoordSystem") == 0) { for (auto _viewer : _viewers) { _viewer->setFeedbackVisibility(rGrp.GetBool("CornerCoordSystem", true)); } } - else if (strcmp(Reason,"CornerCoordSystemSize") == 0) { + else if (strcmp(Reason, "CornerCoordSystemSize") == 0) { for (auto _viewer : _viewers) { _viewer->setFeedbackSize(rGrp.GetInt("CornerCoordSystemSize", 10)); } } - else if (strcmp(Reason,"AxisLetterColor") == 0) { - unsigned long backlight = rGrp.GetUnsigned("AxisLetterColor", 0x00000000); // default color (black) + else if (strcmp(Reason, "AxisLetterColor") == 0) { + unsigned long backlight = rGrp.GetUnsigned("AxisLetterColor", 0x00000000); // default color + // (black) float transparency; SbColor color; color.setPackedValue((uint32_t)backlight, transparency); @@ -394,22 +403,22 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M _viewer->setAxisLetterColor(color); } } - else if (strcmp(Reason,"ShowAxisCross") == 0) { + else if (strcmp(Reason, "ShowAxisCross") == 0) { for (auto _viewer : _viewers) { _viewer->setAxisCross(rGrp.GetBool("ShowAxisCross", false)); } } - else if (strcmp(Reason,"UseNavigationAnimations") == 0) { + else if (strcmp(Reason, "UseNavigationAnimations") == 0) { for (auto _viewer : _viewers) { _viewer->setAnimationEnabled(rGrp.GetBool("UseNavigationAnimations", true)); } } - else if (strcmp(Reason,"UseSpinningAnimations") == 0) { + else if (strcmp(Reason, "UseSpinningAnimations") == 0) { for (auto _viewer : _viewers) { _viewer->setSpinningAnimationEnabled(rGrp.GetBool("UseSpinningAnimations", false)); } } - else if (strcmp(Reason,"Gradient") == 0 || strcmp(Reason,"RadialGradient") == 0) { + else if (strcmp(Reason, "Gradient") == 0 || strcmp(Reason, "RadialGradient") == 0) { View3DInventorViewer::Background background = View3DInventorViewer::Background::NoGradient; if (rGrp.GetBool("Gradient", true)) { background = View3DInventorViewer::Background::LinearGradient; @@ -421,36 +430,37 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M _viewer->setGradientBackground(background); } } - else if (strcmp(Reason,"ShowFPS") == 0) { + else if (strcmp(Reason, "ShowFPS") == 0) { for (auto _viewer : _viewers) { _viewer->setEnabledFPSCounter(rGrp.GetBool("ShowFPS", false)); } } - else if (strcmp(Reason,"ShowNaviCube") == 0) { + else if (strcmp(Reason, "ShowNaviCube") == 0) { for (auto _viewer : _viewers) { _viewer->setEnabledNaviCube(rGrp.GetBool("ShowNaviCube", true)); } } - else if (strcmp(Reason,"AxisXColor") == 0 || strcmp(Reason,"AxisYColor") == 0 || strcmp(Reason,"AxisZColor") == 0) { + else if (strcmp(Reason, "AxisXColor") == 0 || strcmp(Reason, "AxisYColor") == 0 + || strcmp(Reason, "AxisZColor") == 0) { for (auto _viewer : _viewers) { _viewer->updateColors(); } } - else if (strcmp(Reason,"UseVBO") == 0) { + else if (strcmp(Reason, "UseVBO") == 0) { if (!ignoreVBO) { for (auto _viewer : _viewers) { _viewer->setEnabledVBO(rGrp.GetBool("UseVBO", false)); } } } - else if (strcmp(Reason,"RenderCache") == 0) { + else if (strcmp(Reason, "RenderCache") == 0) { if (!ignoreRenderCache) { for (auto _viewer : _viewers) { _viewer->setRenderCache(rGrp.GetInt("RenderCache", 0)); } } } - else if (strcmp(Reason,"Orthographic") == 0) { + else if (strcmp(Reason, "Orthographic") == 0) { // check whether a perspective or orthogrphic camera should be set if (rGrp.GetBool("Orthographic", true)) { for (auto _viewer : _viewers) { @@ -515,39 +525,52 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M long renderType = rGrp.GetInt("TransparentObjectRenderType", 0); if (renderType == 0) { for (auto _viewer : _viewers) { - _viewer->getSoRenderManager()->getGLRenderAction() - ->setTransparentDelayedObjectRenderType(SoGLRenderAction::ONE_PASS); + _viewer->getSoRenderManager() + ->getGLRenderAction() + ->setTransparentDelayedObjectRenderType(SoGLRenderAction::ONE_PASS); } } else if (renderType == 1) { for (auto _viewer : _viewers) { - _viewer->getSoRenderManager()->getGLRenderAction() - ->setTransparentDelayedObjectRenderType(SoGLRenderAction:: - NONSOLID_SEPARATE_BACKFACE_PASS); + _viewer->getSoRenderManager()->getGLRenderAction()->setTransparentDelayedObjectRenderType( + SoGLRenderAction::NONSOLID_SEPARATE_BACKFACE_PASS + ); } } } } else { - unsigned long col1 = rGrp.GetUnsigned("BackgroundColor",3940932863UL); - unsigned long col2 = rGrp.GetUnsigned("BackgroundColor2",859006463UL); // default color (dark blue) - unsigned long col3 = rGrp.GetUnsigned("BackgroundColor3",2880160255UL); // default color (blue/grey) - unsigned long col4 = rGrp.GetUnsigned("BackgroundColor4",1869583359UL); // default color (blue/grey) - float r1,g1,b1,r2,g2,b2,r3,g3,b3,r4,g4,b4; - r1 = ((col1 >> 24) & 0xff) / 255.0; g1 = ((col1 >> 16) & 0xff) / 255.0; b1 = ((col1 >> 8) & 0xff) / 255.0; - r2 = ((col2 >> 24) & 0xff) / 255.0; g2 = ((col2 >> 16) & 0xff) / 255.0; b2 = ((col2 >> 8) & 0xff) / 255.0; - r3 = ((col3 >> 24) & 0xff) / 255.0; g3 = ((col3 >> 16) & 0xff) / 255.0; b3 = ((col3 >> 8) & 0xff) / 255.0; - r4 = ((col4 >> 24) & 0xff) / 255.0; g4 = ((col4 >> 16) & 0xff) / 255.0; b4 = ((col4 >> 8) & 0xff) / 255.0; + unsigned long col1 = rGrp.GetUnsigned("BackgroundColor", 3940932863UL); + unsigned long col2 = rGrp.GetUnsigned("BackgroundColor2", 859006463UL); // default color + // (dark blue) + unsigned long col3 = rGrp.GetUnsigned("BackgroundColor3", 2880160255UL); // default color + // (blue/grey) + unsigned long col4 = rGrp.GetUnsigned("BackgroundColor4", 1869583359UL); // default color + // (blue/grey) + float r1, g1, b1, r2, g2, b2, r3, g3, b3, r4, g4, b4; + r1 = ((col1 >> 24) & 0xff) / 255.0; + g1 = ((col1 >> 16) & 0xff) / 255.0; + b1 = ((col1 >> 8) & 0xff) / 255.0; + r2 = ((col2 >> 24) & 0xff) / 255.0; + g2 = ((col2 >> 16) & 0xff) / 255.0; + b2 = ((col2 >> 8) & 0xff) / 255.0; + r3 = ((col3 >> 24) & 0xff) / 255.0; + g3 = ((col3 >> 16) & 0xff) / 255.0; + b3 = ((col3 >> 8) & 0xff) / 255.0; + r4 = ((col4 >> 24) & 0xff) / 255.0; + g4 = ((col4 >> 16) & 0xff) / 255.0; + b4 = ((col4 >> 8) & 0xff) / 255.0; for (auto _viewer : _viewers) { _viewer->setBackgroundColor(QColor::fromRgbF(r1, g1, b1)); - if (!rGrp.GetBool("UseBackgroundColorMid",false)) { - _viewer->setGradientBackgroundColor(SbColor(r2, g2, b2), - SbColor(r3, g3, b3)); + if (!rGrp.GetBool("UseBackgroundColorMid", false)) { + _viewer->setGradientBackgroundColor(SbColor(r2, g2, b2), SbColor(r3, g3, b3)); } else { - _viewer->setGradientBackgroundColor(SbColor(r2, g2, b2), - SbColor(r3, g3, b3), - SbColor(r4, g4, b4)); + _viewer->setGradientBackgroundColor( + SbColor(r2, g2, b2), + SbColor(r3, g3, b3), + SbColor(r4, g4, b4) + ); } } } @@ -555,15 +578,15 @@ void View3DSettings::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M // ---------------------------------------------------------------------------- -NaviCubeSettings::NaviCubeSettings(ParameterGrp::handle hGrp, - View3DInventorViewer* view) +NaviCubeSettings::NaviCubeSettings(ParameterGrp::handle hGrp, View3DInventorViewer* view) : hGrp(hGrp) , _viewer(view) { connectParameterChanged = hGrp->Manager()->signalParamChanged.connect( - [this](ParameterGrp*, ParameterGrp::ParamType, const char *Name, const char *) { + [this](ParameterGrp*, ParameterGrp::ParamType, const char* Name, const char*) { parameterChanged(Name); - }); + } + ); } NaviCubeSettings::~NaviCubeSettings() @@ -577,7 +600,7 @@ void NaviCubeSettings::applySettings() parameterChanged("EmphaseColor"); parameterChanged("HiliteColor"); parameterChanged("CornerNaviCube"); - parameterChanged("OffsetX"); // Updates OffsetY too + parameterChanged("OffsetX"); // Updates OffsetY too parameterChanged("CubeSize"); parameterChanged("ChamferSize"); parameterChanged("NaviRotateToNearest"); @@ -589,13 +612,14 @@ void NaviCubeSettings::applySettings() parameterChanged("FontStretch"); parameterChanged("ShowCS"); parameterChanged("InactiveOpacity"); - parameterChanged("TextFront"); // Updates all labels + parameterChanged("TextFront"); // Updates all labels } void NaviCubeSettings::parameterChanged(const char* Name) { - if (Name == nullptr) + if (Name == nullptr) { return; + } NaviCube* nc = _viewer->getNaviCube(); if (strcmp(Name, "CornerNaviCube") == 0) { nc->setCorner(static_cast(hGrp->GetInt("CornerNaviCube", 1))); diff --git a/src/Gui/View3DViewerPy.cpp b/src/Gui/View3DViewerPy.cpp index 25ef1f424d..8f12149fe7 100644 --- a/src/Gui/View3DViewerPy.cpp +++ b/src/Gui/View3DViewerPy.cpp @@ -20,8 +20,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include #include @@ -45,96 +45,178 @@ void View3DInventorViewerPy::init_type() behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("getSoRenderManager",&View3DInventorViewerPy::getSoRenderManager,"getSoRenderManager() -> SoRenderManager\n" + add_varargs_method( + "getSoRenderManager", + &View3DInventorViewerPy::getSoRenderManager, + "getSoRenderManager() -> SoRenderManager\n" "Returns the render manager which is used to handle everything related to\n" "rendering the scene graph. It can be used to get full control over the\n" "render process\n" ); - add_varargs_method("getSoEventManager",&View3DInventorViewerPy::getSoEventManager,"getSoEventManager() -> SoEventManager\n" + add_varargs_method( + "getSoEventManager", + &View3DInventorViewerPy::getSoEventManager, + "getSoEventManager() -> SoEventManager\n" "Returns the event manager which is used to handle everything event related in\n" "the viewer. It can be used to change the event processing. This must however be\n" "done very carefully to not change the user interaction in an unpredictable manner.\n" ); - add_varargs_method("getSceneGraph", &View3DInventorViewerPy::getSceneGraph, "getSceneGraph() -> SoNode"); + add_varargs_method( + "getSceneGraph", + &View3DInventorViewerPy::getSceneGraph, + "getSceneGraph() -> SoNode" + ); add_varargs_method("setSceneGraph", &View3DInventorViewerPy::setSceneGraph, "setSceneGraph(SoNode)"); - add_varargs_method("seekToPoint",&View3DInventorViewerPy::seekToPoint,"seekToPoint(tuple) -> None\n" - "Initiate a seek action towards the 3D intersection of the scene and the\n" - "ray from the screen coordinate's point and in the same direction as the\n" - "camera is pointing. If the tuple has two entries it is interpreted as the\n" - "screen coordinates xy and the intersection point with the scene is\n" - "calculated. If three entries are given it is interpreted as the intersection\n" - "point xyz and the seek is done towards this point" + add_varargs_method( + "seekToPoint", + &View3DInventorViewerPy::seekToPoint, + "seekToPoint(tuple) -> None\n" + "Initiate a seek action towards the 3D intersection of the scene and the\n" + "ray from the screen coordinate's point and in the same direction as the\n" + "camera is pointing. If the tuple has two entries it is interpreted as the\n" + "screen coordinates xy and the intersection point with the scene is\n" + "calculated. If three entries are given it is interpreted as the intersection\n" + "point xyz and the seek is done towards this point" ); - add_varargs_method("setFocalDistance",&View3DInventorViewerPy::setFocalDistance,"setFocalDistance(float) -> None\n"); - add_varargs_method("getFocalDistance",&View3DInventorViewerPy::getFocalDistance,"getFocalDistance() -> float\n"); - add_varargs_method("getPoint", &View3DInventorViewerPy::getPointOnFocalPlane, "Same as getPointOnFocalPlane"); - add_varargs_method("getPointOnFocalPlane", &View3DInventorViewerPy::getPointOnFocalPlane, "getPointOnFocalPlane(x, y) -> Base::Vector(x,y,z)"); - add_varargs_method("getPickRadius", &View3DInventorViewerPy::getPickRadius, - "getPickRadius(): returns radius of confusion in pixels for picking objects on screen (selection)."); - add_varargs_method("setPickRadius", &View3DInventorViewerPy::setPickRadius, - "setPickRadius(new_radius): sets radius of confusion in pixels for picking objects on screen (selection)."); - add_varargs_method("setupEditingRoot", &View3DInventorViewerPy::setupEditingRoot, + add_varargs_method( + "setFocalDistance", + &View3DInventorViewerPy::setFocalDistance, + "setFocalDistance(float) -> None\n" + ); + add_varargs_method( + "getFocalDistance", + &View3DInventorViewerPy::getFocalDistance, + "getFocalDistance() -> float\n" + ); + add_varargs_method( + "getPoint", + &View3DInventorViewerPy::getPointOnFocalPlane, + "Same as getPointOnFocalPlane" + ); + add_varargs_method( + "getPointOnFocalPlane", + &View3DInventorViewerPy::getPointOnFocalPlane, + "getPointOnFocalPlane(x, y) -> Base::Vector(x,y,z)" + ); + add_varargs_method( + "getPickRadius", + &View3DInventorViewerPy::getPickRadius, + "getPickRadius(): returns radius of confusion in pixels for picking objects on screen " + "(selection)." + ); + add_varargs_method( + "setPickRadius", + &View3DInventorViewerPy::setPickRadius, + "setPickRadius(new_radius): sets radius of confusion in pixels for picking objects on " + "screen (selection)." + ); + add_varargs_method( + "setupEditingRoot", + &View3DInventorViewerPy::setupEditingRoot, "setupEditingRoot(matrix=None): setup the editing ViewProvider's root node.\n" "All child coin nodes of the current editing ViewProvider will be transferred to\n" "an internal editing node of this viewer, with a new transformation node specified\n" "by 'matrix'. All ViewProviderLink to the editing ViewProvider will be temporary\n" - "hidden. Call resetEditingRoot() to restore everything back to normal"); - add_varargs_method("resetEditingRoot", &View3DInventorViewerPy::resetEditingRoot, - "resetEditingRoot(updateLinks=True): restore the editing ViewProvider's root node"); - add_varargs_method("setBackgroundColor", &View3DInventorViewerPy::setBackgroundColor, - "setBackgroundColor(r,g,b): sets the background color of the current viewer."); - add_varargs_method("setGradientBackground", &View3DInventorViewerPy::setGradientBackground, - "setGradientBackground(str): sets the background gradient of the current viewer."); - add_varargs_method("setGradientBackgroundColor", &View3DInventorViewerPy::setGradientBackgroundColor, - "setGradientBackgroundColor(tuple,tuple,[tuple]): sets the gradient colors of the current viewer."); - add_varargs_method("setRedirectToSceneGraph", &View3DInventorViewerPy::setRedirectToSceneGraph, - "setRedirectToSceneGraph(bool): enables or disables to redirect events directly to the scene graph."); - add_varargs_method("isRedirectedToSceneGraph", &View3DInventorViewerPy::isRedirectedToSceneGraph, - "isRedirectedToSceneGraph() -> bool: check whether event redirection is enabled."); - add_varargs_method("grabFramebuffer", &View3DInventorViewerPy::grabFramebuffer, - "grabFramebuffer() -> QImage: renders and returns a 32-bit RGB image of the framebuffer."); + "hidden. Call resetEditingRoot() to restore everything back to normal" + ); + add_varargs_method( + "resetEditingRoot", + &View3DInventorViewerPy::resetEditingRoot, + "resetEditingRoot(updateLinks=True): restore the editing ViewProvider's root node" + ); + add_varargs_method( + "setBackgroundColor", + &View3DInventorViewerPy::setBackgroundColor, + "setBackgroundColor(r,g,b): sets the background color of the current viewer." + ); + add_varargs_method( + "setGradientBackground", + &View3DInventorViewerPy::setGradientBackground, + "setGradientBackground(str): sets the background gradient of the current viewer." + ); + add_varargs_method( + "setGradientBackgroundColor", + &View3DInventorViewerPy::setGradientBackgroundColor, + "setGradientBackgroundColor(tuple,tuple,[tuple]): sets the gradient colors of the current " + "viewer." + ); + add_varargs_method( + "setRedirectToSceneGraph", + &View3DInventorViewerPy::setRedirectToSceneGraph, + "setRedirectToSceneGraph(bool): enables or disables to redirect events directly to the " + "scene graph." + ); + add_varargs_method( + "isRedirectedToSceneGraph", + &View3DInventorViewerPy::isRedirectedToSceneGraph, + "isRedirectedToSceneGraph() -> bool: check whether event redirection is enabled." + ); + add_varargs_method( + "grabFramebuffer", + &View3DInventorViewerPy::grabFramebuffer, + "grabFramebuffer() -> QImage: renders and returns a 32-bit RGB image of the framebuffer." + ); - add_varargs_method("setOverrideMode", &View3DInventorViewerPy::setOverrideMode, - "setOverrideMode(mode): sets the display override mode."); + add_varargs_method( + "setOverrideMode", + &View3DInventorViewerPy::setOverrideMode, + "setOverrideMode(mode): sets the display override mode." + ); - add_varargs_method("setEnabledNaviCube", &View3DInventorViewerPy::setEnabledNaviCube, - "setEnabledNaviCube(bool): enables or disables the navi cube of the viewer."); - add_varargs_method("isEnabledNaviCube", &View3DInventorViewerPy::isEnabledNaviCube, - "isEnabledNaviCube() -> bool: check whether the navi cube is enabled."); - add_varargs_method("setNaviCubeCorner", &View3DInventorViewerPy::setNaviCubeCorner, + add_varargs_method( + "setEnabledNaviCube", + &View3DInventorViewerPy::setEnabledNaviCube, + "setEnabledNaviCube(bool): enables or disables the navi cube of the viewer." + ); + add_varargs_method( + "isEnabledNaviCube", + &View3DInventorViewerPy::isEnabledNaviCube, + "isEnabledNaviCube() -> bool: check whether the navi cube is enabled." + ); + add_varargs_method( + "setNaviCubeCorner", + &View3DInventorViewerPy::setNaviCubeCorner, "setNaviCubeCorner(int): sets the corner where to show the navi cube:\n" - "0=top left, 1=top right, 2=bottom left, 3=bottom right"); + "0=top left, 1=top right, 2=bottom left, 3=bottom right" + ); - add_varargs_method("getNavigationStyle",&View3DInventorViewerPy::getNavigationStyle, - "getNavigationStyle() -> NavigationStyle\n" "Returns the current viewer navigation style class.\n" + add_varargs_method( + "getNavigationStyle", + &View3DInventorViewerPy::getNavigationStyle, + "getNavigationStyle() -> NavigationStyle\n" + "Returns the current viewer navigation style class.\n" ); } -View3DInventorViewerPy::View3DInventorViewerPy(View3DInventorViewer *vi) - : _viewer(vi) -{ -} +View3DInventorViewerPy::View3DInventorViewerPy(View3DInventorViewer* vi) + : _viewer(vi) +{} View3DInventorViewerPy::~View3DInventorViewerPy() { Base::PyGILStateLocker lock; - for (auto it : callbacks) + for (auto it : callbacks) { Py_DECREF(it); + } } Py::Object View3DInventorViewerPy::repr() { - if (!_viewer) + if (!_viewer) { throw Py::RuntimeError("Cannot print representation of deleted object"); + } return Py::String("View3DInventorViewer"); } View3DInventorViewerPy::method_varargs_handler View3DInventorViewerPy::pycxx_handler = nullptr; -PyObject *View3DInventorViewerPy::method_varargs_ext_handler(PyObject *_self_and_name_tuple, PyObject *_args) +PyObject* View3DInventorViewerPy::method_varargs_ext_handler( + PyObject* _self_and_name_tuple, + PyObject* _args +) { try { return pycxx_handler(_self_and_name_tuple, _args); @@ -145,12 +227,12 @@ PyObject *View3DInventorViewerPy::method_varargs_ext_handler(PyObject *_self_and catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } -Py::Object View3DInventorViewerPy::getattr(const char * attr) +Py::Object View3DInventorViewerPy::getattr(const char* attr) { if (!_viewer) { std::string s; @@ -162,15 +244,16 @@ Py::Object View3DInventorViewerPy::getattr(const char * attr) Py::Object obj = Py::PythonExtension::getattr(attr); if (PyCFunction_Check(obj.ptr())) { auto op = reinterpret_cast(obj.ptr()); - if (!pycxx_handler) + if (!pycxx_handler) { pycxx_handler = op->m_ml->ml_meth; + } op->m_ml->ml_meth = method_varargs_ext_handler; } return obj; } } -int View3DInventorViewerPy::setattr(const char * attr, const Py::Object & value) +int View3DInventorViewerPy::setattr(const char* attr, const Py::Object& value) { if (!_viewer) { std::string s; @@ -185,13 +268,19 @@ int View3DInventorViewerPy::setattr(const char * attr, const Py::Object & value) Py::Object View3DInventorViewerPy::getSoRenderManager(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { SoRenderManager* manager = _viewer->getSoRenderManager(); PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoRenderManager *", static_cast(manager), 0); + proxy = Base::Interpreter().createSWIGPointerObj( + "pivy.coin", + "SoRenderManager *", + static_cast(manager), + 0 + ); return Py::Object(proxy, true); } catch (const Base::Exception& e) { @@ -201,13 +290,15 @@ Py::Object View3DInventorViewerPy::getSoRenderManager(const Py::Tuple& args) Py::Object View3DInventorViewerPy::getSceneGraph(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { SoNode* scene = _viewer->getSceneGraph(); PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoSeparator *", static_cast(scene), 1); + proxy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", "SoSeparator *", static_cast(scene), 1); scene->ref(); return Py::Object(proxy, true); } @@ -219,8 +310,9 @@ Py::Object View3DInventorViewerPy::getSceneGraph(const Py::Tuple& args) Py::Object View3DInventorViewerPy::setSceneGraph(const Py::Tuple& args) { PyObject* proxy; - if (!PyArg_ParseTuple(args.ptr(), "O", &proxy)) + if (!PyArg_ParseTuple(args.ptr(), "O", &proxy)) { throw Py::Exception(); + } void* ptr = nullptr; try { @@ -239,13 +331,19 @@ Py::Object View3DInventorViewerPy::setSceneGraph(const Py::Tuple& args) Py::Object View3DInventorViewerPy::getSoEventManager(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { SoEventManager* manager = _viewer->getSoEventManager(); PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoEventManager *", static_cast(manager), 0); + proxy = Base::Interpreter().createSWIGPointerObj( + "pivy.coin", + "SoEventManager *", + static_cast(manager), + 0 + ); return Py::Object(proxy, true); } catch (const Base::Exception& e) { @@ -256,10 +354,11 @@ Py::Object View3DInventorViewerPy::getSoEventManager(const Py::Tuple& args) Py::Object View3DInventorViewerPy::seekToPoint(const Py::Tuple& args) { PyObject* object; - if (!PyArg_ParseTuple(args.ptr(), "O", &object)) + if (!PyArg_ParseTuple(args.ptr(), "O", &object)) { throw Py::Exception(); + } - try { + try { const Py::Tuple tuple(object); // If the 3d point is given @@ -268,14 +367,14 @@ Py::Object View3DInventorViewerPy::seekToPoint(const Py::Tuple& args) Py::Float y = tuple[1]; Py::Float z = tuple[2]; - SbVec3f hitpoint((float)x,(float)y,(float)z); + SbVec3f hitpoint((float)x, (float)y, (float)z); _viewer->seekToPoint(hitpoint); } else { Py::Long x(tuple[0]); Py::Long y(tuple[1]); - SbVec2s hitpoint ((long)x,(long)y); + SbVec2s hitpoint((long)x, (long)y); _viewer->seekToPoint(hitpoint); } @@ -289,16 +388,18 @@ Py::Object View3DInventorViewerPy::seekToPoint(const Py::Tuple& args) Py::Object View3DInventorViewerPy::setFocalDistance(const Py::Tuple& args) { float distance; - if (!PyArg_ParseTuple(args.ptr(), "f", &distance)) + if (!PyArg_ParseTuple(args.ptr(), "f", &distance)) { throw Py::Exception(); + } try { SoCamera* cam = _viewer->getSoRenderManager()->getCamera(); - if (cam) + if (cam) { cam->focalDistance.setValue(distance); + } } catch (const Py::Exception&) { - throw; // re-throw + throw; // re-throw } catch (const Base::Exception& e) { throw Py::RuntimeError(e.what()); @@ -306,7 +407,7 @@ Py::Object View3DInventorViewerPy::setFocalDistance(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } @@ -315,8 +416,9 @@ Py::Object View3DInventorViewerPy::setFocalDistance(const Py::Tuple& args) Py::Object View3DInventorViewerPy::getFocalDistance(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } try { double d = _viewer->getSoRenderManager()->getCamera()->focalDistance.getValue(); @@ -328,14 +430,14 @@ Py::Object View3DInventorViewerPy::getFocalDistance(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } Py::Object View3DInventorViewerPy::getPointOnFocalPlane(const Py::Tuple& args) { - short x,y; + short x, y; if (!PyArg_ParseTuple(args.ptr(), "hh", &x, &y)) { PyErr_Clear(); Py::Tuple t(args[0]); @@ -343,7 +445,7 @@ Py::Object View3DInventorViewerPy::getPointOnFocalPlane(const Py::Tuple& args) y = (int)Py::Long(t[1]); } try { - SbVec3f pt = _viewer->getPointOnFocalPlane(SbVec2s(x,y)); + SbVec3f pt = _viewer->getPointOnFocalPlane(SbVec2s(x, y)); return Py::Vector(Base::Vector3f(pt[0], pt[1], pt[2])); } catch (const Base::Exception& e) { @@ -356,8 +458,9 @@ Py::Object View3DInventorViewerPy::getPointOnFocalPlane(const Py::Tuple& args) Py::Object View3DInventorViewerPy::getPickRadius(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } double d = _viewer->getPickRadius(); return Py::Float(d); @@ -370,8 +473,10 @@ Py::Object View3DInventorViewerPy::setPickRadius(const Py::Tuple& args) throw Py::Exception(); } - if (r < 0.001){ - throw Py::ValueError(std::string("Pick radius is zero or negative; positive number is required.")); + if (r < 0.001) { + throw Py::ValueError( + std::string("Pick radius is zero or negative; positive number is required.") + ); } try { _viewer->setPickRadius(r); @@ -383,26 +488,27 @@ Py::Object View3DInventorViewerPy::setPickRadius(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } Py::Object View3DInventorViewerPy::setupEditingRoot(const Py::Tuple& args) { - PyObject *pynode = Py_None; - PyObject *pymat = Py_None; - if (!PyArg_ParseTuple(args.ptr(), "|OO!", &pynode,&Base::MatrixPy::Type,&pymat)) { + PyObject* pynode = Py_None; + PyObject* pymat = Py_None; + if (!PyArg_ParseTuple(args.ptr(), "|OO!", &pynode, &Base::MatrixPy::Type, &pymat)) { throw Py::Exception(); } - Base::Matrix4D *mat = nullptr; - if(pymat != Py_None) + Base::Matrix4D* mat = nullptr; + if (pymat != Py_None) { mat = static_cast(pymat)->getMatrixPtr(); + } try { - SoNode *node = nullptr; - if(pynode!=Py_None) { + SoNode* node = nullptr; + if (pynode != Py_None) { void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoNode *", pynode, &ptr, 0); if (!ptr) { @@ -410,7 +516,7 @@ Py::Object View3DInventorViewerPy::setupEditingRoot(const Py::Tuple& args) } node = static_cast(ptr); } - _viewer->setupEditingRoot(node,mat); + _viewer->setupEditingRoot(node, mat); return Py::None(); } catch (const Base::Exception& e) { @@ -420,14 +526,14 @@ Py::Object View3DInventorViewerPy::setupEditingRoot(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } Py::Object View3DInventorViewerPy::resetEditingRoot(const Py::Tuple& args) { - PyObject *updateLinks = Py_True; + PyObject* updateLinks = Py_True; if (!PyArg_ParseTuple(args.ptr(), "|O!", &PyBool_Type, &updateLinks)) { throw Py::Exception(); } @@ -442,7 +548,7 @@ Py::Object View3DInventorViewerPy::resetEditingRoot(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -472,7 +578,7 @@ Py::Object View3DInventorViewerPy::setGradientBackground(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -482,17 +588,23 @@ Py::Object View3DInventorViewerPy::setGradientBackgroundColor(const Py::Tuple& a PyObject* col1; PyObject* col2; PyObject* col3 = nullptr; - if (!PyArg_ParseTuple(args.ptr(), "O!O!|O!", - &PyTuple_Type, &col1, - &PyTuple_Type, &col2, - &PyTuple_Type, &col3)) { + if (!PyArg_ParseTuple( + args.ptr(), + "O!O!|O!", + &PyTuple_Type, + &col1, + &PyTuple_Type, + &col2, + &PyTuple_Type, + &col3 + )) { throw Py::Exception(); } auto tupleToColor = [](PyObject* col) { SbColor color; Py::Tuple tuple(col); - for (int i=0; i<3; i++) { + for (int i = 0; i < 3; i++) { color[i] = static_cast(Py::Float(tuple[i])); } @@ -517,7 +629,7 @@ Py::Object View3DInventorViewerPy::setGradientBackgroundColor(const Py::Tuple& a catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } @@ -548,32 +660,35 @@ Py::Object View3DInventorViewerPy::setBackgroundColor(const Py::Tuple& args) catch (const std::exception& e) { throw Py::RuntimeError(e.what()); } - catch(...) { + catch (...) { throw Py::RuntimeError("Unknown C++ exception"); } } Py::Object View3DInventorViewerPy::setRedirectToSceneGraph(const Py::Tuple& args) { - PyObject* m=Py_False; - if (!PyArg_ParseTuple(args.ptr(), "O!", &PyBool_Type, &m)) + PyObject* m = Py_False; + if (!PyArg_ParseTuple(args.ptr(), "O!", &PyBool_Type, &m)) { throw Py::Exception(); + } _viewer->setRedirectToSceneGraph(Base::asBoolean(m)); return Py::None(); } Py::Object View3DInventorViewerPy::isRedirectedToSceneGraph(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } bool ok = _viewer->isRedirectedToSceneGraph(); return Py::Boolean(ok); } Py::Object View3DInventorViewerPy::grabFramebuffer(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } QImage img = _viewer->grabFramebuffer(); PythonWrapper wrap; @@ -594,17 +709,19 @@ Py::Object View3DInventorViewerPy::setOverrideMode(const Py::Tuple& args) Py::Object View3DInventorViewerPy::setEnabledNaviCube(const Py::Tuple& args) { - PyObject* m=Py_False; - if (!PyArg_ParseTuple(args.ptr(), "O!", &PyBool_Type, &m)) + PyObject* m = Py_False; + if (!PyArg_ParseTuple(args.ptr(), "O!", &PyBool_Type, &m)) { throw Py::Exception(); + } _viewer->setEnabledNaviCube(Base::asBoolean(m)); return Py::None(); } Py::Object View3DInventorViewerPy::isEnabledNaviCube(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } bool ok = _viewer->isEnabledNaviCube(); return Py::Boolean(ok); } @@ -612,18 +729,21 @@ Py::Object View3DInventorViewerPy::isEnabledNaviCube(const Py::Tuple& args) Py::Object View3DInventorViewerPy::setNaviCubeCorner(const Py::Tuple& args) { int pos; - if (!PyArg_ParseTuple(args.ptr(), "i", &pos)) + if (!PyArg_ParseTuple(args.ptr(), "i", &pos)) { throw Py::Exception(); - if (pos < 0 || pos > 3) + } + if (pos < 0 || pos > 3) { throw Py::IndexError("Value out of range"); + } _viewer->setNaviCubeCorner(pos); return Py::None(); } Py::Object View3DInventorViewerPy::getNavigationStyle(const Py::Tuple& args) { - if (!PyArg_ParseTuple(args.ptr(), "")) + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } NavigationStyle* navigationStyle = _viewer->navigationStyle(); if (navigationStyle) { diff --git a/src/Gui/View3DViewerPy.h b/src/Gui/View3DViewerPy.h index c675fd64af..0d78b1be04 100644 --- a/src/Gui/View3DViewerPy.h +++ b/src/Gui/View3DViewerPy.h @@ -27,31 +27,32 @@ #include -namespace Gui { +namespace Gui +{ class View3DInventorViewer; /** * @brief Python interface for View3DInventorViewer * - * The interface does not offer all methods the c++ View3DInventorViewer counterpart has, respectively - * also not everything the QuarterWidget and the SoQtQuarterAdaptor offers. It only exposes - * methods with additional functionality in comparison to the View3DInventorPy class. Everything that - * can be done from there has no interface here. + * The interface does not offer all methods the c++ View3DInventorViewer counterpart has, + * respectively also not everything the QuarterWidget and the SoQtQuarterAdaptor offers. It only + * exposes methods with additional functionality in comparison to the View3DInventorPy class. + * Everything that can be done from there has no interface here. */ -class View3DInventorViewerPy : public Py::PythonExtension +class View3DInventorViewerPy: public Py::PythonExtension { public: - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods - explicit View3DInventorViewerPy(View3DInventorViewer *vi); + explicit View3DInventorViewerPy(View3DInventorViewer* vi); ~View3DInventorViewerPy() override; Py::Object repr() override; - Py::Object getattr(const char *) override; - int setattr(const char *, const Py::Object &) override; + Py::Object getattr(const char*) override; + int setattr(const char*, const Py::Object&) override; - //exposed methods + // exposed methods Py::Object getSoEventManager(const Py::Tuple&); Py::Object getSoRenderManager(const Py::Tuple&); Py::Object getSceneGraph(const Py::Tuple&); @@ -64,8 +65,8 @@ public: Py::Object getPickRadius(const Py::Tuple& args); Py::Object setPickRadius(const Py::Tuple& args); - Py::Object setupEditingRoot(const Py::Tuple &args); - Py::Object resetEditingRoot(const Py::Tuple &args); + Py::Object setupEditingRoot(const Py::Tuple& args); + Py::Object resetEditingRoot(const Py::Tuple& args); Py::Object setGradientBackground(const Py::Tuple& args); Py::Object setGradientBackgroundColor(const Py::Tuple& args); @@ -84,9 +85,9 @@ public: Py::Object getNavigationStyle(const Py::Tuple&); private: - using method_varargs_handler = PyObject* (*)(PyObject *_self, PyObject *_args); + using method_varargs_handler = PyObject* (*)(PyObject * _self, PyObject* _args); static method_varargs_handler pycxx_handler; - static PyObject *method_varargs_ext_handler(PyObject *_self, PyObject *_args); + static PyObject* method_varargs_ext_handler(PyObject* _self, PyObject* _args); private: std::list callbacks; @@ -94,6 +95,6 @@ private: friend class View3DInventorViewer; }; -} // namespace Gui +} // namespace Gui -#endif //GUI_VIEW3DPY_H +#endif // GUI_VIEW3DPY_H diff --git a/src/Gui/ViewParams.cpp b/src/Gui/ViewParams.cpp index 0c4206e409..bb0f4dfdaa 100644 --- a/src/Gui/ViewParams.cpp +++ b/src/Gui/ViewParams.cpp @@ -26,35 +26,37 @@ using namespace Gui; -ViewParams::ViewParams() { - handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); +ViewParams::ViewParams() +{ + handle = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); handle->Attach(this); #undef FC_VIEW_PARAM -#define FC_VIEW_PARAM(_name,_ctype,_type,_def) \ - _name = handle->Get##_type(#_name,_def); +#define FC_VIEW_PARAM(_name, _ctype, _type, _def) _name = handle->Get##_type(#_name, _def); FC_VIEW_PARAMS } ViewParams::~ViewParams() = default; -void ViewParams::OnChange(Base::Subject &, const char* sReason) { - if(!sReason) +void ViewParams::OnChange(Base::Subject&, const char* sReason) +{ + if (!sReason) { return; + } #undef FC_VIEW_PARAM -#define FC_VIEW_PARAM(_name,_ctype,_type,_def) \ - if(strcmp(sReason,#_name)==0) {\ - _name = handle->Get##_type(#_name,_def);\ - return;\ +#define FC_VIEW_PARAM(_name, _ctype, _type, _def) \ + if (strcmp(sReason, #_name) == 0) { \ + _name = handle->Get##_type(#_name, _def); \ + return; \ } FC_VIEW_PARAMS } -ViewParams *ViewParams::instance() { - static ViewParams *inst; - if(!inst) +ViewParams* ViewParams::instance() +{ + static ViewParams* inst; + if (!inst) { inst = new ViewParams; + } return inst; } - diff --git a/src/Gui/ViewParams.h b/src/Gui/ViewParams.h index faf266e932..ed561d1060 100644 --- a/src/Gui/ViewParams.h +++ b/src/Gui/ViewParams.h @@ -26,66 +26,75 @@ #include -namespace Gui { +namespace Gui +{ /** Convenient class to obtain view provider related parameters * * The parameters are under group "User parameter:BaseApp/Preferences/View" */ -class GuiExport ViewParams: public ParameterGrp::ObserverType { +class GuiExport ViewParams: public ParameterGrp::ObserverType +{ public: ViewParams(); ~ViewParams() override; - void OnChange(Base::Subject &, const char* sReason) override; - static ViewParams *instance(); + void OnChange(Base::Subject&, const char* sReason) override; + static ViewParams* instance(); - ParameterGrp::handle getHandle() { + ParameterGrp::handle getHandle() + { return handle; } #define FC_VIEW_PARAMS \ - FC_VIEW_PARAM(UseNewSelection,bool,Bool,true) \ - FC_VIEW_PARAM(UseSelectionRoot,bool,Bool,true) \ - FC_VIEW_PARAM(EnableSelection,bool,Bool,true) \ - FC_VIEW_PARAM(RenderCache,int,Int,0) \ - FC_VIEW_PARAM(RandomColor,bool,Bool,false) \ - FC_VIEW_PARAM(BoundingBoxColor,unsigned long,Unsigned,4294967295UL) \ - FC_VIEW_PARAM(AnnotationTextColor,unsigned long,Unsigned,4294967295UL) \ - FC_VIEW_PARAM(MarkerSize,int,Int,9) \ - FC_VIEW_PARAM(DefaultLinkColor,unsigned long,Unsigned,0x66FFFF00) \ - FC_VIEW_PARAM(DefaultShapeLineColor,unsigned long,Unsigned,421075455UL) \ - FC_VIEW_PARAM(DefaultShapeVertexColor,unsigned long,Unsigned,421075455UL) \ - FC_VIEW_PARAM(DefaultShapeColor,unsigned long,Unsigned,0xCCCCCC00) \ - FC_VIEW_PARAM(DefaultShapeTransparency,int,Int,0) \ - FC_VIEW_PARAM(DefaultShapeLineWidth,int,Int,2) \ - FC_VIEW_PARAM(DefaultShapePointSize,int,Int,2) \ - FC_VIEW_PARAM(CoinCycleCheck,bool,Bool,true) \ - FC_VIEW_PARAM(EnablePropertyViewForInactiveDocument,bool,Bool,true) \ - FC_VIEW_PARAM(ShowSelectionBoundingBox,bool,Bool,false) \ + FC_VIEW_PARAM(UseNewSelection, bool, Bool, true) \ + FC_VIEW_PARAM(UseSelectionRoot, bool, Bool, true) \ + FC_VIEW_PARAM(EnableSelection, bool, Bool, true) \ + FC_VIEW_PARAM(RenderCache, int, Int, 0) \ + FC_VIEW_PARAM(RandomColor, bool, Bool, false) \ + FC_VIEW_PARAM(BoundingBoxColor, unsigned long, Unsigned, 4294967295UL) \ + FC_VIEW_PARAM(AnnotationTextColor, unsigned long, Unsigned, 4294967295UL) \ + FC_VIEW_PARAM(MarkerSize, int, Int, 9) \ + FC_VIEW_PARAM(DefaultLinkColor, unsigned long, Unsigned, 0x66FFFF00) \ + FC_VIEW_PARAM(DefaultShapeLineColor, unsigned long, Unsigned, 421075455UL) \ + FC_VIEW_PARAM(DefaultShapeVertexColor, unsigned long, Unsigned, 421075455UL) \ + FC_VIEW_PARAM(DefaultShapeColor, unsigned long, Unsigned, 0xCCCCCC00) \ + FC_VIEW_PARAM(DefaultShapeTransparency, int, Int, 0) \ + FC_VIEW_PARAM(DefaultShapeLineWidth, int, Int, 2) \ + FC_VIEW_PARAM(DefaultShapePointSize, int, Int, 2) \ + FC_VIEW_PARAM(CoinCycleCheck, bool, Bool, true) \ + FC_VIEW_PARAM(EnablePropertyViewForInactiveDocument, bool, Bool, true) \ + FC_VIEW_PARAM(ShowSelectionBoundingBox, bool, Bool, false) \ FC_VIEW_PARAM(PropertyViewTimer, unsigned long, Unsigned, 100) \ - FC_VIEW_PARAM(AxisXColor,unsigned long,Unsigned,0xCC333300) \ - FC_VIEW_PARAM(AxisYColor,unsigned long,Unsigned,0x33CC3300) \ - FC_VIEW_PARAM(AxisZColor,unsigned long,Unsigned,0x3333CC00) \ - FC_VIEW_PARAM(OriginColor,unsigned long,Unsigned,0xFBD62900) \ - FC_VIEW_PARAM(NeutralColor,unsigned long,Unsigned,0xB3B38000) \ - FC_VIEW_PARAM(PlacementIndicatorScale,double,Float,40.0) \ - FC_VIEW_PARAM(DraggerScale,double,Float,0.03) \ - FC_VIEW_PARAM(DatumScale,double,Float,100.0) \ - FC_VIEW_PARAM(DatumPlaneSize,double,Float,62.0) \ - FC_VIEW_PARAM(DatumLineSize,double,Float,70.0) \ - FC_VIEW_PARAM(DatumTemporaryScaleFactor,double,Float,2.0) \ + FC_VIEW_PARAM(AxisXColor, unsigned long, Unsigned, 0xCC333300) \ + FC_VIEW_PARAM(AxisYColor, unsigned long, Unsigned, 0x33CC3300) \ + FC_VIEW_PARAM(AxisZColor, unsigned long, Unsigned, 0x3333CC00) \ + FC_VIEW_PARAM(OriginColor, unsigned long, Unsigned, 0xFBD62900) \ + FC_VIEW_PARAM(NeutralColor, unsigned long, Unsigned, 0xB3B38000) \ + FC_VIEW_PARAM(PlacementIndicatorScale, double, Float, 40.0) \ + FC_VIEW_PARAM(DraggerScale, double, Float, 0.03) \ + FC_VIEW_PARAM(DatumScale, double, Float, 100.0) \ + FC_VIEW_PARAM(DatumPlaneSize, double, Float, 62.0) \ + FC_VIEW_PARAM(DatumLineSize, double, Float, 70.0) \ + FC_VIEW_PARAM(DatumTemporaryScaleFactor, double, Float, 2.0) #undef FC_VIEW_PARAM -#define FC_VIEW_PARAM(_name,_ctype,_type,_def) \ - _ctype get##_name() const { return _name; }\ - void set##_name(_ctype _v) { handle->Set##_type(#_name,_v); _name=_v; } +#define FC_VIEW_PARAM(_name, _ctype, _type, _def) \ + _ctype get##_name() const \ + { \ + return _name; \ + } \ + void set##_name(_ctype _v) \ + { \ + handle->Set##_type(#_name, _v); \ + _name = _v; \ + } FC_VIEW_PARAMS private: #undef FC_VIEW_PARAM -#define FC_VIEW_PARAM(_name,_ctype,_type,_def) \ - _ctype _name; +#define FC_VIEW_PARAM(_name, _ctype, _type, _def) _ctype _name; FC_VIEW_PARAMS ParameterGrp::handle handle; @@ -93,6 +102,6 @@ private: #undef FC_VIEW_PARAM -} // namespace Gui +} // namespace Gui -#endif // GUI_VIEW_PARAMS_H +#endif // GUI_VIEW_PARAMS_H diff --git a/src/Gui/ViewProvider.cpp b/src/Gui/ViewProvider.cpp index cafe8df7ee..568f8403fd 100644 --- a/src/Gui/ViewProvider.cpp +++ b/src/Gui/ViewProvider.cpp @@ -21,19 +21,18 @@ ***************************************************************************/ - -# 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 @@ -67,23 +66,28 @@ using namespace std; using namespace Gui; -namespace Gui { +namespace Gui +{ -void coinRemoveAllChildren(SoGroup *group) { - if(!group) +void coinRemoveAllChildren(SoGroup* group) +{ + if (!group) { return; + } int count = group->getNumChildren(); - if(!count) + if (!count) { return; + } FC_TRACE("coin remove all children " << count); SbBool autonotify = group->enableNotify(FALSE); - for(;count>0;--count) - group->removeChild(count-1); + for (; count > 0; --count) { + group->removeChild(count - 1); + } group->enableNotify(autonotify); group->touch(); } -} // namespace Gui +} // namespace Gui //************************************************************************** //************************************************************************** @@ -111,7 +115,7 @@ ViewProvider::ViewProvider() pcModeSwitch = new SoSwitch(); pcModeSwitch->ref(); pcModeSwitch->setName("ModeSwitch"); - pcTransform = new SoFCTransform(); + pcTransform = new SoFCTransform(); pcTransform->ref(); pcRoot->addChild(pcTransform); pcRoot->addChild(pcModeSwitch); @@ -132,11 +136,12 @@ ViewProvider::~ViewProvider() pcRoot->unref(); pcTransform->unref(); pcModeSwitch->unref(); - if (pcAnnotation) + if (pcAnnotation) { pcAnnotation->unref(); + } } -ViewProvider *ViewProvider::startEditing(int ModNum) +ViewProvider* ViewProvider::startEditing(int ModNum) { try { if (setEdit(ModNum)) { @@ -183,15 +188,14 @@ void ViewProvider::setEditViewer(View3DInventorViewer*, int ModNum) } void ViewProvider::unsetEditViewer(View3DInventorViewer*) -{ -} +{} -bool ViewProvider::isUpdatesEnabled () const +bool ViewProvider::isUpdatesEnabled() const { return testStatus(UpdateData); } -void ViewProvider::setUpdatesEnabled (bool enable) +void ViewProvider::setUpdatesEnabled(bool enable) { setStatus(UpdateData, enable); } @@ -201,9 +205,9 @@ void highlight(const HighlightMode& high) Q_UNUSED(high); } -void ViewProvider::eventCallback(void * ud, SoEventCallback * node) +void ViewProvider::eventCallback(void* ud, SoEventCallback* node) { - const SoEvent * ev = node->getEvent(); + const SoEvent* ev = node->getEvent(); auto viewer = static_cast(node->getUserData()); auto self = static_cast(ud); assert(self); @@ -211,96 +215,107 @@ void ViewProvider::eventCallback(void * ud, SoEventCallback * node) try { // Keyboard events if (ev->getTypeId().isDerivedFrom(SoKeyboardEvent::getClassTypeId())) { - auto ke = static_cast(ev); + auto ke = static_cast(ev); const SbBool press = ke->getState() == SoButtonEvent::DOWN ? true : false; switch (ke->getKey()) { - case SoKeyboardEvent::ESCAPE: - if (self->keyPressed (press, ke->getKey())) { - node->setHandled(); - } - else if(QApplication::mouseButtons()==Qt::NoButton) { - // Because of a Coin bug (https://bitbucket.org/Coin3D/coin/pull-requests/119), - // FC may crash if user hits ESC to cancel while still - // holding the mouse button while using some SoDragger. - // Therefore, we shall ignore ESC while any mouse button is - // pressed, until this Coin bug is fixed. - if (!press) { - // react only on key release - // Let first selection mode terminate - Gui::Document* doc = Gui::Application::Instance->activeDocument(); - const auto view = qobject_cast(doc->getActiveView()); - if (view) { - Gui::View3DInventorViewer* viewer = view->getViewer(); - if (viewer->isSelecting()) { - return; - } - } - - DockWindowManager* pDockMgr = DockWindowManager::instance(); - if (QWidget* widget = pDockMgr->getDockWindow("Tasks")) { - auto* ev = new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); - qApp->postEvent(widget, ev); - } - - auto func = new Gui::TimerFunction(); - func->setAutoDelete(true); - func->setFunction([doc]() { - doc->resetEdit(); - }); - func->singleShot(0); + case SoKeyboardEvent::ESCAPE: + if (self->keyPressed(press, ke->getKey())) { + node->setHandled(); } - } - else if (press) { - FC_WARN("Release all mouse buttons before exiting editing"); - } - break; - default: - // call the virtual method - if (self->keyPressed (press, ke->getKey())) - node->setHandled(); - break; + else if (QApplication::mouseButtons() == Qt::NoButton) { + // Because of a Coin bug + // (https://bitbucket.org/Coin3D/coin/pull-requests/119), FC may crash if + // user hits ESC to cancel while still holding the mouse button while using + // some SoDragger. Therefore, we shall ignore ESC while any mouse button is + // pressed, until this Coin bug is fixed. + if (!press) { + // react only on key release + // Let first selection mode terminate + Gui::Document* doc = Gui::Application::Instance->activeDocument(); + const auto view = qobject_cast(doc->getActiveView()); + if (view) { + Gui::View3DInventorViewer* viewer = view->getViewer(); + if (viewer->isSelecting()) { + return; + } + } + + DockWindowManager* pDockMgr = DockWindowManager::instance(); + if (QWidget* widget = pDockMgr->getDockWindow("Tasks")) { + auto* ev + = new QKeyEvent(QEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); + qApp->postEvent(widget, ev); + } + + auto func = new Gui::TimerFunction(); + func->setAutoDelete(true); + func->setFunction([doc]() { doc->resetEdit(); }); + func->singleShot(0); + } + } + else if (press) { + FC_WARN("Release all mouse buttons before exiting editing"); + } + break; + default: + // call the virtual method + if (self->keyPressed(press, ke->getKey())) { + node->setHandled(); + } + break; } } // switching the mouse buttons else if (ev->getTypeId().isDerivedFrom(SoMouseButtonEvent::getClassTypeId())) { - const auto event = (const SoMouseButtonEvent *) ev; + const auto event = (const SoMouseButtonEvent*)ev; const int button = event->getButton(); const SbBool press = event->getState() == SoButtonEvent::DOWN ? true : false; // call the virtual method - if (self->mouseButtonPressed(button,press,ev->getPosition(),viewer)) + if (self->mouseButtonPressed(button, press, ev->getPosition(), viewer)) { node->setHandled(); + } } else if (ev->getTypeId().isDerivedFrom(SoMouseWheelEvent::getClassTypeId())) { - const auto event = (const SoMouseWheelEvent *) ev; + const auto event = (const SoMouseWheelEvent*)ev; - if (self->mouseWheelEvent(event->getDelta(), event->getPosition(), viewer)) + if (self->mouseWheelEvent(event->getDelta(), event->getPosition(), viewer)) { node->setHandled(); + } } // Mouse Movement handling else if (ev->getTypeId().isDerivedFrom(SoLocation2Event::getClassTypeId())) { - if (self->mouseMove(ev->getPosition(),viewer)) + if (self->mouseMove(ev->getPosition(), viewer)) { node->setHandled(); + } } } catch (const Base::Exception& e) { - Base::Console().error("Unhandled exception in ViewProvider::eventCallback: %s\n" - "(Event type: %s, object type: %s)\n" - , e.what(), ev->getTypeId().getName().getString() - , self->getTypeId().getName()); + Base::Console().error( + "Unhandled exception in ViewProvider::eventCallback: %s\n" + "(Event type: %s, object type: %s)\n", + e.what(), + ev->getTypeId().getName().getString(), + self->getTypeId().getName() + ); } catch (const std::exception& e) { - Base::Console().error("Unhandled std exception in ViewProvider::eventCallback: %s\n" - "(Event type: %s, object type: %s)\n" - , e.what(), ev->getTypeId().getName().getString() - , self->getTypeId().getName()); + Base::Console().error( + "Unhandled std exception in ViewProvider::eventCallback: %s\n" + "(Event type: %s, object type: %s)\n", + e.what(), + ev->getTypeId().getName().getString(), + self->getTypeId().getName() + ); } catch (...) { - Base::Console().error("Unhandled unknown C++ exception in ViewProvider::eventCallback" - " (Event type: %s, object type: %s)\n" - , ev->getTypeId().getName().getString() - , self->getTypeId().getName()); + Base::Console().error( + "Unhandled unknown C++ exception in ViewProvider::eventCallback" + " (Event type: %s, object type: %s)\n", + ev->getTypeId().getName().getString(), + self->getTypeId().getName() + ); } } @@ -317,68 +332,75 @@ SoSeparator* ViewProvider::getAnnotation() void ViewProvider::update(const App::Property* prop) { // Hide the object temporarily to speed up the update - if (!isUpdatesEnabled()) + if (!isUpdatesEnabled()) { return; + } bool vis = ViewProvider::isShow(); - if (vis) ViewProvider::hide(); + if (vis) { + ViewProvider::hide(); + } updateData(prop); - if (vis) ViewProvider::show(); + if (vis) { + ViewProvider::show(); + } } QIcon ViewProvider::getIcon() const { - return mergeGreyableOverlayIcons (Gui::BitmapFactory().pixmap(sPixmap)); + return mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(sPixmap)); } -QIcon ViewProvider::mergeGreyableOverlayIcons (const QIcon & orig) const +QIcon ViewProvider::mergeGreyableOverlayIcons(const QIcon& orig) const { auto vector = getExtensionsDerivedFromType(); QIcon overlayedIcon = orig; for (Gui::ViewProviderExtension* ext : vector) { - if (!ext->ignoreOverlayIcon()) + if (!ext->ignoreOverlayIcon()) { overlayedIcon = ext->extensionMergeGreyableOverlayIcons(overlayedIcon); + } } return overlayedIcon; } -QIcon ViewProvider::mergeColorfulOverlayIcons (const QIcon & orig) const +QIcon ViewProvider::mergeColorfulOverlayIcons(const QIcon& orig) const { auto vector = getExtensionsDerivedFromType(); QIcon overlayedIcon = orig; for (Gui::ViewProviderExtension* ext : vector) { - if (!ext->ignoreOverlayIcon()) + if (!ext->ignoreOverlayIcon()) { overlayedIcon = ext->extensionMergeColorfullOverlayIcons(overlayedIcon); + } } return overlayedIcon; } -void ViewProvider::setTransformation(const Base::Matrix4D &rcMatrix) +void ViewProvider::setTransformation(const Base::Matrix4D& rcMatrix) { pcTransform->setMatrix(convert(rcMatrix)); } -void ViewProvider::setTransformation(const SbMatrix &rcMatrix) +void ViewProvider::setTransformation(const SbMatrix& rcMatrix) { pcTransform->setMatrix(rcMatrix); } -SbMatrix ViewProvider::convert(const Base::Matrix4D &rcMatrix) +SbMatrix ViewProvider::convert(const Base::Matrix4D& rcMatrix) { return Base::convertTo(rcMatrix); } -Base::Matrix4D ViewProvider::convert(const SbMatrix &smat) +Base::Matrix4D ViewProvider::convert(const SbMatrix& smat) { return Base::convertTo(smat); } -void ViewProvider::addDisplayMaskMode(SoNode *node, const char* type) +void ViewProvider::addDisplayMaskMode(SoNode* node, const char* type) { _sDisplayMaskModes[type] = pcModeSwitch->getNumChildren(); pcModeSwitch->addChild(node); @@ -387,16 +409,18 @@ void ViewProvider::addDisplayMaskMode(SoNode *node, const char* type) void ViewProvider::setDisplayMaskMode(const char* type) { std::map::const_iterator it = _sDisplayMaskModes.find(type); - if (it != _sDisplayMaskModes.end()) + if (it != _sDisplayMaskModes.end()) { _iActualMode = it->second; - else + } + else { _iActualMode = -1; + } setModeSwitch(); } SoNode* ViewProvider::getDisplayMaskMode(const char* type) const { - std::map::const_iterator it = _sDisplayMaskModes.find( type ); + std::map::const_iterator it = _sDisplayMaskModes.find(type); if (it != _sDisplayMaskModes.end()) { return pcModeSwitch->getChild(it->second); } @@ -407,8 +431,9 @@ SoNode* ViewProvider::getDisplayMaskMode(const char* type) const std::vector ViewProvider::getDisplayMaskModes() const { std::vector types; - for (const auto & it : _sDisplayMaskModes) - types.push_back( it.first ); + for (const auto& it : _sDisplayMaskModes) { + types.push_back(it.first); + } return types; } @@ -421,24 +446,27 @@ void ViewProvider::setDisplayMode(const char* ModeName) { _sCurrentMode = ModeName; - //infom the exteensions + // infom the exteensions auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionSetDisplayMode(ModeName); + } } -const char* ViewProvider::getDefaultDisplayMode() const { +const char* ViewProvider::getDefaultDisplayMode() const +{ return nullptr; } -vector ViewProvider::getDisplayModes() const { +vector ViewProvider::getDisplayModes() const +{ - std::vector< std::string > modes; + std::vector modes; auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { auto extModes = ext->extensionGetDisplayModes(); - modes.insert( modes.end(), extModes.begin(), extModes.end() ); + modes.insert(modes.end(), extModes.begin(), extModes.end()); } return modes; } @@ -452,25 +480,28 @@ void ViewProvider::hide() { auto exts = getExtensionsDerivedFromType(); - if(pcModeSwitch->whichChild.getValue() >= 0) { + if (pcModeSwitch->whichChild.getValue() >= 0) { pcModeSwitch->whichChild = -1; - for(auto ext : exts) + for (auto ext : exts) { ext->extensionModeSwitchChange(); + } } - //tell extensions that we hide - for (Gui::ViewProviderExtension* ext : exts) + // tell extensions that we hide + for (Gui::ViewProviderExtension* ext : exts) { ext->extensionHide(); + } } void ViewProvider::show() { setModeSwitch(); - //tell extensions that we show + // tell extensions that we show auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionShow(); + } } bool ViewProvider::isShow() const @@ -488,7 +519,7 @@ bool ViewProvider::isVisible() const return isShow(); } -void ViewProvider::setOverrideMode(const std::string &mode) +void ViewProvider::setOverrideMode(const std::string& mode) { if (mode == "As Is") { viewOverrideMode = -1; @@ -496,45 +527,55 @@ void ViewProvider::setOverrideMode(const std::string &mode) } else { std::map::const_iterator it = _sDisplayMaskModes.find(mode); - if (it == _sDisplayMaskModes.end()) - return; //view style not supported + if (it == _sDisplayMaskModes.end()) { + return; // view style not supported + } viewOverrideMode = (*it).second; overrideMode = mode; } - if (pcModeSwitch->whichChild.getValue() != -1) + if (pcModeSwitch->whichChild.getValue() != -1) { setModeSwitch(); + } else { - for(auto ext : getExtensionsDerivedFromType()) + for (auto ext : getExtensionsDerivedFromType()) { ext->extensionModeSwitchChange(); + } } } -const string ViewProvider::getOverrideMode() { +const string ViewProvider::getOverrideMode() +{ return overrideMode; } void ViewProvider::setModeSwitch() { - if (viewOverrideMode == -1) + if (viewOverrideMode == -1) { pcModeSwitch->whichChild = _iActualMode; - else if (viewOverrideMode < pcModeSwitch->getNumChildren()) + } + else if (viewOverrideMode < pcModeSwitch->getNumChildren()) { pcModeSwitch->whichChild = viewOverrideMode; - else + } + else { return; - for(auto ext : getExtensionsDerivedFromType()) + } + for (auto ext : getExtensionsDerivedFromType()) { ext->extensionModeSwitchChange(); + } } void ViewProvider::setDefaultMode(int val) { _iActualMode = val; - for(auto ext : getExtensionsDerivedFromType()) + for (auto ext : getExtensionsDerivedFromType()) { ext->extensionModeSwitchChange(); + } } -int ViewProvider::getDefaultMode() const { - return viewOverrideMode>=0?viewOverrideMode:_iActualMode; +int ViewProvider::getDefaultMode() const +{ + return viewOverrideMode >= 0 ? viewOverrideMode : _iActualMode; } void ViewProvider::onBeforeChange(const App::Property* prop) @@ -559,24 +600,26 @@ std::string ViewProvider::toString() const PyObject* ViewProvider::getPyObject() { - if (!pyViewObject) + if (!pyViewObject) { pyViewObject = new ViewProviderPy(this); + } pyViewObject->IncRef(); return pyViewObject; } #include -namespace Gui { -using Graph = boost::adjacency_list < - boost::vecS, // class OutEdgeListS : a Sequence or an AssociativeContainer - boost::vecS, // class VertexListS : a Sequence or a RandomAccessContainer - boost::directedS, // class DirectedS : This is a directed graph - boost::no_property, // class VertexProperty: - boost::no_property, // class EdgeProperty: - boost::no_property, // class GraphProperty: - boost::listS // class EdgeListS: ->; +namespace Gui +{ +using Graph = boost::adjacency_list< + boost::vecS, // class OutEdgeListS : a Sequence or an AssociativeContainer + boost::vecS, // class VertexListS : a Sequence or a RandomAccessContainer + boost::directedS, // class DirectedS : This is a directed graph + boost::no_property, // class VertexProperty: + boost::no_property, // class EdgeProperty: + boost::no_property, // class GraphProperty: + boost::listS // class EdgeListS: + >; using Vertex = boost::graph_traits::vertex_descriptor; using Edge = boost::graph_traits::edge_descriptor; @@ -586,7 +629,7 @@ void addNodes(Graph& graph, std::map& vertexNodeMap, SoNode* no auto group = static_cast(node); Vertex groupV = vertexNodeMap[group]; - for (int i=0; igetNumChildren(); i++) { + for (int i = 0; i < group->getNumChildren(); i++) { SoNode* child = group->getChild(i); auto it = vertexNodeMap.find(child); @@ -604,7 +647,7 @@ void addNodes(Graph& graph, std::map& vertexNodeMap, SoNode* no } } } -} +} // namespace Gui bool ViewProvider::checkRecursion(SoNode* node) { @@ -632,7 +675,11 @@ SoPickedPoint* ViewProvider::getPointOnRay(const SbVec2s& pos, const View3DInven return viewer->getPointOnRay(pos, this); } -SoPickedPoint* ViewProvider::getPointOnRay(const SbVec3f& pos,const SbVec3f& dir, const View3DInventorViewer* viewer) const +SoPickedPoint* ViewProvider::getPointOnRay( + const SbVec3f& pos, + const SbVec3f& dir, + const View3DInventorViewer* viewer +) const { return viewer->getPointOnRay(pos, dir, this); } @@ -642,7 +689,7 @@ std::vector ViewProvider::getModelPoints(const SoPickedPoint* pp // the default implementation just returns the picked point from the visual representation std::vector pts; const SbVec3f& vec = pp->getPoint(); - pts.emplace_back(vec[0],vec[1],vec[2]); + pts.emplace_back(vec[0], vec[1], vec[2]); return pts; } @@ -653,17 +700,19 @@ bool ViewProvider::keyPressed(bool pressed, int key) return false; } -bool ViewProvider::mouseMove(const SbVec2s &cursorPos, - View3DInventorViewer* viewer) +bool ViewProvider::mouseMove(const SbVec2s& cursorPos, View3DInventorViewer* viewer) { (void)cursorPos; (void)viewer; return false; } -bool ViewProvider::mouseButtonPressed(int button, bool pressed, - const SbVec2s &cursorPos, - const View3DInventorViewer* viewer) +bool ViewProvider::mouseButtonPressed( + int button, + bool pressed, + const SbVec2s& cursorPos, + const View3DInventorViewer* viewer +) { (void)button; (void)pressed; @@ -672,27 +721,29 @@ bool ViewProvider::mouseButtonPressed(int button, bool pressed, return false; } -bool ViewProvider::mouseWheelEvent(int delta, const SbVec2s &cursorPos, const View3DInventorViewer* viewer) +bool ViewProvider::mouseWheelEvent(int delta, const SbVec2s& cursorPos, const View3DInventorViewer* viewer) { - (void) delta; - (void) cursorPos; - (void) viewer; + (void)delta; + (void)cursorPos; + (void)viewer; return false; } void ViewProvider::setupContextMenu(QMenu* menu, QObject* receiver, const char* method) { auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionSetupContextMenu(menu, receiver, method); + } } -bool ViewProvider::onDelete(const vector< string >& subNames) +bool ViewProvider::onDelete(const vector& subNames) { bool del = true; auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { del &= ext->extensionOnDelete(subNames); + } return del; } @@ -706,14 +757,18 @@ bool ViewProvider::canDragObject(App::DocumentObject* obj) const { auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { - if (ext->extensionCanDragObject(obj)) + if (ext->extensionCanDragObject(obj)) { return true; + } } return false; } -bool ViewProvider::canDragObjectToTarget(App::DocumentObject* obj, [[maybe_unused]] App::DocumentObject* target) const +bool ViewProvider::canDragObjectToTarget( + App::DocumentObject* obj, + [[maybe_unused]] App::DocumentObject* target +) const { return canDragObject(obj); } @@ -722,8 +777,9 @@ bool ViewProvider::canDragObjects() const { auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { - if (ext->extensionCanDragObjects()) + if (ext->extensionCanDragObjects()) { return true; + } } return false; @@ -739,7 +795,9 @@ void ViewProvider::dragObject(App::DocumentObject* obj) } } - throw Base::RuntimeError("ViewProvider::dragObject: no extension for dragging given object available."); + throw Base::RuntimeError( + "ViewProvider::dragObject: no extension for dragging given object available." + ); } bool ViewProvider::canDropObject(App::DocumentObject* obj) const @@ -748,28 +806,33 @@ bool ViewProvider::canDropObject(App::DocumentObject* obj) const #if FC_DEBUG Base::Console().log("Check extensions for drop\n"); #endif - for (Gui::ViewProviderExtension* ext : vector){ + for (Gui::ViewProviderExtension* ext : vector) { #if FC_DEBUG Base::Console().log("Check extensions %s\n", ext->name().c_str()); #endif - if (ext->extensionCanDropObject(obj)) + if (ext->extensionCanDropObject(obj)) { return true; + } } return false; } -bool ViewProvider::canDropObjects() const { +bool ViewProvider::canDropObjects() const +{ auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) - if(ext->extensionCanDropObjects()) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionCanDropObjects()) { return true; + } + } return false; } -bool ViewProvider::canDragAndDropObject(App::DocumentObject* obj) const { +bool ViewProvider::canDragAndDropObject(App::DocumentObject* obj) const +{ auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { @@ -781,7 +844,8 @@ bool ViewProvider::canDragAndDropObject(App::DocumentObject* obj) const { return false; } -void ViewProvider::dropObject(App::DocumentObject* obj) { +void ViewProvider::dropObject(App::DocumentObject* obj) +{ auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { if (ext->extensionCanDropObject(obj)) { @@ -791,24 +855,34 @@ void ViewProvider::dropObject(App::DocumentObject* obj) { } } -bool ViewProvider::canDropObjectEx(App::DocumentObject* obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) const +bool ViewProvider::canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements +) const { auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector){ - if(ext->extensionCanDropObjectEx(obj,owner,subname, elements)) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionCanDropObjectEx(obj, owner, subname, elements)) { return true; + } } return canDropObject(obj); } -std::string ViewProvider::dropObjectEx(App::DocumentObject* obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) +std::string ViewProvider::dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements +) { auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) { - if(ext->extensionCanDropObjectEx(obj, owner, subname, elements)) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionCanDropObjectEx(obj, owner, subname, elements)) { return ext->extensionDropObjectEx(obj, owner, subname, elements); + } } dropObject(obj); return {}; @@ -820,14 +894,16 @@ int ViewProvider::replaceObject(App::DocumentObject* oldValue, App::DocumentObje for (Gui::ViewProviderExtension* ext : vector) { if (ext->extensionCanDropObject(newValue)) { int ret = ext->extensionReplaceObject(oldValue, newValue); - if(ret>=0) + if (ret >= 0) { return !!ret; + } } } return -1; } -void ViewProvider::Restore(Base::XMLReader& reader) { +void ViewProvider::Restore(Base::XMLReader& reader) +{ // Because some PropertyLists type properties are stored in a separate file, // and is thus restored outside this function. So we rely on Gui::Document // to set the isRestoring flags for us. @@ -842,8 +918,9 @@ void ViewProvider::Restore(Base::XMLReader& reader) { void ViewProvider::updateData(const App::Property* prop) { auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionUpdateData(prop); + } } SoSeparator* ViewProvider::getBackRoot() const @@ -851,8 +928,9 @@ SoSeparator* ViewProvider::getBackRoot() const auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { auto* node = ext->extensionGetBackRoot(); - if (node) + if (node) { return node; + } } return nullptr; } @@ -862,8 +940,9 @@ SoGroup* ViewProvider::getChildRoot() const auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { auto* node = ext->extensionGetChildRoot(); - if (node) + if (node) { return node; + } } return nullptr; } @@ -873,97 +952,108 @@ SoSeparator* ViewProvider::getFrontRoot() const auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { auto* node = ext->extensionGetFrontRoot(); - if (node) + if (node) { return node; + } } return nullptr; } -std::vector< App::DocumentObject* > ViewProvider::claimChildren() const +std::vector ViewProvider::claimChildren() const { - std::vector< App::DocumentObject* > vec; + std::vector vec; auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { - std::vector< App::DocumentObject* > nvec = ext->extensionClaimChildren(); - if (!nvec.empty()){ + std::vector nvec = ext->extensionClaimChildren(); + if (!nvec.empty()) { vec.insert(std::end(vec), std::begin(nvec), std::end(nvec)); } } return vec; } -std::vector< App::DocumentObject* > ViewProvider::claimChildrenRecursive() const +std::vector ViewProvider::claimChildrenRecursive() const { std::vector children = claimChildren(); for (auto* child : claimChildren()) { auto* vp = Application::Instance->getViewProvider(child); - if (!vp) { continue; } + if (!vp) { + continue; + } std::vector nvec = vp->claimChildrenRecursive(); - if (!nvec.empty()){ + if (!nvec.empty()) { children.insert(std::end(children), std::begin(nvec), std::end(nvec)); } } return children; } -std::vector< App::DocumentObject* > ViewProvider::claimChildren3D() const +std::vector ViewProvider::claimChildren3D() const { - std::vector< App::DocumentObject* > vec; + std::vector vec; auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { - std::vector< App::DocumentObject* > nvec = ext->extensionClaimChildren3D(); - if (!nvec.empty()) + std::vector nvec = ext->extensionClaimChildren3D(); + if (!nvec.empty()) { vec.insert(std::end(vec), std::begin(nvec), std::end(nvec)); + } } return vec; } -bool ViewProvider::getElementPicked(const SoPickedPoint *pp, std::string &subname) const { +bool ViewProvider::getElementPicked(const SoPickedPoint* pp, std::string& subname) const +{ auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) { - if(ext->extensionGetElementPicked(pp,subname)) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionGetElementPicked(pp, subname)) { return true; + } } - subname = getElement(pp?pp->getDetail():nullptr); + subname = getElement(pp ? pp->getDetail() : nullptr); return true; } -bool ViewProvider::getDetailPath(const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const { - if(pcRoot->findChild(pcModeSwitch) < 0) { +bool ViewProvider::getDetailPath(const char* subname, SoFullPath* pPath, bool append, SoDetail*& det) const +{ + if (pcRoot->findChild(pcModeSwitch) < 0) { // this is possible in case of editing, where the switch node // of the linked view object is temporarily removed from its root // if(append) // pPath->append(pcRoot); return false; } - if(append) { + if (append) { pPath->append(pcRoot); pPath->append(pcModeSwitch); } auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) { - if(ext->extensionGetDetailPath(subname,pPath,det)) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionGetDetailPath(subname, pPath, det)) { return true; + } } det = getDetail(subname); return true; } -const std::string &ViewProvider::hiddenMarker() { +const std::string& ViewProvider::hiddenMarker() +{ return App::DocumentObject::hiddenMarker(); } -const char *ViewProvider::hasHiddenMarker(const char *subname) { +const char* ViewProvider::hasHiddenMarker(const char* subname) +{ return App::DocumentObject::hasHiddenMarker(subname); } -int ViewProvider::partialRender(const std::vector &elements, bool clear) { - if(elements.empty()) { +int ViewProvider::partialRender(const std::vector& elements, bool clear) +{ + if (elements.empty()) { auto node = pcModeSwitch->getChild(_iActualMode); - if(node) { + if (node) { FC_LOG("partial render clear"); - SoSelectionElementAction action(SoSelectionElementAction::None,true); + SoSelectionElementAction action(SoSelectionElementAction::None, true); action.apply(node); } } @@ -972,22 +1062,27 @@ int ViewProvider::partialRender(const std::vector &elements, bool c path->ref(); SoSelectionElementAction action; action.setSecondary(true); - for(auto element : elements) { + for (auto element : elements) { bool hidden = hasHiddenMarker(element.c_str()); - if(hidden) - element.resize(element.size()-hiddenMarker().size()); + if (hidden) { + element.resize(element.size() - hiddenMarker().size()); + } path->truncate(0); - SoDetail *det = nullptr; - if(getDetailPath(element.c_str(),path,false,det)) { - if(!hidden && !det) { + SoDetail* det = nullptr; + if (getDetailPath(element.c_str(), path, false, det)) { + if (!hidden && !det) { FC_LOG("partial render element not found: " << element); continue; } FC_LOG("partial render (" << path->getLength() << "): " << element); - if(!hidden) - action.setType(clear?SoSelectionElementAction::Remove:SoSelectionElementAction::Append); - else - action.setType(clear?SoSelectionElementAction::Show:SoSelectionElementAction::Hide); + if (!hidden) { + action.setType( + clear ? SoSelectionElementAction::Remove : SoSelectionElementAction::Append + ); + } + else { + action.setType(clear ? SoSelectionElementAction::Show : SoSelectionElementAction::Hide); + } action.setElement(det); action.apply(path); ++count; @@ -998,36 +1093,44 @@ int ViewProvider::partialRender(const std::vector &elements, bool c return count; } -bool ViewProvider::useNewSelectionModel() const { +bool ViewProvider::useNewSelectionModel() const +{ return ViewParams::instance()->getUseNewSelection(); } -void ViewProvider::beforeDelete() { +void ViewProvider::beforeDelete() +{ auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionBeforeDelete(); + } } -void ViewProvider::setRenderCacheMode(int mode) { - pcRoot->renderCaching = - mode==0?SoSeparator::AUTO:(mode==1?SoSeparator::ON:SoSeparator::OFF); +void ViewProvider::setRenderCacheMode(int mode) +{ + pcRoot->renderCaching = mode == 0 ? SoSeparator::AUTO + : (mode == 1 ? SoSeparator::ON : SoSeparator::OFF); } -Base::BoundBox3d ViewProvider::getBoundingBox(const char *subname, bool transform, MDIView *view) const { - if(!pcRoot || !pcModeSwitch || pcRoot->findChild(pcModeSwitch)<0) +Base::BoundBox3d ViewProvider::getBoundingBox(const char* subname, bool transform, MDIView* view) const +{ + if (!pcRoot || !pcModeSwitch || pcRoot->findChild(pcModeSwitch) < 0) { return Base::BoundBox3d(); + } - if(!view) - view = Application::Instance->activeView(); + if (!view) { + view = Application::Instance->activeView(); + } auto iview = qobject_cast(view); - if(!iview) { + if (!iview) { auto doc = Application::Instance->activeDocument(); - if(doc) { + if (doc) { auto views = doc->getMDIViewsOfType(View3DInventor::getClassTypeId()); - if(!views.empty()) + if (!views.empty()) { iview = qobject_cast(views.front()); + } } - if(!iview) { + if (!iview) { FC_ERR("no view"); return Base::BoundBox3d(); } @@ -1037,16 +1140,18 @@ Base::BoundBox3d ViewProvider::getBoundingBox(const char *subname, bool transfor SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion()); auto mode = pcModeSwitch->whichChild.getValue(); - if(mode < 0) + if (mode < 0) { pcModeSwitch->whichChild = getDefaultMode(); + } SoTempPath path(20); path.ref(); - if(!Base::Tools::isNullOrEmpty(subname)) { - SoDetail *det=nullptr; - if(!getDetailPath(subname,&path,true,det)) { - if(mode < 0) + if (!Base::Tools::isNullOrEmpty(subname)) { + SoDetail* det = nullptr; + if (!getDetailPath(subname, &path, true, det)) { + if (mode < 0) { pcModeSwitch->whichChild = mode; + } path.unrefNoDelete(); return Base::BoundBox3d(); } @@ -1054,36 +1159,42 @@ Base::BoundBox3d ViewProvider::getBoundingBox(const char *subname, bool transfor } SoTempPath resetPath(3); resetPath.ref(); - if(!transform) { + if (!transform) { resetPath.append(pcRoot); resetPath.append(pcModeSwitch); - bboxAction.setResetPath(&resetPath,true,SoGetBoundingBoxAction::TRANSFORM); + bboxAction.setResetPath(&resetPath, true, SoGetBoundingBoxAction::TRANSFORM); } - if(path.getLength()) + if (path.getLength()) { bboxAction.apply(&path); - else + } + else { bboxAction.apply(pcRoot); - if(mode < 0) + } + if (mode < 0) { pcModeSwitch->whichChild = mode; + } resetPath.unrefNoDelete(); path.unrefNoDelete(); auto bbox = bboxAction.getBoundingBox(); - float minX,minY,minZ,maxX,maxY,maxZ; - bbox.getMax().getValue(maxX,maxY,maxZ); - bbox.getMin().getValue(minX,minY,minZ); - return Base::BoundBox3d(minX,minY,minZ,maxX,maxY,maxZ); + float minX, minY, minZ, maxX, maxY, maxZ; + bbox.getMax().getValue(maxX, maxY, maxZ); + bbox.getMin().getValue(minX, minY, minZ); + return Base::BoundBox3d(minX, minY, minZ, maxX, maxY, maxZ); } -bool ViewProvider::isLinkVisible() const { +bool ViewProvider::isLinkVisible() const +{ auto ext = getExtensionByType(true); - if(!ext) + if (!ext) { return true; + } return ext->isLinkVisible(); } -void ViewProvider::setLinkVisible(bool visible) { +void ViewProvider::setLinkVisible(bool visible) +{ auto ext = getExtensionByType(true); - if(ext) + if (ext) { ext->setLinkVisible(visible); + } } - diff --git a/src/Gui/ViewProvider.h b/src/Gui/ViewProvider.h index a376491ebe..d431cd3932 100644 --- a/src/Gui/ViewProvider.h +++ b/src/Gui/ViewProvider.h @@ -56,25 +56,29 @@ class QMenu; class QObject; -namespace Base { - class Matrix4D; - class Color; -} +namespace Base +{ +class Matrix4D; +class Color; +} // namespace Base class SoGroup; -namespace Gui { - namespace TaskView { - class TaskContent; - } +namespace Gui +{ +namespace TaskView +{ +class TaskContent; +} class View3DInventorViewer; class ViewProviderPy; class ObjectItem; class MDIView; class SelectionChanges; -enum ViewStatus { +enum ViewStatus +{ UpdateData = 0, Detach = 1, isRestoring = 2, @@ -89,39 +93,47 @@ enum ViewStatus { * trouble of typing get() all the time. */ template -class CoinPtr: public boost::intrusive_ptr { +class CoinPtr: public boost::intrusive_ptr +{ public: // Too bad, VC2013 does not support constructor inheritance - //using boost::intrusive_ptr::intrusive_ptr; + // using boost::intrusive_ptr::intrusive_ptr; using inherited = boost::intrusive_ptr; CoinPtr() = default; - CoinPtr(T *p, bool add_ref=true):inherited(p,add_ref){} - template CoinPtr(CoinPtr const &r):inherited(r){} + CoinPtr(T* p, bool add_ref = true) + : inherited(p, add_ref) + {} + template + CoinPtr(CoinPtr const& r) + : inherited(r) + {} - operator T *() const { + operator T*() const + { return this->get(); - }//explicit bombs + } // explicit bombs }; /** Helper function to deal with bug in SoNode::removeAllChildren() * * @sa https://bitbucket.org/Coin3D/coin/pull-requests/119/fix-sochildlist-auditing/diff */ -void GuiExport coinRemoveAllChildren(SoGroup *node); +void GuiExport coinRemoveAllChildren(SoGroup* node); /** General interface for all visual stuff in FreeCAD - * This class is used to generate and handle all around - * visualizing and presenting objects from the FreeCAD - * App layer to the user. This class and its descendents - * have to be implemented for any object type in order to - * show them in the 3DView and TreeView. - */ -class GuiExport ViewProvider : public App::TransactionalObject + * This class is used to generate and handle all around + * visualizing and presenting objects from the FreeCAD + * App layer to the user. This class and its descendents + * have to be implemented for any object type in order to + * show them in the 3DView and TreeView. + */ +class GuiExport ViewProvider: public App::TransactionalObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProvider); public: - enum class ToggleVisibilityMode : bool { + enum class ToggleVisibilityMode : bool + { CanToggleVisibility = true, NoToggleVisibility = false }; @@ -133,10 +145,19 @@ public: ~ViewProvider() override; // returns the root node of the Provider (3D) - virtual SoSeparator* getRoot() const {return pcRoot;} + virtual SoSeparator* getRoot() const + { + return pcRoot; + } // return the mode switch node of the Provider (3D) - SoSwitch *getModeSwitch() const {return pcModeSwitch;} - SoTransform *getTransformNode() const {return pcTransform;} + SoSwitch* getModeSwitch() const + { + return pcModeSwitch; + } + SoTransform* getTransformNode() const + { + return pcTransform; + } // returns the root for the Annotations. SoSeparator* getAnnotation(); // returns the root node of the Provider (3D) @@ -145,37 +166,53 @@ public: virtual SoGroup* getChildRoot() const; // returns the root node of the Provider (3D) virtual SoSeparator* getBackRoot() const; - ///Indicate whether to be added to scene graph or not - virtual bool canAddToSceneGraph() const {return true;} + /// Indicate whether to be added to scene graph or not + virtual bool canAddToSceneGraph() const + { + return true; + } // Indicate whether to be added to object group (true) or only to scene graph (false) - virtual bool isPartOfPhysicalObject() const {return true;} + virtual bool isPartOfPhysicalObject() const + { + return true; + } /** deliver the children belonging to this object - * this method is used to deliver the objects to - * the 3DView which should be grouped under its - * scene graph. This affects the visibility and the 3D - * position of the object. - */ + * this method is used to deliver the objects to + * the 3DView which should be grouped under its + * scene graph. This affects the visibility and the 3D + * position of the object. + */ virtual std::vector claimChildren3D() const; /** @name Selection handling - * This group of methods do the selection handling. - * Here you can define how the selection for your ViewProfider - * works. + * This group of methods do the selection handling. + * Here you can define how the selection for your ViewProfider + * works. */ //@{ /// indicates if the ViewProvider use the new Selection model virtual bool useNewSelectionModel() const; - virtual bool isSelectable() const {return true;} + virtual bool isSelectable() const + { + return true; + } /// called when the selection changes for the view provider - virtual void onSelectionChanged(const SelectionChanges&) {} + virtual void onSelectionChanged(const SelectionChanges&) + {} /// return a hit element given the picked point which contains the full node path - virtual bool getElementPicked(const SoPickedPoint *, std::string &subname) const; + virtual bool getElementPicked(const SoPickedPoint*, std::string& subname) const; /// return a hit element to the selection path or 0 - virtual std::string getElement(const SoDetail *) const { return {}; } + virtual std::string getElement(const SoDetail*) const + { + return {}; + } /// return the coin node detail of the subelement - virtual SoDetail* getDetail(const char *) const { return nullptr; } + virtual SoDetail* getDetail(const char*) const + { + return nullptr; + } /** return the coin node detail and path to the node of the subelement * @@ -191,7 +228,7 @@ public: * nodes starting just after the mode switch node up till the mode switch of * the linked view provider. */ - virtual bool getDetailPath(const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const; + virtual bool getDetailPath(const char* subname, SoFullPath* pPath, bool append, SoDetail*& det) const; /** partial rendering setup * @@ -204,11 +241,12 @@ public: * Partial rendering only works if there is at least one SoFCSelectRoot node * in this view provider */ - int partialRender(const std::vector &subelements, bool clear); + int partialRender(const std::vector& subelements, bool clear); - virtual std::vector getModelPoints(const SoPickedPoint *) const; + virtual std::vector getModelPoints(const SoPickedPoint*) const; /// return the highlight lines for a given element or the whole shape - virtual std::vector getSelectionShape(const char* Element) const { + virtual std::vector getSelectionShape(const char* Element) const + { (void)Element; return {}; } @@ -218,15 +256,20 @@ public: * This method shall work regardless whether the current view object is * visible or not. */ - Base::BoundBox3d getBoundingBox(const char *subname=nullptr, bool transform=true, MDIView *view=nullptr) const; + Base::BoundBox3d getBoundingBox( + const char* subname = nullptr, + bool transform = true, + MDIView* view = nullptr + ) const; /** * Get called if the object is about to get deleted. - * Here you can delete other objects, switch their visibility or prevent the deletion of the object. + * Here you can delete other objects, switch their visibility or prevent the deletion of the + * object. * @param subNames list of selected subelements * @return true if the deletion is approved by the view provider. */ - virtual bool onDelete(const std::vector &subNames); + virtual bool onDelete(const std::vector& subNames); /** Called before deletion * * Unlike onDelete(), this function is guaranteed to be called before @@ -244,9 +287,9 @@ public: /** @name Methods used by the Tree - * If you want to take control over the - * appearance of your object in the tree you - * can reimplement these methods. + * If you want to take control over the + * appearance of your object in the tree you + * can reimplement these methods. */ //@{ /// deliver the icon shown in the tree view @@ -264,30 +307,31 @@ public: * Coin but are "rendered" on the TechDraw page and hence this function can * return true for those items. */ - bool canToggleVisibility() const { + bool canToggleVisibility() const + { return toggleVisibilityMode == ToggleVisibilityMode::CanToggleVisibility; } - /** @name Methods used by the Tree + /** @name Methods used by the Tree * If you want to take control over the * viewprovider specific overlay icons that will be drawn with color * regardless of whether the icon is greyed out or not, such as status, you * can reimplement this method. */ - virtual QIcon mergeColorfulOverlayIcons (const QIcon & orig) const; + virtual QIcon mergeColorfulOverlayIcons(const QIcon& orig) const; /** deliver the children belonging to this object - * this method is used to deliver the objects to - * the tree framework which should be grouped under its - * label. Obvious is the usage in the group but it can - * be used for any kind of grouping needed for a special - * purpose. - */ + * this method is used to deliver the objects to + * the tree framework which should be grouped under its + * label. Obvious is the usage in the group but it can + * be used for any kind of grouping needed for a special + * purpose. + */ virtual std::vector claimChildren() const; //@} /** deliver the children belonging to this object recursively. - */ + */ virtual std::vector claimChildrenRecursive() const; //@} @@ -304,7 +348,8 @@ public: virtual bool canDragObjects() const; /** Check whether the object can be removed from the view provider by drag and drop */ virtual bool canDragObject(App::DocumentObject*) const; - /** Check whether the object can be removed from the view provider by drag and drop to a determined target*/ + /** Check whether the object can be removed from the view provider by drag and drop to a + * determined target*/ virtual bool canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const; /** Remove a child from the view provider by drag and drop */ virtual void dragObject(App::DocumentObject*); @@ -338,13 +383,23 @@ public: * * @return Return whether the dropping action is allowed. * */ - virtual bool canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) const; + virtual bool canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements + ) const; /* Check whether the object accept reordering of its children during drop.*/ - virtual bool acceptReorderingObjects() const { return false; }; + virtual bool acceptReorderingObjects() const + { + return false; + }; /// return a subname referencing the sub-object holding the dropped objects - virtual std::string getDropPrefix() const { return {}; } + virtual std::string getDropPrefix() const + { + return {}; + } /** Add an object with full qualified name to the view provider by drag and drop * @@ -364,8 +419,12 @@ public: * object, which may or may not be the actual dropped object, e.g. it may be * a link. */ - virtual std::string dropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements); + virtual std::string dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements + ); /** Replace an object to the view provider by drag and drop * * @param oldObj: object to be replaced @@ -373,24 +432,30 @@ public: * * @return Returns 0 if not found, 1 if succeeded, -1 if not supported */ - virtual int replaceObject(App::DocumentObject *oldObj, App::DocumentObject *newObj); + virtual int replaceObject(App::DocumentObject* oldObj, App::DocumentObject* newObj); //@} /** Tell the tree view if this object should appear there */ - virtual bool showInTree() const { return true; } + virtual bool showInTree() const + { + return true; + } /** Tell the tree view to remove children items from the tree root*/ - virtual bool canRemoveChildrenFromRoot() const {return true;} + virtual bool canRemoveChildrenFromRoot() const + { + return true; + } /** @name Signals of the view provider */ //@{ /// signal on icon change - boost::signals2::signal signalChangeIcon; + boost::signals2::signal signalChangeIcon; /// signal on tooltip change - boost::signals2::signal signalChangeToolTip; + boost::signals2::signal signalChangeToolTip; /// signal on status tip change - boost::signals2::signal signalChangeStatusTip; + boost::signals2::signal signalChangeStatusTip; /// signal on highlight change - boost::signals2::signal signalChangeHighlight; + boost::signals2::signal signalChangeHighlight; //@} /** update the content of the ViewProvider @@ -401,13 +466,22 @@ public: */ virtual void update(const App::Property*); virtual void updateData(const App::Property*); - bool isUpdatesEnabled () const; - void setUpdatesEnabled (bool enable); + bool isUpdatesEnabled() const; + void setUpdatesEnabled(bool enable); /// return the status bits - unsigned long getStatus() const {return StatusBits.to_ulong();} - bool testStatus(ViewStatus pos) const {return StatusBits.test((size_t)pos);} - void setStatus(ViewStatus pos, bool on) {StatusBits.set((size_t)pos, on);} + unsigned long getStatus() const + { + return StatusBits.to_ulong(); + } + bool testStatus(ViewStatus pos) const + { + return StatusBits.test((size_t)pos); + } + void setStatus(ViewStatus pos, bool on) + { + StatusBits.set((size_t)pos, on); + } std::string toString() const; PyObject* getPyObject() override; @@ -433,22 +507,24 @@ public: void setLinkVisible(bool); bool isLinkVisible() const; /// Overrides the display mode with mode. - virtual void setOverrideMode(const std::string &mode); + virtual void setOverrideMode(const std::string& mode); const std::string getOverrideMode(); //@} /** @name Color management methods */ //@{ - virtual std::map getElementColors(const char *element=nullptr) const { + virtual std::map getElementColors(const char* element = nullptr) const + { (void)element; return {}; } - virtual void setElementColors(const std::map &colors) { + virtual void setElementColors(const std::map& colors) + { (void)colors; } - static const std::string &hiddenMarker(); - static const char *hasHiddenMarker(const char *subname); + static const std::string& hiddenMarker(); + static const char* hasHiddenMarker(const char* subname); //@} /** @name Edit methods @@ -459,11 +535,14 @@ public: // the below enum is reflected in 'userEditModes' std::map in Application.h // so it is possible for the user to choose a default one through GUI // if you add a mode here, consider to make it accessible there too - enum EditMode {Default = 0, - Transform, - Cutting, - Color, + enum EditMode + { + Default = 0, + Transform, + Cutting, + Color, }; + protected: /// is called by the document when the provider goes in edit mode virtual bool setEdit(int ModNum); @@ -473,7 +552,7 @@ protected: int getEditingMode() const; public: - virtual ViewProvider *startEditing(int ModNum=0); + virtual ViewProvider* startEditing(int ModNum = 0); bool isEditing() const; void finishEditing(); /// adjust viewer settings when editing a view provider @@ -488,27 +567,41 @@ public: */ //@{ /// get a list of TaskBoxes associated with this object - virtual void getTaskViewContent(std::vector&) const {} + virtual void getTaskViewContent(std::vector&) const + {} //@} /// is called when the provider is in edit and a "Select All" command was issued /// Provider shall return 'false' is it ignores the command, 'true' otherwise - virtual bool selectAll() { return false; } + virtual bool selectAll() + { + return false; + } /// is called when the provider is in edit and a key event occurs. Only ESC ends edit. virtual bool keyPressed(bool pressed, int key); /// 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. - virtual const char* getTransactionText() const { return nullptr; } + virtual const char* getTransactionText() const + { + return nullptr; + } /// is called by the tree if the user double clicks on the object - virtual bool doubleClicked() { return false; } + virtual bool doubleClicked() + { + return false; + } /// is called when the provider is in edit and the mouse is moved - virtual bool mouseMove(const SbVec2s &cursorPos, View3DInventorViewer* viewer); + virtual bool mouseMove(const SbVec2s& cursorPos, View3DInventorViewer* viewer); /// is called when the Provider is in edit and the mouse is clicked - virtual bool mouseButtonPressed(int button, bool pressed, const SbVec2s &cursorPos, - const View3DInventorViewer* viewer); + virtual bool mouseButtonPressed( + int button, + bool pressed, + const SbVec2s& cursorPos, + const View3DInventorViewer* viewer + ); - virtual bool mouseWheelEvent(int delta, const SbVec2s &cursorPos, const View3DInventorViewer* viewer); + virtual bool mouseWheelEvent(int delta, const SbVec2s& cursorPos, const View3DInventorViewer* viewer); /// set up the context-menu with the supported edit modes virtual void setupContextMenu(QMenu*, QObject*, const char*); @@ -520,24 +613,28 @@ public: */ //@{ /// set the viewing transformation of the provider - virtual void setTransformation(const Base::Matrix4D &rcMatrix); - virtual void setTransformation(const SbMatrix &rcMatrix); - static SbMatrix convert(const Base::Matrix4D &rcMatrix); - static Base::Matrix4D convert(const SbMatrix &sbMat); + virtual void setTransformation(const Base::Matrix4D& rcMatrix); + virtual void setTransformation(const SbMatrix& rcMatrix); + static SbMatrix convert(const Base::Matrix4D& rcMatrix); + static Base::Matrix4D convert(const SbMatrix& sbMat); //@} - virtual MDIView *getMDIView() const { + virtual MDIView* getMDIView() const + { return nullptr; } public: // this method is called by the viewer when the ViewProvider is in edit - static void eventCallback(void * ud, SoEventCallback * node); + static void eventCallback(void* ud, SoEventCallback* node); - //restoring the object from document: - //this may be of interest to extensions, hence call them + // restoring the object from document: + // this may be of interest to extensions, hence call them void Restore(Base::XMLReader& reader) override; - bool isRestoring() {return testStatus(Gui::isRestoring);} + bool isRestoring() + { + return testStatus(Gui::isRestoring); + } /** @name Display mask modes @@ -549,9 +646,9 @@ public: */ //@{ /// Adds a new display mask mode - void addDisplayMaskMode( SoNode *node, const char* type ); + void addDisplayMaskMode(SoNode* node, const char* type); /// Activates the display mask mode \a type - void setDisplayMaskMode( const char* type ); + void setDisplayMaskMode(const char* type); /// Get the node to the display mask mode \a type SoNode* getDisplayMaskMode(const char* type) const; /// Returns a list of added display mask modes @@ -570,13 +667,15 @@ protected: /** Helper method to get picked entities while editing. * It's in the responsibility of the caller to delete the returned instance. */ - SoPickedPoint* getPointOnRay(const SbVec2s& pos, - const View3DInventorViewer* viewer) const; + SoPickedPoint* getPointOnRay(const SbVec2s& pos, const View3DInventorViewer* viewer) const; /** Helper method to get picked entities while editing. * It's in the responsibility of the caller to delete the returned instance. */ - SoPickedPoint* getPointOnRay(const SbVec3f& pos, const SbVec3f& dir, - const View3DInventorViewer* viewer) const; + SoPickedPoint* getPointOnRay( + const SbVec3f& pos, + const SbVec3f& dir, + const View3DInventorViewer* viewer + ) const; /// Reimplemented from subclass void onBeforeChange(const App::Property* prop) override; /// Reimplemented from subclass @@ -587,24 +686,27 @@ protected: * viewprovider specific overlay icons, that will be grayed out together * with the base icon, you can reimplement this method. */ - virtual QIcon mergeGreyableOverlayIcons (const QIcon & orig) const; + virtual QIcon mergeGreyableOverlayIcons(const QIcon& orig) const; /// Turn on mode switch virtual void setModeSwitch(); - void setToggleVisibility(ToggleVisibilityMode mode) { toggleVisibilityMode = mode; } + void setToggleVisibility(ToggleVisibilityMode mode) + { + toggleVisibilityMode = mode; + } protected: /// The root Separator of the ViewProvider - SoSeparator *pcRoot; + SoSeparator* pcRoot; /// this is transformation for the provider - SoTransform *pcTransform; + SoTransform* pcTransform; const char* sPixmap; /// this is the mode switch, all the different viewing modes are collected here - SoSwitch *pcModeSwitch; + SoSwitch* pcModeSwitch; /// The root separator for annotations - SoSeparator *pcAnnotation{nullptr}; - ViewProviderPy* pyViewObject{nullptr}; + SoSeparator* pcAnnotation {nullptr}; + ViewProviderPy* pyViewObject {nullptr}; std::string overrideMode; std::bitset<32> StatusBits; /// whether visibility can toggled @@ -613,13 +715,13 @@ protected: friend class ViewProviderPy; private: - int _iActualMode{-1}; - int _iEditMode{-1}; - int viewOverrideMode{-1}; + int _iActualMode {-1}; + int _iEditMode {-1}; + int viewOverrideMode {-1}; std::string _sCurrentMode; std::map _sDisplayMaskModes; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDER_H +#endif // GUI_VIEWPROVIDER_H diff --git a/src/Gui/ViewProvider.pyi b/src/Gui/ViewProvider.pyi index 939f463223..300beb369e 100644 --- a/src/Gui/ViewProvider.pyi +++ b/src/Gui/ViewProvider.pyi @@ -4,7 +4,6 @@ from App.ExtensionContainer import ExtensionContainer from typing import Any, Final, List, Optional import enum - class ViewProvider(ExtensionContainer): """ This is the ViewProvider base class @@ -17,7 +16,6 @@ class ViewProvider(ExtensionContainer): CanToggleVisibility = "CanToggleVisibility" NoToggleVisibility = "NoToggleVisibility" - def addProperty( self, *, @@ -120,12 +118,7 @@ class ViewProvider(ExtensionContainer): ... def canDropObject( - self, - *, - obj: Any = None, - owner: Any = None, - subname: str, - elem: Optional[List[str]] = None + self, *, obj: Any = None, owner: Any = None, subname: str, elem: Optional[List[str]] = None ) -> bool: """ canDropObject(obj=None, owner=None, subname, elem=None) -> bool @@ -146,12 +139,7 @@ class ViewProvider(ExtensionContainer): ... def dropObject( - self, - *, - obj: Any, - owner: Any = None, - subname: str, - elem: Optional[List[str]] = None + self, *, obj: Any, owner: Any = None, subname: str, elem: Optional[List[str]] = None ) -> str: """ dropObject(obj, owner=None, subname, elem=None) -> str @@ -350,7 +338,6 @@ class ViewProvider(ExtensionContainer): Default to active view. Optional. """ ... - Annotation: Any = ... """A pivy Separator to add a custom scenegraph to this ViewProvider.""" diff --git a/src/Gui/ViewProviderAnnotation.cpp b/src/Gui/ViewProviderAnnotation.cpp index 189a940ba8..82c247f984 100644 --- a/src/Gui/ViewProviderAnnotation.cpp +++ b/src/Gui/ViewProviderAnnotation.cpp @@ -21,27 +21,26 @@ ***************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include - -# include +#include #include #include @@ -59,26 +58,30 @@ using namespace Gui; -const char* ViewProviderAnnotation::JustificationEnums[]= {"Left","Right","Center",nullptr}; -const char* ViewProviderAnnotation::RotationAxisEnums[]= {"X","Y","Z",nullptr}; +const char* ViewProviderAnnotation::JustificationEnums[] = {"Left", "Right", "Center", nullptr}; +const char* ViewProviderAnnotation::RotationAxisEnums[] = {"X", "Y", "Z", nullptr}; PROPERTY_SOURCE(Gui::ViewProviderAnnotation, Gui::ViewProviderDocumentObject) ViewProviderAnnotation::ViewProviderAnnotation() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - unsigned long col = hGrp->GetUnsigned("AnnotationTextColor",4294967295UL); // light grey - float r,g,b; - r = ((col >> 24) & 0xff) / 255.0; g = ((col >> 16) & 0xff) / 255.0; b = ((col >> 8) & 0xff) / 255.0; - ADD_PROPERTY(TextColor,(r,g,b)); - ADD_PROPERTY(Justification,((long)0)); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + unsigned long col = hGrp->GetUnsigned("AnnotationTextColor", 4294967295UL); // light grey + float r, g, b; + r = ((col >> 24) & 0xff) / 255.0; + g = ((col >> 16) & 0xff) / 255.0; + b = ((col >> 8) & 0xff) / 255.0; + ADD_PROPERTY(TextColor, (r, g, b)); + ADD_PROPERTY(Justification, ((long)0)); Justification.setEnums(JustificationEnums); - ADD_PROPERTY(FontSize,(12)); - ADD_PROPERTY(FontName,("Arial")); - ADD_PROPERTY(LineSpacing,(1.0)); - ADD_PROPERTY(Rotation,(0)); - ADD_PROPERTY(RotationAxis,((long)2)); + ADD_PROPERTY(FontSize, (12)); + ADD_PROPERTY(FontName, ("Arial")); + ADD_PROPERTY(LineSpacing, (1.0)); + ADD_PROPERTY(Rotation, (0)); + ADD_PROPERTY(RotationAxis, ((long)2)); RotationAxis.setEnums(RotationAxisEnums); pFont = new SoFont(); @@ -116,7 +119,7 @@ void ViewProviderAnnotation::onChanged(const App::Property* prop) { if (prop == &TextColor) { const Base::Color& c = TextColor.getValue(); - pColor->rgb.setValue(c.r,c.g,c.b); + pColor->rgb.setValue(c.r, c.g, c.b); } else if (prop == &Justification) { if (Justification.getValue() == 0) { @@ -154,7 +157,7 @@ void ViewProviderAnnotation::onChanged(const App::Property* prop) } } else if (prop == &Rotation) { - pRotationXYZ->angle = (Rotation.getValue()/360)*(2*std::numbers::pi); + pRotationXYZ->angle = (Rotation.getValue() / 360) * (2 * std::numbers::pi); } else { ViewProviderDocumentObject::onChanged(prop); @@ -172,10 +175,12 @@ std::vector ViewProviderAnnotation::getDisplayModes() const void ViewProviderAnnotation::setDisplayMode(const char* ModeName) { - if (strcmp(ModeName, "Screen") == 0) + if (strcmp(ModeName, "Screen") == 0) { setDisplayMaskMode("Screen"); - else if (strcmp(ModeName, "World")==0) + } + else if (strcmp(ModeName, "World") == 0) { setDisplayMaskMode("World"); + } ViewProviderDocumentObject::setDisplayMode(ModeName); } @@ -210,7 +215,7 @@ void ViewProviderAnnotation::attach(App::DocumentObject* f) textsep->addChild(pTranslation); textsep->addChild(pRotationXYZ); textsep->addChild(pColor); - textsep->addChild(pFont); // causes problems + textsep->addChild(pFont); // causes problems textsep->addChild(pLabel); auto textsep3d = new SoFCSelection(); @@ -237,25 +242,25 @@ void ViewProviderAnnotation::attach(App::DocumentObject* f) void ViewProviderAnnotation::updateData(const App::Property* prop) { - if (prop->is() && - strcmp(prop->getName(),"LabelText") == 0) { - const std::vector lines = static_cast(prop)->getValues(); - int index=0; + if (prop->is() && strcmp(prop->getName(), "LabelText") == 0) { + const std::vector lines + = static_cast(prop)->getValues(); + int index = 0; pLabel->string.setNum((int)lines.size()); pLabel3d->string.setNum((int)lines.size()); - for (const auto & line : lines) { + for (const auto& line : lines) { const char* cs = line.c_str(); - if (line.empty()) - cs = " "; // empty lines make coin crash, we use a space instead + if (line.empty()) { + cs = " "; // empty lines make coin crash, we use a space instead + } pLabel->string.set1Value(index, SbString(cs)); pLabel3d->string.set1Value(index, SbString(cs)); index++; } } - else if (prop->is() && - strcmp(prop->getName(),"Position") == 0) { + else if (prop->is() && strcmp(prop->getName(), "Position") == 0) { Base::Vector3d v = static_cast(prop)->getValue(); - pTranslation->translation.setValue(v.x,v.y,v.z); + pTranslation->translation.setValue(v.x, v.y, v.z); } ViewProviderDocumentObject::updateData(prop); @@ -263,21 +268,21 @@ void ViewProviderAnnotation::updateData(const App::Property* prop) // ---------------------------------------------------------------------------- -const char* ViewProviderAnnotationLabel::JustificationEnums[]= {"Left","Right","Center",nullptr}; +const char* ViewProviderAnnotationLabel::JustificationEnums[] = {"Left", "Right", "Center", nullptr}; PROPERTY_SOURCE(Gui::ViewProviderAnnotationLabel, Gui::ViewProviderDocumentObject) ViewProviderAnnotationLabel::ViewProviderAnnotationLabel() { - ADD_PROPERTY(TextColor,(1.0f,1.0f,1.0f)); - ADD_PROPERTY(BackgroundColor,(0.0f,0.333f,1.0f)); - ADD_PROPERTY(Justification,((long)0)); + ADD_PROPERTY(TextColor, (1.0f, 1.0f, 1.0f)); + ADD_PROPERTY(BackgroundColor, (0.0f, 0.333f, 1.0f)); + ADD_PROPERTY(Justification, ((long)0)); Justification.setEnums(JustificationEnums); QFont fn; - ADD_PROPERTY(FontSize,(fn.pointSize())); - ADD_PROPERTY(FontName,((const char*)fn.family().toLatin1())); - ADD_PROPERTY(Frame,(true)); + ADD_PROPERTY(FontSize, (fn.pointSize())); + ADD_PROPERTY(FontName, ((const char*)fn.family().toLatin1())); + ADD_PROPERTY(Frame, (true)); pColor = new SoBaseColor(); pColor->ref(); @@ -308,15 +313,15 @@ void ViewProviderAnnotationLabel::onChanged(const App::Property* prop) { if (prop == &BackgroundColor) { const Base::Color& c = BackgroundColor.getValue(); - pColor->rgb.setValue(c.r,c.g,c.b); + pColor->rgb.setValue(c.r, c.g, c.b); } - if (prop == &TextColor || prop == &BackgroundColor || - prop == &Justification || prop == &FontSize || - prop == &FontName || prop == &Frame) { + if (prop == &TextColor || prop == &BackgroundColor || prop == &Justification + || prop == &FontSize || prop == &FontName || prop == &Frame) { if (getObject()) { App::Property* label = getObject()->getPropertyByName("LabelText"); - if (label && label->is()) + if (label && label->is()) { drawImage(static_cast(label)->getValues()); + } } } else { @@ -335,10 +340,12 @@ std::vector ViewProviderAnnotationLabel::getDisplayModes() const void ViewProviderAnnotationLabel::setDisplayMode(const char* ModeName) { - if (strcmp(ModeName, "Line") == 0) + if (strcmp(ModeName, "Line") == 0) { setDisplayMaskMode("Line"); - else if (strcmp(ModeName, "Object")==0) + } + else if (strcmp(ModeName, "Object") == 0) { setDisplayMaskMode("Object"); + } ViewProviderDocumentObject::setDisplayMode(ModeName); } @@ -374,7 +381,7 @@ void ViewProviderAnnotationLabel::attach(App::DocumentObject* f) sa.setSearchingAll(true); sa.setNode(this->pImage); sa.apply(pcRoot); - SoPath * imagePath = sa.getPath(); + SoPath* imagePath = sa.getPath(); if (imagePath) { SoDragger* dragger = pTextTranslation->getDragger(); dragger->addStartCallback(dragStartCallback, this); @@ -392,45 +399,44 @@ void ViewProviderAnnotationLabel::attach(App::DocumentObject* f) void ViewProviderAnnotationLabel::updateData(const App::Property* prop) { - if (prop->is() && - strcmp(prop->getName(),"LabelText") == 0) { + if (prop->is() && strcmp(prop->getName(), "LabelText") == 0) { drawImage(static_cast(prop)->getValues()); } - else if (prop->is() && - strcmp(prop->getName(),"BasePosition") == 0) { + else if (prop->is() && strcmp(prop->getName(), "BasePosition") == 0) { Base::Vector3d v = static_cast(prop)->getValue(); - pBaseTranslation->translation.setValue(v.x,v.y,v.z); + pBaseTranslation->translation.setValue(v.x, v.y, v.z); } - else if (prop->is() && - strcmp(prop->getName(),"TextPosition") == 0) { + else if (prop->is() && strcmp(prop->getName(), "TextPosition") == 0) { Base::Vector3d v = static_cast(prop)->getValue(); - pCoords->point.set1Value(1, SbVec3f(v.x,v.y,v.z)); - pTextTranslation->translation.setValue(v.x,v.y,v.z); + pCoords->point.set1Value(1, SbVec3f(v.x, v.y, v.z)); + pTextTranslation->translation.setValue(v.x, v.y, v.z); } ViewProviderDocumentObject::updateData(prop); } -void ViewProviderAnnotationLabel::dragStartCallback(void *, SoDragger *) +void ViewProviderAnnotationLabel::dragStartCallback(void*, SoDragger*) { // This is called when a manipulator is about to manipulating - Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Transform")); + Gui::Application::Instance->activeDocument()->openCommand( + QT_TRANSLATE_NOOP("Command", "Transform") + ); } -void ViewProviderAnnotationLabel::dragFinishCallback(void *, SoDragger *) +void ViewProviderAnnotationLabel::dragFinishCallback(void*, SoDragger*) { // This is called when a manipulator has done manipulating Gui::Application::Instance->activeDocument()->commitCommand(); } -void ViewProviderAnnotationLabel::dragMotionCallback(void *data, SoDragger *drag) +void ViewProviderAnnotationLabel::dragMotionCallback(void* data, SoDragger* drag) { auto that = static_cast(data); const SbMatrix& mat = drag->getMotionMatrix(); App::DocumentObject* obj = that->getObject(); if (obj && obj->is()) { - static_cast(obj)->TextPosition.setValue(mat[3][0],mat[3][1],mat[3][2]); + static_cast(obj)->TextPosition.setValue(mat[3][0], mat[3][1], mat[3][2]); } } @@ -448,44 +454,46 @@ void ViewProviderAnnotationLabel::drawImage(const std::vector& s) int h = fm.height() * s.size(); const Base::Color& b = this->BackgroundColor.getValue(); QColor brush; - brush.setRgbF(b.r,b.g,b.b); + brush.setRgbF(b.r, b.g, b.b); const Base::Color& t = this->TextColor.getValue(); QColor front; - front.setRgbF(t.r,t.g,t.b); + front.setRgbF(t.r, t.g, t.b); QStringList lines; - for (const auto & it : s) { + for (const auto& it : s) { QString line = QString::fromUtf8(it.c_str()); w = std::max(w, QtTools::horizontalAdvance(fm, line)); lines << line; } - QImage image(w+10,h+10,QImage::Format_ARGB32_Premultiplied); + QImage image(w + 10, h + 10, QImage::Format_ARGB32_Premultiplied); image.fill(0x00000000); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing); bool drawFrame = this->Frame.getValue(); if (drawFrame) { - painter.setPen(QPen(QColor(0,0,127), 2, Qt::SolidLine, Qt::RoundCap, - Qt::RoundJoin)); + painter.setPen(QPen(QColor(0, 0, 127), 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); painter.setBrush(QBrush(brush, Qt::SolidPattern)); - QRectF rectangle(0.0, 0.0, w+10, h+10); + QRectF rectangle(0.0, 0.0, w + 10, h + 10); painter.drawRoundedRect(rectangle, 5, 5); } painter.setPen(front); Qt::Alignment align = Qt::AlignVCenter; - if (Justification.getValue() == 0) + if (Justification.getValue() == 0) { align = Qt::AlignVCenter | Qt::AlignLeft; - else if (Justification.getValue() == 1) + } + else if (Justification.getValue() == 1) { align = Qt::AlignVCenter | Qt::AlignRight; - else + } + else { align = Qt::AlignVCenter | Qt::AlignHCenter; + } QString text = lines.join(QLatin1String("\n")); painter.setFont(font); - painter.drawText(5,5,w,h,align,text); + painter.drawText(5, 5, w, h, align, text); painter.end(); SoSFImage sfimage; diff --git a/src/Gui/ViewProviderAnnotation.h b/src/Gui/ViewProviderAnnotation.h index ee4f0adea4..f5965f8aad 100644 --- a/src/Gui/ViewProviderAnnotation.h +++ b/src/Gui/ViewProviderAnnotation.h @@ -41,7 +41,7 @@ class SoCoordinate3; namespace Gui { -class GuiExport ViewProviderAnnotation : public ViewProviderDocumentObject +class GuiExport ViewProviderAnnotation: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderAnnotation); @@ -51,15 +51,15 @@ public: ~ViewProviderAnnotation() override; // Display properties - App::PropertyColor TextColor; - App::PropertyEnumeration Justification; - App::PropertyFloat FontSize; - App::PropertyFont FontName; - App::PropertyFloat LineSpacing; - App::PropertyAngle Rotation; - App::PropertyEnumeration RotationAxis; + App::PropertyColor TextColor; + App::PropertyEnumeration Justification; + App::PropertyFloat FontSize; + App::PropertyFont FontName; + App::PropertyFloat LineSpacing; + App::PropertyAngle Rotation; + App::PropertyEnumeration RotationAxis; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void updateData(const App::Property*) override; std::vector getDisplayModes() const override; void setDisplayMode(const char* ModeName) override; @@ -68,12 +68,12 @@ protected: void onChanged(const App::Property* prop) override; private: - SoFont * pFont; - SoText2 * pLabel; - SoAsciiText * pLabel3d; - SoBaseColor * pColor; - SoTranslation * pTranslation; - SoRotationXYZ * pRotationXYZ; + SoFont* pFont; + SoText2* pLabel; + SoAsciiText* pLabel3d; + SoBaseColor* pColor; + SoTranslation* pTranslation; + SoRotationXYZ* pRotationXYZ; static const char* JustificationEnums[]; static const char* RotationAxisEnums[]; @@ -85,7 +85,7 @@ private: * This approach gives a bit more flexibility since it can render arbitrary * annotations. */ -class GuiExport ViewProviderAnnotationLabel : public ViewProviderDocumentObject +class GuiExport ViewProviderAnnotationLabel: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderAnnotationLabel); @@ -95,14 +95,14 @@ public: ~ViewProviderAnnotationLabel() override; // Display properties - App::PropertyColor TextColor; - App::PropertyColor BackgroundColor; - App::PropertyEnumeration Justification; - App::PropertyFloat FontSize; - App::PropertyFont FontName; - App::PropertyBool Frame; + App::PropertyColor TextColor; + App::PropertyColor BackgroundColor; + App::PropertyEnumeration Justification; + App::PropertyFloat FontSize; + App::PropertyFont FontName; + App::PropertyBool Frame; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void updateData(const App::Property*) override; std::vector getDisplayModes() const override; void setDisplayMode(const char* ModeName) override; @@ -112,21 +112,21 @@ protected: void drawImage(const std::vector&); private: - static void dragStartCallback(void * data, SoDragger * d); - static void dragFinishCallback(void * data, SoDragger * d); - static void dragMotionCallback(void * data, SoDragger * d); + static void dragStartCallback(void* data, SoDragger* d); + static void dragFinishCallback(void* data, SoDragger* d); + static void dragMotionCallback(void* data, SoDragger* d); private: - SoCoordinate3 * pCoords; - SoImage * pImage; - SoBaseColor * pColor; - SoTranslation * pBaseTranslation; - TranslateManip * pTextTranslation; + SoCoordinate3* pCoords; + SoImage* pImage; + SoBaseColor* pColor; + SoTranslation* pBaseTranslation; + TranslateManip* pTextTranslation; static const char* JustificationEnums[]; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDERANNOTATION_H +#endif // GUI_VIEWPROVIDERANNOTATION_H diff --git a/src/Gui/ViewProviderBuilder.cpp b/src/Gui/ViewProviderBuilder.cpp index 30b59a5420..eb54318d76 100644 --- a/src/Gui/ViewProviderBuilder.cpp +++ b/src/Gui/ViewProviderBuilder.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -48,8 +47,9 @@ void ViewProviderBuilder::add(const Base::Type& prop, const Base::Type& view) ViewProvider* ViewProviderBuilder::create(const Base::Type& type) { std::map::iterator it = _prop_to_view.find(type); - if (it != _prop_to_view.end()) + if (it != _prop_to_view.end()) { return static_cast(it->second.createInstance()); + } return nullptr; } @@ -97,13 +97,13 @@ void ViewProviderColorBuilder::buildNodes(const App::Property* prop, std::vector { const auto color = static_cast(prop); const std::vector& val = color->getValues(); - unsigned long i=0; + unsigned long i = 0; auto material = new SoMaterial(); material->diffuseColor.setNum(val.size()); SbColor* colors = material->diffuseColor.startEditing(); - for (const auto & it : val) { + for (const auto& it : val) { colors[i].setValue(it.r, it.g, it.b); i++; } diff --git a/src/Gui/ViewProviderBuilder.h b/src/Gui/ViewProviderBuilder.h index 9a10276b47..5464d68299 100644 --- a/src/Gui/ViewProviderBuilder.h +++ b/src/Gui/ViewProviderBuilder.h @@ -30,8 +30,9 @@ class SoNode; -namespace App { - class Property; +namespace App +{ +class Property; } namespace Gui @@ -55,7 +56,7 @@ private: static std::map _prop_to_view; }; -class GuiExport ViewProviderColorBuilder : public ViewProviderBuilder +class GuiExport ViewProviderColorBuilder: public ViewProviderBuilder { public: /// Constructor @@ -64,7 +65,7 @@ public: void buildNodes(const App::Property*, std::vector&) const override; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDERBUILDER_H +#endif // GUI_VIEWPROVIDERBUILDER_H diff --git a/src/Gui/ViewProviderCoordinateSystem.cpp b/src/Gui/ViewProviderCoordinateSystem.cpp index ba2a565f18..0b454efc86 100644 --- a/src/Gui/ViewProviderCoordinateSystem.cpp +++ b/src/Gui/ViewProviderCoordinateSystem.cpp @@ -22,11 +22,10 @@ ***************************************************************************/ - -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -64,7 +63,8 @@ ViewProviderCoordinateSystem::ViewProviderCoordinateSystem() pcRoot->insertChild(lm, 0); } -ViewProviderCoordinateSystem::~ViewProviderCoordinateSystem() { +ViewProviderCoordinateSystem::~ViewProviderCoordinateSystem() +{ pcGroupChildren->unref(); pcGroupChildren = nullptr; } @@ -97,13 +97,14 @@ void ViewProviderCoordinateSystem::attach(App::DocumentObject* pcObject) std::vector ViewProviderCoordinateSystem::getDisplayModes() const { - return { "Base" }; + return {"Base"}; } void ViewProviderCoordinateSystem::setDisplayMode(const char* ModeName) { - if (strcmp(ModeName, "Base") == 0) + if (strcmp(ModeName, "Base") == 0) { setDisplayMaskMode("Base"); + } ViewProviderDocumentObject::setDisplayMode(ModeName); } @@ -118,7 +119,7 @@ void ViewProviderCoordinateSystem::setTemporaryVisibility(DatumElements elements try { // Remember & Set axis visibility - for(App::DocumentObject* obj : lcs->axes()) { + for (App::DocumentObject* obj : lcs->axes()) { if (auto vp = Gui::Application::Instance->getViewProvider(obj)) { if (saveState) { tempVisMap[vp] = vp->isVisible(); @@ -128,7 +129,7 @@ void ViewProviderCoordinateSystem::setTemporaryVisibility(DatumElements elements } // Remember & Set plane visibility - for(App::DocumentObject* obj : lcs->planes()) { + for (App::DocumentObject* obj : lcs->planes()) { if (auto vp = Gui::Application::Instance->getViewProvider(obj)) { if (saveState) { tempVisMap[vp] = vp->isVisible(); @@ -146,26 +147,28 @@ void ViewProviderCoordinateSystem::setTemporaryVisibility(DatumElements elements vp->setVisible(elements.testFlag(DatumElement::Origin)); } } - catch (const Base::Exception &ex) { - Base::Console().error ("%s\n", ex.what() ); + catch (const Base::Exception& ex) { + Base::Console().error("%s\n", ex.what()); } // Remember & Set self visibility tempVisMap[this] = isVisible(); setVisible(true); - } -void ViewProviderCoordinateSystem::resetTemporaryVisibility() { - for(std::pair pair : tempVisMap) { +void ViewProviderCoordinateSystem::resetTemporaryVisibility() +{ + for (std::pair pair : tempVisMap) { pair.first->setVisible(pair.second); } - tempVisMap.clear (); + tempVisMap.clear(); } double ViewProviderCoordinateSystem::defaultSize() { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); return hGrp->GetFloat("DatumsSize", 25); } @@ -182,7 +185,8 @@ void ViewProviderCoordinateSystem::setPlaneLabelVisibility(bool val) } for (auto* plane : lcs->planes()) { auto* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(plane)); + Gui::Application::Instance->getViewProvider(plane) + ); if (vp) { vp->setLabelVisibility(val); } @@ -198,7 +202,8 @@ void ViewProviderCoordinateSystem::applyDatumObjects(const DatumObjectFunc& func const auto& objs = lcs->OriginFeatures.getValues(); for (auto* obj : objs) { auto* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(obj)); + Gui::Application::Instance->getViewProvider(obj) + ); if (vp) { func(vp); } @@ -207,19 +212,15 @@ void ViewProviderCoordinateSystem::applyDatumObjects(const DatumObjectFunc& func void ViewProviderCoordinateSystem::setTemporaryScale(double factor) { - applyDatumObjects([factor](ViewProviderDatum* vp) { - vp->setTemporaryScale(factor); - }); + applyDatumObjects([factor](ViewProviderDatum* vp) { vp->setTemporaryScale(factor); }); } void ViewProviderCoordinateSystem::resetTemporarySize() { - applyDatumObjects([](ViewProviderDatum* vp) { - vp->resetTemporarySize(); - }); + applyDatumObjects([](ViewProviderDatum* vp) { vp->resetTemporarySize(); }); } -bool ViewProviderCoordinateSystem::onDelete(const std::vector &) +bool ViewProviderCoordinateSystem::onDelete(const std::vector&) { auto* lcs = getObject(); if (!lcs) { @@ -234,9 +235,13 @@ bool ViewProviderCoordinateSystem::onDelete(const std::vector &) auto objs = lcs->OriginFeatures.getValues(); lcs->OriginFeatures.setValues({}); - for (auto obj: objs ) { - Gui::Command::doCommand( Gui::Command::Doc, "App.getDocument(\"%s\").removeObject(\"%s\")", - obj->getDocument()->getName(), obj->getNameInDocument() ); + for (auto obj : objs) { + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument(\"%s\").removeObject(\"%s\")", + obj->getDocument()->getName(), + obj->getNameInDocument() + ); } return true; diff --git a/src/Gui/ViewProviderCoordinateSystem.h b/src/Gui/ViewProviderCoordinateSystem.h index 1b3704799b..bdb6ac0de1 100644 --- a/src/Gui/ViewProviderCoordinateSystem.h +++ b/src/Gui/ViewProviderCoordinateSystem.h @@ -31,7 +31,8 @@ #include "ViewProviderGeoFeatureGroup.h" -namespace Gui { +namespace Gui +{ class Document; class ViewProviderDatum; @@ -47,7 +48,7 @@ enum class DatumElement using DatumElements = Base::Flags; -class GuiExport ViewProviderCoordinateSystem : public ViewProviderGeoFeatureGroup +class GuiExport ViewProviderCoordinateSystem: public ViewProviderGeoFeatureGroup { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderCoordinateSystem); @@ -62,7 +63,10 @@ public: std::vector claimChildren() const override; std::vector claimChildren3D() const override; - SoGroup* getChildRoot() const override {return pcGroupChildren;} + SoGroup* getChildRoot() const override + { + return pcGroupChildren; + } void attach(App::DocumentObject* pcObject) override; std::vector getDisplayModes() const override; @@ -74,11 +78,11 @@ public: */ ///@{ /// Set temporary visibility of some of origin's objects e.g. while rotating or mirroring - void setTemporaryVisibility (DatumElements elements); + void setTemporaryVisibility(DatumElements elements); /// Returns true if the origin in temporary visibility mode - bool isTemporaryVisibility (); + bool isTemporaryVisibility(); /// Reset the visibility - void resetTemporaryVisibility (); + void resetTemporaryVisibility(); ///@} void setTemporaryScale(double factor); @@ -86,7 +90,8 @@ public: void setPlaneLabelVisibility(bool val); - bool canDragObjects() const override { + bool canDragObjects() const override + { return false; } @@ -100,21 +105,20 @@ public: static const uint32_t defaultColor = 0x3296faff; protected: - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; private: using DatumObjectFunc = std::function; void applyDatumObjects(const DatumObjectFunc& func); private: - SoGroup *pcGroupChildren; + SoGroup* pcGroupChildren; std::map tempVisMap; }; -} // namespace Gui +} // namespace Gui ENABLE_BITMASK_OPERATORS(Gui::DatumElement) -#endif // GUI_VIEWPROVIDER_ViewProviderOrigin_H - +#endif // GUI_VIEWPROVIDER_ViewProviderOrigin_H diff --git a/src/Gui/ViewProviderDatum.cpp b/src/Gui/ViewProviderDatum.cpp index 4dd0683308..0be3c7fba0 100644 --- a/src/Gui/ViewProviderDatum.cpp +++ b/src/Gui/ViewProviderDatum.cpp @@ -20,13 +20,13 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -44,11 +44,13 @@ using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderDatum, Gui::ViewProviderGeometryObject) -ViewProviderDatum::ViewProviderDatum() { +ViewProviderDatum::ViewProviderDatum() +{ // Set default color for origin (light-blue) ShapeAppearance.setDiffuseColor(ViewProviderCoordinateSystem::defaultColor); Transparency.setValue(0); - BoundingBox.setStatus(App::Property::Hidden, true); // Hide Boundingbox from the user due to it doesn't make sense + BoundingBox.setStatus(App::Property::Hidden, true); // Hide Boundingbox from the user due to it + // doesn't make sense // Create node for scaling the origin soScale = new SoShapeScale(); @@ -61,7 +63,8 @@ ViewProviderDatum::ViewProviderDatum() { } -ViewProviderDatum::~ViewProviderDatum() { +ViewProviderDatum::~ViewProviderDatum() +{ pRoot->unref(); } @@ -84,7 +87,9 @@ void ViewProviderDatum::attach(App::DocumentObject* pcObject) // Setup font size auto font = new SoFont(); - static const float size = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")->GetFloat("DatumFontSize", 15.0); + static const float size = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetFloat("DatumFontSize", 15.0); font->size.setValue(size); sep->addChild(font); @@ -114,7 +119,7 @@ void ViewProviderDatum::attach(App::DocumentObject* pcObject) // Style for hidden lines style = new SoDrawStyle(); style->lineWidth = lineThickness; - style->linePattern.setValue(0xFF00); // (dash-skip) + style->linePattern.setValue(0xFF00); // (dash-skip) hidden->addChild(style); // Hidden lines @@ -140,13 +145,14 @@ void ViewProviderDatum::setTemporaryScale(double factor) void ViewProviderDatum::resetTemporarySize() { float sz = App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetFloat("LocalCoordinateSystemSize", 1.0); // NOLINT + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetFloat("LocalCoordinateSystemSize", 1.0); // NOLINT soScale->scaleFactor = sz; } -void ViewProviderDatum::onChanged(const App::Property* prop) { +void ViewProviderDatum::onChanged(const App::Property* prop) +{ ViewProviderGeometryObject::onChanged(prop); } @@ -166,8 +172,9 @@ void ViewProviderDatum::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode(ModeName); } -bool ViewProviderDatum::onDelete(const std::vector&) { - auto feat = static_cast (getObject()); +bool ViewProviderDatum::onDelete(const std::vector&) +{ + auto feat = static_cast(getObject()); // Forbid deletion if there is an origin this feature belongs to return !feat->getLCS(); } diff --git a/src/Gui/ViewProviderDatum.h b/src/Gui/ViewProviderDatum.h index 6ae24abae3..188bf7f88a 100644 --- a/src/Gui/ViewProviderDatum.h +++ b/src/Gui/ViewProviderDatum.h @@ -30,47 +30,52 @@ class SoScale; namespace Gui { - class SoShapeScale; +class SoShapeScale; - /** - * View provider associated with an App::DatumElement. - */ - class GuiExport ViewProviderDatum : public ViewProviderGeometryObject { - PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderDatum); +/** + * View provider associated with an App::DatumElement. + */ +class GuiExport ViewProviderDatum: public ViewProviderGeometryObject +{ + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderDatum); - public: - ViewProviderDatum(); - ~ViewProviderDatum() override; +public: + ViewProviderDatum(); + ~ViewProviderDatum() override; - /// Get point derived classes will add their specific stuff - SoSeparator* getDatumRoot() const { return pRoot; } + /// Get point derived classes will add their specific stuff + SoSeparator* getDatumRoot() const + { + return pRoot; + } - void attach(App::DocumentObject*) override; - std::vector getDisplayModes() const override; - void setDisplayMode(const char* ModeName) override; + void attach(App::DocumentObject*) override; + std::vector getDisplayModes() const override; + void setDisplayMode(const char* ModeName) override; - /// @name Suppress ViewProviderGeometryObject's behaviour - ///@{ - bool setEdit(int) override - { - return false; - } - void unsetEdit(int) override - { } - ///@} + /// @name Suppress ViewProviderGeometryObject's behaviour + ///@{ + bool setEdit(int) override + { + return false; + } + void unsetEdit(int) override + {} + ///@} - void setTemporaryScale(double factor); - void resetTemporarySize(); + void setTemporaryScale(double factor); + void resetTemporarySize(); - protected: - void onChanged(const App::Property* prop) override; - bool onDelete(const std::vector&) override; - protected: - SoSeparator* pRoot; - SoShapeScale* soScale; - double lineThickness; - }; +protected: + void onChanged(const App::Property* prop) override; + bool onDelete(const std::vector&) override; -} /* Gui */ +protected: + SoSeparator* pRoot; + SoShapeScale* soScale; + double lineThickness; +}; + +} // namespace Gui #endif /* end of include guard: VIEWPROVIDEDATUM_H_BYJRZNDL */ diff --git a/src/Gui/ViewProviderDocumentObject.cpp b/src/Gui/ViewProviderDocumentObject.cpp index 3f6eabea10..0090e3c3a7 100644 --- a/src/Gui/ViewProviderDocumentObject.cpp +++ b/src/Gui/ViewProviderDocumentObject.cpp @@ -21,15 +21,14 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -58,22 +57,27 @@ PROPERTY_SOURCE(Gui::ViewProviderDocumentObject, Gui::ViewProvider) ViewProviderDocumentObject::ViewProviderDocumentObject() { - static const char *dogroup = "Display Options"; - static const char *sgroup = "Selection"; + static const char* dogroup = "Display Options"; + static const char* sgroup = "Selection"; ADD_PROPERTY_TYPE(DisplayMode, ((long)0), dogroup, App::Prop_None, "Set the display mode"); ADD_PROPERTY_TYPE(Visibility, (true), dogroup, App::Prop_None, "Show the object in the 3d view"); ADD_PROPERTY_TYPE(ShowInTree, (true), dogroup, App::Prop_None, "Show the object in the tree view"); ADD_PROPERTY_TYPE(SelectionStyle, ((long)0), sgroup, App::Prop_None, "Set the object selection style"); - static const char *SelectionStyleEnum[] = {"Shape","BoundBox",nullptr}; + static const char* SelectionStyleEnum[] = {"Shape", "BoundBox", nullptr}; SelectionStyle.setEnums(SelectionStyleEnum); - static const char* OnTopEnum[]= {"Disabled","Enabled","Object","Element",nullptr}; - ADD_PROPERTY_TYPE(OnTopWhenSelected,((long int)0), sgroup, App::Prop_None, - "Enabled: Display the object on top of any other object when selected\n" - "Object: On top only if the whole object is selected\n" - "Element: On top only if some sub-element of the object is selected"); + static const char* OnTopEnum[] = {"Disabled", "Enabled", "Object", "Element", nullptr}; + ADD_PROPERTY_TYPE( + OnTopWhenSelected, + ((long int)0), + sgroup, + App::Prop_None, + "Enabled: Display the object on top of any other object when selected\n" + "Object: On top only if the whole object is selected\n" + "Element: On top only if some sub-element of the object is selected" + ); OnTopWhenSelected.setEnums(OnTopEnum); sPixmap = "Feature"; @@ -95,15 +99,17 @@ void ViewProviderDocumentObject::startRestoring() { hide(); auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionStartRestoring(); + } } void ViewProviderDocumentObject::finishRestoring() { auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionFinishRestoring(); + } } bool ViewProviderDocumentObject::isAttachedToDocument() const @@ -122,29 +128,38 @@ const char* ViewProviderDocumentObject::detachFromDocument() bool ViewProviderDocumentObject::removeDynamicProperty(const char* name) { App::Property* prop = getDynamicPropertyByName(name); - if(!prop || prop->testStatus(App::Property::LockDynamic)) + if (!prop || prop->testStatus(App::Property::LockDynamic)) { return false; + } // transactions of view providers are also managed in App::Document. App::DocumentObject* docobject = getObject(); App::Document* document = docobject ? docobject->getDocument() : nullptr; - if (document) + if (document) { document->addOrRemovePropertyOfObject(this, prop, false); + } return ViewProvider::removeDynamicProperty(name); } App::Property* ViewProviderDocumentObject::addDynamicProperty( - const char* type, const char* name, const char* group, const char* doc, - short attr, bool ro, bool hidden) + const char* type, + const char* name, + const char* group, + const char* doc, + short attr, + bool ro, + bool hidden +) { - auto prop = ViewProvider::addDynamicProperty(type,name,group,doc,attr,ro,hidden); - if(prop) { + auto prop = ViewProvider::addDynamicProperty(type, name, group, doc, attr, ro, hidden); + if (prop) { // transactions of view providers are also managed in App::Document. App::DocumentObject* docobject = getObject(); App::Document* document = docobject ? docobject->getDocument() : nullptr; - if (document) + if (document) { document->addOrRemovePropertyOfObject(this, prop, true); + } } return prop; } @@ -174,10 +189,8 @@ void ViewProviderDocumentObject::onChanged(const App::Property* prop) Visibility.getValue() ? show() : hide(); Visibility.setStatus(App::Property::User2, false); } - if (!Visibility.testStatus(App::Property::User1) - && getObject() - && getObject()->Visibility.getValue()!=Visibility.getValue()) - { + if (!Visibility.testStatus(App::Property::User1) && getObject() + && getObject()->Visibility.getValue() != Visibility.getValue()) { // Changing the visibility of a document object will automatically set // the document modified but if the 'TouchDocument' flag is not set then // this is undesired behaviour. So, if this change marks the document as @@ -188,8 +201,10 @@ void ViewProviderDocumentObject::onChanged(const App::Property* prop) // property being changed due to the change of Visibility here. // Temporary setting the Visibility property as 'NoModify' is // the proper way. - Base::ObjectStatusLocker guard( - App::Property::NoModify, &Visibility); + Base::ObjectStatusLocker guard( + App::Property::NoModify, + &Visibility + ); // bool mod = false; // if (pcDocument) // mod = pcDocument->isModified(); @@ -203,18 +218,18 @@ void ViewProviderDocumentObject::onChanged(const App::Property* prop) } } else if (prop == &SelectionStyle) { - if(getRoot()->isOfType(SoFCSelectionRoot::getClassTypeId())) { + if (getRoot()->isOfType(SoFCSelectionRoot::getClassTypeId())) { static_cast(getRoot())->selectionStyle = SelectionStyle.getValue() - ? SoFCSelectionRoot::Box : SoFCSelectionRoot::Full; + ? SoFCSelectionRoot::Box + : SoFCSelectionRoot::Full; } } - if (prop && !prop->testStatus(App::Property::NoModify) - && pcDocument - && !pcDocument->isModified() - && testStatus(Gui::ViewStatus::TouchDocument)) { - if (prop) + if (prop && !prop->testStatus(App::Property::NoModify) && pcDocument + && !pcDocument->isModified() && testStatus(Gui::ViewStatus::TouchDocument)) { + if (prop) { FC_LOG(prop->getFullName() << " changed"); + } pcDocument->setModified(true); } @@ -239,8 +254,9 @@ bool ViewProviderDocumentObject::isShowable() const void ViewProviderDocumentObject::setShowable(bool enable) { - if (_Showable == enable) + if (_Showable == enable) { return; + } _Showable = enable; int which = getModeSwitch()->whichChild.getValue(); @@ -248,8 +264,9 @@ void ViewProviderDocumentObject::setShowable(bool enable) setModeSwitch(); } else if (!_Showable) { - if (which >= 0) + if (which >= 0) { ViewProvider::hide(); + } } } @@ -269,24 +286,26 @@ void ViewProviderDocumentObject::addDefaultAction(QMenu* menu, const QString& te QAction* act = menu->addAction(text); act->setData(QVariant((int)ViewProvider::Default)); auto func = new Gui::ActionFunction(menu); - func->trigger(act, [this](){ - this->startDefaultEditMode(); - }); + func->trigger(act, [this]() { this->startDefaultEditMode(); }); } -void ViewProviderDocumentObject::setModeSwitch() { - if(isShowable()) +void ViewProviderDocumentObject::setModeSwitch() +{ + if (isShowable()) { ViewProvider::setModeSwitch(); + } } void ViewProviderDocumentObject::show() { - if(TreeWidget::isObjectShowable(getObject())) + if (TreeWidget::isObjectShowable(getObject())) { ViewProvider::show(); + } else { Visibility.setValue(false); - if(getObject()) + if (getObject()) { getObject()->Visibility.setValue(false); + } return; } @@ -305,88 +324,107 @@ const char* ViewProviderDocumentObject::getTransactionText() const void ViewProviderDocumentObject::updateView() { - if(!pcObject || testStatus(ViewStatus::UpdatingView)) + if (!pcObject || testStatus(ViewStatus::UpdatingView)) { return; + } - Base::ObjectStatusLocker lock(ViewStatus::UpdatingView,this); + Base::ObjectStatusLocker lock(ViewStatus::UpdatingView, this); // Disable object visibility syncing - Base::ObjectStatusLocker lock2(App::Property::User1, &Visibility); + Base::ObjectStatusLocker lock2( + App::Property::User1, + &Visibility + ); std::map Map; pcObject->getPropertyMap(Map); // Hide the object temporarily to speed up the update bool vis = ViewProvider::isShow(); - if (vis) ViewProvider::hide(); - for (const auto & it : Map) { + if (vis) { + ViewProvider::hide(); + } + for (const auto& it : Map) { updateData(it.second); } - if (vis && Visibility.getValue()) ViewProvider::show(); + if (vis && Visibility.getValue()) { + ViewProvider::show(); + } } -void ViewProviderDocumentObject::attach(App::DocumentObject *pcObj) +void ViewProviderDocumentObject::attach(App::DocumentObject* pcObj) { // save Object pointer pcObject = pcObj; - if(pcObj && pcObj->isAttachedToDocument() && - Visibility.getValue()!=pcObj->Visibility.getValue()) + if (pcObj && pcObj->isAttachedToDocument() + && Visibility.getValue() != pcObj->Visibility.getValue()) { pcObj->Visibility.setValue(Visibility.getValue()); + } // Retrieve the supported display modes of the view provider aDisplayModesArray = this->getDisplayModes(); - if (aDisplayModesArray.empty()) + if (aDisplayModesArray.empty()) { aDisplayModesArray.emplace_back(""); + } // We must collect the const char* of the strings and give it to PropertyEnumeration, // but we are still responsible for them, i.e. the property class must not delete the literals. - //for (auto it = aDisplayModesArray.begin(); it != aDisplayModesArray.end(); ++it) { - for (const auto & it : aDisplayModesArray) { - aDisplayEnumsArray.push_back( it.c_str() ); + // for (auto it = aDisplayModesArray.begin(); it != aDisplayModesArray.end(); ++it) { + for (const auto& it : aDisplayModesArray) { + aDisplayEnumsArray.push_back(it.c_str()); } - aDisplayEnumsArray.push_back(nullptr); // null termination + aDisplayEnumsArray.push_back(nullptr); // null termination DisplayMode.setEnums(&(aDisplayEnumsArray[0])); - if(!isRestoring()) { + if (!isRestoring()) { // set the active mode const char* defmode = this->getDefaultDisplayMode(); - if (defmode) + if (defmode) { DisplayMode.setValue(defmode); + } } - //attach the extensions + // attach the extensions auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionAttach(pcObj); + } } -void ViewProviderDocumentObject::reattach(App::DocumentObject *pcObj) { +void ViewProviderDocumentObject::reattach(App::DocumentObject* pcObj) +{ auto vector = getExtensionsDerivedFromType(); - for (Gui::ViewProviderExtension* ext : vector) + for (Gui::ViewProviderExtension* ext : vector) { ext->extensionReattach(pcObj); + } } void ViewProviderDocumentObject::update(const App::Property* prop) { // bypass view provider update to always allow changing visibility from // document object - if(prop == &getObject()->Visibility) { - if(!isRestoring() && Visibility.getValue()!=getObject()->Visibility.getValue()) + if (prop == &getObject()->Visibility) { + if (!isRestoring() && Visibility.getValue() != getObject()->Visibility.getValue()) { Visibility.setValue(!Visibility.getValue()); - } else { + } + } + else { // Disable object visibility syncing - Base::ObjectStatusLocker - guard(App::Property::User1, &Visibility); + Base::ObjectStatusLocker guard( + App::Property::User1, + &Visibility + ); ViewProvider::update(prop); } } Gui::Document* ViewProviderDocumentObject::getDocument() const { - if(!pcObject) + if (!pcObject) { throw Base::RuntimeError("View provider detached"); + } if (pcDocument) { return pcDocument; } @@ -398,8 +436,9 @@ Gui::Document* ViewProviderDocumentObject::getDocument() const Gui::MDIView* ViewProviderDocumentObject::getActiveView() const { - if(!pcObject) + if (!pcObject) { throw Base::RuntimeError("View provider detached"); + } if (!pcObject->isAttachedToDocument()) { // Check if view provider is attached to a document as an annotation @@ -419,8 +458,9 @@ Gui::MDIView* ViewProviderDocumentObject::getActiveView() const Gui::MDIView* ViewProviderDocumentObject::getEditingView() const { - if(!pcObject) + if (!pcObject) { throw Base::RuntimeError("View provider detached"); + } App::Document* pAppDoc = pcObject->getDocument(); Gui::Document* pGuiDoc = Gui::Application::Instance->getDocument(pAppDoc); return pGuiDoc->getEditingViewOfViewProvider(const_cast(this)); @@ -428,12 +468,15 @@ Gui::MDIView* ViewProviderDocumentObject::getEditingView() const Gui::MDIView* ViewProviderDocumentObject::getInventorView() const { - if(!pcObject) + if (!pcObject) { throw Base::RuntimeError("View provider detached"); + } App::Document* pAppDoc = pcObject->getDocument(); Gui::Document* pGuiDoc = Gui::Application::Instance->getDocument(pAppDoc); - Gui::MDIView* mdi = pGuiDoc->getEditingViewOfViewProvider(const_cast(this)); + Gui::MDIView* mdi = pGuiDoc->getEditingViewOfViewProvider( + const_cast(this) + ); if (!mdi) { mdi = pGuiDoc->getViewOfViewProvider(const_cast(this)); } @@ -443,8 +486,9 @@ Gui::MDIView* ViewProviderDocumentObject::getInventorView() const Gui::MDIView* ViewProviderDocumentObject::getViewOfNode(SoNode* node) const { - if(!pcObject) + if (!pcObject) { throw Base::RuntimeError("View provider detached"); + } App::Document* pAppDoc = pcObject->getDocument(); Gui::Document* pGuiDoc = Gui::Application::Instance->getDocument(pAppDoc); return pGuiDoc->getViewOfNode(node); @@ -452,8 +496,9 @@ Gui::MDIView* ViewProviderDocumentObject::getViewOfNode(SoNode* node) const SoNode* ViewProviderDocumentObject::findFrontRootOfType(const SoType& type) const { - if(!pcObject) + if (!pcObject) { return nullptr; + } // first get the document this object is part of and get its GUI counterpart App::Document* pAppDoc = pcObject->getDocument(); Gui::Document* pGuiDoc = Gui::Application::Instance->getDocument(pAppDoc); @@ -464,21 +509,23 @@ SoNode* ViewProviderDocumentObject::findFrontRootOfType(const SoType& type) cons // search in all view providers for the node type std::vector obj = pAppDoc->getObjects(); - for (auto & it : obj) { + for (auto& it : obj) { const ViewProvider* vp = pGuiDoc->getViewProvider(it); // Ignore 'this' view provider. It could also happen that vp is 0, e.g. when // several objects have been added to the App::Document before notifying the // Gui::Document - if (!vp || vp == this) + if (!vp || vp == this) { continue; + } SoSeparator* front = vp->getFrontRoot(); - //if (front && front->getTypeId() == type) - // return front; + // if (front && front->getTypeId() == type) + // return front; if (front) { searchAction.apply(front); SoPath* path = searchAction.getPath(); - if (path) + if (path) { return path->getTail(); + } } } @@ -489,11 +536,13 @@ void ViewProviderDocumentObject::setActiveMode() { if (DisplayMode.isValid()) { const char* mode = DisplayMode.getValueAsString(); - if (mode) + if (mode) { setDisplayMode(mode); + } } - if (!Visibility.getValue()) + if (!Visibility.getValue()) { ViewProvider::hide(); + } } bool ViewProviderDocumentObject::canDelete(App::DocumentObject* obj) const @@ -501,203 +550,242 @@ bool ViewProviderDocumentObject::canDelete(App::DocumentObject* obj) const Q_UNUSED(obj); auto* o = getObject(); return o->hasExtension(App::GroupExtension::getExtensionClassTypeId()) - || o->isDerivedFrom(); + || o->isDerivedFrom(); } PyObject* ViewProviderDocumentObject::getPyObject() { - if (!pyViewObject) + if (!pyViewObject) { pyViewObject = new ViewProviderDocumentObjectPy(this); + } pyViewObject->IncRef(); return pyViewObject; } -bool ViewProviderDocumentObject::canDropObjectEx(App::DocumentObject* obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) const +bool ViewProviderDocumentObject::canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements +) const { auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector){ - if(ext->extensionCanDropObjectEx(obj,owner,subname,elements)) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionCanDropObjectEx(obj, owner, subname, elements)) { return true; + } } - if(obj && obj->getDocument()!=getObject()->getDocument()) + if (obj && obj->getDocument() != getObject()->getDocument()) { return false; + } return canDropObject(obj); } -int ViewProviderDocumentObject::replaceObject( - App::DocumentObject *oldObj, App::DocumentObject *newObj) +int ViewProviderDocumentObject::replaceObject(App::DocumentObject* oldObj, App::DocumentObject* newObj) { - if(!oldObj || !oldObj->isAttachedToDocument() - || !newObj || !newObj->isAttachedToDocument()) - { - FC_THROWM(Base::RuntimeError,"Invalid object"); + if (!oldObj || !oldObj->isAttachedToDocument() || !newObj || !newObj->isAttachedToDocument()) { + FC_THROWM(Base::RuntimeError, "Invalid object"); } auto obj = getObject(); - if(!obj || !obj->isAttachedToDocument()) - FC_THROWM(Base::RuntimeError,"View provider not attached"); - - int res = ViewProvider::replaceObject(oldObj,newObj); - if(res>=0) - return res; - - std::vector > > propChanges; - std::vector props; - obj->getPropertyList(props); - for(auto prop : props) { - auto linkProp = freecad_cast(prop); - if(!linkProp) - continue; - std::unique_ptr copy(linkProp->CopyOnLinkReplace(obj, oldObj,newObj)); - if(!copy) - continue; - propChanges.emplace_back(prop,std::move(copy)); + if (!obj || !obj->isAttachedToDocument()) { + FC_THROWM(Base::RuntimeError, "View provider not attached"); } - if(propChanges.empty()) + int res = ViewProvider::replaceObject(oldObj, newObj); + if (res >= 0) { + return res; + } + + std::vector>> propChanges; + std::vector props; + obj->getPropertyList(props); + for (auto prop : props) { + auto linkProp = freecad_cast(prop); + if (!linkProp) { + continue; + } + std::unique_ptr copy(linkProp->CopyOnLinkReplace(obj, oldObj, newObj)); + if (!copy) { + continue; + } + propChanges.emplace_back(prop, std::move(copy)); + } + + if (propChanges.empty()) { return 0; + } // Global search for affected links - for(auto doc : App::GetApplication().getDocuments()) { - for(auto o : doc->getObjects()) { - if(o == obj) + for (auto doc : App::GetApplication().getDocuments()) { + for (auto o : doc->getObjects()) { + if (o == obj) { continue; + } std::vector props; o->getPropertyList(props); - for(auto prop : props) { + for (auto prop : props) { auto linkProp = freecad_cast(prop); - if(!linkProp) + if (!linkProp) { continue; - std::unique_ptr copy(linkProp->CopyOnLinkReplace(obj,oldObj,newObj)); - if(!copy) + } + std::unique_ptr copy(linkProp->CopyOnLinkReplace(obj, oldObj, newObj)); + if (!copy) { continue; - propChanges.emplace_back(App::DocumentObjectT(prop),std::move(copy)); + } + propChanges.emplace_back(App::DocumentObjectT(prop), std::move(copy)); } } } - for(auto &v : propChanges) { + for (auto& v : propChanges) { auto prop = v.first.getProperty(); - if(prop) + if (prop) { prop->Paste(*v.second.get()); + } } return 1; } -bool ViewProviderDocumentObject::showInTree() const { +bool ViewProviderDocumentObject::showInTree() const +{ return ShowInTree.getValue(); } -bool ViewProviderDocumentObject::getElementPicked(const SoPickedPoint *pp, std::string &subname) const +bool ViewProviderDocumentObject::getElementPicked(const SoPickedPoint* pp, std::string& subname) const { auto vector = getExtensionsDerivedFromType(); - for(Gui::ViewProviderExtension* ext : vector) - if(ext->extensionGetElementPicked(pp,subname)) + for (Gui::ViewProviderExtension* ext : vector) { + if (ext->extensionGetElementPicked(pp, subname)) { return true; + } + } auto childRoot = getChildRoot(); int idx; - if(!childRoot || - (idx=pcModeSwitch->whichChild.getValue())<0 || - pcModeSwitch->getChild(idx)!=childRoot) - { - return ViewProvider::getElementPicked(pp,subname); + if (!childRoot || (idx = pcModeSwitch->whichChild.getValue()) < 0 + || pcModeSwitch->getChild(idx) != childRoot) { + return ViewProvider::getElementPicked(pp, subname); } SoPath* path = pp->getPath(); idx = path->findNode(childRoot); - if(idx<0 || idx+1>=path->getLength()) + if (idx < 0 || idx + 1 >= path->getLength()) { return false; - auto vp = getDocument()->getViewProvider(path->getNode(idx+1)); - if(!vp) + } + auto vp = getDocument()->getViewProvider(path->getNode(idx + 1)); + if (!vp) { return false; + } auto obj = vp->getObject(); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return false; + } std::ostringstream str; str << obj->getNameInDocument() << '.'; - if(vp->getElementPicked(pp,subname)) + if (vp->getElementPicked(pp, subname)) { str << subname; + } subname = str.str(); return true; } -bool ViewProviderDocumentObject::getDetailPath(const char *subname, SoFullPath *path, bool append, SoDetail *&det) const +bool ViewProviderDocumentObject::getDetailPath( + const char* subname, + SoFullPath* path, + bool append, + SoDetail*& det +) const { auto len = path->getLength(); - if(!append && len>=2) + if (!append && len >= 2) { len -= 2; - if(ViewProvider::getDetailPath(subname,path,append,det)) { - if(det || !subname || !*subname) + } + if (ViewProvider::getDetailPath(subname, path, append, det)) { + if (det || !subname || !*subname) { return true; + } } - if(det) { + if (det) { delete det; det = nullptr; } - const char *dot = strchr(subname,'.'); - if(!dot) + const char* dot = strchr(subname, '.'); + if (!dot) { return false; + } auto obj = getObject(); - if(!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { return false; - auto sobj = obj->getSubObject(std::string(subname,dot-subname+1).c_str()); - if(!sobj) + } + auto sobj = obj->getSubObject(std::string(subname, dot - subname + 1).c_str()); + if (!sobj) { return false; + } auto vp = Application::Instance->getViewProvider(sobj); - if(!vp) + if (!vp) { return false; + } auto childRoot = getChildRoot(); - if(!childRoot) + if (!childRoot) { path->truncate(len); + } else { auto idx = pcModeSwitch->whichChild.getValue(); - if(idx < 0 || pcModeSwitch->getChild(idx)!=childRoot) + if (idx < 0 || pcModeSwitch->getChild(idx) != childRoot) { return false; + } path->append(childRoot); } bool ret = false; - if(path->getLength()) { - SoNode * tail = path->getTail(); - const SoChildList * children = tail->getChildren(); - if(children && children->find(vp->getRoot())>=0) - ret = vp->getDetailPath(dot+1,path,true,det); + if (path->getLength()) { + SoNode* tail = path->getTail(); + const SoChildList* children = tail->getChildren(); + if (children && children->find(vp->getRoot()) >= 0) { + ret = vp->getDetailPath(dot + 1, path, true, det); + } } return ret; } -void ViewProviderDocumentObject::onPropertyStatusChanged( - const App::Property &prop, unsigned long oldStatus) +void ViewProviderDocumentObject::onPropertyStatusChanged(const App::Property& prop, unsigned long oldStatus) { (void)oldStatus; - if(!App::Document::isAnyRestoring() && pcObject && pcObject->getDocument()) - pcObject->getDocument()->signalChangePropertyEditor(*pcObject->getDocument(),prop); + if (!App::Document::isAnyRestoring() && pcObject && pcObject->getDocument()) { + pcObject->getDocument()->signalChangePropertyEditor(*pcObject->getDocument(), prop); + } } -ViewProviderDocumentObject *ViewProviderDocumentObject::getLinkedViewProvider( - std::string *subname, bool recursive) const +ViewProviderDocumentObject* ViewProviderDocumentObject::getLinkedViewProvider( + std::string* subname, + bool recursive +) const { (void)subname; auto self = const_cast(this); - if(!pcObject || !pcObject->isAttachedToDocument()) + if (!pcObject || !pcObject->isAttachedToDocument()) { return self; + } auto linked = pcObject->getLinkedObject(recursive); - if(!linked || linked == pcObject) + if (!linked || linked == pcObject) { return self; + } auto res = freecad_cast( - Application::Instance->getViewProvider(linked)); - if(!res) + Application::Instance->getViewProvider(linked) + ); + if (!res) { res = self; + } return res; } -std::string ViewProviderDocumentObject::getFullName() const { - if(pcObject) +std::string ViewProviderDocumentObject::getFullName() const +{ + if (pcObject) { return pcObject->getFullName() + ".ViewObject"; + } return std::string("?"); } - diff --git a/src/Gui/ViewProviderDocumentObject.h b/src/Gui/ViewProviderDocumentObject.h index 41a5cf3417..54d8b7bf1d 100644 --- a/src/Gui/ViewProviderDocumentObject.h +++ b/src/Gui/ViewProviderDocumentObject.h @@ -36,17 +36,18 @@ class SoType; namespace App { - class DocumentObject; - class Material; -} +class DocumentObject; +class Material; +} // namespace App -namespace Gui { +namespace Gui +{ class MDIView; class Document; -class GuiExport ViewProviderDocumentObject : public ViewProvider +class GuiExport ViewProviderDocumentObject: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderDocumentObject); @@ -64,8 +65,8 @@ public: App::PropertyEnumeration OnTopWhenSelected; App::PropertyEnumeration SelectionStyle; - virtual void attach(App::DocumentObject *pcObject); - virtual void reattach(App::DocumentObject *); + virtual void attach(App::DocumentObject* pcObject); + virtual void reattach(App::DocumentObject*); void update(const App::Property*) override; /// Set the active mode, i.e. the first item of the 'Display' property. void setActiveMode(); @@ -78,8 +79,12 @@ public: /// If null is returned then no transaction will be opened. const char* getTransactionText() const override; - bool canDropObjectEx(App::DocumentObject *, App::DocumentObject *, - const char *, const std::vector &) const override; + bool canDropObjectEx( + App::DocumentObject*, + App::DocumentObject*, + const char*, + const std::vector& + ) const override; int replaceObject(App::DocumentObject*, App::DocumentObject*) override; @@ -91,23 +96,32 @@ public: /// Run a redraw void updateView(); /// Get the object of this ViewProvider object - App::DocumentObject *getObject() const {return pcObject;} + App::DocumentObject* getObject() const + { + return pcObject; + } /// Get the object of this ViewProvider object as specified type - template - T *getObject() const { return freecad_cast(pcObject); } + template + T* getObject() const + { + return freecad_cast(pcObject); + } /// Asks the view provider if the given object can be deleted. bool canDelete(App::DocumentObject* obj) const override; /// Ask the view provider if it accepts object deletions while in edit - virtual bool acceptDeletionsInEdit() { return false; } + virtual bool acceptDeletionsInEdit() + { + return false; + } /// Get the GUI document to this ViewProvider object Gui::Document* getDocument() const; /// Get the python wrapper for that ViewProvider PyObject* getPyObject() override; /// return a hit element given the picked point which contains the full node path - bool getElementPicked(const SoPickedPoint *, std::string &subname) const override; + bool getElementPicked(const SoPickedPoint*, std::string& subname) const override; /// return the coin node detail and path to the node of the subname - bool getDetailPath(const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const override; + bool getDetailPath(const char* subname, SoFullPath* pPath, bool append, SoDetail*& det) const override; /* Force update visual * @@ -116,8 +130,14 @@ public: * visual update. */ //@{ - virtual void forceUpdate(bool enable = true) {(void)enable;} - virtual bool isUpdateForced() const {return false;} + virtual void forceUpdate(bool enable = true) + { + (void)enable; + } + virtual bool isUpdateForced() const + { + return false; + } //@} /** @name Restoring view provider from document load */ @@ -141,9 +161,14 @@ public: bool removeDynamicProperty(const char* prop) override; App::Property* addDynamicProperty( - const char* type, const char* name=nullptr, - const char* group=nullptr, const char* doc=nullptr, - short attr=0, bool ro=false, bool hidden=false) override; + const char* type, + const char* name = nullptr, + const char* group = nullptr, + const char* doc = nullptr, + short attr = 0, + bool ro = false, + bool hidden = false + ) override; /** Return the linked view object * @@ -156,8 +181,10 @@ public: * @return Returns the linked view provider. If none, it shall return * itself. */ - virtual ViewProviderDocumentObject *getLinkedViewProvider( - std::string *subname=nullptr, bool recursive=false) const; + virtual ViewProviderDocumentObject* getLinkedViewProvider( + std::string* subname = nullptr, + bool recursive = false + ) const; std::string getFullName() const override; @@ -165,7 +192,8 @@ public: * * @sa App::DocumentObject::getViewProviderNameOverride() */ - virtual bool allowOverride(const App::DocumentObject &) const { + virtual bool allowOverride(const App::DocumentObject&) const + { return false; } @@ -217,7 +245,7 @@ protected: const char* detachFromDocument() override; /// get called when a property status has changed - void onPropertyStatusChanged(const App::Property &prop, unsigned long oldStatus) override; + void onPropertyStatusChanged(const App::Property& prop, unsigned long oldStatus) override; //@} @@ -227,8 +255,8 @@ protected: void addDefaultAction(QMenu*, const QString&); protected: - App::DocumentObject *pcObject{nullptr}; - Gui::Document* pcDocument{nullptr}; + App::DocumentObject* pcObject {nullptr}; + Gui::Document* pcDocument {nullptr}; private: bool _Showable = true; @@ -241,7 +269,6 @@ private: }; -} // namespace Gui - -#endif // GUI_VIEWPROVIDER_DOCUMENTOBJECT_H +} // namespace Gui +#endif // GUI_VIEWPROVIDER_DOCUMENTOBJECT_H diff --git a/src/Gui/ViewProviderDocumentObject.pyi b/src/Gui/ViewProviderDocumentObject.pyi index 2057c2bd14..83bb882370 100644 --- a/src/Gui/ViewProviderDocumentObject.pyi +++ b/src/Gui/ViewProviderDocumentObject.pyi @@ -1,7 +1,6 @@ from ViewProvider import ViewProvider from typing import Any, Final - class ViewProviderDocumentObject(ViewProvider): """ This is the ViewProvider base class @@ -15,7 +14,6 @@ class ViewProviderDocumentObject(ViewProvider): Update the view representation of the object """ ... - Object: Any = ... """Set/Get the associated data object""" diff --git a/src/Gui/ViewProviderDocumentObjectGroup.cpp b/src/Gui/ViewProviderDocumentObjectGroup.cpp index d84d0bfc1a..f8eb14b245 100644 --- a/src/Gui/ViewProviderDocumentObjectGroup.cpp +++ b/src/Gui/ViewProviderDocumentObjectGroup.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -67,7 +66,7 @@ bool ViewProviderDocumentObjectGroup::isShow() const QIcon ViewProviderDocumentObjectGroup::getIcon() const { - return mergeGreyableOverlayIcons (Gui::BitmapFactory().iconFromTheme(sPixmap)); + return mergeGreyableOverlayIcons(Gui::BitmapFactory().iconFromTheme(sPixmap)); } /** @@ -80,10 +79,11 @@ void ViewProviderDocumentObjectGroup::getViewProviders(std::vectorgetDocument(doc->getDocument()); auto grp = static_cast(doc); std::vector obj = grp->getObjects(); - for (const auto & it : obj) { + for (const auto& it : obj) { ViewProvider* v = gd->getViewProvider(it); - if (v && v->isDerivedFrom()) + if (v && v->isDerivedFrom()) { vp.push_back(static_cast(v)); + } } } } @@ -105,11 +105,15 @@ void ViewProviderDocumentObjectGroup::setupContextMenu(QMenu* menu, QObject* rec // Add the custom action. QIcon icon = BitmapFactory().iconFromTheme("Std_SelectGroupContents"); QAction* selectAction = new QAction(icon, QObject::tr("Select Group Contents"), menu); - selectAction->setToolTip(QObject::tr("Selects all objects that are children of this group")); + selectAction->setToolTip( + QObject::tr("Selects all objects that are children of this group") + ); // Connect the action's triggered signal to a lambda function that performs the selection. QObject::connect(selectAction, &QAction::triggered, [group]() { - if (!group) return; + if (!group) { + return; + } // Use getAllChildren() to recursively select contents of subgroups. const auto& children = group->getAllChildren(); @@ -129,18 +133,22 @@ void ViewProviderDocumentObjectGroup::setupContextMenu(QMenu* menu, QObject* rec }); // Insert the action at the top of the menu for better visibility. - menu->insertAction(menu->actions().isEmpty() ? nullptr : menu->actions().first(), selectAction); + menu->insertAction( + menu->actions().isEmpty() ? nullptr : menu->actions().first(), + selectAction + ); } } } // Python feature ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderDocumentObjectGroupPython, Gui::ViewProviderDocumentObjectGroup) /// @endcond // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderDocumentObjectGroup.h b/src/Gui/ViewProviderDocumentObjectGroup.h index 42a91abdcd..9f8153ab44 100644 --- a/src/Gui/ViewProviderDocumentObjectGroup.h +++ b/src/Gui/ViewProviderDocumentObjectGroup.h @@ -28,10 +28,11 @@ #include "ViewProviderFeaturePython.h" -namespace Gui { +namespace Gui +{ -class GuiExport ViewProviderDocumentObjectGroup : public ViewProviderDocumentObject, - public ViewProviderGroupExtension +class GuiExport ViewProviderDocumentObjectGroup: public ViewProviderDocumentObject, + public ViewProviderGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Gui::ViewProviderDocumentObjectGroup); @@ -52,7 +53,10 @@ public: void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; /* Check whether the object accept reordering of its children during drop.*/ - bool acceptReorderingObjects() const override { return true; }; + bool acceptReorderingObjects() const override + { + return true; + }; protected: void getViewProviders(std::vector&) const; @@ -61,9 +65,9 @@ private: std::vector nodes; }; -using ViewProviderDocumentObjectGroupPython = ViewProviderFeaturePythonT; +using ViewProviderDocumentObjectGroupPython + = ViewProviderFeaturePythonT; -} // namespace Gui - -#endif // GUI_VIEWPROVIDER_DOCUMENTOBJECTGROUP_H +} // namespace Gui +#endif // GUI_VIEWPROVIDER_DOCUMENTOBJECTGROUP_H diff --git a/src/Gui/ViewProviderDocumentObjectPyImp.cpp b/src/Gui/ViewProviderDocumentObjectPyImp.cpp index 5997a86ef2..a0a97f9afd 100644 --- a/src/Gui/ViewProviderDocumentObjectPyImp.cpp +++ b/src/Gui/ViewProviderDocumentObjectPyImp.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -44,31 +43,37 @@ std::string ViewProviderDocumentObjectPy::representation() const return str.str(); } -PyObject* ViewProviderDocumentObjectPy::update(PyObject *args) +PyObject* ViewProviderDocumentObjectPy::update(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - PY_TRY { + } + PY_TRY + { getViewProviderDocumentObjectPtr()->updateView(); Py_Return; - } PY_CATCH; + } + PY_CATCH; } Py::Object ViewProviderDocumentObjectPy::getObject() const { App::DocumentObject* obj = getViewProviderDocumentObjectPtr()->getObject(); - return Py::Object(obj->getPyObject(), true); // do not inc'ref twice + return Py::Object(obj->getPyObject(), true); // do not inc'ref twice } void ViewProviderDocumentObjectPy::setObject(Py::Object pyobj) { - if(!PyObject_TypeCheck(*pyobj,&App::DocumentObjectPy::Type)) + if (!PyObject_TypeCheck(*pyobj, &App::DocumentObjectPy::Type)) { throw Py::TypeError("Expect document object"); + } App::DocumentObject* obj = getViewProviderDocumentObjectPtr()->getObject(); - if(obj) + if (obj) { throw Py::RuntimeError("View object already attached"); + } getViewProviderDocumentObjectPtr()->attach( - static_cast(*pyobj)->getDocumentObjectPtr()); + static_cast(*pyobj)->getDocumentObjectPtr() + ); } Py::Boolean ViewProviderDocumentObjectPy::getForceUpdate() const @@ -84,10 +89,10 @@ void ViewProviderDocumentObjectPy::setForceUpdate(Py::Boolean arg) Py::Object ViewProviderDocumentObjectPy::getDocument() const { Document* doc = getViewProviderDocumentObjectPtr()->getDocument(); - return Py::asObject(doc->getPyObject()); // do not inc'ref twice + return Py::asObject(doc->getPyObject()); // do not inc'ref twice } -PyObject *ViewProviderDocumentObjectPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ViewProviderDocumentObjectPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Gui/ViewProviderDragger.cpp b/src/Gui/ViewProviderDragger.cpp index 4d74931229..1d5b858435 100644 --- a/src/Gui/ViewProviderDragger.cpp +++ b/src/Gui/ViewProviderDragger.cpp @@ -69,8 +69,7 @@ ViewProviderDragger::~ViewProviderDragger() = default; void ViewProviderDragger::updateData(const App::Property* prop) { - if (prop->isDerivedFrom() - && strcmp(prop->getName(), "Placement") == 0) { + if (prop->isDerivedFrom() && strcmp(prop->getName(), "Placement") == 0) { // Note: If R is the rotation, c the rotation center and t the translation // vector then Inventor applies the following transformation: R*(x-c)+c+t // In FreeCAD a placement only has a rotation and a translation part but @@ -124,8 +123,7 @@ bool ViewProviderDragger::doubleClicked() void ViewProviderDragger::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { - QIcon iconObject = - mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap("Std_TransformManip.svg")); + QIcon iconObject = mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap("Std_TransformManip.svg")); QAction* act = menu->addAction(iconObject, QObject::tr("Transform"), receiver, member); act->setData(QVariant((int)ViewProvider::Transform)); ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); @@ -145,8 +143,8 @@ ViewProvider* ViewProviderDragger::startEditing(int mode) bool ViewProviderDragger::forwardToLink() { - // typically we want to transform the selected object, but if the selected object is in the link, - // we want to transform the link instead. + // typically we want to transform the selected object, but if the selected object is in the + // link, we want to transform the link instead. // // To achieve that, we use the sub object path and look for the first link in the chain, and // we forward the request there. @@ -215,9 +213,11 @@ bool ViewProviderDragger::setEdit(int ModNum) assert(!transformDragger); transformDragger = new SoTransformDragger(); - transformDragger->setAxisColors(Gui::ViewParams::instance()->getAxisXColor(), - Gui::ViewParams::instance()->getAxisYColor(), - Gui::ViewParams::instance()->getAxisZColor()); + transformDragger->setAxisColors( + Gui::ViewParams::instance()->getAxisXColor(), + Gui::ViewParams::instance()->getAxisYColor(), + Gui::ViewParams::instance()->getAxisZColor() + ); transformDragger->draggerSize.setValue(ViewParams::instance()->getDraggerScale()); transformDragger->addStartCallback(dragStartCallback, this); @@ -251,7 +251,8 @@ void ViewProviderDragger::setEditViewer(Gui::View3DInventorViewer* viewer, int M if (transformDragger) { transformDragger->setUpAutoScale(viewer->getSoRenderManager()->getCamera()); - auto originPlacement = App::GeoFeature::getGlobalPlacement(getObject()) * getObjectPlacement().inverse(); + auto originPlacement = App::GeoFeature::getGlobalPlacement(getObject()) + * getObjectPlacement().inverse(); auto mat = originPlacement.toMatrix(); viewer->getDocument()->setEditingTransform(mat); @@ -329,7 +330,9 @@ void ViewProviderDragger::updatePlacementFromDragger(DraggerComponents component maskedDeltaPositionLocal.z = 0.0; } - const Base::Vector3d maskedDeltaPositionGlobal = oldDraggerRotation.multVec(maskedDeltaPositionLocal); + const Base::Vector3d maskedDeltaPositionGlobal = oldDraggerRotation.multVec( + maskedDeltaPositionLocal + ); Base::Vector3d finalPosition = oldDraggerPosition + maskedDeltaPositionGlobal; // --- Mask rotation --- @@ -350,7 +353,7 @@ void ViewProviderDragger::updatePlacementFromDragger(DraggerComponents component // Create new dragger placement, only if components are masked Base::Placement finalDraggerPlacement(newDraggerPosition, newDraggerRotation); - if (!components.testFlag(DraggerComponent::All)){ + if (!components.testFlag(DraggerComponent::All)) { finalDraggerPlacement.setPosition(finalPosition); finalDraggerPlacement.setRotation(finalRotation); } @@ -359,10 +362,12 @@ void ViewProviderDragger::updatePlacementFromDragger(DraggerComponents component updateDraggerPosition(); } -Base::Rotation Gui::ViewProviderDragger::orthonormalize(Base::Vector3d x, - Base::Vector3d y, - Base::Vector3d z, - ViewProviderDragger::DraggerComponents components) +Base::Rotation Gui::ViewProviderDragger::orthonormalize( + Base::Vector3d x, + Base::Vector3d y, + Base::Vector3d z, + ViewProviderDragger::DraggerComponents components +) { // Orthonormalize (Gram–Schmidt process) to find perpendicular unit vector depending on masked axes if (components.testFlag(Gui::ViewProviderDragger::DraggerComponent::XRot) @@ -373,14 +378,16 @@ Base::Rotation Gui::ViewProviderDragger::orthonormalize(Base::Vector3d x, z = x.Cross(y); z.Normalize(); } - else if (components.testFlag(Gui::ViewProviderDragger::DraggerComponent::XRot) && components.testFlag(Gui::ViewProviderDragger::DraggerComponent::ZRot)) { + else if (components.testFlag(Gui::ViewProviderDragger::DraggerComponent::XRot) + && components.testFlag(Gui::ViewProviderDragger::DraggerComponent::ZRot)) { x.Normalize(); z = z - x * (x * z); z.Normalize(); y = z.Cross(x); y.Normalize(); } - else if (components.testFlag(Gui::ViewProviderDragger::DraggerComponent::YRot) && components.testFlag(Gui::ViewProviderDragger::DraggerComponent::ZRot)) { + else if (components.testFlag(Gui::ViewProviderDragger::DraggerComponent::YRot) + && components.testFlag(Gui::ViewProviderDragger::DraggerComponent::ZRot)) { y.Normalize(); z = z - y * (y * z); z.Normalize(); @@ -441,10 +448,8 @@ Base::Placement ViewProviderDragger::getDraggerPlacement() const const auto yBase = rotation.multVec(Base::Vector3d(0, 1, 0)); const auto zBase = rotation.multVec(Base::Vector3d(0, 0, 1)); - const auto positionIncrement = - xBase * (translationStep * xSteps) + - yBase * (translationStep * ySteps) + - zBase * (translationStep * zSteps); + const auto positionIncrement = xBase * (translationStep * xSteps) + + yBase * (translationStep * ySteps) + zBase * (translationStep * zSteps); const double rotationStep = transformDragger->rotationIncrement.getValue(); const int xRotationSteps = transformDragger->rotationIncrementCountX.getValue(); @@ -452,14 +457,14 @@ Base::Placement ViewProviderDragger::getDraggerPlacement() const const int zRotationSteps = transformDragger->rotationIncrementCountZ.getValue(); auto newRotation = rotation; - newRotation = newRotation * Base::Rotation(Base::Vector3d(1, 0, 0), xRotationSteps * rotationStep); - newRotation = newRotation * Base::Rotation(Base::Vector3d(0, 1, 0), yRotationSteps * rotationStep); - newRotation = newRotation * Base::Rotation(Base::Vector3d(0, 0, 1), zRotationSteps * rotationStep); + newRotation = newRotation + * Base::Rotation(Base::Vector3d(1, 0, 0), xRotationSteps * rotationStep); + newRotation = newRotation + * Base::Rotation(Base::Vector3d(0, 1, 0), yRotationSteps * rotationStep); + newRotation = newRotation + * Base::Rotation(Base::Vector3d(0, 0, 1), zRotationSteps * rotationStep); - return Base::Placement( - draggerPlacement.getPosition() + positionIncrement, - newRotation - ); + return Base::Placement(draggerPlacement.getPosition() + positionIncrement, newRotation); } Base::Placement ViewProviderDragger::getOriginalDraggerPlacement() const diff --git a/src/Gui/ViewProviderDragger.h b/src/Gui/ViewProviderDragger.h index 3f0ced5cb9..5f1e6e6dcb 100644 --- a/src/Gui/ViewProviderDragger.h +++ b/src/Gui/ViewProviderDragger.h @@ -32,10 +32,12 @@ class SoDragger; class SoTransform; -namespace Gui { +namespace Gui +{ -namespace TaskView { - class TaskDialog; +namespace TaskView +{ +class TaskDialog; } class SoTransformDragger; @@ -47,7 +49,7 @@ class GizmoContainer; * of a geometric feature. * @author Werner Mayer */ -class GuiExport ViewProviderDragger : public ViewProviderDocumentObject +class GuiExport ViewProviderDragger: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderDragger); @@ -66,7 +68,10 @@ public: void attach(App::DocumentObject* pcObject) override; /// Convenience method to obtain the transform origin - Base::Placement getTransformOrigin() const { return TransformOrigin.getValue(); } + Base::Placement getTransformOrigin() const + { + return TransformOrigin.getValue(); + } /// Convenience method to set the transform origin void setTransformOrigin(const Base::Placement& placement); /// Resets transform origin to the object origin @@ -81,10 +86,10 @@ public: void setupContextMenu(QMenu*, QObject*, const char*) override; void updateData(const App::Property*) override; - ViewProvider *startEditing(int ModNum=0) override; + ViewProvider* startEditing(int ModNum = 0) override; /*! synchronize From FC placement to Coin placement*/ - static void updateTransform(const Base::Placement &from, SoTransform *to); + static void updateTransform(const Base::Placement& from, SoTransform* to); enum class DraggerComponent { @@ -133,30 +138,32 @@ protected: virtual TaskView::TaskDialog* getTransformDialog(); CoinPtr transformDragger; - ViewProvider *forwardedViewProvider = nullptr; + ViewProvider* forwardedViewProvider = nullptr; CoinPtr pcPlacement; + private: - static void dragStartCallback(void *data, SoDragger *d); - static void dragFinishCallback(void *data, SoDragger *d); - static void dragMotionCallback(void *data, SoDragger *d); + static void dragStartCallback(void* data, SoDragger* d); + static void dragFinishCallback(void* data, SoDragger* d); + static void dragMotionCallback(void* data, SoDragger* d); void updateDraggerPosition(); - Base::Placement draggerPlacement { }; + Base::Placement draggerPlacement {}; // Rotation by orthonormalizing depending on given axes components - Base::Rotation orthonormalize(Base::Vector3d x, - Base::Vector3d y, - Base::Vector3d z, - ViewProviderDragger::DraggerComponents components = DraggerComponent::All); + Base::Rotation orthonormalize( + Base::Vector3d x, + Base::Vector3d y, + Base::Vector3d z, + ViewProviderDragger::DraggerComponents components = DraggerComponent::All + ); GizmoContainer* gizmoContainer = nullptr; }; -} // namespace Gui +} // namespace Gui ENABLE_BITMASK_OPERATORS(Gui::ViewProviderDragger::DraggerComponent) -#endif // GUI_VIEWPROVIDER_DRAGGER_H - +#endif // GUI_VIEWPROVIDER_DRAGGER_H diff --git a/src/Gui/ViewProviderExtension.cpp b/src/Gui/ViewProviderExtension.cpp index e048d32665..d261215906 100644 --- a/src/Gui/ViewProviderExtension.cpp +++ b/src/Gui/ViewProviderExtension.cpp @@ -21,10 +21,8 @@ ***************************************************************************/ - - -# include -# include +#include +#include #include "ViewProviderExtension.h" @@ -43,25 +41,27 @@ ViewProviderExtension::ViewProviderExtension() ViewProviderExtension::~ViewProviderExtension() = default; -const ViewProviderDocumentObject* ViewProviderExtension::getExtendedViewProvider() const{ +const ViewProviderDocumentObject* ViewProviderExtension::getExtendedViewProvider() const +{ assert(getExtendedContainer()->isDerivedFrom()); return static_cast(getExtendedContainer()); } -ViewProviderDocumentObject* ViewProviderExtension::getExtendedViewProvider() { +ViewProviderDocumentObject* ViewProviderExtension::getExtendedViewProvider() +{ assert(getExtendedContainer()->isDerivedFrom()); return static_cast(getExtendedContainer()); } -void ViewProviderExtension::extensionUpdateData(const App::Property*) { +void ViewProviderExtension::extensionUpdateData(const App::Property*) +{} -} +PyObject* ViewProviderExtension::getExtensionPyObject() +{ -PyObject* ViewProviderExtension::getExtensionPyObject() { - - if (ExtensionPythonObject.is(Py::_None())){ + if (ExtensionPythonObject.is(Py::_None())) { // ref counter is set to 1 auto ext = new ViewProviderExtensionPy(this); ExtensionPythonObject = Py::asObject(ext); @@ -69,9 +69,10 @@ PyObject* ViewProviderExtension::getExtensionPyObject() { return Py::new_reference_to(ExtensionPythonObject); } -namespace Gui { +namespace Gui +{ EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderExtensionPython, Gui::ViewProviderExtension) // explicit template instantiation template class GuiExport ViewProviderExtensionPythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderExtension.h b/src/Gui/ViewProviderExtension.h index 728acfec11..8d6778e3d3 100644 --- a/src/Gui/ViewProviderExtension.h +++ b/src/Gui/ViewProviderExtension.h @@ -37,7 +37,8 @@ class SoSeparator; class QMenu; class QObject; -namespace Gui { +namespace Gui +{ class ViewProvider; class ViewProviderDocumentObject; @@ -46,85 +47,159 @@ class ViewProviderDocumentObject; * @brief Extension with special viewprovider calls * */ -class GuiExport ViewProviderExtension : public App::Extension +class GuiExport ViewProviderExtension: public App::Extension { - //The class does not have properties itself, but it is important to provide the property access - //functions. + // The class does not have properties itself, but it is important to provide the property access + // functions. EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderExtension); public: + ViewProviderExtension(); + ~ViewProviderExtension() override; - ViewProviderExtension (); - ~ViewProviderExtension () override; - - Gui::ViewProviderDocumentObject* getExtendedViewProvider(); + Gui::ViewProviderDocumentObject* getExtendedViewProvider(); const Gui::ViewProviderDocumentObject* getExtendedViewProvider() const; - virtual std::vector extensionClaimChildren3D() const { - return {}; } + virtual std::vector extensionClaimChildren3D() const + { + return {}; + } - virtual bool extensionOnDelete(const std::vector &){ return true;} - virtual void extensionBeforeDelete(){} + virtual bool extensionOnDelete(const std::vector&) + { + return true; + } + virtual void extensionBeforeDelete() + {} - virtual std::vector extensionClaimChildren() const { - return {}; } + virtual std::vector extensionClaimChildren() const + { + return {}; + } - virtual bool extensionCanDragObjects() const { return false; } - virtual bool extensionCanDragObject(App::DocumentObject*) const { return true; } - virtual void extensionDragObject(App::DocumentObject*) { } - virtual bool extensionCanDropObjects() const { return false; } - virtual bool extensionCanDropObject(App::DocumentObject*) const { return true; } - virtual bool extensionCanDragAndDropObject(App::DocumentObject*) const { return true; } - virtual void extensionDropObject(App::DocumentObject*) { } - virtual bool extensionCanDropObjectEx(App::DocumentObject *, App::DocumentObject *, - const char *, const std::vector &) const - { return false; } - virtual std::string extensionDropObjectEx(App::DocumentObject *obj, App::DocumentObject *, - const char *, const std::vector &) - { extensionDropObject(obj); return {}; } + virtual bool extensionCanDragObjects() const + { + return false; + } + virtual bool extensionCanDragObject(App::DocumentObject*) const + { + return true; + } + virtual void extensionDragObject(App::DocumentObject*) + {} + virtual bool extensionCanDropObjects() const + { + return false; + } + virtual bool extensionCanDropObject(App::DocumentObject*) const + { + return true; + } + virtual bool extensionCanDragAndDropObject(App::DocumentObject*) const + { + return true; + } + virtual void extensionDropObject(App::DocumentObject*) + {} + virtual bool extensionCanDropObjectEx( + App::DocumentObject*, + App::DocumentObject*, + const char*, + const std::vector& + ) const + { + return false; + } + virtual std::string extensionDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject*, + const char*, + const std::vector& + ) + { + extensionDropObject(obj); + return {}; + } virtual int extensionReplaceObject(App::DocumentObject* /*oldValue*/, App::DocumentObject* /*newValue*/) - { return -1; } + { + return -1; + } /// Hides the view provider - virtual void extensionHide() { } + virtual void extensionHide() + {} /// Shows the view provider - virtual void extensionShow() { } + virtual void extensionShow() + {} - virtual void extensionModeSwitchChange() { } + virtual void extensionModeSwitchChange() + {} - virtual SoSeparator* extensionGetFrontRoot() const {return nullptr;} - virtual SoGroup* extensionGetChildRoot() const {return nullptr;} - virtual SoSeparator* extensionGetBackRoot() const {return nullptr;} - virtual void extensionAttach(App::DocumentObject* ) { } - virtual void extensionReattach(App::DocumentObject* ) { } - virtual void extensionSetDisplayMode(const char* ) { } - virtual std::vector extensionGetDisplayModes() const {return {};} - virtual void extensionSetupContextMenu(QMenu*, QObject*, const char*) {} + virtual SoSeparator* extensionGetFrontRoot() const + { + return nullptr; + } + virtual SoGroup* extensionGetChildRoot() const + { + return nullptr; + } + virtual SoSeparator* extensionGetBackRoot() const + { + return nullptr; + } + virtual void extensionAttach(App::DocumentObject*) + {} + virtual void extensionReattach(App::DocumentObject*) + {} + virtual void extensionSetDisplayMode(const char*) + {} + virtual std::vector extensionGetDisplayModes() const + { + return {}; + } + virtual void extensionSetupContextMenu(QMenu*, QObject*, const char*) + {} // update data of extended object virtual void extensionUpdateData(const App::Property*); PyObject* getExtensionPyObject() override; - void setIgnoreOverlayIcon(bool on) { + void setIgnoreOverlayIcon(bool on) + { m_ignoreOverlayIcon = on; } - bool ignoreOverlayIcon() const { + bool ignoreOverlayIcon() const + { return m_ignoreOverlayIcon; } - virtual QIcon extensionMergeGreyableOverlayIcons(const QIcon & orig) const {return orig;} - virtual QIcon extensionMergeColorfullOverlayIcons(const QIcon & orig) const {return orig;} + virtual QIcon extensionMergeGreyableOverlayIcons(const QIcon& orig) const + { + return orig; + } + virtual QIcon extensionMergeColorfullOverlayIcons(const QIcon& orig) const + { + return orig; + } - virtual void extensionStartRestoring() {} - virtual void extensionFinishRestoring() {} + virtual void extensionStartRestoring() + {} + virtual void extensionFinishRestoring() + {} - virtual bool extensionGetElementPicked(const SoPickedPoint *, std::string &) const {return false;} - virtual bool extensionGetDetailPath(const char *, SoFullPath *, SoDetail *&) const {return false;} + virtual bool extensionGetElementPicked(const SoPickedPoint*, std::string&) const + { + return false; + } + virtual bool extensionGetDetailPath(const char*, SoFullPath*, SoDetail*&) const + { + return false; + } private: bool m_ignoreOverlayIcon = false; }; -} //Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDEREXTENSION_H +#endif // GUI_VIEWPROVIDEREXTENSION_H diff --git a/src/Gui/ViewProviderExtension.pyi b/src/Gui/ViewProviderExtension.pyi index 66df2b2695..eb5800c6e8 100644 --- a/src/Gui/ViewProviderExtension.pyi +++ b/src/Gui/ViewProviderExtension.pyi @@ -1,7 +1,6 @@ from Base.Metadata import constmethod from App.Extension import Extension - class ViewProviderExtension(Extension): """ Base class for all view provider extensions diff --git a/src/Gui/ViewProviderExtensionPyImp.cpp b/src/Gui/ViewProviderExtensionPyImp.cpp index 331fd4f95d..bf89904b26 100644 --- a/src/Gui/ViewProviderExtensionPyImp.cpp +++ b/src/Gui/ViewProviderExtensionPyImp.cpp @@ -21,9 +21,7 @@ ***************************************************************************/ - - -# include +#include // inclusion of the generated files (generated out of PropertyContainerPy.pyi) @@ -39,17 +37,20 @@ std::string ViewProviderExtensionPy::representation() const return {""}; } -PyObject* ViewProviderExtensionPy::setIgnoreOverlayIcon(PyObject *args) +PyObject* ViewProviderExtensionPy::setIgnoreOverlayIcon(PyObject* args) { PyObject* ignore; const char* name = nullptr; - if (!PyArg_ParseTuple(args, "O!s", &PyBool_Type, &ignore, &name)) + if (!PyArg_ParseTuple(args, "O!s", &PyBool_Type, &ignore, &name)) { return nullptr; + } ViewProviderExtension* ext = getViewProviderExtensionPtr(); if (name) { Base::Type type = Base::Type::fromName(name); - ext = dynamic_cast(ext->getExtendedContainer()->getExtension(type, true, true)); + ext = dynamic_cast( + ext->getExtendedContainer()->getExtension(type, true, true) + ); if (!ext) { PyErr_SetString(PyExc_NameError, "no such extension"); return nullptr; @@ -60,16 +61,19 @@ PyObject* ViewProviderExtensionPy::setIgnoreOverlayIcon(PyObject *args) Py_Return; } -PyObject* ViewProviderExtensionPy::ignoreOverlayIcon(PyObject *args) const +PyObject* ViewProviderExtensionPy::ignoreOverlayIcon(PyObject* args) const { const char* name = nullptr; - if (!PyArg_ParseTuple(args, "s", &name)) + if (!PyArg_ParseTuple(args, "s", &name)) { return nullptr; + } ViewProviderExtension* ext = getViewProviderExtensionPtr(); if (name) { Base::Type type = Base::Type::fromName(name); - ext = dynamic_cast(ext->getExtendedContainer()->getExtension(type, true, true)); + ext = dynamic_cast( + ext->getExtendedContainer()->getExtension(type, true, true) + ); if (!ext) { PyErr_SetString(PyExc_NameError, "no such extension"); return nullptr; @@ -80,12 +84,12 @@ PyObject* ViewProviderExtensionPy::ignoreOverlayIcon(PyObject *args) const return Py_BuildValue("O", (ignore ? Py_True : Py_False)); } -PyObject *ViewProviderExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ViewProviderExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } -int ViewProviderExtensionPy::setCustomAttributes(const char* /*attr*/, PyObject * /*obj*/) +int ViewProviderExtensionPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } diff --git a/src/Gui/ViewProviderExtensionPython.h b/src/Gui/ViewProviderExtensionPython.h index 86df23857d..e28163e6f2 100644 --- a/src/Gui/ViewProviderExtensionPython.h +++ b/src/Gui/ViewProviderExtensionPython.h @@ -27,21 +27,23 @@ #include "ViewProviderExtension.h" #include -namespace Gui { +namespace Gui +{ /** * Generic Python extension class which allows one to behave every extension * derived class as Python extension -- simply by subclassing. */ -template -class ViewProviderExtensionPythonT : public ExtensionT //NOLINT +template +class ViewProviderExtensionPythonT: public ExtensionT // NOLINT { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderExtensionPythonT); public: using Inherited = ExtensionT; - ViewProviderExtensionPythonT() { + ViewProviderExtensionPythonT() + { ExtensionT::m_isPythonExtension = true; ExtensionT::initExtensionType(ViewProviderExtensionPythonT::getExtensionClassTypeId()); } @@ -49,12 +51,12 @@ public: ViewProviderExtensionPythonT(const ViewProviderExtensionPythonT&) = delete; ViewProviderExtensionPythonT(ViewProviderExtensionPythonT&&) = delete; - ViewProviderExtensionPythonT& operator= (const ViewProviderExtensionPythonT&) = delete; - ViewProviderExtensionPythonT& operator= (ViewProviderExtensionPythonT&&) = delete; + ViewProviderExtensionPythonT& operator=(const ViewProviderExtensionPythonT&) = delete; + ViewProviderExtensionPythonT& operator=(ViewProviderExtensionPythonT&&) = delete; }; using ViewProviderExtensionPython = ViewProviderExtensionPythonT; -} //Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDEREXTENSIONPYTHON_H +#endif // GUI_VIEWPROVIDEREXTENSIONPYTHON_H diff --git a/src/Gui/ViewProviderExtern.cpp b/src/Gui/ViewProviderExtern.cpp index 79a59aa92b..8d8857b648 100644 --- a/src/Gui/ViewProviderExtern.cpp +++ b/src/Gui/ViewProviderExtern.cpp @@ -21,10 +21,9 @@ ***************************************************************************/ - -# include -# include -# include +#include +#include +#include #include @@ -34,8 +33,8 @@ #include "SoFCSelection.h" -using std::vector; using std::string; +using std::vector; using namespace Gui; @@ -50,15 +49,15 @@ ViewProviderExtern::~ViewProviderExtern() = default; void ViewProviderExtern::setModeByString(const char* name, const char* ivFragment) { SoInput in; - in.setBuffer((void*)ivFragment,std::strlen(ivFragment)); - setModeBySoInput(name,in); + in.setBuffer((void*)ivFragment, std::strlen(ivFragment)); + setModeBySoInput(name, in); } void ViewProviderExtern::setModeByFile(const char* name, const char* ivFileName) { SoInput in; Base::ifstream file(Base::FileInfo(ivFileName), std::ios::in | std::ios::binary); - if (file){ + if (file) { std::streamoff size = 0; std::streambuf* buf = file.rdbuf(); if (buf) { @@ -77,17 +76,20 @@ void ViewProviderExtern::setModeByFile(const char* name, const char* ivFileName) } file.close(); - in.setBuffer(&(content[0]),content.size()); - setModeBySoInput(name,in); + in.setBuffer(&(content[0]), content.size()); + setModeBySoInput(name, in); } } -void ViewProviderExtern::setModeBySoInput(const char* name, SoInput &ivFileInput) +void ViewProviderExtern::setModeBySoInput(const char* name, SoInput& ivFileInput) { - SoSeparator * root = SoDB::readAll(&ivFileInput); + SoSeparator* root = SoDB::readAll(&ivFileInput); if (root) { - std::vector::iterator pos = std::find - ::iterator,string>(modes.begin(),modes.end(),string(name)); + std::vector::iterator pos = std::find::iterator, string>( + modes.begin(), + modes.end(), + string(name) + ); if (pos == modes.end()) { // new mode modes.emplace_back(name); @@ -110,7 +112,7 @@ void ViewProviderExtern::setModeBySoInput(const char* name, SoInput &ivFileInput void ViewProviderExtern::adjustDocumentName(const char* docname) { - for (int i=0; ipcModeSwitch->getNumChildren(); i++) { + for (int i = 0; i < this->pcModeSwitch->getNumChildren(); i++) { SoNode* child = this->pcModeSwitch->getChild(i); adjustRecursiveDocumentName(child, docname); } @@ -121,9 +123,9 @@ void ViewProviderExtern::adjustRecursiveDocumentName(SoNode* child, const char* if (child->getTypeId().isDerivedFrom(SoFCSelection::getClassTypeId())) { static_cast(child)->documentName = docname; } - else if (child->getTypeId().isDerivedFrom( SoGroup::getClassTypeId())) { + else if (child->getTypeId().isDerivedFrom(SoGroup::getClassTypeId())) { SoGroup* group = static_cast(child); - for (int i=0; igetNumChildren(); i++) { + for (int i = 0; i < group->getNumChildren(); i++) { SoNode* subchild = group->getChild(i); adjustRecursiveDocumentName(subchild, docname); } diff --git a/src/Gui/ViewProviderExtern.h b/src/Gui/ViewProviderExtern.h index 0cbc917d03..284c404e0a 100644 --- a/src/Gui/ViewProviderExtern.h +++ b/src/Gui/ViewProviderExtern.h @@ -30,10 +30,11 @@ class SoNode; class SoInput; -namespace Gui { +namespace Gui +{ -class GuiExport ViewProviderExtern:public ViewProvider +class GuiExport ViewProviderExtern: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderExtern); @@ -46,12 +47,13 @@ public: void setModeByString(const char* name, const char* ivFragment); void setModeByFile(const char* name, const char* ivFileName); - void setModeBySoInput(const char* name, SoInput &ivFileInput); + void setModeBySoInput(const char* name, SoInput& ivFileInput); void adjustDocumentName(const char* docname); const char* getDefaultDisplayMode() const override; std::vector getDisplayModes() const override; - void updateData(const App::Property*) override{} + void updateData(const App::Property*) override + {} private: void adjustRecursiveDocumentName(SoNode*, const char* docname); @@ -60,7 +62,6 @@ protected: std::vector modes; }; -} // namespace Gui - -#endif // GUI_VIEWPROVIDER_EXTERN_H +} // namespace Gui +#endif // GUI_VIEWPROVIDER_EXTERN_H diff --git a/src/Gui/ViewProviderFeature.cpp b/src/Gui/ViewProviderFeature.cpp index fe7da67307..83867703b9 100644 --- a/src/Gui/ViewProviderFeature.cpp +++ b/src/Gui/ViewProviderFeature.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include "ViewProviderFeature.h" @@ -35,12 +34,12 @@ PROPERTY_SOURCE(Gui::ViewProviderFeature, Gui::ViewProviderDocumentObject) ViewProviderFeature::ViewProviderFeature() { Base::Color c; - ADD_PROPERTY(ColourList,(c)); + ADD_PROPERTY(ColourList, (c)); } ViewProviderFeature::~ViewProviderFeature() = default; -void ViewProviderFeature::attach(App::DocumentObject *pcObj) +void ViewProviderFeature::attach(App::DocumentObject* pcObj) { ViewProviderDocumentObject::attach(pcObj); } diff --git a/src/Gui/ViewProviderFeature.h b/src/Gui/ViewProviderFeature.h index cc9968215e..19715ee185 100644 --- a/src/Gui/ViewProviderFeature.h +++ b/src/Gui/ViewProviderFeature.h @@ -28,11 +28,12 @@ class SbVec2s; -namespace Gui { +namespace Gui +{ class View3DInventorViewer; -class GuiExport ViewProviderFeature:public ViewProviderDocumentObject +class GuiExport ViewProviderFeature: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderFeature); @@ -43,15 +44,14 @@ public: /// destructor. ~ViewProviderFeature() override; - App::PropertyColorList ColourList; + App::PropertyColorList ColourList; /** * Attaches the document object to this view provider. */ - void attach(App::DocumentObject *pcObj) override; + void attach(App::DocumentObject* pcObj) override; }; -} // namespace Gui - -#endif // GUI_VIEWPROVIDER_FEATURE_H +} // namespace Gui +#endif // GUI_VIEWPROVIDER_FEATURE_H diff --git a/src/Gui/ViewProviderFeaturePython.cpp b/src/Gui/ViewProviderFeaturePython.cpp index 7c1c4e1886..5ddeed1ab3 100644 --- a/src/Gui/ViewProviderFeaturePython.cpp +++ b/src/Gui/ViewProviderFeaturePython.cpp @@ -21,15 +21,14 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -57,11 +56,12 @@ namespace sp = std::placeholders; // ---------------------------------------------------------------------------- ViewProviderFeaturePythonImp::ViewProviderFeaturePythonImp( - ViewProviderDocumentObject* vp, App::PropertyPythonObject &proxy) - : object(vp) - , Proxy(proxy) -{ -} + ViewProviderDocumentObject* vp, + App::PropertyPythonObject& proxy +) + : object(vp) + , Proxy(proxy) +{} ViewProviderFeaturePythonImp::~ViewProviderFeaturePythonImp() { @@ -79,7 +79,8 @@ ViewProviderFeaturePythonImp::~ViewProviderFeaturePythonImp() this->selectionObserver.~SelectionObserverPythonHandler(); } -void ViewProviderFeaturePythonImp::init(PyObject *pyobj) { +void ViewProviderFeaturePythonImp::init(PyObject* pyobj) +{ Base::PyGILStateLocker lock; has__object__ = !!PyObject_HasAttrString(pyobj, "__object__"); @@ -91,40 +92,44 @@ void ViewProviderFeaturePythonImp::init(PyObject *pyobj) { this->selectionObserver.init(pyobj); } -#define FC_PY_CALL_CHECK(_name) _FC_PY_CALL_CHECK(_name,return(NotImplemented)) +#define FC_PY_CALL_CHECK(_name) _FC_PY_CALL_CHECK(_name, return (NotImplemented)) QIcon ViewProviderFeaturePythonImp::getIcon() const { - _FC_PY_CALL_CHECK(getIcon,return(QIcon())); + _FC_PY_CALL_CHECK(getIcon, return (QIcon())); // Run the getIcon method of the proxy object. Base::PyGILStateLocker lock; try { Py::Object ret(Base::pyCall(py_getIcon.ptr())); - if(ret.isNone()) + if (ret.isNone()) { return {}; + } - if(ret.isString()) { + if (ret.isString()) { std::string content = Py::String(ret).as_std_string("utf-8"); QPixmap icon; - if (BitmapFactory().findPixmapInCache(content.c_str(), icon)) + if (BitmapFactory().findPixmapInCache(content.c_str(), icon)) { return icon; + } // Check if the passed string is a filename, otherwise treat as xpm data QFileInfo fi(QString::fromUtf8(content.c_str())); if (fi.isFile() && fi.exists()) { icon.load(fi.absoluteFilePath()); - } else { + } + else { QByteArray ary; int strlen = (int)content.size(); ary.resize(strlen); - for (int j=0; j lines = ary.split('\n'); QByteArray buffer; - buffer.reserve(ary.size()+lines.size()); - for (const auto & line : lines) { + buffer.reserve(ary.size() + lines.size()); + for (const auto& line : lines) { QByteArray trim = line.trimmed(); if (!trim.isEmpty()) { buffer.append(trim); @@ -136,20 +141,23 @@ QIcon ViewProviderFeaturePythonImp::getIcon() const if (!icon.isNull()) { return icon; } - } else { + } + else { PythonWrapper wrap; wrap.loadGuiModule(); wrap.loadWidgetsModule(); - QIcon *picon = wrap.toQIcon(ret.ptr()); - if(picon) + QIcon* picon = wrap.toQIcon(ret.ptr()); + if (picon) { return *picon; + } } } catch (Py::Exception&) { - if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) + if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) { PyErr_Clear(); + } else { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -157,8 +165,7 @@ QIcon ViewProviderFeaturePythonImp::getIcon() const return {}; } -std::map -ViewProviderFeaturePythonImp::getOverlayIcons() const +std::map ViewProviderFeaturePythonImp::getOverlayIcons() const { std::map overlays; _FC_PY_CALL_CHECK(getOverlayIcons, return overlays); @@ -215,9 +222,9 @@ ViewProviderFeaturePythonImp::getOverlayIcons() const return overlays; } -bool ViewProviderFeaturePythonImp::claimChildren(std::vector &children) const +bool ViewProviderFeaturePythonImp::claimChildren(std::vector& children) const { - _FC_PY_CALL_CHECK(claimChildren,return(false)); + _FC_PY_CALL_CHECK(claimChildren, return (false)); Base::PyGILStateLocker lock; try { @@ -225,7 +232,8 @@ bool ViewProviderFeaturePythonImp::claimChildren(std::vector(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); children.push_back(obj); } } @@ -235,15 +243,14 @@ bool ViewProviderFeaturePythonImp::claimChildren(std::vectorselectionObserver.handleSelectionChanged(changes); } -bool ViewProviderFeaturePythonImp::getElement(const SoDetail *det, std::string &res) const +bool ViewProviderFeaturePythonImp::getElement(const SoDetail* det, std::string& res) const { - _FC_PY_CALL_CHECK(getElement,return(false)); + _FC_PY_CALL_CHECK(getElement, return (false)); // Run the onChanged method of the proxy object. Base::PyGILStateLocker lock; @@ -280,10 +288,15 @@ bool ViewProviderFeaturePythonImp::getElement(const SoDetail *det, std::string & // Note: As there is no ref'counting mechanism for the SoDetail class we must // pass '0' as the last parameter so that the Python object does not 'own' // the detail object. - pivy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoDetail *", const_cast(static_cast(det)), 0); + pivy = Base::Interpreter().createSWIGPointerObj( + "pivy.coin", + "SoDetail *", + const_cast(static_cast(det)), + 0 + ); Py::Tuple args(1); args.setItem(0, Py::Object(pivy, true)); - Py::String name(Base::pyCall(py_getElement.ptr(),args.ptr())); + Py::String name(Base::pyCall(py_getElement.ptr(), args.ptr())); res = name; return true; } @@ -295,27 +308,35 @@ bool ViewProviderFeaturePythonImp::getElement(const SoDetail *det, std::string & PyErr_Clear(); return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return true; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::getElementPicked(const SoPickedPoint *pp, std::string &subname) const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::getElementPicked( + const SoPickedPoint* pp, + std::string& subname +) const { FC_PY_CALL_CHECK(getElementPicked); Base::PyGILStateLocker lock; try { PyObject* pivy = nullptr; - pivy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoPickedPoint *", const_cast(static_cast(pp)), 0); + pivy = Base::Interpreter().createSWIGPointerObj( + "pivy.coin", + "SoPickedPoint *", + const_cast(static_cast(pp)), + 0 + ); Py::Tuple args(1); args.setItem(0, Py::Object(pivy, true)); - Py::Object ret(Base::pyCall(py_getElementPicked.ptr(),args.ptr())); - if(!ret.isString()) + Py::Object ret(Base::pyCall(py_getElementPicked.ptr(), args.ptr())); + if (!ret.isString()) { return Rejected; + } subname = ret.as_string(); return Accepted; } @@ -327,23 +348,23 @@ ViewProviderFeaturePythonImp::getElementPicked(const SoPickedPoint *pp, std::str PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -bool ViewProviderFeaturePythonImp::getDetail(const char* name, SoDetail *&det) const +bool ViewProviderFeaturePythonImp::getDetail(const char* name, SoDetail*& det) const { - _FC_PY_CALL_CHECK(getDetail,return(false)); + _FC_PY_CALL_CHECK(getDetail, return (false)); // Run the onChanged method of the proxy object. Base::PyGILStateLocker lock; try { Py::Tuple args(1); args.setItem(0, Py::String(name)); - Py::Object pydet(Base::pyCall(py_getDetail.ptr(),args.ptr())); + Py::Object pydet(Base::pyCall(py_getDetail.ptr(), args.ptr())); void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoDetail *", pydet.ptr(), &ptr, 0); auto detail = static_cast(ptr); @@ -358,7 +379,7 @@ bool ViewProviderFeaturePythonImp::getDetail(const char* name, SoDetail *&det) c PyErr_Clear(); return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -366,7 +387,11 @@ bool ViewProviderFeaturePythonImp::getDetail(const char* name, SoDetail *&det) c } ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::getDetailPath( - const char* name, SoFullPath *path, bool append, SoDetail *&det) const + const char* name, + SoFullPath* path, + bool append, + SoDetail*& det +) const { FC_PY_CALL_CHECK(getDetailPath); @@ -374,23 +399,27 @@ ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::getDetailPath auto length = path->getLength(); try { PyObject* pivy = nullptr; - pivy = Base::Interpreter().createSWIGPointerObj("pivy.coin", "SoFullPath *", static_cast(path), 1); + pivy = Base::Interpreter() + .createSWIGPointerObj("pivy.coin", "SoFullPath *", static_cast(path), 1); path->ref(); Py::Tuple args(3); args.setItem(0, Py::String(name)); args.setItem(1, Py::Object(pivy, true)); args.setItem(2, Py::Boolean(append)); - Py::Object pyDet(Base::pyCall(py_getDetailPath.ptr(),args.ptr())); - if(!pyDet.isTrue()) + Py::Object pyDet(Base::pyCall(py_getDetailPath.ptr(), args.ptr())); + if (!pyDet.isTrue()) { return Rejected; - if(pyDet.isBoolean()) + } + if (pyDet.isBoolean()) { return Accepted; + } void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "SoDetail *", pyDet.ptr(), &ptr, 0); auto detail = static_cast(ptr); det = detail ? detail->copy() : nullptr; - if(det) + if (det) { return Accepted; + } delete det; } catch (const Base::Exception& e) { @@ -401,7 +430,7 @@ ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::getDetailPath PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } path->truncate(length); @@ -414,8 +443,7 @@ std::vector ViewProviderFeaturePythonImp::getSelectionShape(cons return {}; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::setEdit(int ModNum) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::setEdit(int ModNum) { FC_PY_CALL_CHECK(setEdit) @@ -424,9 +452,10 @@ ViewProviderFeaturePythonImp::setEdit(int ModNum) if (has__object__) { Py::Tuple args(1); args.setItem(0, Py::Long(ModNum)); - Py::Object ret(Base::pyCall(py_setEdit.ptr(),args.ptr())); - if (ret.isNone()) + Py::Object ret(Base::pyCall(py_setEdit.ptr(), args.ptr())); + if (ret.isNone()) { return NotImplemented; + } Py::Boolean ok(ret); bool value = static_cast(ok); return value ? Accepted : Rejected; @@ -435,9 +464,10 @@ ViewProviderFeaturePythonImp::setEdit(int ModNum) Py::Tuple args(2); args.setItem(0, Py::Object(object->getPyObject(), true)); args.setItem(1, Py::Long(ModNum)); - Py::Object ret(Base::pyCall(py_setEdit.ptr(),args.ptr())); - if (ret.isNone()) + Py::Object ret(Base::pyCall(py_setEdit.ptr(), args.ptr())); + if (ret.isNone()) { return NotImplemented; + } Py::Boolean ok(ret); bool value = static_cast(ok); return value ? Accepted : Rejected; @@ -448,15 +478,14 @@ ViewProviderFeaturePythonImp::setEdit(int ModNum) PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::unsetEdit(int ModNum) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::unsetEdit(int ModNum) { FC_PY_CALL_CHECK(unsetEdit) @@ -465,9 +494,10 @@ ViewProviderFeaturePythonImp::unsetEdit(int ModNum) if (has__object__) { Py::Tuple args(1); args.setItem(0, Py::Long(ModNum)); - Py::Object ret(Base::pyCall(py_unsetEdit.ptr(),args.ptr())); - if (ret.isNone()) + Py::Object ret(Base::pyCall(py_unsetEdit.ptr(), args.ptr())); + if (ret.isNone()) { return NotImplemented; + } Py::Boolean ok(ret); bool value = static_cast(ok); return value ? Accepted : Rejected; @@ -476,9 +506,10 @@ ViewProviderFeaturePythonImp::unsetEdit(int ModNum) Py::Tuple args(2); args.setItem(0, Py::Object(object->getPyObject(), true)); args.setItem(1, Py::Long(ModNum)); - Py::Object ret(Base::pyCall(py_unsetEdit.ptr(),args.ptr())); - if (ret.isNone()) + Py::Object ret(Base::pyCall(py_unsetEdit.ptr(), args.ptr())); + if (ret.isNone()) { return NotImplemented; + } Py::Boolean ok(ret); bool value = static_cast(ok); return value ? Accepted : Rejected; @@ -489,40 +520,43 @@ ViewProviderFeaturePythonImp::unsetEdit(int ModNum) PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::setEditViewer(View3DInventorViewer *viewer, int ModNum) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::setEditViewer( + View3DInventorViewer* viewer, + int ModNum +) { FC_PY_CALL_CHECK(setEditViewer) Base::PyGILStateLocker lock; try { Py::Tuple args(3); - args.setItem(0, Py::Object(object->getPyObject(),true)); - args.setItem(1, Py::Object(viewer->getPyObject(),true)); + args.setItem(0, Py::Object(object->getPyObject(), true)); + args.setItem(1, Py::Object(viewer->getPyObject(), true)); args.setItem(2, Py::Long(ModNum)); - Py::Object ret(Base::pyCall(py_setEditViewer.ptr(),args.ptr())); - return ret.isTrue()?Accepted:Rejected; + Py::Object ret(Base::pyCall(py_setEditViewer.ptr(), args.ptr())); + return ret.isTrue() ? Accepted : Rejected; } catch (Py::Exception&) { if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) { PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::unsetEditViewer(View3DInventorViewer *viewer) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::unsetEditViewer( + View3DInventorViewer* viewer +) { FC_PY_CALL_CHECK(unsetEditViewer) @@ -530,24 +564,23 @@ ViewProviderFeaturePythonImp::unsetEditViewer(View3DInventorViewer *viewer) Base::PyGILStateLocker lock; try { Py::Tuple args(2); - args.setItem(0, Py::Object(object->getPyObject(),true)); - args.setItem(1, Py::Object(viewer->getPyObject(),true)); - Py::Object ret(Base::pyCall(py_unsetEditViewer.ptr(),args.ptr())); - return ret.isTrue()?Accepted:Rejected; + args.setItem(0, Py::Object(object->getPyObject(), true)); + args.setItem(1, Py::Object(viewer->getPyObject(), true)); + Py::Object ret(Base::pyCall(py_unsetEditViewer.ptr(), args.ptr())); + return ret.isTrue() ? Accepted : Rejected; } catch (Py::Exception&) { if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) { PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::doubleClicked() +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::doubleClicked() { FC_PY_CALL_CHECK(doubleClicked) @@ -562,7 +595,7 @@ ViewProviderFeaturePythonImp::doubleClicked() else { Py::Tuple args(1); args.setItem(0, Py::Object(object->getPyObject(), true)); - Py::Boolean ok(Base::pyCall(py_doubleClicked.ptr(),args.ptr())); + Py::Boolean ok(Base::pyCall(py_doubleClicked.ptr(), args.ptr())); bool value = (bool)ok; return value ? Accepted : Rejected; } @@ -572,7 +605,7 @@ ViewProviderFeaturePythonImp::doubleClicked() PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -581,7 +614,7 @@ ViewProviderFeaturePythonImp::doubleClicked() bool ViewProviderFeaturePythonImp::setupContextMenu(QMenu* menu) { - _FC_PY_CALL_CHECK(setupContextMenu,return(false)); + _FC_PY_CALL_CHECK(setupContextMenu, return (false)); // Run the attach method of the proxy object. Base::PyGILStateLocker lock; @@ -592,7 +625,7 @@ bool ViewProviderFeaturePythonImp::setupContextMenu(QMenu* menu) wrap.loadWidgetsModule(); Py::Tuple args(1); args.setItem(0, wrap.fromQWidget(menu, "QMenu")); - return Base::pyCall(py_setupContextMenu.ptr(),args.ptr()).isTrue(); + return Base::pyCall(py_setupContextMenu.ptr(), args.ptr()).isTrue(); } else { PythonWrapper wrap; @@ -601,7 +634,7 @@ bool ViewProviderFeaturePythonImp::setupContextMenu(QMenu* menu) Py::Tuple args(2); args.setItem(0, Py::Object(object->getPyObject(), true)); args.setItem(1, wrap.fromQWidget(menu, "QMenu")); - return Base::pyCall(py_setupContextMenu.ptr(),args.ptr()).isTrue(); + return Base::pyCall(py_setupContextMenu.ptr(), args.ptr()).isTrue(); } } catch (Py::Exception&) { @@ -609,15 +642,15 @@ bool ViewProviderFeaturePythonImp::setupContextMenu(QMenu* menu) PyErr_Clear(); return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return true; } -void ViewProviderFeaturePythonImp::attach(App::DocumentObject *pcObject) +void ViewProviderFeaturePythonImp::attach(App::DocumentObject* pcObject) { - _FC_PY_CALL_CHECK(attach,return); + _FC_PY_CALL_CHECK(attach, return); // Run the attach method of the proxy object. Base::PyGILStateLocker lock; @@ -628,7 +661,7 @@ void ViewProviderFeaturePythonImp::attach(App::DocumentObject *pcObject) else { Py::Tuple args(1); args.setItem(0, Py::Object(object->getPyObject(), true)); - Base::pyCall(py_attach.ptr(),args.ptr()); + Base::pyCall(py_attach.ptr(), args.ptr()); } // #0000415: Now simulate a property change event to call @@ -636,15 +669,16 @@ void ViewProviderFeaturePythonImp::attach(App::DocumentObject *pcObject) pcObject->Label.touch(); } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } void ViewProviderFeaturePythonImp::updateData(const App::Property* prop) { - if(py_updateData.isNone()) + if (py_updateData.isNone()) { return; + } // Run the updateData method of the proxy object. Base::PyGILStateLocker lock; @@ -654,7 +688,7 @@ void ViewProviderFeaturePythonImp::updateData(const App::Property* prop) const char* prop_name = object->getObject()->getPropertyName(prop); if (prop_name) { args.setItem(0, Py::String(prop_name)); - Base::pyCall(py_updateData.ptr(),args.ptr()); + Base::pyCall(py_updateData.ptr(), args.ptr()); } } else { @@ -663,20 +697,21 @@ void ViewProviderFeaturePythonImp::updateData(const App::Property* prop) const char* prop_name = object->getObject()->getPropertyName(prop); if (prop_name) { args.setItem(1, Py::String(prop_name)); - Base::pyCall(py_updateData.ptr(),args.ptr()); + Base::pyCall(py_updateData.ptr(), args.ptr()); } } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } void ViewProviderFeaturePythonImp::onChanged(const App::Property* prop) { - if(py_onChanged.isNone()) + if (py_onChanged.isNone()) { return; + } // Run the onChanged method of the proxy object. Base::PyGILStateLocker lock; @@ -686,7 +721,7 @@ void ViewProviderFeaturePythonImp::onChanged(const App::Property* prop) const char* prop_name = object->getPropertyName(prop); if (prop_name) { args.setItem(0, Py::String(prop_name)); - Base::pyCall(py_onChanged.ptr(),args.ptr()); + Base::pyCall(py_onChanged.ptr(), args.ptr()); } } else { @@ -695,20 +730,21 @@ void ViewProviderFeaturePythonImp::onChanged(const App::Property* prop) const char* prop_name = object->getPropertyName(prop); if (prop_name) { args.setItem(1, Py::String(prop_name)); - Base::pyCall(py_onChanged.ptr(),args.ptr()); + Base::pyCall(py_onChanged.ptr(), args.ptr()); } } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } void ViewProviderFeaturePythonImp::onBeforeChange(const App::Property* prop) { - if(py_onBeforeChange.isNone()) + if (py_onBeforeChange.isNone()) { return; + } // Run the onChanged method of the proxy object. Base::PyGILStateLocker lock; @@ -718,7 +754,7 @@ void ViewProviderFeaturePythonImp::onBeforeChange(const App::Property* prop) const char* prop_name = object->getPropertyName(prop); if (prop_name) { args.setItem(0, Py::String(prop_name)); - Base::pyCall(py_onBeforeChange.ptr(),args.ptr()); + Base::pyCall(py_onBeforeChange.ptr(), args.ptr()); } } else { @@ -727,19 +763,18 @@ void ViewProviderFeaturePythonImp::onBeforeChange(const App::Property* prop) const char* prop_name = object->getPropertyName(prop); if (prop_name) { args.setItem(1, Py::String(prop_name)); - Base::pyCall(py_onBeforeChange.ptr(),args.ptr()); + Base::pyCall(py_onBeforeChange.ptr(), args.ptr()); } } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } void ViewProviderFeaturePythonImp::startRestoring() -{ -} +{} void ViewProviderFeaturePythonImp::finishRestoring() { @@ -749,12 +784,14 @@ void ViewProviderFeaturePythonImp::finishRestoring() if (vp.isNone()) { object->show(); Proxy.setValue(Py::Long(1)); - } else { - _FC_PY_CALL_CHECK(finishRestoring,return); + } + else { + _FC_PY_CALL_CHECK(finishRestoring, return); Base::pyCall(py_finishRestoring.ptr()); } - }catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + } + catch (Py::Exception&) { + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -785,31 +822,32 @@ void ViewProviderFeaturePythonImp::beforeDelete() } } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::onDelete(const std::vector & sub) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::onDelete( + const std::vector& sub +) { FC_PY_CALL_CHECK(onDelete); Base::PyGILStateLocker lock; try { Py::Tuple seq(sub.size()); - int index=0; - for (const auto & it : sub) { + int index = 0; + for (const auto& it : sub) { seq.setItem(index++, Py::String(it)); } if (has__object__) { Py::Tuple args(1); args.setItem(0, seq); - Py::Boolean ok(Base::pyCall(py_onDelete.ptr(),args.ptr())); - return ok?Accepted:Rejected; + Py::Boolean ok(Base::pyCall(py_onDelete.ptr(), args.ptr())); + return ok ? Accepted : Rejected; } else { Py::Tuple args(2); args.setItem(0, Py::Object(object->getPyObject(), true)); args.setItem(1, seq); - Py::Boolean ok(Base::pyCall(py_onDelete.ptr(),args.ptr())); - return ok?Accepted:Rejected; + Py::Boolean ok(Base::pyCall(py_onDelete.ptr(), args.ptr())); + return ok ? Accepted : Rejected; } } catch (Py::Exception&) { @@ -817,57 +855,58 @@ ViewProviderFeaturePythonImp::onDelete(const std::vector & sub) PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); return Rejected; } } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDelete(App::DocumentObject *obj) const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDelete( + App::DocumentObject* obj +) const { FC_PY_CALL_CHECK(canDelete); Base::PyGILStateLocker lock; try { Py::Tuple args(1); - args.setItem(0,obj?Py::Object(obj->getPyObject(),true):Py::Object()); - return Py::Boolean(Base::pyCall(py_canDelete.ptr(),args.ptr()))?Accepted:Rejected; + args.setItem(0, obj ? Py::Object(obj->getPyObject(), true) : Py::Object()); + return Py::Boolean(Base::pyCall(py_canDelete.ptr(), args.ptr())) ? Accepted : Rejected; } catch (Py::Exception&) { if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) { PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); return Rejected; } } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canAddToSceneGraph() const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canAddToSceneGraph() const { FC_PY_CALL_CHECK(canAddToSceneGraph); Base::PyGILStateLocker lock; try { - return Py::Boolean(Py::Callable(py_canAddToSceneGraph).apply(Py::Tuple()))?Accepted:Rejected; + return Py::Boolean(Py::Callable(py_canAddToSceneGraph).apply(Py::Tuple())) ? Accepted + : Rejected; } catch (Py::Exception&) { if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) { PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Accepted; } -bool ViewProviderFeaturePythonImp::getDefaultDisplayMode(std::string &mode) const +bool ViewProviderFeaturePythonImp::getDefaultDisplayMode(std::string& mode) const { - _FC_PY_CALL_CHECK(getDefaultDisplayMode,return(0)); + _FC_PY_CALL_CHECK(getDefaultDisplayMode, return (0)); // Run the getDefaultDisplayMode method of the proxy object. Base::PyGILStateLocker lock; @@ -881,7 +920,7 @@ bool ViewProviderFeaturePythonImp::getDefaultDisplayMode(std::string &mode) cons PyErr_Clear(); return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -891,7 +930,7 @@ bool ViewProviderFeaturePythonImp::getDefaultDisplayMode(std::string &mode) cons std::vector ViewProviderFeaturePythonImp::getDisplayModes() const { std::vector modes; - _FC_PY_CALL_CHECK(getDisplayModes,return(modes)); + _FC_PY_CALL_CHECK(getDisplayModes, return (modes)); // Run the getDisplayModes method of the proxy object. Base::PyGILStateLocker lock; @@ -906,7 +945,7 @@ std::vector ViewProviderFeaturePythonImp::getDisplayModes() const else { Py::Tuple args(1); args.setItem(0, Py::Object(object->getPyObject(), true)); - Py::Sequence list(Base::pyCall(py_getDisplayModes.ptr(),args.ptr())); + Py::Sequence list(Base::pyCall(py_getDisplayModes.ptr(), args.ptr())); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::String str(*it); modes.push_back(str.as_std_string("ascii")); @@ -914,10 +953,11 @@ std::vector ViewProviderFeaturePythonImp::getDisplayModes() const } } catch (Py::Exception&) { - if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) + if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) { PyErr_Clear(); + } else { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -927,26 +967,25 @@ std::vector ViewProviderFeaturePythonImp::getDisplayModes() const std::string ViewProviderFeaturePythonImp::setDisplayMode(const char* ModeName) { - _FC_PY_CALL_CHECK(setDisplayMode,return(ModeName)); + _FC_PY_CALL_CHECK(setDisplayMode, return (ModeName)); // Run the setDisplayMode method of the proxy object. Base::PyGILStateLocker lock; try { Py::Tuple args(1); args.setItem(0, Py::String(ModeName)); - Py::String str(Base::pyCall(py_setDisplayMode.ptr(),args.ptr())); + Py::String str(Base::pyCall(py_setDisplayMode.ptr(), args.ptr())); return str.as_std_string("ascii"); } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return ModeName; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDragObjects() const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDragObjects() const { FC_PY_CALL_CHECK(canDragObjects); @@ -960,15 +999,16 @@ ViewProviderFeaturePythonImp::canDragObjects() const PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDragObject(App::DocumentObject* obj) const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDragObject( + App::DocumentObject* obj +) const { FC_PY_CALL_CHECK(canDragObject); @@ -976,7 +1016,7 @@ ViewProviderFeaturePythonImp::canDragObject(App::DocumentObject* obj) const try { Py::Tuple args(1); args.setItem(0, Py::Object(obj->getPyObject(), true)); - Py::Boolean ok(Base::pyCall(py_canDragObject.ptr(),args.ptr())); + Py::Boolean ok(Base::pyCall(py_canDragObject.ptr(), args.ptr())); return static_cast(ok) ? Accepted : Rejected; } catch (Py::Exception&) { @@ -984,15 +1024,14 @@ ViewProviderFeaturePythonImp::canDragObject(App::DocumentObject* obj) const PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::dragObject(App::DocumentObject* obj) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::dragObject(App::DocumentObject* obj) { FC_PY_CALL_CHECK(dragObject); @@ -1002,14 +1041,14 @@ ViewProviderFeaturePythonImp::dragObject(App::DocumentObject* obj) if (has__object__) { Py::Tuple args(1); args.setItem(0, Py::Object(obj->getPyObject(), true)); - Base::pyCall(py_dragObject.ptr(),args.ptr()); + Base::pyCall(py_dragObject.ptr(), args.ptr()); return Accepted; } else { Py::Tuple args(2); args.setItem(0, Py::Object(object->getPyObject(), true)); args.setItem(1, Py::Object(obj->getPyObject(), true)); - Base::pyCall(py_dragObject.ptr(),args.ptr()); + Base::pyCall(py_dragObject.ptr(), args.ptr()); return Accepted; } } @@ -1018,15 +1057,14 @@ ViewProviderFeaturePythonImp::dragObject(App::DocumentObject* obj) PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDropObjects() const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDropObjects() const { FC_PY_CALL_CHECK(canDropObjects); @@ -1040,15 +1078,16 @@ ViewProviderFeaturePythonImp::canDropObjects() const PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDropObject(App::DocumentObject* obj) const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDropObject( + App::DocumentObject* obj +) const { FC_PY_CALL_CHECK(canDropObject); @@ -1056,7 +1095,7 @@ ViewProviderFeaturePythonImp::canDropObject(App::DocumentObject* obj) const try { Py::Tuple args(1); args.setItem(0, Py::Object(obj->getPyObject(), true)); - Py::Boolean ok(Base::pyCall(py_canDropObject.ptr(),args.ptr())); + Py::Boolean ok(Base::pyCall(py_canDropObject.ptr(), args.ptr())); return static_cast(ok) ? Accepted : Rejected; } catch (Py::Exception&) { @@ -1064,15 +1103,14 @@ ViewProviderFeaturePythonImp::canDropObject(App::DocumentObject* obj) const PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::dropObject(App::DocumentObject* obj) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::dropObject(App::DocumentObject* obj) { FC_PY_CALL_CHECK(dropObject); @@ -1081,14 +1119,14 @@ ViewProviderFeaturePythonImp::dropObject(App::DocumentObject* obj) if (has__object__) { Py::Tuple args(1); args.setItem(0, Py::Object(obj->getPyObject(), true)); - Base::pyCall(py_dropObject.ptr(),args.ptr()); + Base::pyCall(py_dropObject.ptr(), args.ptr()); return Accepted; } else { Py::Tuple args(2); args.setItem(0, Py::Object(object->getPyObject(), true)); args.setItem(1, Py::Object(obj->getPyObject(), true)); - Base::pyCall(py_dropObject.ptr(),args.ptr()); + Base::pyCall(py_dropObject.ptr(), args.ptr()); return Accepted; } } @@ -1103,15 +1141,16 @@ ViewProviderFeaturePythonImp::dropObject(App::DocumentObject* obj) return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDragAndDropObject(App::DocumentObject *obj) const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDragAndDropObject( + App::DocumentObject* obj +) const { FC_PY_CALL_CHECK(canDragAndDropObject); Base::PyGILStateLocker lock; try { - Py::TupleN args(Py::Object(obj->getPyObject(),true)); - Py::Boolean ok(Base::pyCall(py_canDragAndDropObject.ptr(),args.ptr())); + Py::TupleN args(Py::Object(obj->getPyObject(), true)); + Py::Boolean ok(Base::pyCall(py_canDragAndDropObject.ptr(), args.ptr())); return static_cast(ok) ? Accepted : Rejected; } catch (Py::Exception&) { @@ -1119,16 +1158,19 @@ ViewProviderFeaturePythonImp::canDragAndDropObject(App::DocumentObject *obj) con PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canDropObjectEx(App::DocumentObject* obj, - App::DocumentObject *owner, const char *subname, const std::vector &elements) const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements +) const { FC_PY_CALL_CHECK(canDropObjectEx); @@ -1136,14 +1178,15 @@ ViewProviderFeaturePythonImp::canDropObjectEx(App::DocumentObject* obj, try { Py::Tuple args(4); args.setItem(0, Py::Object(obj->getPyObject(), true)); - args.setItem(1, owner?Py::Object(owner->getPyObject(), true):Py::None()); - args.setItem(2, Py::String(subname?subname:"")); + args.setItem(1, owner ? Py::Object(owner->getPyObject(), true) : Py::None()); + args.setItem(2, Py::String(subname ? subname : "")); Py::Tuple tuple(elements.size()); - int i=0; - for(auto &element : elements) - tuple.setItem(i++,Py::String(element)); + int i = 0; + for (auto& element : elements) { + tuple.setItem(i++, Py::String(element)); + } args.setItem(3, tuple); - Py::Boolean ok(Base::pyCall(py_canDropObjectEx.ptr(),args.ptr())); + Py::Boolean ok(Base::pyCall(py_canDropObjectEx.ptr(), args.ptr())); return static_cast(ok) ? Accepted : Rejected; } catch (Py::Exception&) { @@ -1151,33 +1194,42 @@ ViewProviderFeaturePythonImp::canDropObjectEx(App::DocumentObject* obj, PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -bool ViewProviderFeaturePythonImp::dropObjectEx(App::DocumentObject* obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements,std::string &ret) +bool ViewProviderFeaturePythonImp::dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements, + std::string& ret +) { - _FC_PY_CALL_CHECK(dropObjectEx, return(false)); + _FC_PY_CALL_CHECK(dropObjectEx, return (false)); Base::PyGILStateLocker lock; try { Py::Tuple tuple(elements.size()); - int i=0; - for(auto &element : elements) - tuple.setItem(i++,Py::String(element)); + int i = 0; + for (auto& element : elements) { + tuple.setItem(i++, Py::String(element)); + } Py::Object res; Py::TupleN args( - Py::Object(object->getPyObject(),true), - Py::Object(obj->getPyObject(),true), - owner?Py::Object(owner->getPyObject(),true):Py::Object(), - Py::String(subname?subname:""),tuple); - res = Base::pyCall(py_dropObjectEx.ptr(),args.ptr()); - if(!res.isNone()) + Py::Object(object->getPyObject(), true), + Py::Object(obj->getPyObject(), true), + owner ? Py::Object(owner->getPyObject(), true) : Py::Object(), + Py::String(subname ? subname : ""), + tuple + ); + res = Base::pyCall(py_dropObjectEx.ptr(), args.ptr()); + if (!res.isNone()) { ret = res.as_string(); + } return true; } catch (Py::Exception&) { @@ -1190,8 +1242,7 @@ bool ViewProviderFeaturePythonImp::dropObjectEx(App::DocumentObject* obj, App::D return true; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::isShow() const +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::isShow() const { FC_PY_CALL_CHECK(isShow); @@ -1205,7 +1256,7 @@ ViewProviderFeaturePythonImp::isShow() const PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } @@ -1213,8 +1264,8 @@ ViewProviderFeaturePythonImp::isShow() const } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::canRemoveChildrenFromRoot() const { +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::canRemoveChildrenFromRoot() const +{ FC_PY_CALL_CHECK(canRemoveChildrenFromRoot); @@ -1228,21 +1279,23 @@ ViewProviderFeaturePythonImp::canRemoveChildrenFromRoot() const { PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } -bool ViewProviderFeaturePythonImp::getDropPrefix(std::string &prefix) const { +bool ViewProviderFeaturePythonImp::getDropPrefix(std::string& prefix) const +{ - _FC_PY_CALL_CHECK(getDropPrefix,return(false)); + _FC_PY_CALL_CHECK(getDropPrefix, return (false)); Base::PyGILStateLocker lock; try { Py::Object ret(Base::pyCall(py_getDropPrefix.ptr())); - if(ret.isNone()) + if (ret.isNone()) { return false; + } prefix = ret.as_string(); return true; } @@ -1251,27 +1304,27 @@ bool ViewProviderFeaturePythonImp::getDropPrefix(std::string &prefix) const { PyErr_Clear(); return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return true; } -ViewProviderFeaturePythonImp::ValueT -ViewProviderFeaturePythonImp::replaceObject( - App::DocumentObject *oldObj, App::DocumentObject *newObj) +ViewProviderFeaturePythonImp::ValueT ViewProviderFeaturePythonImp::replaceObject( + App::DocumentObject* oldObj, + App::DocumentObject* newObj +) { - if(!oldObj || !oldObj->isAttachedToDocument() - || !newObj || !newObj->isAttachedToDocument()) + if (!oldObj || !oldObj->isAttachedToDocument() || !newObj || !newObj->isAttachedToDocument()) { return NotImplemented; + } FC_PY_CALL_CHECK(replaceObject); Base::PyGILStateLocker lock; try { - Py::TupleN args(Py::asObject(oldObj->getPyObject()), - Py::asObject(newObj->getPyObject())); - Py::Boolean ok(Base::pyCall(py_replaceObject.ptr(),args.ptr())); + Py::TupleN args(Py::asObject(oldObj->getPyObject()), Py::asObject(newObj->getPyObject())); + Py::Boolean ok(Base::pyCall(py_replaceObject.ptr(), args.ptr())); return ok ? Accepted : Rejected; } catch (Py::Exception&) { @@ -1279,37 +1332,44 @@ ViewProviderFeaturePythonImp::replaceObject( PyErr_Clear(); return NotImplemented; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return Rejected; } bool ViewProviderFeaturePythonImp::getLinkedViewProvider( - ViewProviderDocumentObject *&vp, std::string *subname, bool recursive) const + ViewProviderDocumentObject*& vp, + std::string* subname, + bool recursive +) const { - _FC_PY_CALL_CHECK(getLinkedViewProvider,return(false)); + _FC_PY_CALL_CHECK(getLinkedViewProvider, return (false)); Base::PyGILStateLocker lock; try { Py::Tuple args(1); - args.setItem(0,Py::Boolean(recursive)); - Py::Object res(Base::pyCall(py_getLinkedViewProvider.ptr(),args.ptr())); - if(res.isNone()) + args.setItem(0, Py::Boolean(recursive)); + Py::Object res(Base::pyCall(py_getLinkedViewProvider.ptr(), args.ptr())); + if (res.isNone()) { return true; - if(PyObject_TypeCheck(res.ptr(),&ViewProviderDocumentObjectPy::Type)) { - vp = static_cast( - res.ptr())->getViewProviderDocumentObjectPtr(); + } + if (PyObject_TypeCheck(res.ptr(), &ViewProviderDocumentObjectPy::Type)) { + vp = static_cast(res.ptr()) + ->getViewProviderDocumentObjectPtr(); return true; - } else if (PySequence_Check(res.ptr()) && PySequence_Length(res.ptr())==2) { + } + else if (PySequence_Check(res.ptr()) && PySequence_Length(res.ptr()) == 2) { Py::Sequence seq(res); Py::Object item0(seq[0].ptr()); Py::Object item1(seq[1].ptr()); - if(PyObject_TypeCheck(item0.ptr(), &ViewProviderDocumentObjectPy::Type) && item1.isString()) { - if(subname) + if (PyObject_TypeCheck(item0.ptr(), &ViewProviderDocumentObjectPy::Type) + && item1.isString()) { + if (subname) { *subname = Py::String(item1).as_std_string("utf-8"); - vp = static_cast( - item0.ptr())->getViewProviderDocumentObjectPtr(); + } + vp = static_cast(item0.ptr()) + ->getViewProviderDocumentObjectPtr(); return true; } } @@ -1321,20 +1381,20 @@ bool ViewProviderFeaturePythonImp::getLinkedViewProvider( PyErr_Clear(); return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return true; } -bool ViewProviderFeaturePythonImp::editProperty(const char *name) +bool ViewProviderFeaturePythonImp::editProperty(const char* name) { - _FC_PY_CALL_CHECK(editProperty,return false); + _FC_PY_CALL_CHECK(editProperty, return false); Base::PyGILStateLocker lock; try { Py::Tuple args(1); args.setItem(0, Py::String(name)); - Py::Object ret(Base::pyCall(py_editProperty.ptr(),args.ptr())); + Py::Object ret(Base::pyCall(py_editProperty.ptr(), args.ptr())); return ret.isTrue(); } catch (Py::Exception&) { @@ -1343,7 +1403,7 @@ bool ViewProviderFeaturePythonImp::editProperty(const char *name) return false; } - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } return false; @@ -1351,18 +1411,18 @@ bool ViewProviderFeaturePythonImp::editProperty(const char *name) // --------------------------------------------------------- -namespace Gui { +namespace Gui +{ PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderFeaturePython, Gui::ViewProviderDocumentObject) // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui // --------------------------------------------------------- -namespace Gui { +namespace Gui +{ PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderGeometryPython, Gui::ViewProviderGeometryObject) // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} - - +} // namespace Gui diff --git a/src/Gui/ViewProviderFeaturePython.h b/src/Gui/ViewProviderFeaturePython.h index af11302365..16570bbf9c 100644 --- a/src/Gui/ViewProviderFeaturePython.h +++ b/src/Gui/ViewProviderFeaturePython.h @@ -36,21 +36,23 @@ class SoSensor; class SoDragger; class SoNode; -namespace Gui { +namespace Gui +{ class SelectionChanges; class GuiExport ViewProviderFeaturePythonImp { public: - enum ValueT { - NotImplemented = 0, // not handled - Accepted = 1, // handled and accepted - Rejected = 2 // handled and rejected + enum ValueT + { + NotImplemented = 0, // not handled + Accepted = 1, // handled and accepted + Rejected = 2 // handled and rejected }; /// constructor. - ViewProviderFeaturePythonImp(ViewProviderDocumentObject*, App::PropertyPythonObject &); + ViewProviderFeaturePythonImp(ViewProviderDocumentObject*, App::PropertyPythonObject&); /// destructor. ~ViewProviderFeaturePythonImp(); @@ -61,10 +63,10 @@ public: bool claimChildren(std::vector&) const; ValueT useNewSelectionModel() const; void onSelectionChanged(const SelectionChanges&); - ValueT getElementPicked(const SoPickedPoint *pp, std::string &subname) const; - bool getElement(const SoDetail *det, std::string &) const; - bool getDetail(const char*, SoDetail *&det) const; - ValueT getDetailPath(const char *name, SoFullPath *path, bool append, SoDetail *&det) const; + ValueT getElementPicked(const SoPickedPoint* pp, std::string& subname) const; + bool getElement(const SoDetail* det, std::string&) const; + bool getDetail(const char*, SoDetail*& det) const; + ValueT getDetailPath(const char* name, SoFullPath* path, bool append, SoDetail*& det) const; std::vector getSelectionShape(const char* Element) const; ValueT setEdit(int ModNum); ValueT unsetEdit(int ModNum); @@ -75,15 +77,15 @@ public: /** @name Update data methods*/ //@{ - void attach(App::DocumentObject *pcObject); + void attach(App::DocumentObject* pcObject); void updateData(const App::Property*); void onChanged(const App::Property* prop); void onBeforeChange(const App::Property* prop); void startRestoring(); void finishRestoring(); void beforeDelete(); - ValueT onDelete(const std::vector & sub); - ValueT canDelete(App::DocumentObject *obj) const; + ValueT onDelete(const std::vector& sub); + ValueT canDelete(App::DocumentObject* obj) const; //@} /** @name Display methods */ @@ -91,7 +93,7 @@ public: /// Returns true if the icon must always appear enabled in the tree view ValueT isShow() const; /// get the default display mode - bool getDefaultDisplayMode(std::string &mode) const; + bool getDefaultDisplayMode(std::string& mode) const; /// returns a list of all possible modes std::vector getDisplayModes() const; /// set the display mode @@ -117,28 +119,36 @@ public: /** Return false to force drop only operation for a give object*/ ValueT canDragAndDropObject(App::DocumentObject*) const; /** Query object dropping with full qualified name */ - ValueT canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *, - const char *,const std::vector &elements) const; + ValueT canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject*, + const char*, + const std::vector& elements + ) const; /** Add an object with full qualified name to the view provider by drag and drop */ - bool dropObjectEx(App::DocumentObject *obj, App::DocumentObject *, - const char *, const std::vector &elements, std::string &ret); - ValueT replaceObject(App::DocumentObject *, App::DocumentObject *); + bool dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject*, + const char*, + const std::vector& elements, + std::string& ret + ); + ValueT replaceObject(App::DocumentObject*, App::DocumentObject*); //@} - bool getLinkedViewProvider(ViewProviderDocumentObject *&res, - std::string *subname, bool recursive) const; + bool getLinkedViewProvider(ViewProviderDocumentObject*& res, std::string* subname, bool recursive) const; ValueT canAddToSceneGraph() const; - bool getDropPrefix(std::string &prefix) const; + bool getDropPrefix(std::string& prefix) const; - bool editProperty(const char *propName); + bool editProperty(const char* propName); private: ViewProviderDocumentObject* object; - App::PropertyPythonObject &Proxy; + App::PropertyPythonObject& Proxy; SelectionObserverPythonHandler selectionObserver; - bool has__object__{false}; + bool has__object__ {false}; #define FC_PY_VIEW_OBJECT \ FC_PY_ELEMENT(getIcon) \ @@ -183,7 +193,7 @@ private: FC_PY_ELEMENT(getDropPrefix) \ FC_PY_ELEMENT(replaceObject) \ FC_PY_ELEMENT(getLinkedViewProvider) \ - FC_PY_ELEMENT(editProperty) \ + FC_PY_ELEMENT(editProperty) #undef FC_PY_ELEMENT #define FC_PY_ELEMENT(_name) FC_PY_ELEMENT_DEFINE(_name) @@ -193,40 +203,45 @@ private: #undef FC_PY_ELEMENT #define FC_PY_ELEMENT(_name) FC_PY_ELEMENT_FLAG(_name) - enum Flag { - FC_PY_VIEW_OBJECT - FlagMax, + enum Flag + { + FC_PY_VIEW_OBJECT FlagMax, }; using Flags = std::bitset; mutable Flags _Flags; public: - void init(PyObject *pyobj); + void init(PyObject* pyobj); }; -template -class ViewProviderFeaturePythonT : public ViewProviderT +template +class ViewProviderFeaturePythonT: public ViewProviderT { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderFeaturePythonT); public: /// constructor. - ViewProviderFeaturePythonT() { - ADD_PROPERTY(Proxy,(Py::Object())); - imp = new ViewProviderFeaturePythonImp(this,Proxy); + ViewProviderFeaturePythonT() + { + ADD_PROPERTY(Proxy, (Py::Object())); + imp = new ViewProviderFeaturePythonImp(this, Proxy); } /// destructor. - ~ViewProviderFeaturePythonT() override { + ~ViewProviderFeaturePythonT() override + { delete imp; } // Returns the icon - QIcon getIcon() const override { + QIcon getIcon() const override + { QIcon icon = imp->getIcon(); - if (icon.isNull()) + if (icon.isNull()) { icon = ViewProviderT::getIcon(); - else + } + else { icon = ViewProviderT::mergeGreyableOverlayIcons(icon); + } return icon; } @@ -240,12 +255,12 @@ public: if (!overlayMap.empty()) { // Use the static instance of BitmapFactory to perform the merge for (const auto& [position, name] : overlayMap) { - static const QSize overlayIconSize { 10, 10 }; - QPixmap overlayPixmap = - Gui::BitmapFactory().pixmapFromSvg(name.c_str(), overlayIconSize); + static const QSize overlayIconSize {10, 10}; + QPixmap overlayPixmap + = Gui::BitmapFactory().pixmapFromSvg(name.c_str(), overlayIconSize); if (!overlayPixmap.isNull()) { - currentIcon = - Gui::BitmapFactoryInst::mergePixmap(currentIcon, overlayPixmap, position); + currentIcon + = Gui::BitmapFactoryInst::mergePixmap(currentIcon, overlayPixmap, position); } } } @@ -253,121 +268,146 @@ public: return ViewProviderT::mergeColorfulOverlayIcons(currentIcon); } - std::vector claimChildren() const override { - std::vector res; - if(!imp->claimChildren(res)) + std::vector claimChildren() const override + { + std::vector res; + if (!imp->claimChildren(res)) { return ViewProviderT::claimChildren(); + } return res; } /** @name Nodes */ //@{ - SoSeparator* getRoot() const override { + SoSeparator* getRoot() const override + { return ViewProviderT::getRoot(); } - SoSeparator* getFrontRoot() const override { + SoSeparator* getFrontRoot() const override + { return ViewProviderT::getFrontRoot(); } // returns the root node of the Provider (3D) - SoSeparator* getBackRoot() const override { + SoSeparator* getBackRoot() const override + { return ViewProviderT::getBackRoot(); } //@} /** @name Selection handling */ //@{ - bool useNewSelectionModel() const override { - switch(imp->useNewSelectionModel()) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::useNewSelectionModel(); + bool useNewSelectionModel() const override + { + switch (imp->useNewSelectionModel()) { + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::useNewSelectionModel(); } } /// called when the selection changes for the view provider - void onSelectionChanged(const SelectionChanges& changes) override { + void onSelectionChanged(const SelectionChanges& changes) override + { return imp->onSelectionChanged(changes); } - bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const override { - auto ret = imp->getElementPicked(pp,subname); - if(ret == ViewProviderFeaturePythonImp::NotImplemented) - return ViewProviderT::getElementPicked(pp,subname); - else if(ret == ViewProviderFeaturePythonImp::Accepted) + bool getElementPicked(const SoPickedPoint* pp, std::string& subname) const override + { + auto ret = imp->getElementPicked(pp, subname); + if (ret == ViewProviderFeaturePythonImp::NotImplemented) { + return ViewProviderT::getElementPicked(pp, subname); + } + else if (ret == ViewProviderFeaturePythonImp::Accepted) { return true; + } return false; } - std::string getElement(const SoDetail *det) const override { + std::string getElement(const SoDetail* det) const override + { std::string name; - if(!imp->getElement(det,name)) + if (!imp->getElement(det, name)) { return ViewProviderT::getElement(det); + } return name; } - SoDetail* getDetail(const char* name) const override { - SoDetail *det = nullptr; - if(imp->getDetail(name,det)) + SoDetail* getDetail(const char* name) const override + { + SoDetail* det = nullptr; + if (imp->getDetail(name, det)) { return det; + } return ViewProviderT::getDetail(name); } - bool getDetailPath(const char *name, SoFullPath *path, bool append,SoDetail *&det) const override { - auto ret = imp->getDetailPath(name,path,append,det); - if(ret == ViewProviderFeaturePythonImp::NotImplemented) - return ViewProviderT::getDetailPath(name,path,append,det); + bool getDetailPath(const char* name, SoFullPath* path, bool append, SoDetail*& det) const override + { + auto ret = imp->getDetailPath(name, path, append, det); + if (ret == ViewProviderFeaturePythonImp::NotImplemented) { + return ViewProviderT::getDetailPath(name, path, append, det); + } return ret == ViewProviderFeaturePythonImp::Accepted; } - std::vector getSelectionShape(const char* Element) const override { + std::vector getSelectionShape(const char* Element) const override + { return ViewProviderT::getSelectionShape(Element); }; //@} /** @name Update data methods*/ //@{ - void attach(App::DocumentObject *obj) override { + void attach(App::DocumentObject* obj) override + { // delay loading of the actual attach() method because the Python // view provider class is not attached yet ViewProviderT::pcObject = obj; } - void updateData(const App::Property* prop) override { + void updateData(const App::Property* prop) override + { imp->updateData(prop); ViewProviderT::updateData(prop); } - void getTaskViewContent(std::vector& c) const override { + void getTaskViewContent(std::vector& c) const override + { ViewProviderT::getTaskViewContent(c); } - void beforeDelete() override { + void beforeDelete() override + { imp->beforeDelete(); ViewProviderT::beforeDelete(); } - bool onDelete(const std::vector & sub) override { - switch(imp->onDelete(sub)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::onDelete(sub); + bool onDelete(const std::vector& sub) override + { + switch (imp->onDelete(sub)) { + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::onDelete(sub); } } - bool canDelete(App::DocumentObject *obj) const override { - switch(imp->canDelete(obj)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDelete(obj); + bool canDelete(App::DocumentObject* obj) const override + { + switch (imp->canDelete(obj)) { + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDelete(obj); } } //@} /** @name Restoring view provider from document load */ //@{ - void startRestoring() override { + void startRestoring() override + { ViewProviderT::startRestoring(); imp->startRestoring(); } - void finishRestoring() override { + void finishRestoring() override + { imp->finishRestoring(); ViewProviderT::finishRestoring(); } @@ -376,102 +416,118 @@ public: /** @name Drag and drop */ //@{ /// Returns true if the view provider generally supports dragging objects - bool canDragObjects() const override { + bool canDragObjects() const override + { switch (imp->canDragObjects()) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDragObjects(); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDragObjects(); } } /// Check whether the object can be removed from the view provider by drag and drop - bool canDragObject(App::DocumentObject* obj) const override { + bool canDragObject(App::DocumentObject* obj) const override + { switch (imp->canDragObject(obj)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDragObject(obj); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDragObject(obj); } } /// Starts to drag the object - void dragObject(App::DocumentObject* obj) override { + void dragObject(App::DocumentObject* obj) override + { App::AutoTransaction committer; switch (imp->dragObject(obj)) { - case ViewProviderFeaturePythonImp::Accepted: - case ViewProviderFeaturePythonImp::Rejected: - return; - default: - return ViewProviderT::dragObject(obj); + case ViewProviderFeaturePythonImp::Accepted: + case ViewProviderFeaturePythonImp::Rejected: + return; + default: + return ViewProviderT::dragObject(obj); } } /// Returns true if the view provider generally accepts dropping of objects - bool canDropObjects() const override { + bool canDropObjects() const override + { switch (imp->canDropObjects()) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDropObjects(); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDropObjects(); } } /// Check whether the object can be dropped to the view provider by drag and drop - bool canDropObject(App::DocumentObject* obj) const override { + bool canDropObject(App::DocumentObject* obj) const override + { switch (imp->canDropObject(obj)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDropObject(obj); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDropObject(obj); } } /// If the dropped object type is accepted the object will be added as child - void dropObject(App::DocumentObject* obj) override { + void dropObject(App::DocumentObject* obj) override + { App::AutoTransaction committer; switch (imp->dropObject(obj)) { - case ViewProviderFeaturePythonImp::Accepted: - case ViewProviderFeaturePythonImp::Rejected: - return; - default: - return ViewProviderT::dropObject(obj); + case ViewProviderFeaturePythonImp::Accepted: + case ViewProviderFeaturePythonImp::Rejected: + return; + default: + return ViewProviderT::dropObject(obj); } } /** Return false to force drop only operation for a give object*/ - bool canDragAndDropObject(App::DocumentObject *obj) const override { + bool canDragAndDropObject(App::DocumentObject* obj) const override + { switch (imp->canDragAndDropObject(obj)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDragAndDropObject(obj); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDragAndDropObject(obj); } } - bool canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) const override + bool canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements + ) const override { - switch (imp->canDropObjectEx(obj,owner,subname,elements)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canDropObjectEx(obj,owner,subname,elements); + switch (imp->canDropObjectEx(obj, owner, subname, elements)) { + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canDropObjectEx(obj, owner, subname, elements); } } /** Add an object with full qualified name to the view provider by drag and drop */ - std::string dropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) override + std::string dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements + ) override { App::AutoTransaction committer; std::string ret; - if(!imp->dropObjectEx(obj,owner,subname,elements,ret)) - ret = ViewProviderT::dropObjectEx(obj,owner,subname,elements); + if (!imp->dropObjectEx(obj, owner, subname, elements, ret)) { + ret = ViewProviderT::dropObjectEx(obj, owner, subname, elements); + } return ret; } //@} @@ -479,66 +535,75 @@ public: /** @name Display methods */ //@{ /// Returns true if the icon must always appear enabled in the tree view - bool isShow() const override { - switch(imp->isShow()) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::isShow(); + bool isShow() const override + { + switch (imp->isShow()) { + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::isShow(); } } /// get the default display mode - const char* getDefaultDisplayMode() const override { + const char* getDefaultDisplayMode() const override + { defaultMode.clear(); - if(imp->getDefaultDisplayMode(defaultMode)) + if (imp->getDefaultDisplayMode(defaultMode)) { return defaultMode.c_str(); + } return ViewProviderT::getDefaultDisplayMode(); } /// returns a list of all possible modes - std::vector getDisplayModes() const override { + std::vector getDisplayModes() const override + { std::vector modes = ViewProviderT::getDisplayModes(); std::vector more_modes = imp->getDisplayModes(); modes.insert(modes.end(), more_modes.begin(), more_modes.end()); return modes; } /// set the display mode - void setDisplayMode(const char* ModeName) override { + void setDisplayMode(const char* ModeName) override + { std::string mask = imp->setDisplayMode(ModeName); ViewProviderT::setDisplayMaskMode(mask.c_str()); ViewProviderT::setDisplayMode(ModeName); } //@} - bool canRemoveChildrenFromRoot() const override { - switch(imp->canRemoveChildrenFromRoot()) { - case ViewProviderFeaturePythonImp::NotImplemented: - return ViewProviderT::canRemoveChildrenFromRoot(); - case ViewProviderFeaturePythonImp::Accepted: - return true; - default: - return false; + bool canRemoveChildrenFromRoot() const override + { + switch (imp->canRemoveChildrenFromRoot()) { + case ViewProviderFeaturePythonImp::NotImplemented: + return ViewProviderT::canRemoveChildrenFromRoot(); + case ViewProviderFeaturePythonImp::Accepted: + return true; + default: + return false; } } - PyObject* getPyObject() override { + PyObject* getPyObject() override + { return ViewProviderT::getPyObject(); } - bool canAddToSceneGraph() const override { - switch(imp->canAddToSceneGraph()) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::canAddToSceneGraph(); + bool canAddToSceneGraph() const override + { + switch (imp->canAddToSceneGraph()) { + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::canAddToSceneGraph(); } } protected: - void onChanged(const App::Property* prop) override { + void onChanged(const App::Property* prop) override + { if (prop == &Proxy) { imp->init(Proxy.getValue().ptr()); if (ViewProviderT::pcObject && !Proxy.getValue().is(Py::_None())) { @@ -550,8 +615,7 @@ protected: ViewProviderT::DisplayMode.touch(); ViewProviderT::setOverrideMode(viewerMode); } - if (!this->testStatus(Gui::isRestoring) && - !canAddToSceneGraph()) { + if (!this->testStatus(Gui::isRestoring) && !canAddToSceneGraph()) { this->getDocument()->toggleInSceneGraph(this); } ViewProviderT::updateView(); @@ -570,71 +634,85 @@ protected: bool setEdit(int ModNum) override { switch (imp->setEdit(ModNum)) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::setEdit(ModNum); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::setEdit(ModNum); } } /// is called when you lose the edit mode void unsetEdit(int ModNum) override { switch (imp->unsetEdit(ModNum)) { - case ViewProviderFeaturePythonImp::Accepted: - return; - case ViewProviderFeaturePythonImp::Rejected: - default: - return ViewProviderT::unsetEdit(ModNum); + case ViewProviderFeaturePythonImp::Accepted: + return; + case ViewProviderFeaturePythonImp::Rejected: + default: + return ViewProviderT::unsetEdit(ModNum); } } - void setEditViewer(View3DInventorViewer *viewer, int ModNum) override { - if (imp->setEditViewer(viewer,ModNum) == ViewProviderFeaturePythonImp::NotImplemented) - ViewProviderT::setEditViewer(viewer,ModNum); + void setEditViewer(View3DInventorViewer* viewer, int ModNum) override + { + if (imp->setEditViewer(viewer, ModNum) == ViewProviderFeaturePythonImp::NotImplemented) { + ViewProviderT::setEditViewer(viewer, ModNum); + } } - void unsetEditViewer(View3DInventorViewer *viewer) override { - if (imp->unsetEditViewer(viewer) == ViewProviderFeaturePythonImp::NotImplemented) + void unsetEditViewer(View3DInventorViewer* viewer) override + { + if (imp->unsetEditViewer(viewer) == ViewProviderFeaturePythonImp::NotImplemented) { ViewProviderT::unsetEditViewer(viewer); + } } - std::string getDropPrefix() const override { + std::string getDropPrefix() const override + { std::string prefix; - if(!imp->getDropPrefix(prefix)) + if (!imp->getDropPrefix(prefix)) { return ViewProviderT::getDropPrefix(); + } return prefix; } - int replaceObject(App::DocumentObject *oldObj, App::DocumentObject *newObj) override { + int replaceObject(App::DocumentObject* oldObj, App::DocumentObject* newObj) override + { App::AutoTransaction committer; - switch (imp->replaceObject(oldObj,newObj)) { - case ViewProviderFeaturePythonImp::Accepted: - return 1; - case ViewProviderFeaturePythonImp::Rejected: - return 0; - default: - return ViewProviderT::replaceObject(oldObj,newObj); + switch (imp->replaceObject(oldObj, newObj)) { + case ViewProviderFeaturePythonImp::Accepted: + return 1; + case ViewProviderFeaturePythonImp::Rejected: + return 0; + default: + return ViewProviderT::replaceObject(oldObj, newObj); } } - ViewProviderDocumentObject *getLinkedViewProvider( - std::string *subname=nullptr, bool recursive=false) const override{ - ViewProviderDocumentObject *res = nullptr; - if(!imp->getLinkedViewProvider(res, subname, recursive)) - res = ViewProviderT::getLinkedViewProvider(subname,recursive); + ViewProviderDocumentObject* getLinkedViewProvider( + std::string* subname = nullptr, + bool recursive = false + ) const override + { + ViewProviderDocumentObject* res = nullptr; + if (!imp->getLinkedViewProvider(res, subname, recursive)) { + res = ViewProviderT::getLinkedViewProvider(subname, recursive); + } return res; } - void editProperty(const char *propName) override { - if (!imp->editProperty(propName)) + void editProperty(const char* propName) override + { + if (!imp->editProperty(propName)) { ViewProviderT::editProperty(propName); + } } public: void setupContextMenu(QMenu* menu, QObject* recipient, const char* member) override { - if(!imp->setupContextMenu(menu)) + if (!imp->setupContextMenu(menu)) { ViewProviderT::setupContextMenu(menu, recipient, member); + } } protected: @@ -642,15 +720,15 @@ protected: { App::AutoTransaction committer; switch (imp->doubleClicked()) { - case ViewProviderFeaturePythonImp::Accepted: - return true; - case ViewProviderFeaturePythonImp::Rejected: - return false; - default: - return ViewProviderT::doubleClicked(); + case ViewProviderFeaturePythonImp::Accepted: + return true; + case ViewProviderFeaturePythonImp::Rejected: + return false; + default: + return ViewProviderT::doubleClicked(); } } - void setOverrideMode(const std::string &mode) override + void setOverrideMode(const std::string& mode) override { ViewProviderT::setOverrideMode(mode); viewerMode = mode; @@ -659,22 +737,21 @@ protected: public: ViewProviderFeaturePythonT(const ViewProviderFeaturePythonT&) = delete; ViewProviderFeaturePythonT(ViewProviderFeaturePythonT&&) = delete; - ViewProviderFeaturePythonT& operator= (const ViewProviderFeaturePythonT&) = delete; - ViewProviderFeaturePythonT& operator= (ViewProviderFeaturePythonT&&) = delete; + ViewProviderFeaturePythonT& operator=(const ViewProviderFeaturePythonT&) = delete; + ViewProviderFeaturePythonT& operator=(ViewProviderFeaturePythonT&&) = delete; private: ViewProviderFeaturePythonImp* imp; App::PropertyPythonObject Proxy; mutable std::string defaultMode; std::string viewerMode; - bool _attached{false}; + bool _attached {false}; }; // Special Feature-Python classes -using ViewProviderFeaturePython = ViewProviderFeaturePythonT; +using ViewProviderFeaturePython = ViewProviderFeaturePythonT; using ViewProviderGeometryPython = ViewProviderFeaturePythonT; -} // namespace Gui - -#endif // GUI_VIEWPROVIDERFEATUREPYTHON_H +} // namespace Gui +#endif // GUI_VIEWPROVIDERFEATUREPYTHON_H diff --git a/src/Gui/ViewProviderGeoFeatureGroup.cpp b/src/Gui/ViewProviderGeoFeatureGroup.cpp index 79c3a82f68..4efdb214ad 100644 --- a/src/Gui/ViewProviderGeoFeatureGroup.cpp +++ b/src/Gui/ViewProviderGeoFeatureGroup.cpp @@ -22,7 +22,6 @@ ***************************************************************************/ - #include "ViewProviderGeoFeatureGroup.h" @@ -41,11 +40,12 @@ ViewProviderGeoFeatureGroup::~ViewProviderGeoFeatureGroup() = default; // Python feature ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderGeoFeatureGroupPython, Gui::ViewProviderGeoFeatureGroup) /// @endcond // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderGeoFeatureGroup.h b/src/Gui/ViewProviderGeoFeatureGroup.h index a365ed91e8..2be0f08a92 100644 --- a/src/Gui/ViewProviderGeoFeatureGroup.h +++ b/src/Gui/ViewProviderGeoFeatureGroup.h @@ -30,10 +30,11 @@ #include "ViewProviderGeoFeatureGroupExtension.h" #include "ViewProviderFeaturePython.h" -namespace Gui { +namespace Gui +{ -class GuiExport ViewProviderGeoFeatureGroup : public ViewProviderDocumentObject, - public ViewProviderGeoFeatureGroupExtension +class GuiExport ViewProviderGeoFeatureGroup: public ViewProviderDocumentObject, + public ViewProviderGeoFeatureGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Gui::ViewProviderGeoFeatureGroup); @@ -46,7 +47,6 @@ public: using ViewProviderGeoFeatureGroupPython = ViewProviderFeaturePythonT; -} // namespace Gui - -#endif // GUI_VIEWPROVIDER_ViewProviderGeoFeatureGroup_H +} // namespace Gui +#endif // GUI_VIEWPROVIDER_ViewProviderGeoFeatureGroup_H diff --git a/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp b/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp index 7610493478..3e2775a7dd 100644 --- a/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp +++ b/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp @@ -23,7 +23,6 @@ ***************************************************************************/ - #include @@ -63,9 +62,10 @@ ViewProviderGeoFeatureGroupExtension::~ViewProviderGeoFeatureGroupExtension() } -std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren3D() const { +std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren3D() const +{ - //all object in the group must be claimed in 3D, as we are a coordinate system for all of them + // all object in the group must be claimed in 3D, as we are a coordinate system for all of them auto* obj = getExtendedViewProvider()->getObject(); auto* ext = obj ? obj->getExtensionByType() : nullptr; if (ext) { @@ -75,7 +75,8 @@ std::vector ViewProviderGeoFeatureGroupExtension::extensio return {}; } -std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren() const { +std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren() const +{ auto* obj = getExtendedViewProvider()->getObject(); if (!obj) { @@ -83,30 +84,37 @@ std::vector ViewProviderGeoFeatureGroupExtension::extensio } auto* group = obj->getExtensionByType(); - const std::vector &model = group->Group.getValues (); - std::set outSet; //< set of objects not to claim (childrens of childrens) + const std::vector& model = group->Group.getValues(); + std::set outSet; //< set of objects not to claim (childrens of childrens) // search for objects handled (claimed) by the features - for (auto obj: model) { - //stuff in another geofeaturegroup is not in the model anyway - if (!obj || obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId())) { continue; } + for (auto obj : model) { + // stuff in another geofeaturegroup is not in the model anyway + if (!obj || obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId())) { + continue; + } - Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider ( obj ); - if (!vp || vp == getExtendedViewProvider()) { continue; } + Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(obj); + if (!vp || vp == getExtendedViewProvider()) { + continue; + } auto children = vp->claimChildren(); - std::remove_copy ( children.begin (), children.end (), std::inserter (outSet, outSet.begin () ), nullptr); + std::remove_copy(children.begin(), children.end(), std::inserter(outSet, outSet.begin()), nullptr); } - // remove the otherwise handled objects, preserving their order so the order in the TreeWidget is correct + // remove the otherwise handled objects, preserving their order so the order in the TreeWidget + // is correct std::vector Result; - for(auto obj : model) { - if(!obj || !obj->isAttachedToDocument()) + for (auto obj : model) { + if (!obj || !obj->isAttachedToDocument()) { continue; - if(outSet.contains(obj)) - obj->setStatus(App::ObjectStatus::GeoExcluded,true); + } + if (outSet.contains(obj)) { + obj->setStatus(App::ObjectStatus::GeoExcluded, true); + } else { - obj->setStatus(App::ObjectStatus::GeoExcluded,false); + obj->setStatus(App::ObjectStatus::GeoExcluded, false); Result.push_back(obj); } } @@ -128,10 +136,11 @@ void ViewProviderGeoFeatureGroupExtension::extensionAttach(App::DocumentObject* void ViewProviderGeoFeatureGroupExtension::extensionSetDisplayMode(const char* ModeName) { - if ( strcmp("Group",ModeName)==0 ) + if (strcmp("Group", ModeName) == 0) { getExtendedViewProvider()->setDisplayMaskMode("Group"); + } - ViewProviderGroupExtension::extensionSetDisplayMode( ModeName ); + ViewProviderGroupExtension::extensionSetDisplayMode(ModeName); } std::vector ViewProviderGeoFeatureGroupExtension::extensionGetDisplayModes() const @@ -150,16 +159,20 @@ void ViewProviderGeoFeatureGroupExtension::extensionUpdateData(const App::Proper auto obj = getExtendedViewProvider()->getObject(); auto grp = obj ? obj->getExtensionByType() : nullptr; if (grp && prop == &grp->placement()) { - getExtendedViewProvider()->setTransformation ( grp->placement().getValue().toMatrix() ); + getExtendedViewProvider()->setTransformation(grp->placement().getValue().toMatrix()); } else { - ViewProviderGroupExtension::extensionUpdateData ( prop ); + ViewProviderGroupExtension::extensionUpdateData(prop); } } -namespace Gui { -EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderGeoFeatureGroupExtensionPython, Gui::ViewProviderGeoFeatureGroupExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + Gui::ViewProviderGeoFeatureGroupExtensionPython, + Gui::ViewProviderGeoFeatureGroupExtension +) // explicit template instantiation template class GuiExport ViewProviderExtensionPythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderGeoFeatureGroupExtension.h b/src/Gui/ViewProviderGeoFeatureGroupExtension.h index 9a4ba7f002..72cd7fc5d1 100644 --- a/src/Gui/ViewProviderGeoFeatureGroupExtension.h +++ b/src/Gui/ViewProviderGeoFeatureGroupExtension.h @@ -31,7 +31,7 @@ namespace Gui { -class GuiExport ViewProviderGeoFeatureGroupExtension : public ViewProviderGroupExtension +class GuiExport ViewProviderGeoFeatureGroupExtension: public ViewProviderGroupExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderGeoFeatureGroupExtension); @@ -40,35 +40,47 @@ public: ViewProviderGeoFeatureGroupExtension(); ~ViewProviderGeoFeatureGroupExtension() override; - std::vector extensionClaimChildren3D()const override; - std::vector< App::DocumentObject* > extensionClaimChildren() const override; - SoSeparator* extensionGetFrontRoot() const override {return pcGroupFront;} - SoSeparator* extensionGetBackRoot() const override {return pcGroupBack;} - SoGroup* extensionGetChildRoot() const override {return pcGroupChildren;} + std::vector extensionClaimChildren3D() const override; + std::vector extensionClaimChildren() const override; + SoSeparator* extensionGetFrontRoot() const override + { + return pcGroupFront; + } + SoSeparator* extensionGetBackRoot() const override + { + return pcGroupBack; + } + SoGroup* extensionGetChildRoot() const override + { + return pcGroupChildren; + } void extensionAttach(App::DocumentObject* pcObject) override; void extensionSetDisplayMode(const char* ModeName) override; std::vector extensionGetDisplayModes() const override; void extensionFinishRestoring() override; /// Show the object in the view: suppresses behavior of DocumentObjectGroup - void extensionShow() override { - ViewProviderExtension::extensionShow(); // clazy:exclude=skipped-base-method + void extensionShow() override + { + ViewProviderExtension::extensionShow(); // clazy:exclude=skipped-base-method } /// Hide the object in the view: suppresses behavior of DocumentObjectGroup - void extensionHide() override { - ViewProviderExtension::extensionHide(); // clazy:exclude=skipped-base-method + void extensionHide() override + { + ViewProviderExtension::extensionHide(); // clazy:exclude=skipped-base-method } void extensionUpdateData(const App::Property*) override; protected: - SoSeparator *pcGroupFront; - SoSeparator *pcGroupBack; - SoGroup *pcGroupChildren; + SoSeparator* pcGroupFront; + SoSeparator* pcGroupBack; + SoGroup* pcGroupChildren; }; -using ViewProviderGeoFeatureGroupExtensionPython = ViewProviderExtensionPythonT; +using ViewProviderGeoFeatureGroupExtensionPython + = ViewProviderExtensionPythonT; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDERGEOFEATUREGROUPEXTENSION_H +#endif // GUI_VIEWPROVIDERGEOFEATUREGROUPEXTENSION_H diff --git a/src/Gui/ViewProviderGeometryObject.cpp b/src/Gui/ViewProviderGeometryObject.cpp index d401848ca2..5ecba8fbd8 100644 --- a/src/Gui/ViewProviderGeometryObject.cpp +++ b/src/Gui/ViewProviderGeometryObject.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -66,20 +65,24 @@ ViewProviderGeometryObject::ViewProviderGeometryObject() static const char* sgroup = "Selection"; static const char* osgroup = "Object Style"; - ADD_PROPERTY_TYPE(Transparency, - (initialTransparency), - osgroup, - App::Prop_None, - "Set object transparency"); + ADD_PROPERTY_TYPE( + Transparency, + (initialTransparency), + osgroup, + App::Prop_None, + "Set object transparency" + ); Transparency.setConstraints(&intPercent); ADD_PROPERTY_TYPE(ShapeAppearance, (mat), osgroup, App::Prop_None, "Shape appearance"); ADD_PROPERTY_TYPE(BoundingBox, (false), dogroup, App::Prop_None, "Display object bounding box"); - ADD_PROPERTY_TYPE(Selectable, - (true), - sgroup, - App::Prop_None, - "Set if the object is selectable in the 3d view"); + ADD_PROPERTY_TYPE( + Selectable, + (true), + sgroup, + App::Prop_None, + "Set if the object is selectable in the 3d view" + ); pickStyle = new SoPickStyle(); pickStyle->ref(); @@ -113,8 +116,9 @@ ViewProviderGeometryObject::~ViewProviderGeometryObject() bool ViewProviderGeometryObject::isSelectionEnabled() const { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); return hGrp->GetBool("EnableSelection", true); } @@ -165,8 +169,7 @@ void ViewProviderGeometryObject::attach(App::DocumentObject* pcObj) void ViewProviderGeometryObject::updateData(const App::Property* prop) { if (prop->isDerivedFrom()) { - Base::BoundBox3d box = - static_cast(prop)->getBoundingBox(); + Base::BoundBox3d box = static_cast(prop)->getBoundingBox(); pcBoundingBox->minBounds.setValue(box.MinX, box.MinY, box.MinZ); pcBoundingBox->maxBounds.setValue(box.MaxX, box.MaxY, box.MaxZ); } @@ -203,9 +206,11 @@ void ViewProviderGeometryObject::updateData(const App::Property* prop) ViewProviderDragger::updateData(prop); } -SoPickedPointList ViewProviderGeometryObject::getPickedPoints(const SbVec2s& pos, - const View3DInventorViewer& viewer, - bool pickAll) const +SoPickedPointList ViewProviderGeometryObject::getPickedPoints( + const SbVec2s& pos, + const View3DInventorViewer& viewer, + bool pickAll +) const { auto root = new SoSeparator; root->ref(); @@ -224,8 +229,10 @@ SoPickedPointList ViewProviderGeometryObject::getPickedPoints(const SbVec2s& pos return rp.getPickedPointList(); } -SoPickedPoint* ViewProviderGeometryObject::getPickedPoint(const SbVec2s& pos, - const View3DInventorViewer& viewer) const +SoPickedPoint* ViewProviderGeometryObject::getPickedPoint( + const SbVec2s& pos, + const View3DInventorViewer& viewer +) const { auto root = new SoSeparator; root->ref(); @@ -247,8 +254,9 @@ SoPickedPoint* ViewProviderGeometryObject::getPickedPoint(const SbVec2s& pos, unsigned long ViewProviderGeometryObject::getBoundColor() const { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); // white (255,255,255) unsigned long bbcol = hGrp->GetUnsigned("BoundingBoxColor", 4294967295UL); return bbcol; @@ -256,18 +264,14 @@ unsigned long ViewProviderGeometryObject::getBoundColor() const void ViewProviderGeometryObject::setCoinAppearance(const App::Material& source) { - pcShapeMaterial->ambientColor.setValue(source.ambientColor.r, - source.ambientColor.g, - source.ambientColor.b); - pcShapeMaterial->diffuseColor.setValue(source.diffuseColor.r, - source.diffuseColor.g, - source.diffuseColor.b); - pcShapeMaterial->specularColor.setValue(source.specularColor.r, - source.specularColor.g, - source.specularColor.b); - pcShapeMaterial->emissiveColor.setValue(source.emissiveColor.r, - source.emissiveColor.g, - source.emissiveColor.b); + pcShapeMaterial->ambientColor + .setValue(source.ambientColor.r, source.ambientColor.g, source.ambientColor.b); + pcShapeMaterial->diffuseColor + .setValue(source.diffuseColor.r, source.diffuseColor.g, source.diffuseColor.b); + pcShapeMaterial->specularColor + .setValue(source.specularColor.r, source.specularColor.g, source.specularColor.b); + pcShapeMaterial->emissiveColor + .setValue(source.emissiveColor.r, source.emissiveColor.g, source.emissiveColor.b); pcShapeMaterial->shininess.setValue(source.shininess); pcShapeMaterial->transparency.setValue(source.transparency); } @@ -276,8 +280,9 @@ namespace { float getBoundBoxFontSize() { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); return hGrp->GetFloat("BoundingBoxFontSize", 10.0); } } // namespace @@ -360,9 +365,11 @@ PyObject* ViewProviderGeometryObject::getPyObject() return pyViewObject; } -void ViewProviderGeometryObject::handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) +void ViewProviderGeometryObject::handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName +) { if (strcmp(PropName, "ShapeColor") == 0 && strcmp(TypeName, App::PropertyColor::getClassTypeId().getName()) == 0) { diff --git a/src/Gui/ViewProviderGeometryObject.h b/src/Gui/ViewProviderGeometryObject.h index 71a885684a..bba4d6aa18 100644 --- a/src/Gui/ViewProviderGeometryObject.h +++ b/src/Gui/ViewProviderGeometryObject.h @@ -79,9 +79,11 @@ public: * If \a pickAll is false (the default) only the intersection point closest to the camera will * be picked, otherwise all intersection points will be picked. */ - SoPickedPointList getPickedPoints(const SbVec2s& pos, - const View3DInventorViewer& viewer, - bool pickAll = false) const; + SoPickedPointList getPickedPoints( + const SbVec2s& pos, + const View3DInventorViewer& viewer, + bool pickAll = false + ) const; /** * This method is provided for convenience and does basically the same as getPickedPoints() * unless that only the closest point to the camera will be picked. \note It is in the response @@ -104,9 +106,11 @@ protected: virtual unsigned long getBoundColor() const; - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; void setCoinAppearance(const App::Material& source); private: diff --git a/src/Gui/ViewProviderGeometryObject.pyi b/src/Gui/ViewProviderGeometryObject.pyi index 6034c942ff..14ee732de4 100644 --- a/src/Gui/ViewProviderGeometryObject.pyi +++ b/src/Gui/ViewProviderGeometryObject.pyi @@ -1,7 +1,6 @@ from Base.Metadata import no_args from ViewProviderDocumentObject import ViewProviderDocumentObject - class ViewProviderGeometryObject(ViewProviderDocumentObject): """ This is the ViewProvider geometry class diff --git a/src/Gui/ViewProviderGeometryObjectPyImp.cpp b/src/Gui/ViewProviderGeometryObjectPyImp.cpp index fb7c48c5a4..d257c7331d 100644 --- a/src/Gui/ViewProviderGeometryObjectPyImp.cpp +++ b/src/Gui/ViewProviderGeometryObjectPyImp.cpp @@ -22,7 +22,6 @@ **************************************************************************/ - #include diff --git a/src/Gui/ViewProviderGroupExtension.cpp b/src/Gui/ViewProviderGroupExtension.cpp index f6e7ca2954..5638807940 100644 --- a/src/Gui/ViewProviderGroupExtension.cpp +++ b/src/Gui/ViewProviderGroupExtension.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -42,48 +41,50 @@ using namespace Gui; -namespace { - // helper function to recursively delete group contents while respecting view provider onDelete methods - void deleteGroupContentsRecursively(App::GroupExtension* group) { - if (!group) { - return; +namespace +{ +// helper function to recursively delete group contents while respecting view provider onDelete methods +void deleteGroupContentsRecursively(App::GroupExtension* group) +{ + if (!group) { + return; + } + + std::vector children = group->Group.getValues(); + + for (App::DocumentObject* child : children) { + if (!child || !child->isAttachedToDocument() || child->isRemoving()) { + continue; } - - std::vector children = group->Group.getValues(); - - for (App::DocumentObject* child : children) { - if (!child || !child->isAttachedToDocument() || child->isRemoving()) { - continue; - } - - // if the child is a group, recursively delete its contents first - if (child->hasExtension(App::GroupExtension::getExtensionClassTypeId())) { - auto* childGroup = child->getExtensionByType(); - deleteGroupContentsRecursively(childGroup); - } - - Gui::Document* guiDoc = Application::Instance->getDocument(child->getDocument()); - if (guiDoc) { - ViewProvider* vp = guiDoc->getViewProvider(child); - if (vp) { - // give group_recursive_deletion marker to the VP to mark that the deletion - // is supposed to delete all of its children - std::vector groupDeletionMarker = {"group_recursive_deletion"}; - bool shouldDelete = vp->onDelete(groupDeletionMarker); - - if (!shouldDelete) { - return; - } + + // if the child is a group, recursively delete its contents first + if (child->hasExtension(App::GroupExtension::getExtensionClassTypeId())) { + auto* childGroup = child->getExtensionByType(); + deleteGroupContentsRecursively(childGroup); + } + + Gui::Document* guiDoc = Application::Instance->getDocument(child->getDocument()); + if (guiDoc) { + ViewProvider* vp = guiDoc->getViewProvider(child); + if (vp) { + // give group_recursive_deletion marker to the VP to mark that the deletion + // is supposed to delete all of its children + std::vector groupDeletionMarker = {"group_recursive_deletion"}; + bool shouldDelete = vp->onDelete(groupDeletionMarker); + + if (!shouldDelete) { + return; } } - - // if the object still exists and wasn't deleted by its view provider, delete it directly - if (child->isAttachedToDocument() && !child->isRemoving()) { - child->getDocument()->removeObject(child->getNameInDocument()); - } + } + + // if the object still exists and wasn't deleted by its view provider, delete it directly + if (child->isAttachedToDocument() && !child->isRemoving()) { + child->getDocument()->removeObject(child->getNameInDocument()); } } } +} // namespace EXTENSION_PROPERTY_SOURCE(Gui::ViewProviderGroupExtension, Gui::ViewProviderExtension) @@ -94,25 +95,34 @@ ViewProviderGroupExtension::ViewProviderGroupExtension() ViewProviderGroupExtension::~ViewProviderGroupExtension() = default; -bool ViewProviderGroupExtension::extensionCanDragObjects() const { +bool ViewProviderGroupExtension::extensionCanDragObjects() const +{ return true; } -bool ViewProviderGroupExtension::extensionCanDragObject(App::DocumentObject*) const { +bool ViewProviderGroupExtension::extensionCanDragObject(App::DocumentObject*) const +{ - //we can drag anything out + // we can drag anything out return true; } -void ViewProviderGroupExtension::extensionDragObject(App::DocumentObject* obj) { +void ViewProviderGroupExtension::extensionDragObject(App::DocumentObject* obj) +{ - Gui::Command::doCommand(Gui::Command::Doc,"App.getDocument(\"%s\").getObject(\"%s\").removeObject(" - "App.getDocument(\"%s\").getObject(\"%s\"))", - getExtendedViewProvider()->getObject()->getDocument()->getName(), getExtendedViewProvider()->getObject()->getNameInDocument(), - obj->getDocument()->getName(), obj->getNameInDocument() ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument(\"%s\").getObject(\"%s\").removeObject(" + "App.getDocument(\"%s\").getObject(\"%s\"))", + getExtendedViewProvider()->getObject()->getDocument()->getName(), + getExtendedViewProvider()->getObject()->getNameInDocument(), + obj->getDocument()->getName(), + obj->getNameInDocument() + ); } -bool ViewProviderGroupExtension::extensionCanDropObjects() const { +bool ViewProviderGroupExtension::extensionCanDropObjects() const +{ return true; } @@ -125,7 +135,7 @@ bool ViewProviderGroupExtension::extensionCanDropObject(App::DocumentObject* obj auto extobj = getExtendedViewProvider()->getObject(); auto group = extobj->getExtensionByType(); - //we cannot drop thing of this group into it again if it does not allow reorder + // we cannot drop thing of this group into it again if it does not allow reorder if (group->hasObject(obj) && !getExtendedViewProvider()->acceptReorderingObjects()) { return false; } @@ -140,23 +150,29 @@ bool ViewProviderGroupExtension::extensionCanDropObject(App::DocumentObject* obj return group->allowObject(obj); } -void ViewProviderGroupExtension::extensionDropObject(App::DocumentObject* obj) { +void ViewProviderGroupExtension::extensionDropObject(App::DocumentObject* obj) +{ auto grp = getExtendedViewProvider()->getObject(); App::Document* doc = grp->getDocument(); // build Python command for execution QString cmd; - cmd = QStringLiteral("App.getDocument(\"%1\").getObject(\"%2\").addObject(" - "App.getDocument(\"%1\").getObject(\"%3\"))") - .arg(QString::fromUtf8(doc->getName()), - QString::fromUtf8(grp->getNameInDocument()), - QString::fromUtf8(obj->getNameInDocument())); + cmd = QStringLiteral( + "App.getDocument(\"%1\").getObject(\"%2\").addObject(" + "App.getDocument(\"%1\").getObject(\"%3\"))" + ) + .arg( + QString::fromUtf8(doc->getName()), + QString::fromUtf8(grp->getNameInDocument()), + QString::fromUtf8(obj->getNameInDocument()) + ); Gui::Command::doCommand(Gui::Command::App, cmd.toUtf8()); } -std::vector< App::DocumentObject* > ViewProviderGroupExtension::extensionClaimChildren() const { +std::vector ViewProviderGroupExtension::extensionClaimChildren() const +{ auto* obj = getExtendedViewProvider()->getObject(); if (!obj) { @@ -167,11 +183,13 @@ std::vector< App::DocumentObject* > ViewProviderGroupExtension::extensionClaimCh return group->Group.getValues(); } -void ViewProviderGroupExtension::extensionShow() { +void ViewProviderGroupExtension::extensionShow() +{ // avoid possible infinite recursion - if (guard) + if (guard) { return; + } Base::StateLocker lock(guard); // when reading the Visibility property from file then do not hide the @@ -180,22 +198,25 @@ void ViewProviderGroupExtension::extensionShow() { // Property::User1 is used by ViewProviderDocumentObject to mark for // temporary visibility changes. Do not propagate the change to children. if (!getExtendedViewProvider()->isRestoring() - && !getExtendedViewProvider()->Visibility.testStatus(App::Property::User1)) { + && !getExtendedViewProvider()->Visibility.testStatus(App::Property::User1)) { auto* group = getExtendedViewProvider()->getObject()->getExtensionByType(); - for(auto obj : group->Group.getValues()) { - if(obj && !obj->Visibility.getValue()) + for (auto obj : group->Group.getValues()) { + if (obj && !obj->Visibility.getValue()) { obj->Visibility.setValue(true); + } } } ViewProviderExtension::extensionShow(); } -void ViewProviderGroupExtension::extensionHide() { +void ViewProviderGroupExtension::extensionHide() +{ // avoid possible infinite recursion - if (guard) + if (guard) { return; + } Base::StateLocker lock(guard); // when reading the Visibility property from file then do not hide the @@ -204,45 +225,52 @@ void ViewProviderGroupExtension::extensionHide() { // Property::User1 is used by ViewProviderDocumentObject to mark for // temporary visibility changes. Do not propagate the change to children. if (!getExtendedViewProvider()->isRestoring() - && !getExtendedViewProvider()->Visibility.testStatus(App::Property::User1)) - { + && !getExtendedViewProvider()->Visibility.testStatus(App::Property::User1)) { auto* group = getExtendedViewProvider()->getObject()->getExtensionByType(); - for(auto obj : group->Group.getValues()) { - if(obj && obj->Visibility.getValue()) + for (auto obj : group->Group.getValues()) { + if (obj && obj->Visibility.getValue()) { obj->Visibility.setValue(false); + } } } ViewProviderExtension::extensionHide(); } -bool ViewProviderGroupExtension::extensionOnDelete(const std::vector< std::string >&) { +bool ViewProviderGroupExtension::extensionOnDelete(const std::vector&) +{ auto* group = getExtendedViewProvider()->getObject()->getExtensionByType(); - + std::vector directChildren = group->Group.getValues(); - + // just delete without messagebox if group is empty if (directChildren.empty()) { return true; } - - const auto* docGroup = - freecad_cast(getExtendedViewProvider()->getObject()); + + const auto* docGroup = freecad_cast( + getExtendedViewProvider()->getObject() + ); auto allDescendants = docGroup ? docGroup->getAllChildren() : directChildren; - + QString message; if (allDescendants.size() == directChildren.size()) { - message = QObject::tr("The group '%1' contains %2 object(s). Do you want to delete them as well?") - .arg(QString::fromUtf8(getExtendedViewProvider()->getObject()->Label.getValue())) - .arg(allDescendants.size()); - } else { + message + = QObject::tr("The group '%1' contains %2 object(s). Do you want to delete them as well?") + .arg(QString::fromUtf8(getExtendedViewProvider()->getObject()->Label.getValue())) + .arg(allDescendants.size()); + } + else { // if we have nested groups - message = QObject::tr("The group '%1' contains %2 direct children and %3 total descendants (including nested groups). Do you want to delete all of them recursively?") + message = QObject::tr( + "The group '%1' contains %2 direct children and %3 total descendants " + "(including nested groups). Do you want to delete all of them recursively?" + ) .arg(QString::fromUtf8(getExtendedViewProvider()->getObject()->Label.getValue())) .arg(directChildren.size()) .arg(allDescendants.size()); } - + QMessageBox::StandardButton choice = QMessageBox::question( getMainWindow(), QObject::tr("Delete group contents recursively?"), @@ -250,25 +278,26 @@ bool ViewProviderGroupExtension::extensionOnDelete(const std::vector< std::strin QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::No ); - + if (choice == QMessageBox::Cancel) { // don't delete anything if user has cancelled return false; } - + if (choice == QMessageBox::Yes) { // delete all of the children recursively and call their viewprovider method deleteGroupContentsRecursively(group); } // if user has specified "No" then delete the group but move children to the parent or root - + return true; } -namespace Gui { +namespace Gui +{ EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderGroupExtensionPython, Gui::ViewProviderGroupExtension) // explicit template instantiation template class GuiExport ViewProviderExtensionPythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderGroupExtension.h b/src/Gui/ViewProviderGroupExtension.h index 882d96c0f4..1da81d2be3 100644 --- a/src/Gui/ViewProviderGroupExtension.h +++ b/src/Gui/ViewProviderGroupExtension.h @@ -29,7 +29,7 @@ namespace Gui { -class GuiExport ViewProviderGroupExtension : public ViewProviderExtension +class GuiExport ViewProviderGroupExtension: public ViewProviderExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderGroupExtension); @@ -38,7 +38,7 @@ public: ViewProviderGroupExtension(); ~ViewProviderGroupExtension() override; - std::vector extensionClaimChildren()const override; + std::vector extensionClaimChildren() const override; bool extensionCanDragObjects() const override; bool extensionCanDragObject(App::DocumentObject*) const override; void extensionDragObject(App::DocumentObject*) override; @@ -49,15 +49,15 @@ public: void extensionHide() override; void extensionShow() override; - bool extensionOnDelete(const std::vector &) override; + bool extensionOnDelete(const std::vector&) override; private: - bool guard{false}; + bool guard {false}; std::vector nodes; }; using ViewProviderGroupExtensionPython = ViewProviderExtensionPythonT; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDERGROUPEXTENSION_H +#endif // GUI_VIEWPROVIDERGROUPEXTENSION_H diff --git a/src/Gui/ViewProviderImagePlane.cpp b/src/Gui/ViewProviderImagePlane.cpp index b3374bbe9b..5f55c497ee 100644 --- a/src/Gui/ViewProviderImagePlane.cpp +++ b/src/Gui/ViewProviderImagePlane.cpp @@ -21,21 +21,21 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -52,11 +52,11 @@ using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderImagePlane, Gui::ViewProviderGeometryObject) -const char* ViewProviderImagePlane::LightingEnums[]= {"One side", "Two side", nullptr}; +const char* ViewProviderImagePlane::LightingEnums[] = {"One side", "Two side", nullptr}; ViewProviderImagePlane::ViewProviderImagePlane() { - ADD_PROPERTY_TYPE(Lighting,(1L), "Object Style", App::Prop_None, "Set object lighting."); + ADD_PROPERTY_TYPE(Lighting, (1L), "Object Style", App::Prop_None, "Set object lighting."); Lighting.setEnums(LightingEnums); texture = new SoTexture2; @@ -82,7 +82,7 @@ ViewProviderImagePlane::~ViewProviderImagePlane() shapeHints->unref(); } -void ViewProviderImagePlane::attach(App::DocumentObject *pcObj) +void ViewProviderImagePlane::attach(App::DocumentObject* pcObj) { ViewProviderGeometryObject::attach(pcObj); @@ -92,11 +92,11 @@ void ViewProviderImagePlane::attach(App::DocumentObject *pcObj) SoSeparator* shading = new SoSeparator; shading->addChild(pcCoords); - SoTextureCoordinate2 *textCoord = new SoTextureCoordinate2; - textCoord->point.set1Value(0,0,0); - textCoord->point.set1Value(1,1,0); - textCoord->point.set1Value(2,1,1); - textCoord->point.set1Value(3,0,1); + SoTextureCoordinate2* textCoord = new SoTextureCoordinate2; + textCoord->point.set1Value(0, 0, 0); + textCoord->point.set1Value(1, 1, 0); + textCoord->point.set1Value(2, 1, 1); + textCoord->point.set1Value(3, 0, 1); shading->addChild(textCoord); // texture @@ -107,12 +107,12 @@ void ViewProviderImagePlane::attach(App::DocumentObject *pcObj) shading->addChild(pcShapeMaterial); // plane - pcCoords->point.set1Value(0,0,0,0); - pcCoords->point.set1Value(1,1,0,0); - pcCoords->point.set1Value(2,1,1,0); - pcCoords->point.set1Value(3,0,1,0); - SoFaceSet *faceset = new SoFaceSet; - faceset->numVertices.set1Value(0,4); + pcCoords->point.set1Value(0, 0, 0, 0); + pcCoords->point.set1Value(1, 1, 0, 0); + pcCoords->point.set1Value(2, 1, 1, 0); + pcCoords->point.set1Value(3, 0, 1, 0); + SoFaceSet* faceset = new SoFaceSet; + faceset->numVertices.set1Value(0, 4); shading->addChild(faceset); addDisplayMaskMode(shading, "Shading"); @@ -154,10 +154,12 @@ std::vector ViewProviderImagePlane::getDisplayModes() const void ViewProviderImagePlane::onChanged(const App::Property* prop) { if (prop == &Lighting) { - if (Lighting.getValue() == 0) + if (Lighting.getValue() == 0) { shapeHints->vertexOrdering = SoShapeHints::UNKNOWN_ORDERING; - else + } + else { shapeHints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE; + } } ViewProviderGeometryObject::onChanged(prop); } @@ -167,9 +169,7 @@ void ViewProviderImagePlane::setupContextMenu(QMenu* menu, QObject* receiver, co Gui::ActionFunction* func = new Gui::ActionFunction(menu); QAction* action = menu->addAction(QObject::tr("Change Image")); action->setIcon(QIcon(QLatin1String("images:image-scaling.svg"))); - func->trigger(action, [this](){ - this->manipulateImage(); - }); + func->trigger(action, [this]() { this->manipulateImage(); }); ViewProviderGeometryObject::setupContextMenu(menu, receiver, member); } @@ -189,10 +189,10 @@ void ViewProviderImagePlane::manipulateImage() void ViewProviderImagePlane::resizePlane(float xsize, float ysize) { - pcCoords->point.set1Value(0,-(xsize/2),-(ysize/2),0.0); - pcCoords->point.set1Value(1,+(xsize/2),-(ysize/2),0.0); - pcCoords->point.set1Value(2,+(xsize/2),+(ysize/2),0.0); - pcCoords->point.set1Value(3,-(xsize/2),+(ysize/2),0.0); + pcCoords->point.set1Value(0, -(xsize / 2), -(ysize / 2), 0.0); + pcCoords->point.set1Value(1, +(xsize / 2), -(ysize / 2), 0.0); + pcCoords->point.set1Value(2, +(xsize / 2), +(ysize / 2), 0.0); + pcCoords->point.set1Value(3, -(xsize / 2), +(ysize / 2), 0.0); } void ViewProviderImagePlane::loadImage() diff --git a/src/Gui/ViewProviderImagePlane.h b/src/Gui/ViewProviderImagePlane.h index 00316bfee8..c8c2b45332 100644 --- a/src/Gui/ViewProviderImagePlane.h +++ b/src/Gui/ViewProviderImagePlane.h @@ -35,7 +35,7 @@ class QImage; namespace Gui { -class GuiExport ViewProviderImagePlane : public Gui::ViewProviderGeometryObject +class GuiExport ViewProviderImagePlane: public Gui::ViewProviderGeometryObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderImagePlane); @@ -45,7 +45,7 @@ public: App::PropertyEnumeration Lighting; - void attach(App::DocumentObject *pcObject) override; + void attach(App::DocumentObject* pcObject) override; void setDisplayMode(const char* ModeName) override; std::vector getDisplayModes() const override; void updateData(const App::Property*) override; @@ -69,13 +69,13 @@ private: void manipulateImage(); private: - SoCoordinate3 * pcCoords; - SoTexture2 * texture; - SoShapeHints * shapeHints; - static const char * LightingEnums[]; + SoCoordinate3* pcCoords; + SoTexture2* texture; + SoShapeHints* shapeHints; + static const char* LightingEnums[]; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_ViewProviderImagePlane_H +#endif // GUI_ViewProviderImagePlane_H diff --git a/src/Gui/ViewProviderInventorObject.cpp b/src/Gui/ViewProviderInventorObject.cpp index c42761632f..0ed4204786 100644 --- a/src/Gui/ViewProviderInventorObject.cpp +++ b/src/Gui/ViewProviderInventorObject.cpp @@ -21,12 +21,11 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -54,7 +53,7 @@ ViewProviderInventorObject::~ViewProviderInventorObject() pcFile->unref(); } -void ViewProviderInventorObject::attach(App::DocumentObject *pcObj) +void ViewProviderInventorObject::attach(App::DocumentObject* pcObj) { ViewProviderDocumentObject::attach(pcObj); auto pcFileBuf = new SoGroup(); @@ -67,12 +66,15 @@ void ViewProviderInventorObject::attach(App::DocumentObject *pcObj) void ViewProviderInventorObject::setDisplayMode(const char* ModeName) { - if (strcmp("File+Buffer",ModeName)==0) + if (strcmp("File+Buffer", ModeName) == 0) { setDisplayMaskMode("FileBuffer"); - else if (strcmp("Buffer",ModeName)==0) + } + else if (strcmp("Buffer", ModeName) == 0) { setDisplayMaskMode("Buffer"); - else if (strcmp("File",ModeName)==0) + } + else if (strcmp("File", ModeName) == 0) { setDisplayMaskMode("File"); + } ViewProviderDocumentObject::setDisplayMode(ModeName); } @@ -93,10 +95,11 @@ void ViewProviderInventorObject::updateData(const App::Property* prop) SoInput in; std::string buffer = ivObj->Buffer.getValue(); coinRemoveAllChildren(pcBuffer); - if (buffer.empty()) + if (buffer.empty()) { return; - in.setBuffer((void *)buffer.c_str(), buffer.size()); - SoSeparator * node = SoDB::readAll(&in); + } + in.setBuffer((void*)buffer.c_str(), buffer.size()); + SoSeparator* node = SoDB::readAll(&in); if (node) { const char* doc = this->pcObject->getDocument()->getName(); const char* obj = this->pcObject->getNameInDocument(); @@ -113,8 +116,8 @@ void ViewProviderInventorObject::updateData(const App::Property* prop) coinRemoveAllChildren(pcFile); if (!fn.isEmpty() && file.open(QFile::ReadOnly)) { QByteArray buffer = file.readAll(); - in.setBuffer((void *)buffer.constData(), buffer.length()); - SoSeparator * node = SoDB::readAll(&in); + in.setBuffer((void*)buffer.constData(), buffer.length()); + SoSeparator* node = SoDB::readAll(&in); if (node) { const char* doc = this->pcObject->getDocument()->getName(); const char* obj = this->pcObject->getNameInDocument(); @@ -123,8 +126,8 @@ void ViewProviderInventorObject::updateData(const App::Property* prop) } } } - else if (prop->isDerivedFrom() && - strcmp(prop->getName(), "Placement") == 0) { + else if (prop->isDerivedFrom() + && strcmp(prop->getName(), "Placement") == 0) { // Note: If R is the rotation, c the rotation center and t the translation // vector then Inventor applies the following transformation: R*(x-c)+c+t // In FreeCAD a placement only has a rotation and a translation part but @@ -141,15 +144,14 @@ void ViewProviderInventorObject::updateData(const App::Property* prop) auto px = (float)p.getPosition().x; auto py = (float)p.getPosition().y; auto pz = (float)p.getPosition().z; - pcTransform->rotation.setValue(q0,q1,q2,q3); - pcTransform->translation.setValue(px,py,pz); - pcTransform->center.setValue(0.0f,0.0f,0.0f); - pcTransform->scaleFactor.setValue(1.0f,1.0f,1.0f); + pcTransform->rotation.setValue(q0, q1, q2, q3); + pcTransform->translation.setValue(px, py, pz); + pcTransform->center.setValue(0.0f, 0.0f, 0.0f); + pcTransform->scaleFactor.setValue(1.0f, 1.0f, 1.0f); } } -void ViewProviderInventorObject::adjustSelectionNodes(SoNode* child, const char* docname, - const char* objname) +void ViewProviderInventorObject::adjustSelectionNodes(SoNode* child, const char* docname, const char* objname) { if (child->getTypeId().isDerivedFrom(SoFCSelection::getClassTypeId())) { static_cast(child)->documentName = docname; @@ -157,7 +159,7 @@ void ViewProviderInventorObject::adjustSelectionNodes(SoNode* child, const char* } else if (child->getTypeId().isDerivedFrom(SoGroup::getClassTypeId())) { auto group = static_cast(child); - for (int i=0; igetNumChildren(); i++) { + for (int i = 0; i < group->getNumChildren(); i++) { SoNode* subchild = group->getChild(i); adjustSelectionNodes(subchild, docname, objname); } diff --git a/src/Gui/ViewProviderInventorObject.h b/src/Gui/ViewProviderInventorObject.h index 57b7c3356d..e6f487b145 100644 --- a/src/Gui/ViewProviderInventorObject.h +++ b/src/Gui/ViewProviderInventorObject.h @@ -30,7 +30,7 @@ namespace Gui { -class GuiExport ViewProviderInventorObject : public ViewProviderDocumentObject +class GuiExport ViewProviderInventorObject: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderInventorObject); @@ -41,21 +41,24 @@ public: /// destructor. ~ViewProviderInventorObject() override; - void attach(App::DocumentObject *pcObject) override; + void attach(App::DocumentObject* pcObject) override; void setDisplayMode(const char* ModeName) override; std::vector getDisplayModes() const override; void updateData(const App::Property*) override; - bool useNewSelectionModel() const override {return true;} + bool useNewSelectionModel() const override + { + return true; + } private: void adjustSelectionNodes(SoNode* child, const char* docname, const char* objname); protected: - SoSeparator *pcBuffer; - SoSeparator *pcFile; + SoSeparator* pcBuffer; + SoSeparator* pcFile; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDER_INVENTOROBJECT_H +#endif // GUI_VIEWPROVIDER_INVENTOROBJECT_H diff --git a/src/Gui/ViewProviderLine.cpp b/src/Gui/ViewProviderLine.cpp index b63e1ef656..f5e5c2dc70 100644 --- a/src/Gui/ViewProviderLine.cpp +++ b/src/Gui/ViewProviderLine.cpp @@ -22,13 +22,12 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -63,19 +62,19 @@ ViewProviderLine::ViewProviderLine() ViewProviderLine::~ViewProviderLine() = default; -void ViewProviderLine::attach(App::DocumentObject *obj) +void ViewProviderLine::attach(App::DocumentObject* obj) { ViewProviderDatum::attach(obj); // indexes used to create the edges - static const int32_t lines[4] = { 0, 1, -1 }; + static const int32_t lines[4] = {0, 1, -1}; - SoSeparator *sep = getDatumRoot(); + SoSeparator* sep = getDatumRoot(); pCoords = new SoCoordinate3(); sep->addChild(pCoords); - auto pLines = new SoIndexedLineSet(); + auto pLines = new SoIndexedLineSet(); pLines->coordIndex.setNum(3); pLines->coordIndex.setValues(0, 3, lines); sep->addChild(pLines); diff --git a/src/Gui/ViewProviderLine.h b/src/Gui/ViewProviderLine.h index 658abc6479..ea946ce861 100644 --- a/src/Gui/ViewProviderLine.h +++ b/src/Gui/ViewProviderLine.h @@ -40,7 +40,8 @@ class SoFrameLabel; namespace Gui { -class GuiExport ViewProviderLine : public ViewProviderDatum { +class GuiExport ViewProviderLine: public ViewProviderDatum +{ PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderLine); public: @@ -61,7 +62,7 @@ protected: ParamHandlers handlers; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_ViewProviderLine_H +#endif // GUI_ViewProviderLine_H diff --git a/src/Gui/ViewProviderLink.cpp b/src/Gui/ViewProviderLink.cpp index e6d7384b1a..4d440ec18c 100644 --- a/src/Gui/ViewProviderLink.cpp +++ b/src/Gui/ViewProviderLink.cpp @@ -21,38 +21,37 @@ ****************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#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 @@ -92,29 +91,32 @@ using namespace Base; using CharRange = boost::iterator_range; //////////////////////////////////////////////////////////////////////////// -static inline bool appendPathSafe(SoPath *path, SoNode *node) { - if(path->getLength()) { - SoNode * tail = path->getTail(); - const SoChildList * children = tail->getChildren(); - if(!children || children->find((void *)node)<0) +static inline bool appendPathSafe(SoPath* path, SoNode* node) +{ + if (path->getLength()) { + SoNode* tail = path->getTail(); + const SoChildList* children = tail->getChildren(); + if (!children || children->find((void*)node) < 0) { return false; + } } path->append(node); return true; } #ifdef FC_DEBUG -#define appendPath(_path,_node) \ -do{\ - if(!appendPathSafe(_path,_node))\ - FC_ERR("LinkView: coin path error");\ -}while(0) +# define appendPath(_path, _node) \ + do { \ + if (!appendPathSafe(_path, _node)) \ + FC_ERR("LinkView: coin path error"); \ + } while (0) #else -#define appendPath(_path, _node) (_path)->append(_node) +# define appendPath(_path, _node) (_path)->append(_node) #endif //////////////////////////////////////////////////////////////////////////// -class Gui::LinkInfo { +class Gui::LinkInfo +{ public: std::atomic ref; @@ -122,7 +124,7 @@ public: using Connection = boost::signals2::scoped_connection; Connection connChangeIcon; - ViewProviderDocumentObject *pcLinked; + ViewProviderDocumentObject* pcLinked; std::unordered_set links; using Pointer = LinkInfoPtr; @@ -132,81 +134,92 @@ public: SoNodeSensor childSensor; SoNodeSensor transformSensor; - std::array,LinkView::SnapshotMax> pcSnapshots; - std::array,LinkView::SnapshotMax> pcSwitches; + std::array, LinkView::SnapshotMax> pcSnapshots; + std::array, LinkView::SnapshotMax> pcSwitches; CoinPtr pcLinkedSwitch; // for group type view providers CoinPtr pcChildGroup; - using NodeMap = std::unordered_map; + using NodeMap = std::unordered_map; NodeMap nodeMap; std::map iconMap; - static ViewProviderDocumentObject *getView(App::DocumentObject *obj) { - if(obj && obj->isAttachedToDocument()) { - Document *pDoc = Application::Instance->getDocument(obj->getDocument()); - if(pDoc) { - ViewProvider *vp = pDoc->getViewProvider(obj); - if(vp && vp->isDerivedFrom()) + static ViewProviderDocumentObject* getView(App::DocumentObject* obj) + { + if (obj && obj->isAttachedToDocument()) { + Document* pDoc = Application::Instance->getDocument(obj->getDocument()); + if (pDoc) { + ViewProvider* vp = pDoc->getViewProvider(obj); + if (vp && vp->isDerivedFrom()) { return static_cast(vp); + } } } return nullptr; } - static Pointer get(App::DocumentObject *obj, Gui::LinkOwner *owner) { - return get(getView(obj),owner); + static Pointer get(App::DocumentObject* obj, Gui::LinkOwner* owner) + { + return get(getView(obj), owner); } - static Pointer get(ViewProviderDocumentObject *vp, LinkOwner *owner) { - if(!vp) + static Pointer get(ViewProviderDocumentObject* vp, LinkOwner* owner) + { + if (!vp) { return Pointer(); + } auto ext = vp->getExtensionByType(true); - if(!ext) { + if (!ext) { ext = new ViewProviderLinkObserver(); ext->initExtension(vp); } - if(!ext->linkInfo) { + if (!ext->linkInfo) { // extension can be created automatically when restored from document, // with an empty linkInfo. So we need to check here. ext->linkInfo = Pointer(new LinkInfo(vp)); ext->linkInfo->update(); } - if(owner) + if (owner) { ext->linkInfo->links.insert(owner); + } return ext->linkInfo; } - static void sensorCB(void *data, SoSensor *) { + static void sensorCB(void* data, SoSensor*) + { static_cast(data)->update(); } - static void switchSensorCB(void *data, SoSensor *) { + static void switchSensorCB(void* data, SoSensor*) + { static_cast(data)->updateSwitch(); } - static void childSensorCB(void *data, SoSensor *) { + static void childSensorCB(void* data, SoSensor*) + { static_cast(data)->updateChildren(); } - static void transformSensorCB(void *data, SoSensor *) { + static void transformSensorCB(void* data, SoSensor*) + { auto self = static_cast(data); - for(size_t i=0;ipcSnapshots.size();++i) { - if(self->pcSnapshots[i] && i!=LinkView::SnapshotTransform) - self->getSnapshot(i,true); + for (size_t i = 0; i < self->pcSnapshots.size(); ++i) { + if (self->pcSnapshots[i] && i != LinkView::SnapshotTransform) { + self->getSnapshot(i, true); + } } } - explicit LinkInfo(ViewProviderDocumentObject *vp) - :ref(0),pcLinked(vp) + explicit LinkInfo(ViewProviderDocumentObject* vp) + : ref(0) + , pcLinked(vp) { FC_LOG("new link to " << pcLinked->getObject()->getFullName()); - //NOLINTBEGIN - connChangeIcon = vp->signalChangeIcon.connect( - std::bind(&LinkInfo::slotChangeIcon,this)); - //NOLINTEND + // NOLINTBEGIN + connChangeIcon = vp->signalChangeIcon.connect(std::bind(&LinkInfo::slotChangeIcon, this)); + // NOLINTEND vp->forceUpdate(true); sensor.setFunction(sensorCB); sensor.setData(this); @@ -220,42 +233,50 @@ public: ~LinkInfo() = default; - bool checkName(const char *name) const { - return isLinked() && strcmp(name,getLinkedName())==0; + bool checkName(const char* name) const + { + return isLinked() && strcmp(name, getLinkedName()) == 0; } - void remove(LinkOwner *owner) { + void remove(LinkOwner* owner) + { links.erase(owner); } - bool isLinked() const { - return pcLinked && pcLinked->getObject() && - pcLinked->getObject()->isAttachedToDocument(); + bool isLinked() const + { + return pcLinked && pcLinked->getObject() && pcLinked->getObject()->isAttachedToDocument(); } - const char *getLinkedName() const { + const char* getLinkedName() const + { return pcLinked->getObject()->getDagKey(); } - const char *getLinkedLabel() const { + const char* getLinkedLabel() const + { return pcLinked->getObject()->Label.getValue(); } - const char *getLinkedNameSafe() const { - if(isLinked()) + const char* getLinkedNameSafe() const + { + if (isLinked()) { return getLinkedName(); + } return ""; } - const char *getDocName() const { + const char* getDocName() const + { return pcLinked->getDocument()->getDocument()->getName(); } - void detach(bool unlink) { + void detach(bool unlink) + { FC_LOG("link detach " << getLinkedNameSafe()); auto me = LinkInfoPtr(this); - if(unlink) { - while(!links.empty()) { + if (unlink) { + while (!links.empty()) { auto link = *links.begin(); links.erase(links.begin()); link->unlink(me); @@ -265,16 +286,18 @@ public: switchSensor.detach(); childSensor.detach(); transformSensor.detach(); - for(const auto &node : pcSnapshots) { - if(node) + for (const auto& node : pcSnapshots) { + if (node) { coinRemoveAllChildren(node); + } } - for(const auto &node : pcSwitches) { - if(node) + for (const auto& node : pcSwitches) { + if (node) { coinRemoveAllChildren(node); + } } pcLinkedSwitch.reset(); - if(pcChildGroup) { + if (pcChildGroup) { coinRemoveAllChildren(pcChildGroup); pcChildGroup.reset(); } @@ -282,37 +305,46 @@ public: connChangeIcon.disconnect(); } - void updateSwitch(SoSwitch *node=nullptr) { - if(!isLinked() || !pcLinkedSwitch) + void updateSwitch(SoSwitch* node = nullptr) + { + if (!isLinked() || !pcLinkedSwitch) { return; + } int index = pcLinkedSwitch->whichChild.getValue(); - for(size_t i=0;igetNumChildren(); - if((index<0 && i==LinkView::SnapshotChild) || !count) + if ((index < 0 && i == LinkView::SnapshotChild) || !count) { pcSwitches[i]->whichChild = SO_SWITCH_NONE; - else if(count>pcLinked->getDefaultMode()) + } + else if (count > pcLinked->getDefaultMode()) { pcSwitches[i]->whichChild = pcLinked->getDefaultMode(); - else + } + else { pcSwitches[i]->whichChild = 0; + } } } - inline void addref() { + inline void addref() + { ++ref; } - inline void release(){ + inline void release() + { int r = --ref; - assert(r>=0); - if(r==0) + assert(r >= 0); + if (r == 0) { delete this; - else if(r==1) { - if(pcLinked) { + } + else if (r == 1) { + if (pcLinked) { FC_LOG("link release " << getLinkedNameSafe()); auto ext = pcLinked->getExtensionByType(true); - if(ext && ext->linkInfo == this) { + if (ext && ext->linkInfo == this) { pcLinked->forceUpdate(false); detach(true); ext->linkInfo.reset(); @@ -324,68 +356,89 @@ public: // MSVC has trouble with template argument dependent lookup in // namespace. Have to put the below functions in global namespace. #if defined(_MSC_VER) - friend void Gui::intrusive_ptr_add_ref(LinkInfo *px); - friend void Gui::intrusive_ptr_release(LinkInfo *px); + friend void Gui::intrusive_ptr_add_ref(LinkInfo* px); + friend void Gui::intrusive_ptr_release(LinkInfo* px); #else - friend inline void intrusive_ptr_add_ref(LinkInfo *px) { px->addref(); } - friend inline void intrusive_ptr_release(LinkInfo *px) { px->release(); } + friend inline void intrusive_ptr_add_ref(LinkInfo* px) + { + px->addref(); + } + friend inline void intrusive_ptr_release(LinkInfo* px) + { + px->release(); + } #endif - bool isVisible() const { - if(!isLinked()) + bool isVisible() const + { + if (!isLinked()) { return true; + } int indices[] = {LinkView::SnapshotTransform, LinkView::SnapshotVisible}; - for(int idx : indices) { - if(!pcSwitches[idx]) + for (int idx : indices) { + if (!pcSwitches[idx]) { continue; - if(pcSwitches[idx]->whichChild.getValue()==SO_SWITCH_NONE) + } + if (pcSwitches[idx]->whichChild.getValue() == SO_SWITCH_NONE) { return false; + } } return true; } - void setVisible(bool visible) { - if(!isLinked()) + void setVisible(bool visible) + { + if (!isLinked()) { return; + } int indices[] = {LinkView::SnapshotTransform, LinkView::SnapshotVisible}; - for(int idx : indices) { - if(!pcSwitches[idx]) + for (int idx : indices) { + if (!pcSwitches[idx]) { continue; - if(!visible) + } + if (!visible) { pcSwitches[idx]->whichChild = SO_SWITCH_NONE; - else if(pcSwitches[idx]->getNumChildren()>pcLinked->getDefaultMode()) + } + else if (pcSwitches[idx]->getNumChildren() > pcLinked->getDefaultMode()) { pcSwitches[idx]->whichChild = pcLinked->getDefaultMode(); + } } } - SoSeparator *getSnapshot(int type, bool update=false) { - if(type<0 || type>=LinkView::SnapshotMax) + SoSeparator* getSnapshot(int type, bool update = false) + { + if (type < 0 || type >= LinkView::SnapshotMax) { return nullptr; + } - SoSeparator *root; - if(!isLinked() || !(root=pcLinked->getRoot())) + SoSeparator* root; + if (!isLinked() || !(root = pcLinked->getRoot())) { return nullptr; + } - if(sensor.getAttachedNode()!=root) { + if (sensor.getAttachedNode() != root) { sensor.detach(); sensor.attach(root); } - auto &pcSnapshot = pcSnapshots[type]; - auto &pcModeSwitch = pcSwitches[type]; - if(pcSnapshot) { - if(!update) + auto& pcSnapshot = pcSnapshots[type]; + auto& pcModeSwitch = pcSwitches[type]; + if (pcSnapshot) { + if (!update) { return pcSnapshot; - }else{ - if(ViewParams::instance()->getUseSelectionRoot()) + } + } + else { + if (ViewParams::instance()->getUseSelectionRoot()) { pcSnapshot = new SoFCSelectionRoot; - else + } + else { pcSnapshot = new SoSeparator; + } pcSnapshot->boundingBoxCaching = SoSeparator::OFF; pcSnapshot->renderCaching = SoSeparator::OFF; std::ostringstream ss; - ss << pcLinked->getObject()->getNameInDocument() - << "(" << type << ')'; + ss << pcLinked->getObject()->getNameInDocument() << "(" << type << ')'; pcSnapshot->setName(ss.str().c_str()); pcModeSwitch = new SoSwitch; } @@ -396,12 +449,12 @@ public: pcModeSwitch->whichChild = SO_SWITCH_NONE; coinRemoveAllChildren(pcModeSwitch); - SoSwitch *pcUpdateSwitch = pcModeSwitch; + SoSwitch* pcUpdateSwitch = pcModeSwitch; auto childRoot = pcLinked->getChildRoot(); - for(int i=0,count=root->getNumChildren();igetChild(i); + for (int i = 0, count = root->getNumChildren(); i < count; ++i) { + SoNode* node = root->getChild(i); // Exclude the linked object's pick style from the snapshot, // so that the Link's own pick style is the only one in effect. @@ -409,94 +462,113 @@ public: continue; } - if(node==pcLinked->getTransformNode()) { - if(type!=LinkView::SnapshotTransform) + if (node == pcLinked->getTransformNode()) { + if (type != LinkView::SnapshotTransform) { pcSnapshot->addChild(node); + } else { auto transform = pcLinked->getTransformNode(); - const auto &scale = transform->scaleFactor.getValue(); - if(scale[0]!=1.0 || scale[1]!=1.0 || scale[2]!=1.0) { + const auto& scale = transform->scaleFactor.getValue(); + if (scale[0] != 1.0 || scale[1] != 1.0 || scale[2] != 1.0) { auto trans = new SoTransform; pcSnapshot->addChild(trans); trans->scaleFactor.setValue(scale); trans->scaleOrientation = transform->scaleOrientation; - if(transformSensor.getAttachedNode()!=transform) { + if (transformSensor.getAttachedNode() != transform) { transformSensor.detach(); transformSensor.attach(transform); } } } continue; - } else if(node!=pcLinked->getModeSwitch()) { + } + else if (node != pcLinked->getModeSwitch()) { pcSnapshot->addChild(node); continue; } pcLinkedSwitch = static_cast(node); - if(switchSensor.getAttachedNode() != pcLinkedSwitch) { + if (switchSensor.getAttachedNode() != pcLinkedSwitch) { switchSensor.detach(); switchSensor.attach(pcLinkedSwitch); pcUpdateSwitch = nullptr; } pcSnapshot->addChild(pcModeSwitch); - for(int i=0,count=pcLinkedSwitch->getNumChildren();igetNumChildren(); i < count; ++i) { auto child = pcLinkedSwitch->getChild(i); - if(pcChildGroup && child==childRoot) + if (pcChildGroup && child == childRoot) { pcModeSwitch->addChild(pcChildGroup); - else + } + else { pcModeSwitch->addChild(child); + } } } updateSwitch(pcUpdateSwitch); return pcSnapshot; } - void updateData(const App::Property *prop) { + void updateData(const App::Property* prop) + { LinkInfoPtr me(this); - for(auto link : links) - link->onLinkedUpdateData(me,prop); + for (auto link : links) { + link->onLinkedUpdateData(me, prop); + } // update(); } - void update() { - if(!isLinked() || pcLinked->isRestoring()) + void update() + { + if (!isLinked() || pcLinked->isRestoring()) { return; + } updateChildren(); - for(size_t i=0;igetChildRoot()) { - childSensor.detach(); - if(pcChildGroup) - coinRemoveAllChildren(pcChildGroup); + void updateChildren() + { + if (!isLinked()) { return; } - if(childSensor.getAttachedNode() != pcLinked->getChildRoot()) { + if (!pcLinked->getChildRoot()) { + childSensor.detach(); + if (pcChildGroup) { + coinRemoveAllChildren(pcChildGroup); + } + return; + } + + if (childSensor.getAttachedNode() != pcLinked->getChildRoot()) { childSensor.detach(); childSensor.attach(pcLinked->getChildRoot()); } - if(!pcChildGroup) + if (!pcChildGroup) { pcChildGroup = new SoGroup; - else + } + else { coinRemoveAllChildren(pcChildGroup); + } NodeMap nodeMap; - for(auto child : pcLinked->claimChildren3D()) { - Pointer info = get(child,nullptr); - if(!info) continue; - SoNode *node = info->getSnapshot(LinkView::SnapshotChild); - if(!node) continue; + for (auto child : pcLinked->claimChildren3D()) { + Pointer info = get(child, nullptr); + if (!info) { + continue; + } + SoNode* node = info->getSnapshot(LinkView::SnapshotChild); + if (!node) { + continue; + } nodeMap[node] = info; pcChildGroup->addChild(node); } @@ -506,98 +578,112 @@ public: this->nodeMap.swap(nodeMap); } - bool getElementPicked(bool addname, int type, - const SoPickedPoint *pp, std::ostream &str) const + bool getElementPicked(bool addname, int type, const SoPickedPoint* pp, std::ostream& str) const { - if(!pp || !isLinked()) + if (!pp || !isLinked()) { return false; + } - if(addname) - str << getLinkedName() <<'.'; + if (addname) { + str << getLinkedName() << '.'; + } auto pcSwitch = pcSwitches[type]; - if(pcChildGroup && pcSwitch && pcSwitch->whichChild.getValue()>=0 && - pcSwitch->getChild(pcSwitch->whichChild.getValue())==pcChildGroup) - { - SoPath *path = pp->getPath(); + if (pcChildGroup && pcSwitch && pcSwitch->whichChild.getValue() >= 0 + && pcSwitch->getChild(pcSwitch->whichChild.getValue()) == pcChildGroup) { + SoPath* path = pp->getPath(); int index = path->findNode(pcChildGroup); - if(index<=0) + if (index <= 0) { return false; - auto it = nodeMap.find(path->getNode(index+1)); - if(it==nodeMap.end()) + } + auto it = nodeMap.find(path->getNode(index + 1)); + if (it == nodeMap.end()) { return false; - return it->second->getElementPicked(true,LinkView::SnapshotChild,pp,str); - }else{ + } + return it->second->getElementPicked(true, LinkView::SnapshotChild, pp, str); + } + else { std::string subname; - if(!pcLinked->getElementPicked(pp,subname)) + if (!pcLinked->getElementPicked(pp, subname)) { return false; - str<getDocument()->getName(),'*'); // } - CHECK_NAME(obj->getNameInDocument(),'.'); + CHECK_NAME(obj->getNameInDocument(), '.'); return subname; } - bool getDetail(bool checkname, int type, const char* subname, - SoDetail *&det, SoFullPath *path) const + bool getDetail(bool checkname, int type, const char* subname, SoDetail*& det, SoFullPath* path) const { - if(!isLinked()) + if (!isLinked()) { return false; - - if(checkname) { - subname = checkSubname(pcLinked->getObject(),subname); - if(!subname) - return false; } - if(pcSnapshots[type]->findChild(pcSwitches[type]) < 0) { - if(path) { - if(!appendPathSafe(path,pcSnapshots[type])) + if (checkname) { + subname = checkSubname(pcLinked->getObject(), subname); + if (!subname) { + return false; + } + } + + if (pcSnapshots[type]->findChild(pcSwitches[type]) < 0) { + if (path) { + if (!appendPathSafe(path, pcSnapshots[type])) { return false; + } } // this is possible in case of editing, where the switch node // of the linked view object is temparaly removed from its root return true; } int len = 0; - if(path) { + if (path) { len = path->getLength(); - if(!appendPathSafe(path,pcSnapshots[type])) + if (!appendPathSafe(path, pcSnapshots[type])) { return false; - appendPath(path,pcSwitches[type]); + } + appendPath(path, pcSwitches[type]); } - if(*subname == 0) + if (*subname == 0) { return true; + } auto pcSwitch = pcSwitches[type]; - if(!pcChildGroup || !pcSwitch || pcSwitch->whichChild.getValue()<0 || - pcSwitch->getChild(pcSwitch->whichChild.getValue())!=pcChildGroup) - { - return pcLinked->getDetailPath(subname,path,false,det); + if (!pcChildGroup || !pcSwitch || pcSwitch->whichChild.getValue() < 0 + || pcSwitch->getChild(pcSwitch->whichChild.getValue()) != pcChildGroup) { + return pcLinked->getDetailPath(subname, path, false, det); } - if(path){ - appendPath(path,pcChildGroup); - if(pcLinked->getChildRoot()) + if (path) { + appendPath(path, pcChildGroup); + if (pcLinked->getChildRoot()) { type = LinkView::SnapshotChild; - else + } + else { type = LinkView::SnapshotVisible; + } } // Special handling of nodes with childRoot, especially geo feature @@ -616,15 +702,16 @@ public: // |--Pad // |--Sketch - const char *dot = strchr(subname,'.'); - const char *nextsub = subname; - if(!dot) + const char* dot = strchr(subname, '.'); + const char* nextsub = subname; + if (!dot) { return false; + } auto geoGroup = pcLinked->getObject(); auto sobj = geoGroup; - while(true) { - std::string objname = std::string(nextsub,dot-nextsub+1); - if(!geoGroup->getSubObject(objname.c_str())) { + while (true) { + std::string objname = std::string(nextsub, dot - nextsub + 1); + if (!geoGroup->getSubObject(objname.c_str())) { // this object is not found under the geo group, abort. break; } @@ -632,52 +719,59 @@ public: subname = nextsub; auto ssobj = sobj->getSubObject(objname.c_str()); - if(!ssobj) { + if (!ssobj) { FC_ERR("invalid sub name " << nextsub << " of object " << sobj->getFullName()); return false; } sobj = ssobj; auto vp = Application::Instance->getViewProvider(sobj); - if(!vp) { + if (!vp) { FC_ERR("cannot find view provider of " << sobj->getFullName()); return false; } - if(vp->getChildRoot()) { + if (vp->getChildRoot()) { // In case the children is also a geo group, it will visually // hold all of its own children, so stop going further down. break; } // new style mapped sub-element - if(Data::isMappedElement(dot+1)) + if (Data::isMappedElement(dot + 1)) { break; - auto next = strchr(dot+1,'.'); - if(!next) { + } + auto next = strchr(dot + 1, '.'); + if (!next) { // no dot any more, the following must be a sub-element break; } - nextsub = dot+1; + nextsub = dot + 1; dot = next; } - for(const auto& v : nodeMap) { - if(v.second->getDetail(true,type,subname,det,path)) + for (const auto& v : nodeMap) { + if (v.second->getDetail(true, type, subname, det, path)) { return true; + } } - if(path) + if (path) { path->truncate(len); + } return false; } - void slotChangeIcon() { + void slotChangeIcon() + { iconMap.clear(); - if(!isLinked()) + if (!isLinked()) { return; + } LinkInfoPtr me(this); - for(auto link : links) + for (auto link : links) { link->onLinkedIconChange(me); + } } - QIcon getIcon(QPixmap px) { + QIcon getIcon(QPixmap px) + { static int iconSize = -1; if (iconSize < 0) { auto sampleIcon = QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon); @@ -685,19 +779,35 @@ public: iconSize = static_cast(sampleIcon.width() / pixelRatio); } - if(!isLinked()) + if (!isLinked()) { return QIcon(); + } - if(px.isNull()) + if (px.isNull()) { return pcLinked->getIcon(); - QIcon &iconLink = iconMap[px.cacheKey()]; - if(iconLink.isNull()) { + } + QIcon& iconLink = iconMap[px.cacheKey()]; + if (iconLink.isNull()) { QIcon icon = pcLinked->getIcon(); iconLink = QIcon(); - iconLink.addPixmap(BitmapFactory().merge(icon.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::Off), - px,BitmapFactoryInst::BottomLeft), QIcon::Normal, QIcon::Off); - iconLink.addPixmap(BitmapFactory().merge(icon.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::On ), - px,BitmapFactoryInst::BottomLeft), QIcon::Normal, QIcon::On); + iconLink.addPixmap( + BitmapFactory().merge( + icon.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::Off), + px, + BitmapFactoryInst::BottomLeft + ), + QIcon::Normal, + QIcon::Off + ); + iconLink.addPixmap( + BitmapFactory().merge( + icon.pixmap(iconSize, iconSize, QIcon::Normal, QIcon::On), + px, + BitmapFactoryInst::BottomLeft + ), + QIcon::Normal, + QIcon::On + ); } return iconLink; } @@ -706,116 +816,138 @@ public: #if defined(_MSC_VER) namespace Gui { - void intrusive_ptr_add_ref(Gui::LinkInfo* px) - { - px->addref(); - } +void intrusive_ptr_add_ref(Gui::LinkInfo* px) +{ + px->addref(); +} - void intrusive_ptr_release(Gui::LinkInfo* px) - { - px->release(); - } -} // namespace Gui +void intrusive_ptr_release(Gui::LinkInfo* px) +{ + px->release(); +} +} // namespace Gui #endif //////////////////////////////////////////////////////////////////////////////////// -EXTENSION_TYPESYSTEM_SOURCE(Gui::ViewProviderLinkObserver,Gui::ViewProviderExtension) +EXTENSION_TYPESYSTEM_SOURCE(Gui::ViewProviderLinkObserver, Gui::ViewProviderExtension) -ViewProviderLinkObserver::ViewProviderLinkObserver() { +ViewProviderLinkObserver::ViewProviderLinkObserver() +{ // TODO: any better way to get deleted automatically? m_isPythonExtension = true; initExtensionType(ViewProviderLinkObserver::getExtensionClassTypeId()); } -ViewProviderLinkObserver::~ViewProviderLinkObserver() { - if(linkInfo) { +ViewProviderLinkObserver::~ViewProviderLinkObserver() +{ + if (linkInfo) { linkInfo->detach(true); linkInfo.reset(); } } -bool ViewProviderLinkObserver::isLinkVisible() const { - if(linkInfo) +bool ViewProviderLinkObserver::isLinkVisible() const +{ + if (linkInfo) { return linkInfo->isVisible(); + } return true; } -void ViewProviderLinkObserver::setLinkVisible(bool visible) { - if(linkInfo) +void ViewProviderLinkObserver::setLinkVisible(bool visible) +{ + if (linkInfo) { linkInfo->setVisible(visible); + } } -void ViewProviderLinkObserver::extensionBeforeDelete() { - if(linkInfo) +void ViewProviderLinkObserver::extensionBeforeDelete() +{ + if (linkInfo) { linkInfo->detach(false); + } } -void ViewProviderLinkObserver::extensionReattach(App::DocumentObject *) { - if(linkInfo) { - linkInfo->pcLinked = - freecad_cast(getExtendedContainer()); +void ViewProviderLinkObserver::extensionReattach(App::DocumentObject*) +{ + if (linkInfo) { + linkInfo->pcLinked = freecad_cast(getExtendedContainer()); linkInfo->update(); } } -void ViewProviderLinkObserver::extensionOnChanged(const App::Property *prop) { +void ViewProviderLinkObserver::extensionOnChanged(const App::Property* prop) +{ (void)prop; } -void ViewProviderLinkObserver::extensionModeSwitchChange() { +void ViewProviderLinkObserver::extensionModeSwitchChange() +{ auto owner = freecad_cast(getExtendedContainer()); - if(owner && linkInfo) + if (owner && linkInfo) { linkInfo->updateSwitch(); + } } -void ViewProviderLinkObserver::extensionUpdateData(const App::Property *prop) { - if(linkInfo && linkInfo->pcLinked && linkInfo->pcLinked->getObject() && - prop != &linkInfo->pcLinked->getObject()->Visibility) +void ViewProviderLinkObserver::extensionUpdateData(const App::Property* prop) +{ + if (linkInfo && linkInfo->pcLinked && linkInfo->pcLinked->getObject() + && prop != &linkInfo->pcLinked->getObject()->Visibility) { linkInfo->updateData(prop); + } } -void ViewProviderLinkObserver::extensionFinishRestoring() { - if(linkInfo) { +void ViewProviderLinkObserver::extensionFinishRestoring() +{ + if (linkInfo) { FC_TRACE("linked finish restoing"); linkInfo->update(); } } -class LinkView::SubInfo : public LinkOwner { +class LinkView::SubInfo: public LinkOwner +{ public: LinkInfoPtr linkInfo; - LinkView &handle; + LinkView& handle; CoinPtr pcNode; CoinPtr pcTransform; std::set subElements; friend LinkView; - SubInfo(LinkView &handle):handle(handle) { + SubInfo(LinkView& handle) + : handle(handle) + { pcNode = new SoFCSelectionRoot(true); pcTransform = new SoTransform; pcNode->addChild(pcTransform); } - ~SubInfo() override { + ~SubInfo() override + { unlink(); auto root = handle.getLinkRoot(); - if(root) { + if (root) { int idx = root->findChild(pcNode); - if(idx>=0) + if (idx >= 0) { root->removeChild(idx); + } } } - void onLinkedIconChange(LinkInfoPtr) override { - if(handle.autoSubLink && handle.subInfo.size()==1) + void onLinkedIconChange(LinkInfoPtr) override + { + if (handle.autoSubLink && handle.subInfo.size() == 1) { handle.onLinkedIconChange(handle.linkInfo); + } } - void unlink(LinkInfoPtr info=LinkInfoPtr()) override { + void unlink(LinkInfoPtr info = LinkInfoPtr()) override + { (void)info; - if(linkInfo) { + if (linkInfo) { linkInfo->remove(this); linkInfo.reset(); } @@ -823,26 +955,31 @@ public: pcNode->addChild(pcTransform); } - void link(App::DocumentObject *obj) { - if(isLinked() && linkInfo->pcLinked->getObject()==obj) + void link(App::DocumentObject* obj) + { + if (isLinked() && linkInfo->pcLinked->getObject() == obj) { return; + } unlink(); - linkInfo = LinkInfo::get(obj,this); - if(linkInfo) + linkInfo = LinkInfo::get(obj, this); + if (linkInfo) { pcNode->addChild(linkInfo->getSnapshot(LinkView::SnapshotTransform)); + } } - bool isLinked() const{ + bool isLinked() const + { return linkInfo && linkInfo->isLinked(); } }; ////////////////////////////////////////////////////////////////////////////////// -class LinkView::Element : public LinkOwner { +class LinkView::Element: public LinkOwner +{ public: LinkInfoPtr linkInfo; - LinkView &handle; + LinkView& handle; CoinPtr pcSwitch; CoinPtr pcRoot; CoinPtr pcTransform; @@ -851,7 +988,9 @@ public: friend LinkView; - Element(LinkView &handle):handle(handle) { + Element(LinkView& handle) + : handle(handle) + { pcTransform = new SoTransform; pcRoot = new SoFCSelectionRoot(true); pcSwitch = new SoSwitch; @@ -859,172 +998,203 @@ public: pcSwitch->whichChild = 0; } - ~Element() override { + ~Element() override + { unlink(); auto root = handle.getLinkRoot(); - if(root) { + if (root) { int idx = root->findChild(pcRoot); - if(idx>=0) + if (idx >= 0) { root->removeChild(idx); + } } } - void unlink(LinkInfoPtr info=LinkInfoPtr()) override{ + void unlink(LinkInfoPtr info = LinkInfoPtr()) override + { (void)info; - if(linkInfo) { + if (linkInfo) { linkInfo->remove(this); linkInfo.reset(); } coinRemoveAllChildren(pcRoot); } - void link(App::DocumentObject *obj) { - if(isLinked() && linkInfo->pcLinked->getObject()==obj) + void link(App::DocumentObject* obj) + { + if (isLinked() && linkInfo->pcLinked->getObject() == obj) { return; + } unlink(); - linkInfo = LinkInfo::get(obj,this); - if(isLinked()) + linkInfo = LinkInfo::get(obj, this); + if (isLinked()) { pcRoot->addChild(linkInfo->getSnapshot(handle.childType)); + } } - bool isLinked() const{ + bool isLinked() const + { return linkInfo && linkInfo->isLinked(); } }; /////////////////////////////////////////////////////////////////////////////////// -TYPESYSTEM_SOURCE(Gui::LinkView,Base::BaseClass) +TYPESYSTEM_SOURCE(Gui::LinkView, Base::BaseClass) LinkView::LinkView() - :nodeType(SnapshotTransform) - ,childType((SnapshotType)-1),autoSubLink(true) + : nodeType(SnapshotTransform) + , childType((SnapshotType)-1) + , autoSubLink(true) { pcLinkRoot = new SoFCSelectionRoot; } -LinkView::~LinkView() { +LinkView::~LinkView() +{ unlink(linkInfo); unlink(linkOwner); } -PyObject *LinkView::getPyObject() +PyObject* LinkView::getPyObject() { - if (PythonObject.is(Py::_None())) - PythonObject = Py::Object(new LinkViewPy(this),true); + if (PythonObject.is(Py::_None())) { + PythonObject = Py::Object(new LinkViewPy(this), true); + } return Py::new_reference_to(PythonObject); } -void LinkView::setInvalid() { - if (!PythonObject.is(Py::_None())){ +void LinkView::setInvalid() +{ + if (!PythonObject.is(Py::_None())) { auto obj = static_cast(PythonObject.ptr()); obj->setInvalid(); obj->DecRef(); - }else + } + else { delete this; + } } -Base::BoundBox3d _getBoundBox(ViewProviderDocumentObject *vpd, SoNode *rootNode) { +Base::BoundBox3d _getBoundBox(ViewProviderDocumentObject* vpd, SoNode* rootNode) +{ auto doc = vpd->getDocument(); - if(!doc) - LINK_THROW(Base::RuntimeError,"no document"); + if (!doc) { + LINK_THROW(Base::RuntimeError, "no document"); + } Gui::MDIView* view = doc->getViewOfViewProvider(vpd); - if(!view) - LINK_THROW(Base::RuntimeError,"no view"); + if (!view) { + LINK_THROW(Base::RuntimeError, "no view"); + } Gui::View3DInventorViewer* viewer = static_cast(view)->getViewer(); SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion()); bboxAction.apply(rootNode); auto bbox = bboxAction.getBoundingBox(); - float minX,minY,minZ,maxX,maxY,maxZ; - bbox.getMax().getValue(maxX,maxY,maxZ); - bbox.getMin().getValue(minX,minY,minZ); - return Base::BoundBox3d(minX,minY,minZ,maxX,maxY,maxZ); + float minX, minY, minZ, maxX, maxY, maxZ; + bbox.getMax().getValue(maxX, maxY, maxZ); + bbox.getMin().getValue(minX, minY, minZ); + return Base::BoundBox3d(minX, minY, minZ, maxX, maxY, maxZ); } -Base::BoundBox3d LinkView::getBoundBox(ViewProviderDocumentObject *vpd) const { - if(!vpd) { - if(!linkOwner || !linkOwner->isLinked()) - LINK_THROW(Base::ValueError,"no ViewProvider"); +Base::BoundBox3d LinkView::getBoundBox(ViewProviderDocumentObject* vpd) const +{ + if (!vpd) { + if (!linkOwner || !linkOwner->isLinked()) { + LINK_THROW(Base::ValueError, "no ViewProvider"); + } vpd = linkOwner->pcLinked; } - return _getBoundBox(vpd,pcLinkRoot); + return _getBoundBox(vpd, pcLinkRoot); } -ViewProviderDocumentObject *LinkView::getOwner() const { - if(linkOwner && linkOwner->isLinked()) +ViewProviderDocumentObject* LinkView::getOwner() const +{ + if (linkOwner && linkOwner->isLinked()) { return linkOwner->pcLinked; + } return nullptr; } -void LinkView::setOwner(ViewProviderDocumentObject *vpd) { +void LinkView::setOwner(ViewProviderDocumentObject* vpd) +{ unlink(linkOwner); - linkOwner = LinkInfo::get(vpd,this); + linkOwner = LinkInfo::get(vpd, this); } -bool LinkView::isLinked() const{ +bool LinkView::isLinked() const +{ return linkInfo && linkInfo->isLinked(); } -void LinkView::setDrawStyle(int style, double lineWidth, double pointSize) { - if(!pcDrawStyle) { - if(!style) +void LinkView::setDrawStyle(int style, double lineWidth, double pointSize) +{ + if (!pcDrawStyle) { + if (!style) { return; + } pcDrawStyle = new SoDrawStyle; pcDrawStyle->style = SoDrawStyle::FILLED; - pcLinkRoot->insertChild(pcDrawStyle,0); + pcLinkRoot->insertChild(pcDrawStyle, 0); } - if(!style) { + if (!style) { pcDrawStyle->setOverride(false); return; } pcDrawStyle->lineWidth = lineWidth; pcDrawStyle->pointSize = pointSize; - switch(style) { - case 2: - pcDrawStyle->linePattern = 0xf00f; - break; - case 3: - pcDrawStyle->linePattern = 0x0f0f; - break; - case 4: - pcDrawStyle->linePattern = 0xff88; - break; - default: - pcDrawStyle->linePattern = 0xffff; + switch (style) { + case 2: + pcDrawStyle->linePattern = 0xf00f; + break; + case 3: + pcDrawStyle->linePattern = 0x0f0f; + break; + case 4: + pcDrawStyle->linePattern = 0xff88; + break; + default: + pcDrawStyle->linePattern = 0xffff; } pcDrawStyle->setOverride(true); } -void LinkView::renderDoubleSide(bool enable) { - if(enable) { - if(!pcShapeHints) { +void LinkView::renderDoubleSide(bool enable) +{ + if (enable) { + if (!pcShapeHints) { pcShapeHints = new SoShapeHints; pcShapeHints->vertexOrdering = SoShapeHints::CLOCKWISE; pcShapeHints->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE; - pcLinkRoot->insertChild(pcShapeHints,0); + pcLinkRoot->insertChild(pcShapeHints, 0); } pcShapeHints->setOverride(true); - }else if(pcShapeHints) + } + else if (pcShapeHints) { pcShapeHints->setOverride(false); + } } -void LinkView::setMaterial(int index, const App::Material *material) { - if(index < 0) { - if(!material) { +void LinkView::setMaterial(int index, const App::Material* material) +{ + if (index < 0) { + if (!material) { pcLinkRoot->removeColorOverride(); return; } Base::Color c = material->diffuseColor; c.setTransparency(material->transparency); pcLinkRoot->setColorOverride(c); - for(int i=0;i= (int)nodeArray.size()) - LINK_THROW(Base::ValueError,"LinkView: material index out of range"); + for (int i = 0; i < getSize(); ++i) { + setMaterial(i, nullptr); + } + } + else if (index >= (int)nodeArray.size()) { + LINK_THROW(Base::ValueError, "LinkView: material index out of range"); + } else { - auto &info = *nodeArray[index]; - if(!material) { + auto& info = *nodeArray[index]; + if (!material) { info.pcRoot->removeColorOverride(); return; } @@ -1034,146 +1204,185 @@ void LinkView::setMaterial(int index, const App::Material *material) { } } -void LinkView::setLink(App::DocumentObject *obj, const std::vector &subs) { - setLinkViewObject(freecad_cast( - Application::Instance->getViewProvider(obj)),subs); - +void LinkView::setLink(App::DocumentObject* obj, const std::vector& subs) +{ + setLinkViewObject( + freecad_cast(Application::Instance->getViewProvider(obj)), + subs + ); } -void LinkView::setLinkViewObject(ViewProviderDocumentObject *vpd, - const std::vector &subs) +void LinkView::setLinkViewObject(ViewProviderDocumentObject* vpd, const std::vector& subs) { - if(!isLinked() || linkInfo->pcLinked != vpd) { + if (!isLinked() || linkInfo->pcLinked != vpd) { unlink(linkInfo); - linkInfo = LinkInfo::get(vpd,this); - if(!linkInfo) + linkInfo = LinkInfo::get(vpd, this); + if (!linkInfo) { return; + } } subInfo.clear(); - for(const auto &sub : subs) { - if(sub.empty()) continue; - const char *subelement = Data::findElementName(sub.c_str()); - std::string subname = sub.substr(0,subelement-sub.c_str()); + for (const auto& sub : subs) { + if (sub.empty()) { + continue; + } + const char* subelement = Data::findElementName(sub.c_str()); + std::string subname = sub.substr(0, subelement - sub.c_str()); auto it = subInfo.find(subname); - if(it == subInfo.end()) { - it = subInfo.insert(std::make_pair(subname,std::unique_ptr())).first; + if (it == subInfo.end()) { + it = subInfo.insert(std::make_pair(subname, std::unique_ptr())).first; it->second = std::make_unique(*this); } - if(subelement[0]) + if (subelement[0]) { it->second->subElements.insert(subelement); + } } updateLink(); } -void LinkView::setTransform(SoTransform *pcTransform, const Base::Matrix4D &mat) { +void LinkView::setTransform(SoTransform* pcTransform, const Base::Matrix4D& mat) +{ double dMtrx[16]; mat.getGLMatrix(dMtrx); - pcTransform->setMatrix(SbMatrix(dMtrx[0], dMtrx[1], dMtrx[2], dMtrx[3], - dMtrx[4], dMtrx[5], dMtrx[6], dMtrx[7], - dMtrx[8], dMtrx[9], dMtrx[10], dMtrx[11], - dMtrx[12],dMtrx[13],dMtrx[14], dMtrx[15])); + pcTransform->setMatrix(SbMatrix( + dMtrx[0], + dMtrx[1], + dMtrx[2], + dMtrx[3], + dMtrx[4], + dMtrx[5], + dMtrx[6], + dMtrx[7], + dMtrx[8], + dMtrx[9], + dMtrx[10], + dMtrx[11], + dMtrx[12], + dMtrx[13], + dMtrx[14], + dMtrx[15] + )); } -void LinkView::setSize(int _size) { - size_t size = _size<0?0:(size_t)_size; - if(childType<0 && size==nodeArray.size()) +void LinkView::setSize(int _size) +{ + size_t size = _size < 0 ? 0 : (size_t)_size; + if (childType < 0 && size == nodeArray.size()) { return; + } resetRoot(); - if(!size || childType>=0) { + if (!size || childType >= 0) { nodeArray.clear(); nodeMap.clear(); - if(!size && childType<0) { - if(pcLinkedRoot) + if (!size && childType < 0) { + if (pcLinkedRoot) { pcLinkRoot->addChild(pcLinkedRoot); + } return; } childType = SnapshotContainer; } - if(sizepcSwitch); + } nodeArray.resize(size); } - for(const auto &info : nodeArray) + for (const auto& info : nodeArray) { pcLinkRoot->addChild(info->pcSwitch); + } - while(nodeArray.size()(*this)); - auto &info = *nodeArray.back(); + auto& info = *nodeArray.back(); info.pcRoot->addChild(info.pcTransform); - if(pcLinkedRoot) + if (pcLinkedRoot) { info.pcRoot->addChild(pcLinkedRoot); + } pcLinkRoot->addChild(info.pcSwitch); - nodeMap.emplace(info.pcSwitch,(int)nodeArray.size()-1); + nodeMap.emplace(info.pcSwitch, (int)nodeArray.size() - 1); } } -void LinkView::resetRoot() { +void LinkView::resetRoot() +{ coinRemoveAllChildren(pcLinkRoot); - if(pcTransform) + if (pcTransform) { pcLinkRoot->addChild(pcTransform); - if(pcShapeHints) + } + if (pcShapeHints) { pcLinkRoot->addChild(pcShapeHints); - if(pcDrawStyle) + } + if (pcDrawStyle) { pcLinkRoot->addChild(pcDrawStyle); + } } -void LinkView::setChildren(const std::vector &children, - const boost::dynamic_bitset<> &vis, SnapshotType type) +void LinkView::setChildren( + const std::vector& children, + const boost::dynamic_bitset<>& vis, + SnapshotType type +) { - if(children.empty()) { - if(!nodeArray.empty()) { + if (children.empty()) { + if (!nodeArray.empty()) { nodeArray.clear(); nodeMap.clear(); childType = SnapshotContainer; resetRoot(); - if(pcLinkedRoot) + if (pcLinkedRoot) { pcLinkRoot->addChild(pcLinkedRoot); + } } return; } - if(type<0 || type>=SnapshotMax) - LINK_THROW(Base::ValueError,"invalid children type"); + if (type < 0 || type >= SnapshotMax) { + LINK_THROW(Base::ValueError, "invalid children type"); + } resetRoot(); - if(childType<0) + if (childType < 0) { nodeArray.clear(); + } childType = type; - if(nodeArray.size() > children.size()) + if (nodeArray.size() > children.size()) { nodeArray.resize(children.size()); - else + } + else { nodeArray.reserve(children.size()); + } std::map groups; - for(size_t i=0;i(*this)); } - auto &info = *nodeArray[i]; + auto& info = *nodeArray[i]; info.isGroup = false; info.groupIndex = -1; - info.pcSwitch->whichChild = (vis.size()<=i||vis[i])?0:SO_SWITCH_NONE; + info.pcSwitch->whichChild = (vis.size() <= i || vis[i]) ? 0 : SO_SWITCH_NONE; info.link(obj); - if(obj->hasExtension(App::GroupExtension::getExtensionClassTypeId(),false)) { + if (obj->hasExtension(App::GroupExtension::getExtensionClassTypeId(), false)) { info.isGroup = true; coinRemoveAllChildren(info.pcRoot); - groups.emplace(obj,i); + groups.emplace(obj, i); } } nodeMap.clear(); - for(size_t i=0;ipcLinked->getObject())); - if(iter != groups.end()) { + for (size_t i = 0; i < nodeArray.size(); ++i) { + auto& info = *nodeArray[i]; + nodeMap.emplace(info.pcSwitch, i); + if (info.isLinked() && !groups.empty()) { + auto iter = groups.find( + App::GroupExtension::getGroupOfObject(info.linkInfo->pcLinked->getObject()) + ); + if (iter != groups.end()) { info.groupIndex = iter->second; - auto &groupInfo = *nodeArray[iter->second]; + auto& groupInfo = *nodeArray[iter->second]; groupInfo.pcRoot->addChild(info.pcSwitch); continue; } @@ -1182,140 +1391,176 @@ void LinkView::setChildren(const std::vector &children, } } -std::vector LinkView::getChildren() const { +std::vector LinkView::getChildren() const +{ std::vector ret; - for(const auto &info : nodeArray) { - if(info->isLinked()) + for (const auto& info : nodeArray) { + if (info->isLinked()) { ret.push_back(info->linkInfo->pcLinked); + } } return ret; } -void LinkView::setTransform(int index, const Base::Matrix4D &mat) { - if(index<0) { - if(!pcTransform) { +void LinkView::setTransform(int index, const Base::Matrix4D& mat) +{ + if (index < 0) { + if (!pcTransform) { pcTransform = new SoTransform; - pcLinkRoot->insertChild(pcTransform,0); + pcLinkRoot->insertChild(pcTransform, 0); } - setTransform(pcTransform,mat); + setTransform(pcTransform, mat); return; } - if(index<0 || index>=(int)nodeArray.size()) - LINK_THROW(Base::ValueError,"LinkView: index out of range"); - setTransform(nodeArray[index]->pcTransform,mat); + if (index < 0 || index >= (int)nodeArray.size()) { + LINK_THROW(Base::ValueError, "LinkView: index out of range"); + } + setTransform(nodeArray[index]->pcTransform, mat); } -void LinkView::setElementVisible(int idx, bool visible) { - if(idx>=0 && idx<(int)nodeArray.size()) - nodeArray[idx]->pcSwitch->whichChild = visible?0:SO_SWITCH_NONE; +void LinkView::setElementVisible(int idx, bool visible) +{ + if (idx >= 0 && idx < (int)nodeArray.size()) { + nodeArray[idx]->pcSwitch->whichChild = visible ? 0 : SO_SWITCH_NONE; + } } -bool LinkView::isElementVisible(int idx) const { - if(idx>=0 && idx<(int)nodeArray.size()) - return nodeArray[idx]->pcSwitch->whichChild.getValue()>=0; +bool LinkView::isElementVisible(int idx) const +{ + if (idx >= 0 && idx < (int)nodeArray.size()) { + return nodeArray[idx]->pcSwitch->whichChild.getValue() >= 0; + } return false; } -ViewProviderDocumentObject *LinkView::getLinkedView() const { +ViewProviderDocumentObject* LinkView::getLinkedView() const +{ auto link = linkInfo; - if(autoSubLink && subInfo.size()==1) + if (autoSubLink && subInfo.size() == 1) { link = subInfo.begin()->second->linkInfo; - return link?link->pcLinked:nullptr; + } + return link ? link->pcLinked : nullptr; } -std::vector LinkView::getSubNames() const { +std::vector LinkView::getSubNames() const +{ std::vector ret; - for(const auto &v : subInfo) { - if(v.second->subElements.empty()) { + for (const auto& v : subInfo) { + if (v.second->subElements.empty()) { ret.push_back(v.first); continue; } - for(const auto &s : v.second->subElements) - ret.push_back(v.first+s); + for (const auto& s : v.second->subElements) { + ret.push_back(v.first + s); + } } return ret; } -void LinkView::setNodeType(SnapshotType type, bool sublink) { +void LinkView::setNodeType(SnapshotType type, bool sublink) +{ autoSubLink = sublink; - if(nodeType==type) + if (nodeType == type) { return; - if(type>=SnapshotMax || - (type<0 && type!=SnapshotContainer && type!=SnapshotContainerTransform)) - LINK_THROW(Base::ValueError,"LinkView: invalid node type"); + } + if (type >= SnapshotMax + || (type < 0 && type != SnapshotContainer && type != SnapshotContainerTransform)) { + LINK_THROW(Base::ValueError, "LinkView: invalid node type"); + } - if(nodeType>=0 && type<0) { - if(pcLinkedRoot) { - SoSelectionElementAction action(SoSelectionElementAction::None,true); + if (nodeType >= 0 && type < 0) { + if (pcLinkedRoot) { + SoSelectionElementAction action(SoSelectionElementAction::None, true); action.apply(pcLinkedRoot); } replaceLinkedRoot(CoinPtr(new SoFCSelectionRoot)); - }else if(nodeType<0 && type>=0) { - if(isLinked()) + } + else if (nodeType < 0 && type >= 0) { + if (isLinked()) { replaceLinkedRoot(linkInfo->getSnapshot(type)); - else + } + else { replaceLinkedRoot(nullptr); + } } nodeType = type; updateLink(); } -void LinkView::replaceLinkedRoot(SoSeparator *root) { - if(root==pcLinkedRoot) +void LinkView::replaceLinkedRoot(SoSeparator* root) +{ + if (root == pcLinkedRoot) { return; - if(nodeArray.empty()) { - if(pcLinkedRoot && root) - pcLinkRoot->replaceChild(pcLinkedRoot,root); - else if(root) + } + if (nodeArray.empty()) { + if (pcLinkedRoot && root) { + pcLinkRoot->replaceChild(pcLinkedRoot, root); + } + else if (root) { pcLinkRoot->addChild(root); - else + } + else { resetRoot(); - }else if(childType<0) { - if(pcLinkedRoot && root) { - for(const auto &info : nodeArray) - info->pcRoot->replaceChild(pcLinkedRoot,root); - }else if(root) { - for(const auto &info : nodeArray) + } + } + else if (childType < 0) { + if (pcLinkedRoot && root) { + for (const auto& info : nodeArray) { + info->pcRoot->replaceChild(pcLinkedRoot, root); + } + } + else if (root) { + for (const auto& info : nodeArray) { info->pcRoot->addChild(root); - }else{ - for(const auto &info : nodeArray) + } + } + else { + for (const auto& info : nodeArray) { info->pcRoot->removeChild(pcLinkedRoot); + } } } pcLinkedRoot = root; } -void LinkView::onLinkedIconChange(LinkInfoPtr info) { - if(info==linkInfo && info!=linkOwner && linkOwner && linkOwner->isLinked()) +void LinkView::onLinkedIconChange(LinkInfoPtr info) +{ + if (info == linkInfo && info != linkOwner && linkOwner && linkOwner->isLinked()) { linkOwner->pcLinked->signalChangeIcon(); + } } -void LinkView::onLinkedUpdateData(LinkInfoPtr info, const App::Property *prop) { - if(info!=linkInfo || !linkOwner || !linkOwner->isLinked() || info==linkOwner) +void LinkView::onLinkedUpdateData(LinkInfoPtr info, const App::Property* prop) +{ + if (info != linkInfo || !linkOwner || !linkOwner->isLinked() || info == linkOwner) { return; + } auto ext = linkOwner->pcLinked->getObject()->getExtensionByType(true); - if (ext && !(prop->getType() & App::Prop_Output) && - !prop->testStatus(App::Property::Output)) - { + if (ext && !(prop->getType() & App::Prop_Output) && !prop->testStatus(App::Property::Output)) { // propagate the signalChangedObject to potentially multiple levels // of links, to inform tree view of children change, and other // parent objects about the change. But we need to be careful to not // touch the object if the property of change is marked as output. ext->_LinkTouched.touch(); - }else{ + } + else { // In case the owner object does not have link extension, here is a // trick to link the signalChangedObject from linked object to the // owner linkOwner->pcLinked->getDocument()->signalChangedObject( - *linkOwner->pcLinked,linkOwner->pcLinked->getObject()->Label); + *linkOwner->pcLinked, + linkOwner->pcLinked->getObject()->Label + ); } } -void LinkView::updateLink() { - if(!isLinked()) +void LinkView::updateLink() +{ + if (!isLinked()) { return; + } - if(linkOwner && linkOwner->isLinked() && linkOwner->pcLinked->isRestoring()) { + if (linkOwner && linkOwner->isLinked() && linkOwner->pcLinked->isRestoring()) { FC_TRACE("restoring '" << linkOwner->pcLinked->getObject()->getFullName() << "'"); return; } @@ -1323,47 +1568,49 @@ void LinkView::updateLink() { // TODO: is it a good idea to clear any selection here? pcLinkRoot->resetContext(); - if(nodeType >= 0) { + if (nodeType >= 0) { replaceLinkedRoot(linkInfo->getSnapshot(nodeType)); return; } // rebuild link sub objects tree CoinPtr linkedRoot = pcLinkedRoot; - if(!linkedRoot) + if (!linkedRoot) { linkedRoot = new SoFCSelectionRoot; - else{ - SoSelectionElementAction action(SoSelectionElementAction::None,true); + } + else { + SoSelectionElementAction action(SoSelectionElementAction::None, true); action.apply(linkedRoot); coinRemoveAllChildren(linkedRoot); } SoTempPath path(10); path.ref(); - appendPath(&path,linkedRoot); + appendPath(&path, linkedRoot); auto obj = linkInfo->pcLinked->getObject(); - for(const auto &v : subInfo) { - auto &sub = *v.second; + for (const auto& v : subInfo) { + auto& sub = *v.second; Base::Matrix4D mat; - App::DocumentObject *sobj = obj->getSubObject( - v.first.c_str(), nullptr, &mat, nodeType==SnapshotContainer); - if(!sobj) { + App::DocumentObject* sobj + = obj->getSubObject(v.first.c_str(), nullptr, &mat, nodeType == SnapshotContainer); + if (!sobj) { sub.unlink(); continue; } sub.link(sobj); linkedRoot->addChild(sub.pcNode); - setTransform(sub.pcTransform,mat); + setTransform(sub.pcTransform, mat); - if(!sub.subElements.empty()) { + if (!sub.subElements.empty()) { path.truncate(1); - appendPath(&path,sub.pcNode); - SoSelectionElementAction action(SoSelectionElementAction::Append,true); - for(const auto &subelement : sub.subElements) { + appendPath(&path, sub.pcNode); + SoSelectionElementAction action(SoSelectionElementAction::Append, true); + for (const auto& subelement : sub.subElements) { path.truncate(2); - SoDetail *det = nullptr; - if(!sub.linkInfo->getDetail(false,SnapshotTransform,subelement.c_str(),det,&path)) + SoDetail* det = nullptr; + if (!sub.linkInfo->getDetail(false, SnapshotTransform, subelement.c_str(), det, &path)) { continue; + } action.setElement(det); action.apply(&path); delete det; @@ -1374,40 +1621,40 @@ void LinkView::updateLink() { replaceLinkedRoot(linkedRoot); } -bool LinkView::linkGetElementPicked(const SoPickedPoint *pp, std::string &subname) const +bool LinkView::linkGetElementPicked(const SoPickedPoint* pp, std::string& subname) const { std::ostringstream ss; CoinPtr path = pp->getPath(); - if(!nodeArray.empty()) { + if (!nodeArray.empty()) { auto idx = path->findNode(pcLinkRoot); if (idx < 0 || idx + 2 >= path->getLength()) { return false; } - auto node = path->getNode(idx+1); + auto node = path->getNode(idx + 1); auto it = nodeMap.find(node); - if(it == nodeMap.end() || !isElementVisible(it->second)) { + if (it == nodeMap.end() || !isElementVisible(it->second)) { return false; } int nodeIdx = it->second; ++idx; - while(nodeArray[nodeIdx]->isGroup) { - auto &info = *nodeArray[nodeIdx]; - if(!info.isLinked()) { + while (nodeArray[nodeIdx]->isGroup) { + auto& info = *nodeArray[nodeIdx]; + if (!info.isLinked()) { return false; } ss << info.linkInfo->getLinkedName() << '.'; idx += 2; - if(idx>=path->getLength()) { + if (idx >= path->getLength()) { return false; } auto iter = nodeMap.find(path->getNode(idx)); - if(iter == nodeMap.end() || !isElementVisible(iter->second)) { + if (iter == nodeMap.end() || !isElementVisible(iter->second)) { return false; } nodeIdx = iter->second; } - auto &info = *nodeArray[nodeIdx]; + auto& info = *nodeArray[nodeIdx]; if (!info.linkInfo) { ss << it->second << '.'; } @@ -1415,7 +1662,7 @@ bool LinkView::linkGetElementPicked(const SoPickedPoint *pp, std::string &subnam ss << info.linkInfo->getLinkedName() << '.'; } - if(info.isLinked()) { + if (info.isLinked()) { if (!info.linkInfo->getElementPicked(false, childType, pp, ss)) { return false; } @@ -1424,38 +1671,38 @@ bool LinkView::linkGetElementPicked(const SoPickedPoint *pp, std::string &subnam } } - if(!isLinked()) { + if (!isLinked()) { return false; } - if(nodeType >= 0) { - if(linkInfo->getElementPicked(false,nodeType,pp,ss)) { + if (nodeType >= 0) { + if (linkInfo->getElementPicked(false, nodeType, pp, ss)) { subname = ss.str(); return true; } return false; } auto idx = path->findNode(pcLinkedRoot); - if(idx<0 || idx+1>=path->getLength()) { + if (idx < 0 || idx + 1 >= path->getLength()) { return false; } - auto node = path->getNode(idx+1); - for(const auto &v : subInfo) { - auto &sub = *v.second; + auto node = path->getNode(idx + 1); + for (const auto& v : subInfo) { + auto& sub = *v.second; if (node != sub.pcNode) { continue; } std::ostringstream ss2; - if(!sub.linkInfo->getElementPicked(false,SnapshotTransform,pp,ss2)) { + if (!sub.linkInfo->getElementPicked(false, SnapshotTransform, pp, ss2)) { return false; } - const std::string &element = ss2.str(); - if(!sub.subElements.empty()) { - if(sub.subElements.find(element)==sub.subElements.end()) { + const std::string& element = ss2.str(); + if (!sub.subElements.empty()) { + if (sub.subElements.find(element) == sub.subElements.end()) { auto pos = element.find('.'); - if (pos == std::string::npos || - sub.subElements.find(element.c_str() + pos + 1) == sub.subElements.end()) { + if (pos == std::string::npos + || sub.subElements.find(element.c_str() + pos + 1) == sub.subElements.end()) { return false; } } @@ -1470,48 +1717,58 @@ bool LinkView::linkGetElementPicked(const SoPickedPoint *pp, std::string &subnam return false; } -bool LinkView::getGroupHierarchy(int index, SoFullPath *path) const { - if(index > (int)nodeArray.size()) +bool LinkView::getGroupHierarchy(int index, SoFullPath* path) const +{ + if (index > (int)nodeArray.size()) { return false; - auto &info = *nodeArray[index]; - if(info.groupIndex>=0 && !getGroupHierarchy(info.groupIndex,path)) + } + auto& info = *nodeArray[index]; + if (info.groupIndex >= 0 && !getGroupHierarchy(info.groupIndex, path)) { return false; - appendPath(path,info.pcSwitch); - appendPath(path,info.pcRoot); + } + appendPath(path, info.pcSwitch); + appendPath(path, info.pcRoot); return true; } -bool LinkView::linkGetDetailPath(const char *subname, SoFullPath *path, SoDetail *&det) const +bool LinkView::linkGetDetailPath(const char* subname, SoFullPath* path, SoDetail*& det) const { - if(!subname || *subname==0) + if (!subname || *subname == 0) { return true; + } auto len = path->getLength(); - if(nodeArray.empty()) { - if(!appendPathSafe(path,pcLinkRoot)) + if (nodeArray.empty()) { + if (!appendPathSafe(path, pcLinkRoot)) { return false; - } else { + } + } + else { int idx = -1; - if (subname[0]>='0' && subname[0]<='9') { - idx = App::LinkBaseExtension::getArrayIndex(subname,&subname); - } else { - while(true) { - const char *dot = strchr(subname,'.'); - if(!dot) + if (subname[0] >= '0' && subname[0] <= '9') { + idx = App::LinkBaseExtension::getArrayIndex(subname, &subname); + } + else { + while (true) { + const char* dot = strchr(subname, '.'); + if (!dot) { break; + } int i = 0; if (subname[0] == '$') { - CharRange name(subname+1,dot); - for(const auto &info : nodeArray) { - if(info->isLinked() && boost::equals(name,info->linkInfo->getLinkedLabel())) { + CharRange name(subname + 1, dot); + for (const auto& info : nodeArray) { + if (info->isLinked() + && boost::equals(name, info->linkInfo->getLinkedLabel())) { idx = i; break; } ++i; } - } else { - CharRange name(subname,dot); - for(const auto &info : nodeArray) { - if(info->isLinked() && boost::equals(name,info->linkInfo->getLinkedName())) { + } + else { + CharRange name(subname, dot); + for (const auto& info : nodeArray) { + if (info->isLinked() && boost::equals(name, info->linkInfo->getLinkedName())) { idx = i; break; } @@ -1519,63 +1776,77 @@ bool LinkView::linkGetDetailPath(const char *subname, SoFullPath *path, SoDetail } } - if(idx<0) + if (idx < 0) { return false; + } - subname = dot+1; - if(!subname[0] || nodeArray[idx]->isGroup==0) + subname = dot + 1; + if (!subname[0] || nodeArray[idx]->isGroup == 0) { break; + } idx = -1; } } - if(idx<0 || idx>=(int)nodeArray.size()) + if (idx < 0 || idx >= (int)nodeArray.size()) { return false; - auto &info = *nodeArray[idx]; - if(!appendPathSafe(path,pcLinkRoot)) + } + auto& info = *nodeArray[idx]; + if (!appendPathSafe(path, pcLinkRoot)) { return false; - if(info.groupIndex>=0 && !getGroupHierarchy(info.groupIndex,path)) + } + if (info.groupIndex >= 0 && !getGroupHierarchy(info.groupIndex, path)) { return false; - appendPath(path,info.pcSwitch); - appendPath(path,info.pcRoot); + } + appendPath(path, info.pcSwitch); + appendPath(path, info.pcRoot); - if(*subname == 0) + if (*subname == 0) { return true; + } - if(info.isLinked()) { - if (info.linkInfo->getDetail(false,childType,subname,det,path)) { + if (info.isLinked()) { + if (info.linkInfo->getDetail(false, childType, subname, det, path)) { return true; } } } - if(isLinked()) { - if(nodeType >= 0) { - if(linkInfo->getDetail(false,nodeType,subname,det,path)) + if (isLinked()) { + if (nodeType >= 0) { + if (linkInfo->getDetail(false, nodeType, subname, det, path)) { return true; - }else { - appendPath(path,pcLinkedRoot); - for(const auto &v : subInfo) { - auto &sub = *v.second; - if(!sub.isLinked()) + } + } + else { + appendPath(path, pcLinkedRoot); + for (const auto& v : subInfo) { + auto& sub = *v.second; + if (!sub.isLinked()) { continue; - const char *nextsub; - if(autoSubLink && subInfo.size()==1) + } + const char* nextsub; + if (autoSubLink && subInfo.size() == 1) { nextsub = subname; - else{ - if(!boost::algorithm::starts_with(subname,v.first)) + } + else { + if (!boost::algorithm::starts_with(subname, v.first)) { continue; - nextsub = subname+v.first.size(); - if(*nextsub != '.') + } + nextsub = subname + v.first.size(); + if (*nextsub != '.') { continue; + } ++nextsub; } - if(*nextsub && !sub.subElements.empty() && - sub.subElements.find(nextsub)==sub.subElements.end()) + if (*nextsub && !sub.subElements.empty() + && sub.subElements.find(nextsub) == sub.subElements.end()) { break; - appendPath(path,sub.pcNode); + } + appendPath(path, sub.pcNode); len = path->getLength(); - if(sub.linkInfo->getDetail(false,SnapshotTransform,nextsub,det,path)) + if (sub.linkInfo->getDetail(false, SnapshotTransform, nextsub, det, path)) { return true; + } break; } } @@ -1584,29 +1855,33 @@ bool LinkView::linkGetDetailPath(const char *subname, SoFullPath *path, SoDetail return false; } -void LinkView::unlink(LinkInfoPtr info) { - if(!info) +void LinkView::unlink(LinkInfoPtr info) +{ + if (!info) { return; - if(info == linkOwner) { + } + if (info == linkOwner) { linkOwner->remove(this); linkOwner.reset(); } - if(info != linkInfo) + if (info != linkInfo) { return; - if(linkInfo) { + } + if (linkInfo) { linkInfo->remove(this); linkInfo.reset(); } pcLinkRoot->resetContext(); - if(pcLinkedRoot) { - if(nodeArray.empty()) + if (pcLinkedRoot) { + if (nodeArray.empty()) { resetRoot(); + } else { - for(const auto &info : nodeArray) { + for (const auto& info : nodeArray) { int idx; - if(info->isLinked() && - (idx=info->pcRoot->findChild(pcLinkedRoot))>=0) + if (info->isLinked() && (idx = info->pcRoot->findChild(pcLinkedRoot)) >= 0) { info->pcRoot->removeChild(idx); + } } } pcLinkedRoot.reset(); @@ -1615,16 +1890,20 @@ void LinkView::unlink(LinkInfoPtr info) { return; } -QIcon LinkView::getLinkedIcon(QPixmap px) const { +QIcon LinkView::getLinkedIcon(QPixmap px) const +{ auto link = linkInfo; - if(autoSubLink && subInfo.size()==1) + if (autoSubLink && subInfo.size() == 1) { link = subInfo.begin()->second->linkInfo; - if(!link || !link->isLinked()) + } + if (!link || !link->isLinked()) { return QIcon(); + } return link->getIcon(px); } -bool LinkView::hasSubs() const { +bool LinkView::hasSubs() const +{ return isLinked() && !subInfo.empty(); } @@ -1632,47 +1911,56 @@ bool LinkView::hasSubs() const { PROPERTY_SOURCE(Gui::ViewProviderLink, Gui::ViewProviderDocumentObject) -static const char *_LinkIcon = "Link"; +static const char* _LinkIcon = "Link"; // static const char *_LinkArrayIcon = "LinkArray"; -static const char *_LinkGroupIcon = "LinkGroup"; -static const char *_LinkElementIcon = "LinkElement"; +static const char* _LinkGroupIcon = "LinkGroup"; +static const char* _LinkElementIcon = "LinkElement"; ViewProviderLink::ViewProviderLink() - :linkType(LinkTypeNone),hasSubName(false),hasSubElement(false) - ,childVp(nullptr),overlayCacheKey(0) + : linkType(LinkTypeNone) + , hasSubName(false) + , hasSubElement(false) + , childVp(nullptr) + , overlayCacheKey(0) { sPixmap = _LinkIcon; ADD_PROPERTY_TYPE(Selectable, (true), " Link", App::Prop_None, 0); - ADD_PROPERTY_TYPE(OverrideMaterial, (false), " Link", App::Prop_None, "Override linked object's material"); + ADD_PROPERTY_TYPE( + OverrideMaterial, + (false), + " Link", + App::Prop_None, + "Override linked object's material" + ); App::Material mat(App::Material::DEFAULT); mat.diffuseColor.setPackedValue(ViewParams::instance()->getDefaultLinkColor()); ADD_PROPERTY_TYPE(ShapeMaterial, (mat), " Link", App::Prop_None, 0); ShapeMaterial.setStatus(App::Property::MaterialEdit, true); - ADD_PROPERTY_TYPE(DrawStyle,((long int)0), " Link", App::Prop_None, ""); - static const char* DrawStyleEnums[]= {"None","Solid","Dashed","Dotted","Dashdot",nullptr}; + ADD_PROPERTY_TYPE(DrawStyle, ((long int)0), " Link", App::Prop_None, ""); + static const char* DrawStyleEnums[] = {"None", "Solid", "Dashed", "Dotted", "Dashdot", nullptr}; DrawStyle.setEnums(DrawStyleEnums); int lwidth = ViewParams::instance()->getDefaultShapeLineWidth(); - ADD_PROPERTY_TYPE(LineWidth,(lwidth), " Link", App::Prop_None, ""); + ADD_PROPERTY_TYPE(LineWidth, (lwidth), " Link", App::Prop_None, ""); - static App::PropertyFloatConstraint::Constraints sizeRange = {1.0,64.0,1.0}; + static App::PropertyFloatConstraint::Constraints sizeRange = {1.0, 64.0, 1.0}; LineWidth.setConstraints(&sizeRange); - ADD_PROPERTY_TYPE(PointSize,(lwidth), " Link", App::Prop_None, ""); + ADD_PROPERTY_TYPE(PointSize, (lwidth), " Link", App::Prop_None, ""); PointSize.setConstraints(&sizeRange); - ADD_PROPERTY(MaterialList,()); + ADD_PROPERTY(MaterialList, ()); MaterialList.setStatus(App::Property::NoMaterialListEdit, true); - ADD_PROPERTY(OverrideMaterialList,()); - ADD_PROPERTY(OverrideColorList,()); + ADD_PROPERTY(OverrideMaterialList, ()); + ADD_PROPERTY(OverrideColorList, ()); ADD_PROPERTY(ChildViewProvider, ("")); - ChildViewProvider.setStatus(App::Property::Hidden,true); + ChildViewProvider.setStatus(App::Property::Hidden, true); DisplayMode.setStatus(App::Property::Status::Hidden, true); @@ -1688,7 +1976,8 @@ ViewProviderLink::~ViewProviderLink() linkView->setInvalid(); } -bool ViewProviderLink::isSelectable() const { +bool ViewProviderLink::isSelectable() const +{ return Selectable.getValue(); } @@ -1698,27 +1987,29 @@ void ViewProviderLink::attach(App::DocumentObject* pcObj) pcRoot->insertChild(pcPickStyle, 0); } - SoNode *node = linkView->getLinkRoot(); + SoNode* node = linkView->getLinkRoot(); node->setName(pcObj->getFullName().c_str()); - addDisplayMaskMode(node,"Link"); - if(childVp) { - childVpLink = LinkInfo::get(childVp,nullptr); + addDisplayMaskMode(node, "Link"); + if (childVp) { + childVpLink = LinkInfo::get(childVp, nullptr); node = childVpLink->getSnapshot(LinkView::SnapshotTransform); } - addDisplayMaskMode(node,"ChildView"); + addDisplayMaskMode(node, "ChildView"); setDisplayMaskMode("Link"); inherited::attach(pcObj); checkIcon(); - if(pcObj->isDerivedFrom()) + if (pcObj->isDerivedFrom()) { hide(); + } linkView->setOwner(this); - } -void ViewProviderLink::reattach(App::DocumentObject *obj) { +void ViewProviderLink::reattach(App::DocumentObject* obj) +{ linkView->setOwner(this); - if(childVp) + if (childVp) { childVp->reattach(obj); + } ViewProviderDocumentObject::reattach(obj); } @@ -1730,33 +2021,40 @@ std::vector ViewProviderLink::getDisplayModes() const return StrList; } -QIcon ViewProviderLink::getIcon() const { +QIcon ViewProviderLink::getIcon() const +{ auto ext = getLinkExtension(); - if(ext) { + if (ext) { auto link = ext->getLinkedObjectValue(); - if(link && link!=getObject()) { + if (link && link != getObject()) { QPixmap overlay = getOverlayPixmap(); overlayCacheKey = overlay.cacheKey(); QIcon icon = linkView->getLinkedIcon(overlay); - if(!icon.isNull()) + if (!icon.isNull()) { return icon; + } } } overlayCacheKey = 0; return Gui::BitmapFactory().pixmap(sPixmap); } -QPixmap ViewProviderLink::getOverlayPixmap() const { +QPixmap ViewProviderLink::getOverlayPixmap() const +{ auto ext = getLinkExtension(); constexpr int px = 12; - if(ext && ext->getLinkedObjectProperty() && ext->_getElementCountValue()) - return BitmapFactory().pixmapFromSvg("LinkArrayOverlay", QSizeF(px,px)); - else if(hasSubElement) - return BitmapFactory().pixmapFromSvg("LinkSubElement", QSizeF(px,px)); - else if(hasSubName) - return BitmapFactory().pixmapFromSvg("LinkSubOverlay", QSizeF(px,px)); - else - return BitmapFactory().pixmapFromSvg("LinkOverlay", QSizeF(px,px)); + if (ext && ext->getLinkedObjectProperty() && ext->_getElementCountValue()) { + return BitmapFactory().pixmapFromSvg("LinkArrayOverlay", QSizeF(px, px)); + } + else if (hasSubElement) { + return BitmapFactory().pixmapFromSvg("LinkSubElement", QSizeF(px, px)); + } + else if (hasSubName) { + return BitmapFactory().pixmapFromSvg("LinkSubOverlay", QSizeF(px, px)); + } + else { + return BitmapFactory().pixmapFromSvg("LinkOverlay", QSizeF(px, px)); + } } void ViewProviderLink::onChanged(const App::Property* prop) @@ -1765,287 +2063,352 @@ void ViewProviderLink::onChanged(const App::Property* prop) pcPickStyle->style = Selectable.getValue() ? SoPickStyle::SHAPE : SoPickStyle::UNPICKABLE; } - if(prop==&ChildViewProvider) { + if (prop == &ChildViewProvider) { childVp = freecad_cast(ChildViewProvider.getObject().get()); - if(childVp && getObject()) { - if(strcmp(childVp->getTypeId().getName(),getObject()->getViewProviderName())!=0 - && !childVp->allowOverride(*getObject())) - { - FC_ERR("Child view provider type '" << childVp->getTypeId().getName() - << "' does not support " << getObject()->getFullName()); - } else { + if (childVp && getObject()) { + if (strcmp(childVp->getTypeId().getName(), getObject()->getViewProviderName()) != 0 + && !childVp->allowOverride(*getObject())) { + FC_ERR( + "Child view provider type '" << childVp->getTypeId().getName() + << "' does not support " + << getObject()->getFullName() + ); + } + else { childVp->setPropertyPrefix("ChildViewProvider."); childVp->Visibility.setValue(getObject()->Visibility.getValue()); childVp->attach(getObject()); childVp->updateView(); childVp->setActiveMode(); - if(pcModeSwitch->getNumChildren()>1){ - childVpLink = LinkInfo::get(childVp,nullptr); - pcModeSwitch->replaceChild(1,childVpLink->getSnapshot(LinkView::SnapshotTransform)); + if (pcModeSwitch->getNumChildren() > 1) { + childVpLink = LinkInfo::get(childVp, nullptr); + pcModeSwitch->replaceChild(1, childVpLink->getSnapshot(LinkView::SnapshotTransform)); } } } - }else if(!isRestoring()) { - if (prop == &OverrideMaterial || prop == &ShapeMaterial || - prop == &MaterialList || prop == &OverrideMaterialList) - { + } + else if (!isRestoring()) { + if (prop == &OverrideMaterial || prop == &ShapeMaterial || prop == &MaterialList + || prop == &OverrideMaterialList) { applyMaterial(); - }else if(prop == &OverrideColorList) { + } + else if (prop == &OverrideColorList) { applyColors(); - }else if(prop==&DrawStyle || prop==&PointSize || prop==&LineWidth) { - if(!DrawStyle.getValue()) + } + else if (prop == &DrawStyle || prop == &PointSize || prop == &LineWidth) { + if (!DrawStyle.getValue()) { linkView->setDrawStyle(0); - else - linkView->setDrawStyle(DrawStyle.getValue(),LineWidth.getValue(),PointSize.getValue()); + } + else { + linkView->setDrawStyle(DrawStyle.getValue(), LineWidth.getValue(), PointSize.getValue()); + } } } inherited::onChanged(prop); } -bool ViewProviderLink::setLinkType(App::LinkBaseExtension *ext) { +bool ViewProviderLink::setLinkType(App::LinkBaseExtension* ext) +{ auto propLink = ext->getLinkedObjectProperty(); - if(!propLink) + if (!propLink) { return false; + } LinkType type; - if(hasSubName) + if (hasSubName) { type = LinkTypeSubs; - else + } + else { type = LinkTypeNormal; - if(linkType != type) + } + if (linkType != type) { linkType = type; - switch(type) { - case LinkTypeSubs: - linkView->setNodeType(ext->linkTransform()?LinkView::SnapshotContainer: - LinkView::SnapshotContainerTransform); - break; - case LinkTypeNormal: - linkView->setNodeType(ext->linkTransform()?LinkView::SnapshotVisible: - LinkView::SnapshotTransform); - break; - default: - break; + } + switch (type) { + case LinkTypeSubs: + linkView->setNodeType( + ext->linkTransform() ? LinkView::SnapshotContainer : LinkView::SnapshotContainerTransform + ); + break; + case LinkTypeNormal: + linkView->setNodeType( + ext->linkTransform() ? LinkView::SnapshotVisible : LinkView::SnapshotTransform + ); + break; + default: + break; } return true; } -App::LinkBaseExtension *ViewProviderLink::getLinkExtension() { - if(!pcObject || !pcObject->isAttachedToDocument()) +App::LinkBaseExtension* ViewProviderLink::getLinkExtension() +{ + if (!pcObject || !pcObject->isAttachedToDocument()) { return nullptr; + } return pcObject->getExtensionByType(true); } -const App::LinkBaseExtension *ViewProviderLink::getLinkExtension() const{ - if(!pcObject || !pcObject->isAttachedToDocument()) +const App::LinkBaseExtension* ViewProviderLink::getLinkExtension() const +{ + if (!pcObject || !pcObject->isAttachedToDocument()) { return nullptr; + } return const_cast(pcObject)->getExtensionByType(true); } -void ViewProviderLink::updateData(const App::Property *prop) { - if(childVp) +void ViewProviderLink::updateData(const App::Property* prop) +{ + if (childVp) { childVp->updateData(prop); - if(!isRestoring() && !pcObject->isRestoring()) { + } + if (!isRestoring() && !pcObject->isRestoring()) { auto ext = getLinkExtension(); - if(ext) updateDataPrivate(getLinkExtension(),prop); + if (ext) { + updateDataPrivate(getLinkExtension(), prop); + } } return inherited::updateData(prop); } -static inline bool canScale(const Base::Vector3d &v) { - return fabs(v.x)>1e-7 && fabs(v.y)>1e-7 && fabs(v.z)>1e-7; +static inline bool canScale(const Base::Vector3d& v) +{ + return fabs(v.x) > 1e-7 && fabs(v.y) > 1e-7 && fabs(v.z) > 1e-7; } -void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension *ext, const App::Property *prop) { - if(!prop) +void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension* ext, const App::Property* prop) +{ + if (!prop) { return; - if(prop == &ext->_ChildCache) { + } + if (prop == &ext->_ChildCache) { updateElementList(ext); - } else if(prop == &ext->_LinkTouched) { - if(linkView->hasSubs()) + } + else if (prop == &ext->_LinkTouched) { + if (linkView->hasSubs()) { linkView->updateLink(); + } applyColors(); checkIcon(ext); - }else if(prop==ext->getColoredElementsProperty()) { - if(!prop->testStatus(App::Property::User3)) + } + else if (prop == ext->getColoredElementsProperty()) { + if (!prop->testStatus(App::Property::User3)) { applyColors(); - }else if(prop==ext->getScaleProperty() || prop==ext->getScaleVectorProperty()) { - if(!prop->testStatus(App::Property::User3)) { - const auto &v = ext->getScaleVector(); - if(canScale(v)) - pcTransform->scaleFactor.setValue(v.x,v.y,v.z); + } + } + else if (prop == ext->getScaleProperty() || prop == ext->getScaleVectorProperty()) { + if (!prop->testStatus(App::Property::User3)) { + const auto& v = ext->getScaleVector(); + if (canScale(v)) { + pcTransform->scaleFactor.setValue(v.x, v.y, v.z); + } SbMatrix matrix = convert(ext->getTransform(false)); linkView->renderDoubleSide(matrix.det3() < 1e-7); } - }else if(prop == ext->getPlacementProperty() || prop == ext->getLinkPlacementProperty()) { + } + else if (prop == ext->getPlacementProperty() || prop == ext->getLinkPlacementProperty()) { auto propLinkPlacement = ext->getLinkPlacementProperty(); - if(!propLinkPlacement || propLinkPlacement == prop) { - const auto &v = ext->getScaleVector(); - if(canScale(v)) - pcTransform->scaleFactor.setValue(v.x,v.y,v.z); + if (!propLinkPlacement || propLinkPlacement == prop) { + const auto& v = ext->getScaleVector(); + if (canScale(v)) { + pcTransform->scaleFactor.setValue(v.x, v.y, v.z); + } SbMatrix matrix = convert(ext->getTransform(false)); linkView->renderDoubleSide(matrix.det3() < 1e-7); } - }else if(prop == ext->getLinkCopyOnChangeGroupProperty()) { + } + else if (prop == ext->getLinkCopyOnChangeGroupProperty()) { if (auto group = ext->getLinkCopyOnChangeGroupValue()) { auto vp = freecad_cast( - Application::Instance->getViewProvider(group)); + Application::Instance->getViewProvider(group) + ); if (vp) { vp->hide(); vp->ShowInTree.setValue(false); } } - }else if(prop == ext->getLinkedObjectProperty()) { + } + else if (prop == ext->getLinkedObjectProperty()) { - if(!prop->testStatus(App::Property::User3)) { + if (!prop->testStatus(App::Property::User3)) { std::vector subs; - const char *subname = ext->getSubName(); + const char* subname = ext->getSubName(); std::string sub; - if(subname) + if (subname) { sub = subname; + } hasSubElement = false; - for(const auto &s : ext->getSubElements()) { - if(s.empty()) continue; + for (const auto& s : ext->getSubElements()) { + if (s.empty()) { + continue; + } hasSubElement = true; - subs.push_back(sub+s); + subs.push_back(sub + s); } - if(subs.empty() && !sub.empty()) + if (subs.empty() && !sub.empty()) { subs.push_back(sub); + } hasSubName = !subs.empty(); setLinkType(ext); auto obj = ext->getLinkedObjectValue(); - linkView->setLink(obj,subs); + linkView->setLink(obj, subs); - if(ext->_getShowElementValue()) + if (ext->_getShowElementValue()) { updateElementList(ext); - else - updateDataPrivate(ext,ext->_getElementCountProperty()); + } + else { + updateDataPrivate(ext, ext->_getElementCountProperty()); + } // applyColors(); signalChangeIcon(); } - }else if(prop == ext->getLinkTransformProperty()) { + } + else if (prop == ext->getLinkTransformProperty()) { setLinkType(ext); applyColors(); - }else if(prop==ext->_getElementCountProperty()) { - if(!ext->_getShowElementValue()) { + } + else if (prop == ext->_getElementCountProperty()) { + if (!ext->_getShowElementValue()) { linkView->setSize(ext->_getElementCountValue()); - updateDataPrivate(ext,ext->getVisibilityListProperty()); - updateDataPrivate(ext,ext->getPlacementListProperty()); + updateDataPrivate(ext, ext->getVisibilityListProperty()); + updateDataPrivate(ext, ext->getPlacementListProperty()); } - }else if(prop == ext->_getShowElementProperty()) { - if(!ext->_getShowElementValue()) { + } + else if (prop == ext->_getShowElementProperty()) { + if (!ext->_getShowElementValue()) { - auto linked = freecad_cast(getLinkedView(true,ext)); - if(linked && linked->getDocument()==getDocument()) + auto linked = freecad_cast(getLinkedView(true, ext)); + if (linked && linked->getDocument() == getDocument()) { linked->hide(); + } - const auto &elements = ext->_getElementListValue(); + const auto& elements = ext->_getElementListValue(); // elements is about to be collapsed, preserve the materials - if(!elements.empty()) { + if (!elements.empty()) { std::vector materials; boost::dynamic_bitset<> overrideMaterials; - overrideMaterials.resize(elements.size(),false); + overrideMaterials.resize(elements.size(), false); bool overrideMaterial = false; bool hasMaterial = false; materials.reserve(elements.size()); - for(size_t i=0;i(elements[i]); - if(!element) continue; + if (!element) { + continue; + } auto vp = freecad_cast( - Application::Instance->getViewProvider(element)); - if(!vp) continue; + Application::Instance->getViewProvider(element) + ); + if (!vp) { + continue; + } overrideMaterial = overrideMaterial || vp->OverrideMaterial.getValue(); hasMaterial = overrideMaterial || hasMaterial - || vp->ShapeMaterial.getValue()!=ShapeMaterial.getValue(); + || vp->ShapeMaterial.getValue() != ShapeMaterial.getValue(); materials.push_back(vp->ShapeMaterial.getValue()); overrideMaterials[i] = vp->OverrideMaterial.getValue(); } - if(!overrideMaterial) + if (!overrideMaterial) { overrideMaterials.clear(); - OverrideMaterialList.setStatus(App::Property::User3,true); + } + OverrideMaterialList.setStatus(App::Property::User3, true); OverrideMaterialList.setValue(overrideMaterials); - OverrideMaterialList.setStatus(App::Property::User3,false); - if(!hasMaterial) + OverrideMaterialList.setStatus(App::Property::User3, false); + if (!hasMaterial) { materials.clear(); - MaterialList.setStatus(App::Property::User3,true); + } + MaterialList.setStatus(App::Property::User3, true); MaterialList.setValue(materials); - MaterialList.setStatus(App::Property::User3,false); + MaterialList.setStatus(App::Property::User3, false); linkView->setSize(ext->_getElementCountValue()); - updateDataPrivate(ext,ext->getVisibilityListProperty()); + updateDataPrivate(ext, ext->getVisibilityListProperty()); applyMaterial(); applyColors(); } } - }else if(prop==ext->getScaleListProperty() || prop==ext->getPlacementListProperty()) { - if(!prop->testStatus(App::Property::User3) && - linkView->getSize() && - !ext->_getShowElementValue()) - { + } + else if (prop == ext->getScaleListProperty() || prop == ext->getPlacementListProperty()) { + if (!prop->testStatus(App::Property::User3) && linkView->getSize() + && !ext->_getShowElementValue()) { auto propPlacements = ext->getPlacementListProperty(); auto propScales = ext->getScaleListProperty(); - if(propPlacements && linkView->getSize()) { - const auto &touched = - prop==propScales?propScales->getTouchList():propPlacements->getTouchList(); - if(touched.empty()) { - for(int i=0;igetSize();++i) { + if (propPlacements && linkView->getSize()) { + const auto& touched = prop == propScales ? propScales->getTouchList() + : propPlacements->getTouchList(); + if (touched.empty()) { + for (int i = 0; i < linkView->getSize(); ++i) { Base::Matrix4D mat; - if(propPlacements && propPlacements->getSize()>i) + if (propPlacements && propPlacements->getSize() > i) { mat = (*propPlacements)[i].toMatrix(); - if(propScales && propScales->getSize()>i && canScale((*propScales)[i])) { + } + if (propScales && propScales->getSize() > i && canScale((*propScales)[i])) { Base::Matrix4D s; s.scale((*propScales)[i]); mat *= s; } - linkView->setTransform(i,mat); + linkView->setTransform(i, mat); } - }else{ - for(int i : touched) { - if(i<0 || i>=linkView->getSize()) + } + else { + for (int i : touched) { + if (i < 0 || i >= linkView->getSize()) { continue; + } Base::Matrix4D mat; - if(propPlacements && propPlacements->getSize()>i) + if (propPlacements && propPlacements->getSize() > i) { mat = (*propPlacements)[i].toMatrix(); - if(propScales && propScales->getSize()>i && canScale((*propScales)[i])) { + } + if (propScales && propScales->getSize() > i && canScale((*propScales)[i])) { Base::Matrix4D s; s.scale((*propScales)[i]); mat *= s; } - linkView->setTransform(i,mat); + linkView->setTransform(i, mat); } } } } - }else if(prop == ext->getVisibilityListProperty()) { - const auto &vis = ext->getVisibilityListValue(); - for(size_t i=0;i<(size_t)linkView->getSize();++i) { - if(vis.size()>i) - linkView->setElementVisible(i,vis[i]); - else - linkView->setElementVisible(i,true); + } + else if (prop == ext->getVisibilityListProperty()) { + const auto& vis = ext->getVisibilityListValue(); + for (size_t i = 0; i < (size_t)linkView->getSize(); ++i) { + if (vis.size() > i) { + linkView->setElementVisible(i, vis[i]); + } + else { + linkView->setElementVisible(i, true); + } } - }else if(prop == ext->_getElementListProperty()) { - if(ext->_getShowElementValue()) + } + else if (prop == ext->_getElementListProperty()) { + if (ext->_getShowElementValue()) { updateElementList(ext); + } } } -void ViewProviderLink::updateElementList(App::LinkBaseExtension *ext) { - const auto &elements = ext->_getElementListValue(); - if(OverrideMaterialList.getSize() || MaterialList.getSize()) { - int i=-1; - for(auto obj : elements) { +void ViewProviderLink::updateElementList(App::LinkBaseExtension* ext) +{ + const auto& elements = ext->_getElementListValue(); + if (OverrideMaterialList.getSize() || MaterialList.getSize()) { + int i = -1; + for (auto obj : elements) { ++i; - auto vp = freecad_cast( - Application::Instance->getViewProvider(obj)); - if(!vp) continue; - if(OverrideMaterialList.getSize()>i) + auto vp = freecad_cast(Application::Instance->getViewProvider(obj)); + if (!vp) { + continue; + } + if (OverrideMaterialList.getSize() > i) { vp->OverrideMaterial.setValue(OverrideMaterialList[i]); - if(MaterialList.getSize()>i) + } + if (MaterialList.getSize() > i) { vp->ShapeMaterial.setValue(MaterialList[i]); + } } OverrideMaterialList.setSize(0); MaterialList.setSize(0); @@ -2054,26 +2417,32 @@ void ViewProviderLink::updateElementList(App::LinkBaseExtension *ext) { applyColors(); } -void ViewProviderLink::checkIcon(const App::LinkBaseExtension *ext) { - if(!ext) { +void ViewProviderLink::checkIcon(const App::LinkBaseExtension* ext) +{ + if (!ext) { ext = getLinkExtension(); - if(!ext) + if (!ext) { return; + } } - const char *icon; + const char* icon; auto element = getObject(); - if(element) + if (element) { icon = _LinkElementIcon; - else if(!ext->getLinkedObjectProperty() && ext->getElementListProperty()) + } + else if (!ext->getLinkedObjectProperty() && ext->getElementListProperty()) { icon = _LinkGroupIcon; + } // else if(ext->_getElementCountValue()) // icon = _LinkArrayIcon; - else + else { icon = _LinkIcon; + } qint64 cacheKey = 0; - if(getObject()->getLinkedObject(false)!=getObject()) + if (getObject()->getLinkedObject(false) != getObject()) { cacheKey = getOverlayPixmap().cacheKey(); - if(icon!=sPixmap || cacheKey!=overlayCacheKey) { + } + if (icon != sPixmap || cacheKey != overlayCacheKey) { sPixmap = icon; signalChangeIcon(); } @@ -2102,8 +2471,10 @@ void ViewProviderLink::applyMaterial() // 4. Create and dispatch the action. We use a secondary context action, // which is the established mechanism for this kind of override. - SoSelectionElementAction action(SoSelectionElementAction::Color, - true); // true for secondary + SoSelectionElementAction action( + SoSelectionElementAction::Color, + true + ); // true for secondary action.swapColors(colorMap); linkView->getLinkRoot()->doAction(&action); @@ -2133,319 +2504,385 @@ void ViewProviderLink::applyMaterial() } } -void ViewProviderLink::finishRestoring() { +void ViewProviderLink::finishRestoring() +{ FC_TRACE("finish restoring"); auto ext = getLinkExtension(); - if(!ext) + if (!ext) { return; - linkView->setDrawStyle(DrawStyle.getValue(),LineWidth.getValue(),PointSize.getValue()); - updateDataPrivate(ext,ext->getLinkedObjectProperty()); - if(ext->getLinkPlacementProperty()) - updateDataPrivate(ext,ext->getLinkPlacementProperty()); - else - updateDataPrivate(ext,ext->getPlacementProperty()); - updateDataPrivate(ext,ext->_getElementCountProperty()); - if(ext->getPlacementListProperty()) - updateDataPrivate(ext,ext->getPlacementListProperty()); - else - updateDataPrivate(ext,ext->getScaleListProperty()); - updateDataPrivate(ext,ext->_getElementListProperty()); + } + linkView->setDrawStyle(DrawStyle.getValue(), LineWidth.getValue(), PointSize.getValue()); + updateDataPrivate(ext, ext->getLinkedObjectProperty()); + if (ext->getLinkPlacementProperty()) { + updateDataPrivate(ext, ext->getLinkPlacementProperty()); + } + else { + updateDataPrivate(ext, ext->getPlacementProperty()); + } + updateDataPrivate(ext, ext->_getElementCountProperty()); + if (ext->getPlacementListProperty()) { + updateDataPrivate(ext, ext->getPlacementListProperty()); + } + else { + updateDataPrivate(ext, ext->getScaleListProperty()); + } + updateDataPrivate(ext, ext->_getElementListProperty()); applyMaterial(); applyColors(); // TODO: notify the tree. This is ugly, any other way? - getDocument()->signalChangedObject(*this,ext->_LinkTouched); + getDocument()->signalChangedObject(*this, ext->_LinkTouched); - if(childVp) + if (childVp) { childVp->finishRestoring(); -} - -bool ViewProviderLink::hasElements(const App::LinkBaseExtension *ext) const { - if(!ext) { - ext = getLinkExtension(); - if(!ext) - return false; } - const auto &elements = ext->getElementListValue(); - return !elements.empty() && (int)elements.size()==ext->_getElementCountValue(); } -bool ViewProviderLink::isGroup(const App::LinkBaseExtension *ext, bool plainGroup) const { - if(!ext) { +bool ViewProviderLink::hasElements(const App::LinkBaseExtension* ext) const +{ + if (!ext) { ext = getLinkExtension(); - if(!ext) + if (!ext) { return false; + } + } + const auto& elements = ext->getElementListValue(); + return !elements.empty() && (int)elements.size() == ext->_getElementCountValue(); +} + +bool ViewProviderLink::isGroup(const App::LinkBaseExtension* ext, bool plainGroup) const +{ + if (!ext) { + ext = getLinkExtension(); + if (!ext) { + return false; + } } return (plainGroup && ext->linkedPlainGroup()) || (ext->getElementListProperty() && !ext->getLinkedObjectProperty()); } -ViewProvider *ViewProviderLink::getLinkedView( - bool real,const App::LinkBaseExtension *ext) const +ViewProvider* ViewProviderLink::getLinkedView(bool real, const App::LinkBaseExtension* ext) const { - if(!ext) + if (!ext) { ext = getLinkExtension(); - auto obj = ext&&real?ext->getTrueLinkedObject(true): - getObject()->getLinkedObject(true); - if(obj && obj!=getObject()) + } + auto obj = ext && real ? ext->getTrueLinkedObject(true) : getObject()->getLinkedObject(true); + if (obj && obj != getObject()) { return Application::Instance->getViewProvider(obj); + } return nullptr; } -std::vector ViewProviderLink::claimChildren() const { +std::vector ViewProviderLink::claimChildren() const +{ auto ext = getLinkExtension(); std::vector ret; - if(ext && !ext->_getShowElementValue() && ext->_getElementCountValue()) { + if (ext && !ext->_getShowElementValue() && ext->_getElementCountValue()) { // in array mode without element objects, we'd better not show the // linked object's children to avoid inconsistent behavior on selection. // We claim the linked object instead - if(ext) { + if (ext) { auto obj = ext->getLinkedObjectValue(); - if(obj) ret.push_back(obj); - } - } else if(hasElements(ext) || isGroup(ext)) { - ret = ext->getElementListValue(); - if (ext->_getElementCountValue() - && ext->getLinkClaimChildValue() - && ext->getLinkedObjectValue()) - ret.insert(ret.begin(), ext->getLinkedObjectValue()); - } else if(!hasSubName) { - auto linked = getLinkedView(true); - if(linked) { - ret = linked->claimChildren(); - if (ext->getLinkClaimChildValue() && ext->getLinkedObjectValue()) - ret.insert(ret.begin(), ext->getLinkedObjectValue()); + if (obj) { + ret.push_back(obj); + } } } - if (ext && ext->getLinkCopyOnChangeGroupValue()) + else if (hasElements(ext) || isGroup(ext)) { + ret = ext->getElementListValue(); + if (ext->_getElementCountValue() && ext->getLinkClaimChildValue() + && ext->getLinkedObjectValue()) { + ret.insert(ret.begin(), ext->getLinkedObjectValue()); + } + } + else if (!hasSubName) { + auto linked = getLinkedView(true); + if (linked) { + ret = linked->claimChildren(); + if (ext->getLinkClaimChildValue() && ext->getLinkedObjectValue()) { + ret.insert(ret.begin(), ext->getLinkedObjectValue()); + } + } + } + if (ext && ext->getLinkCopyOnChangeGroupValue()) { ret.insert(ret.begin(), ext->getLinkCopyOnChangeGroupValue()); + } return ret; } -bool ViewProviderLink::canDragObject(App::DocumentObject* obj) const { +bool ViewProviderLink::canDragObject(App::DocumentObject* obj) const +{ auto ext = getLinkExtension(); - if(isGroup(ext)) + if (isGroup(ext)) { return true; - if(hasElements(ext)) + } + if (hasElements(ext)) { return false; - auto linked = getLinkedView(false,ext); - if(linked) + } + auto linked = getLinkedView(false, ext); + if (linked) { return linked->canDragObject(obj); + } return false; } -bool ViewProviderLink::canDragObjects() const { +bool ViewProviderLink::canDragObjects() const +{ auto ext = getLinkExtension(); - if(isGroup(ext)) + if (isGroup(ext)) { return true; - if(hasElements(ext)) + } + if (hasElements(ext)) { return false; - auto linked = getLinkedView(false,ext); - if(linked) + } + auto linked = getLinkedView(false, ext); + if (linked) { return linked->canDragObjects(); + } return false; } -void ViewProviderLink::dragObject(App::DocumentObject* obj) { +void ViewProviderLink::dragObject(App::DocumentObject* obj) +{ auto ext = getLinkExtension(); - if(isGroup(ext)) { - const auto &objs = ext->getElementListValue(); - for(size_t i=0;isetLink(i,nullptr); + if (isGroup(ext)) { + const auto& objs = ext->getElementListValue(); + for (size_t i = 0; i < objs.size(); ++i) { + if (obj == objs[i]) { + ext->setLink(i, nullptr); break; } } return; } - if(hasElements(ext)) + if (hasElements(ext)) { return; + } auto linked = getLinkedView(false); - if(linked) + if (linked) { linked->dragObject(obj); + } } -bool ViewProviderLink::canDropObjects() const { +bool ViewProviderLink::canDropObjects() const +{ auto ext = getLinkExtension(); - if(isGroup(ext)) + if (isGroup(ext)) { return true; - if(hasElements(ext)) + } + if (hasElements(ext)) { return false; - if(hasSubElement) + } + if (hasSubElement) { return true; - else if(hasSubName) + } + else if (hasSubName) { return false; - auto linked = getLinkedView(false,ext); - if(linked) + } + auto linked = getLinkedView(false, ext); + if (linked) { return linked->canDropObjects(); + } return true; } -bool ViewProviderLink::canDropObjectEx(App::DocumentObject *obj, - App::DocumentObject *owner, const char *subname, - const std::vector &subElements) const +bool ViewProviderLink::canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& subElements +) const { - if(pcObject == obj || pcObject == owner) + if (pcObject == obj || pcObject == owner) { return false; + } auto ext = getLinkExtension(); - if(isGroup(ext)) + if (isGroup(ext)) { return true; - if(!ext || !ext->getLinkedObjectProperty() || hasElements(ext)) + } + if (!ext || !ext->getLinkedObjectProperty() || hasElements(ext)) { return false; - if(!hasSubName && linkView->isLinked()) { - auto linked = getLinkedView(false,ext); - if(linked) { + } + if (!hasSubName && linkView->isLinked()) { + auto linked = getLinkedView(false, ext); + if (linked) { auto linkedVdp = freecad_cast(linked); - if(linkedVdp) { - if(linkedVdp->getObject()==obj || linkedVdp->getObject()==owner) + if (linkedVdp) { + if (linkedVdp->getObject() == obj || linkedVdp->getObject() == owner) { return false; + } } - return linked->canDropObjectEx(obj,owner,subname,subElements); + return linked->canDropObjectEx(obj, owner, subname, subElements); } } - if(obj->getDocument() != getObject()->getDocument() && - !freecad_cast(ext->getLinkedObjectProperty())) + if (obj->getDocument() != getObject()->getDocument() + && !freecad_cast(ext->getLinkedObjectProperty())) { return false; + } return true; } -std::string ViewProviderLink::dropObjectEx(App::DocumentObject* obj, - App::DocumentObject *owner, const char *subname, - const std::vector &subElements) +std::string ViewProviderLink::dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& subElements +) { auto ext = getLinkExtension(); - if (!ext) + if (!ext) { return std::string(); + } - if(isGroup(ext)) { + if (isGroup(ext)) { size_t size = ext->getElementListValue().size(); - ext->setLink(size,obj); - return std::to_string(size)+"."; + ext->setLink(size, obj); + return std::to_string(size) + "."; } - if(!ext->getLinkedObjectProperty() || hasElements(ext)) + if (!ext->getLinkedObjectProperty() || hasElements(ext)) { return std::string(); - - if(!hasSubName) { - auto linked = getLinkedView(false,ext); - if(linked) - return linked->dropObjectEx(obj,owner,subname,subElements); } - if(owner) { - if(!ext->getSubElements().empty()) - ext->setLink(-1,owner,subname,subElements); - else - ext->setLink(-1,owner,subname); - } else if(!ext->getSubElements().empty()) - ext->setLink(-1,obj,nullptr,subElements); - else - ext->setLink(-1,obj,nullptr); + + if (!hasSubName) { + auto linked = getLinkedView(false, ext); + if (linked) { + return linked->dropObjectEx(obj, owner, subname, subElements); + } + } + if (owner) { + if (!ext->getSubElements().empty()) { + ext->setLink(-1, owner, subname, subElements); + } + else { + ext->setLink(-1, owner, subname); + } + } + else if (!ext->getSubElements().empty()) { + ext->setLink(-1, obj, nullptr, subElements); + } + else { + ext->setLink(-1, obj, nullptr); + } return std::string(); } -bool ViewProviderLink::canDragAndDropObject(App::DocumentObject* obj) const { +bool ViewProviderLink::canDragAndDropObject(App::DocumentObject* obj) const +{ auto ext = getLinkExtension(); - if(!ext) + if (!ext) { return true; - if(isGroup(ext)) { - return ext->getLinkModeValue()getDocument()==getObject()->getDocument(); } - if(!ext->getLinkedObjectProperty() || hasElements(ext)) + if (isGroup(ext)) { + return ext->getLinkModeValue() < App::LinkBaseExtension::LinkModeAutoLink + && obj->getDocument() == getObject()->getDocument(); + } + if (!ext->getLinkedObjectProperty() || hasElements(ext)) { return false; - if(!hasSubName) { - auto linked = getLinkedView(false,ext); - if(linked) + } + if (!hasSubName) { + auto linked = getLinkedView(false, ext); + if (linked) { return linked->canDragAndDropObject(obj); + } } return false; } -bool ViewProviderLink::getElementPicked(const SoPickedPoint *pp, std::string &subname) const { - if(!isSelectable()) { +bool ViewProviderLink::getElementPicked(const SoPickedPoint* pp, std::string& subname) const +{ + if (!isSelectable()) { return false; } auto ext = getLinkExtension(); if (!ext) { return false; } - if(childVpLink && childVp) { + if (childVpLink && childVp) { auto path = pp->getPath(); int idx = path->findNode(childVpLink->getSnapshot(LinkView::SnapshotTransform)); - if(idx>=0) { + if (idx >= 0) { return childVp->getElementPicked(pp, subname); } } - bool ret = linkView->linkGetElementPicked(pp,subname); - if(!ret) { + bool ret = linkView->linkGetElementPicked(pp, subname); + if (!ret) { return ret; } - if(isGroup(ext,true)) { - const char *sub = nullptr; - int idx = App::LinkBaseExtension::getArrayIndex(subname.c_str(),&sub); - if(idx>=0 ) { + if (isGroup(ext, true)) { + const char* sub = nullptr; + int idx = App::LinkBaseExtension::getArrayIndex(subname.c_str(), &sub); + if (idx >= 0) { --sub; assert(*sub == '.'); - const auto &elements = ext->_getElementListValue(); - subname.replace(0,sub-subname.c_str(),elements[idx]->getNameInDocument()); + const auto& elements = ext->_getElementListValue(); + subname.replace(0, sub - subname.c_str(), elements[idx]->getNameInDocument()); } } return ret; } -bool ViewProviderLink::getDetailPath( - const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const +bool ViewProviderLink::getDetailPath(const char* subname, SoFullPath* pPath, bool append, SoDetail*& det) const { auto ext = getLinkExtension(); - if(!ext) + if (!ext) { return false; + } auto len = pPath->getLength(); - if(append) { - appendPath(pPath,pcRoot); - appendPath(pPath,pcModeSwitch); + if (append) { + appendPath(pPath, pcRoot); + appendPath(pPath, pcModeSwitch); } - if(childVpLink && getDefaultMode()==1) { - if(childVpLink->getDetail(false,LinkView::SnapshotTransform,subname,det,pPath)) + if (childVpLink && getDefaultMode() == 1) { + if (childVpLink->getDetail(false, LinkView::SnapshotTransform, subname, det, pPath)) { return true; + } pPath->truncate(len); return false; } std::string _subname; - if(!Base::Tools::isNullOrEmpty(subname)) { + if (!Base::Tools::isNullOrEmpty(subname)) { if (auto linked = ext->getLinkedObjectValue()) { - if (const char *dot = strchr(subname,'.')) { - if(subname[0]=='$') { - CharRange sub(subname+1, dot); - if (!boost::equals(sub, linked->Label.getValue())) - dot = nullptr; - } else { - CharRange sub(subname, dot); - if (!boost::equals(sub, linked->getNameInDocument())) + if (const char* dot = strchr(subname, '.')) { + if (subname[0] == '$') { + CharRange sub(subname + 1, dot); + if (!boost::equals(sub, linked->Label.getValue())) { dot = nullptr; + } + } + else { + CharRange sub(subname, dot); + if (!boost::equals(sub, linked->getNameInDocument())) { + dot = nullptr; + } + } + if (dot && linked->getSubObject(dot + 1)) { + subname = dot + 1; } - if (dot && linked->getSubObject(dot+1)) - subname = dot+1; } } - if (isGroup(ext,true) || hasElements(ext) || ext->getElementCountValue()) { - int index = ext->getElementIndex(subname,&subname); - if(index>=0) { - _subname = std::to_string(index)+'.'+subname; + if (isGroup(ext, true) || hasElements(ext) || ext->getElementCountValue()) { + int index = ext->getElementIndex(subname, &subname); + if (index >= 0) { + _subname = std::to_string(index) + '.' + subname; subname = _subname.c_str(); } } } - if(linkView->linkGetDetailPath(subname,pPath,det)) + if (linkView->linkGetDetailPath(subname, pPath, det)) { return true; + } pPath->truncate(len); return false; } -bool ViewProviderLink::onDelete(const std::vector &) { +bool ViewProviderLink::onDelete(const std::vector&) +{ auto element = getObject(); if (element && !element->canDelete()) { return false; @@ -2459,7 +2896,7 @@ bool ViewProviderLink::onDelete(const std::vector &) { doc->removeObject(element->getNameInDocument()); } } - + auto ext = getLinkExtension(); if (ext->isLinkMutated()) { auto linked = ext->getLinkedObjectValue(); @@ -2474,114 +2911,137 @@ bool ViewProviderLink::onDelete(const std::vector &) { objs.emplace_front(obj->getNameInDocument()); } } - for (const auto &name : objs) + for (const auto& name : objs) { doc->removeObject(name.c_str()); + } } } return true; } -bool ViewProviderLink::canDelete(App::DocumentObject *obj) const { +bool ViewProviderLink::canDelete(App::DocumentObject* obj) const +{ auto ext = getLinkExtension(); - if(isGroup(ext) || hasElements(ext) || hasSubElement) + if (isGroup(ext) || hasElements(ext) || hasSubElement) { return true; - auto linked = getLinkedView(false,ext); - if(linked) + } + auto linked = getLinkedView(false, ext); + if (linked) { return linked->canDelete(obj); + } return false; } -bool ViewProviderLink::linkEdit(const App::LinkBaseExtension *ext) const { - if(!ext) +bool ViewProviderLink::linkEdit(const App::LinkBaseExtension* ext) const +{ + if (!ext) { ext = getLinkExtension(); - if(!ext || - (!ext->_getShowElementValue() && ext->_getElementCountValue()) || - hasElements(ext) || - isGroup(ext) || - hasSubName) - { + } + if (!ext || (!ext->_getShowElementValue() && ext->_getElementCountValue()) || hasElements(ext) + || isGroup(ext) || hasSubName) { return false; } return linkView->isLinked(); } -bool ViewProviderLink::doubleClicked() { - if(linkEdit()) +bool ViewProviderLink::doubleClicked() +{ + if (linkEdit()) { return linkView->getLinkedView()->doubleClicked(); - return getDocument()->setEdit(this,ViewProvider::Transform); + } + return getDocument()->setEdit(this, ViewProvider::Transform); } void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { auto ext = getLinkExtension(); - if (!ext) + if (!ext) { return; + } _setupContextMenu(ext, menu, receiver, member); Gui::ActionFunction* func = nullptr; if (ext->isLinkedToConfigurableObject()) { auto src = ext->getLinkCopyOnChangeSourceValue(); - if (!src) src = ext->getLinkedObjectValue(); + if (!src) { + src = ext->getLinkedObjectValue(); + } if (src && !ext->getOnChangeCopyObjects(nullptr, src).empty()) { - QAction *act = menu->addAction( - QObject::tr("Setup Configurable Object")); - act->setToolTip(QObject::tr( - "Selects which object to copy or exclude when configuration changes. " - "All external linked objects are excluded by default.")); + QAction* act = menu->addAction(QObject::tr("Setup Configurable Object")); + act->setToolTip( + QObject::tr( + "Selects which object to copy or exclude when configuration changes. " + "All external linked objects are excluded by default." + ) + ); act->setData(-1); - if (!func) func = new Gui::ActionFunction(menu); - func->trigger(act, [ext](){ + if (!func) { + func = new Gui::ActionFunction(menu); + } + func->trigger(act, [ext]() { try { std::vector excludes; auto src = ext->getLinkCopyOnChangeSourceValue(); - if (!src) + if (!src) { src = ext->getLinkedObjectValue(); + } auto objs = ext->getOnChangeCopyObjects(&excludes, src); - if (objs.empty()) + if (objs.empty()) { return; + } DlgObjectSelection dlg({src}, excludes, getMainWindow()); - dlg.setMessage(QObject::tr( - "Select which objects to copy when the configuration is changed")); + dlg.setMessage( + QObject::tr("Select which objects to copy when the configuration is changed") + ); auto box = new QCheckBox(QObject::tr("Apply to all"), &dlg); box->setToolTip(QObject::tr("Applies the setting to all links")); box->setChecked(App::LinkParams::getCopyOnChangeApplyToAll()); dlg.addCheckBox(box); - if(dlg.exec()!=QDialog::Accepted) + if (dlg.exec() != QDialog::Accepted) { return; + } bool applyAll = box->isChecked(); App::LinkParams::setCopyOnChangeApplyToAll(applyAll); App::Link::OnChangeCopyOptions options {App::Link::OnChangeCopyOptions::None}; - if (applyAll) + if (applyAll) { options |= App::Link::OnChangeCopyOptions::ApplyAll; + } App::AutoTransaction guard("Setup configurable object"); auto sels = dlg.getSelections(DlgObjectSelection::SelectionOptions::InvertSort); - for (const auto & exclude : excludes) { + for (const auto& exclude : excludes) { auto iter = std::lower_bound(sels.begin(), sels.end(), exclude); if (iter == sels.end() || *iter != exclude) { ext->setOnChangeCopyObject(exclude, options); - } else + } + else { sels.erase(iter); + } } options |= App::Link::OnChangeCopyOptions::Exclude; - for (auto obj : sels) + for (auto obj : sels) { ext->setOnChangeCopyObject(obj, options); - if (!applyAll) + } + if (!applyAll) { ext->monitorOnChangeCopyObjects(ext->getOnChangeCopyObjects()); + } else { std::set exts; for (auto o : App::Document::getDependencyList(objs)) { - if (auto ext = o->getExtensionByType(true)) + if (auto ext = o->getExtensionByType(true)) { exts.insert(ext); + } } - for (auto ext : exts) + for (auto ext : exts) { ext->monitorOnChangeCopyObjects(ext->getOnChangeCopyObjects()); + } } Command::updateActive(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); } }); @@ -2590,48 +3050,57 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch if (ext->getLinkCopyOnChangeValue() == 0) { auto submenu = menu->addMenu(QObject::tr("Copy on Change")); auto act = submenu->addAction(QObject::tr("Enable")); - act->setToolTip(QObject::tr( - "Enable auto copy of linked object when its configuration is changed")); + act->setToolTip( + QObject::tr("Enable auto copy of linked object when its configuration is changed") + ); act->setData(-1); - if (!func) func = new Gui::ActionFunction(menu); - func->trigger(act, [ext](){ + if (!func) { + func = new Gui::ActionFunction(menu); + } + func->trigger(act, [ext]() { try { App::AutoTransaction guard("Enable Link copy on change"); ext->getLinkCopyOnChangeProperty()->setValue(1); Command::updateActive(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); } }); act = submenu->addAction(QObject::tr("Tracking")); - act->setToolTip(QObject::tr( - "Copies the linked object when its configuration is changed.\n" - "Also auto redo the copy if the original linked object is changed.\n")); + act->setToolTip( + QObject::tr( + "Copies the linked object when its configuration is changed.\n" + "Also auto redo the copy if the original linked object is changed.\n" + ) + ); act->setData(-1); - func->trigger(act, [ext](){ + func->trigger(act, [ext]() { try { App::AutoTransaction guard("Enable Link tracking"); ext->getLinkCopyOnChangeProperty()->setValue(3); Command::updateActive(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); } }); } } - if (ext->getLinkCopyOnChangeValue() != 2 - && ext->getLinkCopyOnChangeValue() != 0) { - QAction *act = menu->addAction( - QObject::tr("Disable Copy on Change")); + if (ext->getLinkCopyOnChangeValue() != 2 && ext->getLinkCopyOnChangeValue() != 0) { + QAction* act = menu->addAction(QObject::tr("Disable Copy on Change")); act->setData(-1); - if (!func) func = new Gui::ActionFunction(menu); - func->trigger(act, [ext](){ + if (!func) { + func = new Gui::ActionFunction(menu); + } + func->trigger(act, [ext]() { try { App::AutoTransaction guard("Disable copy on change"); ext->getLinkCopyOnChangeProperty()->setValue((long)0); Command::updateActive(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); } }); @@ -2639,18 +3108,24 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch if (ext->isLinkMutated()) { QAction* act = menu->addAction(QObject::tr("Refresh Configurable Object")); - act->setToolTip(QObject::tr( - "Synchronizes the original configurable source object by\n" - "creating a new deep copy. Any changes made to\n" - "the current copy will be lost.\n")); + act->setToolTip( + QObject::tr( + "Synchronizes the original configurable source object by\n" + "creating a new deep copy. Any changes made to\n" + "the current copy will be lost.\n" + ) + ); act->setData(-1); - if (!func) func = new Gui::ActionFunction(menu); - func->trigger(act, [ext](){ + if (!func) { + func = new Gui::ActionFunction(menu); + } + func->trigger(act, [ext]() { try { App::AutoTransaction guard("Link refresh"); ext->syncCopyOnChange(); Command::updateActive(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); } }); @@ -2658,62 +3133,69 @@ void ViewProviderLink::setupContextMenu(QMenu* menu, QObject* receiver, const ch } void ViewProviderLink::_setupContextMenu( - App::LinkBaseExtension *ext, QMenu* menu, QObject* receiver, const char* member) + App::LinkBaseExtension* ext, + QMenu* menu, + QObject* receiver, + const char* member +) { - if(linkEdit(ext)) { - if (auto linkvp = freecad_cast(linkView->getLinkedView())) + if (linkEdit(ext)) { + if (auto linkvp = freecad_cast(linkView->getLinkedView())) { linkvp->_setupContextMenu(ext, menu, receiver, member); - else - linkView->getLinkedView()->setupContextMenu(menu,receiver,member); + } + else { + linkView->getLinkedView()->setupContextMenu(menu, receiver, member); + } } - if(ext->getLinkedObjectProperty() - && ext->_getShowElementProperty() - && ext->_getElementCountValue() > 1) - { + if (ext->getLinkedObjectProperty() && ext->_getShowElementProperty() + && ext->_getElementCountValue() > 1) { auto action = menu->addAction(QObject::tr("Toggle Array Elements"), [ext] { try { App::AutoTransaction guard(QT_TRANSLATE_NOOP("Command", "Toggle array elements")); ext->getShowElementProperty()->setValue(!ext->getShowElementValue()); Command::updateActive(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); } }); - action->setToolTip(QObject::tr( - "Changes whether to show each link array element as individual objects")); + action->setToolTip( + QObject::tr("Changes whether to show each link array element as individual objects") + ); } - if((ext->getPlacementProperty() && !ext->getPlacementProperty()->isReadOnly()) - || (ext->getLinkPlacementProperty() && !ext->getLinkPlacementProperty()->isReadOnly())) - { + if ((ext->getPlacementProperty() && !ext->getPlacementProperty()->isReadOnly()) + || (ext->getLinkPlacementProperty() && !ext->getLinkPlacementProperty()->isReadOnly())) { bool found = false; const auto actions = menu->actions(); - for(auto action : actions) { - if(action->data().toInt() == ViewProvider::Transform) { + for (auto action : actions) { + if (action->data().toInt() == ViewProvider::Transform) { found = true; break; } } if (!found) { - QIcon iconObject = mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap("Std_TransformManip.svg")); + QIcon iconObject = mergeGreyableOverlayIcons( + Gui::BitmapFactory().pixmap("Std_TransformManip.svg") + ); QAction* act = menu->addAction(iconObject, QObject::tr("Transform"), receiver, member); act->setToolTip(QObject::tr("Transforms the object at the origin of the placement")); act->setData(QVariant((int)ViewProvider::Transform)); } } - if(ext->getColoredElementsProperty()) { + if (ext->getColoredElementsProperty()) { bool found = false; const auto actions = menu->actions(); - for(auto action : actions) { - if(action->data().toInt() == ViewProvider::Color) { + for (auto action : actions) { + if (action->data().toInt() == ViewProvider::Color) { action->setText(QObject::tr("Override Colors")); found = true; break; } } - if(!found) { + if (!found) { QAction* act = menu->addAction(QObject::tr("Override Colors"), receiver, member); act->setData(QVariant((int)ViewProvider::Color)); } @@ -2723,51 +3205,63 @@ void ViewProviderLink::_setupContextMenu( menu->addAction(cmd->getAction()->action()); } -bool ViewProviderLink::initDraggingPlacement() { +bool ViewProviderLink::initDraggingPlacement() +{ Base::PyGILStateLocker lock; try { auto* proxy = getPropertyByName("Proxy"); if (proxy && proxy->is()) { Py::Object feature = static_cast(proxy)->getValue(); - const char *fname = "initDraggingPlacement"; + const char* fname = "initDraggingPlacement"; if (feature.hasAttr(fname)) { Py::Callable method(feature.getAttr(fname)); Py::Tuple arg; Py::Object ret(method.apply(arg)); - if(ret.isTuple()) { - PyObject *pymat,*pypla,*pybbox; - if(!PyArg_ParseTuple(ret.ptr(),"O!O!O!",&Base::MatrixPy::Type, &pymat, - &Base::PlacementPy::Type, &pypla, - &Base::BoundBoxPy::Type, &pybbox)) { + if (ret.isTuple()) { + PyObject *pymat, *pypla, *pybbox; + if (!PyArg_ParseTuple( + ret.ptr(), + "O!O!O!", + &Base::MatrixPy::Type, + &pymat, + &Base::PlacementPy::Type, + &pypla, + &Base::BoundBoxPy::Type, + &pybbox + )) { FC_ERR("initDraggingPlacement() expects return of type tuple(matrix,placement,boundbox)"); return false; } dragCtx = std::make_unique(); - dragCtx->initialPlacement = *static_cast(pypla)->getPlacementPtr(); + dragCtx->initialPlacement + = *static_cast(pypla)->getPlacementPtr(); dragCtx->preTransform = *static_cast(pymat)->getMatrixPtr(); dragCtx->bbox = *static_cast(pybbox)->getBoundBoxPtr(); return true; - }else if(!ret.isTrue()) + } + else if (!ret.isTrue()) { return false; + } } } - } catch (Py::Exception&) { + } + catch (Py::Exception&) { Base::PyException e; e.reportException(); return false; } auto ext = getLinkExtension(); - if(!ext) { + if (!ext) { FC_ERR("no link extension"); return false; } - if(!ext->hasPlacement()) { + if (!ext->hasPlacement()) { FC_ERR("no placement"); return false; } auto doc = Application::Instance->editDocument(); - if(!doc) { + if (!doc) { FC_ERR("no editing document"); return false; } @@ -2775,13 +3269,13 @@ bool ViewProviderLink::initDraggingPlacement() { dragCtx = std::make_unique(); dragCtx->preTransform = doc->getEditingTransform(); - const auto &pla = getPlacementProperty()->getValue(); + const auto& pla = getPlacementProperty()->getValue(); // Cancel out our own transformation from the editing transform, because // the dragger is meant to change our transformation. dragCtx->preTransform *= pla.inverse().toMatrix(); - dragCtx->bbox = getBoundingBox(nullptr,false); + dragCtx->bbox = getBoundingBox(nullptr, false); // The returned bounding box is before our own transform, but we still need // to scale it to get the correct center. auto scale = ext->getScaleVector(); @@ -2789,27 +3283,31 @@ bool ViewProviderLink::initDraggingPlacement() { dragCtx->bbox.ScaleY(scale.y); dragCtx->bbox.ScaleZ(scale.z); - App::PropertyPlacement *propPla = nullptr; - if(ext->getLinkTransformValue() && ext->getLinkedObjectValue()) { + App::PropertyPlacement* propPla = nullptr; + if (ext->getLinkTransformValue() && ext->getLinkedObjectValue()) { propPla = freecad_cast( - ext->getLinkedObjectValue()->getPropertyByName("Placement")); + ext->getLinkedObjectValue()->getPropertyByName("Placement") + ); } - if(propPla) { + if (propPla) { dragCtx->initialPlacement = pla * propPla->getValue(); dragCtx->mat *= propPla->getValue().inverse().toMatrix(); - } else { + } + else { dragCtx->initialPlacement = pla; } return true; } -ViewProvider *ViewProviderLink::startEditing(int mode) { - if(mode==ViewProvider::Color) { +ViewProvider* ViewProviderLink::startEditing(int mode) +{ + if (mode == ViewProvider::Color) { auto ext = getLinkExtension(); - if(!ext || !ext->getColoredElementsProperty()) { - if(linkEdit(ext)) + if (!ext || !ext->getColoredElementsProperty()) { + if (linkEdit(ext)) { return linkView->getLinkedView()->startEditing(mode); + } } return inherited::startEditing(mode); } @@ -2841,7 +3339,7 @@ ViewProvider *ViewProviderLink::startEditing(int mode) { } } - if(!linkEdit()) { + if (!linkEdit()) { FC_ERR("unsupported edit mode " << mode); return nullptr; } @@ -2853,7 +3351,7 @@ ViewProvider *ViewProviderLink::startEditing(int mode) { // and set color. We need to find a better place to declare this constant. mode &= ~0x8000; - if(!doc) { + if (!doc) { FC_ERR("no editing document"); return nullptr; } @@ -2861,14 +3359,15 @@ ViewProvider *ViewProviderLink::startEditing(int mode) { // We are forwarding the editing request to linked object. We need to // adjust the editing transformation. Base::Matrix4D mat; - auto linked = getObject()->getLinkedObject(true,&mat,false); - if(!linked || linked==getObject()) { + auto linked = getObject()->getLinkedObject(true, &mat, false); + if (!linked || linked == getObject()) { FC_ERR("no linked object"); return nullptr; } auto vpd = freecad_cast( - Application::Instance->getViewProvider(linked)); - if(!vpd) { + Application::Instance->getViewProvider(linked) + ); + if (!vpd) { FC_ERR("no linked viewprovider"); return nullptr; } @@ -2876,7 +3375,7 @@ ViewProvider *ViewProviderLink::startEditing(int mode) { // But save it first in case the linked object reroute the editing request // back to us. _editingTransform = doc->getEditingTransform(); - doc->setEditingTransform(doc->getEditingTransform()*mat); + doc->setEditingTransform(doc->getEditingTransform() * mat); Base::FlagToggler<> guard(_pendingTransform); return vpd->startEditing(mode); } @@ -2885,9 +3384,10 @@ bool ViewProviderLink::setEdit(int ModNum) { if (ModNum == ViewProvider::Color) { auto ext = getLinkExtension(); - if(!ext || !ext->getColoredElementsProperty()) + if (!ext || !ext->getColoredElementsProperty()) { return false; - TaskView::TaskDialog *dlg = Control().activeDialog(); + } + TaskView::TaskDialog* dlg = Control().activeDialog(); if (dlg) { Control().showDialog(dlg); return false; @@ -2918,7 +3418,8 @@ void ViewProviderLink::unsetEditViewer(Gui::View3DInventorViewer* viewer) inherited::unsetEditViewer(viewer); } -bool ViewProviderLink::callDraggerProxy(const char* fname) { +bool ViewProviderLink::callDraggerProxy(const char* fname) +{ if (!transformDragger) { return false; } @@ -2931,11 +3432,13 @@ bool ViewProviderLink::callDraggerProxy(const char* fname) { if (feature.hasAttr(fname)) { Py::Callable method(feature.getAttr(fname)); Py::Tuple args; - if(method.apply(args).isTrue()) + if (method.apply(args).isTrue()) { return true; + } } } - } catch (Py::Exception&) { + } + catch (Py::Exception&) { Base::PyException e; e.reportException(); return true; @@ -2944,142 +3447,171 @@ bool ViewProviderLink::callDraggerProxy(const char* fname) { return false; } -void ViewProviderLink::dragStartCallback(void *data, SoDragger *) { +void ViewProviderLink::dragStartCallback(void* data, SoDragger*) +{ auto me = static_cast(data); me->dragCtx->initialPlacement = me->getDraggerPlacement(); me->callDraggerProxy("onDragStart"); } -void ViewProviderLink::dragFinishCallback(void *data, SoDragger *) { +void ViewProviderLink::dragFinishCallback(void* data, SoDragger*) +{ auto me = static_cast(data); me->callDraggerProxy("onDragEnd"); if (me->dragCtx->cmdPending) { if (me->getDraggerPlacement() == me->dragCtx->initialPlacement) { me->getDocument()->abortCommand(); - } else { + } + else { me->getDocument()->commitCommand(); } } } -void ViewProviderLink::dragMotionCallback(void *data, SoDragger *) { +void ViewProviderLink::dragMotionCallback(void* data, SoDragger*) +{ auto me = static_cast(data); me->callDraggerProxy("onDragMotion"); } -void ViewProviderLink::updateLinks(ViewProvider *vp) { +void ViewProviderLink::updateLinks(ViewProvider* vp) +{ try { auto ext = vp->getExtensionByType(true); - if (ext && ext->linkInfo) + if (ext && ext->linkInfo) { ext->linkInfo->update(); + } } - catch (const Base::TypeError &e) { + catch (const Base::TypeError& e) { e.reportException(); } - catch (const Base::ValueError &e) { + catch (const Base::ValueError& e) { e.reportException(); } } -PyObject *ViewProviderLink::getPyObject() { - if (!pyViewObject) +PyObject* ViewProviderLink::getPyObject() +{ + if (!pyViewObject) { pyViewObject = new ViewProviderLinkPy(this); + } pyViewObject->IncRef(); return pyViewObject; } -PyObject *ViewProviderLink::getPyLinkView() { +PyObject* ViewProviderLink::getPyLinkView() +{ return linkView->getPyObject(); } -std::map ViewProviderLink::getElementColors(const char *subname) const { +std::map ViewProviderLink::getElementColors(const char* subname) const +{ bool isPrefix = true; - if(!subname) + if (!subname) { subname = ""; + } else { auto len = strlen(subname); - isPrefix = !len || subname[len-1]=='.'; + isPrefix = !len || subname[len - 1] == '.'; } std::map colors; auto ext = getLinkExtension(); - if(!ext || ! ext->getColoredElementsProperty()) + if (!ext || !ext->getColoredElementsProperty()) { return colors; - const auto &subs = ext->getColoredElementsProperty()->getShadowSubs(); + } + const auto& subs = ext->getColoredElementsProperty()->getShadowSubs(); int size = OverrideColorList.getSize(); std::string wildcard(subname); - if(wildcard == "Face" || wildcard == "Face*" || wildcard.empty()) { - if(wildcard.size()==4 || OverrideMaterial.getValue()) { + if (wildcard == "Face" || wildcard == "Face*" || wildcard.empty()) { + if (wildcard.size() == 4 || OverrideMaterial.getValue()) { Base::Color c = ShapeMaterial.getValue().diffuseColor; c.setTransparency(ShapeMaterial.getValue().transparency); colors["Face"] = c; - if(wildcard.size()==4) + if (wildcard.size() == 4) { return colors; + } } - if(!wildcard.empty()) + if (!wildcard.empty()) { wildcard.resize(4); - }else if(wildcard == "Edge*") + } + } + else if (wildcard == "Edge*") { wildcard.resize(4); - else if(wildcard == "Vertex*") + } + else if (wildcard == "Vertex*") { wildcard.resize(5); - else if(wildcard == ViewProvider::hiddenMarker()+"*") + } + else if (wildcard == ViewProvider::hiddenMarker() + "*") { wildcard.resize(ViewProvider::hiddenMarker().size()); - else + } + else { wildcard.clear(); + } - int i=-1; - if(!wildcard.empty()) { - for(const auto &sub : subs) { - if(++i >= size) + int i = -1; + if (!wildcard.empty()) { + for (const auto& sub : subs) { + if (++i >= size) { break; + } auto pos = sub.oldName.rfind('.'); - if(pos == std::string::npos) + if (pos == std::string::npos) { pos = 0; - else + } + else { ++pos; - const char *element = sub.oldName.c_str()+pos; - if(boost::starts_with(element,wildcard)) + } + const char* element = sub.oldName.c_str() + pos; + if (boost::starts_with(element, wildcard)) { colors[sub.oldName] = OverrideColorList[i]; - else if(!element[0] && wildcard=="Face") - colors[sub.oldName.substr(0,element-sub.oldName.c_str())+wildcard] = OverrideColorList[i]; + } + else if (!element[0] && wildcard == "Face") { + colors[sub.oldName.substr(0, element - sub.oldName.c_str()) + wildcard] + = OverrideColorList[i]; + } } // In case of multi-level linking, we recursively call into each level, // and merge the colors auto vp = this; - while(true) { - if(wildcard!=ViewProvider::hiddenMarker() && vp->OverrideMaterial.getValue()) { + while (true) { + if (wildcard != ViewProvider::hiddenMarker() && vp->OverrideMaterial.getValue()) { auto color = ShapeMaterial.getValue().diffuseColor; color.setTransparency(ShapeMaterial.getValue().transparency); - colors.emplace(wildcard,color); + colors.emplace(wildcard, color); } auto link = vp->getObject()->getLinkedObject(false); - if(!link || link==vp->getObject()) + if (!link || link == vp->getObject()) { break; - auto next = freecad_cast( - Application::Instance->getViewProvider(link)); - if(!next) + } + auto next = freecad_cast(Application::Instance->getViewProvider(link)); + if (!next) { break; - for(const auto &v : next->getElementColors(subname)) + } + for (const auto& v : next->getElementColors(subname)) { colors.insert(v); + } vp = next; } - if(wildcard!=ViewProvider::hiddenMarker()) { + if (wildcard != ViewProvider::hiddenMarker()) { // Get collapsed array color override. auto ext = vp->getLinkExtension(); - if(ext->_getElementCountValue() && !ext->_getShowElementValue()) { - const auto &overrides = vp->OverrideMaterialList.getValues(); - int i=-1; - for(const auto &mat : vp->MaterialList.getValues()) { - if(++i>=(int)overrides.size()) + if (ext->_getElementCountValue() && !ext->_getShowElementValue()) { + const auto& overrides = vp->OverrideMaterialList.getValues(); + int i = -1; + for (const auto& mat : vp->MaterialList.getValues()) { + if (++i >= (int)overrides.size()) { break; - if(!overrides[i]) + } + if (!overrides[i]) { continue; + } auto color = mat.diffuseColor; color.setTransparency(mat.transparency); - colors.emplace(std::to_string(i)+"."+wildcard,color); + colors.emplace(std::to_string(i) + "." + wildcard, color); } } } @@ -3088,124 +3620,142 @@ std::map ViewProviderLink::getElementColors(const char int element_count = ext->getElementCountValue(); - for(const auto &sub : subs) { - if(++i >= size) + for (const auto& sub : subs) { + if (++i >= size) { break; + } int offset = 0; - if(!sub.oldName.empty() && element_count && !std::isdigit(sub.oldName[0])) { + if (!sub.oldName.empty() && element_count && !std::isdigit(sub.oldName[0])) { // For checking and expanding color override of array base - if(!subname[0]) { + if (!subname[0]) { std::ostringstream ss; ss << "0." << sub.oldName; - if(getObject()->getSubObject(ss.str().c_str())) { - for(int j=0;jgetSubObject(ss.str().c_str())) { + for (int j = 0; j < element_count; ++j) { ss.str(""); ss << j << '.' << sub.oldName; - colors.emplace(ss.str(),OverrideColorList[i]); + colors.emplace(ss.str(), OverrideColorList[i]); } continue; } - } else if (std::isdigit(subname[0])) { - const char *dot = strchr(subname,'.'); - if(dot) - offset = dot-subname+1; + } + else if (std::isdigit(subname[0])) { + const char* dot = strchr(subname, '.'); + if (dot) { + offset = dot - subname + 1; + } } } - if(isPrefix) { - if(!boost::starts_with(sub.newName,subname+offset) - && !boost::starts_with(sub.oldName,subname+offset)) + if (isPrefix) { + if (!boost::starts_with(sub.newName, subname + offset) + && !boost::starts_with(sub.oldName, subname + offset)) { continue; - }else if(sub.newName!=subname+offset && sub.oldName!=subname+offset) + } + } + else if (sub.newName != subname + offset && sub.oldName != subname + offset) { continue; + } - if(offset) - colors.emplace(std::string(subname,offset)+sub.oldName, OverrideColorList[i]); - else + if (offset) { + colors.emplace(std::string(subname, offset) + sub.oldName, OverrideColorList[i]); + } + else { colors[sub.oldName] = OverrideColorList[i]; + } } - if(!subname[0]) + if (!subname[0]) { return colors; + } bool found = true; - if(colors.empty()) { + if (colors.empty()) { found = false; - colors.emplace(subname,Base::Color()); + colors.emplace(subname, Base::Color()); } std::map ret; - for(const auto &v : colors) { - const char *pos = nullptr; - auto sobj = getObject()->resolve(v.first.c_str(),nullptr,nullptr,&pos); - if(!sobj || !pos) + for (const auto& v : colors) { + const char* pos = nullptr; + auto sobj = getObject()->resolve(v.first.c_str(), nullptr, nullptr, &pos); + if (!sobj || !pos) { continue; + } auto link = sobj->getLinkedObject(true); - if(!link || link==getObject()) + if (!link || link == getObject()) { continue; + } auto vp = Application::Instance->getViewProvider(sobj->getLinkedObject(true)); - if(!vp) + if (!vp) { continue; - for(const auto &v2 : vp->getElementColors(!pos[0]?"Face":pos)) { + } + for (const auto& v2 : vp->getElementColors(!pos[0] ? "Face" : pos)) { std::string name; - if(pos[0]) - name = v.first.substr(0,pos-v.first.c_str())+v2.first; - else + if (pos[0]) { + name = v.first.substr(0, pos - v.first.c_str()) + v2.first; + } + else { name = v.first; - ret[name] = found?v.second:v2.second; + } + ret[name] = found ? v.second : v2.second; } } return ret; } -void ViewProviderLink::setElementColors(const std::map &colorMap) { +void ViewProviderLink::setElementColors(const std::map& colorMap) +{ auto ext = getLinkExtension(); - if(!ext || ! ext->getColoredElementsProperty()) + if (!ext || !ext->getColoredElementsProperty()) { return; + } // For checking and collapsing array element color - std::map > subMap; + std::map> subMap; int element_count = ext->getElementCountValue(); std::vector subs; std::vector colors; Base::Color faceColor; bool hasFaceColor = false; - for(const auto &v : colorMap) { - if(!hasFaceColor && v.first == "Face") { + for (const auto& v : colorMap) { + if (!hasFaceColor && v.first == "Face") { hasFaceColor = true; faceColor = v.second; continue; } - if(element_count && !v.first.empty() && std::isdigit(v.first[0])) { + if (element_count && !v.first.empty() && std::isdigit(v.first[0])) { // In case of array, check if there are override of the same // sub-element for every array element. And collapse those overrides // into one without the index. - const char *dot = strchr(v.first.c_str(),'.'); - if(dot) { - subMap[dot+1][std::atoi(v.first.c_str())] = v.second; + const char* dot = strchr(v.first.c_str(), '.'); + if (dot) { + subMap[dot + 1][std::atoi(v.first.c_str())] = v.second; continue; } } subs.push_back(v.first); colors.push_back(v.second); } - for(auto &v : subMap) { - if(element_count == (int)v.second.size()) { + for (auto& v : subMap) { + if (element_count == (int)v.second.size()) { Base::Color firstColor = v.second.begin()->second; subs.push_back(v.first); colors.push_back(firstColor); - for(auto it=v.second.begin();it!=v.second.end();) { - if(it->second==firstColor) + for (auto it = v.second.begin(); it != v.second.end();) { + if (it->second == firstColor) { it = v.second.erase(it); - else + } + else { ++it; + } } } std::ostringstream ss; - for(const auto &colorInfo : v.second) { + for (const auto& colorInfo : v.second) { ss.str(""); ss << colorInfo.first << '.' << v.first; subs.push_back(ss.str()); @@ -3214,92 +3764,103 @@ void ViewProviderLink::setElementColors(const std::map } auto prop = ext->getColoredElementsProperty(); - if(subs!=prop->getSubValues() || colors!=OverrideColorList.getValues()) { - prop->setStatus(App::Property::User3,true); - prop->setValue(getObject(),subs); - prop->setStatus(App::Property::User3,false); + if (subs != prop->getSubValues() || colors != OverrideColorList.getValues()) { + prop->setStatus(App::Property::User3, true); + prop->setValue(getObject(), subs); + prop->setStatus(App::Property::User3, false); OverrideColorList.setValues(colors); } - if(hasFaceColor) { + if (hasFaceColor) { auto mat = ShapeMaterial.getValue(); mat.diffuseColor = faceColor; mat.transparency = faceColor.transparency(); - ShapeMaterial.setStatus(App::Property::User3,true); + ShapeMaterial.setStatus(App::Property::User3, true); ShapeMaterial.setValue(mat); - ShapeMaterial.setStatus(App::Property::User3,false); + ShapeMaterial.setStatus(App::Property::User3, false); } OverrideMaterial.setValue(hasFaceColor); } -void ViewProviderLink::applyColors() { +void ViewProviderLink::applyColors() +{ auto ext = getLinkExtension(); - if(!ext || ! ext->getColoredElementsProperty()) + if (!ext || !ext->getColoredElementsProperty()) { return; + } - SoSelectionElementAction action(SoSelectionElementAction::Color,true); + SoSelectionElementAction action(SoSelectionElementAction::Color, true); // reset color and visibility first action.apply(linkView->getLinkRoot()); - std::map > colorMap; + std::map> colorMap; std::set hideList; auto colors = getElementColors(); colors.erase("Face"); - for(const auto &v : colors) { - const char *subname = v.first.c_str(); - const char *element = nullptr; - auto sobj = getObject()->resolve(subname,nullptr,nullptr,&element); - if(!sobj || !element) + for (const auto& v : colors) { + const char* subname = v.first.c_str(); + const char* element = nullptr; + auto sobj = getObject()->resolve(subname, nullptr, nullptr, &element); + if (!sobj || !element) { continue; - if(ViewProvider::hiddenMarker() == element) - hideList.emplace(subname,element-subname); - else - colorMap[std::string(subname,element-subname)][element] = v.second; + } + if (ViewProvider::hiddenMarker() == element) { + hideList.emplace(subname, element - subname); + } + else { + colorMap[std::string(subname, element - subname)][element] = v.second; + } } SoTempPath path(10); path.ref(); - for(auto &v : colorMap) { + for (auto& v : colorMap) { action.swapColors(v.second); - if(v.first.empty()) { + if (v.first.empty()) { action.apply(linkView->getLinkRoot()); continue; } - SoDetail *det=nullptr; + SoDetail* det = nullptr; path.truncate(0); - if(getDetailPath(v.first.c_str(), &path, false, det)) + if (getDetailPath(v.first.c_str(), &path, false, det)) { action.apply(&path); + } delete det; } action.setType(SoSelectionElementAction::Hide); - for(const auto &sub : hideList) { - SoDetail *det=nullptr; + for (const auto& sub : hideList) { + SoDetail* det = nullptr; path.truncate(0); - if(!sub.empty() && getDetailPath(sub.c_str(), &path, false, det)) + if (!sub.empty() && getDetailPath(sub.c_str(), &path, false, det)) { action.apply(&path); + } delete det; } path.unrefNoDelete(); } -void ViewProviderLink::setOverrideMode(const std::string &mode) { +void ViewProviderLink::setOverrideMode(const std::string& mode) +{ auto ext = getLinkExtension(); - if(!ext) + if (!ext) { return; + } auto obj = ext->getTrueLinkedObject(false); - if(obj && obj!=getObject()) { + if (obj && obj != getObject()) { auto vp = Application::Instance->getViewProvider(obj); vp->setOverrideMode(mode); } - if(childVp) + if (childVp) { childVp->setOverrideMode(mode); + } } -void ViewProviderLink::onBeforeChange(const App::Property *prop) { - if(prop == &ChildViewProvider) { - if(childVp) { +void ViewProviderLink::onBeforeChange(const App::Property* prop) +{ + if (prop == &ChildViewProvider) { + if (childVp) { childVp->beforeDelete(); - pcModeSwitch->replaceChild(1,linkView->getLinkRoot()); + pcModeSwitch->replaceChild(1, linkView->getLinkRoot()); childVpLink.reset(); childVp = nullptr; } @@ -3307,42 +3868,52 @@ void ViewProviderLink::onBeforeChange(const App::Property *prop) { inherited::onBeforeChange(prop); } -static bool isExcludedProperties(const char *name) { -#define CHECK_EXCLUDE_PROP(_name) if(strcmp(name,#_name)==0) return true; +static bool isExcludedProperties(const char* name) +{ +#define CHECK_EXCLUDE_PROP(_name) \ + if (strcmp(name, #_name) == 0) \ + return true; CHECK_EXCLUDE_PROP(Proxy); return false; } -App::Property *ViewProviderLink::getPropertyByName(const char *name) const { +App::Property* ViewProviderLink::getPropertyByName(const char* name) const +{ auto prop = inherited::getPropertyByName(name); - if(prop || isExcludedProperties(name)) + if (prop || isExcludedProperties(name)) { return prop; - if(childVp) { + } + if (childVp) { prop = childVp->getPropertyByName(name); - if(prop && !prop->testStatus(App::Property::Hidden)) + if (prop && !prop->testStatus(App::Property::Hidden)) { return prop; + } prop = nullptr; } - if(pcObject && pcObject->canLinkProperties()) { - auto linked = getLinkedViewProvider(nullptr,true); - if(linked && linked!=this) + if (pcObject && pcObject->canLinkProperties()) { + auto linked = getLinkedViewProvider(nullptr, true); + if (linked && linked != this) { prop = linked->getPropertyByName(name); + } } return prop; } -void ViewProviderLink::getPropertyMap(std::map &Map) const { +void ViewProviderLink::getPropertyMap(std::map& Map) const +{ inherited::getPropertyMap(Map); - if(!childVp) + if (!childVp) { return; - std::map childMap; + } + std::map childMap; childVp->getPropertyMap(childMap); - for(const auto &v : childMap) { + for (const auto& v : childMap) { auto ret = Map.insert(v); - if(!ret.second) { + if (!ret.second) { auto myProp = ret.first->second; - if(myProp->testStatus(App::Property::Hidden)) + if (myProp->testStatus(App::Property::Hidden)) { ret.first->second = v.second; + } } } } @@ -3357,64 +3928,79 @@ void ViewProviderLink::visitProperties(const std::function void ViewProviderLink::getPropertyList(std::vector& List) const { - std::map Map; + std::map Map; getPropertyMap(Map); - List.reserve(List.size()+Map.size()); - for(const auto &v:Map) + List.reserve(List.size() + Map.size()); + for (const auto& v : Map) { List.push_back(v.second); -} - -ViewProviderDocumentObject *ViewProviderLink::getLinkedViewProvider( - std::string *subname, bool recursive) const -{ - auto self = const_cast(this); - auto ext = getLinkExtension(); - if(!ext) - return self; - App::DocumentObject *linked = nullptr; - if(!recursive) { - linked = ext->getLink(); - const char *s = ext->getSubName(); - if(subname && s) - *subname = s; - } else - linked = ext->getTrueLinkedObject(recursive); - if(!linked) - return self; - auto res = freecad_cast( - Application::Instance->getViewProvider(linked)); - if(res) - return res; - return self; -} - -void ViewProviderLink::setTransformation(const Base::Matrix4D &rcMatrix) -{ - inherited::setTransformation(rcMatrix); - auto ext = getLinkExtension(); - if(ext) { - if (ext->getScaleVectorProperty()) - updateDataPrivate(getLinkExtension(),ext->getScaleVectorProperty()); - else - updateDataPrivate(getLinkExtension(),ext->getScaleProperty()); } } -void ViewProviderLink::setTransformation(const SbMatrix &rcMatrix) +ViewProviderDocumentObject* ViewProviderLink::getLinkedViewProvider( + std::string* subname, + bool recursive +) const +{ + auto self = const_cast(this); + auto ext = getLinkExtension(); + if (!ext) { + return self; + } + App::DocumentObject* linked = nullptr; + if (!recursive) { + linked = ext->getLink(); + const char* s = ext->getSubName(); + if (subname && s) { + *subname = s; + } + } + else { + linked = ext->getTrueLinkedObject(recursive); + } + if (!linked) { + return self; + } + auto res = freecad_cast( + Application::Instance->getViewProvider(linked) + ); + if (res) { + return res; + } + return self; +} + +void ViewProviderLink::setTransformation(const Base::Matrix4D& rcMatrix) { inherited::setTransformation(rcMatrix); auto ext = getLinkExtension(); - if(ext) { - if (ext->getScaleVectorProperty()) - updateDataPrivate(getLinkExtension(),ext->getScaleVectorProperty()); - else - updateDataPrivate(getLinkExtension(),ext->getScaleProperty()); + if (ext) { + if (ext->getScaleVectorProperty()) { + updateDataPrivate(getLinkExtension(), ext->getScaleVectorProperty()); + } + else { + updateDataPrivate(getLinkExtension(), ext->getScaleProperty()); + } + } +} + +void ViewProviderLink::setTransformation(const SbMatrix& rcMatrix) +{ + inherited::setTransformation(rcMatrix); + auto ext = getLinkExtension(); + if (ext) { + if (ext->getScaleVectorProperty()) { + updateDataPrivate(getLinkExtension(), ext->getScaleVectorProperty()); + } + else { + updateDataPrivate(getLinkExtension(), ext->getScaleProperty()); + } } } //////////////////////////////////////////////////////////////////////////////////////// -namespace Gui { +namespace Gui +{ PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderLinkPython, Gui::ViewProviderLink) template class GuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderLink.h b/src/Gui/ViewProviderLink.h index 4af944e3b5..780cd4e5d9 100644 --- a/src/Gui/ViewProviderLink.h +++ b/src/Gui/ViewProviderLink.h @@ -41,29 +41,38 @@ class SoDragger; class SoMaterialBinding; class SoPickStyle; -namespace Gui { +namespace Gui +{ class LinkInfo; using LinkInfoPtr = boost::intrusive_ptr; #if defined(_MSC_VER) // forward declaration to please MSVC -void intrusive_ptr_add_ref(Gui::LinkInfo *px); -void intrusive_ptr_release(Gui::LinkInfo *px); +void intrusive_ptr_add_ref(Gui::LinkInfo* px); +void intrusive_ptr_release(Gui::LinkInfo* px); #endif -class GuiExport ViewProviderLinkObserver: public ViewProviderExtension { +class GuiExport ViewProviderLinkObserver: public ViewProviderExtension +{ EXTENSION_TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: ViewProviderLinkObserver(); ~ViewProviderLinkObserver() override; - void extensionReattach(App::DocumentObject *) override; + void extensionReattach(App::DocumentObject*) override; void extensionBeforeDelete() override; - void extensionOnChanged(const App::Property *) override; + void extensionOnChanged(const App::Property*) override; void extensionUpdateData(const App::Property*) override; void extensionFinishRestoring() override; - bool extensionCanDragObject(App::DocumentObject*) const override { return false; } - bool extensionCanDropObject(App::DocumentObject*) const override { return false; } + bool extensionCanDragObject(App::DocumentObject*) const override + { + return false; + } + bool extensionCanDropObject(App::DocumentObject*) const override + { + return false; + } void extensionModeSwitchChange() override; bool isLinkVisible() const; @@ -72,100 +81,120 @@ public: LinkInfoPtr linkInfo; }; -class GuiExport LinkOwner { +class GuiExport LinkOwner +{ public: - virtual void unlink(LinkInfoPtr) {} - virtual void onLinkedIconChange(LinkInfoPtr) {} - virtual void onLinkedUpdateData(LinkInfoPtr,const App::Property *) {} + virtual void unlink(LinkInfoPtr) + {} + virtual void onLinkedIconChange(LinkInfoPtr) + {} + virtual void onLinkedUpdateData(LinkInfoPtr, const App::Property*) + {} + protected: virtual ~LinkOwner() = default; }; -class GuiExport LinkView : public Base::BaseClass, public LinkOwner { +class GuiExport LinkView: public Base::BaseClass, public LinkOwner +{ TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: +public: LinkView(); ~LinkView() override; - LinkView &operator=(const LinkView&) = delete; + LinkView& operator=(const LinkView&) = delete; LinkView(const LinkView&) = delete; - PyObject *getPyObject() override; + PyObject* getPyObject() override; void unlink(LinkInfoPtr) override; void onLinkedIconChange(LinkInfoPtr) override; - void onLinkedUpdateData(LinkInfoPtr, const App::Property *) override; + void onLinkedUpdateData(LinkInfoPtr, const App::Property*) override; bool isLinked() const; - SoFCSelectionRoot *getLinkRoot() const {return pcLinkRoot;} + SoFCSelectionRoot* getLinkRoot() const + { + return pcLinkRoot; + } QIcon getLinkedIcon(QPixmap overlay) const; void updateLink(); - void setLink(App::DocumentObject *obj, - const std::vector &subs = std::vector()); + void setLink( + App::DocumentObject* obj, + const std::vector& subs = std::vector() + ); - void setLinkViewObject(ViewProviderDocumentObject *vpd, - const std::vector &subs = std::vector()); + void setLinkViewObject( + ViewProviderDocumentObject* vpd, + const std::vector& subs = std::vector() + ); std::vector getChildren() const; - void setMaterial(int index, const App::Material *material); - void setDrawStyle(int linePattern, double lineWidth=0, double pointSize=0); - void setTransform(int index, const Base::Matrix4D &mat); + void setMaterial(int index, const App::Material* material); + void setDrawStyle(int linePattern, double lineWidth = 0, double pointSize = 0); + void setTransform(int index, const Base::Matrix4D& mat); void renderDoubleSide(bool); void setSize(int size); - int getSize() const { return nodeArray.size(); } + int getSize() const + { + return nodeArray.size(); + } - static void setTransform(SoTransform *pcTransform, const Base::Matrix4D &mat); + static void setTransform(SoTransform* pcTransform, const Base::Matrix4D& mat); - enum SnapshotType { - //three type of snapshot to override linked root node: + enum SnapshotType + { + // three type of snapshot to override linked root node: - //override transform and visibility + // override transform and visibility SnapshotTransform = 0, - //override visibility + // override visibility SnapshotVisible = 1, - //override none (for child objects of a container) + // override none (for child objects of a container) SnapshotChild = 2, SnapshotMax, - //special type for sub object linking + // special type for sub object linking SnapshotContainer = -1, // sub object linking with transform override SnapshotContainerTransform = -2, }; - void setNodeType(SnapshotType type, bool sublink=true); + void setNodeType(SnapshotType type, bool sublink = true); - void setChildren(const std::vector &children, - const boost::dynamic_bitset<> &vis, SnapshotType type=SnapshotVisible); + void setChildren( + const std::vector& children, + const boost::dynamic_bitset<>& vis, + SnapshotType type = SnapshotVisible + ); - bool linkGetDetailPath(const char *, SoFullPath *, SoDetail *&) const; - bool linkGetElementPicked(const SoPickedPoint *, std::string &) const; + bool linkGetDetailPath(const char*, SoFullPath*, SoDetail*&) const; + bool linkGetElementPicked(const SoPickedPoint*, std::string&) const; void setElementVisible(int index, bool visible); bool isElementVisible(int index) const; - ViewProviderDocumentObject *getOwner() const; - void setOwner(ViewProviderDocumentObject *vpd); + ViewProviderDocumentObject* getOwner() const; + void setOwner(ViewProviderDocumentObject* vpd); bool hasSubs() const; std::vector getSubNames() const; - ViewProviderDocumentObject *getLinkedView() const; + ViewProviderDocumentObject* getLinkedView() const; - Base::BoundBox3d getBoundBox(ViewProviderDocumentObject *vpd=nullptr) const; + Base::BoundBox3d getBoundBox(ViewProviderDocumentObject* vpd = nullptr) const; void setInvalid(); protected: - void replaceLinkedRoot(SoSeparator *); + void replaceLinkedRoot(SoSeparator*); void resetRoot(); - bool getGroupHierarchy(int index, SoFullPath *path) const; + bool getGroupHierarchy(int index, SoFullPath* path) const; protected: LinkInfoPtr linkOwner; @@ -173,24 +202,24 @@ protected: CoinPtr pcLinkRoot; CoinPtr pcTransform; CoinPtr pcLinkedRoot; - CoinPtr pcDrawStyle; // for override line width and point size - CoinPtr pcShapeHints; // for override double side rendering for mirror + CoinPtr pcDrawStyle; // for override line width and point size + CoinPtr pcShapeHints; // for override double side rendering for mirror SnapshotType nodeType; SnapshotType childType; - bool autoSubLink; //auto delegate to linked sub object if there is only one sub object + bool autoSubLink; // auto delegate to linked sub object if there is only one sub object class SubInfo; friend class SubInfo; - std::map > subInfo; + std::map> subInfo; class Element; - std::vector > nodeArray; - std::unordered_map nodeMap; + std::vector> nodeArray; + std::unordered_map nodeMap; Py::Object PythonObject; }; -class GuiExport ViewProviderLink : public ViewProviderDragger +class GuiExport ViewProviderLink: public ViewProviderDragger { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderLink); using inherited = ViewProviderDragger; @@ -210,18 +239,21 @@ public: ViewProviderLink(); ~ViewProviderLink() override; - void attach(App::DocumentObject *pcObj) override; - void reattach(App::DocumentObject *pcObj) override; + void attach(App::DocumentObject* pcObj) override; + void reattach(App::DocumentObject* pcObj) override; bool isSelectable() const override; - bool useNewSelectionModel() const override {return true;} + bool useNewSelectionModel() const override + { + return true; + } void updateData(const App::Property*) override; void onChanged(const App::Property* prop) override; std::vector claimChildren() const override; - bool getElementPicked(const SoPickedPoint *, std::string &) const override; - bool getDetailPath(const char *, SoFullPath *, bool, SoDetail *&) const override; + bool getElementPicked(const SoPickedPoint*, std::string&) const override; + bool getDetailPath(const char*, SoFullPath*, bool, SoDetail*&) const override; void finishRestoring() override; @@ -232,12 +264,20 @@ public: void dragObject(App::DocumentObject*) override; bool canDropObjects() const override; bool canDragAndDropObject(App::DocumentObject*) const override; - bool canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, - const char *subname, const std::vector &subElements) const override; - std::string dropObjectEx(App::DocumentObject*, App::DocumentObject*, - const char *subname, const std::vector &subElements) override; + bool canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& subElements + ) const override; + std::string dropObjectEx( + App::DocumentObject*, + App::DocumentObject*, + const char* subname, + const std::vector& subElements + ) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; bool canDelete(App::DocumentObject* obj) const override; std::vector getDisplayModes() const override; @@ -246,62 +286,67 @@ public: virtual QPixmap getOverlayPixmap() const; - ViewProvider *startEditing(int ModNum) override; + ViewProvider* startEditing(int ModNum) override; bool doubleClicked() override; - PyObject *getPyObject() override; - PyObject *getPyLinkView(); + PyObject* getPyObject() override; + PyObject* getPyLinkView(); - static void updateLinks(ViewProvider *vp); + static void updateLinks(ViewProvider* vp); - std::map getElementColors(const char *subname=nullptr) const override; - void setElementColors(const std::map &colors) override; + std::map getElementColors(const char* subname = nullptr) const override; + void setElementColors(const std::map& colors) override; - void setOverrideMode(const std::string &mode) override; + void setOverrideMode(const std::string& mode) override; void onBeforeChange(const App::Property*) override; - ViewProviderDocumentObject *getChildViewProvider() const { + ViewProviderDocumentObject* getChildViewProvider() const + { return childVp; } - App::Property *getPropertyByName(const char* name) const override; - void getPropertyMap(std::map &Map) const override; + App::Property* getPropertyByName(const char* name) const override; + void getPropertyMap(std::map& Map) const override; /// See PropertyContainer::visitProperties for semantics void visitProperties(const std::function& visitor) const override; void getPropertyList(std::vector& List) const override; - ViewProviderDocumentObject *getLinkedViewProvider( - std::string *subname=nullptr, bool recursive=false) const override; + ViewProviderDocumentObject* getLinkedViewProvider( + std::string* subname = nullptr, + bool recursive = false + ) const override; - bool allowOverride(const App::DocumentObject &) const override { + bool allowOverride(const App::DocumentObject&) const override + { return true; } - void setTransformation(const Base::Matrix4D &rcMatrix) override; - void setTransformation(const SbMatrix &rcMatrix) override; + void setTransformation(const Base::Matrix4D& rcMatrix) override; + void setTransformation(const SbMatrix& rcMatrix) override; protected: bool setEdit(int ModNum) override; void setEditViewer(View3DInventorViewer*, int ModNum) override; void unsetEditViewer(View3DInventorViewer*) override; - bool linkEdit(const App::LinkBaseExtension *ext=nullptr) const; - void _setupContextMenu(App::LinkBaseExtension *ext, QMenu*, QObject*, const char*); + bool linkEdit(const App::LinkBaseExtension* ext = nullptr) const; + void _setupContextMenu(App::LinkBaseExtension* ext, QMenu*, QObject*, const char*); - enum LinkType { + enum LinkType + { LinkTypeNone, LinkTypeNormal, LinkTypeSubs, }; - bool hasElements(const App::LinkBaseExtension *ext = nullptr) const; - bool isGroup(const App::LinkBaseExtension *ext=nullptr, bool plainGroup=false) const; - const App::LinkBaseExtension *getLinkExtension() const; - App::LinkBaseExtension *getLinkExtension(); + bool hasElements(const App::LinkBaseExtension* ext = nullptr) const; + bool isGroup(const App::LinkBaseExtension* ext = nullptr, bool plainGroup = false) const; + const App::LinkBaseExtension* getLinkExtension() const; + App::LinkBaseExtension* getLinkExtension(); - void updateDataPrivate(App::LinkBaseExtension *ext, const App::Property*); - void updateElementList(App::LinkBaseExtension *ext); + void updateDataPrivate(App::LinkBaseExtension* ext, const App::Property*); + void updateElementList(App::LinkBaseExtension* ext); - bool setLinkType(App::LinkBaseExtension *ext); + bool setLinkType(App::LinkBaseExtension* ext); void onChangeIcon() const; std::vector claimChildrenPrivate() const; @@ -309,25 +354,26 @@ protected: void applyMaterial(); void applyColors(); - void checkIcon(const App::LinkBaseExtension *ext=nullptr); + void checkIcon(const App::LinkBaseExtension* ext = nullptr); - ViewProvider *getLinkedView(bool real,const App::LinkBaseExtension *ext=nullptr) const; + ViewProvider* getLinkedView(bool real, const App::LinkBaseExtension* ext = nullptr) const; bool initDraggingPlacement(); bool callDraggerProxy(const char* fname); private: - static void dragStartCallback(void * data, SoDragger * d); - static void dragFinishCallback(void * data, SoDragger * d); - static void dragMotionCallback(void * data, SoDragger * d); + static void dragStartCallback(void* data, SoDragger* d); + static void dragFinishCallback(void* data, SoDragger* d); + static void dragMotionCallback(void* data, SoDragger* d); protected: - LinkView *linkView; + LinkView* linkView; LinkType linkType; bool hasSubName; bool hasSubElement; - struct DraggerContext{ + struct DraggerContext + { Base::Matrix4D preTransform; Base::Placement initialPlacement; Base::Matrix4D mat; @@ -335,7 +381,7 @@ protected: bool cmdPending; }; std::unique_ptr dragCtx; - ViewProviderDocumentObject *childVp; + ViewProviderDocumentObject* childVp; LinkInfoPtr childVpLink; mutable qint64 overlayCacheKey; @@ -345,7 +391,7 @@ private: using ViewProviderLinkPython = ViewProviderFeaturePythonT; -} //namespace Gui +} // namespace Gui -#endif // SRC_GUI_VIEWPROVIDER_LINK_H_ +#endif // SRC_GUI_VIEWPROVIDER_LINK_H_ diff --git a/src/Gui/ViewProviderLink.pyi b/src/Gui/ViewProviderLink.pyi index b9a3ebf84a..2e75516a03 100644 --- a/src/Gui/ViewProviderLink.pyi +++ b/src/Gui/ViewProviderLink.pyi @@ -1,7 +1,6 @@ from ViewProviderDocumentObject import ViewProviderDocumentObject from typing import Any, Final - class ViewProviderLink(ViewProviderDocumentObject): """ This is the ViewProviderLink class diff --git a/src/Gui/ViewProviderLinkPyImp.cpp b/src/Gui/ViewProviderLinkPyImp.cpp index 3fd86cb3b9..44b51d460f 100644 --- a/src/Gui/ViewProviderLinkPyImp.cpp +++ b/src/Gui/ViewProviderLinkPyImp.cpp @@ -21,8 +21,7 @@ ****************************************************************************/ - -# include +#include #include @@ -43,23 +42,29 @@ std::string ViewProviderLinkPy::representation() const return str.str(); } -Py::Object ViewProviderLinkPy::getDraggingPlacement() const { - return Py::asObject(new Base::PlacementPy(new Base::Placement( - getViewProviderLinkPtr()->getDraggerPlacement()))); +Py::Object ViewProviderLinkPy::getDraggingPlacement() const +{ + return Py::asObject( + new Base::PlacementPy(new Base::Placement(getViewProviderLinkPtr()->getDraggerPlacement())) + ); } -void ViewProviderLinkPy::setDraggingPlacement(Py::Object arg) { - if(!PyObject_TypeCheck(arg.ptr(),&Base::PlacementPy::Type)) +void ViewProviderLinkPy::setDraggingPlacement(Py::Object arg) +{ + if (!PyObject_TypeCheck(arg.ptr(), &Base::PlacementPy::Type)) { throw Py::TypeError("expects a placement"); + } getViewProviderLinkPtr()->setDraggerPlacement( - *static_cast(arg.ptr())->getPlacementPtr()); + *static_cast(arg.ptr())->getPlacementPtr() + ); } -Py::Object ViewProviderLinkPy::getLinkView() const { - return Py::Object(getViewProviderLinkPtr()->getPyLinkView(),true); +Py::Object ViewProviderLinkPy::getLinkView() const +{ + return Py::Object(getViewProviderLinkPtr()->getPyLinkView(), true); } -PyObject *ViewProviderLinkPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ViewProviderLinkPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Gui/ViewProviderMaterialObject.cpp b/src/Gui/ViewProviderMaterialObject.cpp index ed3501d344..7d3c4fe717 100644 --- a/src/Gui/ViewProviderMaterialObject.cpp +++ b/src/Gui/ViewProviderMaterialObject.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include "ViewProviderMaterialObject.h" @@ -56,21 +55,28 @@ bool ViewProviderMaterialObject::doubleClicked() QIcon ViewProviderMaterialObject::getIcon() const { QIcon groupIcon; - groupIcon.addPixmap(QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon), - QIcon::Normal, QIcon::Off); - groupIcon.addPixmap(QApplication::style()->standardPixmap(QStyle::SP_DirOpenIcon), - QIcon::Normal, QIcon::On); + groupIcon.addPixmap( + QApplication::style()->standardPixmap(QStyle::SP_DirClosedIcon), + QIcon::Normal, + QIcon::Off + ); + groupIcon.addPixmap( + QApplication::style()->standardPixmap(QStyle::SP_DirOpenIcon), + QIcon::Normal, + QIcon::On + ); return groupIcon; } // Python feature ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderMaterialObjectPython, Gui::ViewProviderMaterialObject) /// @endcond // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderMaterialObject.h b/src/Gui/ViewProviderMaterialObject.h index e1cb6b0814..562d1e01f8 100644 --- a/src/Gui/ViewProviderMaterialObject.h +++ b/src/Gui/ViewProviderMaterialObject.h @@ -28,9 +28,10 @@ #include "ViewProviderDocumentObject.h" #include "ViewProviderFeaturePython.h" -namespace Gui { +namespace Gui +{ -class GuiExport ViewProviderMaterialObject : public ViewProviderDocumentObject +class GuiExport ViewProviderMaterialObject: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderMaterialObject); @@ -45,13 +46,14 @@ public: bool doubleClicked() override; // shows solid in the tree - bool isShow() const override{return true;} - + bool isShow() const override + { + return true; + } }; using ViewProviderMaterialObjectPython = ViewProviderFeaturePythonT; -} // namespace Gui - -#endif // GUI_ViewProviderMaterialObject_H +} // namespace Gui +#endif // GUI_ViewProviderMaterialObject_H diff --git a/src/Gui/ViewProviderOriginGroup.cpp b/src/Gui/ViewProviderOriginGroup.cpp index 77fa94bcde..56a21e5d16 100644 --- a/src/Gui/ViewProviderOriginGroup.cpp +++ b/src/Gui/ViewProviderOriginGroup.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include "ViewProviderOriginGroup.h" @@ -30,9 +29,9 @@ using namespace Gui; PROPERTY_SOURCE_WITH_EXTENSIONS(Gui::ViewProviderOriginGroup, Gui::ViewProviderDocumentObject) -ViewProviderOriginGroup::ViewProviderOriginGroup () +ViewProviderOriginGroup::ViewProviderOriginGroup() { initExtension(this); } -ViewProviderOriginGroup::~ViewProviderOriginGroup () = default; +ViewProviderOriginGroup::~ViewProviderOriginGroup() = default; diff --git a/src/Gui/ViewProviderOriginGroup.h b/src/Gui/ViewProviderOriginGroup.h index d10f93f688..f02ed2badc 100644 --- a/src/Gui/ViewProviderOriginGroup.h +++ b/src/Gui/ViewProviderOriginGroup.h @@ -25,18 +25,20 @@ #include "ViewProviderOriginGroupExtension.h" -namespace Gui { +namespace Gui +{ class GuiExport ViewProviderOriginGroup: public ViewProviderDocumentObject, public ViewProviderOriginGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Gui::ViewProviderOriginGroup); + public: - ViewProviderOriginGroup (); - ~ViewProviderOriginGroup () override; + ViewProviderOriginGroup(); + ~ViewProviderOriginGroup() override; }; -} /* Gui */ +} // namespace Gui #endif /* end of include guard: VIEWPROVIDERORIGINGROUP_H */ diff --git a/src/Gui/ViewProviderOriginGroupExtension.cpp b/src/Gui/ViewProviderOriginGroupExtension.cpp index e966292ef4..74c2674853 100644 --- a/src/Gui/ViewProviderOriginGroupExtension.cpp +++ b/src/Gui/ViewProviderOriginGroupExtension.cpp @@ -22,7 +22,6 @@ ***************************************************************************/ - #include #include @@ -53,43 +52,51 @@ ViewProviderOriginGroupExtension::ViewProviderOriginGroupExtension() } ViewProviderOriginGroupExtension::~ViewProviderOriginGroupExtension() -{ -} +{} -std::vector ViewProviderOriginGroupExtension::constructChildren ( - const std::vector &children ) const +std::vector ViewProviderOriginGroupExtension::constructChildren( + const std::vector& children +) const { auto* obj = getExtendedViewProvider()->getObject(); auto* group = obj ? obj->getExtensionByType() : nullptr; - if(!group) + if (!group) { return children; + } - App::DocumentObject *originObj = group->Origin.getValue(); + App::DocumentObject* originObj = group->Origin.getValue(); // Origin must be first if (originObj) { std::vector rv; - rv.push_back (originObj); - std::copy (children.begin(), children.end(), std::back_inserter (rv)); + rv.push_back(originObj); + std::copy(children.begin(), children.end(), std::back_inserter(rv)); return rv; - } else { // Generally shouldn't happen but must be handled in case origin is lost + } + else { // Generally shouldn't happen but must be handled in case origin is lost return children; } } -std::vector ViewProviderOriginGroupExtension::extensionClaimChildren () const { - return constructChildren ( ViewProviderGeoFeatureGroupExtension::extensionClaimChildren () ); +std::vector ViewProviderOriginGroupExtension::extensionClaimChildren() const +{ + return constructChildren(ViewProviderGeoFeatureGroupExtension::extensionClaimChildren()); } -std::vector ViewProviderOriginGroupExtension::extensionClaimChildren3D () const { - return constructChildren ( ViewProviderGeoFeatureGroupExtension::extensionClaimChildren3D () ); +std::vector ViewProviderOriginGroupExtension::extensionClaimChildren3D() const +{ + return constructChildren(ViewProviderGeoFeatureGroupExtension::extensionClaimChildren3D()); } -namespace Gui { -EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderOriginGroupExtensionPython, Gui::ViewProviderOriginGroupExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + Gui::ViewProviderOriginGroupExtensionPython, + Gui::ViewProviderOriginGroupExtension +) // explicit template instantiation template class GuiExport ViewProviderExtensionPythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderOriginGroupExtension.h b/src/Gui/ViewProviderOriginGroupExtension.h index 09571ad323..74d0d89a9b 100644 --- a/src/Gui/ViewProviderOriginGroupExtension.h +++ b/src/Gui/ViewProviderOriginGroupExtension.h @@ -30,7 +30,7 @@ namespace Gui { -class GuiExport ViewProviderOriginGroupExtension : public ViewProviderGeoFeatureGroupExtension +class GuiExport ViewProviderOriginGroupExtension: public ViewProviderGeoFeatureGroupExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderOriginGroupExtension); @@ -39,16 +39,18 @@ public: ViewProviderOriginGroupExtension(); ~ViewProviderOriginGroupExtension() override; - std::vector extensionClaimChildren()const override; - std::vector extensionClaimChildren3D()const override; + std::vector extensionClaimChildren() const override; + std::vector extensionClaimChildren3D() const override; private: - std::vector constructChildren ( - const std::vector &children ) const; + std::vector constructChildren( + const std::vector& children + ) const; }; -using ViewProviderOriginGroupExtensionPython = ViewProviderExtensionPythonT; +using ViewProviderOriginGroupExtensionPython + = ViewProviderExtensionPythonT; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDERORIGINGROUPEXTENSION_H +#endif // GUI_VIEWPROVIDERORIGINGROUPEXTENSION_H diff --git a/src/Gui/ViewProviderPart.cpp b/src/Gui/ViewProviderPart.cpp index 0a5ba20177..8dff54813f 100644 --- a/src/Gui/ViewProviderPart.cpp +++ b/src/Gui/ViewProviderPart.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -61,7 +60,8 @@ ViewProviderPart::~ViewProviderPart() = default; * Whenever a property of the group gets changed then the same property of all * associated view providers of the objects of the object group get changed as well. */ -void ViewProviderPart::onChanged(const App::Property* prop) { +void ViewProviderPart::onChanged(const App::Property* prop) +{ ViewProviderDragger::onChanged(prop); } @@ -72,9 +72,7 @@ void ViewProviderPart::setupContextMenu(QMenu* menu, QObject* receiver, const ch QAction* act = menu->addAction(QObject::tr("Active Object")); act->setCheckable(true); act->setChecked(isActivePart()); - func->trigger(act, [this](){ - this->toggleActivePart(); - }); + func->trigger(act, [this]() { this->toggleActivePart(); }); ViewProviderDragger::setupContextMenu(menu, receiver, member); } @@ -83,36 +81,45 @@ bool ViewProviderPart::isActivePart() { App::DocumentObject* activePart = nullptr; auto activeDoc = Gui::Application::Instance->activeDocument(); - if(!activeDoc) + if (!activeDoc) { activeDoc = getDocument(); + } auto activeView = activeDoc->setActiveView(this); - if(!activeView) + if (!activeView) { return false; + } - activePart = activeView->getActiveObject (PARTKEY); + activePart = activeView->getActiveObject(PARTKEY); - if (activePart == this->getObject()){ + if (activePart == this->getObject()) { return true; - } else { + } + else { return false; } } void ViewProviderPart::toggleActivePart() { - //make the part the active one - if (isActivePart()){ - //active part double-clicked. Deactivate. - Gui::Command::doCommand(Gui::Command::Gui, - "Gui.ActiveDocument.ActiveView.setActiveObject('%s', None)", - PARTKEY); - } else { - //set new active part - Gui::Command::doCommand(Gui::Command::Gui, - "Gui.ActiveDocument.ActiveView.setActiveObject('%s', App.getDocument('%s').getObject('%s'))", - PARTKEY, - this->getObject()->getDocument()->getName(), - this->getObject()->getNameInDocument()); + // make the part the active one + if (isActivePart()) { + // active part double-clicked. Deactivate. + Gui::Command::doCommand( + Gui::Command::Gui, + "Gui.ActiveDocument.ActiveView.setActiveObject('%s', None)", + PARTKEY + ); + } + else { + // set new active part + Gui::Command::doCommand( + Gui::Command::Gui, + "Gui.ActiveDocument.ActiveView.setActiveObject('%s', " + "App.getDocument('%s').getObject('%s'))", + PARTKEY, + this->getObject()->getDocument()->getName(), + this->getObject()->getNameInDocument() + ); } } @@ -129,19 +136,22 @@ QIcon ViewProviderPart::getIcon() const // the normal case for Std_Part const char* pixmap = sPixmap; // if it's flagged as an Assembly in its Type, it gets another icon - if (part->Type.getStrValue() == "Assembly") { pixmap = aPixmap; } + if (part->Type.getStrValue() == "Assembly") { + pixmap = aPixmap; + } - return mergeGreyableOverlayIcons (Gui::BitmapFactory().pixmap(pixmap)); + return mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(pixmap)); } // Python feature ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderPartPython, Gui::ViewProviderPart) /// @endcond // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Gui/ViewProviderPart.h b/src/Gui/ViewProviderPart.h index c75e355191..4098fcae22 100644 --- a/src/Gui/ViewProviderPart.h +++ b/src/Gui/ViewProviderPart.h @@ -28,10 +28,10 @@ #include "ViewProviderFeaturePython.h" -namespace Gui { +namespace Gui +{ -class GuiExport ViewProviderPart : public ViewProviderDragger, - public ViewProviderOriginGroupExtension +class GuiExport ViewProviderPart: public ViewProviderDragger, public ViewProviderOriginGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Gui::ViewProviderPart); @@ -51,19 +51,20 @@ public: QIcon getIcon() const override; /* Check whether the object accept reordering of its children during drop.*/ - bool acceptReorderingObjects() const override { return true; }; + bool acceptReorderingObjects() const override + { + return true; + }; protected: /// get called by the container whenever a property has been changed void onChanged(const App::Property* prop) override; /// a second icon for the Assembly type const char* aPixmap; - }; using ViewProviderPartPython = ViewProviderFeaturePythonT; -} // namespace Gui - -#endif // GUI_VIEWPROVIDER_ViewProviderPart_H +} // namespace Gui +#endif // GUI_VIEWPROVIDER_ViewProviderPart_H diff --git a/src/Gui/ViewProviderPlacement.cpp b/src/Gui/ViewProviderPlacement.cpp index c544a8f39c..30a2ece28e 100644 --- a/src/Gui/ViewProviderPlacement.cpp +++ b/src/Gui/ViewProviderPlacement.cpp @@ -21,10 +21,9 @@ ***************************************************************************/ - -# include -# include -# include +#include +#include +#include #include @@ -43,8 +42,9 @@ ViewProviderPlacement::ViewProviderPlacement() // Change root node to SoFCSelectionRoot because we share the same // AxisOrigin node for all instances of Placement auto newRoot = new SoFCSelectionRoot(true); - for(int i=0;igetNumChildren();++i) + for (int i = 0; i < pcRoot->getNumChildren(); ++i) { newRoot->addChild(pcRoot->getChild(i)); + } pcRoot->unref(); pcRoot = newRoot; pcRoot->ref(); @@ -57,7 +57,7 @@ ViewProviderPlacement::~ViewProviderPlacement() = default; void ViewProviderPlacement::onChanged(const App::Property* prop) { - ViewProviderGeometryObject::onChanged(prop); + ViewProviderGeometryObject::onChanged(prop); } std::vector ViewProviderPlacement::getDisplayModes() const @@ -70,8 +70,9 @@ std::vector ViewProviderPlacement::getDisplayModes() const void ViewProviderPlacement::setDisplayMode(const char* ModeName) { - if (strcmp(ModeName, "Base") == 0) + if (strcmp(ModeName, "Base") == 0) { setDisplayMaskMode("Base"); + } ViewProviderGeometryObject::setDisplayMode(ModeName); } @@ -80,9 +81,9 @@ static std::unique_ptr Axis; void ViewProviderPlacement::attach(App::DocumentObject* pcObject) { ViewProviderGeometryObject::attach(pcObject); - if(!Axis) { + if (!Axis) { Axis = std::make_unique(); - std::map labels; + std::map labels; labels["O"] = "Origin"; labels["X"] = "X-Axis"; labels["Y"] = "Y-Axis"; @@ -100,23 +101,30 @@ void ViewProviderPlacement::updateData(const App::Property* prop) ViewProviderGeometryObject::updateData(prop); } -bool ViewProviderPlacement::getElementPicked(const SoPickedPoint *pp, std::string &subname) const { - if(!Axis) +bool ViewProviderPlacement::getElementPicked(const SoPickedPoint* pp, std::string& subname) const +{ + if (!Axis) { return false; - return Axis->getElementPicked(pp,subname); + } + return Axis->getElementPicked(pp, subname); } bool ViewProviderPlacement::getDetailPath( - const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const + const char* subname, + SoFullPath* pPath, + bool append, + SoDetail*& det +) const { - if(!Axis) + if (!Axis) { return false; + } int length = pPath->getLength(); - if(append) { + if (append) { pPath->append(pcRoot); pPath->append(pcModeSwitch); } - if(!Axis->getDetailPath(subname,pPath,det)) { + if (!Axis->getDetailPath(subname, pPath, det)) { pPath->truncate(length); return false; } @@ -131,12 +139,12 @@ bool ViewProviderPlacement::isSelectable() const // Python feature ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderPlacementPython, Gui::ViewProviderPlacement) /// @endcond // explicit template instantiation template class GuiExport ViewProviderFeaturePythonT; -} - +} // namespace Gui diff --git a/src/Gui/ViewProviderPlacement.h b/src/Gui/ViewProviderPlacement.h index 0c8e83af3d..a94ef3ab5c 100644 --- a/src/Gui/ViewProviderPlacement.h +++ b/src/Gui/ViewProviderPlacement.h @@ -40,7 +40,7 @@ class SoMaterial; namespace Gui { -class GuiExport ViewProviderPlacement : public ViewProviderGeometryObject +class GuiExport ViewProviderPlacement: public ViewProviderGeometryObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderPlacement); @@ -49,27 +49,29 @@ public: ViewProviderPlacement(); ~ViewProviderPlacement() override; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void updateData(const App::Property*) override; std::vector getDisplayModes() const override; void setDisplayMode(const char* ModeName) override; /// indicates if the ViewProvider use the new Selection model - bool useNewSelectionModel() const override {return true;} + bool useNewSelectionModel() const override + { + return true; + } /// indicates if the ViewProvider can be selected bool isSelectable() const override; - bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const override; - bool getDetailPath(const char *, SoFullPath *, bool, SoDetail *&) const override; + bool getElementPicked(const SoPickedPoint* pp, std::string& subname) const override; + bool getDetailPath(const char*, SoFullPath*, bool, SoDetail*&) const override; protected: void onChanged(const App::Property* prop) override; - }; using ViewProviderPlacementPython = ViewProviderFeaturePythonT; -} //namespace Gui +} // namespace Gui -#endif // GUI_ViewProviderPlacement_H +#endif // GUI_ViewProviderPlacement_H diff --git a/src/Gui/ViewProviderPlane.cpp b/src/Gui/ViewProviderPlane.cpp index a211952364..b14e2dd0e2 100644 --- a/src/Gui/ViewProviderPlane.cpp +++ b/src/Gui/ViewProviderPlane.cpp @@ -21,17 +21,17 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -51,7 +51,8 @@ using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderDatum) -ViewProviderPlane::ViewProviderPlane() : SelectionObserver(true) +ViewProviderPlane::ViewProviderPlane() + : SelectionObserver(true) { sPixmap = "Std_Plane"; lineThickness = 1.0; @@ -61,7 +62,8 @@ ViewProviderPlane::ViewProviderPlane() : SelectionObserver(true) ViewProviderPlane::~ViewProviderPlane() = default; -void ViewProviderPlane::attach(App::DocumentObject * obj) { +void ViewProviderPlane::attach(App::DocumentObject* obj) +{ ViewProviderDatum::attach(obj); std::string role = getRole(); @@ -72,7 +74,7 @@ void ViewProviderPlane::attach(App::DocumentObject * obj) { // Can't use transparency because of https://github.com/FreeCAD/FreeCAD/issues/18395 // When this issue is fixed then we can use the below and remove the material here // and faceSeparator... - //ShapeAppearance.setTransparency(0.8); + // ShapeAppearance.setTransparency(0.8); auto material = new SoMaterial(); material->transparency.setValue(0.85f); @@ -94,7 +96,7 @@ void ViewProviderPlane::attach(App::DocumentObject * obj) { auto lineSeparator = new SoSeparator(); auto pLines = new SoIndexedLineSet(); - static const int32_t lines[6] = { 0, 1, 2, 3, 0, -1 }; + static const int32_t lines[6] = {0, 1, 2, 3, 0, -1}; pLines->coordIndex.setNum(6); pLines->coordIndex.setValues(0, 6, lines); @@ -159,7 +161,8 @@ void ViewProviderPlane::setLabelVisibility(bool val) void ViewProviderPlane::onSelectionChanged(const SelectionChanges&) { isSelected = Gui::Selection().isSelected(getObject()); - isHovered = Gui::Selection().getPreselection().Object.getSubObject() == getObject() || Gui::Selection().getPreselection().Object.getObject() == getObject(); + isHovered = Gui::Selection().getPreselection().Object.getSubObject() == getObject() + || Gui::Selection().getPreselection().Object.getObject() == getObject(); updatePlaneSize(); } @@ -184,14 +187,15 @@ void ViewProviderPlane::updatePlaneSize() verts[1] = SbVec3f(size, offset, 0); verts[2] = SbVec3f(offset, offset, 0); verts[3] = SbVec3f(offset, size, 0); - } else { + } + else { verts[0] = SbVec3f(size, size, 0); verts[1] = SbVec3f(size, -size, 0); verts[2] = SbVec3f(-size, -size, 0); verts[3] = SbVec3f(-size, size, 0); } - pTextTranslation->translation.setValue(verts[0] / 2 - SbVec3f(2, 6, 0)); // NOLINT + pTextTranslation->translation.setValue(verts[0] / 2 - SbVec3f(2, 6, 0)); // NOLINT pCoords->point.setNum(4); pCoords->point.setValues(0, 4, verts); } @@ -200,13 +204,13 @@ unsigned long ViewProviderPlane::getColor(const std::string& role) const { auto planesRoles = App::LocalCoordinateSystem::PlaneRoles; if (role == planesRoles[0]) { - return ViewParams::instance()->getAxisZColor(); // XY-plane + return ViewParams::instance()->getAxisZColor(); // XY-plane } else if (role == planesRoles[1]) { - return ViewParams::instance()->getAxisYColor(); // XZ-plane + return ViewParams::instance()->getAxisYColor(); // XZ-plane } else if (role == planesRoles[2]) { - return ViewParams::instance()->getAxisXColor(); // YZ-plane + return ViewParams::instance()->getAxisXColor(); // YZ-plane } return 0; } diff --git a/src/Gui/ViewProviderPlane.h b/src/Gui/ViewProviderPlane.h index abfb600989..bc51ce58f0 100644 --- a/src/Gui/ViewProviderPlane.h +++ b/src/Gui/ViewProviderPlane.h @@ -39,15 +39,16 @@ class SoCoordinate3; namespace Gui { -class GuiExport ViewProviderPlane : public ViewProviderDatum, public SelectionObserver +class GuiExport ViewProviderPlane: public ViewProviderDatum, public SelectionObserver { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderPlane); + public: /// Constructor ViewProviderPlane(); ~ViewProviderPlane() override; - void attach (App::DocumentObject*) override; + void attach(App::DocumentObject*) override; unsigned long getColor(const std::string& role) const; std::string getRole() const; @@ -59,8 +60,8 @@ public: private: void updatePlaneSize(); - bool isHovered { false }; - bool isSelected { false }; + bool isHovered {false}; + bool isSelected {false}; CoinPtr labelSwitch; CoinPtr pLabel; @@ -70,7 +71,7 @@ private: ParamHandlers handlers; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_ViewProviderPlane_H +#endif // GUI_ViewProviderPlane_H diff --git a/src/Gui/ViewProviderPoint.cpp b/src/Gui/ViewProviderPoint.cpp index f25a0babc6..0e59583da0 100644 --- a/src/Gui/ViewProviderPoint.cpp +++ b/src/Gui/ViewProviderPoint.cpp @@ -22,13 +22,12 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include "ViewProviderPoint.h" @@ -45,7 +44,8 @@ ViewProviderPoint::ViewProviderPoint() ViewProviderPoint::~ViewProviderPoint() = default; -void ViewProviderPoint::attach(App::DocumentObject * obj) { +void ViewProviderPoint::attach(App::DocumentObject* obj) +{ ViewProviderDatum::attach(obj); // The coordinates for the point (single vertex at the origin) @@ -58,7 +58,9 @@ void ViewProviderPoint::attach(App::DocumentObject * obj) { pCoords->point.setValue(point); sep->addChild(pCoords); - static const float size = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View")->GetFloat("DatumPointSize", 2.5); + static const float size = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetFloat("DatumPointSize", 2.5); auto sphere = new SoSphere(); sphere->radius.setValue(size); sep->addChild(sphere); diff --git a/src/Gui/ViewProviderPoint.h b/src/Gui/ViewProviderPoint.h index cbb8be9cd2..bf8b871a19 100644 --- a/src/Gui/ViewProviderPoint.h +++ b/src/Gui/ViewProviderPoint.h @@ -1,4 +1,4 @@ - // SPDX-License-Identifier: LGPL-2.1-or-later +// SPDX-License-Identifier: LGPL-2.1-or-later /**************************************************************************** * * * Copyright (c) 2024 Ondsel (PL Boyer) * @@ -30,17 +30,19 @@ namespace Gui { -class GuiExport ViewProviderPoint : public ViewProviderDatum { +class GuiExport ViewProviderPoint: public ViewProviderDatum +{ PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderPoint); + public: /// Constructor ViewProviderPoint(); ~ViewProviderPoint() override; - void attach ( App::DocumentObject * ) override; + void attach(App::DocumentObject*) override; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_ViewProviderPoint_H +#endif // GUI_ViewProviderPoint_H diff --git a/src/Gui/ViewProviderPyImp.cpp b/src/Gui/ViewProviderPyImp.cpp index c159fa8c8a..c6305789ea 100644 --- a/src/Gui/ViewProviderPyImp.cpp +++ b/src/Gui/ViewProviderPyImp.cpp @@ -21,13 +21,13 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -65,47 +65,53 @@ PyObject* ViewProviderPy::addProperty(PyObject* args, PyObject* kwd) short attr = 0; PyObject *ro = Py_False, *hd = Py_False, *lk = Py_False; PyObject* enumVals = nullptr; - const std::array kwlist {"type", - "name", - "group", - "doc", - "attr", - "read_only", - "hidden", - "locked", - "enum_vals", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwd, - "ss|sethO!O!O!O", - kwlist, - &sType, - &sName, - &sGroup, - "utf-8", - &sDoc, - &attr, - &PyBool_Type, - &ro, - &PyBool_Type, - &hd, - &PyBool_Type, - &lk, - &enumVals)) { + const std::array kwlist { + "type", + "name", + "group", + "doc", + "attr", + "read_only", + "hidden", + "locked", + "enum_vals", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwd, + "ss|sethO!O!O!O", + kwlist, + &sType, + &sName, + &sGroup, + "utf-8", + &sDoc, + &attr, + &PyBool_Type, + &ro, + &PyBool_Type, + &hd, + &PyBool_Type, + &lk, + &enumVals + )) { return nullptr; } - App::Property* prop = getViewProviderPtr()->addDynamicProperty(sType, - sName, - sGroup, - sDoc, - attr, - Base::asBoolean(ro), - Base::asBoolean(hd)); + App::Property* prop = getViewProviderPtr()->addDynamicProperty( + sType, + sName, + sGroup, + sDoc, + attr, + Base::asBoolean(ro), + Base::asBoolean(hd) + ); prop->setStatus(App::Property::LockDynamic, Base::asBoolean(lk)); - // enum support + // enum support auto* propEnum = freecad_cast(prop); if (propEnum && enumVals) { propEnum->setPyObject(enumVals); @@ -114,11 +120,12 @@ PyObject* ViewProviderPy::addProperty(PyObject* args, PyObject* kwd) return Py::new_reference_to(this); } -PyObject* ViewProviderPy::removeProperty(PyObject *args) +PyObject* ViewProviderPy::removeProperty(PyObject* args) { - char *sName; - if (!PyArg_ParseTuple(args, "s", &sName)) + char* sName; + if (!PyArg_ParseTuple(args, "s", &sName)) { return nullptr; + } try { bool ok = getViewProviderPtr()->removeDynamicProperty(sName); @@ -129,15 +136,16 @@ PyObject* ViewProviderPy::removeProperty(PyObject *args) } } -PyObject* ViewProviderPy::supportedProperties(PyObject *args) +PyObject* ViewProviderPy::supportedProperties(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::vector ary; Base::Type::getAllDerivedFrom(App::Property::getClassTypeId(), ary); Py::List res; - for (auto & it : ary) { + for (auto& it : ary) { auto data = static_cast(it.createInstance()); if (data) { delete data; @@ -147,76 +155,95 @@ PyObject* ViewProviderPy::supportedProperties(PyObject *args) return Py::new_reference_to(res); } -PyObject* ViewProviderPy::show(PyObject *args) +PyObject* ViewProviderPy::show(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { getViewProviderPtr()->show(); Py_Return; } PY_CATCH; } -PyObject* ViewProviderPy::hide(PyObject *args) +PyObject* ViewProviderPy::hide(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { getViewProviderPtr()->hide(); Py_Return; } PY_CATCH; } -PyObject* ViewProviderPy::isVisible(PyObject *args) +PyObject* ViewProviderPy::isVisible(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { return Py::new_reference_to(Py::Boolean(getViewProviderPtr()->isShow())); } PY_CATCH; } -PyObject* ViewProviderPy::canDragObject(PyObject *args) +PyObject* ViewProviderPy::canDragObject(PyObject* args) { - PyObject *obj = Py_None; - if (!PyArg_ParseTuple(args, "|O", &obj)) + PyObject* obj = Py_None; + if (!PyArg_ParseTuple(args, "|O", &obj)) { return nullptr; + } - PY_TRY { + PY_TRY + { Base::PyTypeCheck(&obj, &App::DocumentObjectPy::Type); bool ret; - if (!obj) + if (!obj) { ret = getViewProviderPtr()->canDragObjects(); - else + } + else { ret = getViewProviderPtr()->canDragObject( - static_cast(obj)->getDocumentObjectPtr()); + static_cast(obj)->getDocumentObjectPtr() + ); + } return Py::new_reference_to(Py::Boolean(ret)); } PY_CATCH; } -PyObject* ViewProviderPy::canDropObject(PyObject *args, PyObject *kw) +PyObject* ViewProviderPy::canDropObject(PyObject* args, PyObject* kw) { - PyObject *obj = Py_None; - PyObject *owner = Py_None; - PyObject *pyElements = Py_None; - const char *subname = nullptr; - static const std::array kwlist{"obj", "owner", "subname", "elem", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kw, "|OOsO", kwlist, - &obj, &owner, &subname, &pyElements)) { + PyObject* obj = Py_None; + PyObject* owner = Py_None; + PyObject* pyElements = Py_None; + const char* subname = nullptr; + static const std::array kwlist {"obj", "owner", "subname", "elem", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords(args, kw, "|OOsO", kwlist, &obj, &owner, &subname, &pyElements)) { return nullptr; } - PY_TRY { - Base::PyTypeCheck(&obj, &App::DocumentObjectPy::Type, "expecting 'obj' to be of type App.DocumentObject or None"); - Base::PyTypeCheck(&owner, &App::DocumentObjectPy::Type, "expecting 'owner' to be of type App.DocumentObject or None"); + PY_TRY + { + Base::PyTypeCheck( + &obj, + &App::DocumentObjectPy::Type, + "expecting 'obj' to be of type App.DocumentObject or None" + ); + Base::PyTypeCheck( + &owner, + &App::DocumentObjectPy::Type, + "expecting 'owner' to be of type App.DocumentObject or None" + ); Base::PyTypeCheck(&pyElements, PySequence_Check, "expecting 'elem' to be sequence or None"); bool ret; @@ -224,123 +251,157 @@ PyObject* ViewProviderPy::canDropObject(PyObject *args, PyObject *kw) App::DocumentObject* pcOwner = nullptr; App::PropertyStringList elements; if (!obj && (owner || pyElements || subname)) { - PyErr_SetString(PyExc_ValueError, "'obj' must be specified if 'owner', 'subname' or 'elem' is given"); + PyErr_SetString( + PyExc_ValueError, + "'obj' must be specified if 'owner', 'subname' or 'elem' is given" + ); return nullptr; } - if(!obj) { + if (!obj) { ret = getViewProviderPtr()->canDropObjects(); return Py::new_reference_to(Py::Boolean(ret)); } pcObject = static_cast(obj)->getDocumentObjectPtr(); - if (owner) + if (owner) { pcOwner = static_cast(owner)->getDocumentObjectPtr(); + } if (pyElements) { try { elements.setPyObject(pyElements); } - catch(...) { + catch (...) { PyErr_SetString(PyExc_TypeError, "'elem' must be a sequence of strings"); return nullptr; } } - ret = getViewProviderPtr()->canDropObjectEx(pcObject,pcOwner,subname,elements.getValues()); + ret = getViewProviderPtr()->canDropObjectEx(pcObject, pcOwner, subname, elements.getValues()); return Py::new_reference_to(Py::Boolean(ret)); } PY_CATCH; } -PyObject* ViewProviderPy::canDragAndDropObject(PyObject *args) +PyObject* ViewProviderPy::canDragAndDropObject(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!", &App::DocumentObjectPy::Type,&obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &App::DocumentObjectPy::Type, &obj)) { return nullptr; + } - PY_TRY { + PY_TRY + { bool ret = getViewProviderPtr()->canDragAndDropObject( - static_cast(obj)->getDocumentObjectPtr()); + static_cast(obj)->getDocumentObjectPtr() + ); return Py::new_reference_to(Py::Boolean(ret)); } PY_CATCH; } -PyObject* ViewProviderPy::dropObject(PyObject *args, PyObject *kw) +PyObject* ViewProviderPy::dropObject(PyObject* args, PyObject* kw) { - PyObject *obj; - PyObject *owner = Py_None; - PyObject *pyElements = Py_None; - const char *subname = nullptr; - static const std::array kwlist{"obj", "owner", "subname", "elem", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kw, "O!|OsO", kwlist, - &App::DocumentObjectPy::Type, &obj, &owner, &subname, &pyElements)) { + PyObject* obj; + PyObject* owner = Py_None; + PyObject* pyElements = Py_None; + const char* subname = nullptr; + static const std::array kwlist {"obj", "owner", "subname", "elem", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kw, + "O!|OsO", + kwlist, + &App::DocumentObjectPy::Type, + &obj, + &owner, + &subname, + &pyElements + )) { return nullptr; } - PY_TRY { - Base::PyTypeCheck(&owner, &App::DocumentObjectPy::Type, "expecting 'owner' to be of type App.DocumentObject or None"); + PY_TRY + { + Base::PyTypeCheck( + &owner, + &App::DocumentObjectPy::Type, + "expecting 'owner' to be of type App.DocumentObject or None" + ); Base::PyTypeCheck(&pyElements, PySequence_Check, "expecting 'elem' to be sequence or None"); auto pcObject = static_cast(obj)->getDocumentObjectPtr(); - App::DocumentObject *pcOwner = nullptr; + App::DocumentObject* pcOwner = nullptr; App::PropertyStringList elements; - if (owner) + if (owner) { pcOwner = static_cast(owner)->getDocumentObjectPtr(); + } if (pyElements) { try { elements.setPyObject(pyElements); } - catch(...) { + catch (...) { PyErr_SetString(PyExc_TypeError, "'elem' must be a sequence of strings"); return nullptr; } } - auto ret = getViewProviderPtr()->dropObjectEx(pcObject,pcOwner, subname,elements.getValues()); + auto ret = getViewProviderPtr()->dropObjectEx(pcObject, pcOwner, subname, elements.getValues()); return Py::new_reference_to(Py::String(ret)); } PY_CATCH; } -PyObject* ViewProviderPy::dragObject(PyObject *args) +PyObject* ViewProviderPy::dragObject(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!", &App::DocumentObjectPy::Type,&obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &App::DocumentObjectPy::Type, &obj)) { return nullptr; + } - PY_TRY { + PY_TRY + { getViewProviderPtr()->dragObject( - static_cast(obj)->getDocumentObjectPtr()); + static_cast(obj)->getDocumentObjectPtr() + ); Py_Return; } PY_CATCH; } -PyObject* ViewProviderPy::replaceObject(PyObject *args) +PyObject* ViewProviderPy::replaceObject(PyObject* args) { - PyObject *oldObj; - PyObject *newObj; - if (!PyArg_ParseTuple(args, "O!O!", - &App::DocumentObjectPy::Type,&oldObj, - &App::DocumentObjectPy::Type,&newObj)) + PyObject* oldObj; + PyObject* newObj; + if (!PyArg_ParseTuple( + args, + "O!O!", + &App::DocumentObjectPy::Type, + &oldObj, + &App::DocumentObjectPy::Type, + &newObj + )) { return nullptr; + } - PY_TRY { + PY_TRY + { int ret = getViewProviderPtr()->replaceObject( - static_cast(oldObj)->getDocumentObjectPtr(), - static_cast(newObj)->getDocumentObjectPtr()); + static_cast(oldObj)->getDocumentObjectPtr(), + static_cast(newObj)->getDocumentObjectPtr() + ); return Py::new_reference_to(Py::Long(ret)); } PY_CATCH; } -PyObject* ViewProviderPy::addDisplayMode(PyObject * args) +PyObject* ViewProviderPy::addDisplayMode(PyObject* args) { char* mode; PyObject* obj; - if (!PyArg_ParseTuple(args, "Os", &obj, &mode)) + if (!PyArg_ParseTuple(args, "Os", &obj, &mode)) { return nullptr; + } void* ptr = nullptr; try { - Base::Interpreter().convertSWIGPointerObj("pivy.coin","_p_SoNode", obj, &ptr, 0); + Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoNode", obj, &ptr, 0); if (!ptr) { PyErr_SetString(PyExc_RuntimeError, "Conversion of coin.SoNode failed"); return nullptr; @@ -351,25 +412,28 @@ PyObject* ViewProviderPy::addDisplayMode(PyObject * args) return nullptr; } - PY_TRY { + PY_TRY + { auto node = static_cast(ptr); - getViewProviderPtr()->addDisplayMaskMode(node,mode); + getViewProviderPtr()->addDisplayMaskMode(node, mode); Py_Return; } PY_CATCH; } -PyObject* ViewProviderPy::listDisplayModes(PyObject *args) +PyObject* ViewProviderPy::listDisplayModes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { std::vector modes = getViewProviderPtr()->getDisplayModes(); PyObject* pyList = PyList_New(modes.size()); - int i=0; + int i = 0; - for (const auto & mode : modes) { + for (const auto& mode : modes) { PyObject* str = PyUnicode_FromString(mode.c_str()); PyList_SetItem(pyList, i++, str); } @@ -379,30 +443,32 @@ PyObject* ViewProviderPy::listDisplayModes(PyObject *args) PY_CATCH; } -PyObject* ViewProviderPy::toString(PyObject *args) +PyObject* ViewProviderPy::toString(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { std::string buffer = getViewProviderPtr()->toString(); return Py::new_reference_to(Py::String(buffer)); } PY_CATCH; } -PyObject* ViewProviderPy::setTransformation(PyObject *args) +PyObject* ViewProviderPy::setTransformation(PyObject* args) { PyObject* p; Base::Matrix4D mat; - if (PyArg_ParseTuple(args, "O!",&(Base::MatrixPy::Type),&p)) { + if (PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type), &p)) { mat = *static_cast(p)->getMatrixPtr(); getViewProviderPtr()->setTransformation(mat); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!",&(Base::PlacementPy::Type),&p)) { + if (PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &p)) { auto plc = static_cast(p); getViewProviderPtr()->setTransformation(plc->getPlacementPtr()->toMatrix()); Py_Return; @@ -414,42 +480,49 @@ PyObject* ViewProviderPy::setTransformation(PyObject *args) PyObject* ViewProviderPy::claimChildren(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::vector children = this->getViewProviderPtr()->claimChildren(); Py::List ret; - for(auto* child : children){ - if (child) + for (auto* child : children) { + if (child) { ret.append(Py::asObject(child->getPyObject())); - else + } + else { ret.append(Py::None()); + } } return Py::new_reference_to(ret); } PyObject* ViewProviderPy::claimChildrenRecursive(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::vector children = this->getViewProviderPtr()->claimChildrenRecursive(); Py::List ret; - for(auto* child : children){ - if (child) + for (auto* child : children) { + if (child) { ret.append(Py::asObject(child->getPyObject())); - else + } + else { ret.append(Py::None()); + } } return Py::new_reference_to(ret); } PyObject* ViewProviderPy::partialRender(PyObject* args) { - PyObject *value = Py_None; - PyObject *clear = Py_False; - if (!PyArg_ParseTuple(args, "|OO!",&value,&PyBool_Type,&clear)) + PyObject* value = Py_None; + PyObject* clear = Py_False; + if (!PyArg_ParseTuple(args, "|OO!", &value, &PyBool_Type, &clear)) { return nullptr; + } std::vector values; if (value != Py_None) { @@ -484,34 +557,40 @@ PyObject* ViewProviderPy::partialRender(PyObject* args) PyObject* ViewProviderPy::getElementColors(PyObject* args) { - const char *element = nullptr; - if (!PyArg_ParseTuple(args, "|s", &element)) + const char* element = nullptr; + if (!PyArg_ParseTuple(args, "|s", &element)) { return nullptr; + } Py::Dict dict; - for(auto &v : getViewProviderPtr()->getElementColors(element)) { - auto &c = v.second; - dict.setItem(Py::String(v.first), - Py::TupleN(Py::Float(c.r),Py::Float(c.g),Py::Float(c.b),Py::Float(c.a))); + for (auto& v : getViewProviderPtr()->getElementColors(element)) { + auto& c = v.second; + dict.setItem( + Py::String(v.first), + Py::TupleN(Py::Float(c.r), Py::Float(c.g), Py::Float(c.b), Py::Float(c.a)) + ); } return Py::new_reference_to(dict); } PyObject* ViewProviderPy::setElementColors(PyObject* args) { - PyObject *pyObj; - if (!PyArg_ParseTuple(args, "O", &pyObj)) + PyObject* pyObj; + if (!PyArg_ParseTuple(args, "O", &pyObj)) { return nullptr; + } - if(!PyDict_Check(pyObj)) + if (!PyDict_Check(pyObj)) { throw Py::TypeError("Expect a dict"); + } - std::map colors; + std::map colors; Py::Dict dict(pyObj); - for(auto it=dict.begin();it!=dict.end();++it) { - const auto &value = *it; - if(!value.first.isString() || !value.second.isSequence()) + for (auto it = dict.begin(); it != dict.end(); ++it) { + const auto& value = *it; + if (!value.first.isString() || !value.second.isSequence()) { throw Py::TypeError("Expect the dictionary to contain items of type elementName:(r,g,b,a)"); + } App::PropertyColor prop; prop.setPyObject(value.second.ptr()); @@ -523,90 +602,115 @@ PyObject* ViewProviderPy::setElementColors(PyObject* args) PyObject* ViewProviderPy::getElementPicked(PyObject* args) const { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O",&obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } - void *ptr = nullptr; + void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoPickedPoint", obj, &ptr, 0); auto pp = static_cast(ptr); - if(!pp) + if (!pp) { throw Base::TypeError("type must be coin.SoPickedPoint"); + } std::string name; - if(!getViewProviderPtr()->getElementPicked(pp,name)) + if (!getViewProviderPtr()->getElementPicked(pp, name)) { Py_Return; + } return Py::new_reference_to(Py::String(name)); } PyObject* ViewProviderPy::getDetailPath(PyObject* args) const { - const char *sub; - PyObject *path; - PyObject *append = Py_True; - if (!PyArg_ParseTuple(args, "sO|O!",&sub,&path,&PyBool_Type,&append)) + const char* sub; + PyObject* path; + PyObject* append = Py_True; + if (!PyArg_ParseTuple(args, "sO|O!", &sub, &path, &PyBool_Type, &append)) { return nullptr; + } - void *ptr = nullptr; + void* ptr = nullptr; Base::Interpreter().convertSWIGPointerObj("pivy.coin", "_p_SoPath", path, &ptr, 0); auto pPath = static_cast(ptr); - if(!pPath) + if (!pPath) { throw Base::TypeError("'path' must be a coin.SoPath"); - SoDetail *det = nullptr; - if(!getViewProviderPtr()->getDetailPath(sub,static_cast(pPath),append,det)) { + } + SoDetail* det = nullptr; + if (!getViewProviderPtr()->getDetailPath(sub, static_cast(pPath), append, det)) { delete det; Py_Return; } - if(!det) + if (!det) { Py_Return; - return Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoDetail", static_cast(det), 0); + } + return Base::Interpreter() + .createSWIGPointerObj("pivy.coin", "_p_SoDetail", static_cast(det), 0); } -PyObject *ViewProviderPy::signalChangeIcon(PyObject *args) const +PyObject* ViewProviderPy::signalChangeIcon(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getViewProviderPtr()->signalChangeIcon(); Py_Return; } -PyObject *ViewProviderPy::getBoundingBox(PyObject *args) { - PyObject *transform=Py_True; - PyObject *pyView = nullptr; - const char *subname = nullptr; - if (!PyArg_ParseTuple(args, "|sO!O!", &subname,&PyBool_Type,&transform,View3DInventorPy::type_object(),&pyView)) +PyObject* ViewProviderPy::getBoundingBox(PyObject* args) +{ + PyObject* transform = Py_True; + PyObject* pyView = nullptr; + const char* subname = nullptr; + if (!PyArg_ParseTuple( + args, + "|sO!O!", + &subname, + &PyBool_Type, + &transform, + View3DInventorPy::type_object(), + &pyView + )) { return nullptr; + } - PY_TRY { - View3DInventor *view = nullptr; - if(pyView) + PY_TRY + { + View3DInventor* view = nullptr; + if (pyView) { view = static_cast(pyView)->getView3DInventorPtr(); + } auto bbox = getViewProviderPtr()->getBoundingBox(subname, Base::asBoolean(transform), view); return new Base::BoundBoxPy(new Base::BoundBox3d(bbox)); } PY_CATCH; } -PyObject *ViewProviderPy::doubleClicked(PyObject *args) { - if(!PyArg_ParseTuple(args, "")) +PyObject* ViewProviderPy::doubleClicked(PyObject* args) +{ + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { return Py::new_reference_to(Py::Boolean(getViewProviderPtr()->doubleClicked())); } PY_CATCH; } -PyObject *ViewProviderPy::getCustomAttributes(const char* attr) const +PyObject* ViewProviderPy::getCustomAttributes(const char* attr) const { // search for dynamic property App::Property* prop = getViewProviderPtr()->getDynamicPropertyByName(attr); - if (prop) + if (prop) { return prop->getPyObject(); - else + } + else { return nullptr; + } } int ViewProviderPy::setCustomAttributes(const char* attr, PyObject* value) @@ -620,7 +724,7 @@ int ViewProviderPy::setCustomAttributes(const char* attr, PyObject* value) } return 0; } - catch (Base::Exception &exc) { + catch (Base::Exception& exc) { PyErr_Format(PyExc_AttributeError, "Attribute (Name: %s) error: '%s' ", attr, exc.what()); return -1; } @@ -634,7 +738,8 @@ Py::Object ViewProviderPy::getAnnotation() const { try { auto node = getViewProviderPtr()->getAnnotation(); - PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", node, 1); + PyObject* Ptr + = Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", node, 1); node->ref(); return Py::Object(Ptr, true); } @@ -643,16 +748,15 @@ Py::Object ViewProviderPy::getAnnotation() const } } -void ViewProviderPy::setAnnotation(Py::Object) -{ - -} +void ViewProviderPy::setAnnotation(Py::Object) +{} Py::Object ViewProviderPy::getRootNode() const { try { SoSeparator* node = getViewProviderPtr()->getRoot(); - PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin","_p_SoSeparator", node, 1); + PyObject* Ptr + = Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", node, 1); node->ref(); return Py::Object(Ptr, true); } @@ -661,16 +765,14 @@ Py::Object ViewProviderPy::getRootNode() const } } -void ViewProviderPy::setRootNode(Py::Object) -{ - -} +void ViewProviderPy::setRootNode(Py::Object) +{} Py::Object ViewProviderPy::getSwitchNode() const { try { SoSwitch* node = getViewProviderPtr()->getModeSwitch(); - PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin","_p_SoSwitch", node, 1); + PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSwitch", node, 1); node->ref(); return Py::Object(Ptr, true); } @@ -679,10 +781,8 @@ Py::Object ViewProviderPy::getSwitchNode() const } } -void ViewProviderPy::setSwitchNode(Py::Object) -{ - -} +void ViewProviderPy::setSwitchNode(Py::Object) +{} Py::String ViewProviderPy::getIV() const { @@ -743,13 +843,19 @@ void ViewProviderPy::setToggleVisibility(Py::Object arg) } if (val == "CanToggleVisibility") { - getViewProviderPtr()->setToggleVisibility(ViewProvider::ToggleVisibilityMode::CanToggleVisibility); + getViewProviderPtr()->setToggleVisibility( + ViewProvider::ToggleVisibilityMode::CanToggleVisibility + ); } else if (val == "NoToggleVisibility") { - getViewProviderPtr()->setToggleVisibility(ViewProvider::ToggleVisibilityMode::NoToggleVisibility); + getViewProviderPtr()->setToggleVisibility( + ViewProvider::ToggleVisibilityMode::NoToggleVisibility + ); } else { - throw Py::ValueError("Invalid ToggleVisibility mode. Use 'CanToggleVisibility' or 'NoToggleVisibility'."); + throw Py::ValueError( + "Invalid ToggleVisibility mode. Use 'CanToggleVisibility' or 'NoToggleVisibility'." + ); } } diff --git a/src/Gui/ViewProviderSuppressibleExtension.cpp b/src/Gui/ViewProviderSuppressibleExtension.cpp index dfdbcc2d73..ef6ac54198 100644 --- a/src/Gui/ViewProviderSuppressibleExtension.cpp +++ b/src/Gui/ViewProviderSuppressibleExtension.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include @@ -53,33 +52,36 @@ void ViewProviderSuppressibleExtension::extensionUpdateData(const App::Property* { auto vp = getExtendedViewProvider(); auto owner = vp->getObject(); - if(!owner || !owner->isValid()) + if (!owner || !owner->isValid()) { return; + } auto ext = owner->getExtensionByType(); if (ext && prop == &ext->Suppressed) { - //update the tree item + // update the tree item bool suppressed = ext->Suppressed.getValue(); setSuppressedIcon(suppressed); getExtendedViewProvider()->signalChangeHighlight(suppressed, Gui::HighlightMode::StrikeOut); } } -void ViewProviderSuppressibleExtension::setSuppressedIcon(bool onoff) { +void ViewProviderSuppressibleExtension::setSuppressedIcon(bool onoff) +{ isSetSuppressedIcon = onoff; - getExtendedViewProvider()->signalChangeIcon(); // signal icon change + getExtendedViewProvider()->signalChangeIcon(); // signal icon change } -QIcon ViewProviderSuppressibleExtension::extensionMergeColorfullOverlayIcons (const QIcon & orig) const +QIcon ViewProviderSuppressibleExtension::extensionMergeColorfullOverlayIcons(const QIcon& orig) const { QIcon mergedicon = orig; - if(isSetSuppressedIcon) { + if (isSetSuppressedIcon) { static QPixmap px(Gui::BitmapFactory().pixmapFromSvg("feature_suppressed", QSize(16, 16))); - mergedicon = Gui::BitmapFactoryInst::mergePixmap(mergedicon, px, Gui::BitmapFactoryInst::TopLeft); + mergedicon + = Gui::BitmapFactoryInst::mergePixmap(mergedicon, px, Gui::BitmapFactoryInst::TopLeft); } return Gui::ViewProviderExtension::extensionMergeColorfullOverlayIcons(mergedicon); } @@ -89,23 +91,25 @@ void ViewProviderSuppressibleExtension::extensionSetupContextMenu(QMenu* menu, Q { auto vp = getExtendedViewProvider(); auto obj = vp->getObject()->getExtensionByType(); - //Show Suppressed toggle action if the Suppressed property is visible - if (obj && ! obj->Suppressed.testStatus(App::Property::Hidden)) { + // Show Suppressed toggle action if the Suppressed property is visible + if (obj && !obj->Suppressed.testStatus(App::Property::Hidden)) { Gui::ActionFunction* func = new Gui::ActionFunction(menu); QAction* act = menu->addAction(QObject::tr("Suppressed")); act->setCheckable(true); act->setChecked(obj->Suppressed.getValue()); - func->trigger(act, [obj](){ - obj->Suppressed.setValue(! obj->Suppressed.getValue()); - }); + func->trigger(act, [obj]() { obj->Suppressed.setValue(!obj->Suppressed.getValue()); }); } } -namespace Gui { -EXTENSION_PROPERTY_SOURCE_TEMPLATE(Gui::ViewProviderSuppressibleExtensionPython, Gui::ViewProviderSuppressibleExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + Gui::ViewProviderSuppressibleExtensionPython, + Gui::ViewProviderSuppressibleExtension +) // explicit template instantiation template class GuiExport ViewProviderExtensionPythonT; -} //namespace Gui +} // namespace Gui diff --git a/src/Gui/ViewProviderSuppressibleExtension.h b/src/Gui/ViewProviderSuppressibleExtension.h index dfc4b4b182..acefd86646 100644 --- a/src/Gui/ViewProviderSuppressibleExtension.h +++ b/src/Gui/ViewProviderSuppressibleExtension.h @@ -29,7 +29,7 @@ namespace Gui { -class GuiExport ViewProviderSuppressibleExtension : public ViewProviderExtension +class GuiExport ViewProviderSuppressibleExtension: public ViewProviderExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderSuppressibleExtension); @@ -40,15 +40,16 @@ public: void extensionUpdateData(const App::Property* prop) override; void setSuppressedIcon(bool onoff); - QIcon extensionMergeColorfullOverlayIcons (const QIcon & orig) const override; + QIcon extensionMergeColorfullOverlayIcons(const QIcon& orig) const override; void extensionSetupContextMenu(QMenu* menu, QObject*, const char*) override; private: - bool isSetSuppressedIcon{false}; + bool isSetSuppressedIcon {false}; }; -using ViewProviderSuppressibleExtensionPython = ViewProviderExtensionPythonT; +using ViewProviderSuppressibleExtensionPython + = ViewProviderExtensionPythonT; -} //namespace Gui +} // namespace Gui -#endif // VIEWPROVIDERSUPPRESSIBLEEXTENSION_H +#endif // VIEWPROVIDERSUPPRESSIBLEEXTENSION_H diff --git a/src/Gui/ViewProviderTextDocument.cpp b/src/Gui/ViewProviderTextDocument.cpp index baa80ab059..6a35efd2c9 100644 --- a/src/Gui/ViewProviderTextDocument.cpp +++ b/src/Gui/ViewProviderTextDocument.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -41,26 +40,57 @@ using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderTextDocument, Gui::ViewProviderDocumentObject) -const char* ViewProviderTextDocument::SyntaxEnums[]= {"None","Python",nullptr}; +const char* ViewProviderTextDocument::SyntaxEnums[] = {"None", "Python", nullptr}; ViewProviderTextDocument::ViewProviderTextDocument() { sPixmap = "TextDocument"; ADD_PROPERTY_TYPE( - ReadOnly, (false), "Editor", App::Prop_None, - "Defines whether the content can be edited."); + ReadOnly, + (false), + "Editor", + App::Prop_None, + "Defines whether the content can be edited." + ); QFont font; - font.setFamily(QString::fromLatin1(App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Editor")->GetASCII("Font", font.family().toLatin1()).c_str())); - font.setPointSize(App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Editor")->GetInt("FontSize", font.pointSize())); + font.setFamily( + QString::fromLatin1( + App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Editor") + ->GetASCII("Font", font.family().toLatin1()) + .c_str() + ) + ); + font.setPointSize( + App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Editor") + ->GetInt("FontSize", font.pointSize()) + ); - ADD_PROPERTY_TYPE(FontSize,(font.pointSize()), "Editor", App::Prop_None, "Font size"); - ADD_PROPERTY_TYPE(FontName,((const char*)font.family().toLatin1()), "Editor", App::Prop_None, "Font name"); + ADD_PROPERTY_TYPE(FontSize, (font.pointSize()), "Editor", App::Prop_None, "Font size"); + ADD_PROPERTY_TYPE( + FontName, + ((const char*)font.family().toLatin1()), + "Editor", + App::Prop_None, + "Font name" + ); - ADD_PROPERTY_TYPE(SyntaxHighlighter,(static_cast(0)), "Editor", App::Prop_None, "Syntax highlighting"); + ADD_PROPERTY_TYPE( + SyntaxHighlighter, + (static_cast(0)), + "Editor", + App::Prop_None, + "Syntax highlighting" + ); SyntaxHighlighter.setEnums(SyntaxEnums); DisplayMode.setStatus(App::Property::Hidden, true); @@ -73,9 +103,7 @@ void ViewProviderTextDocument::setupContextMenu(QMenu* menu, QObject* receiver, { auto func = new Gui::ActionFunction(menu); QAction* act = menu->addAction(QObject::tr("Edit Text")); - func->trigger(act, [this](){ - this->doubleClicked(); - }); + func->trigger(act, [this]() { this->doubleClicked(); }); ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); } @@ -89,9 +117,8 @@ bool ViewProviderTextDocument::doubleClicked() SyntaxHighlighter.touch(); getMainWindow()->addWindow( - new TextDocumentEditorView { - getObject(), - editorWidget, getMainWindow()}); + new TextDocumentEditorView {getObject(), editorWidget, getMainWindow()} + ); } return true; } @@ -114,8 +141,9 @@ void ViewProviderTextDocument::onChanged(const App::Property* prop) } else { auto shl = editorWidget->findChild(); - if (shl) + if (shl) { shl->deleteLater(); + } } } } @@ -124,10 +152,9 @@ void ViewProviderTextDocument::onChanged(const App::Property* prop) MDIView* ViewProviderTextDocument::getMDIView() const { - auto views = getDocument()->getMDIViewsOfType( - TextDocumentEditorView::getClassTypeId()); + auto views = getDocument()->getMDIViewsOfType(TextDocumentEditorView::getClassTypeId()); for (auto v : views) { - auto textView = static_cast(v); + auto textView = static_cast(v); if (textView->getTextObject() == getObject()) { return textView; } @@ -137,10 +164,9 @@ MDIView* ViewProviderTextDocument::getMDIView() const bool ViewProviderTextDocument::activateView() const { - auto views = getDocument()->getMDIViewsOfType( - TextDocumentEditorView::getClassTypeId()); + auto views = getDocument()->getMDIViewsOfType(TextDocumentEditorView::getClassTypeId()); for (auto v : views) { - auto textView = static_cast(v); + auto textView = static_cast(v); if (textView->getTextObject() == getObject()) { getMainWindow()->setActiveWindow(textView); return true; diff --git a/src/Gui/ViewProviderTextDocument.h b/src/Gui/ViewProviderTextDocument.h index c56b4a886d..eedaac452d 100644 --- a/src/Gui/ViewProviderTextDocument.h +++ b/src/Gui/ViewProviderTextDocument.h @@ -29,10 +29,13 @@ class QPlainTextEdit; -namespace Gui { +namespace Gui +{ -class GuiExport ViewProviderTextDocument : public ViewProviderDocumentObject { +class GuiExport ViewProviderTextDocument: public ViewProviderDocumentObject +{ PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderTextDocument); + public: ViewProviderTextDocument(); ~ViewProviderTextDocument() override = default; @@ -44,11 +47,14 @@ public: bool doubleClicked() override; void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; - bool isShow() const override { return true; } + bool isShow() const override + { + return true; + } void onChanged(const App::Property* prop) override; - MDIView *getMDIView() const override; + MDIView* getMDIView() const override; private: bool activateView() const; @@ -58,7 +64,6 @@ private: static const char* SyntaxEnums[]; }; -} +} // namespace Gui #endif - diff --git a/src/Gui/ViewProviderTextureExtension.cpp b/src/Gui/ViewProviderTextureExtension.cpp index eeba50561a..42748636ff 100644 --- a/src/Gui/ViewProviderTextureExtension.cpp +++ b/src/Gui/ViewProviderTextureExtension.cpp @@ -90,7 +90,10 @@ SoGroup* ViewProviderTextureExtension::getTextureGroup3D() const return pcTextureGroup3D; } -void ViewProviderTextureExtension::setCoinAppearance(SoMaterial* pcShapeMaterial, const App::Material& source) +void ViewProviderTextureExtension::setCoinAppearance( + SoMaterial* pcShapeMaterial, + const App::Material& source +) { #if 0 if (!source.image.empty()) { @@ -111,18 +114,14 @@ void ViewProviderTextureExtension::setCoinAppearance(SoMaterial* pcShapeMaterial activateMaterial(); // Always set the material for items such as lines that don't support textures - pcShapeMaterial->ambientColor.setValue(source.ambientColor.r, - source.ambientColor.g, - source.ambientColor.b); - pcShapeMaterial->diffuseColor.setValue(source.diffuseColor.r, - source.diffuseColor.g, - source.diffuseColor.b); - pcShapeMaterial->specularColor.setValue(source.specularColor.r, - source.specularColor.g, - source.specularColor.b); - pcShapeMaterial->emissiveColor.setValue(source.emissiveColor.r, - source.emissiveColor.g, - source.emissiveColor.b); + pcShapeMaterial->ambientColor + .setValue(source.ambientColor.r, source.ambientColor.g, source.ambientColor.b); + pcShapeMaterial->diffuseColor + .setValue(source.diffuseColor.r, source.diffuseColor.g, source.diffuseColor.b); + pcShapeMaterial->specularColor + .setValue(source.specularColor.r, source.specularColor.g, source.specularColor.b); + pcShapeMaterial->emissiveColor + .setValue(source.emissiveColor.r, source.emissiveColor.g, source.emissiveColor.b); pcShapeMaterial->shininess.setValue(source.shininess); pcShapeMaterial->transparency.setValue(source.transparency); } diff --git a/src/Gui/ViewProviderTextureExtension.h b/src/Gui/ViewProviderTextureExtension.h index dd3e0590cf..75a7cde3e6 100644 --- a/src/Gui/ViewProviderTextureExtension.h +++ b/src/Gui/ViewProviderTextureExtension.h @@ -88,13 +88,12 @@ public: private: // Used to support per face textures - SoTexture3 * pcShapeTexture3D; - SoCoordinate3 * pcShapeCoordinates; - SoIndexedFaceSet * pcShapeFaceset; + SoTexture3* pcShapeTexture3D; + SoCoordinate3* pcShapeCoordinates; + SoIndexedFaceSet* pcShapeFaceset; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDERTEXTUREEXT_H - +#endif // GUI_VIEWPROVIDERTEXTUREEXT_H diff --git a/src/Gui/ViewProviderVRMLObject.cpp b/src/Gui/ViewProviderVRMLObject.cpp index 30ecb139dd..3733de9313 100644 --- a/src/Gui/ViewProviderVRMLObject.cpp +++ b/src/Gui/ViewProviderVRMLObject.cpp @@ -21,16 +21,15 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -60,7 +59,7 @@ ViewProviderVRMLObject::ViewProviderVRMLObject() pcVRML = new SoFCSelection(); pcVRML->preselectionMode = Gui::SoFCSelection::OFF; pcVRML->selectionMode = Gui::SoFCSelection::SEL_OFF; - //pcVRML->style = Gui::SoFCSelection::BOX; + // pcVRML->style = Gui::SoFCSelection::BOX; pcVRML->ref(); } @@ -69,7 +68,7 @@ ViewProviderVRMLObject::~ViewProviderVRMLObject() pcVRML->unref(); } -void ViewProviderVRMLObject::attach(App::DocumentObject *pcObj) +void ViewProviderVRMLObject::attach(App::DocumentObject* pcObj) { ViewProviderDocumentObject::attach(pcObj); addDisplayMaskMode(pcVRML, "VRML"); @@ -80,9 +79,10 @@ void ViewProviderVRMLObject::attach(App::DocumentObject *pcObj) void ViewProviderVRMLObject::setDisplayMode(const char* ModeName) { - if ( strcmp("VRML",ModeName)==0 ) + if (strcmp("VRML", ModeName) == 0) { setDisplayMaskMode("VRML"); - ViewProviderDocumentObject::setDisplayMode( ModeName ); + } + ViewProviderDocumentObject::setDisplayMode(ModeName); } std::vector ViewProviderVRMLObject::getDisplayModes() const @@ -100,11 +100,11 @@ void ViewProviderVRMLObject::getResourceFile(SoNode* node, std::list(pathlist[i]); + const SoPathList& pathlist = sa.getPaths(); + for (int i = 0; i < pathlist.getLength(); i++) { + auto path = static_cast(pathlist[i]); if (path->getTail()->isOfType(T::getClassTypeId())) { - T * tex = static_cast(path->getTail()); + T* tex = static_cast(path->getTail()); for (int j = 0; j < tex->url.getNum(); j++) { this->addResource(tex->url[j], resources); } @@ -112,19 +112,23 @@ void ViewProviderVRMLObject::getResourceFile(SoNode* node, std::list -void ViewProviderVRMLObject::getResourceFile(SoNode* node, std::list& resources) +void ViewProviderVRMLObject::getResourceFile( + SoNode* node, + std::list& resources +) { SoSearchAction sa; sa.setType(SoVRMLBackground::getClassTypeId()); sa.setInterest(SoSearchAction::ALL); sa.setSearchingAll(true); sa.apply(node); - const SoPathList & pathlist = sa.getPaths(); - for (int i = 0; i < pathlist.getLength(); i++ ) { - auto path = static_cast(pathlist[i]); + const SoPathList& pathlist = sa.getPaths(); + for (int i = 0; i < pathlist.getLength(); i++) { + auto path = static_cast(pathlist[i]); if (path->getTail()->isOfType(SoVRMLBackground::getClassTypeId())) { auto vrml = static_cast(path->getTail()); // backUrl @@ -155,7 +159,7 @@ void ViewProviderVRMLObject::getResourceFile(SoNode* node, std } } -} +} // namespace Gui void ViewProviderVRMLObject::addResource(const SbString& url, std::list& resources) { @@ -178,9 +182,9 @@ void ViewProviderVRMLObject::getLocalResources(SoNode* node, std::list(path->getTail()); const SbString& url = vrml->getFullURLName(); if (url.getLength() > 0) { @@ -197,12 +201,12 @@ void ViewProviderVRMLObject::getLocalResources(SoNode* node, std::list(node, resources); - getResourceFile(node, resources); - getResourceFile(node, resources); - getResourceFile(node, resources); - getResourceFile(node, resources); - getResourceFile(node, resources); + getResourceFile(node, resources); + getResourceFile(node, resources); + getResourceFile(node, resources); + getResourceFile(node, resources); + getResourceFile(node, resources); + getResourceFile(node, resources); } void ViewProviderVRMLObject::updateData(const App::Property* prop) @@ -226,8 +230,8 @@ void ViewProviderVRMLObject::updateData(const App::Property* prop) // Read in the file QByteArray buffer = file.readAll(); - in.setBuffer((void *)buffer.constData(), buffer.length()); - SoSeparator * node = SoDB::readAll(&in); + in.setBuffer((void*)buffer.constData(), buffer.length()); + SoSeparator* node = SoDB::readAll(&in); if (node) { if (!checkRecursion(node)) { @@ -248,8 +252,8 @@ void ViewProviderVRMLObject::updateData(const App::Property* prop) SoInput::removeDirectory(subpath.constData()); } } - else if (prop->isDerivedFrom() && - strcmp(prop->getName(), "Placement") == 0) { + else if (prop->isDerivedFrom() + && strcmp(prop->getName(), "Placement") == 0) { // Note: If R is the rotation, c the rotation center and t the translation // vector then Inventor applies the following transformation: R*(x-c)+c+t // In FreeCAD a placement only has a rotation and a translation part but @@ -266,9 +270,9 @@ void ViewProviderVRMLObject::updateData(const App::Property* prop) auto px = (float)p.getPosition().x; auto py = (float)p.getPosition().y; auto pz = (float)p.getPosition().z; - pcTransform->rotation.setValue(q0,q1,q2,q3); - pcTransform->translation.setValue(px,py,pz); - pcTransform->center.setValue(0.0f,0.0f,0.0f); - pcTransform->scaleFactor.setValue(1.0f,1.0f,1.0f); + pcTransform->rotation.setValue(q0, q1, q2, q3); + pcTransform->translation.setValue(px, py, pz); + pcTransform->center.setValue(0.0f, 0.0f, 0.0f); + pcTransform->scaleFactor.setValue(1.0f, 1.0f, 1.0f); } } diff --git a/src/Gui/ViewProviderVRMLObject.h b/src/Gui/ViewProviderVRMLObject.h index 944e429b1a..715e8787a2 100644 --- a/src/Gui/ViewProviderVRMLObject.h +++ b/src/Gui/ViewProviderVRMLObject.h @@ -32,7 +32,7 @@ namespace Gui { class SoFCSelection; -class GuiExport ViewProviderVRMLObject : public ViewProviderDocumentObject +class GuiExport ViewProviderVRMLObject: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderVRMLObject); @@ -43,19 +43,20 @@ public: /// destructor. ~ViewProviderVRMLObject() override; - void attach(App::DocumentObject *pcObject) override; + void attach(App::DocumentObject* pcObject) override; void setDisplayMode(const char* ModeName) override; std::vector getDisplayModes() const override; void updateData(const App::Property*) override; void getLocalResources(SoNode*, std::list&); void addResource(const SbString&, std::list&); - template void getResourceFile(SoNode*, std::list&); + template + void getResourceFile(SoNode*, std::list&); protected: - SoFCSelection * pcVRML; + SoFCSelection* pcVRML; }; -} //namespace Gui +} // namespace Gui -#endif // GUI_VIEWPROVIDER_INVENTOROBJECT_H +#endif // GUI_VIEWPROVIDER_INVENTOROBJECT_H diff --git a/src/Gui/ViewProviderVarSet.cpp b/src/Gui/ViewProviderVarSet.cpp index 200be1dafa..3fe76b71d4 100644 --- a/src/Gui/ViewProviderVarSet.cpp +++ b/src/Gui/ViewProviderVarSet.cpp @@ -21,7 +21,7 @@ ****************************************************************************/ -# include +#include #include diff --git a/src/Gui/ViewProviderVarSet.h b/src/Gui/ViewProviderVarSet.h index 3542abedfc..05cb938425 100644 --- a/src/Gui/ViewProviderVarSet.h +++ b/src/Gui/ViewProviderVarSet.h @@ -26,18 +26,23 @@ #include "ViewProviderDocumentObject.h" #include "Dialogs/DlgAddProperty.h" -namespace Gui { +namespace Gui +{ /** View provider associated with an App::VarSet */ -class GuiExport ViewProviderVarSet : public ViewProviderDocumentObject +class GuiExport ViewProviderVarSet: public ViewProviderDocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderVarSet); + public: ViewProviderVarSet(); ~ViewProviderVarSet() override = default; - bool isShow() const override { return true; } + bool isShow() const override + { + return true; + } bool doubleClicked() override; @@ -47,6 +52,6 @@ private: std::unique_ptr dialog; }; -} // namespace Gui +} // namespace Gui #endif diff --git a/src/Gui/WaitCursor.cpp b/src/Gui/WaitCursor.cpp index 31a6bf31e2..b46da3b20e 100644 --- a/src/Gui/WaitCursor.cpp +++ b/src/Gui/WaitCursor.cpp @@ -22,20 +22,21 @@ #include -# include -# include -# include -# include -# ifdef FC_OS_WIN32 -# include -# endif +#include +#include +#include +#include +#ifdef FC_OS_WIN32 +# include +#endif #include "WaitCursor.h" using namespace Gui; -namespace Gui { -class WaitCursorP : public QObject +namespace Gui +{ +class WaitCursorP: public QObject { public: static WaitCursorP* getInstance(); @@ -48,30 +49,32 @@ protected: bool isModalDialog(QObject* o) const; private: - WaitCursorP(); // Disable constructor + WaitCursorP(); // Disable constructor static WaitCursorP* _instance; - bool isOn{false}; - WaitCursor::FilterEventsFlags flags{WaitCursor::AllEvents}; + bool isOn {false}; + WaitCursor::FilterEventsFlags flags {WaitCursor::AllEvents}; }; -} // namespace Gui +} // namespace Gui WaitCursorP* WaitCursorP::_instance = nullptr; -WaitCursorP::WaitCursorP() : QObject(nullptr) -{ -} +WaitCursorP::WaitCursorP() + : QObject(nullptr) +{} WaitCursorP* WaitCursorP::getInstance() { - if (!_instance) + if (!_instance) { _instance = new WaitCursorP(); + } return _instance; } void WaitCursorP::setBusy(bool on) { - if (on == this->isOn) + if (on == this->isOn) { return; + } if (on) { qApp->installEventFilter(this); @@ -100,16 +103,19 @@ bool WaitCursorP::isModalDialog(QObject* o) const QWidget* parent = qobject_cast(o); if (!parent) { QWindow* window = qobject_cast(o); - if (window) + if (window) { parent = QWidget::find(window->winId()); + } } while (parent) { auto dlg = qobject_cast(parent); - if (dlg && dlg->isModal()) + if (dlg && dlg->isModal()) { return true; + } auto pd = qobject_cast(parent); - if (pd) + if (pd) { return true; + } parent = parent->parentWidget(); } @@ -120,20 +126,22 @@ bool WaitCursorP::eventFilter(QObject* o, QEvent* e) { // Note: This might cause problems when we want to open a modal dialog at the lifetime // of a WaitCursor instance because the incoming events are still filtered. - if (e->type() == QEvent::KeyPress || - e->type() == QEvent::KeyRelease) { - if (isModalDialog(o)) + if (e->type() == QEvent::KeyPress || e->type() == QEvent::KeyRelease) { + if (isModalDialog(o)) { return false; - if (this->flags & WaitCursor::KeyEvents) + } + if (this->flags & WaitCursor::KeyEvents) { return true; + } } - if (e->type() == QEvent::MouseButtonPress || - e->type() == QEvent::MouseButtonRelease || - e->type() == QEvent::MouseButtonDblClick) { - if (isModalDialog(o)) + if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonRelease + || e->type() == QEvent::MouseButtonDblClick) { + if (isModalDialog(o)) { return false; - if (this->flags & WaitCursor::MouseEvents) + } + if (this->flags & WaitCursor::MouseEvents) { return true; + } } return false; } @@ -148,16 +156,18 @@ int WaitCursor::instances = 0; */ WaitCursor::WaitCursor() { - if (instances++ == 0) + if (instances++ == 0) { setWaitCursor(); + } filter = WaitCursorP::getInstance()->ignoreEvents(); } /** Restores the last cursor again. */ WaitCursor::~WaitCursor() { - if (--instances == 0) + if (--instances == 0) { restoreCursor(); + } WaitCursorP::getInstance()->setIgnoreEvents(filter); } @@ -198,4 +208,4 @@ void WaitCursor::resume() // Calling setBusy(true) will set the wait cursor and reinstall the event filter. // The WaitCursorP's internal state `isOn` correctly handles this call. WaitCursorP::getInstance()->setBusy(true); -} \ No newline at end of file +} diff --git a/src/Gui/WaitCursor.h b/src/Gui/WaitCursor.h index 86b6a3ae14..95602d9032 100644 --- a/src/Gui/WaitCursor.h +++ b/src/Gui/WaitCursor.h @@ -25,7 +25,8 @@ #include -namespace Gui { +namespace Gui +{ /** * This class sets a waitcursor automatically while a slow operation is running. @@ -60,7 +61,8 @@ namespace Gui { class GuiExport WaitCursor { public: - enum FilterEventsFlag { + enum FilterEventsFlag + { NoEvents = 0x00, KeyEvents = 0x01, MouseEvents = 0x02, @@ -94,7 +96,6 @@ private: static int instances; }; -} // namespace Gui - -#endif // GUI_WAIT_CURSOR_H +} // namespace Gui +#endif // GUI_WAIT_CURSOR_H diff --git a/src/Gui/WhatsThis.cpp b/src/Gui/WhatsThis.cpp index bccfe36bec..fee2748c37 100644 --- a/src/Gui/WhatsThis.cpp +++ b/src/Gui/WhatsThis.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include "WhatsThis.h" @@ -39,57 +38,57 @@ bool StdCmdDescription::_descrMode = false; /* TRANSLATOR Gui::StdCmdDescription */ StdCmdDescription::StdCmdDescription() - : Command("Std_DescriptionMode") + : Command("Std_DescriptionMode") { - sGroup = "Help"; - sMenuText = QT_TR_NOOP("Des&cription"); - sToolTipText = QT_TR_NOOP("Long description of commands"); - sWhatsThis = "Std_DescriptionMode"; - sStatusTip = sToolTipText; - sAccel = "F1"; + sGroup = "Help"; + sMenuText = QT_TR_NOOP("Des&cription"); + sToolTipText = QT_TR_NOOP("Long description of commands"); + sWhatsThis = "Std_DescriptionMode"; + sStatusTip = sToolTipText; + sAccel = "F1"; } StdCmdDescription::~StdCmdDescription() = default; -Action * StdCmdDescription::createAction() +Action* StdCmdDescription::createAction() { - Action *pcAction = Command::createAction(); - pcAction->setCheckable( true ); - return pcAction; + Action* pcAction = Command::createAction(); + pcAction->setCheckable(true); + return pcAction; } void StdCmdDescription::activated(int iMsg) { - Q_UNUSED(iMsg); - if ( !inDescriptionMode() ) - enterDescriptionMode(); - else - leaveDescriptionMode(); + Q_UNUSED(iMsg); + if (!inDescriptionMode()) { + enterDescriptionMode(); + } + else { + leaveDescriptionMode(); + } } bool StdCmdDescription::inDescriptionMode() { - return _descrMode; + return _descrMode; } -void StdCmdDescription::setSource( const QString& src ) +void StdCmdDescription::setSource(const QString& src) { - if ( !src.isEmpty() ) - { - QWhatsThisClickedEvent e(src); - QApplication::sendEvent(getMainWindow(), &e); - } + if (!src.isEmpty()) { + QWhatsThisClickedEvent e(src); + QApplication::sendEvent(getMainWindow(), &e); + } } void StdCmdDescription::enterDescriptionMode() { - _descrMode = true; - QApplication::setOverrideCursor(Qt::WhatsThisCursor); + _descrMode = true; + QApplication::setOverrideCursor(Qt::WhatsThisCursor); } void StdCmdDescription::leaveDescriptionMode() { - _descrMode = false; - QApplication::restoreOverrideCursor(); + _descrMode = false; + QApplication::restoreOverrideCursor(); } - diff --git a/src/Gui/WhatsThis.h b/src/Gui/WhatsThis.h index 8a0b4965cd..15ecdea18d 100644 --- a/src/Gui/WhatsThis.h +++ b/src/Gui/WhatsThis.h @@ -27,31 +27,32 @@ #include #include "Command.h" -namespace Gui { +namespace Gui +{ /** * @author Werner Mayer */ -class StdCmdDescription : public Command +class StdCmdDescription: public Command { public: - StdCmdDescription(); - ~StdCmdDescription() override; + StdCmdDescription(); + ~StdCmdDescription() override; - static bool inDescriptionMode(); - static void enterDescriptionMode(); - static void leaveDescriptionMode(); + static bool inDescriptionMode(); + static void enterDescriptionMode(); + static void leaveDescriptionMode(); - static void setSource( const QString& ); + static void setSource(const QString&); protected: - Action* createAction() override; - void activated(int iMsg) override; + Action* createAction() override; + void activated(int iMsg) override; private: - static bool _descrMode; + static bool _descrMode; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_WHATSTHIS_H +#endif // GUI_WHATSTHIS_H diff --git a/src/Gui/WidgetFactory.cpp b/src/Gui/WidgetFactory.cpp index ccc27860f5..025ef415f3 100644 --- a/src/Gui/WidgetFactory.cpp +++ b/src/Gui/WidgetFactory.cpp @@ -21,19 +21,18 @@ ***************************************************************************/ - -# include -# include +#include +#include #include #ifdef FC_OS_WIN32 -#undef max -#undef min -#ifdef _MSC_VER -#pragma warning( disable : 4099 ) -#pragma warning( disable : 4522 ) -#endif +# undef max +# undef min +# ifdef _MSC_VER +# pragma warning(disable : 4099) +# pragma warning(disable : 4522) +# endif #endif #include @@ -53,15 +52,17 @@ Gui::WidgetFactoryInst* Gui::WidgetFactoryInst::_pcSingleton = nullptr; WidgetFactoryInst& WidgetFactoryInst::instance() { - if (!_pcSingleton) + if (!_pcSingleton) { _pcSingleton = new WidgetFactoryInst; + } return *_pcSingleton; } -void WidgetFactoryInst::destruct () +void WidgetFactoryInst::destruct() { - if (_pcSingleton) + if (_pcSingleton) { delete _pcSingleton; + } _pcSingleton = nullptr; } @@ -70,7 +71,7 @@ void WidgetFactoryInst::destruct () * To create an instance of this widget once it must has been registered. * If there is no appropriate widget registered nullptr is returned. */ -QWidget* WidgetFactoryInst::createWidget (const char* sName, QWidget* parent) const +QWidget* WidgetFactoryInst::createWidget(const char* sName, QWidget* parent) const { auto w = static_cast(Produce(sName)); @@ -101,8 +102,9 @@ QWidget* WidgetFactoryInst::createWidget (const char* sName, QWidget* parent) co } // set the parent to the widget - if (parent) + if (parent) { w->setParent(parent); + } return w; } @@ -112,7 +114,10 @@ QWidget* WidgetFactoryInst::createWidget (const char* sName, QWidget* parent) co * To create an instance of this widget once it must has been registered. * If there is no appropriate widget registered nullptr is returned. */ -Gui::Dialog::PreferencePage* WidgetFactoryInst::createPreferencePage (const char* sName, QWidget* parent) const +Gui::Dialog::PreferencePage* WidgetFactoryInst::createPreferencePage( + const char* sName, + QWidget* parent +) const { auto w = (Gui::Dialog::PreferencePage*)Produce(sName); @@ -140,8 +145,9 @@ Gui::Dialog::PreferencePage* WidgetFactoryInst::createPreferencePage (const char } // set the parent to the widget - if (parent) + if (parent) { w->setParent(parent); + } return w; } @@ -157,8 +163,9 @@ QWidget* WidgetFactoryInst::createPrefWidget(const char* sName, QWidget* parent, { QWidget* w = createWidget(sName); // this widget class is not registered - if (!w) - return nullptr; // no valid QWidget object + if (!w) { + return nullptr; // no valid QWidget object + } // set the parent to the widget w->setParent(parent); @@ -185,11 +192,12 @@ QWidget* WidgetFactoryInst::createPrefWidget(const char* sName, QWidget* parent, WidgetFactorySupplier* WidgetFactorySupplier::_pcSingleton = nullptr; -WidgetFactorySupplier & WidgetFactorySupplier::instance() +WidgetFactorySupplier& WidgetFactorySupplier::instance() { // not initialized? - if (!_pcSingleton) + if (!_pcSingleton) { _pcSingleton = new WidgetFactorySupplier; + } return *_pcSingleton; } @@ -198,13 +206,13 @@ void WidgetFactorySupplier::destruct() // delete the widget factory and all its producers first WidgetFactoryInst::destruct(); delete _pcSingleton; - _pcSingleton=nullptr; + _pcSingleton = nullptr; } // ---------------------------------------------------- -PrefPageUiProducer::PrefPageUiProducer (const char* filename, const char* group) - : fn(QString::fromUtf8(filename)) +PrefPageUiProducer::PrefPageUiProducer(const char* filename, const char* group) + : fn(QString::fromUtf8(filename)) { WidgetFactoryInst::instance().AddProducer(filename, this); Gui::Dialog::DlgPreferencesImp::addPage(filename, group); @@ -212,7 +220,7 @@ PrefPageUiProducer::PrefPageUiProducer (const char* filename, const char* group) PrefPageUiProducer::~PrefPageUiProducer() = default; -void* PrefPageUiProducer::Produce () const +void* PrefPageUiProducer::Produce() const { QWidget* page = new Gui::Dialog::PreferenceUiForm(fn); return static_cast(page); @@ -220,8 +228,8 @@ void* PrefPageUiProducer::Produce () const // ---------------------------------------------------- -PrefPagePyProducer::PrefPagePyProducer (const Py::Object& p, const char* group) - : type(p) +PrefPagePyProducer::PrefPagePyProducer(const Py::Object& p, const char* group) + : type(p) { std::string str; Base::PyGILStateLocker lock; @@ -233,13 +241,13 @@ PrefPagePyProducer::PrefPagePyProducer (const Py::Object& p, const char* group) Gui::Dialog::DlgPreferencesImp::addPage(str, group); } -PrefPagePyProducer::~PrefPagePyProducer () +PrefPagePyProducer::~PrefPagePyProducer() { Base::PyGILStateLocker lock; type = Py::None(); } -void* PrefPagePyProducer::Produce () const +void* PrefPagePyProducer::Produce() const { Base::PyGILStateLocker lock; try { @@ -264,7 +272,8 @@ void* PrefPagePyProducer::Produce () const using namespace Gui::Dialog; PreferencePagePython::PreferencePagePython(const Py::Object& p, QWidget* parent) - : PreferencePage(parent), page(p) + : PreferencePage(parent) + , page(p) { Base::PyGILStateLocker lock; Gui::PythonWrapper wrap; @@ -273,10 +282,12 @@ PreferencePagePython::PreferencePagePython(const Py::Object& p, QWidget* parent) // old style class must have a form attribute while // new style classes can be the widget itself Py::Object widget; - if (page.hasAttr(std::string("form"))) + if (page.hasAttr(std::string("form"))) { widget = page.getAttr(std::string("form")); - else + } + else { widget = page; + } QObject* object = wrap.toQObject(widget); if (object) { @@ -297,7 +308,7 @@ PreferencePagePython::~PreferencePagePython() page = Py::None(); } -void PreferencePagePython::changeEvent(QEvent *e) +void PreferencePagePython::changeEvent(QEvent* e) { QWidget::changeEvent(e); } @@ -313,7 +324,7 @@ void PreferencePagePython::loadSettings() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -329,7 +340,7 @@ void PreferencePagePython::saveSettings() } } catch (Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -342,41 +353,41 @@ void PreferencePagePython::saveSettings() * Constructs a ContainerDialog which embeds the child \a templChild. * The dialog will be modal. */ -ContainerDialog::ContainerDialog( QWidget* templChild ) - : QDialog( QApplication::activeWindow()) +ContainerDialog::ContainerDialog(QWidget* templChild) + : QDialog(QApplication::activeWindow()) { setModal(true); - setWindowTitle( templChild->objectName() ); - setObjectName( templChild->objectName() ); + setWindowTitle(templChild->objectName()); + setObjectName(templChild->objectName()); - setSizeGripEnabled( true ); + setSizeGripEnabled(true); MyDialogLayout = new QGridLayout(this); buttonOk = new QPushButton(this); buttonOk->setObjectName(QLatin1String("buttonOK")); - buttonOk->setText( tr( "&OK" ) ); - buttonOk->setAutoDefault( true ); - buttonOk->setDefault( true ); + buttonOk->setText(tr("&OK")); + buttonOk->setAutoDefault(true); + buttonOk->setDefault(true); - MyDialogLayout->addWidget( buttonOk, 1, 0 ); - auto spacer = new QSpacerItem( 210, 20, QSizePolicy::Expanding, QSizePolicy::Minimum ); - MyDialogLayout->addItem( spacer, 1, 1 ); + MyDialogLayout->addWidget(buttonOk, 1, 0); + auto spacer = new QSpacerItem(210, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); + MyDialogLayout->addItem(spacer, 1, 1); buttonCancel = new QPushButton(this); buttonCancel->setObjectName(QLatin1String("buttonCancel")); - buttonCancel->setText( tr( "&Cancel" ) ); - buttonCancel->setAutoDefault( true ); + buttonCancel->setText(tr("&Cancel")); + buttonCancel->setAutoDefault(true); - MyDialogLayout->addWidget( buttonCancel, 1, 2 ); + MyDialogLayout->addWidget(buttonCancel, 1, 2); templChild->setParent(this); - MyDialogLayout->addWidget( templChild, 0, 0, 0, 2 ); - resize( QSize(307, 197).expandedTo(minimumSizeHint()) ); + MyDialogLayout->addWidget(templChild, 0, 0, 0, 2); + resize(QSize(307, 197).expandedTo(minimumSizeHint())); // signals and slots connections - connect( buttonOk, &QPushButton::clicked, this, &QDialog::accept); - connect( buttonCancel, &QPushButton::clicked, this, &QDialog::reject); + connect(buttonOk, &QPushButton::clicked, this, &QDialog::accept); + connect(buttonCancel, &QPushButton::clicked, this, &QDialog::reject); } /** Destroys the object and frees any allocated resources */ @@ -392,15 +403,15 @@ void PyResource::init_type() behaviors().supportRepr(); behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("value",&PyResource::value); - add_varargs_method("setValue",&PyResource::setValue); - add_varargs_method("show",&PyResource::show); - add_varargs_method("connect",&PyResource::connect); + add_varargs_method("value", &PyResource::value); + add_varargs_method("setValue", &PyResource::setValue); + add_varargs_method("show", &PyResource::show); + add_varargs_method("connect", &PyResource::connect); } -PyResource::PyResource() : myDlg(nullptr) -{ -} +PyResource::PyResource() + : myDlg(nullptr) +{} PyResource::~PyResource() { @@ -423,8 +434,8 @@ void PyResource::load(const char* name) // checks whether it's a relative path if (fi.isRelative()) { - QString cwd = QDir::currentPath (); - QString home= QDir(QString::fromStdString(App::Application::getHomePath())).path(); + QString cwd = QDir::currentPath(); + QString home = QDir(QString::fromStdString(App::Application::getHomePath())).path(); // search in cwd and home path for the file // @@ -435,15 +446,15 @@ void PyResource::load(const char* name) throw Base::FileSystemError(what.toUtf8().constData()); } else { - fi.setFile( QDir(home), fn ); + fi.setFile(QDir(home), fn); if (!fi.exists()) { QString what = QObject::tr("Cannot find file %1 neither in %2 nor in %3") - .arg(fn, cwd, home); + .arg(fn, cwd, home); throw Base::FileSystemError(what.toUtf8().constData()); } else { - fn = fi.absoluteFilePath(); // file resides in FreeCAD's home directory + fn = fi.absoluteFilePath(); // file resides in FreeCAD's home directory } } } @@ -455,20 +466,22 @@ void PyResource::load(const char* name) } } - QWidget* w=nullptr; + QWidget* w = nullptr; try { auto loader = UiLoader::newInstance(); QFile file(fn); - if (file.open(QFile::ReadOnly)) + if (file.open(QFile::ReadOnly)) { w = loader->load(&file, QApplication::activeWindow()); + } file.close(); } catch (...) { throw Base::RuntimeError("Cannot create resource"); } - if (!w) + if (!w) { throw Base::ValueError("Invalid widget."); + } if (w->inherits("QDialog")) { myDlg = static_cast(w); @@ -486,16 +499,17 @@ void PyResource::load(const char* name) */ bool PyResource::connect(const char* sender, const char* signal, PyObject* cb) { - if ( !myDlg ) + if (!myDlg) { return false; + } - QObject* objS=nullptr; + QObject* objS = nullptr; QList list = myDlg->findChildren(); QList::const_iterator it = list.cbegin(); - QObject *obj; + QObject* obj; QString sigStr = QStringLiteral("2%1").arg(QString::fromLatin1(signal)); - while ( it != list.cend() ) { + while (it != list.cend()) { obj = *it; ++it; if (obj->objectName() == QLatin1String(sender)) { @@ -507,10 +521,11 @@ bool PyResource::connect(const char* sender, const char* signal, PyObject* cb) if (objS) { auto sc = new SignalConnect(this, cb); mySignals.push_back(sc); - return QObject::connect(objS, sigStr.toLatin1(), sc, SLOT ( onExecute() ) ); + return QObject::connect(objS, sigStr.toLatin1(), sc, SLOT(onExecute())); + } + else { + qWarning("'%s' does not exist.\n", sender); } - else - qWarning( "'%s' does not exist.\n", sender ); return false; } @@ -527,19 +542,20 @@ Py::Object PyResource::repr() */ Py::Object PyResource::value(const Py::Tuple& args) { - char *psName; - char *psProperty; - if (!PyArg_ParseTuple(args.ptr(), "ss", &psName, &psProperty)) + char* psName; + char* psProperty; + if (!PyArg_ParseTuple(args.ptr(), "ss", &psName, &psProperty)) { throw Py::Exception(); + } QVariant v; if (myDlg) { QList list = myDlg->findChildren(); QList::const_iterator it = list.cbegin(); - QObject *obj; + QObject* obj; bool fnd = false; - while ( it != list.cend() ) { + while (it != list.cend()) { obj = *it; ++it; if (obj->objectName() == QLatin1String(psName)) { @@ -549,43 +565,42 @@ Py::Object PyResource::value(const Py::Tuple& args) } } - if ( !fnd ) - qWarning( "'%s' not found.\n", psName ); + if (!fnd) { + qWarning("'%s' not found.\n", psName); + } } Py::Object item = Py::None(); - switch (v.userType()) - { - case QMetaType::QStringList: - { + switch (v.userType()) { + case QMetaType::QStringList: { QStringList str = v.toStringList(); int nSize = str.count(); Py::List slist(nSize); - for (int i=0; i(v.toUInt())); - break; - case QMetaType::Int: - item = Py::Long(v.toInt()); - break; - default: - item = Py::String(""); - break; + } break; + case QMetaType::QByteArray: + break; + case QMetaType::QString: + item = Py::String(v.toString().toLatin1()); + break; + case QMetaType::Double: + item = Py::Float(v.toDouble()); + break; + case QMetaType::Bool: + item = Py::Boolean(v.toBool()); + break; + case QMetaType::UInt: + item = Py::Long(static_cast(v.toUInt())); + break; + case QMetaType::Int: + item = Py::Long(v.toInt()); + break; + default: + item = Py::String(""); + break; } return item; @@ -598,16 +613,16 @@ Py::Object PyResource::value(const Py::Tuple& args) */ Py::Object PyResource::setValue(const Py::Tuple& args) { - char *psName; - char *psProperty; - PyObject *psValue; - if (!PyArg_ParseTuple(args.ptr(), "ssO", &psName, &psProperty, &psValue)) + char* psName; + char* psProperty; + PyObject* psValue; + if (!PyArg_ParseTuple(args.ptr(), "ssO", &psName, &psProperty, &psValue)) { throw Py::Exception(); + } QVariant v; if (PyUnicode_Check(psValue)) { v = QString::fromUtf8(PyUnicode_AsUTF8(psValue)); - } else if (PyLong_Check(psValue)) { unsigned int val = PyLong_AsLong(psValue); @@ -619,10 +634,11 @@ Py::Object PyResource::setValue(const Py::Tuple& args) else if (PyList_Check(psValue)) { QStringList str; int nSize = PyList_Size(psValue); - for (int i=0; i list = myDlg->findChildren(); QList::const_iterator it = list.cbegin(); - QObject *obj; + QObject* obj; bool fnd = false; - while ( it != list.cend() ) { + while (it != list.cend()) { obj = *it; ++it; if (obj->objectName() == QLatin1String(psName)) { @@ -649,8 +665,9 @@ Py::Object PyResource::setValue(const Py::Tuple& args) } } - if (!fnd) - qWarning( "'%s' not found.\n", psName ); + if (!fnd) { + qWarning("'%s' not found.\n", psName); + } } return Py::None(); @@ -686,10 +703,10 @@ Py::Object PyResource::show(const Py::Tuple&) */ Py::Object PyResource::connect(const Py::Tuple& args) { - char *psSender; - char *psSignal; + char* psSender; + char* psSignal; - PyObject *temp; + PyObject* temp; if (PyArg_ParseTuple(args.ptr(), "ssO", &psSender, &psSignal, &temp)) { if (!PyCallable_Check(temp)) { @@ -697,13 +714,13 @@ Py::Object PyResource::connect(const Py::Tuple& args) throw Py::Exception(); } - Py_XINCREF(temp); /* Add a reference to new callback */ + Py_XINCREF(temp); /* Add a reference to new callback */ std::string sSender = psSender; std::string sSignal = psSignal; if (!connect(psSender, psSignal, temp)) { // no signal object found => dispose the callback object - Py_XDECREF(temp); /* Dispose of callback */ + Py_XDECREF(temp); /* Dispose of callback */ } return Py::None(); @@ -716,14 +733,14 @@ Py::Object PyResource::connect(const Py::Tuple& args) // ---------------------------------------------------- SignalConnect::SignalConnect(PyObject* res, PyObject* cb) - : myResource(res), myCallback(cb) -{ -} + : myResource(res) + , myCallback(cb) +{} SignalConnect::~SignalConnect() { Base::PyGILStateLocker lock; - Py_XDECREF(myCallback); /* Dispose of callback */ + Py_XDECREF(myCallback); /* Dispose of callback */ } /** @@ -731,8 +748,8 @@ SignalConnect::~SignalConnect() */ void SignalConnect::onExecute() { - PyObject *arglist; - PyObject *result; + PyObject* arglist; + PyObject* result; /* Time to call the callback */ arglist = Py_BuildValue("(O)", myResource); diff --git a/src/Gui/WidgetFactory.h b/src/Gui/WidgetFactory.h index 71418c48d5..f1705f4a2e 100644 --- a/src/Gui/WidgetFactory.h +++ b/src/Gui/WidgetFactory.h @@ -36,10 +36,12 @@ QT_BEGIN_NAMESPACE class QDir; QT_END_NAMESPACE -namespace Gui { - namespace Dialog{ - class PreferencePage; - } +namespace Gui +{ +namespace Dialog +{ +class PreferencePage; +} /** * The widget factory provides methods for the dynamic creation of widgets. @@ -48,14 +50,14 @@ namespace Gui { * preference page use PrefPageProducer instead. * \author Werner Mayer */ -class GuiExport WidgetFactoryInst : public Base::Factory +class GuiExport WidgetFactoryInst: public Base::Factory { public: static WidgetFactoryInst& instance(); - static void destruct (); + static void destruct(); - QWidget* createWidget (const char* sName, QWidget* parent=nullptr) const; - Gui::Dialog::PreferencePage* createPreferencePage (const char* sName, QWidget* parent=nullptr) const; + QWidget* createWidget(const char* sName, QWidget* parent = nullptr) const; + Gui::Dialog::PreferencePage* createPreferencePage(const char* sName, QWidget* parent = nullptr) const; QWidget* createPrefWidget(const char* sName, QWidget* parent, const char* sPref); private: @@ -77,25 +79,25 @@ inline WidgetFactoryInst& WidgetFactory() * the ability to create widgets dynamically. * \author Werner Mayer */ -template -class WidgetProducer : public Base::AbstractProducer +template +class WidgetProducer: public Base::AbstractProducer { public: /** * Register a special type of widget to the WidgetFactoryInst. */ - WidgetProducer () + WidgetProducer() { const char* cname = CLASS::staticMetaObject.className(); WidgetFactoryInst::instance().AddProducer(cname, this); } - ~WidgetProducer () override = default; + ~WidgetProducer() override = default; /** * Creates an instance of the specified widget. */ - void* Produce () const override + void* Produce() const override { return (new CLASS); } @@ -108,18 +110,19 @@ public: * the ability to create preference pages dynamically. * \author Werner Mayer */ -template -class PrefPageProducer : public Base::AbstractProducer +template +class PrefPageProducer: public Base::AbstractProducer { public: /** * Register a special type of preference page to the WidgetFactoryInst. */ - PrefPageProducer (const char* group) + PrefPageProducer(const char* group) { const char* cname = CLASS::staticMetaObject.className(); - if (strcmp(cname, Gui::Dialog::PreferencePage::staticMetaObject.className()) == 0) + if (strcmp(cname, Gui::Dialog::PreferencePage::staticMetaObject.className()) == 0) { qWarning("The class '%s' lacks of Q_OBJECT macro", typeid(CLASS).name()); + } if (WidgetFactoryInst::instance().CanProduce(cname)) { qWarning("The preference page class '%s' is already registered", cname); } @@ -129,12 +132,12 @@ public: } } - ~PrefPageProducer () override = default; + ~PrefPageProducer() override = default; /** * Creates an instance of the specified widget. */ - void* Produce () const override + void* Produce() const override { return (new CLASS); } @@ -145,18 +148,18 @@ public: * dynamically from an external UI file. * @author Werner Mayer */ -class GuiExport PrefPageUiProducer : public Base::AbstractProducer +class GuiExport PrefPageUiProducer: public Base::AbstractProducer { public: /** * Register a special type of preference page to the WidgetFactoryInst. */ - PrefPageUiProducer (const char* filename, const char* group); - ~PrefPageUiProducer () override; + PrefPageUiProducer(const char* filename, const char* group); + ~PrefPageUiProducer() override; /** * Creates an instance of the specified widget. */ - void* Produce () const override; + void* Produce() const override; private: QString fn; @@ -167,18 +170,18 @@ private: * dynamically from a Python class. * @author Werner Mayer */ -class GuiExport PrefPagePyProducer : public Base::AbstractProducer +class GuiExport PrefPagePyProducer: public Base::AbstractProducer { public: /** * Register a special type of preference page to the WidgetFactoryInst. */ - PrefPagePyProducer (const Py::Object&, const char* group); - ~PrefPagePyProducer () override; + PrefPagePyProducer(const Py::Object&, const char* group); + ~PrefPagePyProducer() override; /** * Creates an instance of the specified widget. */ - void* Produce () const override; + void* Produce() const override; private: Py::Object type; @@ -191,18 +194,19 @@ private: * the ability to create custom pages dynamically. * \author Werner Mayer */ -template -class CustomPageProducer : public Base::AbstractProducer +template +class CustomPageProducer: public Base::AbstractProducer { public: /** * Register a special type of customize page to the WidgetFactoryInst. */ - CustomPageProducer () + CustomPageProducer() { const char* cname = CLASS::staticMetaObject.className(); - if (strcmp(cname, Gui::Dialog::CustomizeActionPage::staticMetaObject.className()) == 0) + if (strcmp(cname, Gui::Dialog::CustomizeActionPage::staticMetaObject.className()) == 0) { qWarning("The class '%s' lacks of Q_OBJECT macro", typeid(CLASS).name()); + } if (WidgetFactoryInst::instance().CanProduce(cname)) { qWarning("The preference page class '%s' is already registered", cname); } @@ -212,12 +216,12 @@ public: } } - ~CustomPageProducer () override = default; + ~CustomPageProducer() override = default; /** * Creates an instance of the specified widget. */ - void* Produce () const override + void* Produce() const override { return (new CLASS); } @@ -235,15 +239,15 @@ class WidgetFactorySupplier private: // Singleton WidgetFactorySupplier(); - static WidgetFactorySupplier *_pcSingleton; + static WidgetFactorySupplier* _pcSingleton; public: - static WidgetFactorySupplier &instance(); + static WidgetFactorySupplier& instance(); static void destruct(); - friend WidgetFactorySupplier &GetWidgetFactorySupplier(); + friend WidgetFactorySupplier& GetWidgetFactorySupplier(); }; -inline WidgetFactorySupplier &GetWidgetFactorySupplier() +inline WidgetFactorySupplier& GetWidgetFactorySupplier() { return WidgetFactorySupplier::instance(); } @@ -256,15 +260,15 @@ inline WidgetFactorySupplier &GetWidgetFactorySupplier() * At most this class is used to embed widgets which are created from .ui files. * \author Werner Mayer */ -class ContainerDialog : public QDialog +class ContainerDialog: public QDialog { Q_OBJECT public: - ContainerDialog( QWidget* templChild ); + ContainerDialog(QWidget* templChild); ~ContainerDialog() override; - QPushButton* buttonOk; /**< The Ok button. */ + QPushButton* buttonOk; /**< The Ok button. */ QPushButton* buttonCancel; /**< The cancel button. */ private: @@ -326,10 +330,10 @@ private: * \author Werner Mayer */ -class PyResource : public Py::PythonExtension +class PyResource: public Py::PythonExtension { public: - static void init_type(); // announce properties and methods + static void init_type(); // announce properties and methods PyResource(); ~PyResource() override; @@ -355,7 +359,7 @@ private: * This mechanism is used in the Python/Qt framework. * \author Werner Mayer */ -class SignalConnect : public QObject +class SignalConnect: public QObject { Q_OBJECT @@ -372,12 +376,13 @@ private: }; // ---------------------------------------------------- -namespace Dialog { +namespace Dialog +{ /** Subclass that embeds a form from a Python class. * \author Werner Mayer */ -class GuiExport PreferencePagePython : public PreferencePage +class GuiExport PreferencePagePython: public PreferencePage { Q_OBJECT @@ -389,14 +394,14 @@ public: void saveSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: Py::Object page; }; -} // namespace Dialog +} // namespace Dialog -} // namespace Gui +} // namespace Gui -#endif // GUI_WIDGETFACTORY_H +#endif // GUI_WIDGETFACTORY_H diff --git a/src/Gui/Widgets.cpp b/src/Gui/Widgets.cpp index aab896e269..bd3e6ffead 100644 --- a/src/Gui/Widgets.cpp +++ b/src/Gui/Widgets.cpp @@ -21,22 +21,21 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -63,22 +62,21 @@ using namespace Base; /** * Constructs an empty command view with parent \a parent. */ -CommandIconView::CommandIconView ( QWidget * parent ) - : QListWidget(parent) +CommandIconView::CommandIconView(QWidget* parent) + : QListWidget(parent) { - connect(this, &QListWidget::currentItemChanged, - this, &CommandIconView::onSelectionChanged); + connect(this, &QListWidget::currentItemChanged, this, &CommandIconView::onSelectionChanged); } /** * Destroys the icon view and deletes all items. */ -CommandIconView::~CommandIconView () = default; +CommandIconView::~CommandIconView() = default; /** * Stores the name of the selected commands for drag and drop. */ -void CommandIconView::startDrag (Qt::DropActions supportedActions) +void CommandIconView::startDrag(Qt::DropActions supportedActions) { Q_UNUSED(supportedActions); QList items = selectedItems(); @@ -88,8 +86,9 @@ void CommandIconView::startDrag (Qt::DropActions supportedActions) QPixmap pixmap; dataStream << items.count(); for (QList::Iterator it = items.begin(); it != items.end(); ++it) { - if (it == items.begin()) + if (it == items.begin()) { pixmap = ((*it)->data(Qt::UserRole)).value(); + } dataStream << (*it)->text(); } @@ -98,7 +97,7 @@ void CommandIconView::startDrag (Qt::DropActions supportedActions) auto drag = new QDrag(this); drag->setMimeData(mimeData); - drag->setHotSpot(QPoint(pixmap.width()/2, pixmap.height()/2)); + drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2)); drag->setPixmap(pixmap); drag->exec(Qt::MoveAction); } @@ -108,10 +107,11 @@ void CommandIconView::startDrag (Qt::DropActions supportedActions) * (or 0 if no item is now current). This slot emits the emitSelectionChanged() * signal for its part. */ -void CommandIconView::onSelectionChanged(QListWidgetItem * item, QListWidgetItem *) +void CommandIconView::onSelectionChanged(QListWidgetItem* item, QListWidgetItem*) { - if (item) + if (item) { Q_EMIT emitSelectionChanged(item->toolTip()); + } } // ------------------------------------------------------------------------------ @@ -119,7 +119,7 @@ void CommandIconView::onSelectionChanged(QListWidgetItem * item, QListWidgetItem /* TRANSLATOR Gui::ActionSelector */ ActionSelector::ActionSelector(QWidget* parent) - : QWidget(parent) + : QWidget(parent) { addButton = new QPushButton(this); addButton->setObjectName(QLatin1String("addButton")); @@ -247,23 +247,22 @@ void ActionSelector::changeEvent(QEvent* event) void ActionSelector::keyPressEvent(QKeyEvent* event) { if ((event->modifiers() & Qt::ControlModifier)) { - switch (event->key()) - { - case Qt::Key_Right: - onAddButtonClicked(); - break; - case Qt::Key_Left: - onRemoveButtonClicked(); - break; - case Qt::Key_Up: - onUpButtonClicked(); - break; - case Qt::Key_Down: - onDownButtonClicked(); - break; - default: - event->ignore(); - return; + switch (event->key()) { + case Qt::Key_Right: + onAddButtonClicked(); + break; + case Qt::Key_Left: + onRemoveButtonClicked(); + break; + case Qt::Key_Up: + onUpButtonClicked(); + break; + case Qt::Key_Down: + onDownButtonClicked(); + break; + default: + event->ignore(); + return; } } } @@ -273,8 +272,11 @@ void ActionSelector::setButtonsEnabled() addButton->setEnabled(availableWidget->indexOfTopLevelItem(availableWidget->currentItem()) > -1); removeButton->setEnabled(selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > -1); upButton->setEnabled(selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > 0); - downButton->setEnabled(selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > -1 && - selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) < selectedWidget->topLevelItemCount() - 1); + downButton->setEnabled( + selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) > -1 + && selectedWidget->indexOfTopLevelItem(selectedWidget->currentItem()) + < selectedWidget->topLevelItemCount() - 1 + ); } void ActionSelector::onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*) @@ -282,7 +284,7 @@ void ActionSelector::onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*) setButtonsEnabled(); } -void ActionSelector::onItemDoubleClicked(QTreeWidgetItem * item, int column) +void ActionSelector::onItemDoubleClicked(QTreeWidgetItem* item, int column) { Q_UNUSED(column); QTreeWidget* treeWidget = item->treeWidget(); @@ -333,7 +335,7 @@ void ActionSelector::onUpButtonClicked() int index = selectedWidget->indexOfTopLevelItem(item); if (index > 0) { selectedWidget->takeTopLevelItem(index); - selectedWidget->insertTopLevelItem(index-1, item); + selectedWidget->insertTopLevelItem(index - 1, item); selectedWidget->setCurrentItem(item); } } @@ -344,9 +346,9 @@ void ActionSelector::onDownButtonClicked() QTreeWidgetItem* item = selectedWidget->currentItem(); if (item && item->isSelected()) { int index = selectedWidget->indexOfTopLevelItem(item); - if (index < selectedWidget->topLevelItemCount()-1) { + if (index < selectedWidget->topLevelItemCount() - 1) { selectedWidget->takeTopLevelItem(index); - selectedWidget->insertTopLevelItem(index+1, item); + selectedWidget->insertTopLevelItem(index + 1, item); selectedWidget->setCurrentItem(item); } } @@ -361,7 +363,7 @@ void ActionSelector::onDownButtonClicked() * The \a parent argument is sent to the QKeySequenceEdit constructor. */ AccelLineEdit::AccelLineEdit(QWidget* parent) - : QKeySequenceEdit(parent) + : QKeySequenceEdit(parent) { if (auto le = findChild()) { le->setClearButtonEnabled(true); @@ -369,7 +371,7 @@ AccelLineEdit::AccelLineEdit(QWidget* parent) } AccelLineEdit::AccelLineEdit(const QKeySequence& keySequence, QWidget* parent) - : QKeySequenceEdit(keySequence, parent) + : QKeySequenceEdit(keySequence, parent) { if (auto le = findChild()) { le->setClearButtonEnabled(true); @@ -401,8 +403,8 @@ QString AccelLineEdit::text() const * Constructs a line edit with no text. * The \a parent argument is sent to the QLineEdit constructor. */ -ModifierLineEdit::ModifierLineEdit (QWidget * parent ) - : QLineEdit(parent) +ModifierLineEdit::ModifierLineEdit(QWidget* parent) + : QLineEdit(parent) { setPlaceholderText(tr("Press modifier keys")); } @@ -410,23 +412,23 @@ ModifierLineEdit::ModifierLineEdit (QWidget * parent ) /** * Checks which modifiers are pressed and show it as text. */ -void ModifierLineEdit::keyPressEvent (QKeyEvent * e) +void ModifierLineEdit::keyPressEvent(QKeyEvent* e) { int key = e->key(); Qt::KeyboardModifiers state = e->modifiers(); switch (key) { - case Qt::Key_Backspace: - case Qt::Key_Delete: - clear(); - return; - case Qt::Key_Control: - case Qt::Key_Shift: - case Qt::Key_Alt: - case Qt::Key_Meta: - break; - default: - return; + case Qt::Key_Backspace: + case Qt::Key_Delete: + clear(); + return; + case Qt::Key_Control: + case Qt::Key_Shift: + case Qt::Key_Alt: + case Qt::Key_Meta: + break; + default: + return; } clear(); @@ -455,16 +457,18 @@ void ModifierLineEdit::keyPressEvent (QKeyEvent * e) // ------------------------------------------------------------------------------ -ClearLineEdit::ClearLineEdit (QWidget * parent) - : QLineEdit(parent) +ClearLineEdit::ClearLineEdit(QWidget* parent) + : QLineEdit(parent) { - clearAction = this->addAction(QIcon(QStringLiteral(":/icons/edit-cleartext.svg")), - QLineEdit::TrailingPosition); + clearAction = this->addAction( + QIcon(QStringLiteral(":/icons/edit-cleartext.svg")), + QLineEdit::TrailingPosition + ); connect(clearAction, &QAction::triggered, this, &ClearLineEdit::clear); connect(this, &QLineEdit::textChanged, this, &ClearLineEdit::updateClearButton); } -void ClearLineEdit::resizeEvent(QResizeEvent *e) +void ClearLineEdit::resizeEvent(QResizeEvent* e) { QLineEdit::resizeEvent(e); } @@ -485,8 +489,8 @@ void ClearLineEdit::updateClearButton(const QString& text) * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -CheckListDialog::CheckListDialog( QWidget* parent, Qt::WindowFlags fl ) - : QDialog( parent, fl ) +CheckListDialog::CheckListDialog(QWidget* parent, Qt::WindowFlags fl) + : QDialog(parent, fl) , ui(new Ui_DlgTreeWidget) { ui->setupUi(this); @@ -500,9 +504,9 @@ CheckListDialog::~CheckListDialog() = default; /** * Sets the items to the dialog's list view. By default all items are checkable.. */ -void CheckListDialog::setCheckableItems( const QStringList& items ) +void CheckListDialog::setCheckableItems(const QStringList& items) { - for (const auto & it : items) { + for (const auto& it : items) { auto item = new QTreeWidgetItem(ui->treeWidget); item->setText(0, it); item->setCheckState(0, Qt::Unchecked); @@ -513,12 +517,12 @@ void CheckListDialog::setCheckableItems( const QStringList& items ) * Sets the items to the dialog's list view. If the boolean type of a CheckListItem * is set to false the item is not checkable any more. */ -void CheckListDialog::setCheckableItems( const QList& items ) +void CheckListDialog::setCheckableItems(const QList& items) { - for (const auto & it : items) { + for (const auto& it : items) { auto item = new QTreeWidgetItem(ui->treeWidget); item->setText(0, it.first); - item->setCheckState(0, ( it.second ? Qt::Checked : Qt::Unchecked)); + item->setCheckState(0, (it.second ? Qt::Checked : Qt::Unchecked)); } } @@ -533,7 +537,7 @@ QStringList CheckListDialog::getCheckedItems() const /** * Collects all checked items to be able to return them by call \ref getCheckedItems(). */ -void CheckListDialog::accept () +void CheckListDialog::accept() { QTreeWidgetItemIterator it(ui->treeWidget, QTreeWidgetItemIterator::Checked); while (*it) { @@ -546,18 +550,19 @@ void CheckListDialog::accept () // ------------------------------------------------------------------------------ -namespace Gui { +namespace Gui +{ struct ColorButtonP { QColor old, col; QPointer cd; - bool allowChange{true}; - bool autoChange{false}; - bool drawFrame{true}; - bool allowTransparency{false}; - bool modal{true}; + bool allowChange {true}; + bool autoChange {false}; + bool drawFrame {true}; + bool allowTransparency {false}; + bool modal {true}; }; -} +} // namespace Gui /** * Constructs a colored button called \a name with parent \a parent. @@ -566,11 +571,11 @@ ColorButton::ColorButton(QWidget* parent) : QPushButton(parent) { d = new ColorButtonP(); - d->col = palette().color(QPalette::Active,QPalette::Midlight); + d->col = palette().color(QPalette::Active, QPalette::Midlight); connect(this, &ColorButton::clicked, this, &ColorButton::onChooseColor); int e = style()->pixelMetric(QStyle::PM_ButtonIconSize); - setIconSize(QSize(2*e, e)); + setIconSize(QSize(2 * e, e)); } /** @@ -644,16 +649,19 @@ bool ColorButton::drawFrame() const void Gui::ColorButton::setAllowTransparency(bool allow) { d->allowTransparency = allow; - if (d->cd) + if (d->cd) { d->cd->setOption(QColorDialog::ColorDialogOption::ShowAlphaChannel, allow); + } } bool Gui::ColorButton::allowTransparency() const { - if (d->cd) + if (d->cd) { return d->cd->testOption(QColorDialog::ColorDialogOption::ShowAlphaChannel); - else + } + else { return d->allowTransparency; + } } void ColorButton::setModal(bool b) @@ -679,7 +687,7 @@ bool ColorButton::autoChangeColor() const /** * Draws the button label. */ -void ColorButton::paintEvent (QPaintEvent * e) +void ColorButton::paintEvent(QPaintEvent* e) { QPushButton::paintEvent(e); @@ -689,7 +697,7 @@ void ColorButton::paintEvent (QPaintEvent * e) colorRect.moveCenter(buttonCenter); // move colorRect to center of button QPainter painter(this); - if(d->drawFrame) { + if (d->drawFrame) { // frame is drawn on the outside of rectangle // so we need to adjust to get same size as for non-frame button constexpr qreal strokeWidth = 2; @@ -710,8 +718,9 @@ void ColorButton::showModeless() QColorDialog* dlg = new QColorDialog(d->col, this); dlg->setAttribute(Qt::WA_DeleteOnClose); - if (DialogOptions::dontUseNativeColorDialog()) + if (DialogOptions::dontUseNativeColorDialog()) { dlg->setOptions(QColorDialog::DontUseNativeDialog); + } dlg->setOption(QColorDialog::ColorDialogOption::ShowAlphaChannel, d->allowTransparency); dlg->setCurrentColor(d->old); connect(dlg, &QColorDialog::rejected, this, &ColorButton::onRejected); @@ -726,8 +735,9 @@ void ColorButton::showModal() QColor currentColor = d->col; QColorDialog* dlg = new QColorDialog(d->col, this); dlg->setAttribute(Qt::WA_DeleteOnClose); - if (DialogOptions::dontUseNativeColorDialog()) + if (DialogOptions::dontUseNativeColorDialog()) { dlg->setOptions(QColorDialog::DontUseNativeDialog); + } dlg->setOption(QColorDialog::ColorDialogOption::ShowAlphaChannel, d->allowTransparency); if (d->autoChange) { @@ -765,8 +775,9 @@ void ColorButton::showModal() */ void ColorButton::onChooseColor() { - if (!d->allowChange) + if (!d->allowChange) { return; + } if (d->modal) { showModal(); } @@ -791,13 +802,14 @@ void ColorButton::onRejected() UrlLabel::UrlLabel(QWidget* parent, Qt::WindowFlags f) : QLabel(parent, f) - , _url (QStringLiteral("http://localhost")) + , _url(QStringLiteral("http://localhost")) , _launchExternal(true) { setToolTip(this->_url); setCursor(Qt::PointingHandCursor); - if (qApp->styleSheet().isEmpty()) + if (qApp->styleSheet().isEmpty()) { setStyleSheet(QStringLiteral("Gui--UrlLabel {color: #0000FF;text-decoration: underline;}")); + } } UrlLabel::~UrlLabel() = default; @@ -809,11 +821,13 @@ void Gui::UrlLabel::setLaunchExternal(bool l) void UrlLabel::mouseReleaseEvent(QMouseEvent*) { - if (_launchExternal) + if (_launchExternal) { QDesktopServices::openUrl(this->_url); - else + } + else { // Someone else will deal with it... Q_EMIT linkClicked(_url); + } } QString UrlLabel::url() const @@ -839,14 +853,17 @@ StatefulLabel::StatefulLabel(QWidget* parent) , _overridePreference(false) { // Always attach to the parameter group that stores the main FreeCAD stylesheet - _stylesheetGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General"); + _stylesheetGroup = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/General" + ); _stylesheetGroup->Attach(this); } StatefulLabel::~StatefulLabel() { - if (_parameterGroup.isValid()) + if (_parameterGroup.isValid()) { _parameterGroup->Detach(this); + } _stylesheetGroup->Detach(this); } @@ -857,40 +874,67 @@ void StatefulLabel::setDefaultStyle(const QString& defaultStyle) void StatefulLabel::setParameterGroup(const std::string& groupName) { - if (_parameterGroup.isValid()) + if (_parameterGroup.isValid()) { _parameterGroup->Detach(this); + } // Attach to the Parametergroup so we know when it changes _parameterGroup = App::GetApplication().GetParameterGroupByPath(groupName.c_str()); - if (_parameterGroup.isValid()) + if (_parameterGroup.isValid()) { _parameterGroup->Attach(this); + } } -void StatefulLabel::registerState(const QString& state, const QString& styleCSS, - const std::string& preferenceName) +void StatefulLabel::registerState( + const QString& state, + const QString& styleCSS, + const std::string& preferenceName +) { - _availableStates[state] = { styleCSS, preferenceName }; + _availableStates[state] = {styleCSS, preferenceName}; } -void StatefulLabel::registerState(const QString& state, const QColor& color, - const std::string& preferenceName) +void StatefulLabel::registerState( + const QString& state, + const QColor& color, + const std::string& preferenceName +) { QString css; - if (color.isValid()) - css = QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}").arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha()); - _availableStates[state] = { css, preferenceName }; + if (color.isValid()) { + css = QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}") + .arg(color.red()) + .arg(color.green()) + .arg(color.blue()) + .arg(color.alpha()); + } + _availableStates[state] = {css, preferenceName}; } -void StatefulLabel::registerState(const QString& state, const QColor& fg, const QColor& bg, - const std::string& preferenceName) +void StatefulLabel::registerState( + const QString& state, + const QColor& fg, + const QColor& bg, + const std::string& preferenceName +) { QString colorEntries; - if (fg.isValid()) - colorEntries.append(QStringLiteral("color : rgba(%1,%2,%3,%4);").arg(fg.red()).arg(fg.green()).arg(fg.blue()).arg(fg.alpha())); - if (bg.isValid()) - colorEntries.append(QStringLiteral("background-color : rgba(%1,%2,%3,%4);").arg(bg.red()).arg(bg.green()).arg(bg.blue()).arg(bg.alpha())); + if (fg.isValid()) { + colorEntries.append(QStringLiteral("color : rgba(%1,%2,%3,%4);") + .arg(fg.red()) + .arg(fg.green()) + .arg(fg.blue()) + .arg(fg.alpha())); + } + if (bg.isValid()) { + colorEntries.append(QStringLiteral("background-color : rgba(%1,%2,%3,%4);") + .arg(bg.red()) + .arg(bg.green()) + .arg(bg.blue()) + .arg(bg.alpha())); + } QString css = QStringLiteral("Gui--StatefulLabel{ %1 }").arg(colorEntries); - _availableStates[state] = { css, preferenceName }; + _availableStates[state] = {css, preferenceName}; } /** Observes the parameter group and clears the cache if it changes */ @@ -922,8 +966,9 @@ void StatefulLabel::setState(QString state) // If the stylesheet insists, ignore all other logic and let it do its thing. This // property is *only* set by the stylesheet. - if (_overridePreference) + if (_overridePreference) { return; + } // Check the cache first: if (auto style = _styleCache.find(_state); style != _styleCache.end()) { @@ -938,13 +983,19 @@ void StatefulLabel::setState(QString state) // First, try to see if it's just stored a color (as an unsigned int): auto availableColorPrefs = _parameterGroup->GetUnsignedMap(); std::string lookingForGroup = entry->second.preferenceString; - for (const auto &unsignedEntry : availableColorPrefs) { + for (const auto& unsignedEntry : availableColorPrefs) { std::string foundGroup = unsignedEntry.first; if (unsignedEntry.first == entry->second.preferenceString) { // Convert the stored Uint into usable color data: unsigned int col = unsignedEntry.second; QColor qcolor(Base::Color::fromPackedRGB(col)); - this->setStyleSheet(QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}").arg(qcolor.red()).arg(qcolor.green()).arg(qcolor.blue()).arg(qcolor.alpha())); + this->setStyleSheet( + QStringLiteral("Gui--StatefulLabel{ color : rgba(%1,%2,%3,%4) ;}") + .arg(qcolor.red()) + .arg(qcolor.green()) + .arg(qcolor.blue()) + .arg(qcolor.alpha()) + ); _styleCache[state] = this->styleSheet(); return; } @@ -954,7 +1005,8 @@ void StatefulLabel::setState(QString state) auto availableStringPrefs = _parameterGroup->GetASCIIMap(); for (const auto& stringEntry : availableStringPrefs) { if (stringEntry.first == entry->second.preferenceString) { - QString css = QStringLiteral("Gui--StatefulLabel{ %1 }").arg(QString::fromStdString(stringEntry.second)); + QString css = QStringLiteral("Gui--StatefulLabel{ %1 }") + .arg(QString::fromStdString(stringEntry.second)); this->setStyleSheet(css); _styleCache[state] = this->styleSheet(); return; @@ -962,8 +1014,8 @@ void StatefulLabel::setState(QString state) } } - // If there is no preferences entry for this label, allow the stylesheet to set it, and only set to the default - // formatting if there is no stylesheet entry + // If there is no preferences entry for this label, allow the stylesheet to set it, and only + // set to the default formatting if there is no stylesheet entry if (qApp->styleSheet().isEmpty()) { this->setStyleSheet(entry->second.defaultCSS); _styleCache[state] = this->styleSheet(); @@ -990,8 +1042,8 @@ void StatefulLabel::setState(QString state) /** * Constructs a file chooser called \a name with the parent \a parent. */ -LabelButton::LabelButton (QWidget * parent) - : QWidget(parent) +LabelButton::LabelButton(QWidget* parent) + : QWidget(parent) { auto layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); @@ -1002,8 +1054,8 @@ LabelButton::LabelButton (QWidget * parent) layout->addWidget(label); button = new QPushButton(QStringLiteral("…"), this); -#if defined (Q_OS_MACOS) - button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct +#if defined(Q_OS_MACOS) + button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct #endif layout->addWidget(button); @@ -1019,12 +1071,12 @@ void LabelButton::resizeEvent(QResizeEvent* e) button->setFixedHeight(e->size().height()); } -QLabel *LabelButton::getLabel() const +QLabel* LabelButton::getLabel() const { return label; } -QPushButton *LabelButton::getButton() const +QPushButton* LabelButton::getButton() const { return button; } @@ -1047,8 +1099,7 @@ void LabelButton::showValue(const QVariant& data) } void LabelButton::browse() -{ -} +{} // ---------------------------------------------------------------------- @@ -1056,34 +1107,38 @@ ToolTip* ToolTip::inst = nullptr; ToolTip* ToolTip::instance() { - if (!inst) + if (!inst) { inst = new ToolTip(); + } return inst; } -ToolTip::ToolTip() : installed(false), hidden(true) -{ -} +ToolTip::ToolTip() + : installed(false) + , hidden(true) +{} ToolTip::~ToolTip() = default; void ToolTip::installEventFilter() { - if (this->installed) + if (this->installed) { return; + } qApp->installEventFilter(this); this->installed = true; } void ToolTip::removeEventFilter() { - if (!this->installed) + if (!this->installed) { return; + } qApp->removeEventFilter(this); this->installed = false; } -void ToolTip::showText(const QPoint & pos, const QString & text, QWidget * w) +void ToolTip::showText(const QPoint& pos, const QString& text, QWidget* w) { ToolTip* tip = instance(); if (!text.isEmpty()) { @@ -1108,7 +1163,7 @@ void ToolTip::hideText() QToolTip::hideText(); } -void ToolTip::timerEvent(QTimerEvent *e) +void ToolTip::timerEvent(QTimerEvent* e) { if (e->timerId() == tooltipTimer.timerId()) { QToolTip::showText(pos, text, w); @@ -1117,47 +1172,49 @@ void ToolTip::timerEvent(QTimerEvent *e) } } -bool ToolTip::eventFilter(QObject* o, QEvent*e) +bool ToolTip::eventFilter(QObject* o, QEvent* e) { - if (!o->isWidgetType()) + if (!o->isWidgetType()) { return false; - switch(e->type()) { - case QEvent::MouseButtonPress: - hideText(); - break; - case QEvent::KeyPress: - if (static_cast(e)->key() == Qt::Key_Escape) + } + switch (e->type()) { + case QEvent::MouseButtonPress: hideText(); - break; - case QEvent::Leave: - hideText(); - break; - case QEvent::Timer: - case QEvent::Show: - case QEvent::Hide: - if (auto label = qobject_cast(o)) { - if (label->objectName() == QStringLiteral("qtooltip_label")) { - // This is a trick to circumvent that the tooltip gets hidden immediately - // after it gets visible. We just filter out all timer events to keep the - // label visible. + break; + case QEvent::KeyPress: + if (static_cast(e)->key() == Qt::Key_Escape) { + hideText(); + } + break; + case QEvent::Leave: + hideText(); + break; + case QEvent::Timer: + case QEvent::Show: + case QEvent::Hide: + if (auto label = qobject_cast(o)) { + if (label->objectName() == QStringLiteral("qtooltip_label")) { + // This is a trick to circumvent that the tooltip gets hidden immediately + // after it gets visible. We just filter out all timer events to keep the + // label visible. - // Ignore the timer events to prevent from being closed - if (e->type() == QEvent::Show) { - this->hidden = false; - } - else if (e->type() == QEvent::Hide) { - // removeEventFilter(); - this->hidden = true; - } - else if (e->type() == QEvent::Timer && - !this->hidden && displayTime.elapsed() < 5000) { - return true; + // Ignore the timer events to prevent from being closed + if (e->type() == QEvent::Show) { + this->hidden = false; + } + else if (e->type() == QEvent::Hide) { + // removeEventFilter(); + this->hidden = true; + } + else if (e->type() == QEvent::Timer && !this->hidden + && displayTime.elapsed() < 5000) { + return true; + } } } - } - break; - default: - break; + break; + default: + break; } return false; } @@ -1165,7 +1222,7 @@ bool ToolTip::eventFilter(QObject* o, QEvent*e) // ---------------------------------------------------------------------- StatusWidget::StatusWidget(QWidget* parent) - : QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint) + : QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint) { label = new QLabel(this); label->setAlignment(Qt::AlignCenter); @@ -1194,9 +1251,9 @@ void StatusWidget::showText(int ms) hide(); } -QSize StatusWidget::sizeHint () const +QSize StatusWidget::sizeHint() const { - return {250,100}; + return {250, 100}; } void StatusWidget::showEvent(QShowEvent* event) @@ -1205,41 +1262,42 @@ void StatusWidget::showEvent(QShowEvent* event) } void StatusWidget::hideEvent(QHideEvent*) -{ -} +{} // -------------------------------------------------------------------- -class LineNumberArea : public QWidget +class LineNumberArea: public QWidget { public: - explicit LineNumberArea(PropertyListEditor *editor) : QWidget(editor) { + explicit LineNumberArea(PropertyListEditor* editor) + : QWidget(editor) + { codeEditor = editor; } - QSize sizeHint() const override { + QSize sizeHint() const override + { return {codeEditor->lineNumberAreaWidth(), 0}; } protected: - void paintEvent(QPaintEvent *event) override { + void paintEvent(QPaintEvent* event) override + { codeEditor->lineNumberAreaPaintEvent(event); } private: - PropertyListEditor *codeEditor; + PropertyListEditor* codeEditor; }; -PropertyListEditor::PropertyListEditor(QWidget *parent) : QPlainTextEdit(parent) +PropertyListEditor::PropertyListEditor(QWidget* parent) + : QPlainTextEdit(parent) { lineNumberArea = new LineNumberArea(this); - connect(this, &QPlainTextEdit::blockCountChanged, - this, &PropertyListEditor::updateLineNumberAreaWidth); - connect(this, &QPlainTextEdit::updateRequest, - this, &PropertyListEditor::updateLineNumberArea); - connect(this, &QPlainTextEdit::cursorPositionChanged, - this, &PropertyListEditor::highlightCurrentLine); + connect(this, &QPlainTextEdit::blockCountChanged, this, &PropertyListEditor::updateLineNumberAreaWidth); + connect(this, &QPlainTextEdit::updateRequest, this, &PropertyListEditor::updateLineNumberArea); + connect(this, &QPlainTextEdit::cursorPositionChanged, this, &PropertyListEditor::highlightCurrentLine); updateLineNumberAreaWidth(0); highlightCurrentLine(); @@ -1264,18 +1322,21 @@ void PropertyListEditor::updateLineNumberAreaWidth(int /* newBlockCount */) setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); } -void PropertyListEditor::updateLineNumberArea(const QRect &rect, int dy) +void PropertyListEditor::updateLineNumberArea(const QRect& rect, int dy) { - if (dy) + if (dy) { lineNumberArea->scroll(0, dy); - else + } + else { lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); + } - if (rect.contains(viewport()->rect())) + if (rect.contains(viewport()->rect())) { updateLineNumberAreaWidth(0); + } } -void PropertyListEditor::resizeEvent(QResizeEvent *e) +void PropertyListEditor::resizeEvent(QResizeEvent* e) { QPlainTextEdit::resizeEvent(e); @@ -1302,39 +1363,39 @@ void PropertyListEditor::highlightCurrentLine() setExtraSelections(extraSelections); } -void PropertyListEditor::lineNumberAreaPaintEvent(QPaintEvent *event) +void PropertyListEditor::lineNumberAreaPaintEvent(QPaintEvent* event) { QPainter painter(lineNumberArea); painter.fillRect(event->rect(), Qt::lightGray); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); - int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); - int bottom = top + (int) blockBoundingRect(block).height(); + int top = (int)blockBoundingGeometry(block).translated(contentOffset()).top(); + int bottom = top + (int)blockBoundingRect(block).height(); while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(Qt::black); - painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), - Qt::AlignRight, number); + painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(), Qt::AlignRight, number); } block = block.next(); top = bottom; - bottom = top + (int) blockBoundingRect(block).height(); + bottom = top + (int)blockBoundingRect(block).height(); ++blockNumber; } } -class PropertyListDialog : public QDialog +class PropertyListDialog: public QDialog { int type; public: - PropertyListDialog(int type, QWidget* parent) : QDialog(parent),type(type) - { - } + PropertyListDialog(int type, QWidget* parent) + : QDialog(parent) + , type(type) + {} void accept() override { @@ -1342,28 +1403,38 @@ public: QStringList lines; if (edit) { QString inputText = edit->toPlainText(); - if (!inputText.isEmpty()) // let pass empty input, regardless of the type, so user can void the value + if (!inputText.isEmpty()) { // let pass empty input, regardless of the type, so user + // can void the value lines = inputText.split(QStringLiteral("\n")); + } } if (!lines.isEmpty()) { - if (type == 1) { // floats + if (type == 1) { // floats bool ok; - int line=1; + int line = 1; for (QStringList::iterator it = lines.begin(); it != lines.end(); ++it, ++line) { it->toDouble(&ok); if (!ok) { - QMessageBox::critical(this, tr("Invalid input"), tr("Input in line %1 is not a number").arg(line)); + QMessageBox::critical( + this, + tr("Invalid input"), + tr("Input in line %1 is not a number").arg(line) + ); return; } } } - else if (type == 2) { // integers + else if (type == 2) { // integers bool ok; - int line=1; + int line = 1; for (QStringList::iterator it = lines.begin(); it != lines.end(); ++it, ++line) { it->toInt(&ok); if (!ok) { - QMessageBox::critical(this, tr("Invalid input"), tr("Input in line %1 is not a number").arg(line)); + QMessageBox::critical( + this, + tr("Invalid input"), + tr("Input in line %1 is not a number").arg(line) + ); return; } } @@ -1375,8 +1446,8 @@ public: // -------------------------------------------------------------------- -LabelEditor::LabelEditor (QWidget * parent) - : QWidget(parent) +LabelEditor::LabelEditor(QWidget* parent) + : QWidget(parent) { type = String; auto layout = new QHBoxLayout(this); @@ -1386,12 +1457,11 @@ LabelEditor::LabelEditor (QWidget * parent) lineEdit = new QLineEdit(this); layout->addWidget(lineEdit); - connect(lineEdit, &QLineEdit::textChanged, - this, &LabelEditor::validateText); + connect(lineEdit, &QLineEdit::textChanged, this, &LabelEditor::validateText); button = new QPushButton(QStringLiteral("…"), this); -#if defined (Q_OS_MACOS) - button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct +#if defined(Q_OS_MACOS) + button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct #endif layout->addWidget(button); @@ -1453,7 +1523,7 @@ void LabelEditor::changeText() void LabelEditor::validateText(const QString& text) { if (text.startsWith(QLatin1String("[")) && text.endsWith(QLatin1String("]"))) { - this->plainText = text.mid(1, text.size()-2); + this->plainText = text.mid(1, text.size() - 2); Q_EMIT textChanged(this->plainText); } } @@ -1485,19 +1555,27 @@ void LabelEditor::setInputType(InputType t) // -------------------------------------------------------------------- ExpLineEdit::ExpLineEdit(QWidget* parent, bool expressionOnly) - : QLineEdit(parent), autoClose(expressionOnly) + : QLineEdit(parent) + , autoClose(expressionOnly) { makeLabel(this); QObject::connect(iconLabel, &ExpressionLabel::clicked, this, &ExpLineEdit::openFormulaDialog); - if (expressionOnly) - QMetaObject::invokeMethod(this, "openFormulaDialog", Qt::QueuedConnection, QGenericReturnArgument()); + if (expressionOnly) { + QMetaObject::invokeMethod( + this, + "openFormulaDialog", + Qt::QueuedConnection, + QGenericReturnArgument() + ); + } } -bool ExpLineEdit::apply(const std::string& propName) { +bool ExpLineEdit::apply(const std::string& propName) +{ if (!ExpressionBinding::apply(propName)) { - if(!autoClose) { + if (!autoClose) { QString val = QString::fromUtf8(Base::Interpreter().strToPython(text().toUtf8()).c_str()); Gui::Command::doCommand(Gui::Command::Doc, "%s = \"%s\"", propName.c_str(), val.constData()); } @@ -1507,12 +1585,14 @@ bool ExpLineEdit::apply(const std::string& propName) { return false; } -void ExpLineEdit::bind(const ObjectIdentifier& _path) { +void ExpLineEdit::bind(const ObjectIdentifier& _path) +{ ExpressionBinding::bind(_path); int frameWidth = style()->pixelMetric(QStyle::PM_SpinBoxFrameWidth); - setStyleSheet(QStringLiteral("QLineEdit { padding-right: %1px } ").arg(iconLabel->sizeHint().width() + frameWidth + 1)); + setStyleSheet(QStringLiteral("QLineEdit { padding-right: %1px } ") + .arg(iconLabel->sizeHint().width() + frameWidth + 1)); iconLabel->show(); } @@ -1533,15 +1613,19 @@ void ExpLineEdit::setExpression(std::shared_ptr expr) } } -void ExpLineEdit::onChange() { +void ExpLineEdit::onChange() +{ if (getExpression()) { std::unique_ptr result(getExpression()->eval()); - if(result->isDerivedFrom()) - setText(QString::fromUtf8(static_cast( - result.get())->getText().c_str())); - else + if (result->isDerivedFrom()) { + setText( + QString::fromUtf8(static_cast(result.get())->getText().c_str()) + ); + } + else { setText(QString::fromUtf8(result->toString().c_str())); + } setReadOnly(true); iconLabel->setPixmap(getIcon(":/icons/bound-expression.svg", QSize(iconHeight, iconHeight))); @@ -1552,7 +1636,9 @@ void ExpLineEdit::onChange() { } else { setReadOnly(false); - iconLabel->setPixmap(getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight))); + iconLabel->setPixmap( + getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight)) + ); QPalette p(palette()); p.setColor(QPalette::Active, QPalette::Text, defaultPalette.color(QPalette::Text)); setPalette(p); @@ -1560,7 +1646,7 @@ void ExpLineEdit::onChange() { } } -void ExpLineEdit::resizeEvent(QResizeEvent * event) +void ExpLineEdit::resizeEvent(QResizeEvent* event) { QLineEdit::resizeEvent(event); @@ -1582,7 +1668,8 @@ void ExpLineEdit::resizeEvent(QResizeEvent * event) } else { setReadOnly(false); - QPixmap pixmap = getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight)); + QPixmap pixmap + = getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight)); iconLabel->setPixmap(pixmap); QPalette p(palette()); @@ -1604,13 +1691,12 @@ void ExpLineEdit::openFormulaDialog() { Q_ASSERT(isBound()); - auto box = new Gui::Dialog::DlgExpressionInput( - getPath(), getExpression(),Unit(), this); + auto box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), Unit(), this); connect(box, &Dialog::DlgExpressionInput::finished, this, &ExpLineEdit::finishFormulaDialog); box->show(); - QPoint pos = mapToGlobal(QPoint(0,0)); - box->move(pos-box->expressionPosition()); + QPoint pos = mapToGlobal(QPoint(0, 0)); + box->move(pos - box->expressionPosition()); Gui::adjustDialogPosition(box); } @@ -1622,42 +1708,50 @@ void ExpLineEdit::finishFormulaDialog() return; } - if (box->result() == QDialog::Accepted) + if (box->result() == QDialog::Accepted) { setExpression(box->getExpression()); - else if (box->discardedFormula()) + } + else if (box->discardedFormula()) { setExpression(std::shared_ptr()); + } onChange(); box->deleteLater(); - if(autoClose) + if (autoClose) { this->deleteLater(); + } } -void ExpLineEdit::keyPressEvent(QKeyEvent *event) +void ExpLineEdit::keyPressEvent(QKeyEvent* event) { - if (!hasExpression()) + if (!hasExpression()) { QLineEdit::keyPressEvent(event); + } } // -------------------------------------------------------------------- -ButtonGroup::ButtonGroup(QObject *parent) - : QButtonGroup(parent) - , _exclusive(true) +ButtonGroup::ButtonGroup(QObject* parent) + : QButtonGroup(parent) + , _exclusive(true) { QButtonGroup::setExclusive(false); - connect(this, qOverload(&QButtonGroup::buttonClicked), - [this](QAbstractButton *button) { - if (exclusive()) { - const auto btns = buttons(); - for (auto btn : btns) { - if (btn && btn != button && btn->isCheckable()) - btn->setChecked(false); + connect( + this, + qOverload(&QButtonGroup::buttonClicked), + [this](QAbstractButton* button) { + if (exclusive()) { + const auto btns = buttons(); + for (auto btn : btns) { + if (btn && btn != button && btn->isCheckable()) { + btn->setChecked(false); + } + } } } - }); + ); } void ButtonGroup::setExclusive(bool on) @@ -1670,9 +1764,11 @@ bool ButtonGroup::exclusive() const return _exclusive; } -namespace Gui { +namespace Gui +{ -void adjustDialogPosition(QDialog* dialog) { +void adjustDialogPosition(QDialog* dialog) +{ if (!dialog) { return; } @@ -1680,11 +1776,11 @@ void adjustDialogPosition(QDialog* dialog) { if (!mw) { return; } - - dialog->adjustSize(); // ensure correct size - const QRect mainWindowRect{ mw->mapToGlobal(QPoint(0, 0)), mw->size() }; - const QRect dialogRect{ dialog->frameGeometry() }; + dialog->adjustSize(); // ensure correct size + + const QRect mainWindowRect {mw->mapToGlobal(QPoint(0, 0)), mw->size()}; + const QRect dialogRect {dialog->frameGeometry()}; const bool isFullyInside = mainWindowRect.contains(dialogRect); if (isFullyInside) { @@ -1697,27 +1793,21 @@ void adjustDialogPosition(QDialog* dialog) { } const int margin = 5; - const QRect availableArea = mainWindowRect.adjusted( - margin, margin, -margin, -margin - ); + const QRect availableArea = mainWindowRect.adjusted(margin, margin, -margin, -margin); QPoint adjustedTopLeft = dialogRect.topLeft(); - adjustedTopLeft.setX(std::clamp( - adjustedTopLeft.x(), - availableArea.left(), - availableArea.right() - dialogRect.width() - )); + adjustedTopLeft.setX( + std::clamp(adjustedTopLeft.x(), availableArea.left(), availableArea.right() - dialogRect.width()) + ); - adjustedTopLeft.setY(std::clamp( - adjustedTopLeft.y(), - availableArea.top(), - availableArea.bottom() - dialogRect.height() - )); + adjustedTopLeft.setY( + std::clamp(adjustedTopLeft.y(), availableArea.top(), availableArea.bottom() - dialogRect.height()) + ); dialog->move(adjustedTopLeft); } -} +} // namespace Gui #include "moc_Widgets.cpp" diff --git a/src/Gui/Widgets.h b/src/Gui/Widgets.h index 34bfe251fe..2873a387fd 100644 --- a/src/Gui/Widgets.h +++ b/src/Gui/Widgets.h @@ -1,4 +1,4 @@ - /*************************************************************************** +/*************************************************************************** * Copyright (c) 2004 Werner Mayer * * * * This file is part of the FreeCAD CAx development system. * @@ -49,7 +49,8 @@ class QTreeWidget; class QTreeWidgetItem; class QSpacerItem; -namespace Gui { +namespace Gui +{ class PrefCheckBox; class CommandViewItemPrivate; @@ -59,46 +60,50 @@ class CommandViewItemPrivate; * @see CommandViewItem, Command * @author Werner Mayer */ -class CommandIconView : public QListWidget -{ - Q_OBJECT - -public: - CommandIconView (QWidget * parent = nullptr); - ~CommandIconView () override; - -protected: - void startDrag ( Qt::DropActions supportedActions ) override; - -protected Q_SLOTS: - void onSelectionChanged( QListWidgetItem * item, QListWidgetItem * ); - -Q_SIGNALS: - /** Emits this signal if selection has changed. */ - void emitSelectionChanged( const QString& ); -}; - -// ------------------------------------------------------------------------------ - -class GuiExport ActionSelector : public QWidget +class CommandIconView: public QListWidget { Q_OBJECT public: - ActionSelector(QWidget* parent=nullptr); + CommandIconView(QWidget* parent = nullptr); + ~CommandIconView() override; + +protected: + void startDrag(Qt::DropActions supportedActions) override; + +protected Q_SLOTS: + void onSelectionChanged(QListWidgetItem* item, QListWidgetItem*); + +Q_SIGNALS: + /** Emits this signal if selection has changed. */ + void emitSelectionChanged(const QString&); +}; + +// ------------------------------------------------------------------------------ + +class GuiExport ActionSelector: public QWidget +{ + Q_OBJECT + +public: + ActionSelector(QWidget* parent = nullptr); ~ActionSelector() override; QTreeWidget* availableTreeWidget() const - { return availableWidget; } + { + return availableWidget; + } QTreeWidget* selectedTreeWidget() const - { return selectedWidget; } + { + return selectedWidget; + } void setSelectedLabel(const QString&); QString selectedLabel() const; void setAvailableLabel(const QString&); QString availableLabel() const; private: - void keyPressEvent(QKeyEvent *) override; + void keyPressEvent(QKeyEvent*) override; void changeEvent(QEvent*) override; void retranslateUi(); void setButtonsEnabled(); @@ -109,22 +114,22 @@ private Q_SLOTS: void onUpButtonClicked(); void onDownButtonClicked(); void onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*); - void onItemDoubleClicked(QTreeWidgetItem * item, int column); + void onItemDoubleClicked(QTreeWidgetItem* item, int column); private: - QGridLayout *gridLayout; - QVBoxLayout *vboxLayout; - QVBoxLayout *vboxLayout1; - QPushButton *addButton; - QPushButton *removeButton; - QPushButton *upButton; - QPushButton *downButton; - QLabel *labelAvailable; - QLabel *labelSelected; - QTreeWidget *availableWidget; - QTreeWidget *selectedWidget; - QSpacerItem *spacerItem; - QSpacerItem *spacerItem1; + QGridLayout* gridLayout; + QVBoxLayout* vboxLayout; + QVBoxLayout* vboxLayout1; + QPushButton* addButton; + QPushButton* removeButton; + QPushButton* upButton; + QPushButton* downButton; + QLabel* labelAvailable; + QLabel* labelSelected; + QTreeWidget* availableWidget; + QTreeWidget* selectedWidget; + QSpacerItem* spacerItem; + QSpacerItem* spacerItem1; }; // ------------------------------------------------------------------------------ @@ -133,9 +138,9 @@ private: * The AccelLineEdit class provides a lineedit to specify shortcuts. * \author Werner Mayer */ -class GuiExport AccelLineEdit : public QKeySequenceEdit +class GuiExport AccelLineEdit: public QKeySequenceEdit { - Q_OBJECT + Q_OBJECT public: explicit AccelLineEdit(QWidget* parent = nullptr); @@ -150,15 +155,15 @@ public: /** * The ModifierLineEdit class provides a lineedit to specify modifiers. */ -class GuiExport ModifierLineEdit : public QLineEdit +class GuiExport ModifierLineEdit: public QLineEdit { - Q_OBJECT + Q_OBJECT public: - ModifierLineEdit(QWidget * parent=nullptr); + ModifierLineEdit(QWidget* parent = nullptr); protected: - void keyPressEvent(QKeyEvent * e) override; + void keyPressEvent(QKeyEvent* e) override; }; // ------------------------------------------------------------------------------ @@ -167,21 +172,21 @@ protected: * The ClearLineEdit class adds a clear button at the right side. * http://stackoverflow.com/questions/21232224/qlineedit-with-custom-button */ -class GuiExport ClearLineEdit : public QLineEdit +class GuiExport ClearLineEdit: public QLineEdit { - Q_OBJECT + Q_OBJECT public: - ClearLineEdit (QWidget * parent=nullptr); + ClearLineEdit(QWidget* parent = nullptr); protected: - void resizeEvent(QResizeEvent *) override; + void resizeEvent(QResizeEvent*) override; private Q_SLOTS: - void updateClearButton(const QString &text); + void updateClearButton(const QString& text); private: - QAction *clearAction; + QAction* clearAction; }; // ------------------------------------------------------------------------------ @@ -194,24 +199,24 @@ class Ui_DlgTreeWidget; * checkable items inside. * \author Werner Mayer */ -class GuiExport CheckListDialog : public QDialog +class GuiExport CheckListDialog: public QDialog { - Q_OBJECT + Q_OBJECT public: - CheckListDialog( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~CheckListDialog() override; + CheckListDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~CheckListDialog() override; - void setCheckableItems( const QStringList& items ); - void setCheckableItems( const QList& items ); - QStringList getCheckedItems() const; + void setCheckableItems(const QStringList& items); + void setCheckableItems(const QList& items); + QStringList getCheckedItems() const; - void accept () override; + void accept() override; private: - QStringList checked; - std::unique_ptr ui; + QStringList checked; + std::unique_ptr ui; }; // ------------------------------------------------------------------------------ @@ -220,14 +225,18 @@ private: * Implementation of a color button. * \author Werner Mayer */ -class GuiExport ColorButton : public QPushButton +class GuiExport ColorButton: public QPushButton { Q_OBJECT - Q_PROPERTY( QColor color READ color WRITE setColor NOTIFY changed) - Q_PROPERTY( bool allowChangeColor READ allowChangeColor WRITE setAllowChangeColor ) // clazy:exclude=qproperty-without-notify - Q_PROPERTY( bool drawFrame READ drawFrame WRITE setDrawFrame ) // clazy:exclude=qproperty-without-notify - Q_PROPERTY( bool allowTransparency READ allowTransparency WRITE setAllowTransparency) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY changed) + Q_PROPERTY( + bool allowChangeColor READ allowChangeColor WRITE setAllowChangeColor + ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool drawFrame READ drawFrame WRITE setDrawFrame) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( + bool allowTransparency READ allowTransparency WRITE setAllowTransparency + ) // clazy:exclude=qproperty-without-notify public: ColorButton(QWidget* parent = nullptr); @@ -266,14 +275,14 @@ Q_SIGNALS: void changed(); protected: - void paintEvent (QPaintEvent*) override; + void paintEvent(QPaintEvent*) override; private: void showModeless(); void showModal(); private: - struct ColorButtonP *d; + struct ColorButtonP* d; }; // ------------------------------------------------------------------------------ @@ -286,32 +295,34 @@ private: * can be specified. * @author Werner Mayer */ -class GuiExport UrlLabel : public QLabel +class GuiExport UrlLabel: public QLabel { - Q_OBJECT - Q_PROPERTY( QString url READ url WRITE setUrl) // clazy:exclude=qproperty-without-notify - Q_PROPERTY( bool launchExternal READ launchExternal WRITE setLaunchExternal) // clazy:exclude=qproperty-without-notify + Q_OBJECT + Q_PROPERTY(QString url READ url WRITE setUrl) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( + bool launchExternal READ launchExternal WRITE setLaunchExternal + ) // clazy:exclude=qproperty-without-notify public: - UrlLabel ( QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags() ); - ~UrlLabel() override; + UrlLabel(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + ~UrlLabel() override; - QString url() const; - bool launchExternal() const; + QString url() const; + bool launchExternal() const; Q_SIGNALS: - void linkClicked(QString url); + void linkClicked(QString url); public Q_SLOTS: - void setUrl( const QString &u ); - void setLaunchExternal(bool l); + void setUrl(const QString& u); + void setLaunchExternal(bool l); protected: - void mouseReleaseEvent ( QMouseEvent * ) override; + void mouseReleaseEvent(QMouseEvent*) override; private: - QString _url; - bool _launchExternal; + QString _url; + bool _launchExternal; }; @@ -340,18 +351,18 @@ private: * * @author Chris Hennes */ -class GuiExport StatefulLabel : public QLabel, public Base::Observer +class GuiExport StatefulLabel: public QLabel, public Base::Observer { Q_OBJECT - Q_PROPERTY( bool overridePreference MEMBER _overridePreference WRITE setOverridePreference) - Q_PROPERTY( QString state MEMBER _state WRITE setState ) + Q_PROPERTY(bool overridePreference MEMBER _overridePreference WRITE setOverridePreference) + Q_PROPERTY(QString state MEMBER _state WRITE setState) public: StatefulLabel(QWidget* parent = nullptr); ~StatefulLabel() override; /** If an unrecognized state is set, use this style */ - void setDefaultStyle(const QString &defaultStyle); + void setDefaultStyle(const QString& defaultStyle); /** If any of the states have user preferences associated with them, this sets the parameter group that stores those preferences. All states must be in the same parameter group, but @@ -359,19 +370,31 @@ public: void setParameterGroup(const std::string& groupName); /** Register a state and its corresponding style (optionally attached to a user preference) */ - void registerState(const QString &state, const QString &styleCSS, - const std::string& preferenceName = std::string()); + void registerState( + const QString& state, + const QString& styleCSS, + const std::string& preferenceName = std::string() + ); - /** For convenience, allow simple color-only states via QColor (optionally attached to a user preference) */ - void registerState(const QString& state, const QColor& color, - const std::string& preferenceName = std::string()); + /** For convenience, allow simple color-only states via QColor (optionally attached to a user + * preference) */ + void registerState( + const QString& state, + const QColor& color, + const std::string& preferenceName = std::string() + ); - /** For convenience, allow simple color-only states via QColor (optionally attached to a user preference) */ - void registerState(const QString& state, const QColor& foregroundColor, const QColor& backgroundColor, - const std::string& preferenceName = std::string()); + /** For convenience, allow simple color-only states via QColor (optionally attached to a user + * preference) */ + void registerState( + const QString& state, + const QColor& foregroundColor, + const QColor& backgroundColor, + const std::string& preferenceName = std::string() + ); /** Observes the parameter group and clears the cache if it changes */ - void OnChange(Base::Subject& rCaller, const char* rcReason) override; + void OnChange(Base::Subject& rCaller, const char* rcReason) override; public Q_SLOTS: void setState(QString state); @@ -383,7 +406,8 @@ private: ParameterGrp::handle _parameterGroup; ParameterGrp::handle _stylesheetGroup; - struct StateData { + struct StateData + { QString defaultCSS; std::string preferenceString; }; @@ -399,20 +423,20 @@ private: * The LabelButton class provides a label with a button on the right side. * @author Werner Mayer */ -class GuiExport LabelButton : public QWidget +class GuiExport LabelButton: public QWidget { Q_OBJECT - Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) + Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) public: - LabelButton (QWidget * parent = nullptr); + LabelButton(QWidget* parent = nullptr); ~LabelButton() override; QVariant value() const; - QLabel *getLabel() const; - QPushButton *getButton() const; + QLabel* getLabel() const; + QPushButton* getButton() const; public Q_SLOTS: void setValue(const QVariant&); @@ -425,12 +449,12 @@ protected Q_SLOTS: virtual void browse(); Q_SIGNALS: - void valueChanged(const QVariant &); + void valueChanged(const QVariant&); void buttonClicked(); private: - QLabel *label; - QPushButton *button; + QLabel* label; + QPushButton* button; QVariant _val; }; @@ -443,10 +467,10 @@ private: * timer events. * @author Werner Mayer */ -class GuiExport ToolTip : public QObject +class GuiExport ToolTip: public QObject { public: - static void showText(const QPoint & pos, const QString & text, QWidget * w = nullptr); + static void showText(const QPoint& pos, const QString& text, QWidget* w = nullptr); static void hideText(); protected: @@ -455,8 +479,8 @@ protected: ToolTip(); ~ToolTip() override; - void timerEvent(QTimerEvent *e) override; - bool eventFilter(QObject* o, QEvent*e) override; + void timerEvent(QTimerEvent* e) override; + bool eventFilter(QObject* o, QEvent* e) override; void installEventFilter(); void removeEventFilter(); @@ -466,14 +490,14 @@ private: static ToolTip* inst; QString text; QPoint pos; - QPointer w; // need guard in case widget gets destroyed + QPointer w; // need guard in case widget gets destroyed QBasicTimer tooltipTimer; QElapsedTimer displayTime; }; // ---------------------------------------------------------------------- -class GuiExport StatusWidget : public QDialog +class GuiExport StatusWidget: public QDialog { Q_OBJECT @@ -481,7 +505,7 @@ public: StatusWidget(QWidget* parent); ~StatusWidget() override; void setStatusText(const QString&); - QSize sizeHint () const override; + QSize sizeHint() const override; void showText(int ms); protected: @@ -494,65 +518,72 @@ private: // ---------------------------------------------------------------------- -class GuiExport PropertyListEditor : public QPlainTextEdit +class GuiExport PropertyListEditor: public QPlainTextEdit { Q_OBJECT public: - PropertyListEditor(QWidget *parent = nullptr); + PropertyListEditor(QWidget* parent = nullptr); - void lineNumberAreaPaintEvent(QPaintEvent *event); + void lineNumberAreaPaintEvent(QPaintEvent* event); int lineNumberAreaWidth(); protected: - void resizeEvent(QResizeEvent *event) override; + void resizeEvent(QResizeEvent* event) override; private Q_SLOTS: void updateLineNumberAreaWidth(int newBlockCount); void highlightCurrentLine(); - void updateLineNumberArea(const QRect &, int); + void updateLineNumberArea(const QRect&, int); private: - QWidget *lineNumberArea; + QWidget* lineNumberArea; }; // ---------------------------------------------------------------------- -class GuiExport LabelEditor : public QWidget +class GuiExport LabelEditor: public QWidget { Q_OBJECT Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) - Q_PROPERTY(QString buttonText READ buttonText WRITE setButtonText) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( + QString buttonText READ buttonText WRITE setButtonText + ) // clazy:exclude=qproperty-without-notify public: - enum InputType {String, Float, Integer}; + enum InputType + { + String, + Float, + Integer + }; - LabelEditor (QWidget * parent = nullptr); + LabelEditor(QWidget* parent = nullptr); ~LabelEditor() override; /** - * Returns the text. - */ + * Returns the text. + */ QString text() const; /** - * Returns the button's text. - */ + * Returns the button's text. + */ QString buttonText() const; /** - * Set the input type. - */ + * Set the input type. + */ void setInputType(InputType); public Q_SLOTS: - virtual void setText(const QString &); - virtual void setButtonText (const QString &); - virtual void validateText (const QString &); + virtual void setText(const QString&); + virtual void setButtonText(const QString&); + virtual void validateText(const QString&); Q_SIGNALS: - void textChanged(const QString &); + void textChanged(const QString&); private Q_SLOTS: void changeText(); @@ -563,27 +594,27 @@ protected: private: InputType type; QString plainText; - QLineEdit *lineEdit; - QPushButton *button; + QLineEdit* lineEdit; + QPushButton* button; }; /** * The ExpLineEdit class provides a lineedit that support expressing binding. * \author realthunder */ -class GuiExport ExpLineEdit : public QLineEdit, public ExpressionWidget +class GuiExport ExpLineEdit: public QLineEdit, public ExpressionWidget { Q_OBJECT public: - ExpLineEdit ( QWidget * parent=nullptr, bool expressionOnly=false ); + ExpLineEdit(QWidget* parent = nullptr, bool expressionOnly = false); void setExpression(std::shared_ptr expr) override; - void bind(const App::ObjectIdentifier &_path) override; - bool apply(const std::string &propName) override; + void bind(const App::ObjectIdentifier& _path) override; + bool apply(const std::string& propName) override; - void keyPressEvent(QKeyEvent *event) override; - void resizeEvent(QResizeEvent *event) override; + void keyPressEvent(QKeyEvent* event) override; + void resizeEvent(QResizeEvent* event) override; private Q_SLOTS: void finishFormulaDialog(); @@ -599,12 +630,12 @@ private: * Unlike Qt's QButtonGroup this class allows it that in exclusive mode * all buttons can be unchecked. */ -class GuiExport ButtonGroup : public QButtonGroup +class GuiExport ButtonGroup: public QButtonGroup { Q_OBJECT public: - ButtonGroup(QObject *parent = nullptr); + ButtonGroup(QObject* parent = nullptr); void setExclusive(bool on); bool exclusive() const; @@ -614,14 +645,16 @@ private: }; /** - * Adjusts the position of the given dialog to ensure it remains within the bounds of the main window. - * This helps prevent dialogs from appearing partially or fully off-screen relative to the main application window. - * - * This function shall be invoked after the dialog has been shown (using show()) or its position or size has changed. - * Exception: If the dialog is modal, this function should be called before the dialog is called with exec(). + * Adjusts the position of the given dialog to ensure it remains within the bounds of the main + * window. This helps prevent dialogs from appearing partially or fully off-screen relative to the + * main application window. + * + * This function shall be invoked after the dialog has been shown (using show()) or its position or + * size has changed. Exception: If the dialog is modal, this function should be called before the + * dialog is called with exec(). */ void adjustDialogPosition(QDialog* dialog); -} // namespace Gui +} // namespace Gui -#endif // GUI_WIDGETS_H +#endif // GUI_WIDGETS_H diff --git a/src/Gui/Window.cpp b/src/Gui/Window.cpp index f44f6e1c24..d313f1686b 100644 --- a/src/Gui/Window.cpp +++ b/src/Gui/Window.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ - - #include #include @@ -42,15 +40,16 @@ using namespace Gui; //************************************************************************** // Construction/Destruction -WindowParameter::WindowParameter(const char *name) +WindowParameter::WindowParameter(const char* name) { // not allowed to use a Window without a name, see the constructor // of a DockWindow or a other QT Widget assert(name); // if string is empty do not create group - if ( strcmp(name, "") != 0 ) - _handle = getDefaultParameter()->GetGroup( name ); + if (strcmp(name, "") != 0) { + _handle = getDefaultParameter()->GetGroup(name); + } } WindowParameter::~WindowParameter() @@ -85,13 +84,13 @@ bool WindowParameter::setGroupName(const char* name) return true; } -void WindowParameter::OnChange(Base::Subject &rCaller, const char * sReason) +void WindowParameter::OnChange(Base::Subject& rCaller, const char* sReason) { Q_UNUSED(rCaller); Q_UNUSED(sReason); } -ParameterGrp::handle WindowParameter::getWindowParameter() +ParameterGrp::handle WindowParameter::getWindowParameter() { return _handle; } @@ -100,7 +99,7 @@ ParameterGrp::handle WindowParameter::getWindowParameter() * Returns a handle to the parameter group to the user parameter * under BaseApp/Preferences. */ -ParameterGrp::handle WindowParameter::getDefaultParameter() +ParameterGrp::handle WindowParameter::getDefaultParameter() { return App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); } diff --git a/src/Gui/Window.h b/src/Gui/Window.h index a57fe5e4c3..c19be52479 100644 --- a/src/Gui/Window.h +++ b/src/Gui/Window.h @@ -27,19 +27,20 @@ #include #include -namespace Gui { +namespace Gui +{ /** Adapter class to the parameter of FreeCAD for all windows * Retrieve the parameter group of the specific window by the windowname. * @author Jürgen Riegel */ -class GuiExport WindowParameter : public ParameterGrp::ObserverType +class GuiExport WindowParameter: public ParameterGrp::ObserverType { public: - WindowParameter(const char *name); + WindowParameter(const char* name); ~WindowParameter() override; - void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject& rCaller, const char* sReason) override; /// get the parameters static ParameterGrp::handle getDefaultParameter(); @@ -47,7 +48,7 @@ public: ParameterGrp::handle getWindowParameter(); protected: - bool setGroupName( const char* name ); + bool setGroupName(const char* name); /// connect slot to ParameterManager signal template void setSlotParamChanged(S slot, T* obsPtr); @@ -64,10 +65,11 @@ inline void WindowParameter::setSlotParamChanged(S slot, T* obsPtr) namespace bp = std::placeholders; if (_handle->Manager()) { connParamChanged = _handle->Manager()->signalParamChanged.connect( - std::bind(slot, obsPtr, bp::_1, bp::_2, bp::_3, bp::_4)); + std::bind(slot, obsPtr, bp::_1, bp::_2, bp::_3, bp::_4) + ); } } -} // namespace Gui +} // namespace Gui -#endif // GUI_WINDOW_H +#endif // GUI_WINDOW_H diff --git a/src/Gui/Workbench.cpp b/src/Gui/Workbench.cpp index 75f6fa5223..e6d5e07e9c 100644 --- a/src/Gui/Workbench.cpp +++ b/src/Gui/Workbench.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include "Workbench.h" @@ -55,18 +54,28 @@ using namespace Gui; \ingroup GUI FreeCAD provides the possibility to have one or more workbenches for a module. - A workbench changes the appearance of the main window in that way that it defines toolbars, items in the toolbox, menus or the context menu and dockable windows that are shown to the user. - The idea behind this concept is that the user should see only the functions that are required for the task that they are doing at this moment and not to show dozens of unneeded functions which the user never uses. + A workbench changes the appearance of the main window in that way that it defines toolbars, + items in the toolbox, menus or the context menu and dockable windows that are shown to the user. + The idea behind this concept is that the user should see only the functions that are required for + the task that they are doing at this moment and not to show dozens of unneeded functions which the + user never uses. \section stepbystep Step by step Here follows a short description of how your own workbench can be added to a module. \subsection newClass Inherit either from Workbench or StdWorkbench - First you have to subclass either \ref Gui::Workbench "Workbench" or \ref Gui::StdWorkbench "StdWorkbench" and reimplement the methods \ref Gui::Workbench::setupMenuBar() "setupMenuBar()", \ref Gui::Workbench::setupToolBars() "setupToolBars()", \ref Gui::Workbench::setupCommandBars() "setupCommandBars()" and \ref Gui::Workbench::setupDockWindows() "setupDockWindows()". + First you have to subclass either \ref Gui::Workbench "Workbench" or \ref Gui::StdWorkbench + "StdWorkbench" and reimplement the methods \ref Gui::Workbench::setupMenuBar() "setupMenuBar()", + \ref Gui::Workbench::setupToolBars() "setupToolBars()", \ref Gui::Workbench::setupCommandBars() + "setupCommandBars()" and \ref Gui::Workbench::setupDockWindows() "setupDockWindows()". - The difference between both classes is that these methods of %Workbench are pure virtual while StdWorkbench defines already the standard menus and toolbars, such as the 'File', 'Edit', ..., 'Help' menus with their common functions. + The difference between both classes is that these methods of %Workbench are pure virtual while + StdWorkbench defines already the standard menus and toolbars, such as the 'File', 'Edit', ..., + 'Help' menus with their common functions. - If your class derives from %Workbench then you have to define your menus, toolbars and toolbox items from scratch while deriving from StdWorkbench you have the possibility to add your preferred functions or even remove some unneeded functions. + If your class derives from %Workbench then you have to define your menus, toolbars and toolbox + items from scratch while deriving from StdWorkbench you have the possibility to add your preferred + functions or even remove some unneeded functions. * \code * * class MyWorkbench : public StdWorkbench @@ -124,7 +133,8 @@ using namespace Gui; * \endcode * * \subsection customizeWorkbench Customizing the workbench - * If you want to customize your workbench by adding or removing items you can use the ToolBarItem class for customizing toolbars and the MenuItem class + * If you want to customize your workbench by adding or removing items you can use the ToolBarItem + class for customizing toolbars and the MenuItem class * for menus. Both classes behave basically the same. * To add a new menu item you can do it as follows * \code @@ -140,15 +150,19 @@ using namespace Gui; * MenuItem* myMenu = new MenuItem( root ); * myMenu->setCommand( "&My Menu" ); * // fill up the menu with some command items - * *myMenu << mySub << "Separator" << "Std_Cut" << "Std_Copy" << "Std_Paste" << "Separator" << "Std_Undo" << "Std_Redo"; + * *myMenu << mySub << "Separator" << "Std_Cut" << "Std_Copy" << "Std_Paste" << "Separator" << + "Std_Undo" << "Std_Redo"; * } * \endcode * - * Toolbars can be customized the same way unless that you shouldn't create subitems (there are no subtoolbars). + * Toolbars can be customized the same way unless that you shouldn't create subitems (there are no + subtoolbars). * * \subsection regWorkbench Register your workbench - * Once you have implemented your workbench class you have to register it to make it known to the FreeCAD core system. You must make sure that the step - * of registration is performed only once. A good place to do it is e.g. in the global function initMODULEGui in AppMODULEGui.cpp where MODULE stands + * Once you have implemented your workbench class you have to register it to make it known to the + FreeCAD core system. You must make sure that the step + * of registration is performed only once. A good place to do it is e.g. in the global function + initMODULEGui in AppMODULEGui.cpp where MODULE stands * for the name of your module. Just add the line * \code * MODULEGui::MyWorkbench::init(); @@ -156,11 +170,16 @@ using namespace Gui; * somewhere there. * * \subsection itemWorkbench Create an item for your workbench - * Though your workbench has been registered now, at this stage you still cannot invoke it yet. Therefore you must create an item in the list of all visible - * workbenches. To perform this step you must open your InitGui.py (a Python file) and do some adjustments. The file contains already a Python class - * MODULEWorkbench that implements the Activate() method (it imports the needed library). You can also implement the GetIcon() method to set your own icon for - * your workbench, if not, the default FreeCAD icon is taken, and finally the most important method GetClassName(). that represents the link between - * Python and C++. This method must return the name of the associated C++ including namespace. In this case it must the string "ModuleGui::MyWorkbench". + * Though your workbench has been registered now, at this stage you still cannot invoke it yet. + Therefore you must create an item in the list of all visible + * workbenches. To perform this step you must open your InitGui.py (a Python file) and do some + adjustments. The file contains already a Python class + * MODULEWorkbench that implements the Activate() method (it imports the needed library). You can + also implement the GetIcon() method to set your own icon for + * your workbench, if not, the default FreeCAD icon is taken, and finally the most important method + GetClassName(). that represents the link between + * Python and C++. This method must return the name of the associated C++ including namespace. In + this case it must the string "ModuleGui::MyWorkbench". * At the end you can change the line from * \code * Gui.addWorkbench("MODULE design",MODULEWorkbench()) @@ -170,33 +189,49 @@ using namespace Gui; * Gui.addWorkbench("My workbench",MODULEWorkbench()) * \endcode * or whatever you want. - * \note You must make sure to choose a unique name for your workbench (in this example "My workbench"). Since FreeCAD doesn't provide a mechanism for + * \note You must make sure to choose a unique name for your workbench (in this example "My + workbench"). Since FreeCAD doesn't provide a mechanism for * this you have to care on your own. * * \section moredetails More details and limitations - * One of the key concepts of the workbench framework is to load a module at runtime when the user needs some function that it - * provides. So, if the user doesn't need a module it never gets loaded into RAM. This speeds up the startup procedure of + * One of the key concepts of the workbench framework is to load a module at runtime when the user + needs some function that it + * provides. So, if the user doesn't need a module it never gets loaded into RAM. This speeds up the + startup procedure of * FreeCAD and saves memory. * - * At startup FreeCAD scans all module directories and invokes InitGui.py. So an item for a workbench gets created. If the user - * clicks on such an item the matching module gets loaded, the C++ workbench gets registered and activated. + * At startup FreeCAD scans all module directories and invokes InitGui.py. So an item for a + workbench gets created. If the user + * clicks on such an item the matching module gets loaded, the C++ workbench gets registered and + activated. * - * The user is able to modify a workbench (Edit|Customize). E.g. they can add new toolbars or items for the toolbox and add their preferred - * functions to them. But the user only has full control over "their" own toolbars, the default workbench items cannot be modified or even removed. + * The user is able to modify a workbench (Edit|Customize). E.g. they can add new toolbars or items + for the toolbox and add their preferred + * functions to them. But the user only has full control over "their" own toolbars, the default + workbench items cannot be modified or even removed. * - * FreeCAD provides also the possibility to define pure Python workbenches. Such workbenches are temporarily only and are lost after exiting - * the FreeCAD session. But if you want to keep your Python workbench you can write a macro and attach it with a user defined button or just + * FreeCAD provides also the possibility to define pure Python workbenches. Such workbenches are + temporarily only and are lost after exiting + * the FreeCAD session. But if you want to keep your Python workbench you can write a macro and + attach it with a user defined button or just * perform the macro during the next FreeCAD session. * Here follows a short example of how to create and embed a workbench in Python * \code - * w=Workbench() # creates a standard workbench (the same as StdWorkbench in C++) - * w.MenuText = "My Workbench" # the text that will appear in the combo box - * dir(w) # lists all available function of the object - * FreeCADGui.addWorkbench(w) # Creates an item for our workbench now - * # Note: We must first add the workbench to run some initialization code - * # Then we are ready to customize the workbench + * w=Workbench() # creates a standard workbench (the + same as StdWorkbench in C++) + * w.MenuText = "My Workbench" # the text that will appear in the + combo box + * dir(w) # lists all available function of the + object + * FreeCADGui.addWorkbench(w) # Creates an item for our workbench + now + * # Note: We must first add the + workbench to run some initialization code + * # Then we are ready to customize the + workbench * list = ["Std_Test1", "Std_Test2", "Std_Test3"] # creates a list of new functions - * w.appendMenu("Test functions", list) # creates a new menu with these functions + * w.appendMenu("Test functions", list) # creates a new menu with these + functions * w.appendToolbar("Test", list) # ... and also a new toolbar * \endcode */ @@ -250,10 +285,10 @@ void Workbench::setupCustomToolbars(ToolBarItem* root, const char* toolbar) cons void Workbench::setupCustomToolbars(ToolBarItem* root, const Base::Reference hGrp) const { - std::vector > hGrps = hGrp->GetGroups(); + std::vector> hGrps = hGrp->GetGroups(); CommandManager& rMgr = Application::Instance->commandManager(); std::string separator = "Separator"; - for (const auto & it : hGrps) { + for (const auto& it : hGrps) { bool active = it->GetBool("Active", true); if (!active) { // ignore this toolbar @@ -264,8 +299,9 @@ void Workbench::setupCustomToolbars(ToolBarItem* root, const Base::ReferencesetCommand("Custom"); // get the elements of the subgroups - std::vector > items = hGrp->GetGroup(it->GetGroupName())->GetASCIIMap(); - for (const auto & item : items) { + std::vector> items + = hGrp->GetGroup(it->GetGroupName())->GetASCIIMap(); + for (const auto& item : items) { if (item.first.substr(0, separator.size()) == separator) { *bar << "Separator"; } @@ -274,7 +310,7 @@ void Workbench::setupCustomToolbars(ToolBarItem* root, const Base::ReferencesetCommand("Link Actions"); *linkMenu << "Std_LinkMakeGroup" << "Std_LinkMake"; - auto &rMgr = Application::Instance->commandManager(); - const char *cmds[] = {"Std_LinkMakeRelative",nullptr,"Std_LinkUnlink","Std_LinkReplace", - "Std_LinkImport","Std_LinkImportAll",nullptr,"Std_LinkSelectLinked", - "Std_LinkSelectLinkedFinal","Std_LinkSelectAllLinks"}; + auto& rMgr = Application::Instance->commandManager(); + const char* cmds[] = { + "Std_LinkMakeRelative", + nullptr, + "Std_LinkUnlink", + "Std_LinkReplace", + "Std_LinkImport", + "Std_LinkImportAll", + nullptr, + "Std_LinkSelectLinked", + "Std_LinkSelectLinkedFinal", + "Std_LinkSelectAllLinks" + }; bool separator = true; - for(const auto & it : cmds) { - if(!it) { - if(separator) { + for (const auto& it : cmds) { + if (!it) { + if (separator) { separator = false; *linkMenu << "Separator"; } continue; } auto cmd = rMgr.getCommandByName(it); - if(cmd->isActive()) { + if (cmd->isActive()) { separator = true; *linkMenu << it; } @@ -368,16 +413,18 @@ void Workbench::addPermanentMenuItem(const std::string& cmd, const std::string& void Workbench::removePermanentMenuItem(const std::string& cmd) { - auto it = std::find_if(staticMenuItems.begin(), staticMenuItems.end(), [cmd](const std::pair& pmi) { - return (pmi.first == cmd); - }); + auto it = std::find_if( + staticMenuItems.begin(), + staticMenuItems.end(), + [cmd](const std::pair& pmi) { return (pmi.first == cmd); } + ); if (it != staticMenuItems.end()) { staticMenuItems.erase(it); } } -void Workbench::addPermanentMenuItems(MenuItem* mb) const +void Workbench::addPermanentMenuItems(MenuItem* mb) const { for (const auto& it : staticMenuItems) { MenuItem* par = mb->findParentOf(it.second); @@ -398,31 +445,30 @@ void Workbench::activated() } void Workbench::deactivated() -{ -} +{} bool Workbench::activate() { ToolBarItem* tb = setupToolBars(); setupCustomToolbars(tb, "Toolbar"); WorkbenchManipulator::changeToolBars(tb); - ToolBarManager::getInstance()->setup( tb ); + ToolBarManager::getInstance()->setup(tb); delete tb; - //ToolBarItem* cb = setupCommandBars(); - //setupCustomToolbars(cb, "Toolboxbar"); - //ToolBoxManager::getInstance()->setup( cb ); - //delete cb; + // ToolBarItem* cb = setupCommandBars(); + // setupCustomToolbars(cb, "Toolboxbar"); + // ToolBoxManager::getInstance()->setup( cb ); + // delete cb; DockWindowItems* dw = setupDockWindows(); WorkbenchManipulator::changeDockWindows(dw); - DockWindowManager::instance()->setup( dw ); + DockWindowManager::instance()->setup(dw); delete dw; MenuItem* mb = setupMenuBar(); addPermanentMenuItems(mb); WorkbenchManipulator::changeMenuBar(mb); - MenuManager::getInstance()->setup( mb ); + MenuManager::getInstance()->setup(mb); delete mb; setupCustomShortcuts(); @@ -433,7 +479,7 @@ bool Workbench::activate() void Workbench::retranslate() const { ToolBarManager::getInstance()->retranslate(); - //ToolBoxManager::getInstance()->retranslate(); + // ToolBoxManager::getInstance()->retranslate(); DockWindowManager::instance()->retranslate(); MenuManager::getInstance()->retranslate(); } @@ -443,7 +489,7 @@ PyObject* Workbench::getPyObject() return new WorkbenchPy(this); } -void Workbench::addTaskWatcher(const std::vector &Watcher) +void Workbench::addTaskWatcher(const std::vector& Watcher) { Gui::TaskView::TaskView* taskView = Control().taskPanel(); if (taskView) { @@ -467,7 +513,7 @@ std::list Workbench::listToolbars() const std::list bars; QList items = tb->getItems(); - for (const auto & item : items) { + for (const auto& item : items) { bars.push_back(item->command()); } return bars; @@ -481,10 +527,10 @@ std::list>> Workbench::getToolbarI std::list>> itemsList; QList items = tb->getItems(); - for (const auto & item : items) { + for (const auto& item : items) { QList sub = item->getItems(); std::list cmds; - for (const auto & jt : sub) { + for (const auto& jt : sub) { cmds.push_back(jt->command()); } @@ -501,7 +547,7 @@ std::list Workbench::listMenus() const std::list menus; QList items = mb->getItems(); - for (const auto & item : items) { + for (const auto& item : items) { menus.push_back(item->command()); } return menus; @@ -512,7 +558,7 @@ std::list Workbench::listCommandbars() const std::unique_ptr cb(setupCommandBars()); std::list bars; QList items = cb->getItems(); - for (const auto & item : items) { + for (const auto& item : items) { bars.push_back(item->command()); } return bars; @@ -520,7 +566,7 @@ std::list Workbench::listCommandbars() const // -------------------------------------------------------------------- -#if 0 // needed for Qt's lupdate utility +#if 0 // needed for Qt's lupdate utility qApp->translate("CommandGroup", "File"); qApp->translate("CommandGroup", "Edit"); qApp->translate("CommandGroup", "Help"); @@ -564,7 +610,7 @@ std::list Workbench::listCommandbars() const qApp->translate("Workbench", "Link Actions"); #endif -#if 0 // needed for the application menu on OSX +#if 0 // needed for the application menu on OSX qApp->translate("MAC_APPLICATION_MENU", "Services"); qApp->translate("MAC_APPLICATION_MENU", "Hide %1"); qApp->translate("MAC_APPLICATION_MENU", "Hide Others"); @@ -577,28 +623,27 @@ std::list Workbench::listCommandbars() const TYPESYSTEM_SOURCE(Gui::StdWorkbench, Gui::Workbench) StdWorkbench::StdWorkbench() - : Workbench() -{ -} + : Workbench() +{} StdWorkbench::~StdWorkbench() = default; void StdWorkbench::setupContextMenu(const char* recipient, MenuItem* item) const { - if (strcmp(recipient,"View") == 0) - { + if (strcmp(recipient, "View") == 0) { createLinkMenu(item); *item << "Separator"; auto StdViews = new MenuItem; - StdViews->setCommand( "Standard Views" ); + StdViews->setCommand("Standard Views"); - *StdViews << "Std_ViewIsometric" << "Separator" << "Std_ViewHome" << "Std_ViewFront" << "Std_ViewTop" << "Std_ViewRight" + *StdViews << "Std_ViewIsometric" << "Separator" << "Std_ViewHome" << "Std_ViewFront" + << "Std_ViewTop" << "Std_ViewRight" << "Std_ViewRear" << "Std_ViewBottom" << "Std_ViewLeft" << "Separator" << "Std_ViewRotateLeft" << "Std_ViewRotateRight"; - *item << "Std_ViewFitAll" << "Std_ViewFitSelection" << "Std_AlignToSelection" << "Std_DrawStyle" - << StdViews << "Separator" + *item << "Std_ViewFitAll" << "Std_ViewFitSelection" << "Std_AlignToSelection" + << "Std_DrawStyle" << StdViews << "Separator" << "Std_ViewDockUndockFullscreen"; if (Gui::Selection().countObjectsOfType() > 0) { @@ -608,11 +653,11 @@ void StdWorkbench::setupContextMenu(const char* recipient, MenuItem* item) const << "Std_SendToPythonConsole" << "Std_TransformManip" << "Std_Placement"; } } - else if (strcmp(recipient,"Tree") == 0) - { + else if (strcmp(recipient, "Tree") == 0) { if (Gui::Selection().countObjectsOfType() > 0) { - *item << "Std_ToggleFreeze" << "Separator" - << "Std_Placement" << "Std_ToggleVisibility" << "Std_ShowSelection" << "Std_HideSelection" + *item << "Std_ToggleFreeze" << "Separator" + << "Std_Placement" << "Std_ToggleVisibility" << "Std_ShowSelection" + << "Std_HideSelection" << "Std_ToggleSelectability" << "Std_TreeSelectAllInstances" << "Separator" << "Std_RandomColor" << "Std_ToggleTransparency" << "Separator" << "Std_Cut" << "Std_Copy" << "Std_Paste" << "Std_Delete" @@ -633,7 +678,7 @@ MenuItem* StdWorkbench::setupMenuBar() const auto menuBar = new MenuItem; // File - auto file = new MenuItem( menuBar ); + auto file = new MenuItem(menuBar); file->setCommand("&File"); *file << "Std_New" << "Std_Open" << "Std_RecentFiles" << "Separator" << "Std_CloseActiveWindow" << "Std_CloseAllWindows" << "Separator" << "Std_Save" << "Std_SaveAs" @@ -643,14 +688,15 @@ MenuItem* StdWorkbench::setupMenuBar() const << "Separator" << "Std_Quit"; // Edit - auto edit = new MenuItem( menuBar ); + auto edit = new MenuItem(menuBar); edit->setCommand("&Edit"); *edit << "Std_Undo" << "Std_Redo" << "Separator" << "Std_Cut" << "Std_Copy" << "Std_Paste" << "Std_DuplicateSelection" << "Separator" << "Std_Refresh" << "Std_BoxSelection" << "Std_BoxElementSelection" << "Std_SelectAll" << "Std_Delete" << "Std_SendToPythonConsole" << "Separator" << "Std_Placement" << "Std_TransformManip" << "Std_Alignment" - << "Std_Edit" << "Std_Properties" << "Separator" << "Std_UserEditMode" << "Separator" << "Std_DlgPreferences"; + << "Std_Edit" << "Std_Properties" << "Separator" << "Std_UserEditMode" << "Separator" + << "Std_DlgPreferences"; auto axoviews = new MenuItem; axoviews->setCommand("A&xonometric"); @@ -688,18 +734,18 @@ MenuItem* StdWorkbench::setupMenuBar() const << "Separator" << "Std_ToggleSelectability"; // View - auto view = new MenuItem( menuBar ); + auto view = new MenuItem(menuBar); view->setCommand("&View"); - *view << "Std_ViewCreate" << "Std_OrthographicCamera" << "Std_PerspectiveCamera" << "Std_MainFullscreen" << "Separator" - << stdviews << "Std_FreezeViews" << "Std_DrawStyle" << "Std_SelBoundingBox" - << "Separator" << view3d << zoom - << "Std_ViewDockUndockFullscreen" << "Std_AxisCross" << "Std_ToggleClipPlane" + *view << "Std_ViewCreate" << "Std_OrthographicCamera" << "Std_PerspectiveCamera" + << "Std_MainFullscreen" << "Separator" << stdviews << "Std_FreezeViews" << "Std_DrawStyle" + << "Std_SelBoundingBox" + << "Separator" << view3d << zoom << "Std_ViewDockUndockFullscreen" << "Std_AxisCross" + << "Std_ToggleClipPlane" << "Std_TextureMapping" #ifdef BUILD_VR << "Std_ViewVR" #endif - << "Separator" << visu - << "Std_ToggleNavigation" + << "Separator" << visu << "Std_ToggleNavigation" << "Std_RandomColor" << "Std_ToggleTransparency" << "Separator" @@ -715,7 +761,7 @@ MenuItem* StdWorkbench::setupMenuBar() const << "Std_ViewStatusBar"; // Tools - auto tool = new MenuItem( menuBar ); + auto tool = new MenuItem(menuBar); tool->setCommand("&Tools"); #ifdef BUILD_ADDONMGR if (Application::Instance->commandManager().getCommandByName("Std_AddonMgr")) { @@ -741,7 +787,7 @@ MenuItem* StdWorkbench::setupMenuBar() const << "Std_DlgCustomize"; // Macro - auto macro = new MenuItem( menuBar ); + auto macro = new MenuItem(menuBar); macro->setCommand("&Macro"); *macro << "Std_DlgMacroRecord" << "Std_DlgMacroExecute" @@ -756,20 +802,21 @@ MenuItem* StdWorkbench::setupMenuBar() const << "Std_ToggleBreakpoint"; // Windows - auto wnd = new MenuItem( menuBar ); + auto wnd = new MenuItem(menuBar); wnd->setCommand("&Windows"); *wnd << "Std_ActivateNextWindow" << "Std_ActivatePrevWindow" << "Separator" << "Std_TileWindows" << "Std_CascadeWindows" << "Separator" << "Std_WindowsMenu" << "Std_Windows"; // Separator - auto sep = new MenuItem( menuBar ); - sep->setCommand( "Separator" ); + auto sep = new MenuItem(menuBar); + sep->setCommand("Separator"); // Help - auto help = new MenuItem( menuBar ); + auto help = new MenuItem(menuBar); help->setCommand("&Help"); - *help << "Std_WhatsThis" << "Separator" + *help << "Std_WhatsThis" + << "Separator" // Start page and additional separator are dynamically inserted here << "Std_FreeCADUserHub" << "Std_FreeCADForum" << "Std_ReportBug" << "Separator" << "Std_RestartInSafeMode" << "Separator" @@ -784,18 +831,18 @@ ToolBarItem* StdWorkbench::setupToolBars() const auto root = new ToolBarItem; // File - auto file = new ToolBarItem( root ); + auto file = new ToolBarItem(root); file->setCommand("File"); *file << "Std_New" << "Std_Open" << "Std_Save"; // Edit - auto edit = new ToolBarItem( root ); + auto edit = new ToolBarItem(root); edit->setCommand("Edit"); *edit << "Std_Undo" << "Std_Redo" << "Separator" << "Std_Refresh"; // Clipboard - auto clipboard = new ToolBarItem( root , ToolBarItem::DefaultVisibility::Hidden ); + auto clipboard = new ToolBarItem(root, ToolBarItem::DefaultVisibility::Hidden); clipboard->setCommand("Clipboard"); *clipboard << "Std_Cut" << "Std_Copy" << "Std_Paste"; @@ -805,13 +852,13 @@ ToolBarItem* StdWorkbench::setupToolBars() const *wb << "Std_Workbench"; // Macro - auto macro = new ToolBarItem( root, ToolBarItem::DefaultVisibility::Hidden); + auto macro = new ToolBarItem(root, ToolBarItem::DefaultVisibility::Hidden); macro->setCommand("Macro"); *macro << "Std_DlgMacroRecord" << "Std_DlgMacroExecute" << "Std_DlgMacroExecuteDirect"; // View - auto view = new ToolBarItem( root ); + auto view = new ToolBarItem(root); view->setCommand("View"); *view << "Std_ViewFitAll" << "Std_ViewFitSelection" << "Std_ViewGroup" << "Std_AlignToSelection" << "Separator" << "Std_DrawStyle" << "Std_TreeViewActions" << "Std_Measure"; @@ -828,12 +875,12 @@ ToolBarItem* StdWorkbench::setupToolBars() const << "Std_ViewLeft"; // Structure - auto structure = new ToolBarItem( root ); + auto structure = new ToolBarItem(root); structure->setCommand("Structure"); *structure << "Std_Part" << "Std_Group" << "Std_LinkActions" << "Std_VarSet"; // Help - auto help = new ToolBarItem( root ); + auto help = new ToolBarItem(root); help->setCommand("Help"); *help << "Std_WhatsThis"; @@ -845,14 +892,14 @@ ToolBarItem* StdWorkbench::setupCommandBars() const auto root = new ToolBarItem; // View - auto view = new ToolBarItem( root ); + auto view = new ToolBarItem(root); view->setCommand("Standard Views"); *view << "Std_ViewFitAll" << "Std_ViewFitSelection" << "Std_ViewIsometric" << "Separator" << "Std_ViewFront" << "Std_ViewRight" << "Std_ViewTop" << "Std_ViewRear" << "Std_ViewLeft" << "Std_ViewBottom"; // Special Ops - auto macro = new ToolBarItem( root ); + auto macro = new ToolBarItem(root); macro->setCommand("Special Ops"); *macro << "Std_DlgParameter" << "Std_DlgPreferences" << "Std_DlgMacroRecord" << "Std_DlgMacroExecute" << "Std_DlgCustomize"; @@ -871,13 +918,17 @@ DockWindowItems* StdWorkbench::setupDockWindows() const root->addDockWidget("Std_ReportView", Qt::BottomDockWidgetArea, Gui::DockWindowOption::HiddenTabbed); root->addDockWidget("Std_PythonView", Qt::BottomDockWidgetArea, Gui::DockWindowOption::HiddenTabbed); - //Dagview through parameter. - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("DockWindows")->GetGroup("DAGView"); + // Dagview through parameter. + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("DockWindows") + ->GetGroup("DAGView"); bool enabled = group->GetBool("Enabled", false); if (enabled) { - root->addDockWidget("Std_DAGView", Qt::RightDockWidgetArea, Gui::DockWindowOption::Hidden); + root->addDockWidget("Std_DAGView", Qt::RightDockWidgetArea, Gui::DockWindowOption::Hidden); } return root; @@ -888,16 +939,15 @@ DockWindowItems* StdWorkbench::setupDockWindows() const TYPESYSTEM_SOURCE(Gui::BlankWorkbench, Gui::Workbench) BlankWorkbench::BlankWorkbench() - : Workbench() -{ -} + : Workbench() +{} BlankWorkbench::~BlankWorkbench() = default; void BlankWorkbench::activated() { QList dw = getMainWindow()->findChildren(); - for (auto & it : dw) { + for (auto& it : dw) { it->toggleViewAction()->setVisible(false); } getMainWindow()->statusBar()->hide(); @@ -908,7 +958,7 @@ void BlankWorkbench::deactivated() getMainWindow()->statusBar()->show(); } -void BlankWorkbench::setupContextMenu(const char* recipient,MenuItem* item) const +void BlankWorkbench::setupContextMenu(const char* recipient, MenuItem* item) const { Q_UNUSED(recipient); Q_UNUSED(item); @@ -939,13 +989,12 @@ DockWindowItems* BlankWorkbench::setupDockWindows() const TYPESYSTEM_SOURCE(Gui::NoneWorkbench, Gui::StdWorkbench) NoneWorkbench::NoneWorkbench() - : StdWorkbench() -{ -} + : StdWorkbench() +{} NoneWorkbench::~NoneWorkbench() = default; -void NoneWorkbench::setupContextMenu(const char* recipient,MenuItem* item) const +void NoneWorkbench::setupContextMenu(const char* recipient, MenuItem* item) const { Q_UNUSED(recipient); Q_UNUSED(item); @@ -957,26 +1006,26 @@ MenuItem* NoneWorkbench::setupMenuBar() const auto menuBar = new MenuItem; // File - auto file = new MenuItem( menuBar ); + auto file = new MenuItem(menuBar); file->setCommand("&File"); *file << "Std_Quit"; // Edit - auto edit = new MenuItem( menuBar ); + auto edit = new MenuItem(menuBar); edit->setCommand("&Edit"); *edit << "Std_DlgPreferences"; // View - auto view = new MenuItem( menuBar ); + auto view = new MenuItem(menuBar); view->setCommand("&View"); *view << "Std_Workbench"; // Separator - auto sep = new MenuItem( menuBar ); + auto sep = new MenuItem(menuBar); sep->setCommand("Separator"); // Help - auto help = new MenuItem( menuBar ); + auto help = new MenuItem(menuBar); help->setCommand("&Help"); *help << "Std_OnlineHelp" << "Std_About"; @@ -1007,9 +1056,8 @@ DockWindowItems* NoneWorkbench::setupDockWindows() const TYPESYSTEM_SOURCE(Gui::TestWorkbench, Gui::Workbench) TestWorkbench::TestWorkbench() - : StdWorkbench() -{ -} + : StdWorkbench() +{} TestWorkbench::~TestWorkbench() = default; @@ -1023,14 +1071,14 @@ MenuItem* TestWorkbench::setupMenuBar() const // Test commands auto test = new MenuItem; - menuBar->insertItem( item, test ); - test->setCommand( "Test &Commands" ); + menuBar->insertItem(item, test); + test->setCommand("Test &Commands"); *test << "Std_Test1" << "Std_Test2" << "Std_Test3" << "Std_Test4" << "Std_Test5" << "Std_Test6" << "Std_Test7" << "Std_Test8"; // Inventor View auto opiv = new MenuItem; - menuBar->insertItem( item, opiv ); + menuBar->insertItem(item, opiv); opiv->setCommand("&Inventor View"); *opiv << "Std_ViewExample1" << "Std_ViewExample2" << "Std_ViewExample3"; @@ -1068,8 +1116,7 @@ PythonBaseWorkbench::~PythonBaseWorkbench() PyObject* PythonBaseWorkbench::getPyObject() { - if (!_workbenchPy) - { + if (!_workbenchPy) { _workbenchPy = new PythonWorkbenchPy(this); } @@ -1103,23 +1150,26 @@ void PythonBaseWorkbench::setupContextMenu(const char* recipient, MenuItem* item { Q_UNUSED(recipient); QList items = _contextMenu->getItems(); - for (const auto & it : items) { + for (const auto& it : items) { item->appendItem(it->copy()); } } -void PythonBaseWorkbench::appendMenu(const std::list& menu, const std::list& items) const +void PythonBaseWorkbench::appendMenu( + const std::list& menu, + const std::list& items +) const { - if ( menu.empty() || items.empty() ) { + if (menu.empty() || items.empty()) { return; } - auto jt=menu.begin(); - MenuItem* item = _menuBar->findItem( *jt ); + auto jt = menu.begin(); + MenuItem* item = _menuBar->findItem(*jt); if (!item) { item = new MenuItem; - item->setCommand( *jt ); - Gui::MenuItem* wnd = _menuBar->findItem( "&Windows" ); + item->setCommand(*jt); + Gui::MenuItem* wnd = _menuBar->findItem("&Windows"); if (wnd) { _menuBar->insertItem(wnd, item); } @@ -1129,18 +1179,16 @@ void PythonBaseWorkbench::appendMenu(const std::list& menu, const s } // create sub menus - for ( jt++; jt != menu.end(); jt++ ) - { - MenuItem* subitem = item->findItem( *jt ); - if ( !subitem ) - { + for (jt++; jt != menu.end(); jt++) { + MenuItem* subitem = item->findItem(*jt); + if (!subitem) { subitem = new MenuItem(item); - subitem->setCommand( *jt ); + subitem->setCommand(*jt); } item = subitem; } - for (const auto & it : items) { + for (const auto& it : items) { *item << it; } } @@ -1148,16 +1196,19 @@ void PythonBaseWorkbench::appendMenu(const std::list& menu, const s void PythonBaseWorkbench::removeMenu(const std::string& menu) const { MenuItem* item = _menuBar->findItem(menu); - if ( item ) { + if (item) { _menuBar->removeItem(item); delete item; } } -void PythonBaseWorkbench::appendContextMenu(const std::list& menu, const std::list& items) const +void PythonBaseWorkbench::appendContextMenu( + const std::list& menu, + const std::list& items +) const { MenuItem* item = _contextMenu; - for (const auto & jt : menu) { + for (const auto& jt : menu) { MenuItem* subitem = item->findItem(jt); if (!subitem) { subitem = new MenuItem(item); @@ -1166,7 +1217,7 @@ void PythonBaseWorkbench::appendContextMenu(const std::list& menu, item = subitem; } - for (const auto & it : items) { + for (const auto& it : items) { *item << it; } } @@ -1193,7 +1244,7 @@ void PythonBaseWorkbench::appendToolbar(const std::string& bar, const std::list< item->setCommand(bar); } - for (const auto & it : items) { + for (const auto& it : items) { *item << it; } } @@ -1209,13 +1260,13 @@ void PythonBaseWorkbench::removeToolbar(const std::string& bar) const void PythonBaseWorkbench::appendCommandbar(const std::string& bar, const std::list& items) const { - ToolBarItem* item = _commandBar->findItem( bar ); + ToolBarItem* item = _commandBar->findItem(bar); if (!item) { item = new ToolBarItem(_commandBar); item->setCommand(bar); } - for (const auto & it : items) { + for (const auto& it : items) { *item << it; } } diff --git a/src/Gui/Workbench.h b/src/Gui/Workbench.h index 2bb9c2cf40..e3152bdce8 100644 --- a/src/Gui/Workbench.h +++ b/src/Gui/Workbench.h @@ -30,11 +30,13 @@ #include #include -namespace Base { +namespace Base +{ class PyObjectBase; } -namespace Gui { +namespace Gui +{ class MenuItem; class ToolBarItem; @@ -49,7 +51,7 @@ class WorkbenchManager; * loaded into RAM. * @author Werner Mayer */ -class GuiExport Workbench : public Base::BaseClass +class GuiExport Workbench: public Base::BaseClass { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -90,11 +92,11 @@ public: virtual void deactivated(); /// helper to add TaskWatcher to the TaskView - void addTaskWatcher(const std::vector &Watcher); + void addTaskWatcher(const std::vector& Watcher); /// remove the added TaskWatcher void removeTaskWatcher(); - static void createLinkMenu(MenuItem *); + static void createLinkMenu(MenuItem*); //// Shows a list of all toolbars std::list listToolbars() const; @@ -113,17 +115,17 @@ public: protected: /** Returns a MenuItem tree structure of menus for this workbench. */ - virtual MenuItem* setupMenuBar() const=0; + virtual MenuItem* setupMenuBar() const = 0; /** Returns a ToolBarItem tree structure of toolbars for this workbench. */ - virtual ToolBarItem* setupToolBars() const=0; + virtual ToolBarItem* setupToolBars() const = 0; /** Returns a ToolBarItem tree structure of command bars for this workbench. */ - virtual ToolBarItem* setupCommandBars() const=0; + virtual ToolBarItem* setupCommandBars() const = 0; /** Returns a DockWindowItems structure of dock windows this workbench. */ - virtual DockWindowItems* setupDockWindows() const=0; + virtual DockWindowItems* setupDockWindows() const = 0; /** Sets up the contextmenu for this workbench. * The default implementation does nothing. */ - virtual void setupContextMenu(const char* recipient,MenuItem*) const; + virtual void setupContextMenu(const char* recipient, MenuItem*) const; /** Add permanent menu items to the structure */ void addPermanentMenuItems(MenuItem*) const; @@ -147,7 +149,7 @@ private: * to have defined the standard GUI elements. * @author Werner Mayer */ -class GuiExport StdWorkbench : public Workbench +class GuiExport StdWorkbench: public Workbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -177,7 +179,7 @@ protected: * The BlankWorkbench class defines a complete empty workbench. * @author Werner Mayer */ -class GuiExport BlankWorkbench : public Workbench +class GuiExport BlankWorkbench: public Workbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -186,7 +188,7 @@ public: ~BlankWorkbench() override; /** Defines the standard context menu. */ - void setupContextMenu(const char* recipient,MenuItem*) const override; + void setupContextMenu(const char* recipient, MenuItem*) const override; /** Run some actions when the workbench gets activated. */ void activated() override; /** Run some actions when the workbench gets deactivated. */ @@ -207,7 +209,7 @@ protected: * The NoneWorkbench class defines a slim workbench. * @author Werner Mayer */ -class GuiExport NoneWorkbench : public StdWorkbench +class GuiExport NoneWorkbench: public StdWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -216,7 +218,7 @@ public: ~NoneWorkbench() override; /** Defines the standard context menu. */ - void setupContextMenu(const char* recipient,MenuItem*) const override; + void setupContextMenu(const char* recipient, MenuItem*) const override; protected: /** Defines the standard menus. */ @@ -229,7 +231,7 @@ protected: DockWindowItems* setupDockWindows() const override; }; -class GuiExport TestWorkbench : public StdWorkbench +class GuiExport TestWorkbench: public StdWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -248,7 +250,7 @@ protected: * Therefore PythonWorkbenchPy provides the required Python interface. * @author Werner Mayer */ -class GuiExport PythonBaseWorkbench : public Workbench +class GuiExport PythonBaseWorkbench: public Workbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -265,13 +267,13 @@ public: /// Appends a new menu void appendMenu(const std::list& menu, const std::list& items) const; /// Removes a menu - void removeMenu(const std::string& menu ) const; + void removeMenu(const std::string& menu) const; /// Appends new context menu items void appendContextMenu(const std::list& menu, const std::list& items) const; /// Removes a context menu - void removeContextMenu(const std::string& menu ) const; - void setupContextMenu(const char* recipient,MenuItem*) const override; + void removeContextMenu(const std::string& menu) const; + void setupContextMenu(const char* recipient, MenuItem*) const override; void clearContextMenu(); /// Appends a new toolbar @@ -292,14 +294,14 @@ protected: DockWindowItems* setupDockWindows() const override; protected: - MenuItem* _menuBar{nullptr}; - MenuItem* _contextMenu{nullptr}; - ToolBarItem* _toolBar{nullptr}; - ToolBarItem* _commandBar{nullptr}; - Base::PyObjectBase* _workbenchPy{nullptr}; + MenuItem* _menuBar {nullptr}; + MenuItem* _contextMenu {nullptr}; + ToolBarItem* _toolBar {nullptr}; + ToolBarItem* _commandBar {nullptr}; + Base::PyObjectBase* _workbenchPy {nullptr}; }; -class GuiExport PythonBlankWorkbench : public PythonBaseWorkbench +class GuiExport PythonBlankWorkbench: public PythonBaseWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -313,7 +315,7 @@ public: * Therefore PythonWorkbenchPy provides the required Python interface. * @author Werner Mayer */ -class GuiExport PythonWorkbench : public PythonBaseWorkbench +class GuiExport PythonWorkbench: public PythonBaseWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -332,7 +334,7 @@ protected: DockWindowItems* setupDockWindows() const override; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_WORKBENCH_H +#endif // GUI_WORKBENCH_H diff --git a/src/Gui/Workbench.pyi b/src/Gui/Workbench.pyi index 0c88fb61d8..3688761e93 100644 --- a/src/Gui/Workbench.pyi +++ b/src/Gui/Workbench.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from Base.BaseClass import BaseClass from typing import Any, List, Dict - @export( Include="Gui/Workbench.h", ) diff --git a/src/Gui/WorkbenchFactory.cpp b/src/Gui/WorkbenchFactory.cpp index 35a4bf4e1b..7ecb992296 100644 --- a/src/Gui/WorkbenchFactory.cpp +++ b/src/Gui/WorkbenchFactory.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ - - #include "WorkbenchFactory.h" #include "Workbench.h" @@ -32,27 +30,28 @@ Gui::WorkbenchFactoryInst* Gui::WorkbenchFactoryInst::_pcSingleton = nullptr; WorkbenchFactoryInst& WorkbenchFactoryInst::instance() { - if (!_pcSingleton) - _pcSingleton = new WorkbenchFactoryInst; - return *_pcSingleton; + if (!_pcSingleton) { + _pcSingleton = new WorkbenchFactoryInst; + } + return *_pcSingleton; } -void WorkbenchFactoryInst::destruct () +void WorkbenchFactoryInst::destruct() { delete _pcSingleton; _pcSingleton = nullptr; } -Workbench* WorkbenchFactoryInst::createWorkbench ( const char* sName ) const +Workbench* WorkbenchFactoryInst::createWorkbench(const char* sName) const { - auto obj = (Workbench*)Produce( sName ); + auto obj = (Workbench*)Produce(sName); auto wb = freecad_cast(obj); if (!wb) { - delete obj; // delete the unknown object as no workbench object + delete obj; // delete the unknown object as no workbench object return nullptr; } - wb->setName( sName ); + wb->setName(sName); return wb; } diff --git a/src/Gui/WorkbenchFactory.h b/src/Gui/WorkbenchFactory.h index b7ef2cdbdb..4084d5c10b 100644 --- a/src/Gui/WorkbenchFactory.h +++ b/src/Gui/WorkbenchFactory.h @@ -28,7 +28,8 @@ #include #include -namespace Gui { +namespace Gui +{ class Workbench; /** @@ -38,31 +39,31 @@ class Workbench; * @note To create workbenches you should use the API of WorkbenchManager. * @author Werner Mayer */ -class GuiExport WorkbenchFactoryInst : public Base::Factory +class GuiExport WorkbenchFactoryInst: public Base::Factory { public: - /// The one and only instance. - static WorkbenchFactoryInst& instance(); - /// Destructs the sole instance. - static void destruct (); + /// The one and only instance. + static WorkbenchFactoryInst& instance(); + /// Destructs the sole instance. + static void destruct(); - /** Creates the workbench with \a name. If no such workbench is registered - * 0 is returned. - */ - Workbench* createWorkbench ( const char* sName ) const; - /** Returns a list of all registered workbench classes. */ - std::list workbenches() const; + /** Creates the workbench with \a name. If no such workbench is registered + * 0 is returned. + */ + Workbench* createWorkbench(const char* sName) const; + /** Returns a list of all registered workbench classes. */ + std::list workbenches() const; private: - static WorkbenchFactoryInst* _pcSingleton; + static WorkbenchFactoryInst* _pcSingleton; - WorkbenchFactoryInst() = default; - ~WorkbenchFactoryInst() override = default; + WorkbenchFactoryInst() = default; + ~WorkbenchFactoryInst() override = default; }; inline GuiExport WorkbenchFactoryInst& WorkbenchFactory() { - return WorkbenchFactoryInst::instance(); + return WorkbenchFactoryInst::instance(); } // -------------------------------------------------------------------- @@ -72,20 +73,20 @@ inline GuiExport WorkbenchFactoryInst& WorkbenchFactory() * classes. * @author Werner Mayer */ -template +template class WorkbenchProducer: public Base::AbstractProducer { public: - WorkbenchProducer() = default; + WorkbenchProducer() = default; - ~WorkbenchProducer () override = default; + ~WorkbenchProducer() override = default; - void* Produce () const override - { - return (new CLASS); - } + void* Produce() const override + { + return (new CLASS); + } }; -} // namespace Gui +} // namespace Gui -#endif // GUI_WORKBENCHFACTORY_H +#endif // GUI_WORKBENCHFACTORY_H diff --git a/src/Gui/WorkbenchManager.cpp b/src/Gui/WorkbenchManager.cpp index 784a3f321c..5832187b92 100644 --- a/src/Gui/WorkbenchManager.cpp +++ b/src/Gui/WorkbenchManager.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ - - #include #include "WorkbenchManager.h" @@ -37,8 +35,9 @@ WorkbenchManager* WorkbenchManager::_instance = nullptr; WorkbenchManager* WorkbenchManager::instance() { - if (!_instance) + if (!_instance) { _instance = new WorkbenchManager; + } return _instance; } @@ -52,24 +51,25 @@ WorkbenchManager::WorkbenchManager() = default; WorkbenchManager::~WorkbenchManager() { - for (auto & it : _workbenches) { + for (auto& it : _workbenches) { Workbench* wb = it.second; delete wb; } MenuManager::destruct(); ToolBarManager::destruct(); - //ToolBoxManager::destruct(); + // ToolBoxManager::destruct(); DockWindowManager::destruct(); } -Workbench* WorkbenchManager::createWorkbench (const std::string& name, const std::string& className) +Workbench* WorkbenchManager::createWorkbench(const std::string& name, const std::string& className) { Workbench* wb = getWorkbench(name); if (!wb) { // try to create an instance now - Base::Type type = Base::Type::getTypeIfDerivedFrom(className.c_str(), Workbench::getClassTypeId(), false); + Base::Type type + = Base::Type::getTypeIfDerivedFrom(className.c_str(), Workbench::getClassTypeId(), false); wb = static_cast(type.createInstance()); // createInstance could return a null pointer if (!wb) { @@ -91,15 +91,16 @@ void WorkbenchManager::removeWorkbench(const std::string& name) if (it != _workbenches.end()) { Workbench* wb = it->second; _workbenches.erase(it); - if (_activeWorkbench == wb) + if (_activeWorkbench == wb) { _activeWorkbench = nullptr; + } delete wb; } } -Workbench* WorkbenchManager::getWorkbench (const std::string& name) const +Workbench* WorkbenchManager::getWorkbench(const std::string& name) const { - Workbench* wb=nullptr; + Workbench* wb = nullptr; std::map::const_iterator it = _workbenches.find(name); if (it != _workbenches.end()) { @@ -139,7 +140,8 @@ std::string WorkbenchManager::activeName() const std::list WorkbenchManager::workbenches() const { std::list wb; - for (const auto & it : _workbenches) + for (const auto& it : _workbenches) { wb.push_back(it.first); + } return wb; } diff --git a/src/Gui/WorkbenchManager.h b/src/Gui/WorkbenchManager.h index 40f68e8497..a20fdf9892 100644 --- a/src/Gui/WorkbenchManager.h +++ b/src/Gui/WorkbenchManager.h @@ -29,7 +29,8 @@ #include #include -namespace Gui { +namespace Gui +{ class Workbench; @@ -48,7 +49,7 @@ public: * such workbench exists then a workbench of class \a className gets created, if possible. * If the workbench cannot be created 0 is returned. */ - Workbench* createWorkbench (const std::string& name, const std::string& className); + Workbench* createWorkbench(const std::string& name, const std::string& className); /** Removes the workbench with name \a name. If there is no such * workbench exists nothing happens. */ @@ -56,7 +57,7 @@ public: /** Returns an instance of the workbench with name \a name. If there is * no such workbench 0 is returned. */ - Workbench* getWorkbench (const std::string& name) const; + Workbench* getWorkbench(const std::string& name) const; /** Activates the workbench with name \a name. */ bool activate(const std::string& name, const std::string& className); /** Returns the active workbench. */ @@ -72,11 +73,11 @@ protected: private: static WorkbenchManager* _instance; - Workbench* _activeWorkbench{nullptr}; + Workbench* _activeWorkbench {nullptr}; std::map _workbenches; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_WORKBENCHMANAGER_H +#endif // GUI_WORKBENCHMANAGER_H diff --git a/src/Gui/WorkbenchManipulator.cpp b/src/Gui/WorkbenchManipulator.cpp index 96c7a89d1e..360e25a707 100644 --- a/src/Gui/WorkbenchManipulator.cpp +++ b/src/Gui/WorkbenchManipulator.cpp @@ -22,12 +22,11 @@ **************************************************************************/ - #include "WorkbenchManipulator.h" using namespace Gui; -std::set WorkbenchManipulator::manipulators; // NOLINT +std::set WorkbenchManipulator::manipulators; // NOLINT void WorkbenchManipulator::installManipulator(const WorkbenchManipulator::Ptr& ptr) { @@ -81,18 +80,16 @@ void WorkbenchManipulator::changeDockWindows(DockWindowItems* dockWindow) } void WorkbenchManipulator::modifyMenuBar([[maybe_unused]] MenuItem* menuBar) -{ -} +{} -void WorkbenchManipulator::modifyContextMenu([[maybe_unused]] const char* recipient, - [[maybe_unused]] MenuItem* menuBar) -{ -} +void WorkbenchManipulator::modifyContextMenu( + [[maybe_unused]] const char* recipient, + [[maybe_unused]] MenuItem* menuBar +) +{} void WorkbenchManipulator::modifyToolBars([[maybe_unused]] ToolBarItem* toolBar) -{ -} +{} void WorkbenchManipulator::modifyDockWindows([[maybe_unused]] DockWindowItems* dockWindow) -{ -} +{} diff --git a/src/Gui/WorkbenchManipulator.h b/src/Gui/WorkbenchManipulator.h index b4a0444e84..1ceef23a6d 100644 --- a/src/Gui/WorkbenchManipulator.h +++ b/src/Gui/WorkbenchManipulator.h @@ -31,7 +31,8 @@ #include #include -namespace Gui { +namespace Gui +{ class DockWindowItems; class MenuItem; @@ -99,8 +100,10 @@ protected: * Method to manipulate the contextmenu structure of a workbench. * The default implementation doesn't change anything. */ - virtual void modifyContextMenu([[maybe_unused]] const char* recipient, - [[maybe_unused]] MenuItem* menuBar); + virtual void modifyContextMenu( + [[maybe_unused]] const char* recipient, + [[maybe_unused]] MenuItem* menuBar + ); /*! * \brief modifyToolBars * Method to manipulate the toolbar structure of a workbench @@ -117,17 +120,17 @@ protected: public: WorkbenchManipulator(const WorkbenchManipulator&) = delete; WorkbenchManipulator(WorkbenchManipulator&&) = delete; - WorkbenchManipulator& operator = (const WorkbenchManipulator&) = delete; - WorkbenchManipulator& operator = (WorkbenchManipulator&&) = delete; + WorkbenchManipulator& operator=(const WorkbenchManipulator&) = delete; + WorkbenchManipulator& operator=(WorkbenchManipulator&&) = delete; protected: static std::set getManipulators(); private: - static std::set manipulators; // NOLINT + static std::set manipulators; // NOLINT }; -} // namespace Gui +} // namespace Gui -#endif // GUI_WORKBENCHMANIPULATOR_H +#endif // GUI_WORKBENCHMANIPULATOR_H diff --git a/src/Gui/WorkbenchManipulatorPython.cpp b/src/Gui/WorkbenchManipulatorPython.cpp index e58ae33543..3fd13ab669 100644 --- a/src/Gui/WorkbenchManipulatorPython.cpp +++ b/src/Gui/WorkbenchManipulatorPython.cpp @@ -22,7 +22,6 @@ **************************************************************************/ - #include "WorkbenchManipulatorPython.h" #include "MenuManager.h" #include "ToolBarManager.h" @@ -53,8 +52,7 @@ void WorkbenchManipulatorPython::removeManipulator(const Py::Object& obj) WorkbenchManipulatorPython::WorkbenchManipulatorPython(const Py::Object& obj) : object(obj) -{ -} +{} WorkbenchManipulatorPython::~WorkbenchManipulatorPython() { @@ -88,7 +86,7 @@ void WorkbenchManipulatorPython::modifyMenuBar(MenuItem* menuBar) tryModifyMenuBar(menuBar); } catch (Py::Exception&) { - Base::PyException exc; // extract the Python error text + Base::PyException exc; // extract the Python error text exc.reportException(); } } @@ -165,7 +163,6 @@ void WorkbenchManipulatorPython::tryModifyMenuBar(const Py::Dict& dict, MenuItem delete item; // NOLINT } } - } } @@ -193,7 +190,7 @@ void WorkbenchManipulatorPython::modifyContextMenu(const char* recipient, MenuIt tryModifyContextMenu(recipient, menuBar); } catch (Py::Exception&) { - Base::PyException exc; // extract the Python error text + Base::PyException exc; // extract the Python error text exc.reportException(); } } @@ -231,7 +228,7 @@ void WorkbenchManipulatorPython::modifyToolBars(ToolBarItem* toolBar) tryModifyToolBar(toolBar); } catch (Py::Exception&) { - Base::PyException exc; // extract the Python error text + Base::PyException exc; // extract the Python error text exc.reportException(); } } @@ -339,7 +336,7 @@ void WorkbenchManipulatorPython::modifyDockWindows(DockWindowItems* dockWindow) tryModifyDockWindows(dockWindow); } catch (Py::Exception&) { - Base::PyException exc; // extract the Python error text + Base::PyException exc; // extract the Python error text exc.reportException(); } } @@ -364,7 +361,8 @@ void WorkbenchManipulatorPython::tryModifyDockWindows(DockWindowItems* dockWindo } } -void WorkbenchManipulatorPython::tryModifyDockWindows([[maybe_unused]]const Py::Dict& dict, - [[maybe_unused]]DockWindowItems* dockWindow) -{ -} +void WorkbenchManipulatorPython::tryModifyDockWindows( + [[maybe_unused]] const Py::Dict& dict, + [[maybe_unused]] DockWindowItems* dockWindow +) +{} diff --git a/src/Gui/WorkbenchManipulatorPython.h b/src/Gui/WorkbenchManipulatorPython.h index 573f916438..c8dfe1ec45 100644 --- a/src/Gui/WorkbenchManipulatorPython.h +++ b/src/Gui/WorkbenchManipulatorPython.h @@ -28,14 +28,15 @@ #include #include -namespace Gui { +namespace Gui +{ /** * The WorkbenchManipulatorPython class accepts an instance of a Python class * that is supposed to implement any of the virtual functions. * @author Werner Mayer */ -class GuiExport WorkbenchManipulatorPython : public WorkbenchManipulator +class GuiExport WorkbenchManipulatorPython: public WorkbenchManipulator { public: static void installManipulator(const Py::Object& obj); @@ -68,8 +69,8 @@ protected: public: WorkbenchManipulatorPython(const WorkbenchManipulatorPython&) = delete; WorkbenchManipulatorPython(WorkbenchManipulatorPython&&) = delete; - WorkbenchManipulatorPython& operator = (const WorkbenchManipulatorPython&) = delete; - WorkbenchManipulatorPython& operator = (WorkbenchManipulatorPython&&) = delete; + WorkbenchManipulatorPython& operator=(const WorkbenchManipulatorPython&) = delete; + WorkbenchManipulatorPython& operator=(WorkbenchManipulatorPython&&) = delete; private: void tryModifyMenuBar(MenuItem* menuBar); @@ -85,7 +86,7 @@ private: Py::Object object; }; -} // namespace Gui +} // namespace Gui -#endif // GUI_WORKBENCHMANIPULATOR_PYTHON_H +#endif // GUI_WORKBENCHMANIPULATOR_PYTHON_H diff --git a/src/Gui/WorkbenchPyImp.cpp b/src/Gui/WorkbenchPyImp.cpp index b7a859beec..cc1f927cc8 100644 --- a/src/Gui/WorkbenchPyImp.cpp +++ b/src/Gui/WorkbenchPyImp.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ - - #include "Workbench.h" #include "WorkbenchManager.h" @@ -49,72 +47,87 @@ std::string WorkbenchPy::representation() const } /** Retrieves the workbench name */ -PyObject* WorkbenchPy::name(PyObject *args) +PyObject* WorkbenchPy::name(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { Py::String name(getWorkbenchPtr()->name()); return Py::new_reference_to(name); - }PY_CATCH; + } + PY_CATCH; } /** Activates the workbench object */ -PyObject* WorkbenchPy::activate(PyObject *args) +PyObject* WorkbenchPy::activate(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { std::string name = getWorkbenchPtr()->name(); - WorkbenchManager::instance()->activate( name, getWorkbenchPtr()->getTypeId().getName() ); + WorkbenchManager::instance()->activate(name, getWorkbenchPtr()->getTypeId().getName()); Py_Return; - }PY_CATCH; + } + PY_CATCH; } /** Shows a list of all menus */ -PyObject* WorkbenchPy::listMenus(PyObject *args) +PyObject* WorkbenchPy::listMenus(PyObject* args) { - PY_TRY { - if (!PyArg_ParseTuple(args, "")) + PY_TRY + { + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::list menus = getWorkbenchPtr()->listMenus(); Py::List list; - for (const auto & menu : menus) { + for (const auto& menu : menus) { list.append(Py::String(menu)); } return Py::new_reference_to(list); - } PY_CATCH; + } + PY_CATCH; } /** Shows a list of all toolbars */ -PyObject* WorkbenchPy::listToolbars(PyObject *args) +PyObject* WorkbenchPy::listToolbars(PyObject* args) { - PY_TRY { - if (!PyArg_ParseTuple(args, "")) + PY_TRY + { + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::list bars = getWorkbenchPtr()->listToolbars(); Py::List list; - for (const auto & bar : bars) { + for (const auto& bar : bars) { list.append(Py::String(bar)); } return Py::new_reference_to(list); - } PY_CATCH; + } + PY_CATCH; } /** Shows a dict of all toolbars and their commands*/ -PyObject* WorkbenchPy::getToolbarItems(PyObject *args) +PyObject* WorkbenchPy::getToolbarItems(PyObject* args) { - PY_TRY { - if (!PyArg_ParseTuple(args, "")) + PY_TRY + { + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - std::list>> bars = getWorkbenchPtr()->getToolbarItems(); + std::list>> bars + = getWorkbenchPtr()->getToolbarItems(); Py::Dict dict; for (const auto& it : bars) { @@ -125,38 +138,46 @@ PyObject* WorkbenchPy::getToolbarItems(PyObject *args) dict.setItem(it.first, list); } return Py::new_reference_to(dict); - } PY_CATCH; + } + PY_CATCH; } /** Shows a list of all command bars */ -PyObject* WorkbenchPy::listCommandbars(PyObject *args) +PyObject* WorkbenchPy::listCommandbars(PyObject* args) { - PY_TRY { - if (!PyArg_ParseTuple(args, "")) + PY_TRY + { + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } std::list bars = getWorkbenchPtr()->listCommandbars(); Py::List list; - for (const auto & bar : bars) { + for (const auto& bar : bars) { list.append(Py::String(bar)); } return Py::new_reference_to(list); - } PY_CATCH; + } + PY_CATCH; } /** Reload the workbench */ -PyObject* WorkbenchPy::reloadActive(PyObject *args) +PyObject* WorkbenchPy::reloadActive(PyObject* args) { - PY_TRY { - if (!PyArg_ParseTuple(args, "")) + PY_TRY + { + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Workbench* active = Gui::WorkbenchManager::instance()->active(); - if (active) + if (active) { active->activate(); + } Py_Return; - } PY_CATCH; + } + PY_CATCH; } PyObject* WorkbenchPy::getCustomAttributes(const char*) const @@ -164,7 +185,7 @@ PyObject* WorkbenchPy::getCustomAttributes(const char*) const return nullptr; } -int WorkbenchPy::setCustomAttributes(const char*, PyObject *) +int WorkbenchPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Gui/WorkbenchSelector.cpp b/src/Gui/WorkbenchSelector.cpp index 04f1ae13e3..2fab705ad0 100644 --- a/src/Gui/WorkbenchSelector.cpp +++ b/src/Gui/WorkbenchSelector.cpp @@ -20,17 +20,15 @@ ***************************************************************************/ - - -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "Base/Tools.h" @@ -45,7 +43,8 @@ using namespace Gui; -WorkbenchComboBox::WorkbenchComboBox(WorkbenchGroup* aGroup, QWidget* parent) : QComboBox(parent) +WorkbenchComboBox::WorkbenchComboBox(WorkbenchGroup* aGroup, QWidget* parent) + : QComboBox(parent) { setIconSize(QSize(16, 16)); setToolTip(aGroup->toolTip()); @@ -67,7 +66,7 @@ void WorkbenchComboBox::showPopup() if (rows > 0) { int height = view()->sizeHintForRow(0); int maxHeight = QApplication::primaryScreen()->size().height(); - view()->setMinimumHeight(qMin(height * rows, maxHeight/2)); + view()->setMinimumHeight(qMin(height * rows, maxHeight / 2)); } QComboBox::showPopup(); @@ -77,7 +76,9 @@ void WorkbenchComboBox::refreshList(QList actionList) { clear(); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Workbenches"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Workbenches" + ); auto itemStyle = static_cast(hGrp->GetInt("WorkbenchSelectorItem", 0)); @@ -88,7 +89,7 @@ void WorkbenchComboBox::refreshList(QList actionList) addItem(action->text()); } else if (itemStyle == WorkbenchItemStyle::IconOnly) { - addItem(icon, {}); // empty string to ensure that only icon is displayed + addItem(icon, {}); // empty string to ensure that only icon is displayed } else { addItem(icon, action->text()); @@ -146,7 +147,12 @@ WorkbenchTabWidget::WorkbenchTabWidget(WorkbenchGroup* aGroup, QWidget* parent) updateWorkbenchList(); connect(aGroup, &WorkbenchGroup::workbenchListRefreshed, this, &WorkbenchTabWidget::updateWorkbenchList); - connect(aGroup->groupAction(), &QActionGroup::triggered, this, &WorkbenchTabWidget::handleWorkbenchSelection); + connect( + aGroup->groupAction(), + &QActionGroup::triggered, + this, + &WorkbenchTabWidget::handleWorkbenchSelection + ); connect(tabBar, &QTabBar::currentChanged, this, &WorkbenchTabWidget::handleTabChange); if (auto toolBar = qobject_cast(parent)) { @@ -204,7 +210,9 @@ int WorkbenchTabWidget::tabIndexForWorkbenchActivateAction(QAction* workbenchAct WorkbenchItemStyle Gui::WorkbenchTabWidget::itemStyle() const { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Workbenches"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Workbenches" + ); return static_cast(hGrp->GetInt("WorkbenchSelectorItem", 0)); } @@ -220,7 +228,10 @@ void WorkbenchTabWidget::updateLayout() tabBar->setSizePolicy(toolBar->sizePolicy()); if (toolBar->isFloating()) { - setToolBarArea(toolBar->orientation() == Qt::Horizontal ? Gui::ToolBarArea::TopToolBarArea : Gui::ToolBarArea::LeftToolBarArea); + setToolBarArea( + toolBar->orientation() == Qt::Horizontal ? Gui::ToolBarArea::TopToolBarArea + : Gui::ToolBarArea::LeftToolBarArea + ); return; } } @@ -230,9 +241,7 @@ void WorkbenchTabWidget::updateLayout() setToolBarArea(toolBarArea); tabBar->setSelectionBehaviorOnRemove( - direction() == Qt::LeftToRight - ? QTabBar::SelectLeftTab - : QTabBar::SelectRightTab + direction() == Qt::LeftToRight ? QTabBar::SelectLeftTab : QTabBar::SelectRightTab ); } @@ -342,7 +351,7 @@ int WorkbenchTabWidget::addWorkbenchTab(QAction* action, int tabIndex) tabBar->insertTab(tabIndex, action->text()); } else if (itemStyle == WorkbenchItemStyle::IconOnly) { - tabBar->insertTab(tabIndex, icon, {}); // empty string to ensure only icon is displayed + tabBar->insertTab(tabIndex, icon, {}); // empty string to ensure only icon is displayed } else { tabBar->insertTab(tabIndex, icon, action->text()); @@ -363,8 +372,12 @@ void WorkbenchTabWidget::setToolBarArea(Gui::ToolBarArea area) case Gui::ToolBarArea::LeftToolBarArea: case Gui::ToolBarArea::RightToolBarArea: { setDirection(Qt::LeftToRight); - layout->setDirection(direction() == Qt::LeftToRight ? QBoxLayout::TopToBottom : QBoxLayout::BottomToTop); - tabBar->setShape(area == Gui::ToolBarArea::LeftToolBarArea ? QTabBar::RoundedWest : QTabBar::RoundedEast); + layout->setDirection( + direction() == Qt::LeftToRight ? QBoxLayout::TopToBottom : QBoxLayout::BottomToTop + ); + tabBar->setShape( + area == Gui::ToolBarArea::LeftToolBarArea ? QTabBar::RoundedWest : QTabBar::RoundedEast + ); break; } @@ -373,17 +386,17 @@ void WorkbenchTabWidget::setToolBarArea(Gui::ToolBarArea area) case Gui::ToolBarArea::LeftMenuToolBarArea: case Gui::ToolBarArea::RightMenuToolBarArea: case Gui::ToolBarArea::StatusBarToolBarArea: { - bool isTop = - area == Gui::ToolBarArea::TopToolBarArea || - area == Gui::ToolBarArea::LeftMenuToolBarArea || - area == Gui::ToolBarArea::RightMenuToolBarArea; + bool isTop = area == Gui::ToolBarArea::TopToolBarArea + || area == Gui::ToolBarArea::LeftMenuToolBarArea + || area == Gui::ToolBarArea::RightMenuToolBarArea; - bool isRightAligned = - area == Gui::ToolBarArea::RightMenuToolBarArea || - area == Gui::ToolBarArea::StatusBarToolBarArea; + bool isRightAligned = area == Gui::ToolBarArea::RightMenuToolBarArea + || area == Gui::ToolBarArea::StatusBarToolBarArea; setDirection(isRightAligned ? Qt::RightToLeft : Qt::LeftToRight); - layout->setDirection(direction() == Qt::LeftToRight ? QBoxLayout::LeftToRight : QBoxLayout::RightToLeft); + layout->setDirection( + direction() == Qt::LeftToRight ? QBoxLayout::LeftToRight : QBoxLayout::RightToLeft + ); tabBar->setShape(isTop ? QTabBar::RoundedNorth : QTabBar::RoundedSouth); break; } diff --git a/src/Gui/WorkbenchSelector.h b/src/Gui/WorkbenchSelector.h index d5955cfb45..8d586b24cc 100644 --- a/src/Gui/WorkbenchSelector.h +++ b/src/Gui/WorkbenchSelector.h @@ -38,23 +38,23 @@ namespace Gui { class WorkbenchGroup; -enum class WorkbenchItemStyle { +enum class WorkbenchItemStyle +{ IconAndText = 0, IconOnly = 1, TextOnly = 2 }; -class GuiExport WorkbenchComboBox : public QComboBox +class GuiExport WorkbenchComboBox: public QComboBox { - Q_OBJECT // NOLINT +Q_OBJECT // NOLINT -public: - explicit WorkbenchComboBox(WorkbenchGroup* aGroup, QWidget* parent = nullptr); + public: explicit WorkbenchComboBox(WorkbenchGroup* aGroup, QWidget* parent = nullptr); ~WorkbenchComboBox() override = default; - WorkbenchComboBox(WorkbenchComboBox &&rhs) = delete; + WorkbenchComboBox(WorkbenchComboBox&& rhs) = delete; void showPopup() override; - WorkbenchComboBox operator=(WorkbenchComboBox &&rhs) = delete; + WorkbenchComboBox operator=(WorkbenchComboBox&& rhs) = delete; public Q_SLOTS: void refreshList(QList); @@ -64,16 +64,20 @@ private: }; -class GuiExport WorkbenchTabWidget : public QWidget +class GuiExport WorkbenchTabWidget: public QWidget { Q_OBJECT // NOLINT Q_PROPERTY(Qt::LayoutDirection direction READ direction WRITE setDirection NOTIFY directionChanged) - class WbTabBar : public QTabBar { + class WbTabBar: public QTabBar + { public: - explicit WbTabBar(QWidget* parent) : QTabBar(parent) {} + explicit WbTabBar(QWidget* parent) + : QTabBar(parent) + {} - QSize tabSizeHint(int index) const override { + QSize tabSizeHint(int index) const override + { auto sizeFromParent = QTabBar::tabSizeHint(index); if (itemStyle() != WorkbenchItemStyle::IconOnly) { @@ -91,7 +95,8 @@ class GuiExport WorkbenchTabWidget : public QWidget if (isHorizontal) { csz.setWidth(csz.width() + padding); - } else { + } + else { csz.setHeight(csz.height() + padding); } @@ -99,7 +104,8 @@ class GuiExport WorkbenchTabWidget : public QWidget if (isHorizontal) { size.setHeight(sizeFromParent.height()); - } else { + } + else { size.setWidth(sizeFromParent.width()); } @@ -120,23 +126,31 @@ class GuiExport WorkbenchTabWidget : public QWidget } } - WorkbenchItemStyle itemStyle() const { return _itemStyle; } + WorkbenchItemStyle itemStyle() const + { + return _itemStyle; + } - void setItemStyle(WorkbenchItemStyle itemStyle) { + void setItemStyle(WorkbenchItemStyle itemStyle) + { _itemStyle = itemStyle; setProperty("style", QString::fromUtf8(workbenchItemStyleToString(itemStyle))); } private: - WorkbenchItemStyle _itemStyle{WorkbenchItemStyle::IconAndText}; + WorkbenchItemStyle _itemStyle {WorkbenchItemStyle::IconAndText}; static const char* workbenchItemStyleToString(WorkbenchItemStyle style) { switch (style) { - case WorkbenchItemStyle::IconAndText: return "icon-and-text"; - case WorkbenchItemStyle::IconOnly: return "icon-only"; - case WorkbenchItemStyle::TextOnly: return "text-only"; - default: return "WorkbenchItemStyle-internal-error"; + case WorkbenchItemStyle::IconAndText: + return "icon-and-text"; + case WorkbenchItemStyle::IconOnly: + return "icon-only"; + case WorkbenchItemStyle::TextOnly: + return "text-only"; + default: + return "WorkbenchItemStyle-internal-error"; } } }; @@ -191,7 +205,6 @@ private: }; +} // namespace Gui -} // namespace Gui - -#endif // GUI_WORKBENCHSELECTOR_H +#endif // GUI_WORKBENCHSELECTOR_H diff --git a/src/Gui/cet_lut.hpp b/src/Gui/cet_lut.hpp index 0bd93dae25..033072bc85 100644 --- a/src/Gui/cet_lut.hpp +++ b/src/Gui/cet_lut.hpp @@ -31,77 +31,2626 @@ #pragma once #ifndef _CET_LUT_HPP_ -#define _CET_LUT_HPP_ +# define _CET_LUT_HPP_ -#include +# include // 8 bit CET luts as {R,G,B,R,G,B,...} // see https://colorcet.com/gallery.html for more details -namespace CET { - // linear - static constexpr std::array L01 = {0x00,0x00,0x00,0x01,0x01,0x01,0x03,0x03,0x03,0x04,0x04,0x04,0x06,0x06,0x06,0x07,0x07,0x07,0x09,0x09,0x09,0x0a,0x0a,0x0a,0x0b,0x0b,0x0b,0x0d,0x0d,0x0d,0x0e,0x0e,0x0e,0x0f,0x0f,0x0f,0x10,0x10,0x10,0x11,0x11,0x11,0x12,0x12,0x12,0x13,0x13,0x13,0x14,0x14,0x14,0x15,0x15,0x15,0x16,0x16,0x16,0x16,0x16,0x16,0x17,0x17,0x17,0x18,0x18,0x18,0x19,0x19,0x19,0x1a,0x1a,0x1a,0x1a,0x1a,0x1a,0x1b,0x1b,0x1b,0x1c,0x1c,0x1c,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1e,0x1e,0x1e,0x1f,0x1f,0x1f,0x20,0x20,0x20,0x21,0x21,0x21,0x21,0x21,0x21,0x22,0x22,0x22,0x23,0x23,0x23,0x24,0x24,0x24,0x25,0x25,0x25,0x25,0x25,0x25,0x26,0x26,0x26,0x27,0x27,0x27,0x28,0x28,0x28,0x29,0x29,0x29,0x2a,0x2a,0x2a,0x2a,0x2a,0x2a,0x2b,0x2b,0x2b,0x2c,0x2c,0x2c,0x2d,0x2d,0x2d,0x2e,0x2e,0x2e,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x30,0x30,0x30,0x31,0x31,0x31,0x32,0x32,0x32,0x33,0x33,0x33,0x34,0x34,0x34,0x35,0x35,0x35,0x35,0x35,0x35,0x36,0x36,0x36,0x37,0x37,0x37,0x38,0x38,0x38,0x39,0x39,0x39,0x3a,0x3a,0x3a,0x3b,0x3b,0x3b,0x3b,0x3c,0x3c,0x3c,0x3c,0x3c,0x3d,0x3d,0x3d,0x3e,0x3e,0x3e,0x3f,0x3f,0x3f,0x40,0x40,0x40,0x41,0x41,0x41,0x42,0x42,0x42,0x43,0x43,0x43,0x43,0x43,0x43,0x44,0x44,0x44,0x45,0x45,0x45,0x46,0x46,0x46,0x47,0x47,0x47,0x48,0x48,0x48,0x49,0x49,0x49,0x4a,0x4a,0x4a,0x4b,0x4b,0x4b,0x4c,0x4c,0x4c,0x4d,0x4d,0x4d,0x4d,0x4d,0x4d,0x4e,0x4e,0x4e,0x4f,0x4f,0x4f,0x50,0x50,0x50,0x51,0x51,0x51,0x52,0x52,0x52,0x53,0x53,0x53,0x54,0x54,0x54,0x55,0x55,0x55,0x56,0x56,0x56,0x57,0x57,0x57,0x58,0x58,0x58,0x59,0x59,0x59,0x5a,0x5a,0x5a,0x5a,0x5a,0x5a,0x5b,0x5b,0x5b,0x5c,0x5c,0x5c,0x5d,0x5d,0x5d,0x5e,0x5e,0x5e,0x5f,0x5f,0x5f,0x60,0x60,0x60,0x61,0x61,0x61,0x62,0x62,0x62,0x63,0x63,0x63,0x64,0x64,0x64,0x65,0x65,0x65,0x66,0x66,0x66,0x67,0x67,0x67,0x68,0x68,0x68,0x69,0x69,0x69,0x6a,0x6a,0x6a,0x6b,0x6b,0x6b,0x6c,0x6c,0x6c,0x6d,0x6d,0x6d,0x6e,0x6e,0x6e,0x6f,0x6f,0x6f,0x70,0x70,0x70,0x71,0x71,0x71,0x71,0x72,0x72,0x72,0x72,0x72,0x73,0x73,0x73,0x74,0x74,0x74,0x75,0x75,0x75,0x76,0x76,0x76,0x77,0x77,0x77,0x78,0x78,0x78,0x79,0x79,0x79,0x7a,0x7a,0x7a,0x7b,0x7b,0x7b,0x7c,0x7c,0x7c,0x7d,0x7d,0x7d,0x7e,0x7e,0x7e,0x7f,0x7f,0x7f,0x80,0x80,0x80,0x81,0x81,0x81,0x82,0x82,0x82,0x83,0x83,0x83,0x84,0x84,0x84,0x85,0x85,0x85,0x86,0x86,0x86,0x87,0x87,0x87,0x88,0x88,0x88,0x89,0x89,0x89,0x8a,0x8a,0x8a,0x8b,0x8b,0x8b,0x8c,0x8c,0x8c,0x8d,0x8d,0x8d,0x8e,0x8f,0x8f,0x90,0x90,0x90,0x91,0x91,0x91,0x92,0x92,0x92,0x93,0x93,0x93,0x94,0x94,0x94,0x95,0x95,0x95,0x96,0x96,0x96,0x97,0x97,0x97,0x98,0x98,0x98,0x99,0x99,0x99,0x9a,0x9a,0x9a,0x9b,0x9b,0x9b,0x9c,0x9c,0x9c,0x9d,0x9d,0x9d,0x9e,0x9e,0x9e,0x9f,0x9f,0x9f,0xa0,0xa0,0xa0,0xa1,0xa1,0xa1,0xa2,0xa2,0xa2,0xa3,0xa3,0xa3,0xa4,0xa4,0xa4,0xa5,0xa5,0xa5,0xa6,0xa6,0xa6,0xa7,0xa7,0xa7,0xa8,0xa8,0xa8,0xa9,0xa9,0xa9,0xaa,0xab,0xab,0xac,0xac,0xac,0xad,0xad,0xad,0xae,0xae,0xae,0xaf,0xaf,0xaf,0xb0,0xb0,0xb0,0xb1,0xb1,0xb1,0xb2,0xb2,0xb2,0xb3,0xb3,0xb3,0xb4,0xb4,0xb4,0xb5,0xb5,0xb5,0xb6,0xb6,0xb6,0xb7,0xb7,0xb7,0xb8,0xb8,0xb8,0xb9,0xb9,0xb9,0xba,0xba,0xba,0xbc,0xbc,0xbc,0xbd,0xbd,0xbd,0xbe,0xbe,0xbe,0xbf,0xbf,0xbf,0xc0,0xc0,0xc0,0xc1,0xc1,0xc1,0xc2,0xc2,0xc2,0xc3,0xc3,0xc3,0xc4,0xc4,0xc4,0xc5,0xc5,0xc5,0xc6,0xc6,0xc6,0xc7,0xc7,0xc7,0xc8,0xc9,0xc9,0xca,0xca,0xca,0xcb,0xcb,0xcb,0xcc,0xcc,0xcc,0xcd,0xcd,0xcd,0xce,0xce,0xce,0xcf,0xcf,0xcf,0xd0,0xd0,0xd0,0xd1,0xd1,0xd1,0xd2,0xd2,0xd2,0xd3,0xd3,0xd3,0xd4,0xd5,0xd5,0xd6,0xd6,0xd6,0xd7,0xd7,0xd7,0xd8,0xd8,0xd8,0xd9,0xd9,0xd9,0xda,0xda,0xda,0xdb,0xdb,0xdb,0xdc,0xdc,0xdc,0xdd,0xdd,0xdd,0xde,0xde,0xde,0xe0,0xe0,0xe0,0xe1,0xe1,0xe1,0xe2,0xe2,0xe2,0xe3,0xe3,0xe3,0xe4,0xe4,0xe4,0xe5,0xe5,0xe5,0xe6,0xe6,0xe6,0xe7,0xe7,0xe7,0xe8,0xe8,0xe8,0xea,0xea,0xea,0xeb,0xeb,0xeb,0xec,0xec,0xec,0xed,0xed,0xed,0xee,0xee,0xee,0xef,0xef,0xef,0xf0,0xf0,0xf0,0xf1,0xf1,0xf1,0xf3,0xf3,0xf3,0xf4,0xf4,0xf4,0xf5,0xf5,0xf5,0xf6,0xf6,0xf6,0xf7,0xf7,0xf7,0xf8,0xf8,0xf8,0xf9,0xf9,0xf9,0xfa,0xfa,0xfa,0xfc,0xfc,0xfc,0xfd,0xfd,0xfd,0xfe,0xfe,0xfe,0xff,0xff,0xff}; - static constexpr std::array L02 = {0x1b,0x1b,0x1b,0x1c,0x1c,0x1c,0x1d,0x1d,0x1d,0x1d,0x1d,0x1d,0x1e,0x1e,0x1e,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x20,0x20,0x20,0x21,0x21,0x21,0x22,0x22,0x22,0x22,0x22,0x22,0x23,0x23,0x23,0x24,0x24,0x24,0x24,0x24,0x24,0x25,0x25,0x25,0x26,0x26,0x26,0x26,0x26,0x26,0x27,0x27,0x27,0x28,0x28,0x28,0x28,0x28,0x28,0x29,0x29,0x29,0x2a,0x2a,0x2a,0x2b,0x2b,0x2b,0x2b,0x2b,0x2b,0x2c,0x2c,0x2c,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2e,0x2e,0x2e,0x2f,0x2f,0x2f,0x30,0x30,0x30,0x30,0x30,0x30,0x31,0x31,0x31,0x32,0x32,0x32,0x32,0x32,0x32,0x33,0x33,0x33,0x34,0x34,0x34,0x35,0x35,0x35,0x35,0x35,0x35,0x36,0x36,0x36,0x37,0x37,0x37,0x38,0x38,0x38,0x38,0x38,0x38,0x39,0x39,0x39,0x3a,0x3a,0x3a,0x3b,0x3b,0x3b,0x3b,0x3b,0x3b,0x3c,0x3c,0x3c,0x3d,0x3d,0x3d,0x3e,0x3e,0x3e,0x3e,0x3e,0x3e,0x3f,0x3f,0x3f,0x40,0x40,0x40,0x41,0x41,0x41,0x41,0x41,0x41,0x42,0x42,0x42,0x43,0x43,0x43,0x44,0x44,0x44,0x44,0x44,0x44,0x45,0x45,0x45,0x46,0x46,0x46,0x47,0x47,0x47,0x47,0x47,0x47,0x48,0x48,0x48,0x49,0x49,0x49,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4b,0x4b,0x4b,0x4c,0x4c,0x4c,0x4d,0x4d,0x4d,0x4e,0x4e,0x4e,0x4e,0x4e,0x4e,0x4f,0x4f,0x4f,0x50,0x50,0x50,0x51,0x51,0x51,0x51,0x52,0x52,0x52,0x52,0x52,0x53,0x53,0x53,0x54,0x54,0x54,0x55,0x55,0x55,0x55,0x55,0x55,0x56,0x56,0x56,0x57,0x57,0x57,0x58,0x58,0x58,0x59,0x59,0x59,0x59,0x59,0x59,0x5a,0x5a,0x5a,0x5b,0x5b,0x5b,0x5c,0x5c,0x5c,0x5d,0x5d,0x5d,0x5d,0x5d,0x5d,0x5e,0x5e,0x5e,0x5f,0x5f,0x5f,0x60,0x60,0x60,0x61,0x61,0x61,0x61,0x61,0x61,0x62,0x62,0x62,0x63,0x63,0x63,0x64,0x64,0x64,0x65,0x65,0x65,0x66,0x66,0x66,0x66,0x66,0x66,0x67,0x67,0x67,0x68,0x68,0x68,0x69,0x69,0x69,0x6a,0x6a,0x6a,0x6a,0x6a,0x6a,0x6b,0x6b,0x6b,0x6c,0x6c,0x6c,0x6d,0x6d,0x6d,0x6e,0x6e,0x6e,0x6f,0x6f,0x6f,0x6f,0x6f,0x6f,0x70,0x70,0x70,0x71,0x71,0x71,0x72,0x72,0x72,0x73,0x73,0x73,0x74,0x74,0x74,0x74,0x74,0x74,0x75,0x75,0x75,0x76,0x76,0x76,0x77,0x77,0x77,0x78,0x78,0x78,0x79,0x79,0x79,0x79,0x79,0x79,0x7a,0x7a,0x7a,0x7b,0x7b,0x7b,0x7c,0x7c,0x7c,0x7d,0x7d,0x7d,0x7e,0x7e,0x7e,0x7e,0x7f,0x7f,0x7f,0x7f,0x7f,0x80,0x80,0x80,0x81,0x81,0x81,0x82,0x82,0x82,0x83,0x83,0x83,0x84,0x84,0x84,0x84,0x84,0x84,0x85,0x85,0x85,0x86,0x86,0x86,0x87,0x87,0x87,0x88,0x88,0x88,0x89,0x89,0x89,0x8a,0x8a,0x8a,0x8a,0x8a,0x8a,0x8b,0x8b,0x8b,0x8c,0x8c,0x8c,0x8d,0x8d,0x8d,0x8e,0x8e,0x8e,0x8f,0x8f,0x8f,0x90,0x90,0x90,0x91,0x91,0x91,0x91,0x91,0x91,0x92,0x92,0x92,0x93,0x93,0x93,0x94,0x94,0x94,0x95,0x95,0x95,0x96,0x96,0x96,0x97,0x97,0x97,0x98,0x98,0x98,0x98,0x98,0x98,0x99,0x99,0x99,0x9a,0x9a,0x9a,0x9b,0x9b,0x9b,0x9c,0x9c,0x9c,0x9d,0x9d,0x9d,0x9e,0x9e,0x9e,0x9f,0x9f,0x9f,0x9f,0x9f,0x9f,0xa0,0xa0,0xa0,0xa1,0xa1,0xa1,0xa2,0xa2,0xa2,0xa3,0xa3,0xa3,0xa4,0xa4,0xa4,0xa5,0xa5,0xa5,0xa6,0xa6,0xa6,0xa7,0xa7,0xa7,0xa7,0xa7,0xa7,0xa8,0xa8,0xa8,0xa9,0xa9,0xa9,0xaa,0xaa,0xaa,0xab,0xab,0xab,0xac,0xac,0xac,0xad,0xad,0xad,0xae,0xae,0xae,0xaf,0xaf,0xaf,0xb0,0xb0,0xb0,0xb0,0xb0,0xb0,0xb1,0xb1,0xb1,0xb2,0xb2,0xb2,0xb3,0xb3,0xb3,0xb4,0xb4,0xb4,0xb5,0xb5,0xb5,0xb6,0xb6,0xb6,0xb7,0xb7,0xb7,0xb8,0xb8,0xb8,0xb9,0xb9,0xb9,0xb9,0xba,0xba,0xba,0xba,0xba,0xbb,0xbb,0xbb,0xbc,0xbc,0xbc,0xbd,0xbd,0xbd,0xbe,0xbe,0xbe,0xbf,0xbf,0xbf,0xc0,0xc0,0xc0,0xc1,0xc1,0xc1,0xc2,0xc2,0xc2,0xc3,0xc3,0xc3,0xc4,0xc4,0xc4,0xc4,0xc4,0xc4,0xc5,0xc5,0xc5,0xc6,0xc6,0xc6,0xc7,0xc7,0xc7,0xc8,0xc8,0xc8,0xc9,0xc9,0xc9,0xca,0xca,0xca,0xcb,0xcb,0xcb,0xcc,0xcc,0xcc,0xcd,0xcd,0xcd,0xce,0xce,0xce,0xcf,0xcf,0xcf,0xd0,0xd0,0xd0,0xd0,0xd1,0xd1,0xd1,0xd1,0xd1,0xd2,0xd2,0xd2,0xd3,0xd3,0xd3,0xd4,0xd4,0xd4,0xd5,0xd5,0xd5,0xd6,0xd6,0xd6,0xd7,0xd7,0xd7,0xd8,0xd8,0xd8,0xd9,0xd9,0xd9,0xda,0xda,0xda,0xdb,0xdb,0xdb,0xdc,0xdc,0xdc,0xdd,0xdd,0xdd,0xde,0xde,0xde,0xdf,0xdf,0xdf,0xdf,0xe0,0xe0,0xe0,0xe0,0xe0,0xe1,0xe1,0xe1,0xe2,0xe2,0xe2,0xe3,0xe3,0xe3,0xe4,0xe4,0xe4,0xe5,0xe5,0xe5,0xe6,0xe6,0xe6,0xe7,0xe7,0xe7,0xe8,0xe8,0xe8,0xe9,0xe9,0xe9,0xea,0xea,0xea,0xeb,0xeb,0xeb,0xec,0xec,0xec,0xed,0xed,0xed,0xee,0xee,0xee,0xef,0xef,0xef,0xf0,0xf0,0xf0,0xf1,0xf1,0xf1}; - static constexpr std::array L03 = {0x00,0x00,0x00,0x07,0x00,0x00,0x0d,0x00,0x00,0x12,0x00,0x00,0x16,0x00,0x00,0x1a,0x00,0x00,0x1d,0x00,0x00,0x20,0x00,0x00,0x22,0x00,0x00,0x25,0x00,0x00,0x27,0x00,0x00,0x29,0x00,0x00,0x2b,0x00,0x00,0x2d,0x00,0x00,0x2f,0x00,0x00,0x31,0x00,0x00,0x32,0x00,0x00,0x34,0x00,0x00,0x36,0x01,0x00,0x37,0x01,0x00,0x39,0x00,0x00,0x3a,0x00,0x00,0x3c,0x00,0x00,0x3d,0x00,0x00,0x3f,0x00,0x00,0x40,0x00,0x00,0x42,0x01,0x00,0x43,0x01,0x00,0x45,0x01,0x00,0x46,0x01,0x00,0x48,0x01,0x00,0x49,0x01,0x00,0x4b,0x01,0x00,0x4c,0x01,0x00,0x4e,0x01,0x00,0x4f,0x01,0x00,0x51,0x01,0x00,0x52,0x01,0x00,0x54,0x01,0x00,0x55,0x01,0x00,0x57,0x01,0x00,0x58,0x01,0x00,0x5a,0x01,0x00,0x5c,0x01,0x00,0x5d,0x01,0x00,0x5f,0x01,0x00,0x60,0x01,0x00,0x62,0x01,0x00,0x63,0x01,0x00,0x65,0x01,0x00,0x67,0x01,0x00,0x68,0x01,0x00,0x6a,0x01,0x00,0x6b,0x02,0x00,0x6d,0x02,0x00,0x6f,0x02,0x00,0x70,0x02,0x00,0x72,0x02,0x00,0x74,0x02,0x00,0x75,0x02,0x00,0x77,0x02,0x00,0x79,0x02,0x00,0x7a,0x02,0x00,0x7c,0x02,0x00,0x7e,0x02,0x00,0x7f,0x02,0x00,0x81,0x02,0x00,0x83,0x02,0x00,0x84,0x03,0x00,0x86,0x03,0x00,0x88,0x03,0x00,0x89,0x03,0x00,0x8b,0x03,0x00,0x8d,0x03,0x00,0x8e,0x03,0x00,0x90,0x03,0x00,0x92,0x03,0x00,0x93,0x03,0x00,0x95,0x03,0x00,0x97,0x04,0x00,0x99,0x04,0x00,0x9a,0x04,0x00,0x9c,0x04,0x00,0x9e,0x04,0x00,0x9f,0x04,0x00,0xa1,0x04,0x00,0xa3,0x04,0x00,0xa5,0x05,0x00,0xa6,0x05,0x00,0xa8,0x05,0x00,0xaa,0x05,0x00,0xac,0x05,0x00,0xad,0x05,0x00,0xaf,0x05,0x00,0xb1,0x06,0x00,0xb3,0x06,0x00,0xb5,0x06,0x00,0xb6,0x06,0x00,0xb8,0x06,0x00,0xba,0x07,0x00,0xbc,0x07,0x00,0xbd,0x07,0x00,0xbf,0x07,0x00,0xc1,0x07,0x00,0xc3,0x08,0x00,0xc5,0x08,0x00,0xc6,0x08,0x00,0xc8,0x08,0x00,0xca,0x09,0x00,0xcc,0x09,0x00,0xce,0x09,0x00,0xcf,0x09,0x00,0xd1,0x0a,0x00,0xd3,0x0a,0x00,0xd5,0x0b,0x00,0xd7,0x0b,0x00,0xd8,0x0b,0x00,0xda,0x0c,0x00,0xdc,0x0c,0x00,0xde,0x0d,0x00,0xe0,0x0d,0x00,0xe1,0x0e,0x00,0xe3,0x0e,0x00,0xe5,0x0f,0x00,0xe7,0x10,0x00,0xe8,0x11,0x00,0xea,0x12,0x00,0xec,0x13,0x00,0xed,0x15,0x00,0xef,0x17,0x00,0xf0,0x19,0x00,0xf2,0x1b,0x00,0xf3,0x1e,0x00,0xf4,0x20,0x00,0xf5,0x23,0x00,0xf6,0x26,0x00,0xf7,0x29,0x00,0xf8,0x2c,0x00,0xf8,0x2f,0x00,0xf9,0x32,0x00,0xfa,0x35,0x00,0xfa,0x38,0x00,0xfb,0x3b,0x00,0xfb,0x3e,0x00,0xfc,0x41,0x00,0xfc,0x44,0x00,0xfc,0x46,0x00,0xfd,0x49,0x00,0xfd,0x4c,0x00,0xfd,0x4e,0x00,0xfd,0x51,0x00,0xfe,0x54,0x00,0xfe,0x56,0x00,0xfe,0x59,0x00,0xfe,0x5b,0x00,0xfe,0x5d,0x00,0xfe,0x60,0x00,0xfe,0x62,0x00,0xfe,0x64,0x00,0xff,0x67,0x00,0xff,0x69,0x00,0xff,0x6b,0x00,0xff,0x6d,0x00,0xff,0x6f,0x00,0xff,0x72,0x00,0xff,0x74,0x00,0xff,0x76,0x00,0xff,0x78,0x00,0xff,0x7a,0x00,0xff,0x7c,0x00,0xff,0x7e,0x00,0xff,0x80,0x00,0xff,0x82,0x00,0xff,0x84,0x00,0xff,0x86,0x00,0xff,0x88,0x00,0xff,0x8a,0x00,0xff,0x8c,0x00,0xff,0x8e,0x00,0xff,0x8f,0x00,0xff,0x91,0x00,0xff,0x93,0x00,0xff,0x95,0x00,0xff,0x97,0x00,0xff,0x99,0x00,0xff,0x9a,0x00,0xff,0x9c,0x01,0xff,0x9e,0x01,0xff,0xa0,0x01,0xff,0xa1,0x01,0xff,0xa3,0x01,0xff,0xa5,0x01,0xff,0xa7,0x01,0xff,0xa8,0x01,0xff,0xaa,0x01,0xff,0xac,0x01,0xff,0xad,0x02,0xff,0xaf,0x02,0xff,0xb1,0x02,0xff,0xb2,0x02,0xff,0xb4,0x02,0xff,0xb6,0x02,0xff,0xb7,0x03,0xff,0xb9,0x03,0xff,0xbb,0x03,0xff,0xbc,0x03,0xff,0xbe,0x03,0xff,0xc0,0x04,0xff,0xc1,0x04,0xff,0xc3,0x04,0xff,0xc4,0x04,0xff,0xc6,0x05,0xff,0xc8,0x05,0xff,0xc9,0x05,0xff,0xcb,0x05,0xff,0xcc,0x06,0xff,0xce,0x06,0xff,0xd0,0x06,0xff,0xd1,0x07,0xff,0xd3,0x07,0xff,0xd4,0x08,0xff,0xd6,0x08,0xff,0xd7,0x09,0xff,0xd9,0x09,0xff,0xdb,0x0a,0xff,0xdc,0x0a,0xff,0xde,0x0b,0xff,0xdf,0x0b,0xff,0xe1,0x0c,0xff,0xe2,0x0d,0xff,0xe4,0x0d,0xff,0xe5,0x0e,0xff,0xe7,0x0f,0xff,0xe9,0x10,0xff,0xea,0x11,0xff,0xec,0x13,0xff,0xed,0x15,0xff,0xef,0x17,0xff,0xf0,0x1a,0xff,0xf2,0x1f,0xff,0xf3,0x24,0xff,0xf5,0x2b,0xff,0xf6,0x33,0xff,0xf7,0x3c,0xff,0xf9,0x47,0xff,0xfa,0x54,0xff,0xfb,0x62,0xff,0xfc,0x72,0xff,0xfd,0x84,0xff,0xfe,0x96,0xff,0xfe,0xa8,0xff,0xfe,0xbb,0xff,0xff,0xcd,0xff,0xff,0xde,0xff,0xff,0xef,0xff,0xff,0xff}; - static constexpr std::array L04 = {0x00,0x00,0x00,0x07,0x00,0x00,0x0d,0x00,0x00,0x12,0x00,0x00,0x16,0x00,0x00,0x19,0x00,0x00,0x1c,0x00,0x00,0x1f,0x00,0x00,0x22,0x00,0x00,0x24,0x00,0x00,0x26,0x00,0x00,0x28,0x00,0x00,0x2a,0x00,0x00,0x2c,0x00,0x00,0x2e,0x00,0x00,0x30,0x00,0x00,0x32,0x00,0x00,0x33,0x00,0x00,0x35,0x00,0x00,0x36,0x00,0x00,0x38,0x00,0x00,0x39,0x00,0x00,0x3b,0x00,0x00,0x3c,0x00,0x00,0x3e,0x00,0x00,0x3f,0x00,0x00,0x40,0x00,0x00,0x42,0x01,0x00,0x43,0x01,0x00,0x45,0x01,0x00,0x46,0x01,0x00,0x48,0x01,0x00,0x49,0x01,0x00,0x4b,0x01,0x00,0x4c,0x01,0x00,0x4e,0x01,0x00,0x4f,0x01,0x00,0x51,0x01,0x00,0x52,0x01,0x00,0x54,0x01,0x00,0x55,0x01,0x00,0x57,0x01,0x00,0x58,0x01,0x00,0x5a,0x01,0x00,0x5b,0x01,0x00,0x5d,0x01,0x00,0x5e,0x01,0x00,0x60,0x01,0x00,0x61,0x01,0x00,0x63,0x01,0x00,0x64,0x01,0x00,0x66,0x01,0x00,0x67,0x01,0x00,0x69,0x01,0x00,0x6b,0x02,0x00,0x6c,0x02,0x00,0x6e,0x02,0x00,0x6f,0x02,0x00,0x71,0x02,0x00,0x72,0x02,0x00,0x74,0x02,0x00,0x76,0x02,0x00,0x77,0x02,0x00,0x79,0x02,0x00,0x7a,0x02,0x00,0x7c,0x02,0x00,0x7e,0x02,0x00,0x7f,0x02,0x00,0x81,0x02,0x00,0x83,0x02,0x00,0x84,0x03,0x00,0x86,0x03,0x00,0x87,0x03,0x00,0x89,0x03,0x00,0x8b,0x03,0x00,0x8c,0x03,0x00,0x8e,0x03,0x00,0x90,0x03,0x00,0x91,0x03,0x00,0x93,0x03,0x00,0x95,0x03,0x00,0x96,0x04,0x00,0x98,0x04,0x00,0x9a,0x04,0x00,0x9b,0x04,0x00,0x9d,0x04,0x00,0x9f,0x04,0x00,0xa0,0x04,0x00,0xa2,0x04,0x00,0xa4,0x04,0x00,0xa5,0x05,0x00,0xa7,0x05,0x00,0xa9,0x05,0x00,0xab,0x05,0x00,0xac,0x05,0x00,0xae,0x05,0x00,0xb0,0x06,0x00,0xb1,0x06,0x00,0xb3,0x06,0x00,0xb5,0x06,0x00,0xb7,0x06,0x00,0xb8,0x06,0x00,0xba,0x07,0x00,0xbc,0x07,0x00,0xbd,0x07,0x00,0xbf,0x07,0x00,0xc1,0x07,0x00,0xc3,0x08,0x00,0xc4,0x08,0x00,0xc6,0x08,0x00,0xc8,0x08,0x00,0xca,0x09,0x00,0xcb,0x09,0x00,0xcd,0x09,0x00,0xcf,0x09,0x00,0xd1,0x0a,0x00,0xd2,0x0a,0x00,0xd4,0x0a,0x00,0xd6,0x0b,0x00,0xd8,0x0b,0x00,0xd9,0x0c,0x00,0xdb,0x0c,0x00,0xdd,0x0c,0x00,0xdf,0x0d,0x00,0xe0,0x0d,0x00,0xe2,0x0e,0x00,0xe4,0x0f,0x00,0xe6,0x0f,0x00,0xe7,0x10,0x00,0xe9,0x11,0x00,0xeb,0x12,0x00,0xec,0x13,0x00,0xee,0x15,0x00,0xef,0x18,0x00,0xf0,0x1a,0x00,0xf1,0x1d,0x00,0xf2,0x21,0x00,0xf3,0x24,0x00,0xf4,0x27,0x00,0xf4,0x2a,0x00,0xf5,0x2e,0x00,0xf6,0x31,0x00,0xf6,0x34,0x00,0xf7,0x37,0x00,0xf7,0x3a,0x00,0xf7,0x3d,0x00,0xf8,0x3f,0x00,0xf8,0x42,0x00,0xf8,0x45,0x00,0xf9,0x48,0x00,0xf9,0x4a,0x00,0xf9,0x4d,0x00,0xf9,0x4f,0x00,0xfa,0x52,0x00,0xfa,0x54,0x00,0xfa,0x56,0x00,0xfa,0x59,0x00,0xfa,0x5b,0x00,0xfb,0x5d,0x00,0xfb,0x60,0x00,0xfb,0x62,0x00,0xfb,0x64,0x00,0xfb,0x66,0x00,0xfb,0x68,0x00,0xfc,0x6a,0x00,0xfc,0x6c,0x00,0xfc,0x6e,0x00,0xfc,0x70,0x00,0xfc,0x72,0x00,0xfc,0x74,0x00,0xfc,0x76,0x00,0xfc,0x78,0x00,0xfc,0x7a,0x00,0xfc,0x7c,0x00,0xfd,0x7e,0x00,0xfd,0x80,0x00,0xfd,0x82,0x00,0xfd,0x83,0x00,0xfd,0x85,0x00,0xfd,0x87,0x00,0xfd,0x89,0x00,0xfd,0x8b,0x00,0xfd,0x8c,0x00,0xfd,0x8e,0x00,0xfd,0x90,0x00,0xfd,0x92,0x00,0xfd,0x93,0x00,0xfe,0x95,0x00,0xfe,0x97,0x00,0xfe,0x99,0x00,0xfe,0x9a,0x00,0xfe,0x9c,0x00,0xfe,0x9e,0x00,0xfe,0x9f,0x00,0xfe,0xa1,0x00,0xfe,0xa3,0x00,0xfe,0xa4,0x00,0xfe,0xa6,0x00,0xfe,0xa8,0x00,0xfe,0xa9,0x00,0xfe,0xab,0x00,0xfe,0xad,0x00,0xfe,0xae,0x00,0xfe,0xb0,0x00,0xfe,0xb1,0x00,0xfe,0xb3,0x00,0xfe,0xb5,0x00,0xfe,0xb6,0x00,0xfe,0xb8,0x00,0xfe,0xb9,0x00,0xfe,0xbb,0x00,0xfe,0xbd,0x00,0xff,0xbe,0x00,0xff,0xc0,0x00,0xff,0xc1,0x00,0xff,0xc3,0x00,0xff,0xc4,0x00,0xff,0xc6,0x00,0xff,0xc7,0x00,0xff,0xc9,0x00,0xff,0xcb,0x00,0xff,0xcc,0x00,0xff,0xce,0x00,0xff,0xcf,0x00,0xff,0xd1,0x00,0xff,0xd2,0x00,0xff,0xd4,0x00,0xff,0xd5,0x00,0xff,0xd7,0x00,0xff,0xd8,0x00,0xff,0xda,0x00,0xff,0xdb,0x00,0xff,0xdd,0x00,0xff,0xde,0x00,0xff,0xe0,0x00,0xff,0xe1,0x00,0xff,0xe3,0x00,0xff,0xe4,0x00,0xff,0xe6,0x00,0xff,0xe7,0x00,0xff,0xe9,0x00,0xff,0xea,0x00,0xff,0xec,0x00,0xff,0xed,0x00,0xff,0xef,0x00,0xff,0xf0,0x00,0xff,0xf2,0x00,0xff,0xf3,0x00,0xff,0xf5,0x00,0xff,0xf6,0x00,0xff,0xf8,0x00,0xff,0xf9,0x00,0xff,0xfb,0x00,0xff,0xfc,0x00,0xff,0xfe,0x00,0xff,0xff,0x00}; - static constexpr std::array L05 = {0x01,0x15,0x06,0x01,0x16,0x06,0x02,0x17,0x06,0x02,0x18,0x06,0x03,0x19,0x06,0x04,0x19,0x06,0x04,0x1a,0x06,0x05,0x1b,0x06,0x05,0x1c,0x06,0x06,0x1c,0x06,0x07,0x1d,0x06,0x07,0x1e,0x06,0x08,0x1f,0x06,0x08,0x20,0x06,0x08,0x20,0x06,0x09,0x21,0x06,0x09,0x22,0x06,0x09,0x23,0x05,0x09,0x24,0x05,0x09,0x24,0x05,0x09,0x25,0x05,0x09,0x26,0x05,0x09,0x27,0x05,0x09,0x28,0x05,0x09,0x29,0x05,0x09,0x2a,0x05,0x09,0x2a,0x05,0x09,0x2b,0x05,0x09,0x2c,0x05,0x09,0x2d,0x05,0x09,0x2e,0x05,0x09,0x2f,0x05,0x09,0x30,0x05,0x08,0x31,0x05,0x08,0x31,0x05,0x08,0x32,0x05,0x08,0x33,0x05,0x08,0x34,0x05,0x09,0x35,0x05,0x09,0x36,0x05,0x09,0x37,0x05,0x09,0x38,0x05,0x09,0x38,0x05,0x09,0x39,0x05,0x0a,0x3a,0x05,0x0a,0x3b,0x05,0x0a,0x3c,0x05,0x0a,0x3d,0x05,0x0b,0x3e,0x05,0x0b,0x3f,0x05,0x0b,0x40,0x05,0x0b,0x40,0x05,0x0c,0x41,0x05,0x0c,0x42,0x05,0x0c,0x43,0x05,0x0d,0x44,0x05,0x0d,0x45,0x05,0x0d,0x46,0x05,0x0d,0x47,0x05,0x0e,0x48,0x05,0x0e,0x49,0x05,0x0e,0x49,0x05,0x0e,0x4a,0x05,0x0f,0x4b,0x05,0x0f,0x4c,0x05,0x0f,0x4d,0x05,0x0f,0x4e,0x05,0x10,0x4f,0x05,0x10,0x50,0x05,0x10,0x51,0x05,0x10,0x52,0x05,0x11,0x53,0x05,0x11,0x54,0x06,0x11,0x55,0x06,0x11,0x55,0x06,0x12,0x56,0x06,0x12,0x57,0x06,0x12,0x58,0x06,0x12,0x59,0x06,0x13,0x5a,0x06,0x13,0x5b,0x06,0x13,0x5c,0x06,0x13,0x5d,0x06,0x14,0x5e,0x06,0x14,0x5f,0x07,0x14,0x60,0x07,0x14,0x61,0x07,0x15,0x62,0x07,0x15,0x63,0x07,0x15,0x64,0x07,0x15,0x65,0x07,0x16,0x66,0x07,0x16,0x67,0x07,0x16,0x68,0x07,0x16,0x68,0x08,0x17,0x69,0x08,0x17,0x6a,0x08,0x17,0x6b,0x08,0x17,0x6c,0x08,0x18,0x6d,0x08,0x18,0x6e,0x08,0x18,0x6f,0x08,0x18,0x70,0x08,0x19,0x71,0x08,0x19,0x72,0x09,0x19,0x73,0x09,0x19,0x74,0x09,0x1a,0x75,0x09,0x1a,0x76,0x09,0x1a,0x77,0x09,0x1a,0x78,0x09,0x1b,0x79,0x09,0x1b,0x7a,0x09,0x1b,0x7b,0x0a,0x1b,0x7c,0x0a,0x1c,0x7d,0x0a,0x1c,0x7e,0x0a,0x1c,0x7f,0x0a,0x1c,0x80,0x0a,0x1d,0x81,0x0a,0x1d,0x82,0x0a,0x1d,0x83,0x0b,0x1e,0x84,0x0b,0x1e,0x85,0x0b,0x1e,0x86,0x0b,0x1e,0x87,0x0b,0x1f,0x88,0x0b,0x1f,0x89,0x0b,0x1f,0x8a,0x0b,0x1f,0x8b,0x0b,0x20,0x8c,0x0c,0x20,0x8d,0x0c,0x20,0x8e,0x0c,0x20,0x8f,0x0c,0x21,0x90,0x0c,0x21,0x91,0x0c,0x21,0x92,0x0c,0x21,0x93,0x0c,0x22,0x95,0x0d,0x22,0x96,0x0d,0x22,0x97,0x0d,0x22,0x98,0x0d,0x23,0x99,0x0d,0x23,0x9a,0x0d,0x23,0x9b,0x0d,0x23,0x9c,0x0d,0x24,0x9d,0x0d,0x24,0x9e,0x0e,0x24,0x9f,0x0e,0x25,0xa0,0x0e,0x25,0xa1,0x0e,0x25,0xa2,0x0e,0x25,0xa3,0x0e,0x26,0xa4,0x0e,0x26,0xa5,0x0e,0x26,0xa6,0x0e,0x26,0xa7,0x0f,0x27,0xa8,0x0f,0x27,0xa9,0x0f,0x27,0xaa,0x0f,0x27,0xac,0x0f,0x28,0xad,0x0f,0x28,0xae,0x0f,0x28,0xaf,0x0f,0x28,0xb0,0x10,0x29,0xb1,0x10,0x29,0xb2,0x10,0x29,0xb3,0x10,0x2a,0xb4,0x10,0x2a,0xb5,0x10,0x2a,0xb6,0x10,0x2a,0xb7,0x10,0x2b,0xb8,0x10,0x2b,0xb9,0x11,0x2b,0xba,0x11,0x2b,0xbc,0x11,0x2c,0xbd,0x11,0x2c,0xbe,0x11,0x2c,0xbf,0x11,0x2c,0xc0,0x11,0x2d,0xc1,0x11,0x2d,0xc2,0x11,0x2d,0xc3,0x12,0x2e,0xc4,0x12,0x2e,0xc5,0x12,0x2e,0xc6,0x12,0x2e,0xc7,0x12,0x2f,0xc9,0x12,0x2f,0xca,0x12,0x2f,0xcb,0x12,0x2f,0xcc,0x13,0x30,0xcd,0x13,0x30,0xce,0x13,0x30,0xcf,0x13,0x31,0xd0,0x13,0x31,0xd1,0x13,0x31,0xd2,0x13,0x31,0xd3,0x13,0x32,0xd5,0x13,0x32,0xd6,0x14,0x32,0xd7,0x14,0x32,0xd8,0x14,0x33,0xd9,0x14,0x33,0xda,0x14,0x33,0xdb,0x14,0x34,0xdc,0x14,0x34,0xdd,0x14,0x34,0xdf,0x14,0x34,0xe0,0x15,0x35,0xe1,0x15,0x35,0xe2,0x15,0x35,0xe3,0x15,0x35,0xe4,0x15,0x36,0xe5,0x15,0x37,0xe6,0x15,0x39,0xe7,0x15,0x3b,0xe8,0x15,0x3e,0xe9,0x15,0x41,0xea,0x16,0x44,0xeb,0x16,0x48,0xec,0x16,0x4b,0xed,0x16,0x4f,0xee,0x16,0x53,0xef,0x16,0x57,0xf0,0x16,0x5c,0xf0,0x16,0x60,0xf1,0x16,0x64,0xf2,0x16,0x68,0xf3,0x16,0x6c,0xf3,0x16,0x71,0xf4,0x15,0x75,0xf5,0x15,0x79,0xf6,0x15,0x7d,0xf6,0x15,0x81,0xf7,0x15,0x86,0xf8,0x15,0x8a,0xf8,0x15,0x8e,0xf9,0x15,0x92,0xf9,0x15,0x96,0xfa,0x15,0x9a,0xfb,0x15,0x9f,0xfb,0x15,0xa3,0xfc,0x15,0xa7,0xfc,0x15,0xab,0xfd,0x15,0xaf,0xfd,0x15,0xb3,0xfe,0x15,0xb7,0xfe,0x15,0xbb,0xff,0x15,0xc0,0xff,0x15,0xc4,0xff,0x15,0xc8,0xff,0x15,0xcc,0xff,0x15,0xd0,0xff,0x15,0xd4,0xff,0x15,0xd8,0xff,0x15}; - static constexpr std::array L06 = {0x00,0x01,0x4e,0x00,0x01,0x50,0x00,0x02,0x52,0x00,0x02,0x54,0x00,0x02,0x56,0x00,0x03,0x58,0x00,0x03,0x5a,0x00,0x03,0x5c,0x00,0x03,0x5e,0x00,0x03,0x60,0x01,0x03,0x62,0x02,0x03,0x64,0x02,0x03,0x66,0x03,0x03,0x68,0x04,0x02,0x6a,0x05,0x02,0x6c,0x05,0x02,0x6e,0x06,0x02,0x70,0x07,0x02,0x72,0x08,0x02,0x74,0x08,0x02,0x76,0x09,0x02,0x78,0x0a,0x02,0x7b,0x0b,0x02,0x7d,0x0b,0x02,0x7f,0x0c,0x02,0x81,0x0d,0x02,0x83,0x0d,0x02,0x85,0x0e,0x02,0x88,0x0e,0x01,0x8a,0x0f,0x01,0x8c,0x0f,0x01,0x8e,0x0f,0x01,0x90,0x10,0x01,0x93,0x10,0x01,0x95,0x10,0x01,0x97,0x10,0x01,0x99,0x10,0x02,0x9c,0x10,0x02,0x9e,0x10,0x02,0xa0,0x10,0x02,0xa2,0x0f,0x02,0xa5,0x0f,0x02,0xa7,0x0e,0x03,0xaa,0x0d,0x03,0xac,0x0d,0x03,0xae,0x0c,0x04,0xb1,0x0b,0x04,0xb3,0x0a,0x04,0xb5,0x0a,0x05,0xb7,0x09,0x05,0xb9,0x09,0x06,0xbc,0x08,0x07,0xbe,0x08,0x07,0xc0,0x08,0x08,0xc2,0x08,0x09,0xc4,0x08,0x0a,0xc6,0x08,0x0a,0xc8,0x08,0x0b,0xca,0x08,0x0c,0xcc,0x09,0x0d,0xce,0x09,0x0e,0xd0,0x0a,0x0f,0xd2,0x0b,0x10,0xd4,0x0c,0x11,0xd6,0x0d,0x12,0xd8,0x0e,0x12,0xd9,0x10,0x13,0xdb,0x11,0x14,0xdd,0x12,0x15,0xdf,0x13,0x16,0xe0,0x15,0x17,0xe2,0x16,0x18,0xe3,0x18,0x19,0xe5,0x19,0x1a,0xe7,0x1a,0x1c,0xe8,0x1b,0x1d,0xe9,0x1c,0x1e,0xeb,0x1d,0x1f,0xec,0x1f,0x21,0xed,0x20,0x22,0xee,0x21,0x24,0xf0,0x22,0x25,0xf1,0x23,0x26,0xf2,0x23,0x28,0xf3,0x24,0x29,0xf4,0x25,0x2b,0xf4,0x26,0x2d,0xf5,0x27,0x2e,0xf6,0x28,0x30,0xf7,0x28,0x31,0xf7,0x29,0x33,0xf8,0x2a,0x35,0xf8,0x2a,0x36,0xf9,0x2b,0x38,0xf9,0x2b,0x3a,0xfa,0x2c,0x3b,0xfa,0x2c,0x3d,0xfa,0x2d,0x3f,0xfa,0x2d,0x41,0xfb,0x2d,0x42,0xfb,0x2e,0x44,0xfb,0x2e,0x46,0xfb,0x2e,0x47,0xfb,0x2f,0x49,0xfb,0x2f,0x4b,0xfb,0x2f,0x4c,0xfb,0x2f,0x4e,0xfb,0x2f,0x4f,0xfb,0x2f,0x51,0xfb,0x2f,0x52,0xfc,0x30,0x54,0xfc,0x30,0x56,0xfc,0x30,0x57,0xfc,0x30,0x59,0xfc,0x30,0x5a,0xfc,0x30,0x5c,0xfc,0x30,0x5d,0xfc,0x2f,0x5e,0xfc,0x2f,0x60,0xfc,0x2f,0x61,0xfc,0x2f,0x63,0xfd,0x2f,0x64,0xfd,0x2f,0x66,0xfd,0x2e,0x67,0xfd,0x2e,0x69,0xfd,0x2e,0x6a,0xfd,0x2e,0x6b,0xfd,0x2d,0x6d,0xfd,0x2d,0x6e,0xfd,0x2d,0x70,0xfd,0x2c,0x71,0xfd,0x2c,0x72,0xfd,0x2c,0x74,0xfd,0x2c,0x75,0xfe,0x2c,0x76,0xfe,0x2b,0x78,0xfe,0x2b,0x79,0xfe,0x2b,0x7b,0xfe,0x2b,0x7c,0xfe,0x2b,0x7d,0xfe,0x2c,0x7e,0xfe,0x2c,0x80,0xfe,0x2c,0x81,0xfe,0x2c,0x82,0xfe,0x2c,0x84,0xfe,0x2d,0x85,0xfe,0x2d,0x86,0xfe,0x2d,0x87,0xfe,0x2e,0x89,0xfe,0x2e,0x8a,0xfe,0x2f,0x8b,0xfe,0x2f,0x8d,0xfe,0x30,0x8e,0xfe,0x30,0x8f,0xfe,0x31,0x90,0xfd,0x32,0x92,0xfd,0x32,0x93,0xfd,0x33,0x94,0xfd,0x33,0x95,0xfd,0x34,0x96,0xfd,0x34,0x98,0xfd,0x35,0x99,0xfd,0x35,0x9a,0xfd,0x35,0x9b,0xfd,0x35,0x9d,0xfd,0x36,0x9e,0xfd,0x36,0x9f,0xfd,0x36,0xa0,0xfd,0x36,0xa2,0xfd,0x36,0xa3,0xfd,0x36,0xa4,0xfd,0x36,0xa6,0xfd,0x36,0xa7,0xfd,0x35,0xa8,0xfd,0x35,0xa9,0xfc,0x35,0xab,0xfc,0x35,0xac,0xfc,0x34,0xad,0xfc,0x34,0xae,0xfc,0x33,0xb0,0xfc,0x33,0xb1,0xfc,0x32,0xb2,0xfc,0x31,0xb4,0xfc,0x31,0xb5,0xfc,0x30,0xb6,0xfc,0x2f,0xb7,0xfc,0x2e,0xb9,0xfc,0x2e,0xba,0xfc,0x2d,0xbb,0xfc,0x2c,0xbc,0xfc,0x2c,0xbe,0xfc,0x2b,0xbf,0xfc,0x2b,0xc0,0xfc,0x2a,0xc2,0xfc,0x2a,0xc3,0xfc,0x2a,0xc4,0xfc,0x29,0xc5,0xfc,0x29,0xc7,0xfc,0x29,0xc8,0xfc,0x29,0xc9,0xfb,0x29,0xca,0xfb,0x29,0xcb,0xfb,0x29,0xcd,0xfb,0x29,0xce,0xfb,0x29,0xcf,0xfb,0x29,0xd0,0xfb,0x2a,0xd2,0xfb,0x2a,0xd3,0xfb,0x2b,0xd4,0xfb,0x2b,0xd5,0xfb,0x2c,0xd6,0xfb,0x2c,0xd8,0xfa,0x2d,0xd9,0xfa,0x2f,0xda,0xfa,0x30,0xdb,0xfa,0x33,0xdc,0xfa,0x35,0xdd,0xfa,0x38,0xde,0xfa,0x3c,0xdf,0xfa,0x3f,0xe1,0xfa,0x42,0xe2,0xf9,0x46,0xe3,0xf9,0x49,0xe4,0xf9,0x4d,0xe5,0xf9,0x50,0xe5,0xf9,0x54,0xe6,0xf9,0x57,0xe7,0xf9,0x5b,0xe8,0xf9,0x5e,0xe9,0xf9,0x62,0xea,0xf8,0x65,0xeb,0xf8,0x69,0xec,0xf8,0x6c,0xed,0xf8,0x70,0xee,0xf8,0x73,0xef,0xf8,0x76,0xf0,0xf8,0x7a,0xf0,0xf8,0x7d,0xf1,0xf8,0x80,0xf2,0xf7,0x84,0xf3,0xf7,0x87,0xf4,0xf7,0x8a,0xf5,0xf7,0x8e,0xf5,0xf7,0x91,0xf6,0xf7,0x94,0xf7,0xf7,0x97,0xf8,0xf7,0x9a,0xf9,0xf6,0x9d,0xf9,0xf6,0xa1,0xfa,0xf6,0xa4,0xfb,0xf6,0xa7,0xfc,0xf6,0xaa,0xfd,0xf6,0xad,0xfd,0xf6,0xb0,0xfe,0xf6,0xb3,0xff,0xf6}; - static constexpr std::array L07 = {0x00,0x02,0x4b,0x00,0x03,0x4d,0x00,0x03,0x4f,0x00,0x04,0x51,0x00,0x04,0x53,0x00,0x04,0x55,0x00,0x05,0x58,0x00,0x05,0x5a,0x00,0x05,0x5c,0x00,0x05,0x5e,0x00,0x05,0x60,0x00,0x05,0x62,0x00,0x05,0x64,0x00,0x05,0x66,0x00,0x05,0x68,0x01,0x05,0x6a,0x01,0x05,0x6d,0x01,0x05,0x6f,0x01,0x05,0x71,0x02,0x05,0x73,0x02,0x05,0x75,0x02,0x05,0x77,0x03,0x05,0x79,0x03,0x05,0x7c,0x03,0x05,0x7e,0x04,0x05,0x80,0x04,0x05,0x82,0x04,0x05,0x84,0x04,0x06,0x87,0x05,0x06,0x89,0x05,0x06,0x8b,0x05,0x06,0x8d,0x05,0x06,0x90,0x06,0x06,0x92,0x06,0x06,0x94,0x06,0x06,0x96,0x06,0x06,0x99,0x06,0x06,0x9b,0x06,0x06,0x9d,0x06,0x06,0x9f,0x06,0x06,0xa2,0x06,0x07,0xa4,0x05,0x07,0xa6,0x05,0x07,0xa9,0x05,0x07,0xab,0x05,0x07,0xad,0x05,0x08,0xaf,0x05,0x08,0xb2,0x05,0x08,0xb4,0x05,0x08,0xb6,0x05,0x09,0xb8,0x06,0x09,0xba,0x06,0x0a,0xbd,0x07,0x0a,0xbf,0x08,0x0a,0xc1,0x09,0x0b,0xc3,0x0b,0x0b,0xc5,0x0c,0x0c,0xc7,0x0d,0x0c,0xc9,0x0f,0x0d,0xcb,0x10,0x0d,0xcd,0x12,0x0e,0xcf,0x13,0x0e,0xd1,0x15,0x0f,0xd3,0x16,0x0f,0xd5,0x18,0x10,0xd6,0x19,0x11,0xd8,0x1b,0x11,0xda,0x1d,0x12,0xdc,0x1e,0x12,0xde,0x20,0x13,0xdf,0x22,0x14,0xe1,0x24,0x14,0xe3,0x26,0x15,0xe4,0x28,0x15,0xe6,0x2a,0x16,0xe7,0x2c,0x16,0xe9,0x2f,0x17,0xea,0x31,0x17,0xec,0x34,0x18,0xed,0x37,0x18,0xee,0x39,0x19,0xef,0x3c,0x19,0xf0,0x3f,0x19,0xf2,0x42,0x1a,0xf3,0x45,0x1a,0xf4,0x48,0x1a,0xf5,0x4b,0x1b,0xf5,0x4d,0x1b,0xf6,0x50,0x1b,0xf7,0x53,0x1b,0xf8,0x56,0x1b,0xf8,0x59,0x1c,0xf9,0x5d,0x1c,0xfa,0x60,0x1c,0xfa,0x63,0x1c,0xfa,0x66,0x1c,0xfb,0x69,0x1c,0xfb,0x6c,0x1c,0xfb,0x6f,0x1c,0xfc,0x72,0x1c,0xfc,0x75,0x1c,0xfc,0x78,0x1c,0xfc,0x7b,0x1c,0xfc,0x7e,0x1c,0xfc,0x80,0x1c,0xfd,0x83,0x1c,0xfd,0x86,0x1c,0xfd,0x89,0x1c,0xfd,0x8b,0x1c,0xfd,0x8e,0x1c,0xfd,0x91,0x1c,0xfd,0x93,0x1d,0xfd,0x96,0x1d,0xfe,0x99,0x1d,0xfe,0x9b,0x1d,0xfe,0x9e,0x1d,0xfe,0xa0,0x1d,0xfe,0xa3,0x1d,0xfe,0xa5,0x1d,0xfe,0xa8,0x1d,0xfe,0xaa,0x1d,0xfe,0xad,0x1d,0xfe,0xaf,0x1d,0xfe,0xb1,0x1d,0xfe,0xb4,0x1d,0xfe,0xb6,0x1c,0xfe,0xb9,0x1c,0xfe,0xbb,0x1c,0xfe,0xbd,0x1d,0xfe,0xc0,0x1d,0xfe,0xc2,0x1d,0xfe,0xc4,0x1d,0xfe,0xc6,0x1e,0xfe,0xc8,0x1e,0xfe,0xca,0x1f,0xfe,0xcc,0x20,0xfe,0xce,0x21,0xfe,0xd0,0x22,0xfe,0xd2,0x23,0xfe,0xd4,0x24,0xfe,0xd6,0x25,0xfe,0xd7,0x26,0xfe,0xd9,0x27,0xfe,0xdb,0x29,0xfe,0xdc,0x2a,0xfe,0xde,0x2c,0xfe,0xe0,0x2d,0xfe,0xe1,0x2e,0xfe,0xe3,0x30,0xfe,0xe4,0x32,0xfe,0xe5,0x33,0xfe,0xe7,0x35,0xfe,0xe8,0x37,0xfe,0xe9,0x38,0xfe,0xeb,0x3a,0xfe,0xec,0x3c,0xfe,0xed,0x3e,0xfe,0xee,0x3f,0xfe,0xef,0x41,0xfe,0xf0,0x43,0xfe,0xf1,0x45,0xfe,0xf2,0x47,0xfe,0xf3,0x49,0xfe,0xf4,0x4b,0xfe,0xf5,0x4d,0xfe,0xf6,0x4f,0xfe,0xf7,0x51,0xfe,0xf8,0x53,0xfe,0xf8,0x55,0xfe,0xf9,0x57,0xfe,0xfa,0x59,0xfe,0xfa,0x5b,0xfe,0xfb,0x5d,0xfe,0xfb,0x5f,0xfe,0xfc,0x61,0xfe,0xfc,0x63,0xfe,0xfc,0x65,0xfe,0xfd,0x67,0xfe,0xfd,0x6a,0xfe,0xfd,0x6c,0xfd,0xfd,0x6e,0xfd,0xfe,0x70,0xfd,0xfe,0x72,0xfd,0xfe,0x74,0xfd,0xfe,0x76,0xfd,0xfe,0x78,0xfd,0xfe,0x7b,0xfd,0xfe,0x7d,0xfd,0xfe,0x7f,0xfd,0xfe,0x81,0xfd,0xfe,0x83,0xfd,0xfe,0x85,0xfd,0xfe,0x87,0xfd,0xfe,0x88,0xfd,0xfe,0x8a,0xfd,0xfe,0x8c,0xfd,0xfe,0x8e,0xfd,0xfe,0x90,0xfd,0xfe,0x92,0xfd,0xfe,0x94,0xfd,0xfe,0x95,0xfd,0xfe,0x97,0xfd,0xfe,0x99,0xfd,0xfe,0x9b,0xfd,0xfe,0x9c,0xfd,0xfe,0x9e,0xfd,0xfe,0xa0,0xfd,0xfe,0xa2,0xfd,0xfe,0xa3,0xfd,0xfe,0xa5,0xfd,0xfe,0xa7,0xfd,0xfe,0xa8,0xfd,0xfe,0xaa,0xfd,0xfe,0xac,0xfd,0xfe,0xad,0xfd,0xfe,0xaf,0xfd,0xfe,0xb1,0xfe,0xfe,0xb2,0xfe,0xfe,0xb4,0xfe,0xfe,0xb5,0xfe,0xfe,0xb7,0xfe,0xfe,0xb9,0xfe,0xfe,0xba,0xfe,0xfe,0xbc,0xfe,0xfe,0xbd,0xfe,0xfe,0xbf,0xfe,0xfe,0xc1,0xfe,0xfe,0xc2,0xfe,0xff,0xc4,0xfe,0xff,0xc5,0xfe,0xff,0xc7,0xfe,0xff,0xc8,0xfe,0xff,0xca,0xfe,0xff,0xcb,0xfe,0xff,0xcd,0xfe,0xff,0xce,0xfe,0xff,0xd0,0xfe,0xff,0xd1,0xfe,0xff,0xd3,0xfe,0xff,0xd4,0xfe,0xff,0xd6,0xfe,0xff,0xd7,0xfe,0xff,0xd9,0xfe,0xff,0xda,0xfe,0xff,0xdc,0xfe,0xff,0xdd,0xfe,0xff,0xdf,0xfe,0xff,0xe0,0xfe,0xff,0xe2,0xfe,0xff,0xe3,0xfe,0xff,0xe5,0xfe,0xfe,0xe6,0xfe,0xfe,0xe8,0xfe,0xfe,0xe9,0xfe,0xfe,0xeb,0xfe}; - static constexpr std::array L08 = {0x00,0x0f,0x5d,0x01,0x0f,0x5e,0x01,0x10,0x60,0x01,0x10,0x62,0x01,0x11,0x63,0x02,0x11,0x65,0x02,0x12,0x67,0x03,0x12,0x68,0x04,0x12,0x6a,0x05,0x13,0x6b,0x06,0x13,0x6d,0x07,0x14,0x6f,0x08,0x14,0x70,0x0a,0x15,0x72,0x0c,0x15,0x73,0x0d,0x15,0x75,0x0f,0x16,0x76,0x11,0x16,0x77,0x12,0x16,0x79,0x14,0x17,0x7a,0x16,0x17,0x7c,0x18,0x17,0x7d,0x19,0x18,0x7e,0x1b,0x18,0x80,0x1d,0x18,0x81,0x1f,0x19,0x82,0x21,0x19,0x83,0x23,0x19,0x85,0x25,0x19,0x86,0x27,0x1a,0x87,0x29,0x1a,0x88,0x2b,0x1a,0x89,0x2e,0x1a,0x8a,0x30,0x1a,0x8b,0x32,0x1b,0x8c,0x34,0x1b,0x8d,0x37,0x1b,0x8e,0x39,0x1b,0x8f,0x3b,0x1b,0x8f,0x3e,0x1b,0x90,0x40,0x1b,0x90,0x43,0x1a,0x91,0x46,0x1a,0x91,0x48,0x1a,0x92,0x4b,0x1a,0x92,0x4e,0x19,0x92,0x51,0x19,0x92,0x54,0x19,0x92,0x56,0x18,0x92,0x59,0x18,0x92,0x5c,0x17,0x92,0x5e,0x17,0x92,0x61,0x17,0x92,0x63,0x16,0x92,0x66,0x16,0x92,0x68,0x15,0x92,0x6b,0x15,0x92,0x6d,0x14,0x92,0x6f,0x14,0x92,0x72,0x13,0x92,0x74,0x13,0x92,0x76,0x12,0x91,0x79,0x12,0x91,0x7b,0x11,0x91,0x7d,0x11,0x91,0x7f,0x10,0x91,0x81,0x10,0x91,0x83,0x0f,0x90,0x86,0x0f,0x90,0x88,0x0e,0x90,0x8a,0x0e,0x90,0x8c,0x0d,0x8f,0x8e,0x0d,0x8f,0x90,0x0d,0x8f,0x92,0x0c,0x8e,0x94,0x0c,0x8e,0x96,0x0b,0x8e,0x98,0x0b,0x8d,0x9a,0x0b,0x8d,0x9c,0x0a,0x8c,0x9e,0x0a,0x8c,0xa0,0x0a,0x8c,0xa2,0x0a,0x8b,0xa3,0x0a,0x8b,0xa5,0x09,0x8a,0xa7,0x09,0x8a,0xa9,0x09,0x8a,0xab,0x09,0x89,0xad,0x09,0x89,0xae,0x0a,0x88,0xb0,0x0a,0x88,0xb2,0x0a,0x88,0xb4,0x0a,0x87,0xb6,0x0a,0x87,0xb7,0x0b,0x86,0xb9,0x0b,0x86,0xbb,0x0c,0x85,0xbd,0x0c,0x85,0xbe,0x0d,0x85,0xc0,0x0d,0x84,0xc2,0x0e,0x84,0xc3,0x0e,0x83,0xc5,0x0f,0x83,0xc7,0x10,0x82,0xc8,0x10,0x82,0xca,0x11,0x81,0xcc,0x12,0x81,0xcd,0x13,0x80,0xcf,0x14,0x80,0xd0,0x15,0x7f,0xd2,0x16,0x7f,0xd3,0x17,0x7e,0xd5,0x19,0x7d,0xd6,0x1a,0x7d,0xd8,0x1c,0x7c,0xd9,0x1d,0x7b,0xda,0x1f,0x7b,0xdc,0x20,0x7a,0xdd,0x22,0x79,0xde,0x23,0x78,0xdf,0x25,0x78,0xe0,0x27,0x77,0xe2,0x29,0x76,0xe3,0x2a,0x75,0xe4,0x2c,0x74,0xe5,0x2e,0x73,0xe6,0x30,0x72,0xe7,0x31,0x72,0xe8,0x33,0x71,0xe9,0x35,0x70,0xea,0x37,0x6f,0xeb,0x39,0x6e,0xec,0x3b,0x6c,0xed,0x3d,0x6b,0xed,0x3e,0x6a,0xee,0x40,0x69,0xef,0x42,0x68,0xf0,0x44,0x67,0xf0,0x46,0x66,0xf1,0x48,0x65,0xf2,0x4a,0x64,0xf2,0x4c,0x62,0xf3,0x4d,0x61,0xf3,0x4f,0x60,0xf4,0x51,0x5f,0xf4,0x53,0x5e,0xf5,0x55,0x5d,0xf5,0x57,0x5c,0xf6,0x58,0x5c,0xf6,0x5a,0x5b,0xf7,0x5c,0x5a,0xf7,0x5e,0x59,0xf7,0x60,0x58,0xf8,0x62,0x57,0xf8,0x64,0x56,0xf8,0x65,0x55,0xf8,0x67,0x55,0xf8,0x69,0x54,0xf9,0x6b,0x53,0xf9,0x6d,0x52,0xf9,0x6f,0x52,0xf9,0x70,0x51,0xf9,0x72,0x50,0xf9,0x74,0x4f,0xf9,0x76,0x4f,0xf9,0x78,0x4e,0xf9,0x7a,0x4d,0xf9,0x7b,0x4d,0xf9,0x7d,0x4c,0xf9,0x7f,0x4c,0xf9,0x81,0x4b,0xf9,0x82,0x4a,0xf9,0x84,0x4a,0xf9,0x86,0x49,0xf9,0x87,0x48,0xf9,0x89,0x48,0xf9,0x8a,0x47,0xf9,0x8c,0x46,0xf9,0x8e,0x46,0xf9,0x8f,0x45,0xf9,0x91,0x44,0xf9,0x92,0x44,0xf9,0x94,0x43,0xf9,0x95,0x42,0xf9,0x97,0x42,0xfa,0x98,0x41,0xfa,0x9a,0x41,0xfa,0x9b,0x40,0xfa,0x9d,0x3f,0xfa,0x9e,0x3f,0xfa,0x9f,0x3e,0xfa,0xa1,0x3d,0xfb,0xa2,0x3d,0xfb,0xa4,0x3c,0xfb,0xa5,0x3b,0xfb,0xa6,0x3b,0xfb,0xa8,0x3a,0xfc,0xa9,0x39,0xfc,0xab,0x39,0xfc,0xac,0x39,0xfc,0xad,0x38,0xfc,0xaf,0x38,0xfc,0xb0,0x38,0xfc,0xb1,0x38,0xfc,0xb3,0x38,0xfc,0xb4,0x38,0xfc,0xb6,0x38,0xfd,0xb7,0x38,0xfd,0xb8,0x38,0xfd,0xba,0x38,0xfd,0xbb,0x38,0xfd,0xbd,0x38,0xfd,0xbe,0x38,0xfd,0xbf,0x38,0xfd,0xc1,0x39,0xfd,0xc2,0x39,0xfc,0xc3,0x39,0xfc,0xc5,0x39,0xfc,0xc6,0x3a,0xfc,0xc8,0x3a,0xfc,0xc9,0x3a,0xfc,0xca,0x3b,0xfc,0xcc,0x3b,0xfc,0xcd,0x3b,0xfc,0xce,0x3c,0xfc,0xd0,0x3c,0xfc,0xd1,0x3d,0xfc,0xd3,0x3d,0xfb,0xd4,0x3e,0xfb,0xd5,0x3e,0xfb,0xd7,0x3f,0xfb,0xd8,0x3f,0xfb,0xd9,0x40,0xfb,0xdb,0x40,0xfb,0xdc,0x41,0xfa,0xde,0x41,0xfa,0xdf,0x42,0xfa,0xe0,0x42,0xfa,0xe2,0x43,0xfa,0xe3,0x43,0xf9,0xe4,0x44,0xf9,0xe6,0x45,0xf9,0xe7,0x45,0xf9,0xe8,0x46,0xf8,0xea,0x46,0xf8,0xeb,0x47,0xf8,0xed,0x48,0xf8,0xee,0x48,0xf7,0xef,0x49,0xf7,0xf1,0x4a,0xf7,0xf2,0x4a,0xf7,0xf3,0x4b,0xf6,0xf5,0x4c,0xf6,0xf6,0x4c,0xf6,0xf7,0x4d,0xf5,0xf9,0x4e}; - static constexpr std::array L09 = {0x05,0x00,0xac,0x06,0x02,0xac,0x06,0x05,0xac,0x07,0x08,0xad,0x07,0x0b,0xad,0x08,0x0e,0xad,0x08,0x10,0xae,0x08,0x12,0xae,0x09,0x14,0xae,0x09,0x16,0xaf,0x0a,0x18,0xaf,0x0a,0x1a,0xaf,0x0a,0x1c,0xb0,0x0b,0x1d,0xb0,0x0b,0x1f,0xb0,0x0b,0x20,0xb1,0x0c,0x22,0xb1,0x0c,0x23,0xb1,0x0c,0x25,0xb1,0x0c,0x26,0xb2,0x0d,0x28,0xb2,0x0d,0x29,0xb2,0x0d,0x2a,0xb2,0x0d,0x2c,0xb3,0x0d,0x2d,0xb3,0x0d,0x2e,0xb3,0x0d,0x30,0xb3,0x0e,0x31,0xb4,0x0e,0x32,0xb4,0x0e,0x33,0xb4,0x0e,0x35,0xb4,0x0e,0x36,0xb4,0x0e,0x37,0xb4,0x0e,0x38,0xb4,0x0e,0x3a,0xb5,0x0e,0x3b,0xb5,0x0e,0x3c,0xb5,0x0e,0x3d,0xb5,0x0e,0x3e,0xb5,0x0e,0x40,0xb5,0x0d,0x41,0xb5,0x0d,0x42,0xb5,0x0d,0x43,0xb5,0x0d,0x44,0xb5,0x0d,0x46,0xb5,0x0d,0x47,0xb5,0x0d,0x48,0xb5,0x0c,0x49,0xb5,0x0c,0x4a,0xb5,0x0c,0x4c,0xb4,0x0c,0x4d,0xb4,0x0b,0x4e,0xb4,0x0b,0x4f,0xb4,0x0b,0x50,0xb4,0x0a,0x51,0xb3,0x0a,0x53,0xb3,0x0a,0x54,0xb3,0x09,0x55,0xb2,0x09,0x56,0xb2,0x08,0x57,0xb1,0x08,0x59,0xb1,0x08,0x5a,0xb0,0x07,0x5b,0xaf,0x07,0x5c,0xae,0x06,0x5e,0xae,0x06,0x5f,0xad,0x06,0x60,0xac,0x06,0x61,0xaa,0x06,0x63,0xa9,0x07,0x64,0xa8,0x08,0x65,0xa7,0x0a,0x66,0xa5,0x0c,0x67,0xa4,0x0d,0x68,0xa3,0x0f,0x6a,0xa1,0x11,0x6b,0xa0,0x13,0x6c,0x9e,0x14,0x6d,0x9c,0x16,0x6e,0x9b,0x18,0x6f,0x99,0x19,0x71,0x98,0x1b,0x72,0x96,0x1d,0x73,0x94,0x1e,0x74,0x92,0x1f,0x75,0x91,0x21,0x76,0x8f,0x22,0x77,0x8d,0x23,0x78,0x8b,0x24,0x79,0x89,0x25,0x7a,0x87,0x26,0x7c,0x85,0x27,0x7d,0x83,0x28,0x7e,0x81,0x29,0x7f,0x7f,0x2a,0x80,0x7d,0x2b,0x81,0x7b,0x2c,0x82,0x79,0x2c,0x83,0x77,0x2d,0x84,0x75,0x2e,0x85,0x72,0x2e,0x86,0x70,0x2e,0x87,0x6e,0x2f,0x89,0x6c,0x2f,0x8a,0x69,0x30,0x8b,0x67,0x30,0x8c,0x64,0x30,0x8d,0x62,0x30,0x8e,0x60,0x30,0x8f,0x5d,0x31,0x90,0x5b,0x31,0x91,0x59,0x31,0x92,0x56,0x32,0x93,0x54,0x32,0x94,0x52,0x33,0x95,0x50,0x34,0x96,0x4e,0x34,0x97,0x4c,0x35,0x98,0x4a,0x36,0x99,0x48,0x37,0x9a,0x47,0x38,0x9b,0x45,0x39,0x9c,0x43,0x3a,0x9d,0x41,0x3b,0x9d,0x40,0x3c,0x9e,0x3e,0x3d,0x9f,0x3c,0x3e,0xa0,0x3b,0x40,0xa1,0x39,0x41,0xa2,0x37,0x42,0xa3,0x36,0x44,0xa4,0x34,0x45,0xa4,0x33,0x47,0xa5,0x31,0x48,0xa6,0x30,0x4a,0xa7,0x2e,0x4c,0xa8,0x2d,0x4d,0xa8,0x2c,0x4f,0xa9,0x2a,0x51,0xaa,0x29,0x52,0xab,0x27,0x54,0xac,0x26,0x56,0xac,0x24,0x58,0xad,0x23,0x59,0xae,0x22,0x5b,0xaf,0x20,0x5d,0xaf,0x1f,0x5f,0xb0,0x1e,0x61,0xb1,0x1c,0x63,0xb2,0x1b,0x65,0xb2,0x1a,0x67,0xb3,0x18,0x69,0xb4,0x17,0x6b,0xb4,0x16,0x6d,0xb5,0x14,0x6f,0xb6,0x13,0x71,0xb6,0x12,0x73,0xb7,0x10,0x75,0xb8,0x0f,0x77,0xb8,0x0e,0x79,0xb9,0x0c,0x7b,0xba,0x0b,0x7d,0xba,0x0a,0x7f,0xbb,0x08,0x82,0xbc,0x07,0x84,0xbc,0x06,0x86,0xbd,0x06,0x88,0xbe,0x05,0x8a,0xbe,0x04,0x8c,0xbf,0x04,0x8f,0xbf,0x03,0x91,0xc0,0x03,0x93,0xc0,0x03,0x95,0xc1,0x02,0x98,0xc2,0x02,0x9a,0xc2,0x02,0x9c,0xc3,0x02,0x9e,0xc3,0x02,0xa0,0xc4,0x03,0xa2,0xc4,0x03,0xa5,0xc5,0x03,0xa7,0xc6,0x03,0xa9,0xc6,0x03,0xab,0xc7,0x04,0xad,0xc7,0x04,0xaf,0xc8,0x04,0xb1,0xc8,0x05,0xb3,0xc9,0x05,0xb5,0xca,0x06,0xb7,0xca,0x06,0xb9,0xcb,0x07,0xbb,0xcb,0x08,0xbd,0xcc,0x09,0xbf,0xcc,0x0a,0xc1,0xcd,0x0b,0xc2,0xce,0x0c,0xc4,0xce,0x0d,0xc6,0xcf,0x0e,0xc8,0xcf,0x0f,0xca,0xd0,0x10,0xcc,0xd1,0x11,0xcd,0xd1,0x12,0xcf,0xd2,0x13,0xd1,0xd2,0x14,0xd3,0xd3,0x15,0xd4,0xd4,0x17,0xd6,0xd4,0x18,0xd8,0xd5,0x19,0xd9,0xd6,0x1a,0xdb,0xd6,0x1c,0xdd,0xd7,0x1d,0xde,0xd7,0x1e,0xe0,0xd8,0x20,0xe1,0xd9,0x21,0xe3,0xda,0x22,0xe4,0xda,0x24,0xe6,0xdb,0x25,0xe7,0xdc,0x27,0xe9,0xdc,0x28,0xea,0xdd,0x2a,0xeb,0xde,0x2c,0xec,0xdf,0x2d,0xee,0xdf,0x2f,0xef,0xe0,0x31,0xf0,0xe1,0x33,0xf1,0xe2,0x34,0xf2,0xe3,0x36,0xf3,0xe3,0x38,0xf3,0xe4,0x3b,0xf4,0xe5,0x3d,0xf5,0xe6,0x3f,0xf5,0xe7,0x42,0xf6,0xe8,0x45,0xf6,0xe9,0x48,0xf7,0xea,0x4b,0xf8,0xeb,0x4f,0xf8,0xec,0x53,0xf9,0xed,0x58,0xfa,0xed,0x5d,0xfa,0xee,0x62,0xfb,0xef,0x67,0xfc,0xf0,0x6d,0xfc,0xf1,0x73,0xfd,0xf1,0x79,0xfd,0xf2,0x80,0xfe,0xf3,0x87,0xfe,0xf3,0x8e,0xff,0xf4,0x96,0xff,0xf5,0x9f,0xff,0xf5,0xa8,0xff,0xf6,0xb1,0xff,0xf7,0xbb,0xff,0xf7,0xc6,0xfe,0xf8,0xd2,0xfd,0xf8,0xde,0xfb,0xf9,0xeb,0xf9,0xf9,0xf9}; - static constexpr std::array L10 = {0x66,0x9b,0x90,0x66,0x9b,0x8f,0x67,0x9b,0x8f,0x68,0x9b,0x8f,0x69,0x9c,0x8e,0x69,0x9c,0x8e,0x6a,0x9c,0x8d,0x6b,0x9c,0x8d,0x6b,0x9d,0x8c,0x6c,0x9d,0x8c,0x6d,0x9d,0x8b,0x6e,0x9d,0x8b,0x6e,0x9d,0x8a,0x6f,0x9e,0x8a,0x70,0x9e,0x89,0x71,0x9e,0x89,0x71,0x9e,0x89,0x72,0x9f,0x88,0x73,0x9f,0x88,0x74,0x9f,0x87,0x74,0x9f,0x87,0x75,0x9f,0x86,0x76,0xa0,0x86,0x77,0xa0,0x85,0x77,0xa0,0x85,0x78,0xa0,0x85,0x79,0xa1,0x84,0x7a,0xa1,0x84,0x7b,0xa1,0x83,0x7b,0xa1,0x83,0x7c,0xa1,0x82,0x7d,0xa2,0x82,0x7e,0xa2,0x81,0x7f,0xa2,0x81,0x7f,0xa2,0x81,0x80,0xa2,0x80,0x81,0xa2,0x80,0x82,0xa3,0x7f,0x83,0xa3,0x7f,0x84,0xa3,0x7f,0x84,0xa3,0x7e,0x85,0xa3,0x7e,0x86,0xa4,0x7d,0x87,0xa4,0x7d,0x88,0xa4,0x7d,0x89,0xa4,0x7c,0x8a,0xa4,0x7c,0x8b,0xa4,0x7b,0x8c,0xa4,0x7b,0x8c,0xa5,0x7b,0x8d,0xa5,0x7a,0x8e,0xa5,0x7a,0x8f,0xa5,0x7a,0x90,0xa5,0x79,0x91,0xa5,0x79,0x92,0xa5,0x78,0x93,0xa5,0x78,0x94,0xa6,0x78,0x95,0xa6,0x77,0x96,0xa6,0x77,0x97,0xa6,0x77,0x99,0xa6,0x76,0x9a,0xa6,0x76,0x9b,0xa6,0x76,0x9c,0xa6,0x76,0x9d,0xa6,0x75,0x9e,0xa6,0x75,0x9f,0xa6,0x75,0xa1,0xa6,0x74,0xa2,0xa6,0x74,0xa3,0xa6,0x74,0xa4,0xa6,0x74,0xa6,0xa6,0x73,0xa7,0xa6,0x73,0xa8,0xa6,0x73,0xaa,0xa6,0x73,0xab,0xa6,0x73,0xac,0xa6,0x72,0xae,0xa6,0x72,0xaf,0xa6,0x72,0xb1,0xa6,0x72,0xb2,0xa6,0x72,0xb3,0xa6,0x72,0xb4,0xa6,0x71,0xb6,0xa6,0x71,0xb7,0xa6,0x71,0xb8,0xa6,0x71,0xb9,0xa6,0x71,0xba,0xa6,0x71,0xbb,0xa6,0x70,0xbc,0xa6,0x70,0xbd,0xa6,0x70,0xbf,0xa6,0x70,0xc0,0xa6,0x70,0xc0,0xa6,0x6f,0xc1,0xa6,0x6f,0xc2,0xa6,0x6f,0xc3,0xa6,0x6f,0xc4,0xa6,0x6f,0xc5,0xa6,0x6f,0xc6,0xa6,0x6e,0xc7,0xa6,0x6e,0xc7,0xa6,0x6e,0xc8,0xa7,0x6e,0xc9,0xa7,0x6e,0xca,0xa7,0x6e,0xca,0xa7,0x6d,0xcb,0xa7,0x6d,0xcc,0xa7,0x6d,0xcc,0xa7,0x6d,0xcd,0xa7,0x6d,0xcd,0xa8,0x6d,0xce,0xa8,0x6c,0xcf,0xa8,0x6c,0xcf,0xa8,0x6c,0xd0,0xa8,0x6c,0xd0,0xa9,0x6c,0xd0,0xa9,0x6c,0xd1,0xa9,0x6b,0xd1,0xa9,0x6b,0xd2,0xaa,0x6b,0xd2,0xaa,0x6b,0xd2,0xaa,0x6b,0xd3,0xaa,0x6a,0xd3,0xab,0x6a,0xd3,0xab,0x6a,0xd4,0xab,0x6a,0xd4,0xac,0x6a,0xd4,0xac,0x6a,0xd4,0xac,0x69,0xd4,0xad,0x69,0xd5,0xad,0x69,0xd5,0xad,0x69,0xd5,0xad,0x69,0xd5,0xae,0x69,0xd5,0xae,0x69,0xd5,0xae,0x69,0xd6,0xaf,0x69,0xd6,0xaf,0x69,0xd6,0xaf,0x69,0xd6,0xb0,0x69,0xd6,0xb0,0x6a,0xd6,0xb0,0x6a,0xd7,0xb1,0x6a,0xd7,0xb1,0x6a,0xd7,0xb1,0x6a,0xd7,0xb2,0x6b,0xd7,0xb2,0x6b,0xd7,0xb2,0x6b,0xd7,0xb3,0x6c,0xd7,0xb3,0x6c,0xd8,0xb3,0x6d,0xd8,0xb4,0x6d,0xd8,0xb4,0x6d,0xd8,0xb4,0x6e,0xd8,0xb5,0x6e,0xd8,0xb5,0x6f,0xd8,0xb5,0x70,0xd8,0xb6,0x70,0xd8,0xb6,0x71,0xd8,0xb6,0x71,0xd8,0xb7,0x72,0xd8,0xb7,0x73,0xd8,0xb7,0x73,0xd9,0xb8,0x74,0xd9,0xb8,0x75,0xd9,0xb8,0x76,0xd9,0xb8,0x76,0xd9,0xb9,0x77,0xd9,0xb9,0x78,0xd9,0xb9,0x79,0xd9,0xba,0x7a,0xd9,0xba,0x7b,0xd9,0xba,0x7c,0xd9,0xbb,0x7d,0xd9,0xbb,0x7e,0xd9,0xbb,0x7f,0xd9,0xbc,0x80,0xd8,0xbc,0x81,0xd8,0xbc,0x82,0xd8,0xbd,0x83,0xd8,0xbd,0x84,0xd8,0xbd,0x85,0xd8,0xbe,0x87,0xd8,0xbe,0x88,0xd8,0xbe,0x89,0xd8,0xbf,0x8a,0xd8,0xbf,0x8b,0xd8,0xbf,0x8c,0xd8,0xc0,0x8d,0xd8,0xc0,0x8e,0xd8,0xc0,0x8f,0xd8,0xc1,0x90,0xd8,0xc1,0x91,0xd8,0xc1,0x92,0xd8,0xc2,0x94,0xd8,0xc2,0x95,0xd8,0xc2,0x96,0xd8,0xc3,0x97,0xd8,0xc3,0x98,0xd8,0xc3,0x99,0xd8,0xc4,0x9a,0xd8,0xc4,0x9b,0xd8,0xc4,0x9c,0xd7,0xc5,0x9d,0xd7,0xc5,0x9e,0xd7,0xc5,0x9f,0xd7,0xc5,0xa1,0xd7,0xc6,0xa2,0xd7,0xc6,0xa3,0xd7,0xc6,0xa4,0xd7,0xc7,0xa5,0xd7,0xc7,0xa6,0xd7,0xc7,0xa7,0xd7,0xc8,0xa8,0xd7,0xc8,0xa9,0xd7,0xc8,0xaa,0xd7,0xc9,0xab,0xd7,0xc9,0xac,0xd7,0xc9,0xad,0xd7,0xca,0xaf,0xd7,0xca,0xb0,0xd7,0xca,0xb1,0xd7,0xca,0xb2,0xd7,0xcb,0xb3,0xd7,0xcb,0xb4,0xd7,0xcb,0xb5,0xd6,0xcc,0xb6,0xd6,0xcc,0xb7,0xd6,0xcc,0xb8,0xd6,0xcd,0xb9,0xd6,0xcd,0xba,0xd6,0xcd,0xbb,0xd6,0xce,0xbd,0xd6,0xce,0xbe,0xd6,0xce,0xbf,0xd6,0xce,0xc0,0xd6,0xcf,0xc1,0xd6,0xcf,0xc2,0xd6,0xcf,0xc3,0xd6,0xd0,0xc4,0xd6,0xd0,0xc5,0xd5,0xd0,0xc6,0xd5,0xd1,0xc7,0xd5,0xd1,0xc8,0xd5,0xd1,0xc9,0xd5,0xd1,0xcb,0xd5,0xd2,0xcc,0xd5,0xd2,0xcd,0xd5,0xd2,0xce,0xd5,0xd3,0xcf,0xd5,0xd3,0xd0,0xd5,0xd3,0xd1,0xd4,0xd4,0xd2,0xd4,0xd4,0xd3,0xd4,0xd4,0xd4}; - static constexpr std::array L11 = {0x70,0xad,0x5c,0x71,0xad,0x5c,0x72,0xad,0x5c,0x74,0xad,0x5c,0x75,0xad,0x5c,0x76,0xad,0x5d,0x78,0xad,0x5d,0x79,0xad,0x5d,0x7a,0xae,0x5d,0x7c,0xae,0x5d,0x7d,0xae,0x5d,0x7e,0xae,0x5d,0x80,0xae,0x5d,0x81,0xae,0x5d,0x82,0xae,0x5e,0x83,0xae,0x5e,0x85,0xae,0x5e,0x86,0xae,0x5e,0x87,0xae,0x5e,0x88,0xae,0x5e,0x8a,0xae,0x5e,0x8b,0xae,0x5e,0x8c,0xae,0x5f,0x8d,0xaf,0x5f,0x8e,0xaf,0x5f,0x90,0xaf,0x5f,0x91,0xaf,0x5f,0x92,0xaf,0x5f,0x93,0xaf,0x5f,0x94,0xaf,0x5f,0x95,0xaf,0x5f,0x96,0xaf,0x60,0x98,0xaf,0x60,0x99,0xaf,0x60,0x9a,0xaf,0x60,0x9b,0xaf,0x60,0x9c,0xaf,0x60,0x9d,0xaf,0x60,0x9e,0xaf,0x60,0x9f,0xaf,0x61,0xa0,0xb0,0x61,0xa1,0xb0,0x61,0xa3,0xb0,0x61,0xa4,0xb0,0x61,0xa5,0xb0,0x61,0xa6,0xb0,0x61,0xa7,0xb0,0x61,0xa8,0xb0,0x62,0xa9,0xb0,0x62,0xaa,0xb0,0x62,0xab,0xb0,0x62,0xac,0xb0,0x62,0xad,0xb0,0x62,0xae,0xb0,0x62,0xaf,0xb0,0x62,0xb0,0xb0,0x63,0xb1,0xb0,0x63,0xb2,0xb0,0x63,0xb3,0xb0,0x63,0xb4,0xb1,0x63,0xb5,0xb1,0x63,0xb6,0xb1,0x63,0xb7,0xb1,0x64,0xb8,0xb1,0x64,0xb9,0xb1,0x64,0xba,0xb1,0x64,0xbb,0xb1,0x64,0xbc,0xb1,0x64,0xbd,0xb1,0x64,0xbe,0xb1,0x64,0xbf,0xb1,0x65,0xc0,0xb1,0x65,0xc1,0xb1,0x65,0xc1,0xb1,0x65,0xc2,0xb1,0x65,0xc3,0xb1,0x65,0xc4,0xb1,0x65,0xc5,0xb2,0x66,0xc6,0xb2,0x66,0xc7,0xb2,0x66,0xc8,0xb2,0x66,0xc9,0xb2,0x66,0xca,0xb2,0x66,0xca,0xb2,0x66,0xcb,0xb2,0x66,0xcc,0xb2,0x67,0xcd,0xb2,0x67,0xce,0xb2,0x67,0xcf,0xb2,0x67,0xcf,0xb2,0x67,0xd0,0xb2,0x67,0xd1,0xb2,0x67,0xd2,0xb3,0x68,0xd3,0xb3,0x68,0xd4,0xb3,0x68,0xd4,0xb3,0x68,0xd5,0xb3,0x68,0xd6,0xb3,0x68,0xd7,0xb3,0x68,0xd7,0xb3,0x69,0xd8,0xb3,0x69,0xd9,0xb3,0x69,0xda,0xb3,0x69,0xda,0xb4,0x69,0xdb,0xb4,0x69,0xdc,0xb4,0x69,0xdc,0xb4,0x6a,0xdd,0xb4,0x6a,0xde,0xb4,0x6a,0xde,0xb4,0x6a,0xdf,0xb4,0x6a,0xe0,0xb5,0x6a,0xe0,0xb5,0x6b,0xe1,0xb5,0x6b,0xe1,0xb5,0x6b,0xe2,0xb5,0x6b,0xe2,0xb5,0x6b,0xe3,0xb6,0x6b,0xe3,0xb6,0x6b,0xe4,0xb6,0x6c,0xe4,0xb6,0x6c,0xe5,0xb6,0x6c,0xe5,0xb7,0x6c,0xe5,0xb7,0x6c,0xe6,0xb7,0x6c,0xe6,0xb7,0x6d,0xe6,0xb8,0x6d,0xe6,0xb8,0x6d,0xe6,0xb8,0x6d,0xe6,0xb9,0x6d,0xe7,0xb9,0x6e,0xe7,0xb9,0x6e,0xe7,0xba,0x6e,0xe7,0xba,0x6e,0xe7,0xbb,0x6f,0xe7,0xbb,0x6f,0xe7,0xbb,0x6f,0xe7,0xbc,0x70,0xe7,0xbc,0x70,0xe7,0xbc,0x71,0xe7,0xbd,0x71,0xe7,0xbd,0x71,0xe7,0xbd,0x72,0xe7,0xbe,0x72,0xe7,0xbe,0x73,0xe7,0xbe,0x73,0xe7,0xbf,0x74,0xe7,0xbf,0x74,0xe7,0xc0,0x75,0xe7,0xc0,0x75,0xe7,0xc0,0x76,0xe7,0xc1,0x77,0xe7,0xc1,0x77,0xe7,0xc1,0x78,0xe7,0xc2,0x79,0xe7,0xc2,0x79,0xe7,0xc2,0x7a,0xe7,0xc3,0x7b,0xe7,0xc3,0x7c,0xe7,0xc3,0x7c,0xe7,0xc4,0x7d,0xe7,0xc4,0x7e,0xe7,0xc4,0x7f,0xe7,0xc5,0x7f,0xe7,0xc5,0x80,0xe7,0xc5,0x81,0xe7,0xc6,0x82,0xe7,0xc6,0x83,0xe7,0xc6,0x84,0xe7,0xc7,0x85,0xe7,0xc7,0x86,0xe7,0xc8,0x87,0xe7,0xc8,0x88,0xe7,0xc8,0x89,0xe7,0xc9,0x8a,0xe7,0xc9,0x8b,0xe7,0xc9,0x8c,0xe7,0xca,0x8d,0xe7,0xca,0x8e,0xe7,0xca,0x8f,0xe7,0xcb,0x90,0xe7,0xcb,0x91,0xe7,0xcb,0x93,0xe7,0xcc,0x94,0xe7,0xcc,0x95,0xe7,0xcc,0x96,0xe7,0xcd,0x97,0xe6,0xcd,0x98,0xe6,0xcd,0x99,0xe6,0xce,0x9a,0xe6,0xce,0x9b,0xe6,0xce,0x9c,0xe6,0xcf,0x9e,0xe6,0xcf,0x9f,0xe6,0xcf,0xa0,0xe6,0xd0,0xa1,0xe6,0xd0,0xa2,0xe6,0xd0,0xa3,0xe6,0xd0,0xa4,0xe6,0xd1,0xa5,0xe6,0xd1,0xa6,0xe6,0xd1,0xa7,0xe6,0xd2,0xa9,0xe6,0xd2,0xaa,0xe6,0xd2,0xab,0xe6,0xd3,0xac,0xe6,0xd3,0xad,0xe6,0xd3,0xae,0xe6,0xd4,0xaf,0xe6,0xd4,0xb0,0xe5,0xd4,0xb1,0xe5,0xd5,0xb2,0xe5,0xd5,0xb3,0xe5,0xd5,0xb5,0xe5,0xd6,0xb6,0xe5,0xd6,0xb7,0xe5,0xd6,0xb8,0xe5,0xd7,0xb9,0xe5,0xd7,0xba,0xe5,0xd7,0xbb,0xe5,0xd7,0xbc,0xe5,0xd8,0xbd,0xe5,0xd8,0xbe,0xe5,0xd8,0xbf,0xe5,0xd9,0xc1,0xe5,0xd9,0xc2,0xe5,0xd9,0xc3,0xe5,0xda,0xc4,0xe5,0xda,0xc5,0xe4,0xda,0xc6,0xe4,0xdb,0xc7,0xe4,0xdb,0xc8,0xe4,0xdb,0xc9,0xe4,0xdc,0xca,0xe4,0xdc,0xcb,0xe4,0xdc,0xcc,0xe4,0xdc,0xce,0xe4,0xdd,0xcf,0xe4,0xdd,0xd0,0xe4,0xdd,0xd1,0xe4,0xde,0xd2,0xe4,0xde,0xd3,0xe4,0xde,0xd4,0xe3,0xdf,0xd5,0xe3,0xdf,0xd6,0xe3,0xdf,0xd7,0xe3,0xe0,0xd8,0xe3,0xe0,0xda,0xe3,0xe0,0xdb,0xe3,0xe0,0xdc,0xe3,0xe1,0xdd,0xe3,0xe1,0xde,0xe3,0xe1,0xdf,0xe3,0xe2,0xe0,0xe2,0xe2,0xe1,0xe2,0xe2,0xe2}; - static constexpr std::array L12 = {0xf1,0xf1,0xf1,0xf0,0xf0,0xf1,0xef,0xf0,0xf0,0xee,0xef,0xf0,0xee,0xef,0xf0,0xed,0xee,0xf0,0xec,0xee,0xf0,0xeb,0xed,0xf0,0xea,0xed,0xf0,0xea,0xec,0xf0,0xe9,0xec,0xf0,0xe8,0xeb,0xf0,0xe7,0xeb,0xf0,0xe7,0xea,0xf0,0xe6,0xea,0xf0,0xe5,0xe9,0xf0,0xe4,0xe9,0xf0,0xe4,0xe9,0xef,0xe3,0xe8,0xef,0xe2,0xe8,0xef,0xe1,0xe7,0xef,0xe1,0xe7,0xef,0xe0,0xe6,0xef,0xdf,0xe6,0xef,0xde,0xe5,0xef,0xde,0xe5,0xef,0xdd,0xe4,0xef,0xdc,0xe4,0xef,0xdb,0xe3,0xef,0xda,0xe3,0xef,0xda,0xe2,0xee,0xd9,0xe2,0xee,0xd8,0xe1,0xee,0xd7,0xe1,0xee,0xd7,0xe1,0xee,0xd6,0xe0,0xee,0xd5,0xe0,0xee,0xd4,0xdf,0xee,0xd4,0xdf,0xee,0xd3,0xde,0xee,0xd2,0xde,0xee,0xd1,0xdd,0xee,0xd1,0xdd,0xed,0xd0,0xdc,0xed,0xcf,0xdc,0xed,0xce,0xdb,0xed,0xcd,0xdb,0xed,0xcd,0xda,0xed,0xcc,0xda,0xed,0xcb,0xd9,0xed,0xca,0xd9,0xed,0xca,0xd9,0xed,0xc9,0xd8,0xec,0xc8,0xd8,0xec,0xc7,0xd7,0xec,0xc7,0xd7,0xec,0xc6,0xd6,0xec,0xc5,0xd6,0xec,0xc4,0xd5,0xec,0xc4,0xd5,0xec,0xc3,0xd4,0xec,0xc2,0xd4,0xeb,0xc1,0xd3,0xeb,0xc0,0xd3,0xeb,0xc0,0xd2,0xeb,0xbf,0xd2,0xeb,0xbe,0xd2,0xeb,0xbd,0xd1,0xeb,0xbd,0xd1,0xeb,0xbc,0xd0,0xea,0xbb,0xd0,0xea,0xba,0xcf,0xea,0xba,0xcf,0xea,0xb9,0xce,0xea,0xb8,0xce,0xea,0xb7,0xcd,0xea,0xb7,0xcd,0xe9,0xb6,0xcc,0xe9,0xb5,0xcc,0xe9,0xb4,0xcc,0xe9,0xb4,0xcb,0xe9,0xb3,0xcb,0xe9,0xb2,0xca,0xe9,0xb1,0xca,0xe8,0xb1,0xc9,0xe8,0xb0,0xc9,0xe8,0xaf,0xc8,0xe8,0xae,0xc8,0xe8,0xae,0xc7,0xe7,0xad,0xc7,0xe7,0xac,0xc6,0xe7,0xab,0xc6,0xe7,0xab,0xc5,0xe7,0xaa,0xc5,0xe7,0xa9,0xc5,0xe6,0xa8,0xc4,0xe6,0xa8,0xc4,0xe6,0xa7,0xc3,0xe6,0xa6,0xc3,0xe6,0xa6,0xc2,0xe5,0xa5,0xc2,0xe5,0xa4,0xc1,0xe5,0xa3,0xc1,0xe5,0xa3,0xc0,0xe4,0xa2,0xc0,0xe4,0xa1,0xbf,0xe4,0xa1,0xbf,0xe4,0xa0,0xbf,0xe3,0x9f,0xbe,0xe3,0x9f,0xbe,0xe3,0x9e,0xbd,0xe2,0x9d,0xbd,0xe2,0x9d,0xbc,0xe2,0x9c,0xbc,0xe2,0x9b,0xbb,0xe1,0x9b,0xbb,0xe1,0x9a,0xba,0xe1,0x99,0xba,0xe0,0x99,0xb9,0xe0,0x98,0xb9,0xdf,0x98,0xb8,0xdf,0x97,0xb8,0xdf,0x96,0xb7,0xde,0x96,0xb7,0xde,0x95,0xb7,0xde,0x95,0xb6,0xdd,0x94,0xb6,0xdd,0x93,0xb5,0xdd,0x93,0xb5,0xdc,0x92,0xb4,0xdc,0x92,0xb4,0xdb,0x91,0xb3,0xdb,0x91,0xb3,0xdb,0x90,0xb2,0xda,0x8f,0xb2,0xda,0x8f,0xb1,0xd9,0x8e,0xb1,0xd9,0x8e,0xb0,0xd9,0x8d,0xb0,0xd8,0x8d,0xaf,0xd8,0x8c,0xaf,0xd7,0x8b,0xaf,0xd7,0x8b,0xae,0xd7,0x8a,0xae,0xd6,0x8a,0xad,0xd6,0x89,0xad,0xd5,0x89,0xac,0xd5,0x88,0xac,0xd4,0x88,0xab,0xd4,0x87,0xab,0xd4,0x87,0xaa,0xd3,0x86,0xaa,0xd3,0x85,0xa9,0xd2,0x85,0xa9,0xd2,0x84,0xa8,0xd1,0x84,0xa8,0xd1,0x83,0xa8,0xd0,0x83,0xa7,0xd0,0x82,0xa7,0xd0,0x82,0xa6,0xcf,0x81,0xa6,0xcf,0x81,0xa5,0xce,0x80,0xa5,0xce,0x80,0xa4,0xcd,0x7f,0xa4,0xcd,0x7f,0xa3,0xcc,0x7e,0xa3,0xcc,0x7e,0xa2,0xcb,0x7d,0xa2,0xcb,0x7d,0xa1,0xca,0x7c,0xa1,0xca,0x7c,0xa0,0xc9,0x7c,0xa0,0xc9,0x7b,0xa0,0xc8,0x7b,0x9f,0xc8,0x7a,0x9f,0xc7,0x79,0x9e,0xc7,0x79,0x9e,0xc7,0x78,0x9d,0xc6,0x78,0x9d,0xc6,0x77,0x9c,0xc5,0x77,0x9c,0xc5,0x76,0x9b,0xc5,0x76,0x9b,0xc4,0x75,0x9a,0xc4,0x74,0x9a,0xc3,0x74,0x9a,0xc3,0x73,0x99,0xc3,0x73,0x99,0xc2,0x72,0x98,0xc2,0x71,0x98,0xc2,0x71,0x97,0xc1,0x70,0x97,0xc1,0x6f,0x96,0xc1,0x6f,0x96,0xc0,0x6e,0x96,0xc0,0x6d,0x95,0xc0,0x6d,0x95,0xbf,0x6c,0x94,0xbf,0x6b,0x94,0xbf,0x6b,0x93,0xbe,0x6a,0x93,0xbe,0x69,0x92,0xbe,0x69,0x92,0xbe,0x68,0x91,0xbd,0x67,0x91,0xbd,0x67,0x91,0xbd,0x66,0x90,0xbc,0x65,0x90,0xbc,0x64,0x8f,0xbc,0x64,0x8f,0xbc,0x63,0x8e,0xbb,0x62,0x8e,0xbb,0x61,0x8e,0xbb,0x61,0x8d,0xbb,0x60,0x8d,0xba,0x5f,0x8c,0xba,0x5e,0x8c,0xba,0x5e,0x8b,0xba,0x5d,0x8b,0xb9,0x5c,0x8a,0xb9,0x5b,0x8a,0xb9,0x5a,0x8a,0xb9,0x5a,0x89,0xb8,0x59,0x89,0xb8,0x58,0x88,0xb8,0x57,0x88,0xb8,0x56,0x87,0xb8,0x55,0x87,0xb7,0x54,0x87,0xb7,0x54,0x86,0xb7,0x53,0x86,0xb7,0x52,0x85,0xb6,0x51,0x85,0xb6,0x50,0x84,0xb6,0x4f,0x84,0xb6,0x4e,0x84,0xb6,0x4d,0x83,0xb5,0x4c,0x83,0xb5,0x4b,0x82,0xb5,0x4a,0x82,0xb5,0x4a,0x81,0xb5,0x49,0x81,0xb4,0x48,0x81,0xb4,0x47,0x80,0xb4,0x46,0x80,0xb4,0x45,0x7f,0xb4,0x43,0x7f,0xb3,0x42,0x7e,0xb3,0x41,0x7e,0xb3,0x40,0x7e,0xb3,0x3f,0x7d,0xb3,0x3e,0x7d,0xb2,0x3d,0x7c,0xb2,0x3c,0x7c,0xb2,0x3b,0x7c,0xb2}; - static constexpr std::array L13 = {0x00,0x00,0x00,0x02,0x00,0x00,0x04,0x01,0x00,0x06,0x01,0x00,0x08,0x02,0x00,0x0a,0x02,0x00,0x0c,0x02,0x00,0x0e,0x03,0x00,0x10,0x03,0x00,0x12,0x03,0x00,0x13,0x04,0x00,0x15,0x04,0x00,0x16,0x04,0x00,0x17,0x04,0x00,0x19,0x05,0x00,0x1a,0x05,0x00,0x1b,0x05,0x00,0x1c,0x05,0x00,0x1e,0x06,0x00,0x1f,0x06,0x00,0x20,0x06,0x00,0x21,0x06,0x00,0x22,0x06,0x00,0x23,0x07,0x00,0x24,0x07,0x00,0x25,0x07,0x00,0x26,0x07,0x00,0x27,0x07,0x00,0x28,0x08,0x00,0x29,0x08,0x00,0x29,0x08,0x00,0x2a,0x08,0x00,0x2b,0x08,0x00,0x2c,0x08,0x00,0x2d,0x08,0x00,0x2e,0x09,0x00,0x2e,0x09,0x00,0x2f,0x09,0x00,0x30,0x09,0x00,0x31,0x09,0x00,0x32,0x09,0x00,0x32,0x0a,0x00,0x33,0x0a,0x00,0x34,0x0a,0x00,0x35,0x0a,0x00,0x35,0x0a,0x00,0x36,0x0a,0x00,0x37,0x0a,0x00,0x37,0x0a,0x00,0x38,0x0b,0x00,0x39,0x0b,0x00,0x3a,0x0b,0x00,0x3a,0x0b,0x00,0x3b,0x0b,0x00,0x3c,0x0b,0x00,0x3d,0x0b,0x00,0x3d,0x0c,0x00,0x3e,0x0c,0x00,0x3f,0x0c,0x00,0x40,0x0c,0x00,0x40,0x0c,0x00,0x41,0x0c,0x00,0x42,0x0c,0x00,0x43,0x0d,0x00,0x44,0x0d,0x00,0x44,0x0d,0x00,0x45,0x0d,0x00,0x46,0x0d,0x00,0x47,0x0d,0x00,0x47,0x0d,0x00,0x48,0x0e,0x00,0x49,0x0e,0x00,0x4a,0x0e,0x00,0x4a,0x0e,0x00,0x4b,0x0e,0x00,0x4c,0x0e,0x00,0x4d,0x0f,0x00,0x4e,0x0f,0x00,0x4e,0x0f,0x00,0x4f,0x0f,0x00,0x50,0x0f,0x00,0x51,0x0f,0x00,0x51,0x0f,0x00,0x52,0x10,0x00,0x53,0x10,0x00,0x54,0x10,0x00,0x55,0x10,0x00,0x55,0x10,0x00,0x56,0x10,0x00,0x57,0x10,0x00,0x58,0x11,0x00,0x58,0x11,0x00,0x59,0x11,0x00,0x5a,0x11,0x00,0x5b,0x11,0x00,0x5c,0x11,0x00,0x5c,0x11,0x00,0x5d,0x12,0x00,0x5e,0x12,0x00,0x5f,0x12,0x00,0x60,0x12,0x00,0x60,0x12,0x00,0x61,0x12,0x00,0x62,0x13,0x00,0x63,0x13,0x00,0x64,0x13,0x00,0x64,0x13,0x00,0x65,0x13,0x00,0x66,0x13,0x00,0x67,0x13,0x00,0x68,0x14,0x00,0x68,0x14,0x00,0x69,0x14,0x00,0x6a,0x14,0x00,0x6b,0x14,0x00,0x6c,0x14,0x00,0x6d,0x14,0x00,0x6d,0x15,0x00,0x6e,0x15,0x00,0x6f,0x15,0x00,0x70,0x15,0x00,0x71,0x15,0x00,0x71,0x15,0x00,0x72,0x16,0x00,0x73,0x16,0x00,0x74,0x16,0x00,0x75,0x16,0x00,0x76,0x16,0x00,0x76,0x16,0x00,0x77,0x17,0x00,0x78,0x17,0x00,0x79,0x17,0x00,0x7a,0x17,0x00,0x7a,0x17,0x00,0x7b,0x17,0x00,0x7c,0x17,0x00,0x7d,0x18,0x00,0x7e,0x18,0x00,0x7f,0x18,0x00,0x7f,0x18,0x00,0x80,0x18,0x00,0x81,0x18,0x00,0x82,0x19,0x00,0x83,0x19,0x00,0x84,0x19,0x00,0x84,0x19,0x00,0x85,0x19,0x00,0x86,0x19,0x00,0x87,0x19,0x00,0x88,0x1a,0x00,0x89,0x1a,0x00,0x8a,0x1a,0x00,0x8a,0x1a,0x00,0x8b,0x1a,0x00,0x8c,0x1a,0x00,0x8d,0x1b,0x00,0x8e,0x1b,0x00,0x8f,0x1b,0x00,0x8f,0x1b,0x00,0x90,0x1b,0x00,0x91,0x1b,0x00,0x92,0x1c,0x00,0x93,0x1c,0x00,0x94,0x1c,0x00,0x95,0x1c,0x00,0x95,0x1c,0x00,0x96,0x1c,0x00,0x97,0x1d,0x00,0x98,0x1d,0x00,0x99,0x1d,0x00,0x9a,0x1d,0x00,0x9b,0x1d,0x00,0x9b,0x1d,0x00,0x9c,0x1e,0x00,0x9d,0x1e,0x00,0x9e,0x1e,0x00,0x9f,0x1e,0x00,0xa0,0x1e,0x00,0xa1,0x1e,0x00,0xa1,0x1e,0x00,0xa2,0x1f,0x00,0xa3,0x1f,0x00,0xa4,0x1f,0x00,0xa5,0x1f,0x00,0xa6,0x1f,0x00,0xa7,0x1f,0x00,0xa8,0x20,0x00,0xa8,0x20,0x00,0xa9,0x20,0x00,0xaa,0x20,0x00,0xab,0x20,0x00,0xac,0x20,0x00,0xad,0x21,0x00,0xae,0x21,0x00,0xaf,0x21,0x00,0xaf,0x21,0x00,0xb0,0x21,0x00,0xb1,0x21,0x00,0xb2,0x22,0x00,0xb3,0x22,0x00,0xb4,0x22,0x00,0xb5,0x22,0x00,0xb6,0x22,0x00,0xb6,0x22,0x00,0xb7,0x23,0x00,0xb8,0x23,0x00,0xb9,0x23,0x00,0xba,0x23,0x00,0xbb,0x23,0x00,0xbc,0x23,0x00,0xbd,0x24,0x00,0xbe,0x24,0x00,0xbe,0x24,0x00,0xbf,0x24,0x00,0xc0,0x24,0x00,0xc1,0x24,0x00,0xc2,0x25,0x00,0xc3,0x25,0x00,0xc4,0x25,0x00,0xc5,0x25,0x00,0xc6,0x25,0x00,0xc7,0x26,0x00,0xc7,0x26,0x00,0xc8,0x26,0x00,0xc9,0x26,0x00,0xca,0x26,0x00,0xcb,0x26,0x00,0xcc,0x27,0x00,0xcd,0x27,0x00,0xce,0x27,0x00,0xcf,0x27,0x00,0xd0,0x27,0x00,0xd0,0x27,0x00,0xd1,0x28,0x00,0xd2,0x28,0x00,0xd3,0x28,0x00,0xd4,0x28,0x00,0xd5,0x28,0x00,0xd6,0x28,0x00,0xd7,0x29,0x00,0xd8,0x29,0x00,0xd9,0x29,0x00,0xda,0x29,0x00,0xda,0x29,0x00,0xdb,0x29,0x00,0xdc,0x2a,0x00,0xdd,0x2a,0x00,0xde,0x2a,0x00,0xdf,0x2a,0x00,0xe0,0x2a,0x00,0xe1,0x2a,0x00,0xe2,0x2b,0x00,0xe3,0x2b,0x00,0xe4,0x2b,0x00,0xe5,0x2b,0x00,0xe6,0x2b,0x00}; - static constexpr std::array L14 = {0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x02,0x00,0x00,0x03,0x00,0x00,0x04,0x00,0x00,0x05,0x00,0x00,0x06,0x00,0x00,0x06,0x00,0x00,0x07,0x00,0x00,0x08,0x00,0x00,0x09,0x00,0x00,0x0a,0x00,0x00,0x0b,0x00,0x00,0x0c,0x00,0x00,0x0d,0x00,0x00,0x0d,0x00,0x00,0x0e,0x00,0x00,0x0f,0x00,0x00,0x10,0x00,0x00,0x10,0x00,0x00,0x11,0x00,0x00,0x12,0x00,0x00,0x12,0x00,0x00,0x13,0x00,0x00,0x13,0x00,0x00,0x14,0x00,0x00,0x15,0x00,0x00,0x15,0x00,0x00,0x16,0x00,0x00,0x16,0x00,0x00,0x17,0x00,0x00,0x17,0x00,0x00,0x18,0x00,0x00,0x18,0x00,0x00,0x19,0x00,0x00,0x19,0x00,0x00,0x1a,0x00,0x00,0x1a,0x00,0x00,0x1a,0x00,0x00,0x1b,0x00,0x00,0x1b,0x00,0x00,0x1c,0x00,0x00,0x1c,0x00,0x00,0x1d,0x00,0x00,0x1d,0x00,0x00,0x1d,0x00,0x00,0x1e,0x00,0x00,0x1e,0x00,0x00,0x1f,0x00,0x00,0x1f,0x00,0x00,0x1f,0x00,0x00,0x20,0x00,0x00,0x20,0x00,0x00,0x21,0x00,0x00,0x21,0x00,0x00,0x22,0x00,0x00,0x22,0x00,0x00,0x22,0x00,0x00,0x23,0x00,0x00,0x23,0x00,0x00,0x24,0x00,0x00,0x24,0x00,0x00,0x24,0x00,0x00,0x25,0x00,0x00,0x25,0x00,0x00,0x26,0x00,0x00,0x26,0x00,0x00,0x27,0x00,0x00,0x27,0x00,0x00,0x27,0x00,0x00,0x28,0x00,0x00,0x28,0x00,0x00,0x29,0x00,0x00,0x29,0x00,0x00,0x2a,0x00,0x00,0x2a,0x00,0x00,0x2a,0x00,0x00,0x2b,0x00,0x00,0x2b,0x00,0x00,0x2c,0x00,0x00,0x2c,0x00,0x00,0x2d,0x00,0x00,0x2d,0x00,0x00,0x2d,0x00,0x00,0x2e,0x00,0x00,0x2e,0x00,0x00,0x2f,0x00,0x00,0x2f,0x00,0x00,0x30,0x00,0x00,0x30,0x00,0x00,0x30,0x00,0x00,0x31,0x00,0x00,0x31,0x00,0x00,0x32,0x00,0x00,0x32,0x00,0x00,0x33,0x00,0x00,0x33,0x00,0x00,0x34,0x00,0x00,0x34,0x00,0x00,0x34,0x00,0x00,0x35,0x00,0x00,0x35,0x00,0x00,0x36,0x00,0x00,0x36,0x00,0x00,0x37,0x00,0x00,0x37,0x00,0x00,0x38,0x00,0x00,0x38,0x00,0x00,0x38,0x00,0x00,0x39,0x00,0x00,0x39,0x00,0x00,0x3a,0x00,0x00,0x3a,0x00,0x00,0x3b,0x00,0x00,0x3b,0x00,0x00,0x3c,0x00,0x00,0x3c,0x00,0x00,0x3c,0x00,0x00,0x3d,0x00,0x00,0x3d,0x00,0x00,0x3e,0x00,0x00,0x3e,0x00,0x00,0x3f,0x00,0x00,0x3f,0x00,0x00,0x40,0x00,0x00,0x40,0x00,0x00,0x41,0x00,0x00,0x41,0x00,0x00,0x41,0x00,0x00,0x42,0x00,0x00,0x42,0x00,0x00,0x43,0x00,0x00,0x43,0x00,0x00,0x44,0x00,0x00,0x44,0x00,0x00,0x45,0x00,0x00,0x45,0x00,0x00,0x46,0x00,0x00,0x46,0x00,0x00,0x47,0x00,0x00,0x47,0x00,0x00,0x47,0x00,0x00,0x48,0x00,0x00,0x48,0x00,0x00,0x49,0x00,0x00,0x49,0x00,0x00,0x4a,0x00,0x00,0x4a,0x00,0x00,0x4b,0x00,0x00,0x4b,0x00,0x00,0x4c,0x00,0x00,0x4c,0x00,0x00,0x4d,0x00,0x00,0x4d,0x00,0x00,0x4e,0x00,0x00,0x4e,0x00,0x00,0x4f,0x00,0x00,0x4f,0x00,0x00,0x4f,0x00,0x00,0x50,0x00,0x00,0x50,0x00,0x00,0x51,0x00,0x00,0x51,0x00,0x00,0x52,0x00,0x00,0x52,0x00,0x00,0x53,0x00,0x00,0x53,0x00,0x00,0x54,0x00,0x00,0x54,0x00,0x00,0x55,0x00,0x00,0x55,0x00,0x00,0x56,0x00,0x00,0x56,0x00,0x00,0x57,0x00,0x00,0x57,0x00,0x00,0x58,0x00,0x00,0x58,0x00,0x00,0x59,0x00,0x00,0x59,0x00,0x00,0x5a,0x00,0x00,0x5a,0x00,0x00,0x5a,0x00,0x00,0x5b,0x00,0x00,0x5b,0x00,0x00,0x5c,0x00,0x00,0x5c,0x00,0x00,0x5d,0x00,0x00,0x5d,0x00,0x00,0x5e,0x00,0x00,0x5e,0x00,0x00,0x5f,0x00,0x00,0x5f,0x00,0x00,0x60,0x00,0x00,0x60,0x00,0x00,0x61,0x00,0x00,0x61,0x00,0x00,0x62,0x00,0x00,0x62,0x00,0x00,0x63,0x00,0x00,0x63,0x00,0x00,0x64,0x00,0x00,0x64,0x00,0x00,0x65,0x00,0x00,0x65,0x00,0x00,0x66,0x00,0x00,0x66,0x00,0x00,0x67,0x00,0x00,0x67,0x00,0x00,0x68,0x00,0x00,0x68,0x00,0x00,0x69,0x00,0x00,0x69,0x00,0x00,0x6a,0x00,0x00,0x6a,0x00,0x00,0x6b,0x00,0x00,0x6b,0x00,0x00,0x6c,0x00,0x00,0x6c,0x00,0x00,0x6d,0x00,0x00,0x6d,0x00,0x00,0x6e,0x00,0x00,0x6e,0x00,0x00,0x6f,0x00,0x00,0x6f,0x00,0x00,0x70,0x00,0x00,0x70,0x00,0x00,0x71,0x00,0x00,0x71,0x00,0x00,0x72,0x00,0x00,0x72,0x00,0x00,0x73,0x00,0x00,0x73,0x00,0x00,0x74,0x00,0x00,0x74,0x00,0x00,0x75,0x00,0x00,0x75,0x00,0x00,0x76,0x00,0x00,0x76,0x00,0x00,0x77,0x00,0x00,0x77,0x00,0x00,0x78,0x00,0x00,0x78,0x00,0x00,0x79,0x00,0x00,0x79,0x00,0x00,0x7a,0x00,0x00,0x7a,0x00,0x00,0x7b,0x00,0x00,0x7b,0x00,0x00,0x7c,0x00,0x00,0x7c,0x00,0x00,0x7d,0x00,0x00,0x7d,0x00,0x00,0x7e,0x00,0x00,0x7e,0x00,0x00,0x7f,0x00,0x00,0x80,0x00}; - static constexpr std::array L15 = {0x00,0x00,0x00,0x00,0x01,0x02,0x00,0x01,0x04,0x01,0x02,0x06,0x01,0x03,0x08,0x01,0x03,0x0a,0x01,0x04,0x0b,0x01,0x04,0x0d,0x02,0x05,0x0f,0x02,0x06,0x11,0x02,0x06,0x13,0x02,0x07,0x14,0x02,0x07,0x16,0x02,0x08,0x18,0x03,0x08,0x19,0x03,0x09,0x1b,0x03,0x09,0x1c,0x03,0x0a,0x1e,0x03,0x0a,0x1f,0x03,0x0b,0x21,0x03,0x0b,0x22,0x04,0x0c,0x23,0x04,0x0c,0x25,0x04,0x0d,0x26,0x04,0x0d,0x27,0x04,0x0d,0x28,0x04,0x0e,0x29,0x04,0x0e,0x2b,0x04,0x0e,0x2c,0x04,0x0f,0x2d,0x05,0x0f,0x2e,0x05,0x0f,0x2f,0x05,0x10,0x30,0x05,0x10,0x31,0x05,0x11,0x32,0x05,0x11,0x33,0x05,0x11,0x34,0x05,0x11,0x35,0x05,0x12,0x36,0x05,0x12,0x37,0x06,0x12,0x38,0x06,0x13,0x39,0x06,0x13,0x39,0x06,0x13,0x3a,0x06,0x14,0x3b,0x06,0x14,0x3c,0x06,0x14,0x3d,0x06,0x14,0x3e,0x06,0x15,0x3e,0x06,0x15,0x3f,0x06,0x15,0x40,0x06,0x15,0x41,0x07,0x16,0x42,0x07,0x16,0x43,0x07,0x16,0x43,0x07,0x17,0x44,0x07,0x17,0x45,0x07,0x17,0x46,0x07,0x17,0x47,0x07,0x18,0x48,0x07,0x18,0x48,0x07,0x18,0x49,0x07,0x18,0x4a,0x07,0x19,0x4b,0x08,0x19,0x4c,0x08,0x19,0x4d,0x08,0x1a,0x4e,0x08,0x1a,0x4e,0x08,0x1a,0x4f,0x08,0x1a,0x50,0x08,0x1b,0x51,0x08,0x1b,0x52,0x08,0x1b,0x53,0x08,0x1c,0x53,0x08,0x1c,0x54,0x09,0x1c,0x55,0x09,0x1c,0x56,0x09,0x1d,0x57,0x09,0x1d,0x58,0x09,0x1d,0x59,0x09,0x1e,0x5a,0x09,0x1e,0x5a,0x09,0x1e,0x5b,0x09,0x1e,0x5c,0x09,0x1f,0x5d,0x09,0x1f,0x5e,0x09,0x1f,0x5f,0x0a,0x20,0x60,0x0a,0x20,0x60,0x0a,0x20,0x61,0x0a,0x20,0x62,0x0a,0x21,0x63,0x0a,0x21,0x64,0x0a,0x21,0x65,0x0a,0x22,0x66,0x0a,0x22,0x67,0x0a,0x22,0x67,0x0a,0x22,0x68,0x0b,0x23,0x69,0x0b,0x23,0x6a,0x0b,0x23,0x6b,0x0b,0x24,0x6c,0x0b,0x24,0x6d,0x0b,0x24,0x6e,0x0b,0x24,0x6f,0x0b,0x25,0x6f,0x0b,0x25,0x70,0x0b,0x25,0x71,0x0b,0x26,0x72,0x0c,0x26,0x73,0x0c,0x26,0x74,0x0c,0x27,0x75,0x0c,0x27,0x76,0x0c,0x27,0x77,0x0c,0x27,0x77,0x0c,0x28,0x78,0x0c,0x28,0x79,0x0c,0x28,0x7a,0x0c,0x29,0x7b,0x0c,0x29,0x7c,0x0c,0x29,0x7d,0x0d,0x2a,0x7e,0x0d,0x2a,0x7f,0x0d,0x2a,0x80,0x0d,0x2a,0x81,0x0d,0x2b,0x81,0x0d,0x2b,0x82,0x0d,0x2b,0x83,0x0d,0x2c,0x84,0x0d,0x2c,0x85,0x0d,0x2c,0x86,0x0d,0x2d,0x87,0x0e,0x2d,0x88,0x0e,0x2d,0x89,0x0e,0x2d,0x8a,0x0e,0x2e,0x8b,0x0e,0x2e,0x8c,0x0e,0x2e,0x8c,0x0e,0x2f,0x8d,0x0e,0x2f,0x8e,0x0e,0x2f,0x8f,0x0e,0x30,0x90,0x0f,0x30,0x91,0x0f,0x30,0x92,0x0f,0x30,0x93,0x0f,0x31,0x94,0x0f,0x31,0x95,0x0f,0x31,0x96,0x0f,0x32,0x97,0x0f,0x32,0x98,0x0f,0x32,0x98,0x0f,0x33,0x99,0x0f,0x33,0x9a,0x10,0x33,0x9b,0x10,0x34,0x9c,0x10,0x34,0x9d,0x10,0x34,0x9e,0x10,0x34,0x9f,0x10,0x35,0xa0,0x10,0x35,0xa1,0x10,0x35,0xa2,0x10,0x36,0xa3,0x10,0x36,0xa4,0x10,0x36,0xa5,0x11,0x37,0xa6,0x11,0x37,0xa7,0x11,0x37,0xa8,0x11,0x38,0xa8,0x11,0x38,0xa9,0x11,0x38,0xaa,0x11,0x39,0xab,0x11,0x39,0xac,0x11,0x39,0xad,0x11,0x39,0xae,0x12,0x3a,0xaf,0x12,0x3a,0xb0,0x12,0x3a,0xb1,0x12,0x3b,0xb2,0x12,0x3b,0xb3,0x12,0x3b,0xb4,0x12,0x3c,0xb5,0x12,0x3c,0xb6,0x12,0x3c,0xb7,0x12,0x3d,0xb8,0x12,0x3d,0xb9,0x13,0x3d,0xba,0x13,0x3e,0xbb,0x13,0x3e,0xbc,0x13,0x3e,0xbd,0x13,0x3f,0xbe,0x13,0x3f,0xbe,0x13,0x3f,0xbf,0x13,0x40,0xc0,0x13,0x40,0xc1,0x13,0x40,0xc2,0x14,0x40,0xc3,0x14,0x41,0xc4,0x14,0x41,0xc5,0x14,0x41,0xc6,0x14,0x42,0xc7,0x14,0x42,0xc8,0x14,0x42,0xc9,0x14,0x43,0xca,0x14,0x43,0xcb,0x14,0x43,0xcc,0x15,0x44,0xcd,0x15,0x44,0xce,0x15,0x44,0xcf,0x15,0x45,0xd0,0x15,0x45,0xd1,0x15,0x45,0xd2,0x15,0x46,0xd3,0x15,0x46,0xd4,0x15,0x46,0xd5,0x15,0x47,0xd6,0x15,0x47,0xd7,0x16,0x47,0xd8,0x16,0x48,0xd9,0x16,0x48,0xda,0x16,0x48,0xdb,0x16,0x49,0xdc,0x16,0x49,0xdd,0x16,0x49,0xde,0x16,0x4a,0xdf,0x16,0x4a,0xe0,0x16,0x4a,0xe1,0x17,0x4b,0xe2,0x17,0x4b,0xe3,0x17,0x4b,0xe4,0x17,0x4c,0xe5,0x17,0x4c,0xe6,0x17,0x4c,0xe7,0x17,0x4c,0xe8,0x17,0x4d,0xe9,0x17,0x4d,0xea,0x17,0x4d,0xeb,0x18,0x4e,0xec,0x18,0x4e,0xed,0x18,0x4e,0xee,0x18,0x4f,0xef,0x18,0x4f,0xf0,0x18,0x4f,0xf1,0x18,0x50,0xf2,0x18,0x50,0xf3,0x18,0x50,0xf4,0x18,0x51,0xf5,0x19,0x51,0xf6,0x19,0x51,0xf7,0x19,0x52,0xf8,0x19,0x52,0xf9,0x19,0x52,0xfa,0x19,0x53,0xfb,0x19,0x53,0xfc,0x19,0x53,0xfd,0x19,0x54,0xfe,0x1a,0x54,0xff}; - static constexpr std::array L16 = {0x1b,0x1b,0x1b,0x1d,0x1b,0x20,0x1f,0x1b,0x24,0x20,0x1b,0x29,0x22,0x1b,0x2d,0x23,0x1b,0x31,0x24,0x1b,0x35,0x25,0x1b,0x3a,0x26,0x1b,0x3e,0x27,0x1b,0x42,0x27,0x1a,0x46,0x28,0x1a,0x4a,0x28,0x1a,0x4f,0x29,0x1a,0x53,0x29,0x1a,0x57,0x29,0x1a,0x5b,0x29,0x19,0x5f,0x29,0x19,0x63,0x29,0x19,0x66,0x29,0x19,0x6a,0x29,0x19,0x6e,0x28,0x19,0x72,0x28,0x19,0x75,0x27,0x19,0x79,0x27,0x19,0x7c,0x26,0x19,0x80,0x25,0x19,0x83,0x25,0x19,0x86,0x24,0x1a,0x89,0x23,0x1a,0x8c,0x22,0x1a,0x8f,0x21,0x1a,0x92,0x20,0x1b,0x95,0x1f,0x1b,0x98,0x1d,0x1c,0x9a,0x1c,0x1d,0x9d,0x1b,0x1d,0x9f,0x19,0x1e,0xa2,0x18,0x1f,0xa4,0x17,0x20,0xa6,0x15,0x20,0xa8,0x14,0x21,0xaa,0x12,0x22,0xac,0x11,0x23,0xad,0x0f,0x25,0xaf,0x0e,0x26,0xb0,0x0d,0x27,0xb1,0x0c,0x28,0xb2,0x0b,0x29,0xb3,0x0a,0x2b,0xb4,0x09,0x2c,0xb4,0x09,0x2e,0xb5,0x08,0x2f,0xb5,0x08,0x30,0xb6,0x08,0x32,0xb6,0x08,0x33,0xb6,0x07,0x35,0xb7,0x07,0x36,0xb7,0x07,0x37,0xb7,0x07,0x39,0xb7,0x07,0x3a,0xb8,0x07,0x3c,0xb8,0x07,0x3d,0xb8,0x07,0x3e,0xb8,0x07,0x40,0xb8,0x07,0x41,0xb8,0x07,0x42,0xb8,0x07,0x44,0xb8,0x07,0x45,0xb8,0x07,0x46,0xb8,0x07,0x48,0xb7,0x07,0x49,0xb7,0x07,0x4b,0xb7,0x07,0x4c,0xb7,0x07,0x4d,0xb6,0x07,0x4f,0xb6,0x07,0x50,0xb5,0x07,0x51,0xb5,0x07,0x53,0xb4,0x07,0x54,0xb4,0x07,0x56,0xb3,0x07,0x57,0xb2,0x07,0x58,0xb1,0x07,0x5a,0xb0,0x07,0x5b,0xaf,0x06,0x5d,0xae,0x06,0x5e,0xad,0x06,0x5f,0xac,0x06,0x61,0xab,0x06,0x62,0xaa,0x07,0x64,0xa8,0x08,0x65,0xa7,0x0a,0x66,0xa5,0x0c,0x68,0xa4,0x0e,0x69,0xa2,0x10,0x6a,0xa0,0x12,0x6c,0x9f,0x14,0x6d,0x9d,0x16,0x6e,0x9b,0x18,0x6f,0x99,0x1a,0x71,0x97,0x1b,0x72,0x95,0x1d,0x73,0x93,0x1f,0x74,0x91,0x20,0x76,0x8f,0x22,0x77,0x8d,0x23,0x78,0x8b,0x24,0x79,0x89,0x26,0x7b,0x87,0x27,0x7c,0x85,0x28,0x7d,0x82,0x29,0x7e,0x80,0x2a,0x80,0x7e,0x2b,0x81,0x7b,0x2c,0x82,0x79,0x2c,0x83,0x77,0x2d,0x84,0x74,0x2e,0x86,0x72,0x2e,0x87,0x6f,0x2f,0x88,0x6d,0x2f,0x89,0x6a,0x30,0x8b,0x67,0x30,0x8c,0x65,0x30,0x8d,0x62,0x30,0x8e,0x5f,0x31,0x8f,0x5c,0x31,0x91,0x5a,0x31,0x92,0x57,0x32,0x93,0x55,0x32,0x94,0x53,0x33,0x95,0x50,0x34,0x96,0x4e,0x34,0x97,0x4c,0x35,0x98,0x4a,0x36,0x99,0x48,0x37,0x9a,0x46,0x38,0x9b,0x44,0x3a,0x9c,0x42,0x3b,0x9d,0x40,0x3c,0x9e,0x3e,0x3d,0x9f,0x3c,0x3f,0xa0,0x3a,0x40,0xa1,0x38,0x42,0xa2,0x37,0x44,0xa3,0x35,0x45,0xa4,0x33,0x47,0xa5,0x31,0x49,0xa6,0x30,0x4a,0xa7,0x2e,0x4c,0xa8,0x2c,0x4e,0xa9,0x2b,0x50,0xaa,0x29,0x52,0xab,0x28,0x54,0xac,0x26,0x56,0xac,0x24,0x58,0xad,0x23,0x5a,0xae,0x21,0x5c,0xaf,0x20,0x5e,0xb0,0x1e,0x60,0xb1,0x1d,0x62,0xb1,0x1b,0x65,0xb2,0x1a,0x67,0xb3,0x18,0x69,0xb4,0x17,0x6b,0xb5,0x15,0x6e,0xb5,0x14,0x70,0xb6,0x12,0x72,0xb7,0x11,0x75,0xb8,0x0f,0x77,0xb8,0x0e,0x79,0xb9,0x0c,0x7c,0xba,0x0b,0x7e,0xbb,0x09,0x80,0xbb,0x08,0x83,0xbc,0x07,0x85,0xbd,0x06,0x88,0xbd,0x05,0x8a,0xbe,0x04,0x8d,0xbf,0x04,0x8f,0xbf,0x03,0x92,0xc0,0x03,0x94,0xc1,0x03,0x97,0xc1,0x02,0x99,0xc2,0x02,0x9c,0xc3,0x02,0x9e,0xc3,0x02,0xa1,0xc4,0x03,0xa3,0xc5,0x03,0xa5,0xc5,0x03,0xa8,0xc6,0x03,0xaa,0xc7,0x03,0xac,0xc7,0x04,0xaf,0xc8,0x04,0xb1,0xc8,0x05,0xb3,0xc9,0x05,0xb6,0xca,0x06,0xb8,0xca,0x07,0xba,0xcb,0x08,0xbc,0xcc,0x08,0xbe,0xcc,0x09,0xc0,0xcd,0x0b,0xc3,0xce,0x0c,0xc5,0xce,0x0d,0xc7,0xcf,0x0e,0xc9,0xd0,0x0f,0xcb,0xd0,0x10,0xcd,0xd1,0x12,0xcf,0xd2,0x13,0xd1,0xd2,0x14,0xd3,0xd3,0x16,0xd5,0xd4,0x17,0xd7,0xd5,0x18,0xd9,0xd5,0x1a,0xda,0xd6,0x1b,0xdc,0xd7,0x1d,0xde,0xd7,0x1e,0xe0,0xd8,0x20,0xe2,0xd9,0x21,0xe3,0xda,0x23,0xe5,0xda,0x24,0xe6,0xdb,0x26,0xe8,0xdc,0x28,0xea,0xdd,0x2a,0xeb,0xde,0x2b,0xec,0xdf,0x2d,0xee,0xdf,0x2f,0xef,0xe0,0x31,0xf0,0xe1,0x33,0xf1,0xe2,0x35,0xf2,0xe3,0x38,0xf3,0xe4,0x3a,0xf4,0xe5,0x3d,0xf5,0xe6,0x3f,0xf5,0xe7,0x42,0xf6,0xe8,0x46,0xf7,0xe9,0x49,0xf7,0xea,0x4e,0xf8,0xeb,0x52,0xf9,0xec,0x57,0xfa,0xed,0x5c,0xfa,0xee,0x62,0xfb,0xef,0x68,0xfc,0xf0,0x6f,0xfc,0xf1,0x76,0xfd,0xf2,0x7d,0xfe,0xf3,0x85,0xfe,0xf3,0x8d,0xff,0xf4,0x96,0xff,0xf5,0xa0,0xff,0xf6,0xaa,0xff,0xf6,0xb5,0xff,0xf7,0xc1,0xfe,0xf8,0xcd,0xfd,0xf8,0xdb,0xfc,0xf9,0xe9,0xf9,0xf9,0xf9}; - static constexpr std::array L17 = {0xff,0xff,0xff,0xff,0xfe,0xfc,0xfe,0xfd,0xf9,0xfe,0xfd,0xf7,0xfd,0xfc,0xf4,0xfd,0xfb,0xf1,0xfc,0xfa,0xee,0xfc,0xfa,0xeb,0xfb,0xf9,0xe9,0xfb,0xf8,0xe6,0xfa,0xf7,0xe3,0xfa,0xf7,0xe0,0xf9,0xf6,0xdd,0xf8,0xf5,0xdb,0xf8,0xf4,0xd8,0xf7,0xf3,0xd5,0xf7,0xf3,0xd2,0xf6,0xf2,0xcf,0xf6,0xf1,0xcd,0xf5,0xf0,0xca,0xf4,0xf0,0xc7,0xf4,0xef,0xc4,0xf3,0xee,0xc2,0xf2,0xed,0xbf,0xf2,0xec,0xbd,0xf2,0xeb,0xbb,0xf2,0xea,0xba,0xf2,0xe9,0xb8,0xf3,0xe8,0xb6,0xf3,0xe7,0xb4,0xf3,0xe6,0xb3,0xf3,0xe5,0xb1,0xf3,0xe4,0xaf,0xf3,0xe3,0xae,0xf3,0xe2,0xac,0xf3,0xe1,0xaa,0xf3,0xe0,0xa9,0xf2,0xdf,0xa7,0xf2,0xde,0xa5,0xf2,0xdd,0xa4,0xf2,0xdc,0xa2,0xf2,0xdb,0xa0,0xf2,0xda,0x9f,0xf2,0xd9,0x9d,0xf2,0xd7,0x9c,0xf2,0xd6,0x9a,0xf2,0xd5,0x98,0xf2,0xd4,0x97,0xf2,0xd3,0x96,0xf2,0xd2,0x94,0xf2,0xd1,0x93,0xf3,0xd0,0x92,0xf3,0xcf,0x91,0xf3,0xcd,0x90,0xf3,0xcc,0x8e,0xf3,0xcb,0x8d,0xf3,0xca,0x8c,0xf3,0xc9,0x8b,0xf3,0xc8,0x8a,0xf3,0xc6,0x88,0xf4,0xc5,0x87,0xf4,0xc4,0x86,0xf4,0xc3,0x85,0xf4,0xc2,0x84,0xf4,0xc1,0x83,0xf4,0xbf,0x81,0xf4,0xbe,0x80,0xf4,0xbd,0x7f,0xf4,0xbc,0x7e,0xf4,0xbb,0x7d,0xf4,0xba,0x7c,0xf4,0xb8,0x7b,0xf4,0xb7,0x7a,0xf4,0xb6,0x7a,0xf5,0xb5,0x79,0xf5,0xb3,0x78,0xf5,0xb2,0x77,0xf5,0xb1,0x77,0xf5,0xb0,0x76,0xf5,0xae,0x75,0xf5,0xad,0x75,0xf5,0xac,0x74,0xf5,0xab,0x73,0xf5,0xaa,0x73,0xf5,0xa8,0x72,0xf5,0xa7,0x71,0xf5,0xa6,0x70,0xf5,0xa4,0x70,0xf5,0xa3,0x6f,0xf5,0xa2,0x6e,0xf5,0xa1,0x6e,0xf5,0x9f,0x6d,0xf5,0x9e,0x6c,0xf5,0x9d,0x6c,0xf5,0x9c,0x6c,0xf5,0x9a,0x6b,0xf5,0x99,0x6b,0xf5,0x98,0x6b,0xf5,0x97,0x6b,0xf5,0x95,0x6a,0xf5,0x94,0x6a,0xf5,0x93,0x6a,0xf5,0x91,0x6a,0xf5,0x90,0x6a,0xf4,0x8f,0x69,0xf4,0x8d,0x69,0xf4,0x8c,0x69,0xf4,0x8b,0x69,0xf4,0x8a,0x69,0xf4,0x88,0x68,0xf4,0x87,0x68,0xf4,0x86,0x68,0xf4,0x84,0x68,0xf3,0x83,0x67,0xf3,0x81,0x67,0xf3,0x80,0x67,0xf3,0x7f,0x67,0xf3,0x7e,0x67,0xf2,0x7c,0x67,0xf2,0x7b,0x67,0xf2,0x7a,0x68,0xf2,0x78,0x68,0xf1,0x77,0x68,0xf1,0x76,0x68,0xf1,0x74,0x68,0xf0,0x73,0x68,0xf0,0x72,0x69,0xf0,0x70,0x69,0xef,0x6f,0x69,0xef,0x6e,0x69,0xef,0x6c,0x69,0xee,0x6b,0x6a,0xee,0x6a,0x6a,0xee,0x68,0x6a,0xed,0x67,0x6a,0xed,0x66,0x6a,0xed,0x64,0x6a,0xec,0x63,0x6a,0xec,0x61,0x6b,0xec,0x60,0x6b,0xeb,0x5f,0x6b,0xea,0x5d,0x6c,0xea,0x5c,0x6c,0xe9,0x5b,0x6d,0xe8,0x5a,0x6d,0xe8,0x58,0x6e,0xe7,0x57,0x6e,0xe7,0x56,0x6e,0xe6,0x55,0x6f,0xe5,0x53,0x6f,0xe5,0x52,0x70,0xe4,0x51,0x70,0xe3,0x4f,0x71,0xe3,0x4e,0x71,0xe2,0x4d,0x72,0xe1,0x4b,0x72,0xe1,0x4a,0x72,0xe0,0x49,0x73,0xe0,0x47,0x73,0xdf,0x46,0x74,0xde,0x44,0x74,0xde,0x43,0x75,0xdd,0x41,0x75,0xdc,0x40,0x75,0xdb,0x3f,0x76,0xda,0x3e,0x77,0xd9,0x3d,0x77,0xd8,0x3c,0x78,0xd7,0x3b,0x79,0xd6,0x3a,0x79,0xd5,0x38,0x7a,0xd4,0x37,0x7a,0xd3,0x36,0x7b,0xd2,0x35,0x7c,0xd1,0x34,0x7c,0xd0,0x33,0x7d,0xcf,0x32,0x7d,0xce,0x30,0x7e,0xcd,0x2f,0x7f,0xcc,0x2e,0x7f,0xcb,0x2d,0x80,0xca,0x2b,0x80,0xc9,0x2a,0x81,0xc8,0x29,0x82,0xc7,0x28,0x82,0xc5,0x26,0x83,0xc4,0x25,0x83,0xc3,0x25,0x84,0xc1,0x24,0x85,0xc0,0x23,0x85,0xbe,0x23,0x86,0xbd,0x22,0x87,0xbc,0x22,0x87,0xba,0x21,0x88,0xb9,0x20,0x89,0xb7,0x20,0x89,0xb6,0x1f,0x8a,0xb4,0x1f,0x8a,0xb3,0x1e,0x8b,0xb1,0x1d,0x8c,0xb0,0x1d,0x8c,0xae,0x1c,0x8d,0xad,0x1c,0x8e,0xab,0x1b,0x8e,0xaa,0x1b,0x8f,0xa8,0x1a,0x90,0xa7,0x19,0x90,0xa5,0x19,0x91,0xa3,0x18,0x92,0xa2,0x18,0x92,0xa0,0x18,0x93,0x9e,0x19,0x93,0x9c,0x19,0x94,0x9a,0x1a,0x94,0x98,0x1a,0x95,0x96,0x1a,0x96,0x94,0x1b,0x96,0x92,0x1b,0x97,0x90,0x1b,0x97,0x8e,0x1c,0x98,0x8c,0x1c,0x99,0x89,0x1c,0x99,0x87,0x1d,0x9a,0x85,0x1d,0x9a,0x83,0x1d,0x9b,0x81,0x1d,0x9b,0x7f,0x1e,0x9c,0x7c,0x1e,0x9d,0x7a,0x1e,0x9d,0x78,0x1e,0x9e,0x75,0x1f,0x9e,0x73,0x1f,0x9f,0x70,0x1f,0x9f,0x6e,0x20,0xa0,0x6b,0x21,0xa0,0x68,0x21,0xa0,0x65,0x22,0xa1,0x62,0x23,0xa1,0x5f,0x23,0xa2,0x5c,0x24,0xa2,0x59,0x24,0xa2,0x55,0x25,0xa3,0x52,0x25,0xa3,0x4e,0x26,0xa3,0x4b,0x26,0xa4,0x47,0x27,0xa4,0x43,0x27,0xa4,0x3e,0x27,0xa5,0x3a,0x28,0xa5,0x34,0x28,0xa6,0x2f,0x29,0xa6,0x29,0x29,0xa6,0x21,0x29,0xa7,0x18,0x2a,0xa7,0x0a,0x2a,0xa7,0x00,0x2a,0xa8}; - static constexpr std::array L18 = {0xff,0xff,0xff,0xfe,0xff,0xfc,0xfe,0xfe,0xfa,0xfd,0xfe,0xf7,0xfd,0xfd,0xf5,0xfc,0xfd,0xf2,0xfb,0xfc,0xef,0xfb,0xfc,0xed,0xfa,0xfb,0xea,0xfa,0xfb,0xe8,0xf9,0xfb,0xe5,0xf8,0xfa,0xe3,0xf8,0xfa,0xe0,0xf7,0xf9,0xdd,0xf6,0xf9,0xdb,0xf6,0xf8,0xd8,0xf5,0xf8,0xd6,0xf4,0xf7,0xd3,0xf4,0xf7,0xd0,0xf3,0xf7,0xce,0xf2,0xf6,0xcb,0xf2,0xf6,0xc9,0xf1,0xf5,0xc6,0xf0,0xf5,0xc4,0xf0,0xf4,0xc2,0xf0,0xf4,0xc0,0xef,0xf3,0xbf,0xef,0xf2,0xbd,0xef,0xf2,0xbc,0xef,0xf1,0xba,0xee,0xf0,0xb9,0xee,0xf0,0xb7,0xee,0xef,0xb6,0xee,0xee,0xb4,0xed,0xee,0xb3,0xed,0xed,0xb1,0xed,0xec,0xaf,0xec,0xec,0xae,0xec,0xeb,0xac,0xec,0xea,0xab,0xec,0xea,0xa9,0xeb,0xe9,0xa8,0xeb,0xe8,0xa6,0xeb,0xe8,0xa5,0xea,0xe7,0xa3,0xea,0xe6,0xa2,0xea,0xe6,0xa0,0xea,0xe5,0x9f,0xea,0xe4,0x9d,0xe9,0xe4,0x9c,0xe9,0xe3,0x9b,0xe9,0xe2,0x99,0xe9,0xe1,0x98,0xe9,0xe1,0x97,0xe9,0xe0,0x96,0xe9,0xdf,0x94,0xe9,0xdf,0x93,0xe8,0xde,0x92,0xe8,0xdd,0x90,0xe8,0xdc,0x8f,0xe8,0xdc,0x8e,0xe8,0xdb,0x8c,0xe8,0xda,0x8b,0xe8,0xda,0x8a,0xe7,0xd9,0x88,0xe7,0xd8,0x87,0xe7,0xd7,0x86,0xe7,0xd7,0x84,0xe7,0xd6,0x83,0xe7,0xd5,0x82,0xe6,0xd5,0x80,0xe6,0xd4,0x7f,0xe6,0xd3,0x7e,0xe6,0xd2,0x7d,0xe6,0xd1,0x7c,0xe6,0xd1,0x7b,0xe6,0xd0,0x79,0xe6,0xcf,0x78,0xe6,0xce,0x77,0xe6,0xce,0x76,0xe6,0xcd,0x75,0xe6,0xcc,0x74,0xe6,0xcb,0x72,0xe6,0xcb,0x71,0xe6,0xca,0x70,0xe6,0xc9,0x6f,0xe5,0xc8,0x6e,0xe5,0xc8,0x6d,0xe5,0xc7,0x6b,0xe5,0xc6,0x6a,0xe5,0xc5,0x69,0xe5,0xc4,0x68,0xe5,0xc4,0x67,0xe5,0xc3,0x66,0xe5,0xc2,0x65,0xe5,0xc1,0x64,0xe5,0xc1,0x63,0xe5,0xc0,0x62,0xe5,0xbf,0x61,0xe5,0xbe,0x60,0xe5,0xbd,0x5f,0xe5,0xbd,0x5e,0xe5,0xbc,0x5c,0xe4,0xbb,0x5b,0xe4,0xba,0x5a,0xe4,0xb9,0x59,0xe4,0xb9,0x58,0xe4,0xb8,0x57,0xe4,0xb7,0x56,0xe4,0xb6,0x55,0xe4,0xb5,0x54,0xe4,0xb5,0x53,0xe4,0xb4,0x52,0xe4,0xb3,0x51,0xe4,0xb2,0x50,0xe4,0xb1,0x4f,0xe4,0xb0,0x4e,0xe4,0xb0,0x4d,0xe4,0xaf,0x4c,0xe4,0xae,0x4c,0xe4,0xad,0x4b,0xe4,0xac,0x4a,0xe4,0xab,0x49,0xe4,0xab,0x48,0xe4,0xaa,0x47,0xe4,0xa9,0x46,0xe4,0xa8,0x45,0xe3,0xa7,0x45,0xe3,0xa6,0x44,0xe3,0xa6,0x43,0xe3,0xa5,0x42,0xe3,0xa4,0x41,0xe3,0xa3,0x40,0xe3,0xa2,0x3f,0xe3,0xa1,0x3e,0xe3,0xa1,0x3e,0xe3,0xa0,0x3d,0xe3,0x9f,0x3c,0xe3,0x9e,0x3b,0xe3,0x9d,0x3a,0xe3,0x9c,0x39,0xe3,0x9b,0x39,0xe3,0x9b,0x38,0xe3,0x9a,0x37,0xe3,0x99,0x37,0xe3,0x98,0x36,0xe3,0x97,0x35,0xe3,0x96,0x34,0xe3,0x95,0x34,0xe3,0x94,0x33,0xe2,0x93,0x32,0xe2,0x93,0x32,0xe2,0x92,0x31,0xe2,0x91,0x30,0xe2,0x90,0x2f,0xe2,0x8f,0x2f,0xe2,0x8e,0x2e,0xe2,0x8d,0x2d,0xe2,0x8c,0x2d,0xe2,0x8b,0x2c,0xe2,0x8b,0x2b,0xe2,0x8a,0x2a,0xe2,0x89,0x2a,0xe2,0x88,0x29,0xe2,0x87,0x29,0xe2,0x86,0x28,0xe2,0x85,0x28,0xe1,0x84,0x27,0xe1,0x83,0x27,0xe1,0x82,0x26,0xe1,0x81,0x26,0xe1,0x80,0x25,0xe1,0x7f,0x25,0xe1,0x7f,0x24,0xe1,0x7e,0x24,0xe1,0x7d,0x23,0xe1,0x7c,0x23,0xe1,0x7b,0x22,0xe1,0x7a,0x22,0xe1,0x79,0x21,0xe1,0x78,0x21,0xe0,0x77,0x20,0xe0,0x76,0x20,0xe0,0x75,0x1f,0xe0,0x74,0x1f,0xe0,0x73,0x1e,0xe0,0x72,0x1e,0xe0,0x71,0x1e,0xe0,0x70,0x1d,0xe0,0x6f,0x1d,0xe0,0x6e,0x1d,0xe0,0x6d,0x1d,0xdf,0x6c,0x1c,0xdf,0x6b,0x1c,0xdf,0x6a,0x1c,0xdf,0x69,0x1c,0xdf,0x68,0x1b,0xdf,0x67,0x1b,0xdf,0x66,0x1b,0xdf,0x65,0x1b,0xdf,0x64,0x1b,0xde,0x63,0x1a,0xde,0x62,0x1a,0xde,0x61,0x1a,0xde,0x60,0x1a,0xde,0x5f,0x19,0xde,0x5d,0x19,0xde,0x5c,0x19,0xde,0x5b,0x19,0xdd,0x5a,0x19,0xdd,0x59,0x19,0xdd,0x58,0x19,0xdd,0x57,0x19,0xdd,0x56,0x19,0xdd,0x55,0x19,0xdd,0x53,0x19,0xdc,0x52,0x19,0xdc,0x51,0x19,0xdc,0x50,0x19,0xdc,0x4f,0x19,0xdc,0x4e,0x19,0xdc,0x4c,0x19,0xdb,0x4b,0x19,0xdb,0x4a,0x19,0xdb,0x49,0x19,0xdb,0x47,0x19,0xdb,0x46,0x19,0xdb,0x45,0x19,0xda,0x43,0x19,0xda,0x42,0x19,0xda,0x41,0x19,0xda,0x3f,0x19,0xda,0x3e,0x19,0xda,0x3d,0x19,0xd9,0x3b,0x1a,0xd9,0x3a,0x1a,0xd9,0x38,0x1a,0xd9,0x37,0x1a,0xd9,0x35,0x1a,0xd8,0x34,0x1b,0xd8,0x32,0x1b,0xd8,0x30,0x1b,0xd8,0x2f,0x1b,0xd7,0x2d,0x1b,0xd7,0x2b,0x1b,0xd7,0x29,0x1c,0xd7,0x27,0x1c,0xd7,0x25,0x1c,0xd6,0x23,0x1c,0xd6,0x21,0x1c,0xd6,0x1f,0x1c,0xd6,0x1c,0x1d,0xd5,0x19,0x1d,0xd5,0x16,0x1d,0xd5,0x13,0x1d,0xd5,0x0f,0x1d}; - static constexpr std::array L19 = {0xff,0xff,0xff,0xfe,0xff,0xff,0xfc,0xfe,0xff,0xfb,0xfe,0xff,0xfa,0xfd,0xff,0xf9,0xfd,0xfe,0xf7,0xfc,0xfe,0xf6,0xfc,0xfe,0xf5,0xfb,0xfe,0xf4,0xfb,0xfe,0xf2,0xfa,0xfe,0xf1,0xfa,0xfe,0xf0,0xf9,0xfe,0xef,0xf9,0xfe,0xed,0xf8,0xfe,0xec,0xf8,0xfd,0xeb,0xf7,0xfd,0xe9,0xf7,0xfd,0xe8,0xf6,0xfd,0xe7,0xf6,0xfd,0xe6,0xf5,0xfd,0xe4,0xf5,0xfd,0xe3,0xf4,0xfd,0xe2,0xf4,0xfd,0xe1,0xf3,0xfd,0xe0,0xf3,0xfd,0xdf,0xf2,0xfd,0xde,0xf1,0xfd,0xdc,0xf1,0xfd,0xdb,0xf0,0xfd,0xda,0xf0,0xfd,0xd9,0xef,0xfd,0xd8,0xee,0xfd,0xd7,0xee,0xfd,0xd6,0xed,0xfd,0xd5,0xed,0xfd,0xd4,0xec,0xfd,0xd3,0xec,0xfd,0xd2,0xeb,0xfd,0xd1,0xea,0xfd,0xd0,0xea,0xfd,0xcf,0xe9,0xfe,0xce,0xe9,0xfe,0xcd,0xe8,0xfe,0xcc,0xe8,0xfe,0xcb,0xe7,0xfe,0xca,0xe6,0xfe,0xc9,0xe6,0xfe,0xc8,0xe5,0xfe,0xc8,0xe4,0xfe,0xc7,0xe4,0xfe,0xc6,0xe3,0xfe,0xc6,0xe2,0xfe,0xc5,0xe2,0xfe,0xc5,0xe1,0xfe,0xc4,0xe0,0xfe,0xc3,0xe0,0xfe,0xc3,0xdf,0xfe,0xc2,0xde,0xfe,0xc1,0xde,0xff,0xc1,0xdd,0xff,0xc0,0xdc,0xff,0xbf,0xdb,0xff,0xbf,0xdb,0xff,0xbe,0xda,0xff,0xbd,0xd9,0xff,0xbd,0xd9,0xff,0xbc,0xd8,0xff,0xbc,0xd7,0xff,0xbb,0xd7,0xff,0xba,0xd6,0xff,0xba,0xd5,0xff,0xba,0xd4,0xff,0xba,0xd4,0xff,0xba,0xd3,0xff,0xba,0xd2,0xff,0xba,0xd1,0xff,0xba,0xd0,0xfe,0xb9,0xd0,0xfe,0xb9,0xcf,0xfe,0xb9,0xce,0xfe,0xb9,0xcd,0xfe,0xb9,0xcc,0xfe,0xb9,0xcc,0xfe,0xb9,0xcb,0xfe,0xb9,0xca,0xfe,0xb8,0xc9,0xfe,0xb8,0xc9,0xfe,0xb8,0xc8,0xfd,0xb8,0xc7,0xfd,0xb8,0xc6,0xfd,0xb8,0xc5,0xfd,0xb8,0xc5,0xfd,0xb8,0xc4,0xfd,0xb8,0xc3,0xfd,0xb8,0xc2,0xfc,0xb9,0xc1,0xfc,0xb9,0xc0,0xfb,0xba,0xbf,0xfb,0xba,0xbe,0xfb,0xba,0xbd,0xfa,0xbb,0xbc,0xfa,0xbb,0xbc,0xfa,0xbb,0xbb,0xf9,0xbc,0xba,0xf9,0xbc,0xb9,0xf8,0xbc,0xb8,0xf8,0xbd,0xb7,0xf8,0xbd,0xb6,0xf7,0xbd,0xb5,0xf7,0xbe,0xb4,0xf7,0xbe,0xb3,0xf6,0xbe,0xb2,0xf6,0xbf,0xb1,0xf5,0xbf,0xb1,0xf5,0xbf,0xb0,0xf5,0xc0,0xaf,0xf4,0xc0,0xae,0xf4,0xc1,0xad,0xf3,0xc2,0xac,0xf2,0xc3,0xab,0xf1,0xc3,0xaa,0xf1,0xc4,0xa9,0xf0,0xc5,0xa8,0xef,0xc5,0xa6,0xee,0xc6,0xa5,0xee,0xc7,0xa4,0xed,0xc7,0xa3,0xec,0xc8,0xa2,0xeb,0xc9,0xa1,0xeb,0xc9,0xa0,0xea,0xca,0x9f,0xe9,0xca,0x9e,0xe8,0xcb,0x9d,0xe8,0xcc,0x9c,0xe7,0xcc,0x9b,0xe6,0xcd,0x9a,0xe5,0xcd,0x99,0xe5,0xce,0x98,0xe4,0xce,0x97,0xe3,0xcf,0x96,0xe2,0xd0,0x95,0xe1,0xd1,0x93,0xe0,0xd1,0x92,0xde,0xd2,0x91,0xdd,0xd3,0x90,0xdc,0xd4,0x8f,0xdb,0xd4,0x8e,0xda,0xd5,0x8d,0xd8,0xd6,0x8b,0xd7,0xd6,0x8a,0xd6,0xd7,0x89,0xd5,0xd8,0x88,0xd4,0xd8,0x87,0xd3,0xd9,0x86,0xd1,0xda,0x84,0xd0,0xda,0x83,0xcf,0xdb,0x82,0xce,0xdc,0x81,0xcd,0xdc,0x80,0xcc,0xdd,0x7e,0xca,0xdd,0x7d,0xc9,0xde,0x7c,0xc8,0xdf,0x7b,0xc7,0xdf,0x7a,0xc5,0xe0,0x78,0xc3,0xe0,0x77,0xc2,0xe1,0x76,0xc0,0xe1,0x75,0xbf,0xe2,0x74,0xbd,0xe2,0x72,0xbb,0xe3,0x71,0xba,0xe3,0x70,0xb8,0xe4,0x6f,0xb7,0xe4,0x6e,0xb5,0xe5,0x6c,0xb4,0xe5,0x6b,0xb2,0xe6,0x6a,0xb0,0xe6,0x68,0xaf,0xe7,0x67,0xad,0xe7,0x66,0xac,0xe8,0x65,0xaa,0xe8,0x63,0xa9,0xe8,0x62,0xa7,0xe9,0x60,0xa6,0xe9,0x5f,0xa4,0xe9,0x5e,0xa2,0xea,0x5d,0xa0,0xea,0x5c,0x9e,0xea,0x5a,0x9d,0xea,0x59,0x9b,0xea,0x58,0x99,0xeb,0x57,0x97,0xeb,0x55,0x95,0xeb,0x54,0x93,0xeb,0x53,0x91,0xeb,0x52,0x8f,0xeb,0x50,0x8d,0xeb,0x4f,0x8c,0xeb,0x4e,0x8a,0xec,0x4d,0x88,0xec,0x4b,0x86,0xec,0x4a,0x84,0xec,0x49,0x82,0xec,0x47,0x80,0xec,0x46,0x7e,0xec,0x44,0x7d,0xec,0x43,0x7b,0xec,0x42,0x79,0xec,0x40,0x77,0xec,0x3f,0x75,0xeb,0x3e,0x73,0xeb,0x3d,0x71,0xeb,0x3c,0x6f,0xea,0x3b,0x6c,0xea,0x3a,0x6a,0xea,0x39,0x68,0xea,0x38,0x66,0xe9,0x37,0x64,0xe9,0x36,0x62,0xe8,0x35,0x60,0xe8,0x34,0x5e,0xe8,0x33,0x5c,0xe7,0x32,0x5a,0xe7,0x31,0x58,0xe7,0x30,0x56,0xe6,0x2e,0x54,0xe6,0x2d,0x52,0xe5,0x2c,0x4f,0xe5,0x2b,0x4d,0xe5,0x2a,0x4b,0xe4,0x28,0x49,0xe4,0x27,0x47,0xe3,0x27,0x45,0xe2,0x27,0x43,0xe1,0x26,0x41,0xe0,0x26,0x3e,0xe0,0x26,0x3c,0xdf,0x26,0x3a,0xde,0x25,0x38,0xdd,0x25,0x35,0xdc,0x25,0x33,0xdb,0x24,0x31,0xdb,0x24,0x2f,0xda,0x24,0x2c,0xd9,0x24,0x2a,0xd8,0x23,0x27,0xd7,0x23,0x25,0xd6,0x23,0x23,0xd5,0x22,0x20,0xd5,0x22,0x1d,0xd4,0x22,0x1b,0xd3,0x22,0x18,0xd2,0x22,0x15,0xd1,0x21,0x12,0xd0,0x21,0x0e}; - static constexpr std::array L20 = {0x30,0x30,0x30,0x31,0x31,0x33,0x32,0x31,0x35,0x33,0x31,0x38,0x34,0x32,0x3b,0x35,0x32,0x3d,0x36,0x32,0x40,0x36,0x33,0x42,0x37,0x33,0x45,0x38,0x33,0x47,0x39,0x34,0x4a,0x39,0x34,0x4c,0x3a,0x34,0x4f,0x3b,0x35,0x51,0x3b,0x35,0x54,0x3c,0x36,0x56,0x3c,0x36,0x59,0x3d,0x36,0x5b,0x3d,0x37,0x5e,0x3e,0x37,0x60,0x3e,0x37,0x63,0x3f,0x38,0x65,0x3f,0x38,0x68,0x40,0x39,0x6a,0x40,0x39,0x6c,0x40,0x39,0x6f,0x41,0x3a,0x71,0x41,0x3a,0x74,0x41,0x3b,0x76,0x42,0x3b,0x78,0x42,0x3c,0x7b,0x42,0x3c,0x7d,0x42,0x3d,0x7f,0x42,0x3d,0x82,0x43,0x3e,0x84,0x43,0x3e,0x86,0x43,0x3f,0x89,0x43,0x3f,0x8b,0x43,0x40,0x8d,0x43,0x40,0x8f,0x43,0x41,0x91,0x43,0x41,0x93,0x43,0x42,0x96,0x43,0x42,0x98,0x43,0x43,0x9a,0x43,0x43,0x9c,0x43,0x44,0x9e,0x43,0x45,0xa0,0x43,0x45,0xa2,0x42,0x46,0xa4,0x42,0x47,0xa6,0x42,0x47,0xa8,0x42,0x48,0xa9,0x42,0x49,0xab,0x42,0x49,0xad,0x41,0x4a,0xaf,0x41,0x4b,0xb0,0x41,0x4b,0xb2,0x41,0x4c,0xb4,0x40,0x4d,0xb5,0x40,0x4e,0xb7,0x40,0x4e,0xb8,0x3f,0x4f,0xba,0x3f,0x50,0xbb,0x3f,0x51,0xbc,0x3e,0x52,0xbe,0x3e,0x53,0xbf,0x3d,0x53,0xc0,0x3d,0x54,0xc1,0x3d,0x55,0xc2,0x3c,0x56,0xc3,0x3c,0x57,0xc4,0x3b,0x58,0xc5,0x3b,0x59,0xc6,0x3a,0x5a,0xc6,0x3a,0x5b,0xc7,0x3a,0x5c,0xc8,0x39,0x5d,0xc8,0x39,0x5e,0xc8,0x38,0x60,0xc9,0x37,0x61,0xc9,0x37,0x62,0xc9,0x36,0x63,0xc9,0x36,0x64,0xc8,0x35,0x65,0xc8,0x34,0x67,0xc8,0x34,0x68,0xc7,0x33,0x69,0xc6,0x32,0x6b,0xc5,0x31,0x6c,0xc4,0x30,0x6e,0xc3,0x2f,0x6f,0xc1,0x2e,0x70,0xc0,0x2d,0x72,0xbe,0x2b,0x74,0xbb,0x2a,0x75,0xb9,0x29,0x77,0xb7,0x27,0x78,0xb5,0x26,0x7a,0xb3,0x25,0x7b,0xb0,0x24,0x7c,0xae,0x24,0x7e,0xac,0x23,0x7f,0xaa,0x22,0x80,0xa8,0x22,0x82,0xa6,0x22,0x83,0xa4,0x22,0x84,0xa1,0x22,0x85,0x9f,0x22,0x86,0x9d,0x23,0x88,0x9b,0x24,0x89,0x99,0x24,0x8a,0x97,0x25,0x8b,0x95,0x26,0x8c,0x93,0x28,0x8d,0x91,0x29,0x8e,0x8f,0x2a,0x8f,0x8d,0x2c,0x90,0x8b,0x2d,0x91,0x89,0x2f,0x92,0x87,0x31,0x93,0x85,0x33,0x94,0x83,0x35,0x95,0x81,0x37,0x96,0x7f,0x39,0x97,0x7d,0x3b,0x98,0x7b,0x3d,0x98,0x79,0x3f,0x99,0x78,0x42,0x9a,0x76,0x44,0x9b,0x74,0x46,0x9c,0x72,0x49,0x9d,0x70,0x4b,0x9d,0x6e,0x4e,0x9e,0x6c,0x50,0x9f,0x6a,0x53,0x9f,0x68,0x55,0xa0,0x67,0x58,0xa1,0x65,0x5b,0xa2,0x63,0x5d,0xa2,0x61,0x60,0xa3,0x5f,0x63,0xa3,0x5d,0x66,0xa4,0x5b,0x69,0xa5,0x59,0x6c,0xa5,0x57,0x6f,0xa6,0x56,0x71,0xa6,0x54,0x74,0xa7,0x52,0x77,0xa7,0x50,0x7a,0xa8,0x4e,0x7c,0xa8,0x4c,0x7f,0xa9,0x4a,0x82,0xa9,0x48,0x84,0xaa,0x47,0x87,0xaa,0x45,0x89,0xab,0x43,0x8c,0xab,0x41,0x8f,0xac,0x3f,0x91,0xac,0x3d,0x94,0xad,0x3b,0x96,0xad,0x3a,0x98,0xae,0x38,0x9b,0xae,0x36,0x9d,0xae,0x34,0xa0,0xaf,0x32,0xa2,0xaf,0x30,0xa5,0xb0,0x2e,0xa7,0xb0,0x2d,0xaa,0xb0,0x2b,0xac,0xb1,0x29,0xaf,0xb1,0x27,0xb1,0xb2,0x25,0xb4,0xb2,0x24,0xb6,0xb2,0x22,0xb9,0xb3,0x20,0xbb,0xb3,0x1e,0xbe,0xb3,0x1d,0xc0,0xb3,0x1b,0xc3,0xb4,0x19,0xc5,0xb4,0x18,0xc8,0xb4,0x17,0xcb,0xb4,0x15,0xcd,0xb5,0x14,0xd0,0xb5,0x13,0xd3,0xb5,0x13,0xd5,0xb5,0x12,0xd8,0xb5,0x12,0xdb,0xb5,0x12,0xdd,0xb6,0x12,0xe0,0xb6,0x13,0xe2,0xb6,0x13,0xe4,0xb6,0x13,0xe6,0xb7,0x13,0xe8,0xb7,0x13,0xe9,0xb8,0x14,0xeb,0xb8,0x14,0xec,0xb9,0x14,0xee,0xba,0x14,0xef,0xba,0x14,0xf0,0xbb,0x14,0xf1,0xbc,0x14,0xf2,0xbc,0x14,0xf3,0xbd,0x14,0xf4,0xbe,0x14,0xf5,0xbf,0x14,0xf6,0xc0,0x14,0xf7,0xc1,0x14,0xf7,0xc1,0x14,0xf8,0xc2,0x14,0xf9,0xc3,0x14,0xf9,0xc4,0x14,0xfa,0xc5,0x14,0xfa,0xc6,0x14,0xfb,0xc7,0x14,0xfb,0xc8,0x14,0xfc,0xc9,0x14,0xfc,0xca,0x14,0xfd,0xcb,0x13,0xfd,0xcc,0x13,0xfd,0xcd,0x13,0xfd,0xcf,0x13,0xfe,0xd0,0x13,0xfe,0xd1,0x13,0xfe,0xd2,0x13,0xfe,0xd3,0x13,0xfe,0xd4,0x12,0xfe,0xd5,0x12,0xff,0xd6,0x12,0xff,0xd8,0x12,0xff,0xd9,0x12,0xff,0xda,0x12,0xff,0xdb,0x11,0xff,0xdc,0x11,0xff,0xdd,0x11,0xff,0xdf,0x11,0xfe,0xe0,0x10,0xfe,0xe1,0x10,0xfe,0xe2,0x10,0xfe,0xe3,0x10,0xfe,0xe5,0x0f,0xfe,0xe6,0x0f,0xfe,0xe7,0x0f,0xfd,0xe8,0x0f,0xfd,0xea,0x0e,0xfd,0xeb,0x0e,0xfd,0xec,0x0e,0xfc,0xed,0x0d,0xfc,0xef,0x0d,0xfc,0xf0,0x0d,0xfb,0xf1,0x0c,0xfb,0xf2,0x0c,0xfa,0xf4,0x0c,0xfa,0xf5,0x0b,0xfa,0xf6,0x0b,0xf9,0xf7,0x0a,0xf9,0xf9,0x0a}; +namespace CET +{ +// linear +static constexpr std::array L01 = { + 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x06, 0x06, 0x06, 0x07, + 0x07, 0x07, 0x09, 0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0b, 0x0b, 0x0b, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, + 0x0e, 0x0f, 0x0f, 0x0f, 0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13, + 0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17, 0x18, + 0x18, 0x18, 0x19, 0x19, 0x19, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1a, 0x1b, 0x1b, 0x1b, 0x1c, 0x1c, + 0x1c, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1e, 0x1e, 0x1e, 0x1f, 0x1f, 0x1f, 0x20, 0x20, 0x20, + 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x22, 0x22, 0x22, 0x23, 0x23, 0x23, 0x24, 0x24, 0x24, 0x25, + 0x25, 0x25, 0x25, 0x25, 0x25, 0x26, 0x26, 0x26, 0x27, 0x27, 0x27, 0x28, 0x28, 0x28, 0x29, 0x29, + 0x29, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2b, 0x2b, 0x2b, 0x2c, 0x2c, 0x2c, 0x2d, 0x2d, 0x2d, + 0x2e, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, 0x30, 0x30, 0x30, 0x31, 0x31, 0x31, 0x32, + 0x32, 0x32, 0x33, 0x33, 0x33, 0x34, 0x34, 0x34, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x36, 0x36, + 0x36, 0x37, 0x37, 0x37, 0x38, 0x38, 0x38, 0x39, 0x39, 0x39, 0x3a, 0x3a, 0x3a, 0x3b, 0x3b, 0x3b, + 0x3b, 0x3c, 0x3c, 0x3c, 0x3c, 0x3c, 0x3d, 0x3d, 0x3d, 0x3e, 0x3e, 0x3e, 0x3f, 0x3f, 0x3f, 0x40, + 0x40, 0x40, 0x41, 0x41, 0x41, 0x42, 0x42, 0x42, 0x43, 0x43, 0x43, 0x43, 0x43, 0x43, 0x44, 0x44, + 0x44, 0x45, 0x45, 0x45, 0x46, 0x46, 0x46, 0x47, 0x47, 0x47, 0x48, 0x48, 0x48, 0x49, 0x49, 0x49, + 0x4a, 0x4a, 0x4a, 0x4b, 0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d, 0x4d, 0x4e, + 0x4e, 0x4e, 0x4f, 0x4f, 0x4f, 0x50, 0x50, 0x50, 0x51, 0x51, 0x51, 0x52, 0x52, 0x52, 0x53, 0x53, + 0x53, 0x54, 0x54, 0x54, 0x55, 0x55, 0x55, 0x56, 0x56, 0x56, 0x57, 0x57, 0x57, 0x58, 0x58, 0x58, + 0x59, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b, 0x5b, 0x5c, 0x5c, 0x5c, 0x5d, + 0x5d, 0x5d, 0x5e, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61, 0x62, 0x62, + 0x62, 0x63, 0x63, 0x63, 0x64, 0x64, 0x64, 0x65, 0x65, 0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x67, + 0x68, 0x68, 0x68, 0x69, 0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6b, 0x6b, 0x6b, 0x6c, 0x6c, 0x6c, 0x6d, + 0x6d, 0x6d, 0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f, 0x70, 0x70, 0x70, 0x71, 0x71, 0x71, 0x71, 0x72, + 0x72, 0x72, 0x72, 0x72, 0x73, 0x73, 0x73, 0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x76, 0x76, 0x76, + 0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7c, + 0x7c, 0x7c, 0x7d, 0x7d, 0x7d, 0x7e, 0x7e, 0x7e, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x81, 0x81, + 0x81, 0x82, 0x82, 0x82, 0x83, 0x83, 0x83, 0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x86, 0x86, 0x86, + 0x87, 0x87, 0x87, 0x88, 0x88, 0x88, 0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8b, 0x8b, 0x8b, 0x8c, + 0x8c, 0x8c, 0x8d, 0x8d, 0x8d, 0x8e, 0x8f, 0x8f, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x92, 0x92, + 0x92, 0x93, 0x93, 0x93, 0x94, 0x94, 0x94, 0x95, 0x95, 0x95, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97, + 0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c, 0x9d, + 0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0x9f, 0x9f, 0x9f, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, + 0xa2, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa6, 0xa7, 0xa7, 0xa7, + 0xa8, 0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xaa, 0xab, 0xab, 0xac, 0xac, 0xac, 0xad, 0xad, 0xad, 0xae, + 0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, + 0xb3, 0xb4, 0xb4, 0xb4, 0xb5, 0xb5, 0xb5, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, + 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbf, + 0xbf, 0xbf, 0xc0, 0xc0, 0xc0, 0xc1, 0xc1, 0xc1, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, + 0xc4, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc8, 0xc9, 0xc9, 0xca, 0xca, 0xca, + 0xcb, 0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf, 0xd0, + 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd2, 0xd2, 0xd2, 0xd3, 0xd3, 0xd3, 0xd4, 0xd5, 0xd5, 0xd6, 0xd6, + 0xd6, 0xd7, 0xd7, 0xd7, 0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, + 0xdc, 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe2, + 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, + 0xe7, 0xe8, 0xe8, 0xe8, 0xea, 0xea, 0xea, 0xeb, 0xeb, 0xeb, 0xec, 0xec, 0xec, 0xed, 0xed, 0xed, + 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf3, 0xf3, 0xf3, 0xf4, + 0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7, 0xf8, 0xf8, 0xf8, 0xf9, 0xf9, + 0xf9, 0xfa, 0xfa, 0xfa, 0xfc, 0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff +}; +static constexpr std::array L02 = { + 0x1b, 0x1b, 0x1b, 0x1c, 0x1c, 0x1c, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1d, 0x1e, 0x1e, 0x1e, 0x1f, + 0x1f, 0x1f, 0x1f, 0x1f, 0x1f, 0x20, 0x20, 0x20, 0x21, 0x21, 0x21, 0x22, 0x22, 0x22, 0x22, 0x22, + 0x22, 0x23, 0x23, 0x23, 0x24, 0x24, 0x24, 0x24, 0x24, 0x24, 0x25, 0x25, 0x25, 0x26, 0x26, 0x26, + 0x26, 0x26, 0x26, 0x27, 0x27, 0x27, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x29, 0x29, 0x29, 0x2a, + 0x2a, 0x2a, 0x2b, 0x2b, 0x2b, 0x2b, 0x2b, 0x2b, 0x2c, 0x2c, 0x2c, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, + 0x2d, 0x2e, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x31, 0x31, + 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x33, 0x33, 0x33, 0x34, 0x34, 0x34, 0x35, 0x35, 0x35, 0x35, + 0x35, 0x35, 0x36, 0x36, 0x36, 0x37, 0x37, 0x37, 0x38, 0x38, 0x38, 0x38, 0x38, 0x38, 0x39, 0x39, + 0x39, 0x3a, 0x3a, 0x3a, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3b, 0x3c, 0x3c, 0x3c, 0x3d, 0x3d, 0x3d, + 0x3e, 0x3e, 0x3e, 0x3e, 0x3e, 0x3e, 0x3f, 0x3f, 0x3f, 0x40, 0x40, 0x40, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x42, 0x42, 0x42, 0x43, 0x43, 0x43, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x45, 0x45, + 0x45, 0x46, 0x46, 0x46, 0x47, 0x47, 0x47, 0x47, 0x47, 0x47, 0x48, 0x48, 0x48, 0x49, 0x49, 0x49, + 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4a, 0x4b, 0x4b, 0x4b, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d, 0x4e, + 0x4e, 0x4e, 0x4e, 0x4e, 0x4e, 0x4f, 0x4f, 0x4f, 0x50, 0x50, 0x50, 0x51, 0x51, 0x51, 0x51, 0x52, + 0x52, 0x52, 0x52, 0x52, 0x53, 0x53, 0x53, 0x54, 0x54, 0x54, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, + 0x56, 0x56, 0x56, 0x57, 0x57, 0x57, 0x58, 0x58, 0x58, 0x59, 0x59, 0x59, 0x59, 0x59, 0x59, 0x5a, + 0x5a, 0x5a, 0x5b, 0x5b, 0x5b, 0x5c, 0x5c, 0x5c, 0x5d, 0x5d, 0x5d, 0x5d, 0x5d, 0x5d, 0x5e, 0x5e, + 0x5e, 0x5f, 0x5f, 0x5f, 0x60, 0x60, 0x60, 0x61, 0x61, 0x61, 0x61, 0x61, 0x61, 0x62, 0x62, 0x62, + 0x63, 0x63, 0x63, 0x64, 0x64, 0x64, 0x65, 0x65, 0x65, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x67, + 0x67, 0x67, 0x68, 0x68, 0x68, 0x69, 0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6a, 0x6b, 0x6b, + 0x6b, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, + 0x70, 0x70, 0x70, 0x71, 0x71, 0x71, 0x72, 0x72, 0x72, 0x73, 0x73, 0x73, 0x74, 0x74, 0x74, 0x74, + 0x74, 0x74, 0x75, 0x75, 0x75, 0x76, 0x76, 0x76, 0x77, 0x77, 0x77, 0x78, 0x78, 0x78, 0x79, 0x79, + 0x79, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d, + 0x7e, 0x7e, 0x7e, 0x7e, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x80, 0x80, 0x80, 0x81, 0x81, 0x81, 0x82, + 0x82, 0x82, 0x83, 0x83, 0x83, 0x84, 0x84, 0x84, 0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x86, 0x86, + 0x86, 0x87, 0x87, 0x87, 0x88, 0x88, 0x88, 0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8a, 0x8a, 0x8a, + 0x8b, 0x8b, 0x8b, 0x8c, 0x8c, 0x8c, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f, 0x90, + 0x90, 0x90, 0x91, 0x91, 0x91, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92, 0x93, 0x93, 0x93, 0x94, 0x94, + 0x94, 0x95, 0x95, 0x95, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98, 0x98, 0x98, 0x98, + 0x99, 0x99, 0x99, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b, 0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9e, + 0x9e, 0x9e, 0x9f, 0x9f, 0x9f, 0x9f, 0x9f, 0x9f, 0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, + 0xa2, 0xa3, 0xa3, 0xa3, 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa6, 0xa7, 0xa7, 0xa7, + 0xa7, 0xa7, 0xa7, 0xa8, 0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xaa, 0xaa, 0xaa, 0xab, 0xab, 0xab, 0xac, + 0xac, 0xac, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xb0, 0xb0, 0xb0, 0xb0, 0xb0, + 0xb0, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3, 0xb4, 0xb4, 0xb4, 0xb5, 0xb5, 0xb5, + 0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, + 0xba, 0xba, 0xbb, 0xbb, 0xbb, 0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, + 0xbf, 0xc0, 0xc0, 0xc0, 0xc1, 0xc1, 0xc1, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, + 0xc4, 0xc4, 0xc4, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc8, 0xc8, 0xc8, 0xc9, + 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb, 0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xce, 0xce, + 0xce, 0xcf, 0xcf, 0xcf, 0xd0, 0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd1, 0xd1, 0xd2, 0xd2, 0xd2, + 0xd3, 0xd3, 0xd3, 0xd4, 0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7, 0xd8, + 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb, 0xdc, 0xdc, 0xdc, 0xdd, 0xdd, + 0xdd, 0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf, 0xdf, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, + 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3, 0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, + 0xe7, 0xe7, 0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xea, 0xea, 0xea, 0xeb, 0xeb, 0xeb, 0xec, 0xec, + 0xec, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef, 0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1 +}; +static constexpr std::array L03 = { + 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x12, 0x00, 0x00, 0x16, 0x00, 0x00, 0x1a, + 0x00, 0x00, 0x1d, 0x00, 0x00, 0x20, 0x00, 0x00, 0x22, 0x00, 0x00, 0x25, 0x00, 0x00, 0x27, 0x00, + 0x00, 0x29, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x31, 0x00, 0x00, + 0x32, 0x00, 0x00, 0x34, 0x00, 0x00, 0x36, 0x01, 0x00, 0x37, 0x01, 0x00, 0x39, 0x00, 0x00, 0x3a, + 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x40, 0x00, 0x00, 0x42, 0x01, + 0x00, 0x43, 0x01, 0x00, 0x45, 0x01, 0x00, 0x46, 0x01, 0x00, 0x48, 0x01, 0x00, 0x49, 0x01, 0x00, + 0x4b, 0x01, 0x00, 0x4c, 0x01, 0x00, 0x4e, 0x01, 0x00, 0x4f, 0x01, 0x00, 0x51, 0x01, 0x00, 0x52, + 0x01, 0x00, 0x54, 0x01, 0x00, 0x55, 0x01, 0x00, 0x57, 0x01, 0x00, 0x58, 0x01, 0x00, 0x5a, 0x01, + 0x00, 0x5c, 0x01, 0x00, 0x5d, 0x01, 0x00, 0x5f, 0x01, 0x00, 0x60, 0x01, 0x00, 0x62, 0x01, 0x00, + 0x63, 0x01, 0x00, 0x65, 0x01, 0x00, 0x67, 0x01, 0x00, 0x68, 0x01, 0x00, 0x6a, 0x01, 0x00, 0x6b, + 0x02, 0x00, 0x6d, 0x02, 0x00, 0x6f, 0x02, 0x00, 0x70, 0x02, 0x00, 0x72, 0x02, 0x00, 0x74, 0x02, + 0x00, 0x75, 0x02, 0x00, 0x77, 0x02, 0x00, 0x79, 0x02, 0x00, 0x7a, 0x02, 0x00, 0x7c, 0x02, 0x00, + 0x7e, 0x02, 0x00, 0x7f, 0x02, 0x00, 0x81, 0x02, 0x00, 0x83, 0x02, 0x00, 0x84, 0x03, 0x00, 0x86, + 0x03, 0x00, 0x88, 0x03, 0x00, 0x89, 0x03, 0x00, 0x8b, 0x03, 0x00, 0x8d, 0x03, 0x00, 0x8e, 0x03, + 0x00, 0x90, 0x03, 0x00, 0x92, 0x03, 0x00, 0x93, 0x03, 0x00, 0x95, 0x03, 0x00, 0x97, 0x04, 0x00, + 0x99, 0x04, 0x00, 0x9a, 0x04, 0x00, 0x9c, 0x04, 0x00, 0x9e, 0x04, 0x00, 0x9f, 0x04, 0x00, 0xa1, + 0x04, 0x00, 0xa3, 0x04, 0x00, 0xa5, 0x05, 0x00, 0xa6, 0x05, 0x00, 0xa8, 0x05, 0x00, 0xaa, 0x05, + 0x00, 0xac, 0x05, 0x00, 0xad, 0x05, 0x00, 0xaf, 0x05, 0x00, 0xb1, 0x06, 0x00, 0xb3, 0x06, 0x00, + 0xb5, 0x06, 0x00, 0xb6, 0x06, 0x00, 0xb8, 0x06, 0x00, 0xba, 0x07, 0x00, 0xbc, 0x07, 0x00, 0xbd, + 0x07, 0x00, 0xbf, 0x07, 0x00, 0xc1, 0x07, 0x00, 0xc3, 0x08, 0x00, 0xc5, 0x08, 0x00, 0xc6, 0x08, + 0x00, 0xc8, 0x08, 0x00, 0xca, 0x09, 0x00, 0xcc, 0x09, 0x00, 0xce, 0x09, 0x00, 0xcf, 0x09, 0x00, + 0xd1, 0x0a, 0x00, 0xd3, 0x0a, 0x00, 0xd5, 0x0b, 0x00, 0xd7, 0x0b, 0x00, 0xd8, 0x0b, 0x00, 0xda, + 0x0c, 0x00, 0xdc, 0x0c, 0x00, 0xde, 0x0d, 0x00, 0xe0, 0x0d, 0x00, 0xe1, 0x0e, 0x00, 0xe3, 0x0e, + 0x00, 0xe5, 0x0f, 0x00, 0xe7, 0x10, 0x00, 0xe8, 0x11, 0x00, 0xea, 0x12, 0x00, 0xec, 0x13, 0x00, + 0xed, 0x15, 0x00, 0xef, 0x17, 0x00, 0xf0, 0x19, 0x00, 0xf2, 0x1b, 0x00, 0xf3, 0x1e, 0x00, 0xf4, + 0x20, 0x00, 0xf5, 0x23, 0x00, 0xf6, 0x26, 0x00, 0xf7, 0x29, 0x00, 0xf8, 0x2c, 0x00, 0xf8, 0x2f, + 0x00, 0xf9, 0x32, 0x00, 0xfa, 0x35, 0x00, 0xfa, 0x38, 0x00, 0xfb, 0x3b, 0x00, 0xfb, 0x3e, 0x00, + 0xfc, 0x41, 0x00, 0xfc, 0x44, 0x00, 0xfc, 0x46, 0x00, 0xfd, 0x49, 0x00, 0xfd, 0x4c, 0x00, 0xfd, + 0x4e, 0x00, 0xfd, 0x51, 0x00, 0xfe, 0x54, 0x00, 0xfe, 0x56, 0x00, 0xfe, 0x59, 0x00, 0xfe, 0x5b, + 0x00, 0xfe, 0x5d, 0x00, 0xfe, 0x60, 0x00, 0xfe, 0x62, 0x00, 0xfe, 0x64, 0x00, 0xff, 0x67, 0x00, + 0xff, 0x69, 0x00, 0xff, 0x6b, 0x00, 0xff, 0x6d, 0x00, 0xff, 0x6f, 0x00, 0xff, 0x72, 0x00, 0xff, + 0x74, 0x00, 0xff, 0x76, 0x00, 0xff, 0x78, 0x00, 0xff, 0x7a, 0x00, 0xff, 0x7c, 0x00, 0xff, 0x7e, + 0x00, 0xff, 0x80, 0x00, 0xff, 0x82, 0x00, 0xff, 0x84, 0x00, 0xff, 0x86, 0x00, 0xff, 0x88, 0x00, + 0xff, 0x8a, 0x00, 0xff, 0x8c, 0x00, 0xff, 0x8e, 0x00, 0xff, 0x8f, 0x00, 0xff, 0x91, 0x00, 0xff, + 0x93, 0x00, 0xff, 0x95, 0x00, 0xff, 0x97, 0x00, 0xff, 0x99, 0x00, 0xff, 0x9a, 0x00, 0xff, 0x9c, + 0x01, 0xff, 0x9e, 0x01, 0xff, 0xa0, 0x01, 0xff, 0xa1, 0x01, 0xff, 0xa3, 0x01, 0xff, 0xa5, 0x01, + 0xff, 0xa7, 0x01, 0xff, 0xa8, 0x01, 0xff, 0xaa, 0x01, 0xff, 0xac, 0x01, 0xff, 0xad, 0x02, 0xff, + 0xaf, 0x02, 0xff, 0xb1, 0x02, 0xff, 0xb2, 0x02, 0xff, 0xb4, 0x02, 0xff, 0xb6, 0x02, 0xff, 0xb7, + 0x03, 0xff, 0xb9, 0x03, 0xff, 0xbb, 0x03, 0xff, 0xbc, 0x03, 0xff, 0xbe, 0x03, 0xff, 0xc0, 0x04, + 0xff, 0xc1, 0x04, 0xff, 0xc3, 0x04, 0xff, 0xc4, 0x04, 0xff, 0xc6, 0x05, 0xff, 0xc8, 0x05, 0xff, + 0xc9, 0x05, 0xff, 0xcb, 0x05, 0xff, 0xcc, 0x06, 0xff, 0xce, 0x06, 0xff, 0xd0, 0x06, 0xff, 0xd1, + 0x07, 0xff, 0xd3, 0x07, 0xff, 0xd4, 0x08, 0xff, 0xd6, 0x08, 0xff, 0xd7, 0x09, 0xff, 0xd9, 0x09, + 0xff, 0xdb, 0x0a, 0xff, 0xdc, 0x0a, 0xff, 0xde, 0x0b, 0xff, 0xdf, 0x0b, 0xff, 0xe1, 0x0c, 0xff, + 0xe2, 0x0d, 0xff, 0xe4, 0x0d, 0xff, 0xe5, 0x0e, 0xff, 0xe7, 0x0f, 0xff, 0xe9, 0x10, 0xff, 0xea, + 0x11, 0xff, 0xec, 0x13, 0xff, 0xed, 0x15, 0xff, 0xef, 0x17, 0xff, 0xf0, 0x1a, 0xff, 0xf2, 0x1f, + 0xff, 0xf3, 0x24, 0xff, 0xf5, 0x2b, 0xff, 0xf6, 0x33, 0xff, 0xf7, 0x3c, 0xff, 0xf9, 0x47, 0xff, + 0xfa, 0x54, 0xff, 0xfb, 0x62, 0xff, 0xfc, 0x72, 0xff, 0xfd, 0x84, 0xff, 0xfe, 0x96, 0xff, 0xfe, + 0xa8, 0xff, 0xfe, 0xbb, 0xff, 0xff, 0xcd, 0xff, 0xff, 0xde, 0xff, 0xff, 0xef, 0xff, 0xff, 0xff +}; +static constexpr std::array L04 = { + 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x12, 0x00, 0x00, 0x16, 0x00, 0x00, 0x19, + 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x22, 0x00, 0x00, 0x24, 0x00, 0x00, 0x26, 0x00, + 0x00, 0x28, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x30, 0x00, 0x00, + 0x32, 0x00, 0x00, 0x33, 0x00, 0x00, 0x35, 0x00, 0x00, 0x36, 0x00, 0x00, 0x38, 0x00, 0x00, 0x39, + 0x00, 0x00, 0x3b, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x3f, 0x00, 0x00, 0x40, 0x00, + 0x00, 0x42, 0x01, 0x00, 0x43, 0x01, 0x00, 0x45, 0x01, 0x00, 0x46, 0x01, 0x00, 0x48, 0x01, 0x00, + 0x49, 0x01, 0x00, 0x4b, 0x01, 0x00, 0x4c, 0x01, 0x00, 0x4e, 0x01, 0x00, 0x4f, 0x01, 0x00, 0x51, + 0x01, 0x00, 0x52, 0x01, 0x00, 0x54, 0x01, 0x00, 0x55, 0x01, 0x00, 0x57, 0x01, 0x00, 0x58, 0x01, + 0x00, 0x5a, 0x01, 0x00, 0x5b, 0x01, 0x00, 0x5d, 0x01, 0x00, 0x5e, 0x01, 0x00, 0x60, 0x01, 0x00, + 0x61, 0x01, 0x00, 0x63, 0x01, 0x00, 0x64, 0x01, 0x00, 0x66, 0x01, 0x00, 0x67, 0x01, 0x00, 0x69, + 0x01, 0x00, 0x6b, 0x02, 0x00, 0x6c, 0x02, 0x00, 0x6e, 0x02, 0x00, 0x6f, 0x02, 0x00, 0x71, 0x02, + 0x00, 0x72, 0x02, 0x00, 0x74, 0x02, 0x00, 0x76, 0x02, 0x00, 0x77, 0x02, 0x00, 0x79, 0x02, 0x00, + 0x7a, 0x02, 0x00, 0x7c, 0x02, 0x00, 0x7e, 0x02, 0x00, 0x7f, 0x02, 0x00, 0x81, 0x02, 0x00, 0x83, + 0x02, 0x00, 0x84, 0x03, 0x00, 0x86, 0x03, 0x00, 0x87, 0x03, 0x00, 0x89, 0x03, 0x00, 0x8b, 0x03, + 0x00, 0x8c, 0x03, 0x00, 0x8e, 0x03, 0x00, 0x90, 0x03, 0x00, 0x91, 0x03, 0x00, 0x93, 0x03, 0x00, + 0x95, 0x03, 0x00, 0x96, 0x04, 0x00, 0x98, 0x04, 0x00, 0x9a, 0x04, 0x00, 0x9b, 0x04, 0x00, 0x9d, + 0x04, 0x00, 0x9f, 0x04, 0x00, 0xa0, 0x04, 0x00, 0xa2, 0x04, 0x00, 0xa4, 0x04, 0x00, 0xa5, 0x05, + 0x00, 0xa7, 0x05, 0x00, 0xa9, 0x05, 0x00, 0xab, 0x05, 0x00, 0xac, 0x05, 0x00, 0xae, 0x05, 0x00, + 0xb0, 0x06, 0x00, 0xb1, 0x06, 0x00, 0xb3, 0x06, 0x00, 0xb5, 0x06, 0x00, 0xb7, 0x06, 0x00, 0xb8, + 0x06, 0x00, 0xba, 0x07, 0x00, 0xbc, 0x07, 0x00, 0xbd, 0x07, 0x00, 0xbf, 0x07, 0x00, 0xc1, 0x07, + 0x00, 0xc3, 0x08, 0x00, 0xc4, 0x08, 0x00, 0xc6, 0x08, 0x00, 0xc8, 0x08, 0x00, 0xca, 0x09, 0x00, + 0xcb, 0x09, 0x00, 0xcd, 0x09, 0x00, 0xcf, 0x09, 0x00, 0xd1, 0x0a, 0x00, 0xd2, 0x0a, 0x00, 0xd4, + 0x0a, 0x00, 0xd6, 0x0b, 0x00, 0xd8, 0x0b, 0x00, 0xd9, 0x0c, 0x00, 0xdb, 0x0c, 0x00, 0xdd, 0x0c, + 0x00, 0xdf, 0x0d, 0x00, 0xe0, 0x0d, 0x00, 0xe2, 0x0e, 0x00, 0xe4, 0x0f, 0x00, 0xe6, 0x0f, 0x00, + 0xe7, 0x10, 0x00, 0xe9, 0x11, 0x00, 0xeb, 0x12, 0x00, 0xec, 0x13, 0x00, 0xee, 0x15, 0x00, 0xef, + 0x18, 0x00, 0xf0, 0x1a, 0x00, 0xf1, 0x1d, 0x00, 0xf2, 0x21, 0x00, 0xf3, 0x24, 0x00, 0xf4, 0x27, + 0x00, 0xf4, 0x2a, 0x00, 0xf5, 0x2e, 0x00, 0xf6, 0x31, 0x00, 0xf6, 0x34, 0x00, 0xf7, 0x37, 0x00, + 0xf7, 0x3a, 0x00, 0xf7, 0x3d, 0x00, 0xf8, 0x3f, 0x00, 0xf8, 0x42, 0x00, 0xf8, 0x45, 0x00, 0xf9, + 0x48, 0x00, 0xf9, 0x4a, 0x00, 0xf9, 0x4d, 0x00, 0xf9, 0x4f, 0x00, 0xfa, 0x52, 0x00, 0xfa, 0x54, + 0x00, 0xfa, 0x56, 0x00, 0xfa, 0x59, 0x00, 0xfa, 0x5b, 0x00, 0xfb, 0x5d, 0x00, 0xfb, 0x60, 0x00, + 0xfb, 0x62, 0x00, 0xfb, 0x64, 0x00, 0xfb, 0x66, 0x00, 0xfb, 0x68, 0x00, 0xfc, 0x6a, 0x00, 0xfc, + 0x6c, 0x00, 0xfc, 0x6e, 0x00, 0xfc, 0x70, 0x00, 0xfc, 0x72, 0x00, 0xfc, 0x74, 0x00, 0xfc, 0x76, + 0x00, 0xfc, 0x78, 0x00, 0xfc, 0x7a, 0x00, 0xfc, 0x7c, 0x00, 0xfd, 0x7e, 0x00, 0xfd, 0x80, 0x00, + 0xfd, 0x82, 0x00, 0xfd, 0x83, 0x00, 0xfd, 0x85, 0x00, 0xfd, 0x87, 0x00, 0xfd, 0x89, 0x00, 0xfd, + 0x8b, 0x00, 0xfd, 0x8c, 0x00, 0xfd, 0x8e, 0x00, 0xfd, 0x90, 0x00, 0xfd, 0x92, 0x00, 0xfd, 0x93, + 0x00, 0xfe, 0x95, 0x00, 0xfe, 0x97, 0x00, 0xfe, 0x99, 0x00, 0xfe, 0x9a, 0x00, 0xfe, 0x9c, 0x00, + 0xfe, 0x9e, 0x00, 0xfe, 0x9f, 0x00, 0xfe, 0xa1, 0x00, 0xfe, 0xa3, 0x00, 0xfe, 0xa4, 0x00, 0xfe, + 0xa6, 0x00, 0xfe, 0xa8, 0x00, 0xfe, 0xa9, 0x00, 0xfe, 0xab, 0x00, 0xfe, 0xad, 0x00, 0xfe, 0xae, + 0x00, 0xfe, 0xb0, 0x00, 0xfe, 0xb1, 0x00, 0xfe, 0xb3, 0x00, 0xfe, 0xb5, 0x00, 0xfe, 0xb6, 0x00, + 0xfe, 0xb8, 0x00, 0xfe, 0xb9, 0x00, 0xfe, 0xbb, 0x00, 0xfe, 0xbd, 0x00, 0xff, 0xbe, 0x00, 0xff, + 0xc0, 0x00, 0xff, 0xc1, 0x00, 0xff, 0xc3, 0x00, 0xff, 0xc4, 0x00, 0xff, 0xc6, 0x00, 0xff, 0xc7, + 0x00, 0xff, 0xc9, 0x00, 0xff, 0xcb, 0x00, 0xff, 0xcc, 0x00, 0xff, 0xce, 0x00, 0xff, 0xcf, 0x00, + 0xff, 0xd1, 0x00, 0xff, 0xd2, 0x00, 0xff, 0xd4, 0x00, 0xff, 0xd5, 0x00, 0xff, 0xd7, 0x00, 0xff, + 0xd8, 0x00, 0xff, 0xda, 0x00, 0xff, 0xdb, 0x00, 0xff, 0xdd, 0x00, 0xff, 0xde, 0x00, 0xff, 0xe0, + 0x00, 0xff, 0xe1, 0x00, 0xff, 0xe3, 0x00, 0xff, 0xe4, 0x00, 0xff, 0xe6, 0x00, 0xff, 0xe7, 0x00, + 0xff, 0xe9, 0x00, 0xff, 0xea, 0x00, 0xff, 0xec, 0x00, 0xff, 0xed, 0x00, 0xff, 0xef, 0x00, 0xff, + 0xf0, 0x00, 0xff, 0xf2, 0x00, 0xff, 0xf3, 0x00, 0xff, 0xf5, 0x00, 0xff, 0xf6, 0x00, 0xff, 0xf8, + 0x00, 0xff, 0xf9, 0x00, 0xff, 0xfb, 0x00, 0xff, 0xfc, 0x00, 0xff, 0xfe, 0x00, 0xff, 0xff, 0x00 +}; +static constexpr std::array L05 = { + 0x01, 0x15, 0x06, 0x01, 0x16, 0x06, 0x02, 0x17, 0x06, 0x02, 0x18, 0x06, 0x03, 0x19, 0x06, 0x04, + 0x19, 0x06, 0x04, 0x1a, 0x06, 0x05, 0x1b, 0x06, 0x05, 0x1c, 0x06, 0x06, 0x1c, 0x06, 0x07, 0x1d, + 0x06, 0x07, 0x1e, 0x06, 0x08, 0x1f, 0x06, 0x08, 0x20, 0x06, 0x08, 0x20, 0x06, 0x09, 0x21, 0x06, + 0x09, 0x22, 0x06, 0x09, 0x23, 0x05, 0x09, 0x24, 0x05, 0x09, 0x24, 0x05, 0x09, 0x25, 0x05, 0x09, + 0x26, 0x05, 0x09, 0x27, 0x05, 0x09, 0x28, 0x05, 0x09, 0x29, 0x05, 0x09, 0x2a, 0x05, 0x09, 0x2a, + 0x05, 0x09, 0x2b, 0x05, 0x09, 0x2c, 0x05, 0x09, 0x2d, 0x05, 0x09, 0x2e, 0x05, 0x09, 0x2f, 0x05, + 0x09, 0x30, 0x05, 0x08, 0x31, 0x05, 0x08, 0x31, 0x05, 0x08, 0x32, 0x05, 0x08, 0x33, 0x05, 0x08, + 0x34, 0x05, 0x09, 0x35, 0x05, 0x09, 0x36, 0x05, 0x09, 0x37, 0x05, 0x09, 0x38, 0x05, 0x09, 0x38, + 0x05, 0x09, 0x39, 0x05, 0x0a, 0x3a, 0x05, 0x0a, 0x3b, 0x05, 0x0a, 0x3c, 0x05, 0x0a, 0x3d, 0x05, + 0x0b, 0x3e, 0x05, 0x0b, 0x3f, 0x05, 0x0b, 0x40, 0x05, 0x0b, 0x40, 0x05, 0x0c, 0x41, 0x05, 0x0c, + 0x42, 0x05, 0x0c, 0x43, 0x05, 0x0d, 0x44, 0x05, 0x0d, 0x45, 0x05, 0x0d, 0x46, 0x05, 0x0d, 0x47, + 0x05, 0x0e, 0x48, 0x05, 0x0e, 0x49, 0x05, 0x0e, 0x49, 0x05, 0x0e, 0x4a, 0x05, 0x0f, 0x4b, 0x05, + 0x0f, 0x4c, 0x05, 0x0f, 0x4d, 0x05, 0x0f, 0x4e, 0x05, 0x10, 0x4f, 0x05, 0x10, 0x50, 0x05, 0x10, + 0x51, 0x05, 0x10, 0x52, 0x05, 0x11, 0x53, 0x05, 0x11, 0x54, 0x06, 0x11, 0x55, 0x06, 0x11, 0x55, + 0x06, 0x12, 0x56, 0x06, 0x12, 0x57, 0x06, 0x12, 0x58, 0x06, 0x12, 0x59, 0x06, 0x13, 0x5a, 0x06, + 0x13, 0x5b, 0x06, 0x13, 0x5c, 0x06, 0x13, 0x5d, 0x06, 0x14, 0x5e, 0x06, 0x14, 0x5f, 0x07, 0x14, + 0x60, 0x07, 0x14, 0x61, 0x07, 0x15, 0x62, 0x07, 0x15, 0x63, 0x07, 0x15, 0x64, 0x07, 0x15, 0x65, + 0x07, 0x16, 0x66, 0x07, 0x16, 0x67, 0x07, 0x16, 0x68, 0x07, 0x16, 0x68, 0x08, 0x17, 0x69, 0x08, + 0x17, 0x6a, 0x08, 0x17, 0x6b, 0x08, 0x17, 0x6c, 0x08, 0x18, 0x6d, 0x08, 0x18, 0x6e, 0x08, 0x18, + 0x6f, 0x08, 0x18, 0x70, 0x08, 0x19, 0x71, 0x08, 0x19, 0x72, 0x09, 0x19, 0x73, 0x09, 0x19, 0x74, + 0x09, 0x1a, 0x75, 0x09, 0x1a, 0x76, 0x09, 0x1a, 0x77, 0x09, 0x1a, 0x78, 0x09, 0x1b, 0x79, 0x09, + 0x1b, 0x7a, 0x09, 0x1b, 0x7b, 0x0a, 0x1b, 0x7c, 0x0a, 0x1c, 0x7d, 0x0a, 0x1c, 0x7e, 0x0a, 0x1c, + 0x7f, 0x0a, 0x1c, 0x80, 0x0a, 0x1d, 0x81, 0x0a, 0x1d, 0x82, 0x0a, 0x1d, 0x83, 0x0b, 0x1e, 0x84, + 0x0b, 0x1e, 0x85, 0x0b, 0x1e, 0x86, 0x0b, 0x1e, 0x87, 0x0b, 0x1f, 0x88, 0x0b, 0x1f, 0x89, 0x0b, + 0x1f, 0x8a, 0x0b, 0x1f, 0x8b, 0x0b, 0x20, 0x8c, 0x0c, 0x20, 0x8d, 0x0c, 0x20, 0x8e, 0x0c, 0x20, + 0x8f, 0x0c, 0x21, 0x90, 0x0c, 0x21, 0x91, 0x0c, 0x21, 0x92, 0x0c, 0x21, 0x93, 0x0c, 0x22, 0x95, + 0x0d, 0x22, 0x96, 0x0d, 0x22, 0x97, 0x0d, 0x22, 0x98, 0x0d, 0x23, 0x99, 0x0d, 0x23, 0x9a, 0x0d, + 0x23, 0x9b, 0x0d, 0x23, 0x9c, 0x0d, 0x24, 0x9d, 0x0d, 0x24, 0x9e, 0x0e, 0x24, 0x9f, 0x0e, 0x25, + 0xa0, 0x0e, 0x25, 0xa1, 0x0e, 0x25, 0xa2, 0x0e, 0x25, 0xa3, 0x0e, 0x26, 0xa4, 0x0e, 0x26, 0xa5, + 0x0e, 0x26, 0xa6, 0x0e, 0x26, 0xa7, 0x0f, 0x27, 0xa8, 0x0f, 0x27, 0xa9, 0x0f, 0x27, 0xaa, 0x0f, + 0x27, 0xac, 0x0f, 0x28, 0xad, 0x0f, 0x28, 0xae, 0x0f, 0x28, 0xaf, 0x0f, 0x28, 0xb0, 0x10, 0x29, + 0xb1, 0x10, 0x29, 0xb2, 0x10, 0x29, 0xb3, 0x10, 0x2a, 0xb4, 0x10, 0x2a, 0xb5, 0x10, 0x2a, 0xb6, + 0x10, 0x2a, 0xb7, 0x10, 0x2b, 0xb8, 0x10, 0x2b, 0xb9, 0x11, 0x2b, 0xba, 0x11, 0x2b, 0xbc, 0x11, + 0x2c, 0xbd, 0x11, 0x2c, 0xbe, 0x11, 0x2c, 0xbf, 0x11, 0x2c, 0xc0, 0x11, 0x2d, 0xc1, 0x11, 0x2d, + 0xc2, 0x11, 0x2d, 0xc3, 0x12, 0x2e, 0xc4, 0x12, 0x2e, 0xc5, 0x12, 0x2e, 0xc6, 0x12, 0x2e, 0xc7, + 0x12, 0x2f, 0xc9, 0x12, 0x2f, 0xca, 0x12, 0x2f, 0xcb, 0x12, 0x2f, 0xcc, 0x13, 0x30, 0xcd, 0x13, + 0x30, 0xce, 0x13, 0x30, 0xcf, 0x13, 0x31, 0xd0, 0x13, 0x31, 0xd1, 0x13, 0x31, 0xd2, 0x13, 0x31, + 0xd3, 0x13, 0x32, 0xd5, 0x13, 0x32, 0xd6, 0x14, 0x32, 0xd7, 0x14, 0x32, 0xd8, 0x14, 0x33, 0xd9, + 0x14, 0x33, 0xda, 0x14, 0x33, 0xdb, 0x14, 0x34, 0xdc, 0x14, 0x34, 0xdd, 0x14, 0x34, 0xdf, 0x14, + 0x34, 0xe0, 0x15, 0x35, 0xe1, 0x15, 0x35, 0xe2, 0x15, 0x35, 0xe3, 0x15, 0x35, 0xe4, 0x15, 0x36, + 0xe5, 0x15, 0x37, 0xe6, 0x15, 0x39, 0xe7, 0x15, 0x3b, 0xe8, 0x15, 0x3e, 0xe9, 0x15, 0x41, 0xea, + 0x16, 0x44, 0xeb, 0x16, 0x48, 0xec, 0x16, 0x4b, 0xed, 0x16, 0x4f, 0xee, 0x16, 0x53, 0xef, 0x16, + 0x57, 0xf0, 0x16, 0x5c, 0xf0, 0x16, 0x60, 0xf1, 0x16, 0x64, 0xf2, 0x16, 0x68, 0xf3, 0x16, 0x6c, + 0xf3, 0x16, 0x71, 0xf4, 0x15, 0x75, 0xf5, 0x15, 0x79, 0xf6, 0x15, 0x7d, 0xf6, 0x15, 0x81, 0xf7, + 0x15, 0x86, 0xf8, 0x15, 0x8a, 0xf8, 0x15, 0x8e, 0xf9, 0x15, 0x92, 0xf9, 0x15, 0x96, 0xfa, 0x15, + 0x9a, 0xfb, 0x15, 0x9f, 0xfb, 0x15, 0xa3, 0xfc, 0x15, 0xa7, 0xfc, 0x15, 0xab, 0xfd, 0x15, 0xaf, + 0xfd, 0x15, 0xb3, 0xfe, 0x15, 0xb7, 0xfe, 0x15, 0xbb, 0xff, 0x15, 0xc0, 0xff, 0x15, 0xc4, 0xff, + 0x15, 0xc8, 0xff, 0x15, 0xcc, 0xff, 0x15, 0xd0, 0xff, 0x15, 0xd4, 0xff, 0x15, 0xd8, 0xff, 0x15 +}; +static constexpr std::array L06 = { + 0x00, 0x01, 0x4e, 0x00, 0x01, 0x50, 0x00, 0x02, 0x52, 0x00, 0x02, 0x54, 0x00, 0x02, 0x56, 0x00, + 0x03, 0x58, 0x00, 0x03, 0x5a, 0x00, 0x03, 0x5c, 0x00, 0x03, 0x5e, 0x00, 0x03, 0x60, 0x01, 0x03, + 0x62, 0x02, 0x03, 0x64, 0x02, 0x03, 0x66, 0x03, 0x03, 0x68, 0x04, 0x02, 0x6a, 0x05, 0x02, 0x6c, + 0x05, 0x02, 0x6e, 0x06, 0x02, 0x70, 0x07, 0x02, 0x72, 0x08, 0x02, 0x74, 0x08, 0x02, 0x76, 0x09, + 0x02, 0x78, 0x0a, 0x02, 0x7b, 0x0b, 0x02, 0x7d, 0x0b, 0x02, 0x7f, 0x0c, 0x02, 0x81, 0x0d, 0x02, + 0x83, 0x0d, 0x02, 0x85, 0x0e, 0x02, 0x88, 0x0e, 0x01, 0x8a, 0x0f, 0x01, 0x8c, 0x0f, 0x01, 0x8e, + 0x0f, 0x01, 0x90, 0x10, 0x01, 0x93, 0x10, 0x01, 0x95, 0x10, 0x01, 0x97, 0x10, 0x01, 0x99, 0x10, + 0x02, 0x9c, 0x10, 0x02, 0x9e, 0x10, 0x02, 0xa0, 0x10, 0x02, 0xa2, 0x0f, 0x02, 0xa5, 0x0f, 0x02, + 0xa7, 0x0e, 0x03, 0xaa, 0x0d, 0x03, 0xac, 0x0d, 0x03, 0xae, 0x0c, 0x04, 0xb1, 0x0b, 0x04, 0xb3, + 0x0a, 0x04, 0xb5, 0x0a, 0x05, 0xb7, 0x09, 0x05, 0xb9, 0x09, 0x06, 0xbc, 0x08, 0x07, 0xbe, 0x08, + 0x07, 0xc0, 0x08, 0x08, 0xc2, 0x08, 0x09, 0xc4, 0x08, 0x0a, 0xc6, 0x08, 0x0a, 0xc8, 0x08, 0x0b, + 0xca, 0x08, 0x0c, 0xcc, 0x09, 0x0d, 0xce, 0x09, 0x0e, 0xd0, 0x0a, 0x0f, 0xd2, 0x0b, 0x10, 0xd4, + 0x0c, 0x11, 0xd6, 0x0d, 0x12, 0xd8, 0x0e, 0x12, 0xd9, 0x10, 0x13, 0xdb, 0x11, 0x14, 0xdd, 0x12, + 0x15, 0xdf, 0x13, 0x16, 0xe0, 0x15, 0x17, 0xe2, 0x16, 0x18, 0xe3, 0x18, 0x19, 0xe5, 0x19, 0x1a, + 0xe7, 0x1a, 0x1c, 0xe8, 0x1b, 0x1d, 0xe9, 0x1c, 0x1e, 0xeb, 0x1d, 0x1f, 0xec, 0x1f, 0x21, 0xed, + 0x20, 0x22, 0xee, 0x21, 0x24, 0xf0, 0x22, 0x25, 0xf1, 0x23, 0x26, 0xf2, 0x23, 0x28, 0xf3, 0x24, + 0x29, 0xf4, 0x25, 0x2b, 0xf4, 0x26, 0x2d, 0xf5, 0x27, 0x2e, 0xf6, 0x28, 0x30, 0xf7, 0x28, 0x31, + 0xf7, 0x29, 0x33, 0xf8, 0x2a, 0x35, 0xf8, 0x2a, 0x36, 0xf9, 0x2b, 0x38, 0xf9, 0x2b, 0x3a, 0xfa, + 0x2c, 0x3b, 0xfa, 0x2c, 0x3d, 0xfa, 0x2d, 0x3f, 0xfa, 0x2d, 0x41, 0xfb, 0x2d, 0x42, 0xfb, 0x2e, + 0x44, 0xfb, 0x2e, 0x46, 0xfb, 0x2e, 0x47, 0xfb, 0x2f, 0x49, 0xfb, 0x2f, 0x4b, 0xfb, 0x2f, 0x4c, + 0xfb, 0x2f, 0x4e, 0xfb, 0x2f, 0x4f, 0xfb, 0x2f, 0x51, 0xfb, 0x2f, 0x52, 0xfc, 0x30, 0x54, 0xfc, + 0x30, 0x56, 0xfc, 0x30, 0x57, 0xfc, 0x30, 0x59, 0xfc, 0x30, 0x5a, 0xfc, 0x30, 0x5c, 0xfc, 0x30, + 0x5d, 0xfc, 0x2f, 0x5e, 0xfc, 0x2f, 0x60, 0xfc, 0x2f, 0x61, 0xfc, 0x2f, 0x63, 0xfd, 0x2f, 0x64, + 0xfd, 0x2f, 0x66, 0xfd, 0x2e, 0x67, 0xfd, 0x2e, 0x69, 0xfd, 0x2e, 0x6a, 0xfd, 0x2e, 0x6b, 0xfd, + 0x2d, 0x6d, 0xfd, 0x2d, 0x6e, 0xfd, 0x2d, 0x70, 0xfd, 0x2c, 0x71, 0xfd, 0x2c, 0x72, 0xfd, 0x2c, + 0x74, 0xfd, 0x2c, 0x75, 0xfe, 0x2c, 0x76, 0xfe, 0x2b, 0x78, 0xfe, 0x2b, 0x79, 0xfe, 0x2b, 0x7b, + 0xfe, 0x2b, 0x7c, 0xfe, 0x2b, 0x7d, 0xfe, 0x2c, 0x7e, 0xfe, 0x2c, 0x80, 0xfe, 0x2c, 0x81, 0xfe, + 0x2c, 0x82, 0xfe, 0x2c, 0x84, 0xfe, 0x2d, 0x85, 0xfe, 0x2d, 0x86, 0xfe, 0x2d, 0x87, 0xfe, 0x2e, + 0x89, 0xfe, 0x2e, 0x8a, 0xfe, 0x2f, 0x8b, 0xfe, 0x2f, 0x8d, 0xfe, 0x30, 0x8e, 0xfe, 0x30, 0x8f, + 0xfe, 0x31, 0x90, 0xfd, 0x32, 0x92, 0xfd, 0x32, 0x93, 0xfd, 0x33, 0x94, 0xfd, 0x33, 0x95, 0xfd, + 0x34, 0x96, 0xfd, 0x34, 0x98, 0xfd, 0x35, 0x99, 0xfd, 0x35, 0x9a, 0xfd, 0x35, 0x9b, 0xfd, 0x35, + 0x9d, 0xfd, 0x36, 0x9e, 0xfd, 0x36, 0x9f, 0xfd, 0x36, 0xa0, 0xfd, 0x36, 0xa2, 0xfd, 0x36, 0xa3, + 0xfd, 0x36, 0xa4, 0xfd, 0x36, 0xa6, 0xfd, 0x36, 0xa7, 0xfd, 0x35, 0xa8, 0xfd, 0x35, 0xa9, 0xfc, + 0x35, 0xab, 0xfc, 0x35, 0xac, 0xfc, 0x34, 0xad, 0xfc, 0x34, 0xae, 0xfc, 0x33, 0xb0, 0xfc, 0x33, + 0xb1, 0xfc, 0x32, 0xb2, 0xfc, 0x31, 0xb4, 0xfc, 0x31, 0xb5, 0xfc, 0x30, 0xb6, 0xfc, 0x2f, 0xb7, + 0xfc, 0x2e, 0xb9, 0xfc, 0x2e, 0xba, 0xfc, 0x2d, 0xbb, 0xfc, 0x2c, 0xbc, 0xfc, 0x2c, 0xbe, 0xfc, + 0x2b, 0xbf, 0xfc, 0x2b, 0xc0, 0xfc, 0x2a, 0xc2, 0xfc, 0x2a, 0xc3, 0xfc, 0x2a, 0xc4, 0xfc, 0x29, + 0xc5, 0xfc, 0x29, 0xc7, 0xfc, 0x29, 0xc8, 0xfc, 0x29, 0xc9, 0xfb, 0x29, 0xca, 0xfb, 0x29, 0xcb, + 0xfb, 0x29, 0xcd, 0xfb, 0x29, 0xce, 0xfb, 0x29, 0xcf, 0xfb, 0x29, 0xd0, 0xfb, 0x2a, 0xd2, 0xfb, + 0x2a, 0xd3, 0xfb, 0x2b, 0xd4, 0xfb, 0x2b, 0xd5, 0xfb, 0x2c, 0xd6, 0xfb, 0x2c, 0xd8, 0xfa, 0x2d, + 0xd9, 0xfa, 0x2f, 0xda, 0xfa, 0x30, 0xdb, 0xfa, 0x33, 0xdc, 0xfa, 0x35, 0xdd, 0xfa, 0x38, 0xde, + 0xfa, 0x3c, 0xdf, 0xfa, 0x3f, 0xe1, 0xfa, 0x42, 0xe2, 0xf9, 0x46, 0xe3, 0xf9, 0x49, 0xe4, 0xf9, + 0x4d, 0xe5, 0xf9, 0x50, 0xe5, 0xf9, 0x54, 0xe6, 0xf9, 0x57, 0xe7, 0xf9, 0x5b, 0xe8, 0xf9, 0x5e, + 0xe9, 0xf9, 0x62, 0xea, 0xf8, 0x65, 0xeb, 0xf8, 0x69, 0xec, 0xf8, 0x6c, 0xed, 0xf8, 0x70, 0xee, + 0xf8, 0x73, 0xef, 0xf8, 0x76, 0xf0, 0xf8, 0x7a, 0xf0, 0xf8, 0x7d, 0xf1, 0xf8, 0x80, 0xf2, 0xf7, + 0x84, 0xf3, 0xf7, 0x87, 0xf4, 0xf7, 0x8a, 0xf5, 0xf7, 0x8e, 0xf5, 0xf7, 0x91, 0xf6, 0xf7, 0x94, + 0xf7, 0xf7, 0x97, 0xf8, 0xf7, 0x9a, 0xf9, 0xf6, 0x9d, 0xf9, 0xf6, 0xa1, 0xfa, 0xf6, 0xa4, 0xfb, + 0xf6, 0xa7, 0xfc, 0xf6, 0xaa, 0xfd, 0xf6, 0xad, 0xfd, 0xf6, 0xb0, 0xfe, 0xf6, 0xb3, 0xff, 0xf6 +}; +static constexpr std::array L07 = { + 0x00, 0x02, 0x4b, 0x00, 0x03, 0x4d, 0x00, 0x03, 0x4f, 0x00, 0x04, 0x51, 0x00, 0x04, 0x53, 0x00, + 0x04, 0x55, 0x00, 0x05, 0x58, 0x00, 0x05, 0x5a, 0x00, 0x05, 0x5c, 0x00, 0x05, 0x5e, 0x00, 0x05, + 0x60, 0x00, 0x05, 0x62, 0x00, 0x05, 0x64, 0x00, 0x05, 0x66, 0x00, 0x05, 0x68, 0x01, 0x05, 0x6a, + 0x01, 0x05, 0x6d, 0x01, 0x05, 0x6f, 0x01, 0x05, 0x71, 0x02, 0x05, 0x73, 0x02, 0x05, 0x75, 0x02, + 0x05, 0x77, 0x03, 0x05, 0x79, 0x03, 0x05, 0x7c, 0x03, 0x05, 0x7e, 0x04, 0x05, 0x80, 0x04, 0x05, + 0x82, 0x04, 0x05, 0x84, 0x04, 0x06, 0x87, 0x05, 0x06, 0x89, 0x05, 0x06, 0x8b, 0x05, 0x06, 0x8d, + 0x05, 0x06, 0x90, 0x06, 0x06, 0x92, 0x06, 0x06, 0x94, 0x06, 0x06, 0x96, 0x06, 0x06, 0x99, 0x06, + 0x06, 0x9b, 0x06, 0x06, 0x9d, 0x06, 0x06, 0x9f, 0x06, 0x06, 0xa2, 0x06, 0x07, 0xa4, 0x05, 0x07, + 0xa6, 0x05, 0x07, 0xa9, 0x05, 0x07, 0xab, 0x05, 0x07, 0xad, 0x05, 0x08, 0xaf, 0x05, 0x08, 0xb2, + 0x05, 0x08, 0xb4, 0x05, 0x08, 0xb6, 0x05, 0x09, 0xb8, 0x06, 0x09, 0xba, 0x06, 0x0a, 0xbd, 0x07, + 0x0a, 0xbf, 0x08, 0x0a, 0xc1, 0x09, 0x0b, 0xc3, 0x0b, 0x0b, 0xc5, 0x0c, 0x0c, 0xc7, 0x0d, 0x0c, + 0xc9, 0x0f, 0x0d, 0xcb, 0x10, 0x0d, 0xcd, 0x12, 0x0e, 0xcf, 0x13, 0x0e, 0xd1, 0x15, 0x0f, 0xd3, + 0x16, 0x0f, 0xd5, 0x18, 0x10, 0xd6, 0x19, 0x11, 0xd8, 0x1b, 0x11, 0xda, 0x1d, 0x12, 0xdc, 0x1e, + 0x12, 0xde, 0x20, 0x13, 0xdf, 0x22, 0x14, 0xe1, 0x24, 0x14, 0xe3, 0x26, 0x15, 0xe4, 0x28, 0x15, + 0xe6, 0x2a, 0x16, 0xe7, 0x2c, 0x16, 0xe9, 0x2f, 0x17, 0xea, 0x31, 0x17, 0xec, 0x34, 0x18, 0xed, + 0x37, 0x18, 0xee, 0x39, 0x19, 0xef, 0x3c, 0x19, 0xf0, 0x3f, 0x19, 0xf2, 0x42, 0x1a, 0xf3, 0x45, + 0x1a, 0xf4, 0x48, 0x1a, 0xf5, 0x4b, 0x1b, 0xf5, 0x4d, 0x1b, 0xf6, 0x50, 0x1b, 0xf7, 0x53, 0x1b, + 0xf8, 0x56, 0x1b, 0xf8, 0x59, 0x1c, 0xf9, 0x5d, 0x1c, 0xfa, 0x60, 0x1c, 0xfa, 0x63, 0x1c, 0xfa, + 0x66, 0x1c, 0xfb, 0x69, 0x1c, 0xfb, 0x6c, 0x1c, 0xfb, 0x6f, 0x1c, 0xfc, 0x72, 0x1c, 0xfc, 0x75, + 0x1c, 0xfc, 0x78, 0x1c, 0xfc, 0x7b, 0x1c, 0xfc, 0x7e, 0x1c, 0xfc, 0x80, 0x1c, 0xfd, 0x83, 0x1c, + 0xfd, 0x86, 0x1c, 0xfd, 0x89, 0x1c, 0xfd, 0x8b, 0x1c, 0xfd, 0x8e, 0x1c, 0xfd, 0x91, 0x1c, 0xfd, + 0x93, 0x1d, 0xfd, 0x96, 0x1d, 0xfe, 0x99, 0x1d, 0xfe, 0x9b, 0x1d, 0xfe, 0x9e, 0x1d, 0xfe, 0xa0, + 0x1d, 0xfe, 0xa3, 0x1d, 0xfe, 0xa5, 0x1d, 0xfe, 0xa8, 0x1d, 0xfe, 0xaa, 0x1d, 0xfe, 0xad, 0x1d, + 0xfe, 0xaf, 0x1d, 0xfe, 0xb1, 0x1d, 0xfe, 0xb4, 0x1d, 0xfe, 0xb6, 0x1c, 0xfe, 0xb9, 0x1c, 0xfe, + 0xbb, 0x1c, 0xfe, 0xbd, 0x1d, 0xfe, 0xc0, 0x1d, 0xfe, 0xc2, 0x1d, 0xfe, 0xc4, 0x1d, 0xfe, 0xc6, + 0x1e, 0xfe, 0xc8, 0x1e, 0xfe, 0xca, 0x1f, 0xfe, 0xcc, 0x20, 0xfe, 0xce, 0x21, 0xfe, 0xd0, 0x22, + 0xfe, 0xd2, 0x23, 0xfe, 0xd4, 0x24, 0xfe, 0xd6, 0x25, 0xfe, 0xd7, 0x26, 0xfe, 0xd9, 0x27, 0xfe, + 0xdb, 0x29, 0xfe, 0xdc, 0x2a, 0xfe, 0xde, 0x2c, 0xfe, 0xe0, 0x2d, 0xfe, 0xe1, 0x2e, 0xfe, 0xe3, + 0x30, 0xfe, 0xe4, 0x32, 0xfe, 0xe5, 0x33, 0xfe, 0xe7, 0x35, 0xfe, 0xe8, 0x37, 0xfe, 0xe9, 0x38, + 0xfe, 0xeb, 0x3a, 0xfe, 0xec, 0x3c, 0xfe, 0xed, 0x3e, 0xfe, 0xee, 0x3f, 0xfe, 0xef, 0x41, 0xfe, + 0xf0, 0x43, 0xfe, 0xf1, 0x45, 0xfe, 0xf2, 0x47, 0xfe, 0xf3, 0x49, 0xfe, 0xf4, 0x4b, 0xfe, 0xf5, + 0x4d, 0xfe, 0xf6, 0x4f, 0xfe, 0xf7, 0x51, 0xfe, 0xf8, 0x53, 0xfe, 0xf8, 0x55, 0xfe, 0xf9, 0x57, + 0xfe, 0xfa, 0x59, 0xfe, 0xfa, 0x5b, 0xfe, 0xfb, 0x5d, 0xfe, 0xfb, 0x5f, 0xfe, 0xfc, 0x61, 0xfe, + 0xfc, 0x63, 0xfe, 0xfc, 0x65, 0xfe, 0xfd, 0x67, 0xfe, 0xfd, 0x6a, 0xfe, 0xfd, 0x6c, 0xfd, 0xfd, + 0x6e, 0xfd, 0xfe, 0x70, 0xfd, 0xfe, 0x72, 0xfd, 0xfe, 0x74, 0xfd, 0xfe, 0x76, 0xfd, 0xfe, 0x78, + 0xfd, 0xfe, 0x7b, 0xfd, 0xfe, 0x7d, 0xfd, 0xfe, 0x7f, 0xfd, 0xfe, 0x81, 0xfd, 0xfe, 0x83, 0xfd, + 0xfe, 0x85, 0xfd, 0xfe, 0x87, 0xfd, 0xfe, 0x88, 0xfd, 0xfe, 0x8a, 0xfd, 0xfe, 0x8c, 0xfd, 0xfe, + 0x8e, 0xfd, 0xfe, 0x90, 0xfd, 0xfe, 0x92, 0xfd, 0xfe, 0x94, 0xfd, 0xfe, 0x95, 0xfd, 0xfe, 0x97, + 0xfd, 0xfe, 0x99, 0xfd, 0xfe, 0x9b, 0xfd, 0xfe, 0x9c, 0xfd, 0xfe, 0x9e, 0xfd, 0xfe, 0xa0, 0xfd, + 0xfe, 0xa2, 0xfd, 0xfe, 0xa3, 0xfd, 0xfe, 0xa5, 0xfd, 0xfe, 0xa7, 0xfd, 0xfe, 0xa8, 0xfd, 0xfe, + 0xaa, 0xfd, 0xfe, 0xac, 0xfd, 0xfe, 0xad, 0xfd, 0xfe, 0xaf, 0xfd, 0xfe, 0xb1, 0xfe, 0xfe, 0xb2, + 0xfe, 0xfe, 0xb4, 0xfe, 0xfe, 0xb5, 0xfe, 0xfe, 0xb7, 0xfe, 0xfe, 0xb9, 0xfe, 0xfe, 0xba, 0xfe, + 0xfe, 0xbc, 0xfe, 0xfe, 0xbd, 0xfe, 0xfe, 0xbf, 0xfe, 0xfe, 0xc1, 0xfe, 0xfe, 0xc2, 0xfe, 0xff, + 0xc4, 0xfe, 0xff, 0xc5, 0xfe, 0xff, 0xc7, 0xfe, 0xff, 0xc8, 0xfe, 0xff, 0xca, 0xfe, 0xff, 0xcb, + 0xfe, 0xff, 0xcd, 0xfe, 0xff, 0xce, 0xfe, 0xff, 0xd0, 0xfe, 0xff, 0xd1, 0xfe, 0xff, 0xd3, 0xfe, + 0xff, 0xd4, 0xfe, 0xff, 0xd6, 0xfe, 0xff, 0xd7, 0xfe, 0xff, 0xd9, 0xfe, 0xff, 0xda, 0xfe, 0xff, + 0xdc, 0xfe, 0xff, 0xdd, 0xfe, 0xff, 0xdf, 0xfe, 0xff, 0xe0, 0xfe, 0xff, 0xe2, 0xfe, 0xff, 0xe3, + 0xfe, 0xff, 0xe5, 0xfe, 0xfe, 0xe6, 0xfe, 0xfe, 0xe8, 0xfe, 0xfe, 0xe9, 0xfe, 0xfe, 0xeb, 0xfe +}; +static constexpr std::array L08 = { + 0x00, 0x0f, 0x5d, 0x01, 0x0f, 0x5e, 0x01, 0x10, 0x60, 0x01, 0x10, 0x62, 0x01, 0x11, 0x63, 0x02, + 0x11, 0x65, 0x02, 0x12, 0x67, 0x03, 0x12, 0x68, 0x04, 0x12, 0x6a, 0x05, 0x13, 0x6b, 0x06, 0x13, + 0x6d, 0x07, 0x14, 0x6f, 0x08, 0x14, 0x70, 0x0a, 0x15, 0x72, 0x0c, 0x15, 0x73, 0x0d, 0x15, 0x75, + 0x0f, 0x16, 0x76, 0x11, 0x16, 0x77, 0x12, 0x16, 0x79, 0x14, 0x17, 0x7a, 0x16, 0x17, 0x7c, 0x18, + 0x17, 0x7d, 0x19, 0x18, 0x7e, 0x1b, 0x18, 0x80, 0x1d, 0x18, 0x81, 0x1f, 0x19, 0x82, 0x21, 0x19, + 0x83, 0x23, 0x19, 0x85, 0x25, 0x19, 0x86, 0x27, 0x1a, 0x87, 0x29, 0x1a, 0x88, 0x2b, 0x1a, 0x89, + 0x2e, 0x1a, 0x8a, 0x30, 0x1a, 0x8b, 0x32, 0x1b, 0x8c, 0x34, 0x1b, 0x8d, 0x37, 0x1b, 0x8e, 0x39, + 0x1b, 0x8f, 0x3b, 0x1b, 0x8f, 0x3e, 0x1b, 0x90, 0x40, 0x1b, 0x90, 0x43, 0x1a, 0x91, 0x46, 0x1a, + 0x91, 0x48, 0x1a, 0x92, 0x4b, 0x1a, 0x92, 0x4e, 0x19, 0x92, 0x51, 0x19, 0x92, 0x54, 0x19, 0x92, + 0x56, 0x18, 0x92, 0x59, 0x18, 0x92, 0x5c, 0x17, 0x92, 0x5e, 0x17, 0x92, 0x61, 0x17, 0x92, 0x63, + 0x16, 0x92, 0x66, 0x16, 0x92, 0x68, 0x15, 0x92, 0x6b, 0x15, 0x92, 0x6d, 0x14, 0x92, 0x6f, 0x14, + 0x92, 0x72, 0x13, 0x92, 0x74, 0x13, 0x92, 0x76, 0x12, 0x91, 0x79, 0x12, 0x91, 0x7b, 0x11, 0x91, + 0x7d, 0x11, 0x91, 0x7f, 0x10, 0x91, 0x81, 0x10, 0x91, 0x83, 0x0f, 0x90, 0x86, 0x0f, 0x90, 0x88, + 0x0e, 0x90, 0x8a, 0x0e, 0x90, 0x8c, 0x0d, 0x8f, 0x8e, 0x0d, 0x8f, 0x90, 0x0d, 0x8f, 0x92, 0x0c, + 0x8e, 0x94, 0x0c, 0x8e, 0x96, 0x0b, 0x8e, 0x98, 0x0b, 0x8d, 0x9a, 0x0b, 0x8d, 0x9c, 0x0a, 0x8c, + 0x9e, 0x0a, 0x8c, 0xa0, 0x0a, 0x8c, 0xa2, 0x0a, 0x8b, 0xa3, 0x0a, 0x8b, 0xa5, 0x09, 0x8a, 0xa7, + 0x09, 0x8a, 0xa9, 0x09, 0x8a, 0xab, 0x09, 0x89, 0xad, 0x09, 0x89, 0xae, 0x0a, 0x88, 0xb0, 0x0a, + 0x88, 0xb2, 0x0a, 0x88, 0xb4, 0x0a, 0x87, 0xb6, 0x0a, 0x87, 0xb7, 0x0b, 0x86, 0xb9, 0x0b, 0x86, + 0xbb, 0x0c, 0x85, 0xbd, 0x0c, 0x85, 0xbe, 0x0d, 0x85, 0xc0, 0x0d, 0x84, 0xc2, 0x0e, 0x84, 0xc3, + 0x0e, 0x83, 0xc5, 0x0f, 0x83, 0xc7, 0x10, 0x82, 0xc8, 0x10, 0x82, 0xca, 0x11, 0x81, 0xcc, 0x12, + 0x81, 0xcd, 0x13, 0x80, 0xcf, 0x14, 0x80, 0xd0, 0x15, 0x7f, 0xd2, 0x16, 0x7f, 0xd3, 0x17, 0x7e, + 0xd5, 0x19, 0x7d, 0xd6, 0x1a, 0x7d, 0xd8, 0x1c, 0x7c, 0xd9, 0x1d, 0x7b, 0xda, 0x1f, 0x7b, 0xdc, + 0x20, 0x7a, 0xdd, 0x22, 0x79, 0xde, 0x23, 0x78, 0xdf, 0x25, 0x78, 0xe0, 0x27, 0x77, 0xe2, 0x29, + 0x76, 0xe3, 0x2a, 0x75, 0xe4, 0x2c, 0x74, 0xe5, 0x2e, 0x73, 0xe6, 0x30, 0x72, 0xe7, 0x31, 0x72, + 0xe8, 0x33, 0x71, 0xe9, 0x35, 0x70, 0xea, 0x37, 0x6f, 0xeb, 0x39, 0x6e, 0xec, 0x3b, 0x6c, 0xed, + 0x3d, 0x6b, 0xed, 0x3e, 0x6a, 0xee, 0x40, 0x69, 0xef, 0x42, 0x68, 0xf0, 0x44, 0x67, 0xf0, 0x46, + 0x66, 0xf1, 0x48, 0x65, 0xf2, 0x4a, 0x64, 0xf2, 0x4c, 0x62, 0xf3, 0x4d, 0x61, 0xf3, 0x4f, 0x60, + 0xf4, 0x51, 0x5f, 0xf4, 0x53, 0x5e, 0xf5, 0x55, 0x5d, 0xf5, 0x57, 0x5c, 0xf6, 0x58, 0x5c, 0xf6, + 0x5a, 0x5b, 0xf7, 0x5c, 0x5a, 0xf7, 0x5e, 0x59, 0xf7, 0x60, 0x58, 0xf8, 0x62, 0x57, 0xf8, 0x64, + 0x56, 0xf8, 0x65, 0x55, 0xf8, 0x67, 0x55, 0xf8, 0x69, 0x54, 0xf9, 0x6b, 0x53, 0xf9, 0x6d, 0x52, + 0xf9, 0x6f, 0x52, 0xf9, 0x70, 0x51, 0xf9, 0x72, 0x50, 0xf9, 0x74, 0x4f, 0xf9, 0x76, 0x4f, 0xf9, + 0x78, 0x4e, 0xf9, 0x7a, 0x4d, 0xf9, 0x7b, 0x4d, 0xf9, 0x7d, 0x4c, 0xf9, 0x7f, 0x4c, 0xf9, 0x81, + 0x4b, 0xf9, 0x82, 0x4a, 0xf9, 0x84, 0x4a, 0xf9, 0x86, 0x49, 0xf9, 0x87, 0x48, 0xf9, 0x89, 0x48, + 0xf9, 0x8a, 0x47, 0xf9, 0x8c, 0x46, 0xf9, 0x8e, 0x46, 0xf9, 0x8f, 0x45, 0xf9, 0x91, 0x44, 0xf9, + 0x92, 0x44, 0xf9, 0x94, 0x43, 0xf9, 0x95, 0x42, 0xf9, 0x97, 0x42, 0xfa, 0x98, 0x41, 0xfa, 0x9a, + 0x41, 0xfa, 0x9b, 0x40, 0xfa, 0x9d, 0x3f, 0xfa, 0x9e, 0x3f, 0xfa, 0x9f, 0x3e, 0xfa, 0xa1, 0x3d, + 0xfb, 0xa2, 0x3d, 0xfb, 0xa4, 0x3c, 0xfb, 0xa5, 0x3b, 0xfb, 0xa6, 0x3b, 0xfb, 0xa8, 0x3a, 0xfc, + 0xa9, 0x39, 0xfc, 0xab, 0x39, 0xfc, 0xac, 0x39, 0xfc, 0xad, 0x38, 0xfc, 0xaf, 0x38, 0xfc, 0xb0, + 0x38, 0xfc, 0xb1, 0x38, 0xfc, 0xb3, 0x38, 0xfc, 0xb4, 0x38, 0xfc, 0xb6, 0x38, 0xfd, 0xb7, 0x38, + 0xfd, 0xb8, 0x38, 0xfd, 0xba, 0x38, 0xfd, 0xbb, 0x38, 0xfd, 0xbd, 0x38, 0xfd, 0xbe, 0x38, 0xfd, + 0xbf, 0x38, 0xfd, 0xc1, 0x39, 0xfd, 0xc2, 0x39, 0xfc, 0xc3, 0x39, 0xfc, 0xc5, 0x39, 0xfc, 0xc6, + 0x3a, 0xfc, 0xc8, 0x3a, 0xfc, 0xc9, 0x3a, 0xfc, 0xca, 0x3b, 0xfc, 0xcc, 0x3b, 0xfc, 0xcd, 0x3b, + 0xfc, 0xce, 0x3c, 0xfc, 0xd0, 0x3c, 0xfc, 0xd1, 0x3d, 0xfc, 0xd3, 0x3d, 0xfb, 0xd4, 0x3e, 0xfb, + 0xd5, 0x3e, 0xfb, 0xd7, 0x3f, 0xfb, 0xd8, 0x3f, 0xfb, 0xd9, 0x40, 0xfb, 0xdb, 0x40, 0xfb, 0xdc, + 0x41, 0xfa, 0xde, 0x41, 0xfa, 0xdf, 0x42, 0xfa, 0xe0, 0x42, 0xfa, 0xe2, 0x43, 0xfa, 0xe3, 0x43, + 0xf9, 0xe4, 0x44, 0xf9, 0xe6, 0x45, 0xf9, 0xe7, 0x45, 0xf9, 0xe8, 0x46, 0xf8, 0xea, 0x46, 0xf8, + 0xeb, 0x47, 0xf8, 0xed, 0x48, 0xf8, 0xee, 0x48, 0xf7, 0xef, 0x49, 0xf7, 0xf1, 0x4a, 0xf7, 0xf2, + 0x4a, 0xf7, 0xf3, 0x4b, 0xf6, 0xf5, 0x4c, 0xf6, 0xf6, 0x4c, 0xf6, 0xf7, 0x4d, 0xf5, 0xf9, 0x4e +}; +static constexpr std::array L09 = { + 0x05, 0x00, 0xac, 0x06, 0x02, 0xac, 0x06, 0x05, 0xac, 0x07, 0x08, 0xad, 0x07, 0x0b, 0xad, 0x08, + 0x0e, 0xad, 0x08, 0x10, 0xae, 0x08, 0x12, 0xae, 0x09, 0x14, 0xae, 0x09, 0x16, 0xaf, 0x0a, 0x18, + 0xaf, 0x0a, 0x1a, 0xaf, 0x0a, 0x1c, 0xb0, 0x0b, 0x1d, 0xb0, 0x0b, 0x1f, 0xb0, 0x0b, 0x20, 0xb1, + 0x0c, 0x22, 0xb1, 0x0c, 0x23, 0xb1, 0x0c, 0x25, 0xb1, 0x0c, 0x26, 0xb2, 0x0d, 0x28, 0xb2, 0x0d, + 0x29, 0xb2, 0x0d, 0x2a, 0xb2, 0x0d, 0x2c, 0xb3, 0x0d, 0x2d, 0xb3, 0x0d, 0x2e, 0xb3, 0x0d, 0x30, + 0xb3, 0x0e, 0x31, 0xb4, 0x0e, 0x32, 0xb4, 0x0e, 0x33, 0xb4, 0x0e, 0x35, 0xb4, 0x0e, 0x36, 0xb4, + 0x0e, 0x37, 0xb4, 0x0e, 0x38, 0xb4, 0x0e, 0x3a, 0xb5, 0x0e, 0x3b, 0xb5, 0x0e, 0x3c, 0xb5, 0x0e, + 0x3d, 0xb5, 0x0e, 0x3e, 0xb5, 0x0e, 0x40, 0xb5, 0x0d, 0x41, 0xb5, 0x0d, 0x42, 0xb5, 0x0d, 0x43, + 0xb5, 0x0d, 0x44, 0xb5, 0x0d, 0x46, 0xb5, 0x0d, 0x47, 0xb5, 0x0d, 0x48, 0xb5, 0x0c, 0x49, 0xb5, + 0x0c, 0x4a, 0xb5, 0x0c, 0x4c, 0xb4, 0x0c, 0x4d, 0xb4, 0x0b, 0x4e, 0xb4, 0x0b, 0x4f, 0xb4, 0x0b, + 0x50, 0xb4, 0x0a, 0x51, 0xb3, 0x0a, 0x53, 0xb3, 0x0a, 0x54, 0xb3, 0x09, 0x55, 0xb2, 0x09, 0x56, + 0xb2, 0x08, 0x57, 0xb1, 0x08, 0x59, 0xb1, 0x08, 0x5a, 0xb0, 0x07, 0x5b, 0xaf, 0x07, 0x5c, 0xae, + 0x06, 0x5e, 0xae, 0x06, 0x5f, 0xad, 0x06, 0x60, 0xac, 0x06, 0x61, 0xaa, 0x06, 0x63, 0xa9, 0x07, + 0x64, 0xa8, 0x08, 0x65, 0xa7, 0x0a, 0x66, 0xa5, 0x0c, 0x67, 0xa4, 0x0d, 0x68, 0xa3, 0x0f, 0x6a, + 0xa1, 0x11, 0x6b, 0xa0, 0x13, 0x6c, 0x9e, 0x14, 0x6d, 0x9c, 0x16, 0x6e, 0x9b, 0x18, 0x6f, 0x99, + 0x19, 0x71, 0x98, 0x1b, 0x72, 0x96, 0x1d, 0x73, 0x94, 0x1e, 0x74, 0x92, 0x1f, 0x75, 0x91, 0x21, + 0x76, 0x8f, 0x22, 0x77, 0x8d, 0x23, 0x78, 0x8b, 0x24, 0x79, 0x89, 0x25, 0x7a, 0x87, 0x26, 0x7c, + 0x85, 0x27, 0x7d, 0x83, 0x28, 0x7e, 0x81, 0x29, 0x7f, 0x7f, 0x2a, 0x80, 0x7d, 0x2b, 0x81, 0x7b, + 0x2c, 0x82, 0x79, 0x2c, 0x83, 0x77, 0x2d, 0x84, 0x75, 0x2e, 0x85, 0x72, 0x2e, 0x86, 0x70, 0x2e, + 0x87, 0x6e, 0x2f, 0x89, 0x6c, 0x2f, 0x8a, 0x69, 0x30, 0x8b, 0x67, 0x30, 0x8c, 0x64, 0x30, 0x8d, + 0x62, 0x30, 0x8e, 0x60, 0x30, 0x8f, 0x5d, 0x31, 0x90, 0x5b, 0x31, 0x91, 0x59, 0x31, 0x92, 0x56, + 0x32, 0x93, 0x54, 0x32, 0x94, 0x52, 0x33, 0x95, 0x50, 0x34, 0x96, 0x4e, 0x34, 0x97, 0x4c, 0x35, + 0x98, 0x4a, 0x36, 0x99, 0x48, 0x37, 0x9a, 0x47, 0x38, 0x9b, 0x45, 0x39, 0x9c, 0x43, 0x3a, 0x9d, + 0x41, 0x3b, 0x9d, 0x40, 0x3c, 0x9e, 0x3e, 0x3d, 0x9f, 0x3c, 0x3e, 0xa0, 0x3b, 0x40, 0xa1, 0x39, + 0x41, 0xa2, 0x37, 0x42, 0xa3, 0x36, 0x44, 0xa4, 0x34, 0x45, 0xa4, 0x33, 0x47, 0xa5, 0x31, 0x48, + 0xa6, 0x30, 0x4a, 0xa7, 0x2e, 0x4c, 0xa8, 0x2d, 0x4d, 0xa8, 0x2c, 0x4f, 0xa9, 0x2a, 0x51, 0xaa, + 0x29, 0x52, 0xab, 0x27, 0x54, 0xac, 0x26, 0x56, 0xac, 0x24, 0x58, 0xad, 0x23, 0x59, 0xae, 0x22, + 0x5b, 0xaf, 0x20, 0x5d, 0xaf, 0x1f, 0x5f, 0xb0, 0x1e, 0x61, 0xb1, 0x1c, 0x63, 0xb2, 0x1b, 0x65, + 0xb2, 0x1a, 0x67, 0xb3, 0x18, 0x69, 0xb4, 0x17, 0x6b, 0xb4, 0x16, 0x6d, 0xb5, 0x14, 0x6f, 0xb6, + 0x13, 0x71, 0xb6, 0x12, 0x73, 0xb7, 0x10, 0x75, 0xb8, 0x0f, 0x77, 0xb8, 0x0e, 0x79, 0xb9, 0x0c, + 0x7b, 0xba, 0x0b, 0x7d, 0xba, 0x0a, 0x7f, 0xbb, 0x08, 0x82, 0xbc, 0x07, 0x84, 0xbc, 0x06, 0x86, + 0xbd, 0x06, 0x88, 0xbe, 0x05, 0x8a, 0xbe, 0x04, 0x8c, 0xbf, 0x04, 0x8f, 0xbf, 0x03, 0x91, 0xc0, + 0x03, 0x93, 0xc0, 0x03, 0x95, 0xc1, 0x02, 0x98, 0xc2, 0x02, 0x9a, 0xc2, 0x02, 0x9c, 0xc3, 0x02, + 0x9e, 0xc3, 0x02, 0xa0, 0xc4, 0x03, 0xa2, 0xc4, 0x03, 0xa5, 0xc5, 0x03, 0xa7, 0xc6, 0x03, 0xa9, + 0xc6, 0x03, 0xab, 0xc7, 0x04, 0xad, 0xc7, 0x04, 0xaf, 0xc8, 0x04, 0xb1, 0xc8, 0x05, 0xb3, 0xc9, + 0x05, 0xb5, 0xca, 0x06, 0xb7, 0xca, 0x06, 0xb9, 0xcb, 0x07, 0xbb, 0xcb, 0x08, 0xbd, 0xcc, 0x09, + 0xbf, 0xcc, 0x0a, 0xc1, 0xcd, 0x0b, 0xc2, 0xce, 0x0c, 0xc4, 0xce, 0x0d, 0xc6, 0xcf, 0x0e, 0xc8, + 0xcf, 0x0f, 0xca, 0xd0, 0x10, 0xcc, 0xd1, 0x11, 0xcd, 0xd1, 0x12, 0xcf, 0xd2, 0x13, 0xd1, 0xd2, + 0x14, 0xd3, 0xd3, 0x15, 0xd4, 0xd4, 0x17, 0xd6, 0xd4, 0x18, 0xd8, 0xd5, 0x19, 0xd9, 0xd6, 0x1a, + 0xdb, 0xd6, 0x1c, 0xdd, 0xd7, 0x1d, 0xde, 0xd7, 0x1e, 0xe0, 0xd8, 0x20, 0xe1, 0xd9, 0x21, 0xe3, + 0xda, 0x22, 0xe4, 0xda, 0x24, 0xe6, 0xdb, 0x25, 0xe7, 0xdc, 0x27, 0xe9, 0xdc, 0x28, 0xea, 0xdd, + 0x2a, 0xeb, 0xde, 0x2c, 0xec, 0xdf, 0x2d, 0xee, 0xdf, 0x2f, 0xef, 0xe0, 0x31, 0xf0, 0xe1, 0x33, + 0xf1, 0xe2, 0x34, 0xf2, 0xe3, 0x36, 0xf3, 0xe3, 0x38, 0xf3, 0xe4, 0x3b, 0xf4, 0xe5, 0x3d, 0xf5, + 0xe6, 0x3f, 0xf5, 0xe7, 0x42, 0xf6, 0xe8, 0x45, 0xf6, 0xe9, 0x48, 0xf7, 0xea, 0x4b, 0xf8, 0xeb, + 0x4f, 0xf8, 0xec, 0x53, 0xf9, 0xed, 0x58, 0xfa, 0xed, 0x5d, 0xfa, 0xee, 0x62, 0xfb, 0xef, 0x67, + 0xfc, 0xf0, 0x6d, 0xfc, 0xf1, 0x73, 0xfd, 0xf1, 0x79, 0xfd, 0xf2, 0x80, 0xfe, 0xf3, 0x87, 0xfe, + 0xf3, 0x8e, 0xff, 0xf4, 0x96, 0xff, 0xf5, 0x9f, 0xff, 0xf5, 0xa8, 0xff, 0xf6, 0xb1, 0xff, 0xf7, + 0xbb, 0xff, 0xf7, 0xc6, 0xfe, 0xf8, 0xd2, 0xfd, 0xf8, 0xde, 0xfb, 0xf9, 0xeb, 0xf9, 0xf9, 0xf9 +}; +static constexpr std::array L10 = { + 0x66, 0x9b, 0x90, 0x66, 0x9b, 0x8f, 0x67, 0x9b, 0x8f, 0x68, 0x9b, 0x8f, 0x69, 0x9c, 0x8e, 0x69, + 0x9c, 0x8e, 0x6a, 0x9c, 0x8d, 0x6b, 0x9c, 0x8d, 0x6b, 0x9d, 0x8c, 0x6c, 0x9d, 0x8c, 0x6d, 0x9d, + 0x8b, 0x6e, 0x9d, 0x8b, 0x6e, 0x9d, 0x8a, 0x6f, 0x9e, 0x8a, 0x70, 0x9e, 0x89, 0x71, 0x9e, 0x89, + 0x71, 0x9e, 0x89, 0x72, 0x9f, 0x88, 0x73, 0x9f, 0x88, 0x74, 0x9f, 0x87, 0x74, 0x9f, 0x87, 0x75, + 0x9f, 0x86, 0x76, 0xa0, 0x86, 0x77, 0xa0, 0x85, 0x77, 0xa0, 0x85, 0x78, 0xa0, 0x85, 0x79, 0xa1, + 0x84, 0x7a, 0xa1, 0x84, 0x7b, 0xa1, 0x83, 0x7b, 0xa1, 0x83, 0x7c, 0xa1, 0x82, 0x7d, 0xa2, 0x82, + 0x7e, 0xa2, 0x81, 0x7f, 0xa2, 0x81, 0x7f, 0xa2, 0x81, 0x80, 0xa2, 0x80, 0x81, 0xa2, 0x80, 0x82, + 0xa3, 0x7f, 0x83, 0xa3, 0x7f, 0x84, 0xa3, 0x7f, 0x84, 0xa3, 0x7e, 0x85, 0xa3, 0x7e, 0x86, 0xa4, + 0x7d, 0x87, 0xa4, 0x7d, 0x88, 0xa4, 0x7d, 0x89, 0xa4, 0x7c, 0x8a, 0xa4, 0x7c, 0x8b, 0xa4, 0x7b, + 0x8c, 0xa4, 0x7b, 0x8c, 0xa5, 0x7b, 0x8d, 0xa5, 0x7a, 0x8e, 0xa5, 0x7a, 0x8f, 0xa5, 0x7a, 0x90, + 0xa5, 0x79, 0x91, 0xa5, 0x79, 0x92, 0xa5, 0x78, 0x93, 0xa5, 0x78, 0x94, 0xa6, 0x78, 0x95, 0xa6, + 0x77, 0x96, 0xa6, 0x77, 0x97, 0xa6, 0x77, 0x99, 0xa6, 0x76, 0x9a, 0xa6, 0x76, 0x9b, 0xa6, 0x76, + 0x9c, 0xa6, 0x76, 0x9d, 0xa6, 0x75, 0x9e, 0xa6, 0x75, 0x9f, 0xa6, 0x75, 0xa1, 0xa6, 0x74, 0xa2, + 0xa6, 0x74, 0xa3, 0xa6, 0x74, 0xa4, 0xa6, 0x74, 0xa6, 0xa6, 0x73, 0xa7, 0xa6, 0x73, 0xa8, 0xa6, + 0x73, 0xaa, 0xa6, 0x73, 0xab, 0xa6, 0x73, 0xac, 0xa6, 0x72, 0xae, 0xa6, 0x72, 0xaf, 0xa6, 0x72, + 0xb1, 0xa6, 0x72, 0xb2, 0xa6, 0x72, 0xb3, 0xa6, 0x72, 0xb4, 0xa6, 0x71, 0xb6, 0xa6, 0x71, 0xb7, + 0xa6, 0x71, 0xb8, 0xa6, 0x71, 0xb9, 0xa6, 0x71, 0xba, 0xa6, 0x71, 0xbb, 0xa6, 0x70, 0xbc, 0xa6, + 0x70, 0xbd, 0xa6, 0x70, 0xbf, 0xa6, 0x70, 0xc0, 0xa6, 0x70, 0xc0, 0xa6, 0x6f, 0xc1, 0xa6, 0x6f, + 0xc2, 0xa6, 0x6f, 0xc3, 0xa6, 0x6f, 0xc4, 0xa6, 0x6f, 0xc5, 0xa6, 0x6f, 0xc6, 0xa6, 0x6e, 0xc7, + 0xa6, 0x6e, 0xc7, 0xa6, 0x6e, 0xc8, 0xa7, 0x6e, 0xc9, 0xa7, 0x6e, 0xca, 0xa7, 0x6e, 0xca, 0xa7, + 0x6d, 0xcb, 0xa7, 0x6d, 0xcc, 0xa7, 0x6d, 0xcc, 0xa7, 0x6d, 0xcd, 0xa7, 0x6d, 0xcd, 0xa8, 0x6d, + 0xce, 0xa8, 0x6c, 0xcf, 0xa8, 0x6c, 0xcf, 0xa8, 0x6c, 0xd0, 0xa8, 0x6c, 0xd0, 0xa9, 0x6c, 0xd0, + 0xa9, 0x6c, 0xd1, 0xa9, 0x6b, 0xd1, 0xa9, 0x6b, 0xd2, 0xaa, 0x6b, 0xd2, 0xaa, 0x6b, 0xd2, 0xaa, + 0x6b, 0xd3, 0xaa, 0x6a, 0xd3, 0xab, 0x6a, 0xd3, 0xab, 0x6a, 0xd4, 0xab, 0x6a, 0xd4, 0xac, 0x6a, + 0xd4, 0xac, 0x6a, 0xd4, 0xac, 0x69, 0xd4, 0xad, 0x69, 0xd5, 0xad, 0x69, 0xd5, 0xad, 0x69, 0xd5, + 0xad, 0x69, 0xd5, 0xae, 0x69, 0xd5, 0xae, 0x69, 0xd5, 0xae, 0x69, 0xd6, 0xaf, 0x69, 0xd6, 0xaf, + 0x69, 0xd6, 0xaf, 0x69, 0xd6, 0xb0, 0x69, 0xd6, 0xb0, 0x6a, 0xd6, 0xb0, 0x6a, 0xd7, 0xb1, 0x6a, + 0xd7, 0xb1, 0x6a, 0xd7, 0xb1, 0x6a, 0xd7, 0xb2, 0x6b, 0xd7, 0xb2, 0x6b, 0xd7, 0xb2, 0x6b, 0xd7, + 0xb3, 0x6c, 0xd7, 0xb3, 0x6c, 0xd8, 0xb3, 0x6d, 0xd8, 0xb4, 0x6d, 0xd8, 0xb4, 0x6d, 0xd8, 0xb4, + 0x6e, 0xd8, 0xb5, 0x6e, 0xd8, 0xb5, 0x6f, 0xd8, 0xb5, 0x70, 0xd8, 0xb6, 0x70, 0xd8, 0xb6, 0x71, + 0xd8, 0xb6, 0x71, 0xd8, 0xb7, 0x72, 0xd8, 0xb7, 0x73, 0xd8, 0xb7, 0x73, 0xd9, 0xb8, 0x74, 0xd9, + 0xb8, 0x75, 0xd9, 0xb8, 0x76, 0xd9, 0xb8, 0x76, 0xd9, 0xb9, 0x77, 0xd9, 0xb9, 0x78, 0xd9, 0xb9, + 0x79, 0xd9, 0xba, 0x7a, 0xd9, 0xba, 0x7b, 0xd9, 0xba, 0x7c, 0xd9, 0xbb, 0x7d, 0xd9, 0xbb, 0x7e, + 0xd9, 0xbb, 0x7f, 0xd9, 0xbc, 0x80, 0xd8, 0xbc, 0x81, 0xd8, 0xbc, 0x82, 0xd8, 0xbd, 0x83, 0xd8, + 0xbd, 0x84, 0xd8, 0xbd, 0x85, 0xd8, 0xbe, 0x87, 0xd8, 0xbe, 0x88, 0xd8, 0xbe, 0x89, 0xd8, 0xbf, + 0x8a, 0xd8, 0xbf, 0x8b, 0xd8, 0xbf, 0x8c, 0xd8, 0xc0, 0x8d, 0xd8, 0xc0, 0x8e, 0xd8, 0xc0, 0x8f, + 0xd8, 0xc1, 0x90, 0xd8, 0xc1, 0x91, 0xd8, 0xc1, 0x92, 0xd8, 0xc2, 0x94, 0xd8, 0xc2, 0x95, 0xd8, + 0xc2, 0x96, 0xd8, 0xc3, 0x97, 0xd8, 0xc3, 0x98, 0xd8, 0xc3, 0x99, 0xd8, 0xc4, 0x9a, 0xd8, 0xc4, + 0x9b, 0xd8, 0xc4, 0x9c, 0xd7, 0xc5, 0x9d, 0xd7, 0xc5, 0x9e, 0xd7, 0xc5, 0x9f, 0xd7, 0xc5, 0xa1, + 0xd7, 0xc6, 0xa2, 0xd7, 0xc6, 0xa3, 0xd7, 0xc6, 0xa4, 0xd7, 0xc7, 0xa5, 0xd7, 0xc7, 0xa6, 0xd7, + 0xc7, 0xa7, 0xd7, 0xc8, 0xa8, 0xd7, 0xc8, 0xa9, 0xd7, 0xc8, 0xaa, 0xd7, 0xc9, 0xab, 0xd7, 0xc9, + 0xac, 0xd7, 0xc9, 0xad, 0xd7, 0xca, 0xaf, 0xd7, 0xca, 0xb0, 0xd7, 0xca, 0xb1, 0xd7, 0xca, 0xb2, + 0xd7, 0xcb, 0xb3, 0xd7, 0xcb, 0xb4, 0xd7, 0xcb, 0xb5, 0xd6, 0xcc, 0xb6, 0xd6, 0xcc, 0xb7, 0xd6, + 0xcc, 0xb8, 0xd6, 0xcd, 0xb9, 0xd6, 0xcd, 0xba, 0xd6, 0xcd, 0xbb, 0xd6, 0xce, 0xbd, 0xd6, 0xce, + 0xbe, 0xd6, 0xce, 0xbf, 0xd6, 0xce, 0xc0, 0xd6, 0xcf, 0xc1, 0xd6, 0xcf, 0xc2, 0xd6, 0xcf, 0xc3, + 0xd6, 0xd0, 0xc4, 0xd6, 0xd0, 0xc5, 0xd5, 0xd0, 0xc6, 0xd5, 0xd1, 0xc7, 0xd5, 0xd1, 0xc8, 0xd5, + 0xd1, 0xc9, 0xd5, 0xd1, 0xcb, 0xd5, 0xd2, 0xcc, 0xd5, 0xd2, 0xcd, 0xd5, 0xd2, 0xce, 0xd5, 0xd3, + 0xcf, 0xd5, 0xd3, 0xd0, 0xd5, 0xd3, 0xd1, 0xd4, 0xd4, 0xd2, 0xd4, 0xd4, 0xd3, 0xd4, 0xd4, 0xd4 +}; +static constexpr std::array L11 = { + 0x70, 0xad, 0x5c, 0x71, 0xad, 0x5c, 0x72, 0xad, 0x5c, 0x74, 0xad, 0x5c, 0x75, 0xad, 0x5c, 0x76, + 0xad, 0x5d, 0x78, 0xad, 0x5d, 0x79, 0xad, 0x5d, 0x7a, 0xae, 0x5d, 0x7c, 0xae, 0x5d, 0x7d, 0xae, + 0x5d, 0x7e, 0xae, 0x5d, 0x80, 0xae, 0x5d, 0x81, 0xae, 0x5d, 0x82, 0xae, 0x5e, 0x83, 0xae, 0x5e, + 0x85, 0xae, 0x5e, 0x86, 0xae, 0x5e, 0x87, 0xae, 0x5e, 0x88, 0xae, 0x5e, 0x8a, 0xae, 0x5e, 0x8b, + 0xae, 0x5e, 0x8c, 0xae, 0x5f, 0x8d, 0xaf, 0x5f, 0x8e, 0xaf, 0x5f, 0x90, 0xaf, 0x5f, 0x91, 0xaf, + 0x5f, 0x92, 0xaf, 0x5f, 0x93, 0xaf, 0x5f, 0x94, 0xaf, 0x5f, 0x95, 0xaf, 0x5f, 0x96, 0xaf, 0x60, + 0x98, 0xaf, 0x60, 0x99, 0xaf, 0x60, 0x9a, 0xaf, 0x60, 0x9b, 0xaf, 0x60, 0x9c, 0xaf, 0x60, 0x9d, + 0xaf, 0x60, 0x9e, 0xaf, 0x60, 0x9f, 0xaf, 0x61, 0xa0, 0xb0, 0x61, 0xa1, 0xb0, 0x61, 0xa3, 0xb0, + 0x61, 0xa4, 0xb0, 0x61, 0xa5, 0xb0, 0x61, 0xa6, 0xb0, 0x61, 0xa7, 0xb0, 0x61, 0xa8, 0xb0, 0x62, + 0xa9, 0xb0, 0x62, 0xaa, 0xb0, 0x62, 0xab, 0xb0, 0x62, 0xac, 0xb0, 0x62, 0xad, 0xb0, 0x62, 0xae, + 0xb0, 0x62, 0xaf, 0xb0, 0x62, 0xb0, 0xb0, 0x63, 0xb1, 0xb0, 0x63, 0xb2, 0xb0, 0x63, 0xb3, 0xb0, + 0x63, 0xb4, 0xb1, 0x63, 0xb5, 0xb1, 0x63, 0xb6, 0xb1, 0x63, 0xb7, 0xb1, 0x64, 0xb8, 0xb1, 0x64, + 0xb9, 0xb1, 0x64, 0xba, 0xb1, 0x64, 0xbb, 0xb1, 0x64, 0xbc, 0xb1, 0x64, 0xbd, 0xb1, 0x64, 0xbe, + 0xb1, 0x64, 0xbf, 0xb1, 0x65, 0xc0, 0xb1, 0x65, 0xc1, 0xb1, 0x65, 0xc1, 0xb1, 0x65, 0xc2, 0xb1, + 0x65, 0xc3, 0xb1, 0x65, 0xc4, 0xb1, 0x65, 0xc5, 0xb2, 0x66, 0xc6, 0xb2, 0x66, 0xc7, 0xb2, 0x66, + 0xc8, 0xb2, 0x66, 0xc9, 0xb2, 0x66, 0xca, 0xb2, 0x66, 0xca, 0xb2, 0x66, 0xcb, 0xb2, 0x66, 0xcc, + 0xb2, 0x67, 0xcd, 0xb2, 0x67, 0xce, 0xb2, 0x67, 0xcf, 0xb2, 0x67, 0xcf, 0xb2, 0x67, 0xd0, 0xb2, + 0x67, 0xd1, 0xb2, 0x67, 0xd2, 0xb3, 0x68, 0xd3, 0xb3, 0x68, 0xd4, 0xb3, 0x68, 0xd4, 0xb3, 0x68, + 0xd5, 0xb3, 0x68, 0xd6, 0xb3, 0x68, 0xd7, 0xb3, 0x68, 0xd7, 0xb3, 0x69, 0xd8, 0xb3, 0x69, 0xd9, + 0xb3, 0x69, 0xda, 0xb3, 0x69, 0xda, 0xb4, 0x69, 0xdb, 0xb4, 0x69, 0xdc, 0xb4, 0x69, 0xdc, 0xb4, + 0x6a, 0xdd, 0xb4, 0x6a, 0xde, 0xb4, 0x6a, 0xde, 0xb4, 0x6a, 0xdf, 0xb4, 0x6a, 0xe0, 0xb5, 0x6a, + 0xe0, 0xb5, 0x6b, 0xe1, 0xb5, 0x6b, 0xe1, 0xb5, 0x6b, 0xe2, 0xb5, 0x6b, 0xe2, 0xb5, 0x6b, 0xe3, + 0xb6, 0x6b, 0xe3, 0xb6, 0x6b, 0xe4, 0xb6, 0x6c, 0xe4, 0xb6, 0x6c, 0xe5, 0xb6, 0x6c, 0xe5, 0xb7, + 0x6c, 0xe5, 0xb7, 0x6c, 0xe6, 0xb7, 0x6c, 0xe6, 0xb7, 0x6d, 0xe6, 0xb8, 0x6d, 0xe6, 0xb8, 0x6d, + 0xe6, 0xb8, 0x6d, 0xe6, 0xb9, 0x6d, 0xe7, 0xb9, 0x6e, 0xe7, 0xb9, 0x6e, 0xe7, 0xba, 0x6e, 0xe7, + 0xba, 0x6e, 0xe7, 0xbb, 0x6f, 0xe7, 0xbb, 0x6f, 0xe7, 0xbb, 0x6f, 0xe7, 0xbc, 0x70, 0xe7, 0xbc, + 0x70, 0xe7, 0xbc, 0x71, 0xe7, 0xbd, 0x71, 0xe7, 0xbd, 0x71, 0xe7, 0xbd, 0x72, 0xe7, 0xbe, 0x72, + 0xe7, 0xbe, 0x73, 0xe7, 0xbe, 0x73, 0xe7, 0xbf, 0x74, 0xe7, 0xbf, 0x74, 0xe7, 0xc0, 0x75, 0xe7, + 0xc0, 0x75, 0xe7, 0xc0, 0x76, 0xe7, 0xc1, 0x77, 0xe7, 0xc1, 0x77, 0xe7, 0xc1, 0x78, 0xe7, 0xc2, + 0x79, 0xe7, 0xc2, 0x79, 0xe7, 0xc2, 0x7a, 0xe7, 0xc3, 0x7b, 0xe7, 0xc3, 0x7c, 0xe7, 0xc3, 0x7c, + 0xe7, 0xc4, 0x7d, 0xe7, 0xc4, 0x7e, 0xe7, 0xc4, 0x7f, 0xe7, 0xc5, 0x7f, 0xe7, 0xc5, 0x80, 0xe7, + 0xc5, 0x81, 0xe7, 0xc6, 0x82, 0xe7, 0xc6, 0x83, 0xe7, 0xc6, 0x84, 0xe7, 0xc7, 0x85, 0xe7, 0xc7, + 0x86, 0xe7, 0xc8, 0x87, 0xe7, 0xc8, 0x88, 0xe7, 0xc8, 0x89, 0xe7, 0xc9, 0x8a, 0xe7, 0xc9, 0x8b, + 0xe7, 0xc9, 0x8c, 0xe7, 0xca, 0x8d, 0xe7, 0xca, 0x8e, 0xe7, 0xca, 0x8f, 0xe7, 0xcb, 0x90, 0xe7, + 0xcb, 0x91, 0xe7, 0xcb, 0x93, 0xe7, 0xcc, 0x94, 0xe7, 0xcc, 0x95, 0xe7, 0xcc, 0x96, 0xe7, 0xcd, + 0x97, 0xe6, 0xcd, 0x98, 0xe6, 0xcd, 0x99, 0xe6, 0xce, 0x9a, 0xe6, 0xce, 0x9b, 0xe6, 0xce, 0x9c, + 0xe6, 0xcf, 0x9e, 0xe6, 0xcf, 0x9f, 0xe6, 0xcf, 0xa0, 0xe6, 0xd0, 0xa1, 0xe6, 0xd0, 0xa2, 0xe6, + 0xd0, 0xa3, 0xe6, 0xd0, 0xa4, 0xe6, 0xd1, 0xa5, 0xe6, 0xd1, 0xa6, 0xe6, 0xd1, 0xa7, 0xe6, 0xd2, + 0xa9, 0xe6, 0xd2, 0xaa, 0xe6, 0xd2, 0xab, 0xe6, 0xd3, 0xac, 0xe6, 0xd3, 0xad, 0xe6, 0xd3, 0xae, + 0xe6, 0xd4, 0xaf, 0xe6, 0xd4, 0xb0, 0xe5, 0xd4, 0xb1, 0xe5, 0xd5, 0xb2, 0xe5, 0xd5, 0xb3, 0xe5, + 0xd5, 0xb5, 0xe5, 0xd6, 0xb6, 0xe5, 0xd6, 0xb7, 0xe5, 0xd6, 0xb8, 0xe5, 0xd7, 0xb9, 0xe5, 0xd7, + 0xba, 0xe5, 0xd7, 0xbb, 0xe5, 0xd7, 0xbc, 0xe5, 0xd8, 0xbd, 0xe5, 0xd8, 0xbe, 0xe5, 0xd8, 0xbf, + 0xe5, 0xd9, 0xc1, 0xe5, 0xd9, 0xc2, 0xe5, 0xd9, 0xc3, 0xe5, 0xda, 0xc4, 0xe5, 0xda, 0xc5, 0xe4, + 0xda, 0xc6, 0xe4, 0xdb, 0xc7, 0xe4, 0xdb, 0xc8, 0xe4, 0xdb, 0xc9, 0xe4, 0xdc, 0xca, 0xe4, 0xdc, + 0xcb, 0xe4, 0xdc, 0xcc, 0xe4, 0xdc, 0xce, 0xe4, 0xdd, 0xcf, 0xe4, 0xdd, 0xd0, 0xe4, 0xdd, 0xd1, + 0xe4, 0xde, 0xd2, 0xe4, 0xde, 0xd3, 0xe4, 0xde, 0xd4, 0xe3, 0xdf, 0xd5, 0xe3, 0xdf, 0xd6, 0xe3, + 0xdf, 0xd7, 0xe3, 0xe0, 0xd8, 0xe3, 0xe0, 0xda, 0xe3, 0xe0, 0xdb, 0xe3, 0xe0, 0xdc, 0xe3, 0xe1, + 0xdd, 0xe3, 0xe1, 0xde, 0xe3, 0xe1, 0xdf, 0xe3, 0xe2, 0xe0, 0xe2, 0xe2, 0xe1, 0xe2, 0xe2, 0xe2 +}; +static constexpr std::array L12 = { + 0xf1, 0xf1, 0xf1, 0xf0, 0xf0, 0xf1, 0xef, 0xf0, 0xf0, 0xee, 0xef, 0xf0, 0xee, 0xef, 0xf0, 0xed, + 0xee, 0xf0, 0xec, 0xee, 0xf0, 0xeb, 0xed, 0xf0, 0xea, 0xed, 0xf0, 0xea, 0xec, 0xf0, 0xe9, 0xec, + 0xf0, 0xe8, 0xeb, 0xf0, 0xe7, 0xeb, 0xf0, 0xe7, 0xea, 0xf0, 0xe6, 0xea, 0xf0, 0xe5, 0xe9, 0xf0, + 0xe4, 0xe9, 0xf0, 0xe4, 0xe9, 0xef, 0xe3, 0xe8, 0xef, 0xe2, 0xe8, 0xef, 0xe1, 0xe7, 0xef, 0xe1, + 0xe7, 0xef, 0xe0, 0xe6, 0xef, 0xdf, 0xe6, 0xef, 0xde, 0xe5, 0xef, 0xde, 0xe5, 0xef, 0xdd, 0xe4, + 0xef, 0xdc, 0xe4, 0xef, 0xdb, 0xe3, 0xef, 0xda, 0xe3, 0xef, 0xda, 0xe2, 0xee, 0xd9, 0xe2, 0xee, + 0xd8, 0xe1, 0xee, 0xd7, 0xe1, 0xee, 0xd7, 0xe1, 0xee, 0xd6, 0xe0, 0xee, 0xd5, 0xe0, 0xee, 0xd4, + 0xdf, 0xee, 0xd4, 0xdf, 0xee, 0xd3, 0xde, 0xee, 0xd2, 0xde, 0xee, 0xd1, 0xdd, 0xee, 0xd1, 0xdd, + 0xed, 0xd0, 0xdc, 0xed, 0xcf, 0xdc, 0xed, 0xce, 0xdb, 0xed, 0xcd, 0xdb, 0xed, 0xcd, 0xda, 0xed, + 0xcc, 0xda, 0xed, 0xcb, 0xd9, 0xed, 0xca, 0xd9, 0xed, 0xca, 0xd9, 0xed, 0xc9, 0xd8, 0xec, 0xc8, + 0xd8, 0xec, 0xc7, 0xd7, 0xec, 0xc7, 0xd7, 0xec, 0xc6, 0xd6, 0xec, 0xc5, 0xd6, 0xec, 0xc4, 0xd5, + 0xec, 0xc4, 0xd5, 0xec, 0xc3, 0xd4, 0xec, 0xc2, 0xd4, 0xeb, 0xc1, 0xd3, 0xeb, 0xc0, 0xd3, 0xeb, + 0xc0, 0xd2, 0xeb, 0xbf, 0xd2, 0xeb, 0xbe, 0xd2, 0xeb, 0xbd, 0xd1, 0xeb, 0xbd, 0xd1, 0xeb, 0xbc, + 0xd0, 0xea, 0xbb, 0xd0, 0xea, 0xba, 0xcf, 0xea, 0xba, 0xcf, 0xea, 0xb9, 0xce, 0xea, 0xb8, 0xce, + 0xea, 0xb7, 0xcd, 0xea, 0xb7, 0xcd, 0xe9, 0xb6, 0xcc, 0xe9, 0xb5, 0xcc, 0xe9, 0xb4, 0xcc, 0xe9, + 0xb4, 0xcb, 0xe9, 0xb3, 0xcb, 0xe9, 0xb2, 0xca, 0xe9, 0xb1, 0xca, 0xe8, 0xb1, 0xc9, 0xe8, 0xb0, + 0xc9, 0xe8, 0xaf, 0xc8, 0xe8, 0xae, 0xc8, 0xe8, 0xae, 0xc7, 0xe7, 0xad, 0xc7, 0xe7, 0xac, 0xc6, + 0xe7, 0xab, 0xc6, 0xe7, 0xab, 0xc5, 0xe7, 0xaa, 0xc5, 0xe7, 0xa9, 0xc5, 0xe6, 0xa8, 0xc4, 0xe6, + 0xa8, 0xc4, 0xe6, 0xa7, 0xc3, 0xe6, 0xa6, 0xc3, 0xe6, 0xa6, 0xc2, 0xe5, 0xa5, 0xc2, 0xe5, 0xa4, + 0xc1, 0xe5, 0xa3, 0xc1, 0xe5, 0xa3, 0xc0, 0xe4, 0xa2, 0xc0, 0xe4, 0xa1, 0xbf, 0xe4, 0xa1, 0xbf, + 0xe4, 0xa0, 0xbf, 0xe3, 0x9f, 0xbe, 0xe3, 0x9f, 0xbe, 0xe3, 0x9e, 0xbd, 0xe2, 0x9d, 0xbd, 0xe2, + 0x9d, 0xbc, 0xe2, 0x9c, 0xbc, 0xe2, 0x9b, 0xbb, 0xe1, 0x9b, 0xbb, 0xe1, 0x9a, 0xba, 0xe1, 0x99, + 0xba, 0xe0, 0x99, 0xb9, 0xe0, 0x98, 0xb9, 0xdf, 0x98, 0xb8, 0xdf, 0x97, 0xb8, 0xdf, 0x96, 0xb7, + 0xde, 0x96, 0xb7, 0xde, 0x95, 0xb7, 0xde, 0x95, 0xb6, 0xdd, 0x94, 0xb6, 0xdd, 0x93, 0xb5, 0xdd, + 0x93, 0xb5, 0xdc, 0x92, 0xb4, 0xdc, 0x92, 0xb4, 0xdb, 0x91, 0xb3, 0xdb, 0x91, 0xb3, 0xdb, 0x90, + 0xb2, 0xda, 0x8f, 0xb2, 0xda, 0x8f, 0xb1, 0xd9, 0x8e, 0xb1, 0xd9, 0x8e, 0xb0, 0xd9, 0x8d, 0xb0, + 0xd8, 0x8d, 0xaf, 0xd8, 0x8c, 0xaf, 0xd7, 0x8b, 0xaf, 0xd7, 0x8b, 0xae, 0xd7, 0x8a, 0xae, 0xd6, + 0x8a, 0xad, 0xd6, 0x89, 0xad, 0xd5, 0x89, 0xac, 0xd5, 0x88, 0xac, 0xd4, 0x88, 0xab, 0xd4, 0x87, + 0xab, 0xd4, 0x87, 0xaa, 0xd3, 0x86, 0xaa, 0xd3, 0x85, 0xa9, 0xd2, 0x85, 0xa9, 0xd2, 0x84, 0xa8, + 0xd1, 0x84, 0xa8, 0xd1, 0x83, 0xa8, 0xd0, 0x83, 0xa7, 0xd0, 0x82, 0xa7, 0xd0, 0x82, 0xa6, 0xcf, + 0x81, 0xa6, 0xcf, 0x81, 0xa5, 0xce, 0x80, 0xa5, 0xce, 0x80, 0xa4, 0xcd, 0x7f, 0xa4, 0xcd, 0x7f, + 0xa3, 0xcc, 0x7e, 0xa3, 0xcc, 0x7e, 0xa2, 0xcb, 0x7d, 0xa2, 0xcb, 0x7d, 0xa1, 0xca, 0x7c, 0xa1, + 0xca, 0x7c, 0xa0, 0xc9, 0x7c, 0xa0, 0xc9, 0x7b, 0xa0, 0xc8, 0x7b, 0x9f, 0xc8, 0x7a, 0x9f, 0xc7, + 0x79, 0x9e, 0xc7, 0x79, 0x9e, 0xc7, 0x78, 0x9d, 0xc6, 0x78, 0x9d, 0xc6, 0x77, 0x9c, 0xc5, 0x77, + 0x9c, 0xc5, 0x76, 0x9b, 0xc5, 0x76, 0x9b, 0xc4, 0x75, 0x9a, 0xc4, 0x74, 0x9a, 0xc3, 0x74, 0x9a, + 0xc3, 0x73, 0x99, 0xc3, 0x73, 0x99, 0xc2, 0x72, 0x98, 0xc2, 0x71, 0x98, 0xc2, 0x71, 0x97, 0xc1, + 0x70, 0x97, 0xc1, 0x6f, 0x96, 0xc1, 0x6f, 0x96, 0xc0, 0x6e, 0x96, 0xc0, 0x6d, 0x95, 0xc0, 0x6d, + 0x95, 0xbf, 0x6c, 0x94, 0xbf, 0x6b, 0x94, 0xbf, 0x6b, 0x93, 0xbe, 0x6a, 0x93, 0xbe, 0x69, 0x92, + 0xbe, 0x69, 0x92, 0xbe, 0x68, 0x91, 0xbd, 0x67, 0x91, 0xbd, 0x67, 0x91, 0xbd, 0x66, 0x90, 0xbc, + 0x65, 0x90, 0xbc, 0x64, 0x8f, 0xbc, 0x64, 0x8f, 0xbc, 0x63, 0x8e, 0xbb, 0x62, 0x8e, 0xbb, 0x61, + 0x8e, 0xbb, 0x61, 0x8d, 0xbb, 0x60, 0x8d, 0xba, 0x5f, 0x8c, 0xba, 0x5e, 0x8c, 0xba, 0x5e, 0x8b, + 0xba, 0x5d, 0x8b, 0xb9, 0x5c, 0x8a, 0xb9, 0x5b, 0x8a, 0xb9, 0x5a, 0x8a, 0xb9, 0x5a, 0x89, 0xb8, + 0x59, 0x89, 0xb8, 0x58, 0x88, 0xb8, 0x57, 0x88, 0xb8, 0x56, 0x87, 0xb8, 0x55, 0x87, 0xb7, 0x54, + 0x87, 0xb7, 0x54, 0x86, 0xb7, 0x53, 0x86, 0xb7, 0x52, 0x85, 0xb6, 0x51, 0x85, 0xb6, 0x50, 0x84, + 0xb6, 0x4f, 0x84, 0xb6, 0x4e, 0x84, 0xb6, 0x4d, 0x83, 0xb5, 0x4c, 0x83, 0xb5, 0x4b, 0x82, 0xb5, + 0x4a, 0x82, 0xb5, 0x4a, 0x81, 0xb5, 0x49, 0x81, 0xb4, 0x48, 0x81, 0xb4, 0x47, 0x80, 0xb4, 0x46, + 0x80, 0xb4, 0x45, 0x7f, 0xb4, 0x43, 0x7f, 0xb3, 0x42, 0x7e, 0xb3, 0x41, 0x7e, 0xb3, 0x40, 0x7e, + 0xb3, 0x3f, 0x7d, 0xb3, 0x3e, 0x7d, 0xb2, 0x3d, 0x7c, 0xb2, 0x3c, 0x7c, 0xb2, 0x3b, 0x7c, 0xb2 +}; +static constexpr std::array L13 = { + 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x04, 0x01, 0x00, 0x06, 0x01, 0x00, 0x08, 0x02, 0x00, 0x0a, + 0x02, 0x00, 0x0c, 0x02, 0x00, 0x0e, 0x03, 0x00, 0x10, 0x03, 0x00, 0x12, 0x03, 0x00, 0x13, 0x04, + 0x00, 0x15, 0x04, 0x00, 0x16, 0x04, 0x00, 0x17, 0x04, 0x00, 0x19, 0x05, 0x00, 0x1a, 0x05, 0x00, + 0x1b, 0x05, 0x00, 0x1c, 0x05, 0x00, 0x1e, 0x06, 0x00, 0x1f, 0x06, 0x00, 0x20, 0x06, 0x00, 0x21, + 0x06, 0x00, 0x22, 0x06, 0x00, 0x23, 0x07, 0x00, 0x24, 0x07, 0x00, 0x25, 0x07, 0x00, 0x26, 0x07, + 0x00, 0x27, 0x07, 0x00, 0x28, 0x08, 0x00, 0x29, 0x08, 0x00, 0x29, 0x08, 0x00, 0x2a, 0x08, 0x00, + 0x2b, 0x08, 0x00, 0x2c, 0x08, 0x00, 0x2d, 0x08, 0x00, 0x2e, 0x09, 0x00, 0x2e, 0x09, 0x00, 0x2f, + 0x09, 0x00, 0x30, 0x09, 0x00, 0x31, 0x09, 0x00, 0x32, 0x09, 0x00, 0x32, 0x0a, 0x00, 0x33, 0x0a, + 0x00, 0x34, 0x0a, 0x00, 0x35, 0x0a, 0x00, 0x35, 0x0a, 0x00, 0x36, 0x0a, 0x00, 0x37, 0x0a, 0x00, + 0x37, 0x0a, 0x00, 0x38, 0x0b, 0x00, 0x39, 0x0b, 0x00, 0x3a, 0x0b, 0x00, 0x3a, 0x0b, 0x00, 0x3b, + 0x0b, 0x00, 0x3c, 0x0b, 0x00, 0x3d, 0x0b, 0x00, 0x3d, 0x0c, 0x00, 0x3e, 0x0c, 0x00, 0x3f, 0x0c, + 0x00, 0x40, 0x0c, 0x00, 0x40, 0x0c, 0x00, 0x41, 0x0c, 0x00, 0x42, 0x0c, 0x00, 0x43, 0x0d, 0x00, + 0x44, 0x0d, 0x00, 0x44, 0x0d, 0x00, 0x45, 0x0d, 0x00, 0x46, 0x0d, 0x00, 0x47, 0x0d, 0x00, 0x47, + 0x0d, 0x00, 0x48, 0x0e, 0x00, 0x49, 0x0e, 0x00, 0x4a, 0x0e, 0x00, 0x4a, 0x0e, 0x00, 0x4b, 0x0e, + 0x00, 0x4c, 0x0e, 0x00, 0x4d, 0x0f, 0x00, 0x4e, 0x0f, 0x00, 0x4e, 0x0f, 0x00, 0x4f, 0x0f, 0x00, + 0x50, 0x0f, 0x00, 0x51, 0x0f, 0x00, 0x51, 0x0f, 0x00, 0x52, 0x10, 0x00, 0x53, 0x10, 0x00, 0x54, + 0x10, 0x00, 0x55, 0x10, 0x00, 0x55, 0x10, 0x00, 0x56, 0x10, 0x00, 0x57, 0x10, 0x00, 0x58, 0x11, + 0x00, 0x58, 0x11, 0x00, 0x59, 0x11, 0x00, 0x5a, 0x11, 0x00, 0x5b, 0x11, 0x00, 0x5c, 0x11, 0x00, + 0x5c, 0x11, 0x00, 0x5d, 0x12, 0x00, 0x5e, 0x12, 0x00, 0x5f, 0x12, 0x00, 0x60, 0x12, 0x00, 0x60, + 0x12, 0x00, 0x61, 0x12, 0x00, 0x62, 0x13, 0x00, 0x63, 0x13, 0x00, 0x64, 0x13, 0x00, 0x64, 0x13, + 0x00, 0x65, 0x13, 0x00, 0x66, 0x13, 0x00, 0x67, 0x13, 0x00, 0x68, 0x14, 0x00, 0x68, 0x14, 0x00, + 0x69, 0x14, 0x00, 0x6a, 0x14, 0x00, 0x6b, 0x14, 0x00, 0x6c, 0x14, 0x00, 0x6d, 0x14, 0x00, 0x6d, + 0x15, 0x00, 0x6e, 0x15, 0x00, 0x6f, 0x15, 0x00, 0x70, 0x15, 0x00, 0x71, 0x15, 0x00, 0x71, 0x15, + 0x00, 0x72, 0x16, 0x00, 0x73, 0x16, 0x00, 0x74, 0x16, 0x00, 0x75, 0x16, 0x00, 0x76, 0x16, 0x00, + 0x76, 0x16, 0x00, 0x77, 0x17, 0x00, 0x78, 0x17, 0x00, 0x79, 0x17, 0x00, 0x7a, 0x17, 0x00, 0x7a, + 0x17, 0x00, 0x7b, 0x17, 0x00, 0x7c, 0x17, 0x00, 0x7d, 0x18, 0x00, 0x7e, 0x18, 0x00, 0x7f, 0x18, + 0x00, 0x7f, 0x18, 0x00, 0x80, 0x18, 0x00, 0x81, 0x18, 0x00, 0x82, 0x19, 0x00, 0x83, 0x19, 0x00, + 0x84, 0x19, 0x00, 0x84, 0x19, 0x00, 0x85, 0x19, 0x00, 0x86, 0x19, 0x00, 0x87, 0x19, 0x00, 0x88, + 0x1a, 0x00, 0x89, 0x1a, 0x00, 0x8a, 0x1a, 0x00, 0x8a, 0x1a, 0x00, 0x8b, 0x1a, 0x00, 0x8c, 0x1a, + 0x00, 0x8d, 0x1b, 0x00, 0x8e, 0x1b, 0x00, 0x8f, 0x1b, 0x00, 0x8f, 0x1b, 0x00, 0x90, 0x1b, 0x00, + 0x91, 0x1b, 0x00, 0x92, 0x1c, 0x00, 0x93, 0x1c, 0x00, 0x94, 0x1c, 0x00, 0x95, 0x1c, 0x00, 0x95, + 0x1c, 0x00, 0x96, 0x1c, 0x00, 0x97, 0x1d, 0x00, 0x98, 0x1d, 0x00, 0x99, 0x1d, 0x00, 0x9a, 0x1d, + 0x00, 0x9b, 0x1d, 0x00, 0x9b, 0x1d, 0x00, 0x9c, 0x1e, 0x00, 0x9d, 0x1e, 0x00, 0x9e, 0x1e, 0x00, + 0x9f, 0x1e, 0x00, 0xa0, 0x1e, 0x00, 0xa1, 0x1e, 0x00, 0xa1, 0x1e, 0x00, 0xa2, 0x1f, 0x00, 0xa3, + 0x1f, 0x00, 0xa4, 0x1f, 0x00, 0xa5, 0x1f, 0x00, 0xa6, 0x1f, 0x00, 0xa7, 0x1f, 0x00, 0xa8, 0x20, + 0x00, 0xa8, 0x20, 0x00, 0xa9, 0x20, 0x00, 0xaa, 0x20, 0x00, 0xab, 0x20, 0x00, 0xac, 0x20, 0x00, + 0xad, 0x21, 0x00, 0xae, 0x21, 0x00, 0xaf, 0x21, 0x00, 0xaf, 0x21, 0x00, 0xb0, 0x21, 0x00, 0xb1, + 0x21, 0x00, 0xb2, 0x22, 0x00, 0xb3, 0x22, 0x00, 0xb4, 0x22, 0x00, 0xb5, 0x22, 0x00, 0xb6, 0x22, + 0x00, 0xb6, 0x22, 0x00, 0xb7, 0x23, 0x00, 0xb8, 0x23, 0x00, 0xb9, 0x23, 0x00, 0xba, 0x23, 0x00, + 0xbb, 0x23, 0x00, 0xbc, 0x23, 0x00, 0xbd, 0x24, 0x00, 0xbe, 0x24, 0x00, 0xbe, 0x24, 0x00, 0xbf, + 0x24, 0x00, 0xc0, 0x24, 0x00, 0xc1, 0x24, 0x00, 0xc2, 0x25, 0x00, 0xc3, 0x25, 0x00, 0xc4, 0x25, + 0x00, 0xc5, 0x25, 0x00, 0xc6, 0x25, 0x00, 0xc7, 0x26, 0x00, 0xc7, 0x26, 0x00, 0xc8, 0x26, 0x00, + 0xc9, 0x26, 0x00, 0xca, 0x26, 0x00, 0xcb, 0x26, 0x00, 0xcc, 0x27, 0x00, 0xcd, 0x27, 0x00, 0xce, + 0x27, 0x00, 0xcf, 0x27, 0x00, 0xd0, 0x27, 0x00, 0xd0, 0x27, 0x00, 0xd1, 0x28, 0x00, 0xd2, 0x28, + 0x00, 0xd3, 0x28, 0x00, 0xd4, 0x28, 0x00, 0xd5, 0x28, 0x00, 0xd6, 0x28, 0x00, 0xd7, 0x29, 0x00, + 0xd8, 0x29, 0x00, 0xd9, 0x29, 0x00, 0xda, 0x29, 0x00, 0xda, 0x29, 0x00, 0xdb, 0x29, 0x00, 0xdc, + 0x2a, 0x00, 0xdd, 0x2a, 0x00, 0xde, 0x2a, 0x00, 0xdf, 0x2a, 0x00, 0xe0, 0x2a, 0x00, 0xe1, 0x2a, + 0x00, 0xe2, 0x2b, 0x00, 0xe3, 0x2b, 0x00, 0xe4, 0x2b, 0x00, 0xe5, 0x2b, 0x00, 0xe6, 0x2b, 0x00 +}; +static constexpr std::array L14 = { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x00, 0x04, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x06, 0x00, 0x00, 0x06, 0x00, 0x00, 0x07, 0x00, 0x00, 0x08, 0x00, 0x00, 0x09, + 0x00, 0x00, 0x0a, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x0d, 0x00, + 0x00, 0x0e, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x11, 0x00, 0x00, + 0x12, 0x00, 0x00, 0x12, 0x00, 0x00, 0x13, 0x00, 0x00, 0x13, 0x00, 0x00, 0x14, 0x00, 0x00, 0x15, + 0x00, 0x00, 0x15, 0x00, 0x00, 0x16, 0x00, 0x00, 0x16, 0x00, 0x00, 0x17, 0x00, 0x00, 0x17, 0x00, + 0x00, 0x18, 0x00, 0x00, 0x18, 0x00, 0x00, 0x19, 0x00, 0x00, 0x19, 0x00, 0x00, 0x1a, 0x00, 0x00, + 0x1a, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x1c, + 0x00, 0x00, 0x1d, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x1e, 0x00, + 0x00, 0x1f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x20, 0x00, 0x00, 0x20, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x21, 0x00, 0x00, 0x22, 0x00, 0x00, 0x22, 0x00, 0x00, 0x22, 0x00, 0x00, 0x23, + 0x00, 0x00, 0x23, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x24, 0x00, 0x00, 0x25, 0x00, + 0x00, 0x25, 0x00, 0x00, 0x26, 0x00, 0x00, 0x26, 0x00, 0x00, 0x27, 0x00, 0x00, 0x27, 0x00, 0x00, + 0x27, 0x00, 0x00, 0x28, 0x00, 0x00, 0x28, 0x00, 0x00, 0x29, 0x00, 0x00, 0x29, 0x00, 0x00, 0x2a, + 0x00, 0x00, 0x2a, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x2c, 0x00, + 0x00, 0x2c, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x2d, 0x00, 0x00, 0x2e, 0x00, 0x00, + 0x2e, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x30, 0x00, 0x00, 0x30, 0x00, 0x00, 0x30, + 0x00, 0x00, 0x31, 0x00, 0x00, 0x31, 0x00, 0x00, 0x32, 0x00, 0x00, 0x32, 0x00, 0x00, 0x33, 0x00, + 0x00, 0x33, 0x00, 0x00, 0x34, 0x00, 0x00, 0x34, 0x00, 0x00, 0x34, 0x00, 0x00, 0x35, 0x00, 0x00, + 0x35, 0x00, 0x00, 0x36, 0x00, 0x00, 0x36, 0x00, 0x00, 0x37, 0x00, 0x00, 0x37, 0x00, 0x00, 0x38, + 0x00, 0x00, 0x38, 0x00, 0x00, 0x38, 0x00, 0x00, 0x39, 0x00, 0x00, 0x39, 0x00, 0x00, 0x3a, 0x00, + 0x00, 0x3a, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x3b, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x3c, 0x00, 0x00, + 0x3c, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x3f, + 0x00, 0x00, 0x3f, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x00, 0x00, 0x41, 0x00, 0x00, 0x41, 0x00, + 0x00, 0x41, 0x00, 0x00, 0x42, 0x00, 0x00, 0x42, 0x00, 0x00, 0x43, 0x00, 0x00, 0x43, 0x00, 0x00, + 0x44, 0x00, 0x00, 0x44, 0x00, 0x00, 0x45, 0x00, 0x00, 0x45, 0x00, 0x00, 0x46, 0x00, 0x00, 0x46, + 0x00, 0x00, 0x47, 0x00, 0x00, 0x47, 0x00, 0x00, 0x47, 0x00, 0x00, 0x48, 0x00, 0x00, 0x48, 0x00, + 0x00, 0x49, 0x00, 0x00, 0x49, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x4b, 0x00, 0x00, + 0x4b, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x4d, 0x00, 0x00, 0x4d, 0x00, 0x00, 0x4e, + 0x00, 0x00, 0x4e, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x4f, 0x00, 0x00, 0x50, 0x00, + 0x00, 0x50, 0x00, 0x00, 0x51, 0x00, 0x00, 0x51, 0x00, 0x00, 0x52, 0x00, 0x00, 0x52, 0x00, 0x00, + 0x53, 0x00, 0x00, 0x53, 0x00, 0x00, 0x54, 0x00, 0x00, 0x54, 0x00, 0x00, 0x55, 0x00, 0x00, 0x55, + 0x00, 0x00, 0x56, 0x00, 0x00, 0x56, 0x00, 0x00, 0x57, 0x00, 0x00, 0x57, 0x00, 0x00, 0x58, 0x00, + 0x00, 0x58, 0x00, 0x00, 0x59, 0x00, 0x00, 0x59, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x5a, 0x00, 0x00, + 0x5a, 0x00, 0x00, 0x5b, 0x00, 0x00, 0x5b, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x5d, + 0x00, 0x00, 0x5d, 0x00, 0x00, 0x5e, 0x00, 0x00, 0x5e, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x5f, 0x00, + 0x00, 0x60, 0x00, 0x00, 0x60, 0x00, 0x00, 0x61, 0x00, 0x00, 0x61, 0x00, 0x00, 0x62, 0x00, 0x00, + 0x62, 0x00, 0x00, 0x63, 0x00, 0x00, 0x63, 0x00, 0x00, 0x64, 0x00, 0x00, 0x64, 0x00, 0x00, 0x65, + 0x00, 0x00, 0x65, 0x00, 0x00, 0x66, 0x00, 0x00, 0x66, 0x00, 0x00, 0x67, 0x00, 0x00, 0x67, 0x00, + 0x00, 0x68, 0x00, 0x00, 0x68, 0x00, 0x00, 0x69, 0x00, 0x00, 0x69, 0x00, 0x00, 0x6a, 0x00, 0x00, + 0x6a, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x6c, 0x00, 0x00, 0x6d, + 0x00, 0x00, 0x6d, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x6f, 0x00, 0x00, 0x6f, 0x00, + 0x00, 0x70, 0x00, 0x00, 0x70, 0x00, 0x00, 0x71, 0x00, 0x00, 0x71, 0x00, 0x00, 0x72, 0x00, 0x00, + 0x72, 0x00, 0x00, 0x73, 0x00, 0x00, 0x73, 0x00, 0x00, 0x74, 0x00, 0x00, 0x74, 0x00, 0x00, 0x75, + 0x00, 0x00, 0x75, 0x00, 0x00, 0x76, 0x00, 0x00, 0x76, 0x00, 0x00, 0x77, 0x00, 0x00, 0x77, 0x00, + 0x00, 0x78, 0x00, 0x00, 0x78, 0x00, 0x00, 0x79, 0x00, 0x00, 0x79, 0x00, 0x00, 0x7a, 0x00, 0x00, + 0x7a, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x7d, + 0x00, 0x00, 0x7d, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x80, 0x00 +}; +static constexpr std::array L15 = { + 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x01, 0x04, 0x01, 0x02, 0x06, 0x01, 0x03, 0x08, 0x01, + 0x03, 0x0a, 0x01, 0x04, 0x0b, 0x01, 0x04, 0x0d, 0x02, 0x05, 0x0f, 0x02, 0x06, 0x11, 0x02, 0x06, + 0x13, 0x02, 0x07, 0x14, 0x02, 0x07, 0x16, 0x02, 0x08, 0x18, 0x03, 0x08, 0x19, 0x03, 0x09, 0x1b, + 0x03, 0x09, 0x1c, 0x03, 0x0a, 0x1e, 0x03, 0x0a, 0x1f, 0x03, 0x0b, 0x21, 0x03, 0x0b, 0x22, 0x04, + 0x0c, 0x23, 0x04, 0x0c, 0x25, 0x04, 0x0d, 0x26, 0x04, 0x0d, 0x27, 0x04, 0x0d, 0x28, 0x04, 0x0e, + 0x29, 0x04, 0x0e, 0x2b, 0x04, 0x0e, 0x2c, 0x04, 0x0f, 0x2d, 0x05, 0x0f, 0x2e, 0x05, 0x0f, 0x2f, + 0x05, 0x10, 0x30, 0x05, 0x10, 0x31, 0x05, 0x11, 0x32, 0x05, 0x11, 0x33, 0x05, 0x11, 0x34, 0x05, + 0x11, 0x35, 0x05, 0x12, 0x36, 0x05, 0x12, 0x37, 0x06, 0x12, 0x38, 0x06, 0x13, 0x39, 0x06, 0x13, + 0x39, 0x06, 0x13, 0x3a, 0x06, 0x14, 0x3b, 0x06, 0x14, 0x3c, 0x06, 0x14, 0x3d, 0x06, 0x14, 0x3e, + 0x06, 0x15, 0x3e, 0x06, 0x15, 0x3f, 0x06, 0x15, 0x40, 0x06, 0x15, 0x41, 0x07, 0x16, 0x42, 0x07, + 0x16, 0x43, 0x07, 0x16, 0x43, 0x07, 0x17, 0x44, 0x07, 0x17, 0x45, 0x07, 0x17, 0x46, 0x07, 0x17, + 0x47, 0x07, 0x18, 0x48, 0x07, 0x18, 0x48, 0x07, 0x18, 0x49, 0x07, 0x18, 0x4a, 0x07, 0x19, 0x4b, + 0x08, 0x19, 0x4c, 0x08, 0x19, 0x4d, 0x08, 0x1a, 0x4e, 0x08, 0x1a, 0x4e, 0x08, 0x1a, 0x4f, 0x08, + 0x1a, 0x50, 0x08, 0x1b, 0x51, 0x08, 0x1b, 0x52, 0x08, 0x1b, 0x53, 0x08, 0x1c, 0x53, 0x08, 0x1c, + 0x54, 0x09, 0x1c, 0x55, 0x09, 0x1c, 0x56, 0x09, 0x1d, 0x57, 0x09, 0x1d, 0x58, 0x09, 0x1d, 0x59, + 0x09, 0x1e, 0x5a, 0x09, 0x1e, 0x5a, 0x09, 0x1e, 0x5b, 0x09, 0x1e, 0x5c, 0x09, 0x1f, 0x5d, 0x09, + 0x1f, 0x5e, 0x09, 0x1f, 0x5f, 0x0a, 0x20, 0x60, 0x0a, 0x20, 0x60, 0x0a, 0x20, 0x61, 0x0a, 0x20, + 0x62, 0x0a, 0x21, 0x63, 0x0a, 0x21, 0x64, 0x0a, 0x21, 0x65, 0x0a, 0x22, 0x66, 0x0a, 0x22, 0x67, + 0x0a, 0x22, 0x67, 0x0a, 0x22, 0x68, 0x0b, 0x23, 0x69, 0x0b, 0x23, 0x6a, 0x0b, 0x23, 0x6b, 0x0b, + 0x24, 0x6c, 0x0b, 0x24, 0x6d, 0x0b, 0x24, 0x6e, 0x0b, 0x24, 0x6f, 0x0b, 0x25, 0x6f, 0x0b, 0x25, + 0x70, 0x0b, 0x25, 0x71, 0x0b, 0x26, 0x72, 0x0c, 0x26, 0x73, 0x0c, 0x26, 0x74, 0x0c, 0x27, 0x75, + 0x0c, 0x27, 0x76, 0x0c, 0x27, 0x77, 0x0c, 0x27, 0x77, 0x0c, 0x28, 0x78, 0x0c, 0x28, 0x79, 0x0c, + 0x28, 0x7a, 0x0c, 0x29, 0x7b, 0x0c, 0x29, 0x7c, 0x0c, 0x29, 0x7d, 0x0d, 0x2a, 0x7e, 0x0d, 0x2a, + 0x7f, 0x0d, 0x2a, 0x80, 0x0d, 0x2a, 0x81, 0x0d, 0x2b, 0x81, 0x0d, 0x2b, 0x82, 0x0d, 0x2b, 0x83, + 0x0d, 0x2c, 0x84, 0x0d, 0x2c, 0x85, 0x0d, 0x2c, 0x86, 0x0d, 0x2d, 0x87, 0x0e, 0x2d, 0x88, 0x0e, + 0x2d, 0x89, 0x0e, 0x2d, 0x8a, 0x0e, 0x2e, 0x8b, 0x0e, 0x2e, 0x8c, 0x0e, 0x2e, 0x8c, 0x0e, 0x2f, + 0x8d, 0x0e, 0x2f, 0x8e, 0x0e, 0x2f, 0x8f, 0x0e, 0x30, 0x90, 0x0f, 0x30, 0x91, 0x0f, 0x30, 0x92, + 0x0f, 0x30, 0x93, 0x0f, 0x31, 0x94, 0x0f, 0x31, 0x95, 0x0f, 0x31, 0x96, 0x0f, 0x32, 0x97, 0x0f, + 0x32, 0x98, 0x0f, 0x32, 0x98, 0x0f, 0x33, 0x99, 0x0f, 0x33, 0x9a, 0x10, 0x33, 0x9b, 0x10, 0x34, + 0x9c, 0x10, 0x34, 0x9d, 0x10, 0x34, 0x9e, 0x10, 0x34, 0x9f, 0x10, 0x35, 0xa0, 0x10, 0x35, 0xa1, + 0x10, 0x35, 0xa2, 0x10, 0x36, 0xa3, 0x10, 0x36, 0xa4, 0x10, 0x36, 0xa5, 0x11, 0x37, 0xa6, 0x11, + 0x37, 0xa7, 0x11, 0x37, 0xa8, 0x11, 0x38, 0xa8, 0x11, 0x38, 0xa9, 0x11, 0x38, 0xaa, 0x11, 0x39, + 0xab, 0x11, 0x39, 0xac, 0x11, 0x39, 0xad, 0x11, 0x39, 0xae, 0x12, 0x3a, 0xaf, 0x12, 0x3a, 0xb0, + 0x12, 0x3a, 0xb1, 0x12, 0x3b, 0xb2, 0x12, 0x3b, 0xb3, 0x12, 0x3b, 0xb4, 0x12, 0x3c, 0xb5, 0x12, + 0x3c, 0xb6, 0x12, 0x3c, 0xb7, 0x12, 0x3d, 0xb8, 0x12, 0x3d, 0xb9, 0x13, 0x3d, 0xba, 0x13, 0x3e, + 0xbb, 0x13, 0x3e, 0xbc, 0x13, 0x3e, 0xbd, 0x13, 0x3f, 0xbe, 0x13, 0x3f, 0xbe, 0x13, 0x3f, 0xbf, + 0x13, 0x40, 0xc0, 0x13, 0x40, 0xc1, 0x13, 0x40, 0xc2, 0x14, 0x40, 0xc3, 0x14, 0x41, 0xc4, 0x14, + 0x41, 0xc5, 0x14, 0x41, 0xc6, 0x14, 0x42, 0xc7, 0x14, 0x42, 0xc8, 0x14, 0x42, 0xc9, 0x14, 0x43, + 0xca, 0x14, 0x43, 0xcb, 0x14, 0x43, 0xcc, 0x15, 0x44, 0xcd, 0x15, 0x44, 0xce, 0x15, 0x44, 0xcf, + 0x15, 0x45, 0xd0, 0x15, 0x45, 0xd1, 0x15, 0x45, 0xd2, 0x15, 0x46, 0xd3, 0x15, 0x46, 0xd4, 0x15, + 0x46, 0xd5, 0x15, 0x47, 0xd6, 0x15, 0x47, 0xd7, 0x16, 0x47, 0xd8, 0x16, 0x48, 0xd9, 0x16, 0x48, + 0xda, 0x16, 0x48, 0xdb, 0x16, 0x49, 0xdc, 0x16, 0x49, 0xdd, 0x16, 0x49, 0xde, 0x16, 0x4a, 0xdf, + 0x16, 0x4a, 0xe0, 0x16, 0x4a, 0xe1, 0x17, 0x4b, 0xe2, 0x17, 0x4b, 0xe3, 0x17, 0x4b, 0xe4, 0x17, + 0x4c, 0xe5, 0x17, 0x4c, 0xe6, 0x17, 0x4c, 0xe7, 0x17, 0x4c, 0xe8, 0x17, 0x4d, 0xe9, 0x17, 0x4d, + 0xea, 0x17, 0x4d, 0xeb, 0x18, 0x4e, 0xec, 0x18, 0x4e, 0xed, 0x18, 0x4e, 0xee, 0x18, 0x4f, 0xef, + 0x18, 0x4f, 0xf0, 0x18, 0x4f, 0xf1, 0x18, 0x50, 0xf2, 0x18, 0x50, 0xf3, 0x18, 0x50, 0xf4, 0x18, + 0x51, 0xf5, 0x19, 0x51, 0xf6, 0x19, 0x51, 0xf7, 0x19, 0x52, 0xf8, 0x19, 0x52, 0xf9, 0x19, 0x52, + 0xfa, 0x19, 0x53, 0xfb, 0x19, 0x53, 0xfc, 0x19, 0x53, 0xfd, 0x19, 0x54, 0xfe, 0x1a, 0x54, 0xff +}; +static constexpr std::array L16 = { + 0x1b, 0x1b, 0x1b, 0x1d, 0x1b, 0x20, 0x1f, 0x1b, 0x24, 0x20, 0x1b, 0x29, 0x22, 0x1b, 0x2d, 0x23, + 0x1b, 0x31, 0x24, 0x1b, 0x35, 0x25, 0x1b, 0x3a, 0x26, 0x1b, 0x3e, 0x27, 0x1b, 0x42, 0x27, 0x1a, + 0x46, 0x28, 0x1a, 0x4a, 0x28, 0x1a, 0x4f, 0x29, 0x1a, 0x53, 0x29, 0x1a, 0x57, 0x29, 0x1a, 0x5b, + 0x29, 0x19, 0x5f, 0x29, 0x19, 0x63, 0x29, 0x19, 0x66, 0x29, 0x19, 0x6a, 0x29, 0x19, 0x6e, 0x28, + 0x19, 0x72, 0x28, 0x19, 0x75, 0x27, 0x19, 0x79, 0x27, 0x19, 0x7c, 0x26, 0x19, 0x80, 0x25, 0x19, + 0x83, 0x25, 0x19, 0x86, 0x24, 0x1a, 0x89, 0x23, 0x1a, 0x8c, 0x22, 0x1a, 0x8f, 0x21, 0x1a, 0x92, + 0x20, 0x1b, 0x95, 0x1f, 0x1b, 0x98, 0x1d, 0x1c, 0x9a, 0x1c, 0x1d, 0x9d, 0x1b, 0x1d, 0x9f, 0x19, + 0x1e, 0xa2, 0x18, 0x1f, 0xa4, 0x17, 0x20, 0xa6, 0x15, 0x20, 0xa8, 0x14, 0x21, 0xaa, 0x12, 0x22, + 0xac, 0x11, 0x23, 0xad, 0x0f, 0x25, 0xaf, 0x0e, 0x26, 0xb0, 0x0d, 0x27, 0xb1, 0x0c, 0x28, 0xb2, + 0x0b, 0x29, 0xb3, 0x0a, 0x2b, 0xb4, 0x09, 0x2c, 0xb4, 0x09, 0x2e, 0xb5, 0x08, 0x2f, 0xb5, 0x08, + 0x30, 0xb6, 0x08, 0x32, 0xb6, 0x08, 0x33, 0xb6, 0x07, 0x35, 0xb7, 0x07, 0x36, 0xb7, 0x07, 0x37, + 0xb7, 0x07, 0x39, 0xb7, 0x07, 0x3a, 0xb8, 0x07, 0x3c, 0xb8, 0x07, 0x3d, 0xb8, 0x07, 0x3e, 0xb8, + 0x07, 0x40, 0xb8, 0x07, 0x41, 0xb8, 0x07, 0x42, 0xb8, 0x07, 0x44, 0xb8, 0x07, 0x45, 0xb8, 0x07, + 0x46, 0xb8, 0x07, 0x48, 0xb7, 0x07, 0x49, 0xb7, 0x07, 0x4b, 0xb7, 0x07, 0x4c, 0xb7, 0x07, 0x4d, + 0xb6, 0x07, 0x4f, 0xb6, 0x07, 0x50, 0xb5, 0x07, 0x51, 0xb5, 0x07, 0x53, 0xb4, 0x07, 0x54, 0xb4, + 0x07, 0x56, 0xb3, 0x07, 0x57, 0xb2, 0x07, 0x58, 0xb1, 0x07, 0x5a, 0xb0, 0x07, 0x5b, 0xaf, 0x06, + 0x5d, 0xae, 0x06, 0x5e, 0xad, 0x06, 0x5f, 0xac, 0x06, 0x61, 0xab, 0x06, 0x62, 0xaa, 0x07, 0x64, + 0xa8, 0x08, 0x65, 0xa7, 0x0a, 0x66, 0xa5, 0x0c, 0x68, 0xa4, 0x0e, 0x69, 0xa2, 0x10, 0x6a, 0xa0, + 0x12, 0x6c, 0x9f, 0x14, 0x6d, 0x9d, 0x16, 0x6e, 0x9b, 0x18, 0x6f, 0x99, 0x1a, 0x71, 0x97, 0x1b, + 0x72, 0x95, 0x1d, 0x73, 0x93, 0x1f, 0x74, 0x91, 0x20, 0x76, 0x8f, 0x22, 0x77, 0x8d, 0x23, 0x78, + 0x8b, 0x24, 0x79, 0x89, 0x26, 0x7b, 0x87, 0x27, 0x7c, 0x85, 0x28, 0x7d, 0x82, 0x29, 0x7e, 0x80, + 0x2a, 0x80, 0x7e, 0x2b, 0x81, 0x7b, 0x2c, 0x82, 0x79, 0x2c, 0x83, 0x77, 0x2d, 0x84, 0x74, 0x2e, + 0x86, 0x72, 0x2e, 0x87, 0x6f, 0x2f, 0x88, 0x6d, 0x2f, 0x89, 0x6a, 0x30, 0x8b, 0x67, 0x30, 0x8c, + 0x65, 0x30, 0x8d, 0x62, 0x30, 0x8e, 0x5f, 0x31, 0x8f, 0x5c, 0x31, 0x91, 0x5a, 0x31, 0x92, 0x57, + 0x32, 0x93, 0x55, 0x32, 0x94, 0x53, 0x33, 0x95, 0x50, 0x34, 0x96, 0x4e, 0x34, 0x97, 0x4c, 0x35, + 0x98, 0x4a, 0x36, 0x99, 0x48, 0x37, 0x9a, 0x46, 0x38, 0x9b, 0x44, 0x3a, 0x9c, 0x42, 0x3b, 0x9d, + 0x40, 0x3c, 0x9e, 0x3e, 0x3d, 0x9f, 0x3c, 0x3f, 0xa0, 0x3a, 0x40, 0xa1, 0x38, 0x42, 0xa2, 0x37, + 0x44, 0xa3, 0x35, 0x45, 0xa4, 0x33, 0x47, 0xa5, 0x31, 0x49, 0xa6, 0x30, 0x4a, 0xa7, 0x2e, 0x4c, + 0xa8, 0x2c, 0x4e, 0xa9, 0x2b, 0x50, 0xaa, 0x29, 0x52, 0xab, 0x28, 0x54, 0xac, 0x26, 0x56, 0xac, + 0x24, 0x58, 0xad, 0x23, 0x5a, 0xae, 0x21, 0x5c, 0xaf, 0x20, 0x5e, 0xb0, 0x1e, 0x60, 0xb1, 0x1d, + 0x62, 0xb1, 0x1b, 0x65, 0xb2, 0x1a, 0x67, 0xb3, 0x18, 0x69, 0xb4, 0x17, 0x6b, 0xb5, 0x15, 0x6e, + 0xb5, 0x14, 0x70, 0xb6, 0x12, 0x72, 0xb7, 0x11, 0x75, 0xb8, 0x0f, 0x77, 0xb8, 0x0e, 0x79, 0xb9, + 0x0c, 0x7c, 0xba, 0x0b, 0x7e, 0xbb, 0x09, 0x80, 0xbb, 0x08, 0x83, 0xbc, 0x07, 0x85, 0xbd, 0x06, + 0x88, 0xbd, 0x05, 0x8a, 0xbe, 0x04, 0x8d, 0xbf, 0x04, 0x8f, 0xbf, 0x03, 0x92, 0xc0, 0x03, 0x94, + 0xc1, 0x03, 0x97, 0xc1, 0x02, 0x99, 0xc2, 0x02, 0x9c, 0xc3, 0x02, 0x9e, 0xc3, 0x02, 0xa1, 0xc4, + 0x03, 0xa3, 0xc5, 0x03, 0xa5, 0xc5, 0x03, 0xa8, 0xc6, 0x03, 0xaa, 0xc7, 0x03, 0xac, 0xc7, 0x04, + 0xaf, 0xc8, 0x04, 0xb1, 0xc8, 0x05, 0xb3, 0xc9, 0x05, 0xb6, 0xca, 0x06, 0xb8, 0xca, 0x07, 0xba, + 0xcb, 0x08, 0xbc, 0xcc, 0x08, 0xbe, 0xcc, 0x09, 0xc0, 0xcd, 0x0b, 0xc3, 0xce, 0x0c, 0xc5, 0xce, + 0x0d, 0xc7, 0xcf, 0x0e, 0xc9, 0xd0, 0x0f, 0xcb, 0xd0, 0x10, 0xcd, 0xd1, 0x12, 0xcf, 0xd2, 0x13, + 0xd1, 0xd2, 0x14, 0xd3, 0xd3, 0x16, 0xd5, 0xd4, 0x17, 0xd7, 0xd5, 0x18, 0xd9, 0xd5, 0x1a, 0xda, + 0xd6, 0x1b, 0xdc, 0xd7, 0x1d, 0xde, 0xd7, 0x1e, 0xe0, 0xd8, 0x20, 0xe2, 0xd9, 0x21, 0xe3, 0xda, + 0x23, 0xe5, 0xda, 0x24, 0xe6, 0xdb, 0x26, 0xe8, 0xdc, 0x28, 0xea, 0xdd, 0x2a, 0xeb, 0xde, 0x2b, + 0xec, 0xdf, 0x2d, 0xee, 0xdf, 0x2f, 0xef, 0xe0, 0x31, 0xf0, 0xe1, 0x33, 0xf1, 0xe2, 0x35, 0xf2, + 0xe3, 0x38, 0xf3, 0xe4, 0x3a, 0xf4, 0xe5, 0x3d, 0xf5, 0xe6, 0x3f, 0xf5, 0xe7, 0x42, 0xf6, 0xe8, + 0x46, 0xf7, 0xe9, 0x49, 0xf7, 0xea, 0x4e, 0xf8, 0xeb, 0x52, 0xf9, 0xec, 0x57, 0xfa, 0xed, 0x5c, + 0xfa, 0xee, 0x62, 0xfb, 0xef, 0x68, 0xfc, 0xf0, 0x6f, 0xfc, 0xf1, 0x76, 0xfd, 0xf2, 0x7d, 0xfe, + 0xf3, 0x85, 0xfe, 0xf3, 0x8d, 0xff, 0xf4, 0x96, 0xff, 0xf5, 0xa0, 0xff, 0xf6, 0xaa, 0xff, 0xf6, + 0xb5, 0xff, 0xf7, 0xc1, 0xfe, 0xf8, 0xcd, 0xfd, 0xf8, 0xdb, 0xfc, 0xf9, 0xe9, 0xf9, 0xf9, 0xf9 +}; +static constexpr std::array L17 = { + 0xff, 0xff, 0xff, 0xff, 0xfe, 0xfc, 0xfe, 0xfd, 0xf9, 0xfe, 0xfd, 0xf7, 0xfd, 0xfc, 0xf4, 0xfd, + 0xfb, 0xf1, 0xfc, 0xfa, 0xee, 0xfc, 0xfa, 0xeb, 0xfb, 0xf9, 0xe9, 0xfb, 0xf8, 0xe6, 0xfa, 0xf7, + 0xe3, 0xfa, 0xf7, 0xe0, 0xf9, 0xf6, 0xdd, 0xf8, 0xf5, 0xdb, 0xf8, 0xf4, 0xd8, 0xf7, 0xf3, 0xd5, + 0xf7, 0xf3, 0xd2, 0xf6, 0xf2, 0xcf, 0xf6, 0xf1, 0xcd, 0xf5, 0xf0, 0xca, 0xf4, 0xf0, 0xc7, 0xf4, + 0xef, 0xc4, 0xf3, 0xee, 0xc2, 0xf2, 0xed, 0xbf, 0xf2, 0xec, 0xbd, 0xf2, 0xeb, 0xbb, 0xf2, 0xea, + 0xba, 0xf2, 0xe9, 0xb8, 0xf3, 0xe8, 0xb6, 0xf3, 0xe7, 0xb4, 0xf3, 0xe6, 0xb3, 0xf3, 0xe5, 0xb1, + 0xf3, 0xe4, 0xaf, 0xf3, 0xe3, 0xae, 0xf3, 0xe2, 0xac, 0xf3, 0xe1, 0xaa, 0xf3, 0xe0, 0xa9, 0xf2, + 0xdf, 0xa7, 0xf2, 0xde, 0xa5, 0xf2, 0xdd, 0xa4, 0xf2, 0xdc, 0xa2, 0xf2, 0xdb, 0xa0, 0xf2, 0xda, + 0x9f, 0xf2, 0xd9, 0x9d, 0xf2, 0xd7, 0x9c, 0xf2, 0xd6, 0x9a, 0xf2, 0xd5, 0x98, 0xf2, 0xd4, 0x97, + 0xf2, 0xd3, 0x96, 0xf2, 0xd2, 0x94, 0xf2, 0xd1, 0x93, 0xf3, 0xd0, 0x92, 0xf3, 0xcf, 0x91, 0xf3, + 0xcd, 0x90, 0xf3, 0xcc, 0x8e, 0xf3, 0xcb, 0x8d, 0xf3, 0xca, 0x8c, 0xf3, 0xc9, 0x8b, 0xf3, 0xc8, + 0x8a, 0xf3, 0xc6, 0x88, 0xf4, 0xc5, 0x87, 0xf4, 0xc4, 0x86, 0xf4, 0xc3, 0x85, 0xf4, 0xc2, 0x84, + 0xf4, 0xc1, 0x83, 0xf4, 0xbf, 0x81, 0xf4, 0xbe, 0x80, 0xf4, 0xbd, 0x7f, 0xf4, 0xbc, 0x7e, 0xf4, + 0xbb, 0x7d, 0xf4, 0xba, 0x7c, 0xf4, 0xb8, 0x7b, 0xf4, 0xb7, 0x7a, 0xf4, 0xb6, 0x7a, 0xf5, 0xb5, + 0x79, 0xf5, 0xb3, 0x78, 0xf5, 0xb2, 0x77, 0xf5, 0xb1, 0x77, 0xf5, 0xb0, 0x76, 0xf5, 0xae, 0x75, + 0xf5, 0xad, 0x75, 0xf5, 0xac, 0x74, 0xf5, 0xab, 0x73, 0xf5, 0xaa, 0x73, 0xf5, 0xa8, 0x72, 0xf5, + 0xa7, 0x71, 0xf5, 0xa6, 0x70, 0xf5, 0xa4, 0x70, 0xf5, 0xa3, 0x6f, 0xf5, 0xa2, 0x6e, 0xf5, 0xa1, + 0x6e, 0xf5, 0x9f, 0x6d, 0xf5, 0x9e, 0x6c, 0xf5, 0x9d, 0x6c, 0xf5, 0x9c, 0x6c, 0xf5, 0x9a, 0x6b, + 0xf5, 0x99, 0x6b, 0xf5, 0x98, 0x6b, 0xf5, 0x97, 0x6b, 0xf5, 0x95, 0x6a, 0xf5, 0x94, 0x6a, 0xf5, + 0x93, 0x6a, 0xf5, 0x91, 0x6a, 0xf5, 0x90, 0x6a, 0xf4, 0x8f, 0x69, 0xf4, 0x8d, 0x69, 0xf4, 0x8c, + 0x69, 0xf4, 0x8b, 0x69, 0xf4, 0x8a, 0x69, 0xf4, 0x88, 0x68, 0xf4, 0x87, 0x68, 0xf4, 0x86, 0x68, + 0xf4, 0x84, 0x68, 0xf3, 0x83, 0x67, 0xf3, 0x81, 0x67, 0xf3, 0x80, 0x67, 0xf3, 0x7f, 0x67, 0xf3, + 0x7e, 0x67, 0xf2, 0x7c, 0x67, 0xf2, 0x7b, 0x67, 0xf2, 0x7a, 0x68, 0xf2, 0x78, 0x68, 0xf1, 0x77, + 0x68, 0xf1, 0x76, 0x68, 0xf1, 0x74, 0x68, 0xf0, 0x73, 0x68, 0xf0, 0x72, 0x69, 0xf0, 0x70, 0x69, + 0xef, 0x6f, 0x69, 0xef, 0x6e, 0x69, 0xef, 0x6c, 0x69, 0xee, 0x6b, 0x6a, 0xee, 0x6a, 0x6a, 0xee, + 0x68, 0x6a, 0xed, 0x67, 0x6a, 0xed, 0x66, 0x6a, 0xed, 0x64, 0x6a, 0xec, 0x63, 0x6a, 0xec, 0x61, + 0x6b, 0xec, 0x60, 0x6b, 0xeb, 0x5f, 0x6b, 0xea, 0x5d, 0x6c, 0xea, 0x5c, 0x6c, 0xe9, 0x5b, 0x6d, + 0xe8, 0x5a, 0x6d, 0xe8, 0x58, 0x6e, 0xe7, 0x57, 0x6e, 0xe7, 0x56, 0x6e, 0xe6, 0x55, 0x6f, 0xe5, + 0x53, 0x6f, 0xe5, 0x52, 0x70, 0xe4, 0x51, 0x70, 0xe3, 0x4f, 0x71, 0xe3, 0x4e, 0x71, 0xe2, 0x4d, + 0x72, 0xe1, 0x4b, 0x72, 0xe1, 0x4a, 0x72, 0xe0, 0x49, 0x73, 0xe0, 0x47, 0x73, 0xdf, 0x46, 0x74, + 0xde, 0x44, 0x74, 0xde, 0x43, 0x75, 0xdd, 0x41, 0x75, 0xdc, 0x40, 0x75, 0xdb, 0x3f, 0x76, 0xda, + 0x3e, 0x77, 0xd9, 0x3d, 0x77, 0xd8, 0x3c, 0x78, 0xd7, 0x3b, 0x79, 0xd6, 0x3a, 0x79, 0xd5, 0x38, + 0x7a, 0xd4, 0x37, 0x7a, 0xd3, 0x36, 0x7b, 0xd2, 0x35, 0x7c, 0xd1, 0x34, 0x7c, 0xd0, 0x33, 0x7d, + 0xcf, 0x32, 0x7d, 0xce, 0x30, 0x7e, 0xcd, 0x2f, 0x7f, 0xcc, 0x2e, 0x7f, 0xcb, 0x2d, 0x80, 0xca, + 0x2b, 0x80, 0xc9, 0x2a, 0x81, 0xc8, 0x29, 0x82, 0xc7, 0x28, 0x82, 0xc5, 0x26, 0x83, 0xc4, 0x25, + 0x83, 0xc3, 0x25, 0x84, 0xc1, 0x24, 0x85, 0xc0, 0x23, 0x85, 0xbe, 0x23, 0x86, 0xbd, 0x22, 0x87, + 0xbc, 0x22, 0x87, 0xba, 0x21, 0x88, 0xb9, 0x20, 0x89, 0xb7, 0x20, 0x89, 0xb6, 0x1f, 0x8a, 0xb4, + 0x1f, 0x8a, 0xb3, 0x1e, 0x8b, 0xb1, 0x1d, 0x8c, 0xb0, 0x1d, 0x8c, 0xae, 0x1c, 0x8d, 0xad, 0x1c, + 0x8e, 0xab, 0x1b, 0x8e, 0xaa, 0x1b, 0x8f, 0xa8, 0x1a, 0x90, 0xa7, 0x19, 0x90, 0xa5, 0x19, 0x91, + 0xa3, 0x18, 0x92, 0xa2, 0x18, 0x92, 0xa0, 0x18, 0x93, 0x9e, 0x19, 0x93, 0x9c, 0x19, 0x94, 0x9a, + 0x1a, 0x94, 0x98, 0x1a, 0x95, 0x96, 0x1a, 0x96, 0x94, 0x1b, 0x96, 0x92, 0x1b, 0x97, 0x90, 0x1b, + 0x97, 0x8e, 0x1c, 0x98, 0x8c, 0x1c, 0x99, 0x89, 0x1c, 0x99, 0x87, 0x1d, 0x9a, 0x85, 0x1d, 0x9a, + 0x83, 0x1d, 0x9b, 0x81, 0x1d, 0x9b, 0x7f, 0x1e, 0x9c, 0x7c, 0x1e, 0x9d, 0x7a, 0x1e, 0x9d, 0x78, + 0x1e, 0x9e, 0x75, 0x1f, 0x9e, 0x73, 0x1f, 0x9f, 0x70, 0x1f, 0x9f, 0x6e, 0x20, 0xa0, 0x6b, 0x21, + 0xa0, 0x68, 0x21, 0xa0, 0x65, 0x22, 0xa1, 0x62, 0x23, 0xa1, 0x5f, 0x23, 0xa2, 0x5c, 0x24, 0xa2, + 0x59, 0x24, 0xa2, 0x55, 0x25, 0xa3, 0x52, 0x25, 0xa3, 0x4e, 0x26, 0xa3, 0x4b, 0x26, 0xa4, 0x47, + 0x27, 0xa4, 0x43, 0x27, 0xa4, 0x3e, 0x27, 0xa5, 0x3a, 0x28, 0xa5, 0x34, 0x28, 0xa6, 0x2f, 0x29, + 0xa6, 0x29, 0x29, 0xa6, 0x21, 0x29, 0xa7, 0x18, 0x2a, 0xa7, 0x0a, 0x2a, 0xa7, 0x00, 0x2a, 0xa8 +}; +static constexpr std::array L18 = { + 0xff, 0xff, 0xff, 0xfe, 0xff, 0xfc, 0xfe, 0xfe, 0xfa, 0xfd, 0xfe, 0xf7, 0xfd, 0xfd, 0xf5, 0xfc, + 0xfd, 0xf2, 0xfb, 0xfc, 0xef, 0xfb, 0xfc, 0xed, 0xfa, 0xfb, 0xea, 0xfa, 0xfb, 0xe8, 0xf9, 0xfb, + 0xe5, 0xf8, 0xfa, 0xe3, 0xf8, 0xfa, 0xe0, 0xf7, 0xf9, 0xdd, 0xf6, 0xf9, 0xdb, 0xf6, 0xf8, 0xd8, + 0xf5, 0xf8, 0xd6, 0xf4, 0xf7, 0xd3, 0xf4, 0xf7, 0xd0, 0xf3, 0xf7, 0xce, 0xf2, 0xf6, 0xcb, 0xf2, + 0xf6, 0xc9, 0xf1, 0xf5, 0xc6, 0xf0, 0xf5, 0xc4, 0xf0, 0xf4, 0xc2, 0xf0, 0xf4, 0xc0, 0xef, 0xf3, + 0xbf, 0xef, 0xf2, 0xbd, 0xef, 0xf2, 0xbc, 0xef, 0xf1, 0xba, 0xee, 0xf0, 0xb9, 0xee, 0xf0, 0xb7, + 0xee, 0xef, 0xb6, 0xee, 0xee, 0xb4, 0xed, 0xee, 0xb3, 0xed, 0xed, 0xb1, 0xed, 0xec, 0xaf, 0xec, + 0xec, 0xae, 0xec, 0xeb, 0xac, 0xec, 0xea, 0xab, 0xec, 0xea, 0xa9, 0xeb, 0xe9, 0xa8, 0xeb, 0xe8, + 0xa6, 0xeb, 0xe8, 0xa5, 0xea, 0xe7, 0xa3, 0xea, 0xe6, 0xa2, 0xea, 0xe6, 0xa0, 0xea, 0xe5, 0x9f, + 0xea, 0xe4, 0x9d, 0xe9, 0xe4, 0x9c, 0xe9, 0xe3, 0x9b, 0xe9, 0xe2, 0x99, 0xe9, 0xe1, 0x98, 0xe9, + 0xe1, 0x97, 0xe9, 0xe0, 0x96, 0xe9, 0xdf, 0x94, 0xe9, 0xdf, 0x93, 0xe8, 0xde, 0x92, 0xe8, 0xdd, + 0x90, 0xe8, 0xdc, 0x8f, 0xe8, 0xdc, 0x8e, 0xe8, 0xdb, 0x8c, 0xe8, 0xda, 0x8b, 0xe8, 0xda, 0x8a, + 0xe7, 0xd9, 0x88, 0xe7, 0xd8, 0x87, 0xe7, 0xd7, 0x86, 0xe7, 0xd7, 0x84, 0xe7, 0xd6, 0x83, 0xe7, + 0xd5, 0x82, 0xe6, 0xd5, 0x80, 0xe6, 0xd4, 0x7f, 0xe6, 0xd3, 0x7e, 0xe6, 0xd2, 0x7d, 0xe6, 0xd1, + 0x7c, 0xe6, 0xd1, 0x7b, 0xe6, 0xd0, 0x79, 0xe6, 0xcf, 0x78, 0xe6, 0xce, 0x77, 0xe6, 0xce, 0x76, + 0xe6, 0xcd, 0x75, 0xe6, 0xcc, 0x74, 0xe6, 0xcb, 0x72, 0xe6, 0xcb, 0x71, 0xe6, 0xca, 0x70, 0xe6, + 0xc9, 0x6f, 0xe5, 0xc8, 0x6e, 0xe5, 0xc8, 0x6d, 0xe5, 0xc7, 0x6b, 0xe5, 0xc6, 0x6a, 0xe5, 0xc5, + 0x69, 0xe5, 0xc4, 0x68, 0xe5, 0xc4, 0x67, 0xe5, 0xc3, 0x66, 0xe5, 0xc2, 0x65, 0xe5, 0xc1, 0x64, + 0xe5, 0xc1, 0x63, 0xe5, 0xc0, 0x62, 0xe5, 0xbf, 0x61, 0xe5, 0xbe, 0x60, 0xe5, 0xbd, 0x5f, 0xe5, + 0xbd, 0x5e, 0xe5, 0xbc, 0x5c, 0xe4, 0xbb, 0x5b, 0xe4, 0xba, 0x5a, 0xe4, 0xb9, 0x59, 0xe4, 0xb9, + 0x58, 0xe4, 0xb8, 0x57, 0xe4, 0xb7, 0x56, 0xe4, 0xb6, 0x55, 0xe4, 0xb5, 0x54, 0xe4, 0xb5, 0x53, + 0xe4, 0xb4, 0x52, 0xe4, 0xb3, 0x51, 0xe4, 0xb2, 0x50, 0xe4, 0xb1, 0x4f, 0xe4, 0xb0, 0x4e, 0xe4, + 0xb0, 0x4d, 0xe4, 0xaf, 0x4c, 0xe4, 0xae, 0x4c, 0xe4, 0xad, 0x4b, 0xe4, 0xac, 0x4a, 0xe4, 0xab, + 0x49, 0xe4, 0xab, 0x48, 0xe4, 0xaa, 0x47, 0xe4, 0xa9, 0x46, 0xe4, 0xa8, 0x45, 0xe3, 0xa7, 0x45, + 0xe3, 0xa6, 0x44, 0xe3, 0xa6, 0x43, 0xe3, 0xa5, 0x42, 0xe3, 0xa4, 0x41, 0xe3, 0xa3, 0x40, 0xe3, + 0xa2, 0x3f, 0xe3, 0xa1, 0x3e, 0xe3, 0xa1, 0x3e, 0xe3, 0xa0, 0x3d, 0xe3, 0x9f, 0x3c, 0xe3, 0x9e, + 0x3b, 0xe3, 0x9d, 0x3a, 0xe3, 0x9c, 0x39, 0xe3, 0x9b, 0x39, 0xe3, 0x9b, 0x38, 0xe3, 0x9a, 0x37, + 0xe3, 0x99, 0x37, 0xe3, 0x98, 0x36, 0xe3, 0x97, 0x35, 0xe3, 0x96, 0x34, 0xe3, 0x95, 0x34, 0xe3, + 0x94, 0x33, 0xe2, 0x93, 0x32, 0xe2, 0x93, 0x32, 0xe2, 0x92, 0x31, 0xe2, 0x91, 0x30, 0xe2, 0x90, + 0x2f, 0xe2, 0x8f, 0x2f, 0xe2, 0x8e, 0x2e, 0xe2, 0x8d, 0x2d, 0xe2, 0x8c, 0x2d, 0xe2, 0x8b, 0x2c, + 0xe2, 0x8b, 0x2b, 0xe2, 0x8a, 0x2a, 0xe2, 0x89, 0x2a, 0xe2, 0x88, 0x29, 0xe2, 0x87, 0x29, 0xe2, + 0x86, 0x28, 0xe2, 0x85, 0x28, 0xe1, 0x84, 0x27, 0xe1, 0x83, 0x27, 0xe1, 0x82, 0x26, 0xe1, 0x81, + 0x26, 0xe1, 0x80, 0x25, 0xe1, 0x7f, 0x25, 0xe1, 0x7f, 0x24, 0xe1, 0x7e, 0x24, 0xe1, 0x7d, 0x23, + 0xe1, 0x7c, 0x23, 0xe1, 0x7b, 0x22, 0xe1, 0x7a, 0x22, 0xe1, 0x79, 0x21, 0xe1, 0x78, 0x21, 0xe0, + 0x77, 0x20, 0xe0, 0x76, 0x20, 0xe0, 0x75, 0x1f, 0xe0, 0x74, 0x1f, 0xe0, 0x73, 0x1e, 0xe0, 0x72, + 0x1e, 0xe0, 0x71, 0x1e, 0xe0, 0x70, 0x1d, 0xe0, 0x6f, 0x1d, 0xe0, 0x6e, 0x1d, 0xe0, 0x6d, 0x1d, + 0xdf, 0x6c, 0x1c, 0xdf, 0x6b, 0x1c, 0xdf, 0x6a, 0x1c, 0xdf, 0x69, 0x1c, 0xdf, 0x68, 0x1b, 0xdf, + 0x67, 0x1b, 0xdf, 0x66, 0x1b, 0xdf, 0x65, 0x1b, 0xdf, 0x64, 0x1b, 0xde, 0x63, 0x1a, 0xde, 0x62, + 0x1a, 0xde, 0x61, 0x1a, 0xde, 0x60, 0x1a, 0xde, 0x5f, 0x19, 0xde, 0x5d, 0x19, 0xde, 0x5c, 0x19, + 0xde, 0x5b, 0x19, 0xdd, 0x5a, 0x19, 0xdd, 0x59, 0x19, 0xdd, 0x58, 0x19, 0xdd, 0x57, 0x19, 0xdd, + 0x56, 0x19, 0xdd, 0x55, 0x19, 0xdd, 0x53, 0x19, 0xdc, 0x52, 0x19, 0xdc, 0x51, 0x19, 0xdc, 0x50, + 0x19, 0xdc, 0x4f, 0x19, 0xdc, 0x4e, 0x19, 0xdc, 0x4c, 0x19, 0xdb, 0x4b, 0x19, 0xdb, 0x4a, 0x19, + 0xdb, 0x49, 0x19, 0xdb, 0x47, 0x19, 0xdb, 0x46, 0x19, 0xdb, 0x45, 0x19, 0xda, 0x43, 0x19, 0xda, + 0x42, 0x19, 0xda, 0x41, 0x19, 0xda, 0x3f, 0x19, 0xda, 0x3e, 0x19, 0xda, 0x3d, 0x19, 0xd9, 0x3b, + 0x1a, 0xd9, 0x3a, 0x1a, 0xd9, 0x38, 0x1a, 0xd9, 0x37, 0x1a, 0xd9, 0x35, 0x1a, 0xd8, 0x34, 0x1b, + 0xd8, 0x32, 0x1b, 0xd8, 0x30, 0x1b, 0xd8, 0x2f, 0x1b, 0xd7, 0x2d, 0x1b, 0xd7, 0x2b, 0x1b, 0xd7, + 0x29, 0x1c, 0xd7, 0x27, 0x1c, 0xd7, 0x25, 0x1c, 0xd6, 0x23, 0x1c, 0xd6, 0x21, 0x1c, 0xd6, 0x1f, + 0x1c, 0xd6, 0x1c, 0x1d, 0xd5, 0x19, 0x1d, 0xd5, 0x16, 0x1d, 0xd5, 0x13, 0x1d, 0xd5, 0x0f, 0x1d +}; +static constexpr std::array L19 = { + 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0xfe, 0xff, 0xfb, 0xfe, 0xff, 0xfa, 0xfd, 0xff, 0xf9, + 0xfd, 0xfe, 0xf7, 0xfc, 0xfe, 0xf6, 0xfc, 0xfe, 0xf5, 0xfb, 0xfe, 0xf4, 0xfb, 0xfe, 0xf2, 0xfa, + 0xfe, 0xf1, 0xfa, 0xfe, 0xf0, 0xf9, 0xfe, 0xef, 0xf9, 0xfe, 0xed, 0xf8, 0xfe, 0xec, 0xf8, 0xfd, + 0xeb, 0xf7, 0xfd, 0xe9, 0xf7, 0xfd, 0xe8, 0xf6, 0xfd, 0xe7, 0xf6, 0xfd, 0xe6, 0xf5, 0xfd, 0xe4, + 0xf5, 0xfd, 0xe3, 0xf4, 0xfd, 0xe2, 0xf4, 0xfd, 0xe1, 0xf3, 0xfd, 0xe0, 0xf3, 0xfd, 0xdf, 0xf2, + 0xfd, 0xde, 0xf1, 0xfd, 0xdc, 0xf1, 0xfd, 0xdb, 0xf0, 0xfd, 0xda, 0xf0, 0xfd, 0xd9, 0xef, 0xfd, + 0xd8, 0xee, 0xfd, 0xd7, 0xee, 0xfd, 0xd6, 0xed, 0xfd, 0xd5, 0xed, 0xfd, 0xd4, 0xec, 0xfd, 0xd3, + 0xec, 0xfd, 0xd2, 0xeb, 0xfd, 0xd1, 0xea, 0xfd, 0xd0, 0xea, 0xfd, 0xcf, 0xe9, 0xfe, 0xce, 0xe9, + 0xfe, 0xcd, 0xe8, 0xfe, 0xcc, 0xe8, 0xfe, 0xcb, 0xe7, 0xfe, 0xca, 0xe6, 0xfe, 0xc9, 0xe6, 0xfe, + 0xc8, 0xe5, 0xfe, 0xc8, 0xe4, 0xfe, 0xc7, 0xe4, 0xfe, 0xc6, 0xe3, 0xfe, 0xc6, 0xe2, 0xfe, 0xc5, + 0xe2, 0xfe, 0xc5, 0xe1, 0xfe, 0xc4, 0xe0, 0xfe, 0xc3, 0xe0, 0xfe, 0xc3, 0xdf, 0xfe, 0xc2, 0xde, + 0xfe, 0xc1, 0xde, 0xff, 0xc1, 0xdd, 0xff, 0xc0, 0xdc, 0xff, 0xbf, 0xdb, 0xff, 0xbf, 0xdb, 0xff, + 0xbe, 0xda, 0xff, 0xbd, 0xd9, 0xff, 0xbd, 0xd9, 0xff, 0xbc, 0xd8, 0xff, 0xbc, 0xd7, 0xff, 0xbb, + 0xd7, 0xff, 0xba, 0xd6, 0xff, 0xba, 0xd5, 0xff, 0xba, 0xd4, 0xff, 0xba, 0xd4, 0xff, 0xba, 0xd3, + 0xff, 0xba, 0xd2, 0xff, 0xba, 0xd1, 0xff, 0xba, 0xd0, 0xfe, 0xb9, 0xd0, 0xfe, 0xb9, 0xcf, 0xfe, + 0xb9, 0xce, 0xfe, 0xb9, 0xcd, 0xfe, 0xb9, 0xcc, 0xfe, 0xb9, 0xcc, 0xfe, 0xb9, 0xcb, 0xfe, 0xb9, + 0xca, 0xfe, 0xb8, 0xc9, 0xfe, 0xb8, 0xc9, 0xfe, 0xb8, 0xc8, 0xfd, 0xb8, 0xc7, 0xfd, 0xb8, 0xc6, + 0xfd, 0xb8, 0xc5, 0xfd, 0xb8, 0xc5, 0xfd, 0xb8, 0xc4, 0xfd, 0xb8, 0xc3, 0xfd, 0xb8, 0xc2, 0xfc, + 0xb9, 0xc1, 0xfc, 0xb9, 0xc0, 0xfb, 0xba, 0xbf, 0xfb, 0xba, 0xbe, 0xfb, 0xba, 0xbd, 0xfa, 0xbb, + 0xbc, 0xfa, 0xbb, 0xbc, 0xfa, 0xbb, 0xbb, 0xf9, 0xbc, 0xba, 0xf9, 0xbc, 0xb9, 0xf8, 0xbc, 0xb8, + 0xf8, 0xbd, 0xb7, 0xf8, 0xbd, 0xb6, 0xf7, 0xbd, 0xb5, 0xf7, 0xbe, 0xb4, 0xf7, 0xbe, 0xb3, 0xf6, + 0xbe, 0xb2, 0xf6, 0xbf, 0xb1, 0xf5, 0xbf, 0xb1, 0xf5, 0xbf, 0xb0, 0xf5, 0xc0, 0xaf, 0xf4, 0xc0, + 0xae, 0xf4, 0xc1, 0xad, 0xf3, 0xc2, 0xac, 0xf2, 0xc3, 0xab, 0xf1, 0xc3, 0xaa, 0xf1, 0xc4, 0xa9, + 0xf0, 0xc5, 0xa8, 0xef, 0xc5, 0xa6, 0xee, 0xc6, 0xa5, 0xee, 0xc7, 0xa4, 0xed, 0xc7, 0xa3, 0xec, + 0xc8, 0xa2, 0xeb, 0xc9, 0xa1, 0xeb, 0xc9, 0xa0, 0xea, 0xca, 0x9f, 0xe9, 0xca, 0x9e, 0xe8, 0xcb, + 0x9d, 0xe8, 0xcc, 0x9c, 0xe7, 0xcc, 0x9b, 0xe6, 0xcd, 0x9a, 0xe5, 0xcd, 0x99, 0xe5, 0xce, 0x98, + 0xe4, 0xce, 0x97, 0xe3, 0xcf, 0x96, 0xe2, 0xd0, 0x95, 0xe1, 0xd1, 0x93, 0xe0, 0xd1, 0x92, 0xde, + 0xd2, 0x91, 0xdd, 0xd3, 0x90, 0xdc, 0xd4, 0x8f, 0xdb, 0xd4, 0x8e, 0xda, 0xd5, 0x8d, 0xd8, 0xd6, + 0x8b, 0xd7, 0xd6, 0x8a, 0xd6, 0xd7, 0x89, 0xd5, 0xd8, 0x88, 0xd4, 0xd8, 0x87, 0xd3, 0xd9, 0x86, + 0xd1, 0xda, 0x84, 0xd0, 0xda, 0x83, 0xcf, 0xdb, 0x82, 0xce, 0xdc, 0x81, 0xcd, 0xdc, 0x80, 0xcc, + 0xdd, 0x7e, 0xca, 0xdd, 0x7d, 0xc9, 0xde, 0x7c, 0xc8, 0xdf, 0x7b, 0xc7, 0xdf, 0x7a, 0xc5, 0xe0, + 0x78, 0xc3, 0xe0, 0x77, 0xc2, 0xe1, 0x76, 0xc0, 0xe1, 0x75, 0xbf, 0xe2, 0x74, 0xbd, 0xe2, 0x72, + 0xbb, 0xe3, 0x71, 0xba, 0xe3, 0x70, 0xb8, 0xe4, 0x6f, 0xb7, 0xe4, 0x6e, 0xb5, 0xe5, 0x6c, 0xb4, + 0xe5, 0x6b, 0xb2, 0xe6, 0x6a, 0xb0, 0xe6, 0x68, 0xaf, 0xe7, 0x67, 0xad, 0xe7, 0x66, 0xac, 0xe8, + 0x65, 0xaa, 0xe8, 0x63, 0xa9, 0xe8, 0x62, 0xa7, 0xe9, 0x60, 0xa6, 0xe9, 0x5f, 0xa4, 0xe9, 0x5e, + 0xa2, 0xea, 0x5d, 0xa0, 0xea, 0x5c, 0x9e, 0xea, 0x5a, 0x9d, 0xea, 0x59, 0x9b, 0xea, 0x58, 0x99, + 0xeb, 0x57, 0x97, 0xeb, 0x55, 0x95, 0xeb, 0x54, 0x93, 0xeb, 0x53, 0x91, 0xeb, 0x52, 0x8f, 0xeb, + 0x50, 0x8d, 0xeb, 0x4f, 0x8c, 0xeb, 0x4e, 0x8a, 0xec, 0x4d, 0x88, 0xec, 0x4b, 0x86, 0xec, 0x4a, + 0x84, 0xec, 0x49, 0x82, 0xec, 0x47, 0x80, 0xec, 0x46, 0x7e, 0xec, 0x44, 0x7d, 0xec, 0x43, 0x7b, + 0xec, 0x42, 0x79, 0xec, 0x40, 0x77, 0xec, 0x3f, 0x75, 0xeb, 0x3e, 0x73, 0xeb, 0x3d, 0x71, 0xeb, + 0x3c, 0x6f, 0xea, 0x3b, 0x6c, 0xea, 0x3a, 0x6a, 0xea, 0x39, 0x68, 0xea, 0x38, 0x66, 0xe9, 0x37, + 0x64, 0xe9, 0x36, 0x62, 0xe8, 0x35, 0x60, 0xe8, 0x34, 0x5e, 0xe8, 0x33, 0x5c, 0xe7, 0x32, 0x5a, + 0xe7, 0x31, 0x58, 0xe7, 0x30, 0x56, 0xe6, 0x2e, 0x54, 0xe6, 0x2d, 0x52, 0xe5, 0x2c, 0x4f, 0xe5, + 0x2b, 0x4d, 0xe5, 0x2a, 0x4b, 0xe4, 0x28, 0x49, 0xe4, 0x27, 0x47, 0xe3, 0x27, 0x45, 0xe2, 0x27, + 0x43, 0xe1, 0x26, 0x41, 0xe0, 0x26, 0x3e, 0xe0, 0x26, 0x3c, 0xdf, 0x26, 0x3a, 0xde, 0x25, 0x38, + 0xdd, 0x25, 0x35, 0xdc, 0x25, 0x33, 0xdb, 0x24, 0x31, 0xdb, 0x24, 0x2f, 0xda, 0x24, 0x2c, 0xd9, + 0x24, 0x2a, 0xd8, 0x23, 0x27, 0xd7, 0x23, 0x25, 0xd6, 0x23, 0x23, 0xd5, 0x22, 0x20, 0xd5, 0x22, + 0x1d, 0xd4, 0x22, 0x1b, 0xd3, 0x22, 0x18, 0xd2, 0x22, 0x15, 0xd1, 0x21, 0x12, 0xd0, 0x21, 0x0e +}; +static constexpr std::array L20 = { + 0x30, 0x30, 0x30, 0x31, 0x31, 0x33, 0x32, 0x31, 0x35, 0x33, 0x31, 0x38, 0x34, 0x32, 0x3b, 0x35, + 0x32, 0x3d, 0x36, 0x32, 0x40, 0x36, 0x33, 0x42, 0x37, 0x33, 0x45, 0x38, 0x33, 0x47, 0x39, 0x34, + 0x4a, 0x39, 0x34, 0x4c, 0x3a, 0x34, 0x4f, 0x3b, 0x35, 0x51, 0x3b, 0x35, 0x54, 0x3c, 0x36, 0x56, + 0x3c, 0x36, 0x59, 0x3d, 0x36, 0x5b, 0x3d, 0x37, 0x5e, 0x3e, 0x37, 0x60, 0x3e, 0x37, 0x63, 0x3f, + 0x38, 0x65, 0x3f, 0x38, 0x68, 0x40, 0x39, 0x6a, 0x40, 0x39, 0x6c, 0x40, 0x39, 0x6f, 0x41, 0x3a, + 0x71, 0x41, 0x3a, 0x74, 0x41, 0x3b, 0x76, 0x42, 0x3b, 0x78, 0x42, 0x3c, 0x7b, 0x42, 0x3c, 0x7d, + 0x42, 0x3d, 0x7f, 0x42, 0x3d, 0x82, 0x43, 0x3e, 0x84, 0x43, 0x3e, 0x86, 0x43, 0x3f, 0x89, 0x43, + 0x3f, 0x8b, 0x43, 0x40, 0x8d, 0x43, 0x40, 0x8f, 0x43, 0x41, 0x91, 0x43, 0x41, 0x93, 0x43, 0x42, + 0x96, 0x43, 0x42, 0x98, 0x43, 0x43, 0x9a, 0x43, 0x43, 0x9c, 0x43, 0x44, 0x9e, 0x43, 0x45, 0xa0, + 0x43, 0x45, 0xa2, 0x42, 0x46, 0xa4, 0x42, 0x47, 0xa6, 0x42, 0x47, 0xa8, 0x42, 0x48, 0xa9, 0x42, + 0x49, 0xab, 0x42, 0x49, 0xad, 0x41, 0x4a, 0xaf, 0x41, 0x4b, 0xb0, 0x41, 0x4b, 0xb2, 0x41, 0x4c, + 0xb4, 0x40, 0x4d, 0xb5, 0x40, 0x4e, 0xb7, 0x40, 0x4e, 0xb8, 0x3f, 0x4f, 0xba, 0x3f, 0x50, 0xbb, + 0x3f, 0x51, 0xbc, 0x3e, 0x52, 0xbe, 0x3e, 0x53, 0xbf, 0x3d, 0x53, 0xc0, 0x3d, 0x54, 0xc1, 0x3d, + 0x55, 0xc2, 0x3c, 0x56, 0xc3, 0x3c, 0x57, 0xc4, 0x3b, 0x58, 0xc5, 0x3b, 0x59, 0xc6, 0x3a, 0x5a, + 0xc6, 0x3a, 0x5b, 0xc7, 0x3a, 0x5c, 0xc8, 0x39, 0x5d, 0xc8, 0x39, 0x5e, 0xc8, 0x38, 0x60, 0xc9, + 0x37, 0x61, 0xc9, 0x37, 0x62, 0xc9, 0x36, 0x63, 0xc9, 0x36, 0x64, 0xc8, 0x35, 0x65, 0xc8, 0x34, + 0x67, 0xc8, 0x34, 0x68, 0xc7, 0x33, 0x69, 0xc6, 0x32, 0x6b, 0xc5, 0x31, 0x6c, 0xc4, 0x30, 0x6e, + 0xc3, 0x2f, 0x6f, 0xc1, 0x2e, 0x70, 0xc0, 0x2d, 0x72, 0xbe, 0x2b, 0x74, 0xbb, 0x2a, 0x75, 0xb9, + 0x29, 0x77, 0xb7, 0x27, 0x78, 0xb5, 0x26, 0x7a, 0xb3, 0x25, 0x7b, 0xb0, 0x24, 0x7c, 0xae, 0x24, + 0x7e, 0xac, 0x23, 0x7f, 0xaa, 0x22, 0x80, 0xa8, 0x22, 0x82, 0xa6, 0x22, 0x83, 0xa4, 0x22, 0x84, + 0xa1, 0x22, 0x85, 0x9f, 0x22, 0x86, 0x9d, 0x23, 0x88, 0x9b, 0x24, 0x89, 0x99, 0x24, 0x8a, 0x97, + 0x25, 0x8b, 0x95, 0x26, 0x8c, 0x93, 0x28, 0x8d, 0x91, 0x29, 0x8e, 0x8f, 0x2a, 0x8f, 0x8d, 0x2c, + 0x90, 0x8b, 0x2d, 0x91, 0x89, 0x2f, 0x92, 0x87, 0x31, 0x93, 0x85, 0x33, 0x94, 0x83, 0x35, 0x95, + 0x81, 0x37, 0x96, 0x7f, 0x39, 0x97, 0x7d, 0x3b, 0x98, 0x7b, 0x3d, 0x98, 0x79, 0x3f, 0x99, 0x78, + 0x42, 0x9a, 0x76, 0x44, 0x9b, 0x74, 0x46, 0x9c, 0x72, 0x49, 0x9d, 0x70, 0x4b, 0x9d, 0x6e, 0x4e, + 0x9e, 0x6c, 0x50, 0x9f, 0x6a, 0x53, 0x9f, 0x68, 0x55, 0xa0, 0x67, 0x58, 0xa1, 0x65, 0x5b, 0xa2, + 0x63, 0x5d, 0xa2, 0x61, 0x60, 0xa3, 0x5f, 0x63, 0xa3, 0x5d, 0x66, 0xa4, 0x5b, 0x69, 0xa5, 0x59, + 0x6c, 0xa5, 0x57, 0x6f, 0xa6, 0x56, 0x71, 0xa6, 0x54, 0x74, 0xa7, 0x52, 0x77, 0xa7, 0x50, 0x7a, + 0xa8, 0x4e, 0x7c, 0xa8, 0x4c, 0x7f, 0xa9, 0x4a, 0x82, 0xa9, 0x48, 0x84, 0xaa, 0x47, 0x87, 0xaa, + 0x45, 0x89, 0xab, 0x43, 0x8c, 0xab, 0x41, 0x8f, 0xac, 0x3f, 0x91, 0xac, 0x3d, 0x94, 0xad, 0x3b, + 0x96, 0xad, 0x3a, 0x98, 0xae, 0x38, 0x9b, 0xae, 0x36, 0x9d, 0xae, 0x34, 0xa0, 0xaf, 0x32, 0xa2, + 0xaf, 0x30, 0xa5, 0xb0, 0x2e, 0xa7, 0xb0, 0x2d, 0xaa, 0xb0, 0x2b, 0xac, 0xb1, 0x29, 0xaf, 0xb1, + 0x27, 0xb1, 0xb2, 0x25, 0xb4, 0xb2, 0x24, 0xb6, 0xb2, 0x22, 0xb9, 0xb3, 0x20, 0xbb, 0xb3, 0x1e, + 0xbe, 0xb3, 0x1d, 0xc0, 0xb3, 0x1b, 0xc3, 0xb4, 0x19, 0xc5, 0xb4, 0x18, 0xc8, 0xb4, 0x17, 0xcb, + 0xb4, 0x15, 0xcd, 0xb5, 0x14, 0xd0, 0xb5, 0x13, 0xd3, 0xb5, 0x13, 0xd5, 0xb5, 0x12, 0xd8, 0xb5, + 0x12, 0xdb, 0xb5, 0x12, 0xdd, 0xb6, 0x12, 0xe0, 0xb6, 0x13, 0xe2, 0xb6, 0x13, 0xe4, 0xb6, 0x13, + 0xe6, 0xb7, 0x13, 0xe8, 0xb7, 0x13, 0xe9, 0xb8, 0x14, 0xeb, 0xb8, 0x14, 0xec, 0xb9, 0x14, 0xee, + 0xba, 0x14, 0xef, 0xba, 0x14, 0xf0, 0xbb, 0x14, 0xf1, 0xbc, 0x14, 0xf2, 0xbc, 0x14, 0xf3, 0xbd, + 0x14, 0xf4, 0xbe, 0x14, 0xf5, 0xbf, 0x14, 0xf6, 0xc0, 0x14, 0xf7, 0xc1, 0x14, 0xf7, 0xc1, 0x14, + 0xf8, 0xc2, 0x14, 0xf9, 0xc3, 0x14, 0xf9, 0xc4, 0x14, 0xfa, 0xc5, 0x14, 0xfa, 0xc6, 0x14, 0xfb, + 0xc7, 0x14, 0xfb, 0xc8, 0x14, 0xfc, 0xc9, 0x14, 0xfc, 0xca, 0x14, 0xfd, 0xcb, 0x13, 0xfd, 0xcc, + 0x13, 0xfd, 0xcd, 0x13, 0xfd, 0xcf, 0x13, 0xfe, 0xd0, 0x13, 0xfe, 0xd1, 0x13, 0xfe, 0xd2, 0x13, + 0xfe, 0xd3, 0x13, 0xfe, 0xd4, 0x12, 0xfe, 0xd5, 0x12, 0xff, 0xd6, 0x12, 0xff, 0xd8, 0x12, 0xff, + 0xd9, 0x12, 0xff, 0xda, 0x12, 0xff, 0xdb, 0x11, 0xff, 0xdc, 0x11, 0xff, 0xdd, 0x11, 0xff, 0xdf, + 0x11, 0xfe, 0xe0, 0x10, 0xfe, 0xe1, 0x10, 0xfe, 0xe2, 0x10, 0xfe, 0xe3, 0x10, 0xfe, 0xe5, 0x0f, + 0xfe, 0xe6, 0x0f, 0xfe, 0xe7, 0x0f, 0xfd, 0xe8, 0x0f, 0xfd, 0xea, 0x0e, 0xfd, 0xeb, 0x0e, 0xfd, + 0xec, 0x0e, 0xfc, 0xed, 0x0d, 0xfc, 0xef, 0x0d, 0xfc, 0xf0, 0x0d, 0xfb, 0xf1, 0x0c, 0xfb, 0xf2, + 0x0c, 0xfa, 0xf4, 0x0c, 0xfa, 0xf5, 0x0b, 0xfa, 0xf6, 0x0b, 0xf9, 0xf7, 0x0a, 0xf9, 0xf9, 0x0a +}; - // diverging - static constexpr std::array D01 = {0x21,0x51,0xdb,0x25,0x52,0xdb,0x2a,0x53,0xdb,0x2e,0x54,0xdc,0x31,0x55,0xdc,0x35,0x56,0xdc,0x38,0x57,0xdc,0x3b,0x58,0xdc,0x3e,0x59,0xdd,0x41,0x5b,0xdd,0x43,0x5c,0xdd,0x46,0x5d,0xdd,0x48,0x5e,0xdd,0x4b,0x5f,0xde,0x4d,0x60,0xde,0x50,0x61,0xde,0x52,0x63,0xde,0x54,0x64,0xdf,0x56,0x65,0xdf,0x58,0x66,0xdf,0x5a,0x67,0xdf,0x5c,0x68,0xdf,0x5e,0x69,0xe0,0x60,0x6b,0xe0,0x62,0x6c,0xe0,0x64,0x6d,0xe0,0x66,0x6e,0xe0,0x68,0x6f,0xe1,0x69,0x70,0xe1,0x6b,0x72,0xe1,0x6d,0x73,0xe1,0x6f,0x74,0xe1,0x70,0x75,0xe2,0x72,0x76,0xe2,0x74,0x78,0xe2,0x75,0x79,0xe2,0x77,0x7a,0xe2,0x79,0x7b,0xe3,0x7a,0x7c,0xe3,0x7c,0x7e,0xe3,0x7d,0x7f,0xe3,0x7f,0x80,0xe3,0x81,0x81,0xe4,0x82,0x82,0xe4,0x84,0x84,0xe4,0x85,0x85,0xe4,0x87,0x86,0xe4,0x88,0x87,0xe5,0x8a,0x88,0xe5,0x8b,0x8a,0xe5,0x8d,0x8b,0xe5,0x8e,0x8c,0xe5,0x8f,0x8d,0xe5,0x91,0x8f,0xe6,0x92,0x90,0xe6,0x94,0x91,0xe6,0x95,0x92,0xe6,0x97,0x94,0xe6,0x98,0x95,0xe7,0x99,0x96,0xe7,0x9b,0x97,0xe7,0x9c,0x99,0xe7,0x9e,0x9a,0xe7,0x9f,0x9b,0xe7,0xa0,0x9c,0xe8,0xa2,0x9e,0xe8,0xa3,0x9f,0xe8,0xa4,0xa0,0xe8,0xa6,0xa1,0xe8,0xa7,0xa3,0xe8,0xa8,0xa4,0xe9,0xaa,0xa5,0xe9,0xab,0xa6,0xe9,0xac,0xa8,0xe9,0xae,0xa9,0xe9,0xaf,0xaa,0xe9,0xb0,0xac,0xea,0xb2,0xad,0xea,0xb3,0xae,0xea,0xb4,0xaf,0xea,0xb5,0xb1,0xea,0xb7,0xb2,0xea,0xb8,0xb3,0xeb,0xb9,0xb4,0xeb,0xbb,0xb6,0xeb,0xbc,0xb7,0xeb,0xbd,0xb8,0xeb,0xbe,0xba,0xeb,0xc0,0xbb,0xeb,0xc1,0xbc,0xec,0xc2,0xbe,0xec,0xc3,0xbf,0xec,0xc5,0xc0,0xec,0xc6,0xc1,0xec,0xc7,0xc3,0xec,0xc8,0xc4,0xec,0xca,0xc5,0xed,0xcb,0xc7,0xed,0xcc,0xc8,0xed,0xcd,0xc9,0xed,0xcf,0xcb,0xed,0xd0,0xcc,0xed,0xd1,0xcd,0xed,0xd2,0xcf,0xee,0xd3,0xd0,0xee,0xd5,0xd1,0xee,0xd6,0xd3,0xee,0xd7,0xd4,0xee,0xd8,0xd5,0xee,0xda,0xd7,0xee,0xdb,0xd8,0xee,0xdc,0xd9,0xef,0xdd,0xda,0xef,0xde,0xdc,0xef,0xe0,0xdd,0xef,0xe1,0xde,0xef,0xe2,0xe0,0xef,0xe3,0xe1,0xef,0xe4,0xe2,0xef,0xe5,0xe3,0xef,0xe6,0xe4,0xee,0xe7,0xe5,0xee,0xe8,0xe5,0xee,0xe9,0xe6,0xed,0xea,0xe7,0xed,0xeb,0xe7,0xec,0xec,0xe7,0xeb,0xed,0xe7,0xea,0xee,0xe7,0xe9,0xee,0xe7,0xe8,0xef,0xe6,0xe7,0xef,0xe6,0xe6,0xf0,0xe5,0xe4,0xf0,0xe4,0xe3,0xf1,0xe3,0xe1,0xf1,0xe2,0xdf,0xf1,0xe1,0xdd,0xf1,0xe0,0xdc,0xf1,0xde,0xda,0xf2,0xdd,0xd8,0xf2,0xdb,0xd6,0xf2,0xda,0xd4,0xf2,0xd8,0xd2,0xf2,0xd7,0xd0,0xf2,0xd5,0xce,0xf2,0xd4,0xcc,0xf2,0xd2,0xcb,0xf2,0xd1,0xc9,0xf2,0xcf,0xc7,0xf2,0xce,0xc5,0xf2,0xcc,0xc3,0xf1,0xcb,0xc1,0xf1,0xc9,0xbf,0xf1,0xc7,0xbd,0xf1,0xc6,0xbb,0xf1,0xc4,0xb9,0xf1,0xc3,0xb7,0xf1,0xc1,0xb5,0xf1,0xc0,0xb4,0xf0,0xbe,0xb2,0xf0,0xbd,0xb0,0xf0,0xbb,0xae,0xf0,0xb9,0xac,0xf0,0xb8,0xaa,0xf0,0xb6,0xa8,0xef,0xb5,0xa6,0xef,0xb3,0xa5,0xef,0xb2,0xa3,0xef,0xb0,0xa1,0xee,0xaf,0x9f,0xee,0xad,0x9d,0xee,0xac,0x9b,0xee,0xaa,0x99,0xed,0xa8,0x98,0xed,0xa7,0x96,0xed,0xa5,0x94,0xed,0xa4,0x92,0xec,0xa2,0x90,0xec,0xa1,0x8e,0xec,0x9f,0x8c,0xeb,0x9d,0x8b,0xeb,0x9c,0x89,0xeb,0x9a,0x87,0xea,0x99,0x85,0xea,0x97,0x83,0xea,0x96,0x82,0xe9,0x94,0x80,0xe9,0x93,0x7e,0xe8,0x91,0x7c,0xe8,0x8f,0x7a,0xe8,0x8e,0x79,0xe7,0x8c,0x77,0xe7,0x8b,0x75,0xe6,0x89,0x73,0xe6,0x88,0x71,0xe6,0x86,0x70,0xe5,0x84,0x6e,0xe5,0x83,0x6c,0xe4,0x81,0x6a,0xe4,0x80,0x69,0xe3,0x7e,0x67,0xe3,0x7c,0x65,0xe2,0x7b,0x63,0xe2,0x79,0x62,0xe1,0x78,0x60,0xe1,0x76,0x5e,0xe0,0x74,0x5c,0xe0,0x73,0x5b,0xdf,0x71,0x59,0xdf,0x6f,0x57,0xde,0x6e,0x55,0xde,0x6c,0x54,0xdd,0x6a,0x52,0xdd,0x69,0x50,0xdc,0x67,0x4f,0xdb,0x66,0x4d,0xdb,0x64,0x4b,0xda,0x62,0x49,0xda,0x60,0x48,0xd9,0x5f,0x46,0xd8,0x5d,0x44,0xd8,0x5b,0x43,0xd7,0x5a,0x41,0xd7,0x58,0x3f,0xd6,0x56,0x3e,0xd5,0x54,0x3c,0xd5,0x52,0x3a,0xd4,0x51,0x38,0xd3,0x4f,0x37,0xd3,0x4d,0x35,0xd2,0x4b,0x33,0xd1,0x49,0x32,0xd1,0x47,0x30,0xd0,0x45,0x2e,0xcf,0x44,0x2d,0xcf,0x42,0x2b,0xce,0x40,0x29,0xcd,0x3d,0x28,0xcd,0x3b,0x26,0xcc,0x39,0x24,0xcb,0x37,0x22,0xca,0x35,0x21,0xca,0x33,0x1f,0xc9,0x30,0x1d,0xc8,0x2e,0x1b,0xc8,0x2b,0x1a,0xc7,0x29,0x18,0xc6,0x26,0x16,0xc5,0x23,0x14,0xc5,0x20,0x12,0xc4,0x1c,0x10,0xc3,0x19,0x0e,0xc2,0x14,0x0c,0xc1,0x0f,0x0a,0xc1,0x09,0x08,0xc0,0x02,0x06}; - static constexpr std::array D01A = {0x17,0x29,0x72,0x18,0x2a,0x75,0x18,0x2b,0x78,0x19,0x2c,0x7b,0x19,0x2d,0x7e,0x19,0x2f,0x80,0x1a,0x30,0x83,0x1a,0x31,0x86,0x1a,0x32,0x89,0x1b,0x33,0x8c,0x1b,0x34,0x8f,0x1b,0x35,0x92,0x1c,0x36,0x95,0x1c,0x38,0x98,0x1c,0x39,0x9b,0x1c,0x3a,0x9e,0x1d,0x3b,0xa1,0x1d,0x3c,0xa4,0x1d,0x3d,0xa7,0x1e,0x3e,0xab,0x1e,0x40,0xae,0x1e,0x41,0xb1,0x1f,0x42,0xb4,0x1f,0x43,0xb7,0x20,0x44,0xba,0x20,0x46,0xbd,0x21,0x47,0xbf,0x22,0x48,0xc2,0x23,0x49,0xc5,0x24,0x4a,0xc8,0x25,0x4c,0xca,0x27,0x4d,0xcd,0x29,0x4e,0xcf,0x2b,0x50,0xd2,0x2d,0x51,0xd4,0x2f,0x52,0xd6,0x31,0x54,0xd8,0x34,0x55,0xd9,0x37,0x56,0xdb,0x39,0x58,0xdc,0x3c,0x59,0xde,0x3f,0x5b,0xdf,0x42,0x5c,0xe0,0x44,0x5d,0xe1,0x47,0x5f,0xe2,0x4a,0x60,0xe3,0x4d,0x62,0xe4,0x4f,0x63,0xe5,0x52,0x65,0xe6,0x55,0x66,0xe7,0x57,0x68,0xe8,0x5a,0x69,0xe9,0x5c,0x6b,0xea,0x5f,0x6c,0xeb,0x61,0x6e,0xeb,0x63,0x6f,0xec,0x66,0x71,0xed,0x68,0x73,0xee,0x6a,0x74,0xef,0x6d,0x76,0xf0,0x6f,0x77,0xf0,0x71,0x79,0xf1,0x73,0x7a,0xf2,0x75,0x7c,0xf3,0x77,0x7e,0xf4,0x7a,0x7f,0xf4,0x7c,0x81,0xf5,0x7e,0x82,0xf6,0x80,0x84,0xf7,0x82,0x85,0xf7,0x84,0x87,0xf8,0x86,0x89,0xf9,0x88,0x8a,0xf9,0x8a,0x8c,0xfa,0x8d,0x8e,0xfb,0x8f,0x8f,0xfb,0x91,0x91,0xfb,0x93,0x93,0xfc,0x95,0x94,0xfc,0x97,0x96,0xfc,0x99,0x98,0xfc,0x9b,0x99,0xfd,0x9d,0x9b,0xfd,0x9f,0x9d,0xfd,0xa1,0x9f,0xfd,0xa3,0xa0,0xfc,0xa5,0xa2,0xfc,0xa7,0xa4,0xfc,0xa9,0xa6,0xfc,0xab,0xa7,0xfc,0xad,0xa9,0xfc,0xaf,0xab,0xfc,0xb1,0xad,0xfb,0xb3,0xaf,0xfb,0xb5,0xb0,0xfb,0xb7,0xb2,0xfb,0xb9,0xb4,0xfa,0xbb,0xb6,0xfa,0xbd,0xb8,0xfa,0xbf,0xb9,0xfa,0xc0,0xbb,0xf9,0xc2,0xbd,0xf9,0xc4,0xbf,0xf9,0xc6,0xc1,0xf9,0xc8,0xc3,0xf8,0xc9,0xc4,0xf8,0xcb,0xc6,0xf8,0xcd,0xc8,0xf7,0xcf,0xca,0xf7,0xd0,0xcc,0xf7,0xd2,0xce,0xf7,0xd4,0xcf,0xf6,0xd6,0xd1,0xf6,0xd7,0xd3,0xf5,0xd9,0xd5,0xf5,0xdb,0xd7,0xf5,0xdc,0xd8,0xf4,0xde,0xda,0xf4,0xe0,0xdb,0xf3,0xe1,0xdd,0xf2,0xe3,0xde,0xf2,0xe5,0xdf,0xf1,0xe6,0xe1,0xf0,0xe8,0xe1,0xef,0xe9,0xe2,0xed,0xeb,0xe3,0xec,0xec,0xe3,0xea,0xed,0xe3,0xe9,0xef,0xe3,0xe7,0xf0,0xe2,0xe5,0xf1,0xe1,0xe3,0xf2,0xe1,0xe1,0xf3,0xdf,0xde,0xf4,0xde,0xdc,0xf5,0xdd,0xd9,0xf6,0xdb,0xd6,0xf7,0xd9,0xd4,0xf7,0xd7,0xd1,0xf8,0xd5,0xce,0xf9,0xd3,0xcb,0xf9,0xd1,0xc9,0xfa,0xcf,0xc6,0xfa,0xcd,0xc3,0xfa,0xca,0xc0,0xfb,0xc8,0xbd,0xfb,0xc6,0xba,0xfb,0xc3,0xb7,0xfc,0xc1,0xb5,0xfc,0xbf,0xb2,0xfc,0xbd,0xaf,0xfc,0xba,0xac,0xfc,0xb8,0xa9,0xfc,0xb6,0xa6,0xfd,0xb3,0xa4,0xfd,0xb1,0xa1,0xfd,0xaf,0x9e,0xfd,0xac,0x9b,0xfd,0xaa,0x98,0xfd,0xa7,0x96,0xfd,0xa5,0x93,0xfd,0xa3,0x90,0xfd,0xa0,0x8d,0xfd,0x9e,0x8b,0xfc,0x9c,0x88,0xfc,0x99,0x85,0xfc,0x97,0x82,0xfc,0x94,0x80,0xfc,0x92,0x7d,0xfb,0x90,0x7a,0xfb,0x8d,0x78,0xfb,0x8b,0x75,0xfa,0x88,0x73,0xfa,0x86,0x70,0xf9,0x84,0x6d,0xf9,0x81,0x6b,0xf8,0x7f,0x69,0xf8,0x7d,0x66,0xf7,0x7a,0x64,0xf6,0x78,0x61,0xf5,0x76,0x5f,0xf5,0x73,0x5d,0xf4,0x71,0x5b,0xf3,0x6f,0x58,0xf2,0x6d,0x56,0xf1,0x6b,0x54,0xf0,0x68,0x52,0xef,0x66,0x50,0xed,0x64,0x4e,0xec,0x62,0x4c,0xeb,0x60,0x4a,0xea,0x5e,0x48,0xe9,0x5b,0x46,0xe7,0x59,0x44,0xe6,0x57,0x42,0xe5,0x55,0x40,0xe4,0x53,0x3f,0xe2,0x50,0x3d,0xe1,0x4e,0x3b,0xe0,0x4c,0x39,0xdf,0x49,0x37,0xdd,0x47,0x35,0xdc,0x45,0x33,0xdb,0x42,0x31,0xd9,0x40,0x2f,0xd8,0x3d,0x2d,0xd7,0x3b,0x2c,0xd6,0x38,0x2a,0xd4,0x36,0x28,0xd3,0x33,0x26,0xd1,0x30,0x24,0xd0,0x2e,0x22,0xcf,0x2b,0x21,0xcd,0x28,0x1f,0xcc,0x25,0x1d,0xca,0x22,0x1b,0xc8,0x1f,0x1a,0xc7,0x1c,0x18,0xc5,0x19,0x17,0xc3,0x16,0x15,0xc1,0x13,0x14,0xbf,0x10,0x13,0xbd,0x0d,0x12,0xbb,0x0a,0x11,0xb9,0x07,0x10,0xb6,0x05,0x0f,0xb4,0x03,0x0e,0xb2,0x02,0x0d,0xaf,0x01,0x0d,0xad,0x00,0x0c,0xaa,0x00,0x0c,0xa7,0x00,0x0c,0xa5,0x00,0x0b,0xa2,0x00,0x0b,0x9f,0x01,0x0b,0x9d,0x01,0x0a,0x9a,0x02,0x0a,0x97,0x02,0x0a,0x95,0x02,0x0a,0x92,0x03,0x09,0x8f,0x03,0x09,0x8d,0x04,0x09,0x8a,0x04,0x08,0x87,0x04,0x08,0x85,0x05,0x08,0x82,0x05,0x07,0x80,0x05,0x07,0x7d,0x06,0x07,0x7a,0x06,0x06,0x78,0x06,0x06,0x75,0x06,0x05,0x73,0x07,0x05,0x70,0x07,0x04,0x6e,0x07,0x04,0x6b,0x07,0x03,0x69,0x07,0x03,0x66,0x07,0x02}; - static constexpr std::array D02 = {0x39,0x97,0x0e,0x3b,0x97,0x12,0x3d,0x98,0x15,0x3f,0x99,0x18,0x40,0x9a,0x1a,0x42,0x9a,0x1d,0x44,0x9b,0x1f,0x46,0x9c,0x22,0x48,0x9c,0x24,0x4a,0x9d,0x26,0x4b,0x9e,0x28,0x4d,0x9f,0x2a,0x4f,0x9f,0x2c,0x51,0xa0,0x2e,0x52,0xa1,0x30,0x54,0xa1,0x32,0x56,0xa2,0x34,0x57,0xa3,0x36,0x59,0xa4,0x38,0x5a,0xa4,0x39,0x5c,0xa5,0x3b,0x5e,0xa6,0x3d,0x5f,0xa6,0x3f,0x61,0xa7,0x41,0x62,0xa8,0x42,0x64,0xa9,0x44,0x65,0xa9,0x46,0x67,0xaa,0x47,0x68,0xab,0x49,0x6a,0xab,0x4b,0x6b,0xac,0x4d,0x6d,0xad,0x4e,0x6e,0xae,0x50,0x70,0xae,0x52,0x71,0xaf,0x53,0x73,0xb0,0x55,0x74,0xb0,0x57,0x76,0xb1,0x58,0x77,0xb2,0x5a,0x79,0xb2,0x5c,0x7a,0xb3,0x5d,0x7c,0xb4,0x5f,0x7d,0xb5,0x61,0x7e,0xb5,0x62,0x80,0xb6,0x64,0x81,0xb7,0x66,0x83,0xb7,0x67,0x84,0xb8,0x69,0x85,0xb9,0x6a,0x87,0xba,0x6c,0x88,0xba,0x6e,0x8a,0xbb,0x6f,0x8b,0xbc,0x71,0x8c,0xbc,0x73,0x8e,0xbd,0x74,0x8f,0xbe,0x76,0x91,0xbe,0x78,0x92,0xbf,0x79,0x93,0xc0,0x7b,0x95,0xc1,0x7c,0x96,0xc1,0x7e,0x97,0xc2,0x80,0x99,0xc3,0x81,0x9a,0xc3,0x83,0x9b,0xc4,0x85,0x9d,0xc5,0x86,0x9e,0xc5,0x88,0xa0,0xc6,0x8a,0xa1,0xc7,0x8b,0xa2,0xc8,0x8d,0xa4,0xc8,0x8e,0xa5,0xc9,0x90,0xa6,0xca,0x92,0xa8,0xca,0x93,0xa9,0xcb,0x95,0xaa,0xcc,0x97,0xac,0xcc,0x98,0xad,0xcd,0x9a,0xae,0xce,0x9c,0xb0,0xce,0x9d,0xb1,0xcf,0x9f,0xb2,0xd0,0xa1,0xb4,0xd1,0xa2,0xb5,0xd1,0xa4,0xb6,0xd2,0xa6,0xb8,0xd3,0xa7,0xb9,0xd3,0xa9,0xba,0xd4,0xab,0xbc,0xd5,0xac,0xbd,0xd5,0xae,0xbe,0xd6,0xb0,0xc0,0xd7,0xb1,0xc1,0xd8,0xb3,0xc2,0xd8,0xb5,0xc4,0xd9,0xb6,0xc5,0xda,0xb8,0xc6,0xda,0xba,0xc7,0xdb,0xbb,0xc9,0xdc,0xbd,0xca,0xdc,0xbf,0xcb,0xdd,0xc0,0xcd,0xde,0xc2,0xce,0xde,0xc4,0xcf,0xdf,0xc5,0xd1,0xe0,0xc7,0xd2,0xe0,0xc9,0xd3,0xe1,0xca,0xd5,0xe2,0xcc,0xd6,0xe3,0xce,0xd7,0xe3,0xcf,0xd9,0xe4,0xd1,0xda,0xe5,0xd3,0xdb,0xe5,0xd5,0xdc,0xe6,0xd6,0xde,0xe7,0xd8,0xdf,0xe7,0xda,0xe0,0xe8,0xdb,0xe1,0xe8,0xdd,0xe3,0xe9,0xde,0xe4,0xe9,0xe0,0xe5,0xea,0xe2,0xe6,0xea,0xe3,0xe7,0xeb,0xe4,0xe8,0xeb,0xe6,0xe9,0xeb,0xe7,0xea,0xeb,0xe8,0xea,0xeb,0xe9,0xeb,0xeb,0xea,0xec,0xeb,0xeb,0xec,0xea,0xec,0xec,0xea,0xed,0xed,0xe9,0xed,0xed,0xe9,0xee,0xed,0xe8,0xee,0xed,0xe7,0xef,0xed,0xe6,0xef,0xed,0xe5,0xef,0xed,0xe4,0xef,0xec,0xe3,0xef,0xec,0xe2,0xf0,0xec,0xe1,0xf0,0xec,0xe0,0xf0,0xeb,0xdf,0xf0,0xeb,0xde,0xf0,0xeb,0xdd,0xef,0xea,0xdc,0xef,0xea,0xda,0xef,0xea,0xd9,0xef,0xe9,0xd8,0xef,0xe9,0xd7,0xef,0xe9,0xd6,0xef,0xe8,0xd5,0xef,0xe8,0xd4,0xef,0xe7,0xd2,0xef,0xe7,0xd1,0xef,0xe7,0xd0,0xef,0xe6,0xcf,0xef,0xe6,0xce,0xef,0xe6,0xcd,0xee,0xe5,0xcc,0xee,0xe5,0xca,0xee,0xe4,0xc9,0xee,0xe4,0xc8,0xee,0xe4,0xc7,0xee,0xe3,0xc6,0xee,0xe3,0xc5,0xee,0xe2,0xc4,0xee,0xe2,0xc2,0xee,0xe2,0xc1,0xee,0xe1,0xc0,0xee,0xe1,0xbf,0xed,0xe0,0xbe,0xed,0xe0,0xbd,0xed,0xe0,0xbb,0xed,0xdf,0xba,0xed,0xdf,0xb9,0xed,0xde,0xb8,0xed,0xde,0xb7,0xed,0xde,0xb6,0xed,0xdd,0xb5,0xed,0xdd,0xb3,0xed,0xdc,0xb2,0xed,0xdc,0xb1,0xec,0xdb,0xb0,0xec,0xdb,0xaf,0xec,0xdb,0xae,0xec,0xda,0xad,0xec,0xda,0xab,0xec,0xd9,0xaa,0xec,0xd9,0xa9,0xec,0xd8,0xa8,0xec,0xd8,0xa7,0xec,0xd8,0xa6,0xeb,0xd7,0xa4,0xeb,0xd7,0xa3,0xeb,0xd6,0xa2,0xeb,0xd6,0xa1,0xeb,0xd5,0xa0,0xeb,0xd5,0x9f,0xeb,0xd4,0x9e,0xeb,0xd4,0x9c,0xeb,0xd3,0x9b,0xeb,0xd3,0x9a,0xea,0xd3,0x99,0xea,0xd2,0x98,0xea,0xd2,0x97,0xea,0xd1,0x95,0xea,0xd1,0x94,0xea,0xd0,0x93,0xea,0xd0,0x92,0xea,0xcf,0x91,0xea,0xcf,0x90,0xea,0xce,0x8e,0xe9,0xce,0x8d,0xe9,0xcd,0x8c,0xe9,0xcd,0x8b,0xe9,0xcc,0x8a,0xe9,0xcc,0x88,0xe9,0xcb,0x87,0xe9,0xcb,0x86,0xe9,0xca,0x85,0xe9,0xca,0x84,0xe8,0xc9,0x82,0xe8,0xc9,0x81,0xe8,0xc8,0x80,0xe8,0xc8,0x7f,0xe8,0xc7,0x7e,0xe8,0xc7,0x7c,0xe8,0xc6,0x7b,0xe8,0xc6,0x7a,0xe7,0xc5,0x79,0xe7,0xc5,0x78,0xe7,0xc4,0x76,0xe7,0xc4,0x75,0xe7,0xc3,0x74,0xe7,0xc3,0x73,0xe7,0xc2,0x72,0xe7,0xc2,0x70,0xe7,0xc1,0x6f,0xe6,0xc1,0x6e,0xe6,0xc0,0x6d,0xe6,0xbf,0x6b,0xe6,0xbf,0x6a,0xe6,0xbe,0x69,0xe6,0xbe,0x68,0xe6,0xbd,0x66,0xe6,0xbd,0x65,0xe5,0xbc,0x64,0xe5,0xbc,0x62,0xe5,0xbb,0x61,0xe5,0xba,0x60,0xe5,0xba,0x5e,0xe5,0xb9,0x5d,0xe5,0xb9,0x5c,0xe4,0xb8,0x5b,0xe4,0xb8,0x59,0xe4}; - static constexpr std::array D03 = {0x39,0x97,0x0e,0x3b,0x97,0x12,0x3d,0x98,0x15,0x3f,0x99,0x18,0x40,0x9a,0x1a,0x42,0x9a,0x1d,0x44,0x9b,0x1f,0x46,0x9c,0x22,0x48,0x9c,0x24,0x4a,0x9d,0x26,0x4b,0x9e,0x28,0x4d,0x9f,0x2a,0x4f,0x9f,0x2c,0x51,0xa0,0x2e,0x52,0xa1,0x30,0x54,0xa1,0x32,0x56,0xa2,0x34,0x57,0xa3,0x36,0x59,0xa4,0x38,0x5a,0xa4,0x39,0x5c,0xa5,0x3b,0x5e,0xa6,0x3d,0x5f,0xa6,0x3f,0x61,0xa7,0x41,0x62,0xa8,0x42,0x64,0xa9,0x44,0x65,0xa9,0x46,0x67,0xaa,0x47,0x68,0xab,0x49,0x6a,0xab,0x4b,0x6b,0xac,0x4d,0x6d,0xad,0x4e,0x6e,0xae,0x50,0x70,0xae,0x52,0x71,0xaf,0x53,0x73,0xb0,0x55,0x74,0xb0,0x57,0x76,0xb1,0x58,0x77,0xb2,0x5a,0x79,0xb2,0x5c,0x7a,0xb3,0x5d,0x7c,0xb4,0x5f,0x7d,0xb5,0x61,0x7e,0xb5,0x62,0x80,0xb6,0x64,0x81,0xb7,0x66,0x83,0xb7,0x67,0x84,0xb8,0x69,0x85,0xb9,0x6a,0x87,0xba,0x6c,0x88,0xba,0x6e,0x8a,0xbb,0x6f,0x8b,0xbc,0x71,0x8c,0xbc,0x73,0x8e,0xbd,0x74,0x8f,0xbe,0x76,0x91,0xbe,0x78,0x92,0xbf,0x79,0x93,0xc0,0x7b,0x95,0xc1,0x7c,0x96,0xc1,0x7e,0x97,0xc2,0x80,0x99,0xc3,0x81,0x9a,0xc3,0x83,0x9b,0xc4,0x85,0x9d,0xc5,0x86,0x9e,0xc5,0x88,0xa0,0xc6,0x8a,0xa1,0xc7,0x8b,0xa2,0xc8,0x8d,0xa4,0xc8,0x8e,0xa5,0xc9,0x90,0xa6,0xca,0x92,0xa8,0xca,0x93,0xa9,0xcb,0x95,0xaa,0xcc,0x97,0xac,0xcc,0x98,0xad,0xcd,0x9a,0xae,0xce,0x9c,0xb0,0xce,0x9d,0xb1,0xcf,0x9f,0xb2,0xd0,0xa1,0xb4,0xd1,0xa2,0xb5,0xd1,0xa4,0xb6,0xd2,0xa6,0xb8,0xd3,0xa7,0xb9,0xd3,0xa9,0xba,0xd4,0xab,0xbc,0xd5,0xac,0xbd,0xd5,0xae,0xbe,0xd6,0xb0,0xc0,0xd7,0xb1,0xc1,0xd8,0xb3,0xc2,0xd8,0xb5,0xc4,0xd9,0xb6,0xc5,0xda,0xb8,0xc6,0xda,0xba,0xc7,0xdb,0xbb,0xc9,0xdc,0xbd,0xca,0xdc,0xbf,0xcb,0xdd,0xc0,0xcd,0xde,0xc2,0xce,0xde,0xc4,0xcf,0xdf,0xc5,0xd1,0xe0,0xc7,0xd2,0xe0,0xc9,0xd3,0xe1,0xca,0xd5,0xe2,0xcc,0xd6,0xe3,0xce,0xd7,0xe3,0xcf,0xd9,0xe4,0xd1,0xda,0xe5,0xd3,0xdb,0xe5,0xd4,0xdc,0xe6,0xd6,0xde,0xe7,0xd8,0xdf,0xe7,0xd9,0xe0,0xe8,0xdb,0xe2,0xe8,0xdc,0xe3,0xe9,0xde,0xe4,0xe9,0xdf,0xe5,0xea,0xe1,0xe7,0xea,0xe2,0xe8,0xeb,0xe3,0xe9,0xeb,0xe4,0xea,0xeb,0xe5,0xeb,0xeb,0xe6,0xec,0xeb,0xe6,0xed,0xeb,0xe6,0xee,0xea,0xe6,0xef,0xea,0xe6,0xf0,0xe9,0xe6,0xf0,0xe9,0xe6,0xf1,0xe8,0xe5,0xf2,0xe7,0xe5,0xf2,0xe6,0xe4,0xf3,0xe6,0xe3,0xf3,0xe5,0xe2,0xf4,0xe4,0xe1,0xf4,0xe2,0xdf,0xf4,0xe1,0xde,0xf5,0xe0,0xdd,0xf5,0xdf,0xdc,0xf5,0xde,0xda,0xf6,0xdd,0xd9,0xf6,0xdb,0xd7,0xf6,0xda,0xd6,0xf6,0xd9,0xd5,0xf7,0xd8,0xd3,0xf7,0xd7,0xd2,0xf7,0xd5,0xd0,0xf7,0xd4,0xcf,0xf8,0xd3,0xce,0xf8,0xd2,0xcc,0xf8,0xd0,0xcb,0xf8,0xcf,0xc9,0xf8,0xce,0xc8,0xf8,0xcd,0xc6,0xf9,0xcc,0xc5,0xf9,0xca,0xc4,0xf9,0xc9,0xc2,0xf9,0xc8,0xc1,0xf9,0xc7,0xbf,0xf9,0xc5,0xbe,0xf9,0xc4,0xbd,0xf9,0xc3,0xbb,0xfa,0xc2,0xba,0xfa,0xc1,0xb8,0xfa,0xbf,0xb7,0xfa,0xbe,0xb6,0xfa,0xbd,0xb4,0xfa,0xbc,0xb3,0xfa,0xba,0xb1,0xfa,0xb9,0xb0,0xfa,0xb8,0xaf,0xfa,0xb7,0xad,0xfa,0xb5,0xac,0xfa,0xb4,0xab,0xfa,0xb3,0xa9,0xfa,0xb2,0xa8,0xfa,0xb0,0xa6,0xfa,0xaf,0xa5,0xfa,0xae,0xa4,0xfa,0xad,0xa2,0xfa,0xab,0xa1,0xfa,0xaa,0xa0,0xfa,0xa9,0x9e,0xfa,0xa8,0x9d,0xfa,0xa6,0x9c,0xfa,0xa5,0x9a,0xfa,0xa4,0x99,0xfa,0xa3,0x98,0xfa,0xa1,0x96,0xfa,0xa0,0x95,0xfa,0x9f,0x93,0xfa,0x9e,0x92,0xfa,0x9c,0x91,0xfa,0x9b,0x8f,0xfa,0x9a,0x8e,0xfa,0x99,0x8d,0xf9,0x97,0x8b,0xf9,0x96,0x8a,0xf9,0x95,0x89,0xf9,0x93,0x87,0xf9,0x92,0x86,0xf9,0x91,0x85,0xf9,0x90,0x84,0xf9,0x8e,0x82,0xf9,0x8d,0x81,0xf8,0x8c,0x80,0xf8,0x8a,0x7e,0xf8,0x89,0x7d,0xf8,0x88,0x7c,0xf8,0x86,0x7a,0xf8,0x85,0x79,0xf7,0x84,0x78,0xf7,0x82,0x76,0xf7,0x81,0x75,0xf7,0x80,0x74,0xf7,0x7e,0x73,0xf7,0x7d,0x71,0xf6,0x7c,0x70,0xf6,0x7a,0x6f,0xf6,0x79,0x6d,0xf6,0x78,0x6c,0xf6,0x76,0x6b,0xf5,0x75,0x6a,0xf5,0x74,0x68,0xf5,0x72,0x67,0xf5,0x71,0x66,0xf4,0x6f,0x64,0xf4,0x6e,0x63,0xf4,0x6d,0x62,0xf4,0x6b,0x61,0xf3,0x6a,0x5f,0xf3,0x68,0x5e,0xf3,0x67,0x5d,0xf3,0x65,0x5c,0xf2,0x64,0x5a,0xf2,0x62,0x59,0xf2,0x61,0x58,0xf2,0x5f,0x57,0xf1,0x5e,0x55,0xf1,0x5c,0x54,0xf1,0x5b,0x53,0xf0,0x59,0x52,0xf0,0x58,0x50,0xf0,0x56,0x4f,0xf0,0x55,0x4e,0xef,0x53,0x4d,0xef,0x51,0x4b,0xef,0x50,0x4a,0xee,0x4e,0x49,0xee,0x4c,0x48,0xee,0x4b,0x47,0xed,0x49,0x45,0xed,0x47,0x44}; - static constexpr std::array D04 = {0x19,0x81,0xfa,0x1a,0x80,0xf8,0x1c,0x80,0xf6,0x1d,0x7f,0xf4,0x1e,0x7e,0xf3,0x1f,0x7d,0xf1,0x20,0x7c,0xef,0x21,0x7b,0xed,0x22,0x7a,0xeb,0x23,0x79,0xe9,0x24,0x79,0xe7,0x25,0x78,0xe5,0x26,0x77,0xe3,0x26,0x76,0xe1,0x27,0x75,0xdf,0x28,0x74,0xdd,0x28,0x73,0xdb,0x29,0x72,0xd9,0x2a,0x72,0xd7,0x2a,0x71,0xd5,0x2b,0x70,0xd3,0x2b,0x6f,0xd1,0x2c,0x6e,0xd0,0x2c,0x6d,0xce,0x2c,0x6c,0xcc,0x2d,0x6c,0xca,0x2d,0x6b,0xc8,0x2e,0x6a,0xc6,0x2e,0x69,0xc4,0x2e,0x68,0xc2,0x2f,0x67,0xc0,0x2f,0x66,0xbf,0x2f,0x66,0xbd,0x2f,0x65,0xbb,0x30,0x64,0xb9,0x30,0x63,0xb7,0x30,0x62,0xb5,0x30,0x61,0xb3,0x30,0x61,0xb1,0x31,0x60,0xb0,0x31,0x5f,0xae,0x31,0x5e,0xac,0x31,0x5d,0xaa,0x31,0x5c,0xa8,0x31,0x5c,0xa6,0x31,0x5b,0xa4,0x31,0x5a,0xa3,0x32,0x59,0xa1,0x32,0x58,0x9f,0x32,0x57,0x9d,0x32,0x57,0x9b,0x32,0x56,0x9a,0x32,0x55,0x98,0x32,0x54,0x96,0x32,0x53,0x94,0x32,0x52,0x92,0x32,0x52,0x91,0x32,0x51,0x8f,0x32,0x50,0x8d,0x32,0x4f,0x8b,0x32,0x4e,0x89,0x31,0x4e,0x88,0x31,0x4d,0x86,0x31,0x4c,0x84,0x31,0x4b,0x82,0x31,0x4a,0x81,0x31,0x4a,0x7f,0x31,0x49,0x7d,0x31,0x48,0x7b,0x31,0x47,0x7a,0x30,0x46,0x78,0x30,0x46,0x76,0x30,0x45,0x74,0x30,0x44,0x73,0x30,0x43,0x71,0x30,0x42,0x6f,0x2f,0x42,0x6e,0x2f,0x41,0x6c,0x2f,0x40,0x6a,0x2f,0x3f,0x68,0x2f,0x3f,0x67,0x2e,0x3e,0x65,0x2e,0x3d,0x63,0x2e,0x3c,0x62,0x2e,0x3c,0x60,0x2d,0x3b,0x5e,0x2d,0x3a,0x5d,0x2d,0x39,0x5b,0x2c,0x38,0x59,0x2c,0x38,0x58,0x2c,0x37,0x56,0x2c,0x36,0x55,0x2b,0x35,0x53,0x2b,0x35,0x51,0x2b,0x34,0x50,0x2a,0x33,0x4e,0x2a,0x32,0x4c,0x2a,0x32,0x4b,0x29,0x31,0x49,0x29,0x30,0x48,0x29,0x2f,0x46,0x28,0x2f,0x44,0x28,0x2e,0x43,0x27,0x2d,0x41,0x27,0x2d,0x40,0x27,0x2c,0x3e,0x26,0x2b,0x3d,0x26,0x2a,0x3b,0x25,0x2a,0x3a,0x25,0x29,0x38,0x25,0x28,0x36,0x24,0x28,0x35,0x24,0x27,0x33,0x23,0x26,0x32,0x23,0x25,0x30,0x23,0x25,0x2f,0x22,0x24,0x2e,0x22,0x23,0x2c,0x22,0x23,0x2b,0x21,0x22,0x29,0x21,0x22,0x28,0x21,0x21,0x27,0x21,0x21,0x26,0x21,0x20,0x25,0x21,0x20,0x24,0x21,0x20,0x23,0x22,0x1f,0x22,0x22,0x1f,0x21,0x22,0x1f,0x21,0x23,0x1f,0x20,0x24,0x1f,0x20,0x25,0x1f,0x1f,0x26,0x1f,0x1f,0x27,0x20,0x1f,0x28,0x20,0x1f,0x29,0x20,0x1f,0x2a,0x20,0x1f,0x2b,0x21,0x1f,0x2d,0x21,0x1f,0x2e,0x22,0x1f,0x30,0x22,0x20,0x31,0x22,0x20,0x32,0x23,0x20,0x34,0x23,0x20,0x35,0x24,0x21,0x37,0x24,0x21,0x38,0x25,0x21,0x3a,0x25,0x21,0x3b,0x26,0x22,0x3d,0x26,0x22,0x3e,0x27,0x22,0x3f,0x27,0x23,0x41,0x27,0x23,0x42,0x28,0x23,0x44,0x28,0x23,0x45,0x29,0x24,0x47,0x29,0x24,0x48,0x2a,0x24,0x4a,0x2a,0x25,0x4b,0x2b,0x25,0x4d,0x2b,0x25,0x4e,0x2b,0x26,0x50,0x2c,0x26,0x51,0x2c,0x26,0x53,0x2d,0x26,0x54,0x2d,0x27,0x56,0x2e,0x27,0x57,0x2e,0x27,0x59,0x2e,0x28,0x5a,0x2f,0x28,0x5c,0x2f,0x28,0x5d,0x30,0x29,0x5f,0x30,0x29,0x60,0x31,0x29,0x62,0x31,0x29,0x63,0x31,0x2a,0x65,0x32,0x2a,0x66,0x32,0x2a,0x68,0x33,0x2b,0x6a,0x33,0x2b,0x6b,0x34,0x2b,0x6d,0x34,0x2b,0x6e,0x34,0x2c,0x70,0x35,0x2c,0x71,0x35,0x2c,0x73,0x36,0x2d,0x74,0x36,0x2d,0x76,0x36,0x2d,0x78,0x37,0x2e,0x79,0x37,0x2e,0x7b,0x38,0x2e,0x7c,0x38,0x2e,0x7e,0x38,0x2f,0x7f,0x39,0x2f,0x81,0x39,0x2f,0x83,0x3a,0x30,0x84,0x3a,0x30,0x86,0x3a,0x30,0x87,0x3b,0x30,0x89,0x3b,0x31,0x8a,0x3c,0x31,0x8c,0x3c,0x31,0x8e,0x3c,0x32,0x8f,0x3d,0x32,0x91,0x3d,0x32,0x92,0x3e,0x33,0x94,0x3e,0x33,0x96,0x3e,0x33,0x97,0x3f,0x33,0x99,0x3f,0x34,0x9b,0x40,0x34,0x9c,0x40,0x34,0x9e,0x40,0x35,0x9f,0x41,0x35,0xa1,0x41,0x35,0xa3,0x41,0x36,0xa4,0x42,0x36,0xa6,0x42,0x36,0xa8,0x43,0x36,0xa9,0x43,0x37,0xab,0x43,0x37,0xad,0x44,0x37,0xae,0x44,0x38,0xb0,0x44,0x38,0xb2,0x45,0x38,0xb3,0x45,0x38,0xb5,0x46,0x39,0xb7,0x46,0x39,0xb8,0x46,0x39,0xba,0x47,0x3a,0xbc,0x47,0x3a,0xbd,0x47,0x3a,0xbf,0x48,0x3b,0xc1,0x48,0x3b,0xc2,0x48,0x3b,0xc4,0x49,0x3b,0xc6,0x49,0x3c,0xc7,0x4a,0x3c,0xc9,0x4a,0x3c,0xcb,0x4a,0x3d,0xcc,0x4b,0x3d,0xce,0x4b,0x3d,0xd0,0x4b,0x3e,0xd1,0x4c,0x3e,0xd3,0x4c,0x3e,0xd5,0x4c,0x3e,0xd7,0x4d,0x3f,0xd8,0x4d,0x3f,0xda,0x4d,0x3f,0xdc,0x4e,0x40,0xdd,0x4e,0x40,0xdf,0x4e,0x40,0xe1,0x4f,0x41,0xe3,0x4f,0x41,0xe4,0x4f,0x41,0xe6,0x50,0x41}; - static constexpr std::array D06 = {0x0e,0x94,0xfa,0x11,0x93,0xf8,0x13,0x92,0xf6,0x15,0x91,0xf4,0x17,0x90,0xf2,0x18,0x8f,0xf0,0x1a,0x8e,0xee,0x1b,0x8c,0xec,0x1c,0x8b,0xea,0x1d,0x8a,0xe9,0x1f,0x89,0xe7,0x20,0x88,0xe5,0x21,0x87,0xe3,0x22,0x86,0xe1,0x22,0x85,0xdf,0x23,0x84,0xdd,0x24,0x83,0xdb,0x25,0x82,0xd9,0x26,0x81,0xd7,0x26,0x80,0xd5,0x27,0x7f,0xd3,0x27,0x7e,0xd1,0x28,0x7d,0xcf,0x29,0x7c,0xcd,0x29,0x7b,0xcc,0x2a,0x7a,0xca,0x2a,0x79,0xc8,0x2b,0x78,0xc6,0x2b,0x77,0xc4,0x2b,0x76,0xc2,0x2c,0x75,0xc0,0x2c,0x74,0xbe,0x2c,0x73,0xbc,0x2d,0x72,0xbb,0x2d,0x71,0xb9,0x2d,0x70,0xb7,0x2e,0x6f,0xb5,0x2e,0x6e,0xb3,0x2e,0x6d,0xb1,0x2e,0x6c,0xaf,0x2f,0x6b,0xad,0x2f,0x6a,0xac,0x2f,0x69,0xaa,0x2f,0x68,0xa8,0x2f,0x67,0xa6,0x2f,0x66,0xa4,0x30,0x65,0xa2,0x30,0x64,0xa1,0x30,0x63,0x9f,0x30,0x62,0x9d,0x30,0x61,0x9b,0x30,0x60,0x99,0x30,0x5f,0x98,0x30,0x5e,0x96,0x30,0x5d,0x94,0x30,0x5c,0x92,0x30,0x5b,0x90,0x30,0x5a,0x8f,0x30,0x59,0x8d,0x30,0x58,0x8b,0x30,0x57,0x89,0x30,0x57,0x87,0x30,0x56,0x86,0x30,0x55,0x84,0x30,0x54,0x82,0x30,0x53,0x80,0x30,0x52,0x7f,0x30,0x51,0x7d,0x30,0x50,0x7b,0x30,0x4f,0x79,0x2f,0x4e,0x78,0x2f,0x4d,0x76,0x2f,0x4c,0x74,0x2f,0x4b,0x73,0x2f,0x4a,0x71,0x2f,0x49,0x6f,0x2f,0x48,0x6d,0x2e,0x48,0x6c,0x2e,0x47,0x6a,0x2e,0x46,0x68,0x2e,0x45,0x67,0x2e,0x44,0x65,0x2d,0x43,0x63,0x2d,0x42,0x62,0x2d,0x41,0x60,0x2d,0x40,0x5e,0x2c,0x3f,0x5d,0x2c,0x3e,0x5b,0x2c,0x3e,0x59,0x2c,0x3d,0x58,0x2b,0x3c,0x56,0x2b,0x3b,0x54,0x2b,0x3a,0x53,0x2a,0x39,0x51,0x2a,0x38,0x4f,0x2a,0x37,0x4e,0x2a,0x36,0x4c,0x29,0x36,0x4b,0x29,0x35,0x49,0x29,0x34,0x47,0x28,0x33,0x46,0x28,0x32,0x44,0x27,0x31,0x43,0x27,0x30,0x41,0x27,0x30,0x40,0x26,0x2f,0x3e,0x26,0x2e,0x3c,0x26,0x2d,0x3b,0x25,0x2c,0x39,0x25,0x2b,0x38,0x24,0x2a,0x36,0x24,0x2a,0x35,0x23,0x29,0x33,0x23,0x28,0x32,0x23,0x27,0x30,0x22,0x26,0x2f,0x22,0x26,0x2d,0x22,0x25,0x2c,0x21,0x24,0x2b,0x21,0x24,0x29,0x21,0x23,0x28,0x20,0x22,0x27,0x20,0x22,0x26,0x20,0x21,0x25,0x20,0x21,0x23,0x20,0x21,0x23,0x20,0x21,0x22,0x21,0x20,0x21,0x21,0x20,0x20,0x21,0x20,0x20,0x22,0x21,0x1f,0x23,0x21,0x1f,0x23,0x21,0x1e,0x24,0x22,0x1e,0x25,0x22,0x1e,0x26,0x22,0x1e,0x26,0x23,0x1e,0x27,0x24,0x1e,0x28,0x24,0x1e,0x29,0x25,0x1e,0x2a,0x26,0x1e,0x2c,0x26,0x1e,0x2d,0x27,0x1e,0x2e,0x28,0x1e,0x2f,0x29,0x1e,0x30,0x29,0x1e,0x31,0x2a,0x1e,0x32,0x2b,0x1e,0x33,0x2c,0x1e,0x34,0x2d,0x1f,0x35,0x2d,0x1f,0x36,0x2e,0x1f,0x38,0x2f,0x1f,0x39,0x30,0x1f,0x3a,0x31,0x1f,0x3b,0x31,0x1f,0x3c,0x32,0x1f,0x3d,0x33,0x1f,0x3e,0x34,0x1f,0x3f,0x35,0x20,0x41,0x35,0x20,0x42,0x36,0x20,0x43,0x37,0x20,0x44,0x38,0x20,0x45,0x39,0x20,0x46,0x3a,0x20,0x47,0x3a,0x20,0x48,0x3b,0x20,0x4a,0x3c,0x20,0x4b,0x3d,0x20,0x4c,0x3e,0x20,0x4d,0x3f,0x21,0x4e,0x3f,0x21,0x4f,0x40,0x21,0x50,0x41,0x21,0x52,0x42,0x21,0x53,0x43,0x21,0x54,0x44,0x21,0x55,0x45,0x21,0x56,0x45,0x21,0x57,0x46,0x21,0x58,0x47,0x21,0x5a,0x48,0x21,0x5b,0x49,0x21,0x5c,0x4a,0x21,0x5d,0x4b,0x21,0x5e,0x4b,0x21,0x5f,0x4c,0x21,0x61,0x4d,0x21,0x62,0x4e,0x21,0x63,0x4f,0x21,0x64,0x50,0x21,0x65,0x51,0x21,0x67,0x52,0x21,0x68,0x52,0x21,0x69,0x53,0x21,0x6a,0x54,0x21,0x6b,0x55,0x21,0x6c,0x56,0x21,0x6e,0x57,0x21,0x6f,0x58,0x21,0x70,0x59,0x21,0x71,0x5a,0x21,0x72,0x5a,0x21,0x74,0x5b,0x21,0x75,0x5c,0x21,0x76,0x5d,0x21,0x77,0x5e,0x21,0x78,0x5f,0x21,0x7a,0x60,0x21,0x7b,0x61,0x21,0x7c,0x62,0x21,0x7d,0x63,0x21,0x7f,0x63,0x21,0x80,0x64,0x21,0x81,0x65,0x21,0x82,0x66,0x21,0x83,0x67,0x21,0x85,0x68,0x20,0x86,0x69,0x20,0x87,0x6a,0x20,0x88,0x6b,0x20,0x8a,0x6c,0x20,0x8b,0x6d,0x20,0x8c,0x6e,0x20,0x8d,0x6e,0x20,0x8e,0x6f,0x20,0x90,0x70,0x20,0x91,0x71,0x1f,0x92,0x72,0x1f,0x93,0x73,0x1f,0x95,0x74,0x1f,0x96,0x75,0x1f,0x97,0x76,0x1f,0x98,0x77,0x1f,0x9a,0x78,0x1e,0x9b,0x79,0x1e,0x9c,0x7a,0x1e,0x9d,0x7b,0x1e,0x9f,0x7c,0x1e,0xa0,0x7d,0x1e,0xa1,0x7e,0x1d,0xa3,0x7e,0x1d,0xa4,0x7f,0x1d,0xa5,0x80,0x1d,0xa6,0x81,0x1d,0xa8,0x82,0x1c,0xa9,0x83,0x1c,0xaa,0x84,0x1c,0xab,0x85,0x1c,0xad,0x86,0x1b,0xae,0x87,0x1b,0xaf,0x88,0x1b,0xb1,0x89,0x1b,0xb2,0x8a,0x1a,0xb3,0x8b,0x1a}; - static constexpr std::array D07 = {0x14,0x31,0xc1,0x18,0x32,0xc1,0x1c,0x33,0xc1,0x1f,0x33,0xc0,0x22,0x34,0xc0,0x25,0x35,0xc0,0x28,0x36,0xbf,0x2a,0x36,0xbf,0x2d,0x37,0xbf,0x2f,0x38,0xbe,0x31,0x39,0xbe,0x33,0x39,0xbe,0x35,0x3a,0xbd,0x36,0x3b,0xbd,0x38,0x3b,0xbc,0x3a,0x3c,0xbc,0x3b,0x3d,0xbc,0x3d,0x3e,0xbb,0x3f,0x3e,0xbb,0x40,0x3f,0xbb,0x42,0x40,0xba,0x43,0x41,0xba,0x44,0x41,0xba,0x46,0x42,0xb9,0x47,0x43,0xb9,0x48,0x44,0xb9,0x4a,0x44,0xb8,0x4b,0x45,0xb8,0x4c,0x46,0xb7,0x4d,0x46,0xb7,0x4e,0x47,0xb7,0x4f,0x48,0xb6,0x51,0x49,0xb6,0x52,0x49,0xb6,0x53,0x4a,0xb5,0x54,0x4b,0xb5,0x55,0x4c,0xb5,0x56,0x4c,0xb4,0x57,0x4d,0xb4,0x58,0x4e,0xb4,0x59,0x4f,0xb3,0x5a,0x4f,0xb3,0x5b,0x50,0xb2,0x5c,0x51,0xb2,0x5d,0x51,0xb2,0x5e,0x52,0xb1,0x5e,0x53,0xb1,0x5f,0x54,0xb1,0x60,0x54,0xb0,0x61,0x55,0xb0,0x62,0x56,0xaf,0x63,0x57,0xaf,0x64,0x57,0xaf,0x64,0x58,0xae,0x65,0x59,0xae,0x66,0x5a,0xae,0x67,0x5a,0xad,0x68,0x5b,0xad,0x68,0x5c,0xad,0x69,0x5d,0xac,0x6a,0x5d,0xac,0x6b,0x5e,0xab,0x6b,0x5f,0xab,0x6c,0x60,0xab,0x6d,0x60,0xaa,0x6e,0x61,0xaa,0x6e,0x62,0xa9,0x6f,0x63,0xa9,0x70,0x63,0xa9,0x70,0x64,0xa8,0x71,0x65,0xa8,0x72,0x66,0xa8,0x73,0x66,0xa7,0x73,0x67,0xa7,0x74,0x68,0xa6,0x75,0x69,0xa6,0x75,0x69,0xa6,0x76,0x6a,0xa5,0x76,0x6b,0xa5,0x77,0x6c,0xa5,0x78,0x6c,0xa4,0x78,0x6d,0xa4,0x79,0x6e,0xa3,0x7a,0x6f,0xa3,0x7a,0x6f,0xa3,0x7b,0x70,0xa2,0x7b,0x71,0xa2,0x7c,0x72,0xa1,0x7d,0x72,0xa1,0x7d,0x73,0xa1,0x7e,0x74,0xa0,0x7e,0x75,0xa0,0x7f,0x75,0x9f,0x7f,0x76,0x9f,0x80,0x77,0x9f,0x81,0x78,0x9e,0x81,0x78,0x9e,0x82,0x79,0x9d,0x82,0x7a,0x9d,0x83,0x7b,0x9d,0x83,0x7b,0x9c,0x84,0x7c,0x9c,0x84,0x7d,0x9b,0x85,0x7e,0x9b,0x85,0x7f,0x9b,0x86,0x7f,0x9a,0x86,0x80,0x9a,0x87,0x81,0x99,0x87,0x82,0x99,0x88,0x82,0x98,0x88,0x83,0x98,0x89,0x84,0x98,0x89,0x85,0x97,0x8a,0x85,0x97,0x8a,0x86,0x96,0x8b,0x87,0x96,0x8b,0x88,0x96,0x8c,0x88,0x95,0x8c,0x89,0x95,0x8d,0x8a,0x94,0x8d,0x8b,0x94,0x8e,0x8c,0x93,0x8e,0x8c,0x93,0x8f,0x8d,0x93,0x8f,0x8e,0x92,0x8f,0x8f,0x92,0x90,0x8f,0x91,0x90,0x90,0x91,0x91,0x91,0x90,0x92,0x91,0x90,0x93,0x92,0x8f,0x94,0x93,0x8e,0x95,0x93,0x8e,0x96,0x94,0x8d,0x97,0x95,0x8d,0x98,0x95,0x8c,0x99,0x96,0x8b,0x9a,0x96,0x8b,0x9b,0x97,0x8a,0x9c,0x98,0x8a,0x9d,0x98,0x89,0x9e,0x99,0x88,0x9f,0x99,0x88,0xa0,0x9a,0x87,0xa1,0x9b,0x86,0xa2,0x9b,0x86,0xa3,0x9c,0x85,0xa4,0x9d,0x85,0xa5,0x9d,0x84,0xa6,0x9e,0x83,0xa7,0x9e,0x83,0xa8,0x9f,0x82,0xa9,0xa0,0x81,0xaa,0xa0,0x81,0xaa,0xa1,0x80,0xab,0xa2,0x7f,0xac,0xa2,0x7f,0xad,0xa3,0x7e,0xae,0xa3,0x7d,0xaf,0xa4,0x7d,0xb0,0xa5,0x7c,0xb1,0xa5,0x7b,0xb2,0xa6,0x7b,0xb3,0xa7,0x7a,0xb3,0xa7,0x79,0xb4,0xa8,0x79,0xb5,0xa9,0x78,0xb6,0xa9,0x77,0xb7,0xaa,0x77,0xb8,0xaa,0x76,0xb9,0xab,0x75,0xba,0xac,0x75,0xba,0xac,0x74,0xbb,0xad,0x73,0xbc,0xae,0x73,0xbd,0xae,0x72,0xbe,0xaf,0x71,0xbf,0xb0,0x70,0xc0,0xb0,0x70,0xc0,0xb1,0x6f,0xc1,0xb2,0x6e,0xc2,0xb2,0x6d,0xc3,0xb3,0x6d,0xc4,0xb4,0x6c,0xc5,0xb4,0x6b,0xc6,0xb5,0x6a,0xc6,0xb5,0x6a,0xc7,0xb6,0x69,0xc8,0xb7,0x68,0xc9,0xb7,0x67,0xca,0xb8,0x67,0xcb,0xb9,0x66,0xcb,0xb9,0x65,0xcc,0xba,0x64,0xcd,0xbb,0x63,0xce,0xbb,0x63,0xcf,0xbc,0x62,0xcf,0xbd,0x61,0xd0,0xbd,0x60,0xd1,0xbe,0x5f,0xd2,0xbf,0x5e,0xd3,0xbf,0x5e,0xd4,0xc0,0x5d,0xd4,0xc1,0x5c,0xd5,0xc1,0x5b,0xd6,0xc2,0x5a,0xd7,0xc3,0x59,0xd8,0xc3,0x58,0xd8,0xc4,0x57,0xd9,0xc5,0x56,0xda,0xc5,0x56,0xdb,0xc6,0x55,0xdc,0xc7,0x54,0xdc,0xc7,0x53,0xdd,0xc8,0x52,0xde,0xc9,0x51,0xdf,0xc9,0x50,0xdf,0xca,0x4f,0xe0,0xcb,0x4e,0xe1,0xcb,0x4d,0xe2,0xcc,0x4c,0xe3,0xcd,0x4b,0xe3,0xcd,0x49,0xe4,0xce,0x48,0xe5,0xcf,0x47,0xe6,0xcf,0x46,0xe7,0xd0,0x45,0xe7,0xd1,0x44,0xe8,0xd1,0x43,0xe9,0xd2,0x41,0xea,0xd3,0x40,0xea,0xd3,0x3f,0xeb,0xd4,0x3e,0xec,0xd5,0x3c,0xed,0xd6,0x3b,0xed,0xd6,0x39,0xee,0xd7,0x38,0xef,0xd8,0x37,0xf0,0xd8,0x35,0xf1,0xd9,0x33,0xf1,0xda,0x32,0xf2,0xda,0x30,0xf3,0xdb,0x2e,0xf4,0xdc,0x2d,0xf4,0xdc,0x2b,0xf5,0xdd,0x29,0xf6,0xde,0x27,0xf7,0xde,0x25,0xf7,0xdf,0x22,0xf8,0xe0,0x20,0xf9,0xe0,0x1d,0xfa,0xe1,0x1a,0xfa,0xe2,0x17,0xfb,0xe3,0x13,0xfc,0xe3,0x0f,0xfd,0xe4,0x09}; - static constexpr std::array D08 = {0x00,0x2a,0xd7,0x00,0x2b,0xd6,0x00,0x2b,0xd5,0x00,0x2c,0xd4,0x00,0x2c,0xd4,0x00,0x2d,0xd3,0x00,0x2d,0xd2,0x00,0x2e,0xd1,0x07,0x2e,0xd0,0x0d,0x2f,0xcf,0x13,0x2f,0xce,0x17,0x30,0xcd,0x1b,0x30,0xcc,0x1e,0x31,0xcb,0x21,0x31,0xca,0x23,0x32,0xc9,0x26,0x32,0xc9,0x28,0x33,0xc8,0x2a,0x33,0xc7,0x2c,0x34,0xc6,0x2e,0x34,0xc5,0x2f,0x35,0xc4,0x31,0x35,0xc3,0x33,0x36,0xc2,0x34,0x36,0xc1,0x36,0x37,0xc0,0x37,0x37,0xbf,0x38,0x38,0xbf,0x3a,0x38,0xbe,0x3b,0x39,0xbd,0x3c,0x39,0xbc,0x3d,0x39,0xbb,0x3e,0x3a,0xba,0x40,0x3a,0xb9,0x41,0x3b,0xb8,0x42,0x3b,0xb7,0x43,0x3c,0xb6,0x44,0x3c,0xb5,0x45,0x3d,0xb5,0x45,0x3d,0xb4,0x46,0x3e,0xb3,0x47,0x3e,0xb2,0x48,0x3f,0xb1,0x49,0x3f,0xb0,0x4a,0x40,0xaf,0x4a,0x40,0xae,0x4b,0x40,0xad,0x4c,0x41,0xac,0x4d,0x41,0xac,0x4d,0x42,0xab,0x4e,0x42,0xaa,0x4f,0x43,0xa9,0x4f,0x43,0xa8,0x50,0x44,0xa7,0x51,0x44,0xa6,0x51,0x45,0xa5,0x52,0x45,0xa4,0x52,0x46,0xa3,0x53,0x46,0xa3,0x54,0x46,0xa2,0x54,0x47,0xa1,0x55,0x47,0xa0,0x55,0x48,0x9f,0x56,0x48,0x9e,0x56,0x49,0x9d,0x57,0x49,0x9c,0x57,0x4a,0x9b,0x58,0x4a,0x9b,0x58,0x4a,0x9a,0x58,0x4b,0x99,0x59,0x4b,0x98,0x59,0x4c,0x97,0x5a,0x4c,0x96,0x5a,0x4d,0x95,0x5b,0x4d,0x94,0x5b,0x4e,0x93,0x5b,0x4e,0x92,0x5c,0x4e,0x92,0x5c,0x4f,0x91,0x5c,0x4f,0x90,0x5d,0x50,0x8f,0x5d,0x50,0x8e,0x5d,0x51,0x8d,0x5e,0x51,0x8c,0x5e,0x52,0x8b,0x5e,0x52,0x8a,0x5e,0x52,0x8a,0x5f,0x53,0x89,0x5f,0x53,0x88,0x5f,0x54,0x87,0x60,0x54,0x86,0x60,0x55,0x85,0x60,0x55,0x84,0x60,0x56,0x83,0x60,0x56,0x82,0x61,0x56,0x82,0x61,0x57,0x81,0x61,0x57,0x80,0x61,0x58,0x7f,0x62,0x58,0x7e,0x62,0x59,0x7d,0x62,0x59,0x7c,0x62,0x59,0x7b,0x62,0x5a,0x7a,0x62,0x5a,0x7a,0x63,0x5b,0x79,0x63,0x5b,0x78,0x63,0x5c,0x77,0x63,0x5c,0x76,0x63,0x5c,0x75,0x63,0x5d,0x74,0x63,0x5d,0x73,0x63,0x5e,0x72,0x63,0x5e,0x71,0x64,0x5f,0x71,0x64,0x5f,0x70,0x64,0x5f,0x6f,0x64,0x60,0x6e,0x64,0x60,0x6d,0x64,0x61,0x6c,0x64,0x61,0x6b,0x64,0x62,0x6a,0x64,0x62,0x69,0x64,0x62,0x68,0x64,0x63,0x67,0x64,0x63,0x67,0x64,0x64,0x66,0x64,0x64,0x65,0x65,0x64,0x64,0x67,0x64,0x63,0x69,0x64,0x63,0x6a,0x64,0x62,0x6c,0x64,0x61,0x6e,0x64,0x61,0x6f,0x63,0x60,0x71,0x63,0x60,0x72,0x63,0x5f,0x74,0x63,0x5e,0x75,0x63,0x5e,0x77,0x63,0x5d,0x78,0x63,0x5c,0x7a,0x62,0x5c,0x7b,0x62,0x5b,0x7d,0x62,0x5b,0x7e,0x62,0x5a,0x80,0x62,0x59,0x81,0x62,0x59,0x83,0x61,0x58,0x84,0x61,0x57,0x86,0x61,0x57,0x87,0x61,0x56,0x88,0x61,0x56,0x8a,0x60,0x55,0x8b,0x60,0x54,0x8c,0x60,0x54,0x8e,0x60,0x53,0x8f,0x60,0x52,0x90,0x5f,0x52,0x92,0x5f,0x51,0x93,0x5f,0x51,0x94,0x5f,0x50,0x96,0x5e,0x4f,0x97,0x5e,0x4f,0x98,0x5e,0x4e,0x9a,0x5e,0x4d,0x9b,0x5d,0x4d,0x9c,0x5d,0x4c,0x9e,0x5d,0x4b,0x9f,0x5d,0x4b,0xa0,0x5c,0x4a,0xa1,0x5c,0x49,0xa3,0x5c,0x49,0xa4,0x5b,0x48,0xa5,0x5b,0x48,0xa6,0x5b,0x47,0xa8,0x5b,0x46,0xa9,0x5a,0x46,0xaa,0x5a,0x45,0xab,0x5a,0x44,0xad,0x59,0x44,0xae,0x59,0x43,0xaf,0x59,0x42,0xb0,0x58,0x42,0xb1,0x58,0x41,0xb3,0x58,0x40,0xb4,0x57,0x40,0xb5,0x57,0x3f,0xb6,0x56,0x3e,0xb7,0x56,0x3e,0xb9,0x56,0x3d,0xba,0x55,0x3c,0xbb,0x55,0x3c,0xbc,0x54,0x3b,0xbd,0x54,0x3a,0xbf,0x54,0x3a,0xc0,0x53,0x39,0xc1,0x53,0x38,0xc2,0x52,0x38,0xc3,0x52,0x37,0xc5,0x51,0x36,0xc6,0x51,0x35,0xc7,0x50,0x35,0xc8,0x50,0x34,0xc9,0x4f,0x33,0xca,0x4f,0x33,0xcc,0x4e,0x32,0xcd,0x4e,0x31,0xce,0x4d,0x30,0xcf,0x4d,0x30,0xd0,0x4c,0x2f,0xd1,0x4c,0x2e,0xd2,0x4b,0x2e,0xd4,0x4a,0x2d,0xd5,0x4a,0x2c,0xd6,0x49,0x2b,0xd7,0x49,0x2b,0xd8,0x48,0x2a,0xd9,0x47,0x29,0xda,0x47,0x28,0xdc,0x46,0x27,0xdd,0x45,0x27,0xde,0x45,0x26,0xdf,0x44,0x25,0xe0,0x43,0x24,0xe1,0x42,0x23,0xe2,0x41,0x23,0xe4,0x41,0x22,0xe5,0x40,0x21,0xe6,0x3f,0x20,0xe7,0x3e,0x1f,0xe8,0x3d,0x1e,0xe9,0x3c,0x1d,0xea,0x3b,0x1c,0xeb,0x3a,0x1b,0xed,0x3a,0x1b,0xee,0x38,0x1a,0xef,0x37,0x19,0xf0,0x36,0x18,0xf1,0x35,0x16,0xf2,0x34,0x15,0xf3,0x33,0x14,0xf4,0x32,0x13,0xf6,0x30,0x12,0xf7,0x2f,0x11,0xf8,0x2e,0x0f,0xf9,0x2c,0x0e,0xfa,0x2b,0x0d,0xfb,0x29,0x0b,0xfc,0x28,0x09,0xfd,0x26,0x08,0xff,0x24,0x06,0xff,0x22,0x05,0xff,0x20,0x03,0xff,0x1e,0x01,0xff,0x1b,0x00,0xff,0x19,0x00}; - static constexpr std::array D09 = {0x24,0x80,0xff,0x29,0x81,0xff,0x2e,0x81,0xff,0x32,0x82,0xff,0x36,0x83,0xff,0x3a,0x84,0xff,0x3e,0x85,0xff,0x41,0x86,0xff,0x44,0x87,0xff,0x47,0x87,0xff,0x4a,0x88,0xfe,0x4d,0x89,0xfe,0x4f,0x8a,0xfe,0x52,0x8b,0xfe,0x54,0x8c,0xfe,0x57,0x8d,0xfe,0x59,0x8e,0xfe,0x5b,0x8e,0xfe,0x5e,0x8f,0xfe,0x60,0x90,0xfe,0x62,0x91,0xfe,0x64,0x92,0xfe,0x66,0x93,0xfe,0x68,0x94,0xfe,0x6a,0x95,0xfe,0x6c,0x96,0xfe,0x6e,0x96,0xfe,0x70,0x97,0xfe,0x72,0x98,0xfe,0x74,0x99,0xfe,0x76,0x9a,0xfe,0x77,0x9b,0xfe,0x79,0x9c,0xfe,0x7b,0x9d,0xfe,0x7d,0x9e,0xfe,0x7e,0x9f,0xfe,0x80,0x9f,0xfe,0x82,0xa0,0xfe,0x83,0xa1,0xfe,0x85,0xa2,0xfe,0x87,0xa3,0xfe,0x88,0xa4,0xfe,0x8a,0xa5,0xfe,0x8b,0xa6,0xfe,0x8d,0xa7,0xfe,0x8f,0xa8,0xfe,0x90,0xa9,0xfe,0x92,0xaa,0xfe,0x93,0xab,0xfe,0x95,0xab,0xfe,0x96,0xac,0xfe,0x98,0xad,0xfe,0x99,0xae,0xfe,0x9b,0xaf,0xfe,0x9c,0xb0,0xfe,0x9d,0xb1,0xfe,0x9f,0xb2,0xfe,0xa0,0xb3,0xfe,0xa2,0xb4,0xfe,0xa3,0xb5,0xfe,0xa5,0xb6,0xfe,0xa6,0xb7,0xfd,0xa7,0xb8,0xfd,0xa9,0xb9,0xfd,0xaa,0xba,0xfd,0xab,0xbb,0xfd,0xad,0xbb,0xfd,0xae,0xbc,0xfd,0xaf,0xbd,0xfd,0xb1,0xbe,0xfd,0xb2,0xbf,0xfd,0xb3,0xc0,0xfd,0xb5,0xc1,0xfd,0xb6,0xc2,0xfd,0xb7,0xc3,0xfd,0xb9,0xc4,0xfd,0xba,0xc5,0xfd,0xbb,0xc6,0xfd,0xbd,0xc7,0xfd,0xbe,0xc8,0xfd,0xbf,0xc9,0xfd,0xc0,0xca,0xfd,0xc2,0xcb,0xfd,0xc3,0xcc,0xfc,0xc4,0xcd,0xfc,0xc6,0xce,0xfc,0xc7,0xcf,0xfc,0xc8,0xd0,0xfc,0xc9,0xd1,0xfc,0xcb,0xd2,0xfc,0xcc,0xd3,0xfc,0xcd,0xd4,0xfc,0xce,0xd5,0xfc,0xcf,0xd6,0xfc,0xd1,0xd7,0xfc,0xd2,0xd8,0xfc,0xd3,0xd9,0xfc,0xd4,0xda,0xfc,0xd6,0xdb,0xfc,0xd7,0xdc,0xfc,0xd8,0xdd,0xfb,0xd9,0xde,0xfb,0xda,0xdf,0xfb,0xdc,0xe0,0xfb,0xdd,0xe1,0xfb,0xde,0xe2,0xfb,0xdf,0xe3,0xfb,0xe0,0xe4,0xfb,0xe2,0xe5,0xfb,0xe3,0xe6,0xfb,0xe4,0xe7,0xfb,0xe5,0xe8,0xfb,0xe6,0xe9,0xfb,0xe7,0xea,0xfb,0xe9,0xeb,0xfa,0xea,0xec,0xfa,0xeb,0xed,0xfa,0xec,0xee,0xfa,0xed,0xef,0xfa,0xee,0xf0,0xfa,0xf0,0xf1,0xfa,0xf1,0xf2,0xfa,0xf2,0xf3,0xfa,0xf3,0xf4,0xfa,0xf4,0xf5,0xf9,0xf5,0xf6,0xf9,0xf7,0xf6,0xf9,0xf8,0xf7,0xf8,0xf9,0xf6,0xf7,0xf9,0xf6,0xf5,0xfa,0xf5,0xf4,0xfa,0xf4,0xf2,0xfa,0xf2,0xf0,0xfb,0xf1,0xef,0xfb,0xf0,0xed,0xfb,0xef,0xec,0xfb,0xed,0xea,0xfc,0xec,0xe8,0xfc,0xeb,0xe7,0xfc,0xea,0xe5,0xfc,0xe8,0xe3,0xfc,0xe7,0xe2,0xfc,0xe6,0xe0,0xfc,0xe5,0xdf,0xfd,0xe3,0xdd,0xfd,0xe2,0xdb,0xfd,0xe1,0xda,0xfd,0xdf,0xd8,0xfd,0xde,0xd7,0xfd,0xdd,0xd5,0xfd,0xdc,0xd3,0xfd,0xda,0xd2,0xfd,0xd9,0xd0,0xfd,0xd8,0xcf,0xfe,0xd7,0xcd,0xfe,0xd5,0xcb,0xfe,0xd4,0xca,0xfe,0xd3,0xc8,0xfe,0xd2,0xc7,0xfe,0xd0,0xc5,0xfe,0xcf,0xc3,0xfe,0xce,0xc2,0xfe,0xcd,0xc0,0xfe,0xcb,0xbf,0xfe,0xca,0xbd,0xfe,0xc9,0xbc,0xfe,0xc7,0xba,0xfe,0xc6,0xb9,0xfe,0xc5,0xb7,0xfe,0xc4,0xb5,0xfe,0xc2,0xb4,0xfe,0xc1,0xb2,0xfd,0xc0,0xb1,0xfd,0xbf,0xaf,0xfd,0xbd,0xae,0xfd,0xbc,0xac,0xfd,0xbb,0xab,0xfd,0xba,0xa9,0xfd,0xb8,0xa7,0xfd,0xb7,0xa6,0xfd,0xb6,0xa4,0xfd,0xb4,0xa3,0xfd,0xb3,0xa1,0xfc,0xb2,0xa0,0xfc,0xb1,0x9e,0xfc,0xaf,0x9d,0xfc,0xae,0x9b,0xfc,0xad,0x9a,0xfc,0xac,0x98,0xfc,0xaa,0x97,0xfb,0xa9,0x95,0xfb,0xa8,0x94,0xfb,0xa6,0x92,0xfb,0xa5,0x91,0xfb,0xa4,0x8f,0xfb,0xa3,0x8e,0xfa,0xa1,0x8c,0xfa,0xa0,0x8b,0xfa,0x9f,0x89,0xfa,0x9e,0x88,0xf9,0x9c,0x86,0xf9,0x9b,0x85,0xf9,0x9a,0x83,0xf9,0x98,0x82,0xf9,0x97,0x80,0xf8,0x96,0x7f,0xf8,0x94,0x7d,0xf8,0x93,0x7c,0xf8,0x92,0x7a,0xf7,0x91,0x79,0xf7,0x8f,0x77,0xf7,0x8e,0x76,0xf6,0x8d,0x74,0xf6,0x8b,0x73,0xf6,0x8a,0x71,0xf6,0x89,0x70,0xf5,0x87,0x6e,0xf5,0x86,0x6d,0xf5,0x85,0x6b,0xf4,0x83,0x6a,0xf4,0x82,0x69,0xf4,0x81,0x67,0xf3,0x7f,0x66,0xf3,0x7e,0x64,0xf3,0x7d,0x63,0xf2,0x7b,0x61,0xf2,0x7a,0x60,0xf2,0x79,0x5e,0xf1,0x77,0x5d,0xf1,0x76,0x5c,0xf1,0x75,0x5a,0xf0,0x73,0x59,0xf0,0x72,0x57,0xf0,0x71,0x56,0xef,0x6f,0x54,0xef,0x6e,0x53,0xee,0x6c,0x52,0xee,0x6b,0x50,0xee,0x6a,0x4f,0xed,0x68,0x4d,0xed,0x67,0x4c,0xec,0x65,0x4a,0xec,0x64,0x49,0xec,0x62,0x48,0xeb,0x61,0x46,0xeb,0x60,0x45,0xea,0x5e,0x43,0xea,0x5d,0x42,0xe9,0x5b,0x41,0xe9,0x5a,0x3f,0xe9,0x58,0x3e,0xe8,0x57,0x3c,0xe8,0x55,0x3b,0xe7,0x53,0x3a,0xe7,0x52,0x38,0xe6,0x50,0x37}; - static constexpr std::array D10 = {0x00,0xd9,0xff,0x00,0xd9,0xff,0x0e,0xda,0xff,0x1a,0xda,0xff,0x22,0xda,0xff,0x28,0xda,0xff,0x2e,0xdb,0xff,0x33,0xdb,0xff,0x37,0xdb,0xff,0x3b,0xdc,0xff,0x3f,0xdc,0xff,0x43,0xdc,0xff,0x46,0xdd,0xff,0x49,0xdd,0xff,0x4d,0xdd,0xff,0x50,0xde,0xff,0x52,0xde,0xff,0x55,0xde,0xff,0x58,0xdf,0xff,0x5b,0xdf,0xff,0x5d,0xdf,0xff,0x60,0xdf,0xff,0x62,0xe0,0xff,0x64,0xe0,0xff,0x67,0xe0,0xff,0x69,0xe1,0xff,0x6b,0xe1,0xff,0x6d,0xe1,0xff,0x6f,0xe2,0xff,0x72,0xe2,0xff,0x74,0xe2,0xff,0x76,0xe2,0xff,0x78,0xe3,0xff,0x7a,0xe3,0xff,0x7b,0xe3,0xff,0x7d,0xe4,0xff,0x7f,0xe4,0xff,0x81,0xe4,0xff,0x83,0xe5,0xff,0x85,0xe5,0xff,0x86,0xe5,0xff,0x88,0xe6,0xff,0x8a,0xe6,0xff,0x8c,0xe6,0xff,0x8d,0xe6,0xff,0x8f,0xe7,0xff,0x91,0xe7,0xff,0x92,0xe7,0xff,0x94,0xe8,0xff,0x96,0xe8,0xff,0x97,0xe8,0xff,0x99,0xe9,0xff,0x9b,0xe9,0xff,0x9c,0xe9,0xff,0x9e,0xe9,0xff,0x9f,0xea,0xff,0xa1,0xea,0xff,0xa2,0xea,0xff,0xa4,0xeb,0xff,0xa5,0xeb,0xff,0xa7,0xeb,0xff,0xa8,0xec,0xff,0xaa,0xec,0xff,0xab,0xec,0xff,0xad,0xec,0xff,0xae,0xed,0xff,0xb0,0xed,0xff,0xb1,0xed,0xff,0xb3,0xee,0xff,0xb4,0xee,0xff,0xb5,0xee,0xff,0xb7,0xef,0xff,0xb8,0xef,0xff,0xba,0xef,0xff,0xbb,0xef,0xff,0xbc,0xf0,0xff,0xbe,0xf0,0xff,0xbf,0xf0,0xff,0xc0,0xf1,0xff,0xc2,0xf1,0xff,0xc3,0xf1,0xff,0xc5,0xf1,0xff,0xc6,0xf2,0xff,0xc7,0xf2,0xff,0xc9,0xf2,0xff,0xca,0xf3,0xff,0xcb,0xf3,0xff,0xcd,0xf3,0xff,0xce,0xf4,0xff,0xcf,0xf4,0xff,0xd0,0xf4,0xff,0xd2,0xf4,0xff,0xd3,0xf5,0xff,0xd4,0xf5,0xff,0xd6,0xf5,0xff,0xd7,0xf6,0xff,0xd8,0xf6,0xff,0xd9,0xf6,0xff,0xdb,0xf6,0xff,0xdc,0xf7,0xff,0xdd,0xf7,0xff,0xde,0xf7,0xff,0xe0,0xf8,0xff,0xe1,0xf8,0xff,0xe2,0xf8,0xff,0xe3,0xf8,0xff,0xe5,0xf9,0xff,0xe6,0xf9,0xff,0xe7,0xf9,0xff,0xe8,0xfa,0xff,0xea,0xfa,0xff,0xeb,0xfa,0xff,0xec,0xfb,0xff,0xed,0xfb,0xff,0xee,0xfb,0xff,0xf0,0xfb,0xff,0xf1,0xfc,0xff,0xf2,0xfc,0xff,0xf3,0xfc,0xff,0xf5,0xfd,0xff,0xf6,0xfd,0xff,0xf7,0xfd,0xff,0xf8,0xfd,0xff,0xf9,0xfe,0xff,0xfb,0xfe,0xff,0xfc,0xfe,0xff,0xfd,0xfe,0xff,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xff,0xff,0xfd,0xff,0xff,0xfd,0xff,0xff,0xfc,0xfe,0xff,0xfb,0xfe,0xff,0xfb,0xfe,0xff,0xfa,0xfe,0xff,0xfa,0xfe,0xff,0xf9,0xfe,0xff,0xf8,0xfe,0xff,0xf8,0xfe,0xff,0xf7,0xfe,0xff,0xf6,0xfd,0xff,0xf6,0xfd,0xff,0xf5,0xfd,0xff,0xf5,0xfd,0xff,0xf4,0xfd,0xff,0xf3,0xfd,0xff,0xf3,0xfd,0xff,0xf2,0xfd,0xff,0xf1,0xfd,0xff,0xf1,0xfc,0xff,0xf0,0xfc,0xff,0xef,0xfc,0xff,0xef,0xfc,0xff,0xee,0xfc,0xff,0xee,0xfc,0xff,0xed,0xfc,0xff,0xec,0xfc,0xff,0xec,0xfc,0xff,0xeb,0xfb,0xff,0xea,0xfb,0xff,0xea,0xfb,0xff,0xe9,0xfb,0xff,0xe9,0xfb,0xff,0xe8,0xfb,0xff,0xe7,0xfb,0xff,0xe7,0xfb,0xff,0xe6,0xfb,0xff,0xe5,0xfa,0xff,0xe5,0xfa,0xff,0xe4,0xfa,0xff,0xe4,0xfa,0xff,0xe3,0xfa,0xfe,0xe2,0xfa,0xfe,0xe2,0xfa,0xfe,0xe1,0xfa,0xfe,0xe0,0xfa,0xfe,0xe0,0xf9,0xfe,0xdf,0xf9,0xfe,0xde,0xf9,0xfe,0xde,0xf9,0xfe,0xdd,0xf9,0xfe,0xdd,0xf9,0xfe,0xdc,0xf9,0xfe,0xdb,0xf9,0xfe,0xdb,0xf8,0xfe,0xda,0xf8,0xfe,0xd9,0xf8,0xfe,0xd9,0xf8,0xfe,0xd8,0xf8,0xfe,0xd8,0xf8,0xfe,0xd7,0xf8,0xfe,0xd6,0xf8,0xfe,0xd6,0xf8,0xfe,0xd5,0xf7,0xfe,0xd4,0xf7,0xfe,0xd4,0xf7,0xfe,0xd3,0xf7,0xfe,0xd2,0xf7,0xfe,0xd2,0xf7,0xfd,0xd1,0xf7,0xfd,0xd1,0xf7,0xfd,0xd0,0xf6,0xfd,0xcf,0xf6,0xfd,0xcf,0xf6,0xfd,0xce,0xf6,0xfd,0xcd,0xf6,0xfd,0xcd,0xf6,0xfd,0xcc,0xf6,0xfd,0xcb,0xf6,0xfd,0xcb,0xf6,0xfd,0xca,0xf5,0xfd,0xc9,0xf5,0xfd,0xc9,0xf5,0xfd,0xc8,0xf5,0xfd,0xc8,0xf5,0xfd,0xc7,0xf5,0xfd,0xc6,0xf5,0xfd,0xc6,0xf5,0xfc,0xc5,0xf4,0xfc,0xc4,0xf4,0xfc,0xc4,0xf4,0xfc,0xc3,0xf4,0xfc,0xc2,0xf4,0xfc,0xc2,0xf4,0xfc,0xc1,0xf4,0xfc,0xc0,0xf4,0xfc,0xc0,0xf4,0xfc,0xbf,0xf3,0xfc,0xbf,0xf3,0xfc,0xbe,0xf3,0xfc,0xbd,0xf3,0xfc,0xbd,0xf3,0xfc,0xbc,0xf3,0xfb,0xbb,0xf3,0xfb,0xbb,0xf3,0xfb,0xba,0xf2,0xfb,0xb9,0xf2,0xfb,0xb9,0xf2,0xfb,0xb8,0xf2,0xfb,0xb7,0xf2,0xfb,0xb7,0xf2,0xfb,0xb6,0xf2,0xfb,0xb5,0xf2,0xfb,0xb5,0xf1,0xfb,0xb4,0xf1,0xfb,0xb3,0xf1,0xfb,0xb3,0xf1,0xfa,0xb2,0xf1,0xfa,0xb1,0xf1,0xfa,0xb1,0xf1,0xfa,0xb0,0xf1,0xfa,0xaf,0xf0,0xfa,0xaf,0xf0,0xfa,0xae,0xf0,0xfa,0xae,0xf0}; - static constexpr std::array D11 = {0x00,0xb6,0xff,0x00,0xb6,0xff,0x00,0xb6,0xff,0x00,0xb6,0xff,0x06,0xb6,0xff,0x11,0xb6,0xff,0x19,0xb6,0xfe,0x1f,0xb6,0xfd,0x24,0xb6,0xfd,0x28,0xb6,0xfc,0x2c,0xb5,0xfb,0x2f,0xb5,0xfb,0x33,0xb5,0xfa,0x36,0xb5,0xf9,0x39,0xb5,0xf9,0x3b,0xb5,0xf8,0x3e,0xb5,0xf7,0x40,0xb5,0xf6,0x43,0xb5,0xf6,0x45,0xb5,0xf5,0x47,0xb5,0xf4,0x49,0xb4,0xf4,0x4b,0xb4,0xf3,0x4d,0xb4,0xf2,0x4f,0xb4,0xf2,0x51,0xb4,0xf1,0x52,0xb4,0xf0,0x54,0xb4,0xf0,0x56,0xb4,0xef,0x57,0xb4,0xee,0x59,0xb4,0xed,0x5a,0xb4,0xed,0x5c,0xb3,0xec,0x5d,0xb3,0xeb,0x5f,0xb3,0xeb,0x60,0xb3,0xea,0x62,0xb3,0xe9,0x63,0xb3,0xe9,0x64,0xb3,0xe8,0x66,0xb3,0xe7,0x67,0xb3,0xe7,0x68,0xb3,0xe6,0x69,0xb3,0xe5,0x6b,0xb2,0xe5,0x6c,0xb2,0xe4,0x6d,0xb2,0xe3,0x6e,0xb2,0xe3,0x6f,0xb2,0xe2,0x70,0xb2,0xe1,0x71,0xb2,0xe0,0x73,0xb2,0xe0,0x74,0xb2,0xdf,0x75,0xb2,0xde,0x76,0xb2,0xde,0x77,0xb1,0xdd,0x78,0xb1,0xdc,0x79,0xb1,0xdc,0x7a,0xb1,0xdb,0x7b,0xb1,0xda,0x7c,0xb1,0xda,0x7d,0xb1,0xd9,0x7e,0xb1,0xd8,0x7e,0xb1,0xd8,0x7f,0xb1,0xd7,0x80,0xb1,0xd6,0x81,0xb0,0xd6,0x82,0xb0,0xd5,0x83,0xb0,0xd4,0x84,0xb0,0xd3,0x85,0xb0,0xd3,0x85,0xb0,0xd2,0x86,0xb0,0xd1,0x87,0xb0,0xd1,0x88,0xb0,0xd0,0x89,0xb0,0xcf,0x8a,0xb0,0xcf,0x8a,0xb0,0xce,0x8b,0xaf,0xcd,0x8c,0xaf,0xcd,0x8d,0xaf,0xcc,0x8d,0xaf,0xcb,0x8e,0xaf,0xcb,0x8f,0xaf,0xca,0x90,0xaf,0xc9,0x90,0xaf,0xc9,0x91,0xaf,0xc8,0x92,0xaf,0xc7,0x93,0xaf,0xc7,0x93,0xae,0xc6,0x94,0xae,0xc5,0x95,0xae,0xc4,0x95,0xae,0xc4,0x96,0xae,0xc3,0x97,0xae,0xc2,0x97,0xae,0xc2,0x98,0xae,0xc1,0x99,0xae,0xc0,0x99,0xae,0xc0,0x9a,0xae,0xbf,0x9b,0xae,0xbe,0x9b,0xad,0xbe,0x9c,0xad,0xbd,0x9d,0xad,0xbc,0x9d,0xad,0xbc,0x9e,0xad,0xbb,0x9e,0xad,0xba,0x9f,0xad,0xba,0xa0,0xad,0xb9,0xa0,0xad,0xb8,0xa1,0xad,0xb8,0xa1,0xad,0xb7,0xa2,0xac,0xb6,0xa3,0xac,0xb6,0xa3,0xac,0xb5,0xa4,0xac,0xb4,0xa4,0xac,0xb4,0xa5,0xac,0xb3,0xa5,0xac,0xb2,0xa6,0xac,0xb2,0xa7,0xac,0xb1,0xa7,0xac,0xb0,0xa8,0xac,0xb0,0xa8,0xab,0xaf,0xa9,0xab,0xae,0xaa,0xab,0xae,0xaa,0xab,0xad,0xab,0xab,0xac,0xab,0xab,0xac,0xac,0xab,0xab,0xad,0xab,0xab,0xad,0xaa,0xaa,0xae,0xaa,0xaa,0xaf,0xaa,0xa9,0xaf,0xaa,0xa9,0xb0,0xaa,0xa8,0xb1,0xaa,0xa7,0xb2,0xa9,0xa7,0xb2,0xa9,0xa6,0xb3,0xa9,0xa6,0xb4,0xa9,0xa5,0xb4,0xa9,0xa5,0xb5,0xa9,0xa4,0xb6,0xa8,0xa4,0xb6,0xa8,0xa3,0xb7,0xa8,0xa3,0xb8,0xa8,0xa2,0xb9,0xa8,0xa2,0xb9,0xa7,0xa2,0xba,0xa7,0xa1,0xbb,0xa7,0xa1,0xbb,0xa7,0xa0,0xbc,0xa7,0xa0,0xbd,0xa7,0x9f,0xbd,0xa6,0x9f,0xbe,0xa6,0x9e,0xbf,0xa6,0x9e,0xbf,0xa6,0x9d,0xc0,0xa6,0x9d,0xc1,0xa5,0x9c,0xc1,0xa5,0x9c,0xc2,0xa5,0x9b,0xc3,0xa5,0x9b,0xc3,0xa5,0x9a,0xc4,0xa4,0x9a,0xc5,0xa4,0x99,0xc5,0xa4,0x99,0xc6,0xa4,0x98,0xc6,0xa4,0x98,0xc7,0xa3,0x97,0xc8,0xa3,0x97,0xc8,0xa3,0x96,0xc9,0xa3,0x96,0xca,0xa3,0x95,0xca,0xa2,0x95,0xcb,0xa2,0x94,0xcb,0xa2,0x94,0xcc,0xa2,0x93,0xcd,0xa2,0x93,0xcd,0xa1,0x92,0xce,0xa1,0x92,0xce,0xa1,0x91,0xcf,0xa1,0x91,0xd0,0xa1,0x90,0xd0,0xa0,0x90,0xd1,0xa0,0x90,0xd1,0xa0,0x8f,0xd2,0xa0,0x8f,0xd3,0xa0,0x8e,0xd3,0x9f,0x8e,0xd4,0x9f,0x8d,0xd4,0x9f,0x8d,0xd5,0x9f,0x8c,0xd5,0x9f,0x8c,0xd6,0x9e,0x8b,0xd7,0x9e,0x8b,0xd7,0x9e,0x8a,0xd8,0x9e,0x8a,0xd8,0x9e,0x89,0xd9,0x9d,0x89,0xd9,0x9d,0x88,0xda,0x9d,0x88,0xdb,0x9d,0x87,0xdb,0x9c,0x87,0xdc,0x9c,0x86,0xdc,0x9c,0x86,0xdd,0x9c,0x85,0xdd,0x9c,0x85,0xde,0x9b,0x84,0xde,0x9b,0x84,0xdf,0x9b,0x83,0xe0,0x9b,0x83,0xe0,0x9a,0x82,0xe1,0x9a,0x82,0xe1,0x9a,0x81,0xe2,0x9a,0x81,0xe2,0x9a,0x80,0xe3,0x99,0x80,0xe3,0x99,0x7f,0xe4,0x99,0x7f,0xe4,0x99,0x7e,0xe5,0x98,0x7e,0xe5,0x98,0x7d,0xe6,0x98,0x7d,0xe6,0x98,0x7d,0xe7,0x98,0x7c,0xe7,0x97,0x7c,0xe8,0x97,0x7b,0xe9,0x97,0x7b,0xe9,0x97,0x7a,0xea,0x96,0x7a,0xea,0x96,0x79,0xeb,0x96,0x79,0xeb,0x96,0x78,0xec,0x95,0x78,0xec,0x95,0x77,0xed,0x95,0x77,0xed,0x95,0x76,0xee,0x95,0x76,0xee,0x94,0x75,0xef,0x94,0x75,0xef,0x94,0x74,0xf0,0x94,0x74,0xf0,0x93,0x73,0xf1,0x93,0x73,0xf1,0x93,0x72,0xf2,0x93,0x72,0xf2,0x92,0x71,0xf3,0x92,0x71,0xf3,0x92,0x70,0xf4,0x92,0x70,0xf4,0x91,0x6f,0xf5,0x91,0x6f,0xf5,0x91,0x6e,0xf5,0x91,0x6e,0xf6,0x90,0x6d,0xf6,0x90,0x6d}; - static constexpr std::array D12 = {0x00,0xc9,0xff,0x00,0xc8,0xff,0x00,0xc8,0xfe,0x00,0xc8,0xfe,0x00,0xc8,0xfd,0x00,0xc8,0xfd,0x00,0xc8,0xfc,0x0d,0xc8,0xfc,0x17,0xc8,0xfb,0x1d,0xc8,0xfa,0x23,0xc7,0xfa,0x28,0xc7,0xf9,0x2c,0xc7,0xf9,0x30,0xc7,0xf8,0x33,0xc7,0xf8,0x37,0xc7,0xf7,0x3a,0xc7,0xf7,0x3d,0xc7,0xf6,0x40,0xc6,0xf5,0x42,0xc6,0xf5,0x45,0xc6,0xf4,0x47,0xc6,0xf4,0x49,0xc6,0xf3,0x4c,0xc6,0xf3,0x4e,0xc6,0xf2,0x50,0xc6,0xf1,0x52,0xc5,0xf1,0x54,0xc5,0xf0,0x56,0xc5,0xf0,0x57,0xc5,0xef,0x59,0xc5,0xef,0x5b,0xc5,0xee,0x5d,0xc5,0xee,0x5e,0xc5,0xed,0x60,0xc5,0xec,0x62,0xc4,0xec,0x63,0xc4,0xeb,0x65,0xc4,0xeb,0x66,0xc4,0xea,0x68,0xc4,0xea,0x69,0xc4,0xe9,0x6b,0xc4,0xe9,0x6c,0xc4,0xe8,0x6d,0xc3,0xe7,0x6f,0xc3,0xe7,0x70,0xc3,0xe6,0x71,0xc3,0xe6,0x73,0xc3,0xe5,0x74,0xc3,0xe5,0x75,0xc3,0xe4,0x76,0xc3,0xe4,0x78,0xc2,0xe3,0x79,0xc2,0xe2,0x7a,0xc2,0xe2,0x7b,0xc2,0xe1,0x7c,0xc2,0xe1,0x7d,0xc2,0xe0,0x7e,0xc2,0xe0,0x80,0xc2,0xdf,0x81,0xc1,0xdf,0x82,0xc1,0xde,0x83,0xc1,0xdd,0x84,0xc1,0xdd,0x85,0xc1,0xdc,0x86,0xc1,0xdc,0x87,0xc1,0xdb,0x88,0xc1,0xdb,0x89,0xc0,0xda,0x8a,0xc0,0xda,0x8b,0xc0,0xd9,0x8c,0xc0,0xd8,0x8d,0xc0,0xd8,0x8e,0xc0,0xd7,0x8f,0xc0,0xd7,0x90,0xc0,0xd6,0x91,0xbf,0xd6,0x92,0xbf,0xd5,0x92,0xbf,0xd5,0x93,0xbf,0xd4,0x94,0xbf,0xd3,0x95,0xbf,0xd3,0x96,0xbf,0xd2,0x97,0xbf,0xd2,0x98,0xbe,0xd1,0x99,0xbe,0xd1,0x99,0xbe,0xd0,0x9a,0xbe,0xd0,0x9b,0xbe,0xcf,0x9c,0xbe,0xcf,0x9d,0xbe,0xce,0x9e,0xbe,0xcd,0x9e,0xbd,0xcd,0x9f,0xbd,0xcc,0xa0,0xbd,0xcc,0xa1,0xbd,0xcb,0xa2,0xbd,0xcb,0xa2,0xbd,0xca,0xa3,0xbd,0xca,0xa4,0xbd,0xc9,0xa5,0xbc,0xc8,0xa5,0xbc,0xc8,0xa6,0xbc,0xc7,0xa7,0xbc,0xc7,0xa8,0xbc,0xc6,0xa8,0xbc,0xc6,0xa9,0xbc,0xc5,0xaa,0xbb,0xc5,0xab,0xbb,0xc4,0xab,0xbb,0xc3,0xac,0xbb,0xc3,0xad,0xbb,0xc2,0xad,0xbb,0xc2,0xae,0xbb,0xc1,0xaf,0xbb,0xc1,0xaf,0xba,0xc0,0xb0,0xba,0xc0,0xb1,0xba,0xbf,0xb2,0xba,0xbf,0xb2,0xba,0xbe,0xb3,0xba,0xbe,0xb3,0xba,0xbd,0xb4,0xb9,0xbd,0xb5,0xb9,0xbd,0xb5,0xb9,0xbc,0xb6,0xb9,0xbc,0xb7,0xb9,0xbc,0xb7,0xb9,0xbb,0xb8,0xb9,0xbb,0xb8,0xb8,0xbb,0xb9,0xb8,0xbb,0xb9,0xb8,0xbb,0xba,0xb8,0xbb,0xba,0xb8,0xbb,0xbb,0xb8,0xbb,0xbb,0xb7,0xbb,0xbc,0xb7,0xbc,0xbc,0xb7,0xbc,0xbd,0xb7,0xbc,0xbd,0xb7,0xbc,0xbe,0xb7,0xbd,0xbe,0xb6,0xbd,0xbf,0xb6,0xbd,0xbf,0xb6,0xbe,0xc0,0xb6,0xbe,0xc0,0xb6,0xbe,0xc0,0xb6,0xbf,0xc1,0xb5,0xbf,0xc1,0xb5,0xbf,0xc2,0xb5,0xc0,0xc2,0xb5,0xc0,0xc3,0xb5,0xc0,0xc3,0xb4,0xc1,0xc4,0xb4,0xc1,0xc4,0xb4,0xc1,0xc4,0xb4,0xc2,0xc5,0xb4,0xc2,0xc5,0xb4,0xc2,0xc6,0xb3,0xc3,0xc6,0xb3,0xc3,0xc7,0xb3,0xc3,0xc7,0xb3,0xc4,0xc7,0xb3,0xc4,0xc8,0xb2,0xc4,0xc8,0xb2,0xc5,0xc9,0xb2,0xc5,0xc9,0xb2,0xc5,0xca,0xb2,0xc6,0xca,0xb2,0xc6,0xca,0xb1,0xc6,0xcb,0xb1,0xc7,0xcb,0xb1,0xc7,0xcc,0xb1,0xc7,0xcc,0xb1,0xc8,0xcd,0xb0,0xc8,0xcd,0xb0,0xc8,0xcd,0xb0,0xc9,0xce,0xb0,0xc9,0xce,0xb0,0xc9,0xcf,0xaf,0xca,0xcf,0xaf,0xca,0xcf,0xaf,0xca,0xd0,0xaf,0xcb,0xd0,0xaf,0xcb,0xd1,0xae,0xcb,0xd1,0xae,0xcc,0xd2,0xae,0xcc,0xd2,0xae,0xcc,0xd2,0xae,0xcd,0xd3,0xad,0xcd,0xd3,0xad,0xcd,0xd4,0xad,0xce,0xd4,0xad,0xce,0xd4,0xad,0xce,0xd5,0xac,0xcf,0xd5,0xac,0xcf,0xd6,0xac,0xcf,0xd6,0xac,0xd0,0xd6,0xac,0xd0,0xd7,0xab,0xd0,0xd7,0xab,0xd1,0xd8,0xab,0xd1,0xd8,0xab,0xd1,0xd9,0xab,0xd2,0xd9,0xaa,0xd2,0xd9,0xaa,0xd2,0xda,0xaa,0xd3,0xda,0xaa,0xd3,0xdb,0xa9,0xd4,0xdb,0xa9,0xd4,0xdb,0xa9,0xd4,0xdc,0xa9,0xd5,0xdc,0xa9,0xd5,0xdd,0xa8,0xd5,0xdd,0xa8,0xd6,0xdd,0xa8,0xd6,0xde,0xa8,0xd6,0xde,0xa8,0xd7,0xdf,0xa7,0xd7,0xdf,0xa7,0xd7,0xdf,0xa7,0xd8,0xe0,0xa7,0xd8,0xe0,0xa6,0xd8,0xe1,0xa6,0xd9,0xe1,0xa6,0xd9,0xe1,0xa6,0xd9,0xe2,0xa6,0xda,0xe2,0xa5,0xda,0xe3,0xa5,0xda,0xe3,0xa5,0xdb,0xe3,0xa5,0xdb,0xe4,0xa4,0xdb,0xe4,0xa4,0xdc,0xe4,0xa4,0xdc,0xe5,0xa4,0xdc,0xe5,0xa4,0xdd,0xe6,0xa3,0xdd,0xe6,0xa3,0xdd,0xe6,0xa3,0xde,0xe7,0xa3,0xde,0xe7,0xa2,0xde,0xe8,0xa2,0xdf,0xe8,0xa2,0xdf,0xe8,0xa2,0xdf,0xe9,0xa1,0xe0,0xe9,0xa1,0xe0,0xea,0xa1,0xe0,0xea,0xa1,0xe1,0xea,0xa0,0xe1,0xeb,0xa0,0xe1,0xeb,0xa0,0xe2,0xeb,0xa0,0xe2,0xec,0x9f,0xe2,0xec,0x9f,0xe3,0xed,0x9f,0xe3,0xed,0x9f,0xe3,0xed,0x9e,0xe4}; - static constexpr std::array D13 = {0x11,0x2d,0x68,0x12,0x2e,0x6a,0x13,0x2f,0x6c,0x14,0x31,0x6e,0x15,0x32,0x70,0x16,0x33,0x73,0x17,0x34,0x75,0x18,0x36,0x77,0x19,0x37,0x79,0x1a,0x38,0x7b,0x1b,0x39,0x7d,0x1c,0x3b,0x7f,0x1d,0x3c,0x82,0x1e,0x3d,0x84,0x1f,0x3f,0x86,0x20,0x40,0x88,0x21,0x41,0x8a,0x22,0x43,0x8c,0x23,0x44,0x8e,0x24,0x45,0x90,0x25,0x47,0x93,0x25,0x48,0x95,0x26,0x49,0x97,0x27,0x4b,0x99,0x28,0x4c,0x9b,0x29,0x4e,0x9d,0x2a,0x4f,0x9f,0x2a,0x51,0xa1,0x2b,0x52,0xa3,0x2c,0x53,0xa5,0x2d,0x55,0xa8,0x2d,0x56,0xaa,0x2e,0x58,0xac,0x2f,0x59,0xae,0x2f,0x5b,0xb0,0x30,0x5c,0xb2,0x31,0x5e,0xb4,0x31,0x5f,0xb6,0x32,0x61,0xb8,0x32,0x62,0xba,0x33,0x64,0xbc,0x33,0x65,0xbe,0x34,0x67,0xc0,0x34,0x69,0xc2,0x35,0x6a,0xc3,0x35,0x6c,0xc5,0x36,0x6d,0xc7,0x36,0x6f,0xc9,0x36,0x71,0xcb,0x36,0x72,0xcd,0x36,0x74,0xcf,0x36,0x76,0xd0,0x37,0x77,0xd2,0x37,0x79,0xd4,0x36,0x7b,0xd6,0x36,0x7d,0xd7,0x36,0x7e,0xd9,0x36,0x80,0xdb,0x35,0x82,0xdc,0x35,0x84,0xde,0x35,0x86,0xdf,0x34,0x87,0xe1,0x34,0x89,0xe2,0x33,0x8b,0xe4,0x33,0x8d,0xe5,0x32,0x8f,0xe6,0x32,0x91,0xe7,0x32,0x92,0xe9,0x32,0x94,0xea,0x32,0x96,0xeb,0x32,0x98,0xec,0x33,0x9a,0xed,0x33,0x9b,0xee,0x34,0x9d,0xef,0x36,0x9f,0xf0,0x37,0xa1,0xf1,0x39,0xa3,0xf2,0x3b,0xa4,0xf3,0x3d,0xa6,0xf4,0x40,0xa8,0xf5,0x42,0xa9,0xf5,0x45,0xab,0xf6,0x48,0xad,0xf7,0x4b,0xaf,0xf7,0x4e,0xb0,0xf8,0x51,0xb2,0xf8,0x54,0xb3,0xf9,0x57,0xb5,0xf9,0x5b,0xb7,0xfa,0x5e,0xb8,0xfa,0x62,0xba,0xfa,0x65,0xbb,0xfb,0x69,0xbd,0xfb,0x6d,0xbf,0xfb,0x71,0xc0,0xfb,0x74,0xc2,0xfb,0x78,0xc3,0xfb,0x7c,0xc5,0xfc,0x80,0xc6,0xfb,0x84,0xc8,0xfb,0x88,0xc9,0xfb,0x8c,0xca,0xfb,0x90,0xcc,0xfb,0x94,0xcd,0xfb,0x98,0xcf,0xfb,0x9c,0xd0,0xfa,0xa0,0xd2,0xfa,0xa4,0xd3,0xfa,0xa7,0xd4,0xf9,0xab,0xd6,0xf9,0xaf,0xd7,0xf9,0xb3,0xd9,0xf8,0xb7,0xda,0xf8,0xbb,0xdb,0xf7,0xbe,0xdd,0xf7,0xc2,0xde,0xf7,0xc6,0xdf,0xf6,0xc9,0xe1,0xf6,0xcd,0xe2,0xf5,0xd0,0xe3,0xf5,0xd3,0xe5,0xf4,0xd6,0xe6,0xf3,0xd9,0xe7,0xf3,0xdb,0xe8,0xf2,0xdd,0xe9,0xf1,0xde,0xea,0xf0,0xdf,0xea,0xef,0xdf,0xeb,0xee,0xdf,0xeb,0xec,0xde,0xeb,0xeb,0xdd,0xeb,0xe9,0xdb,0xeb,0xe7,0xd8,0xea,0xe6,0xd5,0xea,0xe4,0xd2,0xe9,0xe2,0xcf,0xe8,0xe0,0xcb,0xe7,0xde,0xc7,0xe6,0xdc,0xc3,0xe5,0xda,0xbf,0xe4,0xd8,0xbb,0xe3,0xd6,0xb7,0xe2,0xd4,0xb3,0xe1,0xd2,0xaf,0xe0,0xd1,0xab,0xdf,0xcf,0xa6,0xde,0xcd,0xa2,0xdd,0xcb,0x9e,0xdc,0xc9,0x9a,0xda,0xc7,0x96,0xd9,0xc5,0x91,0xd8,0xc3,0x8d,0xd7,0xc1,0x89,0xd6,0xbf,0x85,0xd5,0xbd,0x81,0xd3,0xbb,0x7d,0xd2,0xb9,0x79,0xd1,0xb6,0x75,0xd0,0xb4,0x71,0xce,0xb2,0x6d,0xcd,0xb0,0x69,0xcc,0xae,0x65,0xca,0xac,0x62,0xc9,0xa9,0x5e,0xc8,0xa7,0x5a,0xc6,0xa5,0x57,0xc5,0xa3,0x53,0xc4,0xa0,0x50,0xc2,0x9e,0x4d,0xc1,0x9c,0x49,0xbf,0x99,0x46,0xbe,0x97,0x43,0xbc,0x94,0x40,0xbb,0x92,0x3e,0xb9,0x8f,0x3b,0xb8,0x8d,0x38,0xb6,0x8a,0x36,0xb5,0x88,0x33,0xb3,0x85,0x31,0xb2,0x83,0x2f,0xb0,0x80,0x2d,0xaf,0x7d,0x2c,0xad,0x7b,0x2a,0xac,0x78,0x29,0xaa,0x75,0x28,0xa8,0x73,0x27,0xa7,0x70,0x26,0xa5,0x6d,0x25,0xa4,0x6b,0x25,0xa2,0x68,0x25,0xa0,0x65,0x24,0x9f,0x62,0x24,0x9d,0x60,0x24,0x9b,0x5d,0x24,0x9a,0x5a,0x24,0x98,0x58,0x24,0x96,0x55,0x24,0x95,0x53,0x23,0x93,0x50,0x23,0x92,0x4e,0x23,0x90,0x4c,0x23,0x8e,0x49,0x22,0x8d,0x47,0x22,0x8b,0x45,0x22,0x89,0x43,0x21,0x88,0x41,0x21,0x86,0x3f,0x20,0x85,0x3d,0x20,0x83,0x3b,0x1f,0x81,0x39,0x1f,0x80,0x37,0x1e,0x7e,0x36,0x1e,0x7d,0x34,0x1d,0x7b,0x32,0x1c,0x79,0x31,0x1c,0x78,0x2f,0x1b,0x76,0x2d,0x1a,0x75,0x2c,0x1a,0x73,0x2a,0x19,0x71,0x29,0x18,0x70,0x27,0x18,0x6e,0x26,0x17,0x6d,0x25,0x16,0x6b,0x23,0x16,0x6a,0x22,0x15,0x68,0x20,0x14,0x66,0x1f,0x13,0x65,0x1e,0x12,0x63,0x1d,0x12,0x62,0x1b,0x11,0x60,0x1a,0x10,0x5f,0x19,0x0f,0x5d,0x18,0x0e,0x5c,0x17,0x0e,0x5a,0x16,0x0d,0x59,0x15,0x0c,0x57,0x13,0x0b,0x56,0x12,0x0a,0x54,0x11,0x09,0x53,0x10,0x08,0x51,0x0f,0x08,0x50,0x0e,0x07,0x4e,0x0d,0x06,0x4d,0x0d,0x05,0x4b,0x0c,0x05,0x4a,0x0b,0x04,0x48,0x0a,0x03,0x47,0x09,0x03,0x45,0x08,0x02,0x44,0x07,0x02,0x42,0x07,0x01,0x41,0x06,0x01,0x3f,0x05,0x01,0x3e,0x04,0x00,0x3c,0x03,0x00,0x3b,0x02,0x00,0x3a,0x02}; +// diverging +static constexpr std::array D01 = { + 0x21, 0x51, 0xdb, 0x25, 0x52, 0xdb, 0x2a, 0x53, 0xdb, 0x2e, 0x54, 0xdc, 0x31, 0x55, 0xdc, 0x35, + 0x56, 0xdc, 0x38, 0x57, 0xdc, 0x3b, 0x58, 0xdc, 0x3e, 0x59, 0xdd, 0x41, 0x5b, 0xdd, 0x43, 0x5c, + 0xdd, 0x46, 0x5d, 0xdd, 0x48, 0x5e, 0xdd, 0x4b, 0x5f, 0xde, 0x4d, 0x60, 0xde, 0x50, 0x61, 0xde, + 0x52, 0x63, 0xde, 0x54, 0x64, 0xdf, 0x56, 0x65, 0xdf, 0x58, 0x66, 0xdf, 0x5a, 0x67, 0xdf, 0x5c, + 0x68, 0xdf, 0x5e, 0x69, 0xe0, 0x60, 0x6b, 0xe0, 0x62, 0x6c, 0xe0, 0x64, 0x6d, 0xe0, 0x66, 0x6e, + 0xe0, 0x68, 0x6f, 0xe1, 0x69, 0x70, 0xe1, 0x6b, 0x72, 0xe1, 0x6d, 0x73, 0xe1, 0x6f, 0x74, 0xe1, + 0x70, 0x75, 0xe2, 0x72, 0x76, 0xe2, 0x74, 0x78, 0xe2, 0x75, 0x79, 0xe2, 0x77, 0x7a, 0xe2, 0x79, + 0x7b, 0xe3, 0x7a, 0x7c, 0xe3, 0x7c, 0x7e, 0xe3, 0x7d, 0x7f, 0xe3, 0x7f, 0x80, 0xe3, 0x81, 0x81, + 0xe4, 0x82, 0x82, 0xe4, 0x84, 0x84, 0xe4, 0x85, 0x85, 0xe4, 0x87, 0x86, 0xe4, 0x88, 0x87, 0xe5, + 0x8a, 0x88, 0xe5, 0x8b, 0x8a, 0xe5, 0x8d, 0x8b, 0xe5, 0x8e, 0x8c, 0xe5, 0x8f, 0x8d, 0xe5, 0x91, + 0x8f, 0xe6, 0x92, 0x90, 0xe6, 0x94, 0x91, 0xe6, 0x95, 0x92, 0xe6, 0x97, 0x94, 0xe6, 0x98, 0x95, + 0xe7, 0x99, 0x96, 0xe7, 0x9b, 0x97, 0xe7, 0x9c, 0x99, 0xe7, 0x9e, 0x9a, 0xe7, 0x9f, 0x9b, 0xe7, + 0xa0, 0x9c, 0xe8, 0xa2, 0x9e, 0xe8, 0xa3, 0x9f, 0xe8, 0xa4, 0xa0, 0xe8, 0xa6, 0xa1, 0xe8, 0xa7, + 0xa3, 0xe8, 0xa8, 0xa4, 0xe9, 0xaa, 0xa5, 0xe9, 0xab, 0xa6, 0xe9, 0xac, 0xa8, 0xe9, 0xae, 0xa9, + 0xe9, 0xaf, 0xaa, 0xe9, 0xb0, 0xac, 0xea, 0xb2, 0xad, 0xea, 0xb3, 0xae, 0xea, 0xb4, 0xaf, 0xea, + 0xb5, 0xb1, 0xea, 0xb7, 0xb2, 0xea, 0xb8, 0xb3, 0xeb, 0xb9, 0xb4, 0xeb, 0xbb, 0xb6, 0xeb, 0xbc, + 0xb7, 0xeb, 0xbd, 0xb8, 0xeb, 0xbe, 0xba, 0xeb, 0xc0, 0xbb, 0xeb, 0xc1, 0xbc, 0xec, 0xc2, 0xbe, + 0xec, 0xc3, 0xbf, 0xec, 0xc5, 0xc0, 0xec, 0xc6, 0xc1, 0xec, 0xc7, 0xc3, 0xec, 0xc8, 0xc4, 0xec, + 0xca, 0xc5, 0xed, 0xcb, 0xc7, 0xed, 0xcc, 0xc8, 0xed, 0xcd, 0xc9, 0xed, 0xcf, 0xcb, 0xed, 0xd0, + 0xcc, 0xed, 0xd1, 0xcd, 0xed, 0xd2, 0xcf, 0xee, 0xd3, 0xd0, 0xee, 0xd5, 0xd1, 0xee, 0xd6, 0xd3, + 0xee, 0xd7, 0xd4, 0xee, 0xd8, 0xd5, 0xee, 0xda, 0xd7, 0xee, 0xdb, 0xd8, 0xee, 0xdc, 0xd9, 0xef, + 0xdd, 0xda, 0xef, 0xde, 0xdc, 0xef, 0xe0, 0xdd, 0xef, 0xe1, 0xde, 0xef, 0xe2, 0xe0, 0xef, 0xe3, + 0xe1, 0xef, 0xe4, 0xe2, 0xef, 0xe5, 0xe3, 0xef, 0xe6, 0xe4, 0xee, 0xe7, 0xe5, 0xee, 0xe8, 0xe5, + 0xee, 0xe9, 0xe6, 0xed, 0xea, 0xe7, 0xed, 0xeb, 0xe7, 0xec, 0xec, 0xe7, 0xeb, 0xed, 0xe7, 0xea, + 0xee, 0xe7, 0xe9, 0xee, 0xe7, 0xe8, 0xef, 0xe6, 0xe7, 0xef, 0xe6, 0xe6, 0xf0, 0xe5, 0xe4, 0xf0, + 0xe4, 0xe3, 0xf1, 0xe3, 0xe1, 0xf1, 0xe2, 0xdf, 0xf1, 0xe1, 0xdd, 0xf1, 0xe0, 0xdc, 0xf1, 0xde, + 0xda, 0xf2, 0xdd, 0xd8, 0xf2, 0xdb, 0xd6, 0xf2, 0xda, 0xd4, 0xf2, 0xd8, 0xd2, 0xf2, 0xd7, 0xd0, + 0xf2, 0xd5, 0xce, 0xf2, 0xd4, 0xcc, 0xf2, 0xd2, 0xcb, 0xf2, 0xd1, 0xc9, 0xf2, 0xcf, 0xc7, 0xf2, + 0xce, 0xc5, 0xf2, 0xcc, 0xc3, 0xf1, 0xcb, 0xc1, 0xf1, 0xc9, 0xbf, 0xf1, 0xc7, 0xbd, 0xf1, 0xc6, + 0xbb, 0xf1, 0xc4, 0xb9, 0xf1, 0xc3, 0xb7, 0xf1, 0xc1, 0xb5, 0xf1, 0xc0, 0xb4, 0xf0, 0xbe, 0xb2, + 0xf0, 0xbd, 0xb0, 0xf0, 0xbb, 0xae, 0xf0, 0xb9, 0xac, 0xf0, 0xb8, 0xaa, 0xf0, 0xb6, 0xa8, 0xef, + 0xb5, 0xa6, 0xef, 0xb3, 0xa5, 0xef, 0xb2, 0xa3, 0xef, 0xb0, 0xa1, 0xee, 0xaf, 0x9f, 0xee, 0xad, + 0x9d, 0xee, 0xac, 0x9b, 0xee, 0xaa, 0x99, 0xed, 0xa8, 0x98, 0xed, 0xa7, 0x96, 0xed, 0xa5, 0x94, + 0xed, 0xa4, 0x92, 0xec, 0xa2, 0x90, 0xec, 0xa1, 0x8e, 0xec, 0x9f, 0x8c, 0xeb, 0x9d, 0x8b, 0xeb, + 0x9c, 0x89, 0xeb, 0x9a, 0x87, 0xea, 0x99, 0x85, 0xea, 0x97, 0x83, 0xea, 0x96, 0x82, 0xe9, 0x94, + 0x80, 0xe9, 0x93, 0x7e, 0xe8, 0x91, 0x7c, 0xe8, 0x8f, 0x7a, 0xe8, 0x8e, 0x79, 0xe7, 0x8c, 0x77, + 0xe7, 0x8b, 0x75, 0xe6, 0x89, 0x73, 0xe6, 0x88, 0x71, 0xe6, 0x86, 0x70, 0xe5, 0x84, 0x6e, 0xe5, + 0x83, 0x6c, 0xe4, 0x81, 0x6a, 0xe4, 0x80, 0x69, 0xe3, 0x7e, 0x67, 0xe3, 0x7c, 0x65, 0xe2, 0x7b, + 0x63, 0xe2, 0x79, 0x62, 0xe1, 0x78, 0x60, 0xe1, 0x76, 0x5e, 0xe0, 0x74, 0x5c, 0xe0, 0x73, 0x5b, + 0xdf, 0x71, 0x59, 0xdf, 0x6f, 0x57, 0xde, 0x6e, 0x55, 0xde, 0x6c, 0x54, 0xdd, 0x6a, 0x52, 0xdd, + 0x69, 0x50, 0xdc, 0x67, 0x4f, 0xdb, 0x66, 0x4d, 0xdb, 0x64, 0x4b, 0xda, 0x62, 0x49, 0xda, 0x60, + 0x48, 0xd9, 0x5f, 0x46, 0xd8, 0x5d, 0x44, 0xd8, 0x5b, 0x43, 0xd7, 0x5a, 0x41, 0xd7, 0x58, 0x3f, + 0xd6, 0x56, 0x3e, 0xd5, 0x54, 0x3c, 0xd5, 0x52, 0x3a, 0xd4, 0x51, 0x38, 0xd3, 0x4f, 0x37, 0xd3, + 0x4d, 0x35, 0xd2, 0x4b, 0x33, 0xd1, 0x49, 0x32, 0xd1, 0x47, 0x30, 0xd0, 0x45, 0x2e, 0xcf, 0x44, + 0x2d, 0xcf, 0x42, 0x2b, 0xce, 0x40, 0x29, 0xcd, 0x3d, 0x28, 0xcd, 0x3b, 0x26, 0xcc, 0x39, 0x24, + 0xcb, 0x37, 0x22, 0xca, 0x35, 0x21, 0xca, 0x33, 0x1f, 0xc9, 0x30, 0x1d, 0xc8, 0x2e, 0x1b, 0xc8, + 0x2b, 0x1a, 0xc7, 0x29, 0x18, 0xc6, 0x26, 0x16, 0xc5, 0x23, 0x14, 0xc5, 0x20, 0x12, 0xc4, 0x1c, + 0x10, 0xc3, 0x19, 0x0e, 0xc2, 0x14, 0x0c, 0xc1, 0x0f, 0x0a, 0xc1, 0x09, 0x08, 0xc0, 0x02, 0x06 +}; +static constexpr std::array D01A = { + 0x17, 0x29, 0x72, 0x18, 0x2a, 0x75, 0x18, 0x2b, 0x78, 0x19, 0x2c, 0x7b, 0x19, 0x2d, 0x7e, 0x19, + 0x2f, 0x80, 0x1a, 0x30, 0x83, 0x1a, 0x31, 0x86, 0x1a, 0x32, 0x89, 0x1b, 0x33, 0x8c, 0x1b, 0x34, + 0x8f, 0x1b, 0x35, 0x92, 0x1c, 0x36, 0x95, 0x1c, 0x38, 0x98, 0x1c, 0x39, 0x9b, 0x1c, 0x3a, 0x9e, + 0x1d, 0x3b, 0xa1, 0x1d, 0x3c, 0xa4, 0x1d, 0x3d, 0xa7, 0x1e, 0x3e, 0xab, 0x1e, 0x40, 0xae, 0x1e, + 0x41, 0xb1, 0x1f, 0x42, 0xb4, 0x1f, 0x43, 0xb7, 0x20, 0x44, 0xba, 0x20, 0x46, 0xbd, 0x21, 0x47, + 0xbf, 0x22, 0x48, 0xc2, 0x23, 0x49, 0xc5, 0x24, 0x4a, 0xc8, 0x25, 0x4c, 0xca, 0x27, 0x4d, 0xcd, + 0x29, 0x4e, 0xcf, 0x2b, 0x50, 0xd2, 0x2d, 0x51, 0xd4, 0x2f, 0x52, 0xd6, 0x31, 0x54, 0xd8, 0x34, + 0x55, 0xd9, 0x37, 0x56, 0xdb, 0x39, 0x58, 0xdc, 0x3c, 0x59, 0xde, 0x3f, 0x5b, 0xdf, 0x42, 0x5c, + 0xe0, 0x44, 0x5d, 0xe1, 0x47, 0x5f, 0xe2, 0x4a, 0x60, 0xe3, 0x4d, 0x62, 0xe4, 0x4f, 0x63, 0xe5, + 0x52, 0x65, 0xe6, 0x55, 0x66, 0xe7, 0x57, 0x68, 0xe8, 0x5a, 0x69, 0xe9, 0x5c, 0x6b, 0xea, 0x5f, + 0x6c, 0xeb, 0x61, 0x6e, 0xeb, 0x63, 0x6f, 0xec, 0x66, 0x71, 0xed, 0x68, 0x73, 0xee, 0x6a, 0x74, + 0xef, 0x6d, 0x76, 0xf0, 0x6f, 0x77, 0xf0, 0x71, 0x79, 0xf1, 0x73, 0x7a, 0xf2, 0x75, 0x7c, 0xf3, + 0x77, 0x7e, 0xf4, 0x7a, 0x7f, 0xf4, 0x7c, 0x81, 0xf5, 0x7e, 0x82, 0xf6, 0x80, 0x84, 0xf7, 0x82, + 0x85, 0xf7, 0x84, 0x87, 0xf8, 0x86, 0x89, 0xf9, 0x88, 0x8a, 0xf9, 0x8a, 0x8c, 0xfa, 0x8d, 0x8e, + 0xfb, 0x8f, 0x8f, 0xfb, 0x91, 0x91, 0xfb, 0x93, 0x93, 0xfc, 0x95, 0x94, 0xfc, 0x97, 0x96, 0xfc, + 0x99, 0x98, 0xfc, 0x9b, 0x99, 0xfd, 0x9d, 0x9b, 0xfd, 0x9f, 0x9d, 0xfd, 0xa1, 0x9f, 0xfd, 0xa3, + 0xa0, 0xfc, 0xa5, 0xa2, 0xfc, 0xa7, 0xa4, 0xfc, 0xa9, 0xa6, 0xfc, 0xab, 0xa7, 0xfc, 0xad, 0xa9, + 0xfc, 0xaf, 0xab, 0xfc, 0xb1, 0xad, 0xfb, 0xb3, 0xaf, 0xfb, 0xb5, 0xb0, 0xfb, 0xb7, 0xb2, 0xfb, + 0xb9, 0xb4, 0xfa, 0xbb, 0xb6, 0xfa, 0xbd, 0xb8, 0xfa, 0xbf, 0xb9, 0xfa, 0xc0, 0xbb, 0xf9, 0xc2, + 0xbd, 0xf9, 0xc4, 0xbf, 0xf9, 0xc6, 0xc1, 0xf9, 0xc8, 0xc3, 0xf8, 0xc9, 0xc4, 0xf8, 0xcb, 0xc6, + 0xf8, 0xcd, 0xc8, 0xf7, 0xcf, 0xca, 0xf7, 0xd0, 0xcc, 0xf7, 0xd2, 0xce, 0xf7, 0xd4, 0xcf, 0xf6, + 0xd6, 0xd1, 0xf6, 0xd7, 0xd3, 0xf5, 0xd9, 0xd5, 0xf5, 0xdb, 0xd7, 0xf5, 0xdc, 0xd8, 0xf4, 0xde, + 0xda, 0xf4, 0xe0, 0xdb, 0xf3, 0xe1, 0xdd, 0xf2, 0xe3, 0xde, 0xf2, 0xe5, 0xdf, 0xf1, 0xe6, 0xe1, + 0xf0, 0xe8, 0xe1, 0xef, 0xe9, 0xe2, 0xed, 0xeb, 0xe3, 0xec, 0xec, 0xe3, 0xea, 0xed, 0xe3, 0xe9, + 0xef, 0xe3, 0xe7, 0xf0, 0xe2, 0xe5, 0xf1, 0xe1, 0xe3, 0xf2, 0xe1, 0xe1, 0xf3, 0xdf, 0xde, 0xf4, + 0xde, 0xdc, 0xf5, 0xdd, 0xd9, 0xf6, 0xdb, 0xd6, 0xf7, 0xd9, 0xd4, 0xf7, 0xd7, 0xd1, 0xf8, 0xd5, + 0xce, 0xf9, 0xd3, 0xcb, 0xf9, 0xd1, 0xc9, 0xfa, 0xcf, 0xc6, 0xfa, 0xcd, 0xc3, 0xfa, 0xca, 0xc0, + 0xfb, 0xc8, 0xbd, 0xfb, 0xc6, 0xba, 0xfb, 0xc3, 0xb7, 0xfc, 0xc1, 0xb5, 0xfc, 0xbf, 0xb2, 0xfc, + 0xbd, 0xaf, 0xfc, 0xba, 0xac, 0xfc, 0xb8, 0xa9, 0xfc, 0xb6, 0xa6, 0xfd, 0xb3, 0xa4, 0xfd, 0xb1, + 0xa1, 0xfd, 0xaf, 0x9e, 0xfd, 0xac, 0x9b, 0xfd, 0xaa, 0x98, 0xfd, 0xa7, 0x96, 0xfd, 0xa5, 0x93, + 0xfd, 0xa3, 0x90, 0xfd, 0xa0, 0x8d, 0xfd, 0x9e, 0x8b, 0xfc, 0x9c, 0x88, 0xfc, 0x99, 0x85, 0xfc, + 0x97, 0x82, 0xfc, 0x94, 0x80, 0xfc, 0x92, 0x7d, 0xfb, 0x90, 0x7a, 0xfb, 0x8d, 0x78, 0xfb, 0x8b, + 0x75, 0xfa, 0x88, 0x73, 0xfa, 0x86, 0x70, 0xf9, 0x84, 0x6d, 0xf9, 0x81, 0x6b, 0xf8, 0x7f, 0x69, + 0xf8, 0x7d, 0x66, 0xf7, 0x7a, 0x64, 0xf6, 0x78, 0x61, 0xf5, 0x76, 0x5f, 0xf5, 0x73, 0x5d, 0xf4, + 0x71, 0x5b, 0xf3, 0x6f, 0x58, 0xf2, 0x6d, 0x56, 0xf1, 0x6b, 0x54, 0xf0, 0x68, 0x52, 0xef, 0x66, + 0x50, 0xed, 0x64, 0x4e, 0xec, 0x62, 0x4c, 0xeb, 0x60, 0x4a, 0xea, 0x5e, 0x48, 0xe9, 0x5b, 0x46, + 0xe7, 0x59, 0x44, 0xe6, 0x57, 0x42, 0xe5, 0x55, 0x40, 0xe4, 0x53, 0x3f, 0xe2, 0x50, 0x3d, 0xe1, + 0x4e, 0x3b, 0xe0, 0x4c, 0x39, 0xdf, 0x49, 0x37, 0xdd, 0x47, 0x35, 0xdc, 0x45, 0x33, 0xdb, 0x42, + 0x31, 0xd9, 0x40, 0x2f, 0xd8, 0x3d, 0x2d, 0xd7, 0x3b, 0x2c, 0xd6, 0x38, 0x2a, 0xd4, 0x36, 0x28, + 0xd3, 0x33, 0x26, 0xd1, 0x30, 0x24, 0xd0, 0x2e, 0x22, 0xcf, 0x2b, 0x21, 0xcd, 0x28, 0x1f, 0xcc, + 0x25, 0x1d, 0xca, 0x22, 0x1b, 0xc8, 0x1f, 0x1a, 0xc7, 0x1c, 0x18, 0xc5, 0x19, 0x17, 0xc3, 0x16, + 0x15, 0xc1, 0x13, 0x14, 0xbf, 0x10, 0x13, 0xbd, 0x0d, 0x12, 0xbb, 0x0a, 0x11, 0xb9, 0x07, 0x10, + 0xb6, 0x05, 0x0f, 0xb4, 0x03, 0x0e, 0xb2, 0x02, 0x0d, 0xaf, 0x01, 0x0d, 0xad, 0x00, 0x0c, 0xaa, + 0x00, 0x0c, 0xa7, 0x00, 0x0c, 0xa5, 0x00, 0x0b, 0xa2, 0x00, 0x0b, 0x9f, 0x01, 0x0b, 0x9d, 0x01, + 0x0a, 0x9a, 0x02, 0x0a, 0x97, 0x02, 0x0a, 0x95, 0x02, 0x0a, 0x92, 0x03, 0x09, 0x8f, 0x03, 0x09, + 0x8d, 0x04, 0x09, 0x8a, 0x04, 0x08, 0x87, 0x04, 0x08, 0x85, 0x05, 0x08, 0x82, 0x05, 0x07, 0x80, + 0x05, 0x07, 0x7d, 0x06, 0x07, 0x7a, 0x06, 0x06, 0x78, 0x06, 0x06, 0x75, 0x06, 0x05, 0x73, 0x07, + 0x05, 0x70, 0x07, 0x04, 0x6e, 0x07, 0x04, 0x6b, 0x07, 0x03, 0x69, 0x07, 0x03, 0x66, 0x07, 0x02 +}; +static constexpr std::array D02 = { + 0x39, 0x97, 0x0e, 0x3b, 0x97, 0x12, 0x3d, 0x98, 0x15, 0x3f, 0x99, 0x18, 0x40, 0x9a, 0x1a, 0x42, + 0x9a, 0x1d, 0x44, 0x9b, 0x1f, 0x46, 0x9c, 0x22, 0x48, 0x9c, 0x24, 0x4a, 0x9d, 0x26, 0x4b, 0x9e, + 0x28, 0x4d, 0x9f, 0x2a, 0x4f, 0x9f, 0x2c, 0x51, 0xa0, 0x2e, 0x52, 0xa1, 0x30, 0x54, 0xa1, 0x32, + 0x56, 0xa2, 0x34, 0x57, 0xa3, 0x36, 0x59, 0xa4, 0x38, 0x5a, 0xa4, 0x39, 0x5c, 0xa5, 0x3b, 0x5e, + 0xa6, 0x3d, 0x5f, 0xa6, 0x3f, 0x61, 0xa7, 0x41, 0x62, 0xa8, 0x42, 0x64, 0xa9, 0x44, 0x65, 0xa9, + 0x46, 0x67, 0xaa, 0x47, 0x68, 0xab, 0x49, 0x6a, 0xab, 0x4b, 0x6b, 0xac, 0x4d, 0x6d, 0xad, 0x4e, + 0x6e, 0xae, 0x50, 0x70, 0xae, 0x52, 0x71, 0xaf, 0x53, 0x73, 0xb0, 0x55, 0x74, 0xb0, 0x57, 0x76, + 0xb1, 0x58, 0x77, 0xb2, 0x5a, 0x79, 0xb2, 0x5c, 0x7a, 0xb3, 0x5d, 0x7c, 0xb4, 0x5f, 0x7d, 0xb5, + 0x61, 0x7e, 0xb5, 0x62, 0x80, 0xb6, 0x64, 0x81, 0xb7, 0x66, 0x83, 0xb7, 0x67, 0x84, 0xb8, 0x69, + 0x85, 0xb9, 0x6a, 0x87, 0xba, 0x6c, 0x88, 0xba, 0x6e, 0x8a, 0xbb, 0x6f, 0x8b, 0xbc, 0x71, 0x8c, + 0xbc, 0x73, 0x8e, 0xbd, 0x74, 0x8f, 0xbe, 0x76, 0x91, 0xbe, 0x78, 0x92, 0xbf, 0x79, 0x93, 0xc0, + 0x7b, 0x95, 0xc1, 0x7c, 0x96, 0xc1, 0x7e, 0x97, 0xc2, 0x80, 0x99, 0xc3, 0x81, 0x9a, 0xc3, 0x83, + 0x9b, 0xc4, 0x85, 0x9d, 0xc5, 0x86, 0x9e, 0xc5, 0x88, 0xa0, 0xc6, 0x8a, 0xa1, 0xc7, 0x8b, 0xa2, + 0xc8, 0x8d, 0xa4, 0xc8, 0x8e, 0xa5, 0xc9, 0x90, 0xa6, 0xca, 0x92, 0xa8, 0xca, 0x93, 0xa9, 0xcb, + 0x95, 0xaa, 0xcc, 0x97, 0xac, 0xcc, 0x98, 0xad, 0xcd, 0x9a, 0xae, 0xce, 0x9c, 0xb0, 0xce, 0x9d, + 0xb1, 0xcf, 0x9f, 0xb2, 0xd0, 0xa1, 0xb4, 0xd1, 0xa2, 0xb5, 0xd1, 0xa4, 0xb6, 0xd2, 0xa6, 0xb8, + 0xd3, 0xa7, 0xb9, 0xd3, 0xa9, 0xba, 0xd4, 0xab, 0xbc, 0xd5, 0xac, 0xbd, 0xd5, 0xae, 0xbe, 0xd6, + 0xb0, 0xc0, 0xd7, 0xb1, 0xc1, 0xd8, 0xb3, 0xc2, 0xd8, 0xb5, 0xc4, 0xd9, 0xb6, 0xc5, 0xda, 0xb8, + 0xc6, 0xda, 0xba, 0xc7, 0xdb, 0xbb, 0xc9, 0xdc, 0xbd, 0xca, 0xdc, 0xbf, 0xcb, 0xdd, 0xc0, 0xcd, + 0xde, 0xc2, 0xce, 0xde, 0xc4, 0xcf, 0xdf, 0xc5, 0xd1, 0xe0, 0xc7, 0xd2, 0xe0, 0xc9, 0xd3, 0xe1, + 0xca, 0xd5, 0xe2, 0xcc, 0xd6, 0xe3, 0xce, 0xd7, 0xe3, 0xcf, 0xd9, 0xe4, 0xd1, 0xda, 0xe5, 0xd3, + 0xdb, 0xe5, 0xd5, 0xdc, 0xe6, 0xd6, 0xde, 0xe7, 0xd8, 0xdf, 0xe7, 0xda, 0xe0, 0xe8, 0xdb, 0xe1, + 0xe8, 0xdd, 0xe3, 0xe9, 0xde, 0xe4, 0xe9, 0xe0, 0xe5, 0xea, 0xe2, 0xe6, 0xea, 0xe3, 0xe7, 0xeb, + 0xe4, 0xe8, 0xeb, 0xe6, 0xe9, 0xeb, 0xe7, 0xea, 0xeb, 0xe8, 0xea, 0xeb, 0xe9, 0xeb, 0xeb, 0xea, + 0xec, 0xeb, 0xeb, 0xec, 0xea, 0xec, 0xec, 0xea, 0xed, 0xed, 0xe9, 0xed, 0xed, 0xe9, 0xee, 0xed, + 0xe8, 0xee, 0xed, 0xe7, 0xef, 0xed, 0xe6, 0xef, 0xed, 0xe5, 0xef, 0xed, 0xe4, 0xef, 0xec, 0xe3, + 0xef, 0xec, 0xe2, 0xf0, 0xec, 0xe1, 0xf0, 0xec, 0xe0, 0xf0, 0xeb, 0xdf, 0xf0, 0xeb, 0xde, 0xf0, + 0xeb, 0xdd, 0xef, 0xea, 0xdc, 0xef, 0xea, 0xda, 0xef, 0xea, 0xd9, 0xef, 0xe9, 0xd8, 0xef, 0xe9, + 0xd7, 0xef, 0xe9, 0xd6, 0xef, 0xe8, 0xd5, 0xef, 0xe8, 0xd4, 0xef, 0xe7, 0xd2, 0xef, 0xe7, 0xd1, + 0xef, 0xe7, 0xd0, 0xef, 0xe6, 0xcf, 0xef, 0xe6, 0xce, 0xef, 0xe6, 0xcd, 0xee, 0xe5, 0xcc, 0xee, + 0xe5, 0xca, 0xee, 0xe4, 0xc9, 0xee, 0xe4, 0xc8, 0xee, 0xe4, 0xc7, 0xee, 0xe3, 0xc6, 0xee, 0xe3, + 0xc5, 0xee, 0xe2, 0xc4, 0xee, 0xe2, 0xc2, 0xee, 0xe2, 0xc1, 0xee, 0xe1, 0xc0, 0xee, 0xe1, 0xbf, + 0xed, 0xe0, 0xbe, 0xed, 0xe0, 0xbd, 0xed, 0xe0, 0xbb, 0xed, 0xdf, 0xba, 0xed, 0xdf, 0xb9, 0xed, + 0xde, 0xb8, 0xed, 0xde, 0xb7, 0xed, 0xde, 0xb6, 0xed, 0xdd, 0xb5, 0xed, 0xdd, 0xb3, 0xed, 0xdc, + 0xb2, 0xed, 0xdc, 0xb1, 0xec, 0xdb, 0xb0, 0xec, 0xdb, 0xaf, 0xec, 0xdb, 0xae, 0xec, 0xda, 0xad, + 0xec, 0xda, 0xab, 0xec, 0xd9, 0xaa, 0xec, 0xd9, 0xa9, 0xec, 0xd8, 0xa8, 0xec, 0xd8, 0xa7, 0xec, + 0xd8, 0xa6, 0xeb, 0xd7, 0xa4, 0xeb, 0xd7, 0xa3, 0xeb, 0xd6, 0xa2, 0xeb, 0xd6, 0xa1, 0xeb, 0xd5, + 0xa0, 0xeb, 0xd5, 0x9f, 0xeb, 0xd4, 0x9e, 0xeb, 0xd4, 0x9c, 0xeb, 0xd3, 0x9b, 0xeb, 0xd3, 0x9a, + 0xea, 0xd3, 0x99, 0xea, 0xd2, 0x98, 0xea, 0xd2, 0x97, 0xea, 0xd1, 0x95, 0xea, 0xd1, 0x94, 0xea, + 0xd0, 0x93, 0xea, 0xd0, 0x92, 0xea, 0xcf, 0x91, 0xea, 0xcf, 0x90, 0xea, 0xce, 0x8e, 0xe9, 0xce, + 0x8d, 0xe9, 0xcd, 0x8c, 0xe9, 0xcd, 0x8b, 0xe9, 0xcc, 0x8a, 0xe9, 0xcc, 0x88, 0xe9, 0xcb, 0x87, + 0xe9, 0xcb, 0x86, 0xe9, 0xca, 0x85, 0xe9, 0xca, 0x84, 0xe8, 0xc9, 0x82, 0xe8, 0xc9, 0x81, 0xe8, + 0xc8, 0x80, 0xe8, 0xc8, 0x7f, 0xe8, 0xc7, 0x7e, 0xe8, 0xc7, 0x7c, 0xe8, 0xc6, 0x7b, 0xe8, 0xc6, + 0x7a, 0xe7, 0xc5, 0x79, 0xe7, 0xc5, 0x78, 0xe7, 0xc4, 0x76, 0xe7, 0xc4, 0x75, 0xe7, 0xc3, 0x74, + 0xe7, 0xc3, 0x73, 0xe7, 0xc2, 0x72, 0xe7, 0xc2, 0x70, 0xe7, 0xc1, 0x6f, 0xe6, 0xc1, 0x6e, 0xe6, + 0xc0, 0x6d, 0xe6, 0xbf, 0x6b, 0xe6, 0xbf, 0x6a, 0xe6, 0xbe, 0x69, 0xe6, 0xbe, 0x68, 0xe6, 0xbd, + 0x66, 0xe6, 0xbd, 0x65, 0xe5, 0xbc, 0x64, 0xe5, 0xbc, 0x62, 0xe5, 0xbb, 0x61, 0xe5, 0xba, 0x60, + 0xe5, 0xba, 0x5e, 0xe5, 0xb9, 0x5d, 0xe5, 0xb9, 0x5c, 0xe4, 0xb8, 0x5b, 0xe4, 0xb8, 0x59, 0xe4 +}; +static constexpr std::array D03 = { + 0x39, 0x97, 0x0e, 0x3b, 0x97, 0x12, 0x3d, 0x98, 0x15, 0x3f, 0x99, 0x18, 0x40, 0x9a, 0x1a, 0x42, + 0x9a, 0x1d, 0x44, 0x9b, 0x1f, 0x46, 0x9c, 0x22, 0x48, 0x9c, 0x24, 0x4a, 0x9d, 0x26, 0x4b, 0x9e, + 0x28, 0x4d, 0x9f, 0x2a, 0x4f, 0x9f, 0x2c, 0x51, 0xa0, 0x2e, 0x52, 0xa1, 0x30, 0x54, 0xa1, 0x32, + 0x56, 0xa2, 0x34, 0x57, 0xa3, 0x36, 0x59, 0xa4, 0x38, 0x5a, 0xa4, 0x39, 0x5c, 0xa5, 0x3b, 0x5e, + 0xa6, 0x3d, 0x5f, 0xa6, 0x3f, 0x61, 0xa7, 0x41, 0x62, 0xa8, 0x42, 0x64, 0xa9, 0x44, 0x65, 0xa9, + 0x46, 0x67, 0xaa, 0x47, 0x68, 0xab, 0x49, 0x6a, 0xab, 0x4b, 0x6b, 0xac, 0x4d, 0x6d, 0xad, 0x4e, + 0x6e, 0xae, 0x50, 0x70, 0xae, 0x52, 0x71, 0xaf, 0x53, 0x73, 0xb0, 0x55, 0x74, 0xb0, 0x57, 0x76, + 0xb1, 0x58, 0x77, 0xb2, 0x5a, 0x79, 0xb2, 0x5c, 0x7a, 0xb3, 0x5d, 0x7c, 0xb4, 0x5f, 0x7d, 0xb5, + 0x61, 0x7e, 0xb5, 0x62, 0x80, 0xb6, 0x64, 0x81, 0xb7, 0x66, 0x83, 0xb7, 0x67, 0x84, 0xb8, 0x69, + 0x85, 0xb9, 0x6a, 0x87, 0xba, 0x6c, 0x88, 0xba, 0x6e, 0x8a, 0xbb, 0x6f, 0x8b, 0xbc, 0x71, 0x8c, + 0xbc, 0x73, 0x8e, 0xbd, 0x74, 0x8f, 0xbe, 0x76, 0x91, 0xbe, 0x78, 0x92, 0xbf, 0x79, 0x93, 0xc0, + 0x7b, 0x95, 0xc1, 0x7c, 0x96, 0xc1, 0x7e, 0x97, 0xc2, 0x80, 0x99, 0xc3, 0x81, 0x9a, 0xc3, 0x83, + 0x9b, 0xc4, 0x85, 0x9d, 0xc5, 0x86, 0x9e, 0xc5, 0x88, 0xa0, 0xc6, 0x8a, 0xa1, 0xc7, 0x8b, 0xa2, + 0xc8, 0x8d, 0xa4, 0xc8, 0x8e, 0xa5, 0xc9, 0x90, 0xa6, 0xca, 0x92, 0xa8, 0xca, 0x93, 0xa9, 0xcb, + 0x95, 0xaa, 0xcc, 0x97, 0xac, 0xcc, 0x98, 0xad, 0xcd, 0x9a, 0xae, 0xce, 0x9c, 0xb0, 0xce, 0x9d, + 0xb1, 0xcf, 0x9f, 0xb2, 0xd0, 0xa1, 0xb4, 0xd1, 0xa2, 0xb5, 0xd1, 0xa4, 0xb6, 0xd2, 0xa6, 0xb8, + 0xd3, 0xa7, 0xb9, 0xd3, 0xa9, 0xba, 0xd4, 0xab, 0xbc, 0xd5, 0xac, 0xbd, 0xd5, 0xae, 0xbe, 0xd6, + 0xb0, 0xc0, 0xd7, 0xb1, 0xc1, 0xd8, 0xb3, 0xc2, 0xd8, 0xb5, 0xc4, 0xd9, 0xb6, 0xc5, 0xda, 0xb8, + 0xc6, 0xda, 0xba, 0xc7, 0xdb, 0xbb, 0xc9, 0xdc, 0xbd, 0xca, 0xdc, 0xbf, 0xcb, 0xdd, 0xc0, 0xcd, + 0xde, 0xc2, 0xce, 0xde, 0xc4, 0xcf, 0xdf, 0xc5, 0xd1, 0xe0, 0xc7, 0xd2, 0xe0, 0xc9, 0xd3, 0xe1, + 0xca, 0xd5, 0xe2, 0xcc, 0xd6, 0xe3, 0xce, 0xd7, 0xe3, 0xcf, 0xd9, 0xe4, 0xd1, 0xda, 0xe5, 0xd3, + 0xdb, 0xe5, 0xd4, 0xdc, 0xe6, 0xd6, 0xde, 0xe7, 0xd8, 0xdf, 0xe7, 0xd9, 0xe0, 0xe8, 0xdb, 0xe2, + 0xe8, 0xdc, 0xe3, 0xe9, 0xde, 0xe4, 0xe9, 0xdf, 0xe5, 0xea, 0xe1, 0xe7, 0xea, 0xe2, 0xe8, 0xeb, + 0xe3, 0xe9, 0xeb, 0xe4, 0xea, 0xeb, 0xe5, 0xeb, 0xeb, 0xe6, 0xec, 0xeb, 0xe6, 0xed, 0xeb, 0xe6, + 0xee, 0xea, 0xe6, 0xef, 0xea, 0xe6, 0xf0, 0xe9, 0xe6, 0xf0, 0xe9, 0xe6, 0xf1, 0xe8, 0xe5, 0xf2, + 0xe7, 0xe5, 0xf2, 0xe6, 0xe4, 0xf3, 0xe6, 0xe3, 0xf3, 0xe5, 0xe2, 0xf4, 0xe4, 0xe1, 0xf4, 0xe2, + 0xdf, 0xf4, 0xe1, 0xde, 0xf5, 0xe0, 0xdd, 0xf5, 0xdf, 0xdc, 0xf5, 0xde, 0xda, 0xf6, 0xdd, 0xd9, + 0xf6, 0xdb, 0xd7, 0xf6, 0xda, 0xd6, 0xf6, 0xd9, 0xd5, 0xf7, 0xd8, 0xd3, 0xf7, 0xd7, 0xd2, 0xf7, + 0xd5, 0xd0, 0xf7, 0xd4, 0xcf, 0xf8, 0xd3, 0xce, 0xf8, 0xd2, 0xcc, 0xf8, 0xd0, 0xcb, 0xf8, 0xcf, + 0xc9, 0xf8, 0xce, 0xc8, 0xf8, 0xcd, 0xc6, 0xf9, 0xcc, 0xc5, 0xf9, 0xca, 0xc4, 0xf9, 0xc9, 0xc2, + 0xf9, 0xc8, 0xc1, 0xf9, 0xc7, 0xbf, 0xf9, 0xc5, 0xbe, 0xf9, 0xc4, 0xbd, 0xf9, 0xc3, 0xbb, 0xfa, + 0xc2, 0xba, 0xfa, 0xc1, 0xb8, 0xfa, 0xbf, 0xb7, 0xfa, 0xbe, 0xb6, 0xfa, 0xbd, 0xb4, 0xfa, 0xbc, + 0xb3, 0xfa, 0xba, 0xb1, 0xfa, 0xb9, 0xb0, 0xfa, 0xb8, 0xaf, 0xfa, 0xb7, 0xad, 0xfa, 0xb5, 0xac, + 0xfa, 0xb4, 0xab, 0xfa, 0xb3, 0xa9, 0xfa, 0xb2, 0xa8, 0xfa, 0xb0, 0xa6, 0xfa, 0xaf, 0xa5, 0xfa, + 0xae, 0xa4, 0xfa, 0xad, 0xa2, 0xfa, 0xab, 0xa1, 0xfa, 0xaa, 0xa0, 0xfa, 0xa9, 0x9e, 0xfa, 0xa8, + 0x9d, 0xfa, 0xa6, 0x9c, 0xfa, 0xa5, 0x9a, 0xfa, 0xa4, 0x99, 0xfa, 0xa3, 0x98, 0xfa, 0xa1, 0x96, + 0xfa, 0xa0, 0x95, 0xfa, 0x9f, 0x93, 0xfa, 0x9e, 0x92, 0xfa, 0x9c, 0x91, 0xfa, 0x9b, 0x8f, 0xfa, + 0x9a, 0x8e, 0xfa, 0x99, 0x8d, 0xf9, 0x97, 0x8b, 0xf9, 0x96, 0x8a, 0xf9, 0x95, 0x89, 0xf9, 0x93, + 0x87, 0xf9, 0x92, 0x86, 0xf9, 0x91, 0x85, 0xf9, 0x90, 0x84, 0xf9, 0x8e, 0x82, 0xf9, 0x8d, 0x81, + 0xf8, 0x8c, 0x80, 0xf8, 0x8a, 0x7e, 0xf8, 0x89, 0x7d, 0xf8, 0x88, 0x7c, 0xf8, 0x86, 0x7a, 0xf8, + 0x85, 0x79, 0xf7, 0x84, 0x78, 0xf7, 0x82, 0x76, 0xf7, 0x81, 0x75, 0xf7, 0x80, 0x74, 0xf7, 0x7e, + 0x73, 0xf7, 0x7d, 0x71, 0xf6, 0x7c, 0x70, 0xf6, 0x7a, 0x6f, 0xf6, 0x79, 0x6d, 0xf6, 0x78, 0x6c, + 0xf6, 0x76, 0x6b, 0xf5, 0x75, 0x6a, 0xf5, 0x74, 0x68, 0xf5, 0x72, 0x67, 0xf5, 0x71, 0x66, 0xf4, + 0x6f, 0x64, 0xf4, 0x6e, 0x63, 0xf4, 0x6d, 0x62, 0xf4, 0x6b, 0x61, 0xf3, 0x6a, 0x5f, 0xf3, 0x68, + 0x5e, 0xf3, 0x67, 0x5d, 0xf3, 0x65, 0x5c, 0xf2, 0x64, 0x5a, 0xf2, 0x62, 0x59, 0xf2, 0x61, 0x58, + 0xf2, 0x5f, 0x57, 0xf1, 0x5e, 0x55, 0xf1, 0x5c, 0x54, 0xf1, 0x5b, 0x53, 0xf0, 0x59, 0x52, 0xf0, + 0x58, 0x50, 0xf0, 0x56, 0x4f, 0xf0, 0x55, 0x4e, 0xef, 0x53, 0x4d, 0xef, 0x51, 0x4b, 0xef, 0x50, + 0x4a, 0xee, 0x4e, 0x49, 0xee, 0x4c, 0x48, 0xee, 0x4b, 0x47, 0xed, 0x49, 0x45, 0xed, 0x47, 0x44 +}; +static constexpr std::array D04 = { + 0x19, 0x81, 0xfa, 0x1a, 0x80, 0xf8, 0x1c, 0x80, 0xf6, 0x1d, 0x7f, 0xf4, 0x1e, 0x7e, 0xf3, 0x1f, + 0x7d, 0xf1, 0x20, 0x7c, 0xef, 0x21, 0x7b, 0xed, 0x22, 0x7a, 0xeb, 0x23, 0x79, 0xe9, 0x24, 0x79, + 0xe7, 0x25, 0x78, 0xe5, 0x26, 0x77, 0xe3, 0x26, 0x76, 0xe1, 0x27, 0x75, 0xdf, 0x28, 0x74, 0xdd, + 0x28, 0x73, 0xdb, 0x29, 0x72, 0xd9, 0x2a, 0x72, 0xd7, 0x2a, 0x71, 0xd5, 0x2b, 0x70, 0xd3, 0x2b, + 0x6f, 0xd1, 0x2c, 0x6e, 0xd0, 0x2c, 0x6d, 0xce, 0x2c, 0x6c, 0xcc, 0x2d, 0x6c, 0xca, 0x2d, 0x6b, + 0xc8, 0x2e, 0x6a, 0xc6, 0x2e, 0x69, 0xc4, 0x2e, 0x68, 0xc2, 0x2f, 0x67, 0xc0, 0x2f, 0x66, 0xbf, + 0x2f, 0x66, 0xbd, 0x2f, 0x65, 0xbb, 0x30, 0x64, 0xb9, 0x30, 0x63, 0xb7, 0x30, 0x62, 0xb5, 0x30, + 0x61, 0xb3, 0x30, 0x61, 0xb1, 0x31, 0x60, 0xb0, 0x31, 0x5f, 0xae, 0x31, 0x5e, 0xac, 0x31, 0x5d, + 0xaa, 0x31, 0x5c, 0xa8, 0x31, 0x5c, 0xa6, 0x31, 0x5b, 0xa4, 0x31, 0x5a, 0xa3, 0x32, 0x59, 0xa1, + 0x32, 0x58, 0x9f, 0x32, 0x57, 0x9d, 0x32, 0x57, 0x9b, 0x32, 0x56, 0x9a, 0x32, 0x55, 0x98, 0x32, + 0x54, 0x96, 0x32, 0x53, 0x94, 0x32, 0x52, 0x92, 0x32, 0x52, 0x91, 0x32, 0x51, 0x8f, 0x32, 0x50, + 0x8d, 0x32, 0x4f, 0x8b, 0x32, 0x4e, 0x89, 0x31, 0x4e, 0x88, 0x31, 0x4d, 0x86, 0x31, 0x4c, 0x84, + 0x31, 0x4b, 0x82, 0x31, 0x4a, 0x81, 0x31, 0x4a, 0x7f, 0x31, 0x49, 0x7d, 0x31, 0x48, 0x7b, 0x31, + 0x47, 0x7a, 0x30, 0x46, 0x78, 0x30, 0x46, 0x76, 0x30, 0x45, 0x74, 0x30, 0x44, 0x73, 0x30, 0x43, + 0x71, 0x30, 0x42, 0x6f, 0x2f, 0x42, 0x6e, 0x2f, 0x41, 0x6c, 0x2f, 0x40, 0x6a, 0x2f, 0x3f, 0x68, + 0x2f, 0x3f, 0x67, 0x2e, 0x3e, 0x65, 0x2e, 0x3d, 0x63, 0x2e, 0x3c, 0x62, 0x2e, 0x3c, 0x60, 0x2d, + 0x3b, 0x5e, 0x2d, 0x3a, 0x5d, 0x2d, 0x39, 0x5b, 0x2c, 0x38, 0x59, 0x2c, 0x38, 0x58, 0x2c, 0x37, + 0x56, 0x2c, 0x36, 0x55, 0x2b, 0x35, 0x53, 0x2b, 0x35, 0x51, 0x2b, 0x34, 0x50, 0x2a, 0x33, 0x4e, + 0x2a, 0x32, 0x4c, 0x2a, 0x32, 0x4b, 0x29, 0x31, 0x49, 0x29, 0x30, 0x48, 0x29, 0x2f, 0x46, 0x28, + 0x2f, 0x44, 0x28, 0x2e, 0x43, 0x27, 0x2d, 0x41, 0x27, 0x2d, 0x40, 0x27, 0x2c, 0x3e, 0x26, 0x2b, + 0x3d, 0x26, 0x2a, 0x3b, 0x25, 0x2a, 0x3a, 0x25, 0x29, 0x38, 0x25, 0x28, 0x36, 0x24, 0x28, 0x35, + 0x24, 0x27, 0x33, 0x23, 0x26, 0x32, 0x23, 0x25, 0x30, 0x23, 0x25, 0x2f, 0x22, 0x24, 0x2e, 0x22, + 0x23, 0x2c, 0x22, 0x23, 0x2b, 0x21, 0x22, 0x29, 0x21, 0x22, 0x28, 0x21, 0x21, 0x27, 0x21, 0x21, + 0x26, 0x21, 0x20, 0x25, 0x21, 0x20, 0x24, 0x21, 0x20, 0x23, 0x22, 0x1f, 0x22, 0x22, 0x1f, 0x21, + 0x22, 0x1f, 0x21, 0x23, 0x1f, 0x20, 0x24, 0x1f, 0x20, 0x25, 0x1f, 0x1f, 0x26, 0x1f, 0x1f, 0x27, + 0x20, 0x1f, 0x28, 0x20, 0x1f, 0x29, 0x20, 0x1f, 0x2a, 0x20, 0x1f, 0x2b, 0x21, 0x1f, 0x2d, 0x21, + 0x1f, 0x2e, 0x22, 0x1f, 0x30, 0x22, 0x20, 0x31, 0x22, 0x20, 0x32, 0x23, 0x20, 0x34, 0x23, 0x20, + 0x35, 0x24, 0x21, 0x37, 0x24, 0x21, 0x38, 0x25, 0x21, 0x3a, 0x25, 0x21, 0x3b, 0x26, 0x22, 0x3d, + 0x26, 0x22, 0x3e, 0x27, 0x22, 0x3f, 0x27, 0x23, 0x41, 0x27, 0x23, 0x42, 0x28, 0x23, 0x44, 0x28, + 0x23, 0x45, 0x29, 0x24, 0x47, 0x29, 0x24, 0x48, 0x2a, 0x24, 0x4a, 0x2a, 0x25, 0x4b, 0x2b, 0x25, + 0x4d, 0x2b, 0x25, 0x4e, 0x2b, 0x26, 0x50, 0x2c, 0x26, 0x51, 0x2c, 0x26, 0x53, 0x2d, 0x26, 0x54, + 0x2d, 0x27, 0x56, 0x2e, 0x27, 0x57, 0x2e, 0x27, 0x59, 0x2e, 0x28, 0x5a, 0x2f, 0x28, 0x5c, 0x2f, + 0x28, 0x5d, 0x30, 0x29, 0x5f, 0x30, 0x29, 0x60, 0x31, 0x29, 0x62, 0x31, 0x29, 0x63, 0x31, 0x2a, + 0x65, 0x32, 0x2a, 0x66, 0x32, 0x2a, 0x68, 0x33, 0x2b, 0x6a, 0x33, 0x2b, 0x6b, 0x34, 0x2b, 0x6d, + 0x34, 0x2b, 0x6e, 0x34, 0x2c, 0x70, 0x35, 0x2c, 0x71, 0x35, 0x2c, 0x73, 0x36, 0x2d, 0x74, 0x36, + 0x2d, 0x76, 0x36, 0x2d, 0x78, 0x37, 0x2e, 0x79, 0x37, 0x2e, 0x7b, 0x38, 0x2e, 0x7c, 0x38, 0x2e, + 0x7e, 0x38, 0x2f, 0x7f, 0x39, 0x2f, 0x81, 0x39, 0x2f, 0x83, 0x3a, 0x30, 0x84, 0x3a, 0x30, 0x86, + 0x3a, 0x30, 0x87, 0x3b, 0x30, 0x89, 0x3b, 0x31, 0x8a, 0x3c, 0x31, 0x8c, 0x3c, 0x31, 0x8e, 0x3c, + 0x32, 0x8f, 0x3d, 0x32, 0x91, 0x3d, 0x32, 0x92, 0x3e, 0x33, 0x94, 0x3e, 0x33, 0x96, 0x3e, 0x33, + 0x97, 0x3f, 0x33, 0x99, 0x3f, 0x34, 0x9b, 0x40, 0x34, 0x9c, 0x40, 0x34, 0x9e, 0x40, 0x35, 0x9f, + 0x41, 0x35, 0xa1, 0x41, 0x35, 0xa3, 0x41, 0x36, 0xa4, 0x42, 0x36, 0xa6, 0x42, 0x36, 0xa8, 0x43, + 0x36, 0xa9, 0x43, 0x37, 0xab, 0x43, 0x37, 0xad, 0x44, 0x37, 0xae, 0x44, 0x38, 0xb0, 0x44, 0x38, + 0xb2, 0x45, 0x38, 0xb3, 0x45, 0x38, 0xb5, 0x46, 0x39, 0xb7, 0x46, 0x39, 0xb8, 0x46, 0x39, 0xba, + 0x47, 0x3a, 0xbc, 0x47, 0x3a, 0xbd, 0x47, 0x3a, 0xbf, 0x48, 0x3b, 0xc1, 0x48, 0x3b, 0xc2, 0x48, + 0x3b, 0xc4, 0x49, 0x3b, 0xc6, 0x49, 0x3c, 0xc7, 0x4a, 0x3c, 0xc9, 0x4a, 0x3c, 0xcb, 0x4a, 0x3d, + 0xcc, 0x4b, 0x3d, 0xce, 0x4b, 0x3d, 0xd0, 0x4b, 0x3e, 0xd1, 0x4c, 0x3e, 0xd3, 0x4c, 0x3e, 0xd5, + 0x4c, 0x3e, 0xd7, 0x4d, 0x3f, 0xd8, 0x4d, 0x3f, 0xda, 0x4d, 0x3f, 0xdc, 0x4e, 0x40, 0xdd, 0x4e, + 0x40, 0xdf, 0x4e, 0x40, 0xe1, 0x4f, 0x41, 0xe3, 0x4f, 0x41, 0xe4, 0x4f, 0x41, 0xe6, 0x50, 0x41 +}; +static constexpr std::array D06 = { + 0x0e, 0x94, 0xfa, 0x11, 0x93, 0xf8, 0x13, 0x92, 0xf6, 0x15, 0x91, 0xf4, 0x17, 0x90, 0xf2, 0x18, + 0x8f, 0xf0, 0x1a, 0x8e, 0xee, 0x1b, 0x8c, 0xec, 0x1c, 0x8b, 0xea, 0x1d, 0x8a, 0xe9, 0x1f, 0x89, + 0xe7, 0x20, 0x88, 0xe5, 0x21, 0x87, 0xe3, 0x22, 0x86, 0xe1, 0x22, 0x85, 0xdf, 0x23, 0x84, 0xdd, + 0x24, 0x83, 0xdb, 0x25, 0x82, 0xd9, 0x26, 0x81, 0xd7, 0x26, 0x80, 0xd5, 0x27, 0x7f, 0xd3, 0x27, + 0x7e, 0xd1, 0x28, 0x7d, 0xcf, 0x29, 0x7c, 0xcd, 0x29, 0x7b, 0xcc, 0x2a, 0x7a, 0xca, 0x2a, 0x79, + 0xc8, 0x2b, 0x78, 0xc6, 0x2b, 0x77, 0xc4, 0x2b, 0x76, 0xc2, 0x2c, 0x75, 0xc0, 0x2c, 0x74, 0xbe, + 0x2c, 0x73, 0xbc, 0x2d, 0x72, 0xbb, 0x2d, 0x71, 0xb9, 0x2d, 0x70, 0xb7, 0x2e, 0x6f, 0xb5, 0x2e, + 0x6e, 0xb3, 0x2e, 0x6d, 0xb1, 0x2e, 0x6c, 0xaf, 0x2f, 0x6b, 0xad, 0x2f, 0x6a, 0xac, 0x2f, 0x69, + 0xaa, 0x2f, 0x68, 0xa8, 0x2f, 0x67, 0xa6, 0x2f, 0x66, 0xa4, 0x30, 0x65, 0xa2, 0x30, 0x64, 0xa1, + 0x30, 0x63, 0x9f, 0x30, 0x62, 0x9d, 0x30, 0x61, 0x9b, 0x30, 0x60, 0x99, 0x30, 0x5f, 0x98, 0x30, + 0x5e, 0x96, 0x30, 0x5d, 0x94, 0x30, 0x5c, 0x92, 0x30, 0x5b, 0x90, 0x30, 0x5a, 0x8f, 0x30, 0x59, + 0x8d, 0x30, 0x58, 0x8b, 0x30, 0x57, 0x89, 0x30, 0x57, 0x87, 0x30, 0x56, 0x86, 0x30, 0x55, 0x84, + 0x30, 0x54, 0x82, 0x30, 0x53, 0x80, 0x30, 0x52, 0x7f, 0x30, 0x51, 0x7d, 0x30, 0x50, 0x7b, 0x30, + 0x4f, 0x79, 0x2f, 0x4e, 0x78, 0x2f, 0x4d, 0x76, 0x2f, 0x4c, 0x74, 0x2f, 0x4b, 0x73, 0x2f, 0x4a, + 0x71, 0x2f, 0x49, 0x6f, 0x2f, 0x48, 0x6d, 0x2e, 0x48, 0x6c, 0x2e, 0x47, 0x6a, 0x2e, 0x46, 0x68, + 0x2e, 0x45, 0x67, 0x2e, 0x44, 0x65, 0x2d, 0x43, 0x63, 0x2d, 0x42, 0x62, 0x2d, 0x41, 0x60, 0x2d, + 0x40, 0x5e, 0x2c, 0x3f, 0x5d, 0x2c, 0x3e, 0x5b, 0x2c, 0x3e, 0x59, 0x2c, 0x3d, 0x58, 0x2b, 0x3c, + 0x56, 0x2b, 0x3b, 0x54, 0x2b, 0x3a, 0x53, 0x2a, 0x39, 0x51, 0x2a, 0x38, 0x4f, 0x2a, 0x37, 0x4e, + 0x2a, 0x36, 0x4c, 0x29, 0x36, 0x4b, 0x29, 0x35, 0x49, 0x29, 0x34, 0x47, 0x28, 0x33, 0x46, 0x28, + 0x32, 0x44, 0x27, 0x31, 0x43, 0x27, 0x30, 0x41, 0x27, 0x30, 0x40, 0x26, 0x2f, 0x3e, 0x26, 0x2e, + 0x3c, 0x26, 0x2d, 0x3b, 0x25, 0x2c, 0x39, 0x25, 0x2b, 0x38, 0x24, 0x2a, 0x36, 0x24, 0x2a, 0x35, + 0x23, 0x29, 0x33, 0x23, 0x28, 0x32, 0x23, 0x27, 0x30, 0x22, 0x26, 0x2f, 0x22, 0x26, 0x2d, 0x22, + 0x25, 0x2c, 0x21, 0x24, 0x2b, 0x21, 0x24, 0x29, 0x21, 0x23, 0x28, 0x20, 0x22, 0x27, 0x20, 0x22, + 0x26, 0x20, 0x21, 0x25, 0x20, 0x21, 0x23, 0x20, 0x21, 0x23, 0x20, 0x21, 0x22, 0x21, 0x20, 0x21, + 0x21, 0x20, 0x20, 0x21, 0x20, 0x20, 0x22, 0x21, 0x1f, 0x23, 0x21, 0x1f, 0x23, 0x21, 0x1e, 0x24, + 0x22, 0x1e, 0x25, 0x22, 0x1e, 0x26, 0x22, 0x1e, 0x26, 0x23, 0x1e, 0x27, 0x24, 0x1e, 0x28, 0x24, + 0x1e, 0x29, 0x25, 0x1e, 0x2a, 0x26, 0x1e, 0x2c, 0x26, 0x1e, 0x2d, 0x27, 0x1e, 0x2e, 0x28, 0x1e, + 0x2f, 0x29, 0x1e, 0x30, 0x29, 0x1e, 0x31, 0x2a, 0x1e, 0x32, 0x2b, 0x1e, 0x33, 0x2c, 0x1e, 0x34, + 0x2d, 0x1f, 0x35, 0x2d, 0x1f, 0x36, 0x2e, 0x1f, 0x38, 0x2f, 0x1f, 0x39, 0x30, 0x1f, 0x3a, 0x31, + 0x1f, 0x3b, 0x31, 0x1f, 0x3c, 0x32, 0x1f, 0x3d, 0x33, 0x1f, 0x3e, 0x34, 0x1f, 0x3f, 0x35, 0x20, + 0x41, 0x35, 0x20, 0x42, 0x36, 0x20, 0x43, 0x37, 0x20, 0x44, 0x38, 0x20, 0x45, 0x39, 0x20, 0x46, + 0x3a, 0x20, 0x47, 0x3a, 0x20, 0x48, 0x3b, 0x20, 0x4a, 0x3c, 0x20, 0x4b, 0x3d, 0x20, 0x4c, 0x3e, + 0x20, 0x4d, 0x3f, 0x21, 0x4e, 0x3f, 0x21, 0x4f, 0x40, 0x21, 0x50, 0x41, 0x21, 0x52, 0x42, 0x21, + 0x53, 0x43, 0x21, 0x54, 0x44, 0x21, 0x55, 0x45, 0x21, 0x56, 0x45, 0x21, 0x57, 0x46, 0x21, 0x58, + 0x47, 0x21, 0x5a, 0x48, 0x21, 0x5b, 0x49, 0x21, 0x5c, 0x4a, 0x21, 0x5d, 0x4b, 0x21, 0x5e, 0x4b, + 0x21, 0x5f, 0x4c, 0x21, 0x61, 0x4d, 0x21, 0x62, 0x4e, 0x21, 0x63, 0x4f, 0x21, 0x64, 0x50, 0x21, + 0x65, 0x51, 0x21, 0x67, 0x52, 0x21, 0x68, 0x52, 0x21, 0x69, 0x53, 0x21, 0x6a, 0x54, 0x21, 0x6b, + 0x55, 0x21, 0x6c, 0x56, 0x21, 0x6e, 0x57, 0x21, 0x6f, 0x58, 0x21, 0x70, 0x59, 0x21, 0x71, 0x5a, + 0x21, 0x72, 0x5a, 0x21, 0x74, 0x5b, 0x21, 0x75, 0x5c, 0x21, 0x76, 0x5d, 0x21, 0x77, 0x5e, 0x21, + 0x78, 0x5f, 0x21, 0x7a, 0x60, 0x21, 0x7b, 0x61, 0x21, 0x7c, 0x62, 0x21, 0x7d, 0x63, 0x21, 0x7f, + 0x63, 0x21, 0x80, 0x64, 0x21, 0x81, 0x65, 0x21, 0x82, 0x66, 0x21, 0x83, 0x67, 0x21, 0x85, 0x68, + 0x20, 0x86, 0x69, 0x20, 0x87, 0x6a, 0x20, 0x88, 0x6b, 0x20, 0x8a, 0x6c, 0x20, 0x8b, 0x6d, 0x20, + 0x8c, 0x6e, 0x20, 0x8d, 0x6e, 0x20, 0x8e, 0x6f, 0x20, 0x90, 0x70, 0x20, 0x91, 0x71, 0x1f, 0x92, + 0x72, 0x1f, 0x93, 0x73, 0x1f, 0x95, 0x74, 0x1f, 0x96, 0x75, 0x1f, 0x97, 0x76, 0x1f, 0x98, 0x77, + 0x1f, 0x9a, 0x78, 0x1e, 0x9b, 0x79, 0x1e, 0x9c, 0x7a, 0x1e, 0x9d, 0x7b, 0x1e, 0x9f, 0x7c, 0x1e, + 0xa0, 0x7d, 0x1e, 0xa1, 0x7e, 0x1d, 0xa3, 0x7e, 0x1d, 0xa4, 0x7f, 0x1d, 0xa5, 0x80, 0x1d, 0xa6, + 0x81, 0x1d, 0xa8, 0x82, 0x1c, 0xa9, 0x83, 0x1c, 0xaa, 0x84, 0x1c, 0xab, 0x85, 0x1c, 0xad, 0x86, + 0x1b, 0xae, 0x87, 0x1b, 0xaf, 0x88, 0x1b, 0xb1, 0x89, 0x1b, 0xb2, 0x8a, 0x1a, 0xb3, 0x8b, 0x1a +}; +static constexpr std::array D07 = { + 0x14, 0x31, 0xc1, 0x18, 0x32, 0xc1, 0x1c, 0x33, 0xc1, 0x1f, 0x33, 0xc0, 0x22, 0x34, 0xc0, 0x25, + 0x35, 0xc0, 0x28, 0x36, 0xbf, 0x2a, 0x36, 0xbf, 0x2d, 0x37, 0xbf, 0x2f, 0x38, 0xbe, 0x31, 0x39, + 0xbe, 0x33, 0x39, 0xbe, 0x35, 0x3a, 0xbd, 0x36, 0x3b, 0xbd, 0x38, 0x3b, 0xbc, 0x3a, 0x3c, 0xbc, + 0x3b, 0x3d, 0xbc, 0x3d, 0x3e, 0xbb, 0x3f, 0x3e, 0xbb, 0x40, 0x3f, 0xbb, 0x42, 0x40, 0xba, 0x43, + 0x41, 0xba, 0x44, 0x41, 0xba, 0x46, 0x42, 0xb9, 0x47, 0x43, 0xb9, 0x48, 0x44, 0xb9, 0x4a, 0x44, + 0xb8, 0x4b, 0x45, 0xb8, 0x4c, 0x46, 0xb7, 0x4d, 0x46, 0xb7, 0x4e, 0x47, 0xb7, 0x4f, 0x48, 0xb6, + 0x51, 0x49, 0xb6, 0x52, 0x49, 0xb6, 0x53, 0x4a, 0xb5, 0x54, 0x4b, 0xb5, 0x55, 0x4c, 0xb5, 0x56, + 0x4c, 0xb4, 0x57, 0x4d, 0xb4, 0x58, 0x4e, 0xb4, 0x59, 0x4f, 0xb3, 0x5a, 0x4f, 0xb3, 0x5b, 0x50, + 0xb2, 0x5c, 0x51, 0xb2, 0x5d, 0x51, 0xb2, 0x5e, 0x52, 0xb1, 0x5e, 0x53, 0xb1, 0x5f, 0x54, 0xb1, + 0x60, 0x54, 0xb0, 0x61, 0x55, 0xb0, 0x62, 0x56, 0xaf, 0x63, 0x57, 0xaf, 0x64, 0x57, 0xaf, 0x64, + 0x58, 0xae, 0x65, 0x59, 0xae, 0x66, 0x5a, 0xae, 0x67, 0x5a, 0xad, 0x68, 0x5b, 0xad, 0x68, 0x5c, + 0xad, 0x69, 0x5d, 0xac, 0x6a, 0x5d, 0xac, 0x6b, 0x5e, 0xab, 0x6b, 0x5f, 0xab, 0x6c, 0x60, 0xab, + 0x6d, 0x60, 0xaa, 0x6e, 0x61, 0xaa, 0x6e, 0x62, 0xa9, 0x6f, 0x63, 0xa9, 0x70, 0x63, 0xa9, 0x70, + 0x64, 0xa8, 0x71, 0x65, 0xa8, 0x72, 0x66, 0xa8, 0x73, 0x66, 0xa7, 0x73, 0x67, 0xa7, 0x74, 0x68, + 0xa6, 0x75, 0x69, 0xa6, 0x75, 0x69, 0xa6, 0x76, 0x6a, 0xa5, 0x76, 0x6b, 0xa5, 0x77, 0x6c, 0xa5, + 0x78, 0x6c, 0xa4, 0x78, 0x6d, 0xa4, 0x79, 0x6e, 0xa3, 0x7a, 0x6f, 0xa3, 0x7a, 0x6f, 0xa3, 0x7b, + 0x70, 0xa2, 0x7b, 0x71, 0xa2, 0x7c, 0x72, 0xa1, 0x7d, 0x72, 0xa1, 0x7d, 0x73, 0xa1, 0x7e, 0x74, + 0xa0, 0x7e, 0x75, 0xa0, 0x7f, 0x75, 0x9f, 0x7f, 0x76, 0x9f, 0x80, 0x77, 0x9f, 0x81, 0x78, 0x9e, + 0x81, 0x78, 0x9e, 0x82, 0x79, 0x9d, 0x82, 0x7a, 0x9d, 0x83, 0x7b, 0x9d, 0x83, 0x7b, 0x9c, 0x84, + 0x7c, 0x9c, 0x84, 0x7d, 0x9b, 0x85, 0x7e, 0x9b, 0x85, 0x7f, 0x9b, 0x86, 0x7f, 0x9a, 0x86, 0x80, + 0x9a, 0x87, 0x81, 0x99, 0x87, 0x82, 0x99, 0x88, 0x82, 0x98, 0x88, 0x83, 0x98, 0x89, 0x84, 0x98, + 0x89, 0x85, 0x97, 0x8a, 0x85, 0x97, 0x8a, 0x86, 0x96, 0x8b, 0x87, 0x96, 0x8b, 0x88, 0x96, 0x8c, + 0x88, 0x95, 0x8c, 0x89, 0x95, 0x8d, 0x8a, 0x94, 0x8d, 0x8b, 0x94, 0x8e, 0x8c, 0x93, 0x8e, 0x8c, + 0x93, 0x8f, 0x8d, 0x93, 0x8f, 0x8e, 0x92, 0x8f, 0x8f, 0x92, 0x90, 0x8f, 0x91, 0x90, 0x90, 0x91, + 0x91, 0x91, 0x90, 0x92, 0x91, 0x90, 0x93, 0x92, 0x8f, 0x94, 0x93, 0x8e, 0x95, 0x93, 0x8e, 0x96, + 0x94, 0x8d, 0x97, 0x95, 0x8d, 0x98, 0x95, 0x8c, 0x99, 0x96, 0x8b, 0x9a, 0x96, 0x8b, 0x9b, 0x97, + 0x8a, 0x9c, 0x98, 0x8a, 0x9d, 0x98, 0x89, 0x9e, 0x99, 0x88, 0x9f, 0x99, 0x88, 0xa0, 0x9a, 0x87, + 0xa1, 0x9b, 0x86, 0xa2, 0x9b, 0x86, 0xa3, 0x9c, 0x85, 0xa4, 0x9d, 0x85, 0xa5, 0x9d, 0x84, 0xa6, + 0x9e, 0x83, 0xa7, 0x9e, 0x83, 0xa8, 0x9f, 0x82, 0xa9, 0xa0, 0x81, 0xaa, 0xa0, 0x81, 0xaa, 0xa1, + 0x80, 0xab, 0xa2, 0x7f, 0xac, 0xa2, 0x7f, 0xad, 0xa3, 0x7e, 0xae, 0xa3, 0x7d, 0xaf, 0xa4, 0x7d, + 0xb0, 0xa5, 0x7c, 0xb1, 0xa5, 0x7b, 0xb2, 0xa6, 0x7b, 0xb3, 0xa7, 0x7a, 0xb3, 0xa7, 0x79, 0xb4, + 0xa8, 0x79, 0xb5, 0xa9, 0x78, 0xb6, 0xa9, 0x77, 0xb7, 0xaa, 0x77, 0xb8, 0xaa, 0x76, 0xb9, 0xab, + 0x75, 0xba, 0xac, 0x75, 0xba, 0xac, 0x74, 0xbb, 0xad, 0x73, 0xbc, 0xae, 0x73, 0xbd, 0xae, 0x72, + 0xbe, 0xaf, 0x71, 0xbf, 0xb0, 0x70, 0xc0, 0xb0, 0x70, 0xc0, 0xb1, 0x6f, 0xc1, 0xb2, 0x6e, 0xc2, + 0xb2, 0x6d, 0xc3, 0xb3, 0x6d, 0xc4, 0xb4, 0x6c, 0xc5, 0xb4, 0x6b, 0xc6, 0xb5, 0x6a, 0xc6, 0xb5, + 0x6a, 0xc7, 0xb6, 0x69, 0xc8, 0xb7, 0x68, 0xc9, 0xb7, 0x67, 0xca, 0xb8, 0x67, 0xcb, 0xb9, 0x66, + 0xcb, 0xb9, 0x65, 0xcc, 0xba, 0x64, 0xcd, 0xbb, 0x63, 0xce, 0xbb, 0x63, 0xcf, 0xbc, 0x62, 0xcf, + 0xbd, 0x61, 0xd0, 0xbd, 0x60, 0xd1, 0xbe, 0x5f, 0xd2, 0xbf, 0x5e, 0xd3, 0xbf, 0x5e, 0xd4, 0xc0, + 0x5d, 0xd4, 0xc1, 0x5c, 0xd5, 0xc1, 0x5b, 0xd6, 0xc2, 0x5a, 0xd7, 0xc3, 0x59, 0xd8, 0xc3, 0x58, + 0xd8, 0xc4, 0x57, 0xd9, 0xc5, 0x56, 0xda, 0xc5, 0x56, 0xdb, 0xc6, 0x55, 0xdc, 0xc7, 0x54, 0xdc, + 0xc7, 0x53, 0xdd, 0xc8, 0x52, 0xde, 0xc9, 0x51, 0xdf, 0xc9, 0x50, 0xdf, 0xca, 0x4f, 0xe0, 0xcb, + 0x4e, 0xe1, 0xcb, 0x4d, 0xe2, 0xcc, 0x4c, 0xe3, 0xcd, 0x4b, 0xe3, 0xcd, 0x49, 0xe4, 0xce, 0x48, + 0xe5, 0xcf, 0x47, 0xe6, 0xcf, 0x46, 0xe7, 0xd0, 0x45, 0xe7, 0xd1, 0x44, 0xe8, 0xd1, 0x43, 0xe9, + 0xd2, 0x41, 0xea, 0xd3, 0x40, 0xea, 0xd3, 0x3f, 0xeb, 0xd4, 0x3e, 0xec, 0xd5, 0x3c, 0xed, 0xd6, + 0x3b, 0xed, 0xd6, 0x39, 0xee, 0xd7, 0x38, 0xef, 0xd8, 0x37, 0xf0, 0xd8, 0x35, 0xf1, 0xd9, 0x33, + 0xf1, 0xda, 0x32, 0xf2, 0xda, 0x30, 0xf3, 0xdb, 0x2e, 0xf4, 0xdc, 0x2d, 0xf4, 0xdc, 0x2b, 0xf5, + 0xdd, 0x29, 0xf6, 0xde, 0x27, 0xf7, 0xde, 0x25, 0xf7, 0xdf, 0x22, 0xf8, 0xe0, 0x20, 0xf9, 0xe0, + 0x1d, 0xfa, 0xe1, 0x1a, 0xfa, 0xe2, 0x17, 0xfb, 0xe3, 0x13, 0xfc, 0xe3, 0x0f, 0xfd, 0xe4, 0x09 +}; +static constexpr std::array D08 = { + 0x00, 0x2a, 0xd7, 0x00, 0x2b, 0xd6, 0x00, 0x2b, 0xd5, 0x00, 0x2c, 0xd4, 0x00, 0x2c, 0xd4, 0x00, + 0x2d, 0xd3, 0x00, 0x2d, 0xd2, 0x00, 0x2e, 0xd1, 0x07, 0x2e, 0xd0, 0x0d, 0x2f, 0xcf, 0x13, 0x2f, + 0xce, 0x17, 0x30, 0xcd, 0x1b, 0x30, 0xcc, 0x1e, 0x31, 0xcb, 0x21, 0x31, 0xca, 0x23, 0x32, 0xc9, + 0x26, 0x32, 0xc9, 0x28, 0x33, 0xc8, 0x2a, 0x33, 0xc7, 0x2c, 0x34, 0xc6, 0x2e, 0x34, 0xc5, 0x2f, + 0x35, 0xc4, 0x31, 0x35, 0xc3, 0x33, 0x36, 0xc2, 0x34, 0x36, 0xc1, 0x36, 0x37, 0xc0, 0x37, 0x37, + 0xbf, 0x38, 0x38, 0xbf, 0x3a, 0x38, 0xbe, 0x3b, 0x39, 0xbd, 0x3c, 0x39, 0xbc, 0x3d, 0x39, 0xbb, + 0x3e, 0x3a, 0xba, 0x40, 0x3a, 0xb9, 0x41, 0x3b, 0xb8, 0x42, 0x3b, 0xb7, 0x43, 0x3c, 0xb6, 0x44, + 0x3c, 0xb5, 0x45, 0x3d, 0xb5, 0x45, 0x3d, 0xb4, 0x46, 0x3e, 0xb3, 0x47, 0x3e, 0xb2, 0x48, 0x3f, + 0xb1, 0x49, 0x3f, 0xb0, 0x4a, 0x40, 0xaf, 0x4a, 0x40, 0xae, 0x4b, 0x40, 0xad, 0x4c, 0x41, 0xac, + 0x4d, 0x41, 0xac, 0x4d, 0x42, 0xab, 0x4e, 0x42, 0xaa, 0x4f, 0x43, 0xa9, 0x4f, 0x43, 0xa8, 0x50, + 0x44, 0xa7, 0x51, 0x44, 0xa6, 0x51, 0x45, 0xa5, 0x52, 0x45, 0xa4, 0x52, 0x46, 0xa3, 0x53, 0x46, + 0xa3, 0x54, 0x46, 0xa2, 0x54, 0x47, 0xa1, 0x55, 0x47, 0xa0, 0x55, 0x48, 0x9f, 0x56, 0x48, 0x9e, + 0x56, 0x49, 0x9d, 0x57, 0x49, 0x9c, 0x57, 0x4a, 0x9b, 0x58, 0x4a, 0x9b, 0x58, 0x4a, 0x9a, 0x58, + 0x4b, 0x99, 0x59, 0x4b, 0x98, 0x59, 0x4c, 0x97, 0x5a, 0x4c, 0x96, 0x5a, 0x4d, 0x95, 0x5b, 0x4d, + 0x94, 0x5b, 0x4e, 0x93, 0x5b, 0x4e, 0x92, 0x5c, 0x4e, 0x92, 0x5c, 0x4f, 0x91, 0x5c, 0x4f, 0x90, + 0x5d, 0x50, 0x8f, 0x5d, 0x50, 0x8e, 0x5d, 0x51, 0x8d, 0x5e, 0x51, 0x8c, 0x5e, 0x52, 0x8b, 0x5e, + 0x52, 0x8a, 0x5e, 0x52, 0x8a, 0x5f, 0x53, 0x89, 0x5f, 0x53, 0x88, 0x5f, 0x54, 0x87, 0x60, 0x54, + 0x86, 0x60, 0x55, 0x85, 0x60, 0x55, 0x84, 0x60, 0x56, 0x83, 0x60, 0x56, 0x82, 0x61, 0x56, 0x82, + 0x61, 0x57, 0x81, 0x61, 0x57, 0x80, 0x61, 0x58, 0x7f, 0x62, 0x58, 0x7e, 0x62, 0x59, 0x7d, 0x62, + 0x59, 0x7c, 0x62, 0x59, 0x7b, 0x62, 0x5a, 0x7a, 0x62, 0x5a, 0x7a, 0x63, 0x5b, 0x79, 0x63, 0x5b, + 0x78, 0x63, 0x5c, 0x77, 0x63, 0x5c, 0x76, 0x63, 0x5c, 0x75, 0x63, 0x5d, 0x74, 0x63, 0x5d, 0x73, + 0x63, 0x5e, 0x72, 0x63, 0x5e, 0x71, 0x64, 0x5f, 0x71, 0x64, 0x5f, 0x70, 0x64, 0x5f, 0x6f, 0x64, + 0x60, 0x6e, 0x64, 0x60, 0x6d, 0x64, 0x61, 0x6c, 0x64, 0x61, 0x6b, 0x64, 0x62, 0x6a, 0x64, 0x62, + 0x69, 0x64, 0x62, 0x68, 0x64, 0x63, 0x67, 0x64, 0x63, 0x67, 0x64, 0x64, 0x66, 0x64, 0x64, 0x65, + 0x65, 0x64, 0x64, 0x67, 0x64, 0x63, 0x69, 0x64, 0x63, 0x6a, 0x64, 0x62, 0x6c, 0x64, 0x61, 0x6e, + 0x64, 0x61, 0x6f, 0x63, 0x60, 0x71, 0x63, 0x60, 0x72, 0x63, 0x5f, 0x74, 0x63, 0x5e, 0x75, 0x63, + 0x5e, 0x77, 0x63, 0x5d, 0x78, 0x63, 0x5c, 0x7a, 0x62, 0x5c, 0x7b, 0x62, 0x5b, 0x7d, 0x62, 0x5b, + 0x7e, 0x62, 0x5a, 0x80, 0x62, 0x59, 0x81, 0x62, 0x59, 0x83, 0x61, 0x58, 0x84, 0x61, 0x57, 0x86, + 0x61, 0x57, 0x87, 0x61, 0x56, 0x88, 0x61, 0x56, 0x8a, 0x60, 0x55, 0x8b, 0x60, 0x54, 0x8c, 0x60, + 0x54, 0x8e, 0x60, 0x53, 0x8f, 0x60, 0x52, 0x90, 0x5f, 0x52, 0x92, 0x5f, 0x51, 0x93, 0x5f, 0x51, + 0x94, 0x5f, 0x50, 0x96, 0x5e, 0x4f, 0x97, 0x5e, 0x4f, 0x98, 0x5e, 0x4e, 0x9a, 0x5e, 0x4d, 0x9b, + 0x5d, 0x4d, 0x9c, 0x5d, 0x4c, 0x9e, 0x5d, 0x4b, 0x9f, 0x5d, 0x4b, 0xa0, 0x5c, 0x4a, 0xa1, 0x5c, + 0x49, 0xa3, 0x5c, 0x49, 0xa4, 0x5b, 0x48, 0xa5, 0x5b, 0x48, 0xa6, 0x5b, 0x47, 0xa8, 0x5b, 0x46, + 0xa9, 0x5a, 0x46, 0xaa, 0x5a, 0x45, 0xab, 0x5a, 0x44, 0xad, 0x59, 0x44, 0xae, 0x59, 0x43, 0xaf, + 0x59, 0x42, 0xb0, 0x58, 0x42, 0xb1, 0x58, 0x41, 0xb3, 0x58, 0x40, 0xb4, 0x57, 0x40, 0xb5, 0x57, + 0x3f, 0xb6, 0x56, 0x3e, 0xb7, 0x56, 0x3e, 0xb9, 0x56, 0x3d, 0xba, 0x55, 0x3c, 0xbb, 0x55, 0x3c, + 0xbc, 0x54, 0x3b, 0xbd, 0x54, 0x3a, 0xbf, 0x54, 0x3a, 0xc0, 0x53, 0x39, 0xc1, 0x53, 0x38, 0xc2, + 0x52, 0x38, 0xc3, 0x52, 0x37, 0xc5, 0x51, 0x36, 0xc6, 0x51, 0x35, 0xc7, 0x50, 0x35, 0xc8, 0x50, + 0x34, 0xc9, 0x4f, 0x33, 0xca, 0x4f, 0x33, 0xcc, 0x4e, 0x32, 0xcd, 0x4e, 0x31, 0xce, 0x4d, 0x30, + 0xcf, 0x4d, 0x30, 0xd0, 0x4c, 0x2f, 0xd1, 0x4c, 0x2e, 0xd2, 0x4b, 0x2e, 0xd4, 0x4a, 0x2d, 0xd5, + 0x4a, 0x2c, 0xd6, 0x49, 0x2b, 0xd7, 0x49, 0x2b, 0xd8, 0x48, 0x2a, 0xd9, 0x47, 0x29, 0xda, 0x47, + 0x28, 0xdc, 0x46, 0x27, 0xdd, 0x45, 0x27, 0xde, 0x45, 0x26, 0xdf, 0x44, 0x25, 0xe0, 0x43, 0x24, + 0xe1, 0x42, 0x23, 0xe2, 0x41, 0x23, 0xe4, 0x41, 0x22, 0xe5, 0x40, 0x21, 0xe6, 0x3f, 0x20, 0xe7, + 0x3e, 0x1f, 0xe8, 0x3d, 0x1e, 0xe9, 0x3c, 0x1d, 0xea, 0x3b, 0x1c, 0xeb, 0x3a, 0x1b, 0xed, 0x3a, + 0x1b, 0xee, 0x38, 0x1a, 0xef, 0x37, 0x19, 0xf0, 0x36, 0x18, 0xf1, 0x35, 0x16, 0xf2, 0x34, 0x15, + 0xf3, 0x33, 0x14, 0xf4, 0x32, 0x13, 0xf6, 0x30, 0x12, 0xf7, 0x2f, 0x11, 0xf8, 0x2e, 0x0f, 0xf9, + 0x2c, 0x0e, 0xfa, 0x2b, 0x0d, 0xfb, 0x29, 0x0b, 0xfc, 0x28, 0x09, 0xfd, 0x26, 0x08, 0xff, 0x24, + 0x06, 0xff, 0x22, 0x05, 0xff, 0x20, 0x03, 0xff, 0x1e, 0x01, 0xff, 0x1b, 0x00, 0xff, 0x19, 0x00 +}; +static constexpr std::array D09 = { + 0x24, 0x80, 0xff, 0x29, 0x81, 0xff, 0x2e, 0x81, 0xff, 0x32, 0x82, 0xff, 0x36, 0x83, 0xff, 0x3a, + 0x84, 0xff, 0x3e, 0x85, 0xff, 0x41, 0x86, 0xff, 0x44, 0x87, 0xff, 0x47, 0x87, 0xff, 0x4a, 0x88, + 0xfe, 0x4d, 0x89, 0xfe, 0x4f, 0x8a, 0xfe, 0x52, 0x8b, 0xfe, 0x54, 0x8c, 0xfe, 0x57, 0x8d, 0xfe, + 0x59, 0x8e, 0xfe, 0x5b, 0x8e, 0xfe, 0x5e, 0x8f, 0xfe, 0x60, 0x90, 0xfe, 0x62, 0x91, 0xfe, 0x64, + 0x92, 0xfe, 0x66, 0x93, 0xfe, 0x68, 0x94, 0xfe, 0x6a, 0x95, 0xfe, 0x6c, 0x96, 0xfe, 0x6e, 0x96, + 0xfe, 0x70, 0x97, 0xfe, 0x72, 0x98, 0xfe, 0x74, 0x99, 0xfe, 0x76, 0x9a, 0xfe, 0x77, 0x9b, 0xfe, + 0x79, 0x9c, 0xfe, 0x7b, 0x9d, 0xfe, 0x7d, 0x9e, 0xfe, 0x7e, 0x9f, 0xfe, 0x80, 0x9f, 0xfe, 0x82, + 0xa0, 0xfe, 0x83, 0xa1, 0xfe, 0x85, 0xa2, 0xfe, 0x87, 0xa3, 0xfe, 0x88, 0xa4, 0xfe, 0x8a, 0xa5, + 0xfe, 0x8b, 0xa6, 0xfe, 0x8d, 0xa7, 0xfe, 0x8f, 0xa8, 0xfe, 0x90, 0xa9, 0xfe, 0x92, 0xaa, 0xfe, + 0x93, 0xab, 0xfe, 0x95, 0xab, 0xfe, 0x96, 0xac, 0xfe, 0x98, 0xad, 0xfe, 0x99, 0xae, 0xfe, 0x9b, + 0xaf, 0xfe, 0x9c, 0xb0, 0xfe, 0x9d, 0xb1, 0xfe, 0x9f, 0xb2, 0xfe, 0xa0, 0xb3, 0xfe, 0xa2, 0xb4, + 0xfe, 0xa3, 0xb5, 0xfe, 0xa5, 0xb6, 0xfe, 0xa6, 0xb7, 0xfd, 0xa7, 0xb8, 0xfd, 0xa9, 0xb9, 0xfd, + 0xaa, 0xba, 0xfd, 0xab, 0xbb, 0xfd, 0xad, 0xbb, 0xfd, 0xae, 0xbc, 0xfd, 0xaf, 0xbd, 0xfd, 0xb1, + 0xbe, 0xfd, 0xb2, 0xbf, 0xfd, 0xb3, 0xc0, 0xfd, 0xb5, 0xc1, 0xfd, 0xb6, 0xc2, 0xfd, 0xb7, 0xc3, + 0xfd, 0xb9, 0xc4, 0xfd, 0xba, 0xc5, 0xfd, 0xbb, 0xc6, 0xfd, 0xbd, 0xc7, 0xfd, 0xbe, 0xc8, 0xfd, + 0xbf, 0xc9, 0xfd, 0xc0, 0xca, 0xfd, 0xc2, 0xcb, 0xfd, 0xc3, 0xcc, 0xfc, 0xc4, 0xcd, 0xfc, 0xc6, + 0xce, 0xfc, 0xc7, 0xcf, 0xfc, 0xc8, 0xd0, 0xfc, 0xc9, 0xd1, 0xfc, 0xcb, 0xd2, 0xfc, 0xcc, 0xd3, + 0xfc, 0xcd, 0xd4, 0xfc, 0xce, 0xd5, 0xfc, 0xcf, 0xd6, 0xfc, 0xd1, 0xd7, 0xfc, 0xd2, 0xd8, 0xfc, + 0xd3, 0xd9, 0xfc, 0xd4, 0xda, 0xfc, 0xd6, 0xdb, 0xfc, 0xd7, 0xdc, 0xfc, 0xd8, 0xdd, 0xfb, 0xd9, + 0xde, 0xfb, 0xda, 0xdf, 0xfb, 0xdc, 0xe0, 0xfb, 0xdd, 0xe1, 0xfb, 0xde, 0xe2, 0xfb, 0xdf, 0xe3, + 0xfb, 0xe0, 0xe4, 0xfb, 0xe2, 0xe5, 0xfb, 0xe3, 0xe6, 0xfb, 0xe4, 0xe7, 0xfb, 0xe5, 0xe8, 0xfb, + 0xe6, 0xe9, 0xfb, 0xe7, 0xea, 0xfb, 0xe9, 0xeb, 0xfa, 0xea, 0xec, 0xfa, 0xeb, 0xed, 0xfa, 0xec, + 0xee, 0xfa, 0xed, 0xef, 0xfa, 0xee, 0xf0, 0xfa, 0xf0, 0xf1, 0xfa, 0xf1, 0xf2, 0xfa, 0xf2, 0xf3, + 0xfa, 0xf3, 0xf4, 0xfa, 0xf4, 0xf5, 0xf9, 0xf5, 0xf6, 0xf9, 0xf7, 0xf6, 0xf9, 0xf8, 0xf7, 0xf8, + 0xf9, 0xf6, 0xf7, 0xf9, 0xf6, 0xf5, 0xfa, 0xf5, 0xf4, 0xfa, 0xf4, 0xf2, 0xfa, 0xf2, 0xf0, 0xfb, + 0xf1, 0xef, 0xfb, 0xf0, 0xed, 0xfb, 0xef, 0xec, 0xfb, 0xed, 0xea, 0xfc, 0xec, 0xe8, 0xfc, 0xeb, + 0xe7, 0xfc, 0xea, 0xe5, 0xfc, 0xe8, 0xe3, 0xfc, 0xe7, 0xe2, 0xfc, 0xe6, 0xe0, 0xfc, 0xe5, 0xdf, + 0xfd, 0xe3, 0xdd, 0xfd, 0xe2, 0xdb, 0xfd, 0xe1, 0xda, 0xfd, 0xdf, 0xd8, 0xfd, 0xde, 0xd7, 0xfd, + 0xdd, 0xd5, 0xfd, 0xdc, 0xd3, 0xfd, 0xda, 0xd2, 0xfd, 0xd9, 0xd0, 0xfd, 0xd8, 0xcf, 0xfe, 0xd7, + 0xcd, 0xfe, 0xd5, 0xcb, 0xfe, 0xd4, 0xca, 0xfe, 0xd3, 0xc8, 0xfe, 0xd2, 0xc7, 0xfe, 0xd0, 0xc5, + 0xfe, 0xcf, 0xc3, 0xfe, 0xce, 0xc2, 0xfe, 0xcd, 0xc0, 0xfe, 0xcb, 0xbf, 0xfe, 0xca, 0xbd, 0xfe, + 0xc9, 0xbc, 0xfe, 0xc7, 0xba, 0xfe, 0xc6, 0xb9, 0xfe, 0xc5, 0xb7, 0xfe, 0xc4, 0xb5, 0xfe, 0xc2, + 0xb4, 0xfe, 0xc1, 0xb2, 0xfd, 0xc0, 0xb1, 0xfd, 0xbf, 0xaf, 0xfd, 0xbd, 0xae, 0xfd, 0xbc, 0xac, + 0xfd, 0xbb, 0xab, 0xfd, 0xba, 0xa9, 0xfd, 0xb8, 0xa7, 0xfd, 0xb7, 0xa6, 0xfd, 0xb6, 0xa4, 0xfd, + 0xb4, 0xa3, 0xfd, 0xb3, 0xa1, 0xfc, 0xb2, 0xa0, 0xfc, 0xb1, 0x9e, 0xfc, 0xaf, 0x9d, 0xfc, 0xae, + 0x9b, 0xfc, 0xad, 0x9a, 0xfc, 0xac, 0x98, 0xfc, 0xaa, 0x97, 0xfb, 0xa9, 0x95, 0xfb, 0xa8, 0x94, + 0xfb, 0xa6, 0x92, 0xfb, 0xa5, 0x91, 0xfb, 0xa4, 0x8f, 0xfb, 0xa3, 0x8e, 0xfa, 0xa1, 0x8c, 0xfa, + 0xa0, 0x8b, 0xfa, 0x9f, 0x89, 0xfa, 0x9e, 0x88, 0xf9, 0x9c, 0x86, 0xf9, 0x9b, 0x85, 0xf9, 0x9a, + 0x83, 0xf9, 0x98, 0x82, 0xf9, 0x97, 0x80, 0xf8, 0x96, 0x7f, 0xf8, 0x94, 0x7d, 0xf8, 0x93, 0x7c, + 0xf8, 0x92, 0x7a, 0xf7, 0x91, 0x79, 0xf7, 0x8f, 0x77, 0xf7, 0x8e, 0x76, 0xf6, 0x8d, 0x74, 0xf6, + 0x8b, 0x73, 0xf6, 0x8a, 0x71, 0xf6, 0x89, 0x70, 0xf5, 0x87, 0x6e, 0xf5, 0x86, 0x6d, 0xf5, 0x85, + 0x6b, 0xf4, 0x83, 0x6a, 0xf4, 0x82, 0x69, 0xf4, 0x81, 0x67, 0xf3, 0x7f, 0x66, 0xf3, 0x7e, 0x64, + 0xf3, 0x7d, 0x63, 0xf2, 0x7b, 0x61, 0xf2, 0x7a, 0x60, 0xf2, 0x79, 0x5e, 0xf1, 0x77, 0x5d, 0xf1, + 0x76, 0x5c, 0xf1, 0x75, 0x5a, 0xf0, 0x73, 0x59, 0xf0, 0x72, 0x57, 0xf0, 0x71, 0x56, 0xef, 0x6f, + 0x54, 0xef, 0x6e, 0x53, 0xee, 0x6c, 0x52, 0xee, 0x6b, 0x50, 0xee, 0x6a, 0x4f, 0xed, 0x68, 0x4d, + 0xed, 0x67, 0x4c, 0xec, 0x65, 0x4a, 0xec, 0x64, 0x49, 0xec, 0x62, 0x48, 0xeb, 0x61, 0x46, 0xeb, + 0x60, 0x45, 0xea, 0x5e, 0x43, 0xea, 0x5d, 0x42, 0xe9, 0x5b, 0x41, 0xe9, 0x5a, 0x3f, 0xe9, 0x58, + 0x3e, 0xe8, 0x57, 0x3c, 0xe8, 0x55, 0x3b, 0xe7, 0x53, 0x3a, 0xe7, 0x52, 0x38, 0xe6, 0x50, 0x37 +}; +static constexpr std::array D10 = { + 0x00, 0xd9, 0xff, 0x00, 0xd9, 0xff, 0x0e, 0xda, 0xff, 0x1a, 0xda, 0xff, 0x22, 0xda, 0xff, 0x28, + 0xda, 0xff, 0x2e, 0xdb, 0xff, 0x33, 0xdb, 0xff, 0x37, 0xdb, 0xff, 0x3b, 0xdc, 0xff, 0x3f, 0xdc, + 0xff, 0x43, 0xdc, 0xff, 0x46, 0xdd, 0xff, 0x49, 0xdd, 0xff, 0x4d, 0xdd, 0xff, 0x50, 0xde, 0xff, + 0x52, 0xde, 0xff, 0x55, 0xde, 0xff, 0x58, 0xdf, 0xff, 0x5b, 0xdf, 0xff, 0x5d, 0xdf, 0xff, 0x60, + 0xdf, 0xff, 0x62, 0xe0, 0xff, 0x64, 0xe0, 0xff, 0x67, 0xe0, 0xff, 0x69, 0xe1, 0xff, 0x6b, 0xe1, + 0xff, 0x6d, 0xe1, 0xff, 0x6f, 0xe2, 0xff, 0x72, 0xe2, 0xff, 0x74, 0xe2, 0xff, 0x76, 0xe2, 0xff, + 0x78, 0xe3, 0xff, 0x7a, 0xe3, 0xff, 0x7b, 0xe3, 0xff, 0x7d, 0xe4, 0xff, 0x7f, 0xe4, 0xff, 0x81, + 0xe4, 0xff, 0x83, 0xe5, 0xff, 0x85, 0xe5, 0xff, 0x86, 0xe5, 0xff, 0x88, 0xe6, 0xff, 0x8a, 0xe6, + 0xff, 0x8c, 0xe6, 0xff, 0x8d, 0xe6, 0xff, 0x8f, 0xe7, 0xff, 0x91, 0xe7, 0xff, 0x92, 0xe7, 0xff, + 0x94, 0xe8, 0xff, 0x96, 0xe8, 0xff, 0x97, 0xe8, 0xff, 0x99, 0xe9, 0xff, 0x9b, 0xe9, 0xff, 0x9c, + 0xe9, 0xff, 0x9e, 0xe9, 0xff, 0x9f, 0xea, 0xff, 0xa1, 0xea, 0xff, 0xa2, 0xea, 0xff, 0xa4, 0xeb, + 0xff, 0xa5, 0xeb, 0xff, 0xa7, 0xeb, 0xff, 0xa8, 0xec, 0xff, 0xaa, 0xec, 0xff, 0xab, 0xec, 0xff, + 0xad, 0xec, 0xff, 0xae, 0xed, 0xff, 0xb0, 0xed, 0xff, 0xb1, 0xed, 0xff, 0xb3, 0xee, 0xff, 0xb4, + 0xee, 0xff, 0xb5, 0xee, 0xff, 0xb7, 0xef, 0xff, 0xb8, 0xef, 0xff, 0xba, 0xef, 0xff, 0xbb, 0xef, + 0xff, 0xbc, 0xf0, 0xff, 0xbe, 0xf0, 0xff, 0xbf, 0xf0, 0xff, 0xc0, 0xf1, 0xff, 0xc2, 0xf1, 0xff, + 0xc3, 0xf1, 0xff, 0xc5, 0xf1, 0xff, 0xc6, 0xf2, 0xff, 0xc7, 0xf2, 0xff, 0xc9, 0xf2, 0xff, 0xca, + 0xf3, 0xff, 0xcb, 0xf3, 0xff, 0xcd, 0xf3, 0xff, 0xce, 0xf4, 0xff, 0xcf, 0xf4, 0xff, 0xd0, 0xf4, + 0xff, 0xd2, 0xf4, 0xff, 0xd3, 0xf5, 0xff, 0xd4, 0xf5, 0xff, 0xd6, 0xf5, 0xff, 0xd7, 0xf6, 0xff, + 0xd8, 0xf6, 0xff, 0xd9, 0xf6, 0xff, 0xdb, 0xf6, 0xff, 0xdc, 0xf7, 0xff, 0xdd, 0xf7, 0xff, 0xde, + 0xf7, 0xff, 0xe0, 0xf8, 0xff, 0xe1, 0xf8, 0xff, 0xe2, 0xf8, 0xff, 0xe3, 0xf8, 0xff, 0xe5, 0xf9, + 0xff, 0xe6, 0xf9, 0xff, 0xe7, 0xf9, 0xff, 0xe8, 0xfa, 0xff, 0xea, 0xfa, 0xff, 0xeb, 0xfa, 0xff, + 0xec, 0xfb, 0xff, 0xed, 0xfb, 0xff, 0xee, 0xfb, 0xff, 0xf0, 0xfb, 0xff, 0xf1, 0xfc, 0xff, 0xf2, + 0xfc, 0xff, 0xf3, 0xfc, 0xff, 0xf5, 0xfd, 0xff, 0xf6, 0xfd, 0xff, 0xf7, 0xfd, 0xff, 0xf8, 0xfd, + 0xff, 0xf9, 0xfe, 0xff, 0xfb, 0xfe, 0xff, 0xfc, 0xfe, 0xff, 0xfd, 0xfe, 0xff, 0xfe, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xfd, 0xff, 0xff, 0xfc, 0xfe, 0xff, + 0xfb, 0xfe, 0xff, 0xfb, 0xfe, 0xff, 0xfa, 0xfe, 0xff, 0xfa, 0xfe, 0xff, 0xf9, 0xfe, 0xff, 0xf8, + 0xfe, 0xff, 0xf8, 0xfe, 0xff, 0xf7, 0xfe, 0xff, 0xf6, 0xfd, 0xff, 0xf6, 0xfd, 0xff, 0xf5, 0xfd, + 0xff, 0xf5, 0xfd, 0xff, 0xf4, 0xfd, 0xff, 0xf3, 0xfd, 0xff, 0xf3, 0xfd, 0xff, 0xf2, 0xfd, 0xff, + 0xf1, 0xfd, 0xff, 0xf1, 0xfc, 0xff, 0xf0, 0xfc, 0xff, 0xef, 0xfc, 0xff, 0xef, 0xfc, 0xff, 0xee, + 0xfc, 0xff, 0xee, 0xfc, 0xff, 0xed, 0xfc, 0xff, 0xec, 0xfc, 0xff, 0xec, 0xfc, 0xff, 0xeb, 0xfb, + 0xff, 0xea, 0xfb, 0xff, 0xea, 0xfb, 0xff, 0xe9, 0xfb, 0xff, 0xe9, 0xfb, 0xff, 0xe8, 0xfb, 0xff, + 0xe7, 0xfb, 0xff, 0xe7, 0xfb, 0xff, 0xe6, 0xfb, 0xff, 0xe5, 0xfa, 0xff, 0xe5, 0xfa, 0xff, 0xe4, + 0xfa, 0xff, 0xe4, 0xfa, 0xff, 0xe3, 0xfa, 0xfe, 0xe2, 0xfa, 0xfe, 0xe2, 0xfa, 0xfe, 0xe1, 0xfa, + 0xfe, 0xe0, 0xfa, 0xfe, 0xe0, 0xf9, 0xfe, 0xdf, 0xf9, 0xfe, 0xde, 0xf9, 0xfe, 0xde, 0xf9, 0xfe, + 0xdd, 0xf9, 0xfe, 0xdd, 0xf9, 0xfe, 0xdc, 0xf9, 0xfe, 0xdb, 0xf9, 0xfe, 0xdb, 0xf8, 0xfe, 0xda, + 0xf8, 0xfe, 0xd9, 0xf8, 0xfe, 0xd9, 0xf8, 0xfe, 0xd8, 0xf8, 0xfe, 0xd8, 0xf8, 0xfe, 0xd7, 0xf8, + 0xfe, 0xd6, 0xf8, 0xfe, 0xd6, 0xf8, 0xfe, 0xd5, 0xf7, 0xfe, 0xd4, 0xf7, 0xfe, 0xd4, 0xf7, 0xfe, + 0xd3, 0xf7, 0xfe, 0xd2, 0xf7, 0xfe, 0xd2, 0xf7, 0xfd, 0xd1, 0xf7, 0xfd, 0xd1, 0xf7, 0xfd, 0xd0, + 0xf6, 0xfd, 0xcf, 0xf6, 0xfd, 0xcf, 0xf6, 0xfd, 0xce, 0xf6, 0xfd, 0xcd, 0xf6, 0xfd, 0xcd, 0xf6, + 0xfd, 0xcc, 0xf6, 0xfd, 0xcb, 0xf6, 0xfd, 0xcb, 0xf6, 0xfd, 0xca, 0xf5, 0xfd, 0xc9, 0xf5, 0xfd, + 0xc9, 0xf5, 0xfd, 0xc8, 0xf5, 0xfd, 0xc8, 0xf5, 0xfd, 0xc7, 0xf5, 0xfd, 0xc6, 0xf5, 0xfd, 0xc6, + 0xf5, 0xfc, 0xc5, 0xf4, 0xfc, 0xc4, 0xf4, 0xfc, 0xc4, 0xf4, 0xfc, 0xc3, 0xf4, 0xfc, 0xc2, 0xf4, + 0xfc, 0xc2, 0xf4, 0xfc, 0xc1, 0xf4, 0xfc, 0xc0, 0xf4, 0xfc, 0xc0, 0xf4, 0xfc, 0xbf, 0xf3, 0xfc, + 0xbf, 0xf3, 0xfc, 0xbe, 0xf3, 0xfc, 0xbd, 0xf3, 0xfc, 0xbd, 0xf3, 0xfc, 0xbc, 0xf3, 0xfb, 0xbb, + 0xf3, 0xfb, 0xbb, 0xf3, 0xfb, 0xba, 0xf2, 0xfb, 0xb9, 0xf2, 0xfb, 0xb9, 0xf2, 0xfb, 0xb8, 0xf2, + 0xfb, 0xb7, 0xf2, 0xfb, 0xb7, 0xf2, 0xfb, 0xb6, 0xf2, 0xfb, 0xb5, 0xf2, 0xfb, 0xb5, 0xf1, 0xfb, + 0xb4, 0xf1, 0xfb, 0xb3, 0xf1, 0xfb, 0xb3, 0xf1, 0xfa, 0xb2, 0xf1, 0xfa, 0xb1, 0xf1, 0xfa, 0xb1, + 0xf1, 0xfa, 0xb0, 0xf1, 0xfa, 0xaf, 0xf0, 0xfa, 0xaf, 0xf0, 0xfa, 0xae, 0xf0, 0xfa, 0xae, 0xf0 +}; +static constexpr std::array D11 = { + 0x00, 0xb6, 0xff, 0x00, 0xb6, 0xff, 0x00, 0xb6, 0xff, 0x00, 0xb6, 0xff, 0x06, 0xb6, 0xff, 0x11, + 0xb6, 0xff, 0x19, 0xb6, 0xfe, 0x1f, 0xb6, 0xfd, 0x24, 0xb6, 0xfd, 0x28, 0xb6, 0xfc, 0x2c, 0xb5, + 0xfb, 0x2f, 0xb5, 0xfb, 0x33, 0xb5, 0xfa, 0x36, 0xb5, 0xf9, 0x39, 0xb5, 0xf9, 0x3b, 0xb5, 0xf8, + 0x3e, 0xb5, 0xf7, 0x40, 0xb5, 0xf6, 0x43, 0xb5, 0xf6, 0x45, 0xb5, 0xf5, 0x47, 0xb5, 0xf4, 0x49, + 0xb4, 0xf4, 0x4b, 0xb4, 0xf3, 0x4d, 0xb4, 0xf2, 0x4f, 0xb4, 0xf2, 0x51, 0xb4, 0xf1, 0x52, 0xb4, + 0xf0, 0x54, 0xb4, 0xf0, 0x56, 0xb4, 0xef, 0x57, 0xb4, 0xee, 0x59, 0xb4, 0xed, 0x5a, 0xb4, 0xed, + 0x5c, 0xb3, 0xec, 0x5d, 0xb3, 0xeb, 0x5f, 0xb3, 0xeb, 0x60, 0xb3, 0xea, 0x62, 0xb3, 0xe9, 0x63, + 0xb3, 0xe9, 0x64, 0xb3, 0xe8, 0x66, 0xb3, 0xe7, 0x67, 0xb3, 0xe7, 0x68, 0xb3, 0xe6, 0x69, 0xb3, + 0xe5, 0x6b, 0xb2, 0xe5, 0x6c, 0xb2, 0xe4, 0x6d, 0xb2, 0xe3, 0x6e, 0xb2, 0xe3, 0x6f, 0xb2, 0xe2, + 0x70, 0xb2, 0xe1, 0x71, 0xb2, 0xe0, 0x73, 0xb2, 0xe0, 0x74, 0xb2, 0xdf, 0x75, 0xb2, 0xde, 0x76, + 0xb2, 0xde, 0x77, 0xb1, 0xdd, 0x78, 0xb1, 0xdc, 0x79, 0xb1, 0xdc, 0x7a, 0xb1, 0xdb, 0x7b, 0xb1, + 0xda, 0x7c, 0xb1, 0xda, 0x7d, 0xb1, 0xd9, 0x7e, 0xb1, 0xd8, 0x7e, 0xb1, 0xd8, 0x7f, 0xb1, 0xd7, + 0x80, 0xb1, 0xd6, 0x81, 0xb0, 0xd6, 0x82, 0xb0, 0xd5, 0x83, 0xb0, 0xd4, 0x84, 0xb0, 0xd3, 0x85, + 0xb0, 0xd3, 0x85, 0xb0, 0xd2, 0x86, 0xb0, 0xd1, 0x87, 0xb0, 0xd1, 0x88, 0xb0, 0xd0, 0x89, 0xb0, + 0xcf, 0x8a, 0xb0, 0xcf, 0x8a, 0xb0, 0xce, 0x8b, 0xaf, 0xcd, 0x8c, 0xaf, 0xcd, 0x8d, 0xaf, 0xcc, + 0x8d, 0xaf, 0xcb, 0x8e, 0xaf, 0xcb, 0x8f, 0xaf, 0xca, 0x90, 0xaf, 0xc9, 0x90, 0xaf, 0xc9, 0x91, + 0xaf, 0xc8, 0x92, 0xaf, 0xc7, 0x93, 0xaf, 0xc7, 0x93, 0xae, 0xc6, 0x94, 0xae, 0xc5, 0x95, 0xae, + 0xc4, 0x95, 0xae, 0xc4, 0x96, 0xae, 0xc3, 0x97, 0xae, 0xc2, 0x97, 0xae, 0xc2, 0x98, 0xae, 0xc1, + 0x99, 0xae, 0xc0, 0x99, 0xae, 0xc0, 0x9a, 0xae, 0xbf, 0x9b, 0xae, 0xbe, 0x9b, 0xad, 0xbe, 0x9c, + 0xad, 0xbd, 0x9d, 0xad, 0xbc, 0x9d, 0xad, 0xbc, 0x9e, 0xad, 0xbb, 0x9e, 0xad, 0xba, 0x9f, 0xad, + 0xba, 0xa0, 0xad, 0xb9, 0xa0, 0xad, 0xb8, 0xa1, 0xad, 0xb8, 0xa1, 0xad, 0xb7, 0xa2, 0xac, 0xb6, + 0xa3, 0xac, 0xb6, 0xa3, 0xac, 0xb5, 0xa4, 0xac, 0xb4, 0xa4, 0xac, 0xb4, 0xa5, 0xac, 0xb3, 0xa5, + 0xac, 0xb2, 0xa6, 0xac, 0xb2, 0xa7, 0xac, 0xb1, 0xa7, 0xac, 0xb0, 0xa8, 0xac, 0xb0, 0xa8, 0xab, + 0xaf, 0xa9, 0xab, 0xae, 0xaa, 0xab, 0xae, 0xaa, 0xab, 0xad, 0xab, 0xab, 0xac, 0xab, 0xab, 0xac, + 0xac, 0xab, 0xab, 0xad, 0xab, 0xab, 0xad, 0xaa, 0xaa, 0xae, 0xaa, 0xaa, 0xaf, 0xaa, 0xa9, 0xaf, + 0xaa, 0xa9, 0xb0, 0xaa, 0xa8, 0xb1, 0xaa, 0xa7, 0xb2, 0xa9, 0xa7, 0xb2, 0xa9, 0xa6, 0xb3, 0xa9, + 0xa6, 0xb4, 0xa9, 0xa5, 0xb4, 0xa9, 0xa5, 0xb5, 0xa9, 0xa4, 0xb6, 0xa8, 0xa4, 0xb6, 0xa8, 0xa3, + 0xb7, 0xa8, 0xa3, 0xb8, 0xa8, 0xa2, 0xb9, 0xa8, 0xa2, 0xb9, 0xa7, 0xa2, 0xba, 0xa7, 0xa1, 0xbb, + 0xa7, 0xa1, 0xbb, 0xa7, 0xa0, 0xbc, 0xa7, 0xa0, 0xbd, 0xa7, 0x9f, 0xbd, 0xa6, 0x9f, 0xbe, 0xa6, + 0x9e, 0xbf, 0xa6, 0x9e, 0xbf, 0xa6, 0x9d, 0xc0, 0xa6, 0x9d, 0xc1, 0xa5, 0x9c, 0xc1, 0xa5, 0x9c, + 0xc2, 0xa5, 0x9b, 0xc3, 0xa5, 0x9b, 0xc3, 0xa5, 0x9a, 0xc4, 0xa4, 0x9a, 0xc5, 0xa4, 0x99, 0xc5, + 0xa4, 0x99, 0xc6, 0xa4, 0x98, 0xc6, 0xa4, 0x98, 0xc7, 0xa3, 0x97, 0xc8, 0xa3, 0x97, 0xc8, 0xa3, + 0x96, 0xc9, 0xa3, 0x96, 0xca, 0xa3, 0x95, 0xca, 0xa2, 0x95, 0xcb, 0xa2, 0x94, 0xcb, 0xa2, 0x94, + 0xcc, 0xa2, 0x93, 0xcd, 0xa2, 0x93, 0xcd, 0xa1, 0x92, 0xce, 0xa1, 0x92, 0xce, 0xa1, 0x91, 0xcf, + 0xa1, 0x91, 0xd0, 0xa1, 0x90, 0xd0, 0xa0, 0x90, 0xd1, 0xa0, 0x90, 0xd1, 0xa0, 0x8f, 0xd2, 0xa0, + 0x8f, 0xd3, 0xa0, 0x8e, 0xd3, 0x9f, 0x8e, 0xd4, 0x9f, 0x8d, 0xd4, 0x9f, 0x8d, 0xd5, 0x9f, 0x8c, + 0xd5, 0x9f, 0x8c, 0xd6, 0x9e, 0x8b, 0xd7, 0x9e, 0x8b, 0xd7, 0x9e, 0x8a, 0xd8, 0x9e, 0x8a, 0xd8, + 0x9e, 0x89, 0xd9, 0x9d, 0x89, 0xd9, 0x9d, 0x88, 0xda, 0x9d, 0x88, 0xdb, 0x9d, 0x87, 0xdb, 0x9c, + 0x87, 0xdc, 0x9c, 0x86, 0xdc, 0x9c, 0x86, 0xdd, 0x9c, 0x85, 0xdd, 0x9c, 0x85, 0xde, 0x9b, 0x84, + 0xde, 0x9b, 0x84, 0xdf, 0x9b, 0x83, 0xe0, 0x9b, 0x83, 0xe0, 0x9a, 0x82, 0xe1, 0x9a, 0x82, 0xe1, + 0x9a, 0x81, 0xe2, 0x9a, 0x81, 0xe2, 0x9a, 0x80, 0xe3, 0x99, 0x80, 0xe3, 0x99, 0x7f, 0xe4, 0x99, + 0x7f, 0xe4, 0x99, 0x7e, 0xe5, 0x98, 0x7e, 0xe5, 0x98, 0x7d, 0xe6, 0x98, 0x7d, 0xe6, 0x98, 0x7d, + 0xe7, 0x98, 0x7c, 0xe7, 0x97, 0x7c, 0xe8, 0x97, 0x7b, 0xe9, 0x97, 0x7b, 0xe9, 0x97, 0x7a, 0xea, + 0x96, 0x7a, 0xea, 0x96, 0x79, 0xeb, 0x96, 0x79, 0xeb, 0x96, 0x78, 0xec, 0x95, 0x78, 0xec, 0x95, + 0x77, 0xed, 0x95, 0x77, 0xed, 0x95, 0x76, 0xee, 0x95, 0x76, 0xee, 0x94, 0x75, 0xef, 0x94, 0x75, + 0xef, 0x94, 0x74, 0xf0, 0x94, 0x74, 0xf0, 0x93, 0x73, 0xf1, 0x93, 0x73, 0xf1, 0x93, 0x72, 0xf2, + 0x93, 0x72, 0xf2, 0x92, 0x71, 0xf3, 0x92, 0x71, 0xf3, 0x92, 0x70, 0xf4, 0x92, 0x70, 0xf4, 0x91, + 0x6f, 0xf5, 0x91, 0x6f, 0xf5, 0x91, 0x6e, 0xf5, 0x91, 0x6e, 0xf6, 0x90, 0x6d, 0xf6, 0x90, 0x6d +}; +static constexpr std::array D12 = { + 0x00, 0xc9, 0xff, 0x00, 0xc8, 0xff, 0x00, 0xc8, 0xfe, 0x00, 0xc8, 0xfe, 0x00, 0xc8, 0xfd, 0x00, + 0xc8, 0xfd, 0x00, 0xc8, 0xfc, 0x0d, 0xc8, 0xfc, 0x17, 0xc8, 0xfb, 0x1d, 0xc8, 0xfa, 0x23, 0xc7, + 0xfa, 0x28, 0xc7, 0xf9, 0x2c, 0xc7, 0xf9, 0x30, 0xc7, 0xf8, 0x33, 0xc7, 0xf8, 0x37, 0xc7, 0xf7, + 0x3a, 0xc7, 0xf7, 0x3d, 0xc7, 0xf6, 0x40, 0xc6, 0xf5, 0x42, 0xc6, 0xf5, 0x45, 0xc6, 0xf4, 0x47, + 0xc6, 0xf4, 0x49, 0xc6, 0xf3, 0x4c, 0xc6, 0xf3, 0x4e, 0xc6, 0xf2, 0x50, 0xc6, 0xf1, 0x52, 0xc5, + 0xf1, 0x54, 0xc5, 0xf0, 0x56, 0xc5, 0xf0, 0x57, 0xc5, 0xef, 0x59, 0xc5, 0xef, 0x5b, 0xc5, 0xee, + 0x5d, 0xc5, 0xee, 0x5e, 0xc5, 0xed, 0x60, 0xc5, 0xec, 0x62, 0xc4, 0xec, 0x63, 0xc4, 0xeb, 0x65, + 0xc4, 0xeb, 0x66, 0xc4, 0xea, 0x68, 0xc4, 0xea, 0x69, 0xc4, 0xe9, 0x6b, 0xc4, 0xe9, 0x6c, 0xc4, + 0xe8, 0x6d, 0xc3, 0xe7, 0x6f, 0xc3, 0xe7, 0x70, 0xc3, 0xe6, 0x71, 0xc3, 0xe6, 0x73, 0xc3, 0xe5, + 0x74, 0xc3, 0xe5, 0x75, 0xc3, 0xe4, 0x76, 0xc3, 0xe4, 0x78, 0xc2, 0xe3, 0x79, 0xc2, 0xe2, 0x7a, + 0xc2, 0xe2, 0x7b, 0xc2, 0xe1, 0x7c, 0xc2, 0xe1, 0x7d, 0xc2, 0xe0, 0x7e, 0xc2, 0xe0, 0x80, 0xc2, + 0xdf, 0x81, 0xc1, 0xdf, 0x82, 0xc1, 0xde, 0x83, 0xc1, 0xdd, 0x84, 0xc1, 0xdd, 0x85, 0xc1, 0xdc, + 0x86, 0xc1, 0xdc, 0x87, 0xc1, 0xdb, 0x88, 0xc1, 0xdb, 0x89, 0xc0, 0xda, 0x8a, 0xc0, 0xda, 0x8b, + 0xc0, 0xd9, 0x8c, 0xc0, 0xd8, 0x8d, 0xc0, 0xd8, 0x8e, 0xc0, 0xd7, 0x8f, 0xc0, 0xd7, 0x90, 0xc0, + 0xd6, 0x91, 0xbf, 0xd6, 0x92, 0xbf, 0xd5, 0x92, 0xbf, 0xd5, 0x93, 0xbf, 0xd4, 0x94, 0xbf, 0xd3, + 0x95, 0xbf, 0xd3, 0x96, 0xbf, 0xd2, 0x97, 0xbf, 0xd2, 0x98, 0xbe, 0xd1, 0x99, 0xbe, 0xd1, 0x99, + 0xbe, 0xd0, 0x9a, 0xbe, 0xd0, 0x9b, 0xbe, 0xcf, 0x9c, 0xbe, 0xcf, 0x9d, 0xbe, 0xce, 0x9e, 0xbe, + 0xcd, 0x9e, 0xbd, 0xcd, 0x9f, 0xbd, 0xcc, 0xa0, 0xbd, 0xcc, 0xa1, 0xbd, 0xcb, 0xa2, 0xbd, 0xcb, + 0xa2, 0xbd, 0xca, 0xa3, 0xbd, 0xca, 0xa4, 0xbd, 0xc9, 0xa5, 0xbc, 0xc8, 0xa5, 0xbc, 0xc8, 0xa6, + 0xbc, 0xc7, 0xa7, 0xbc, 0xc7, 0xa8, 0xbc, 0xc6, 0xa8, 0xbc, 0xc6, 0xa9, 0xbc, 0xc5, 0xaa, 0xbb, + 0xc5, 0xab, 0xbb, 0xc4, 0xab, 0xbb, 0xc3, 0xac, 0xbb, 0xc3, 0xad, 0xbb, 0xc2, 0xad, 0xbb, 0xc2, + 0xae, 0xbb, 0xc1, 0xaf, 0xbb, 0xc1, 0xaf, 0xba, 0xc0, 0xb0, 0xba, 0xc0, 0xb1, 0xba, 0xbf, 0xb2, + 0xba, 0xbf, 0xb2, 0xba, 0xbe, 0xb3, 0xba, 0xbe, 0xb3, 0xba, 0xbd, 0xb4, 0xb9, 0xbd, 0xb5, 0xb9, + 0xbd, 0xb5, 0xb9, 0xbc, 0xb6, 0xb9, 0xbc, 0xb7, 0xb9, 0xbc, 0xb7, 0xb9, 0xbb, 0xb8, 0xb9, 0xbb, + 0xb8, 0xb8, 0xbb, 0xb9, 0xb8, 0xbb, 0xb9, 0xb8, 0xbb, 0xba, 0xb8, 0xbb, 0xba, 0xb8, 0xbb, 0xbb, + 0xb8, 0xbb, 0xbb, 0xb7, 0xbb, 0xbc, 0xb7, 0xbc, 0xbc, 0xb7, 0xbc, 0xbd, 0xb7, 0xbc, 0xbd, 0xb7, + 0xbc, 0xbe, 0xb7, 0xbd, 0xbe, 0xb6, 0xbd, 0xbf, 0xb6, 0xbd, 0xbf, 0xb6, 0xbe, 0xc0, 0xb6, 0xbe, + 0xc0, 0xb6, 0xbe, 0xc0, 0xb6, 0xbf, 0xc1, 0xb5, 0xbf, 0xc1, 0xb5, 0xbf, 0xc2, 0xb5, 0xc0, 0xc2, + 0xb5, 0xc0, 0xc3, 0xb5, 0xc0, 0xc3, 0xb4, 0xc1, 0xc4, 0xb4, 0xc1, 0xc4, 0xb4, 0xc1, 0xc4, 0xb4, + 0xc2, 0xc5, 0xb4, 0xc2, 0xc5, 0xb4, 0xc2, 0xc6, 0xb3, 0xc3, 0xc6, 0xb3, 0xc3, 0xc7, 0xb3, 0xc3, + 0xc7, 0xb3, 0xc4, 0xc7, 0xb3, 0xc4, 0xc8, 0xb2, 0xc4, 0xc8, 0xb2, 0xc5, 0xc9, 0xb2, 0xc5, 0xc9, + 0xb2, 0xc5, 0xca, 0xb2, 0xc6, 0xca, 0xb2, 0xc6, 0xca, 0xb1, 0xc6, 0xcb, 0xb1, 0xc7, 0xcb, 0xb1, + 0xc7, 0xcc, 0xb1, 0xc7, 0xcc, 0xb1, 0xc8, 0xcd, 0xb0, 0xc8, 0xcd, 0xb0, 0xc8, 0xcd, 0xb0, 0xc9, + 0xce, 0xb0, 0xc9, 0xce, 0xb0, 0xc9, 0xcf, 0xaf, 0xca, 0xcf, 0xaf, 0xca, 0xcf, 0xaf, 0xca, 0xd0, + 0xaf, 0xcb, 0xd0, 0xaf, 0xcb, 0xd1, 0xae, 0xcb, 0xd1, 0xae, 0xcc, 0xd2, 0xae, 0xcc, 0xd2, 0xae, + 0xcc, 0xd2, 0xae, 0xcd, 0xd3, 0xad, 0xcd, 0xd3, 0xad, 0xcd, 0xd4, 0xad, 0xce, 0xd4, 0xad, 0xce, + 0xd4, 0xad, 0xce, 0xd5, 0xac, 0xcf, 0xd5, 0xac, 0xcf, 0xd6, 0xac, 0xcf, 0xd6, 0xac, 0xd0, 0xd6, + 0xac, 0xd0, 0xd7, 0xab, 0xd0, 0xd7, 0xab, 0xd1, 0xd8, 0xab, 0xd1, 0xd8, 0xab, 0xd1, 0xd9, 0xab, + 0xd2, 0xd9, 0xaa, 0xd2, 0xd9, 0xaa, 0xd2, 0xda, 0xaa, 0xd3, 0xda, 0xaa, 0xd3, 0xdb, 0xa9, 0xd4, + 0xdb, 0xa9, 0xd4, 0xdb, 0xa9, 0xd4, 0xdc, 0xa9, 0xd5, 0xdc, 0xa9, 0xd5, 0xdd, 0xa8, 0xd5, 0xdd, + 0xa8, 0xd6, 0xdd, 0xa8, 0xd6, 0xde, 0xa8, 0xd6, 0xde, 0xa8, 0xd7, 0xdf, 0xa7, 0xd7, 0xdf, 0xa7, + 0xd7, 0xdf, 0xa7, 0xd8, 0xe0, 0xa7, 0xd8, 0xe0, 0xa6, 0xd8, 0xe1, 0xa6, 0xd9, 0xe1, 0xa6, 0xd9, + 0xe1, 0xa6, 0xd9, 0xe2, 0xa6, 0xda, 0xe2, 0xa5, 0xda, 0xe3, 0xa5, 0xda, 0xe3, 0xa5, 0xdb, 0xe3, + 0xa5, 0xdb, 0xe4, 0xa4, 0xdb, 0xe4, 0xa4, 0xdc, 0xe4, 0xa4, 0xdc, 0xe5, 0xa4, 0xdc, 0xe5, 0xa4, + 0xdd, 0xe6, 0xa3, 0xdd, 0xe6, 0xa3, 0xdd, 0xe6, 0xa3, 0xde, 0xe7, 0xa3, 0xde, 0xe7, 0xa2, 0xde, + 0xe8, 0xa2, 0xdf, 0xe8, 0xa2, 0xdf, 0xe8, 0xa2, 0xdf, 0xe9, 0xa1, 0xe0, 0xe9, 0xa1, 0xe0, 0xea, + 0xa1, 0xe0, 0xea, 0xa1, 0xe1, 0xea, 0xa0, 0xe1, 0xeb, 0xa0, 0xe1, 0xeb, 0xa0, 0xe2, 0xeb, 0xa0, + 0xe2, 0xec, 0x9f, 0xe2, 0xec, 0x9f, 0xe3, 0xed, 0x9f, 0xe3, 0xed, 0x9f, 0xe3, 0xed, 0x9e, 0xe4 +}; +static constexpr std::array D13 = { + 0x11, 0x2d, 0x68, 0x12, 0x2e, 0x6a, 0x13, 0x2f, 0x6c, 0x14, 0x31, 0x6e, 0x15, 0x32, 0x70, 0x16, + 0x33, 0x73, 0x17, 0x34, 0x75, 0x18, 0x36, 0x77, 0x19, 0x37, 0x79, 0x1a, 0x38, 0x7b, 0x1b, 0x39, + 0x7d, 0x1c, 0x3b, 0x7f, 0x1d, 0x3c, 0x82, 0x1e, 0x3d, 0x84, 0x1f, 0x3f, 0x86, 0x20, 0x40, 0x88, + 0x21, 0x41, 0x8a, 0x22, 0x43, 0x8c, 0x23, 0x44, 0x8e, 0x24, 0x45, 0x90, 0x25, 0x47, 0x93, 0x25, + 0x48, 0x95, 0x26, 0x49, 0x97, 0x27, 0x4b, 0x99, 0x28, 0x4c, 0x9b, 0x29, 0x4e, 0x9d, 0x2a, 0x4f, + 0x9f, 0x2a, 0x51, 0xa1, 0x2b, 0x52, 0xa3, 0x2c, 0x53, 0xa5, 0x2d, 0x55, 0xa8, 0x2d, 0x56, 0xaa, + 0x2e, 0x58, 0xac, 0x2f, 0x59, 0xae, 0x2f, 0x5b, 0xb0, 0x30, 0x5c, 0xb2, 0x31, 0x5e, 0xb4, 0x31, + 0x5f, 0xb6, 0x32, 0x61, 0xb8, 0x32, 0x62, 0xba, 0x33, 0x64, 0xbc, 0x33, 0x65, 0xbe, 0x34, 0x67, + 0xc0, 0x34, 0x69, 0xc2, 0x35, 0x6a, 0xc3, 0x35, 0x6c, 0xc5, 0x36, 0x6d, 0xc7, 0x36, 0x6f, 0xc9, + 0x36, 0x71, 0xcb, 0x36, 0x72, 0xcd, 0x36, 0x74, 0xcf, 0x36, 0x76, 0xd0, 0x37, 0x77, 0xd2, 0x37, + 0x79, 0xd4, 0x36, 0x7b, 0xd6, 0x36, 0x7d, 0xd7, 0x36, 0x7e, 0xd9, 0x36, 0x80, 0xdb, 0x35, 0x82, + 0xdc, 0x35, 0x84, 0xde, 0x35, 0x86, 0xdf, 0x34, 0x87, 0xe1, 0x34, 0x89, 0xe2, 0x33, 0x8b, 0xe4, + 0x33, 0x8d, 0xe5, 0x32, 0x8f, 0xe6, 0x32, 0x91, 0xe7, 0x32, 0x92, 0xe9, 0x32, 0x94, 0xea, 0x32, + 0x96, 0xeb, 0x32, 0x98, 0xec, 0x33, 0x9a, 0xed, 0x33, 0x9b, 0xee, 0x34, 0x9d, 0xef, 0x36, 0x9f, + 0xf0, 0x37, 0xa1, 0xf1, 0x39, 0xa3, 0xf2, 0x3b, 0xa4, 0xf3, 0x3d, 0xa6, 0xf4, 0x40, 0xa8, 0xf5, + 0x42, 0xa9, 0xf5, 0x45, 0xab, 0xf6, 0x48, 0xad, 0xf7, 0x4b, 0xaf, 0xf7, 0x4e, 0xb0, 0xf8, 0x51, + 0xb2, 0xf8, 0x54, 0xb3, 0xf9, 0x57, 0xb5, 0xf9, 0x5b, 0xb7, 0xfa, 0x5e, 0xb8, 0xfa, 0x62, 0xba, + 0xfa, 0x65, 0xbb, 0xfb, 0x69, 0xbd, 0xfb, 0x6d, 0xbf, 0xfb, 0x71, 0xc0, 0xfb, 0x74, 0xc2, 0xfb, + 0x78, 0xc3, 0xfb, 0x7c, 0xc5, 0xfc, 0x80, 0xc6, 0xfb, 0x84, 0xc8, 0xfb, 0x88, 0xc9, 0xfb, 0x8c, + 0xca, 0xfb, 0x90, 0xcc, 0xfb, 0x94, 0xcd, 0xfb, 0x98, 0xcf, 0xfb, 0x9c, 0xd0, 0xfa, 0xa0, 0xd2, + 0xfa, 0xa4, 0xd3, 0xfa, 0xa7, 0xd4, 0xf9, 0xab, 0xd6, 0xf9, 0xaf, 0xd7, 0xf9, 0xb3, 0xd9, 0xf8, + 0xb7, 0xda, 0xf8, 0xbb, 0xdb, 0xf7, 0xbe, 0xdd, 0xf7, 0xc2, 0xde, 0xf7, 0xc6, 0xdf, 0xf6, 0xc9, + 0xe1, 0xf6, 0xcd, 0xe2, 0xf5, 0xd0, 0xe3, 0xf5, 0xd3, 0xe5, 0xf4, 0xd6, 0xe6, 0xf3, 0xd9, 0xe7, + 0xf3, 0xdb, 0xe8, 0xf2, 0xdd, 0xe9, 0xf1, 0xde, 0xea, 0xf0, 0xdf, 0xea, 0xef, 0xdf, 0xeb, 0xee, + 0xdf, 0xeb, 0xec, 0xde, 0xeb, 0xeb, 0xdd, 0xeb, 0xe9, 0xdb, 0xeb, 0xe7, 0xd8, 0xea, 0xe6, 0xd5, + 0xea, 0xe4, 0xd2, 0xe9, 0xe2, 0xcf, 0xe8, 0xe0, 0xcb, 0xe7, 0xde, 0xc7, 0xe6, 0xdc, 0xc3, 0xe5, + 0xda, 0xbf, 0xe4, 0xd8, 0xbb, 0xe3, 0xd6, 0xb7, 0xe2, 0xd4, 0xb3, 0xe1, 0xd2, 0xaf, 0xe0, 0xd1, + 0xab, 0xdf, 0xcf, 0xa6, 0xde, 0xcd, 0xa2, 0xdd, 0xcb, 0x9e, 0xdc, 0xc9, 0x9a, 0xda, 0xc7, 0x96, + 0xd9, 0xc5, 0x91, 0xd8, 0xc3, 0x8d, 0xd7, 0xc1, 0x89, 0xd6, 0xbf, 0x85, 0xd5, 0xbd, 0x81, 0xd3, + 0xbb, 0x7d, 0xd2, 0xb9, 0x79, 0xd1, 0xb6, 0x75, 0xd0, 0xb4, 0x71, 0xce, 0xb2, 0x6d, 0xcd, 0xb0, + 0x69, 0xcc, 0xae, 0x65, 0xca, 0xac, 0x62, 0xc9, 0xa9, 0x5e, 0xc8, 0xa7, 0x5a, 0xc6, 0xa5, 0x57, + 0xc5, 0xa3, 0x53, 0xc4, 0xa0, 0x50, 0xc2, 0x9e, 0x4d, 0xc1, 0x9c, 0x49, 0xbf, 0x99, 0x46, 0xbe, + 0x97, 0x43, 0xbc, 0x94, 0x40, 0xbb, 0x92, 0x3e, 0xb9, 0x8f, 0x3b, 0xb8, 0x8d, 0x38, 0xb6, 0x8a, + 0x36, 0xb5, 0x88, 0x33, 0xb3, 0x85, 0x31, 0xb2, 0x83, 0x2f, 0xb0, 0x80, 0x2d, 0xaf, 0x7d, 0x2c, + 0xad, 0x7b, 0x2a, 0xac, 0x78, 0x29, 0xaa, 0x75, 0x28, 0xa8, 0x73, 0x27, 0xa7, 0x70, 0x26, 0xa5, + 0x6d, 0x25, 0xa4, 0x6b, 0x25, 0xa2, 0x68, 0x25, 0xa0, 0x65, 0x24, 0x9f, 0x62, 0x24, 0x9d, 0x60, + 0x24, 0x9b, 0x5d, 0x24, 0x9a, 0x5a, 0x24, 0x98, 0x58, 0x24, 0x96, 0x55, 0x24, 0x95, 0x53, 0x23, + 0x93, 0x50, 0x23, 0x92, 0x4e, 0x23, 0x90, 0x4c, 0x23, 0x8e, 0x49, 0x22, 0x8d, 0x47, 0x22, 0x8b, + 0x45, 0x22, 0x89, 0x43, 0x21, 0x88, 0x41, 0x21, 0x86, 0x3f, 0x20, 0x85, 0x3d, 0x20, 0x83, 0x3b, + 0x1f, 0x81, 0x39, 0x1f, 0x80, 0x37, 0x1e, 0x7e, 0x36, 0x1e, 0x7d, 0x34, 0x1d, 0x7b, 0x32, 0x1c, + 0x79, 0x31, 0x1c, 0x78, 0x2f, 0x1b, 0x76, 0x2d, 0x1a, 0x75, 0x2c, 0x1a, 0x73, 0x2a, 0x19, 0x71, + 0x29, 0x18, 0x70, 0x27, 0x18, 0x6e, 0x26, 0x17, 0x6d, 0x25, 0x16, 0x6b, 0x23, 0x16, 0x6a, 0x22, + 0x15, 0x68, 0x20, 0x14, 0x66, 0x1f, 0x13, 0x65, 0x1e, 0x12, 0x63, 0x1d, 0x12, 0x62, 0x1b, 0x11, + 0x60, 0x1a, 0x10, 0x5f, 0x19, 0x0f, 0x5d, 0x18, 0x0e, 0x5c, 0x17, 0x0e, 0x5a, 0x16, 0x0d, 0x59, + 0x15, 0x0c, 0x57, 0x13, 0x0b, 0x56, 0x12, 0x0a, 0x54, 0x11, 0x09, 0x53, 0x10, 0x08, 0x51, 0x0f, + 0x08, 0x50, 0x0e, 0x07, 0x4e, 0x0d, 0x06, 0x4d, 0x0d, 0x05, 0x4b, 0x0c, 0x05, 0x4a, 0x0b, 0x04, + 0x48, 0x0a, 0x03, 0x47, 0x09, 0x03, 0x45, 0x08, 0x02, 0x44, 0x07, 0x02, 0x42, 0x07, 0x01, 0x41, + 0x06, 0x01, 0x3f, 0x05, 0x01, 0x3e, 0x04, 0x00, 0x3c, 0x03, 0x00, 0x3b, 0x02, 0x00, 0x3a, 0x02 +}; - // rainbow - static constexpr std::array R1 = {0x00,0x30,0xf5,0x00,0x34,0xf2,0x00,0x37,0xee,0x00,0x3b,0xeb,0x03,0x3e,0xe7,0x09,0x42,0xe4,0x0e,0x45,0xe1,0x12,0x48,0xdd,0x14,0x4a,0xda,0x16,0x4d,0xd6,0x17,0x50,0xd3,0x18,0x52,0xcf,0x19,0x55,0xcc,0x19,0x57,0xc8,0x19,0x5a,0xc5,0x19,0x5c,0xc1,0x19,0x5e,0xbe,0x19,0x60,0xbb,0x18,0x63,0xb7,0x18,0x65,0xb4,0x18,0x67,0xb1,0x17,0x69,0xad,0x17,0x6a,0xaa,0x18,0x6c,0xa7,0x18,0x6e,0xa4,0x19,0x70,0xa0,0x1b,0x71,0x9d,0x1c,0x73,0x9a,0x1e,0x75,0x97,0x20,0x76,0x94,0x22,0x78,0x91,0x24,0x79,0x8e,0x27,0x7a,0x8b,0x29,0x7c,0x88,0x2b,0x7d,0x85,0x2d,0x7e,0x82,0x2f,0x80,0x7f,0x31,0x81,0x7c,0x33,0x82,0x79,0x35,0x84,0x76,0x36,0x85,0x73,0x38,0x86,0x70,0x39,0x88,0x6d,0x3a,0x89,0x6a,0x3b,0x8a,0x67,0x3c,0x8b,0x63,0x3d,0x8d,0x60,0x3e,0x8e,0x5d,0x3e,0x8f,0x5a,0x3f,0x91,0x57,0x3f,0x92,0x53,0x40,0x93,0x50,0x40,0x95,0x4d,0x40,0x96,0x4a,0x41,0x97,0x46,0x41,0x99,0x43,0x41,0x9a,0x3f,0x41,0x9b,0x3c,0x42,0x9c,0x38,0x42,0x9e,0x35,0x43,0x9f,0x32,0x44,0xa0,0x2e,0x45,0xa1,0x2b,0x46,0xa2,0x28,0x47,0xa3,0x25,0x49,0xa4,0x22,0x4b,0xa5,0x1f,0x4d,0xa6,0x1c,0x4f,0xa7,0x1a,0x52,0xa8,0x18,0x54,0xa9,0x16,0x57,0xaa,0x14,0x5a,0xab,0x13,0x5d,0xac,0x12,0x60,0xad,0x11,0x63,0xad,0x11,0x66,0xae,0x10,0x69,0xaf,0x10,0x6c,0xb0,0x10,0x6f,0xb0,0x10,0x72,0xb1,0x11,0x75,0xb2,0x11,0x79,0xb3,0x11,0x7c,0xb3,0x12,0x7f,0xb4,0x12,0x82,0xb5,0x13,0x84,0xb6,0x13,0x87,0xb6,0x14,0x8a,0xb7,0x14,0x8d,0xb8,0x14,0x90,0xb8,0x15,0x93,0xb9,0x15,0x96,0xba,0x16,0x99,0xba,0x16,0x9b,0xbb,0x17,0x9e,0xbc,0x17,0xa1,0xbc,0x18,0xa4,0xbd,0x18,0xa6,0xbe,0x19,0xa9,0xbe,0x19,0xac,0xbf,0x19,0xaf,0xc0,0x1a,0xb1,0xc0,0x1a,0xb4,0xc1,0x1b,0xb7,0xc2,0x1b,0xba,0xc2,0x1c,0xbc,0xc3,0x1c,0xbf,0xc3,0x1d,0xc2,0xc4,0x1d,0xc4,0xc5,0x1e,0xc7,0xc5,0x1e,0xca,0xc6,0x1e,0xcc,0xc7,0x1f,0xcf,0xc7,0x1f,0xd2,0xc8,0x20,0xd4,0xc8,0x20,0xd7,0xc9,0x21,0xd9,0xc9,0x21,0xdc,0xca,0x22,0xdf,0xca,0x22,0xe1,0xca,0x22,0xe3,0xcb,0x23,0xe6,0xcb,0x23,0xe8,0xcb,0x23,0xea,0xcb,0x24,0xec,0xcb,0x24,0xee,0xcb,0x24,0xf0,0xcb,0x24,0xf1,0xca,0x24,0xf3,0xca,0x24,0xf4,0xc9,0x24,0xf5,0xc8,0x24,0xf6,0xc8,0x24,0xf7,0xc7,0x24,0xf8,0xc5,0x24,0xf8,0xc4,0x24,0xf9,0xc3,0x24,0xf9,0xc2,0x23,0xf9,0xc0,0x23,0xfa,0xbf,0x23,0xfa,0xbe,0x23,0xfa,0xbc,0x22,0xfa,0xbb,0x22,0xfa,0xb9,0x22,0xfa,0xb8,0x21,0xfa,0xb6,0x21,0xfa,0xb4,0x21,0xfa,0xb3,0x20,0xf9,0xb1,0x20,0xf9,0xb0,0x20,0xf9,0xae,0x1f,0xf9,0xad,0x1f,0xf9,0xab,0x1f,0xf9,0xa9,0x1e,0xf9,0xa8,0x1e,0xf9,0xa6,0x1e,0xf8,0xa5,0x1d,0xf8,0xa3,0x1d,0xf8,0xa1,0x1d,0xf8,0xa0,0x1d,0xf8,0x9e,0x1c,0xf8,0x9d,0x1c,0xf8,0x9b,0x1c,0xf7,0x99,0x1b,0xf7,0x98,0x1b,0xf7,0x96,0x1b,0xf7,0x94,0x1a,0xf7,0x93,0x1a,0xf6,0x91,0x1a,0xf6,0x8f,0x1a,0xf6,0x8e,0x19,0xf6,0x8c,0x19,0xf6,0x8a,0x19,0xf5,0x89,0x18,0xf5,0x87,0x18,0xf5,0x85,0x18,0xf5,0x84,0x18,0xf4,0x82,0x17,0xf4,0x80,0x17,0xf4,0x7f,0x17,0xf4,0x7d,0x17,0xf4,0x7b,0x16,0xf3,0x79,0x16,0xf3,0x77,0x16,0xf3,0x76,0x16,0xf3,0x74,0x15,0xf2,0x72,0x15,0xf2,0x70,0x15,0xf2,0x6e,0x15,0xf1,0x6d,0x15,0xf1,0x6b,0x15,0xf1,0x69,0x15,0xf1,0x67,0x15,0xf0,0x65,0x15,0xf0,0x64,0x16,0xf0,0x62,0x16,0xf0,0x60,0x17,0xf0,0x5f,0x18,0xf0,0x5d,0x1a,0xf0,0x5c,0x1b,0xf0,0x5a,0x1d,0xf0,0x59,0x1f,0xf0,0x58,0x21,0xf0,0x57,0x24,0xf0,0x57,0x26,0xf1,0x56,0x29,0xf1,0x56,0x2c,0xf2,0x56,0x2f,0xf2,0x56,0x33,0xf3,0x56,0x36,0xf3,0x57,0x3a,0xf4,0x58,0x3e,0xf5,0x58,0x41,0xf5,0x59,0x45,0xf6,0x5a,0x49,0xf7,0x5b,0x4d,0xf7,0x5c,0x52,0xf8,0x5e,0x56,0xf9,0x5f,0x5a,0xf9,0x60,0x5e,0xfa,0x61,0x62,0xfb,0x63,0x66,0xfb,0x64,0x6a,0xfc,0x65,0x6f,0xfc,0x67,0x73,0xfd,0x68,0x77,0xfd,0x69,0x7b,0xfe,0x6b,0x80,0xfe,0x6c,0x84,0xff,0x6d,0x88,0xff,0x6f,0x8c,0xff,0x70,0x91,0xff,0x72,0x95,0xff,0x73,0x99,0xff,0x74,0x9d,0xff,0x76,0xa2,0xff,0x77,0xa6,0xff,0x78,0xaa,0xff,0x7a,0xaf,0xff,0x7b,0xb3,0xff,0x7d,0xb7,0xff,0x7e,0xbc,0xff,0x7f,0xc0,0xff,0x81,0xc4,0xff,0x82,0xc9,0xff,0x84,0xcd,0xff,0x85,0xd2,0xff,0x86,0xd6,0xff,0x88,0xdb,0xff,0x89,0xdf,0xff,0x8b,0xe3,0xff,0x8c,0xe8,0xff,0x8d,0xec,0xfe,0x8f,0xf1,0xfe,0x90,0xf5,0xfd,0x92,0xfa}; - static constexpr std::array R2 = {0x00,0x34,0xf5,0x00,0x37,0xf3,0x00,0x3a,0xf0,0x00,0x3c,0xed,0x00,0x3f,0xea,0x00,0x41,0xe7,0x00,0x44,0xe5,0x00,0x46,0xe2,0x00,0x48,0xdf,0x00,0x4a,0xdc,0x00,0x4d,0xd9,0x00,0x4f,0xd6,0x00,0x51,0xd4,0x00,0x53,0xd1,0x00,0x55,0xce,0x00,0x57,0xcb,0x00,0x59,0xc9,0x00,0x5a,0xc6,0x00,0x5c,0xc3,0x00,0x5e,0xc0,0x00,0x60,0xbd,0x00,0x62,0xbb,0x00,0x63,0xb8,0x00,0x65,0xb5,0x00,0x67,0xb2,0x00,0x68,0xb0,0x00,0x6a,0xad,0x00,0x6c,0xaa,0x00,0x6d,0xa7,0x00,0x6f,0xa5,0x00,0x70,0xa2,0x00,0x71,0xa0,0x00,0x73,0x9d,0x00,0x74,0x9a,0x00,0x75,0x98,0x01,0x76,0x95,0x08,0x77,0x93,0x0e,0x78,0x91,0x14,0x7a,0x8e,0x18,0x7b,0x8c,0x1c,0x7c,0x89,0x20,0x7d,0x87,0x23,0x7e,0x85,0x26,0x7f,0x82,0x29,0x80,0x80,0x2b,0x81,0x7e,0x2d,0x82,0x7b,0x2f,0x83,0x79,0x31,0x84,0x76,0x33,0x85,0x74,0x34,0x86,0x72,0x35,0x87,0x6f,0x37,0x88,0x6d,0x38,0x89,0x6a,0x39,0x8a,0x68,0x3a,0x8b,0x65,0x3b,0x8c,0x63,0x3b,0x8d,0x60,0x3c,0x8e,0x5e,0x3d,0x8f,0x5b,0x3d,0x90,0x58,0x3e,0x91,0x56,0x3e,0x92,0x53,0x3e,0x93,0x50,0x3f,0x94,0x4e,0x3f,0x95,0x4b,0x3f,0x96,0x48,0x3f,0x98,0x45,0x3f,0x99,0x42,0x3f,0x9a,0x3f,0x3f,0x9b,0x3c,0x3f,0x9c,0x39,0x3f,0x9d,0x35,0x3f,0x9e,0x32,0x3f,0x9f,0x2f,0x3f,0xa0,0x2b,0x3f,0xa1,0x28,0x40,0xa2,0x24,0x40,0xa3,0x21,0x41,0xa4,0x1e,0x42,0xa5,0x1b,0x44,0xa6,0x18,0x46,0xa6,0x16,0x48,0xa7,0x14,0x4a,0xa8,0x12,0x4d,0xa9,0x10,0x4f,0xa9,0x10,0x52,0xaa,0x0f,0x55,0xab,0x0f,0x57,0xab,0x0f,0x5a,0xac,0x0f,0x5d,0xac,0x0f,0x60,0xad,0x10,0x62,0xae,0x10,0x65,0xae,0x11,0x68,0xaf,0x11,0x6a,0xaf,0x12,0x6d,0xb0,0x12,0x6f,0xb1,0x12,0x72,0xb1,0x13,0x74,0xb2,0x13,0x77,0xb2,0x14,0x79,0xb3,0x14,0x7c,0xb4,0x15,0x7e,0xb4,0x15,0x81,0xb5,0x16,0x83,0xb5,0x16,0x85,0xb6,0x17,0x88,0xb6,0x17,0x8a,0xb7,0x18,0x8c,0xb7,0x18,0x8f,0xb8,0x19,0x91,0xb9,0x19,0x93,0xb9,0x1a,0x96,0xba,0x1a,0x98,0xba,0x1a,0x9a,0xbb,0x1b,0x9c,0xbb,0x1b,0x9f,0xbc,0x1c,0xa1,0xbc,0x1c,0xa3,0xbd,0x1d,0xa5,0xbe,0x1d,0xa8,0xbe,0x1e,0xaa,0xbf,0x1e,0xac,0xbf,0x1f,0xae,0xc0,0x1f,0xb0,0xc0,0x1f,0xb3,0xc1,0x20,0xb5,0xc1,0x20,0xb7,0xc2,0x21,0xb9,0xc2,0x21,0xbb,0xc3,0x22,0xbe,0xc3,0x22,0xc0,0xc4,0x23,0xc2,0xc4,0x23,0xc4,0xc5,0x23,0xc6,0xc5,0x24,0xc8,0xc6,0x24,0xcb,0xc6,0x25,0xcd,0xc7,0x25,0xcf,0xc7,0x26,0xd1,0xc8,0x26,0xd3,0xc8,0x27,0xd5,0xc9,0x27,0xd7,0xc9,0x27,0xda,0xca,0x28,0xdc,0xca,0x28,0xde,0xcb,0x29,0xe0,0xcb,0x29,0xe2,0xcb,0x2a,0xe4,0xcc,0x2a,0xe6,0xcc,0x2b,0xe8,0xcd,0x2b,0xea,0xcd,0x2b,0xec,0xcd,0x2c,0xee,0xcd,0x2c,0xf0,0xcd,0x2c,0xf2,0xcd,0x2c,0xf4,0xcd,0x2c,0xf5,0xcd,0x2c,0xf6,0xcc,0x2c,0xf8,0xcc,0x2c,0xf9,0xcb,0x2c,0xf9,0xca,0x2c,0xfa,0xc9,0x2b,0xfb,0xc8,0x2b,0xfb,0xc7,0x2a,0xfc,0xc5,0x2a,0xfc,0xc4,0x29,0xfc,0xc3,0x29,0xfc,0xc2,0x28,0xfd,0xc0,0x28,0xfd,0xbf,0x27,0xfd,0xbe,0x27,0xfd,0xbc,0x26,0xfd,0xbb,0x26,0xfd,0xba,0x25,0xfe,0xb8,0x25,0xfe,0xb7,0x24,0xfe,0xb5,0x23,0xfe,0xb4,0x23,0xfe,0xb3,0x22,0xfe,0xb1,0x22,0xfe,0xb0,0x21,0xfe,0xaf,0x21,0xff,0xad,0x20,0xff,0xac,0x1f,0xff,0xaa,0x1f,0xff,0xa9,0x1e,0xff,0xa8,0x1e,0xff,0xa6,0x1d,0xff,0xa5,0x1d,0xff,0xa3,0x1c,0xff,0xa2,0x1c,0xff,0xa1,0x1b,0xff,0x9f,0x1a,0xff,0x9e,0x1a,0xff,0x9c,0x19,0xff,0x9b,0x19,0xff,0x99,0x18,0xff,0x98,0x18,0xff,0x96,0x17,0xff,0x95,0x16,0xff,0x93,0x16,0xff,0x92,0x15,0xff,0x91,0x15,0xff,0x8f,0x14,0xff,0x8e,0x14,0xff,0x8c,0x13,0xff,0x8b,0x12,0xff,0x89,0x12,0xff,0x88,0x11,0xff,0x86,0x11,0xff,0x84,0x10,0xff,0x83,0x10,0xff,0x81,0x0f,0xff,0x80,0x0e,0xff,0x7e,0x0e,0xff,0x7d,0x0d,0xff,0x7b,0x0d,0xff,0x79,0x0c,0xff,0x78,0x0b,0xff,0x76,0x0b,0xff,0x74,0x0a,0xff,0x73,0x0a,0xff,0x71,0x09,0xff,0x6f,0x08,0xff,0x6e,0x08,0xff,0x6c,0x07,0xff,0x6a,0x07,0xff,0x69,0x06,0xff,0x67,0x06,0xff,0x65,0x05,0xff,0x63,0x05,0xff,0x61,0x04,0xff,0x5f,0x04,0xff,0x5e,0x03,0xff,0x5c,0x03,0xff,0x5a,0x03,0xff,0x58,0x02,0xfe,0x56,0x02,0xfe,0x54,0x02,0xfe,0x52,0x01,0xfe,0x4f,0x01,0xfe,0x4d,0x01,0xfe,0x4b,0x00,0xfe,0x49,0x00,0xfe,0x46,0x00,0xfe,0x44,0x00,0xfd,0x41,0x00,0xfd,0x3f,0x00,0xfd,0x3c,0x00,0xfd,0x39,0x00,0xfd,0x36,0x00,0xfd,0x33,0x00,0xfd,0x30,0x00}; - static constexpr std::array R3 = {0x08,0x5c,0xf8,0x0f,0x5f,0xf4,0x13,0x61,0xf1,0x17,0x63,0xed,0x19,0x65,0xe9,0x1b,0x67,0xe5,0x1c,0x6a,0xe1,0x1d,0x6c,0xde,0x1d,0x6e,0xda,0x1e,0x70,0xd6,0x1d,0x72,0xd2,0x1d,0x74,0xce,0x1c,0x75,0xcb,0x1b,0x77,0xc7,0x19,0x79,0xc3,0x18,0x7b,0xbf,0x16,0x7d,0xbb,0x14,0x7e,0xb8,0x13,0x80,0xb4,0x12,0x82,0xb0,0x12,0x83,0xac,0x13,0x85,0xa8,0x14,0x86,0xa4,0x17,0x88,0xa0,0x1a,0x89,0x9c,0x1d,0x8a,0x98,0x20,0x8c,0x93,0x23,0x8d,0x8f,0x27,0x8e,0x8b,0x2a,0x8f,0x86,0x2d,0x90,0x82,0x2f,0x92,0x7e,0x31,0x93,0x79,0x34,0x94,0x75,0x35,0x95,0x70,0x37,0x96,0x6c,0x38,0x97,0x67,0x39,0x98,0x62,0x3a,0x9a,0x5e,0x3b,0x9b,0x59,0x3b,0x9c,0x54,0x3b,0x9d,0x50,0x3c,0x9e,0x4b,0x3c,0x9f,0x46,0x3c,0xa0,0x42,0x3d,0xa1,0x3d,0x3d,0xa2,0x39,0x3e,0xa3,0x35,0x3f,0xa4,0x31,0x41,0xa5,0x2e,0x42,0xa6,0x2b,0x44,0xa7,0x28,0x47,0xa8,0x26,0x49,0xa8,0x24,0x4c,0xa9,0x22,0x4e,0xaa,0x21,0x51,0xaa,0x20,0x54,0xab,0x20,0x57,0xac,0x1f,0x5a,0xac,0x1f,0x5c,0xad,0x1e,0x5f,0xae,0x1e,0x62,0xae,0x1e,0x65,0xaf,0x1e,0x67,0xaf,0x1d,0x6a,0xb0,0x1d,0x6c,0xb1,0x1d,0x6f,0xb1,0x1d,0x72,0xb2,0x1d,0x74,0xb2,0x1d,0x77,0xb3,0x1c,0x79,0xb4,0x1c,0x7b,0xb4,0x1c,0x7e,0xb5,0x1c,0x80,0xb5,0x1b,0x83,0xb6,0x1b,0x85,0xb6,0x1b,0x87,0xb7,0x1b,0x8a,0xb8,0x1b,0x8c,0xb8,0x1a,0x8e,0xb9,0x1a,0x91,0xb9,0x1a,0x93,0xba,0x1a,0x95,0xba,0x19,0x97,0xbb,0x19,0x9a,0xbb,0x19,0x9c,0xbc,0x19,0x9e,0xbd,0x18,0xa0,0xbd,0x18,0xa3,0xbe,0x18,0xa5,0xbe,0x18,0xa7,0xbf,0x17,0xa9,0xbf,0x17,0xab,0xc0,0x17,0xae,0xc0,0x16,0xb0,0xc1,0x16,0xb2,0xc1,0x16,0xb4,0xc2,0x15,0xb6,0xc2,0x15,0xb8,0xc3,0x15,0xbb,0xc3,0x14,0xbd,0xc4,0x14,0xbf,0xc5,0x14,0xc1,0xc5,0x13,0xc3,0xc6,0x13,0xc5,0xc6,0x13,0xc7,0xc7,0x12,0xca,0xc7,0x12,0xcc,0xc8,0x12,0xce,0xc8,0x11,0xd0,0xc9,0x11,0xd2,0xc9,0x10,0xd4,0xca,0x10,0xd6,0xca,0x0f,0xd8,0xcb,0x0f,0xdb,0xcb,0x0e,0xdd,0xcb,0x0e,0xdf,0xcc,0x0e,0xe1,0xcc,0x0e,0xe3,0xcd,0x0e,0xe5,0xcd,0x0e,0xe7,0xcd,0x0f,0xe9,0xce,0x10,0xeb,0xce,0x12,0xed,0xce,0x14,0xef,0xcd,0x16,0xf1,0xcd,0x19,0xf3,0xcd,0x1c,0xf4,0xcc,0x1f,0xf6,0xcb,0x23,0xf7,0xca,0x26,0xf8,0xc9,0x29,0xf9,0xc8,0x2d,0xf9,0xc7,0x30,0xfa,0xc6,0x33,0xfa,0xc5,0x36,0xfb,0xc3,0x39,0xfb,0xc2,0x3c,0xfc,0xc0,0x3f,0xfc,0xbf,0x41,0xfc,0xbe,0x44,0xfc,0xbc,0x46,0xfc,0xbb,0x48,0xfd,0xb9,0x4b,0xfd,0xb8,0x4d,0xfd,0xb6,0x4f,0xfd,0xb5,0x51,0xfd,0xb3,0x53,0xfd,0xb2,0x55,0xfe,0xb0,0x57,0xfe,0xaf,0x59,0xfe,0xad,0x5b,0xfe,0xac,0x5d,0xfe,0xaa,0x5f,0xfe,0xa9,0x61,0xfe,0xa7,0x63,0xfe,0xa6,0x65,0xfe,0xa4,0x66,0xfe,0xa3,0x68,0xfe,0xa1,0x6a,0xfe,0xa0,0x6c,0xff,0x9e,0x6d,0xff,0x9d,0x6f,0xff,0x9b,0x71,0xff,0x9a,0x72,0xff,0x98,0x74,0xff,0x97,0x75,0xff,0x95,0x77,0xff,0x93,0x79,0xff,0x92,0x7a,0xff,0x90,0x7c,0xff,0x8f,0x7d,0xff,0x8d,0x7f,0xfe,0x8b,0x80,0xfe,0x8a,0x82,0xfe,0x88,0x84,0xfe,0x86,0x85,0xfe,0x85,0x87,0xfe,0x83,0x88,0xfe,0x81,0x8a,0xfe,0x80,0x8b,0xfe,0x7e,0x8c,0xfe,0x7c,0x8e,0xfe,0x7a,0x8f,0xfd,0x79,0x91,0xfd,0x77,0x92,0xfd,0x75,0x94,0xfd,0x73,0x95,0xfd,0x71,0x97,0xfd,0x70,0x98,0xfd,0x6e,0x99,0xfc,0x6c,0x9b,0xfc,0x6a,0x9c,0xfc,0x68,0x9e,0xfc,0x66,0x9f,0xfc,0x64,0xa0,0xfb,0x62,0xa2,0xfb,0x60,0xa3,0xfb,0x5e,0xa4,0xfb,0x5c,0xa5,0xfa,0x5a,0xa6,0xfa,0x58,0xa7,0xfa,0x56,0xa8,0xfa,0x54,0xa8,0xf9,0x52,0xa8,0xf9,0x50,0xa8,0xf9,0x4e,0xa7,0xf8,0x4c,0xa6,0xf8,0x4a,0xa5,0xf8,0x49,0xa3,0xf7,0x47,0xa1,0xf7,0x46,0x9e,0xf7,0x44,0x9c,0xf6,0x43,0x99,0xf6,0x42,0x96,0xf6,0x40,0x92,0xf5,0x3f,0x8f,0xf5,0x3e,0x8c,0xf4,0x3d,0x88,0xf4,0x3c,0x85,0xf3,0x3a,0x82,0xf3,0x39,0x7e,0xf2,0x38,0x7b,0xf1,0x37,0x78,0xf1,0x36,0x74,0xf0,0x34,0x71,0xf0,0x33,0x6d,0xef,0x32,0x6a,0xee,0x31,0x67,0xee,0x2f,0x63,0xed,0x2e,0x60,0xec,0x2d,0x5d,0xeb,0x2c,0x59,0xeb,0x2a,0x56,0xea,0x29,0x53,0xe9,0x28,0x4f,0xe8,0x26,0x4c,0xe8,0x25,0x49,0xe7,0x24,0x45,0xe6,0x22,0x42,0xe5,0x21,0x3f,0xe4,0x20,0x3b,0xe3,0x1e,0x38,0xe2,0x1d,0x35,0xe2,0x1b,0x31,0xe1,0x1a,0x2e,0xe0,0x18,0x2a,0xdf,0x16,0x26,0xde,0x14,0x23,0xdd,0x13,0x1f,0xdc,0x11,0x1b,0xdb,0x0f,0x17,0xda,0x0c,0x12,0xd9,0x0a,0x0c,0xd8,0x07,0x06,0xd7,0x05,0x00}; - static constexpr std::array R4 = {0x04,0x00,0x6c,0x04,0x00,0x6f,0x04,0x00,0x72,0x04,0x00,0x75,0x04,0x00,0x78,0x04,0x00,0x7b,0x04,0x00,0x7e,0x04,0x00,0x81,0x04,0x00,0x84,0x05,0x00,0x87,0x05,0x00,0x8a,0x05,0x00,0x8d,0x05,0x00,0x91,0x05,0x00,0x94,0x05,0x00,0x97,0x05,0x01,0x9a,0x05,0x01,0x9c,0x05,0x01,0x9f,0x05,0x02,0xa2,0x06,0x02,0xa5,0x06,0x03,0xa7,0x06,0x04,0xaa,0x06,0x06,0xac,0x07,0x07,0xaf,0x07,0x09,0xb1,0x08,0x0b,0xb3,0x08,0x0d,0xb5,0x09,0x0f,0xb7,0x09,0x11,0xb9,0x0a,0x13,0xbb,0x0a,0x15,0xbd,0x0b,0x17,0xbf,0x0b,0x18,0xc1,0x0c,0x1a,0xc3,0x0c,0x1c,0xc5,0x0c,0x1d,0xc7,0x0d,0x1f,0xc9,0x0d,0x20,0xcb,0x0e,0x22,0xcd,0x0e,0x24,0xcf,0x0e,0x25,0xd1,0x0f,0x27,0xd2,0x0f,0x28,0xd4,0x0f,0x2a,0xd6,0x10,0x2b,0xd8,0x10,0x2c,0xda,0x10,0x2e,0xdc,0x10,0x2f,0xde,0x11,0x31,0xe0,0x11,0x32,0xe2,0x11,0x34,0xe4,0x11,0x35,0xe6,0x12,0x37,0xe8,0x12,0x38,0xe9,0x12,0x3a,0xeb,0x13,0x3b,0xed,0x14,0x3d,0xee,0x14,0x3f,0xef,0x15,0x41,0xf0,0x17,0x43,0xf0,0x18,0x45,0xf0,0x19,0x47,0xef,0x1b,0x4a,0xee,0x1c,0x4d,0xed,0x1d,0x50,0xeb,0x1e,0x53,0xe8,0x1f,0x56,0xe5,0x1f,0x59,0xe2,0x20,0x5c,0xde,0x1f,0x5f,0xda,0x1f,0x62,0xd6,0x1d,0x65,0xd2,0x1c,0x68,0xce,0x1a,0x6a,0xca,0x17,0x6d,0xc5,0x14,0x70,0xc1,0x11,0x73,0xbc,0x0d,0x75,0xb8,0x09,0x78,0xb3,0x07,0x7a,0xae,0x05,0x7d,0xaa,0x06,0x7f,0xa5,0x08,0x81,0xa0,0x0c,0x83,0x9b,0x10,0x85,0x96,0x15,0x87,0x90,0x19,0x89,0x8b,0x1d,0x8b,0x85,0x21,0x8d,0x80,0x24,0x8e,0x7a,0x27,0x90,0x74,0x2a,0x92,0x6e,0x2b,0x94,0x68,0x2d,0x95,0x62,0x2e,0x97,0x5c,0x2f,0x99,0x56,0x30,0x9b,0x50,0x30,0x9c,0x4a,0x30,0x9e,0x44,0x31,0xa0,0x3e,0x31,0xa1,0x38,0x32,0xa3,0x32,0x33,0xa4,0x2c,0x35,0xa6,0x27,0x37,0xa7,0x22,0x39,0xa9,0x1d,0x3c,0xaa,0x19,0x3f,0xab,0x15,0x43,0xad,0x11,0x46,0xae,0x0e,0x4a,0xaf,0x0c,0x4e,0xb0,0x0a,0x52,0xb1,0x08,0x56,0xb2,0x08,0x5a,0xb3,0x07,0x5d,0xb4,0x06,0x61,0xb5,0x06,0x65,0xb6,0x06,0x68,0xb7,0x06,0x6c,0xb8,0x06,0x6f,0xba,0x05,0x73,0xbb,0x05,0x76,0xbc,0x05,0x7a,0xbd,0x05,0x7d,0xbe,0x05,0x80,0xbf,0x05,0x83,0xc0,0x05,0x87,0xc1,0x05,0x8a,0xc2,0x04,0x8d,0xc3,0x04,0x90,0xc4,0x04,0x93,0xc5,0x04,0x96,0xc6,0x04,0x9a,0xc7,0x04,0x9d,0xc8,0x04,0xa0,0xc9,0x04,0xa3,0xca,0x04,0xa6,0xcb,0x03,0xa9,0xcc,0x03,0xac,0xcd,0x03,0xaf,0xce,0x03,0xb2,0xcf,0x03,0xb5,0xd0,0x03,0xb8,0xd1,0x03,0xbb,0xd2,0x03,0xbe,0xd3,0x02,0xc1,0xd4,0x02,0xc4,0xd5,0x02,0xc7,0xd6,0x02,0xca,0xd7,0x02,0xcd,0xd8,0x02,0xd0,0xd9,0x02,0xd3,0xd9,0x02,0xd6,0xda,0x02,0xd9,0xdb,0x02,0xdc,0xdc,0x02,0xdf,0xdd,0x02,0xe1,0xde,0x02,0xe4,0xde,0x02,0xe7,0xdf,0x02,0xea,0xdf,0x02,0xec,0xdf,0x02,0xee,0xdf,0x02,0xf0,0xde,0x03,0xf2,0xde,0x03,0xf4,0xdd,0x04,0xf5,0xdc,0x05,0xf7,0xda,0x05,0xf8,0xd9,0x06,0xf8,0xd7,0x07,0xf9,0xd6,0x07,0xfa,0xd4,0x08,0xfa,0xd2,0x09,0xfa,0xd0,0x0a,0xfa,0xce,0x0b,0xfb,0xcc,0x0b,0xfb,0xca,0x0c,0xfb,0xc8,0x0d,0xfb,0xc6,0x0d,0xfb,0xc4,0x0e,0xfb,0xc2,0x0e,0xfb,0xc0,0x0f,0xfb,0xbe,0x0f,0xfb,0xbc,0x10,0xfc,0xba,0x10,0xfc,0xb8,0x11,0xfc,0xb6,0x11,0xfc,0xb4,0x12,0xfc,0xb2,0x12,0xfc,0xb0,0x13,0xfc,0xae,0x13,0xfc,0xac,0x13,0xfc,0xa9,0x14,0xfc,0xa7,0x14,0xfc,0xa5,0x14,0xfc,0xa3,0x15,0xfc,0xa1,0x15,0xfc,0x9f,0x15,0xfc,0x9d,0x15,0xfc,0x9a,0x15,0xfc,0x98,0x16,0xfc,0x96,0x16,0xfc,0x94,0x16,0xfc,0x91,0x16,0xfc,0x8f,0x15,0xfc,0x8d,0x15,0xfc,0x8a,0x15,0xfc,0x88,0x15,0xfc,0x86,0x14,0xfc,0x83,0x14,0xfd,0x80,0x14,0xfd,0x7e,0x13,0xfd,0x7b,0x13,0xfd,0x79,0x13,0xfd,0x76,0x12,0xfe,0x73,0x12,0xfe,0x70,0x11,0xfe,0x6e,0x11,0xfe,0x6b,0x11,0xfe,0x68,0x10,0xfe,0x65,0x10,0xfe,0x62,0x10,0xfe,0x5f,0x0f,0xfe,0x5b,0x0f,0xfe,0x58,0x0f,0xfe,0x55,0x0e,0xfe,0x51,0x0e,0xfe,0x4e,0x0e,0xfe,0x4a,0x0e,0xfe,0x47,0x0e,0xfe,0x43,0x0d,0xfd,0x3f,0x0d,0xfd,0x3c,0x0d,0xfc,0x38,0x0d,0xfb,0x35,0x0d,0xfa,0x32,0x0d,0xf9,0x2f,0x0d,0xf8,0x2c,0x0d,0xf6,0x29,0x0d,0xf5,0x27,0x0d,0xf3,0x24,0x0d,0xf1,0x22,0x0d,0xf0,0x20,0x0d,0xee,0x1f,0x0d,0xec,0x1d,0x0d,0xea,0x1b,0x0d,0xe8,0x19,0x0d,0xe6,0x17,0x0d,0xe4,0x16,0x0d,0xe2,0x14,0x0d,0xe0,0x12,0x0d,0xde,0x10,0x0d,0xdc,0x0d,0x0d,0xdb,0x0b,0x0d,0xd9,0x08,0x0d,0xd7,0x05,0x0d}; +// rainbow +static constexpr std::array R1 = { + 0x00, 0x30, 0xf5, 0x00, 0x34, 0xf2, 0x00, 0x37, 0xee, 0x00, 0x3b, 0xeb, 0x03, 0x3e, 0xe7, 0x09, + 0x42, 0xe4, 0x0e, 0x45, 0xe1, 0x12, 0x48, 0xdd, 0x14, 0x4a, 0xda, 0x16, 0x4d, 0xd6, 0x17, 0x50, + 0xd3, 0x18, 0x52, 0xcf, 0x19, 0x55, 0xcc, 0x19, 0x57, 0xc8, 0x19, 0x5a, 0xc5, 0x19, 0x5c, 0xc1, + 0x19, 0x5e, 0xbe, 0x19, 0x60, 0xbb, 0x18, 0x63, 0xb7, 0x18, 0x65, 0xb4, 0x18, 0x67, 0xb1, 0x17, + 0x69, 0xad, 0x17, 0x6a, 0xaa, 0x18, 0x6c, 0xa7, 0x18, 0x6e, 0xa4, 0x19, 0x70, 0xa0, 0x1b, 0x71, + 0x9d, 0x1c, 0x73, 0x9a, 0x1e, 0x75, 0x97, 0x20, 0x76, 0x94, 0x22, 0x78, 0x91, 0x24, 0x79, 0x8e, + 0x27, 0x7a, 0x8b, 0x29, 0x7c, 0x88, 0x2b, 0x7d, 0x85, 0x2d, 0x7e, 0x82, 0x2f, 0x80, 0x7f, 0x31, + 0x81, 0x7c, 0x33, 0x82, 0x79, 0x35, 0x84, 0x76, 0x36, 0x85, 0x73, 0x38, 0x86, 0x70, 0x39, 0x88, + 0x6d, 0x3a, 0x89, 0x6a, 0x3b, 0x8a, 0x67, 0x3c, 0x8b, 0x63, 0x3d, 0x8d, 0x60, 0x3e, 0x8e, 0x5d, + 0x3e, 0x8f, 0x5a, 0x3f, 0x91, 0x57, 0x3f, 0x92, 0x53, 0x40, 0x93, 0x50, 0x40, 0x95, 0x4d, 0x40, + 0x96, 0x4a, 0x41, 0x97, 0x46, 0x41, 0x99, 0x43, 0x41, 0x9a, 0x3f, 0x41, 0x9b, 0x3c, 0x42, 0x9c, + 0x38, 0x42, 0x9e, 0x35, 0x43, 0x9f, 0x32, 0x44, 0xa0, 0x2e, 0x45, 0xa1, 0x2b, 0x46, 0xa2, 0x28, + 0x47, 0xa3, 0x25, 0x49, 0xa4, 0x22, 0x4b, 0xa5, 0x1f, 0x4d, 0xa6, 0x1c, 0x4f, 0xa7, 0x1a, 0x52, + 0xa8, 0x18, 0x54, 0xa9, 0x16, 0x57, 0xaa, 0x14, 0x5a, 0xab, 0x13, 0x5d, 0xac, 0x12, 0x60, 0xad, + 0x11, 0x63, 0xad, 0x11, 0x66, 0xae, 0x10, 0x69, 0xaf, 0x10, 0x6c, 0xb0, 0x10, 0x6f, 0xb0, 0x10, + 0x72, 0xb1, 0x11, 0x75, 0xb2, 0x11, 0x79, 0xb3, 0x11, 0x7c, 0xb3, 0x12, 0x7f, 0xb4, 0x12, 0x82, + 0xb5, 0x13, 0x84, 0xb6, 0x13, 0x87, 0xb6, 0x14, 0x8a, 0xb7, 0x14, 0x8d, 0xb8, 0x14, 0x90, 0xb8, + 0x15, 0x93, 0xb9, 0x15, 0x96, 0xba, 0x16, 0x99, 0xba, 0x16, 0x9b, 0xbb, 0x17, 0x9e, 0xbc, 0x17, + 0xa1, 0xbc, 0x18, 0xa4, 0xbd, 0x18, 0xa6, 0xbe, 0x19, 0xa9, 0xbe, 0x19, 0xac, 0xbf, 0x19, 0xaf, + 0xc0, 0x1a, 0xb1, 0xc0, 0x1a, 0xb4, 0xc1, 0x1b, 0xb7, 0xc2, 0x1b, 0xba, 0xc2, 0x1c, 0xbc, 0xc3, + 0x1c, 0xbf, 0xc3, 0x1d, 0xc2, 0xc4, 0x1d, 0xc4, 0xc5, 0x1e, 0xc7, 0xc5, 0x1e, 0xca, 0xc6, 0x1e, + 0xcc, 0xc7, 0x1f, 0xcf, 0xc7, 0x1f, 0xd2, 0xc8, 0x20, 0xd4, 0xc8, 0x20, 0xd7, 0xc9, 0x21, 0xd9, + 0xc9, 0x21, 0xdc, 0xca, 0x22, 0xdf, 0xca, 0x22, 0xe1, 0xca, 0x22, 0xe3, 0xcb, 0x23, 0xe6, 0xcb, + 0x23, 0xe8, 0xcb, 0x23, 0xea, 0xcb, 0x24, 0xec, 0xcb, 0x24, 0xee, 0xcb, 0x24, 0xf0, 0xcb, 0x24, + 0xf1, 0xca, 0x24, 0xf3, 0xca, 0x24, 0xf4, 0xc9, 0x24, 0xf5, 0xc8, 0x24, 0xf6, 0xc8, 0x24, 0xf7, + 0xc7, 0x24, 0xf8, 0xc5, 0x24, 0xf8, 0xc4, 0x24, 0xf9, 0xc3, 0x24, 0xf9, 0xc2, 0x23, 0xf9, 0xc0, + 0x23, 0xfa, 0xbf, 0x23, 0xfa, 0xbe, 0x23, 0xfa, 0xbc, 0x22, 0xfa, 0xbb, 0x22, 0xfa, 0xb9, 0x22, + 0xfa, 0xb8, 0x21, 0xfa, 0xb6, 0x21, 0xfa, 0xb4, 0x21, 0xfa, 0xb3, 0x20, 0xf9, 0xb1, 0x20, 0xf9, + 0xb0, 0x20, 0xf9, 0xae, 0x1f, 0xf9, 0xad, 0x1f, 0xf9, 0xab, 0x1f, 0xf9, 0xa9, 0x1e, 0xf9, 0xa8, + 0x1e, 0xf9, 0xa6, 0x1e, 0xf8, 0xa5, 0x1d, 0xf8, 0xa3, 0x1d, 0xf8, 0xa1, 0x1d, 0xf8, 0xa0, 0x1d, + 0xf8, 0x9e, 0x1c, 0xf8, 0x9d, 0x1c, 0xf8, 0x9b, 0x1c, 0xf7, 0x99, 0x1b, 0xf7, 0x98, 0x1b, 0xf7, + 0x96, 0x1b, 0xf7, 0x94, 0x1a, 0xf7, 0x93, 0x1a, 0xf6, 0x91, 0x1a, 0xf6, 0x8f, 0x1a, 0xf6, 0x8e, + 0x19, 0xf6, 0x8c, 0x19, 0xf6, 0x8a, 0x19, 0xf5, 0x89, 0x18, 0xf5, 0x87, 0x18, 0xf5, 0x85, 0x18, + 0xf5, 0x84, 0x18, 0xf4, 0x82, 0x17, 0xf4, 0x80, 0x17, 0xf4, 0x7f, 0x17, 0xf4, 0x7d, 0x17, 0xf4, + 0x7b, 0x16, 0xf3, 0x79, 0x16, 0xf3, 0x77, 0x16, 0xf3, 0x76, 0x16, 0xf3, 0x74, 0x15, 0xf2, 0x72, + 0x15, 0xf2, 0x70, 0x15, 0xf2, 0x6e, 0x15, 0xf1, 0x6d, 0x15, 0xf1, 0x6b, 0x15, 0xf1, 0x69, 0x15, + 0xf1, 0x67, 0x15, 0xf0, 0x65, 0x15, 0xf0, 0x64, 0x16, 0xf0, 0x62, 0x16, 0xf0, 0x60, 0x17, 0xf0, + 0x5f, 0x18, 0xf0, 0x5d, 0x1a, 0xf0, 0x5c, 0x1b, 0xf0, 0x5a, 0x1d, 0xf0, 0x59, 0x1f, 0xf0, 0x58, + 0x21, 0xf0, 0x57, 0x24, 0xf0, 0x57, 0x26, 0xf1, 0x56, 0x29, 0xf1, 0x56, 0x2c, 0xf2, 0x56, 0x2f, + 0xf2, 0x56, 0x33, 0xf3, 0x56, 0x36, 0xf3, 0x57, 0x3a, 0xf4, 0x58, 0x3e, 0xf5, 0x58, 0x41, 0xf5, + 0x59, 0x45, 0xf6, 0x5a, 0x49, 0xf7, 0x5b, 0x4d, 0xf7, 0x5c, 0x52, 0xf8, 0x5e, 0x56, 0xf9, 0x5f, + 0x5a, 0xf9, 0x60, 0x5e, 0xfa, 0x61, 0x62, 0xfb, 0x63, 0x66, 0xfb, 0x64, 0x6a, 0xfc, 0x65, 0x6f, + 0xfc, 0x67, 0x73, 0xfd, 0x68, 0x77, 0xfd, 0x69, 0x7b, 0xfe, 0x6b, 0x80, 0xfe, 0x6c, 0x84, 0xff, + 0x6d, 0x88, 0xff, 0x6f, 0x8c, 0xff, 0x70, 0x91, 0xff, 0x72, 0x95, 0xff, 0x73, 0x99, 0xff, 0x74, + 0x9d, 0xff, 0x76, 0xa2, 0xff, 0x77, 0xa6, 0xff, 0x78, 0xaa, 0xff, 0x7a, 0xaf, 0xff, 0x7b, 0xb3, + 0xff, 0x7d, 0xb7, 0xff, 0x7e, 0xbc, 0xff, 0x7f, 0xc0, 0xff, 0x81, 0xc4, 0xff, 0x82, 0xc9, 0xff, + 0x84, 0xcd, 0xff, 0x85, 0xd2, 0xff, 0x86, 0xd6, 0xff, 0x88, 0xdb, 0xff, 0x89, 0xdf, 0xff, 0x8b, + 0xe3, 0xff, 0x8c, 0xe8, 0xff, 0x8d, 0xec, 0xfe, 0x8f, 0xf1, 0xfe, 0x90, 0xf5, 0xfd, 0x92, 0xfa +}; +static constexpr std::array R2 = { + 0x00, 0x34, 0xf5, 0x00, 0x37, 0xf3, 0x00, 0x3a, 0xf0, 0x00, 0x3c, 0xed, 0x00, 0x3f, 0xea, 0x00, + 0x41, 0xe7, 0x00, 0x44, 0xe5, 0x00, 0x46, 0xe2, 0x00, 0x48, 0xdf, 0x00, 0x4a, 0xdc, 0x00, 0x4d, + 0xd9, 0x00, 0x4f, 0xd6, 0x00, 0x51, 0xd4, 0x00, 0x53, 0xd1, 0x00, 0x55, 0xce, 0x00, 0x57, 0xcb, + 0x00, 0x59, 0xc9, 0x00, 0x5a, 0xc6, 0x00, 0x5c, 0xc3, 0x00, 0x5e, 0xc0, 0x00, 0x60, 0xbd, 0x00, + 0x62, 0xbb, 0x00, 0x63, 0xb8, 0x00, 0x65, 0xb5, 0x00, 0x67, 0xb2, 0x00, 0x68, 0xb0, 0x00, 0x6a, + 0xad, 0x00, 0x6c, 0xaa, 0x00, 0x6d, 0xa7, 0x00, 0x6f, 0xa5, 0x00, 0x70, 0xa2, 0x00, 0x71, 0xa0, + 0x00, 0x73, 0x9d, 0x00, 0x74, 0x9a, 0x00, 0x75, 0x98, 0x01, 0x76, 0x95, 0x08, 0x77, 0x93, 0x0e, + 0x78, 0x91, 0x14, 0x7a, 0x8e, 0x18, 0x7b, 0x8c, 0x1c, 0x7c, 0x89, 0x20, 0x7d, 0x87, 0x23, 0x7e, + 0x85, 0x26, 0x7f, 0x82, 0x29, 0x80, 0x80, 0x2b, 0x81, 0x7e, 0x2d, 0x82, 0x7b, 0x2f, 0x83, 0x79, + 0x31, 0x84, 0x76, 0x33, 0x85, 0x74, 0x34, 0x86, 0x72, 0x35, 0x87, 0x6f, 0x37, 0x88, 0x6d, 0x38, + 0x89, 0x6a, 0x39, 0x8a, 0x68, 0x3a, 0x8b, 0x65, 0x3b, 0x8c, 0x63, 0x3b, 0x8d, 0x60, 0x3c, 0x8e, + 0x5e, 0x3d, 0x8f, 0x5b, 0x3d, 0x90, 0x58, 0x3e, 0x91, 0x56, 0x3e, 0x92, 0x53, 0x3e, 0x93, 0x50, + 0x3f, 0x94, 0x4e, 0x3f, 0x95, 0x4b, 0x3f, 0x96, 0x48, 0x3f, 0x98, 0x45, 0x3f, 0x99, 0x42, 0x3f, + 0x9a, 0x3f, 0x3f, 0x9b, 0x3c, 0x3f, 0x9c, 0x39, 0x3f, 0x9d, 0x35, 0x3f, 0x9e, 0x32, 0x3f, 0x9f, + 0x2f, 0x3f, 0xa0, 0x2b, 0x3f, 0xa1, 0x28, 0x40, 0xa2, 0x24, 0x40, 0xa3, 0x21, 0x41, 0xa4, 0x1e, + 0x42, 0xa5, 0x1b, 0x44, 0xa6, 0x18, 0x46, 0xa6, 0x16, 0x48, 0xa7, 0x14, 0x4a, 0xa8, 0x12, 0x4d, + 0xa9, 0x10, 0x4f, 0xa9, 0x10, 0x52, 0xaa, 0x0f, 0x55, 0xab, 0x0f, 0x57, 0xab, 0x0f, 0x5a, 0xac, + 0x0f, 0x5d, 0xac, 0x0f, 0x60, 0xad, 0x10, 0x62, 0xae, 0x10, 0x65, 0xae, 0x11, 0x68, 0xaf, 0x11, + 0x6a, 0xaf, 0x12, 0x6d, 0xb0, 0x12, 0x6f, 0xb1, 0x12, 0x72, 0xb1, 0x13, 0x74, 0xb2, 0x13, 0x77, + 0xb2, 0x14, 0x79, 0xb3, 0x14, 0x7c, 0xb4, 0x15, 0x7e, 0xb4, 0x15, 0x81, 0xb5, 0x16, 0x83, 0xb5, + 0x16, 0x85, 0xb6, 0x17, 0x88, 0xb6, 0x17, 0x8a, 0xb7, 0x18, 0x8c, 0xb7, 0x18, 0x8f, 0xb8, 0x19, + 0x91, 0xb9, 0x19, 0x93, 0xb9, 0x1a, 0x96, 0xba, 0x1a, 0x98, 0xba, 0x1a, 0x9a, 0xbb, 0x1b, 0x9c, + 0xbb, 0x1b, 0x9f, 0xbc, 0x1c, 0xa1, 0xbc, 0x1c, 0xa3, 0xbd, 0x1d, 0xa5, 0xbe, 0x1d, 0xa8, 0xbe, + 0x1e, 0xaa, 0xbf, 0x1e, 0xac, 0xbf, 0x1f, 0xae, 0xc0, 0x1f, 0xb0, 0xc0, 0x1f, 0xb3, 0xc1, 0x20, + 0xb5, 0xc1, 0x20, 0xb7, 0xc2, 0x21, 0xb9, 0xc2, 0x21, 0xbb, 0xc3, 0x22, 0xbe, 0xc3, 0x22, 0xc0, + 0xc4, 0x23, 0xc2, 0xc4, 0x23, 0xc4, 0xc5, 0x23, 0xc6, 0xc5, 0x24, 0xc8, 0xc6, 0x24, 0xcb, 0xc6, + 0x25, 0xcd, 0xc7, 0x25, 0xcf, 0xc7, 0x26, 0xd1, 0xc8, 0x26, 0xd3, 0xc8, 0x27, 0xd5, 0xc9, 0x27, + 0xd7, 0xc9, 0x27, 0xda, 0xca, 0x28, 0xdc, 0xca, 0x28, 0xde, 0xcb, 0x29, 0xe0, 0xcb, 0x29, 0xe2, + 0xcb, 0x2a, 0xe4, 0xcc, 0x2a, 0xe6, 0xcc, 0x2b, 0xe8, 0xcd, 0x2b, 0xea, 0xcd, 0x2b, 0xec, 0xcd, + 0x2c, 0xee, 0xcd, 0x2c, 0xf0, 0xcd, 0x2c, 0xf2, 0xcd, 0x2c, 0xf4, 0xcd, 0x2c, 0xf5, 0xcd, 0x2c, + 0xf6, 0xcc, 0x2c, 0xf8, 0xcc, 0x2c, 0xf9, 0xcb, 0x2c, 0xf9, 0xca, 0x2c, 0xfa, 0xc9, 0x2b, 0xfb, + 0xc8, 0x2b, 0xfb, 0xc7, 0x2a, 0xfc, 0xc5, 0x2a, 0xfc, 0xc4, 0x29, 0xfc, 0xc3, 0x29, 0xfc, 0xc2, + 0x28, 0xfd, 0xc0, 0x28, 0xfd, 0xbf, 0x27, 0xfd, 0xbe, 0x27, 0xfd, 0xbc, 0x26, 0xfd, 0xbb, 0x26, + 0xfd, 0xba, 0x25, 0xfe, 0xb8, 0x25, 0xfe, 0xb7, 0x24, 0xfe, 0xb5, 0x23, 0xfe, 0xb4, 0x23, 0xfe, + 0xb3, 0x22, 0xfe, 0xb1, 0x22, 0xfe, 0xb0, 0x21, 0xfe, 0xaf, 0x21, 0xff, 0xad, 0x20, 0xff, 0xac, + 0x1f, 0xff, 0xaa, 0x1f, 0xff, 0xa9, 0x1e, 0xff, 0xa8, 0x1e, 0xff, 0xa6, 0x1d, 0xff, 0xa5, 0x1d, + 0xff, 0xa3, 0x1c, 0xff, 0xa2, 0x1c, 0xff, 0xa1, 0x1b, 0xff, 0x9f, 0x1a, 0xff, 0x9e, 0x1a, 0xff, + 0x9c, 0x19, 0xff, 0x9b, 0x19, 0xff, 0x99, 0x18, 0xff, 0x98, 0x18, 0xff, 0x96, 0x17, 0xff, 0x95, + 0x16, 0xff, 0x93, 0x16, 0xff, 0x92, 0x15, 0xff, 0x91, 0x15, 0xff, 0x8f, 0x14, 0xff, 0x8e, 0x14, + 0xff, 0x8c, 0x13, 0xff, 0x8b, 0x12, 0xff, 0x89, 0x12, 0xff, 0x88, 0x11, 0xff, 0x86, 0x11, 0xff, + 0x84, 0x10, 0xff, 0x83, 0x10, 0xff, 0x81, 0x0f, 0xff, 0x80, 0x0e, 0xff, 0x7e, 0x0e, 0xff, 0x7d, + 0x0d, 0xff, 0x7b, 0x0d, 0xff, 0x79, 0x0c, 0xff, 0x78, 0x0b, 0xff, 0x76, 0x0b, 0xff, 0x74, 0x0a, + 0xff, 0x73, 0x0a, 0xff, 0x71, 0x09, 0xff, 0x6f, 0x08, 0xff, 0x6e, 0x08, 0xff, 0x6c, 0x07, 0xff, + 0x6a, 0x07, 0xff, 0x69, 0x06, 0xff, 0x67, 0x06, 0xff, 0x65, 0x05, 0xff, 0x63, 0x05, 0xff, 0x61, + 0x04, 0xff, 0x5f, 0x04, 0xff, 0x5e, 0x03, 0xff, 0x5c, 0x03, 0xff, 0x5a, 0x03, 0xff, 0x58, 0x02, + 0xfe, 0x56, 0x02, 0xfe, 0x54, 0x02, 0xfe, 0x52, 0x01, 0xfe, 0x4f, 0x01, 0xfe, 0x4d, 0x01, 0xfe, + 0x4b, 0x00, 0xfe, 0x49, 0x00, 0xfe, 0x46, 0x00, 0xfe, 0x44, 0x00, 0xfd, 0x41, 0x00, 0xfd, 0x3f, + 0x00, 0xfd, 0x3c, 0x00, 0xfd, 0x39, 0x00, 0xfd, 0x36, 0x00, 0xfd, 0x33, 0x00, 0xfd, 0x30, 0x00 +}; +static constexpr std::array R3 = { + 0x08, 0x5c, 0xf8, 0x0f, 0x5f, 0xf4, 0x13, 0x61, 0xf1, 0x17, 0x63, 0xed, 0x19, 0x65, 0xe9, 0x1b, + 0x67, 0xe5, 0x1c, 0x6a, 0xe1, 0x1d, 0x6c, 0xde, 0x1d, 0x6e, 0xda, 0x1e, 0x70, 0xd6, 0x1d, 0x72, + 0xd2, 0x1d, 0x74, 0xce, 0x1c, 0x75, 0xcb, 0x1b, 0x77, 0xc7, 0x19, 0x79, 0xc3, 0x18, 0x7b, 0xbf, + 0x16, 0x7d, 0xbb, 0x14, 0x7e, 0xb8, 0x13, 0x80, 0xb4, 0x12, 0x82, 0xb0, 0x12, 0x83, 0xac, 0x13, + 0x85, 0xa8, 0x14, 0x86, 0xa4, 0x17, 0x88, 0xa0, 0x1a, 0x89, 0x9c, 0x1d, 0x8a, 0x98, 0x20, 0x8c, + 0x93, 0x23, 0x8d, 0x8f, 0x27, 0x8e, 0x8b, 0x2a, 0x8f, 0x86, 0x2d, 0x90, 0x82, 0x2f, 0x92, 0x7e, + 0x31, 0x93, 0x79, 0x34, 0x94, 0x75, 0x35, 0x95, 0x70, 0x37, 0x96, 0x6c, 0x38, 0x97, 0x67, 0x39, + 0x98, 0x62, 0x3a, 0x9a, 0x5e, 0x3b, 0x9b, 0x59, 0x3b, 0x9c, 0x54, 0x3b, 0x9d, 0x50, 0x3c, 0x9e, + 0x4b, 0x3c, 0x9f, 0x46, 0x3c, 0xa0, 0x42, 0x3d, 0xa1, 0x3d, 0x3d, 0xa2, 0x39, 0x3e, 0xa3, 0x35, + 0x3f, 0xa4, 0x31, 0x41, 0xa5, 0x2e, 0x42, 0xa6, 0x2b, 0x44, 0xa7, 0x28, 0x47, 0xa8, 0x26, 0x49, + 0xa8, 0x24, 0x4c, 0xa9, 0x22, 0x4e, 0xaa, 0x21, 0x51, 0xaa, 0x20, 0x54, 0xab, 0x20, 0x57, 0xac, + 0x1f, 0x5a, 0xac, 0x1f, 0x5c, 0xad, 0x1e, 0x5f, 0xae, 0x1e, 0x62, 0xae, 0x1e, 0x65, 0xaf, 0x1e, + 0x67, 0xaf, 0x1d, 0x6a, 0xb0, 0x1d, 0x6c, 0xb1, 0x1d, 0x6f, 0xb1, 0x1d, 0x72, 0xb2, 0x1d, 0x74, + 0xb2, 0x1d, 0x77, 0xb3, 0x1c, 0x79, 0xb4, 0x1c, 0x7b, 0xb4, 0x1c, 0x7e, 0xb5, 0x1c, 0x80, 0xb5, + 0x1b, 0x83, 0xb6, 0x1b, 0x85, 0xb6, 0x1b, 0x87, 0xb7, 0x1b, 0x8a, 0xb8, 0x1b, 0x8c, 0xb8, 0x1a, + 0x8e, 0xb9, 0x1a, 0x91, 0xb9, 0x1a, 0x93, 0xba, 0x1a, 0x95, 0xba, 0x19, 0x97, 0xbb, 0x19, 0x9a, + 0xbb, 0x19, 0x9c, 0xbc, 0x19, 0x9e, 0xbd, 0x18, 0xa0, 0xbd, 0x18, 0xa3, 0xbe, 0x18, 0xa5, 0xbe, + 0x18, 0xa7, 0xbf, 0x17, 0xa9, 0xbf, 0x17, 0xab, 0xc0, 0x17, 0xae, 0xc0, 0x16, 0xb0, 0xc1, 0x16, + 0xb2, 0xc1, 0x16, 0xb4, 0xc2, 0x15, 0xb6, 0xc2, 0x15, 0xb8, 0xc3, 0x15, 0xbb, 0xc3, 0x14, 0xbd, + 0xc4, 0x14, 0xbf, 0xc5, 0x14, 0xc1, 0xc5, 0x13, 0xc3, 0xc6, 0x13, 0xc5, 0xc6, 0x13, 0xc7, 0xc7, + 0x12, 0xca, 0xc7, 0x12, 0xcc, 0xc8, 0x12, 0xce, 0xc8, 0x11, 0xd0, 0xc9, 0x11, 0xd2, 0xc9, 0x10, + 0xd4, 0xca, 0x10, 0xd6, 0xca, 0x0f, 0xd8, 0xcb, 0x0f, 0xdb, 0xcb, 0x0e, 0xdd, 0xcb, 0x0e, 0xdf, + 0xcc, 0x0e, 0xe1, 0xcc, 0x0e, 0xe3, 0xcd, 0x0e, 0xe5, 0xcd, 0x0e, 0xe7, 0xcd, 0x0f, 0xe9, 0xce, + 0x10, 0xeb, 0xce, 0x12, 0xed, 0xce, 0x14, 0xef, 0xcd, 0x16, 0xf1, 0xcd, 0x19, 0xf3, 0xcd, 0x1c, + 0xf4, 0xcc, 0x1f, 0xf6, 0xcb, 0x23, 0xf7, 0xca, 0x26, 0xf8, 0xc9, 0x29, 0xf9, 0xc8, 0x2d, 0xf9, + 0xc7, 0x30, 0xfa, 0xc6, 0x33, 0xfa, 0xc5, 0x36, 0xfb, 0xc3, 0x39, 0xfb, 0xc2, 0x3c, 0xfc, 0xc0, + 0x3f, 0xfc, 0xbf, 0x41, 0xfc, 0xbe, 0x44, 0xfc, 0xbc, 0x46, 0xfc, 0xbb, 0x48, 0xfd, 0xb9, 0x4b, + 0xfd, 0xb8, 0x4d, 0xfd, 0xb6, 0x4f, 0xfd, 0xb5, 0x51, 0xfd, 0xb3, 0x53, 0xfd, 0xb2, 0x55, 0xfe, + 0xb0, 0x57, 0xfe, 0xaf, 0x59, 0xfe, 0xad, 0x5b, 0xfe, 0xac, 0x5d, 0xfe, 0xaa, 0x5f, 0xfe, 0xa9, + 0x61, 0xfe, 0xa7, 0x63, 0xfe, 0xa6, 0x65, 0xfe, 0xa4, 0x66, 0xfe, 0xa3, 0x68, 0xfe, 0xa1, 0x6a, + 0xfe, 0xa0, 0x6c, 0xff, 0x9e, 0x6d, 0xff, 0x9d, 0x6f, 0xff, 0x9b, 0x71, 0xff, 0x9a, 0x72, 0xff, + 0x98, 0x74, 0xff, 0x97, 0x75, 0xff, 0x95, 0x77, 0xff, 0x93, 0x79, 0xff, 0x92, 0x7a, 0xff, 0x90, + 0x7c, 0xff, 0x8f, 0x7d, 0xff, 0x8d, 0x7f, 0xfe, 0x8b, 0x80, 0xfe, 0x8a, 0x82, 0xfe, 0x88, 0x84, + 0xfe, 0x86, 0x85, 0xfe, 0x85, 0x87, 0xfe, 0x83, 0x88, 0xfe, 0x81, 0x8a, 0xfe, 0x80, 0x8b, 0xfe, + 0x7e, 0x8c, 0xfe, 0x7c, 0x8e, 0xfe, 0x7a, 0x8f, 0xfd, 0x79, 0x91, 0xfd, 0x77, 0x92, 0xfd, 0x75, + 0x94, 0xfd, 0x73, 0x95, 0xfd, 0x71, 0x97, 0xfd, 0x70, 0x98, 0xfd, 0x6e, 0x99, 0xfc, 0x6c, 0x9b, + 0xfc, 0x6a, 0x9c, 0xfc, 0x68, 0x9e, 0xfc, 0x66, 0x9f, 0xfc, 0x64, 0xa0, 0xfb, 0x62, 0xa2, 0xfb, + 0x60, 0xa3, 0xfb, 0x5e, 0xa4, 0xfb, 0x5c, 0xa5, 0xfa, 0x5a, 0xa6, 0xfa, 0x58, 0xa7, 0xfa, 0x56, + 0xa8, 0xfa, 0x54, 0xa8, 0xf9, 0x52, 0xa8, 0xf9, 0x50, 0xa8, 0xf9, 0x4e, 0xa7, 0xf8, 0x4c, 0xa6, + 0xf8, 0x4a, 0xa5, 0xf8, 0x49, 0xa3, 0xf7, 0x47, 0xa1, 0xf7, 0x46, 0x9e, 0xf7, 0x44, 0x9c, 0xf6, + 0x43, 0x99, 0xf6, 0x42, 0x96, 0xf6, 0x40, 0x92, 0xf5, 0x3f, 0x8f, 0xf5, 0x3e, 0x8c, 0xf4, 0x3d, + 0x88, 0xf4, 0x3c, 0x85, 0xf3, 0x3a, 0x82, 0xf3, 0x39, 0x7e, 0xf2, 0x38, 0x7b, 0xf1, 0x37, 0x78, + 0xf1, 0x36, 0x74, 0xf0, 0x34, 0x71, 0xf0, 0x33, 0x6d, 0xef, 0x32, 0x6a, 0xee, 0x31, 0x67, 0xee, + 0x2f, 0x63, 0xed, 0x2e, 0x60, 0xec, 0x2d, 0x5d, 0xeb, 0x2c, 0x59, 0xeb, 0x2a, 0x56, 0xea, 0x29, + 0x53, 0xe9, 0x28, 0x4f, 0xe8, 0x26, 0x4c, 0xe8, 0x25, 0x49, 0xe7, 0x24, 0x45, 0xe6, 0x22, 0x42, + 0xe5, 0x21, 0x3f, 0xe4, 0x20, 0x3b, 0xe3, 0x1e, 0x38, 0xe2, 0x1d, 0x35, 0xe2, 0x1b, 0x31, 0xe1, + 0x1a, 0x2e, 0xe0, 0x18, 0x2a, 0xdf, 0x16, 0x26, 0xde, 0x14, 0x23, 0xdd, 0x13, 0x1f, 0xdc, 0x11, + 0x1b, 0xdb, 0x0f, 0x17, 0xda, 0x0c, 0x12, 0xd9, 0x0a, 0x0c, 0xd8, 0x07, 0x06, 0xd7, 0x05, 0x00 +}; +static constexpr std::array R4 = { + 0x04, 0x00, 0x6c, 0x04, 0x00, 0x6f, 0x04, 0x00, 0x72, 0x04, 0x00, 0x75, 0x04, 0x00, 0x78, 0x04, + 0x00, 0x7b, 0x04, 0x00, 0x7e, 0x04, 0x00, 0x81, 0x04, 0x00, 0x84, 0x05, 0x00, 0x87, 0x05, 0x00, + 0x8a, 0x05, 0x00, 0x8d, 0x05, 0x00, 0x91, 0x05, 0x00, 0x94, 0x05, 0x00, 0x97, 0x05, 0x01, 0x9a, + 0x05, 0x01, 0x9c, 0x05, 0x01, 0x9f, 0x05, 0x02, 0xa2, 0x06, 0x02, 0xa5, 0x06, 0x03, 0xa7, 0x06, + 0x04, 0xaa, 0x06, 0x06, 0xac, 0x07, 0x07, 0xaf, 0x07, 0x09, 0xb1, 0x08, 0x0b, 0xb3, 0x08, 0x0d, + 0xb5, 0x09, 0x0f, 0xb7, 0x09, 0x11, 0xb9, 0x0a, 0x13, 0xbb, 0x0a, 0x15, 0xbd, 0x0b, 0x17, 0xbf, + 0x0b, 0x18, 0xc1, 0x0c, 0x1a, 0xc3, 0x0c, 0x1c, 0xc5, 0x0c, 0x1d, 0xc7, 0x0d, 0x1f, 0xc9, 0x0d, + 0x20, 0xcb, 0x0e, 0x22, 0xcd, 0x0e, 0x24, 0xcf, 0x0e, 0x25, 0xd1, 0x0f, 0x27, 0xd2, 0x0f, 0x28, + 0xd4, 0x0f, 0x2a, 0xd6, 0x10, 0x2b, 0xd8, 0x10, 0x2c, 0xda, 0x10, 0x2e, 0xdc, 0x10, 0x2f, 0xde, + 0x11, 0x31, 0xe0, 0x11, 0x32, 0xe2, 0x11, 0x34, 0xe4, 0x11, 0x35, 0xe6, 0x12, 0x37, 0xe8, 0x12, + 0x38, 0xe9, 0x12, 0x3a, 0xeb, 0x13, 0x3b, 0xed, 0x14, 0x3d, 0xee, 0x14, 0x3f, 0xef, 0x15, 0x41, + 0xf0, 0x17, 0x43, 0xf0, 0x18, 0x45, 0xf0, 0x19, 0x47, 0xef, 0x1b, 0x4a, 0xee, 0x1c, 0x4d, 0xed, + 0x1d, 0x50, 0xeb, 0x1e, 0x53, 0xe8, 0x1f, 0x56, 0xe5, 0x1f, 0x59, 0xe2, 0x20, 0x5c, 0xde, 0x1f, + 0x5f, 0xda, 0x1f, 0x62, 0xd6, 0x1d, 0x65, 0xd2, 0x1c, 0x68, 0xce, 0x1a, 0x6a, 0xca, 0x17, 0x6d, + 0xc5, 0x14, 0x70, 0xc1, 0x11, 0x73, 0xbc, 0x0d, 0x75, 0xb8, 0x09, 0x78, 0xb3, 0x07, 0x7a, 0xae, + 0x05, 0x7d, 0xaa, 0x06, 0x7f, 0xa5, 0x08, 0x81, 0xa0, 0x0c, 0x83, 0x9b, 0x10, 0x85, 0x96, 0x15, + 0x87, 0x90, 0x19, 0x89, 0x8b, 0x1d, 0x8b, 0x85, 0x21, 0x8d, 0x80, 0x24, 0x8e, 0x7a, 0x27, 0x90, + 0x74, 0x2a, 0x92, 0x6e, 0x2b, 0x94, 0x68, 0x2d, 0x95, 0x62, 0x2e, 0x97, 0x5c, 0x2f, 0x99, 0x56, + 0x30, 0x9b, 0x50, 0x30, 0x9c, 0x4a, 0x30, 0x9e, 0x44, 0x31, 0xa0, 0x3e, 0x31, 0xa1, 0x38, 0x32, + 0xa3, 0x32, 0x33, 0xa4, 0x2c, 0x35, 0xa6, 0x27, 0x37, 0xa7, 0x22, 0x39, 0xa9, 0x1d, 0x3c, 0xaa, + 0x19, 0x3f, 0xab, 0x15, 0x43, 0xad, 0x11, 0x46, 0xae, 0x0e, 0x4a, 0xaf, 0x0c, 0x4e, 0xb0, 0x0a, + 0x52, 0xb1, 0x08, 0x56, 0xb2, 0x08, 0x5a, 0xb3, 0x07, 0x5d, 0xb4, 0x06, 0x61, 0xb5, 0x06, 0x65, + 0xb6, 0x06, 0x68, 0xb7, 0x06, 0x6c, 0xb8, 0x06, 0x6f, 0xba, 0x05, 0x73, 0xbb, 0x05, 0x76, 0xbc, + 0x05, 0x7a, 0xbd, 0x05, 0x7d, 0xbe, 0x05, 0x80, 0xbf, 0x05, 0x83, 0xc0, 0x05, 0x87, 0xc1, 0x05, + 0x8a, 0xc2, 0x04, 0x8d, 0xc3, 0x04, 0x90, 0xc4, 0x04, 0x93, 0xc5, 0x04, 0x96, 0xc6, 0x04, 0x9a, + 0xc7, 0x04, 0x9d, 0xc8, 0x04, 0xa0, 0xc9, 0x04, 0xa3, 0xca, 0x04, 0xa6, 0xcb, 0x03, 0xa9, 0xcc, + 0x03, 0xac, 0xcd, 0x03, 0xaf, 0xce, 0x03, 0xb2, 0xcf, 0x03, 0xb5, 0xd0, 0x03, 0xb8, 0xd1, 0x03, + 0xbb, 0xd2, 0x03, 0xbe, 0xd3, 0x02, 0xc1, 0xd4, 0x02, 0xc4, 0xd5, 0x02, 0xc7, 0xd6, 0x02, 0xca, + 0xd7, 0x02, 0xcd, 0xd8, 0x02, 0xd0, 0xd9, 0x02, 0xd3, 0xd9, 0x02, 0xd6, 0xda, 0x02, 0xd9, 0xdb, + 0x02, 0xdc, 0xdc, 0x02, 0xdf, 0xdd, 0x02, 0xe1, 0xde, 0x02, 0xe4, 0xde, 0x02, 0xe7, 0xdf, 0x02, + 0xea, 0xdf, 0x02, 0xec, 0xdf, 0x02, 0xee, 0xdf, 0x02, 0xf0, 0xde, 0x03, 0xf2, 0xde, 0x03, 0xf4, + 0xdd, 0x04, 0xf5, 0xdc, 0x05, 0xf7, 0xda, 0x05, 0xf8, 0xd9, 0x06, 0xf8, 0xd7, 0x07, 0xf9, 0xd6, + 0x07, 0xfa, 0xd4, 0x08, 0xfa, 0xd2, 0x09, 0xfa, 0xd0, 0x0a, 0xfa, 0xce, 0x0b, 0xfb, 0xcc, 0x0b, + 0xfb, 0xca, 0x0c, 0xfb, 0xc8, 0x0d, 0xfb, 0xc6, 0x0d, 0xfb, 0xc4, 0x0e, 0xfb, 0xc2, 0x0e, 0xfb, + 0xc0, 0x0f, 0xfb, 0xbe, 0x0f, 0xfb, 0xbc, 0x10, 0xfc, 0xba, 0x10, 0xfc, 0xb8, 0x11, 0xfc, 0xb6, + 0x11, 0xfc, 0xb4, 0x12, 0xfc, 0xb2, 0x12, 0xfc, 0xb0, 0x13, 0xfc, 0xae, 0x13, 0xfc, 0xac, 0x13, + 0xfc, 0xa9, 0x14, 0xfc, 0xa7, 0x14, 0xfc, 0xa5, 0x14, 0xfc, 0xa3, 0x15, 0xfc, 0xa1, 0x15, 0xfc, + 0x9f, 0x15, 0xfc, 0x9d, 0x15, 0xfc, 0x9a, 0x15, 0xfc, 0x98, 0x16, 0xfc, 0x96, 0x16, 0xfc, 0x94, + 0x16, 0xfc, 0x91, 0x16, 0xfc, 0x8f, 0x15, 0xfc, 0x8d, 0x15, 0xfc, 0x8a, 0x15, 0xfc, 0x88, 0x15, + 0xfc, 0x86, 0x14, 0xfc, 0x83, 0x14, 0xfd, 0x80, 0x14, 0xfd, 0x7e, 0x13, 0xfd, 0x7b, 0x13, 0xfd, + 0x79, 0x13, 0xfd, 0x76, 0x12, 0xfe, 0x73, 0x12, 0xfe, 0x70, 0x11, 0xfe, 0x6e, 0x11, 0xfe, 0x6b, + 0x11, 0xfe, 0x68, 0x10, 0xfe, 0x65, 0x10, 0xfe, 0x62, 0x10, 0xfe, 0x5f, 0x0f, 0xfe, 0x5b, 0x0f, + 0xfe, 0x58, 0x0f, 0xfe, 0x55, 0x0e, 0xfe, 0x51, 0x0e, 0xfe, 0x4e, 0x0e, 0xfe, 0x4a, 0x0e, 0xfe, + 0x47, 0x0e, 0xfe, 0x43, 0x0d, 0xfd, 0x3f, 0x0d, 0xfd, 0x3c, 0x0d, 0xfc, 0x38, 0x0d, 0xfb, 0x35, + 0x0d, 0xfa, 0x32, 0x0d, 0xf9, 0x2f, 0x0d, 0xf8, 0x2c, 0x0d, 0xf6, 0x29, 0x0d, 0xf5, 0x27, 0x0d, + 0xf3, 0x24, 0x0d, 0xf1, 0x22, 0x0d, 0xf0, 0x20, 0x0d, 0xee, 0x1f, 0x0d, 0xec, 0x1d, 0x0d, 0xea, + 0x1b, 0x0d, 0xe8, 0x19, 0x0d, 0xe6, 0x17, 0x0d, 0xe4, 0x16, 0x0d, 0xe2, 0x14, 0x0d, 0xe0, 0x12, + 0x0d, 0xde, 0x10, 0x0d, 0xdc, 0x0d, 0x0d, 0xdb, 0x0b, 0x0d, 0xd9, 0x08, 0x0d, 0xd7, 0x05, 0x0d +}; - // cyclic - static constexpr std::array C1 = {0xf9,0x85,0xf8,0xfa,0x84,0xf6,0xfb,0x83,0xf3,0xfc,0x82,0xf1,0xfc,0x81,0xee,0xfd,0x7f,0xeb,0xfd,0x7e,0xe8,0xfd,0x7c,0xe5,0xfd,0x7a,0xe2,0xfd,0x78,0xde,0xfd,0x76,0xdb,0xfc,0x74,0xd7,0xfc,0x72,0xd4,0xfb,0x70,0xd0,0xfb,0x6d,0xcc,0xfa,0x6b,0xc8,0xfa,0x69,0xc5,0xf9,0x67,0xc1,0xf8,0x64,0xbd,0xf7,0x62,0xb9,0xf7,0x5f,0xb5,0xf6,0x5d,0xb2,0xf5,0x5b,0xae,0xf4,0x58,0xaa,0xf3,0x56,0xa6,0xf2,0x54,0xa3,0xf1,0x51,0x9f,0xf0,0x4f,0x9b,0xef,0x4c,0x97,0xee,0x4a,0x94,0xed,0x48,0x90,0xec,0x46,0x8c,0xea,0x43,0x88,0xe9,0x41,0x84,0xe8,0x3f,0x81,0xe6,0x3d,0x7d,0xe5,0x3b,0x79,0xe3,0x39,0x75,0xe1,0x37,0x71,0xe0,0x35,0x6d,0xde,0x33,0x6a,0xdc,0x31,0x66,0xda,0x2f,0x62,0xd9,0x2d,0x5e,0xd7,0x2c,0x5a,0xd5,0x2a,0x56,0xd3,0x28,0x53,0xd1,0x26,0x4f,0xcf,0x24,0x4b,0xcd,0x23,0x47,0xcb,0x21,0x44,0xc9,0x1f,0x40,0xc7,0x1e,0x3c,0xc6,0x1c,0x39,0xc4,0x1b,0x35,0xc2,0x19,0x32,0xc0,0x18,0x2e,0xbe,0x17,0x2b,0xbd,0x17,0x27,0xbb,0x17,0x24,0xba,0x17,0x21,0xb9,0x17,0x1e,0xb8,0x18,0x1b,0xb7,0x19,0x19,0xb6,0x1b,0x16,0xb5,0x1d,0x14,0xb5,0x1f,0x11,0xb5,0x21,0x0f,0xb5,0x23,0x0d,0xb5,0x26,0x0c,0xb5,0x29,0x0a,0xb6,0x2b,0x08,0xb6,0x2e,0x07,0xb7,0x31,0x06,0xb8,0x33,0x06,0xb8,0x36,0x05,0xb9,0x39,0x05,0xba,0x3b,0x05,0xbb,0x3e,0x04,0xbc,0x41,0x04,0xbd,0x43,0x04,0xbe,0x46,0x04,0xbf,0x48,0x04,0xc0,0x4b,0x04,0xc1,0x4d,0x04,0xc2,0x50,0x04,0xc3,0x52,0x04,0xc4,0x54,0x04,0xc5,0x57,0x04,0xc6,0x59,0x05,0xc7,0x5c,0x05,0xc8,0x5e,0x05,0xc9,0x60,0x05,0xca,0x63,0x05,0xca,0x65,0x05,0xcb,0x67,0x05,0xcc,0x6a,0x05,0xcd,0x6c,0x05,0xce,0x6f,0x05,0xce,0x71,0x05,0xcf,0x73,0x05,0xd0,0x76,0x05,0xd0,0x78,0x05,0xd1,0x7a,0x05,0xd1,0x7d,0x05,0xd2,0x7f,0x04,0xd2,0x81,0x04,0xd3,0x84,0x04,0xd3,0x86,0x04,0xd4,0x89,0x04,0xd4,0x8b,0x04,0xd5,0x8d,0x04,0xd5,0x8f,0x04,0xd6,0x92,0x04,0xd6,0x94,0x05,0xd6,0x96,0x05,0xd6,0x98,0x06,0xd7,0x9b,0x07,0xd7,0x9d,0x08,0xd7,0x9f,0x0a,0xd7,0xa0,0x0d,0xd6,0xa2,0x0f,0xd6,0xa4,0x12,0xd5,0xa5,0x15,0xd5,0xa7,0x18,0xd4,0xa8,0x1c,0xd2,0xa9,0x1f,0xd1,0xaa,0x23,0xd0,0xaa,0x27,0xce,0xaa,0x2b,0xcc,0xab,0x2f,0xca,0xab,0x33,0xc7,0xaa,0x37,0xc5,0xaa,0x3b,0xc2,0xa9,0x3f,0xbf,0xa9,0x43,0xbc,0xa8,0x46,0xb9,0xa7,0x4a,0xb6,0xa6,0x4e,0xb3,0xa5,0x52,0xaf,0xa4,0x55,0xac,0xa3,0x59,0xa9,0xa1,0x5c,0xa5,0xa0,0x60,0xa1,0x9f,0x63,0x9d,0x9e,0x66,0x9a,0x9d,0x69,0x96,0x9b,0x6d,0x92,0x9a,0x70,0x8e,0x99,0x73,0x89,0x98,0x76,0x85,0x96,0x79,0x81,0x95,0x7c,0x7c,0x94,0x7f,0x77,0x93,0x82,0x73,0x91,0x85,0x6e,0x90,0x88,0x69,0x8f,0x8b,0x63,0x8d,0x8e,0x5e,0x8c,0x91,0x59,0x8b,0x94,0x53,0x89,0x97,0x4e,0x88,0x9a,0x48,0x86,0x9d,0x43,0x84,0xa0,0x3e,0x83,0xa3,0x39,0x81,0xa6,0x34,0x7f,0xa9,0x2f,0x7d,0xac,0x2b,0x7b,0xaf,0x28,0x79,0xb2,0x25,0x76,0xb5,0x23,0x74,0xb8,0x22,0x71,0xbb,0x22,0x6f,0xbe,0x22,0x6c,0xc1,0x22,0x69,0xc5,0x24,0x66,0xc8,0x25,0x63,0xcb,0x26,0x60,0xce,0x28,0x5d,0xd1,0x29,0x5a,0xd4,0x2b,0x57,0xd7,0x2d,0x54,0xda,0x2e,0x51,0xdd,0x30,0x4e,0xe0,0x31,0x4b,0xe3,0x33,0x49,0xe5,0x35,0x46,0xe8,0x37,0x44,0xea,0x39,0x42,0xec,0x3c,0x40,0xee,0x3e,0x3f,0xf0,0x41,0x3e,0xf2,0x44,0x3d,0xf3,0x47,0x3d,0xf4,0x49,0x3d,0xf5,0x4c,0x3d,0xf6,0x4f,0x3e,0xf7,0x52,0x3f,0xf7,0x55,0x40,0xf8,0x58,0x41,0xf8,0x5b,0x43,0xf9,0x5e,0x45,0xf9,0x61,0x47,0xf9,0x63,0x49,0xf9,0x66,0x4b,0xf9,0x69,0x4d,0xf9,0x6b,0x4f,0xf9,0x6e,0x51,0xf9,0x70,0x53,0xf9,0x73,0x55,0xf9,0x75,0x57,0xf9,0x77,0x59,0xf9,0x7a,0x5b,0xfa,0x7c,0x5d,0xfa,0x7f,0x5e,0xfa,0x82,0x60,0xfa,0x84,0x62,0xfa,0x87,0x64,0xfa,0x8a,0x65,0xfa,0x8d,0x67,0xfa,0x90,0x69,0xfa,0x93,0x6a,0xfa,0x96,0x6b,0xfb,0x99,0x6d,0xfb,0x9c,0x6e,0xfb,0xa0,0x6f,0xfb,0xa3,0x71,0xfb,0xa7,0x72,0xfc,0xaa,0x73,0xfc,0xae,0x74,0xfc,0xb1,0x75,0xfc,0xb5,0x76,0xfd,0xb9,0x77,0xfd,0xbc,0x78,0xfd,0xc0,0x79,0xfe,0xc3,0x7a,0xfe,0xc7,0x7b,0xfe,0xca,0x7c,0xff,0xce,0x7d,0xff,0xd1,0x7e,0xff,0xd5,0x7f,0xff,0xd8,0x80,0xff,0xdb,0x81,0xff,0xdf,0x82,0xff,0xe2,0x83,0xff,0xe5,0x84,0xff,0xe8,0x84,0xff,0xea,0x85,0xff,0xed,0x85,0xff,0xf0,0x86,0xfe,0xf2,0x86,0xfd,0xf4,0x86,0xfc,0xf6,0x86,0xfb,0xf7,0x85,0xf9}; - static constexpr std::array C2 = {0xef,0x55,0xf2,0xf1,0x57,0xf0,0xf2,0x5a,0xef,0xf3,0x5d,0xed,0xf5,0x5f,0xeb,0xf6,0x62,0xe9,0xf6,0x65,0xe7,0xf7,0x68,0xe5,0xf8,0x6b,0xe2,0xf9,0x6f,0xe0,0xf9,0x72,0xde,0xfa,0x75,0xdb,0xfa,0x78,0xd9,0xfa,0x7b,0xd6,0xfb,0x7e,0xd3,0xfb,0x81,0xd1,0xfb,0x84,0xce,0xfb,0x87,0xcb,0xfb,0x8a,0xc9,0xfc,0x8d,0xc6,0xfc,0x90,0xc3,0xfc,0x93,0xc0,0xfc,0x95,0xbe,0xfc,0x98,0xbb,0xfc,0x9b,0xb8,0xfc,0x9e,0xb5,0xfc,0xa0,0xb3,0xfc,0xa3,0xb0,0xfc,0xa6,0xad,0xfc,0xa8,0xaa,0xfc,0xab,0xa7,0xfc,0xad,0xa5,0xfc,0xb0,0xa2,0xfb,0xb2,0x9f,0xfb,0xb5,0x9c,0xfb,0xb7,0x99,0xfb,0xb9,0x96,0xfc,0xbc,0x93,0xfc,0xbe,0x90,0xfc,0xc0,0x8d,0xfc,0xc3,0x8a,0xfc,0xc5,0x87,0xfc,0xc7,0x84,0xfc,0xc9,0x81,0xfc,0xcc,0x7e,0xfc,0xce,0x7b,0xfc,0xd0,0x78,0xfc,0xd2,0x75,0xfc,0xd4,0x71,0xfc,0xd6,0x6e,0xfc,0xd8,0x6b,0xfc,0xda,0x67,0xfc,0xdd,0x64,0xfb,0xdf,0x60,0xfb,0xe0,0x5c,0xfb,0xe2,0x58,0xfa,0xe4,0x55,0xfa,0xe6,0x51,0xf9,0xe7,0x4d,0xf8,0xe9,0x49,0xf7,0xea,0x45,0xf5,0xeb,0x41,0xf4,0xec,0x3d,0xf2,0xed,0x39,0xf1,0xee,0x35,0xef,0xee,0x32,0xed,0xee,0x2e,0xea,0xef,0x2b,0xe8,0xee,0x28,0xe6,0xee,0x25,0xe3,0xee,0x23,0xe1,0xed,0x21,0xde,0xed,0x1f,0xdb,0xec,0x1d,0xd8,0xeb,0x1b,0xd6,0xea,0x1a,0xd3,0xe9,0x19,0xd0,0xe8,0x18,0xcd,0xe7,0x18,0xca,0xe6,0x17,0xc7,0xe5,0x16,0xc4,0xe4,0x16,0xc1,0xe3,0x15,0xbe,0xe2,0x15,0xbb,0xe1,0x15,0xb8,0xe0,0x14,0xb5,0xdf,0x14,0xb2,0xde,0x13,0xaf,0xdd,0x13,0xac,0xdc,0x13,0xa9,0xda,0x12,0xa6,0xd9,0x12,0xa3,0xd8,0x12,0xa0,0xd7,0x11,0x9d,0xd6,0x11,0x9a,0xd5,0x11,0x97,0xd4,0x10,0x94,0xd3,0x10,0x91,0xd2,0x10,0x8d,0xd0,0x0f,0x8a,0xcf,0x0f,0x87,0xce,0x0f,0x84,0xcd,0x0e,0x81,0xcc,0x0e,0x7d,0xcb,0x0e,0x7a,0xca,0x0d,0x77,0xc8,0x0d,0x73,0xc7,0x0d,0x70,0xc6,0x0d,0x6c,0xc5,0x0c,0x69,0xc4,0x0c,0x65,0xc3,0x0c,0x62,0xc2,0x0c,0x5e,0xc0,0x0c,0x5a,0xbf,0x0c,0x56,0xbe,0x0c,0x53,0xbd,0x0d,0x4f,0xbc,0x0e,0x4b,0xba,0x0f,0x48,0xb9,0x10,0x44,0xb8,0x12,0x41,0xb7,0x14,0x3e,0xb5,0x16,0x3b,0xb4,0x19,0x38,0xb3,0x1b,0x36,0xb1,0x1e,0x34,0xb0,0x21,0x33,0xae,0x25,0x32,0xad,0x28,0x32,0xab,0x2c,0x32,0xa9,0x2f,0x32,0xa8,0x33,0x33,0xa6,0x37,0x35,0xa4,0x3b,0x36,0xa3,0x3f,0x38,0xa1,0x42,0x39,0x9f,0x46,0x3b,0x9d,0x4a,0x3c,0x9b,0x4e,0x3e,0x99,0x52,0x3f,0x98,0x56,0x40,0x96,0x59,0x41,0x94,0x5d,0x42,0x92,0x61,0x43,0x90,0x64,0x44,0x8e,0x68,0x44,0x8c,0x6b,0x45,0x8a,0x6f,0x45,0x89,0x72,0x45,0x87,0x76,0x45,0x85,0x79,0x45,0x83,0x7d,0x45,0x81,0x80,0x44,0x7f,0x84,0x44,0x7d,0x87,0x43,0x7b,0x8a,0x42,0x79,0x8e,0x41,0x78,0x91,0x40,0x76,0x94,0x3f,0x74,0x97,0x3e,0x72,0x9b,0x3c,0x70,0x9e,0x3b,0x6e,0xa1,0x39,0x6c,0xa4,0x38,0x6a,0xa7,0x36,0x68,0xaa,0x34,0x66,0xad,0x33,0x64,0xb0,0x31,0x61,0xb3,0x30,0x5f,0xb6,0x2f,0x5d,0xb9,0x2d,0x5b,0xbb,0x2c,0x58,0xbe,0x2b,0x56,0xc1,0x2a,0x53,0xc3,0x2a,0x51,0xc6,0x29,0x4e,0xc8,0x28,0x4c,0xcb,0x27,0x49,0xcd,0x27,0x46,0xd0,0x26,0x43,0xd2,0x26,0x40,0xd5,0x25,0x3e,0xd7,0x25,0x3b,0xd9,0x24,0x38,0xdb,0x24,0x35,0xde,0x25,0x32,0xe0,0x25,0x2f,0xe2,0x26,0x2c,0xe4,0x28,0x29,0xe5,0x29,0x27,0xe7,0x2c,0x24,0xe9,0x2e,0x22,0xea,0x31,0x20,0xec,0x34,0x1e,0xed,0x37,0x1d,0xee,0x3b,0x1c,0xef,0x3e,0x1b,0xf0,0x42,0x1b,0xf1,0x45,0x1b,0xf2,0x49,0x1b,0xf2,0x4d,0x1c,0xf3,0x50,0x1c,0xf3,0x54,0x1d,0xf4,0x57,0x1f,0xf4,0x5a,0x20,0xf5,0x5e,0x21,0xf5,0x61,0x23,0xf6,0x64,0x24,0xf6,0x67,0x26,0xf6,0x6a,0x27,0xf7,0x6d,0x29,0xf7,0x70,0x2a,0xf7,0x73,0x2c,0xf8,0x75,0x2d,0xf8,0x78,0x2e,0xf8,0x7b,0x30,0xf9,0x7e,0x31,0xf9,0x80,0x32,0xf9,0x83,0x34,0xfa,0x86,0x35,0xfa,0x89,0x36,0xfa,0x8c,0x37,0xfa,0x8f,0x38,0xfb,0x91,0x39,0xfb,0x94,0x3a,0xfb,0x98,0x3b,0xfb,0x9b,0x3c,0xfb,0x9e,0x3d,0xfb,0xa1,0x3e,0xfb,0xa4,0x3e,0xfb,0xa7,0x3f,0xfb,0xab,0x40,0xfb,0xae,0x40,0xfb,0xb1,0x41,0xfb,0xb5,0x41,0xfb,0xb8,0x42,0xfb,0xbb,0x42,0xfb,0xbf,0x43,0xfb,0xc2,0x43,0xfb,0xc5,0x44,0xfb,0xc8,0x44,0xfa,0xcb,0x45,0xfa,0xcf,0x45,0xfa,0xd2,0x46,0xfa,0xd5,0x46,0xfa,0xd8,0x47,0xf9,0xdb,0x48,0xf9,0xdd,0x48,0xf9,0xe0,0x49,0xf8,0xe3,0x4b,0xf8,0xe5,0x4c,0xf7,0xe7,0x4d,0xf6,0xe9,0x4f,0xf5,0xec,0x51,0xf4,0xed,0x53,0xf3}; - static constexpr std::array C3 = {0xe1,0xd7,0xda,0xe2,0xd7,0xd8,0xe3,0xd6,0xd6,0xe4,0xd5,0xd4,0xe5,0xd4,0xd1,0xe6,0xd2,0xcf,0xe7,0xd1,0xcc,0xe8,0xcf,0xc9,0xe9,0xcd,0xc6,0xea,0xcb,0xc3,0xea,0xc9,0xc0,0xeb,0xc7,0xbd,0xec,0xc5,0xba,0xec,0xc2,0xb7,0xed,0xc0,0xb4,0xed,0xbd,0xb0,0xee,0xbb,0xad,0xee,0xb9,0xaa,0xee,0xb6,0xa7,0xef,0xb4,0xa4,0xef,0xb1,0xa0,0xef,0xaf,0x9d,0xef,0xac,0x9a,0xf0,0xaa,0x97,0xf0,0xa7,0x94,0xf0,0xa5,0x90,0xf0,0xa2,0x8d,0xf0,0xa0,0x8a,0xf0,0x9d,0x87,0xf0,0x9b,0x84,0xf0,0x98,0x81,0xf0,0x96,0x7e,0xf0,0x93,0x7a,0xf0,0x91,0x77,0xf0,0x8e,0x74,0xf0,0x8b,0x71,0xef,0x89,0x6e,0xef,0x86,0x6b,0xef,0x84,0x68,0xef,0x81,0x65,0xee,0x7e,0x62,0xee,0x7c,0x5f,0xee,0x79,0x5c,0xed,0x76,0x59,0xed,0x74,0x56,0xed,0x71,0x53,0xec,0x6e,0x50,0xec,0x6b,0x4d,0xeb,0x69,0x4a,0xeb,0x66,0x47,0xea,0x63,0x44,0xea,0x60,0x41,0xe9,0x5d,0x3e,0xe8,0x5a,0x3b,0xe8,0x57,0x38,0xe7,0x55,0x35,0xe6,0x52,0x33,0xe5,0x4f,0x30,0xe4,0x4c,0x2d,0xe3,0x49,0x2b,0xe1,0x47,0x29,0xe0,0x44,0x26,0xde,0x42,0x24,0xdc,0x40,0x23,0xda,0x3e,0x21,0xd8,0x3c,0x20,0xd6,0x3a,0x1e,0xd4,0x39,0x1d,0xd1,0x38,0x1c,0xcf,0x37,0x1c,0xcc,0x36,0x1b,0xc9,0x35,0x1b,0xc6,0x34,0x1a,0xc3,0x34,0x1a,0xc0,0x34,0x1a,0xbd,0x33,0x1a,0xba,0x33,0x1a,0xb7,0x33,0x1a,0xb4,0x33,0x1a,0xb1,0x32,0x1b,0xae,0x32,0x1b,0xab,0x32,0x1b,0xa7,0x32,0x1b,0xa4,0x32,0x1b,0xa1,0x31,0x1b,0x9e,0x31,0x1b,0x9b,0x31,0x1c,0x98,0x31,0x1c,0x94,0x31,0x1c,0x91,0x30,0x1c,0x8e,0x30,0x1c,0x8b,0x30,0x1c,0x88,0x2f,0x1c,0x85,0x2f,0x1c,0x82,0x2f,0x1c,0x7f,0x2e,0x1c,0x7c,0x2e,0x1c,0x79,0x2e,0x1d,0x76,0x2d,0x1d,0x73,0x2d,0x1d,0x70,0x2c,0x1d,0x6d,0x2c,0x1d,0x6a,0x2c,0x1d,0x67,0x2b,0x1d,0x64,0x2b,0x1d,0x61,0x2a,0x1d,0x5e,0x2a,0x1d,0x5b,0x29,0x1d,0x58,0x29,0x1d,0x55,0x28,0x1d,0x52,0x28,0x1d,0x4f,0x27,0x1d,0x4c,0x26,0x1d,0x49,0x26,0x1d,0x47,0x25,0x1d,0x44,0x25,0x1d,0x41,0x24,0x1d,0x3e,0x24,0x1d,0x3c,0x23,0x1d,0x39,0x23,0x1e,0x37,0x22,0x1e,0x34,0x22,0x1f,0x32,0x22,0x1f,0x30,0x21,0x20,0x2e,0x21,0x21,0x2d,0x21,0x22,0x2b,0x21,0x23,0x2a,0x21,0x25,0x29,0x22,0x26,0x28,0x22,0x28,0x27,0x22,0x2a,0x27,0x23,0x2c,0x27,0x23,0x2e,0x27,0x24,0x31,0x27,0x25,0x33,0x27,0x26,0x36,0x27,0x27,0x39,0x27,0x28,0x3c,0x28,0x29,0x3f,0x28,0x2a,0x42,0x29,0x2b,0x45,0x29,0x2c,0x48,0x2a,0x2d,0x4b,0x2a,0x2e,0x4f,0x2b,0x30,0x52,0x2b,0x31,0x55,0x2c,0x32,0x59,0x2c,0x33,0x5c,0x2d,0x35,0x60,0x2d,0x36,0x63,0x2e,0x37,0x66,0x2e,0x38,0x6a,0x2f,0x3a,0x6d,0x2f,0x3b,0x71,0x2f,0x3c,0x74,0x2f,0x3d,0x78,0x30,0x3f,0x7c,0x30,0x40,0x7f,0x30,0x41,0x83,0x30,0x42,0x86,0x30,0x44,0x8a,0x30,0x45,0x8e,0x30,0x46,0x91,0x30,0x48,0x95,0x30,0x49,0x99,0x30,0x4a,0x9c,0x2f,0x4c,0xa0,0x2f,0x4d,0xa4,0x2f,0x4e,0xa8,0x2e,0x50,0xab,0x2e,0x51,0xaf,0x2d,0x52,0xb3,0x2c,0x54,0xb7,0x2c,0x55,0xbb,0x2b,0x56,0xbf,0x2a,0x58,0xc2,0x29,0x59,0xc6,0x28,0x5a,0xca,0x27,0x5c,0xce,0x26,0x5d,0xd2,0x25,0x5f,0xd5,0x24,0x60,0xd9,0x24,0x61,0xdd,0x23,0x63,0xe0,0x23,0x64,0xe3,0x23,0x66,0xe7,0x24,0x67,0xea,0x25,0x69,0xec,0x27,0x6a,0xef,0x29,0x6c,0xf1,0x2c,0x6d,0xf4,0x2f,0x6f,0xf5,0x33,0x70,0xf7,0x37,0x72,0xf9,0x3b,0x73,0xfa,0x3f,0x75,0xfb,0x44,0x76,0xfb,0x48,0x78,0xfc,0x4c,0x7a,0xfc,0x51,0x7b,0xfc,0x55,0x7d,0xfc,0x59,0x7f,0xfc,0x5d,0x80,0xfc,0x61,0x82,0xfc,0x65,0x84,0xfc,0x68,0x85,0xfc,0x6c,0x87,0xfb,0x6f,0x89,0xfb,0x73,0x8b,0xfa,0x76,0x8c,0xfa,0x79,0x8e,0xfa,0x7d,0x90,0xf9,0x80,0x92,0xf9,0x83,0x93,0xf8,0x86,0x95,0xf8,0x88,0x97,0xf7,0x8b,0x99,0xf7,0x8e,0x9b,0xf6,0x91,0x9c,0xf6,0x93,0x9e,0xf5,0x96,0xa0,0xf5,0x99,0xa2,0xf5,0x9b,0xa4,0xf4,0x9e,0xa5,0xf4,0xa0,0xa7,0xf3,0xa3,0xa9,0xf3,0xa5,0xab,0xf2,0xa8,0xad,0xf2,0xaa,0xaf,0xf1,0xac,0xb1,0xf1,0xaf,0xb2,0xf0,0xb1,0xb4,0xf0,0xb3,0xb6,0xef,0xb5,0xb8,0xef,0xb8,0xba,0xee,0xba,0xbc,0xee,0xbc,0xbe,0xed,0xbe,0xc0,0xed,0xc0,0xc1,0xec,0xc2,0xc3,0xeb,0xc4,0xc5,0xeb,0xc6,0xc7,0xea,0xc9,0xc9,0xea,0xcb,0xcb,0xe9,0xcd,0xcc,0xe8,0xce,0xce,0xe8,0xd0,0xd0,0xe7,0xd2,0xd1,0xe6,0xd4,0xd3,0xe5,0xd6,0xd4,0xe4,0xd8,0xd5,0xe3,0xd9,0xd6,0xe2,0xdb,0xd7,0xe1,0xdc,0xd7,0xe0,0xde,0xd7,0xde,0xdf,0xd7,0xdc}; - static constexpr std::array C4 = {0xdf,0xd5,0xd8,0xe0,0xd5,0xd6,0xe1,0xd4,0xd4,0xe2,0xd3,0xd2,0xe3,0xd1,0xcf,0xe3,0xd0,0xcc,0xe4,0xce,0xc9,0xe5,0xcc,0xc6,0xe5,0xca,0xc3,0xe5,0xc8,0xc0,0xe6,0xc5,0xbd,0xe6,0xc3,0xb9,0xe6,0xc0,0xb6,0xe6,0xbd,0xb2,0xe6,0xbb,0xaf,0xe6,0xb8,0xab,0xe6,0xb5,0xa8,0xe6,0xb2,0xa4,0xe6,0xb0,0xa1,0xe6,0xad,0x9d,0xe6,0xaa,0x9a,0xe6,0xa7,0x96,0xe5,0xa4,0x93,0xe5,0xa2,0x8f,0xe5,0x9f,0x8c,0xe5,0x9c,0x88,0xe4,0x99,0x85,0xe4,0x96,0x81,0xe3,0x93,0x7e,0xe3,0x91,0x7b,0xe2,0x8e,0x77,0xe2,0x8b,0x74,0xe1,0x88,0x70,0xe1,0x85,0x6d,0xe0,0x82,0x6a,0xe0,0x7f,0x66,0xdf,0x7c,0x63,0xde,0x7a,0x60,0xdd,0x77,0x5c,0xdd,0x74,0x59,0xdc,0x71,0x56,0xdb,0x6e,0x52,0xda,0x6b,0x4f,0xda,0x68,0x4c,0xd9,0x65,0x48,0xd8,0x62,0x45,0xd7,0x5e,0x42,0xd6,0x5b,0x3f,0xd5,0x58,0x3c,0xd4,0x55,0x38,0xd3,0x52,0x35,0xd2,0x4f,0x32,0xd1,0x4c,0x2f,0xd0,0x48,0x2c,0xcf,0x45,0x29,0xce,0x42,0x26,0xcd,0x3f,0x24,0xcd,0x3c,0x21,0xcc,0x3a,0x1f,0xcb,0x37,0x1d,0xca,0x35,0x1b,0xca,0x33,0x19,0xca,0x32,0x18,0xc9,0x31,0x17,0xc9,0x31,0x17,0xc9,0x31,0x17,0xc9,0x31,0x18,0xca,0x32,0x18,0xca,0x34,0x1a,0xcb,0x36,0x1b,0xcb,0x38,0x1d,0xcc,0x3a,0x1f,0xcd,0x3d,0x22,0xce,0x40,0x24,0xcf,0x43,0x27,0xcf,0x46,0x2a,0xd0,0x49,0x2d,0xd1,0x4c,0x30,0xd2,0x50,0x33,0xd3,0x53,0x36,0xd4,0x56,0x39,0xd5,0x59,0x3c,0xd6,0x5c,0x40,0xd7,0x5f,0x43,0xd8,0x62,0x46,0xd9,0x65,0x49,0xda,0x69,0x4d,0xdb,0x6c,0x50,0xdb,0x6f,0x53,0xdc,0x72,0x56,0xdd,0x74,0x5a,0xde,0x77,0x5d,0xde,0x7a,0x60,0xdf,0x7d,0x64,0xe0,0x80,0x67,0xe0,0x83,0x6a,0xe1,0x86,0x6e,0xe1,0x89,0x71,0xe2,0x8c,0x75,0xe3,0x8f,0x78,0xe3,0x91,0x7b,0xe3,0x94,0x7f,0xe4,0x97,0x82,0xe4,0x9a,0x86,0xe5,0x9d,0x89,0xe5,0xa0,0x8d,0xe5,0xa2,0x90,0xe6,0xa5,0x94,0xe6,0xa8,0x97,0xe6,0xab,0x9b,0xe6,0xae,0x9e,0xe6,0xb0,0xa2,0xe6,0xb3,0xa5,0xe6,0xb6,0xa9,0xe6,0xb9,0xac,0xe6,0xbb,0xb0,0xe6,0xbe,0xb3,0xe6,0xc0,0xb7,0xe6,0xc3,0xba,0xe5,0xc5,0xbe,0xe5,0xc7,0xc1,0xe4,0xca,0xc4,0xe3,0xcb,0xc7,0xe2,0xcd,0xcb,0xe1,0xcf,0xcd,0xe0,0xd0,0xd0,0xdf,0xd1,0xd3,0xde,0xd1,0xd5,0xdc,0xd2,0xd7,0xdb,0xd2,0xd9,0xd9,0xd1,0xdb,0xd7,0xd1,0xdd,0xd5,0xd0,0xde,0xd3,0xcf,0xdf,0xd1,0xce,0xe0,0xcf,0xcc,0xe1,0xcd,0xcb,0xe2,0xca,0xc9,0xe2,0xc8,0xc7,0xe3,0xc6,0xc5,0xe3,0xc3,0xc3,0xe4,0xc1,0xc1,0xe4,0xbe,0xbf,0xe4,0xbc,0xbd,0xe4,0xb9,0xbb,0xe4,0xb7,0xb8,0xe4,0xb4,0xb6,0xe5,0xb2,0xb4,0xe5,0xaf,0xb2,0xe5,0xad,0xaf,0xe5,0xaa,0xad,0xe5,0xa7,0xab,0xe5,0xa5,0xa9,0xe5,0xa2,0xa7,0xe5,0x9f,0xa4,0xe5,0x9d,0xa2,0xe5,0x9a,0xa0,0xe5,0x97,0x9e,0xe5,0x94,0x9c,0xe5,0x91,0x99,0xe5,0x8f,0x97,0xe5,0x8c,0x95,0xe5,0x89,0x93,0xe5,0x86,0x91,0xe5,0x83,0x8f,0xe5,0x7f,0x8d,0xe5,0x7c,0x8a,0xe5,0x79,0x88,0xe5,0x76,0x86,0xe5,0x72,0x84,0xe5,0x6f,0x82,0xe5,0x6b,0x80,0xe5,0x68,0x7e,0xe5,0x64,0x7c,0xe5,0x60,0x7a,0xe5,0x5c,0x78,0xe5,0x58,0x76,0xe5,0x54,0x74,0xe5,0x4f,0x72,0xe5,0x4b,0x70,0xe5,0x46,0x6e,0xe5,0x41,0x6d,0xe5,0x3c,0x6b,0xe5,0x37,0x6a,0xe5,0x32,0x68,0xe5,0x2d,0x67,0xe5,0x28,0x66,0xe5,0x23,0x65,0xe5,0x1f,0x64,0xe5,0x1c,0x64,0xe5,0x1a,0x63,0xe5,0x19,0x63,0xe5,0x1a,0x63,0xe5,0x1d,0x64,0xe5,0x20,0x64,0xe5,0x24,0x65,0xe5,0x29,0x66,0xe5,0x2e,0x67,0xe5,0x33,0x68,0xe5,0x38,0x6a,0xe5,0x3d,0x6b,0xe5,0x42,0x6d,0xe5,0x47,0x6f,0xe5,0x4c,0x71,0xe5,0x50,0x72,0xe5,0x55,0x74,0xe5,0x59,0x76,0xe5,0x5d,0x78,0xe5,0x61,0x7a,0xe5,0x65,0x7c,0xe5,0x68,0x7e,0xe5,0x6c,0x80,0xe5,0x70,0x83,0xe5,0x73,0x85,0xe5,0x76,0x87,0xe5,0x7a,0x89,0xe5,0x7d,0x8b,0xe5,0x80,0x8d,0xe5,0x83,0x8f,0xe5,0x86,0x91,0xe5,0x89,0x93,0xe5,0x8c,0x96,0xe5,0x8f,0x98,0xe5,0x92,0x9a,0xe5,0x95,0x9c,0xe5,0x98,0x9e,0xe5,0x9b,0xa0,0xe5,0x9d,0xa3,0xe5,0xa0,0xa5,0xe5,0xa3,0xa7,0xe5,0xa5,0xa9,0xe5,0xa8,0xab,0xe5,0xab,0xae,0xe5,0xad,0xb0,0xe5,0xb0,0xb2,0xe5,0xb2,0xb4,0xe5,0xb5,0xb7,0xe5,0xb7,0xb9,0xe4,0xba,0xbb,0xe4,0xbc,0xbd,0xe4,0xbf,0xc0,0xe4,0xc1,0xc2,0xe4,0xc4,0xc4,0xe4,0xc6,0xc6,0xe4,0xc8,0xc8,0xe3,0xcb,0xca,0xe3,0xcd,0xcc,0xe3,0xcf,0xce,0xe2,0xd1,0xd0,0xe2,0xd3,0xd1,0xe1,0xd5,0xd2,0xe0,0xd7,0xd3,0xe0,0xd9,0xd4,0xdf,0xda,0xd5,0xdd,0xdc,0xd5,0xdc,0xdd,0xd5,0xda}; - static constexpr std::array C5 = {0x78,0x78,0x78,0x79,0x79,0x79,0x7a,0x7a,0x7a,0x7b,0x7b,0x7b,0x7d,0x7d,0x7d,0x7e,0x7e,0x7e,0x7f,0x7f,0x7f,0x81,0x81,0x81,0x82,0x82,0x82,0x83,0x83,0x83,0x85,0x85,0x85,0x86,0x86,0x86,0x87,0x87,0x87,0x89,0x89,0x89,0x8a,0x8a,0x8a,0x8c,0x8c,0x8c,0x8d,0x8d,0x8d,0x8e,0x8e,0x8e,0x90,0x90,0x90,0x91,0x91,0x91,0x93,0x93,0x93,0x94,0x94,0x94,0x95,0x95,0x95,0x97,0x97,0x97,0x98,0x98,0x98,0x9a,0x9a,0x9a,0x9b,0x9b,0x9b,0x9d,0x9d,0x9d,0x9e,0x9e,0x9e,0x9f,0x9f,0x9f,0xa1,0xa1,0xa1,0xa2,0xa2,0xa2,0xa4,0xa4,0xa4,0xa5,0xa5,0xa5,0xa7,0xa7,0xa7,0xa8,0xa8,0xa8,0xaa,0xaa,0xaa,0xab,0xab,0xab,0xac,0xac,0xac,0xae,0xae,0xae,0xaf,0xaf,0xaf,0xb1,0xb1,0xb1,0xb2,0xb2,0xb2,0xb4,0xb4,0xb4,0xb5,0xb5,0xb5,0xb7,0xb7,0xb7,0xb8,0xb8,0xb8,0xba,0xba,0xba,0xbb,0xbb,0xbb,0xbc,0xbd,0xbd,0xbe,0xbe,0xbe,0xbf,0xbf,0xbf,0xc1,0xc1,0xc1,0xc2,0xc2,0xc2,0xc3,0xc3,0xc3,0xc4,0xc4,0xc4,0xc6,0xc6,0xc6,0xc7,0xc7,0xc7,0xc8,0xc8,0xc8,0xc8,0xc8,0xc8,0xc9,0xc9,0xc9,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xca,0xc9,0xc9,0xc9,0xc9,0xc9,0xc9,0xc8,0xc8,0xc8,0xc7,0xc7,0xc7,0xc6,0xc6,0xc6,0xc5,0xc5,0xc5,0xc4,0xc4,0xc4,0xc2,0xc2,0xc2,0xc1,0xc1,0xc1,0xc0,0xc0,0xc0,0xbe,0xbe,0xbe,0xbd,0xbd,0xbd,0xbb,0xbb,0xbb,0xba,0xba,0xba,0xb8,0xb9,0xb9,0xb7,0xb7,0xb7,0xb6,0xb6,0xb6,0xb4,0xb4,0xb4,0xb3,0xb3,0xb3,0xb1,0xb1,0xb1,0xb0,0xb0,0xb0,0xae,0xae,0xae,0xad,0xad,0xad,0xab,0xab,0xab,0xaa,0xaa,0xaa,0xa8,0xa8,0xa8,0xa7,0xa7,0xa7,0xa6,0xa6,0xa6,0xa4,0xa4,0xa4,0xa3,0xa3,0xa3,0xa1,0xa1,0xa1,0xa0,0xa0,0xa0,0x9e,0x9e,0x9e,0x9d,0x9d,0x9d,0x9b,0x9c,0x9c,0x9a,0x9a,0x9a,0x99,0x99,0x99,0x97,0x97,0x97,0x96,0x96,0x96,0x94,0x94,0x94,0x93,0x93,0x93,0x92,0x92,0x92,0x90,0x90,0x90,0x8f,0x8f,0x8f,0x8d,0x8d,0x8d,0x8c,0x8c,0x8c,0x8b,0x8b,0x8b,0x89,0x89,0x89,0x88,0x88,0x88,0x86,0x86,0x86,0x85,0x85,0x85,0x84,0x84,0x84,0x82,0x82,0x82,0x81,0x81,0x81,0x7f,0x7f,0x7f,0x7e,0x7e,0x7e,0x7d,0x7d,0x7d,0x7b,0x7b,0x7b,0x7a,0x7a,0x7a,0x79,0x79,0x79,0x77,0x77,0x77,0x76,0x76,0x76,0x75,0x75,0x75,0x73,0x73,0x73,0x72,0x72,0x72,0x70,0x70,0x70,0x6f,0x6f,0x6f,0x6e,0x6e,0x6e,0x6c,0x6c,0x6c,0x6b,0x6b,0x6b,0x6a,0x6a,0x6a,0x68,0x68,0x68,0x67,0x67,0x67,0x66,0x66,0x66,0x64,0x64,0x64,0x63,0x63,0x63,0x62,0x62,0x62,0x61,0x61,0x61,0x5f,0x5f,0x5f,0x5e,0x5e,0x5e,0x5d,0x5d,0x5d,0x5b,0x5b,0x5b,0x5a,0x5a,0x5a,0x59,0x59,0x59,0x57,0x57,0x57,0x56,0x56,0x56,0x55,0x55,0x55,0x54,0x54,0x54,0x52,0x52,0x52,0x51,0x51,0x51,0x50,0x50,0x50,0x4e,0x4e,0x4e,0x4d,0x4d,0x4d,0x4c,0x4c,0x4c,0x4b,0x4b,0x4b,0x49,0x49,0x49,0x48,0x48,0x48,0x47,0x47,0x47,0x46,0x46,0x46,0x44,0x44,0x44,0x43,0x43,0x43,0x42,0x42,0x42,0x41,0x41,0x41,0x40,0x40,0x40,0x3e,0x3e,0x3e,0x3d,0x3d,0x3d,0x3c,0x3c,0x3c,0x3b,0x3b,0x3b,0x3a,0x3a,0x3a,0x38,0x38,0x38,0x37,0x37,0x37,0x36,0x36,0x36,0x35,0x35,0x35,0x34,0x34,0x34,0x33,0x33,0x33,0x32,0x32,0x32,0x31,0x31,0x31,0x30,0x30,0x30,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x2e,0x2e,0x2e,0x2e,0x2e,0x2e,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2d,0x2e,0x2e,0x2e,0x2e,0x2e,0x2e,0x2f,0x2f,0x2f,0x2f,0x2f,0x2f,0x30,0x30,0x30,0x31,0x31,0x31,0x32,0x32,0x32,0x33,0x33,0x33,0x34,0x34,0x34,0x35,0x35,0x35,0x36,0x36,0x36,0x37,0x37,0x37,0x38,0x38,0x38,0x39,0x39,0x39,0x3a,0x3a,0x3a,0x3c,0x3c,0x3c,0x3d,0x3d,0x3d,0x3e,0x3e,0x3e,0x3f,0x3f,0x3f,0x40,0x41,0x40,0x42,0x42,0x42,0x43,0x43,0x43,0x44,0x44,0x44,0x45,0x45,0x45,0x47,0x47,0x47,0x48,0x48,0x48,0x49,0x49,0x49,0x4a,0x4a,0x4a,0x4c,0x4c,0x4c,0x4d,0x4d,0x4d,0x4e,0x4e,0x4e,0x4f,0x4f,0x4f,0x51,0x51,0x51,0x52,0x52,0x52,0x53,0x53,0x53,0x55,0x55,0x55,0x56,0x56,0x56,0x57,0x57,0x57,0x58,0x58,0x58,0x5a,0x5a,0x5a,0x5b,0x5b,0x5b,0x5c,0x5c,0x5c,0x5e,0x5e,0x5e,0x5f,0x5f,0x5f,0x60,0x60,0x60,0x61,0x62,0x62,0x63,0x63,0x63,0x64,0x64,0x64,0x65,0x65,0x65,0x67,0x67,0x67,0x68,0x68,0x68,0x69,0x69,0x69,0x6b,0x6b,0x6b,0x6c,0x6c,0x6c,0x6d,0x6d,0x6d,0x6f,0x6f,0x6f,0x70,0x70,0x70,0x71,0x71,0x71,0x72,0x72,0x72,0x74,0x74,0x74,0x75,0x75,0x75,0x76,0x76,0x76}; - static constexpr std::array C6 = {0xf7,0x37,0x1a,0xf6,0x38,0x17,0xf6,0x3a,0x15,0xf6,0x3d,0x12,0xf7,0x40,0x10,0xf7,0x44,0x0e,0xf7,0x48,0x0c,0xf8,0x4c,0x0a,0xf8,0x50,0x08,0xf8,0x55,0x07,0xf9,0x59,0x06,0xf9,0x5e,0x05,0xfa,0x62,0x04,0xfb,0x67,0x03,0xfb,0x6b,0x02,0xfc,0x70,0x02,0xfc,0x74,0x01,0xfd,0x78,0x01,0xfd,0x7d,0x00,0xfe,0x81,0x00,0xfe,0x85,0x00,0xfe,0x89,0x00,0xff,0x8d,0x00,0xff,0x91,0x00,0xff,0x95,0x00,0xff,0x99,0x00,0xff,0x9d,0x00,0xff,0xa1,0x00,0xff,0xa5,0x00,0xff,0xa8,0x00,0xff,0xac,0x00,0xff,0xb0,0x00,0xff,0xb3,0x00,0xff,0xb7,0x00,0xff,0xba,0x00,0xff,0xbd,0x00,0xfe,0xc1,0x00,0xfd,0xc3,0x00,0xfc,0xc6,0x00,0xfb,0xc9,0x00,0xf9,0xcb,0x00,0xf7,0xcd,0x00,0xf5,0xce,0x00,0xf2,0xd0,0x00,0xef,0xd0,0x00,0xec,0xd1,0x00,0xe9,0xd1,0x00,0xe5,0xd1,0x00,0xe1,0xd1,0x00,0xdd,0xd0,0x00,0xd9,0xd0,0x00,0xd5,0xcf,0x00,0xd1,0xcd,0x00,0xcc,0xcc,0x00,0xc8,0xcb,0x00,0xc3,0xc9,0x00,0xbf,0xc7,0x00,0xba,0xc5,0x00,0xb5,0xc4,0x00,0xb1,0xc2,0x00,0xac,0xc0,0x00,0xa7,0xbe,0x00,0xa2,0xbc,0x00,0x9e,0xba,0x00,0x99,0xb8,0x00,0x94,0xb6,0x00,0x8f,0xb4,0x00,0x8a,0xb2,0x01,0x86,0xb0,0x01,0x81,0xae,0x02,0x7c,0xac,0x02,0x77,0xaa,0x03,0x72,0xa9,0x03,0x6d,0xa7,0x04,0x68,0xa5,0x06,0x64,0xa3,0x07,0x5f,0xa1,0x09,0x5a,0xa0,0x0b,0x55,0x9e,0x0d,0x51,0x9d,0x10,0x4c,0x9c,0x12,0x48,0x9b,0x15,0x44,0x9a,0x18,0x40,0x9a,0x1b,0x3c,0x99,0x1e,0x39,0x99,0x22,0x36,0x99,0x26,0x33,0x9a,0x29,0x31,0x9b,0x2d,0x2f,0x9b,0x31,0x2d,0x9d,0x36,0x2c,0x9e,0x3a,0x2b,0xa0,0x3e,0x2b,0xa1,0x43,0x2b,0xa3,0x48,0x2b,0xa5,0x4c,0x2c,0xa7,0x51,0x2c,0xaa,0x56,0x2d,0xac,0x5b,0x2e,0xae,0x60,0x2e,0xb1,0x65,0x2f,0xb3,0x6a,0x30,0xb5,0x6f,0x30,0xb8,0x74,0x31,0xba,0x79,0x31,0xbd,0x7e,0x32,0xbf,0x83,0x32,0xc2,0x88,0x32,0xc4,0x8d,0x32,0xc7,0x92,0x32,0xca,0x97,0x32,0xcc,0x9c,0x32,0xcf,0xa1,0x32,0xd1,0xa6,0x31,0xd4,0xab,0x30,0xd6,0xb1,0x30,0xd8,0xb6,0x2f,0xdb,0xbb,0x2e,0xdd,0xc0,0x2d,0xdf,0xc5,0x2c,0xe1,0xca,0x2b,0xe3,0xce,0x2a,0xe4,0xd3,0x28,0xe6,0xd7,0x27,0xe7,0xdc,0x27,0xe8,0xe0,0x26,0xe8,0xe4,0x25,0xe8,0xe7,0x25,0xe8,0xeb,0x25,0xe8,0xee,0x26,0xe7,0xf0,0x26,0xe6,0xf3,0x27,0xe4,0xf5,0x28,0xe3,0xf7,0x29,0xe1,0xf9,0x2a,0xdf,0xfa,0x2b,0xdc,0xfb,0x2c,0xda,0xfc,0x2d,0xd7,0xfd,0x2e,0xd4,0xfe,0x2f,0xd1,0xfe,0x2f,0xce,0xff,0x30,0xcb,0xff,0x31,0xc8,0xff,0x31,0xc5,0xff,0x31,0xc2,0xff,0x31,0xbf,0xff,0x31,0xbc,0xff,0x31,0xb8,0xff,0x31,0xb5,0xff,0x30,0xb2,0xff,0x30,0xaf,0xff,0x2f,0xac,0xff,0x2e,0xa9,0xff,0x2d,0xa6,0xff,0x2c,0xa3,0xff,0x2b,0xa0,0xff,0x2a,0x9d,0xff,0x29,0x9a,0xff,0x28,0x97,0xff,0x28,0x94,0xff,0x27,0x91,0xff,0x28,0x8f,0xff,0x28,0x8c,0xff,0x29,0x8a,0xff,0x2b,0x88,0xff,0x2e,0x86,0xff,0x31,0x84,0xff,0x35,0x83,0xff,0x39,0x82,0xff,0x3e,0x81,0xff,0x43,0x80,0xff,0x48,0x80,0xff,0x4d,0x80,0xff,0x53,0x81,0xff,0x59,0x81,0xff,0x5e,0x82,0xff,0x64,0x83,0xff,0x69,0x84,0xff,0x6f,0x86,0xff,0x74,0x88,0xff,0x7a,0x89,0xff,0x7f,0x8b,0xff,0x84,0x8d,0xff,0x89,0x8f,0xff,0x8e,0x91,0xff,0x93,0x93,0xff,0x98,0x96,0xff,0x9d,0x98,0xff,0xa1,0x9a,0xff,0xa6,0x9c,0xff,0xaa,0x9f,0xff,0xae,0xa1,0xff,0xb3,0xa3,0xff,0xb7,0xa5,0xff,0xbb,0xa8,0xff,0xbf,0xaa,0xff,0xc4,0xac,0xff,0xc8,0xae,0xff,0xcc,0xb1,0xff,0xd0,0xb3,0xff,0xd4,0xb5,0xff,0xd8,0xb7,0xff,0xdb,0xb8,0xff,0xdf,0xba,0xff,0xe3,0xbc,0xff,0xe7,0xbd,0xfd,0xea,0xbe,0xfc,0xee,0xbf,0xfa,0xf1,0xbf,0xf7,0xf4,0xbf,0xf5,0xf7,0xbf,0xf2,0xfa,0xbe,0xee,0xfc,0xbd,0xea,0xff,0xbc,0xe7,0xff,0xbb,0xe2,0xff,0xb9,0xde,0xff,0xb7,0xd9,0xff,0xb4,0xd4,0xff,0xb2,0xcf,0xff,0xaf,0xca,0xff,0xac,0xc5,0xff,0xa9,0xbf,0xff,0xa5,0xba,0xff,0xa2,0xb4,0xff,0x9e,0xaf,0xff,0x9b,0xa9,0xff,0x97,0xa4,0xff,0x94,0x9e,0xff,0x90,0x99,0xff,0x8c,0x93,0xff,0x88,0x8e,0xff,0x85,0x89,0xff,0x81,0x83,0xff,0x7d,0x7e,0xff,0x79,0x79,0xff,0x75,0x73,0xff,0x71,0x6e,0xff,0x6d,0x69,0xff,0x69,0x64,0xff,0x65,0x5e,0xff,0x61,0x59,0xff,0x5c,0x54,0xff,0x58,0x4f,0xff,0x54,0x4a,0xff,0x50,0x45,0xfe,0x4c,0x41,0xfd,0x48,0x3c,0xfc,0x44,0x38,0xfb,0x41,0x33,0xfa,0x3d,0x2f,0xf9,0x3b,0x2b,0xf8,0x38,0x27,0xf8,0x37,0x24,0xf7,0x36,0x20,0xf7,0x36,0x1d}; - static constexpr std::array C7 = {0xe9,0xe4,0x19,0xeb,0xe3,0x1f,0xec,0xe2,0x26,0xee,0xe1,0x2b,0xef,0xdf,0x31,0xf0,0xde,0x37,0xf1,0xdc,0x3c,0xf2,0xda,0x41,0xf4,0xd8,0x46,0xf5,0xd5,0x4b,0xf6,0xd3,0x50,0xf6,0xd1,0x54,0xf7,0xcf,0x58,0xf8,0xcc,0x5c,0xf9,0xca,0x61,0xfa,0xc8,0x64,0xfb,0xc5,0x68,0xfb,0xc3,0x6c,0xfc,0xc1,0x70,0xfd,0xbe,0x73,0xfd,0xbc,0x77,0xfe,0xba,0x7a,0xff,0xb7,0x7e,0xff,0xb5,0x81,0xff,0xb2,0x84,0xff,0xb0,0x87,0xff,0xad,0x8b,0xff,0xab,0x8e,0xff,0xa8,0x91,0xff,0xa6,0x94,0xff,0xa3,0x97,0xff,0xa1,0x9a,0xff,0x9e,0x9d,0xff,0x9b,0xa0,0xff,0x99,0xa3,0xff,0x96,0xa6,0xff,0x93,0xa9,0xff,0x90,0xac,0xff,0x8e,0xaf,0xff,0x8b,0xb2,0xff,0x88,0xb5,0xff,0x85,0xb8,0xff,0x82,0xbb,0xff,0x7f,0xbe,0xff,0x7c,0xc1,0xff,0x79,0xc4,0xff,0x76,0xc7,0xff,0x72,0xc9,0xff,0x6f,0xcc,0xff,0x6c,0xcf,0xff,0x68,0xd2,0xff,0x65,0xd5,0xff,0x61,0xd8,0xff,0x5d,0xdb,0xff,0x5a,0xdd,0xff,0x56,0xe0,0xff,0x52,0xe3,0xff,0x4e,0xe6,0xff,0x4a,0xe9,0xff,0x47,0xeb,0xff,0x44,0xee,0xff,0x41,0xf0,0xfe,0x3f,0xf3,0xfd,0x3f,0xf5,0xfc,0x3f,0xf7,0xfb,0x40,0xf8,0xf9,0x42,0xfa,0xf8,0x45,0xfb,0xf7,0x48,0xfc,0xf5,0x4c,0xfd,0xf4,0x51,0xfd,0xf2,0x55,0xfe,0xf1,0x5a,0xfe,0xef,0x5e,0xfe,0xee,0x62,0xfe,0xec,0x67,0xfe,0xeb,0x6b,0xfe,0xe9,0x6f,0xfe,0xe7,0x73,0xfe,0xe6,0x77,0xfe,0xe4,0x7a,0xfe,0xe2,0x7e,0xfe,0xe0,0x81,0xfe,0xde,0x85,0xfe,0xdd,0x88,0xfe,0xdb,0x8b,0xfe,0xd9,0x8f,0xfe,0xd7,0x92,0xfe,0xd5,0x95,0xfe,0xd3,0x98,0xfe,0xd1,0x9b,0xfe,0xcf,0x9e,0xfe,0xcc,0xa1,0xfe,0xca,0xa4,0xfe,0xc8,0xa7,0xfe,0xc6,0xa9,0xfe,0xc3,0xac,0xfe,0xc1,0xaf,0xfe,0xbe,0xb2,0xfe,0xbc,0xb4,0xfe,0xb9,0xb7,0xfe,0xb7,0xba,0xfe,0xb4,0xbc,0xfe,0xb1,0xbf,0xfd,0xae,0xc1,0xfd,0xab,0xc4,0xfd,0xa8,0xc6,0xfd,0xa5,0xc9,0xfd,0xa2,0xcb,0xfd,0x9e,0xce,0xfd,0x9b,0xd0,0xfd,0x97,0xd3,0xfd,0x93,0xd5,0xfd,0x8f,0xd8,0xfd,0x8b,0xda,0xfd,0x87,0xdc,0xfd,0x82,0xdf,0xfd,0x7e,0xe1,0xfc,0x79,0xe3,0xfc,0x73,0xe5,0xfc,0x6e,0xe8,0xfc,0x68,0xea,0xfb,0x62,0xec,0xfb,0x5c,0xed,0xfa,0x55,0xef,0xf9,0x4f,0xf0,0xf8,0x48,0xf2,0xf6,0x41,0xf3,0xf5,0x3b,0xf3,0xf3,0x35,0xf3,0xf0,0x30,0xf3,0xee,0x2c,0xf3,0xeb,0x29,0xf3,0xe8,0x27,0xf2,0xe5,0x26,0xf1,0xe2,0x26,0xf0,0xdf,0x26,0xef,0xdb,0x27,0xee,0xd8,0x28,0xed,0xd5,0x29,0xec,0xd1,0x2b,0xea,0xce,0x2c,0xe9,0xca,0x2d,0xe8,0xc7,0x2e,0xe6,0xc3,0x2f,0xe5,0xc0,0x30,0xe4,0xbd,0x31,0xe3,0xb9,0x31,0xe1,0xb6,0x32,0xe0,0xb2,0x32,0xdf,0xaf,0x33,0xdd,0xac,0x33,0xdc,0xa8,0x33,0xdb,0xa5,0x34,0xda,0xa2,0x34,0xd8,0x9e,0x34,0xd7,0x9b,0x34,0xd6,0x97,0x34,0xd5,0x94,0x34,0xd3,0x91,0x33,0xd2,0x8d,0x33,0xd1,0x8a,0x33,0xcf,0x87,0x32,0xce,0x83,0x32,0xcd,0x80,0x31,0xcc,0x7c,0x31,0xca,0x79,0x30,0xc9,0x76,0x30,0xc8,0x72,0x2f,0xc7,0x6f,0x2e,0xc5,0x6c,0x2d,0xc4,0x68,0x2c,0xc3,0x65,0x2b,0xc2,0x61,0x2a,0xc0,0x5e,0x29,0xbf,0x5a,0x28,0xbe,0x57,0x27,0xbd,0x53,0x25,0xbb,0x50,0x24,0xba,0x4c,0x22,0xb9,0x48,0x21,0xb8,0x45,0x1f,0xb7,0x41,0x1e,0xb5,0x3d,0x1c,0xb4,0x39,0x1b,0xb3,0x35,0x1a,0xb2,0x31,0x1a,0xb1,0x2d,0x1b,0xb1,0x29,0x1c,0xb0,0x25,0x1e,0xaf,0x21,0x20,0xaf,0x1c,0x23,0xaf,0x18,0x27,0xaf,0x14,0x2b,0xaf,0x10,0x2f,0xaf,0x0c,0x33,0xb0,0x08,0x37,0xb1,0x05,0x3b,0xb1,0x02,0x3f,0xb2,0x00,0x44,0xb3,0x00,0x48,0xb4,0x00,0x4c,0xb5,0x00,0x4f,0xb6,0x00,0x53,0xb7,0x00,0x57,0xb8,0x00,0x5a,0xb9,0x00,0x5e,0xba,0x00,0x61,0xbb,0x00,0x65,0xbc,0x00,0x68,0xbd,0x00,0x6b,0xbe,0x00,0x6e,0xbf,0x00,0x72,0xc0,0x00,0x75,0xc1,0x00,0x78,0xc2,0x00,0x7b,0xc3,0x00,0x7e,0xc4,0x00,0x81,0xc5,0x00,0x84,0xc6,0x00,0x87,0xc7,0x00,0x8a,0xc8,0x00,0x8d,0xc9,0x00,0x90,0xca,0x00,0x93,0xcb,0x00,0x95,0xcc,0x00,0x98,0xcd,0x00,0x9b,0xce,0x00,0x9e,0xcf,0x00,0xa1,0xd0,0x00,0xa4,0xd1,0x00,0xa6,0xd2,0x00,0xa9,0xd3,0x00,0xac,0xd4,0x00,0xaf,0xd5,0x00,0xb2,0xd6,0x00,0xb4,0xd7,0x00,0xb7,0xd8,0x00,0xba,0xd9,0x00,0xbd,0xda,0x00,0xbf,0xdb,0x00,0xc2,0xdc,0x00,0xc5,0xdd,0x00,0xc7,0xde,0x00,0xca,0xde,0x00,0xcd,0xdf,0x00,0xd0,0xe0,0x00,0xd2,0xe1,0x00,0xd5,0xe2,0x00,0xd7,0xe3,0x00,0xda,0xe4,0x00,0xdc,0xe4,0x00,0xdf,0xe5,0x00,0xe1,0xe5,0x00,0xe3,0xe5,0x03,0xe5,0xe5,0x0b,0xe7,0xe5,0x12}; +// cyclic +static constexpr std::array C1 = { + 0xf9, 0x85, 0xf8, 0xfa, 0x84, 0xf6, 0xfb, 0x83, 0xf3, 0xfc, 0x82, 0xf1, 0xfc, 0x81, 0xee, 0xfd, + 0x7f, 0xeb, 0xfd, 0x7e, 0xe8, 0xfd, 0x7c, 0xe5, 0xfd, 0x7a, 0xe2, 0xfd, 0x78, 0xde, 0xfd, 0x76, + 0xdb, 0xfc, 0x74, 0xd7, 0xfc, 0x72, 0xd4, 0xfb, 0x70, 0xd0, 0xfb, 0x6d, 0xcc, 0xfa, 0x6b, 0xc8, + 0xfa, 0x69, 0xc5, 0xf9, 0x67, 0xc1, 0xf8, 0x64, 0xbd, 0xf7, 0x62, 0xb9, 0xf7, 0x5f, 0xb5, 0xf6, + 0x5d, 0xb2, 0xf5, 0x5b, 0xae, 0xf4, 0x58, 0xaa, 0xf3, 0x56, 0xa6, 0xf2, 0x54, 0xa3, 0xf1, 0x51, + 0x9f, 0xf0, 0x4f, 0x9b, 0xef, 0x4c, 0x97, 0xee, 0x4a, 0x94, 0xed, 0x48, 0x90, 0xec, 0x46, 0x8c, + 0xea, 0x43, 0x88, 0xe9, 0x41, 0x84, 0xe8, 0x3f, 0x81, 0xe6, 0x3d, 0x7d, 0xe5, 0x3b, 0x79, 0xe3, + 0x39, 0x75, 0xe1, 0x37, 0x71, 0xe0, 0x35, 0x6d, 0xde, 0x33, 0x6a, 0xdc, 0x31, 0x66, 0xda, 0x2f, + 0x62, 0xd9, 0x2d, 0x5e, 0xd7, 0x2c, 0x5a, 0xd5, 0x2a, 0x56, 0xd3, 0x28, 0x53, 0xd1, 0x26, 0x4f, + 0xcf, 0x24, 0x4b, 0xcd, 0x23, 0x47, 0xcb, 0x21, 0x44, 0xc9, 0x1f, 0x40, 0xc7, 0x1e, 0x3c, 0xc6, + 0x1c, 0x39, 0xc4, 0x1b, 0x35, 0xc2, 0x19, 0x32, 0xc0, 0x18, 0x2e, 0xbe, 0x17, 0x2b, 0xbd, 0x17, + 0x27, 0xbb, 0x17, 0x24, 0xba, 0x17, 0x21, 0xb9, 0x17, 0x1e, 0xb8, 0x18, 0x1b, 0xb7, 0x19, 0x19, + 0xb6, 0x1b, 0x16, 0xb5, 0x1d, 0x14, 0xb5, 0x1f, 0x11, 0xb5, 0x21, 0x0f, 0xb5, 0x23, 0x0d, 0xb5, + 0x26, 0x0c, 0xb5, 0x29, 0x0a, 0xb6, 0x2b, 0x08, 0xb6, 0x2e, 0x07, 0xb7, 0x31, 0x06, 0xb8, 0x33, + 0x06, 0xb8, 0x36, 0x05, 0xb9, 0x39, 0x05, 0xba, 0x3b, 0x05, 0xbb, 0x3e, 0x04, 0xbc, 0x41, 0x04, + 0xbd, 0x43, 0x04, 0xbe, 0x46, 0x04, 0xbf, 0x48, 0x04, 0xc0, 0x4b, 0x04, 0xc1, 0x4d, 0x04, 0xc2, + 0x50, 0x04, 0xc3, 0x52, 0x04, 0xc4, 0x54, 0x04, 0xc5, 0x57, 0x04, 0xc6, 0x59, 0x05, 0xc7, 0x5c, + 0x05, 0xc8, 0x5e, 0x05, 0xc9, 0x60, 0x05, 0xca, 0x63, 0x05, 0xca, 0x65, 0x05, 0xcb, 0x67, 0x05, + 0xcc, 0x6a, 0x05, 0xcd, 0x6c, 0x05, 0xce, 0x6f, 0x05, 0xce, 0x71, 0x05, 0xcf, 0x73, 0x05, 0xd0, + 0x76, 0x05, 0xd0, 0x78, 0x05, 0xd1, 0x7a, 0x05, 0xd1, 0x7d, 0x05, 0xd2, 0x7f, 0x04, 0xd2, 0x81, + 0x04, 0xd3, 0x84, 0x04, 0xd3, 0x86, 0x04, 0xd4, 0x89, 0x04, 0xd4, 0x8b, 0x04, 0xd5, 0x8d, 0x04, + 0xd5, 0x8f, 0x04, 0xd6, 0x92, 0x04, 0xd6, 0x94, 0x05, 0xd6, 0x96, 0x05, 0xd6, 0x98, 0x06, 0xd7, + 0x9b, 0x07, 0xd7, 0x9d, 0x08, 0xd7, 0x9f, 0x0a, 0xd7, 0xa0, 0x0d, 0xd6, 0xa2, 0x0f, 0xd6, 0xa4, + 0x12, 0xd5, 0xa5, 0x15, 0xd5, 0xa7, 0x18, 0xd4, 0xa8, 0x1c, 0xd2, 0xa9, 0x1f, 0xd1, 0xaa, 0x23, + 0xd0, 0xaa, 0x27, 0xce, 0xaa, 0x2b, 0xcc, 0xab, 0x2f, 0xca, 0xab, 0x33, 0xc7, 0xaa, 0x37, 0xc5, + 0xaa, 0x3b, 0xc2, 0xa9, 0x3f, 0xbf, 0xa9, 0x43, 0xbc, 0xa8, 0x46, 0xb9, 0xa7, 0x4a, 0xb6, 0xa6, + 0x4e, 0xb3, 0xa5, 0x52, 0xaf, 0xa4, 0x55, 0xac, 0xa3, 0x59, 0xa9, 0xa1, 0x5c, 0xa5, 0xa0, 0x60, + 0xa1, 0x9f, 0x63, 0x9d, 0x9e, 0x66, 0x9a, 0x9d, 0x69, 0x96, 0x9b, 0x6d, 0x92, 0x9a, 0x70, 0x8e, + 0x99, 0x73, 0x89, 0x98, 0x76, 0x85, 0x96, 0x79, 0x81, 0x95, 0x7c, 0x7c, 0x94, 0x7f, 0x77, 0x93, + 0x82, 0x73, 0x91, 0x85, 0x6e, 0x90, 0x88, 0x69, 0x8f, 0x8b, 0x63, 0x8d, 0x8e, 0x5e, 0x8c, 0x91, + 0x59, 0x8b, 0x94, 0x53, 0x89, 0x97, 0x4e, 0x88, 0x9a, 0x48, 0x86, 0x9d, 0x43, 0x84, 0xa0, 0x3e, + 0x83, 0xa3, 0x39, 0x81, 0xa6, 0x34, 0x7f, 0xa9, 0x2f, 0x7d, 0xac, 0x2b, 0x7b, 0xaf, 0x28, 0x79, + 0xb2, 0x25, 0x76, 0xb5, 0x23, 0x74, 0xb8, 0x22, 0x71, 0xbb, 0x22, 0x6f, 0xbe, 0x22, 0x6c, 0xc1, + 0x22, 0x69, 0xc5, 0x24, 0x66, 0xc8, 0x25, 0x63, 0xcb, 0x26, 0x60, 0xce, 0x28, 0x5d, 0xd1, 0x29, + 0x5a, 0xd4, 0x2b, 0x57, 0xd7, 0x2d, 0x54, 0xda, 0x2e, 0x51, 0xdd, 0x30, 0x4e, 0xe0, 0x31, 0x4b, + 0xe3, 0x33, 0x49, 0xe5, 0x35, 0x46, 0xe8, 0x37, 0x44, 0xea, 0x39, 0x42, 0xec, 0x3c, 0x40, 0xee, + 0x3e, 0x3f, 0xf0, 0x41, 0x3e, 0xf2, 0x44, 0x3d, 0xf3, 0x47, 0x3d, 0xf4, 0x49, 0x3d, 0xf5, 0x4c, + 0x3d, 0xf6, 0x4f, 0x3e, 0xf7, 0x52, 0x3f, 0xf7, 0x55, 0x40, 0xf8, 0x58, 0x41, 0xf8, 0x5b, 0x43, + 0xf9, 0x5e, 0x45, 0xf9, 0x61, 0x47, 0xf9, 0x63, 0x49, 0xf9, 0x66, 0x4b, 0xf9, 0x69, 0x4d, 0xf9, + 0x6b, 0x4f, 0xf9, 0x6e, 0x51, 0xf9, 0x70, 0x53, 0xf9, 0x73, 0x55, 0xf9, 0x75, 0x57, 0xf9, 0x77, + 0x59, 0xf9, 0x7a, 0x5b, 0xfa, 0x7c, 0x5d, 0xfa, 0x7f, 0x5e, 0xfa, 0x82, 0x60, 0xfa, 0x84, 0x62, + 0xfa, 0x87, 0x64, 0xfa, 0x8a, 0x65, 0xfa, 0x8d, 0x67, 0xfa, 0x90, 0x69, 0xfa, 0x93, 0x6a, 0xfa, + 0x96, 0x6b, 0xfb, 0x99, 0x6d, 0xfb, 0x9c, 0x6e, 0xfb, 0xa0, 0x6f, 0xfb, 0xa3, 0x71, 0xfb, 0xa7, + 0x72, 0xfc, 0xaa, 0x73, 0xfc, 0xae, 0x74, 0xfc, 0xb1, 0x75, 0xfc, 0xb5, 0x76, 0xfd, 0xb9, 0x77, + 0xfd, 0xbc, 0x78, 0xfd, 0xc0, 0x79, 0xfe, 0xc3, 0x7a, 0xfe, 0xc7, 0x7b, 0xfe, 0xca, 0x7c, 0xff, + 0xce, 0x7d, 0xff, 0xd1, 0x7e, 0xff, 0xd5, 0x7f, 0xff, 0xd8, 0x80, 0xff, 0xdb, 0x81, 0xff, 0xdf, + 0x82, 0xff, 0xe2, 0x83, 0xff, 0xe5, 0x84, 0xff, 0xe8, 0x84, 0xff, 0xea, 0x85, 0xff, 0xed, 0x85, + 0xff, 0xf0, 0x86, 0xfe, 0xf2, 0x86, 0xfd, 0xf4, 0x86, 0xfc, 0xf6, 0x86, 0xfb, 0xf7, 0x85, 0xf9 +}; +static constexpr std::array C2 = { + 0xef, 0x55, 0xf2, 0xf1, 0x57, 0xf0, 0xf2, 0x5a, 0xef, 0xf3, 0x5d, 0xed, 0xf5, 0x5f, 0xeb, 0xf6, + 0x62, 0xe9, 0xf6, 0x65, 0xe7, 0xf7, 0x68, 0xe5, 0xf8, 0x6b, 0xe2, 0xf9, 0x6f, 0xe0, 0xf9, 0x72, + 0xde, 0xfa, 0x75, 0xdb, 0xfa, 0x78, 0xd9, 0xfa, 0x7b, 0xd6, 0xfb, 0x7e, 0xd3, 0xfb, 0x81, 0xd1, + 0xfb, 0x84, 0xce, 0xfb, 0x87, 0xcb, 0xfb, 0x8a, 0xc9, 0xfc, 0x8d, 0xc6, 0xfc, 0x90, 0xc3, 0xfc, + 0x93, 0xc0, 0xfc, 0x95, 0xbe, 0xfc, 0x98, 0xbb, 0xfc, 0x9b, 0xb8, 0xfc, 0x9e, 0xb5, 0xfc, 0xa0, + 0xb3, 0xfc, 0xa3, 0xb0, 0xfc, 0xa6, 0xad, 0xfc, 0xa8, 0xaa, 0xfc, 0xab, 0xa7, 0xfc, 0xad, 0xa5, + 0xfc, 0xb0, 0xa2, 0xfb, 0xb2, 0x9f, 0xfb, 0xb5, 0x9c, 0xfb, 0xb7, 0x99, 0xfb, 0xb9, 0x96, 0xfc, + 0xbc, 0x93, 0xfc, 0xbe, 0x90, 0xfc, 0xc0, 0x8d, 0xfc, 0xc3, 0x8a, 0xfc, 0xc5, 0x87, 0xfc, 0xc7, + 0x84, 0xfc, 0xc9, 0x81, 0xfc, 0xcc, 0x7e, 0xfc, 0xce, 0x7b, 0xfc, 0xd0, 0x78, 0xfc, 0xd2, 0x75, + 0xfc, 0xd4, 0x71, 0xfc, 0xd6, 0x6e, 0xfc, 0xd8, 0x6b, 0xfc, 0xda, 0x67, 0xfc, 0xdd, 0x64, 0xfb, + 0xdf, 0x60, 0xfb, 0xe0, 0x5c, 0xfb, 0xe2, 0x58, 0xfa, 0xe4, 0x55, 0xfa, 0xe6, 0x51, 0xf9, 0xe7, + 0x4d, 0xf8, 0xe9, 0x49, 0xf7, 0xea, 0x45, 0xf5, 0xeb, 0x41, 0xf4, 0xec, 0x3d, 0xf2, 0xed, 0x39, + 0xf1, 0xee, 0x35, 0xef, 0xee, 0x32, 0xed, 0xee, 0x2e, 0xea, 0xef, 0x2b, 0xe8, 0xee, 0x28, 0xe6, + 0xee, 0x25, 0xe3, 0xee, 0x23, 0xe1, 0xed, 0x21, 0xde, 0xed, 0x1f, 0xdb, 0xec, 0x1d, 0xd8, 0xeb, + 0x1b, 0xd6, 0xea, 0x1a, 0xd3, 0xe9, 0x19, 0xd0, 0xe8, 0x18, 0xcd, 0xe7, 0x18, 0xca, 0xe6, 0x17, + 0xc7, 0xe5, 0x16, 0xc4, 0xe4, 0x16, 0xc1, 0xe3, 0x15, 0xbe, 0xe2, 0x15, 0xbb, 0xe1, 0x15, 0xb8, + 0xe0, 0x14, 0xb5, 0xdf, 0x14, 0xb2, 0xde, 0x13, 0xaf, 0xdd, 0x13, 0xac, 0xdc, 0x13, 0xa9, 0xda, + 0x12, 0xa6, 0xd9, 0x12, 0xa3, 0xd8, 0x12, 0xa0, 0xd7, 0x11, 0x9d, 0xd6, 0x11, 0x9a, 0xd5, 0x11, + 0x97, 0xd4, 0x10, 0x94, 0xd3, 0x10, 0x91, 0xd2, 0x10, 0x8d, 0xd0, 0x0f, 0x8a, 0xcf, 0x0f, 0x87, + 0xce, 0x0f, 0x84, 0xcd, 0x0e, 0x81, 0xcc, 0x0e, 0x7d, 0xcb, 0x0e, 0x7a, 0xca, 0x0d, 0x77, 0xc8, + 0x0d, 0x73, 0xc7, 0x0d, 0x70, 0xc6, 0x0d, 0x6c, 0xc5, 0x0c, 0x69, 0xc4, 0x0c, 0x65, 0xc3, 0x0c, + 0x62, 0xc2, 0x0c, 0x5e, 0xc0, 0x0c, 0x5a, 0xbf, 0x0c, 0x56, 0xbe, 0x0c, 0x53, 0xbd, 0x0d, 0x4f, + 0xbc, 0x0e, 0x4b, 0xba, 0x0f, 0x48, 0xb9, 0x10, 0x44, 0xb8, 0x12, 0x41, 0xb7, 0x14, 0x3e, 0xb5, + 0x16, 0x3b, 0xb4, 0x19, 0x38, 0xb3, 0x1b, 0x36, 0xb1, 0x1e, 0x34, 0xb0, 0x21, 0x33, 0xae, 0x25, + 0x32, 0xad, 0x28, 0x32, 0xab, 0x2c, 0x32, 0xa9, 0x2f, 0x32, 0xa8, 0x33, 0x33, 0xa6, 0x37, 0x35, + 0xa4, 0x3b, 0x36, 0xa3, 0x3f, 0x38, 0xa1, 0x42, 0x39, 0x9f, 0x46, 0x3b, 0x9d, 0x4a, 0x3c, 0x9b, + 0x4e, 0x3e, 0x99, 0x52, 0x3f, 0x98, 0x56, 0x40, 0x96, 0x59, 0x41, 0x94, 0x5d, 0x42, 0x92, 0x61, + 0x43, 0x90, 0x64, 0x44, 0x8e, 0x68, 0x44, 0x8c, 0x6b, 0x45, 0x8a, 0x6f, 0x45, 0x89, 0x72, 0x45, + 0x87, 0x76, 0x45, 0x85, 0x79, 0x45, 0x83, 0x7d, 0x45, 0x81, 0x80, 0x44, 0x7f, 0x84, 0x44, 0x7d, + 0x87, 0x43, 0x7b, 0x8a, 0x42, 0x79, 0x8e, 0x41, 0x78, 0x91, 0x40, 0x76, 0x94, 0x3f, 0x74, 0x97, + 0x3e, 0x72, 0x9b, 0x3c, 0x70, 0x9e, 0x3b, 0x6e, 0xa1, 0x39, 0x6c, 0xa4, 0x38, 0x6a, 0xa7, 0x36, + 0x68, 0xaa, 0x34, 0x66, 0xad, 0x33, 0x64, 0xb0, 0x31, 0x61, 0xb3, 0x30, 0x5f, 0xb6, 0x2f, 0x5d, + 0xb9, 0x2d, 0x5b, 0xbb, 0x2c, 0x58, 0xbe, 0x2b, 0x56, 0xc1, 0x2a, 0x53, 0xc3, 0x2a, 0x51, 0xc6, + 0x29, 0x4e, 0xc8, 0x28, 0x4c, 0xcb, 0x27, 0x49, 0xcd, 0x27, 0x46, 0xd0, 0x26, 0x43, 0xd2, 0x26, + 0x40, 0xd5, 0x25, 0x3e, 0xd7, 0x25, 0x3b, 0xd9, 0x24, 0x38, 0xdb, 0x24, 0x35, 0xde, 0x25, 0x32, + 0xe0, 0x25, 0x2f, 0xe2, 0x26, 0x2c, 0xe4, 0x28, 0x29, 0xe5, 0x29, 0x27, 0xe7, 0x2c, 0x24, 0xe9, + 0x2e, 0x22, 0xea, 0x31, 0x20, 0xec, 0x34, 0x1e, 0xed, 0x37, 0x1d, 0xee, 0x3b, 0x1c, 0xef, 0x3e, + 0x1b, 0xf0, 0x42, 0x1b, 0xf1, 0x45, 0x1b, 0xf2, 0x49, 0x1b, 0xf2, 0x4d, 0x1c, 0xf3, 0x50, 0x1c, + 0xf3, 0x54, 0x1d, 0xf4, 0x57, 0x1f, 0xf4, 0x5a, 0x20, 0xf5, 0x5e, 0x21, 0xf5, 0x61, 0x23, 0xf6, + 0x64, 0x24, 0xf6, 0x67, 0x26, 0xf6, 0x6a, 0x27, 0xf7, 0x6d, 0x29, 0xf7, 0x70, 0x2a, 0xf7, 0x73, + 0x2c, 0xf8, 0x75, 0x2d, 0xf8, 0x78, 0x2e, 0xf8, 0x7b, 0x30, 0xf9, 0x7e, 0x31, 0xf9, 0x80, 0x32, + 0xf9, 0x83, 0x34, 0xfa, 0x86, 0x35, 0xfa, 0x89, 0x36, 0xfa, 0x8c, 0x37, 0xfa, 0x8f, 0x38, 0xfb, + 0x91, 0x39, 0xfb, 0x94, 0x3a, 0xfb, 0x98, 0x3b, 0xfb, 0x9b, 0x3c, 0xfb, 0x9e, 0x3d, 0xfb, 0xa1, + 0x3e, 0xfb, 0xa4, 0x3e, 0xfb, 0xa7, 0x3f, 0xfb, 0xab, 0x40, 0xfb, 0xae, 0x40, 0xfb, 0xb1, 0x41, + 0xfb, 0xb5, 0x41, 0xfb, 0xb8, 0x42, 0xfb, 0xbb, 0x42, 0xfb, 0xbf, 0x43, 0xfb, 0xc2, 0x43, 0xfb, + 0xc5, 0x44, 0xfb, 0xc8, 0x44, 0xfa, 0xcb, 0x45, 0xfa, 0xcf, 0x45, 0xfa, 0xd2, 0x46, 0xfa, 0xd5, + 0x46, 0xfa, 0xd8, 0x47, 0xf9, 0xdb, 0x48, 0xf9, 0xdd, 0x48, 0xf9, 0xe0, 0x49, 0xf8, 0xe3, 0x4b, + 0xf8, 0xe5, 0x4c, 0xf7, 0xe7, 0x4d, 0xf6, 0xe9, 0x4f, 0xf5, 0xec, 0x51, 0xf4, 0xed, 0x53, 0xf3 +}; +static constexpr std::array C3 = { + 0xe1, 0xd7, 0xda, 0xe2, 0xd7, 0xd8, 0xe3, 0xd6, 0xd6, 0xe4, 0xd5, 0xd4, 0xe5, 0xd4, 0xd1, 0xe6, + 0xd2, 0xcf, 0xe7, 0xd1, 0xcc, 0xe8, 0xcf, 0xc9, 0xe9, 0xcd, 0xc6, 0xea, 0xcb, 0xc3, 0xea, 0xc9, + 0xc0, 0xeb, 0xc7, 0xbd, 0xec, 0xc5, 0xba, 0xec, 0xc2, 0xb7, 0xed, 0xc0, 0xb4, 0xed, 0xbd, 0xb0, + 0xee, 0xbb, 0xad, 0xee, 0xb9, 0xaa, 0xee, 0xb6, 0xa7, 0xef, 0xb4, 0xa4, 0xef, 0xb1, 0xa0, 0xef, + 0xaf, 0x9d, 0xef, 0xac, 0x9a, 0xf0, 0xaa, 0x97, 0xf0, 0xa7, 0x94, 0xf0, 0xa5, 0x90, 0xf0, 0xa2, + 0x8d, 0xf0, 0xa0, 0x8a, 0xf0, 0x9d, 0x87, 0xf0, 0x9b, 0x84, 0xf0, 0x98, 0x81, 0xf0, 0x96, 0x7e, + 0xf0, 0x93, 0x7a, 0xf0, 0x91, 0x77, 0xf0, 0x8e, 0x74, 0xf0, 0x8b, 0x71, 0xef, 0x89, 0x6e, 0xef, + 0x86, 0x6b, 0xef, 0x84, 0x68, 0xef, 0x81, 0x65, 0xee, 0x7e, 0x62, 0xee, 0x7c, 0x5f, 0xee, 0x79, + 0x5c, 0xed, 0x76, 0x59, 0xed, 0x74, 0x56, 0xed, 0x71, 0x53, 0xec, 0x6e, 0x50, 0xec, 0x6b, 0x4d, + 0xeb, 0x69, 0x4a, 0xeb, 0x66, 0x47, 0xea, 0x63, 0x44, 0xea, 0x60, 0x41, 0xe9, 0x5d, 0x3e, 0xe8, + 0x5a, 0x3b, 0xe8, 0x57, 0x38, 0xe7, 0x55, 0x35, 0xe6, 0x52, 0x33, 0xe5, 0x4f, 0x30, 0xe4, 0x4c, + 0x2d, 0xe3, 0x49, 0x2b, 0xe1, 0x47, 0x29, 0xe0, 0x44, 0x26, 0xde, 0x42, 0x24, 0xdc, 0x40, 0x23, + 0xda, 0x3e, 0x21, 0xd8, 0x3c, 0x20, 0xd6, 0x3a, 0x1e, 0xd4, 0x39, 0x1d, 0xd1, 0x38, 0x1c, 0xcf, + 0x37, 0x1c, 0xcc, 0x36, 0x1b, 0xc9, 0x35, 0x1b, 0xc6, 0x34, 0x1a, 0xc3, 0x34, 0x1a, 0xc0, 0x34, + 0x1a, 0xbd, 0x33, 0x1a, 0xba, 0x33, 0x1a, 0xb7, 0x33, 0x1a, 0xb4, 0x33, 0x1a, 0xb1, 0x32, 0x1b, + 0xae, 0x32, 0x1b, 0xab, 0x32, 0x1b, 0xa7, 0x32, 0x1b, 0xa4, 0x32, 0x1b, 0xa1, 0x31, 0x1b, 0x9e, + 0x31, 0x1b, 0x9b, 0x31, 0x1c, 0x98, 0x31, 0x1c, 0x94, 0x31, 0x1c, 0x91, 0x30, 0x1c, 0x8e, 0x30, + 0x1c, 0x8b, 0x30, 0x1c, 0x88, 0x2f, 0x1c, 0x85, 0x2f, 0x1c, 0x82, 0x2f, 0x1c, 0x7f, 0x2e, 0x1c, + 0x7c, 0x2e, 0x1c, 0x79, 0x2e, 0x1d, 0x76, 0x2d, 0x1d, 0x73, 0x2d, 0x1d, 0x70, 0x2c, 0x1d, 0x6d, + 0x2c, 0x1d, 0x6a, 0x2c, 0x1d, 0x67, 0x2b, 0x1d, 0x64, 0x2b, 0x1d, 0x61, 0x2a, 0x1d, 0x5e, 0x2a, + 0x1d, 0x5b, 0x29, 0x1d, 0x58, 0x29, 0x1d, 0x55, 0x28, 0x1d, 0x52, 0x28, 0x1d, 0x4f, 0x27, 0x1d, + 0x4c, 0x26, 0x1d, 0x49, 0x26, 0x1d, 0x47, 0x25, 0x1d, 0x44, 0x25, 0x1d, 0x41, 0x24, 0x1d, 0x3e, + 0x24, 0x1d, 0x3c, 0x23, 0x1d, 0x39, 0x23, 0x1e, 0x37, 0x22, 0x1e, 0x34, 0x22, 0x1f, 0x32, 0x22, + 0x1f, 0x30, 0x21, 0x20, 0x2e, 0x21, 0x21, 0x2d, 0x21, 0x22, 0x2b, 0x21, 0x23, 0x2a, 0x21, 0x25, + 0x29, 0x22, 0x26, 0x28, 0x22, 0x28, 0x27, 0x22, 0x2a, 0x27, 0x23, 0x2c, 0x27, 0x23, 0x2e, 0x27, + 0x24, 0x31, 0x27, 0x25, 0x33, 0x27, 0x26, 0x36, 0x27, 0x27, 0x39, 0x27, 0x28, 0x3c, 0x28, 0x29, + 0x3f, 0x28, 0x2a, 0x42, 0x29, 0x2b, 0x45, 0x29, 0x2c, 0x48, 0x2a, 0x2d, 0x4b, 0x2a, 0x2e, 0x4f, + 0x2b, 0x30, 0x52, 0x2b, 0x31, 0x55, 0x2c, 0x32, 0x59, 0x2c, 0x33, 0x5c, 0x2d, 0x35, 0x60, 0x2d, + 0x36, 0x63, 0x2e, 0x37, 0x66, 0x2e, 0x38, 0x6a, 0x2f, 0x3a, 0x6d, 0x2f, 0x3b, 0x71, 0x2f, 0x3c, + 0x74, 0x2f, 0x3d, 0x78, 0x30, 0x3f, 0x7c, 0x30, 0x40, 0x7f, 0x30, 0x41, 0x83, 0x30, 0x42, 0x86, + 0x30, 0x44, 0x8a, 0x30, 0x45, 0x8e, 0x30, 0x46, 0x91, 0x30, 0x48, 0x95, 0x30, 0x49, 0x99, 0x30, + 0x4a, 0x9c, 0x2f, 0x4c, 0xa0, 0x2f, 0x4d, 0xa4, 0x2f, 0x4e, 0xa8, 0x2e, 0x50, 0xab, 0x2e, 0x51, + 0xaf, 0x2d, 0x52, 0xb3, 0x2c, 0x54, 0xb7, 0x2c, 0x55, 0xbb, 0x2b, 0x56, 0xbf, 0x2a, 0x58, 0xc2, + 0x29, 0x59, 0xc6, 0x28, 0x5a, 0xca, 0x27, 0x5c, 0xce, 0x26, 0x5d, 0xd2, 0x25, 0x5f, 0xd5, 0x24, + 0x60, 0xd9, 0x24, 0x61, 0xdd, 0x23, 0x63, 0xe0, 0x23, 0x64, 0xe3, 0x23, 0x66, 0xe7, 0x24, 0x67, + 0xea, 0x25, 0x69, 0xec, 0x27, 0x6a, 0xef, 0x29, 0x6c, 0xf1, 0x2c, 0x6d, 0xf4, 0x2f, 0x6f, 0xf5, + 0x33, 0x70, 0xf7, 0x37, 0x72, 0xf9, 0x3b, 0x73, 0xfa, 0x3f, 0x75, 0xfb, 0x44, 0x76, 0xfb, 0x48, + 0x78, 0xfc, 0x4c, 0x7a, 0xfc, 0x51, 0x7b, 0xfc, 0x55, 0x7d, 0xfc, 0x59, 0x7f, 0xfc, 0x5d, 0x80, + 0xfc, 0x61, 0x82, 0xfc, 0x65, 0x84, 0xfc, 0x68, 0x85, 0xfc, 0x6c, 0x87, 0xfb, 0x6f, 0x89, 0xfb, + 0x73, 0x8b, 0xfa, 0x76, 0x8c, 0xfa, 0x79, 0x8e, 0xfa, 0x7d, 0x90, 0xf9, 0x80, 0x92, 0xf9, 0x83, + 0x93, 0xf8, 0x86, 0x95, 0xf8, 0x88, 0x97, 0xf7, 0x8b, 0x99, 0xf7, 0x8e, 0x9b, 0xf6, 0x91, 0x9c, + 0xf6, 0x93, 0x9e, 0xf5, 0x96, 0xa0, 0xf5, 0x99, 0xa2, 0xf5, 0x9b, 0xa4, 0xf4, 0x9e, 0xa5, 0xf4, + 0xa0, 0xa7, 0xf3, 0xa3, 0xa9, 0xf3, 0xa5, 0xab, 0xf2, 0xa8, 0xad, 0xf2, 0xaa, 0xaf, 0xf1, 0xac, + 0xb1, 0xf1, 0xaf, 0xb2, 0xf0, 0xb1, 0xb4, 0xf0, 0xb3, 0xb6, 0xef, 0xb5, 0xb8, 0xef, 0xb8, 0xba, + 0xee, 0xba, 0xbc, 0xee, 0xbc, 0xbe, 0xed, 0xbe, 0xc0, 0xed, 0xc0, 0xc1, 0xec, 0xc2, 0xc3, 0xeb, + 0xc4, 0xc5, 0xeb, 0xc6, 0xc7, 0xea, 0xc9, 0xc9, 0xea, 0xcb, 0xcb, 0xe9, 0xcd, 0xcc, 0xe8, 0xce, + 0xce, 0xe8, 0xd0, 0xd0, 0xe7, 0xd2, 0xd1, 0xe6, 0xd4, 0xd3, 0xe5, 0xd6, 0xd4, 0xe4, 0xd8, 0xd5, + 0xe3, 0xd9, 0xd6, 0xe2, 0xdb, 0xd7, 0xe1, 0xdc, 0xd7, 0xe0, 0xde, 0xd7, 0xde, 0xdf, 0xd7, 0xdc +}; +static constexpr std::array C4 = { + 0xdf, 0xd5, 0xd8, 0xe0, 0xd5, 0xd6, 0xe1, 0xd4, 0xd4, 0xe2, 0xd3, 0xd2, 0xe3, 0xd1, 0xcf, 0xe3, + 0xd0, 0xcc, 0xe4, 0xce, 0xc9, 0xe5, 0xcc, 0xc6, 0xe5, 0xca, 0xc3, 0xe5, 0xc8, 0xc0, 0xe6, 0xc5, + 0xbd, 0xe6, 0xc3, 0xb9, 0xe6, 0xc0, 0xb6, 0xe6, 0xbd, 0xb2, 0xe6, 0xbb, 0xaf, 0xe6, 0xb8, 0xab, + 0xe6, 0xb5, 0xa8, 0xe6, 0xb2, 0xa4, 0xe6, 0xb0, 0xa1, 0xe6, 0xad, 0x9d, 0xe6, 0xaa, 0x9a, 0xe6, + 0xa7, 0x96, 0xe5, 0xa4, 0x93, 0xe5, 0xa2, 0x8f, 0xe5, 0x9f, 0x8c, 0xe5, 0x9c, 0x88, 0xe4, 0x99, + 0x85, 0xe4, 0x96, 0x81, 0xe3, 0x93, 0x7e, 0xe3, 0x91, 0x7b, 0xe2, 0x8e, 0x77, 0xe2, 0x8b, 0x74, + 0xe1, 0x88, 0x70, 0xe1, 0x85, 0x6d, 0xe0, 0x82, 0x6a, 0xe0, 0x7f, 0x66, 0xdf, 0x7c, 0x63, 0xde, + 0x7a, 0x60, 0xdd, 0x77, 0x5c, 0xdd, 0x74, 0x59, 0xdc, 0x71, 0x56, 0xdb, 0x6e, 0x52, 0xda, 0x6b, + 0x4f, 0xda, 0x68, 0x4c, 0xd9, 0x65, 0x48, 0xd8, 0x62, 0x45, 0xd7, 0x5e, 0x42, 0xd6, 0x5b, 0x3f, + 0xd5, 0x58, 0x3c, 0xd4, 0x55, 0x38, 0xd3, 0x52, 0x35, 0xd2, 0x4f, 0x32, 0xd1, 0x4c, 0x2f, 0xd0, + 0x48, 0x2c, 0xcf, 0x45, 0x29, 0xce, 0x42, 0x26, 0xcd, 0x3f, 0x24, 0xcd, 0x3c, 0x21, 0xcc, 0x3a, + 0x1f, 0xcb, 0x37, 0x1d, 0xca, 0x35, 0x1b, 0xca, 0x33, 0x19, 0xca, 0x32, 0x18, 0xc9, 0x31, 0x17, + 0xc9, 0x31, 0x17, 0xc9, 0x31, 0x17, 0xc9, 0x31, 0x18, 0xca, 0x32, 0x18, 0xca, 0x34, 0x1a, 0xcb, + 0x36, 0x1b, 0xcb, 0x38, 0x1d, 0xcc, 0x3a, 0x1f, 0xcd, 0x3d, 0x22, 0xce, 0x40, 0x24, 0xcf, 0x43, + 0x27, 0xcf, 0x46, 0x2a, 0xd0, 0x49, 0x2d, 0xd1, 0x4c, 0x30, 0xd2, 0x50, 0x33, 0xd3, 0x53, 0x36, + 0xd4, 0x56, 0x39, 0xd5, 0x59, 0x3c, 0xd6, 0x5c, 0x40, 0xd7, 0x5f, 0x43, 0xd8, 0x62, 0x46, 0xd9, + 0x65, 0x49, 0xda, 0x69, 0x4d, 0xdb, 0x6c, 0x50, 0xdb, 0x6f, 0x53, 0xdc, 0x72, 0x56, 0xdd, 0x74, + 0x5a, 0xde, 0x77, 0x5d, 0xde, 0x7a, 0x60, 0xdf, 0x7d, 0x64, 0xe0, 0x80, 0x67, 0xe0, 0x83, 0x6a, + 0xe1, 0x86, 0x6e, 0xe1, 0x89, 0x71, 0xe2, 0x8c, 0x75, 0xe3, 0x8f, 0x78, 0xe3, 0x91, 0x7b, 0xe3, + 0x94, 0x7f, 0xe4, 0x97, 0x82, 0xe4, 0x9a, 0x86, 0xe5, 0x9d, 0x89, 0xe5, 0xa0, 0x8d, 0xe5, 0xa2, + 0x90, 0xe6, 0xa5, 0x94, 0xe6, 0xa8, 0x97, 0xe6, 0xab, 0x9b, 0xe6, 0xae, 0x9e, 0xe6, 0xb0, 0xa2, + 0xe6, 0xb3, 0xa5, 0xe6, 0xb6, 0xa9, 0xe6, 0xb9, 0xac, 0xe6, 0xbb, 0xb0, 0xe6, 0xbe, 0xb3, 0xe6, + 0xc0, 0xb7, 0xe6, 0xc3, 0xba, 0xe5, 0xc5, 0xbe, 0xe5, 0xc7, 0xc1, 0xe4, 0xca, 0xc4, 0xe3, 0xcb, + 0xc7, 0xe2, 0xcd, 0xcb, 0xe1, 0xcf, 0xcd, 0xe0, 0xd0, 0xd0, 0xdf, 0xd1, 0xd3, 0xde, 0xd1, 0xd5, + 0xdc, 0xd2, 0xd7, 0xdb, 0xd2, 0xd9, 0xd9, 0xd1, 0xdb, 0xd7, 0xd1, 0xdd, 0xd5, 0xd0, 0xde, 0xd3, + 0xcf, 0xdf, 0xd1, 0xce, 0xe0, 0xcf, 0xcc, 0xe1, 0xcd, 0xcb, 0xe2, 0xca, 0xc9, 0xe2, 0xc8, 0xc7, + 0xe3, 0xc6, 0xc5, 0xe3, 0xc3, 0xc3, 0xe4, 0xc1, 0xc1, 0xe4, 0xbe, 0xbf, 0xe4, 0xbc, 0xbd, 0xe4, + 0xb9, 0xbb, 0xe4, 0xb7, 0xb8, 0xe4, 0xb4, 0xb6, 0xe5, 0xb2, 0xb4, 0xe5, 0xaf, 0xb2, 0xe5, 0xad, + 0xaf, 0xe5, 0xaa, 0xad, 0xe5, 0xa7, 0xab, 0xe5, 0xa5, 0xa9, 0xe5, 0xa2, 0xa7, 0xe5, 0x9f, 0xa4, + 0xe5, 0x9d, 0xa2, 0xe5, 0x9a, 0xa0, 0xe5, 0x97, 0x9e, 0xe5, 0x94, 0x9c, 0xe5, 0x91, 0x99, 0xe5, + 0x8f, 0x97, 0xe5, 0x8c, 0x95, 0xe5, 0x89, 0x93, 0xe5, 0x86, 0x91, 0xe5, 0x83, 0x8f, 0xe5, 0x7f, + 0x8d, 0xe5, 0x7c, 0x8a, 0xe5, 0x79, 0x88, 0xe5, 0x76, 0x86, 0xe5, 0x72, 0x84, 0xe5, 0x6f, 0x82, + 0xe5, 0x6b, 0x80, 0xe5, 0x68, 0x7e, 0xe5, 0x64, 0x7c, 0xe5, 0x60, 0x7a, 0xe5, 0x5c, 0x78, 0xe5, + 0x58, 0x76, 0xe5, 0x54, 0x74, 0xe5, 0x4f, 0x72, 0xe5, 0x4b, 0x70, 0xe5, 0x46, 0x6e, 0xe5, 0x41, + 0x6d, 0xe5, 0x3c, 0x6b, 0xe5, 0x37, 0x6a, 0xe5, 0x32, 0x68, 0xe5, 0x2d, 0x67, 0xe5, 0x28, 0x66, + 0xe5, 0x23, 0x65, 0xe5, 0x1f, 0x64, 0xe5, 0x1c, 0x64, 0xe5, 0x1a, 0x63, 0xe5, 0x19, 0x63, 0xe5, + 0x1a, 0x63, 0xe5, 0x1d, 0x64, 0xe5, 0x20, 0x64, 0xe5, 0x24, 0x65, 0xe5, 0x29, 0x66, 0xe5, 0x2e, + 0x67, 0xe5, 0x33, 0x68, 0xe5, 0x38, 0x6a, 0xe5, 0x3d, 0x6b, 0xe5, 0x42, 0x6d, 0xe5, 0x47, 0x6f, + 0xe5, 0x4c, 0x71, 0xe5, 0x50, 0x72, 0xe5, 0x55, 0x74, 0xe5, 0x59, 0x76, 0xe5, 0x5d, 0x78, 0xe5, + 0x61, 0x7a, 0xe5, 0x65, 0x7c, 0xe5, 0x68, 0x7e, 0xe5, 0x6c, 0x80, 0xe5, 0x70, 0x83, 0xe5, 0x73, + 0x85, 0xe5, 0x76, 0x87, 0xe5, 0x7a, 0x89, 0xe5, 0x7d, 0x8b, 0xe5, 0x80, 0x8d, 0xe5, 0x83, 0x8f, + 0xe5, 0x86, 0x91, 0xe5, 0x89, 0x93, 0xe5, 0x8c, 0x96, 0xe5, 0x8f, 0x98, 0xe5, 0x92, 0x9a, 0xe5, + 0x95, 0x9c, 0xe5, 0x98, 0x9e, 0xe5, 0x9b, 0xa0, 0xe5, 0x9d, 0xa3, 0xe5, 0xa0, 0xa5, 0xe5, 0xa3, + 0xa7, 0xe5, 0xa5, 0xa9, 0xe5, 0xa8, 0xab, 0xe5, 0xab, 0xae, 0xe5, 0xad, 0xb0, 0xe5, 0xb0, 0xb2, + 0xe5, 0xb2, 0xb4, 0xe5, 0xb5, 0xb7, 0xe5, 0xb7, 0xb9, 0xe4, 0xba, 0xbb, 0xe4, 0xbc, 0xbd, 0xe4, + 0xbf, 0xc0, 0xe4, 0xc1, 0xc2, 0xe4, 0xc4, 0xc4, 0xe4, 0xc6, 0xc6, 0xe4, 0xc8, 0xc8, 0xe3, 0xcb, + 0xca, 0xe3, 0xcd, 0xcc, 0xe3, 0xcf, 0xce, 0xe2, 0xd1, 0xd0, 0xe2, 0xd3, 0xd1, 0xe1, 0xd5, 0xd2, + 0xe0, 0xd7, 0xd3, 0xe0, 0xd9, 0xd4, 0xdf, 0xda, 0xd5, 0xdd, 0xdc, 0xd5, 0xdc, 0xdd, 0xd5, 0xda +}; +static constexpr std::array C5 = { + 0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b, 0x7d, 0x7d, 0x7d, 0x7e, + 0x7e, 0x7e, 0x7f, 0x7f, 0x7f, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x83, 0x83, 0x83, 0x85, 0x85, + 0x85, 0x86, 0x86, 0x86, 0x87, 0x87, 0x87, 0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8c, 0x8c, 0x8c, + 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x93, 0x93, 0x93, 0x94, + 0x94, 0x94, 0x95, 0x95, 0x95, 0x97, 0x97, 0x97, 0x98, 0x98, 0x98, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, + 0x9b, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0x9f, 0x9f, 0x9f, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2, + 0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa7, 0xa7, 0xa7, 0xa8, 0xa8, 0xa8, 0xaa, 0xaa, 0xaa, 0xab, + 0xab, 0xab, 0xac, 0xac, 0xac, 0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, + 0xb2, 0xb4, 0xb4, 0xb4, 0xb5, 0xb5, 0xb5, 0xb7, 0xb7, 0xb7, 0xb8, 0xb8, 0xb8, 0xba, 0xba, 0xba, + 0xbb, 0xbb, 0xbb, 0xbc, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf, 0xc1, 0xc1, 0xc1, 0xc2, + 0xc2, 0xc2, 0xc3, 0xc3, 0xc3, 0xc4, 0xc4, 0xc4, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7, 0xc8, 0xc8, + 0xc8, 0xc8, 0xc8, 0xc8, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, + 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xca, 0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xc9, 0xc8, + 0xc8, 0xc8, 0xc7, 0xc7, 0xc7, 0xc6, 0xc6, 0xc6, 0xc5, 0xc5, 0xc5, 0xc4, 0xc4, 0xc4, 0xc2, 0xc2, + 0xc2, 0xc1, 0xc1, 0xc1, 0xc0, 0xc0, 0xc0, 0xbe, 0xbe, 0xbe, 0xbd, 0xbd, 0xbd, 0xbb, 0xbb, 0xbb, + 0xba, 0xba, 0xba, 0xb8, 0xb9, 0xb9, 0xb7, 0xb7, 0xb7, 0xb6, 0xb6, 0xb6, 0xb4, 0xb4, 0xb4, 0xb3, + 0xb3, 0xb3, 0xb1, 0xb1, 0xb1, 0xb0, 0xb0, 0xb0, 0xae, 0xae, 0xae, 0xad, 0xad, 0xad, 0xab, 0xab, + 0xab, 0xaa, 0xaa, 0xaa, 0xa8, 0xa8, 0xa8, 0xa7, 0xa7, 0xa7, 0xa6, 0xa6, 0xa6, 0xa4, 0xa4, 0xa4, + 0xa3, 0xa3, 0xa3, 0xa1, 0xa1, 0xa1, 0xa0, 0xa0, 0xa0, 0x9e, 0x9e, 0x9e, 0x9d, 0x9d, 0x9d, 0x9b, + 0x9c, 0x9c, 0x9a, 0x9a, 0x9a, 0x99, 0x99, 0x99, 0x97, 0x97, 0x97, 0x96, 0x96, 0x96, 0x94, 0x94, + 0x94, 0x93, 0x93, 0x93, 0x92, 0x92, 0x92, 0x90, 0x90, 0x90, 0x8f, 0x8f, 0x8f, 0x8d, 0x8d, 0x8d, + 0x8c, 0x8c, 0x8c, 0x8b, 0x8b, 0x8b, 0x89, 0x89, 0x89, 0x88, 0x88, 0x88, 0x86, 0x86, 0x86, 0x85, + 0x85, 0x85, 0x84, 0x84, 0x84, 0x82, 0x82, 0x82, 0x81, 0x81, 0x81, 0x7f, 0x7f, 0x7f, 0x7e, 0x7e, + 0x7e, 0x7d, 0x7d, 0x7d, 0x7b, 0x7b, 0x7b, 0x7a, 0x7a, 0x7a, 0x79, 0x79, 0x79, 0x77, 0x77, 0x77, + 0x76, 0x76, 0x76, 0x75, 0x75, 0x75, 0x73, 0x73, 0x73, 0x72, 0x72, 0x72, 0x70, 0x70, 0x70, 0x6f, + 0x6f, 0x6f, 0x6e, 0x6e, 0x6e, 0x6c, 0x6c, 0x6c, 0x6b, 0x6b, 0x6b, 0x6a, 0x6a, 0x6a, 0x68, 0x68, + 0x68, 0x67, 0x67, 0x67, 0x66, 0x66, 0x66, 0x64, 0x64, 0x64, 0x63, 0x63, 0x63, 0x62, 0x62, 0x62, + 0x61, 0x61, 0x61, 0x5f, 0x5f, 0x5f, 0x5e, 0x5e, 0x5e, 0x5d, 0x5d, 0x5d, 0x5b, 0x5b, 0x5b, 0x5a, + 0x5a, 0x5a, 0x59, 0x59, 0x59, 0x57, 0x57, 0x57, 0x56, 0x56, 0x56, 0x55, 0x55, 0x55, 0x54, 0x54, + 0x54, 0x52, 0x52, 0x52, 0x51, 0x51, 0x51, 0x50, 0x50, 0x50, 0x4e, 0x4e, 0x4e, 0x4d, 0x4d, 0x4d, + 0x4c, 0x4c, 0x4c, 0x4b, 0x4b, 0x4b, 0x49, 0x49, 0x49, 0x48, 0x48, 0x48, 0x47, 0x47, 0x47, 0x46, + 0x46, 0x46, 0x44, 0x44, 0x44, 0x43, 0x43, 0x43, 0x42, 0x42, 0x42, 0x41, 0x41, 0x41, 0x40, 0x40, + 0x40, 0x3e, 0x3e, 0x3e, 0x3d, 0x3d, 0x3d, 0x3c, 0x3c, 0x3c, 0x3b, 0x3b, 0x3b, 0x3a, 0x3a, 0x3a, + 0x38, 0x38, 0x38, 0x37, 0x37, 0x37, 0x36, 0x36, 0x36, 0x35, 0x35, 0x35, 0x34, 0x34, 0x34, 0x33, + 0x33, 0x33, 0x32, 0x32, 0x32, 0x31, 0x31, 0x31, 0x30, 0x30, 0x30, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f, + 0x2f, 0x2e, 0x2e, 0x2e, 0x2e, 0x2e, 0x2e, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, + 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2d, 0x2e, 0x2e, 0x2e, 0x2e, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f, 0x2f, + 0x2f, 0x2f, 0x30, 0x30, 0x30, 0x31, 0x31, 0x31, 0x32, 0x32, 0x32, 0x33, 0x33, 0x33, 0x34, 0x34, + 0x34, 0x35, 0x35, 0x35, 0x36, 0x36, 0x36, 0x37, 0x37, 0x37, 0x38, 0x38, 0x38, 0x39, 0x39, 0x39, + 0x3a, 0x3a, 0x3a, 0x3c, 0x3c, 0x3c, 0x3d, 0x3d, 0x3d, 0x3e, 0x3e, 0x3e, 0x3f, 0x3f, 0x3f, 0x40, + 0x41, 0x40, 0x42, 0x42, 0x42, 0x43, 0x43, 0x43, 0x44, 0x44, 0x44, 0x45, 0x45, 0x45, 0x47, 0x47, + 0x47, 0x48, 0x48, 0x48, 0x49, 0x49, 0x49, 0x4a, 0x4a, 0x4a, 0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d, + 0x4e, 0x4e, 0x4e, 0x4f, 0x4f, 0x4f, 0x51, 0x51, 0x51, 0x52, 0x52, 0x52, 0x53, 0x53, 0x53, 0x55, + 0x55, 0x55, 0x56, 0x56, 0x56, 0x57, 0x57, 0x57, 0x58, 0x58, 0x58, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b, + 0x5b, 0x5c, 0x5c, 0x5c, 0x5e, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f, 0x60, 0x60, 0x60, 0x61, 0x62, 0x62, + 0x63, 0x63, 0x63, 0x64, 0x64, 0x64, 0x65, 0x65, 0x65, 0x67, 0x67, 0x67, 0x68, 0x68, 0x68, 0x69, + 0x69, 0x69, 0x6b, 0x6b, 0x6b, 0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6f, 0x6f, 0x6f, 0x70, 0x70, + 0x70, 0x71, 0x71, 0x71, 0x72, 0x72, 0x72, 0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x76, 0x76, 0x76 +}; +static constexpr std::array C6 = { + 0xf7, 0x37, 0x1a, 0xf6, 0x38, 0x17, 0xf6, 0x3a, 0x15, 0xf6, 0x3d, 0x12, 0xf7, 0x40, 0x10, 0xf7, + 0x44, 0x0e, 0xf7, 0x48, 0x0c, 0xf8, 0x4c, 0x0a, 0xf8, 0x50, 0x08, 0xf8, 0x55, 0x07, 0xf9, 0x59, + 0x06, 0xf9, 0x5e, 0x05, 0xfa, 0x62, 0x04, 0xfb, 0x67, 0x03, 0xfb, 0x6b, 0x02, 0xfc, 0x70, 0x02, + 0xfc, 0x74, 0x01, 0xfd, 0x78, 0x01, 0xfd, 0x7d, 0x00, 0xfe, 0x81, 0x00, 0xfe, 0x85, 0x00, 0xfe, + 0x89, 0x00, 0xff, 0x8d, 0x00, 0xff, 0x91, 0x00, 0xff, 0x95, 0x00, 0xff, 0x99, 0x00, 0xff, 0x9d, + 0x00, 0xff, 0xa1, 0x00, 0xff, 0xa5, 0x00, 0xff, 0xa8, 0x00, 0xff, 0xac, 0x00, 0xff, 0xb0, 0x00, + 0xff, 0xb3, 0x00, 0xff, 0xb7, 0x00, 0xff, 0xba, 0x00, 0xff, 0xbd, 0x00, 0xfe, 0xc1, 0x00, 0xfd, + 0xc3, 0x00, 0xfc, 0xc6, 0x00, 0xfb, 0xc9, 0x00, 0xf9, 0xcb, 0x00, 0xf7, 0xcd, 0x00, 0xf5, 0xce, + 0x00, 0xf2, 0xd0, 0x00, 0xef, 0xd0, 0x00, 0xec, 0xd1, 0x00, 0xe9, 0xd1, 0x00, 0xe5, 0xd1, 0x00, + 0xe1, 0xd1, 0x00, 0xdd, 0xd0, 0x00, 0xd9, 0xd0, 0x00, 0xd5, 0xcf, 0x00, 0xd1, 0xcd, 0x00, 0xcc, + 0xcc, 0x00, 0xc8, 0xcb, 0x00, 0xc3, 0xc9, 0x00, 0xbf, 0xc7, 0x00, 0xba, 0xc5, 0x00, 0xb5, 0xc4, + 0x00, 0xb1, 0xc2, 0x00, 0xac, 0xc0, 0x00, 0xa7, 0xbe, 0x00, 0xa2, 0xbc, 0x00, 0x9e, 0xba, 0x00, + 0x99, 0xb8, 0x00, 0x94, 0xb6, 0x00, 0x8f, 0xb4, 0x00, 0x8a, 0xb2, 0x01, 0x86, 0xb0, 0x01, 0x81, + 0xae, 0x02, 0x7c, 0xac, 0x02, 0x77, 0xaa, 0x03, 0x72, 0xa9, 0x03, 0x6d, 0xa7, 0x04, 0x68, 0xa5, + 0x06, 0x64, 0xa3, 0x07, 0x5f, 0xa1, 0x09, 0x5a, 0xa0, 0x0b, 0x55, 0x9e, 0x0d, 0x51, 0x9d, 0x10, + 0x4c, 0x9c, 0x12, 0x48, 0x9b, 0x15, 0x44, 0x9a, 0x18, 0x40, 0x9a, 0x1b, 0x3c, 0x99, 0x1e, 0x39, + 0x99, 0x22, 0x36, 0x99, 0x26, 0x33, 0x9a, 0x29, 0x31, 0x9b, 0x2d, 0x2f, 0x9b, 0x31, 0x2d, 0x9d, + 0x36, 0x2c, 0x9e, 0x3a, 0x2b, 0xa0, 0x3e, 0x2b, 0xa1, 0x43, 0x2b, 0xa3, 0x48, 0x2b, 0xa5, 0x4c, + 0x2c, 0xa7, 0x51, 0x2c, 0xaa, 0x56, 0x2d, 0xac, 0x5b, 0x2e, 0xae, 0x60, 0x2e, 0xb1, 0x65, 0x2f, + 0xb3, 0x6a, 0x30, 0xb5, 0x6f, 0x30, 0xb8, 0x74, 0x31, 0xba, 0x79, 0x31, 0xbd, 0x7e, 0x32, 0xbf, + 0x83, 0x32, 0xc2, 0x88, 0x32, 0xc4, 0x8d, 0x32, 0xc7, 0x92, 0x32, 0xca, 0x97, 0x32, 0xcc, 0x9c, + 0x32, 0xcf, 0xa1, 0x32, 0xd1, 0xa6, 0x31, 0xd4, 0xab, 0x30, 0xd6, 0xb1, 0x30, 0xd8, 0xb6, 0x2f, + 0xdb, 0xbb, 0x2e, 0xdd, 0xc0, 0x2d, 0xdf, 0xc5, 0x2c, 0xe1, 0xca, 0x2b, 0xe3, 0xce, 0x2a, 0xe4, + 0xd3, 0x28, 0xe6, 0xd7, 0x27, 0xe7, 0xdc, 0x27, 0xe8, 0xe0, 0x26, 0xe8, 0xe4, 0x25, 0xe8, 0xe7, + 0x25, 0xe8, 0xeb, 0x25, 0xe8, 0xee, 0x26, 0xe7, 0xf0, 0x26, 0xe6, 0xf3, 0x27, 0xe4, 0xf5, 0x28, + 0xe3, 0xf7, 0x29, 0xe1, 0xf9, 0x2a, 0xdf, 0xfa, 0x2b, 0xdc, 0xfb, 0x2c, 0xda, 0xfc, 0x2d, 0xd7, + 0xfd, 0x2e, 0xd4, 0xfe, 0x2f, 0xd1, 0xfe, 0x2f, 0xce, 0xff, 0x30, 0xcb, 0xff, 0x31, 0xc8, 0xff, + 0x31, 0xc5, 0xff, 0x31, 0xc2, 0xff, 0x31, 0xbf, 0xff, 0x31, 0xbc, 0xff, 0x31, 0xb8, 0xff, 0x31, + 0xb5, 0xff, 0x30, 0xb2, 0xff, 0x30, 0xaf, 0xff, 0x2f, 0xac, 0xff, 0x2e, 0xa9, 0xff, 0x2d, 0xa6, + 0xff, 0x2c, 0xa3, 0xff, 0x2b, 0xa0, 0xff, 0x2a, 0x9d, 0xff, 0x29, 0x9a, 0xff, 0x28, 0x97, 0xff, + 0x28, 0x94, 0xff, 0x27, 0x91, 0xff, 0x28, 0x8f, 0xff, 0x28, 0x8c, 0xff, 0x29, 0x8a, 0xff, 0x2b, + 0x88, 0xff, 0x2e, 0x86, 0xff, 0x31, 0x84, 0xff, 0x35, 0x83, 0xff, 0x39, 0x82, 0xff, 0x3e, 0x81, + 0xff, 0x43, 0x80, 0xff, 0x48, 0x80, 0xff, 0x4d, 0x80, 0xff, 0x53, 0x81, 0xff, 0x59, 0x81, 0xff, + 0x5e, 0x82, 0xff, 0x64, 0x83, 0xff, 0x69, 0x84, 0xff, 0x6f, 0x86, 0xff, 0x74, 0x88, 0xff, 0x7a, + 0x89, 0xff, 0x7f, 0x8b, 0xff, 0x84, 0x8d, 0xff, 0x89, 0x8f, 0xff, 0x8e, 0x91, 0xff, 0x93, 0x93, + 0xff, 0x98, 0x96, 0xff, 0x9d, 0x98, 0xff, 0xa1, 0x9a, 0xff, 0xa6, 0x9c, 0xff, 0xaa, 0x9f, 0xff, + 0xae, 0xa1, 0xff, 0xb3, 0xa3, 0xff, 0xb7, 0xa5, 0xff, 0xbb, 0xa8, 0xff, 0xbf, 0xaa, 0xff, 0xc4, + 0xac, 0xff, 0xc8, 0xae, 0xff, 0xcc, 0xb1, 0xff, 0xd0, 0xb3, 0xff, 0xd4, 0xb5, 0xff, 0xd8, 0xb7, + 0xff, 0xdb, 0xb8, 0xff, 0xdf, 0xba, 0xff, 0xe3, 0xbc, 0xff, 0xe7, 0xbd, 0xfd, 0xea, 0xbe, 0xfc, + 0xee, 0xbf, 0xfa, 0xf1, 0xbf, 0xf7, 0xf4, 0xbf, 0xf5, 0xf7, 0xbf, 0xf2, 0xfa, 0xbe, 0xee, 0xfc, + 0xbd, 0xea, 0xff, 0xbc, 0xe7, 0xff, 0xbb, 0xe2, 0xff, 0xb9, 0xde, 0xff, 0xb7, 0xd9, 0xff, 0xb4, + 0xd4, 0xff, 0xb2, 0xcf, 0xff, 0xaf, 0xca, 0xff, 0xac, 0xc5, 0xff, 0xa9, 0xbf, 0xff, 0xa5, 0xba, + 0xff, 0xa2, 0xb4, 0xff, 0x9e, 0xaf, 0xff, 0x9b, 0xa9, 0xff, 0x97, 0xa4, 0xff, 0x94, 0x9e, 0xff, + 0x90, 0x99, 0xff, 0x8c, 0x93, 0xff, 0x88, 0x8e, 0xff, 0x85, 0x89, 0xff, 0x81, 0x83, 0xff, 0x7d, + 0x7e, 0xff, 0x79, 0x79, 0xff, 0x75, 0x73, 0xff, 0x71, 0x6e, 0xff, 0x6d, 0x69, 0xff, 0x69, 0x64, + 0xff, 0x65, 0x5e, 0xff, 0x61, 0x59, 0xff, 0x5c, 0x54, 0xff, 0x58, 0x4f, 0xff, 0x54, 0x4a, 0xff, + 0x50, 0x45, 0xfe, 0x4c, 0x41, 0xfd, 0x48, 0x3c, 0xfc, 0x44, 0x38, 0xfb, 0x41, 0x33, 0xfa, 0x3d, + 0x2f, 0xf9, 0x3b, 0x2b, 0xf8, 0x38, 0x27, 0xf8, 0x37, 0x24, 0xf7, 0x36, 0x20, 0xf7, 0x36, 0x1d +}; +static constexpr std::array C7 = { + 0xe9, 0xe4, 0x19, 0xeb, 0xe3, 0x1f, 0xec, 0xe2, 0x26, 0xee, 0xe1, 0x2b, 0xef, 0xdf, 0x31, 0xf0, + 0xde, 0x37, 0xf1, 0xdc, 0x3c, 0xf2, 0xda, 0x41, 0xf4, 0xd8, 0x46, 0xf5, 0xd5, 0x4b, 0xf6, 0xd3, + 0x50, 0xf6, 0xd1, 0x54, 0xf7, 0xcf, 0x58, 0xf8, 0xcc, 0x5c, 0xf9, 0xca, 0x61, 0xfa, 0xc8, 0x64, + 0xfb, 0xc5, 0x68, 0xfb, 0xc3, 0x6c, 0xfc, 0xc1, 0x70, 0xfd, 0xbe, 0x73, 0xfd, 0xbc, 0x77, 0xfe, + 0xba, 0x7a, 0xff, 0xb7, 0x7e, 0xff, 0xb5, 0x81, 0xff, 0xb2, 0x84, 0xff, 0xb0, 0x87, 0xff, 0xad, + 0x8b, 0xff, 0xab, 0x8e, 0xff, 0xa8, 0x91, 0xff, 0xa6, 0x94, 0xff, 0xa3, 0x97, 0xff, 0xa1, 0x9a, + 0xff, 0x9e, 0x9d, 0xff, 0x9b, 0xa0, 0xff, 0x99, 0xa3, 0xff, 0x96, 0xa6, 0xff, 0x93, 0xa9, 0xff, + 0x90, 0xac, 0xff, 0x8e, 0xaf, 0xff, 0x8b, 0xb2, 0xff, 0x88, 0xb5, 0xff, 0x85, 0xb8, 0xff, 0x82, + 0xbb, 0xff, 0x7f, 0xbe, 0xff, 0x7c, 0xc1, 0xff, 0x79, 0xc4, 0xff, 0x76, 0xc7, 0xff, 0x72, 0xc9, + 0xff, 0x6f, 0xcc, 0xff, 0x6c, 0xcf, 0xff, 0x68, 0xd2, 0xff, 0x65, 0xd5, 0xff, 0x61, 0xd8, 0xff, + 0x5d, 0xdb, 0xff, 0x5a, 0xdd, 0xff, 0x56, 0xe0, 0xff, 0x52, 0xe3, 0xff, 0x4e, 0xe6, 0xff, 0x4a, + 0xe9, 0xff, 0x47, 0xeb, 0xff, 0x44, 0xee, 0xff, 0x41, 0xf0, 0xfe, 0x3f, 0xf3, 0xfd, 0x3f, 0xf5, + 0xfc, 0x3f, 0xf7, 0xfb, 0x40, 0xf8, 0xf9, 0x42, 0xfa, 0xf8, 0x45, 0xfb, 0xf7, 0x48, 0xfc, 0xf5, + 0x4c, 0xfd, 0xf4, 0x51, 0xfd, 0xf2, 0x55, 0xfe, 0xf1, 0x5a, 0xfe, 0xef, 0x5e, 0xfe, 0xee, 0x62, + 0xfe, 0xec, 0x67, 0xfe, 0xeb, 0x6b, 0xfe, 0xe9, 0x6f, 0xfe, 0xe7, 0x73, 0xfe, 0xe6, 0x77, 0xfe, + 0xe4, 0x7a, 0xfe, 0xe2, 0x7e, 0xfe, 0xe0, 0x81, 0xfe, 0xde, 0x85, 0xfe, 0xdd, 0x88, 0xfe, 0xdb, + 0x8b, 0xfe, 0xd9, 0x8f, 0xfe, 0xd7, 0x92, 0xfe, 0xd5, 0x95, 0xfe, 0xd3, 0x98, 0xfe, 0xd1, 0x9b, + 0xfe, 0xcf, 0x9e, 0xfe, 0xcc, 0xa1, 0xfe, 0xca, 0xa4, 0xfe, 0xc8, 0xa7, 0xfe, 0xc6, 0xa9, 0xfe, + 0xc3, 0xac, 0xfe, 0xc1, 0xaf, 0xfe, 0xbe, 0xb2, 0xfe, 0xbc, 0xb4, 0xfe, 0xb9, 0xb7, 0xfe, 0xb7, + 0xba, 0xfe, 0xb4, 0xbc, 0xfe, 0xb1, 0xbf, 0xfd, 0xae, 0xc1, 0xfd, 0xab, 0xc4, 0xfd, 0xa8, 0xc6, + 0xfd, 0xa5, 0xc9, 0xfd, 0xa2, 0xcb, 0xfd, 0x9e, 0xce, 0xfd, 0x9b, 0xd0, 0xfd, 0x97, 0xd3, 0xfd, + 0x93, 0xd5, 0xfd, 0x8f, 0xd8, 0xfd, 0x8b, 0xda, 0xfd, 0x87, 0xdc, 0xfd, 0x82, 0xdf, 0xfd, 0x7e, + 0xe1, 0xfc, 0x79, 0xe3, 0xfc, 0x73, 0xe5, 0xfc, 0x6e, 0xe8, 0xfc, 0x68, 0xea, 0xfb, 0x62, 0xec, + 0xfb, 0x5c, 0xed, 0xfa, 0x55, 0xef, 0xf9, 0x4f, 0xf0, 0xf8, 0x48, 0xf2, 0xf6, 0x41, 0xf3, 0xf5, + 0x3b, 0xf3, 0xf3, 0x35, 0xf3, 0xf0, 0x30, 0xf3, 0xee, 0x2c, 0xf3, 0xeb, 0x29, 0xf3, 0xe8, 0x27, + 0xf2, 0xe5, 0x26, 0xf1, 0xe2, 0x26, 0xf0, 0xdf, 0x26, 0xef, 0xdb, 0x27, 0xee, 0xd8, 0x28, 0xed, + 0xd5, 0x29, 0xec, 0xd1, 0x2b, 0xea, 0xce, 0x2c, 0xe9, 0xca, 0x2d, 0xe8, 0xc7, 0x2e, 0xe6, 0xc3, + 0x2f, 0xe5, 0xc0, 0x30, 0xe4, 0xbd, 0x31, 0xe3, 0xb9, 0x31, 0xe1, 0xb6, 0x32, 0xe0, 0xb2, 0x32, + 0xdf, 0xaf, 0x33, 0xdd, 0xac, 0x33, 0xdc, 0xa8, 0x33, 0xdb, 0xa5, 0x34, 0xda, 0xa2, 0x34, 0xd8, + 0x9e, 0x34, 0xd7, 0x9b, 0x34, 0xd6, 0x97, 0x34, 0xd5, 0x94, 0x34, 0xd3, 0x91, 0x33, 0xd2, 0x8d, + 0x33, 0xd1, 0x8a, 0x33, 0xcf, 0x87, 0x32, 0xce, 0x83, 0x32, 0xcd, 0x80, 0x31, 0xcc, 0x7c, 0x31, + 0xca, 0x79, 0x30, 0xc9, 0x76, 0x30, 0xc8, 0x72, 0x2f, 0xc7, 0x6f, 0x2e, 0xc5, 0x6c, 0x2d, 0xc4, + 0x68, 0x2c, 0xc3, 0x65, 0x2b, 0xc2, 0x61, 0x2a, 0xc0, 0x5e, 0x29, 0xbf, 0x5a, 0x28, 0xbe, 0x57, + 0x27, 0xbd, 0x53, 0x25, 0xbb, 0x50, 0x24, 0xba, 0x4c, 0x22, 0xb9, 0x48, 0x21, 0xb8, 0x45, 0x1f, + 0xb7, 0x41, 0x1e, 0xb5, 0x3d, 0x1c, 0xb4, 0x39, 0x1b, 0xb3, 0x35, 0x1a, 0xb2, 0x31, 0x1a, 0xb1, + 0x2d, 0x1b, 0xb1, 0x29, 0x1c, 0xb0, 0x25, 0x1e, 0xaf, 0x21, 0x20, 0xaf, 0x1c, 0x23, 0xaf, 0x18, + 0x27, 0xaf, 0x14, 0x2b, 0xaf, 0x10, 0x2f, 0xaf, 0x0c, 0x33, 0xb0, 0x08, 0x37, 0xb1, 0x05, 0x3b, + 0xb1, 0x02, 0x3f, 0xb2, 0x00, 0x44, 0xb3, 0x00, 0x48, 0xb4, 0x00, 0x4c, 0xb5, 0x00, 0x4f, 0xb6, + 0x00, 0x53, 0xb7, 0x00, 0x57, 0xb8, 0x00, 0x5a, 0xb9, 0x00, 0x5e, 0xba, 0x00, 0x61, 0xbb, 0x00, + 0x65, 0xbc, 0x00, 0x68, 0xbd, 0x00, 0x6b, 0xbe, 0x00, 0x6e, 0xbf, 0x00, 0x72, 0xc0, 0x00, 0x75, + 0xc1, 0x00, 0x78, 0xc2, 0x00, 0x7b, 0xc3, 0x00, 0x7e, 0xc4, 0x00, 0x81, 0xc5, 0x00, 0x84, 0xc6, + 0x00, 0x87, 0xc7, 0x00, 0x8a, 0xc8, 0x00, 0x8d, 0xc9, 0x00, 0x90, 0xca, 0x00, 0x93, 0xcb, 0x00, + 0x95, 0xcc, 0x00, 0x98, 0xcd, 0x00, 0x9b, 0xce, 0x00, 0x9e, 0xcf, 0x00, 0xa1, 0xd0, 0x00, 0xa4, + 0xd1, 0x00, 0xa6, 0xd2, 0x00, 0xa9, 0xd3, 0x00, 0xac, 0xd4, 0x00, 0xaf, 0xd5, 0x00, 0xb2, 0xd6, + 0x00, 0xb4, 0xd7, 0x00, 0xb7, 0xd8, 0x00, 0xba, 0xd9, 0x00, 0xbd, 0xda, 0x00, 0xbf, 0xdb, 0x00, + 0xc2, 0xdc, 0x00, 0xc5, 0xdd, 0x00, 0xc7, 0xde, 0x00, 0xca, 0xde, 0x00, 0xcd, 0xdf, 0x00, 0xd0, + 0xe0, 0x00, 0xd2, 0xe1, 0x00, 0xd5, 0xe2, 0x00, 0xd7, 0xe3, 0x00, 0xda, 0xe4, 0x00, 0xdc, 0xe4, + 0x00, 0xdf, 0xe5, 0x00, 0xe1, 0xe5, 0x00, 0xe3, 0xe5, 0x03, 0xe5, 0xe5, 0x0b, 0xe7, 0xe5, 0x12 +}; - // isoluminant - static constexpr std::array I1 = {0x37,0xb7,0xec,0x38,0xb7,0xeb,0x38,0xb7,0xea,0x39,0xb7,0xea,0x39,0xb7,0xe9,0x3a,0xb7,0xe8,0x3b,0xb8,0xe7,0x3b,0xb8,0xe6,0x3c,0xb8,0xe5,0x3c,0xb8,0xe4,0x3d,0xb8,0xe3,0x3d,0xb8,0xe3,0x3e,0xb8,0xe2,0x3e,0xb8,0xe1,0x3f,0xb8,0xe0,0x3f,0xb8,0xdf,0x40,0xb8,0xde,0x40,0xb8,0xdd,0x41,0xb8,0xdc,0x42,0xb8,0xdc,0x42,0xb9,0xdb,0x43,0xb9,0xda,0x43,0xb9,0xd9,0x44,0xb9,0xd8,0x44,0xb9,0xd7,0x45,0xb9,0xd6,0x45,0xb9,0xd5,0x45,0xb9,0xd4,0x46,0xb9,0xd4,0x46,0xb9,0xd3,0x47,0xb9,0xd2,0x47,0xb9,0xd1,0x48,0xb9,0xd0,0x48,0xb9,0xcf,0x49,0xb9,0xce,0x49,0xb9,0xcd,0x4a,0xba,0xcc,0x4a,0xba,0xcb,0x4b,0xba,0xcb,0x4b,0xba,0xca,0x4c,0xba,0xc9,0x4c,0xba,0xc8,0x4d,0xba,0xc7,0x4d,0xba,0xc6,0x4e,0xba,0xc5,0x4e,0xba,0xc4,0x4f,0xba,0xc3,0x4f,0xba,0xc2,0x50,0xba,0xc1,0x50,0xba,0xc1,0x50,0xba,0xc0,0x51,0xba,0xbf,0x51,0xba,0xbe,0x52,0xba,0xbd,0x52,0xba,0xbc,0x53,0xbb,0xbb,0x53,0xbb,0xba,0x54,0xbb,0xb9,0x54,0xbb,0xb8,0x55,0xbb,0xb7,0x55,0xbb,0xb6,0x56,0xbb,0xb5,0x56,0xbb,0xb4,0x57,0xbb,0xb3,0x57,0xbb,0xb3,0x58,0xbb,0xb2,0x58,0xbb,0xb1,0x59,0xbb,0xb0,0x59,0xbb,0xaf,0x5a,0xbb,0xae,0x5b,0xbb,0xad,0x5b,0xbb,0xac,0x5c,0xbb,0xab,0x5c,0xbb,0xaa,0x5d,0xbb,0xa9,0x5d,0xbb,0xa8,0x5e,0xbb,0xa7,0x5e,0xbb,0xa6,0x5f,0xbb,0xa5,0x60,0xbb,0xa4,0x60,0xbb,0xa3,0x61,0xbb,0xa2,0x61,0xbb,0xa1,0x62,0xbb,0xa0,0x62,0xbb,0x9f,0x63,0xbb,0x9e,0x64,0xbb,0x9d,0x64,0xbb,0x9c,0x65,0xbb,0x9b,0x66,0xbb,0x9a,0x66,0xbb,0x99,0x67,0xbb,0x98,0x68,0xbb,0x97,0x68,0xbb,0x97,0x69,0xbb,0x96,0x6a,0xbb,0x95,0x6a,0xbb,0x94,0x6b,0xbb,0x93,0x6c,0xbb,0x92,0x6d,0xbb,0x91,0x6d,0xbb,0x90,0x6e,0xbb,0x8f,0x6f,0xbb,0x8e,0x70,0xbb,0x8d,0x71,0xbb,0x8c,0x71,0xbb,0x8b,0x72,0xbb,0x8a,0x73,0xba,0x89,0x74,0xba,0x88,0x75,0xba,0x87,0x76,0xba,0x86,0x76,0xba,0x85,0x77,0xba,0x84,0x78,0xba,0x83,0x79,0xba,0x82,0x7a,0xba,0x81,0x7b,0xba,0x80,0x7c,0xba,0x7f,0x7d,0xb9,0x7e,0x7e,0xb9,0x7d,0x7f,0xb9,0x7c,0x80,0xb9,0x7c,0x81,0xb9,0x7b,0x82,0xb9,0x7a,0x83,0xb9,0x79,0x84,0xb8,0x78,0x85,0xb8,0x77,0x86,0xb8,0x77,0x87,0xb8,0x76,0x88,0xb8,0x75,0x89,0xb8,0x74,0x8a,0xb8,0x73,0x8b,0xb7,0x73,0x8c,0xb7,0x72,0x8e,0xb7,0x71,0x8f,0xb7,0x71,0x90,0xb7,0x70,0x91,0xb6,0x6f,0x92,0xb6,0x6f,0x93,0xb6,0x6e,0x94,0xb6,0x6d,0x95,0xb6,0x6d,0x96,0xb5,0x6c,0x97,0xb5,0x6c,0x98,0xb5,0x6b,0x99,0xb5,0x6b,0x9a,0xb4,0x6a,0x9b,0xb4,0x6a,0x9d,0xb4,0x69,0x9e,0xb4,0x69,0x9f,0xb3,0x68,0xa0,0xb3,0x68,0xa1,0xb3,0x67,0xa2,0xb3,0x67,0xa3,0xb2,0x66,0xa4,0xb2,0x66,0xa5,0xb2,0x65,0xa6,0xb2,0x65,0xa7,0xb1,0x64,0xa8,0xb1,0x64,0xa9,0xb1,0x64,0xaa,0xb1,0x63,0xab,0xb0,0x63,0xac,0xb0,0x63,0xad,0xb0,0x62,0xae,0xb0,0x62,0xaf,0xaf,0x62,0xb0,0xaf,0x61,0xb1,0xaf,0x61,0xb2,0xaf,0x61,0xb3,0xae,0x60,0xb4,0xae,0x60,0xb5,0xae,0x60,0xb5,0xad,0x60,0xb6,0xad,0x5f,0xb7,0xad,0x5f,0xb8,0xac,0x5f,0xb9,0xac,0x5f,0xba,0xac,0x5f,0xbb,0xac,0x5f,0xbc,0xab,0x5e,0xbd,0xab,0x5e,0xbe,0xab,0x5e,0xbf,0xaa,0x5e,0xc0,0xaa,0x5e,0xc1,0xaa,0x5e,0xc2,0xa9,0x5e,0xc2,0xa9,0x5e,0xc3,0xa9,0x5e,0xc4,0xa8,0x5e,0xc5,0xa8,0x5d,0xc6,0xa8,0x5d,0xc7,0xa8,0x5d,0xc8,0xa7,0x5d,0xc9,0xa7,0x5d,0xc9,0xa7,0x5d,0xca,0xa6,0x5e,0xcb,0xa6,0x5e,0xcc,0xa6,0x5e,0xcd,0xa5,0x5e,0xce,0xa5,0x5e,0xcf,0xa5,0x5e,0xcf,0xa4,0x5e,0xd0,0xa4,0x5e,0xd1,0xa4,0x5e,0xd2,0xa3,0x5e,0xd3,0xa3,0x5e,0xd3,0xa2,0x5e,0xd4,0xa2,0x5f,0xd5,0xa2,0x5f,0xd6,0xa1,0x5f,0xd7,0xa1,0x5f,0xd8,0xa1,0x5f,0xd8,0xa0,0x5f,0xd9,0xa0,0x60,0xda,0xa0,0x60,0xdb,0x9f,0x60,0xdb,0x9f,0x60,0xdc,0x9f,0x60,0xdd,0x9e,0x61,0xde,0x9e,0x61,0xdf,0x9d,0x61,0xdf,0x9d,0x61,0xe0,0x9d,0x62,0xe1,0x9c,0x62,0xe2,0x9c,0x62,0xe2,0x9c,0x63,0xe3,0x9b,0x63,0xe4,0x9b,0x63,0xe4,0x9a,0x63,0xe5,0x9a,0x64,0xe6,0x9a,0x64,0xe7,0x99,0x64,0xe7,0x99,0x65,0xe8,0x99,0x65,0xe9,0x98,0x65,0xea,0x98,0x66,0xea,0x97,0x66,0xeb,0x97,0x66,0xec,0x97,0x67,0xec,0x96,0x67,0xed,0x96,0x67,0xee,0x95,0x68,0xee,0x95,0x68,0xef,0x95,0x68,0xf0,0x94,0x69,0xf0,0x94,0x69,0xf1,0x93,0x6a,0xf2,0x93,0x6a,0xf2,0x93,0x6a,0xf3,0x92,0x6b,0xf4,0x92,0x6b,0xf4,0x91,0x6c,0xf5,0x91,0x6c,0xf6,0x91,0x6c,0xf6,0x90,0x6d}; - static constexpr std::array I2 = {0x70,0xd1,0xff,0x70,0xd2,0xff,0x70,0xd2,0xff,0x70,0xd2,0xff,0x70,0xd2,0xff,0x70,0xd2,0xfe,0x70,0xd2,0xfe,0x70,0xd2,0xfd,0x70,0xd2,0xfc,0x70,0xd2,0xfb,0x70,0xd2,0xfa,0x70,0xd2,0xfa,0x71,0xd3,0xf9,0x71,0xd3,0xf8,0x71,0xd3,0xf7,0x71,0xd3,0xf7,0x71,0xd3,0xf6,0x71,0xd3,0xf5,0x71,0xd3,0xf4,0x71,0xd3,0xf3,0x71,0xd3,0xf3,0x71,0xd3,0xf2,0x71,0xd3,0xf1,0x72,0xd4,0xf0,0x72,0xd4,0xef,0x72,0xd4,0xee,0x72,0xd4,0xee,0x72,0xd4,0xed,0x72,0xd4,0xec,0x72,0xd4,0xeb,0x72,0xd4,0xea,0x73,0xd4,0xea,0x73,0xd4,0xe9,0x73,0xd4,0xe8,0x73,0xd4,0xe7,0x73,0xd4,0xe6,0x73,0xd5,0xe5,0x73,0xd5,0xe5,0x74,0xd5,0xe4,0x74,0xd5,0xe3,0x74,0xd5,0xe2,0x74,0xd5,0xe1,0x74,0xd5,0xe1,0x74,0xd5,0xe0,0x74,0xd5,0xdf,0x75,0xd5,0xde,0x75,0xd5,0xdd,0x75,0xd5,0xdc,0x75,0xd5,0xdb,0x75,0xd5,0xdb,0x76,0xd5,0xda,0x76,0xd6,0xd9,0x76,0xd6,0xd8,0x76,0xd6,0xd7,0x76,0xd6,0xd6,0x77,0xd6,0xd6,0x77,0xd6,0xd5,0x77,0xd6,0xd4,0x77,0xd6,0xd3,0x77,0xd6,0xd2,0x78,0xd6,0xd1,0x78,0xd6,0xd0,0x78,0xd6,0xd0,0x78,0xd6,0xcf,0x79,0xd6,0xce,0x79,0xd6,0xcd,0x79,0xd6,0xcc,0x7a,0xd6,0xcb,0x7a,0xd6,0xca,0x7a,0xd6,0xc9,0x7a,0xd6,0xc9,0x7b,0xd6,0xc8,0x7b,0xd7,0xc7,0x7b,0xd7,0xc6,0x7c,0xd7,0xc5,0x7c,0xd7,0xc4,0x7c,0xd7,0xc3,0x7d,0xd7,0xc2,0x7d,0xd7,0xc1,0x7d,0xd7,0xc1,0x7e,0xd7,0xc0,0x7e,0xd7,0xbf,0x7e,0xd7,0xbe,0x7f,0xd7,0xbd,0x7f,0xd7,0xbc,0x80,0xd7,0xbb,0x80,0xd7,0xba,0x81,0xd7,0xb9,0x81,0xd7,0xb8,0x81,0xd7,0xb8,0x82,0xd7,0xb7,0x82,0xd7,0xb6,0x83,0xd7,0xb5,0x83,0xd7,0xb4,0x84,0xd7,0xb3,0x84,0xd7,0xb2,0x85,0xd7,0xb1,0x85,0xd7,0xb0,0x86,0xd7,0xaf,0x86,0xd7,0xae,0x87,0xd7,0xad,0x88,0xd7,0xac,0x88,0xd7,0xac,0x89,0xd7,0xab,0x89,0xd7,0xaa,0x8a,0xd7,0xa9,0x8b,0xd7,0xa8,0x8b,0xd7,0xa7,0x8c,0xd7,0xa6,0x8d,0xd6,0xa5,0x8d,0xd6,0xa4,0x8e,0xd6,0xa3,0x8f,0xd6,0xa2,0x90,0xd6,0xa1,0x90,0xd6,0xa0,0x91,0xd6,0xa0,0x92,0xd6,0x9f,0x93,0xd6,0x9e,0x93,0xd6,0x9d,0x94,0xd6,0x9c,0x95,0xd6,0x9b,0x96,0xd6,0x9a,0x97,0xd5,0x99,0x98,0xd5,0x99,0x99,0xd5,0x98,0x9a,0xd5,0x97,0x9a,0xd5,0x96,0x9b,0xd5,0x95,0x9c,0xd5,0x94,0x9d,0xd5,0x94,0x9e,0xd4,0x93,0x9f,0xd4,0x92,0xa0,0xd4,0x91,0xa1,0xd4,0x90,0xa2,0xd4,0x90,0xa3,0xd4,0x8f,0xa4,0xd3,0x8e,0xa5,0xd3,0x8e,0xa6,0xd3,0x8d,0xa7,0xd3,0x8c,0xa8,0xd3,0x8c,0xa9,0xd3,0x8b,0xaa,0xd2,0x8a,0xab,0xd2,0x8a,0xac,0xd2,0x89,0xad,0xd2,0x88,0xae,0xd2,0x88,0xaf,0xd1,0x87,0xb0,0xd1,0x87,0xb1,0xd1,0x86,0xb2,0xd1,0x86,0xb3,0xd1,0x85,0xb4,0xd0,0x85,0xb5,0xd0,0x84,0xb6,0xd0,0x84,0xb7,0xd0,0x83,0xb8,0xcf,0x83,0xb9,0xcf,0x82,0xba,0xcf,0x82,0xbb,0xcf,0x81,0xbc,0xcf,0x81,0xbd,0xce,0x80,0xbe,0xce,0x80,0xbf,0xce,0x7f,0xc0,0xce,0x7f,0xc1,0xcd,0x7f,0xc2,0xcd,0x7e,0xc3,0xcd,0x7e,0xc4,0xcd,0x7d,0xc5,0xcc,0x7d,0xc5,0xcc,0x7d,0xc6,0xcc,0x7c,0xc7,0xcc,0x7c,0xc8,0xcb,0x7c,0xc9,0xcb,0x7b,0xca,0xcb,0x7b,0xcb,0xcb,0x7b,0xcc,0xca,0x7a,0xcd,0xca,0x7a,0xce,0xca,0x7a,0xcf,0xca,0x79,0xd0,0xc9,0x79,0xd1,0xc9,0x79,0xd1,0xc9,0x79,0xd2,0xc9,0x78,0xd3,0xc8,0x78,0xd4,0xc8,0x78,0xd5,0xc8,0x78,0xd6,0xc7,0x77,0xd7,0xc7,0x77,0xd8,0xc7,0x77,0xd9,0xc7,0x77,0xd9,0xc6,0x77,0xda,0xc6,0x77,0xdb,0xc6,0x76,0xdc,0xc5,0x76,0xdd,0xc5,0x76,0xde,0xc5,0x76,0xdf,0xc5,0x76,0xe0,0xc4,0x76,0xe0,0xc4,0x76,0xe1,0xc4,0x76,0xe2,0xc3,0x76,0xe3,0xc3,0x76,0xe4,0xc3,0x76,0xe5,0xc2,0x76,0xe5,0xc2,0x76,0xe6,0xc2,0x76,0xe7,0xc2,0x76,0xe8,0xc1,0x76,0xe9,0xc1,0x76,0xe9,0xc1,0x76,0xea,0xc0,0x76,0xeb,0xc0,0x76,0xec,0xc0,0x76,0xed,0xbf,0x76,0xed,0xbf,0x76,0xee,0xbf,0x76,0xef,0xbe,0x76,0xf0,0xbe,0x77,0xf1,0xbe,0x77,0xf1,0xbd,0x77,0xf2,0xbd,0x77,0xf3,0xbd,0x77,0xf4,0xbc,0x77,0xf4,0xbc,0x78,0xf5,0xbc,0x78,0xf6,0xbc,0x78,0xf7,0xbb,0x78,0xf7,0xbb,0x79,0xf8,0xbb,0x79,0xf9,0xba,0x79,0xf9,0xba,0x79,0xfa,0xba,0x7a,0xfb,0xb9,0x7a,0xfc,0xb9,0x7a,0xfc,0xb9,0x7a,0xfd,0xb8,0x7b,0xfe,0xb8,0x7b,0xfe,0xb8,0x7b,0xff,0xb7,0x7c,0xff,0xb7,0x7c,0xff,0xb7,0x7c,0xff,0xb6,0x7d,0xff,0xb6,0x7d,0xff,0xb6,0x7d,0xff,0xb5,0x7e,0xff,0xb5,0x7e,0xff,0xb5,0x7f,0xff,0xb4,0x7f,0xff,0xb4,0x7f,0xff,0xb4,0x80,0xff,0xb3,0x80,0xff,0xb3,0x81,0xff,0xb3,0x81,0xff,0xb2,0x81}; - static constexpr std::array I3 = {0x14,0xba,0xe6,0x19,0xb9,0xe6,0x1d,0xb9,0xe6,0x20,0xb9,0xe6,0x23,0xb9,0xe6,0x26,0xb9,0xe6,0x29,0xb9,0xe6,0x2c,0xb8,0xe7,0x2e,0xb8,0xe7,0x30,0xb8,0xe7,0x33,0xb8,0xe7,0x35,0xb8,0xe7,0x37,0xb8,0xe7,0x39,0xb8,0xe7,0x3b,0xb7,0xe8,0x3c,0xb7,0xe8,0x3e,0xb7,0xe8,0x40,0xb7,0xe8,0x42,0xb7,0xe8,0x43,0xb7,0xe8,0x45,0xb6,0xe8,0x46,0xb6,0xe8,0x48,0xb6,0xe9,0x4a,0xb6,0xe9,0x4b,0xb6,0xe9,0x4c,0xb6,0xe9,0x4e,0xb6,0xe9,0x4f,0xb5,0xe9,0x51,0xb5,0xe9,0x52,0xb5,0xe9,0x53,0xb5,0xe9,0x55,0xb5,0xe9,0x56,0xb5,0xea,0x57,0xb4,0xea,0x59,0xb4,0xea,0x5a,0xb4,0xea,0x5b,0xb4,0xea,0x5c,0xb4,0xea,0x5d,0xb4,0xea,0x5f,0xb3,0xea,0x60,0xb3,0xea,0x61,0xb3,0xea,0x62,0xb3,0xeb,0x63,0xb3,0xeb,0x64,0xb2,0xeb,0x66,0xb2,0xeb,0x67,0xb2,0xeb,0x68,0xb2,0xeb,0x69,0xb2,0xeb,0x6a,0xb2,0xeb,0x6b,0xb1,0xeb,0x6c,0xb1,0xeb,0x6d,0xb1,0xeb,0x6e,0xb1,0xeb,0x6f,0xb1,0xeb,0x70,0xb1,0xeb,0x71,0xb0,0xec,0x72,0xb0,0xec,0x73,0xb0,0xec,0x74,0xb0,0xec,0x75,0xb0,0xec,0x76,0xaf,0xec,0x77,0xaf,0xec,0x78,0xaf,0xec,0x79,0xaf,0xec,0x7a,0xaf,0xec,0x7b,0xae,0xec,0x7c,0xae,0xec,0x7d,0xae,0xec,0x7e,0xae,0xec,0x7f,0xae,0xec,0x80,0xae,0xec,0x81,0xad,0xec,0x82,0xad,0xec,0x83,0xad,0xec,0x84,0xad,0xec,0x85,0xad,0xec,0x86,0xac,0xec,0x87,0xac,0xec,0x88,0xac,0xec,0x89,0xac,0xec,0x8a,0xac,0xec,0x8b,0xab,0xec,0x8b,0xab,0xec,0x8c,0xab,0xec,0x8d,0xab,0xec,0x8e,0xaa,0xec,0x8f,0xaa,0xec,0x90,0xaa,0xec,0x91,0xaa,0xec,0x92,0xaa,0xec,0x93,0xa9,0xec,0x94,0xa9,0xec,0x95,0xa9,0xec,0x95,0xa9,0xeb,0x96,0xa9,0xeb,0x97,0xa8,0xeb,0x98,0xa8,0xeb,0x99,0xa8,0xeb,0x9a,0xa8,0xeb,0x9b,0xa7,0xeb,0x9c,0xa7,0xeb,0x9c,0xa7,0xeb,0x9d,0xa7,0xeb,0x9e,0xa7,0xea,0x9f,0xa6,0xea,0xa0,0xa6,0xea,0xa1,0xa6,0xea,0xa2,0xa6,0xea,0xa3,0xa5,0xea,0xa3,0xa5,0xe9,0xa4,0xa5,0xe9,0xa5,0xa5,0xe9,0xa6,0xa5,0xe9,0xa7,0xa4,0xe9,0xa8,0xa4,0xe8,0xa9,0xa4,0xe8,0xa9,0xa4,0xe8,0xaa,0xa3,0xe8,0xab,0xa3,0xe7,0xac,0xa3,0xe7,0xad,0xa3,0xe7,0xae,0xa3,0xe7,0xaf,0xa2,0xe6,0xaf,0xa2,0xe6,0xb0,0xa2,0xe6,0xb1,0xa2,0xe5,0xb2,0xa1,0xe5,0xb3,0xa1,0xe5,0xb3,0xa1,0xe4,0xb4,0xa1,0xe4,0xb5,0xa1,0xe4,0xb6,0xa0,0xe3,0xb7,0xa0,0xe3,0xb7,0xa0,0xe3,0xb8,0xa0,0xe2,0xb9,0x9f,0xe2,0xba,0x9f,0xe2,0xba,0x9f,0xe1,0xbb,0x9f,0xe1,0xbc,0x9f,0xe0,0xbd,0x9e,0xe0,0xbd,0x9e,0xe0,0xbe,0x9e,0xdf,0xbf,0x9e,0xdf,0xc0,0x9e,0xdf,0xc0,0x9d,0xde,0xc1,0x9d,0xde,0xc2,0x9d,0xdd,0xc3,0x9d,0xdd,0xc3,0x9c,0xdd,0xc4,0x9c,0xdc,0xc5,0x9c,0xdc,0xc5,0x9c,0xdb,0xc6,0x9c,0xdb,0xc7,0x9b,0xdb,0xc7,0x9b,0xda,0xc8,0x9b,0xda,0xc9,0x9b,0xd9,0xc9,0x9a,0xd9,0xca,0x9a,0xd8,0xcb,0x9a,0xd8,0xcb,0x9a,0xd8,0xcc,0x9a,0xd7,0xcd,0x99,0xd7,0xcd,0x99,0xd6,0xce,0x99,0xd6,0xcf,0x99,0xd5,0xcf,0x99,0xd5,0xd0,0x98,0xd5,0xd1,0x98,0xd4,0xd1,0x98,0xd4,0xd2,0x98,0xd3,0xd3,0x97,0xd3,0xd3,0x97,0xd2,0xd4,0x97,0xd2,0xd4,0x97,0xd2,0xd5,0x97,0xd1,0xd6,0x96,0xd1,0xd6,0x96,0xd0,0xd7,0x96,0xd0,0xd7,0x96,0xcf,0xd8,0x95,0xcf,0xd9,0x95,0xce,0xd9,0x95,0xce,0xda,0x95,0xce,0xda,0x95,0xcd,0xdb,0x94,0xcd,0xdc,0x94,0xcc,0xdc,0x94,0xcc,0xdd,0x94,0xcb,0xdd,0x94,0xcb,0xde,0x93,0xca,0xde,0x93,0xca,0xdf,0x93,0xca,0xe0,0x93,0xc9,0xe0,0x92,0xc9,0xe1,0x92,0xc8,0xe1,0x92,0xc8,0xe2,0x92,0xc7,0xe2,0x92,0xc7,0xe3,0x91,0xc6,0xe3,0x91,0xc6,0xe4,0x91,0xc5,0xe5,0x91,0xc5,0xe5,0x90,0xc4,0xe6,0x90,0xc4,0xe6,0x90,0xc4,0xe7,0x90,0xc3,0xe7,0x90,0xc3,0xe8,0x8f,0xc2,0xe8,0x8f,0xc2,0xe9,0x8f,0xc1,0xe9,0x8f,0xc1,0xea,0x8e,0xc0,0xea,0x8e,0xc0,0xeb,0x8e,0xbf,0xeb,0x8e,0xbf,0xec,0x8e,0xbe,0xec,0x8d,0xbe,0xed,0x8d,0xbe,0xed,0x8d,0xbd,0xee,0x8d,0xbd,0xee,0x8c,0xbc,0xef,0x8c,0xbc,0xef,0x8c,0xbb,0xf0,0x8c,0xbb,0xf0,0x8b,0xba,0xf1,0x8b,0xba,0xf1,0x8b,0xb9,0xf2,0x8b,0xb9,0xf2,0x8b,0xb8,0xf3,0x8a,0xb8,0xf3,0x8a,0xb7,0xf4,0x8a,0xb7,0xf4,0x8a,0xb6,0xf5,0x89,0xb6,0xf5,0x89,0xb5,0xf6,0x89,0xb5,0xf6,0x89,0xb5,0xf7,0x88,0xb4,0xf7,0x88,0xb4,0xf8,0x88,0xb3,0xf8,0x88,0xb3,0xf9,0x88,0xb2,0xf9,0x87,0xb2,0xf9,0x87,0xb1,0xfa,0x87,0xb1,0xfa,0x87,0xb0,0xfb,0x86,0xb0,0xfb,0x86,0xaf,0xfc,0x86,0xaf,0xfc,0x86,0xae,0xfd,0x85,0xae,0xfd,0x85,0xad,0xfe,0x85,0xad}; +// isoluminant +static constexpr std::array I1 = { + 0x37, 0xb7, 0xec, 0x38, 0xb7, 0xeb, 0x38, 0xb7, 0xea, 0x39, 0xb7, 0xea, 0x39, 0xb7, 0xe9, 0x3a, + 0xb7, 0xe8, 0x3b, 0xb8, 0xe7, 0x3b, 0xb8, 0xe6, 0x3c, 0xb8, 0xe5, 0x3c, 0xb8, 0xe4, 0x3d, 0xb8, + 0xe3, 0x3d, 0xb8, 0xe3, 0x3e, 0xb8, 0xe2, 0x3e, 0xb8, 0xe1, 0x3f, 0xb8, 0xe0, 0x3f, 0xb8, 0xdf, + 0x40, 0xb8, 0xde, 0x40, 0xb8, 0xdd, 0x41, 0xb8, 0xdc, 0x42, 0xb8, 0xdc, 0x42, 0xb9, 0xdb, 0x43, + 0xb9, 0xda, 0x43, 0xb9, 0xd9, 0x44, 0xb9, 0xd8, 0x44, 0xb9, 0xd7, 0x45, 0xb9, 0xd6, 0x45, 0xb9, + 0xd5, 0x45, 0xb9, 0xd4, 0x46, 0xb9, 0xd4, 0x46, 0xb9, 0xd3, 0x47, 0xb9, 0xd2, 0x47, 0xb9, 0xd1, + 0x48, 0xb9, 0xd0, 0x48, 0xb9, 0xcf, 0x49, 0xb9, 0xce, 0x49, 0xb9, 0xcd, 0x4a, 0xba, 0xcc, 0x4a, + 0xba, 0xcb, 0x4b, 0xba, 0xcb, 0x4b, 0xba, 0xca, 0x4c, 0xba, 0xc9, 0x4c, 0xba, 0xc8, 0x4d, 0xba, + 0xc7, 0x4d, 0xba, 0xc6, 0x4e, 0xba, 0xc5, 0x4e, 0xba, 0xc4, 0x4f, 0xba, 0xc3, 0x4f, 0xba, 0xc2, + 0x50, 0xba, 0xc1, 0x50, 0xba, 0xc1, 0x50, 0xba, 0xc0, 0x51, 0xba, 0xbf, 0x51, 0xba, 0xbe, 0x52, + 0xba, 0xbd, 0x52, 0xba, 0xbc, 0x53, 0xbb, 0xbb, 0x53, 0xbb, 0xba, 0x54, 0xbb, 0xb9, 0x54, 0xbb, + 0xb8, 0x55, 0xbb, 0xb7, 0x55, 0xbb, 0xb6, 0x56, 0xbb, 0xb5, 0x56, 0xbb, 0xb4, 0x57, 0xbb, 0xb3, + 0x57, 0xbb, 0xb3, 0x58, 0xbb, 0xb2, 0x58, 0xbb, 0xb1, 0x59, 0xbb, 0xb0, 0x59, 0xbb, 0xaf, 0x5a, + 0xbb, 0xae, 0x5b, 0xbb, 0xad, 0x5b, 0xbb, 0xac, 0x5c, 0xbb, 0xab, 0x5c, 0xbb, 0xaa, 0x5d, 0xbb, + 0xa9, 0x5d, 0xbb, 0xa8, 0x5e, 0xbb, 0xa7, 0x5e, 0xbb, 0xa6, 0x5f, 0xbb, 0xa5, 0x60, 0xbb, 0xa4, + 0x60, 0xbb, 0xa3, 0x61, 0xbb, 0xa2, 0x61, 0xbb, 0xa1, 0x62, 0xbb, 0xa0, 0x62, 0xbb, 0x9f, 0x63, + 0xbb, 0x9e, 0x64, 0xbb, 0x9d, 0x64, 0xbb, 0x9c, 0x65, 0xbb, 0x9b, 0x66, 0xbb, 0x9a, 0x66, 0xbb, + 0x99, 0x67, 0xbb, 0x98, 0x68, 0xbb, 0x97, 0x68, 0xbb, 0x97, 0x69, 0xbb, 0x96, 0x6a, 0xbb, 0x95, + 0x6a, 0xbb, 0x94, 0x6b, 0xbb, 0x93, 0x6c, 0xbb, 0x92, 0x6d, 0xbb, 0x91, 0x6d, 0xbb, 0x90, 0x6e, + 0xbb, 0x8f, 0x6f, 0xbb, 0x8e, 0x70, 0xbb, 0x8d, 0x71, 0xbb, 0x8c, 0x71, 0xbb, 0x8b, 0x72, 0xbb, + 0x8a, 0x73, 0xba, 0x89, 0x74, 0xba, 0x88, 0x75, 0xba, 0x87, 0x76, 0xba, 0x86, 0x76, 0xba, 0x85, + 0x77, 0xba, 0x84, 0x78, 0xba, 0x83, 0x79, 0xba, 0x82, 0x7a, 0xba, 0x81, 0x7b, 0xba, 0x80, 0x7c, + 0xba, 0x7f, 0x7d, 0xb9, 0x7e, 0x7e, 0xb9, 0x7d, 0x7f, 0xb9, 0x7c, 0x80, 0xb9, 0x7c, 0x81, 0xb9, + 0x7b, 0x82, 0xb9, 0x7a, 0x83, 0xb9, 0x79, 0x84, 0xb8, 0x78, 0x85, 0xb8, 0x77, 0x86, 0xb8, 0x77, + 0x87, 0xb8, 0x76, 0x88, 0xb8, 0x75, 0x89, 0xb8, 0x74, 0x8a, 0xb8, 0x73, 0x8b, 0xb7, 0x73, 0x8c, + 0xb7, 0x72, 0x8e, 0xb7, 0x71, 0x8f, 0xb7, 0x71, 0x90, 0xb7, 0x70, 0x91, 0xb6, 0x6f, 0x92, 0xb6, + 0x6f, 0x93, 0xb6, 0x6e, 0x94, 0xb6, 0x6d, 0x95, 0xb6, 0x6d, 0x96, 0xb5, 0x6c, 0x97, 0xb5, 0x6c, + 0x98, 0xb5, 0x6b, 0x99, 0xb5, 0x6b, 0x9a, 0xb4, 0x6a, 0x9b, 0xb4, 0x6a, 0x9d, 0xb4, 0x69, 0x9e, + 0xb4, 0x69, 0x9f, 0xb3, 0x68, 0xa0, 0xb3, 0x68, 0xa1, 0xb3, 0x67, 0xa2, 0xb3, 0x67, 0xa3, 0xb2, + 0x66, 0xa4, 0xb2, 0x66, 0xa5, 0xb2, 0x65, 0xa6, 0xb2, 0x65, 0xa7, 0xb1, 0x64, 0xa8, 0xb1, 0x64, + 0xa9, 0xb1, 0x64, 0xaa, 0xb1, 0x63, 0xab, 0xb0, 0x63, 0xac, 0xb0, 0x63, 0xad, 0xb0, 0x62, 0xae, + 0xb0, 0x62, 0xaf, 0xaf, 0x62, 0xb0, 0xaf, 0x61, 0xb1, 0xaf, 0x61, 0xb2, 0xaf, 0x61, 0xb3, 0xae, + 0x60, 0xb4, 0xae, 0x60, 0xb5, 0xae, 0x60, 0xb5, 0xad, 0x60, 0xb6, 0xad, 0x5f, 0xb7, 0xad, 0x5f, + 0xb8, 0xac, 0x5f, 0xb9, 0xac, 0x5f, 0xba, 0xac, 0x5f, 0xbb, 0xac, 0x5f, 0xbc, 0xab, 0x5e, 0xbd, + 0xab, 0x5e, 0xbe, 0xab, 0x5e, 0xbf, 0xaa, 0x5e, 0xc0, 0xaa, 0x5e, 0xc1, 0xaa, 0x5e, 0xc2, 0xa9, + 0x5e, 0xc2, 0xa9, 0x5e, 0xc3, 0xa9, 0x5e, 0xc4, 0xa8, 0x5e, 0xc5, 0xa8, 0x5d, 0xc6, 0xa8, 0x5d, + 0xc7, 0xa8, 0x5d, 0xc8, 0xa7, 0x5d, 0xc9, 0xa7, 0x5d, 0xc9, 0xa7, 0x5d, 0xca, 0xa6, 0x5e, 0xcb, + 0xa6, 0x5e, 0xcc, 0xa6, 0x5e, 0xcd, 0xa5, 0x5e, 0xce, 0xa5, 0x5e, 0xcf, 0xa5, 0x5e, 0xcf, 0xa4, + 0x5e, 0xd0, 0xa4, 0x5e, 0xd1, 0xa4, 0x5e, 0xd2, 0xa3, 0x5e, 0xd3, 0xa3, 0x5e, 0xd3, 0xa2, 0x5e, + 0xd4, 0xa2, 0x5f, 0xd5, 0xa2, 0x5f, 0xd6, 0xa1, 0x5f, 0xd7, 0xa1, 0x5f, 0xd8, 0xa1, 0x5f, 0xd8, + 0xa0, 0x5f, 0xd9, 0xa0, 0x60, 0xda, 0xa0, 0x60, 0xdb, 0x9f, 0x60, 0xdb, 0x9f, 0x60, 0xdc, 0x9f, + 0x60, 0xdd, 0x9e, 0x61, 0xde, 0x9e, 0x61, 0xdf, 0x9d, 0x61, 0xdf, 0x9d, 0x61, 0xe0, 0x9d, 0x62, + 0xe1, 0x9c, 0x62, 0xe2, 0x9c, 0x62, 0xe2, 0x9c, 0x63, 0xe3, 0x9b, 0x63, 0xe4, 0x9b, 0x63, 0xe4, + 0x9a, 0x63, 0xe5, 0x9a, 0x64, 0xe6, 0x9a, 0x64, 0xe7, 0x99, 0x64, 0xe7, 0x99, 0x65, 0xe8, 0x99, + 0x65, 0xe9, 0x98, 0x65, 0xea, 0x98, 0x66, 0xea, 0x97, 0x66, 0xeb, 0x97, 0x66, 0xec, 0x97, 0x67, + 0xec, 0x96, 0x67, 0xed, 0x96, 0x67, 0xee, 0x95, 0x68, 0xee, 0x95, 0x68, 0xef, 0x95, 0x68, 0xf0, + 0x94, 0x69, 0xf0, 0x94, 0x69, 0xf1, 0x93, 0x6a, 0xf2, 0x93, 0x6a, 0xf2, 0x93, 0x6a, 0xf3, 0x92, + 0x6b, 0xf4, 0x92, 0x6b, 0xf4, 0x91, 0x6c, 0xf5, 0x91, 0x6c, 0xf6, 0x91, 0x6c, 0xf6, 0x90, 0x6d +}; +static constexpr std::array I2 = { + 0x70, 0xd1, 0xff, 0x70, 0xd2, 0xff, 0x70, 0xd2, 0xff, 0x70, 0xd2, 0xff, 0x70, 0xd2, 0xff, 0x70, + 0xd2, 0xfe, 0x70, 0xd2, 0xfe, 0x70, 0xd2, 0xfd, 0x70, 0xd2, 0xfc, 0x70, 0xd2, 0xfb, 0x70, 0xd2, + 0xfa, 0x70, 0xd2, 0xfa, 0x71, 0xd3, 0xf9, 0x71, 0xd3, 0xf8, 0x71, 0xd3, 0xf7, 0x71, 0xd3, 0xf7, + 0x71, 0xd3, 0xf6, 0x71, 0xd3, 0xf5, 0x71, 0xd3, 0xf4, 0x71, 0xd3, 0xf3, 0x71, 0xd3, 0xf3, 0x71, + 0xd3, 0xf2, 0x71, 0xd3, 0xf1, 0x72, 0xd4, 0xf0, 0x72, 0xd4, 0xef, 0x72, 0xd4, 0xee, 0x72, 0xd4, + 0xee, 0x72, 0xd4, 0xed, 0x72, 0xd4, 0xec, 0x72, 0xd4, 0xeb, 0x72, 0xd4, 0xea, 0x73, 0xd4, 0xea, + 0x73, 0xd4, 0xe9, 0x73, 0xd4, 0xe8, 0x73, 0xd4, 0xe7, 0x73, 0xd4, 0xe6, 0x73, 0xd5, 0xe5, 0x73, + 0xd5, 0xe5, 0x74, 0xd5, 0xe4, 0x74, 0xd5, 0xe3, 0x74, 0xd5, 0xe2, 0x74, 0xd5, 0xe1, 0x74, 0xd5, + 0xe1, 0x74, 0xd5, 0xe0, 0x74, 0xd5, 0xdf, 0x75, 0xd5, 0xde, 0x75, 0xd5, 0xdd, 0x75, 0xd5, 0xdc, + 0x75, 0xd5, 0xdb, 0x75, 0xd5, 0xdb, 0x76, 0xd5, 0xda, 0x76, 0xd6, 0xd9, 0x76, 0xd6, 0xd8, 0x76, + 0xd6, 0xd7, 0x76, 0xd6, 0xd6, 0x77, 0xd6, 0xd6, 0x77, 0xd6, 0xd5, 0x77, 0xd6, 0xd4, 0x77, 0xd6, + 0xd3, 0x77, 0xd6, 0xd2, 0x78, 0xd6, 0xd1, 0x78, 0xd6, 0xd0, 0x78, 0xd6, 0xd0, 0x78, 0xd6, 0xcf, + 0x79, 0xd6, 0xce, 0x79, 0xd6, 0xcd, 0x79, 0xd6, 0xcc, 0x7a, 0xd6, 0xcb, 0x7a, 0xd6, 0xca, 0x7a, + 0xd6, 0xc9, 0x7a, 0xd6, 0xc9, 0x7b, 0xd6, 0xc8, 0x7b, 0xd7, 0xc7, 0x7b, 0xd7, 0xc6, 0x7c, 0xd7, + 0xc5, 0x7c, 0xd7, 0xc4, 0x7c, 0xd7, 0xc3, 0x7d, 0xd7, 0xc2, 0x7d, 0xd7, 0xc1, 0x7d, 0xd7, 0xc1, + 0x7e, 0xd7, 0xc0, 0x7e, 0xd7, 0xbf, 0x7e, 0xd7, 0xbe, 0x7f, 0xd7, 0xbd, 0x7f, 0xd7, 0xbc, 0x80, + 0xd7, 0xbb, 0x80, 0xd7, 0xba, 0x81, 0xd7, 0xb9, 0x81, 0xd7, 0xb8, 0x81, 0xd7, 0xb8, 0x82, 0xd7, + 0xb7, 0x82, 0xd7, 0xb6, 0x83, 0xd7, 0xb5, 0x83, 0xd7, 0xb4, 0x84, 0xd7, 0xb3, 0x84, 0xd7, 0xb2, + 0x85, 0xd7, 0xb1, 0x85, 0xd7, 0xb0, 0x86, 0xd7, 0xaf, 0x86, 0xd7, 0xae, 0x87, 0xd7, 0xad, 0x88, + 0xd7, 0xac, 0x88, 0xd7, 0xac, 0x89, 0xd7, 0xab, 0x89, 0xd7, 0xaa, 0x8a, 0xd7, 0xa9, 0x8b, 0xd7, + 0xa8, 0x8b, 0xd7, 0xa7, 0x8c, 0xd7, 0xa6, 0x8d, 0xd6, 0xa5, 0x8d, 0xd6, 0xa4, 0x8e, 0xd6, 0xa3, + 0x8f, 0xd6, 0xa2, 0x90, 0xd6, 0xa1, 0x90, 0xd6, 0xa0, 0x91, 0xd6, 0xa0, 0x92, 0xd6, 0x9f, 0x93, + 0xd6, 0x9e, 0x93, 0xd6, 0x9d, 0x94, 0xd6, 0x9c, 0x95, 0xd6, 0x9b, 0x96, 0xd6, 0x9a, 0x97, 0xd5, + 0x99, 0x98, 0xd5, 0x99, 0x99, 0xd5, 0x98, 0x9a, 0xd5, 0x97, 0x9a, 0xd5, 0x96, 0x9b, 0xd5, 0x95, + 0x9c, 0xd5, 0x94, 0x9d, 0xd5, 0x94, 0x9e, 0xd4, 0x93, 0x9f, 0xd4, 0x92, 0xa0, 0xd4, 0x91, 0xa1, + 0xd4, 0x90, 0xa2, 0xd4, 0x90, 0xa3, 0xd4, 0x8f, 0xa4, 0xd3, 0x8e, 0xa5, 0xd3, 0x8e, 0xa6, 0xd3, + 0x8d, 0xa7, 0xd3, 0x8c, 0xa8, 0xd3, 0x8c, 0xa9, 0xd3, 0x8b, 0xaa, 0xd2, 0x8a, 0xab, 0xd2, 0x8a, + 0xac, 0xd2, 0x89, 0xad, 0xd2, 0x88, 0xae, 0xd2, 0x88, 0xaf, 0xd1, 0x87, 0xb0, 0xd1, 0x87, 0xb1, + 0xd1, 0x86, 0xb2, 0xd1, 0x86, 0xb3, 0xd1, 0x85, 0xb4, 0xd0, 0x85, 0xb5, 0xd0, 0x84, 0xb6, 0xd0, + 0x84, 0xb7, 0xd0, 0x83, 0xb8, 0xcf, 0x83, 0xb9, 0xcf, 0x82, 0xba, 0xcf, 0x82, 0xbb, 0xcf, 0x81, + 0xbc, 0xcf, 0x81, 0xbd, 0xce, 0x80, 0xbe, 0xce, 0x80, 0xbf, 0xce, 0x7f, 0xc0, 0xce, 0x7f, 0xc1, + 0xcd, 0x7f, 0xc2, 0xcd, 0x7e, 0xc3, 0xcd, 0x7e, 0xc4, 0xcd, 0x7d, 0xc5, 0xcc, 0x7d, 0xc5, 0xcc, + 0x7d, 0xc6, 0xcc, 0x7c, 0xc7, 0xcc, 0x7c, 0xc8, 0xcb, 0x7c, 0xc9, 0xcb, 0x7b, 0xca, 0xcb, 0x7b, + 0xcb, 0xcb, 0x7b, 0xcc, 0xca, 0x7a, 0xcd, 0xca, 0x7a, 0xce, 0xca, 0x7a, 0xcf, 0xca, 0x79, 0xd0, + 0xc9, 0x79, 0xd1, 0xc9, 0x79, 0xd1, 0xc9, 0x79, 0xd2, 0xc9, 0x78, 0xd3, 0xc8, 0x78, 0xd4, 0xc8, + 0x78, 0xd5, 0xc8, 0x78, 0xd6, 0xc7, 0x77, 0xd7, 0xc7, 0x77, 0xd8, 0xc7, 0x77, 0xd9, 0xc7, 0x77, + 0xd9, 0xc6, 0x77, 0xda, 0xc6, 0x77, 0xdb, 0xc6, 0x76, 0xdc, 0xc5, 0x76, 0xdd, 0xc5, 0x76, 0xde, + 0xc5, 0x76, 0xdf, 0xc5, 0x76, 0xe0, 0xc4, 0x76, 0xe0, 0xc4, 0x76, 0xe1, 0xc4, 0x76, 0xe2, 0xc3, + 0x76, 0xe3, 0xc3, 0x76, 0xe4, 0xc3, 0x76, 0xe5, 0xc2, 0x76, 0xe5, 0xc2, 0x76, 0xe6, 0xc2, 0x76, + 0xe7, 0xc2, 0x76, 0xe8, 0xc1, 0x76, 0xe9, 0xc1, 0x76, 0xe9, 0xc1, 0x76, 0xea, 0xc0, 0x76, 0xeb, + 0xc0, 0x76, 0xec, 0xc0, 0x76, 0xed, 0xbf, 0x76, 0xed, 0xbf, 0x76, 0xee, 0xbf, 0x76, 0xef, 0xbe, + 0x76, 0xf0, 0xbe, 0x77, 0xf1, 0xbe, 0x77, 0xf1, 0xbd, 0x77, 0xf2, 0xbd, 0x77, 0xf3, 0xbd, 0x77, + 0xf4, 0xbc, 0x77, 0xf4, 0xbc, 0x78, 0xf5, 0xbc, 0x78, 0xf6, 0xbc, 0x78, 0xf7, 0xbb, 0x78, 0xf7, + 0xbb, 0x79, 0xf8, 0xbb, 0x79, 0xf9, 0xba, 0x79, 0xf9, 0xba, 0x79, 0xfa, 0xba, 0x7a, 0xfb, 0xb9, + 0x7a, 0xfc, 0xb9, 0x7a, 0xfc, 0xb9, 0x7a, 0xfd, 0xb8, 0x7b, 0xfe, 0xb8, 0x7b, 0xfe, 0xb8, 0x7b, + 0xff, 0xb7, 0x7c, 0xff, 0xb7, 0x7c, 0xff, 0xb7, 0x7c, 0xff, 0xb6, 0x7d, 0xff, 0xb6, 0x7d, 0xff, + 0xb6, 0x7d, 0xff, 0xb5, 0x7e, 0xff, 0xb5, 0x7e, 0xff, 0xb5, 0x7f, 0xff, 0xb4, 0x7f, 0xff, 0xb4, + 0x7f, 0xff, 0xb4, 0x80, 0xff, 0xb3, 0x80, 0xff, 0xb3, 0x81, 0xff, 0xb3, 0x81, 0xff, 0xb2, 0x81 +}; +static constexpr std::array I3 = { + 0x14, 0xba, 0xe6, 0x19, 0xb9, 0xe6, 0x1d, 0xb9, 0xe6, 0x20, 0xb9, 0xe6, 0x23, 0xb9, 0xe6, 0x26, + 0xb9, 0xe6, 0x29, 0xb9, 0xe6, 0x2c, 0xb8, 0xe7, 0x2e, 0xb8, 0xe7, 0x30, 0xb8, 0xe7, 0x33, 0xb8, + 0xe7, 0x35, 0xb8, 0xe7, 0x37, 0xb8, 0xe7, 0x39, 0xb8, 0xe7, 0x3b, 0xb7, 0xe8, 0x3c, 0xb7, 0xe8, + 0x3e, 0xb7, 0xe8, 0x40, 0xb7, 0xe8, 0x42, 0xb7, 0xe8, 0x43, 0xb7, 0xe8, 0x45, 0xb6, 0xe8, 0x46, + 0xb6, 0xe8, 0x48, 0xb6, 0xe9, 0x4a, 0xb6, 0xe9, 0x4b, 0xb6, 0xe9, 0x4c, 0xb6, 0xe9, 0x4e, 0xb6, + 0xe9, 0x4f, 0xb5, 0xe9, 0x51, 0xb5, 0xe9, 0x52, 0xb5, 0xe9, 0x53, 0xb5, 0xe9, 0x55, 0xb5, 0xe9, + 0x56, 0xb5, 0xea, 0x57, 0xb4, 0xea, 0x59, 0xb4, 0xea, 0x5a, 0xb4, 0xea, 0x5b, 0xb4, 0xea, 0x5c, + 0xb4, 0xea, 0x5d, 0xb4, 0xea, 0x5f, 0xb3, 0xea, 0x60, 0xb3, 0xea, 0x61, 0xb3, 0xea, 0x62, 0xb3, + 0xeb, 0x63, 0xb3, 0xeb, 0x64, 0xb2, 0xeb, 0x66, 0xb2, 0xeb, 0x67, 0xb2, 0xeb, 0x68, 0xb2, 0xeb, + 0x69, 0xb2, 0xeb, 0x6a, 0xb2, 0xeb, 0x6b, 0xb1, 0xeb, 0x6c, 0xb1, 0xeb, 0x6d, 0xb1, 0xeb, 0x6e, + 0xb1, 0xeb, 0x6f, 0xb1, 0xeb, 0x70, 0xb1, 0xeb, 0x71, 0xb0, 0xec, 0x72, 0xb0, 0xec, 0x73, 0xb0, + 0xec, 0x74, 0xb0, 0xec, 0x75, 0xb0, 0xec, 0x76, 0xaf, 0xec, 0x77, 0xaf, 0xec, 0x78, 0xaf, 0xec, + 0x79, 0xaf, 0xec, 0x7a, 0xaf, 0xec, 0x7b, 0xae, 0xec, 0x7c, 0xae, 0xec, 0x7d, 0xae, 0xec, 0x7e, + 0xae, 0xec, 0x7f, 0xae, 0xec, 0x80, 0xae, 0xec, 0x81, 0xad, 0xec, 0x82, 0xad, 0xec, 0x83, 0xad, + 0xec, 0x84, 0xad, 0xec, 0x85, 0xad, 0xec, 0x86, 0xac, 0xec, 0x87, 0xac, 0xec, 0x88, 0xac, 0xec, + 0x89, 0xac, 0xec, 0x8a, 0xac, 0xec, 0x8b, 0xab, 0xec, 0x8b, 0xab, 0xec, 0x8c, 0xab, 0xec, 0x8d, + 0xab, 0xec, 0x8e, 0xaa, 0xec, 0x8f, 0xaa, 0xec, 0x90, 0xaa, 0xec, 0x91, 0xaa, 0xec, 0x92, 0xaa, + 0xec, 0x93, 0xa9, 0xec, 0x94, 0xa9, 0xec, 0x95, 0xa9, 0xec, 0x95, 0xa9, 0xeb, 0x96, 0xa9, 0xeb, + 0x97, 0xa8, 0xeb, 0x98, 0xa8, 0xeb, 0x99, 0xa8, 0xeb, 0x9a, 0xa8, 0xeb, 0x9b, 0xa7, 0xeb, 0x9c, + 0xa7, 0xeb, 0x9c, 0xa7, 0xeb, 0x9d, 0xa7, 0xeb, 0x9e, 0xa7, 0xea, 0x9f, 0xa6, 0xea, 0xa0, 0xa6, + 0xea, 0xa1, 0xa6, 0xea, 0xa2, 0xa6, 0xea, 0xa3, 0xa5, 0xea, 0xa3, 0xa5, 0xe9, 0xa4, 0xa5, 0xe9, + 0xa5, 0xa5, 0xe9, 0xa6, 0xa5, 0xe9, 0xa7, 0xa4, 0xe9, 0xa8, 0xa4, 0xe8, 0xa9, 0xa4, 0xe8, 0xa9, + 0xa4, 0xe8, 0xaa, 0xa3, 0xe8, 0xab, 0xa3, 0xe7, 0xac, 0xa3, 0xe7, 0xad, 0xa3, 0xe7, 0xae, 0xa3, + 0xe7, 0xaf, 0xa2, 0xe6, 0xaf, 0xa2, 0xe6, 0xb0, 0xa2, 0xe6, 0xb1, 0xa2, 0xe5, 0xb2, 0xa1, 0xe5, + 0xb3, 0xa1, 0xe5, 0xb3, 0xa1, 0xe4, 0xb4, 0xa1, 0xe4, 0xb5, 0xa1, 0xe4, 0xb6, 0xa0, 0xe3, 0xb7, + 0xa0, 0xe3, 0xb7, 0xa0, 0xe3, 0xb8, 0xa0, 0xe2, 0xb9, 0x9f, 0xe2, 0xba, 0x9f, 0xe2, 0xba, 0x9f, + 0xe1, 0xbb, 0x9f, 0xe1, 0xbc, 0x9f, 0xe0, 0xbd, 0x9e, 0xe0, 0xbd, 0x9e, 0xe0, 0xbe, 0x9e, 0xdf, + 0xbf, 0x9e, 0xdf, 0xc0, 0x9e, 0xdf, 0xc0, 0x9d, 0xde, 0xc1, 0x9d, 0xde, 0xc2, 0x9d, 0xdd, 0xc3, + 0x9d, 0xdd, 0xc3, 0x9c, 0xdd, 0xc4, 0x9c, 0xdc, 0xc5, 0x9c, 0xdc, 0xc5, 0x9c, 0xdb, 0xc6, 0x9c, + 0xdb, 0xc7, 0x9b, 0xdb, 0xc7, 0x9b, 0xda, 0xc8, 0x9b, 0xda, 0xc9, 0x9b, 0xd9, 0xc9, 0x9a, 0xd9, + 0xca, 0x9a, 0xd8, 0xcb, 0x9a, 0xd8, 0xcb, 0x9a, 0xd8, 0xcc, 0x9a, 0xd7, 0xcd, 0x99, 0xd7, 0xcd, + 0x99, 0xd6, 0xce, 0x99, 0xd6, 0xcf, 0x99, 0xd5, 0xcf, 0x99, 0xd5, 0xd0, 0x98, 0xd5, 0xd1, 0x98, + 0xd4, 0xd1, 0x98, 0xd4, 0xd2, 0x98, 0xd3, 0xd3, 0x97, 0xd3, 0xd3, 0x97, 0xd2, 0xd4, 0x97, 0xd2, + 0xd4, 0x97, 0xd2, 0xd5, 0x97, 0xd1, 0xd6, 0x96, 0xd1, 0xd6, 0x96, 0xd0, 0xd7, 0x96, 0xd0, 0xd7, + 0x96, 0xcf, 0xd8, 0x95, 0xcf, 0xd9, 0x95, 0xce, 0xd9, 0x95, 0xce, 0xda, 0x95, 0xce, 0xda, 0x95, + 0xcd, 0xdb, 0x94, 0xcd, 0xdc, 0x94, 0xcc, 0xdc, 0x94, 0xcc, 0xdd, 0x94, 0xcb, 0xdd, 0x94, 0xcb, + 0xde, 0x93, 0xca, 0xde, 0x93, 0xca, 0xdf, 0x93, 0xca, 0xe0, 0x93, 0xc9, 0xe0, 0x92, 0xc9, 0xe1, + 0x92, 0xc8, 0xe1, 0x92, 0xc8, 0xe2, 0x92, 0xc7, 0xe2, 0x92, 0xc7, 0xe3, 0x91, 0xc6, 0xe3, 0x91, + 0xc6, 0xe4, 0x91, 0xc5, 0xe5, 0x91, 0xc5, 0xe5, 0x90, 0xc4, 0xe6, 0x90, 0xc4, 0xe6, 0x90, 0xc4, + 0xe7, 0x90, 0xc3, 0xe7, 0x90, 0xc3, 0xe8, 0x8f, 0xc2, 0xe8, 0x8f, 0xc2, 0xe9, 0x8f, 0xc1, 0xe9, + 0x8f, 0xc1, 0xea, 0x8e, 0xc0, 0xea, 0x8e, 0xc0, 0xeb, 0x8e, 0xbf, 0xeb, 0x8e, 0xbf, 0xec, 0x8e, + 0xbe, 0xec, 0x8d, 0xbe, 0xed, 0x8d, 0xbe, 0xed, 0x8d, 0xbd, 0xee, 0x8d, 0xbd, 0xee, 0x8c, 0xbc, + 0xef, 0x8c, 0xbc, 0xef, 0x8c, 0xbb, 0xf0, 0x8c, 0xbb, 0xf0, 0x8b, 0xba, 0xf1, 0x8b, 0xba, 0xf1, + 0x8b, 0xb9, 0xf2, 0x8b, 0xb9, 0xf2, 0x8b, 0xb8, 0xf3, 0x8a, 0xb8, 0xf3, 0x8a, 0xb7, 0xf4, 0x8a, + 0xb7, 0xf4, 0x8a, 0xb6, 0xf5, 0x89, 0xb6, 0xf5, 0x89, 0xb5, 0xf6, 0x89, 0xb5, 0xf6, 0x89, 0xb5, + 0xf7, 0x88, 0xb4, 0xf7, 0x88, 0xb4, 0xf8, 0x88, 0xb3, 0xf8, 0x88, 0xb3, 0xf9, 0x88, 0xb2, 0xf9, + 0x87, 0xb2, 0xf9, 0x87, 0xb1, 0xfa, 0x87, 0xb1, 0xfa, 0x87, 0xb0, 0xfb, 0x86, 0xb0, 0xfb, 0x86, + 0xaf, 0xfc, 0x86, 0xaf, 0xfc, 0x86, 0xae, 0xfd, 0x85, 0xae, 0xfd, 0x85, 0xad, 0xfe, 0x85, 0xad +}; - // maps for the color blind - static constexpr std::array CBL1 = {0x11,0x11,0x11,0x11,0x12,0x13,0x12,0x13,0x15,0x12,0x13,0x17,0x13,0x14,0x19,0x13,0x15,0x1b,0x13,0x16,0x1d,0x14,0x16,0x1f,0x14,0x17,0x20,0x14,0x18,0x22,0x14,0x18,0x24,0x14,0x19,0x26,0x14,0x1a,0x28,0x14,0x1a,0x2a,0x14,0x1b,0x2c,0x14,0x1c,0x2e,0x14,0x1d,0x2f,0x14,0x1d,0x31,0x13,0x1e,0x33,0x13,0x1f,0x35,0x13,0x1f,0x37,0x13,0x20,0x39,0x12,0x21,0x3a,0x12,0x22,0x3c,0x12,0x22,0x3e,0x11,0x23,0x40,0x11,0x24,0x42,0x11,0x25,0x44,0x10,0x25,0x45,0x10,0x26,0x47,0x0f,0x27,0x49,0x0e,0x28,0x4b,0x0e,0x28,0x4d,0x0d,0x29,0x4e,0x0c,0x2a,0x50,0x0c,0x2b,0x52,0x0b,0x2b,0x54,0x0a,0x2c,0x55,0x09,0x2d,0x57,0x08,0x2e,0x59,0x07,0x2e,0x5a,0x06,0x2f,0x5c,0x06,0x30,0x5e,0x05,0x31,0x5f,0x04,0x31,0x61,0x03,0x32,0x63,0x02,0x33,0x64,0x02,0x34,0x66,0x01,0x35,0x67,0x00,0x35,0x69,0x00,0x36,0x6b,0x00,0x37,0x6c,0x00,0x38,0x6e,0x00,0x38,0x6f,0x00,0x39,0x71,0x00,0x3a,0x72,0x00,0x3b,0x73,0x00,0x3c,0x75,0x00,0x3c,0x76,0x00,0x3d,0x77,0x00,0x3e,0x79,0x00,0x3f,0x7a,0x00,0x40,0x7b,0x00,0x40,0x7d,0x01,0x41,0x7e,0x03,0x42,0x7f,0x04,0x43,0x80,0x05,0x44,0x81,0x07,0x44,0x82,0x09,0x45,0x83,0x0b,0x46,0x84,0x0d,0x47,0x85,0x0f,0x48,0x86,0x11,0x48,0x87,0x13,0x49,0x88,0x15,0x4a,0x89,0x18,0x4b,0x8a,0x1a,0x4c,0x8a,0x1c,0x4c,0x8b,0x1e,0x4d,0x8c,0x20,0x4e,0x8c,0x22,0x4f,0x8d,0x24,0x50,0x8d,0x26,0x50,0x8e,0x28,0x51,0x8e,0x2a,0x52,0x8e,0x2d,0x53,0x8e,0x2f,0x54,0x8f,0x31,0x54,0x8f,0x33,0x55,0x8f,0x35,0x56,0x8f,0x37,0x57,0x8f,0x3a,0x58,0x8e,0x3c,0x59,0x8e,0x3e,0x59,0x8e,0x40,0x5a,0x8d,0x43,0x5b,0x8d,0x45,0x5c,0x8c,0x47,0x5d,0x8b,0x49,0x5e,0x8b,0x4b,0x5e,0x8a,0x4d,0x5f,0x89,0x4f,0x60,0x89,0x51,0x61,0x88,0x53,0x62,0x87,0x55,0x63,0x87,0x57,0x64,0x86,0x59,0x64,0x85,0x5a,0x65,0x85,0x5c,0x66,0x84,0x5e,0x67,0x83,0x5f,0x68,0x83,0x61,0x69,0x82,0x63,0x6a,0x81,0x64,0x6a,0x80,0x66,0x6b,0x80,0x68,0x6c,0x7f,0x69,0x6d,0x7e,0x6b,0x6e,0x7e,0x6c,0x6f,0x7d,0x6e,0x70,0x7c,0x6f,0x71,0x7b,0x71,0x71,0x7b,0x72,0x72,0x7a,0x74,0x73,0x79,0x75,0x74,0x79,0x77,0x75,0x78,0x78,0x76,0x77,0x7a,0x77,0x76,0x7b,0x78,0x76,0x7c,0x79,0x75,0x7e,0x79,0x74,0x7f,0x7a,0x73,0x81,0x7b,0x73,0x82,0x7c,0x72,0x83,0x7d,0x71,0x85,0x7e,0x70,0x86,0x7f,0x6f,0x88,0x80,0x6f,0x89,0x81,0x6e,0x8a,0x81,0x6d,0x8c,0x82,0x6c,0x8d,0x83,0x6b,0x8e,0x84,0x6b,0x90,0x85,0x6a,0x91,0x86,0x69,0x92,0x87,0x68,0x94,0x88,0x67,0x95,0x89,0x67,0x96,0x8a,0x66,0x98,0x8a,0x65,0x99,0x8b,0x64,0x9a,0x8c,0x63,0x9c,0x8d,0x62,0x9d,0x8e,0x61,0x9e,0x8f,0x60,0xa0,0x90,0x60,0xa1,0x91,0x5f,0xa2,0x92,0x5e,0xa4,0x93,0x5d,0xa5,0x94,0x5c,0xa6,0x94,0x5b,0xa7,0x95,0x5b,0xa9,0x96,0x5a,0xaa,0x97,0x5a,0xab,0x98,0x59,0xac,0x99,0x59,0xad,0x9a,0x59,0xaf,0x9b,0x59,0xb0,0x9c,0x59,0xb1,0x9d,0x59,0xb2,0x9e,0x59,0xb3,0x9f,0x59,0xb4,0x9f,0x59,0xb5,0xa0,0x5a,0xb6,0xa1,0x5a,0xb7,0xa2,0x5a,0xb8,0xa3,0x5b,0xb9,0xa4,0x5b,0xba,0xa5,0x5c,0xbb,0xa6,0x5d,0xbc,0xa7,0x5e,0xbd,0xa8,0x5e,0xbf,0xa9,0x5f,0xc0,0xaa,0x60,0xc1,0xab,0x61,0xc1,0xac,0x62,0xc2,0xad,0x63,0xc3,0xae,0x64,0xc4,0xaf,0x65,0xc5,0xb0,0x67,0xc6,0xb0,0x68,0xc7,0xb1,0x69,0xc8,0xb2,0x6a,0xc9,0xb3,0x6c,0xca,0xb4,0x6d,0xcb,0xb5,0x6e,0xcc,0xb6,0x70,0xcd,0xb7,0x71,0xce,0xb8,0x73,0xcf,0xb9,0x75,0xcf,0xba,0x76,0xd0,0xbb,0x78,0xd1,0xbc,0x79,0xd2,0xbd,0x7b,0xd3,0xbe,0x7d,0xd4,0xbf,0x7f,0xd5,0xc0,0x80,0xd5,0xc1,0x82,0xd6,0xc2,0x84,0xd7,0xc3,0x86,0xd8,0xc4,0x88,0xd9,0xc5,0x8a,0xd9,0xc6,0x8c,0xda,0xc7,0x8d,0xdb,0xc8,0x8f,0xdc,0xc9,0x91,0xdd,0xca,0x94,0xdd,0xcb,0x96,0xde,0xcc,0x98,0xdf,0xcd,0x9a,0xdf,0xce,0x9c,0xe0,0xcf,0x9e,0xe1,0xd0,0xa0,0xe2,0xd1,0xa2,0xe2,0xd2,0xa5,0xe3,0xd3,0xa7,0xe4,0xd4,0xa9,0xe4,0xd5,0xab,0xe5,0xd6,0xae,0xe5,0xd7,0xb0,0xe6,0xd8,0xb2,0xe7,0xd9,0xb5,0xe7,0xda,0xb7,0xe8,0xdb,0xba,0xe8,0xdc,0xbc,0xe9,0xdd,0xbf,0xe9,0xde,0xc1,0xea,0xdf,0xc3,0xea,0xe0,0xc6,0xeb,0xe1,0xc9,0xeb,0xe2,0xcb,0xec,0xe3,0xce,0xec,0xe4,0xd0,0xed,0xe5,0xd3,0xed,0xe6,0xd5,0xee,0xe7,0xd8,0xee,0xe8,0xdb,0xee,0xe9,0xdd,0xef,0xea,0xe0,0xef,0xeb,0xe3,0xef,0xec,0xe6,0xf0,0xed,0xe8,0xf0,0xee,0xeb,0xf0,0xf0,0xee,0xf1,0xf1,0xf1}; - static constexpr std::array CBL2 = {0x11,0x11,0x11,0x11,0x12,0x13,0x12,0x13,0x15,0x13,0x13,0x17,0x13,0x14,0x18,0x14,0x15,0x1a,0x14,0x16,0x1c,0x14,0x17,0x1d,0x15,0x17,0x1f,0x15,0x18,0x21,0x15,0x19,0x22,0x16,0x19,0x24,0x16,0x1a,0x26,0x16,0x1b,0x27,0x16,0x1b,0x29,0x16,0x1c,0x2b,0x16,0x1d,0x2d,0x16,0x1e,0x2e,0x17,0x1e,0x30,0x17,0x1f,0x32,0x17,0x20,0x34,0x17,0x21,0x36,0x17,0x21,0x37,0x17,0x22,0x39,0x17,0x23,0x3b,0x16,0x24,0x3d,0x16,0x24,0x3f,0x16,0x25,0x40,0x16,0x26,0x42,0x16,0x27,0x44,0x16,0x27,0x46,0x15,0x28,0x48,0x15,0x29,0x4a,0x15,0x2a,0x4b,0x14,0x2b,0x4d,0x14,0x2b,0x4f,0x14,0x2c,0x51,0x13,0x2d,0x53,0x13,0x2e,0x54,0x13,0x2e,0x56,0x12,0x2f,0x58,0x12,0x30,0x5a,0x12,0x31,0x5b,0x11,0x32,0x5d,0x11,0x32,0x5f,0x11,0x33,0x60,0x10,0x34,0x62,0x10,0x35,0x63,0x10,0x36,0x65,0x10,0x36,0x67,0x10,0x37,0x68,0x10,0x38,0x6a,0x10,0x39,0x6b,0x0f,0x3a,0x6d,0x0f,0x3b,0x6e,0x0f,0x3b,0x70,0x0f,0x3c,0x71,0x0f,0x3d,0x73,0x0f,0x3e,0x74,0x0f,0x3f,0x76,0x0f,0x3f,0x77,0x0f,0x40,0x79,0x0f,0x41,0x7a,0x0f,0x42,0x7c,0x0f,0x43,0x7e,0x0f,0x44,0x7f,0x0f,0x44,0x81,0x0f,0x45,0x82,0x0f,0x46,0x84,0x0f,0x47,0x85,0x0f,0x48,0x87,0x0f,0x49,0x88,0x0f,0x49,0x8a,0x0f,0x4a,0x8b,0x0f,0x4b,0x8d,0x0f,0x4c,0x8e,0x0f,0x4d,0x90,0x0f,0x4e,0x92,0x0f,0x4f,0x93,0x0f,0x4f,0x95,0x0e,0x50,0x96,0x0e,0x51,0x98,0x0e,0x52,0x99,0x0e,0x53,0x9b,0x0e,0x54,0x9d,0x0e,0x55,0x9e,0x0e,0x56,0xa0,0x0e,0x56,0xa1,0x0d,0x57,0xa3,0x0d,0x58,0xa5,0x0d,0x59,0xa6,0x0d,0x5a,0xa8,0x0d,0x5b,0xa9,0x0d,0x5c,0xab,0x0c,0x5c,0xad,0x0c,0x5d,0xae,0x0c,0x5e,0xb0,0x0c,0x5f,0xb2,0x0b,0x60,0xb3,0x0b,0x61,0xb5,0x0b,0x62,0xb6,0x0a,0x63,0xb8,0x0a,0x64,0xba,0x0a,0x64,0xbb,0x09,0x65,0xbd,0x09,0x66,0xbf,0x09,0x67,0xc0,0x08,0x68,0xc2,0x08,0x69,0xc4,0x07,0x6a,0xc5,0x07,0x6b,0xc7,0x07,0x6c,0xc9,0x06,0x6d,0xca,0x06,0x6d,0xcc,0x05,0x6e,0xce,0x05,0x6f,0xcf,0x04,0x70,0xd1,0x04,0x71,0xd3,0x03,0x72,0xd4,0x03,0x73,0xd6,0x02,0x74,0xd8,0x02,0x75,0xd9,0x01,0x76,0xdb,0x01,0x77,0xdd,0x00,0x78,0xde,0x00,0x78,0xe0,0x00,0x79,0xe2,0x01,0x7a,0xe3,0x01,0x7b,0xe5,0x02,0x7c,0xe6,0x03,0x7d,0xe8,0x05,0x7e,0xe9,0x07,0x7f,0xeb,0x0b,0x80,0xec,0x0e,0x81,0xed,0x12,0x82,0xee,0x16,0x83,0xef,0x1a,0x84,0xf0,0x1f,0x84,0xf1,0x23,0x85,0xf2,0x28,0x86,0xf2,0x2d,0x87,0xf2,0x31,0x88,0xf2,0x36,0x89,0xf2,0x3b,0x8a,0xf2,0x40,0x8b,0xf1,0x45,0x8c,0xf0,0x4a,0x8d,0xef,0x4f,0x8d,0xee,0x54,0x8e,0xec,0x59,0x8f,0xea,0x5d,0x90,0xe8,0x62,0x91,0xe6,0x67,0x92,0xe4,0x6b,0x93,0xe2,0x6f,0x94,0xdf,0x73,0x95,0xdc,0x77,0x96,0xd9,0x7b,0x97,0xd6,0x7f,0x98,0xd4,0x83,0x99,0xd0,0x86,0x9a,0xcd,0x89,0x9b,0xca,0x8d,0x9b,0xc7,0x90,0x9c,0xc4,0x93,0x9d,0xc1,0x96,0x9e,0xbd,0x98,0x9f,0xba,0x9b,0xa0,0xb7,0x9e,0xa1,0xb4,0xa0,0xa2,0xb1,0xa3,0xa3,0xae,0xa5,0xa4,0xaa,0xa8,0xa5,0xa7,0xaa,0xa6,0xa4,0xac,0xa7,0xa1,0xaf,0xa8,0x9e,0xb1,0xa9,0x9b,0xb3,0xaa,0x98,0xb5,0xab,0x95,0xb7,0xac,0x92,0xb9,0xad,0x8f,0xbb,0xae,0x8c,0xbd,0xaf,0x89,0xbf,0xb0,0x86,0xc1,0xb1,0x83,0xc3,0xb2,0x80,0xc5,0xb3,0x7d,0xc7,0xb4,0x7a,0xc9,0xb5,0x77,0xca,0xb6,0x74,0xcc,0xb7,0x71,0xce,0xb8,0x6d,0xd0,0xb8,0x6a,0xd1,0xb9,0x67,0xd3,0xba,0x64,0xd5,0xbb,0x60,0xd6,0xbc,0x5d,0xd8,0xbd,0x5a,0xda,0xbe,0x56,0xdb,0xbf,0x52,0xdd,0xc0,0x4f,0xde,0xc1,0x4b,0xe0,0xc2,0x48,0xe1,0xc3,0x44,0xe3,0xc4,0x40,0xe4,0xc5,0x3c,0xe5,0xc6,0x39,0xe7,0xc7,0x35,0xe8,0xc8,0x31,0xe9,0xc9,0x2e,0xeb,0xca,0x2a,0xec,0xcb,0x27,0xed,0xcc,0x25,0xef,0xcd,0x23,0xf0,0xce,0x22,0xf1,0xcf,0x22,0xf2,0xd0,0x23,0xf3,0xd1,0x25,0xf4,0xd2,0x27,0xf5,0xd3,0x2b,0xf6,0xd4,0x2f,0xf7,0xd6,0x34,0xf8,0xd7,0x39,0xf9,0xd8,0x3e,0xfa,0xd9,0x44,0xfb,0xda,0x4a,0xfb,0xdb,0x50,0xfc,0xdc,0x56,0xfd,0xdd,0x5d,0xfd,0xde,0x63,0xfe,0xdf,0x6a,0xfe,0xe0,0x70,0xff,0xe1,0x77,0xff,0xe2,0x7e,0xff,0xe3,0x84,0xff,0xe4,0x8b,0xff,0xe5,0x92,0xff,0xe6,0x98,0xff,0xe7,0x9f,0xff,0xe8,0xa5,0xff,0xe9,0xab,0xff,0xeb,0xb1,0xff,0xec,0xb7,0xfe,0xed,0xbd,0xfe,0xee,0xc3,0xfe,0xef,0xc9,0xfd,0xf0,0xce,0xfd,0xf1,0xd3,0xfd,0xf2,0xd8,0xfd,0xf3,0xdd,0xfc,0xf5,0xe2,0xfc,0xf6,0xe7,0xfc,0xf7,0xeb,0xfc,0xf8,0xef,0xfc,0xf9,0xf3}; - static constexpr std::array CBC1 = {0x3e,0x87,0xea,0x41,0x88,0xeb,0x44,0x8a,0xed,0x47,0x8b,0xed,0x4b,0x8c,0xee,0x4f,0x8e,0xef,0x53,0x8f,0xef,0x57,0x91,0xf0,0x5a,0x93,0xf0,0x5e,0x94,0xf0,0x62,0x96,0xf0,0x66,0x97,0xf0,0x69,0x99,0xf0,0x6d,0x9a,0xf1,0x70,0x9c,0xf1,0x74,0x9e,0xf1,0x77,0x9f,0xf1,0x7a,0xa1,0xf1,0x7d,0xa2,0xf1,0x80,0xa4,0xf1,0x83,0xa6,0xf1,0x86,0xa7,0xf1,0x89,0xa9,0xf1,0x8c,0xab,0xf2,0x8f,0xac,0xf2,0x92,0xae,0xf2,0x95,0xb0,0xf2,0x97,0xb1,0xf2,0x9a,0xb3,0xf2,0x9d,0xb5,0xf2,0x9f,0xb6,0xf2,0xa2,0xb8,0xf2,0xa5,0xba,0xf2,0xa7,0xbb,0xf2,0xaa,0xbd,0xf2,0xac,0xbf,0xf3,0xaf,0xc1,0xf3,0xb2,0xc2,0xf3,0xb4,0xc4,0xf3,0xb7,0xc6,0xf3,0xb9,0xc7,0xf3,0xbb,0xc9,0xf3,0xbe,0xcb,0xf3,0xc0,0xcd,0xf3,0xc3,0xce,0xf3,0xc5,0xd0,0xf3,0xc8,0xd2,0xf3,0xca,0xd3,0xf3,0xcc,0xd5,0xf3,0xcf,0xd7,0xf3,0xd1,0xd9,0xf3,0xd3,0xda,0xf3,0xd6,0xdc,0xf3,0xd8,0xde,0xf3,0xda,0xe0,0xf3,0xdd,0xe1,0xf3,0xdf,0xe3,0xf3,0xe1,0xe4,0xf2,0xe3,0xe6,0xf2,0xe5,0xe7,0xf1,0xe6,0xe8,0xf0,0xe8,0xe9,0xef,0xe9,0xea,0xed,0xea,0xea,0xeb,0xeb,0xea,0xe9,0xec,0xea,0xe7,0xec,0xe9,0xe4,0xec,0xe8,0xe1,0xec,0xe7,0xde,0xeb,0xe6,0xdb,0xeb,0xe5,0xd8,0xea,0xe3,0xd5,0xe9,0xe2,0xd1,0xe8,0xe0,0xce,0xe7,0xde,0xca,0xe6,0xdd,0xc7,0xe5,0xdb,0xc3,0xe3,0xd9,0xc0,0xe2,0xd8,0xbc,0xe1,0xd6,0xb9,0xe0,0xd4,0xb6,0xdf,0xd2,0xb2,0xde,0xd0,0xaf,0xdc,0xcf,0xab,0xdb,0xcd,0xa8,0xda,0xcb,0xa4,0xd9,0xca,0xa1,0xd7,0xc8,0x9e,0xd6,0xc6,0x9a,0xd5,0xc4,0x97,0xd3,0xc3,0x93,0xd2,0xc1,0x90,0xd1,0xbf,0x8d,0xcf,0xbe,0x89,0xce,0xbc,0x86,0xcd,0xba,0x83,0xcb,0xb8,0x7f,0xca,0xb7,0x7c,0xc9,0xb5,0x78,0xc7,0xb3,0x75,0xc6,0xb2,0x72,0xc5,0xb0,0x6e,0xc3,0xae,0x6b,0xc2,0xad,0x68,0xc0,0xab,0x64,0xbf,0xa9,0x61,0xbd,0xa8,0x5d,0xbc,0xa6,0x5a,0xba,0xa4,0x57,0xb9,0xa3,0x53,0xb7,0xa1,0x50,0xb6,0x9f,0x4c,0xb4,0x9e,0x49,0xb3,0x9c,0x45,0xb1,0x9b,0x42,0xb0,0x99,0x3e,0xae,0x97,0x3b,0xad,0x96,0x37,0xab,0x94,0x33,0xa9,0x92,0x30,0xa8,0x91,0x2c,0xa6,0x8f,0x28,0xa5,0x8e,0x24,0xa3,0x8c,0x21,0xa1,0x8b,0x1d,0xa0,0x89,0x1a,0x9e,0x87,0x17,0x9c,0x86,0x14,0x9a,0x84,0x12,0x99,0x83,0x10,0x97,0x81,0x0f,0x95,0x80,0x0f,0x93,0x7e,0x0f,0x91,0x7c,0x0f,0x90,0x7b,0x10,0x8e,0x79,0x10,0x8c,0x78,0x11,0x8a,0x76,0x13,0x88,0x75,0x14,0x86,0x73,0x15,0x85,0x72,0x16,0x83,0x70,0x17,0x81,0x6f,0x18,0x7f,0x6d,0x18,0x7d,0x6c,0x19,0x7c,0x6a,0x1a,0x7a,0x69,0x1b,0x78,0x67,0x1c,0x76,0x65,0x1c,0x74,0x64,0x1d,0x73,0x63,0x1d,0x71,0x61,0x1e,0x6f,0x60,0x1f,0x6d,0x5e,0x1f,0x6b,0x5d,0x20,0x6a,0x5b,0x20,0x68,0x5a,0x21,0x66,0x58,0x21,0x64,0x57,0x21,0x63,0x55,0x22,0x61,0x54,0x22,0x5f,0x52,0x23,0x5d,0x51,0x23,0x5c,0x4f,0x23,0x5a,0x4e,0x24,0x58,0x4d,0x24,0x56,0x4b,0x24,0x54,0x4a,0x24,0x53,0x48,0x25,0x51,0x47,0x25,0x4f,0x46,0x25,0x4e,0x44,0x25,0x4c,0x43,0x26,0x4a,0x41,0x26,0x48,0x40,0x26,0x47,0x3f,0x26,0x45,0x3d,0x26,0x43,0x3c,0x27,0x41,0x3b,0x27,0x40,0x39,0x27,0x3e,0x38,0x27,0x3c,0x37,0x27,0x3a,0x35,0x27,0x39,0x34,0x28,0x37,0x33,0x28,0x36,0x32,0x28,0x34,0x31,0x29,0x33,0x30,0x2a,0x32,0x2f,0x2b,0x31,0x2f,0x2c,0x30,0x2e,0x2d,0x2f,0x2e,0x2e,0x2f,0x2e,0x30,0x2e,0x2f,0x32,0x2e,0x2f,0x34,0x2e,0x30,0x36,0x2e,0x31,0x38,0x2f,0x32,0x3b,0x2f,0x33,0x3d,0x30,0x34,0x40,0x30,0x35,0x43,0x31,0x36,0x45,0x32,0x37,0x48,0x32,0x39,0x4b,0x33,0x3a,0x4e,0x34,0x3c,0x51,0x34,0x3d,0x53,0x35,0x3e,0x56,0x35,0x40,0x59,0x36,0x41,0x5c,0x37,0x42,0x5f,0x37,0x44,0x62,0x38,0x45,0x65,0x38,0x47,0x68,0x39,0x48,0x6b,0x39,0x49,0x6e,0x39,0x4b,0x71,0x3a,0x4c,0x74,0x3a,0x4e,0x77,0x3a,0x4f,0x7a,0x3b,0x51,0x7d,0x3b,0x52,0x80,0x3b,0x54,0x83,0x3c,0x55,0x86,0x3c,0x56,0x89,0x3c,0x58,0x8c,0x3c,0x59,0x8f,0x3c,0x5b,0x93,0x3c,0x5c,0x96,0x3c,0x5e,0x99,0x3c,0x5f,0x9c,0x3c,0x61,0x9f,0x3c,0x62,0xa3,0x3c,0x64,0xa6,0x3c,0x65,0xa9,0x3c,0x67,0xac,0x3c,0x68,0xaf,0x3c,0x6a,0xb3,0x3c,0x6b,0xb6,0x3b,0x6d,0xb9,0x3b,0x6f,0xbc,0x3b,0x70,0xc0,0x3a,0x72,0xc3,0x3a,0x73,0xc6,0x39,0x75,0xca,0x39,0x76,0xcd,0x38,0x78,0xd0,0x38,0x79,0xd3,0x38,0x7b,0xd7,0x37,0x7c,0xda,0x37,0x7e,0xdd,0x37,0x7f,0xdf,0x38,0x81,0xe2,0x39,0x82,0xe4,0x3a,0x84,0xe6,0x3c,0x85,0xe8}; - static constexpr std::array CBC2 = {0xee,0xed,0xec,0xee,0xed,0xea,0xee,0xec,0xe8,0xee,0xeb,0xe5,0xee,0xea,0xe2,0xed,0xe9,0xdf,0xed,0xe8,0xdc,0xec,0xe6,0xd9,0xeb,0xe5,0xd5,0xea,0xe3,0xd2,0xe9,0xe1,0xce,0xe8,0xdf,0xca,0xe7,0xde,0xc7,0xe6,0xdc,0xc3,0xe5,0xda,0xbf,0xe4,0xd8,0xbc,0xe2,0xd6,0xb8,0xe1,0xd5,0xb4,0xe0,0xd3,0xb1,0xdf,0xd1,0xad,0xde,0xcf,0xa9,0xdc,0xce,0xa6,0xdb,0xcc,0xa2,0xda,0xca,0x9e,0xd9,0xc8,0x9b,0xd7,0xc7,0x97,0xd6,0xc5,0x94,0xd5,0xc3,0x90,0xd4,0xc1,0x8c,0xd2,0xc0,0x89,0xd1,0xbe,0x85,0xd0,0xbc,0x82,0xce,0xba,0x7e,0xcd,0xb9,0x7b,0xcb,0xb7,0x77,0xca,0xb5,0x73,0xc9,0xb4,0x70,0xc7,0xb2,0x6c,0xc6,0xb0,0x69,0xc4,0xae,0x65,0xc3,0xad,0x61,0xc1,0xab,0x5e,0xc0,0xa9,0x5a,0xbe,0xa8,0x56,0xbd,0xa6,0x53,0xbb,0xa4,0x4f,0xba,0xa3,0x4b,0xb8,0xa1,0x48,0xb7,0x9f,0x44,0xb5,0x9e,0x40,0xb4,0x9c,0x3c,0xb2,0x9a,0x38,0xb0,0x99,0x34,0xaf,0x97,0x30,0xad,0x96,0x2c,0xac,0x94,0x27,0xaa,0x93,0x23,0xa9,0x91,0x1e,0xa7,0x90,0x19,0xa6,0x8e,0x14,0xa5,0x8d,0x0f,0xa4,0x8d,0x0a,0xa3,0x8c,0x06,0xa3,0x8b,0x03,0xa3,0x8b,0x02,0xa3,0x8b,0x02,0xa3,0x8b,0x04,0xa4,0x8c,0x07,0xa4,0x8d,0x0c,0xa5,0x8e,0x11,0xa6,0x8f,0x16,0xa8,0x90,0x1b,0xa9,0x91,0x1f,0xab,0x93,0x24,0xac,0x94,0x28,0xae,0x96,0x2d,0xaf,0x98,0x31,0xb1,0x99,0x35,0xb2,0x9b,0x39,0xb4,0x9c,0x3d,0xb6,0x9e,0x41,0xb7,0xa0,0x45,0xb9,0xa1,0x49,0xba,0xa3,0x4c,0xbc,0xa5,0x50,0xbd,0xa6,0x54,0xbf,0xa8,0x57,0xc0,0xaa,0x5b,0xc2,0xab,0x5f,0xc3,0xad,0x62,0xc5,0xaf,0x66,0xc6,0xb1,0x6a,0xc8,0xb2,0x6d,0xc9,0xb4,0x71,0xca,0xb6,0x74,0xcc,0xb7,0x78,0xcd,0xb9,0x7c,0xcf,0xbb,0x7f,0xd0,0xbd,0x83,0xd1,0xbe,0x86,0xd3,0xc0,0x8a,0xd4,0xc2,0x8d,0xd5,0xc3,0x91,0xd6,0xc5,0x95,0xd8,0xc7,0x98,0xd9,0xc9,0x9c,0xda,0xcb,0x9f,0xdc,0xcc,0xa3,0xdd,0xce,0xa7,0xde,0xd0,0xaa,0xdf,0xd2,0xae,0xe0,0xd3,0xb2,0xe2,0xd5,0xb5,0xe3,0xd7,0xb9,0xe4,0xd9,0xbd,0xe5,0xda,0xc0,0xe6,0xdc,0xc4,0xe7,0xde,0xc8,0xe8,0xe0,0xcb,0xe9,0xe1,0xcf,0xea,0xe3,0xd3,0xeb,0xe5,0xd6,0xec,0xe6,0xda,0xec,0xe7,0xdd,0xec,0xe8,0xe0,0xec,0xe9,0xe3,0xec,0xea,0xe6,0xec,0xea,0xe9,0xeb,0xea,0xeb,0xea,0xea,0xed,0xe9,0xea,0xef,0xe7,0xe9,0xf0,0xe6,0xe8,0xf2,0xe4,0xe7,0xf3,0xe2,0xe5,0xf3,0xe0,0xe4,0xf4,0xdd,0xe2,0xf4,0xdb,0xe1,0xf5,0xd9,0xdf,0xf5,0xd6,0xdd,0xf5,0xd4,0xdb,0xf5,0xd2,0xda,0xf5,0xcf,0xd8,0xf6,0xcd,0xd6,0xf6,0xca,0xd4,0xf6,0xc8,0xd3,0xf6,0xc5,0xd1,0xf6,0xc3,0xcf,0xf6,0xc0,0xcd,0xf6,0xbe,0xcc,0xf6,0xbb,0xca,0xf6,0xb8,0xc8,0xf7,0xb6,0xc6,0xf7,0xb3,0xc5,0xf7,0xb1,0xc3,0xf7,0xae,0xc1,0xf7,0xab,0xbf,0xf7,0xa8,0xbe,0xf7,0xa6,0xbc,0xf7,0xa3,0xba,0xf7,0xa0,0xb9,0xf7,0x9d,0xb7,0xf7,0x9a,0xb5,0xf7,0x97,0xb3,0xf7,0x94,0xb2,0xf8,0x91,0xb0,0xf8,0x8e,0xae,0xf8,0x8b,0xad,0xf8,0x88,0xab,0xf8,0x85,0xa9,0xf8,0x82,0xa8,0xf8,0x7e,0xa6,0xf8,0x7b,0xa4,0xf8,0x78,0xa3,0xf8,0x74,0xa1,0xf8,0x70,0x9f,0xf8,0x6d,0x9e,0xf8,0x69,0x9c,0xf8,0x65,0x9b,0xf8,0x61,0x99,0xf8,0x5d,0x97,0xf8,0x58,0x96,0xf8,0x54,0x94,0xf8,0x4f,0x93,0xf8,0x4b,0x92,0xf8,0x46,0x90,0xf8,0x42,0x8f,0xf8,0x3e,0x8e,0xf8,0x3b,0x8d,0xf8,0x38,0x8d,0xf8,0x37,0x8c,0xf8,0x36,0x8c,0xf8,0x37,0x8c,0xf8,0x39,0x8d,0xf8,0x3b,0x8d,0xf8,0x3f,0x8e,0xf8,0x43,0x8f,0xf8,0x47,0x91,0xf8,0x4c,0x92,0xf8,0x50,0x93,0xf8,0x55,0x95,0xf8,0x59,0x96,0xf8,0x5e,0x98,0xf8,0x62,0x99,0xf8,0x66,0x9b,0xf8,0x6a,0x9d,0xf8,0x6e,0x9e,0xf8,0x71,0xa0,0xf8,0x75,0xa1,0xf8,0x78,0xa3,0xf8,0x7c,0xa5,0xf8,0x7f,0xa6,0xf8,0x82,0xa8,0xf8,0x86,0xaa,0xf8,0x89,0xab,0xf8,0x8c,0xad,0xf8,0x8f,0xaf,0xf8,0x92,0xb0,0xf8,0x95,0xb2,0xf8,0x98,0xb4,0xf7,0x9b,0xb5,0xf7,0x9e,0xb7,0xf7,0xa1,0xb9,0xf7,0xa3,0xbb,0xf7,0xa6,0xbc,0xf7,0xa9,0xbe,0xf7,0xac,0xc0,0xf7,0xae,0xc1,0xf7,0xb1,0xc3,0xf7,0xb4,0xc5,0xf7,0xb6,0xc7,0xf7,0xb9,0xc8,0xf7,0xbc,0xca,0xf6,0xbe,0xcc,0xf6,0xc1,0xce,0xf6,0xc3,0xcf,0xf6,0xc6,0xd1,0xf6,0xc8,0xd3,0xf6,0xcb,0xd5,0xf6,0xcd,0xd7,0xf6,0xd0,0xd8,0xf6,0xd2,0xda,0xf5,0xd5,0xdc,0xf5,0xd7,0xde,0xf5,0xd9,0xdf,0xf5,0xdc,0xe1,0xf5,0xde,0xe3,0xf5,0xe0,0xe5,0xf4,0xe3,0xe6,0xf4,0xe5,0xe8,0xf4,0xe7,0xe9,0xf3,0xe8,0xea,0xf3,0xea,0xeb,0xf2,0xeb,0xec,0xf1,0xed,0xed,0xf0,0xed,0xed,0xee}; - static constexpr std::array CBD1 = {0x3a,0x90,0xfe,0x3e,0x91,0xfe,0x41,0x92,0xfe,0x44,0x92,0xfe,0x46,0x93,0xfe,0x49,0x94,0xfe,0x4c,0x94,0xfe,0x4e,0x95,0xfe,0x50,0x96,0xfe,0x53,0x97,0xfd,0x55,0x97,0xfd,0x57,0x98,0xfd,0x59,0x99,0xfd,0x5b,0x99,0xfd,0x5e,0x9a,0xfd,0x60,0x9b,0xfd,0x61,0x9b,0xfd,0x63,0x9c,0xfd,0x65,0x9d,0xfd,0x67,0x9e,0xfd,0x69,0x9e,0xfd,0x6b,0x9f,0xfd,0x6d,0xa0,0xfc,0x6e,0xa0,0xfc,0x70,0xa1,0xfc,0x72,0xa2,0xfc,0x73,0xa3,0xfc,0x75,0xa3,0xfc,0x77,0xa4,0xfc,0x78,0xa5,0xfc,0x7a,0xa5,0xfc,0x7c,0xa6,0xfc,0x7d,0xa7,0xfc,0x7f,0xa8,0xfb,0x80,0xa8,0xfb,0x82,0xa9,0xfb,0x83,0xaa,0xfb,0x85,0xab,0xfb,0x86,0xab,0xfb,0x88,0xac,0xfb,0x89,0xad,0xfb,0x8b,0xad,0xfb,0x8c,0xae,0xfb,0x8d,0xaf,0xfb,0x8f,0xb0,0xfa,0x90,0xb0,0xfa,0x92,0xb1,0xfa,0x93,0xb2,0xfa,0x94,0xb3,0xfa,0x96,0xb3,0xfa,0x97,0xb4,0xfa,0x98,0xb5,0xfa,0x9a,0xb6,0xfa,0x9b,0xb6,0xfa,0x9c,0xb7,0xfa,0x9e,0xb8,0xf9,0x9f,0xb9,0xf9,0xa0,0xb9,0xf9,0xa1,0xba,0xf9,0xa3,0xbb,0xf9,0xa4,0xbb,0xf9,0xa5,0xbc,0xf9,0xa6,0xbd,0xf9,0xa8,0xbe,0xf9,0xa9,0xbe,0xf9,0xaa,0xbf,0xf8,0xab,0xc0,0xf8,0xad,0xc1,0xf8,0xae,0xc2,0xf8,0xaf,0xc2,0xf8,0xb0,0xc3,0xf8,0xb1,0xc4,0xf8,0xb3,0xc5,0xf8,0xb4,0xc5,0xf8,0xb5,0xc6,0xf7,0xb6,0xc7,0xf7,0xb7,0xc8,0xf7,0xb9,0xc8,0xf7,0xba,0xc9,0xf7,0xbb,0xca,0xf7,0xbc,0xcb,0xf7,0xbd,0xcb,0xf7,0xbe,0xcc,0xf7,0xc0,0xcd,0xf6,0xc1,0xce,0xf6,0xc2,0xce,0xf6,0xc3,0xcf,0xf6,0xc4,0xd0,0xf6,0xc5,0xd1,0xf6,0xc6,0xd2,0xf6,0xc7,0xd2,0xf6,0xc9,0xd3,0xf6,0xca,0xd4,0xf5,0xcb,0xd5,0xf5,0xcc,0xd5,0xf5,0xcd,0xd6,0xf5,0xce,0xd7,0xf5,0xcf,0xd8,0xf5,0xd0,0xd9,0xf5,0xd1,0xd9,0xf5,0xd3,0xda,0xf4,0xd4,0xdb,0xf4,0xd5,0xdc,0xf4,0xd6,0xdc,0xf4,0xd7,0xdd,0xf4,0xd8,0xde,0xf4,0xd9,0xdf,0xf4,0xda,0xe0,0xf4,0xdb,0xe0,0xf3,0xdc,0xe1,0xf3,0xdd,0xe2,0xf3,0xde,0xe3,0xf3,0xdf,0xe4,0xf3,0xe0,0xe4,0xf3,0xe2,0xe5,0xf3,0xe3,0xe6,0xf2,0xe4,0xe7,0xf2,0xe5,0xe7,0xf2,0xe6,0xe8,0xf2,0xe7,0xe9,0xf2,0xe8,0xea,0xf1,0xe9,0xea,0xf1,0xea,0xeb,0xf1,0xea,0xec,0xf0,0xeb,0xec,0xf0,0xec,0xec,0xef,0xec,0xed,0xee,0xed,0xed,0xed,0xed,0xed,0xec,0xee,0xed,0xeb,0xee,0xec,0xea,0xee,0xec,0xe8,0xee,0xec,0xe7,0xee,0xeb,0xe5,0xed,0xea,0xe4,0xed,0xea,0xe2,0xed,0xe9,0xe0,0xec,0xe8,0xdf,0xec,0xe7,0xdd,0xec,0xe7,0xdb,0xeb,0xe6,0xda,0xeb,0xe5,0xd8,0xea,0xe4,0xd6,0xea,0xe4,0xd5,0xe9,0xe3,0xd3,0xe9,0xe2,0xd1,0xe9,0xe1,0xd0,0xe8,0xe0,0xce,0xe8,0xe0,0xcc,0xe7,0xdf,0xca,0xe7,0xde,0xc9,0xe6,0xdd,0xc7,0xe6,0xdc,0xc5,0xe5,0xdc,0xc4,0xe5,0xdb,0xc2,0xe4,0xda,0xc0,0xe4,0xd9,0xbf,0xe3,0xd8,0xbd,0xe3,0xd8,0xbb,0xe2,0xd7,0xba,0xe2,0xd6,0xb8,0xe2,0xd5,0xb6,0xe1,0xd5,0xb5,0xe1,0xd4,0xb3,0xe0,0xd3,0xb1,0xe0,0xd2,0xb0,0xdf,0xd1,0xae,0xdf,0xd1,0xac,0xde,0xd0,0xab,0xde,0xcf,0xa9,0xdd,0xce,0xa7,0xdc,0xce,0xa6,0xdc,0xcd,0xa4,0xdb,0xcc,0xa2,0xdb,0xcb,0xa1,0xda,0xcb,0x9f,0xda,0xca,0x9d,0xd9,0xc9,0x9c,0xd9,0xc8,0x9a,0xd8,0xc7,0x98,0xd8,0xc7,0x97,0xd7,0xc6,0x95,0xd7,0xc5,0x94,0xd6,0xc4,0x92,0xd6,0xc4,0x90,0xd5,0xc3,0x8f,0xd4,0xc2,0x8d,0xd4,0xc1,0x8b,0xd3,0xc1,0x8a,0xd3,0xc0,0x88,0xd2,0xbf,0x86,0xd2,0xbe,0x85,0xd1,0xbe,0x83,0xd0,0xbd,0x81,0xd0,0xbc,0x80,0xcf,0xbb,0x7e,0xcf,0xbb,0x7d,0xce,0xba,0x7b,0xce,0xb9,0x79,0xcd,0xb8,0x78,0xcc,0xb8,0x76,0xcc,0xb7,0x74,0xcb,0xb6,0x73,0xcb,0xb5,0x71,0xca,0xb5,0x6f,0xc9,0xb4,0x6e,0xc9,0xb3,0x6c,0xc8,0xb2,0x6a,0xc7,0xb2,0x69,0xc7,0xb1,0x67,0xc6,0xb0,0x66,0xc6,0xaf,0x64,0xc5,0xaf,0x62,0xc4,0xae,0x61,0xc4,0xad,0x5f,0xc3,0xac,0x5d,0xc2,0xac,0x5c,0xc2,0xab,0x5a,0xc1,0xaa,0x58,0xc1,0xa9,0x57,0xc0,0xa9,0x55,0xbf,0xa8,0x53,0xbf,0xa7,0x51,0xbe,0xa6,0x50,0xbd,0xa6,0x4e,0xbd,0xa5,0x4c,0xbc,0xa4,0x4b,0xbb,0xa4,0x49,0xbb,0xa3,0x47,0xba,0xa2,0x45,0xb9,0xa1,0x44,0xb9,0xa1,0x42,0xb8,0xa0,0x40,0xb7,0x9f,0x3e,0xb7,0x9f,0x3c,0xb6,0x9e,0x3b,0xb5,0x9d,0x39,0xb4,0x9c,0x37,0xb4,0x9c,0x35,0xb3,0x9b,0x33,0xb2,0x9a,0x31,0xb2,0x99,0x2f,0xb1,0x99,0x2d,0xb0,0x98,0x2b,0xb0,0x97,0x29,0xaf,0x97,0x27,0xae,0x96,0x24,0xad,0x95,0x22,0xad,0x95,0x20,0xac,0x94,0x1d,0xab,0x93,0x1a,0xab,0x92,0x17,0xaa,0x92,0x14,0xa9,0x91,0x11,0xa8,0x90,0x0d,0xa8,0x90,0x08}; -} +// maps for the color blind +static constexpr std::array CBL1 = { + 0x11, 0x11, 0x11, 0x11, 0x12, 0x13, 0x12, 0x13, 0x15, 0x12, 0x13, 0x17, 0x13, 0x14, 0x19, 0x13, + 0x15, 0x1b, 0x13, 0x16, 0x1d, 0x14, 0x16, 0x1f, 0x14, 0x17, 0x20, 0x14, 0x18, 0x22, 0x14, 0x18, + 0x24, 0x14, 0x19, 0x26, 0x14, 0x1a, 0x28, 0x14, 0x1a, 0x2a, 0x14, 0x1b, 0x2c, 0x14, 0x1c, 0x2e, + 0x14, 0x1d, 0x2f, 0x14, 0x1d, 0x31, 0x13, 0x1e, 0x33, 0x13, 0x1f, 0x35, 0x13, 0x1f, 0x37, 0x13, + 0x20, 0x39, 0x12, 0x21, 0x3a, 0x12, 0x22, 0x3c, 0x12, 0x22, 0x3e, 0x11, 0x23, 0x40, 0x11, 0x24, + 0x42, 0x11, 0x25, 0x44, 0x10, 0x25, 0x45, 0x10, 0x26, 0x47, 0x0f, 0x27, 0x49, 0x0e, 0x28, 0x4b, + 0x0e, 0x28, 0x4d, 0x0d, 0x29, 0x4e, 0x0c, 0x2a, 0x50, 0x0c, 0x2b, 0x52, 0x0b, 0x2b, 0x54, 0x0a, + 0x2c, 0x55, 0x09, 0x2d, 0x57, 0x08, 0x2e, 0x59, 0x07, 0x2e, 0x5a, 0x06, 0x2f, 0x5c, 0x06, 0x30, + 0x5e, 0x05, 0x31, 0x5f, 0x04, 0x31, 0x61, 0x03, 0x32, 0x63, 0x02, 0x33, 0x64, 0x02, 0x34, 0x66, + 0x01, 0x35, 0x67, 0x00, 0x35, 0x69, 0x00, 0x36, 0x6b, 0x00, 0x37, 0x6c, 0x00, 0x38, 0x6e, 0x00, + 0x38, 0x6f, 0x00, 0x39, 0x71, 0x00, 0x3a, 0x72, 0x00, 0x3b, 0x73, 0x00, 0x3c, 0x75, 0x00, 0x3c, + 0x76, 0x00, 0x3d, 0x77, 0x00, 0x3e, 0x79, 0x00, 0x3f, 0x7a, 0x00, 0x40, 0x7b, 0x00, 0x40, 0x7d, + 0x01, 0x41, 0x7e, 0x03, 0x42, 0x7f, 0x04, 0x43, 0x80, 0x05, 0x44, 0x81, 0x07, 0x44, 0x82, 0x09, + 0x45, 0x83, 0x0b, 0x46, 0x84, 0x0d, 0x47, 0x85, 0x0f, 0x48, 0x86, 0x11, 0x48, 0x87, 0x13, 0x49, + 0x88, 0x15, 0x4a, 0x89, 0x18, 0x4b, 0x8a, 0x1a, 0x4c, 0x8a, 0x1c, 0x4c, 0x8b, 0x1e, 0x4d, 0x8c, + 0x20, 0x4e, 0x8c, 0x22, 0x4f, 0x8d, 0x24, 0x50, 0x8d, 0x26, 0x50, 0x8e, 0x28, 0x51, 0x8e, 0x2a, + 0x52, 0x8e, 0x2d, 0x53, 0x8e, 0x2f, 0x54, 0x8f, 0x31, 0x54, 0x8f, 0x33, 0x55, 0x8f, 0x35, 0x56, + 0x8f, 0x37, 0x57, 0x8f, 0x3a, 0x58, 0x8e, 0x3c, 0x59, 0x8e, 0x3e, 0x59, 0x8e, 0x40, 0x5a, 0x8d, + 0x43, 0x5b, 0x8d, 0x45, 0x5c, 0x8c, 0x47, 0x5d, 0x8b, 0x49, 0x5e, 0x8b, 0x4b, 0x5e, 0x8a, 0x4d, + 0x5f, 0x89, 0x4f, 0x60, 0x89, 0x51, 0x61, 0x88, 0x53, 0x62, 0x87, 0x55, 0x63, 0x87, 0x57, 0x64, + 0x86, 0x59, 0x64, 0x85, 0x5a, 0x65, 0x85, 0x5c, 0x66, 0x84, 0x5e, 0x67, 0x83, 0x5f, 0x68, 0x83, + 0x61, 0x69, 0x82, 0x63, 0x6a, 0x81, 0x64, 0x6a, 0x80, 0x66, 0x6b, 0x80, 0x68, 0x6c, 0x7f, 0x69, + 0x6d, 0x7e, 0x6b, 0x6e, 0x7e, 0x6c, 0x6f, 0x7d, 0x6e, 0x70, 0x7c, 0x6f, 0x71, 0x7b, 0x71, 0x71, + 0x7b, 0x72, 0x72, 0x7a, 0x74, 0x73, 0x79, 0x75, 0x74, 0x79, 0x77, 0x75, 0x78, 0x78, 0x76, 0x77, + 0x7a, 0x77, 0x76, 0x7b, 0x78, 0x76, 0x7c, 0x79, 0x75, 0x7e, 0x79, 0x74, 0x7f, 0x7a, 0x73, 0x81, + 0x7b, 0x73, 0x82, 0x7c, 0x72, 0x83, 0x7d, 0x71, 0x85, 0x7e, 0x70, 0x86, 0x7f, 0x6f, 0x88, 0x80, + 0x6f, 0x89, 0x81, 0x6e, 0x8a, 0x81, 0x6d, 0x8c, 0x82, 0x6c, 0x8d, 0x83, 0x6b, 0x8e, 0x84, 0x6b, + 0x90, 0x85, 0x6a, 0x91, 0x86, 0x69, 0x92, 0x87, 0x68, 0x94, 0x88, 0x67, 0x95, 0x89, 0x67, 0x96, + 0x8a, 0x66, 0x98, 0x8a, 0x65, 0x99, 0x8b, 0x64, 0x9a, 0x8c, 0x63, 0x9c, 0x8d, 0x62, 0x9d, 0x8e, + 0x61, 0x9e, 0x8f, 0x60, 0xa0, 0x90, 0x60, 0xa1, 0x91, 0x5f, 0xa2, 0x92, 0x5e, 0xa4, 0x93, 0x5d, + 0xa5, 0x94, 0x5c, 0xa6, 0x94, 0x5b, 0xa7, 0x95, 0x5b, 0xa9, 0x96, 0x5a, 0xaa, 0x97, 0x5a, 0xab, + 0x98, 0x59, 0xac, 0x99, 0x59, 0xad, 0x9a, 0x59, 0xaf, 0x9b, 0x59, 0xb0, 0x9c, 0x59, 0xb1, 0x9d, + 0x59, 0xb2, 0x9e, 0x59, 0xb3, 0x9f, 0x59, 0xb4, 0x9f, 0x59, 0xb5, 0xa0, 0x5a, 0xb6, 0xa1, 0x5a, + 0xb7, 0xa2, 0x5a, 0xb8, 0xa3, 0x5b, 0xb9, 0xa4, 0x5b, 0xba, 0xa5, 0x5c, 0xbb, 0xa6, 0x5d, 0xbc, + 0xa7, 0x5e, 0xbd, 0xa8, 0x5e, 0xbf, 0xa9, 0x5f, 0xc0, 0xaa, 0x60, 0xc1, 0xab, 0x61, 0xc1, 0xac, + 0x62, 0xc2, 0xad, 0x63, 0xc3, 0xae, 0x64, 0xc4, 0xaf, 0x65, 0xc5, 0xb0, 0x67, 0xc6, 0xb0, 0x68, + 0xc7, 0xb1, 0x69, 0xc8, 0xb2, 0x6a, 0xc9, 0xb3, 0x6c, 0xca, 0xb4, 0x6d, 0xcb, 0xb5, 0x6e, 0xcc, + 0xb6, 0x70, 0xcd, 0xb7, 0x71, 0xce, 0xb8, 0x73, 0xcf, 0xb9, 0x75, 0xcf, 0xba, 0x76, 0xd0, 0xbb, + 0x78, 0xd1, 0xbc, 0x79, 0xd2, 0xbd, 0x7b, 0xd3, 0xbe, 0x7d, 0xd4, 0xbf, 0x7f, 0xd5, 0xc0, 0x80, + 0xd5, 0xc1, 0x82, 0xd6, 0xc2, 0x84, 0xd7, 0xc3, 0x86, 0xd8, 0xc4, 0x88, 0xd9, 0xc5, 0x8a, 0xd9, + 0xc6, 0x8c, 0xda, 0xc7, 0x8d, 0xdb, 0xc8, 0x8f, 0xdc, 0xc9, 0x91, 0xdd, 0xca, 0x94, 0xdd, 0xcb, + 0x96, 0xde, 0xcc, 0x98, 0xdf, 0xcd, 0x9a, 0xdf, 0xce, 0x9c, 0xe0, 0xcf, 0x9e, 0xe1, 0xd0, 0xa0, + 0xe2, 0xd1, 0xa2, 0xe2, 0xd2, 0xa5, 0xe3, 0xd3, 0xa7, 0xe4, 0xd4, 0xa9, 0xe4, 0xd5, 0xab, 0xe5, + 0xd6, 0xae, 0xe5, 0xd7, 0xb0, 0xe6, 0xd8, 0xb2, 0xe7, 0xd9, 0xb5, 0xe7, 0xda, 0xb7, 0xe8, 0xdb, + 0xba, 0xe8, 0xdc, 0xbc, 0xe9, 0xdd, 0xbf, 0xe9, 0xde, 0xc1, 0xea, 0xdf, 0xc3, 0xea, 0xe0, 0xc6, + 0xeb, 0xe1, 0xc9, 0xeb, 0xe2, 0xcb, 0xec, 0xe3, 0xce, 0xec, 0xe4, 0xd0, 0xed, 0xe5, 0xd3, 0xed, + 0xe6, 0xd5, 0xee, 0xe7, 0xd8, 0xee, 0xe8, 0xdb, 0xee, 0xe9, 0xdd, 0xef, 0xea, 0xe0, 0xef, 0xeb, + 0xe3, 0xef, 0xec, 0xe6, 0xf0, 0xed, 0xe8, 0xf0, 0xee, 0xeb, 0xf0, 0xf0, 0xee, 0xf1, 0xf1, 0xf1 +}; +static constexpr std::array CBL2 = { + 0x11, 0x11, 0x11, 0x11, 0x12, 0x13, 0x12, 0x13, 0x15, 0x13, 0x13, 0x17, 0x13, 0x14, 0x18, 0x14, + 0x15, 0x1a, 0x14, 0x16, 0x1c, 0x14, 0x17, 0x1d, 0x15, 0x17, 0x1f, 0x15, 0x18, 0x21, 0x15, 0x19, + 0x22, 0x16, 0x19, 0x24, 0x16, 0x1a, 0x26, 0x16, 0x1b, 0x27, 0x16, 0x1b, 0x29, 0x16, 0x1c, 0x2b, + 0x16, 0x1d, 0x2d, 0x16, 0x1e, 0x2e, 0x17, 0x1e, 0x30, 0x17, 0x1f, 0x32, 0x17, 0x20, 0x34, 0x17, + 0x21, 0x36, 0x17, 0x21, 0x37, 0x17, 0x22, 0x39, 0x17, 0x23, 0x3b, 0x16, 0x24, 0x3d, 0x16, 0x24, + 0x3f, 0x16, 0x25, 0x40, 0x16, 0x26, 0x42, 0x16, 0x27, 0x44, 0x16, 0x27, 0x46, 0x15, 0x28, 0x48, + 0x15, 0x29, 0x4a, 0x15, 0x2a, 0x4b, 0x14, 0x2b, 0x4d, 0x14, 0x2b, 0x4f, 0x14, 0x2c, 0x51, 0x13, + 0x2d, 0x53, 0x13, 0x2e, 0x54, 0x13, 0x2e, 0x56, 0x12, 0x2f, 0x58, 0x12, 0x30, 0x5a, 0x12, 0x31, + 0x5b, 0x11, 0x32, 0x5d, 0x11, 0x32, 0x5f, 0x11, 0x33, 0x60, 0x10, 0x34, 0x62, 0x10, 0x35, 0x63, + 0x10, 0x36, 0x65, 0x10, 0x36, 0x67, 0x10, 0x37, 0x68, 0x10, 0x38, 0x6a, 0x10, 0x39, 0x6b, 0x0f, + 0x3a, 0x6d, 0x0f, 0x3b, 0x6e, 0x0f, 0x3b, 0x70, 0x0f, 0x3c, 0x71, 0x0f, 0x3d, 0x73, 0x0f, 0x3e, + 0x74, 0x0f, 0x3f, 0x76, 0x0f, 0x3f, 0x77, 0x0f, 0x40, 0x79, 0x0f, 0x41, 0x7a, 0x0f, 0x42, 0x7c, + 0x0f, 0x43, 0x7e, 0x0f, 0x44, 0x7f, 0x0f, 0x44, 0x81, 0x0f, 0x45, 0x82, 0x0f, 0x46, 0x84, 0x0f, + 0x47, 0x85, 0x0f, 0x48, 0x87, 0x0f, 0x49, 0x88, 0x0f, 0x49, 0x8a, 0x0f, 0x4a, 0x8b, 0x0f, 0x4b, + 0x8d, 0x0f, 0x4c, 0x8e, 0x0f, 0x4d, 0x90, 0x0f, 0x4e, 0x92, 0x0f, 0x4f, 0x93, 0x0f, 0x4f, 0x95, + 0x0e, 0x50, 0x96, 0x0e, 0x51, 0x98, 0x0e, 0x52, 0x99, 0x0e, 0x53, 0x9b, 0x0e, 0x54, 0x9d, 0x0e, + 0x55, 0x9e, 0x0e, 0x56, 0xa0, 0x0e, 0x56, 0xa1, 0x0d, 0x57, 0xa3, 0x0d, 0x58, 0xa5, 0x0d, 0x59, + 0xa6, 0x0d, 0x5a, 0xa8, 0x0d, 0x5b, 0xa9, 0x0d, 0x5c, 0xab, 0x0c, 0x5c, 0xad, 0x0c, 0x5d, 0xae, + 0x0c, 0x5e, 0xb0, 0x0c, 0x5f, 0xb2, 0x0b, 0x60, 0xb3, 0x0b, 0x61, 0xb5, 0x0b, 0x62, 0xb6, 0x0a, + 0x63, 0xb8, 0x0a, 0x64, 0xba, 0x0a, 0x64, 0xbb, 0x09, 0x65, 0xbd, 0x09, 0x66, 0xbf, 0x09, 0x67, + 0xc0, 0x08, 0x68, 0xc2, 0x08, 0x69, 0xc4, 0x07, 0x6a, 0xc5, 0x07, 0x6b, 0xc7, 0x07, 0x6c, 0xc9, + 0x06, 0x6d, 0xca, 0x06, 0x6d, 0xcc, 0x05, 0x6e, 0xce, 0x05, 0x6f, 0xcf, 0x04, 0x70, 0xd1, 0x04, + 0x71, 0xd3, 0x03, 0x72, 0xd4, 0x03, 0x73, 0xd6, 0x02, 0x74, 0xd8, 0x02, 0x75, 0xd9, 0x01, 0x76, + 0xdb, 0x01, 0x77, 0xdd, 0x00, 0x78, 0xde, 0x00, 0x78, 0xe0, 0x00, 0x79, 0xe2, 0x01, 0x7a, 0xe3, + 0x01, 0x7b, 0xe5, 0x02, 0x7c, 0xe6, 0x03, 0x7d, 0xe8, 0x05, 0x7e, 0xe9, 0x07, 0x7f, 0xeb, 0x0b, + 0x80, 0xec, 0x0e, 0x81, 0xed, 0x12, 0x82, 0xee, 0x16, 0x83, 0xef, 0x1a, 0x84, 0xf0, 0x1f, 0x84, + 0xf1, 0x23, 0x85, 0xf2, 0x28, 0x86, 0xf2, 0x2d, 0x87, 0xf2, 0x31, 0x88, 0xf2, 0x36, 0x89, 0xf2, + 0x3b, 0x8a, 0xf2, 0x40, 0x8b, 0xf1, 0x45, 0x8c, 0xf0, 0x4a, 0x8d, 0xef, 0x4f, 0x8d, 0xee, 0x54, + 0x8e, 0xec, 0x59, 0x8f, 0xea, 0x5d, 0x90, 0xe8, 0x62, 0x91, 0xe6, 0x67, 0x92, 0xe4, 0x6b, 0x93, + 0xe2, 0x6f, 0x94, 0xdf, 0x73, 0x95, 0xdc, 0x77, 0x96, 0xd9, 0x7b, 0x97, 0xd6, 0x7f, 0x98, 0xd4, + 0x83, 0x99, 0xd0, 0x86, 0x9a, 0xcd, 0x89, 0x9b, 0xca, 0x8d, 0x9b, 0xc7, 0x90, 0x9c, 0xc4, 0x93, + 0x9d, 0xc1, 0x96, 0x9e, 0xbd, 0x98, 0x9f, 0xba, 0x9b, 0xa0, 0xb7, 0x9e, 0xa1, 0xb4, 0xa0, 0xa2, + 0xb1, 0xa3, 0xa3, 0xae, 0xa5, 0xa4, 0xaa, 0xa8, 0xa5, 0xa7, 0xaa, 0xa6, 0xa4, 0xac, 0xa7, 0xa1, + 0xaf, 0xa8, 0x9e, 0xb1, 0xa9, 0x9b, 0xb3, 0xaa, 0x98, 0xb5, 0xab, 0x95, 0xb7, 0xac, 0x92, 0xb9, + 0xad, 0x8f, 0xbb, 0xae, 0x8c, 0xbd, 0xaf, 0x89, 0xbf, 0xb0, 0x86, 0xc1, 0xb1, 0x83, 0xc3, 0xb2, + 0x80, 0xc5, 0xb3, 0x7d, 0xc7, 0xb4, 0x7a, 0xc9, 0xb5, 0x77, 0xca, 0xb6, 0x74, 0xcc, 0xb7, 0x71, + 0xce, 0xb8, 0x6d, 0xd0, 0xb8, 0x6a, 0xd1, 0xb9, 0x67, 0xd3, 0xba, 0x64, 0xd5, 0xbb, 0x60, 0xd6, + 0xbc, 0x5d, 0xd8, 0xbd, 0x5a, 0xda, 0xbe, 0x56, 0xdb, 0xbf, 0x52, 0xdd, 0xc0, 0x4f, 0xde, 0xc1, + 0x4b, 0xe0, 0xc2, 0x48, 0xe1, 0xc3, 0x44, 0xe3, 0xc4, 0x40, 0xe4, 0xc5, 0x3c, 0xe5, 0xc6, 0x39, + 0xe7, 0xc7, 0x35, 0xe8, 0xc8, 0x31, 0xe9, 0xc9, 0x2e, 0xeb, 0xca, 0x2a, 0xec, 0xcb, 0x27, 0xed, + 0xcc, 0x25, 0xef, 0xcd, 0x23, 0xf0, 0xce, 0x22, 0xf1, 0xcf, 0x22, 0xf2, 0xd0, 0x23, 0xf3, 0xd1, + 0x25, 0xf4, 0xd2, 0x27, 0xf5, 0xd3, 0x2b, 0xf6, 0xd4, 0x2f, 0xf7, 0xd6, 0x34, 0xf8, 0xd7, 0x39, + 0xf9, 0xd8, 0x3e, 0xfa, 0xd9, 0x44, 0xfb, 0xda, 0x4a, 0xfb, 0xdb, 0x50, 0xfc, 0xdc, 0x56, 0xfd, + 0xdd, 0x5d, 0xfd, 0xde, 0x63, 0xfe, 0xdf, 0x6a, 0xfe, 0xe0, 0x70, 0xff, 0xe1, 0x77, 0xff, 0xe2, + 0x7e, 0xff, 0xe3, 0x84, 0xff, 0xe4, 0x8b, 0xff, 0xe5, 0x92, 0xff, 0xe6, 0x98, 0xff, 0xe7, 0x9f, + 0xff, 0xe8, 0xa5, 0xff, 0xe9, 0xab, 0xff, 0xeb, 0xb1, 0xff, 0xec, 0xb7, 0xfe, 0xed, 0xbd, 0xfe, + 0xee, 0xc3, 0xfe, 0xef, 0xc9, 0xfd, 0xf0, 0xce, 0xfd, 0xf1, 0xd3, 0xfd, 0xf2, 0xd8, 0xfd, 0xf3, + 0xdd, 0xfc, 0xf5, 0xe2, 0xfc, 0xf6, 0xe7, 0xfc, 0xf7, 0xeb, 0xfc, 0xf8, 0xef, 0xfc, 0xf9, 0xf3 +}; +static constexpr std::array CBC1 = { + 0x3e, 0x87, 0xea, 0x41, 0x88, 0xeb, 0x44, 0x8a, 0xed, 0x47, 0x8b, 0xed, 0x4b, 0x8c, 0xee, 0x4f, + 0x8e, 0xef, 0x53, 0x8f, 0xef, 0x57, 0x91, 0xf0, 0x5a, 0x93, 0xf0, 0x5e, 0x94, 0xf0, 0x62, 0x96, + 0xf0, 0x66, 0x97, 0xf0, 0x69, 0x99, 0xf0, 0x6d, 0x9a, 0xf1, 0x70, 0x9c, 0xf1, 0x74, 0x9e, 0xf1, + 0x77, 0x9f, 0xf1, 0x7a, 0xa1, 0xf1, 0x7d, 0xa2, 0xf1, 0x80, 0xa4, 0xf1, 0x83, 0xa6, 0xf1, 0x86, + 0xa7, 0xf1, 0x89, 0xa9, 0xf1, 0x8c, 0xab, 0xf2, 0x8f, 0xac, 0xf2, 0x92, 0xae, 0xf2, 0x95, 0xb0, + 0xf2, 0x97, 0xb1, 0xf2, 0x9a, 0xb3, 0xf2, 0x9d, 0xb5, 0xf2, 0x9f, 0xb6, 0xf2, 0xa2, 0xb8, 0xf2, + 0xa5, 0xba, 0xf2, 0xa7, 0xbb, 0xf2, 0xaa, 0xbd, 0xf2, 0xac, 0xbf, 0xf3, 0xaf, 0xc1, 0xf3, 0xb2, + 0xc2, 0xf3, 0xb4, 0xc4, 0xf3, 0xb7, 0xc6, 0xf3, 0xb9, 0xc7, 0xf3, 0xbb, 0xc9, 0xf3, 0xbe, 0xcb, + 0xf3, 0xc0, 0xcd, 0xf3, 0xc3, 0xce, 0xf3, 0xc5, 0xd0, 0xf3, 0xc8, 0xd2, 0xf3, 0xca, 0xd3, 0xf3, + 0xcc, 0xd5, 0xf3, 0xcf, 0xd7, 0xf3, 0xd1, 0xd9, 0xf3, 0xd3, 0xda, 0xf3, 0xd6, 0xdc, 0xf3, 0xd8, + 0xde, 0xf3, 0xda, 0xe0, 0xf3, 0xdd, 0xe1, 0xf3, 0xdf, 0xe3, 0xf3, 0xe1, 0xe4, 0xf2, 0xe3, 0xe6, + 0xf2, 0xe5, 0xe7, 0xf1, 0xe6, 0xe8, 0xf0, 0xe8, 0xe9, 0xef, 0xe9, 0xea, 0xed, 0xea, 0xea, 0xeb, + 0xeb, 0xea, 0xe9, 0xec, 0xea, 0xe7, 0xec, 0xe9, 0xe4, 0xec, 0xe8, 0xe1, 0xec, 0xe7, 0xde, 0xeb, + 0xe6, 0xdb, 0xeb, 0xe5, 0xd8, 0xea, 0xe3, 0xd5, 0xe9, 0xe2, 0xd1, 0xe8, 0xe0, 0xce, 0xe7, 0xde, + 0xca, 0xe6, 0xdd, 0xc7, 0xe5, 0xdb, 0xc3, 0xe3, 0xd9, 0xc0, 0xe2, 0xd8, 0xbc, 0xe1, 0xd6, 0xb9, + 0xe0, 0xd4, 0xb6, 0xdf, 0xd2, 0xb2, 0xde, 0xd0, 0xaf, 0xdc, 0xcf, 0xab, 0xdb, 0xcd, 0xa8, 0xda, + 0xcb, 0xa4, 0xd9, 0xca, 0xa1, 0xd7, 0xc8, 0x9e, 0xd6, 0xc6, 0x9a, 0xd5, 0xc4, 0x97, 0xd3, 0xc3, + 0x93, 0xd2, 0xc1, 0x90, 0xd1, 0xbf, 0x8d, 0xcf, 0xbe, 0x89, 0xce, 0xbc, 0x86, 0xcd, 0xba, 0x83, + 0xcb, 0xb8, 0x7f, 0xca, 0xb7, 0x7c, 0xc9, 0xb5, 0x78, 0xc7, 0xb3, 0x75, 0xc6, 0xb2, 0x72, 0xc5, + 0xb0, 0x6e, 0xc3, 0xae, 0x6b, 0xc2, 0xad, 0x68, 0xc0, 0xab, 0x64, 0xbf, 0xa9, 0x61, 0xbd, 0xa8, + 0x5d, 0xbc, 0xa6, 0x5a, 0xba, 0xa4, 0x57, 0xb9, 0xa3, 0x53, 0xb7, 0xa1, 0x50, 0xb6, 0x9f, 0x4c, + 0xb4, 0x9e, 0x49, 0xb3, 0x9c, 0x45, 0xb1, 0x9b, 0x42, 0xb0, 0x99, 0x3e, 0xae, 0x97, 0x3b, 0xad, + 0x96, 0x37, 0xab, 0x94, 0x33, 0xa9, 0x92, 0x30, 0xa8, 0x91, 0x2c, 0xa6, 0x8f, 0x28, 0xa5, 0x8e, + 0x24, 0xa3, 0x8c, 0x21, 0xa1, 0x8b, 0x1d, 0xa0, 0x89, 0x1a, 0x9e, 0x87, 0x17, 0x9c, 0x86, 0x14, + 0x9a, 0x84, 0x12, 0x99, 0x83, 0x10, 0x97, 0x81, 0x0f, 0x95, 0x80, 0x0f, 0x93, 0x7e, 0x0f, 0x91, + 0x7c, 0x0f, 0x90, 0x7b, 0x10, 0x8e, 0x79, 0x10, 0x8c, 0x78, 0x11, 0x8a, 0x76, 0x13, 0x88, 0x75, + 0x14, 0x86, 0x73, 0x15, 0x85, 0x72, 0x16, 0x83, 0x70, 0x17, 0x81, 0x6f, 0x18, 0x7f, 0x6d, 0x18, + 0x7d, 0x6c, 0x19, 0x7c, 0x6a, 0x1a, 0x7a, 0x69, 0x1b, 0x78, 0x67, 0x1c, 0x76, 0x65, 0x1c, 0x74, + 0x64, 0x1d, 0x73, 0x63, 0x1d, 0x71, 0x61, 0x1e, 0x6f, 0x60, 0x1f, 0x6d, 0x5e, 0x1f, 0x6b, 0x5d, + 0x20, 0x6a, 0x5b, 0x20, 0x68, 0x5a, 0x21, 0x66, 0x58, 0x21, 0x64, 0x57, 0x21, 0x63, 0x55, 0x22, + 0x61, 0x54, 0x22, 0x5f, 0x52, 0x23, 0x5d, 0x51, 0x23, 0x5c, 0x4f, 0x23, 0x5a, 0x4e, 0x24, 0x58, + 0x4d, 0x24, 0x56, 0x4b, 0x24, 0x54, 0x4a, 0x24, 0x53, 0x48, 0x25, 0x51, 0x47, 0x25, 0x4f, 0x46, + 0x25, 0x4e, 0x44, 0x25, 0x4c, 0x43, 0x26, 0x4a, 0x41, 0x26, 0x48, 0x40, 0x26, 0x47, 0x3f, 0x26, + 0x45, 0x3d, 0x26, 0x43, 0x3c, 0x27, 0x41, 0x3b, 0x27, 0x40, 0x39, 0x27, 0x3e, 0x38, 0x27, 0x3c, + 0x37, 0x27, 0x3a, 0x35, 0x27, 0x39, 0x34, 0x28, 0x37, 0x33, 0x28, 0x36, 0x32, 0x28, 0x34, 0x31, + 0x29, 0x33, 0x30, 0x2a, 0x32, 0x2f, 0x2b, 0x31, 0x2f, 0x2c, 0x30, 0x2e, 0x2d, 0x2f, 0x2e, 0x2e, + 0x2f, 0x2e, 0x30, 0x2e, 0x2f, 0x32, 0x2e, 0x2f, 0x34, 0x2e, 0x30, 0x36, 0x2e, 0x31, 0x38, 0x2f, + 0x32, 0x3b, 0x2f, 0x33, 0x3d, 0x30, 0x34, 0x40, 0x30, 0x35, 0x43, 0x31, 0x36, 0x45, 0x32, 0x37, + 0x48, 0x32, 0x39, 0x4b, 0x33, 0x3a, 0x4e, 0x34, 0x3c, 0x51, 0x34, 0x3d, 0x53, 0x35, 0x3e, 0x56, + 0x35, 0x40, 0x59, 0x36, 0x41, 0x5c, 0x37, 0x42, 0x5f, 0x37, 0x44, 0x62, 0x38, 0x45, 0x65, 0x38, + 0x47, 0x68, 0x39, 0x48, 0x6b, 0x39, 0x49, 0x6e, 0x39, 0x4b, 0x71, 0x3a, 0x4c, 0x74, 0x3a, 0x4e, + 0x77, 0x3a, 0x4f, 0x7a, 0x3b, 0x51, 0x7d, 0x3b, 0x52, 0x80, 0x3b, 0x54, 0x83, 0x3c, 0x55, 0x86, + 0x3c, 0x56, 0x89, 0x3c, 0x58, 0x8c, 0x3c, 0x59, 0x8f, 0x3c, 0x5b, 0x93, 0x3c, 0x5c, 0x96, 0x3c, + 0x5e, 0x99, 0x3c, 0x5f, 0x9c, 0x3c, 0x61, 0x9f, 0x3c, 0x62, 0xa3, 0x3c, 0x64, 0xa6, 0x3c, 0x65, + 0xa9, 0x3c, 0x67, 0xac, 0x3c, 0x68, 0xaf, 0x3c, 0x6a, 0xb3, 0x3c, 0x6b, 0xb6, 0x3b, 0x6d, 0xb9, + 0x3b, 0x6f, 0xbc, 0x3b, 0x70, 0xc0, 0x3a, 0x72, 0xc3, 0x3a, 0x73, 0xc6, 0x39, 0x75, 0xca, 0x39, + 0x76, 0xcd, 0x38, 0x78, 0xd0, 0x38, 0x79, 0xd3, 0x38, 0x7b, 0xd7, 0x37, 0x7c, 0xda, 0x37, 0x7e, + 0xdd, 0x37, 0x7f, 0xdf, 0x38, 0x81, 0xe2, 0x39, 0x82, 0xe4, 0x3a, 0x84, 0xe6, 0x3c, 0x85, 0xe8 +}; +static constexpr std::array CBC2 = { + 0xee, 0xed, 0xec, 0xee, 0xed, 0xea, 0xee, 0xec, 0xe8, 0xee, 0xeb, 0xe5, 0xee, 0xea, 0xe2, 0xed, + 0xe9, 0xdf, 0xed, 0xe8, 0xdc, 0xec, 0xe6, 0xd9, 0xeb, 0xe5, 0xd5, 0xea, 0xe3, 0xd2, 0xe9, 0xe1, + 0xce, 0xe8, 0xdf, 0xca, 0xe7, 0xde, 0xc7, 0xe6, 0xdc, 0xc3, 0xe5, 0xda, 0xbf, 0xe4, 0xd8, 0xbc, + 0xe2, 0xd6, 0xb8, 0xe1, 0xd5, 0xb4, 0xe0, 0xd3, 0xb1, 0xdf, 0xd1, 0xad, 0xde, 0xcf, 0xa9, 0xdc, + 0xce, 0xa6, 0xdb, 0xcc, 0xa2, 0xda, 0xca, 0x9e, 0xd9, 0xc8, 0x9b, 0xd7, 0xc7, 0x97, 0xd6, 0xc5, + 0x94, 0xd5, 0xc3, 0x90, 0xd4, 0xc1, 0x8c, 0xd2, 0xc0, 0x89, 0xd1, 0xbe, 0x85, 0xd0, 0xbc, 0x82, + 0xce, 0xba, 0x7e, 0xcd, 0xb9, 0x7b, 0xcb, 0xb7, 0x77, 0xca, 0xb5, 0x73, 0xc9, 0xb4, 0x70, 0xc7, + 0xb2, 0x6c, 0xc6, 0xb0, 0x69, 0xc4, 0xae, 0x65, 0xc3, 0xad, 0x61, 0xc1, 0xab, 0x5e, 0xc0, 0xa9, + 0x5a, 0xbe, 0xa8, 0x56, 0xbd, 0xa6, 0x53, 0xbb, 0xa4, 0x4f, 0xba, 0xa3, 0x4b, 0xb8, 0xa1, 0x48, + 0xb7, 0x9f, 0x44, 0xb5, 0x9e, 0x40, 0xb4, 0x9c, 0x3c, 0xb2, 0x9a, 0x38, 0xb0, 0x99, 0x34, 0xaf, + 0x97, 0x30, 0xad, 0x96, 0x2c, 0xac, 0x94, 0x27, 0xaa, 0x93, 0x23, 0xa9, 0x91, 0x1e, 0xa7, 0x90, + 0x19, 0xa6, 0x8e, 0x14, 0xa5, 0x8d, 0x0f, 0xa4, 0x8d, 0x0a, 0xa3, 0x8c, 0x06, 0xa3, 0x8b, 0x03, + 0xa3, 0x8b, 0x02, 0xa3, 0x8b, 0x02, 0xa3, 0x8b, 0x04, 0xa4, 0x8c, 0x07, 0xa4, 0x8d, 0x0c, 0xa5, + 0x8e, 0x11, 0xa6, 0x8f, 0x16, 0xa8, 0x90, 0x1b, 0xa9, 0x91, 0x1f, 0xab, 0x93, 0x24, 0xac, 0x94, + 0x28, 0xae, 0x96, 0x2d, 0xaf, 0x98, 0x31, 0xb1, 0x99, 0x35, 0xb2, 0x9b, 0x39, 0xb4, 0x9c, 0x3d, + 0xb6, 0x9e, 0x41, 0xb7, 0xa0, 0x45, 0xb9, 0xa1, 0x49, 0xba, 0xa3, 0x4c, 0xbc, 0xa5, 0x50, 0xbd, + 0xa6, 0x54, 0xbf, 0xa8, 0x57, 0xc0, 0xaa, 0x5b, 0xc2, 0xab, 0x5f, 0xc3, 0xad, 0x62, 0xc5, 0xaf, + 0x66, 0xc6, 0xb1, 0x6a, 0xc8, 0xb2, 0x6d, 0xc9, 0xb4, 0x71, 0xca, 0xb6, 0x74, 0xcc, 0xb7, 0x78, + 0xcd, 0xb9, 0x7c, 0xcf, 0xbb, 0x7f, 0xd0, 0xbd, 0x83, 0xd1, 0xbe, 0x86, 0xd3, 0xc0, 0x8a, 0xd4, + 0xc2, 0x8d, 0xd5, 0xc3, 0x91, 0xd6, 0xc5, 0x95, 0xd8, 0xc7, 0x98, 0xd9, 0xc9, 0x9c, 0xda, 0xcb, + 0x9f, 0xdc, 0xcc, 0xa3, 0xdd, 0xce, 0xa7, 0xde, 0xd0, 0xaa, 0xdf, 0xd2, 0xae, 0xe0, 0xd3, 0xb2, + 0xe2, 0xd5, 0xb5, 0xe3, 0xd7, 0xb9, 0xe4, 0xd9, 0xbd, 0xe5, 0xda, 0xc0, 0xe6, 0xdc, 0xc4, 0xe7, + 0xde, 0xc8, 0xe8, 0xe0, 0xcb, 0xe9, 0xe1, 0xcf, 0xea, 0xe3, 0xd3, 0xeb, 0xe5, 0xd6, 0xec, 0xe6, + 0xda, 0xec, 0xe7, 0xdd, 0xec, 0xe8, 0xe0, 0xec, 0xe9, 0xe3, 0xec, 0xea, 0xe6, 0xec, 0xea, 0xe9, + 0xeb, 0xea, 0xeb, 0xea, 0xea, 0xed, 0xe9, 0xea, 0xef, 0xe7, 0xe9, 0xf0, 0xe6, 0xe8, 0xf2, 0xe4, + 0xe7, 0xf3, 0xe2, 0xe5, 0xf3, 0xe0, 0xe4, 0xf4, 0xdd, 0xe2, 0xf4, 0xdb, 0xe1, 0xf5, 0xd9, 0xdf, + 0xf5, 0xd6, 0xdd, 0xf5, 0xd4, 0xdb, 0xf5, 0xd2, 0xda, 0xf5, 0xcf, 0xd8, 0xf6, 0xcd, 0xd6, 0xf6, + 0xca, 0xd4, 0xf6, 0xc8, 0xd3, 0xf6, 0xc5, 0xd1, 0xf6, 0xc3, 0xcf, 0xf6, 0xc0, 0xcd, 0xf6, 0xbe, + 0xcc, 0xf6, 0xbb, 0xca, 0xf6, 0xb8, 0xc8, 0xf7, 0xb6, 0xc6, 0xf7, 0xb3, 0xc5, 0xf7, 0xb1, 0xc3, + 0xf7, 0xae, 0xc1, 0xf7, 0xab, 0xbf, 0xf7, 0xa8, 0xbe, 0xf7, 0xa6, 0xbc, 0xf7, 0xa3, 0xba, 0xf7, + 0xa0, 0xb9, 0xf7, 0x9d, 0xb7, 0xf7, 0x9a, 0xb5, 0xf7, 0x97, 0xb3, 0xf7, 0x94, 0xb2, 0xf8, 0x91, + 0xb0, 0xf8, 0x8e, 0xae, 0xf8, 0x8b, 0xad, 0xf8, 0x88, 0xab, 0xf8, 0x85, 0xa9, 0xf8, 0x82, 0xa8, + 0xf8, 0x7e, 0xa6, 0xf8, 0x7b, 0xa4, 0xf8, 0x78, 0xa3, 0xf8, 0x74, 0xa1, 0xf8, 0x70, 0x9f, 0xf8, + 0x6d, 0x9e, 0xf8, 0x69, 0x9c, 0xf8, 0x65, 0x9b, 0xf8, 0x61, 0x99, 0xf8, 0x5d, 0x97, 0xf8, 0x58, + 0x96, 0xf8, 0x54, 0x94, 0xf8, 0x4f, 0x93, 0xf8, 0x4b, 0x92, 0xf8, 0x46, 0x90, 0xf8, 0x42, 0x8f, + 0xf8, 0x3e, 0x8e, 0xf8, 0x3b, 0x8d, 0xf8, 0x38, 0x8d, 0xf8, 0x37, 0x8c, 0xf8, 0x36, 0x8c, 0xf8, + 0x37, 0x8c, 0xf8, 0x39, 0x8d, 0xf8, 0x3b, 0x8d, 0xf8, 0x3f, 0x8e, 0xf8, 0x43, 0x8f, 0xf8, 0x47, + 0x91, 0xf8, 0x4c, 0x92, 0xf8, 0x50, 0x93, 0xf8, 0x55, 0x95, 0xf8, 0x59, 0x96, 0xf8, 0x5e, 0x98, + 0xf8, 0x62, 0x99, 0xf8, 0x66, 0x9b, 0xf8, 0x6a, 0x9d, 0xf8, 0x6e, 0x9e, 0xf8, 0x71, 0xa0, 0xf8, + 0x75, 0xa1, 0xf8, 0x78, 0xa3, 0xf8, 0x7c, 0xa5, 0xf8, 0x7f, 0xa6, 0xf8, 0x82, 0xa8, 0xf8, 0x86, + 0xaa, 0xf8, 0x89, 0xab, 0xf8, 0x8c, 0xad, 0xf8, 0x8f, 0xaf, 0xf8, 0x92, 0xb0, 0xf8, 0x95, 0xb2, + 0xf8, 0x98, 0xb4, 0xf7, 0x9b, 0xb5, 0xf7, 0x9e, 0xb7, 0xf7, 0xa1, 0xb9, 0xf7, 0xa3, 0xbb, 0xf7, + 0xa6, 0xbc, 0xf7, 0xa9, 0xbe, 0xf7, 0xac, 0xc0, 0xf7, 0xae, 0xc1, 0xf7, 0xb1, 0xc3, 0xf7, 0xb4, + 0xc5, 0xf7, 0xb6, 0xc7, 0xf7, 0xb9, 0xc8, 0xf7, 0xbc, 0xca, 0xf6, 0xbe, 0xcc, 0xf6, 0xc1, 0xce, + 0xf6, 0xc3, 0xcf, 0xf6, 0xc6, 0xd1, 0xf6, 0xc8, 0xd3, 0xf6, 0xcb, 0xd5, 0xf6, 0xcd, 0xd7, 0xf6, + 0xd0, 0xd8, 0xf6, 0xd2, 0xda, 0xf5, 0xd5, 0xdc, 0xf5, 0xd7, 0xde, 0xf5, 0xd9, 0xdf, 0xf5, 0xdc, + 0xe1, 0xf5, 0xde, 0xe3, 0xf5, 0xe0, 0xe5, 0xf4, 0xe3, 0xe6, 0xf4, 0xe5, 0xe8, 0xf4, 0xe7, 0xe9, + 0xf3, 0xe8, 0xea, 0xf3, 0xea, 0xeb, 0xf2, 0xeb, 0xec, 0xf1, 0xed, 0xed, 0xf0, 0xed, 0xed, 0xee +}; +static constexpr std::array CBD1 = { + 0x3a, 0x90, 0xfe, 0x3e, 0x91, 0xfe, 0x41, 0x92, 0xfe, 0x44, 0x92, 0xfe, 0x46, 0x93, 0xfe, 0x49, + 0x94, 0xfe, 0x4c, 0x94, 0xfe, 0x4e, 0x95, 0xfe, 0x50, 0x96, 0xfe, 0x53, 0x97, 0xfd, 0x55, 0x97, + 0xfd, 0x57, 0x98, 0xfd, 0x59, 0x99, 0xfd, 0x5b, 0x99, 0xfd, 0x5e, 0x9a, 0xfd, 0x60, 0x9b, 0xfd, + 0x61, 0x9b, 0xfd, 0x63, 0x9c, 0xfd, 0x65, 0x9d, 0xfd, 0x67, 0x9e, 0xfd, 0x69, 0x9e, 0xfd, 0x6b, + 0x9f, 0xfd, 0x6d, 0xa0, 0xfc, 0x6e, 0xa0, 0xfc, 0x70, 0xa1, 0xfc, 0x72, 0xa2, 0xfc, 0x73, 0xa3, + 0xfc, 0x75, 0xa3, 0xfc, 0x77, 0xa4, 0xfc, 0x78, 0xa5, 0xfc, 0x7a, 0xa5, 0xfc, 0x7c, 0xa6, 0xfc, + 0x7d, 0xa7, 0xfc, 0x7f, 0xa8, 0xfb, 0x80, 0xa8, 0xfb, 0x82, 0xa9, 0xfb, 0x83, 0xaa, 0xfb, 0x85, + 0xab, 0xfb, 0x86, 0xab, 0xfb, 0x88, 0xac, 0xfb, 0x89, 0xad, 0xfb, 0x8b, 0xad, 0xfb, 0x8c, 0xae, + 0xfb, 0x8d, 0xaf, 0xfb, 0x8f, 0xb0, 0xfa, 0x90, 0xb0, 0xfa, 0x92, 0xb1, 0xfa, 0x93, 0xb2, 0xfa, + 0x94, 0xb3, 0xfa, 0x96, 0xb3, 0xfa, 0x97, 0xb4, 0xfa, 0x98, 0xb5, 0xfa, 0x9a, 0xb6, 0xfa, 0x9b, + 0xb6, 0xfa, 0x9c, 0xb7, 0xfa, 0x9e, 0xb8, 0xf9, 0x9f, 0xb9, 0xf9, 0xa0, 0xb9, 0xf9, 0xa1, 0xba, + 0xf9, 0xa3, 0xbb, 0xf9, 0xa4, 0xbb, 0xf9, 0xa5, 0xbc, 0xf9, 0xa6, 0xbd, 0xf9, 0xa8, 0xbe, 0xf9, + 0xa9, 0xbe, 0xf9, 0xaa, 0xbf, 0xf8, 0xab, 0xc0, 0xf8, 0xad, 0xc1, 0xf8, 0xae, 0xc2, 0xf8, 0xaf, + 0xc2, 0xf8, 0xb0, 0xc3, 0xf8, 0xb1, 0xc4, 0xf8, 0xb3, 0xc5, 0xf8, 0xb4, 0xc5, 0xf8, 0xb5, 0xc6, + 0xf7, 0xb6, 0xc7, 0xf7, 0xb7, 0xc8, 0xf7, 0xb9, 0xc8, 0xf7, 0xba, 0xc9, 0xf7, 0xbb, 0xca, 0xf7, + 0xbc, 0xcb, 0xf7, 0xbd, 0xcb, 0xf7, 0xbe, 0xcc, 0xf7, 0xc0, 0xcd, 0xf6, 0xc1, 0xce, 0xf6, 0xc2, + 0xce, 0xf6, 0xc3, 0xcf, 0xf6, 0xc4, 0xd0, 0xf6, 0xc5, 0xd1, 0xf6, 0xc6, 0xd2, 0xf6, 0xc7, 0xd2, + 0xf6, 0xc9, 0xd3, 0xf6, 0xca, 0xd4, 0xf5, 0xcb, 0xd5, 0xf5, 0xcc, 0xd5, 0xf5, 0xcd, 0xd6, 0xf5, + 0xce, 0xd7, 0xf5, 0xcf, 0xd8, 0xf5, 0xd0, 0xd9, 0xf5, 0xd1, 0xd9, 0xf5, 0xd3, 0xda, 0xf4, 0xd4, + 0xdb, 0xf4, 0xd5, 0xdc, 0xf4, 0xd6, 0xdc, 0xf4, 0xd7, 0xdd, 0xf4, 0xd8, 0xde, 0xf4, 0xd9, 0xdf, + 0xf4, 0xda, 0xe0, 0xf4, 0xdb, 0xe0, 0xf3, 0xdc, 0xe1, 0xf3, 0xdd, 0xe2, 0xf3, 0xde, 0xe3, 0xf3, + 0xdf, 0xe4, 0xf3, 0xe0, 0xe4, 0xf3, 0xe2, 0xe5, 0xf3, 0xe3, 0xe6, 0xf2, 0xe4, 0xe7, 0xf2, 0xe5, + 0xe7, 0xf2, 0xe6, 0xe8, 0xf2, 0xe7, 0xe9, 0xf2, 0xe8, 0xea, 0xf1, 0xe9, 0xea, 0xf1, 0xea, 0xeb, + 0xf1, 0xea, 0xec, 0xf0, 0xeb, 0xec, 0xf0, 0xec, 0xec, 0xef, 0xec, 0xed, 0xee, 0xed, 0xed, 0xed, + 0xed, 0xed, 0xec, 0xee, 0xed, 0xeb, 0xee, 0xec, 0xea, 0xee, 0xec, 0xe8, 0xee, 0xec, 0xe7, 0xee, + 0xeb, 0xe5, 0xed, 0xea, 0xe4, 0xed, 0xea, 0xe2, 0xed, 0xe9, 0xe0, 0xec, 0xe8, 0xdf, 0xec, 0xe7, + 0xdd, 0xec, 0xe7, 0xdb, 0xeb, 0xe6, 0xda, 0xeb, 0xe5, 0xd8, 0xea, 0xe4, 0xd6, 0xea, 0xe4, 0xd5, + 0xe9, 0xe3, 0xd3, 0xe9, 0xe2, 0xd1, 0xe9, 0xe1, 0xd0, 0xe8, 0xe0, 0xce, 0xe8, 0xe0, 0xcc, 0xe7, + 0xdf, 0xca, 0xe7, 0xde, 0xc9, 0xe6, 0xdd, 0xc7, 0xe6, 0xdc, 0xc5, 0xe5, 0xdc, 0xc4, 0xe5, 0xdb, + 0xc2, 0xe4, 0xda, 0xc0, 0xe4, 0xd9, 0xbf, 0xe3, 0xd8, 0xbd, 0xe3, 0xd8, 0xbb, 0xe2, 0xd7, 0xba, + 0xe2, 0xd6, 0xb8, 0xe2, 0xd5, 0xb6, 0xe1, 0xd5, 0xb5, 0xe1, 0xd4, 0xb3, 0xe0, 0xd3, 0xb1, 0xe0, + 0xd2, 0xb0, 0xdf, 0xd1, 0xae, 0xdf, 0xd1, 0xac, 0xde, 0xd0, 0xab, 0xde, 0xcf, 0xa9, 0xdd, 0xce, + 0xa7, 0xdc, 0xce, 0xa6, 0xdc, 0xcd, 0xa4, 0xdb, 0xcc, 0xa2, 0xdb, 0xcb, 0xa1, 0xda, 0xcb, 0x9f, + 0xda, 0xca, 0x9d, 0xd9, 0xc9, 0x9c, 0xd9, 0xc8, 0x9a, 0xd8, 0xc7, 0x98, 0xd8, 0xc7, 0x97, 0xd7, + 0xc6, 0x95, 0xd7, 0xc5, 0x94, 0xd6, 0xc4, 0x92, 0xd6, 0xc4, 0x90, 0xd5, 0xc3, 0x8f, 0xd4, 0xc2, + 0x8d, 0xd4, 0xc1, 0x8b, 0xd3, 0xc1, 0x8a, 0xd3, 0xc0, 0x88, 0xd2, 0xbf, 0x86, 0xd2, 0xbe, 0x85, + 0xd1, 0xbe, 0x83, 0xd0, 0xbd, 0x81, 0xd0, 0xbc, 0x80, 0xcf, 0xbb, 0x7e, 0xcf, 0xbb, 0x7d, 0xce, + 0xba, 0x7b, 0xce, 0xb9, 0x79, 0xcd, 0xb8, 0x78, 0xcc, 0xb8, 0x76, 0xcc, 0xb7, 0x74, 0xcb, 0xb6, + 0x73, 0xcb, 0xb5, 0x71, 0xca, 0xb5, 0x6f, 0xc9, 0xb4, 0x6e, 0xc9, 0xb3, 0x6c, 0xc8, 0xb2, 0x6a, + 0xc7, 0xb2, 0x69, 0xc7, 0xb1, 0x67, 0xc6, 0xb0, 0x66, 0xc6, 0xaf, 0x64, 0xc5, 0xaf, 0x62, 0xc4, + 0xae, 0x61, 0xc4, 0xad, 0x5f, 0xc3, 0xac, 0x5d, 0xc2, 0xac, 0x5c, 0xc2, 0xab, 0x5a, 0xc1, 0xaa, + 0x58, 0xc1, 0xa9, 0x57, 0xc0, 0xa9, 0x55, 0xbf, 0xa8, 0x53, 0xbf, 0xa7, 0x51, 0xbe, 0xa6, 0x50, + 0xbd, 0xa6, 0x4e, 0xbd, 0xa5, 0x4c, 0xbc, 0xa4, 0x4b, 0xbb, 0xa4, 0x49, 0xbb, 0xa3, 0x47, 0xba, + 0xa2, 0x45, 0xb9, 0xa1, 0x44, 0xb9, 0xa1, 0x42, 0xb8, 0xa0, 0x40, 0xb7, 0x9f, 0x3e, 0xb7, 0x9f, + 0x3c, 0xb6, 0x9e, 0x3b, 0xb5, 0x9d, 0x39, 0xb4, 0x9c, 0x37, 0xb4, 0x9c, 0x35, 0xb3, 0x9b, 0x33, + 0xb2, 0x9a, 0x31, 0xb2, 0x99, 0x2f, 0xb1, 0x99, 0x2d, 0xb0, 0x98, 0x2b, 0xb0, 0x97, 0x29, 0xaf, + 0x97, 0x27, 0xae, 0x96, 0x24, 0xad, 0x95, 0x22, 0xad, 0x95, 0x20, 0xac, 0x94, 0x1d, 0xab, 0x93, + 0x1a, 0xab, 0x92, 0x17, 0xaa, 0x92, 0x14, 0xa9, 0x91, 0x11, 0xa8, 0x90, 0x0d, 0xa8, 0x90, 0x08 +}; +} // namespace CET -#endif//_CET_LUT_HPP_ +#endif //_CET_LUT_HPP_ diff --git a/src/Gui/propertyeditor/PropertyEditor.cpp b/src/Gui/propertyeditor/PropertyEditor.cpp index 500ce3ccca..039a1f3481 100644 --- a/src/Gui/propertyeditor/PropertyEditor.cpp +++ b/src/Gui/propertyeditor/PropertyEditor.cpp @@ -106,7 +106,8 @@ PropertyEditor::PropertyEditor(QWidget* parent) viewport()->setMouseTracking(true); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/DockWindows/PropertyView"); + "User parameter:BaseApp/Preferences/DockWindows/PropertyView" + ); int firstColumnSize = hGrp->GetInt("FirstColumnSize", 0); if (firstColumnSize != 0) { header()->resizeSection(0, firstColumnSize); @@ -243,14 +244,12 @@ void PropertyEditor::keyPressEvent(QKeyEvent* event) const auto key = event->key(); const auto mods = event->modifiers(); - const bool allowedDeleteModifiers = - mods == Qt::NoModifier || - mods == Qt::KeypadModifier; + const bool allowedDeleteModifiers = mods == Qt::NoModifier || mods == Qt::KeypadModifier; #if defined(Q_OS_MACOS) || defined(Q_OS_MAC) const bool isDeleteKey = key == Qt::Key_Backspace || key == Qt::Key_Delete; - const bool isEditKey = (mods == Qt::NoModifier) && - (key == Qt::Key_Return || key == Qt::Key_Enter); + const bool isEditKey = (mods == Qt::NoModifier) + && (key == Qt::Key_Return || key == Qt::Key_Enter); #else const bool isDeleteKey = key == Qt::Key_Delete; const bool isEditKey = (mods == Qt::NoModifier) && (key == Qt::Key_F2); @@ -298,8 +297,10 @@ void PropertyEditor::editorDestroyed(QObject* editor) void PropertyEditor::currentChanged(const QModelIndex& current, const QModelIndex& previous) { - FC_LOG("current changed " << current.row() << "," << current.column() << " " << previous.row() - << "," << previous.column()); + FC_LOG( + "current changed " << current.row() << "," << current.column() << " " << previous.row() + << "," << previous.column() + ); QTreeView::currentChanged(current, previous); @@ -449,11 +450,13 @@ void PropertyEditor::recomputeDocument(App::Document* doc) Base::Console().error( "Unhandled std::exception caught in PropertyEditor::recomputeDocument.\n" "The error message is: %s\n", - e.what()); + e.what() + ); } catch (...) { Base::Console().error( - "Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n"); + "Unhandled unknown exception caught in PropertyEditor::recomputeDocument.\n" + ); } } @@ -569,11 +572,7 @@ void PropertyEditor::reset() } } -void PropertyEditor::onRowsMoved(const QModelIndex& parent, - int start, - int end, - const QModelIndex& dst, - int) +void PropertyEditor::onRowsMoved(const QModelIndex& parent, int start, int end, const QModelIndex& dst, int) { if (parent != dst) { auto item = static_cast(parent.internalPointer()); @@ -650,9 +649,7 @@ void PropertyEditor::onRowsRemoved(const QModelIndex&, int, int) removingRows = 0; } -void PropertyEditor::drawBranches(QPainter* painter, - const QRect& rect, - const QModelIndex& index) const +void PropertyEditor::drawBranches(QPainter* painter, const QRect& rect, const QModelIndex& index) const { QTreeView::drawBranches(painter, rect, index); @@ -663,9 +660,11 @@ void PropertyEditor::drawBranches(QPainter* painter, } } -void Gui::PropertyEditor::PropertyEditor::drawRow(QPainter* painter, - const QStyleOptionViewItem& options, - const QModelIndex& index) const +void Gui::PropertyEditor::PropertyEditor::drawRow( + QPainter* painter, + const QStyleOptionViewItem& options, + const QModelIndex& index +) const { // render background also for non alternate rows based on the `itemBackground` property. painter->fillRect(options.rect, itemBackground()); @@ -684,7 +683,8 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList&& props, bool _checkDoc if (committing) { Base::Console().warning( - "While committing the data to the property the selection has changed.\n"); + "While committing the data to the property the selection has changed.\n" + ); delaybuild = true; return; } @@ -722,18 +722,18 @@ void PropertyEditor::buildUp(PropertyModel::PropertyList&& props, bool _checkDoc } switch (expansionMode) { - case ExpansionMode::DefaultExpand: - // take the current expansion state - break; - case ExpansionMode::AutoExpand: - expandAll(); - break; - case ExpansionMode::AutoCollapse: - if (!blockCollapse) { - collapseAll(); - } - blockCollapse = false; - break; + case ExpansionMode::DefaultExpand: + // take the current expansion state + break; + case ExpansionMode::AutoExpand: + expandAll(); + break; + case ExpansionMode::AutoCollapse: + if (!blockCollapse) { + collapseAll(); + } + blockCollapse = false; + break; } } @@ -778,7 +778,7 @@ void PropertyEditor::removeProperty(const App::Property& prop) void PropertyEditor::renameProperty(const App::Property& prop) { - for (auto & it : propList) { + for (auto& it : propList) { // find the given property in the list and rename it if it's there auto pos = std::ranges::find(it.second, &prop); if (pos != it.second.end()) { @@ -821,8 +821,8 @@ void PropertyEditor::setFirstLevelExpanded(bool doExpand) return; } - std::function setExpanded = [&]( - const QModelIndex& index, bool doExpand) { + std::function setExpanded = [&](const QModelIndex& index, + bool doExpand) { if (!index.isValid()) { return; } @@ -845,7 +845,7 @@ void PropertyEditor::setFirstLevelExpanded(bool doExpand) }; const QModelIndex root = QModelIndex(); - for (int row = 0; row rowCount(root); ++row) { + for (int row = 0; row < propertyModel->rowCount(root); ++row) { setExpanded(propertyModel->index(row, 0, root), doExpand); } } @@ -889,15 +889,15 @@ QMenu* PropertyEditor::setupExpansionSubmenu(QWidget* parent) } switch (expansionMode) { - case ExpansionMode::DefaultExpand: - defaultExpand->setChecked(true); - break; - case ExpansionMode::AutoExpand: - autoExpand->setChecked(true); - break; - case ExpansionMode::AutoCollapse: - autoCollapse->setChecked(true); - break; + case ExpansionMode::DefaultExpand: + defaultExpand->setChecked(true); + break; + case ExpansionMode::AutoExpand: + autoExpand->setChecked(true); + break; + case ExpansionMode::AutoCollapse: + autoCollapse->setChecked(true); + break; } return expandMenu; @@ -1045,22 +1045,22 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent*) QAction* action; QString text; -#define _ACTION_SETUP(_name) \ - do { \ - text = tr(#_name); \ - action = subMenu->addAction(text); \ - action->setData(QVariant(MA_##_name)); \ - action->setCheckable(true); \ - if (propStatus & (1 << App::Property::_name)) \ - action->setChecked(true); \ +#define _ACTION_SETUP(_name) \ + do { \ + text = tr(#_name); \ + action = subMenu->addAction(text); \ + action->setData(QVariant(MA_##_name)); \ + action->setCheckable(true); \ + if (propStatus & (1 << App::Property::_name)) \ + action->setChecked(true); \ } while (0) -#define ACTION_SETUP(_name) \ - do { \ - _ACTION_SETUP(_name); \ - if (propType & App::Prop_##_name) { \ - action->setText(text + QStringLiteral(" *")); \ - action->setChecked(true); \ - } \ +#define ACTION_SETUP(_name) \ + do { \ + _ACTION_SETUP(_name); \ + if (propType & App::Prop_##_name) { \ + action->setText(text + QStringLiteral(" *")); \ + action->setChecked(true); \ + } \ } while (0) ACTION_SETUP(Hidden); @@ -1110,15 +1110,15 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent*) case MA_Copy: { const QVariant valueToCopy = contextIndex.data(Qt::DisplayRole); if (valueToCopy.isValid()) { - auto *clipboard = QApplication::clipboard(); + auto* clipboard = QApplication::clipboard(); clipboard->setText(valueToCopy.toString()); } return; } -#define ACTION_CHECK(_name) \ - case MA_##_name: \ - for (auto prop : props) \ - prop->setStatus(App::Property::_name, action->isChecked()); \ +#define ACTION_CHECK(_name) \ + case MA_##_name: \ + for (auto prop : props) \ + prop->setStatus(App::Property::_name, action->isChecked()); \ break ACTION_CHECK(Transient); ACTION_CHECK(ReadOnly); @@ -1166,18 +1166,19 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent*) bool ok = false; const QString currentTooltip = QString::fromUtf8(prop->getDocumentation()); - QString newTooltip = QInputDialog::getMultiLineText(Gui::getMainWindow(), - tr("Edit Property Tooltip"), - tr("Tooltip"), - currentTooltip, - &ok); + QString newTooltip = QInputDialog::getMultiLineText( + Gui::getMainWindow(), + tr("Edit Property Tooltip"), + tr("Tooltip"), + currentTooltip, + &ok + ); if (!ok || newTooltip == currentTooltip) { break; } - prop->getContainer()->changeDynamicProperty(prop, - prop->getGroup(), - newTooltip.toUtf8().constData()); + prop->getContainer() + ->changeDynamicProperty(prop, prop->getGroup(), newTooltip.toUtf8().constData()); break; } case MA_RenameProp: { @@ -1193,11 +1194,13 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent*) App::AutoTransaction committer("Rename property"); const char* oldName = prop->getName(); - QString res = QInputDialog::getText(Gui::getMainWindow(), - tr("Rename property"), - tr("Property name"), - QLineEdit::Normal, - QString::fromUtf8(oldName)); + QString res = QInputDialog::getText( + Gui::getMainWindow(), + tr("Rename property"), + tr("Property name"), + QLineEdit::Normal, + QString::fromUtf8(oldName) + ); if (res.isEmpty()) { break; } @@ -1218,11 +1221,13 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent*) if (!groupName) { groupName = "Base"; } - QString res = QInputDialog::getText(Gui::getMainWindow(), - tr("Rename property group"), - tr("Group name:"), - QLineEdit::Normal, - QString::fromUtf8(groupName)); + QString res = QInputDialog::getText( + Gui::getMainWindow(), + tr("Rename property group"), + tr("Group name:"), + QLineEdit::Normal, + QString::fromUtf8(groupName) + ); if (res.size()) { std::string group = res.toUtf8().constData(); for (auto prop : props) { @@ -1255,7 +1260,8 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) // using minimal size = dragSensibility * 2 to prevent collapsing header_view->resizeSection( dragSection, - qMax(dragSensibility * 2, header_view->sectionSize(dragSection) + delta)); + qMax(dragSensibility * 2, header_view->sectionSize(dragSection) + delta) + ); return true; } else { // set mouse cursor shape @@ -1285,7 +1291,8 @@ bool PropertyEditor::eventFilter(QObject* object, QEvent* event) dragInProgress = false; auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/DockWindows/PropertyView"); + "User parameter:BaseApp/Preferences/DockWindows/PropertyView" + ); hGrp->SetInt("FirstColumnSize", header()->sectionSize(0)); return true; } diff --git a/src/Gui/propertyeditor/PropertyEditor.h b/src/Gui/propertyeditor/PropertyEditor.h index 6fa535b5e2..210b89e7a4 100644 --- a/src/Gui/propertyeditor/PropertyEditor.h +++ b/src/Gui/propertyeditor/PropertyEditor.h @@ -71,7 +71,8 @@ class GuiExport PropertyEditor: public QTreeView // clang-format on public: - enum class ExpansionMode { + enum class ExpansionMode + { DefaultExpand, AutoExpand, AutoCollapse @@ -81,8 +82,10 @@ public: ~PropertyEditor() override; /** Builds up the list view with the properties. */ - void buildUp(PropertyModel::PropertyList&& props = PropertyModel::PropertyList(), - bool checkDocument = false); + void buildUp( + PropertyModel::PropertyList&& props = PropertyModel::PropertyList(), + bool checkDocument = false + ); void blockCollapseAll(); void updateProperty(const App::Property&); void removeProperty(const App::Property&); @@ -110,8 +113,7 @@ protected Q_SLOTS: void onItemActivated(const QModelIndex& index); void onItemExpanded(const QModelIndex& index); void onItemCollapsed(const QModelIndex& index); - void - onRowsMoved(const QModelIndex& parent, int start, int end, const QModelIndex& dst, int row); + void onRowsMoved(const QModelIndex& parent, int start, int end, const QModelIndex& dst, int row); void onRowsRemoved(const QModelIndex& parent, int start, int end); protected: @@ -122,11 +124,12 @@ protected: void currentChanged(const QModelIndex& current, const QModelIndex& previous) override; void rowsInserted(const QModelIndex& parent, int start, int end) override; void rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) override; - void - drawBranches(QPainter* painter, const QRect& rect, const QModelIndex& index) const override; - void drawRow(QPainter* painter, - const QStyleOptionViewItem& options, - const QModelIndex& index) const override; + void drawBranches(QPainter* painter, const QRect& rect, const QModelIndex& index) const override; + void drawRow( + QPainter* painter, + const QStyleOptionViewItem& options, + const QModelIndex& index + ) const override; #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) QStyleOptionViewItem viewOptions() const override; #else diff --git a/src/Gui/propertyeditor/PropertyItem.cpp b/src/Gui/propertyeditor/PropertyItem.cpp index ef9a2a15de..904fd58130 100644 --- a/src/Gui/propertyeditor/PropertyItem.cpp +++ b/src/Gui/propertyeditor/PropertyItem.cpp @@ -496,9 +496,8 @@ QVariant PropertyItem::value(const App::Property* /*prop*/) const void PropertyItem::setValue(const QVariant& /*value*/) {} -QWidget* PropertyItem::createEditor(QWidget* /*parent*/, - const std::function& /*method*/, - FrameOption /*frameOption*/) const +QWidget* PropertyItem:: + createEditor(QWidget* /*parent*/, const std::function& /*method*/, FrameOption /*frameOption*/) const { return nullptr; } @@ -511,8 +510,7 @@ QVariant PropertyItem::editorData(QWidget* /*editor*/) const return {}; } -QWidget* PropertyItem::createExpressionEditor(QWidget* parent, - const std::function& method) const +QWidget* PropertyItem::createExpressionEditor(QWidget* parent, const std::function& method) const { if (!isBound()) { return nullptr; @@ -620,8 +618,7 @@ void PropertyItem::setPropertyValue(const std::string& value) << obj->getNameInDocument() << "')."; } else if (parent->isDerivedFrom()) { - App::DocumentObject* obj = - static_cast(parent)->getObject(); + App::DocumentObject* obj = static_cast(parent)->getObject(); App::Document* doc = obj->getDocument(); ss << "FreeCADGui.getDocument('" << doc->getName() << "').getObject('" << obj->getNameInDocument() << "')."; @@ -682,9 +679,9 @@ QVariant PropertyItem::dataPropertyName(int role) const return {}; } if (role == Qt::ToolTipRole) { - QString type = - QStringLiteral("Type: %1\nName: %2") - .arg(QString::fromLatin1(propertyItems[0]->getTypeId().getName()), objectName()); + QString type + = QStringLiteral("Type: %1\nName: %2") + .arg(QString::fromLatin1(propertyItems[0]->getTypeId().getName()), objectName()); QString doc = PropertyItem::toolTip(propertyItems[0]).toString(); if (doc.isEmpty()) { @@ -846,9 +843,11 @@ void PropertyStringItem::setValue(const QVariant& value) } } -QWidget* PropertyStringItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyStringItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto le = new ExpLineEdit(parent); le->setFrame(static_cast(frameOption)); @@ -894,9 +893,11 @@ void PropertyFontItem::setValue(const QVariant& value) } } -QWidget* PropertyFontItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyFontItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto cb = new QComboBox(parent); cb->setFrame(static_cast(frameOption)); @@ -927,9 +928,11 @@ QVariant PropertyFontItem::editorData(QWidget* editor) const PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertySeparatorItem) -QWidget* PropertySeparatorItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertySeparatorItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { Q_UNUSED(parent); Q_UNUSED(method); @@ -960,9 +963,11 @@ void PropertyIntegerItem::setValue(const QVariant& value) } } -QWidget* PropertyIntegerItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyIntegerItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto sb = new Gui::IntSpinBox(parent); sb->setFrame(static_cast(frameOption)); @@ -979,8 +984,7 @@ QWidget* PropertyIntegerItem::createEditor(QWidget* parent, void PropertyIntegerItem::setEditorData(QWidget* editor, const QVariant& data) const { auto sb = qobject_cast(editor); - sb->setRange(std::numeric_limits::min(), - std::numeric_limits::max()); + sb->setRange(std::numeric_limits::min(), std::numeric_limits::max()); sb->setValue(data.toInt()); } @@ -995,8 +999,7 @@ QString PropertyIntegerItem::toString(const QVariant& v) const QString string(PropertyItem::toString(v)); if (hasExpression()) { - string += - QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString())); + string += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString())); } return string; @@ -1026,9 +1029,11 @@ void PropertyIntegerConstraintItem::setValue(const QVariant& value) } } -QWidget* PropertyIntegerConstraintItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyIntegerConstraintItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto sb = new Gui::IntSpinBox(parent); sb->setFrame(static_cast(frameOption)); @@ -1077,8 +1082,7 @@ QString PropertyIntegerConstraintItem::toString(const QVariant& v) const QString string(PropertyItem::toString(v)); if (hasExpression()) { - string += - QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString())); + string += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString())); } return string; @@ -1121,9 +1125,11 @@ void PropertyFloatItem::setValue(const QVariant& value) } } -QWidget* PropertyFloatItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyFloatItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto sb = new Gui::DoubleSpinBox(parent); sb->setFrame(static_cast(frameOption)); @@ -1141,8 +1147,10 @@ QWidget* PropertyFloatItem::createEditor(QWidget* parent, void PropertyFloatItem::setEditorData(QWidget* editor, const QVariant& data) const { auto sb = qobject_cast(editor); - sb->setRange(static_cast(std::numeric_limits::min()), - static_cast(std::numeric_limits::max())); + sb->setRange( + static_cast(std::numeric_limits::min()), + static_cast(std::numeric_limits::max()) + ); sb->setValue(data.toDouble()); } @@ -1188,9 +1196,11 @@ void PropertyUnitItem::setValue(const QVariant& value) } } -QWidget* PropertyUnitItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyUnitItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto infield = new Gui::QuantitySpinBox(parent); infield->setFrame(static_cast(frameOption)); @@ -1286,9 +1296,11 @@ void PropertyFloatConstraintItem::setValue(const QVariant& value) } } -QWidget* PropertyFloatConstraintItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyFloatConstraintItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { auto sb = new Gui::DoubleSpinBox(parent); sb->setDecimals(decimals()); @@ -1380,9 +1392,8 @@ void PropertyBoolItem::setValue(const QVariant& value) } } -QWidget* PropertyBoolItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyBoolItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto checkbox = new QCheckBox(parent); #if QT_VERSION < QT_VERSION_CHECK(6, 7, 0) @@ -1436,10 +1447,12 @@ public: .arg(value.y, 0, 'f', decimals) .arg(value.z, 0, 'f', decimals); - Gui::Command::doCommand(Gui::Command::Doc, - "%s = %s", - propName.c_str(), - str.toLatin1().constData()); + Gui::Command::doCommand( + Gui::Command::Doc, + "%s = %s", + propName.c_str(), + str.toLatin1().constData() + ); return true; } } @@ -1474,9 +1487,11 @@ QString PropertyVectorItem::toString(const QVariant& prop) const QLocale loc; const Base::Vector3d& value = prop.value(); QString data = QStringLiteral("[%1 %2 %3]") - .arg(loc.toString(value.x, 'f', lowPrec), - loc.toString(value.y, 'f', lowPrec), - loc.toString(value.z, 'f', lowPrec)); + .arg( + loc.toString(value.x, 'f', lowPrec), + loc.toString(value.y, 'f', lowPrec), + loc.toString(value.z, 'f', lowPrec) + ); if (hasExpression()) { data += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString())); } @@ -1504,9 +1519,11 @@ void PropertyVectorItem::setValue(const QVariant& value) setPropertyValue(data); } -QWidget* PropertyVectorItem::createEditor(QWidget* parent, - const std::function& /*method*/, - FrameOption frameOption) const +QWidget* PropertyVectorItem::createEditor( + QWidget* parent, + const std::function& /*method*/, + FrameOption frameOption +) const { auto le = new VectorLineEdit(decimals(), parent); le->setFrame(static_cast(frameOption)); @@ -1526,9 +1543,11 @@ void PropertyVectorItem::setEditorData(QWidget* editor, const QVariant& data) co auto le = qobject_cast(editor); const Base::Vector3d& value = data.value(); QString text = QStringLiteral("[%1 %2 %3]") - .arg(loc.toString(value.x, 'f', lowPrec), - loc.toString(value.y, 'f', lowPrec), - loc.toString(value.z, 'f', lowPrec)); + .arg( + loc.toString(value.x, 'f', lowPrec), + loc.toString(value.y, 'f', lowPrec), + loc.toString(value.z, 'f', lowPrec) + ); le->setProperty("coords", data); le->setText(text); } @@ -1591,8 +1610,7 @@ PropertyEditorWidget::PropertyEditorWidget(QWidget* parent) button = new QPushButton(QStringLiteral("…"), this); #if defined(Q_OS_MACOS) - button->setAttribute( - Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct + button->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct #endif layout->addWidget(button); @@ -1668,9 +1686,11 @@ void VectorListWidget::showValue(const QVariant& d) } else { data = QStringLiteral("[%1 %2 %3], ...") - .arg(loc.toString(value[0].x, 'f', lowPrec), - loc.toString(value[0].y, 'f', lowPrec), - loc.toString(value[0].z, 'f', lowPrec)); + .arg( + loc.toString(value[0].x, 'f', lowPrec), + loc.toString(value[0].y, 'f', lowPrec), + loc.toString(value[0].z, 'f', lowPrec) + ); } lineEdit->setText(data); } @@ -1688,9 +1708,11 @@ QString PropertyVectorListItem::toString(const QVariant& prop) const } QLocale loc; QString data = QStringLiteral("[%1 %2 %3], ...") - .arg(loc.toString(value[0].x, 'f', lowPrec), - loc.toString(value[0].y, 'f', lowPrec), - loc.toString(value[0].z, 'f', lowPrec)); + .arg( + loc.toString(value[0].x, 'f', lowPrec), + loc.toString(value[0].y, 'f', lowPrec), + loc.toString(value[0].z, 'f', lowPrec) + ); if (hasExpression()) { data += QStringLiteral(" ( %1 )").arg(QString::fromStdString(getExpressionString())); @@ -1702,8 +1724,8 @@ QVariant PropertyVectorListItem::value(const App::Property* prop) const { assert(prop && prop->isDerivedFrom()); - const std::vector& value = - static_cast(prop)->getValue(); + const std::vector& value + = static_cast(prop)->getValue(); QList list; std::copy(value.begin(), value.end(), std::back_inserter(list)); return QVariant::fromValue>(list); @@ -1728,9 +1750,8 @@ void PropertyVectorListItem::setValue(const QVariant& value) setPropertyValue(data); } -QWidget* PropertyVectorListItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyVectorListItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto pe = new VectorListWidget(decimals(), parent); QObject::connect(pe, &VectorListWidget::valueChanged, method); @@ -1772,10 +1793,12 @@ PropertyVectorDistanceItem::PropertyVectorDistanceItem() QString PropertyVectorDistanceItem::toString(const QVariant& prop) const { const Base::Vector3d& value = prop.value(); - std::string str = fmt::format("[{} {} {}]", - Base::Quantity(value.x, Base::Unit::Length).getUserString(), - Base::Quantity(value.y, Base::Unit::Length).getUserString(), - Base::Quantity(value.z, Base::Unit::Length).getUserString()); + std::string str = fmt::format( + "[{} {} {}]", + Base::Quantity(value.x, Base::Unit::Length).getUserString(), + Base::Quantity(value.y, Base::Unit::Length).getUserString(), + Base::Quantity(value.z, Base::Unit::Length).getUserString() + ); if (hasExpression()) { str += fmt::format(" ( {} )", getExpressionString()); } @@ -1797,8 +1820,15 @@ void PropertyVectorDistanceItem::setValue(const QVariant& variant) return; } const Base::Vector3d& value = variant.value(); - std::string val = fmt::format("({:.{}g}, {:.{}g}, {:.{}g})", - value.x, highPrec, value.y, highPrec, value.z, highPrec); + std::string val = fmt::format( + "({:.{}g}, {:.{}g}, {:.{}g})", + value.x, + highPrec, + value.y, + highPrec, + value.z, + highPrec + ); setPropertyValue(val); } @@ -1809,9 +1839,11 @@ void PropertyVectorDistanceItem::setEditorData(QWidget* editor, const QVariant& le->setText(toString(data)); } -QWidget* PropertyVectorDistanceItem::createEditor(QWidget* parent, - const std::function& /*method*/, - FrameOption frameOption) const +QWidget* PropertyVectorDistanceItem::createEditor( + QWidget* parent, + const std::function& /*method*/, + FrameOption frameOption +) const { auto le = new VectorLineEdit(decimals(), parent); le->setFrame(static_cast(frameOption)); @@ -1969,22 +2001,26 @@ QString PropertyMatrixItem::toString(const QVariant& prop) const const Base::Matrix4D& value = prop.value(); // NOLINTBEGIN QString text = QStringLiteral("[%1 %2 %3 %4 %5 %6 %7 %8 %9 %10 %11 %12 %13 %14 %15 %16]") - .arg(loc.toString(value[0][0], 'f', lowPrec), //(unsigned short usNdx) - loc.toString(value[0][1], 'f', lowPrec), - loc.toString(value[0][2], 'f', lowPrec), - loc.toString(value[0][3], 'f', lowPrec), - loc.toString(value[1][0], 'f', lowPrec), - loc.toString(value[1][1], 'f', lowPrec), - loc.toString(value[1][2], 'f', lowPrec), - loc.toString(value[1][3], 'f', lowPrec), - loc.toString(value[2][0], 'f', lowPrec)) - .arg(loc.toString(value[2][1], 'f', lowPrec), - loc.toString(value[2][2], 'f', lowPrec), - loc.toString(value[2][3], 'f', lowPrec), - loc.toString(value[3][0], 'f', lowPrec), - loc.toString(value[3][1], 'f', lowPrec), - loc.toString(value[3][2], 'f', lowPrec), - loc.toString(value[3][3], 'f', lowPrec)); + .arg( + loc.toString(value[0][0], 'f', lowPrec), //(unsigned short usNdx) + loc.toString(value[0][1], 'f', lowPrec), + loc.toString(value[0][2], 'f', lowPrec), + loc.toString(value[0][3], 'f', lowPrec), + loc.toString(value[1][0], 'f', lowPrec), + loc.toString(value[1][1], 'f', lowPrec), + loc.toString(value[1][2], 'f', lowPrec), + loc.toString(value[1][3], 'f', lowPrec), + loc.toString(value[2][0], 'f', lowPrec) + ) + .arg( + loc.toString(value[2][1], 'f', lowPrec), + loc.toString(value[2][2], 'f', lowPrec), + loc.toString(value[2][3], 'f', lowPrec), + loc.toString(value[3][0], 'f', lowPrec), + loc.toString(value[3][1], 'f', lowPrec), + loc.toString(value[3][2], 'f', lowPrec), + loc.toString(value[3][3], 'f', lowPrec) + ); // NOLINTEND return text; } @@ -2012,32 +2048,33 @@ void PropertyMatrixItem::setValue(const QVariant& value) } const Base::Matrix4D& val = value.value(); // NOLINTBEGIN - QString data = - QStringLiteral( - "FreeCAD.Matrix(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16)") - .arg(val[0][0], 0, 'g', highPrec) - .arg(val[0][1], 0, 'g', highPrec) - .arg(val[0][2], 0, 'g', highPrec) - .arg(val[0][3], 0, 'g', highPrec) - .arg(val[1][0], 0, 'g', highPrec) - .arg(val[1][1], 0, 'g', highPrec) - .arg(val[1][2], 0, 'g', highPrec) - .arg(val[1][3], 0, 'g', highPrec) - .arg(val[2][0], 0, 'g', highPrec) - .arg(val[2][1], 0, 'g', highPrec) - .arg(val[2][2], 0, 'g', highPrec) - .arg(val[2][3], 0, 'g', highPrec) - .arg(val[3][0], 0, 'g', highPrec) - .arg(val[3][1], 0, 'g', highPrec) - .arg(val[3][2], 0, 'g', highPrec) - .arg(val[3][3], 0, 'g', highPrec); + QString data + = QStringLiteral("FreeCAD.Matrix(%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, %12, %13, %14, %15, %16)") + .arg(val[0][0], 0, 'g', highPrec) + .arg(val[0][1], 0, 'g', highPrec) + .arg(val[0][2], 0, 'g', highPrec) + .arg(val[0][3], 0, 'g', highPrec) + .arg(val[1][0], 0, 'g', highPrec) + .arg(val[1][1], 0, 'g', highPrec) + .arg(val[1][2], 0, 'g', highPrec) + .arg(val[1][3], 0, 'g', highPrec) + .arg(val[2][0], 0, 'g', highPrec) + .arg(val[2][1], 0, 'g', highPrec) + .arg(val[2][2], 0, 'g', highPrec) + .arg(val[2][3], 0, 'g', highPrec) + .arg(val[3][0], 0, 'g', highPrec) + .arg(val[3][1], 0, 'g', highPrec) + .arg(val[3][2], 0, 'g', highPrec) + .arg(val[3][3], 0, 'g', highPrec); // NOLINTEND setPropertyValue(data); } -QWidget* PropertyMatrixItem::createEditor(QWidget* parent, - const std::function& /*method*/, - FrameOption frameOption) const +QWidget* PropertyMatrixItem::createEditor( + QWidget* parent, + const std::function& /*method*/, + FrameOption frameOption +) const { auto le = new QLineEdit(parent); le->setFrame(static_cast(frameOption)); @@ -2491,13 +2528,17 @@ QVariant PropertyRotationItem::toolTip(const App::Property* prop) const angle = Base::toDegrees(angle); QLocale loc; - QString data = - QStringLiteral("Axis: (%1 %2 %3)\n" - "Angle: %4") - .arg(loc.toString(dir.x, 'f', decimals()), - loc.toString(dir.y, 'f', decimals()), - loc.toString(dir.z, 'f', decimals()), - QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString())); + QString data + = QStringLiteral( + "Axis: (%1 %2 %3)\n" + "Angle: %4" + ) + .arg( + loc.toString(dir.x, 'f', decimals()), + loc.toString(dir.y, 'f', decimals()), + loc.toString(dir.z, 'f', decimals()), + QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()) + ); return {data}; } @@ -2510,12 +2551,14 @@ QString PropertyRotationItem::toString(const QVariant& prop) const angle = Base::toDegrees(angle); QLocale loc; - QString data = - QStringLiteral("[(%1 %2 %3); %4]") - .arg(loc.toString(dir.x, 'f', lowPrec), - loc.toString(dir.y, 'f', lowPrec), - loc.toString(dir.z, 'f', lowPrec), - QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString())); + QString data + = QStringLiteral("[(%1 %2 %3); %4]") + .arg( + loc.toString(dir.x, 'f', lowPrec), + loc.toString(dir.y, 'f', lowPrec), + loc.toString(dir.z, 'f', lowPrec), + QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()) + ); return data; } @@ -2533,15 +2576,25 @@ void PropertyRotationItem::setValue(const QVariant& value) Base::Vector3d axis; double angle {}; h.getValue(axis, angle); - std::string val = fmt::format("App.Rotation(App.Vector({:.{}g},{:.{}g},{:.{}g}),{:.{}g})", - axis.x, highPrec, axis.y, highPrec, axis.z, highPrec, - angle, highPrec); + std::string val = fmt::format( + "App.Rotation(App.Vector({:.{}g},{:.{}g},{:.{}g}),{:.{}g})", + axis.x, + highPrec, + axis.y, + highPrec, + axis.z, + highPrec, + angle, + highPrec + ); setPropertyValue(val); } -QWidget* PropertyRotationItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyRotationItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { Q_UNUSED(parent) Q_UNUSED(method) @@ -2618,13 +2671,15 @@ void PlacementEditor::showValue(const QVariant& d) QLocale loc; QString data = QString::fromUtf8("[(%1 %2 %3);%4 \xc2\xb0;(%5 %6 %7)]") - .arg(loc.toString(dir.x, 'f', lowPrec), - loc.toString(dir.y, 'f', lowPrec), - loc.toString(dir.z, 'f', lowPrec), - loc.toString(angle, 'f', lowPrec), - loc.toString(pos.x, 'f', lowPrec), - loc.toString(pos.y, 'f', lowPrec), - loc.toString(pos.z, 'f', lowPrec)); + .arg( + loc.toString(dir.x, 'f', lowPrec), + loc.toString(dir.y, 'f', lowPrec), + loc.toString(dir.z, 'f', lowPrec), + loc.toString(angle, 'f', lowPrec), + loc.toString(pos.x, 'f', lowPrec), + loc.toString(pos.y, 'f', lowPrec), + loc.toString(pos.z, 'f', lowPrec) + ); getLabel()->setText(data); } @@ -2794,17 +2849,21 @@ QVariant PropertyPlacementItem::toolTip(const App::Property* prop) const pos = p.getPosition(); QLocale loc; - QString data = - QStringLiteral("Axis: (%1 %2 %3)\n" - "Angle: %4\n" - "Position: (%5 %6 %7)") - .arg(loc.toString(dir.x, 'f', decimals()), - loc.toString(dir.y, 'f', decimals()), - loc.toString(dir.z, 'f', decimals()), - QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()), - QString::fromStdString(Base::Quantity(pos.x, Base::Unit::Length).getUserString()), - QString::fromStdString(Base::Quantity(pos.y, Base::Unit::Length).getUserString()), - QString::fromStdString(Base::Quantity(pos.z, Base::Unit::Length).getUserString())); + QString data + = QStringLiteral( + "Axis: (%1 %2 %3)\n" + "Angle: %4\n" + "Position: (%5 %6 %7)" + ) + .arg( + loc.toString(dir.x, 'f', decimals()), + loc.toString(dir.y, 'f', decimals()), + loc.toString(dir.z, 'f', decimals()), + QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()), + QString::fromStdString(Base::Quantity(pos.x, Base::Unit::Length).getUserString()), + QString::fromStdString(Base::Quantity(pos.y, Base::Unit::Length).getUserString()), + QString::fromStdString(Base::Quantity(pos.z, Base::Unit::Length).getUserString()) + ); return {data}; } @@ -2819,15 +2878,17 @@ QString PropertyPlacementItem::toString(const QVariant& prop) const pos = p.getPosition(); QLocale loc; - QString data = - QStringLiteral("[(%1 %2 %3); %4; (%5 %6 %7)]") - .arg(loc.toString(dir.x, 'f', lowPrec), - loc.toString(dir.y, 'f', lowPrec), - loc.toString(dir.z, 'f', lowPrec), - QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()), - QString::fromStdString(Base::Quantity(pos.x, Base::Unit::Length).getUserString()), - QString::fromStdString(Base::Quantity(pos.y, Base::Unit::Length).getUserString()), - QString::fromStdString(Base::Quantity(pos.z, Base::Unit::Length).getUserString())); + QString data + = QStringLiteral("[(%1 %2 %3); %4; (%5 %6 %7)]") + .arg( + loc.toString(dir.x, 'f', lowPrec), + loc.toString(dir.y, 'f', lowPrec), + loc.toString(dir.z, 'f', lowPrec), + QString::fromStdString(Base::Quantity(angle, Base::Unit::Angle).getUserString()), + QString::fromStdString(Base::Quantity(pos.x, Base::Unit::Length).getUserString()), + QString::fromStdString(Base::Quantity(pos.y, Base::Unit::Length).getUserString()), + QString::fromStdString(Base::Quantity(pos.z, Base::Unit::Length).getUserString()) + ); return data; } @@ -2848,18 +2909,30 @@ void PropertyPlacementItem::setValue(const QVariant& value) Base::Vector3d axis; double angle {}; h.getValue(axis, angle); - std::string str = fmt::format("App.Placement(" - "App.Vector({:.{}g},{:.{}g},{:.{}g})," - "App.Rotation(App.Vector({:.{}g},{:.{}g},{:.{}g}),{:.{}g}))", - pos.x, highPrec, pos.y, highPrec, pos.z, highPrec, - axis.x, highPrec, axis.y, highPrec, axis.z, highPrec, - angle, highPrec); + std::string str = fmt::format( + "App.Placement(" + "App.Vector({:.{}g},{:.{}g},{:.{}g})," + "App.Rotation(App.Vector({:.{}g},{:.{}g},{:.{}g}),{:.{}g}))", + pos.x, + highPrec, + pos.y, + highPrec, + pos.z, + highPrec, + axis.x, + highPrec, + axis.y, + highPrec, + axis.z, + highPrec, + angle, + highPrec + ); setPropertyValue(str); } -QWidget* PropertyPlacementItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyPlacementItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto pe = new PlacementEditor(this->propertyName(), parent); QObject::connect(pe, &PlacementEditor::valueChanged, method); @@ -2888,11 +2961,15 @@ QVariant PropertyPlacementItem::editorData(QWidget* editor) const void PropertyPlacementItem::propertyBound() { if (isBound()) { - m_a->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Rotation") - << App::ObjectIdentifier::String("Angle")); + m_a->bind( + App::ObjectIdentifier(getPath()) + << App::ObjectIdentifier::String("Rotation") << App::ObjectIdentifier::String("Angle") + ); - m_d->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Rotation") - << App::ObjectIdentifier::String("Axis")); + m_d->bind( + App::ObjectIdentifier(getPath()) + << App::ObjectIdentifier::String("Rotation") << App::ObjectIdentifier::String("Axis") + ); m_p->bind(App::ObjectIdentifier(getPath()) << App::ObjectIdentifier::String("Base")); } @@ -3045,11 +3122,9 @@ std::shared_ptr getEnumItems(const QStringList& commonModes) // NOLI } } else { - it = std::find_if(children->begin(), - children->end(), - [&field](const EnumItem& item) { - return item.text == field; - }); + it = std::find_if(children->begin(), children->end(), [&field](const EnumItem& item) { + return item.text == field; + }); if (it == children->end()) { it = children->emplace(children->end(), field, mode); } @@ -3104,9 +3179,11 @@ QStringList PropertyEnumItem::getCommonModes() const return commonModes; } -QWidget* PropertyEnumItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyEnumItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { QStringList commonModes = getCommonModes(); if (commonModes.isEmpty()) { @@ -3169,9 +3246,8 @@ PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyStringListItem) PropertyStringListItem::PropertyStringListItem() = default; -QWidget* PropertyStringListItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyStringListItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto le = new Gui::LabelEditor(parent); le->setAutoFillBackground(true); @@ -3210,8 +3286,8 @@ QVariant PropertyStringListItem::value(const App::Property* prop) const { assert(prop && prop->isDerivedFrom()); QStringList list; - const std::vector& value = - (static_cast(prop))->getValues(); + const std::vector& value + = (static_cast(prop))->getValues(); for (const auto& jt : value) { list << QString::fromUtf8(jt.c_str()); } @@ -3243,9 +3319,8 @@ PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyFloatListItem) PropertyFloatListItem::PropertyFloatListItem() = default; -QWidget* PropertyFloatListItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyFloatListItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto le = new Gui::LabelEditor(parent); le->setAutoFillBackground(true); @@ -3285,8 +3360,7 @@ QVariant PropertyFloatListItem::value(const App::Property* prop) const assert(prop && prop->isDerivedFrom()); QStringList list; - const std::vector& value = - static_cast(prop)->getValues(); + const std::vector& value = static_cast(prop)->getValues(); for (double jt : value) { list << QString::number(jt, 'f', decimals()); } @@ -3320,9 +3394,8 @@ PROPERTYITEM_SOURCE(Gui::PropertyEditor::PropertyIntegerListItem) PropertyIntegerListItem::PropertyIntegerListItem() = default; -QWidget* PropertyIntegerListItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyIntegerListItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto le = new Gui::LabelEditor(parent); le->setAutoFillBackground(true); @@ -3364,8 +3437,7 @@ QVariant PropertyIntegerListItem::value(const App::Property* prop) const assert(prop && prop->isDerivedFrom()); QStringList list; - const std::vector& value = - static_cast(prop)->getValues(); + const std::vector& value = static_cast(prop)->getValues(); for (long jt : value) { list << QString::number(jt); } @@ -3413,8 +3485,7 @@ QVariant PropertyColorItem::decoration(const QVariant& value) const QString PropertyColorItem::toString(const QVariant& prop) const { auto value = prop.value(); - return - QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue()); + return QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue()); } QVariant PropertyColorItem::value(const App::Property* prop) const @@ -3431,14 +3502,12 @@ void PropertyColorItem::setValue(const QVariant& value) return; } auto col = value.value(); - QString data = - QStringLiteral("(%1,%2,%3)").arg(col.red()).arg(col.green()).arg(col.blue()); + QString data = QStringLiteral("(%1,%2,%3)").arg(col.red()).arg(col.green()).arg(col.blue()); setPropertyValue(data); } -QWidget* PropertyColorItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyColorItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto cb = new Gui::ColorButton(parent); QObject::connect(cb, &Gui::ColorButton::changed, method); @@ -3505,16 +3574,14 @@ PropertyMaterialItem::PropertyMaterialItem() emissive->setPropertyName(QLatin1String("EmissiveColor")); this->appendChild(emissive); - shininess = - static_cast(PropertyIntegerConstraintItem::create()); + shininess = static_cast(PropertyIntegerConstraintItem::create()); shininess->setRange(min, max); shininess->setStepSize(steps); shininess->setParent(this); shininess->setPropertyName(QLatin1String("Shininess")); this->appendChild(shininess); - transparency = - static_cast(PropertyIntegerConstraintItem::create()); + transparency = static_cast(PropertyIntegerConstraintItem::create()); transparency->setRange(min, max); transparency->setStepSize(steps); transparency->setParent(this); @@ -3683,8 +3750,7 @@ QString PropertyMaterialItem::toString(const QVariant& prop) const // use the diffuse color auto val = prop.value(); QColor value = val.diffuseColor; - return - QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue()); + return QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue()); } QVariant PropertyMaterialItem::toolTip(const App::Property* prop) const @@ -3697,12 +3763,14 @@ QVariant PropertyMaterialItem::toolTip(const App::Property* prop) const auto sc = value.specularColor.asValue(); auto ec = value.emissiveColor.asValue(); - QString data = QStringLiteral("Diffuse color: [%1, %2, %3]\n" - "Ambient color: [%4, %5, %6]\n" - "Specular color: [%7, %8, %9]\n" - "Emissive color: [%10, %11, %12]\n" - "Shininess: %13\n" - "Transparency: %14") + QString data = QStringLiteral( + "Diffuse color: [%1, %2, %3]\n" + "Ambient color: [%4, %5, %6]\n" + "Specular color: [%7, %8, %9]\n" + "Emissive color: [%10, %11, %12]\n" + "Shininess: %13\n" + "Transparency: %14" + ) .arg(dc.red()) .arg(dc.green()) .arg(dc.blue()) @@ -3760,14 +3828,16 @@ void PropertyMaterialItem::setValue(const QVariant& value) float s = mat.shininess; float t = mat.transparency; - QString data = QStringLiteral("App.Material(" - "DiffuseColor = %1," - "AmbientColor = %2," - "SpecularColor = %3," - "EmissiveColor = %4," - "Shininess = %5," - "Transparency = %6," - ")") + QString data = QStringLiteral( + "App.Material(" + "DiffuseColor = %1," + "AmbientColor = %2," + "SpecularColor = %3," + "EmissiveColor = %4," + "Shininess = %5," + "Transparency = %6," + ")" + ) .arg(dcp) .arg(acp) .arg(scp) @@ -3778,9 +3848,8 @@ void PropertyMaterialItem::setValue(const QVariant& value) setPropertyValue(data); } -QWidget* PropertyMaterialItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyMaterialItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto cb = new Gui::ColorButton(parent); QObject::connect(cb, &Gui::ColorButton::changed, method); @@ -3842,16 +3911,14 @@ PropertyMaterialListItem::PropertyMaterialListItem() emissive->setPropertyName(QLatin1String("EmissiveColor")); this->appendChild(emissive); - shininess = - static_cast(PropertyIntegerConstraintItem::create()); + shininess = static_cast(PropertyIntegerConstraintItem::create()); shininess->setRange(min, max); shininess->setStepSize(steps); shininess->setParent(this); shininess->setPropertyName(QLatin1String("Shininess")); this->appendChild(shininess); - transparency = - static_cast(PropertyIntegerConstraintItem::create()); + transparency = static_cast(PropertyIntegerConstraintItem::create()); transparency->setRange(min, max); transparency->setStepSize(steps); transparency->setParent(this); @@ -4160,16 +4227,15 @@ QString PropertyMaterialListItem::toString(const QVariant& prop) const // use the diffuse color auto mat = list[0].value(); QColor value = mat.diffuseColor; - return - QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue()); + return QStringLiteral("[%1, %2, %3]").arg(value.red()).arg(value.green()).arg(value.blue()); } QVariant PropertyMaterialListItem::toolTip(const App::Property* prop) const { assert(prop && prop->isDerivedFrom()); - const std::vector& values = - static_cast(prop)->getValues(); + const std::vector& values + = static_cast(prop)->getValues(); if (values.empty()) { return {}; } @@ -4180,12 +4246,14 @@ QVariant PropertyMaterialListItem::toolTip(const App::Property* prop) const auto sc = value.specularColor.asValue(); auto ec = value.emissiveColor.asValue(); - QString data = QStringLiteral("Diffuse color: [%1, %2, %3]\n" - "Ambient color: [%4, %5, %6]\n" - "Specular color: [%7, %8, %9]\n" - "Emissive color: [%10, %11, %12]\n" - "Shininess: %13\n" - "Transparency: %14") + QString data = QStringLiteral( + "Diffuse color: [%1, %2, %3]\n" + "Ambient color: [%4, %5, %6]\n" + "Specular color: [%7, %8, %9]\n" + "Emissive color: [%10, %11, %12]\n" + "Shininess: %13\n" + "Transparency: %14" + ) .arg(dc.red()) .arg(dc.green()) .arg(dc.blue()) @@ -4208,8 +4276,8 @@ QVariant PropertyMaterialListItem::value(const App::Property* prop) const { assert(prop && prop->isDerivedFrom()); - const std::vector& value = - static_cast(prop)->getValues(); + const std::vector& value + = static_cast(prop)->getValues(); QVariantList variantList; for (const auto& it : value) { @@ -4262,14 +4330,16 @@ void PropertyMaterialListItem::setValue(const QVariant& value) float s = mat.shininess; float t = mat.transparency; - QString item = QStringLiteral("App.Material(" - "DiffuseColor = %1," - "AmbientColor = %2," - "SpecularColor = %3," - "EmissiveColor = %4," - "Shininess = %5," - "Transparency = %6," - ")") + QString item = QStringLiteral( + "App.Material(" + "DiffuseColor = %1," + "AmbientColor = %2," + "SpecularColor = %3," + "EmissiveColor = %4," + "Shininess = %5," + "Transparency = %6," + ")" + ) .arg(dcp) .arg(acp) .arg(scp) @@ -4281,9 +4351,8 @@ void PropertyMaterialListItem::setValue(const QVariant& value) setPropertyValue(data); } -QWidget* PropertyMaterialListItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyMaterialListItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto cb = new Gui::ColorButton(parent); QObject::connect(cb, &Gui::ColorButton::changed, method); @@ -4364,9 +4433,8 @@ QVariant PropertyFileItem::toolTip(const App::Property* prop) const return value(prop); } -QWidget* PropertyFileItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyFileItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto fc = new Gui::FileChooser(parent); fc->setAutoFillBackground(true); @@ -4419,9 +4487,8 @@ QVariant PropertyPathItem::toolTip(const App::Property* prop) const return value(prop); } -QWidget* PropertyPathItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyPathItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto fc = new Gui::FileChooser(parent); fc->setMode(FileChooser::Directory); @@ -4468,9 +4535,8 @@ QVariant PropertyTransientFileItem::toolTip(const App::Property* prop) const return value(prop); } -QWidget* PropertyTransientFileItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyTransientFileItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { auto fc = new Gui::FileChooser(parent); fc->setAutoFillBackground(true); @@ -4516,9 +4582,11 @@ void LinkSelection::select() } Gui::Selection().selStackPush(); Gui::Selection().clearSelection(); - Gui::Selection().addSelection(link.getDocumentName().c_str(), - link.getObjectName().c_str(), - link.getSubName().c_str()); + Gui::Selection().addSelection( + link.getDocumentName().c_str(), + link.getObjectName().c_str(), + link.getSubName().c_str() + ); this->deleteLater(); } @@ -4542,8 +4610,7 @@ LinkLabel::LinkLabel(QWidget* parent, const App::Property* prop) editButton = new QPushButton(QStringLiteral("…"), this); #if defined(Q_OS_MACOS) - editButton->setAttribute( - Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct + editButton->setAttribute(Qt::WA_LayoutUsesWidgetRect); // layout size from QMacStyle was not correct #endif editButton->setToolTip(tr("Changes the linked object")); layout->addWidget(editButton); @@ -4573,20 +4640,26 @@ void LinkLabel::updatePropertyLink() auto& sobj = links.front(); link = QVariant::fromValue(sobj); QString linkcolor = QApplication::palette().color(QPalette::Link).name(); - text = QStringLiteral("" - "

      " - "%5" - "

      ") - .arg(QLatin1String(sobj.getDocumentName().c_str()), - QLatin1String(sobj.getObjectName().c_str()), - QString::fromUtf8(sobj.getSubName().c_str()), - linkcolor, - DlgPropertyLink::formatObject(owner->getDocument(), - sobj.getObject(), - sobj.getSubName().c_str())); + text = QStringLiteral( + "" + "

      " + "%5" + "

      " + ) + .arg( + QLatin1String(sobj.getDocumentName().c_str()), + QLatin1String(sobj.getObjectName().c_str()), + QString::fromUtf8(sobj.getSubName().c_str()), + linkcolor, + DlgPropertyLink::formatObject( + owner->getDocument(), + sobj.getObject(), + sobj.getSubName().c_str() + ) + ); } else if (!links.empty()) { text = DlgPropertyLink::formatLinks(owner->getDocument(), links); @@ -4650,8 +4723,10 @@ QString PropertyLinkItem::toString(const QVariant& prop) const return {}; } App::DocumentObjectT owner(propertyItems[0]); - return DlgPropertyLink::formatLinks(owner.getDocument(), - qvariant_cast>(prop)); + return DlgPropertyLink::formatLinks( + owner.getDocument(), + qvariant_cast>(prop) + ); } QVariant PropertyLinkItem::data(int column, int role) const @@ -4697,9 +4772,8 @@ void PropertyLinkItem::setValue(const QVariant& value) setPropertyValue(DlgPropertyLink::linksToPython(links)); } -QWidget* PropertyLinkItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyLinkItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { if (propertyItems.empty()) { return nullptr; @@ -4733,8 +4807,7 @@ PropertyItemEditorFactory::PropertyItemEditorFactory() = default; PropertyItemEditorFactory::~PropertyItemEditorFactory() = default; -QWidget* PropertyItemEditorFactory::createEditor(int /*type*/, - QWidget* /*parent*/) const +QWidget* PropertyItemEditorFactory::createEditor(int /*type*/, QWidget* /*parent*/) const { // do not allow to create any editor widgets because we do that in subclasses of PropertyItem return nullptr; diff --git a/src/Gui/propertyeditor/PropertyItem.h b/src/Gui/propertyeditor/PropertyItem.h index 88152bd952..be5834df07 100644 --- a/src/Gui/propertyeditor/PropertyItem.h +++ b/src/Gui/propertyeditor/PropertyItem.h @@ -57,19 +57,19 @@ Q_DECLARE_METATYPE(QList) #endif -#define PROPERTYITEM_HEADER \ -public: \ - static void* create(void); \ +#define PROPERTYITEM_HEADER \ +public: \ + static void* create(void); \ static void init(void); -#define PROPERTYITEM_SOURCE(_class_) \ - void* _class_::create(void) \ - { \ - return new _class_(); \ - } \ - void _class_::init(void) \ - { \ - (void)new Gui::PropertyEditor::PropertyItemProducer<_class_>(#_class_); \ +#define PROPERTYITEM_SOURCE(_class_) \ + void* _class_::create(void) \ + { \ + return new _class_(); \ + } \ + void _class_::init(void) \ + { \ + (void)new Gui::PropertyEditor::PropertyItemProducer<_class_>(#_class_); \ } namespace Gui @@ -88,9 +88,10 @@ class PropertyItem; class PropertyModel; class PropertyEditorWidget; -enum class FrameOption : bool { - NoFrame=false, - WithFrame=true +enum class FrameOption : bool +{ + NoFrame = false, + WithFrame = true }; /** * The PropertyItemFactory provides methods for the dynamic creation of property items. @@ -135,7 +136,8 @@ class GuiExport PropertyItem: public QObject, public ExpressionBinding PROPERTYITEM_HEADER public: - enum Column { + enum Column + { NameColumn = 0, ValueColumn = 1, ColumnCount @@ -156,9 +158,11 @@ public: /** Creates the appropriate editor for this item and sets the editor to the value of * overrideValue(). */ - virtual QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const; + virtual QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const; virtual void setEditorData(QWidget* editor, const QVariant& data) const; virtual QVariant editorData(QWidget* editor) const; virtual bool isSeparator() const @@ -261,9 +265,11 @@ class GuiExport PropertyStringItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -284,9 +290,11 @@ class GuiExport PropertyFontItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -311,9 +319,11 @@ class GuiExport PropertySeparatorItem: public PropertyItem { return true; } - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; int row() const override { @@ -334,9 +344,11 @@ class GuiExport PropertyIntegerItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -358,9 +370,11 @@ class GuiExport PropertyIntegerConstraintItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -398,9 +412,11 @@ class GuiExport PropertyFloatItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -422,9 +438,11 @@ class GuiExport PropertyUnitItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -476,9 +494,11 @@ class GuiExport PropertyFloatConstraintItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -544,9 +564,11 @@ class GuiExport PropertyBoolItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -573,9 +595,11 @@ class GuiExport PropertyVectorItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -654,9 +678,11 @@ class GuiExport PropertyVectorListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -684,9 +710,11 @@ class GuiExport PropertyVectorDistanceItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -747,9 +775,11 @@ class GuiExport PropertyMatrixItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -849,9 +879,11 @@ class GuiExport PropertyRotationItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -911,9 +943,11 @@ class GuiExport PropertyPlacementItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -956,9 +990,11 @@ class GuiExport PropertyEnumItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1001,9 +1037,11 @@ class GuiExport PropertyStringListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1025,9 +1063,11 @@ class GuiExport PropertyFloatListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1049,9 +1089,11 @@ class GuiExport PropertyIntegerListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1073,9 +1115,11 @@ class GuiExport PropertyColorItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1106,9 +1150,11 @@ class GuiExport PropertyMaterialItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1159,9 +1205,11 @@ class GuiExport PropertyMaterialListItem: public PropertyItem PROPERTYITEM_HEADER // clang-format on - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1208,9 +1256,11 @@ class GuiExport PropertyFileItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1232,9 +1282,11 @@ class GuiExport PropertyPathItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1256,9 +1308,11 @@ class GuiExport PropertyTransientFileItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -1326,9 +1380,11 @@ class GuiExport PropertyLinkItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption = FrameOption::NoFrame) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption = FrameOption::NoFrame + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; diff --git a/src/Gui/propertyeditor/PropertyItemDelegate.cpp b/src/Gui/propertyeditor/PropertyItemDelegate.cpp index 02dc928911..36cf94bc60 100644 --- a/src/Gui/propertyeditor/PropertyItemDelegate.cpp +++ b/src/Gui/propertyeditor/PropertyItemDelegate.cpp @@ -21,12 +21,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -43,21 +43,26 @@ using namespace Gui::PropertyEditor; PropertyItemDelegate::PropertyItemDelegate(QObject* parent) - : QItemDelegate(parent), expressionEditor(nullptr) - , pressed(false), changed(false) -{ -} + : QItemDelegate(parent) + , expressionEditor(nullptr) + , pressed(false) + , changed(false) +{} PropertyItemDelegate::~PropertyItemDelegate() = default; -QSize PropertyItemDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const +QSize PropertyItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QSize size = QItemDelegate::sizeHint(option, index); size += QSize(0, 5); return size; } -void PropertyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const +void PropertyItemDelegate::paint( + QPainter* painter, + const QStyleOptionViewItem& opt, + const QModelIndex& index +) const { QStyleOptionViewItem option = opt; @@ -68,8 +73,9 @@ void PropertyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & QObject* par = parent(); if (par) { QVariant value = par->property("groupTextColor"); - if (value.canConvert()) + if (value.canConvert()) { color = value.value(); + } } option.palette.setColor(QPalette::Text, color); option.font.setBold(true); @@ -93,8 +99,9 @@ void PropertyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & QObject* par = parent(); if (par) { QVariant value = par->property("groupBackground"); - if (value.canConvert()) + if (value.canConvert()) { brush = value.value(); + } } painter->fillRect(option.rect, brush); } @@ -117,11 +124,13 @@ void PropertyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, option.widget); // Draw the checkbox - checkboxOption.rect = style->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxOption, option.widget); + checkboxOption.rect + = style->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxOption, option.widget); int leftSpacing = style->pixelMetric(QStyle::PM_FocusFrameHMargin, nullptr, option.widget); QRect checkboxRect = QStyle::alignedRect( - option.direction, Qt::AlignVCenter, + option.direction, + Qt::AlignVCenter, checkboxOption.rect.size(), option.rect.adjusted(leftSpacing, 0, -leftSpacing, 0) ); @@ -145,19 +154,26 @@ void PropertyItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem & QItemDelegate::paint(painter, option, index); } - QColor color = static_cast(QApplication::style()->styleHint(QStyle::SH_Table_GridLineColor, &opt, qobject_cast(parent()))); + QColor color = static_cast(QApplication::style()->styleHint( + QStyle::SH_Table_GridLineColor, + &opt, + qobject_cast(parent()) + )); painter->setPen(QPen(color)); if (index.column() == 1 || !(property && property->isSeparator())) { int right = (option.direction == Qt::LeftToRight) ? option.rect.right() : option.rect.left(); painter->drawLine(right, option.rect.y(), right, option.rect.bottom()); } - painter->drawLine(option.rect.x(), option.rect.bottom(), - option.rect.right(), option.rect.bottom()); + painter->drawLine(option.rect.x(), option.rect.bottom(), option.rect.right(), option.rect.bottom()); painter->setPen(savedPen); } -bool PropertyItemDelegate::editorEvent (QEvent * event, QAbstractItemModel* model, - const QStyleOptionViewItem& option, const QModelIndex& index) +bool PropertyItemDelegate::editorEvent( + QEvent* event, + QAbstractItemModel* model, + const QStyleOptionViewItem& option, + const QModelIndex& index +) { auto property = static_cast(index.internalPointer()); @@ -172,17 +188,17 @@ bool PropertyItemDelegate::editorEvent (QEvent * event, QAbstractItemModel* mode return QItemDelegate::editorEvent(event, model, option, index); } -bool PropertyItemDelegate::eventFilter(QObject *o, QEvent *ev) +bool PropertyItemDelegate::eventFilter(QObject* o, QEvent* ev) { if (ev->type() == QEvent::FocusIn) { - auto *comboBox = qobject_cast(o); + auto* comboBox = qobject_cast(o); if (comboBox) { auto parentEditor = qobject_cast(this->parent()); if (parentEditor && parentEditor->activeEditor == comboBox) { comboBox->showPopup(); } } - auto *checkBox = qobject_cast(o); + auto* checkBox = qobject_cast(o); if (checkBox) { auto parentEditor = qobject_cast(this->parent()); if (parentEditor && parentEditor->activeEditor == checkBox) { @@ -205,7 +221,7 @@ bool PropertyItemDelegate::eventFilter(QObject *o, QEvent *ev) } auto widget = qobject_cast(o); if (widget && parentEditor && parentEditor->activeEditor - && widget != parentEditor->activeEditor) { + && widget != parentEditor->activeEditor) { // All the attempts to ignore the focus-out event has been approved to not work // reliably because there are still cases that cannot be handled. // So, the best for now is to always ignore this event. @@ -217,11 +233,15 @@ bool PropertyItemDelegate::eventFilter(QObject *o, QEvent *ev) return QItemDelegate::eventFilter(o, ev); } -QWidget * PropertyItemDelegate::createEditor (QWidget * parent, const QStyleOptionViewItem & /*option*/, - const QModelIndex & index ) const +QWidget* PropertyItemDelegate::createEditor( + QWidget* parent, + const QStyleOptionViewItem& /*option*/, + const QModelIndex& index +) const { - if (!index.isValid()) + if (!index.isValid()) { return nullptr; + } auto childItem = static_cast(index.internalPointer()); if (!childItem || childItem->isSeparator() || childItem->isReadOnly()) { @@ -229,8 +249,9 @@ QWidget * PropertyItemDelegate::createEditor (QWidget * parent, const QStyleOpti } auto parentEditor = qobject_cast(this->parent()); - if(parentEditor) + if (parentEditor) { parentEditor->closeEditor(); + } FC_LOG("create editor " << index.row() << "," << index.column()); QWidget* editor = nullptr; @@ -243,7 +264,7 @@ QWidget * PropertyItemDelegate::createEditor (QWidget * parent, const QStyleOpti propertyEditor = editor; } else { - const auto &props = childItem->getPropertyData(); + const auto& props = childItem->getPropertyData(); if (!props.empty() && props[0]->testStatus(App::Property::UserEdit)) { editor = userEditor = childItem->createPropertyEditorWidget(parent); propertyEditor = editor; @@ -274,9 +295,7 @@ QWidget * PropertyItemDelegate::createEditor (QWidget * parent, const QStyleOpti if (editor) { const auto widgets = editor->findChildren(); for (auto w : widgets) { - if (qobject_cast(w) - || qobject_cast(w)) - { + if (qobject_cast(w) || qobject_cast(w)) { w->installEventFilter(const_cast(this)); } } @@ -292,42 +311,51 @@ void PropertyItemDelegate::valueChanged() if (propertyEditor) { Base::FlagToggler<> flag(changed); Q_EMIT commitData(propertyEditor); - if (qobject_cast(propertyEditor) - || qobject_cast(propertyEditor)) - { + if (qobject_cast(propertyEditor) || qobject_cast(propertyEditor)) { Q_EMIT closeEditor(propertyEditor); return; } } } -void PropertyItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +void PropertyItemDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { - if (!index.isValid()) + if (!index.isValid()) { return; + } QVariant data = index.data(Qt::EditRole); auto childItem = static_cast(index.internalPointer()); editor->blockSignals(true); - if (expressionEditor == editor) + if (expressionEditor == editor) { childItem->setExpressionEditorData(editor, data); - else if (userEditor == editor) + } + else if (userEditor == editor) { userEditor->setValue(PropertyItemAttorney::toString(childItem, data)); - else + } + else { childItem->setEditorData(editor, data); + } editor->blockSignals(false); return; } -void PropertyItemDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const +void PropertyItemDelegate::setModelData( + QWidget* editor, + QAbstractItemModel* model, + const QModelIndex& index +) const { - if (!index.isValid() || !changed || userEditor) + if (!index.isValid() || !changed || userEditor) { return; + } auto childItem = static_cast(index.internalPointer()); QVariant data; - if(expressionEditor == editor) + if (expressionEditor == editor) { data = childItem->expressionEditorData(editor); - else + } + else { data = childItem->editorData(editor); + } model->setData(index, data, Qt::EditRole); } diff --git a/src/Gui/propertyeditor/PropertyItemDelegate.h b/src/Gui/propertyeditor/PropertyItemDelegate.h index b8a3dfdaf5..f975e12cc3 100644 --- a/src/Gui/propertyeditor/PropertyItemDelegate.h +++ b/src/Gui/propertyeditor/PropertyItemDelegate.h @@ -28,12 +28,14 @@ #include #include -namespace Gui { -namespace PropertyEditor { +namespace Gui +{ +namespace PropertyEditor +{ class PropertyEditorWidget; -class PropertyItemDelegate : public QItemDelegate +class PropertyItemDelegate: public QItemDelegate { Q_OBJECT @@ -41,27 +43,32 @@ public: explicit PropertyItemDelegate(QObject* parent); ~PropertyItemDelegate() override; - void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const override; - QWidget * createEditor (QWidget *, const QStyleOptionViewItem&, const QModelIndex&) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex& index ) const override; - QSize sizeHint(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& opt, const QModelIndex& index) const override; + QWidget* createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const override; + void setEditorData(QWidget* editor, const QModelIndex& index) const override; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; + QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override; + bool editorEvent( + QEvent* event, + QAbstractItemModel* model, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) override; + protected: - bool eventFilter(QObject *, QEvent *) override; + bool eventFilter(QObject*, QEvent*) override; void valueChanged(); private: mutable QPointer propertyEditor; - mutable QWidget *expressionEditor; - mutable PropertyEditorWidget *userEditor = nullptr; + mutable QWidget* expressionEditor; + mutable PropertyEditorWidget* userEditor = nullptr; mutable bool pressed; bool changed; }; -} // namespace PropertyEditor -} // namespace Gui +} // namespace PropertyEditor +} // namespace Gui -#endif // PROPERTYITEMDELEGATE_H +#endif // PROPERTYITEMDELEGATE_H diff --git a/src/Gui/propertyeditor/PropertyModel.cpp b/src/Gui/propertyeditor/PropertyModel.cpp index ef3bcd6e88..1e29ca2516 100644 --- a/src/Gui/propertyeditor/PropertyModel.cpp +++ b/src/Gui/propertyeditor/PropertyModel.cpp @@ -260,8 +260,7 @@ static PropertyItem* createPropertyItem(App::Property* prop) return nullptr; } } - auto item = - static_cast(PropertyItemFactory::instance().createPropertyItem(editor)); + auto item = static_cast(PropertyItemFactory::instance().createPropertyItem(editor)); if (!item) { qWarning("No property item for type %s found\n", editor); } @@ -272,8 +271,9 @@ PropertyModel::GroupInfo& PropertyModel::getGroupInfo(App::Property* prop) { const char* group = prop->getGroup(); bool isEmpty = Base::Tools::isNullOrEmpty(group); - QString groupName = - QString::fromLatin1(isEmpty ? QT_TRANSLATE_NOOP("App::Property", "Base") : group); + QString groupName = QString::fromLatin1( + isEmpty ? QT_TRANSLATE_NOOP("App::Property", "Base") : group + ); auto res = groupItems.insert(std::make_pair(groupName, GroupInfo())); if (res.second) { @@ -454,11 +454,7 @@ void PropertyModel::insertOrMoveChildren() } else { flushChanges(); - beginMoveRows(createIndex(groupItem->row(), 0, groupItem), - oldRow, - oldRow, - midx, - row); + beginMoveRows(createIndex(groupItem->row(), 0, groupItem), oldRow, oldRow, midx, row); if (groupItem == groupInfo.groupItem) { groupInfo.groupItem->moveChild(oldRow, row); } diff --git a/src/Gui/propertyeditor/PropertyModel.h b/src/Gui/propertyeditor/PropertyModel.h index 8e2afabee9..683ce0931a 100644 --- a/src/Gui/propertyeditor/PropertyModel.h +++ b/src/Gui/propertyeditor/PropertyModel.h @@ -33,35 +33,43 @@ #include "PropertyItem.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { -namespace PropertyEditor { +namespace Gui +{ +namespace PropertyEditor +{ -class GuiExport PropertyModel : public QAbstractItemModel +class GuiExport PropertyModel: public QAbstractItemModel { Q_OBJECT public: - using PropertyList = std::vector< std::pair< std::string, std::vector > >; + using PropertyList = std::vector>>; PropertyModel(QObject* parent); ~PropertyModel() override; - QModelIndex buddy (const QModelIndex & index) const override; - int columnCount (const QModelIndex & parent = QModelIndex()) const override; - QVariant data (const QModelIndex & index, int role = Qt::DisplayRole) const override; - bool setData (const QModelIndex & idx, const QVariant & value, int role) override; - Qt::ItemFlags flags(const QModelIndex &index) const override; - QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex()) const override; - QModelIndex parent (const QModelIndex & index) const override; - int rowCount (const QModelIndex & parent = QModelIndex()) const override; - QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; - bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole) override; + QModelIndex buddy(const QModelIndex& index) const override; + int columnCount(const QModelIndex& parent = QModelIndex()) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; + bool setData(const QModelIndex& idx, const QVariant& value, int role) override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex& index) const override; + int rowCount(const QModelIndex& parent = QModelIndex()) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + bool setHeaderData( + int section, + Qt::Orientation orientation, + const QVariant& value, + int role = Qt::EditRole + ) override; void buildUp(const PropertyList& props); - bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()) override; + bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) override; void updateProperty(const App::Property&); void appendProperty(const App::Property&); @@ -79,23 +87,24 @@ private: void insertOrMoveChildren(); void removeChildren(); - struct GroupInfo { - PropertySeparatorItem *groupItem = nullptr; - std::vector children; + struct GroupInfo + { + PropertySeparatorItem* groupItem = nullptr; + std::vector children; }; - GroupInfo &getGroupInfo(App::Property *); + GroupInfo& getGroupInfo(App::Property*); void getRange(const GroupInfo&, int& first, int& last) const; private: - PropertyItem *rootItem; + PropertyItem* rootItem; - std::unordered_map > itemMap; + std::unordered_map> itemMap; std::map groupItems; }; -} //namespace PropertyEditor -} //namespace Gui +} // namespace PropertyEditor +} // namespace Gui -#endif //PROPERTYMODEL_H +#endif // PROPERTYMODEL_H diff --git a/src/Gui/resource.cpp b/src/Gui/resource.cpp index 3a142e39a5..75c1f73c23 100644 --- a/src/Gui/resource.cpp +++ b/src/Gui/resource.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ - - #include "BitmapFactory.h" #include "WidgetFactory.h" #include "Workbench.h" @@ -53,8 +51,8 @@ #include "Dialogs/DlgKeyboardImp.h" #if defined(_USE_3DCONNEXION_SDK) || defined(SPNAV_FOUND) -#include "Dialogs/DlgCustomizeSpaceball.h" -#include "Dialogs/DlgCustomizeSpNavSettings.h" +# include "Dialogs/DlgCustomizeSpaceball.h" +# include "Dialogs/DlgCustomizeSpNavSettings.h" #endif #include "InputField.h" diff --git a/src/Main/FreeCADGuiPy.cpp b/src/Main/FreeCADGuiPy.cpp index 99ca6593b7..948d18e9e6 100644 --- a/src/Main/FreeCADGuiPy.cpp +++ b/src/Main/FreeCADGuiPy.cpp @@ -24,19 +24,19 @@ #include #if HAVE_CONFIG_H -#include +# include #endif // HAVE_CONFIG_H #ifdef _MSC_VER -#pragma warning(disable : 4005) +# pragma warning(disable : 4005) #endif #include #include #if defined(Q_OS_WIN) -#include +# include #elif defined(Q_WS_X11) -#include +# include #endif #include @@ -94,8 +94,10 @@ LRESULT CALLBACK FilterProc(int nCode, WPARAM wParam, LPARAM lParam) static PyObject* FreeCADGui_showMainWindow(PyObject* /*self*/, PyObject* args) { if (_isSetupWithoutGui) { - PyErr_SetString(PyExc_RuntimeError, - "Cannot call showMainWindow() after calling setupWithoutGUI()\n"); + PyErr_SetString( + PyExc_RuntimeError, + "Cannot call showMainWindow() after calling setupWithoutGUI()\n" + ); return nullptr; } @@ -137,8 +139,7 @@ static PyObject* FreeCADGui_showMainWindow(PyObject* /*self*/, PyObject* args) static char** argv = {nullptr}; (void)new QApplication(argc, argv); #else - PyErr_SetString(PyExc_RuntimeError, - "Must construct a QApplication before a QPaintDevice\n"); + PyErr_SetString(PyExc_RuntimeError, "Must construct a QApplication before a QPaintDevice\n"); return nullptr; #endif } @@ -174,8 +175,7 @@ static PyObject* FreeCADGui_exec_loop(PyObject* /*self*/, PyObject* args) } if (!qApp) { - PyErr_SetString(PyExc_RuntimeError, - "Must construct a QApplication before a QPaintDevice\n"); + PyErr_SetString(PyExc_RuntimeError, "Must construct a QApplication before a QPaintDevice\n"); return nullptr; } else if (!qobject_cast(qApp)) { @@ -310,7 +310,8 @@ static QWidget* setupMainWindow() QIcon icon = qApp->windowIcon(); if (icon.isNull()) { qApp->setWindowIcon( - Gui::BitmapFactory().pixmap(App::Application::Config()["AppIcon"].c_str())); + Gui::BitmapFactory().pixmap(App::Application::Config()["AppIcon"].c_str()) + ); } mw->setWindowIcon(qApp->windowIcon()); @@ -347,15 +348,17 @@ PyMOD_INIT_FUNC(FreeCADGui) if (Base::Type::fromName("Gui::BaseView").isBad()) { Gui::Application::initApplication(); } - static struct PyModuleDef FreeCADGuiModuleDef = {PyModuleDef_HEAD_INIT, - "FreeCADGui", - "FreeCAD GUI module\n", - -1, - FreeCADGui_methods, - nullptr, - nullptr, - nullptr, - nullptr}; + static struct PyModuleDef FreeCADGuiModuleDef = { + PyModuleDef_HEAD_INIT, + "FreeCADGui", + "FreeCAD GUI module\n", + -1, + FreeCADGui_methods, + nullptr, + nullptr, + nullptr, + nullptr + }; PyObject* module = PyModule_Create(&FreeCADGuiModuleDef); return module; } diff --git a/src/Main/MainCmd.cpp b/src/Main/MainCmd.cpp index 8386f94e98..1f14d93c6b 100644 --- a/src/Main/MainCmd.cpp +++ b/src/Main/MainCmd.cpp @@ -25,7 +25,7 @@ #include "../FCConfig.h" #if HAVE_CONFIG_H -#include +# include #endif // HAVE_CONFIG_H #include @@ -44,9 +44,9 @@ using App::Application; using Base::Console; -const char sBanner[] = - "(C) 2001-2025 FreeCAD contributors\n" - "FreeCAD is free and open-source software licensed under the terms of LGPL2+ license.\n\n"; +const char sBanner[] + = "(C) 2001-2025 FreeCAD contributors\n" + "FreeCAD is free and open-source software licensed under the terms of LGPL2+ license.\n\n"; int main(int argc, char** argv) { diff --git a/src/Main/MainGui.cpp b/src/Main/MainGui.cpp index 7485ee12f8..9de976c904 100644 --- a/src/Main/MainGui.cpp +++ b/src/Main/MainGui.cpp @@ -25,12 +25,12 @@ #include #if defined(_MSC_VER) -#include -#include +# include +# include #endif #if HAVE_CONFIG_H -#include +# include #endif // HAVE_CONFIG_H #include @@ -52,9 +52,9 @@ void PrintInitHelp(); -const char sBanner[] = - "(C) 2001-2025 FreeCAD contributors\n" - "FreeCAD is free and open-source software licensed under the terms of LGPL2+ license.\n\n"; +const char sBanner[] + = "(C) 2001-2025 FreeCAD contributors\n" + "FreeCAD is free and open-source software licensed under the terms of LGPL2+ license.\n\n"; #if defined(_MSC_VER) void InitMiniDumpWriter(const std::string&); @@ -193,8 +193,9 @@ int main(int argc, char** argv) App::Application::Config()["CopyrightInfo"] = sBanner; App::Application::Config()["AppIcon"] = "freecad"; App::Application::Config()["SplashScreen"] = "freecadsplash"; - App::Application::Config()["AboutImage"] = - App::Application::isDevelopmentVersion() ? "freecadaboutdev" : "freecadabout"; + App::Application::Config()["AboutImage"] = App::Application::isDevelopmentVersion() + ? "freecadaboutdev" + : "freecadabout"; App::Application::Config()["StartWorkbench"] = "PartDesignWorkbench"; // App::Application::Config()["HiddenDockWindow"] = "Property editor"; App::Application::Config()["SplashAlignment"] = "Bottom|Left"; @@ -219,7 +220,8 @@ int main(int argc, char** argv) #endif // to set window icon on wayland, the desktop file has to be available to the compositor QGuiApplication::setDesktopFileName( - QString::fromStdString(App::Application::Config()["DesktopFileName"])); + QString::fromStdString(App::Application::Config()["DesktopFileName"]) + ); #if defined(_MSC_VER) // create a dump file when the application crashes @@ -227,11 +229,13 @@ int main(int argc, char** argv) dmpfile += "crash.dmp"; InitMiniDumpWriter(dmpfile); #endif - std::map::iterator it = - App::Application::Config().find("NavigationStyle"); + std::map::iterator it = App::Application::Config().find( + "NavigationStyle" + ); if (it != App::Application::Config().end()) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); // if not already defined do it now (for the very first start) std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str()); hGrp->SetASCII("NavigationStyle", style.c_str()); @@ -272,23 +276,30 @@ int main(int argc, char** argv) QApplication app(argc, argv); QString appName = QString::fromStdString(App::Application::Config()["ExeName"]); QString msg; - msg = QObject::tr("While initializing %1 the following exception occurred: '%2'\n\n" - "Python is searching for its files in the following directories:\n%3\n\n" - "Python version information:\n%4\n") - .arg(appName, - QString::fromUtf8(e.what()), - QString::fromStdString(Base::Interpreter().getPythonPath()), - QString::fromLatin1(Py_GetVersion())); + msg = QObject::tr( + "While initializing %1 the following exception occurred: '%2'\n\n" + "Python is searching for its files in the following directories:\n%3\n\n" + "Python version information:\n%4\n" + ) + .arg( + appName, + QString::fromUtf8(e.what()), + QString::fromStdString(Base::Interpreter().getPythonPath()), + QString::fromLatin1(Py_GetVersion()) + ); const char* pythonhome = getenv("PYTHONHOME"); if (pythonhome) { msg += QObject::tr("\nThe environment variable PYTHONHOME is set to '%1'.") .arg(QString::fromUtf8(pythonhome)); - msg += QObject::tr("\nSetting this environment variable might cause Python to fail. " - "Please contact your administrator to unset it on your system.\n\n"); + msg += QObject::tr( + "\nSetting this environment variable might cause Python to fail. " + "Please contact your administrator to unset it on your system.\n\n" + ); } else { msg += QObject::tr( - "\nPlease contact the application's support team for more information.\n\n"); + "\nPlease contact the application's support team for more information.\n\n" + ); } displayCritical(msg, false); @@ -298,10 +309,11 @@ int main(int argc, char** argv) // Popup an own dialog box instead of that one of Windows QApplication app(argc, argv); QString appName = QString::fromStdString(App::Application::Config()["ExeName"]); - QString msg = - QObject::tr("Unknown runtime error occurred while initializing %1.\n\n" - "Please contact the application's support team for more information.\n\n") - .arg(appName); + QString msg = QObject::tr( + "Unknown runtime error occurred while initializing %1.\n\n" + "Please contact the application's support team for more information.\n\n" + ) + .arg(appName); displayCritical(msg, false); exit(101); } @@ -348,29 +360,29 @@ int main(int argc, char** argv) // cleans up App::Application::destruct(); - Base::Console().log("%s completely terminated\n", - App::Application::Config()["ExeName"].c_str()); + Base::Console().log("%s completely terminated\n", App::Application::Config()["ExeName"].c_str()); return 0; } #if defined(_MSC_VER) -typedef BOOL(__stdcall* tMDWD)(IN HANDLE hProcess, - IN DWORD ProcessId, - IN HANDLE hFile, - IN MINIDUMP_TYPE DumpType, - IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, - OPTIONAL IN CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, - OPTIONAL IN CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam - OPTIONAL); +typedef BOOL(__stdcall* tMDWD)( + IN HANDLE hProcess, + IN DWORD ProcessId, + IN HANDLE hFile, + IN MINIDUMP_TYPE DumpType, + IN CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, + OPTIONAL IN CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, + OPTIONAL IN CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam OPTIONAL +); static tMDWD s_pMDWD; static HMODULE s_hDbgHelpMod; static MINIDUMP_TYPE s_dumpTyp = MiniDumpNormal; static std::wstring s_szMiniDumpFileName; // initialize with whatever appropriate... -#include +# include class MyStackWalker: public StackWalker { DWORD threadId; @@ -395,7 +407,7 @@ public: static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx) { -#ifdef _M_IX86 +# ifdef _M_IX86 if (pEx->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW) { // be sure that we have enough space... static char MyStack[1024 * 128]; @@ -406,7 +418,7 @@ static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx) __asm mov eax, offset MyStack[1024 * 128]; __asm mov esp, eax; } -#endif +# endif MyStackWalker sw; sw.ShowCallstack(GetCurrentThread(), pEx->ContextRecord); Base::Console().log("*** Unhandled Exception!\n"); @@ -416,26 +428,22 @@ static LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx) bool bFailed = true; HANDLE hFile; - hFile = CreateFileW(s_szMiniDumpFileName.c_str(), - GENERIC_WRITE, - 0, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); + hFile = CreateFileW( + s_szMiniDumpFileName.c_str(), + GENERIC_WRITE, + 0, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL + ); if (hFile != INVALID_HANDLE_VALUE) { MINIDUMP_EXCEPTION_INFORMATION stMDEI; stMDEI.ThreadId = GetCurrentThreadId(); stMDEI.ExceptionPointers = pEx; stMDEI.ClientPointers = true; // try to create a miniDump: - if (s_pMDWD(GetCurrentProcess(), - GetCurrentProcessId(), - hFile, - s_dumpTyp, - &stMDEI, - NULL, - NULL)) { + if (s_pMDWD(GetCurrentProcess(), GetCurrentProcessId(), hFile, s_dumpTyp, &stMDEI, NULL, NULL)) { bFailed = false; // succeeded } CloseHandle(hFile); diff --git a/src/Main/MainPy.cpp b/src/Main/MainPy.cpp index 3557b89bba..c31802f405 100644 --- a/src/Main/MainPy.cpp +++ b/src/Main/MainPy.cpp @@ -25,16 +25,16 @@ #include #if defined(FC_OS_WIN32) -#include +# include #endif #ifdef FC_OS_MACOSX -#include -#include +# include +# include #endif #if HAVE_CONFIG_H -#include +# include #endif // HAVE_CONFIG_H #include @@ -69,12 +69,12 @@ BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID /*lpReser return true; } #elif defined(FC_OS_LINUX) || defined(FC_OS_BSD) -#ifndef GNU_SOURCE -#define GNU_SOURCE -#endif -#include +# ifndef GNU_SOURCE +# define GNU_SOURCE +# endif +# include #elif defined(FC_OS_CYGWIN) -#include +# include #endif PyMOD_INIT_FUNC(FreeCAD) @@ -156,7 +156,7 @@ PyMOD_INIT_FUNC(FreeCAD) } #else -#error "Implement: Retrieve the path of the module for your platform." +# error "Implement: Retrieve the path of the module for your platform." #endif int argc = 1; std::vector argv; diff --git a/src/Mod/Assembly/App/AssemblyLink.cpp b/src/Mod/Assembly/App/AssemblyLink.cpp index 7d87e3d5cd..5fc633f29f 100644 --- a/src/Mod/Assembly/App/AssemblyLink.cpp +++ b/src/Mod/Assembly/App/AssemblyLink.cpp @@ -59,18 +59,22 @@ PROPERTY_SOURCE(Assembly::AssemblyLink, App::Part) AssemblyLink::AssemblyLink() { - ADD_PROPERTY_TYPE(Rigid, - (true), - "General", - (App::PropertyType)(App::Prop_None), - "If the sub-assembly is set to Rigid, it will act " - "as a rigid body. Else its joints will be taken into account."); + ADD_PROPERTY_TYPE( + Rigid, + (true), + "General", + (App::PropertyType)(App::Prop_None), + "If the sub-assembly is set to Rigid, it will act " + "as a rigid body. Else its joints will be taken into account." + ); - ADD_PROPERTY_TYPE(LinkedObject, - (nullptr), - "General", - (App::PropertyType)(App::Prop_None), - "The linked assembly."); + ADD_PROPERTY_TYPE( + LinkedObject, + (nullptr), + "General", + (App::PropertyType)(App::Prop_None), + "The linked assembly." + ); } AssemblyLink::~AssemblyLink() = default; @@ -105,8 +109,9 @@ void AssemblyLink::onChanged(const App::Property* prop) // If a rigid sub-assembly has an object that is grounded, we also remove it. auto groundedJoints = getParentAssembly()->getGroundedJoints(); for (auto* joint : groundedJoints) { - auto* propObj = - dynamic_cast(joint->getPropertyByName("ObjectToGround")); + auto* propObj = dynamic_cast( + joint->getPropertyByName("ObjectToGround") + ); if (!propObj) { continue; } @@ -125,8 +130,7 @@ void AssemblyLink::onChanged(const App::Property* prop) // movePlc needs to be computed before updateContents. App::DocumentObject* firstLink = nullptr; for (auto* obj : Group.getValues()) { - if (obj - && (obj->isDerivedFrom() || obj->isDerivedFrom())) { + if (obj && (obj->isDerivedFrom() || obj->isDerivedFrom())) { firstLink = obj; break; } @@ -143,9 +147,11 @@ void AssemblyLink::onChanged(const App::Property* prop) if (sourceObj) { auto* propSource = dynamic_cast( - sourceObj->getPropertyByName("Placement")); + sourceObj->getPropertyByName("Placement") + ); auto* propLink = dynamic_cast( - firstLink->getPropertyByName("Placement")); + firstLink->getPropertyByName("Placement") + ); if (propSource && propLink) { movePlc = propLink->getValue() * propSource->getValue().inverse(); @@ -179,8 +185,8 @@ void AssemblyLink::onChanged(const App::Property* prop) if (obj->isLinkGroup()) { auto* srcLink = static_cast(obj); - const std::vector srcElements = - srcLink->ElementList.getValues(); + const std::vector srcElements + = srcLink->ElementList.getValues(); for (auto elt : srcElements) { if (!elt) { @@ -188,7 +194,8 @@ void AssemblyLink::onChanged(const App::Property* prop) } auto* prop = dynamic_cast( - elt->getPropertyByName("Placement")); + elt->getPropertyByName("Placement") + ); if (prop) { prop->setValue(plc * prop->getValue()); } @@ -196,7 +203,8 @@ void AssemblyLink::onChanged(const App::Property* prop) } else { auto* prop = dynamic_cast( - obj->getPropertyByName("Placement")); + obj->getPropertyByName("Placement") + ); if (prop) { prop->setValue(plc * prop->getValue()); } @@ -278,10 +286,10 @@ void AssemblyLink::synchronizeComponents() // same number of elements. linkGroupsAdded.insert(srcLink); - const std::vector srcElements = - srcLink->ElementList.getValues(); - const std::vector newElements = - link2->ElementList.getValues(); + const std::vector srcElements + = srcLink->ElementList.getValues(); + const std::vector newElements + = link2->ElementList.getValues(); for (int i = 0; i < srcElements.size(); ++i) { objLinkMap[srcElements[i]] = newElements[i]; } @@ -309,8 +317,8 @@ void AssemblyLink::synchronizeComponents() if (obj->isDerivedFrom()) { auto* asmLink = static_cast(obj); - App::DocumentObject* newObj = - doc->addObject("Assembly::AssemblyLink", obj->getNameInDocument()); + App::DocumentObject* newObj + = doc->addObject("Assembly::AssemblyLink", obj->getNameInDocument()); auto* subAsmLink = static_cast(newObj); subAsmLink->LinkedObject.setValue(obj); subAsmLink->Rigid.setValue(asmLink->Rigid.getValue()); @@ -321,18 +329,17 @@ void AssemblyLink::synchronizeComponents() else if (obj->isDerivedFrom() && obj->isLinkGroup()) { auto* srcLink = static_cast(obj); - auto* newLink = - static_cast(doc->addObject("App::Link", obj->getNameInDocument())); + auto* newLink = static_cast( + doc->addObject("App::Link", obj->getNameInDocument()) + ); newLink->LinkedObject.setValue(srcLink->getTrueLinkedObject(false)); newLink->Label.setValue(obj->Label.getValue()); addObject(newLink); newLink->ElementCount.setValue(srcLink->ElementCount.getValue()); - const std::vector srcElements = - srcLink->ElementList.getValues(); - const std::vector newElements = - newLink->ElementList.getValues(); + const std::vector srcElements = srcLink->ElementList.getValues(); + const std::vector newElements = newLink->ElementList.getValues(); for (int i = 0; i < srcElements.size(); ++i) { auto* newObj = newElements[i]; auto* srcObj = srcElements[i]; @@ -387,9 +394,11 @@ void AssemblyLink::synchronizeComponents() namespace { template -void copyPropertyIfDifferent(App::DocumentObject* source, - App::DocumentObject* target, - const char* propertyName) +void copyPropertyIfDifferent( + App::DocumentObject* source, + App::DocumentObject* target, + const char* propertyName +) { auto sourceProp = freecad_cast(source->getPropertyByName(propertyName)); auto targetProp = freecad_cast(target->getPropertyByName(propertyName)); @@ -412,8 +421,11 @@ std::string removeUpToName(const std::string& sub, const std::string& name) return sub; } -std::string -replaceLastOccurrence(const std::string& str, const std::string& oldStr, const std::string& newStr) +std::string replaceLastOccurrence( + const std::string& str, + const std::string& oldStr, + const std::string& newStr +) { size_t pos = str.rfind(oldStr); if (pos != std::string::npos) { @@ -435,8 +447,8 @@ void AssemblyLink::synchronizeJoints() JointGroup* jGroup = ensureJointGroup(); - std::vector assemblyJoints = - assembly->getJoints(assembly->isTouched(), false, false); + std::vector assemblyJoints + = assembly->getJoints(assembly->isTouched(), false, false); std::vector assemblyLinkJoints = getJoints(); // We delete the excess of joints if any @@ -495,9 +507,11 @@ void AssemblyLink::synchronizeJoints() } -void AssemblyLink::handleJointReference(App::DocumentObject* joint, - App::DocumentObject* lJoint, - const char* refName) +void AssemblyLink::handleJointReference( + App::DocumentObject* joint, + App::DocumentObject* lJoint, + const char* refName +) { AssemblyObject* assembly = getLinkedAssembly(); diff --git a/src/Mod/Assembly/App/AssemblyLink.h b/src/Mod/Assembly/App/AssemblyLink.h index 942f67d93c..e20b69d4c7 100644 --- a/src/Mod/Assembly/App/AssemblyLink.h +++ b/src/Mod/Assembly/App/AssemblyLink.h @@ -75,9 +75,11 @@ public: void synchronizeComponents(); void synchronizeJoints(); - void handleJointReference(App::DocumentObject* joint, - App::DocumentObject* lJoint, - const char* refName); + void handleJointReference( + App::DocumentObject* joint, + App::DocumentObject* lJoint, + const char* refName + ); void ensureNoJointGroup(); JointGroup* ensureJointGroup(); std::vector getJoints(); diff --git a/src/Mod/Assembly/App/AssemblyObject.cpp b/src/Mod/Assembly/App/AssemblyObject.cpp index df25cfc044..5913f00232 100644 --- a/src/Mod/Assembly/App/AssemblyObject.cpp +++ b/src/Mod/Assembly/App/AssemblyObject.cpp @@ -129,7 +129,8 @@ App::DocumentObjectExecReturn* AssemblyObject::execute() App::DocumentObjectExecReturn* ret = App::Part::execute(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Assembly"); + "User parameter:BaseApp/Preferences/Mod/Assembly" + ); if (hGrp->GetBool("SolveOnRecompute", true)) { solve(); } @@ -305,7 +306,8 @@ void AssemblyObject::doDragStep() Base::Placement plc = getPlacementFromProp(part, "Placement"); Base::Vector3d pos = plc.getPosition(); mbdPart->updateMbDFromPosition3D( - std::make_shared>(ListD {pos.x, pos.y, pos.z})); + std::make_shared>(ListD {pos.x, pos.y, pos.z}) + ); // Update the MBD part's rotation Base::Rotation rot = plc.getRotation(); @@ -314,8 +316,7 @@ void AssemblyObject::doDragStep() Base::Vector3d r0 = mat.getRow(0); Base::Vector3d r1 = mat.getRow(1); Base::Vector3d r2 = mat.getRow(2); - mbdPart - ->updateMbDFromRotationMatrix(r0.x, r0.y, r0.z, r1.x, r1.y, r1.z, r2.x, r2.y, r2.z); + mbdPart->updateMbDFromRotationMatrix(r0.x, r0.y, r0.z, r1.x, r1.y, r1.z, r2.x, r2.y, r2.z); } // Timing mbdAssembly->runDragStep() @@ -362,8 +363,9 @@ bool AssemblyObject::validateNewPlacements() // First we check if a grounded object has moved. It can happen that they flip. auto groundedParts = getGroundedParts(); for (auto* obj : groundedParts) { - auto* propPlacement = - dynamic_cast(obj->getPropertyByName("Placement")); + auto* propPlacement = dynamic_cast( + obj->getPropertyByName("Placement") + ); if (propPlacement) { Base::Placement oldPlc = propPlacement->getValue(); @@ -378,7 +380,8 @@ bool AssemblyObject::validateNewPlacements() if (!oldPlc.isSame(newPlacement, Precision::Confusion())) { Base::Console().warning( "Assembly : Ignoring bad solve, a grounded object (%s) moved.\n", - obj->getFullLabel()); + obj->getFullLabel() + ); return false; } } @@ -432,8 +435,9 @@ void AssemblyObject::undoSolve() } // Check if the object has a "Placement" property - auto* propPlacement = - dynamic_cast(obj->getPropertyByName("Placement")); + auto* propPlacement = dynamic_cast( + obj->getPropertyByName("Placement") + ); if (!propPlacement) { continue; } @@ -475,8 +479,9 @@ void AssemblyObject::setNewPlacements() } // Check if the object has a "Placement" property - auto* propPlacement = - dynamic_cast(obj->getPropertyByName("Placement")); + auto* propPlacement = dynamic_cast( + obj->getPropertyByName("Placement") + ); if (!propPlacement) { continue; } @@ -562,7 +567,8 @@ std::shared_ptr AssemblyObject::makeMbdAssembly() assembly->setName("OndselAssembly"); ParameterGrp::handle hPgr = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Assembly"); + "User parameter:BaseApp/Preferences/Mod/Assembly" + ); assembly->setDebug(hPgr->GetBool("LogSolverDebug", false)); return assembly; @@ -571,7 +577,8 @@ std::shared_ptr AssemblyObject::makeMbdAssembly() App::DocumentObject* AssemblyObject::getJointOfPartConnectingToGround( App::DocumentObject* part, std::string& name, - const std::vector& excludeJoints) + const std::vector& excludeJoints +) { if (!part) { return nullptr; @@ -644,8 +651,7 @@ ViewGroup* AssemblyObject::getExplodedViewGroup() const return nullptr; } -std::vector -AssemblyObject::getJoints(bool updateJCS, bool delBadJoints, bool subJoints) +std::vector AssemblyObject::getJoints(bool updateJCS, bool delBadJoints, bool subJoints) { std::vector joints = {}; @@ -775,8 +781,7 @@ std::unordered_set AssemblyObject::getGroundedParts() continue; } - auto* propObj = - dynamic_cast(gJoint->getPropertyByName("ObjectToGround")); + auto* propObj = dynamic_cast(gJoint->getPropertyByName("ObjectToGround")); if (propObj) { App::DocumentObject* objToGround = propObj->getValue(); @@ -830,9 +835,7 @@ std::unordered_set AssemblyObject::fixGroundedParts() return groundedParts; } -void AssemblyObject::fixGroundedPart(App::DocumentObject* obj, - Base::Placement& plc, - std::string& name) +void AssemblyObject::fixGroundedPart(App::DocumentObject* obj, Base::Placement& plc, std::string& name) { if (!obj) { return; @@ -937,8 +940,10 @@ bool AssemblyObject::isObjInSetOfObjRefs(App::DocumentObject* obj, const std::ve return false; } -void AssemblyObject::removeUnconnectedJoints(std::vector& joints, - std::unordered_set groundedObjs) +void AssemblyObject::removeUnconnectedJoints( + std::vector& joints, + std::unordered_set groundedObjs +) { std::vector connectedParts; @@ -953,22 +958,28 @@ void AssemblyObject::removeUnconnectedJoints(std::vector& } // Filter out unconnected joints - joints.erase(std::remove_if(joints.begin(), - joints.end(), - [&](App::DocumentObject* joint) { - App::DocumentObject* obj1 = - getMovingPartFromRef(this, joint, "Reference1"); - App::DocumentObject* obj2 = - getMovingPartFromRef(this, joint, "Reference2"); - return (!isObjInSetOfObjRefs(obj1, connectedParts) - || !isObjInSetOfObjRefs(obj2, connectedParts)); - }), - joints.end()); + joints.erase( + std::remove_if( + joints.begin(), + joints.end(), + [&](App::DocumentObject* joint) { + App::DocumentObject* obj1 = getMovingPartFromRef(this, joint, "Reference1"); + App::DocumentObject* obj2 = getMovingPartFromRef(this, joint, "Reference2"); + return ( + !isObjInSetOfObjRefs(obj1, connectedParts) + || !isObjInSetOfObjRefs(obj2, connectedParts) + ); + } + ), + joints.end() + ); } -void AssemblyObject::traverseAndMarkConnectedParts(App::DocumentObject* currentObj, - std::vector& connectedParts, - const std::vector& joints) +void AssemblyObject::traverseAndMarkConnectedParts( + App::DocumentObject* currentObj, + std::vector& connectedParts, + const std::vector& joints +) { // getConnectedParts returns the objs connected to the currentObj by any joint auto connectedObjs = getConnectedParts(currentObj, joints); @@ -981,9 +992,10 @@ void AssemblyObject::traverseAndMarkConnectedParts(App::DocumentObject* currentO } } -std::vector -AssemblyObject::getConnectedParts(App::DocumentObject* part, - const std::vector& joints) +std::vector AssemblyObject::getConnectedParts( + App::DocumentObject* part, + const std::vector& joints +) { if (!part) { return {}; @@ -1004,16 +1016,14 @@ AssemblyObject::getConnectedParts(App::DocumentObject* part, } if (obj1 == part) { - auto* ref = - dynamic_cast(joint->getPropertyByName("Reference2")); + auto* ref = dynamic_cast(joint->getPropertyByName("Reference2")); if (!ref) { continue; } connectedParts.push_back({obj2, ref}); } else if (obj2 == part) { - auto* ref = - dynamic_cast(joint->getPropertyByName("Reference1")); + auto* ref = dynamic_cast(joint->getPropertyByName("Reference1")); if (!ref) { continue; } @@ -1105,8 +1115,7 @@ void Assembly::AssemblyObject::create_mbdSimulationParameters(App::DocumentObjec mbdSim->seterrorTol(valueOf(sim, "fGlobalErrorTolerance")); } -std::shared_ptr AssemblyObject::makeMbdJointOfType(App::DocumentObject* joint, - JointType type) +std::shared_ptr AssemblyObject::makeMbdJointOfType(App::DocumentObject* joint, JointType type) { switch (type) { case JointType::Fixed: @@ -1222,8 +1231,8 @@ std::shared_ptr AssemblyObject::makeMbdJointDistance(App::DocumentObj case DistanceType::CircleCircle: { auto mbdJoint = CREATE::With(); - mbdJoint->distanceIJ = - getJointDistance(joint) + getEdgeRadius(obj1, elt1) + getEdgeRadius(obj2, elt2); + mbdJoint->distanceIJ = getJointDistance(joint) + getEdgeRadius(obj1, elt1) + + getEdgeRadius(obj2, elt2); return mbdJoint; } @@ -1254,22 +1263,22 @@ std::shared_ptr AssemblyObject::makeMbdJointDistance(App::DocumentObj case DistanceType::CylinderCylinder: { auto mbdJoint = CREATE::With(); - mbdJoint->distanceIJ = - getJointDistance(joint) + getFaceRadius(obj1, elt1) + getFaceRadius(obj2, elt2); + mbdJoint->distanceIJ = getJointDistance(joint) + getFaceRadius(obj1, elt1) + + getFaceRadius(obj2, elt2); return mbdJoint; } case DistanceType::CylinderSphere: { auto mbdJoint = CREATE::With(); - mbdJoint->distanceIJ = - getJointDistance(joint) + getFaceRadius(obj1, elt1) + getFaceRadius(obj2, elt2); + mbdJoint->distanceIJ = getJointDistance(joint) + getFaceRadius(obj1, elt1) + + getFaceRadius(obj2, elt2); return mbdJoint; } case DistanceType::CylinderTorus: { auto mbdJoint = CREATE::With(); - mbdJoint->distanceIJ = - getJointDistance(joint) + getFaceRadius(obj1, elt1) + getFaceRadius(obj2, elt2); + mbdJoint->distanceIJ = getJointDistance(joint) + getFaceRadius(obj1, elt1) + + getFaceRadius(obj2, elt2); return mbdJoint; } @@ -1281,15 +1290,15 @@ std::shared_ptr AssemblyObject::makeMbdJointDistance(App::DocumentObj case DistanceType::TorusSphere: { auto mbdJoint = CREATE::With(); - mbdJoint->distanceIJ = - getJointDistance(joint) + getFaceRadius(obj1, elt1) + getFaceRadius(obj2, elt2); + mbdJoint->distanceIJ = getJointDistance(joint) + getFaceRadius(obj1, elt1) + + getFaceRadius(obj2, elt2); return mbdJoint; } case DistanceType::SphereSphere: { auto mbdJoint = CREATE::With(); - mbdJoint->distanceIJ = - getJointDistance(joint) + getFaceRadius(obj1, elt1) + getFaceRadius(obj2, elt2); + mbdJoint->distanceIJ = getJointDistance(joint) + getFaceRadius(obj1, elt1) + + getFaceRadius(obj2, elt2); return mbdJoint; } @@ -1345,8 +1354,7 @@ std::shared_ptr AssemblyObject::makeMbdJointDistance(App::DocumentObj } } -std::vector> -AssemblyObject::makeMbdJoint(App::DocumentObject* joint) +std::vector> AssemblyObject::makeMbdJoint(App::DocumentObject* joint) { if (!joint) { return {}; @@ -1378,17 +1386,16 @@ AssemblyObject::makeMbdJoint(App::DocumentObject* joint) // Add limits if needed. We do not add if this is a simulation or their might clash. if (motions.empty()) { if (jointType == JointType::Slider || jointType == JointType::Cylindrical) { - auto* pLenMin = - dynamic_cast(joint->getPropertyByName("LengthMin")); - auto* pLenMax = - dynamic_cast(joint->getPropertyByName("LengthMax")); - auto* pMinEnabled = - dynamic_cast(joint->getPropertyByName("EnableLengthMin")); - auto* pMaxEnabled = - dynamic_cast(joint->getPropertyByName("EnableLengthMax")); + auto* pLenMin = dynamic_cast(joint->getPropertyByName("LengthMin")); + auto* pLenMax = dynamic_cast(joint->getPropertyByName("LengthMax")); + auto* pMinEnabled = dynamic_cast( + joint->getPropertyByName("EnableLengthMin") + ); + auto* pMaxEnabled = dynamic_cast( + joint->getPropertyByName("EnableLengthMax") + ); - if (pLenMin && pLenMax && pMinEnabled - && pMaxEnabled) { // Make sure properties do exist + if (pLenMin && pLenMax && pMinEnabled && pMaxEnabled) { // Make sure properties do exist // Swap the values if necessary. bool minEnabled = pMinEnabled->getValue(); bool maxEnabled = pMaxEnabled->getValue(); @@ -1433,13 +1440,14 @@ AssemblyObject::makeMbdJoint(App::DocumentObject* joint) if (jointType == JointType::Revolute || jointType == JointType::Cylindrical) { auto* pRotMin = dynamic_cast(joint->getPropertyByName("AngleMin")); auto* pRotMax = dynamic_cast(joint->getPropertyByName("AngleMax")); - auto* pMinEnabled = - dynamic_cast(joint->getPropertyByName("EnableAngleMin")); - auto* pMaxEnabled = - dynamic_cast(joint->getPropertyByName("EnableAngleMax")); + auto* pMinEnabled = dynamic_cast( + joint->getPropertyByName("EnableAngleMin") + ); + auto* pMaxEnabled = dynamic_cast( + joint->getPropertyByName("EnableAngleMax") + ); - if (pRotMin && pRotMax && pMinEnabled - && pMaxEnabled) { // Make sure properties do exist + if (pRotMin && pRotMax && pMinEnabled && pMaxEnabled) { // Make sure properties do exist // Swap the values if necessary. bool minEnabled = pMinEnabled->getValue(); bool maxEnabled = pMaxEnabled->getValue(); @@ -1497,8 +1505,7 @@ AssemblyObject::makeMbdJoint(App::DocumentObject* joint) continue; } - auto* pType = - dynamic_cast(motion->getPropertyByName("MotionType")); + auto* pType = dynamic_cast(motion->getPropertyByName("MotionType")); auto* pFormula = dynamic_cast(motion->getPropertyByName("Formula")); if (!pType || !pFormula) { continue; @@ -1521,10 +1528,10 @@ AssemblyObject::makeMbdJoint(App::DocumentObject* joint) continue; } - auto* pType2 = - dynamic_cast(motion2->getPropertyByName("MotionType")); - auto* pFormula2 = - dynamic_cast(motion2->getPropertyByName("Formula")); + auto* pType2 = dynamic_cast( + motion2->getPropertyByName("MotionType") + ); + auto* pFormula2 = dynamic_cast(motion2->getPropertyByName("Formula")); if (!pType2 || !pFormula2) { continue; } @@ -1569,17 +1576,18 @@ AssemblyObject::makeMbdJoint(App::DocumentObject* joint) return {mbdJoint}; } -std::string AssemblyObject::handleOneSideOfJoint(App::DocumentObject* joint, - const char* propRefName, - const char* propPlcName) +std::string AssemblyObject::handleOneSideOfJoint( + App::DocumentObject* joint, + const char* propRefName, + const char* propPlcName +) { App::DocumentObject* part = getMovingPartFromRef(this, joint, propRefName); App::DocumentObject* obj = getObjFromRef(joint, propRefName); if (!part || !obj) { - Base::Console().warning("The property %s of Joint %s is bad.", - propRefName, - joint->getFullName()); + Base::Console() + .warning("The property %s of Joint %s is bad.", propRefName, joint->getFullName()); return ""; } @@ -1614,9 +1622,11 @@ std::string AssemblyObject::handleOneSideOfJoint(App::DocumentObject* joint, return "/OndselAssembly/" + mbdPart->name + "/" + markerName; } -void AssemblyObject::getRackPinionMarkers(App::DocumentObject* joint, - std::string& markerNameI, - std::string& markerNameJ) +void AssemblyObject::getRackPinionMarkers( + App::DocumentObject* joint, + std::string& markerNameI, + std::string& markerNameJ +) { // ASMT rack pinion joint must get the rack as I and pinion as J. // - rack marker has to have Z axis parallel to pinion Z axis. @@ -1741,8 +1751,7 @@ int AssemblyObject::slidingPartIndex(App::DocumentObject* joint) double y1, p1, r1, y2, p2, r2; plcjt.getRotation().getYawPitchRoll(y1, p1, r1); plci.getRotation().getYawPitchRoll(y2, p2, r2); - if (fabs(p1 - p2) < Precision::Confusion() - && fabs(r1 - r2) < Precision::Confusion()) { + if (fabs(p1 - p2) < Precision::Confusion() && fabs(r1 - r2) < Precision::Confusion()) { slidingFound = found; } } @@ -1767,7 +1776,8 @@ bool AssemblyObject::isMbDJointValid(App::DocumentObject* joint) Base::Console().warning( "Assembly: Ignoring joint (%s) because its parts are connected by a fixed " "joint bundle. This joint is a conflicting or redundant constraint.\n", - joint->getFullLabel()); + joint->getFullLabel() + ); return false; } return true; @@ -1828,8 +1838,7 @@ std::shared_ptr AssemblyObject::getMbDPart(App::DocumentObject* part) return getMbDData(part).part; } -std::shared_ptr -AssemblyObject::makeMbdPart(std::string& name, Base::Placement plc, double mass) +std::shared_ptr AssemblyObject::makeMbdPart(std::string& name, Base::Placement plc, double mass) { auto mbdPart = CREATE::With(); mbdPart->setName(name); @@ -1875,8 +1884,10 @@ std::shared_ptr AssemblyObject::makeMbdMarker(std::string& name, Bas return mbdMarker; } -std::vector AssemblyObject::getDownstreamParts(App::DocumentObject* part, - App::DocumentObject* joint) +std::vector AssemblyObject::getDownstreamParts( + App::DocumentObject* part, + App::DocumentObject* joint +) { if (!part) { return {}; @@ -1908,11 +1919,12 @@ std::vector AssemblyObject::getDownstreamParts(App::DocumentObject* part return downstreamParts; } -App::DocumentObject* -AssemblyObject::getUpstreamMovingPart(App::DocumentObject* part, - App::DocumentObject*& joint, - std::string& name, - std::vector excludeJoints) +App::DocumentObject* AssemblyObject::getUpstreamMovingPart( + App::DocumentObject* part, + App::DocumentObject*& joint, + std::string& name, + std::vector excludeJoints +) { if (!part || isPartGrounded(part)) { return nullptr; @@ -1956,8 +1968,9 @@ std::vector AssemblyObject::getSubAssemblies() App::Document* doc = getDocument(); - std::vector assemblies = - doc->getObjectsOfType(Assembly::AssemblyLink::getClassTypeId()); + std::vector assemblies = doc->getObjectsOfType( + Assembly::AssemblyLink::getClassTypeId() + ); for (auto assembly : assemblies) { if (hasObject(assembly)) { subAssemblies.push_back(freecad_cast(assembly)); diff --git a/src/Mod/Assembly/App/AssemblyObject.h b/src/Mod/Assembly/App/AssemblyObject.h index 2d2959c9dd..56e197fdcd 100644 --- a/src/Mod/Assembly/App/AssemblyObject.h +++ b/src/Mod/Assembly/App/AssemblyObject.h @@ -118,8 +118,11 @@ public: // Ondsel Solver interface std::shared_ptr makeMbdAssembly(); void create_mbdSimulationParameters(App::DocumentObject* sim); - std::shared_ptr - makeMbdPart(std::string& name, Base::Placement plc = Base::Placement(), double mass = 1.0); + std::shared_ptr makeMbdPart( + std::string& name, + Base::Placement plc = Base::Placement(), + double mass = 1.0 + ); std::shared_ptr getMbDPart(App::DocumentObject* obj); // To help the solver, during dragging, we are bundling parts connected by a fixed joint. // So several assembly components are bundled in a single ASMTPart. @@ -133,15 +136,18 @@ public: MbDPartData getMbDData(App::DocumentObject* part); std::shared_ptr makeMbdMarker(std::string& name, Base::Placement& plc); std::vector> makeMbdJoint(App::DocumentObject* joint); - std::shared_ptr makeMbdJointOfType(App::DocumentObject* joint, - JointType jointType); + std::shared_ptr makeMbdJointOfType(App::DocumentObject* joint, JointType jointType); std::shared_ptr makeMbdJointDistance(App::DocumentObject* joint); - std::string handleOneSideOfJoint(App::DocumentObject* joint, - const char* propRefName, - const char* propPlcName); - void getRackPinionMarkers(App::DocumentObject* joint, - std::string& markerNameI, - std::string& markerNameJ); + std::string handleOneSideOfJoint( + App::DocumentObject* joint, + const char* propRefName, + const char* propPlcName + ); + void getRackPinionMarkers( + App::DocumentObject* joint, + std::string& markerNameI, + std::string& markerNameJ + ); int slidingPartIndex(App::DocumentObject* joint); void jointParts(std::vector joints); @@ -150,15 +156,19 @@ public: template T* getGroup(); - std::vector - getJoints(bool updateJCS = true, bool delBadJoints = false, bool subJoints = true); + std::vector getJoints( + bool updateJCS = true, + bool delBadJoints = false, + bool subJoints = true + ); std::vector getGroundedJoints(); std::vector getJointsOfObj(App::DocumentObject* obj); std::vector getJointsOfPart(App::DocumentObject* part); - App::DocumentObject* - getJointOfPartConnectingToGround(App::DocumentObject* part, - std::string& name, - const std::vector& excludeJoints = {}); + App::DocumentObject* getJointOfPartConnectingToGround( + App::DocumentObject* part, + std::string& name, + const std::vector& excludeJoints = {} + ); std::unordered_set getGroundedParts(); std::unordered_set fixGroundedParts(); void fixGroundedPart(App::DocumentObject* obj, Base::Placement& plc, std::string& jointName); @@ -167,23 +177,32 @@ public: bool isJointTypeConnecting(App::DocumentObject* joint); bool isObjInSetOfObjRefs(App::DocumentObject* obj, const std::vector& pairs); - void removeUnconnectedJoints(std::vector& joints, - std::unordered_set groundedObjs); - void traverseAndMarkConnectedParts(App::DocumentObject* currentPart, - std::vector& connectedParts, - const std::vector& joints); - std::vector getConnectedParts(App::DocumentObject* part, - const std::vector& joints); + void removeUnconnectedJoints( + std::vector& joints, + std::unordered_set groundedObjs + ); + void traverseAndMarkConnectedParts( + App::DocumentObject* currentPart, + std::vector& connectedParts, + const std::vector& joints + ); + std::vector getConnectedParts( + App::DocumentObject* part, + const std::vector& joints + ); bool isPartGrounded(App::DocumentObject* part); bool isPartConnected(App::DocumentObject* part); - std::vector getDownstreamParts(App::DocumentObject* part, - App::DocumentObject* joint = nullptr); - App::DocumentObject* - getUpstreamMovingPart(App::DocumentObject* part, - App::DocumentObject*& joint, - std::string& name, - std::vector excludeJoints = {}); + std::vector getDownstreamParts( + App::DocumentObject* part, + App::DocumentObject* joint = nullptr + ); + App::DocumentObject* getUpstreamMovingPart( + App::DocumentObject* part, + App::DocumentObject*& joint, + std::string& name, + std::vector excludeJoints = {} + ); double getObjMass(App::DocumentObject* obj); void setObjMasses(std::vector> objectMasses); diff --git a/src/Mod/Assembly/App/AssemblyObjectPyImp.cpp b/src/Mod/Assembly/App/AssemblyObjectPyImp.cpp index adf27ed798..ca284bdb6f 100644 --- a/src/Mod/Assembly/App/AssemblyObjectPyImp.cpp +++ b/src/Mod/Assembly/App/AssemblyObjectPyImp.cpp @@ -205,12 +205,14 @@ PyObject* AssemblyObjectPy::getDownstreamParts(PyObject* args) const PyObject* pyJoint; // Parse the two arguments: a part object and a joint object - if (!PyArg_ParseTuple(args, - "O!O!", - &(App::DocumentObjectPy::Type), - &pyPart, - &(App::DocumentObjectPy::Type), - &pyJoint)) { + if (!PyArg_ParseTuple( + args, + "O!O!", + &(App::DocumentObjectPy::Type), + &pyPart, + &(App::DocumentObjectPy::Type), + &pyJoint + )) { return nullptr; } @@ -218,8 +220,8 @@ PyObject* AssemblyObjectPy::getDownstreamParts(PyObject* args) const auto* joint = static_cast(pyJoint)->getDocumentObjectPtr(); // Call the C++ method - std::vector downstreamParts = - this->getAssemblyObjectPtr()->getDownstreamParts(part, joint); + std::vector downstreamParts + = this->getAssemblyObjectPtr()->getDownstreamParts(part, joint); // Convert the result into a Python list of DocumentObjects Py::List ret; diff --git a/src/Mod/Assembly/App/AssemblyUtils.cpp b/src/Mod/Assembly/App/AssemblyUtils.cpp index eced34ddc2..46c0b67466 100644 --- a/src/Mod/Assembly/App/AssemblyUtils.cpp +++ b/src/Mod/Assembly/App/AssemblyUtils.cpp @@ -84,9 +84,7 @@ void swapJCS(const App::DocumentObject* joint) } } -bool isEdgeType(const App::DocumentObject* obj, - const std::string& elName, - const GeomAbs_CurveType type) +bool isEdgeType(const App::DocumentObject* obj, const std::string& elName, const GeomAbs_CurveType type) { auto* base = dynamic_cast(obj); if (!base) { @@ -102,9 +100,7 @@ bool isEdgeType(const App::DocumentObject* obj, return sf.GetType() == type; } -bool isFaceType(const App::DocumentObject* obj, - const std::string& elName, - const GeomAbs_SurfaceType type) +bool isFaceType(const App::DocumentObject* obj, const std::string& elName, const GeomAbs_SurfaceType type) { auto* base = dynamic_cast(obj); if (!base) { @@ -537,8 +533,8 @@ App::DocumentObject* getObjFromRef(const App::DocumentObject* obj, const std::st const auto isBodySubObject = [](App::DocumentObject* obj) -> bool { // PartDesign::Point + Line + Plane + CoordinateSystem // getViewProviderName instead of isDerivedFrom to avoid dependency on sketcher - const auto isDerivedFromVpSketch = - strcmp(obj->getViewProviderName(), "SketcherGui::ViewProviderSketch") == 0; + const auto isDerivedFromVpSketch + = strcmp(obj->getViewProviderName(), "SketcherGui::ViewProviderSketch") == 0; return isDerivedFromVpSketch || obj->isDerivedFrom() || obj->isDerivedFrom() || obj->isDerivedFrom(); @@ -645,9 +641,11 @@ App::DocumentObject* getLinkedObjFromRef(const App::DocumentObject* joint, const return nullptr; } -App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, - App::DocumentObject* obj, - const std::string& sub) +App::DocumentObject* getMovingPartFromRef( + const AssemblyObject* assemblyObject, + App::DocumentObject* obj, + const std::string& sub +) { if (!obj) { return nullptr; @@ -700,8 +698,10 @@ App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, return nullptr; } -App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, - App::PropertyXLinkSub* prop) +App::DocumentObject* getMovingPartFromRef( + const AssemblyObject* assemblyObject, + App::PropertyXLinkSub* prop +) { if (!prop) { return nullptr; @@ -719,9 +719,11 @@ App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, return getMovingPartFromRef(assemblyObject, obj, subs[0]); } -App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, - App::DocumentObject* joint, - const char* pName) +App::DocumentObject* getMovingPartFromRef( + const AssemblyObject* assemblyObject, + App::DocumentObject* joint, + const char* pName +) { if (!joint) { return nullptr; @@ -733,8 +735,7 @@ App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, void syncPlacements(App::DocumentObject* src, App::DocumentObject* to) { - auto* plcPropSource = - dynamic_cast(src->getPropertyByName("Placement")); + auto* plcPropSource = dynamic_cast(src->getPropertyByName("Placement")); auto* plcPropLink = dynamic_cast(to->getPropertyByName("Placement")); if (plcPropSource && plcPropLink) { diff --git a/src/Mod/Assembly/App/AssemblyUtils.h b/src/Mod/Assembly/App/AssemblyUtils.h index 5844e7b1a1..2e3b2b42ab 100644 --- a/src/Mod/Assembly/App/AssemblyUtils.h +++ b/src/Mod/Assembly/App/AssemblyUtils.h @@ -134,11 +134,16 @@ class JointGroup; AssemblyExport void swapJCS(const App::DocumentObject* joint); -AssemblyExport bool -isEdgeType(const App::DocumentObject* obj, const std::string& elName, const GeomAbs_CurveType type); -AssemblyExport bool isFaceType(const App::DocumentObject* obj, - const std::string& elName, - const GeomAbs_SurfaceType type); +AssemblyExport bool isEdgeType( + const App::DocumentObject* obj, + const std::string& elName, + const GeomAbs_CurveType type +); +AssemblyExport bool isFaceType( + const App::DocumentObject* obj, + const std::string& elName, + const GeomAbs_SurfaceType type +); AssemblyExport double getFaceRadius(const App::DocumentObject* obj, const std::string& elName); AssemblyExport double getEdgeRadius(const App::DocumentObject* obj, const std::string& elName); @@ -153,28 +158,37 @@ AssemblyExport double getJointDistance(const App::DocumentObject* joint); AssemblyExport double getJointDistance2(const App::DocumentObject* joint); AssemblyExport JointType getJointType(const App::DocumentObject* joint); AssemblyExport std::string getElementFromProp(const App::DocumentObject* obj, const char* propName); -AssemblyExport std::string getElementTypeFromProp(const App::DocumentObject* obj, - const char* propName); -AssemblyExport App::DocumentObject* getObjFromProp(const App::DocumentObject* joint, - const char* propName); -AssemblyExport App::DocumentObject* getObjFromRef(const App::DocumentObject* obj, - const std::string& sub); +AssemblyExport std::string getElementTypeFromProp(const App::DocumentObject* obj, const char* propName); +AssemblyExport App::DocumentObject* getObjFromProp( + const App::DocumentObject* joint, + const char* propName +); +AssemblyExport App::DocumentObject* getObjFromRef(const App::DocumentObject* obj, const std::string& sub); AssemblyExport App::DocumentObject* getObjFromRef(const App::PropertyXLinkSub* prop); -AssemblyExport App::DocumentObject* getObjFromRef(const App::DocumentObject* joint, - const char* propName); -AssemblyExport App::DocumentObject* getLinkedObjFromRef(const App::DocumentObject* joint, - const char* propName); -AssemblyExport App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, - App::DocumentObject* obj, - const std::string& sub); -AssemblyExport App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, - const App::PropertyXLinkSub* prop); -AssemblyExport App::DocumentObject* getMovingPartFromRef(const AssemblyObject* assemblyObject, - App::DocumentObject* joint, - const char* pName); +AssemblyExport App::DocumentObject* getObjFromRef(const App::DocumentObject* joint, const char* propName); +AssemblyExport App::DocumentObject* getLinkedObjFromRef( + const App::DocumentObject* joint, + const char* propName +); +AssemblyExport App::DocumentObject* getMovingPartFromRef( + const AssemblyObject* assemblyObject, + App::DocumentObject* obj, + const std::string& sub +); +AssemblyExport App::DocumentObject* getMovingPartFromRef( + const AssemblyObject* assemblyObject, + const App::PropertyXLinkSub* prop +); +AssemblyExport App::DocumentObject* getMovingPartFromRef( + const AssemblyObject* assemblyObject, + App::DocumentObject* joint, + const char* pName +); AssemblyExport std::vector getSubAsList(const App::PropertyXLinkSub* prop); -AssemblyExport std::vector getSubAsList(const App::DocumentObject* joint, - const char* propName); +AssemblyExport std::vector getSubAsList( + const App::DocumentObject* joint, + const char* propName +); AssemblyExport void syncPlacements(App::DocumentObject* src, App::DocumentObject* to); } // namespace Assembly diff --git a/src/Mod/Assembly/App/BomObject.cpp b/src/Mod/Assembly/App/BomObject.cpp index ca9b8c1679..e1c5790c4f 100644 --- a/src/Mod/Assembly/App/BomObject.cpp +++ b/src/Mod/Assembly/App/BomObject.cpp @@ -58,30 +58,37 @@ PROPERTY_SOURCE(Assembly::BomObject, Spreadsheet::Sheet) BomObject::BomObject() : Spreadsheet::Sheet() { - ADD_PROPERTY_TYPE(columnsNames, - ("Index"), - "Bom", - (App::PropertyType)(App::Prop_None), - "List of the columns of the Bill of Materials."); + ADD_PROPERTY_TYPE( + columnsNames, + ("Index"), + "Bom", + (App::PropertyType)(App::Prop_None), + "List of the columns of the Bill of Materials." + ); - ADD_PROPERTY_TYPE(detailSubAssemblies, - (true), - "Bom", - (App::PropertyType)(App::Prop_None), - "Detail sub-assemblies components."); + ADD_PROPERTY_TYPE( + detailSubAssemblies, + (true), + "Bom", + (App::PropertyType)(App::Prop_None), + "Detail sub-assemblies components." + ); - ADD_PROPERTY_TYPE(detailParts, - (true), - "Bom", - (App::PropertyType)(App::Prop_None), - "Detail Parts sub-components."); + ADD_PROPERTY_TYPE( + detailParts, + (true), + "Bom", + (App::PropertyType)(App::Prop_None), + "Detail Parts sub-components." + ); ADD_PROPERTY_TYPE( onlyParts, (false), "Bom", (App::PropertyType)(App::Prop_None), - "Only Part containers will be added. Solids like PartDesign Bodies will be ignored."); + "Only Part containers will be added. Solids like PartDesign Bodies will be ignored." + ); } BomObject::~BomObject() = default; @@ -157,9 +164,11 @@ void BomObject::generateBOM() } } -void BomObject::addObjectChildrenToBom(std::vector objs, - size_t& row, - std::string index) +void BomObject::addObjectChildrenToBom( + std::vector objs, + size_t& row, + std::string index +) { int quantityColIndex = getColumnIndex("Quantity"); bool hasQuantityCol = hasQuantityColumn(); diff --git a/src/Mod/Assembly/App/BomObject.h b/src/Mod/Assembly/App/BomObject.h index 7d0950830d..c1e4954323 100644 --- a/src/Mod/Assembly/App/BomObject.h +++ b/src/Mod/Assembly/App/BomObject.h @@ -77,8 +77,7 @@ public: void generateBOM(); void addObjectToBom(App::DocumentObject* obj, size_t row, std::string index); - void - addObjectChildrenToBom(std::vector objs, size_t& row, std::string index); + void addObjectChildrenToBom(std::vector objs, size_t& row, std::string index); void saveCustomColumnData(); AssemblyObject* getAssembly(); diff --git a/src/Mod/Assembly/AssemblyGlobal.h b/src/Mod/Assembly/AssemblyGlobal.h index 34be7d45e2..d4d2f7967b 100644 --- a/src/Mod/Assembly/AssemblyGlobal.h +++ b/src/Mod/Assembly/AssemblyGlobal.h @@ -24,25 +24,25 @@ #include #ifndef ASSEMBLY_GLOBAL_H -#define ASSEMBLY_GLOBAL_H +# define ASSEMBLY_GLOBAL_H // Assembly -#ifndef AssemblyExport -#ifdef Assembly_EXPORTS -#define AssemblyExport FREECAD_DECL_EXPORT -#else -#define AssemblyExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef AssemblyExport +# ifdef Assembly_EXPORTS +# define AssemblyExport FREECAD_DECL_EXPORT +# else +# define AssemblyExport FREECAD_DECL_IMPORT +# endif +# endif // AssemblyGui -#ifndef AssemblyGuiExport -#ifdef AssemblyGui_EXPORTS -#define AssemblyGuiExport FREECAD_DECL_EXPORT -#else -#define AssemblyGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef AssemblyGuiExport +# ifdef AssemblyGui_EXPORTS +# define AssemblyGuiExport FREECAD_DECL_EXPORT +# else +# define AssemblyGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // ASSEMBLY_GLOBAL_H diff --git a/src/Mod/Assembly/Gui/TaskAssemblyMessages.cpp b/src/Mod/Assembly/Gui/TaskAssemblyMessages.cpp index 7fd12654ba..418cbb1084 100644 --- a/src/Mod/Assembly/Gui/TaskAssemblyMessages.cpp +++ b/src/Mod/Assembly/Gui/TaskAssemblyMessages.cpp @@ -40,7 +40,8 @@ TaskAssemblyMessages::TaskAssemblyMessages(ViewProviderAssembly* vp) { // NOLINTBEGIN connectionSetUp = vp->signalSetUp.connect( - std::bind(&TaskAssemblyMessages::slotSetUp, this, sp::_1, sp::_2, sp::_3, sp::_4)); + std::bind(&TaskAssemblyMessages::slotSetUp, this, sp::_1, sp::_2, sp::_3, sp::_4) + ); // NOLINTEND } @@ -58,8 +59,10 @@ void TaskAssemblyMessages::updateToolTip(const QString& link) setLinkTooltip(tr("Click to select these redundant joints.")); } else if (link == QStringLiteral("#dofs")) { - setLinkTooltip(tr("The assembly has unconstrained components giving rise to those " - "Degrees Of Freedom. Click to select these unconstrained components.")); + setLinkTooltip( + tr("The assembly has unconstrained components giving rise to those " + "Degrees Of Freedom. Click to select these unconstrained components.") + ); } else if (link == QStringLiteral("#malformed")) { setLinkTooltip(tr("Click to select these malformed joints.")); diff --git a/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp b/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp index ce6db14f4d..57907cfe94 100644 --- a/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp +++ b/src/Mod/Assembly/Gui/ViewProviderAssembly.cpp @@ -99,7 +99,8 @@ void printPlacement(Base::Placement plc, const char* name) axis.x, axis.y, axis.z, - angle); + angle + ); } PROPERTY_SOURCE(AssemblyGui::ViewProviderAssembly, Gui::ViewProviderPart) @@ -118,7 +119,8 @@ ViewProviderAssembly::ViewProviderAssembly() , docsToMove({}) { m_preTransactionConn = App::GetApplication().signalBeforeOpenTransaction.connect( - std::bind(&ViewProviderAssembly::slotAboutToOpenTransaction, this, std::placeholders::_1)); + std::bind(&ViewProviderAssembly::slotAboutToOpenTransaction, this, std::placeholders::_1) + ); } ViewProviderAssembly::~ViewProviderAssembly() @@ -138,9 +140,7 @@ void ViewProviderAssembly::setupContextMenu(QMenu* menu, QObject* receiver, cons QAction* act = menu->addAction(QObject::tr("Active object")); act->setCheckable(true); act->setChecked(isActivePart()); - func->trigger(act, [this]() { - this->doubleClicked(); - }); + func->trigger(act, [this]() { this->doubleClicked(); }); ViewProviderDragger::setupContextMenu(menu, receiver, member); // NOLINT } @@ -175,8 +175,7 @@ bool ViewProviderAssembly::canDragObject(App::DocumentObject* obj) const return obj && !obj->is(); } -bool ViewProviderAssembly::canDragObjectToTarget(App::DocumentObject* obj, - App::DocumentObject* target) const +bool ViewProviderAssembly::canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const { // If a solid is removed from the assembly, its joints need to be removed. bool prompted = false; @@ -206,7 +205,8 @@ bool ViewProviderAssembly::canDragObjectToTarget(App::DocumentObject* obj, QMessageBox msgBox(Gui::getMainWindow()); msgBox.setText(tr("The object is associated to one or more joints.")); msgBox.setInformativeText( - tr("Do you want to move the object and delete associated joints?")); + tr("Do you want to move the object and delete associated joints?") + ); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); @@ -215,9 +215,11 @@ bool ViewProviderAssembly::canDragObjectToTarget(App::DocumentObject* obj, return false; } } - Gui::Command::doCommand(Gui::Command::Gui, - "App.activeDocument().removeObject('%s')", - joint->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Gui, + "App.activeDocument().removeObject('%s')", + joint->getNameInDocument() + ); } } return true; @@ -276,13 +278,15 @@ bool ViewProviderAssembly::setEdit(int mode) getDocument()->setEditRestore(true); // Set the part as 'Activated' ie bold in the tree. - Gui::Command::doCommand(Gui::Command::Gui, - "appDoc = App.getDocument('%s')\n" - "Gui.getDocument(appDoc).ActiveView.setActiveObject('%s', " - "appDoc.getObject('%s'))", - this->getObject()->getDocument()->getName(), - PARTKEY, - this->getObject()->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Gui, + "appDoc = App.getDocument('%s')\n" + "Gui.getDocument(appDoc).ActiveView.setActiveObject('%s', " + "appDoc.getObject('%s'))", + this->getObject()->getDocument()->getName(), + PARTKEY, + this->getObject()->getNameInDocument() + ); setDragger(); @@ -297,7 +301,8 @@ bool ViewProviderAssembly::setEdit(int mode) auto* assembly = getObject(); connectSolverUpdate = assembly->signalSolverUpdate.connect( - boost::bind(&ViewProviderAssembly::UpdateSolverInformation, this)); + boost::bind(&ViewProviderAssembly::UpdateSolverInformation, this) + ); return true; } @@ -321,11 +326,13 @@ void ViewProviderAssembly::unsetEdit(int mode) } // Set the part as not 'Activated' ie not bold in the tree. - Gui::Command::doCommand(Gui::Command::Gui, - "appDoc = App.getDocument('%s')\n" - "Gui.getDocument(appDoc).ActiveView.setActiveObject('%s', None)", - this->getObject()->getDocument()->getName(), - PARTKEY); + Gui::Command::doCommand( + Gui::Command::Gui, + "appDoc = App.getDocument('%s')\n" + "Gui.getDocument(appDoc).ActiveView.setActiveObject('%s', None)", + this->getObject()->getDocument()->getName(), + PARTKEY + ); Gui::TaskView::TaskView* taskView = Gui::Control().taskPanel(); if (taskView) { @@ -345,9 +352,11 @@ void ViewProviderAssembly::setDragger() // Create the dragger coin object assert(!asmDragger); asmDragger = new Gui::SoTransformDragger(); - asmDragger->setAxisColors(Gui::ViewParams::instance()->getAxisXColor(), - Gui::ViewParams::instance()->getAxisYColor(), - Gui::ViewParams::instance()->getAxisZColor()); + asmDragger->setAxisColors( + Gui::ViewParams::instance()->getAxisXColor(), + Gui::ViewParams::instance()->getAxisYColor(), + Gui::ViewParams::instance()->getAxisZColor() + ); asmDragger->draggerSize.setValue(Gui::ViewParams::instance()->getDraggerScale()); asmDraggerSwitch = new SoSwitch(SO_SWITCH_NONE); @@ -399,7 +408,8 @@ bool ViewProviderAssembly::keyPressed(bool pressed, int key) } ParameterGrp::handle hPgr = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Assembly"); + "User parameter:BaseApp/Preferences/Mod/Assembly" + ); return !hPgr->GetBool("LeaveEditWithEscape", true); } @@ -474,20 +484,22 @@ bool ViewProviderAssembly::tryMouseMove(const SbVec2s& cursorPos, Gui::View3DInv for (auto& objToMove : docsToMove) { App::DocumentObject* obj = objToMove.obj; - auto* propPlacement = - dynamic_cast(obj->getPropertyByName("Placement")); + auto* propPlacement = dynamic_cast( + obj->getPropertyByName("Placement") + ); if (propPlacement) { Base::Placement plc = objToMove.plc; if (dragMode == DragMode::RotationOnPlane) { Base::Vector3d center = jcsGlobalPlc.getPosition(); - Base::Vector3d norm = - jcsGlobalPlc.getRotation().multVec(Base::Vector3d(0., 0., -1.)); - double angle = - (newPosRot - center).GetAngleOriented(initialPositionRot - center, norm); + Base::Vector3d norm = jcsGlobalPlc.getRotation().multVec( + Base::Vector3d(0., 0., -1.) + ); + double angle + = (newPosRot - center).GetAngleOriented(initialPositionRot - center, norm); Base::Rotation zRotation = Base::Rotation(Base::Vector3d(0., 0., 1.), angle); - Base::Placement rotatedGlovalJcsPlc = - jcsGlobalPlc * Base::Placement(Base::Vector3d(), zRotation); + Base::Placement rotatedGlovalJcsPlc = jcsGlobalPlc + * Base::Placement(Base::Vector3d(), zRotation); Base::Placement jcsPlcRelativeToPart = plc.inverse() * jcsGlobalPlc; plc = rotatedGlovalJcsPlc * jcsPlcRelativeToPart.inverse(); } @@ -500,21 +512,23 @@ bool ViewProviderAssembly::tryMouseMove(const SbVec2s& cursorPos, Gui::View3DInv plc.setPosition(pos); Base::Placement newJcsGlobalPlc = jcsGlobalPlc; - newJcsGlobalPlc.setPosition(jcsGlobalPlc.getPosition() - + (newPos - initialPosition)); + newJcsGlobalPlc.setPosition( + jcsGlobalPlc.getPosition() + (newPos - initialPosition) + ); Base::Vector3d center = newJcsGlobalPlc.getPosition(); - Base::Vector3d norm = - newJcsGlobalPlc.getRotation().multVec(Base::Vector3d(0., 0., -1.)); + Base::Vector3d norm = newJcsGlobalPlc.getRotation().multVec( + Base::Vector3d(0., 0., -1.) + ); - Base::Vector3d projInitialPositionRot = - initialPositionRot.ProjectToPlane(newJcsGlobalPlc.getPosition(), norm); + Base::Vector3d projInitialPositionRot + = initialPositionRot.ProjectToPlane(newJcsGlobalPlc.getPosition(), norm); boost::ignore_unused(projInitialPositionRot); - double angle = - (newPosRot - center).GetAngleOriented(initialPositionRot - center, norm); + double angle + = (newPosRot - center).GetAngleOriented(initialPositionRot - center, norm); Base::Rotation zRotation = Base::Rotation(Base::Vector3d(0., 0., 1.), angle); - Base::Placement rotatedGlovalJcsPlc = - newJcsGlobalPlc * Base::Placement(Base::Vector3d(), zRotation); + Base::Placement rotatedGlovalJcsPlc = newJcsGlobalPlc + * Base::Placement(Base::Vector3d(), zRotation); Base::Placement jcsPlcRelativeToPart = plc.inverse() * newJcsGlobalPlc; plc = rotatedGlovalJcsPlc * jcsPlcRelativeToPart.inverse(); } @@ -536,7 +550,8 @@ bool ViewProviderAssembly::tryMouseMove(const SbVec2s& cursorPos, Gui::View3DInv auto* assemblyPart = getObject(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Assembly"); + "User parameter:BaseApp/Preferences/Mod/Assembly" + ); bool solveOnMove = hGrp->GetBool("SolveOnMove", true); if (solveOnMove && dragMode != DragMode::TranslationNoSolve) { assemblyPart->doDragStep(); @@ -548,10 +563,12 @@ bool ViewProviderAssembly::tryMouseMove(const SbVec2s& cursorPos, Gui::View3DInv return false; } -bool ViewProviderAssembly::mouseButtonPressed(int Button, - bool pressed, - const SbVec2s& cursorPos, - const Gui::View3DInventorViewer* viewer) +bool ViewProviderAssembly::mouseButtonPressed( + int Button, + bool pressed, + const SbVec2s& cursorPos, + const Gui::View3DInventorViewer* viewer +) { Q_UNUSED(cursorPos); Q_UNUSED(viewer); @@ -565,9 +582,8 @@ bool ViewProviderAssembly::mouseButtonPressed(int Button, if (pressed && !getDraggerVisibility()) { // Check for double-click auto now = std::chrono::steady_clock::now(); - long nowMillis = - std::chrono::duration_cast(now.time_since_epoch()) - .count(); + long nowMillis + = std::chrono::duration_cast(now.time_since_epoch()).count(); if (nowMillis - lastClickTime < 500) { auto* joint = getSelectedJoint(); if (joint) { @@ -578,9 +594,7 @@ bool ViewProviderAssembly::mouseButtonPressed(int Button, // singleShot timer to make sure this happens after the release of the click. // Else the release will trigger a removeSelection of what // doubleClickedIn3dView adds to the selection. - QTimer::singleShot(50, [this]() { - doubleClickedIn3dView(); - }); + QTimer::singleShot(50, [this]() { doubleClickedIn3dView(); }); return true; } } @@ -651,8 +665,7 @@ bool ViewProviderAssembly::canDragObjectIn3d(App::DocumentObject* obj) const return false; } - auto* propPlacement = - dynamic_cast(obj->getPropertyByName("Placement")); + auto* propPlacement = dynamic_cast(obj->getPropertyByName("Placement")); if (!propPlacement) { return false; } @@ -677,8 +690,7 @@ App::DocumentObject* ViewProviderAssembly::getSelectedJoint() if (sel.size() == 1) { // Handle double click only if only one obj selected. App::DocumentObject* obj = sel[0].getObject(); if (obj) { - auto* prop = - dynamic_cast(obj->getPropertyByName("EnableLengthMin")); + auto* prop = dynamic_cast(obj->getPropertyByName("EnableLengthMin")); if (prop) { return obj; } @@ -703,9 +715,11 @@ bool ViewProviderAssembly::getSelectedObjectsWithinAssembly(bool addPreselection } if (!moveOnlyPreselected) { - for (auto& selObj : Gui::Selection().getSelectionEx("", - App::DocumentObject::getClassTypeId(), - Gui::ResolveMode::NoResolve)) { + for (auto& selObj : Gui::Selection().getSelectionEx( + "", + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::NoResolve + )) { // getSubNames() returns ["Body001.Pad.Face14", "Body002.Pad.Face7"] // if you have several objects within the same assembly selected. @@ -751,8 +765,7 @@ bool ViewProviderAssembly::getSelectedObjectsWithinAssembly(bool addPreselection } if (!alreadyIn) { - auto* pPlc = - dynamic_cast(obj->getPropertyByName("Placement")); + auto* pPlc = dynamic_cast(obj->getPropertyByName("Placement")); if (!ctrlPressed && !moveOnlyPreselected) { Gui::Selection().clearSelection(); docsToMove.clear(); @@ -766,10 +779,12 @@ bool ViewProviderAssembly::getSelectedObjectsWithinAssembly(bool addPreselection return !docsToMove.empty(); } -void ViewProviderAssembly::collectMovableObjects(App::DocumentObject* selRoot, - const std::string& subNamePrefix, - App::DocumentObject* currentObject, - bool onlySolids) +void ViewProviderAssembly::collectMovableObjects( + App::DocumentObject* selRoot, + const std::string& subNamePrefix, + App::DocumentObject* currentObject, + bool onlySolids +) { // Get the AssemblyObject for context auto* assemblyPart = getObject(); @@ -785,8 +800,7 @@ void ViewProviderAssembly::collectMovableObjects(App::DocumentObject* selRoot, auto* link = static_cast(child); std::vector elts = link->ElementList.getValues(); for (auto* elt : elts) { - std::string eltSubNamePrefix = - newSubNamePrefix + elt->getNameInDocument() + "."; + std::string eltSubNamePrefix = newSubNamePrefix + elt->getNameInDocument() + "."; collectMovableObjects(selRoot, eltSubNamePrefix, elt, onlySolids); } } @@ -799,10 +813,11 @@ void ViewProviderAssembly::collectMovableObjects(App::DocumentObject* selRoot, // Base case: This is not a flexible link, process it as a potential movable part. if (onlySolids - && !(currentObject->isDerivedFrom() - || currentObject->isDerivedFrom() - || currentObject->isDerivedFrom() - || currentObject->isDerivedFrom())) { + && !( + currentObject->isDerivedFrom() || currentObject->isDerivedFrom() + || currentObject->isDerivedFrom() + || currentObject->isDerivedFrom() + )) { return; } @@ -823,8 +838,9 @@ ViewProviderAssembly::DragMode ViewProviderAssembly::findDragMode() if (!partRef.obj) { continue; } - auto* pPlc = - dynamic_cast(partRef.obj->getPropertyByName("Placement")); + auto* pPlc = dynamic_cast( + partRef.obj->getPropertyByName("Placement") + ); if (pPlc) { App::DocumentObject* selRoot = partRef.ref->getValue(); if (!selRoot) { @@ -849,8 +865,8 @@ ViewProviderAssembly::DragMode ViewProviderAssembly::findDragMode() // In this case the user is moving an object that is not grounded // Then we want to also move other parts that may be connected to it. // In particular for case of flexible subassemblies or it looks really weird - std::vector connectedParts = - assemblyPart->getDownstreamParts(docsToMove[0].obj, movingJoint); + std::vector connectedParts + = assemblyPart->getDownstreamParts(docsToMove[0].obj, movingJoint); addPartsToMove(connectedParts); return DragMode::TranslationNoSolve; @@ -863,8 +879,7 @@ ViewProviderAssembly::DragMode ViewProviderAssembly::findDragMode() // actually move A movingJoint = nullptr; // reinitialize because getUpstreamMovingPart will call // getJointOfPartConnectingToGround again which will find the same joint. - auto* upPart = - assemblyPart->getUpstreamMovingPart(docsToMove[0].obj, movingJoint, pName); + auto* upPart = assemblyPart->getUpstreamMovingPart(docsToMove[0].obj, movingJoint, pName); if (!movingJoint) { return DragMode::Translation; } @@ -873,11 +888,11 @@ ViewProviderAssembly::DragMode ViewProviderAssembly::findDragMode() return DragMode::None; } - auto* pPlc = - dynamic_cast(upPart->getPropertyByName("Placement")); + auto* pPlc = dynamic_cast(upPart->getPropertyByName("Placement")); if (pPlc) { auto* ref = dynamic_cast( - movingJoint->getPropertyByName(pName.c_str())); + movingJoint->getPropertyByName(pName.c_str()) + ); App::DocumentObject* selRoot = ref->getValue(); if (!selRoot) { @@ -900,8 +915,7 @@ ViewProviderAssembly::DragMode ViewProviderAssembly::findDragMode() jcsPlc = App::GeoFeature::getPlacementFromProp(movingJoint, plcPropName); // Make jcsGlobalPlc relative to the origin of the doc - auto* ref = - dynamic_cast(movingJoint->getPropertyByName(pName.c_str())); + auto* ref = dynamic_cast(movingJoint->getPropertyByName(pName.c_str())); if (!ref) { return DragMode::Translation; } @@ -910,8 +924,8 @@ ViewProviderAssembly::DragMode ViewProviderAssembly::findDragMode() jcsGlobalPlc = global_plc * jcsPlc; // Add downstream parts so that they move together - std::vector downstreamParts = - assemblyPart->getDownstreamParts(docsToMove[0].obj, movingJoint); + std::vector downstreamParts + = assemblyPart->getDownstreamParts(docsToMove[0].obj, movingJoint); addPartsToMove(downstreamParts); if (jointType == JointType::Revolute) { @@ -1017,7 +1031,8 @@ void ViewProviderAssembly::tryInitMove(const SbVec2s& cursorPos, Gui::View3DInve viewer->setSelectionEnabled(false); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Assembly"); + "User parameter:BaseApp/Preferences/Mod/Assembly" + ); bool solveOnMove = hGrp->GetBool("SolveOnMove", true); if (solveOnMove && dragMode != DragMode::TranslationNoSolve) { objectMasses.clear(); @@ -1061,7 +1076,8 @@ void ViewProviderAssembly::endMove() } ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Assembly"); + "User parameter:BaseApp/Preferences/Mod/Assembly" + ); bool solveOnMove = hGrp->GetBool("SolveOnMove", true); if (solveOnMove) { assemblyPart->postDrag(); @@ -1080,8 +1096,8 @@ void ViewProviderAssembly::initMoveDragger() // find the placement for the dragger. App::DocumentObject* part = docsToMove[0].obj; - draggerInitPlc = - App::GeoFeature::getGlobalPlacement(part, docsToMove[0].rootObj, docsToMove[0].sub); + draggerInitPlc + = App::GeoFeature::getGlobalPlacement(part, docsToMove[0].rootObj, docsToMove[0].sub); std::vector listOfObjs; std::vector listOfRefs; for (auto& movingObj : docsToMove) { @@ -1112,8 +1128,7 @@ void ViewProviderAssembly::draggerMotionCallback(void* data, SoDragger* d) Base::Placement movePlc = draggerPlc * sudoThis->draggerInitPlc.inverse(); // Transform the global delta `movePlc` in case the assembly is transformed. - Base::Placement asmPlc = - App::GeoFeature::getGlobalPlacement(sudoThis->getObject()); + Base::Placement asmPlc = App::GeoFeature::getGlobalPlacement(sudoThis->getObject()); if (!asmPlc.isIdentity()) { movePlc = asmPlc.inverse() * movePlc * asmPlc; } @@ -1180,13 +1195,15 @@ bool ViewProviderAssembly::onDelete(const std::vector& subNames) || obj->is()) { // Delete the group content first. - Gui::Command::doCommand(Gui::Command::Doc, - "doc = App.getDocument(\"%s\")\n" - "objName = \"%s\"\n" - "doc.getObject(objName).removeObjectsFromDocument()\n" - "doc.removeObject(objName)\n", - obj->getDocument()->getName(), - obj->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Doc, + "doc = App.getDocument(\"%s\")\n" + "objName = \"%s\"\n" + "doc.getObject(objName).removeObjectsFromDocument()\n" + "doc.removeObject(objName)\n", + obj->getDocument()->getName(), + obj->getNameInDocument() + ); } } @@ -1204,8 +1221,8 @@ bool ViewProviderAssembly::canDelete(App::DocumentObject* objBeingDeleted) const std::vector objsBeingDeleted; objsBeingDeleted.push_back(objBeingDeleted); - auto addSubComponents = - std::function&)> {}; + auto addSubComponents + = std::function&)> {}; addSubComponents = [&](AssemblyLink* asmLink, std::vector& objs) { std::vector assemblyLinkGroup = asmLink->Group.getValues(); for (auto* obj : assemblyLinkGroup) { @@ -1257,10 +1274,12 @@ bool ViewProviderAssembly::canDelete(App::DocumentObject* objBeingDeleted) const // Deletes them. for (auto* joint : objToDel) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.getDocument(\"%s\").removeObject(\"%s\")", - joint->getDocument()->getName(), - joint->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument(\"%s\").removeObject(\"%s\")", + joint->getDocument()->getName(), + joint->getNameInDocument() + ); } } return res; @@ -1287,8 +1306,10 @@ void ViewProviderAssembly::setDraggerPlacement(Base::Placement plc) Base::Placement ViewProviderAssembly::getDraggerPlacement() { - return {Base::convertTo(asmDragger->translation.getValue()), - Base::convertTo(asmDragger->rotation.getValue())}; + return { + Base::convertTo(asmDragger->translation.getValue()), + Base::convertTo(asmDragger->rotation.getValue()) + }; } Gui::SoTransformDragger* ViewProviderAssembly::getDragger() @@ -1305,10 +1326,12 @@ PyObject* ViewProviderAssembly::getPyObject() return pyViewObject; } -void ViewProviderAssembly::applyIsolationRecursively(App::DocumentObject* current, - std::set& isolateSet, - IsolateMode mode, - std::set& visited) +void ViewProviderAssembly::applyIsolationRecursively( + App::DocumentObject* current, + std::set& isolateSet, + IsolateMode mode, + std::set& visited +) { if (!current || !visited.insert(current).second) { return; // Object is null or already processed @@ -1392,7 +1415,8 @@ void ViewProviderAssembly::applyIsolationRecursively(App::DocumentObject* curren if (child->isDerivedFrom() && child->getLinkedObject() == current) { // In this case we need to reverse isolate this! auto* childVp = freecad_cast( - Gui::Application::Instance->getViewProvider(child)); + Gui::Application::Instance->getViewProvider(child) + ); // we give the child the color the current had before we changed it childVp->OverrideMaterial.setValue(true); @@ -1403,8 +1427,7 @@ void ViewProviderAssembly::applyIsolationRecursively(App::DocumentObject* curren } } -void ViewProviderAssembly::isolateComponents(std::set& isolateSet, - IsolateMode mode) +void ViewProviderAssembly::isolateComponents(std::set& isolateSet, IsolateMode mode) { if (!stateBackup.empty()) { clearIsolate(); @@ -1462,13 +1485,15 @@ void ViewProviderAssembly::clearIsolate() component->Visibility.setValue(state.visibility); if (auto* vpl = dynamic_cast( - Gui::Application::Instance->getViewProvider(component))) { + Gui::Application::Instance->getViewProvider(component) + )) { vpl->Selectable.setValue(state.selectable); vpl->ShapeMaterial.setValue(state.shapeMaterial); vpl->OverrideMaterial.setValue(state.overrideMaterial); } else if (auto* vpg = dynamic_cast( - Gui::Application::Instance->getViewProvider(component))) { + Gui::Application::Instance->getViewProvider(component) + )) { vpg->Selectable.setValue(state.selectable); vpg->ShapeAppearance.setValue(state.shapeMaterial); } @@ -1484,15 +1509,13 @@ void ViewProviderAssembly::slotAboutToOpenTransaction(const std::string& cmdName } // UTILS -Base::Vector3d -ViewProviderAssembly::getCenterOfBoundingBox(const std::vector& movingObjs) +Base::Vector3d ViewProviderAssembly::getCenterOfBoundingBox(const std::vector& movingObjs) { int count = 0; Base::Vector3d center; // feujhzef for (auto& movingObj : movingObjs) { - Gui::ViewProvider* viewProvider = - Gui::Application::Instance->getViewProvider(movingObj.obj); + Gui::ViewProvider* viewProvider = Gui::Application::Instance->getViewProvider(movingObj.obj); if (!viewProvider) { continue; } @@ -1510,8 +1533,8 @@ ViewProviderAssembly::getCenterOfBoundingBox(const std::vector& mo Base::Placement objPlc = App::GeoFeature::getPlacementFromProp(movingObj.obj, "Placement"); plc = objPlc.inverse() * plc; // Change plc to be relative to the origin of the document. - Base::Placement global_plc = - App::GeoFeature::getGlobalPlacement(movingObj.obj, movingObj.rootObj, movingObj.sub); + Base::Placement global_plc + = App::GeoFeature::getGlobalPlacement(movingObj.obj, movingObj.rootObj, movingObj.sub); plc = global_plc * plc; bboxCenter = plc.getPosition(); @@ -1565,47 +1588,54 @@ void ViewProviderAssembly::UpdateSolverInformation() signalSetUp(QStringLiteral("empty"), tr("Empty Assembly"), QString(), QString()); } else if (dofs < 0 || hasConflicts) { // over-constrained - signalSetUp(QStringLiteral("conflicting_constraints"), - tr("Over-constrained:") + QLatin1String(" "), - QStringLiteral("#conflicting"), - QStringLiteral("(%1)").arg(intListHelper(assembly->getLastConflicting()))); + signalSetUp( + QStringLiteral("conflicting_constraints"), + tr("Over-constrained:") + QLatin1String(" "), + QStringLiteral("#conflicting"), + QStringLiteral("(%1)").arg(intListHelper(assembly->getLastConflicting())) + ); } else if (hasMalformed) { // malformed joints signalSetUp( QStringLiteral("malformed_constraints"), tr("Malformed joints:") + QLatin1String(" "), QStringLiteral("#malformed"), - QStringLiteral("(%1)").arg(intListHelper(assembly->getLastMalformedConstraints()))); + QStringLiteral("(%1)").arg(intListHelper(assembly->getLastMalformedConstraints())) + ); } else if (hasRedundancies) { - signalSetUp(QStringLiteral("redundant_constraints"), - tr("Redundant joints:") + QLatin1String(" "), - QStringLiteral("#redundant"), - QStringLiteral("(%1)").arg(intListHelper(assembly->getLastRedundant()))); + signalSetUp( + QStringLiteral("redundant_constraints"), + tr("Redundant joints:") + QLatin1String(" "), + QStringLiteral("#redundant"), + QStringLiteral("(%1)").arg(intListHelper(assembly->getLastRedundant())) + ); } else if (hasPartiallyRedundant) { signalSetUp( QStringLiteral("partially_redundant_constraints"), tr("Partially redundant:") + QLatin1String(" "), QStringLiteral("#partiallyredundant"), - QStringLiteral("(%1)").arg(intListHelper(assembly->getLastPartiallyRedundant()))); + QStringLiteral("(%1)").arg(intListHelper(assembly->getLastPartiallyRedundant())) + ); } else if (assembly->getLastSolverStatus() != 0) { - signalSetUp(QStringLiteral("solver_failed"), - tr("Solver failed to converge"), - QStringLiteral(""), - QStringLiteral("")); + signalSetUp( + QStringLiteral("solver_failed"), + tr("Solver failed to converge"), + QStringLiteral(""), + QStringLiteral("") + ); } else if (dofs > 0) { - signalSetUp(QStringLiteral("under_constrained"), - tr("Under-constrained:") + QLatin1String(" "), - QStringLiteral("#dofs"), - tr("%n Degrees of Freedom", "", dofs)); + signalSetUp( + QStringLiteral("under_constrained"), + tr("Under-constrained:") + QLatin1String(" "), + QStringLiteral("#dofs"), + tr("%n Degrees of Freedom", "", dofs) + ); } else { - signalSetUp(QStringLiteral("fully_constrained"), - tr("Fully constrained"), - QString(), - QString()); + signalSetUp(QStringLiteral("fully_constrained"), tr("Fully constrained"), QString(), QString()); } } diff --git a/src/Mod/Assembly/Gui/ViewProviderAssembly.h b/src/Mod/Assembly/Gui/ViewProviderAssembly.h index 66a707da36..76a2dabdd4 100644 --- a/src/Mod/Assembly/Gui/ViewProviderAssembly.h +++ b/src/Mod/Assembly/Gui/ViewProviderAssembly.h @@ -56,10 +56,12 @@ struct MovingObject const std::string sub; // sub name given by the selection. // Constructor - MovingObject(App::DocumentObject* o, - const Base::Placement& p, - App::DocumentObject* ro, - const std::string& s) + MovingObject( + App::DocumentObject* o, + const Base::Placement& p, + App::DocumentObject* ro, + const std::string& s + ) : obj(o) , plc(p) , ref(nullptr) @@ -132,8 +134,7 @@ public: } bool canDragObject(App::DocumentObject*) const override; - bool canDragObjectToTarget(App::DocumentObject* obj, - App::DocumentObject* target) const override; + bool canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const override; App::DocumentObject* getActivePart() const; @@ -143,10 +144,12 @@ public: /// is called when the provider is in edit and the mouse is moved bool mouseMove(const SbVec2s& cursorPos, Gui::View3DInventorViewer* viewer) 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 mouseButtonPressed( + int Button, + bool pressed, + const SbVec2s& cursorPos, + const Gui::View3DInventorViewer* viewer + ) override; // Function to handle double click event void doubleClickedIn3dView(); @@ -212,8 +215,7 @@ public: void UpdateSolverInformation(); void isolateComponents(std::set& parts, IsolateMode mode); - void isolateJointReferences(App::DocumentObject* joint, - IsolateMode mode = IsolateMode::Transparent); + void isolateJointReferences(App::DocumentObject* joint, IsolateMode mode = IsolateMode::Transparent); void clearIsolate(); DragMode dragMode; @@ -253,10 +255,12 @@ private: bool tryMouseMove(const SbVec2s& cursorPos, Gui::View3DInventorViewer* viewer); void tryInitMove(const SbVec2s& cursorPos, Gui::View3DInventorViewer* viewer); - void collectMovableObjects(App::DocumentObject* selRoot, - const std::string& subNamePrefix, - App::DocumentObject* currentObject, - bool onlySolids); + void collectMovableObjects( + App::DocumentObject* selRoot, + const std::string& subNamePrefix, + App::DocumentObject* currentObject, + bool onlySolids + ); void slotAboutToOpenTransaction(const std::string& cmdName); @@ -273,10 +277,12 @@ private: App::DocumentObject* isolatedJoint {nullptr}; bool isolatedJointVisibilityBackup {false}; - void applyIsolationRecursively(App::DocumentObject* current, - std::set& isolateSet, - IsolateMode mode, - std::set& visited); + void applyIsolationRecursively( + App::DocumentObject* current, + std::set& isolateSet, + IsolateMode mode, + std::set& visited + ); TaskAssemblyMessages* taskSolver; boost::signals2::connection connectSolverUpdate; diff --git a/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp b/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp index becbf84f56..bfcf15de01 100644 --- a/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp +++ b/src/Mod/Assembly/Gui/ViewProviderAssemblyLink.cpp @@ -74,8 +74,7 @@ bool ViewProviderAssemblyLink::setEdit(int mode) auto* assemblyLink = dynamic_cast(getObject()); if (!assemblyLink->isRigid() && mode == (int)ViewProvider::Transform) { - Base::Console().userTranslatedNotification( - "Flexible sub-assemblies cannot be transformed."); + Base::Console().userTranslatedNotification("Flexible sub-assemblies cannot be transformed."); return true; } @@ -91,8 +90,9 @@ bool ViewProviderAssemblyLink::doubleClicked() } auto* assembly = link->getLinkedAssembly(); - auto* vpa = - freecad_cast(Gui::Application::Instance->getViewProvider(assembly)); + auto* vpa = freecad_cast( + Gui::Application::Instance->getViewProvider(assembly) + ); if (!vpa) { return true; } @@ -104,10 +104,12 @@ bool ViewProviderAssemblyLink::onDelete(const std::vector& subNames { Q_UNUSED(subNames) - Gui::Command::doCommand(Gui::Command::Doc, - "App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()", - getObject()->getDocument()->getName(), - getObject()->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument(\"%s\").getObject(\"%s\").removeObjectsFromDocument()", + getObject()->getDocument()->getName(), + getObject()->getNameInDocument() + ); // getObject()->purgeTouched(); @@ -121,21 +123,25 @@ void ViewProviderAssemblyLink::setupContextMenu(QMenu* menu, QObject* receiver, auto* assemblyLink = dynamic_cast(getObject()); if (assemblyLink->isRigid()) { act = menu->addAction(QObject::tr("Turn flexible")); - act->setToolTip(QObject::tr( - "Your sub-assembly is currently rigid. This will make it flexible instead.")); + act->setToolTip( + QObject::tr("Your sub-assembly is currently rigid. This will make it flexible instead.") + ); } else { act = menu->addAction(QObject::tr("Turn rigid")); - act->setToolTip(QObject::tr( - "Your sub-assembly is currently flexible. This will make it rigid instead.")); + act->setToolTip( + QObject::tr("Your sub-assembly is currently flexible. This will make it rigid instead.") + ); } func->trigger(act, [this]() { auto* assemblyLink = dynamic_cast(getObject()); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Toggle Rigid")); - Gui::cmdAppObjectArgs(assemblyLink, - "Rigid = %s", - assemblyLink->Rigid.getValue() ? "False" : "True"); + Gui::cmdAppObjectArgs( + assemblyLink, + "Rigid = %s", + assemblyLink->Rigid.getValue() ? "False" : "True" + ); Gui::Command::commitCommand(); Gui::Selection().clearSelection(); diff --git a/src/Mod/CAM/App/AppPathPy.cpp b/src/Mod/CAM/App/AppPathPy.cpp index a032a332f1..eaaf027a1d 100644 --- a/src/Mod/CAM/App/AppPathPy.cpp +++ b/src/Mod/CAM/App/AppPathPy.cpp @@ -49,44 +49,44 @@ #include "FeaturePath.h" -#define PATH_CATCH \ - catch (Standard_Failure & e) \ - { \ - std::string str; \ - Standard_CString msg = e.GetMessageString(); \ - str += typeid(e).name(); \ - str += " "; \ - if (msg) { \ - str += msg; \ - } \ - else { \ - str += "No OCCT Exception Message"; \ - } \ - Base::Console().error(str.c_str()); \ - PyErr_SetString(Part::PartExceptionOCCError, str.c_str()); \ - } \ - catch (Base::Exception & e) \ - { \ - std::string str; \ - str += "FreeCAD exception thrown ("; \ - str += e.what(); \ - str += ")"; \ - e.reportException(); \ - PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); \ - } \ - catch (std::exception & e) \ - { \ - std::string str; \ - str += "STL exception thrown ("; \ - str += e.what(); \ - str += ")"; \ - Base::Console().error(str.c_str()); \ - PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); \ - } \ - catch (const char* e) \ - { \ - PyErr_SetString(Base::PyExc_FC_GeneralError, e); \ - } \ +#define PATH_CATCH \ + catch (Standard_Failure & e) \ + { \ + std::string str; \ + Standard_CString msg = e.GetMessageString(); \ + str += typeid(e).name(); \ + str += " "; \ + if (msg) { \ + str += msg; \ + } \ + else { \ + str += "No OCCT Exception Message"; \ + } \ + Base::Console().error(str.c_str()); \ + PyErr_SetString(Part::PartExceptionOCCError, str.c_str()); \ + } \ + catch (Base::Exception & e) \ + { \ + std::string str; \ + str += "FreeCAD exception thrown ("; \ + str += e.what(); \ + str += ")"; \ + e.reportException(); \ + PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); \ + } \ + catch (std::exception & e) \ + { \ + std::string str; \ + str += "STL exception thrown ("; \ + str += e.what(); \ + str += ")"; \ + Base::Console().error(str.c_str()); \ + PyErr_SetString(Base::PyExc_FC_GeneralError, str.c_str()); \ + } \ + catch (const char* e) \ + { \ + PyErr_SetString(Base::PyExc_FC_GeneralError, e); \ + } \ throw Py::Exception(); namespace PathApp @@ -111,49 +111,60 @@ public: Module() : Py::ExtensionModule("PathApp") { - add_varargs_method("write", - &Module::write, - "write(object,filename): Exports a given path object to a GCode file"); + add_varargs_method( + "write", + &Module::write, + "write(object,filename): Exports a given path object to a GCode file" + ); add_varargs_method( "read", &Module::read, - "read(filename,[document]): Imports a GCode file into the given document"); - add_varargs_method("show", - &Module::show, - "show(path,[string]): Add the path to the active document or create one " - "if no document exists"); - add_varargs_method("fromShape", - &Module::fromShape, - "fromShape(Shape): Returns a Path object from a Part Shape (deprecated " - "- use fromShapes() instead)"); + "read(filename,[document]): Imports a GCode file into the given document" + ); + add_varargs_method( + "show", + &Module::show, + "show(path,[string]): Add the path to the active document or create one " + "if no document exists" + ); + add_varargs_method( + "fromShape", + &Module::fromShape, + "fromShape(Shape): Returns a Path object from a Part Shape (deprecated " + "- use fromShapes() instead)" + ); add_keyword_method( "fromShapes", &Module::fromShapes, "fromShapes(shapes, start=Vector(), return_end=False" PARAM_PY_ARGS_DOC( ARG, - AREA_PARAMS_PATH) ")\n" - "\nReturns a Path object from a list of shapes\n" - "\n* shapes: input list of shapes.\n" - "\n* start (Vector()): feed start position, and also serves as a " - "hint of path entry.\n" - "\n* return_end (False): if True, returns tuple (path, " - "endPosition).\n" PARAM_PY_DOC(ARG, AREA_PARAMS_PATH)); + AREA_PARAMS_PATH + ) ")\n" + "\nReturns a Path object from a list of shapes\n" + "\n* shapes: input list of shapes.\n" + "\n* start (Vector()): feed start position, and also serves as a " + "hint of path entry.\n" + "\n* return_end (False): if True, returns tuple (path, " + "endPosition).\n" PARAM_PY_DOC(ARG, AREA_PARAMS_PATH) + ); add_keyword_method( "sortWires", &Module::sortWires, "sortWires(shapes, start=Vector(), " PARAM_PY_ARGS_DOC(ARG, AREA_PARAMS_ARC_PLANE) PARAM_PY_ARGS_DOC( ARG, - AREA_PARAMS_SORT) ")\n" - "\nReturns (wires,end), where 'wires' is sorted across Z " - "value and with optimized travel distance,\n" - "and 'end' is the ending position of the whole wires. If " - "arc_plane==1, it returns (wires,end,arc_plane),\n" - "where arc_plane is the found plane if any, or unchanged.\n" - "\n* shapes: input shape list\n" - "\n* start (Vector()): optional start " - "position.\n" PARAM_PY_DOC(ARG, AREA_PARAMS_ARC_PLANE) - PARAM_PY_DOC(ARG, AREA_PARAMS_SORT)); + AREA_PARAMS_SORT + ) ")\n" + "\nReturns (wires,end), where 'wires' is sorted across Z " + "value and with optimized travel distance,\n" + "and 'end' is the ending position of the whole wires. If " + "arc_plane==1, it returns (wires,end,arc_plane),\n" + "where arc_plane is the found plane if any, or unchanged.\n" + "\n* shapes: input shape list\n" + "\n* start (Vector()): optional start " + "position.\n" PARAM_PY_DOC(ARG, AREA_PARAMS_ARC_PLANE) + PARAM_PY_DOC(ARG, AREA_PARAMS_SORT) + ); initialize("This module is the Path module."); // register with Python PyModule_AddObject(m_module, "Voronoi", voronoi.module().ptr()); @@ -175,8 +186,8 @@ private: Base::FileInfo file(EncodedName.c_str()); if (PyObject_TypeCheck(pObj, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = - static_cast(pObj)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(pObj)->getDocumentObjectPtr(); if (obj->isDerivedFrom()) { const Path::Toolpath& path = static_cast(obj)->Path.getValue(); std::string gcode = path.toGCode(); @@ -368,24 +379,26 @@ private: "start", "return_end", PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_PATH), - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|O!O!" PARAM_PY_KWDS(AREA_PARAMS_PATH), - kwd_list, - &pShapes, - &(Base::VectorPy::Type), - &start, - &PyBool_Type, - &return_end, - PARAM_REF(PARAM_FARG, AREA_PARAMS_PATH))) { + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O|O!O!" PARAM_PY_KWDS(AREA_PARAMS_PATH), + kwd_list, + &pShapes, + &(Base::VectorPy::Type), + &start, + &PyBool_Type, + &return_end, + PARAM_REF(PARAM_FARG, AREA_PARAMS_PATH) + )) { throw Py::Exception(); } std::list shapes; if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type))) { - shapes.push_back( - static_cast(pShapes)->getTopoShapePtr()->getShape()); + shapes.push_back(static_cast(pShapes)->getTopoShapePtr()->getShape()); } else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) || PyObject_TypeCheck(pShapes, &(PyTuple_Type))) { @@ -396,8 +409,7 @@ private: PyErr_SetString(PyExc_TypeError, "non-shape object in sequence"); throw Py::Exception(); } - shapes.push_back( - static_cast(item)->getTopoShapePtr()->getShape()); + shapes.push_back(static_cast(item)->getTopoShapePtr()->getShape()); } } @@ -410,11 +422,13 @@ private: try { gp_Pnt pend; std::unique_ptr path(new Path::Toolpath); - Path::Area::toPath(*path, - shapes, - start ? &pstart : nullptr, - &pend, - PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_PATH)); + Path::Area::toPath( + *path, + shapes, + start ? &pstart : nullptr, + &pend, + PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_PATH) + ); if (!Base::asBoolean(return_end)) { return Py::asObject(new Path::PathPy(path.release())); } @@ -422,7 +436,8 @@ private: tuple.setItem(0, Py::asObject(new Path::PathPy(path.release()))); tuple.setItem( 1, - Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(), pend.Y(), pend.Z())))); + Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(), pend.Y(), pend.Z()))) + ); return tuple; } PATH_CATCH @@ -439,24 +454,25 @@ private: "start", PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_ARC_PLANE), PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_SORT), - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|O!" PARAM_PY_KWDS(AREA_PARAMS_ARC_PLANE) - PARAM_PY_KWDS(AREA_PARAMS_SORT), - kwd_list, - &pShapes, - &(Base::VectorPy::Type), - &start, - PARAM_REF(PARAM_FARG, AREA_PARAMS_ARC_PLANE), - PARAM_REF(PARAM_FARG, AREA_PARAMS_SORT))) { + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O|O!" PARAM_PY_KWDS(AREA_PARAMS_ARC_PLANE) PARAM_PY_KWDS(AREA_PARAMS_SORT), + kwd_list, + &pShapes, + &(Base::VectorPy::Type), + &start, + PARAM_REF(PARAM_FARG, AREA_PARAMS_ARC_PLANE), + PARAM_REF(PARAM_FARG, AREA_PARAMS_SORT) + )) { throw Py::Exception(); } std::list shapes; if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type))) { - shapes.push_back( - static_cast(pShapes)->getTopoShapePtr()->getShape()); + shapes.push_back(static_cast(pShapes)->getTopoShapePtr()->getShape()); } else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) || PyObject_TypeCheck(pShapes, &(PyTuple_Type))) { @@ -467,8 +483,7 @@ private: PyErr_SetString(PyExc_TypeError, "non-shape object in sequence"); throw Py::Exception(); } - shapes.push_back( - static_cast(item)->getTopoShapePtr()->getShape()); + shapes.push_back(static_cast(item)->getTopoShapePtr()->getShape()); } } @@ -480,14 +495,15 @@ private: try { bool need_arc_plane = arc_plane == Path::Area::ArcPlaneAuto; - std::list wires = - Path::Area::sortWires(shapes, - start != nullptr, - &pstart, - &pend, - nullptr, - &arc_plane, - PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_SORT)); + std::list wires = Path::Area::sortWires( + shapes, + start != nullptr, + &pstart, + &pend, + nullptr, + &arc_plane, + PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_SORT) + ); Py::List list; for (auto& wire : wires) { list.append(Part::shape2pyshape(TopoDS::Wire(wire))); @@ -497,7 +513,8 @@ private: ret.setItem(0, list); ret.setItem( 1, - Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(), pend.Y(), pend.Z())))); + Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(), pend.Y(), pend.Z()))) + ); if (need_arc_plane) { ret.setItem(2, Py::Long(arc_plane)); } diff --git a/src/Mod/CAM/App/Area.cpp b/src/Mod/CAM/App/Area.cpp index bb17d87a9a..4bff07f0e0 100644 --- a/src/Mod/CAM/App/Area.cpp +++ b/src/Mod/CAM/App/Area.cpp @@ -83,8 +83,8 @@ // FIXME: ISO C++11 requires at least one argument for the "..." in a variadic macro #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif @@ -93,15 +93,7 @@ namespace bgi = boost::geometry::index; using RParameters = bgi::linear<16>; -BOOST_GEOMETRY_REGISTER_POINT_3D_GET_SET(gp_Pnt, - double, - bg::cs::cartesian, - X, - Y, - Z, - SetX, - SetY, - SetZ) +BOOST_GEOMETRY_REGISTER_POINT_3D_GET_SET(gp_Pnt, double, bg::cs::cartesian, X, Y, Z, SetX, SetY, SetZ) #define AREA_LOG FC_LOG #define AREA_WARN FC_WARN @@ -111,11 +103,11 @@ BOOST_GEOMETRY_REGISTER_POINT_3D_GET_SET(gp_Pnt, #define AREA_XY AREA_XY #ifdef FC_DEBUG -#define AREA_DBG FC_WARN +# define AREA_DBG FC_WARN #else -#define AREA_DBG(...) \ - do { \ - } while (0) +# define AREA_DBG(...) \ + do { \ + } while (0) #endif FC_LOG_LEVEL_INIT("Path.Area", true, true) @@ -133,7 +125,7 @@ AreaParams::AreaParams() void AreaParams::dump(const char* msg) const { -#define AREA_PARAM_PRINT(_param) \ +#define AREA_PARAM_PRINT(_param) \ ss << PARAM_FNAME_STR(_param) << " = " << PARAM_FNAME(_param) << '\n'; if (FC_LOG_INSTANCE.level() > FC_LOGLEVEL_TRACE) { @@ -146,8 +138,8 @@ void AreaParams::dump(const char* msg) const CAreaConfig::CAreaConfig(const CAreaParams& p, bool noFitArcs) { -#define AREA_CONF_SAVE_AND_APPLY(_param) \ - PARAM_FNAME(_param) = BOOST_PP_CAT(CArea::get_, PARAM_FARG(_param))(); \ +#define AREA_CONF_SAVE_AND_APPLY(_param) \ + PARAM_FNAME(_param) = BOOST_PP_CAT(CArea::get_, PARAM_FARG(_param))(); \ BOOST_PP_CAT(CArea::set_, PARAM_FARG(_param))(p.PARAM_FNAME(_param)); PARAM_FOREACH(AREA_CONF_SAVE_AND_APPLY, AREA_PARAMS_CAREA); @@ -161,7 +153,7 @@ CAreaConfig::CAreaConfig(const CAreaParams& p, bool noFitArcs) CAreaConfig::~CAreaConfig() { -#define AREA_CONF_RESTORE(_param) \ +#define AREA_CONF_RESTORE(_param) \ BOOST_PP_CAT(CArea::set_, PARAM_FARG(_param))(PARAM_FNAME(_param)); PARAM_FOREACH(AREA_CONF_RESTORE, AREA_PARAMS_CAREA); @@ -278,20 +270,20 @@ bool Area::isCoplanar(const TopoDS_Shape& s1, const TopoDS_Shape& s2) if (!getShapePlane(s1, pln1) || !getShapePlane(s2, pln2)) { return false; } - return pln1.Position().IsCoplanar(pln2.Position(), - Precision::Confusion(), - Precision::Confusion()); + return pln1.Position().IsCoplanar(pln2.Position(), Precision::Confusion(), Precision::Confusion()); } -int Area::addShape(CArea& area, - const TopoDS_Shape& shape, - const gp_Trsf* trsf, - double deflection, - const TopoDS_Shape* plane, - bool force_coplanar, - CArea* areaOpen, - bool to_edges, - bool reorient) +int Area::addShape( + CArea& area, + const TopoDS_Shape& shape, + const gp_Trsf* trsf, + double deflection, + const TopoDS_Shape* plane, + bool force_coplanar, + CArea* areaOpen, + bool to_edges, + bool reorient +) { bool haveShape = false; int skipped = 0; @@ -330,11 +322,13 @@ int Area::addShape(CArea& area, } else if (to_edges) { for (TopExp_Explorer it(wire, TopAbs_EDGE); it.More(); it.Next()) { - addWire(_areaOpen, - BRepBuilderAPI_MakeWire(TopoDS::Edge(it.Current())).Wire(), - trsf, - deflection, - true); + addWire( + _areaOpen, + BRepBuilderAPI_MakeWire(TopoDS::Edge(it.Current())).Wire(), + trsf, + deflection, + true + ); } } else { @@ -408,11 +402,7 @@ static std::vector discretize(const TopoDS_Edge& edge, double deflection return ret; } -void Area::addWire(CArea& area, - const TopoDS_Wire& wire, - const gp_Trsf* trsf, - double deflection, - bool to_edges) +void Area::addWire(CArea& area, const TopoDS_Wire& wire, const gp_Trsf* trsf, double deflection, bool to_edges) { CCurve ccurve; BRepTools_WireExplorer xp(trsf ? TopoDS::Wire(wire.Moved(TopLoc_Location(*trsf))) : wire); @@ -456,7 +446,8 @@ void Area::addWire(CArea& area, // can't handle full circle? gp_Pnt mid = curve.Value((last - first) * 0.5 + first); ccurve.append( - CVertex(type, Point(mid.X(), mid.Y()), Point(center.X(), center.Y()))); + CVertex(type, Point(mid.X(), mid.Y()), Point(center.X(), center.Y())) + ); } ccurve.append(CVertex(type, Point(p.X(), p.Y()), Point(center.X(), center.Y()))); if (to_edges) { @@ -614,31 +605,37 @@ public: return result; } - void g0(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) override + void g0( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ) override { (void)id; (void)pts; line(last, next); } - void g1(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) override + void g1( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ) override { (void)id; (void)pts; line(last, next); } - void g23(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const Base::Vector3d& center) override + void g23( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const Base::Vector3d& center + ) override { (void)id; (void)center; @@ -655,12 +652,14 @@ public: pathSegments.append(curve); } - void g8x(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const std::deque& plist, - const std::deque& qlist) override + void g8x( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const std::deque& plist, + const std::deque& qlist + ) override { // (peck) drilling (void)id; @@ -684,8 +683,12 @@ public: } }; -std::shared_ptr -Area::getClearedArea(const Toolpath* path, double diameter, double zmax, Base::BoundBox3d bbox) +std::shared_ptr Area::getClearedArea( + const Toolpath* path, + double diameter, + double zmax, + Base::BoundBox3d bbox +) { build(); @@ -695,8 +698,7 @@ Area::getClearedArea(const Toolpath* path, double diameter, double zmax, Base::B // target area offset in and back out Oversize cleared areas by buffer to smooth out imprecision // in arc/segment conversion. getRestArea() will compensate for this AreaParams params = myParams; - params.Accuracy = - myParams.Accuracy * .7 / 4; // 2.3 already encoded in gcode; 4 * .7/4 = 3 total + params.Accuracy = myParams.Accuracy * .7 / 4; // 2.3 already encoded in gcode; 4 * .7/4 = 3 total params.SubjectFill = ClipperLib::pftNonZero; params.ClipFill = ClipperLib::pftNonZero; const double buffer = myParams.Accuracy * 3; @@ -726,8 +728,7 @@ Area::getClearedArea(const Toolpath* path, double diameter, double zmax, Base::B return clearedArea; } -std::shared_ptr Area::getRestArea(std::vector> clearedAreas, - double diameter) +std::shared_ptr Area::getRestArea(std::vector> clearedAreas, double diameter) { build(); #define AREA_MY(_param) myParams.PARAM_FNAME(_param) @@ -740,8 +741,7 @@ std::shared_ptr Area::getRestArea(std::vector> clear // target area offset in and back out Cleared area representations are oversized by buffer to // smooth out imprecision in arc/segment conversion. getRestArea() will compensate for this AreaParams params = myParams; - params.Accuracy = - myParams.Accuracy * .7 / 4; // 2.3 already encoded in gcode; 4 * .7/4 = 3 total + params.Accuracy = myParams.Accuracy * .7 / 4; // 2.3 already encoded in gcode; 4 * .7/4 = 3 total const double buffer = myParams.Accuracy * 3; const double roundPrecision = params.Accuracy; @@ -751,42 +751,40 @@ std::shared_ptr Area::getRestArea(std::vector> clear for (std::shared_ptr clearedArea : clearedAreas) { gp_Trsf trsf = clearedArea->myTrsf; trsf.Invert(); - trsf.SetTranslationPart(gp_Vec { - trsf.TranslationPart().X(), - trsf.TranslationPart().Y(), - -myTrsf.TranslationPart() - .Z()}); // discard z-height of cleared workplane, set to myWorkPlane's height + trsf.SetTranslationPart( + gp_Vec { + trsf.TranslationPart().X(), + trsf.TranslationPart().Y(), + -myTrsf.TranslationPart().Z() + } + ); // discard z-height of cleared workplane, set to myWorkPlane's height TopoDS_Shape clearedShape = Area::toShape(*clearedArea->myArea, false, &trsf); - Area::addShape(*(clearedAreasInPlane.myArea), - clearedShape, - &myTrsf, - .01 /*default value*/, - &myWorkPlane); + Area::addShape( + *(clearedAreasInPlane.myArea), + clearedShape, + &myTrsf, + .01 /*default value*/, + &myWorkPlane + ); } CArea clearable(*myArea); - clearable.OffsetWithClipper(-diameter / 2, - JoinType, - EndType, - params.MiterLimit, - roundPrecision); + clearable.OffsetWithClipper(-diameter / 2, JoinType, EndType, params.MiterLimit, roundPrecision); clearable.OffsetWithClipper(diameter / 2, JoinType, EndType, params.MiterLimit, roundPrecision); // remaining = clearable - prevCleared CArea remaining(clearable); - remaining.Clip(toClipperOp(Area::OperationDifference), - &*(clearedAreasInPlane.myArea), - SubjectFill, - ClipFill); + remaining.Clip( + toClipperOp(Area::OperationDifference), + &*(clearedAreasInPlane.myArea), + SubjectFill, + ClipFill + ); // rest = intersect(clearable, offset(remaining, dTool)) // add buffer to dTool to compensate for oversizing in getClearedArea CArea restCArea(remaining); - restCArea.OffsetWithClipper(diameter + buffer, - JoinType, - EndType, - params.MiterLimit, - roundPrecision); + restCArea.OffsetWithClipper(diameter + buffer, JoinType, EndType, params.MiterLimit, roundPrecision); restCArea.Clip(toClipperOp(Area::OperationIntersection), &clearable, SubjectFill, ClipFill); if (restCArea.m_curves.size() == 0) { @@ -828,15 +826,17 @@ void Area::addToBuild(CArea& area, const TopoDS_Shape& shape) } TopoDS_Shape plane = getPlane(); CArea areaOpen; - mySkippedShapes += addShape(area, - shape, - &myTrsf, - myParams.Deflection, - myParams.Coplanar == CoplanarNone ? nullptr : &plane, - myHaveSolid || myParams.Coplanar == CoplanarForce, - &areaOpen, - myParams.OpenMode == OpenModeEdges, - myParams.Reorient); + mySkippedShapes += addShape( + area, + shape, + &myTrsf, + myParams.Deflection, + myParams.Coplanar == CoplanarNone ? nullptr : &plane, + myHaveSolid || myParams.Coplanar == CoplanarForce, + &areaOpen, + myParams.OpenMode == OpenModeEdges, + myParams.Reorient + ); if (myProjecting) { // when projecting, we force all wires to be CCW in order to remove @@ -1150,8 +1150,7 @@ struct WireJoiner Standard_Real first, last; Handle(Geom_Curve) curve = BRep_Tool::Curve(it->edge, first, last); - bool reversed = - pstart.SquareDistance(curve->Value(last)) <= Precision::SquareConfusion(); + bool reversed = pstart.SquareDistance(curve->Value(last)) <= Precision::SquareConfusion(); BRepBuilderAPI_MakeEdge mkEdge1, mkEdge2; if (reversed) { @@ -1164,10 +1163,12 @@ struct WireJoiner } if (!mkEdge1.IsDone() || !mkEdge2.IsDone()) { if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { - AREA_WARN((reversed ? "reversed " : "") - << "edge split failed " << AREA_XYZ(pstart) << ", " << AREA_XYZ(pt) - << ", " << AREA_XYZ(pend) << ", " << ", err: " << mkEdge1.Error() - << ", " << mkEdge2.Error()); + AREA_WARN( + (reversed ? "reversed " : "") + << "edge split failed " << AREA_XYZ(pstart) << ", " << AREA_XYZ(pt) << ", " + << AREA_XYZ(pend) << ", " << ", err: " << mkEdge1.Error() << ", " + << mkEdge2.Error() + ); } ++it; continue; @@ -1221,8 +1222,7 @@ struct WireJoiner // populate adjacent list constexpr int intMax = std::numeric_limits::max(); - for (auto vit = vmap.qbegin(bgi::nearest(pt[i], intMax)); vit != vmap.qend(); - ++vit) { + for (auto vit = vmap.qbegin(bgi::nearest(pt[i], intMax)); vit != vmap.qend(); ++vit) { ++rcount; if (vit->pt().SquareDistance(pt[i]) > tol) { break; @@ -1272,8 +1272,7 @@ struct WireJoiner for (int iteration = 1; !edgesToVisit.empty(); ++iteration) { EdgeInfo* currentInfo = *edgesToVisit.begin(); - int currentIdx = - 1; // used to tell whether search connection from the start(0) or end(1) + int currentIdx = 1; // used to tell whether search connection from the start(0) or end(1) TopoDS_Edge& e = currentInfo->edge; edgesToVisit.erase(edgesToVisit.begin()); gp_Pnt pstart = currentInfo->p1; @@ -1290,8 +1289,7 @@ struct WireJoiner auto& r = stack.back(); // this loop is to find all edges connected to pend, and save them into stack.back() - for (int i = currentInfo->iStart[currentIdx]; i < currentInfo->iEnd[currentIdx]; - ++i) { + for (int i = currentInfo->iStart[currentIdx]; i < currentInfo->iEnd[currentIdx]; ++i) { auto& info = *adjacentList[i].it; if (info.iteration != iteration) { info.iteration = iteration; @@ -1412,11 +1410,13 @@ void Area::explode(const TopoDS_Shape& shape) } for (TopExp_Explorer itw(it.Current(), TopAbs_WIRE); itw.More(); itw.Next()) { for (BRepTools_WireExplorer xp(TopoDS::Wire(itw.Current())); xp.More(); xp.Next()) { - addWire(*myArea, - BRepBuilderAPI_MakeWire(TopoDS::Edge(xp.Current())).Wire(), - &myTrsf, - myParams.Deflection, - true); + addWire( + *myArea, + BRepBuilderAPI_MakeWire(TopoDS::Edge(xp.Current())).Wire(), + &myTrsf, + myParams.Deflection, + true + ); } } } @@ -1430,11 +1430,13 @@ void Area::explode(const TopoDS_Shape& shape) continue; } } - addWire(*myArea, - BRepBuilderAPI_MakeWire(TopoDS::Edge(it.Current())).Wire(), - &myTrsf, - myParams.Deflection, - true); + addWire( + *myArea, + BRepBuilderAPI_MakeWire(TopoDS::Edge(it.Current())).Wire(), + &myTrsf, + myParams.Deflection, + true + ); } } @@ -1484,10 +1486,12 @@ static void showShapes(const T& shapes, const char* name, const char* fmt = null } template -static int foreachSubshape(const TopoDS_Shape& shape, - Func func, - int type = TopAbs_FACE, - bool groupOpenEdges = false) +static int foreachSubshape( + const TopoDS_Shape& shape, + Func func, + int type = TopAbs_FACE, + bool groupOpenEdges = false +) { int res = -1; std::vector openShapes; @@ -1625,10 +1629,12 @@ TopoDS_Shape Area::findPlane(const TopoDS_Shape& shape, gp_Trsf& trsf) return plane; } -int Area::project(TopoDS_Shape& shape_out, - const TopoDS_Shape& shape_in, - const AreaParams* params, - const TopoDS_Shape* work_plane) +int Area::project( + TopoDS_Shape& shape_out, + const TopoDS_Shape& shape_in, + const AreaParams* params, + const TopoDS_Shape* work_plane +) { FC_TIME_INIT2(t, t1); Handle(HLRBRep_Algo) brep_hlr; @@ -1648,12 +1654,12 @@ int Area::project(TopoDS_Shape& shape_out, FC_TIME_LOG(t1, "HLRBrep_Algo"); WireJoiner joiner; try { -#define ADD_HLR_SHAPE(_name) \ - shape = hlrToShape._name##Compound(); \ - if (!shape.IsNull()) { \ - BRepLib::BuildCurves3d(shape); \ - joiner.add(shape, true); \ - showShape(shape, "raw_" #_name); \ +#define ADD_HLR_SHAPE(_name) \ + shape = hlrToShape._name##Compound(); \ + if (!shape.IsNull()) { \ + BRepLib::BuildCurves3d(shape); \ + joiner.add(shape, true); \ + showShape(shape, "raw_" #_name); \ } TopoDS_Shape shape; HLRBRep_HLRToShape hlrToShape(brep_hlr); @@ -1709,9 +1715,11 @@ int Area::project(TopoDS_Shape& shape_out, return skips; } -std::vector> Area::makeSections(PARAM_ARGS(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), - const std::vector& _heights, - const TopoDS_Shape& section_plane) +std::vector> Area::makeSections( + PARAM_ARGS(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), + const std::vector& _heights, + const TopoDS_Shape& section_plane +) { TopoDS_Shape plane; gp_Trsf trsf; @@ -1739,8 +1747,10 @@ std::vector> Area::makeSections(PARAM_ARGS(PARAM_FARG, AREA_PAR bounds.SetGap(0.0); Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); - AREA_TRACE("section bounds X(" << xMin << ',' << xMax << "), Y(" << yMin << ',' << yMax - << "), Z(" << zMin << ',' << zMax << ')'); + AREA_TRACE( + "section bounds X(" << xMin << ',' << xMax << "), Y(" << yMin << ',' << yMax << "), Z(" + << zMin << ',' << zMax << ')' + ); std::vector heights; double tolerance = 0.0; @@ -1957,9 +1967,10 @@ std::vector> Area::makeSections(PARAM_ARGS(PARAM_FARG, AREA_PAR wires.erase(it); } } - for (TopExp_Explorer xp(shape, - myParams.Fill == FillNone ? TopAbs_WIRE - : TopAbs_FACE); + for (TopExp_Explorer xp( + shape, + myParams.Fill == FillNone ? TopAbs_WIRE : TopAbs_FACE + ); xp.More(); xp.Next()) { builder.Add(comp, xp.Current()); @@ -1983,8 +1994,7 @@ std::vector> Area::makeSections(PARAM_ARGS(PARAM_FARG, AREA_PAR else if (area->myShapes.empty()) { auto itNext = it; if (++itNext != myShapes.end() - && (itNext->op == OperationIntersection - || itNext->op == OperationDifference)) { + && (itNext->op == OperationIntersection || itNext->op == OperationDifference)) { break; } } @@ -2100,8 +2110,8 @@ void Area::build() short op = OperationUnion; bool pending = false; bool exploding = myParams.Explode; - const auto& shapes = - (myParams.Outline && !myProjecting) ? getProjectedShapes(trsf) : myShapes; + const auto& shapes = (myParams.Outline && !myProjecting) ? getProjectedShapes(trsf) + : myShapes; for (const Shape& s : shapes) { if (exploding) { exploding = false; @@ -2128,8 +2138,10 @@ void Area::build() pending = true; } if (mySkippedShapes && !myHaveSolid) { - AREA_WARN((myParams.Coplanar == CoplanarForce ? "Skipped " : "Found ") - << mySkippedShapes << " non coplanar shapes"); + AREA_WARN( + (myParams.Coplanar == CoplanarForce ? "Skipped " : "Found ") + << mySkippedShapes << " non coplanar shapes" + ); } if (pending) { @@ -2212,27 +2224,27 @@ TopoDS_Shape Area::toShape(CArea& area, short fill, int reorient) } -#define AREA_SECTION(_op, _index, ...) \ - do { \ - if (mySections.size()) { \ - if (_index >= (int)mySections.size()) \ - return TopoDS_Shape(); \ - if (_index < 0) { \ - BRep_Builder builder; \ - TopoDS_Compound compound; \ - builder.MakeCompound(compound); \ - for (shared_ptr area : mySections) { \ - const TopoDS_Shape& s = area->_op(_index, ##__VA_ARGS__); \ - if (s.IsNull()) \ - continue; \ - builder.Add(compound, s); \ - } \ - if (TopExp_Explorer(compound, TopAbs_EDGE).More()) \ - return TopoDS_Shape(std::move(compound)); \ - return TopoDS_Shape(); \ - } \ - return mySections[_index]->_op(_index, ##__VA_ARGS__); \ - } \ +#define AREA_SECTION(_op, _index, ...) \ + do { \ + if (mySections.size()) { \ + if (_index >= (int)mySections.size()) \ + return TopoDS_Shape(); \ + if (_index < 0) { \ + BRep_Builder builder; \ + TopoDS_Compound compound; \ + builder.MakeCompound(compound); \ + for (shared_ptr area : mySections) { \ + const TopoDS_Shape& s = area->_op(_index, ##__VA_ARGS__); \ + if (s.IsNull()) \ + continue; \ + builder.Add(compound, s); \ + } \ + if (TopExp_Explorer(compound, TopAbs_EDGE).More()) \ + return TopoDS_Shape(std::move(compound)); \ + return TopoDS_Shape(); \ + } \ + return mySections[_index]->_op(_index, ##__VA_ARGS__); \ + } \ } while (0) TopoDS_Shape Area::getShape(int index) @@ -2333,17 +2345,15 @@ TopoDS_Shape Area::getShape(int index) return myShape; } -TopoDS_Shape Area::makeOffset(int index, - PARAM_ARGS(PARAM_FARG, AREA_PARAMS_OFFSET), - int reorient, - bool from_center) +TopoDS_Shape Area::makeOffset( + int index, + PARAM_ARGS(PARAM_FARG, AREA_PARAMS_OFFSET), + int reorient, + bool from_center +) { build(); - AREA_SECTION(makeOffset, - index, - PARAM_FIELDS(PARAM_FARG, AREA_PARAMS_OFFSET), - reorient, - from_center); + AREA_SECTION(makeOffset, index, PARAM_FIELDS(PARAM_FARG, AREA_PARAMS_OFFSET), reorient, from_center); std::list> areas; makeOffset(areas, PARAM_FIELDS(PARAM_FARG, AREA_PARAMS_OFFSET), from_center); @@ -2393,9 +2403,11 @@ TopoDS_Shape Area::makeOffset(int index, return TopoDS_Shape(); } -void Area::makeOffset(list>& areas, - PARAM_ARGS(PARAM_FARG, AREA_PARAMS_OFFSET), - bool from_center) +void Area::makeOffset( + list>& areas, + PARAM_ARGS(PARAM_FARG, AREA_PARAMS_OFFSET), + bool from_center +) { if (fabs(offset) < Precision::Confusion()) { return; @@ -2473,11 +2485,13 @@ void Area::makeOffset(list>& areas, break; case Area::AlgoClipperOffset: #endif - area.OffsetWithClipper(offset, - JoinType, - EndType, - myParams.MiterLimit, - myParams.RoundPrecision); + area.OffsetWithClipper( + offset, + JoinType, + EndType, + myParams.MiterLimit, + myParams.RoundPrecision + ); #ifdef AREA_OFFSET_ALGO break; } @@ -2580,10 +2594,7 @@ TopoDS_Shape Area::makePocket(int index, PARAM_ARGS(PARAM_FARG, AREA_PARAMS_POCK Stepover = -stepover; LastStepover = -last_stepover; // make offset and make sure the loop is CW (i.e. inner wires) - return makeOffset(index, - PARAM_FIELDS(PARAM_FNAME, AREA_PARAMS_OFFSET), - -1, - from_center); + return makeOffset(index, PARAM_FIELDS(PARAM_FNAME, AREA_PARAMS_OFFSET), -1, from_center); } case Area::PocketModeZigZagOffset: pm = ZigZagThenSingleOffsetPocketMode; @@ -2644,11 +2655,13 @@ TopoDS_Shape Area::makePocket(int index, PARAM_ARGS(PARAM_FARG, AREA_PARAMS_POCK PARAM_ENUM_CONVERT(AREA_MY, PARAM_FNAME, PARAM_ENUM_EXCEPT, AREA_PARAMS_CLIPPER_FILL); PARAM_ENUM_CONVERT(AREA_MY, PARAM_FNAME, PARAM_ENUM_EXCEPT, AREA_PARAMS_OFFSET_CONF); auto area = *myArea; - area.OffsetWithClipper(-tool_radius - extra_offset, - JoinType, - EndType, - myParams.MiterLimit, - myParams.RoundPrecision); + area.OffsetWithClipper( + -tool_radius - extra_offset, + JoinType, + EndType, + myParams.MiterLimit, + myParams.RoundPrecision + ); out.Clip(toClipperOp(OperationIntersection), &area, SubjectFill, ClipFill); done = true; break; @@ -2739,9 +2752,10 @@ TopoDS_Shape Area::toShape(const CCurve& _c, const gp_Trsf* trsf, int reorient) newCenter.SetX(x - dx); newCenter.SetY(y - dy); } - AREA_WARN("Arc correction: " << r << ", " << r2 << ", center" - << AREA_XYZ(center) << "->" - << AREA_XYZ(newCenter)); + AREA_WARN( + "Arc correction: " << r << ", " << r2 << ", center" << AREA_XYZ(center) + << "->" << AREA_XYZ(newCenter) + ); center = newCenter; } gp_Ax2 axis(center, gp_Dir(0, 0, v.m_type)); @@ -2765,10 +2779,7 @@ TopoDS_Shape Area::toShape(const CCurve& _c, const gp_Trsf* trsf, int reorient) pt = pnext; } - ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, - Precision::Confusion(), - Standard_False, - hWires); + ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, Precision::Confusion(), Standard_False, hWires); if (!hWires->Length()) { return shape; } @@ -2964,10 +2975,12 @@ struct GetWires info.points.push_back(BRep_Tool::Pnt(xp.CurrentVertex())); BRepAdaptor_Curve curve(xp.Current()); - GCPnts_UniformAbscissa discretizer(curve, - params.abscissa, - curve.FirstParameter(), - curve.LastParameter()); + GCPnts_UniformAbscissa discretizer( + curve, + params.abscissa, + curve.FirstParameter(), + curve.LastParameter() + ); if (discretizer.IsDone()) { int nbPoints = discretizer.NbPoints(); // OCC discretizer uses one-based index, so index one is @@ -3222,11 +3235,12 @@ struct ShapeInfo state = 1; continue; } - AREA_WARN((reversed ? "reversed " : "") - << "edge split failed " << AREA_XYZ(pprev) << ", " - << AREA_XYZ(myBestPt) << ", " << AREA_XYZ(pt) << ", " << d1 - << ", " << d2 << ", err: " << mkEdge1.Error() << ", " - << mkEdge2.Error()); + AREA_WARN( + (reversed ? "reversed " : "") + << "edge split failed " << AREA_XYZ(pprev) << ", " + << AREA_XYZ(myBestPt) << ", " << AREA_XYZ(pt) << ", " << d1 << ", " + << d2 << ", err: " << mkEdge1.Error() << ", " << mkEdge2.Error() + ); } if (d1 < d2) { @@ -3267,8 +3281,13 @@ struct ShapeInfo return myBestWire->wire; } - std::list - sortWires(const gp_Pnt& pstart, gp_Pnt& pend, double min_dist, double max_dist, gp_Pnt* pentry) + std::list sortWires( + const gp_Pnt& pstart, + gp_Pnt& pend, + double min_dist, + double max_dist, + gp_Pnt* pentry + ) { std::list wires; @@ -3326,11 +3345,13 @@ struct ShapeInfoBuilder bool& myArcPlaneFound; ShapeParams& myParams; - ShapeInfoBuilder(bool& plane_found, - short& arc_plane, - gp_Trsf& trsf, - std::list& list, - ShapeParams& params) + ShapeInfoBuilder( + bool& plane_found, + short& arc_plane, + gp_Trsf& trsf, + std::list& list, + ShapeParams& params + ) : myList(list) , myTrsf(trsf) , myArcPlane(arc_plane) @@ -3498,13 +3519,15 @@ struct WireOrienter typedef Standard_Real (gp_Pnt::*AxisGetter)() const; typedef void (gp_Pnt::*AxisSetter)(Standard_Real); -std::list Area::sortWires(const std::list& shapes, - bool has_start, - gp_Pnt* _pstart, - gp_Pnt* _pend, - double* stepdown_hint, - short* _parc_plane, - PARAM_ARGS(PARAM_FARG, AREA_PARAMS_SORT)) +std::list Area::sortWires( + const std::list& shapes, + bool has_start, + gp_Pnt* _pstart, + gp_Pnt* _pend, + double* stepdown_hint, + short* _parc_plane, + PARAM_ARGS(PARAM_FARG, AREA_PARAMS_SORT) +) { std::list wires; @@ -3529,8 +3552,7 @@ std::list Area::sortWires(const std::list& shapes, } if (sort_mode == SortModeGreedy && threshold < Precision::Confusion()) { - AREA_WARN( - "Sort mode 'Greedy' requires a threshold value (suggestion: use the tool diameter)"); + AREA_WARN("Sort mode 'Greedy' requires a threshold value (suggestion: use the tool diameter)"); sort_mode = SortMode2D5; } @@ -3556,9 +3578,7 @@ std::list Area::sortWires(const std::list& shapes, } for (auto& shape : shapes) { if (!shape.IsNull()) { - foreachSubshape(shape, - WireOrienter(wires, dir, orientation, direction), - TopAbs_WIRE); + foreachSubshape(shape, WireOrienter(wires, dir, orientation, direction), TopAbs_WIRE); } } return wires; @@ -3595,7 +3615,8 @@ std::list Area::sortWires(const std::list& shapes, shape, ShapeInfoBuilder(arcPlaneFound, arc_plane, trsf, shape_list, rparams), TopAbs_FACE, - true); + true + ); } } FC_TIME_LOG(t1, "plane finding"); @@ -3640,9 +3661,11 @@ std::list Area::sortWires(const std::list& shapes, itNext2 = itNext3) { ++itNext3; if (!itNext2->myPlanar - || !it->myPln.Position().IsCoplanar(itNext2->myPln.Position(), - Precision::Confusion(), - Precision::Confusion())) { + || !it->myPln.Position().IsCoplanar( + itNext2->myPln.Position(), + Precision::Confusion(), + Precision::Confusion() + )) { continue; } if (itNext == itNext2) { @@ -3663,8 +3686,10 @@ std::list Area::sortWires(const std::list& shapes, bounds.SetGap(0.0); Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); - AREA_TRACE("bound (" << xMin << ", " << xMax << "), (" << yMin << ", " << yMax << "), (" << zMin - << ", " << zMax << ')'); + AREA_TRACE( + "bound (" << xMin << ", " << xMax << "), (" << yMin << ", " << yMax << "), (" << zMin + << ", " << zMax << ')' + ); if (use_bound) { pstart.SetCoord(xMax, yMax, zMax); @@ -3761,8 +3786,9 @@ std::list Area::sortWires(const std::list& shapes, const gp_Pnt& P = pln.Position().Location(); const gp_Pnt& loc = best_it->myPln.Position().Location(); const gp_Dir& dir = best_it->myPln.Position().Direction(); - double d = (dir.X() * (P.X() - loc.X()) + dir.Y() * (P.Y() - loc.Y()) - + dir.Z() * (P.Z() - loc.Z())); + double d + = (dir.X() * (P.X() - loc.X()) + dir.Y() * (P.Y() - loc.Y()) + + dir.Z() * (P.Z() - loc.Z())); if (d < 0) { d = -d; } @@ -3795,12 +3821,14 @@ std::list Area::sortWires(const std::list& shapes, return wires; } -static inline void addParameter(bool verbose, - Command& cmd, - const char* name, - double last, - double next, - bool relative = false) +static inline void addParameter( + bool verbose, + Command& cmd, + const char* name, + double last, + double next, + bool relative = false +) { double d = next - last; if (verbose || fabs(d) > Precision::Confusion()) { @@ -3808,8 +3836,13 @@ static inline void addParameter(bool verbose, } } -static inline void -addGCode(bool verbose, Toolpath& path, const gp_Pnt& last, const gp_Pnt& next, const char* name) +static inline void addGCode( + bool verbose, + Toolpath& path, + const gp_Pnt& last, + const gp_Pnt& next, + const char* name +) { Command cmd; cmd.Name = name; @@ -3820,12 +3853,14 @@ addGCode(bool verbose, Toolpath& path, const gp_Pnt& last, const gp_Pnt& next, c return; } -static inline void addG1(bool verbose, - Toolpath& path, - const gp_Pnt& last, - const gp_Pnt& next, - double f, - double& last_f) +static inline void addG1( + bool verbose, + Toolpath& path, + const gp_Pnt& last, + const gp_Pnt& next, + double f, + double& last_f +) { addGCode(verbose, path, last, next, "G1"); if (f > Precision::Confusion()) { @@ -3836,12 +3871,14 @@ static inline void addG1(bool verbose, return; } -static void addG0(bool verbose, - Toolpath& path, - gp_Pnt last, - const gp_Pnt& next, - AxisSetter setter, - double height) +static void addG0( + bool verbose, + Toolpath& path, + gp_Pnt last, + const gp_Pnt& next, + AxisSetter setter, + double height +) { gp_Pnt pt(next); (pt.*setter)(height); @@ -3850,15 +3887,17 @@ static void addG0(bool verbose, } } -static void addGArc(bool verbose, - bool abs_center, - Toolpath& path, - const gp_Pnt& pstart, - const gp_Pnt& pend, - const gp_Pnt& center, - bool clockwise, - double f, - double& last_f) +static void addGArc( + bool verbose, + bool abs_center, + Toolpath& path, + const gp_Pnt& pstart, + const gp_Pnt& pend, + const gp_Pnt& center, + bool clockwise, + double f, + double& last_f +) { Command cmd; cmd.Name = clockwise ? "G2" : "G3"; @@ -3912,11 +3951,13 @@ void Area::setWireOrientation(TopoDS_Wire& wire, const gp_Dir& dir, bool wire_cc } } -void Area::toPath(Toolpath& path, - const std::list& shapes, - const gp_Pnt* _pstart, - gp_Pnt* pend, - PARAM_ARGS(PARAM_FARG, AREA_PARAMS_PATH)) +void Area::toPath( + Toolpath& path, + const std::list& shapes, + const gp_Pnt* _pstart, + gp_Pnt* pend, + PARAM_ARGS(PARAM_FARG, AREA_PARAMS_PATH) +) { std::list wires; @@ -3926,13 +3967,15 @@ void Area::toPath(Toolpath& path, } double stepdown_hint = 1.0; - wires = sortWires(shapes, - _pstart != nullptr, - &pstart, - pend, - &stepdown_hint, - PARAM_REF(PARAM_FARG, AREA_PARAMS_ARC_PLANE), - PARAM_FIELDS(PARAM_FARG, AREA_PARAMS_SORT)); + wires = sortWires( + shapes, + _pstart != nullptr, + &pstart, + pend, + &stepdown_hint, + PARAM_REF(PARAM_FARG, AREA_PARAMS_ARC_PLANE), + PARAM_FIELDS(PARAM_FARG, AREA_PARAMS_SORT) + ); if (wires.empty()) { return; @@ -4053,10 +4096,12 @@ void Area::toPath(Toolpath& path, switch (curve.GetType()) { case GeomAbs_Line: { if (segmentation > Precision::Confusion()) { - GCPnts_UniformAbscissa discretizer(curve, - segmentation, - curve.FirstParameter(), - curve.LastParameter()); + GCPnts_UniformAbscissa discretizer( + curve, + segmentation, + curve.FirstParameter(), + curve.LastParameter() + ); if (discretizer.IsDone() && discretizer.NbPoints() > 2) { int nbPoints = discretizer.NbPoints(); if (reversed) { @@ -4124,30 +4169,34 @@ void Area::toPath(Toolpath& path, if (reversed) { for (int i = nbPoints - 1; i >= 1; --i) { gp_Pnt pt = curve.Value(discretizer.Parameter(i)); - addGArc(verbose, - abs_center, - path, - plast, - pt, - center, - clockwise, - nf, - cur_f); + addGArc( + verbose, + abs_center, + path, + plast, + pt, + center, + clockwise, + nf, + cur_f + ); plast = pt; } } else { for (int i = 2; i <= nbPoints; i++) { gp_Pnt pt = curve.Value(discretizer.Parameter(i)); - addGArc(verbose, - abs_center, - path, - plast, - pt, - center, - clockwise, - nf, - cur_f); + addGArc( + verbose, + abs_center, + path, + plast, + pt, + center, + clockwise, + nf, + cur_f + ); plast = pt; } } @@ -4158,15 +4207,7 @@ void Area::toPath(Toolpath& path, if (fabs(first - last) > std::numbers::pi) { // Split arc(circle) larger than half circle. gp_Pnt mid = curve.Value((last - first) * 0.5 + first); - addGArc(verbose, - abs_center, - path, - plast, - mid, - center, - clockwise, - nf, - cur_f); + addGArc(verbose, abs_center, path, plast, mid, center, clockwise, nf, cur_f); plast = mid; } addGArc(verbose, abs_center, path, plast, p, center, clockwise, nf, cur_f); @@ -4219,5 +4260,5 @@ const AreaStaticParams& Area::getDefaultParams() } #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif diff --git a/src/Mod/CAM/App/Area.h b/src/Mod/CAM/App/Area.h index 48b3ccfed1..64fe5336ec 100644 --- a/src/Mod/CAM/App/Area.h +++ b/src/Mod/CAM/App/Area.h @@ -61,8 +61,8 @@ struct PathExport AreaParams: CAreaParams bool operator==(const AreaParams& other) const { -#define AREA_COMPARE(_param) \ - if (PARAM_FIELD(NAME, _param) != other.PARAM_FIELD(NAME, _param)) \ +#define AREA_COMPARE(_param) \ + if (PARAM_FIELD(NAME, _param) != other.PARAM_FIELD(NAME, _param)) \ return false; PARAM_FOREACH(AREA_COMPARE, AREA_PARAMS_CAREA); PARAM_FOREACH(AREA_COMPARE, AREA_PARAMS_AREA); @@ -160,9 +160,11 @@ protected: * * See #AREA_PARAMS_OFFSET for description of the arguments. */ - void makeOffset(std::list>& areas, - PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_OFFSET), - bool from_center = false); + void makeOffset( + std::list>& areas, + PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_OFFSET), + bool from_center = false + ); /** Make a pocket of the combined shape * @@ -227,10 +229,12 @@ public: * If more than one offset is requested, a compound shape is return * containing all offset shapes as wires regardless of \c Fill setting. */ - TopoDS_Shape makeOffset(int index = -1, - PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_OFFSET), - int reoirent = 0, - bool from_center = false); + TopoDS_Shape makeOffset( + int index = -1, + PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_OFFSET), + int reoirent = 0, + bool from_center = false + ); /** Make a pocket of the combined shape * @@ -250,15 +254,19 @@ public: * See #AREA_PARAMS_EXTRA for description of the arguments. Currently, there * is only one argument, namely \c mode for section mode. */ - std::vector> - makeSections(PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), - const std::vector& heights = std::vector(), - const TopoDS_Shape& plane = TopoDS_Shape()); + std::vector> makeSections( + PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), + const std::vector& heights = std::vector(), + const TopoDS_Shape& plane = TopoDS_Shape() + ); - std::shared_ptr - getClearedArea(const Toolpath* path, double diameter, double zmax, Base::BoundBox3d bbox); - std::shared_ptr getRestArea(std::vector> clearedAreas, - double diameter); + std::shared_ptr getClearedArea( + const Toolpath* path, + double diameter, + double zmax, + Base::BoundBox3d bbox + ); + std::shared_ptr getRestArea(std::vector> clearedAreas, double diameter); TopoDS_Shape toTopoShape(); /** Config this Area object */ @@ -308,11 +316,13 @@ public: * \arg \c to_edges: if true, discretize all curves, and insert as open * line segments * */ - static void addWire(CArea& area, - const TopoDS_Wire& wire, - const gp_Trsf* trsf = nullptr, - double deflection = 0.01, - bool to_edges = false); + static void addWire( + CArea& area, + const TopoDS_Wire& wire, + const gp_Trsf* trsf = nullptr, + double deflection = 0.01, + bool to_edges = false + ); /** Add a OCC generic shape to CArea * @@ -331,15 +341,17 @@ public: * \return Returns the number of non coplaner. Planar testing only happens * if \c plane is supplied * */ - static int addShape(CArea& area, - const TopoDS_Shape& shape, - const gp_Trsf* trsf = nullptr, - double deflection = 0.01, - const TopoDS_Shape* plane = nullptr, - bool force_coplanar = true, - CArea* areaOpen = nullptr, - bool to_edges = false, - bool reorient = true); + static int addShape( + CArea& area, + const TopoDS_Shape& shape, + const gp_Trsf* trsf = nullptr, + double deflection = 0.01, + const TopoDS_Shape* plane = nullptr, + bool force_coplanar = true, + CArea* areaOpen = nullptr, + bool to_edges = false, + bool reorient = true + ); /** Convert curves in CArea into an OCC shape * @@ -348,8 +360,12 @@ public: * \arg \c trsf: optional transform matrix to transform the shape back into * its original position. * */ - static TopoDS_Shape - toShape(const CArea& area, bool fill, const gp_Trsf* trsf = nullptr, int reoirent = 0); + static TopoDS_Shape toShape( + const CArea& area, + bool fill, + const gp_Trsf* trsf = nullptr, + int reoirent = 0 + ); /** Convert a single curve into an OCC wire * @@ -357,8 +373,7 @@ public: * \arg \c trsf: optional transform matrix to transform the shape back into * its original position. * */ - static TopoDS_Shape - toShape(const CCurve& curve, const gp_Trsf* trsf = nullptr, int reorient = 0); + static TopoDS_Shape toShape(const CCurve& curve, const gp_Trsf* trsf = nullptr, int reorient = 0); /** Check if two OCC shape is coplanar */ static bool isCoplanar(const TopoDS_Shape& s1, const TopoDS_Shape& s2); @@ -383,13 +398,15 @@ public: * * \return sorted wires */ - static std::list sortWires(const std::list& shapes, - bool has_start = false, - gp_Pnt* pstart = nullptr, - gp_Pnt* pend = nullptr, - double* stepdown_hint = nullptr, - short* arc_plane = nullptr, - PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_SORT)); + static std::list sortWires( + const std::list& shapes, + bool has_start = false, + gp_Pnt* pstart = nullptr, + gp_Pnt* pend = nullptr, + double* stepdown_hint = nullptr, + short* arc_plane = nullptr, + PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_SORT) + ); /** Convert a list of wires to gcode * @@ -400,16 +417,20 @@ public: * * See #AREA_PARAMS_PATH for other arguments */ - static void toPath(Toolpath& path, - const std::list& shapes, - const gp_Pnt* pstart = nullptr, - gp_Pnt* pend = nullptr, - PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_PATH)); + static void toPath( + Toolpath& path, + const std::list& shapes, + const gp_Pnt* pstart = nullptr, + gp_Pnt* pend = nullptr, + PARAM_ARGS_DEF(PARAM_FARG, AREA_PARAMS_PATH) + ); - static int project(TopoDS_Shape& out, - const TopoDS_Shape& in, - const AreaParams* params = nullptr, - const TopoDS_Shape* work_plane = nullptr); + static int project( + TopoDS_Shape& out, + const TopoDS_Shape& in, + const AreaParams* params = nullptr, + const TopoDS_Shape* work_plane = nullptr + ); static void setWireOrientation(TopoDS_Wire& wire, const gp_Dir& dir, bool ccw); @@ -421,8 +442,7 @@ public: static void setDefaultParams(const AreaStaticParams& params); static const AreaStaticParams& getDefaultParams(); - static void - showShape(const TopoDS_Shape& shape, const char* name, const char* fmt = nullptr, ...); + static void showShape(const TopoDS_Shape& shape, const char* name, const char* fmt = nullptr, ...); }; } // namespace Path diff --git a/src/Mod/CAM/App/AreaParams.h b/src/Mod/CAM/App/AreaParams.h index 8d6099baed..9c24371ffe 100644 --- a/src/Mod/CAM/App/AreaParams.h +++ b/src/Mod/CAM/App/AreaParams.h @@ -35,35 +35,37 @@ #include "ParamsHelper.h" /** clipper fill type */ -#define AREA_CLIPPER_FILL_TYPE \ +#define AREA_CLIPPER_FILL_TYPE \ (NonZero)(EvenOdd)(Positive)(Negative), (ClipperLib::PolyFillType, ClipperLib::pft) /** Parameters of clipper fill types */ -#define AREA_PARAMS_CLIPPER_FILL \ - ((enum2, \ - subject_fill, \ - SubjectFill, \ - 0, \ - "ClipperLib subject fill type. \nSee https://goo.gl/5pYQQP", \ - AREA_CLIPPER_FILL_TYPE))((enum2, \ - clip_fill, \ - ClipFill, \ - 0, \ - "ClipperLib clip fill type. \nSee https://goo.gl/5pYQQP", \ - AREA_CLIPPER_FILL_TYPE)) +#define AREA_PARAMS_CLIPPER_FILL \ + ((enum2, \ + subject_fill, \ + SubjectFill, \ + 0, \ + "ClipperLib subject fill type. \nSee https://goo.gl/5pYQQP", \ + AREA_CLIPPER_FILL_TYPE))( \ + (enum2, \ + clip_fill, \ + ClipFill, \ + 0, \ + "ClipperLib clip fill type. \nSee https://goo.gl/5pYQQP", \ + AREA_CLIPPER_FILL_TYPE) \ + ) /** Deflection parameter */ -#define AREA_PARAMS_DEFLECTION \ - ((double, \ - deflection, \ - Deflection, \ - 0.01, \ - "Deflection for non circular curve discretization. It also also used for\n" \ - "discretizing circular wires when you 'Explode' the shape for wire operations", \ +#define AREA_PARAMS_DEFLECTION \ + ((double, \ + deflection, \ + Deflection, \ + 0.01, \ + "Deflection for non circular curve discretization. It also also used for\n" \ + "discretizing circular wires when you 'Explode' the shape for wire operations", \ App::PropertyPrecision)) /** Base parameters */ -#define AREA_PARAMS_BASE \ +#define AREA_PARAMS_BASE \ ((enum, \ fill, \ Fill, \ @@ -108,50 +110,28 @@ #define AREA_PARAMS_FIT_ARCS ((bool, fit_arcs, FitArcs, true, "Enable arc fitting")) /** libarea algorithm option parameters */ -#define AREA_PARAMS_CAREA \ - ((double, \ - tolerance, \ - Tolerance, \ - Precision::Confusion(), \ - "Point coincidence tolerance", \ - App::PropertyPrecision)) \ - AREA_PARAMS_FIT_ARCS((bool, \ - clipper_simple, \ - Simplify, \ - false, \ - "Simplify polygons after operation. See https://goo.gl/Mh9XK1"))( \ - (double, \ - clipper_clean_distance, \ - CleanDistance, \ - 0.0, \ - "Clean polygon smaller than this distance. See https://goo.gl/jox3JY", \ - App::PropertyLength))( \ - (double, accuracy, Accuracy, 0.01, "Arc fitting accuracy", App::PropertyPrecision))( \ - (double, \ - units, \ - Unit, \ - 1.0, \ - "Scaling factor for conversion to inch", \ - App::PropertyFloat))( \ - (short, min_arc_points, MinArcPoints, 4, "Minimum segments for arc discretization"))( \ - (short, \ - max_arc_points, \ - MaxArcPoints, \ - 100, \ - "Maximum segments for arc discretization (ignored currently)"))( \ - (double, \ - clipper_scale, \ - ClipperScale, \ - 1e7, \ - "ClipperLib operate on integers. This is the scale factor to convert\n" \ - "floating points.", \ - App::PropertyFloat)) +#define AREA_PARAMS_CAREA \ + ((double, \ + tolerance, \ + Tolerance, \ + Precision::Confusion(), \ + "Point coincidence tolerance", \ + App::PropertyPrecision)) \ + AREA_PARAMS_FIT_ARCS((bool, clipper_simple, Simplify, false, "Simplify polygons after operation. See https://goo.gl/Mh9XK1"))((double, clipper_clean_distance, CleanDistance, 0.0, "Clean polygon smaller than this distance. See https://goo.gl/jox3JY", App::PropertyLength))((double, accuracy, Accuracy, 0.01, "Arc fitting accuracy", App::PropertyPrecision))((double, units, Unit, 1.0, "Scaling factor for conversion to inch", App::PropertyFloat))((short, min_arc_points, MinArcPoints, 4, "Minimum segments for arc discretization"))((short, max_arc_points, MaxArcPoints, 100, "Maximum segments for arc discretization (ignored currently)"))( \ + (double, \ + clipper_scale, \ + ClipperScale, \ + 1e7, \ + "ClipperLib operate on integers. This is the scale factor to convert\n" \ + "floating points.", \ + App::PropertyFloat) \ + ) /** Pocket parameters * * These parameters corresponds to CAreaPocketParams in libarea * */ -#define AREA_PARAMS_POCKET \ +#define AREA_PARAMS_POCKET \ ((enum, \ mode, \ PocketMode, \ @@ -197,66 +177,62 @@ "and 'Triangle'", \ App::PropertyDistance)) -#define AREA_PARAMS_POCKET_CONF \ +#define AREA_PARAMS_POCKET_CONF \ ((bool, thicken, Thicken, false, "Thicken the resulting wires with ToolRadius")) /** Operation code */ -#define AREA_PARAMS_OPCODE \ - ((enum, \ - op, \ - Operation, \ - 0, \ - "Boolean operation.\n" \ - "For the first four operations, see https://goo.gl/Gj8RUu.\n" \ - "'Compound' means no operation, normally used to do Area.sortWires().", \ +#define AREA_PARAMS_OPCODE \ + ((enum, \ + op, \ + Operation, \ + 0, \ + "Boolean operation.\n" \ + "For the first four operations, see https://goo.gl/Gj8RUu.\n" \ + "'Compound' means no operation, normally used to do Area.sortWires().", \ (Union)(Difference)(Intersection)(Xor)(Compound))) /** Offset parameters */ -#define AREA_PARAMS_OFFSET \ - ((double, \ - offset, \ - Offset, \ - 0.0, \ - "Offset value, positive for expansion, negative for shrinking", \ - App::PropertyDistance))( \ - (long, extra_pass, ExtraPass, 0, "Number of extra offset pass to generate."))( \ - (double, \ - stepover, \ - Stepover, \ - 0.0, \ - "Cutter diameter to step over on each pass. If =0, use Offset", \ - App::PropertyLength))((double, \ - last_stepover, \ - LastStepover, \ - 0.0, \ - "Cutter diameter to step over for the last loop when shrinking " \ - "with ExtraPass<0, i.e. for\n" \ - "offset pocketing. If =0, use 0.5*Offset.", \ - App::PropertyLength)) +#define AREA_PARAMS_OFFSET \ + ((double, \ + offset, \ + Offset, \ + 0.0, \ + "Offset value, positive for expansion, negative for shrinking", \ + App::PropertyDistance))((long, extra_pass, ExtraPass, 0, "Number of extra offset pass to generate."))((double, stepover, Stepover, 0.0, "Cutter diameter to step over on each pass. If =0, use Offset", App::PropertyLength))( \ + (double, \ + last_stepover, \ + LastStepover, \ + 0.0, \ + "Cutter diameter to step over for the last loop when shrinking " \ + "with ExtraPass<0, i.e. for\n" \ + "offset pocketing. If =0, use 0.5*Offset.", \ + App::PropertyLength) \ + ) -#define AREA_PARAMS_SECTION_EXTRA \ - ((enum, \ - mode, \ - SectionMode, \ - 2, \ - "Section offset coordinate mode.\n" \ - "'Absolute' means the absolute Z height (given in SectionOffset) to start slicing.\n" \ - "'BoundBox' means relative Z height to the bounding box of all the children shape.\n" \ - "'Workplane' means relative to workplane, minus SectionOffset.\n" \ - "Note that OCC has trouble getting the minimum bounding box of some solids, particularly\n" \ - "those with non-planar surface. It is recommended to use Workplane to specify the " \ - "intended\n" \ - "starting z height.\n", \ - (Absolute)(BoundBox)(Workplane)))( \ - (bool, \ - project, \ - Project, \ - false, \ - "The section is produced by normal projecting the outline\n" \ - "of all added shapes to the section plane, instead of slicing.")) +#define AREA_PARAMS_SECTION_EXTRA \ + ((enum, \ + mode, \ + SectionMode, \ + 2, \ + "Section offset coordinate mode.\n" \ + "'Absolute' means the absolute Z height (given in SectionOffset) to start slicing.\n" \ + "'BoundBox' means relative Z height to the bounding box of all the children shape.\n" \ + "'Workplane' means relative to workplane, minus SectionOffset.\n" \ + "Note that OCC has trouble getting the minimum bounding box of some solids, particularly\n" \ + "those with non-planar surface. It is recommended to use Workplane to specify the " \ + "intended\n" \ + "starting z height.\n", \ + (Absolute)(BoundBox)(Workplane)))( \ + (bool, \ + project, \ + Project, \ + false, \ + "The section is produced by normal projecting the outline\n" \ + "of all added shapes to the section plane, instead of slicing.") \ + ) /** Section parameters */ -#define AREA_PARAMS_SECTION \ +#define AREA_PARAMS_SECTION \ ((long, count, SectionCount, 0, "Number of sections to generate. -1 means full sections."))( \ (double, \ stepdown, \ @@ -285,76 +261,78 @@ App::PropertyPrecision))AREA_PARAMS_SECTION_EXTRA #ifdef AREA_OFFSET_ALGO -#define AREA_PARAMS_OFFSET_ALGO ((enum, algo, Algo, 0, "Offset algorithm type", (Clipper)(libarea))) +# define AREA_PARAMS_OFFSET_ALGO \ + ((enum, algo, Algo, 0, "Offset algorithm type", (Clipper)(libarea))) #else -#define AREA_PARAMS_OFFSET_ALGO +# define AREA_PARAMS_OFFSET_ALGO #endif /** Offset configuration parameters */ -#define AREA_PARAMS_OFFSET_CONF \ - AREA_PARAMS_OFFSET_ALGO((enum2, \ - join_type, \ - JoinType, \ - 0, \ - "ClipperOffset join type. \nSee https://goo.gl/4odfQh", \ - (Round)(Square)(Miter), \ - (ClipperLib::JoinType, ClipperLib::jt))) \ - ((enum2, \ - end_type, \ - EndType, \ - 0, \ - "\nClipperOffset end type. See https://goo.gl/tj7gkX", \ - (OpenRound)(ClosedPolygon)(ClosedLine)(OpenSquare)(OpenButt), \ - (ClipperLib::EndType, ClipperLib::et)))( \ - (double, \ - miter_limit, \ - MiterLimit, \ - 2.0, \ - "Miter limit for joint type Miter. See https://goo.gl/K8xX9h", \ - App::PropertyFloat))((double, \ - round_precision, \ - RoundPrecision, \ - 0.0, \ - "Round joint precision. If =0, it defaults to Accuracy. \n" \ - "See https://goo.gl/4odfQh", \ - App::PropertyPrecision)) +#define AREA_PARAMS_OFFSET_CONF \ + AREA_PARAMS_OFFSET_ALGO( \ + (enum2, \ + join_type, \ + JoinType, \ + 0, \ + "ClipperOffset join type. \nSee https://goo.gl/4odfQh", \ + (Round)(Square)(Miter), \ + (ClipperLib::JoinType, ClipperLib::jt)) \ + ) \ + ((enum2, \ + end_type, \ + EndType, \ + 0, \ + "\nClipperOffset end type. See https://goo.gl/tj7gkX", \ + (OpenRound)(ClosedPolygon)(ClosedLine)(OpenSquare)(OpenButt), \ + ( \ + ClipperLib::EndType, \ + ClipperLib::et \ + )))((double, miter_limit, MiterLimit, 2.0, "Miter limit for joint type Miter. See https://goo.gl/K8xX9h", App::PropertyFloat))( \ + (double, \ + round_precision, \ + RoundPrecision, \ + 0.0, \ + "Round joint precision. If =0, it defaults to Accuracy. \n" \ + "See https://goo.gl/4odfQh", \ + App::PropertyPrecision) \ + ) -#define AREA_PARAMS_MIN_DIST \ - ((double, \ - min_dist, \ - MinDistance, \ - 0.0, \ - "minimum distance for the generated new wires. Wires maybe broken if the\n" \ - "algorithm see fits. Set to zero to disable wire breaking.", \ +#define AREA_PARAMS_MIN_DIST \ + ((double, \ + min_dist, \ + MinDistance, \ + 0.0, \ + "minimum distance for the generated new wires. Wires maybe broken if the\n" \ + "algorithm see fits. Set to zero to disable wire breaking.", \ App::PropertyLength)) /** Arc plane */ -#define AREA_PARAMS_ARC_PLANE \ - ((enum, \ - arc_plane, \ - ArcPlane, \ - 1, \ - "Arc drawing plane, corresponding to G17, G18, and G19.\n" \ - "If not 'None', the output wires will be transformed to align with the selected plane,\n" \ - "and the corresponding GCode will be inserted.\n" \ - "'Auto' means the plane is determined by the first encountered arc plane. If the found\n" \ - "plane does not align to any GCode plane, XY plane is used.\n" \ - "'Variable' means the arc plane can be changed during operation to align to the\n" \ - "arc encountered.", \ +#define AREA_PARAMS_ARC_PLANE \ + ((enum, \ + arc_plane, \ + ArcPlane, \ + 1, \ + "Arc drawing plane, corresponding to G17, G18, and G19.\n" \ + "If not 'None', the output wires will be transformed to align with the selected plane,\n" \ + "and the corresponding GCode will be inserted.\n" \ + "'Auto' means the plane is determined by the first encountered arc plane. If the found\n" \ + "plane does not align to any GCode plane, XY plane is used.\n" \ + "'Variable' means the arc plane can be changed during operation to align to the\n" \ + "arc encountered.", \ (None)(Auto)(XY)(ZX)(YZ)(Variable))) -#define AREA_PARAMS_ORIENTATION \ - ((enum, \ - orientation, \ - Orientation, \ - 0, \ - "Enforce loop orientation\n" \ - "'Normal' means CCW for outer wires when looking against the positive axis direction, \n" \ - "and CW for inner wires. 'Reversed' means the other way round", \ +#define AREA_PARAMS_ORIENTATION \ + ((enum, \ + orientation, \ + Orientation, \ + 0, \ + "Enforce loop orientation\n" \ + "'Normal' means CCW for outer wires when looking against the positive axis direction, \n" \ + "and CW for inner wires. 'Reversed' means the other way round", \ (Normal)(Reversed))) /** Area wire sorting parameters */ -#define AREA_PARAMS_SORT \ +#define AREA_PARAMS_SORT \ ((enum, \ sort_mode, \ SortMode, \ @@ -400,14 +378,16 @@ (enum, retract_axis, RetractAxis, 2, "Tool retraction axis", (X)(Y)(Z))) /** Area path generation parameters */ -#define AREA_PARAMS_PATH \ - AREA_PARAMS_ARC_PLANE \ - AREA_PARAMS_SORT((double, \ - retraction, \ - Retraction, \ - 0.0, \ - "Tool retraction absolute coordinate along retraction axis", \ - App::PropertyLength)) \ +#define AREA_PARAMS_PATH \ + AREA_PARAMS_ARC_PLANE \ + AREA_PARAMS_SORT( \ + (double, \ + retraction, \ + Retraction, \ + 0.0, \ + "Tool retraction absolute coordinate along retraction axis", \ + App::PropertyLength) \ + ) \ ((double, \ resume_height, \ ResumeHeight, \ @@ -438,22 +418,22 @@ (bool, preamble, EmitPreamble, true, "Emit preambles"))AREA_PARAMS_DEFLECTION /** Group of all Area configuration parameters except CArea's*/ -#define AREA_PARAMS_AREA \ - AREA_PARAMS_BASE \ - AREA_PARAMS_OFFSET \ - AREA_PARAMS_OFFSET_CONF \ - AREA_PARAMS_POCKET \ - AREA_PARAMS_POCKET_CONF \ +#define AREA_PARAMS_AREA \ + AREA_PARAMS_BASE \ + AREA_PARAMS_OFFSET \ + AREA_PARAMS_OFFSET_CONF \ + AREA_PARAMS_POCKET \ + AREA_PARAMS_POCKET_CONF \ AREA_PARAMS_SECTION /** Group of all Area configuration parameters */ -#define AREA_PARAMS_CONF \ - AREA_PARAMS_CAREA \ +#define AREA_PARAMS_CONF \ + AREA_PARAMS_CAREA \ AREA_PARAMS_AREA /** Group of all Area parameters */ -#define AREA_PARAMS_ALL \ - AREA_PARAMS_CONF \ +#define AREA_PARAMS_ALL \ + AREA_PARAMS_CONF \ AREA_PARAMS_OPCODE #define AREA_PARAMS_STATIC_CONF AREA_PARAMS_CONF diff --git a/src/Mod/CAM/App/AreaPyImp.cpp b/src/Mod/CAM/App/AreaPyImp.cpp index a059b536cd..f76b6475fd 100644 --- a/src/Mod/CAM/App/AreaPyImp.cpp +++ b/src/Mod/CAM/App/AreaPyImp.cpp @@ -51,7 +51,8 @@ static PyObject* areaSetParams(PyObject*, PyObject* args, PyObject* kwd) static const std::array kwlist { PARAM_FIELD_STRINGS(NAME, AREA_PARAMS_STATIC_CONF), - nullptr}; + nullptr + }; if (args && PySequence_Size(args) > 0) { PyErr_SetString(PyExc_ValueError, "Non-keyword argument is not supported"); @@ -62,21 +63,23 @@ static PyObject* areaSetParams(PyObject*, PyObject* args, PyObject* kwd) AreaStaticParams params = Area::getDefaultParams(); -#define AREA_SET(_param) \ +#define AREA_SET(_param) \ PARAM_FNAME(_param) = PARAM_TYPED(PARAM_PY_CAST_, _param)(params.PARAM_FNAME(_param)); // populate the CONF variables with params PARAM_FOREACH(AREA_SET, AREA_PARAMS_STATIC_CONF) // Parse arguments to overwrite CONF variables - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwd, - "|" PARAM_PY_KWDS(AREA_PARAMS_STATIC_CONF), - kwlist, - PARAM_REF(PARAM_FNAME, AREA_PARAMS_STATIC_CONF))) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwd, + "|" PARAM_PY_KWDS(AREA_PARAMS_STATIC_CONF), + kwlist, + PARAM_REF(PARAM_FNAME, AREA_PARAMS_STATIC_CONF) + )) { return nullptr; } -#define AREA_GET(_param) \ +#define AREA_GET(_param) \ params.PARAM_FNAME(_param) = PARAM_TYPED(PARAM_CAST_PY_, _param)(PARAM_FNAME(_param)); // populate 'params' with the CONF variables PARAM_FOREACH(AREA_GET, AREA_PARAMS_STATIC_CONF) @@ -122,30 +125,31 @@ static const PyMethodDef areaOverrides[] = { nullptr, 0, "setParam(key=value...): Set algorithm parameters. You can call getParamsDesc() to \n" - "get a list of supported parameters and their descriptions.\n" PARAM_PY_DOC(NAME, - AREA_PARAMS_CONF)}, + "get a list of supported parameters and their descriptions.\n" PARAM_PY_DOC(NAME, AREA_PARAMS_CONF)}, { "add", nullptr, 0, "add((shape...)," PARAM_PY_ARGS_DOC( ARG, - AREA_PARAMS_OPCODE) "):\n" - "Add TopoShape(s) with given operation code\n" PARAM_PY_DOC( - ARG, - AREA_PARAMS_OPCODE) "\nThe first shape's wires will be unioned " - "together regardless of the op code given\n" - "(except for 'Compound'). Subsequent " - "shape's wire will be combined using the " - "op code.\n" - "All shape wires shall be coplanar, and " - "are used to determine a working plane for " - "face\n" - "making and offsetting. You can call " - "setPlane() to supply a reference shape to " - "determine\n" - "the workplane in case the added shapes " - "are all colinear lines.\n", + AREA_PARAMS_OPCODE + ) "):\n" + "Add TopoShape(s) with given operation code\n" PARAM_PY_DOC( + ARG, + AREA_PARAMS_OPCODE + ) "\nThe first shape's wires will be unioned " + "together regardless of the op code given\n" + "(except for 'Compound'). Subsequent " + "shape's wire will be combined using the " + "op code.\n" + "All shape wires shall be coplanar, and " + "are used to determine a working plane for " + "face\n" + "making and offsetting. You can call " + "setPlane() to supply a reference shape to " + "determine\n" + "the workplane in case the added shapes " + "are all colinear lines.\n", }, { @@ -154,11 +158,11 @@ static const PyMethodDef areaOverrides[] = { 0, "makeOffset(index=-1, " PARAM_PY_ARGS_DOC( ARG, - AREA_PARAMS_OFFSET) "):\n" - "Make an 2D offset of the shape.\n" - "\n* index (-1): the index of the section. -1 means all sections. " - "No effect on planar shape.\n" PARAM_PY_DOC(ARG, - AREA_PARAMS_OFFSET), + AREA_PARAMS_OFFSET + ) "):\n" + "Make an 2D offset of the shape.\n" + "\n* index (-1): the index of the section. -1 means all sections. " + "No effect on planar shape.\n" PARAM_PY_DOC(ARG, AREA_PARAMS_OFFSET), }, { "makePocket", @@ -166,11 +170,11 @@ static const PyMethodDef areaOverrides[] = { 0, "makePocket(index=-1, " PARAM_PY_ARGS_DOC( ARG, - AREA_PARAMS_POCKET) "):\n" - "Generate pocket toolpath of the shape.\n" - "\n* index (-1): the index of the section. -1 means all sections. " - "No effect on planar shape.\n" PARAM_PY_DOC(ARG, - AREA_PARAMS_POCKET), + AREA_PARAMS_POCKET + ) "):\n" + "Generate pocket toolpath of the shape.\n" + "\n* index (-1): the index of the section. -1 means all sections. " + "No effect on planar shape.\n" PARAM_PY_DOC(ARG, AREA_PARAMS_POCKET), }, { "makeSections", @@ -178,25 +182,27 @@ static const PyMethodDef areaOverrides[] = { 0, "makeSections(" PARAM_PY_ARGS_DOC( ARG, - AREA_PARAMS_SECTION_EXTRA) ", heights=[], plane=None):\n" - "Make a list of area holding the sectioned children shapes " - "on given heights\n" PARAM_PY_DOC( - ARG, - AREA_PARAMS_SECTION_EXTRA) "\n* heights ([]): a list of " - "section heights, the " - "meaning of the value is " - "determined by 'mode'.\n" - "If not specified, the " - "current SectionCount, and " - "SectionOffset of this Area " - "is used.\n" - "\n* plane (None): optional " - "shape to specify a section " - "plane. If not give, the " - "current workplane\n" - "of this Area is used if " - "section mode is " - "'Workplane'.", + AREA_PARAMS_SECTION_EXTRA + ) ", heights=[], plane=None):\n" + "Make a list of area holding the sectioned children shapes " + "on given heights\n" PARAM_PY_DOC( + ARG, + AREA_PARAMS_SECTION_EXTRA + ) "\n* heights ([]): a list of " + "section heights, the " + "meaning of the value is " + "determined by 'mode'.\n" + "If not specified, the " + "current SectionCount, and " + "SectionOffset of this Area " + "is used.\n" + "\n* plane (None): optional " + "shape to specify a section " + "plane. If not give, the " + "current workplane\n" + "of this Area is used if " + "section mode is " + "'Workplane'.", }, { "getClearedArea", @@ -321,13 +327,7 @@ PyObject* AreaPy::getShape(PyObject* args, PyObject* keywds) PyObject* pcObj = Py_False; short index = -1; static const std::array kwlist {"index", "rebuild", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|hO!", - kwlist, - &index, - &PyBool_Type, - &pcObj)) { + if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "|hO!", kwlist, &index, &PyBool_Type, &pcObj)) { return nullptr; } @@ -349,16 +349,20 @@ PyObject* AreaPy::add(PyObject* args, PyObject* keywds) // Strangely, PyArg_ParseTupleAndKeywords requires all arguments to be keyword based, // even non-optional ones? That doesn't make sense in python. Seems only in python 3 // they added '$' to address that issue. - static const std::array kwlist {"shape", - PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_OPCODE), - nullptr}; + static const std::array kwlist { + "shape", + PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_OPCODE), + nullptr + }; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "O|" PARAM_PY_KWDS(AREA_PARAMS_OPCODE), - kwlist, - &pcObj, - PARAM_REF(PARAM_FARG, AREA_PARAMS_OPCODE))) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "O|" PARAM_PY_KWDS(AREA_PARAMS_OPCODE), + kwlist, + &pcObj, + PARAM_REF(PARAM_FARG, AREA_PARAMS_OPCODE) + )) { return nullptr; } @@ -381,8 +385,7 @@ PyObject* AreaPy::add(PyObject* args, PyObject* keywds) } for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) { PyObject* item = (*it).ptr(); - getAreaPtr()->add(GET_TOPOSHAPE(item), - PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_OPCODE)); + getAreaPtr()->add(GET_TOPOSHAPE(item), PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_OPCODE)); } Py_INCREF(this); return this; @@ -397,9 +400,11 @@ PyObject* AreaPy::add(PyObject* args, PyObject* keywds) PyObject* AreaPy::makeOffset(PyObject* args, PyObject* keywds) { // Generate a keyword string defined in the ARG field of OFFSET parameter list - static const std::array kwlist {"index", - PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_OFFSET), - nullptr}; + static const std::array kwlist { + "index", + PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_OFFSET), + nullptr + }; short index = -1; // Declare variables defined in the ARG field of the OFFSET parameter list with @@ -407,20 +412,22 @@ PyObject* AreaPy::makeOffset(PyObject* args, PyObject* keywds) PARAM_PY_DECLARE_INIT(PARAM_FARG, AREA_PARAMS_OFFSET) // Parse arguments to overwrite the defaults - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|h" PARAM_PY_KWDS(AREA_PARAMS_OFFSET), - kwlist, - &index, - PARAM_REF(PARAM_FARG, AREA_PARAMS_OFFSET))) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "|h" PARAM_PY_KWDS(AREA_PARAMS_OFFSET), + kwlist, + &index, + PARAM_REF(PARAM_FARG, AREA_PARAMS_OFFSET) + )) { return nullptr; } PY_TRY { // Expand the variable as function call arguments - TopoDS_Shape resultShape = - getAreaPtr()->makeOffset(index, PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_OFFSET)); + TopoDS_Shape resultShape + = getAreaPtr()->makeOffset(index, PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_OFFSET)); return Py::new_reference_to(Part::shape2pyshape(resultShape)); } PY_CATCH_OCC @@ -428,28 +435,32 @@ PyObject* AreaPy::makeOffset(PyObject* args, PyObject* keywds) PyObject* AreaPy::makePocket(PyObject* args, PyObject* keywds) { - static const std::array kwlist {"index", - PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_POCKET), - nullptr}; + static const std::array kwlist { + "index", + PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_POCKET), + nullptr + }; short index = -1; PARAM_PY_DECLARE_INIT(PARAM_FARG, AREA_PARAMS_POCKET) // Override pocket mode default mode = Area::PocketModeZigZagOffset; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|h" PARAM_PY_KWDS(AREA_PARAMS_POCKET), - kwlist, - &index, - PARAM_REF(PARAM_FARG, AREA_PARAMS_POCKET))) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "|h" PARAM_PY_KWDS(AREA_PARAMS_POCKET), + kwlist, + &index, + PARAM_REF(PARAM_FARG, AREA_PARAMS_POCKET) + )) { return nullptr; } PY_TRY { - TopoDS_Shape resultShape = - getAreaPtr()->makePocket(index, PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_POCKET)); + TopoDS_Shape resultShape + = getAreaPtr()->makePocket(index, PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_POCKET)); return Py::new_reference_to(Part::shape2pyshape(resultShape)); } PY_CATCH_OCC @@ -461,20 +472,23 @@ PyObject* AreaPy::makeSections(PyObject* args, PyObject* keywds) PARAM_FIELD_STRINGS(ARG, AREA_PARAMS_SECTION_EXTRA), "heights", "plane", - nullptr}; + nullptr + }; PyObject* heights = nullptr; PyObject* plane = nullptr; PARAM_PY_DECLARE_INIT(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA) - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|" PARAM_PY_KWDS(AREA_PARAMS_SECTION_EXTRA) "OO!", - kwlist, - PARAM_REF(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), - &heights, - &(Part::TopoShapePy::Type), - &plane)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "|" PARAM_PY_KWDS(AREA_PARAMS_SECTION_EXTRA) "OO!", + kwlist, + PARAM_REF(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), + &heights, + &(Part::TopoShapePy::Type), + &plane + )) { return nullptr; } @@ -499,16 +513,16 @@ PyObject* AreaPy::makeSections(PyObject* args, PyObject* keywds) } } else { - PyErr_SetString(PyExc_TypeError, - "heights must be of type float or list/tuple of float"); + PyErr_SetString(PyExc_TypeError, "heights must be of type float or list/tuple of float"); return nullptr; } } - std::vector> sections = - getAreaPtr()->makeSections(PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), - h, - plane ? GET_TOPOSHAPE(plane) : TopoDS_Shape()); + std::vector> sections = getAreaPtr()->makeSections( + PARAM_PY_FIELDS(PARAM_FARG, AREA_PARAMS_SECTION_EXTRA), + h, + plane ? GET_TOPOSHAPE(plane) : TopoDS_Shape() + ); Py::List ret; for (auto& area : sections) { @@ -534,8 +548,8 @@ if (!PyObject_TypeCheck(pyBbox, &(Base::BoundBoxPy::Type))) { } const PathPy* path = static_cast(pyPath); const Py::BoundingBox bbox(pyBbox, false); -std::shared_ptr clearedArea = - getAreaPtr()->getClearedArea(path->getToolpathPtr(), diameter, zmax, bbox.getValue()); +std::shared_ptr clearedArea + = getAreaPtr()->getClearedArea(path->getToolpathPtr(), diameter, zmax, bbox.getValue()); auto pyClearedArea = Py::asObject(new AreaPy(new Area(*clearedArea, true))); return Py::new_reference_to(pyClearedArea); } @@ -557,8 +571,7 @@ if (pyClearedAreas && PyObject_TypeCheck(pyClearedAreas, &PyList_Type)) { PyErr_SetString(PyExc_TypeError, "cleared areas must only contain AreaPy type"); return nullptr; } - clearedAreas.push_back( - std::make_shared(*static_cast(item)->getAreaPtr(), true)); + clearedAreas.push_back(std::make_shared(*static_cast(item)->getAreaPtr(), true)); } } else { @@ -576,8 +589,7 @@ return Py::new_reference_to(pyRestArea); PY_CATCH_OCC } -PyObject* AreaPy::toTopoShape(PyObject* args) { - PY_TRY {if (!PyArg_ParseTuple(args, "")) return nullptr; +PyObject* AreaPy::toTopoShape(PyObject* args) {PY_TRY {if (!PyArg_ParseTuple(args, "")) return nullptr; return Py::new_reference_to(Part::shape2pyshape(getAreaPtr()->toTopoShape())); } PY_CATCH_OCC @@ -590,8 +602,10 @@ PyObject* AreaPy::setDefaultParams(PyObject*, PyObject*) PyObject* AreaPy::setParams(PyObject* args, PyObject* keywds) { - static const std::array kwlist {PARAM_FIELD_STRINGS(NAME, AREA_PARAMS_CONF), - nullptr}; + static const std::array kwlist { + PARAM_FIELD_STRINGS(NAME, AREA_PARAMS_CONF), + nullptr + }; // Declare variables defined in the NAME field of the CONF parameter list PARAM_PY_DECLARE(PARAM_FNAME, AREA_PARAMS_CONF); @@ -602,11 +616,13 @@ PyObject* AreaPy::setParams(PyObject* args, PyObject* keywds) PARAM_FOREACH(AREA_SET, AREA_PARAMS_CONF) // Parse arguments to overwrite CONF variables - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|" PARAM_PY_KWDS(AREA_PARAMS_CONF), - kwlist, - PARAM_REF(PARAM_FNAME, AREA_PARAMS_CONF))) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "|" PARAM_PY_KWDS(AREA_PARAMS_CONF), + kwlist, + PARAM_REF(PARAM_FNAME, AREA_PARAMS_CONF) + )) { return nullptr; } diff --git a/src/Mod/CAM/App/Command.cpp b/src/Mod/CAM/App/Command.cpp index a713bb7689..3bdd9f0663 100644 --- a/src/Mod/CAM/App/Command.cpp +++ b/src/Mod/CAM/App/Command.cpp @@ -103,8 +103,7 @@ std::string Command::toGCode(int precision, bool padzero) const } double scale = std::pow(10.0, precision + 1); std::int64_t iscale = static_cast(scale) / 10; - for (std::map::const_iterator i = Parameters.begin(); - i != Parameters.end(); + for (std::map::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) { if (i->first == "N") { continue; @@ -284,8 +283,7 @@ Command Command::transform(const Base::Placement& other) plac.getRotation().getYawPitchRoll(aval, bval, cval); Command c = Command(); c.Name = Name; - for (std::map::const_iterator i = Parameters.begin(); - i != Parameters.end(); + for (std::map::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) { std::string k = i->first; double v = i->second; @@ -314,8 +312,7 @@ Command Command::transform(const Base::Placement& other) void Command::scaleBy(double factor) { - for (std::map::const_iterator i = Parameters.begin(); - i != Parameters.end(); + for (std::map::const_iterator i = Parameters.begin(); i != Parameters.end(); ++i) { switch (i->first[0]) { case 'X': diff --git a/src/Mod/CAM/App/Command.h b/src/Mod/CAM/App/Command.h index 0fc02615d9..c3c40b5e8a 100644 --- a/src/Mod/CAM/App/Command.h +++ b/src/Mod/CAM/App/Command.h @@ -50,20 +50,23 @@ public: void Restore(Base::XMLReader& /*reader*/) override; // specific methods - Base::Placement getPlacement(const Base::Vector3d pos = Base::Vector3d()) - const; // returns a placement from the x,y,z,a,b,c parameters + Base::Placement getPlacement( + const Base::Vector3d pos = Base::Vector3d() + ) const; // returns a placement from the x,y,z,a,b,c parameters Base::Vector3d getCenter() const; // returns a 3d vector from the i,j,k parameters - void setCenter(const Base::Vector3d&, - bool clockwise = true); // sets the center coordinates and the command name - std::string - toGCode(int precision = 6, - bool padzero = true) const; // returns a GCode string representation of the command - void setFromGCode( - const std::string&); // sets the parameters from the contents of the given GCode string - void setFromPlacement( - const Base::Placement&); // sets the parameters from the contents of the given placement - bool - has(const std::string&) const; // returns true if the given string exists in the parameters + void setCenter( + const Base::Vector3d&, + bool clockwise = true + ); // sets the center coordinates and the command name + std::string toGCode( + int precision = 6, + bool padzero = true + ) const; // returns a GCode string representation of the command + void setFromGCode(const std::string&); // sets the parameters from the contents of the given + // GCode string + void setFromPlacement(const Base::Placement&); // sets the parameters from the contents of the + // given placement + bool has(const std::string&) const; // returns true if the given string exists in the parameters Command transform(const Base::Placement&); // returns a transformed copy of this command double getValue(const std::string& name) const; // returns the value of a given parameter void scaleBy(double factor); // scales the receiver - use for imperial/metric conversions diff --git a/src/Mod/CAM/App/CommandPyImp.cpp b/src/Mod/CAM/App/CommandPyImp.cpp index d9598ed88a..42cda803fc 100644 --- a/src/Mod/CAM/App/CommandPyImp.cpp +++ b/src/Mod/CAM/App/CommandPyImp.cpp @@ -73,13 +73,7 @@ int CommandPy::PyInit(PyObject* args, PyObject* kwd) PyObject* parameters = nullptr; const char* name = ""; static const std::array kwlist {"name", "parameters", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, - kwd, - "|sO!", - kwlist, - &name, - &PyDict_Type, - ¶meters)) { + if (Base::Wrapped_ParseTupleAndKeywords(args, kwd, "|sO!", kwlist, &name, &PyDict_Type, ¶meters)) { std::string sname(name); boost::to_upper(sname); try { @@ -123,13 +117,15 @@ int CommandPy::PyInit(PyObject* args, PyObject* kwd) } PyErr_Clear(); // set by PyArg_ParseTuple() - if (Base::Wrapped_ParseTupleAndKeywords(args, - kwd, - "|sO!", - kwlist, - &name, - &(Base::PlacementPy::Type), - ¶meters)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwd, + "|sO!", + kwlist, + &name, + &(Base::PlacementPy::Type), + ¶meters + )) { std::string sname(name); boost::to_upper(sname); try { @@ -241,16 +237,14 @@ PyObject* CommandPy::setFromGCode(PyObject* args) Py::Object CommandPy::getPlacement() const { - return Py::asObject( - new Base::PlacementPy(new Base::Placement(getCommandPtr()->getPlacement()))); + return Py::asObject(new Base::PlacementPy(new Base::Placement(getCommandPtr()->getPlacement()))); } void CommandPy::setPlacement(Py::Object arg) { Py::Type PlacementType(Base::getTypeAsObject(&(Base::PlacementPy::Type))); if (arg.isType(PlacementType)) { - getCommandPtr()->setFromPlacement( - *static_cast((*arg))->getPlacementPtr()); + getCommandPtr()->setFromPlacement(*static_cast((*arg))->getPlacementPtr()); parameters_copy_dict.clear(); } else { diff --git a/src/Mod/CAM/App/FeatureArea.cpp b/src/Mod/CAM/App/FeatureArea.cpp index 7dd8969db0..4cbce5a353 100644 --- a/src/Mod/CAM/App/FeatureArea.cpp +++ b/src/Mod/CAM/App/FeatureArea.cpp @@ -83,7 +83,8 @@ App::DocumentObjectExecReturn* FeatureArea::execute() for (std::vector::iterator it = links.begin(); it != links.end(); ++it) { if (!(*it && (*it)->isDerivedFrom())) { return new App::DocumentObjectExecReturn( - "Linked object is not a Part object (has no Shape)."); + "Linked object is not a Part object (has no Shape)." + ); } TopoDS_Shape shape = static_cast(*it)->Shape.getShape().getShape(); if (shape.IsNull()) { @@ -105,8 +106,10 @@ App::DocumentObjectExecReturn* FeatureArea::execute() myArea.setPlane(workPlane); for (std::vector::iterator it = links.begin(); it != links.end(); ++it) { - myArea.add(static_cast(*it)->Shape.getShape().getShape(), - PARAM_PROP_ARGS(AREA_PARAMS_OPCODE)); + myArea.add( + static_cast(*it)->Shape.getShape().getShape(), + PARAM_PROP_ARGS(AREA_PARAMS_OPCODE) + ); } myShapes.clear(); @@ -185,13 +188,15 @@ FeatureAreaView::FeatureAreaView() (0), "Section", App::Prop_None, - "The start index of the section to show, negative value for reverse index from bottom"); + "The start index of the section to show, negative value for reverse index from bottom" + ); ADD_PROPERTY_TYPE( SectionCount, (1), "Section", App::Prop_None, - "Number of sections to show, 0 to show all section starting from SectionIndex"); + "Number of sections to show, 0 to show all section starting from SectionIndex" + ); } std::list FeatureAreaView::getShapes() diff --git a/src/Mod/CAM/App/FeatureAreaPyImp.cpp b/src/Mod/CAM/App/FeatureAreaPyImp.cpp index 57a67380e7..c2920b447d 100644 --- a/src/Mod/CAM/App/FeatureAreaPyImp.cpp +++ b/src/Mod/CAM/App/FeatureAreaPyImp.cpp @@ -52,30 +52,35 @@ PyObject* FeatureAreaPy::getArea(PyObject* args) PyObject* FeatureAreaPy::setParams(PyObject* args, PyObject* keywds) { - static const std::array kwlist {PARAM_FIELD_STRINGS(NAME, AREA_PARAMS_CONF), - nullptr}; + static const std::array kwlist { + PARAM_FIELD_STRINGS(NAME, AREA_PARAMS_CONF), + nullptr + }; // Declare variables defined in the NAME field of the CONF parameter list PARAM_PY_DECLARE(PARAM_FNAME, AREA_PARAMS_CONF); FeatureArea* feature = getFeatureAreaPtr(); -#define AREA_SET(_param) \ - PARAM_FNAME(_param) = \ - PARAM_TYPED(PARAM_PY_CAST_, _param)(feature->PARAM_FNAME(_param).getValue()); +#define AREA_SET(_param) \ + PARAM_FNAME(_param) = PARAM_TYPED(PARAM_PY_CAST_, _param)( \ + feature->PARAM_FNAME(_param).getValue() \ + ); // populate the CONF variables with values in properties PARAM_FOREACH(AREA_SET, AREA_PARAMS_CONF) // Parse arguments to overwrite CONF variables - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|" PARAM_PY_KWDS(AREA_PARAMS_CONF), - kwlist, - PARAM_REF(PARAM_FNAME, AREA_PARAMS_CONF))) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "|" PARAM_PY_KWDS(AREA_PARAMS_CONF), + kwlist, + PARAM_REF(PARAM_FNAME, AREA_PARAMS_CONF) + )) { return nullptr; } -#define AREA_GET(_param) \ +#define AREA_GET(_param) \ feature->PARAM_FNAME(_param).setValue(PARAM_TYPED(PARAM_CAST_PY_, _param)(PARAM_FNAME(_param))); // populate properties with the CONF variables PARAM_FOREACH(AREA_GET, AREA_PARAMS_CONF) @@ -98,7 +103,8 @@ void FeatureAreaPy::setWorkPlane(Py::Object obj) throw Py::TypeError(error); } getFeatureAreaPtr()->setWorkPlane( - static_cast(p)->getTopoShapePtr()->getShape()); + static_cast(p)->getTopoShapePtr()->getShape() + ); } PyObject* FeatureAreaPy::getCustomAttributes(const char* /*attr*/) const diff --git a/src/Mod/CAM/App/FeaturePath.cpp b/src/Mod/CAM/App/FeaturePath.cpp index 97602a84e6..2098767aee 100644 --- a/src/Mod/CAM/App/FeaturePath.cpp +++ b/src/Mod/CAM/App/FeaturePath.cpp @@ -34,11 +34,7 @@ PROPERTY_SOURCE(Path::Feature, App::GeoFeature) Feature::Feature() { - ADD_PROPERTY_TYPE(Path, - (Path::Toolpath()), - "Base", - App::Prop_None, - "The path data of this feature"); + ADD_PROPERTY_TYPE(Path, (Path::Toolpath()), "Base", App::Prop_None, "The path data of this feature"); } Feature::~Feature() diff --git a/src/Mod/CAM/App/FeaturePathCompound.cpp b/src/Mod/CAM/App/FeaturePathCompound.cpp index 55605462c3..f4f28a8e4b 100644 --- a/src/Mod/CAM/App/FeaturePathCompound.cpp +++ b/src/Mod/CAM/App/FeaturePathCompound.cpp @@ -36,11 +36,13 @@ PROPERTY_SOURCE(Path::FeatureCompound, Path::Feature) FeatureCompound::FeatureCompound() { ADD_PROPERTY_TYPE(Group, (nullptr), "Base", Prop_None, "Ordered list of paths to combine"); - ADD_PROPERTY_TYPE(UsePlacements, - (false), - "Base", - Prop_None, - "Specifies if the placements of children must be computed"); + ADD_PROPERTY_TYPE( + UsePlacements, + (false), + "Base", + Prop_None, + "Specifies if the placements of children must be computed" + ); } FeatureCompound::~FeatureCompound() @@ -53,11 +55,10 @@ App::DocumentObjectExecReturn* FeatureCompound::execute() for (std::vector::const_iterator it = Paths.begin(); it != Paths.end(); ++it) { if ((*it)->isDerivedFrom()) { - const std::vector& cmds = - static_cast(*it)->Path.getValue().getCommands(); + const std::vector& cmds + = static_cast(*it)->Path.getValue().getCommands(); const Base::Placement pl = static_cast(*it)->Placement.getValue(); - for (std::vector::const_iterator it2 = cmds.begin(); it2 != cmds.end(); - ++it2) { + for (std::vector::const_iterator it2 = cmds.begin(); it2 != cmds.end(); ++it2) { if (UsePlacements.getValue()) { result.addCommand((*it2)->transform(pl)); } diff --git a/src/Mod/CAM/App/FeaturePathCompoundPyImp.cpp b/src/Mod/CAM/App/FeaturePathCompoundPyImp.cpp index b999421297..d7ccb0b9b7 100644 --- a/src/Mod/CAM/App/FeaturePathCompoundPyImp.cpp +++ b/src/Mod/CAM/App/FeaturePathCompoundPyImp.cpp @@ -44,15 +44,15 @@ PyObject* FeaturePathCompoundPy::addObject(PyObject* args) } DocumentObjectPy* docObj = static_cast(object); - if (!docObj->getDocumentObjectPtr() - || !docObj->getDocumentObjectPtr()->isAttachedToDocument()) { + if (!docObj->getDocumentObjectPtr() || !docObj->getDocumentObjectPtr()->isAttachedToDocument()) { PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot add an invalid object"); return nullptr; } - if (docObj->getDocumentObjectPtr()->getDocument() - != getFeaturePathCompoundPtr()->getDocument()) { - PyErr_SetString(Base::PyExc_FC_GeneralError, - "Cannot add an object from another document to this group"); + if (docObj->getDocumentObjectPtr()->getDocument() != getFeaturePathCompoundPtr()->getDocument()) { + PyErr_SetString( + Base::PyExc_FC_GeneralError, + "Cannot add an object from another document to this group" + ); return nullptr; } if (docObj->getDocumentObjectPtr() == this->getFeaturePathCompoundPtr()) { @@ -93,15 +93,15 @@ PyObject* FeaturePathCompoundPy::removeObject(PyObject* args) } DocumentObjectPy* docObj = static_cast(object); - if (!docObj->getDocumentObjectPtr() - || !docObj->getDocumentObjectPtr()->isAttachedToDocument()) { + if (!docObj->getDocumentObjectPtr() || !docObj->getDocumentObjectPtr()->isAttachedToDocument()) { PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot remove an invalid object"); return nullptr; } - if (docObj->getDocumentObjectPtr()->getDocument() - != getFeaturePathCompoundPtr()->getDocument()) { - PyErr_SetString(Base::PyExc_FC_GeneralError, - "Cannot remove an object from another document from this group"); + if (docObj->getDocumentObjectPtr()->getDocument() != getFeaturePathCompoundPtr()->getDocument()) { + PyErr_SetString( + Base::PyExc_FC_GeneralError, + "Cannot remove an object from another document from this group" + ); return nullptr; } diff --git a/src/Mod/CAM/App/FeaturePathShape.cpp b/src/Mod/CAM/App/FeaturePathShape.cpp index 36f481a347..3b6f7cef13 100644 --- a/src/Mod/CAM/App/FeaturePathShape.cpp +++ b/src/Mod/CAM/App/FeaturePathShape.cpp @@ -38,11 +38,7 @@ PARAM_ENUM_STRING_DECLARE(static const char* Enums, AREA_PARAMS_PATH) FeatureShape::FeatureShape() { ADD_PROPERTY(Sources, (nullptr)); - ADD_PROPERTY_TYPE(StartPoint, - (Base::Vector3d()), - "Path", - App::Prop_None, - "Feed start position"); + ADD_PROPERTY_TYPE(StartPoint, (Base::Vector3d()), "Path", App::Prop_None, "Feed start position"); ADD_PROPERTY_TYPE(UseStartPoint, (false), "Path", App::Prop_None, "Enable feed start position"); PARAM_PROP_ADD("Path", AREA_PARAMS_PATH); PARAM_PROP_SET_ENUM(Enums, AREA_PARAMS_PATH); @@ -75,11 +71,13 @@ App::DocumentObjectExecReturn* FeatureShape::execute() shapes.push_back(shape); } - Area::toPath(path, - shapes, - UseStartPoint.getValue() ? &pstart : nullptr, - nullptr, - PARAM_PROP_ARGS(AREA_PARAMS_PATH)); + Area::toPath( + path, + shapes, + UseStartPoint.getValue() ? &pstart : nullptr, + nullptr, + PARAM_PROP_ARGS(AREA_PARAMS_PATH) + ); Path.setValue(path); return App::DocumentObject::StdReturn; diff --git a/src/Mod/CAM/App/ParamsHelper.h b/src/Mod/CAM/App/ParamsHelper.h index 531b7ca8f1..8fac1612ba 100644 --- a/src/Mod/CAM/App/ParamsHelper.h +++ b/src/Mod/CAM/App/ParamsHelper.h @@ -355,12 +355,12 @@ #define PARAM_DECLARE_INIT(_src, _seq) BOOST_PP_SEQ_FOR_EACH(PARAM_DECLARE_INIT_, _src, _seq) -#define PARAM_ENUM_DECLARE_enum_(_1, _name, _i, _elem) \ +#define PARAM_ENUM_DECLARE_enum_(_1, _name, _i, _elem) \ BOOST_PP_COMMA_IF(_i) BOOST_PP_CAT(_name, _elem) -#define PARAM_ENUM_DECLARE_enum(_param) \ - enum \ - { \ +#define PARAM_ENUM_DECLARE_enum(_param) \ + enum \ + { \ BOOST_PP_SEQ_FOR_EACH_I(PARAM_ENUM_DECLARE_enum_, PARAM_FNAME(_param), PARAM_FSEQ(_param)) \ }; @@ -396,23 +396,22 @@ #define PARAM_ENUM_CONVERT_enum(...) #define PARAM_ENUM_CONVERT_enum2 PARAM_ENUM_CONVERT_SINGLE -#define PARAM_ENUM_CONVERT_enum_(_dst, _name, _prefix, _elem) \ - case BOOST_PP_CAT(_name, _elem): \ - _dst = BOOST_PP_CAT(_prefix, _elem); \ +#define PARAM_ENUM_CONVERT_enum_(_dst, _name, _prefix, _elem) \ + case BOOST_PP_CAT(_name, _elem): \ + _dst = BOOST_PP_CAT(_prefix, _elem); \ break; -#define PARAM_ENUM_CONVERT__(_1, _args, _i, _elem) \ - PARAM_ENUM_CONVERT_enum_(BOOST_PP_TUPLE_ELEM(0, _args), \ - BOOST_PP_TUPLE_ELEM(1, _args), \ - BOOST_PP_TUPLE_ELEM(2, _args), \ - _elem); +#define PARAM_ENUM_CONVERT__(_1, _args, _i, _elem) \ + PARAM_ENUM_CONVERT_enum_( \ + BOOST_PP_TUPLE_ELEM(0, _args), \ + BOOST_PP_TUPLE_ELEM(1, _args), \ + BOOST_PP_TUPLE_ELEM(2, _args), \ + _elem \ + ); -#define PARAM_ENUM_CONVERT_(_1, _args, _param) \ - PARAM_TYPED(PARAM_ENUM_CONVERT_, _param) \ - (BOOST_PP_TUPLE_ELEM(0, _args), \ - BOOST_PP_TUPLE_ELEM(1, _args), \ - BOOST_PP_TUPLE_ELEM(2, _args), \ - _param) +#define PARAM_ENUM_CONVERT_(_1, _args, _param) \ + PARAM_TYPED(PARAM_ENUM_CONVERT_, _param) \ + (BOOST_PP_TUPLE_ELEM(0, _args), BOOST_PP_TUPLE_ELEM(1, _args), BOOST_PP_TUPLE_ELEM(2, _args), _param) /** Convert single enum parameter value into user defined enum type * @@ -421,18 +420,20 @@ * for more detail. Make sure the outer parenthesis of \c _param is stripped, * i.e. not double but single parenthesis */ -#define PARAM_ENUM_CONVERT_SINGLE(_src, _dst, _default, _param) \ - PARAM_FENUM_TYPE(_param) _dst(_param); \ - switch (_src(_param)) { \ - BOOST_PP_SEQ_FOR_EACH_I(PARAM_ENUM_CONVERT__, \ - (_dst(_param), PARAM_FNAME(_param), PARAM_FENUM_PREFIX(_param)), \ - PARAM_FSEQ(_param)) \ - default: \ - _default(_param); \ +#define PARAM_ENUM_CONVERT_SINGLE(_src, _dst, _default, _param) \ + PARAM_FENUM_TYPE(_param) _dst(_param); \ + switch (_src(_param)) { \ + BOOST_PP_SEQ_FOR_EACH_I( \ + PARAM_ENUM_CONVERT__, \ + (_dst(_param), PARAM_FNAME(_param), PARAM_FENUM_PREFIX(_param)), \ + PARAM_FSEQ(_param) \ + ) \ + default: \ + _default(_param); \ } /** Default handling in #PARAM_ENUM_CONVERT and #PARAM_ENUM_CHECK*/ -#define PARAM_ENUM_EXCEPT(_param) \ +#define PARAM_ENUM_EXCEPT(_param) \ throw Base::ValueError("invalid value for enum " PARAM_FNAME_STR(_param)) /** @} */ @@ -500,7 +501,7 @@ * The above code assumes you've already defined \a Test1 and \a Test2 some * where as the source variable. */ -#define PARAM_ENUM_CONVERT(_src, _dst, _default, _seq) \ +#define PARAM_ENUM_CONVERT(_src, _dst, _default, _seq) \ BOOST_PP_SEQ_FOR_EACH(PARAM_ENUM_CONVERT_, (_src, _dst, _default), _seq) @@ -511,19 +512,19 @@ #define PARAM_ENUM_CHECK_enum PARAM_ENUM_CHECK_SINGLE #define PARAM_ENUM_CHECK_enum2 PARAM_ENUM_CHECK_SINGLE -#define PARAM_ENUM_CHECK_enum_(_1, _name, _i, _elem) \ - case BOOST_PP_CAT(_name, _elem): \ +#define PARAM_ENUM_CHECK_enum_(_1, _name, _i, _elem) \ + case BOOST_PP_CAT(_name, _elem): \ break; -#define PARAM_ENUM_CHECK_(_1, _args, _param) \ - PARAM_TYPED(PARAM_ENUM_CHECK_, _param) \ +#define PARAM_ENUM_CHECK_(_1, _args, _param) \ + PARAM_TYPED(PARAM_ENUM_CHECK_, _param) \ (BOOST_PP_TUPLE_ELEM(0, _args), BOOST_PP_TUPLE_ELEM(1, _args), _param) -#define PARAM_ENUM_CHECK_SINGLE(_src, _default, _param) \ - switch (_src(_param)) { \ - BOOST_PP_SEQ_FOR_EACH_I(PARAM_ENUM_CHECK_enum_, PARAM_FNAME(_param), PARAM_FSEQ(_param)) \ - default: \ - _default(_param); \ +#define PARAM_ENUM_CHECK_SINGLE(_src, _default, _param) \ + switch (_src(_param)) { \ + BOOST_PP_SEQ_FOR_EACH_I(PARAM_ENUM_CHECK_enum_, PARAM_FNAME(_param), PARAM_FSEQ(_param)) \ + default: \ + _default(_param); \ } /* Validate enum type parameters @@ -545,7 +546,7 @@ * * \arg \c _seq: Parameter sequence */ -#define PARAM_ENUM_CHECK(_src, _default, _seq) \ +#define PARAM_ENUM_CHECK(_src, _default, _seq) \ BOOST_PP_SEQ_FOR_EACH(PARAM_ENUM_CHECK_, (_src, _default), _seq) @@ -556,11 +557,11 @@ #define PARAM_ENUM_STRING_DECLARE_enum2 PARAM_ENUM_STRING_DECLARE_enum /** Helper for #PARAM_ENUM_STRING_DECLARE */ -#define PARAM_ENUM_STRING_DECLARE_enum(_prefix, _param) \ +#define PARAM_ENUM_STRING_DECLARE_enum(_prefix, _param) \ BOOST_PP_CAT(_prefix, PARAM_FNAME(_param))[] = {PARAM_FSEQ_STR(_param), NULL}; /** Helper for #PARAM_ENUM_STRING_DECLARE */ -#define PARAM_ENUM_STRING_DECLARE_(_1, _prefix, _param) \ +#define PARAM_ENUM_STRING_DECLARE_(_1, _prefix, _param) \ PARAM_TYPED(PARAM_ENUM_STRING_DECLARE_, _param)(_prefix, _param) /** Make \c enum string list @@ -575,7 +576,7 @@ * PARAM_ENUM_STRING_DECLARE(static const char *Enum, MyParamsSeq) * \ingroup ParamEnumHelper */ -#define PARAM_ENUM_STRING_DECLARE(_prefix, _seq) \ +#define PARAM_ENUM_STRING_DECLARE(_prefix, _seq) \ BOOST_PP_SEQ_FOR_EACH(PARAM_ENUM_STRING_DECLARE_, _prefix, _seq) @@ -597,8 +598,8 @@ /** Helper for #PARAM_OP */ -#define PARAM_OP_(_, _args, _param) \ - BOOST_PP_TUPLE_ELEM(0, _args) \ +#define PARAM_OP_(_, _args, _param) \ + BOOST_PP_TUPLE_ELEM(0, _args) \ (_param) BOOST_PP_TUPLE_ELEM(1, _args) BOOST_PP_TUPLE_ELEM(2, _args)(_param); /** Perform operation on two instance of each parameter in a sequence @@ -622,7 +623,7 @@ /** Helper for #PARAM_ARGS_DEF */ -#define PARAM_ARGS_DEF_(_, _src, _i, _param) \ +#define PARAM_ARGS_DEF_(_, _src, _i, _param) \ BOOST_PP_COMMA_IF(_i) PARAM_TYPE(_param) _src(_param) = PARAM_FDEF(_param) /** Declare the parameters as function argument list with defaults. @@ -670,13 +671,13 @@ #define PARAM_PY_DOC_enum_(_i, _elem) BOOST_PP_IF(_i, ",", " ") #_i "=" #_elem /** Generate doc for an enum parameter */ -#define PARAM_PY_DOC_enum(_field, _param) \ - "\n* " PARAM_FIELD_STR(_field, _param) "(" PARAM_FDEF_STR(_param) "):" PARAM_FOREACH_I( \ - PARAM_PY_DOC_enum_, \ - PARAM_FSEQ(_param)) ". " PARAM_FDOC(_param) "\n" +#define PARAM_PY_DOC_enum(_field, _param) \ + "\n* " PARAM_FIELD_STR(_field, _param) "(" PARAM_FDEF_STR( \ + _param \ + ) "):" PARAM_FOREACH_I(PARAM_PY_DOC_enum_, PARAM_FSEQ(_param)) ". " PARAM_FDOC(_param) "\n" /* Generate doc for other type of parameter */ -#define PARAM_PY_DOC_short(_field, _param) \ +#define PARAM_PY_DOC_short(_field, _param) \ "\n* " PARAM_FIELD_STR(_field, _param) "(" PARAM_FDEF_STR(_param) "): " PARAM_FDOC(_param) "\n" #define PARAM_PY_DOC_long PARAM_PY_DOC_short #define PARAM_PY_DOC_double PARAM_PY_DOC_short @@ -692,7 +693,7 @@ /** Helper for #PARAM_PY_ARGS_DOC */ -#define PARAM_PY_ARGS_DOC_(_, _field, _i, _param) \ +#define PARAM_PY_ARGS_DOC_(_, _field, _i, _param) \ BOOST_PP_IF(_i, ", ", " ") PARAM_FIELD_STR(_field, _param) "=" PARAM_FDEF_STR(_param) /** Generate argument list string @@ -741,7 +742,7 @@ /** Helper for #PARAM_PY_FIELDS */ -#define PARAM_PY_FIELDS_(_1, _src, _i, _param) \ +#define PARAM_PY_FIELDS_(_1, _src, _i, _param) \ BOOST_PP_COMMA_IF(_i) PARAM_TYPED(PARAM_CAST_PY_, _param)(_src(_param)) /** Expand to a comma separated list of the given field in the sequence @@ -756,13 +757,13 @@ /** Helper for #PARAM_FIELD_STRINGS */ -#define PARAM_FIELD_STRINGS_(_1, _field, _i, _param) \ +#define PARAM_FIELD_STRINGS_(_1, _field, _i, _param) \ BOOST_PP_COMMA_IF(_i) PARAM_FIELD_STR(_field, _param) /** Expand to a list of stringified fields * \ingroup ParamStringizer ParamPy */ -#define PARAM_FIELD_STRINGS(_field, _seq) \ +#define PARAM_FIELD_STRINGS(_field, _seq) \ BOOST_PP_SEQ_FOR_EACH_I(PARAM_FIELD_STRINGS_, _field, _seq) @@ -804,8 +805,8 @@ #define PARAM_PY_INIT_enum2(_v) _v /** Helper for #PARAM_PY_DECLARE_INIT */ -#define PARAM_PY_DECLARE_INIT_(_1, _src, _param) \ - PARAM_TYPED(PARAM_PY_TYPE_, _param) \ +#define PARAM_PY_DECLARE_INIT_(_1, _src, _param) \ + PARAM_TYPED(PARAM_PY_TYPE_, _param) \ _src(_param) = PARAM_TYPED(PARAM_PY_INIT_, _param)(PARAM_FDEF(_param)); /** Declare field variables of Python c type with initialization to default @@ -845,10 +846,12 @@ #define PARAM_PY_STR(_field, _param) PyUnicode_FromString(PARAM_FIELD_STR(_field, _param)) /** Helper for #PARAM_PY_DICT_SET_VALUE */ -#define PARAM_PY_DICT_SET_VALUE_(_1, _args, _param) \ - PyDict_SetItem(BOOST_PP_TUPLE_ELEM(0, _args), \ - PARAM_PY_STR(BOOST_PP_TUPLE_ELEM(1, _args), _param), \ - PARAM_TYPED(PARAM_CAST_PYOBJ_, _param)(BOOST_PP_TUPLE_ELEM(2, _args)(_param))); +#define PARAM_PY_DICT_SET_VALUE_(_1, _args, _param) \ + PyDict_SetItem( \ + BOOST_PP_TUPLE_ELEM(0, _args), \ + PARAM_PY_STR(BOOST_PP_TUPLE_ELEM(1, _args), _param), \ + PARAM_TYPED(PARAM_CAST_PYOBJ_, _param)(BOOST_PP_TUPLE_ELEM(2, _args)(_param)) \ + ); /** Populate a Python dict with a structure variable * @@ -865,17 +868,17 @@ * \endcode * \ingroup ParamPy */ -#define PARAM_PY_DICT_SET_VALUE(_dict, _field, _src, _seq) \ +#define PARAM_PY_DICT_SET_VALUE(_dict, _field, _src, _seq) \ BOOST_PP_SEQ_FOR_EACH(PARAM_PY_DICT_SET_VALUE_, (_dict, _field, _src), _seq) #define PARAM_PY_DICT_DOC_enum_(_i, _elem) BOOST_PP_IF(_i, ",", " ") #_i "=" #_elem /** Generate doc for an enum parameter */ -#define PARAM_PY_DICT_DOC_enum(_param) \ - "(" PARAM_FDEF_STR(_param) ") - " PARAM_FOREACH_I( \ - PARAM_PY_DOC_enum_, \ - PARAM_FSEQ(_param)) ".\n" PARAM_FDOC(_param) "\n" +#define PARAM_PY_DICT_DOC_enum(_param) \ + "(" PARAM_FDEF_STR( \ + _param \ + ) ") - " PARAM_FOREACH_I(PARAM_PY_DOC_enum_, PARAM_FSEQ(_param)) ".\n" PARAM_FDOC(_param) "\n" /* Generate doc for other type of parameter */ #define PARAM_PY_DICT_DOC_(_param) "(" PARAM_FDEF_STR(_param) ") - " PARAM_FDOC(_param) "\n" @@ -888,10 +891,12 @@ #define PARAM_PY_DICT_DOC_enum2 PARAM_PY_DICT_DOC_enum /** Helper for #PARAM_PY_DICT_SET_DOC */ -#define PARAM_PY_DICT_SET_DOC_(_1, _args, _param) \ - PyDict_SetItem(BOOST_PP_TUPLE_ELEM(0, _args), \ - PARAM_PY_STR(BOOST_PP_TUPLE_ELEM(1, _args), _param), \ - PyUnicode_FromString(PARAM_TYPED(PARAM_PY_DICT_DOC_, _param)(_param))); +#define PARAM_PY_DICT_SET_DOC_(_1, _args, _param) \ + PyDict_SetItem( \ + BOOST_PP_TUPLE_ELEM(0, _args), \ + PARAM_PY_STR(BOOST_PP_TUPLE_ELEM(1, _args), _param), \ + PyUnicode_FromString(PARAM_TYPED(PARAM_PY_DICT_DOC_, _param)(_param)) \ + ); /** Populate a Python dict with the doc field of the parameter sequence * @@ -906,7 +911,7 @@ * \endcode * \ingroup ParamDoc */ -#define PARAM_PY_DICT_SET_DOC(_dict, _field, _seq) \ +#define PARAM_PY_DICT_SET_DOC(_dict, _field, _seq) \ BOOST_PP_SEQ_FOR_EACH(PARAM_PY_DICT_SET_DOC_, (_dict, _field), _seq) @@ -931,22 +936,25 @@ #define PARAM_PROP_DECLARE(_seq) PARAM_FOREACH(PARAM_PROP_DECLARE_, _seq) /** Replace FreeCAD #ADD_PROPERTY_TYPE to fix singifying macro */ -#define PARAM_ADD_PROPERTY_TYPE(_prop_, _defaultval_, _group_, _type_, _Docu_) \ - do { \ - this->_prop_.setValue _defaultval_; \ - this->_prop_.setContainer(this); \ - propertyData.addProperty( \ - static_cast(this), \ - BOOST_PP_STRINGIZE(_prop_), &this->_prop_, (_group_), (_type_), (_Docu_)); \ +#define PARAM_ADD_PROPERTY_TYPE(_prop_, _defaultval_, _group_, _type_, _Docu_) \ + do { \ + this->_prop_.setValue _defaultval_; \ + this->_prop_.setContainer(this); \ + propertyData.addProperty( \ + static_cast(this), \ + BOOST_PP_STRINGIZE(_prop_), &this->_prop_, (_group_), (_type_), (_Docu_) \ + ); \ } while (0) /** Generic property adding */ -#define PARAM_PROP_ADD_(_group, _param) \ - PARAM_ADD_PROPERTY_TYPE(PARAM_FNAME(_param), \ - (PARAM_FDEF(_param)), \ - _group, \ - App::Prop_None, \ - PARAM_FDOC(_param)); +#define PARAM_PROP_ADD_(_group, _param) \ + PARAM_ADD_PROPERTY_TYPE( \ + PARAM_FNAME(_param), \ + (PARAM_FDEF(_param)), \ + _group, \ + App::Prop_None, \ + PARAM_FDOC(_param) \ + ); #define PARAM_PROP_ADD_short PARAM_PROP_ADD_ #define PARAM_PROP_ADD_long PARAM_PROP_ADD_ @@ -955,15 +963,17 @@ #define PARAM_PROP_ADD_enum2 PARAM_PROP_ADD_enum /** Add \c enum type parameter as property */ -#define PARAM_PROP_ADD_enum(_group, _param) \ - PARAM_ADD_PROPERTY_TYPE(PARAM_FNAME(_param), \ - ((long)PARAM_FDEF(_param)), \ - _group, \ - App::Prop_None, \ - PARAM_FDOC(_param)); +#define PARAM_PROP_ADD_enum(_group, _param) \ + PARAM_ADD_PROPERTY_TYPE( \ + PARAM_FNAME(_param), \ + ((long)PARAM_FDEF(_param)), \ + _group, \ + App::Prop_None, \ + PARAM_FDOC(_param) \ + ); /** Helper for #PARAM_PROP_ADD */ -#define PARAM_PROP_ADD_TYPED(_1, _group, _i, _param) \ +#define PARAM_PROP_ADD_TYPED(_1, _group, _i, _param) \ PARAM_TYPED(PARAM_PROP_ADD_, _param)(_group, _param) /** Add FreeCAD properties @@ -978,17 +988,17 @@ #define PARAM_PROP_SET_ENUM_enum2 PARAM_PROP_SET_ENUM_enum /** Setup \c enum type parameter */ -#define PARAM_PROP_SET_ENUM_enum(_prefix, _param) \ +#define PARAM_PROP_SET_ENUM_enum(_prefix, _param) \ PARAM_FNAME(_param).setEnums(BOOST_PP_CAT(_prefix, PARAM_FNAME(_param))); /** Helper for #PARAM_PROP_SET_ENUM */ -#define PARAM_PROP_SET_ENUM_TYPED(_1, _prefix, _param) \ +#define PARAM_PROP_SET_ENUM_TYPED(_1, _prefix, _param) \ PARAM_TYPED(PARAM_PROP_SET_ENUM_, _param)(_prefix, _param) /* Setup the \c enum string list for \c enum type properties * \ingroup ParamProperty */ -#define PARAM_PROP_SET_ENUM(_prefix, _seq) \ +#define PARAM_PROP_SET_ENUM(_prefix, _seq) \ BOOST_PP_SEQ_FOR_EACH(PARAM_PROP_SET_ENUM_TYPED, _prefix, _seq) @@ -1007,8 +1017,8 @@ /** Helper for #PARAM_PROP_TOUCHED */ -#define PARAM_PROP_TOUCHED_(_param) \ - if (PARAM_FNAME(_param).isTouched()) \ +#define PARAM_PROP_TOUCHED_(_param) \ + if (PARAM_FNAME(_param).isTouched()) \ return 1; /** Returns 1 if any properties is touched diff --git a/src/Mod/CAM/App/Path.cpp b/src/Mod/CAM/App/Path.cpp index be3c9cf1fb..c2e7795b2c 100644 --- a/src/Mod/CAM/App/Path.cpp +++ b/src/Mod/CAM/App/Path.cpp @@ -152,7 +152,8 @@ double Toolpath::getCycleTime(double hFeed, double vFeed, double hRapid, double // check the feedrates are set if ((hFeed == 0) || (vFeed == 0)) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/CAM"); + "User parameter:BaseApp/Preferences/Mod/CAM" + ); if (!hGrp->GetBool("WarningsSuppressAllSpeeds", true)) { Base::Console().warning("Feed Rate Error: Check Tool Controllers have Feed Rates"); } @@ -222,31 +223,37 @@ public: BoundBoxSegmentVisitor() {} - void g0(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) override + void g0( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ) override { (void)id; processPt(last); processPts(pts); processPt(next); } - void g1(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) override + void g1( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ) override { (void)id; processPt(last); processPts(pts); processPt(next); } - void g23(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const Base::Vector3d& center) override + void g23( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const Base::Vector3d& center + ) override { (void)id; (void)center; @@ -254,12 +261,14 @@ public: processPts(pts); processPt(next); } - void g8x(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const std::deque& p, - const std::deque& q) override + void g8x( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const std::deque& p, + const std::deque& q + ) override { (void)id; (void)q; // always within the bounds of p @@ -304,8 +313,7 @@ Base::BoundBox3d Toolpath::getBoundBox() const return visitor.bb; } -static void -bulkAddCommand(const std::string& gcodestr, std::vector& commands, bool& inches) +static void bulkAddCommand(const std::string& gcodestr, std::vector& commands, bool& inches) { Command* cmd = new Command(); cmd->setFromGCode(gcodestr); diff --git a/src/Mod/CAM/App/Path.h b/src/Mod/CAM/App/Path.h index 7647630669..38a6e43721 100644 --- a/src/Mod/CAM/App/Path.h +++ b/src/Mod/CAM/App/Path.h @@ -62,9 +62,8 @@ public: double getLength(); // return the Length (mm) of the Path double getCycleTime(double, double, double, double); // return the Cycle Time (s) of the Path void recalculate(); // recalculates the points - void - setFromGCode(const std::string); // sets the path from the contents of the given GCode string - std::string toGCode() const; // gets a gcode string representation from the Path + void setFromGCode(const std::string); // sets the path from the contents of the given GCode string + std::string toGCode() const; // gets a gcode string representation from the Path Base::BoundBox3d getBoundBox() const; // shortcut functions diff --git a/src/Mod/CAM/App/PathPyImp.cpp b/src/Mod/CAM/App/PathPyImp.cpp index 032ffddf47..41f44cf253 100644 --- a/src/Mod/CAM/App/PathPyImp.cpp +++ b/src/Mod/CAM/App/PathPyImp.cpp @@ -62,8 +62,7 @@ int PathPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::List list(pcObj); for (Py::List::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Path::CommandPy::Type))) { - Path::Command& cmd = - *static_cast((*it).ptr())->getCommandPtr(); + Path::Command& cmd = *static_cast((*it).ptr())->getCommandPtr(); getToolpathPtr()->addCommand(cmd); } else { @@ -91,7 +90,8 @@ Py::List PathPy::getCommands() const Py::List list; for (unsigned int i = 0; i < getToolpathPtr()->getSize(); i++) { list.append( - Py::asObject(new Path::CommandPy(new Path::Command(getToolpathPtr()->getCommand(i))))); + Py::asObject(new Path::CommandPy(new Path::Command(getToolpathPtr()->getCommand(i)))) + ); } return list; } diff --git a/src/Mod/CAM/App/PathSegmentWalker.cpp b/src/Mod/CAM/App/PathSegmentWalker.cpp index d9324c9b68..e948f8b546 100644 --- a/src/Mod/CAM/App/PathSegmentWalker.cpp +++ b/src/Mod/CAM/App/PathSegmentWalker.cpp @@ -36,9 +36,11 @@ namespace Path { -Base::Vector3d compensateRotation(const Base::Vector3d& pt, - const Base::Rotation& rot, - const Base::Vector3d& center) +Base::Vector3d compensateRotation( + const Base::Vector3d& pt, + const Base::Rotation& rot, + const Base::Vector3d& center +) { Base::Vector3d ptRotated; rot.multVec(pt - center, ptRotated); @@ -60,10 +62,12 @@ void PathSegmentVisitor::setup(const Base::Vector3d& last) (void)last; } -void PathSegmentVisitor::g0(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) +void PathSegmentVisitor::g0( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts +) { (void)id; (void)last; @@ -71,10 +75,12 @@ void PathSegmentVisitor::g0(int id, (void)pts; } -void PathSegmentVisitor::g1(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) +void PathSegmentVisitor::g1( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts +) { (void)id; (void)last; @@ -82,11 +88,13 @@ void PathSegmentVisitor::g1(int id, (void)pts; } -void PathSegmentVisitor::g23(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const Base::Vector3d& center) +void PathSegmentVisitor::g23( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const Base::Vector3d& center +) { (void)id; (void)last; @@ -95,12 +103,14 @@ void PathSegmentVisitor::g23(int id, (void)center; } -void PathSegmentVisitor::g8x(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const std::deque& p, - const std::deque& q) +void PathSegmentVisitor::g8x( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const std::deque& p, + const std::deque& q +) { (void)id; (void)last; @@ -129,7 +139,8 @@ void PathSegmentWalker::walk(PathSegmentVisitor& cb, const Base::Vector3d& start } ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Part"); + "User parameter:BaseApp/Preferences/Mod/Part" + ); float deviation = hGrp->GetFloat("MeshDeviation", 0.2); Base::Vector3d rotCenter = tp.getCenter(); @@ -186,8 +197,10 @@ void PathSegmentWalker::walk(PathSegmentVisitor& cb, const Base::Vector3d& start if ((name == "G0") || (name == "G00") || (name == "G1") || (name == "G01")) { // straight line if (nrot != lrot) { - double amax = std::max(fmod(fabs(a - A), 360), - std::max(fmod(fabs(b - B), 360), fmod(fabs(c - C), 360))); + double amax = std::max( + fmod(fabs(a - A), 360), + std::max(fmod(fabs(b - B), 360), fmod(fabs(c - C), 360)) + ); double angle = Base::toRadians(amax); int segments = std::max(ARC_MIN_SEGMENTS, 3.0 / (deviation / angle)); @@ -262,14 +275,15 @@ void PathSegmentWalker::walk(PathSegmentVisitor& cb, const Base::Vector3d& start angle = std::numbers::pi * 2; } - double amax = std::max(fmod(fabs(a - A), 360), - std::max(fmod(fabs(b - B), 360), fmod(fabs(c - C), 360))); + double amax = std::max( + fmod(fabs(a - A), 360), + std::max(fmod(fabs(b - B), 360), fmod(fabs(c - C), 360)) + ); int segments = std::max( ARC_MIN_SEGMENTS, - 3.0 - / (deviation - / std::max(angle, amax))); // we use a rather simple rule here, provisorily + 3.0 / (deviation / std::max(angle, amax)) + ); // we use a rather simple rule here, provisorily double dZ = (next.*pz - last.*pz) / segments; // How far each segment will helix in Z double dangle = angle / segments; @@ -329,8 +343,10 @@ void PathSegmentWalker::walk(PathSegmentVisitor& cb, const Base::Vector3d& start p1.*pz = last.*pz; if (nrot != lrot) { - double amax = std::max(fmod(fabs(a - A), 360), - std::max(fmod(fabs(b - B), 360), fmod(fabs(c - C), 360))); + double amax = std::max( + fmod(fabs(a - A), 360), + std::max(fmod(fabs(b - B), 360), fmod(fabs(c - C), 360)) + ); double angle = Base::toRadians(amax); int segments = std::max(ARC_MIN_SEGMENTS, 3.0 / (deviation / angle)); diff --git a/src/Mod/CAM/App/PathSegmentWalker.h b/src/Mod/CAM/App/PathSegmentWalker.h index 96c4c2f8fb..99d68a4251 100644 --- a/src/Mod/CAM/App/PathSegmentWalker.h +++ b/src/Mod/CAM/App/PathSegmentWalker.h @@ -44,25 +44,33 @@ public: virtual void setup(const Base::Vector3d& last); - virtual void g0(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts); - virtual void g1(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts); - virtual void g23(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const Base::Vector3d& center); - virtual void g8x(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const std::deque& p, - const std::deque& q); + virtual void g0( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ); + virtual void g1( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ); + virtual void g23( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const Base::Vector3d& center + ); + virtual void g8x( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const std::deque& p, + const std::deque& q + ); virtual void g38(int id, const Base::Vector3d& last, const Base::Vector3d& next); }; diff --git a/src/Mod/CAM/App/Voronoi.cpp b/src/Mod/CAM/App/Voronoi.cpp index eac3a4f071..54691e140d 100644 --- a/src/Mod/CAM/App/Voronoi.cpp +++ b/src/Mod/CAM/App/Voronoi.cpp @@ -112,8 +112,9 @@ void Voronoi::diagram_type::reIndex() } } -Voronoi::point_type -Voronoi::diagram_type::retrievePoint(const Voronoi::diagram_type::cell_type* cell) const +Voronoi::point_type Voronoi::diagram_type::retrievePoint( + const Voronoi::diagram_type::cell_type* cell +) const { Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index(); Voronoi::diagram_type::cell_type::source_category_type category = cell->source_category(); @@ -129,11 +130,11 @@ Voronoi::diagram_type::retrievePoint(const Voronoi::diagram_type::cell_type* cel } } -Voronoi::segment_type -Voronoi::diagram_type::retrieveSegment(const Voronoi::diagram_type::cell_type* cell) const +Voronoi::segment_type Voronoi::diagram_type::retrieveSegment( + const Voronoi::diagram_type::cell_type* cell +) const { - Voronoi::diagram_type::cell_type::source_index_type index = - cell->source_index() - points.size(); + Voronoi::diagram_type::cell_type::source_index_type index = cell->source_index() - points.size(); return segments[index]; } @@ -195,11 +196,13 @@ long Voronoi::numVertices() const void Voronoi::construct() { vd->clear(); - construct_voronoi(vd->points.begin(), - vd->points.end(), - vd->segments.begin(), - vd->segments.end(), - static_cast(vd)); + construct_voronoi( + vd->points.begin(), + vd->points.end(), + vd->segments.begin(), + vd->segments.end(), + static_cast(vd) + ); vd->reIndex(); } @@ -225,8 +228,7 @@ void Voronoi::colorExterior(const Voronoi::diagram_type::edge_type* edge, std::s void Voronoi::colorExterior(Voronoi::color_type color) { - for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); - ++it) { + for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) { if (it->is_infinite()) { colorExterior(&(*it), color); } @@ -235,8 +237,7 @@ void Voronoi::colorExterior(Voronoi::color_type color) void Voronoi::colorTwins(Voronoi::color_type color) { - for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); - ++it) { + for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) { if (!it->color()) { auto twin = it->twin(); if (!twin->color()) { @@ -248,8 +249,9 @@ void Voronoi::colorTwins(Voronoi::color_type color) double Voronoi::diagram_type::angleOfSegment(int i, Voronoi::diagram_type::angle_map_t* angle) const { - Voronoi::diagram_type::angle_map_t::const_iterator a = - angle ? angle->find(i) : Voronoi::diagram_type::angle_map_t::const_iterator(); + Voronoi::diagram_type::angle_map_t::const_iterator a = angle + ? angle->find(i) + : Voronoi::diagram_type::angle_map_t::const_iterator(); if (!angle || a == angle->end()) { Voronoi::point_type p0 = low(segments[i]); Voronoi::point_type p1 = high(segments[i]); @@ -294,8 +296,7 @@ void Voronoi::colorColinear(Voronoi::color_type color, double degree) Voronoi::diagram_type::angle_map_t angle; int psize = vd->points.size(); - for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); - ++it) { + for (diagram_type::const_edge_iterator it = vd->edges().begin(); it != vd->edges().end(); ++it) { int i0 = it->cell()->source_index() - psize; int i1 = it->twin()->cell()->source_index() - psize; if (it->color() == 0 && it->cell()->contains_segment() diff --git a/src/Mod/CAM/App/VoronoiCellPyImp.cpp b/src/Mod/CAM/App/VoronoiCellPyImp.cpp index 70e516da74..963e60cc2a 100644 --- a/src/Mod/CAM/App/VoronoiCellPyImp.cpp +++ b/src/Mod/CAM/App/VoronoiCellPyImp.cpp @@ -78,8 +78,10 @@ PyObject* VoronoiCellPy::richCompare(PyObject* lhs, PyObject* rhs, int op) return cmp; } -const Voronoi::voronoi_diagram_type::cell_type* getCellFromPy(VoronoiCellPy* c, - bool throwIfNotBound = true) +const Voronoi::voronoi_diagram_type::cell_type* getCellFromPy( + VoronoiCellPy* c, + bool throwIfNotBound = true +) { auto self = c->getVoronoiCellPtr(); if (self->isBound()) { diff --git a/src/Mod/CAM/App/VoronoiEdgePyImp.cpp b/src/Mod/CAM/App/VoronoiEdgePyImp.cpp index 15032df5a4..97991af7e1 100644 --- a/src/Mod/CAM/App/VoronoiEdgePyImp.cpp +++ b/src/Mod/CAM/App/VoronoiEdgePyImp.cpp @@ -49,8 +49,10 @@ Voronoi::point_type pointFromVertex(const Voronoi::vertex_type v) return pt; } -Voronoi::point_type orthognalProjection(const Voronoi::point_type& point, - const Voronoi::segment_type& segment) +Voronoi::point_type orthognalProjection( + const Voronoi::point_type& point, + const Voronoi::segment_type& segment +) { // move segment so it goes through the origin (s) Voronoi::point_type offset; @@ -124,10 +126,12 @@ double signedDistanceBetween(const pt0_type& p0, const pt1_type& p1, double scal } -void addDistanceBetween(const Voronoi::diagram_type::vertex_type* v0, - const Voronoi::point_type& p1, - Py::List* list, - double scale) +void addDistanceBetween( + const Voronoi::diagram_type::vertex_type* v0, + const Voronoi::point_type& p1, + Py::List* list, + double scale +) { if (v0) { list->append(Py::Float(distanceBetween(*v0, p1, scale))); @@ -138,10 +142,12 @@ void addDistanceBetween(const Voronoi::diagram_type::vertex_type* v0, } } -void addProjectedDistanceBetween(const Voronoi::diagram_type::vertex_type* v0, - const Voronoi::segment_type& segment, - Py::List* list, - double scale) +void addProjectedDistanceBetween( + const Voronoi::diagram_type::vertex_type* v0, + const Voronoi::segment_type& segment, + Py::List* list, + double scale +) { if (v0) { Voronoi::point_type p0; @@ -158,10 +164,7 @@ void addProjectedDistanceBetween(const Voronoi::diagram_type::vertex_type* v0, } } -bool addDistancesToPoint(const VoronoiEdge* edge, - Voronoi::point_type p, - Py::List* list, - double scale) +bool addDistancesToPoint(const VoronoiEdge* edge, Voronoi::point_type p, Py::List* list, double scale) { addDistanceBetween(edge->ptr->vertex0(), p, list, scale); addDistanceBetween(edge->ptr->vertex1(), p, list, scale); @@ -190,9 +193,7 @@ bool pointsMatch(const Voronoi::point_type& p0, const Voronoi::point_type& p1, d return 1e-6 > distanceBetween(p0, p1, scale); } -bool isPointOnSegment(const Voronoi::point_type& point, - const Voronoi::segment_type& segment, - double scale) +bool isPointOnSegment(const Voronoi::point_type& point, const Voronoi::segment_type& segment, double scale) { return pointsMatch(point, low(segment), scale) || pointsMatch(point, high(segment), scale); } @@ -286,8 +287,10 @@ PyObject* VoronoiEdgePy::richCompare(PyObject* lhs, PyObject* rhs, int op) return cmp; } -const Voronoi::voronoi_diagram_type::edge_type* getEdgeFromPy(VoronoiEdgePy* e, - bool throwIfNotBound = true) +const Voronoi::voronoi_diagram_type::edge_type* getEdgeFromPy( + VoronoiEdgePy* e, + bool throwIfNotBound = true +) { auto self = e->getVoronoiEdgePtr(); if (self->isBound()) { diff --git a/src/Mod/CAM/App/VoronoiPyImp.cpp b/src/Mod/CAM/App/VoronoiPyImp.cpp index c18ece0757..d31c2c02a6 100644 --- a/src/Mod/CAM/App/VoronoiPyImp.cpp +++ b/src/Mod/CAM/App/VoronoiPyImp.cpp @@ -176,11 +176,13 @@ using coordinate_map_t = std::map>; #define VORONOI_USE_EXTERIOR_CACHE 1 -static bool callbackWithVertex(Voronoi::diagram_type* dia, - PyObject* callback, - const Voronoi::diagram_type::vertex_type* v, - bool& bail, - exterior_map_t& cache) +static bool callbackWithVertex( + Voronoi::diagram_type* dia, + PyObject* callback, + const Voronoi::diagram_type::vertex_type* v, + bool& bail, + exterior_map_t& cache +) { bool rc = false; if (!bail && v->color() == 0) { @@ -275,8 +277,10 @@ PyObject* VoronoiPy::colorColinear(PyObject* args) Voronoi::color_type color = 0; double degree = 10.; if (!PyArg_ParseTuple(args, "k|d", &color, °ree)) { - throw Py::RuntimeError("colorColinear requires an integer (color) and optionally a " - "derivation in degrees argument (default 10)"); + throw Py::RuntimeError( + "colorColinear requires an integer (color) and optionally a " + "derivation in degrees argument (default 10)" + ); } getVoronoiPtr()->colorColinear(color, degree); @@ -306,8 +310,7 @@ PyObject* VoronoiPy::getPoints(PyObject* args) const Voronoi* vo = getVoronoiPtr(); Py::List list; for (auto it = vo->vd->points.begin(); it != vo->vd->points.end(); ++it) { - list.append( - Py::asObject(new Base::VectorPy(new Base::Vector3d(vo->vd->scaledVector(*it, z))))); + list.append(Py::asObject(new Base::VectorPy(new Base::Vector3d(vo->vd->scaledVector(*it, z))))); } return Py::new_reference_to(list); } diff --git a/src/Mod/CAM/App/VoronoiVertexPyImp.cpp b/src/Mod/CAM/App/VoronoiVertexPyImp.cpp index 89c0bc2c83..f27726601f 100644 --- a/src/Mod/CAM/App/VoronoiVertexPyImp.cpp +++ b/src/Mod/CAM/App/VoronoiVertexPyImp.cpp @@ -79,8 +79,10 @@ PyObject* VoronoiVertexPy::richCompare(PyObject* lhs, PyObject* rhs, int op) return cmp; } -const Voronoi::voronoi_diagram_type::vertex_type* getVertexFromPy(VoronoiVertexPy* v, - bool throwIfNotBound = true) +const Voronoi::voronoi_diagram_type::vertex_type* getVertexFromPy( + VoronoiVertexPy* v, + bool throwIfNotBound = true +) { auto self = v->getVoronoiVertexPtr(); if (self->isBound()) { @@ -155,9 +157,9 @@ PyObject* VoronoiVertexPy::toPoint(PyObject* args) const } VoronoiVertex* v = getVoronoiVertexPtr(); if (v->isBound()) { - return new Base::VectorPy(new Base::Vector3d(v->ptr->x() / v->dia->getScale(), - v->ptr->y() / v->dia->getScale(), - z)); + return new Base::VectorPy( + new Base::Vector3d(v->ptr->x() / v->dia->getScale(), v->ptr->y() / v->dia->getScale(), z) + ); } Py_INCREF(Py_None); return Py_None; diff --git a/src/Mod/CAM/Gui/AppPathGuiPy.cpp b/src/Mod/CAM/Gui/AppPathGuiPy.cpp index 9aaeb78627..711971a8c3 100644 --- a/src/Mod/CAM/Gui/AppPathGuiPy.cpp +++ b/src/Mod/CAM/Gui/AppPathGuiPy.cpp @@ -47,17 +47,17 @@ public: Module() : Py::ExtensionModule("PathGui") { - add_varargs_method("open", - &Module::open, - "open(filename): Opens a GCode file as a new document"); + add_varargs_method("open", &Module::open, "open(filename): Opens a GCode file as a new document"); add_varargs_method( "insert", &Module::insert, - "insert(filename,docname): Imports a given GCode file into the given document"); + "insert(filename,docname): Imports a given GCode file into the given document" + ); add_varargs_method( "export", &Module::exporter, - "export(objectslist,filename): Exports a given list of Path objects to a GCode file"); + "export(objectslist,filename): Exports a given list of Path objects to a GCode file" + ); initialize("This module is the PathGui module."); // register with Python } @@ -85,10 +85,10 @@ private: std::string path = App::Application::getHomePath(); path += "Mod/CAM/Path/Post/scripts/"; QDir dir1(QString::fromUtf8(path.c_str()), QStringLiteral("*_pre.py")); - std::string cMacroPath = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") - ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); + std::string cMacroPath + = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QStringLiteral("*_pre.py")); QFileInfoList list = dir1.entryInfoList(); list << dir2.entryInfoList(); @@ -158,10 +158,10 @@ private: std::string path = App::Application::getHomePath(); path += "Mod/CAM/Path/Post/scripts/"; QDir dir1(QString::fromUtf8(path.c_str()), QStringLiteral("*_pre.py")); - std::string cMacroPath = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") - ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); + std::string cMacroPath + = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QStringLiteral("*_pre.py")); QFileInfoList list = dir1.entryInfoList(); list << dir2.entryInfoList(); @@ -243,10 +243,10 @@ private: std::string path = App::Application::getHomePath(); path += "Mod/CAM/Path/Post/scripts/"; QDir dir1(QString::fromUtf8(path.c_str()), QStringLiteral("*_post.py")); - std::string cMacroPath = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") - ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); + std::string cMacroPath + = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Macro") + ->GetASCII("MacroPath", App::Application::getUserMacroDir().c_str()); QDir dir2(QString::fromUtf8(cMacroPath.c_str()), QStringLiteral("*_post.py")); QFileInfoList list = dir1.entryInfoList(); list << dir2.entryInfoList(); @@ -267,17 +267,17 @@ private: if (processor.empty()) { if (objlist.size() > 1) { throw Py::RuntimeError( - "Cannot export more than one object without using a post script"); + "Cannot export more than one object without using a post script" + ); } PyObject* item = objlist[0].ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = - static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); App::Document* doc = obj->getDocument(); Gui::Command::runCommand(Gui::Command::Gui, "import Path"); - cmd << "Path.write(FreeCAD.getDocument(\"" << doc->getName() - << "\").getObject(\"" << obj->getNameInDocument() << "\"),\"" << EncodedName - << "\")"; + cmd << "Path.write(FreeCAD.getDocument(\"" << doc->getName() << "\").getObject(\"" + << obj->getNameInDocument() << "\"),\"" << EncodedName << "\")"; Gui::Command::runCommand(Gui::Command::Gui, cmd.str().c_str()); } else { diff --git a/src/Mod/CAM/Gui/Command.cpp b/src/Mod/CAM/Gui/Command.cpp index ea08a52cff..6fb8c5c1b6 100644 --- a/src/Mod/CAM/Gui/Command.cpp +++ b/src/Mod/CAM/Gui/Command.cpp @@ -99,13 +99,17 @@ void CmdPathArea::activated(int iMsg) if (addView && !areaName.empty()) { std::string FeatName = getUniqueObjectName("FeatureAreaView"); openCommand(QT_TRANSLATE_NOOP("Command", "Create Path Area View")); - doCommand(Doc, - "FreeCAD.activeDocument().addObject('Path::FeatureAreaView','%s')", - FeatName.c_str()); - doCommand(Doc, - "FreeCAD.activeDocument().%s.Source = FreeCAD.activeDocument().%s", - FeatName.c_str(), - areaName.c_str()); + doCommand( + Doc, + "FreeCAD.activeDocument().addObject('Path::FeatureAreaView','%s')", + FeatName.c_str() + ); + doCommand( + Doc, + "FreeCAD.activeDocument().%s.Source = FreeCAD.activeDocument().%s", + FeatName.c_str(), + areaName.c_str() + ); commitCommand(); updateActive(); return; @@ -116,13 +120,13 @@ void CmdPathArea::activated(int iMsg) for (const std::string& cmd : cmds) { doCommand(Doc, "%s", cmd.c_str()); } - doCommand(Doc, - "FreeCAD.activeDocument().addObject('Path::FeatureArea','%s')", - FeatName.c_str()); - doCommand(Doc, - "FreeCAD.activeDocument().%s.Sources = [ %s ]", - FeatName.c_str(), - sources.str().c_str()); + doCommand(Doc, "FreeCAD.activeDocument().addObject('Path::FeatureArea','%s')", FeatName.c_str()); + doCommand( + Doc, + "FreeCAD.activeDocument().%s.Sources = [ %s ]", + FeatName.c_str(), + sources.str().c_str() + ); commitCommand(); updateActive(); } @@ -208,11 +212,13 @@ void CmdPathAreaWorkplane::activated(int iMsg) openCommand(QT_TRANSLATE_NOOP("Command", "Select Workplane for Path Area")); doCommand(Doc, "import PathCommands"); - doCommand(Doc, - "FreeCAD.activeDocument().%s.WorkPlane = PathCommands.findShape(" - "FreeCAD.activeDocument().%s)", - areaName.c_str(), - planeSubname.c_str()); + doCommand( + Doc, + "FreeCAD.activeDocument().%s.WorkPlane = PathCommands.findShape(" + "FreeCAD.activeDocument().%s)", + areaName.c_str(), + planeSubname.c_str() + ); doCommand(Doc, "FreeCAD.activeDocument().%s.ViewObject.Visibility = True", areaName.c_str()); commitCommand(); updateActive(); @@ -259,20 +265,20 @@ void CmdPathCompound::activated(int iMsg) } else { Base::Console().error( - "Only path objects must be selected before running this command\n"); + "Only path objects must be selected before running this command\n" + ); return; } } cmd << "]"; std::string FeatName = getUniqueObjectName("PathCompound"); openCommand(QT_TRANSLATE_NOOP("Command", "Create Path Compound")); - doCommand(Doc, - "FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')", - FeatName.c_str()); - doCommand(Doc, - "FreeCAD.activeDocument().%s.Group = %s", - FeatName.c_str(), - cmd.str().c_str()); + doCommand( + Doc, + "FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')", + FeatName.c_str() + ); + doCommand(Doc, "FreeCAD.activeDocument().%s.Group = %s", FeatName.c_str(), cmd.str().c_str()); commitCommand(); updateActive(); } @@ -320,9 +326,8 @@ void CmdPathShape::activated(int iMsg) } for (const std::string& name : subnames) { if (name.compare(0, 4, "Face") && name.compare(0, 4, "Edge")) { - Base::Console().warning("Ignored shape %s %s\n", - pcObj->getNameInDocument(), - name.c_str()); + Base::Console() + .warning("Ignored shape %s %s\n", pcObj->getNameInDocument(), name.c_str()); continue; } @@ -348,13 +353,13 @@ void CmdPathShape::activated(int iMsg) for (const std::string& cmd : cmds) { doCommand(Doc, "%s", cmd.c_str()); } - doCommand(Doc, - "FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')", - FeatName.c_str()); - doCommand(Doc, - "FreeCAD.activeDocument().%s.Sources = [ %s ]", - FeatName.c_str(), - sources.str().c_str()); + doCommand(Doc, "FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')", FeatName.c_str()); + doCommand( + Doc, + "FreeCAD.activeDocument().%s.Sources = [ %s ]", + FeatName.c_str(), + sources.str().c_str() + ); commitCommand(); updateActive(); } diff --git a/src/Mod/CAM/Gui/TaskDlgPathCompound.cpp b/src/Mod/CAM/Gui/TaskDlgPathCompound.cpp index 4e9db38d83..f87d37aabf 100644 --- a/src/Mod/CAM/Gui/TaskDlgPathCompound.cpp +++ b/src/Mod/CAM/Gui/TaskDlgPathCompound.cpp @@ -45,8 +45,7 @@ using namespace Gui; // TaskWidget //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskWidgetPathCompound::TaskWidgetPathCompound(ViewProviderPathCompound* CompoundView, - QWidget* parent) +TaskWidgetPathCompound::TaskWidgetPathCompound(ViewProviderPathCompound* CompoundView, QWidget* parent) : TaskBox(Gui::BitmapFactory().pixmap("CAM_Compound"), tr("Compound paths"), true, parent) { // we need a separate container widget to add all controls to @@ -131,8 +130,9 @@ bool TaskDlgPathCompound::accept() App::Document* pcDoc = static_cast(pcCompound->getDocument()); std::vector names = parameter->getList(); for (std::size_t i = 0; i < names.size(); i++) { - App::DocumentObject* pcPath = - static_cast(pcDoc->getObject(names[i].c_str())); + App::DocumentObject* pcPath = static_cast( + pcDoc->getObject(names[i].c_str()) + ); paths.push_back(pcPath); } pcCompound->Group.setValues(paths); diff --git a/src/Mod/CAM/Gui/TaskDlgPathCompound.h b/src/Mod/CAM/Gui/TaskDlgPathCompound.h index ee7894b2df..a2dc7ade1a 100644 --- a/src/Mod/CAM/Gui/TaskDlgPathCompound.h +++ b/src/Mod/CAM/Gui/TaskDlgPathCompound.h @@ -43,8 +43,7 @@ class TaskWidgetPathCompound: public Gui::TaskView::TaskBox Q_OBJECT public: - explicit TaskWidgetPathCompound(ViewProviderPathCompound* CompoundView, - QWidget* parent = nullptr); + explicit TaskWidgetPathCompound(ViewProviderPathCompound* CompoundView, QWidget* parent = nullptr); ~TaskWidgetPathCompound() override; std::vector getList() const; diff --git a/src/Mod/CAM/Gui/ViewProviderArea.cpp b/src/Mod/CAM/Gui/ViewProviderArea.cpp index 0a0272b958..c4ed7a1f34 100644 --- a/src/Mod/CAM/Gui/ViewProviderArea.cpp +++ b/src/Mod/CAM/Gui/ViewProviderArea.cpp @@ -60,8 +60,7 @@ void ViewProviderArea::dragObject(App::DocumentObject* obj) { Path::FeatureArea* area = getObject(); std::vector sources = area->Sources.getValues(); - for (std::vector::iterator it = sources.begin(); it != sources.end(); - ++it) { + for (std::vector::iterator it = sources.begin(); it != sources.end(); ++it) { if (*it == obj) { sources.erase(it); area->Sources.setValues(sources); @@ -92,8 +91,8 @@ void ViewProviderArea::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->isDerivedFrom()) { - std::vector pShapes = - static_cast(prop)->getValues(); + std::vector pShapes + = static_cast(prop)->getValues(); for (std::vector::iterator it = pShapes.begin(); it != pShapes.end(); ++it) { if (*it) { @@ -108,8 +107,7 @@ bool ViewProviderArea::onDelete(const std::vector&) // get the input shapes Path::FeatureArea* area = getObject(); std::vector pShapes = area->Sources.getValues(); - for (std::vector::iterator it = pShapes.begin(); it != pShapes.end(); - ++it) { + for (std::vector::iterator it = pShapes.begin(); it != pShapes.end(); ++it) { if (*it) { Gui::Application::Instance->showViewProvider(*it); } @@ -176,7 +174,8 @@ void ViewProviderAreaView::updateData(const App::Property* prop) PartGui::ViewProviderPlaneParametric::updateData(prop); if (prop->isDerivedFrom()) { Gui::Application::Instance->hideViewProvider( - static_cast(prop)->getValue()); + static_cast(prop)->getValue() + ); } } diff --git a/src/Mod/CAM/Gui/ViewProviderPath.cpp b/src/Mod/CAM/Gui/ViewProviderPath.cpp index 7b096ad776..b84f9309c2 100644 --- a/src/Mod/CAM/Gui/ViewProviderPath.cpp +++ b/src/Mod/CAM/Gui/ViewProviderPath.cpp @@ -147,38 +147,27 @@ ViewProviderPath::ViewProviderPath() , coordStart(-1) , coordEnd(-1) { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/CAM"); - unsigned long lcol = - hGrp->GetUnsigned("DefaultNormalPathColor", 11141375UL); // dark green (0,170,0) + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/CAM" + ); + unsigned long lcol = hGrp->GetUnsigned("DefaultNormalPathColor", 11141375UL); // dark green + // (0,170,0) float lr, lg, lb; lr = ((lcol >> 24) & 0xff) / 255.0; lg = ((lcol >> 16) & 0xff) / 255.0; lb = ((lcol >> 8) & 0xff) / 255.0; - unsigned long mcol = - hGrp->GetUnsigned("DefaultPathMarkerColor", 1442775295UL); // lime green (85,255,0) + unsigned long mcol = hGrp->GetUnsigned("DefaultPathMarkerColor", 1442775295UL); // lime green + // (85,255,0) float mr, mg, mb; mr = ((mcol >> 24) & 0xff) / 255.0; mg = ((mcol >> 16) & 0xff) / 255.0; mb = ((mcol >> 8) & 0xff) / 255.0; int lwidth = hGrp->GetInt("DefaultPathLineWidth", 1); float arrowScale = hGrp->GetFloat("DefaultArrowScale", 3.0f); - ADD_PROPERTY_TYPE(NormalColor, - (lr, lg, lb), - "Path", - App::Prop_None, - "The color of the feed rate moves"); - ADD_PROPERTY_TYPE(MarkerColor, - (mr, mg, mb), - "Path", - App::Prop_None, - "The color of the markers"); + ADD_PROPERTY_TYPE(NormalColor, (lr, lg, lb), "Path", App::Prop_None, "The color of the feed rate moves"); + ADD_PROPERTY_TYPE(MarkerColor, (mr, mg, mb), "Path", App::Prop_None, "The color of the markers"); ADD_PROPERTY_TYPE(LineWidth, (lwidth), "Path", App::Prop_None, "The line width of this path"); - ADD_PROPERTY_TYPE(ShowNodes, - (false), - "Path", - App::Prop_None, - "Turns the display of nodes on/off"); + ADD_PROPERTY_TYPE(ShowNodes, (false), "Path", App::Prop_None, "Turns the display of nodes on/off"); ShowCountConstraints.LowerBound = 0; @@ -189,17 +178,15 @@ ViewProviderPath::ViewProviderPath() StartIndexConstraints.UpperBound = std::numeric_limits::max(); StartIndexConstraints.StepSize = 1; StartIndex.setConstraints(&StartIndexConstraints); - ADD_PROPERTY_TYPE(StartPosition, - (Base::Vector3d()), - "Show", - App::Prop_None, - "Tool initial position"); + ADD_PROPERTY_TYPE(StartPosition, (Base::Vector3d()), "Show", App::Prop_None, "Tool initial position"); ADD_PROPERTY_TYPE(StartIndex, (0), "Show", App::Prop_None, "The index of first GCode to show"); - ADD_PROPERTY_TYPE(ShowCount, - (0), - "Show", - App::Prop_None, - "Number of movement GCode to show, 0 means all"); + ADD_PROPERTY_TYPE( + ShowCount, + (0), + "Show", + App::Prop_None, + "Number of movement GCode to show, 0 means all" + ); pcLineCoords = new SoCoordinate3(); pcLineCoords->ref(); @@ -214,10 +201,9 @@ ViewProviderPath::ViewProviderPath() pcMarkerStyle = new SoDrawStyle(); pcMarkerStyle->ref(); pcMarkerStyle->style = SoDrawStyle::POINTS; - pcMarkerStyle->pointSize = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetInt("MarkerSize", 4); + pcMarkerStyle->pointSize = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetInt("MarkerSize", 4); pcDrawStyle = new SoDrawStyle(); pcDrawStyle->ref(); @@ -388,16 +374,17 @@ void ViewProviderPath::onChanged(const App::Property* prop) if (!colorindex.empty() && coordStart >= 0 && coordStart < (int)colorindex.size()) { const Base::Color& c = NormalColor.getValue(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/CAM"); - unsigned long rcol = - hGrp->GetUnsigned("DefaultRapidPathColor", 2852126975UL); // dark red (170,0,0) + "User parameter:BaseApp/Preferences/Mod/CAM" + ); + unsigned long rcol + = hGrp->GetUnsigned("DefaultRapidPathColor", 2852126975UL); // dark red (170,0,0) float rr, rg, rb; rr = ((rcol >> 24) & 0xff) / 255.0; rg = ((rcol >> 16) & 0xff) / 255.0; rb = ((rcol >> 8) & 0xff) / 255.0; - unsigned long pcol = - hGrp->GetUnsigned("DefaultProbePathColor", 4293591295UL); // yellow (255,255,5) + unsigned long pcol + = hGrp->GetUnsigned("DefaultProbePathColor", 4293591295UL); // yellow (255,255,5) float pr, pg, pb; pr = ((pcol >> 24) & 0xff) / 255.0; pg = ((pcol >> 16) & 0xff) / 255.0; @@ -471,8 +458,9 @@ void ViewProviderPath::showBoundingBox(bool show) unsigned long ViewProviderPath::getBoundColor() const { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/CAM"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/CAM" + ); if (SelectionStyle.getValue() == 0 || !Selectable.getValue()) { return hGrp->GetUnsigned("DefaultBBoxNormalColor", 4294967295UL); // white (255,255,255) } @@ -531,15 +519,17 @@ void ViewProviderPath::hideSelection() class VisualPathSegmentVisitor: public PathSegmentVisitor { public: - VisualPathSegmentVisitor(const Toolpath& tp, - SoCoordinate3* pcLineCoords_, - SoCoordinate3* pcMarkerCoords_, - std::vector& command2Edge_, - std::deque& edge2Command_, - std::deque& edgeIndices_, - std::vector& colorindex_, - std::deque& points_, - std::deque& markers_) + VisualPathSegmentVisitor( + const Toolpath& tp, + SoCoordinate3* pcLineCoords_, + SoCoordinate3* pcMarkerCoords_, + std::vector& command2Edge_, + std::deque& edge2Command_, + std::deque& edgeIndices_, + std::vector& colorindex_, + std::deque& points_, + std::deque& markers_ + ) : pcLineCoords(pcLineCoords_) , pcMarkerCoords(pcMarkerCoords_) , command2Edge(command2Edge_) @@ -567,41 +557,49 @@ public: markers.push_back(last); } - void g0(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) override + void g0( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ) override { (void)last; gx(id, &next, pts, 0); } - void g1(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts) override + void g1( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts + ) override { (void)last; gx(id, &next, pts, 1); } - void g23(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const Base::Vector3d& center) override + void g23( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const Base::Vector3d& center + ) override { (void)last; gx(id, &next, pts, 1); markers.push_back(center); } - void g8x(int id, - const Base::Vector3d& last, - const Base::Vector3d& next, - const std::deque& pts, - const std::deque& p, - const std::deque& q) override + void g8x( + int id, + const Base::Vector3d& last, + const Base::Vector3d& next, + const std::deque& pts, + const std::deque& p, + const std::deque& q + ) override { (void)last; @@ -664,8 +662,7 @@ private: std::deque& points; std::deque& markers; - virtual void - gx(int id, const Base::Vector3d* next, const std::deque& pts, int color) + virtual void gx(int id, const Base::Vector3d* next, const std::deque& pts, int color) { for (std::deque::const_iterator it = pts.begin(); pts.end() != it; ++it) { points.push_back(*it); @@ -705,15 +702,17 @@ void ViewProviderPath::updateVisual(bool rebuild) std::deque points; std::deque markers; - VisualPathSegmentVisitor collect(tp, - pcLineCoords, - pcMarkerCoords, - command2Edge, - edge2Command, - edgeIndices, - colorindex, - points, - markers); + VisualPathSegmentVisitor collect( + tp, + pcLineCoords, + pcMarkerCoords, + command2Edge, + edge2Command, + edgeIndices, + colorindex, + points, + markers + ); PathSegmentWalker segments(tp); segments.walk(collect, StartPosition.getValue()); diff --git a/src/Mod/CAM/Gui/ViewProviderPathShape.cpp b/src/Mod/CAM/Gui/ViewProviderPathShape.cpp index 5888a90225..80235c68b0 100644 --- a/src/Mod/CAM/Gui/ViewProviderPathShape.cpp +++ b/src/Mod/CAM/Gui/ViewProviderPathShape.cpp @@ -59,8 +59,7 @@ void ViewProviderPathShape::dragObject(App::DocumentObject* obj) { Path::FeatureShape* feature = getObject(); std::vector sources = feature->Sources.getValues(); - for (std::vector::iterator it = sources.begin(); it != sources.end(); - ++it) { + for (std::vector::iterator it = sources.begin(); it != sources.end(); ++it) { if (*it == obj) { sources.erase(it); feature->Sources.setValues(sources); @@ -91,8 +90,8 @@ void ViewProviderPathShape::updateData(const App::Property* prop) { PathGui::ViewProviderPath::updateData(prop); if (prop->isDerivedFrom()) { - std::vector pShapes = - static_cast(prop)->getValues(); + std::vector pShapes + = static_cast(prop)->getValues(); for (std::vector::iterator it = pShapes.begin(); it != pShapes.end(); ++it) { if (*it) { @@ -107,8 +106,7 @@ bool ViewProviderPathShape::onDelete(const std::vector&) // get the input shapes Path::FeatureShape* feature = getObject(); std::vector pShapes = feature->Sources.getValues(); - for (std::vector::iterator it = pShapes.begin(); it != pShapes.end(); - ++it) { + for (std::vector::iterator it = pShapes.begin(); it != pShapes.end(); ++it) { if (*it) { Gui::Application::Instance->showViewProvider(*it); } diff --git a/src/Mod/CAM/PathGlobal.h b/src/Mod/CAM/PathGlobal.h index b6644044dc..aa9ea1413a 100644 --- a/src/Mod/CAM/PathGlobal.h +++ b/src/Mod/CAM/PathGlobal.h @@ -25,43 +25,43 @@ #include #ifndef PATH_GLOBAL_H -#define PATH_GLOBAL_H +# define PATH_GLOBAL_H // Path -#ifndef PathExport -#ifdef Path_EXPORTS -#define PathExport FREECAD_DECL_EXPORT -#else -#define PathExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PathExport +# ifdef Path_EXPORTS +# define PathExport FREECAD_DECL_EXPORT +# else +# define PathExport FREECAD_DECL_IMPORT +# endif +# endif // PathGui -#ifndef PathGuiExport -#ifdef PathGui_EXPORTS -#define PathGuiExport FREECAD_DECL_EXPORT -#else -#define PathGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PathGuiExport +# ifdef PathGui_EXPORTS +# define PathGuiExport FREECAD_DECL_EXPORT +# else +# define PathGuiExport FREECAD_DECL_IMPORT +# endif +# endif // PathSimulator -#ifndef PathSimulatorExport -#ifdef PathSimulator_EXPORTS -#define PathSimulatorExport FREECAD_DECL_EXPORT -#else -#define PathSimulatorExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PathSimulatorExport +# ifdef PathSimulator_EXPORTS +# define PathSimulatorExport FREECAD_DECL_EXPORT +# else +# define PathSimulatorExport FREECAD_DECL_IMPORT +# endif +# endif // CAMSimulator (new GL simulator) -#ifndef CAMSimulatorExport -#ifdef CAMSimulator_EXPORTS -#define CAMSimulatorExport FREECAD_DECL_EXPORT -#else -#define CAMSimulatorExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef CAMSimulatorExport +# ifdef CAMSimulator_EXPORTS +# define CAMSimulatorExport FREECAD_DECL_EXPORT +# else +# define CAMSimulatorExport FREECAD_DECL_IMPORT +# endif +# endif #endif // PATH_GLOBAL_H diff --git a/src/Mod/CAM/PathSimulator/App/PathSim.cpp b/src/Mod/CAM/PathSimulator/App/PathSim.cpp index 97e6ef4813..746da0c7ba 100644 --- a/src/Mod/CAM/PathSimulator/App/PathSim.cpp +++ b/src/Mod/CAM/PathSimulator/App/PathSim.cpp @@ -40,13 +40,15 @@ PathSim::~PathSim() void PathSim::BeginSimulation(Part::TopoShape* stock, float resolution) { Base::BoundBox3d bbox = stock->getBoundBox(); - m_stock = std::make_unique(bbox.MinX, - bbox.MinY, - bbox.MinZ, - bbox.LengthX(), - bbox.LengthY(), - bbox.LengthZ(), - resolution); + m_stock = std::make_unique( + bbox.MinX, + bbox.MinY, + bbox.MinZ, + bbox.LengthX(), + bbox.LengthY(), + bbox.LengthZ(), + resolution + ); } void PathSim::SetToolShape(const TopoDS_Shape& toolShape, float resolution) diff --git a/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp b/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp index 2838f05c47..fe49dffa84 100644 --- a/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp +++ b/src/Mod/CAM/PathSimulator/App/PathSimPyImp.cpp @@ -62,13 +62,15 @@ PyObject* PathSimPy::BeginSimulation(PyObject* args, PyObject* kwds) static const std::array kwlist {"stock", "resolution", nullptr}; PyObject* pObjStock; float resolution; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "O!f", - kwlist, - &(Part::TopoShapePy::Type), - &pObjStock, - &resolution)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!f", + kwlist, + &(Part::TopoShapePy::Type), + &pObjStock, + &resolution + )) { return nullptr; } PathSim* sim = getPathSimPtr(); @@ -86,8 +88,8 @@ PyObject* PathSimPy::SetToolShape(PyObject* args) return nullptr; } PathSim* sim = getPathSimPtr(); - const TopoDS_Shape& toolShape = - static_cast(pObjToolShape)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& toolShape + = static_cast(pObjToolShape)->getTopoShapePtr()->getShape(); sim->SetToolShape(toolShape, resolution); Py_IncRef(Py_None); return Py_None; @@ -121,14 +123,16 @@ PyObject* PathSimPy::ApplyCommand(PyObject* args, PyObject* kwds) static const std::array kwlist {"position", "command", nullptr}; PyObject* pObjPlace; PyObject* pObjCmd; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "O!O!", - kwlist, - &(Base::PlacementPy::Type), - &pObjPlace, - &(Path::CommandPy::Type), - &pObjCmd)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!", + kwlist, + &(Base::PlacementPy::Type), + &pObjPlace, + &(Path::CommandPy::Type), + &pObjCmd + )) { return nullptr; } PathSim* sim = getPathSimPtr(); diff --git a/src/Mod/CAM/PathSimulator/App/VolSim.cpp b/src/Mod/CAM/PathSimulator/App/VolSim.cpp index 1e84d7c222..a2bb57a374 100644 --- a/src/Mod/CAM/PathSimulator/App/VolSim.cpp +++ b/src/Mod/CAM/PathSimulator/App/VolSim.cpp @@ -433,11 +433,13 @@ void cStock::SetFacetPoints(MeshCore::MeshGeomFacet& facet, Point3D& p1, Point3D facet.CalcNormal(); } -void cStock::AddQuad(Point3D& p1, - Point3D& p2, - Point3D& p3, - Point3D& p4, - std::vector& facets) +void cStock::AddQuad( + Point3D& p1, + Point3D& p2, + Point3D& p3, + Point3D& p4, + std::vector& facets +) { MeshCore::MeshGeomFacet facet; SetFacetPoints(facet, p1, p2, p3); @@ -779,14 +781,14 @@ cSimTool::cSimTool(const TopoDS_Shape& toolShape, float res) // duration.count() / 1000); } -float cSimTool::GetToolProfileAt( - float pos) // pos is -1..1 location along the radius of the tool (0 is center) +float cSimTool::GetToolProfileAt(float pos) // pos is -1..1 location along the radius of the tool + // (0 is center) { toolShapePoint test; test.radiusPos = std::abs(pos) * radius; - auto it = - std::lower_bound(m_toolShape.begin(), m_toolShape.end(), test, toolShapePoint::less_than()); + auto it + = std::lower_bound(m_toolShape.begin(), m_toolShape.end(), test, toolShapePoint::less_than()); return it != m_toolShape.end() ? it->heightPos : 0.0f; } diff --git a/src/Mod/CAM/PathSimulator/App/VolSim.h b/src/Mod/CAM/PathSimulator/App/VolSim.h index 60635635ac..39950d0c2d 100644 --- a/src/Mod/CAM/PathSimulator/App/VolSim.h +++ b/src/Mod/CAM/PathSimulator/App/VolSim.h @@ -36,7 +36,7 @@ #define SIM_EPSILON 0.00001 #define SIM_TESSEL_TOP 1 #define SIM_TESSEL_BOT 2 -#define SIM_WALK_RES \ +#define SIM_WALK_RES \ 0.6 // step size in pixel units (to make sure all pixels in the path are visited) struct toolShapePoint @@ -238,11 +238,13 @@ private: float FindRectTop(int& xp, int& yp, int& x_size, int& y_size, bool scanHoriz); void FindRectBot(int& xp, int& yp, int& x_size, int& y_size, bool scanHoriz); void SetFacetPoints(MeshCore::MeshGeomFacet& facet, Point3D& p1, Point3D& p2, Point3D& p3); - void AddQuad(Point3D& p1, - Point3D& p2, - Point3D& p3, - Point3D& p4, - std::vector& facets); + void AddQuad( + Point3D& p1, + Point3D& p2, + Point3D& p3, + Point3D& p4, + std::vector& facets + ); int TesselTop(int x, int y); int TesselBot(int x, int y); int TesselSidesX(int yp); diff --git a/src/Mod/CAM/PathSimulator/AppGL/CAMSim.cpp b/src/Mod/CAM/PathSimulator/AppGL/CAMSim.cpp index 46880c5f1e..5cf70b719e 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/CAMSim.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/CAMSim.cpp @@ -46,10 +46,12 @@ void CAMSimulator::CAMSim::resetSimulation() DlgCAMSimulator::GetInstance()->resetSimulation(); } -void CAMSim::addTool(const std::vector& toolProfilePoints, - int toolNumber, - float diameter, - float resolution) +void CAMSim::addTool( + const std::vector& toolProfilePoints, + int toolNumber, + float diameter, + float resolution +) { DlgCAMSimulator::GetInstance()->addTool(toolProfilePoints, toolNumber, diameter, resolution); } diff --git a/src/Mod/CAM/PathSimulator/AppGL/CAMSim.h b/src/Mod/CAM/PathSimulator/AppGL/CAMSim.h index 721c970934..ea124ba97f 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/CAMSim.h +++ b/src/Mod/CAM/PathSimulator/AppGL/CAMSim.h @@ -61,10 +61,12 @@ public: void BeginSimulation(const Part::TopoShape& stock, float resolution); void resetSimulation(); - void addTool(const std::vector& toolProfilePoints, - int toolNumber, - float diameter, - float resolution); + void addTool( + const std::vector& toolProfilePoints, + int toolNumber, + float diameter, + float resolution + ); void SetBaseShape(const Part::TopoShape& baseShape, float resolution); void AddCommand(Command* cmd); diff --git a/src/Mod/CAM/PathSimulator/AppGL/CAMSimPyImp.cpp b/src/Mod/CAM/PathSimulator/AppGL/CAMSimPyImp.cpp index 7f7f15344a..90f9af8655 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/CAMSimPyImp.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/CAMSimPyImp.cpp @@ -69,13 +69,15 @@ PyObject* CAMSimPy::BeginSimulation(PyObject* args, PyObject* kwds) static const std::array kwlist {"stock", "resolution", nullptr}; PyObject* pObjStock; float resolution; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "O!f", - kwlist, - &(Part::TopoShapePy::Type), - &pObjStock, - &resolution)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!f", + kwlist, + &(Part::TopoShapePy::Type), + &pObjStock, + &resolution + )) { return nullptr; } CAMSim* sim = getCAMSimPtr(); @@ -87,23 +89,22 @@ PyObject* CAMSimPy::BeginSimulation(PyObject* args, PyObject* kwds) PyObject* CAMSimPy::AddTool(PyObject* args, PyObject* kwds) { - static const std::array kwlist {"shape", - "toolnumber", - "diameter", - "resolution", - nullptr}; + static const std::array + kwlist {"shape", "toolnumber", "diameter", "resolution", nullptr}; PyObject* pObjToolShape; int toolNumber; float resolution; float diameter; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "Oiff", - kwlist, - &pObjToolShape, - &toolNumber, - &diameter, - &resolution)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "Oiff", + kwlist, + &pObjToolShape, + &toolNumber, + &diameter, + &resolution + )) { return nullptr; } // The tool shape is defined by a list of 2d points that represents the tool revolving profile @@ -126,21 +127,23 @@ PyObject* CAMSimPy::SetBaseShape(PyObject* args, PyObject* kwds) static const std::array kwlist {"shape", "resolution", nullptr}; PyObject* pObjBaseShape; float resolution; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "O!f", - kwlist, - &(Part::TopoShapePy::Type), - &pObjBaseShape, - &resolution)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!f", + kwlist, + &(Part::TopoShapePy::Type), + &pObjBaseShape, + &resolution + )) { return nullptr; } if (!PyArg_ParseTuple(args, "O!f", &(Part::TopoShapePy::Type), &pObjBaseShape, &resolution)) { return nullptr; } CAMSim* sim = getCAMSimPtr(); - const Part::TopoShape& baseShape = - static_cast(pObjBaseShape)->getTopoShapePtr()->getShape(); + const Part::TopoShape& baseShape + = static_cast(pObjBaseShape)->getTopoShapePtr()->getShape(); sim->SetBaseShape(baseShape, resolution); Py_IncRef(Py_None); diff --git a/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp b/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp index b4009e65fe..5b923a8711 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.cpp @@ -136,10 +136,12 @@ void DlgCAMSimulator::addGcodeCommand(const char* cmd) mMillSimulator->AddGcodeLine(cmd); } -void DlgCAMSimulator::addTool(const std::vector& toolProfilePoints, - int toolNumber, - float diameter, - float resolution) +void DlgCAMSimulator::addTool( + const std::vector& toolProfilePoints, + int toolNumber, + float diameter, + float resolution +) { Q_UNUSED(resolution) std::string toolCmd = "T" + std::to_string(toolNumber); @@ -174,10 +176,12 @@ void DlgCAMSimulator::resizeEvent(QResizeEvent* event) glViewport(0, 0, (int)(newWidth * retinaScale), (int)(newHeight * retinaScale)); } -void DlgCAMSimulator::GetMeshData(const Part::TopoShape& tshape, - float resolution, - std::vector& verts, - std::vector& indices) +void DlgCAMSimulator::GetMeshData( + const Part::TopoShape& tshape, + float resolution, + std::vector& verts, + std::vector& indices +) { std::vector normalCount; int nVerts = 0; diff --git a/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.h b/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.h index a58a2fbb2d..a2a8c333db 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.h +++ b/src/Mod/CAM/PathSimulator/AppGL/DlgCAMSimulator.h @@ -26,7 +26,7 @@ #define PATHSIMULATOR_CAMSimulatorGui_H #ifdef _MSC_VER -#pragma warning(disable : 4251) +# pragma warning(disable : 4251) #endif #include @@ -81,10 +81,12 @@ public: // slots: void startSimulation(const Part::TopoShape& stock, float quality); void resetSimulation(); void addGcodeCommand(const char* cmd); - void addTool(const std::vector& toolProfilePoints, - int toolNumber, - float diameter, - float resolution); + void addTool( + const std::vector& toolProfilePoints, + int toolNumber, + float diameter, + float resolution + ); protected: bool event(QEvent* event) override; @@ -97,10 +99,12 @@ protected: void wheelEvent(QWheelEvent* ev) override; void hideEvent(QHideEvent* ev) override; void resizeEvent(QResizeEvent* event) override; - void GetMeshData(const Part::TopoShape& tshape, - float resolution, - std::vector& verts, - std::vector& indices); + void GetMeshData( + const Part::TopoShape& tshape, + float resolution, + std::vector& verts, + std::vector& indices + ); private: bool mAnimating = false; diff --git a/src/Mod/CAM/PathSimulator/AppGL/EndMill.cpp b/src/Mod/CAM/PathSimulator/AppGL/EndMill.cpp index 96c02b5be9..5be6acf840 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/EndMill.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/EndMill.cpp @@ -97,17 +97,10 @@ void EndMill::GenerateDisplayLists(float quality) pathShape.ExtrudeProfileLinear(profilePoints.data(), nFullPoints, 0, 1, 0, 0, true, false); } -unsigned int -EndMill::GenerateArcSegmentDL(float radius, float angleRad, float zShift, Shape* retShape) +unsigned int EndMill::GenerateArcSegmentDL(float radius, float angleRad, float zShift, Shape* retShape) { int nFullPoints = PROFILE_BUFFER_POINTS(nPoints); - retShape->ExtrudeProfileRadial(profilePoints.data(), - nFullPoints, - radius, - angleRad, - zShift, - true, - true); + retShape->ExtrudeProfileRadial(profilePoints.data(), nFullPoints, radius, angleRad, zShift, true, true); return 0; } diff --git a/src/Mod/CAM/PathSimulator/AppGL/GCodeParser.cpp b/src/Mod/CAM/PathSimulator/AppGL/GCodeParser.cpp index 0b3208c679..e7370d80bb 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/GCodeParser.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/GCodeParser.cpp @@ -23,9 +23,9 @@ ***************************************************************************/ #ifdef _MSC_VER -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif +# ifndef _CRT_SECURE_NO_WARNINGS +# define _CRT_SECURE_NO_WARNINGS +# endif #endif #include "GCodeParser.h" diff --git a/src/Mod/CAM/PathSimulator/AppGL/GlUtils.h b/src/Mod/CAM/PathSimulator/AppGL/GlUtils.h index 8115196cc3..2d67582311 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/GlUtils.h +++ b/src/Mod/CAM/PathSimulator/AppGL/GlUtils.h @@ -38,20 +38,20 @@ constexpr auto EPSILON = 0.00001f; #define MS_KBD_CONTROL 0x10 #define MS_KBD_ALT 0x20 -#define GL(x) \ - { \ - GLClearError(); \ - x; \ - if (GLLogError()) \ - __debugbreak(); \ +#define GL(x) \ + { \ + GLClearError(); \ + x; \ + if (GLLogError()) \ + __debugbreak(); \ } -#define GLDELETE(type, x) \ - { \ - if (x != 0) \ - glDelete##type(1, &x); \ - x = 0; \ +#define GLDELETE(type, x) \ + { \ + if (x != 0) \ + glDelete##type(1, &x); \ + x = 0; \ } #define GLDELETE_FRAMEBUFFER(x) GLDELETE(Framebuffers, x) diff --git a/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp b/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp index aa53e95207..acffc0defa 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/GuiDisplay.cpp @@ -61,24 +61,26 @@ GuiItem guiItems[] = { #define NUM_GUI_ITEMS (sizeof(guiItems) / sizeof(GuiItem)) #define TEX_SIZE 256 -std::vector guiFileNames = {"Slider.png", - "Thumb.png", - "Pause.png", - "Play.png", - "SingleStep.png", - "Slower.png", - "Faster.png", - "x.png", - "1.png", - "5.png", - "10.png", - "25.png", - "50.png", - "Rotate.png", - "Path.png", - "AmbientOclusion.png", - "View.png", - "Home.png"}; +std::vector guiFileNames = { + "Slider.png", + "Thumb.png", + "Pause.png", + "Play.png", + "SingleStep.png", + "Slower.png", + "Faster.png", + "x.png", + "1.png", + "5.png", + "10.png", + "25.png", + "50.png", + "Rotate.png", + "Path.png", + "AmbientOclusion.png", + "View.png", + "Home.png" +}; void GuiDisplay::UpdateProjection() { @@ -118,12 +120,7 @@ bool GuiDisplay::GenerateGlItem(GuiItem* guiItem) glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, x)); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, - 2, - GL_FLOAT, - GL_FALSE, - sizeof(Vertex2D), - (void*)offsetof(Vertex2D, tx)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, tx)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo); glBindVertexArray(0); @@ -175,12 +172,7 @@ bool MillSim::GuiDisplay::HStretchGlItem(GuiItem* guiItem, float newWidth, float glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, x)); glEnableVertexAttribArray(1); - glVertexAttribPointer(1, - 2, - GL_FLOAT, - GL_FALSE, - sizeof(Vertex2D), - (void*)offsetof(Vertex2D, tx)); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, tx)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo); glBindVertexArray(0); @@ -272,28 +264,32 @@ void GuiDisplay::RenderItem(int itemId) void MillSim::GuiDisplay::SetupTooltips() { - guiItems[eGuiItemPause].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Pause simulation", nullptr); - guiItems[eGuiItemPlay].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Play simulation", nullptr); - guiItems[eGuiItemSingleStep].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Single step simulation", nullptr); - guiItems[eGuiItemSlower].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Decrease simulation speed", nullptr); - guiItems[eGuiItemFaster].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Increase simulation speed", nullptr); - guiItems[eGuiItemPath].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Show/Hide tool path", nullptr); - guiItems[eGuiItemRotate].toolTip = QCoreApplication::translate("CAM:Simulator:Tooltips", - "Toggle turn table animation", - nullptr); - guiItems[eGuiItemAmbientOclusion].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Toggle ambient occlusion", nullptr); - guiItems[eGuiItemView].toolTip = QCoreApplication::translate("CAM:Simulator:Tooltips", - "Toggle view simulation/model", - nullptr); - guiItems[eGuiItemHome].toolTip = - QCoreApplication::translate("CAM:Simulator:Tooltips", "Reset camera", nullptr); + guiItems[eGuiItemPause].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Pause simulation", nullptr); + guiItems[eGuiItemPlay].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Play simulation", nullptr); + guiItems[eGuiItemSingleStep].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Single step simulation", nullptr); + guiItems[eGuiItemSlower].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Decrease simulation speed", nullptr); + guiItems[eGuiItemFaster].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Increase simulation speed", nullptr); + guiItems[eGuiItemPath].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Show/Hide tool path", nullptr); + guiItems[eGuiItemRotate].toolTip = QCoreApplication::translate( + "CAM:Simulator:Tooltips", + "Toggle turn table animation", + nullptr + ); + guiItems[eGuiItemAmbientOclusion].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Toggle ambient occlusion", nullptr); + guiItems[eGuiItemView].toolTip = QCoreApplication::translate( + "CAM:Simulator:Tooltips", + "Toggle view simulation/model", + nullptr + ); + guiItems[eGuiItemHome].toolTip + = QCoreApplication::translate("CAM:Simulator:Tooltips", "Reset camera", nullptr); } void GuiDisplay::MouseCursorPos(int x, int y) diff --git a/src/Mod/CAM/PathSimulator/AppGL/MillPathLine.cpp b/src/Mod/CAM/PathSimulator/AppGL/MillPathLine.cpp index ca8dae700e..539bf7bcfc 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/MillPathLine.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/MillPathLine.cpp @@ -30,18 +30,22 @@ void MillPathLine::GenerateModel() // vertex attribs glEnableVertexAttribArray(0); - glVertexAttribPointer(0, - 3, - GL_FLOAT, - GL_FALSE, - sizeof(MillPathPosition), - (void*)offsetof(MillPathPosition, X)); + glVertexAttribPointer( + 0, + 3, + GL_FLOAT, + GL_FALSE, + sizeof(MillPathPosition), + (void*)offsetof(MillPathPosition, X) + ); glEnableVertexAttribArray(1); - glVertexAttribIPointer(1, - 1, - GL_INT, - sizeof(MillPathPosition), - (void*)offsetof(MillPathPosition, SegmentId)); + glVertexAttribIPointer( + 1, + 1, + GL_INT, + sizeof(MillPathPosition), + (void*)offsetof(MillPathPosition, SegmentId) + ); // unbind and free glBindVertexArray(0); diff --git a/src/Mod/CAM/PathSimulator/AppGL/MillPathSegment.cpp b/src/Mod/CAM/PathSimulator/AppGL/MillPathSegment.cpp index f8a5cd98da..cfe4153fa0 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/MillPathSegment.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/MillPathSegment.cpp @@ -106,10 +106,12 @@ MillPathSegment::MillPathSegment(EndMill* _endmill, MillMotion* from, MillMotion mShape = endmill->toolShape; } else { - endmill->GenerateArcSegmentDL(mRadius, - mStepAngRad * SWEEP_ARC_PAD, - mDiff[PZ] / numSimSteps, - &mShape); + endmill->GenerateArcSegmentDL( + mRadius, + mStepAngRad * SWEEP_ARC_PAD, + mDiff[PZ] / numSimSteps, + &mShape + ); numSimSteps++; } @@ -176,10 +178,12 @@ void MillPathSegment::render(int step) mat4x4_identity(mat); mat4x4_identity(rmat); if (mMotionType == MTCurved) { - mat4x4_translate_in_place(mat, - mCenter[PX], - mCenter[PY], - mCenter[PZ] + mDiff[PZ] * (step - 1) / numSimSteps); + mat4x4_translate_in_place( + mat, + mCenter[PX], + mCenter[PY], + mCenter[PZ] + mDiff[PZ] * (step - 1) / numSimSteps + ); mat4x4_rotate_Z(mat, mat, mStartAngRad - (step - 1) * mStepAngRad); mat4x4_rotate_Z(rmat, rmat, mStartAngRad - (step - 1) * mStepAngRad); @@ -197,10 +201,12 @@ void MillPathSegment::render(int step) mat4x4_translate_in_place_v(mat, mStartPos); } else { - mat4x4_translate_in_place(mat, - mStartPos[PX], - mStartPos[PY], - mStartPos[PZ] + mStepNumber * mStepLength[PZ]); + mat4x4_translate_in_place( + mat, + mStartPos[PX], + mStartPos[PY], + mStartPos[PZ] + mStepNumber * mStepLength[PZ] + ); } endmill->toolShape.Render(mat, rmat); } diff --git a/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp b/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp index dac82218d2..94b8b3f6e9 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/MillSimulation.cpp @@ -110,8 +110,8 @@ void MillSimulation::InitSimulation(float quality) mDestMotion = mCodeParser.Operations[i]; EndMill* tool = GetTool(mDestMotion.tool); if (tool != nullptr) { - MillSim::MillPathSegment* segment = - new MillSim::MillPathSegment(tool, &mCurMotion, &mDestMotion); + MillSim::MillPathSegment* segment + = new MillSim::MillPathSegment(tool, &mCurMotion, &mDestMotion); segment->indexInArray = i; segment->segmentIndex = segId++; mNTotalSteps += segment->numSimSteps; diff --git a/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp b/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp index b831250617..175ac3e02b 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/Shader.cpp @@ -187,11 +187,8 @@ bool CheckCompileResult(int shaderId, const char* shaderName, bool isVertex) if (res != 0) { return false; } - int headerLen = snprintf(log, - 48, - "Error compiling %s %s shader: ", - shaderName, - isVertex ? "vertex" : "fragment"); + int headerLen + = snprintf(log, 48, "Error compiling %s %s shader: ", shaderName, isVertex ? "vertex" : "fragment"); glGetShaderInfoLog(shaderId, 1020 - headerLen, &len, log + headerLen); len += headerLen; if (len > 1020) { @@ -202,8 +199,7 @@ bool CheckCompileResult(int shaderId, const char* shaderName, bool isVertex) return true; } -unsigned int -Shader::CompileShader(const char* name, const char* _vertShader, const char* _fragShader) +unsigned int Shader::CompileShader(const char* name, const char* _vertShader, const char* _fragShader) { vertShader = _vertShader; fragShader = _fragShader; diff --git a/src/Mod/CAM/PathSimulator/AppGL/SimDisplay.cpp b/src/Mod/CAM/PathSimulator/AppGL/SimDisplay.cpp index 801117b7e5..1d097f8fd9 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/SimDisplay.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/SimDisplay.cpp @@ -88,7 +88,8 @@ void SimDisplay::CreateFboQuad() // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f}; + 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f + }; glGenVertexArrays(1, &mFboQuadVAO); glGenBuffers(1, &mFboQuadVBO); @@ -101,11 +102,7 @@ void SimDisplay::CreateFboQuad() glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); } -void SimDisplay::CreateGBufTex(GLenum texUnit, - GLint intFormat, - GLenum format, - GLenum type, - GLuint& texid) +void SimDisplay::CreateGBufTex(GLenum texUnit, GLint intFormat, GLenum format, GLenum type, GLuint& texid) { glActiveTexture(texUnit); glGenTextures(1, &texid); @@ -154,9 +151,7 @@ void SimDisplay::CreateDisplayFbos() glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, mFboNormTexture, 0); - unsigned int attachments[3] = {GL_COLOR_ATTACHMENT0, - GL_COLOR_ATTACHMENT1, - GL_COLOR_ATTACHMENT2}; + unsigned int attachments[3] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2}; glDrawBuffers(3, attachments); glGenRenderbuffers(1, &mRboDepthStencil); @@ -165,11 +160,14 @@ void SimDisplay::CreateDisplayFbos() GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, mWidth, - mHeight); // use a single renderbuffer object for both a depth AND stencil buffer. - glFramebufferRenderbuffer(GL_FRAMEBUFFER, - GL_DEPTH_STENCIL_ATTACHMENT, - GL_RENDERBUFFER, - mRboDepthStencil); // now actually attach it + mHeight + ); // use a single renderbuffer object for both a depth AND stencil buffer. + glFramebufferRenderbuffer( + GL_FRAMEBUFFER, + GL_DEPTH_STENCIL_ATTACHMENT, + GL_RENDERBUFFER, + mRboDepthStencil + ); // now actually attach it if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { return; @@ -198,11 +196,7 @@ void SimDisplay::CreateSsaoFbos() glGenFramebuffers(1, &mSsaoBlurFbo); glBindFramebuffer(GL_FRAMEBUFFER, mSsaoBlurFbo); CreateGBufTex(GL_TEXTURE0, GL_R16F, GL_RED, GL_FLOAT, mFboSsaoBlurTexture); - glFramebufferTexture2D(GL_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, - mFboSsaoBlurTexture, - 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mFboSsaoBlurTexture, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { mSsaoValid = false; return; diff --git a/src/Mod/CAM/PathSimulator/AppGL/SimShapes.cpp b/src/Mod/CAM/PathSimulator/AppGL/SimShapes.cpp index a9fd543e5a..9f5c9989fc 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/SimShapes.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/SimShapes.cpp @@ -54,12 +54,14 @@ void Shape::GenerateSinTable(int nSlices) } -void Shape::RotateProfile(float* profPoints, - int nPoints, - float distance, - float /* deltaHeight */, - int nSlices, - bool isHalfTurn) +void Shape::RotateProfile( + float* profPoints, + int nPoints, + float distance, + float /* deltaHeight */, + int nSlices, + bool isHalfTurn +) { int vidx = 0; int iidx = 0; @@ -124,15 +126,17 @@ void Shape::RotateProfile(float* profPoints, SetModelData(vbuffer, ibuffer); } -void Shape::CalculateExtrudeBufferSizes(int nProfilePoints, - bool capStart, - bool capEnd, - int* numVerts, - int* numIndices, - int* vc1idx, - int* vc2idx, - int* ic1idx, - int* ic2idx) +void Shape::CalculateExtrudeBufferSizes( + int nProfilePoints, + bool capStart, + bool capEnd, + int* numVerts, + int* numIndices, + int* vc1idx, + int* vc2idx, + int* ic1idx, + int* ic2idx +) { *numVerts = nProfilePoints * 4; // one face per profile point times 4 vertex per face *numIndices = nProfilePoints * 2 * 3; // 2 triangles per face times 3 indices per triangle @@ -150,27 +154,31 @@ void Shape::CalculateExtrudeBufferSizes(int nProfilePoints, } } -void Shape::ExtrudeProfileRadial(float* profPoints, - int nPoints, - float radius, - float angleRad, - float deltaHeight, - bool capStart, - bool capEnd) +void Shape::ExtrudeProfileRadial( + float* profPoints, + int nPoints, + float radius, + float angleRad, + float deltaHeight, + bool capStart, + bool capEnd +) { int vidx = 0, vc1idx, vc2idx; int iidx = 0, ic1idx, ic2idx; int numVerts, numIndices; - CalculateExtrudeBufferSizes(nPoints, - capStart, - capEnd, - &numVerts, - &numIndices, - &vc1idx, - &vc2idx, - &ic1idx, - &ic2idx); + CalculateExtrudeBufferSizes( + nPoints, + capStart, + capEnd, + &numVerts, + &numIndices, + &vc1idx, + &vc2idx, + &ic1idx, + &ic2idx + ); int vc1start = vc1idx; int vc2start = vc2idx; @@ -244,28 +252,32 @@ void Shape::ExtrudeProfileRadial(float* profPoints, SetModelData(vbuffer, ibuffer); } -void Shape::ExtrudeProfileLinear(float* profPoints, - int nPoints, - float fromX, - float toX, - float fromZ, - float toZ, - bool capStart, - bool capEnd) +void Shape::ExtrudeProfileLinear( + float* profPoints, + int nPoints, + float fromX, + float toX, + float fromZ, + float toZ, + bool capStart, + bool capEnd +) { int vidx = 0, vc1idx, vc2idx; int iidx = 0, ic1idx, ic2idx; int numVerts, numIndices; - CalculateExtrudeBufferSizes(nPoints, - capStart, - capEnd, - &numVerts, - &numIndices, - &vc1idx, - &vc2idx, - &ic1idx, - &ic2idx); + CalculateExtrudeBufferSizes( + nPoints, + capStart, + capEnd, + &numVerts, + &numIndices, + &vc1idx, + &vc2idx, + &ic1idx, + &ic2idx + ); int vc1start = vc1idx; int vc2start = vc2idx; diff --git a/src/Mod/CAM/PathSimulator/AppGL/SimShapes.h b/src/Mod/CAM/PathSimulator/AppGL/SimShapes.h index 68332af1e6..b60e05f79b 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/SimShapes.h +++ b/src/Mod/CAM/PathSimulator/AppGL/SimShapes.h @@ -27,23 +27,23 @@ #include "OpenGlWrapper.h" #include "linmath.h" -#define SET_DUAL(var, idx, y, z) \ - { \ - var[idx++] = y; \ - var[idx++] = z; \ +#define SET_DUAL(var, idx, y, z) \ + { \ + var[idx++] = y; \ + var[idx++] = z; \ } -#define SET_TRIPLE(var, idx, x, y, z) \ - { \ - var[idx++] = x; \ - var[idx++] = y; \ - var[idx++] = z; \ +#define SET_TRIPLE(var, idx, x, y, z) \ + { \ + var[idx++] = x; \ + var[idx++] = y; \ + var[idx++] = z; \ } -#define SET_TRIPLE_OFFS(var, idx, offs, x, y, z) \ - { \ - var[idx++] = x + offs; \ - var[idx++] = y + offs; \ - var[idx++] = z + offs; \ +#define SET_TRIPLE_OFFS(var, idx, offs, x, y, z) \ + { \ + var[idx++] = x + offs; \ + var[idx++] = y + offs; \ + var[idx++] = z + offs; \ } namespace MillSim @@ -86,27 +86,33 @@ public: void Render(mat4x4 modelMat, mat4x4 normallMat); void FreeResources(); void SetModelData(std::vector& vbuffer, std::vector& ibuffer); - void RotateProfile(float* profPoints, - int nPoints, - float distance, - float deltaHeight, - int nSlices, - bool isHalfTurn); - void ExtrudeProfileRadial(float* profPoints, - int nPoints, - float radius, - float angleRad, - float deltaHeight, - bool capStart, - bool capEnd); - void ExtrudeProfileLinear(float* profPoints, - int nPoints, - float fromX, - float toX, - float fromZ, - float toZ, - bool capStart, - bool capEnd); + void RotateProfile( + float* profPoints, + int nPoints, + float distance, + float deltaHeight, + int nSlices, + bool isHalfTurn + ); + void ExtrudeProfileRadial( + float* profPoints, + int nPoints, + float radius, + float angleRad, + float deltaHeight, + bool capStart, + bool capEnd + ); + void ExtrudeProfileLinear( + float* profPoints, + int nPoints, + float fromX, + float toX, + float fromZ, + float toZ, + bool capStart, + bool capEnd + ); static void GenerateSinTable(int nSlices); static std::vector sinTable; @@ -115,15 +121,17 @@ public: protected: void GenerateModel(float* vbuffer, GLushort* ibuffer, int numVerts, int numIndices); - void CalculateExtrudeBufferSizes(int nProfilePoints, - bool capStart, - bool capEnd, - int* numVerts, - int* numIndices, - int* vc1idx, - int* vc2idx, - int* ic1idx, - int* ic2idx); + void CalculateExtrudeBufferSizes( + int nProfilePoints, + bool capStart, + bool capEnd, + int* numVerts, + int* numIndices, + int* vc1idx, + int* vc2idx, + int* ic1idx, + int* ic2idx + ); }; } // namespace MillSim diff --git a/src/Mod/CAM/PathSimulator/AppGL/TextureLoader.cpp b/src/Mod/CAM/PathSimulator/AppGL/TextureLoader.cpp index dd3ca9826f..abbab378a5 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/TextureLoader.cpp +++ b/src/Mod/CAM/PathSimulator/AppGL/TextureLoader.cpp @@ -52,13 +52,11 @@ TextureItem texItems[] = { int sssize = -1; -TextureLoader::TextureLoader(std::string imgFolder, - std::vector fileNames, - int textureSize) +TextureLoader::TextureLoader(std::string imgFolder, std::vector fileNames, int textureSize) : mImageFolder(imgFolder) { - size_t buffsize = - static_cast(textureSize) * static_cast(textureSize) * sizeof(unsigned int); + size_t buffsize = static_cast(textureSize) * static_cast(textureSize) + * sizeof(unsigned int); mRawData = (unsigned int*)malloc(buffsize); if (mRawData == nullptr) { return; @@ -71,10 +69,7 @@ TextureLoader::TextureLoader(std::string imgFolder, } // parse compressed image into a texture buffer -bool TextureLoader::AddImage(TextureItem* texItem, - QImage& pixmap, - unsigned int* buffPos, - int stride) +bool TextureLoader::AddImage(TextureItem* texItem, QImage& pixmap, unsigned int* buffPos, int stride) { int width = pixmap.width(); int height = pixmap.height(); diff --git a/src/Mod/CAM/PathSimulator/AppGL/linmath.h b/src/Mod/CAM/PathSimulator/AppGL/linmath.h index 1239a33218..5ca94e2e68 100644 --- a/src/Mod/CAM/PathSimulator/AppGL/linmath.h +++ b/src/Mod/CAM/PathSimulator/AppGL/linmath.h @@ -10,65 +10,65 @@ #include #ifdef LINMATH_NO_INLINE -#define LINMATH_H_FUNC static +# define LINMATH_H_FUNC static #else -#define LINMATH_H_FUNC static inline +# define LINMATH_H_FUNC static inline #endif -#define LINMATH_H_DEFINE_VEC(n) \ - typedef float vec##n[n]; \ - LINMATH_H_FUNC void vec##n##_add(vec##n r, vec##n const a, vec##n const b) \ - { \ - int i; \ - for (i = 0; i < n; ++i) \ - r[i] = a[i] + b[i]; \ - } \ - LINMATH_H_FUNC void vec##n##_sub(vec##n r, vec##n const a, vec##n const b) \ - { \ - int i; \ - for (i = 0; i < n; ++i) \ - r[i] = a[i] - b[i]; \ - } \ - LINMATH_H_FUNC void vec##n##_scale(vec##n r, vec##n const v, float const s) \ - { \ - int i; \ - for (i = 0; i < n; ++i) \ - r[i] = v[i] * s; \ - } \ - LINMATH_H_FUNC float vec##n##_mul_inner(vec##n const a, vec##n const b) \ - { \ - float p = 0.f; \ - int i; \ - for (i = 0; i < n; ++i) \ - p += b[i] * a[i]; \ - return p; \ - } \ - LINMATH_H_FUNC float vec##n##_len(vec##n const v) \ - { \ - return sqrtf(vec##n##_mul_inner(v, v)); \ - } \ - LINMATH_H_FUNC void vec##n##_norm(vec##n r, vec##n const v) \ - { \ - float k = 1.f / vec##n##_len(v); \ - vec##n##_scale(r, v, k); \ - } \ - LINMATH_H_FUNC void vec##n##_min(vec##n r, vec##n const a, vec##n const b) \ - { \ - int i; \ - for (i = 0; i < n; ++i) \ - r[i] = a[i] < b[i] ? a[i] : b[i]; \ - } \ - LINMATH_H_FUNC void vec##n##_max(vec##n r, vec##n const a, vec##n const b) \ - { \ - int i; \ - for (i = 0; i < n; ++i) \ - r[i] = a[i] > b[i] ? a[i] : b[i]; \ - } \ - LINMATH_H_FUNC void vec##n##_dup(vec##n r, vec##n const src) \ - { \ - int i; \ - for (i = 0; i < n; ++i) \ - r[i] = src[i]; \ +#define LINMATH_H_DEFINE_VEC(n) \ + typedef float vec##n[n]; \ + LINMATH_H_FUNC void vec##n##_add(vec##n r, vec##n const a, vec##n const b) \ + { \ + int i; \ + for (i = 0; i < n; ++i) \ + r[i] = a[i] + b[i]; \ + } \ + LINMATH_H_FUNC void vec##n##_sub(vec##n r, vec##n const a, vec##n const b) \ + { \ + int i; \ + for (i = 0; i < n; ++i) \ + r[i] = a[i] - b[i]; \ + } \ + LINMATH_H_FUNC void vec##n##_scale(vec##n r, vec##n const v, float const s) \ + { \ + int i; \ + for (i = 0; i < n; ++i) \ + r[i] = v[i] * s; \ + } \ + LINMATH_H_FUNC float vec##n##_mul_inner(vec##n const a, vec##n const b) \ + { \ + float p = 0.f; \ + int i; \ + for (i = 0; i < n; ++i) \ + p += b[i] * a[i]; \ + return p; \ + } \ + LINMATH_H_FUNC float vec##n##_len(vec##n const v) \ + { \ + return sqrtf(vec##n##_mul_inner(v, v)); \ + } \ + LINMATH_H_FUNC void vec##n##_norm(vec##n r, vec##n const v) \ + { \ + float k = 1.f / vec##n##_len(v); \ + vec##n##_scale(r, v, k); \ + } \ + LINMATH_H_FUNC void vec##n##_min(vec##n r, vec##n const a, vec##n const b) \ + { \ + int i; \ + for (i = 0; i < n; ++i) \ + r[i] = a[i] < b[i] ? a[i] : b[i]; \ + } \ + LINMATH_H_FUNC void vec##n##_max(vec##n r, vec##n const a, vec##n const b) \ + { \ + int i; \ + for (i = 0; i < n; ++i) \ + r[i] = a[i] > b[i] ? a[i] : b[i]; \ + } \ + LINMATH_H_FUNC void vec##n##_dup(vec##n r, vec##n const src) \ + { \ + int i; \ + for (i = 0; i < n; ++i) \ + r[i] = src[i]; \ } LINMATH_H_DEFINE_VEC(2) @@ -315,8 +315,8 @@ LINMATH_H_FUNC void mat4x4_invert(mat4x4 T, mat4x4 const M) c[5] = M[2][2] * M[3][3] - M[3][2] * M[2][3]; /* Assumes it is invertible */ - float idet = - 1.0f / (s[0] * c[5] - s[1] * c[4] + s[2] * c[3] + s[3] * c[2] - s[4] * c[1] + s[5] * c[0]); + float idet = 1.0f + / (s[0] * c[5] - s[1] * c[4] + s[2] * c[3] + s[3] * c[2] - s[4] * c[1] + s[5] * c[0]); T[0][0] = (M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; diff --git a/src/Mod/CAM/libarea/Adaptive.cpp b/src/Mod/CAM/libarea/Adaptive.cpp index bfc09ef01d..13497a6ff4 100644 --- a/src/Mod/CAM/libarea/Adaptive.cpp +++ b/src/Mod/CAM/libarea/Adaptive.cpp @@ -312,12 +312,14 @@ void AverageDirection(const vector& unityVectors, DoublePoint& outp output.Y /= magnitude; } -double DistancePointToLineSegSquared(const IntPoint& p1, - const IntPoint& p2, - const IntPoint& pt, - IntPoint& closestPoint, - double& ptParameter, - bool clamp = true) +double DistancePointToLineSegSquared( + const IntPoint& p1, + const IntPoint& p2, + const IntPoint& pt, + IntPoint& closestPoint, + double& ptParameter, + bool clamp = true +) { double D21X = double(p2.X - p1.X); double D21Y = double(p2.Y - p1.Y); @@ -370,12 +372,14 @@ void ScaleDownPaths(Paths& paths, long scaleFactor) } -double DistancePointToPathsSqrd(const Paths& paths, - const IntPoint& pt, - IntPoint& closestPointOnPath, - size_t& clpPathIndex, - size_t& clpSegmentIndex, - double& clpParameter) +double DistancePointToPathsSqrd( + const Paths& paths, + const IntPoint& pt, + IntPoint& closestPointOnPath, + size_t& clpPathIndex, + size_t& clpSegmentIndex, + double& clpParameter +) { double minDistSq = __DBL_MAX__; IntPoint clp; @@ -386,11 +390,13 @@ double DistancePointToPathsSqrd(const Paths& paths, // iterate through segments for (Path::size_type j = 0; j < size; j++) { double ptPar; - double distSq = DistancePointToLineSegSquared(path->at(j > 0 ? j - 1 : size - 1), - path->at(j), - pt, - clp, - ptPar); + double distSq = DistancePointToLineSegSquared( + path->at(j > 0 ? j - 1 : size - 1), + path->at(j), + pt, + clp, + ptPar + ); if (distSq < minDistSq) { clpPathIndex = i; clpSegmentIndex = j; @@ -460,10 +466,12 @@ void CleanPath(const Path& inp, Path& outpt, double tolerance) } } -bool Circle2CircleIntersect(const IntPoint& c1, - const IntPoint& c2, - double radius, - pair& intersections) +bool Circle2CircleIntersect( + const IntPoint& c1, + const IntPoint& c2, + double radius, + pair& intersections +) { double DX = double(c2.X - c1.X); double DY = double(c2.Y - c1.Y); @@ -475,19 +483,21 @@ bool Circle2CircleIntersect(const IntPoint& c1, return false; // do not intersect, or intersect in one point (this case not relevant here) } double a_2 = sqrt(4 * radius * radius - d * d) / 2.0; - intersections.first = - DoublePoint(0.5 * (c1.X + c2.X) - DY * a_2 / d, 0.5 * (c1.Y + c2.Y) + DX * a_2 / d); - intersections.second = - DoublePoint(0.5 * (c1.X + c2.X) + DY * a_2 / d, 0.5 * (c1.Y + c2.Y) - DX * a_2 / d); + intersections.first + = DoublePoint(0.5 * (c1.X + c2.X) - DY * a_2 / d, 0.5 * (c1.Y + c2.Y) + DX * a_2 / d); + intersections.second + = DoublePoint(0.5 * (c1.X + c2.X) + DY * a_2 / d, 0.5 * (c1.Y + c2.Y) - DX * a_2 / d); return true; } -bool Line2CircleIntersect(const IntPoint& c, - double radius, - const IntPoint& p1, - const IntPoint& p2, - vector& result, - bool clamp = true) +bool Line2CircleIntersect( + const IntPoint& c, + double radius, + const IntPoint& p1, + const IntPoint& p2, + vector& result, + bool clamp = true +) { // if more intersections returned, first is closer to p1 @@ -577,11 +587,13 @@ bool IsPointWithinCutRegion(const Paths& toolBoundPaths, const IntPoint& point) } /* finds intersection of line segment with line segment */ -bool IntersectionPoint(const IntPoint& s1p1, - const IntPoint& s1p2, - const IntPoint& s2p1, - const IntPoint& s2p2, - IntPoint& intersection) +bool IntersectionPoint( + const IntPoint& s1p1, + const IntPoint& s1p2, + const IntPoint& s2p1, + const IntPoint& s2p2, + IntPoint& intersection +) { double S1DX = double(s1p2.X - s1p1.X); double S1DY = double(s1p2.Y - s1p1.Y); @@ -608,10 +620,7 @@ bool IntersectionPoint(const IntPoint& s1p1, } /* finds one/first intersection of line segment with paths */ -bool IntersectionPoint(const Paths& paths, - const IntPoint& p1, - const IntPoint& p2, - IntPoint& intersection) +bool IntersectionPoint(const Paths& paths, const IntPoint& p1, const IntPoint& p2, IntPoint& intersection) { BoundBox segBB(p1, p2); for (size_t i = 0; i < paths.size(); i++) { @@ -697,8 +706,10 @@ void SmoothPaths(Paths& paths, double stepSize, long pointCount, long iterations continue; } const double p = double(idx) / steps; - const IntPoint ptx(long(lastPt.X + double(pt.X - lastPt.X) * p), - long(lastPt.Y + double(pt.Y - lastPt.Y) * p)); + const IntPoint ptx( + long(lastPt.X + double(pt.X - lastPt.X) * p), + long(lastPt.Y + double(pt.Y - lastPt.Y) * p) + ); if (idx == 0 && DistanceSqrd(back.second, ptx) < scale && points.size() > 1) { points.pop_back(); @@ -760,11 +771,13 @@ void SmoothPaths(Paths& paths, double stepSize, long pointCount, long iterations ScaleDownPaths(paths, scale); } -bool PopPathWithClosestPoint(Paths& paths /*closest path is removed from collection and shifted to - start with closest point */ - , - IntPoint p1, - Path& result) +bool PopPathWithClosestPoint( + Paths& paths /*closest path is removed from collection and shifted to + start with closest point */ + , + IntPoint p1, + Path& result +) { if (paths.empty()) { @@ -1275,16 +1288,18 @@ public: calculateCurrentPathLength(); ResetPasses(); } - bool nextEngagePoint(Adaptive2d* parent, - ClearedArea& clearedArea, - double step, - double minCutArea, - double maxCutArea, - int maxPases = 2) + bool nextEngagePoint( + Adaptive2d* parent, + ClearedArea& clearedArea, + double step, + double minCutArea, + double maxCutArea, + int maxPases = 2 + ) { Perf_NextEngagePoint.Start(); - double prevArea = - 0; // we want to make sure that we catch the point where the area is on raising slope + double prevArea = 0; // we want to make sure that we catch the point where the area is on + // raising slope IntPoint initialPoint(-1000000000, -1000000000); for (;;) { if (!moveForward(step)) { @@ -1309,19 +1324,23 @@ public: IntPoint getCurrentPoint() { const Path* pth = &toolBoundPaths.at(state.currentPathIndex); - const IntPoint* p1 = &pth->at(state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 - : pth->size() - 1); + const IntPoint* p1 = &pth->at( + state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 : pth->size() - 1 + ); const IntPoint* p2 = &pth->at(state.currentSegmentIndex); double segLength = sqrt(DistanceSqrd(*p1, *p2)); - return IntPoint(long(p1->X + state.segmentPos * double(p2->X - p1->X) / segLength), - long(p1->Y + state.segmentPos * double(p2->Y - p1->Y) / segLength)); + return IntPoint( + long(p1->X + state.segmentPos * double(p2->X - p1->X) / segLength), + long(p1->Y + state.segmentPos * double(p2->Y - p1->Y) / segLength) + ); } DoublePoint getCurrentDir() { const Path* pth = &toolBoundPaths.at(state.currentPathIndex); - const IntPoint* p1 = &pth->at(state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 - : pth->size() - 1); + const IntPoint* p1 = &pth->at( + state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 : pth->size() - 1 + ); const IntPoint* p2 = &pth->at(state.currentSegmentIndex); double segLength = sqrt(DistanceSqrd(*p1, *p2)); return DoublePoint(double(p2->X - p1->X) / segLength, double(p2->Y - p1->Y) / segLength); @@ -1382,8 +1401,9 @@ private: double currentSegmentLength() { const Path* pth = &toolBoundPaths.at(state.currentPathIndex); - const IntPoint* p1 = &pth->at(state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 - : pth->size() - 1); + const IntPoint* p1 = &pth->at( + state.currentSegmentIndex > 0 ? state.currentSegmentIndex - 1 : pth->size() - 1 + ); const IntPoint* p2 = &pth->at(state.currentSegmentIndex); return sqrt(DistanceSqrd(*p1, *p2)); } @@ -1396,11 +1416,13 @@ private: Adaptive2d::Adaptive2d() {} -double Adaptive2d::CalcCutArea(Clipper& clip, - const IntPoint& c1, - const IntPoint& c2, - ClearedArea& clearedArea, - bool preventConventional) +double Adaptive2d::CalcCutArea( + Clipper& clip, + const IntPoint& c1, + const IntPoint& c2, + ClearedArea& clearedArea, + bool preventConventional +) { double dist = DistanceSqrd(c1, c2); @@ -1495,9 +1517,9 @@ double Adaptive2d::CalcCutArea(Clipper& clip, } } } - else if (interPath != NULL) { // state: inside - if ((DistanceSqrd(c2, *p2) - <= rsqrd)) { // next point still inside, add it and continue, no state change + else if (interPath != NULL) { // state: inside + if ((DistanceSqrd(c2, *p2) <= rsqrd)) { // next point still inside, add it and + // continue, no state change interPath->push_back(IntPoint(*p2)); } else { // prev point inside, current point outside, find intersection @@ -1550,8 +1572,10 @@ double Adaptive2d::CalcCutArea(Clipper& clip, if (preventConventional && interPathLen >= RESOLUTION_FACTOR) { // detect conventional mode cut - we want only climb mode - IntPoint midPoint(long(c2.X + toolRadiusScaled * cos(0.5 * (maxFi + minFi))), - long(c2.Y + toolRadiusScaled * sin(0.5 * (maxFi + minFi)))); + IntPoint midPoint( + long(c2.X + toolRadiusScaled * cos(0.5 * (maxFi + minFi))), + long(c2.Y + toolRadiusScaled * sin(0.5 * (maxFi + minFi))) + ); if (PointSideOfLine(c1, c2, midPoint) < 0) { area = __DBL_MAX__; Perf_CalcCutAreaCirc.Stop(); @@ -1585,13 +1609,14 @@ double Adaptive2d::CalcCutArea(Clipper& clip, } double dx = double(cpt->X - prevPt->X); double dy = double(cpt->Y - prevPt->Y); - IntPoint segPoint(long(prevPt->X + dx * pos / segLen), - long(prevPt->Y + dy * pos / segLen)); + IntPoint segPoint( + long(prevPt->X + dx * pos / segLen), + long(prevPt->Y + dy * pos / segLen) + ); IntPoint scanPoint( - long(c2.X - + scanDistance * cos(minFi + distance * (maxFi - minFi) / interPathLen)), - long(c2.Y - + scanDistance * sin(minFi + distance * (maxFi - minFi) / interPathLen))); + long(c2.X + scanDistance * cos(minFi + distance * (maxFi - minFi) / interPathLen)), + long(c2.Y + scanDistance * sin(minFi + distance * (maxFi - minFi) / interPathLen)) + ); IntPoint intersC2(segPoint.X, segPoint.Y); IntPoint intersC1(segPoint.X, segPoint.Y); @@ -1706,9 +1731,11 @@ void Adaptive2d::ApplyStockToLeave(Paths& inputPaths) // Adaptive2d - Execute //******************************************** -std::list Adaptive2d::Execute(const DPaths& stockPaths, - const DPaths& paths, - std::function progressCallbackFn) +std::list Adaptive2d::Execute( + const DPaths& stockPaths, + const DPaths& paths, + std::function progressCallbackFn +) { //********************************** // Initializations @@ -1858,8 +1885,7 @@ std::list Adaptive2d::Execute(const DPaths& stockPaths, clipof.Execute(paths, -toolRadiusScaled - finishPassOffsetScaled - cornerRoundingOffset); for (const auto& current : paths) { int nesting = getPathNestingLevel(current, paths); - if (nesting % 2 != 0 - && (polyTreeNestingLimit == 0 || nesting <= polyTreeNestingLimit)) { + if (nesting % 2 != 0 && (polyTreeNestingLimit == 0 || nesting <= polyTreeNestingLimit)) { Paths toolBoundPaths; toolBoundPaths.push_back(current); if (polyTreeNestingLimit != nesting) { @@ -1890,8 +1916,7 @@ std::list Adaptive2d::Execute(const DPaths& stockPaths, : 2 * (helixRampRadiusScaled + toolRadiusScaled) + RESOLUTION_FACTOR; for (const auto& current : inputPaths) { int nesting = getPathNestingLevel(current, inputPaths); - if (nesting % 2 != 0 - && (polyTreeNestingLimit == 0 || nesting <= polyTreeNestingLimit)) { + if (nesting % 2 != 0 && (polyTreeNestingLimit == 0 || nesting <= polyTreeNestingLimit)) { Paths profilePaths; profilePaths.push_back(current); if (polyTreeNestingLimit != nesting) { @@ -1920,9 +1945,10 @@ std::list Adaptive2d::Execute(const DPaths& stockPaths, Paths toolBoundPaths; clipof.Clear(); clipof.AddPaths(boundPaths, JoinType::jtRound, EndType::etClosedPolygon); - clipof.Execute(toolBoundPaths, - -toolRadiusScaled - finishPassOffsetScaled - - cornerRoundingOffset); + clipof.Execute( + toolBoundPaths, + -toolRadiusScaled - finishPassOffsetScaled - cornerRoundingOffset + ); /** offset back outwards - corner rounding */ clipof.Clear(); @@ -1944,13 +1970,15 @@ std::list Adaptive2d::Execute(const DPaths& stockPaths, return results; } -bool Adaptive2d::FindEntryPoint(TPaths& progressPaths, - const Paths& toolBoundPaths, - const Paths& boundPaths, - ClearedArea& clearedArea /*output-initial cleared area by helix*/, - IntPoint& entryPoint /*output*/, - IntPoint& toolPos, - DoublePoint& toolDir) +bool Adaptive2d::FindEntryPoint( + TPaths& progressPaths, + const Paths& toolBoundPaths, + const Paths& boundPaths, + ClearedArea& clearedArea /*output-initial cleared area by helix*/, + IntPoint& entryPoint /*output*/, + IntPoint& toolPos, + DoublePoint& toolDir +) { Paths incOffset; Paths lastValidOffset; @@ -2057,7 +2085,8 @@ bool Adaptive2d::FindEntryPointOutside( ClearedArea& clearedArea /*output-initial cleared area by helix*/, IntPoint& entryPoint /*output*/, IntPoint& toolPos, - DoublePoint& toolDir) + DoublePoint& toolDir +) { UNUSED(progressPaths); // to silence compiler warning @@ -2089,8 +2118,10 @@ bool Adaptive2d::FindEntryPointOutside( toolPos = entryPoint; // find tool dir double len = sqrt(DistanceSqrd(lastPoint, checkPoint)); - toolDir = DoublePoint((checkPoint.X - lastPoint.X) / len, - (checkPoint.Y - lastPoint.Y) / len); + toolDir = DoublePoint( + (checkPoint.X - lastPoint.X) / len, + (checkPoint.Y - lastPoint.Y) / len + ); return true; } } @@ -2121,12 +2152,14 @@ bool Adaptive2d::IsClearPath(const Path& tp, ClearedArea& cleared, double safety return collisionArea < 1.0; } -bool Adaptive2d::IsAllowedToCutTrough(const IntPoint& p1, - const IntPoint& p2, - ClearedArea& cleared, - const Paths& toolBoundPaths, - double areaFactor, - bool skipBoundsCheck) +bool Adaptive2d::IsAllowedToCutTrough( + const IntPoint& p1, + const IntPoint& p2, + ClearedArea& cleared, + const Paths& toolBoundPaths, + double areaFactor, + bool skipBoundsCheck +) { Perf_IsAllowedToCutTrough.Start(); @@ -2157,8 +2190,10 @@ bool Adaptive2d::IsAllowedToCutTrough(const IntPoint& p1, stepSize = distance / steps; for (long i = 1; i <= steps; i++) { double p = double(i) / steps; - IntPoint toolPos2(long(p1.X + double(p2.X - p1.X) * p), - long(p1.Y + double(p2.Y - p1.Y) * p)); + IntPoint toolPos2( + long(p1.X + double(p2.X - p1.X) * p), + long(p1.Y + double(p2.Y - p1.Y) * p) + ); double area = CalcCutArea(clip, toolPos1, toolPos2, cleared, false); // if we are cutting above optimal -> not clear to cut if (area > areaFactor * stepSize * optimalCutAreaPD) { @@ -2177,10 +2212,12 @@ bool Adaptive2d::IsAllowedToCutTrough(const IntPoint& p1, return true; } -bool Adaptive2d::ResolveLinkPath(const IntPoint& startPoint, - const IntPoint& endPoint, - ClearedArea& clearedArea, - Path& output) +bool Adaptive2d::ResolveLinkPath( + const IntPoint& startPoint, + const IntPoint& endPoint, + ClearedArea& clearedArea, + Path& output +) { vector> queue; queue.emplace_back(startPoint, endPoint); @@ -2239,13 +2276,14 @@ bool Adaptive2d::ResolveLinkPath(const IntPoint& startPoint, // check for self intersections - if found discard the link path for (size_t i = 0; i < linkPaths.size(); i++) { if (linkPaths[i].front() != pointPair.first && linkPaths[i].back() != pointPair.first - && linkPaths[i].front() != pointPair.second - && linkPaths[i].back() != pointPair.second - && IntersectionPoint(linkPaths[i].front(), - linkPaths[i].back(), - pointPair.first, - pointPair.second, - clp)) { + && linkPaths[i].front() != pointPair.second && linkPaths[i].back() != pointPair.second + && IntersectionPoint( + linkPaths[i].front(), + linkPaths[i].back(), + pointPair.first, + pointPair.second, + clp + )) { cout << "Unable to resolve tool down linking path (self-intersects)." << endl; return false; } @@ -2254,15 +2292,19 @@ bool Adaptive2d::ResolveLinkPath(const IntPoint& startPoint, DoublePoint direction = DirectionV(pointPair.first, pointPair.second); checkPath.clear(); if (pointPair.first == startPoint) { - checkPath.push_back(IntPoint(pointPair.first.X + offClearance * direction.X, - pointPair.first.Y + offClearance * direction.Y)); + checkPath.push_back(IntPoint( + pointPair.first.X + offClearance * direction.X, + pointPair.first.Y + offClearance * direction.Y + )); } else { checkPath.push_back(pointPair.first); } if (pointPair.second == endPoint) { - checkPath.push_back(IntPoint(pointPair.second.X - offClearance * direction.X, - pointPair.second.Y - offClearance * direction.Y)); + checkPath.push_back(IntPoint( + pointPair.second.X - offClearance * direction.X, + pointPair.second.Y - offClearance * direction.Y + )); } else { checkPath.push_back(pointPair.second); @@ -2285,8 +2327,10 @@ bool Adaptive2d::ResolveLinkPath(const IntPoint& startPoint, } DoublePoint pDir(-direction.Y, direction.X); // find mid point - IntPoint midPoint(0.5 * double(pointPair.first.X + pointPair.second.X), - 0.5 * double(pointPair.first.Y + pointPair.second.Y)); + IntPoint midPoint( + 0.5 * double(pointPair.first.X + pointPair.second.X), + 0.5 * double(pointPair.first.Y + pointPair.second.Y) + ); for (long i = 1;; i++) { if (stopProcessing) { return false; @@ -2295,18 +2339,15 @@ bool Adaptive2d::ResolveLinkPath(const IntPoint& startPoint, IntPoint checkPoint1(midPoint.X + offset * pDir.X, midPoint.Y + offset * pDir.Y); IntPoint checkPoint2(midPoint.X - offset * pDir.X, midPoint.Y - offset * pDir.Y); - if (DistancePointToPathsSqrd(clearedArea.GetCleared(), - checkPoint1, - clp, - pindex, - sindex, - par) - < DistancePointToPathsSqrd(clearedArea.GetCleared(), - checkPoint2, - clp, - pindex, - sindex, - par)) { + if (DistancePointToPathsSqrd(clearedArea.GetCleared(), checkPoint1, clp, pindex, sindex, par) + < DistancePointToPathsSqrd( + clearedArea.GetCleared(), + checkPoint2, + clp, + pindex, + sindex, + par + )) { // exchange points IntPoint tmp = checkPoint2; checkPoint2 = checkPoint1; @@ -2344,13 +2385,15 @@ bool Adaptive2d::ResolveLinkPath(const IntPoint& startPoint, return true; } -bool Adaptive2d::MakeLeadPath(bool leadIn, - const IntPoint& startPoint, - const DoublePoint& startDir, - const IntPoint& beaconPoint, - ClearedArea& clearedArea, - const Paths& toolBoundPaths, - Path& output) +bool Adaptive2d::MakeLeadPath( + bool leadIn, + const IntPoint& startPoint, + const DoublePoint& startDir, + const IntPoint& beaconPoint, + ClearedArea& clearedArea, + const Paths& toolBoundPaths, + Path& output +) { IntPoint currentPoint = startPoint; DoublePoint targetDir = DirectionV(currentPoint, beaconPoint); @@ -2358,19 +2401,23 @@ bool Adaptive2d::MakeLeadPath(bool leadIn, double stepSize = 0.2 * stepOverScaled + 1; double maxPathLen = stepOverScaled; DoublePoint nextDir = startDir; - IntPoint nextPoint = - IntPoint(currentPoint.X + nextDir.X * stepSize, currentPoint.Y + nextDir.Y * stepSize); + IntPoint nextPoint + = IntPoint(currentPoint.X + nextDir.X * stepSize, currentPoint.Y + nextDir.Y * stepSize); Path checkPath; double adaptFactor = 0.4; double alfa = std::numbers::pi / 64; double pathLen = 0; checkPath.push_back(nextPoint); for (int i = 0; i < 10000; i++) { - if (IsAllowedToCutTrough(IntPoint(currentPoint.X + RESOLUTION_FACTOR * nextDir.X, - currentPoint.Y + RESOLUTION_FACTOR * nextDir.Y), - nextPoint, - clearedArea, - toolBoundPaths)) { + if (IsAllowedToCutTrough( + IntPoint( + currentPoint.X + RESOLUTION_FACTOR * nextDir.X, + currentPoint.Y + RESOLUTION_FACTOR * nextDir.Y + ), + nextPoint, + clearedArea, + toolBoundPaths + )) { if (output.empty()) { output.push_back(currentPoint); } @@ -2378,8 +2425,10 @@ bool Adaptive2d::MakeLeadPath(bool leadIn, currentPoint = nextPoint; pathLen += stepSize; targetDir = DirectionV(currentPoint, beaconPoint); - nextDir = DoublePoint(nextDir.X + adaptFactor * targetDir.X, - nextDir.Y + adaptFactor * targetDir.Y); + nextDir = DoublePoint( + nextDir.X + adaptFactor * targetDir.X, + nextDir.Y + adaptFactor * targetDir.Y + ); NormalizeV(nextDir); if (pathLen > maxPathLen) { break; @@ -2391,20 +2440,22 @@ bool Adaptive2d::MakeLeadPath(bool leadIn, else { nextDir = rotate(nextDir, leadIn ? -alfa : alfa); } - nextPoint = - IntPoint(currentPoint.X + nextDir.X * stepSize, currentPoint.Y + nextDir.Y * stepSize); + nextPoint + = IntPoint(currentPoint.X + nextDir.X * stepSize, currentPoint.Y + nextDir.Y * stepSize); } if (output.empty()) { output.push_back(startPoint); } return true; } -void Adaptive2d::AppendToolPath(TPaths& progressPaths, - AdaptiveOutput& output, - const Path& passToolPath, - ClearedArea& clearedBefore, - ClearedArea& clearedAfter, - const Paths& toolBoundPaths) +void Adaptive2d::AppendToolPath( + TPaths& progressPaths, + AdaptiveOutput& output, + const Path& passToolPath, + ClearedArea& clearedBefore, + ClearedArea& clearedAfter, + const Paths& toolBoundPaths +) { if (passToolPath.size() < 2) { return; @@ -2421,10 +2472,11 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, auto& lastPrevTPoint = lastTPath.second.at(lastTPath.second.size() - 2); auto& lastTPoint = lastTPath.second.back(); - IntPoint startPrevPoint(long(lastPrevTPoint.first * scaleFactor), - long(lastPrevTPoint.second * scaleFactor)); - IntPoint startPoint(long(lastTPoint.first * scaleFactor), - long(lastTPoint.second * scaleFactor)); + IntPoint startPrevPoint( + long(lastPrevTPoint.first * scaleFactor), + long(lastPrevTPoint.second * scaleFactor) + ); + IntPoint startPoint(long(lastTPoint.first * scaleFactor), long(lastTPoint.second * scaleFactor)); ClipperOffset clipof; // first we try to cut through the linking move for short distances @@ -2453,43 +2505,47 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, beaconOffset = linkDistance / 2; } - DistancePointToPathsSqrd(toolBoundPaths, - startPoint, - clp, - clpPathIndex, - clpSegmentIndex, - clpParameter); + DistancePointToPathsSqrd( + toolBoundPaths, + startPoint, + clp, + clpPathIndex, + clpSegmentIndex, + clpParameter + ); DoublePoint startDir = GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex); - DistancePointToPathsSqrd(toolBoundPaths, - endPoint, - clp, - clpPathIndex, - clpSegmentIndex, - clpParameter); + DistancePointToPathsSqrd( + toolBoundPaths, + endPoint, + clp, + clpPathIndex, + clpSegmentIndex, + clpParameter + ); DoublePoint endDir = GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex); - IntPoint startBeacon(startPoint.X - beaconOffset * (startDir.Y - startDir.X), - startPoint.Y + beaconOffset * (startDir.X + startDir.Y)); - IntPoint endBeacon(endPoint.X - beaconOffset * (endDir.X + endDir.Y), - endPoint.Y + beaconOffset * (endDir.X - endDir.Y)); + IntPoint startBeacon( + startPoint.X - beaconOffset * (startDir.Y - startDir.X), + startPoint.Y + beaconOffset * (startDir.X + startDir.Y) + ); + IntPoint endBeacon( + endPoint.X - beaconOffset * (endDir.X + endDir.Y), + endPoint.Y + beaconOffset * (endDir.X - endDir.Y) + ); Path leadOutPath; - MakeLeadPath(false, - startPoint, - startDir, - startBeacon, - clearedBefore, - toolBoundPaths, - leadOutPath); + MakeLeadPath(false, startPoint, startDir, startBeacon, clearedBefore, toolBoundPaths, leadOutPath); Path leadInPath; - MakeLeadPath(true, - endPoint, - DoublePoint(-endDir.X, -endDir.Y), - endBeacon, - clearedBefore, - toolBoundPaths, - leadInPath); + MakeLeadPath( + true, + endPoint, + DoublePoint(-endDir.X, -endDir.Y), + endBeacon, + clearedBefore, + toolBoundPaths, + leadInPath + ); ReversePath(leadInPath); Path linkPath; @@ -2509,7 +2565,8 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, if (l >= remainingLeadInExtension) { IntPoint splitPoint( p1.X + (p2.X - p1.X) * (l - remainingLeadInExtension) / l, - p1.Y + (p2.Y - p1.Y) * (l - remainingLeadInExtension) / l); + p1.Y + (p2.Y - p1.Y) * (l - remainingLeadInExtension) / l + ); linkPath.pop_back(); linkPath.push_back(splitPoint); leadInPath.insert(leadInPath.begin(), splitPoint); @@ -2541,16 +2598,17 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, double dist = sqrt(DistanceSqrd(leadOutPath.back(), leadInPath.front())); if (dist < 2 * stepOverScaled && IsAllowedToCutTrough( - IntPoint(leadOutPath.back().X - + (leadInPath.front().X - leadOutPath.back().X) / dist, - leadOutPath.back().Y - + (leadInPath.front().Y - leadOutPath.back().Y) / dist), - IntPoint(leadInPath.front().X - - (leadInPath.front().X - leadOutPath.back().X) / dist, - leadInPath.front().Y - - (leadInPath.front().Y - leadOutPath.back().Y) / dist), + IntPoint( + leadOutPath.back().X + (leadInPath.front().X - leadOutPath.back().X) / dist, + leadOutPath.back().Y + (leadInPath.front().Y - leadOutPath.back().Y) / dist + ), + IntPoint( + leadInPath.front().X - (leadInPath.front().X - leadOutPath.back().X) / dist, + leadInPath.front().Y - (leadInPath.front().Y - leadOutPath.back().Y) / dist + ), clearedBefore, - toolBoundPaths)) { + toolBoundPaths + )) { linkType = MotionType::mtCutting; } // add direct linking move at clear height @@ -2578,8 +2636,7 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, TPath linkPath1; linkPath1.first = MotionType::mtCutting; for (const auto& pt : leadOutPath) { - linkPath1.second.emplace_back(double(pt.X) / scaleFactor, - double(pt.Y) / scaleFactor); + linkPath1.second.emplace_back(double(pt.X) / scaleFactor, double(pt.Y) / scaleFactor); } output.AdaptivePaths.push_back(linkPath1); @@ -2587,8 +2644,7 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, TPath linkPath2; linkPath2.first = linkType; for (const auto& pt : linkPath) { - linkPath2.second.emplace_back(double(pt.X) / scaleFactor, - double(pt.Y) / scaleFactor); + linkPath2.second.emplace_back(double(pt.X) / scaleFactor, double(pt.Y) / scaleFactor); } output.AdaptivePaths.push_back(linkPath2); @@ -2596,8 +2652,7 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, TPath linkPath3; linkPath3.first = MotionType::mtCutting; for (const auto& pt : leadInPath) { - linkPath3.second.emplace_back(double(pt.X) / scaleFactor, - double(pt.Y) / scaleFactor); + linkPath3.second.emplace_back(double(pt.X) / scaleFactor, double(pt.Y) / scaleFactor); } output.AdaptivePaths.push_back(linkPath3); @@ -2623,10 +2678,14 @@ void Adaptive2d::AppendToolPath(TPaths& progressPaths, TPath linkPath; linkPath.first = mt; - linkPath.second.emplace_back(double(startPoint.X) / scaleFactor, - double(startPoint.Y) / scaleFactor); - linkPath.second.emplace_back(double(endPoint.X) / scaleFactor, - double(endPoint.Y) / scaleFactor); + linkPath.second.emplace_back( + double(startPoint.X) / scaleFactor, + double(startPoint.Y) / scaleFactor + ); + linkPath.second.emplace_back( + double(endPoint.X) / scaleFactor, + double(endPoint.Y) / scaleFactor + ); output.AdaptivePaths.push_back(linkPath); } } @@ -2683,11 +2742,15 @@ void Adaptive2d::AddPathsToProgress(TPaths& progressPaths, Paths paths, MotionTy progressPaths.push_back(TPath()); progressPaths.back().first = mt; for (const auto pt : pth) { - progressPaths.back().second.emplace_back(double(pt.X) / scaleFactor, - double(pt.Y) / scaleFactor); + progressPaths.back().second.emplace_back( + double(pt.X) / scaleFactor, + double(pt.Y) / scaleFactor + ); } - progressPaths.back().second.emplace_back(double(pth.front().X) / scaleFactor, - double(pth.front().Y) / scaleFactor); + progressPaths.back().second.emplace_back( + double(pth.front().X) / scaleFactor, + double(pth.front().Y) / scaleFactor + ); } } } @@ -2698,8 +2761,10 @@ void Adaptive2d::AddPathToProgress(TPaths& progressPaths, const Path pth, Motion progressPaths.push_back(TPath()); progressPaths.back().first = mt; for (const auto pt : pth) { - progressPaths.back().second.emplace_back(double(pt.X) / scaleFactor, - double(pt.Y) / scaleFactor); + progressPaths.back().second.emplace_back( + double(pt.X) / scaleFactor, + double(pt.Y) / scaleFactor + ); } } } @@ -2735,13 +2800,15 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) Paths engageBounds = toolBoundPaths; if (!forceInsideOut - && FindEntryPointOutside(progressPaths, - toolBoundPaths, - boundPaths, - cleared, - entryPoint, - toolPos, - toolDir)) { + && FindEntryPointOutside( + progressPaths, + toolBoundPaths, + boundPaths, + cleared, + entryPoint, + toolPos, + toolDir + )) { if (!Orientation(engageBounds[0])) { ReversePath(engageBounds[0]); } @@ -2758,13 +2825,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) outsideEntry = true; } else { - if (!FindEntryPoint(progressPaths, - toolBoundPaths, - boundPaths, - cleared, - entryPoint, - toolPos, - toolDir)) { + if (!FindEntryPoint(progressPaths, toolBoundPaths, boundPaths, cleared, entryPoint, toolPos, toolDir)) { Perf_ProcessPolyNode.Stop(); return; } @@ -2797,8 +2858,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) CheckReportProgress(progressPaths, true); IntPoint startPoint = toolPos; - output.StartPoint = - DPoint(double(startPoint.X) / scaleFactor, double(startPoint.Y) / scaleFactor); + output.StartPoint = DPoint(double(startPoint.X) / scaleFactor, double(startPoint.Y) / scaleFactor); Path passToolPath; // to store pass toolpath Path toClearPath; @@ -2876,14 +2936,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) AverageDirection(gyro, toolDir); Perf_DistanceToBoundary.Start(); - double distanceToBoundary = sqrt(DistancePointToPathsSqrd(toolBoundPaths, - toolPos, - clp, - clpPathIndex, - clpSegmentIndex, - clpParameter)); - DoublePoint boundaryDir = - GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex); + double distanceToBoundary = sqrt( + DistancePointToPathsSqrd(toolBoundPaths, toolPos, clp, clpPathIndex, clpSegmentIndex, clpParameter) + ); + DoublePoint boundaryDir = GetPathDirectionV(toolBoundPaths[clpPathIndex], clpSegmentIndex); double distBoundaryPointToEngage = sqrt(DistanceSqrd(clp, engagePoint)); Perf_DistanceToBoundary.Stop(); @@ -2943,8 +2999,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) angle = interp.clampAngle(angle); newToolDir = rotate(toolDir, angle); - newToolPos = IntPoint(long(toolPos.X + newToolDir.X * stepScaled), - long(toolPos.Y + newToolDir.Y * stepScaled)); + newToolPos = IntPoint( + long(toolPos.X + newToolDir.X * stepScaled), + long(toolPos.Y + newToolDir.Y * stepScaled) + ); area = CalcCutArea(clip, toolPos, newToolPos, cleared); @@ -2978,11 +3036,15 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) && distanceToEngage > 2 * stepOverScaled && distBoundaryPointToEngage > 2 * stepOverScaled) { double wb = 1 - relDistToBoundary; - newToolDir = DoublePoint(newToolDir.X + wb * boundaryDir.X, - newToolDir.Y + wb * boundaryDir.Y); + newToolDir = DoublePoint( + newToolDir.X + wb * boundaryDir.X, + newToolDir.Y + wb * boundaryDir.Y + ); NormalizeV(newToolDir); - newToolPos = IntPoint(long(toolPos.X + newToolDir.X * stepScaled), - long(toolPos.Y + newToolDir.Y * stepScaled)); + newToolPos = IntPoint( + long(toolPos.X + newToolDir.X * stepScaled), + long(toolPos.Y + newToolDir.Y * stepScaled) + ); recalcArea = true; } @@ -2995,8 +3057,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) // if new tool pos. outside boundary rotate until back in recalcArea = true; newToolDir = rotate(newToolDir, std::numbers::pi / 90); - newToolPos = IntPoint(long(toolPos.X + newToolDir.X * stepScaled), - long(toolPos.Y + newToolDir.Y * stepScaled)); + newToolPos = IntPoint( + long(toolPos.X + newToolDir.X * stepScaled), + long(toolPos.Y + newToolDir.Y * stepScaled) + ); } if (rotateStep >= 180) { #ifdef DEV_MODE @@ -3045,8 +3109,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) entryPoint = toolPos; output.HelixCenterPoint.first = double(entryPoint.X) / scaleFactor; output.HelixCenterPoint.second = double(entryPoint.Y) / scaleFactor; - output.StartPoint = DPoint(double(entryPoint.X) / scaleFactor, - double(entryPoint.Y) / scaleFactor); + output.StartPoint = DPoint( + double(entryPoint.X) / scaleFactor, + double(entryPoint.Y) / scaleFactor + ); } passToolPath.push_back(toolPos); } @@ -3059,8 +3125,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) if (progressPaths.empty()) { progressPaths.push_back(TPath()); } - progressPaths.back().second.emplace_back(double(newToolPos.X) / scaleFactor, - double(newToolPos.Y) / scaleFactor); + progressPaths.back().second.emplace_back( + double(newToolPos.X) / scaleFactor, + double(newToolPos.Y) / scaleFactor + ); // append gyro gyro.push_back(newToolDir); @@ -3091,12 +3159,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) Path cleaned; CleanPath(passToolPath, cleaned, CLEAN_PATH_TOLERANCE); total_output_points += long(cleaned.size()); - AppendToolPath(progressPaths, - output, - cleaned, - clearedBeforePass, - cleared, - toolBoundPaths); + AppendToolPath(progressPaths, output, cleaned, clearedBeforePass, cleared, toolBoundPaths); CheckReportProgress(progressPaths); bad_engage_count = 0; engage.ResetPasses(); @@ -3118,23 +3181,25 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) else { double moveDistance = ENGAGE_SCAN_DISTANCE_FACTOR * stepOverScaled * refinement_factor; - if (!engage.nextEngagePoint(this, - cleared, - moveDistance, - ENGAGE_AREA_THR_FACTOR * optimalCutAreaPD - * RESOLUTION_FACTOR, - 4 * referenceCutArea * stepOverFactor)) { + if (!engage.nextEngagePoint( + this, + cleared, + moveDistance, + ENGAGE_AREA_THR_FACTOR * optimalCutAreaPD * RESOLUTION_FACTOR, + 4 * referenceCutArea * stepOverFactor + )) { // check if there are any uncleared area left Paths remaining; for (const auto& p : cleared.GetCleared()) { if (!p.empty() && IsPointWithinCutRegion(toolBoundPaths, p.front()) - && DistancePointToPathsSqrd(boundPaths, - p.front(), - clp, - clpPathIndex, - clpSegmentIndex, - clpParameter) - > 4 * toolRadiusScaled * toolRadiusScaled) { + && DistancePointToPathsSqrd( + boundPaths, + p.front(), + clp, + clpPathIndex, + clpSegmentIndex, + clpParameter + ) > 4 * toolRadiusScaled * toolRadiusScaled) { remaining.push_back(p); } }; @@ -3143,8 +3208,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) break; } else { - cout << "Clearing " << remaining.size() << " remaining internal path(s)." - << endl; + cout << "Clearing " << remaining.size() << " remaining internal path(s)." << endl; } // try to find new engage point along the remaining @@ -3155,12 +3219,13 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) ReversePaths(remaining); engage.SetPaths(remaining); engage.moveToClosestPoint(newToolPos, stepScaled + 1); - if (!engage.nextEngagePoint(this, - cleared, - moveDistance, - ENGAGE_AREA_THR_FACTOR * optimalCutAreaPD - * RESOLUTION_FACTOR, - 4 * referenceCutArea * stepOverFactor)) { + if (!engage.nextEngagePoint( + this, + cleared, + moveDistance, + ENGAGE_AREA_THR_FACTOR * optimalCutAreaPD * RESOLUTION_FACTOR, + 4 * referenceCutArea * stepOverFactor + )) { break; } } @@ -3186,8 +3251,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) Path finShiftedPath; bool allCutsAllowed = true; - while (!stopProcessing - && PopPathWithClosestPoint(finishingPaths, lastPoint, finShiftedPath)) { + while (!stopProcessing && PopPathWithClosestPoint(finishingPaths, lastPoint, finShiftedPath)) { if (finShiftedPath.empty()) { continue; } @@ -3198,8 +3262,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) for (const auto& pt : finShiftedPath) { // midpoint - if (IsPointWithinCutRegion(stockInputPaths, - IntPoint((p1.X + pt.X) / 2, (p1.Y + pt.Y) / 2))) { + if (IsPointWithinCutRegion( + stockInputPaths, + IntPoint((p1.X + pt.X) / 2, (p1.Y + pt.Y) / 2) + )) { allPointsOutside = false; break; } @@ -3218,8 +3284,10 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) progressPaths.push_back(TPath()); // show in progress cb for (auto& pt : finShiftedPath) { - progressPaths.back().second.emplace_back(double(pt.X) / scaleFactor, - double(pt.Y) / scaleFactor); + progressPaths.back().second.emplace_back( + double(pt.X) / scaleFactor, + double(pt.Y) / scaleFactor + ); } if (!finShiftedPath.empty()) { @@ -3231,12 +3299,14 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) // sanity check for finishing paths - check the area of finishing cut for (size_t i = 1; i < finCleaned.size(); i++) { - if (!IsAllowedToCutTrough(finCleaned.at(i - 1), - finCleaned.at(i), - cleared, - toolBoundPaths, - 2.0, - true)) { + if (!IsAllowedToCutTrough( + finCleaned.at(i - 1), + finCleaned.at(i), + cleared, + toolBoundPaths, + 2.0, + true + )) { allCutsAllowed = false; } } @@ -3256,8 +3326,8 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) Path returnPath; returnPath << lastPoint; returnPath << entryPoint; - output.ReturnMotionType = - IsClearPath(returnPath, cleared) ? MotionType::mtLinkClear : MotionType::mtLinkNotClear; + output.ReturnMotionType = IsClearPath(returnPath, cleared) ? MotionType::mtLinkClear + : MotionType::mtLinkNotClear; // dump performance results #ifdef DEV_MODE diff --git a/src/Mod/CAM/libarea/Adaptive.hpp b/src/Mod/CAM/libarea/Adaptive.hpp index 2dc9ed1c50..6dc9ff9788 100644 --- a/src/Mod/CAM/libarea/Adaptive.hpp +++ b/src/Mod/CAM/libarea/Adaptive.hpp @@ -28,19 +28,19 @@ #include #ifndef ADAPTIVE_HPP -#define ADAPTIVE_HPP +# define ADAPTIVE_HPP -#ifndef __DBL_MAX__ -#define __DBL_MAX__ 1.7976931348623158e+308 -#endif +# ifndef __DBL_MAX__ +# define __DBL_MAX__ 1.7976931348623158e+308 +# endif -#ifndef __LONG_MAX__ -#define __LONG_MAX__ 2147483647 -#endif +# ifndef __LONG_MAX__ +# define __LONG_MAX__ 2147483647 +# endif // #define DEV_MODE -#define NTOL 1.0e-7 // numeric tolerance +# define NTOL 1.0e-7 // numeric tolerance namespace AdaptivePath { @@ -96,16 +96,18 @@ public: double keepToolDownDistRatio = 3.0; // keep tool down distance ratio OperationType opType = OperationType::otClearingInside; - std::list Execute(const DPaths& stockPaths, - const DPaths& paths, - std::function progressCallbackFn); + std::list Execute( + const DPaths& stockPaths, + const DPaths& paths, + std::function progressCallbackFn + ); -#ifdef DEV_MODE +# ifdef DEV_MODE /*for debugging*/ std::function DrawCircleFn; std::function DrawPathFn; std::function ClearScreenFn; -#endif +# endif private: std::list results; @@ -127,72 +129,87 @@ private: Path toolGeometry; // tool geometry at coord 0,0, should not be modified void ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths); - bool FindEntryPoint(TPaths& progressPaths, - const Paths& toolBoundPaths, - const Paths& bound, - ClearedArea& cleared /*output*/, - IntPoint& entryPoint /*output*/, - IntPoint& toolPos, - DoublePoint& toolDir); - bool FindEntryPointOutside(TPaths& progressPaths, - const Paths& toolBoundPaths, - const Paths& bound, - ClearedArea& cleared /*output*/, - IntPoint& entryPoint /*output*/, - IntPoint& toolPos, - DoublePoint& toolDir); - double CalcCutArea(Clipper& clip, - const IntPoint& toolPos, - const IntPoint& newToolPos, - ClearedArea& clearedArea, - bool preventConventionalMode = true); - void AppendToolPath(TPaths& progressPaths, - AdaptiveOutput& output, - const Path& passToolPath, - ClearedArea& clearedAreaBefore, - ClearedArea& clearedAreaAfter, - const Paths& toolBoundPaths); + bool FindEntryPoint( + TPaths& progressPaths, + const Paths& toolBoundPaths, + const Paths& bound, + ClearedArea& cleared /*output*/, + IntPoint& entryPoint /*output*/, + IntPoint& toolPos, + DoublePoint& toolDir + ); + bool FindEntryPointOutside( + TPaths& progressPaths, + const Paths& toolBoundPaths, + const Paths& bound, + ClearedArea& cleared /*output*/, + IntPoint& entryPoint /*output*/, + IntPoint& toolPos, + DoublePoint& toolDir + ); + double CalcCutArea( + Clipper& clip, + const IntPoint& toolPos, + const IntPoint& newToolPos, + ClearedArea& clearedArea, + bool preventConventionalMode = true + ); + void AppendToolPath( + TPaths& progressPaths, + AdaptiveOutput& output, + const Path& passToolPath, + ClearedArea& clearedAreaBefore, + ClearedArea& clearedAreaAfter, + const Paths& toolBoundPaths + ); bool IsClearPath(const Path& path, ClearedArea& clearedArea, double safetyDistanceScaled = 0); - bool IsAllowedToCutTrough(const IntPoint& p1, - const IntPoint& p2, - ClearedArea& clearedArea, - const Paths& toolBoundPaths, - double areaFactor = 1.5, - bool skipBoundsCheck = false); - bool MakeLeadPath(bool leadIn, - const IntPoint& startPoint, - const DoublePoint& startDir, - const IntPoint& beaconPoint, - ClearedArea& clearedArea, - const Paths& toolBoundPaths, - Path& output); + bool IsAllowedToCutTrough( + const IntPoint& p1, + const IntPoint& p2, + ClearedArea& clearedArea, + const Paths& toolBoundPaths, + double areaFactor = 1.5, + bool skipBoundsCheck = false + ); + bool MakeLeadPath( + bool leadIn, + const IntPoint& startPoint, + const DoublePoint& startDir, + const IntPoint& beaconPoint, + ClearedArea& clearedArea, + const Paths& toolBoundPaths, + Path& output + ); - bool ResolveLinkPath(const IntPoint& startPoint, - const IntPoint& endPoint, - ClearedArea& clearedArea, - Path& output); + bool ResolveLinkPath( + const IntPoint& startPoint, + const IntPoint& endPoint, + ClearedArea& clearedArea, + Path& output + ); friend class EngagePoint; // for CalcCutArea void CheckReportProgress(TPaths& progressPaths, bool force = false); - void AddPathsToProgress(TPaths& progressPaths, - const Paths paths, - MotionType mt = MotionType::mtCutting); - void - AddPathToProgress(TPaths& progressPaths, const Path pth, MotionType mt = MotionType::mtCutting); + void AddPathsToProgress( + TPaths& progressPaths, + const Paths paths, + MotionType mt = MotionType::mtCutting + ); + void AddPathToProgress(TPaths& progressPaths, const Path pth, MotionType mt = MotionType::mtCutting); void ApplyStockToLeave(Paths& inputPaths); private: // constants for fine tuning const double RESOLUTION_FACTOR = 16.0; const int MAX_ITERATIONS = 10; - const double AREA_ERROR_FACTOR = - 0.05; /* how precise to match the cut area to optimal, reasonable value: 0.05 = 5%*/ + const double AREA_ERROR_FACTOR = 0.05; /* how precise to match the cut area to optimal, + reasonable value: 0.05 = 5%*/ const size_t ANGLE_HISTORY_POINTS = 3; // used for angle prediction const int DIRECTION_SMOOTHING_BUFLEN = 3; // gyro points - used for angle smoothing - const double MIN_CUT_AREA_FACTOR = - 0.1; // used for filtering out of insignificant cuts (should be < ENGAGE_AREA_THR_FACTOR) + const double MIN_CUT_AREA_FACTOR = 0.1; // used for filtering out of insignificant cuts (should + // be < ENGAGE_AREA_THR_FACTOR) const double ENGAGE_AREA_THR_FACTOR = 0.5; // influences minimal engage area const double ENGAGE_SCAN_DISTANCE_FACTOR = 0.2; // influences the engage scan/stepping distance diff --git a/src/Mod/CAM/libarea/Arc.h b/src/Mod/CAM/libarea/Arc.h index 8092d17502..a392aa8c68 100644 --- a/src/Mod/CAM/libarea/Arc.h +++ b/src/Mod/CAM/libarea/Arc.h @@ -29,9 +29,8 @@ public: , m_user_data(user_data) {} - void - SetDirWithPoint(const Point& p); // set m_dir, such that this point lies between m_s and m_e - double IncludedAngle() const; // always > 0 + void SetDirWithPoint(const Point& p); // set m_dir, such that this point lies between m_s and m_e + double IncludedAngle() const; // always > 0 bool AlmostALine() const; Point MidParam(double param) const; void GetSegments(void (*callbackfunc)(const double* p), double pixels_per_mm) const; diff --git a/src/Mod/CAM/libarea/Area.cpp b/src/Mod/CAM/libarea/Area.cpp index bbb4fa987f..53c6631727 100644 --- a/src/Mod/CAM/libarea/Area.cpp +++ b/src/Mod/CAM/libarea/Area.cpp @@ -27,24 +27,24 @@ bool CArea::m_set_processing_length_in_split = false; double CArea::m_after_MakeOffsets_length = 0.0; // static const double PI = 3.1415926535897932; -#define _CAREA_PARAM_DEFINE(_class, _type, _name) \ - _type CArea::get_##_name() \ - { \ - return _class::_name; \ - } \ - void CArea::set_##_name(_type _name) \ - { \ - _class::_name = _name; \ +#define _CAREA_PARAM_DEFINE(_class, _type, _name) \ + _type CArea::get_##_name() \ + { \ + return _class::_name; \ + } \ + void CArea::set_##_name(_type _name) \ + { \ + _class::_name = _name; \ } -#define CAREA_PARAM_DEFINE(_type, _name) \ - _type CArea::get_##_name() \ - { \ - return m_##_name; \ - } \ - void CArea::set_##_name(_type _name) \ - { \ - m_##_name = _name; \ +#define CAREA_PARAM_DEFINE(_type, _name) \ + _type CArea::get_##_name() \ + { \ + return m_##_name; \ + } \ + void CArea::set_##_name(_type _name) \ + { \ + m_##_name = _name; \ } _CAREA_PARAM_DEFINE(Point, double, tolerance) @@ -228,14 +228,18 @@ static double one_over_units = 0.0; static Point rotated_point(const Point& p) { - return Point(p.x * cos_angle_for_zigs - p.y * sin_angle_for_zigs, - p.x * sin_angle_for_zigs + p.y * cos_angle_for_zigs); + return Point( + p.x * cos_angle_for_zigs - p.y * sin_angle_for_zigs, + p.x * sin_angle_for_zigs + p.y * cos_angle_for_zigs + ); } static Point unrotated_point(const Point& p) { - return Point(p.x * cos_minus_angle_for_zigs - p.y * sin_minus_angle_for_zigs, - p.x * sin_minus_angle_for_zigs + p.y * cos_minus_angle_for_zigs); + return Point( + p.x * cos_minus_angle_for_zigs - p.y * sin_minus_angle_for_zigs, + p.x * sin_minus_angle_for_zigs + p.y * cos_minus_angle_for_zigs + ); } static CVertex rotated_vertex(const CVertex& v) @@ -267,13 +271,7 @@ static void rotate_area(CArea& a) } } -void test_y_point(int i, - const Point& p, - Point& best_p, - bool& found, - int& best_index, - double y, - bool left_not_right) +void test_y_point(int i, const Point& p, Point& best_p, bool& found, int& best_index, double y, bool left_not_right) { // only consider points at y if (fabs(p.y - y) < 0.002 * one_over_units) { @@ -334,27 +332,9 @@ static void make_zig_curve(const CCurve& input_curve, double y0, double y) VIt++, i++) { const CVertex& vertex = *VIt; - test_y_point(i, - vertex.m_p, - top_right, - top_right_found, - top_right_index, - y, - !rightward_for_zigs); - test_y_point(i, - vertex.m_p, - top_left, - top_left_found, - top_left_index, - y, - rightward_for_zigs); - test_y_point(i, - vertex.m_p, - bottom_left, - bottom_left_found, - bottom_left_index, - y0, - rightward_for_zigs); + test_y_point(i, vertex.m_p, top_right, top_right_found, top_right_index, y, !rightward_for_zigs); + test_y_point(i, vertex.m_p, top_left, top_left_found, top_left_index, y, rightward_for_zigs); + test_y_point(i, vertex.m_p, bottom_left, bottom_left_found, bottom_left_index, y0, rightward_for_zigs); } int start_index = 0; @@ -606,8 +586,7 @@ static void zigzag(const CArea& input_a) CArea::m_processing_done += 0.2 * CArea::m_single_area_processing_length; } -void CArea::SplitAndMakePocketToolpath(std::list& curve_list, - const CAreaPocketParams& params) const +void CArea::SplitAndMakePocketToolpath(std::list& curve_list, const CAreaPocketParams& params) const { CArea::m_processing_done = 0.0; @@ -728,16 +707,14 @@ void CArea::MakePocketToolpath(std::list& curve_list, const CAreaPocketP } else { if (nmin != endCurve.m_vertices.back().m_p) { - endCurve.append(CVertex(smin.m_v.m_type, - nmin, - smin.m_v.m_c, - smin.m_v.m_user_data)); + endCurve.append( + CVertex(smin.m_v.m_type, nmin, smin.m_v.m_c, smin.m_v.m_user_data) + ); } if (nmin != it->m_v.m_p) { - startCurve.append(CVertex(smin.m_v.m_type, - it->m_v.m_p, - smin.m_v.m_c, - smin.m_v.m_user_data)); + startCurve.append( + CVertex(smin.m_v.m_type, it->m_v.m_p, smin.m_v.m_c, smin.m_v.m_user_data) + ); } } } @@ -747,8 +724,7 @@ void CArea::MakePocketToolpath(std::list& curve_list, const CAreaPocketP // curve const auto appendCurve = [&curve_list](const CCurve& curve) { if (curve_list.size() > 0 - && curve_list.back().m_vertices.back().m_p - == curve.m_vertices.front().m_p) { + && curve_list.back().m_vertices.back().m_p == curve.m_vertices.front().m_p) { auto it = curve.m_vertices.begin(); for (it++; it != curve.m_vertices.end(); it++) { curve_list.back().append(*it); @@ -809,8 +785,7 @@ void CArea::Split(std::list& m_areas) const return; } - for (std::list::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); - It++) { + for (std::list::const_iterator It = a.m_curves.begin(); It != a.m_curves.end(); It++) { const CCurve& curve = *It; if (curve.IsClockwise()) { if (m_areas.size() > 0) { @@ -978,8 +953,7 @@ void CArea::InsideCurves(const CCurve& curve, std::list& curves_inside) curve.ExtractSeparateCurves(pts, separate_curves); // 3. if the midpoint of a separate curve lies in a1, then we return it. - for (std::list::iterator It = separate_curves.begin(); It != separate_curves.end(); - It++) { + for (std::list::iterator It = separate_curves.begin(); It != separate_curves.end(); It++) { CCurve& curve = *It; double length = curve.Perim(); Point mid_point = curve.PerimToPoint(length * 0.5); diff --git a/src/Mod/CAM/libarea/Area.h b/src/Mod/CAM/libarea/Area.h index f540c51cad..7eb2ed82ad 100644 --- a/src/Mod/CAM/libarea/Area.h +++ b/src/Mod/CAM/libarea/Area.h @@ -28,12 +28,14 @@ struct CAreaPocketParams PocketMode mode; double zig_angle; bool only_cut_first_offset; - CAreaPocketParams(double Tool_radius, - double Extra_offset, - double Stepover, - bool From_center, - PocketMode Mode, - double Zig_angle) + CAreaPocketParams( + double Tool_radius, + double Extra_offset, + double Stepover, + bool From_center, + PocketMode Mode, + double Zig_angle + ) { tool_radius = Tool_radius; extra_offset = Extra_offset; @@ -75,11 +77,13 @@ public: static CArea UniteCurves(std::list& curves); void Xor(const CArea& a2); void Offset(double inwards_value); - void OffsetWithClipper(double offset, - ClipperLib::JoinType joinType = ClipperLib::jtRound, - ClipperLib::EndType endType = ClipperLib::etOpenRound, - double miterLimit = 5.0, - double roundPrecision = 0.0); + void OffsetWithClipper( + double offset, + ClipperLib::JoinType joinType = ClipperLib::jtRound, + ClipperLib::EndType endType = ClipperLib::etOpenRound, + double miterLimit = 5.0, + double roundPrecision = 0.0 + ); void Thicken(double value); void FitArcs(); unsigned int num_curves() @@ -90,8 +94,7 @@ public: void GetBox(CBox2D& box); void Reorder(); void MakePocketToolpath(std::list& toolpath, const CAreaPocketParams& params) const; - void SplitAndMakePocketToolpath(std::list& toolpath, - const CAreaPocketParams& params) const; + void SplitAndMakePocketToolpath(std::list& toolpath, const CAreaPocketParams& params) const; void MakeOnePocketCurve(std::list& curve_list, const CAreaPocketParams& params) const; static bool HolesLinked(); void Split(std::list& m_areas) const; @@ -103,8 +106,8 @@ public: void ChangeStartToNearest(const Point* pstart = NULL, double min_dist = 1.0); // Avoid outside direct accessing static member variable because of Windows DLL issue -#define CAREA_PARAM_DECLARE(_type, _name) \ - static _type get_##_name(); \ +#define CAREA_PARAM_DECLARE(_type, _name) \ + static _type get_##_name(); \ static void set_##_name(_type _name); CAREA_PARAM_DECLARE(double, tolerance) @@ -119,10 +122,12 @@ public: // Following functions is add to operate on possible open curves void PopulateClipper(ClipperLib::Clipper& c, ClipperLib::PolyType type) const; - void Clip(ClipperLib::ClipType op, - const CArea* a, - ClipperLib::PolyFillType subjFillType = ClipperLib::pftEvenOdd, - ClipperLib::PolyFillType clipFillType = ClipperLib::pftEvenOdd); + void Clip( + ClipperLib::ClipType op, + const CArea* a, + ClipperLib::PolyFillType subjFillType = ClipperLib::pftEvenOdd, + ClipperLib::PolyFillType clipFillType = ClipperLib::pftEvenOdd + ); }; enum eOverlapType diff --git a/src/Mod/CAM/libarea/AreaClipper.cpp b/src/Mod/CAM/libarea/AreaClipper.cpp index e7c07f9e96..6cb08ccccc 100644 --- a/src/Mod/CAM/libarea/AreaClipper.cpp +++ b/src/Mod/CAM/libarea/AreaClipper.cpp @@ -130,10 +130,12 @@ static void AddVertex(const CVertex& vertex, const CVertex* prev_vertex) } } -static void MakeLoop(const DoubleAreaPoint& pt0, - const DoubleAreaPoint& pt1, - const DoubleAreaPoint& pt2, - double radius) +static void MakeLoop( + const DoubleAreaPoint& pt0, + const DoubleAreaPoint& pt1, + const DoubleAreaPoint& pt2, + double radius +) { Point p0(pt0.X, pt0.Y); Point p1(pt1.X, pt1.Y); @@ -348,8 +350,7 @@ static void MakePoly(const CCurve& curve, TPolygon& p, bool reverse = false) p.resize(pts_for_AddVertex.size()); if (reverse) { - std::size_t i = - pts_for_AddVertex.size() - 1; // clipper wants them the opposite way to CArea + std::size_t i = pts_for_AddVertex.size() - 1; // clipper wants them the opposite way to CArea for (std::list::iterator It = pts_for_AddVertex.begin(); It != pts_for_AddVertex.end(); It++, i--) { @@ -409,11 +410,13 @@ static void SetFromResult(CCurve& curve, TPolygon& p, bool reverse = true, bool } } -static void SetFromResult(CArea& area, - TPolyPolygon& pp, - bool reverse = true, - bool is_closed = true, - bool clear = true) +static void SetFromResult( + CArea& area, + TPolyPolygon& pp, + bool reverse = true, + bool is_closed = true, + bool clear = true +) { // delete existing geometry if (clear) { @@ -556,11 +559,13 @@ void CArea::Clip(ClipType op, const CArea* a, PolyFillType subjFillType, PolyFil SetFromResult(*this, solution, false, false, false); } -void CArea::OffsetWithClipper(double offset, - JoinType joinType /* =jtRound */, - EndType endType /* =etOpenRound */, - double miterLimit /* = 5.0 */, - double roundPrecision /* = 0.0 */) +void CArea::OffsetWithClipper( + double offset, + JoinType joinType /* =jtRound */, + EndType endType /* =etOpenRound */, + double miterLimit /* = 5.0 */, + double roundPrecision /* = 0.0 */ +) { offset *= m_units * m_clipper_scale; if (roundPrecision == 0.0) { diff --git a/src/Mod/CAM/libarea/AreaDxf.cpp b/src/Mod/CAM/libarea/AreaDxf.cpp index 7bf6ba4aeb..a1be38d130 100644 --- a/src/Mod/CAM/libarea/AreaDxf.cpp +++ b/src/Mod/CAM/libarea/AreaDxf.cpp @@ -23,22 +23,21 @@ void AreaDxfRead::StartCurveIfNecessary(const Base::Vector3d& startPoint) const } } -void AreaDxfRead::OnReadLine(const Base::Vector3d& start, - const Base::Vector3d& end, - bool /*hidden*/) +void AreaDxfRead::OnReadLine(const Base::Vector3d& start, const Base::Vector3d& end, bool /*hidden*/) { StartCurveIfNecessary(start); m_area->m_curves.back().m_vertices.emplace_back(Point(end.x, end.y)); } -void AreaDxfRead::OnReadArc(const Base::Vector3d& start, - const Base::Vector3d& end, - const Base::Vector3d& center, - bool dir, - bool /*hidden*/) +void AreaDxfRead::OnReadArc( + const Base::Vector3d& start, + const Base::Vector3d& end, + const Base::Vector3d& center, + bool dir, + bool /*hidden*/ +) { StartCurveIfNecessary(start); - m_area->m_curves.back().m_vertices.emplace_back(dir ? 1 : 0, - Point(end.x, end.y), - Point(center.x, center.y)); + m_area->m_curves.back() + .m_vertices.emplace_back(dir ? 1 : 0, Point(end.x, end.y), Point(center.x, center.y)); } diff --git a/src/Mod/CAM/libarea/AreaDxf.h b/src/Mod/CAM/libarea/AreaDxf.h index f110ea3dd8..9cd4c4dcf9 100644 --- a/src/Mod/CAM/libarea/AreaDxf.h +++ b/src/Mod/CAM/libarea/AreaDxf.h @@ -21,11 +21,12 @@ public: AreaDxfRead(CArea* area, const char* filepath); // AreaDxfRead's virtual functions - void - OnReadLine(const Base::Vector3d& start, const Base::Vector3d& end, bool /*hidden*/) override; - void OnReadArc(const Base::Vector3d& start, - const Base::Vector3d& end, - const Base::Vector3d& center, - bool dir, - bool /*hidden*/) override; + void OnReadLine(const Base::Vector3d& start, const Base::Vector3d& end, bool /*hidden*/) override; + void OnReadArc( + const Base::Vector3d& start, + const Base::Vector3d& end, + const Base::Vector3d& center, + bool dir, + bool /*hidden*/ + ) override; }; diff --git a/src/Mod/CAM/libarea/AreaPocket.cpp b/src/Mod/CAM/libarea/AreaPocket.cpp index ab4b2c06d5..105f1e78ac 100644 --- a/src/Mod/CAM/libarea/AreaPocket.cpp +++ b/src/Mod/CAM/libarea/AreaPocket.cpp @@ -148,15 +148,16 @@ void GetCurveItem::GetCurve(CCurve& output) if (inner.point_on_parent.dist(back().m_p) > 0.01 / CArea::m_units) { output.m_vertices.insert( this->EndIt, - CVertex(vertex.m_type, inner.point_on_parent, vertex.m_c)); + CVertex(vertex.m_type, inner.point_on_parent, vertex.m_c) + ); } if (CArea::m_please_abort) { return; } // vertex add after GetCurve - std::list::iterator VIt = - output.m_vertices.insert(this->EndIt, CVertex(inner.point_on_parent)); + std::list::iterator VIt + = output.m_vertices.insert(this->EndIt, CVertex(inner.point_on_parent)); // inner.GetCurve(output); GetCurveItem::to_do_list.emplace_back(&inner, VIt); @@ -172,8 +173,7 @@ void GetCurveItem::GetCurve(CCurve& output) if (CArea::m_please_abort) { return; } - for (std::list::iterator It2 = inners_to_visit.begin(); - It2 != inners_to_visit.end(); + for (std::list::iterator It2 = inners_to_visit.begin(); It2 != inners_to_visit.end(); It2++) { CurveTree& inner = *(*It2); if (inner.point_on_parent != back().m_p) { @@ -184,8 +184,8 @@ void GetCurveItem::GetCurve(CCurve& output) } // vertex add after GetCurve - std::list::iterator VIt = - output.m_vertices.insert(this->EndIt, CVertex(inner.point_on_parent)); + std::list::iterator VIt + = output.m_vertices.insert(this->EndIt, CVertex(inner.point_on_parent)); // inner.GetCurve(output); GetCurveItem::to_do_list.emplace_back(&inner, VIt); @@ -204,17 +204,18 @@ public: } }; -static Point GetNearestPoint(CurveTree* curve_tree, - std::list& islands_added, - const CCurve& test_curve, - CurveTree** best_curve_tree) +static Point GetNearestPoint( + CurveTree* curve_tree, + std::list& islands_added, + const CCurve& test_curve, + CurveTree** best_curve_tree +) { // find nearest point to test_curve, from curve and all the islands in double best_dist; Point best_point = curve_tree->curve.NearestPoint(test_curve, &best_dist); *best_curve_tree = curve_tree; - for (std::list::iterator It = islands_added.begin(); It != islands_added.end(); - It++) { + for (std::list::iterator It = islands_added.begin(); It != islands_added.end(); It++) { CurveTree* island = *It; double dist; Point p = island->curve.NearestPoint(test_curve, &dist); @@ -258,8 +259,9 @@ void CurveTree::MakeOffsets2() if (CArea::m_please_abort) { return; } - Point island_point = - island_and_offset->island->NearestPoint(inners.back()->point_on_parent); + Point island_point = island_and_offset->island->NearestPoint( + inners.back()->point_on_parent + ); if (CArea::m_please_abort) { return; } @@ -274,19 +276,22 @@ void CurveTree::MakeOffsets2() It2++) { const CCurve& island_inner = *It2; inners.back()->inners.push_back(new CurveTree(island_inner)); - inners.back()->inners.back()->point_on_parent = - inners.back()->curve.NearestPoint(island_inner); + inners.back()->inners.back()->point_on_parent = inners.back()->curve.NearestPoint( + island_inner + ); if (CArea::m_please_abort) { return; } - Point island_point = - island_inner.NearestPoint(inners.back()->inners.back()->point_on_parent); + Point island_point = island_inner.NearestPoint( + inners.back()->inners.back()->point_on_parent + ); if (CArea::m_please_abort) { return; } inners.back()->inners.back()->curve.ChangeStart(island_point); to_do_list_for_MakeOffsets.push_back( - inners.back()->inners.back()); // do it later, in a while loop + inners.back()->inners.back() + ); // do it later, in a while loop if (CArea::m_please_abort) { return; } @@ -297,8 +302,8 @@ void CurveTree::MakeOffsets2() std::set added; std::list touching_list; - for (std::list::const_iterator It2 = - island_and_offset->touching_offsets.begin(); + for (std::list::const_iterator It2 + = island_and_offset->touching_offsets.begin(); It2 != island_and_offset->touching_offsets.end(); It2++) { const IslandAndOffset* touching = *It2; @@ -309,44 +314,45 @@ void CurveTree::MakeOffsets2() while (touching_list.size() > 0) { IslandAndOffsetLink touching = touching_list.front(); touching_list.pop_front(); - touching.add_to->inners.push_back( - new CurveTree(*touching.island_and_offset->island)); + touching.add_to->inners.push_back(new CurveTree(*touching.island_and_offset->island)); islands_added.push_back(touching.add_to->inners.back()); - touching.add_to->inners.back()->point_on_parent = - touching.add_to->curve.NearestPoint(*touching.island_and_offset->island); + touching.add_to->inners.back()->point_on_parent + = touching.add_to->curve.NearestPoint(*touching.island_and_offset->island); Point island_point = touching.island_and_offset->island->NearestPoint( - touching.add_to->inners.back()->point_on_parent); + touching.add_to->inners.back()->point_on_parent + ); touching.add_to->inners.back()->curve.ChangeStart(island_point); smaller.Subtract(touching.island_and_offset->offset); // add the island offset's inner curves - for (std::list::const_iterator It2 = - touching.island_and_offset->island_inners.begin(); + for (std::list::const_iterator It2 + = touching.island_and_offset->island_inners.begin(); It2 != touching.island_and_offset->island_inners.end(); It2++) { const CCurve& island_inner = *It2; touching.add_to->inners.back()->inners.push_back(new CurveTree(island_inner)); - touching.add_to->inners.back()->inners.back()->point_on_parent = - touching.add_to->inners.back()->curve.NearestPoint(island_inner); + touching.add_to->inners.back()->inners.back()->point_on_parent + = touching.add_to->inners.back()->curve.NearestPoint(island_inner); if (CArea::m_please_abort) { return; } Point island_point = island_inner.NearestPoint( - touching.add_to->inners.back()->inners.back()->point_on_parent); + touching.add_to->inners.back()->inners.back()->point_on_parent + ); if (CArea::m_please_abort) { return; } touching.add_to->inners.back()->inners.back()->curve.ChangeStart(island_point); to_do_list_for_MakeOffsets.push_back( - touching.add_to->inners.back() - ->inners.back()); // do it later, in a while loop + touching.add_to->inners.back()->inners.back() + ); // do it later, in a while loop if (CArea::m_please_abort) { return; } } - for (std::list::const_iterator It2 = - touching.island_and_offset->touching_offsets.begin(); + for (std::list::const_iterator It2 + = touching.island_and_offset->touching_offsets.begin(); It2 != touching.island_and_offset->touching_offsets.end(); It2++) { if (added.find(*It2) == added.end() && ((*It2) != island_and_offset)) { @@ -410,8 +416,9 @@ void CurveTree::MakeOffsets2() if (CArea::m_please_abort) { return; } - Point first_curve_point = - first_curve.NearestPoint(nearest_curve_tree->inners.back()->point_on_parent); + Point first_curve_point = first_curve.NearestPoint( + nearest_curve_tree->inners.back()->point_on_parent + ); if (CArea::m_please_abort) { return; } @@ -419,8 +426,8 @@ void CurveTree::MakeOffsets2() if (CArea::m_please_abort) { return; } - to_do_list_for_MakeOffsets.push_back( - nearest_curve_tree->inners.back()); // do it later, in a while loop + to_do_list_for_MakeOffsets.push_back(nearest_curve_tree->inners.back()); // do it later, in + // a while loop if (CArea::m_please_abort) { return; } @@ -615,8 +622,7 @@ void CArea::MakeOnePocketCurve(std::list& curve_list, const CAreaPocketP // delete curve_trees non-recursively std::list CurveTreeDestructList; - for (std::list::iterator It = top_level.inners.begin(); - It != top_level.inners.end(); + for (std::list::iterator It = top_level.inners.begin(); It != top_level.inners.end(); It++) { CurveTreeDestructList.push_back(*It); } diff --git a/src/Mod/CAM/libarea/Curve.cpp b/src/Mod/CAM/libarea/Curve.cpp index 6c41e40478..717a3e8e48 100644 --- a/src/Mod/CAM/libarea/Curve.cpp +++ b/src/Mod/CAM/libarea/Curve.cpp @@ -73,9 +73,11 @@ void CCurve::append(const CVertex& vertex) m_vertices.push_back(vertex); } -bool CCurve::CheckForArc(const CVertex& prev_vt, - std::list& might_be_an_arc, - CArc& arc_returned) +bool CCurve::CheckForArc( + const CVertex& prev_vt, + std::list& might_be_an_arc, + CArc& arc_returned +) { // this examines the vertices in might_be_an_arc // if they do fit an arc, set arc to be the arc that they fit and return true @@ -180,12 +182,14 @@ bool CCurve::CheckForArc(const CVertex& prev_vt, return true; } -void CCurve::AddArcOrLines(bool check_for_arc, - std::list& new_vertices, - std::list& might_be_an_arc, - CArc& arc, - bool& arc_found, - bool& arc_added) +void CCurve::AddArcOrLines( + bool check_for_arc, + std::list& new_vertices, + std::list& might_be_an_arc, + CArc& arc, + bool& arc_found, + bool& arc_added +) { if (check_for_arc && CheckForArc(new_vertices.back(), might_be_an_arc, arc)) { arc_found = true; @@ -249,7 +253,8 @@ void CCurve::FitArcs(bool retry) else { might_be_an_arc.push_back(&vt); - if (might_be_an_arc.size() == 1) {} + if (might_be_an_arc.size() == 1) { + } else { AddArcOrLines(true, new_vertices, might_be_an_arc, arc, arc_found, arc_added); } @@ -307,8 +312,7 @@ void CCurve::UnFitArcs() std::list new_pts; const CVertex* prev_vertex = NULL; - for (std::list::const_iterator It2 = m_vertices.begin(); It2 != m_vertices.end(); - It2++) { + for (std::list::const_iterator It2 = m_vertices.begin(); It2 != m_vertices.end(); It2++) { const CVertex& vertex = *It2; if (vertex.m_type == 0 || prev_vertex == NULL) { new_pts.push_back(vertex.m_p * CArea::m_units); @@ -606,8 +610,10 @@ void CCurve::Break(const Point& p) } } -void CCurve::ExtractSeparateCurves(const std::list& ordered_points, - std::list& separate_curves) const +void CCurve::ExtractSeparateCurves( + const std::list& ordered_points, + std::list& separate_curves +) const { // returns separate curves for this curve split at points // the points must be in order along this curve, already, and lie on this curve @@ -623,8 +629,7 @@ void CCurve::ExtractSeparateCurves(const std::list& ordered_points, std::list::const_iterator PIt = ordered_points.begin(); Point point = *PIt; - for (std::list::const_iterator VIt = m_vertices.begin(); VIt != m_vertices.end(); - VIt++) { + for (std::list::const_iterator VIt = m_vertices.begin(); VIt != m_vertices.end(); VIt++) { const CVertex& vertex = *VIt; if (prev_p) // not the first vertex { @@ -690,8 +695,7 @@ void CCurve::ChangeEnd(const Point& p) const Point* prev_p = NULL; - for (std::list::const_iterator VIt = m_vertices.begin(); VIt != m_vertices.end(); - VIt++) { + for (std::list::const_iterator VIt = m_vertices.begin(); VIt != m_vertices.end(); VIt++) { const CVertex& vertex = *VIt; if (prev_p) { @@ -753,9 +757,13 @@ static geoff_geometry::Kurve MakeKurve(const CCurve& curve) It != curve.m_vertices.end(); It++) { const CVertex& v = *It; - k.Add(geoff_geometry::spVertex(v.m_type, - geoff_geometry::Point(v.m_p.x, v.m_p.y), - geoff_geometry::Point(v.m_c.x, v.m_c.y))); + k.Add( + geoff_geometry::spVertex( + v.m_type, + geoff_geometry::Point(v.m_p.x, v.m_p.y), + geoff_geometry::Point(v.m_c.x, v.m_c.y) + ) + ); } return k; } @@ -774,10 +782,12 @@ static CCurve MakeCCurve(const geoff_geometry::Kurve& k) static geoff_geometry::Span MakeSpan(const Span& span) { - return geoff_geometry::Span(span.m_v.m_type, - geoff_geometry::Point(span.m_p.x, span.m_p.y), - geoff_geometry::Point(span.m_v.m_p.x, span.m_v.m_p.y), - geoff_geometry::Point(span.m_v.m_c.x, span.m_v.m_c.y)); + return geoff_geometry::Span( + span.m_v.m_type, + geoff_geometry::Point(span.m_p.x, span.m_p.y), + geoff_geometry::Point(span.m_v.m_p.x, span.m_v.m_p.y), + geoff_geometry::Point(span.m_v.m_c.x, span.m_v.m_c.y) + ); } bool CCurve::Offset(double leftwards_value) @@ -1271,9 +1281,11 @@ double Span::GetArea() const if (m_v.m_type) { double angle = IncludedAngle(); double radius = m_p.dist(m_v.m_c); - return (0.5 - * ((m_v.m_c.x - m_p.x) * (m_v.m_c.y + m_p.y) - - (m_v.m_c.x - m_v.m_p.x) * (m_v.m_c.y + m_v.m_p.y) - angle * radius * radius)); + return ( + 0.5 + * ((m_v.m_c.x - m_p.x) * (m_v.m_c.y + m_p.y) + - (m_v.m_c.x - m_v.m_p.x) * (m_v.m_c.y + m_v.m_p.y) - angle * radius * radius) + ); } return 0.5 * (m_v.m_p.x - m_p.x) * (m_p.y + m_v.m_p.y); diff --git a/src/Mod/CAM/libarea/Curve.h b/src/Mod/CAM/libarea/Curve.h index 02dde67510..7be16a4687 100644 --- a/src/Mod/CAM/libarea/Curve.h +++ b/src/Mod/CAM/libarea/Curve.h @@ -97,9 +97,10 @@ public: Point MidParam(double param) const; double Length() const; Point GetVector(double fraction) const; - void - Intersect(const Span& s, - std::list& pts) const; // finds all the intersection points between two spans + void Intersect( + const Span& s, + std::list& pts + ) const; // finds all the intersection points between two spans }; class CCurve @@ -107,14 +108,15 @@ class CCurve // a closed curve, please make sure you add an end point, the same as the start point protected: - void AddArcOrLines(bool check_for_arc, - std::list& new_vertices, - std::list& might_be_an_arc, - CArc& arc, - bool& arc_found, - bool& arc_added); - static bool - CheckForArc(const CVertex& prev_vt, std::list& might_be_an_arc, CArc& arc); + void AddArcOrLines( + bool check_for_arc, + std::list& new_vertices, + std::list& might_be_an_arc, + CArc& arc, + bool& arc_found, + bool& arc_added + ); + static bool CheckForArc(const CVertex& prev_vt, std::list& might_be_an_arc, CArc& arc); public: std::list m_vertices; @@ -136,11 +138,15 @@ public: void ChangeStart(const Point& p); void ChangeEnd(const Point& p); bool Offset(double leftwards_value); - void OffsetForward(double forwards_value, - bool refit_arcs = true); // for drag-knife compensation + void OffsetForward( + double forwards_value, + bool refit_arcs = true + ); // for drag-knife compensation void Break(const Point& p); - void ExtractSeparateCurves(const std::list& ordered_points, - std::list& separate_curves) const; + void ExtractSeparateCurves( + const std::list& ordered_points, + std::list& separate_curves + ) const; double Perim() const; Point PerimToPoint(double perim) const; double PointToPerim(const Point& p) const; diff --git a/src/Mod/CAM/libarea/clipper.cpp b/src/Mod/CAM/libarea/clipper.cpp index b55610f27f..9122e3e98c 100644 --- a/src/Mod/CAM/libarea/clipper.cpp +++ b/src/Mod/CAM/libarea/clipper.cpp @@ -655,11 +655,13 @@ bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, const IntPoint pt3, boo } //------------------------------------------------------------------------------ -bool SlopesEqual(const IntPoint pt1, - const IntPoint pt2, - const IntPoint pt3, - const IntPoint pt4, - bool UseFullInt64Range) +bool SlopesEqual( + const IntPoint pt1, + const IntPoint pt2, + const IntPoint pt3, + const IntPoint pt4, + bool UseFullInt64Range +) { #ifndef use_int32 if (UseFullInt64Range) { @@ -877,12 +879,14 @@ void SwapPoints(IntPoint& pt1, IntPoint& pt2) } //------------------------------------------------------------------------------ -bool GetOverlapSegment(IntPoint pt1a, - IntPoint pt1b, - IntPoint pt2a, - IntPoint pt2b, - IntPoint& pt1, - IntPoint& pt2) +bool GetOverlapSegment( + IntPoint pt1a, + IntPoint pt1b, + IntPoint pt2a, + IntPoint pt2b, + IntPoint& pt1, + IntPoint& pt2 +) { // precondition: segments are Collinear. if (Abs(pt1a.X - pt1b.X) > Abs(pt1a.Y - pt1b.Y)) { @@ -954,8 +958,7 @@ bool FirstIsBottomPt(const OutPt* btmPt1, const OutPt* btmPt2) } double dx2n = std::fabs(GetDx(btmPt2->Pt, p->Pt)); - if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) - && std::min(dx1p, dx1n) == std::min(dx2p, dx2n)) { + if (std::max(dx1p, dx1n) == std::max(dx2p, dx2n) && std::min(dx1p, dx1n) == std::min(dx2p, dx2n)) { return Area(btmPt1) > 0; // if otherwise identical use orientation } else { @@ -1201,8 +1204,7 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) while (IsHorizontal(*Horz->Next)) { Horz = Horz->Next; } - if (Horz->Next->Top.X == Result->Prev->Top.X - || Horz->Next->Top.X > Result->Prev->Top.X) { + if (Horz->Next->Top.X == Result->Prev->Top.X || Horz->Next->Top.X > Result->Prev->Top.X) { Result = Horz->Next; } } @@ -1767,10 +1769,7 @@ bool Clipper::Execute(ClipType clipType, PolyTree& polytree, PolyFillType fillTy } //------------------------------------------------------------------------------ -bool Clipper::Execute(ClipType clipType, - Paths& solution, - PolyFillType subjFillType, - PolyFillType clipFillType) +bool Clipper::Execute(ClipType clipType, Paths& solution, PolyFillType subjFillType, PolyFillType clipFillType) { if (m_ExecuteLocked) { return false; @@ -1794,10 +1793,12 @@ bool Clipper::Execute(ClipType clipType, } //------------------------------------------------------------------------------ -bool Clipper::Execute(ClipType clipType, - PolyTree& polytree, - PolyFillType subjFillType, - PolyFillType clipFillType) +bool Clipper::Execute( + ClipType clipType, + PolyTree& polytree, + PolyFillType subjFillType, + PolyFillType clipFillType +) { if (m_ExecuteLocked) { return false; @@ -2168,11 +2169,7 @@ OutPt* Clipper::AddLocalMinPoly(TEdge* e1, TEdge* e2, const IntPoint& Pt) cInt xPrev = TopX(*prevE, Pt.Y); cInt xE = TopX(*e, Pt.Y); if (xPrev == xE && (e->WindDelta != 0) && (prevE->WindDelta != 0) - && SlopesEqual(IntPoint(xPrev, Pt.Y), - prevE->Top, - IntPoint(xE, Pt.Y), - e->Top, - m_UseFullRange)) { + && SlopesEqual(IntPoint(xPrev, Pt.Y), prevE->Top, IntPoint(xE, Pt.Y), e->Top, m_UseFullRange)) { OutPt* outPt = AddOutPt(prevE, Pt); AddJoin(result, outPt, e->Top); } @@ -2345,11 +2342,7 @@ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) if (lb->OutIdx >= 0 && lb->PrevInAEL && lb->PrevInAEL->Curr.X == lb->Bot.X && lb->PrevInAEL->OutIdx >= 0 - && SlopesEqual(lb->PrevInAEL->Bot, - lb->PrevInAEL->Top, - lb->Curr, - lb->Top, - m_UseFullRange) + && SlopesEqual(lb->PrevInAEL->Bot, lb->PrevInAEL->Top, lb->Curr, lb->Top, m_UseFullRange) && (lb->WindDelta != 0) && (lb->PrevInAEL->WindDelta != 0)) { OutPt* Op2 = AddOutPt(lb->PrevInAEL, lb->Bot); AddJoin(Op1, Op2, lb->Top); @@ -2358,11 +2351,7 @@ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) if (lb->NextInAEL != rb) { if (rb->OutIdx >= 0 && rb->PrevInAEL->OutIdx >= 0 - && SlopesEqual(rb->PrevInAEL->Curr, - rb->PrevInAEL->Top, - rb->Curr, - rb->Top, - m_UseFullRange) + && SlopesEqual(rb->PrevInAEL->Curr, rb->PrevInAEL->Top, rb->Curr, rb->Top, m_UseFullRange) && (rb->WindDelta != 0) && (rb->PrevInAEL->WindDelta != 0)) { OutPt* Op2 = AddOutPt(rb->PrevInAEL, rb->Bot); AddJoin(Op1, Op2, rb->Top); @@ -3134,10 +3123,12 @@ void Clipper::ProcessHorizontal(TEdge* horzEdge) TEdge* eNextHorz = m_SortedEdges; while (eNextHorz) { if (eNextHorz->OutIdx >= 0 - && HorzSegmentsOverlap(horzEdge->Bot.X, - horzEdge->Top.X, - eNextHorz->Bot.X, - eNextHorz->Top.X)) { + && HorzSegmentsOverlap( + horzEdge->Bot.X, + horzEdge->Top.X, + eNextHorz->Bot.X, + eNextHorz->Top.X + )) { OutPt* op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz->Top); } @@ -3188,10 +3179,12 @@ void Clipper::ProcessHorizontal(TEdge* horzEdge) TEdge* eNextHorz = m_SortedEdges; while (eNextHorz) { if (eNextHorz->OutIdx >= 0 - && HorzSegmentsOverlap(horzEdge->Bot.X, - horzEdge->Top.X, - eNextHorz->Bot.X, - eNextHorz->Top.X)) { + && HorzSegmentsOverlap( + horzEdge->Bot.X, + horzEdge->Top.X, + eNextHorz->Bot.X, + eNextHorz->Top.X + )) { OutPt* op2 = GetLastOutPt(eNextHorz); AddJoin(op2, op1, eNextHorz->Top); } @@ -4007,8 +4000,8 @@ bool Clipper::JoinPoints(Join* j, OutRec* outRec1, OutRec* outRec2) while ((op1b->Pt == op1->Pt) && (op1b != op1)) { op1b = op1b->Next; } - bool Reverse1 = - ((op1b->Pt.Y > op1->Pt.Y) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)); + bool Reverse1 + = ((op1b->Pt.Y > op1->Pt.Y) || !SlopesEqual(op1->Pt, op1b->Pt, j->OffPt, m_UseFullRange)); if (Reverse1) { op1b = op1->Prev; while ((op1b->Pt == op1->Pt) && (op1b != op1)) { @@ -4023,8 +4016,8 @@ bool Clipper::JoinPoints(Join* j, OutRec* outRec1, OutRec* outRec2) while ((op2b->Pt == op2->Pt) && (op2b != op2)) { op2b = op2b->Next; } - bool Reverse2 = - ((op2b->Pt.Y > op2->Pt.Y) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)); + bool Reverse2 + = ((op2b->Pt.Y > op2->Pt.Y) || !SlopesEqual(op2->Pt, op2b->Pt, j->OffPt, m_UseFullRange)); if (Reverse2) { op2b = op2->Prev; while ((op2b->Pt == op2->Pt) && (op2b != op2)) { @@ -4500,8 +4493,9 @@ void ClipperOffset::DoOffset(double delta) if (node.m_jointype == jtRound) { double X = 1.0, Y = 0.0; for (cInt j = 1; j <= steps; j++) { - m_destPoly.push_back(IntPoint(Round(m_srcPoly[0].X + X * delta), - Round(m_srcPoly[0].Y + Y * delta))); + m_destPoly.push_back( + IntPoint(Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta)) + ); double X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; @@ -4510,8 +4504,9 @@ void ClipperOffset::DoOffset(double delta) else { double X = -1.0, Y = -1.0; for (int j = 0; j < 4; ++j) { - m_destPoly.push_back(IntPoint(Round(m_srcPoly[0].X + X * delta), - Round(m_srcPoly[0].Y + Y * delta))); + m_destPoly.push_back( + IntPoint(Round(m_srcPoly[0].X + X * delta), Round(m_srcPoly[0].Y + Y * delta)) + ); if (X < 0) { X = 1; } @@ -4574,11 +4569,15 @@ void ClipperOffset::DoOffset(double delta) IntPoint pt1; if (node.m_endtype == etOpenButt) { int j = len - 1; - pt1 = IntPoint((cInt)Round(m_srcPoly[j].X + m_normals[j].X * delta), - (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta)); + pt1 = IntPoint( + (cInt)Round(m_srcPoly[j].X + m_normals[j].X * delta), + (cInt)Round(m_srcPoly[j].Y + m_normals[j].Y * delta) + ); m_destPoly.push_back(pt1); - pt1 = IntPoint((cInt)Round(m_srcPoly[j].X - m_normals[j].X * delta), - (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta)); + pt1 = IntPoint( + (cInt)Round(m_srcPoly[j].X - m_normals[j].X * delta), + (cInt)Round(m_srcPoly[j].Y - m_normals[j].Y * delta) + ); m_destPoly.push_back(pt1); } else { @@ -4606,11 +4605,15 @@ void ClipperOffset::DoOffset(double delta) } if (node.m_endtype == etOpenButt) { - pt1 = IntPoint((cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta), - (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta)); + pt1 = IntPoint( + (cInt)Round(m_srcPoly[0].X - m_normals[0].X * delta), + (cInt)Round(m_srcPoly[0].Y - m_normals[0].Y * delta) + ); m_destPoly.push_back(pt1); - pt1 = IntPoint((cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta), - (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta)); + pt1 = IntPoint( + (cInt)Round(m_srcPoly[0].X + m_normals[0].X * delta), + (cInt)Round(m_srcPoly[0].Y + m_normals[0].Y * delta) + ); m_destPoly.push_back(pt1); } else { @@ -4638,8 +4641,10 @@ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) double cosA = (m_normals[k].X * m_normals[j].X + m_normals[j].Y * m_normals[k].Y); if (cosA > 0) // angle => 0 degrees { - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + m_normals[k].X * m_delta), + Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta) + )); return; } // else angle => 180 degrees @@ -4652,11 +4657,15 @@ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) } if (m_sinA * m_delta < 0) { - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[k].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta))); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + m_normals[k].X * m_delta), + Round(m_srcPoly[j].Y + m_normals[k].Y * m_delta) + )); m_destPoly.push_back(m_srcPoly[j]); - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + m_normals[j].X * m_delta), + Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta) + )); } else { switch (jointype) { @@ -4685,40 +4694,47 @@ void ClipperOffset::OffsetPoint(int j, int& k, JoinType jointype) void ClipperOffset::DoSquare(int j, int k) { double dx = std::tan( - std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4); - m_destPoly.push_back( - IntPoint(Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), - Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx)))); - m_destPoly.push_back( - IntPoint(Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)), - Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx)))); + std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y) / 4 + ); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + m_delta * (m_normals[k].X - m_normals[k].Y * dx)), + Round(m_srcPoly[j].Y + m_delta * (m_normals[k].Y + m_normals[k].X * dx)) + )); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + m_delta * (m_normals[j].X + m_normals[j].Y * dx)), + Round(m_srcPoly[j].Y + m_delta * (m_normals[j].Y - m_normals[j].X * dx)) + )); } //------------------------------------------------------------------------------ void ClipperOffset::DoMiter(int j, int k, double r) { double q = m_delta / r; - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q), - Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q))); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + (m_normals[k].X + m_normals[j].X) * q), + Round(m_srcPoly[j].Y + (m_normals[k].Y + m_normals[j].Y) * q) + )); } //------------------------------------------------------------------------------ void ClipperOffset::DoRound(int j, int k) { - double a = - std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); + double a = std::atan2(m_sinA, m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1); double X = m_normals[k].X, Y = m_normals[k].Y, X2; for (int i = 0; i < steps; ++i) { m_destPoly.push_back( - IntPoint(Round(m_srcPoly[j].X + X * m_delta), Round(m_srcPoly[j].Y + Y * m_delta))); + IntPoint(Round(m_srcPoly[j].X + X * m_delta), Round(m_srcPoly[j].Y + Y * m_delta)) + ); X2 = X; X = X * m_cos - m_sin * Y; Y = X2 * m_sin + Y * m_cos; } - m_destPoly.push_back(IntPoint(Round(m_srcPoly[j].X + m_normals[j].X * m_delta), - Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta))); + m_destPoly.push_back(IntPoint( + Round(m_srcPoly[j].X + m_normals[j].X * m_delta), + Round(m_srcPoly[j].Y + m_normals[j].Y * m_delta) + )); } //------------------------------------------------------------------------------ @@ -4849,10 +4865,7 @@ double DistanceFromLineSqrd(const IntPoint& pt, const IntPoint& ln1, const IntPo } //--------------------------------------------------------------------------- -bool SlopesNearCollinear(const IntPoint& pt1, - const IntPoint& pt2, - const IntPoint& pt3, - double distSqrd) +bool SlopesNearCollinear(const IntPoint& pt1, const IntPoint& pt2, const IntPoint& pt3, double distSqrd) { // this function is more accurate when the point that's geometrically // between the other 2 points is the one that's tested for distance. diff --git a/src/Mod/CAM/libarea/clipper.hpp b/src/Mod/CAM/libarea/clipper.hpp index 0692557534..5e934dd784 100644 --- a/src/Mod/CAM/libarea/clipper.hpp +++ b/src/Mod/CAM/libarea/clipper.hpp @@ -162,11 +162,13 @@ struct DoublePoint //------------------------------------------------------------------------------ #ifdef use_xyz -typedef void (*ZFillCallback)(IntPoint& e1bot, - IntPoint& e1top, - IntPoint& e2bot, - IntPoint& e2top, - IntPoint& pt); +typedef void (*ZFillCallback)( + IntPoint& e1bot, + IntPoint& e1top, + IntPoint& e2bot, + IntPoint& e2top, + IntPoint& pt +); #endif enum InitOptions @@ -347,15 +349,14 @@ class Clipper: public virtual ClipperBase public: Clipper(int initOptions = 0); bool Execute(ClipType clipType, Paths& solution, PolyFillType fillType = pftEvenOdd); - bool Execute(ClipType clipType, - Paths& solution, - PolyFillType subjFillType, - PolyFillType clipFillType); + bool Execute(ClipType clipType, Paths& solution, PolyFillType subjFillType, PolyFillType clipFillType); bool Execute(ClipType clipType, PolyTree& polytree, PolyFillType fillType = pftEvenOdd); - bool Execute(ClipType clipType, - PolyTree& polytree, - PolyFillType subjFillType, - PolyFillType clipFillType); + bool Execute( + ClipType clipType, + PolyTree& polytree, + PolyFillType subjFillType, + PolyFillType clipFillType + ); bool ReverseSolution() { return m_ReverseOutput; diff --git a/src/Mod/CAM/libarea/kurve/Construction.cpp b/src/Mod/CAM/libarea/kurve/Construction.cpp index f28cdbae6a..098ca7c3e7 100644 --- a/src/Mod/CAM/libarea/kurve/Construction.cpp +++ b/src/Mod/CAM/libarea/kurve/Construction.cpp @@ -185,8 +185,7 @@ Point3d::Point3d(const Vector3d& v) bool Point3d::operator==(const Point3d& p) const { // p1 == p2 (uses TOLERANCE) - if (FNE(this->x, p.x, TOLERANCE) || FNE(this->y, p.y, TOLERANCE) - || FNE(this->z, p.z, TOLERANCE)) { + if (FNE(this->x, p.x, TOLERANCE) || FNE(this->y, p.y, TOLERANCE) || FNE(this->z, p.z, TOLERANCE)) { return false; } return true; @@ -395,8 +394,10 @@ Point Around(const Circle& c, double d, const Point& p) if (fabs(c.radius) > TOLERANCE) { double a = sin(-d / c.radius); double b = cos(-d / c.radius); - return Point(c.pc.x - c.radius * (radial.v.gety() * a - radial.v.getx() * b), - c.pc.y + c.radius * (radial.v.gety() * b + radial.v.getx() * a)); + return Point( + c.pc.x - c.radius * (radial.v.gety() * a - radial.v.getx() * b), + c.pc.y + c.radius * (radial.v.gety() * b + radial.v.getx() * a) + ); } } return INVALID_POINT; @@ -406,9 +407,11 @@ CLine AtAngle(double angle, const Point& p0, const CLine& s) // cline at angle [to a cline] thro' a point angle *= DegreesToRadians; Vector2d v(cos(angle), sin(angle)); - return CLine(p0, - v.getx() * s.v.getx() - v.gety() * s.v.gety(), - v.gety() * s.v.getx() + v.getx() * s.v.gety()); + return CLine( + p0, + v.getx() * s.v.getx() - v.gety() * s.v.gety(), + v.gety() * s.v.getx() + v.getx() * s.v.gety() + ); } CLine Parallel(int side, const CLine& s0, double distance) { @@ -583,8 +586,7 @@ Point Intof(int NF, const CLine& s, const Circle& c, Point& otherInters) int nRoots; double t, tFar, tNear, tOther; Vector2d v0(c.pc, s.p); - if ((nRoots = - quadratic(1, 2 * (v0 * s.v), v0.magnitudesqd() - c.radius * c.radius, tFar, tNear)) + if ((nRoots = quadratic(1, 2 * (v0 * s.v), v0.magnitudesqd() - c.radius * c.radius, tFar, tNear)) != 0) { if (nRoots == 2 && NF == NEARINT) { t = tNear; @@ -759,8 +761,7 @@ Circle Thro(int LR, const Point& p0, const Point& p1, double rad) } else { // 2 solutions - return Circle(Along(Normal(thro, pm), (double)LR * sqrt((rad + d) * (rad - d)), pm), - rad); + return Circle(Along(Normal(thro, pm), (double)LR * sqrt((rad + d) * (rad - d)), pm), rad); } } return INVALID_CIRCLE; diff --git a/src/Mod/CAM/libarea/kurve/Finite.cpp b/src/Mod/CAM/libarea/kurve/Finite.cpp index 33c0ec18f3..802170b86d 100644 --- a/src/Mod/CAM/libarea/kurve/Finite.cpp +++ b/src/Mod/CAM/libarea/kurve/Finite.cpp @@ -12,8 +12,8 @@ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef WIN32 -#define __min(a, b) ((a < b) ? a : b) -#define __max(a, b) ((a > b) ? a : b) +# define __min(a, b) ((a < b) ? a : b) +# define __max(a, b) ((a > b) ? a : b) #endif namespace geoff_geometry @@ -92,8 +92,7 @@ int LineArcIntof(const Span& line, const Span& arc, Point& p0, Point& p1, double double s = v1.magnitudesqd(); p0.ok = p1.ok = false; - if ((nRoots = - quadratic(s, 2 * (v0 * v1), v0.magnitudesqd() - arc.radius * arc.radius, t[0], t[1])) + if ((nRoots = quadratic(s, 2 * (v0 * v1), v0.magnitudesqd() - arc.radius * arc.radius, t[0], t[1])) != 0) { double toler = geoff_geometry::TOLERANCE / sqrt(s); // calc a parametric tolerance if (t[0] > -toler && t[0] < 1 + toler) { diff --git a/src/Mod/CAM/libarea/kurve/Matrix.cpp b/src/Mod/CAM/libarea/kurve/Matrix.cpp index d1463307e0..7c8ed60db4 100644 --- a/src/Mod/CAM/libarea/kurve/Matrix.cpp +++ b/src/Mod/CAM/libarea/kurve/Matrix.cpp @@ -13,9 +13,9 @@ using namespace geoff_geometry; #ifdef PEPSDLL -#include "vdm.h" -#include "pepsdll.h" -#include "realds.h" +# include "vdm.h" +# include "pepsdll.h" +# include "realds.h" #endif //////////////////////////////////////////////////////////////////////////////////////////////// // matrix @@ -182,8 +182,8 @@ void Matrix::Multiply(Matrix& m) for (i = 0; i < 16; i++) { l = i - (k = (i % 4)); - ret.e[i] = - m.e[l] * e[k] + m.e[l + 1] * e[k + 4] + m.e[l + 2] * e[k + 8] + m.e[l + 3] * e[k + 12]; + ret.e[i] = m.e[l] * e[k] + m.e[l + 1] * e[k + 4] + m.e[l + 2] * e[k + 8] + + m.e[l + 3] * e[k + 12]; } *this = ret; @@ -231,9 +231,10 @@ int Matrix::IsMirrored() } else if (m_mirrored == -1) { - m_mirrored = ((e[0] * (e[5] * e[10] - e[6] * e[9]) - e[1] * (e[4] * e[10] - e[6] * e[8]) - + e[2] * (e[4] * e[9] - e[5] * e[8])) - < 0); + m_mirrored + = ((e[0] * (e[5] * e[10] - e[6] * e[9]) - e[1] * (e[4] * e[10] - e[6] * e[8]) + + e[2] * (e[4] * e[9] - e[5] * e[8])) + < 0); } return m_mirrored; } diff --git a/src/Mod/CAM/libarea/kurve/geometry.h b/src/Mod/CAM/libarea/kurve/geometry.h index 7e150c0a92..86963ebf96 100644 --- a/src/Mod/CAM/libarea/kurve/geometry.h +++ b/src/Mod/CAM/libarea/kurve/geometry.h @@ -12,10 +12,10 @@ ///////////////////////////////////////////////////////////////////////////////////////// #pragma once #ifdef _MSC_VER -#pragma warning(disable : 4996) -#ifndef WINVER -#define WINVER 0x501 -#endif +# pragma warning(disable : 4996) +# ifndef WINVER +# define WINVER 0x501 +# endif #endif #include @@ -619,8 +619,10 @@ public: // operators bool operator==(const Vector3d& v) const { - return (FEQ(dx, v.dx, UNIT_VECTOR_TOLERANCE) && FEQ(dy, v.dy, UNIT_VECTOR_TOLERANCE) - && FEQ(dz, v.dz, UNIT_VECTOR_TOLERANCE)); + return ( + FEQ(dx, v.dx, UNIT_VECTOR_TOLERANCE) && FEQ(dy, v.dy, UNIT_VECTOR_TOLERANCE) + && FEQ(dz, v.dz, UNIT_VECTOR_TOLERANCE) + ); } // v1 == v2 (unit only!) bool operator!=(const Vector3d& v) const { @@ -888,13 +890,17 @@ public: } Circle Transform(Matrix& m); // transform a Circle Point Intof(int LR, const Circle& c1); // intof 2 circles - Point Intof(int LR, - const Circle& c1, - Point& otherInters); // intof 2 circles, (returns the other intersection) - int Intof(const Circle& c1, - Point& leftInters, - Point& rightInters); // intof 2 circles (returns number of intersections & left/right - // inters) + Point Intof( + int LR, + const Circle& c1, + Point& otherInters + ); // intof 2 circles, (returns the other intersection) + int Intof( + const Circle& c1, + Point& leftInters, + Point& rightInters + ); // intof 2 circles (returns number of intersections & left/right + // inters) CLine Tanto(int AT, double angle, const CLine& s0) const; // a cline tanto this circle at angle // ~Circle(); // destructor }; @@ -1027,16 +1033,17 @@ public: Point Mid() const; // midpoint of a span Point MidPerim(double d) const; // interior point of Span (param 0 - d) Point MidParam(double param) const; // interior point of Span (param 0 - 1) + bool OnSpan(const Point& p) const; // tests if p is on sp *** FAST TEST p MUST LIE on + // unbounded span bool OnSpan( - const Point& p) const; // tests if p is on sp *** FAST TEST p MUST LIE on unbounded span - bool - OnSpan(const Point& p, - double* t) const; // tests if p is on sp *** FAST TEST p MUST LIE on unbounded span + const Point& p, + double* t + ) const; // tests if p is on sp *** FAST TEST p MUST LIE on unbounded span bool JoinSeparateSpans(Span& sp); Span BlendTwoSpans(Span& sp2, double radius, double maxt); // Blends 2 Spans bool isJoinable(const Span& sp) const; // is this & sp joinable to 1 span? - Vector2d - GetVector(double fraction) const; // the direction along the span, 0.0 for start, 1.0 for end + Vector2d GetVector(double fraction) const; // the direction along the span, 0.0 for start, 1.0 + // for end // constructor Span() @@ -1072,19 +1079,22 @@ double atn360(double dx, double dy); // angle 0 to 2pi // double Dist(Point& p0, Point& p1); // distance between 2 points (3d) // double Dist(CLine& s, Point& p1); // distance between cline & point -double -Dist(const Point3d* p, const Vector3d* vl, const Point3d* pf); // distance from line (p, vl) and pf -double DistSq(const Point3d* p, - const Vector3d* vl, - const Point3d* pf); // distance squared from line (p, vl) and pf +double Dist(const Point3d* p, const Vector3d* vl, const Point3d* pf); // distance from line (p, vl) + // and pf +double DistSq( + const Point3d* p, + const Vector3d* vl, + const Point3d* pf +); // distance squared from line (p, vl) and pf double Dist(const Circle& c, const Point& p); // distance between c & p -double Dist(const Point& p0, - const Circle& c, - const Point& p1); // clockwise distance around c from p0 to p1 +double Dist( + const Point& p0, + const Circle& c, + const Point& p1 +); // clockwise distance around c from p0 to p1 double Dist(const CLine& s, const Circle& c); // distance between line and circle double Dist(const Circle& c0, const Circle& c1); // distance between 2 circles -double -IncludedAngle(const Vector2d& v0, const Vector2d& v1, int dir = 1); // angle between 2 vectors +double IncludedAngle(const Vector2d& v0, const Vector2d& v1, int dir = 1); // angle between 2 vectors double IncludedAngle(const Vector3d& v0, const Vector3d& v1, const Vector3d& normal, int dir = 1); inline double IncludedAngle(const CLine& s0, const CLine& s1, int dir = 1) { // angle between 2 Clines @@ -1102,15 +1112,19 @@ Point XonCLine(const CLine& s, double xval); // returns point that has Point YonCLine(const CLine& s, double yval); // returns point that has Y on this line Point Intof(const CLine& s0, const CLine& s1); // intof 2 clines Point Intof(int NF, const CLine& s, const Circle& c); // intof of circle & a cline -Point Intof(int NF, - const CLine& s, - const Circle& c, - Point& otherInters); // intof of circle & a cline (returns the other intersection) +Point Intof( + int NF, + const CLine& s, + const Circle& c, + Point& otherInters +); // intof of circle & a cline (returns the other intersection) Point Intof(int LR, const Circle& c0, const Circle& c1); // intof 2 circles -Point Intof(int LR, - const Circle& c0, - const Circle& c1, - Point& otherInters); // intof 2 circles, (returns the other intersection) +Point Intof( + int LR, + const Circle& c0, + const Circle& c1, + Point& otherInters +); // intof 2 circles, (returns the other intersection) int Intof(const Circle& c0, const Circle& c1, Point& pLeft, Point& pRight); // ditto Point Along(const CLine& s, double d); // distance along Cline Point Along(const CLine& s, double d, const Point& p); // distance along Cline from point @@ -1120,13 +1134,17 @@ Point On(const Circle& c, const Point& p); // returns a point on // cline definitions -CLine AtAngle(double angle, - const Point& p, - const CLine& s = HORIZ_CLINE); // cline at angle to line thro' point -CLine Tanto(int AT, - const Circle& c, - double angle, - const CLine& s0 = HORIZ_CLINE); // cline tanto circle at angle to optional cline +CLine AtAngle( + double angle, + const Point& p, + const CLine& s = HORIZ_CLINE +); // cline at angle to line thro' point +CLine Tanto( + int AT, + const Circle& c, + double angle, + const CLine& s0 = HORIZ_CLINE +); // cline tanto circle at angle to optional cline CLine Tanto(int AT, const Circle& c, const Point& p); // cline tanto circle thro' a point CLine Tanto(int AT0, const Circle& c0, int AT1, const Circle& c1); // cline tanto 2 circles CLine Normal(const CLine& s); // noirmal to cline @@ -1138,71 +1156,90 @@ CLine Parallel(const CLine& cl, const Point& p); // parallel to cline thro' a p // circle definitions Circle Thro(const Point& p0, const Point& p1); // circle thro 2 points (diametric) Circle Thro(const Point& p0, const Point& p1, const Point& p2); // circle thro 3 points -Circle Tanto(int NF, - const CLine& s0, - const Point& p, - double rad); // circle tanto a CLine thro' a point with radius -Circle -Thro(int LR, const Point& p0, const Point& p1, double rad); // circle thro' 2 points with radius -Circle Tanto(int AT1, - const CLine& s1, - int AT2, - const CLine& s2, - double rad); // circle tanto 2 clines with radius -Circle Tanto(int AT1, - const CLine& s1, - int AT2, - const CLine& s2, - int AT3, - const CLine& s3); // circle tanto 3 clines -Circle Tanto(int LR, - int AT, - const Circle& c, - const Point& p, - double rad); // circle tanto circle & thro' a point -Circle Tanto(int NF, - int AT0, - const CLine& s0, - int AT1, - const Circle& c1, - double rad); // circle tanto cline & circle with radius -Circle Tanto(int LR, - int AT0, - const Circle& c0, - int AT1, - const Circle& c1, - double rad); // circle tanto 2 circles with radius -Circle Tanto(int LR, - int AT1, - const Circle& c1, - int AT2, - const Circle& c2, - int AT3, - const Circle c3); // tanto 3 circles -int apolloniusProblem(int AT1, - const Circle& c1, - int AT2, - const Circle& c2, - int AT3, - const Circle& c3, - Circle& Solution1, - Circle& Solution2); -int apolloniusProblem(int AT1, - const Circle& c1, - int AT2, - const Circle& c2, - int AT3, - const CLine& cl3, - Circle& Solution1, - Circle& Solution2); -int apolloniusProblem(int AT1, - const Circle& c1, - int AT2, - const CLine& cl2, - int AT3, - const CLine& cl3, - Circle& Solution1, - Circle& Solution2); +Circle Tanto( + int NF, + const CLine& s0, + const Point& p, + double rad +); // circle tanto a CLine thro' a point with radius +Circle Thro(int LR, const Point& p0, const Point& p1, double rad); // circle thro' 2 points with radius +Circle Tanto( + int AT1, + const CLine& s1, + int AT2, + const CLine& s2, + double rad +); // circle tanto 2 clines with radius +Circle Tanto( + int AT1, + const CLine& s1, + int AT2, + const CLine& s2, + int AT3, + const CLine& s3 +); // circle tanto 3 clines +Circle Tanto( + int LR, + int AT, + const Circle& c, + const Point& p, + double rad +); // circle tanto circle & thro' a point +Circle Tanto( + int NF, + int AT0, + const CLine& s0, + int AT1, + const Circle& c1, + double rad +); // circle tanto cline & circle with radius +Circle Tanto( + int LR, + int AT0, + const Circle& c0, + int AT1, + const Circle& c1, + double rad +); // circle tanto 2 circles with radius +Circle Tanto( + int LR, + int AT1, + const Circle& c1, + int AT2, + const Circle& c2, + int AT3, + const Circle c3 +); // tanto 3 circles +int apolloniusProblem( + int AT1, + const Circle& c1, + int AT2, + const Circle& c2, + int AT3, + const Circle& c3, + Circle& Solution1, + Circle& Solution2 +); +int apolloniusProblem( + int AT1, + const Circle& c1, + int AT2, + const Circle& c2, + int AT3, + const CLine& cl3, + Circle& Solution1, + Circle& Solution2 +); +int apolloniusProblem( + int AT1, + const Circle& c1, + int AT2, + const CLine& cl2, + int AT3, + const CLine& cl3, + Circle& Solution1, + Circle& Solution2 +); // Circle Tanto(int AT0, // int NF, @@ -1224,9 +1261,11 @@ inline double Degrees(double radians) } int quadratic(double a, double b, double c, double& x0, double& x1); // solve quadratic -int corner(const Vector2d& v0, - const Vector2d& v1, - double cpTol = CPTANGENTTOL); // corner (TANGENT, LEFT, RIGHT) +int corner( + const Vector2d& v0, + const Vector2d& v1, + double cpTol = CPTANGENTTOL +); // corner (TANGENT, LEFT, RIGHT) inline int corner(const Span& span, const Span& next, double cpTol = CPTANGENTTOL) { return corner((Vector2d)span.ve, (Vector2d)next.vs, cpTol); @@ -1255,11 +1294,10 @@ public: // ax + by + cz + d = 0 // methods double Dist(const Point3d& p) const; // signed distance of point to plane - bool Intof(const Line& l, Point3d& intof, double& t) - const; // intersection of plane & line (0 >= t <= 1 if intersect within line) + bool Intof(const Line& l, Point3d& intof, double& t) const; // intersection of plane & line (0 + // >= t <= 1 if intersect within line) bool Intof(const Plane& pl, Line& intof) const; // intersection of 2 planes - bool - Intof(const Plane& pl0, const Plane& pl1, Point3d& intof) const; // intersection of 3 planes + bool Intof(const Plane& pl0, const Plane& pl1, Point3d& intof) const; // intersection of 3 planes Point3d Near(const Point3d& p) const; // returns near point to p on the plane void Mirrored(Matrix* m); // returns a matrix for a mirror about this }; @@ -1352,7 +1390,7 @@ public: #ifdef _MSC_VER -#pragma warning(disable : 4522) +# pragma warning(disable : 4522) #endif class Kurve: public Matrix @@ -1417,9 +1455,9 @@ public: bool Add(const Point& p0, bool AddNullSpans = true); // linear void Add(); // add a null span void Add(const Kurve* k, bool AddNullSpans = true); // a kurve - void StoreAllSpans(std::vector& kSpans) - const; // store all kurve spans in array, normally when fast access is reqd - void Clear(); // remove all the spans + void StoreAllSpans(std::vector& kSpans) const; // store all kurve spans in array, + // normally when fast access is reqd + void Clear(); // remove all the spans void Replace(int vertexnumber, const spVertex& spv); void Replace(int vertexnumber, int type, const Point& p, const Point& pc, int ID = UNMARKED); @@ -1434,8 +1472,7 @@ public: pc = pc2d; return d; } - int - Get(int spannumber, Span& sp, bool returnSpanProperties = false, bool transform = false) const; + int Get(int spannumber, Span& sp, bool returnSpanProperties = false, bool transform = false) const; // int Get(int spannumber, // Span3d& sp, // bool returnSpanProperties = false, @@ -1473,16 +1510,20 @@ public: }; int Reduce(double tolerance); // reduce spans which are in tolerance - int Offset(vector& OffsetKurves, - double offset, - int direction, - int method, - int& ret) const; // offset methods + int Offset( + vector& OffsetKurves, + double offset, + int direction, + int method, + int& ret + ) const; // offset methods int OffsetMethod1(Kurve& kOffset, double off, int direction, int method, int& ret) const; - int OffsetISOMethod(Kurve& kOffset, - double off, - int direction, - bool BlendAll) const; // special offset (ISO radius - no span elimination) + int OffsetISOMethod( + Kurve& kOffset, + double off, + int direction, + bool BlendAll + ) const; // special offset (ISO radius - no span elimination) int Intof(const Span& sp, vector& p) const; // intof span int Intof(const Kurve& k, vector& p) const; // intof kurve bool Compare(const Kurve* k, Matrix* m, bool bAllowMirror = true) const; // compare 2 Kurves @@ -1490,20 +1531,26 @@ public: void ChangeEnd(const Point* pNewEnd, int endSpanno); // change the Kurve's endpoint private: - bool compareKurves(const std::vector& first, - const std::vector& second, - int& nOffset /*, Kurve *k, Matrix *m*/) const; + bool compareKurves( + const std::vector& first, + const std::vector& second, + int& nOffset /*, Kurve *k, Matrix *m*/ + ) const; bool calculateMatrix(const Kurve* k, Matrix* m, int nOffset, bool bMirror = false) const; public: void AddIndex(int vertexNumber, const SpanDataObject* data); - bool Split(double MaximumRadius, - double reslution); // split arcs larger than MaximumRadius to resolution - int IntExtWire(Kurve& kSec, - double Ref, - double Sec, - double height, - Kurve* kOut); // interpolate / extrapolate a mid height kurve (wire) + bool Split( + double MaximumRadius, + double reslution + ); // split arcs larger than MaximumRadius to resolution + int IntExtWire( + Kurve& kSec, + double Ref, + double Sec, + double height, + Kurve* kOut + ); // interpolate / extrapolate a mid height kurve (wire) void SetZ(double z) { e[11] = z; @@ -1513,31 +1560,37 @@ public: } // assigns kurve to fixed height (wire) void Part(int startVertex, int EndVertex, Kurve* part); - Kurve Part(int fromSpanno, - const Point& fromPt, - int toSpanno, - const Point& toPt); // make a Part Kurve - int - Break(double atParam, - const Kurve* secInput, - Kurve* refOut, - Kurve* secOut); // break kurve perimeter parameterisation with synchronised Kurve (wire) - void - Part(double fromParam, - double toParam, - const Kurve* secInput, - Kurve* refOut, - Kurve* secOut); // part kurve perimeter parameterisation with synchronised Kurve (wire) + Kurve Part( + int fromSpanno, + const Point& fromPt, + int toSpanno, + const Point& toPt + ); // make a Part Kurve + int Break( + double atParam, + const Kurve* secInput, + Kurve* refOut, + Kurve* secOut + ); // break kurve perimeter parameterisation with synchronised Kurve (wire) + void Part( + double fromParam, + double toParam, + const Kurve* secInput, + Kurve* refOut, + Kurve* secOut + ); // part kurve perimeter parameterisation with synchronised Kurve (wire) Kurve Part(double fromParam, double toParam); // part kurve perimeter parameterisation void AddSections(const Kurve* k, bool endOfSection); // special add kurves for rollingball - void AddEllipse(int dir, - const Point& pStart, - const Point& pEnd, - const Point& pCentre, - const Vector2d& majorAxis, - double majorRadius, - double minorRadius, - double tolerance); + void AddEllipse( + int dir, + const Point& pStart, + const Point& pEnd, + const Point& pCentre, + const Vector2d& majorAxis, + double majorRadius, + double minorRadius, + double tolerance + ); // void Kurve::AddEllipse(int dir, // Plane* plEllipse, // Vector3d* cylAxis, @@ -1547,16 +1600,20 @@ public: // Point3d* pEnd, // double tolerance); // elliptical curve - biarc in tolerance - void Spiral(const Point& centre, - double startAngle, - double startRadius, - double radiusRisePerRevolution, - double endRadius); + void Spiral( + const Point& centre, + double startAngle, + double startRadius, + double radiusRisePerRevolution, + double endRadius + ); #ifdef PARASOLID - int ToPKcurve(PK_CURVE_t* curves, - PK_INTERVAL_t* ranges, - int start_spanno, - int n_spans); // Convert to PK Curve + int ToPKcurve( + PK_CURVE_t* curves, + PK_INTERVAL_t* ranges, + int start_spanno, + int n_spans + ); // Convert to PK Curve PK_BODY_t ToPKwire(); // Convert to PK Wire Body PK_BODY_t ToPKwire(int start_spanno, int n_spans); @@ -1569,25 +1626,30 @@ public: #endif }; #ifdef _MSC_VER -#pragma warning(default : 4522) +# pragma warning(default : 4522) #endif void tangential_arc(const Point& p0, const Point& p1, const Vector2d& v0, Point& c, int& dir); -int EqualiseSpanCount(Kurve& k1, - Kurve& k2, - Kurve& k1equal, - Kurve& k2equal, - bool equalise_same_span_count); // span count equalisation -void EqualiseSpanCountAfterOffset(Kurve& k1, - Kurve& k2, - Kurve& k1Out, - Kurve& k2Out); // span equalisation after offset +int EqualiseSpanCount( + Kurve& k1, + Kurve& k2, + Kurve& k1equal, + Kurve& k2equal, + bool equalise_same_span_count +); // span count equalisation +void EqualiseSpanCountAfterOffset( + Kurve& k1, + Kurve& k2, + Kurve& k1Out, + Kurve& k2Out +); // span equalisation after offset void EqualiseSpanCountAfterOffsetFromRollAround( Kurve& k1, Kurve& k2, Kurve& k1Out, - Kurve& k2Out /*, double offset, int arc_direction*/); // span equalisation after offset + Kurve& k2Out /*, double offset, int arc_direction*/ +); // span equalisation after offset Point IntofIso(Span& one, Span& two, Span& three); // for iso blend radiuses - calc intersection @@ -1615,25 +1677,30 @@ int LineArcIntof(const Span& line, const Span& arc, Point& p0, Point& p1, double int ArcArcIntof(const Span& arc0, const Span& arc1, Point& pLeft, Point& pRight); bool OnSpan(const Span& sp, const Point& p); -bool OnSpan(const Span& sp, - const Point& p, - bool nearPoints, - Point& pNear, - Point& pOnSpan); // function returns true if pNear == pOnSpan +bool OnSpan( + const Span& sp, + const Point& p, + bool nearPoints, + Point& pNear, + Point& pOnSpan +); // function returns true if pNear == pOnSpan // pNear (nearest on unbound span) // pOnSpan (nearest on finite span) int Intof(const Line& v0, const Line& v1, Point3d& intof); // intof 2 lines -double Dist(const Line& l, - const Point3d& p, - Point3d& pnear, - double& t); // distance from a point to a line -Point3d -Near(const Line& l, const Point3d& p, double& t); // near point to a line & t in 0-length range -double Dist(const Span& sp, - const Point& p, - Point& pnear); // distance from p to sp, nearpoint returned as pnear +double Dist( + const Line& l, + const Point3d& p, + Point3d& pnear, + double& t +); // distance from a point to a line +Point3d Near(const Line& l, const Point3d& p, double& t); // near point to a line & t in 0-length range +double Dist( + const Span& sp, + const Point& p, + Point& pnear +); // distance from p to sp, nearpoint returned as pnear // Kurve splineUsingBiarc(CLine& cl0, CLine& cl1, std::vector); @@ -1661,17 +1728,21 @@ public: // methods void minmax(); - Point3d Near(const Point3d& p, - double& t) const; // near point to line from point (0 >= t <= 1) in range + Point3d Near( + const Point3d& p, + double& t + ) const; // near point to line from point (0 >= t <= 1) in range int Intof(const Line& l, Point3d& intof) const { return geoff_geometry::Intof(*this, l, intof); }; // intof 2 lines bool atZ(double z, Point3d& p) const; // returns p at z on line - bool Shortest(const Line& l2, - Line& lshort, - double& t1, - double& t2) const; // calculate shortest line between this & l2 + bool Shortest( + const Line& l2, + Line& lshort, + double& t1, + double& t2 + ) const; // calculate shortest line between this & l2 }; diff --git a/src/Mod/CAM/libarea/kurve/kurve.cpp b/src/Mod/CAM/libarea/kurve/kurve.cpp index e666a677da..ac2fc18d4a 100644 --- a/src/Mod/CAM/libarea/kurve/kurve.cpp +++ b/src/Mod/CAM/libarea/kurve/kurve.cpp @@ -9,7 +9,7 @@ using namespace geoff_geometry; #ifdef PEPSPOST -#include "postoutput.h" +# include "postoutput.h" #endif @@ -777,11 +777,11 @@ void Kurve::Replace(int vertexnumber, int type, const Point& p0, const Point& pc void Kurve::ModifyIndex(int vertexnumber, WireExtraData* i) { // replace an index -#ifdef _DEBUG +# ifdef _DEBUG if (vertexnumber > m_nVertices) { FAILURE(getMessage(L"Kurve::ModifyIndex - vertexNumber out of range")); } -#endif +# endif SpanVertex* p = (SpanVertex*)m_spans[vertexnumber / SPANSTORAGE]; p->Add(vertexnumber % SPANSTORAGE, i); } @@ -1197,8 +1197,7 @@ void Kurve::minmax(Point& min, Point& max) max = Point(-1.0e61, -1.0e61); if (!GetScale(xscale)) { - FAILURE( - getMessage(L"Differential Scale not allowed for this method")); // differential scale + FAILURE(getMessage(L"Differential Scale not allowed for this method")); // differential scale } Span sp; for (int i = 1; i < m_nVertices; i++) { @@ -1260,8 +1259,7 @@ double Kurve::Perim() const Span sp; double xscale = 1.0; if (!GetScale(xscale)) { - FAILURE( - getMessage(L"Differential Scale not allowed for this method")); // differential scale + FAILURE(getMessage(L"Differential Scale not allowed for this method")); // differential scale } if (m_nVertices > 1) { @@ -1280,15 +1278,16 @@ double Kurve::Area() const if (Closed()) { if (!GetScale(xscale)) { - FAILURE(getMessage( - L"Differential Scale not allowed for this method")); // differential scale + FAILURE(getMessage(L"Differential Scale not allowed for this method")); // differential + // scale } for (int i = 1; i < m_nVertices; i++) { if (Get(i, sp, true)) { - area += (0.5 - * ((sp.pc.x - sp.p0.x) * (sp.pc.y + sp.p0.y) - - (sp.pc.x - sp.p1.x) * (sp.pc.y + sp.p1.y) - - sp.angle * sp.radius * sp.radius)); + area + += (0.5 + * ((sp.pc.x - sp.p0.x) * (sp.pc.y + sp.p0.y) + - (sp.pc.x - sp.p1.x) * (sp.pc.y + sp.p1.y) + - sp.angle * sp.radius * sp.radius)); } else { area += 0.5 * (sp.p1.x - sp.p0.x) * (sp.p0.y + sp.p1.y); diff --git a/src/Mod/CAM/libarea/kurve/offset.cpp b/src/Mod/CAM/libarea/kurve/offset.cpp index ea62c53c31..5cdebdd203 100644 --- a/src/Mod/CAM/libarea/kurve/offset.cpp +++ b/src/Mod/CAM/libarea/kurve/offset.cpp @@ -16,11 +16,7 @@ namespace geoff_geometry static Kurve eliminateLoops(const Kurve& k, const Kurve& originalk, double offset, int& ret); static bool DoesIntersInterfere(const Point& pInt, const Kurve& k, double offset); -int Kurve::Offset(vector& OffsetKurves, - double offset, - int direction, - int method, - int& ret) const +int Kurve::Offset(vector& OffsetKurves, double offset, int direction, int method, int& ret) const { switch (method) { @@ -111,8 +107,8 @@ int Kurve::OffsetMethod1(Kurve& kOffset, double off, int direction, int method, // see if offset spans intersect double cp = prevSpanOff.ve ^ curSpanOff.vs; - bool inters = - (cp > 0 && direction == GEOFF_LEFT) || (cp < 0 && direction == GEOFF_RIGHT); + bool inters = (cp > 0 && direction == GEOFF_LEFT) + || (cp < 0 && direction == GEOFF_RIGHT); if (inters) { double t[4]; @@ -121,11 +117,13 @@ int Kurve::OffsetMethod1(Kurve& kOffset, double off, int direction, int method, if (numint == 1) { // intersection - modify previous endpoint - kOffset.Replace(kOffset.m_nVertices - 1, - prevSpanOff.dir, - p0, - prevSpanOff.pc, - prevSpanOff.ID); + kOffset.Replace( + kOffset.m_nVertices - 1, + prevSpanOff.dir, + p0, + prevSpanOff.pc, + prevSpanOff.ID + ); } else { // 0 or 2 intersections, add roll around (remove -ve loops in elimination @@ -240,8 +238,7 @@ static Kurve eliminateLoops(const Kurve& k, const Kurve& originalk, double offse double t[4]; int numint = sp0.Intof(sp1, pInt, pIntOther, t); // find span intersections if (numint && sp0.p0.Dist(pInt) < geoff_geometry::TOLERANCE) { - numint = - 0; // check that intersection is not at the start of the check span + numint = 0; // check that intersection is not at the start of the check span } if (numint) { diff --git a/src/Mod/CAM/libarea/pyarea.cpp b/src/Mod/CAM/libarea/pyarea.cpp index 2dcb2b01ec..ee3cfd483b 100644 --- a/src/Mod/CAM/libarea/pyarea.cpp +++ b/src/Mod/CAM/libarea/pyarea.cpp @@ -7,7 +7,7 @@ #ifdef _MSC_VER -#define strdup _strdup +# define strdup _strdup #endif #include "Area.h" @@ -59,15 +59,19 @@ static void print_curve(const CCurve& c) for (std::list::const_iterator It = c.m_vertices.begin(); It != c.m_vertices.end(); It++, i++) { const CVertex& vertex = *It; - printf("vertex %d type = %d, x = %g, y = %g", - i + 1, - vertex.m_type, - vertex.m_p.x / CArea::get_units(), - vertex.m_p.y / CArea::get_units()); + printf( + "vertex %d type = %d, x = %g, y = %g", + i + 1, + vertex.m_type, + vertex.m_p.x / CArea::get_units(), + vertex.m_p.y / CArea::get_units() + ); if (vertex.m_type) { - printf(", xc = %g, yc = %g", - vertex.m_c.x / CArea::get_units(), - vertex.m_c.y / CArea::get_units()); + printf( + ", xc = %g, yc = %g", + vertex.m_c.x / CArea::get_units(), + vertex.m_c.y / CArea::get_units() + ); } printf("\n"); } @@ -132,22 +136,26 @@ static py::tuple nearest_point_to_curve(CCurve& c1, const CCurve& c2) return py::make_tuple(p, dist); } -std::list MakePocketToolpath(const CArea& a, - double tool_radius, - double extra_offset, - double stepover, - bool from_center, - bool use_zig_zag, - double zig_angle) +std::list MakePocketToolpath( + const CArea& a, + double tool_radius, + double extra_offset, + double stepover, + bool from_center, + bool use_zig_zag, + double zig_angle +) { std::list toolpath; - CAreaPocketParams params(tool_radius, - extra_offset, - stepover, - from_center, - use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, - zig_angle); + CAreaPocketParams params( + tool_radius, + extra_offset, + stepover, + from_center, + use_zig_zag ? ZigZagPocketMode : SpiralPocketMode, + zig_angle + ); a.SplitAndMakePocketToolpath(toolpath, params); return toolpath; @@ -305,10 +313,11 @@ void init_pyarea(py::module& m) py::class_(m, "Span") .def(py::init()) .def(py::init()) - .def("NearestPoint", - static_cast(&Span::NearestPoint)) - .def("NearestPoint", - static_cast(&Span::NearestPoint)) + .def("NearestPoint", static_cast(&Span::NearestPoint)) + .def( + "NearestPoint", + static_cast(&Span::NearestPoint) + ) .def("GetBox", &Span::GetBox) .def("IncludedAngle", &Span::IncludedAngle) .def("GetArea", &Span::GetArea) @@ -327,8 +336,7 @@ void init_pyarea(py::module& m) .def("append", &CCurve::append) .def("append", &append_point) .def("text", &print_curve) - .def("NearestPoint", - static_cast(&CCurve::NearestPoint)) + .def("NearestPoint", static_cast(&CCurve::NearestPoint)) .def("NearestPoint", &nearest_point_to_curve) .def("Reverse", &CCurve::Reverse) .def("getNumVertices", &num_vertices) diff --git a/src/Mod/Cloud/App/AppCloud.cpp b/src/Mod/Cloud/App/AppCloud.cpp index 0b7a98689c..638c1bb819 100644 --- a/src/Mod/Cloud/App/AppCloud.cpp +++ b/src/Mod/Cloud/App/AppCloud.cpp @@ -27,8 +27,8 @@ #include #if defined(FC_OS_WIN32) -#include -#include +# include +# include #endif #include @@ -281,23 +281,21 @@ void Cloud::CloudWriter::createBucket() eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - RequestData = Cloud::ComputeDigestAmzS3v2("PUT", - "application/xml", - path, - this->TokenSecret, - nullptr, - 0); + RequestData + = Cloud::ComputeDigestAmzS3v2("PUT", "application/xml", path, this->TokenSecret, nullptr, 0); } else { - RequestDatav4 = Cloud::ComputeDigestAmzS3v4("PUT", - strURL.c_str(), - "application/xml", - path, - this->TokenSecret, - nullptr, - 0, - nullptr, - this->Region); + RequestDatav4 = Cloud::ComputeDigestAmzS3v4( + "PUT", + strURL.c_str(), + "application/xml", + path, + this->TokenSecret, + nullptr, + 0, + nullptr, + this->Region + ); } // Let's build the Header and call to curl @@ -316,10 +314,7 @@ void Cloud::CloudWriter::createBucket() eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), - this->TCPPort, - this->TokenAuth, - RequestData); + chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), this->TCPPort, this->TokenAuth, RequestData); delete RequestData; } else { @@ -354,15 +349,17 @@ void Cloud::CloudWriter::createBucket() } -struct Cloud::AmzDatav4* Cloud::ComputeDigestAmzS3v4(char* operation, - const char* server, - char* data_type, - const char* target, - const char* Secret, - const char* ptr, - long size, - char* parameters, - std::string Region) +struct Cloud::AmzDatav4* Cloud::ComputeDigestAmzS3v4( + char* operation, + const char* server, + char* data_type, + const char* target, + const char* Secret, + const char* ptr, + long size, + char* parameters, + std::string Region +) { struct AmzDatav4* returnData; returnData = new Cloud::AmzDatav4; @@ -456,56 +453,66 @@ struct Cloud::AmzDatav4* Cloud::ComputeDigestAmzS3v4(char* operation, std::string temporary; - kDate = HMAC(EVP_sha256(), - kSecret, - strlen(kSecret), - (const unsigned char*)returnData->dateFormattedD, - strlen(returnData->dateFormattedD), - nullptr, - &HMACLength); + kDate = HMAC( + EVP_sha256(), + kSecret, + strlen(kSecret), + (const unsigned char*)returnData->dateFormattedD, + strlen(returnData->dateFormattedD), + nullptr, + &HMACLength + ); temporary = getHexValue(kDate, HMACLength); temporary = getHexValue(kDate, HMACLength); // We can now compute the remaining parts - kRegion = HMAC(EVP_sha256(), - kDate, - HMACLength, - (const unsigned char*)Region.c_str(), - strlen(Region.c_str()), - nullptr, - &HMACLength); + kRegion = HMAC( + EVP_sha256(), + kDate, + HMACLength, + (const unsigned char*)Region.c_str(), + strlen(Region.c_str()), + nullptr, + &HMACLength + ); temporary = getHexValue(kRegion, HMACLength); - kService = HMAC(EVP_sha256(), - kRegion, - HMACLength, - (const unsigned char*)"s3", - strlen("s3"), - nullptr, - &HMACLength); + kService = HMAC( + EVP_sha256(), + kRegion, + HMACLength, + (const unsigned char*)"s3", + strlen("s3"), + nullptr, + &HMACLength + ); temporary = getHexValue(kService, HMACLength); - kSigning = HMAC(EVP_sha256(), - kService, - HMACLength, - (const unsigned char*)"aws4_request", - strlen("aws4_request"), - nullptr, - &HMACLength); + kSigning = HMAC( + EVP_sha256(), + kService, + HMACLength, + (const unsigned char*)"aws4_request", + strlen("aws4_request"), + nullptr, + &HMACLength + ); temporary = getHexValue(kService, HMACLength); - kSigned = HMAC(EVP_sha256(), - kSigning, - HMACLength, - (const unsigned char*)stringToSign, - strlen(stringToSign), - nullptr, - &HMACLength); + kSigned = HMAC( + EVP_sha256(), + kSigning, + HMACLength, + (const unsigned char*)stringToSign, + strlen(stringToSign), + nullptr, + &HMACLength + ); temporary = getHexValue(kSigned, HMACLength); @@ -530,12 +537,14 @@ std::string Cloud::getHexValue(unsigned char* input, unsigned int HMACLength) return resultReadable; } -struct Cloud::AmzData* Cloud::ComputeDigestAmzS3v2(char* operation, - char* data_type, - const char* target, - const char* Secret, - const char* ptr, - long size) +struct Cloud::AmzData* Cloud::ComputeDigestAmzS3v2( + char* operation, + char* data_type, + const char* target, + const char* Secret, + const char* ptr, + long size +) { struct AmzData* returnData; // struct timeval tv; @@ -566,13 +575,15 @@ struct Cloud::AmzData* Cloud::ComputeDigestAmzS3v2(char* operation, if (strcmp(operation, "PUT") == 0) { if (ptr != nullptr) { returnData->MD5 = Cloud::MD5Sum(ptr, size); - sprintf(StringToSign, - "%s\n%s\n%s\n%s\n%s", - operation, - returnData->MD5, - data_type, - date_formatted, - target); + sprintf( + StringToSign, + "%s\n%s\n%s\n%s\n%s", + operation, + returnData->MD5, + data_type, + date_formatted, + target + ); } else { sprintf(StringToSign, "%s\n\n%s\n%s\n%s", operation, data_type, date_formatted, target); @@ -582,13 +593,15 @@ struct Cloud::AmzData* Cloud::ComputeDigestAmzS3v2(char* operation, sprintf(StringToSign, "%s\n\n%s\n%s\n%s", operation, data_type, date_formatted, target); } // We have to use HMAC encoding and SHA1 - digest = HMAC(EVP_sha1(), - Secret, - strlen(Secret), - (const unsigned char*)&StringToSign, - strlen(StringToSign), - nullptr, - &HMACLength); + digest = HMAC( + EVP_sha1(), + Secret, + strlen(Secret), + (const unsigned char*)&StringToSign, + strlen(StringToSign), + nullptr, + &HMACLength + ); returnData->digest = Base::base64_encode(digest, HMACLength); strcpy(returnData->dateFormatted, date_formatted); return returnData; @@ -620,8 +633,11 @@ char* Cloud::MD5Sum(const char* ptr, long size) return (output); } -struct curl_slist* -Cloud::BuildHeaderAmzS3v4(const char* URL, const char* PublicKey, struct Cloud::AmzDatav4* Data) +struct curl_slist* Cloud::BuildHeaderAmzS3v4( + const char* URL, + const char* PublicKey, + struct Cloud::AmzDatav4* Data +) { char header_data[1024]; struct curl_slist* chunk = nullptr; @@ -660,24 +676,28 @@ Cloud::BuildHeaderAmzS3v4(const char* URL, const char* PublicKey, struct Cloud:: } // build the Auth entry - sprintf(header_data, - "Authorization: AWS4-HMAC-SHA256 Credential=%s/%s/%s/%s/aws4_request, " - "SignedHeaders=%s, Signature=%s", - PublicKey, - Data->dateFormattedD, - "us", - "s3", - "host;x-amz-date", - Data->digest.c_str()); + sprintf( + header_data, + "Authorization: AWS4-HMAC-SHA256 Credential=%s/%s/%s/%s/aws4_request, " + "SignedHeaders=%s, Signature=%s", + PublicKey, + Data->dateFormattedD, + "us", + "s3", + "host;x-amz-date", + Data->digest.c_str() + ); chunk = curl_slist_append(chunk, header_data); return chunk; } -struct curl_slist* Cloud::BuildHeaderAmzS3v2(const char* URL, - const char* TCPPort, - const char* PublicKey, - struct Cloud::AmzData* Data) +struct curl_slist* Cloud::BuildHeaderAmzS3v2( + const char* URL, + const char* TCPPort, + const char* PublicKey, + struct Cloud::AmzData* Data +) { char header_data[1024]; struct curl_slist* chunk = nullptr; @@ -712,13 +732,15 @@ struct curl_slist* Cloud::BuildHeaderAmzS3v2(const char* URL, return chunk; } -Cloud::CloudWriter::CloudWriter(const char* URL, - const char* TokenAuth, - const char* TokenSecret, - const char* TCPPort, - const char* Bucket, - std::string ProtocolVersion, - std::string Region) +Cloud::CloudWriter::CloudWriter( + const char* URL, + const char* TokenAuth, + const char* TokenSecret, + const char* TCPPort, + const char* Bucket, + std::string ProtocolVersion, + std::string Region +) { struct Cloud::AmzData* RequestData; struct Cloud::AmzDatav4* RequestDatav4; @@ -746,23 +768,21 @@ Cloud::CloudWriter::CloudWriter(const char* URL, eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - RequestData = Cloud::ComputeDigestAmzS3v2("GET", - "application/xml", - path, - this->TokenSecret, - nullptr, - 0); + RequestData + = Cloud::ComputeDigestAmzS3v2("GET", "application/xml", path, this->TokenSecret, nullptr, 0); } else { - RequestDatav4 = Cloud::ComputeDigestAmzS3v4("GET", - strURL.c_str(), - "application/xml", - path, - this->TokenSecret, - nullptr, - 0, - nullptr, - this->Region); + RequestDatav4 = Cloud::ComputeDigestAmzS3v4( + "GET", + strURL.c_str(), + "application/xml", + path, + this->TokenSecret, + nullptr, + 0, + nullptr, + this->Region + ); } // Let's build the Header and call to curl curl_global_init(CURL_GLOBAL_ALL); @@ -779,10 +799,7 @@ Cloud::CloudWriter::CloudWriter(const char* URL, eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), - this->TCPPort, - this->TokenAuth, - RequestData); + chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), this->TCPPort, this->TokenAuth, RequestData); delete RequestData; } else { @@ -823,9 +840,11 @@ Cloud::CloudWriter::CloudWriter(const char* URL, parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); - xercesc::MemBufInputSource myxml_buf((const XMLByte* const)s.c_str(), - s.size(), - "myxml (in memory)"); + xercesc::MemBufInputSource myxml_buf( + (const XMLByte* const)s.c_str(), + s.size(), + "myxml (in memory)" + ); parser->parse(myxml_buf); auto* dom = parser->getDocument(); @@ -842,8 +861,7 @@ Cloud::CloudWriter::CloudWriter(const char* URL, Cloud::CloudWriter::~CloudWriter() {} -size_t -Cloud::CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::string* s) +size_t Cloud::CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::string* s) { size_t newLength = size * nmemb; try { @@ -932,13 +950,15 @@ void Cloud::CloudReader::checkXML(DOMNode* node) Cloud::CloudReader::~CloudReader() {} -Cloud::CloudReader::CloudReader(const char* URL, - const char* TokenAuth, - const char* TokenSecret, - const char* TCPPort, - const char* Bucket, - std::string ProtocolVersion, - std::string Region) +Cloud::CloudReader::CloudReader( + const char* URL, + const char* TokenAuth, + const char* TokenSecret, + const char* TCPPort, + const char* Bucket, + std::string ProtocolVersion, + std::string Region +) { struct Cloud::AmzData* RequestData; struct Cloud::AmzDatav4* RequestDatav4; @@ -995,28 +1015,34 @@ Cloud::CloudReader::CloudReader(const char* URL, curl_easy_setopt(curl, CURLOPT_URL, URL); if (this->ProtocolVersion == "2") { - RequestData = Cloud::ComputeDigestAmzS3v2("GET", - "application/xml", - path, - this->TokenSecret, - nullptr, - 0); - chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), - this->TCPPort, - this->TokenAuth, - RequestData); + RequestData = Cloud::ComputeDigestAmzS3v2( + "GET", + "application/xml", + path, + this->TokenSecret, + nullptr, + 0 + ); + chunk = Cloud::BuildHeaderAmzS3v2( + strURL.c_str(), + this->TCPPort, + this->TokenAuth, + RequestData + ); delete RequestData; } else { - RequestDatav4 = Cloud::ComputeDigestAmzS3v4("GET", - strURL.c_str(), - "application/xml", - path, - this->TokenSecret, - nullptr, - 0, - (char*)¶meters[0], - this->Region); + RequestDatav4 = Cloud::ComputeDigestAmzS3v4( + "GET", + strURL.c_str(), + "application/xml", + path, + this->TokenSecret, + nullptr, + 0, + (char*)¶meters[0], + this->Region + ); chunk = Cloud::BuildHeaderAmzS3v4(strURL.c_str(), this->TokenAuth, RequestDatav4); delete RequestDatav4; } @@ -1053,9 +1079,11 @@ Cloud::CloudReader::CloudReader(const char* URL, parser->setValidationScheme(XercesDOMParser::Val_Always); parser->setDoNamespaces(true); - xercesc::MemBufInputSource myxml_buf((const XMLByte* const)s.c_str(), - s.size(), - "myxml (in memory)"); + xercesc::MemBufInputSource myxml_buf( + (const XMLByte* const)s.c_str(), + s.size(), + "myxml (in memory)" + ); parser->parse(myxml_buf); auto* dom = parser->getDocument(); @@ -1088,23 +1116,27 @@ void Cloud::CloudReader::DownloadFile(Cloud::CloudReader::FileEntry* entry) eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - RequestData = Cloud::ComputeDigestAmzS3v2("GET", - "application/octet-stream", - path, - this->TokenSecret, - nullptr, - 0); + RequestData = Cloud::ComputeDigestAmzS3v2( + "GET", + "application/octet-stream", + path, + this->TokenSecret, + nullptr, + 0 + ); } else { - RequestDatav4 = Cloud::ComputeDigestAmzS3v4("GET", - strURL.c_str(), - "application/octet-stream", - path, - this->TokenSecret, - nullptr, - 0, - nullptr, - this->Region); + RequestDatav4 = Cloud::ComputeDigestAmzS3v4( + "GET", + strURL.c_str(), + "application/octet-stream", + path, + this->TokenSecret, + nullptr, + 0, + nullptr, + this->Region + ); } // Let's build the Header and call to curl @@ -1122,10 +1154,7 @@ void Cloud::CloudReader::DownloadFile(Cloud::CloudReader::FileEntry* entry) eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), - this->TCPPort, - this->TokenAuth, - RequestData); + chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), this->TCPPort, this->TokenAuth, RequestData); delete RequestData; } else { @@ -1227,23 +1256,27 @@ void Cloud::CloudWriter::pushCloud(const char* FileName, const char* data, long eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - RequestData = Cloud::ComputeDigestAmzS3v2("PUT", - "application/octet-stream", - path, - this->TokenSecret, - data, - size); + RequestData = Cloud::ComputeDigestAmzS3v2( + "PUT", + "application/octet-stream", + path, + this->TokenSecret, + data, + size + ); } else { - RequestDatav4 = Cloud::ComputeDigestAmzS3v4("PUT", - strURL.c_str(), - "application/octet-stream", - path, - this->TokenSecret, - data, - size, - nullptr, - this->Region); + RequestDatav4 = Cloud::ComputeDigestAmzS3v4( + "PUT", + strURL.c_str(), + "application/octet-stream", + path, + this->TokenSecret, + data, + size, + nullptr, + this->Region + ); } // Let's build the Header and call to curl @@ -1261,10 +1294,7 @@ void Cloud::CloudWriter::pushCloud(const char* FileName, const char* data, long eraseSubStr(strURL, "http://"); eraseSubStr(strURL, "https://"); if (this->ProtocolVersion == "2") { - chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), - this->TCPPort, - this->TokenAuth, - RequestData); + chunk = Cloud::BuildHeaderAmzS3v2(strURL.c_str(), this->TCPPort, this->TokenAuth, RequestData); delete RequestData; } else { @@ -1337,7 +1367,8 @@ bool Cloud::Module::cloudSave(const char* BucketName) Document* doc = GetApplication().getActiveDocument(); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Document"); + "User parameter:BaseApp/Preferences/Document" + ); // Save the name of the tip object in order to handle in Restore() if (doc->Tip.getValue()) { @@ -1351,23 +1382,24 @@ bool Cloud::Module::cloudSave(const char* BucketName) .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") ->GetBool("prefSetAuthorOnSave", false); if (saveAuthor) { - std::string Author = - App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") - ->GetASCII("prefAuthor", ""); + std::string Author = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document") + ->GetASCII("prefAuthor", ""); doc->LastModifiedBy.setValue(Author.c_str()); } if (strcmp(BucketName, doc->Label.getValue()) != 0) { doc->Label.setValue(BucketName); } - Cloud::CloudWriter mywriter((const char*)this->URL.getStrValue().c_str(), - (const char*)this->TokenAuth.getStrValue().c_str(), - (const char*)this->TokenSecret.getStrValue().c_str(), - (const char*)this->TCPPort.getStrValue().c_str(), - BucketName, - (const char*)this->ProtocolVersion.getStrValue().c_str(), - this->Region.getStrValue()); + Cloud::CloudWriter mywriter( + (const char*)this->URL.getStrValue().c_str(), + (const char*)this->TokenAuth.getStrValue().c_str(), + (const char*)this->TokenSecret.getStrValue().c_str(), + (const char*)this->TCPPort.getStrValue().c_str(), + BucketName, + (const char*)this->ProtocolVersion.getStrValue().c_str(), + this->Region.getStrValue() + ); mywriter.putNextEntry("Document.xml"); @@ -1404,9 +1436,11 @@ void readFiles(Cloud::CloudReader reader, Base::XMLReader* xmlreader) std::vector::const_iterator it = xmlreader->FileList.begin(); while (it != xmlreader->FileList.end()) { if (reader.isTouched(it->FileName.c_str()) == 0) { - Base::Reader localreader(reader.GetEntry(it->FileName.c_str())->FileStream, - it->FileName, - xmlreader->FileVersion); + Base::Reader localreader( + reader.GetEntry(it->FileName.c_str())->FileStream, + it->FileName, + xmlreader->FileVersion + ); // for debugging only purpose if (false) { std::stringstream ss; @@ -1470,13 +1504,15 @@ bool Cloud::Module::cloudRestore(const char* BucketName) std::stringstream oss; - Cloud::CloudReader myreader((const char*)this->URL.getStrValue().c_str(), - (const char*)this->TokenAuth.getStrValue().c_str(), - (const char*)this->TokenSecret.getStrValue().c_str(), - (const char*)this->TCPPort.getStrValue().c_str(), - BucketName, - (const char*)this->ProtocolVersion.getStrValue().c_str(), - this->Region.getStrValue()); + Cloud::CloudReader myreader( + (const char*)this->URL.getStrValue().c_str(), + (const char*)this->TokenAuth.getStrValue().c_str(), + (const char*)this->TokenSecret.getStrValue().c_str(), + (const char*)this->TCPPort.getStrValue().c_str(), + BucketName, + (const char*)this->ProtocolVersion.getStrValue().c_str(), + this->Region.getStrValue() + ); // we shall pass there the initial Document.xml file diff --git a/src/Mod/Cloud/App/AppCloud.h b/src/Mod/Cloud/App/AppCloud.h index d629b43437..7edcfe8745 100644 --- a/src/Mod/Cloud/App/AppCloud.h +++ b/src/Mod/Cloud/App/AppCloud.h @@ -71,40 +71,47 @@ struct AmzDatav4 std::string getHexValue(unsigned char* input, unsigned int HMACLength); void eraseSubStr(std::string& Str, const std::string& toErase); size_t CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::string* s); -struct AmzData* ComputeDigestAmzS3v2(char* operation, - char* data_type, - const char* target, - const char* Secret, - const char* ptr, - long size); -struct AmzDatav4* ComputeDigestAmzS3v4(char* operation, - const char* server, - char* data_type, - const char* target, - const char* Secret, - const char* ptr, - long size, - char* parameters, - std::string Region); -struct curl_slist* BuildHeaderAmzS3v2(const char* URL, - const char* TCPPort, - const char* PublicKey, - struct AmzData* Data); -struct curl_slist* -BuildHeaderAmzS3v4(const char* URL, const char* PublicKey, struct AmzDatav4* Data); +struct AmzData* ComputeDigestAmzS3v2( + char* operation, + char* data_type, + const char* target, + const char* Secret, + const char* ptr, + long size +); +struct AmzDatav4* ComputeDigestAmzS3v4( + char* operation, + const char* server, + char* data_type, + const char* target, + const char* Secret, + const char* ptr, + long size, + char* parameters, + std::string Region +); +struct curl_slist* BuildHeaderAmzS3v2( + const char* URL, + const char* TCPPort, + const char* PublicKey, + struct AmzData* Data +); +struct curl_slist* BuildHeaderAmzS3v4(const char* URL, const char* PublicKey, struct AmzDatav4* Data); char* MD5Sum(const char* ptr, long size); char* SHA256Sum(const char* ptr, long size); class CloudAppExport CloudReader { public: - CloudReader(const char* URL, - const char* AccessKey, - const char* SecretKey, - const char* TCPPort, - const char* Bucket, - std::string ProtocolVersion, - std::string Region); + CloudReader( + const char* URL, + const char* AccessKey, + const char* SecretKey, + const char* TCPPort, + const char* Bucket, + std::string ProtocolVersion, + std::string Region + ); virtual ~CloudReader(); int file = 0; int continuation = 0; @@ -142,35 +149,44 @@ public: Module() : Py::ExtensionModule("Cloud") { - add_varargs_method("URL", - &Module::sCloudURL, - "URL(string) -- Connect to a Cloud Storage service."); + add_varargs_method( + "URL", + &Module::sCloudURL, + "URL(string) -- Connect to a Cloud Storage service." + ); - add_varargs_method("TokenAuth", - &Module::sCloudTokenAuth, - "TokenAuth(string) -- Token Authorization string."); + add_varargs_method( + "TokenAuth", + &Module::sCloudTokenAuth, + "TokenAuth(string) -- Token Authorization string." + ); - add_varargs_method("TokenSecret", - &Module::sCloudTokenSecret, - "TokenSecret(string) -- Token Secret string."); + add_varargs_method( + "TokenSecret", + &Module::sCloudTokenSecret, + "TokenSecret(string) -- Token Secret string." + ); add_varargs_method("TCPPort", &Module::sCloudTCPPort, "TCPPort(string) -- Port number."); - add_varargs_method("Save", - &Module::sCloudSave, - "Save(string) -- Save the active document to the Cloud."); + add_varargs_method( + "Save", + &Module::sCloudSave, + "Save(string) -- Save the active document to the Cloud." + ); - add_varargs_method("Restore", - &Module::sCloudRestore, - "Restore(string) -- Restore to the active document from the Cloud."); + add_varargs_method( + "Restore", + &Module::sCloudRestore, + "Restore(string) -- Restore to the active document from the Cloud." + ); add_varargs_method( "ProtocolVersion", &Module::sCloudProtocolVersion, - "ProtocolVersion(string) -- Specify Amazon s3 protocol version (2 or 4)"); - add_varargs_method("Region", - &Module::sCloudRegion, - "Region(string) -- Specify Amazon s3 Region"); + "ProtocolVersion(string) -- Specify Amazon s3 protocol version (2 or 4)" + ); + add_varargs_method("Region", &Module::sCloudRegion, "Region(string) -- Specify Amazon s3 Region"); initialize("This module is the Cloud module."); // register with Python } @@ -212,13 +228,15 @@ class CloudAppExport CloudWriter: public Base::Writer public: int print = 0; char errorCode[1024] = ""; - CloudWriter(const char* URL, - const char* TokenAuth, - const char* TokenSecret, - const char* TCPPort, - const char* Bucket, - std::string ProtocolVersion, - std::string Region); + CloudWriter( + const char* URL, + const char* TokenAuth, + const char* TokenSecret, + const char* TCPPort, + const char* Bucket, + std::string ProtocolVersion, + std::string Region + ); virtual ~CloudWriter(); void pushCloud(const char* FileName, const char* data, long size); void putNextEntry(const char* file); diff --git a/src/Mod/Cloud/CloudGlobal.h b/src/Mod/Cloud/CloudGlobal.h index 56dd19c36b..c98cb95bd1 100644 --- a/src/Mod/Cloud/CloudGlobal.h +++ b/src/Mod/Cloud/CloudGlobal.h @@ -28,20 +28,20 @@ // Cloud #ifndef CloudAppExport -#ifdef CloudApp_EXPORTS -#define CloudAppExport FREECAD_DECL_EXPORT -#else -#define CloudAppExport FREECAD_DECL_IMPORT -#endif +# ifdef CloudApp_EXPORTS +# define CloudAppExport FREECAD_DECL_EXPORT +# else +# define CloudAppExport FREECAD_DECL_IMPORT +# endif #endif // Cloud #ifndef CloudGuiExport -#ifdef CloudGui_EXPORTS -#define CloudGuiExport FREECAD_DECL_EXPORT -#else -#define CloudGuiExport FREECAD_DECL_IMPORT -#endif +# ifdef CloudGui_EXPORTS +# define CloudGuiExport FREECAD_DECL_EXPORT +# else +# define CloudGuiExport FREECAD_DECL_IMPORT +# endif #endif diff --git a/src/Mod/Cloud/Gui/PreCompiled.h b/src/Mod/Cloud/Gui/PreCompiled.h index 84be05f500..6911745401 100644 --- a/src/Mod/Cloud/Gui/PreCompiled.h +++ b/src/Mod/Cloud/Gui/PreCompiled.h @@ -44,7 +44,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // Qt Toolkit diff --git a/src/Mod/Draft/App/AppDraftUtilsPy.cpp b/src/Mod/Draft/App/AppDraftUtilsPy.cpp index f6e47bb4bb..5081b48d00 100644 --- a/src/Mod/Draft/App/AppDraftUtilsPy.cpp +++ b/src/Mod/Draft/App/AppDraftUtilsPy.cpp @@ -35,24 +35,29 @@ public: Module() : Py::ExtensionModule("DraftUtils") { - add_varargs_method("readDXF", - &Module::readDXF, - "readDXF(filename,[document,ignore_errors]): " - "Imports a DXF file into the given document. " - "ignore_errors is True by default. " - "NOTE: DraftUtils.readDXF is removed. " - "Use Import.readDxf instead."); + add_varargs_method( + "readDXF", + &Module::readDXF, + "readDXF(filename,[document,ignore_errors]): " + "Imports a DXF file into the given document. " + "ignore_errors is True by default. " + "NOTE: DraftUtils.readDXF is removed. " + "Use Import.readDxf instead." + ); initialize( - "The DraftUtils module contains utility functions for the Draft module."); // register - // with - // Python + "The DraftUtils module contains utility functions for the Draft module." + ); // register + // with + // Python } private: Py::Object readDXF(const Py::Tuple& /*args*/) { - Base::Console().warning("DraftUtils.readDXF is removed. " - "Use Import.readDxf instead.\n"); + Base::Console().warning( + "DraftUtils.readDXF is removed. " + "Use Import.readDxf instead.\n" + ); return Py::None(); } }; diff --git a/src/Mod/Draft/DraftGlobal.h b/src/Mod/Draft/DraftGlobal.h index 7fd3963226..2bb8fa5a90 100644 --- a/src/Mod/Draft/DraftGlobal.h +++ b/src/Mod/Draft/DraftGlobal.h @@ -25,16 +25,16 @@ #include #ifndef DRAFT_GLOBAL_H -#define DRAFT_GLOBAL_H +# define DRAFT_GLOBAL_H // Draft -#ifndef DraftUtilsExport -#ifdef DraftUtils_EXPORTS -#define DraftUtilsExport FREECAD_DECL_EXPORT -#else -#define DraftUtilsExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef DraftUtilsExport +# ifdef DraftUtils_EXPORTS +# define DraftUtilsExport FREECAD_DECL_EXPORT +# else +# define DraftUtilsExport FREECAD_DECL_IMPORT +# endif +# endif #endif // DRAFT_GLOBAL_H diff --git a/src/Mod/Fem/App/AppFem.cpp b/src/Mod/Fem/App/AppFem.cpp index 1810ec64d3..465cb6cd4a 100644 --- a/src/Mod/Fem/App/AppFem.cpp +++ b/src/Mod/Fem/App/AppFem.cpp @@ -61,11 +61,11 @@ #include "HypothesisPy.h" #ifdef FC_USE_VTK -#include "FemPostFilter.h" -#include "FemPostFunction.h" -#include "FemPostPipeline.h" -#include "FemPostBranchFilter.h" -#include "PropertyPostDataObject.h" +# include "FemPostFilter.h" +# include "FemPostFunction.h" +# include "FemPostPipeline.h" +# include "FemPostBranchFilter.h" +# include "PropertyPostDataObject.h" #endif diff --git a/src/Mod/Fem/App/AppFemPy.cpp b/src/Mod/Fem/App/AppFemPy.cpp index 3a397668e6..7e2b989040 100644 --- a/src/Mod/Fem/App/AppFemPy.cpp +++ b/src/Mod/Fem/App/AppFemPy.cpp @@ -36,14 +36,14 @@ #include "FemMeshObject.h" #include "FemMeshPy.h" #ifdef FC_USE_VTK -#include "FemPostPipeline.h" -#include "FemVTKTools.h" -#include -#include +# include "FemPostPipeline.h" +# include "FemVTKTools.h" +# include +# include #endif #ifdef FC_USE_VTK_PYTHON -#include +# include #endif @@ -55,50 +55,67 @@ public: Module() : Py::ExtensionModule("Fem") { - add_varargs_method("open", - &Module::open, - "open(string) -- Create a new document and a Mesh::Import feature to " - "load the file into the document."); - add_varargs_method("insert", - &Module::insert, - "insert(string|mesh,[string]) -- Load or insert a mesh into the given " - "or active document."); - add_varargs_method("export", - &Module::exporter, - "export(list,string) -- Export a list of objects into a single file."); - add_varargs_method("read", - &Module::read, - "Read a mesh from a file and returns a Mesh object."); + add_varargs_method( + "open", + &Module::open, + "open(string) -- Create a new document and a Mesh::Import feature to " + "load the file into the document." + ); + add_varargs_method( + "insert", + &Module::insert, + "insert(string|mesh,[string]) -- Load or insert a mesh into the given " + "or active document." + ); + add_varargs_method( + "export", + &Module::exporter, + "export(list,string) -- Export a list of objects into a single file." + ); + add_varargs_method("read", &Module::read, "Read a mesh from a file and returns a Mesh object."); #ifdef FC_USE_VTK add_varargs_method("frdToVTK", &Module::frdToVTK, "Convert a .frd result file to VTK file"); - add_varargs_method("readResult", - &Module::readResult, - "Read a CFD or Mechanical result (auto detect) from a file (file format " - "detected from file suffix)"); - add_varargs_method("writeResult", - &Module::writeResult, - "write a CFD or FEM result (auto detect) to a file (file format " - "detected from file suffix)"); - add_varargs_method("getVtkVersion", - &Module::getVtkVersion, - "Returns the VTK version FreeCAD is linked against"); - add_varargs_method("getVtkVersionNumber", - &Module::getVtkVersionNumber, - "Returns the VTK version FreeCAD is linked against as a number"); - add_varargs_method("vtkVersionCheck", - &Module::vtkVersionCheck, - "Returns VTK version number from `major`, `minor` and `build` values"); -#ifdef FC_USE_VTK_PYTHON + add_varargs_method( + "readResult", + &Module::readResult, + "Read a CFD or Mechanical result (auto detect) from a file (file format " + "detected from file suffix)" + ); + add_varargs_method( + "writeResult", + &Module::writeResult, + "write a CFD or FEM result (auto detect) to a file (file format " + "detected from file suffix)" + ); + add_varargs_method( + "getVtkVersion", + &Module::getVtkVersion, + "Returns the VTK version FreeCAD is linked against" + ); + add_varargs_method( + "getVtkVersionNumber", + &Module::getVtkVersionNumber, + "Returns the VTK version FreeCAD is linked against as a number" + ); + add_varargs_method( + "vtkVersionCheck", + &Module::vtkVersionCheck, + "Returns VTK version number from `major`, `minor` and `build` values" + ); +# ifdef FC_USE_VTK_PYTHON add_varargs_method( "isVtkCompatible", &Module::isVtkCompatible, - "Checks if the passed vtkObject is compatible with the c++ VTK version FreeCAD uses"); + "Checks if the passed vtkObject is compatible with the c++ VTK version FreeCAD uses" + ); +# endif #endif -#endif - add_varargs_method("show", - &Module::show, - "show(shape,[string]) -- Add the mesh to the active document or create " - "one if no document exists."); + add_varargs_method( + "show", + &Module::show, + "show(shape,[string]) -- Add the mesh to the active document or create " + "one if no document exists." + ); initialize("This module is the Fem module."); // register with Python } @@ -217,22 +234,22 @@ private: PyMem_Free(Name); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem"); + "User parameter:BaseApp/Preferences/Mod/Fem" + ); Py::Sequence list(object); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = - static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); if (obj->isDerivedFrom()) { auto femMesh = static_cast(obj)->FemMesh.getValue(); if (file.hasExtension({"vtk", "vtu"})) { // get VTK prefs ParameterGrp::handle g = hGrp->GetGroup("InOutVtk"); std::string level = g->GetASCII("MeshExportLevel", "Highest"); - femMesh.writeVTK(file.filePath().c_str(), - level == "Highest" ? true : false); + femMesh.writeVTK(file.filePath().c_str(), level == "Highest" ? true : false); } else if (file.hasExtension("inp")) { // get Abaqus inp prefs @@ -313,12 +330,14 @@ private: char* fileName = nullptr; PyObject* pcObj = nullptr; - if (!PyArg_ParseTuple(args.ptr(), - "et|O!", - "utf-8", - &fileName, - &(App::DocumentObjectPy::Type), - &pcObj)) { + if (!PyArg_ParseTuple( + args.ptr(), + "et|O!", + "utf-8", + &fileName, + &(App::DocumentObjectPy::Type), + &pcObj + )) { throw Py::Exception(); } std::string EncodedName = std::string(fileName); @@ -326,8 +345,8 @@ private: if (pcObj) { if (PyObject_TypeCheck(pcObj, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = - static_cast(pcObj)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(pcObj)->getDocumentObjectPtr(); FemVTKTools::writeResult(EncodedName.c_str(), obj); } } @@ -368,7 +387,7 @@ private: return Py::Long(VTK_VERSION_CHECK(major, minor, build)); } -#ifdef FC_USE_VTK_PYTHON +# ifdef FC_USE_VTK_PYTHON Py::Object isVtkCompatible(const Py::Tuple& args) { PyObject* pcObj = nullptr; @@ -385,7 +404,7 @@ private: } return Py::True(); } -#endif +# endif #endif Py::Object show(const Py::Tuple& args) diff --git a/src/Mod/Fem/App/FemAnalysis.cpp b/src/Mod/Fem/App/FemAnalysis.cpp index 3fdfa18471..16f0e0900a 100644 --- a/src/Mod/Fem/App/FemAnalysis.cpp +++ b/src/Mod/Fem/App/FemAnalysis.cpp @@ -42,9 +42,11 @@ FemAnalysis::FemAnalysis() FemAnalysis::~FemAnalysis() = default; -void FemAnalysis::handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) +void FemAnalysis::handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName +) { Base::Type type = Base::Type::fromName(TypeName); if (Group.getClassTypeId() == type && strcmp(PropName, "Member") == 0) { diff --git a/src/Mod/Fem/App/FemAnalysis.h b/src/Mod/Fem/App/FemAnalysis.h index 884db2ea46..de2be925a4 100644 --- a/src/Mod/Fem/App/FemAnalysis.h +++ b/src/Mod/Fem/App/FemAnalysis.h @@ -85,9 +85,11 @@ protected: * property of DocumentObjectGroup. This methods translates old files * still using the "Member" property. */ - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; }; class FemExport DocumentObject: public App::DocumentObject diff --git a/src/Mod/Fem/App/FemConstraint.cpp b/src/Mod/Fem/App/FemConstraint.cpp index d3b1cbfdaf..ba112fee90 100644 --- a/src/Mod/Fem/App/FemConstraint.cpp +++ b/src/Mod/Fem/App/FemConstraint.cpp @@ -50,8 +50,8 @@ #include #include #if OCC_VERSION_HEX < 0x070600 -#include -#include +# include +# include #endif #include @@ -73,41 +73,49 @@ using Adaptor3d_HSurface = Adaptor3d_Surface; using BRepAdaptor_HSurface = BRepAdaptor_Surface; #endif -static const App::PropertyFloatConstraint::Constraints scaleConstraint = { - 0.0, - std::numeric_limits::max(), - 0.1}; +static const App::PropertyFloatConstraint::Constraints scaleConstraint + = {0.0, std::numeric_limits::max(), 0.1}; PROPERTY_SOURCE(Fem::Constraint, App::DocumentObject) Constraint::Constraint() : sizeFactor {1} { - ADD_PROPERTY_TYPE(References, - (nullptr, nullptr), - "Constraint", - (App::PropertyType)(App::Prop_None), - "Elements where the constraint is applied"); - ADD_PROPERTY_TYPE(NormalDirection, - (Base::Vector3d(0, 0, 1)), - "Constraint", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Normal direction pointing outside of solid"); - ADD_PROPERTY_TYPE(Scale, - (1), - "Constraint", - App::PropertyType(App::Prop_None), - "Scale used for drawing constraints"); - ADD_PROPERTY_TYPE(Points, - (Base::Vector3d()), - "Constraint", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output | App::Prop_Hidden), - "Points where symbols are drawn"); - ADD_PROPERTY_TYPE(Normals, - (Base::Vector3d()), - "Constraint", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output | App::Prop_Hidden), - "Normals where symbols are drawn"); + ADD_PROPERTY_TYPE( + References, + (nullptr, nullptr), + "Constraint", + (App::PropertyType)(App::Prop_None), + "Elements where the constraint is applied" + ); + ADD_PROPERTY_TYPE( + NormalDirection, + (Base::Vector3d(0, 0, 1)), + "Constraint", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Normal direction pointing outside of solid" + ); + ADD_PROPERTY_TYPE( + Scale, + (1), + "Constraint", + App::PropertyType(App::Prop_None), + "Scale used for drawing constraints" + ); + ADD_PROPERTY_TYPE( + Points, + (Base::Vector3d()), + "Constraint", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output | App::Prop_Hidden), + "Points where symbols are drawn" + ); + ADD_PROPERTY_TYPE( + Normals, + (Base::Vector3d()), + "Constraint", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output | App::Prop_Hidden), + "Normals where symbols are drawn" + ); Scale.setConstraints(&scaleConstraint); @@ -217,7 +225,8 @@ void Constraint::onSettingDocument() App::Document* doc = getDocument(); if (doc) { connDocChangedObject = doc->signalChangedObject.connect( - std::bind(&Constraint::slotChangedObject, this, sp::_1, sp::_2)); + std::bind(&Constraint::slotChangedObject, this, sp::_1, sp::_2) + ); } App::DocumentObject::onSettingDocument(); @@ -235,9 +244,11 @@ void Constraint::onDocumentRestored() App::DocumentObject::onDocumentRestored(); } -void Constraint::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Constraint::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // Old integer Scale is equal to sizeFactor, now Scale*sizeFactor is used to scale the symbol if (prop == &Scale && strcmp(TypeName, "App::PropertyInteger") == 0) { @@ -248,9 +259,11 @@ void Constraint::handleChangedPropertyType(Base::XMLReader& reader, } } -bool Constraint::getPoints(std::vector& points, - std::vector& normals, - double* scale) const +bool Constraint::getPoints( + std::vector& points, + std::vector& normals, + double* scale +) const { std::vector Objects = References.getValues(); std::vector SubElements = References.getSubValues(); @@ -438,8 +451,7 @@ bool Constraint::getPoints(std::vector& points, int stepWire = stepsu + stepsv; // apply subshape transformation to the geometry gp_Trsf faceTrans = face.Location().Transformation(); - Handle(Geom_Geometry) transGeo = - surface.Surface().Surface()->Transformed(faceTrans); + Handle(Geom_Geometry) transGeo = surface.Surface().Surface()->Transformed(faceTrans); ShapeAnalysis_Surface surfAnalysis(Handle(Geom_Surface)::DownCast(transGeo)); for (int i = 0; i < stepWire; ++i) { gp_Pnt p = compCurve.Value(outWireLength * i / stepWire); @@ -453,10 +465,12 @@ bool Constraint::getPoints(std::vector& points, return true; } -Base::Vector3d Constraint::getBasePoint(const Base::Vector3d& base, - const Base::Vector3d& axis, - const App::PropertyLinkSub& location, - const double& dist) +Base::Vector3d Constraint::getBasePoint( + const Base::Vector3d& base, + const Base::Vector3d& axis, + const App::PropertyLinkSub& location, + const double& dist +) { // Get the point specified by Location and Distance App::DocumentObject* objLoc = location.getValue(); diff --git a/src/Mod/Fem/App/FemConstraint.h b/src/Mod/Fem/App/FemConstraint.h index 1e70cf1b06..fcc6370468 100644 --- a/src/Mod/Fem/App/FemConstraint.h +++ b/src/Mod/Fem/App/FemConstraint.h @@ -156,9 +156,11 @@ protected: void onDocumentRestored() override; void onSettingDocument() override; void unsetupObject() override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; /** * @brief Returns data based on References relevant for rendering widgets. @@ -194,9 +196,11 @@ protected: * returns true. If an error occurred and the data couldn't be extracted * properly false is returned. */ - bool getPoints(std::vector& points, - std::vector& normals, - double* scale) const; + bool getPoints( + std::vector& points, + std::vector& normals, + double* scale + ) const; /** * @brief Calculate point of cylindrical face where to render widget. @@ -205,10 +209,12 @@ protected: * This method is very specific and doesn't require access to member * variables. It should be rewritten at a different place. */ - Base::Vector3d getBasePoint(const Base::Vector3d& base, - const Base::Vector3d& axis, - const App::PropertyLinkSub& location, - const double& dist); + Base::Vector3d getBasePoint( + const Base::Vector3d& base, + const Base::Vector3d& axis, + const App::PropertyLinkSub& location, + const double& dist + ); /** * @brief Get normal vector of point calculated by @ref getBasePoint. * diff --git a/src/Mod/Fem/App/FemConstraintBearing.cpp b/src/Mod/Fem/App/FemConstraintBearing.cpp index 43bb170125..84a07a1ceb 100644 --- a/src/Mod/Fem/App/FemConstraintBearing.cpp +++ b/src/Mod/Fem/App/FemConstraintBearing.cpp @@ -38,25 +38,31 @@ PROPERTY_SOURCE(Fem::ConstraintBearing, Fem::Constraint) ConstraintBearing::ConstraintBearing() { - ADD_PROPERTY_TYPE(Location, - (nullptr), - "ConstraintBearing", - (App::PropertyType)(App::Prop_None), - "Element giving axial location of constraint"); + ADD_PROPERTY_TYPE( + Location, + (nullptr), + "ConstraintBearing", + (App::PropertyType)(App::Prop_None), + "Element giving axial location of constraint" + ); ADD_PROPERTY(Dist, (0.0)); ADD_PROPERTY(AxialFree, (0)); ADD_PROPERTY(Radius, (0.0)); ADD_PROPERTY(Height, (0.0)); - ADD_PROPERTY_TYPE(BasePoint, - (Base::Vector3d(0, 0, 0)), - "ConstraintBearing", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Base point of cylindrical bearing seat"); - ADD_PROPERTY_TYPE(Axis, - (Base::Vector3d(0, 1, 0)), - "ConstraintBearing", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Axis of bearing seat"); + ADD_PROPERTY_TYPE( + BasePoint, + (Base::Vector3d(0, 0, 0)), + "ConstraintBearing", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Base point of cylindrical bearing seat" + ); + ADD_PROPERTY_TYPE( + Axis, + (Base::Vector3d(0, 1, 0)), + "ConstraintBearing", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Axis of bearing seat" + ); } App::DocumentObjectExecReturn* ConstraintBearing::execute() diff --git a/src/Mod/Fem/App/FemConstraintContact.cpp b/src/Mod/Fem/App/FemConstraintContact.cpp index fabfb4c7b8..a0ec9d95be 100644 --- a/src/Mod/Fem/App/FemConstraintContact.cpp +++ b/src/Mod/Fem/App/FemConstraintContact.cpp @@ -34,46 +34,56 @@ static const char* SurfaceBehaviors[] = {"Hard", "Linear", "Tied", nullptr}; ConstraintContact::ConstraintContact() { /*Note: Initialise parameters here*/ - ADD_PROPERTY_TYPE(Slope, - (0.0), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Contact stiffness"); - ADD_PROPERTY_TYPE(Adjust, - (0.0), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Node clearance adjustment limit"); - ADD_PROPERTY_TYPE(Friction, - (false), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Enable friction interaction"); - ADD_PROPERTY_TYPE(FrictionCoefficient, - (0.0), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Friction coefficient"); - ADD_PROPERTY_TYPE(StickSlope, - (0.0), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Stick slope"); - ADD_PROPERTY_TYPE(EnableThermalContact, - (false), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Enable thermal contact"); - ADD_PROPERTY_TYPE(ThermalContactConductance, - (std::vector {}), - "ConstraintContact", - App::PropertyType(App::Prop_None), - "Thermal contact conductance"); - ADD_PROPERTY_TYPE(SurfaceBehavior, - (1), - "ConstraintContact", - App::Prop_None, - "Surface behavior type"); + ADD_PROPERTY_TYPE( + Slope, + (0.0), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Contact stiffness" + ); + ADD_PROPERTY_TYPE( + Adjust, + (0.0), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Node clearance adjustment limit" + ); + ADD_PROPERTY_TYPE( + Friction, + (false), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Enable friction interaction" + ); + ADD_PROPERTY_TYPE( + FrictionCoefficient, + (0.0), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Friction coefficient" + ); + ADD_PROPERTY_TYPE( + StickSlope, + (0.0), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Stick slope" + ); + ADD_PROPERTY_TYPE( + EnableThermalContact, + (false), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Enable thermal contact" + ); + ADD_PROPERTY_TYPE( + ThermalContactConductance, + (std::vector {}), + "ConstraintContact", + App::PropertyType(App::Prop_None), + "Thermal contact conductance" + ); + ADD_PROPERTY_TYPE(SurfaceBehavior, (1), "ConstraintContact", App::Prop_None, "Surface behavior type"); SurfaceBehavior.setEnums(SurfaceBehaviors); } @@ -92,9 +102,11 @@ void ConstraintContact::onChanged(const App::Property* prop) Constraint::onChanged(prop); } -void ConstraintContact::handleChangedPropertyType(Base::XMLReader& reader, - const char* typeName, - App::Property* prop) +void ConstraintContact::handleChangedPropertyType( + Base::XMLReader& reader, + const char* typeName, + App::Property* prop +) { if (prop == &Slope && strcmp(typeName, "App::PropertyFloat") == 0) { App::PropertyFloat oldSlope; diff --git a/src/Mod/Fem/App/FemConstraintContact.h b/src/Mod/Fem/App/FemConstraintContact.h index f6a93cbdf3..66dbb4a5a4 100644 --- a/src/Mod/Fem/App/FemConstraintContact.h +++ b/src/Mod/Fem/App/FemConstraintContact.h @@ -66,9 +66,11 @@ public: protected: void onChanged(const App::Property* prop) override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* typeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* typeName, + App::Property* prop + ) override; }; } // namespace Fem diff --git a/src/Mod/Fem/App/FemConstraintDisplacement.cpp b/src/Mod/Fem/App/FemConstraintDisplacement.cpp index 36cbb5117a..2cdb86adae 100644 --- a/src/Mod/Fem/App/FemConstraintDisplacement.cpp +++ b/src/Mod/Fem/App/FemConstraintDisplacement.cpp @@ -40,123 +40,165 @@ ConstraintDisplacement::ConstraintDisplacement() // Displacement or Rotation not 0.0, prescribed displacement, Free and Fix should be False // x displacement - ADD_PROPERTY_TYPE(xFree, - (true), - "ConstraintDisplacement", - App::Prop_None, - "Use free translation in X-direction"); - ADD_PROPERTY_TYPE(xDisplacement, - (0.0), - "ConstraintDisplacement", - App::Prop_None, - "Translation in local X-direction"); - ADD_PROPERTY_TYPE(hasXFormula, - (false), - "ConstraintDisplacement", - App::Prop_None, - "Define translation in X-direction as a formula"); - ADD_PROPERTY_TYPE(xDisplacementFormula, - (""), - "ConstraintDisplacement", - App::Prop_None, - "Formula for translation in X-direction"); + ADD_PROPERTY_TYPE( + xFree, + (true), + "ConstraintDisplacement", + App::Prop_None, + "Use free translation in X-direction" + ); + ADD_PROPERTY_TYPE( + xDisplacement, + (0.0), + "ConstraintDisplacement", + App::Prop_None, + "Translation in local X-direction" + ); + ADD_PROPERTY_TYPE( + hasXFormula, + (false), + "ConstraintDisplacement", + App::Prop_None, + "Define translation in X-direction as a formula" + ); + ADD_PROPERTY_TYPE( + xDisplacementFormula, + (""), + "ConstraintDisplacement", + App::Prop_None, + "Formula for translation in X-direction" + ); // y displacement - ADD_PROPERTY_TYPE(yFree, - (true), - "ConstraintDisplacement", - App::Prop_None, - "Use free translation in Y-direction"); - ADD_PROPERTY_TYPE(yDisplacement, - (0.0), - "ConstraintDisplacement", - App::Prop_None, - "Translation in local Y-direction"); - ADD_PROPERTY_TYPE(hasYFormula, - (false), - "ConstraintDisplacement", - App::Prop_None, - "Define translation in Y-direction as a formula"); - ADD_PROPERTY_TYPE(yDisplacementFormula, - (""), - "ConstraintDisplacement", - App::Prop_None, - "Formula for translation in Y-direction"); + ADD_PROPERTY_TYPE( + yFree, + (true), + "ConstraintDisplacement", + App::Prop_None, + "Use free translation in Y-direction" + ); + ADD_PROPERTY_TYPE( + yDisplacement, + (0.0), + "ConstraintDisplacement", + App::Prop_None, + "Translation in local Y-direction" + ); + ADD_PROPERTY_TYPE( + hasYFormula, + (false), + "ConstraintDisplacement", + App::Prop_None, + "Define translation in Y-direction as a formula" + ); + ADD_PROPERTY_TYPE( + yDisplacementFormula, + (""), + "ConstraintDisplacement", + App::Prop_None, + "Formula for translation in Y-direction" + ); // z displacement - ADD_PROPERTY_TYPE(zFree, - (true), - "ConstraintDisplacement", - App::Prop_None, - "Use free translation in Z-direction"); - ADD_PROPERTY_TYPE(zDisplacement, - (0.0), - "ConstraintDisplacement", - App::Prop_None, - "Translation in local Z-direction"); - ADD_PROPERTY_TYPE(hasZFormula, - (false), - "ConstraintDisplacement", - App::Prop_None, - "Define translation in Z-direction as a formula"); - ADD_PROPERTY_TYPE(zDisplacementFormula, - (""), - "ConstraintDisplacement", - App::Prop_None, - "Formula for translation in Z-direction"); + ADD_PROPERTY_TYPE( + zFree, + (true), + "ConstraintDisplacement", + App::Prop_None, + "Use free translation in Z-direction" + ); + ADD_PROPERTY_TYPE( + zDisplacement, + (0.0), + "ConstraintDisplacement", + App::Prop_None, + "Translation in local Z-direction" + ); + ADD_PROPERTY_TYPE( + hasZFormula, + (false), + "ConstraintDisplacement", + App::Prop_None, + "Define translation in Z-direction as a formula" + ); + ADD_PROPERTY_TYPE( + zDisplacementFormula, + (""), + "ConstraintDisplacement", + App::Prop_None, + "Formula for translation in Z-direction" + ); // flow surface force - ADD_PROPERTY_TYPE(useFlowSurfaceForce, - (false), - "ConstraintDisplacement", - App::Prop_None, - "Use flow surface force"); + ADD_PROPERTY_TYPE( + useFlowSurfaceForce, + (false), + "ConstraintDisplacement", + App::Prop_None, + "Use flow surface force" + ); // x rotation - ADD_PROPERTY_TYPE(rotxFree, - (true), - "ConstraintDisplacement", - App::Prop_None, - "Use free rotation in X-direction"); - ADD_PROPERTY_TYPE(xRotation, - (0.0), - "ConstraintDisplacement", - App::Prop_None, - "Rotation in local X-direction"); + ADD_PROPERTY_TYPE( + rotxFree, + (true), + "ConstraintDisplacement", + App::Prop_None, + "Use free rotation in X-direction" + ); + ADD_PROPERTY_TYPE( + xRotation, + (0.0), + "ConstraintDisplacement", + App::Prop_None, + "Rotation in local X-direction" + ); // y rotation - ADD_PROPERTY_TYPE(rotyFree, - (true), - "ConstraintDisplacement", - App::Prop_None, - "Use free rotation in Y-direction"); - ADD_PROPERTY_TYPE(yRotation, - (0.0), - "ConstraintDisplacement", - App::Prop_None, - "Rotation in local Y-direction"); + ADD_PROPERTY_TYPE( + rotyFree, + (true), + "ConstraintDisplacement", + App::Prop_None, + "Use free rotation in Y-direction" + ); + ADD_PROPERTY_TYPE( + yRotation, + (0.0), + "ConstraintDisplacement", + App::Prop_None, + "Rotation in local Y-direction" + ); // z rotation - ADD_PROPERTY_TYPE(rotzFree, - (true), - "ConstraintDisplacement", - App::Prop_None, - "Use free rotation in Z-direction"); - ADD_PROPERTY_TYPE(zRotation, - (0.0), - "ConstraintDisplacement", - App::Prop_None, - "Rotation in local Z-direction"); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "ConstraintDisplacement", - (App::PropertyType)(App::Prop_None), - "Amplitude of the displacement boundary condition"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "ConstraintDisplacement", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + rotzFree, + (true), + "ConstraintDisplacement", + App::Prop_None, + "Use free rotation in Z-direction" + ); + ADD_PROPERTY_TYPE( + zRotation, + (0.0), + "ConstraintDisplacement", + App::Prop_None, + "Rotation in local Z-direction" + ); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "ConstraintDisplacement", + (App::PropertyType)(App::Prop_None), + "Amplitude of the displacement boundary condition" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "ConstraintDisplacement", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); } App::DocumentObjectExecReturn* ConstraintDisplacement::execute() @@ -169,9 +211,11 @@ const char* ConstraintDisplacement::getViewProviderName() const return "FemGui::ViewProviderFemConstraintDisplacement"; } -void ConstraintDisplacement::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void ConstraintDisplacement::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // properties _Displacement had App::PropertyFloat and were changed to App::PropertyDistance if (prop == &xDisplacement && strcmp(TypeName, "App::PropertyFloat") == 0) { diff --git a/src/Mod/Fem/App/FemConstraintDisplacement.h b/src/Mod/Fem/App/FemConstraintDisplacement.h index b046fd6db9..0b1d9e85be 100644 --- a/src/Mod/Fem/App/FemConstraintDisplacement.h +++ b/src/Mod/Fem/App/FemConstraintDisplacement.h @@ -71,9 +71,11 @@ public: const char* getViewProviderName() const override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp b/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp index ea5a8e3723..56bd8171c4 100644 --- a/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp @@ -158,8 +158,7 @@ void ConstraintFluidBoundary::onChanged(const App::Property* prop) if (Reversed.getValue() && (DirectionVector.getValue() == naturalDirectionVector)) { DirectionVector.setValue(-naturalDirectionVector); } - else if (!Reversed.getValue() - && (DirectionVector.getValue() != naturalDirectionVector)) { + else if (!Reversed.getValue() && (DirectionVector.getValue() != naturalDirectionVector)) { DirectionVector.setValue(naturalDirectionVector); } } diff --git a/src/Mod/Fem/App/FemConstraintForce.cpp b/src/Mod/Fem/App/FemConstraintForce.cpp index 90b717afa8..0f771477c8 100644 --- a/src/Mod/Fem/App/FemConstraintForce.cpp +++ b/src/Mod/Fem/App/FemConstraintForce.cpp @@ -35,33 +35,41 @@ PROPERTY_SOURCE(Fem::ConstraintForce, Fem::Constraint) ConstraintForce::ConstraintForce() { ADD_PROPERTY(Force, (0.0)); - ADD_PROPERTY_TYPE(Direction, - (nullptr), - "ConstraintForce", - (App::PropertyType)(App::Prop_None), - "Element giving direction of constraint"); + ADD_PROPERTY_TYPE( + Direction, + (nullptr), + "ConstraintForce", + (App::PropertyType)(App::Prop_None), + "Element giving direction of constraint" + ); // RefDispl must get a global scope, see Direction.setScope(App::LinkScope::Global); ADD_PROPERTY(Reversed, (0)); - ADD_PROPERTY_TYPE(DirectionVector, - (Base::Vector3d(0, 0, 1)), - "ConstraintForce", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Direction of arrows"); + ADD_PROPERTY_TYPE( + DirectionVector, + (Base::Vector3d(0, 0, 1)), + "ConstraintForce", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Direction of arrows" + ); // by default use the null vector to indicate an invalid value naturalDirectionVector = Base::Vector3d(0, 0, 0); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "ConstraintForce", - (App::PropertyType)(App::Prop_None), - "Amplitude of the force load"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "ConstraintForce", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "ConstraintForce", + (App::PropertyType)(App::Prop_None), + "Amplitude of the force load" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "ConstraintForce", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); } App::DocumentObjectExecReturn* ConstraintForce::execute() @@ -69,9 +77,11 @@ App::DocumentObjectExecReturn* ConstraintForce::execute() return Constraint::execute(); } -void ConstraintForce::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void ConstraintForce::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // property Force had App::PropertyFloat, was changed to App::PropertyForce if (prop == &Force && strcmp(TypeName, "App::PropertyFloat") == 0) { @@ -113,8 +123,7 @@ void ConstraintForce::onChanged(const App::Property* prop) if (Reversed.getValue() && (DirectionVector.getValue() == naturalDirectionVector)) { DirectionVector.setValue(-naturalDirectionVector); } - else if (!Reversed.getValue() - && (DirectionVector.getValue() != naturalDirectionVector)) { + else if (!Reversed.getValue() && (DirectionVector.getValue() != naturalDirectionVector)) { DirectionVector.setValue(naturalDirectionVector); } } diff --git a/src/Mod/Fem/App/FemConstraintForce.h b/src/Mod/Fem/App/FemConstraintForce.h index e762bbf568..6cef35e974 100644 --- a/src/Mod/Fem/App/FemConstraintForce.h +++ b/src/Mod/Fem/App/FemConstraintForce.h @@ -55,9 +55,11 @@ public: } protected: - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; private: diff --git a/src/Mod/Fem/App/FemConstraintGear.cpp b/src/Mod/Fem/App/FemConstraintGear.cpp index 11902a33e3..5f63041fd6 100644 --- a/src/Mod/Fem/App/FemConstraintGear.cpp +++ b/src/Mod/Fem/App/FemConstraintGear.cpp @@ -37,17 +37,21 @@ ConstraintGear::ConstraintGear() ADD_PROPERTY(Diameter, (100.0)); ADD_PROPERTY(Force, (1000.0)); ADD_PROPERTY(ForceAngle, (0.0)); - ADD_PROPERTY_TYPE(Direction, - (nullptr), - "ConstraintGear", - (App::PropertyType)(App::Prop_None), - "Element giving direction of gear force"); + ADD_PROPERTY_TYPE( + Direction, + (nullptr), + "ConstraintGear", + (App::PropertyType)(App::Prop_None), + "Element giving direction of gear force" + ); ADD_PROPERTY(Reversed, (0)); - ADD_PROPERTY_TYPE(DirectionVector, - (Base::Vector3d(1, 1, 1).Normalize()), - "ConstraintGear", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Direction of gear force"); + ADD_PROPERTY_TYPE( + DirectionVector, + (Base::Vector3d(1, 1, 1).Normalize()), + "ConstraintGear", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Direction of gear force" + ); naturalDirectionVector = Base::Vector3d(1, 1, 1).Normalize(); } diff --git a/src/Mod/Fem/App/FemConstraintHeatflux.cpp b/src/Mod/Fem/App/FemConstraintHeatflux.cpp index 9c464f1ab3..a4d3346929 100644 --- a/src/Mod/Fem/App/FemConstraintHeatflux.cpp +++ b/src/Mod/Fem/App/FemConstraintHeatflux.cpp @@ -34,37 +34,35 @@ static const char* ConstraintTypes[] = {"DFlux", "Convection", "Radiation", null ConstraintHeatflux::ConstraintHeatflux() { - ADD_PROPERTY_TYPE(AmbientTemp, - (0.0), - "ConstraintHeatflux", - App::Prop_None, - "Ambient temperature"); + ADD_PROPERTY_TYPE(AmbientTemp, (0.0), "ConstraintHeatflux", App::Prop_None, "Ambient temperature"); /*ADD_PROPERTY(FaceTemp,(0.0));*/ ADD_PROPERTY_TYPE(FilmCoef, (0.0), "ConstraintHeatflux", App::Prop_None, "Film coefficient"); ADD_PROPERTY_TYPE(Emissivity, (0.0), "ConstraintHeatflux", App::Prop_None, "Emissivity"); ADD_PROPERTY_TYPE(DFlux, (0.0), "ConstraintHeatflux", App::Prop_None, "Distributed heat flux"); - ADD_PROPERTY_TYPE(ConstraintType, - (1), - "ConstraintHeatflux", - App::Prop_None, - "Type of constraint, surface convection, radiation or surface heat flux"); + ADD_PROPERTY_TYPE( + ConstraintType, + (1), + "ConstraintHeatflux", + App::Prop_None, + "Type of constraint, surface convection, radiation or surface heat flux" + ); ConstraintType.setEnums(ConstraintTypes); - ADD_PROPERTY_TYPE(CavityRadiation, - (false), - "ConstraintHeatflux", - App::Prop_None, - "Cavity radiation"); + ADD_PROPERTY_TYPE(CavityRadiation, (false), "ConstraintHeatflux", App::Prop_None, "Cavity radiation"); ADD_PROPERTY_TYPE(CavityName, ("cav"), "ConstraintHeatflux", App::Prop_None, "Cavity name"); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "ConstraintHeatflux", - (App::PropertyType)(App::Prop_None), - "Amplitude of the heat flux load"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "ConstraintHeatflux", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "ConstraintHeatflux", + (App::PropertyType)(App::Prop_None), + "Amplitude of the heat flux load" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "ConstraintHeatflux", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); } App::DocumentObjectExecReturn* ConstraintHeatflux::execute() @@ -77,9 +75,11 @@ const char* ConstraintHeatflux::getViewProviderName() const return "FemGui::ViewProviderFemConstraintHeatflux"; } -void ConstraintHeatflux::handleChangedPropertyType(Base::XMLReader& reader, - const char* typeName, - App::Property* prop) +void ConstraintHeatflux::handleChangedPropertyType( + Base::XMLReader& reader, + const char* typeName, + App::Property* prop +) { if (prop == &FilmCoef && strcmp(typeName, "App::PropertyFloat") == 0) { App::PropertyFloat filmCoefProperty; diff --git a/src/Mod/Fem/App/FemConstraintHeatflux.h b/src/Mod/Fem/App/FemConstraintHeatflux.h index 4e10786f83..875760b57d 100644 --- a/src/Mod/Fem/App/FemConstraintHeatflux.h +++ b/src/Mod/Fem/App/FemConstraintHeatflux.h @@ -58,9 +58,11 @@ public: const char* getViewProviderName() const override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, - const char* typeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* typeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp b/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp index 8eb6c3b751..f0ecf2a0f0 100644 --- a/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp +++ b/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp @@ -36,16 +36,20 @@ ConstraintInitialTemperature::ConstraintInitialTemperature() ADD_PROPERTY(initialTemperature, (300.0)); ADD_PROPERTY(EnableFinalTemperature, (false)); ADD_PROPERTY(FinalTemperature, (300.0)); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "", - (App::PropertyType)(App::Prop_None), - "Amplitude of the final temperature field"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "", + (App::PropertyType)(App::Prop_None), + "Amplitude of the final temperature field" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); } App::DocumentObjectExecReturn* ConstraintInitialTemperature::execute() @@ -58,9 +62,11 @@ const char* ConstraintInitialTemperature::getViewProviderName() const return "FemGui::ViewProviderFemConstraintInitialTemperature"; } -void ConstraintInitialTemperature::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void ConstraintInitialTemperature::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // property initialTemperature had App::PropertyFloat, was changed to App::PropertyTemperature if (prop == &initialTemperature && strcmp(TypeName, "App::PropertyFloat") == 0) { diff --git a/src/Mod/Fem/App/FemConstraintInitialTemperature.h b/src/Mod/Fem/App/FemConstraintInitialTemperature.h index d427c1ca9a..d36ea709fb 100644 --- a/src/Mod/Fem/App/FemConstraintInitialTemperature.h +++ b/src/Mod/Fem/App/FemConstraintInitialTemperature.h @@ -55,9 +55,11 @@ public: const char* getViewProviderName() const override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintPressure.cpp b/src/Mod/Fem/App/FemConstraintPressure.cpp index b098b38cb0..bb986b22fb 100644 --- a/src/Mod/Fem/App/FemConstraintPressure.cpp +++ b/src/Mod/Fem/App/FemConstraintPressure.cpp @@ -33,16 +33,20 @@ ConstraintPressure::ConstraintPressure() { ADD_PROPERTY(Pressure, (0.0)); ADD_PROPERTY(Reversed, (0)); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "ConstraintPressure", - (App::PropertyType)(App::Prop_None), - "Amplitude of the pressure load"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "ConstraintPressure", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "ConstraintPressure", + (App::PropertyType)(App::Prop_None), + "Amplitude of the pressure load" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "ConstraintPressure", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); } App::DocumentObjectExecReturn* ConstraintPressure::execute() @@ -55,9 +59,11 @@ const char* ConstraintPressure::getViewProviderName() const return "FemGui::ViewProviderFemConstraintPressure"; } -void ConstraintPressure::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void ConstraintPressure::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // property Pressure had App::PropertyFloat and was changed to App::PropertyPressure if (prop == &Pressure && strcmp(TypeName, "App::PropertyFloat") == 0) { diff --git a/src/Mod/Fem/App/FemConstraintPressure.h b/src/Mod/Fem/App/FemConstraintPressure.h index 5e8ceeae38..b297a47ac9 100644 --- a/src/Mod/Fem/App/FemConstraintPressure.h +++ b/src/Mod/Fem/App/FemConstraintPressure.h @@ -49,9 +49,11 @@ public: const char* getViewProviderName() const override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; }; } // namespace Fem diff --git a/src/Mod/Fem/App/FemConstraintPulley.cpp b/src/Mod/Fem/App/FemConstraintPulley.cpp index edadddac47..48cdd45655 100644 --- a/src/Mod/Fem/App/FemConstraintPulley.cpp +++ b/src/Mod/Fem/App/FemConstraintPulley.cpp @@ -39,21 +39,27 @@ ConstraintPulley::ConstraintPulley() ADD_PROPERTY(IsDriven, (0)); ADD_PROPERTY(TensionForce, (0.0)); - ADD_PROPERTY_TYPE(BeltAngle, - (0), - "ConstraintPulley", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Angle of belt forces"); - ADD_PROPERTY_TYPE(BeltForce1, - (0.0), - "ConstraintPulley", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "First belt force"); - ADD_PROPERTY_TYPE(BeltForce2, - (0.0), - "ConstraintPulley", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Second belt force"); + ADD_PROPERTY_TYPE( + BeltAngle, + (0), + "ConstraintPulley", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Angle of belt forces" + ); + ADD_PROPERTY_TYPE( + BeltForce1, + (0.0), + "ConstraintPulley", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "First belt force" + ); + ADD_PROPERTY_TYPE( + BeltForce2, + (0.0), + "ConstraintPulley", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Second belt force" + ); ForceAngle.setValue(0.0); Diameter.setValue(300.0); // calculate initial values of read-only properties @@ -71,8 +77,9 @@ void ConstraintPulley::onChanged(const App::Property* prop) if ((prop == &Diameter) || (prop == &OtherDiameter) || (prop == &CenterDistance)) { if (CenterDistance.getValue() > Precision::Confusion()) { - BeltAngle.setValue(asin((Diameter.getValue() - OtherDiameter.getValue()) / 2 - / CenterDistance.getValue())); + BeltAngle.setValue( + asin((Diameter.getValue() - OtherDiameter.getValue()) / 2 / CenterDistance.getValue()) + ); BeltAngle.touch(); } } diff --git a/src/Mod/Fem/App/FemConstraintRigidBody.cpp b/src/Mod/Fem/App/FemConstraintRigidBody.cpp index 136849397f..d1a65dd8f0 100644 --- a/src/Mod/Fem/App/FemConstraintRigidBody.cpp +++ b/src/Mod/Fem/App/FemConstraintRigidBody.cpp @@ -32,92 +32,108 @@ const char* ConstraintRigidBody::boundaryModeEnum[] = {"Free", "Constraint", "Lo ConstraintRigidBody::ConstraintRigidBody() { - ADD_PROPERTY_TYPE(ReferenceNode, - (0.0, 0.0, 0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Reference node position"); - ADD_PROPERTY_TYPE(Displacement, - (0.0, 0.0, 0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Reference node displacement"); - ADD_PROPERTY_TYPE(Rotation, - (Base::Rotation(0.0, 0.0, 0.0, 1.0)), - "ConstraintRigidBody", - App::Prop_Output, - "Reference node rotation"); - ADD_PROPERTY_TYPE(ForceX, - (0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Applied force in X-direction"); - ADD_PROPERTY_TYPE(ForceY, - (0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Applied force in Y-direction"); - ADD_PROPERTY_TYPE(ForceZ, - (0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Applied force in Z-direction"); - ADD_PROPERTY_TYPE(MomentX, - (0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Applied moment in X-direction"); - ADD_PROPERTY_TYPE(MomentY, - (0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Applied moment in Y-direction"); - ADD_PROPERTY_TYPE(MomentZ, - (0.0), - "ConstraintRigidBody", - App::Prop_Output, - "Applied moment in Z-direction"); - ADD_PROPERTY_TYPE(TranslationalModeX, - ("Free"), - "ConstraintRigidBody", - App::Prop_Output, - "X-direction displacement/force mode"); - ADD_PROPERTY_TYPE(TranslationalModeY, - ("Free"), - "ConstraintRigidBody", - App::Prop_Output, - "Y-direction displacement/force mode"); - ADD_PROPERTY_TYPE(TranslationalModeZ, - ("Free"), - "ConstraintRigidBody", - App::Prop_Output, - "Z-direction displacement/force mode"); - ADD_PROPERTY_TYPE(RotationalModeX, - ("None"), - "ConstraintRigidBody", - App::Prop_Output, - "X-direction rotation/moment mode"); - ADD_PROPERTY_TYPE(RotationalModeY, - ("None"), - "ConstraintRigidBody", - App::Prop_Output, - "Y-direction rotation/moment mode"); - ADD_PROPERTY_TYPE(RotationalModeZ, - ("None"), - "ConstraintRigidBody", - App::Prop_Output, - "Z-direction rotation/moment mode"); + ADD_PROPERTY_TYPE( + ReferenceNode, + (0.0, 0.0, 0.0), + "ConstraintRigidBody", + App::Prop_Output, + "Reference node position" + ); + ADD_PROPERTY_TYPE( + Displacement, + (0.0, 0.0, 0.0), + "ConstraintRigidBody", + App::Prop_Output, + "Reference node displacement" + ); + ADD_PROPERTY_TYPE( + Rotation, + (Base::Rotation(0.0, 0.0, 0.0, 1.0)), + "ConstraintRigidBody", + App::Prop_Output, + "Reference node rotation" + ); + ADD_PROPERTY_TYPE(ForceX, (0.0), "ConstraintRigidBody", App::Prop_Output, "Applied force in X-direction"); + ADD_PROPERTY_TYPE(ForceY, (0.0), "ConstraintRigidBody", App::Prop_Output, "Applied force in Y-direction"); + ADD_PROPERTY_TYPE(ForceZ, (0.0), "ConstraintRigidBody", App::Prop_Output, "Applied force in Z-direction"); + ADD_PROPERTY_TYPE( + MomentX, + (0.0), + "ConstraintRigidBody", + App::Prop_Output, + "Applied moment in X-direction" + ); + ADD_PROPERTY_TYPE( + MomentY, + (0.0), + "ConstraintRigidBody", + App::Prop_Output, + "Applied moment in Y-direction" + ); + ADD_PROPERTY_TYPE( + MomentZ, + (0.0), + "ConstraintRigidBody", + App::Prop_Output, + "Applied moment in Z-direction" + ); + ADD_PROPERTY_TYPE( + TranslationalModeX, + ("Free"), + "ConstraintRigidBody", + App::Prop_Output, + "X-direction displacement/force mode" + ); + ADD_PROPERTY_TYPE( + TranslationalModeY, + ("Free"), + "ConstraintRigidBody", + App::Prop_Output, + "Y-direction displacement/force mode" + ); + ADD_PROPERTY_TYPE( + TranslationalModeZ, + ("Free"), + "ConstraintRigidBody", + App::Prop_Output, + "Z-direction displacement/force mode" + ); + ADD_PROPERTY_TYPE( + RotationalModeX, + ("None"), + "ConstraintRigidBody", + App::Prop_Output, + "X-direction rotation/moment mode" + ); + ADD_PROPERTY_TYPE( + RotationalModeY, + ("None"), + "ConstraintRigidBody", + App::Prop_Output, + "Y-direction rotation/moment mode" + ); + ADD_PROPERTY_TYPE( + RotationalModeZ, + ("None"), + "ConstraintRigidBody", + App::Prop_Output, + "Z-direction rotation/moment mode" + ); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "ConstraintRigidBody", - (App::PropertyType)(App::Prop_None), - "Amplitude of the rigid body boundary condition or load"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "ConstraintRigidBody", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "ConstraintRigidBody", + (App::PropertyType)(App::Prop_None), + "Amplitude of the rigid body boundary condition or load" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "ConstraintRigidBody", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); TranslationalModeX.setEnums(boundaryModeEnum); TranslationalModeY.setEnums(boundaryModeEnum); diff --git a/src/Mod/Fem/App/FemConstraintTemperature.cpp b/src/Mod/Fem/App/FemConstraintTemperature.cpp index 5c07b6575f..878fa99c30 100644 --- a/src/Mod/Fem/App/FemConstraintTemperature.cpp +++ b/src/Mod/Fem/App/FemConstraintTemperature.cpp @@ -37,22 +37,28 @@ ConstraintTemperature::ConstraintTemperature() { ADD_PROPERTY(Temperature, (300.0)); ADD_PROPERTY(CFlux, (0.0)); - ADD_PROPERTY_TYPE(ConstraintType, - (1), - "ConstraintTemperature", - (App::PropertyType)(App::Prop_None), - "Type of constraint, temperature or concentrated heat flux"); + ADD_PROPERTY_TYPE( + ConstraintType, + (1), + "ConstraintTemperature", + (App::PropertyType)(App::Prop_None), + "Type of constraint, temperature or concentrated heat flux" + ); ConstraintType.setEnums(ConstraintTypes); - ADD_PROPERTY_TYPE(EnableAmplitude, - (false), - "ConstraintTemperature", - (App::PropertyType)(App::Prop_None), - "Amplitude of the temperature boundary condition"); - ADD_PROPERTY_TYPE(AmplitudeValues, - (std::vector {"0, 0", "1, 1"}), - "ConstraintTemperature", - (App::PropertyType)(App::Prop_None), - "Amplitude values"); + ADD_PROPERTY_TYPE( + EnableAmplitude, + (false), + "ConstraintTemperature", + (App::PropertyType)(App::Prop_None), + "Amplitude of the temperature boundary condition" + ); + ADD_PROPERTY_TYPE( + AmplitudeValues, + (std::vector {"0, 0", "1, 1"}), + "ConstraintTemperature", + (App::PropertyType)(App::Prop_None), + "Amplitude values" + ); } App::DocumentObjectExecReturn* ConstraintTemperature::execute() @@ -65,9 +71,11 @@ const char* ConstraintTemperature::getViewProviderName() const return "FemGui::ViewProviderFemConstraintTemperature"; } -void ConstraintTemperature::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void ConstraintTemperature::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // property Temperature had App::PropertyFloat and was changed to App::PropertyTemperature if (prop == &Temperature && strcmp(TypeName, "App::PropertyFloat") == 0) { diff --git a/src/Mod/Fem/App/FemConstraintTemperature.h b/src/Mod/Fem/App/FemConstraintTemperature.h index 350f59d715..a165f080e1 100644 --- a/src/Mod/Fem/App/FemConstraintTemperature.h +++ b/src/Mod/Fem/App/FemConstraintTemperature.h @@ -56,9 +56,11 @@ public: const char* getViewProviderName() const override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintTransform.cpp b/src/Mod/Fem/App/FemConstraintTransform.cpp index 3bc81d2cda..4a74da9608 100644 --- a/src/Mod/Fem/App/FemConstraintTransform.cpp +++ b/src/Mod/Fem/App/FemConstraintTransform.cpp @@ -36,40 +36,52 @@ static const char* TransformTypes[] = {"Cylindrical", "Rectangular", nullptr}; ConstraintTransform::ConstraintTransform() { - ADD_PROPERTY_TYPE(Rotation, - (Base::Rotation(0.0, 0.0, 0.0, 1.0)), - "ConstraintTransform", - App::Prop_Output, - "Rectangular system transform"); - ADD_PROPERTY_TYPE(TransformType, - (1), - "ConstraintTransform", - (App::PropertyType)(App::Prop_None), - "Type of transform, rectangular or cylindrical"); + ADD_PROPERTY_TYPE( + Rotation, + (Base::Rotation(0.0, 0.0, 0.0, 1.0)), + "ConstraintTransform", + App::Prop_Output, + "Rectangular system transform" + ); + ADD_PROPERTY_TYPE( + TransformType, + (1), + "ConstraintTransform", + (App::PropertyType)(App::Prop_None), + "Type of transform, rectangular or cylindrical" + ); TransformType.setEnums(TransformTypes); - ADD_PROPERTY_TYPE(RefDispl, - (nullptr, nullptr), - "ConstraintTransform", - (App::PropertyType)(App::Prop_None), - "Elements where the constraint is applied"); + ADD_PROPERTY_TYPE( + RefDispl, + (nullptr, nullptr), + "ConstraintTransform", + (App::PropertyType)(App::Prop_None), + "Elements where the constraint is applied" + ); // RefDispl must get a global scope, see // https://forum.freecad.org/viewtopic.php?p=671402#p671402 RefDispl.setScope(App::LinkScope::Global); - ADD_PROPERTY_TYPE(NameDispl, - (nullptr), - "ConstraintTransform", - (App::PropertyType)(App::Prop_None), - "Elements where the constraint is applied"); - ADD_PROPERTY_TYPE(BasePoint, - (Base::Vector3d(0, 0, 0)), - "ConstraintTransform", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Base point of cylindrical surface"); - ADD_PROPERTY_TYPE(Axis, - (Base::Vector3d(0, 1, 0)), - "ConstraintTransform", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Axis of cylindrical surface"); + ADD_PROPERTY_TYPE( + NameDispl, + (nullptr), + "ConstraintTransform", + (App::PropertyType)(App::Prop_None), + "Elements where the constraint is applied" + ); + ADD_PROPERTY_TYPE( + BasePoint, + (Base::Vector3d(0, 0, 0)), + "ConstraintTransform", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Base point of cylindrical surface" + ); + ADD_PROPERTY_TYPE( + Axis, + (Base::Vector3d(0, 1, 0)), + "ConstraintTransform", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Axis of cylindrical surface" + ); } App::DocumentObjectExecReturn* ConstraintTransform::execute() @@ -170,9 +182,11 @@ Base::Rotation anglesToRotation(double xAngle, double yAngle, double zAngle) } // namespace -void ConstraintTransform::handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) +void ConstraintTransform::handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName +) { if (strcmp(propName, "X_rot") == 0) { double xAngle {}; diff --git a/src/Mod/Fem/App/FemConstraintTransform.h b/src/Mod/Fem/App/FemConstraintTransform.h index ecbdbb99cf..9d07ed5e62 100644 --- a/src/Mod/Fem/App/FemConstraintTransform.h +++ b/src/Mod/Fem/App/FemConstraintTransform.h @@ -53,9 +53,11 @@ public: const char* getViewProviderName() const override; protected: - void handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName + ) override; void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemMesh.cpp b/src/Mod/Fem/App/FemMesh.cpp index 4a493c0d04..b712315e64 100644 --- a/src/Mod/Fem/App/FemMesh.cpp +++ b/src/Mod/Fem/App/FemMesh.cpp @@ -70,7 +70,7 @@ #include #ifdef FC_USE_VTK -#include "FemVTKTools.h" +# include "FemVTKTools.h" #endif @@ -179,12 +179,14 @@ void FemMesh::copyMeshData(const FemMesh& mesh) editor.GetMeshDS()->AddPolyhedralVolumeWithID( nodes, static_cast(elem)->GetQuantities(), - ID); + ID + ); #else editor.GetMeshDS()->AddPolyhedralVolumeWithID( nodes, static_cast(elem)->GetQuantities(), - ID); + ID + ); #endif break; case SMDSEntity_Ball: { @@ -364,11 +366,13 @@ std::list> FemMesh::getVolumesByFace(const TopoDS_Face& face } std::vector element_face_nodes; - std::set_intersection(nodes_on_face.begin(), - nodes_on_face.end(), - node_ids.begin(), - node_ids.end(), - std::back_insert_iterator>(element_face_nodes)); + std::set_intersection( + nodes_on_face.begin(), + nodes_on_face.end(), + node_ids.begin(), + node_ids.end(), + std::back_insert_iterator>(element_face_nodes) + ); if (element_face_nodes.size() == node_ids.size()) { face_nodes[face->GetID()] = node_ids; @@ -388,11 +392,13 @@ std::list> FemMesh::getVolumesByFace(const TopoDS_Face& face for (const auto& it : face_nodes) { std::vector element_face_nodes; - std::set_intersection(node_ids.begin(), - node_ids.end(), - it.second.begin(), - it.second.end(), - std::back_insert_iterator>(element_face_nodes)); + std::set_intersection( + node_ids.begin(), + node_ids.end(), + it.second.begin(), + it.second.end(), + std::back_insert_iterator>(element_face_nodes) + ); // For curved faces it is possible that a volume contributes more than one face if (element_face_nodes.size() == it.second.size()) { @@ -423,11 +429,13 @@ std::list FemMesh::getFacesByFace(const TopoDS_Face& face) const } std::vector element_face_nodes; - std::set_intersection(nodes_on_face.begin(), - nodes_on_face.end(), - face_nodes.begin(), - face_nodes.end(), - std::back_insert_iterator>(element_face_nodes)); + std::set_intersection( + nodes_on_face.begin(), + nodes_on_face.end(), + face_nodes.begin(), + face_nodes.end(), + std::back_insert_iterator>(element_face_nodes) + ); // For curved faces it is possible that a volume contributes more than one face if (element_face_nodes.size() == static_cast(numNodes)) { @@ -455,11 +463,13 @@ std::list FemMesh::getEdgesByEdge(const TopoDS_Edge& edge) const } std::vector element_edge_nodes; - std::set_intersection(nodes_on_edge.begin(), - nodes_on_edge.end(), - edge_nodes.begin(), - edge_nodes.end(), - std::back_insert_iterator>(element_edge_nodes)); + std::set_intersection( + nodes_on_edge.begin(), + nodes_on_edge.end(), + edge_nodes.begin(), + edge_nodes.end(), + std::back_insert_iterator>(element_edge_nodes) + ); if (element_edge_nodes.size() == static_cast(numNodes)) { result.push_back(edge->GetID()); @@ -510,11 +520,13 @@ std::map FemMesh::getccxVolumesByFace(const TopoDS_Face& face) const std::vector element_face_nodes; std::set element_nodes; element_nodes.insert(apair.second.begin(), apair.second.end()); - std::set_intersection(nodes_on_face.begin(), - nodes_on_face.end(), - element_nodes.begin(), - element_nodes.end(), - std::back_insert_iterator>(element_face_nodes)); + std::set_intersection( + nodes_on_face.begin(), + nodes_on_face.end(), + element_nodes.begin(), + element_nodes.end(), + std::back_insert_iterator>(element_face_nodes) + ); if ((element_face_nodes.size() == 3 && num_of_nodes == 4) || (element_face_nodes.size() == 6 && num_of_nodes == 10)) { @@ -568,9 +580,7 @@ std::set FemMesh::getNodesBySolid(const TopoDS_Solid& solid) const TopAbs_ShapeEnum shapetype = TopAbs_SHAPE; ShapeAnalysis_ShapeTolerance analysis; double limit = analysis.Tolerance(solid, 1, shapetype); - Base::Console().log("The limit if a node is in or out: %.12lf in scientific: %.4e \n", - limit, - limit); + Base::Console().log("The limit if a node is in or out: %.12lf in scientific: %.4e \n", limit, limit); // get the current transform of the FemMesh const Base::Matrix4D Mtrx(getTransform()); @@ -620,7 +630,8 @@ std::set FemMesh::getNodesByFace(const TopoDS_Face& face) const BRepBndLib::Add( face, box, - Standard_False); // https://forum.freecad.org/viewtopic.php?f=18&t=21571&start=70#p221591 + Standard_False + ); // https://forum.freecad.org/viewtopic.php?f=18&t=21571&start=70#p221591 // limit where the mesh node belongs to the face: double limit = BRep_Tool::Tolerance(face); box.Enlarge(limit); @@ -803,13 +814,17 @@ std::set FemMesh::getEdgesOnly() const // if aEdgeNodes is not a subset of any aFaceNodes --> aEdge does not belong to any Face std::vector inodes; - std::set_intersection(aFaceNodes.begin(), - aFaceNodes.end(), - aEdgeNodes.begin(), - aEdgeNodes.end(), - std::back_inserter(inodes)); - std::set intersection_nodes(inodes.begin(), - inodes.end()); // convert vector to set + std::set_intersection( + aFaceNodes.begin(), + aFaceNodes.end(), + aEdgeNodes.begin(), + aEdgeNodes.end(), + std::back_inserter(inodes) + ); + std::set intersection_nodes( + inodes.begin(), + inodes.end() + ); // convert vector to set if (aEdgeNodes == intersection_nodes) { edgeBelongsToAFace = true; break; @@ -868,13 +883,17 @@ std::set FemMesh::getFacesOnly() const // if aFaceNodes is not a subset of any aVolNodes --> aFace does not belong to any // Volume std::vector inodes; - std::set_intersection(aVolNodes.begin(), - aVolNodes.end(), - aFaceNodes.begin(), - aFaceNodes.end(), - std::back_inserter(inodes)); - std::set intersection_nodes(inodes.begin(), - inodes.end()); // convert vector to set + std::set_intersection( + aVolNodes.begin(), + aVolNodes.end(), + aFaceNodes.begin(), + aFaceNodes.end(), + std::back_inserter(inodes) + ); + std::set intersection_nodes( + inodes.begin(), + inodes.end() + ); // convert vector to set if (aFaceNodes == intersection_nodes) { faceBelongsToAVolume = true; break; @@ -967,11 +986,13 @@ public: meshds->AddFaceWithID(n0, n1, n2, element_id); } else { - Base::Console().warning("NASTRAN: Failed to add face %d from nodes: (%d, %d, %d,)\n", - element_id, - elements[0], - elements[1], - elements[2]); + Base::Console().warning( + "NASTRAN: Failed to add face %d from nodes: (%d, %d, %d,)\n", + element_id, + elements[0], + elements[1], + elements[2] + ); } } }; @@ -1034,19 +1055,21 @@ public: meshds->AddVolumeWithID(n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, element_id); } else { - Base::Console().warning("NASTRAN: Failed to add volume %d from nodes: (%d, %d, %d, %d, " - "%d, %d, %d, %d, %d, %d)\n", - element_id, - elements[1], - elements[0], - elements[2], - elements[3], - elements[4], - elements[6], - elements[5], - elements[8], - elements[7], - elements[9]); + Base::Console().warning( + "NASTRAN: Failed to add volume %d from nodes: (%d, %d, %d, %d, " + "%d, %d, %d, %d, %d, %d)\n", + element_id, + elements[1], + elements[0], + elements[2], + elements[3], + elements[4], + elements[6], + elements[5], + elements[8], + elements[7], + elements[9] + ); } } }; @@ -1222,13 +1245,15 @@ class CWEDGEElement: public NastranElement } void addToMesh(SMESHDS_Mesh* meshds) override { - meshds->AddVolumeWithID(elements[0], - elements[1], - elements[2], - elements[3], - elements[4], - elements[5], - element_id); + meshds->AddVolumeWithID( + elements[0], + elements[1], + elements[2], + elements[3], + elements[4], + elements[5], + element_id + ); } }; @@ -1249,15 +1274,17 @@ class CHEXA1Element: public NastranElement } void addToMesh(SMESHDS_Mesh* meshds) override { - meshds->AddVolumeWithID(elements[0], - elements[1], - elements[2], - elements[3], - elements[4], - elements[5], - elements[6], - elements[7], - element_id); + meshds->AddVolumeWithID( + elements[0], + elements[1], + elements[2], + elements[3], + elements[4], + elements[5], + elements[6], + elements[7], + element_id + ); } }; @@ -1278,15 +1305,17 @@ class CHEXA2Element: public NastranElement } void addToMesh(SMESHDS_Mesh* meshds) override { - meshds->AddVolumeWithID(elements[0], - elements[1], - elements[2], - elements[3], - elements[4], - elements[5], - elements[6], - elements[7], - element_id); + meshds->AddVolumeWithID( + elements[0], + elements[1], + elements[2], + elements[3], + elements[4], + elements[5], + elements[6], + elements[7], + element_id + ); } }; @@ -1371,8 +1400,10 @@ void FemMesh::readNastran(const std::string& Filename) } while (inputfile.good()); inputfile.close(); - Base::Console().log(" %f: File read, start building mesh\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: File read, start building mesh\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // Now fill the SMESH datastructure SMESHDS_Mesh* meshds = this->myMesh->GetMeshDS(); @@ -1382,8 +1413,7 @@ void FemMesh::readNastran(const std::string& Filename) it->addToMesh(meshds); } - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::readNastran95(const std::string& Filename) @@ -1498,8 +1528,10 @@ void FemMesh::readNastran95(const std::string& Filename) } while (inputfile.good()); inputfile.close(); - Base::Console().log(" %f: File read, start building mesh\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: File read, start building mesh\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // Now fill the SMESH datastructure SMESHDS_Mesh* meshds = this->myMesh->GetMeshDS(); @@ -1513,8 +1545,7 @@ void FemMesh::readNastran95(const std::string& Filename) it->addToMesh(meshds); } - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::readAbaqus(const std::string& FileName) @@ -1554,8 +1585,7 @@ void FemMesh::readAbaqus(const std::string& FileName) catch (Py::Exception& e) { e.clear(); } - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::readZ88(const std::string& FileName) @@ -1595,8 +1625,7 @@ void FemMesh::readZ88(const std::string& FileName) catch (Py::Exception& e) { e.clear(); } - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } void FemMesh::read(const char* FileName) @@ -1656,12 +1685,14 @@ void FemMesh::writeVTK(const std::string& fileName, bool highest) const #endif } -void FemMesh::writeABAQUS(const std::string& Filename, - int elemParam, - bool groupParam, - ABAQUS_VolumeVariant volVariant, - ABAQUS_FaceVariant faceVariant, - ABAQUS_EdgeVariant edgeVariant) const +void FemMesh::writeABAQUS( + const std::string& Filename, + int elemParam, + bool groupParam, + ABAQUS_VolumeVariant volVariant, + ABAQUS_FaceVariant faceVariant, + ABAQUS_EdgeVariant edgeVariant +) const { /* * elemParam: @@ -1860,8 +1891,8 @@ void FemMesh::writeABAQUS(const std::string& Filename, // // hexa20 FreeCAD --> C3D20, C3D20R CalculiX // N6, N7, N8, N5, N2, N3, N4, N1, N14, N15, N16, N13, N10, N11, N12, N9, N18, N19, N20, N17 - std::vector hexa20 = boost::assign::list_of(5)(6)(7)(4)(1)(2)(3)(0)(13)(14)(15)(12)(9)(10)( - 11)(8)(17)(18)(19)(16); + std::vector hexa20 + = boost::assign::list_of(5)(6)(7)(4)(1)(2)(3)(0)(13)(14)(15)(12)(9)(10)(11)(8)(17)(18)(19)(16); // // penta6 FreeCAD --> C3D6, F3D6 CalculiX // N5, N6, N4, N2, N3, N1 @@ -1869,8 +1900,7 @@ void FemMesh::writeABAQUS(const std::string& Filename, // // penta15 FreeCAD --> C3D15 CalculiX // N5, N6, N4, N2, N3, N1, N11, N12, N10, N8, N9, N7, N14, N15, N13 - std::vector penta15 = - boost::assign::list_of(4)(5)(3)(1)(2)(0)(10)(11)(9)(7)(8)(6)(13)(14)(12); + std::vector penta15 = boost::assign::list_of(4)(5)(3)(1)(2)(0)(10)(11)(9)(7)(8)(6)(13)(14)(12); elemOrderMap.insert(std::make_pair(variants["Tetra4"], tetra4)); volTypeMap.insert(std::make_pair(tetra4.size(), variants["Tetra4"])); @@ -2029,8 +2059,7 @@ void FemMesh::writeABAQUS(const std::string& Filename, default: anABAQUS_Output << "** Problem on writing" << std::endl; anABAQUS_Output.close(); - throw std::runtime_error( - "Unknown ABAQUS element choice parameter, [0|1|2] are allowed."); + throw std::runtime_error("Unknown ABAQUS element choice parameter, [0|1|2] are allowed."); } // write nodes @@ -2273,10 +2302,12 @@ void FemMesh::write(const char* FileName) const } else if (File.hasExtension("med")) { Base::Console().log("FEM mesh object will be exported to med format.\n"); - myMesh->ExportMED(File.filePath().c_str(), - File.fileNamePure().c_str(), - false, - 2); // 2 means MED_V2_2 version! + myMesh->ExportMED( + File.filePath().c_str(), + File.fileNamePure().c_str(), + false, + 2 + ); // 2 means MED_V2_2 version! } else if (File.hasExtension("stl")) { Base::Console().log("FEM mesh object will be exported to stl format.\n"); @@ -2485,10 +2516,12 @@ Data::Segment* FemMesh::getSubElement(const char* /*Type*/, unsigned long /*n*/) return nullptr; } -void FemMesh::getPoints(std::vector& Points, - std::vector& /*Normals*/, - double /*Accuracy*/, - uint16_t /*flags*/) const +void FemMesh::getPoints( + std::vector& Points, + std::vector& /*Normals*/, + double /*Accuracy*/, + uint16_t /*flags*/ +) const { const SMESHDS_Mesh* data = getSMesh()->GetMeshDS(); std::vector nodes; @@ -2562,8 +2595,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 5,9,8,7 a = v8 - v4; b = v7 - v4; @@ -2571,8 +2604,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 5,2,9,7 a = v1 - v4; b = v8 - v4; @@ -2580,8 +2613,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 2,6,9,7 a = v5 - v1; b = v8 - v1; @@ -2589,8 +2622,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 9,6,10,7 a = v5 - v8; b = v9 - v8; @@ -2598,8 +2631,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 6,3,10,7 a = v2 - v5; b = v9 - v5; @@ -2607,8 +2640,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 8,9,10,7 a = v8 - v7; b = v9 - v7; @@ -2616,8 +2649,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); // 8,9,10,4 a = v8 - v7; b = v9 - v7; @@ -2625,8 +2658,8 @@ Base::Quantity FemMesh::getVolume() const a_b_product.x = a.y * b.z - b.y * a.z; a_b_product.y = a.z * b.x - b.z * a.x; a_b_product.z = a.x * b.y - b.x * a.y; - volume += - 1.0 / 6.0 * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); + volume += 1.0 / 6.0 + * fabs((a_b_product.x * c.x) + (a_b_product.y * c.y) + (a_b_product.z * c.z)); } return Base::Quantity(volume, Unit::Volume); @@ -2657,8 +2690,10 @@ int FemMesh::addGroup(const std::string TypeString, const std::string Name, cons } } if (!typeStringValid) { - throw std::runtime_error("AddGroup: Invalid type string! Allowed: All, Node, Edge, Face, " - "Volume, 0DElement, Ball"); + throw std::runtime_error( + "AddGroup: Invalid type string! Allowed: All, Node, Edge, Face, " + "Volume, 0DElement, Ball" + ); } // add group to mesh SMESH_Group* group = this->getSMesh()->AddGroup(mapping[TypeString], Name.c_str(), aId); diff --git a/src/Mod/Fem/App/FemMesh.h b/src/Mod/Fem/App/FemMesh.h index 3edc6a1a17..ee1cab6751 100644 --- a/src/Mod/Fem/App/FemMesh.h +++ b/src/Mod/Fem/App/FemMesh.h @@ -118,10 +118,12 @@ public: /// get the subelement by type and number Data::Segment* getSubElement(const char* Type, unsigned long) const override; /** Get points from object with given accuracy */ - void getPoints(std::vector& Points, - std::vector& Normals, - double Accuracy, - uint16_t flags = 0) const override; + void getPoints( + std::vector& Points, + std::vector& Normals, + double Accuracy, + uint16_t flags = 0 + ) const override; //@} /** @name search and retrieval */ @@ -206,12 +208,14 @@ public: /// import from files void read(const char* FileName); void write(const char* FileName) const; - void writeABAQUS(const std::string& Filename, - int elemParam, - bool groupParam, - ABAQUS_VolumeVariant volVariant = ABAQUS_VolumeVariant::Standard, - ABAQUS_FaceVariant faceVariant = ABAQUS_FaceVariant::Shell, - ABAQUS_EdgeVariant edgeVariant = ABAQUS_EdgeVariant::Beam) const; + void writeABAQUS( + const std::string& Filename, + int elemParam, + bool groupParam, + ABAQUS_VolumeVariant volVariant = ABAQUS_VolumeVariant::Standard, + ABAQUS_FaceVariant faceVariant = ABAQUS_FaceVariant::Shell, + ABAQUS_EdgeVariant edgeVariant = ABAQUS_EdgeVariant::Beam + ) const; void writeVTK(const std::string& FileName, bool highest = true) const; void writeZ88(const std::string& FileName) const; diff --git a/src/Mod/Fem/App/FemMeshPyImp.cpp b/src/Mod/Fem/App/FemMeshPyImp.cpp index bfb923ebc7..b46a916186 100644 --- a/src/Mod/Fem/App/FemMeshPyImp.cpp +++ b/src/Mod/Fem/App/FemMeshPyImp.cpp @@ -88,9 +88,11 @@ int FemMeshPy::PyInit(PyObject* args, PyObject* /*kwd*/) getFemMeshPtr()->operator=(*static_cast(pcObj)->getFemMeshPtr()); } else { - PyErr_Format(PyExc_TypeError, - "Cannot create a FemMesh out of a '%s'", - pcObj->ob_type->tp_name); + PyErr_Format( + PyExc_TypeError, + "Cannot create a FemMesh out of a '%s'", + pcObj->ob_type->tp_name + ); return -1; } } @@ -232,10 +234,12 @@ PyObject* FemMeshPy::addNode(PyObject* args) return nullptr; } } - PyErr_SetString(PyExc_TypeError, - "addNode() accepts:\n" - "-- addNode(x,y,z)\n" - "-- addNode(x,y,z,ElemId)\n"); + PyErr_SetString( + PyExc_TypeError, + "addNode() accepts:\n" + "-- addNode(x,y,z)\n" + "-- addNode(x,y,z,ElemId)\n" + ); return nullptr; } @@ -295,8 +299,8 @@ PyObject* FemMeshPy::addEdge(PyObject* args) } break; default: - throw std::runtime_error( - "Unknown node count, [2|3] are allowed"); // unknown edge type + throw std::runtime_error("Unknown node count, [2|3] are allowed"); // unknown + // edge type } } else { @@ -314,16 +318,18 @@ PyObject* FemMeshPy::addEdge(PyObject* args) } break; default: - throw std::runtime_error( - "Unknown node count, [2|3] are allowed"); // unknown edge type + throw std::runtime_error("Unknown node count, [2|3] are allowed"); // unknown + // edge type } } return Py::new_reference_to(Py::Long(edge->GetID())); } - PyErr_SetString(PyExc_TypeError, - "addEdge accepts:\n" - "-- int,int\n" - "-- [2|3],[int]\n"); + PyErr_SetString( + PyExc_TypeError, + "addEdge accepts:\n" + "-- int,int\n" + "-- [2|3],[int]\n" + ); return nullptr; } @@ -375,8 +381,7 @@ PyObject* FemMeshPy::addFace(PyObject* args) case 3: face = meshDS->AddFaceWithID(Nodes[0], Nodes[1], Nodes[2], ElementId); if (!face) { - throw std::runtime_error( - "Failed to add triangular face with given ElementId"); + throw std::runtime_error("Failed to add triangular face with given ElementId"); } break; case 4: @@ -386,34 +391,39 @@ PyObject* FemMeshPy::addFace(PyObject* args) } break; case 6: - face = meshDS->AddFaceWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - ElementId); + face = meshDS->AddFaceWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + ElementId + ); if (!face) { throw std::runtime_error("Failed to add face with given ElementId"); } break; case 8: - face = meshDS->AddFaceWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - ElementId); + face = meshDS->AddFaceWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + ElementId + ); if (!face) { throw std::runtime_error("Failed to add face with given ElementId"); } break; default: throw std::runtime_error( - "Unknown node count, [3|4|6|8] are allowed"); // unknown face type + "Unknown node count, [3|4|6|8] are allowed" + ); // unknown face type } } else { @@ -431,37 +441,41 @@ PyObject* FemMeshPy::addFace(PyObject* args) } break; case 6: - face = - meshDS->AddFace(Nodes[0], Nodes[1], Nodes[2], Nodes[3], Nodes[4], Nodes[5]); + face = meshDS->AddFace(Nodes[0], Nodes[1], Nodes[2], Nodes[3], Nodes[4], Nodes[5]); if (!face) { throw std::runtime_error("Failed to add face"); } break; case 8: - face = meshDS->AddFace(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7]); + face = meshDS->AddFace( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7] + ); if (!face) { throw std::runtime_error("Failed to add face"); } break; default: throw std::runtime_error( - "Unknown node count, [4|5|6|8] are allowed"); // unknown face type + "Unknown node count, [4|5|6|8] are allowed" + ); // unknown face type } } return Py::new_reference_to(Py::Long(face->GetID())); } - PyErr_SetString(PyExc_TypeError, - "addFace accepts:\n" - "-- int,int,int\n" - "-- [3|4|6|8 int],[int]\n"); + PyErr_SetString( + PyExc_TypeError, + "addFace accepts:\n" + "-- int,int,int\n" + "-- [3|4|6|8 int],[int]\n" + ); return nullptr; } @@ -540,139 +554,142 @@ PyObject* FemMeshPy::addVolume(PyObject* args) if (ElementId != -1) { switch (Nodes.size()) { case 4: - vol = - meshDS->AddVolumeWithID(Nodes[0], Nodes[1], Nodes[2], Nodes[3], ElementId); + vol = meshDS->AddVolumeWithID(Nodes[0], Nodes[1], Nodes[2], Nodes[3], ElementId); if (!vol) { throw std::runtime_error("Failed to add Tet4 volume with given ElementId"); } break; case 5: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - ElementId); + vol = meshDS->AddVolumeWithID(Nodes[0], Nodes[1], Nodes[2], Nodes[3], Nodes[4], ElementId); if (!vol) { throw std::runtime_error("Failed to add Pyra5 volume with given ElementId"); } break; case 6: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - ElementId); + vol = meshDS->AddVolumeWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + ElementId + ); if (!vol) { - throw std::runtime_error( - "Failed to add Penta6 volume with given ElementId"); + throw std::runtime_error("Failed to add Penta6 volume with given ElementId"); } break; case 8: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - ElementId); + vol = meshDS->AddVolumeWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + ElementId + ); if (!vol) { throw std::runtime_error("Failed to add Hexa8 volume with given ElementId"); } break; case 10: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - ElementId); + vol = meshDS->AddVolumeWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + ElementId + ); if (!vol) { throw std::runtime_error("Failed to add Tet10 volume with given ElementId"); } break; case 13: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - Nodes[10], - Nodes[11], - Nodes[12], - ElementId); + vol = meshDS->AddVolumeWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + Nodes[10], + Nodes[11], + Nodes[12], + ElementId + ); if (!vol) { - throw std::runtime_error( - "Failed to add Pyra13 volume with given ElementId"); + throw std::runtime_error("Failed to add Pyra13 volume with given ElementId"); } break; case 15: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - Nodes[10], - Nodes[11], - Nodes[12], - Nodes[13], - Nodes[14], - ElementId); + vol = meshDS->AddVolumeWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + Nodes[10], + Nodes[11], + Nodes[12], + Nodes[13], + Nodes[14], + ElementId + ); if (!vol) { - throw std::runtime_error( - "Failed to add Penta15 volume with given ElementId"); + throw std::runtime_error("Failed to add Penta15 volume with given ElementId"); } break; case 20: - vol = meshDS->AddVolumeWithID(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - Nodes[10], - Nodes[11], - Nodes[12], - Nodes[13], - Nodes[14], - Nodes[15], - Nodes[16], - Nodes[17], - Nodes[18], - Nodes[19], - ElementId); + vol = meshDS->AddVolumeWithID( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + Nodes[10], + Nodes[11], + Nodes[12], + Nodes[13], + Nodes[14], + Nodes[15], + Nodes[16], + Nodes[17], + Nodes[18], + Nodes[19], + ElementId + ); if (!vol) { - throw std::runtime_error( - "Failed to add Hexa20 volume with given ElementId"); + throw std::runtime_error("Failed to add Hexa20 volume with given ElementId"); } break; default: throw std::runtime_error( - "Unknown node count, [4|5|6|8|10|13|15|20] are allowed"); // unknown volume - // type + "Unknown node count, [4|5|6|8|10|13|15|20] are allowed" + ); // unknown volume + // type } } else { @@ -690,120 +707,128 @@ PyObject* FemMeshPy::addVolume(PyObject* args) } break; case 6: - vol = meshDS->AddVolume(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5]); + vol = meshDS->AddVolume(Nodes[0], Nodes[1], Nodes[2], Nodes[3], Nodes[4], Nodes[5]); if (!vol) { throw std::runtime_error("Failed to add Penta6 volume"); } break; case 8: - vol = meshDS->AddVolume(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7]); + vol = meshDS->AddVolume( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7] + ); if (!vol) { throw std::runtime_error("Failed to add Hexa8 volume"); } break; case 10: - vol = meshDS->AddVolume(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9]); + vol = meshDS->AddVolume( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9] + ); if (!vol) { throw std::runtime_error("Failed to add Tet10 volume"); } break; case 13: - vol = meshDS->AddVolume(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - Nodes[10], - Nodes[11], - Nodes[12]); + vol = meshDS->AddVolume( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + Nodes[10], + Nodes[11], + Nodes[12] + ); if (!vol) { throw std::runtime_error("Failed to add Pyra13 volume"); } break; case 15: - vol = meshDS->AddVolume(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - Nodes[10], - Nodes[11], - Nodes[12], - Nodes[13], - Nodes[14]); + vol = meshDS->AddVolume( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + Nodes[10], + Nodes[11], + Nodes[12], + Nodes[13], + Nodes[14] + ); if (!vol) { throw std::runtime_error("Failed to add Penta15 volume"); } break; case 20: - vol = meshDS->AddVolume(Nodes[0], - Nodes[1], - Nodes[2], - Nodes[3], - Nodes[4], - Nodes[5], - Nodes[6], - Nodes[7], - Nodes[8], - Nodes[9], - Nodes[10], - Nodes[11], - Nodes[12], - Nodes[13], - Nodes[14], - Nodes[15], - Nodes[16], - Nodes[17], - Nodes[18], - Nodes[19]); + vol = meshDS->AddVolume( + Nodes[0], + Nodes[1], + Nodes[2], + Nodes[3], + Nodes[4], + Nodes[5], + Nodes[6], + Nodes[7], + Nodes[8], + Nodes[9], + Nodes[10], + Nodes[11], + Nodes[12], + Nodes[13], + Nodes[14], + Nodes[15], + Nodes[16], + Nodes[17], + Nodes[18], + Nodes[19] + ); if (!vol) { throw std::runtime_error("Failed to add Hexa20 volume"); } break; default: throw std::runtime_error( - "Unknown node count, [4|5|6|8|10|13|15|20] are allowed"); // unknown volume - // type + "Unknown node count, [4|5|6|8|10|13|15|20] are allowed" + ); // unknown volume + // type } } return Py::new_reference_to(Py::Long(vol->GetID())); } - PyErr_SetString(PyExc_TypeError, - "addVolume accepts:\n" - "-- int,int,int,int\n" - "-- [4|5|6|8|10|13|15|20 int],[int]\n"); + PyErr_SetString( + PyExc_TypeError, + "addVolume accepts:\n" + "-- int,int,int,int\n" + "-- [4|5|6|8|10|13|15|20 int],[int]\n" + ); return nullptr; } @@ -899,22 +924,26 @@ PyObject* FemMeshPy::addFaceList(PyObject* args) face = meshDS->AddFace(nodesElem[0], nodesElem[1], nodesElem[2], nodesElem[3]); break; case 6: - face = meshDS->AddFace(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5]); + face = meshDS->AddFace( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5] + ); break; case 8: - face = meshDS->AddFace(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5], - nodesElem[6], - nodesElem[7]); + face = meshDS->AddFace( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5], + nodesElem[6], + nodesElem[7] + ); break; default: PyErr_SetString(PyExc_TypeError, "Unknown node count, [3|4|6|8] are allowed"); @@ -968,99 +997,112 @@ PyObject* FemMeshPy::addVolumeList(PyObject* args) vol = meshDS->AddVolume(nodesElem[0], nodesElem[1], nodesElem[2], nodesElem[3]); break; case 5: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4] + ); break; case 6: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5] + ); break; case 8: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5], - nodesElem[6], - nodesElem[7]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5], + nodesElem[6], + nodesElem[7] + ); break; case 10: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5], - nodesElem[6], - nodesElem[7], - nodesElem[8], - nodesElem[9]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5], + nodesElem[6], + nodesElem[7], + nodesElem[8], + nodesElem[9] + ); break; case 13: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5], - nodesElem[6], - nodesElem[7], - nodesElem[8], - nodesElem[9], - nodesElem[10], - nodesElem[11], - nodesElem[12]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5], + nodesElem[6], + nodesElem[7], + nodesElem[8], + nodesElem[9], + nodesElem[10], + nodesElem[11], + nodesElem[12] + ); break; case 15: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5], - nodesElem[6], - nodesElem[7], - nodesElem[8], - nodesElem[9], - nodesElem[10], - nodesElem[11], - nodesElem[12], - nodesElem[13], - nodesElem[14]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5], + nodesElem[6], + nodesElem[7], + nodesElem[8], + nodesElem[9], + nodesElem[10], + nodesElem[11], + nodesElem[12], + nodesElem[13], + nodesElem[14] + ); break; case 20: - vol = meshDS->AddVolume(nodesElem[0], - nodesElem[1], - nodesElem[2], - nodesElem[3], - nodesElem[4], - nodesElem[5], - nodesElem[6], - nodesElem[7], - nodesElem[8], - nodesElem[9], - nodesElem[10], - nodesElem[11], - nodesElem[12], - nodesElem[13], - nodesElem[14], - nodesElem[15], - nodesElem[16], - nodesElem[17], - nodesElem[18], - nodesElem[19]); + vol = meshDS->AddVolume( + nodesElem[0], + nodesElem[1], + nodesElem[2], + nodesElem[3], + nodesElem[4], + nodesElem[5], + nodesElem[6], + nodesElem[7], + nodesElem[8], + nodesElem[9], + nodesElem[10], + nodesElem[11], + nodesElem[12], + nodesElem[13], + nodesElem[14], + nodesElem[15], + nodesElem[16], + nodesElem[17], + nodesElem[18], + nodesElem[19] + ); break; default: - PyErr_SetString(PyExc_TypeError, - "Unknown node count, [4|5|6|8|10|13|15|20] are allowed"); + PyErr_SetString(PyExc_TypeError, "Unknown node count, [4|5|6|8|10|13|15|20] are allowed"); return nullptr; } if (vol) { @@ -1132,7 +1174,8 @@ std::map volVariantPyMap = { {"reduced", ABAQUS_VolumeVariant::Reduced}, {"incompatible", ABAQUS_VolumeVariant::Incompatible}, {"modified", ABAQUS_VolumeVariant::Modified}, - {"fluid", ABAQUS_VolumeVariant::Fluid}}; + {"fluid", ABAQUS_VolumeVariant::Fluid} +}; std::map faceVariantPyMap = { {"shell", ABAQUS_FaceVariant::Shell}, @@ -1144,13 +1187,15 @@ std::map faceVariantPyMap = { {"strain", ABAQUS_FaceVariant::Strain}, {"strain reduced", ABAQUS_FaceVariant::Strain_Reduced}, {"axisymmetric", ABAQUS_FaceVariant::Axisymmetric}, - {"axisymmetric reduced", ABAQUS_FaceVariant::Axisymmetric_Reduced}}; + {"axisymmetric reduced", ABAQUS_FaceVariant::Axisymmetric_Reduced} +}; std::map edgeVariantPyMap = { {"beam", ABAQUS_EdgeVariant::Beam}, {"beam reduced", ABAQUS_EdgeVariant::Beam_Reduced}, {"truss", ABAQUS_EdgeVariant::Truss}, - {"network", ABAQUS_EdgeVariant::Network}}; + {"network", ABAQUS_EdgeVariant::Network} +}; } // namespace @@ -1163,26 +1208,30 @@ PyObject* FemMeshPy::writeABAQUS(PyObject* args, PyObject* kwd) const const char* faceVariant = "shell"; const char* edgeVariant = "beam"; - const std::array kwlist {"fileName", - "elemParam", - "groupParam", - "volVariant", - "faceVariant", - "edgeVariant", - nullptr}; + const std::array kwlist { + "fileName", + "elemParam", + "groupParam", + "volVariant", + "faceVariant", + "edgeVariant", + nullptr + }; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwd, - "etiO!|sss", - kwlist, - "utf-8", - &Name, - &elemParam, - &PyBool_Type, - &groupParam, - &volVariant, - &faceVariant, - &edgeVariant)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwd, + "etiO!|sss", + kwlist, + "utf-8", + &Name, + &elemParam, + &PyBool_Type, + &groupParam, + &volVariant, + &faceVariant, + &edgeVariant + )) { return nullptr; } @@ -1200,12 +1249,14 @@ PyObject* FemMeshPy::writeABAQUS(PyObject* args, PyObject* kwd) const } try { - getFemMeshPtr()->writeABAQUS(EncodedName.c_str(), - elemParam, - grpParam, - itVol->second, - itFace->second, - itEdge->second); + getFemMeshPtr()->writeABAQUS( + EncodedName.c_str(), + elemParam, + grpParam, + itVol->second, + itFace->second, + itEdge->second + ); } catch (const std::exception& e) { PyErr_SetString(Base::PyExc_FC_GeneralError, e.what()); @@ -1236,8 +1287,7 @@ PyObject* FemMeshPy::getFacesByFace(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Face is empty"); return nullptr; @@ -1268,8 +1318,7 @@ PyObject* FemMeshPy::getEdgesByEdge(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Edge is empty"); return nullptr; @@ -1299,8 +1348,7 @@ PyObject* FemMeshPy::getVolumesByFace(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Face is empty"); return nullptr; @@ -1335,8 +1383,7 @@ PyObject* FemMeshPy::getccxVolumesByFace(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Face is empty"); return nullptr; @@ -1346,8 +1393,7 @@ PyObject* FemMeshPy::getccxVolumesByFace(PyObject* args) const Py::List ret; std::map resultSet = getFemMeshPtr()->getccxVolumesByFace(fc); - for (std::map::const_iterator it = resultSet.begin(); it != resultSet.end(); - ++it) { + for (std::map::const_iterator it = resultSet.begin(); it != resultSet.end(); ++it) { Py::Tuple vol_face(2); vol_face.setItem(0, Py::Long(it->first)); vol_face.setItem(1, Py::Long(it->second)); @@ -1391,8 +1437,8 @@ PyObject* FemMeshPy::getNodesBySolid(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh + = static_cast(pW)->getTopoShapePtr()->getShape(); const TopoDS_Solid& fc = TopoDS::Solid(sh); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Solid is empty"); @@ -1420,8 +1466,7 @@ PyObject* FemMeshPy::getNodesByFace(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); const TopoDS_Face& fc = TopoDS::Face(sh); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Face is empty"); @@ -1449,8 +1494,7 @@ PyObject* FemMeshPy::getNodesByEdge(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); const TopoDS_Edge& fc = TopoDS::Edge(sh); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Edge is empty"); @@ -1478,8 +1522,8 @@ PyObject* FemMeshPy::getNodesByVertex(PyObject* args) const } try { - const TopoDS_Shape& sh = - static_cast(pW)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh + = static_cast(pW)->getTopoShapePtr()->getShape(); const TopoDS_Vertex& fc = TopoDS::Vertex(sh); if (sh.IsNull()) { PyErr_SetString(PyExc_ValueError, "Vertex is empty"); @@ -1745,10 +1789,9 @@ PyObject* FemMeshPy::getElementType(PyObject* args) const elemType = getFemMeshPtr()->getSMesh()->GetElementType(id, false); } - auto it = - std::find_if(vecTypeName.begin() + 1, vecTypeName.end(), [=](const pairStrElemType& x) { - return x.second == elemType; - }); + auto it = std::find_if(vecTypeName.begin() + 1, vecTypeName.end(), [=](const pairStrElemType& x) { + return x.second == elemType; + }); const char* typeStr = it != vecTypeName.end() ? it->first.c_str() : nullptr; if (!typeStr) { @@ -1777,8 +1820,9 @@ PyObject* FemMeshPy::getIdByElementType(PyObject* args) const SMDSAbs_ElementType elemType = it->second; std::set ids; - SMDS_ElemIteratorPtr aElemIter = - getFemMeshPtr()->getSMesh()->GetMeshDS()->elementsIterator(elemType); + SMDS_ElemIteratorPtr aElemIter = getFemMeshPtr()->getSMesh()->GetMeshDS()->elementsIterator( + elemType + ); while (aElemIter->more()) { const SMDS_MeshElement* aElem = aElemIter->next(); ids.insert(aElem->GetID()); diff --git a/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp b/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp index 96353d19d3..da36ffc6b8 100644 --- a/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp +++ b/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp @@ -27,8 +27,8 @@ #include #ifdef FCWithNetgen -#include -#include +# include +# include #endif #include @@ -44,8 +44,8 @@ using namespace App; PROPERTY_SOURCE(Fem::FemMeshShapeNetgenObject, Fem::FemMeshShapeBaseObject) -const char* FinenessEnums[] = - {"VeryCoarse", "Coarse", "Moderate", "Fine", "VeryFine", "UserDefined", nullptr}; +const char* FinenessEnums[] + = {"VeryCoarse", "Coarse", "Moderate", "Fine", "VeryFine", "UserDefined", nullptr}; FemMeshShapeNetgenObject::FemMeshShapeNetgenObject() { @@ -59,19 +59,22 @@ FemMeshShapeNetgenObject::FemMeshShapeNetgenObject() (0.3), "MeshParams", Prop_None, - " allows defining how much the linear dimensions of two adjacent cells can differ"); + " allows defining how much the linear dimensions of two adjacent cells can differ" + ); ADD_PROPERTY_TYPE( NbSegsPerEdge, (1), "MeshParams", Prop_None, - "allows defining the minimum number of mesh segments in which edges will be split"); + "allows defining the minimum number of mesh segments in which edges will be split" + ); ADD_PROPERTY_TYPE( NbSegsPerRadius, (2), "MeshParams", Prop_None, - "allows defining the minimum number of mesh segments in which radii will be split"); + "allows defining the minimum number of mesh segments in which radii will be split" + ); ADD_PROPERTY_TYPE(Optimize, (true), "MeshParams", Prop_None, "Optimize the resulting mesh"); } @@ -91,11 +94,11 @@ App::DocumentObjectExecReturn* FemMeshShapeNetgenObject::execute() TopoDS_Shape shape = feat->Shape.getValue(); NETGENPlugin_Mesher myNetGenMesher(newMesh.getSMesh(), shape, true); -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 NETGENPlugin_Hypothesis* tet = new NETGENPlugin_Hypothesis(0, newMesh.getGenerator()); -#else +# else NETGENPlugin_Hypothesis* tet = new NETGENPlugin_Hypothesis(0, 0, newMesh.getGenerator()); -#endif +# endif tet->SetMaxSize(MaxSize.getValue()); tet->SetMinSize(MinSize.getValue()); tet->SetSecondOrder(SecondOrder.getValue()); @@ -125,6 +128,7 @@ App::DocumentObjectExecReturn* FemMeshShapeNetgenObject::execute() #else return new App::DocumentObjectExecReturn( "The FEM module is built without NETGEN support. Meshing will not work!!!", - this); + this + ); #endif } diff --git a/src/Mod/Fem/App/FemMeshShapeObject.cpp b/src/Mod/Fem/App/FemMeshShapeObject.cpp index 511f2c2502..e6d219a92d 100644 --- a/src/Mod/Fem/App/FemMeshShapeObject.cpp +++ b/src/Mod/Fem/App/FemMeshShapeObject.cpp @@ -44,7 +44,8 @@ FemMeshShapeBaseObject::FemMeshShapeBaseObject() (nullptr), "FEM Mesh", Prop_None, - "Geometry object, the mesh is made from. The geometry object has to have a Shape."); + "Geometry object, the mesh is made from. The geometry object has to have a Shape." + ); Shape.setScope(LinkScope::Global); } diff --git a/src/Mod/Fem/App/FemPostBranchFilter.cpp b/src/Mod/Fem/App/FemPostBranchFilter.cpp index b969c5099a..bf49064837 100644 --- a/src/Mod/Fem/App/FemPostBranchFilter.cpp +++ b/src/Mod/Fem/App/FemPostBranchFilter.cpp @@ -36,13 +36,15 @@ FemPostBranchFilter::FemPostBranchFilter() { FemPostGroupExtension::initExtension(this); - ADD_PROPERTY_TYPE(Output, - (long(0)), - "Pipeline", - App::Prop_None, - "Selects what the output of the branch itself is.\n" - "In passthrough, the branch's output is equal to its input.\n" - "In append, all child filter outputs get appended as the branch's output"); + ADD_PROPERTY_TYPE( + Output, + (long(0)), + "Pipeline", + App::Prop_None, + "Selects what the output of the branch itself is.\n" + "In passthrough, the branch's output is equal to its input.\n" + "In append, all child filter outputs get appended as the branch's output" + ); Output.setEnums(OutputEnums); @@ -111,7 +113,8 @@ void FemPostBranchFilter::setupPipeline() } else { nextFilter->getFilterInput()->SetInputConnection( - filter->getFilterOutput()->GetOutputPort()); + filter->getFilterOutput()->GetOutputPort() + ); } } else if (Mode.getValue() == Fem::PostGroupMode::Parallel) { diff --git a/src/Mod/Fem/App/FemPostFilter.cpp b/src/Mod/Fem/App/FemPostFilter.cpp index a6fc88ed9c..3e7cf9f236 100644 --- a/src/Mod/Fem/App/FemPostFilter.cpp +++ b/src/Mod/Fem/App/FemPostFilter.cpp @@ -47,11 +47,7 @@ PROPERTY_SOURCE(Fem::FemPostFilter, Fem::FemPostObject) FemPostFilter::FemPostFilter() { - ADD_PROPERTY_TYPE(Frame, - ((long)0), - "Data", - App::Prop_ReadOnly, - "The step used to calculate the data"); + ADD_PROPERTY_TYPE(Frame, ((long)0), "Data", App::Prop_ReadOnly, "The step used to calculate the data"); // the default pipeline: just a passthrough // this is used to simplify the python filter handling, @@ -165,11 +161,13 @@ void FemPostFilter::onChanged(const App::Property* prop) // add transform to pipeline if (m_transform_location == TransformLocation::output) { m_transform_filter->SetInputConnection( - m_pipelines[m_activePipeline].target->GetOutputPort(0)); + m_pipelines[m_activePipeline].target->GetOutputPort(0) + ); } else { m_pipelines[m_activePipeline].source->SetInputConnection( - m_transform_filter->GetOutputPort(0)); + m_transform_filter->GetOutputPort(0) + ); } m_use_transform = true; pipelineChanged(); @@ -353,37 +351,49 @@ PROPERTY_SOURCE(Fem::FemPostDataAlongLineFilter, Fem::FemPostFilter) FemPostDataAlongLineFilter::FemPostDataAlongLineFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(Point1, - (Base::Vector3d(0.0, 0.0, 0.0)), - "DataAlongLine", - App::Prop_None, - "The point 1 used to define end point of line"); - ADD_PROPERTY_TYPE(Point2, - (Base::Vector3d(0.0, 0.0, 1.0)), - "DataAlongLine", - App::Prop_None, - "The point 2 used to define end point of line"); - ADD_PROPERTY_TYPE(Resolution, - (100), - "DataAlongLine", - App::Prop_None, - "The number of intervals between the 2 end points of line"); - ADD_PROPERTY_TYPE(XAxisData, - (0), - "DataAlongLine", - App::Prop_None, - "X axis data values used for plotting"); - ADD_PROPERTY_TYPE(YAxisData, - (0), - "DataAlongLine", - App::Prop_None, - "Y axis data values used for plotting"); + ADD_PROPERTY_TYPE( + Point1, + (Base::Vector3d(0.0, 0.0, 0.0)), + "DataAlongLine", + App::Prop_None, + "The point 1 used to define end point of line" + ); + ADD_PROPERTY_TYPE( + Point2, + (Base::Vector3d(0.0, 0.0, 1.0)), + "DataAlongLine", + App::Prop_None, + "The point 2 used to define end point of line" + ); + ADD_PROPERTY_TYPE( + Resolution, + (100), + "DataAlongLine", + App::Prop_None, + "The number of intervals between the 2 end points of line" + ); + ADD_PROPERTY_TYPE( + XAxisData, + (0), + "DataAlongLine", + App::Prop_None, + "X axis data values used for plotting" + ); + ADD_PROPERTY_TYPE( + YAxisData, + (0), + "DataAlongLine", + App::Prop_None, + "Y axis data values used for plotting" + ); ADD_PROPERTY_TYPE(PlotData, (""), "DataAlongLine", App::Prop_None, "Field used for plotting"); - ADD_PROPERTY_TYPE(PlotDataComponent, - ((long)0), - "DataAlongLine", - App::Prop_None, - "Field component used for plotting"); + ADD_PROPERTY_TYPE( + PlotDataComponent, + ((long)0), + "DataAlongLine", + App::Prop_None, + "Field component used for plotting" + ); PlotData.setStatus(App::Property::ReadOnly, true); PlotDataComponent.setStatus(App::Property::ReadOnly, true); @@ -428,9 +438,11 @@ DocumentObjectExecReturn* FemPostDataAlongLineFilter::execute() return Fem::FemPostFilter::execute(); } -void FemPostDataAlongLineFilter::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void FemPostDataAlongLineFilter::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) // transforms properties that had been changed { // property Point1 had the App::PropertyVector and was changed to App::PropertyVectorDistance @@ -551,11 +563,13 @@ PROPERTY_SOURCE(Fem::FemPostDataAtPointFilter, Fem::FemPostFilter) FemPostDataAtPointFilter::FemPostDataAtPointFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(Center, - (Base::Vector3d(0.0, 0.0, 0.0)), - "DataAtPoint", - App::Prop_None, - "Center of the point"); + ADD_PROPERTY_TYPE( + Center, + (Base::Vector3d(0.0, 0.0, 0.0)), + "DataAtPoint", + App::Prop_None, + "Center of the point" + ); ADD_PROPERTY_TYPE(PointData, (0), "DataAtPoint", App::Prop_None, "Point data values"); ADD_PROPERTY_TYPE(FieldName, (""), "DataAtPoint", App::Prop_None, "Field used for plotting"); ADD_PROPERTY_TYPE(Unit, (""), "DataAtPoint", App::Prop_None, "Unit used for the field"); @@ -664,18 +678,21 @@ PROPERTY_SOURCE(Fem::FemPostClipFilter, Fem::FemPostFilter) FemPostClipFilter::FemPostClipFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(Function, - (nullptr), - "Clip", - App::Prop_None, - "The function object which defines the clip regions"); + ADD_PROPERTY_TYPE( + Function, + (nullptr), + "Clip", + App::Prop_None, + "The function object which defines the clip regions" + ); ADD_PROPERTY_TYPE(InsideOut, (false), "Clip", App::Prop_None, "Invert the clip direction"); ADD_PROPERTY_TYPE( CutCells, (false), "Clip", App::Prop_None, - "Decides if cells are cut and interpolated or if the cells are kept as a whole"); + "Decides if cells are cut and interpolated or if the cells are kept as a whole" + ); auto sphere = vtkSmartPointer::New(); sphere->SetRadius(1e12); @@ -754,58 +771,66 @@ DocumentObjectExecReturn* FemPostClipFilter::execute() // *************************************************************************** // smoothing filter extension -const App::PropertyQuantityConstraint::Constraints FemPostSmoothFilterExtension::angleRange = { - 0.0, - 180.0, - 1.0}; -const App::PropertyIntegerConstraint::Constraints FemPostSmoothFilterExtension::iterationRange = { - 0, - VTK_INT_MAX, - 1}; -const App::PropertyFloatConstraint::Constraints FemPostSmoothFilterExtension::relaxationRange = { - 0, - 1.0, - 0.01}; +const App::PropertyQuantityConstraint::Constraints FemPostSmoothFilterExtension::angleRange + = {0.0, 180.0, 1.0}; +const App::PropertyIntegerConstraint::Constraints FemPostSmoothFilterExtension::iterationRange + = {0, VTK_INT_MAX, 1}; +const App::PropertyFloatConstraint::Constraints FemPostSmoothFilterExtension::relaxationRange + = {0, 1.0, 0.01}; EXTENSION_PROPERTY_SOURCE(Fem::FemPostSmoothFilterExtension, App::DocumentObjectExtension) FemPostSmoothFilterExtension::FemPostSmoothFilterExtension() { - EXTENSION_ADD_PROPERTY_TYPE(BoundarySmoothing, - (true), - "Smoothing", - App::Prop_None, - "Smooth vertices on the boundary"); - EXTENSION_ADD_PROPERTY_TYPE(EdgeAngle, - (15), - "Smoothing", - App::Prop_None, - "Angle to control smoothing along edges"); - EXTENSION_ADD_PROPERTY_TYPE(EnableSmoothing, - (false), - "Smoothing", - App::Prop_None, - "Enable Laplacian smoothing"); - EXTENSION_ADD_PROPERTY_TYPE(FeatureAngle, - (45), - "Smoothing", - App::Prop_None, - "Angle for sharp edge identification"); - EXTENSION_ADD_PROPERTY_TYPE(EdgeSmoothing, - (false), - "Smoothing", - App::Prop_None, - "Smooth align sharp interior edges"); - EXTENSION_ADD_PROPERTY_TYPE(RelaxationFactor, - (0.05), - "Smoothing", - App::Prop_None, - "Factor to control vertex displacement"); - EXTENSION_ADD_PROPERTY_TYPE(Iterations, - (20), - "Smoothing", - App::Prop_None, - "Number of smoothing iterations"); + EXTENSION_ADD_PROPERTY_TYPE( + BoundarySmoothing, + (true), + "Smoothing", + App::Prop_None, + "Smooth vertices on the boundary" + ); + EXTENSION_ADD_PROPERTY_TYPE( + EdgeAngle, + (15), + "Smoothing", + App::Prop_None, + "Angle to control smoothing along edges" + ); + EXTENSION_ADD_PROPERTY_TYPE( + EnableSmoothing, + (false), + "Smoothing", + App::Prop_None, + "Enable Laplacian smoothing" + ); + EXTENSION_ADD_PROPERTY_TYPE( + FeatureAngle, + (45), + "Smoothing", + App::Prop_None, + "Angle for sharp edge identification" + ); + EXTENSION_ADD_PROPERTY_TYPE( + EdgeSmoothing, + (false), + "Smoothing", + App::Prop_None, + "Smooth align sharp interior edges" + ); + EXTENSION_ADD_PROPERTY_TYPE( + RelaxationFactor, + (0.05), + "Smoothing", + App::Prop_None, + "Factor to control vertex displacement" + ); + EXTENSION_ADD_PROPERTY_TYPE( + Iterations, + (20), + "Smoothing", + App::Prop_None, + "Number of smoothing iterations" + ); EdgeAngle.setConstraints(&angleRange); FeatureAngle.setConstraints(&angleRange); @@ -859,16 +884,8 @@ FemPostContoursFilter::FemPostContoursFilter() { ADD_PROPERTY_TYPE(NumberOfContours, (10), "Contours", App::Prop_None, "The number of contours"); ADD_PROPERTY_TYPE(Field, (long(0)), "Clip", App::Prop_None, "The field used to clip"); - ADD_PROPERTY_TYPE(VectorMode, - ((long)0), - "Contours", - App::Prop_None, - "Select what vector field"); - ADD_PROPERTY_TYPE(NoColor, - (false), - "Contours", - PropertyType(Prop_Hidden), - "Don't color the contours"); + ADD_PROPERTY_TYPE(VectorMode, ((long)0), "Contours", App::Prop_None, "Select what vector field"); + ADD_PROPERTY_TYPE(NoColor, (false), "Contours", PropertyType(Prop_Hidden), "Don't color the contours"); m_contourConstraints.LowerBound = 1; m_contourConstraints.UpperBound = 1000; @@ -930,11 +947,13 @@ void FemPostContoursFilter::onChanged(const Property* prop) } if (pdata->GetNumberOfComponents() == 1) { // if we have a scalar, we can directly use the array - m_contours->SetInputArrayToProcess(0, - 0, - 0, - vtkDataObject::FIELD_ASSOCIATION_POINTS, - Field.getValueAsString()); + m_contours->SetInputArrayToProcess( + 0, + 0, + 0, + vtkDataObject::FIELD_ASSOCIATION_POINTS, + Field.getValueAsString() + ); pdata->GetRange(p); recalculateContours(p[0], p[1]); } @@ -961,9 +980,7 @@ void FemPostContoursFilter::onChanged(const Property* prop) if (component >= 0) { for (vtkIdType tupleIdx = 0; tupleIdx < numTuples; ++tupleIdx) { - componentArray->SetComponent(tupleIdx, - 0, - pdata->GetComponent(tupleIdx, component)); + componentArray->SetComponent(tupleIdx, 0, pdata->GetComponent(tupleIdx, component)); } } else { @@ -974,7 +991,9 @@ void FemPostContoursFilter::onChanged(const Property* prop) std::sqrt( pdata->GetComponent(tupleIdx, 0) * pdata->GetComponent(tupleIdx, 0) + pdata->GetComponent(tupleIdx, 1) * pdata->GetComponent(tupleIdx, 1) - + pdata->GetComponent(tupleIdx, 2) * pdata->GetComponent(tupleIdx, 2))); + + pdata->GetComponent(tupleIdx, 2) * pdata->GetComponent(tupleIdx, 2) + ) + ); } } // name the array @@ -983,11 +1002,13 @@ void FemPostContoursFilter::onChanged(const Property* prop) // add the array as new field and use it for the contour filter dset->GetPointData()->AddArray(componentArray); - m_contours->SetInputArrayToProcess(0, - 0, - 0, - vtkDataObject::FIELD_ASSOCIATION_POINTS, - contourFieldName.c_str()); + m_contours->SetInputArrayToProcess( + 0, + 0, + 0, + vtkDataObject::FIELD_ASSOCIATION_POINTS, + contourFieldName.c_str() + ); componentArray->GetRange(p); recalculateContours(p[0], p[1]); if (prop == &Data) { @@ -1142,11 +1163,13 @@ PROPERTY_SOURCE(Fem::FemPostCutFilter, Fem::FemPostFilter) FemPostCutFilter::FemPostCutFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(Function, - (nullptr), - "Cut", - App::Prop_None, - "The function object which defines the cut function"); + ADD_PROPERTY_TYPE( + Function, + (nullptr), + "Cut", + App::Prop_None, + "The function object which defines the cut function" + ); auto sphere = vtkSmartPointer::New(); sphere->SetRadius(1e12); @@ -1206,11 +1229,7 @@ FemPostScalarClipFilter::FemPostScalarClipFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(Value, - (0), - "Clip", - App::Prop_None, - "The scalar value used to clip the selected field"); + ADD_PROPERTY_TYPE(Value, (0), "Clip", App::Prop_None, "The scalar value used to clip the selected field"); ADD_PROPERTY_TYPE(Scalars, (long(0)), "Clip", App::Prop_None, "The field used to clip"); ADD_PROPERTY_TYPE(InsideOut, (false), "Clip", App::Prop_None, "Invert the clip direction"); @@ -1259,11 +1278,13 @@ void FemPostScalarClipFilter::onChanged(const Property* prop) m_clipper->SetInsideOut(InsideOut.getValue()); } else if (prop == &Scalars && (Scalars.isValid())) { - m_clipper->SetInputArrayToProcess(0, - 0, - 0, - vtkDataObject::FIELD_ASSOCIATION_POINTS, - Scalars.getValueAsString()); + m_clipper->SetInputArrayToProcess( + 0, + 0, + 0, + vtkDataObject::FIELD_ASSOCIATION_POINTS, + Scalars.getValueAsString() + ); setConstraintForField(); } @@ -1314,16 +1335,14 @@ PROPERTY_SOURCE(Fem::FemPostWarpVectorFilter, Fem::FemPostFilter) FemPostWarpVectorFilter::FemPostWarpVectorFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(Factor, - (0), - "Warp", - App::Prop_None, - "The factor by which the vector is added to the node positions"); - ADD_PROPERTY_TYPE(Vector, - (long(0)), - "Warp", - App::Prop_None, - "The field added to the node position"); + ADD_PROPERTY_TYPE( + Factor, + (0), + "Warp", + App::Prop_None, + "The factor by which the vector is added to the node positions" + ); + ADD_PROPERTY_TYPE(Vector, (long(0)), "Warp", App::Prop_None, "The field added to the node position"); FilterPipeline warp; m_warp = vtkSmartPointer::New(); @@ -1367,11 +1386,13 @@ void FemPostWarpVectorFilter::onChanged(const Property* prop) m_warp->SetScaleFactor(1000 * Factor.getValue()); } else if (prop == &Vector && Vector.isValid()) { - m_warp->SetInputArrayToProcess(0, - 0, - 0, - vtkDataObject::FIELD_ASSOCIATION_POINTS, - Vector.getValueAsString()); + m_warp->SetInputArrayToProcess( + 0, + 0, + 0, + vtkDataObject::FIELD_ASSOCIATION_POINTS, + Vector.getValueAsString() + ); } Fem::FemPostFilter::onChanged(prop); @@ -1395,26 +1416,22 @@ PROPERTY_SOURCE(Fem::FemPostCalculatorFilter, Fem::FemPostFilter) FemPostCalculatorFilter::FemPostCalculatorFilter() : FemPostFilter() { - ADD_PROPERTY_TYPE(FieldName, - ("Calculator"), - "Calculator", - App::Prop_None, - "Name of the calculated field"); - ADD_PROPERTY_TYPE(Function, - (""), - "Calculator", - App::Prop_None, - "Expression of the unction to evaluate"); - ADD_PROPERTY_TYPE(ReplacementValue, - (0.0f), - "Calculator", - App::Prop_None, - "Value used to replace invalid operations"); - ADD_PROPERTY_TYPE(ReplaceInvalid, - (false), - "Calculator", - App::Prop_None, - "Replace invalid values"); + ADD_PROPERTY_TYPE( + FieldName, + ("Calculator"), + "Calculator", + App::Prop_None, + "Name of the calculated field" + ); + ADD_PROPERTY_TYPE(Function, (""), "Calculator", App::Prop_None, "Expression of the unction to evaluate"); + ADD_PROPERTY_TYPE( + ReplacementValue, + (0.0f), + "Calculator", + App::Prop_None, + "Value used to replace invalid operations" + ); + ADD_PROPERTY_TYPE(ReplaceInvalid, (false), "Calculator", App::Prop_None, "Replace invalid values"); FilterPipeline calculator; m_calculator = vtkSmartPointer::New(); @@ -1515,9 +1532,10 @@ const std::vector FemPostCalculatorFilter::getScalarVariables() #if (VTK_MAJOR_VERSION >= 9) && (VTK_MINOR_VERSION > 0) std::vector scalars = m_calculator->GetScalarVariableNames(); #else - std::vector scalars(m_calculator->GetScalarVariableNames(), - m_calculator->GetScalarVariableNames() - + m_calculator->GetNumberOfScalarArrays()); + std::vector scalars( + m_calculator->GetScalarVariableNames(), + m_calculator->GetScalarVariableNames() + m_calculator->GetNumberOfScalarArrays() + ); #endif scalars.insert(scalars.begin(), {"coordsX", "coordsY", "coordsZ"}); @@ -1529,9 +1547,10 @@ const std::vector FemPostCalculatorFilter::getVectorVariables() #if (VTK_MAJOR_VERSION >= 9) && (VTK_MINOR_VERSION > 0) std::vector vectors = m_calculator->GetVectorVariableNames(); #else - std::vector vectors(m_calculator->GetVectorVariableNames(), - m_calculator->GetVectorVariableNames() - + m_calculator->GetNumberOfVectorArrays()); + std::vector vectors( + m_calculator->GetVectorVariableNames(), + m_calculator->GetVectorVariableNames() + m_calculator->GetNumberOfVectorArrays() + ); #endif vectors.insert(vectors.begin(), "coords"); diff --git a/src/Mod/Fem/App/FemPostFilter.h b/src/Mod/Fem/App/FemPostFilter.h index 9487ba54ba..2c6be7d745 100644 --- a/src/Mod/Fem/App/FemPostFilter.h +++ b/src/Mod/Fem/App/FemPostFilter.h @@ -177,9 +177,11 @@ public: protected: App::DocumentObjectExecReturn* execute() override; void onChanged(const App::Property* prop) override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; private: vtkSmartPointer m_line; diff --git a/src/Mod/Fem/App/FemPostFilterPyImp.cpp b/src/Mod/Fem/App/FemPostFilterPyImp.cpp index 7cac967a01..e8f91f63ca 100644 --- a/src/Mod/Fem/App/FemPostFilterPyImp.cpp +++ b/src/Mod/Fem/App/FemPostFilterPyImp.cpp @@ -33,9 +33,9 @@ // clang-format on #ifdef FC_USE_VTK_PYTHON -#include -#include -#include +# include +# include +# include #endif // BUILD_FEM_VTK using namespace Fem; @@ -136,8 +136,7 @@ PyObject* FemPostFilterPy::getInputData(PyObject* args) copy = vtkPolyData::New(); break; default: - PyErr_SetString(PyExc_TypeError, - "cannot return datatype object; not unstructured grid"); + PyErr_SetString(PyExc_TypeError, "cannot return datatype object; not unstructured grid"); return nullptr; } diff --git a/src/Mod/Fem/App/FemPostFunction.cpp b/src/Mod/Fem/App/FemPostFunction.cpp index 87c0f20321..6b62d3bda0 100644 --- a/src/Mod/Fem/App/FemPostFunction.cpp +++ b/src/Mod/Fem/App/FemPostFunction.cpp @@ -50,9 +50,11 @@ void FemPostFunctionProvider::unsetupObject() } } -void FemPostFunctionProvider::handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) +void FemPostFunctionProvider::handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName +) { if (strcmp(propName, "Functions") == 0 && Base::Type::fromName(typeName) == App::PropertyLinkList::getClassTypeId()) { @@ -104,12 +106,14 @@ void FemPostBoxFunction::onChanged(const Property* prop) float l = Length.getValue(); float w = Width.getValue(); float h = Height.getValue(); - m_box->SetBounds(vec[0] - l / 2, - vec[0] + l / 2, - vec[1] - w / 2, - vec[1] + w / 2, - vec[2] - h / 2, - vec[2] + h / 2); + m_box->SetBounds( + vec[0] - l / 2, + vec[0] + l / 2, + vec[1] - w / 2, + vec[1] + w / 2, + vec[2] - h / 2, + vec[2] + h / 2 + ); } Fem::FemPostFunction::onChanged(prop); diff --git a/src/Mod/Fem/App/FemPostFunction.h b/src/Mod/Fem/App/FemPostFunction.h index 803713e347..e320f1ad35 100644 --- a/src/Mod/Fem/App/FemPostFunction.h +++ b/src/Mod/Fem/App/FemPostFunction.h @@ -92,9 +92,11 @@ protected: void unsetupObject() override; // update documents - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; }; // --------------------------------------------------------------------------- diff --git a/src/Mod/Fem/App/FemPostGroupExtension.cpp b/src/Mod/Fem/App/FemPostGroupExtension.cpp index ad3e3864cb..7204db2ee7 100644 --- a/src/Mod/Fem/App/FemPostGroupExtension.cpp +++ b/src/Mod/Fem/App/FemPostGroupExtension.cpp @@ -42,7 +42,8 @@ FemPostGroupExtension::FemPostGroupExtension() App::Prop_None, "Selects the pipeline data transition mode.\n" "In serial, every filter gets the output of the previous one as input.\n" - "In parallel, every filter gets the pipeline source as input.\n"); + "In parallel, every filter gets the pipeline source as input.\n" + ); Mode.setEnums(ModeEnums); } @@ -68,13 +69,15 @@ void FemPostGroupExtension::extensionOnChanged(const App::Property* p) // sort the group, so that non filter objects are always on top (in case any object // using this extension allows those) auto objs = Group.getValues(); - std::sort(objs.begin(), - objs.end(), - [](const App::DocumentObject* lhs, const App::DocumentObject* rhs) { - int l = lhs->isDerivedFrom() ? 0 : 1; - int r = rhs->isDerivedFrom() ? 0 : 1; - return r < l; - }); + std::sort( + objs.begin(), + objs.end(), + [](const App::DocumentObject* lhs, const App::DocumentObject* rhs) { + int l = lhs->isDerivedFrom() ? 0 : 1; + int r = rhs->isDerivedFrom() ? 0 : 1; + return r < l; + } + ); m_blockChange = true; Group.setValue(objs); m_blockChange = false; diff --git a/src/Mod/Fem/App/FemPostObjectPyImp.cpp b/src/Mod/Fem/App/FemPostObjectPyImp.cpp index 95b6e2482e..394a94c272 100644 --- a/src/Mod/Fem/App/FemPostObjectPyImp.cpp +++ b/src/Mod/Fem/App/FemPostObjectPyImp.cpp @@ -28,8 +28,8 @@ #include "FemPostObjectPy.cpp" #ifdef FC_USE_VTK_PYTHON -#include -#include +# include +# include #endif // BUILD_FEM_VTK using namespace Fem; diff --git a/src/Mod/Fem/App/FemPostPipeline.cpp b/src/Mod/Fem/App/FemPostPipeline.cpp index 4d3f118161..caf8d34b85 100644 --- a/src/Mod/Fem/App/FemPostPipeline.cpp +++ b/src/Mod/Fem/App/FemPostPipeline.cpp @@ -65,17 +65,15 @@ FemPostPipeline::FemPostPipeline() FemPostGroupExtension::initExtension(this); - ADD_PROPERTY_TYPE(Frame, - (long(0)), - "Pipeline", - App::Prop_None, - "The frame used to calculate the data in the pipeline processing (read only, " - "set via pipeline object)."); - ADD_PROPERTY_TYPE(MergeDuplicate, - (false), - "Pipeline", - App::Prop_None, - "Remove coindent elements."); + ADD_PROPERTY_TYPE( + Frame, + (long(0)), + "Pipeline", + App::Prop_None, + "The frame used to calculate the data in the pipeline processing (read only, " + "set via pipeline object)." + ); + ADD_PROPERTY_TYPE(MergeDuplicate, (false), "Pipeline", App::Prop_None, "Remove coindent elements."); // create our source algorithm m_source_algorithm = vtkSmartPointer::New(); @@ -182,8 +180,12 @@ vtkSmartPointer FemPostPipeline::readPVD(const Base::FileInfo& fi std::map values; std::vector files; while (strcmp(reader.localName(), "DataSet") == 0) { - values.emplace(std::make_pair(reader.getAttribute("timestep"), - reader.getAttribute("file"))); + values.emplace( + std::make_pair( + reader.getAttribute("timestep"), + reader.getAttribute("file") + ) + ); reader.readNextElement(); } @@ -219,10 +221,12 @@ void FemPostPipeline::read(Base::FileInfo File) Data.setValue(dataObjectFromFile(File)); } -void FemPostPipeline::read(std::vector& files, - std::vector& values, - Base::Unit unit, - std::string& frame_type) +void FemPostPipeline::read( + std::vector& files, + std::vector& values, + Base::Unit unit, + std::string& frame_type +) { if (files.size() != values.size()) { throw Base::ValueError("Result files and frame values have different length"); @@ -371,8 +375,8 @@ void FemPostPipeline::onChanged(const Property* prop) Frame.purgeTouched(); m_block_property = false; - std::vector::iterator it = - std::find(frame_values.begin(), frame_values.end(), val); + std::vector::iterator it + = std::find(frame_values.begin(), frame_values.end(), val); if (!val.empty() && it != frame_values.end()) { // frame stays the same m_block_property = true; @@ -428,18 +432,19 @@ void FemPostPipeline::onChanged(const Property* prop) // case an old document is loaded with "custom" mode, idx 2) if (Mode.getValue() == Fem::PostGroupMode::Parallel) { // parallel: all filters get out input - nextFilter->getFilterInput()->SetInputConnection( - m_transform_filter->GetOutputPort(0)); + nextFilter->getFilterInput()->SetInputConnection(m_transform_filter->GetOutputPort(0)); } else { // serial: the next filter gets the previous output, the first one gets our input if (!filter) { nextFilter->getFilterInput()->SetInputConnection( - m_transform_filter->GetOutputPort(0)); + m_transform_filter->GetOutputPort(0) + ); } else { nextFilter->getFilterInput()->SetInputConnection( - filter->getFilterOutput()->GetOutputPort()); + filter->getFilterOutput()->GetOutputPort() + ); } } @@ -580,10 +585,12 @@ void FemPostPipeline::load(FemResultObject* res) // set multiple result objects as frames for one pipeline // Notes: // 1. values vector must contain growing value, smallest first -void FemPostPipeline::load(std::vector& res, - std::vector& values, - Base::Unit unit, - std::string& frame_type) +void FemPostPipeline::load( + std::vector& res, + std::vector& values, + Base::Unit unit, + std::string& frame_type +) { if (res.size() != values.size()) { @@ -617,8 +624,7 @@ void FemPostPipeline::load(std::vector& res, } // first copy the mesh over - const FemMesh& mesh = - static_cast(res[i]->Mesh.getValue())->FemMesh.getValue(); + const FemMesh& mesh = static_cast(res[i]->Mesh.getValue())->FemMesh.getValue(); vtkSmartPointer grid = vtkSmartPointer::New(); FemVTKTools::exportVTKMesh(&mesh, grid); @@ -640,9 +646,11 @@ void FemPostPipeline::load(std::vector& res, Data.setValue(multiblock); } -void FemPostPipeline::handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) +void FemPostPipeline::handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName +) { if (strcmp(propName, "Filter") == 0 && Base::Type::fromName(typeName) == App::PropertyLinkList::getClassTypeId()) { diff --git a/src/Mod/Fem/App/FemPostPipeline.h b/src/Mod/Fem/App/FemPostPipeline.h index 08ec619aea..b8218f5fed 100644 --- a/src/Mod/Fem/App/FemPostPipeline.h +++ b/src/Mod/Fem/App/FemPostPipeline.h @@ -33,9 +33,9 @@ #include "VTKExtensions/vtkFemFrameSourceAlgorithm.h" #if VTK_VERSION_NUMBER < VTK_VERSION_CHECK(9, 3, 0) -#include "VTKExtensions/vtkCleanUnstructuredGrid.h" +# include "VTKExtensions/vtkCleanUnstructuredGrid.h" #else -#include +# include #endif #include @@ -68,19 +68,23 @@ public: // load data from files (single or as multiframe) static bool canRead(Base::FileInfo file); void read(Base::FileInfo file); - void read(std::vector& files, - std::vector& values, - Base::Unit unit, - std::string& frame_type); + void read( + std::vector& files, + std::vector& values, + Base::Unit unit, + std::string& frame_type + ); void scale(double s); void renameArrays(const std::map& names); // load from results void load(FemResultObject* res); - void load(std::vector& res, - std::vector& values, - Base::Unit unit, - std::string& frame_type); + void load( + std::vector& res, + std::vector& values, + Base::Unit unit, + std::string& frame_type + ); // Group pipeline handling void filterChanged(FemPostFilter* filter) override; @@ -104,9 +108,11 @@ protected: bool allowObject(App::DocumentObject* obj) override; // update documents - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; void onDocumentRestored() override; private: diff --git a/src/Mod/Fem/App/FemPostPipelinePyImp.cpp b/src/Mod/Fem/App/FemPostPipelinePyImp.cpp index 919952da01..ede97fa670 100644 --- a/src/Mod/Fem/App/FemPostPipelinePyImp.cpp +++ b/src/Mod/Fem/App/FemPostPipelinePyImp.cpp @@ -33,7 +33,7 @@ // clang-format on #ifdef FC_USE_VTK_PYTHON -#include +# include #endif // BUILD_FEM_VTK @@ -52,13 +52,7 @@ PyObject* FemPostPipelinePy::read(PyObject* args) PyObject* unitobj = nullptr; const char* value_type; - if (PyArg_ParseTuple(args, - "O|OO!s", - &files, - &values, - &(Base::UnitPy::Type), - &unitobj, - &value_type)) { + if (PyArg_ParseTuple(args, "O|OO!s", &files, &values, &(Base::UnitPy::Type), &unitobj, &value_type)) { if (!values) { // single argument version was called! if (!PyUnicode_Check(files)) { @@ -73,8 +67,10 @@ PyObject* FemPostPipelinePy::read(PyObject* args) // multistep version! if (!(PyTuple_Check(files) || PyList_Check(files)) || !(PyTuple_Check(values) || PyList_Check(values))) { - PyErr_SetString(PyExc_TypeError, - "Files and values must be list of strings and number respectively"); + PyErr_SetString( + PyExc_TypeError, + "Files and values must be list of strings and number respectively" + ); return nullptr; } @@ -139,13 +135,7 @@ PyObject* FemPostPipelinePy::load(PyObject* args) PyObject* unitobj = nullptr; const char* value_type; - if (PyArg_ParseTuple(args, - "O|OO!s", - &py, - &list, - &(Base::UnitPy::Type), - &unitobj, - &value_type)) { + if (PyArg_ParseTuple(args, "O|OO!s", &py, &list, &(Base::UnitPy::Type), &unitobj, &value_type)) { if (!list) { @@ -155,8 +145,7 @@ PyObject* FemPostPipelinePy::load(PyObject* args) PyErr_SetString(PyExc_TypeError, "object is not a result object"); return nullptr; } - App::DocumentObject* obj = - static_cast(py)->getDocumentObjectPtr(); + App::DocumentObject* obj = static_cast(py)->getDocumentObjectPtr(); if (!obj->isDerivedFrom()) { PyErr_SetString(PyExc_TypeError, "object is not a result object"); return nullptr; @@ -173,7 +162,8 @@ PyObject* FemPostPipelinePy::load(PyObject* args) || !(PyTuple_Check(list) || PyList_Check(list))) { std::string error = std::string( - "Result and value must be list of ResultObject and number respectively."); + "Result and value must be list of ResultObject and number respectively." + ); PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } @@ -187,15 +177,13 @@ PyObject* FemPostPipelinePy::load(PyObject* args) for (Py::Sequence::size_type i = 0; i < size; i++) { Py::Object item = result_list[i]; if (!PyObject_TypeCheck(*item, &(DocumentObjectPy::Type))) { - std::string error = - std::string("type in result list must be 'ResultObject', not "); + std::string error = std::string("type in result list must be 'ResultObject', not "); PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } auto obj = static_cast(*item)->getDocumentObjectPtr(); if (!obj->isDerivedFrom()) { - std::string error = - std::string("type in result list must be 'ResultObject', not "); + std::string error = std::string("type in result list must be 'ResultObject', not "); PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } @@ -229,7 +217,8 @@ PyObject* FemPostPipelinePy::load(PyObject* args) } else { std::string error = std::string( - "Multistep load requires 4 arguments: ResultList, ValueList, unit, type"); + "Multistep load requires 4 arguments: ResultList, ValueList, unit, type" + ); PyErr_SetString(PyExc_ValueError, error.c_str()); return nullptr; } diff --git a/src/Mod/Fem/App/FemSetElementNodesObject.cpp b/src/Mod/Fem/App/FemSetElementNodesObject.cpp index a33fa3275c..61ea02c9df 100644 --- a/src/Mod/Fem/App/FemSetElementNodesObject.cpp +++ b/src/Mod/Fem/App/FemSetElementNodesObject.cpp @@ -34,11 +34,7 @@ PROPERTY_SOURCE(Fem::FemSetElementNodesObject, Fem::FemSetObject) FemSetElementNodesObject::FemSetElementNodesObject() { - ADD_PROPERTY_TYPE(Elements, - (), - "Element indexes", - Prop_None, - "Elements belonging to the ElementSet"); + ADD_PROPERTY_TYPE(Elements, (), "Element indexes", Prop_None, "Elements belonging to the ElementSet"); } FemSetElementNodesObject::~FemSetElementNodesObject() = default; diff --git a/src/Mod/Fem/App/FemSolverObject.cpp b/src/Mod/Fem/App/FemSolverObject.cpp index 5c22db9cbe..8a297b91fe 100644 --- a/src/Mod/Fem/App/FemSolverObject.cpp +++ b/src/Mod/Fem/App/FemSolverObject.cpp @@ -36,16 +36,20 @@ PROPERTY_SOURCE(Fem::FemSolverObject, App::DocumentObject) FemSolverObject::FemSolverObject() { - ADD_PROPERTY_TYPE(Results, - (nullptr), - "Solver", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Solver results list"); - ADD_PROPERTY_TYPE(WorkingDirectory, - (""), - "Solver", - App::PropertyType(App::Prop_Transient | App::Prop_Hidden | App::Prop_Output), - "Solver working directory"); + ADD_PROPERTY_TYPE( + Results, + (nullptr), + "Solver", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Solver results list" + ); + ADD_PROPERTY_TYPE( + WorkingDirectory, + (""), + "Solver", + App::PropertyType(App::Prop_Transient | App::Prop_Hidden | App::Prop_Output), + "Solver working directory" + ); } FemSolverObject::~FemSolverObject() = default; diff --git a/src/Mod/Fem/App/FemTools.cpp b/src/Mod/Fem/App/FemTools.cpp index db907ca795..7ed45529bf 100644 --- a/src/Mod/Fem/App/FemTools.cpp +++ b/src/Mod/Fem/App/FemTools.cpp @@ -287,9 +287,11 @@ gp_XYZ Fem::Tools::getDirection(const TopoDS_Edge& edge) } // function to determine 3rd-party binaries used by the FEM WB -std::string Fem::Tools::checkIfBinaryExists(std::string prefSection, - std::string prefBinaryName, - std::string binaryName) +std::string Fem::Tools::checkIfBinaryExists( + std::string prefSection, + std::string prefBinaryName, + std::string binaryName +) { // if "Search in known binary directories" is set in the preferences, we ignore custom path auto paramPath = "User parameter:BaseApp/Preferences/Mod/Fem/" + prefSection; @@ -300,8 +302,9 @@ std::string Fem::Tools::checkIfBinaryExists(std::string prefSection, if (knownDirectories) { // first check the environment paths, normally determined by the PATH environment variable // On Windows, the executable extensions(".exe" etc.) should be automatically appended - QString executablePath = - QStandardPaths::findExecutable(QString::fromLatin1(binaryName.c_str())); + QString executablePath = QStandardPaths::findExecutable( + QString::fromLatin1(binaryName.c_str()) + ); if (!executablePath.isEmpty()) { return executablePath.toStdString(); } @@ -309,9 +312,10 @@ std::string Fem::Tools::checkIfBinaryExists(std::string prefSection, else { auto appBinaryPath = App::Application::getHomePath() + "bin/"; QStringList pathCandidates = {QString::fromLatin1(appBinaryPath.c_str())}; - QString executablePath = - QStandardPaths::findExecutable(QString::fromLatin1(binaryName.c_str()), - pathCandidates); + QString executablePath = QStandardPaths::findExecutable( + QString::fromLatin1(binaryName.c_str()), + pathCandidates + ); if (!executablePath.isEmpty()) { return executablePath.toStdString(); } @@ -321,8 +325,9 @@ std::string Fem::Tools::checkIfBinaryExists(std::string prefSection, auto binaryPathString = prefBinaryName + "BinaryPath"; // use binary path from settings, fall back to system path if not defined auto binaryPath = hGrp->GetASCII(binaryPathString.c_str(), binaryName.c_str()); - QString executablePath = - QStandardPaths::findExecutable(QString::fromLatin1(binaryPath.c_str())); + QString executablePath = QStandardPaths::findExecutable( + QString::fromLatin1(binaryPath.c_str()) + ); if (!executablePath.isEmpty()) { return executablePath.toStdString(); } @@ -330,8 +335,7 @@ std::string Fem::Tools::checkIfBinaryExists(std::string prefSection, return ""; } -Base::Placement Fem::Tools::getSubShapeGlobalLocation(const Part::Feature* feat, - const TopoDS_Shape& sh) +Base::Placement Fem::Tools::getSubShapeGlobalLocation(const Part::Feature* feat, const TopoDS_Shape& sh) { Base::Matrix4D matrix = Part::TopoShape::convert(sh.Location().Transformation()); Base::Placement shPla {matrix}; @@ -348,8 +352,7 @@ void Fem::Tools::setSubShapeGlobalLocation(const Part::Feature* feat, TopoDS_Sha } -TopoDS_Shape -Fem::Tools::getFeatureSubShape(const Part::Feature* feat, const char* subName, bool silent) +TopoDS_Shape Fem::Tools::getFeatureSubShape(const Part::Feature* feat, const char* subName, bool silent) { TopoDS_Shape sh; const Part::TopoShape& toposhape = feat->Shape.getShape(); @@ -367,11 +370,13 @@ Fem::Tools::getFeatureSubShape(const Part::Feature* feat, const char* subName, b return sh; } -bool Fem::Tools::getCylinderParams(const TopoDS_Shape& sh, - Base::Vector3d& base, - Base::Vector3d& axis, - double& height, - double& radius) +bool Fem::Tools::getCylinderParams( + const TopoDS_Shape& sh, + Base::Vector3d& base, + Base::Vector3d& axis, + double& height, + double& radius +) { TopoDS_Face face = TopoDS::Face(sh); BRepAdaptor_Surface surface(face); diff --git a/src/Mod/Fem/App/FemTools.h b/src/Mod/Fem/App/FemTools.h index fd6388b1cc..81e8626841 100644 --- a/src/Mod/Fem/App/FemTools.h +++ b/src/Mod/Fem/App/FemTools.h @@ -80,30 +80,32 @@ public: The result is either the full path if available or just the binary name if it was found in a system path */ - static std::string checkIfBinaryExists(std::string prefSection, - std::string prefBinaryPath, - std::string prefBinaryName); + static std::string checkIfBinaryExists( + std::string prefSection, + std::string prefBinaryPath, + std::string prefBinaryName + ); /*! Subshape placement is not necessarily the same as the feature placement */ - static Base::Placement getSubShapeGlobalLocation(const Part::Feature* feat, - const TopoDS_Shape& sh); + static Base::Placement getSubShapeGlobalLocation(const Part::Feature* feat, const TopoDS_Shape& sh); static void setSubShapeGlobalLocation(const Part::Feature* feat, TopoDS_Shape& sh); /*! Get subshape from Part Feature. The subShape is returned with global location */ - static TopoDS_Shape - getFeatureSubShape(const Part::Feature* feat, const char* subName, bool silent); + static TopoDS_Shape getFeatureSubShape(const Part::Feature* feat, const char* subName, bool silent); /*! Get cylinder parameters. Base is located at the center of the cylinder */ - static bool getCylinderParams(const TopoDS_Shape& sh, - Base::Vector3d& base, - Base::Vector3d& axis, - double& height, - double& radius); + static bool getCylinderParams( + const TopoDS_Shape& sh, + Base::Vector3d& base, + Base::Vector3d& axis, + double& height, + double& radius + ); }; } // namespace Fem diff --git a/src/Mod/Fem/App/FemVTKTools.cpp b/src/Mod/Fem/App/FemVTKTools.cpp index 27ee263450..79dd68270a 100644 --- a/src/Mod/Fem/App/FemVTKTools.cpp +++ b/src/Mod/Fem/App/FemVTKTools.cpp @@ -188,112 +188,125 @@ void FemVTKTools::importVTKMesh(vtkSmartPointer dataset, FemMesh* me meshds->AddFaceWithID(ids[0], ids[1], ids[2], ids[3], iCell + 1); break; case VTK_QUADRATIC_QUAD: // quad8 - meshds->AddFaceWithID(ids[0], - ids[1], - ids[2], - ids[3], - ids[4], - ids[5], - ids[6], - ids[7], - iCell + 1); + meshds->AddFaceWithID( + ids[0], + ids[1], + ids[2], + ids[3], + ids[4], + ids[5], + ids[6], + ids[7], + iCell + 1 + ); break; // 3D volumes case VTK_TETRA: // tetra4 meshds->AddVolumeWithID(ids[0], ids[1], ids[2], ids[3], iCell + 1); break; case VTK_QUADRATIC_TETRA: // tetra10 - meshds->AddVolumeWithID(ids[0], - ids[1], - ids[2], - ids[3], - ids[4], - ids[5], - ids[6], - ids[7], - ids[8], - ids[9], - iCell + 1); + meshds->AddVolumeWithID( + ids[0], + ids[1], + ids[2], + ids[3], + ids[4], + ids[5], + ids[6], + ids[7], + ids[8], + ids[9], + iCell + 1 + ); break; case VTK_HEXAHEDRON: // hexa8 - meshds->AddVolumeWithID(ids[0], - ids[1], - ids[2], - ids[3], - ids[4], - ids[5], - ids[6], - ids[7], - iCell + 1); + meshds->AddVolumeWithID( + ids[0], + ids[1], + ids[2], + ids[3], + ids[4], + ids[5], + ids[6], + ids[7], + iCell + 1 + ); break; case VTK_QUADRATIC_HEXAHEDRON: // hexa20 - meshds->AddVolumeWithID(ids[0], - ids[1], - ids[2], - ids[3], - ids[4], - ids[5], - ids[6], - ids[7], - ids[8], - ids[9], - ids[10], - ids[11], - ids[12], - ids[13], - ids[14], - ids[15], - ids[16], - ids[17], - ids[18], - ids[19], - iCell + 1); + meshds->AddVolumeWithID( + ids[0], + ids[1], + ids[2], + ids[3], + ids[4], + ids[5], + ids[6], + ids[7], + ids[8], + ids[9], + ids[10], + ids[11], + ids[12], + ids[13], + ids[14], + ids[15], + ids[16], + ids[17], + ids[18], + ids[19], + iCell + 1 + ); break; case VTK_WEDGE: // penta6 meshds->AddVolumeWithID(ids[0], ids[1], ids[2], ids[3], ids[4], ids[5], iCell + 1); break; case VTK_QUADRATIC_WEDGE: // penta15 - meshds->AddVolumeWithID(ids[0], - ids[1], - ids[2], - ids[3], - ids[4], - ids[5], - ids[6], - ids[7], - ids[8], - ids[9], - ids[10], - ids[11], - ids[12], - ids[13], - ids[14], - iCell + 1); + meshds->AddVolumeWithID( + ids[0], + ids[1], + ids[2], + ids[3], + ids[4], + ids[5], + ids[6], + ids[7], + ids[8], + ids[9], + ids[10], + ids[11], + ids[12], + ids[13], + ids[14], + iCell + 1 + ); break; case VTK_PYRAMID: // pyra5 meshds->AddVolumeWithID(ids[0], ids[1], ids[2], ids[3], ids[4], iCell + 1); break; case VTK_QUADRATIC_PYRAMID: // pyra13 - meshds->AddVolumeWithID(ids[0], - ids[1], - ids[2], - ids[3], - ids[4], - ids[5], - ids[6], - ids[7], - ids[8], - ids[9], - ids[10], - ids[11], - ids[12], - iCell + 1); + meshds->AddVolumeWithID( + ids[0], + ids[1], + ids[2], + ids[3], + ids[4], + ids[5], + ids[6], + ids[7], + ids[8], + ids[9], + ids[10], + ids[11], + ids[12], + iCell + 1 + ); break; // not handled cases default: { Base::Console().error( - "Only common 1D, 2D and 3D Cells are supported in VTK mesh import\n"); + "Only common 1D, 2D and 3D Cells are supported in VTK mesh import\n" + ); break; } } @@ -336,14 +349,15 @@ FemMesh* FemVTKTools::readVTKMesh(const char* filename, FemMesh* mesh) } // Mesh should link to the part feature, in order to set up FemConstraint - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); return mesh; } -void exportFemMeshEdges(vtkSmartPointer& elemArray, - std::vector& types, - const SMDS_EdgeIteratorPtr& aEdgeIter) +void exportFemMeshEdges( + vtkSmartPointer& elemArray, + std::vector& types, + const SMDS_EdgeIteratorPtr& aEdgeIter +) { Base::Console().log(" Start: VTK mesh builder edges.\n"); @@ -365,9 +379,11 @@ void exportFemMeshEdges(vtkSmartPointer& elemArray, Base::Console().log(" End: VTK mesh builder edges.\n"); } -void exportFemMeshFaces(vtkSmartPointer& elemArray, - std::vector& types, - const SMDS_FaceIteratorPtr& aFaceIter) +void exportFemMeshFaces( + vtkSmartPointer& elemArray, + std::vector& types, + const SMDS_FaceIteratorPtr& aFaceIter +) { Base::Console().log(" Start: VTK mesh builder faces.\n"); @@ -397,9 +413,11 @@ void exportFemMeshFaces(vtkSmartPointer& elemArray, Base::Console().log(" End: VTK mesh builder faces.\n"); } -void exportFemMeshCells(vtkSmartPointer& elemArray, - std::vector& types, - const SMDS_VolumeIteratorPtr& aVolIter) +void exportFemMeshCells( + vtkSmartPointer& elemArray, + std::vector& types, + const SMDS_VolumeIteratorPtr& aVolIter +) { Base::Console().log(" Start: VTK mesh builder volumes.\n"); @@ -438,10 +456,12 @@ void exportFemMeshCells(vtkSmartPointer& elemArray, Base::Console().log(" End: VTK mesh builder volumes.\n"); } -void FemVTKTools::exportVTKMesh(const FemMesh* mesh, - vtkSmartPointer grid, - bool highest, - float scale) +void FemVTKTools::exportVTKMesh( + const FemMesh* mesh, + vtkSmartPointer grid, + bool highest, + float scale +) { Base::Console().log("Start: VTK mesh builder ======================\n"); @@ -456,9 +476,8 @@ void FemVTKTools::exportVTKMesh(const FemMesh* mesh, while (aNodeIter->more()) { const SMDS_MeshNode* node = aNodeIter->next(); // why float, not double? - double coords[3] = {double(node->X() * scale), - double(node->Y() * scale), - double(node->Z() * scale)}; + double coords[3] + = {double(node->X() * scale), double(node->Y() * scale), double(node->Z() * scale)}; points->InsertPoint(node->GetID() - 1, coords); // memory is allocated by VTK points size for max node id, not for point count // if the SMESH mesh has gaps in node numbering, points without any element @@ -532,8 +551,7 @@ void FemVTKTools::writeVTKMesh(const char* filename, const FemMesh* mesh, bool h Base::Console().error("file name extension is not supported to write VTK\n"); } - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); } @@ -584,8 +602,7 @@ App::DocumentObject* createObjectByType(const Base::Type type) App::DocumentObject* FemVTKTools::readResult(const char* filename, App::DocumentObject* res) { Base::TimeElapsed Start; - Base::Console().log( - "Start: read FemResult with FemMesh from VTK file ======================\n"); + Base::Console().log("Start: read FemResult with FemMesh from VTK file ======================\n"); Base::FileInfo f(filename); vtkSmartPointer ds; @@ -610,8 +627,7 @@ App::DocumentObject* FemVTKTools::readResult(const char* filename, App::Document App::DocumentObject* result = nullptr; if (res) { - Base::Console().message( - "FemResultObject pointer is NULL, trying to get the active object\n"); + Base::Console().message("FemResultObject pointer is NULL, trying to get the active object\n"); if (obj->getTypeId() == Base::Type::fromName("Fem::FemResultObjectPython")) { result = obj; } @@ -628,8 +644,7 @@ App::DocumentObject* FemVTKTools::readResult(const char* filename, App::Document if (result) { // PropertyLink is the property type to store DocumentObject pointer - App::PropertyLink* link = - dynamic_cast(result->getPropertyByName("Mesh")); + App::PropertyLink* link = dynamic_cast(result->getPropertyByName("Mesh")); if (link) { link->setValue(mesh); } @@ -639,8 +654,7 @@ App::DocumentObject* FemVTKTools::readResult(const char* filename, App::Document } pcDoc->recompute(); - Base::Console().log(" %f: Done \n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log(" %f: Done \n", Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); Base::Console().log("End: read FemResult with FemMesh from VTK file ======================\n"); return result; @@ -668,14 +682,16 @@ void FemVTKTools::writeResult(const char* filename, const App::DocumentObject* r // mesh vtkSmartPointer grid = vtkSmartPointer::New(); - App::DocumentObject* mesh = - static_cast(res->getPropertyByName("Mesh"))->getValue(); - const FemMesh& fmesh = - static_cast(mesh->getPropertyByName("FemMesh"))->getValue(); + App::DocumentObject* mesh + = static_cast(res->getPropertyByName("Mesh"))->getValue(); + const FemMesh& fmesh + = static_cast(mesh->getPropertyByName("FemMesh"))->getValue(); FemVTKTools::exportVTKMesh(&fmesh, grid); - Base::Console().log(" %f: vtk mesh builder finished\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: vtk mesh builder finished\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // result FemVTKTools::exportFreeCADResult(res, grid); @@ -690,8 +706,10 @@ void FemVTKTools::writeResult(const char* filename, const App::DocumentObject* r Base::Console().error("file name extension is not supported to write VTK\n"); } - Base::Console().log(" %f: writing result object to vtk finished\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: writing result object to vtk finished\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); Base::Console().log("End: write FemResult to VTK unstructuredGrid dataset =======\n"); } @@ -723,8 +741,8 @@ std::map _getFreeCADMechResultScalarProperties() // see src/Mod/Fem/femobjects/result_mechanical.py // App::PropertyFloatList will be a list of scalars in vtk std::map resFCScalProp; - resFCScalProp["DisplacementLengths"] = - "Displacement Magnitude"; // can be plotted in Paraview as THE DISPLACEMENT MAGNITUDE + resFCScalProp["DisplacementLengths"] = "Displacement Magnitude"; // can be plotted in Paraview + // as THE DISPLACEMENT MAGNITUDE resFCScalProp["MaxShear"] = "Tresca Stress"; resFCScalProp["NodeStressXX"] = "Stress xx component"; resFCScalProp["NodeStressYY"] = "Stress yy component"; @@ -753,9 +771,9 @@ std::map _getFreeCADMechResultScalarProperties() // https://forum.freecad.org/viewtopic.php?f=18&t=33106&p=416006#p412800 resFCScalProp["PrincipalMax"] = "Major Principal Stress"; // can be plotted in Paraview as THE // MAJOR PRINCIPAL STRESS MAGNITUDE - resFCScalProp["PrincipalMed"] = - "Intermediate Principal Stress"; // can be plotted in Paraview as THE INTERMEDIATE - // PRINCIPAL STRESS MAGNITUDE + resFCScalProp["PrincipalMed"] = "Intermediate Principal Stress"; // can be plotted in Paraview + // as THE INTERMEDIATE + // PRINCIPAL STRESS MAGNITUDE resFCScalProp["PrincipalMin"] = "Minor Principal Stress"; // can be plotted in Paraview as THE // MINOR PRINCIPAL STRESS MAGNITUDE resFCScalProp["vonMises"] = "von Mises Stress"; @@ -773,8 +791,7 @@ std::map _getFreeCADMechResultScalarProperties() } -void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, - App::DocumentObject* result) +void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, App::DocumentObject* result) { Base::Console().log("Start: import vtk result file data into a FreeCAD result object.\n"); @@ -798,8 +815,7 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, for (vtkIdType i = 0; i < nPoints; ++i) { nodeIds[i] = i + 1; } - static_cast(result->getPropertyByName("NodeNumbers")) - ->setValues(nodeIds); + static_cast(result->getPropertyByName("NodeNumbers"))->setValues(nodeIds); Base::Console().log(" NodeNumbers have been filled with values.\n"); // vectors @@ -808,30 +824,37 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, // FreeCAD only supports dim 3D, I do not know about VTK vtkDataArray* vector_field = vtkDataArray::SafeDownCast(pd->GetArray(it.second.c_str())); if (vector_field && vector_field->GetNumberOfComponents() == dim) { - App::PropertyVectorList* vector_list = - static_cast(result->getPropertyByName(it.first.c_str())); + App::PropertyVectorList* vector_list = static_cast( + result->getPropertyByName(it.first.c_str()) + ); if (vector_list) { std::vector vec(nPoints); for (vtkIdType i = 0; i < nPoints; ++i) { - double* p = vector_field->GetTuple( - i); // both vtkFloatArray and vtkDoubleArray return double* for GetTuple(i) + double* p = vector_field->GetTuple(i); // both vtkFloatArray and vtkDoubleArray + // return double* for GetTuple(i) vec[i] = (Base::Vector3d(p[0], p[1], p[2])); } // PropertyVectorList will not show up in PropertyEditor vector_list->setValues(vec); - Base::Console().log(" A PropertyVectorList has been filled with values: %s\n", - it.first.c_str()); + Base::Console().log( + " A PropertyVectorList has been filled with values: %s\n", + it.first.c_str() + ); } else { - Base::Console().error("static_cast((result->" - "getPropertyByName(\"%s\")) failed.\n", - it.first.c_str()); + Base::Console().error( + "static_cast((result->" + "getPropertyByName(\"%s\")) failed.\n", + it.first.c_str() + ); continue; } } else { - Base::Console().message(" PropertyVectorList NOT found in vkt file data: %s\n", - it.first.c_str()); + Base::Console().message( + " PropertyVectorList NOT found in vkt file data: %s\n", + it.first.c_str() + ); } } @@ -840,11 +863,14 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, vtkDataArray* vec = vtkDataArray::SafeDownCast(pd->GetArray(scalar.second.c_str())); if (nPoints && vec && vec->GetNumberOfComponents() == 1) { App::PropertyFloatList* field = static_cast( - result->getPropertyByName(scalar.first.c_str())); + result->getPropertyByName(scalar.first.c_str()) + ); if (!field) { - Base::Console().error("static_cast((result->" - "getPropertyByName(\"%s\")) failed.\n", - scalar.first.c_str()); + Base::Console().error( + "static_cast((result->" + "getPropertyByName(\"%s\")) failed.\n", + scalar.first.c_str() + ); continue; } @@ -861,12 +887,16 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, } } field->setValues(values); - Base::Console().log(" A PropertyFloatList has been filled with vales: %s\n", - scalar.first.c_str()); + Base::Console().log( + " A PropertyFloatList has been filled with vales: %s\n", + scalar.first.c_str() + ); } else { - Base::Console().message(" PropertyFloatList NOT found in vkt file data %s\n", - scalar.first.c_str()); + Base::Console().message( + " PropertyFloatList NOT found in vkt file data %s\n", + scalar.first.c_str() + ); } } @@ -877,8 +907,7 @@ void FemVTKTools::importFreeCADResult(vtkSmartPointer dataset, } -void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, - vtkSmartPointer grid) +void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, vtkSmartPointer grid) { Base::Console().log("Start: Create VTK result data from FreeCAD result data.\n"); @@ -906,8 +935,7 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, // vectors for (const auto& it : vectors) { - const int dim = - 3; // Fixme, detect dim, but FreeCAD PropertyVectorList ATM only has DIM of 3 + const int dim = 3; // Fixme, detect dim, but FreeCAD PropertyVectorList ATM only has DIM of 3 App::PropertyVectorList* field = nullptr; if (res->getPropertyByName(it.first.c_str())) { field = static_cast(res->getPropertyByName(it.first.c_str())); @@ -950,12 +978,15 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, Base::Console().log( " The PropertyVectorList %s was exported to VTK vector list: %s\n", it.first.c_str(), - it.second.c_str()); + it.second.c_str() + ); } else if (field) { - Base::Console().log(" PropertyVectorList NOT exported to vtk: %s size is: %i\n", - it.first.c_str(), - field->getSize()); + Base::Console().log( + " PropertyVectorList NOT exported to vtk: %s size is: %i\n", + it.first.c_str(), + field->getSize() + ); } } @@ -963,8 +994,7 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, for (const auto& scalar : scalars) { App::PropertyFloatList* field = nullptr; if (res->getPropertyByName(scalar.first.c_str())) { - field = - static_cast(res->getPropertyByName(scalar.first.c_str())); + field = static_cast(res->getPropertyByName(scalar.first.c_str())); } else { Base::Console().error("PropertyFloatList %s not found \n", scalar.first.c_str()); @@ -985,8 +1015,7 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, } } - if ((scalar.first.compare("MaxShear") == 0) - || (scalar.first.compare("NodeStressXX") == 0) + if ((scalar.first.compare("MaxShear") == 0) || (scalar.first.compare("NodeStressXX") == 0) || (scalar.first.compare("NodeStressXY") == 0) || (scalar.first.compare("NodeStressXZ") == 0) || (scalar.first.compare("NodeStressYY") == 0) @@ -1019,12 +1048,15 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, Base::Console().log( " The PropertyFloatList %s was exported to VTK scalar list: %s\n", scalar.first.c_str(), - scalar.second.c_str()); + scalar.second.c_str() + ); } else if (field) { - Base::Console().log(" PropertyFloatList NOT exported to vtk: %s size is: %i\n", - scalar.first.c_str(), - field->getSize()); + Base::Console().log( + " PropertyFloatList NOT exported to vtk: %s size is: %i\n", + scalar.first.c_str(), + field->getSize() + ); } } @@ -1060,11 +1092,13 @@ enum class AnalysisType UserNamed = 4 }; -std::map mapAnalysisTypeToStr = {{AnalysisType::Static, "Static"}, - {AnalysisType::TimeStep, "TimeStep"}, - {AnalysisType::Frequency, "Frequency"}, - {AnalysisType::LoadStep, "LoadStep"}, - {AnalysisType::UserNamed, "User"}}; +std::map mapAnalysisTypeToStr = { + {AnalysisType::Static, "Static"}, + {AnalysisType::TimeStep, "TimeStep"}, + {AnalysisType::Frequency, "Frequency"}, + {AnalysisType::LoadStep, "LoadStep"}, + {AnalysisType::UserNamed, "User"} +}; // value format indicator enum class Indicator @@ -1105,7 +1139,8 @@ std::map> mapCcxToVtk = { {VTK_QUADRATIC_HEXAHEDRON, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 18, 19, 12, 13, 14, 15}}, {VTK_WEDGE, {0, 1, 2, 3, 4, 5}}, - {VTK_QUADRATIC_WEDGE, {0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 9, 10, 11}}}; + {VTK_QUADRATIC_WEDGE, {0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 9, 10, 11}} +}; // give position of first non-blank character of string_view size_t getFirstNotBlankPos(const std::string_view& view) @@ -1154,10 +1189,12 @@ void addCell(vtkSmartPointer& cellArray, const std::vector& t } // fill cell array -void fillCell(vtkSmartPointer& cellArray, - std::vector& topoElem, - std::vector& vtkType, - ElementType elemType) +void fillCell( + vtkSmartPointer& cellArray, + std::vector& topoElem, + std::vector& vtkType, + ElementType elemType +) { switch (elemType) { case ElementType::Hexa: @@ -1270,8 +1307,11 @@ std::vector identifyScalarEntities(const std::vector> e } // read nodes and fill vtkPoints object -std::map -readNodes(std::ifstream& ifstr, const std::string& lines, vtkSmartPointer& points) +std::map readNodes( + std::ifstream& ifstr, + const std::string& lines, + vtkSmartPointer& points +) { std::string keyCode = " 2C"; std::string keyCodeCoord = " -1"; @@ -1319,10 +1359,12 @@ readNodes(std::ifstream& ifstr, const std::string& lines, vtkSmartPointer readElements(std::ifstream& ifstr, - const std::string& lines, - const std::map& mapNodes, - vtkSmartPointer& cellArray) +std::vector readElements( + std::ifstream& ifstr, + const std::string& lines, + const std::map& mapNodes, + vtkSmartPointer& cellArray +) { std::string line; std::string keyCode = " 3C"; @@ -1415,11 +1457,13 @@ void readResultInfo(std::ifstream& ifstr, const std::string& lines, FRDResultInf } // read result from nodal result block and add result array to grid -void readResults(std::ifstream& ifstr, - const std::string& lines, - const std::map& mapNodes, - const FRDResultInfo& info, - vtkSmartPointer& grid) +void readResults( + std::ifstream& ifstr, + const std::string& lines, + const std::map& mapNodes, + const FRDResultInfo& info, + vtkSmartPointer& grid +) { int digits = getDigits(info.indicator); (void)lines; @@ -1725,16 +1769,18 @@ void FemVTKTools::frdToVTK(const char* filename, bool binary) for (unsigned int i = 0; i < multiBlock->GetNumberOfBlocks(); ++i) { vtkDataObject* block = multiBlock->GetBlock(i); // get TimeInfo - vtkSmartPointer info = - vtkStringArray::SafeDownCast(block->GetFieldData()->GetAbstractArray(0)); + vtkSmartPointer info = vtkStringArray::SafeDownCast( + block->GetFieldData()->GetAbstractArray(0) + ); std::string type = info->GetValue(0).c_str(); auto writer = vtkSmartPointer::New(); - writer->SetDataMode(binary ? vtkXMLMultiBlockDataWriter::Binary - : vtkXMLMultiBlockDataWriter::Ascii); + writer->SetDataMode( + binary ? vtkXMLMultiBlockDataWriter::Binary : vtkXMLMultiBlockDataWriter::Ascii + ); - std::string blockFile = - dir + "/" + fi.fileNamePure() + type + "." + writer->GetDefaultFileExtension(); + std::string blockFile = dir + "/" + fi.fileNamePure() + type + "." + + writer->GetDefaultFileExtension(); writer->SetFileName(blockFile.c_str()); writer->SetInputData(block); writer->Update(); diff --git a/src/Mod/Fem/App/FemVTKTools.h b/src/Mod/Fem/App/FemVTKTools.h index cf8db957b4..17143dea5e 100644 --- a/src/Mod/Fem/App/FemVTKTools.h +++ b/src/Mod/Fem/App/FemVTKTools.h @@ -44,20 +44,20 @@ public: // extract data from FreCAD FEM mesh and fill a vtkUnstructuredGrid instance with that data. Set // `highest` to false to export all elements levels. - static void exportVTKMesh(const FemMesh* mesh, - vtkSmartPointer grid, - bool highest = true, - float scale = 1.0); + static void exportVTKMesh( + const FemMesh* mesh, + vtkSmartPointer grid, + bool highest = true, + float scale = 1.0 + ); // extract data from vtkUnstructuredGrid object and fill a FreeCAD FEM result object with that // data (needed by readResult) - static void importFreeCADResult(vtkSmartPointer dataset, - App::DocumentObject* result); + static void importFreeCADResult(vtkSmartPointer dataset, App::DocumentObject* result); // extract data from a FreeCAD FEM result object and fill a vtkUnstructuredGrid object with that // data (needed by writeResult) - static void exportFreeCADResult(const App::DocumentObject* result, - vtkSmartPointer grid); + static void exportFreeCADResult(const App::DocumentObject* result, vtkSmartPointer grid); // FemMesh read from vtkUnstructuredGrid data file static FemMesh* readVTKMesh(const char* filename, FemMesh* mesh); @@ -66,8 +66,7 @@ public: static void writeVTKMesh(const char* Filename, const FemMesh* mesh, bool highest = true); // FemResult (activeObject or created if res= NULL) read from vtkUnstructuredGrid dataset file - static App::DocumentObject* readResult(const char* Filename, - App::DocumentObject* res = nullptr); + static App::DocumentObject* readResult(const char* Filename, App::DocumentObject* res = nullptr); // write FemResult (activeObject if res= NULL) to vtkUnstructuredGrid dataset file static void writeResult(const char* filename, const App::DocumentObject* res = nullptr); diff --git a/src/Mod/Fem/App/HypothesisPy.cpp b/src/Mod/Fem/App/HypothesisPy.cpp index b1a9ace15d..b8d7df6a3d 100644 --- a/src/Mod/Fem/App/HypothesisPy.cpp +++ b/src/Mod/Fem/App/HypothesisPy.cpp @@ -36,7 +36,7 @@ #include #include #if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 -#include +# include #endif #include #include @@ -87,38 +87,58 @@ void SMESH_HypothesisPy::init_type(PyObject* module) SMESH_HypothesisPy::behaviors().supportSetattr(); SMESH_HypothesisPy::behaviors().set_tp_new(PyMake); - SMESH_HypothesisPy::add_varargs_method("setLibName", - &SMESH_HypothesisPy::setLibName, - "setLibName(String)"); - SMESH_HypothesisPy::add_varargs_method("getLibName", - &SMESH_HypothesisPy::getLibName, - "String getLibName()"); + SMESH_HypothesisPy::add_varargs_method( + "setLibName", + &SMESH_HypothesisPy::setLibName, + "setLibName(String)" + ); + SMESH_HypothesisPy::add_varargs_method( + "getLibName", + &SMESH_HypothesisPy::getLibName, + "String getLibName()" + ); #if SMESH_VERSION_MAJOR < 7 - SMESH_HypothesisPy::add_varargs_method("setParameters", - &SMESH_HypothesisPy::setParameters, - "setParameters(String)"); - SMESH_HypothesisPy::add_varargs_method("getParameters", - &SMESH_HypothesisPy::getParameters, - "String getParameters()"); - SMESH_HypothesisPy::add_varargs_method("setLastParameters", - &SMESH_HypothesisPy::setLastParameters, - "setLastParameters(String)"); - SMESH_HypothesisPy::add_varargs_method("getLastParameters", - &SMESH_HypothesisPy::getLastParameters, - "String getLastParameters()"); - SMESH_HypothesisPy::add_varargs_method("clearParameters", - &SMESH_HypothesisPy::clearParameters, - "clearParameters()"); + SMESH_HypothesisPy::add_varargs_method( + "setParameters", + &SMESH_HypothesisPy::setParameters, + "setParameters(String)" + ); + SMESH_HypothesisPy::add_varargs_method( + "getParameters", + &SMESH_HypothesisPy::getParameters, + "String getParameters()" + ); + SMESH_HypothesisPy::add_varargs_method( + "setLastParameters", + &SMESH_HypothesisPy::setLastParameters, + "setLastParameters(String)" + ); + SMESH_HypothesisPy::add_varargs_method( + "getLastParameters", + &SMESH_HypothesisPy::getLastParameters, + "String getLastParameters()" + ); + SMESH_HypothesisPy::add_varargs_method( + "clearParameters", + &SMESH_HypothesisPy::clearParameters, + "clearParameters()" + ); #endif - SMESH_HypothesisPy::add_varargs_method("isAuxiliary", - &SMESH_HypothesisPy::isAuxiliary, - "Bool isAuxiliary()"); - SMESH_HypothesisPy::add_varargs_method("setParametersByMesh", - &SMESH_HypothesisPy::setParametersByMesh, - "setParametersByMesh(Mesh,Shape)"); - Base::Interpreter().addType(SMESH_HypothesisPy::behaviors().type_object(), - module, - SMESH_HypothesisPy::behaviors().getName()); + SMESH_HypothesisPy::add_varargs_method( + "isAuxiliary", + &SMESH_HypothesisPy::isAuxiliary, + "Bool isAuxiliary()" + ); + SMESH_HypothesisPy::add_varargs_method( + "setParametersByMesh", + &SMESH_HypothesisPy::setParametersByMesh, + "setParametersByMesh(Mesh,Shape)" + ); + Base::Interpreter().addType( + SMESH_HypothesisPy::behaviors().type_object(), + module, + SMESH_HypothesisPy::behaviors().getName() + ); } template @@ -168,12 +188,14 @@ template Py::Object SMESH_HypothesisPy::setParametersByMesh(const Py::Tuple& args) { PyObject *mesh, *shape; - if (!PyArg_ParseTuple(args.ptr(), - "O!O!", - &(Fem::FemMeshPy::Type), - &mesh, - &(Part::TopoShapePy::Type), - &shape)) { + if (!PyArg_ParseTuple( + args.ptr(), + "O!O!", + &(Fem::FemMeshPy::Type), + &mesh, + &(Part::TopoShapePy::Type), + &shape + )) { throw Py::Exception(); } Fem::FemMesh* m = static_cast(mesh)->getFemMeshPtr(); @@ -191,8 +213,7 @@ Py::Object SMESH_HypothesisPy::isAuxiliary(const Py::Tuple& args) } template -PyObject* -SMESH_HypothesisPy::PyMake(struct _typeobject* /*type*/, PyObject* args, PyObject* /*kwds*/) +PyObject* SMESH_HypothesisPy::PyMake(struct _typeobject* /*type*/, PyObject* args, PyObject* /*kwds*/) { int hypId; PyObject* obj; @@ -233,8 +254,10 @@ StdMeshers_Arithmetic1DPy::~StdMeshers_Arithmetic1DPy() = default; Py::Object StdMeshers_Arithmetic1DPy::setLength(const Py::Tuple& args) { - hypothesis()->SetLength((double)Py::Float(args[0]), - (bool)Py::Boolean(args[1])); + hypothesis()->SetLength( + (double)Py::Float(args[0]), + (bool)Py::Boolean(args[1]) + ); return Py::None(); } @@ -265,9 +288,7 @@ StdMeshers_AutomaticLengthPy::StdMeshers_AutomaticLengthPy(int /*hypId*/, SMESH_ : SMESH_HypothesisPyBase(0) {} #else -StdMeshers_AutomaticLengthPy::StdMeshers_AutomaticLengthPy(int /*hypId*/, - int /*studyId*/, - SMESH_Gen* /*gen*/) +StdMeshers_AutomaticLengthPy::StdMeshers_AutomaticLengthPy(int /*hypId*/, int /*studyId*/, SMESH_Gen* /*gen*/) : SMESH_HypothesisPyBase(nullptr) {} #endif @@ -336,9 +357,7 @@ StdMeshers_NotConformAllowedPy::StdMeshers_NotConformAllowedPy(int hypId, SMESH_ : SMESH_HypothesisPyBase(new StdMeshers_NotConformAllowed(hypId, gen)) {} #else -StdMeshers_NotConformAllowedPy::StdMeshers_NotConformAllowedPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_NotConformAllowedPy::StdMeshers_NotConformAllowedPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_NotConformAllowed(hypId, studyId, gen)) {} #endif @@ -354,21 +373,31 @@ void StdMeshers_MaxLengthPy::init_type(PyObject* module) add_varargs_method("setLength", &StdMeshers_MaxLengthPy::setLength, "setLength()"); add_varargs_method("getLength", &StdMeshers_MaxLengthPy::getLength, "getLength()"); - add_varargs_method("havePreestimatedLength", - &StdMeshers_MaxLengthPy::havePreestimatedLength, - "havePreestimatedLength()"); - add_varargs_method("getPreestimatedLength", - &StdMeshers_MaxLengthPy::getPreestimatedLength, - "getPreestimatedLength()"); - add_varargs_method("setPreestimatedLength", - &StdMeshers_MaxLengthPy::setPreestimatedLength, - "setPreestimatedLength()"); - add_varargs_method("setUsePreestimatedLength", - &StdMeshers_MaxLengthPy::setUsePreestimatedLength, - "setUsePreestimatedLength()"); - add_varargs_method("getUsePreestimatedLength", - &StdMeshers_MaxLengthPy::getUsePreestimatedLength, - "getUsePreestimatedLength()"); + add_varargs_method( + "havePreestimatedLength", + &StdMeshers_MaxLengthPy::havePreestimatedLength, + "havePreestimatedLength()" + ); + add_varargs_method( + "getPreestimatedLength", + &StdMeshers_MaxLengthPy::getPreestimatedLength, + "getPreestimatedLength()" + ); + add_varargs_method( + "setPreestimatedLength", + &StdMeshers_MaxLengthPy::setPreestimatedLength, + "setPreestimatedLength()" + ); + add_varargs_method( + "setUsePreestimatedLength", + &StdMeshers_MaxLengthPy::setUsePreestimatedLength, + "setUsePreestimatedLength()" + ); + add_varargs_method( + "getUsePreestimatedLength", + &StdMeshers_MaxLengthPy::getUsePreestimatedLength, + "getUsePreestimatedLength()" + ); SMESH_HypothesisPyBase::init_type(module); } @@ -540,9 +569,7 @@ StdMeshers_QuadranglePreferencePy::StdMeshers_QuadranglePreferencePy(int hypId, : SMESH_HypothesisPyBase(new StdMeshers_QuadranglePreference(hypId, gen)) {} #else -StdMeshers_QuadranglePreferencePy::StdMeshers_QuadranglePreferencePy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_QuadranglePreferencePy::StdMeshers_QuadranglePreferencePy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_QuadranglePreference(hypId, studyId, gen)) {} #endif @@ -647,9 +674,7 @@ StdMeshers_CompositeSegment_1DPy::StdMeshers_CompositeSegment_1DPy(int hypId, SM : SMESH_HypothesisPyBase(new StdMeshers_CompositeSegment_1D(hypId, gen)) {} #else -StdMeshers_CompositeSegment_1DPy::StdMeshers_CompositeSegment_1DPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_CompositeSegment_1DPy::StdMeshers_CompositeSegment_1DPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_CompositeSegment_1D(hypId, studyId, gen)) {} #endif @@ -663,9 +688,7 @@ void StdMeshers_Deflection1DPy::init_type(PyObject* module) behaviors().name("StdMeshers_Deflection1D"); behaviors().doc("StdMeshers_Deflection1D"); - add_varargs_method("setDeflection", - &StdMeshers_Deflection1DPy::setDeflection, - "setDeflection()"); + add_varargs_method("setDeflection", &StdMeshers_Deflection1DPy::setDeflection, "setDeflection()"); SMESH_HypothesisPyBase::init_type(module); } @@ -735,15 +758,16 @@ StdMeshers_StartEndLengthPy::~StdMeshers_StartEndLengthPy() = default; Py::Object StdMeshers_StartEndLengthPy::setLength(const Py::Tuple& args) { - hypothesis()->SetLength((double)Py::Float(args[0]), - (bool)Py::Boolean(args[1])); + hypothesis()->SetLength( + (double)Py::Float(args[0]), + (bool)Py::Boolean(args[1]) + ); return Py::None(); } Py::Object StdMeshers_StartEndLengthPy::getLength(const Py::Tuple& args) { - return Py::Float( - hypothesis()->GetLength((bool)Py::Boolean(args[0]))); + return Py::Float(hypothesis()->GetLength((bool)Py::Boolean(args[0]))); } // --------------------------------------------------------------------------- @@ -752,24 +776,21 @@ void StdMeshers_SegmentLengthAroundVertexPy::init_type(PyObject* module) { behaviors().name("StdMeshers_SegmentLengthAroundVertex"); behaviors().doc("StdMeshers_SegmentLengthAroundVertex"); - add_varargs_method("setLength", - &StdMeshers_SegmentLengthAroundVertexPy::setLength, - "setLength()"); - add_varargs_method("getLength", - &StdMeshers_SegmentLengthAroundVertexPy::getLength, - "getLength()"); + add_varargs_method("setLength", &StdMeshers_SegmentLengthAroundVertexPy::setLength, "setLength()"); + add_varargs_method("getLength", &StdMeshers_SegmentLengthAroundVertexPy::getLength, "getLength()"); SMESH_HypothesisPyBase::init_type(module); } #if SMESH_VERSION_MAJOR >= 9 -StdMeshers_SegmentLengthAroundVertexPy::StdMeshers_SegmentLengthAroundVertexPy(int hypId, - SMESH_Gen* gen) +StdMeshers_SegmentLengthAroundVertexPy::StdMeshers_SegmentLengthAroundVertexPy(int hypId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_SegmentLengthAroundVertex(hypId, gen)) {} #else -StdMeshers_SegmentLengthAroundVertexPy::StdMeshers_SegmentLengthAroundVertexPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_SegmentLengthAroundVertexPy::StdMeshers_SegmentLengthAroundVertexPy( + int hypId, + int studyId, + SMESH_Gen* gen +) : SMESH_HypothesisPyBase(new StdMeshers_SegmentLengthAroundVertex(hypId, studyId, gen)) {} #endif @@ -804,9 +825,11 @@ StdMeshers_SegmentAroundVertex_0DPy::StdMeshers_SegmentAroundVertex_0DPy(int hyp : SMESH_HypothesisPyBase(new StdMeshers_SegmentAroundVertex_0D(hypId, gen)) {} #else -StdMeshers_SegmentAroundVertex_0DPy::StdMeshers_SegmentAroundVertex_0DPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_SegmentAroundVertex_0DPy::StdMeshers_SegmentAroundVertex_0DPy( + int hypId, + int studyId, + SMESH_Gen* gen +) : SMESH_HypothesisPyBase(new StdMeshers_SegmentAroundVertex_0D(hypId, studyId, gen)) {} #endif @@ -869,9 +892,7 @@ StdMeshers_ProjectionSource3DPy::StdMeshers_ProjectionSource3DPy(int hypId, SMES : SMESH_HypothesisPyBase(new StdMeshers_ProjectionSource3D(hypId, gen)) {} #else -StdMeshers_ProjectionSource3DPy::StdMeshers_ProjectionSource3DPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_ProjectionSource3DPy::StdMeshers_ProjectionSource3DPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_ProjectionSource3D(hypId, studyId, gen)) {} #endif @@ -892,9 +913,7 @@ StdMeshers_ProjectionSource2DPy::StdMeshers_ProjectionSource2DPy(int hypId, SMES : SMESH_HypothesisPyBase(new StdMeshers_ProjectionSource2D(hypId, gen)) {} #else -StdMeshers_ProjectionSource2DPy::StdMeshers_ProjectionSource2DPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_ProjectionSource2DPy::StdMeshers_ProjectionSource2DPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_ProjectionSource2D(hypId, studyId, gen)) {} #endif @@ -915,9 +934,7 @@ StdMeshers_ProjectionSource1DPy::StdMeshers_ProjectionSource1DPy(int hypId, SMES : SMESH_HypothesisPyBase(new StdMeshers_ProjectionSource1D(hypId, gen)) {} #else -StdMeshers_ProjectionSource1DPy::StdMeshers_ProjectionSource1DPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_ProjectionSource1DPy::StdMeshers_ProjectionSource1DPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_ProjectionSource1D(hypId, studyId, gen)) {} #endif @@ -1014,12 +1031,16 @@ void StdMeshers_NumberOfSegmentsPy::init_type(PyObject* module) { behaviors().name("StdMeshers_NumberOfSegments"); behaviors().doc("StdMeshers_NumberOfSegments"); - add_varargs_method("setNumberOfSegments", - &StdMeshers_NumberOfSegmentsPy::setNumSegm, - "setNumberOfSegments()"); - add_varargs_method("getNumberOfSegments", - &StdMeshers_NumberOfSegmentsPy::getNumSegm, - "getNumberOfSegments()"); + add_varargs_method( + "setNumberOfSegments", + &StdMeshers_NumberOfSegmentsPy::setNumSegm, + "setNumberOfSegments()" + ); + add_varargs_method( + "getNumberOfSegments", + &StdMeshers_NumberOfSegmentsPy::getNumSegm, + "getNumberOfSegments()" + ); SMESH_HypothesisPyBase::init_type(module); } @@ -1055,12 +1076,16 @@ void StdMeshers_NumberOfLayersPy::init_type(PyObject* module) { behaviors().name("StdMeshers_NumberOfLayers"); behaviors().doc("StdMeshers_NumberOfLayers"); - add_varargs_method("setNumberOfLayers", - &StdMeshers_NumberOfLayersPy::setNumLayers, - "setNumberOfLayers()"); - add_varargs_method("getNumberOfLayers", - &StdMeshers_NumberOfLayersPy::getNumLayers, - "getNumberOfLayers()"); + add_varargs_method( + "setNumberOfLayers", + &StdMeshers_NumberOfLayersPy::setNumLayers, + "setNumberOfLayers()" + ); + add_varargs_method( + "getNumberOfLayers", + &StdMeshers_NumberOfLayersPy::getNumLayers, + "getNumberOfLayers()" + ); SMESH_HypothesisPyBase::init_type(module); } @@ -1099,15 +1124,15 @@ void StdMeshers_MEFISTO_2DPy::init_type(PyObject* module) SMESH_HypothesisPyBase::init_type(module); } -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_MEFISTO_2DPy::StdMeshers_MEFISTO_2DPy(int hypId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_MEFISTO_2D(hypId, gen)) {} -#else +# else StdMeshers_MEFISTO_2DPy::StdMeshers_MEFISTO_2DPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_MEFISTO_2D(hypId, studyId, gen)) {} -#endif +# endif StdMeshers_MEFISTO_2DPy::~StdMeshers_MEFISTO_2DPy() = default; #endif @@ -1117,12 +1142,8 @@ void StdMeshers_MaxElementVolumePy::init_type(PyObject* module) { behaviors().name("StdMeshers_MaxElementVolume"); behaviors().doc("StdMeshers_MaxElementVolume"); - add_varargs_method("setMaxVolume", - &StdMeshers_MaxElementVolumePy::setMaxVolume, - "setMaxVolume()"); - add_varargs_method("getMaxVolume", - &StdMeshers_MaxElementVolumePy::getMaxVolume, - "getMaxVolume()"); + add_varargs_method("setMaxVolume", &StdMeshers_MaxElementVolumePy::setMaxVolume, "setMaxVolume()"); + add_varargs_method("getMaxVolume", &StdMeshers_MaxElementVolumePy::getMaxVolume, "getMaxVolume()"); SMESH_HypothesisPyBase::init_type(module); } @@ -1195,12 +1216,16 @@ void StdMeshers_LayerDistributionPy::init_type(PyObject* module) { behaviors().name("StdMeshers_LayerDistribution"); behaviors().doc("StdMeshers_LayerDistribution"); - add_varargs_method("setLayerDistribution", - &StdMeshers_LayerDistributionPy::setLayerDistribution, - "setLayerDistribution()"); - add_varargs_method("getLayerDistribution", - &StdMeshers_LayerDistributionPy::getLayerDistribution, - "getLayerDistribution()"); + add_varargs_method( + "setLayerDistribution", + &StdMeshers_LayerDistributionPy::setLayerDistribution, + "setLayerDistribution()" + ); + add_varargs_method( + "getLayerDistribution", + &StdMeshers_LayerDistributionPy::getLayerDistribution, + "getLayerDistribution()" + ); SMESH_HypothesisPyBase::init_type(module); } @@ -1209,9 +1234,7 @@ StdMeshers_LayerDistributionPy::StdMeshers_LayerDistributionPy(int hypId, SMESH_ : SMESH_HypothesisPyBase(new StdMeshers_LayerDistribution(hypId, gen)) {} #else -StdMeshers_LayerDistributionPy::StdMeshers_LayerDistributionPy(int hypId, - int studyId, - SMESH_Gen* gen) +StdMeshers_LayerDistributionPy::StdMeshers_LayerDistributionPy(int hypId, int studyId, SMESH_Gen* gen) : SMESH_HypothesisPyBase(new StdMeshers_LayerDistribution(hypId, studyId, gen)) {} #endif diff --git a/src/Mod/Fem/App/HypothesisPy.h b/src/Mod/Fem/App/HypothesisPy.h index 379ad7f0bb..56f2e47740 100644 --- a/src/Mod/Fem/App/HypothesisPy.h +++ b/src/Mod/Fem/App/HypothesisPy.h @@ -158,8 +158,7 @@ public: Py::Object getMaxArea(const Py::Tuple& args); }; -class StdMeshers_QuadranglePreferencePy - : public SMESH_HypothesisPy +class StdMeshers_QuadranglePreferencePy: public SMESH_HypothesisPy { public: static void init_type(PyObject*); @@ -347,7 +346,7 @@ public: Py::Object getNumLayers(const Py::Tuple& args); }; -#if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 +# if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 class StdMeshers_MEFISTO_2DPy: public SMESH_HypothesisPy { public: @@ -355,7 +354,7 @@ public: StdMeshers_MEFISTO_2DPy(int hypId, SMESH_Gen* gen); ~StdMeshers_MEFISTO_2DPy(); }; -#endif +# endif class StdMeshers_MaxElementVolumePy: public SMESH_HypothesisPy { @@ -458,8 +457,7 @@ public: Py::Object getMaxArea(const Py::Tuple& args); }; -class StdMeshers_QuadranglePreferencePy - : public SMESH_HypothesisPy +class StdMeshers_QuadranglePreferencePy: public SMESH_HypothesisPy { public: static void init_type(PyObject*); @@ -524,7 +522,7 @@ public: StdMeshers_Hexa_3DPy(int hypId, int studyId, SMESH_Gen* gen); ~StdMeshers_Hexa_3DPy() override; }; -#if SMESH_VERSION_MAJOR < 7 // ----------------------------------------------- +# if SMESH_VERSION_MAJOR < 7 // ----------------------------------------------- class StdMeshers_TrianglePreferencePy: public SMESH_HypothesisPy { public: @@ -532,7 +530,7 @@ public: StdMeshers_TrianglePreferencePy(int hypId, int studyId, SMESH_Gen* gen); ~StdMeshers_TrianglePreferencePy(); }; -#endif // -------------------------------------------------------------------- +# endif // -------------------------------------------------------------------- class StdMeshers_StartEndLengthPy: public SMESH_HypothesisPy { @@ -688,7 +686,7 @@ public: Py::Object getNumLayers(const Py::Tuple& args); }; -#if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 +# if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 class StdMeshers_MEFISTO_2DPy: public SMESH_HypothesisPy { public: @@ -696,7 +694,7 @@ public: StdMeshers_MEFISTO_2DPy(int hypId, int studyId, SMESH_Gen* gen); ~StdMeshers_MEFISTO_2DPy() override; }; -#endif +# endif class StdMeshers_MaxElementVolumePy: public SMESH_HypothesisPy { diff --git a/src/Mod/Fem/App/PreCompiled.h b/src/Mod/Fem/App/PreCompiled.h index cc812dda1b..fd94578e95 100644 --- a/src/Mod/Fem/App/PreCompiled.h +++ b/src/Mod/Fem/App/PreCompiled.h @@ -72,7 +72,7 @@ #include #include #if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 -#include +# include #endif #include #include @@ -106,7 +106,7 @@ #include #include #if OCC_VERSION_HEX < 0x070600 -#include +# include #endif #include #include @@ -152,7 +152,7 @@ #include #include #if VTK_VERSION_NUMBER >= VTK_VERSION_CHECK(9, 3, 0) -#include +# include #endif #include #include @@ -205,9 +205,9 @@ // Netgen #ifdef FCWithNetgen -#include -#include -#include +# include +# include +# include #endif #endif diff --git a/src/Mod/Fem/App/PropertyPostDataObject.cpp b/src/Mod/Fem/App/PropertyPostDataObject.cpp index 593058aa14..7614aec5bd 100644 --- a/src/Mod/Fem/App/PropertyPostDataObject.cpp +++ b/src/Mod/Fem/App/PropertyPostDataObject.cpp @@ -44,9 +44,9 @@ #ifdef FC_USE_VTK_PYTHON -#include +# include #else -#include +# include #endif #include @@ -60,7 +60,7 @@ #ifdef _MSC_VER -#include +# include #endif #include #include @@ -419,9 +419,11 @@ void PropertyPostDataObject::SaveDocFile(Base::Writer& writer) const App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().error("Dataset of '%s' cannot be written to vtk file '%s'\n", - obj->Label.getValue(), - fi.filePath().c_str()); + Base::Console().error( + "Dataset of '%s' cannot be written to vtk file '%s'\n", + obj->Label.getValue(), + fi.filePath().c_str() + ); } else { Base::Console().error("Cannot save vtk file '%s'\n", fi.filePath().c_str()); @@ -548,13 +550,17 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader& reader) App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().error("Dataset file '%s' with data of '%s' seems to be empty\n", - fi.filePath().c_str(), - obj->Label.getValue()); + Base::Console().error( + "Dataset file '%s' with data of '%s' seems to be empty\n", + fi.filePath().c_str(), + obj->Label.getValue() + ); } else { - Base::Console().warning("Loaded Dataset file '%s' seems to be empty\n", - fi.filePath().c_str()); + Base::Console().warning( + "Loaded Dataset file '%s' seems to be empty\n", + fi.filePath().c_str() + ); } } else { @@ -568,7 +574,8 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader& reader) Base::Console().error( "Dataset file '%s' is of unsupported type: %s. Data not loaded.\n", fi.filePath().c_str(), - extension); + extension + ); } } diff --git a/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.cxx b/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.cxx index baeaae7b75..4a7f1f6f07 100644 --- a/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.cxx +++ b/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.cxx @@ -6,32 +6,32 @@ #include "PreCompiled.h" #ifndef _PreComp_ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include -#include +# include #endif #include "vtkCleanUnstructuredGrid.h" @@ -132,7 +132,8 @@ unsigned char GetTopologicalDimension(vtkDataSet* ds) if (topoDim > MAX_CELL_DIM) { vtkErrorWithObjectMacro( nullptr, - "Topological dimension of data set is larger than the maximal cell dimension"); + "Topological dimension of data set is larger than the maximal cell dimension" + ); return MAX_CELL_DIM; } return topoDim; @@ -141,18 +142,23 @@ unsigned char GetTopologicalDimension(vtkDataSet* ds) struct WeighingStrategy { virtual ~WeighingStrategy() = default; - virtual vtkSmartPointer ComputeWeights(vtkDataSet* ds, - const std::vector& ptMap) = 0; + virtual vtkSmartPointer ComputeWeights( + vtkDataSet* ds, + const std::vector& ptMap + ) = 0; }; struct FirstPointStrategy: public WeighingStrategy { - vtkSmartPointer ComputeWeights(vtkDataSet* ds, - const std::vector& ptMap) override + vtkSmartPointer ComputeWeights( + vtkDataSet* ds, + const std::vector& ptMap + ) override { if (ds->GetNumberOfPoints() != static_cast(ptMap.size())) { vtkGenericWarningMacro( - "Number of points in dataset and number of entries in point map don't line up."); + "Number of points in dataset and number of entries in point map don't line up." + ); return nullptr; } vtkNew weights; @@ -174,12 +180,15 @@ struct FirstPointStrategy: public WeighingStrategy struct AveragingStrategy: public WeighingStrategy { - vtkSmartPointer ComputeWeights(vtkDataSet* ds, - const std::vector& ptMap) override + vtkSmartPointer ComputeWeights( + vtkDataSet* ds, + const std::vector& ptMap + ) override { if (ds->GetNumberOfPoints() != static_cast(ptMap.size())) { vtkGenericWarningMacro( - "Number of points in dataset and number of entries in point map don't line up."); + "Number of points in dataset and number of entries in point map don't line up." + ); return nullptr; } std::vector counts(ds->GetNumberOfPoints(), 0.0); @@ -209,12 +218,15 @@ struct AveragingStrategy: public WeighingStrategy struct SpatialDensityStrategy: public WeighingStrategy { - vtkSmartPointer ComputeWeights(vtkDataSet* ds, - const std::vector& ptMap) override + vtkSmartPointer ComputeWeights( + vtkDataSet* ds, + const std::vector& ptMap + ) override { if (ds->GetNumberOfPoints() != static_cast(ptMap.size())) { vtkGenericWarningMacro( - "Number of points in dataset and number of entries in point map don't line up."); + "Number of points in dataset and number of entries in point map don't line up." + ); return nullptr; } // Get topological dimension of data set @@ -233,7 +245,8 @@ struct SpatialDensityStrategy: public WeighingStrategy || !cData->HasArray("Area") || !cData->HasArray("Volume")) { vtkErrorWithObjectMacro( nullptr, - "Could not find correct cell data in output of cell size filter"); + "Could not find correct cell data in output of cell size filter" + ); return nullptr; } switch (topoDim) { @@ -250,9 +263,11 @@ struct SpatialDensityStrategy: public WeighingStrategy measures = cData->GetArray("Volume"); break; default: - vtkErrorWithObjectMacro(nullptr, - "Topological dimension of data set is higher than 3. " - "Cannot deal with that."); + vtkErrorWithObjectMacro( + nullptr, + "Topological dimension of data set is higher than 3. " + "Cannot deal with that." + ); return nullptr; } } @@ -302,18 +317,18 @@ struct SpatialDensityStrategy: public WeighingStrategy // Merits a dedicated struct with a reduce operation // collisions occurring in the += operation // vtkSMPTools::For(0, ds->GetNumberOfPoints(), computeMasses); - vtkSMPTools::For(0, - ds->GetNumberOfPoints(), - [&dRange, &masses, &ptMap](vtkIdType begin, vtkIdType end) { - for (vtkIdType iP = begin; iP < end; ++iP) { - if (ptMap[iP] < 0) { - continue; - } - dRange[iP] = - (masses[ptMap[iP]] != 0 ? dRange[iP] / masses[ptMap[iP]] - : 0.0); - } - }); + vtkSMPTools::For( + 0, + ds->GetNumberOfPoints(), + [&dRange, &masses, &ptMap](vtkIdType begin, vtkIdType end) { + for (vtkIdType iP = begin; iP < end; ++iP) { + if (ptMap[iP] < 0) { + continue; + } + dRange[iP] = (masses[ptMap[iP]] != 0 ? dRange[iP] / masses[ptMap[iP]] : 0.0); + } + } + ); } return density; } @@ -331,8 +346,10 @@ struct WeighingStrategyFactory case vtkCleanUnstructuredGrid::SPATIAL_DENSITY: return std::make_shared(); default: - vtkGenericWarningMacro("Incorrect weighing strategy type passed to factory. " - "defaulting to FIRST_POINT."); + vtkGenericWarningMacro( + "Incorrect weighing strategy type passed to factory. " + "defaulting to FIRST_POINT." + ); return std::make_shared(); } } @@ -341,10 +358,12 @@ struct WeighingStrategyFactory struct WeighingWorklet { template - void operator()(ArrayTypeIn* inArray, - ArrayTypeOut* outArray, - vtkDoubleArray* weights, - const std::vector& ptMap) + void operator()( + ArrayTypeIn* inArray, + ArrayTypeOut* outArray, + vtkDoubleArray* weights, + const std::vector& ptMap + ) { outArray->Fill(0); auto inRange = vtk::DataArrayTupleRange(inArray); @@ -370,10 +389,12 @@ struct WeighingWorklet }; template<> -void WeighingWorklet::operator()(vtkBitArray* inArray, - vtkBitArray* outArray, - vtkDoubleArray* vtkNotUsed(weights), - const std::vector& ptMap) +void WeighingWorklet::operator()( + vtkBitArray* inArray, + vtkBitArray* outArray, + vtkDoubleArray* vtkNotUsed(weights), + const std::vector& ptMap +) { outArray->Fill(0); for (vtkIdType iP = 0; iP < inArray->GetNumberOfValues(); ++iP) { @@ -385,10 +406,12 @@ void WeighingWorklet::operator()(vtkBitArray* inArray, } template<> -void WeighingWorklet::operator()(vtkStringArray* inArray, - vtkStringArray* outArray, - vtkDoubleArray* vtkNotUsed(weights), - const std::vector& ptMap) +void WeighingWorklet::operator()( + vtkStringArray* inArray, + vtkStringArray* outArray, + vtkDoubleArray* vtkNotUsed(weights), + const std::vector& ptMap +) { for (vtkIdType iP = 0; iP < inArray->GetNumberOfValues(); ++iP) { if (ptMap[iP] < 0) { @@ -399,10 +422,12 @@ void WeighingWorklet::operator()(vtkStringArray* inArray, } template<> -void WeighingWorklet::operator()(vtkAbstractArray* inArray, - vtkAbstractArray* outArray, - vtkDoubleArray* vtkNotUsed(weights), - const std::vector& ptMap) +void WeighingWorklet::operator()( + vtkAbstractArray* inArray, + vtkAbstractArray* outArray, + vtkDoubleArray* vtkNotUsed(weights), + const std::vector& ptMap +) { for (vtkIdType iP = 0; iP < inArray->GetNumberOfTuples(); ++iP) { if (ptMap[iP] < 0) { @@ -412,10 +437,12 @@ void WeighingWorklet::operator()(vtkAbstractArray* inArray, } } -void WeightAttributes(vtkPointData* inPD, - vtkPointData* outPD, - vtkDoubleArray* weights, - const std::vector& ptMap) +void WeightAttributes( + vtkPointData* inPD, + vtkPointData* outPD, + vtkDoubleArray* weights, + const std::vector& ptMap +) { // better here to use a Dispatch2BySameArrayType, but that doesn't exist using Dispatcher = vtkArrayDispatch::Dispatch2BySameValueType; @@ -439,9 +466,10 @@ void WeightAttributes(vtkPointData* inPD, if (inStrArr) { auto outStrArr = vtkStringArray::SafeDownCast(outAbsArr); if (!outStrArr) { - vtkGenericWarningMacro("Output array " - << inStrArr->GetName() - << " is not the same type as input string array."); + vtkGenericWarningMacro( + "Output array " << inStrArr->GetName() + << " is not the same type as input string array." + ); continue; } worker(inStrArr, outStrArr, weights, ptMap); @@ -452,8 +480,9 @@ void WeightAttributes(vtkPointData* inPD, } auto outArr = outPD->GetArray(inArr->GetName()); if (!outArr) { - vtkGenericWarningMacro("Output array " << inArr->GetName() - << " is nullptr or not a vtkDataArray."); + vtkGenericWarningMacro( + "Output array " << inArr->GetName() << " is nullptr or not a vtkDataArray." + ); continue; } if (!Dispatcher::Execute(inArr, outArr, worker, weights, ptMap)) { @@ -499,16 +528,19 @@ void vtkCleanUnstructuredGrid::PrintSelf(ostream& os, vtkIndent indent) } //---------------------------------------------------------------------------- -int vtkCleanUnstructuredGrid::RequestData(vtkInformation* vtkNotUsed(request), - vtkInformationVector** inputVector, - vtkInformationVector* outputVector) +int vtkCleanUnstructuredGrid::RequestData( + vtkInformation* vtkNotUsed(request), + vtkInformationVector** inputVector, + vtkInformationVector* outputVector +) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); vtkInformation* outInfo = outputVector->GetInformationObject(0); vtkDataSet* input = vtkDataSet::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); - vtkUnstructuredGrid* output = - vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkUnstructuredGrid* output = vtkUnstructuredGrid::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT()) + ); if (input->GetNumberOfCells() == 0) { // set up a ugrid with same data arrays as input, but diff --git a/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.h b/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.h index f3db74ce4d..db40380601 100644 --- a/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.h +++ b/src/Mod/Fem/App/VTKExtensions/vtkCleanUnstructuredGrid.h @@ -17,11 +17,11 @@ #ifndef vtkCleanUnstructuredGrid_h -#define vtkCleanUnstructuredGrid_h +# define vtkCleanUnstructuredGrid_h -#include "vtkFiltersGeneralModule.h" // For export macro -#include "vtkSmartPointer.h" -#include "vtkUnstructuredGridAlgorithm.h" +# include "vtkFiltersGeneralModule.h" // For export macro +# include "vtkSmartPointer.h" +# include "vtkUnstructuredGridAlgorithm.h" /*VTK_ABI_NAMESPACE_BEGIN*/ diff --git a/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.cpp b/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.cpp index 91574cf9d2..122a3fd175 100644 --- a/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.cpp +++ b/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.cpp @@ -24,17 +24,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 "vtkFemFrameSourceAlgorithm.h" @@ -101,9 +101,11 @@ std::vector vtkFemFrameSourceAlgorithm::getFrameValues() return tFrames; } -int vtkFemFrameSourceAlgorithm::RequestInformation(vtkInformation* reqInfo, - vtkInformationVector** inVector, - vtkInformationVector* outVector) +int vtkFemFrameSourceAlgorithm::RequestInformation( + vtkInformation* reqInfo, + vtkInformationVector** inVector, + vtkInformationVector* outVector +) { // setup default information @@ -134,13 +136,16 @@ int vtkFemFrameSourceAlgorithm::RequestInformation(vtkInformation* reqInfo, return 1; } -int vtkFemFrameSourceAlgorithm::RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector* outVector) +int vtkFemFrameSourceAlgorithm::RequestData( + vtkInformation*, + vtkInformationVector**, + vtkInformationVector* outVector +) { vtkInformation* outInfo = outVector->GetInformationObject(0); - vtkUnstructuredGrid* output = - vtkUnstructuredGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkUnstructuredGrid* output = vtkUnstructuredGrid::SafeDownCast( + outInfo->Get(vtkDataObject::DATA_OBJECT()) + ); if (!output) { return 0; diff --git a/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.h b/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.h index 62b309174a..ea7f338573 100644 --- a/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.h +++ b/src/Mod/Fem/App/VTKExtensions/vtkFemFrameSourceAlgorithm.h @@ -52,12 +52,16 @@ protected: vtkSmartPointer m_data; - int RequestInformation(vtkInformation* reqInfo, - vtkInformationVector** inVector, - vtkInformationVector* outVector) override; - int RequestData(vtkInformation* reqInfo, - vtkInformationVector** inVector, - vtkInformationVector* outVector) override; + int RequestInformation( + vtkInformation* reqInfo, + vtkInformationVector** inVector, + vtkInformationVector* outVector + ) override; + int RequestData( + vtkInformation* reqInfo, + vtkInformationVector** inVector, + vtkInformationVector* outVector + ) override; }; } // namespace Fem diff --git a/src/Mod/Fem/App/VTKExtensions/vtkSMPTools.h b/src/Mod/Fem/App/VTKExtensions/vtkSMPTools.h index 2c887b8d89..f7534c0275 100644 --- a/src/Mod/Fem/App/VTKExtensions/vtkSMPTools.h +++ b/src/Mod/Fem/App/VTKExtensions/vtkSMPTools.h @@ -28,19 +28,19 @@ */ #ifndef vtkSMPTools_h -#define vtkSMPTools_h +# define vtkSMPTools_h -#include "vtkCommonCoreModule.h" // For export macro -#include "vtkObject.h" +# include "vtkCommonCoreModule.h" // For export macro +# include "vtkObject.h" -#include "SMP/Common/vtkSMPToolsAPI.h" -#include "vtkSMPThreadLocal.h" // For Initialized +# include "SMP/Common/vtkSMPToolsAPI.h" +# include "vtkSMPThreadLocal.h" // For Initialized -#include // For std::function -#include // For std::iterator -#include // For std:::enable_if +# include // For std::function +# include // For std::iterator +# include // For std:::enable_if -#ifndef DOXYGEN_SHOULD_SKIP_THIS +# ifndef DOXYGEN_SHOULD_SKIP_THIS namespace vtk { namespace detail @@ -102,8 +102,9 @@ struct vtkSMPTools_FunctorInternal auto& SMPToolsAPI = vtkSMPToolsAPI::GetInstance(); SMPToolsAPI.For(first, last, grain, *this); } - vtkSMPTools_FunctorInternal& - operator=(const vtkSMPTools_FunctorInternal&); + vtkSMPTools_FunctorInternal& operator=( + const vtkSMPTools_FunctorInternal& + ); vtkSMPTools_FunctorInternal(const vtkSMPTools_FunctorInternal&); }; @@ -131,8 +132,9 @@ struct vtkSMPTools_FunctorInternal SMPToolsAPI.For(first, last, grain, *this); this->F.Reduce(); } - vtkSMPTools_FunctorInternal& - operator=(const vtkSMPTools_FunctorInternal&); + vtkSMPTools_FunctorInternal& operator=( + const vtkSMPTools_FunctorInternal& + ); vtkSMPTools_FunctorInternal(const vtkSMPTools_FunctorInternal&); }; @@ -226,7 +228,7 @@ using resolvedNotInt = typename std::enable_if::value, void } // namespace smp } // namespace detail } // namespace vtk -#endif // DOXYGEN_SHOULD_SKIP_THIS +# endif // DOXYGEN_SHOULD_SKIP_THIS class VTKCOMMONCORE_EXPORT vtkSMPTools { @@ -316,8 +318,7 @@ public: * \endcode */ template - static vtk::detail::smp::resolvedNotInt - For(Iter begin, Iter end, vtkIdType grain, Functor& f) + static vtk::detail::smp::resolvedNotInt For(Iter begin, Iter end, vtkIdType grain, Functor& f) { vtkIdType size = std::distance(begin, end); typename vtk::detail::smp::vtkSMPTools_Lookup_RangeFor::type fi(begin, f); @@ -325,12 +326,15 @@ public: } template - static vtk::detail::smp::resolvedNotInt - For(Iter begin, Iter end, vtkIdType grain, Functor const& f) + static vtk::detail::smp::resolvedNotInt For( + Iter begin, + Iter end, + vtkIdType grain, + Functor const& f + ) { vtkIdType size = std::distance(begin, end); - typename vtk::detail::smp::vtkSMPTools_Lookup_RangeFor::type fi(begin, - f); + typename vtk::detail::smp::vtkSMPTools_Lookup_RangeFor::type fi(begin, f); vtkSMPTools::For(0, size, grain, fi); } ///@} @@ -477,13 +481,13 @@ public: , Backend(backend) , NestedParallelism(nestedParallelism) {} -#ifndef DOXYGEN_SHOULD_SKIP_THIS +# ifndef DOXYGEN_SHOULD_SKIP_THIS Config(vtk::detail::smp::vtkSMPToolsAPI& API) : MaxNumberOfThreads(API.GetInternalDesiredNumberOfThread()) , Backend(API.GetBackend()) , NestedParallelism(API.GetNestedParallelism()) {} -#endif // DOXYGEN_SHOULD_SKIP_THIS +# endif // DOXYGEN_SHOULD_SKIP_THIS }; /** @@ -543,11 +547,13 @@ public: * Please visit vtkDataArrayRange.h documentation for more information and optimisation. */ template - static void Transform(InputIt1 inBegin1, - InputIt1 inEnd, - InputIt2 inBegin2, - OutputIt outBegin, - Functor transform) + static void Transform( + InputIt1 inBegin1, + InputIt1 inEnd, + InputIt2 inBegin2, + OutputIt outBegin, + Functor transform + ) { auto& SMPToolsAPI = vtk::detail::smp::vtkSMPToolsAPI::GetInstance(); SMPToolsAPI.Transform(inBegin1, inEnd, inBegin2, outBegin, transform); diff --git a/src/Mod/Fem/FemGlobal.h b/src/Mod/Fem/FemGlobal.h index a9e707885f..bc95b73e26 100644 --- a/src/Mod/Fem/FemGlobal.h +++ b/src/Mod/Fem/FemGlobal.h @@ -23,25 +23,25 @@ #include #ifndef FEM_GLOBAL_H -#define FEM_GLOBAL_H +# define FEM_GLOBAL_H // Fem -#ifndef FemExport -#ifdef Fem_EXPORTS -#define FemExport FREECAD_DECL_EXPORT -#else -#define FemExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef FemExport +# ifdef Fem_EXPORTS +# define FemExport FREECAD_DECL_EXPORT +# else +# define FemExport FREECAD_DECL_IMPORT +# endif +# endif // FemGui -#ifndef FemGuiExport -#ifdef FemGui_EXPORTS -#define FemGuiExport FREECAD_DECL_EXPORT -#else -#define FemGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef FemGuiExport +# ifdef FemGui_EXPORTS +# define FemGuiExport FREECAD_DECL_EXPORT +# else +# define FemGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // FEM_GLOBAL_H diff --git a/src/Mod/Fem/Gui/ActiveAnalysisObserver.cpp b/src/Mod/Fem/Gui/ActiveAnalysisObserver.cpp index 5bcde0bccc..c6c2771e18 100644 --- a/src/Mod/Fem/Gui/ActiveAnalysisObserver.cpp +++ b/src/Mod/Fem/Gui/ActiveAnalysisObserver.cpp @@ -52,7 +52,8 @@ void ActiveAnalysisObserver::setActiveObject(Fem::FemAnalysis* fem) App::Document* doc = fem->getDocument(); activeDocument = Gui::Application::Instance->getDocument(doc); activeView = static_cast( - activeDocument->getViewProvider(activeObject)); + activeDocument->getViewProvider(activeObject) + ); attachDocument(doc); } else { diff --git a/src/Mod/Fem/Gui/AppFemGui.cpp b/src/Mod/Fem/Gui/AppFemGui.cpp index 6e973d69ce..aa7bc3f0f5 100644 --- a/src/Mod/Fem/Gui/AppFemGui.cpp +++ b/src/Mod/Fem/Gui/AppFemGui.cpp @@ -69,11 +69,11 @@ #include "Workbench.h" #ifdef FC_USE_VTK -#include "ViewProviderFemPostFilter.h" -#include "ViewProviderFemPostFunction.h" -#include "ViewProviderFemPostObject.h" -#include "ViewProviderFemPostPipeline.h" -#include "ViewProviderFemPostBranchFilter.h" +# include "ViewProviderFemPostFilter.h" +# include "ViewProviderFemPostFunction.h" +# include "ViewProviderFemPostObject.h" +# include "ViewProviderFemPostPipeline.h" +# include "ViewProviderFemPostBranchFilter.h" #endif diff --git a/src/Mod/Fem/Gui/AppFemGuiPy.cpp b/src/Mod/Fem/Gui/AppFemGuiPy.cpp index da92308754..012ab3776c 100644 --- a/src/Mod/Fem/Gui/AppFemGuiPy.cpp +++ b/src/Mod/Fem/Gui/AppFemGuiPy.cpp @@ -43,18 +43,26 @@ public: Module() : Py::ExtensionModule("FemGui") { - add_varargs_method("setActiveAnalysis", - &Module::setActiveAnalysis, - "setActiveAnalysis(AnalysisObject) -- Set the Analysis object in work."); - add_varargs_method("getActiveAnalysis", - &Module::getActiveAnalysis, - "getActiveAnalysis() -- Returns the Analysis object in work."); - add_varargs_method("open", - &Module::open, - "open(string) -- Opens an Abaqus file in a text editor."); - add_varargs_method("insert", - &Module::open, - "insert(string,string) -- Opens an Abaqus file in a text editor."); + add_varargs_method( + "setActiveAnalysis", + &Module::setActiveAnalysis, + "setActiveAnalysis(AnalysisObject) -- Set the Analysis object in work." + ); + add_varargs_method( + "getActiveAnalysis", + &Module::getActiveAnalysis, + "getActiveAnalysis() -- Returns the Analysis object in work." + ); + add_varargs_method( + "open", + &Module::open, + "open(string) -- Opens an Abaqus file in a text editor." + ); + add_varargs_method( + "insert", + &Module::open, + "insert(string,string) -- Opens an Abaqus file in a text editor." + ); initialize("This module is the FemGui module."); // register with Python } @@ -76,26 +84,30 @@ private: if (FemGui::ActiveAnalysisObserver::instance()->hasActiveObject()) { FemGui::ActiveAnalysisObserver::instance()->highlightActiveObject( Gui::HighlightMode::Blue, - false); + false + ); FemGui::ActiveAnalysisObserver::instance()->setActiveObject(nullptr); } PyObject* object = nullptr; - if (PyArg_ParseTuple(args.ptr(), "|O!", &(App::DocumentObjectPy::Type), &object) - && object) { - App::DocumentObject* obj = - static_cast(object)->getDocumentObjectPtr(); + if (PyArg_ParseTuple(args.ptr(), "|O!", &(App::DocumentObjectPy::Type), &object) && object) { + App::DocumentObject* obj + = static_cast(object)->getDocumentObjectPtr(); if (!obj || !obj->isDerivedFrom()) { - throw Py::Exception(Base::PyExc_FC_GeneralError, - "Active Analysis object have to be of type Fem::FemAnalysis!"); + throw Py::Exception( + Base::PyExc_FC_GeneralError, + "Active Analysis object have to be of type Fem::FemAnalysis!" + ); } // get the gui document of the Analysis Item FemGui::ActiveAnalysisObserver::instance()->setActiveObject( - static_cast(obj)); + static_cast(obj) + ); FemGui::ActiveAnalysisObserver::instance()->highlightActiveObject( Gui::HighlightMode::UserDefined, - true); + true + ); } return Py::None(); @@ -107,7 +119,8 @@ private: } if (FemGui::ActiveAnalysisObserver::instance()->hasActiveObject()) { return Py::asObject( - FemGui::ActiveAnalysisObserver::instance()->getActiveObject()->getPyObject()); + FemGui::ActiveAnalysisObserver::instance()->getActiveObject()->getPyObject() + ); } return Py::None(); } diff --git a/src/Mod/Fem/Gui/Command.cpp b/src/Mod/Fem/Gui/Command.cpp index 0c24a9c458..4da7160b30 100644 --- a/src/Mod/Fem/Gui/Command.cpp +++ b/src/Mod/Fem/Gui/Command.cpp @@ -57,9 +57,9 @@ #include "FemSettings.h" #ifdef FC_USE_VTK -#include -#include -#include +# include +# include +# include #endif @@ -71,9 +71,11 @@ using namespace std; static bool getConstraintPrerequisits(Fem::FemAnalysis** Analysis) { if (!FemGui::ActiveAnalysisObserver::instance()->hasActiveObject()) { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("No active Analysis"), - QObject::tr("You need to create or activate a Analysis")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No active Analysis"), + QObject::tr("You need to create or activate a Analysis") + ); return true; } @@ -117,14 +119,15 @@ static std::string getSelectedNodes(Gui::View3DInventorViewer* view) polygon.Add(Base::Vector2d(it[0], it[1])); } - std::vector docObj = - Gui::Selection().getObjectsOfType(Fem::FemMeshObject::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Fem::FemMeshObject::getClassTypeId() + ); if (docObj.size() != 1) { return {}; } - const SMESHDS_Mesh* data = - static_cast(docObj[0])->FemMesh.getValue().getSMesh()->GetMeshDS(); + const SMESHDS_Mesh* data + = static_cast(docObj[0])->FemMesh.getValue().getSMesh()->GetMeshDS(); SMDS_NodeIteratorPtr aNodeIter = data->nodesIterator(); Base::Vector3f pt2d; @@ -256,13 +259,13 @@ void CmdFemConstraintBearing::activated(int) std::string FeatName = getUniqueObjectName("ConstraintBearing"); openCommand(QT_TRANSLATE_NOOP("Command", "Make bearing constraint")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintBearing\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintBearing\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -304,31 +307,43 @@ void CmdFemConstraintContact::activated(int) std::string FeatName = getUniqueObjectName("ConstraintContact"); openCommand(QT_TRANSLATE_NOOP("Command", "Make contact constraint on a face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintContact\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Slope = \"1e6 GPa/m\"", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.Adjust = 0.0", - FeatName.c_str()); // OvG: set default equal to 0 - doCommand(Doc, - "App.activeDocument().%s.Friction = False", - FeatName.c_str()); // OvG: set default equal to 0 - doCommand(Doc, - "App.activeDocument().%s.FrictionCoefficient = 0.0", - FeatName.c_str()); // OvG: set default equal to 0 - doCommand(Doc, - "App.activeDocument().%s.StickSlope = \"1e4 GPa/m\"", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintContact\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.Slope = \"1e6 GPa/m\"", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.Adjust = 0.0", + FeatName.c_str() + ); // OvG: set default equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.Friction = False", + FeatName.c_str() + ); // OvG: set default equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.FrictionCoefficient = 0.0", + FeatName.c_str() + ); // OvG: set default equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.StickSlope = \"1e4 GPa/m\"", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -370,15 +385,19 @@ void CmdFemConstraintDisplacement::activated(int) std::string FeatName = getUniqueObjectName("ConstraintDisplacement"); openCommand(QT_TRANSLATE_NOOP("Command", "Make displacement boundary condition on face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintDisplacement\",\"%s\")", - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintDisplacement\",\"%s\")", + FeatName.c_str() + ); // OvG: set initial scale to 1 doCommand(Doc, "App.activeDocument().%s.Scale = 1", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -420,15 +439,15 @@ void CmdFemConstraintFixed::activated(int) std::string FeatName = getUniqueObjectName("ConstraintFixed"); openCommand(QT_TRANSLATE_NOOP("Command", "Make fixed boundary condition for geometry")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintFixed\",\"%s\")", - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintFixed\",\"%s\")", FeatName.c_str()); // OvG: set initial scale to 1 doCommand(Doc, "App.activeDocument().%s.Scale = 1", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -470,20 +489,28 @@ void CmdFemConstraintRigidBody::activated(int) std::string FeatName = getUniqueObjectName("ConstraintRigidBody"); openCommand(QT_TRANSLATE_NOOP("Command", "Make rigid body constraint")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintRigidBody\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintRigidBody\",\"%s\")", + FeatName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); - doCommand(Doc, - "%s", - gethideMeshShowPartStr(FeatName).c_str()); // OvG: Hide meshes and show parts + doCommand( + Doc, + "%s", + gethideMeshShowPartStr(FeatName).c_str() + ); // OvG: Hide meshes and show parts updateActive(); @@ -505,8 +532,9 @@ CmdFemConstraintFluidBoundary::CmdFemConstraintFluidBoundary() sAppModule = "Fem"; sGroup = QT_TR_NOOP("Fem"); sMenuText = QT_TR_NOOP("Fluid Boundary Condition"); - sToolTipText = - QT_TR_NOOP("Create fluid boundary condition on face entity for Computional Fluid Dynamics"); + sToolTipText = QT_TR_NOOP( + "Create fluid boundary condition on face entity for Computional Fluid Dynamics" + ); sWhatsThis = "FEM_ConstraintFluidBoundary"; sStatusTip = sToolTipText; sPixmap = "FEM_ConstraintFluidBoundary"; @@ -523,17 +551,23 @@ void CmdFemConstraintFluidBoundary::activated(int) std::string FeatName = getUniqueObjectName("ConstraintFluidBoundary"); openCommand(QT_TRANSLATE_NOOP("Command", "Create fluid boundary condition")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintFluidBoundary\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintFluidBoundary\",\"%s\")", + FeatName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 // BoundaryValue is already the default value, zero is acceptable - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -574,22 +608,28 @@ void CmdFemConstraintForce::activated(int) std::string FeatName = getUniqueObjectName("ConstraintForce"); openCommand(QT_TRANSLATE_NOOP("Command", "Make force load on geometry")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintForce\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Force = \"1 N\"", - FeatName.c_str()); // OvG: set default to 1 N - doCommand(Doc, - "App.activeDocument().%s.Reversed = False", - FeatName.c_str()); // OvG: set default to False - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintForce\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.Force = \"1 N\"", + FeatName.c_str() + ); // OvG: set default to 1 N + doCommand( + Doc, + "App.activeDocument().%s.Reversed = False", + FeatName.c_str() + ); // OvG: set default to False + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -630,14 +670,14 @@ void CmdFemConstraintGear::activated(int) std::string FeatName = getUniqueObjectName("ConstraintGear"); openCommand(QT_TRANSLATE_NOOP("Command", "Make gear constraint")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintGear\",\"%s\")", - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintGear\",\"%s\")", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Diameter = 100.0", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -679,26 +719,38 @@ void CmdFemConstraintHeatflux::activated(int) std::string FeatName = getUniqueObjectName("ConstraintHeatflux"); openCommand(QT_TRANSLATE_NOOP("Command", "Make heat flux load on face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintHeatflux\",\"%s\")", - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintHeatflux\",\"%s\")", + FeatName.c_str() + ); doCommand(Doc, "App.activeDocument().%s.ConstraintType = \"DFlux\"", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.AmbientTemp = 300.0", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.FilmCoef = 10.0", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.Emissivity = 1.0", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.AmbientTemp = 300.0", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.FilmCoef = 10.0", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.Emissivity = 1.0", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr().c_str()); @@ -740,16 +792,22 @@ void CmdFemConstraintInitialTemperature::activated(int) std::string FeatName = getUniqueObjectName("ConstraintInitialTemperature"); openCommand(QT_TRANSLATE_NOOP("Command", "Make initial temperature condition on body")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintInitialTemperature\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintInitialTemperature\",\"%s\")", + FeatName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr().c_str()); @@ -791,16 +849,22 @@ void CmdFemConstraintPlaneRotation::activated(int) std::string FeatName = getUniqueObjectName("ConstraintPlaneRotation"); openCommand(QT_TRANSLATE_NOOP("Command", "Make plane multi-point constraint on face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintPlaneRotation\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintPlaneRotation\",\"%s\")", + FeatName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -842,21 +906,29 @@ void CmdFemConstraintPressure::activated(int) std::string FeatName = getUniqueObjectName("ConstraintPressure"); openCommand(QT_TRANSLATE_NOOP("Command", "Make pressure load on face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintPressure\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Pressure = 0.1", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.Reversed = False", - FeatName.c_str()); // OvG: set default to False + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintPressure\",\"%s\")", + FeatName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Pressure = 0.1", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.Reversed = False", + FeatName.c_str() + ); // OvG: set default to False // OvG: set initial scale to 1 doCommand(Doc, "App.activeDocument().%s.Scale = 1", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -898,21 +970,25 @@ void CmdFemConstraintSpring::activated(int) std::string FeatName = getUniqueObjectName("ConstraintSpring"); openCommand(QT_TRANSLATE_NOOP("Command", "Make Spring Constraint")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintSpring\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.NormalStiffness = 1.0", - FeatName.c_str()); // OvG: set default not equal to 0 - doCommand(Doc, - "App.activeDocument().%s.TangentialStiffness = 0.0", - FeatName.c_str()); // OvG: set default to False + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintSpring\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.NormalStiffness = 1.0", + FeatName.c_str() + ); // OvG: set default not equal to 0 + doCommand( + Doc, + "App.activeDocument().%s.TangentialStiffness = 0.0", + FeatName.c_str() + ); // OvG: set default to False // OvG: set initial scale to 1 doCommand(Doc, "App.activeDocument().%s.Scale = 1", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -953,18 +1029,18 @@ void CmdFemConstraintPulley::activated(int) std::string FeatName = getUniqueObjectName("ConstraintPulley"); openCommand(QT_TRANSLATE_NOOP("Command", "Make pulley constraint")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintPulley\",\"%s\")", - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintPulley\",\"%s\")", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Diameter = 300.0", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.OtherDiameter = 100.0", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.CenterDistance = 500.0", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Force = 100.0", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.TensionForce = 100.0", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -1006,16 +1082,22 @@ void CmdFemConstraintTemperature::activated(int) std::string FeatName = getUniqueObjectName("ConstraintTemperature"); openCommand(QT_TRANSLATE_NOOP("Command", "Make temperature boundary condition on face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintTemperature\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Scale = 1", - FeatName.c_str()); // OvG: set initial scale to 1 - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintTemperature\",\"%s\")", + FeatName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Scale = 1", + FeatName.c_str() + ); // OvG: set initial scale to 1 + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr().c_str()); @@ -1057,14 +1139,18 @@ void CmdFemConstraintTransform::activated(int) std::string FeatName = getUniqueObjectName("ConstraintTransform"); openCommand(QT_TRANSLATE_NOOP("Command", "Make local coordinate system on face")); - doCommand(Doc, - "App.activeDocument().addObject(\"Fem::ConstraintTransform\",\"%s\")", - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Fem::ConstraintTransform\",\"%s\")", + FeatName.c_str() + ); doCommand(Doc, "App.activeDocument().%s.Scale = 1", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.addObject(App.activeDocument().%s)", - Analysis->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + Analysis->getNameInDocument(), + FeatName.c_str() + ); // OvG: Hide meshes and show parts doCommand(Doc, "%s", gethideMeshShowPartStr(FeatName).c_str()); @@ -1107,14 +1193,20 @@ static void DefineNodesCallback(void* ud, SoEventCallback* n) std::string str = getSelectedNodes(view); if (!str.empty()) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Place robot")); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.addObject('Fem::FemSetNodesObject','NodeSet')"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.ActiveObject.Nodes = %s", - str.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.activeDocument().%s.addObject(App.activeDocument().NodeSet)", - Analysis->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.addObject('Fem::FemSetNodesObject','NodeSet')" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.ActiveObject.Nodes = %s", + str.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.activeDocument().%s.addObject(App.activeDocument().NodeSet)", + Analysis->getNameInDocument() + ); Gui::Command::commitCommand(); } @@ -1135,11 +1227,11 @@ CmdFemDefineNodesSet::CmdFemDefineNodesSet() void CmdFemDefineNodesSet::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Fem::FemMeshObject::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Fem::FemMeshObject::getClassTypeId() + ); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -1198,32 +1290,35 @@ void CmdFemCreateNodesSet::activated(int) Gui::SelectionFilter FemMeshFilter("SELECT Fem::FemMeshObject COUNT 1"); if (ObjectFilter.match()) { - Fem::FemSetNodesObject* NodesObj = - static_cast(ObjectFilter.Result[0][0].getObject()); + Fem::FemSetNodesObject* NodesObj = static_cast( + ObjectFilter.Result[0][0].getObject() + ); openCommand(QT_TRANSLATE_NOOP("Command", "Edit nodes set")); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", NodesObj->getNameInDocument()); } else if (FemMeshFilter.match()) { - Fem::FemMeshObject* MeshObj = - static_cast(FemMeshFilter.Result[0][0].getObject()); + Fem::FemMeshObject* MeshObj = static_cast( + FemMeshFilter.Result[0][0].getObject() + ); std::string FeatName = getUniqueObjectName("NodesSet"); openCommand(QT_TRANSLATE_NOOP("Command", "Create nodes set")); - doCommand(Doc, - "App.activeDocument().addObject('Fem::FemSetNodesObject','%s')", - FeatName.c_str()); - doCommand(Gui, - "App.activeDocument().%s.FemMesh = App.activeDocument().%s", - FeatName.c_str(), - MeshObj->getNameInDocument()); + doCommand(Doc, "App.activeDocument().addObject('Fem::FemSetNodesObject','%s')", FeatName.c_str()); + doCommand( + Gui, + "App.activeDocument().%s.FemMesh = App.activeDocument().%s", + FeatName.c_str(), + MeshObj->getNameInDocument() + ); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } else { QMessageBox::warning( Gui::getMainWindow(), qApp->translate("CmdFemCreateNodesSet", "Wrong selection"), - qApp->translate("CmdFemCreateNodesSet", "Select a single FEM mesh or nodes set.")); + qApp->translate("CmdFemCreateNodesSet", "Select a single FEM mesh or nodes set.") + ); } } @@ -1260,14 +1355,18 @@ static void DefineElementsCallback(void* ud, SoEventCallback* n) Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Place robot")); Gui::Command::doCommand( Gui::Command::Doc, - "App.ActiveDocument.addObject('Fem::FemSetElementNodesObject','ElementSet')"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.ActiveObject.Nodes = %s", - str.c_str()); + "App.ActiveDocument.addObject('Fem::FemSetElementNodesObject','ElementSet')" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.ActiveObject.Nodes = %s", + str.c_str() + ); Gui::Command::doCommand( Gui::Command::Doc, "App.activeDocument().%s.addObject(App.activeDocument().ElementSet)", - Analysis->getNameInDocument()); + Analysis->getNameInDocument() + ); Gui::Command::commitCommand(); } @@ -1287,11 +1386,11 @@ CmdFemDefineElementsSet::CmdFemDefineElementsSet() void CmdFemDefineElementsSet::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Fem::FemMeshObject::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Fem::FemMeshObject::getClassTypeId() + ); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -1299,8 +1398,7 @@ void CmdFemDefineElementsSet::activated(int) Gui::View3DInventorViewer* viewer = ((Gui::View3DInventor*)view)->getViewer(); viewer->setEditing(true); viewer->startSelection(Gui::View3DInventorViewer::Clip); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - DefineElementsCallback); + viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), DefineElementsCallback); } else { return; @@ -1346,33 +1444,41 @@ void CmdFemCreateElementsSet::activated(int) Gui::SelectionFilter FemMeshFilter("SELECT Fem::FemMeshObject COUNT 1"); if (ObjectFilter.match()) { - Fem::FemSetElementNodesObject* NodesObj = - static_cast(ObjectFilter.Result[0][0].getObject()); + Fem::FemSetElementNodesObject* NodesObj = static_cast( + ObjectFilter.Result[0][0].getObject() + ); openCommand(QT_TRANSLATE_NOOP("Command", "Edit Elements set")); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", NodesObj->getNameInDocument()); } // start else if (FemMeshFilter.match()) { - Fem::FemMeshObject* MeshObj = - static_cast(FemMeshFilter.Result[0][0].getObject()); + Fem::FemMeshObject* MeshObj = static_cast( + FemMeshFilter.Result[0][0].getObject() + ); std::string elementsName = Fem::FemSetElementNodesObject::getElementName(); std::string uniqueElementsName = Command::getUniqueObjectName(elementsName.c_str()); openCommand(QT_TRANSLATE_NOOP("Command", "Create Elements set")); - doCommand(Doc, - "App.activeDocument().addObject('Fem::FemSetElementNodesObject','%s')", - uniqueElementsName.c_str()); - doCommand(Gui, - "App.activeDocument().%s.FemMesh = App.activeDocument().%s", - uniqueElementsName.c_str(), - MeshObj->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().addObject('Fem::FemSetElementNodesObject','%s')", + uniqueElementsName.c_str() + ); + doCommand( + Gui, + "App.activeDocument().%s.FemMesh = App.activeDocument().%s", + uniqueElementsName.c_str(), + MeshObj->getNameInDocument() + ); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", uniqueElementsName.c_str()); } else { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), - qApp->translate("CmdFemCreateNodesSet", "Select a single FEM Mesh.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), + qApp->translate("CmdFemCreateNodesSet", "Select a single FEM Mesh.") + ); } } @@ -1467,56 +1573,97 @@ void CmdFemCompEmConstraints::languageChange() Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); - Gui::Command* ConstraintElectrostaticPotential = - rcCmdMgr.getCommandByName("FEM_ConstraintElectrostaticPotential"); + Gui::Command* ConstraintElectrostaticPotential = rcCmdMgr.getCommandByName( + "FEM_ConstraintElectrostaticPotential" + ); if (ConstraintElectrostaticPotential) { QAction* cmd0 = a[0]; - cmd0->setText(QApplication::translate("FEM_ConstraintElectrostaticPotential", - ConstraintElectrostaticPotential->getMenuText())); + cmd0->setText( + QApplication::translate( + "FEM_ConstraintElectrostaticPotential", + ConstraintElectrostaticPotential->getMenuText() + ) + ); cmd0->setToolTip( - QApplication::translate("FEM_ConstraintElectrostaticPotential", - ConstraintElectrostaticPotential->getToolTipText())); + QApplication::translate( + "FEM_ConstraintElectrostaticPotential", + ConstraintElectrostaticPotential->getToolTipText() + ) + ); cmd0->setStatusTip( - QApplication::translate("FEM_ConstraintElectrostaticPotential", - ConstraintElectrostaticPotential->getStatusTip())); + QApplication::translate( + "FEM_ConstraintElectrostaticPotential", + ConstraintElectrostaticPotential->getStatusTip() + ) + ); } - Gui::Command* ConstraintCurrentDensity = - rcCmdMgr.getCommandByName("FEM_ConstraintCurrentDensity"); + Gui::Command* ConstraintCurrentDensity = rcCmdMgr.getCommandByName("FEM_ConstraintCurrentDensity"); if (ConstraintCurrentDensity) { QAction* cmd1 = a[1]; - cmd1->setText(QApplication::translate("FEM_ConstraintCurrentDensity", - ConstraintCurrentDensity->getMenuText())); - cmd1->setToolTip(QApplication::translate("FEM_ConstraintCurrentDensity", - ConstraintCurrentDensity->getToolTipText())); - cmd1->setStatusTip(QApplication::translate("FEM_ConstraintCurrentDensity", - ConstraintCurrentDensity->getStatusTip())); + cmd1->setText( + QApplication::translate( + "FEM_ConstraintCurrentDensity", + ConstraintCurrentDensity->getMenuText() + ) + ); + cmd1->setToolTip( + QApplication::translate( + "FEM_ConstraintCurrentDensity", + ConstraintCurrentDensity->getToolTipText() + ) + ); + cmd1->setStatusTip( + QApplication::translate( + "FEM_ConstraintCurrentDensity", + ConstraintCurrentDensity->getStatusTip() + ) + ); } - Gui::Command* ConstraintMagnetization = - rcCmdMgr.getCommandByName("FEM_ConstraintMagnetization"); + Gui::Command* ConstraintMagnetization = rcCmdMgr.getCommandByName("FEM_ConstraintMagnetization"); if (ConstraintMagnetization) { QAction* cmd2 = a[2]; - cmd2->setText(QApplication::translate("FEM_ConstraintMagnetization", - ConstraintMagnetization->getMenuText())); - cmd2->setToolTip(QApplication::translate("FEM_ConstraintMagnetization", - ConstraintMagnetization->getToolTipText())); - cmd2->setStatusTip(QApplication::translate("FEM_ConstraintMagnetization", - ConstraintMagnetization->getStatusTip())); + cmd2->setText( + QApplication::translate("FEM_ConstraintMagnetization", ConstraintMagnetization->getMenuText()) + ); + cmd2->setToolTip( + QApplication::translate( + "FEM_ConstraintMagnetization", + ConstraintMagnetization->getToolTipText() + ) + ); + cmd2->setStatusTip( + QApplication::translate( + "FEM_ConstraintMagnetization", + ConstraintMagnetization->getStatusTip() + ) + ); } - Gui::Command* ConstraintElectricChargeDensity = - rcCmdMgr.getCommandByName("FEM_ConstraintElectricChargeDensity"); + Gui::Command* ConstraintElectricChargeDensity = rcCmdMgr.getCommandByName( + "FEM_ConstraintElectricChargeDensity" + ); if (ConstraintElectricChargeDensity) { QAction* cmd3 = a[3]; - cmd3->setText(QApplication::translate("FEM_ConstraintElectricChargeDensity", - ConstraintElectricChargeDensity->getMenuText())); + cmd3->setText( + QApplication::translate( + "FEM_ConstraintElectricChargeDensity", + ConstraintElectricChargeDensity->getMenuText() + ) + ); cmd3->setToolTip( - QApplication::translate("FEM_ConstraintElectricChargeDensity", - ConstraintElectricChargeDensity->getToolTipText())); + QApplication::translate( + "FEM_ConstraintElectricChargeDensity", + ConstraintElectricChargeDensity->getToolTipText() + ) + ); cmd3->setStatusTip( - QApplication::translate("FEM_ConstraintElectricChargeDensity", - ConstraintElectricChargeDensity->getStatusTip())); + QApplication::translate( + "FEM_ConstraintElectricChargeDensity", + ConstraintElectricChargeDensity->getStatusTip() + ) + ); } } @@ -1618,57 +1765,83 @@ void CmdFemCompEmEquations::languageChange() Gui::Command* EquationElectrostatic = rcCmdMgr.getCommandByName("FEM_EquationElectrostatic"); if (EquationElectrostatic) { QAction* cmd0 = a[0]; - cmd0->setText(QApplication::translate("FEM_EquationElectrostatic", - EquationElectrostatic->getMenuText())); - cmd0->setToolTip(QApplication::translate("FEM_EquationElectrostatic", - EquationElectrostatic->getToolTipText())); - cmd0->setStatusTip(QApplication::translate("FEM_EquationElectrostatic", - EquationElectrostatic->getStatusTip())); + cmd0->setText( + QApplication::translate("FEM_EquationElectrostatic", EquationElectrostatic->getMenuText()) + ); + cmd0->setToolTip( + QApplication::translate("FEM_EquationElectrostatic", EquationElectrostatic->getToolTipText()) + ); + cmd0->setStatusTip( + QApplication::translate("FEM_EquationElectrostatic", EquationElectrostatic->getStatusTip()) + ); } Gui::Command* EquationElectricforce = rcCmdMgr.getCommandByName("FEM_EquationElectricforce"); if (EquationElectricforce) { QAction* cmd1 = a[1]; - cmd1->setText(QApplication::translate("FEM_EquationElectricforce", - EquationElectricforce->getMenuText())); - cmd1->setToolTip(QApplication::translate("FEM_EquationElectricforce", - EquationElectricforce->getToolTipText())); - cmd1->setStatusTip(QApplication::translate("FEM_EquationElectricforce", - EquationElectricforce->getStatusTip())); + cmd1->setText( + QApplication::translate("FEM_EquationElectricforce", EquationElectricforce->getMenuText()) + ); + cmd1->setToolTip( + QApplication::translate("FEM_EquationElectricforce", EquationElectricforce->getToolTipText()) + ); + cmd1->setStatusTip( + QApplication::translate("FEM_EquationElectricforce", EquationElectricforce->getStatusTip()) + ); } Gui::Command* EquationMagnetodynamic = rcCmdMgr.getCommandByName("FEM_EquationMagnetodynamic"); if (EquationMagnetodynamic) { QAction* cmd2 = a[2]; - cmd2->setText(QApplication::translate("FEM_EquationMagnetodynamic", - EquationMagnetodynamic->getMenuText())); - cmd2->setToolTip(QApplication::translate("FEM_EquationMagnetodynamic", - EquationMagnetodynamic->getToolTipText())); - cmd2->setStatusTip(QApplication::translate("FEM_EquationMagnetodynamic", - EquationMagnetodynamic->getStatusTip())); + cmd2->setText( + QApplication::translate("FEM_EquationMagnetodynamic", EquationMagnetodynamic->getMenuText()) + ); + cmd2->setToolTip( + QApplication::translate( + "FEM_EquationMagnetodynamic", + EquationMagnetodynamic->getToolTipText() + ) + ); + cmd2->setStatusTip( + QApplication::translate("FEM_EquationMagnetodynamic", EquationMagnetodynamic->getStatusTip()) + ); } - Gui::Command* EquationMagnetodynamic2D = - rcCmdMgr.getCommandByName("FEM_EquationMagnetodynamic2D"); + Gui::Command* EquationMagnetodynamic2D = rcCmdMgr.getCommandByName("FEM_EquationMagnetodynamic2D"); if (EquationMagnetodynamic2D) { QAction* cmd3 = a[3]; - cmd3->setText(QApplication::translate("FEM_EquationMagnetodynamic2D", - EquationMagnetodynamic2D->getMenuText())); - cmd3->setToolTip(QApplication::translate("FEM_EquationMagnetodynamic2D", - EquationMagnetodynamic2D->getToolTipText())); - cmd3->setStatusTip(QApplication::translate("FEM_EquationMagnetodynamic2D", - EquationMagnetodynamic2D->getStatusTip())); + cmd3->setText( + QApplication::translate( + "FEM_EquationMagnetodynamic2D", + EquationMagnetodynamic2D->getMenuText() + ) + ); + cmd3->setToolTip( + QApplication::translate( + "FEM_EquationMagnetodynamic2D", + EquationMagnetodynamic2D->getToolTipText() + ) + ); + cmd3->setStatusTip( + QApplication::translate( + "FEM_EquationMagnetodynamic2D", + EquationMagnetodynamic2D->getStatusTip() + ) + ); } Gui::Command* EquationStaticCurrent = rcCmdMgr.getCommandByName("FEM_EquationStaticCurrent"); if (EquationStaticCurrent) { QAction* cmd4 = a[4]; - cmd4->setText(QApplication::translate("FEM_EquationStaticCurrent", - EquationStaticCurrent->getMenuText())); - cmd4->setToolTip(QApplication::translate("FEM_EquationStaticCurrent", - EquationStaticCurrent->getToolTipText())); - cmd4->setStatusTip(QApplication::translate("FEM_EquationStaticCurrent", - EquationStaticCurrent->getStatusTip())); + cmd4->setText( + QApplication::translate("FEM_EquationStaticCurrent", EquationStaticCurrent->getMenuText()) + ); + cmd4->setToolTip( + QApplication::translate("FEM_EquationStaticCurrent", EquationStaticCurrent->getToolTipText()) + ); + cmd4->setStatusTip( + QApplication::translate("FEM_EquationStaticCurrent", EquationStaticCurrent->getStatusTip()) + ); } } @@ -1680,9 +1853,11 @@ bool CmdFemCompEmEquations::isActive() } // only activate if a single Elmer object is selected - auto results = getSelection().getSelectionEx(nullptr, - App::DocumentObject::getClassTypeId(), - Gui::ResolveMode::FollowLink); + auto results = getSelection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::FollowLink + ); if (results.size() == 1) { auto object = results.begin()->getObject(); // FIXME: this is not unique since the Ccx solver object has the same type @@ -1772,22 +1947,28 @@ void CmdFemCompMechEquations::languageChange() if (EquationElasticity) { QAction* cmd1 = a[0]; cmd1->setText( - QApplication::translate("FEM_EquationElasticity", EquationElasticity->getMenuText())); - cmd1->setToolTip(QApplication::translate("FEM_EquationElasticity", - EquationElasticity->getToolTipText())); + QApplication::translate("FEM_EquationElasticity", EquationElasticity->getMenuText()) + ); + cmd1->setToolTip( + QApplication::translate("FEM_EquationElasticity", EquationElasticity->getToolTipText()) + ); cmd1->setStatusTip( - QApplication::translate("FEM_EquationElasticity", EquationElasticity->getStatusTip())); + QApplication::translate("FEM_EquationElasticity", EquationElasticity->getStatusTip()) + ); } Gui::Command* EquationDeformation = rcCmdMgr.getCommandByName("FEM_EquationDeformation"); if (EquationDeformation) { QAction* cmd0 = a[1]; cmd0->setText( - QApplication::translate("FEM_EquationDeformation", EquationDeformation->getMenuText())); - cmd0->setToolTip(QApplication::translate("FEM_EquationDeformation", - EquationDeformation->getToolTipText())); - cmd0->setStatusTip(QApplication::translate("FEM_EquationDeformation", - EquationDeformation->getStatusTip())); + QApplication::translate("FEM_EquationDeformation", EquationDeformation->getMenuText()) + ); + cmd0->setToolTip( + QApplication::translate("FEM_EquationDeformation", EquationDeformation->getToolTipText()) + ); + cmd0->setStatusTip( + QApplication::translate("FEM_EquationDeformation", EquationDeformation->getStatusTip()) + ); } } @@ -1799,9 +1980,11 @@ bool CmdFemCompMechEquations::isActive() } // only activate if a single Elmer object is selected - auto results = getSelection().getSelectionEx(nullptr, - App::DocumentObject::getClassTypeId(), - Gui::ResolveMode::FollowLink); + auto results = getSelection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::FollowLink + ); if (results.size() == 1) { auto object = results.begin()->getObject(); // FIXME: this is not unique since the Ccx solver object has the same type @@ -1833,9 +2016,9 @@ void setupFilter(Gui::Command* cmd, std::string Name) if (Gui::Selection().getSelection().size() > 1) { QMessageBox::warning( Gui::getMainWindow(), - qApp->translate("setupFilter", - "Error: A filter can only be applied to a single object."), - qApp->translate("setupFilter", "The filter could not be set up.")); + qApp->translate("setupFilter", "Error: A filter can only be applied to a single object."), + qApp->translate("setupFilter", "The filter could not be set up.") + ); return; } @@ -1846,7 +2029,8 @@ void setupFilter(Gui::Command* cmd, std::string Name) QMessageBox::warning( Gui::getMainWindow(), qApp->translate("setupFilter", "Error: no post processing object selected."), - qApp->translate("setupFilter", "The filter could not be set up.")); + qApp->translate("setupFilter", "The filter could not be set up.") + ); return; } @@ -1866,31 +2050,41 @@ void setupFilter(Gui::Command* cmd, std::string Name) qApp->translate("setupFilter", "Error: Object not in a post processing group"), qApp->translate( "setupFilter", - "The filter could not be set up: Object not in a post processing group.")); + "The filter could not be set up: Object not in a post processing group." + ) + ); return; } } // create the object and add it to the pipeline cmd->openCommand(QT_TRANSLATE_NOOP("Command", "Create filter")); - cmd->doCommand(Gui::Command::Doc, - "App.activeDocument().addObject('Fem::FemPost%sFilter','%s')", - Name.c_str(), - FeatName.c_str()); + cmd->doCommand( + Gui::Command::Doc, + "App.activeDocument().addObject('Fem::FemPost%sFilter','%s')", + Name.c_str(), + FeatName.c_str() + ); // add it as subobject to the pipeline - cmd->doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.addObject(App.ActiveDocument.%s)", - pipeline->getNameInDocument(), - FeatName.c_str()); + cmd->doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.addObject(App.ActiveDocument.%s)", + pipeline->getNameInDocument(), + FeatName.c_str() + ); // set display to assure the user sees the new object - cmd->doCommand(Gui::Command::Doc, - "App.activeDocument().ActiveObject.ViewObject.DisplayMode = \"Surface\""); + cmd->doCommand( + Gui::Command::Doc, + "App.activeDocument().ActiveObject.ViewObject.DisplayMode = \"Surface\"" + ); // Set SelectionStyle to BoundBox because the idea is that the user gets the useful result // from the colors. The default would be to highlight the shape but then the colors are changed // by every highlighting leading to confusions for the user. - cmd->doCommand(Gui::Command::Doc, - "App.activeDocument().ActiveObject.ViewObject.SelectionStyle = \"BoundBox\""); + cmd->doCommand( + Gui::Command::Doc, + "App.activeDocument().ActiveObject.ViewObject.SelectionStyle = \"BoundBox\"" + ); auto objFilter = App::GetApplication().getActiveDocument()->getActiveObject(); auto femFilter = static_cast(objFilter); @@ -1910,9 +2104,11 @@ void setupFilter(Gui::Command* cmd, std::string Name) // hide selected filter if (!femFilter->isDerivedFrom() && !femFilter->isDerivedFrom()) { - cmd->doCommand(Gui::Command::Doc, - "App.activeDocument().%s.ViewObject.Visibility = False", - selObject->getNameInDocument()); + cmd->doCommand( + Gui::Command::Doc, + "App.activeDocument().%s.ViewObject.Visibility = False", + selObject->getNameInDocument() + ); } cmd->updateActive(); @@ -1923,29 +2119,41 @@ void setupFilter(Gui::Command* cmd, std::string Name) std::string Plot() { - auto xAxisLabel = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", - "Thickness [mm]", - "Plot X-Axis Label") + auto xAxisLabel = QCoreApplication::translate( + "CmdFemPostLinearizedStressesFilter", + "Thickness [mm]", + "Plot X-Axis Label" + ) .toStdString(); - auto yAxisLabel = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", - "Stress [MPa]", - "Plot Y-Axis Label") + auto yAxisLabel = QCoreApplication::translate( + "CmdFemPostLinearizedStressesFilter", + "Stress [MPa]", + "Plot Y-Axis Label" + ) .toStdString(); - auto titleLabel = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", - "Linearized Stresses", - "Plot title") + auto titleLabel = QCoreApplication::translate( + "CmdFemPostLinearizedStressesFilter", + "Linearized Stresses", + "Plot title" + ) .toStdString(); - auto legendEntryA = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", - "Membrane", - "Plot legend item label") + auto legendEntryA = QCoreApplication::translate( + "CmdFemPostLinearizedStressesFilter", + "Membrane", + "Plot legend item label" + ) .toStdString(); - auto legendEntryB = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", - "Membrane and Bending", - "Plot legend item label") + auto legendEntryB = QCoreApplication::translate( + "CmdFemPostLinearizedStressesFilter", + "Membrane and Bending", + "Plot legend item label" + ) .toStdString(); - auto legendEntryC = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", - "Total", - "Plot legend item label") + auto legendEntryC = QCoreApplication::translate( + "CmdFemPostLinearizedStressesFilter", + "Total", + "Plot legend item label" + ) .toStdString(); std::ostringstream oss; @@ -2026,8 +2234,9 @@ CmdFemPostClipFilter::CmdFemPostClipFilter() sAppModule = "Fem"; sGroup = QT_TR_NOOP("Fem"); sMenuText = QT_TR_NOOP("Region Clip Filter"); - sToolTipText = - QT_TR_NOOP("Defines a clip filter which uses functions to define the clipped region"); + sToolTipText = QT_TR_NOOP( + "Defines a clip filter which uses functions to define the clipped region" + ); sWhatsThis = "FEM_PostFilterClipRegion"; sStatusTip = sToolTipText; sPixmap = "FEM_PostFilterClipRegion"; @@ -2188,11 +2397,12 @@ void CmdFemPostLinearizedStressesFilter::activated(int) Gui::SelectionFilter DataAlongLineFilter("SELECT Fem::FemPostDataAlongLineFilter COUNT 1"); if (DataAlongLineFilter.match()) { - Fem::FemPostDataAlongLineFilter* DataAlongLine = - static_cast( - DataAlongLineFilter.Result[0][0].getObject()); + Fem::FemPostDataAlongLineFilter* DataAlongLine = static_cast( + DataAlongLineFilter.Result[0][0].getObject() + ); std::string FieldName = DataAlongLine->PlotData.getValue(); - if ((FieldName == "Tresca Stress") || (FieldName == "von Mises Stress") + if ( + (FieldName == "Tresca Stress") || (FieldName == "von Mises Stress") || (FieldName == "Major Principal Stress") || (FieldName == "Intermediate Principal Stress") || (FieldName == "Minor Principal Stress") || (FieldName == "Stress xx component") @@ -2214,16 +2424,22 @@ void CmdFemPostLinearizedStressesFilter::activated(int) QMessageBox::warning( Gui::getMainWindow(), qApp->translate("CmdFemPostLinearizedStressesFilter", "Wrong selection"), - qApp->translate("CmdFemPostLinearizedStressesFilter", - "Select a clip filter which clips a stress field along a line")); + qApp->translate( + "CmdFemPostLinearizedStressesFilter", + "Select a clip filter which clips a stress field along a line" + ) + ); } } else { QMessageBox::warning( Gui::getMainWindow(), qApp->translate("CmdFemPostLinearizedStressesFilter", "Wrong selection"), - qApp->translate("CmdFemPostLinearizedStressesFilter", - "Select a clip filter which clips a stress field along a line")); + qApp->translate( + "CmdFemPostLinearizedStressesFilter", + "Select a clip filter which clips a stress field along a line" + ) + ); } } @@ -2423,8 +2639,8 @@ void CmdFemPostFunctions::activated(int iMsg) } // create the object - std::vector pipelines = - App::GetApplication().getActiveDocument()->getObjectsOfType(); + std::vector pipelines + = App::GetApplication().getActiveDocument()->getObjectsOfType(); if (!pipelines.empty()) { Fem::FemPostPipeline* pipeline = pipelines.front(); @@ -2434,26 +2650,34 @@ void CmdFemPostFunctions::activated(int iMsg) Fem::FemPostFunctionProvider* provider = pipeline->getFunctionProvider(); if (!provider) { std::string FuncName = getUniqueObjectName("Functions"); - doCommand(Doc, - "App.ActiveDocument.addObject('Fem::FemPostFunctionProvider','%s')", - FuncName.c_str()); - doCommand(Doc, - "App.ActiveDocument.%s.addObject(App.ActiveDocument.%s)", - pipeline->getNameInDocument(), - FuncName.c_str()); + doCommand( + Doc, + "App.ActiveDocument.addObject('Fem::FemPostFunctionProvider','%s')", + FuncName.c_str() + ); + doCommand( + Doc, + "App.ActiveDocument.%s.addObject(App.ActiveDocument.%s)", + pipeline->getNameInDocument(), + FuncName.c_str() + ); provider = pipeline->getFunctionProvider(); } // build the object std::string FeatName = getUniqueObjectName(name.c_str()); - doCommand(Doc, - "App.activeDocument().addObject('Fem::FemPost%sFunction','%s')", - name.c_str(), - FeatName.c_str()); - doCommand(Doc, - "App.ActiveDocument.%s.addObject(App.ActiveDocument.%s)", - provider->getNameInDocument(), - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject('Fem::FemPost%sFunction','%s')", + name.c_str(), + FeatName.c_str() + ); + doCommand( + Doc, + "App.ActiveDocument.%s.addObject(App.ActiveDocument.%s)", + provider->getNameInDocument(), + FeatName.c_str() + ); // set the default values, for this get the bounding box vtkBoundingBox box = pipeline->getBoundingBox(); @@ -2462,55 +2686,66 @@ void CmdFemPostFunctions::activated(int iMsg) box.GetCenter(center); if (iMsg == 0) { // Plane - doCommand(Doc, - "App.ActiveDocument.%s.Origin = App.Vector(%f, %f, %f)", - FeatName.c_str(), - center[0], - center[1], - center[2]); - doCommand(Doc, - "Gui.ActiveDocument.%s.Scale = %f", - FeatName.c_str(), - box.GetDiagonalLength()); + doCommand( + Doc, + "App.ActiveDocument.%s.Origin = App.Vector(%f, %f, %f)", + FeatName.c_str(), + center[0], + center[1], + center[2] + ); + doCommand(Doc, "Gui.ActiveDocument.%s.Scale = %f", FeatName.c_str(), box.GetDiagonalLength()); } else if (iMsg == 1) { // Sphere - doCommand(Doc, - "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", - FeatName.c_str(), - center[0], - center[1] + box.GetLength(1) / 2, - center[2] + box.GetLength(2) / 2); - doCommand(Doc, - "App.ActiveDocument.%s.Radius = %f", - FeatName.c_str(), - box.GetDiagonalLength() / 2); + doCommand( + Doc, + "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", + FeatName.c_str(), + center[0], + center[1] + box.GetLength(1) / 2, + center[2] + box.GetLength(2) / 2 + ); + doCommand( + Doc, + "App.ActiveDocument.%s.Radius = %f", + FeatName.c_str(), + box.GetDiagonalLength() / 2 + ); } else if (iMsg == 2) { // Cylinder - doCommand(Doc, - "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", - FeatName.c_str(), - center[0], - center[1] + box.GetLength(1) / 2, - center[2]); - doCommand(Doc, - "App.ActiveDocument.%s.Radius = %f", - FeatName.c_str(), - box.GetDiagonalLength() / 3.6); // make cylinder a bit higher than the box + doCommand( + Doc, + "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", + FeatName.c_str(), + center[0], + center[1] + box.GetLength(1) / 2, + center[2] + ); + doCommand( + Doc, + "App.ActiveDocument.%s.Radius = %f", + FeatName.c_str(), + box.GetDiagonalLength() / 3.6 + ); // make cylinder a bit higher than the box } else if (iMsg == 3) { // Box - doCommand(Doc, - "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", - FeatName.c_str(), - center[0] + box.GetLength(0) / 2, - center[1] + box.GetLength(1) / 2, - center[2]); + doCommand( + Doc, + "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", + FeatName.c_str(), + center[0] + box.GetLength(0) / 2, + center[1] + box.GetLength(1) / 2, + center[2] + ); doCommand(Doc, "App.ActiveDocument.%s.Length = %f", FeatName.c_str(), box.GetLength(0)); doCommand(Doc, "App.ActiveDocument.%s.Width = %f", FeatName.c_str(), box.GetLength(1)); - doCommand(Doc, - "App.ActiveDocument.%s.Height = %f", - FeatName.c_str(), - // purposely a bit higher to avoid rendering artifacts at the box border - 1.1 * box.GetLength(2)); + doCommand( + Doc, + "App.ActiveDocument.%s.Height = %f", + FeatName.c_str(), + // purposely a bit higher to avoid rendering artifacts at the box border + 1.1 * box.GetLength(2) + ); } this->updateActive(); @@ -2520,9 +2755,11 @@ void CmdFemPostFunctions::activated(int iMsg) } } else { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("CmdFemPostClipFilter", "Wrong selection"), - qApp->translate("CmdFemPostClipFilter", "Select a pipeline.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("CmdFemPostClipFilter", "Wrong selection"), + qApp->translate("CmdFemPostClipFilter", "Select a pipeline.") + ); } // Since the default icon is reset when enabling/disabling the command we have @@ -2575,29 +2812,41 @@ void CmdFemPostFunctions::languageChange() QAction* cmd = a[0]; cmd->setText(QApplication::translate("CmdFemPostFunctions", "Plane")); cmd->setToolTip( - QApplication::translate("FEM_PostCreateFunctions", - "Create a plane function, defined by its origin and normal")); + QApplication::translate( + "FEM_PostCreateFunctions", + "Create a plane function, defined by its origin and normal" + ) + ); cmd->setStatusTip(cmd->toolTip()); cmd = a[1]; cmd->setText(QApplication::translate("CmdFemPostFunctions", "Sphere")); cmd->setToolTip( - QApplication::translate("FEM_PostCreateFunctions", - "Create a sphere function, defined by its center and radius")); + QApplication::translate( + "FEM_PostCreateFunctions", + "Create a sphere function, defined by its center and radius" + ) + ); cmd->setStatusTip(cmd->toolTip()); cmd = a[2]; cmd->setText(QApplication::translate("CmdFemPostFunctions", "Cylinder")); - cmd->setToolTip(QApplication::translate( - "FEM_PostCreateFunctions", - "Create a cylinder function, defined by its center, axis and radius")); + cmd->setToolTip( + QApplication::translate( + "FEM_PostCreateFunctions", + "Create a cylinder function, defined by its center, axis and radius" + ) + ); cmd->setStatusTip(cmd->toolTip()); cmd = a[3]; cmd->setText(QApplication::translate("CmdFemPostFunctions", "Box")); - cmd->setToolTip(QApplication::translate( - "FEM_PostCreateFunctions", - "Create a box function, defined by its center, length, width and height")); + cmd->setToolTip( + QApplication::translate( + "FEM_PostCreateFunctions", + "Create a box function, defined by its center, length, width and height" + ) + ); cmd->setStatusTip(cmd->toolTip()); } @@ -2684,19 +2933,22 @@ void CmdFemPostPipelineFromResult::activated(int) // go through active document change some Visibility Gui::Document* doc = Gui::Application::Instance->activeDocument(); App::Document* app = doc->getDocument(); - const std::vector obj = - app->getObjectsOfType(App::DocumentObject::getClassTypeId()); + const std::vector obj = app->getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); for (auto it : obj) { - doCommand(Gui, - "Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=False", - app->getName(), - it->getNameInDocument()); + doCommand( + Gui, + "Gui.getDocument(\"%s\").getObject(\"%s\").Visibility=False", + app->getName(), + it->getNameInDocument() + ); } // we need single result object to attach the pipeline to - std::vector results = - getSelection().getObjectsOfType(); + std::vector results + = getSelection().getObjectsOfType(); if (results.size() == 1) { // the pipeline should be inside the analysis container if possible bool foundAnalysis = false; @@ -2717,22 +2969,25 @@ void CmdFemPostPipelineFromResult::activated(int) pcAnalysis->addObject(FeatName.c_str()); } else { - doCommand(Doc, - "App.activeDocument().addObject('Fem::FemPostPipeline','%s')", - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject('Fem::FemPostPipeline','%s')", + FeatName.c_str() + ); } // load the contents of the result object to the pipeline - doCommand(Doc, - "App.activeDocument().ActiveObject.load(" - "App.activeDocument().getObject(\"%s\"))", - results[0]->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().ActiveObject.load(" + "App.activeDocument().getObject(\"%s\"))", + results[0]->getNameInDocument() + ); // set display to assure the user sees the new object doCommand(Doc, "App.activeDocument().ActiveObject.ViewObject.DisplayMode = \"Surface\""); // Set SelectionStyle to BoundBox because the idea is that the user gets the useful result // from the colors. The default would be to highlight the shape but then the colors are // changed by every highlighting leading to confusions for the user. - doCommand(Doc, - "App.activeDocument().ActiveObject.ViewObject.SelectionStyle = \"BoundBox\""); + doCommand(Doc, "App.activeDocument().ActiveObject.ViewObject.SelectionStyle = \"BoundBox\""); commitCommand(); this->updateActive(); @@ -2741,15 +2996,16 @@ void CmdFemPostPipelineFromResult::activated(int) QMessageBox::warning( Gui::getMainWindow(), qApp->translate("CmdFemPostPipelineFromResult", "Wrong selection type"), - qApp->translate("CmdFemPostPipelineFromResult", "Select a result object.")); + qApp->translate("CmdFemPostPipelineFromResult", "Select a result object.") + ); } } bool CmdFemPostPipelineFromResult::isActive() { // only activate if a result object is selected from which the pipeline can be loaded - std::vector results = - getSelection().getObjectsOfType(); + std::vector results + = getSelection().getObjectsOfType(); return (results.size() == 1) ? true : false; } diff --git a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp index ea1bb29c01..80791db602 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp @@ -45,10 +45,12 @@ DlgSettingsFemCcxImp::DlgSettingsFemCcxImp(QWidget* parent) ui->dsb_ccx_time_period->setMaximum(std::numeric_limits::max()); ui->dsb_ccx_initial_time_increment->setMaximum(std::numeric_limits::max()); - connect(ui->fc_ccx_binary_path, - &Gui::PrefFileChooser::fileNameSelected, - this, - &DlgSettingsFemCcxImp::onfileNameSelected); + connect( + ui->fc_ccx_binary_path, + &Gui::PrefFileChooser::fileNameSelected, + this, + &DlgSettingsFemCcxImp::onfileNameSelected + ); } DlgSettingsFemCcxImp::~DlgSettingsFemCcxImp() = default; @@ -56,7 +58,8 @@ DlgSettingsFemCcxImp::~DlgSettingsFemCcxImp() = default; void DlgSettingsFemCcxImp::saveSettings() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"); + "User parameter:BaseApp/Preferences/Mod/Fem/Ccx" + ); hGrp->SetInt("Solver", ui->cmb_solver->currentIndex()); hGrp->SetInt("AnalysisType", ui->cb_analysis_type->currentIndex()); @@ -114,7 +117,8 @@ void DlgSettingsFemCcxImp::loadSettings() ui->cb_split_inp_writer->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Ccx"); + "User parameter:BaseApp/Preferences/Mod/Fem/Ccx" + ); // determine number of CPU threads int processor_count = hGrp->GetInt("AnalysisNumCPUs", QThread::idealThreadCount()); diff --git a/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp index 0edae3b094..779d5a962f 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp @@ -37,14 +37,18 @@ DlgSettingsFemElmerImp::DlgSettingsFemElmerImp(QWidget* parent) { ui->setupUi(this); - connect(ui->fc_grid_binary_path, - &Gui::PrefFileChooser::fileNameSelected, - this, - &DlgSettingsFemElmerImp::onfileNameSelected); - connect(ui->fc_elmer_binary_path, - &Gui::PrefFileChooser::fileNameSelected, - this, - &DlgSettingsFemElmerImp::onfileNameSelected); + connect( + ui->fc_grid_binary_path, + &Gui::PrefFileChooser::fileNameSelected, + this, + &DlgSettingsFemElmerImp::onfileNameSelected + ); + connect( + ui->fc_elmer_binary_path, + &Gui::PrefFileChooser::fileNameSelected, + this, + &DlgSettingsFemElmerImp::onfileNameSelected + ); } DlgSettingsFemElmerImp::~DlgSettingsFemElmerImp() = default; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.cpp index 5247f22777..62f9fa351a 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.cpp @@ -46,7 +46,8 @@ DlgSettingsFemExportAbaqusImp::~DlgSettingsFemExportAbaqusImp() = default; void DlgSettingsFemExportAbaqusImp::saveSettings() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Abaqus"); + "User parameter:BaseApp/Preferences/Mod/Fem/Abaqus" + ); hGrp->SetInt("AbaqusElementChoice", ui->comboBoxElemChoiceParam->currentIndex()); ui->comboBoxElemChoiceParam->onSave(); @@ -59,7 +60,8 @@ void DlgSettingsFemExportAbaqusImp::loadSettings() ui->checkBoxWriteGroups->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Abaqus"); + "User parameter:BaseApp/Preferences/Mod/Fem/Abaqus" + ); int index = hGrp->GetInt("AbaqusElementChoice", 2); if (index > -1) { ui->comboBoxElemChoiceParam->setCurrentIndex(index); diff --git a/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.cpp index 3e9954ca9d..e1fe528ef2 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.cpp @@ -68,7 +68,8 @@ DlgSettingsFemGeneralImp::DlgSettingsFemGeneralImp(QWidget* parent) // if the "DefaultSolver" parameter is not yet set and there is only // one available solver, set this solver ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/General"); + "User parameter:BaseApp/Preferences/Mod/Fem/General" + ); auto DefaultSolver = hGrp->GetInt("DefaultSolver", 0); if (!DefaultSolver && ui->cmb_def_solver->count() == 2) { ui->cmb_def_solver->setCurrentIndex(1); diff --git a/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp index e39a165d6e..31715e63cc 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp @@ -40,10 +40,12 @@ DlgSettingsFemGmshImp::DlgSettingsFemGmshImp(QWidget* parent) { ui->setupUi(this); - connect(ui->fc_gmsh_binary_path, - &Gui::PrefFileChooser::fileNameSelected, - this, - &DlgSettingsFemGmshImp::onfileNameSelected); + connect( + ui->fc_gmsh_binary_path, + &Gui::PrefFileChooser::fileNameSelected, + this, + &DlgSettingsFemGmshImp::onfileNameSelected + ); } DlgSettingsFemGmshImp::~DlgSettingsFemGmshImp() = default; @@ -60,7 +62,8 @@ void DlgSettingsFemGmshImp::loadSettings() ui->fc_gmsh_binary_path->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Gmsh"); + "User parameter:BaseApp/Preferences/Mod/Fem/Gmsh" + ); // determine number of CPU threads ui->sb_threads->setValue(hGrp->GetInt("NumOfThreads", QThread::idealThreadCount())); @@ -90,21 +93,23 @@ void DlgSettingsFemGmshImp::onfileNameSelected(const QString& fileName) void DlgSettingsFemGmshImp::populateLogVerbosity() { - std::list> mapValues = {{"Silent", 0}, - {"Errors", 1}, - {"Warnings", 2}, - {"Direct", 3}, - {"Information", 4}, - {"Status", 5}, - {"Debug", 99}}; + std::list> mapValues = { + {"Silent", 0}, + {"Errors", 1}, + {"Warnings", 2}, + {"Direct", 3}, + {"Information", 4}, + {"Status", 5}, + {"Debug", 99} + }; for (const auto& val : mapValues) { - ui->cb_log_verbosity->addItem(QString::fromStdString(val.first), - QString::number(val.second)); + ui->cb_log_verbosity->addItem(QString::fromStdString(val.first), QString::number(val.second)); } auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Gmsh"); + "User parameter:BaseApp/Preferences/Mod/Fem/Gmsh" + ); std::string current = hGrp->GetASCII("LogVerbosity", "3"); int index = ui->cb_log_verbosity->findData(QString::fromStdString(current)); ui->cb_log_verbosity->setCurrentIndex(index); diff --git a/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.cpp index 975c1f7f10..4930d671f3 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.cpp @@ -46,7 +46,8 @@ DlgSettingsFemInOutVtkImp::~DlgSettingsFemInOutVtkImp() = default; void DlgSettingsFemInOutVtkImp::saveSettings() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk"); + "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk" + ); hGrp->SetInt("ImportObject", ui->comboBoxVtkImportObject->currentIndex()); ui->comboBoxVtkImportObject->onSave(); @@ -58,7 +59,8 @@ void DlgSettingsFemInOutVtkImp::loadSettings() ui->comboBoxVtkImportObject->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk"); + "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk" + ); int index = hGrp->GetInt("ImportObject", 0); // 0 is standard on first initialize, 0 .. vtk res obj, 1 .. FEM mesh obj, 2 .. FreeCAD res obj if (index > -1) { @@ -93,7 +95,8 @@ void DlgSettingsFemInOutVtkImp::populateExportLevel() const } auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk"); + "User parameter:BaseApp/Preferences/Mod/Fem/InOutVtk" + ); std::string current = hGrp->GetASCII("MeshExportLevel", "Highest"); int index = ui->cb_export_level->findText(QString::fromStdString(current)); ui->cb_export_level->setCurrentIndex(index); diff --git a/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp index 93c383e3ad..a91523d53b 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp @@ -37,10 +37,12 @@ DlgSettingsFemMystranImp::DlgSettingsFemMystranImp(QWidget* parent) { ui->setupUi(this); - connect(ui->fc_mystran_binary_path, - &Gui::PrefFileChooser::fileNameSelected, - this, - &DlgSettingsFemMystranImp::onfileNameSelected); + connect( + ui->fc_mystran_binary_path, + &Gui::PrefFileChooser::fileNameSelected, + this, + &DlgSettingsFemMystranImp::onfileNameSelected + ); } DlgSettingsFemMystranImp::~DlgSettingsFemMystranImp() = default; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.cpp index 8e4f6698d5..52d3de2f8b 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.cpp @@ -39,10 +39,12 @@ DlgSettingsFemZ88Imp::DlgSettingsFemZ88Imp(QWidget* parent) { ui->setupUi(this); - connect(ui->fc_z88_binary_path, - &Gui::PrefFileChooser::fileNameSelected, - this, - &DlgSettingsFemZ88Imp::onfileNameSelected); + connect( + ui->fc_z88_binary_path, + &Gui::PrefFileChooser::fileNameSelected, + this, + &DlgSettingsFemZ88Imp::onfileNameSelected + ); } DlgSettingsFemZ88Imp::~DlgSettingsFemZ88Imp() = default; @@ -52,7 +54,8 @@ void DlgSettingsFemZ88Imp::saveSettings() ui->fc_z88_binary_path->onSave(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Z88"); + "User parameter:BaseApp/Preferences/Mod/Fem/Z88" + ); hGrp->SetInt("Solver", ui->cmb_solver->currentIndex()); ui->cmb_solver->onSave(); hGrp->SetInt("MaxGS", ui->sb_Z88_MaxGS->value()); @@ -68,7 +71,8 @@ void DlgSettingsFemZ88Imp::loadSettings() ui->sb_Z88_MaxGS->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Fem/Z88"); + "User parameter:BaseApp/Preferences/Mod/Fem/Z88" + ); int index = hGrp->GetInt("Solver", 0); if (index > -1) { ui->cmb_solver->setCurrentIndex(index); diff --git a/src/Mod/Fem/Gui/FemGuiTools.cpp b/src/Mod/Fem/Gui/FemGuiTools.cpp index 5f6c5f688c..6990e4b621 100644 --- a/src/Mod/Fem/Gui/FemGuiTools.cpp +++ b/src/Mod/Fem/Gui/FemGuiTools.cpp @@ -49,10 +49,7 @@ void createPlacement(SoSeparator* sep, const SbVec3f& base, const SbRotation& r) sep->addChild(rot); } -void updatePlacement(const SoSeparator* sep, - const int idx, - const SbVec3f& base, - const SbRotation& r) +void updatePlacement(const SoSeparator* sep, const int idx, const SbVec3f& base, const SbRotation& r) { SoTranslation* trans = static_cast(sep->getChild(idx)); trans->translation.setValue(base); @@ -130,11 +127,7 @@ SoSeparator* createCube(const double width, const double length, const double he return sep; } -void updateCube(const SoNode* node, - const int idx, - const double width, - const double length, - const double height) +void updateCube(const SoNode* node, const int idx, const double width, const double length, const double height) { const SoSeparator* sep = static_cast(node); SoCube* cube = static_cast(sep->getChild(idx)); @@ -161,10 +154,12 @@ void updateArrow(const SoNode* node, const int idx, const double length, const d { const SoSeparator* sep = static_cast(node); updateCone(sep, idx, radius, radius / 2); - updatePlacement(sep, - idx + CONE_CHILDREN, - SbVec3f(0, -radius / 2 - (length - radius) / 2, 0), - SbRotation()); + updatePlacement( + sep, + idx + CONE_CHILDREN, + SbVec3f(0, -radius / 2 - (length - radius) / 2, 0), + SbRotation() + ); updateCylinder(sep, idx + CONE_CHILDREN + PLACEMENT_CHILDREN, length - radius, radius / 5); } @@ -174,7 +169,8 @@ void createFixed(SoSeparator* sep, const double height, const double width, cons createPlacement( sep, SbVec3f(0, -(height - width / 4) / 2 - width / 8 - (gap ? 1.0 : 0.1) * width / 8, 0), - SbRotation()); + SbRotation() + ); createCube(sep, width, width, width / 4); } @@ -185,11 +181,7 @@ SoSeparator* createFixed(const double height, const double width, const bool gap return sep; } -void updateFixed(const SoNode* node, - const int idx, - const double height, - const double width, - const bool gap) +void updateFixed(const SoNode* node, const int idx, const double height, const double width, const bool gap) { const SoSeparator* sep = static_cast(node); updateCone(sep, idx, height - width / 4, height - width / 4); @@ -197,7 +189,8 @@ void updateFixed(const SoNode* node, sep, idx + CONE_CHILDREN, SbVec3f(0, -(height - width / 4) / 2 - width / 8 - (gap ? 1.0 : 0.0) * width / 8, 0), - SbRotation()); + SbRotation() + ); updateCube(sep, idx + CONE_CHILDREN + PLACEMENT_CHILDREN, width, width, width / 4); } diff --git a/src/Mod/Fem/Gui/FemGuiTools.h b/src/Mod/Fem/Gui/FemGuiTools.h index 59d61421c1..3863ef3cb1 100644 --- a/src/Mod/Fem/Gui/FemGuiTools.h +++ b/src/Mod/Fem/Gui/FemGuiTools.h @@ -38,10 +38,7 @@ namespace GuiTools { void createPlacement(SoSeparator* sep, const SbVec3f& base, const SbRotation& r); -void updatePlacement(const SoSeparator* sep, - const int idx, - const SbVec3f& base, - const SbRotation& r); +void updatePlacement(const SoSeparator* sep, const int idx, const SbVec3f& base, const SbRotation& r); void createCone(SoSeparator* sep, const double height, const double radius); SoSeparator* createCone(const double height, const double radius); void updateCone(const SoNode* node, const int idx, const double height, const double radius); @@ -50,21 +47,25 @@ SoSeparator* createCylinder(const double height, const double radius); void updateCylinder(const SoNode* node, const int idx, const double height, const double radius); void createCube(SoSeparator* sep, const double width, const double length, const double height); SoSeparator* createCube(const double width, const double length, const double height); -void updateCube(const SoNode* node, - const int idx, - const double width, - const double length, - const double height); +void updateCube( + const SoNode* node, + const int idx, + const double width, + const double length, + const double height +); void createArrow(SoSeparator* sep, const double length, const double radius); SoSeparator* createArrow(const double length, const double radius); void updateArrow(const SoNode* node, const int idx, const double length, const double radius); void createFixed(SoSeparator* sep, const double height, const double width, const bool gap = false); SoSeparator* createFixed(const double height, const double width, const bool gap = false); -void updateFixed(const SoNode* node, - const int idx, - const double height, - const double width, - const bool gap = false); +void updateFixed( + const SoNode* node, + const int idx, + const double height, + const double width, + const bool gap = false +); } // namespace GuiTools diff --git a/src/Mod/Fem/Gui/FemSelectionGate.cpp b/src/Mod/Fem/Gui/FemSelectionGate.cpp index 4cf0caa477..9a7d7ce8c3 100644 --- a/src/Mod/Fem/Gui/FemSelectionGate.cpp +++ b/src/Mod/Fem/Gui/FemSelectionGate.cpp @@ -29,9 +29,7 @@ using namespace FemGui; using namespace Gui; -bool FemSelectionGate::allow(App::Document* /*pDoc*/, - App::DocumentObject* /*pObj*/, - const char* sSubName) +bool FemSelectionGate::allow(App::Document* /*pDoc*/, App::DocumentObject* /*pObj*/, const char* sSubName) { if (Base::Tools::isNullOrEmpty(sSubName)) { return false; diff --git a/src/Mod/Fem/Gui/FemSettings.cpp b/src/Mod/Fem/Gui/FemSettings.cpp index 15c66c0ca1..7e65eb4cac 100644 --- a/src/Mod/Fem/Gui/FemSettings.cpp +++ b/src/Mod/Fem/Gui/FemSettings.cpp @@ -31,8 +31,9 @@ using namespace FemGui; FemSettings::FemSettings() { - pGroup = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Fem"); + pGroup = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Fem" + ); } void FemSettings::setPostAutoRecompute(bool on) diff --git a/src/Mod/Fem/Gui/PreCompiled.h b/src/Mod/Fem/Gui/PreCompiled.h index b44a51effb..79a22da635 100644 --- a/src/Mod/Fem/Gui/PreCompiled.h +++ b/src/Mod/Fem/Gui/PreCompiled.h @@ -49,7 +49,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // OCC diff --git a/src/Mod/Fem/Gui/PropertyFemMeshItem.cpp b/src/Mod/Fem/Gui/PropertyFemMeshItem.cpp index 6c68fc6fb0..971a5e2c11 100644 --- a/src/Mod/Fem/Gui/PropertyFemMeshItem.cpp +++ b/src/Mod/Fem/Gui/PropertyFemMeshItem.cpp @@ -38,37 +38,44 @@ PROPERTYITEM_SOURCE(FemGui::PropertyFemMeshItem) PropertyFemMeshItem::PropertyFemMeshItem() { m_n = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_n->setParent(this); m_n->setPropertyName(QLatin1String("Nodes")); this->appendChild(m_n); m_e = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_e->setParent(this); m_e->setPropertyName(QLatin1String("Edges")); this->appendChild(m_e); m_f = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_f->setParent(this); m_f->setPropertyName(QLatin1String("Faces")); this->appendChild(m_f); m_p = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_p->setParent(this); m_p->setPropertyName(QLatin1String("Polygons")); this->appendChild(m_p); m_v = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_v->setParent(this); m_v->setPropertyName(QLatin1String("Volumes")); this->appendChild(m_v); m_h = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_h->setParent(this); m_h->setPropertyName(QLatin1String("Polyhedrons")); this->appendChild(m_h); m_g = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_g->setParent(this); m_g->setPropertyName(QLatin1String("Groups")); this->appendChild(m_g); @@ -126,9 +133,11 @@ void PropertyFemMeshItem::setValue(const QVariant& value) Q_UNUSED(value); } -QWidget* PropertyFemMeshItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyFemMeshItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { Q_UNUSED(parent); Q_UNUSED(method); diff --git a/src/Mod/Fem/Gui/PropertyFemMeshItem.h b/src/Mod/Fem/Gui/PropertyFemMeshItem.h index 1c616e5bb5..83ba37f44c 100644 --- a/src/Mod/Fem/Gui/PropertyFemMeshItem.h +++ b/src/Mod/Fem/Gui/PropertyFemMeshItem.h @@ -46,9 +46,11 @@ class PropertyFemMeshItem: public Gui::PropertyEditor::PropertyItem Q_PROPERTY(int Groups READ countGroups CONSTANT) PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; diff --git a/src/Mod/Fem/Gui/TaskCreateElementSet.cpp b/src/Mod/Fem/Gui/TaskCreateElementSet.cpp index 39e74e3ae1..56f377e5ab 100644 --- a/src/Mod/Fem/Gui/TaskCreateElementSet.cpp +++ b/src/Mod/Fem/Gui/TaskCreateElementSet.cpp @@ -98,15 +98,17 @@ void addFaceToMesh(const std::vector nodes, SMESHDS_Mesh* MeshDS->AddFaceWithID(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], EID); break; case 8: // 8 node quadrilateral - MeshDS->AddFaceWithID(nodes[0], - nodes[1], - nodes[2], - nodes[3], - nodes[4], - nodes[5], - nodes[6], - nodes[7], - EID); + MeshDS->AddFaceWithID( + nodes[0], + nodes[1], + nodes[2], + nodes[3], + nodes[4], + nodes[5], + nodes[6], + nodes[7], + EID + ); break; } } // addFaceToMesh @@ -124,89 +126,98 @@ void addVolumeToMesh(const std::vector nodes, SMESHDS_Mesh MeshDS->AddVolumeWithID(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], EID); break; case 6: // 6 node pentahedron - MeshDS - ->AddVolumeWithID(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], EID); + MeshDS->AddVolumeWithID(nodes[0], nodes[1], nodes[2], nodes[3], nodes[4], nodes[5], EID); break; case 8: // 8 node hexahedron - MeshDS->AddVolumeWithID(nodes[0], - nodes[1], - nodes[2], - nodes[3], - nodes[4], - nodes[5], - nodes[6], - nodes[7], - EID); + MeshDS->AddVolumeWithID( + nodes[0], + nodes[1], + nodes[2], + nodes[3], + nodes[4], + nodes[5], + nodes[6], + nodes[7], + EID + ); break; case 10: // 10 node tetrahedron - MeshDS->AddVolumeWithID(nodes[0], - nodes[1], - nodes[2], - nodes[3], - nodes[4], - nodes[5], - nodes[6], - nodes[7], - nodes[8], - nodes[9], - EID); + MeshDS->AddVolumeWithID( + nodes[0], + nodes[1], + nodes[2], + nodes[3], + nodes[4], + nodes[5], + nodes[6], + nodes[7], + nodes[8], + nodes[9], + EID + ); break; case 13: // 13 node pyramid - MeshDS->AddVolumeWithID(nodes[0], - nodes[1], - nodes[2], - nodes[3], - nodes[4], - nodes[5], - nodes[6], - nodes[7], - nodes[8], - nodes[9], - nodes[10], - nodes[11], - nodes[12], - EID); + MeshDS->AddVolumeWithID( + nodes[0], + nodes[1], + nodes[2], + nodes[3], + nodes[4], + nodes[5], + nodes[6], + nodes[7], + nodes[8], + nodes[9], + nodes[10], + nodes[11], + nodes[12], + EID + ); break; case 15: // 15 node pentahedron - MeshDS->AddVolumeWithID(nodes[0], - nodes[1], - nodes[2], - nodes[3], - nodes[4], - nodes[5], - nodes[6], - nodes[7], - nodes[8], - nodes[9], - nodes[10], - nodes[11], - nodes[12], - nodes[13], - nodes[14], - EID); + MeshDS->AddVolumeWithID( + nodes[0], + nodes[1], + nodes[2], + nodes[3], + nodes[4], + nodes[5], + nodes[6], + nodes[7], + nodes[8], + nodes[9], + nodes[10], + nodes[11], + nodes[12], + nodes[13], + nodes[14], + EID + ); break; case 20: // 20 node hexahedron - MeshDS->AddVolumeWithID(nodes[0], - nodes[1], - nodes[2], - nodes[3], - nodes[4], - nodes[5], - nodes[6], - nodes[7], - nodes[8], - nodes[9], - nodes[10], - nodes[11], - nodes[12], - nodes[13], - nodes[14], - nodes[15], - nodes[16], - nodes[17], - nodes[18], - nodes[19], - EID); + MeshDS->AddVolumeWithID( + nodes[0], + nodes[1], + nodes[2], + nodes[3], + nodes[4], + nodes[5], + nodes[6], + nodes[7], + nodes[8], + nodes[9], + nodes[10], + nodes[11], + nodes[12], + nodes[13], + nodes[14], + nodes[15], + nodes[16], + nodes[17], + nodes[18], + nodes[19], + EID + ); break; } // default: {} @@ -219,14 +230,17 @@ void myCopyResultsMesh(std::string oldName, std::string newName) Base::Console().warning("copy: %s and %s\n", oldName.c_str(), newName.c_str()); if (oldName.compare(newName) == 0 && error == 0) { error = 1; - Base::Console().warning("Cannot copy ResultMesh to ResultMesh: %s and %s\n", - oldName.c_str(), - newName.c_str()); + Base::Console().warning( + "Cannot copy ResultMesh to ResultMesh: %s and %s\n", + oldName.c_str(), + newName.c_str() + ); QMessageBox::warning( Gui::getMainWindow(), // QMessageBox::warning(Gui::MainWindow(), qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), - qApp->translate("CmdFemCreateElementsSet", "Cannot copy ResultMesh to ResultMesh")); + qApp->translate("CmdFemCreateElementsSet", "Cannot copy ResultMesh to ResultMesh") + ); } if ((oldName.find("Result") == std::string::npos || newName.find("Result") == std::string::npos) && error == 0) { @@ -236,18 +250,25 @@ void myCopyResultsMesh(std::string oldName, std::string newName) Gui::getMainWindow(), // QMessageBox::warning(Gui::MainWindow(), qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), - qApp->translate("CmdFemCreateElementsSet", "Mesh must be a ResultMesh")); + qApp->translate("CmdFemCreateElementsSet", "Mesh must be a ResultMesh") + ); } if (error == 0) { - Gui::Command::doCommand(Gui::Command::Doc, - "c = FreeCADGui.ActiveDocument.getObject(\'%s\')", - oldName.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "FreeCAD.ActiveDocument.%s.FemMesh = c.Object.FemMesh", - newName.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').BackfaceCulling = False", - newName.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "c = FreeCADGui.ActiveDocument.getObject(\'%s\')", + oldName.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "FreeCAD.ActiveDocument.%s.FemMesh = c.Object.FemMesh", + newName.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').BackfaceCulling = False", + newName.c_str() + ); } } // copyresultsmesh @@ -264,13 +285,18 @@ void generateMesh(std::string meshType) Gui::Command::doCommand( Gui::Command::Doc, "obj1 = App.ActiveDocument.addObject('Fem::FemMeshObject', \'%s\')", - startResultMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').Visibility = False", - startResultMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "ne = Gui.ActiveDocument.getObject(\'%s\')", - actualResultMesh.c_str()); + startResultMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').Visibility = False", + startResultMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "ne = Gui.ActiveDocument.getObject(\'%s\')", + actualResultMesh.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "obj1.FemMesh = ne.Object.FemMesh"); } else if (passResult > 0) { @@ -291,47 +317,67 @@ void generateMesh(std::string meshType) App::Document* doc = App::GetApplication().getActiveDocument(); uniqueMesh = doc->getUniqueObjectName(createdMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').Visibility = False", - highLightMesh.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').Visibility = False", + highLightMesh.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "newermesh = Fem.read(\'%s\')", inp_file.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "obj = App.ActiveDocument.addObject('Fem::FemMeshObject', \'%s\')", - uniqueMesh.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "obj = App.ActiveDocument.addObject('Fem::FemMeshObject', \'%s\')", + uniqueMesh.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "obj.FemMesh = newermesh"); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').BackfaceCulling = False", - uniqueMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').Visibility = True", - uniqueMesh.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').BackfaceCulling = False", + uniqueMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').Visibility = True", + uniqueMesh.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "os.remove(\'%s\')", inp_file.c_str()); if (strcmp(meshType.c_str(), "result") == 0) { - Gui::Command::doCommand(Gui::Command::Doc, - "c = FreeCADGui.ActiveDocument.getObject(\'%s\')", - uniqueMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "FreeCAD.ActiveDocument.%s.FemMesh = c.Object.FemMesh", - actualResultMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').BackfaceCulling = False", - actualResultMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').Visibility = True", - actualResultMesh.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "Gui.ActiveDocument.getObject(\'%s\').Visibility = False", - uniqueMesh.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "c = FreeCADGui.ActiveDocument.getObject(\'%s\')", + uniqueMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "FreeCAD.ActiveDocument.%s.FemMesh = c.Object.FemMesh", + actualResultMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').BackfaceCulling = False", + actualResultMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').Visibility = True", + actualResultMesh.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "Gui.ActiveDocument.getObject(\'%s\').Visibility = False", + uniqueMesh.c_str() + ); } } // generate mesh -void writeToFile(std::string fileName, - SMESHDS_Mesh* newMesh, - int* nodeNumbers, - double** nodeCoords, - int rows, - int requiredType) +void writeToFile( + std::string fileName, + SMESHDS_Mesh* newMesh, + int* nodeNumbers, + double** nodeCoords, + int rows, + int requiredType +) { std::map elType2D; std::map elType3D; @@ -362,12 +408,14 @@ void writeToFile(std::string fileName, for (int i = 1; i < rows + 1; i++) { if (nodeNumbers[i] > 0) { - fprintf(fptr, - "%d, %e, %e, %e\n", - nodeNumbers[i], - nodeCoords[i][0], - nodeCoords[i][1], - nodeCoords[i][2]); + fprintf( + fptr, + "%d, %e, %e, %e\n", + nodeNumbers[i], + nodeCoords[i][0], + nodeCoords[i][1], + nodeCoords[i][2] + ); } } @@ -394,15 +442,11 @@ void writeToFile(std::string fileName, fprintf(fptr, "\n"); fprintf(fptr, "\n"); fprintf(fptr, "%s", "** Volume elements\n"); - fprintf(fptr, - "*Element, TYPE=%s, ELSET=Evolumes\n", - elType3D[elem->NbNodes()].c_str()); + fprintf(fptr, "*Element, TYPE=%s, ELSET=Evolumes\n", elType3D[elem->NbNodes()].c_str()); } else if (requiredType == 3) { fprintf(fptr, "%s", "** Face elements\n"); - fprintf(fptr, - "*Element, TYPE=%s, ELSET=Efaces\n", - elType2D[elem->NbNodes()].c_str()); + fprintf(fptr, "*Element, TYPE=%s, ELSET=Efaces\n", elType2D[elem->NbNodes()].c_str()); } numberNodes = elem->NbNodes(); } @@ -434,10 +478,7 @@ void writeToFile(std::string fileName, } // namespace TaskCreateElementSet::TaskCreateElementSet(Fem::FemSetElementNodesObject* pcObject, QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap("FEM_CreateElementsSet"), - tr("Elements set"), - true, - parent) + : TaskBox(Gui::BitmapFactory().pixmap("FEM_CreateElementsSet"), tr("Elements set"), true, parent) , pcObject(pcObject) , selectionMode(none) { @@ -451,9 +492,9 @@ TaskCreateElementSet::TaskCreateElementSet(Fem::FemSetElementNodesObject* pcObje QObject::connect(ui->toolButton_Rename, SIGNAL(clicked()), this, SLOT(CopyResultsMesh())); // check if the Link to the FemMesh is defined assert(pcObject->FemMesh.getValue()); - MeshViewProvider = - freecad_cast(Gui::Application::Instance->getViewProvider( - pcObject->FemMesh.getValue())); + MeshViewProvider = freecad_cast( + Gui::Application::Instance->getViewProvider(pcObject->FemMesh.getValue()) + ); assert(MeshViewProvider); elementTempSet = pcObject->Elements.getValues(); @@ -462,12 +503,13 @@ TaskCreateElementSet::TaskCreateElementSet(Fem::FemSetElementNodesObject* pcObje info = "Delete the generated data in the other project: " + std::string(currentProject); App::Document* doc = App::GetApplication().getActiveDocument(); newProject = doc->Label.getValue(); - if (strcmp(currentProject.c_str(), newProject.c_str()) != 0 - && (passResult + passFemMesh != 0)) { - QMessageBox::warning(Gui::getMainWindow(), - // QMessageBox::warning(Gui::MainWindow(), - qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), - qApp->translate("CmdFemCreateElementsSet", info.c_str())); + if (strcmp(currentProject.c_str(), newProject.c_str()) != 0 && (passResult + passFemMesh != 0)) { + QMessageBox::warning( + Gui::getMainWindow(), + // QMessageBox::warning(Gui::MainWindow(), + qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), + qApp->translate("CmdFemCreateElementsSet", info.c_str()) + ); return; } } @@ -480,16 +522,13 @@ void TaskCreateElementSet::Poly(void) Gui::View3DInventorViewer* viewer = ((Gui::View3DInventor*)view)->getViewer(); viewer->setEditing(true); viewer->startSelection(Gui::View3DInventorViewer::Clip); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - DefineElementsCallback, - this); + viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), DefineElementsCallback, this); } } void TaskCreateElementSet::CopyResultsMesh(void) { - std::vector selection = - Gui::Selection().getSelection(); // [0]; + std::vector selection = Gui::Selection().getSelection(); // [0]; highLightMesh = selection[0].FeatName; myCopyResultsMesh(highLightMesh, actualResultMesh); Gui::Command::doCommand(Gui::Command::Doc, "Gui.activeDocument().resetEdit()"); @@ -504,8 +543,7 @@ void TaskCreateElementSet::Restore(void) // put reverse here std::vector STR; - for (std::vector::const_iterator it = all.begin(); it != all.end(); - ++it) { + for (std::vector::const_iterator it = all.begin(); it != all.end(); ++it) { std::string objectN = all[xpos]->getNameInDocument(); STR.push_back(objectN); xpos++; @@ -517,32 +555,40 @@ void TaskCreateElementSet::Restore(void) if (objectN.find(startResultMesh) != std::string::npos) { number++; myCopyResultsMesh(objectN, actualResultMesh); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.removeObject(\'%s\')", - objectN.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.removeObject(\'%s\')", + objectN.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } else if (objectN.find(newResultMesh) != std::string::npos) { number++; - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.removeObject(\'%s\')", - objectN.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.removeObject(\'%s\')", + objectN.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } - else if (objectN.find(actualResultMesh) != std::string::npos) {} + else if (objectN.find(actualResultMesh) != std::string::npos) { + } else if (objectN.find(newFemMesh) != std::string::npos) { number++; - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.removeObject(\'%s\')", - objectN.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.removeObject(\'%s\')", + objectN.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } - else if (objectN.find(Fem::FemSetElementNodesObject::getElementName()) - != std::string::npos) { + else if (objectN.find(Fem::FemSetElementNodesObject::getElementName()) != std::string::npos) { if (elList > 0) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.removeObject(\'%s\')", - objectN.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.removeObject(\'%s\')", + objectN.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } else if (elList == 0) { @@ -555,10 +601,12 @@ void TaskCreateElementSet::Restore(void) // blank last name - no action } else if (number == 0) { - QMessageBox::warning(Gui::getMainWindow(), - // QMessageBox::warning(Gui::MainWindow(), - qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), - qApp->translate("CmdFemCreateElementsSet", "No Data To Restore\n")); + QMessageBox::warning( + Gui::getMainWindow(), + // QMessageBox::warning(Gui::MainWindow(), + qApp->translate("CmdFemCreateElementsSet", "Wrong selection"), + qApp->translate("CmdFemCreateElementsSet", "No Data To Restore\n") + ); return; } passResult = 0; @@ -573,8 +621,7 @@ void TaskCreateElementSet::DefineElementsCallback(void* ud, SoEventCallback* n) Gui::WaitCursor wc; TaskCreateElementSet* taskBox = static_cast(ud); // When this callback function is invoked we must in either case leave the edit mode - Gui::View3DInventorViewer* view = - reinterpret_cast(n->getUserData()); + Gui::View3DInventorViewer* view = reinterpret_cast(n->getUserData()); view->setEditing(false); view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), DefineElementsCallback, ud); n->setHandled(); @@ -599,17 +646,19 @@ void TaskCreateElementSet::DefineElementsCallback(void* ud, SoEventCallback* n) taskBox->DefineNodes(polygon, proj, role == Gui::SelectionRole::Inner ? true : false); } // DefineElementsCallback -void TaskCreateElementSet::DefineNodes(const Base::Polygon2d& polygon, - const Gui::ViewVolumeProjection& proj, - bool inner) +void TaskCreateElementSet::DefineNodes( + const Base::Polygon2d& polygon, + const Gui::ViewVolumeProjection& proj, + bool inner +) { - const SMESHDS_Mesh* srcMeshDS = - const_cast( - pcObject->FemMesh.getValue()->FemMesh.getValue().getSMesh()) - ->GetMeshDS(); + const SMESHDS_Mesh* srcMeshDS + = const_cast( + pcObject->FemMesh.getValue()->FemMesh.getValue().getSMesh() + ) + ->GetMeshDS(); - std::vector selection = - Gui::Selection().getSelection(); // [0]; + std::vector selection = Gui::Selection().getSelection(); // [0]; highLightMesh = selection[0].FeatName; meshType = "NULL"; @@ -743,9 +792,11 @@ void TaskCreateElementSet::DefineNodes(const Base::Polygon2d& polygon, erase = nElements - keepElement; } if (keepElement > 0) { - Base::Console().warning("Number of Elements Kept: %d, Number of Elements Erased: %d\n", - keepElement, - erase); + Base::Console().warning( + "Number of Elements Kept: %d, Number of Elements Erased: %d\n", + keepElement, + erase + ); writeToFile(inp_file, newMeshDS, nodeNumbers, nodeCoords, maxNode, requiredType); generateMesh(meshType); } @@ -754,7 +805,8 @@ void TaskCreateElementSet::DefineNodes(const Base::Polygon2d& polygon, Gui::getMainWindow(), // QMessageBox::warning(Gui::MainWindow(), qApp->translate("CmdFemCreateElementsSet", "Erased Elements"), - qApp->translate("CmdFemCreateElementsSet", "All Elements Erased - no mesh generated.")); + qApp->translate("CmdFemCreateElementsSet", "All Elements Erased - no mesh generated.") + ); } newMeshDS->Modified(); Gui::Command::doCommand(Gui::Command::Doc, "Gui.activeDocument().resetEdit()"); @@ -778,10 +830,11 @@ void TaskCreateElementSet::onSelectionChanged(const Gui::SelectionChanges& msg) int elem = atoi(subName.substr(4).c_str()); int face = atoi(subName.substr(i + 1).c_str()); elementTempSet.clear(); - std::set tmp = - pcObject->FemMesh.getValue()->FemMesh.getValue().getSurfaceNodes( + std::set tmp + = pcObject->FemMesh.getValue()->FemMesh.getValue().getSurfaceNodes( elem, - face); + face + ); elementTempSet.insert(tmp.begin(), tmp.end()); selectionMode = none; @@ -795,9 +848,11 @@ TaskCreateElementSet::~TaskCreateElementSet() { // delete last elementsset if (strcmp(lastName.c_str(), "") != 0) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.removeObject(\'%s\')", - lastName.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.removeObject(\'%s\')", + lastName.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); lastName = ""; } diff --git a/src/Mod/Fem/Gui/TaskCreateElementSet.h b/src/Mod/Fem/Gui/TaskCreateElementSet.h index d10f1cc994..44dc5f937a 100644 --- a/src/Mod/Fem/Gui/TaskCreateElementSet.h +++ b/src/Mod/Fem/Gui/TaskCreateElementSet.h @@ -57,8 +57,7 @@ class TaskCreateElementSet: public Gui::TaskView::TaskBox, public Gui::Selection Q_OBJECT public: - explicit TaskCreateElementSet(Fem::FemSetElementNodesObject* pcObject, - QWidget* parent = nullptr); + explicit TaskCreateElementSet(Fem::FemSetElementNodesObject* pcObject, QWidget* parent = nullptr); ~TaskCreateElementSet() override; std::set elementTempSet; diff --git a/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp b/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp index 66190ea37b..c905e6b99d 100644 --- a/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp +++ b/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp @@ -64,16 +64,18 @@ TaskCreateNodeSet::TaskCreateNodeSet(Fem::FemSetNodesObject* pcObject, QWidget* QObject::connect(ui->toolButton_Poly, &QToolButton::clicked, this, &TaskCreateNodeSet::Poly); QObject::connect(ui->toolButton_Pick, &QToolButton::clicked, this, &TaskCreateNodeSet::Pick); - QObject::connect(ui->comboBox, - qOverload(&QComboBox::activated), - this, - &TaskCreateNodeSet::SwitchMethod); + QObject::connect( + ui->comboBox, + qOverload(&QComboBox::activated), + this, + &TaskCreateNodeSet::SwitchMethod + ); // check if the Link to the FemMesh is defined assert(pcObject->FemMesh.getValue()); - MeshViewProvider = - freecad_cast(Gui::Application::Instance->getViewProvider( - pcObject->FemMesh.getValue())); + MeshViewProvider = freecad_cast( + Gui::Application::Instance->getViewProvider(pcObject->FemMesh.getValue()) + ); assert(MeshViewProvider); tempSet = pcObject->Nodes.getValues(); @@ -152,14 +154,14 @@ void TaskCreateNodeSet::DefineNodesCallback(void* ud, SoEventCallback* n) taskBox->DefineNodes(polygon, proj, role == Gui::SelectionRole::Inner ? true : false); } -void TaskCreateNodeSet::DefineNodes(const Base::Polygon2d& polygon, - const Gui::ViewVolumeProjection& proj, - bool inner) +void TaskCreateNodeSet::DefineNodes( + const Base::Polygon2d& polygon, + const Gui::ViewVolumeProjection& proj, + bool inner +) { - const SMESHDS_Mesh* data = pcObject->FemMesh.getValue() - ->FemMesh.getValue() - .getSMesh() - ->GetMeshDS(); + const SMESHDS_Mesh* data + = pcObject->FemMesh.getValue()->FemMesh.getValue().getSMesh()->GetMeshDS(); SMDS_NodeIteratorPtr aNodeIter = data->nodesIterator(); Base::Vector3f pt2d; @@ -204,15 +206,18 @@ void TaskCreateNodeSet::onSelectionChanged(const Gui::SelectionChanges& msg) if (!ui->checkBox_Add->isChecked()) { - std::set tmp = pcObject->FemMesh.getValue() - ->FemMesh.getValue() - .getSurfaceNodes(elem, face); + std::set tmp + = pcObject->FemMesh.getValue()->FemMesh.getValue().getSurfaceNodes( + elem, + face + ); tempSet.insert(tmp.begin(), tmp.end()); } else { - tempSet = pcObject->FemMesh.getValue() - ->FemMesh.getValue() - .getSurfaceNodes(elem, face); + tempSet = pcObject->FemMesh.getValue()->FemMesh.getValue().getSurfaceNodes( + elem, + face + ); } selectionMode = none; diff --git a/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp b/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp index 80bf3571e3..c44438c315 100644 --- a/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp +++ b/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.cpp @@ -98,7 +98,8 @@ bool TaskDlgMeshShapeNetgen::accept() QMessageBox::critical( Gui::getMainWindow(), tr("Meshing failure"), - QString::fromStdString(FemMeshShapeNetgenObject->getStatusString())); + QString::fromStdString(FemMeshShapeNetgenObject->getStatusString()) + ); return true; } } diff --git a/src/Mod/Fem/Gui/TaskFemConstraint.cpp b/src/Mod/Fem/Gui/TaskFemConstraint.cpp index cac137556d..a335357f1d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraint.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraint.cpp @@ -48,13 +48,12 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraint */ -TaskFemConstraint::TaskFemConstraint(ViewProviderFemConstraint* ConstraintView, - QWidget* parent, - const char* pixmapname) - : TaskBox(Gui::BitmapFactory().pixmap(pixmapname), - tr("Analysis Feature Properties"), - true, - parent) +TaskFemConstraint::TaskFemConstraint( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent, + const char* pixmapname +) + : TaskBox(Gui::BitmapFactory().pixmap(pixmapname), tr("Analysis Feature Properties"), true, parent) , proxy(nullptr) , actionList(nullptr) , clearListAction(nullptr) @@ -158,14 +157,15 @@ void TaskFemConstraint::onButtonReference(const bool pressed) Gui::Selection().clearSelection(); } -const QString TaskFemConstraint::makeRefText(const std::string& objName, - const std::string& subName) const +const QString TaskFemConstraint::makeRefText(const std::string& objName, const std::string& subName) const { return QString::fromUtf8((objName + ":" + subName).c_str()); } -const QString TaskFemConstraint::makeRefText(const App::DocumentObject* obj, - const std::string& subName) const +const QString TaskFemConstraint::makeRefText( + const App::DocumentObject* obj, + const std::string& subName +) const { return QString::fromUtf8((std::string(obj->getNameInDocument()) + ":" + subName).c_str()); } @@ -224,23 +224,29 @@ bool TaskDlgFemConstraint::accept() std::string refs = parameter->getReferences(); if (!refs.empty()) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.References = [%s]", - name.c_str(), - refs.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.References = [%s]", + name.c_str(), + refs.c_str() + ); } else { - QMessageBox::warning(parameter, - tr("Input error"), - tr("You must specify at least one reference")); + QMessageBox::warning( + parameter, + tr("Input error"), + tr("You must specify at least one reference") + ); return false; } std::string scale = parameter->getScale(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Scale = %s", - name.c_str(), - scale.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Scale = %s", + name.c_str(), + scale.c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); if (!ConstraintView->getObject()->isValid()) { throw Base::RuntimeError(ConstraintView->getObject()->getStatusString()); diff --git a/src/Mod/Fem/Gui/TaskFemConstraint.h b/src/Mod/Fem/Gui/TaskFemConstraint.h index 3ee90ebd19..36783cbd2b 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraint.h +++ b/src/Mod/Fem/Gui/TaskFemConstraint.h @@ -45,9 +45,11 @@ class TaskFemConstraint: public Gui::TaskView::TaskBox, public Gui::SelectionObs Q_OBJECT public: - explicit TaskFemConstraint(ViewProviderFemConstraint* ConstraintView, - QWidget* parent = nullptr, - const char* pixmapname = ""); + explicit TaskFemConstraint( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent = nullptr, + const char* pixmapname = "" + ); ~TaskFemConstraint() override = default; virtual const std::string getReferences() const diff --git a/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp b/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp index c6ae18d397..84184c882f 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp @@ -47,9 +47,11 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintBearing */ -TaskFemConstraintBearing::TaskFemConstraintBearing(ViewProviderFemConstraint* ConstraintView, - QWidget* parent, - const char* pixmapname) +TaskFemConstraintBearing::TaskFemConstraintBearing( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent, + const char* pixmapname +) : TaskFemConstraint(ConstraintView, parent, pixmapname) , ui(new Ui_TaskFemConstraintBearing) { @@ -103,16 +105,14 @@ TaskFemConstraintBearing::TaskFemConstraintBearing(ViewProviderFemConstraint* Co ui->lineLocation->setText(loc); ui->checkAxial->setChecked(axialfree); - connect(ui->spinDistance, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintBearing::onDistanceChanged); - connect(ui->buttonReference, &QPushButton::pressed, this, [this] { - onButtonReference(true); - }); - connect(ui->buttonLocation, &QPushButton::pressed, this, [this] { - onButtonLocation(true); - }); + connect( + ui->spinDistance, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintBearing::onDistanceChanged + ); + connect(ui->buttonReference, &QPushButton::pressed, this, [this] { onButtonReference(true); }); + connect(ui->buttonLocation, &QPushButton::pressed, this, [this] { onButtonLocation(true); }); connect(ui->checkAxial, &QCheckBox::toggled, this, &TaskFemConstraintBearing::onCheckAxial); // Hide unwanted ui elements @@ -154,8 +154,9 @@ void TaskFemConstraintBearing::onSelectionChanged(const Gui::SelectionChanges& m } Fem::ConstraintBearing* pcConstraint = ConstraintView->getObject(); - App::DocumentObject* obj = - ConstraintView->getObject()->getDocument()->getObject(msg.pObjectName); + App::DocumentObject* obj = ConstraintView->getObject()->getDocument()->getObject( + msg.pObjectName + ); Part::Feature* feat = static_cast(obj); TopoDS_Shape ref = feat->Shape.getShape().getSubShape(subName.c_str()); @@ -164,9 +165,11 @@ void TaskFemConstraintBearing::onSelectionChanged(const Gui::SelectionChanges& m std::vector SubElements = pcConstraint->References.getSubValues(); if (!Objects.empty()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Use only a single reference for bearing constraint")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Use only a single reference for bearing constraint") + ); return; } if (subName.substr(0, 4) != "Face") { @@ -177,9 +180,11 @@ void TaskFemConstraintBearing::onSelectionChanged(const Gui::SelectionChanges& m // Only cylindrical faces allowed BRepAdaptor_Surface surface(TopoDS::Face(ref)); if (surface.GetType() != GeomAbs_Cylinder) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only cylindrical faces can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only cylindrical faces can be picked") + ); return; } @@ -195,24 +200,30 @@ void TaskFemConstraintBearing::onSelectionChanged(const Gui::SelectionChanges& m else if (selectionMode == selloc) { if (subName.substr(0, 4) == "Face") { if (!Fem::Tools::isPlanar(TopoDS::Face(ref))) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only planar faces can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only planar faces can be picked") + ); return; } } else if (subName.substr(0, 4) == "Edge") { if (!Fem::Tools::isLinear(TopoDS::Edge(ref))) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only linear edges can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only linear edges can be picked") + ); return; } } else { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only faces and edges can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only faces and edges can be picked") + ); return; } std::vector references(1, subName); @@ -320,7 +331,8 @@ void TaskFemConstraintBearing::changeEvent(QEvent* e) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintBearing::TaskDlgFemConstraintBearing( - ViewProviderFemConstraintBearing* ConstraintView) + ViewProviderFemConstraintBearing* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -334,15 +346,18 @@ TaskDlgFemConstraintBearing::TaskDlgFemConstraintBearing( bool TaskDlgFemConstraintBearing::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintBearing* parameterBearing = - static_cast(parameter); + const TaskFemConstraintBearing* parameterBearing = static_cast( + parameter + ); try { // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "FEM force constraint changed")); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Dist = %f", - name.c_str(), - parameterBearing->getDistance()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Dist = %f", + name.c_str(), + parameterBearing->getDistance() + ); std::string locname = parameterBearing->getLocationName().data(); std::string locobj = parameterBearing->getLocationObject().data(); @@ -351,21 +366,27 @@ bool TaskDlgFemConstraintBearing::accept() QString buf = QStringLiteral("(App.ActiveDocument.%1,[\"%2\"])"); buf = buf.arg(QString::fromStdString(locname)); buf = buf.arg(QString::fromStdString(locobj)); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Location = %s", - name.c_str(), - buf.toStdString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Location = %s", + name.c_str(), + buf.toStdString().c_str() + ); } else { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Location = None", - name.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Location = None", + name.c_str() + ); } - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.AxialFree = %s", - name.c_str(), - parameterBearing->getAxial() ? "True" : "False"); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.AxialFree = %s", + name.c_str(), + parameterBearing->getAxial() ? "True" : "False" + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintBearing.h b/src/Mod/Fem/Gui/TaskFemConstraintBearing.h index a03fbcf268..6debe62394 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintBearing.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintBearing.h @@ -51,9 +51,11 @@ class TaskFemConstraintBearing: public TaskFemConstraint Q_OBJECT public: - explicit TaskFemConstraintBearing(ViewProviderFemConstraint* ConstraintView, - QWidget* parent = nullptr, - const char* pixmapname = "FEM_ConstraintBearing"); + explicit TaskFemConstraintBearing( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent = nullptr, + const char* pixmapname = "FEM_ConstraintBearing" + ); ~TaskFemConstraintBearing() override; double getDistance() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp b/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp index d26a574ca7..333b282573 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp @@ -43,8 +43,10 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintContact */ -TaskFemConstraintContact::TaskFemConstraintContact(ViewProviderFemConstraintContact* ConstraintView, - QWidget* parent) +TaskFemConstraintContact::TaskFemConstraintContact( + ViewProviderFemConstraintContact* ConstraintView, + QWidget* parent +) : TaskFemConstraint(ConstraintView, parent, "FEM_ConstraintContact") , ui(new Ui_TaskFemConstraintContact) { @@ -53,32 +55,30 @@ TaskFemConstraintContact::TaskFemConstraintContact(ViewProviderFemConstraintCont QMetaObject::connectSlotsByName(this); QAction* actionSlave = new QAction(tr("Delete"), ui->lw_referencesSlave); - connect(actionSlave, - &QAction::triggered, - this, - &TaskFemConstraintContact::onReferenceDeletedSlave); + connect(actionSlave, &QAction::triggered, this, &TaskFemConstraintContact::onReferenceDeletedSlave); QAction* actionMaster = new QAction(tr("Delete"), ui->lw_referencesMaster); - connect(actionMaster, - &QAction::triggered, - this, - &TaskFemConstraintContact::onReferenceDeletedMaster); + connect(actionMaster, &QAction::triggered, this, &TaskFemConstraintContact::onReferenceDeletedMaster); ui->lw_referencesSlave->addAction(actionSlave); ui->lw_referencesSlave->setContextMenuPolicy(Qt::ActionsContextMenu); - connect(ui->lw_referencesSlave, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintContact::setSelection); + connect( + ui->lw_referencesSlave, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintContact::setSelection + ); ui->lw_referencesMaster->addAction(actionMaster); ui->lw_referencesMaster->setContextMenuPolicy(Qt::ActionsContextMenu); - connect(ui->lw_referencesMaster, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintContact::setSelection); + connect( + ui->lw_referencesMaster, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintContact::setSelection + ); this->groupLayout()->addWidget(proxy); @@ -125,9 +125,11 @@ TaskFemConstraintContact::TaskFemConstraintContact(ViewProviderFemConstraintCont // QMessageBox::warning(this, tr("Objects.size"), QString::number(Objects.size())); if (Objects.size() == 1) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one face in object! - moved to master face")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one face in object! - moved to master face") + ); ui->lw_referencesMaster->addItem(makeRefText(Objects[0], SubElements[0])); } @@ -136,36 +138,33 @@ TaskFemConstraintContact::TaskFemConstraintContact(ViewProviderFemConstraintCont ui->lw_referencesSlave->addItem(makeRefText(Objects[0], SubElements[0])); } - ui->lbl_info->setText(tr("Select slave geometry of type: ") - + QString::fromUtf8("%1; ").arg(tr("Face")) - + tr("click Add or Remove")); - ui->lbl_info_2->setText(tr("Select master geometry of type: ") - + QString::fromUtf8("%1; ").arg(tr("Face")) - + tr("click Add or Remove")); + ui->lbl_info->setText( + tr("Select slave geometry of type: ") + QString::fromUtf8("%1; ").arg(tr("Face")) + + tr("click Add or Remove") + ); + ui->lbl_info_2->setText( + tr("Select master geometry of type: ") + QString::fromUtf8("%1; ").arg(tr("Face")) + + tr("click Add or Remove") + ); // Selection buttons - connect(ui->btnAddSlave, - &QToolButton::clicked, - this, - &TaskFemConstraintContact::addToSelectionSlave); - connect(ui->btnRemoveSlave, - &QToolButton::clicked, - this, - &TaskFemConstraintContact::removeFromSelectionSlave); + connect(ui->btnAddSlave, &QToolButton::clicked, this, &TaskFemConstraintContact::addToSelectionSlave); + connect( + ui->btnRemoveSlave, + &QToolButton::clicked, + this, + &TaskFemConstraintContact::removeFromSelectionSlave + ); - connect(ui->btnAddMaster, - &QToolButton::clicked, - this, - &TaskFemConstraintContact::addToSelectionMaster); - connect(ui->btnRemoveMaster, - &QToolButton::clicked, - this, - &TaskFemConstraintContact::removeFromSelectionMaster); + connect(ui->btnAddMaster, &QToolButton::clicked, this, &TaskFemConstraintContact::addToSelectionMaster); + connect( + ui->btnRemoveMaster, + &QToolButton::clicked, + this, + &TaskFemConstraintContact::removeFromSelectionMaster + ); - connect(ui->ckbFriction, - &QCheckBox::toggled, - this, - &TaskFemConstraintContact::onFrictionChanged); + connect(ui->ckbFriction, &QCheckBox::toggled, this, &TaskFemConstraintContact::onFrictionChanged); updateUI(); } @@ -189,13 +188,14 @@ void TaskFemConstraintContact::updateUI() void TaskFemConstraintContact::addToSelectionSlave() { int rows = ui->lw_referencesSlave->model()->rowCount(); - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (rows == 1) { QMessageBox::warning( this, tr("Selection error"), - tr("Only one master face and one slave face for a contact constraint!")); + tr("Only one master face and one slave face for a contact constraint!") + ); Gui::Selection().clearSelection(); return; } @@ -204,9 +204,11 @@ void TaskFemConstraintContact::addToSelectionSlave() return; } if ((rows == 0) && (selection.size() >= 2)) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one slave face for a contact constraint!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one slave face for a contact constraint!") + ); Gui::Selection().clearSelection(); return; } @@ -222,38 +224,45 @@ void TaskFemConstraintContact::addToSelectionSlave() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); if (subNames.size() != 1) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one slave face for a contact constraint!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one slave face for a contact constraint!") + ); Gui::Selection().clearSelection(); return; } for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; if ((subName.substr(0, 4) != "Face") && (subName.substr(0, 4) != "Edge")) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only faces can be picked (edges in 2D models)")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only faces can be picked (edges in 2D models)") + ); return; } - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -291,16 +300,17 @@ void TaskFemConstraintContact::removeFromSelectionSlave() const std::vector& subNames = it.getSubNames(); const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -324,13 +334,14 @@ void TaskFemConstraintContact::removeFromSelectionSlave() void TaskFemConstraintContact::addToSelectionMaster() { int rows = ui->lw_referencesMaster->model()->rowCount(); - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (rows == 1) { QMessageBox::warning( this, tr("Selection error"), - tr("Only one master face and one slave face for a contact constraint!")); + tr("Only one master face and one slave face for a contact constraint!") + ); Gui::Selection().clearSelection(); return; } @@ -339,9 +350,11 @@ void TaskFemConstraintContact::addToSelectionMaster() return; } if ((rows == 0) && (selection.size() >= 2)) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one master for a contact constraint!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one master for a contact constraint!") + ); Gui::Selection().clearSelection(); return; } @@ -356,39 +369,48 @@ void TaskFemConstraintContact::addToSelectionMaster() } App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); if (subNames.size() != 1) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one master face for a contact constraint!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one master face for a contact constraint!") + ); Gui::Selection().clearSelection(); return; } for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; if ((subName.substr(0, 4) != "Face") && (subName.substr(0, 4) != "Edge")) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only faces can be picked (edges in 2D models)")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only faces can be picked (edges in 2D models)") + ); return; } for (auto itr = std::ranges::find(SubElements.begin(), SubElements.end(), subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + itr = std::find( + ++itr, + SubElements.end(), + subName + )) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -407,8 +429,8 @@ void TaskFemConstraintContact::addToSelectionMaster() void TaskFemConstraintContact::removeFromSelectionMaster() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -426,16 +448,17 @@ void TaskFemConstraintContact::removeFromSelectionMaster() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -520,7 +543,8 @@ void TaskFemConstraintContact::changeEvent(QEvent*) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintContact::TaskDlgFemConstraintContact( - ViewProviderFemConstraintContact* ConstraintView) + ViewProviderFemConstraintContact* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -535,30 +559,41 @@ bool TaskDlgFemConstraintContact::accept() { /* Note: */ std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintContact* parameterContact = - static_cast(parameter); + const TaskFemConstraintContact* parameterContact = static_cast( + parameter + ); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Slope = \"%s\"", - name.c_str(), - parameterContact->getSlope().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Adjust = \"%s\"", - name.c_str(), - parameterContact->getAdjust().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Friction = %s", - name.c_str(), - parameterContact->getFriction() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.FrictionCoefficient = %f", - name.c_str(), - parameterContact->getFrictionCoeff()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.StickSlope = \"%s\"", - name.c_str(), - parameterContact->getStickSlope().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Slope = \"%s\"", + name.c_str(), + parameterContact->getSlope().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Adjust = \"%s\"", + name.c_str(), + parameterContact->getAdjust().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Friction = %s", + name.c_str(), + parameterContact->getFriction() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.FrictionCoefficient = %f", + name.c_str(), + parameterContact->getFrictionCoeff() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.StickSlope = \"%s\"", + name.c_str(), + parameterContact->getStickSlope().c_str() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintContact.h b/src/Mod/Fem/Gui/TaskFemConstraintContact.h index 98d86ae79a..a39831ba8e 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintContact.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintContact.h @@ -42,8 +42,10 @@ class TaskFemConstraintContact: public TaskFemConstraint Q_OBJECT public: - explicit TaskFemConstraintContact(ViewProviderFemConstraintContact* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintContact( + ViewProviderFemConstraintContact* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintContact() override; const std::string getReferences() const override; const std::string getAdjust() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp index 5910b2a7e4..f1ab6d73b8 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp @@ -46,7 +46,8 @@ using namespace Gui; TaskFemConstraintDisplacement::TaskFemConstraintDisplacement( ViewProviderFemConstraintDisplacement* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintDisplacement") , ui(new Ui_TaskFemConstraintDisplacement) { @@ -56,19 +57,20 @@ TaskFemConstraintDisplacement::TaskFemConstraintDisplacement( // create a context menu for the listview of the references createActions(ui->lw_references); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintDisplacement::onReferenceDeleted); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintDisplacement::onReferenceDeleted); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintDisplacement::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintDisplacement::setSelection); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintDisplacement::setSelection + ); + connect( + ui->lw_references, + &QListWidget::itemClicked, + this, + &TaskFemConstraintDisplacement::setSelection + ); this->groupLayout()->addWidget(proxy); @@ -88,8 +90,8 @@ TaskFemConstraintDisplacement::TaskFemConstraintDisplacement( ui->spinzRotation->setMaximum(max); // Get the feature data - Fem::ConstraintDisplacement* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintDisplacement* pcConstraint + = ConstraintView->getObject(); Base::Quantity fStates[6] {}; const char* sStates[3] {}; bool bStates[10] {}; @@ -125,18 +127,9 @@ TaskFemConstraintDisplacement::TaskFemConstraintDisplacement( } // Connect check box values displacements - connect(ui->DisplacementXFormulaCB, - &QCheckBox::toggled, - this, - &TaskFemConstraintDisplacement::formulaX); - connect(ui->DisplacementYFormulaCB, - &QCheckBox::toggled, - this, - &TaskFemConstraintDisplacement::formulaY); - connect(ui->DisplacementZFormulaCB, - &QCheckBox::toggled, - this, - &TaskFemConstraintDisplacement::formulaZ); + connect(ui->DisplacementXFormulaCB, &QCheckBox::toggled, this, &TaskFemConstraintDisplacement::formulaX); + connect(ui->DisplacementYFormulaCB, &QCheckBox::toggled, this, &TaskFemConstraintDisplacement::formulaY); + connect(ui->DisplacementZFormulaCB, &QCheckBox::toggled, this, &TaskFemConstraintDisplacement::formulaZ); connect(ui->FlowForceCB, &QCheckBox::toggled, this, &TaskFemConstraintDisplacement::flowForce); // Connect to check box values for rotations @@ -161,8 +154,9 @@ TaskFemConstraintDisplacement::TaskFemConstraintDisplacement( ui->DisplacementZFormulaCB->setChecked(bStates[8]); ui->FlowForceCB->setChecked(bStates[9]); - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face")) + ); // Selection buttons buttonGroup->addButton(ui->btnAdd, static_cast(SelectionChangeModes::refAdd)); @@ -237,14 +231,14 @@ void TaskFemConstraintDisplacement::formulaRotz(bool state) void TaskFemConstraintDisplacement::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintDisplacement* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintDisplacement* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); @@ -256,9 +250,11 @@ void TaskFemConstraintDisplacement::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } @@ -267,15 +263,18 @@ void TaskFemConstraintDisplacement::addToSelection() bool addMe = true; for (auto itr = std::ranges::find(SubElements.begin(), SubElements.end(), subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + itr = std::find( + ++itr, + SubElements.end(), + subName + )) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -293,8 +292,10 @@ void TaskFemConstraintDisplacement::addToSelection() } for (const auto& SubElement : SubElements) { if (SubElement.find(searchStr) == std::string::npos) { - QString msg = tr("Only one type of selection (vertex, face or edge) per " - "analysis feature allowed!"); + QString msg = tr( + "Only one type of selection (vertex, face or edge) per " + "analysis feature allowed!" + ); QMessageBox::warning(this, tr("Selection error"), msg); addMe = false; break; @@ -315,14 +316,14 @@ void TaskFemConstraintDisplacement::addToSelection() void TaskFemConstraintDisplacement::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintDisplacement* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintDisplacement* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); std::vector itemsToDel; @@ -335,16 +336,17 @@ void TaskFemConstraintDisplacement::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -510,7 +512,8 @@ void TaskFemConstraintDisplacement::clearButtons(const SelectionChangeModes notT //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintDisplacement::TaskDlgFemConstraintDisplacement( - ViewProviderFemConstraintDisplacement* ConstraintView) + ViewProviderFemConstraintDisplacement* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -524,87 +527,124 @@ TaskDlgFemConstraintDisplacement::TaskDlgFemConstraintDisplacement( bool TaskDlgFemConstraintDisplacement::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintDisplacement* parameterDisplacement = - static_cast(parameter); + const TaskFemConstraintDisplacement* parameterDisplacement + = static_cast(parameter); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.xDisplacement = \"%s\"", - name.c_str(), - parameterDisplacement->get_spinxDisplacement().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.xDisplacementFormula = \"%s\"", - name.c_str(), - parameterDisplacement->get_xFormula().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.yDisplacement = \"%s\"", - name.c_str(), - parameterDisplacement->get_spinyDisplacement().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.yDisplacementFormula = \"%s\"", - name.c_str(), - parameterDisplacement->get_yFormula().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.zDisplacement = \"%s\"", - name.c_str(), - parameterDisplacement->get_spinzDisplacement().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.zDisplacementFormula = \"%s\"", - name.c_str(), - parameterDisplacement->get_zFormula().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.xRotation = \"%s\"", - name.c_str(), - parameterDisplacement->get_spinxRotation().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.yRotation = \"%s\"", - name.c_str(), - parameterDisplacement->get_spinyRotation().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.zRotation = \"%s\"", - name.c_str(), - parameterDisplacement->get_spinzRotation().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.xFree = %s", - name.c_str(), - parameterDisplacement->get_dispxfree() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.hasXFormula = %s", - name.c_str(), - parameterDisplacement->get_hasDispXFormula() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.yFree = %s", - name.c_str(), - parameterDisplacement->get_dispyfree() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.hasYFormula = %s", - name.c_str(), - parameterDisplacement->get_hasDispYFormula() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.zFree = %s", - name.c_str(), - parameterDisplacement->get_dispzfree() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.hasZFormula = %s", - name.c_str(), - parameterDisplacement->get_hasDispZFormula() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.rotxFree = %s", - name.c_str(), - parameterDisplacement->get_rotxfree() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.rotyFree = %s", - name.c_str(), - parameterDisplacement->get_rotyfree() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.rotzFree = %s", - name.c_str(), - parameterDisplacement->get_rotzfree() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.useFlowSurfaceForce = %s", - name.c_str(), - parameterDisplacement->get_useFlowSurfaceForce() ? "True" - : "False"); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.xDisplacement = \"%s\"", + name.c_str(), + parameterDisplacement->get_spinxDisplacement().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.xDisplacementFormula = \"%s\"", + name.c_str(), + parameterDisplacement->get_xFormula().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.yDisplacement = \"%s\"", + name.c_str(), + parameterDisplacement->get_spinyDisplacement().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.yDisplacementFormula = \"%s\"", + name.c_str(), + parameterDisplacement->get_yFormula().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.zDisplacement = \"%s\"", + name.c_str(), + parameterDisplacement->get_spinzDisplacement().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.zDisplacementFormula = \"%s\"", + name.c_str(), + parameterDisplacement->get_zFormula().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.xRotation = \"%s\"", + name.c_str(), + parameterDisplacement->get_spinxRotation().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.yRotation = \"%s\"", + name.c_str(), + parameterDisplacement->get_spinyRotation().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.zRotation = \"%s\"", + name.c_str(), + parameterDisplacement->get_spinzRotation().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.xFree = %s", + name.c_str(), + parameterDisplacement->get_dispxfree() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.hasXFormula = %s", + name.c_str(), + parameterDisplacement->get_hasDispXFormula() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.yFree = %s", + name.c_str(), + parameterDisplacement->get_dispyfree() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.hasYFormula = %s", + name.c_str(), + parameterDisplacement->get_hasDispYFormula() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.zFree = %s", + name.c_str(), + parameterDisplacement->get_dispzfree() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.hasZFormula = %s", + name.c_str(), + parameterDisplacement->get_hasDispZFormula() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.rotxFree = %s", + name.c_str(), + parameterDisplacement->get_rotxfree() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.rotyFree = %s", + name.c_str(), + parameterDisplacement->get_rotyfree() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.rotzFree = %s", + name.c_str(), + parameterDisplacement->get_rotzfree() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.useFlowSurfaceForce = %s", + name.c_str(), + parameterDisplacement->get_useFlowSurfaceForce() ? "True" : "False" + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h index 38f2122d9f..45c411bd42 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h @@ -46,8 +46,10 @@ class TaskFemConstraintDisplacement: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintDisplacement(ViewProviderFemConstraintDisplacement* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintDisplacement( + ViewProviderFemConstraintDisplacement* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintDisplacement() override; const std::string getReferences() const override; @@ -98,8 +100,7 @@ class TaskDlgFemConstraintDisplacement: public TaskDlgFemConstraint Q_OBJECT public: - explicit TaskDlgFemConstraintDisplacement( - ViewProviderFemConstraintDisplacement* ConstraintView); + explicit TaskDlgFemConstraintDisplacement(ViewProviderFemConstraintDisplacement* ConstraintView); bool accept() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp b/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp index 9c80cb43d5..3b5d9ca477 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp @@ -42,8 +42,10 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintFixed */ -TaskFemConstraintFixed::TaskFemConstraintFixed(ViewProviderFemConstraintFixed* ConstraintView, - QWidget* parent) +TaskFemConstraintFixed::TaskFemConstraintFixed( + ViewProviderFemConstraintFixed* ConstraintView, + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintFixed") , ui(new Ui_TaskFemConstraintFixed) { // Note change "Fixed" in line above to new constraint name @@ -54,14 +56,13 @@ TaskFemConstraintFixed::TaskFemConstraintFixed(ViewProviderFemConstraintFixed* C // create a context menu for the listview of the references createActions(ui->lw_references); connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintFixed::onReferenceDeleted); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintFixed::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintFixed::setSelection); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintFixed::setSelection + ); + connect(ui->lw_references, &QListWidget::itemClicked, this, &TaskFemConstraintFixed::setSelection); this->groupLayout()->addWidget(proxy); @@ -82,8 +83,9 @@ TaskFemConstraintFixed::TaskFemConstraintFixed(ViewProviderFemConstraintFixed* C ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face")) + ); // Selection buttons buttonGroup->addButton(ui->btnAdd, (int)SelectionChangeModes::refAdd); @@ -123,25 +125,28 @@ void TaskFemConstraintFixed::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -159,8 +164,10 @@ void TaskFemConstraintFixed::addToSelection() } for (const auto& SubElement : SubElements) { if (SubElement.find(searchStr) == std::string::npos) { - QString msg = tr("Only one type of selection (vertex, face or edge) per " - "analysis feature allowed!"); + QString msg = tr( + "Only one type of selection (vertex, face or edge) per " + "analysis feature allowed!" + ); QMessageBox::warning(this, tr("Selection error"), msg); addMe = false; break; @@ -200,16 +207,17 @@ void TaskFemConstraintFixed::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFixed.h b/src/Mod/Fem/Gui/TaskFemConstraintFixed.h index 81d8f45731..9f3dedfca0 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFixed.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintFixed.h @@ -40,8 +40,10 @@ class TaskFemConstraintFixed: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintFixed(ViewProviderFemConstraintFixed* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintFixed( + ViewProviderFemConstraintFixed* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintFixed() override; const std::string getReferences() const override; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp index 744b339007..6cef1efb7a 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp @@ -57,18 +57,14 @@ using namespace Fem; // also defined in FemConstrainFluidBoundary and foamcasebuilder/basicbuilder.py, please update // simultaneously the second (index 1) is the default enum, as index 0 causes compiling error static // const char* BoundaryTypes[] = {"inlet","wall","outlet","freestream", "interface", NULL}; -static const char* WallSubtypes[] = - {"unspecific", "fixed", "slip", "partialSlip", "moving", "rough", nullptr}; -static const char* InletSubtypes[] = {"unspecific", - "totalPressure", - "uniformVelocity", - "volumetricFlowRate", - "massFlowRate", - nullptr}; -static const char* OutletSubtypes[] = - {"unspecific", "totalPressure", "staticPressure", "uniformVelocity", "outFlow", nullptr}; -static const char* InterfaceSubtypes[] = - {"unspecific", "symmetry", "wedge", "cyclic", "empty", "coupled", nullptr}; +static const char* WallSubtypes[] + = {"unspecific", "fixed", "slip", "partialSlip", "moving", "rough", nullptr}; +static const char* InletSubtypes[] + = {"unspecific", "totalPressure", "uniformVelocity", "volumetricFlowRate", "massFlowRate", nullptr}; +static const char* OutletSubtypes[] + = {"unspecific", "totalPressure", "staticPressure", "uniformVelocity", "outFlow", nullptr}; +static const char* InterfaceSubtypes[] + = {"unspecific", "symmetry", "wedge", "cyclic", "empty", "coupled", nullptr}; static const char* FreestreamSubtypes[] = {"unspecific", "freestream", nullptr}; static const char* InterfaceSubtypeHelpTexts[] = { @@ -78,7 +74,8 @@ static const char* InterfaceSubtypeHelpTexts[] = { "periodic boundary in pair, treated as physical connected", "front and back for single layer 2D mesh, also axis-sym axis line", "exchange boundary vale with external program, need extra manual setup like file name", - nullptr}; + nullptr +}; // defined in file FemConstraintFluidBoundary: // see Ansys fluet manual: Turbulence Specification method @@ -90,24 +87,25 @@ static const char* TurbulenceSpecificationHelpTexts[] = { "intensity (0.05 ~ 0.15) and characteristic length scale of max eddy [m]", "intensity (0.05 ~ 0.15) and turbulent viscosity ratio", "for fully developed internal flow, Turbulence intensity (0-1.0) 0.05 typical", - nullptr}; + nullptr +}; // static const char* ThermalBoundaryTypes[] = {"fixedValue","zeroGradient", "fixedGradient", // "mixed", "heatFlux", "HTC","coupled", NULL}; -static const char* ThermalBoundaryHelpTexts[] = {"fixed Temperature [K]", - "no heat transfer on boundary", - "fixed value gradient [K/m]", - "mixed fixedGradient and fixedValue", - "fixed heat flux [W/m2]", - "Heat transfer coeff [W/(M2)/K]", - "conjugate heat transfer with solid", - nullptr}; +static const char* ThermalBoundaryHelpTexts[] = { + "fixed Temperature [K]", + "no heat transfer on boundary", + "fixed value gradient [K/m]", + "mixed fixedGradient and fixedValue", + "fixed heat flux [W/m2]", + "Heat transfer coeff [W/(M2)/K]", + "conjugate heat transfer with solid", + nullptr +}; // enable & disable quantityUI once valueType is selected // internal function not declared in header file -void initComboBox(QComboBox* combo, - const std::vector& textItems, - const std::string& sItem) +void initComboBox(QComboBox* combo, const std::vector& textItems, const std::string& sItem) { combo->blockSignals(true); @@ -126,7 +124,8 @@ void initComboBox(QComboBox* combo, /* TRANSLATOR FemGui::TaskFemConstraintFluidBoundary */ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( ViewProviderFemConstraintFluidBoundary* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintFluidBoundary") , ui(new Ui_TaskFemConstraintFluidBoundary) , dimension(-1) @@ -138,10 +137,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( // create a context menu for the listview of the references createActions(ui->listReferences); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintFluidBoundary::onReferenceDeleted); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintFluidBoundary::onReferenceDeleted); // setup ranges constexpr float max = std::numeric_limits::max(); @@ -158,40 +154,47 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( ui->spinHTCoeffValue->setMinimum(0.0); ui->spinHTCoeffValue->setMaximum(max); - connect(ui->comboBoundaryType, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskFemConstraintFluidBoundary::onBoundaryTypeChanged); - connect(ui->comboSubtype, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskFemConstraintFluidBoundary::onSubtypeChanged); - connect(ui->spinBoundaryValue, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintFluidBoundary::onBoundaryValueChanged); + connect( + ui->comboBoundaryType, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskFemConstraintFluidBoundary::onBoundaryTypeChanged + ); + connect( + ui->comboSubtype, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskFemConstraintFluidBoundary::onSubtypeChanged + ); + connect( + ui->spinBoundaryValue, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintFluidBoundary::onBoundaryValueChanged + ); - connect(ui->comboTurbulenceSpecification, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskFemConstraintFluidBoundary::onTurbulenceSpecificationChanged); - connect(ui->comboThermalBoundaryType, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskFemConstraintFluidBoundary::onThermalBoundaryTypeChanged); + connect( + ui->comboTurbulenceSpecification, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskFemConstraintFluidBoundary::onTurbulenceSpecificationChanged + ); + connect( + ui->comboThermalBoundaryType, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskFemConstraintFluidBoundary::onThermalBoundaryTypeChanged + ); - connect(ui->buttonDirection, &QPushButton::pressed, this, [this] { - onButtonDirection(true); - }); - connect(ui->checkReverse, - &QCheckBox::toggled, - this, - &TaskFemConstraintFluidBoundary::onCheckReverse); + connect(ui->buttonDirection, &QPushButton::pressed, this, [this] { onButtonDirection(true); }); + connect(ui->checkReverse, &QCheckBox::toggled, this, &TaskFemConstraintFluidBoundary::onCheckReverse); - connect(ui->listReferences, - &QListWidget::itemClicked, - this, - &TaskFemConstraintFluidBoundary::setSelection); + connect( + ui->listReferences, + &QListWidget::itemClicked, + this, + &TaskFemConstraintFluidBoundary::setSelection + ); this->groupLayout()->addWidget(proxy); @@ -207,8 +210,8 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( buttonGroup->addButton(ui->btnRemove, (int)SelectionChangeModes::refRemove); // Get the feature data - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); Fem::FemAnalysis* pcAnalysis = nullptr; if (FemGui::ActiveAnalysisObserver::instance()->hasActiveObject()) { @@ -216,8 +219,9 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } else { App::Document* aDoc = pcConstraint->getDocument(); - std::vector fem = - aDoc->getObjectsOfType(Fem::FemAnalysis::getClassTypeId()); + std::vector fem = aDoc->getObjectsOfType( + Fem::FemAnalysis::getClassTypeId() + ); if (!fem.empty()) { pcAnalysis = static_cast(fem[0]); // get the first } @@ -233,8 +237,10 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } } else { - Base::Console().log("FemAnalysis object is not activated or no FemAnalysis in the active " - "document, mesh dimension is unknown\n"); + Base::Console().log( + "FemAnalysis object is not activated or no FemAnalysis in the active " + "document, mesh dimension is unknown\n" + ); dimension = -1; // unknown dimension of mesh } if (pcMesh) { @@ -244,8 +250,8 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( Part::Feature* pcPart = dynamic_cast(pcLink->getValue()); if (pcPart) { // deduct dimension from part_obj.Shape.ShapeType const TopoDS_Shape& pShape = pcPart->Shape.getShape().getShape(); - const TopAbs_ShapeEnum shapeType = - pShape.IsNull() ? TopAbs_SHAPE : pShape.ShapeType(); + const TopAbs_ShapeEnum shapeType = pShape.IsNull() ? TopAbs_SHAPE + : pShape.ShapeType(); if (shapeType == TopAbs_SOLID || shapeType == TopAbs_COMPSOLID) { // COMPSOLID is solids connected by faces dimension = 3; @@ -257,8 +263,8 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( dimension = 1; } else { - dimension = - -1; // Vertex (0D) can not make mesh, Compound type might contain any types + dimension = -1; // Vertex (0D) can not make mesh, Compound type might contain + // any types } } } @@ -280,13 +286,16 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( // if only it is CFD solver, otherwise exit by SIGSEGV error, detect getPropertyByName() != // NULL if (pcSolver->getPropertyByName("HeatTransferring")) { - pHeatTransferring = - static_cast(pcSolver->getPropertyByName("HeatTransferring")); + pHeatTransferring = static_cast( + pcSolver->getPropertyByName("HeatTransferring") + ); if (pHeatTransferring->getValue()) { ui->tabThermalBoundary->setEnabled(true); - initComboBox(ui->comboThermalBoundaryType, - pcConstraint->ThermalBoundaryType.getEnumVector(), - pcConstraint->ThermalBoundaryType.getValueAsString()); + initComboBox( + ui->comboThermalBoundaryType, + pcConstraint->ThermalBoundaryType.getEnumVector(), + pcConstraint->ThermalBoundaryType.getValueAsString() + ); ui->spinHTCoeffValue->setValue(pcConstraint->HTCoeffValue.getValue()); ui->spinHeatFluxValue->setValue(pcConstraint->HeatFluxValue.getValue()); ui->spinTemperatureValue->setValue(pcConstraint->TemperatureValue.getValue()); @@ -302,21 +311,25 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } if (pcSolver->getPropertyByName("TurbulenceModel")) { pTurbulenceModel = static_cast( - pcSolver->getPropertyByName("TurbulenceModel")); + pcSolver->getPropertyByName("TurbulenceModel") + ); if (pTurbulenceModel->getValueAsString() == std::string("laminar")) { ui->tabTurbulenceBoundary->setEnabled(false); } else { ui->tabTurbulenceBoundary->setEnabled(true); ui->labelTurbulenceSpecification->setText( - QString::fromStdString(pTurbulenceModel->getValueAsString())); - initComboBox(ui->comboTurbulenceSpecification, - pcConstraint->TurbulenceSpecification.getEnumVector(), - pcConstraint->TurbulenceSpecification.getValueAsString()); + QString::fromStdString(pTurbulenceModel->getValueAsString()) + ); + initComboBox( + ui->comboTurbulenceSpecification, + pcConstraint->TurbulenceSpecification.getEnumVector(), + pcConstraint->TurbulenceSpecification.getValueAsString() + ); ui->spinTurbulentIntensityValue->setValue( - pcConstraint->TurbulentIntensityValue.getValue()); - ui->spinTurbulentLengthValue->setValue( - pcConstraint->TurbulentLengthValue.getValue()); + pcConstraint->TurbulentIntensityValue.getValue() + ); + ui->spinTurbulentLengthValue->setValue(pcConstraint->TurbulentLengthValue.getValue()); updateTurbulenceUI(); } } @@ -326,7 +339,8 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( } else { Base::Console().warning( - "No solver object inside FemAnalysis object, default to non-thermal, non-turbulence\n"); + "No solver object inside FemAnalysis object, default to non-thermal, non-turbulence\n" + ); } ui->tabWidget->setTabText(0, tr("Basic")); ui->tabWidget->setTabText(1, tr("Turbulence")); @@ -334,9 +348,11 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( ui->tabWidget->setCurrentIndex(0); ui->labelHelpText->setText(tr("select boundary type, faces and set value")); - initComboBox(ui->comboBoundaryType, - pcConstraint->BoundaryType.getEnumVector(), - pcConstraint->BoundaryType.getValueAsString()); + initComboBox( + ui->comboBoundaryType, + pcConstraint->BoundaryType.getEnumVector(), + pcConstraint->BoundaryType.getValueAsString() + ); updateBoundaryTypeUI(); std::vector subtypes = pcConstraint->Subtype.getEnumVector(); initComboBox(ui->comboSubtype, subtypes, pcConstraint->Subtype.getValueAsString()); @@ -370,8 +386,9 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary( ui->buttonDirection->blockSignals(false); ui->checkReverse->blockSignals(false); - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Face")) + ); updateUI(); } @@ -383,8 +400,8 @@ const Fem::FemSolverObject* TaskFemConstraintFluidBoundary::getFemSolver() const void TaskFemConstraintFluidBoundary::updateBoundaryTypeUI() { - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); std::string boundaryType = ui->comboBoundaryType->currentText().toStdString(); // std::string boundaryType = pcConstraint->BoundaryType.getValueAsString(); @@ -418,8 +435,7 @@ void TaskFemConstraintFluidBoundary::updateBoundaryTypeUI() pcConstraint->Reversed.setValue(false); // outlet must point outward } else { - Base::Console().error("Error: Fluid boundary type `%s` is not defined\n", - boundaryType.c_str()); + Base::Console().error("Error: Fluid boundary type `%s` is not defined\n", boundaryType.c_str()); } // std::string subtypeLabel = boundaryType + std::string(" type"); // ui->labelSubtype->setText(QString::fromUtf8(subtypeLabel)); // too long to show in UI @@ -503,7 +519,8 @@ void TaskFemConstraintFluidBoundary::updateSubtypeUI() void TaskFemConstraintFluidBoundary::updateTurbulenceUI() { ui->labelHelpText->setText( - tr(TurbulenceSpecificationHelpTexts[ui->comboTurbulenceSpecification->currentIndex()])); + tr(TurbulenceSpecificationHelpTexts[ui->comboTurbulenceSpecification->currentIndex()]) + ); /// hide/disable UI only happened in constructor, update helptext and label text here std::string turbulenceSpec = ui->comboTurbulenceSpecification->currentText().toStdString(); ui->labelTurbulentIntensityValue->setText(tr("Intensity [0~1]")); @@ -531,7 +548,8 @@ void TaskFemConstraintFluidBoundary::updateThermalBoundaryUI() // thermalBoundaryType = pcConstraint->ThermalBoundaryType.getValueAsString(); ui->labelHelpText->setText( - tr(ThermalBoundaryHelpTexts[ui->comboThermalBoundaryType->currentIndex()])); + tr(ThermalBoundaryHelpTexts[ui->comboThermalBoundaryType->currentIndex()]) + ); // to hide/disable UI according to subtype std::string thermalBoundaryType = ui->comboThermalBoundaryType->currentText().toStdString(); ui->spinHTCoeffValue->setEnabled(false); @@ -561,15 +579,17 @@ void TaskFemConstraintFluidBoundary::updateThermalBoundaryUI() ui->spinTemperatureValue->setEnabled(true); } else { - Base::Console().error("Thermal boundary type `%s` is not defined\n", - thermalBoundaryType.c_str()); + Base::Console().error( + "Thermal boundary type `%s` is not defined\n", + thermalBoundaryType.c_str() + ); } } void TaskFemConstraintFluidBoundary::onBoundaryTypeChanged() { - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); // temporarily change BoundaryType property, but command transaction should reset it back if you // 'reject' late pcConstraint->BoundaryType.setValue(ui->comboBoundaryType->currentIndex()); @@ -582,8 +602,10 @@ void TaskFemConstraintFluidBoundary::onBoundaryTypeChanged() bool ret = pcConstraint->recomputeFeature(); if (!ret) { std::string boundaryType = ui->comboBoundaryType->currentText().toStdString(); - Base::Console().error("Fluid boundary recomputationg failed for boundaryType `%s` \n", - boundaryType.c_str()); + Base::Console().error( + "Fluid boundary recomputationg failed for boundaryType `%s` \n", + boundaryType.c_str() + ); } } @@ -599,17 +621,16 @@ void TaskFemConstraintFluidBoundary::onBoundaryValueChanged(double) } void TaskFemConstraintFluidBoundary::onTurbulenceSpecificationChanged() { - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); - pcConstraint->TurbulenceSpecification.setValue( - ui->comboTurbulenceSpecification->currentIndex()); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); + pcConstraint->TurbulenceSpecification.setValue(ui->comboTurbulenceSpecification->currentIndex()); updateTurbulenceUI(); } void TaskFemConstraintFluidBoundary::onThermalBoundaryTypeChanged() { - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); pcConstraint->ThermalBoundaryType.setValue(ui->comboThermalBoundaryType->currentIndex()); updateThermalBoundaryUI(); } @@ -634,26 +655,26 @@ void TaskFemConstraintFluidBoundary::onButtonDirection(const bool pressed) QMessageBox::warning(this, tr("Empty selection"), tr("Select an edge or a face.")); return; } - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); // we only handle the first selected object Gui::SelectionObject& selectionElement = selection.at(0); // we can only handle part objects if (!selectionElement.isObjectTypeOf(Part::Feature::getClassTypeId())) { - QMessageBox::warning(this, - tr("Wrong selection"), - tr("Selected object is not a part object!")); + QMessageBox::warning(this, tr("Wrong selection"), tr("Selected object is not a part object!")); return; } // get the names of the subobjects const std::vector& subNames = selectionElement.getSubNames(); if (subNames.size() != 1) { - QMessageBox::warning(this, - tr("Wrong selection"), - tr("Only one planar face or edge can be selected!")); + QMessageBox::warning( + this, + tr("Wrong selection"), + tr("Only one planar face or edge can be selected!") + ); return; } @@ -667,24 +688,30 @@ void TaskFemConstraintFluidBoundary::onButtonDirection(const bool pressed) if (subNamesElement.substr(0, 4) == "Face") { if (!Fem::Tools::isPlanar(TopoDS::Face(ref))) { - QMessageBox::warning(this, - tr("Wrong selection"), - tr("Only planar faces can be picked for 3D")); + QMessageBox::warning( + this, + tr("Wrong selection"), + tr("Only planar faces can be picked for 3D") + ); return; } } else if (subNamesElement.substr(0, 4) == "Edge") { // 2D or 3D can use edge as direction vector if (!Fem::Tools::isLinear(TopoDS::Edge(ref))) { - QMessageBox::warning(this, - tr("Wrong selection"), - tr("Only planar edges can be picked for 2D")); + QMessageBox::warning( + this, + tr("Wrong selection"), + tr("Only planar edges can be picked for 2D") + ); return; } } else { - QMessageBox::warning(this, - tr("Wrong selection"), - tr("Only faces for 3D part or edges for 2D can be picked")); + QMessageBox::warning( + this, + tr("Wrong selection"), + tr("Only faces for 3D part or edges for 2D can be picked") + ); return; } @@ -698,8 +725,8 @@ void TaskFemConstraintFluidBoundary::onButtonDirection(const bool pressed) void TaskFemConstraintFluidBoundary::onCheckReverse(const bool pressed) { - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); pcConstraint->Reversed.setValue(pressed); } @@ -816,14 +843,14 @@ TaskFemConstraintFluidBoundary::~TaskFemConstraintFluidBoundary() = default; void TaskFemConstraintFluidBoundary::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); @@ -835,25 +862,28 @@ void TaskFemConstraintFluidBoundary::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -872,8 +902,10 @@ void TaskFemConstraintFluidBoundary::addToSelection() for (const auto& SubElement : SubElements) { if (SubElement.find(searchStr) == std::string::npos) { - QString msg = tr("Only one type of selection (vertex, face or edge) per " - "analysis feature allowed!"); + QString msg = tr( + "Only one type of selection (vertex, face or edge) per " + "analysis feature allowed!" + ); QMessageBox::warning(this, tr("Selection error"), msg); addMe = false; break; @@ -894,14 +926,14 @@ void TaskFemConstraintFluidBoundary::addToSelection() void TaskFemConstraintFluidBoundary::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintFluidBoundary* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintFluidBoundary* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); std::vector itemsToDel; @@ -914,16 +946,17 @@ void TaskFemConstraintFluidBoundary::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -984,7 +1017,8 @@ void TaskFemConstraintFluidBoundary::clearButtons(const SelectionChangeModes not //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintFluidBoundary::TaskDlgFemConstraintFluidBoundary( - ViewProviderFemConstraintFluidBoundary* ConstraintView) + ViewProviderFemConstraintFluidBoundary* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -998,26 +1032,32 @@ TaskDlgFemConstraintFluidBoundary::TaskDlgFemConstraintFluidBoundary( bool TaskDlgFemConstraintFluidBoundary::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintFluidBoundary* boundary = - static_cast(parameter); + const TaskFemConstraintFluidBoundary* boundary + = static_cast(parameter); // no need to backup pcConstraint object content, if rejected, content can be recovered by // transaction manager try { // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Fluid boundary condition // changed")); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.BoundaryType = '%s'", - name.c_str(), - boundary->getBoundaryType().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Subtype = '%s'", - name.c_str(), - boundary->getSubtype().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.BoundaryValue = %f", - name.c_str(), - boundary->getBoundaryValue()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.BoundaryType = '%s'", + name.c_str(), + boundary->getBoundaryType().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Subtype = '%s'", + name.c_str(), + boundary->getSubtype().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.BoundaryValue = %f", + name.c_str(), + boundary->getBoundaryValue() + ); std::string dirname = boundary->getDirectionName().data(); std::string dirobj = boundary->getDirectionObject().data(); @@ -1026,15 +1066,19 @@ bool TaskDlgFemConstraintFluidBoundary::accept() QString buf = QStringLiteral("(App.ActiveDocument.%1,[\"%2\"])"); buf = buf.arg(QString::fromStdString(dirname)); buf = buf.arg(QString::fromStdString(dirobj)); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Direction = %s", - name.c_str(), - buf.toStdString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Direction = %s", + name.c_str(), + buf.toStdString().c_str() + ); } else { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Direction = None", - name.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Direction = None", + name.c_str() + ); } // Reverse control is done at BoundaryType selection, this UI is hidden from user // Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.%s.Reversed = %s", @@ -1046,51 +1090,69 @@ bool TaskDlgFemConstraintFluidBoundary::accept() if (pcSolver) { App::PropertyBool* pHeatTransferring = nullptr; App::PropertyEnumeration* pTurbulenceModel = nullptr; - pHeatTransferring = - static_cast(pcSolver->getPropertyByName("HeatTransferring")); + pHeatTransferring = static_cast( + pcSolver->getPropertyByName("HeatTransferring") + ); pTurbulenceModel = static_cast( - pcSolver->getPropertyByName("TurbulenceModel")); + pcSolver->getPropertyByName("TurbulenceModel") + ); if (pHeatTransferring && pHeatTransferring->getValue()) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ThermalBoundaryType = '%s'", - name.c_str(), - boundary->getThermalBoundaryType().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TemperatureValue = %f", - name.c_str(), - boundary->getTemperatureValue()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.HeatFluxValue = %f", - name.c_str(), - boundary->getHeatFluxValue()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.HTCoeffValue = %f", - name.c_str(), - boundary->getHTCoeffValue()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ThermalBoundaryType = '%s'", + name.c_str(), + boundary->getThermalBoundaryType().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TemperatureValue = %f", + name.c_str(), + boundary->getTemperatureValue() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.HeatFluxValue = %f", + name.c_str(), + boundary->getHeatFluxValue() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.HTCoeffValue = %f", + name.c_str(), + boundary->getHTCoeffValue() + ); } if (pTurbulenceModel && std::string(pTurbulenceModel->getValueAsString()) != "laminar") { // Invisic and DNS flow also does not need this // update turbulence and thermal boundary settings, only if those models are // activated - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TurbulenceSpecification = '%s'", - name.c_str(), - boundary->getTurbulenceSpecification().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TurbulentIntensityValue = %f", - name.c_str(), - boundary->getTurbulentIntensityValue()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TurbulentLengthValue = %f", - name.c_str(), - boundary->getTurbulentLengthValue()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TurbulenceSpecification = '%s'", + name.c_str(), + boundary->getTurbulenceSpecification().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TurbulentIntensityValue = %f", + name.c_str(), + boundary->getTurbulentIntensityValue() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TurbulentLengthValue = %f", + name.c_str(), + boundary->getTurbulentLengthValue() + ); } } else { - Base::Console().warning("FemSolverObject is not found in the FemAnalysis object, " - "thermal and turbulence setting is not accepted\n"); + Base::Console().warning( + "FemSolverObject is not found in the FemAnalysis object, " + "thermal and turbulence setting is not accepted\n" + ); } } catch (const Base::Exception& e) { diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h index 1441ffc198..a7701193fd 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h @@ -52,8 +52,10 @@ class TaskFemConstraintFluidBoundary: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintFluidBoundary(ViewProviderFemConstraintFluidBoundary* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintFluidBoundary( + ViewProviderFemConstraintFluidBoundary* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintFluidBoundary() override; const Fem::FemSolverObject* getFemSolver() const; @@ -115,8 +117,7 @@ class TaskDlgFemConstraintFluidBoundary: public TaskDlgFemConstraint Q_OBJECT public: - explicit TaskDlgFemConstraintFluidBoundary( - ViewProviderFemConstraintFluidBoundary* ConstraintView); + explicit TaskDlgFemConstraintFluidBoundary(ViewProviderFemConstraintFluidBoundary* ConstraintView); /// is called by the framework if the dialog is accepted (Ok) bool accept() override; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp b/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp index 23541fbd2f..10f7297169 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp @@ -47,8 +47,10 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintForce */ -TaskFemConstraintForce::TaskFemConstraintForce(ViewProviderFemConstraintForce* ConstraintView, - QWidget* parent) +TaskFemConstraintForce::TaskFemConstraintForce( + ViewProviderFemConstraintForce* ConstraintView, + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintForce") , ui(new Ui_TaskFemConstraintForce) { @@ -86,21 +88,16 @@ TaskFemConstraintForce::TaskFemConstraintForce(ViewProviderFemConstraintForce* C ui->lineDirection->setText(dir.isEmpty() ? QString() : dir); ui->checkReverse->setChecked(reversed); - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face")) + ); // create a context menu for the listview of the references createActions(ui->listReferences); connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintForce::onReferenceDeleted); - connect(ui->buttonDirection, - &QToolButton::clicked, - this, - &TaskFemConstraintForce::onButtonDirection); + connect(ui->buttonDirection, &QToolButton::clicked, this, &TaskFemConstraintForce::onButtonDirection); connect(ui->checkReverse, &QCheckBox::toggled, this, &TaskFemConstraintForce::onCheckReverse); - connect(ui->listReferences, - &QListWidget::itemClicked, - this, - &TaskFemConstraintForce::setSelection); + connect(ui->listReferences, &QListWidget::itemClicked, this, &TaskFemConstraintForce::setSelection); // Selection buttons buttonGroup->addButton(ui->btnAdd, (int)SelectionChangeModes::refAdd); @@ -122,8 +119,8 @@ void TaskFemConstraintForce::updateUI() void TaskFemConstraintForce::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -140,25 +137,28 @@ void TaskFemConstraintForce::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -177,8 +177,10 @@ void TaskFemConstraintForce::addToSelection() for (const auto& SubElement : SubElements) { if (SubElement.find(searchStr) == std::string::npos) { - QString msg = tr("Only one type of selection (vertex, face or edge) per " - "analysis feature allowed!"); + QString msg = tr( + "Only one type of selection (vertex, face or edge) per " + "analysis feature allowed!" + ); QMessageBox::warning(this, tr("Selection error"), msg); addMe = false; break; @@ -199,8 +201,8 @@ void TaskFemConstraintForce::addToSelection() void TaskFemConstraintForce::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -218,16 +220,17 @@ void TaskFemConstraintForce::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -257,8 +260,9 @@ void TaskFemConstraintForce::onReferenceDeleted() // selected, so just remove } -std::pair -TaskFemConstraintForce::getDirection(const std::vector& selection) const +std::pair TaskFemConstraintForce::getDirection( + const std::vector& selection +) const { std::pair link; if (selection.empty()) { @@ -426,14 +430,17 @@ TaskDlgFemConstraintForce::TaskDlgFemConstraintForce(ViewProviderFemConstraintFo bool TaskDlgFemConstraintForce::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintForce* parameterForce = - static_cast(parameter); + const TaskFemConstraintForce* parameterForce = static_cast( + parameter + ); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Force = \"%s\"", - name.c_str(), - parameterForce->getForce().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Force = \"%s\"", + name.c_str(), + parameterForce->getForce().c_str() + ); std::string dirname = parameterForce->getDirectionName().data(); std::string dirobj = parameterForce->getDirectionObject().data(); @@ -443,21 +450,27 @@ bool TaskDlgFemConstraintForce::accept() QString buf = QStringLiteral("(App.ActiveDocument.%1,[\"%2\"])"); buf = buf.arg(QString::fromStdString(dirname)); buf = buf.arg(QString::fromStdString(dirobj)); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Direction = %s", - name.c_str(), - buf.toStdString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Direction = %s", + name.c_str(), + buf.toStdString().c_str() + ); } else { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Direction = None", - name.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Direction = None", + name.c_str() + ); } - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Reversed = %s", - name.c_str(), - parameterForce->getReverse() ? "True" : "False"); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Reversed = %s", + name.c_str(), + parameterForce->getReverse() ? "True" : "False" + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintForce.h b/src/Mod/Fem/Gui/TaskFemConstraintForce.h index 443fb54aed..6b70d7e66c 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintForce.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintForce.h @@ -52,8 +52,10 @@ class TaskFemConstraintForce: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintForce(ViewProviderFemConstraintForce* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintForce( + ViewProviderFemConstraintForce* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintForce() override; const std::string getForce() const; const std::string getReferences() const override; @@ -73,8 +75,9 @@ protected: void clearButtons(const SelectionChangeModes notThis) override; private: - std::pair - getDirection(const std::vector&) const; + std::pair getDirection( + const std::vector& + ) const; void updateUI(); private: diff --git a/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp b/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp index f10be2d015..56c5dba9f9 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp @@ -43,26 +43,32 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintGear */ -TaskFemConstraintGear::TaskFemConstraintGear(ViewProviderFemConstraint* ConstraintView, - QWidget* parent, - const char* pixmapname) +TaskFemConstraintGear::TaskFemConstraintGear( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent, + const char* pixmapname +) : TaskFemConstraintBearing(ConstraintView, parent, pixmapname) { - connect(ui->spinDiameter, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintGear::onDiameterChanged); - connect(ui->spinForce, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintGear::onForceChanged); - connect(ui->spinForceAngle, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintGear::onForceAngleChanged); - connect(ui->buttonDirection, &QPushButton::pressed, this, [this] { - onButtonDirection(true); - }); + connect( + ui->spinDiameter, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintGear::onDiameterChanged + ); + connect( + ui->spinForce, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintGear::onForceChanged + ); + connect( + ui->spinForceAngle, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintGear::onForceAngleChanged + ); + connect(ui->buttonDirection, &QPushButton::pressed, this, [this] { onButtonDirection(true); }); connect(ui->checkReversed, &QCheckBox::toggled, this, &TaskFemConstraintGear::onCheckReversed); // Temporarily prevent unnecessary feature recomputes @@ -135,32 +141,39 @@ void TaskFemConstraintGear::onSelectionChanged(const Gui::SelectionChanges& msg) std::vector references(1, subName); Fem::ConstraintGear* pcConstraint = ConstraintView->getObject(); - App::DocumentObject* obj = - ConstraintView->getObject()->getDocument()->getObject(msg.pObjectName); + App::DocumentObject* obj = ConstraintView->getObject()->getDocument()->getObject( + msg.pObjectName + ); Part::Feature* feat = static_cast(obj); TopoDS_Shape ref = feat->Shape.getShape().getSubShape(subName.c_str()); if (selectionMode == seldir) { if (subName.substr(0, 4) == "Face") { if (!Fem::Tools::isPlanar(TopoDS::Face(ref))) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only planar faces can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only planar faces can be picked") + ); return; } } else if (subName.substr(0, 4) == "Edge") { if (!Fem::Tools::isLinear(TopoDS::Edge(ref))) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only linear edges can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only linear edges can be picked") + ); return; } } else { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only faces and edges can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only faces and edges can be picked") + ); return; } pcConstraint->Direction.setValue(obj, references); @@ -287,8 +300,7 @@ TaskDlgFemConstraintGear::TaskDlgFemConstraintGear(ViewProviderFemConstraintGear bool TaskDlgFemConstraintGear::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintGear* parameterGear = - static_cast(parameter); + const TaskFemConstraintGear* parameterGear = static_cast(parameter); try { // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "FEM force constraint changed")); @@ -299,33 +311,45 @@ bool TaskDlgFemConstraintGear::accept() QString buf = QStringLiteral("(App.ActiveDocument.%1,[\"%2\"])"); buf = buf.arg(QString::fromStdString(dirname)); buf = buf.arg(QString::fromStdString(dirobj)); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Direction = %s", - name.c_str(), - buf.toStdString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Direction = %s", + name.c_str(), + buf.toStdString().c_str() + ); } else { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Direction = None", - name.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Direction = None", + name.c_str() + ); } - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Reversed = %s", - name.c_str(), - parameterGear->getReverse() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Diameter = %f", - name.c_str(), - parameterGear->getDiameter()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Force = %f", - name.c_str(), - parameterGear->getForce()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ForceAngle = %f", - name.c_str(), - parameterGear->getForceAngle()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Reversed = %s", + name.c_str(), + parameterGear->getReverse() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Diameter = %f", + name.c_str(), + parameterGear->getDiameter() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Force = %f", + name.c_str(), + parameterGear->getForce() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ForceAngle = %f", + name.c_str(), + parameterGear->getForceAngle() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintGear.h b/src/Mod/Fem/Gui/TaskFemConstraintGear.h index 6b2f205cd1..8678a3eadd 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintGear.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintGear.h @@ -35,9 +35,11 @@ class TaskFemConstraintGear: public TaskFemConstraintBearing Q_OBJECT public: - explicit TaskFemConstraintGear(ViewProviderFemConstraint* ConstraintView, - QWidget* parent = nullptr, - const char* pixmapname = "FEM_ConstraintGear"); + explicit TaskFemConstraintGear( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent = nullptr, + const char* pixmapname = "FEM_ConstraintGear" + ); double getDiameter() const; double getForce() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp index 8f51965597..d0b1ebd05b 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp @@ -46,7 +46,8 @@ using namespace Gui; TaskFemConstraintHeatflux::TaskFemConstraintHeatflux( ViewProviderFemConstraintHeatflux* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintHeatflux") , ui(new Ui_TaskFemConstraintHeatflux) { @@ -56,38 +57,44 @@ TaskFemConstraintHeatflux::TaskFemConstraintHeatflux( // create a context menu for the listview of the references createActions(ui->lw_references); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintHeatflux::onReferenceDeleted); - connect(ui->cb_constr_type, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintHeatflux::onConstrTypeChanged); - connect(ui->qsb_heat_flux, - qOverload(&QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintHeatflux::onHeatFluxChanged); - connect(ui->qsb_ambienttemp_conv, - qOverload(&QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintHeatflux::onAmbientTempChanged); - connect(ui->qsb_film_coef, - qOverload(&QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintHeatflux::onFilmCoefChanged); - connect(ui->dsb_emissivity, - qOverload(&DoubleSpinBox::valueChanged), - this, - &TaskFemConstraintHeatflux::onEmissivityChanged); - connect(ui->qsb_ambienttemp_rad, - qOverload(&QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintHeatflux::onAmbientTempChanged); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintHeatflux::setSelection); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintHeatflux::onReferenceDeleted); + connect( + ui->cb_constr_type, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintHeatflux::onConstrTypeChanged + ); + connect( + ui->qsb_heat_flux, + qOverload(&QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintHeatflux::onHeatFluxChanged + ); + connect( + ui->qsb_ambienttemp_conv, + qOverload(&QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintHeatflux::onAmbientTempChanged + ); + connect( + ui->qsb_film_coef, + qOverload(&QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintHeatflux::onFilmCoefChanged + ); + connect( + ui->dsb_emissivity, + qOverload(&DoubleSpinBox::valueChanged), + this, + &TaskFemConstraintHeatflux::onEmissivityChanged + ); + connect( + ui->qsb_ambienttemp_rad, + qOverload(&QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintHeatflux::onAmbientTempChanged + ); + connect(ui->lw_references, &QListWidget::itemClicked, this, &TaskFemConstraintHeatflux::setSelection); this->groupLayout()->addWidget(proxy); @@ -145,8 +152,9 @@ TaskFemConstraintHeatflux::TaskFemConstraintHeatflux( ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } - ui->lbl_references->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Edge, Face"))); + ui->lbl_references->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Edge, Face")) + ); // Selection buttons buttonGroup->addButton(ui->btnAdd, static_cast(SelectionChangeModes::refAdd)); @@ -210,10 +218,12 @@ void TaskFemConstraintHeatflux::Conv() { Fem::ConstraintHeatflux* pcConstraint = ConstraintView->getObject(); std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ConstraintType = \"%s\"", - name.c_str(), - getConstraintType().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ConstraintType = \"%s\"", + name.c_str(), + getConstraintType().c_str() + ); ui->qsb_ambienttemp_conv->setValue(pcConstraint->AmbientTemp.getQuantityValue()); ui->qsb_film_coef->setValue(pcConstraint->FilmCoef.getQuantityValue()); ui->sw_heatflux->setCurrentIndex(1); @@ -223,10 +233,12 @@ void TaskFemConstraintHeatflux::Rad() { Fem::ConstraintHeatflux* pcConstraint = ConstraintView->getObject(); std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ConstraintType = \"%s\"", - name.c_str(), - getConstraintType().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ConstraintType = \"%s\"", + name.c_str(), + getConstraintType().c_str() + ); ui->qsb_ambienttemp_rad->setValue(pcConstraint->AmbientTemp.getQuantityValue()); ui->dsb_emissivity->setValue(pcConstraint->Emissivity.getValue()); ui->sw_heatflux->setCurrentIndex(2); @@ -236,10 +248,12 @@ void TaskFemConstraintHeatflux::Flux() { Fem::ConstraintHeatflux* pcConstraint = ConstraintView->getObject(); std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ConstraintType = \"%s\"", - name.c_str(), - getConstraintType().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ConstraintType = \"%s\"", + name.c_str(), + getConstraintType().c_str() + ); ui->qsb_heat_flux->setValue(pcConstraint->DFlux.getQuantityValue()); ui->sw_heatflux->setCurrentIndex(0); } @@ -262,8 +276,8 @@ void TaskFemConstraintHeatflux::onConstrTypeChanged(int item) void TaskFemConstraintHeatflux::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -280,9 +294,11 @@ void TaskFemConstraintHeatflux::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } @@ -293,7 +309,8 @@ void TaskFemConstraintHeatflux::addToSelection() QMessageBox::warning( this, tr("Selection error"), - tr("Selection must only consist of faces! (edges in 2D models)")); + tr("Selection must only consist of faces! (edges in 2D models)") + ); return; } } @@ -306,15 +323,18 @@ void TaskFemConstraintHeatflux::addToSelection() bool addMe = true; for (auto itr = std::ranges::find(SubElements.begin(), SubElements.end(), subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + itr = std::find( + ++itr, + SubElements.end(), + subName + )) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -333,8 +353,8 @@ void TaskFemConstraintHeatflux::addToSelection() void TaskFemConstraintHeatflux::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -358,7 +378,8 @@ void TaskFemConstraintHeatflux::removeFromSelection() QMessageBox::warning( this, tr("Selection error"), - tr("Selection must only consist of faces! (edges in 2D models)")); + tr("Selection must only consist of faces! (edges in 2D models)") + ); return; } } @@ -368,16 +389,17 @@ void TaskFemConstraintHeatflux::removeFromSelection() // SubElements } for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -486,7 +508,8 @@ void TaskFemConstraintHeatflux::clearButtons(const SelectionChangeModes notThis) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintHeatflux::TaskDlgFemConstraintHeatflux( - ViewProviderFemConstraintHeatflux* ConstraintView) + ViewProviderFemConstraintHeatflux* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -500,26 +523,34 @@ TaskDlgFemConstraintHeatflux::TaskDlgFemConstraintHeatflux( bool TaskDlgFemConstraintHeatflux::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintHeatflux* parameterHeatflux = - static_cast(parameter); + const TaskFemConstraintHeatflux* parameterHeatflux + = static_cast(parameter); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.AmbientTemp = \"%s\"", - name.c_str(), - parameterHeatflux->getAmbientTemp().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.FilmCoef = \"%s\"", - name.c_str(), - parameterHeatflux->getFilmCoef().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Emissivity = %f", - name.c_str(), - parameterHeatflux->getEmissivity()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.DFlux = \"%s\"", - name.c_str(), - parameterHeatflux->getDFlux().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.AmbientTemp = \"%s\"", + name.c_str(), + parameterHeatflux->getAmbientTemp().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.FilmCoef = \"%s\"", + name.c_str(), + parameterHeatflux->getFilmCoef().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Emissivity = %f", + name.c_str(), + parameterHeatflux->getEmissivity() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.DFlux = \"%s\"", + name.c_str(), + parameterHeatflux->getDFlux().c_str() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h index 5491b357af..f8cfe1b6dc 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h @@ -42,8 +42,10 @@ class TaskFemConstraintHeatflux: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintHeatflux(ViewProviderFemConstraintHeatflux* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintHeatflux( + ViewProviderFemConstraintHeatflux* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintHeatflux() override; std::string getAmbientTemp() const; /*double getFaceTemp(void) const;*/ diff --git a/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.cpp b/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.cpp index 94f771a180..b14b888a82 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.cpp @@ -42,7 +42,8 @@ using namespace Gui; TaskFemConstraintInitialTemperature::TaskFemConstraintInitialTemperature( ViewProviderFemConstraintInitialTemperature* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraint(ConstraintView, parent, "FEM_ConstraintInitialTemperature") , ui(new Ui_TaskFemConstraintInitialTemperature) { @@ -53,8 +54,8 @@ TaskFemConstraintInitialTemperature::TaskFemConstraintInitialTemperature( this->groupLayout()->addWidget(proxy); // Get the feature data - Fem::ConstraintInitialTemperature* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintInitialTemperature* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); @@ -80,7 +81,8 @@ void TaskFemConstraintInitialTemperature::changeEvent(QEvent*) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintInitialTemperature::TaskDlgFemConstraintInitialTemperature( - ViewProviderFemConstraintInitialTemperature* ConstraintView) + ViewProviderFemConstraintInitialTemperature* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -94,14 +96,16 @@ TaskDlgFemConstraintInitialTemperature::TaskDlgFemConstraintInitialTemperature( bool TaskDlgFemConstraintInitialTemperature::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintInitialTemperature* parameterTemperature = - static_cast(parameter); + const TaskFemConstraintInitialTemperature* parameterTemperature + = static_cast(parameter); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.initialTemperature = \"%s\"", - name.c_str(), - parameterTemperature->get_temperature().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.initialTemperature = \"%s\"", + name.c_str(), + parameterTemperature->get_temperature().c_str() + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); if (!ConstraintView->getObject()->isValid()) { throw Base::RuntimeError(ConstraintView->getObject()->getStatusString()); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h b/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h index e71f5ea8e2..a479150eb1 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h @@ -44,7 +44,8 @@ class TaskFemConstraintInitialTemperature: public TaskFemConstraint public: explicit TaskFemConstraintInitialTemperature( ViewProviderFemConstraintInitialTemperature* ConstraintView, - QWidget* parent = nullptr); + QWidget* parent = nullptr + ); ~TaskFemConstraintInitialTemperature() override; std::string get_temperature() const; @@ -61,7 +62,8 @@ class TaskDlgFemConstraintInitialTemperature: public TaskDlgFemConstraint public: explicit TaskDlgFemConstraintInitialTemperature( - ViewProviderFemConstraintInitialTemperature* ConstraintView); + ViewProviderFemConstraintInitialTemperature* ConstraintView + ); bool accept() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.cpp b/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.cpp index 0ce4249467..1703e639e5 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.cpp @@ -29,9 +29,11 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintOnBoundary */ -TaskFemConstraintOnBoundary::TaskFemConstraintOnBoundary(ViewProviderFemConstraint* ConstraintView, - QWidget* parent, - const char* pixmapname) +TaskFemConstraintOnBoundary::TaskFemConstraintOnBoundary( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent, + const char* pixmapname +) : TaskFemConstraint(ConstraintView, parent, pixmapname) , selChangeMode(SelectionChangeModes::none) { @@ -40,10 +42,12 @@ TaskFemConstraintOnBoundary::TaskFemConstraintOnBoundary(ViewProviderFemConstrai buttonGroup = new ButtonGroup(this); buttonGroup->setExclusive(true); - connect(buttonGroup, - qOverload(&QButtonGroup::buttonToggled), - this, - &TaskFemConstraintOnBoundary::onButtonToggled); + connect( + buttonGroup, + qOverload(&QButtonGroup::buttonToggled), + this, + &TaskFemConstraintOnBoundary::onButtonToggled + ); } TaskFemConstraintOnBoundary::~TaskFemConstraintOnBoundary() diff --git a/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h b/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h index dd4136ba5c..d690873032 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h @@ -48,9 +48,11 @@ class TaskFemConstraintOnBoundary: public TaskFemConstraint Q_OBJECT public: - explicit TaskFemConstraintOnBoundary(ViewProviderFemConstraint* ConstraintView, - QWidget* parent = nullptr, - const char* pixmapname = ""); + explicit TaskFemConstraintOnBoundary( + ViewProviderFemConstraint* ConstraintView, + QWidget* parent = nullptr, + const char* pixmapname = "" + ); ~TaskFemConstraintOnBoundary() override; protected Q_SLOTS: diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp index 30ac2c209f..96d89c2df7 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp @@ -49,7 +49,8 @@ using namespace Gui; TaskFemConstraintPlaneRotation::TaskFemConstraintPlaneRotation( ViewProviderFemConstraintPlaneRotation* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraint(ConstraintView, parent, "FEM_ConstraintPlaneRotation") , ui(new Ui_TaskFemConstraintPlaneRotation) { // Note change "planerotation" in line above to new constraint name @@ -59,25 +60,26 @@ TaskFemConstraintPlaneRotation::TaskFemConstraintPlaneRotation( // create a context menu for the listview of the references createActions(ui->lw_references); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintPlaneRotation::onReferenceDeleted); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintPlaneRotation::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintPlaneRotation::setSelection); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintPlaneRotation::onReferenceDeleted); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintPlaneRotation::setSelection + ); + connect( + ui->lw_references, + &QListWidget::itemClicked, + this, + &TaskFemConstraintPlaneRotation::setSelection + ); this->groupLayout()->addWidget(proxy); /* Note: */ // Get the feature data - Fem::ConstraintPlaneRotation* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintPlaneRotation* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); @@ -92,18 +94,18 @@ TaskFemConstraintPlaneRotation::TaskFemConstraintPlaneRotation( ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } - ui->lbl_info->setText(tr("Select single geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Face"))); + ui->lbl_info->setText( + tr("Select single geometry of type: ") + QString::fromUtf8("%1").arg(tr("Face")) + ); // Selection buttons - connect(ui->btnAdd, - &QToolButton::clicked, - this, - &TaskFemConstraintPlaneRotation::addToSelection); - connect(ui->btnRemove, - &QToolButton::clicked, - this, - &TaskFemConstraintPlaneRotation::removeFromSelection); + connect(ui->btnAdd, &QToolButton::clicked, this, &TaskFemConstraintPlaneRotation::addToSelection); + connect( + ui->btnRemove, + &QToolButton::clicked, + this, + &TaskFemConstraintPlaneRotation::removeFromSelection + ); updateUI(); } @@ -126,36 +128,36 @@ void TaskFemConstraintPlaneRotation::addToSelection() QMessageBox::warning( this, tr("Selection error"), - tr("Only one face can be selected for a plane multi-point constraint!")); + tr("Only one face can be selected for a plane multi-point constraint!") + ); Gui::Selection().clearSelection(); return; } else { - std::vector selection = - Gui::Selection() - .getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintPlaneRotation* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintPlaneRotation* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); for (auto& it : selection) { // for every selected object if (!it.isObjectTypeOf(Part::Feature::getClassTypeId())) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Selected object is not a part!")); + QMessageBox::warning(this, tr("Selection error"), tr("Selected object is not a part!")); return; } App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } @@ -164,32 +166,32 @@ void TaskFemConstraintPlaneRotation::addToSelection() for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; if ((subName.substr(0, 4) != "Face")) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only faces can be picked")); + QMessageBox::warning(this, tr("Selection error"), tr("Only faces can be picked")); return; } Part::Feature* feat = static_cast(obj); TopoDS_Shape ref = feat->Shape.getShape().getSubShape(subName.c_str()); if ((subName.substr(0, 4) == "Face")) { if (!Fem::Tools::isPlanar(TopoDS::Face(ref))) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only planar faces can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only planar faces can be picked") + ); return; } } - for (auto itr = std::ranges::find(SubElements, subName); - itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection - // that matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection + // that matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old - // list then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old + // list then it was added before so don't add addMe = false; } } @@ -205,7 +207,8 @@ void TaskFemConstraintPlaneRotation::addToSelection() QMessageBox::warning( this, tr("Selection error"), - tr("Only one face can be selected for a plane multi-point constraint!")); + tr("Only one face can be selected for a plane multi-point constraint!") + ); Gui::Selection().clearSelection(); return; } @@ -218,14 +221,14 @@ void TaskFemConstraintPlaneRotation::addToSelection() void TaskFemConstraintPlaneRotation::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintPlaneRotation* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintPlaneRotation* pcConstraint + = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); std::vector itemsToDel; @@ -238,16 +241,17 @@ void TaskFemConstraintPlaneRotation::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -294,7 +298,8 @@ void TaskFemConstraintPlaneRotation::changeEvent(QEvent*) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintPlaneRotation::TaskDlgFemConstraintPlaneRotation( - ViewProviderFemConstraintPlaneRotation* ConstraintView) + ViewProviderFemConstraintPlaneRotation* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h index 6c476fd614..c5c5084856 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h @@ -42,8 +42,10 @@ class TaskFemConstraintPlaneRotation: public TaskFemConstraint Q_OBJECT public: - explicit TaskFemConstraintPlaneRotation(ViewProviderFemConstraintPlaneRotation* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintPlaneRotation( + ViewProviderFemConstraintPlaneRotation* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintPlaneRotation() override; const std::string getReferences() const override; @@ -65,8 +67,7 @@ class TaskDlgFemConstraintPlaneRotation: public TaskDlgFemConstraint Q_OBJECT public: - explicit TaskDlgFemConstraintPlaneRotation( - ViewProviderFemConstraintPlaneRotation* ConstraintView); + explicit TaskDlgFemConstraintPlaneRotation(ViewProviderFemConstraintPlaneRotation* ConstraintView); bool accept() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp index f9faf6e4b4..5d0a7d2a58 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp @@ -44,7 +44,8 @@ using namespace Gui; TaskFemConstraintPressure::TaskFemConstraintPressure( ViewProviderFemConstraintPressure* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintPressure") , ui(new Ui_TaskFemConstraintPressure) { // Note change "pressure" in line above to new constraint name @@ -70,8 +71,9 @@ TaskFemConstraintPressure::TaskFemConstraintPressure( bool reversed = pcConstraint->Reversed.getValue(); ui->checkBoxReverse->setChecked(reversed); - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Edge, Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Edge, Face")) + ); ui->lw_references->clear(); for (std::size_t i = 0; i < Objects.size(); i++) { @@ -83,23 +85,16 @@ TaskFemConstraintPressure::TaskFemConstraintPressure( // create a context menu for the listview of the references createActions(ui->lw_references); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintPressure::onReferenceDeleted); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintPressure::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintPressure::setSelection); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintPressure::onReferenceDeleted); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintPressure::setSelection + ); + connect(ui->lw_references, &QListWidget::itemClicked, this, &TaskFemConstraintPressure::setSelection); - connect(ui->checkBoxReverse, - &QCheckBox::toggled, - this, - &TaskFemConstraintPressure::onCheckReverse); + connect(ui->checkBoxReverse, &QCheckBox::toggled, this, &TaskFemConstraintPressure::onCheckReverse); // Selection buttons buttonGroup->addButton(ui->btnAdd, static_cast(SelectionChangeModes::refAdd)); @@ -127,8 +122,8 @@ void TaskFemConstraintPressure::onCheckReverse(const bool pressed) void TaskFemConstraintPressure::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -145,9 +140,11 @@ void TaskFemConstraintPressure::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } @@ -155,21 +152,24 @@ void TaskFemConstraintPressure::addToSelection() for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; if ((subName.substr(0, 4) != "Face") && (subName.substr(0, 4) != "Edge")) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only faces (edges in 2D models) can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only faces (edges in 2D models) can be picked") + ); return; } - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -188,8 +188,8 @@ void TaskFemConstraintPressure::addToSelection() void TaskFemConstraintPressure::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -207,16 +207,17 @@ void TaskFemConstraintPressure::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -283,7 +284,8 @@ void TaskFemConstraintPressure::clearButtons(const SelectionChangeModes notThis) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintPressure::TaskDlgFemConstraintPressure( - ViewProviderFemConstraintPressure* ConstraintView) + ViewProviderFemConstraintPressure* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -298,18 +300,22 @@ bool TaskDlgFemConstraintPressure::accept() { /* Note: */ std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintPressure* parameterPressure = - static_cast(parameter); + const TaskFemConstraintPressure* parameterPressure + = static_cast(parameter); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Pressure = \"%s\"", - name.c_str(), - parameterPressure->getPressure().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Reversed = %s", - name.c_str(), - parameterPressure->getReverse() ? "True" : "False"); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Pressure = \"%s\"", + name.c_str(), + parameterPressure->getPressure().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Reversed = %s", + name.c_str(), + parameterPressure->getReverse() ? "True" : "False" + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPressure.h b/src/Mod/Fem/Gui/TaskFemConstraintPressure.h index b68e593c78..ceb98e170e 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPressure.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintPressure.h @@ -42,8 +42,10 @@ class TaskFemConstraintPressure: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintPressure(ViewProviderFemConstraintPressure* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintPressure( + ViewProviderFemConstraintPressure* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintPressure() override; const std::string getReferences() const override; std::string getPressure() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp index 81fc27e5d9..dab230fb97 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp @@ -38,26 +38,31 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintPulley */ -TaskFemConstraintPulley::TaskFemConstraintPulley(ViewProviderFemConstraintPulley* ConstraintView, - QWidget* parent) +TaskFemConstraintPulley::TaskFemConstraintPulley( + ViewProviderFemConstraintPulley* ConstraintView, + QWidget* parent +) : TaskFemConstraintGear(ConstraintView, parent, "FEM_ConstraintPulley") { - connect(ui->spinOtherDiameter, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintPulley::onOtherDiameterChanged); - connect(ui->spinCenterDistance, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintPulley::onCenterDistanceChanged); - connect(ui->checkIsDriven, - &QCheckBox::toggled, - this, - &TaskFemConstraintPulley::onCheckIsDriven); - connect(ui->spinTensionForce, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskFemConstraintPulley::onTensionForceChanged); + connect( + ui->spinOtherDiameter, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintPulley::onOtherDiameterChanged + ); + connect( + ui->spinCenterDistance, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintPulley::onCenterDistanceChanged + ); + connect(ui->checkIsDriven, &QCheckBox::toggled, this, &TaskFemConstraintPulley::onCheckIsDriven); + connect( + ui->spinTensionForce, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskFemConstraintPulley::onTensionForceChanged + ); // Temporarily prevent unnecessary feature recomputes ui->spinOtherDiameter->blockSignals(true); @@ -175,8 +180,7 @@ void TaskFemConstraintPulley::changeEvent(QEvent* e) // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgFemConstraintPulley::TaskDlgFemConstraintPulley( - ViewProviderFemConstraintPulley* ConstraintView) +TaskDlgFemConstraintPulley::TaskDlgFemConstraintPulley(ViewProviderFemConstraintPulley* ConstraintView) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -190,27 +194,36 @@ TaskDlgFemConstraintPulley::TaskDlgFemConstraintPulley( bool TaskDlgFemConstraintPulley::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintPulley* parameterPulley = - static_cast(parameter); + const TaskFemConstraintPulley* parameterPulley = static_cast( + parameter + ); try { // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "FEM pulley constraint changed")); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.OtherDiameter = %f", - name.c_str(), - parameterPulley->getOtherDiameter()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.CenterDistance = %f", - name.c_str(), - parameterPulley->getCenterDistance()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.IsDriven = %s", - name.c_str(), - parameterPulley->getIsDriven() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TensionForce = %f", - name.c_str(), - parameterPulley->getTensionForce()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.OtherDiameter = %f", + name.c_str(), + parameterPulley->getOtherDiameter() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.CenterDistance = %f", + name.c_str(), + parameterPulley->getCenterDistance() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.IsDriven = %s", + name.c_str(), + parameterPulley->getIsDriven() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TensionForce = %f", + name.c_str(), + parameterPulley->getTensionForce() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPulley.h b/src/Mod/Fem/Gui/TaskFemConstraintPulley.h index 4dfde5d8ab..c9ce4fbdb2 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPulley.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintPulley.h @@ -35,8 +35,10 @@ class TaskFemConstraintPulley: public TaskFemConstraintGear Q_OBJECT public: - explicit TaskFemConstraintPulley(ViewProviderFemConstraintPulley* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintPulley( + ViewProviderFemConstraintPulley* ConstraintView, + QWidget* parent = nullptr + ); double getOtherDiameter() const; double getCenterDistance() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.cpp b/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.cpp index 0550b5ae3b..495c5d2ed7 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.cpp @@ -44,7 +44,8 @@ using namespace Gui; TaskFemConstraintRigidBody::TaskFemConstraintRigidBody( ViewProviderFemConstraintRigidBody* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintRigidBody") { // Note change "RigidBody" in line above to new constraint name constexpr float floatMax = std::numeric_limits::max(); @@ -55,55 +56,74 @@ TaskFemConstraintRigidBody::TaskFemConstraintRigidBody( // create a context menu for the listview of the references createActions(ui->lw_references); - deleteAction->connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintRigidBody::onReferenceDeleted); + deleteAction->connect( + deleteAction, + &QAction::triggered, + this, + &TaskFemConstraintRigidBody::onReferenceDeleted + ); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintRigidBody::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintRigidBody::setSelection); - connect(ui->cb_x_trans_mode, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintRigidBody::onTransModeXChanged); - connect(ui->cb_y_trans_mode, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintRigidBody::onTransModeYChanged); - connect(ui->cb_z_trans_mode, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintRigidBody::onTransModeZChanged); - connect(ui->cb_x_rot_mode, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintRigidBody::onRotModeXChanged); - connect(ui->cb_y_rot_mode, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintRigidBody::onRotModeYChanged); - connect(ui->cb_z_rot_mode, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintRigidBody::onRotModeZChanged); - connect(ui->qsb_ref_node_x, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintRigidBody::onRefNodeXChanged); - connect(ui->qsb_ref_node_y, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintRigidBody::onRefNodeYChanged); - connect(ui->qsb_ref_node_z, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintRigidBody::onRefNodeZChanged); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintRigidBody::setSelection + ); + connect(ui->lw_references, &QListWidget::itemClicked, this, &TaskFemConstraintRigidBody::setSelection); + connect( + ui->cb_x_trans_mode, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintRigidBody::onTransModeXChanged + ); + connect( + ui->cb_y_trans_mode, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintRigidBody::onTransModeYChanged + ); + connect( + ui->cb_z_trans_mode, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintRigidBody::onTransModeZChanged + ); + connect( + ui->cb_x_rot_mode, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintRigidBody::onRotModeXChanged + ); + connect( + ui->cb_y_rot_mode, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintRigidBody::onRotModeYChanged + ); + connect( + ui->cb_z_rot_mode, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintRigidBody::onRotModeZChanged + ); + connect( + ui->qsb_ref_node_x, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintRigidBody::onRefNodeXChanged + ); + connect( + ui->qsb_ref_node_y, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintRigidBody::onRefNodeYChanged + ); + connect( + ui->qsb_ref_node_z, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintRigidBody::onRefNodeZChanged + ); this->groupLayout()->addWidget(proxy); @@ -132,11 +152,14 @@ TaskFemConstraintRigidBody::TaskFemConstraintRigidBody( ui->qsb_ref_node_y->setValue(refNode.y); ui->qsb_ref_node_z->setValue(refNode.z); ui->qsb_ref_node_x->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("ReferenceNode.x"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("ReferenceNode.x")) + ); ui->qsb_ref_node_y->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("ReferenceNode.y"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("ReferenceNode.y")) + ); ui->qsb_ref_node_z->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("ReferenceNode.z"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("ReferenceNode.z")) + ); ui->qsb_ref_node_x->setMinimum(-floatMax); ui->qsb_ref_node_x->setMaximum(floatMax); ui->qsb_ref_node_y->setMinimum(-floatMax); @@ -162,13 +185,15 @@ TaskFemConstraintRigidBody::TaskFemConstraintRigidBody( ui->spb_rot_axis_z->setValue(rotDir.z); ui->qsb_rot_angle->setValue(rotAngle.getValueAs(Base::Quantity::Degree)); ui->spb_rot_axis_x->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.x"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.x")) + ); ui->spb_rot_axis_y->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.y"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.y")) + ); ui->spb_rot_axis_z->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.z"))); - ui->qsb_rot_angle->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Angle"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.z")) + ); + ui->qsb_rot_angle->bind(App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Angle"))); ui->spb_rot_axis_x->setMinimum(-floatMax); ui->spb_rot_axis_x->setMaximum(floatMax); ui->spb_rot_axis_y->setMinimum(-floatMax); @@ -248,8 +273,9 @@ TaskFemConstraintRigidBody::TaskFemConstraintRigidBody( buttonGroup->addButton(ui->btnAdd, (int)SelectionChangeModes::refAdd); buttonGroup->addButton(ui->btnRemove, (int)SelectionChangeModes::refRemove); - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face")) + ); updateUI(); } @@ -270,8 +296,8 @@ void TaskFemConstraintRigidBody::updateUI() void TaskFemConstraintRigidBody::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -288,9 +314,11 @@ void TaskFemConstraintRigidBody::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } @@ -298,17 +326,17 @@ void TaskFemConstraintRigidBody::addToSelection() for (size_t subIt = 0; subIt < (subNames.size()); ++subIt) { // for every selected sub element bool addMe = true; - for (auto itr = std::ranges::find(SubElements, subNames[subIt]); - itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subNames[subIt])) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subNames[subIt]); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subNames[subIt])) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -326,8 +354,10 @@ void TaskFemConstraintRigidBody::addToSelection() } for (size_t iStr = 0; iStr < (SubElements.size()); ++iStr) { if (SubElements[iStr].find(searchStr) == std::string::npos) { - QString msg = tr("Only one type of selection (vertex, face or edge) per " - "constraint allowed!"); + QString msg = tr( + "Only one type of selection (vertex, face or edge) per " + "constraint allowed!" + ); QMessageBox::warning(this, tr("Selection error"), msg); addMe = false; break; @@ -348,8 +378,8 @@ void TaskFemConstraintRigidBody::addToSelection() void TaskFemConstraintRigidBody::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -369,17 +399,17 @@ void TaskFemConstraintRigidBody::removeFromSelection() for (size_t subIt = 0; subIt < (subNames.size()); ++subIt) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subNames[subIt]); - itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subNames[subIt])) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subNames[subIt]); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subNames[subIt])) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -642,7 +672,8 @@ void TaskFemConstraintRigidBody::clearButtons(const SelectionChangeModes notThis //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintRigidBody::TaskDlgFemConstraintRigidBody( - ViewProviderFemConstraintRigidBody* ConstraintView) + ViewProviderFemConstraintRigidBody* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -656,24 +687,29 @@ TaskDlgFemConstraintRigidBody::TaskDlgFemConstraintRigidBody( bool TaskDlgFemConstraintRigidBody::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintRigidBody* parameters = - static_cast(parameter); + const TaskFemConstraintRigidBody* parameters = static_cast( + parameter + ); try { Base::Vector3d ref = parameters->getReferenceNode(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ReferenceNode = App.Vector(%f, %f, %f)", - name.c_str(), - ref.x, - ref.y, - ref.z); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ReferenceNode = App.Vector(%f, %f, %f)", + name.c_str(), + ref.x, + ref.y, + ref.z + ); Base::Vector3d disp = parameters->getDisplacement(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Displacement = App.Vector(%f, %f, %f)", - name.c_str(), - disp.x, - disp.y, - disp.z); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Displacement = App.Vector(%f, %f, %f)", + name.c_str(), + disp.x, + disp.y, + disp.z + ); Base::Rotation rot = parameters->getRotation(); Base::Vector3d axis; @@ -686,63 +722,88 @@ bool TaskDlgFemConstraintRigidBody::accept() axis.x, axis.y, axis.z, - angle); + angle + ); auto force = parameters->getForce(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ForceX = \"%s\"", - name.c_str(), - force[0].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ForceY = \"%s\"", - name.c_str(), - force[1].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ForceZ = \"%s\"", - name.c_str(), - force[2].c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ForceX = \"%s\"", + name.c_str(), + force[0].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ForceY = \"%s\"", + name.c_str(), + force[1].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ForceZ = \"%s\"", + name.c_str(), + force[2].c_str() + ); auto moment = parameters->getMoment(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.MomentX = \"%s\"", - name.c_str(), - moment[0].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.MomentY = \"%s\"", - name.c_str(), - moment[1].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.MomentZ = \"%s\"", - name.c_str(), - moment[2].c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.MomentX = \"%s\"", + name.c_str(), + moment[0].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.MomentY = \"%s\"", + name.c_str(), + moment[1].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.MomentZ = \"%s\"", + name.c_str(), + moment[2].c_str() + ); auto transModes = parameters->getTranslationalMode(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TranslationalModeX = \"%s\"", - name.c_str(), - transModes[0].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TranslationalModeY = \"%s\"", - name.c_str(), - transModes[1].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TranslationalModeZ = \"%s\"", - name.c_str(), - transModes[2].c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TranslationalModeX = \"%s\"", + name.c_str(), + transModes[0].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TranslationalModeY = \"%s\"", + name.c_str(), + transModes[1].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TranslationalModeZ = \"%s\"", + name.c_str(), + transModes[2].c_str() + ); auto rotModes = parameters->getRotationalMode(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.RotationalModeX = \"%s\"", - name.c_str(), - rotModes[0].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.RotationalModeY = \"%s\"", - name.c_str(), - rotModes[1].c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.RotationalModeZ = \"%s\"", - name.c_str(), - rotModes[2].c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.RotationalModeX = \"%s\"", + name.c_str(), + rotModes[0].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.RotationalModeY = \"%s\"", + name.c_str(), + rotModes[1].c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.RotationalModeZ = \"%s\"", + name.c_str(), + rotModes[2].c_str() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.h b/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.h index f178422cdd..f48677b9ac 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintRigidBody.h @@ -38,8 +38,10 @@ class TaskFemConstraintRigidBody: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintRigidBody(ViewProviderFemConstraintRigidBody* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintRigidBody( + ViewProviderFemConstraintRigidBody* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintRigidBody() override; const std::string getReferences() const override; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp b/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp index f4642600af..08345d6b94 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp @@ -42,8 +42,10 @@ using namespace Gui; /* TRANSLATOR FemGui::TaskFemConstraintSpring */ -TaskFemConstraintSpring::TaskFemConstraintSpring(ViewProviderFemConstraintSpring* ConstraintView, - QWidget* parent) +TaskFemConstraintSpring::TaskFemConstraintSpring( + ViewProviderFemConstraintSpring* ConstraintView, + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintSpring") , ui(new Ui_TaskFemConstraintSpring) { @@ -55,14 +57,13 @@ TaskFemConstraintSpring::TaskFemConstraintSpring(ViewProviderFemConstraintSpring createActions(ui->lw_references); connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintSpring::onReferenceDeleted); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintSpring::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintSpring::setSelection); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintSpring::setSelection + ); + connect(ui->lw_references, &QListWidget::itemClicked, this, &TaskFemConstraintSpring::setSelection); this->groupLayout()->addWidget(proxy); @@ -99,8 +100,9 @@ TaskFemConstraintSpring::TaskFemConstraintSpring(ViewProviderFemConstraintSpring ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Face")) + ); // Selection buttons buttonGroup->addButton(ui->btnAdd, (int)SelectionChangeModes::refAdd); @@ -125,8 +127,8 @@ void TaskFemConstraintSpring::updateUI() void TaskFemConstraintSpring::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -143,9 +145,11 @@ void TaskFemConstraintSpring::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } @@ -156,16 +160,17 @@ void TaskFemConstraintSpring::addToSelection() QMessageBox::warning(this, tr("Selection error"), tr("Only faces can be picked")); return; } - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -184,8 +189,8 @@ void TaskFemConstraintSpring::addToSelection() void TaskFemConstraintSpring::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -203,16 +208,17 @@ void TaskFemConstraintSpring::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -283,8 +289,7 @@ void TaskFemConstraintSpring::clearButtons(const SelectionChangeModes notThis) // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgFemConstraintSpring::TaskDlgFemConstraintSpring( - ViewProviderFemConstraintSpring* ConstraintView) +TaskDlgFemConstraintSpring::TaskDlgFemConstraintSpring(ViewProviderFemConstraintSpring* ConstraintView) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -299,24 +304,31 @@ bool TaskDlgFemConstraintSpring::accept() { /* Note: */ std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintSpring* parameterStiffness = - static_cast(parameter); + const TaskFemConstraintSpring* parameterStiffness = static_cast( + parameter + ); // const TaskFemConstraintSpring* parameterTan = static_cast(parameter); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.NormalStiffness = \"%s\"", - name.c_str(), - parameterStiffness->getNormalStiffness().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TangentialStiffness = \"%s\"", - name.c_str(), - parameterStiffness->getTangentialStiffness().c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ElmerStiffness = '%s'", - name.c_str(), - parameterStiffness->getElmerStiffness().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.NormalStiffness = \"%s\"", + name.c_str(), + parameterStiffness->getNormalStiffness().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TangentialStiffness = \"%s\"", + name.c_str(), + parameterStiffness->getTangentialStiffness().c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ElmerStiffness = '%s'", + name.c_str(), + parameterStiffness->getElmerStiffness().c_str() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintSpring.h b/src/Mod/Fem/Gui/TaskFemConstraintSpring.h index b6d5de7f8b..d9e399dc37 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintSpring.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintSpring.h @@ -40,8 +40,10 @@ class TaskFemConstraintSpring: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintSpring(ViewProviderFemConstraintSpring* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintSpring( + ViewProviderFemConstraintSpring* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintSpring() override; const std::string getReferences() const override; std::string getNormalStiffness() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp index 1a0eddab7d..e4d6c54ef1 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp @@ -48,7 +48,8 @@ using namespace Gui; TaskFemConstraintTemperature::TaskFemConstraintTemperature( ViewProviderFemConstraintTemperature* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraintOnBoundary(ConstraintView, parent, "FEM_ConstraintTemperature") , ui(new Ui_TaskFemConstraintTemperature) { @@ -59,8 +60,7 @@ TaskFemConstraintTemperature::TaskFemConstraintTemperature( this->groupLayout()->addWidget(proxy); // Get the feature data - Fem::ConstraintTemperature* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintTemperature* pcConstraint = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); @@ -97,36 +97,39 @@ TaskFemConstraintTemperature::TaskFemConstraintTemperature( ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } - ui->lbl_info->setText(tr("Select geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face"))); + ui->lbl_info->setText( + tr("Select geometry of type: ") + QString::fromUtf8("%1").arg(tr("Vertex, Edge, Face")) + ); // create a context menu for the listview of the references createActions(ui->lw_references); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintTemperature::onReferenceDeleted); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintTemperature::onReferenceDeleted); - connect(ui->lw_references, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintTemperature::setSelection); - connect(ui->lw_references, - &QListWidget::itemClicked, - this, - &TaskFemConstraintTemperature::setSelection); - connect(ui->cb_constr_type, - qOverload(&QComboBox::activated), - this, - &TaskFemConstraintTemperature::onConstrTypeChanged); - connect(ui->qsb_temperature, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintTemperature::onTempChanged); - connect(ui->qsb_cflux, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintTemperature::onCFluxChanged); + connect( + ui->lw_references, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintTemperature::setSelection + ); + connect(ui->lw_references, &QListWidget::itemClicked, this, &TaskFemConstraintTemperature::setSelection); + connect( + ui->cb_constr_type, + qOverload(&QComboBox::activated), + this, + &TaskFemConstraintTemperature::onConstrTypeChanged + ); + connect( + ui->qsb_temperature, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintTemperature::onTempChanged + ); + connect( + ui->qsb_cflux, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintTemperature::onCFluxChanged + ); // Selection buttons buttonGroup->addButton(ui->btnAdd, static_cast(SelectionChangeModes::refAdd)); @@ -149,19 +152,23 @@ void TaskFemConstraintTemperature::updateUI() void TaskFemConstraintTemperature::onTempChanged(double) { std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Temperature = \"%s\"", - name.c_str(), - get_temperature().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Temperature = \"%s\"", + name.c_str(), + get_temperature().c_str() + ); } void TaskFemConstraintTemperature::onCFluxChanged(double) { std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.CFlux = \"%s\"", - name.c_str(), - get_cflux().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.CFlux = \"%s\"", + name.c_str(), + get_cflux().c_str() + ); } void TaskFemConstraintTemperature::onConstrTypeChanged(int item) @@ -185,14 +192,13 @@ void TaskFemConstraintTemperature::onConstrTypeChanged(int item) void TaskFemConstraintTemperature::addToSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintTemperature* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintTemperature* pcConstraint = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); @@ -204,25 +210,28 @@ void TaskFemConstraintTemperature::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); for (const auto& subName : subNames) { // for every selected sub element bool addMe = true; - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } @@ -241,14 +250,13 @@ void TaskFemConstraintTemperature::addToSelection() void TaskFemConstraintTemperature::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } - Fem::ConstraintTemperature* pcConstraint = - ConstraintView->getObject(); + Fem::ConstraintTemperature* pcConstraint = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); std::vector itemsToDel; @@ -261,16 +269,17 @@ void TaskFemConstraintTemperature::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -349,7 +358,8 @@ void TaskFemConstraintTemperature::clearButtons(const SelectionChangeModes notTh //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintTemperature::TaskDlgFemConstraintTemperature( - ViewProviderFemConstraintTemperature* ConstraintView) + ViewProviderFemConstraintTemperature* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -363,27 +373,33 @@ TaskDlgFemConstraintTemperature::TaskDlgFemConstraintTemperature( bool TaskDlgFemConstraintTemperature::accept() { std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintTemperature* parameterTemperature = - static_cast(parameter); + const TaskFemConstraintTemperature* parameterTemperature + = static_cast(parameter); auto type = parameterTemperature->get_constraint_type(); try { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.ConstraintType = \"%s\"", - name.c_str(), - parameterTemperature->get_constraint_type().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.ConstraintType = \"%s\"", + name.c_str(), + parameterTemperature->get_constraint_type().c_str() + ); if (type == "Temperature") { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Temperature = \"%s\"", - name.c_str(), - parameterTemperature->get_temperature().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Temperature = \"%s\"", + name.c_str(), + parameterTemperature->get_temperature().c_str() + ); } else if (type == "CFlux") { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.CFlux = \"%s\"", - name.c_str(), - parameterTemperature->get_cflux().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.CFlux = \"%s\"", + name.c_str(), + parameterTemperature->get_cflux().c_str() + ); } } catch (const Base::Exception& e) { diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h index c73fd5f69d..06430cd576 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h @@ -45,8 +45,10 @@ class TaskFemConstraintTemperature: public TaskFemConstraintOnBoundary Q_OBJECT public: - explicit TaskFemConstraintTemperature(ViewProviderFemConstraintTemperature* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintTemperature( + ViewProviderFemConstraintTemperature* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintTemperature() override; const std::string getReferences() const override; std::string get_temperature() const; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp b/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp index 538285b9e0..c690d36b2b 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp @@ -49,7 +49,8 @@ using namespace Gui; TaskFemConstraintTransform::TaskFemConstraintTransform( ViewProviderFemConstraintTransform* ConstraintView, - QWidget* parent) + QWidget* parent +) : TaskFemConstraint(ConstraintView, parent, "FEM_ConstraintTransform") , ui(new Ui_TaskFemConstraintTransform) { @@ -59,50 +60,53 @@ TaskFemConstraintTransform::TaskFemConstraintTransform( // create a context menu for the listview of the references createActions(ui->lw_Rect); - connect(deleteAction, - &QAction::triggered, - this, - &TaskFemConstraintTransform::onReferenceDeleted); + connect(deleteAction, &QAction::triggered, this, &TaskFemConstraintTransform::onReferenceDeleted); // highlight seletcted list items in the model - connect(ui->lw_Rect, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintTransform::setSelection); - connect(ui->lw_Rect, - &QListWidget::itemClicked, - this, - &TaskFemConstraintTransform::setSelection); - connect(ui->lw_displobj_rect, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintTransform::setSelection); - connect(ui->lw_displobj_rect, - &QListWidget::itemClicked, - this, - &TaskFemConstraintTransform::setSelection); + connect(ui->lw_Rect, &QListWidget::currentItemChanged, this, &TaskFemConstraintTransform::setSelection); + connect(ui->lw_Rect, &QListWidget::itemClicked, this, &TaskFemConstraintTransform::setSelection); + connect( + ui->lw_displobj_rect, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintTransform::setSelection + ); + connect( + ui->lw_displobj_rect, + &QListWidget::itemClicked, + this, + &TaskFemConstraintTransform::setSelection + ); this->groupLayout()->addWidget(proxy); connect(ui->rb_rect, &QRadioButton::clicked, this, &TaskFemConstraintTransform::Rect); connect(ui->rb_cylin, &QRadioButton::clicked, this, &TaskFemConstraintTransform::Cyl); - connect(ui->spb_rot_axis_x, - qOverload(&DoubleSpinBox::valueChanged), - this, - &TaskFemConstraintTransform::xAxisChanged); - connect(ui->spb_rot_axis_y, - qOverload(&DoubleSpinBox::valueChanged), - this, - &TaskFemConstraintTransform::yAxisChanged); - connect(ui->spb_rot_axis_z, - qOverload(&DoubleSpinBox::valueChanged), - this, - &TaskFemConstraintTransform::zAxisChanged); - connect(ui->qsb_rot_angle, - qOverload(&QuantitySpinBox::valueChanged), - this, - &TaskFemConstraintTransform::angleChanged); + connect( + ui->spb_rot_axis_x, + qOverload(&DoubleSpinBox::valueChanged), + this, + &TaskFemConstraintTransform::xAxisChanged + ); + connect( + ui->spb_rot_axis_y, + qOverload(&DoubleSpinBox::valueChanged), + this, + &TaskFemConstraintTransform::yAxisChanged + ); + connect( + ui->spb_rot_axis_z, + qOverload(&DoubleSpinBox::valueChanged), + this, + &TaskFemConstraintTransform::zAxisChanged + ); + connect( + ui->qsb_rot_angle, + qOverload(&QuantitySpinBox::valueChanged), + this, + &TaskFemConstraintTransform::angleChanged + ); // Get the feature data Fem::ConstraintTransform* pcConstraint = ConstraintView->getObject(); @@ -121,13 +125,15 @@ TaskFemConstraintTransform::TaskFemConstraintTransform( ui->qsb_rot_angle->setValue(rotAngle.getValueAs(Base::Quantity::Degree)); ui->spb_rot_axis_x->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.x"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.x")) + ); ui->spb_rot_axis_y->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.y"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.y")) + ); ui->spb_rot_axis_z->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.z"))); - ui->qsb_rot_angle->bind( - App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Angle"))); + App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Axis.z")) + ); + ui->qsb_rot_angle->bind(App::ObjectIdentifier::parse(pcConstraint, std::string("Rotation.Angle"))); float max = std::numeric_limits::max(); ui->spb_rot_axis_x->setMinimum(-max); @@ -153,14 +159,18 @@ TaskFemConstraintTransform::TaskFemConstraintTransform( ui->lw_Rect->clear(); - ui->lbl_info_2->setText(tr("Select single geometry of type: ") - + QString::fromUtf8("%1").arg(tr("Face"))); + ui->lbl_info_2->setText( + tr("Select single geometry of type: ") + QString::fromUtf8("%1").arg(tr("Face")) + ); // Transformable surfaces - Gui::Command::doCommand(Gui::Command::Doc, - TaskFemConstraintTransform::getSurfaceReferences( - (ConstraintView->getObject())->getNameInDocument()) - .c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + TaskFemConstraintTransform::getSurfaceReferences( + (ConstraintView->getObject())->getNameInDocument() + ) + .c_str() + ); std::vector ObjDispl = pcConstraint->RefDispl.getValues(); std::vector SubElemDispl = pcConstraint->RefDispl.getSubValues(); @@ -191,18 +201,17 @@ TaskFemConstraintTransform::TaskFemConstraintTransform( } // Selection buttons connect(ui->btnAdd, &QToolButton::clicked, this, &TaskFemConstraintTransform::addToSelection); - connect(ui->btnRemove, - &QToolButton::clicked, - this, - &TaskFemConstraintTransform::removeFromSelection); + connect(ui->btnRemove, &QToolButton::clicked, this, &TaskFemConstraintTransform::removeFromSelection); updateUI(); if ((p == 0) && (!Objects.empty())) { - QMessageBox::warning(this, - tr("Analysis feature update error"), - tr("The transformable faces have changed. Add only the " - "transformable faces and remove non-transformable faces!")); + QMessageBox::warning( + this, + tr("Analysis feature update error"), + tr("The transformable faces have changed. Add only the " + "transformable faces and remove non-transformable faces!") + ); return; } } @@ -259,10 +268,12 @@ void TaskFemConstraintTransform::Rect() { ui->sw_transform->setCurrentIndex(0); std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TransformType = %s", - name.c_str(), - get_transform_type().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TransformType = %s", + name.c_str(), + get_transform_type().c_str() + ); Fem::ConstraintTransform* pcConstraint = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); if (!Objects.empty()) { @@ -275,10 +286,12 @@ void TaskFemConstraintTransform::Cyl() { ui->sw_transform->setCurrentIndex(1); std::string name = ConstraintView->getObject()->getNameInDocument(); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TransformType = %s", - name.c_str(), - get_transform_type().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TransformType = %s", + name.c_str(), + get_transform_type().c_str() + ); Fem::ConstraintTransform* pcConstraint = ConstraintView->getObject(); std::vector Objects = pcConstraint->References.getValues(); if (!Objects.empty()) { @@ -290,25 +303,29 @@ void TaskFemConstraintTransform::Cyl() void TaskFemConstraintTransform::addToSelection() { int rows = ui->lw_Rect->model()->rowCount(); - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } if (rows == 1) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one face for rectangular local coordinate system!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one face for rectangular local coordinate system!") + ); Gui::Selection().clearSelection(); return; } if ((rows == 0) && (selection.size() >= 2)) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one face for rectangular local coordinate system!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one face for rectangular local coordinate system!") + ); Gui::Selection().clearSelection(); return; } @@ -327,17 +344,21 @@ void TaskFemConstraintTransform::addToSelection() App::DocumentObject* obj = it.getObject(); if (obj->getDocument() != pcConstraint->getDocument()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("External object selection is not supported")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("External object selection is not supported") + ); return; } const std::vector& subNames = it.getSubNames(); if (subNames.size() != 1) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only one face for local coordinate system!")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only one face for local coordinate system!") + ); Gui::Selection().clearSelection(); return; } @@ -353,51 +374,59 @@ void TaskFemConstraintTransform::addToSelection() TopoDS_Shape ref = feat->Shape.getShape().getSubShape(subName.c_str()); BRepAdaptor_Surface surface(TopoDS::Face(ref)); if (surface.GetType() != GeomAbs_Cylinder) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only cylindrical faces can be picked")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only cylindrical faces can be picked") + ); return; } } } - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so don't add + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so don't add addMe = false; } } if (addMe) { - disconnect(ui->lw_Rect, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintTransform::setSelection); + disconnect( + ui->lw_Rect, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintTransform::setSelection + ); for (std::size_t i = 0; i < ObjDispl.size(); i++) { - if ((makeRefText(ObjDispl[i], SubElemDispl[i])) - == (makeRefText(obj, subName))) { + if ((makeRefText(ObjDispl[i], SubElemDispl[i])) == (makeRefText(obj, subName))) { Objects.push_back(obj); SubElements.push_back(subName); ui->lw_Rect->addItem(makeRefText(obj, subName)); - connect(ui->lw_Rect, - &QListWidget::currentItemChanged, - this, - &TaskFemConstraintTransform::setSelection); + connect( + ui->lw_Rect, + &QListWidget::currentItemChanged, + this, + &TaskFemConstraintTransform::setSelection + ); } } if (Objects.empty()) { - QMessageBox::warning(this, - tr("Selection error"), - tr("Only transformable faces can be selected! Apply a " - "displacement boundary " - "condition or a force load to a face first then apply " - "local coordinate system to " - "the face.")); + QMessageBox::warning( + this, + tr("Selection error"), + tr("Only transformable faces can be selected! Apply a " + "displacement boundary " + "condition or a force load to a face first then apply " + "local coordinate system to " + "the face.") + ); Gui::Selection().clearSelection(); return; } @@ -423,8 +452,8 @@ void TaskFemConstraintTransform::addToSelection() void TaskFemConstraintTransform::removeFromSelection() { - std::vector selection = - Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document + std::vector selection + = Gui::Selection().getSelectionEx(); // gets vector of selected objects of active document if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; @@ -442,16 +471,17 @@ void TaskFemConstraintTransform::removeFromSelection() const App::DocumentObject* obj = it.getObject(); for (const auto& subName : subNames) { // for every selected sub element - for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); - itr = std::find(++itr, - SubElements.end(), - subName)) { // for every sub element in selection that - // matches one in old list + for (auto itr = std::ranges::find(SubElements, subName); itr != SubElements.end(); itr + = std::find(++itr, + SubElements.end(), + subName)) { // for every sub element in selection that + // matches one in old list if (obj == Objects[std::distance( SubElements.begin(), - itr)]) { // if selected sub element's object equals the one in old list - // then it was added before so mark for deletion + itr + )]) { // if selected sub element's object equals the one in old list + // then it was added before so mark for deletion itemsToDel.push_back(std::distance(SubElements.begin(), itr)); } } @@ -561,7 +591,8 @@ void TaskFemConstraintTransform::changeEvent(QEvent*) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgFemConstraintTransform::TaskDlgFemConstraintTransform( - ViewProviderFemConstraintTransform* ConstraintView) + ViewProviderFemConstraintTransform* ConstraintView +) { this->ConstraintView = ConstraintView; assert(ConstraintView); @@ -576,8 +607,9 @@ bool TaskDlgFemConstraintTransform::accept() { /* Note: */ std::string name = ConstraintView->getObject()->getNameInDocument(); - const TaskFemConstraintTransform* parameters = - static_cast(parameter); + const TaskFemConstraintTransform* parameters = static_cast( + parameter + ); try { Base::Rotation rot = parameters->getRotation(); @@ -591,12 +623,15 @@ bool TaskDlgFemConstraintTransform::accept() axis.x, axis.y, axis.z, - angle); + angle + ); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.TransformType = %s", - name.c_str(), - parameters->get_transform_type().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.TransformType = %s", + name.c_str(), + parameters->get_transform_type().c_str() + ); } catch (const Base::Exception& e) { QMessageBox::warning(parameter, tr("Input error"), QString::fromLatin1(e.what())); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTransform.h b/src/Mod/Fem/Gui/TaskFemConstraintTransform.h index 8e05f30b47..125fc1080f 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTransform.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintTransform.h @@ -43,8 +43,10 @@ class TaskFemConstraintTransform: public TaskFemConstraint Q_OBJECT public: - explicit TaskFemConstraintTransform(ViewProviderFemConstraintTransform* ConstraintView, - QWidget* parent = nullptr); + explicit TaskFemConstraintTransform( + ViewProviderFemConstraintTransform* ConstraintView, + QWidget* parent = nullptr + ); ~TaskFemConstraintTransform() override; const std::string getReferences() const override; Base::Rotation getRotation() const; diff --git a/src/Mod/Fem/Gui/TaskObjectName.cpp b/src/Mod/Fem/Gui/TaskObjectName.cpp index c38c51715e..0576c1ad05 100644 --- a/src/Mod/Fem/Gui/TaskObjectName.cpp +++ b/src/Mod/Fem/Gui/TaskObjectName.cpp @@ -36,10 +36,7 @@ using namespace FemGui; using namespace Gui; TaskObjectName::TaskObjectName(App::DocumentObject* pcObject, QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap("FEM_CreateNodesSet"), - tr("Name of the object"), - true, - parent) + : TaskBox(Gui::BitmapFactory().pixmap("FEM_CreateNodesSet"), tr("Name of the object"), true, parent) , pcObject(pcObject) , ui(new Ui_TaskObjectName) { @@ -50,10 +47,7 @@ TaskObjectName::TaskObjectName(App::DocumentObject* pcObject, QWidget* parent) this->groupLayout()->addWidget(proxy); - QObject::connect(ui->lineEdit_ObjectName, - &QLineEdit::textChanged, - this, - &TaskObjectName::TextChanged); + QObject::connect(ui->lineEdit_ObjectName, &QLineEdit::textChanged, this, &TaskObjectName::TextChanged); if (strcmp(pcObject->Label.getValue(), "") != 0) { ui->lineEdit_ObjectName->setText(QString::fromUtf8(pcObject->Label.getValue())); diff --git a/src/Mod/Fem/Gui/TaskPostBoxes.cpp b/src/Mod/Fem/Gui/TaskPostBoxes.cpp index ad107c0d8d..cff0d9a760 100644 --- a/src/Mod/Fem/Gui/TaskPostBoxes.cpp +++ b/src/Mod/Fem/Gui/TaskPostBoxes.cpp @@ -148,7 +148,8 @@ ViewProviderPointMarker::ViewProviderPointMarker() "CIRCLE_FILLED", App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetInt("MarkerSize", 9)); + ->GetInt("MarkerSize", 9) + ); pMarker->numPoints = 0; pMarker->ref(); @@ -168,8 +169,10 @@ ViewProviderPointMarker::~ViewProviderPointMarker() // *************************************************************************** // DataAlongLine marker -DataAlongLineMarker::DataAlongLineMarker(Gui::View3DInventorViewer* iv, - Fem::FemPostDataAlongLineFilter* obj) +DataAlongLineMarker::DataAlongLineMarker( + Gui::View3DInventorViewer* iv, + Fem::FemPostDataAlongLineFilter* obj +) : PointMarker(iv, obj) {} @@ -179,28 +182,34 @@ void DataAlongLineMarker::customEvent(QEvent*) const SbVec3f& pt2 = getPoint(1); Q_EMIT PointsChanged(pt1[0], pt1[1], pt1[2], pt2[0], pt2[1], pt2[2]); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Point1 = App.Vector(%f, %f, %f)", - getObject()->getNameInDocument(), - pt1[0], - pt1[1], - pt1[2]); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.Point2 = App.Vector(%f, %f, %f)", - getObject()->getNameInDocument(), - pt2[0], - pt2[1], - pt2[2]); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Point1 = App.Vector(%f, %f, %f)", + getObject()->getNameInDocument(), + pt1[0], + pt1[1], + pt1[2] + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.Point2 = App.Vector(%f, %f, %f)", + getObject()->getNameInDocument(), + pt2[0], + pt2[1], + pt2[2] + ); Gui::Command::doCommand(Gui::Command::Doc, ObjectInvisible().c_str()); } // *************************************************************************** // main task dialog -TaskPostWidget::TaskPostWidget(Gui::ViewProviderDocumentObject* view, - const QPixmap& icon, - const QString& title, - QWidget* parent) +TaskPostWidget::TaskPostWidget( + Gui::ViewProviderDocumentObject* view, + const QPixmap& icon, + const QString& title, + QWidget* parent +) : QWidget(parent) , m_object(view->getObject()) , m_view(view) @@ -209,11 +218,14 @@ TaskPostWidget::TaskPostWidget(Gui::ViewProviderDocumentObject* view, setWindowIcon(icon); m_icon = icon; - m_connection = - m_object->signalChanged.connect(boost::bind(&TaskPostWidget::handlePropertyChange, - this, - boost::placeholders::_1, - boost::placeholders::_2)); + m_connection = m_object->signalChanged.connect( + boost::bind( + &TaskPostWidget::handlePropertyChange, + this, + boost::placeholders::_1, + boost::placeholders::_2 + ) + ); } TaskPostWidget::~TaskPostWidget() @@ -312,7 +324,8 @@ void TaskDlgPost::connectSlots() int indexSignal = 0; for (const auto dlg : Content) { indexSignal = dlg->metaObject()->indexOfSignal( - QMetaObject::normalizedSignature("emitAddedFunction()")); + QMetaObject::normalizedSignature("emitAddedFunction()") + ); if (indexSignal >= 0) { sender = dlg; break; @@ -322,12 +335,15 @@ void TaskDlgPost::connectSlots() if (sender) { for (const auto dlg : Content) { int indexSlot = dlg->metaObject()->indexOfSlot( - QMetaObject::normalizedSignature("slotAddedFunction()")); + QMetaObject::normalizedSignature("slotAddedFunction()") + ); if (indexSlot >= 0) { - connect(sender, - sender->metaObject()->method(indexSignal), - dlg, - dlg->metaObject()->method(indexSlot)); + connect( + sender, + sender->metaObject()->method(indexSignal), + dlg, + dlg->metaObject()->method(indexSlot) + ); } } } @@ -431,13 +447,12 @@ TaskPostDisplay::TaskPostDisplay(ViewProviderFemPostObject* view, QWidget* paren { // setup the ui ui->setupUi(this); - setWindowTitle( - tr("Result Display Options")); // set title here as setupUi overrides the constructor title + setWindowTitle(tr("Result Display Options")); // set title here as setupUi overrides the + // constructor title setupConnections(); // update all fields - updateEnumerationList(getTypedView()->DisplayMode, - ui->Representation); + updateEnumerationList(getTypedView()->DisplayMode, ui->Representation); updateEnumerationList(getTypedView()->Field, ui->Field); updateEnumerationList(getTypedView()->Component, ui->VectorMode); @@ -452,22 +467,20 @@ TaskPostDisplay::~TaskPostDisplay() = default; void TaskPostDisplay::setupConnections() { - connect(ui->Representation, - qOverload(&QComboBox::activated), - this, - &TaskPostDisplay::onRepresentationActivated); - connect(ui->Field, - qOverload(&QComboBox::activated), - this, - &TaskPostDisplay::onFieldActivated); - connect(ui->VectorMode, - qOverload(&QComboBox::activated), - this, - &TaskPostDisplay::onVectorModeActivated); - connect(ui->Transparency, - &QSlider::valueChanged, - this, - &TaskPostDisplay::onTransparencyValueChanged); + connect( + ui->Representation, + qOverload(&QComboBox::activated), + this, + &TaskPostDisplay::onRepresentationActivated + ); + connect(ui->Field, qOverload(&QComboBox::activated), this, &TaskPostDisplay::onFieldActivated); + connect( + ui->VectorMode, + qOverload(&QComboBox::activated), + this, + &TaskPostDisplay::onVectorModeActivated + ); + connect(ui->Transparency, &QSlider::valueChanged, this, &TaskPostDisplay::onTransparencyValueChanged); } void TaskPostDisplay::slotAddedFunction() @@ -507,10 +520,7 @@ void TaskPostDisplay::applyPythonCode() // *************************************************************************** // functions TaskPostFunction::TaskPostFunction(ViewProviderFemPostFunction* view, QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("fem-post-geo-plane"), - tr("Implicit function"), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("fem-post-geo-plane"), tr("Implicit function"), parent) { // we load the views widget FunctionWidget* w = getTypedView()->createControlWidget(); @@ -550,7 +560,8 @@ TaskPostFrames::TaskPostFrames(ViewProviderFemPostObject* view, QWidget* parent) for (unsigned long i = 0; i < steps.size(); i++) { QTableWidgetItem* idx = new QTableWidgetItem(QString::number(i)); QTableWidgetItem* value = new QTableWidgetItem( - QString::fromStdString(Base::Quantity(steps[i], unit).getUserString())); + QString::fromStdString(Base::Quantity(steps[i], unit).getUserString()) + ); int rowIdx = ui->FrameTable->rowCount(); ui->FrameTable->insertRow(rowIdx); @@ -564,10 +575,12 @@ TaskPostFrames::~TaskPostFrames() = default; void TaskPostFrames::setupConnections() { - connect(ui->FrameTable, - qOverload<>(&QTableWidget::itemSelectionChanged), - this, - &TaskPostFrames::onSelectionChanged); + connect( + ui->FrameTable, + qOverload<>(&QTableWidget::itemSelectionChanged), + this, + &TaskPostFrames::onSelectionChanged + ); } void TaskPostFrames::onSelectionChanged() @@ -618,15 +631,19 @@ TaskPostBranch::~TaskPostBranch() = default; void TaskPostBranch::setupConnections() { - connect(ui->ModeBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostBranch::onModeIndexChanged); + connect( + ui->ModeBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostBranch::onModeIndexChanged + ); - connect(ui->OutputBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostBranch::onOutputIndexChanged); + connect( + ui->OutputBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostBranch::onOutputIndexChanged + ); } void TaskPostBranch::onModeIndexChanged(int idx) @@ -648,12 +665,8 @@ void TaskPostBranch::applyPythonCode() // *************************************************************************** // data along line filter -TaskPostDataAlongLine::TaskPostDataAlongLine(ViewProviderFemPostDataAlongLine* view, - QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterDataAlongLine"), - QString(), - parent) +TaskPostDataAlongLine::TaskPostDataAlongLine(ViewProviderFemPostDataAlongLine* view, QWidget* parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterDataAlongLine"), QString(), parent) , ui(new Ui_TaskPostDataAlongLine) , marker(nullptr) { @@ -704,8 +717,7 @@ TaskPostDataAlongLine::TaskPostDataAlongLine(ViewProviderFemPostDataAlongLine* v setupConnectionsStep2(); // update all fields - updateEnumerationList(getTypedView()->DisplayMode, - ui->Representation); + updateEnumerationList(getTypedView()->DisplayMode, ui->Representation); updateEnumerationList(getTypedView()->Field, ui->Field); updateEnumerationList(getTypedView()->Component, ui->VectorMode); } @@ -714,92 +726,107 @@ TaskPostDataAlongLine::~TaskPostDataAlongLine() { if (marker && marker->getView()) { marker->getView()->setEditing(false); - marker->getView()->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - pointCallback, - marker); + marker->getView() + ->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), pointCallback, marker); } } void TaskPostDataAlongLine::setupConnectionsStep1() { - connect(ui->SelectPoints, - &QPushButton::clicked, - this, - &TaskPostDataAlongLine::onSelectPointsClicked); - connect(ui->CreatePlot, - &QPushButton::clicked, - this, - &TaskPostDataAlongLine::onCreatePlotClicked); - connect(ui->Representation, - qOverload(&QComboBox::activated), - this, - &TaskPostDataAlongLine::onRepresentationActivated); - connect(ui->Field, - qOverload(&QComboBox::activated), - this, - &TaskPostDataAlongLine::onFieldActivated); - connect(ui->VectorMode, - qOverload(&QComboBox::activated), - this, - &TaskPostDataAlongLine::onVectorModeActivated); + connect(ui->SelectPoints, &QPushButton::clicked, this, &TaskPostDataAlongLine::onSelectPointsClicked); + connect(ui->CreatePlot, &QPushButton::clicked, this, &TaskPostDataAlongLine::onCreatePlotClicked); + connect( + ui->Representation, + qOverload(&QComboBox::activated), + this, + &TaskPostDataAlongLine::onRepresentationActivated + ); + connect( + ui->Field, + qOverload(&QComboBox::activated), + this, + &TaskPostDataAlongLine::onFieldActivated + ); + connect( + ui->VectorMode, + qOverload(&QComboBox::activated), + this, + &TaskPostDataAlongLine::onVectorModeActivated + ); } void TaskPostDataAlongLine::setupConnectionsStep2() { - connect(ui->point1X, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAlongLine::point1Changed); - connect(ui->point1Y, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAlongLine::point1Changed); - connect(ui->point1Z, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAlongLine::point1Changed); - connect(ui->point2X, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAlongLine::point2Changed); - connect(ui->point2Y, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAlongLine::point2Changed); - connect(ui->point2Z, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAlongLine::point2Changed); - connect(ui->resolution, - qOverload(&QSpinBox::valueChanged), - this, - &TaskPostDataAlongLine::resolutionChanged); + connect( + ui->point1X, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAlongLine::point1Changed + ); + connect( + ui->point1Y, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAlongLine::point1Changed + ); + connect( + ui->point1Z, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAlongLine::point1Changed + ); + connect( + ui->point2X, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAlongLine::point2Changed + ); + connect( + ui->point2Y, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAlongLine::point2Changed + ); + connect( + ui->point2Z, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAlongLine::point2Changed + ); + connect( + ui->resolution, + qOverload(&QSpinBox::valueChanged), + this, + &TaskPostDataAlongLine::resolutionChanged + ); } void TaskPostDataAlongLine::applyPythonCode() {} -static const char* cursor_triangle[] = {"32 17 3 1", - " c None", - ". c #FFFFFF", - "+ c #FF0000", - " . ", - " . ", - " . ", - " . ", - " . ", - " ", - "..... ..... ", - " ", - " . ", - " . ", - " . ++ ", - " . + + ", - " . + ++ + ", - " + ++++ + ", - " + ++ ++ + ", - " + ++++++++ + ", - " ++ ++ ++ ++ "}; +static const char* cursor_triangle[] = { + "32 17 3 1", + " c None", + ". c #FFFFFF", + "+ c #FF0000", + " . ", + " . ", + " . ", + " . ", + " . ", + " ", + "..... ..... ", + " ", + " . ", + " . ", + " . ++ ", + " . + + ", + " . + ++ + ", + " + ++++ + ", + " + ++ ++ + ", + " + ++++++++ + ", + " ++ ++ ++ ++ " +}; void TaskPostDataAlongLine::onSelectPointsClicked() { @@ -822,13 +849,17 @@ void TaskPostDataAlongLine::onSelectPointsClicked() } if (!marker->connSelectPoint) { - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - TaskPostDataAlongLine::pointCallback, - marker); - marker->connSelectPoint = connect(marker, - &DataAlongLineMarker::PointsChanged, - this, - &TaskPostDataAlongLine::onChange); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + TaskPostDataAlongLine::pointCallback, + marker + ); + marker->connSelectPoint = connect( + marker, + &DataAlongLineMarker::PointsChanged, + this, + &TaskPostDataAlongLine::onChange + ); } } } @@ -854,12 +885,7 @@ void TaskPostDataAlongLine::onCreatePlotClicked() recompute(); } -void TaskPostDataAlongLine::onChange(double x1, - double y1, - double z1, - double x2, - double y2, - double z2) +void TaskPostDataAlongLine::onChange(double x1, double y1, double z1, double x2, double y2, double z2) { // call point1Changed only once ui->point1X->blockSignals(true); @@ -888,9 +914,11 @@ void TaskPostDataAlongLine::onChange(double x1, if (marker && marker->getView()) { // leave mode marker->getView()->setEditing(false); - marker->getView()->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - TaskPostDataAlongLine::pointCallback, - marker); + marker->getView()->removeEventCallback( + SoMouseButtonEvent::getClassTypeId(), + TaskPostDataAlongLine::pointCallback, + marker + ); disconnect(marker->connSelectPoint); } } @@ -898,16 +926,20 @@ void TaskPostDataAlongLine::onChange(double x1, void TaskPostDataAlongLine::point1Changed(double) { try { - SbVec3f vec(ui->point1X->value().getValue(), - ui->point1Y->value().getValue(), - ui->point1Z->value().getValue()); + SbVec3f vec( + ui->point1X->value().getValue(), + ui->point1Y->value().getValue(), + ui->point1Z->value().getValue() + ); std::string ObjName = getObject()->getNameInDocument(); - Gui::cmdAppDocumentArgs(getDocument(), - "%s.Point1 = App.Vector(%f, %f, %f)", - ObjName, - vec[0], - vec[1], - vec[2]); + Gui::cmdAppDocumentArgs( + getDocument(), + "%s.Point1 = App.Vector(%f, %f, %f)", + ObjName, + vec[0], + vec[1], + vec[2] + ); if (marker && marker->countPoints() > 0) { marker->setPoint(0, vec); @@ -929,16 +961,20 @@ void TaskPostDataAlongLine::point1Changed(double) void TaskPostDataAlongLine::point2Changed(double) { try { - SbVec3f vec(ui->point2X->value().getValue(), - ui->point2Y->value().getValue(), - ui->point2Z->value().getValue()); + SbVec3f vec( + ui->point2X->value().getValue(), + ui->point2Y->value().getValue(), + ui->point2Z->value().getValue() + ); std::string ObjName = getObject()->getNameInDocument(); - Gui::cmdAppDocumentArgs(getDocument(), - "%s.Point2 = App.Vector(%f, %f, %f)", - ObjName, - vec[0], - vec[1], - vec[2]); + Gui::cmdAppDocumentArgs( + getDocument(), + "%s.Point2 = App.Vector(%f, %f, %f)", + ObjName, + vec[0], + vec[1], + vec[2] + ); if (marker && marker->countPoints() > 1) { marker->setPoint(1, vec); @@ -995,13 +1031,14 @@ void TaskPostDataAlongLine::pointCallback(void* ud, SoEventCallback* n) QApplication::postEvent(pm, e); } } - else if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 - && mbe->getState() == SoButtonEvent::UP) { + else if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::UP) { n->setHandled(); view->setEditing(false); - view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - TaskPostDataAlongLine::pointCallback, - ud); + view->removeEventCallback( + SoMouseButtonEvent::getClassTypeId(), + TaskPostDataAlongLine::pointCallback, + ud + ); disconnect(pm->connSelectPoint); } } @@ -1070,10 +1107,7 @@ plt.show()\n"; // *************************************************************************** // data at point filter TaskPostDataAtPoint::TaskPostDataAtPoint(ViewProviderFemPostDataAtPoint* view, QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterDataAtPoint"), - QString(), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterDataAtPoint"), QString(), parent) , viewer(nullptr) , connSelectPoint(QMetaObject::Connection()) , ui(new Ui_TaskPostDataAtPoint) @@ -1111,18 +1145,24 @@ TaskPostDataAtPoint::TaskPostDataAtPoint(ViewProviderFemPostDataAtPoint* view, Q auto pointValue = getObject()->PointData[0]; showValue(pointValue, getObject()->Unit.getValue()); - connect(ui->centerX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAtPoint::centerChanged); - connect(ui->centerY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAtPoint::centerChanged); - connect(ui->centerZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskPostDataAtPoint::centerChanged); + connect( + ui->centerX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAtPoint::centerChanged + ); + connect( + ui->centerY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAtPoint::centerChanged + ); + connect( + ui->centerZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskPostDataAtPoint::centerChanged + ); // the point filter object needs to be recomputed // to fill all fields with data at the current point @@ -1143,14 +1183,8 @@ TaskPostDataAtPoint::~TaskPostDataAtPoint() void TaskPostDataAtPoint::setupConnections() { - connect(ui->SelectPoint, - &QPushButton::clicked, - this, - &TaskPostDataAtPoint::onSelectPointClicked); - connect(ui->Field, - qOverload(&QComboBox::activated), - this, - &TaskPostDataAtPoint::onFieldActivated); + connect(ui->SelectPoint, &QPushButton::clicked, this, &TaskPostDataAtPoint::onSelectPointClicked); + connect(ui->Field, qOverload(&QComboBox::activated), this, &TaskPostDataAtPoint::onFieldActivated); } void TaskPostDataAtPoint::applyPythonCode() @@ -1166,13 +1200,17 @@ void TaskPostDataAtPoint::onSelectPointClicked() viewer->setEditingCursor(QCursor(QPixmap(cursor_triangle), 7, 7)); if (!connSelectPoint) { - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - TaskPostDataAtPoint::pointCallback, - this); - connSelectPoint = connect(this, - &TaskPostDataAtPoint::PointsChanged, - this, - &TaskPostDataAtPoint::onChange); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + TaskPostDataAtPoint::pointCallback, + this + ); + connSelectPoint = connect( + this, + &TaskPostDataAtPoint::PointsChanged, + this, + &TaskPostDataAtPoint::onChange + ); } } getTypedView()->DisplayMode.setValue(1); @@ -1212,9 +1250,11 @@ void TaskPostDataAtPoint::onChange(double x, double y, double z) if (viewer) { // leave mode viewer->setEditing(false); - viewer->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - TaskPostDataAtPoint::pointCallback, - this); + viewer->removeEventCallback( + SoMouseButtonEvent::getClassTypeId(), + TaskPostDataAtPoint::pointCallback, + this + ); disconnect(connSelectPoint); } } @@ -1223,12 +1263,14 @@ void TaskPostDataAtPoint::centerChanged(double) { try { std::string ObjName = getObject()->getNameInDocument(); - Gui::cmdAppDocumentArgs(getDocument(), - "%s.Center = App.Vector(%f, %f, %f)", - ObjName, - ui->centerX->value().getValue(), - ui->centerY->value().getValue(), - ui->centerZ->value().getValue()); + Gui::cmdAppDocumentArgs( + getDocument(), + "%s.Center = App.Vector(%f, %f, %f)", + ObjName, + ui->centerX->value().getValue(), + ui->centerY->value().getValue(), + ui->centerZ->value().getValue() + ); // recompute the feature to fill all fields with data at this point getObject()->recomputeFeature(); @@ -1262,13 +1304,14 @@ void TaskPostDataAtPoint::pointCallback(void* ud, SoEventCallback* n) const SbVec3f& pt = point->getPoint(); Q_EMIT taskPost->PointsChanged(pt[0], pt[1], pt[2]); } - else if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 - && mbe->getState() == SoButtonEvent::UP) { + else if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::UP) { n->setHandled(); view->setEditing(false); - view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - TaskPostDataAtPoint::pointCallback, - ud); + view->removeEventCallback( + SoMouseButtonEvent::getClassTypeId(), + TaskPostDataAtPoint::pointCallback, + ud + ); disconnect(taskPost->connSelectPoint); } } @@ -1301,8 +1344,7 @@ void TaskPostDataAtPoint::onFieldActivated(int i) // The Elmer names are different. If there are EigenModes, the names are unique for // every mode. Therefore we only check for the beginning of the name. else if ((FieldName.find("tresca", 0) == 0) || (FieldName.find("vonmises", 0) == 0) - || (FieldName.find("stress_", 0) == 0) - || (FieldName.find("principal stress", 0) == 0)) { + || (FieldName.find("stress_", 0) == 0) || (FieldName.find("principal stress", 0) == 0)) { getObject()->Unit.setValue("Pa"); } else if ((FieldName == "current density") || (FieldName == "current density re") @@ -1357,9 +1399,8 @@ void TaskPostDataAtPoint::onFieldActivated(int i) getObject()->Unit.setValue("N"); } else if ((FieldName == "potential") || (FieldName == "potential re") - || (FieldName == "potential im") || (FieldName == "potential abs") - || (FieldName == "av") || (FieldName == "av re") || (FieldName == "av im") - || (FieldName == "av abs")) { + || (FieldName == "potential im") || (FieldName == "potential abs") || (FieldName == "av") + || (FieldName == "av re") || (FieldName == "av im") || (FieldName == "av abs")) { getObject()->Unit.setValue("V"); } else if (FieldName == "potential flux") { @@ -1422,13 +1463,8 @@ std::string TaskPostDataAtPoint::toString(double val) const // *************************************************************************** // clip filter -TaskPostClip::TaskPostClip(ViewProviderFemPostClip* view, - App::PropertyLink* function, - QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterClipRegion"), - QString(), - parent) +TaskPostClip::TaskPostClip(ViewProviderFemPostClip* view, App::PropertyLink* function, QWidget* parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterClipRegion"), QString(), parent) , ui(new Ui_TaskPostClip) { assert(function); @@ -1465,14 +1501,13 @@ TaskPostClip::~TaskPostClip() = default; void TaskPostClip::setupConnections() { - connect(ui->CreateButton, - &QToolButton::triggered, - this, - &TaskPostClip::onCreateButtonTriggered); - connect(ui->FunctionBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostClip::onFunctionBoxCurrentIndexChanged); + connect(ui->CreateButton, &QToolButton::triggered, this, &TaskPostClip::onCreateButtonTriggered); + connect( + ui->FunctionBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostClip::onFunctionBoxCurrentIndexChanged + ); connect(ui->InsideOut, &QCheckBox::toggled, this, &TaskPostClip::onInsideOutToggled); connect(ui->CutCells, &QCheckBox::toggled, this, &TaskPostClip::onCutCellsToggled); } @@ -1492,8 +1527,8 @@ void TaskPostClip::collectImplicitFunctions() ui->FunctionBox->clear(); QStringList items; std::size_t currentItem = 0; - App::DocumentObject* currentFunction = - getObject()->Function.getValue(); + App::DocumentObject* currentFunction + = getObject()->Function.getValue(); const std::vector& funcs = provider->Group.getValues(); for (std::size_t i = 0; i < funcs.size(); ++i) { items.push_back(QString::fromLatin1(funcs[i]->getNameInDocument())); @@ -1549,7 +1584,8 @@ void TaskPostClip::onFunctionBoxCurrentIndexChanged(int idx) // load the correct view Fem::FemPostFunction* fobj = static_cast( - getObject()->Function.getValue()); + getObject()->Function.getValue() + ); Gui::ViewProvider* view = nullptr; if (fobj) { view = Gui::Application::Instance->getViewProvider(fobj); @@ -1612,24 +1648,32 @@ TaskPostContours::TaskPostContours(ViewProviderFemPostContours* view, QWidget* p ui->dsb_relaxation->setEnabled(ext->EnableSmoothing.getValue()); // connect - connect(ui->fieldsCB, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostContours::onFieldsChanged); - connect(ui->vectorsCB, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostContours::onVectorModeChanged); - connect(ui->numberContoursSB, - qOverload(&QSpinBox::valueChanged), - this, - &TaskPostContours::onNumberOfContoursChanged); + connect( + ui->fieldsCB, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostContours::onFieldsChanged + ); + connect( + ui->vectorsCB, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostContours::onVectorModeChanged + ); + connect( + ui->numberContoursSB, + qOverload(&QSpinBox::valueChanged), + this, + &TaskPostContours::onNumberOfContoursChanged + ); connect(ui->noColorCB, &QCheckBox::toggled, this, &TaskPostContours::onNoColorChanged); connect(ui->ckb_smoothing, &QCheckBox::toggled, this, &TaskPostContours::onSmoothingChanged); - connect(ui->dsb_relaxation, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskPostContours::onRelaxationChanged); + connect( + ui->dsb_relaxation, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskPostContours::onRelaxationChanged + ); } TaskPostContours::~TaskPostContours() = default; @@ -1642,8 +1686,8 @@ void TaskPostContours::updateFields() // update the ViewProvider Field // since the ViewProvider can have another field sorting, we cannot use the same index if (!getObject()->NoColor.getValue()) { - std::string objectField = - getTypedObject()->Field.getValueAsString(); + std::string objectField + = getTypedObject()->Field.getValueAsString(); getTypedView()->Field.setValue(objectField.c_str()); } else { @@ -1735,10 +1779,7 @@ void TaskPostContours::onRelaxationChanged(double value) // *************************************************************************** // cut filter TaskPostCut::TaskPostCut(ViewProviderFemPostCut* view, App::PropertyLink* function, QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterCutFunction"), - QString(), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterCutFunction"), QString(), parent) , ui(new Ui_TaskPostCut) { assert(function); @@ -1772,10 +1813,12 @@ TaskPostCut::~TaskPostCut() = default; void TaskPostCut::setupConnections() { connect(ui->CreateButton, &QToolButton::triggered, this, &TaskPostCut::onCreateButtonTriggered); - connect(ui->FunctionBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostCut::onFunctionBoxCurrentIndexChanged); + connect( + ui->FunctionBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostCut::onFunctionBoxCurrentIndexChanged + ); } void TaskPostCut::applyPythonCode() @@ -1793,8 +1836,8 @@ void TaskPostCut::collectImplicitFunctions() ui->FunctionBox->clear(); QStringList items; std::size_t currentItem = 0; - App::DocumentObject* currentFunction = - getObject()->Function.getValue(); + App::DocumentObject* currentFunction + = getObject()->Function.getValue(); const std::vector& funcs = provider->Group.getValues(); for (std::size_t i = 0; i < funcs.size(); ++i) { items.push_back(QString::fromLatin1(funcs[i]->getNameInDocument())); @@ -1849,8 +1892,9 @@ void TaskPostCut::onFunctionBoxCurrentIndexChanged(int idx) } // load the correct view - Fem::FemPostFunction* fobj = - static_cast(getObject()->Function.getValue()); + Fem::FemPostFunction* fobj = static_cast( + getObject()->Function.getValue() + ); Gui::ViewProvider* view = nullptr; if (fobj) { view = Gui::Application::Instance->getViewProvider(fobj); @@ -1873,10 +1917,7 @@ void TaskPostCut::onFunctionBoxCurrentIndexChanged(int idx) // *************************************************************************** // scalar clip filter TaskPostScalarClip::TaskPostScalarClip(ViewProviderFemPostScalarClip* view, QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterClipScalar"), - QString(), - parent) + : TaskPostWidget(view, Gui::BitmapFactory().pixmap("FEM_PostFilterClipScalar"), QString(), parent) , ui(new Ui_TaskPostScalarClip) { // setup the ui @@ -1907,9 +1948,7 @@ TaskPostScalarClip::TaskPostScalarClip(ViewProviderFemPostScalarClip* view, QWid ui->Slider->blockSignals(true); ui->Slider->setValue(slider_value); ui->Slider->blockSignals(false); - Base::Console().log("init: scalar_factor, slider_value: %f, %i: \n", - scalar_factor, - slider_value); + Base::Console().log("init: scalar_factor, slider_value: %f, %i: \n", scalar_factor, slider_value); } TaskPostScalarClip::~TaskPostScalarClip() = default; @@ -1917,14 +1956,18 @@ TaskPostScalarClip::~TaskPostScalarClip() = default; void TaskPostScalarClip::setupConnections() { connect(ui->Slider, &QSlider::valueChanged, this, &TaskPostScalarClip::onSliderValueChanged); - connect(ui->Value, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskPostScalarClip::onValueValueChanged); - connect(ui->Scalar, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostScalarClip::onScalarCurrentIndexChanged); + connect( + ui->Value, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskPostScalarClip::onValueValueChanged + ); + connect( + ui->Scalar, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostScalarClip::onScalarCurrentIndexChanged + ); connect(ui->InsideOut, &QCheckBox::toggled, this, &TaskPostScalarClip::onInsideOutToggled); } @@ -1983,7 +2026,8 @@ void TaskPostScalarClip::onValueValueChanged(double v) ui->Slider->setValue( int(((v - value.getConstraints()->LowerBound) / (value.getConstraints()->UpperBound - value.getConstraints()->LowerBound)) - * 100.)); + * 100.) + ); ui->Slider->blockSignals(false); } @@ -2007,8 +2051,9 @@ TaskPostWarpVector::TaskPostWarpVector(ViewProviderFemPostWarpVector* view, QWid // load the default values for warp display updateEnumerationList(getTypedObject()->Vector, ui->Vector); - double warp_factor = getObject() - ->Factor.getValue(); // get the standard warp factor + double warp_factor = getObject()->Factor.getValue(); // get the + // standard + // warp factor // set spinbox warp_factor, don't forget to sync the slider ui->Value->blockSignals(true); @@ -2033,8 +2078,8 @@ TaskPostWarpVector::TaskPostWarpVector(ViewProviderFemPostWarpVector* view, QWid // slider_value = ----------------------- x 100 // ( max - min ) // - int slider_value = - (warp_factor - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) * 100.; + int slider_value = (warp_factor - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) + * 100.; ui->Slider->setValue(slider_value); ui->Slider->blockSignals(false); Base::Console().log("init: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); @@ -2045,22 +2090,30 @@ TaskPostWarpVector::~TaskPostWarpVector() = default; void TaskPostWarpVector::setupConnections() { connect(ui->Slider, &QSlider::valueChanged, this, &TaskPostWarpVector::onSliderValueChanged); - connect(ui->Value, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskPostWarpVector::onValueValueChanged); - connect(ui->Max, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskPostWarpVector::onMaxValueChanged); - connect(ui->Min, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskPostWarpVector::onMinValueChanged); - connect(ui->Vector, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPostWarpVector::onVectorCurrentIndexChanged); + connect( + ui->Value, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskPostWarpVector::onValueValueChanged + ); + connect( + ui->Max, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskPostWarpVector::onMaxValueChanged + ); + connect( + ui->Min, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskPostWarpVector::onMinValueChanged + ); + connect( + ui->Vector, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPostWarpVector::onVectorCurrentIndexChanged + ); } void TaskPostWarpVector::applyPythonCode() @@ -2082,8 +2135,8 @@ void TaskPostWarpVector::onSliderValueChanged(int slider_value) // warp_factor = min + ( slider_value x --------------- ) // 100 // - double warp_factor = - ui->Min->value() + ((ui->Max->value() - ui->Min->value()) / 100.) * slider_value; + double warp_factor = ui->Min->value() + + ((ui->Max->value() - ui->Min->value()) / 100.) * slider_value; getObject()->Factor.setValue(warp_factor); recompute(); @@ -2105,8 +2158,8 @@ void TaskPostWarpVector::onValueValueChanged(double warp_factor) // sync the slider, see above for formula ui->Slider->blockSignals(true); - int slider_value = - (warp_factor - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) * 100.; + int slider_value = (warp_factor - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) + * 100.; ui->Slider->setValue(slider_value); ui->Slider->blockSignals(false); Base::Console().log("Change: warp_factor, slider_value: %f, %i: \n", warp_factor, slider_value); @@ -2116,8 +2169,9 @@ void TaskPostWarpVector::onMaxValueChanged(double) { // TODO max should be greater than min, see a few lines later on problem on input characters ui->Slider->blockSignals(true); - ui->Slider->setValue((ui->Value->value() - ui->Min->value()) - / (ui->Max->value() - ui->Min->value()) * 100.); + ui->Slider->setValue( + (ui->Value->value() - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) * 100. + ); ui->Slider->blockSignals(false); /* @@ -2155,8 +2209,9 @@ void TaskPostWarpVector::onMinValueChanged(double) // TODO min should be smaller than max // TODO if warp factor is smaller than min, warp factor should be min, don't forget to sync ui->Slider->blockSignals(true); - ui->Slider->setValue((ui->Value->value() - ui->Min->value()) - / (ui->Max->value() - ui->Min->value()) * 100.); + ui->Slider->setValue( + (ui->Value->value() - ui->Min->value()) / (ui->Max->value() - ui->Min->value()) * 100. + ); ui->Slider->blockSignals(false); } @@ -2165,13 +2220,16 @@ void TaskPostWarpVector::onMinValueChanged(double) // calculator filter static const std::vector calculatorOperators = { "+", "-", "*", "/", "-", "^", "abs", "cos", "sin", "tan", "exp", - "log", "pow", "sqrt", "iHat", "jHat", "kHat", "cross", "dot", "mag", "norm"}; + "log", "pow", "sqrt", "iHat", "jHat", "kHat", "cross", "dot", "mag", "norm" +}; TaskPostCalculator::TaskPostCalculator(ViewProviderFemPostCalculator* view, QWidget* parent) - : TaskPostWidget(view, - Gui::BitmapFactory().pixmap("FEM_PostFilterCalculator"), - tr("Calculator options"), - parent) + : TaskPostWidget( + view, + Gui::BitmapFactory().pixmap("FEM_PostFilterCalculator"), + tr("Calculator options"), + parent + ) , ui(new Ui_TaskPostCalculator) { // we load the views widget @@ -2217,26 +2275,36 @@ TaskPostCalculator::~TaskPostCalculator() = default; void TaskPostCalculator::setupConnections() { - connect(ui->dsb_replacement_value, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskPostCalculator::onReplacementValueChanged); - connect(ui->ckb_replace_invalid, - &QCheckBox::toggled, - this, - &TaskPostCalculator::onReplaceInvalidChanged); - connect(ui->cb_scalars, - qOverload(&QComboBox::activated), - this, - &TaskPostCalculator::onScalarsActivated); - connect(ui->cb_vectors, - qOverload(&QComboBox::activated), - this, - &TaskPostCalculator::onVectorsActivated); - connect(ui->cb_operators, - qOverload(&QComboBox::activated), - this, - &TaskPostCalculator::onOperatorsActivated); + connect( + ui->dsb_replacement_value, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskPostCalculator::onReplacementValueChanged + ); + connect( + ui->ckb_replace_invalid, + &QCheckBox::toggled, + this, + &TaskPostCalculator::onReplaceInvalidChanged + ); + connect( + ui->cb_scalars, + qOverload(&QComboBox::activated), + this, + &TaskPostCalculator::onScalarsActivated + ); + connect( + ui->cb_vectors, + qOverload(&QComboBox::activated), + this, + &TaskPostCalculator::onVectorsActivated + ); + connect( + ui->cb_operators, + qOverload(&QComboBox::activated), + this, + &TaskPostCalculator::onOperatorsActivated + ); } void TaskPostCalculator::onReplaceInvalidChanged(bool state) diff --git a/src/Mod/Fem/Gui/TaskPostBoxes.h b/src/Mod/Fem/Gui/TaskPostBoxes.h index 1303323898..996afb6c38 100644 --- a/src/Mod/Fem/Gui/TaskPostBoxes.h +++ b/src/Mod/Fem/Gui/TaskPostBoxes.h @@ -137,10 +137,12 @@ class TaskPostWidget: public QWidget // Q_OBJECT public: - TaskPostWidget(Gui::ViewProviderDocumentObject* view, - const QPixmap& icon, - const QString& title = QString(), - QWidget* parent = nullptr); + TaskPostWidget( + Gui::ViewProviderDocumentObject* view, + const QPixmap& icon, + const QString& title = QString(), + QWidget* parent = nullptr + ); ~TaskPostWidget() override; virtual void applyPythonCode() {}; @@ -355,8 +357,7 @@ class TaskPostDataAlongLine: public TaskPostWidget Q_OBJECT public: - explicit TaskPostDataAlongLine(ViewProviderFemPostDataAlongLine* view, - QWidget* parent = nullptr); + explicit TaskPostDataAlongLine(ViewProviderFemPostDataAlongLine* view, QWidget* parent = nullptr); ~TaskPostDataAlongLine() override; void applyPythonCode() override; @@ -428,9 +429,7 @@ class TaskPostClip: public TaskPostWidget Q_OBJECT public: - TaskPostClip(ViewProviderFemPostClip* view, - App::PropertyLink* function, - QWidget* parent = nullptr); + TaskPostClip(ViewProviderFemPostClip* view, App::PropertyLink* function, QWidget* parent = nullptr); ~TaskPostClip() override; void applyPythonCode() override; @@ -492,9 +491,7 @@ class TaskPostCut: public TaskPostWidget Q_OBJECT public: - TaskPostCut(ViewProviderFemPostCut* view, - App::PropertyLink* function, - QWidget* parent = nullptr); + TaskPostCut(ViewProviderFemPostCut* view, App::PropertyLink* function, QWidget* parent = nullptr); ~TaskPostCut() override; void applyPythonCode() override; diff --git a/src/Mod/Fem/Gui/TaskTetParameter.cpp b/src/Mod/Fem/Gui/TaskTetParameter.cpp index 636e1412f6..736a164da6 100644 --- a/src/Mod/Fem/Gui/TaskTetParameter.cpp +++ b/src/Mod/Fem/Gui/TaskTetParameter.cpp @@ -55,51 +55,66 @@ TaskTetParameter::TaskTetParameter(Fem::FemMeshShapeNetgenObject* pcObject, QWid ui->spinBox_SegsPerRadius->setValue(pcObject->NbSegsPerRadius.getValue()); ui->checkBox_Optimize->setChecked(pcObject->Optimize.getValue()); - QObject::connect(ui->doubleSpinBox_MaxSize, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskTetParameter::maxSizeValueChanged); - QObject::connect(ui->doubleSpinBox_MinSize, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskTetParameter::minSizeValueChanged); - QObject::connect(ui->comboBox_Fineness, - qOverload(&QComboBox::activated), - this, - &TaskTetParameter::SwitchMethod); + QObject::connect( + ui->doubleSpinBox_MaxSize, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskTetParameter::maxSizeValueChanged + ); + QObject::connect( + ui->doubleSpinBox_MinSize, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskTetParameter::minSizeValueChanged + ); + QObject::connect( + ui->comboBox_Fineness, + qOverload(&QComboBox::activated), + this, + &TaskTetParameter::SwitchMethod + ); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - QObject::connect(ui->checkBox_SecondOrder, - &QCheckBox::checkStateChanged, - this, - &TaskTetParameter::setQuadric); + QObject::connect( + ui->checkBox_SecondOrder, + &QCheckBox::checkStateChanged, + this, + &TaskTetParameter::setQuadric + ); #else - QObject::connect(ui->checkBox_SecondOrder, - &QCheckBox::stateChanged, - this, - &TaskTetParameter::setQuadric); + QObject::connect( + ui->checkBox_SecondOrder, + &QCheckBox::stateChanged, + this, + &TaskTetParameter::setQuadric + ); #endif - QObject::connect(ui->doubleSpinBox_GrowthRate, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &TaskTetParameter::setGrowthRate); - QObject::connect(ui->spinBox_SegsPerEdge, - qOverload(&QSpinBox::valueChanged), - this, - &TaskTetParameter::setSegsPerEdge); - QObject::connect(ui->spinBox_SegsPerRadius, - qOverload(&QSpinBox::valueChanged), - this, - &TaskTetParameter::setSegsPerRadius); + QObject::connect( + ui->doubleSpinBox_GrowthRate, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &TaskTetParameter::setGrowthRate + ); + QObject::connect( + ui->spinBox_SegsPerEdge, + qOverload(&QSpinBox::valueChanged), + this, + &TaskTetParameter::setSegsPerEdge + ); + QObject::connect( + ui->spinBox_SegsPerRadius, + qOverload(&QSpinBox::valueChanged), + this, + &TaskTetParameter::setSegsPerRadius + ); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - QObject::connect(ui->checkBox_Optimize, - &QCheckBox::checkStateChanged, - this, - &TaskTetParameter::setOptimize); + QObject::connect( + ui->checkBox_Optimize, + &QCheckBox::checkStateChanged, + this, + &TaskTetParameter::setOptimize + ); #else - QObject::connect(ui->checkBox_Optimize, - &QCheckBox::stateChanged, - this, - &TaskTetParameter::setOptimize); + QObject::connect(ui->checkBox_Optimize, &QCheckBox::stateChanged, this, &TaskTetParameter::setOptimize); #endif if (pcObject->FemMesh.getValue().getInfo().numNode == 0) { touched = true; diff --git a/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp b/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp index 51da492e5a..96a85b24b3 100644 --- a/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp +++ b/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp @@ -48,7 +48,7 @@ #include #include #ifdef FC_USE_VTK -#include +# include #endif #include "TaskDlgAnalysis.h" @@ -125,9 +125,11 @@ bool ViewProviderFemAnalysis::doubleClicked() { Gui::Command::assureWorkbench("FemWorkbench"); Gui::Command::addModule(Gui::Command::Gui, "FemGui"); - Gui::Command::doCommand(Gui::Command::Gui, - "FemGui.setActiveAnalysis(App.activeDocument().%s)", - this->getObject()->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Gui, + "FemGui.setActiveAnalysis(App.activeDocument().%s)", + this->getObject()->getNameInDocument() + ); // After activation of the analysis the allowed FEM toolbar buttons should become active. // To achieve this we must clear the object selection to trigger the selection observer. Gui::Command::doCommand(Gui::Command::Gui, "Gui.Selection.clearSelection()"); @@ -160,9 +162,7 @@ void ViewProviderFemAnalysis::setupContextMenu(QMenu* menu, QObject*, const char { Gui::ActionFunction* func = new Gui::ActionFunction(menu); QAction* act = menu->addAction(tr("Activate Analysis")); - func->trigger(act, [this]() { - this->doubleClicked(); - }); + func->trigger(act, [this]() { this->doubleClicked(); }); } bool ViewProviderFemAnalysis::setEdit(int ModNum) @@ -272,9 +272,11 @@ bool ViewProviderFemAnalysis::onDelete(const std::vector&) return checkSelectedChildren(objs, this->getDocument(), "analysis"); } -bool ViewProviderFemAnalysis::checkSelectedChildren(const std::vector objs, - Gui::Document* docGui, - std::string objectName) +bool ViewProviderFemAnalysis::checkSelectedChildren( + const std::vector objs, + Gui::Document* docGui, + std::string objectName +) { // warn the user if the object has unselected children if (!objs.empty()) { @@ -284,8 +286,7 @@ bool ViewProviderFemAnalysis::checkSelectedChildren(const std::vectorgetNameInDocument()) - == std::string(selection.getFeatName())) { + if (std::string(child->getNameInDocument()) == std::string(selection.getFeatName())) { found = true; break; } @@ -301,23 +302,26 @@ bool ViewProviderFemAnalysis::checkSelectedChildren(const std::vectortranslate("Std_Delete", - ("The " + objectName - + " is not empty, therefore the\nfollowing " - "referencing objects might be lost:") - .c_str()); + bodyMessageStream << qApp->translate( + "Std_Delete", + ("The " + objectName + + " is not empty, therefore the\nfollowing " + "referencing objects might be lost:") + .c_str() + ); bodyMessageStream << '\n'; for (auto ObjIterator : objs) { bodyMessageStream << '\n' << QString::fromUtf8(ObjIterator->Label.getValue()); } bodyMessageStream << "\n\n" << QObject::tr("Are you sure you want to continue?"); // show and evaluate the dialog - int DialogResult = - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Std_Delete", "Object dependencies"), - bodyMessage, - QMessageBox::Yes, - QMessageBox::No); + int DialogResult = QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Std_Delete", "Object dependencies"), + bodyMessage, + QMessageBox::Yes, + QMessageBox::No + ); if (DialogResult == QMessageBox::Yes) { return true; } diff --git a/src/Mod/Fem/Gui/ViewProviderAnalysis.h b/src/Mod/Fem/Gui/ViewProviderAnalysis.h index e8f0b0bf2c..65b30375cb 100644 --- a/src/Mod/Fem/Gui/ViewProviderAnalysis.h +++ b/src/Mod/Fem/Gui/ViewProviderAnalysis.h @@ -67,9 +67,11 @@ public: /// handling when object is deleted bool onDelete(const std::vector&) override; /// warning on deletion when there are children - static bool checkSelectedChildren(const std::vector objs, - Gui::Document* docGui, - std::string objectName); + static bool checkSelectedChildren( + const std::vector objs, + Gui::Document* docGui, + std::string objectName + ); /// asks the view provider if the given object can be deleted bool canDelete(App::DocumentObject* obj) const override; diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp index 5da4db43a8..4ac9c5a1a9 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp @@ -94,8 +94,8 @@ void ViewProviderFemConstraint::attach(App::DocumentObject* pcObject) addDisplayMaskMode(sep, "Base"); } -std::string ViewProviderFemConstraint::resourceSymbolDir = - App::Application::getResourceDir() + "Mod/Fem/Resources/symbols/"; +std::string ViewProviderFemConstraint::resourceSymbolDir = App::Application::getResourceDir() + + "Mod/Fem/Resources/symbols/"; void ViewProviderFemConstraint::loadSymbol(const char* fileName) { @@ -156,9 +156,11 @@ void ViewProviderFemConstraint::setupContextMenu(QMenu* menu, QObject* receiver, QAction* act; act = menu->addAction(QObject::tr("Edit Analysis Feature"), receiver, member); act->setData(QVariant((int)ViewProvider::Default)); - ViewProviderGeometryObject::setupContextMenu(menu, - receiver, - member); // clazy:exclude=skipped-base-method + ViewProviderGeometryObject::setupContextMenu( + menu, + receiver, + member + ); // clazy:exclude=skipped-base-method } void ViewProviderFemConstraint::onChanged(const App::Property* prop) @@ -179,9 +181,11 @@ void ViewProviderFemConstraint::updateData(const App::Property* prop) } } -void ViewProviderFemConstraint::handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) +void ViewProviderFemConstraint::handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName +) { if (strcmp(propName, "FaceColor") == 0 && Base::Type::fromName(typeName) == App::PropertyColor::getClassTypeId()) { @@ -229,9 +233,11 @@ void ViewProviderFemConstraint::updateSymbol() transformExtraSymbol(); } -void ViewProviderFemConstraint::transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const +void ViewProviderFemConstraint::transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat +) const { auto obj = this->getObject(); SbVec3f axisY(0, 1, 0); @@ -239,9 +245,7 @@ void ViewProviderFemConstraint::transformSymbol(const Base::Vector3d& point, SbVec3f scale(s, s, s); SbVec3f norm = rotateSymbol ? SbVec3f(normal.x, normal.y, normal.z) : axisY; SbRotation rot(axisY, norm); - SbVec3f tra(static_cast(point.x), - static_cast(point.y), - static_cast(point.z)); + SbVec3f tra(static_cast(point.x), static_cast(point.y), static_cast(point.z)); mat.setTransform(tra, rot, scale); } @@ -275,9 +279,11 @@ std::string ViewProviderFemConstraint::gethideMeshShowPartStr() bool ViewProviderFemConstraint::setEdit(int ModNum) { - Gui::Command::doCommand(Gui::Command::Doc, - "%s", - ViewProviderFemConstraint::gethideMeshShowPartStr().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "%s", + ViewProviderFemConstraint::gethideMeshShowPartStr().c_str() + ); return Gui::ViewProviderGeometryObject::setEdit(ModNum); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraint.h b/src/Mod/Fem/Gui/ViewProviderFemConstraint.h index 0f74e52488..012e5e599a 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraint.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraint.h @@ -87,13 +87,18 @@ protected: void onChanged(const App::Property* prop) override; bool setEdit(int ModNum) override; void unsetEdit(int ModNum) override; - void handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName + ) override; void updateSymbol(); - virtual void - transformSymbol(const Base::Vector3d& point, const Base::Vector3d& normal, SbMatrix& mat) const; + virtual void transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat + ) const; virtual void transformExtraSymbol() const; private: diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp index d4b3470d43..54f3922a99 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp @@ -86,9 +86,9 @@ void ViewProviderFemConstraintBearing::updateData(const App::Property* prop) SbRotation rot(SbVec3f(0, -1, 0), dir); GuiTools::createPlacement(pShapeSep, b, rot); - pShapeSep->addChild(GuiTools::createFixed(radius / 2, - radius / 2 * 1.5, - pcConstraint->AxialFree.getValue())); + pShapeSep->addChild( + GuiTools::createFixed(radius / 2, radius / 2 * 1.5, pcConstraint->AxialFree.getValue()) + ); } else if (prop == &pcConstraint->AxialFree) { if (pShapeSep->getNumChildren() > 0) { @@ -104,11 +104,13 @@ void ViewProviderFemConstraintBearing::updateData(const App::Property* prop) GuiTools::updatePlacement(pShapeSep, 0, b, rot); const SoSeparator* sep = static_cast(pShapeSep->getChild(2)); - GuiTools::updateFixed(sep, - 0, - radius / 2, - radius / 2 * 1.5, - pcConstraint->AxialFree.getValue()); + GuiTools::updateFixed( + sep, + 0, + radius / 2, + radius / 2 * 1.5, + pcConstraint->AxialFree.getValue() + ); } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp index 18bb00786c..20e5919f1e 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp @@ -36,8 +36,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintDisplacement, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintDisplacement, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintDisplacement::ViewProviderFemConstraintDisplacement() { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h index 9eafbcdafb..a1962e235e 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h @@ -30,8 +30,7 @@ namespace FemGui { -class FemGuiExport ViewProviderFemConstraintFixed - : public FemGui::ViewProviderFemConstraintOnBoundary +class FemGuiExport ViewProviderFemConstraintFixed: public FemGui::ViewProviderFemConstraintOnBoundary { PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintFixed); diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp index d314c19472..4165e2ee35 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp @@ -39,8 +39,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintFluidBoundary, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintFluidBoundary, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintFluidBoundary::ViewProviderFemConstraintFluidBoundary() @@ -77,12 +76,12 @@ void ViewProviderFemConstraintFluidBoundary::updateData(const App::Property* pro { // Gets called whenever a property of the attached object changes Fem::ConstraintFluidBoundary* pcConstraint = this->getObject(); - float scaledwidth = - WIDTH * pcConstraint->Scale.getValue(); // OvG: Calculate scaled values once only + float scaledwidth = WIDTH + * pcConstraint->Scale.getValue(); // OvG: Calculate scaled values once only float scaledheight = HEIGHT * pcConstraint->Scale.getValue(); - float scaledheadradius = - ARROWHEADRADIUS * pcConstraint->Scale.getValue(); // OvG: Calculate scaled values once only + float scaledheadradius = ARROWHEADRADIUS + * pcConstraint->Scale.getValue(); // OvG: Calculate scaled values once only float scaledlength = ARROWLENGTH * pcConstraint->Scale.getValue(); std::string boundaryType = pcConstraint->BoundaryType.getValueAsString(); @@ -111,8 +110,8 @@ void ViewProviderFemConstraintFluidBoundary::updateData(const App::Property* pro if (pShapeSep->getNumChildren() == 0) { // Set up the nodes cp->matrix.setNum(0); - cp->addChild( - (SoNode*)GuiTools::createArrow(scaledlength, scaledheadradius)); // OvG: Scaling + cp->addChild((SoNode*)GuiTools::createArrow(scaledlength, scaledheadradius)); // OvG: + // Scaling pShapeSep->addChild(cp); } #endif @@ -216,8 +215,7 @@ void ViewProviderFemConstraintFluidBoundary::updateData(const App::Property* pro if (pShapeSep->getNumChildren() == 0) { // Set up the nodes cp->matrix.setNum(0); - cp->addChild( - (SoNode*)GuiTools::createFixed(scaledheight, scaledwidth)); // OvG: Scaling + cp->addChild((SoNode*)GuiTools::createFixed(scaledheight, scaledwidth)); // OvG: Scaling pShapeSep->addChild(cp); } #endif diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp index f5edccc66c..982fda927c 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp @@ -74,9 +74,11 @@ void ViewProviderFemConstraintForce::updateData(const App::Property* prop) } } -void ViewProviderFemConstraintForce::transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const +void ViewProviderFemConstraintForce::transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat +) const { auto obj = this->getObject(); bool rev = obj->Reversed.getValue(); @@ -88,15 +90,19 @@ void ViewProviderFemConstraintForce::transformSymbol(const Base::Vector3d& point float symTraY = dir.Dot(normal) < 0 ? -1 * symLen : 0.0f; float rotAngle = rev ? std::numbers::pi_v : 0.0f; SbMatrix mat0, mat1; - mat0.setTransform(SbVec3f(0, symTraY, 0), - SbRotation(SbVec3f(0, 0, 1), rotAngle), - SbVec3f(1, 1, 1), - SbRotation(SbVec3f(0, 0, 1), 0), - SbVec3f(0, symLen / 2.0f, 0)); + mat0.setTransform( + SbVec3f(0, symTraY, 0), + SbRotation(SbVec3f(0, 0, 1), rotAngle), + SbVec3f(1, 1, 1), + SbRotation(SbVec3f(0, 0, 1), 0), + SbVec3f(0, symLen / 2.0f, 0) + ); - mat1.setTransform(SbVec3f(point.x, point.y, point.z), - SbRotation(SbVec3f(0, 1, 0), SbVec3f(dir.x, dir.y, dir.z)), - SbVec3f(s, s, s)); + mat1.setTransform( + SbVec3f(point.x, point.y, point.z), + SbRotation(SbVec3f(0, 1, 0), SbVec3f(dir.x, dir.y, dir.z)), + SbVec3f(s, s, s) + ); mat = mat0 * mat1; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h index 440e29e65a..da03e89fe4 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h @@ -30,8 +30,7 @@ namespace FemGui { -class FemGuiExport ViewProviderFemConstraintForce - : public FemGui::ViewProviderFemConstraintOnBoundary +class FemGuiExport ViewProviderFemConstraintForce: public FemGui::ViewProviderFemConstraintOnBoundary { PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintForce); @@ -44,9 +43,11 @@ public: protected: bool setEdit(int ModNum) override; - void transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const override; + void transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat + ) const override; private: /// Direction of the force diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp index f5d9451bb7..fc0526cc22 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp @@ -97,10 +97,13 @@ void ViewProviderFemConstraintGear::updateData(const App::Property* prop) GuiTools::createPlacement(pShapeSep, b, SbRotation(SbVec3f(0, 1, 0), ax)); pShapeSep->addChild( - GuiTools::createCylinder(pcConstraint->Height.getValue() * 0.8, dia / 2)); - GuiTools::createPlacement(pShapeSep, - SbVec3f(dia / 2 * sin(angle), 0, dia / 2 * cos(angle)), - SbRotation(ax, dir)); + GuiTools::createCylinder(pcConstraint->Height.getValue() * 0.8, dia / 2) + ); + GuiTools::createPlacement( + pShapeSep, + SbVec3f(dia / 2 * sin(angle), 0, dia / 2 * cos(angle)), + SbRotation(ax, dir) + ); pShapeSep->addChild(GuiTools::createArrow(dia / 2, dia / 8)); } } @@ -124,10 +127,12 @@ void ViewProviderFemConstraintGear::updateData(const App::Property* prop) const SoSeparator* sep = static_cast(pShapeSep->getChild(2)); GuiTools::updateCylinder(sep, 0, pcConstraint->Height.getValue() * 0.8, dia / 2); - GuiTools::updatePlacement(pShapeSep, - 3, - SbVec3f(dia / 2 * sin(angle), 0, dia / 2 * cos(angle)), - SbRotation(ax, dir)); + GuiTools::updatePlacement( + pShapeSep, + 3, + SbVec3f(dia / 2 * sin(angle), 0, dia / 2 * cos(angle)), + SbRotation(ax, dir) + ); sep = static_cast(pShapeSep->getChild(5)); GuiTools::updateArrow(sep, 0, dia / 2, dia / 8); } @@ -160,10 +165,12 @@ void ViewProviderFemConstraintGear::updateData(const App::Property* prop) directions!) */ - GuiTools::updatePlacement(pShapeSep, - 3, - SbVec3f(dia / 2 * sin(angle), 0, dia / 2 * cos(angle)), - SbRotation(ax, dir)); + GuiTools::updatePlacement( + pShapeSep, + 3, + SbVec3f(dia / 2 * sin(angle), 0, dia / 2 * cos(angle)), + SbRotation(ax, dir) + ); } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp index 4123e6be44..90df60c73f 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp @@ -32,8 +32,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintHeatflux, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintHeatflux, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintHeatflux::ViewProviderFemConstraintHeatflux() { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp index 4d02bd4343..bb76d6d7e4 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp @@ -33,8 +33,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintInitialTemperature, - FemGui::ViewProviderFemConstraint) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintInitialTemperature, FemGui::ViewProviderFemConstraint) ViewProviderFemConstraintInitialTemperature::ViewProviderFemConstraintInitialTemperature() { @@ -42,8 +41,7 @@ ViewProviderFemConstraintInitialTemperature::ViewProviderFemConstraintInitialTem ShapeAppearance.setDiffuseColor(0.2f, 0.3f, 0.2f); } -ViewProviderFemConstraintInitialTemperature::~ViewProviderFemConstraintInitialTemperature() = - default; +ViewProviderFemConstraintInitialTemperature::~ViewProviderFemConstraintInitialTemperature() = default; bool ViewProviderFemConstraintInitialTemperature::setEdit(int ModNum) { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp index 269f07d614..6c8ef7a359 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.cpp @@ -51,7 +51,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) continue; } PartGui::ViewProviderPart* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); + Gui::Application::Instance->getViewProvider(base) + ); if (!vp) { continue; } @@ -72,7 +73,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) // TODO: Replace `ShapeAppearance` with anything more appropriate PartGui::ReferenceHighlighter highlighter( base->Shape.getValue(), - colors.empty() ? ShapeAppearance.getDiffuseColor() : colors[0]); + colors.empty() ? ShapeAppearance.getDiffuseColor() : colors[0] + ); highlighter.getVertexColors(subSet.second, colors); vp->PointColorArray.setValues(colors); } @@ -87,7 +89,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) // TODO: Replace `ShapeAppearance` with anything more appropriate PartGui::ReferenceHighlighter highlighter( base->Shape.getValue(), - colors.empty() ? ShapeAppearance.getDiffuseColor() : colors[0]); + colors.empty() ? ShapeAppearance.getDiffuseColor() : colors[0] + ); highlighter.getEdgeColors(subSet.second, colors); vp->LineColorArray.setValues(colors); } @@ -102,7 +105,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) // TODO: Replace shape DiffuseColor with anything more appropriate PartGui::ReferenceHighlighter highlighter( base->Shape.getValue(), - colors.empty() ? ShapeAppearance.getDiffuseColor() : colors[0]); + colors.empty() ? ShapeAppearance.getDiffuseColor() : colors[0] + ); highlighter.getFaceColors(subSet.second, colors); vp->ShapeAppearance.setDiffuseColors(colors); } @@ -131,7 +135,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) continue; } PartGui::ViewProviderPart* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(ogPair.first)); + Gui::Application::Instance->getViewProvider(ogPair.first) + ); if (!vp) { continue; } @@ -145,7 +150,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) continue; } PartGui::ViewProviderPart* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(ogPair.first)); + Gui::Application::Instance->getViewProvider(ogPair.first) + ); if (!vp) { continue; } @@ -159,7 +165,8 @@ void ViewProviderFemConstraintOnBoundary::highlightReferences(const bool on) continue; } PartGui::ViewProviderPart* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(ogPair.first)); + Gui::Application::Instance->getViewProvider(ogPair.first) + ); if (!vp) { continue; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp index 1e53b6a05c..4a5d3e654b 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp @@ -36,8 +36,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintPressure, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintPressure, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintPressure::ViewProviderFemConstraintPressure() { @@ -75,9 +74,11 @@ void ViewProviderFemConstraintPressure::updateData(const App::Property* prop) } } -void ViewProviderFemConstraintPressure::transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const +void ViewProviderFemConstraintPressure::transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat +) const { auto obj = this->getObject(); float rotAngle = obj->Reversed.getValue() ? std::numbers::pi_v : 0.0f; @@ -85,15 +86,19 @@ void ViewProviderFemConstraintPressure::transformSymbol(const Base::Vector3d& po // Symbol length from .iv file float symLen = 4.0f; SbMatrix mat0, mat1; - mat0.setTransform(SbVec3f(0, 0, 0), - SbRotation(SbVec3f(0, 0, 1), rotAngle), - SbVec3f(1, 1, 1), - SbRotation(SbVec3f(0, 0, 1), 0), - SbVec3f(0, symLen / 2.0f, 0)); + mat0.setTransform( + SbVec3f(0, 0, 0), + SbRotation(SbVec3f(0, 0, 1), rotAngle), + SbVec3f(1, 1, 1), + SbRotation(SbVec3f(0, 0, 1), 0), + SbVec3f(0, symLen / 2.0f, 0) + ); - mat1.setTransform(SbVec3f(point.x, point.y, point.z), - SbRotation(SbVec3f(0, 1, 0), SbVec3f(normal.x, normal.y, normal.z)), - SbVec3f(s, s, s)); + mat1.setTransform( + SbVec3f(point.x, point.y, point.z), + SbRotation(SbVec3f(0, 1, 0), SbVec3f(normal.x, normal.y, normal.z)), + SbVec3f(s, s, s) + ); mat = mat0 * mat1; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h index 2f328bdda3..3833650bcb 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h @@ -41,9 +41,11 @@ public: protected: bool setEdit(int ModNum) override; - void transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const override; + void transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat + ) const override; }; } // namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp index 67d87a1580..876783d734 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp @@ -96,32 +96,34 @@ void ViewProviderFemConstraintPulley::updateData(const App::Property* prop) SbVec3f b(base.x, base.y, base.z); SbVec3f ax(axis.x, axis.y, axis.z); - GuiTools::createPlacement(pShapeSep, - b, - SbRotation(SbVec3f(0, 1, 0), ax)); // child 0 and 1 - pShapeSep->addChild(GuiTools::createCylinder(pcConstraint->Height.getValue() * 0.8, - dia / 2)); // child 2 + GuiTools::createPlacement(pShapeSep, b, SbRotation(SbVec3f(0, 1, 0), ax)); // child 0 and 1 + pShapeSep->addChild( + GuiTools::createCylinder( + pcConstraint->Height.getValue() * 0.8, + dia / 2 + ) + ); // child 2 SoSeparator* sep = new SoSeparator(); - GuiTools::createPlacement(sep, - SbVec3f(dia / 2 * sin(forceAngle + beltAngle), - 0, - dia / 2 * cos(forceAngle + beltAngle)), - SbRotation(SbVec3f(0, 1, 0), - SbVec3f(sin(forceAngle + beltAngle + pi / 2), - 0, - cos(forceAngle + beltAngle + pi / 2)))); + GuiTools::createPlacement( + sep, + SbVec3f(dia / 2 * sin(forceAngle + beltAngle), 0, dia / 2 * cos(forceAngle + beltAngle)), + SbRotation( + SbVec3f(0, 1, 0), + SbVec3f(sin(forceAngle + beltAngle + pi / 2), 0, cos(forceAngle + beltAngle + pi / 2)) + ) + ); GuiTools::createPlacement(sep, SbVec3f(0, dia / 8 + dia / 2 * rat1, 0), SbRotation()); sep->addChild(GuiTools::createArrow(dia / 8 + dia / 2 * rat1, dia / 8)); pShapeSep->addChild(sep); // child 3 sep = new SoSeparator(); - GuiTools::createPlacement(sep, - SbVec3f(-dia / 2 * sin(forceAngle - beltAngle), - 0, - -dia / 2 * cos(forceAngle - beltAngle)), - SbRotation(SbVec3f(0, 1, 0), - SbVec3f(-sin(forceAngle - beltAngle - pi / 2), - 0, - -cos(forceAngle - beltAngle - pi / 2)))); + GuiTools::createPlacement( + sep, + SbVec3f(-dia / 2 * sin(forceAngle - beltAngle), 0, -dia / 2 * cos(forceAngle - beltAngle)), + SbRotation( + SbVec3f(0, 1, 0), + SbVec3f(-sin(forceAngle - beltAngle - pi / 2), 0, -cos(forceAngle - beltAngle - pi / 2)) + ) + ); GuiTools::createPlacement(sep, SbVec3f(0, dia / 8 + dia / 2 * rat2, 0), SbRotation()); sep->addChild(GuiTools::createArrow(dia / 8 + dia / 2 * rat2, dia / 8)); pShapeSep->addChild(sep); // child 4 @@ -148,35 +150,29 @@ void ViewProviderFemConstraintPulley::updateData(const App::Property* prop) const SoSeparator* sep = static_cast(pShapeSep->getChild(2)); GuiTools::updateCylinder(sep, 0, pcConstraint->Height.getValue() * 0.8, dia / 2); sep = static_cast(pShapeSep->getChild(3)); - GuiTools::updatePlacement(sep, - 0, - SbVec3f(dia / 2 * sin(forceAngle + beltAngle), - 0, - dia / 2 * cos(forceAngle + beltAngle)), - SbRotation(SbVec3f(0, 1, 0), - SbVec3f(sin(forceAngle + beltAngle + pi / 2), - 0, - cos(forceAngle + beltAngle + pi / 2)))); - GuiTools::updatePlacement(sep, - 2, - SbVec3f(0, dia / 8 + dia / 2 * rat1, 0), - SbRotation()); + GuiTools::updatePlacement( + sep, + 0, + SbVec3f(dia / 2 * sin(forceAngle + beltAngle), 0, dia / 2 * cos(forceAngle + beltAngle)), + SbRotation( + SbVec3f(0, 1, 0), + SbVec3f(sin(forceAngle + beltAngle + pi / 2), 0, cos(forceAngle + beltAngle + pi / 2)) + ) + ); + GuiTools::updatePlacement(sep, 2, SbVec3f(0, dia / 8 + dia / 2 * rat1, 0), SbRotation()); const SoSeparator* subsep = static_cast(sep->getChild(4)); GuiTools::updateArrow(subsep, 0, dia / 8 + dia / 2 * rat1, dia / 8); sep = static_cast(pShapeSep->getChild(4)); - GuiTools::updatePlacement(sep, - 0, - SbVec3f(-dia / 2 * sin(forceAngle - beltAngle), - 0, - -dia / 2 * cos(forceAngle - beltAngle)), - SbRotation(SbVec3f(0, 1, 0), - SbVec3f(-sin(forceAngle - beltAngle - pi / 2), - 0, - -cos(forceAngle - beltAngle - pi / 2)))); - GuiTools::updatePlacement(sep, - 2, - SbVec3f(0, dia / 8 + dia / 2 * rat2, 0), - SbRotation()); + GuiTools::updatePlacement( + sep, + 0, + SbVec3f(-dia / 2 * sin(forceAngle - beltAngle), 0, -dia / 2 * cos(forceAngle - beltAngle)), + SbRotation( + SbVec3f(0, 1, 0), + SbVec3f(-sin(forceAngle - beltAngle - pi / 2), 0, -cos(forceAngle - beltAngle - pi / 2)) + ) + ); + GuiTools::updatePlacement(sep, 2, SbVec3f(0, dia / 8 + dia / 2 * rat2, 0), SbRotation()); subsep = static_cast(sep->getChild(4)); GuiTools::updateArrow(subsep, 0, dia / 8 + dia / 2 * rat2, dia / 8); } @@ -192,25 +188,25 @@ void ViewProviderFemConstraintPulley::updateData(const App::Property* prop) double beltAngle = pcConstraint->BeltAngle.getValue(); const SoSeparator* sep = static_cast(pShapeSep->getChild(3)); - GuiTools::updatePlacement(sep, - 0, - SbVec3f(dia / 2 * sin(forceAngle + beltAngle), - 0, - dia / 2 * cos(forceAngle + beltAngle)), - SbRotation(SbVec3f(0, 1, 0), - SbVec3f(sin(forceAngle + beltAngle + pi / 2), - 0, - cos(forceAngle + beltAngle + pi / 2)))); + GuiTools::updatePlacement( + sep, + 0, + SbVec3f(dia / 2 * sin(forceAngle + beltAngle), 0, dia / 2 * cos(forceAngle + beltAngle)), + SbRotation( + SbVec3f(0, 1, 0), + SbVec3f(sin(forceAngle + beltAngle + pi / 2), 0, cos(forceAngle + beltAngle + pi / 2)) + ) + ); sep = static_cast(pShapeSep->getChild(4)); - GuiTools::updatePlacement(sep, - 0, - SbVec3f(-dia / 2 * sin(forceAngle - beltAngle), - 0, - -dia / 2 * cos(forceAngle - beltAngle)), - SbRotation(SbVec3f(0, 1, 0), - SbVec3f(-sin(forceAngle - beltAngle - pi / 2), - 0, - -cos(forceAngle - beltAngle - pi / 2)))); + GuiTools::updatePlacement( + sep, + 0, + SbVec3f(-dia / 2 * sin(forceAngle - beltAngle), 0, -dia / 2 * cos(forceAngle - beltAngle)), + SbRotation( + SbVec3f(0, 1, 0), + SbVec3f(-sin(forceAngle - beltAngle - pi / 2), 0, -cos(forceAngle - beltAngle - pi / 2)) + ) + ); } } else if ((prop == &pcConstraint->BeltForce1) || (prop == &pcConstraint->BeltForce2)) { @@ -229,17 +225,11 @@ void ViewProviderFemConstraintPulley::updateData(const App::Property* prop) } const SoSeparator* sep = static_cast(pShapeSep->getChild(3)); - GuiTools::updatePlacement(sep, - 2, - SbVec3f(0, dia / 8 + dia / 2 * rat1, 0), - SbRotation()); + GuiTools::updatePlacement(sep, 2, SbVec3f(0, dia / 8 + dia / 2 * rat1, 0), SbRotation()); const SoSeparator* subsep = static_cast(sep->getChild(4)); GuiTools::updateArrow(subsep, 0, dia / 8 + dia / 2 * rat1, dia / 8); sep = static_cast(pShapeSep->getChild(4)); - GuiTools::updatePlacement(sep, - 2, - SbVec3f(0, dia / 8 + dia / 2 * rat2, 0), - SbRotation()); + GuiTools::updatePlacement(sep, 2, SbVec3f(0, dia / 8 + dia / 2 * rat2, 0), SbRotation()); subsep = static_cast(sep->getChild(4)); GuiTools::updateArrow(subsep, 0, dia / 8 + dia / 2 * rat2, dia / 8); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPyImp.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintPyImp.cpp index 745118ebe0..2eb9c55952 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPyImp.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPyImp.cpp @@ -58,8 +58,8 @@ Py::Object ViewProviderFemConstraintPy::getSymbolNode() const try { SoSeparator* sep = getViewProviderFemConstraintPtr()->getSymbolSeparator(); if (sep) { - PyObject* Ptr = - Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", sep, 1); + PyObject* Ptr + = Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", sep, 1); sep->ref(); return Py::Object(Ptr, true); @@ -78,8 +78,8 @@ Py::Object ViewProviderFemConstraintPy::getExtraSymbolNode() const try { SoSeparator* sep = getViewProviderFemConstraintPtr()->getExtraSymbolSeparator(); if (sep) { - PyObject* Ptr = - Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", sep, 1); + PyObject* Ptr + = Base::Interpreter().createSWIGPointerObj("pivy.coin", "_p_SoSeparator", sep, 1); sep->ref(); return Py::Object(Ptr, true); diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintRigidBody.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintRigidBody.cpp index c02525b281..a0923cdfe0 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintRigidBody.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintRigidBody.cpp @@ -33,8 +33,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintRigidBody, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintRigidBody, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintRigidBody::ViewProviderFemConstraintRigidBody() diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp index 1e570d5b30..8746607590 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp @@ -30,8 +30,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintSpring, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintSpring, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintSpring::ViewProviderFemConstraintSpring() { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h index aeff53484b..34f3350ca7 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h @@ -29,8 +29,7 @@ namespace FemGui { -class FemGuiExport ViewProviderFemConstraintSpring - : public FemGui::ViewProviderFemConstraintOnBoundary +class FemGuiExport ViewProviderFemConstraintSpring: public FemGui::ViewProviderFemConstraintOnBoundary { PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintSpring); diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp index 56278039ce..d26107d217 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp @@ -31,8 +31,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintTemperature, - FemGui::ViewProviderFemConstraintOnBoundary) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraintTemperature, FemGui::ViewProviderFemConstraintOnBoundary) ViewProviderFemConstraintTemperature::ViewProviderFemConstraintTemperature() { diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp index 800cbf7c18..0b423112a6 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp @@ -100,9 +100,11 @@ void ViewProviderFemConstraintTransform::updateData(const App::Property* prop) ViewProviderFemConstraint::updateData(prop); } -void ViewProviderFemConstraintTransform::transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const +void ViewProviderFemConstraintTransform::transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat +) const { auto obj = this->getObject(); @@ -114,16 +116,20 @@ void ViewProviderFemConstraintTransform::transformSymbol(const Base::Vector3d& p rot.getValue(axis, angle); float s = obj->getScaleFactor(); - mat.setTransform(SbVec3f(point.x, point.y, point.z), - SbRotation(SbVec3f(axis.x, axis.y, axis.z), angle), - SbVec3f(s, s, s)); + mat.setTransform( + SbVec3f(point.x, point.y, point.z), + SbRotation(SbVec3f(axis.x, axis.y, axis.z), angle), + SbVec3f(s, s, s) + ); } else if (transType == "Cylindrical") { float s = obj->getScaleFactor(); - mat.setTransform(SbVec3f(point.x, point.y, point.z), - SbRotation(SbVec3f(0, 1, 0), SbVec3f(normal.x, normal.y, normal.z)), - SbVec3f(s, s, s)); + mat.setTransform( + SbVec3f(point.x, point.y, point.z), + SbRotation(SbVec3f(0, 1, 0), SbVec3f(normal.x, normal.y, normal.z)), + SbVec3f(s, s, s) + ); } } @@ -138,9 +144,11 @@ void ViewProviderFemConstraintTransform::transformExtraSymbol() const float s = obj->getScaleFactor(); SbMatrix mat; - mat.setTransform(SbVec3f(point.x, point.y, point.z), - SbRotation(SbVec3f(0, 1, 0), SbVec3f(axis.x, axis.y, axis.z)), - SbVec3f(s, s, s)); + mat.setTransform( + SbVec3f(point.x, point.y, point.z), + SbRotation(SbVec3f(0, 1, 0), SbVec3f(axis.x, axis.y, axis.z)), + SbVec3f(s, s, s) + ); trans->setMatrix(mat); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h index 5b356473f2..86b933393a 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h @@ -43,9 +43,11 @@ public: protected: bool setEdit(int ModNum) override; - void transformSymbol(const Base::Vector3d& point, - const Base::Vector3d& normal, - SbMatrix& mat) const override; + void transformSymbol( + const Base::Vector3d& point, + const Base::Vector3d& normal, + SbMatrix& mat + ) const override; void transformExtraSymbol() const override; }; diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp index 7c1eaa4144..f5e03f5134 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp @@ -67,34 +67,38 @@ struct FemFace return Base::Vector3d(Nodes[0]->X(), Nodes[0]->Y(), Nodes[0]->Z()); } - Base::Vector3d set(short size, - const SMDS_MeshElement* element, - unsigned short id, - short faceNo, - const SMDS_MeshNode* n1, - const SMDS_MeshNode* n2, - const SMDS_MeshNode* n3, - const SMDS_MeshNode* n4 = nullptr, - const SMDS_MeshNode* n5 = nullptr, - const SMDS_MeshNode* n6 = nullptr, - const SMDS_MeshNode* n7 = nullptr, - const SMDS_MeshNode* n8 = nullptr); + Base::Vector3d set( + short size, + const SMDS_MeshElement* element, + unsigned short id, + short faceNo, + const SMDS_MeshNode* n1, + const SMDS_MeshNode* n2, + const SMDS_MeshNode* n3, + const SMDS_MeshNode* n4 = nullptr, + const SMDS_MeshNode* n5 = nullptr, + const SMDS_MeshNode* n6 = nullptr, + const SMDS_MeshNode* n7 = nullptr, + const SMDS_MeshNode* n8 = nullptr + ); bool isSameFace(FemFace& face); }; -Base::Vector3d FemFace::set(short size, - const SMDS_MeshElement* element, - unsigned short id, - short faceNo, - const SMDS_MeshNode* n1, - const SMDS_MeshNode* n2, - const SMDS_MeshNode* n3, - const SMDS_MeshNode* n4, - const SMDS_MeshNode* n5, - const SMDS_MeshNode* n6, - const SMDS_MeshNode* n7, - const SMDS_MeshNode* n8) +Base::Vector3d FemFace::set( + short size, + const SMDS_MeshElement* element, + unsigned short id, + short faceNo, + const SMDS_MeshNode* n1, + const SMDS_MeshNode* n2, + const SMDS_MeshNode* n3, + const SMDS_MeshNode* n4, + const SMDS_MeshNode* n5, + const SMDS_MeshNode* n6, + const SMDS_MeshNode* n7, + const SMDS_MeshNode* n8 +) { Nodes[0] = n1; Nodes[1] = n2; @@ -200,21 +204,21 @@ ViewProviderFemMesh::ViewProviderFemMesh() ADD_PROPERTY(ShowInner, (false)); ADD_PROPERTY(MaxFacesShowInner, (50000)); - ADD_PROPERTY_TYPE(ColorMode, - ("Overall"), - "Display Options", - App::Prop_None, - "Set the color mode"); - ADD_PROPERTY_TYPE(NodeColorArray, - (PointColor.getValue()), - "Object Style", - App::Prop_Hidden, - "Node diffuse color array"); - ADD_PROPERTY_TYPE(ElementColorArray, - (ShapeAppearance.getDiffuseColor()), - "Object Style", - App::Prop_Hidden, - "Node diffuse color array"); + ADD_PROPERTY_TYPE(ColorMode, ("Overall"), "Display Options", App::Prop_None, "Set the color mode"); + ADD_PROPERTY_TYPE( + NodeColorArray, + (PointColor.getValue()), + "Object Style", + App::Prop_Hidden, + "Node diffuse color array" + ); + ADD_PROPERTY_TYPE( + ElementColorArray, + (ShapeAppearance.getDiffuseColor()), + "Object Style", + App::Prop_Hidden, + "Node diffuse color array" + ); suppressibleExt.initExtension(this); @@ -379,15 +383,17 @@ void ViewProviderFemMesh::updateData(const App::Property* prop) ViewProviderFEMMeshBuilder builder; resetColorByNodeId(); resetDisplacementByNodeId(); - builder.createMesh(prop, - pcCoords, - pcFaces, - pcLines, - vFaceElementIdx, - vNodeElementIdx, - onlyEdges, - ShowInner.getValue(), - MaxFacesShowInner.getValue()); + builder.createMesh( + prop, + pcCoords, + pcFaces, + pcLines, + vFaceElementIdx, + vNodeElementIdx, + onlyEdges, + ShowInner.getValue(), + MaxFacesShowInner.getValue() + ); } Gui::ViewProviderGeometryObject::updateData(prop); } @@ -424,15 +430,17 @@ void ViewProviderFemMesh::onChanged(const App::Property* prop) else if (prop == &ShowInner) { // recalc mesh with new settings ViewProviderFEMMeshBuilder builder; - builder.createMesh(&(static_cast(this->pcObject)->FemMesh), - pcCoords, - pcFaces, - pcLines, - vFaceElementIdx, - vNodeElementIdx, - onlyEdges, - ShowInner.getValue(), - MaxFacesShowInner.getValue()); + builder.createMesh( + &(static_cast(this->pcObject)->FemMesh), + pcCoords, + pcFaces, + pcLines, + vFaceElementIdx, + vNodeElementIdx, + onlyEdges, + ShowInner.getValue(), + MaxFacesShowInner.getValue() + ); } else if (prop == &LineWidth) { pcDrawStyle->lineWidth = LineWidth.getValue(); @@ -453,8 +461,7 @@ void ViewProviderFemMesh::onChanged(const App::Property* prop) matchTransparency(); setMaterialOverall(); } - else if ((prop == &ElementColorArray || prop == &ShapeAppearance) - && ColorMode.getValue() == 1) { + else if ((prop == &ElementColorArray || prop == &ShapeAppearance) && ColorMode.getValue() == 1) { matchTransparency(); setMaterialByColorArray(&ElementColorArray, vFaceElementIdx); } @@ -550,10 +557,8 @@ std::set ViewProviderFemMesh::getHighlightNodes() const void ViewProviderFemMesh::setHighlightNodes(const std::set& HighlightedNodes) { if (!HighlightedNodes.empty()) { - const SMESHDS_Mesh* data = static_cast(this->pcObject) - ->FemMesh.getValue() - .getSMesh() - ->GetMeshDS(); + const SMESHDS_Mesh* data + = static_cast(this->pcObject)->FemMesh.getValue().getSMesh()->GetMeshDS(); pcAnoCoords->point.setNum(HighlightedNodes.size()); SbVec3f* verts = pcAnoCoords->point.startEditing(); @@ -573,9 +578,7 @@ void ViewProviderFemMesh::setHighlightNodes(const std::set& HighlightedNod // save the node ids vHighlightedIdx.clear(); - vHighlightedIdx.insert(vHighlightedIdx.end(), - HighlightedNodes.begin(), - HighlightedNodes.end()); + vHighlightedIdx.insert(vHighlightedIdx.end(), HighlightedNodes.begin(), HighlightedNodes.end()); } else { pcAnoCoords->point.setNum(0); @@ -612,8 +615,10 @@ void ViewProviderFemMesh::setDisplacementByNodeId(const std::map& NodeIds, - const std::vector& NodeDisps) +void ViewProviderFemMesh::setDisplacementByNodeId( + const std::vector& NodeIds, + const std::vector& NodeDisps +) { long startId = *(std::min_element(NodeIds.begin(), NodeIds.end())); long endId = *(std::max_element(NodeIds.begin(), NodeIds.end())); @@ -630,7 +635,8 @@ void ViewProviderFemMesh::setDisplacementByNodeId(const std::vector& NodeI void ViewProviderFemMesh::setDisplacementByNodeIdHelper( const std::vector& DispVector, - long startId) + long startId +) { DisplacementVector.resize(vNodeElementIdx.size()); int i = 0; @@ -678,8 +684,10 @@ void ViewProviderFemMesh::applyDisplacementToNodes(double factor) DisplacementFactor = factor; } -void ViewProviderFemMesh::setColorByNodeId(const std::vector& NodeIds, - const std::vector& NodeColors) +void ViewProviderFemMesh::setColorByNodeId( + const std::vector& NodeIds, + const std::vector& NodeColors +) { long endId = *(std::max_element(NodeIds.begin(), NodeIds.end())); @@ -716,14 +724,14 @@ void ViewProviderFemMesh::resetColorByNodeId() NodeColorArray.setValue(c); } -void ViewProviderFemMesh::setColorByNodeId( - const std::map, Base::Color>& elemColorMap) +void ViewProviderFemMesh::setColorByNodeId(const std::map, Base::Color>& elemColorMap) { setColorByIdHelper(elemColorMap, vNodeElementIdx, 0, NodeColorArray); } void ViewProviderFemMesh::setColorByElementId( - const std::map, Base::Color>& elemColorMap) + const std::map, Base::Color>& elemColorMap +) { setColorByIdHelper(elemColorMap, vFaceElementIdx, 3, ElementColorArray); } @@ -732,7 +740,8 @@ void ViewProviderFemMesh::setColorByIdHelper( const std::map, Base::Color>& elemColorMap, const std::vector& vElementIdx, int rShift, - App::PropertyColorList& prop) + App::PropertyColorList& prop +) { std::vector vecColor(vElementIdx.size()); std::map colorMap; @@ -744,8 +753,7 @@ void ViewProviderFemMesh::setColorByIdHelper( Base::Color baseDif = ShapeAppearance.getDiffuseColor(); int i = 0; - for (std::vector::const_iterator it = vElementIdx.begin(); - it != vElementIdx.end(); + for (std::vector::const_iterator it = vElementIdx.begin(); it != vElementIdx.end(); ++it, i++) { unsigned long ElemIdx = ((*it) >> rShift); const std::map::const_iterator pos = colorMap.find(ElemIdx); @@ -786,7 +794,8 @@ void ViewProviderFemMesh::setMaterialOverall() const void ViewProviderFemMesh::setMaterialByColorArray( const App::PropertyColorList* prop, - const std::vector& vElementIdx) const + const std::vector& vElementIdx +) const { const App::Material& baseMat = ShapeAppearance[0]; Base::Color baseDif = baseMat.diffuseColor; @@ -868,8 +877,7 @@ void ViewProviderFemMesh::resetColorByElementId() // ---------------------------------------------------------------------------- -void ViewProviderFEMMeshBuilder::buildNodes(const App::Property* prop, - std::vector& nodes) const +void ViewProviderFEMMeshBuilder::buildNodes(const App::Property* prop, std::vector& nodes) const { SoCoordinate3* pcPointsCoord = nullptr; SoIndexedFaceSet* pcFaces = nullptr; @@ -895,15 +903,17 @@ void ViewProviderFEMMeshBuilder::buildNodes(const App::Property* prop, std::vector vFaceElementIdx; std::vector vNodeElementIdx; bool onlyEdges; - createMesh(prop, - pcPointsCoord, - pcFaces, - pcLines, - vFaceElementIdx, - vNodeElementIdx, - onlyEdges, - false, - 0); + createMesh( + prop, + pcPointsCoord, + pcFaces, + pcLines, + vFaceElementIdx, + vNodeElementIdx, + onlyEdges, + false, + 0 + ); } } @@ -923,15 +933,17 @@ inline unsigned long ElemFold(unsigned long Element, unsigned long FaceNbr) return t2; } -void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, - SoCoordinate3* coords, - SoIndexedFaceSet* faces, - SoIndexedLineSet* lines, - std::vector& vFaceElementIdx, - std::vector& vNodeElementIdx, - bool& onlyEdges, - bool ShowInner, - int MaxFacesShowInner) const +void ViewProviderFEMMeshBuilder::createMesh( + const App::Property* prop, + SoCoordinate3* coords, + SoIndexedFaceSet* faces, + SoIndexedLineSet* lines, + std::vector& vFaceElementIdx, + std::vector& vNodeElementIdx, + bool& onlyEdges, + bool ShowInner, + int MaxFacesShowInner +) const { const Fem::PropertyFemMesh* mesh = static_cast(prop); @@ -950,7 +962,8 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } Base::TimeElapsed Start; Base::Console().log( - "Start: ViewProviderFEMMeshBuilder::createMesh() =================================\n"); + "Start: ViewProviderFEMMeshBuilder::createMesh() =================================\n" + ); const SMDS_MeshInfo& info = data->GetMeshInfo(); int numTria = info.NbTriangles(); @@ -967,8 +980,8 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, int numTries; if (ShowFaces) { - numTries = - numTria + numQuad /*+numPoly*/ + numTetr * 4 + numHexa * 6 + numPyrd * 5 + numPris * 5; + numTries = numTria + numQuad /*+numPoly*/ + numTetr * 4 + numHexa * 6 + numPyrd * 5 + + numPris * 5; } else { numTries = numTetr * 4 + numHexa * 6 + numPyrd * 5 + numPris * 5; @@ -985,9 +998,11 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, std::vector facesHelper(numTries); - Base::Console().log(" %f: Start build up %i face helper\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()), - facesHelper.size()); + Base::Console().log( + " %f: Start build up %i face helper\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()), + facesHelper.size() + ); Base::BoundBox3d BndBox; int i = 0; @@ -1001,57 +1016,74 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, switch (num) { case 3: // tria3 face = N1, N2, N3 - BndBox.Add(facesHelper[i++].set(3, - aFace, - aFace->GetID(), - 0, - aFace->GetNode(0), - aFace->GetNode(1), - aFace->GetNode(2))); + BndBox.Add( + facesHelper[i++].set( + 3, + aFace, + aFace->GetID(), + 0, + aFace->GetNode(0), + aFace->GetNode(1), + aFace->GetNode(2) + ) + ); break; case 4: // quad4 face = N1, N2, N3, N4 - BndBox.Add(facesHelper[i++].set(4, - aFace, - aFace->GetID(), - 0, - aFace->GetNode(0), - aFace->GetNode(1), - aFace->GetNode(2), - aFace->GetNode(3))); + BndBox.Add( + facesHelper[i++].set( + 4, + aFace, + aFace->GetID(), + 0, + aFace->GetNode(0), + aFace->GetNode(1), + aFace->GetNode(2), + aFace->GetNode(3) + ) + ); break; case 6: // tria6 face = N1, N4, N2, N5, N3, N6 - BndBox.Add(facesHelper[i++].set(6, - aFace, - aFace->GetID(), - 0, - aFace->GetNode(0), - aFace->GetNode(3), - aFace->GetNode(1), - aFace->GetNode(4), - aFace->GetNode(2), - aFace->GetNode(5))); + BndBox.Add( + facesHelper[i++].set( + 6, + aFace, + aFace->GetID(), + 0, + aFace->GetNode(0), + aFace->GetNode(3), + aFace->GetNode(1), + aFace->GetNode(4), + aFace->GetNode(2), + aFace->GetNode(5) + ) + ); break; case 8: // quad8 face = N1, N5, N2, N6, N3, N7, N4, N8 - BndBox.Add(facesHelper[i++].set(8, - aFace, - aFace->GetID(), - 0, - aFace->GetNode(0), - aFace->GetNode(4), - aFace->GetNode(1), - aFace->GetNode(5), - aFace->GetNode(2), - aFace->GetNode(6), - aFace->GetNode(3), - aFace->GetNode(7))); + BndBox.Add( + facesHelper[i++].set( + 8, + aFace, + aFace->GetID(), + 0, + aFace->GetNode(0), + aFace->GetNode(4), + aFace->GetNode(1), + aFace->GetNode(5), + aFace->GetNode(2), + aFace->GetNode(6), + aFace->GetNode(3), + aFace->GetNode(7) + ) + ); break; default: // unknown face type throw std::runtime_error( - "Node count not supported by ViewProviderFemMesh, [3|4|6|8] are allowed"); + "Node count not supported by ViewProviderFemMesh, [3|4|6|8] are allowed" + ); } } } @@ -1071,34 +1103,50 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 2 = N1, N4, N2 // face 3 = N2, N4, N3 // face 4 = N3, N4, N1 - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(1), - aVol->GetNode(2))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(0), - aVol->GetNode(3), - aVol->GetNode(1))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(1), - aVol->GetNode(3), - aVol->GetNode(2))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(2), - aVol->GetNode(3), - aVol->GetNode(0))); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(1), + aVol->GetNode(2) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(0), + aVol->GetNode(3), + aVol->GetNode(1) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(1), + aVol->GetNode(3), + aVol->GetNode(2) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(2), + aVol->GetNode(3), + aVol->GetNode(0) + ) + ); break; // pyra5 volume case 5: @@ -1107,42 +1155,62 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 3 = N2, N5, N3 // face 4 = N3, N5, N4 // face 5 = N4, N5, N1 - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(1), - aVol->GetNode(2), - aVol->GetNode(3))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(0), - aVol->GetNode(4), - aVol->GetNode(1))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(1), - aVol->GetNode(4), - aVol->GetNode(2))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(2), - aVol->GetNode(4), - aVol->GetNode(3))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 5, - aVol->GetNode(3), - aVol->GetNode(4), - aVol->GetNode(0))); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(1), + aVol->GetNode(2), + aVol->GetNode(3) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(0), + aVol->GetNode(4), + aVol->GetNode(1) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(1), + aVol->GetNode(4), + aVol->GetNode(2) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(2), + aVol->GetNode(4), + aVol->GetNode(3) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 5, + aVol->GetNode(3), + aVol->GetNode(4), + aVol->GetNode(0) + ) + ); break; // penta6 volume case 6: @@ -1151,44 +1219,64 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 3 = N1, N4, N5, N2 // face 4 = N2, N5, N6, N3 // face 5 = N3, N6, N4, N1 - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(1), - aVol->GetNode(2))); - BndBox.Add(facesHelper[i++].set(3, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(3), - aVol->GetNode(5), - aVol->GetNode(4))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(0), - aVol->GetNode(3), - aVol->GetNode(4), - aVol->GetNode(1))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(1), - aVol->GetNode(4), - aVol->GetNode(5), - aVol->GetNode(2))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 5, - aVol->GetNode(2), - aVol->GetNode(5), - aVol->GetNode(3), - aVol->GetNode(0))); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(1), + aVol->GetNode(2) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 3, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(3), + aVol->GetNode(5), + aVol->GetNode(4) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(0), + aVol->GetNode(3), + aVol->GetNode(4), + aVol->GetNode(1) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(1), + aVol->GetNode(4), + aVol->GetNode(5), + aVol->GetNode(2) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 5, + aVol->GetNode(2), + aVol->GetNode(5), + aVol->GetNode(3), + aVol->GetNode(0) + ) + ); break; // hexa8 volume case 8: @@ -1198,54 +1286,78 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 4 = N2, N6, N7, N3 // face 5 = N3, N7, N8, N4 // face 6 = N4, N8, N5, N1 - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(1), - aVol->GetNode(2), - aVol->GetNode(3))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(4), - aVol->GetNode(7), - aVol->GetNode(6), - aVol->GetNode(5))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(0), - aVol->GetNode(4), - aVol->GetNode(5), - aVol->GetNode(1))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(1), - aVol->GetNode(5), - aVol->GetNode(6), - aVol->GetNode(2))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 5, - aVol->GetNode(2), - aVol->GetNode(6), - aVol->GetNode(7), - aVol->GetNode(3))); - BndBox.Add(facesHelper[i++].set(4, - aVol, - aVol->GetID(), - 6, - aVol->GetNode(3), - aVol->GetNode(7), - aVol->GetNode(4), - aVol->GetNode(0))); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(1), + aVol->GetNode(2), + aVol->GetNode(3) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(4), + aVol->GetNode(7), + aVol->GetNode(6), + aVol->GetNode(5) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(0), + aVol->GetNode(4), + aVol->GetNode(5), + aVol->GetNode(1) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(1), + aVol->GetNode(5), + aVol->GetNode(6), + aVol->GetNode(2) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 5, + aVol->GetNode(2), + aVol->GetNode(6), + aVol->GetNode(7), + aVol->GetNode(3) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 4, + aVol, + aVol->GetID(), + 6, + aVol->GetNode(3), + aVol->GetNode(7), + aVol->GetNode(4), + aVol->GetNode(0) + ) + ); break; // tetra10 volume case 10: @@ -1253,46 +1365,62 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 2 = N1, N8, N4, N9, N2, N5 // face 3 = N2, N9, N4, N10, N3, N6 // face 4 = N3, N10, N4, N8, N1, N7 - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(4), - aVol->GetNode(1), - aVol->GetNode(5), - aVol->GetNode(2), - aVol->GetNode(6))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(0), - aVol->GetNode(7), - aVol->GetNode(3), - aVol->GetNode(8), - aVol->GetNode(1), - aVol->GetNode(4))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(1), - aVol->GetNode(8), - aVol->GetNode(3), - aVol->GetNode(9), - aVol->GetNode(2), - aVol->GetNode(5))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(2), - aVol->GetNode(9), - aVol->GetNode(3), - aVol->GetNode(7), - aVol->GetNode(0), - aVol->GetNode(6))); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(4), + aVol->GetNode(1), + aVol->GetNode(5), + aVol->GetNode(2), + aVol->GetNode(6) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(0), + aVol->GetNode(7), + aVol->GetNode(3), + aVol->GetNode(8), + aVol->GetNode(1), + aVol->GetNode(4) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(1), + aVol->GetNode(8), + aVol->GetNode(3), + aVol->GetNode(9), + aVol->GetNode(2), + aVol->GetNode(5) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(2), + aVol->GetNode(9), + aVol->GetNode(3), + aVol->GetNode(7), + aVol->GetNode(0), + aVol->GetNode(6) + ) + ); break; // pyra13 volume case 13: @@ -1301,58 +1429,78 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 3 = N2, N11, N5, N12, N3, N7 // face 4 = N3, N12, N5, N13, N4, N8 // face 5 = N4, N13, N5, N10, N1, N9 - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(5), - aVol->GetNode(1), - aVol->GetNode(6), - aVol->GetNode(2), - aVol->GetNode(7), - aVol->GetNode(3), - aVol->GetNode(8))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(0), - aVol->GetNode(9), - aVol->GetNode(4), - aVol->GetNode(10), - aVol->GetNode(1), - aVol->GetNode(5))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(1), - aVol->GetNode(10), - aVol->GetNode(4), - aVol->GetNode(11), - aVol->GetNode(2), - aVol->GetNode(6))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(2), - aVol->GetNode(11), - aVol->GetNode(4), - aVol->GetNode(12), - aVol->GetNode(3), - aVol->GetNode(7))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 5, - aVol->GetNode(3), - aVol->GetNode(12), - aVol->GetNode(4), - aVol->GetNode(9), - aVol->GetNode(0), - aVol->GetNode(8))); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(5), + aVol->GetNode(1), + aVol->GetNode(6), + aVol->GetNode(2), + aVol->GetNode(7), + aVol->GetNode(3), + aVol->GetNode(8) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(0), + aVol->GetNode(9), + aVol->GetNode(4), + aVol->GetNode(10), + aVol->GetNode(1), + aVol->GetNode(5) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(1), + aVol->GetNode(10), + aVol->GetNode(4), + aVol->GetNode(11), + aVol->GetNode(2), + aVol->GetNode(6) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(2), + aVol->GetNode(11), + aVol->GetNode(4), + aVol->GetNode(12), + aVol->GetNode(3), + aVol->GetNode(7) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 5, + aVol->GetNode(3), + aVol->GetNode(12), + aVol->GetNode(4), + aVol->GetNode(9), + aVol->GetNode(0), + aVol->GetNode(8) + ) + ); break; // penta15 volume case 15: @@ -1361,62 +1509,82 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 3 = N1, N13, N4, N10, N5, N14, N2, N7 // face 4 = N2, N14, N5, N11, N6, N15, N3, N8 // face 5 = N3, N15, N6, N12, N4, N13, N1, N9 - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(6), - aVol->GetNode(1), - aVol->GetNode(7), - aVol->GetNode(2), - aVol->GetNode(8))); - BndBox.Add(facesHelper[i++].set(6, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(3), - aVol->GetNode(11), - aVol->GetNode(5), - aVol->GetNode(10), - aVol->GetNode(4), - aVol->GetNode(9))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(0), - aVol->GetNode(12), - aVol->GetNode(3), - aVol->GetNode(9), - aVol->GetNode(4), - aVol->GetNode(13), - aVol->GetNode(1), - aVol->GetNode(6))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(1), - aVol->GetNode(13), - aVol->GetNode(4), - aVol->GetNode(10), - aVol->GetNode(5), - aVol->GetNode(14), - aVol->GetNode(2), - aVol->GetNode(7))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 5, - aVol->GetNode(2), - aVol->GetNode(14), - aVol->GetNode(5), - aVol->GetNode(11), - aVol->GetNode(3), - aVol->GetNode(12), - aVol->GetNode(0), - aVol->GetNode(8))); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(6), + aVol->GetNode(1), + aVol->GetNode(7), + aVol->GetNode(2), + aVol->GetNode(8) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 6, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(3), + aVol->GetNode(11), + aVol->GetNode(5), + aVol->GetNode(10), + aVol->GetNode(4), + aVol->GetNode(9) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(0), + aVol->GetNode(12), + aVol->GetNode(3), + aVol->GetNode(9), + aVol->GetNode(4), + aVol->GetNode(13), + aVol->GetNode(1), + aVol->GetNode(6) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(1), + aVol->GetNode(13), + aVol->GetNode(4), + aVol->GetNode(10), + aVol->GetNode(5), + aVol->GetNode(14), + aVol->GetNode(2), + aVol->GetNode(7) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 5, + aVol->GetNode(2), + aVol->GetNode(14), + aVol->GetNode(5), + aVol->GetNode(11), + aVol->GetNode(3), + aVol->GetNode(12), + aVol->GetNode(0), + aVol->GetNode(8) + ) + ); break; // hexa20 volume case 20: @@ -1426,83 +1594,109 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // face 4 = N2, N18, N6, N14, N7, N19, N3, N10 // face 5 = N3, N19, N7, N15, N8, N20, N4, N11 // face 6 = N4, N20, N8, N16, N5, N17, N1, N12 - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 1, - aVol->GetNode(0), - aVol->GetNode(8), - aVol->GetNode(1), - aVol->GetNode(9), - aVol->GetNode(2), - aVol->GetNode(10), - aVol->GetNode(3), - aVol->GetNode(11))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 2, - aVol->GetNode(4), - aVol->GetNode(15), - aVol->GetNode(7), - aVol->GetNode(14), - aVol->GetNode(6), - aVol->GetNode(13), - aVol->GetNode(5), - aVol->GetNode(12))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 3, - aVol->GetNode(0), - aVol->GetNode(16), - aVol->GetNode(4), - aVol->GetNode(12), - aVol->GetNode(5), - aVol->GetNode(17), - aVol->GetNode(1), - aVol->GetNode(8))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 4, - aVol->GetNode(1), - aVol->GetNode(17), - aVol->GetNode(5), - aVol->GetNode(13), - aVol->GetNode(6), - aVol->GetNode(18), - aVol->GetNode(2), - aVol->GetNode(9))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 5, - aVol->GetNode(2), - aVol->GetNode(18), - aVol->GetNode(6), - aVol->GetNode(14), - aVol->GetNode(7), - aVol->GetNode(19), - aVol->GetNode(3), - aVol->GetNode(10))); - BndBox.Add(facesHelper[i++].set(8, - aVol, - aVol->GetID(), - 6, - aVol->GetNode(3), - aVol->GetNode(19), - aVol->GetNode(7), - aVol->GetNode(15), - aVol->GetNode(4), - aVol->GetNode(16), - aVol->GetNode(0), - aVol->GetNode(11))); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 1, + aVol->GetNode(0), + aVol->GetNode(8), + aVol->GetNode(1), + aVol->GetNode(9), + aVol->GetNode(2), + aVol->GetNode(10), + aVol->GetNode(3), + aVol->GetNode(11) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 2, + aVol->GetNode(4), + aVol->GetNode(15), + aVol->GetNode(7), + aVol->GetNode(14), + aVol->GetNode(6), + aVol->GetNode(13), + aVol->GetNode(5), + aVol->GetNode(12) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 3, + aVol->GetNode(0), + aVol->GetNode(16), + aVol->GetNode(4), + aVol->GetNode(12), + aVol->GetNode(5), + aVol->GetNode(17), + aVol->GetNode(1), + aVol->GetNode(8) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 4, + aVol->GetNode(1), + aVol->GetNode(17), + aVol->GetNode(5), + aVol->GetNode(13), + aVol->GetNode(6), + aVol->GetNode(18), + aVol->GetNode(2), + aVol->GetNode(9) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 5, + aVol->GetNode(2), + aVol->GetNode(18), + aVol->GetNode(6), + aVol->GetNode(14), + aVol->GetNode(7), + aVol->GetNode(19), + aVol->GetNode(3), + aVol->GetNode(10) + ) + ); + BndBox.Add( + facesHelper[i++].set( + 8, + aVol, + aVol->GetID(), + 6, + aVol->GetNode(3), + aVol->GetNode(19), + aVol->GetNode(7), + aVol->GetNode(15), + aVol->GetNode(4), + aVol->GetNode(16), + aVol->GetNode(0), + aVol->GetNode(11) + ) + ); break; // unknown volume type default: - throw std::runtime_error("Node count not supported by ViewProviderFemMesh, " - "[4|5|6|8|10|13|15|20] are allowed"); + throw std::runtime_error( + "Node count not supported by ViewProviderFemMesh, " + "[4|5|6|8|10|13|15|20] are allowed" + ); } } } @@ -1510,8 +1704,10 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, if (FaceSize < MaxFacesShowInner) { - Base::Console().log(" %f: Start eliminate internal faces SIMPLE\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start eliminate internal faces SIMPLE\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // search for double (inside) faces and hide them if (!ShowInner) { @@ -1527,8 +1723,10 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } else { - Base::Console().log(" %f: Start eliminate internal faces GRID\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start eliminate internal faces GRID\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); BndBox.Enlarge(BndBox.CalcDiagonalLength() / 10000.0); // calculate grid properties double edge = pow(FaceSize, 1.0 / 3.0); @@ -1548,8 +1746,9 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, double Yln = BndBox.LengthY() / NbrY; double Zln = BndBox.LengthZ() / NbrZ; - std::vector Grid(static_cast(NbrX) * static_cast(NbrY) - * static_cast(NbrZ)); + std::vector Grid( + static_cast(NbrX) * static_cast(NbrY) * static_cast(NbrZ) + ); unsigned int iX = 0; @@ -1596,8 +1795,10 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } // if( FaceSize < 1000) - Base::Console().log(" %f: Start build up node map\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start build up node map\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // sort out double nodes and build up index map std::map mapNodeIndex; @@ -1629,8 +1830,10 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } } - Base::Console().log(" %f: Start set point vector\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start set point vector\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // set the point coordinates coords->point.setNum(mapNodeIndex.size()); @@ -1647,8 +1850,10 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, // count triangle size - Base::Console().log(" %f: Start count triangle size\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start count triangle size\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); int triangleCount = 0; for (int l = 0; l < FaceSize; l++) { if (!facesHelper[l].hide) { @@ -1668,7 +1873,8 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, default: throw std::runtime_error( "Face with unknown node count found, only display mode nodes is supported " - "for this element (tiangleCount)"); + "for this element (tiangleCount)" + ); } } } @@ -1703,8 +1909,10 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, } } - Base::Console().log(" %f: Start build up triangle vector\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start build up triangle vector\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // set the triangle face indices faces->coordIndex.setNum(4 * triangleCount); vFaceElementIdx.resize(triangleCount); @@ -3116,15 +3324,18 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, default: throw std::runtime_error( "Element with unknown node count found (may be not implemented), only " - "display mode nodes is supported for this element (NodeCount)"); + "display mode nodes is supported for this element (NodeCount)" + ); } } } faces->coordIndex.finishEditing(); - Base::Console().log(" %f: Start build up edge vector\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::Console().log( + " %f: Start build up edge vector\n", + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); // std::map > EdgeMap; // count edges int EdgeSize = 0; @@ -3140,8 +3351,7 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, for (std::map>::const_iterator it = EdgeMap.begin(); it != EdgeMap.end(); ++it) { - for (std::set::const_iterator it2 = it->second.begin(); it2 != it->second.end(); - ++it2) { + for (std::set::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2) { indices[index++] = it->first; indices[index++] = *it2; indices[index++] = -1; @@ -3153,7 +3363,8 @@ void ViewProviderFEMMeshBuilder::createMesh(const App::Property* prop, Base::Console().log( " %f: Finish =========================================================\n", - Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed())); + Base::TimeElapsed::diffTimeF(Start, Base::TimeElapsed()) + ); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.h b/src/Mod/Fem/Gui/ViewProviderFemMesh.h index 004c77317f..59b4f15a52 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.h +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.h @@ -45,15 +45,17 @@ public: ViewProviderFEMMeshBuilder() = default; ~ViewProviderFEMMeshBuilder() override = default; void buildNodes(const App::Property*, std::vector&) const override; - void createMesh(const App::Property*, - SoCoordinate3*, - SoIndexedFaceSet*, - SoIndexedLineSet*, - std::vector&, - std::vector&, - bool& edgeOnly, - bool ShowInner, - int MaxFacesShowInner) const; + void createMesh( + const App::Property*, + SoCoordinate3*, + SoIndexedFaceSet*, + SoIndexedLineSet*, + std::vector&, + std::vector&, + bool& edgeOnly, + bool ShowInner, + int MaxFacesShowInner + ) const; }; class FemGuiExport ViewProviderFemMesh: public Gui::ViewProviderGeometryObject @@ -115,15 +117,16 @@ public: /// set the color for each node void setColorByNodeId(const std::map, Base::Color>& NodeColorMap); - void setColorByNodeId(const std::vector& NodeIds, - const std::vector& NodeColors); + void setColorByNodeId(const std::vector& NodeIds, const std::vector& NodeColors); /// reset the view of the node colors void resetColorByNodeId(); /// set the displacement for each node void setDisplacementByNodeId(const std::map& NodeDispMap); - void setDisplacementByNodeId(const std::vector& NodeIds, - const std::vector& NodeDisps); + void setDisplacementByNodeId( + const std::vector& NodeIds, + const std::vector& NodeDisps + ); /// reset the view of the node displacement void resetDisplacementByNodeId(); /// reaply the node displacement with a certain factor and do a redraw @@ -153,12 +156,16 @@ protected: void setColorByNodeIdHelper(const std::vector&); void setDisplacementByNodeIdHelper(const std::vector& DispVector, long startId); - void setColorByIdHelper(const std::map, Base::Color>& elemColorMap, - const std::vector& vElementIdx, - int rShift, - App::PropertyColorList& prop); - void setMaterialByColorArray(const App::PropertyColorList* prop, - const std::vector& vElementIdx) const; + void setColorByIdHelper( + const std::map, Base::Color>& elemColorMap, + const std::vector& vElementIdx, + int rShift, + App::PropertyColorList& prop + ); + void setMaterialByColorArray( + const App::PropertyColorList* prop, + const std::vector& vElementIdx + ) const; void setMaterialOverall() const; /// index of elements to their triangles diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshShape.cpp b/src/Mod/Fem/Gui/ViewProviderFemMeshShape.cpp index 4796653b5e..95fc1e6909 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshShape.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshShape.cpp @@ -46,8 +46,7 @@ ViewProviderFemMeshShape::~ViewProviderFemMeshShape() = default; namespace Gui { -PROPERTY_SOURCE_TEMPLATE(FemGui::ViewProviderFemMeshShapeBasePython, - FemGui::ViewProviderFemMeshShapeBase) +PROPERTY_SOURCE_TEMPLATE(FemGui::ViewProviderFemMeshShapeBasePython, FemGui::ViewProviderFemMeshShapeBase) // explicit template instantiation template class FemGuiExport ViewProviderFeaturePythonT; diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h b/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h index 6301263426..d130157afd 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h @@ -57,8 +57,8 @@ public: ~ViewProviderFemMeshShape() override; }; -using ViewProviderFemMeshShapeBasePython = - Gui::ViewProviderFeaturePythonT; +using ViewProviderFemMeshShapeBasePython + = Gui::ViewProviderFeaturePythonT; } // namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.cpp b/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.cpp index 5aba6df24b..a9ed767922 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.cpp @@ -49,9 +49,7 @@ ViewProviderFemMeshShapeNetgen::ViewProviderFemMeshShapeNetgen() ViewProviderFemMeshShapeNetgen::~ViewProviderFemMeshShapeNetgen() = default; -void ViewProviderFemMeshShapeNetgen::setupContextMenu(QMenu* menu, - QObject* receiver, - const char* member) +void ViewProviderFemMeshShapeNetgen::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { QAction* act = menu->addAction(QObject::tr("Meshing"), receiver, member); act->setData(QVariant((int)ViewProvider::Default)); @@ -68,11 +66,12 @@ bool ViewProviderFemMeshShapeNetgen::setEdit(int ModNum) #else QMessageBox::critical( Gui::getMainWindow(), - QCoreApplication::translate("FemGui::ViewProviderFemMeshShapeNetgen", - "Meshing failure"), + QCoreApplication::translate("FemGui::ViewProviderFemMeshShapeNetgen", "Meshing failure"), QCoreApplication::translate( "FemGui::ViewProviderFemMeshShapeNetgen", - "The FEM module is built without NETGEN support. Meshing will not work!!!")); + "The FEM module is built without NETGEN support. Meshing will not work!!!" + ) + ); return false; #endif } diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp index 90fdd93a34..d6b6337102 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.cpp @@ -29,8 +29,7 @@ using namespace FemGui; -PROPERTY_SOURCE_WITH_EXTENSIONS(FemGui::ViewProviderFemPostBranchFilter, - FemGui::ViewProviderFemPostObject) +PROPERTY_SOURCE_WITH_EXTENSIONS(FemGui::ViewProviderFemPostBranchFilter, FemGui::ViewProviderFemPostObject) ViewProviderFemPostBranchFilter::ViewProviderFemPostBranchFilter() : Gui::ViewProviderGroupExtension() @@ -57,8 +56,10 @@ bool ViewProviderFemPostBranchFilter::acceptReorderingObjects() const return true; } -bool ViewProviderFemPostBranchFilter::canDragObjectToTarget(App::DocumentObject*, - App::DocumentObject* target) const +bool ViewProviderFemPostBranchFilter::canDragObjectToTarget( + App::DocumentObject*, + App::DocumentObject* target +) const { // allow drag only to other post groups diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.h b/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.h index 9f97b8e1b9..e54f51c252 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostBranchFilter.h @@ -52,8 +52,7 @@ protected: // change default group drag/drop behaviour slightly bool acceptReorderingObjects() const override; - bool canDragObjectToTarget(App::DocumentObject* obj, - App::DocumentObject* target) const override; + bool canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const override; // override, to not show/hide children as the parent is shown/hidden like normal groups void extensionHide() override {}; diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp index 38449a99aa..b4bc08f108 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp @@ -31,7 +31,7 @@ #include "ViewProviderFemPostFilterPy.h" #ifdef FC_USE_VTK_PYTHON -#include "TaskPostExtraction.h" +# include "TaskPostExtraction.h" #endif using namespace FemGui; @@ -50,8 +50,7 @@ std::vector ViewProviderFemPostFilterPythonBase::getDisplayModes() namespace Gui { -PROPERTY_SOURCE_TEMPLATE(FemGui::ViewProviderPostFilterPython, - FemGui::ViewProviderFemPostFilterPythonBase) +PROPERTY_SOURCE_TEMPLATE(FemGui::ViewProviderPostFilterPython, FemGui::ViewProviderFemPostFilterPythonBase) template<> PyObject* FemGui::ViewProviderPostFilterPython::getPyObject() @@ -103,9 +102,7 @@ void ViewProviderFemPostDataAlongLine::setupTaskDialog(TaskDlgPost* dlg) // data at point filter PROPERTY_SOURCE(FemGui::ViewProviderFemPostDataAtPoint, FemGui::ViewProviderFemPostObject) -App::PropertyFloatConstraint::Constraints ViewProviderFemPostDataAtPoint::sizeRange = {1.0, - 64.0, - 1.0}; +App::PropertyFloatConstraint::Constraints ViewProviderFemPostDataAtPoint::sizeRange = {1.0, 64.0, 1.0}; ViewProviderFemPostDataAtPoint::ViewProviderFemPostDataAtPoint() { @@ -171,8 +168,7 @@ void ViewProviderFemPostClip::setupTaskDialog(TaskDlgPost* dlg) // add the function box assert(dlg->getView() == this); - auto panel = - new TaskPostClip(this, &dlg->getView()->getObject()->Function); + auto panel = new TaskPostClip(this, &dlg->getView()->getObject()->Function); dlg->addTaskBox(panel->getIcon(), panel); // add the display options @@ -215,8 +211,7 @@ void ViewProviderFemPostCut::setupTaskDialog(TaskDlgPost* dlg) { // add the function box assert(dlg->getView() == this); - auto panel = - new TaskPostCut(this, &dlg->getView()->getObject()->Function); + auto panel = new TaskPostCut(this, &dlg->getView()->getObject()->Function); dlg->addTaskBox(panel->getIcon(), panel); // add the display options diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h index 82b7f16bf8..948089d961 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h @@ -50,8 +50,8 @@ public: // Viewprovider for the python filters -using ViewProviderPostFilterPython = - Gui::ViewProviderFeaturePythonT; +using ViewProviderPostFilterPython + = Gui::ViewProviderFeaturePythonT; // *************************************************************************** diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp index f4aba94c88..1ac22c0c26 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp @@ -70,7 +70,8 @@ void FunctionWidget::setViewProvider(ViewProviderFemPostFunction* view) m_view = view; m_object = view->getObject(); m_connection = m_object->getDocument()->signalChangedObject.connect( - std::bind(&FunctionWidget::onObjectsChanged, this, sp::_1, sp::_2)); + std::bind(&FunctionWidget::onObjectsChanged, this, sp::_1, sp::_2) + ); // NOLINTEND } @@ -114,7 +115,8 @@ void ViewProviderFemPostFunctionProvider::updateSize() } ViewProviderFemPostFunction* vp = static_cast( - Gui::Application::Instance->getViewProvider(it)); + Gui::Application::Instance->getViewProvider(it) + ); vp->AutoScaleFactorX.setValue(SizeX.getValue()); vp->AutoScaleFactorY.setValue(SizeY.getValue()); vp->AutoScaleFactorZ.setValue(SizeZ.getValue()); @@ -125,9 +127,7 @@ bool ViewProviderFemPostFunctionProvider::onDelete(const std::vectorgetDocument(), - "functions list"); + return ViewProviderFemAnalysis::checkSelectedChildren(objs, this->getDocument(), "functions list"); } bool ViewProviderFemPostFunctionProvider::canDelete(App::DocumentObject* obj) const @@ -150,21 +150,9 @@ ViewProviderFemPostFunction::ViewProviderFemPostFunction() , m_isDragging(false) , m_autoRecompute(false) { - ADD_PROPERTY_TYPE(AutoScaleFactorX, - (1), - "AutoScale", - App::Prop_Hidden, - "Automatic scaling factor"); - ADD_PROPERTY_TYPE(AutoScaleFactorY, - (1), - "AutoScale", - App::Prop_Hidden, - "Automatic scaling factor"); - ADD_PROPERTY_TYPE(AutoScaleFactorZ, - (1), - "AutoScale", - App::Prop_Hidden, - "Automatic scaling factor"); + ADD_PROPERTY_TYPE(AutoScaleFactorX, (1), "AutoScale", App::Prop_Hidden, "Automatic scaling factor"); + ADD_PROPERTY_TYPE(AutoScaleFactorY, (1), "AutoScale", App::Prop_Hidden, "Automatic scaling factor"); + ADD_PROPERTY_TYPE(AutoScaleFactorZ, (1), "AutoScale", App::Prop_Hidden, "Automatic scaling factor"); m_geometrySeperator = new SoSeparator(); m_geometrySeperator->ref(); @@ -232,8 +220,7 @@ SbBox3f ViewProviderFemPostFunction::getBoundingsOfView() const { SbBox3f box; Gui::Document* doc = this->getDocument(); - Gui::View3DInventor* view = - qobject_cast(doc->getViewOfViewProvider(this)); + Gui::View3DInventor* view = qobject_cast(doc->getViewOfViewProvider(this)); if (view) { Gui::View3DInventorViewer* viewer = view->getViewer(); box = viewer->getBoundingBox(); @@ -279,7 +266,8 @@ void ViewProviderFemPostFunction::dragStartCallback(void* data, SoDragger*) { // This is called when a manipulator is about to manipulating Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Edit Mirror")); + QT_TRANSLATE_NOOP("Command", "Edit Mirror") + ); static_cast(data)->m_isDragging = true; ViewProviderFemPostFunction* that = static_cast(data); @@ -368,9 +356,11 @@ void ViewProviderFemPostFunction::onChanged(const App::Property* prop) Gui::ViewProviderDocumentObject::onChanged(prop); if (m_autoscale) { - m_scale->scaleFactor = SbVec3f(AutoScaleFactorX.getValue(), - AutoScaleFactorY.getValue(), - AutoScaleFactorZ.getValue()); + m_scale->scaleFactor = SbVec3f( + AutoScaleFactorX.getValue(), + AutoScaleFactorY.getValue(), + AutoScaleFactorZ.getValue() + ); } } @@ -455,30 +445,42 @@ BoxWidget::BoxWidget() ui->width->setDecimals(UserDecimals); ui->height->setDecimals(UserDecimals); - connect(ui->centerX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &BoxWidget::centerChanged); - connect(ui->centerY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &BoxWidget::centerChanged); - connect(ui->centerZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &BoxWidget::centerChanged); - connect(ui->length, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &BoxWidget::lengthChanged); - connect(ui->width, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &BoxWidget::widthChanged); - connect(ui->height, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &BoxWidget::heightChanged); + connect( + ui->centerX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &BoxWidget::centerChanged + ); + connect( + ui->centerY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &BoxWidget::centerChanged + ); + connect( + ui->centerZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &BoxWidget::centerChanged + ); + connect( + ui->length, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &BoxWidget::lengthChanged + ); + connect( + ui->width, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &BoxWidget::widthChanged + ); + connect( + ui->height, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &BoxWidget::heightChanged + ); } BoxWidget::~BoxWidget() = default; @@ -536,9 +538,11 @@ void BoxWidget::onChange(const App::Property& p) void BoxWidget::centerChanged(double) { if (!blockObjectUpdates()) { - Base::Vector3d vec(ui->centerX->value().getValue(), - ui->centerY->value().getValue(), - ui->centerZ->value().getValue()); + Base::Vector3d vec( + ui->centerX->value().getValue(), + ui->centerY->value().getValue(), + ui->centerZ->value().getValue() + ); getObject()->Center.setValue(vec); } } @@ -606,9 +610,7 @@ void ViewProviderFemPostCylinderFunction::updateData(const App::Property* p) SbMatrix translate; SbRotation rot(SbVec3f(0.0, 0.0, 1.0), SbVec3f(axis.x, axis.y, axis.z)); - translate.setTransform(SbVec3f(trans.x, trans.y, trans.z), - rot, - SbVec3f(radius, radius, radius)); + translate.setTransform(SbVec3f(trans.x, trans.y, trans.z), rot, SbVec3f(radius, radius, radius)); getManipulator()->setMatrix(translate); } @@ -647,34 +649,48 @@ CylinderWidget::CylinderWidget() ui->axisY->setDecimals(UserDecimals); ui->axisZ->setDecimals(UserDecimals); - connect(ui->centerX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::centerChanged); - connect(ui->centerY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::centerChanged); - connect(ui->centerZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::centerChanged); - connect(ui->axisX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::axisChanged); - connect(ui->axisY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::axisChanged); - connect(ui->axisZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::axisChanged); - connect(ui->radius, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &CylinderWidget::radiusChanged); + connect( + ui->centerX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::centerChanged + ); + connect( + ui->centerY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::centerChanged + ); + connect( + ui->centerZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::centerChanged + ); + connect( + ui->axisX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::axisChanged + ); + connect( + ui->axisY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::axisChanged + ); + connect( + ui->axisZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::axisChanged + ); + connect( + ui->radius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CylinderWidget::radiusChanged + ); } CylinderWidget::~CylinderWidget() = default; @@ -725,9 +741,11 @@ void CylinderWidget::onChange(const App::Property& p) void CylinderWidget::centerChanged(double) { if (!blockObjectUpdates()) { - Base::Vector3d vec(ui->centerX->value().getValue(), - ui->centerY->value().getValue(), - ui->centerZ->value().getValue()); + Base::Vector3d vec( + ui->centerX->value().getValue(), + ui->centerY->value().getValue(), + ui->centerZ->value().getValue() + ); getObject()->Center.setValue(vec); } } @@ -735,9 +753,11 @@ void CylinderWidget::centerChanged(double) void CylinderWidget::axisChanged(double) { if (!blockObjectUpdates()) { - Base::Vector3d vec(ui->axisX->value().getValue(), - ui->axisY->value().getValue(), - ui->axisZ->value().getValue()); + Base::Vector3d vec( + ui->axisX->value().getValue(), + ui->axisY->value().getValue(), + ui->axisZ->value().getValue() + ); getObject()->Axis.setValue(vec); } } @@ -754,19 +774,13 @@ void CylinderWidget::radiusChanged(double) PROPERTY_SOURCE(FemGui::ViewProviderFemPostPlaneFunction, FemGui::ViewProviderFemPostFunction) // NOTE: The technical lower limit is at 1e-4 that the Coin3D manipulator can handle -static const App::PropertyFloatConstraint::Constraints scaleConstraint = { - 1e-4, - std::numeric_limits::max(), - 1.0}; +static const App::PropertyFloatConstraint::Constraints scaleConstraint + = {1e-4, std::numeric_limits::max(), 1.0}; ViewProviderFemPostPlaneFunction::ViewProviderFemPostPlaneFunction() : m_detectscale {true} { - ADD_PROPERTY_TYPE(Scale, - (10), - "Manipulator", - App::Prop_None, - "Scaling factor for the manipulator"); + ADD_PROPERTY_TYPE(Scale, (10), "Manipulator", App::Prop_None, "Scaling factor for the manipulator"); Scale.setConstraints(&scaleConstraint); sPixmap = "fem-post-geo-plane"; @@ -886,30 +900,42 @@ PlaneWidget::PlaneWidget() ui->normalY->setDecimals(UserDecimals); ui->normalZ->setDecimals(UserDecimals); - connect(ui->originX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PlaneWidget::originChanged); - connect(ui->originY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PlaneWidget::originChanged); - connect(ui->originZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PlaneWidget::originChanged); - connect(ui->normalX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PlaneWidget::normalChanged); - connect(ui->normalY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PlaneWidget::normalChanged); - connect(ui->normalZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PlaneWidget::normalChanged); + connect( + ui->originX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PlaneWidget::originChanged + ); + connect( + ui->originY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PlaneWidget::originChanged + ); + connect( + ui->originZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PlaneWidget::originChanged + ); + connect( + ui->normalX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PlaneWidget::normalChanged + ); + connect( + ui->normalY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PlaneWidget::normalChanged + ); + connect( + ui->normalZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PlaneWidget::normalChanged + ); } PlaneWidget::~PlaneWidget() = default; @@ -955,9 +981,11 @@ void PlaneWidget::onChange(const App::Property& p) void PlaneWidget::normalChanged(double) { if (!blockObjectUpdates()) { - Base::Vector3d vec(ui->normalX->value().getValue(), - ui->normalY->value().getValue(), - ui->normalZ->value().getValue()); + Base::Vector3d vec( + ui->normalX->value().getValue(), + ui->normalY->value().getValue(), + ui->normalZ->value().getValue() + ); getObject()->Normal.setValue(vec); } } @@ -965,9 +993,11 @@ void PlaneWidget::normalChanged(double) void PlaneWidget::originChanged(double) { if (!blockObjectUpdates()) { - Base::Vector3d vec(ui->originX->value().getValue(), - ui->originY->value().getValue(), - ui->originZ->value().getValue()); + Base::Vector3d vec( + ui->originX->value().getValue(), + ui->originY->value().getValue(), + ui->originZ->value().getValue() + ); getObject()->Origin.setValue(vec); } } @@ -1061,22 +1091,30 @@ SphereWidget::SphereWidget() ui->centerY->setDecimals(UserDecimals); ui->centerZ->setDecimals(UserDecimals); - connect(ui->centerX, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SphereWidget::centerChanged); - connect(ui->centerY, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SphereWidget::centerChanged); - connect(ui->centerZ, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SphereWidget::centerChanged); - connect(ui->radius, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SphereWidget::radiusChanged); + connect( + ui->centerX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SphereWidget::centerChanged + ); + connect( + ui->centerY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SphereWidget::centerChanged + ); + connect( + ui->centerZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SphereWidget::centerChanged + ); + connect( + ui->radius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SphereWidget::radiusChanged + ); } SphereWidget::~SphereWidget() = default; @@ -1120,9 +1158,11 @@ void SphereWidget::onChange(const App::Property& p) void SphereWidget::centerChanged(double) { if (!blockObjectUpdates()) { - Base::Vector3d vec(ui->centerX->value().getValue(), - ui->centerY->value().getValue(), - ui->centerZ->value().getValue()); + Base::Vector3d vec( + ui->centerX->value().getValue(), + ui->centerY->value().getValue(), + ui->centerZ->value().getValue() + ); getObject()->Center.setValue(vec); } } @@ -1196,20 +1236,20 @@ SoGroup* postCylinder() // top and bottom for (int i = 0; i < 2; ++i) { for (int j = 0; j < nCirc + 1; ++j) { - points->point.set1Value(idx, - SbVec3f(std::cos(2 * pi / nCirc * j), - std::sin(2 * pi / nCirc * j), - -h / 2. + h * i)); + points->point.set1Value( + idx, + SbVec3f(std::cos(2 * pi / nCirc * j), std::sin(2 * pi / nCirc * j), -h / 2. + h * i) + ); ++idx; } } // sides for (int i = 0; i < nSide; ++i) { for (int j = 0; j < 2; ++j) { - points->point.set1Value(idx, - SbVec3f(std::cos(2 * pi / nSide * i), - std::sin(2 * pi / nSide * i), - -h / 2. + h * j)); + points->point.set1Value( + idx, + SbVec3f(std::cos(2 * pi / nSide * i), std::sin(2 * pi / nSide * i), -h / 2. + h * j) + ); ++idx; } } @@ -1258,19 +1298,27 @@ SoGroup* postSphere() int idx = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 21; j++) { - points->point.set1Value(idx, - SbVec3f(std::sin(2 * pi / 20 * j) * std::cos(pi / 4 * i), - std::sin(2 * pi / 20 * j) * std::sin(pi / 4 * i), - std::cos(2 * pi / 20 * j))); + points->point.set1Value( + idx, + SbVec3f( + std::sin(2 * pi / 20 * j) * std::cos(pi / 4 * i), + std::sin(2 * pi / 20 * j) * std::sin(pi / 4 * i), + std::cos(2 * pi / 20 * j) + ) + ); ++idx; } } for (int i = 0; i < 4; i++) { for (int j = 0; j < 21; j++) { - points->point.set1Value(idx, - SbVec3f(std::sin(pi / 4 * i) * std::cos(2 * pi / 20 * j), - std::sin(pi / 4 * i) * std::sin(2 * pi / 20 * j), - std::cos(pi / 4 * i))); + points->point.set1Value( + idx, + SbVec3f( + std::sin(pi / 4 * i) * std::cos(2 * pi / 20 * j), + std::sin(pi / 4 * i) * std::sin(2 * pi / 20 * j), + std::cos(pi / 4 * i) + ) + ); ++idx; } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp index 829ee2899d..773145594f 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp @@ -64,7 +64,7 @@ #include "TaskPostBoxes.h" #ifdef FC_USE_VTK_PYTHON -#include "TaskPostExtraction.h" +# include "TaskPostExtraction.h" #endif #include "ViewProviderAnalysis.h" #include "ViewProviderFemPostObject.h" @@ -126,7 +126,8 @@ private: { // NOLINTBEGIN this->connectSelection = Gui::Selection().signalSelectionChanged.connect( - std::bind(&FemPostObjectSelectionObserver::selectionChanged, this, sp::_1)); + std::bind(&FemPostObjectSelectionObserver::selectionChanged, this, sp::_1) + ); // NOLINTEND } @@ -153,31 +154,29 @@ PROPERTY_SOURCE(FemGui::ViewProviderFemPostObject, Gui::ViewProviderDocumentObje ViewProviderFemPostObject::ViewProviderFemPostObject() { // initialize the properties - ADD_PROPERTY_TYPE(Field, - ((long)0), - "Coloring", - App::Prop_None, - "Select the field used for calculating the color"); - ADD_PROPERTY_TYPE(Component, - ((long)0), - "Coloring", - App::Prop_None, - "Select component to display"); - ADD_PROPERTY_TYPE(Transparency, - (0), - "Object Style", - App::Prop_None, - "Set object transparency."); - ADD_PROPERTY_TYPE(EdgeColor, - (0.0f, 0.0f, 0.0f), - "Object Style", - App::Prop_None, - "Set wireframe line color."); - ADD_PROPERTY_TYPE(PlainColorEdgeOnSurface, - (false), - "Object Style", - App::Prop_None, - "Use plain color for edges on surface."); + ADD_PROPERTY_TYPE( + Field, + ((long)0), + "Coloring", + App::Prop_None, + "Select the field used for calculating the color" + ); + ADD_PROPERTY_TYPE(Component, ((long)0), "Coloring", App::Prop_None, "Select component to display"); + ADD_PROPERTY_TYPE(Transparency, (0), "Object Style", App::Prop_None, "Set object transparency."); + ADD_PROPERTY_TYPE( + EdgeColor, + (0.0f, 0.0f, 0.0f), + "Object Style", + App::Prop_None, + "Set wireframe line color." + ); + ADD_PROPERTY_TYPE( + PlainColorEdgeOnSurface, + (false), + "Object Style", + App::Prop_None, + "Use plain color for edges on surface." + ); ADD_PROPERTY_TYPE(LineWidth, (1), "Object Style", App::Prop_None, "Set wireframe line width."); ADD_PROPERTY_TYPE(PointSize, (3), "Object Style", App::Prop_None, "Set node point size."); @@ -288,12 +287,14 @@ ViewProviderFemPostObject::~ViewProviderFemPostObject() Base::Console().destructorError( "ViewProviderFemPostObject", "ViewProviderFemPostObject destructor threw an exception: %s\n", - e.what()); + e.what() + ); } catch (...) { Base::Console().destructorError( "ViewProviderFemPostObject", - "ViewProviderFemPostObject destructor threw an unknown exception"); + "ViewProviderFemPostObject destructor threw an unknown exception" + ); } } @@ -331,8 +332,9 @@ void ViewProviderFemPostObject::attach(App::DocumentObject* pcObj) m_separator->addChild(m_faces); // Check for an already existing color bar - Gui::SoFCColorBar* pcBar = - static_cast(findFrontRootOfType(Gui::SoFCColorBar::getClassTypeId())); + Gui::SoFCColorBar* pcBar = static_cast( + findFrontRootOfType(Gui::SoFCColorBar::getClassTypeId()) + ); if (pcBar) { // Attach to the foreign color bar and delete our own bar pcBar->Attach(this); @@ -614,9 +616,11 @@ void ViewProviderFemPostObject::update3D() } } -void ViewProviderFemPostObject::WritePointData(vtkPoints* points, - vtkDataArray* normals, - vtkDataArray* tcoords) +void ViewProviderFemPostObject::WritePointData( + vtkPoints* points, + vtkDataArray* normals, + vtkDataArray* tcoords +) { Q_UNUSED(tcoords); @@ -1036,9 +1040,11 @@ void ViewProviderFemPostObject::onSelectionChanged(const Gui::SelectionChanges& } } -void ViewProviderFemPostObject::handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) +void ViewProviderFemPostObject::handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName +) { if (strcmp(propName, "Field") == 0 && strcmp(typeName, "App::PropertyEnumeration") == 0) { App::PropertyEnumeration field; diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.h b/src/Mod/Fem/Gui/ViewProviderFemPostObject.h index 13f1522ecd..1d6340d93d 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.h @@ -118,9 +118,11 @@ public: virtual void setupTaskDialog(TaskDlgPost* dlg); protected: - void handleChangedPropertyName(Base::XMLReader& reader, - const char* typeName, - const char* propName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* typeName, + const char* propName + ) override; bool setupPipeline(); void updateVtk(); diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp index 04ad1e3240..86cc4219af 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp @@ -75,9 +75,10 @@ void ViewProviderFemPostPipeline::updateFunctionSize() return; } - FemGui::ViewProviderFemPostFunctionProvider* vp = - static_cast( - Gui::Application::Instance->getViewProvider(fp)); + FemGui::ViewProviderFemPostFunctionProvider* vp + = static_cast( + Gui::Application::Instance->getViewProvider(fp) + ); if (obj->Data.getValue() && obj->Data.getValue()->IsA("vtkDataSet")) { vtkBoundingBox box = obj->getBoundingBox(); @@ -98,7 +99,8 @@ ViewProviderFemAnalysis* getAnalyzeView(App::DocumentObject* obj) if (Fem::FemAnalysis* analyze = freecad_cast(grp)) { analyzeView = freecad_cast( - Gui::Application::Instance->getViewProvider(analyze)); + Gui::Application::Instance->getViewProvider(analyze) + ); } return analyzeView; @@ -154,7 +156,8 @@ void ViewProviderFemPostPipeline::updateColorBars() for (auto& child : children) { if (child->Visibility.getValue()) { auto vpObject = dynamic_cast( - Gui::Application::Instance->getViewProvider(child)); + Gui::Application::Instance->getViewProvider(child) + ); if (vpObject) { vpObject->updateMaterial(); } @@ -202,9 +205,7 @@ void ViewProviderFemPostPipeline::transformField(char* FieldName, double FieldFa } } -void ViewProviderFemPostPipeline::scaleField(vtkDataSet* dset, - vtkDataArray* pdata, - double FieldFactor) +void ViewProviderFemPostPipeline::scaleField(vtkDataSet* dset, vtkDataArray* pdata, double FieldFactor) { // safe guard if (!dset || !pdata) { @@ -243,8 +244,10 @@ bool ViewProviderFemPostPipeline::acceptReorderingObjects() const return true; } -bool ViewProviderFemPostPipeline::canDragObjectToTarget(App::DocumentObject*, - App::DocumentObject* target) const +bool ViewProviderFemPostPipeline::canDragObjectToTarget( + App::DocumentObject*, + App::DocumentObject* target +) const { // allow drag only to other post groups diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h index 87f0bb7305..d55fb6184d 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h @@ -59,8 +59,7 @@ protected: // change default group drag/drop behaviour slightly bool acceptReorderingObjects() const override; - bool canDragObjectToTarget(App::DocumentObject* obj, - App::DocumentObject* target) const override; + bool canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const override; // override, to not show/hide children as the parent is shown/hidden like normal groups void extensionHide() override {}; diff --git a/src/Mod/Fem/Gui/ViewProviderSetElementNodes.cpp b/src/Mod/Fem/Gui/ViewProviderSetElementNodes.cpp index b0e8b975e5..9bf168a19e 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetElementNodes.cpp +++ b/src/Mod/Fem/Gui/ViewProviderSetElementNodes.cpp @@ -35,8 +35,9 @@ PROPERTY_SOURCE(FemGui::ViewProviderSetElementNodes, Gui::ViewProviderGeometryOb bool ViewProviderSetElementNodes::doubleClicked() { - Gui::TaskView::TaskDialog* dlg = - new TaskDlgCreateElementSet(getObject()); + Gui::TaskView::TaskDialog* dlg = new TaskDlgCreateElementSet( + getObject() + ); Gui::Control().showDialog(dlg); return true; } diff --git a/src/Mod/Fem/Gui/Workbench.cpp b/src/Mod/Fem/Gui/Workbench.cpp index 1773ace274..c5b0016333 100644 --- a/src/Mod/Fem/Gui/Workbench.cpp +++ b/src/Mod/Fem/Gui/Workbench.cpp @@ -204,18 +204,18 @@ Gui::ToolBarItem* Workbench::setupToolBars() const << "FEM_PostFilterCutFunction" << "FEM_PostFilterClipRegion" << "FEM_PostFilterContours" -#ifdef FC_USE_VTK_PYTHON +# ifdef FC_USE_VTK_PYTHON << "FEM_PostFilterGlyph" -#endif +# endif << "FEM_PostFilterDataAlongLine" << "FEM_PostFilterLinearizedStresses" << "FEM_PostFilterDataAtPoint" << "FEM_PostFilterCalculator" << "Separator" << "FEM_PostCreateFunctions" -#ifdef FC_USE_VTK_PYTHON +# ifdef FC_USE_VTK_PYTHON << "FEM_PostVisualization" -#endif +# endif ; #endif @@ -361,18 +361,18 @@ Gui::MenuItem* Workbench::setupMenuBar() const << "FEM_PostFilterCutFunction" << "FEM_PostFilterClipRegion" << "FEM_PostFilterContours" -#ifdef FC_USE_VTK_PYTHON +# ifdef FC_USE_VTK_PYTHON << "FEM_PostFilterGlyph" -#endif +# endif << "FEM_PostFilterDataAlongLine" << "FEM_PostFilterLinearizedStresses" << "FEM_PostFilterDataAtPoint" << "FEM_PostFilterCalculator" << "Separator" << "FEM_PostCreateFunctions" -#ifdef FC_USE_VTK_PYTHON +# ifdef FC_USE_VTK_PYTHON << "FEM_PostVisualization" -#endif +# endif ; #endif diff --git a/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls_ccx.py b/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls_ccx.py index e1004d8f1d..110579d8a7 100644 --- a/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls_ccx.py +++ b/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls_ccx.py @@ -1,211 +1,211 @@ -# *************************************************************************** -# * Copyright (c) 2020 Sudhanshu Dubey * -# * Copyright (c) 2021 Bernd Hahnebach * -# * Copyright (c) 2025 Jakub Michalski * -# * * -# * This file is part of the FreeCAD CAx development system. * -# * * -# * This program is free software; you can redistribute it and/or modify * -# * it under the terms of the GNU Lesser General Public License (LGPL) * -# * as published by the Free Software Foundation; either version 2 of * -# * the License, or (at your option) any later version. * -# * for detail see the LICENCE text file. * -# * * -# * This program 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 program; if not, write to the Free Software * -# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -# * USA * -# * * -# *************************************************************************** - -import sys -import FreeCAD -from FreeCAD import Rotation -from FreeCAD import Vector - -import Fem -import ObjectsFem - -from . import manager -from .manager import get_meshname -from .manager import init_doc - - -def get_information(): - return { - "name": "Electrostatics Capacitance Two Balls CCX", - "meshtype": "solid", - "meshelement": "Tet4", - "constraints": ["electrostatic potential, electric charge density"], - "solvers": ["calculix"], - "material": "fluid", - "equations": ["electrostatic"], - } - - -def get_explanation(header=""): - return ( - header - + """ - -To run the example from Python console use: -from femexamples.equation_electrostatics_capacitance_two_balls_ccx import setup -setup() - - -See forum topic post for similar Elmer example: -https://forum.freecad.org/viewtopic.php?f=18&t=41488&start=90#p412047 - -Analytical solution - capacitance 6.68e-12 F - -Source of analytical solution: -https://en.wikipedia.org/wiki/Capacitance#Capacitance_of_conductors_with_simple_shapes - -To obtain capacitance in postprocessing: -- cut the sphere in half with Region Clip Filter to see the results inside -- calculate the potential difference (you can use the legend of the Potential field) -- divide the total applied charge (1e-9 C) by this potential difference - -""" - ) - - -def setup(doc=None, solvertype="calculix"): - - # init FreeCAD document - if doc is None: - doc = init_doc() - - # explanation object - # just keep the following line and change text string in get_explanation method - manager.add_explanation_obj(doc, get_explanation(manager.get_header(get_information()))) - - # geometric objects - small_sphere1 = doc.addObject("Part::Sphere", "Small_Sphere1") - small_sphere1.Placement = FreeCAD.Placement(Vector(-300, 0, 0), Rotation(Vector(0, 0, 1), 0)) - small_sphere1.Radius = "100 mm" - - small_sphere2 = doc.addObject("Part::Sphere", "Small_Sphere2") - small_sphere2.Placement = FreeCAD.Placement(Vector(300, 0, 0), Rotation(Vector(0, 0, 1), 0)) - small_sphere2.Radius = "100 mm" - - fusion = doc.addObject("Part::MultiFuse", "Fusion") - fusion.Shapes = [small_sphere1, small_sphere2] - - large_sphere = doc.addObject("Part::Sphere", "Large_Sphere") - large_sphere.Radius = "1000 mm" - - geom_obj = doc.addObject("Part::Cut", "Cut") - geom_obj.Base = large_sphere - geom_obj.Tool = fusion - doc.recompute() - - if FreeCAD.GuiUp: - geom_obj.ViewObject.Transparency = 75 - geom_obj.ViewObject.Document.activeView().viewAxonometric() - geom_obj.ViewObject.Document.activeView().fitAll() - - # analysis - analysis = ObjectsFem.makeAnalysis(doc, "Analysis") - if FreeCAD.GuiUp: - import FemGui - - FemGui.setActiveAnalysis(analysis) - - # solver - if solvertype == "calculix": - solver_obj = ObjectsFem.makeSolverCalculiX(doc, "SolverCalculiX") - solver_obj.AnalysisType = "electromagnetic" - solver_obj.ElectromagneticMode = "electrostatic" - analysis.addObject(solver_obj) - else: - FreeCAD.Console.PrintWarning( - "Unknown or unsupported solver type: {}. " - "No solver object was created.\n".format(solvertype) - ) - - # material - material_obj = ObjectsFem.makeMaterialFluid(doc, "Air") - mat = material_obj.Material - mat["Name"] = "Air" - mat["Density"] = "1.204 kg/m^3" - mat["ThermalConductivity"] = "0.02587 W/m/K" - mat["ThermalExpansionCoefficient"] = "3.43e-3 1/K" - mat["SpecificHeat"] = "1.01 kJ/kg/K" - mat["ElectricalConductivity"] = "1e-12 S/m" - mat["RelativePermeability"] = "1.0" - # mat["RelativePermittivity"] = "1.00059" - mat["RelativePermittivity"] = "1.0" - material_obj.Material = mat - material_obj.References = [(geom_obj, "Solid1")] - analysis.addObject(material_obj) - - # constraint potential large sphere - name_pot1 = "ElectrostaticPotential1" - con_elect_pot1 = ObjectsFem.makeConstraintElectrostaticPotential(doc, name_pot1) - con_elect_pot1.References = [(geom_obj, "Face1")] - con_elect_pot1.Potential = "0.0 mV" - analysis.addObject(con_elect_pot1) - - # constraint electric charge density small sphere 1 - name_ch1 = "ElectricChargeDensity1" - con_elect_charge_dens1 = ObjectsFem.makeConstraintElectricChargeDensity(doc, name_ch1) - con_elect_charge_dens1.References = [(geom_obj, "Face2")] - con_elect_charge_dens1.Mode = "Interface" - con_elect_charge_dens1.InterfaceChargeDensity = "7.94e-9 C/m^2" - analysis.addObject(con_elect_charge_dens1) - - # constraint electric charge density small sphere 2 - name_ch2 = "ElectricChargeDensity2" - con_elect_charge_dens2 = ObjectsFem.makeConstraintElectricChargeDensity(doc, name_ch2) - con_elect_charge_dens2.References = [(geom_obj, "Face3")] - con_elect_charge_dens2.Mode = "Interface" - con_elect_charge_dens2.InterfaceChargeDensity = "-7.94e-9 C/m^2" - analysis.addObject(con_elect_charge_dens2) - - # mesh - femmesh_obj = analysis.addObject(ObjectsFem.makeMeshGmsh(doc, get_meshname()))[0] - femmesh_obj.Shape = geom_obj - femmesh_obj.SecondOrderLinear = False - femmesh_obj.CharacteristicLengthMax = "50 mm" - femmesh_obj.ViewObject.Visibility = False - - # mesh_region - mesh_region = ObjectsFem.makeMeshRegion(doc, femmesh_obj, name="MeshRegion") - mesh_region.CharacteristicLength = "20 mm" - mesh_region.References = [(geom_obj, "Face2"), (geom_obj, "Face3")] - mesh_region.ViewObject.Visibility = False - - # generate the mesh - from femmesh import gmshtools - - gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) - try: - error = gmsh_mesh.create_mesh() - except Exception: - error = sys.exc_info()[1] - FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") - if error: - # try to create from existing rough mesh - from .meshes.mesh_capacitance_two_balls_tetra10 import ( - create_nodes, - create_elements, - ) - - fem_mesh = Fem.FemMesh() - control = create_nodes(fem_mesh) - if not control: - FreeCAD.Console.PrintError("Error on creating nodes.\n") - control = create_elements(fem_mesh) - if not control: - FreeCAD.Console.PrintError("Error on creating elements.\n") - femmesh_obj.FemMesh = fem_mesh - - doc.recompute() - return doc - +# *************************************************************************** +# * Copyright (c) 2020 Sudhanshu Dubey * +# * Copyright (c) 2021 Bernd Hahnebach * +# * Copyright (c) 2025 Jakub Michalski * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** + +import sys +import FreeCAD +from FreeCAD import Rotation +from FreeCAD import Vector + +import Fem +import ObjectsFem + +from . import manager +from .manager import get_meshname +from .manager import init_doc + + +def get_information(): + return { + "name": "Electrostatics Capacitance Two Balls CCX", + "meshtype": "solid", + "meshelement": "Tet4", + "constraints": ["electrostatic potential, electric charge density"], + "solvers": ["calculix"], + "material": "fluid", + "equations": ["electrostatic"], + } + + +def get_explanation(header=""): + return ( + header + + """ + +To run the example from Python console use: +from femexamples.equation_electrostatics_capacitance_two_balls_ccx import setup +setup() + + +See forum topic post for similar Elmer example: +https://forum.freecad.org/viewtopic.php?f=18&t=41488&start=90#p412047 + +Analytical solution - capacitance 6.68e-12 F + +Source of analytical solution: +https://en.wikipedia.org/wiki/Capacitance#Capacitance_of_conductors_with_simple_shapes + +To obtain capacitance in postprocessing: +- cut the sphere in half with Region Clip Filter to see the results inside +- calculate the potential difference (you can use the legend of the Potential field) +- divide the total applied charge (1e-9 C) by this potential difference + +""" + ) + + +def setup(doc=None, solvertype="calculix"): + + # init FreeCAD document + if doc is None: + doc = init_doc() + + # explanation object + # just keep the following line and change text string in get_explanation method + manager.add_explanation_obj(doc, get_explanation(manager.get_header(get_information()))) + + # geometric objects + small_sphere1 = doc.addObject("Part::Sphere", "Small_Sphere1") + small_sphere1.Placement = FreeCAD.Placement(Vector(-300, 0, 0), Rotation(Vector(0, 0, 1), 0)) + small_sphere1.Radius = "100 mm" + + small_sphere2 = doc.addObject("Part::Sphere", "Small_Sphere2") + small_sphere2.Placement = FreeCAD.Placement(Vector(300, 0, 0), Rotation(Vector(0, 0, 1), 0)) + small_sphere2.Radius = "100 mm" + + fusion = doc.addObject("Part::MultiFuse", "Fusion") + fusion.Shapes = [small_sphere1, small_sphere2] + + large_sphere = doc.addObject("Part::Sphere", "Large_Sphere") + large_sphere.Radius = "1000 mm" + + geom_obj = doc.addObject("Part::Cut", "Cut") + geom_obj.Base = large_sphere + geom_obj.Tool = fusion + doc.recompute() + + if FreeCAD.GuiUp: + geom_obj.ViewObject.Transparency = 75 + geom_obj.ViewObject.Document.activeView().viewAxonometric() + geom_obj.ViewObject.Document.activeView().fitAll() + + # analysis + analysis = ObjectsFem.makeAnalysis(doc, "Analysis") + if FreeCAD.GuiUp: + import FemGui + + FemGui.setActiveAnalysis(analysis) + + # solver + if solvertype == "calculix": + solver_obj = ObjectsFem.makeSolverCalculiX(doc, "SolverCalculiX") + solver_obj.AnalysisType = "electromagnetic" + solver_obj.ElectromagneticMode = "electrostatic" + analysis.addObject(solver_obj) + else: + FreeCAD.Console.PrintWarning( + "Unknown or unsupported solver type: {}. " + "No solver object was created.\n".format(solvertype) + ) + + # material + material_obj = ObjectsFem.makeMaterialFluid(doc, "Air") + mat = material_obj.Material + mat["Name"] = "Air" + mat["Density"] = "1.204 kg/m^3" + mat["ThermalConductivity"] = "0.02587 W/m/K" + mat["ThermalExpansionCoefficient"] = "3.43e-3 1/K" + mat["SpecificHeat"] = "1.01 kJ/kg/K" + mat["ElectricalConductivity"] = "1e-12 S/m" + mat["RelativePermeability"] = "1.0" + # mat["RelativePermittivity"] = "1.00059" + mat["RelativePermittivity"] = "1.0" + material_obj.Material = mat + material_obj.References = [(geom_obj, "Solid1")] + analysis.addObject(material_obj) + + # constraint potential large sphere + name_pot1 = "ElectrostaticPotential1" + con_elect_pot1 = ObjectsFem.makeConstraintElectrostaticPotential(doc, name_pot1) + con_elect_pot1.References = [(geom_obj, "Face1")] + con_elect_pot1.Potential = "0.0 mV" + analysis.addObject(con_elect_pot1) + + # constraint electric charge density small sphere 1 + name_ch1 = "ElectricChargeDensity1" + con_elect_charge_dens1 = ObjectsFem.makeConstraintElectricChargeDensity(doc, name_ch1) + con_elect_charge_dens1.References = [(geom_obj, "Face2")] + con_elect_charge_dens1.Mode = "Interface" + con_elect_charge_dens1.InterfaceChargeDensity = "7.94e-9 C/m^2" + analysis.addObject(con_elect_charge_dens1) + + # constraint electric charge density small sphere 2 + name_ch2 = "ElectricChargeDensity2" + con_elect_charge_dens2 = ObjectsFem.makeConstraintElectricChargeDensity(doc, name_ch2) + con_elect_charge_dens2.References = [(geom_obj, "Face3")] + con_elect_charge_dens2.Mode = "Interface" + con_elect_charge_dens2.InterfaceChargeDensity = "-7.94e-9 C/m^2" + analysis.addObject(con_elect_charge_dens2) + + # mesh + femmesh_obj = analysis.addObject(ObjectsFem.makeMeshGmsh(doc, get_meshname()))[0] + femmesh_obj.Shape = geom_obj + femmesh_obj.SecondOrderLinear = False + femmesh_obj.CharacteristicLengthMax = "50 mm" + femmesh_obj.ViewObject.Visibility = False + + # mesh_region + mesh_region = ObjectsFem.makeMeshRegion(doc, femmesh_obj, name="MeshRegion") + mesh_region.CharacteristicLength = "20 mm" + mesh_region.References = [(geom_obj, "Face2"), (geom_obj, "Face3")] + mesh_region.ViewObject.Visibility = False + + # generate the mesh + from femmesh import gmshtools + + gmsh_mesh = gmshtools.GmshTools(femmesh_obj, analysis) + try: + error = gmsh_mesh.create_mesh() + except Exception: + error = sys.exc_info()[1] + FreeCAD.Console.PrintError(f"Unexpected error when creating mesh: {error}\n") + if error: + # try to create from existing rough mesh + from .meshes.mesh_capacitance_two_balls_tetra10 import ( + create_nodes, + create_elements, + ) + + fem_mesh = Fem.FemMesh() + control = create_nodes(fem_mesh) + if not control: + FreeCAD.Console.PrintError("Error on creating nodes.\n") + control = create_elements(fem_mesh) + if not control: + FreeCAD.Console.PrintError("Error on creating elements.\n") + femmesh_obj.FemMesh = fem_mesh + + doc.recompute() + return doc + diff --git a/src/Mod/Import/App/AppImportPy.cpp b/src/Mod/Import/App/AppImportPy.cpp index 7d04de09ad..bef8a15adb 100644 --- a/src/Mod/Import/App/AppImportPy.cpp +++ b/src/Mod/Import/App/AppImportPy.cpp @@ -23,14 +23,14 @@ ***************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include #include #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wextra-semi" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wextra-semi" #endif #include #include @@ -45,7 +45,7 @@ #include #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif #include @@ -81,28 +81,39 @@ public: Module() : Py::ExtensionModule("Import") { - add_keyword_method("open", - &Module::importer, - "open(string) -- Open the file and create a new document."); - add_keyword_method("insert", - &Module::importer, - "insert(string,string) -- Insert the file into the given document."); - add_keyword_method("export", - &Module::exporter, - "export(list,string) -- Export a list of objects into a single file."); - add_varargs_method("readDXF", - &Module::readDXF, - "readDXF(filename,[document,ignore_errors,option_source]): Imports a " - "DXF file into the given document. ignore_errors is True by default."); - add_varargs_method("writeDXFShape", - &Module::writeDXFShape, - "writeDXFShape([shape],filename [version,usePolyline,optionSource]): " - "Exports Shape(s) to a DXF file."); + add_keyword_method( + "open", + &Module::importer, + "open(string) -- Open the file and create a new document." + ); + add_keyword_method( + "insert", + &Module::importer, + "insert(string,string) -- Insert the file into the given document." + ); + add_keyword_method( + "export", + &Module::exporter, + "export(list,string) -- Export a list of objects into a single file." + ); + add_varargs_method( + "readDXF", + &Module::readDXF, + "readDXF(filename,[document,ignore_errors,option_source]): Imports a " + "DXF file into the given document. ignore_errors is True by default." + ); + add_varargs_method( + "writeDXFShape", + &Module::writeDXFShape, + "writeDXFShape([shape],filename [version,usePolyline,optionSource]): " + "Exports Shape(s) to a DXF file." + ); add_varargs_method( "writeDXFObject", &Module::writeDXFObject, "writeDXFObject([objects],filename [,version,usePolyline,optionSource]): Exports " - "DocumentObject(s) to a DXF file."); + "DocumentObject(s) to a DXF file." + ); initialize("This module is the Import module."); // register with Python } @@ -119,20 +130,22 @@ private: int mode = -1; static const std::array kwd_list {"name", "docName", "importHidden", "merge", "useLinkGroup", "mode", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "et|sO!O!O!i", - kwd_list, - "utf-8", - &Name, - &DocName, - &PyBool_Type, - &importHidden, - &PyBool_Type, - &merge, - &PyBool_Type, - &useLinkGroup, - &mode)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "et|sO!O!O!i", + kwd_list, + "utf-8", + &Name, + &DocName, + &PyBool_Type, + &importHidden, + &PyBool_Type, + &merge, + &PyBool_Type, + &useLinkGroup, + &mode + )) { throw Py::Exception(); } @@ -239,25 +252,23 @@ private: PyObject* pyexportHidden = Py_None; PyObject* pylegacy = Py_None; PyObject* pykeepPlacement = Py_None; - static const std::array kwd_list {"obj", - "name", - "exportHidden", - "legacy", - "keepPlacement", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "Oet|O!O!O!", - kwd_list, - &object, - "utf-8", - &Name, - &PyBool_Type, - &pyexportHidden, - &PyBool_Type, - &pylegacy, - &PyBool_Type, - &pykeepPlacement)) { + static const std::array + kwd_list {"obj", "name", "exportHidden", "legacy", "keepPlacement", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "Oet|O!O!O!", + kwd_list, + &object, + "utf-8", + &Name, + &PyBool_Type, + &pyexportHidden, + &PyBool_Type, + &pylegacy, + &PyBool_Type, + &pykeepPlacement + )) { throw Py::Exception(); } @@ -376,13 +387,7 @@ private: const char* optionSource = nullptr; std::string defaultOptions = "User parameter:BaseApp/Preferences/Mod/Draft"; bool IgnoreErrors = true; - if (!PyArg_ParseTuple(args.ptr(), - "et|sbs", - "utf-8", - &Name, - &DocName, - &IgnoreErrors, - &optionSource)) { + if (!PyArg_ParseTuple(args.ptr(), "et|sbs", "utf-8", &Name, &DocName, &IgnoreErrors, &optionSource)) { throw Py::Exception(); } @@ -448,15 +453,17 @@ private: PyObject* usePolyline = Py_False; // handle list of shapes - if (PyArg_ParseTuple(args.ptr(), - "O!et|iOs", - &(PyList_Type), - &shapeObj, - "utf-8", - &fname, - &versionParm, - &usePolyline, - &optionSource)) { + if (PyArg_ParseTuple( + args.ptr(), + "O!et|iOs", + &(PyList_Type), + &shapeObj, + "utf-8", + &fname, + &versionParm, + &usePolyline, + &optionSource + )) { filePath = std::string(fname); layerName = "none"; PyMem_Free(fname); @@ -484,8 +491,8 @@ private: Py::Sequence list(shapeObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { - Part::TopoShape* ts = - static_cast((*it).ptr())->getTopoShapePtr(); + Part::TopoShape* ts + = static_cast((*it).ptr())->getTopoShapePtr(); TopoDS_Shape shape = ts->getShape(); writer.exportShape(shape); } @@ -499,15 +506,17 @@ private: } PyErr_Clear(); - if (PyArg_ParseTuple(args.ptr(), - "O!et|iOs", - &(Part::TopoShapePy::Type), - &shapeObj, - "utf-8", - &fname, - &versionParm, - &usePolyline, - &optionSource)) { + if (PyArg_ParseTuple( + args.ptr(), + "O!et|iOs", + &(Part::TopoShapePy::Type), + &shapeObj, + "utf-8", + &fname, + &versionParm, + &usePolyline, + &optionSource + )) { filePath = std::string(fname); layerName = "none"; PyMem_Free(fname); @@ -559,15 +568,17 @@ private: bool polyOverride = false; PyObject* usePolyline = Py_False; - if (PyArg_ParseTuple(args.ptr(), - "O!et|iOs", - &(PyList_Type), - &docObj, - "utf-8", - &fname, - &versionParm, - &usePolyline, - &optionSource)) { + if (PyArg_ParseTuple( + args.ptr(), + "O!et|iOs", + &(PyList_Type), + &docObj, + "utf-8", + &fname, + &versionParm, + &usePolyline, + &optionSource + )) { filePath = std::string(fname); layerName = "none"; PyMem_Free(fname); @@ -597,8 +608,8 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::PartFeaturePy::Type))) { PyObject* item = (*it).ptr(); - App::DocumentObject* obj = - static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); layerName = obj->getNameInDocument(); writer.setLayerName(layerName); TopoDS_Shape shapeToExport; @@ -625,20 +636,22 @@ private: } PyErr_Clear(); - if (PyArg_ParseTuple(args.ptr(), - "O!et|iOs", - &(App::DocumentObjectPy::Type), - &docObj, - "utf-8", - &fname, - &versionParm, - &usePolyline, - &optionSource)) { + if (PyArg_ParseTuple( + args.ptr(), + "O!et|iOs", + &(App::DocumentObjectPy::Type), + &docObj, + "utf-8", + &fname, + &versionParm, + &usePolyline, + &optionSource + )) { filePath = std::string(fname); layerName = "none"; PyMem_Free(fname); - App::DocumentObject* obj = - static_cast(docObj)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(docObj)->getDocumentObjectPtr(); Base::Console().message("Imp:writeDXFObject - docObj: %s\n", obj->getNameInDocument()); if ((versionParm == 12) || (versionParm == 14)) { @@ -662,8 +675,8 @@ private: writer.setPolyOverride(polyOverride); writer.setLayerName(layerName); writer.init(); - App::DocumentObject* obj = - static_cast(docObj)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(docObj)->getDocumentObjectPtr(); layerName = obj->getNameInDocument(); writer.setLayerName(layerName); TopoDS_Shape shapeToExport; diff --git a/src/Mod/Import/App/ExportOCAF.cpp b/src/Mod/Import/App/ExportOCAF.cpp index 6aa0a0f5bd..302bef57cc 100644 --- a/src/Mod/Import/App/ExportOCAF.cpp +++ b/src/Mod/Import/App/ExportOCAF.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include #include @@ -141,10 +141,12 @@ void ExportOCAF::exportObjects(std::vector& objs) XCAFDoc_DocumentTool::ShapeTool(pDoc->Main())->UpdateAssemblies(); } -int ExportOCAF::exportObject(App::DocumentObject* obj, - std::vector& hierarchical_label, - std::vector& hierarchical_loc, - std::vector& hierarchical_part) +int ExportOCAF::exportObject( + App::DocumentObject* obj, + std::vector& hierarchical_label, + std::vector& hierarchical_loc, + std::vector& hierarchical_part +) { std::vector local_label; int root_id; @@ -162,8 +164,7 @@ int ExportOCAF::exportObject(App::DocumentObject* obj, for (it = entries.begin(); it != entries.end(); ++it) { int new_label = 0; - new_label = - exportObject((*it), hierarchical_label, hierarchical_loc, hierarchical_part); + new_label = exportObject((*it), hierarchical_label, hierarchical_loc, hierarchical_part); local_label.push_back(new_label); } @@ -189,8 +190,7 @@ int ExportOCAF::exportObject(App::DocumentObject* obj, std::vector colors; findColors(part, colors); - return_label = - saveShape(part, colors, hierarchical_label, hierarchical_loc, hierarchical_part); + return_label = saveShape(part, colors, hierarchical_label, hierarchical_loc, hierarchical_part); } return return_label; @@ -198,11 +198,13 @@ int ExportOCAF::exportObject(App::DocumentObject* obj, // This function creates an Assembly node in an XCAF document with its relative placement // information -void ExportOCAF::createNode(App::Part* part, - int& root_id, - std::vector& hierarchical_label, - std::vector& hierarchical_loc, - std::vector& hierarchical_part) +void ExportOCAF::createNode( + App::Part* part, + int& root_id, + std::vector& hierarchical_label, + std::vector& hierarchical_loc, + std::vector& hierarchical_part +) { TDF_Label shapeLabel = aShapeTool->NewShape(); Handle(TDataStd_Name) N; @@ -227,11 +229,13 @@ void ExportOCAF::createNode(App::Part* part, root_id = hierarchical_label.size(); } -int ExportOCAF::saveShape(Part::Feature* part, - const std::vector& colors, - std::vector& hierarchical_label, - std::vector& hierarchical_loc, - std::vector& hierarchical_part) +int ExportOCAF::saveShape( + Part::Feature* part, + const std::vector& colors, + std::vector& hierarchical_label, + std::vector& hierarchical_loc, + std::vector& hierarchical_part +) { const TopoDS_Shape& shape = part->Shape.getValue(); if (shape.IsNull()) { @@ -333,9 +337,11 @@ int ExportOCAF::saveShape(Part::Feature* part, // If this Free Shapes are regular Part::Feature, we must use absolute coordinate instead of // allocating a placement into the hierarchy as it is not attached to a hierarchical node -void ExportOCAF::getFreeLabels(std::vector& hierarchical_label, - std::vector& labels, - std::vector& label_part_id) +void ExportOCAF::getFreeLabels( + std::vector& hierarchical_label, + std::vector& labels, + std::vector& label_part_id +) { TDF_LabelSequence FreeLabels; aShapeTool->GetFreeShapes(FreeLabels); @@ -351,10 +357,12 @@ void ExportOCAF::getFreeLabels(std::vector& hierarchical_label, } } -void ExportOCAF::getPartColors(std::vector hierarchical_part, - std::vector FreeLabels, - std::vector part_id, - std::vector>& Colors) const +void ExportOCAF::getPartColors( + std::vector hierarchical_part, + std::vector FreeLabels, + std::vector part_id, + std::vector>& Colors +) const { // I am seeking for the colors of each parts std::size_t n = FreeLabels.size(); @@ -366,10 +374,12 @@ void ExportOCAF::getPartColors(std::vector hierarchical_pa } } -void ExportOCAF::reallocateFreeShape(std::vector hierarchical_part, - std::vector FreeLabels, - std::vector part_id, - std::vector>& Colors) +void ExportOCAF::reallocateFreeShape( + std::vector hierarchical_part, + std::vector FreeLabels, + std::vector part_id, + std::vector>& Colors +) { std::size_t n = FreeLabels.size(); for (std::size_t i = 0; i < n; i++) { @@ -435,10 +445,12 @@ void ExportOCAF::reallocateFreeShape(std::vector hierarchi } // This function is moving a "standard" node into an Assembly node within an XCAF doc -void ExportOCAF::pushNode(int root_id, - int node_id, - std::vector& hierarchical_label, - std::vector& hierarchical_loc) +void ExportOCAF::pushNode( + int root_id, + int node_id, + std::vector& hierarchical_label, + std::vector& hierarchical_loc +) { auto isValidIndex = [&](std::size_t root, std::size_t node) { // NOLINTBEGIN diff --git a/src/Mod/Import/App/ExportOCAF.h b/src/Mod/Import/App/ExportOCAF.h index 4375a0de72..5afa69f1b8 100644 --- a/src/Mod/Import/App/ExportOCAF.h +++ b/src/Mod/Import/App/ExportOCAF.h @@ -61,35 +61,49 @@ public: ExportOCAF(Handle(TDocStd_Document) hDoc, bool explicitPlacement); virtual ~ExportOCAF(); void exportObjects(std::vector& objs); - int exportObject(App::DocumentObject* obj, - std::vector& hierarchical_label, - std::vector& hierarchical_loc, - std::vector& hierarchical_part); - int saveShape(Part::Feature* part, - const std::vector&, - std::vector& hierarchical_label, - std::vector& hierarchical_loc, - std::vector& hierarchical_part); - void getPartColors(std::vector hierarchical_part, - std::vector FreeLabels, - std::vector part_id, - std::vector>& Colors) const; - void reallocateFreeShape(std::vector hierarchical_part, - std::vector FreeLabels, - std::vector part_id, - std::vector>& Colors); - void getFreeLabels(std::vector& hierarchical_label, - std::vector& labels, - std::vector& label_part_id); - void createNode(App::Part* part, - int& root_it, - std::vector& hierarchical_label, - std::vector& hierarchical_loc, - std::vector& hierarchical_part); - void pushNode(int root, - int node, - std::vector& hierarchical_label, - std::vector& hierarchical_loc); + int exportObject( + App::DocumentObject* obj, + std::vector& hierarchical_label, + std::vector& hierarchical_loc, + std::vector& hierarchical_part + ); + int saveShape( + Part::Feature* part, + const std::vector&, + std::vector& hierarchical_label, + std::vector& hierarchical_loc, + std::vector& hierarchical_part + ); + void getPartColors( + std::vector hierarchical_part, + std::vector FreeLabels, + std::vector part_id, + std::vector>& Colors + ) const; + void reallocateFreeShape( + std::vector hierarchical_part, + std::vector FreeLabels, + std::vector part_id, + std::vector>& Colors + ); + void getFreeLabels( + std::vector& hierarchical_label, + std::vector& labels, + std::vector& label_part_id + ); + void createNode( + App::Part* part, + int& root_it, + std::vector& hierarchical_label, + std::vector& hierarchical_loc, + std::vector& hierarchical_part + ); + void pushNode( + int root, + int node, + std::vector& hierarchical_label, + std::vector& hierarchical_loc + ); private: virtual void findColors(Part::Feature*, std::vector&) const diff --git a/src/Mod/Import/App/ExportOCAF2.cpp b/src/Mod/Import/App/ExportOCAF2.cpp index 4eb542965c..e92d15b2db 100644 --- a/src/Mod/Import/App/ExportOCAF2.cpp +++ b/src/Mod/Import/App/ExportOCAF2.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include #include @@ -91,10 +91,12 @@ ExportOCAFOptions ExportOCAF2::customExportOptions() defaultOptions.exportHidden = settings.getExportHiddenObject(); defaultOptions.keepPlacement = settings.getExportKeepPlacement(); - auto handle = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + auto handle = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); defaultOptions.defaultColor.setPackedValue( - handle->GetUnsigned("DefaultShapeColor", defaultOptions.defaultColor.getPackedValue())); + handle->GetUnsigned("DefaultShapeColor", defaultOptions.defaultColor.getPackedValue()) + ); defaultOptions.defaultColor.a = 1; return defaultOptions; @@ -114,8 +116,10 @@ void ExportOCAF2::setName(TDF_Label label, App::DocumentObject* obj, const char* // Similar to XCAFDoc_ShapeTool::FindSHUO but return only main SHUO, i.e. SHUO // with no upper_usage. It should not be necessary if we strictly export from // bottom up, but let's make sure of it. -static Standard_Boolean FindSHUO(const TDF_LabelSequence& theLabels, - Handle(XCAFDoc_GraphNode) & theSHUOAttr) +static Standard_Boolean FindSHUO( + const TDF_LabelSequence& theLabels, + Handle(XCAFDoc_GraphNode) & theSHUOAttr +) { assert(theLabels.Length() > 1); theSHUOAttr.Nullify(); @@ -154,8 +158,7 @@ static Standard_Boolean FindSHUO(const TDF_LabelSequence& theLabels, return (!theSHUOAttr.IsNull()); } -TDF_Label -ExportOCAF2::findComponent(const char* subname, TDF_Label label, TDF_LabelSequence& labels) +TDF_Label ExportOCAF2::findComponent(const char* subname, TDF_Label label, TDF_LabelSequence& labels) { const char* dot = strchr(subname, '.'); if (!dot) { @@ -198,12 +201,14 @@ ExportOCAF2::findComponent(const char* subname, TDF_Label label, TDF_LabelSequen return {}; } -void ExportOCAF2::setupObject(TDF_Label label, - App::DocumentObject* obj, - const Part::TopoShape& shape, - const std::string& prefix, - const char* name, - bool force) +void ExportOCAF2::setupObject( + TDF_Label label, + App::DocumentObject* obj, + const Part::TopoShape& shape, + const std::string& prefix, + const char* name, + bool force +) { setName(label, obj, name); if (aShapeTool->IsComponent(label)) { @@ -303,8 +308,10 @@ void ExportOCAF2::setupObject(TDF_Label label, // OCCT code, XCAFDoc_ShapeTool.cxx and STEPCAFControl_Writer.cxx. if (!warned) { warned = true; - FC_WARN("Current OCCT does not support element color override, for object " - << obj->getFullName()); + FC_WARN( + "Current OCCT does not support element color override, for object " + << obj->getFullName() + ); } // continue; } @@ -376,10 +383,12 @@ void ExportOCAF2::exportObjects(std::vector& objs, const c aShapeTool->UpdateAssemblies(); } -TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, - const char* sub, - TDF_Label parent, - const char* name) +TDF_Label ExportOCAF2::exportObject( + App::DocumentObject* parentObj, + const char* sub, + TDF_Label parent, + const char* name +) { App::DocumentObject* obj; auto shape = Part::Feature::getTopoShape( @@ -387,7 +396,8 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, (sub ? Part::ShapeOption::NoFlag : Part::ShapeOption::Transform), sub, nullptr, - &obj); + &obj + ); if (!obj || shape.isNull()) { if (obj) { FC_WARN(obj->getFullName() << " has null shape"); @@ -431,9 +441,10 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, auto linked = obj; auto linkedShape = shape; while (true) { - auto s = Part::Feature::getTopoShape(linked, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform); + auto s = Part::Feature::getTopoShape( + linked, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (s.isNull() || !s.getShape().IsPartner(shape.getShape())) { break; } @@ -563,8 +574,8 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, continue; } - TDF_Label childLabel = - exportObject(obj, subobj.c_str(), label, linkArray ? childName.c_str() : nullptr); + TDF_Label childLabel + = exportObject(obj, subobj.c_str(), label, linkArray ? childName.c_str() : nullptr); if (childLabel.IsNull()) { continue; } @@ -584,8 +595,7 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, // First, check if a color was already set (e.g., for a sub-element). Quantity_ColorRGBA existingColor; - bool hasExplicitColor = - aColorTool->GetColor(childLabel, XCAFDoc_ColorGen, existingColor) + bool hasExplicitColor = aColorTool->GetColor(childLabel, XCAFDoc_ColorGen, existingColor) || aColorTool->GetColor(childLabel, XCAFDoc_ColorSurf, existingColor) || aColorTool->GetColor(childLabel, XCAFDoc_ColorCurv, existingColor); diff --git a/src/Mod/Import/App/ExportOCAF2.h b/src/Mod/Import/App/ExportOCAF2.h index afe2d023e2..4f9861580d 100644 --- a/src/Mod/Import/App/ExportOCAF2.h +++ b/src/Mod/Import/App/ExportOCAF2.h @@ -61,10 +61,9 @@ struct ImportExport ExportOCAFOptions class ImportExport ExportOCAF2 { public: - using GetShapeColorsFunc = - std::function(App::DocumentObject*, const char*)>; - explicit ExportOCAF2(Handle(TDocStd_Document) hDoc, - GetShapeColorsFunc func = GetShapeColorsFunc()); + using GetShapeColorsFunc + = std::function(App::DocumentObject*, const char*)>; + explicit ExportOCAF2(Handle(TDocStd_Document) hDoc, GetShapeColorsFunc func = GetShapeColorsFunc()); static ExportOCAFOptions customExportOptions(); void setExportOptions(ExportOCAFOptions opts) @@ -83,16 +82,20 @@ public: bool canFallback(std::vector objs); private: - TDF_Label exportObject(App::DocumentObject* obj, - const char* sub, - TDF_Label parent, - const char* name = nullptr); - void setupObject(TDF_Label label, - App::DocumentObject* obj, - const Part::TopoShape& shape, - const std::string& prefix, - const char* name = nullptr, - bool force = false); + TDF_Label exportObject( + App::DocumentObject* obj, + const char* sub, + TDF_Label parent, + const char* name = nullptr + ); + void setupObject( + TDF_Label label, + App::DocumentObject* obj, + const Part::TopoShape& shape, + const std::string& prefix, + const char* name = nullptr, + bool force = false + ); void setName(TDF_Label label, App::DocumentObject* obj, const char* name = nullptr); TDF_Label findComponent(const char* subname, TDF_Label label, TDF_LabelSequence& labels); diff --git a/src/Mod/Import/App/ImportOCAF.cpp b/src/Mod/Import/App/ImportOCAF.cpp index 38140d81b9..d74b22dca2 100644 --- a/src/Mod/Import/App/ImportOCAF.cpp +++ b/src/Mod/Import/App/ImportOCAF.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include #include @@ -58,9 +58,9 @@ #ifdef HAVE_TBB -#include -#include -#include +# include +# include +# include #endif using namespace Import; @@ -118,12 +118,14 @@ void ImportOCAF::setMerge(bool merge) this->merge = merge; } -void ImportOCAF::loadShapes(const TDF_Label& label, - const TopLoc_Location& loc, - const std::string& defaultname, - const std::string& assembly, - bool isRef, - std::vector& lValue) +void ImportOCAF::loadShapes( + const TDF_Label& label, + const TopLoc_Location& loc, + const std::string& defaultname, + const std::string& assembly, + bool isRef, + std::vector& lValue +) { int hash = 0; #ifdef HAVE_TBB @@ -175,18 +177,20 @@ void ImportOCAF::loadShapes(const TDF_Label& label, } #ifdef FC_DEBUG - Base::Console().log("H:%d, N:%s, T:%d, A:%d, S:%d, C:%d, SS:%d, F:%d, R:%d, C:%d, SS:%d\n", - hash, - part_name.c_str(), - aShapeTool->IsTopLevel(label), - aShapeTool->IsAssembly(label), - aShapeTool->IsShape(label), - aShapeTool->IsCompound(label), - aShapeTool->IsSimpleShape(label), - aShapeTool->IsFree(label), - aShapeTool->IsReference(label), - aShapeTool->IsComponent(label), - aShapeTool->IsSubShape(label)); + Base::Console().log( + "H:%d, N:%s, T:%d, A:%d, S:%d, C:%d, SS:%d, F:%d, R:%d, C:%d, SS:%d\n", + hash, + part_name.c_str(), + aShapeTool->IsTopLevel(label), + aShapeTool->IsAssembly(label), + aShapeTool->IsShape(label), + aShapeTool->IsCompound(label), + aShapeTool->IsSimpleShape(label), + aShapeTool->IsFree(label), + aShapeTool->IsReference(label), + aShapeTool->IsComponent(label), + aShapeTool->IsSubShape(label) + ); #endif #if defined(OCAF_KEEP_PLACEMENT) @@ -265,11 +269,13 @@ void ImportOCAF::loadShapes(const TDF_Label& label, } } -void ImportOCAF::createShape(const TDF_Label& label, - const TopLoc_Location& loc, - const std::string& name, - std::vector& lValue, - bool mergeShape) +void ImportOCAF::createShape( + const TDF_Label& label, + const TopLoc_Location& loc, + const std::string& name, + std::vector& lValue, + bool mergeShape +) { const TopoDS_Shape& aShape = aShapeTool->GetShape(label); #ifdef HAVE_TBB @@ -370,10 +376,12 @@ void ImportOCAF::createShape(const TDF_Label& label, } } -void ImportOCAF::createShape(const TopoDS_Shape& aShape, - const TopLoc_Location& loc, - const std::string& name, - std::vector& lvalue) +void ImportOCAF::createShape( + const TopoDS_Shape& aShape, + const TopLoc_Location& loc, + const std::string& name, + std::vector& lvalue +) { Part::Feature* part = doc->addObject(); diff --git a/src/Mod/Import/App/ImportOCAF.h b/src/Mod/Import/App/ImportOCAF.h index e9cc0399a3..548b54497e 100644 --- a/src/Mod/Import/App/ImportOCAF.h +++ b/src/Mod/Import/App/ImportOCAF.h @@ -66,21 +66,27 @@ public: void setMerge(bool); private: - void loadShapes(const TDF_Label& label, - const TopLoc_Location&, - const std::string& partname, - const std::string& assembly, - bool isRef, - std::vector&); - void createShape(const TDF_Label& label, - const TopLoc_Location&, - const std::string&, - std::vector&, - bool); - void createShape(const TopoDS_Shape& label, - const TopLoc_Location&, - const std::string&, - std::vector&); + void loadShapes( + const TDF_Label& label, + const TopLoc_Location&, + const std::string& partname, + const std::string& assembly, + bool isRef, + std::vector& + ); + void createShape( + const TDF_Label& label, + const TopLoc_Location&, + const std::string&, + std::vector&, + bool + ); + void createShape( + const TopoDS_Shape& label, + const TopLoc_Location&, + const std::string&, + std::vector& + ); void loadColors(Part::Feature* part, const TopoDS_Shape& aShape); virtual void applyColors(Part::Feature*, const std::vector&) {} diff --git a/src/Mod/Import/App/ImportOCAF2.cpp b/src/Mod/Import/App/ImportOCAF2.cpp index d05f14a2ac..61aeee5bfa 100644 --- a/src/Mod/Import/App/ImportOCAF2.cpp +++ b/src/Mod/Import/App/ImportOCAF2.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include #include @@ -106,15 +106,17 @@ ImportOCAFOptions ImportOCAF2::customImportOptions() defaultOptions.expandCompound = settings.getExpandCompound(); defaultOptions.mode = static_cast(settings.getImportMode()); - auto hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + auto hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); defaultOptions.defaultFaceColor.setPackedValue( - hGrp->GetUnsigned("DefaultShapeColor", defaultOptions.defaultFaceColor.getPackedValue())); + hGrp->GetUnsigned("DefaultShapeColor", defaultOptions.defaultFaceColor.getPackedValue()) + ); defaultOptions.defaultFaceColor.a = 1.0F; defaultOptions.defaultEdgeColor.setPackedValue( - hGrp->GetUnsigned("DefaultShapeLineColor", - defaultOptions.defaultEdgeColor.getPackedValue())); + hGrp->GetUnsigned("DefaultShapeLineColor", defaultOptions.defaultEdgeColor.getPackedValue()) + ); defaultOptions.defaultEdgeColor.a = 1.0F; return defaultOptions; @@ -154,8 +156,9 @@ void ImportOCAF2::setMode(int m) static void setPlacement(App::PropertyPlacement* prop, const TopoDS_Shape& shape) { - prop->setValue(Base::Placement(Part::TopoShape::convert(shape.Location().Transformation())) - * prop->getValue()); + prop->setValue( + Base::Placement(Part::TopoShape::convert(shape.Location().Transformation())) * prop->getValue() + ); } std::string ImportOCAF2::getLabelName(TDF_Label label) @@ -238,8 +241,7 @@ bool ImportOCAF2::getColor(const TopoDS_Shape& shape, Info& info, bool check, bo return ret; } -App::DocumentObject* -ImportOCAF2::expandShape(App::Document* doc, TDF_Label label, const TopoDS_Shape& shape) +App::DocumentObject* ImportOCAF2::expandShape(App::Document* doc, TDF_Label label, const TopoDS_Shape& shape) { if (shape.IsNull() || !TopExp_Explorer(shape, TopAbs_VERTEX).More()) { return nullptr; @@ -276,11 +278,13 @@ ImportOCAF2::expandShape(App::Document* doc, TDF_Label label, const TopoDS_Shape return info.obj; } -bool ImportOCAF2::createObject(App::Document* doc, - TDF_Label label, - const TopoDS_Shape& shape, - Info& info, - bool newDoc) +bool ImportOCAF2::createObject( + App::Document* doc, + TDF_Label label, + const TopoDS_Shape& shape, + Info& info, + bool newDoc +) { if (shape.IsNull() || !TopExp_Explorer(shape, TopAbs_VERTEX).More()) { FC_WARN(Tools::labelName(label) << " has empty shape"); @@ -451,24 +455,26 @@ App::Document* ImportOCAF2::getDocument(App::Document* doc, TDF_Label label) return doc; } -bool ImportOCAF2::createGroup(App::Document* doc, - Info& info, - const TopoDS_Shape& shape, - std::vector& children, - const boost::dynamic_bitset<>& visibilities, - bool canReduce) +bool ImportOCAF2::createGroup( + App::Document* doc, + Info& info, + const TopoDS_Shape& shape, + std::vector& children, + const boost::dynamic_bitset<>& visibilities, + bool canReduce +) { assert(children.size() == visibilities.size()); if (children.empty()) { return false; } bool hasColor = getColor(shape, info, false, true); - if (canReduce && !hasColor && options.reduceObjects && children.size() == 1 - && visibilities[0]) { + if (canReduce && !hasColor && options.reduceObjects && children.size() == 1 && visibilities[0]) { info.obj = children.front(); info.free = true; - info.propPlacement = - dynamic_cast(info.obj->getPropertyByName("Placement")); + info.propPlacement = dynamic_cast( + info.obj->getPropertyByName("Placement") + ); myCollapsedObjects.emplace(info.obj, info.propPlacement); return true; } @@ -557,9 +563,10 @@ App::DocumentObject* ImportOCAF2::loadShapes() ret->recomputeFeature(true); } if (options.merge && ret && !ret->isDerivedFrom()) { - auto shape = Part::Feature::getTopoShape(ret, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform); + auto shape = Part::Feature::getTopoShape( + ret, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); auto feature = pDocument->addObject("Feature"); auto name = Tools::labelName(pDoc->Main()); feature->Label.setValue(name.empty() ? default_name.c_str() : name.c_str()); @@ -580,9 +587,7 @@ App::DocumentObject* ImportOCAF2::loadShapes() return ret; } -void ImportOCAF2::getSHUOColors(TDF_Label label, - std::map& colors, - bool appendFirst) +void ImportOCAF2::getSHUOColors(TDF_Label label, std::map& colors, bool appendFirst) { TDF_AttributeSequence seq; if (label.IsNull() || !aShapeTool->GetAllComponentSHUO(label, seq)) { @@ -646,11 +651,13 @@ void ImportOCAF2::getSHUOColors(TDF_Label label, } } -App::DocumentObject* ImportOCAF2::loadShape(App::Document* doc, - TDF_Label label, - const TopoDS_Shape& shape, - bool baseOnly, - bool newDoc) +App::DocumentObject* ImportOCAF2::loadShape( + App::Document* doc, + TDF_Label label, + const TopoDS_Shape& shape, + bool baseOnly, + bool newDoc +) { if (shape.IsNull()) { return nullptr; @@ -736,11 +743,13 @@ struct ChildInfo TopoDS_Shape shape; }; -bool ImportOCAF2::createAssembly(App::Document* _doc, - TDF_Label label, - const TopoDS_Shape& shape, - Info& info, - bool newDoc) +bool ImportOCAF2::createAssembly( + App::Document* _doc, + TDF_Label label, + const TopoDS_Shape& shape, + Info& info, + bool newDoc +) { (void)label; @@ -788,8 +797,7 @@ bool ImportOCAF2::createAssembly(App::Document* _doc, childInfo.vis.push_back(vis); childInfo.labels.push_back(childLabel); - childInfo.plas.emplace_back( - Part::TopoShape::convert(childShape.Location().Transformation())); + childInfo.plas.emplace_back(Part::TopoShape::convert(childShape.Location().Transformation())); Quantity_ColorRGBA aColor; if (aColorTool->GetColor(childShape, XCAFDoc_ColorSurf, aColor)) { childInfo.colors[childInfo.plas.size() - 1] = Tools::convertColor(aColor); @@ -867,9 +875,7 @@ bool ImportOCAF2::createAssembly(App::Document* _doc, // ---------------------------------------------------------------------------- -ImportOCAFExt::ImportOCAFExt(Handle(TDocStd_Document) hStdDoc, - App::Document* doc, - const std::string& name) +ImportOCAFExt::ImportOCAFExt(Handle(TDocStd_Document) hStdDoc, App::Document* doc, const std::string& name) : ImportOCAF2(hStdDoc, doc, name) {} diff --git a/src/Mod/Import/App/ImportOCAF2.h b/src/Mod/Import/App/ImportOCAF2.h index db00588c62..a67d10744b 100644 --- a/src/Mod/Import/App/ImportOCAF2.h +++ b/src/Mod/Import/App/ImportOCAF2.h @@ -138,36 +138,41 @@ private: int free = true; }; - App::DocumentObject* loadShape(App::Document* doc, - TDF_Label label, - const TopoDS_Shape& shape, - bool baseOnly = false, - bool newDoc = true); + App::DocumentObject* loadShape( + App::Document* doc, + TDF_Label label, + const TopoDS_Shape& shape, + bool baseOnly = false, + bool newDoc = true + ); App::Document* getDocument(App::Document* doc, TDF_Label label); - bool createAssembly(App::Document* doc, - TDF_Label label, - const TopoDS_Shape& shape, - Info& info, - bool newDoc); - bool createObject(App::Document* doc, - TDF_Label label, - const TopoDS_Shape& shape, - Info& info, - bool newDoc); - bool createGroup(App::Document* doc, - Info& info, - const TopoDS_Shape& shape, - std::vector& children, - const boost::dynamic_bitset<>& visibilities, - bool canReduce = false); - bool - getColor(const TopoDS_Shape& shape, Info& info, bool check = false, bool noDefault = false); - void - getSHUOColors(TDF_Label label, std::map& colors, bool appendFirst); + bool createAssembly( + App::Document* doc, + TDF_Label label, + const TopoDS_Shape& shape, + Info& info, + bool newDoc + ); + bool createObject( + App::Document* doc, + TDF_Label label, + const TopoDS_Shape& shape, + Info& info, + bool newDoc + ); + bool createGroup( + App::Document* doc, + Info& info, + const TopoDS_Shape& shape, + std::vector& children, + const boost::dynamic_bitset<>& visibilities, + bool canReduce = false + ); + bool getColor(const TopoDS_Shape& shape, Info& info, bool check = false, bool noDefault = false); + void getSHUOColors(TDF_Label label, std::map& colors, bool appendFirst); void setObjectName(Info& info, TDF_Label label); std::string getLabelName(TDF_Label label); - App::DocumentObject* - expandShape(App::Document* doc, TDF_Label label, const TopoDS_Shape& shape); + App::DocumentObject* expandShape(App::Document* doc, TDF_Label label, const TopoDS_Shape& shape); virtual void applyEdgeColors(Part::Feature*, const std::vector&) {} @@ -235,10 +240,9 @@ struct ImportExport ExportOCAFOptions class ImportExport ExportOCAF2 { public: - using GetShapeColorsFunc = - std::function(App::DocumentObject*, const char*)>; - explicit ExportOCAF2(Handle(TDocStd_Document) h, - GetShapeColorsFunc func = GetShapeColorsFunc()); + using GetShapeColorsFunc + = std::function(App::DocumentObject*, const char*)>; + explicit ExportOCAF2(Handle(TDocStd_Document) h, GetShapeColorsFunc func = GetShapeColorsFunc()); static ExportOCAFOptions customExportOptions(); void setExportOptions(ExportOCAFOptions opts) @@ -257,16 +261,20 @@ public: bool canFallback(std::vector objs); private: - TDF_Label exportObject(App::DocumentObject* obj, - const char* sub, - TDF_Label parent, - const char* name = nullptr); - void setupObject(TDF_Label label, - App::DocumentObject* obj, - const Part::TopoShape& shape, - const std::string& prefix, - const char* name = nullptr, - bool force = false); + TDF_Label exportObject( + App::DocumentObject* obj, + const char* sub, + TDF_Label parent, + const char* name = nullptr + ); + void setupObject( + TDF_Label label, + App::DocumentObject* obj, + const Part::TopoShape& shape, + const std::string& prefix, + const char* name = nullptr, + bool force = false + ); void setName(TDF_Label label, App::DocumentObject* obj, const char* name = nullptr); TDF_Label findComponent(const char* subname, TDF_Label label, TDF_LabelSequence& labels); diff --git a/src/Mod/Import/App/ImportOCAFAssembly.cpp b/src/Mod/Import/App/ImportOCAFAssembly.cpp index 4666b65cce..4888eb78f0 100644 --- a/src/Mod/Import/App/ImportOCAFAssembly.cpp +++ b/src/Mod/Import/App/ImportOCAFAssembly.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include #include @@ -52,10 +52,12 @@ using namespace Import; -ImportOCAFAssembly::ImportOCAFAssembly(Handle(TDocStd_Document) h, - App::Document* d, - const std::string& name, - App::DocumentObject* target) +ImportOCAFAssembly::ImportOCAFAssembly( + Handle(TDocStd_Document) h, + App::Document* d, + const std::string& name, + App::DocumentObject* target +) : pDoc(h) , doc(d) , default_name(name) @@ -99,12 +101,14 @@ std::string ImportOCAFAssembly::getName(const TDF_Label& label) } -void ImportOCAFAssembly::loadShapes(const TDF_Label& label, - const TopLoc_Location& loc, - const std::string& defaultname, - const std::string& assembly, - bool isRef, - int dep) +void ImportOCAFAssembly::loadShapes( + const TDF_Label& label, + const TopLoc_Location& loc, + const std::string& defaultname, + const std::string& assembly, + bool isRef, + int dep +) { int hash = 0; TopoDS_Shape aShape; @@ -159,21 +163,23 @@ void ImportOCAFAssembly::loadShapes(const TDF_Label& label, std::stringstream str; - Base::Console().log("H:%-9d \tN:%-30s \tTop:%d, Asm:%d, Shape:%d, Compound:%d, Simple:%d, " - "Free:%d, Ref:%d, Component:%d, SubShape:%d\tTrf:%s-- Dep:%d \n", - hash, - part_name.c_str(), - aShapeTool->IsTopLevel(label), - aShapeTool->IsAssembly(label), - aShapeTool->IsShape(label), - aShapeTool->IsCompound(label), - aShapeTool->IsSimpleShape(label), - aShapeTool->IsFree(label), - aShapeTool->IsReference(label), - aShapeTool->IsComponent(label), - aShapeTool->IsSubShape(label), - s, - dep); + Base::Console().log( + "H:%-9d \tN:%-30s \tTop:%d, Asm:%d, Shape:%d, Compound:%d, Simple:%d, " + "Free:%d, Ref:%d, Component:%d, SubShape:%d\tTrf:%s-- Dep:%d \n", + hash, + part_name.c_str(), + aShapeTool->IsTopLevel(label), + aShapeTool->IsAssembly(label), + aShapeTool->IsShape(label), + aShapeTool->IsCompound(label), + aShapeTool->IsSimpleShape(label), + aShapeTool->IsFree(label), + aShapeTool->IsReference(label), + aShapeTool->IsComponent(label), + aShapeTool->IsSubShape(label), + s, + dep + ); label.Dump(str); Base::Console().message(str.str().c_str()); @@ -214,9 +220,11 @@ void ImportOCAFAssembly::loadShapes(const TDF_Label& label, } } -void ImportOCAFAssembly::createShape(const TDF_Label& label, - const TopLoc_Location& loc, - const std::string& name) +void ImportOCAFAssembly::createShape( + const TDF_Label& label, + const TopLoc_Location& loc, + const std::string& name +) { Base::Console().log("-create Shape\n"); const TopoDS_Shape& aShape = aShapeTool->GetShape(label); @@ -236,9 +244,11 @@ void ImportOCAFAssembly::createShape(const TDF_Label& label, createShape(aShape, loc, name); } -void ImportOCAFAssembly::createShape(const TopoDS_Shape& aShape, - const TopLoc_Location& loc, - const std::string& name) +void ImportOCAFAssembly::createShape( + const TopoDS_Shape& aShape, + const TopLoc_Location& loc, + const std::string& name +) { Part::Feature* part = doc->addObject(); if (!loc.IsIdentity()) { diff --git a/src/Mod/Import/App/ImportOCAFAssembly.h b/src/Mod/Import/App/ImportOCAFAssembly.h index 67ea9a0f83..0a04fa7210 100644 --- a/src/Mod/Import/App/ImportOCAFAssembly.h +++ b/src/Mod/Import/App/ImportOCAFAssembly.h @@ -55,10 +55,12 @@ namespace Import class ImportExport ImportOCAFAssembly { public: - ImportOCAFAssembly(Handle(TDocStd_Document) h, - App::Document* d, - const std::string& name, - App::DocumentObject* target); + ImportOCAFAssembly( + Handle(TDocStd_Document) h, + App::Document* d, + const std::string& name, + App::DocumentObject* target + ); virtual ~ImportOCAFAssembly(); void loadShapes(); void loadAssembly(); @@ -69,12 +71,14 @@ protected: private: - void loadShapes(const TDF_Label& label, - const TopLoc_Location&, - const std::string& partname, - const std::string& assembly, - bool isRef, - int dep); + void loadShapes( + const TDF_Label& label, + const TopLoc_Location&, + const std::string& partname, + const std::string& assembly, + bool isRef, + int dep + ); void createShape(const TDF_Label& label, const TopLoc_Location&, const std::string&); void createShape(const TopoDS_Shape& label, const TopLoc_Location&, const std::string&); virtual void applyColors(Part::Feature*, const std::vector&) diff --git a/src/Mod/Import/App/ReaderGltf.cpp b/src/Mod/Import/App/ReaderGltf.cpp index 12b60a0a15..f9aec32d3d 100644 --- a/src/Mod/Import/App/ReaderGltf.cpp +++ b/src/Mod/Import/App/ReaderGltf.cpp @@ -92,8 +92,10 @@ void ReaderGltf::processDocument(Handle(TDocStd_Document) hDoc) } // NOLINTNEXTLINE -TopoDS_Shape ReaderGltf::processSubShapes(Handle(TDocStd_Document) hDoc, - const TDF_LabelSequence& subShapeLabels) +TopoDS_Shape ReaderGltf::processSubShapes( + Handle(TDocStd_Document) hDoc, + const TDF_LabelSequence& subShapeLabels +) { TopoDS_Compound compound; Handle(XCAFDoc_ShapeTool) aShapeTool = XCAFDoc_DocumentTool::ShapeTool(hDoc->Main()); diff --git a/src/Mod/Import/App/ReaderGltf.h b/src/Mod/Import/App/ReaderGltf.h index 2b6e9f9895..55fb246922 100644 --- a/src/Mod/Import/App/ReaderGltf.h +++ b/src/Mod/Import/App/ReaderGltf.h @@ -45,8 +45,7 @@ public: private: TopoDS_Shape fixShape(TopoDS_Shape); void processDocument(Handle(TDocStd_Document) hDoc); - TopoDS_Shape processSubShapes(Handle(TDocStd_Document) hDoc, - const TDF_LabelSequence& subShapeLabels); + TopoDS_Shape processSubShapes(Handle(TDocStd_Document) hDoc, const TDF_LabelSequence& subShapeLabels); private: Base::FileInfo file; diff --git a/src/Mod/Import/App/SketchExportHelper.cpp b/src/Mod/Import/App/SketchExportHelper.cpp index 5078698c10..7fda7df3e3 100644 --- a/src/Mod/Import/App/SketchExportHelper.cpp +++ b/src/Mod/Import/App/SketchExportHelper.cpp @@ -46,8 +46,7 @@ using namespace Import; //! information is lost in this process, so it should only be used for flat objects like sketches. //! Note: this only returns hard and outline edges. Seam, smooth, isoparametric and hidden lines //! are not returned. -TopoDS_Shape SketchExportHelper::projectShape(const TopoDS_Shape& inShape, - const gp_Ax2& projectionCS) +TopoDS_Shape SketchExportHelper::projectShape(const TopoDS_Shape& inShape, const gp_Ax2& projectionCS) { Handle(HLRBRep_Algo) brep_hlr = new HLRBRep_Algo(); brep_hlr->Add(inShape); @@ -101,9 +100,11 @@ TopoDS_Shape SketchExportHelper::getFlatSketchXY(App::DocumentObject* obj) // get the sketch origin Base::Vector3d position = plm.getPosition(); - gp_Ax2 projectionCS(gp_Pnt(position.x, position.y, position.z), - gp_Dir(sketchNormal.x, sketchNormal.y, sketchNormal.z), - gp_Dir(sketchX.x, sketchX.y, sketchX.z)); + gp_Ax2 projectionCS( + gp_Pnt(position.x, position.y, position.z), + gp_Dir(sketchNormal.x, sketchNormal.y, sketchNormal.z), + gp_Dir(sketchX.x, sketchX.y, sketchX.z) + ); const TopoDS_Shape& shape = sketch->Shape.getValue(); return projectShape(shape, projectionCS); } diff --git a/src/Mod/Import/App/Tools.cpp b/src/Mod/Import/App/Tools.cpp index 05fc19d167..95f16ee6e4 100644 --- a/src/Mod/Import/App/Tools.cpp +++ b/src/Mod/Import/App/Tools.cpp @@ -46,10 +46,12 @@ Base::Color Tools::convertColor(const Quantity_ColorRGBA& rgba) { Standard_Real red, green, blue; rgba.GetRGB().Values(red, green, blue, OCC_COLOR_SPACE); - return Base::Color(static_cast(red), - static_cast(green), - static_cast(blue), - static_cast(rgba.Alpha())); + return Base::Color( + static_cast(red), + static_cast(green), + static_cast(blue), + static_cast(rgba.Alpha()) + ); } Quantity_ColorRGBA Tools::convertColor(const Base::Color& col) @@ -81,10 +83,12 @@ std::string Tools::labelName(TDF_Label label) return txt; } -void Tools::printLabel(TDF_Label label, - Handle(XCAFDoc_ShapeTool) aShapeTool, - Handle(XCAFDoc_ColorTool) aColorTool, - const char* msg) +void Tools::printLabel( + TDF_Label label, + Handle(XCAFDoc_ShapeTool) aShapeTool, + Handle(XCAFDoc_ColorTool) aColorTool, + const char* msg +) { if (label.IsNull() || !FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { return; @@ -127,10 +131,12 @@ void Tools::printLabel(TDF_Label label, Base::Console().notify("ImportOCAF2", ss.str().c_str()); } -void Tools::dumpLabels(TDF_Label label, - Handle(XCAFDoc_ShapeTool) aShapeTool, - Handle(XCAFDoc_ColorTool) aColorTool, - int depth) +void Tools::dumpLabels( + TDF_Label label, + Handle(XCAFDoc_ShapeTool) aShapeTool, + Handle(XCAFDoc_ColorTool) aColorTool, + int depth +) { std::string indent(depth * 2, ' '); printLabel(label, aShapeTool, aColorTool, indent.c_str()); diff --git a/src/Mod/Import/App/Tools.h b/src/Mod/Import/App/Tools.h index d2de34286f..821787d4fc 100644 --- a/src/Mod/Import/App/Tools.h +++ b/src/Mod/Import/App/Tools.h @@ -67,15 +67,19 @@ struct Tools static Base::Color convertColor(const Quantity_ColorRGBA& rgba); static Quantity_ColorRGBA convertColor(const Base::Color& col); static std::string labelName(TDF_Label label); - static void printLabel(TDF_Label label, - Handle(XCAFDoc_ShapeTool) aShapeTool, - Handle(XCAFDoc_ColorTool) aColorTool, - const char* msg = nullptr); + static void printLabel( + TDF_Label label, + Handle(XCAFDoc_ShapeTool) aShapeTool, + Handle(XCAFDoc_ColorTool) aColorTool, + const char* msg = nullptr + ); - static void dumpLabels(TDF_Label label, - Handle(XCAFDoc_ShapeTool) aShapeTool, - Handle(XCAFDoc_ColorTool) aColorTool, - int depth = 0); + static void dumpLabels( + TDF_Label label, + Handle(XCAFDoc_ShapeTool) aShapeTool, + Handle(XCAFDoc_ColorTool) aColorTool, + int depth = 0 + ); }; } // namespace Import diff --git a/src/Mod/Import/App/WriterStep.cpp b/src/Mod/Import/App/WriterStep.cpp index df7d9f966b..f7a80d5fc7 100644 --- a/src/Mod/Import/App/WriterStep.cpp +++ b/src/Mod/Import/App/WriterStep.cpp @@ -60,12 +60,12 @@ void WriterStep::write(Handle(TDocStd_Document) hDoc) const // NOLINT // https://forum.freecad.org/viewtopic.php?f=8&t=52967 makeHeader.SetAuthorValue( 1, - new TCollection_HAsciiString(hGrp->GetASCII("Author", "Author").c_str())); - makeHeader.SetOrganizationValue( - 1, - new TCollection_HAsciiString(hGrp->GetASCII("Company").c_str())); + new TCollection_HAsciiString(hGrp->GetASCII("Author", "Author").c_str()) + ); + makeHeader.SetOrganizationValue(1, new TCollection_HAsciiString(hGrp->GetASCII("Company").c_str())); makeHeader.SetOriginatingSystem( - new TCollection_HAsciiString(App::Application::getExecutableName().c_str())); + new TCollection_HAsciiString(App::Application::getExecutableName().c_str()) + ); makeHeader.SetDescriptionValue(1, new TCollection_HAsciiString("FreeCAD Model")); IFSelect_ReturnStatus ret = writer.Write(name8bit.c_str()); if (ret == IFSelect_RetError || ret == IFSelect_RetFail || ret == IFSelect_RetStop) { diff --git a/src/Mod/Import/App/dxf/ImpExpDxf.cpp b/src/Mod/Import/App/dxf/ImpExpDxf.cpp index 54a286bb3c..903235ca9d 100644 --- a/src/Mod/Import/App/dxf/ImpExpDxf.cpp +++ b/src/Mod/Import/App/dxf/ImpExpDxf.cpp @@ -25,7 +25,7 @@ #include #if OCC_VERSION_HEX < 0x070600 -#include +# include #endif #include #include @@ -98,12 +98,9 @@ namespace Part::Circle* createCirclePrimitive(const TopoDS_Edge& edge, App::Document* doc, const char* name); Part::Line* createLinePrimitive(const TopoDS_Edge& edge, App::Document* doc, const char* name); -Part::Ellipse* -createEllipsePrimitive(const TopoDS_Edge& edge, App::Document* doc, const char* name); -Part::Vertex* -createVertexPrimitive(const TopoDS_Vertex& vertex, App::Document* doc, const char* name); -Part::Feature* -createGenericShapeFeature(const TopoDS_Shape& shape, App::Document* doc, const char* name); +Part::Ellipse* createEllipsePrimitive(const TopoDS_Edge& edge, App::Document* doc, const char* name); +Part::Vertex* createVertexPrimitive(const TopoDS_Vertex& vertex, App::Document* doc, const char* name); +Part::Feature* createGenericShapeFeature(const TopoDS_Shape& shape, App::Document* doc, const char* name); } // namespace @@ -140,9 +137,12 @@ Part::Ellipse* createEllipsePrimitive(const TopoDS_Edge& edge, App::Document* do Base::Placement plc; plc.setPosition(Base::Vector3d(center.X(), center.Y(), center.Z())); plc.setRotation( - Base::Rotation::makeRotationByAxes(Base::Vector3d(xDir.X(), xDir.Y(), xDir.Z()), - Base::Vector3d(yDir.X(), yDir.Y(), yDir.Z()), - Base::Vector3d(zDir.X(), zDir.Y(), zDir.Z()))); + Base::Rotation::makeRotationByAxes( + Base::Vector3d(xDir.X(), xDir.Y(), xDir.Z()), + Base::Vector3d(yDir.X(), yDir.Y(), yDir.Z()), + Base::Vector3d(zDir.X(), zDir.Y(), zDir.Z()) + ) + ); p->Placement.setValue(plc); // Set angles for arcs, converting from radians (OCC) to degrees (PropertyAngle) @@ -179,9 +179,12 @@ Part::Circle* createCirclePrimitive(const TopoDS_Edge& edge, App::Document* doc, Base::Placement plc; plc.setPosition(Base::Vector3d(center.X(), center.Y(), center.Z())); plc.setRotation( - Base::Rotation::makeRotationByAxes(Base::Vector3d(xDir.X(), xDir.Y(), xDir.Z()), - Base::Vector3d(yDir.X(), yDir.Y(), yDir.Z()), - Base::Vector3d(zDir.X(), zDir.Y(), zDir.Z()))); + Base::Rotation::makeRotationByAxes( + Base::Vector3d(xDir.X(), xDir.Y(), xDir.Z()), + Base::Vector3d(yDir.X(), yDir.Y(), yDir.Z()), + Base::Vector3d(zDir.X(), zDir.Y(), zDir.Z()) + ) + ); p->Placement.setValue(plc); // Set angles for arcs @@ -216,8 +219,7 @@ Part::Line* createLinePrimitive(const TopoDS_Edge& edge, App::Document* doc, con } // Helper function to create and configure a Part::Vertex primitive from a TopoDS_Vertex -Part::Vertex* -createVertexPrimitive(const TopoDS_Vertex& vertex, App::Document* doc, const char* name) +Part::Vertex* createVertexPrimitive(const TopoDS_Vertex& vertex, App::Document* doc, const char* name) { auto* p = doc->addObject(name); if (p) { @@ -230,8 +232,7 @@ createVertexPrimitive(const TopoDS_Vertex& vertex, App::Document* doc, const cha } // Helper function to create a generic Part::Feature for any non-parametric shape -Part::Feature* -createGenericShapeFeature(const TopoDS_Shape& shape, App::Document* doc, const char* name) +Part::Feature* createGenericShapeFeature(const TopoDS_Shape& shape, App::Document* doc, const char* name) { auto* p = doc->addObject(name); if (p) { @@ -259,8 +260,10 @@ TopoDS_Wire ImpExpDxfRead::BuildWireFromPolyline(std::list& vertices TopoDS_Edge edge; if (start_vertex.bulge == 0.0) { - edge = BRepBuilderAPI_MakeEdge(makePoint(start_vertex.location), - makePoint(end_vertex.location)) + edge = BRepBuilderAPI_MakeEdge( + makePoint(start_vertex.location), + makePoint(end_vertex.location) + ) .Edge(); } else { @@ -339,8 +342,7 @@ TopoDS_Wire ImpExpDxfRead::BuildWireFromPolyline(std::list& vertices return wireBuilder.Wire(); } -Part::Feature* ImpExpDxfRead::createFlattenedPolylineFeature(const TopoDS_Wire& wire, - const char* name) +Part::Feature* ImpExpDxfRead::createFlattenedPolylineFeature(const TopoDS_Wire& wire, const char* name) { auto* p = document->addObject(document->getUniqueObjectName(name).c_str()); if (p) { @@ -350,8 +352,7 @@ Part::Feature* ImpExpDxfRead::createFlattenedPolylineFeature(const TopoDS_Wire& return p; } -Part::Compound* ImpExpDxfRead::createParametricPolylineCompound(const TopoDS_Wire& wire, - const char* name) +Part::Compound* ImpExpDxfRead::createParametricPolylineCompound(const TopoDS_Wire& wire, const char* name) { auto* p = document->addObject(document->getUniqueObjectName(name).c_str()); IncrementCreatedObjectCount(); @@ -452,11 +453,13 @@ void ImpExpDxfRead::StartImport() CDxfRead::StartImport(); // Create a hidden group to store the base objects for block definitions m_blockDefinitionGroup = static_cast( - document->addObject("App::DocumentObjectGroup", "_BlockDefinitions")); + document->addObject("App::DocumentObjectGroup", "_BlockDefinitions") + ); m_blockDefinitionGroup->Visibility.setValue(false); // Create a hidden group to store unreferenced blocks m_unreferencedBlocksGroup = static_cast( - document->addObject("App::DocumentObjectGroup", "_UnreferencedBlocks")); + document->addObject("App::DocumentObjectGroup", "_UnreferencedBlocks") + ); m_unreferencedBlocksGroup->Visibility.setValue(false); } @@ -480,10 +483,11 @@ bool ImpExpDxfRead::ReadEntitiesSection() // TODO: We do end-to-end joining or complete merging as selected by the options. for (auto& shapeSet : ShapesToCombine) { m_entityAttributes = shapeSet.first; - CombineShapes(shapeSet.second, - m_entityAttributes.m_Layer == nullptr - ? "Compound" - : m_entityAttributes.m_Layer->Name.c_str()); + CombineShapes( + shapeSet.second, + m_entityAttributes.m_Layer == nullptr ? "Compound" + : m_entityAttributes.m_Layer->Name.c_str() + ); } } else { @@ -532,8 +536,9 @@ TopoDS_Shape ImpExpDxfRead::CombineShapesToCompound(const std::listGetBool("dxfUseDraftVisGroups", true); @@ -579,8 +584,7 @@ void ImpExpDxfRead::setOptions() // hGrp->GetBool("dxfhiddenLayers", true); } -void ImpExpDxfRead::ComposeFlattenedBlock(const std::string& blockName, - std::set& composed) +void ImpExpDxfRead::ComposeFlattenedBlock(const std::string& blockName, std::set& composed) { // 1. Base Case: If already composed, do nothing. if (composed.count(blockName)) { @@ -622,7 +626,8 @@ void ImpExpDxfRead::ComposeFlattenedBlock(const std::string& blockName, // Apply the insert's transformation. Base::Placement pl( nestedInsert.Point, - Base::Rotation(Base::Vector3d(0, 0, 1), nestedInsert.Rotation)); + Base::Rotation(Base::Vector3d(0, 0, 1), nestedInsert.Rotation) + ); Base::Matrix4D transform = pl.toMatrix(); transform.scale(nestedInsert.Scale); nestedShape.transformShape(transform, true, true); // Use copy=true @@ -640,7 +645,8 @@ void ImpExpDxfRead::ComposeFlattenedBlock(const std::string& blockName, if (!finalShape.IsNull()) { std::string featureName = "BLOCK_" + blockName; auto blockFeature = document->addObject( - document->getUniqueObjectName(featureName.c_str()).c_str()); + document->getUniqueObjectName(featureName.c_str()).c_str() + ); blockFeature->Shape.setValue(finalShape); blockFeature->Visibility.setValue(false); m_blockDefinitionGroup->addObject(blockFeature); @@ -651,8 +657,7 @@ void ImpExpDxfRead::ComposeFlattenedBlock(const std::string& blockName, composed.insert(blockName); } -void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, - std::set& composed) +void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, std::set& composed) { // 1. Base Case: If this block has already been composed, we're done. if (composed.count(blockName)) { @@ -670,7 +675,8 @@ void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, // 3. Create the master Part::Compound for this block definition. std::string compName = "BLOCK_" + blockName; auto blockCompound = document->addObject( - document->getUniqueObjectName(compName.c_str()).c_str()); + document->getUniqueObjectName(compName.c_str()).c_str() + ); m_blockDefinitionGroup->addObject(blockCompound); IncrementCreatedObjectCount(); blockCompound->Visibility.setValue(false); @@ -692,13 +698,16 @@ void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, // The link's name should be based on the block it is inserting, not the parent. std::string linkName = "Link_" + nestedInsert.Name; auto link = document->addObject( - document->getUniqueObjectName(linkName.c_str()).c_str()); + document->getUniqueObjectName(linkName.c_str()).c_str() + ); link->setLink(-1, baseObjIt->second); link->LinkTransform.setValue(false); // Apply placement and scale to the link itself. - Base::Placement pl(nestedInsert.Point, - Base::Rotation(Base::Vector3d(0, 0, 1), nestedInsert.Rotation)); + Base::Placement pl( + nestedInsert.Point, + Base::Rotation(Base::Vector3d(0, 0, 1), nestedInsert.Rotation) + ); link->Placement.setValue(pl); link->ScaleVector.setValue(nestedInsert.Scale); link->Visibility.setValue(false); @@ -721,14 +730,14 @@ void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, break; } case GeometryBuilder::PrimitiveType::Point: { - newObject = - createVertexPrimitive(TopoDS::Vertex(builder.shape), document, "Point"); + newObject = createVertexPrimitive(TopoDS::Vertex(builder.shape), document, "Point"); break; } case GeometryBuilder::PrimitiveType::Circle: case GeometryBuilder::PrimitiveType::Arc: { - const char* name = - (builder.type == GeometryBuilder::PrimitiveType::Circle) ? "Circle" : "Arc"; + const char* name = (builder.type == GeometryBuilder::PrimitiveType::Circle) + ? "Circle" + : "Arc"; auto* p = createCirclePrimitive(TopoDS::Edge(builder.shape), document, name); if (!p) { break; @@ -741,8 +750,8 @@ void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, break; } case GeometryBuilder::PrimitiveType::Ellipse: { - newObject = - createEllipsePrimitive(TopoDS::Edge(builder.shape), document, "Ellipse"); + newObject + = createEllipsePrimitive(TopoDS::Edge(builder.shape), document, "Ellipse"); break; } case GeometryBuilder::PrimitiveType::Spline: { @@ -755,14 +764,13 @@ void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, case GeometryBuilder::PrimitiveType::PolylineFlattened: { // This creates a simple Part::Feature wrapping the wire, which is standard for // block children. - newObject = - createFlattenedPolylineFeature(TopoDS::Wire(builder.shape), "Polyline"); + newObject = createFlattenedPolylineFeature(TopoDS::Wire(builder.shape), "Polyline"); break; } case GeometryBuilder::PrimitiveType::PolylineParametric: { // This creates a Part::Compound containing line/arc segments. - newObject = - createParametricPolylineCompound(TopoDS::Wire(builder.shape), "Polyline"); + newObject + = createParametricPolylineCompound(TopoDS::Wire(builder.shape), "Polyline"); // No styling needed here, as the block's instance will control appearance. break; } @@ -779,8 +787,8 @@ void ImpExpDxfRead::ComposeParametricBlock(const std::string& blockName, newObject->Visibility.setValue(false); // Children of blocks are hidden by default // Layer and color are applied by the block itself (Part::Compound) or its children // if overridden. - ApplyGuiStyles( - static_cast(newObject)); // Apply style to the child object + ApplyGuiStyles(static_cast(newObject)); // Apply style to the child + // object childObjects.push_back(newObject); // Add to the block's main children list } } @@ -915,17 +923,18 @@ bool ImpExpDxfRead::OnReadBlock(const std::string& name, int flags) // Step 3: Check for duplicates to prevent errors. if (this->Blocks.count(name)) { - ImportError("Duplicate block name '%s' found. Ignoring subsequent definition.", - name.c_str()); + ImportError("Duplicate block name '%s' found. Ignoring subsequent definition.", name.c_str()); return SkipBlockContents(); } // Step 4: Use the temporary Block struct and Collector to parse all contents into memory. // The .emplace method is slightly more efficient here. auto& temporaryBlock = Blocks.emplace(std::make_pair(name, Block(name, flags))).first->second; - BlockDefinitionCollector blockCollector(*this, - temporaryBlock.GeometryBuilders, - temporaryBlock.Inserts); + BlockDefinitionCollector blockCollector( + *this, + temporaryBlock.GeometryBuilders, + temporaryBlock.Inserts + ); if (!ReadBlockContents()) { return false; // Abort on parsing error } @@ -935,9 +944,7 @@ bool ImpExpDxfRead::OnReadBlock(const std::string& name, int flags) return true; } -void ImpExpDxfRead::OnReadLine(const Base::Vector3d& start, - const Base::Vector3d& end, - bool /*hidden*/) +void ImpExpDxfRead::OnReadLine(const Base::Vector3d& start, const Base::Vector3d& end, bool /*hidden*/) { if (shouldSkipEntity()) { return; @@ -992,11 +999,13 @@ void ImpExpDxfRead::OnReadPoint(const Base::Vector3d& start) } -void ImpExpDxfRead::OnReadArc(const Base::Vector3d& start, - const Base::Vector3d& end, - const Base::Vector3d& center, - bool dir, - bool /*hidden*/) +void ImpExpDxfRead::OnReadArc( + const Base::Vector3d& start, + const Base::Vector3d& end, + const Base::Vector3d& center, + bool dir, + bool /*hidden*/ +) { if (shouldSkipEntity()) { return; @@ -1032,10 +1041,7 @@ void ImpExpDxfRead::OnReadArc(const Base::Vector3d& start, } -void ImpExpDxfRead::OnReadCircle(const Base::Vector3d& start, - const Base::Vector3d& center, - bool dir, - bool /*hidden*/) +void ImpExpDxfRead::OnReadCircle(const Base::Vector3d& start, const Base::Vector3d& center, bool dir, bool /*hidden*/) { if (shouldSkipEntity()) { return; @@ -1125,8 +1131,8 @@ Handle(Geom_BSplineCurve) getSplineFromPolesAndKnots(struct SplineData& sd) } Standard_Boolean periodic = sd.flag == 2; - Handle(Geom_BSplineCurve) geom = - new Geom_BSplineCurve(occpoles, occweights, occknots, occmults, sd.degree, periodic); + Handle(Geom_BSplineCurve) geom + = new Geom_BSplineCurve(occpoles, occweights, occknots, occmults, sd.degree, periodic); return geom; } @@ -1202,13 +1208,15 @@ void ImpExpDxfRead::OnReadSpline(struct SplineData& sd) } // NOLINTBEGIN(bugprone-easily-swappable-parameters) -void ImpExpDxfRead::OnReadEllipse(const Base::Vector3d& center, - double major_radius, - double minor_radius, - double rotation, - double /*start_angle*/, - double /*end_angle*/, - bool dir) +void ImpExpDxfRead::OnReadEllipse( + const Base::Vector3d& center, + double major_radius, + double minor_radius, + double rotation, + double /*start_angle*/, + double /*end_angle*/, + bool dir +) // NOLINTEND(bugprone-easily-swappable-parameters) { if (shouldSkipEntity()) { @@ -1247,10 +1255,12 @@ void ImpExpDxfRead::OnReadEllipse(const Base::Vector3d& center, Collector->AddGeometry(builder); } -void ImpExpDxfRead::OnReadText(const Base::Vector3d& point, - const double height, - const std::string& text, - const double rotation) +void ImpExpDxfRead::OnReadText( + const Base::Vector3d& point, + const double height, + const std::string& text, + const double rotation +) { if (shouldSkipEntity() || !m_importAnnotations) { return; @@ -1258,10 +1268,7 @@ void ImpExpDxfRead::OnReadText(const Base::Vector3d& point, auto* p = static_cast(document->addObject("App::FeaturePython", "Text")); if (p) { - p->addDynamicProperty("App::PropertyString", - "DxfEntityType", - "Internal", - "DXF entity type"); + p->addDynamicProperty("App::PropertyString", "DxfEntityType", "Internal", "DXF entity type"); static_cast(p->getPropertyByName("DxfEntityType"))->setValue("TEXT"); p->addDynamicProperty("App::PropertyStringList", "Text", "Data", "Text content"); @@ -1269,10 +1276,7 @@ void ImpExpDxfRead::OnReadText(const Base::Vector3d& point, std::vector text_values = {text}; static_cast(p->getPropertyByName("Text"))->setValues(text_values); - p->addDynamicProperty("App::PropertyFloat", - "DxfTextHeight", - "Internal", - "Original text height"); + p->addDynamicProperty("App::PropertyFloat", "DxfTextHeight", "Internal", "Original text height"); static_cast(p->getPropertyByName("DxfTextHeight"))->setValue(height); p->addDynamicProperty("App::PropertyPlacement", "Placement", "Base", "Object placement"); @@ -1286,10 +1290,12 @@ void ImpExpDxfRead::OnReadText(const Base::Vector3d& point, } -void ImpExpDxfRead::OnReadInsert(const Base::Vector3d& point, - const Base::Vector3d& scale, - const std::string& name, - double rotation) +void ImpExpDxfRead::OnReadInsert( + const Base::Vector3d& point, + const Base::Vector3d& scale, + const std::string& name, + double rotation +) { if (shouldSkipEntity()) { return; @@ -1302,25 +1308,22 @@ void ImpExpDxfRead::OnReadInsert(const Base::Vector3d& point, } -void ImpExpDxfRead::OnReadDimension(const Base::Vector3d& start, - const Base::Vector3d& end, - const Base::Vector3d& point, - int dimensionType, - double rotation) +void ImpExpDxfRead::OnReadDimension( + const Base::Vector3d& start, + const Base::Vector3d& end, + const Base::Vector3d& point, + int dimensionType, + double rotation +) { if (shouldSkipEntity() || !m_importAnnotations) { return; } - auto* p = - static_cast(document->addObject("App::FeaturePython", "Dimension")); + auto* p = static_cast(document->addObject("App::FeaturePython", "Dimension")); if (p) { - p->addDynamicProperty("App::PropertyString", - "DxfEntityType", - "Internal", - "DXF entity type"); - static_cast(p->getPropertyByName("DxfEntityType")) - ->setValue("DIMENSION"); + p->addDynamicProperty("App::PropertyString", "DxfEntityType", "Internal", "DXF entity type"); + static_cast(p->getPropertyByName("DxfEntityType"))->setValue("DIMENSION"); p->addDynamicProperty("App::PropertyVector", "Start", "Data", "Start point of dimension"); static_cast(p->getPropertyByName("Start"))->setValue(start); @@ -1331,17 +1334,21 @@ void ImpExpDxfRead::OnReadDimension(const Base::Vector3d& start, p->addDynamicProperty("App::PropertyVector", "Dimline", "Data", "Point on dimension line"); static_cast(p->getPropertyByName("Dimline"))->setValue(point); - p->addDynamicProperty("App::PropertyInteger", - "DxfDimensionType", - "Internal", - "Original dimension type flag"); + p->addDynamicProperty( + "App::PropertyInteger", + "DxfDimensionType", + "Internal", + "Original dimension type flag" + ); static_cast(p->getPropertyByName("DxfDimensionType")) ->setValue(dimensionType); - p->addDynamicProperty("App::PropertyAngle", - "DxfRotation", - "Internal", - "Original dimension rotation"); + p->addDynamicProperty( + "App::PropertyAngle", + "DxfRotation", + "Internal", + "Original dimension rotation" + ); // rotation is already in radians from the caller static_cast(p->getPropertyByName("DxfRotation"))->setValue(rotation); @@ -1409,13 +1416,11 @@ void ImpExpDxfRead::DrawingEntityCollector::AddGeometry(const GeometryBuilder& b break; } case GeometryBuilder::PrimitiveType::Point: { - newDocObj = - createVertexPrimitive(TopoDS::Vertex(builder.shape), Reader.document, "Point"); + newDocObj = createVertexPrimitive(TopoDS::Vertex(builder.shape), Reader.document, "Point"); break; } case GeometryBuilder::PrimitiveType::Ellipse: { - newDocObj = - createEllipsePrimitive(TopoDS::Edge(builder.shape), Reader.document, "Ellipse"); + newDocObj = createEllipsePrimitive(TopoDS::Edge(builder.shape), Reader.document, "Ellipse"); break; } case GeometryBuilder::PrimitiveType::Spline: { @@ -1448,19 +1453,24 @@ void ImpExpDxfRead::DrawingEntityCollector::AddGeometry(const GeometryBuilder& b } } -ImpExpDxfRead::Layer::Layer(const std::string& name, - ColorIndex_t color, - std::string&& lineType, - PyObject* drawingLayer) +ImpExpDxfRead::Layer::Layer( + const std::string& name, + ColorIndex_t color, + std::string&& lineType, + PyObject* drawingLayer +) : CDxfRead::Layer(name, color, std::move(lineType)) - , DraftLayerView(drawingLayer == nullptr ? Py_None - : PyObject_GetAttrString(drawingLayer, "ViewObject")) - , GroupContents(drawingLayer == nullptr - ? nullptr - : dynamic_cast( - (((App::FeaturePythonPyT*)drawingLayer) - ->getPropertyContainerPtr()) - ->getDynamicPropertyByName("Group"))) + , DraftLayerView( + drawingLayer == nullptr ? Py_None : PyObject_GetAttrString(drawingLayer, "ViewObject") + ) + , GroupContents( + drawingLayer == nullptr ? nullptr + : dynamic_cast( + (((App::FeaturePythonPyT*)drawingLayer) + ->getPropertyContainerPtr()) + ->getDynamicPropertyByName("Group") + ) + ) {} ImpExpDxfRead::Layer::~Layer() { @@ -1484,8 +1494,7 @@ void ImpExpDxfRead::Layer::FinishLayer() const } } -CDxfRead::Layer* -ImpExpDxfRead::MakeLayer(const std::string& name, ColorIndex_t color, std::string&& lineType) +CDxfRead::Layer* ImpExpDxfRead::MakeLayer(const std::string& name, ColorIndex_t color, std::string&& lineType) { if (m_preserveLayers) { // Hidden layers are implemented in the wrapup code after the entire file has been read. @@ -1503,29 +1512,31 @@ ImpExpDxfRead::MakeLayer(const std::string& name, ColorIndex_t color, std::strin layer = // NOLINTNEXTLINE(readability/nolint) // NOLINTNEXTLINE(cppcoreguidelines-pro-type-cstyle-cast) - (Base::PyObjectBase*)PyObject_CallMethod(draftModule, - "make_layer", - "s(fff)(fff)fs", - name.c_str(), - appColor.r, - appColor.g, - appColor.b, - appColor.r, - appColor.g, - appColor.b, - 2.0, - "Solid"); + (Base::PyObjectBase*)PyObject_CallMethod( + draftModule, + "make_layer", + "s(fff)(fff)fs", + name.c_str(), + appColor.r, + appColor.g, + appColor.b, + appColor.r, + appColor.g, + appColor.b, + 2.0, + "Solid" + ); } auto result = new Layer(name, color, std::move(lineType), layer); if (result->DraftLayerView != Py_None) { // Get the correct boolean value based on the user's preference. PyObject* overrideValue = m_preserveColors ? Py_True : Py_False; - PyObject_SetAttrString(result->DraftLayerView, - "OverrideLineColorChildren", - overrideValue); - PyObject_SetAttrString(result->DraftLayerView, - "OverrideShapeAppearanceChildren", - overrideValue); + PyObject_SetAttrString(result->DraftLayerView, "OverrideLineColorChildren", overrideValue); + PyObject_SetAttrString( + result->DraftLayerView, + "OverrideShapeAppearanceChildren", + overrideValue + ); } // We make our own layer class even if we could not make a layer. MoveToLayer will @@ -1585,18 +1596,19 @@ std::string ImpExpDxfRead::Deformat(const char* text) void ImpExpDxfRead::_addOriginalLayerProperty(App::DocumentObject* obj) { if (obj && m_entityAttributes.m_Layer) { - obj->addDynamicProperty("App::PropertyString", - "OriginalLayer", - "Internal", - "Layer name from the original DXF file.", - App::Property::Hidden); + obj->addDynamicProperty( + "App::PropertyString", + "OriginalLayer", + "Internal", + "Layer name from the original DXF file.", + App::Property::Hidden + ); static_cast(obj->getPropertyByName("OriginalLayer")) ->setValue(m_entityAttributes.m_Layer->Name.c_str()); } } -void ImpExpDxfRead::DrawingEntityCollector::AddObject(const TopoDS_Shape& shape, - const char* nameBase) +void ImpExpDxfRead::DrawingEntityCollector::AddObject(const TopoDS_Shape& shape, const char* nameBase) { auto pcFeature = Reader.document->addObject(nameBase); @@ -1609,8 +1621,7 @@ void ImpExpDxfRead::DrawingEntityCollector::AddObject(const TopoDS_Shape& shape, } } -void ImpExpDxfRead::DrawingEntityCollector::AddObject(App::DocumentObject* obj, - const char* /*nameBase*/) +void ImpExpDxfRead::DrawingEntityCollector::AddObject(App::DocumentObject* obj, const char* /*nameBase*/) { Reader.MoveToLayer(obj); Reader._addOriginalLayerProperty(obj); @@ -1664,8 +1675,9 @@ ImpExpDxfWrite::~ImpExpDxfWrite() = default; void ImpExpDxfWrite::setOptions() { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath(getOptionSource().c_str()); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + getOptionSource().c_str() + ); optionMaxLength = hGrp->GetFloat("maxsegmentlength", 5.0); optionExpPoints = hGrp->GetBool("ExportPoints", false); m_version = hGrp->GetInt("DxfVersionOut", 14); @@ -1784,8 +1796,10 @@ void ImpExpDxfWrite::exportShape(const TopoDS_Shape input) exportLine(adapt); } else { - Base::Console().warning("ImpExpDxf - unknown curve type: %d\n", - static_cast(adapt.GetType())); + Base::Console().warning( + "ImpExpDxf - unknown curve type: %d\n", + static_cast(adapt.GetType()) + ); } } @@ -1799,8 +1813,7 @@ void ImpExpDxfWrite::exportShape(const TopoDS_Shape input) } std::sort(duplicates.begin(), duplicates.end(), ImpExpDxfWrite::gp_PntCompare); - auto newEnd = - std::unique(duplicates.begin(), duplicates.end(), ImpExpDxfWrite::gp_PntEqual); + auto newEnd = std::unique(duplicates.begin(), duplicates.end(), ImpExpDxfWrite::gp_PntEqual); std::vector uniquePts(duplicates.begin(), newEnd); for (auto& p : uniquePts) { double point[3] = {0, 0, 0}; @@ -1964,7 +1977,8 @@ void ImpExpDxfWrite::exportBSpline(BRepAdaptor_Curve& c) s.X(), s.Y(), ePt.X(), - ePt.Y()); + ePt.Y() + ); TColgp_Array1OfPnt controlPoints(0, 1); controlPoints.SetValue(0, s); controlPoints.SetValue(1, ePt); @@ -2091,11 +2105,13 @@ void ImpExpDxfWrite::exportPolyline(BRepAdaptor_Curve& c) } } -void ImpExpDxfWrite::exportText(const char* text, - Base::Vector3d position1, - Base::Vector3d position2, - double size, - int just) +void ImpExpDxfWrite::exportText( + const char* text, + Base::Vector3d position1, + Base::Vector3d position2, + double size, + int just +) { double location1[3] = {0, 0, 0}; location1[0] = position1.x; @@ -2109,12 +2125,14 @@ void ImpExpDxfWrite::exportText(const char* text, writeText(text, location1, location2, size, just); } -void ImpExpDxfWrite::exportLinearDim(Base::Vector3d textLocn, - Base::Vector3d lineLocn, - Base::Vector3d extLine1Start, - Base::Vector3d extLine2Start, - char* dimText, - int type) +void ImpExpDxfWrite::exportLinearDim( + Base::Vector3d textLocn, + Base::Vector3d lineLocn, + Base::Vector3d extLine1Start, + Base::Vector3d extLine2Start, + char* dimText, + int type +) { double text[3] = {0, 0, 0}; text[0] = textLocn.x; @@ -2135,12 +2153,14 @@ void ImpExpDxfWrite::exportLinearDim(Base::Vector3d textLocn, writeLinearDim(text, line, ext1, ext2, dimText, type); } -void ImpExpDxfWrite::exportAngularDim(Base::Vector3d textLocn, - Base::Vector3d lineLocn, - Base::Vector3d extLine1End, - Base::Vector3d extLine2End, - Base::Vector3d apexPoint, - char* dimText) +void ImpExpDxfWrite::exportAngularDim( + Base::Vector3d textLocn, + Base::Vector3d lineLocn, + Base::Vector3d extLine1End, + Base::Vector3d extLine2End, + Base::Vector3d apexPoint, + char* dimText +) { double text[3] = {0, 0, 0}; text[0] = textLocn.x; @@ -2165,10 +2185,12 @@ void ImpExpDxfWrite::exportAngularDim(Base::Vector3d textLocn, writeAngularDim(text, line, apex, ext1, apex, ext2, dimText); } -void ImpExpDxfWrite::exportRadialDim(Base::Vector3d centerPoint, - Base::Vector3d textLocn, - Base::Vector3d arcPoint, - char* dimText) +void ImpExpDxfWrite::exportRadialDim( + Base::Vector3d centerPoint, + Base::Vector3d textLocn, + Base::Vector3d arcPoint, + char* dimText +) { double center[3] = {0, 0, 0}; center[0] = centerPoint.x; @@ -2185,10 +2207,12 @@ void ImpExpDxfWrite::exportRadialDim(Base::Vector3d centerPoint, writeRadialDim(center, text, arc, dimText); } -void ImpExpDxfWrite::exportDiametricDim(Base::Vector3d textLocn, - Base::Vector3d arcPoint1, - Base::Vector3d arcPoint2, - char* dimText) +void ImpExpDxfWrite::exportDiametricDim( + Base::Vector3d textLocn, + Base::Vector3d arcPoint1, + Base::Vector3d arcPoint2, + char* dimText +) { double text[3] = {0, 0, 0}; text[0] = textLocn.x; diff --git a/src/Mod/Import/App/dxf/ImpExpDxf.h b/src/Mod/Import/App/dxf/ImpExpDxf.h index a6ffed608a..2f67de578d 100644 --- a/src/Mod/Import/App/dxf/ImpExpDxf.h +++ b/src/Mod/Import/App/dxf/ImpExpDxf.h @@ -74,36 +74,48 @@ public: bool OnReadBlock(const std::string& name, int flags) override; void OnReadLine(const Base::Vector3d& start, const Base::Vector3d& end, bool hidden) override; void OnReadPoint(const Base::Vector3d& start) override; - void OnReadText(const Base::Vector3d& point, - double height, - const std::string& text, - double rotation) override; - void OnReadArc(const Base::Vector3d& start, - const Base::Vector3d& end, - const Base::Vector3d& center, - bool dir, - bool hidden) override; - void OnReadCircle(const Base::Vector3d& start, - const Base::Vector3d& center, - bool dir, - bool hidden) override; - void OnReadEllipse(const Base::Vector3d& center, - double major_radius, - double minor_radius, - double rotation, - double start_angle, - double end_angle, - bool dir) override; + void OnReadText( + const Base::Vector3d& point, + double height, + const std::string& text, + double rotation + ) override; + void OnReadArc( + const Base::Vector3d& start, + const Base::Vector3d& end, + const Base::Vector3d& center, + bool dir, + bool hidden + ) override; + void OnReadCircle( + const Base::Vector3d& start, + const Base::Vector3d& center, + bool dir, + bool hidden + ) override; + void OnReadEllipse( + const Base::Vector3d& center, + double major_radius, + double minor_radius, + double rotation, + double start_angle, + double end_angle, + bool dir + ) override; void OnReadSpline(struct SplineData& sd) override; - void OnReadInsert(const Base::Vector3d& point, - const Base::Vector3d& scale, - const std::string& name, - double rotation) override; - void OnReadDimension(const Base::Vector3d& start, - const Base::Vector3d& end, - const Base::Vector3d& point, - int dimensionType, - double rotation) override; + void OnReadInsert( + const Base::Vector3d& point, + const Base::Vector3d& scale, + const std::string& name, + double rotation + ) override; + void OnReadDimension( + const Base::Vector3d& start, + const Base::Vector3d& end, + const Base::Vector3d& point, + int dimensionType, + double rotation + ) override; void OnReadPolyline(std::list& /*vertices*/, int flags) override; std::string Deformat(const char* text); // Removes DXF formatting from texts @@ -179,8 +191,7 @@ protected: } return DraftModule; } - CDxfRead::Layer* - MakeLayer(const std::string& name, ColorIndex_t color, std::string&& lineType) override; + CDxfRead::Layer* MakeLayer(const std::string& name, ColorIndex_t color, std::string&& lineType) override; TopoDS_Wire BuildWireFromPolyline(std::list& vertices, int flags); void CreateFlattenedPolyline(const TopoDS_Wire& wire, const char* name); @@ -191,10 +202,7 @@ protected: class Layer: public CDxfRead::Layer { public: - Layer(const std::string& name, - ColorIndex_t color, - std::string&& lineType, - PyObject* drawingLayer); + Layer(const std::string& name, ColorIndex_t color, std::string&& lineType, PyObject* drawingLayer); Layer(const Layer&) = delete; Layer(Layer&&) = delete; void operator=(const Layer&) = delete; @@ -207,8 +215,7 @@ protected: App::PropertyLinkListHidden* GroupContents; }; - using FeaturePythonBuilder = - std::function; + using FeaturePythonBuilder = std::function; // Block management class Block { @@ -222,10 +229,12 @@ protected: // NOLINTNEXTLINE(readability/nolint) // NOLINTNEXTLINE(modernize-pass-by-value) Pass by value adds unwarranted complexity - Insert(const std::string& Name, - const Base::Vector3d& Point, - double Rotation, - const Base::Vector3d& Scale) + Insert( + const std::string& Name, + const Base::Vector3d& Point, + double Rotation, + const Base::Vector3d& Scale + ) : Point(Point) , Scale(Scale) , Name(Name) @@ -302,10 +311,12 @@ protected: // Called by OnReadInsert to either remember in a nested block or expand the block into the // drawing // This method is now obsolete with the App::Link implementation - virtual void AddInsert(const Base::Vector3d& point, - const Base::Vector3d& scale, - const std::string& name, - double rotation) = 0; + virtual void AddInsert( + const Base::Vector3d& point, + const Base::Vector3d& scale, + const std::string& name, + double rotation + ) = 0; protected: ImpExpDxfRead& Reader; @@ -325,10 +336,12 @@ protected: void AddGeometry(const GeometryBuilder& builder) override; void AddObject(App::DocumentObject* obj, const char* nameBase) override; void AddObject(FeaturePythonBuilder shapeBuilder) override; - void AddInsert(const Base::Vector3d& point, - const Base::Vector3d& scale, - const std::string& name, - double rotation) override + void AddInsert( + const Base::Vector3d& point, + const Base::Vector3d& scale, + const std::string& name, + double rotation + ) override { // This is the correct place to create top-level App::Link objects for INSERTs. @@ -376,7 +389,8 @@ protected: public: ShapeSavingEntityCollector( ImpExpDxfRead& reader, - std::map>& shapesList) + std::map>& shapesList + ) : DrawingEntityCollector(reader) , ShapesList(shapesList) {} @@ -429,7 +443,8 @@ protected: BlockDefinitionCollector( ImpExpDxfRead& reader, std::map>& buildersList, - std::map>& insertsList) + std::map>& insertsList + ) : EntityCollector(reader) , BuildersList(buildersList) , InsertsList(insertsList) @@ -455,7 +470,8 @@ protected: Reader.ImportError( "Internal logic error: Attempted to add a DocumentObject ('%s') to a block " "definition.\n", - nameBase); + nameBase + ); } void AddObject(FeaturePythonBuilder /*shapeBuilder*/) override @@ -464,13 +480,16 @@ protected: // primitives or shapes modes. } - void AddInsert(const Base::Vector3d& point, - const Base::Vector3d& scale, - const std::string& name, - double rotation) override + void AddInsert( + const Base::Vector3d& point, + const Base::Vector3d& scale, + const std::string& name, + double rotation + ) override { InsertsList[Reader.m_entityAttributes].emplace_back( - Block::Insert(name, point, rotation, scale)); + Block::Insert(name, point, rotation, scale) + ); } private: @@ -503,31 +522,41 @@ public: } void setOptions(); - void exportText(const char* text, - Base::Vector3d position1, - Base::Vector3d position2, - double size, - int just); - void exportLinearDim(Base::Vector3d textLocn, - Base::Vector3d lineLocn, - Base::Vector3d extLine1Start, - Base::Vector3d extLine2Start, - char* dimText, - int type); - void exportAngularDim(Base::Vector3d textLocn, - Base::Vector3d lineLocn, - Base::Vector3d extLine1End, - Base::Vector3d extLine2End, - Base::Vector3d apexPoint, - char* dimText); - void exportRadialDim(Base::Vector3d centerPoint, - Base::Vector3d textLocn, - Base::Vector3d arcPoint, - char* dimText); - void exportDiametricDim(Base::Vector3d textLocn, - Base::Vector3d arcPoint1, - Base::Vector3d arcPoint2, - char* dimText); + void exportText( + const char* text, + Base::Vector3d position1, + Base::Vector3d position2, + double size, + int just + ); + void exportLinearDim( + Base::Vector3d textLocn, + Base::Vector3d lineLocn, + Base::Vector3d extLine1Start, + Base::Vector3d extLine2Start, + char* dimText, + int type + ); + void exportAngularDim( + Base::Vector3d textLocn, + Base::Vector3d lineLocn, + Base::Vector3d extLine1End, + Base::Vector3d extLine2End, + Base::Vector3d apexPoint, + char* dimText + ); + void exportRadialDim( + Base::Vector3d centerPoint, + Base::Vector3d textLocn, + Base::Vector3d arcPoint, + char* dimText + ); + void exportDiametricDim( + Base::Vector3d textLocn, + Base::Vector3d arcPoint1, + Base::Vector3d arcPoint2, + char* dimText + ); static bool gp_PntEqual(gp_Pnt p1, gp_Pnt p2); diff --git a/src/Mod/Import/App/dxf/dxf.cpp b/src/Mod/Import/App/dxf/dxf.cpp index aebb91f293..3f04d2b30e 100644 --- a/src/Mod/Import/App/dxf/dxf.cpp +++ b/src/Mod/Import/App/dxf/dxf.cpp @@ -572,18 +572,16 @@ void CDxfWrite::setLayerName(std::string name) void CDxfWrite::writeLine(const double* start, const double* end) { - putLine(toVector3d(start), - toVector3d(end), - m_ssEntity, - getEntityHandle(), - m_saveModelSpaceHandle); + putLine(toVector3d(start), toVector3d(end), m_ssEntity, getEntityHandle(), m_saveModelSpaceHandle); } -void CDxfWrite::putLine(const Base::Vector3d& start, - const Base::Vector3d& end, - std::ostringstream* outStream, - const std::string& handle, - const std::string& ownerHandle) +void CDxfWrite::putLine( + const Base::Vector3d& start, + const Base::Vector3d& end, + std::ostringstream* outStream, + const std::string& handle, + const std::string& ownerHandle +) { (*outStream) << " 0" << endl; (*outStream) << "LINE" << endl; @@ -836,13 +834,15 @@ void CDxfWrite::writeCircle(const double* center, double radius) (*m_ssEntity) << radius << endl; // Radius } -void CDxfWrite::writeEllipse(const double* center, - double major_radius, - double minor_radius, - double rotation, - double start_angle, - double end_angle, - bool endIsCW) +void CDxfWrite::writeEllipse( + const double* center, + double major_radius, + double minor_radius, + double rotation, + double start_angle, + double end_angle, + bool endIsCW +) { Base::Vector3d m(major_radius * sin(rotation), major_radius * cos(rotation), 0); double ratio = minor_radius / major_radius; @@ -881,14 +881,13 @@ void CDxfWrite::writeEllipse(const double* center, (*m_ssEntity) << " 31" << endl; (*m_ssEntity) << m.z << endl; // Major Z (*m_ssEntity) << " 40" << endl; // - (*m_ssEntity) << ratio - << endl; // Ratio - // (*m_ssEntity) << "210" << endl; //extrusion dir?? - // (*m_ssEntity) << "0" << endl; - // (*m_ssEntity) << "220" << endl; - // (*m_ssEntity) << "0" << endl; - // (*m_ssEntity) << "230" << endl; - // (*m_ssEntity) << "1" << endl; + (*m_ssEntity) << ratio << endl; // Ratio + // (*m_ssEntity) << "210" << endl; //extrusion dir?? + // (*m_ssEntity) << "0" << endl; + // (*m_ssEntity) << "220" << endl; + // (*m_ssEntity) << "0" << endl; + // (*m_ssEntity) << "230" << endl; + // (*m_ssEntity) << "1" << endl; (*m_ssEntity) << " 41" << endl; (*m_ssEntity) << start_angle << endl; // Start angle (radians [0..2pi]) (*m_ssEntity) << " 42" << endl; @@ -1006,33 +1005,39 @@ void CDxfWrite::writeVertex(double x, double y, double z) (*m_ssEntity) << 0 << endl; } -void CDxfWrite::writeText(const char* text, - const double* location1, - const double* location2, - const double height, - const int horizJust) +void CDxfWrite::writeText( + const char* text, + const double* location1, + const double* location2, + const double height, + const int horizJust +) { - putText(text, - toVector3d(location1), - toVector3d(location2), - height, - horizJust, - m_ssEntity, - getEntityHandle(), - m_saveModelSpaceHandle); + putText( + text, + toVector3d(location1), + toVector3d(location2), + height, + horizJust, + m_ssEntity, + getEntityHandle(), + m_saveModelSpaceHandle + ); } //*************************** // putText // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::putText(const char* text, - const Base::Vector3d& location1, - const Base::Vector3d& location2, - const double height, - const int horizJust, - std::ostringstream* outStream, - const std::string& handle, - const std::string& ownerHandle) +void CDxfWrite::putText( + const char* text, + const Base::Vector3d& location1, + const Base::Vector3d& location2, + const double height, + const int horizJust, + std::ostringstream* outStream, + const std::string& handle, + const std::string& ownerHandle +) { (void)location2; @@ -1097,12 +1102,14 @@ void CDxfWrite::putText(const char* text, } } -void CDxfWrite::putArrow(Base::Vector3d& arrowPos, - Base::Vector3d& barb1Pos, - Base::Vector3d& barb2Pos, - std::ostringstream* outStream, - const std::string& handle, - const std::string& ownerHandle) +void CDxfWrite::putArrow( + Base::Vector3d& arrowPos, + Base::Vector3d& barb1Pos, + Base::Vector3d& barb2Pos, + std::ostringstream* outStream, + const std::string& handle, + const std::string& ownerHandle +) { (*outStream) << " 0" << endl; (*outStream) << "SOLID" << endl; @@ -1154,12 +1161,14 @@ void CDxfWrite::putArrow(Base::Vector3d& arrowPos, #define ALIGNED 0 #define HORIZONTAL 1 #define VERTICAL 2 -void CDxfWrite::writeLinearDim(const double* textMidPoint, - const double* lineDefPoint, - const double* extLine1, - const double* extLine2, - const char* dimText, - int type) +void CDxfWrite::writeLinearDim( + const double* textMidPoint, + const double* lineDefPoint, + const double* extLine1, + const double* extLine2, + const char* dimText, + int type +) { (*m_ssEntity) << " 0" << endl; (*m_ssEntity) << "DIMENSION" << endl; @@ -1241,13 +1250,15 @@ void CDxfWrite::writeLinearDim(const double* textMidPoint, //*************************** // writeAngularDim // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeAngularDim(const double* textMidPoint, - const double* lineDefPoint, - const double* startExt1, - const double* endExt1, - const double* startExt2, - const double* endExt2, - const char* dimText) +void CDxfWrite::writeAngularDim( + const double* textMidPoint, + const double* lineDefPoint, + const double* startExt1, + const double* endExt1, + const double* startExt2, + const double* endExt2, + const char* dimText +) { (*m_ssEntity) << " 0" << endl; (*m_ssEntity) << "DIMENSION" << endl; @@ -1324,23 +1335,19 @@ void CDxfWrite::writeAngularDim(const double* textMidPoint, (*m_ssEntity) << " 36" << endl; (*m_ssEntity) << lineDefPoint[2] << endl; writeDimBlockPreamble(); - writeAngularDimBlock(textMidPoint, - lineDefPoint, - startExt1, - endExt1, - startExt2, - endExt2, - dimText); + writeAngularDimBlock(textMidPoint, lineDefPoint, startExt1, endExt1, startExt2, endExt2, dimText); writeBlockTrailer(); } //*************************** // writeRadialDim // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeRadialDim(const double* centerPoint, - const double* textMidPoint, - const double* arcPoint, - const char* dimText) +void CDxfWrite::writeRadialDim( + const double* centerPoint, + const double* textMidPoint, + const double* arcPoint, + const char* dimText +) { (*m_ssEntity) << " 0" << endl; (*m_ssEntity) << "DIMENSION" << endl; @@ -1402,10 +1409,12 @@ void CDxfWrite::writeRadialDim(const double* centerPoint, //*************************** // writeDiametricDim // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeDiametricDim(const double* textMidPoint, - const double* arcPoint1, - const double* arcPoint2, - const char* dimText) +void CDxfWrite::writeDiametricDim( + const double* textMidPoint, + const double* arcPoint1, + const double* arcPoint2, + const char* dimText +) { (*m_ssEntity) << " 0" << endl; (*m_ssEntity) << "DIMENSION" << endl; @@ -1537,12 +1546,14 @@ void CDxfWrite::writeBlockTrailer() //*************************** // writeLinearDimBlock // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeLinearDimBlock(const double* textMidPoint, - const double* lineDefPoint, - const double* extLine1, - const double* extLine2, - const char* dimText, - int type) +void CDxfWrite::writeLinearDimBlock( + const double* textMidPoint, + const double* lineDefPoint, + const double* extLine1, + const double* extLine2, + const char* dimText, + int type +) { Base::Vector3d e1S(MakeVector3d(extLine1)); Base::Vector3d e2S(MakeVector3d(extLine2)); @@ -1595,14 +1606,16 @@ void CDxfWrite::writeLinearDimBlock(const double* textMidPoint, putLine(e1E, e2E, m_ssBlock, getBlockHandle(), m_saveBlkRecordHandle); - putText(dimText, - toVector3d(textMidPoint), - toVector3d(lineDefPoint), - 3.5, - 1, - m_ssBlock, - getBlockHandle(), - m_saveBlkRecordHandle); + putText( + dimText, + toVector3d(textMidPoint), + toVector3d(lineDefPoint), + 3.5, + 1, + m_ssBlock, + getBlockHandle(), + m_saveBlkRecordHandle + ); perp.Normalize(); para.Normalize(); @@ -1621,13 +1634,15 @@ void CDxfWrite::writeLinearDimBlock(const double* textMidPoint, //*************************** // writeAngularDimBlock // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeAngularDimBlock(const double* textMidPoint, - const double* lineDefPoint, - const double* startExt1, - const double* endExt1, - const double* startExt2, - const double* endExt2, - const char* dimText) +void CDxfWrite::writeAngularDimBlock( + const double* textMidPoint, + const double* lineDefPoint, + const double* startExt1, + const double* endExt1, + const double* startExt2, + const double* endExt2, + const char* dimText +) { Base::Vector3d e1S(MakeVector3d(startExt1)); // apex Base::Vector3d e2S(MakeVector3d(startExt2)); @@ -1689,14 +1704,16 @@ void CDxfWrite::writeAngularDimBlock(const double* textMidPoint, (*m_ssBlock) << " 51" << endl; (*m_ssBlock) << endAngle << endl; // end angle - putText(dimText, - toVector3d(textMidPoint), - toVector3d(textMidPoint), - 3.5, - 1, - m_ssBlock, - getBlockHandle(), - m_saveBlkRecordHandle); + putText( + dimText, + toVector3d(textMidPoint), + toVector3d(textMidPoint), + 3.5, + 1, + m_ssBlock, + getBlockHandle(), + m_saveBlkRecordHandle + ); e1.Normalize(); e2.Normalize(); @@ -1727,25 +1744,31 @@ void CDxfWrite::writeAngularDimBlock(const double* textMidPoint, //*************************** // writeRadialDimBlock // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeRadialDimBlock(const double* centerPoint, - const double* textMidPoint, - const double* arcPoint, - const char* dimText) +void CDxfWrite::writeRadialDimBlock( + const double* centerPoint, + const double* textMidPoint, + const double* arcPoint, + const char* dimText +) { - putLine(toVector3d(centerPoint), - toVector3d(arcPoint), - m_ssBlock, - getBlockHandle(), - m_saveBlkRecordHandle); + putLine( + toVector3d(centerPoint), + toVector3d(arcPoint), + m_ssBlock, + getBlockHandle(), + m_saveBlkRecordHandle + ); - putText(dimText, - toVector3d(textMidPoint), - toVector3d(textMidPoint), - 3.5, - 1, - m_ssBlock, - getBlockHandle(), - m_saveBlkRecordHandle); + putText( + dimText, + toVector3d(textMidPoint), + toVector3d(textMidPoint), + 3.5, + 1, + m_ssBlock, + getBlockHandle(), + m_saveBlkRecordHandle + ); Base::Vector3d center(MakeVector3d(centerPoint)); Base::Vector3d a(MakeVector3d(arcPoint)); @@ -1764,25 +1787,25 @@ void CDxfWrite::writeRadialDimBlock(const double* centerPoint, //*************************** // writeDiametricDimBlock // added by Wandererfan 2018 (wandererfan@gmail.com) for FreeCAD project -void CDxfWrite::writeDiametricDimBlock(const double* textMidPoint, - const double* arcPoint1, - const double* arcPoint2, - const char* dimText) +void CDxfWrite::writeDiametricDimBlock( + const double* textMidPoint, + const double* arcPoint1, + const double* arcPoint2, + const char* dimText +) { - putLine(toVector3d(arcPoint1), - toVector3d(arcPoint2), - m_ssBlock, - getBlockHandle(), - m_saveBlkRecordHandle); + putLine(toVector3d(arcPoint1), toVector3d(arcPoint2), m_ssBlock, getBlockHandle(), m_saveBlkRecordHandle); - putText(dimText, - toVector3d(textMidPoint), - toVector3d(textMidPoint), - 3.5, - 1, - m_ssBlock, - getBlockHandle(), - m_saveBlkRecordHandle); + putText( + dimText, + toVector3d(textMidPoint), + toVector3d(textMidPoint), + 3.5, + 1, + m_ssBlock, + getBlockHandle(), + m_saveBlkRecordHandle + ); Base::Vector3d a1(MakeVector3d(arcPoint1)); Base::Vector3d a2(MakeVector3d(arcPoint2)); @@ -1889,10 +1912,12 @@ void CDxfRead::Setup3DVectorAttribute(eDXFGroupCode_t x_record_type, Base::Vecto SetupScaledDoubleAttribute((eDXFGroupCode_t)(x_record_type + eYOffset), destination.y); SetupScaledDoubleAttribute((eDXFGroupCode_t)(x_record_type + eZOffset), destination.z); } -void CDxfRead::Setup3DCoordinatesIntoLists(eDXFGroupCode_t x_record_type, - list& x_destination, - list& y_destination, - list& z_destination) +void CDxfRead::Setup3DCoordinatesIntoLists( + eDXFGroupCode_t x_record_type, + list& x_destination, + list& y_destination, + list& z_destination +) { SetupScaledDoubleIntoList((eDXFGroupCode_t)(x_record_type + eXOffset), x_destination); SetupScaledDoubleIntoList((eDXFGroupCode_t)(x_record_type + eYOffset), y_destination); @@ -1904,8 +1929,10 @@ void CDxfRead::SetupScaledDoubleAttribute(eDXFGroupCode_t x_record_type, double& } void CDxfRead::SetupScaledDoubleIntoList(eDXFGroupCode_t x_record_type, list& destination) { - m_coordinate_attributes.emplace(x_record_type, - std::pair(&ProcessScaledDoubleIntoList, &destination)); + m_coordinate_attributes.emplace( + x_record_type, + std::pair(&ProcessScaledDoubleIntoList, &destination) + ); } void CDxfRead::Setup3DDirectionAttribute(eDXFGroupCode_t x_record_type, Base::Vector3d& destination) { @@ -1934,8 +1961,10 @@ void CDxfRead::ProcessScaledDouble(CDxfRead* object, void* target) double value = 0; ss >> value; if (ss.fail()) { - object->ImportError("Unable to parse value '%s', using zero as its value\n", - object->m_record_data); + object->ImportError( + "Unable to parse value '%s', using zero as its value\n", + object->m_record_data + ); } *static_cast(target) = object->mm(value); } @@ -1948,8 +1977,10 @@ void CDxfRead::ProcessScaledDoubleIntoList(CDxfRead* object, void* target) double value = 0; ss >> value; if (ss.fail()) { - object->ImportError("Unable to parse value '%s', using zero as its value\n", - object->m_record_data); + object->ImportError( + "Unable to parse value '%s', using zero as its value\n", + object->m_record_data + ); } static_cast*>(target)->push_back(object->mm(value)); } @@ -1962,8 +1993,10 @@ bool CDxfRead::ParseValue(CDxfRead* object, void* target) ss.str(object->m_record_data); ss >> *static_cast(target); if (ss.fail()) { - object->ImportError("Unable to parse value '%s', using zero as its value\n", - object->m_record_data); + object->ImportError( + "Unable to parse value '%s', using zero as its value\n", + object->m_record_data + ); *static_cast(target) = 0; return false; } @@ -2092,12 +2125,14 @@ bool CDxfRead::ReadArc() Setup3DVectorAttribute(eExtrusionDirection, extrusionDirection); ProcessAllEntityAttributes(); - OnReadArc(start_angle_degrees, - end_angle_degrees, - radius, - centre, - extrusionDirection.z, - LineTypeIsHidden()); + OnReadArc( + start_angle_degrees, + end_angle_degrees, + radius, + centre, + extrusionDirection.z, + LineTypeIsHidden() + ); return true; } @@ -2402,8 +2437,10 @@ void CDxfRead::UnsupportedFeature(const char* format, args&&... argValuess) { // NOLINTNEXTLINE(runtime/printf) std::string formattedMessage = fmt::sprintf(format, std::forward(argValuess)...); - m_stats.unsupportedFeatures[formattedMessage].emplace_back(m_current_entity_line_number, - m_current_entity_handle); + m_stats.unsupportedFeatures[formattedMessage].emplace_back( + m_current_entity_line_number, + m_current_entity_handle + ); } bool CDxfRead::get_next_record() @@ -2423,8 +2460,10 @@ bool CDxfRead::get_next_record() ++m_line; int temp = 0; if (!ParseValue(this, &temp)) { - ImportError("CDxfRead::get_next_record() Failed to get integer record type from '%s'\n", - m_record_data); + ImportError( + "CDxfRead::get_next_record() Failed to get integer record type from '%s'\n", + m_record_data + ); return false; } m_record_type = (eDXFGroupCode_t)temp; @@ -2483,11 +2522,7 @@ bool CDxfRead::ExplodePolyline(std::list& vertices, int flags) + ((endVertex->location.x - startVertex->location.x) * cot)) / 2; Base::Vector3d pc(cx, cy, (startVertex->location.z + endVertex->location.z) / 2); - OnReadArc(startVertex->location, - endVertex->location, - pc, - startVertex->bulge >= 0, - false); + OnReadArc(startVertex->location, endVertex->location, pc, startVertex->bulge >= 0, false); } else { OnReadLine(startVertex->location, endVertex->location, false); @@ -2499,12 +2534,14 @@ bool CDxfRead::ExplodePolyline(std::list& vertices, int flags) } return true; } -void CDxfRead::OnReadArc(double start_angle, - double end_angle, - double radius, - const Base::Vector3d& center, - double z_extrusion_dir, - bool hidden) +void CDxfRead::OnReadArc( + double start_angle, + double end_angle, + double radius, + const Base::Vector3d& center, + double z_extrusion_dir, + bool hidden +) { Base::Vector3d temp(center); // Calculate the start and end points of the arc @@ -2534,18 +2571,22 @@ void CDxfRead::OnReadCircle(const Base::Vector3d& center, double radius, bool hi Base::Vector3d start(center); start.x += radius; - OnReadCircle(start, - center, - false, - hidden); // false to change direction because otherwise the arc length is zero + OnReadCircle( + start, + center, + false, + hidden + ); // false to change direction because otherwise the arc length is zero } // NOLINTBEGIN(bugprone-easily-swappable-parameters) -void CDxfRead::OnReadEllipse(const Base::Vector3d& center, - const Base::Vector3d& majorAxisEnd, - double ratio, - double start_angle, - double end_angle) +void CDxfRead::OnReadEllipse( + const Base::Vector3d& center, + const Base::Vector3d& majorAxisEnd, + double ratio, + double start_angle, + double end_angle +) // NOLINTEND(bugprone-easily-swappable-parameters) { double major_radius = majorAxisEnd.Length(); @@ -2573,7 +2614,8 @@ bool CDxfRead::ReadVersion() "AC1021", "AC1024", "AC1027", - "AC1032"}; + "AC1032" + }; assert(VersionNames.size() == RNewer - ROlder - 1); get_next_record(); // Get the value for the variable @@ -2679,10 +2721,8 @@ bool CDxfRead::UTF8ToUTF8(std::string& /*encoded*/) const bool CDxfRead::GeneralToUTF8(std::string& encoded) const { Base::PyGILStateLocker lock; - PyObject* decoded = PyUnicode_Decode(encoded.c_str(), - (Py_ssize_t)encoded.length(), - m_encoding.c_str(), - "strict"); + PyObject* decoded + = PyUnicode_Decode(encoded.c_str(), (Py_ssize_t)encoded.length(), m_encoding.c_str(), "strict"); if (decoded == nullptr) { return false; } @@ -2707,16 +2747,20 @@ void CDxfRead::DoRead(const bool ignore_errors /* = false */) // Loop reading the sections. while (get_next_record()) { if (m_record_type != eObjectType) { - ImportError("Found type %d record when expecting start of a SECTION or EOF\n", - (int)m_record_type); + ImportError( + "Found type %d record when expecting start of a SECTION or EOF\n", + (int)m_record_type + ); continue; } if (IsObjectName("EOF")) { // TODO: Check for drivel beyond EOF record break; } if (!IsObjectName("SECTION")) { - ImportError("Found %s record when expecting start of a SECTION\n", - m_record_data.c_str()); + ImportError( + "Found %s record when expecting start of a SECTION\n", + m_record_data.c_str() + ); continue; } if (!ReadSection()) { @@ -2789,8 +2833,8 @@ void CDxfRead::ProcessLayerReference(CDxfRead* object, void* target) // Synthesize the Layer so we don't get the same error again. // We need to take copies of the string arguments because MakeLayer uses them as move // inputs. - object->Layers[object->m_record_data] = - object->MakeLayer(object->m_record_data, DefaultColor, std::string(DefaultLineType)); + object->Layers[object->m_record_data] + = object->MakeLayer(object->m_record_data, DefaultColor, std::string(DefaultLineType)); } *static_cast(target) = object->Layers.at(object->m_record_data); } @@ -2805,12 +2849,15 @@ bool CDxfRead::ReadEntity() EntityNormalVector.Set(0, 0, 1); Setup3DVectorAttribute(eExtrusionDirection, EntityNormalVector); SetupStringAttribute(eLinetypeName, m_entityAttributes.m_LineType); - m_coordinate_attributes.emplace(eLayerName, - std::pair(&ProcessLayerReference, &m_entityAttributes.m_Layer)); + m_coordinate_attributes.emplace( + eLayerName, + std::pair(&ProcessLayerReference, &m_entityAttributes.m_Layer) + ); SetupValueAttribute( eCoordinateSpace, - m_entityAttributes.m_paperSpace); // TODO: Ensure the stream is noboolalpha (for that - // matter ensure the stream has the "C" locale + m_entityAttributes.m_paperSpace + ); // TODO: Ensure the stream is noboolalpha (for that + // matter ensure the stream has the "C" locale SetupValueAttribute(eColor, m_entityAttributes.m_Color); m_stats.entityCounts[m_record_data]++; @@ -2880,8 +2927,7 @@ bool CDxfRead::ReadHeaderSection() std::string currentVarName = m_record_data; if (!ReadVariable()) { // If ReadVariable returns false, throw an exception with the variable name. - throw Base::Exception("Failed while reading value for HEADER variable: " - + currentVarName); + throw Base::Exception("Failed while reading value for HEADER variable: " + currentVarName); } } @@ -2947,8 +2993,7 @@ bool CDxfRead::ReadTablesSection() } get_next_record(); if (m_record_type != eName) { - ImportError("Found unexpected type %d record instead of table name\n", - (int)m_record_type); + ImportError("Found unexpected type %d record instead of table name\n", (int)m_record_type); } else if (IsObjectName("LAYER")) { if (!ReadLayerTable()) { @@ -3058,8 +3103,7 @@ bool CDxfRead::ReadLayer() Layers[layername] = MakeLayer(layername, layerColor, std::move(lineTypeName)); return true; } -CDxfRead::Layer* -CDxfRead::MakeLayer(const std::string& name, ColorIndex_t color, std::string&& lineType) +CDxfRead::Layer* CDxfRead::MakeLayer(const std::string& name, ColorIndex_t color, std::string&& lineType) { return new Layer(name, color, std::move(lineType)); } @@ -3129,9 +3173,11 @@ inline static double level(int distance, double blackLevel) } inline static Base::Color wheel(int hue, double blackLevel, double multiplier = 1.0) { - return Base::Color((float)(level(hue - 0, blackLevel) * multiplier), - (float)(level(hue - 8, blackLevel) * multiplier), - (float)(level(hue - 16, blackLevel) * multiplier)); + return Base::Color( + (float)(level(hue - 0, blackLevel) * multiplier), + (float)(level(hue - 8, blackLevel) * multiplier), + (float)(level(hue - 16, blackLevel) * multiplier) + ); } Base::Color CDxfRead::ObjectColor(ColorIndex_t index) { diff --git a/src/Mod/Import/App/dxf/dxf.h b/src/Mod/Import/App/dxf/dxf.h index 6a59406927..9f3913ffd3 100644 --- a/src/Mod/Import/App/dxf/dxf.h +++ b/src/Mod/Import/App/dxf/dxf.h @@ -9,7 +9,7 @@ #define Included_dxf_h_ #ifdef _MSC_VER -#pragma warning(disable : 4251) +# pragma warning(disable : 4251) #endif #include @@ -40,7 +40,8 @@ using ColorIndex_t = int; // DXF color index class DxfUnits { public: - using eDxfUnits_t = enum { + using eDxfUnits_t = enum + { eUnspecified = 0, // Unspecified (No units) eInches, eFeet, @@ -289,25 +290,31 @@ protected: return Base::Vector3d(coordinatesXYZ[0], coordinatesXYZ[1], coordinatesXYZ[2]); } - void putLine(const Base::Vector3d& start, - const Base::Vector3d& end, - std::ostringstream* outStream, - const std::string& handle, - const std::string& ownerHandle); - void putText(const char* text, - const Base::Vector3d& location1, - const Base::Vector3d& location2, - double height, - int horizJust, - std::ostringstream* outStream, - const std::string& handle, - const std::string& ownerHandle); - void putArrow(Base::Vector3d& arrowPos, - Base::Vector3d& barb1Pos, - Base::Vector3d& barb2Pos, - std::ostringstream* outStream, - const std::string& handle, - const std::string& ownerHandle); + void putLine( + const Base::Vector3d& start, + const Base::Vector3d& end, + std::ostringstream* outStream, + const std::string& handle, + const std::string& ownerHandle + ); + void putText( + const char* text, + const Base::Vector3d& location1, + const Base::Vector3d& location2, + double height, + int horizJust, + std::ostringstream* outStream, + const std::string& handle, + const std::string& ownerHandle + ); + void putArrow( + Base::Vector3d& arrowPos, + Base::Vector3d& barb1Pos, + Base::Vector3d& barb2Pos, + std::ostringstream* outStream, + const std::string& handle, + const std::string& ownerHandle + ); //! copy boiler plate file std::string getPlateFile(std::string fileSpec); @@ -377,13 +384,15 @@ public: void writeLine(const double* start, const double* end); void writePoint(const double*); void writeArc(const double* start, const double* end, const double* center, bool dir); - void writeEllipse(const double* center, - double major_radius, - double minor_radius, - double rotation, - double start_angle, - double end_angle, - bool endIsCW); + void writeEllipse( + const double* center, + double major_radius, + double minor_radius, + double rotation, + double start_angle, + double end_angle, + bool endIsCW + ); void writeCircle(const double* center, double radius); void writeSpline(const SplineDataOut& sd); void writeLWPolyLine(const LWPolyDataOut& pd); @@ -391,53 +400,71 @@ public: // NOLINTNEXTLINE(readability/nolint) // NOLINTNEXTLINE(readability-identifier-length) void writeVertex(double x, double y, double z); - void writeText(const char* text, - const double* location1, - const double* location2, - double height, - int horizJust); - void writeLinearDim(const double* textMidPoint, - const double* lineDefPoint, - const double* extLine1, - const double* extLine2, - const char* dimText, - int type); - void writeLinearDimBlock(const double* textMidPoint, - const double* lineDefPoint, - const double* extLine1, - const double* extLine2, - const char* dimText, - int type); - void writeAngularDim(const double* textMidPoint, - const double* lineDefPoint, - const double* startExt1, - const double* endExt1, - const double* startExt2, - const double* endExt2, - const char* dimText); - void writeAngularDimBlock(const double* textMidPoint, - const double* lineDefPoint, - const double* startExt1, - const double* endExt1, - const double* startExt2, - const double* endExt2, - const char* dimText); - void writeRadialDim(const double* centerPoint, - const double* textMidPoint, - const double* arcPoint, - const char* dimText); - void writeRadialDimBlock(const double* centerPoint, - const double* textMidPoint, - const double* arcPoint, - const char* dimText); - void writeDiametricDim(const double* textMidPoint, - const double* arcPoint1, - const double* arcPoint2, - const char* dimText); - void writeDiametricDimBlock(const double* textMidPoint, - const double* arcPoint1, - const double* arcPoint2, - const char* dimText); + void writeText( + const char* text, + const double* location1, + const double* location2, + double height, + int horizJust + ); + void writeLinearDim( + const double* textMidPoint, + const double* lineDefPoint, + const double* extLine1, + const double* extLine2, + const char* dimText, + int type + ); + void writeLinearDimBlock( + const double* textMidPoint, + const double* lineDefPoint, + const double* extLine1, + const double* extLine2, + const char* dimText, + int type + ); + void writeAngularDim( + const double* textMidPoint, + const double* lineDefPoint, + const double* startExt1, + const double* endExt1, + const double* startExt2, + const double* endExt2, + const char* dimText + ); + void writeAngularDimBlock( + const double* textMidPoint, + const double* lineDefPoint, + const double* startExt1, + const double* endExt1, + const double* startExt2, + const double* endExt2, + const char* dimText + ); + void writeRadialDim( + const double* centerPoint, + const double* textMidPoint, + const double* arcPoint, + const char* dimText + ); + void writeRadialDimBlock( + const double* centerPoint, + const double* textMidPoint, + const double* arcPoint, + const char* dimText + ); + void writeDiametricDim( + const double* textMidPoint, + const double* arcPoint1, + const double* arcPoint2, + const char* dimText + ); + void writeDiametricDimBlock( + const double* textMidPoint, + const double* arcPoint1, + const double* arcPoint2, + const char* dimText + ); void writeDimBlockPreamble(); void writeBlockTrailer(); @@ -507,7 +534,8 @@ protected: // (dxfGetOriginalColors) bool m_preserveColors = true; // Control object simplification (preserve types and individual identities) - using eEntityMergeType_t = enum { + using eEntityMergeType_t = enum + { // Merge shapes (lines, arcs, circles, etc) into a single compound object when attributes // match MergeShapes, @@ -631,18 +659,22 @@ private: bool ReadLwPolyLine(); bool ReadPolyLine(); - void OnReadArc(double start_angle, - double end_angle, - double radius, - const Base::Vector3d& center, - double z_extrusion_dir, - bool hidden); + void OnReadArc( + double start_angle, + double end_angle, + double radius, + const Base::Vector3d& center, + double z_extrusion_dir, + bool hidden + ); void OnReadCircle(const Base::Vector3d& center, double radius, bool hidden); - void OnReadEllipse(const Base::Vector3d& center, - const Base::Vector3d& majorAxisEnd, - double ratio, - double start_angle, - double end_angle); + void OnReadEllipse( + const Base::Vector3d& center, + const Base::Vector3d& majorAxisEnd, + double ratio, + double start_angle, + double end_angle + ); bool ReadInsert(); bool ReadDimension(); bool ReadUnknownEntity(); @@ -654,10 +686,12 @@ private: void Setup3DDirectionAttribute(eDXFGroupCode_t x_record_type, Base::Vector3d& destination); void SetupScaledDoubleAttribute(eDXFGroupCode_t record_type, double& destination); void SetupScaledDoubleIntoList(eDXFGroupCode_t record_type, std::list& destination); - void Setup3DCoordinatesIntoLists(eDXFGroupCode_t x_record_type, - std::list& x_destination, - std::list& y_destination, - std::list& z_destination); + void Setup3DCoordinatesIntoLists( + eDXFGroupCode_t x_record_type, + std::list& x_destination, + std::list& y_destination, + std::list& z_destination + ); void SetupStringAttribute(eDXFGroupCode_t record_type, std::string& destination); std::map> m_coordinate_attributes; static void ProcessScaledDouble(CDxfRead* object, void* target); @@ -873,8 +907,7 @@ public: { m_stats.importTimeSeconds = seconds; } - void - DoRead(bool ignore_errors = false); // this reads the file and calls the following functions + void DoRead(bool ignore_errors = false); // this reads the file and calls the following functions virtual void StartImport() {} virtual void FinishImport() @@ -901,47 +934,53 @@ public: { return SkipBlockContents(); } - virtual void - OnReadLine(const Base::Vector3d& /*start*/, const Base::Vector3d& /*end*/, bool /*hidden*/) + virtual void OnReadLine(const Base::Vector3d& /*start*/, const Base::Vector3d& /*end*/, bool /*hidden*/) {} virtual void OnReadPoint(const Base::Vector3d& /*start*/) {} - virtual void OnReadText(const Base::Vector3d& /*point*/, - const double /*height*/, - const std::string& /*text*/, - const double /*rotation*/) + virtual void OnReadText( + const Base::Vector3d& /*point*/, + const double /*height*/, + const std::string& /*text*/, + const double /*rotation*/ + ) {} - virtual void OnReadArc(const Base::Vector3d& /*start*/, - const Base::Vector3d& /*end*/, - const Base::Vector3d& /*center*/, - bool /*dir*/, - bool /*hidden*/) + virtual void OnReadArc( + const Base::Vector3d& /*start*/, + const Base::Vector3d& /*end*/, + const Base::Vector3d& /*center*/, + bool /*dir*/, + bool /*hidden*/ + ) {} - virtual void OnReadCircle(const Base::Vector3d& /*start*/, - const Base::Vector3d& /*center*/, - bool /*dir*/, - bool /*hidden*/) + virtual void OnReadCircle(const Base::Vector3d& /*start*/, const Base::Vector3d& /*center*/, bool /*dir*/, bool /*hidden*/) {} - virtual void OnReadEllipse(const Base::Vector3d& /*center*/, - double /*major_radius*/, - double /*minor_radius*/, - double /*rotation*/, - double /*start_angle*/, - double /*end_angle*/, - bool /*dir*/) + virtual void OnReadEllipse( + const Base::Vector3d& /*center*/, + double /*major_radius*/, + double /*minor_radius*/, + double /*rotation*/, + double /*start_angle*/, + double /*end_angle*/, + bool /*dir*/ + ) {} virtual void OnReadSpline(struct SplineData& /*sd*/) {} - virtual void OnReadInsert(const Base::Vector3d& /*point*/, - const Base::Vector3d& /*scale*/, - const std::string& /*name*/, - double /*rotation*/) + virtual void OnReadInsert( + const Base::Vector3d& /*point*/, + const Base::Vector3d& /*scale*/, + const std::string& /*name*/, + double /*rotation*/ + ) {} - virtual void OnReadDimension(const Base::Vector3d& /*start*/, - const Base::Vector3d& /*end*/, - const Base::Vector3d& /*point*/, - int /*dimensionType*/, - double /*rotation*/) + virtual void OnReadDimension( + const Base::Vector3d& /*start*/, + const Base::Vector3d& /*end*/, + const Base::Vector3d& /*point*/, + int /*dimensionType*/, + double /*rotation*/ + ) {} virtual void OnReadPolyline(std::list& /*vertices*/, int /*flags*/) {} diff --git a/src/Mod/Import/Gui/AppImportGuiPy.cpp b/src/Mod/Import/Gui/AppImportGuiPy.cpp index 84ee26b7b3..d9a81a3816 100644 --- a/src/Mod/Import/Gui/AppImportGuiPy.cpp +++ b/src/Mod/Import/Gui/AppImportGuiPy.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ #if defined(__MINGW32__) -#define WNT // avoid conflict with GUID +# define WNT // avoid conflict with GUID #endif #include @@ -31,8 +31,8 @@ #include #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wextra-semi" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wextra-semi" #endif #include @@ -43,7 +43,7 @@ #include #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif #include @@ -88,26 +88,38 @@ public: Module() : Py::ExtensionModule("ImportGui") { - add_keyword_method("open", - &Module::insert, - "open(string) -- Open the file and create a new document."); - add_keyword_method("insert", - &Module::insert, - "insert(string,string) -- Insert the file into the given document."); + add_keyword_method( + "open", + &Module::insert, + "open(string) -- Open the file and create a new document." + ); + add_keyword_method( + "insert", + &Module::insert, + "insert(string,string) -- Insert the file into the given document." + ); add_varargs_method("preScanDxf", &Module::preScanDxf, "preScanDxf(filepath) -> dict"); - add_varargs_method("readDXF", - &Module::readDXF, - "readDXF(filename,[document,ignore_errors,option_source]): Imports a " - "DXF file into the given document. ignore_errors is True by default."); - add_varargs_method("importOptions", - &Module::importOptions, - "importOptions(string) -- Return the import options of a file type."); - add_varargs_method("exportOptions", - &Module::exportOptions, - "exportOptions(string) -- Return the export options of a file type."); - add_keyword_method("export", - &Module::exporter, - "export(list,string) -- Export a list of objects into a single file."); + add_varargs_method( + "readDXF", + &Module::readDXF, + "readDXF(filename,[document,ignore_errors,option_source]): Imports a " + "DXF file into the given document. ignore_errors is True by default." + ); + add_varargs_method( + "importOptions", + &Module::importOptions, + "importOptions(string) -- Return the import options of a file type." + ); + add_varargs_method( + "exportOptions", + &Module::exportOptions, + "exportOptions(string) -- Return the export options of a file type." + ); + add_keyword_method( + "export", + &Module::exporter, + "export(list,string) -- Export a list of objects into a single file." + ); add_varargs_method("ocaf", &Module::ocaf, "ocaf(string) -- Browse the ocaf structure."); initialize("This module is the ImportGui module."); // register with Python } @@ -176,30 +188,34 @@ private: PyObject* merge = Py_None; PyObject* useLinkGroup = Py_None; int mode = -1; - static const std::array kwd_list {"name", - "docName", - "options", - "importHidden", - "merge", - "useLinkGroup", - "mode", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "et|sO!O!O!O!i", - kwd_list, - "utf-8", - &Name, - &DocName, - &PyDict_Type, - &pyoptions, - &PyBool_Type, - &importHidden, - &PyBool_Type, - &merge, - &PyBool_Type, - &useLinkGroup, - &mode)) { + static const std::array kwd_list { + "name", + "docName", + "options", + "importHidden", + "merge", + "useLinkGroup", + "mode", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "et|sO!O!O!O!i", + kwd_list, + "utf-8", + &Name, + &DocName, + &PyDict_Type, + &pyoptions, + &PyBool_Type, + &importHidden, + &PyBool_Type, + &merge, + &PyBool_Type, + &useLinkGroup, + &mode + )) { throw Py::Exception(); } @@ -242,27 +258,33 @@ private: } if (options.hasKey("useLinkGroup")) { ocaf.setUseLinkGroup( - static_cast(Py::Boolean(options.getItem("useLinkGroup")))); + static_cast(Py::Boolean(options.getItem("useLinkGroup"))) + ); } if (options.hasKey("useBaseName")) { ocaf.setBaseName( - static_cast(Py::Boolean(options.getItem("useBaseName")))); + static_cast(Py::Boolean(options.getItem("useBaseName"))) + ); } if (options.hasKey("importHidden")) { ocaf.setImportHiddenObject( - static_cast(Py::Boolean(options.getItem("importHidden")))); + static_cast(Py::Boolean(options.getItem("importHidden"))) + ); } if (options.hasKey("reduceObjects")) { ocaf.setReduceObjects( - static_cast(Py::Boolean(options.getItem("reduceObjects")))); + static_cast(Py::Boolean(options.getItem("reduceObjects"))) + ); } if (options.hasKey("showProgress")) { ocaf.setShowProgress( - static_cast(Py::Boolean(options.getItem("showProgress")))); + static_cast(Py::Boolean(options.getItem("showProgress"))) + ); } if (options.hasKey("expandCompound")) { ocaf.setExpandCompound( - static_cast(Py::Boolean(options.getItem("expandCompound")))); + static_cast(Py::Boolean(options.getItem("expandCompound"))) + ); } if (options.hasKey("mode")) { ocaf.setMode(static_cast(Py::Long(options.getItem("mode")))); @@ -361,8 +383,7 @@ private: return Py::None(); } - static std::map getShapeColors(App::DocumentObject* obj, - const char* subname) + static std::map getShapeColors(App::DocumentObject* obj, const char* subname) { auto vp = Gui::Application::Instance->getViewProvider(obj); if (vp) { @@ -385,13 +406,7 @@ private: const char* optionSource = nullptr; std::string defaultOptions = "User parameter:BaseApp/Preferences/Mod/Draft"; bool IgnoreErrors = true; - if (!PyArg_ParseTuple(args.ptr(), - "et|sbs", - "utf-8", - &Name, - &DocName, - &IgnoreErrors, - &optionSource)) { + if (!PyArg_ParseTuple(args.ptr(), "et|sbs", "utf-8", &Name, &DocName, &IgnoreErrors, &optionSource)) { throw Py::Exception(); } @@ -478,21 +493,23 @@ private: PyObject* pykeepPlacement = Py_None; static const std::array kwd_list {"obj", "name", "options", "exportHidden", "legacy", "keepPlacement", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "Oet|O!O!O!O!", - kwd_list, - &object, - "utf-8", - &Name, - &PyDict_Type, - &pyoptions, - &PyBool_Type, - &pyexportHidden, - &PyBool_Type, - &pylegacy, - &PyBool_Type, - &pykeepPlacement)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "Oet|O!O!O!O!", + kwd_list, + &object, + "utf-8", + &Name, + &PyDict_Type, + &pyoptions, + &PyBool_Type, + &pyexportHidden, + &PyBool_Type, + &pylegacy, + &PyBool_Type, + &pykeepPlacement + )) { throw Py::Exception(); } @@ -558,7 +575,8 @@ private: Base::FileInfo file(Utf8Name.c_str()); if (file.hasExtension({"stp", "step"})) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Part/STEP"); + "User parameter:BaseApp/Preferences/Mod/Part/STEP" + ); std::string scheme = hGrp->GetASCII("Scheme", Part::Interface::writeStepScheme()); std::list supported = Part::supportedSTEPSchemes(); if (std::ranges::find(supported, scheme) != supported.end()) { diff --git a/src/Mod/Import/Gui/Command.cpp b/src/Mod/Import/Gui/Command.cpp index 1d4703648f..b94c531670 100644 --- a/src/Mod/Import/Gui/Command.cpp +++ b/src/Mod/Import/Gui/Command.cpp @@ -54,10 +54,12 @@ void FCCmdImportReadBREP::activated(int iMsg) { Q_UNUSED(iMsg); openCommand(QT_TRANSLATE_NOOP("Command", "Read BREP")); - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), - QString(), - QString(), - QLatin1String("BREP (*.brep *.rle)")); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + QLatin1String("BREP (*.brep *.rle)") + ); if (fn.isEmpty()) { abortCommand(); return; @@ -94,10 +96,12 @@ ImportStep::ImportStep() void ImportStep::activated(int iMsg) { Q_UNUSED(iMsg); - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), - QString(), - QString(), - QLatin1String("STEP (*.stp *.step)")); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + QLatin1String("STEP (*.stp *.step)") + ); if (!fn.isEmpty()) { openCommand(QT_TRANSLATE_NOOP("Command", "Part ImportSTEP Create")); doCommand(Doc, "f = App.document().addObject(\"ImportStep\",\"ImportStep\")"); @@ -139,10 +143,12 @@ ImportIges::ImportIges() void ImportIges::activated(int iMsg) { Q_UNUSED(iMsg); - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), - QString(), - QString(), - QLatin1String("IGES (*.igs *.iges)")); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + QLatin1String("IGES (*.igs *.iges)") + ); if (!fn.isEmpty()) { openCommand(QT_TRANSLATE_NOOP("Command", "ImportIGES Create")); doCommand(Doc, "f = App.document().addObject(\"ImportIges\",\"ImportIges\")"); diff --git a/src/Mod/Import/Gui/ImportOCAFGui.cpp b/src/Mod/Import/Gui/ImportOCAFGui.cpp index 5b9a5fe5ef..3f8cd1a580 100644 --- a/src/Mod/Import/Gui/ImportOCAFGui.cpp +++ b/src/Mod/Import/Gui/ImportOCAFGui.cpp @@ -30,16 +30,15 @@ using namespace ImportGui; -ImportOCAFGui::ImportOCAFGui(Handle(TDocStd_Document) hDoc, - App::Document* pDoc, - const std::string& name) +ImportOCAFGui::ImportOCAFGui(Handle(TDocStd_Document) hDoc, App::Document* pDoc, const std::string& name) : ImportOCAF2(hDoc, pDoc, name) {} void ImportOCAFGui::applyFaceColors(Part::Feature* part, const std::vector& colors) { auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(part)); + Gui::Application::Instance->getViewProvider(part) + ); if (!vp) { return; } @@ -59,7 +58,8 @@ void ImportOCAFGui::applyFaceColors(Part::Feature* part, const std::vector& colors) { auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(part)); + Gui::Application::Instance->getViewProvider(part) + ); if (!vp) { return; } @@ -73,8 +73,7 @@ void ImportOCAFGui::applyEdgeColors(Part::Feature* part, const std::vector(Gui::Application::Instance->getViewProvider(obj)); + auto vp = dynamic_cast(Gui::Application::Instance->getViewProvider(obj)); if (!vp) { return; } @@ -95,8 +94,10 @@ void ImportOCAFGui::applyLinkColor(App::DocumentObject* obj, int index, Base::Co vp->MaterialList.set1Value(index, mat); } -void ImportOCAFGui::applyElementColors(App::DocumentObject* obj, - const std::map& colors) +void ImportOCAFGui::applyElementColors( + App::DocumentObject* obj, + const std::map& colors +) { auto vp = Gui::Application::Instance->getViewProvider(obj); if (!vp) { diff --git a/src/Mod/Import/Gui/ImportOCAFGui.h b/src/Mod/Import/Gui/ImportOCAFGui.h index 3d9ef56966..a606b00061 100644 --- a/src/Mod/Import/Gui/ImportOCAFGui.h +++ b/src/Mod/Import/Gui/ImportOCAFGui.h @@ -39,8 +39,10 @@ private: void applyFaceColors(Part::Feature* part, const std::vector& colors) override; void applyEdgeColors(Part::Feature* part, const std::vector& colors) override; void applyLinkColor(App::DocumentObject* obj, int index, Base::Color color) override; - void applyElementColors(App::DocumentObject* obj, - const std::map& colors) override; + void applyElementColors( + App::DocumentObject* obj, + const std::map& colors + ) override; }; } // namespace ImportGui diff --git a/src/Mod/Import/Gui/OCAFBrowser.cpp b/src/Mod/Import/Gui/OCAFBrowser.cpp index c485b94d2f..9ee3935c1d 100644 --- a/src/Mod/Import/Gui/OCAFBrowser.cpp +++ b/src/Mod/Import/Gui/OCAFBrowser.cpp @@ -109,8 +109,8 @@ void OCAFBrowser::load(const TDF_Label& label, QTreeWidgetItem* item, const QStr Handle(TDataStd_Name) name; if (label.FindAttribute(TDataStd_Name::GetID(), name)) { - QString text = - QStringLiteral("%1 %2").arg(str, QString::fromUtf8(toString(name->Get()).c_str())); + QString text + = QStringLiteral("%1 %2").arg(str, QString::fromUtf8(toString(name->Get()).c_str())); item->setText(0, text); } diff --git a/src/Mod/Import/Gui/PreCompiled.h b/src/Mod/Import/Gui/PreCompiled.h index 7e06dc0a0b..9bac7510fb 100644 --- a/src/Mod/Import/Gui/PreCompiled.h +++ b/src/Mod/Import/Gui/PreCompiled.h @@ -40,7 +40,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // OpenCasCade Base diff --git a/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp b/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp index 0b40cf2a2a..91fc3e4858 100644 --- a/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp +++ b/src/Mod/Import/Gui/dxf/ImpExpDxfGui.cpp @@ -26,7 +26,7 @@ #include #if OCC_VERSION_HEX < 0x070600 -#include +# include #endif #include #include @@ -173,7 +173,8 @@ int ImpExpDxfReadGui::GetDrawStyle() const // starts with dot : return dotted std::basic_regex("^dot", std::regex::icase), // dash & dot or center/centre/divide/phantom : return DashDot - std::basic_regex("dot.*dash|dash.*dot|^cent(er|re)|^divide|^phantom", std::regex::icase)}; + std::basic_regex("dot.*dash|dash.*dot|^cent(er|re)|^divide|^phantom", std::regex::icase) + }; // Some line type names can match several patterns, in particular dotdash can also match ^dot // and dashdot can match ^dash Rather than code the latter patterns to forbid subsequent "dash" // or "dot" so they are mutually exclusive, we just match the more specific pattern, which is diff --git a/src/Mod/Import/ImportGlobal.h b/src/Mod/Import/ImportGlobal.h index 2338e90701..1a628faedf 100644 --- a/src/Mod/Import/ImportGlobal.h +++ b/src/Mod/Import/ImportGlobal.h @@ -25,25 +25,25 @@ #include #ifndef IMPORT_GLOBAL_H -#define IMPORT_GLOBAL_H +# define IMPORT_GLOBAL_H // Import -#ifndef ImportExport -#ifdef Import_EXPORTS -#define ImportExport FREECAD_DECL_EXPORT -#else -#define ImportExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef ImportExport +# ifdef Import_EXPORTS +# define ImportExport FREECAD_DECL_EXPORT +# else +# define ImportExport FREECAD_DECL_IMPORT +# endif +# endif // ImportGui -#ifndef ImportGuiExport -#ifdef ImportGui_EXPORTS -#define ImportGuiExport FREECAD_DECL_EXPORT -#else -#define ImportGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef ImportGuiExport +# ifdef ImportGui_EXPORTS +# define ImportGuiExport FREECAD_DECL_EXPORT +# else +# define ImportGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // IMPORT_GLOBAL_H diff --git a/src/Mod/Inspection/App/InspectionFeature.cpp b/src/Mod/Inspection/App/InspectionFeature.cpp index 1ea78c1b31..0ec5affa3a 100644 --- a/src/Mod/Inspection/App/InspectionFeature.cpp +++ b/src/Mod/Inspection/App/InspectionFeature.cpp @@ -153,9 +153,11 @@ public: , _transform(mat) { Base::BoundBox3f clBBMesh = _pclMesh->GetBoundBox().Transformed(mat); - Rebuild(std::max((unsigned long)(clBBMesh.LengthX() / fGridLen), 1), - std::max((unsigned long)(clBBMesh.LengthY() / fGridLen), 1), - std::max((unsigned long)(clBBMesh.LengthZ() / fGridLen), 1)); + Rebuild( + std::max((unsigned long)(clBBMesh.LengthX() / fGridLen), 1), + std::max((unsigned long)(clBBMesh.LengthY() / fGridLen), 1), + std::max((unsigned long)(clBBMesh.LengthZ() / fGridLen), 1) + ); } void Validate(const MeshCore::MeshKernel& kernel) override @@ -186,10 +188,12 @@ protected: return _pclMesh->CountFacets(); } - void Pos(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const + void Pos( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const { rulX = (unsigned long)((rclPoint.x - _fMinX) / _fGridLenX); rulY = (unsigned long)((rclPoint.y - _fMinY) / _fGridLenY); @@ -291,8 +295,8 @@ InspectNominalMesh::InspectNominalMesh(const Mesh::MeshObject& rMesh, float offs Base::BoundBox3f box = _mesh.GetBoundBox().Transformed(rMesh.getTransform()); // estimate the minimum allowed grid length - float fMinGridLen = - (float)pow((box.LengthX() * box.LengthY() * box.LengthZ() / fMaxGridElements), 0.3333f); + float fMinGridLen + = (float)pow((box.LengthX() * box.LengthY() * box.LengthZ() / fMaxGridElements), 0.3333f); float fGridLen = 5.0f * MeshCore::MeshAlgorithm(_mesh).GetAverageEdgeLength(); // We want to avoid to get too small grid elements otherwise building up the grid structure @@ -363,8 +367,8 @@ InspectNominalFastMesh::InspectNominalFastMesh(const Mesh::MeshObject& rMesh, fl Base::BoundBox3f box = kernel.GetBoundBox().Transformed(rMesh.getTransform()); // estimate the minimum allowed grid length - float fMinGridLen = - (float)pow((box.LengthX() * box.LengthY() * box.LengthZ() / fMaxGridElements), 0.3333f); + float fMinGridLen + = (float)pow((box.LengthX() * box.LengthY() * box.LengthZ() / fMaxGridElements), 0.3333f); float fGridLen = 5.0f * MeshCore::MeshAlgorithm(kernel).GetAverageEdgeLength(); // We want to avoid to get too small grid elements otherwise building up the grid structure @@ -701,9 +705,7 @@ namespace Inspection struct DistanceInspection { - DistanceInspection(float radius, - InspectActualGeometry* a, - std::vector n) + DistanceInspection(float radius, InspectActualGeometry* a, std::vector n) : radius(radius) , actual(a) , nominal(n) @@ -843,7 +845,7 @@ App::DocumentObjectExecReturn* Feature::execute() // clang-format on #if 0 -#if 1 // test with some huge data sets +# if 1 // test with some huge data sets std::vector index(actual->countPoints()); std::generate(index.begin(), index.end(), Base::iotaGen(0)); DistanceInspection check(this->SearchRadius.getValue(), actual, inspectNominal); @@ -863,7 +865,7 @@ App::DocumentObjectExecReturn* Feature::execute() std::vector vals; vals.insert(vals.end(), future.begin(), future.end()); -#else +# else DistanceInspection insp(this->SearchRadius.getValue(), actual, inspectNominal); unsigned long count = actual->countPoints(); std::stringstream str; @@ -876,7 +878,7 @@ App::DocumentObjectExecReturn* Feature::execute() vals[index] = fMinDist; seq.next(); } -#endif +# endif Distances.setValues(vals); @@ -934,21 +936,25 @@ App::DocumentObjectExecReturn* Feature::execute() std::iota(index.begin(), index.end(), 0); // Perform map-reduce operation : compute distances and update sum of squares for RMS // computation - QFuture future = - QtConcurrent::mappedReduced(index, fMap, &DistanceInspectionRMS::operator+=); + QFuture future + = QtConcurrent::mappedReduced(index, fMap, &DistanceInspectionRMS::operator+=); // Setup progress bar Base::FutureWatcherProgress progress("Inspecting...", actual->countPoints()); QFutureWatcher watcher; - QObject::connect(&watcher, - &QFutureWatcher::progressValueChanged, - &progress, - &Base::FutureWatcherProgress::progressValueChanged); + QObject::connect( + &watcher, + &QFutureWatcher::progressValueChanged, + &progress, + &Base::FutureWatcherProgress::progressValueChanged + ); // Keep UI responsive during computation QEventLoop loop; - QObject::connect(&watcher, - &QFutureWatcher::finished, - &loop, - &QEventLoop::quit); + QObject::connect( + &watcher, + &QFutureWatcher::finished, + &loop, + &QEventLoop::quit + ); watcher.setFuture(future); loop.exec(); res = future.result(); @@ -964,11 +970,13 @@ App::DocumentObjectExecReturn* Feature::execute() } } - Base::Console().message("RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n", - this->Label.getValue(), - -this->SearchRadius.getValue(), - this->SearchRadius.getValue(), - res.getRMS()); + Base::Console().message( + "RMS value for '%s' with search radius [%.4f,%.4f] is: %.4f\n", + this->Label.getValue(), + -this->SearchRadius.getValue(), + this->SearchRadius.getValue(), + res.getRMS() + ); Distances.setValues(vals); #endif diff --git a/src/Mod/Inspection/Gui/Command.cpp b/src/Mod/Inspection/Gui/Command.cpp index c16a7fcc08..1fc173e60b 100644 --- a/src/Mod/Inspection/Gui/Command.cpp +++ b/src/Mod/Inspection/Gui/Command.cpp @@ -90,9 +90,12 @@ void CmdInspectElement::activated(int) viewer->setRedirectToSceneGraph(true); viewer->setSelectionEnabled(false); viewer->setEditingCursor( - QCursor(Gui::BitmapFactory().pixmapFromSvg("inspect_pipette", QSize(32, 32)), 4, 29)); - viewer->addEventCallback(SoButtonEvent::getClassTypeId(), - InspectionGui::ViewProviderInspection::inspectCallback); + QCursor(Gui::BitmapFactory().pixmapFromSvg("inspect_pipette", QSize(32, 32)), 4, 29) + ); + viewer->addEventCallback( + SoButtonEvent::getClassTypeId(), + InspectionGui::ViewProviderInspection::inspectCallback + ); } } diff --git a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp index 21150f79c0..088b9d05cf 100644 --- a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp +++ b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp @@ -70,16 +70,20 @@ PROPERTY_SOURCE(InspectionGui::ViewProviderInspection, Gui::ViewProviderDocument ViewProviderInspection::ViewProviderInspection() { - ADD_PROPERTY_TYPE(OutsideGrayed, - (false), - "", - (App::PropertyType)(App::Prop_Output | App::Prop_Hidden), - ""); - ADD_PROPERTY_TYPE(PointSize, - (1.0), - "Display", - (App::PropertyType)(App::Prop_None /*App::Prop_Hidden*/), - ""); + ADD_PROPERTY_TYPE( + OutsideGrayed, + (false), + "", + (App::PropertyType)(App::Prop_Output | App::Prop_Hidden), + "" + ); + ADD_PROPERTY_TYPE( + PointSize, + (1.0), + "Display", + (App::PropertyType)(App::Prop_None /*App::Prop_Hidden*/), + "" + ); PointSize.setConstraints(&floatRange); pcColorRoot = new SoSeparator(); @@ -123,12 +127,14 @@ ViewProviderInspection::~ViewProviderInspection() Base::Console().destructorError( "ViewProviderInspection", "ViewProviderInspection::deleteColorBar() threw an exception: %s\n", - e.what()); + e.what() + ); } catch (...) { Base::Console().destructorError( "ViewProviderInspection", - "ViewProviderInspection destructor threw an unknown exception"); + "ViewProviderInspection destructor threw an unknown exception" + ); } } @@ -191,8 +197,8 @@ void ViewProviderInspection::attach(App::DocumentObject* pcFeat) addDisplayMaskMode(pcColorShadedRoot, "ColorShaded"); // Check for an already existing color bar - Gui::SoFCColorBar* pcBar = - ((Gui::SoFCColorBar*)findFrontRootOfType(Gui::SoFCColorBar::getClassTypeId())); + Gui::SoFCColorBar* pcBar + = ((Gui::SoFCColorBar*)findFrontRootOfType(Gui::SoFCColorBar::getClassTypeId())); if (pcBar) { float fMin = pcColorBar->getMinValue(); float fMax = pcColorBar->getMaxValue(); @@ -243,8 +249,10 @@ bool ViewProviderInspection::setupLines(const Data::ComplexGeoData* data) return true; } -bool ViewProviderInspection::setupPoints(const Data::ComplexGeoData* data, - App::PropertyContainer* container) +bool ViewProviderInspection::setupPoints( + const Data::ComplexGeoData* data, + App::PropertyContainer* container +) { std::vector points; std::vector normals; @@ -256,12 +264,12 @@ bool ViewProviderInspection::setupPoints(const Data::ComplexGeoData* data, } normals.reserve(normals_d.size()); - std::transform(normals_d.cbegin(), - normals_d.cend(), - std::back_inserter(normals), - [](const Base::Vector3d& p) { - return Base::toVector(p); - }); + std::transform( + normals_d.cbegin(), + normals_d.cend(), + std::back_inserter(normals), + [](const Base::Vector3d& p) { return Base::toVector(p); } + ); // If getPoints() doesn't deliver normals check a second property if (normals.empty() && container) { @@ -346,10 +354,10 @@ void ViewProviderInspection::updateData(const App::Property* prop) { // set to the expected size if (prop->isDerivedFrom()) { - App::GeoFeature* object = - static_cast(prop)->getValue(); - const App::PropertyComplexGeoData* propData = - object ? object->getPropertyOfGeometry() : nullptr; + App::GeoFeature* object + = static_cast(prop)->getValue(); + const App::PropertyComplexGeoData* propData = object ? object->getPropertyOfGeometry() + : nullptr; if (propData) { Gui::coinRemoveAllChildren(this->pcLinkRoot); @@ -401,13 +409,14 @@ void ViewProviderInspection::setDistances() SoDebugError::post( "ViewProviderInspection::setDistances", "Property 'Distances' has type %s (Inspection::PropertyDistanceList was expected)", - pDistances->getTypeId().getName()); + pDistances->getTypeId().getName() + ); return; } // distance values - const std::vector& fValues = - static_cast(pDistances)->getValues(); + const std::vector& fValues + = static_cast(pDistances)->getValues(); if ((int)fValues.size() != this->pcCoords->point.getNum()) { pcMatBinding->value = SoMaterialBinding::OVERALL; return; @@ -496,12 +505,13 @@ public: if (!widget.isNull()) { QList flags = widget->findChildren(); if (!flags.isEmpty()) { - int ret = - QMessageBox::question(Gui::getMainWindow(), - QObject::tr("Remove annotations"), - QObject::tr("Do you want to remove all annotations?"), - QMessageBox::Yes, - QMessageBox::No); + int ret = QMessageBox::question( + Gui::getMainWindow(), + QObject::tr("Remove annotations"), + QObject::tr("Do you want to remove all annotations?"), + QMessageBox::Yes, + QMessageBox::No + ); if (ret == QMessageBox::Yes) { for (auto it : flags) { it->deleteLater(); @@ -513,8 +523,7 @@ public: this->deleteLater(); } - static void - addFlag(Gui::View3DInventorViewer* view, const QString& text, const SoPickedPoint* point) + static void addFlag(Gui::View3DInventorViewer* view, const QString& text, const SoPickedPoint* point) { Gui::Flag* flag = new Gui::Flag; QPalette p; @@ -524,8 +533,9 @@ public: flag->setText(text); flag->setOrigin(point->getPoint()); Gui::GLFlagWindow* flags = nullptr; - std::list glItems = - view->getGraphicsItemsOfType(Gui::GLFlagWindow::getClassTypeId()); + std::list glItems = view->getGraphicsItemsOfType( + Gui::GLFlagWindow::getClassTypeId() + ); if (glItems.empty()) { flags = new Gui::GLFlagWindow(view); view->addGraphicsItem(flags); @@ -552,8 +562,7 @@ void ViewProviderInspection::inspectCallback(void* ud, SoEventCallback* n) // node n->getAction()->setHandled(); n->setHandled(); - if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 - && mbe->getState() == SoButtonEvent::UP) { + if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::UP) { n->setHandled(); // context-menu QMenu menu; @@ -568,8 +577,10 @@ void ViewProviderInspection::inspectCallback(void* ud, SoEventCallback* n) else if (cl == id) { // post an event to a proxy object to make sure to avoid problems // when opening a modal dialog - QApplication::postEvent(new ViewProviderProxyObject(view->getGLWidget()), - new QEvent(QEvent::User)); + QApplication::postEvent( + new ViewProviderProxyObject(view->getGLWidget()), + new QEvent(QEvent::User) + ); view->setEditing(false); view->getWidget()->setCursor(QCursor(Qt::ArrowCursor)); view->setRedirectToSceneGraph(false); @@ -648,13 +659,15 @@ float calcArea(const SbVec3f& v1, const SbVec3f& v2, const SbVec3f& v3) return a.cross(b).length() / 2.0f; } -bool calcWeights(const SbVec3f& v1, - const SbVec3f& v2, - const SbVec3f& v3, - const SbVec3f& p, - float& w0, - float& w1, - float& w2) +bool calcWeights( + const SbVec3f& v1, + const SbVec3f& v2, + const SbVec3f& v3, + const SbVec3f& p, + float& w0, + float& w1, + float& w2 +) { float fAreaABC = calcArea(v1, v2, v3); float fAreaPBC = calcArea(p, v2, v3); @@ -678,8 +691,9 @@ QString ViewProviderInspection::inspectDistance(const SoPickedPoint* pp) const const SoFaceDetail* facedetail = static_cast(detail); App::Property* pDistance = this->pcObject->getPropertyByName("Distances"); if (pDistance && pDistance->is()) { - Inspection::PropertyDistanceList* dist = - static_cast(pDistance); + Inspection::PropertyDistanceList* dist = static_cast( + pDistance + ); int index1 = facedetail->getPoint(0)->getCoordinateIndex(); int index2 = facedetail->getPoint(1)->getCoordinateIndex(); int index3 = facedetail->getPoint(2)->getCoordinateIndex(); @@ -693,8 +707,7 @@ QString ViewProviderInspection::inspectDistance(const SoPickedPoint* pp) const if (fVal1 > fSearchRadius || fVal2 > fSearchRadius || fVal3 > fSearchRadius) { info = QObject::tr("Distance: > %1").arg(fSearchRadius); } - else if (fVal1 < -fSearchRadius || fVal2 < -fSearchRadius - || fVal3 < -fSearchRadius) { + else if (fVal1 < -fSearchRadius || fVal2 < -fSearchRadius || fVal3 < -fSearchRadius) { info = QObject::tr("Distance: < %1").arg(-fSearchRadius); } else { @@ -705,8 +718,7 @@ QString ViewProviderInspection::inspectDistance(const SoPickedPoint* pp) const SoPath* selectionPath = searchAction.getPath(); if (selectionPath) { - SoCoordinate3* coords = - static_cast(selectionPath->getTail()); + SoCoordinate3* coords = static_cast(selectionPath->getTail()); const SbVec3f& v1 = coords->point[index1]; const SbVec3f& v2 = coords->point[index2]; const SbVec3f& v3 = coords->point[index3]; @@ -729,8 +741,9 @@ QString ViewProviderInspection::inspectDistance(const SoPickedPoint* pp) const int index = pointdetail->getCoordinateIndex(); App::Property* prop = this->pcObject->getPropertyByName("Distances"); if (prop && prop->is()) { - Inspection::PropertyDistanceList* dist = - static_cast(prop); + Inspection::PropertyDistanceList* dist = static_cast( + prop + ); float fVal = (*dist)[index]; info = QObject::tr("Distance: %1").arg(fVal); } diff --git a/src/Mod/Inspection/Gui/VisualInspection.cpp b/src/Mod/Inspection/Gui/VisualInspection.cpp index e77e4abbdf..cc74fc1e4a 100644 --- a/src/Mod/Inspection/Gui/VisualInspection.cpp +++ b/src/Mod/Inspection/Gui/VisualInspection.cpp @@ -82,18 +82,14 @@ VisualInspection::VisualInspection(QWidget* parent, Qt::WindowFlags fl) , ui(new Ui_VisualInspection) { ui->setupUi(this); - connect(ui->treeWidgetActual, - &QTreeWidget::itemClicked, - this, - &VisualInspection::onActivateItem); - connect(ui->treeWidgetNominal, - &QTreeWidget::itemClicked, - this, - &VisualInspection::onActivateItem); - connect(ui->buttonBox, - &QDialogButtonBox::helpRequested, - Gui::getMainWindow(), - &Gui::MainWindow::whatsThis); + connect(ui->treeWidgetActual, &QTreeWidget::itemClicked, this, &VisualInspection::onActivateItem); + connect(ui->treeWidgetNominal, &QTreeWidget::itemClicked, this, &VisualInspection::onActivateItem); + connect( + ui->buttonBox, + &QDialogButtonBox::helpRequested, + Gui::getMainWindow(), + &Gui::MainWindow::whatsThis + ); // FIXME: Not used yet ui->textLabel2->hide(); @@ -157,7 +153,8 @@ VisualInspection::~VisualInspection() void VisualInspection::loadSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Inspection/Inspection"); + "User parameter:BaseApp/Preferences/Mod/Inspection/Inspection" + ); double searchDistance = ui->searchRadius->value().getValue(); searchDistance = handle->GetFloat("SearchDistance", searchDistance); @@ -171,7 +168,8 @@ void VisualInspection::loadSettings() void VisualInspection::saveSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Inspection/Inspection"); + "User parameter:BaseApp/Preferences/Mod/Inspection/Inspection" + ); double searchDistance = ui->searchRadius->value().getValue(); handle->SetFloat("SearchDistance", searchDistance); @@ -236,19 +234,23 @@ void VisualInspection::accept() doc->openCommand(QT_TRANSLATE_NOOP("Command", "Visual Inspection")); // create a group - Gui::Command::runCommand(Gui::Command::App, - "App_activeDocument___InspectionGroup=App.ActiveDocument." - "addObject(\"Inspection::Group\",\"Inspection\")"); + Gui::Command::runCommand( + Gui::Command::App, + "App_activeDocument___InspectionGroup=App.ActiveDocument." + "addObject(\"Inspection::Group\",\"Inspection\")" + ); // for each actual geometry create an inspection feature for (QTreeWidgetItemIterator it(ui->treeWidgetActual); *it; it++) { SingleSelectionItem* sel = (SingleSelectionItem*)*it; if (sel->checkState(0) == Qt::Checked) { QString actualName = sel->data(0, Qt::UserRole).toString(); - Gui::Command::doCommand(Gui::Command::App, - "App_activeDocument___InspectionGroup.newObject(" - "\"Inspection::Feature\",\"%s_Inspect\")", - (const char*)actualName.toLatin1()); + Gui::Command::doCommand( + Gui::Command::App, + "App_activeDocument___InspectionGroup.newObject(" + "\"Inspection::Feature\",\"%s_Inspect\")", + (const char*)actualName.toLatin1() + ); Gui::Command::doCommand( Gui::Command::App, "App.ActiveDocument.ActiveObject.Actual=App.ActiveDocument.%s\n" @@ -257,17 +259,22 @@ void VisualInspection::accept() "App.ActiveDocument.ActiveObject.Thickness=%.3f\n", (const char*)actualName.toLatin1(), searchRadius, - thickness); + thickness + ); for (const auto& it : nominalNames) { - Gui::Command::doCommand(Gui::Command::App, - "App_activeDocument___activeObject___Nominals.append(" - "App.ActiveDocument.%s)\n", - (const char*)it.toLatin1()); + Gui::Command::doCommand( + Gui::Command::App, + "App_activeDocument___activeObject___Nominals.append(" + "App.ActiveDocument.%s)\n", + (const char*)it.toLatin1() + ); } - Gui::Command::doCommand(Gui::Command::App, - "App.ActiveDocument.ActiveObject.Nominals=App_" - "activeDocument___activeObject___Nominals\n" - "del App_activeDocument___activeObject___Nominals\n"); + Gui::Command::doCommand( + Gui::Command::App, + "App.ActiveDocument.ActiveObject.Nominals=App_" + "activeDocument___activeObject___Nominals\n" + "del App_activeDocument___activeObject___Nominals\n" + ); } } @@ -283,7 +290,8 @@ void VisualInspection::accept() Gui::Command::doCommand( Gui::Command::App, "Gui.ActiveDocument.getObject(\"%s\").Visibility=False", - (const char*)sel->data(0, Qt::UserRole).toString().toLatin1()); + (const char*)sel->data(0, Qt::UserRole).toString().toLatin1() + ); } } @@ -293,7 +301,8 @@ void VisualInspection::accept() Gui::Command::doCommand( Gui::Command::App, "Gui.ActiveDocument.getObject(\"%s\").Visibility=False", - (const char*)sel->data(0, Qt::UserRole).toString().toLatin1()); + (const char*)sel->data(0, Qt::UserRole).toString().toLatin1() + ); } } } diff --git a/src/Mod/Inspection/InspectionGlobal.h b/src/Mod/Inspection/InspectionGlobal.h index 8f497dfa69..20f4e29ca5 100644 --- a/src/Mod/Inspection/InspectionGlobal.h +++ b/src/Mod/Inspection/InspectionGlobal.h @@ -25,25 +25,25 @@ #include #ifndef INSPECTION_GLOBAL_H -#define INSPECTION_GLOBAL_H +# define INSPECTION_GLOBAL_H // Inspection -#ifndef InspectionExport -#ifdef Inspection_EXPORTS -#define InspectionExport FREECAD_DECL_EXPORT -#else -#define InspectionExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef InspectionExport +# ifdef Inspection_EXPORTS +# define InspectionExport FREECAD_DECL_EXPORT +# else +# define InspectionExport FREECAD_DECL_IMPORT +# endif +# endif // InspectionGui -#ifndef InspectionGuiExport -#ifdef InspectionGui_EXPORTS -#define InspectionGuiExport FREECAD_DECL_EXPORT -#else -#define InspectionGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef InspectionGuiExport +# ifdef InspectionGui_EXPORTS +# define InspectionGuiExport FREECAD_DECL_EXPORT +# else +# define InspectionGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // INSPECTION_GLOBAL_H diff --git a/src/Mod/JtReader/App/AppJtReaderPy.cpp b/src/Mod/JtReader/App/AppJtReaderPy.cpp index b4759d15b2..53070b825f 100644 --- a/src/Mod/JtReader/App/AppJtReaderPy.cpp +++ b/src/Mod/JtReader/App/AppJtReaderPy.cpp @@ -51,18 +51,24 @@ public: Module() : Py::ExtensionModule("JtReader") { - add_varargs_method("read", - &Module::read, - "Read the mesh from a JT file and return a mesh object."); - add_varargs_method("open", - &Module::open, - "open(string)\n" - "Create a new document and load the JT file into\n" - "the document."); - add_varargs_method("insert", - &Module::importer, - "insert(string|mesh,[string])\n" - "Load or insert a JT file into the given or active document."); + add_varargs_method( + "read", + &Module::read, + "Read the mesh from a JT file and return a mesh object." + ); + add_varargs_method( + "open", + &Module::open, + "open(string)\n" + "Create a new document and load the JT file into\n" + "the document." + ); + add_varargs_method( + "insert", + &Module::importer, + "insert(string|mesh,[string])\n" + "Load or insert a JT file into the given or active document." + ); initialize("This module is the JtReader module."); } @@ -104,7 +110,8 @@ private: App::Document* doc = App::GetApplication().newDocument(); std::string objname = file.fileNamePure(); auto iv = dynamic_cast( - doc->addObject("App::InventorObject", objname.c_str())); + doc->addObject("App::InventorObject", objname.c_str()) + ); iv->Buffer.setValue(jtReader.getOutput()); iv->purgeTouched(); #endif @@ -140,7 +147,8 @@ private: std::string objname = file.fileNamePure(); auto iv = dynamic_cast( - doc->addObject("App::InventorObject", objname.c_str())); + doc->addObject("App::InventorObject", objname.c_str()) + ); iv->Buffer.setValue(jtReader.getOutput()); iv->purgeTouched(); #endif diff --git a/src/Mod/JtReader/App/JrJt/GUID.h b/src/Mod/JtReader/App/JrJt/GUID.h index c5c5511c79..419f2b753a 100644 --- a/src/Mod/JtReader/App/JrJt/GUID.h +++ b/src/Mod/JtReader/App/JrJt/GUID.h @@ -42,17 +42,19 @@ struct GUID { GUID() {}; - GUID(uint32_t a1, - uint16_t b1, - uint16_t b2, - uint8_t c1, - uint8_t c2, - uint8_t c3, - uint8_t c4, - uint8_t c5, - uint8_t c6, - uint8_t c7, - uint8_t c8) + GUID( + uint32_t a1, + uint16_t b1, + uint16_t b2, + uint8_t c1, + uint8_t c2, + uint8_t c3, + uint8_t c4, + uint8_t c5, + uint8_t c6, + uint8_t c7, + uint8_t c8 + ) : _A1(a1) , _B1(b1) , _B2(b2) diff --git a/src/Mod/JtReader/App/JrJt/JtReader.cpp b/src/Mod/JtReader/App/JrJt/JtReader.cpp index e2f41f7309..1414be4d44 100644 --- a/src/Mod/JtReader/App/JrJt/JtReader.cpp +++ b/src/Mod/JtReader/App/JrJt/JtReader.cpp @@ -19,17 +19,19 @@ using namespace std; -const GUID JtReader::TriStripSetShapeLODElement_ID(0x10dd10ab, - 0x2ac8, - 0x11d1, - 0x9b, - 0x6b, - 0x0, - 0x80, - 0xc7, - 0xbb, - 0x59, - 0x97); +const GUID JtReader::TriStripSetShapeLODElement_ID( + 0x10dd10ab, + 0x2ac8, + 0x11d1, + 0x9b, + 0x6b, + 0x0, + 0x80, + 0xc7, + 0xbb, + 0x59, + 0x97 +); JtReader::JtReader() {} diff --git a/src/Mod/JtReader/App/JtReader.cpp b/src/Mod/JtReader/App/JtReader.cpp index c1a22c929a..49c7ac3851 100644 --- a/src/Mod/JtReader/App/JtReader.cpp +++ b/src/Mod/JtReader/App/JtReader.cpp @@ -32,10 +32,10 @@ vector result; vector::const_iterator resultIt; -#define indent(i) \ - { \ - for (int l = 0; l < i; l++) \ - InfoOut << " "; \ +#define indent(i) \ + { \ + for (int l = 0; l < i; l++) \ + InfoOut << " "; \ } void printXform(JtkTransform* partXform, int level) @@ -153,15 +153,17 @@ void printShape(JtkShape* partShape, int level) float *vertex = NULL, *normal = NULL, *color = NULL, *texture = NULL; int vertexCount = -1, normCount = -1, colorCount = -1, textCount = -1; - partShape->getInternal(vertex, - vertexCount, - normal, - normCount, - color, - colorCount, - texture, - textCount, - set); + partShape->getInternal( + vertex, + vertexCount, + normal, + normCount, + color, + colorCount, + texture, + textCount, + set + ); if (vertex && (vertexCount > 0)) { indent(level + 2); @@ -425,15 +427,17 @@ void insertShapeFaces(JtkShape* partShape) float *vertex = NULL, *normal = NULL, *color = NULL, *texture = NULL; int vertexCount = -1, normCount = -1, colorCount = -1, textCount = -1; - partShape->getInternal(vertex, - vertexCount, - normal, - normCount, - color, - colorCount, - texture, - textCount, - set); + partShape->getInternal( + vertex, + vertexCount, + normal, + normCount, + color, + colorCount, + texture, + textCount, + set + ); if (normCount < 3) { return; diff --git a/src/Mod/JtReader/App/TKJtReader.cpp b/src/Mod/JtReader/App/TKJtReader.cpp index e8251baa74..caa548b6d1 100644 --- a/src/Mod/JtReader/App/TKJtReader.cpp +++ b/src/Mod/JtReader/App/TKJtReader.cpp @@ -147,8 +147,9 @@ void TKJtReader::readShapeVertex(const Handle(JtNode_Shape_Vertex) & aShape) anObject = aLateLoaded[index]->DefferedObject(); } if (!anObject.IsNull()) { - Handle(JtElement_ShapeLOD_TriStripSet) aLOD = - Handle(JtElement_ShapeLOD_TriStripSet)::DownCast(anObject); + Handle(JtElement_ShapeLOD_TriStripSet) aLOD = Handle( + JtElement_ShapeLOD_TriStripSet + )::DownCast(anObject); if (!aLOD.IsNull()) { getTriangleStripSet(aLOD); } @@ -224,8 +225,9 @@ void TKJtReader::readAttributes(const JtData_Object::VectorOfObjects& attr) for (std::size_t aAttrIdx = 0; aAttrIdx < attr.Count(); ++aAttrIdx) { Handle(JtData_Object) anAttr = attr[aAttrIdx]; if (anAttr->IsKind(Type_JtAttribute_GeometricTransform)) { - Handle(JtAttribute_GeometricTransform) aTransform = - Handle(JtAttribute_GeometricTransform)::DownCast(anAttr); + Handle(JtAttribute_GeometricTransform) aTransform = Handle( + JtAttribute_GeometricTransform + )::DownCast(anAttr); readTransformAttribute(aTransform); } else if (anAttr->IsKind(Type_JtAttribute_Material)) { diff --git a/src/Mod/JtReader/App/TKJtReader.h b/src/Mod/JtReader/App/TKJtReader.h index eb69006d95..d26909cc0e 100644 --- a/src/Mod/JtReader/App/TKJtReader.h +++ b/src/Mod/JtReader/App/TKJtReader.h @@ -25,18 +25,18 @@ #define JT_READER_TKJTREADER_H #ifdef JTREADER_HAVE_TKJT -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include namespace JtReaderNS { diff --git a/src/Mod/JtReader/App/TestJtReader.cpp b/src/Mod/JtReader/App/TestJtReader.cpp index ec07afd273..6acc2400b5 100644 --- a/src/Mod/JtReader/App/TestJtReader.cpp +++ b/src/Mod/JtReader/App/TestJtReader.cpp @@ -43,8 +43,7 @@ void TestJtReader::read(void) { // const std::vector& toc = readToc(); - for (std::vector::const_iterator i = TocEntries.begin(); i != TocEntries.end(); - ++i) { + for (std::vector::const_iterator i = TocEntries.begin(); i != TocEntries.end(); ++i) { int segType = i->getSegmentType(); if (segType == 7) { diff --git a/src/Mod/Measure/App/AppMeasure.cpp b/src/Mod/Measure/App/AppMeasure.cpp index ae55369c76..5f8a11a419 100644 --- a/src/Mod/Measure/App/AppMeasure.cpp +++ b/src/Mod/Measure/App/AppMeasure.cpp @@ -110,78 +110,104 @@ PyMOD_INIT_FUNC(Measure) // Add fundamental umf Measure Types - App::MeasureManager::addMeasureType("DISTANCE", - "Distance", - "Measure::MeasureDistance", - MeasureDistance::isValidSelection, - MeasureDistance::isPrioritizedSelection); + App::MeasureManager::addMeasureType( + "DISTANCE", + "Distance", + "Measure::MeasureDistance", + MeasureDistance::isValidSelection, + MeasureDistance::isPrioritizedSelection + ); - App::MeasureManager::addMeasureType("DISTANCEFREE", - "Distance Free", - "Measure::MeasureDistanceDetached", - MeasureDistanceDetached::isValidSelection, - nullptr); + App::MeasureManager::addMeasureType( + "DISTANCEFREE", + "Distance Free", + "Measure::MeasureDistanceDetached", + MeasureDistanceDetached::isValidSelection, + nullptr + ); - App::MeasureManager::addMeasureType("ANGLE", - "Angle", - "Measure::MeasureAngle", - MeasureAngle::isValidSelection, - MeasureAngle::isPrioritizedSelection); + App::MeasureManager::addMeasureType( + "ANGLE", + "Angle", + "Measure::MeasureAngle", + MeasureAngle::isValidSelection, + MeasureAngle::isPrioritizedSelection + ); - App::MeasureManager::addMeasureType("LENGTH", - "Length", - "Measure::MeasureLength", - MeasureLength::isValidSelection, - nullptr); + App::MeasureManager::addMeasureType( + "LENGTH", + "Length", + "Measure::MeasureLength", + MeasureLength::isValidSelection, + nullptr + ); - App::MeasureManager::addMeasureType("POSITION", - "Position", - "Measure::MeasurePosition", - MeasurePosition::isValidSelection, - nullptr); + App::MeasureManager::addMeasureType( + "POSITION", + "Position", + "Measure::MeasurePosition", + MeasurePosition::isValidSelection, + nullptr + ); - App::MeasureManager::addMeasureType("AREA", - "Area", - "Measure::MeasureArea", - MeasureArea::isValidSelection, - nullptr); + App::MeasureManager::addMeasureType( + "AREA", + "Area", + "Measure::MeasureArea", + MeasureArea::isValidSelection, + nullptr + ); - App::MeasureManager::addMeasureType("RADIUS", - "Radius", - "Measure::MeasureRadius", - MeasureRadius::isValidSelection, - MeasureRadius::isPrioritizedSelection); + App::MeasureManager::addMeasureType( + "RADIUS", + "Radius", + "Measure::MeasureRadius", + MeasureRadius::isValidSelection, + MeasureRadius::isPrioritizedSelection + ); // load measure callbacks from Part module auto lengthList = Part::MeasureClient::reportLengthCB(); for (auto& entry : lengthList) { - MeasureBaseExtendable::addGeometryHandler(entry.m_module, - entry.m_callback); + MeasureBaseExtendable::addGeometryHandler( + entry.m_module, + entry.m_callback + ); } auto angleList = Part::MeasureClient::reportAngleCB(); for (auto& entry : angleList) { - MeasureBaseExtendable::addGeometryHandler(entry.m_module, - entry.m_callback); + MeasureBaseExtendable::addGeometryHandler( + entry.m_module, + entry.m_callback + ); } auto areaList = Part::MeasureClient::reportAreaCB(); for (auto& entry : areaList) { - MeasureBaseExtendable::addGeometryHandler(entry.m_module, - entry.m_callback); + MeasureBaseExtendable::addGeometryHandler( + entry.m_module, + entry.m_callback + ); } auto distanceList = Part::MeasureClient::reportDistanceCB(); for (auto& entry : distanceList) { - MeasureBaseExtendable::addGeometryHandler(entry.m_module, - entry.m_callback); + MeasureBaseExtendable::addGeometryHandler( + entry.m_module, + entry.m_callback + ); } auto positionList = Part::MeasureClient::reportPositionCB(); for (auto& entry : positionList) { - MeasureBaseExtendable::addGeometryHandler(entry.m_module, - entry.m_callback); + MeasureBaseExtendable::addGeometryHandler( + entry.m_module, + entry.m_callback + ); } auto radiusList = Part::MeasureClient::reportRadiusCB(); for (auto& entry : radiusList) { - MeasureBaseExtendable::addGeometryHandler(entry.m_module, - entry.m_callback); + MeasureBaseExtendable::addGeometryHandler( + entry.m_module, + entry.m_callback + ); } diff --git a/src/Mod/Measure/App/AppMeasurePy.cpp b/src/Mod/Measure/App/AppMeasurePy.cpp index ca88c173d4..25c7128fd2 100644 --- a/src/Mod/Measure/App/AppMeasurePy.cpp +++ b/src/Mod/Measure/App/AppMeasurePy.cpp @@ -88,7 +88,8 @@ public: &Module::getLocatedTopoShape, "Part.TopoShape = Measure.getLocatedTopoShape(DocumentObject, longSubElement) Resolves " "the net placement of DocumentObject and returns the object's shape/subshape with the " - "net placement applied. Link scaling operations along the path are also applied."); + "net placement applied. Link scaling operations along the path are also applied." + ); initialize("This is a module for measuring"); // register with Python } ~Module() override diff --git a/src/Mod/Measure/App/MeasureAngle.cpp b/src/Mod/Measure/App/MeasureAngle.cpp index 172bee584d..52c1299b7d 100644 --- a/src/Mod/Measure/App/MeasureAngle.cpp +++ b/src/Mod/Measure/App/MeasureAngle.cpp @@ -38,27 +38,27 @@ PROPERTY_SOURCE(Measure::MeasureAngle, Measure::MeasureBase) MeasureAngle::MeasureAngle() { - ADD_PROPERTY_TYPE(Element1, - (nullptr), - "Measurement", - App::Prop_None, - "First element of the measurement"); + ADD_PROPERTY_TYPE(Element1, (nullptr), "Measurement", App::Prop_None, "First element of the measurement"); Element1.setScope(App::LinkScope::Global); Element1.setAllowExternal(true); - ADD_PROPERTY_TYPE(Element2, - (nullptr), - "Measurement", - App::Prop_None, - "Second element of the measurement"); + ADD_PROPERTY_TYPE( + Element2, + (nullptr), + "Measurement", + App::Prop_None, + "Second element of the measurement" + ); Element2.setScope(App::LinkScope::Global); Element2.setAllowExternal(true); - ADD_PROPERTY_TYPE(Angle, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Angle between the two elements"); + ADD_PROPERTY_TYPE( + Angle, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Angle between the two elements" + ); Angle.setUnit(Base::Unit::Angle); } diff --git a/src/Mod/Measure/App/MeasureArea.cpp b/src/Mod/Measure/App/MeasureArea.cpp index a18cceb1f2..bc2ee93a55 100644 --- a/src/Mod/Measure/App/MeasureArea.cpp +++ b/src/Mod/Measure/App/MeasureArea.cpp @@ -36,19 +36,17 @@ PROPERTY_SOURCE(Measure::MeasureArea, Measure::MeasureBase) MeasureArea::MeasureArea() { - ADD_PROPERTY_TYPE(Elements, - (nullptr), - "Measurement", - App::Prop_None, - "Element to get the area from"); + ADD_PROPERTY_TYPE(Elements, (nullptr), "Measurement", App::Prop_None, "Element to get the area from"); Elements.setScope(App::LinkScope::Global); Elements.setAllowExternal(true); - ADD_PROPERTY_TYPE(Area, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Area of element"); + ADD_PROPERTY_TYPE( + Area, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Area of element" + ); } MeasureArea::~MeasureArea() = default; diff --git a/src/Mod/Measure/App/MeasureBase.cpp b/src/Mod/Measure/App/MeasureBase.cpp index 98f261b80c..4eb3e06e23 100644 --- a/src/Mod/Measure/App/MeasureBase.cpp +++ b/src/Mod/Measure/App/MeasureBase.cpp @@ -44,7 +44,8 @@ MeasureBase::MeasureBase() (Base::Placement()), nullptr, App::PropertyType(App::Prop_ReadOnly | App::Prop_Output | App::Prop_NoRecompute), - "Visual placement of the measurement"); + "Visual placement of the measurement" + ); } @@ -183,7 +184,8 @@ QString MeasureBase::getResultString() if (prop->isDerivedFrom()) { return QString::fromStdString( - static_cast(prop)->getQuantityValue().getUserString()); + static_cast(prop)->getQuantityValue().getUserString() + ); } diff --git a/src/Mod/Measure/App/MeasureBase.h b/src/Mod/Measure/App/MeasureBase.h index 5a4bcaae60..75b84bd218 100644 --- a/src/Mod/Measure/App/MeasureBase.h +++ b/src/Mod/Measure/App/MeasureBase.h @@ -133,16 +133,17 @@ public: auto handler = getGeometryHandler(mod); if (!handler) { - Base::Console().log("MeasureBaseExtendable::getMeasureInfo: No geometry handler " - "available for submitted element type"); + Base::Console().log( + "MeasureBaseExtendable::getMeasureInfo: No geometry handler " + "available for submitted element type" + ); return nullptr; } return handler(subObjT); } - static void addGeometryHandlers(const std::vector& modules, - GeometryHandler callback) + static void addGeometryHandlers(const std::vector& modules, GeometryHandler callback) { // TODO: this will replace a callback with a later one. Should we check that there isn't // already a handler defined for this module? diff --git a/src/Mod/Measure/App/MeasureDistance.cpp b/src/Mod/Measure/App/MeasureDistance.cpp index e9c423655d..b75586dad1 100644 --- a/src/Mod/Measure/App/MeasureDistance.cpp +++ b/src/Mod/Measure/App/MeasureDistance.cpp @@ -45,58 +45,68 @@ PROPERTY_SOURCE(Measure::MeasureDistance, Measure::MeasureBase) MeasureDistance::MeasureDistance() { - ADD_PROPERTY_TYPE(Element1, - (nullptr), - "Measurement", - App::Prop_None, - "First element of the measurement"); + ADD_PROPERTY_TYPE(Element1, (nullptr), "Measurement", App::Prop_None, "First element of the measurement"); Element1.setScope(App::LinkScope::Global); Element1.setAllowExternal(true); - ADD_PROPERTY_TYPE(Element2, - (nullptr), - "Measurement", - App::Prop_None, - "Second element of the measurement"); + ADD_PROPERTY_TYPE( + Element2, + (nullptr), + "Measurement", + App::Prop_None, + "Second element of the measurement" + ); Element2.setScope(App::LinkScope::Global); Element2.setAllowExternal(true); - ADD_PROPERTY_TYPE(Distance, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance between the two elements"); + ADD_PROPERTY_TYPE( + Distance, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance between the two elements" + ); Distance.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(DistanceX, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance in X-direction"); + ADD_PROPERTY_TYPE( + DistanceX, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance in X-direction" + ); DistanceX.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(DistanceY, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance in Y-direction"); + ADD_PROPERTY_TYPE( + DistanceY, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance in Y-direction" + ); DistanceY.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(DistanceZ, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance in Z-direction"); + ADD_PROPERTY_TYPE( + DistanceZ, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance in Z-direction" + ); DistanceZ.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(Position1, - (Base::Vector3d(0.0, 0.0, 0.0)), - "Measurement", - App::Prop_Hidden, - "Position1"); - ADD_PROPERTY_TYPE(Position2, - (Base::Vector3d(0.0, 1.0, 0.0)), - "Measurement", - App::Prop_Hidden, - "Position2"); + ADD_PROPERTY_TYPE( + Position1, + (Base::Vector3d(0.0, 0.0, 0.0)), + "Measurement", + App::Prop_Hidden, + "Position1" + ); + ADD_PROPERTY_TYPE( + Position2, + (Base::Vector3d(0.0, 1.0, 0.0)), + "Measurement", + App::Prop_Hidden, + "Position2" + ); } MeasureDistance::~MeasureDistance() = default; @@ -117,10 +127,9 @@ bool MeasureDistance::isValidSelection(const App::MeasureSelection& selection) } if (type != App::MeasureElementType::POINT && type != App::MeasureElementType::LINE - && type != App::MeasureElementType::LINESEGMENT - && type != App::MeasureElementType::CIRCLE && type != App::MeasureElementType::ARC - && type != App::MeasureElementType::CURVE && type != App::MeasureElementType::PLANE - && type != App::MeasureElementType::CYLINDER) { + && type != App::MeasureElementType::LINESEGMENT && type != App::MeasureElementType::CIRCLE + && type != App::MeasureElementType::ARC && type != App::MeasureElementType::CURVE + && type != App::MeasureElementType::PLANE && type != App::MeasureElementType::CYLINDER) { return false; } } @@ -322,42 +331,42 @@ PROPERTY_SOURCE(Measure::MeasureDistanceDetached, Measure::MeasureBase) MeasureDistanceDetached::MeasureDistanceDetached() { - ADD_PROPERTY_TYPE(Distance, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance between the two elements"); + ADD_PROPERTY_TYPE( + Distance, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance between the two elements" + ); Distance.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(DistanceX, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance in X-direction"); + ADD_PROPERTY_TYPE( + DistanceX, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance in X-direction" + ); DistanceX.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(DistanceY, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance in Y-direction"); + ADD_PROPERTY_TYPE( + DistanceY, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance in Y-direction" + ); DistanceY.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(DistanceZ, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Distance in Z-direction"); + ADD_PROPERTY_TYPE( + DistanceZ, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Distance in Z-direction" + ); DistanceZ.setUnit(Base::Unit::Length); - ADD_PROPERTY_TYPE(Position1, - (Base::Vector3d(0.0, 0.0, 0.0)), - "Measurement", - App::Prop_None, - "Position1"); - ADD_PROPERTY_TYPE(Position2, - (Base::Vector3d(0.0, 1.0, 0.0)), - "Measurement", - App::Prop_None, - "Position2"); + ADD_PROPERTY_TYPE(Position1, (Base::Vector3d(0.0, 0.0, 0.0)), "Measurement", App::Prop_None, "Position1"); + ADD_PROPERTY_TYPE(Position2, (Base::Vector3d(0.0, 1.0, 0.0)), "Measurement", App::Prop_None, "Position2"); } MeasureDistanceDetached::~MeasureDistanceDetached() = default; @@ -425,10 +434,12 @@ Base::Type MeasureDistanceType::getTypeId() const void MeasureDistanceType::init() { - initSubclass(MeasureDistanceType::classTypeId, - "App::MeasureDistance", - "App::DocumentObject", - &(MeasureDistanceType::create)); + initSubclass( + MeasureDistanceType::classTypeId, + "App::MeasureDistance", + "App::DocumentObject", + &(MeasureDistanceType::create) + ); } void* MeasureDistanceType::create() @@ -440,9 +451,11 @@ Base::Type MeasureDistanceType::classTypeId = Base::Type::BadType; // Migrate old MeasureDistance Type -void MeasureDistanceDetached::handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) +void MeasureDistanceDetached::handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName +) { if (strcmp(PropName, "P1") == 0 && strcmp(TypeName, "App::PropertyVector") == 0) { Position1.Restore(reader); diff --git a/src/Mod/Measure/App/MeasureDistance.h b/src/Mod/Measure/App/MeasureDistance.h index 492d36eb03..44fe0cf045 100644 --- a/src/Mod/Measure/App/MeasureDistance.h +++ b/src/Mod/Measure/App/MeasureDistance.h @@ -57,8 +57,7 @@ private: }; -class MeasureExport MeasureDistance - : public Measure::MeasureBaseExtendable +class MeasureExport MeasureDistance: public Measure::MeasureBaseExtendable { PROPERTY_HEADER_WITH_OVERRIDE(Measure::MeasureDistance); @@ -155,9 +154,11 @@ public: // Return the object we are measuring std::vector getSubject() const override; - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; private: void onChanged(const App::Property* prop) override; diff --git a/src/Mod/Measure/App/MeasureLength.cpp b/src/Mod/Measure/App/MeasureLength.cpp index ce2855bd27..0a6743557b 100644 --- a/src/Mod/Measure/App/MeasureLength.cpp +++ b/src/Mod/Measure/App/MeasureLength.cpp @@ -38,19 +38,17 @@ PROPERTY_SOURCE(Measure::MeasureLength, Measure::MeasureBase) MeasureLength::MeasureLength() { - ADD_PROPERTY_TYPE(Elements, - (nullptr), - "Measurement", - App::Prop_None, - "Elements to get the length from"); + ADD_PROPERTY_TYPE(Elements, (nullptr), "Measurement", App::Prop_None, "Elements to get the length from"); Elements.setScope(App::LinkScope::Global); Elements.setAllowExternal(true); - ADD_PROPERTY_TYPE(Length, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Length of selection"); + ADD_PROPERTY_TYPE( + Length, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Length of selection" + ); } MeasureLength::~MeasureLength() = default; diff --git a/src/Mod/Measure/App/MeasurePosition.cpp b/src/Mod/Measure/App/MeasurePosition.cpp index 397d1d629e..97f2611305 100644 --- a/src/Mod/Measure/App/MeasurePosition.cpp +++ b/src/Mod/Measure/App/MeasurePosition.cpp @@ -37,20 +37,18 @@ PROPERTY_SOURCE(Measure::MeasurePosition, Measure::MeasureBase) MeasurePosition::MeasurePosition() { - ADD_PROPERTY_TYPE(Element, - (nullptr), - "Measurement", - App::Prop_None, - "Element to get the position from"); + ADD_PROPERTY_TYPE(Element, (nullptr), "Measurement", App::Prop_None, "Element to get the position from"); Element.setScope(App::LinkScope::Global); Element.setAllowExternal(true); - ADD_PROPERTY_TYPE(Position, - (0.0, 0.0, 0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "The absolute position"); + ADD_PROPERTY_TYPE( + Position, + (0.0, 0.0, 0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "The absolute position" + ); } MeasurePosition::~MeasurePosition() = default; @@ -137,10 +135,8 @@ QString MeasurePosition::getResultString() int precision = 2; QString text; - QTextStream(&text) << "X: " << QString::number(value.x, 'f', precision) << " " << unit - << Qt::endl - << "Y: " << QString::number(value.y, 'f', precision) << " " << unit - << Qt::endl + QTextStream(&text) << "X: " << QString::number(value.x, 'f', precision) << " " << unit << Qt::endl + << "Y: " << QString::number(value.y, 'f', precision) << " " << unit << Qt::endl << "Z: " << QString::number(value.z, 'f', precision) << " " << unit; return text; } diff --git a/src/Mod/Measure/App/MeasurePosition.h b/src/Mod/Measure/App/MeasurePosition.h index b01c574d71..216ecc10bd 100644 --- a/src/Mod/Measure/App/MeasurePosition.h +++ b/src/Mod/Measure/App/MeasurePosition.h @@ -42,8 +42,7 @@ namespace Measure { -class MeasureExport MeasurePosition - : public Measure::MeasureBaseExtendable +class MeasureExport MeasurePosition: public Measure::MeasureBaseExtendable { PROPERTY_HEADER_WITH_OVERRIDE(Measure::MeasurePosition); diff --git a/src/Mod/Measure/App/MeasureRadius.cpp b/src/Mod/Measure/App/MeasureRadius.cpp index 22c0dd631f..ad78eb0b39 100644 --- a/src/Mod/Measure/App/MeasureRadius.cpp +++ b/src/Mod/Measure/App/MeasureRadius.cpp @@ -45,19 +45,17 @@ PROPERTY_SOURCE(Measure::MeasureRadius, Measure::MeasureBase) MeasureRadius::MeasureRadius() { - ADD_PROPERTY_TYPE(Element, - (nullptr), - "Measurement", - App::Prop_None, - "Element to get the radius from"); + ADD_PROPERTY_TYPE(Element, (nullptr), "Measurement", App::Prop_None, "Element to get the radius from"); Element.setScope(App::LinkScope::Global); Element.setAllowExternal(true); - ADD_PROPERTY_TYPE(Radius, - (0.0), - "Measurement", - App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), - "Radius of selection"); + ADD_PROPERTY_TYPE( + Radius, + (0.0), + "Measurement", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), + "Radius of selection" + ); } MeasureRadius::~MeasureRadius() = default; diff --git a/src/Mod/Measure/App/Measurement.cpp b/src/Mod/Measure/App/Measurement.cpp index bf19131a04..5e68309717 100644 --- a/src/Mod/Measure/App/Measurement.cpp +++ b/src/Mod/Measure/App/Measurement.cpp @@ -127,11 +127,12 @@ MeasureType Measurement::findType() for (; obj != objects.end(); ++obj, ++subEl) { TopoDS_Shape refSubShape; try { - refSubShape = Part::Feature::getShape(*obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - (*subEl).c_str()); + refSubShape = Part::Feature::getShape( + *obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + (*subEl).c_str() + ); if (refSubShape.IsNull()) { return MeasureType::Invalid; @@ -324,14 +325,14 @@ MeasureType Measurement::getType() return measureType; } -TopoDS_Shape -Measurement::getShape(App::DocumentObject* obj, const char* subName, TopAbs_ShapeEnum hint) const +TopoDS_Shape Measurement::getShape(App::DocumentObject* obj, const char* subName, TopAbs_ShapeEnum hint) const { - return Part::Feature::getShape(obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subName); + return Part::Feature::getShape( + obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subName + ); } @@ -408,7 +409,8 @@ double Measurement::length() const } default: { throw Base::RuntimeError( - "Measurement - length - Curve type not currently handled"); + "Measurement - length - Curve type not currently handled" + ); } } } @@ -618,8 +620,7 @@ double Measurement::cylinderAxisDistance() const BRepAdaptor_Surface surface2(face2); if (surface1.GetType() == GeomAbs_Cylinder && surface2.GetType() == GeomAbs_Cylinder) { - distance = - gp_Lin(surface1.Cylinder().Axis()).Distance(gp_Lin(surface2.Cylinder().Axis())); + distance = gp_Lin(surface1.Cylinder().Axis()).Distance(gp_Lin(surface2.Cylinder().Axis())); } } else if (measureType == MeasureType::CircleToCylinder) { @@ -740,7 +741,8 @@ double Measurement::angle(const Base::Vector3d& /*param*/) const } double aRad = axis1.Angle(axis2); return Base::toDegrees( - std::min(aRad, std::fmod(aRad + std::numbers::pi, 2.0 * std::numbers::pi))); + std::min(aRad, std::fmod(aRad + std::numbers::pi, 2.0 * std::numbers::pi)) + ); } } throw Base::RuntimeError("Unexpected error for angle measurement"); @@ -831,10 +833,8 @@ Base::Vector3d Measurement::delta() const if (measureType == MeasureType::PointToPoint) { if (numRefs == 2) { // Keep separate case for two points to reduce need for complex algorithm - TopoDS_Shape shape1 = - getShape(objects.at(0), subElements.at(0).c_str(), TopAbs_VERTEX); - TopoDS_Shape shape2 = - getShape(objects.at(1), subElements.at(1).c_str(), TopAbs_VERTEX); + TopoDS_Shape shape1 = getShape(objects.at(0), subElements.at(0).c_str(), TopAbs_VERTEX); + TopoDS_Shape shape2 = getShape(objects.at(1), subElements.at(1).c_str(), TopAbs_VERTEX); const TopoDS_Vertex& vert1 = TopoDS::Vertex(shape1); const TopoDS_Vertex& vert2 = TopoDS::Vertex(shape2); @@ -845,8 +845,7 @@ Base::Vector3d Measurement::delta() const return Base::Vector3d(diff.X(), diff.Y(), diff.Z()); } } - else if (measureType == MeasureType::PointToEdge - || measureType == MeasureType::PointToSurface + else if (measureType == MeasureType::PointToEdge || measureType == MeasureType::PointToSurface || measureType == MeasureType::PointToCircle || measureType == MeasureType::PointToCylinder) { // BrepExtema can calculate minimum distance between any set of topology sets. @@ -870,8 +869,7 @@ Base::Vector3d Measurement::delta() const else if (measureType == MeasureType::Edges) { // Only case that is supported is straight line edge if (numRefs == 1) { - TopoDS_Shape shape = - getShape(objects.at(0), subElements.at(0).c_str(), TopAbs_EDGE); + TopoDS_Shape shape = getShape(objects.at(0), subElements.at(0).c_str(), TopAbs_EDGE); const TopoDS_Edge& edge = TopoDS::Edge(shape); BRepAdaptor_Curve curve(edge); @@ -883,10 +881,8 @@ Base::Vector3d Measurement::delta() const } } else if (numRefs == 2) { - TopoDS_Shape shape1 = - getShape(objects.at(0), subElements.at(0).c_str(), TopAbs_EDGE); - TopoDS_Shape shape2 = - getShape(objects.at(1), subElements.at(1).c_str(), TopAbs_EDGE); + TopoDS_Shape shape1 = getShape(objects.at(0), subElements.at(0).c_str(), TopAbs_EDGE); + TopoDS_Shape shape2 = getShape(objects.at(1), subElements.at(1).c_str(), TopAbs_EDGE); BRepAdaptor_Curve curve1(TopoDS::Edge(shape1)); BRepAdaptor_Curve curve2(TopoDS::Edge(shape2)); @@ -1026,11 +1022,12 @@ bool Measurement::planesAreParallel() const for (size_t i = 0; i < objects.size(); ++i) { TopoDS_Shape refSubShape; try { - refSubShape = Part::Feature::getShape(objects[i], - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subElements[i].c_str()); + refSubShape = Part::Feature::getShape( + objects[i], + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subElements[i].c_str() + ); if (refSubShape.IsNull()) { return false; diff --git a/src/Mod/Measure/App/Measurement.h b/src/Mod/Measure/App/Measurement.h index b0be587eb4..f557943811 100644 --- a/src/Mod/Measure/App/Measurement.h +++ b/src/Mod/Measure/App/Measurement.h @@ -111,8 +111,7 @@ public: double diameter() const; // Calculates the angle between two edges - double - angle(const Base::Vector3d& param = Base::Vector3d(0, 0, 0)) const; // param is never used??? + double angle(const Base::Vector3d& param = Base::Vector3d(0, 0, 0)) const; // param is never used??? // Calculate the center of mass Base::Vector3d massCenter() const; @@ -134,9 +133,11 @@ public: protected: // Hint parameter helps sort out compound shapes by specifying a subelement type // use hint = TopAbs_COMPOUND to give no hint - TopoDS_Shape getShape(App::DocumentObject* obj, - const char* subName, - TopAbs_ShapeEnum hint = TopAbs_COMPOUND) const; + TopoDS_Shape getShape( + App::DocumentObject* obj, + const char* subName, + TopAbs_ShapeEnum hint = TopAbs_COMPOUND + ) const; private: MeasureType measureType; diff --git a/src/Mod/Measure/App/Preferences.cpp b/src/Mod/Measure/App/Preferences.cpp index 3f13e89bd5..112172a8ef 100644 --- a/src/Mod/Measure/App/Preferences.cpp +++ b/src/Mod/Measure/App/Preferences.cpp @@ -50,7 +50,8 @@ Base::Color Preferences::defaultLineColor() { Base::Color fcColor; fcColor.setPackedValue( - getPreferenceGroup("Appearance")->GetUnsigned("DefaultLineColor", 0x3CF00000)); + getPreferenceGroup("Appearance")->GetUnsigned("DefaultLineColor", 0x3CF00000) + ); return fcColor; } @@ -58,7 +59,8 @@ Base::Color Preferences::defaultTextColor() { Base::Color fcColor; fcColor.setPackedValue( - getPreferenceGroup("Appearance")->GetUnsigned("DefaultTextColor", 0x00000000)); + getPreferenceGroup("Appearance")->GetUnsigned("DefaultTextColor", 0x00000000) + ); return fcColor; } @@ -66,7 +68,8 @@ Base::Color Preferences::defaultTextBackgroundColor() { Base::Color fcColor; fcColor.setPackedValue( - getPreferenceGroup("Appearance")->GetUnsigned("DefaultTextBackgroundColor", 0x3CF00000)); + getPreferenceGroup("Appearance")->GetUnsigned("DefaultTextBackgroundColor", 0x3CF00000) + ); return fcColor; } diff --git a/src/Mod/Measure/App/ShapeFinder.cpp b/src/Mod/Measure/App/ShapeFinder.cpp index dbaff7058d..d8ec29829d 100644 --- a/src/Mod/Measure/App/ShapeFinder.cpp +++ b/src/Mod/Measure/App/ShapeFinder.cpp @@ -55,9 +55,11 @@ using namespace Measure; //! ResolveResult is a class to hold the result of resolving a selection into the actual target //! object and traditional subElement name (Vertex1). -ResolveResult::ResolveResult(const App::DocumentObject* realTarget, - const std::string& shortSubName, - const App::DocumentObject* targetParent) +ResolveResult::ResolveResult( + const App::DocumentObject* realTarget, + const std::string& shortSubName, + const App::DocumentObject* targetParent +) : m_target(App::SubObjectT(realTarget, shortSubName.c_str())) , m_targetParent(App::DocumentObjectT(targetParent)) {} @@ -80,14 +82,16 @@ App::DocumentObject& ResolveResult::getTargetParent() const //! returns the actual target object and subname pointed to by selectObj and selectLongSub (which //! is likely a result from getSelection or getSelectionEx) -ResolveResult ShapeFinder::resolveSelection(const App::DocumentObject& selectObj, - const std::string& selectLongSub) +ResolveResult ShapeFinder::resolveSelection( + const App::DocumentObject& selectObj, + const std::string& selectLongSub +) { App::DocumentObject* targetParent {nullptr}; std::string childName {}; const char* subElement {nullptr}; - App::DocumentObject* realTarget = - selectObj.resolve(selectLongSub.c_str(), &targetParent, &childName, &subElement); + App::DocumentObject* realTarget + = selectObj.resolve(selectLongSub.c_str(), &targetParent, &childName, &subElement); auto shortSub = getLastTerm(selectLongSub); return {realTarget, shortSub, targetParent}; } @@ -100,8 +104,7 @@ ResolveResult ShapeFinder::resolveSelection(const App::DocumentObject& selectObj // TODO: to truly locate the shape, we need to consider attachments - see // ShapeExtractor::getShapesFromXRoot() // and ShapeFinder::getLinkAttachParent() -TopoDS_Shape ShapeFinder::getLocatedShape(const App::DocumentObject& rootObject, - const std::string& leafSub) +TopoDS_Shape ShapeFinder::getLocatedShape(const App::DocumentObject& rootObject, const std::string& leafSub) { auto resolved = resolveSelection(rootObject, leafSub); auto target = &resolved.getTarget(); @@ -110,9 +113,10 @@ TopoDS_Shape ShapeFinder::getLocatedShape(const App::DocumentObject& rootObject, return {}; } - TopoDS_Shape shape = - Part::Feature::getShape(target, - Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + TopoDS_Shape shape = Part::Feature::getShape( + target, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (isShapeReallyNull(shape)) { return {}; } @@ -131,8 +135,10 @@ TopoDS_Shape ShapeFinder::getLocatedShape(const App::DocumentObject& rootObject, //! convenient version of previous method -Part::TopoShape ShapeFinder::getLocatedTopoShape(const App::DocumentObject& rootObject, - const std::string& leafSub) +Part::TopoShape ShapeFinder::getLocatedTopoShape( + const App::DocumentObject& rootObject, + const std::string& leafSub +) { return {getLocatedShape(rootObject, leafSub)}; } @@ -142,10 +148,12 @@ Part::TopoShape ShapeFinder::getLocatedTopoShape(const App::DocumentObject& root //! the placements will need to be applied in the reverse order (ie top down) of what is delivered //! in plm stack. leafSub is a dot separated longSubName which DOES NOT include rootObject. the //! result does not include rootObject's transform. -void ShapeFinder::crawlPlacementChain(std::vector& plmStack, - std::vector& scaleStack, - const App::DocumentObject& rootObject, - const std::string& leafSub) +void ShapeFinder::crawlPlacementChain( + std::vector& plmStack, + std::vector& scaleStack, + const App::DocumentObject& rootObject, + const std::string& leafSub +) { auto currentSub = leafSub; std::string previousSub {}; @@ -169,9 +177,11 @@ void ShapeFinder::crawlPlacementChain(std::vector& plmStack, //! return inShape with placement and scaler applied. If inShape contains any infinite subshapes //! (such as Datum planes), the infinite shapes will not be included in the result. -TopoDS_Shape ShapeFinder::transformShape(TopoDS_Shape& inShape, - const Base::Placement& placement, - const Base::Matrix4D& scaler) +TopoDS_Shape ShapeFinder::transformShape( + TopoDS_Shape& inShape, + const Base::Placement& placement, + const Base::Matrix4D& scaler +) { if (isShapeReallyNull(inShape)) { return {}; @@ -294,8 +304,10 @@ bool ShapeFinder::isShapeReallyNull(const TopoDS_Shape& shape) //! Returns the net transformation of a path from rootObject to leafSub. rootObject's transform //! is included in the result. -std::pair -ShapeFinder::getGlobalTransform(const App::DocumentObject& rootObject, const std::string& leafSub) +std::pair ShapeFinder::getGlobalTransform( + const App::DocumentObject& rootObject, + const std::string& leafSub +) { // we prune the last term if it is a vertex, edge or face std::string newSub = removeGeometryTerm(leafSub); @@ -321,8 +333,9 @@ ShapeFinder::getGlobalTransform(const App::DocumentObject& rootObject, const std //! tries to get the global position and scale for a object with no information about the //! path through the tree from a root to cursor object. -std::pair -ShapeFinder::getGlobalTransform(const App::DocumentObject* cursorObject) +std::pair ShapeFinder::getGlobalTransform( + const App::DocumentObject* cursorObject +) { if (!cursorObject) { return {}; @@ -346,9 +359,10 @@ ShapeFinder::getGlobalTransform(const App::DocumentObject* cursorObject) //! combine a series of placement & scale transforms. The input stacks are expected in leaf to root //! order, but the result is in the expected root to leaf order. -std::pair -ShapeFinder::sumTransforms(const std::vector& plmStack, - const std::vector& scaleStack) +std::pair ShapeFinder::sumTransforms( + const std::vector& plmStack, + const std::vector& scaleStack +) { Base::Placement netPlm; Base::Matrix4D netScale; @@ -398,9 +412,11 @@ std::string ShapeFinder::PlacementAsString(const Base::Placement& inPlacement) //! debug routine. return readable form of TopLoc_Location from OCC std::string ShapeFinder::LocationAsString(const TopLoc_Location& location) { - auto position = Base::Vector3d {location.Transformation().TranslationPart().X(), - location.Transformation().TranslationPart().Y(), - location.Transformation().TranslationPart().Z()}; + auto position = Base::Vector3d { + location.Transformation().TranslationPart().X(), + location.Transformation().TranslationPart().Y(), + location.Transformation().TranslationPart().Z() + }; gp_XYZ axisDir; double angle {0}; auto isRotation = location.Transformation().GetRotation(axisDir, angle); diff --git a/src/Mod/Measure/App/ShapeFinder.h b/src/Mod/Measure/App/ShapeFinder.h index 297dc9c089..3d869038c4 100644 --- a/src/Mod/Measure/App/ShapeFinder.h +++ b/src/Mod/Measure/App/ShapeFinder.h @@ -47,9 +47,11 @@ class MeasureExport ResolveResult { public: ResolveResult(); - ResolveResult(const App::DocumentObject* realTarget, - const std::string& shortSubName, - const App::DocumentObject* targetParent); + ResolveResult( + const App::DocumentObject* realTarget, + const std::string& shortSubName, + const App::DocumentObject* targetParent + ); App::DocumentObject& getTarget() const; std::string getShortSub() const; @@ -65,24 +67,35 @@ private: class MeasureExport ShapeFinder: public SubnameHelper { public: - static TopoDS_Shape getLocatedShape(const App::DocumentObject& rootObject, - const std::string& leafSub); - static Part::TopoShape getLocatedTopoShape(const App::DocumentObject& rootObject, - const std::string& leafSub); + static TopoDS_Shape getLocatedShape( + const App::DocumentObject& rootObject, + const std::string& leafSub + ); + static Part::TopoShape getLocatedTopoShape( + const App::DocumentObject& rootObject, + const std::string& leafSub + ); - static std::pair - getGlobalTransform(const App::DocumentObject& rootObject, const std::string& leafSub); - static std::pair - getGlobalTransform(const App::DocumentObject* cursorObject); + static std::pair getGlobalTransform( + const App::DocumentObject& rootObject, + const std::string& leafSub + ); + static std::pair getGlobalTransform( + const App::DocumentObject* cursorObject + ); - static void crawlPlacementChain(std::vector& plmStack, - std::vector& scaleStack, - const App::DocumentObject& rootObj, - const std::string& leafSub); + static void crawlPlacementChain( + std::vector& plmStack, + std::vector& scaleStack, + const App::DocumentObject& rootObj, + const std::string& leafSub + ); - static ResolveResult resolveSelection(const App::DocumentObject& selectObj, - const std::string& selectLongSub); + static ResolveResult resolveSelection( + const App::DocumentObject& selectObj, + const std::string& selectLongSub + ); static Base::Placement getPlacement(const App::DocumentObject* root); static Base::Matrix4D getScale(const App::DocumentObject* root); @@ -91,34 +104,42 @@ public: static std::string PlacementAsString(const Base::Placement& inPlacement); static std::string LocationAsString(const TopLoc_Location& location); - static TopoDS_Shape transformShape(TopoDS_Shape& inShape, - const Base::Placement& placement, - const Base::Matrix4D& scaler); + static TopoDS_Shape transformShape( + TopoDS_Shape& inShape, + const Base::Placement& placement, + const Base::Matrix4D& scaler + ); static TopoDS_Shape stripInfiniteShapes(const TopoDS_Shape& inShape); static bool isShapeReallyNull(const TopoDS_Shape& shape); - static std::pair - sumTransforms(const std::vector& plmStack, - const std::vector& scaleStack); + static std::pair sumTransforms( + const std::vector& plmStack, + const std::vector& scaleStack + ); static App::DocumentObject* getLinkAttachParent(const App::DocumentObject* attachedObject); static Base::Placement getAttachedPlacement(const App::DocumentObject* cursorObject); static std::string getFullPath(const App::DocumentObject* object); static std::vector getGeometryRootObjects(const App::Document* doc); - static std::vector> - getGeometryPathsFromOutList(const App::DocumentObject* object); + static std::vector> getGeometryPathsFromOutList( + const App::DocumentObject* object + ); private: static bool ignoreModule(const std::string& moduleName); static bool ignoreObject(const App::DocumentObject* object); - static bool ignoreLinkAttachedObject(const App::DocumentObject* object, - const App::DocumentObject* inlistObject); - static std::vector - tidyInList(const std::vector& inlist); - static std::vector - tidyInListAttachment(const App::DocumentObject* owner, - const std::vector& inlist); + static bool ignoreLinkAttachedObject( + const App::DocumentObject* object, + const App::DocumentObject* inlistObject + ); + static std::vector tidyInList( + const std::vector& inlist + ); + static std::vector tidyInListAttachment( + const App::DocumentObject* owner, + const std::vector& inlist + ); }; } // namespace Measure diff --git a/src/Mod/Measure/Gui/AppMeasureGui.cpp b/src/Mod/Measure/Gui/AppMeasureGui.cpp index 92b190ec44..9307a4528b 100644 --- a/src/Mod/Measure/Gui/AppMeasureGui.cpp +++ b/src/Mod/Measure/Gui/AppMeasureGui.cpp @@ -106,7 +106,8 @@ PyMOD_INIT_FUNC(MeasureGui) // register preferences pages new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Measure")); + QT_TRANSLATE_NOOP("QObject", "Measure") + ); // Q_INIT_RESOURCE(Measure); diff --git a/src/Mod/Measure/Gui/PreCompiled.h b/src/Mod/Measure/Gui/PreCompiled.h index f9f9af5d64..5ab47a5620 100644 --- a/src/Mod/Measure/Gui/PreCompiled.h +++ b/src/Mod/Measure/Gui/PreCompiled.h @@ -29,7 +29,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // standard @@ -52,20 +52,20 @@ // GL // Include glext before QtAll/InventorAll #ifdef FC_OS_WIN32 -#include -#include +# include +# include #else -#ifdef FC_OS_MACOSX -#include -#include -#else -#ifndef GL_GLEXT_PROTOTYPES -#define GL_GLEXT_PROTOTYPES 1 -#endif -#include -#include -#endif // FC_OS_MACOSX -#endif // FC_OS_WIN32 +# ifdef FC_OS_MACOSX +# include +# include +# else +# ifndef GL_GLEXT_PROTOTYPES +# define GL_GLEXT_PROTOTYPES 1 +# endif +# include +# include +# endif // FC_OS_MACOSX +#endif // FC_OS_WIN32 // Should come after glext.h to avoid warnings #include diff --git a/src/Mod/Measure/Gui/QuickMeasure.cpp b/src/Mod/Measure/Gui/QuickMeasure.cpp index 8d7e590d7e..e8206e950e 100644 --- a/src/Mod/Measure/Gui/QuickMeasure.cpp +++ b/src/Mod/Measure/Gui/QuickMeasure.cpp @@ -152,9 +152,11 @@ void QuickMeasure::addSelectionToMeasurement() int count = 0; int limit = 100; - auto selObjs = Gui::Selection().getSelectionEx(nullptr, - App::DocumentObject::getClassTypeId(), - Gui::ResolveMode::NoResolve); + auto selObjs = Gui::Selection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::NoResolve + ); for (auto& selObj : selObjs) { App::DocumentObject* rootObj = selObj.getObject(); @@ -237,15 +239,18 @@ void QuickMeasure::printResult() double angle = measurement->angle(); if (angle <= Precision::Confusion()) { - print(tr("Total area: %1, Axis distance: %2") - .arg(areaStr(measurement->area()), - lengthStr(measurement->cylinderAxisDistance()))); + print( + tr("Total area: %1, Axis distance: %2") + .arg(areaStr(measurement->area()), lengthStr(measurement->cylinderAxisDistance())) + ); } else { print(tr("Total area: %1, Axis distance: %2, Axis angle: %3") - .arg(areaStr(measurement->area()), - lengthStr(measurement->cylinderAxisDistance()), - angleStr(angle))); + .arg( + areaStr(measurement->area()), + lengthStr(measurement->cylinderAxisDistance()), + angleStr(angle) + )); } } else if (mtype == MeasureType::Edges) { @@ -274,43 +279,48 @@ void QuickMeasure::printResult() print(tr("Minimum distance: %1").arg(lengthStr(measurement->length()))); } else if (mtype == MeasureType::PointToCylinder) { - print(tr("Minimum distance: %1, Axis distance: %2") - .arg(lengthStr(measurement->length()), - lengthStr(measurement->cylinderAxisDistance()))); + print( + tr("Minimum distance: %1, Axis distance: %2") + .arg(lengthStr(measurement->length()), lengthStr(measurement->cylinderAxisDistance())) + ); } else if (mtype == MeasureType::PointToCircle) { - print(tr("Minimum distance: %1, Center distance: %2") - .arg(lengthStr(measurement->length()), - lengthStr(measurement->circleCenterDistance()))); + print( + tr("Minimum distance: %1, Center distance: %2") + .arg(lengthStr(measurement->length()), lengthStr(measurement->circleCenterDistance())) + ); } else if (mtype == MeasureType::TwoCircles) { double angle = measurement->angle(); if (angle <= Precision::Confusion()) { print(tr("Total length: %1, Center distance: %2") - .arg(lengthStr(measurement->length()), - lengthStr(measurement->circleCenterDistance()))); + .arg( + lengthStr(measurement->length()), + lengthStr(measurement->circleCenterDistance()) + )); } else { print(tr("Total length: %1, Center distance: %2, Axis angle: %3") - .arg(lengthStr(measurement->length()), - lengthStr(measurement->circleCenterDistance()), - angleStr(angle))); + .arg( + lengthStr(measurement->length()), + lengthStr(measurement->circleCenterDistance()), + angleStr(angle) + )); } } else if (mtype == MeasureType::CircleToEdge) { - print(tr("Total length: %1, Center distance: %2") - .arg(lengthStr(measurement->length()), - lengthStr(measurement->circleCenterDistance()))); + print( + tr("Total length: %1, Center distance: %2") + .arg(lengthStr(measurement->length()), lengthStr(measurement->circleCenterDistance())) + ); } else if (mtype == MeasureType::CircleToSurface) { - print( - tr("Center surface distance: %1").arg(lengthStr(measurement->circleCenterDistance()))); + print(tr("Center surface distance: %1").arg(lengthStr(measurement->circleCenterDistance()))); } else if (mtype == MeasureType::CircleToCylinder) { double angle = measurement->angle(); if (angle <= Precision::Confusion()) { - print( - tr("Center axis distance: %1").arg(lengthStr(measurement->cylinderAxisDistance()))); + print(tr("Center axis distance: %1").arg(lengthStr(measurement->cylinderAxisDistance()))); } else { print(tr("Center axis distance: %1, Axis angle: %2") diff --git a/src/Mod/Measure/Gui/TaskMeasure.cpp b/src/Mod/Measure/Gui/TaskMeasure.cpp index 2ba8a302da..7da5a53d13 100644 --- a/src/Mod/Measure/Gui/TaskMeasure.cpp +++ b/src/Mod/Measure/Gui/TaskMeasure.cpp @@ -62,10 +62,12 @@ using SelectionStyle = Gui::SelectionSingleton::SelectionStyle; TaskMeasure::TaskMeasure() { this->setButtonPosition(TaskMeasure::South); - auto taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("umf-measurement"), - tr("Measurement"), - true, - nullptr); + auto taskbox = new Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("umf-measurement"), + tr("Measurement"), + true, + nullptr + ); setupShortcuts(taskbox); @@ -94,22 +96,27 @@ TaskMeasure::TaskMeasure() autoSaveAction->setChecked(mAutoSave); autoSaveAction->setToolTip( tr("Auto saving of the last measurement when starting a new " - "measurement. Use the Shift key to temporarily invert the behaviour.")); + "measurement. Use the Shift key to temporarily invert the behaviour.") + ); connect(autoSaveAction, &QAction::triggered, this, &TaskMeasure::autoSaveChanged); newMeasurementBehaviourAction = new QAction(tr("Additive Selection")); newMeasurementBehaviourAction->setCheckable(true); - newMeasurementBehaviourAction->setChecked(Gui::Selection().getSelectionStyle() - == SelectionStyle::GreedySelection); + newMeasurementBehaviourAction->setChecked( + Gui::Selection().getSelectionStyle() == SelectionStyle::GreedySelection + ); newMeasurementBehaviourAction->setToolTip( tr("If checked, new selection will be added to the measurement. If unchecked, the Ctrl key " "must be " "pressed to add a " - "selection to the current measurement otherwise a new measurement will be started")); - connect(newMeasurementBehaviourAction, - &QAction::triggered, - this, - &TaskMeasure::newMeasurementBehaviourChanged); + "selection to the current measurement otherwise a new measurement will be started") + ); + connect( + newMeasurementBehaviourAction, + &QAction::triggered, + this, + &TaskMeasure::newMeasurementBehaviourChanged + ); mSettings = new QToolButton(); mSettings->setToolTip(tr("Settings")); @@ -131,10 +138,7 @@ TaskMeasure::TaskMeasure() } // Connect dropdown's change signal to our onModeChange slot - connect(modeSwitch, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskMeasure::onModeChanged); + connect(modeSwitch, qOverload(&QComboBox::currentIndexChanged), this, &TaskMeasure::onModeChanged); // Result widget valueResult = new QLineEdit(); @@ -245,7 +249,8 @@ void TaskMeasure::createObject(const App::MeasureType* measureType) else { // Create measure object _mMeasureObject = dynamic_cast( - doc->addObject(measureType->measureObject.c_str(), measureType->label.c_str())); + doc->addObject(measureType->measureObject.c_str(), measureType->label.c_str()) + ); } } @@ -275,8 +280,7 @@ void TaskMeasure::tryUpdate() std::string mod = Base::Type::getModuleName(sub->getTypeId().getName()); if (!App::MeasureManager::hasMeasureHandler(mod.c_str())) { - Base::Console().message("No measure handler available for geometry of module: %s\n", - mod); + Base::Console().message("No measure handler available for geometry of module: %s\n", mod); clearSelection(); return; } @@ -390,9 +394,11 @@ void TaskMeasure::ensureGroup(Measure::MeasureBase* measurement) App::Document* doc = measurement->getDocument(); auto group = dynamic_cast(doc->getObject(measurementGroupName)); if (!group || !group->isValid()) { - group = doc->addObject(measurementGroupName, - true, - "MeasureGui::ViewProviderMeasureGroup"); + group = doc->addObject( + measurementGroupName, + true, + "MeasureGui::ViewProviderMeasureGroup" + ); } group->addObject(measurement); diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp b/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp index 49b47cb770..29166ed724 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp +++ b/src/Mod/Measure/Gui/ViewProviderMeasureAngle.cpp @@ -168,22 +168,24 @@ SbMatrix ViewProviderMeasureAngle::getMatrix() gp_Vec yAxis = zAxis.Crossed(xAxis).Normalized(); zAxis = xAxis.Crossed(yAxis).Normalized(); - dimSys = SbMatrix(xAxis.X(), - yAxis.X(), - zAxis.X(), - origin.X(), - xAxis.Y(), - yAxis.Y(), - zAxis.Y(), - origin.Y(), - xAxis.Z(), - yAxis.Z(), - zAxis.Z(), - origin.Z(), - 0.0, - 0.0, - 0.0, - 1.0); + dimSys = SbMatrix( + xAxis.X(), + yAxis.X(), + zAxis.X(), + origin.X(), + xAxis.Y(), + yAxis.Y(), + zAxis.Y(), + origin.Y(), + xAxis.Z(), + yAxis.Z(), + zAxis.Z(), + origin.Z(), + 0.0, + 0.0, + 0.0, + 1.0 + ); dimSys = dimSys.transpose(); radius = midPointProjection.Magnitude(); @@ -236,22 +238,24 @@ SbMatrix ViewProviderMeasureAngle::getMatrix() gp_Vec zAxis = (xAxis.Crossed(fakeYAxis)).Normalized(); gp_Vec yAxis = zAxis.Crossed(xAxis).Normalized(); - dimSys = SbMatrix(xAxis.X(), - yAxis.X(), - zAxis.X(), - dimensionOriginPoint.X(), - xAxis.Y(), - yAxis.Y(), - zAxis.Y(), - dimensionOriginPoint.Y(), - xAxis.Z(), - yAxis.Z(), - zAxis.Z(), - dimensionOriginPoint.Z(), - 0.0, - 0.0, - 0.0, - 1.0); + dimSys = SbMatrix( + xAxis.X(), + yAxis.X(), + zAxis.X(), + dimensionOriginPoint.X(), + xAxis.Y(), + yAxis.Y(), + zAxis.Y(), + dimensionOriginPoint.Y(), + xAxis.Z(), + yAxis.Z(), + zAxis.Z(), + dimensionOriginPoint.Z(), + 0.0, + 0.0, + 0.0, + 1.0 + ); dimSys = dimSys.transpose(); } @@ -292,7 +296,8 @@ ViewProviderMeasureAngle::ViewProviderMeasureAngle() engineAngle->A.connectFrom(&arcEngine->midpoint); engineAngle->B.connectFrom(&pLabelTranslation->translation); engineAngle->expression.setValue( - "tA=normalize(A); tB=normalize(B); oa=atan2(tB[1], tB[0])-atan2(tA[1], tA[0])"); + "tA=normalize(A); tB=normalize(B); oa=atan2(tB[1], tB[0])-atan2(tA[1], tA[0])" + ); Gui::ArcEngine* arcEngineSecondary = new Gui::ArcEngine(); arcEngineSecondary->radius.connectFrom(&calculatorRadius->oa); @@ -334,8 +339,7 @@ void ViewProviderMeasureAngle::redrawAnnotation() pcTransform->setMatrix(matrix); } catch (const Base::Exception& e) { - Base::Console().error("Error in ViewProviderMeasureAngle::redrawAnnotation: %s\n", - e.what()); + Base::Console().error("Error in ViewProviderMeasureAngle::redrawAnnotation: %s\n", e.what()); return; } diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp b/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp index f051d537b1..222e312935 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp +++ b/src/Mod/Measure/Gui/ViewProviderMeasureBase.cpp @@ -77,26 +77,34 @@ ViewProviderMeasureBase::ViewProviderMeasureBase() { static const char* agroup = "Appearance"; // NOLINTBEGIN - ADD_PROPERTY_TYPE(TextColor, - (Preferences::defaultTextColor()), - agroup, - App::Prop_None, - "Color for the measurement text"); - ADD_PROPERTY_TYPE(TextBackgroundColor, - (Preferences::defaultTextBackgroundColor()), - agroup, - App::Prop_None, - "Color for the measurement text background"); - ADD_PROPERTY_TYPE(LineColor, - (Preferences::defaultLineColor()), - agroup, - App::Prop_None, - "Color for the measurement lines"); - ADD_PROPERTY_TYPE(FontSize, - (Preferences::defaultFontSize()), - agroup, - App::Prop_None, - "Size of measurement text"); + ADD_PROPERTY_TYPE( + TextColor, + (Preferences::defaultTextColor()), + agroup, + App::Prop_None, + "Color for the measurement text" + ); + ADD_PROPERTY_TYPE( + TextBackgroundColor, + (Preferences::defaultTextBackgroundColor()), + agroup, + App::Prop_None, + "Color for the measurement text background" + ); + ADD_PROPERTY_TYPE( + LineColor, + (Preferences::defaultLineColor()), + agroup, + App::Prop_None, + "Color for the measurement lines" + ); + ADD_PROPERTY_TYPE( + FontSize, + (Preferences::defaultFontSize()), + agroup, + App::Prop_None, + "Size of measurement text" + ); // NOLINTEND pGlobalSeparator = new SoSeparator(); @@ -401,10 +409,12 @@ void ViewProviderMeasureBase::connectToSubject(App::DocumentObject* subject) } // NOLINTBEGIN - auto bndVisibility = std::bind(&ViewProviderMeasureBase::onSubjectVisibilityChanged, - this, - std::placeholders::_1, - std::placeholders::_2); + auto bndVisibility = std::bind( + &ViewProviderMeasureBase::onSubjectVisibilityChanged, + this, + std::placeholders::_1, + std::placeholders::_2 + ); // NOLINTEND _mVisibilityChangedConnection = subject->signalChanged.connect(bndVisibility); } @@ -439,8 +449,7 @@ Measure::MeasureBase* ViewProviderMeasureBase::getMeasureObject() //! layout of the elements and relationship with the cardinal axes and the view direction. //! elementDirection is expected to be a normalized vector. an example of an elementDirection would //! be the vector from the start of a line to the end. -Base::Vector3d ViewProviderMeasureBase::getTextDirection(Base::Vector3d elementDirection, - double tolerance) +Base::Vector3d ViewProviderMeasureBase::getTextDirection(Base::Vector3d elementDirection, double tolerance) { // TODO: this can fail if the active view is not a 3d view (spreadsheet, techdraw page) and // something causes a measure to try to update we need to search through the mdi views for a 3d @@ -454,8 +463,7 @@ Base::Vector3d ViewProviderMeasureBase::getTextDirection(Base::Vector3d elementD view = dynamic_cast(this->getActiveView()); } catch (const Base::RuntimeError&) { - Base::Console().log( - "ViewProviderMeasureBase::getTextDirection: Could not get active view\n"); + Base::Console().log("ViewProviderMeasureBase::getTextDirection: Could not get active view\n"); } if (view) { @@ -518,8 +526,10 @@ bool ViewProviderMeasureBase::isSubjectVisible() //! gets called when the subject object issues a signalChanged (ie a property change). We are only //! interested in the subject's Visibility property -void ViewProviderMeasureBase::onSubjectVisibilityChanged(const App::DocumentObject& docObj, - const App::Property& prop) +void ViewProviderMeasureBase::onSubjectVisibilityChanged( + const App::DocumentObject& docObj, + const App::Property& prop +) { if (docObj.isRemoving()) { return; @@ -603,9 +613,10 @@ ViewProviderMeasure::ViewProviderMeasure() lineSep->addChild(pCoords); lineSep->addChild(pLines); auto points = new SoMarkerSet(); - points->markerIndex = - Gui::Inventor::MarkerBitmaps::getMarkerIndex("CROSS", - Gui::ViewParams::instance()->getMarkerSize()); + points->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex( + "CROSS", + Gui::ViewParams::instance()->getMarkerSize() + ); points->numPoints = 1; lineSep->addChild(points); @@ -615,8 +626,7 @@ ViewProviderMeasure::ViewProviderMeasure() view = dynamic_cast(this->getActiveView()); } catch (const Base::RuntimeError&) { - Base::Console().log( - "ViewProviderMeasure::ViewProviderMeasure: Could not get active view\n"); + Base::Console().log("ViewProviderMeasure::ViewProviderMeasure: Could not get active view\n"); } if (view) { @@ -703,8 +713,7 @@ Base::Vector3d ViewProviderMeasure::getTextPosition() Gui::View3DInventor* view = dynamic_cast(this->getActiveView()); if (!view) { - Base::Console().log( - "ViewProviderMeasureBase::getTextPosition: Could not get active view\n"); + Base::Console().log("ViewProviderMeasureBase::getTextPosition: Could not get active view\n"); return Base::Vector3d(); } diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureBase.h b/src/Mod/Measure/Gui/ViewProviderMeasureBase.h index 28372462e4..34c9945dcd 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureBase.h +++ b/src/Mod/Measure/Gui/ViewProviderMeasureBase.h @@ -147,8 +147,10 @@ protected: SoSeparator* getSoSeparatorText(); static constexpr double defaultTolerance = 10e-6; - virtual Base::Vector3d getTextDirection(Base::Vector3d elementDirection, - double tolerance = defaultTolerance); + virtual Base::Vector3d getTextDirection( + Base::Vector3d elementDirection, + double tolerance = defaultTolerance + ); float getViewScale(); // TODO: getters & setters and move variables to private? diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureDistance.cpp b/src/Mod/Measure/Gui/ViewProviderMeasureDistance.cpp index b10fee78ed..097dbc565e 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureDistance.cpp +++ b/src/Mod/Measure/Gui/ViewProviderMeasureDistance.cpp @@ -253,23 +253,25 @@ SbMatrix ViewProviderMeasureDistance::getMatrix() assert(fabs(localYAxis.Dot(localXAxis)) < tolerance); Base::Vector3d localZAxis = localYAxis.Cross(localXAxis).Normalize(); - SbMatrix matrix = SbMatrix(localXAxis.x, - localXAxis.y, - localXAxis.z, - 0, - localYAxis.x, - localYAxis.y, - localYAxis.z, - 0, - localZAxis.x, - localZAxis.y, - localZAxis.z, - 0, - // 0,0,0,1 - origin[0], - origin[1], - origin[2], - 1); + SbMatrix matrix = SbMatrix( + localXAxis.x, + localXAxis.y, + localXAxis.z, + 0, + localYAxis.x, + localYAxis.y, + localYAxis.z, + 0, + localZAxis.x, + localZAxis.y, + localZAxis.z, + 0, + // 0,0,0,1 + origin[0], + origin[1], + origin[2], + 1 + ); return matrix; } @@ -279,8 +281,10 @@ SbMatrix ViewProviderMeasureDistance::getMatrix() //! layout of the elements and its relationship with the cardinal axes and the view direction. //! elementDirection is expected to be a normalized vector. an example of an elementDirection would //! be the vector from the start of a line to the end. -Base::Vector3d ViewProviderMeasureDistance::getTextDirection(Base::Vector3d elementDirection, - double tolerance) +Base::Vector3d ViewProviderMeasureDistance::getTextDirection( + Base::Vector3d elementDirection, + double tolerance +) { const Base::Vector3d stdX(1.0, 0.0, 0.0); const Base::Vector3d stdY(0.0, 1.0, 0.0); @@ -306,11 +310,13 @@ ViewProviderMeasureDistance::ViewProviderMeasureDistance() { sPixmap = "Measurement-Distance"; - ADD_PROPERTY_TYPE(ShowDelta, - (false), - "Appearance", - App::Prop_None, - "Display the X, Y and Z components of the distance"); + ADD_PROPERTY_TYPE( + ShowDelta, + (false), + "Appearance", + App::Prop_None, + "Display the X, Y and Z components of the distance" + ); // vert indexes used to create the annotation lines const size_t lineCount(3); @@ -343,8 +349,10 @@ ViewProviderMeasureDistance::ViewProviderMeasureDistance() auto engineCoords = new SoCalculator(); engineCoords->a.connectFrom(&fieldDistance); engineCoords->A.connectFrom(&pLabelTranslation->translation); - engineCoords->expression.setValue("ta=a/2; tb=A[1]; oA=vec3f(ta, 0, 0); oB=vec3f(-ta, 0, 0); " - "oC=vec3f(ta, tb, 0); oD=vec3f(-ta, tb, 0)"); + engineCoords->expression.setValue( + "ta=a/2; tb=A[1]; oA=vec3f(ta, 0, 0); oB=vec3f(-ta, 0, 0); " + "oC=vec3f(ta, tb, 0); oD=vec3f(-ta, tb, 0)" + ); auto engineCat = new SoConcatenate(SoMFVec3f::getClassTypeId()); engineCat->input[0]->connectFrom(&engineCoords->oA); @@ -374,9 +382,10 @@ ViewProviderMeasureDistance::ViewProviderMeasureDistance() pLineSeparatorSecondary->addChild(lineSetSecondary); auto points = new SoMarkerSet(); - points->markerIndex = - Gui::Inventor::MarkerBitmaps::getMarkerIndex("CROSS", - ViewParams::instance()->getMarkerSize()); + points->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex( + "CROSS", + ViewParams::instance()->getMarkerSize() + ); points->numPoints = 2; pLineSeparator->addChild(points); @@ -472,23 +481,25 @@ void ViewProviderMeasureDistance::redrawAnnotation() // Set the distance fieldDistance = (vec2 - vec1).Length(); - auto propDistance = - dynamic_cast(pcObject->getPropertyByName("Distance")); + auto propDistance = dynamic_cast(pcObject->getPropertyByName("Distance")); setLabelValue(QString::fromStdString(propDistance->getQuantityValue().getUserString())); // Set delta distance - auto propDistanceX = - static_cast(getMeasureObject()->getPropertyByName("DistanceX")); + auto propDistanceX = static_cast( + getMeasureObject()->getPropertyByName("DistanceX") + ); static_cast(pDeltaDimensionSwitch->getChild(0)) ->text.setValue(("Δx: " + propDistanceX->getQuantityValue().getUserString()).c_str()); - auto propDistanceY = - static_cast(getMeasureObject()->getPropertyByName("DistanceY")); + auto propDistanceY = static_cast( + getMeasureObject()->getPropertyByName("DistanceY") + ); static_cast(pDeltaDimensionSwitch->getChild(1)) ->text.setValue(("Δy: " + propDistanceY->getQuantityValue().getUserString()).c_str()); - auto propDistanceZ = - static_cast(getMeasureObject()->getPropertyByName("DistanceZ")); + auto propDistanceZ = static_cast( + getMeasureObject()->getPropertyByName("DistanceZ") + ); static_cast(pDeltaDimensionSwitch->getChild(2)) ->text.setValue(("Δz: " + propDistanceZ->getQuantityValue().getUserString()).c_str()); @@ -504,8 +515,9 @@ void ViewProviderMeasureDistance::onChanged(const App::Property* prop) { if (prop == &ShowDelta) { - pDeltaDimensionSwitch->whichChild.setValue(ShowDelta.getValue() ? SO_SWITCH_ALL - : SO_SWITCH_NONE); + pDeltaDimensionSwitch->whichChild.setValue( + ShowDelta.getValue() ? SO_SWITCH_ALL : SO_SWITCH_NONE + ); } else if (prop == &TextBackgroundColor) { auto bColor = TextBackgroundColor.getValue(); diff --git a/src/Mod/Measure/Gui/ViewProviderMeasureDistance.h b/src/Mod/Measure/Gui/ViewProviderMeasureDistance.h index 67a7e92d09..73b2e53f5b 100644 --- a/src/Mod/Measure/Gui/ViewProviderMeasureDistance.h +++ b/src/Mod/Measure/Gui/ViewProviderMeasureDistance.h @@ -99,8 +99,10 @@ public: void positionAnno(const Measure::MeasureBase* measureObject) override; protected: - Base::Vector3d getTextDirection(Base::Vector3d elementDirection, - double tolerance = defaultTolerance) override; + Base::Vector3d getTextDirection( + Base::Vector3d elementDirection, + double tolerance = defaultTolerance + ) override; void onChanged(const App::Property* prop) override; private: diff --git a/src/Mod/Measure/MeasureGlobal.h b/src/Mod/Measure/MeasureGlobal.h index e91b70987f..c50846635d 100644 --- a/src/Mod/Measure/MeasureGlobal.h +++ b/src/Mod/Measure/MeasureGlobal.h @@ -25,25 +25,25 @@ #include #ifndef MEASURE_GLOBAL_H -#define MEASURE_GLOBAL_H +# define MEASURE_GLOBAL_H // Measure -#ifndef MeasureExport -#ifdef Measure_EXPORTS -#define MeasureExport FREECAD_DECL_EXPORT -#else -#define MeasureExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef MeasureExport +# ifdef Measure_EXPORTS +# define MeasureExport FREECAD_DECL_EXPORT +# else +# define MeasureExport FREECAD_DECL_IMPORT +# endif +# endif // MeasureGui -#ifndef MeasureGuiExport -#ifdef MeasureGui_EXPORTS -#define MeasureGuiExport FREECAD_DECL_EXPORT -#else -#define MeasureGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef MeasureGuiExport +# ifdef MeasureGui_EXPORTS +# define MeasureGuiExport FREECAD_DECL_EXPORT +# else +# define MeasureGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // MEASURE_GLOBAL_H diff --git a/src/Mod/Mesh/App/AppMesh.cpp b/src/Mod/Mesh/App/AppMesh.cpp index f72a9a0153..242c10bbe1 100644 --- a/src/Mod/Mesh/App/AppMesh.cpp +++ b/src/Mod/Mesh/App/AppMesh.cpp @@ -61,7 +61,8 @@ PyMOD_INIT_FUNC(Mesh) // call PyType_Ready, otherwise we run into a segmentation fault, later on. // This function is responsible for adding inherited slots from a type's base class. ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh"); + "User parameter:BaseApp/Preferences/Mod/Mesh" + ); ParameterGrp::handle asy = handle->GetGroup("Asymptote"); MeshCore::MeshOutput::SetAsymptoteSize(asy->GetASCII("Width", "500"), asy->GetASCII("Height")); diff --git a/src/Mod/Mesh/App/AppMeshPy.cpp b/src/Mod/Mesh/App/AppMeshPy.cpp index ac40a221f9..85a0af0924 100644 --- a/src/Mod/Mesh/App/AppMeshPy.cpp +++ b/src/Mod/Mesh/App/AppMeshPy.cpp @@ -59,69 +59,78 @@ public: Module() : Py::ExtensionModule("Mesh") { - add_varargs_method("read", - &Module::read, - "Read a mesh from a file and returns a Mesh object."); - add_varargs_method("open", - &Module::open, - "open(string)\n" - "Create a new document and a Mesh feature to load the file into\n" - "the document."); - add_varargs_method("insert", - &Module::importer, - "insert(string|mesh,[string])\n" - "Load or insert a mesh into the given or active document."); - add_keyword_method("export", - &Module::exporter, - "export(objects, filename, [tolerance=0.1, exportAmfCompressed=True])\n" - "Export a list of objects into a single file identified by filename.\n" - "tolerance is in mm and specifies the maximum acceptable deviation\n" - "between the specified objects and the exported mesh.\n" - "exportAmfCompressed specifies whether exported AMF files should be\n" - "compressed.\n"); - add_varargs_method("show", - &Module::show, - "show(shape,[string]) -- Add the mesh to the active document or create " - "one if no document exists. Returns document object."); + add_varargs_method("read", &Module::read, "Read a mesh from a file and returns a Mesh object."); + add_varargs_method( + "open", + &Module::open, + "open(string)\n" + "Create a new document and a Mesh feature to load the file into\n" + "the document." + ); + add_varargs_method( + "insert", + &Module::importer, + "insert(string|mesh,[string])\n" + "Load or insert a mesh into the given or active document." + ); + add_keyword_method( + "export", + &Module::exporter, + "export(objects, filename, [tolerance=0.1, exportAmfCompressed=True])\n" + "Export a list of objects into a single file identified by filename.\n" + "tolerance is in mm and specifies the maximum acceptable deviation\n" + "between the specified objects and the exported mesh.\n" + "exportAmfCompressed specifies whether exported AMF files should be\n" + "compressed.\n" + ); + add_varargs_method( + "show", + &Module::show, + "show(shape,[string]) -- Add the mesh to the active document or create " + "one if no document exists. Returns document object." + ); add_varargs_method("createBox", &Module::createBox, "Create a solid mesh box"); add_varargs_method("createPlane", &Module::createPlane, "Create a mesh XY plane normal +Z"); add_varargs_method("createSphere", &Module::createSphere, "Create a tessellated sphere"); - add_varargs_method("createEllipsoid", - &Module::createEllipsoid, - "Create a tessellated ellipsoid"); - add_varargs_method("createCylinder", - &Module::createCylinder, - "Create a tessellated cylinder"); + add_varargs_method("createEllipsoid", &Module::createEllipsoid, "Create a tessellated ellipsoid"); + add_varargs_method("createCylinder", &Module::createCylinder, "Create a tessellated cylinder"); add_varargs_method("createCone", &Module::createCone, "Create a tessellated cone"); add_varargs_method("createTorus", &Module::createTorus, "Create a tessellated torus"); - add_varargs_method("calculateEigenTransform", - &Module::calculateEigenTransform, - "calculateEigenTransform(seq(Base.Vector))\n" - "Calculates the eigen Transformation from a list of points.\n" - "calculate the point's local coordinate system with the center\n" - "of gravity as origin. The local coordinate system is computed\n" - "this way that u has minimum and w has maximum expansion.\n" - "The local coordinate system is right-handed.\n"); - add_varargs_method("polynomialFit", - &Module::polynomialFit, - "polynomialFit(seq(Base.Vector)) -- Calculates a polynomial fit."); + add_varargs_method( + "calculateEigenTransform", + &Module::calculateEigenTransform, + "calculateEigenTransform(seq(Base.Vector))\n" + "Calculates the eigen Transformation from a list of points.\n" + "calculate the point's local coordinate system with the center\n" + "of gravity as origin. The local coordinate system is computed\n" + "this way that u has minimum and w has maximum expansion.\n" + "The local coordinate system is right-handed.\n" + ); + add_varargs_method( + "polynomialFit", + &Module::polynomialFit, + "polynomialFit(seq(Base.Vector)) -- Calculates a polynomial fit." + ); add_varargs_method( "minimumVolumeOrientedBox", &Module::minimumVolumeOrientedBox, "minimumVolumeOrientedBox(seq(Base.Vector)) -- Calculates the minimum\n" "volume oriented box containing all points. The return value is a\n" "tuple of seven items:\n" - " center, u, v, w directions and the lengths of the three vectors.\n"); - initialize("The functions in this module allow working with mesh objects.\n" - "A set of functions are provided for reading in registered mesh\n" - "file formats to either a new or existing document.\n" - "\n" - "open(string) -- Create a new document and a Mesh feature\n" - " to load the file into the document.\n" - "insert(string, string) -- Create a Mesh feature to load\n" - " the file into the given document.\n" - "Mesh() -- Create an empty mesh object.\n" - "\n"); + " center, u, v, w directions and the lengths of the three vectors.\n" + ); + initialize( + "The functions in this module allow working with mesh objects.\n" + "A set of functions are provided for reading in registered mesh\n" + "file formats to either a new or existing document.\n" + "\n" + "open(string) -- Create a new document and a Mesh feature\n" + " to load the file into the document.\n" + "insert(string, string) -- Create a Mesh feature to load\n" + " the file into the given document.\n" + "Mesh() -- Create an empty mesh object.\n" + "\n" + ); } private: @@ -204,28 +213,28 @@ private: // If tolerance is specified via python interface, use that. // If not, use the preference, if that exists, else default to 0.1mm. - auto hGrp(App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh")); + auto hGrp( + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Mesh") + ); auto fTolerance(hGrp->GetFloat("MaxDeviationExport", 0.1F)); int exportAmfCompressed(hGrp->GetBool("ExportAmfCompressed", true)); bool export3mfModel(hGrp->GetBool("Export3mfModel", true)); - static const std::array kwList {"objectList", - "filename", - "tolerance", - "exportAmfCompressed", - nullptr}; + static const std::array + kwList {"objectList", "filename", "tolerance", "exportAmfCompressed", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - keywds.ptr(), - "Oet|dp", - kwList, - &objects, - "utf-8", - &fileNamePy, - &fTolerance, - &exportAmfCompressed)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + keywds.ptr(), + "Oet|dp", + kwList, + &objects, + "utf-8", + &fileNamePy, + &fTolerance, + &exportAmfCompressed + )) { throw Py::Exception(); } @@ -260,23 +269,27 @@ private: std::map meta; meta["cad"] = App::Application::Config()["ExeName"] + " " + App::Application::Config()["ExeVersion"]; - meta[App::Application::Config()["ExeName"] + "-buildRevisionHash"] = - App::Application::Config()["BuildRevisionHash"]; + meta[App::Application::Config()["ExeName"] + "-buildRevisionHash"] + = App::Application::Config()["BuildRevisionHash"]; exporter = std::make_unique(outputFileName, meta, exportAmfCompressed); } else if (exportFormat == MeshIO::ThreeMF) { Extension3MFFactory::initialize(); - exporter = std::make_unique(outputFileName, - Extension3MFFactory::createExtensions()); + exporter = std::make_unique( + outputFileName, + Extension3MFFactory::createExtensions() + ); dynamic_cast(exporter.get())->setForceModel(export3mfModel); } else if (exportFormat != MeshIO::Undefined) { exporter = std::make_unique(outputFileName, exportFormat); } else { - std::string exStr("Cannot determine the mesh format from the file name.\nSpecify mesh " - "format file extension: '"); + std::string exStr( + "Cannot determine the mesh format from the file name.\nSpecify mesh " + "format file extension: '" + ); exStr += outputFileName + "'"; throw Py::ValueError(exStr.c_str()); } @@ -361,12 +374,16 @@ private: float hy = y / 2.0F; std::vector TriaList; - TriaList.emplace_back(Base::Vector3f(-hx, -hy, 0.0), - Base::Vector3f(hx, hy, 0.0), - Base::Vector3f(-hx, hy, 0.0)); - TriaList.emplace_back(Base::Vector3f(-hx, -hy, 0.0), - Base::Vector3f(hx, -hy, 0.0), - Base::Vector3f(hx, hy, 0.0)); + TriaList.emplace_back( + Base::Vector3f(-hx, -hy, 0.0), + Base::Vector3f(hx, hy, 0.0), + Base::Vector3f(-hx, hy, 0.0) + ); + TriaList.emplace_back( + Base::Vector3f(-hx, -hy, 0.0), + Base::Vector3f(hx, -hy, 0.0), + Base::Vector3f(hx, hy, 0.0) + ); std::unique_ptr mesh(new MeshObject); mesh->addFacets(TriaList); @@ -408,13 +425,7 @@ private: int closed = 1; float edgelen = 1.0F; int sampling = 50; - if (!PyArg_ParseTuple(args.ptr(), - "|ffifi", - &radius, - &length, - &closed, - &edgelen, - &sampling)) { + if (!PyArg_ParseTuple(args.ptr(), "|ffifi", &radius, &length, &closed, &edgelen, &sampling)) { throw Py::Exception(); } @@ -432,14 +443,7 @@ private: int closed = 1; float edgelen = 1.0F; int sampling = 50; - if (!PyArg_ParseTuple(args.ptr(), - "|fffifi", - &radius1, - &radius2, - &len, - &closed, - &edgelen, - &sampling)) { + if (!PyArg_ParseTuple(args.ptr(), "|fffifi", &radius1, &radius2, &len, &closed, &edgelen, &sampling)) { throw Py::Exception(); } @@ -596,8 +600,7 @@ private: throw Py::RuntimeError("Too few points"); } - Wm4::Box3d mobox = - Wm4::ContMinBox(points.size(), points.data(), 0.001, Wm4::Query::QT_REAL); + Wm4::Box3d mobox = Wm4::ContMinBox(points.size(), points.data(), 0.001, Wm4::Query::QT_REAL); Py::Tuple result(7); Base::Vector3d v; diff --git a/src/Mod/Mesh/App/Core/Algorithm.cpp b/src/Mod/Mesh/App/Core/Algorithm.cpp index da19a7879b..715114d390 100644 --- a/src/Mod/Mesh/App/Core/Algorithm.cpp +++ b/src/Mod/Mesh/App/Core/Algorithm.cpp @@ -43,9 +43,11 @@ using Base::BoundBox3f; using Base::Polygon2d; -bool MeshAlgorithm::IsVertexVisible(const Base::Vector3f& rcVertex, - const Base::Vector3f& rcView, - const MeshFacetGrid& rclGrid) const +bool MeshAlgorithm::IsVertexVisible( + const Base::Vector3f& rcVertex, + const Base::Vector3f& rcView, + const MeshFacetGrid& rclGrid +) const { const float fMaxDistance = 0.001F; Base::Vector3f cDirection = rcVertex - rcView; @@ -69,19 +71,23 @@ bool MeshAlgorithm::IsVertexVisible(const Base::Vector3f& rcVertex, return true; // no facet between the two points } -bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const +bool MeshAlgorithm::NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes, + FacetIndex& rulFacet +) const { return NearestFacetOnRay(rclPt, rclDir, Mathf::PI, rclRes, rulFacet); } -bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - float fMaxAngle, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const +bool MeshAlgorithm::NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + float fMaxAngle, + Base::Vector3f& rclRes, + FacetIndex& rulFacet +) const { Base::Vector3f clProj; Base::Vector3f clRes; @@ -116,11 +122,13 @@ bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, return bSol; } -bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - const MeshFacetGrid& rclGrid, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const +bool MeshAlgorithm::NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + const MeshFacetGrid& rclGrid, + Base::Vector3f& rclRes, + FacetIndex& rulFacet +) const { std::vector aulFacets; MeshGridIterator clGridIter(rclGrid); @@ -142,12 +150,14 @@ bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, return false; } -bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - float fMaxSearchArea, - const MeshFacetGrid& rclGrid, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const +bool MeshAlgorithm::NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + float fMaxSearchArea, + const MeshFacetGrid& rclGrid, + Base::Vector3f& rclRes, + FacetIndex& rulFacet +) const { const float fMaxAngle = 1.75F; std::vector aulFacets; @@ -170,11 +180,13 @@ bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, return false; } -bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - const std::vector& raulFacets, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const +bool MeshAlgorithm::NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + const std::vector& raulFacets, + Base::Vector3f& rclRes, + FacetIndex& rulFacet +) const { Base::Vector3f clProj; Base::Vector3f clRes; @@ -206,12 +218,14 @@ bool MeshAlgorithm::NearestFacetOnRay(const Base::Vector3f& rclPt, return bSol; } -bool MeshAlgorithm::RayNearestField(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - const std::vector& raulFacets, - Base::Vector3f& rclRes, - FacetIndex& rulFacet, - float /*fMaxAngle*/) const +bool MeshAlgorithm::RayNearestField( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + const std::vector& raulFacets, + Base::Vector3f& rclRes, + FacetIndex& rulFacet, + float /*fMaxAngle*/ +) const { Base::Vector3f clProj, clRes; bool bSol = false; @@ -241,10 +255,12 @@ bool MeshAlgorithm::RayNearestField(const Base::Vector3f& rclPt, return bSol; } -bool MeshAlgorithm::FirstFacetToVertex(const Base::Vector3f& rPt, - float fMaxDistance, - const MeshFacetGrid& rGrid, - FacetIndex& uIndex) const +bool MeshAlgorithm::FirstFacetToVertex( + const Base::Vector3f& rPt, + float fMaxDistance, + const MeshFacetGrid& rGrid, + FacetIndex& uIndex +) const { const float fEps = 0.001F; @@ -352,8 +368,10 @@ void MeshAlgorithm::GetMeshBorders(std::list>& rclBorder GetFacetBorders(aulAllFacets, rclBorders, true); } -void MeshAlgorithm::GetFacetBorders(const std::vector& raulInd, - std::list>& rclBorders) const +void MeshAlgorithm::GetFacetBorders( + const std::vector& raulInd, + std::list>& rclBorders +) const { const MeshPointArray& rclPAry = _rclMesh._aclPointArray; std::list> aulBorders; @@ -371,9 +389,11 @@ void MeshAlgorithm::GetFacetBorders(const std::vector& raulInd, } } -void MeshAlgorithm::GetFacetBorders(const std::vector& raulInd, - std::list>& rclBorders, - bool ignoreOrientation) const +void MeshAlgorithm::GetFacetBorders( + const std::vector& raulInd, + std::list>& rclBorders, + bool ignoreOrientation +) const { const MeshFacetArray& rclFAry = _rclMesh._aclFacetArray; @@ -502,8 +522,10 @@ void MeshAlgorithm::GetFacetBorder(FacetIndex uFacet, std::list& rBo SplitBoundaryFromOpenEdges(openEdges, rBorder); } -void MeshAlgorithm::GetFacetsBorders(const std::vector& uFacets, - std::list>& rBorders) const +void MeshAlgorithm::GetFacetsBorders( + const std::vector& uFacets, + std::list>& rBorders +) const { ResetFacetFlag(MeshFacet::TMP0); SetFacetsFlag(uFacets, MeshFacet::TMP0); @@ -561,7 +583,8 @@ void MeshAlgorithm::GetFacetsBorders(const std::vector& uFacets, void MeshAlgorithm::SplitBoundaryFromOpenEdges( std::list>& openEdges, - std::list& boundary) const + std::list& boundary +) const { // Start with the edge that is associated to uFacet if (openEdges.empty()) { @@ -638,8 +661,10 @@ void MeshAlgorithm::SplitBoundaryLoops(std::list>& aBord aBorders = aSplitBorders; } -void MeshAlgorithm::SplitBoundaryLoops(const std::vector& rBound, - std::list>& aBorders) +void MeshAlgorithm::SplitBoundaryLoops( + const std::vector& rBound, + std::list>& aBorders +) { std::map aPtDegree; std::vector cBound; @@ -663,12 +688,14 @@ void MeshAlgorithm::SplitBoundaryLoops(const std::vector& rBound, } } -bool MeshAlgorithm::FillupHole(const std::vector& boundary, - AbstractPolygonTriangulator& cTria, - MeshFacetArray& rFaces, - MeshPointArray& rPoints, - int level, - const MeshRefPointToFacets* pP2FStructure) const +bool MeshAlgorithm::FillupHole( + const std::vector& boundary, + AbstractPolygonTriangulator& cTria, + MeshFacetArray& rFaces, + MeshPointArray& rPoints, + int level, + const MeshRefPointToFacets* pP2FStructure +) const { if (boundary.front() == boundary.back()) { // first and last vertex are identical @@ -689,11 +716,13 @@ bool MeshAlgorithm::FillupHole(const std::vector& boundary, const std::set& ring1 = (*pP2FStructure)[refPoint0]; const std::set& ring2 = (*pP2FStructure)[refPoint1]; std::vector f_int; - std::set_intersection(ring1.begin(), - ring1.end(), - ring2.begin(), - ring2.end(), - std::back_insert_iterator>(f_int)); + std::set_intersection( + ring1.begin(), + ring1.end(), + ring2.begin(), + ring2.end(), + std::back_insert_iterator>(f_int) + ); if (f_int.size() != 1) { return false; // error, this must be an open edge! } @@ -811,7 +840,8 @@ bool MeshAlgorithm::FillupHole(const std::vector& boundary, "MeshAlgorithm::FillupHole: Expected open edge for facet <%d, %d, %d>\n", rFace._aulPoints[0], rFace._aulPoints[1], - rFace._aulPoints[2]); + rFace._aulPoints[2] + ); rFaces.clear(); rPoints.clear(); cTria.Discard(); @@ -857,8 +887,10 @@ bool MeshAlgorithm::FillupHole(const std::vector& boundary, return false; } -void MeshAlgorithm::SetFacetsProperty(const std::vector& raulInds, - const std::vector& raulProps) const +void MeshAlgorithm::SetFacetsProperty( + const std::vector& raulInds, + const std::vector& raulProps +) const { if (raulInds.size() != raulProps.size()) { return; @@ -870,16 +902,14 @@ void MeshAlgorithm::SetFacetsProperty(const std::vector& raulInds, } } -void MeshAlgorithm::SetFacetsFlag(const std::vector& raulInds, - MeshFacet::TFlagType tF) const +void MeshAlgorithm::SetFacetsFlag(const std::vector& raulInds, MeshFacet::TFlagType tF) const { for (FacetIndex it : raulInds) { _rclMesh._aclFacetArray[it].SetFlag(tF); } } -void MeshAlgorithm::SetPointsFlag(const std::vector& raulInds, - MeshPoint::TFlagType tF) const +void MeshAlgorithm::SetPointsFlag(const std::vector& raulInds, MeshPoint::TFlagType tF) const { for (PointIndex it : raulInds) { _rclMesh._aclPointArray[it].SetFlag(tF); @@ -910,16 +940,14 @@ void MeshAlgorithm::GetPointsFlag(std::vector& raulInds, MeshPoint:: } } -void MeshAlgorithm::ResetFacetsFlag(const std::vector& raulInds, - MeshFacet::TFlagType tF) const +void MeshAlgorithm::ResetFacetsFlag(const std::vector& raulInds, MeshFacet::TFlagType tF) const { for (FacetIndex it : raulInds) { _rclMesh._aclFacetArray[it].ResetFlag(tF); } } -void MeshAlgorithm::ResetPointsFlag(const std::vector& raulInds, - MeshPoint::TFlagType tF) const +void MeshAlgorithm::ResetPointsFlag(const std::vector& raulInds, MeshPoint::TFlagType tF) const { for (PointIndex it : raulInds) { _rclMesh._aclPointArray[it].ResetFlag(tF); @@ -949,26 +977,28 @@ void MeshAlgorithm::ResetPointFlag(MeshPoint::TFlagType tF) const unsigned long MeshAlgorithm::CountFacetFlag(MeshFacet::TFlagType tF) const { MeshIsFlag flag; - return std::count_if(_rclMesh._aclFacetArray.begin(), - _rclMesh._aclFacetArray.end(), - [flag, tF](const MeshFacet& f) { - return flag(f, tF); - }); + return std::count_if( + _rclMesh._aclFacetArray.begin(), + _rclMesh._aclFacetArray.end(), + [flag, tF](const MeshFacet& f) { return flag(f, tF); } + ); } unsigned long MeshAlgorithm::CountPointFlag(MeshPoint::TFlagType tF) const { MeshIsFlag flag; - return std::count_if(_rclMesh._aclPointArray.begin(), - _rclMesh._aclPointArray.end(), - [flag, tF](const MeshPoint& f) { - return flag(f, tF); - }); + return std::count_if( + _rclMesh._aclPointArray.begin(), + _rclMesh._aclPointArray.end(), + [flag, tF](const MeshPoint& f) { return flag(f, tF); } + ); } -void MeshAlgorithm::GetFacetsFromToolMesh(const MeshKernel& rToolMesh, - const Base::Vector3f& rcDir, - std::vector& raclCutted) const +void MeshAlgorithm::GetFacetsFromToolMesh( + const MeshKernel& rToolMesh, + const Base::Vector3f& rcDir, + std::vector& raclCutted +) const { MeshFacetIterator cFIt(_rclMesh); MeshFacetIterator cTIt(rToolMesh); @@ -1013,10 +1043,12 @@ void MeshAlgorithm::GetFacetsFromToolMesh(const MeshKernel& rToolMesh, } } -void MeshAlgorithm::GetFacetsFromToolMesh(const MeshKernel& rToolMesh, - const Base::Vector3f& rcDir, - const MeshFacetGrid& rGrid, - std::vector& raclCutted) const +void MeshAlgorithm::GetFacetsFromToolMesh( + const MeshKernel& rToolMesh, + const Base::Vector3f& rcDir, + const MeshFacetGrid& rGrid, + std::vector& raclCutted +) const { // iterator over grid structure MeshGridIterator clGridIter(rGrid); @@ -1113,14 +1145,16 @@ int MeshAlgorithm::Surround(const Base::BoundBox3f& rBox, const Base::Vector3f& // at least both boxes intersect if (cBB && rBox) { // check for intersections with the actual mesh - Base::Vector3f cCorner[8] = {Base::Vector3f(rBox.MinX, rBox.MinY, rBox.MinZ), - Base::Vector3f(rBox.MaxX, rBox.MinY, rBox.MinZ), - Base::Vector3f(rBox.MaxX, rBox.MaxY, rBox.MinZ), - Base::Vector3f(rBox.MinX, rBox.MaxY, rBox.MinZ), - Base::Vector3f(rBox.MinX, rBox.MinY, rBox.MaxZ), - Base::Vector3f(rBox.MaxX, rBox.MinY, rBox.MaxZ), - Base::Vector3f(rBox.MaxX, rBox.MaxY, rBox.MaxZ), - Base::Vector3f(rBox.MinX, rBox.MaxY, rBox.MaxZ)}; + Base::Vector3f cCorner[8] = { + Base::Vector3f(rBox.MinX, rBox.MinY, rBox.MinZ), + Base::Vector3f(rBox.MaxX, rBox.MinY, rBox.MinZ), + Base::Vector3f(rBox.MaxX, rBox.MaxY, rBox.MinZ), + Base::Vector3f(rBox.MinX, rBox.MaxY, rBox.MinZ), + Base::Vector3f(rBox.MinX, rBox.MinY, rBox.MaxZ), + Base::Vector3f(rBox.MaxX, rBox.MinY, rBox.MaxZ), + Base::Vector3f(rBox.MaxX, rBox.MaxY, rBox.MaxZ), + Base::Vector3f(rBox.MinX, rBox.MaxY, rBox.MaxZ) + }; MeshFacetIterator cTIt(_rclMesh); @@ -1174,11 +1208,13 @@ int MeshAlgorithm::Surround(const Base::BoundBox3f& rBox, const Base::Vector3f& return -1; } -void MeshAlgorithm::CheckFacets(const MeshFacetGrid& rclGrid, - const Base::ViewProjMethod* pclProj, - const Base::Polygon2d& rclPoly, - bool bInner, - std::vector& raulFacets) const +void MeshAlgorithm::CheckFacets( + const MeshFacetGrid& rclGrid, + const Base::ViewProjMethod* pclProj, + const Base::Polygon2d& rclPoly, + bool bInner, + std::vector& raulFacets +) const { std::vector::iterator it; MeshFacetIterator clIter(_rclMesh, 0); @@ -1208,8 +1244,10 @@ void MeshAlgorithm::CheckFacets(const MeshFacetGrid& rclGrid, // remove duplicates std::sort(aulAllElements.begin(), aulAllElements.end()); - aulAllElements.erase(std::unique(aulAllElements.begin(), aulAllElements.end()), - aulAllElements.end()); + aulAllElements.erase( + std::unique(aulAllElements.begin(), aulAllElements.end()), + aulAllElements.end() + ); Base::SequencerLauncher seq("Check facets", aulAllElements.size()); @@ -1258,10 +1296,12 @@ void MeshAlgorithm::CheckFacets(const MeshFacetGrid& rclGrid, } } -void MeshAlgorithm::CheckFacets(const Base::ViewProjMethod* pclProj, - const Base::Polygon2d& rclPoly, - bool bInner, - std::vector& raulFacets) const +void MeshAlgorithm::CheckFacets( + const Base::ViewProjMethod* pclProj, + const Base::Polygon2d& rclPoly, + bool bInner, + std::vector& raulFacets +) const { const MeshPointArray& p = _rclMesh.GetPoints(); const MeshFacetArray& f = _rclMesh.GetFacets(); @@ -1324,17 +1364,18 @@ void MeshAlgorithm::SubSampleAllPoints(std::vector& rclPoints) c } } -void MeshAlgorithm::SubSampleByCount(unsigned long ulCtPoints, - std::vector& rclPoints) const +void MeshAlgorithm::SubSampleByCount(unsigned long ulCtPoints, std::vector& rclPoints) const { float fDist = float(std::sqrt(Surface() / float(ulCtPoints))); SubSampleByDist(fDist, rclPoints); } -void MeshAlgorithm::SearchFacetsFromPolyline(const std::vector& rclPolyline, - float fRadius, - const MeshFacetGrid& rclGrid, - std::vector& rclResultFacetsIndices) const +void MeshAlgorithm::SearchFacetsFromPolyline( + const std::vector& rclPolyline, + float fRadius, + const MeshFacetGrid& rclGrid, + std::vector& rclResultFacetsIndices +) const { rclResultFacetsIndices.clear(); if (rclPolyline.size() < 3) { @@ -1359,13 +1400,10 @@ void MeshAlgorithm::SearchFacetsFromPolyline(const std::vector& } } - rclResultFacetsIndices.insert(rclResultFacetsIndices.begin(), - aclFacets.begin(), - aclFacets.end()); + rclResultFacetsIndices.insert(rclResultFacetsIndices.begin(), aclFacets.begin(), aclFacets.end()); } -void MeshAlgorithm::CutBorderFacets(std::vector& raclFacetIndices, - unsigned short usLevel) const +void MeshAlgorithm::CutBorderFacets(std::vector& raclFacetIndices, unsigned short usLevel) const { std::vector aclToDelete; @@ -1400,9 +1438,11 @@ unsigned long MeshAlgorithm::CountBorderEdges() const return cnt; } -void MeshAlgorithm::CheckBorderFacets(const std::vector& raclFacetIndices, - std::vector& raclResultIndices, - unsigned short usLevel) const +void MeshAlgorithm::CheckBorderFacets( + const std::vector& raclFacetIndices, + std::vector& raclResultIndices, + unsigned short usLevel +) const { ResetFacetFlag(MeshFacet::TMP0); SetFacetsFlag(raclFacetIndices, MeshFacet::TMP0); @@ -1427,8 +1467,10 @@ void MeshAlgorithm::CheckBorderFacets(const std::vector& raclFacetIn } } -void MeshAlgorithm::GetBorderPoints(const std::vector& raclFacetIndices, - std::set& raclResultPointsIndices) const +void MeshAlgorithm::GetBorderPoints( + const std::vector& raclFacetIndices, + std::set& raclResultPointsIndices +) const { ResetFacetFlag(MeshFacet::TMP0); SetFacetsFlag(raclFacetIndices, MeshFacet::TMP0); @@ -1453,9 +1495,11 @@ void MeshAlgorithm::GetBorderPoints(const std::vector& raclFacetIndi } } -bool MeshAlgorithm::NearestPointFromPoint(const Base::Vector3f& rclPt, - FacetIndex& rclResFacetIndex, - Base::Vector3f& rclResPoint) const +bool MeshAlgorithm::NearestPointFromPoint( + const Base::Vector3f& rclPt, + FacetIndex& rclResFacetIndex, + Base::Vector3f& rclResPoint +) const { if (_rclMesh.CountFacets() == 0) { return false; @@ -1480,10 +1524,12 @@ bool MeshAlgorithm::NearestPointFromPoint(const Base::Vector3f& rclPt, return true; } -bool MeshAlgorithm::NearestPointFromPoint(const Base::Vector3f& rclPt, - const MeshFacetGrid& rclGrid, - FacetIndex& rclResFacetIndex, - Base::Vector3f& rclResPoint) const +bool MeshAlgorithm::NearestPointFromPoint( + const Base::Vector3f& rclPt, + const MeshFacetGrid& rclGrid, + FacetIndex& rclResFacetIndex, + Base::Vector3f& rclResPoint +) const { FacetIndex ulInd = rclGrid.SearchNearestFromPoint(rclPt); @@ -1498,11 +1544,13 @@ bool MeshAlgorithm::NearestPointFromPoint(const Base::Vector3f& rclPt, return true; } -bool MeshAlgorithm::NearestPointFromPoint(const Base::Vector3f& rclPt, - const MeshFacetGrid& rclGrid, - float fMaxSearchArea, - FacetIndex& rclResFacetIndex, - Base::Vector3f& rclResPoint) const +bool MeshAlgorithm::NearestPointFromPoint( + const Base::Vector3f& rclPt, + const MeshFacetGrid& rclGrid, + float fMaxSearchArea, + FacetIndex& rclResFacetIndex, + Base::Vector3f& rclResPoint +) const { FacetIndex ulInd = rclGrid.SearchNearestFromPoint(rclPt, fMaxSearchArea); @@ -1517,12 +1565,14 @@ bool MeshAlgorithm::NearestPointFromPoint(const Base::Vector3f& rclPt, return true; } -bool MeshAlgorithm::CutWithPlane(const Base::Vector3f& clBase, - const Base::Vector3f& clNormal, - const MeshFacetGrid& rclGrid, - std::list>& rclResult, - float fMinEps, - bool bConnectPolygons) const +bool MeshAlgorithm::CutWithPlane( + const Base::Vector3f& clBase, + const Base::Vector3f& clNormal, + const MeshFacetGrid& rclGrid, + std::list>& rclResult, + float fMinEps, + bool bConnectPolygons +) const { std::vector aulFacets; @@ -1540,8 +1590,8 @@ bool MeshAlgorithm::CutWithPlane(const Base::Vector3f& clBase, aulFacets.erase(std::unique(aulFacets.begin(), aulFacets.end()), aulFacets.end()); // intersect all facets with plane - std::list> - clTempPoly; // Field with intersection lines (unsorted, not chained) + std::list> clTempPoly; // Field with intersection lines + // (unsorted, not chained) for (FacetIndex facetIndex : aulFacets) { Base::Vector3f clE1, clE2; @@ -1555,8 +1605,10 @@ bool MeshAlgorithm::CutWithPlane(const Base::Vector3f& clBase, if (bConnectPolygons) { // std::list > rclTempLines; - std::list> rclResultLines(clTempPoly.begin(), - clTempPoly.end()); + std::list> rclResultLines( + clTempPoly.begin(), + clTempPoly.end() + ); std::list> tempList; ConnectLines(clTempPoly, tempList, fMinEps); ConnectPolygons(tempList, clTempPoly); @@ -1571,9 +1623,11 @@ bool MeshAlgorithm::CutWithPlane(const Base::Vector3f& clBase, return ConnectLines(clTempPoly, rclResult, fMinEps); } -bool MeshAlgorithm::ConnectLines(std::list>& rclLines, - std::list>& rclPolylines, - float fMinEps) const +bool MeshAlgorithm::ConnectLines( + std::list>& rclLines, + std::list>& rclPolylines, + float fMinEps +) const { using TCIter = std::list>::iterator; @@ -1693,7 +1747,8 @@ bool MeshAlgorithm::ConnectLines(std::list>& clPolyList, - std::list>& rclLines) const + std::list>& rclLines +) const { for (auto OutIter = clPolyList.begin(); OutIter != clPolyList.end(); ++OutIter) { @@ -1727,12 +1782,14 @@ bool MeshAlgorithm::ConnectPolygons( return true; } -void MeshAlgorithm::GetFacetsFromPlane(const MeshFacetGrid& rclGrid, - const Base::Vector3f& clNormal, - float d, - const Base::Vector3f& rclLeft, - const Base::Vector3f& rclRight, - std::vector& rclRes) const +void MeshAlgorithm::GetFacetsFromPlane( + const MeshFacetGrid& rclGrid, + const Base::Vector3f& clNormal, + float d, + const Base::Vector3f& rclLeft, + const Base::Vector3f& rclRight, + std::vector& rclRes +) const { std::vector aulFacets; @@ -1770,8 +1827,10 @@ void MeshAlgorithm::GetFacetsFromPlane(const MeshFacetGrid& rclGrid, } } -void MeshAlgorithm::PointsFromFacetsIndices(const std::vector& rvecIndices, - std::vector& rvecPoints) const +void MeshAlgorithm::PointsFromFacetsIndices( + const std::vector& rvecIndices, + std::vector& rvecPoints +) const { const MeshFacetArray& rclFAry = _rclMesh._aclFacetArray; const MeshPointArray& rclPAry = _rclMesh._aclPointArray; @@ -1790,10 +1849,12 @@ void MeshAlgorithm::PointsFromFacetsIndices(const std::vector& rvecI } } -bool MeshAlgorithm::Distance(const Base::Vector3f& rclPt, - FacetIndex ulFacetIdx, - float fMaxDistance, - float& rfDistance) const +bool MeshAlgorithm::Distance( + const Base::Vector3f& rclPt, + FacetIndex ulFacetIdx, + float fMaxDistance, + float& rfDistance +) const { const MeshFacetArray& rclFAry = _rclMesh._aclFacetArray; const MeshPointArray& rclPAry = _rclMesh._aclPointArray; @@ -1814,17 +1875,19 @@ bool MeshAlgorithm::Distance(const Base::Vector3f& rclPt, return rfDistance < fMaxDistance; } -float MeshAlgorithm::CalculateMinimumGridLength(float fLength, - const Base::BoundBox3f& rBBox, - unsigned long maxElements) const +float MeshAlgorithm::CalculateMinimumGridLength( + float fLength, + const Base::BoundBox3f& rBBox, + unsigned long maxElements +) const { // Max. limit of grid elements float fMaxGridElements = static_cast(maxElements); // estimate the minimum allowed grid length float fMinGridLen = static_cast( - std::pow((rBBox.LengthX() * rBBox.LengthY() * rBBox.LengthZ() / fMaxGridElements), - 0.3333F)); + std::pow((rBBox.LengthX() * rBBox.LengthY() * rBBox.LengthZ() / fMaxGridElements), 0.3333F) + ); return std::max(fMinGridLen, fLength); } @@ -1860,8 +1923,10 @@ Base::Vector3f MeshRefPointToFacets::GetNormal(PointIndex pos) const return normal; } -std::set MeshRefPointToFacets::NeighbourPoints(const std::vector& pt, - int level) const +std::set MeshRefPointToFacets::NeighbourPoints( + const std::vector& pt, + int level +) const { std::set cp, nb, lp; cp.insert(pt.begin(), pt.end()); @@ -1910,9 +1975,7 @@ std::set MeshRefPointToFacets::NeighbourPoints(PointIndex pos) const return p; } -void MeshRefPointToFacets::Neighbours(FacetIndex ulFacetInd, - float fMaxDist, - MeshCollector& collect) const +void MeshRefPointToFacets::Neighbours(FacetIndex ulFacetInd, float fMaxDist, MeshCollector& collect) const { std::set visited; Base::Vector3f clCenter = _rclMesh.GetFacet(ulFacetInd).GetGravityPoint(); @@ -1921,12 +1984,14 @@ void MeshRefPointToFacets::Neighbours(FacetIndex ulFacetInd, SearchNeighbours(rFacets, ulFacetInd, clCenter, fMaxDist * fMaxDist, visited, collect); } -void MeshRefPointToFacets::SearchNeighbours(const MeshFacetArray& rFacets, - FacetIndex index, - const Base::Vector3f& rclCenter, - float fMaxDist2, - std::set& visited, - MeshCollector& collect) const +void MeshRefPointToFacets::SearchNeighbours( + const MeshFacetArray& rFacets, + FacetIndex index, + const Base::Vector3f& rclCenter, + float fMaxDist2, + std::set& visited, + MeshCollector& collect +) const { if (visited.find(index) != visited.end()) { return; @@ -1968,8 +2033,11 @@ std::vector MeshRefPointToFacets::GetIndices(PointIndex pos1, PointI return intersection; } -std::vector -MeshRefPointToFacets::GetIndices(PointIndex pos1, PointIndex pos2, PointIndex pos3) const +std::vector MeshRefPointToFacets::GetIndices( + PointIndex pos1, + PointIndex pos2, + PointIndex pos3 +) const { std::vector intersection; std::back_insert_iterator> result(intersection); diff --git a/src/Mod/Mesh/App/Core/Algorithm.h b/src/Mod/Mesh/App/Core/Algorithm.h index c8792acae3..e4f4436940 100644 --- a/src/Mod/Mesh/App/Core/Algorithm.h +++ b/src/Mod/Mesh/App/Core/Algorithm.h @@ -71,10 +71,12 @@ public: * \note This method tests all facets so it should only be used * occasionally. */ - bool NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const; + bool NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes, + FacetIndex& rulFacet + ) const; /** * Searches for the nearest facet to the ray defined by * (\a rclPt, \a rclDir). @@ -83,11 +85,13 @@ public: * triangle must be less than or equal to \a fMaxAngle. \note This method tests all facets so it * should only be used occasionally. */ - bool NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - float fMaxAngle, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const; + bool NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + float fMaxAngle, + Base::Vector3f& rclRes, + FacetIndex& rulFacet + ) const; /** * Searches for the nearest facet to the ray defined by * (\a rclPt, \a rclDir). @@ -96,11 +100,13 @@ public: * \note This method is optimized by using a grid. So this method can be * used for a lot of tests. */ - bool NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - const MeshFacetGrid& rclGrid, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const; + bool NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + const MeshFacetGrid& rclGrid, + Base::Vector3f& rclRes, + FacetIndex& rulFacet + ) const; /** * Searches for the nearest facet to the ray defined by * (\a rclPt, \a rclDir). @@ -110,40 +116,48 @@ public: * the attached mesh. So the caller must ensure that the indices are valid * facets. */ - bool NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - const std::vector& raulFacets, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const; + bool NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + const std::vector& raulFacets, + Base::Vector3f& rclRes, + FacetIndex& rulFacet + ) const; /** * Searches for the nearest facet to the ray defined by (\a rclPt, \a rclDir). The point \a * rclRes holds the intersection point with the ray and the nearest facet with index \a * rulFacet. More a search radius around the ray of \a fMaxSearchArea is defined. \note This * method is optimized by using a grid. So this method can be used for a lot of tests. */ - bool NearestFacetOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - float fMaxSearchArea, - const MeshFacetGrid& rclGrid, - Base::Vector3f& rclRes, - FacetIndex& rulFacet) const; + bool NearestFacetOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + float fMaxSearchArea, + const MeshFacetGrid& rclGrid, + Base::Vector3f& rclRes, + FacetIndex& rulFacet + ) const; /** * Searches for the first facet of the grid element (\a rGrid) in that the point \a rPt lies * into which is a distance not higher than \a fMaxDistance. Of no such facet is found \a * uIndex is undefined and false is returned, otherwise true. \note If the point \a rPt is * outside of the grid \a rclGrid nothing is done. */ - bool FirstFacetToVertex(const Base::Vector3f& rPt, - float fMaxDistance, - const MeshFacetGrid& rGrid, - FacetIndex& uIndex) const; + bool FirstFacetToVertex( + const Base::Vector3f& rPt, + float fMaxDistance, + const MeshFacetGrid& rGrid, + FacetIndex& uIndex + ) const; /** * Checks from the viewpoint \a rcView if the vertex \a rcVertex is visible or it is hidden by a * facet. If the vertex is visible true is returned, false otherwise. */ - bool IsVertexVisible(const Base::Vector3f& rcVertex, - const Base::Vector3f& rcView, - const MeshFacetGrid& rclGrid) const; + bool IsVertexVisible( + const Base::Vector3f& rcVertex, + const Base::Vector3f& rcView, + const MeshFacetGrid& rclGrid + ) const; /** * Calculates the average length of edges. */ @@ -172,8 +186,10 @@ public: /** * Returns all boundaries of a subset the mesh defined by \a raulInd. */ - void GetFacetBorders(const std::vector& raulInd, - std::list>& rclBorders) const; + void GetFacetBorders( + const std::vector& raulInd, + std::list>& rclBorders + ) const; /** * Returns all boundaries of a subset the mesh defined by \a raulInd. This method does basically * the same as above unless that it returns the point indices of the boundaries. If \a @@ -182,9 +198,11 @@ public: * curve with wrong orientation even if the mesh is topologically correct. You should let the * default value unless you exactly know what you do. */ - void GetFacetBorders(const std::vector& raulInd, - std::list>& rclBorders, - bool ignoreOrientation = false) const; + void GetFacetBorders( + const std::vector& raulInd, + std::list>& rclBorders, + bool ignoreOrientation = false + ) const; /** * Returns the boundary of the mesh to the facet \a uFacet. If this facet does not have an open * edge the returned boundary is empty. @@ -194,8 +212,10 @@ public: * Returns the boundary of the mesh to the facets \a uFacest. If none of the facets have an open * edge the returned boundary is empty. */ - void GetFacetsBorders(const std::vector& uFacets, - std::list>& rBorders) const; + void GetFacetsBorders( + const std::vector& uFacets, + std::list>& rBorders + ) const; /** * Boundaries that consist of several loops must be split in several independent boundaries * to perform e.g. a polygon triangulation algorithm on them. @@ -214,17 +234,21 @@ public: * @note If the number of geometric points exceeds the number of boundary indices then the * triangulation algorithm has introduced new points which are added to the end of \a rPoints. */ - bool FillupHole(const std::vector& boundary, - AbstractPolygonTriangulator& cTria, - MeshFacetArray& rFaces, - MeshPointArray& rPoints, - int level, - const MeshRefPointToFacets* pP2FStructure = nullptr) const; + bool FillupHole( + const std::vector& boundary, + AbstractPolygonTriangulator& cTria, + MeshFacetArray& rFaces, + MeshPointArray& rPoints, + int level, + const MeshRefPointToFacets* pP2FStructure = nullptr + ) const; /** Sets to all facets in \a raulInds the properties in raulProps. * \note Both arrays must have the same size. */ - void SetFacetsProperty(const std::vector& raulInds, - const std::vector& raulProps) const; + void SetFacetsProperty( + const std::vector& raulInds, + const std::vector& raulProps + ) const; /** Sets to all facets the flag \a tF. */ void SetFacetFlag(MeshFacet::TFlagType tF) const; /** Sets to all points the flag \a tF. */ @@ -250,8 +274,10 @@ public: /** Count all points with the flag \a tF. */ unsigned long CountPointFlag(MeshPoint::TFlagType tF) const; /** Returns all geometric points from the facets in \a rvecIndices. */ - void PointsFromFacetsIndices(const std::vector& rvecIndices, - std::vector& rvecPoints) const; + void PointsFromFacetsIndices( + const std::vector& rvecIndices, + std::vector& rvecPoints + ) const; /** * Returns the indices of all facets that have at least one point that lies inside the tool * mesh. The direction \a dir is used to try to foraminate the facets of the tool mesh and @@ -261,17 +287,21 @@ public: * @note It's not tested if \a rToolMesh is a valid solid. In case it is not the result is * undefined. */ - void GetFacetsFromToolMesh(const MeshKernel& rToolMesh, - const Base::Vector3f& rcDir, - std::vector& raclCutted) const; + void GetFacetsFromToolMesh( + const MeshKernel& rToolMesh, + const Base::Vector3f& rcDir, + std::vector& raclCutted + ) const; /** * Does basically the same as method above except it uses a mesh grid to speed up the * computation. */ - void GetFacetsFromToolMesh(const MeshKernel& rToolMesh, - const Base::Vector3f& rcDir, - const MeshFacetGrid& rGrid, - std::vector& raclCutted) const; + void GetFacetsFromToolMesh( + const MeshKernel& rToolMesh, + const Base::Vector3f& rcDir, + const MeshFacetGrid& rGrid, + std::vector& raclCutted + ) const; /** * Checks whether the bounding box \a rBox is surrounded by the attached mesh which must be a * solid. The direction \a rcDir is used to try to foraminate the facets of the tool mesh and @@ -288,42 +318,49 @@ public: * with at least one corner outside the polygon get deleted. This algorithm is optimized by * using a grid. */ - void CheckFacets(const MeshFacetGrid& rclGrid, - const Base::ViewProjMethod* pclProj, - const Base::Polygon2d& rclPoly, - bool bInner, - std::vector& facets) const; + void CheckFacets( + const MeshFacetGrid& rclGrid, + const Base::ViewProjMethod* pclProj, + const Base::Polygon2d& rclPoly, + bool bInner, + std::vector& facets + ) const; /** * Does the same as the above method unless that it doesn't use a grid. */ - void CheckFacets(const Base::ViewProjMethod* pclProj, - const Base::Polygon2d& rclPoly, - bool bInner, - std::vector& facets) const; + void CheckFacets( + const Base::ViewProjMethod* pclProj, + const Base::Polygon2d& rclPoly, + bool bInner, + std::vector& facets + ) const; /** * Determines all facets of the given array \a raclFacetIndices that lie at the edge or that * have at least neighbour facet that is not inside the array. The resulting array \a * raclResultIndices is not be deleted before the algorithm starts. \a usLevel indicates how * often the algorithm is repeated. */ - void CheckBorderFacets(const std::vector& raclFacetIndices, - std::vector& raclResultIndices, - unsigned short usLevel = 1) const; + void CheckBorderFacets( + const std::vector& raclFacetIndices, + std::vector& raclResultIndices, + unsigned short usLevel = 1 + ) const; /** * Invokes CheckBorderFacets() to get all border facets of \a raclFacetIndices. Then the content * of \a raclFacetIndices is replaced by all facets that can be deleted. \note The mesh * structure is not modified by this method. This is in the responsibility of the user. */ - void CutBorderFacets(std::vector& raclFacetIndices, - unsigned short usLevel = 1) const; + void CutBorderFacets(std::vector& raclFacetIndices, unsigned short usLevel = 1) const; /** Returns the number of border edges */ unsigned long CountBorderEdges() const; /** * Determines all border points as indices of the facets in \a raclFacetIndices. The points are * unsorted. */ - void GetBorderPoints(const std::vector& raclFacetIndices, - std::set& raclResultPointsIndices) const; + void GetBorderPoints( + const std::vector& raclFacetIndices, + std::set& raclResultPointsIndices + ) const; /** Computes the surface of the mesh. */ float Surface() const; /** Subsamples the mesh with point distance \a fDist and stores the points in \a rclPoints. */ @@ -339,83 +376,109 @@ public: * Searches for all facets that intersect the "search tube" with radius \a r around the * polyline. */ - void SearchFacetsFromPolyline(const std::vector& rclPolyline, - float fRadius, - const MeshFacetGrid& rclGrid, - std::vector& rclResultFacetsIndices) const; + void SearchFacetsFromPolyline( + const std::vector& rclPolyline, + float fRadius, + const MeshFacetGrid& rclGrid, + std::vector& rclResultFacetsIndices + ) const; /** Projects a point directly to the mesh (means nearest facet), the result is the facet index * and the foraminate point, use second version with grid for more performance. */ - bool NearestPointFromPoint(const Base::Vector3f& rclPt, - FacetIndex& rclResFacetIndex, - Base::Vector3f& rclResPoint) const; - bool NearestPointFromPoint(const Base::Vector3f& rclPt, - const MeshFacetGrid& rclGrid, - FacetIndex& rclResFacetIndex, - Base::Vector3f& rclResPoint) const; - bool NearestPointFromPoint(const Base::Vector3f& rclPt, - const MeshFacetGrid& rclGrid, - float fMaxSearchArea, - FacetIndex& rclResFacetIndex, - Base::Vector3f& rclResPoint) const; + bool NearestPointFromPoint( + const Base::Vector3f& rclPt, + FacetIndex& rclResFacetIndex, + Base::Vector3f& rclResPoint + ) const; + bool NearestPointFromPoint( + const Base::Vector3f& rclPt, + const MeshFacetGrid& rclGrid, + FacetIndex& rclResFacetIndex, + Base::Vector3f& rclResPoint + ) const; + bool NearestPointFromPoint( + const Base::Vector3f& rclPt, + const MeshFacetGrid& rclGrid, + float fMaxSearchArea, + FacetIndex& rclResFacetIndex, + Base::Vector3f& rclResPoint + ) const; /** Cuts the mesh with a plane. The result is a list of polylines. */ - bool CutWithPlane(const Base::Vector3f& clBase, - const Base::Vector3f& clNormal, - const MeshFacetGrid& rclGrid, - std::list>& rclResult, - float fMinEps = 1.0e-2F, - bool bConnectPolygons = false) const; + bool CutWithPlane( + const Base::Vector3f& clBase, + const Base::Vector3f& clNormal, + const MeshFacetGrid& rclGrid, + std::list>& rclResult, + float fMinEps = 1.0e-2F, + bool bConnectPolygons = false + ) const; /** * Gets all facets that cut the plane (N,d) and that lie between the two points left and right. * The plane is defined by it normalized normal and the signed distance to the origin. */ - void GetFacetsFromPlane(const MeshFacetGrid& rclGrid, - const Base::Vector3f& clNormal, - float dist, - const Base::Vector3f& rclLeft, - const Base::Vector3f& rclRight, - std::vector& rclRes) const; + void GetFacetsFromPlane( + const MeshFacetGrid& rclGrid, + const Base::Vector3f& clNormal, + float dist, + const Base::Vector3f& rclLeft, + const Base::Vector3f& rclRight, + std::vector& rclRes + ) const; /** Returns true if the distance from the \a rclPt to the facet \a ulFacetIdx is less than \a * fMaxDistance. If this restriction is met \a rfDistance is set to the actual distance, * otherwise false is returned. */ - bool Distance(const Base::Vector3f& rclPt, - FacetIndex ulFacetIdx, - float fMaxDistance, - float& rfDistance) const; + bool Distance( + const Base::Vector3f& rclPt, + FacetIndex ulFacetIdx, + float fMaxDistance, + float& rfDistance + ) const; /** * Calculates the minimum grid length so that not more elements than \a maxElements will be * created when the grid gets built up. The minimum grid length must be at least \a fLength. */ - float CalculateMinimumGridLength(float fLength, - const Base::BoundBox3f& rBBox, - unsigned long maxElements) const; + float CalculateMinimumGridLength( + float fLength, + const Base::BoundBox3f& rBBox, + unsigned long maxElements + ) const; protected: /** Helper method to connect the intersection points to polylines. */ - bool ConnectLines(std::list>& rclLines, - std::list>& rclPolylines, - float fMinEps) const; - bool ConnectPolygons(std::list>& clPolyList, - std::list>& rclLines) const; + bool ConnectLines( + std::list>& rclLines, + std::list>& rclPolylines, + float fMinEps + ) const; + bool ConnectPolygons( + std::list>& clPolyList, + std::list>& rclLines + ) const; /** Searches the nearest facet in \a raulFacets to the ray (\a rclPt, \a rclDir). */ - bool RayNearestField(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - const std::vector& raulFacets, - Base::Vector3f& rclRes, - FacetIndex& rulFacet, - float fMaxAngle = Mathf::PI) const; + bool RayNearestField( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + const std::vector& raulFacets, + Base::Vector3f& rclRes, + FacetIndex& rulFacet, + float fMaxAngle = Mathf::PI + ) const; /** * Splits the boundary \a rBound in several loops and append this loops to the list of borders. */ - void SplitBoundaryLoops(const std::vector& rBound, - std::list>& aBorders); + void SplitBoundaryLoops( + const std::vector& rBound, + std::list>& aBorders + ); /** * From the given \a openEdges a boundary is split and added to \a boundary. */ - void SplitBoundaryFromOpenEdges(std::list>& openEdges, - std::list& boundary) const; + void SplitBoundaryFromOpenEdges( + std::list>& openEdges, + std::list& boundary + ) const; private: const MeshKernel& _rclMesh; /**< The mesh kernel. */ @@ -498,12 +561,14 @@ public: void RemoveFacet(FacetIndex); protected: - void SearchNeighbours(const MeshFacetArray& rFacets, - FacetIndex index, - const Base::Vector3f& rclCenter, - float fMaxDist, - std::set& visit, - MeshCollector& collect) const; + void SearchNeighbours( + const MeshFacetArray& rFacets, + FacetIndex index, + const Base::Vector3f& rclCenter, + float fMaxDist, + std::set& visit, + MeshCollector& collect + ) const; private: const MeshKernel& _rclMesh; /**< The mesh kernel. */ diff --git a/src/Mod/Mesh/App/Core/Approximation.cpp b/src/Mod/Mesh/App/Core/Approximation.cpp index a447c10704..3c345328cc 100644 --- a/src/Mod/Mesh/App/Core/Approximation.cpp +++ b/src/Mod/Mesh/App/Core/Approximation.cpp @@ -39,7 +39,7 @@ #include #include #ifdef FC_USE_EIGEN -#include +# include #endif #include "Approximation.h" @@ -391,8 +391,7 @@ float PlaneFit::GetSignedStdDeviation() const fMean = 1.0F / ulPtCt * fSumXi; - return fFactor - * sqrtf((ulPtCt / (ulPtCt - 3.0F)) * ((1.0F / ulPtCt) * fSumXi2 - fMean * fMean)); + return fFactor * sqrtf((ulPtCt / (ulPtCt - 3.0F)) * ((1.0F / ulPtCt) * fSumXi2 - fMean * fMean)); } void PlaneFit::ProjectToPlane() @@ -437,9 +436,11 @@ std::vector PlaneFit::GetLocalPoints() const for (auto& localPoint : localPoints) { Base::Vector3d clPoint = Base::convertTo(localPoint); clPoint.TransformToCoordinateSystem(bs, ex, ey); - localPoint.Set(static_cast(clPoint.x), - static_cast(clPoint.y), - static_cast(clPoint.z)); + localPoint.Set( + static_cast(clPoint.x), + static_cast(clPoint.y), + static_cast(clPoint.z) + ); } } @@ -458,14 +459,16 @@ Base::BoundBox3f PlaneFit::GetBoundings() const // ------------------------------------------------------------------------------- -bool QuadraticFit::GetCurvatureInfo(double x, - double y, - double z, - double& rfCurv0, - double& rfCurv1, - Base::Vector3f& rkDir0, - Base::Vector3f& rkDir1, - double& dDistance) +bool QuadraticFit::GetCurvatureInfo( + double x, + double y, + double z, + double& rfCurv0, + double& rfCurv1, + Base::Vector3f& rkDir0, + Base::Vector3f& rkDir1, + double& dDistance +) { assert(_bIsFitted); bool bResult = false; @@ -527,12 +530,14 @@ float QuadraticFit::Fit() return fResult; } -void QuadraticFit::CalcEigenValues(double& dLambda1, - double& dLambda2, - double& dLambda3, - Base::Vector3f& clEV1, - Base::Vector3f& clEV2, - Base::Vector3f& clEV3) const +void QuadraticFit::CalcEigenValues( + double& dLambda1, + double& dLambda2, + double& dLambda3, + Base::Vector3f& clEV1, + Base::Vector3f& clEV2, + Base::Vector3f& clEV3 +) const { assert(_bIsFitted); @@ -558,15 +563,17 @@ void QuadraticFit::CalcEigenValues(double& dLambda1, * */ - Wm4::Matrix3 akMat(_fCoeff[4], - _fCoeff[7] / 2.0, - _fCoeff[8] / 2.0, - _fCoeff[7] / 2.0, - _fCoeff[5], - _fCoeff[9] / 2.0, - _fCoeff[8] / 2.0, - _fCoeff[9] / 2.0, - _fCoeff[6]); + Wm4::Matrix3 akMat( + _fCoeff[4], + _fCoeff[7] / 2.0, + _fCoeff[8] / 2.0, + _fCoeff[7] / 2.0, + _fCoeff[5], + _fCoeff[9] / 2.0, + _fCoeff[8] / 2.0, + _fCoeff[9] / 2.0, + _fCoeff[6] + ); Wm4::Matrix3 rkRot, rkDiag; akMat.EigenDecomposition(rkRot, rkDiag); @@ -633,14 +640,16 @@ float SurfaceFit::Fit() return fResult; } -bool SurfaceFit::GetCurvatureInfo(double x, - double y, - double z, - double& rfCurv0, - double& rfCurv1, - Base::Vector3f& rkDir0, - Base::Vector3f& rkDir1, - double& dDistance) +bool SurfaceFit::GetCurvatureInfo( + double x, + double y, + double z, + double& rfCurv0, + double& rfCurv1, + Base::Vector3f& rkDir0, + Base::Vector3f& rkDir1, + double& dDistance +) { bool bResult = false; @@ -846,8 +855,7 @@ double SurfaceFit::Value(double x, double y) const return z; } -void SurfaceFit::GetCoefficients(double& a, double& b, double& c, double& d, double& e, double& f) - const +void SurfaceFit::GetCoefficients(double& a, double& b, double& c, double& d, double& e, double& f) const { a = _fCoeff[4]; b = _fCoeff[5]; @@ -923,8 +931,7 @@ void SurfaceFit::Transform(std::vector& pts) const * f(x,y) = a*x*x + b*y*y + c*x*y + d*y + e*f + f * by getting the 3x3 control points. */ -std::vector -SurfaceFit::toBezier(double umin, double umax, double vmin, double vmax) const +std::vector SurfaceFit::toBezier(double umin, double umax, double vmin, double vmax) const { std::vector pts; pts.reserve(9); @@ -1175,9 +1182,11 @@ float CylinderFit::Fit() MeshCoreFit::CylinderFit cylFit; cylFit.AddPoints(_vPoints); if (_initialGuess) { - cylFit.SetApproximations(_fRadius, - Base::Vector3d(_vBase.x, _vBase.y, _vBase.z), - Base::Vector3d(_vAxis.x, _vAxis.y, _vAxis.z)); + cylFit.SetApproximations( + _fRadius, + Base::Vector3d(_vBase.x, _vBase.y, _vBase.z), + Base::Vector3d(_vAxis.x, _vAxis.y, _vAxis.z) + ); } float result = cylFit.Fit(); @@ -1185,7 +1194,7 @@ float CylinderFit::Fit() Base::Vector3d base = cylFit.GetBase(); Base::Vector3d dir = cylFit.GetAxis(); -#if defined(FC_DEBUG) +# if defined(FC_DEBUG) Base::Console().log( "MeshCoreFit::Cylinder Fit: Base: (%0.4f, %0.4f, %0.4f), Axis: (%0.6f, %0.6f, " "%0.6f), Radius: %0.4f, Std Dev: %0.4f, Iterations: %d\n", @@ -1197,8 +1206,9 @@ float CylinderFit::Fit() dir.z, cylFit.GetRadius(), cylFit.GetStdDeviation(), - cylFit.GetNumIterations()); -#endif + cylFit.GetNumIterations() + ); +# endif _vBase = Base::convertTo(base); _vAxis = Base::convertTo(dir); _fRadius = (float)cylFit.GetRadius(); @@ -1238,10 +1248,8 @@ float CylinderFit::Fit() Eigen::LevenbergMarquardt lm(functor); int status = lm.minimize(x); - Base::Console().log("Cylinder fit: %d, iterations: %d, gradient norm: %f\n", - status, - lm.iter, - lm.gnorm); + Base::Console() + .log("Cylinder fit: %d, iterations: %d, gradient norm: %f\n", status, lm.iter, lm.gnorm); _vAxis.x = x(0); _vAxis.y = x(1); @@ -1405,12 +1413,12 @@ float SphereFit::Fit() } std::vector input; - std::transform(_vPoints.begin(), - _vPoints.end(), - std::back_inserter(input), - [](const Base::Vector3f& v) { - return Wm4::Vector3d(v.x, v.y, v.z); - }); + std::transform( + _vPoints.begin(), + _vPoints.end(), + std::back_inserter(input), + [](const Base::Vector3f& v) { return Wm4::Vector3d(v.x, v.y, v.z); } + ); Wm4::Sphere3d sphere; Wm4::SphereFit3(input.size(), input.data(), 10, sphere, false); @@ -1421,13 +1429,15 @@ float SphereFit::Fit() _fLastResult = 0; #if defined(_DEBUG) - Base::Console().message(" WildMagic Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " - "%0.4f, Std Dev: %0.4f\n", - _vCenter.x, - _vCenter.y, - _vCenter.z, - _fRadius, - GetStdDeviation()); + Base::Console().message( + " WildMagic Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " + "%0.4f, Std Dev: %0.4f\n", + _vCenter.x, + _vCenter.y, + _vCenter.z, + _fRadius, + GetStdDeviation() + ); #endif MeshCoreFit::SphereFit sphereFit; @@ -1437,14 +1447,16 @@ float SphereFit::Fit() if (result < std::numeric_limits::max()) { Base::Vector3d center = sphereFit.GetCenter(); #if defined(_DEBUG) - Base::Console().message("MeshCoreFit::Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " - "%0.4f, Std Dev: %0.4f, Iterations: %d\n", - center.x, - center.y, - center.z, - sphereFit.GetRadius(), - sphereFit.GetStdDeviation(), - sphereFit.GetNumIterations()); + Base::Console().message( + "MeshCoreFit::Sphere Fit: Center: (%0.4f, %0.4f, %0.4f), Radius: " + "%0.4f, Std Dev: %0.4f, Iterations: %d\n", + center.x, + center.y, + center.z, + sphereFit.GetRadius(), + sphereFit.GetStdDeviation(), + sphereFit.GetNumIterations() + ); #endif _vCenter = Base::convertTo(center); _fRadius = (float)sphereFit.GetRadius(); diff --git a/src/Mod/Mesh/App/Core/Approximation.h b/src/Mod/Mesh/App/Core/Approximation.h index c65edb744f..14c85ad423 100644 --- a/src/Mod/Mesh/App/Core/Approximation.h +++ b/src/Mod/Mesh/App/Core/Approximation.h @@ -27,7 +27,7 @@ #include #ifndef MESH_GLOBAL_H -#include +# include #endif #include #include @@ -64,9 +64,11 @@ public: // the function Real F(const Vector3& rkP) const override { - return (m_afCoeff[0] * rkP.X() * rkP.X() + m_afCoeff[1] * rkP.Y() * rkP.Y() - + m_afCoeff[2] * rkP.X() + m_afCoeff[3] * rkP.Y() + m_afCoeff[4] * rkP.X() * rkP.Y() - + m_afCoeff[5] - rkP.Z()); + return ( + m_afCoeff[0] * rkP.X() * rkP.X() + m_afCoeff[1] * rkP.Y() * rkP.Y() + + m_afCoeff[2] * rkP.X() + m_afCoeff[3] * rkP.Y() + m_afCoeff[4] * rkP.X() * rkP.Y() + + m_afCoeff[5] - rkP.Z() + ); } // first-order partial derivatives @@ -204,8 +206,7 @@ protected: // NOLINTBEGIN std::list _vPoints; /**< Holds the points for the fit algorithm. */ bool _bIsFitted {false}; /**< Flag, whether the fit has been called. */ - float _fLastResult { - std::numeric_limits::max()}; /**< Stores the last result of the fit */ + float _fLastResult {std::numeric_limits::max()}; /**< Stores the last result of the fit */ // NOLINTEND }; @@ -322,14 +323,16 @@ public: * @param dDistance * @return bool Success = true, otherwise false */ - bool GetCurvatureInfo(double x, - double y, - double z, - double& rfCurv0, - double& rfCurv1, - Base::Vector3f& rkDir0, - Base::Vector3f& rkDir1, - double& dDistance); + bool GetCurvatureInfo( + double x, + double y, + double z, + double& rfCurv0, + double& rfCurv1, + Base::Vector3f& rkDir0, + Base::Vector3f& rkDir1, + double& dDistance + ); bool GetCurvatureInfo(double x, double y, double z, double& rfCurv0, double& rfcurv1); /** @@ -341,12 +344,14 @@ public: * @param clEV2 Eigenvector 2 * @param clEV3 Eigenvector 3 */ - void CalcEigenValues(double& dLambda1, - double& dLambda2, - double& dLambda3, - Base::Vector3f& clEV1, - Base::Vector3f& clEV2, - Base::Vector3f& clEV3) const; + void CalcEigenValues( + double& dLambda1, + double& dLambda2, + double& dLambda3, + Base::Vector3f& clEV1, + Base::Vector3f& clEV2, + Base::Vector3f& clEV3 + ) const; private: double _fCoeff[10] {}; /**< Coefficients of the fit */ @@ -367,14 +372,16 @@ class MeshExport SurfaceFit: public PlaneFit public: SurfaceFit(); - bool GetCurvatureInfo(double x, - double y, - double z, - double& rfCurv0, - double& rfCurv1, - Base::Vector3f& rkDir0, - Base::Vector3f& rkDir1, - double& dDistance); + bool GetCurvatureInfo( + double x, + double y, + double z, + double& rfCurv0, + double& rfCurv1, + Base::Vector3f& rkDir0, + Base::Vector3f& rkDir1, + double& dDistance + ); bool GetCurvatureInfo(double x, double y, double z, double& rfCurv0, double& rfcurv1); float Fit() override; double Value(double x, double y) const; @@ -393,8 +400,12 @@ public: * @param vmax Parameter range * @return control points of the Bezier surface */ - std::vector - toBezier(double umin = 0.0, double umax = 1.0, double vmin = 0.0, double vmax = 1.0) const; + std::vector toBezier( + double umin = 0.0, + double umax = 1.0, + double vmin = 0.0, + double vmax = 1.0 + ) const; private: double PolynomFit(); @@ -561,29 +572,35 @@ public: * @param dDistance Gives distances from the point to the quadric. * @return bool Success = true, otherwise false */ - bool CurvatureInfo(double x, - double y, - double z, - double& rfCurv0, - double& rfCurv1, - Wm4::Vector3& rkDir0, - Wm4::Vector3& rkDir1, - double& dDistance) + bool CurvatureInfo( + double x, + double y, + double z, + double& rfCurv0, + double& rfCurv1, + Wm4::Vector3& rkDir0, + Wm4::Vector3& rkDir1, + double& dDistance + ) { (void)dDistance; - return pImplSurf->ComputePrincipalCurvatureInfo(Wm4::Vector3(x, y, z), - rfCurv0, - rfCurv1, - rkDir0, - rkDir1); + return pImplSurf->ComputePrincipalCurvatureInfo( + Wm4::Vector3(x, y, z), + rfCurv0, + rfCurv1, + rkDir0, + rkDir1 + ); } Base::Vector3f GetGradient(double x, double y, double z) const { Wm4::Vector3 grad = pImplSurf->GetGradient(Wm4::Vector3(x, y, z)); - return Base::Vector3f(static_cast(grad.X()), - static_cast(grad.Y()), - static_cast(grad.Z())); + return Base::Vector3f( + static_cast(grad.X()), + static_cast(grad.Y()), + static_cast(grad.Z()) + ); } Base::Matrix4D GetHessian(double x, double y, double z) const @@ -630,9 +647,11 @@ public: //+++++++++ Quadric +++++++++++++++++++++++++++++++++++++++ double F(double x, double y, double z) { - return (dKoeff[0] + dKoeff[1] * x + dKoeff[2] * y + dKoeff[3] * z + dKoeff[4] * x * x - + dKoeff[5] * y * y + dKoeff[6] * z * z + dKoeff[7] * x * y + dKoeff[8] * x * z - + dKoeff[9] * y * z); + return ( + dKoeff[0] + dKoeff[1] * x + dKoeff[2] * y + dKoeff[3] * z + dKoeff[4] * x * x + + dKoeff[5] * y * y + dKoeff[6] * z * z + dKoeff[7] * x * y + dKoeff[8] * x * z + + dKoeff[9] * y * z + ); } //+++++++++ 1. derivations ++++++++++++++++++++++++++++++++ diff --git a/src/Mod/Mesh/App/Core/Builder.cpp b/src/Mod/Mesh/App/Core/Builder.cpp index 092878ff86..1235e9d974 100644 --- a/src/Mod/Mesh/App/Core/Builder.cpp +++ b/src/Mod/Mesh/App/Core/Builder.cpp @@ -107,20 +107,17 @@ void MeshBuilder::AddFacet(const MeshGeomFacet& facet, bool takeFlag, bool takeP prop = facet._ulProp; } - AddFacet(facet._aclPoints[0], - facet._aclPoints[1], - facet._aclPoints[2], - facet.GetNormal(), - flag, - prop); + AddFacet(facet._aclPoints[0], facet._aclPoints[1], facet._aclPoints[2], facet.GetNormal(), flag, prop); } -void MeshBuilder::AddFacet(const Base::Vector3f& pt1, - const Base::Vector3f& pt2, - const Base::Vector3f& pt3, - const Base::Vector3f& normal, - unsigned char flag, - unsigned long prop) +void MeshBuilder::AddFacet( + const Base::Vector3f& pt1, + const Base::Vector3f& pt2, + const Base::Vector3f& pt3, + const Base::Vector3f& normal, + unsigned char flag, + unsigned long prop +) { Base::Vector3f facetPoints[4] = {pt1, pt2, pt3, normal}; AddFacet(facetPoints, flag, prop); @@ -217,11 +214,11 @@ void MeshBuilder::RemoveUnreferencedPoints() } } - unsigned long uValidPts = std::count_if(_meshKernel._aclPointArray.begin(), - _meshKernel._aclPointArray.end(), - [](const MeshPoint& p) { - return p.IsValid(); - }); + unsigned long uValidPts = std::count_if( + _meshKernel._aclPointArray.begin(), + _meshKernel._aclPointArray.end(), + [](const MeshPoint& p) { return p.IsValid(); } + ); if (uValidPts < _meshKernel.CountPoints()) { _meshKernel.RemoveInvalids(); } diff --git a/src/Mod/Mesh/App/Core/Builder.h b/src/Mod/Mesh/App/Core/Builder.h index 11d7371c9a..fa5eed8d32 100644 --- a/src/Mod/Mesh/App/Core/Builder.h +++ b/src/Mod/Mesh/App/Core/Builder.h @@ -148,12 +148,14 @@ public: void AddFacet(const MeshGeomFacet& facet, bool takeFlag = false, bool takeProperty = false); /** Add new facet */ - void AddFacet(const Base::Vector3f& pt1, - const Base::Vector3f& pt2, - const Base::Vector3f& pt3, - const Base::Vector3f& normal, - unsigned char flag = 0, - unsigned long prop = 0); + void AddFacet( + const Base::Vector3f& pt1, + const Base::Vector3f& pt2, + const Base::Vector3f& pt3, + const Base::Vector3f& normal, + unsigned char flag = 0, + unsigned long prop = 0 + ); /** Add new facet * @param facetPoints Array of vectors (size 4) in order of vec1, vec2, * vec3, normal diff --git a/src/Mod/Mesh/App/Core/Curvature.cpp b/src/Mod/Mesh/App/Core/Curvature.cpp index 1057d06b83..1b68d13aaf 100644 --- a/src/Mod/Mesh/App/Core/Curvature.cpp +++ b/src/Mod/Mesh/App/Core/Curvature.cpp @@ -35,9 +35,9 @@ // #define OPTIMIZE_CURVATURE #ifdef OPTIMIZE_CURVATURE -#include +# include #else -#include +# include #endif #include "Approximation.h" @@ -82,8 +82,8 @@ void MeshCurvature::ComputePerFace(bool parallel) } else { // NOLINTBEGIN - QFuture future = - QtConcurrent::mapped(mySegment, std::bind(&FacetCurvature::Compute, &face, sp::_1)); + QFuture future + = QtConcurrent::mapped(mySegment, std::bind(&FacetCurvature::Compute, &face, sp::_1)); // NOLINTEND QFutureWatcher watcher; watcher.setFuture(future); @@ -186,8 +186,8 @@ void MeshCurvature::ComputePerVertex() // Compute the matrix of normal derivatives. for (int iRow = 0; iRow < 3; iRow++) { for (int iCol = 0; iCol < 3; iCol++) { - akWWTrn(iRow, iCol) = - 0.5 * akWWTrn(iRow, iCol) + akNormal[i][iRow] * akNormal[i][iCol]; + akWWTrn(iRow, iCol) = 0.5 * akWWTrn(iRow, iCol) + + akNormal[i][iRow] * akNormal[i][iCol]; akDWTrn(iRow, iCol) *= 0.5; } } @@ -318,10 +318,8 @@ void MeshCurvature::ComputePerVertex() } // compute vertex based curvatures - Wm4::MeshCurvature meshCurv(myKernel.CountPoints(), - aPnts.data(), - myKernel.CountFacets(), - aIdx.data()); + Wm4::MeshCurvature + meshCurv(myKernel.CountPoints(), aPnts.data(), myKernel.CountFacets(), aIdx.data()); // get curvature information now const Wm4::Vector3* aMaxCurvDir = meshCurv.GetMaxDirections(); @@ -332,12 +330,16 @@ void MeshCurvature::ComputePerVertex() myCurvature.reserve(myKernel.CountPoints()); for (unsigned long i = 0; i < myKernel.CountPoints(); i++) { CurvatureInfo ci; - ci.cMaxCurvDir = Base::Vector3f((float)aMaxCurvDir[i].X(), - (float)aMaxCurvDir[i].Y(), - (float)aMaxCurvDir[i].Z()); - ci.cMinCurvDir = Base::Vector3f((float)aMinCurvDir[i].X(), - (float)aMinCurvDir[i].Y(), - (float)aMinCurvDir[i].Z()); + ci.cMaxCurvDir = Base::Vector3f( + (float)aMaxCurvDir[i].X(), + (float)aMaxCurvDir[i].Y(), + (float)aMaxCurvDir[i].Z() + ); + ci.cMinCurvDir = Base::Vector3f( + (float)aMinCurvDir[i].X(), + (float)aMinCurvDir[i].Y(), + (float)aMinCurvDir[i].Z() + ); ci.fMaxCurvature = (float)aMaxCurv[i]; ci.fMinCurvature = (float)aMinCurv[i]; myCurvature.push_back(ci); @@ -371,10 +373,12 @@ private: // -------------------------------------------------------- -FacetCurvature::FacetCurvature(const MeshKernel& kernel, - const MeshRefPointToFacets& search, - float r, - unsigned long pt) +FacetCurvature::FacetCurvature( + const MeshKernel& kernel, + const MeshRefPointToFacets& search, + float r, + unsigned long pt +) : myKernel(kernel) , mySearch(search) , myMinPoints(pt) diff --git a/src/Mod/Mesh/App/Core/Curvature.h b/src/Mod/Mesh/App/Core/Curvature.h index 226410127d..2a386e761d 100644 --- a/src/Mod/Mesh/App/Core/Curvature.h +++ b/src/Mod/Mesh/App/Core/Curvature.h @@ -45,10 +45,7 @@ struct MeshExport CurvatureInfo class MeshExport FacetCurvature { public: - FacetCurvature(const MeshKernel& kernel, - const MeshRefPointToFacets& search, - float, - unsigned long); + FacetCurvature(const MeshKernel& kernel, const MeshRefPointToFacets& search, float, unsigned long); CurvatureInfo Compute(FacetIndex index) const; private: diff --git a/src/Mod/Mesh/App/Core/CylinderFit.cpp b/src/Mod/Mesh/App/Core/CylinderFit.cpp index cb95f6f514..e571772e68 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.cpp +++ b/src/Mod/Mesh/App/Core/CylinderFit.cpp @@ -76,9 +76,7 @@ CylinderFit::CylinderFit() {} // Set approximations before calling the fitting -void CylinderFit::SetApproximations(double radius, - const Base::Vector3d& base, - const Base::Vector3d& axis) +void CylinderFit::SetApproximations(double radius, const Base::Vector3d& base, const Base::Vector3d& axis) { _bIsFitted = false; _fLastResult = std::numeric_limits::max(); @@ -110,10 +108,12 @@ void CylinderFit::SetApproximations(const Base::Vector3d& base, const Base::Vect // Set iteration convergence criteria for the fit if special values are needed. // The default values set in the constructor are suitable for most uses -void CylinderFit::SetConvergenceCriteria(double posConvLimit, - double dirConvLimit, - double vConvLimit, - int maxIter) +void CylinderFit::SetConvergenceCriteria( + double posConvLimit, + double dirConvLimit, + double vConvLimit, + int maxIter +) { if (posConvLimit > 0.0) { _posConvLimit = posConvLimit; @@ -246,12 +246,12 @@ void CylinderFit::ComputeApproximationsLine() _dRadius = 0.0; if (!_vPoints.empty()) { std::vector input; - std::transform(_vPoints.begin(), - _vPoints.end(), - std::back_inserter(input), - [](const Base::Vector3f& v) { - return Wm4::Vector3d(v.x, v.y, v.z); - }); + std::transform( + _vPoints.begin(), + _vPoints.end(), + std::back_inserter(input), + [](const Base::Vector3f& v) { return Wm4::Vector3d(v.x, v.y, v.z); } + ); Wm4::Line3 kLine = Wm4::OrthogonalLineFit3(input.size(), input.data()); _vBase.Set(kLine.Origin.X(), kLine.Origin.Y(), kLine.Origin.Z()); _vAxis.Set(kLine.Direction.X(), kLine.Direction.Y(), kLine.Direction.Z()); @@ -446,10 +446,12 @@ double CylinderFit::meanZObs() // Set up the normal equation matrices // atpa ... 5x5 normal matrix // atpl ... 5x1 matrix (right-hand side of equation) -void CylinderFit::setupNormalEquationMatrices(SolutionD solDir, - const std::vector& residuals, - Matrix5x5& atpa, - Eigen::VectorXd& atpl) const +void CylinderFit::setupNormalEquationMatrices( + SolutionD solDir, + const std::vector& residuals, + Matrix5x5& atpa, + Eigen::VectorXd& atpl +) const { // Zero matrices atpa.setZero(); @@ -587,11 +589,13 @@ void CylinderFit::setupObservation(SolutionD solDir, // pi ... weight of observation (= quasi weight qw for this solution) // atpa ... 5x5 normal equation matrix // atpl ... 5x1 matrix/vector (right-hand side of equations) -void CylinderFit::addObservationU(DoubleArray5 a, - double li, - double pi, - Matrix5x5& atpa, - Eigen::VectorXd& atpl) const +void CylinderFit::addObservationU( + DoubleArray5 a, + double li, + double pi, + Matrix5x5& atpa, + Eigen::VectorXd& atpl +) const { const int dim = 5; for (int i = 0; i < dim; ++i) { @@ -618,12 +622,14 @@ void CylinderFit::setLowerPart(Matrix5x5& atpa) const } // Compute the residuals and sigma0 and check the residual convergence -bool CylinderFit::computeResiduals(SolutionD solDir, - const Eigen::VectorXd& x, - std::vector& residuals, - double& sigma0, - double vConvLimit, - bool& vConverged) const +bool CylinderFit::computeResiduals( + SolutionD solDir, + const Eigen::VectorXd& x, + std::vector& residuals, + double& sigma0, + double vConvLimit, + bool& vConverged +) const { const int dim = 5; // A minimum of 5 surface points is needed to define a cylinder diff --git a/src/Mod/Mesh/App/Core/CylinderFit.h b/src/Mod/Mesh/App/Core/CylinderFit.h index f213f6734b..ade27e4d19 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.h +++ b/src/Mod/Mesh/App/Core/CylinderFit.h @@ -71,10 +71,7 @@ public: * Set iteration convergence criteria for the fit if special values are needed. * The default values set in the constructor are suitable for most uses */ - void SetConvergenceCriteria(double posConvLimit, - double dirConvLimit, - double vConvLimit, - int maxIter); + void SetConvergenceCriteria(double posConvLimit, double dirConvLimit, double vConvLimit, int maxIter); /** * Returns the radius of the fitted cylinder. If Fit() has not been called then zero is * returned. @@ -138,28 +135,28 @@ protected: /** * Set up the normal equations */ - void setupNormalEquationMatrices(SolutionD solDir, - const std::vector& residuals, - Matrix5x5& atpa, - Eigen::VectorXd& atpl) const; + void setupNormalEquationMatrices( + SolutionD solDir, + const std::vector& residuals, + Matrix5x5& atpa, + Eigen::VectorXd& atpl + ) const; /** * Sets up contributions of given observation to the normal equation matrices. */ - void setupObservation(SolutionD solDir, - const Base::Vector3f& point, - const Base::Vector3d& residual, - DoubleArray5& a, - double& f0, - double& qw, - DoubleArray3& b) const; + void setupObservation( + SolutionD solDir, + const Base::Vector3f& point, + const Base::Vector3d& residual, + DoubleArray5& a, + double& f0, + double& qw, + DoubleArray3& b + ) const; /** * Computes contribution of the given observation equation on the normal equation matrices */ - void addObservationU(DoubleArray5 a, - double li, - double pi, - Matrix5x5& atpa, - Eigen::VectorXd& atpl) const; + void addObservationU(DoubleArray5 a, double li, double pi, Matrix5x5& atpa, Eigen::VectorXd& atpl) const; /** * Set the lower part of the normal matrix equal to the upper part */ @@ -168,12 +165,14 @@ protected: /** * Compute the residuals and sigma0 and check the residual convergence */ - bool computeResiduals(SolutionD solDir, - const Eigen::VectorXd& x, - std::vector& residuals, - double& sigma0, - double vConvLimit, - bool& vConverged) const; + bool computeResiduals( + SolutionD solDir, + const Eigen::VectorXd& x, + std::vector& residuals, + double& sigma0, + double vConvLimit, + bool& vConverged + ) const; /** * Update the parameters after solving the normal equations */ diff --git a/src/Mod/Mesh/App/Core/Definitions.h b/src/Mod/Mesh/App/Core/Definitions.h index 2a033d5c93..7d225cf48e 100644 --- a/src/Mod/Mesh/App/Core/Definitions.h +++ b/src/Mod/Mesh/App/Core/Definitions.h @@ -26,7 +26,7 @@ #define MESH_DEFINITIONS_H #ifndef MESH_GLOBAL_H -#include +# include #endif #include diff --git a/src/Mod/Mesh/App/Core/Degeneration.cpp b/src/Mod/Mesh/App/Core/Degeneration.cpp index a967a33b0f..8d526c3bc5 100644 --- a/src/Mod/Mesh/App/Core/Degeneration.cpp +++ b/src/Mod/Mesh/App/Core/Degeneration.cpp @@ -138,8 +138,7 @@ bool MeshEvalDuplicatePoints::Evaluate() // if there are two adjacent vertices which have the same coordinates std::sort(vertices.begin(), vertices.end(), Vertex_Less()); - return (std::adjacent_find(vertices.begin(), vertices.end(), Vertex_EqualTo()) - == vertices.end()); + return (std::adjacent_find(vertices.begin(), vertices.end(), Vertex_EqualTo()) == vertices.end()); } std::vector MeshEvalDuplicatePoints::GetIndices() const @@ -890,8 +889,7 @@ bool MeshEvalDentsOnSurface::Evaluate() // remove duplicates std::sort(this->indices.begin(), this->indices.end()); - this->indices.erase(std::unique(this->indices.begin(), this->indices.end()), - this->indices.end()); + this->indices.erase(std::unique(this->indices.begin(), this->indices.end()), this->indices.end()); return this->indices.empty(); } @@ -953,8 +951,7 @@ bool MeshEvalFoldsOnSurface::Evaluate() // remove duplicates std::sort(this->indices.begin(), this->indices.end()); - this->indices.erase(std::unique(this->indices.begin(), this->indices.end()), - this->indices.end()); + this->indices.erase(std::unique(this->indices.begin(), this->indices.end()), this->indices.end()); return this->indices.empty(); } @@ -1114,11 +1111,11 @@ bool MeshEvalRangePoint::Evaluate() PointIndex ulCtPoints = _rclMesh.CountPoints(); for (const auto& it : rFaces) { - if (std::find_if(it._aulPoints, - it._aulPoints + 3, - [ulCtPoints](PointIndex i) { - return i >= ulCtPoints; - }) + if (std::find_if( + it._aulPoints, + it._aulPoints + 3, + [ulCtPoints](PointIndex i) { return i >= ulCtPoints; } + ) < it._aulPoints + 3) { return false; } @@ -1135,11 +1132,11 @@ std::vector MeshEvalRangePoint::GetIndices() const PointIndex ind = 0; for (auto it = rFaces.begin(); it != rFaces.end(); ++it, ind++) { - if (std::find_if(it->_aulPoints, - it->_aulPoints + 3, - [ulCtPoints](PointIndex i) { - return i >= ulCtPoints; - }) + if (std::find_if( + it->_aulPoints, + it->_aulPoints + 3, + [ulCtPoints](PointIndex i) { return i >= ulCtPoints; } + ) < it->_aulPoints + 3) { aInds.push_back(ind); } diff --git a/src/Mod/Mesh/App/Core/Degeneration.h b/src/Mod/Mesh/App/Core/Degeneration.h index 9860fffdca..92339fcbaa 100644 --- a/src/Mod/Mesh/App/Core/Degeneration.h +++ b/src/Mod/Mesh/App/Core/Degeneration.h @@ -360,9 +360,11 @@ public: /** * Construction. The \arg fFactor must be in the range of 0.0 and 0.5. */ - explicit MeshFixCaps(MeshKernel& rclM, - float fMaxAng = 2.61F, - float fFactor = 0.25F) // ~150 degree + explicit MeshFixCaps( + MeshKernel& rclM, + float fMaxAng = 2.61F, + float fFactor = 0.25F + ) // ~150 degree : MeshValidation(rclM) , fMaxAngle(fMaxAng) , fSplitFactor(fFactor) @@ -424,11 +426,7 @@ public: /** * Construction. */ - MeshFixDeformedFacets(MeshKernel& rclM, - float fMinAngle, - float fMaxAngle, - float fSwapAngle, - float fEps) + MeshFixDeformedFacets(MeshKernel& rclM, float fMinAngle, float fMaxAngle, float fSwapAngle, float fEps) : MeshValidation(rclM) , fMinAngle(fMinAngle) , fMaxAngle(fMaxAngle) diff --git a/src/Mod/Mesh/App/Core/Elements.cpp b/src/Mod/Mesh/App/Core/Elements.cpp index c25769128a..627843d0b2 100644 --- a/src/Mod/Mesh/App/Core/Elements.cpp +++ b/src/Mod/Mesh/App/Core/Elements.cpp @@ -240,9 +240,11 @@ bool MeshGeomEdge::IntersectBoundingBox(const Base::BoundBox3f& rclBB) const return intrsectbox.Test(); } -bool MeshGeomEdge::IntersectWithLine(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const +bool MeshGeomEdge::IntersectWithLine( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes +) const { const float eps = 1e-06F; Base::Vector3f n = _aclPoints[1] - _aclPoints[0]; @@ -357,9 +359,11 @@ bool MeshGeomEdge::IntersectWithEdge(const MeshGeomEdge& edge, Base::Vector3f& r } } -bool MeshGeomEdge::IntersectWithPlane(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const +bool MeshGeomEdge::IntersectWithPlane( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes +) const { float dist1 = _aclPoints[0].DistanceToPlane(rclPt, rclDir); float dist2 = _aclPoints[1].DistanceToPlane(rclPt, rclDir); @@ -386,10 +390,12 @@ void MeshGeomEdge::ProjectPointToLine(const Base::Vector3f& rclPoint, Base::Vect rclProj = rclPoint + vec; } -void MeshGeomEdge::ClosestPointsToLine(const Base::Vector3f& linePt, - const Base::Vector3f& lineDir, - Base::Vector3f& rclPnt1, - Base::Vector3f& rclPnt2) const +void MeshGeomEdge::ClosestPointsToLine( + const Base::Vector3f& linePt, + const Base::Vector3f& lineDir, + Base::Vector3f& rclPnt1, + Base::Vector3f& rclPnt2 +) const { const float eps = 1e-06F; Base::Vector3f edgeDir = _aclPoints[1] - _aclPoints[0]; @@ -467,9 +473,7 @@ MeshGeomFacet::MeshGeomFacet() {} -MeshGeomFacet::MeshGeomFacet(const Base::Vector3f& v1, - const Base::Vector3f& v2, - const Base::Vector3f& v3) +MeshGeomFacet::MeshGeomFacet(const Base::Vector3f& v1, const Base::Vector3f& v2, const Base::Vector3f& v3) : _bNormalCalculated(false) , _ucFlag(0) , _ulProp(0) @@ -594,8 +598,7 @@ bool MeshGeomFacet::Weights(const Base::Vector3f& rclP, float& w0, float& w1, fl return std::fabs(w0 + w1 + w2 - 1.0F) < 0.001F; } -void MeshGeomFacet::ProjectPointToPlane(const Base::Vector3f& rclPoint, - Base::Vector3f& rclProj) const +void MeshGeomFacet::ProjectPointToPlane(const Base::Vector3f& rclPoint, Base::Vector3f& rclProj) const { rclPoint.ProjectToPlane(_aclPoints[0], GetNormal(), rclProj); } @@ -755,10 +758,12 @@ bool MeshGeomFacet::IntersectBoundingBox(const Base::BoundBox3f& rclBB) const return (akSec2.Test()); } -bool MeshGeomFacet::IntersectWithPlane(const Base::Vector3f& rclBase, - const Base::Vector3f& rclNormal, - Base::Vector3f& rclP1, - Base::Vector3f& rclP2) const +bool MeshGeomFacet::IntersectWithPlane( + const Base::Vector3f& rclBase, + const Base::Vector3f& rclNormal, + Base::Vector3f& rclP1, + Base::Vector3f& rclP2 +) const { const float eps = 1e-06F; @@ -879,10 +884,12 @@ bool MeshGeomFacet::IntersectWithPlane(const Base::Vector3f& rclBase, return false; } -bool MeshGeomFacet::Foraminate(const Base::Vector3f& P, - const Base::Vector3f& dir, - Base::Vector3f& I, - float fMaxAngle) const +bool MeshGeomFacet::Foraminate( + const Base::Vector3f& P, + const Base::Vector3f& dir, + Base::Vector3f& I, + float fMaxAngle +) const { const float eps = 1e-06F; Base::Vector3f n = this->GetNormal(); @@ -929,9 +936,11 @@ bool MeshGeomFacet::Foraminate(const Base::Vector3f& P, return false; } -bool MeshGeomFacet::IntersectPlaneWithLine(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const +bool MeshGeomFacet::IntersectPlaneWithLine( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes +) const { // calculate the intersection of the straight line <-> plane if (fabs(rclDir * GetNormal()) < 1e-3F) { @@ -944,9 +953,11 @@ bool MeshGeomFacet::IntersectPlaneWithLine(const Base::Vector3f& rclPt, return true; } -bool MeshGeomFacet::IntersectWithLine(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const +bool MeshGeomFacet::IntersectWithLine( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes +) const { if (!IntersectPlaneWithLine(rclPt, rclDir, rclRes)) { return false; // line and plane are parallel @@ -955,8 +966,7 @@ bool MeshGeomFacet::IntersectWithLine(const Base::Vector3f& rclPt, return IsPointOfFace(rclRes, 1e-03F); } -float MeshGeomFacet::DistanceToLineSegment(const Base::Vector3f& rclP1, - const Base::Vector3f& rclP2) const +float MeshGeomFacet::DistanceToLineSegment(const Base::Vector3f& rclP1, const Base::Vector3f& rclP2) const { // line segment Vector3 A(rclP1.x, rclP1.y, rclP1.z); @@ -1101,9 +1111,11 @@ bool MeshGeomFacet::IntersectWithFacet(const MeshGeomFacet& rclFacet) const * http://www.acm.org/jgt/papers/Moller97/tritri.html * http://www.cs.lth.se/home/Tomas_Akenine_Moller/code/ */ -int MeshGeomFacet::IntersectWithFacet(const MeshGeomFacet& rclFacet, - Base::Vector3f& rclPt0, - Base::Vector3f& rclPt1) const +int MeshGeomFacet::IntersectWithFacet( + const MeshGeomFacet& rclFacet, + Base::Vector3f& rclPt0, + Base::Vector3f& rclPt1 +) const { // Note: tri_tri_intersect_with_isection() does not return line of // intersection when triangles are coplanar. See tritritest.h:18 and 658. @@ -1151,15 +1163,7 @@ int MeshGeomFacet::IntersectWithFacet(const MeshGeomFacet& rclFacet, U[i][2] = rclFacet._aclPoints[i].z; } - if (tri_tri_intersect_with_isectline(V[0], - V[1], - V[2], - U[0], - U[1], - U[2], - &coplanar, - isectpt1, - isectpt2) + if (tri_tri_intersect_with_isectline(V[0], V[1], V[2], U[0], U[1], U[2], &coplanar, isectpt1, isectpt2) == 0) { return 0; // no intersections } @@ -1377,9 +1381,11 @@ unsigned short MeshGeomFacet::NearestEdgeToPoint(const Base::Vector3f& rclPt) co return usSide; } -void MeshGeomFacet::NearestEdgeToPoint(const Base::Vector3f& rclPt, - float& fDistance, - unsigned short& usSide) const +void MeshGeomFacet::NearestEdgeToPoint( + const Base::Vector3f& rclPt, + float& fDistance, + unsigned short& usSide +) const { const Base::Vector3f& rcP1 = _aclPoints[0]; const Base::Vector3f& rcP2 = _aclPoints[1]; diff --git a/src/Mod/Mesh/App/Core/Elements.h b/src/Mod/Mesh/App/Core/Elements.h index 82a4bf9c1a..787126c2d1 100644 --- a/src/Mod/Mesh/App/Core/Elements.h +++ b/src/Mod/Mesh/App/Core/Elements.h @@ -199,9 +199,11 @@ public: * \a rclDir with the edge. The intersection must be inside the edge. If there is no * intersection false is returned. */ - bool IntersectWithLine(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const; + bool IntersectWithLine( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes + ) const; /** Calculates the intersection point of an edge with this edge. * The intersection must be inside both edges. If there is no intersection false is returned. */ @@ -210,9 +212,11 @@ public: * direction \a rclDir with the edge. The intersection must be inside the edge. If there is no * intersection false is returned. */ - bool IntersectWithPlane(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const; + bool IntersectWithPlane( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes + ) const; /** * Calculates the projection of a point onto the line defined by the edge. The caller must check * if the projection point is inside the edge. @@ -223,10 +227,12 @@ public: * line defined by \a rclPt and \a rclDir. If the two points are identical then both lines * intersect each other. */ - void ClosestPointsToLine(const Base::Vector3f& linePt, - const Base::Vector3f& lineDir, - Base::Vector3f& rclPnt1, - Base::Vector3f& rclPnt2) const; + void ClosestPointsToLine( + const Base::Vector3f& linePt, + const Base::Vector3f& lineDir, + Base::Vector3f& rclPnt1, + Base::Vector3f& rclPnt2 + ) const; /** * Checks if the point is part of the edge. A point is regarded as part * of an edge if the distance is lower than \a fDistance to the projected point @@ -291,12 +297,14 @@ public: inline MeshFacet(); inline MeshFacet(const MeshFacet& rclF) = default; inline MeshFacet(MeshFacet&& rclF) = default; - inline MeshFacet(PointIndex p1, - PointIndex p2, - PointIndex p3, - FacetIndex n1 = FACET_INDEX_MAX, - FacetIndex n2 = FACET_INDEX_MAX, - FacetIndex n3 = FACET_INDEX_MAX); + inline MeshFacet( + PointIndex p1, + PointIndex p2, + PointIndex p3, + FacetIndex n1 = FACET_INDEX_MAX, + FacetIndex n2 = FACET_INDEX_MAX, + FacetIndex n3 = FACET_INDEX_MAX + ); ~MeshFacet() = default; //@} @@ -568,9 +576,7 @@ public: * Return is the number of intersections points: 0: no intersection, 1: one intersection point * (rclPt0), 2: two intersections points (rclPt0, rclPt1) */ - int IntersectWithFacet(const MeshGeomFacet& facet, - Base::Vector3f& rclPt0, - Base::Vector3f& rclPt1) const; + int IntersectWithFacet(const MeshGeomFacet& facet, Base::Vector3f& rclPt0, Base::Vector3f& rclPt1) const; /** Calculates the shortest distance from the line segment defined by \a rcP1 and \a rcP2 to * this facet. */ @@ -589,39 +595,46 @@ public: * \a rclDir with the facet. The intersection must be inside the facet. If there is no * intersection false is returned. */ - bool IntersectWithLine(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const; + bool IntersectWithLine( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes + ) const; /** Calculates the intersection point of the line defined by the base \a rclPt and the direction * \a rclDir with the facet. The intersection must be inside the facet. If there is no * intersection false is returned. This does actually the same as IntersectWithLine() with one * additionally constraint that the angle between the direction of the line and the normal of * the plane must not exceed \a fMaxAngle. */ - bool Foraminate(const Base::Vector3f& P, - const Base::Vector3f& dir, - Base::Vector3f& I, - float fMaxAngle = Mathf::PI) const; + bool Foraminate( + const Base::Vector3f& P, + const Base::Vector3f& dir, + Base::Vector3f& I, + float fMaxAngle = Mathf::PI + ) const; /** Checks if the facet intersects with the plane defined by the base \a rclBase and the normal * \a rclNormal and returns true if two points are found, false otherwise. */ - bool IntersectWithPlane(const Base::Vector3f& rclBase, - const Base::Vector3f& rclNormal, - Base::Vector3f& rclP1, - Base::Vector3f& rclP2) const; + bool IntersectWithPlane( + const Base::Vector3f& rclBase, + const Base::Vector3f& rclNormal, + Base::Vector3f& rclP1, + Base::Vector3f& rclP2 + ) const; /** * Checks if the facet intersects with the plane defined by the base \a rclBase and the normal * \a rclNormal. */ - inline bool IntersectWithPlane(const Base::Vector3f& rclBase, - const Base::Vector3f& rclNormal) const; + inline bool IntersectWithPlane(const Base::Vector3f& rclBase, const Base::Vector3f& rclNormal) const; /** Checks if the plane defined by the facet \a rclFacet intersects with the line defined by the * base \a rclBase and the direction \a rclNormal and returns the intersection point \a rclRes * if possible. */ - bool IntersectPlaneWithLine(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - Base::Vector3f& rclRes) const; + bool IntersectPlaneWithLine( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + Base::Vector3f& rclRes + ) const; /** Calculates the volume of the prism defined by two facets. * \note The two facets must not intersect. */ @@ -636,8 +649,7 @@ public: unsigned short NearestEdgeToPoint(const Base::Vector3f& rclPt) const; /** Returns the edge number \a side of the facet and the distance to the edge that is nearest to * the point \a rclPt. */ - void - NearestEdgeToPoint(const Base::Vector3f& rclPt, float& fDistance, unsigned short& side) const; + void NearestEdgeToPoint(const Base::Vector3f& rclPt, float& fDistance, unsigned short& side) const; /** Returns the edge for \a side. */ MeshGeomEdge GetEdge(short side) const; /** The center and radius of the circum circle define a sphere in 3D. If the point \a rP is part @@ -985,12 +997,16 @@ inline bool MeshGeomFacet::ContainedByOrIntersectBoundingBox(const Base::BoundBo return (IntersectBoundingBox(rclBB)); } -inline bool MeshGeomFacet::IntersectWithPlane(const Base::Vector3f& rclBase, - const Base::Vector3f& rclNormal) const +inline bool MeshGeomFacet::IntersectWithPlane( + const Base::Vector3f& rclBase, + const Base::Vector3f& rclNormal +) const { bool bD0 = (_aclPoints[0].DistanceToPlane(rclBase, rclNormal) > 0.0F); - return !((bD0 == (_aclPoints[1].DistanceToPlane(rclBase, rclNormal) > 0.0F)) - && (bD0 == (_aclPoints[2].DistanceToPlane(rclBase, rclNormal) > 0.0F))); + return !( + (bD0 == (_aclPoints[1].DistanceToPlane(rclBase, rclNormal) > 0.0F)) + && (bD0 == (_aclPoints[2].DistanceToPlane(rclBase, rclNormal) > 0.0F)) + ); } inline MeshFacet::MeshFacet() // NOLINT @@ -1001,12 +1017,14 @@ inline MeshFacet::MeshFacet() // NOLINT memset(_aulPoints, 0xff, sizeof(PointIndex) * 3); } -inline MeshFacet::MeshFacet(PointIndex p1, - PointIndex p2, - PointIndex p3, - FacetIndex n1, - FacetIndex n2, - FacetIndex n3) +inline MeshFacet::MeshFacet( + PointIndex p1, + PointIndex p2, + PointIndex p3, + FacetIndex n1, + FacetIndex n2, + FacetIndex n3 +) : _ucFlag(0) , _ulProp(0) , _aulPoints {p1, p2, p3} diff --git a/src/Mod/Mesh/App/Core/Evaluation.cpp b/src/Mod/Mesh/App/Core/Evaluation.cpp index 9cd7f36efe..261ba95d66 100644 --- a/src/Mod/Mesh/App/Core/Evaluation.cpp +++ b/src/Mod/Mesh/App/Core/Evaluation.cpp @@ -44,10 +44,12 @@ using namespace MeshCore; MeshOrientationVisitor::MeshOrientationVisitor() = default; -bool MeshOrientationVisitor::Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) +bool MeshOrientationVisitor::Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel +) { (void)ulFInd; (void)ulLevel; @@ -64,16 +66,20 @@ bool MeshOrientationVisitor::HasNonUnifomOrientedFacets() const return _nonuniformOrientation; } -MeshOrientationCollector::MeshOrientationCollector(std::vector& aulIndices, - std::vector& aulComplement) +MeshOrientationCollector::MeshOrientationCollector( + std::vector& aulIndices, + std::vector& aulComplement +) : _aulIndices(aulIndices) , _aulComplement(aulComplement) {} -bool MeshOrientationCollector::Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) +bool MeshOrientationCollector::Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel +) { (void)ulLevel; // different orientation of rclFacet and rclFrom @@ -108,10 +114,12 @@ MeshSameOrientationCollector::MeshSameOrientationCollector(std::vector MeshEvalOrientation::GetIndices() const std::vector diff; std::back_insert_iterator> biit(diff); - std::set_difference(uIndices.begin(), - uIndices.end(), - falsePos.begin(), - falsePos.end(), - biit); + std::set_difference(uIndices.begin(), uIndices.end(), falsePos.begin(), falsePos.end(), biit); uIndices = diff; cAlg.ResetFacetFlag(MeshFacet::TMP0); @@ -457,8 +461,7 @@ bool MeshFixTopology::Fixup() if (!deletedFaces.empty()) { // remove duplicates std::sort(deletedFaces.begin(), deletedFaces.end()); - deletedFaces.erase(std::unique(deletedFaces.begin(), deletedFaces.end()), - deletedFaces.end()); + deletedFaces.erase(std::unique(deletedFaces.begin(), deletedFaces.end()), deletedFaces.end()); _rclMesh.DeleteFacets(deletedFaces); _rclMesh.RebuildNeighbours(); @@ -676,7 +679,8 @@ bool MeshEvalSelfIntersection::Evaluate() void MeshEvalSelfIntersection::GetIntersections( const std::vector>& indices, - std::vector>& intersection) const + std::vector>& intersection +) const { intersection.reserve(indices.size()); MeshFacetIterator cMF1(_rclMesh); @@ -700,7 +704,8 @@ void MeshEvalSelfIntersection::GetIntersections( } void MeshEvalSelfIntersection::GetIntersections( - std::vector>& intersection) const + std::vector>& intersection +) const { // Contains bounding boxes for every facet std::vector boxes; diff --git a/src/Mod/Mesh/App/Core/Evaluation.h b/src/Mod/Mesh/App/Core/Evaluation.h index 1b4f32fa72..e869deca4c 100644 --- a/src/Mod/Mesh/App/Core/Evaluation.h +++ b/src/Mod/Mesh/App/Core/Evaluation.h @@ -129,8 +129,7 @@ private: class MeshExport MeshOrientationCollector: public MeshOrientationVisitor { public: - MeshOrientationCollector(std::vector& aulIndices, - std::vector& aulComplement); + MeshOrientationCollector(std::vector& aulIndices, std::vector& aulComplement); /** Returns always true and collects the indices with wrong orientation. */ bool Visit(const MeshFacet&, const MeshFacet&, FacetIndex, unsigned long) override; @@ -335,8 +334,10 @@ public: /// Evaluate the mesh and return if true if there are self intersections bool Evaluate() override; /// collect all intersection lines - void GetIntersections(const std::vector>&, - std::vector>&) const; + void GetIntersections( + const std::vector>&, + std::vector>& + ) const; /// collect the index of all facets with self intersections void GetIntersections(std::vector>&) const; }; @@ -348,8 +349,7 @@ public: class MeshExport MeshFixSelfIntersection: public MeshValidation { public: - MeshFixSelfIntersection(MeshKernel& rclB, - const std::vector>& si) + MeshFixSelfIntersection(MeshKernel& rclB, const std::vector>& si) : MeshValidation(rclB) , selfIntersectons(si) {} @@ -422,8 +422,7 @@ protected: private: Base::Vector3f _cU, _cV, _cW, _cC; /**< Vectors that define the local coordinate system. */ - float _fU, _fV, - _fW; /**< Expansion in \a u, \a v, and \a w direction of the transformed mesh. */ + float _fU, _fV, _fW; /**< Expansion in \a u, \a v, and \a w direction of the transformed mesh. */ }; } // namespace MeshCore diff --git a/src/Mod/Mesh/App/Core/Functional.h b/src/Mod/Mesh/App/Core/Functional.h index c2dfe16cbf..7913a6fc81 100644 --- a/src/Mod/Mesh/App/Core/Functional.h +++ b/src/Mod/Mesh/App/Core/Functional.h @@ -45,18 +45,16 @@ static void parallel_sort(Iter begin, Iter end, Pred comp, int threads) future.wait(); } else { - auto a = std::async(std::launch::async, - parallel_sort, - begin, - mid, - comp, - threads / 2); - auto b = std::async(std::launch::async, - parallel_sort, - mid, - end, - comp, - threads / 2); + auto a = std::async( + std::launch::async, + parallel_sort, + begin, + mid, + comp, + threads / 2 + ); + auto b + = std::async(std::launch::async, parallel_sort, mid, end, comp, threads / 2); a.wait(); b.wait(); } diff --git a/src/Mod/Mesh/App/Core/Grid.cpp b/src/Mod/Mesh/App/Core/Grid.cpp index a3f2fa79fe..1c9e123a4b 100644 --- a/src/Mod/Mesh/App/Core/Grid.cpp +++ b/src/Mod/Mesh/App/Core/Grid.cpp @@ -139,9 +139,11 @@ void MeshGrid::InitGrid() } } -unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, - std::vector& raulElements, - bool bDelDoubles) const +unsigned long MeshGrid::Inside( + const Base::BoundBox3f& rclBB, + std::vector& raulElements, + bool bDelDoubles +) const { unsigned long ulMinX {}; unsigned long ulMinY {}; @@ -159,9 +161,8 @@ unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, for (auto i = ulMinX; i <= ulMaxX; i++) { for (auto j = ulMinY; j <= ulMaxY; j++) { for (auto k = ulMinZ; k <= ulMaxZ; k++) { - raulElements.insert(raulElements.end(), - _aulGrid[i][j][k].begin(), - _aulGrid[i][j][k].end()); + raulElements + .insert(raulElements.end(), _aulGrid[i][j][k].begin(), _aulGrid[i][j][k].end()); } } } @@ -169,18 +170,19 @@ unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, if (bDelDoubles) { // remove duplicate mentions std::sort(raulElements.begin(), raulElements.end()); - raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), - raulElements.end()); + raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), raulElements.end()); } return raulElements.size(); } -unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, - std::vector& raulElements, - const Base::Vector3f& rclOrg, - float fMaxDist, - bool bDelDoubles) const +unsigned long MeshGrid::Inside( + const Base::BoundBox3f& rclBB, + std::vector& raulElements, + const Base::Vector3f& rclOrg, + float fMaxDist, + bool bDelDoubles +) const { unsigned long ulMinX {}; unsigned long ulMinY {}; @@ -201,9 +203,11 @@ unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, for (auto j = ulMinY; j <= ulMaxY; j++) { for (auto k = ulMinZ; k <= ulMaxZ; k++) { if (Base::DistanceP2(GetBoundBox(i, j, k).GetCenter(), rclOrg) < fMinDistP2) { - raulElements.insert(raulElements.end(), - _aulGrid[i][j][k].begin(), - _aulGrid[i][j][k].end()); + raulElements.insert( + raulElements.end(), + _aulGrid[i][j][k].begin(), + _aulGrid[i][j][k].end() + ); } } } @@ -212,15 +216,13 @@ unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, if (bDelDoubles) { // remove duplicate mentions std::sort(raulElements.begin(), raulElements.end()); - raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), - raulElements.end()); + raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), raulElements.end()); } return raulElements.size(); } -unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, - std::set& raulElements) const +unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, std::set& raulElements) const { unsigned long ulMinX {}; unsigned long ulMinY {}; @@ -246,10 +248,12 @@ unsigned long MeshGrid::Inside(const Base::BoundBox3f& rclBB, return raulElements.size(); } -bool MeshGrid::CheckPosition(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +bool MeshGrid::CheckPosition( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { rulX = static_cast((rclPoint.x - _fMinX) / _fGridLenX); rulY = static_cast((rclPoint.y - _fMinY) / _fGridLenY); @@ -258,36 +262,41 @@ bool MeshGrid::CheckPosition(const Base::Vector3f& rclPoint, return ((rulX < _ulCtGridsX) && (rulY < _ulCtGridsY) && (rulZ < _ulCtGridsZ)); } -void MeshGrid::Position(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +void MeshGrid::Position( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { if (rclPoint.x <= _fMinX) { rulX = 0; } else { - rulX = - std::min(static_cast((rclPoint.x - _fMinX) / _fGridLenX), - _ulCtGridsX - 1); + rulX = std::min( + static_cast((rclPoint.x - _fMinX) / _fGridLenX), + _ulCtGridsX - 1 + ); } if (rclPoint.y <= _fMinY) { rulY = 0; } else { - rulY = - std::min(static_cast((rclPoint.y - _fMinY) / _fGridLenY), - _ulCtGridsY - 1); + rulY = std::min( + static_cast((rclPoint.y - _fMinY) / _fGridLenY), + _ulCtGridsY - 1 + ); } if (rclPoint.z <= _fMinZ) { rulZ = 0; } else { - rulZ = - std::min(static_cast((rclPoint.z - _fMinZ) / _fGridLenZ), - _ulCtGridsZ - 1); + rulZ = std::min( + static_cast((rclPoint.z - _fMinZ) / _fGridLenZ), + _ulCtGridsZ - 1 + ); } } @@ -370,10 +379,10 @@ void MeshGrid::CalculateGridLength(int iCtGridPerAxis) auto fLengthGrid = float(std::sqrt(fAreaGrid)); - _ulCtGridsY = - std::max(static_cast(fLenghtY / fLengthGrid), 1); - _ulCtGridsZ = - std::max(static_cast(fLenghtZ / fLengthGrid), 1); + _ulCtGridsY + = std::max(static_cast(fLenghtY / fLengthGrid), 1); + _ulCtGridsZ + = std::max(static_cast(fLenghtZ / fLengthGrid), 1); } break; case 2: { _ulCtGridsY = 1; // bLenghtYisZero @@ -388,10 +397,10 @@ void MeshGrid::CalculateGridLength(int iCtGridPerAxis) auto fLengthGrid = float(std::sqrt(fAreaGrid)); - _ulCtGridsX = - std::max(static_cast(fLenghtX / fLengthGrid), 1); - _ulCtGridsZ = - std::max(static_cast(fLenghtZ / fLengthGrid), 1); + _ulCtGridsX + = std::max(static_cast(fLenghtX / fLengthGrid), 1); + _ulCtGridsZ + = std::max(static_cast(fLenghtZ / fLengthGrid), 1); } break; case 3: { _ulCtGridsX = 1; // bLenghtXisZero @@ -411,10 +420,10 @@ void MeshGrid::CalculateGridLength(int iCtGridPerAxis) auto fLengthGrid = float(std::sqrt(fAreaGrid)); - _ulCtGridsX = - std::max(static_cast(fLenghtX / fLengthGrid), 1); - _ulCtGridsY = - std::max(static_cast(fLenghtY / fLengthGrid), 1); + _ulCtGridsX + = std::max(static_cast(fLenghtX / fLengthGrid), 1); + _ulCtGridsY + = std::max(static_cast(fLenghtY / fLengthGrid), 1); } break; case 5: { _ulCtGridsX = 1; // bLenghtXisZero @@ -434,8 +443,7 @@ void MeshGrid::CalculateGridLength(int iCtGridPerAxis) } } -void MeshGrid::SearchNearestFromPoint(const Base::Vector3f& pnt, - std::set& indices) const +void MeshGrid::SearchNearestFromPoint(const Base::Vector3f& pnt, std::set& indices) const { indices.clear(); Base::BoundBox3f clBB = GetBoundBox(); @@ -446,8 +454,8 @@ void MeshGrid::SearchNearestFromPoint(const Base::Vector3f& pnt, unsigned long ulZ {}; Position(pnt, ulX, ulY, ulZ); // int nX = ulX, nY = ulY, nZ = ulZ; - unsigned long ulMaxLevel = - std::max(_ulCtGridsX, std::max(_ulCtGridsY, _ulCtGridsZ)); + unsigned long ulMaxLevel + = std::max(_ulCtGridsX, std::max(_ulCtGridsY, _ulCtGridsZ)); unsigned long ulLevel = 0; while (indices.empty() && ulLevel <= ulMaxLevel) { GetHull(ulX, ulY, ulZ, ulLevel++, indices); @@ -536,11 +544,13 @@ void MeshGrid::SearchNearestFromPoint(const Base::Vector3f& pnt, } } -void MeshGrid::GetHull(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - unsigned long ulDistance, - std::set& raclInd) const +void MeshGrid::GetHull( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + unsigned long ulDistance, + std::set& raclInd +) const { int nX1 = std::max(0, int(ulX) - int(ulDistance)); int nY1 = std::max(0, int(ulY) - int(ulDistance)); @@ -552,63 +562,77 @@ void MeshGrid::GetHull(unsigned long ulX, // top plane for (int i = nX1; i <= nX2; i++) { for (int j = nY1; j <= nY2; j++) { - GetElements(static_cast(i), - static_cast(j), - static_cast(nZ1), - raclInd); + GetElements( + static_cast(i), + static_cast(j), + static_cast(nZ1), + raclInd + ); } } // bottom plane for (int i = nX1; i <= nX2; i++) { for (int j = nY1; j <= nY2; j++) { - GetElements(static_cast(i), - static_cast(j), - static_cast(nZ2), - raclInd); + GetElements( + static_cast(i), + static_cast(j), + static_cast(nZ2), + raclInd + ); } } // left plane for (int i = nY1; i <= nY2; i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - GetElements(static_cast(nX1), - static_cast(i), - static_cast(j), - raclInd); + GetElements( + static_cast(nX1), + static_cast(i), + static_cast(j), + raclInd + ); } } // right plane for (int i = nY1; i <= nY2; i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - GetElements(static_cast(nX2), - static_cast(i), - static_cast(j), - raclInd); + GetElements( + static_cast(nX2), + static_cast(i), + static_cast(j), + raclInd + ); } } // front plane for (int i = (nX1 + 1); i <= (nX2 - 1); i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - GetElements(static_cast(i), - static_cast(nY1), - static_cast(j), - raclInd); + GetElements( + static_cast(i), + static_cast(nY1), + static_cast(j), + raclInd + ); } } // back plane for (int i = (nX1 + 1); i <= (nX2 - 1); i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - GetElements(static_cast(i), - static_cast(nY2), - static_cast(j), - raclInd); + GetElements( + static_cast(i), + static_cast(nY2), + static_cast(j), + raclInd + ); } } } -unsigned long MeshGrid::GetElements(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - std::set& raclInd) const +unsigned long MeshGrid::GetElements( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + std::set& raclInd +) const { const std::set& rclSet = _aulGrid[ulX][ulY][ulZ]; if (!rclSet.empty()) { @@ -619,8 +643,10 @@ unsigned long MeshGrid::GetElements(unsigned long ulX, return 0; } -unsigned long MeshGrid::GetElements(const Base::Vector3f& rclPoint, - std::vector& aulFacets) const +unsigned long MeshGrid::GetElements( + const Base::Vector3f& rclPoint, + std::vector& aulFacets +) const { unsigned long ulX {}; unsigned long ulY {}; @@ -635,8 +661,7 @@ unsigned long MeshGrid::GetElements(const Base::Vector3f& rclPoint, return aulFacets.size(); } -unsigned long -MeshGrid::GetIndexToPosition(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const +unsigned long MeshGrid::GetIndexToPosition(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const { if (!CheckPos(ulX, ulY, ulZ)) { return std::numeric_limits::max(); @@ -644,10 +669,12 @@ MeshGrid::GetIndexToPosition(unsigned long ulX, unsigned long ulY, unsigned long return (ulZ * _ulCtGridsY + ulY) * _ulCtGridsX + ulX; } -bool MeshGrid::GetPositionToIndex(unsigned long id, - unsigned long& ulX, - unsigned long& ulY, - unsigned long& ulZ) const +bool MeshGrid::GetPositionToIndex( + unsigned long id, + unsigned long& ulX, + unsigned long& ulY, + unsigned long& ulZ +) const { ulX = id % _ulCtGridsX; ulY = (id / _ulCtGridsX) % _ulCtGridsY; @@ -677,10 +704,7 @@ MeshFacetGrid::MeshFacetGrid(const MeshKernel& rclM, int iCtGridPerAxis) Rebuild(iCtGridPerAxis); } -MeshFacetGrid::MeshFacetGrid(const MeshKernel& rclM, - unsigned long ulX, - unsigned long ulY, - unsigned long ulZ) +MeshFacetGrid::MeshFacetGrid(const MeshKernel& rclM, unsigned long ulX, unsigned long ulY, unsigned long ulZ) : MeshGrid(rclM) { Rebuild(ulX, ulY, ulZ); @@ -690,9 +714,11 @@ MeshFacetGrid::MeshFacetGrid(const MeshKernel& rclM, float fGridLen) : MeshGrid(rclM) { Base::BoundBox3f clBBMesh = _pclMesh->GetBoundBox(); - Rebuild(std::max(static_cast(clBBMesh.LengthX() / fGridLen), 1), - std::max(static_cast(clBBMesh.LengthY() / fGridLen), 1), - std::max(static_cast(clBBMesh.LengthZ() / fGridLen), 1)); + Rebuild( + std::max(static_cast(clBBMesh.LengthX() / fGridLen), 1), + std::max(static_cast(clBBMesh.LengthY() / fGridLen), 1), + std::max(static_cast(clBBMesh.LengthZ() / fGridLen), 1) + ); } void MeshFacetGrid::Validate(const MeshKernel& rclMesh) @@ -865,8 +891,7 @@ unsigned long MeshFacetGrid::SearchNearestFromPoint(const Base::Vector3f& rclPt) return ulFacetInd; } -unsigned long MeshFacetGrid::SearchNearestFromPoint(const Base::Vector3f& rclPt, - float fMaxSearchArea) const +unsigned long MeshFacetGrid::SearchNearestFromPoint(const Base::Vector3f& rclPt, float fMaxSearchArea) const { std::vector aulFacets; ElementIndex ulFacetInd = ELEMENT_INDEX_MAX; @@ -874,12 +899,14 @@ unsigned long MeshFacetGrid::SearchNearestFromPoint(const Base::Vector3f& rclPt, MeshAlgorithm clFTool(*_pclMesh); - Base::BoundBox3f clBB(rclPt.x - fMaxSearchArea, - rclPt.y - fMaxSearchArea, - rclPt.z - fMaxSearchArea, - rclPt.x + fMaxSearchArea, - rclPt.y + fMaxSearchArea, - rclPt.z + fMaxSearchArea); + Base::BoundBox3f clBB( + rclPt.x - fMaxSearchArea, + rclPt.y - fMaxSearchArea, + rclPt.z - fMaxSearchArea, + rclPt.x + fMaxSearchArea, + rclPt.y + fMaxSearchArea, + rclPt.z + fMaxSearchArea + ); Inside(clBB, aulFacets, rclPt, fMaxSearchArea, true); @@ -895,13 +922,15 @@ unsigned long MeshFacetGrid::SearchNearestFromPoint(const Base::Vector3f& rclPt, return ulFacetInd; } -void MeshFacetGrid::SearchNearestFacetInHull(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - unsigned long ulDistance, - const Base::Vector3f& rclPt, - ElementIndex& rulFacetInd, - float& rfMinDist) const +void MeshFacetGrid::SearchNearestFacetInHull( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + unsigned long ulDistance, + const Base::Vector3f& rclPt, + ElementIndex& rulFacetInd, + float& rfMinDist +) const { int nX1 = std::max(0, int(ulX) - int(ulDistance)); int nY1 = std::max(0, int(ulY) - int(ulDistance)); @@ -913,77 +942,91 @@ void MeshFacetGrid::SearchNearestFacetInHull(unsigned long ulX, // top plane for (int i = nX1; i <= nX2; i++) { for (int j = nY1; j <= nY2; j++) { - SearchNearestFacetInGrid(static_cast(i), - static_cast(j), - static_cast(nZ1), - rclPt, - rfMinDist, - rulFacetInd); + SearchNearestFacetInGrid( + static_cast(i), + static_cast(j), + static_cast(nZ1), + rclPt, + rfMinDist, + rulFacetInd + ); } } // bottom plane for (int i = nX1; i <= nX2; i++) { for (int j = nY1; j <= nY2; j++) { - SearchNearestFacetInGrid(static_cast(i), - static_cast(j), - static_cast(nZ2), - rclPt, - rfMinDist, - rulFacetInd); + SearchNearestFacetInGrid( + static_cast(i), + static_cast(j), + static_cast(nZ2), + rclPt, + rfMinDist, + rulFacetInd + ); } } // left plane for (int i = nY1; i <= nY2; i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - SearchNearestFacetInGrid(static_cast(nX1), - static_cast(i), - static_cast(j), - rclPt, - rfMinDist, - rulFacetInd); + SearchNearestFacetInGrid( + static_cast(nX1), + static_cast(i), + static_cast(j), + rclPt, + rfMinDist, + rulFacetInd + ); } } // right plane for (int i = nY1; i <= nY2; i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - SearchNearestFacetInGrid(static_cast(nX2), - static_cast(i), - static_cast(j), - rclPt, - rfMinDist, - rulFacetInd); + SearchNearestFacetInGrid( + static_cast(nX2), + static_cast(i), + static_cast(j), + rclPt, + rfMinDist, + rulFacetInd + ); } } // front plane for (int i = (nX1 + 1); i <= (nX2 - 1); i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - SearchNearestFacetInGrid(static_cast(i), - static_cast(nY1), - static_cast(j), - rclPt, - rfMinDist, - rulFacetInd); + SearchNearestFacetInGrid( + static_cast(i), + static_cast(nY1), + static_cast(j), + rclPt, + rfMinDist, + rulFacetInd + ); } } // back plane for (int i = (nX1 + 1); i <= (nX2 - 1); i++) { for (int j = (nZ1 + 1); j <= (nZ2 - 1); j++) { - SearchNearestFacetInGrid(static_cast(i), - static_cast(nY2), - static_cast(j), - rclPt, - rfMinDist, - rulFacetInd); + SearchNearestFacetInGrid( + static_cast(i), + static_cast(nY2), + static_cast(j), + rclPt, + rfMinDist, + rulFacetInd + ); } } } -void MeshFacetGrid::SearchNearestFacetInGrid(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - const Base::Vector3f& rclPt, - float& rfMinDist, - ElementIndex& rulFacetInd) const +void MeshFacetGrid::SearchNearestFacetInGrid( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + const Base::Vector3f& rclPt, + float& rfMinDist, + ElementIndex& rulFacetInd +) const { const std::set& rclSet = _aulGrid[ulX][ulY][ulZ]; for (ElementIndex pI : rclSet) { @@ -1005,10 +1048,7 @@ MeshPointGrid::MeshPointGrid(const MeshKernel& rclM) MeshPointGrid::MeshPointGrid() = default; -MeshPointGrid::MeshPointGrid(const MeshKernel& rclM, - unsigned long ulX, - unsigned long ulY, - unsigned long ulZ) +MeshPointGrid::MeshPointGrid(const MeshKernel& rclM, unsigned long ulX, unsigned long ulY, unsigned long ulZ) : MeshGrid(rclM) { Rebuild(ulX, ulY, ulZ); @@ -1024,9 +1064,11 @@ MeshPointGrid::MeshPointGrid(const MeshKernel& rclM, float fGridLen) : MeshGrid(rclM) { Base::BoundBox3f clBBMesh = _pclMesh->GetBoundBox(); - Rebuild(std::max(static_cast(clBBMesh.LengthX() / fGridLen), 1), - std::max(static_cast(clBBMesh.LengthY() / fGridLen), 1), - std::max(static_cast(clBBMesh.LengthZ() / fGridLen), 1)); + Rebuild( + std::max(static_cast(clBBMesh.LengthX() / fGridLen), 1), + std::max(static_cast(clBBMesh.LengthY() / fGridLen), 1), + std::max(static_cast(clBBMesh.LengthZ() / fGridLen), 1) + ); } void MeshPointGrid::AddPoint(const MeshPoint& rclPt, ElementIndex ulPtIndex, float fEpsilon) @@ -1103,18 +1145,22 @@ void MeshPointGrid::RebuildGrid() } } -void MeshPointGrid::Pos(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +void MeshPointGrid::Pos( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { rulX = static_cast((rclPoint.x - _fMinX) / _fGridLenX); rulY = static_cast((rclPoint.y - _fMinY) / _fGridLenY); rulZ = static_cast((rclPoint.z - _fMinZ) / _fGridLenZ); } -unsigned long MeshPointGrid::FindElements(const Base::Vector3f& rclPoint, - std::set& aulElements) const +unsigned long MeshPointGrid::FindElements( + const Base::Vector3f& rclPoint, + std::set& aulElements +) const { unsigned long ulX {}; unsigned long ulY {}; @@ -1137,19 +1183,23 @@ MeshGridIterator::MeshGridIterator(const MeshGrid& rclG) , _clDir(0.0F, 0.0F, 0.0F) {} -bool MeshGridIterator::InitOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - float fMaxSearchArea, - std::vector& raulElements) +bool MeshGridIterator::InitOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + float fMaxSearchArea, + std::vector& raulElements +) { bool ret = InitOnRay(rclPt, rclDir, raulElements); _fMaxSearchArea = fMaxSearchArea; return ret; } -bool MeshGridIterator::InitOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - std::vector& raulElements) +bool MeshGridIterator::InitOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + std::vector& raulElements +) { // needed in NextOnRay() to avoid an infinite loop _cSearchPositions.clear(); @@ -1165,9 +1215,11 @@ bool MeshGridIterator::InitOnRay(const Base::Vector3f& rclPt, // point lies within global BB if (_rclGrid.GetBoundBox().IsInBox(rclPt)) { // Determine the voxel by the starting point _rclGrid.Position(rclPt, _ulX, _ulY, _ulZ); - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); _bValidRay = true; } else { // Start point outside @@ -1182,9 +1234,11 @@ bool MeshGridIterator::InitOnRay(const Base::Vector3f& rclPt, _rclGrid.Position(cP1, _ulX, _ulY, _ulZ); } - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); _bValidRay = true; } } @@ -1203,8 +1257,8 @@ bool MeshGridIterator::NextOnRay(std::vector& raulElements) Base::Vector3f clIntersectPoint; // Look for the next adjacent BB on the search beam - Base::BoundBox3f::SIDE tSide = - _rclGrid.GetBoundBox(_ulX, _ulY, _ulZ).GetSideFromRay(_clPt, _clDir, clIntersectPoint); + Base::BoundBox3f::SIDE tSide + = _rclGrid.GetBoundBox(_ulX, _ulY, _ulZ).GetSideFromRay(_clPt, _clDir, clIntersectPoint); // Search area // @@ -1240,17 +1294,18 @@ bool MeshGridIterator::NextOnRay(std::vector& raulElements) GridElement pos(_ulX, _ulY, _ulZ); if (_cSearchPositions.find(pos) != _cSearchPositions.end()) { - _bValidRay = - false; // grid element already visited => result from GetSideFromRay invalid + _bValidRay = false; // grid element already visited => result from GetSideFromRay invalid } } if (_bValidRay && _rclGrid.CheckPos(_ulX, _ulY, _ulZ)) { GridElement pos(_ulX, _ulY, _ulZ); _cSearchPositions.insert(pos); - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); } else { _bValidRay = false; // Beam leaked diff --git a/src/Mod/Mesh/App/Core/Grid.h b/src/Mod/Mesh/App/Core/Grid.h index db76c10add..11e641f8b1 100644 --- a/src/Mod/Mesh/App/Core/Grid.h +++ b/src/Mod/Mesh/App/Core/Grid.h @@ -86,18 +86,24 @@ public: /** @name Search */ //@{ /** Searches for elements lying in the intersection area of the grid and the bounding box. */ - virtual unsigned long Inside(const Base::BoundBox3f& rclBB, - std::vector& raulElements, - bool bDelDoubles = true) const; + virtual unsigned long Inside( + const Base::BoundBox3f& rclBB, + std::vector& raulElements, + bool bDelDoubles = true + ) const; /** Searches for elements lying in the intersection area of the grid and the bounding box. */ - virtual unsigned long Inside(const Base::BoundBox3f& rclBB, - std::set& raulElementss) const; + virtual unsigned long Inside( + const Base::BoundBox3f& rclBB, + std::set& raulElementss + ) const; /** Searches for elements lying in the intersection area of the grid and the bounding box. */ - virtual unsigned long Inside(const Base::BoundBox3f& rclBB, - std::vector& raulElements, - const Base::Vector3f& rclOrg, - float fMaxDist, - bool bDelDoubles = true) const; + virtual unsigned long Inside( + const Base::BoundBox3f& rclBB, + std::vector& raulElements, + const Base::Vector3f& rclOrg, + float fMaxDist, + bool bDelDoubles = true + ) const; /** Searches for the nearest grids that contain elements from a point, the result are grid * indices. */ void SearchNearestFromPoint(const Base::Vector3f& pnt, std::set& indices) const; @@ -106,12 +112,13 @@ public: /** @name Getters */ //@{ /** Returns the indices of the elements in the given grid. */ - unsigned long GetElements(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - std::set& raclInd) const; - unsigned long GetElements(const Base::Vector3f& rclPoint, - std::vector& aulFacets) const; + unsigned long GetElements( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + std::set& raclInd + ) const; + unsigned long GetElements(const Base::Vector3f& rclPoint, std::vector& aulFacets) const; //@} /** Returns the lengths of the grid elements in x,y and z direction. */ @@ -132,8 +139,7 @@ public: /** @name Boundings */ //@{ /** Returns the bounding box of a given grid element. */ - inline Base::BoundBox3f - GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const; + inline Base::BoundBox3f GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const; /** Returns the bounding box of the whole. */ inline Base::BoundBox3f GetBoundBox() const; /** Returns an extended bounding box of the mesh object. */ @@ -147,10 +153,12 @@ public: /** Returns the grid position to the given index. If the index is equal to or higher than the * number of grid elements false is returned and the triple is set to ULONG_MAX. */ - bool GetPositionToIndex(unsigned long id, - unsigned long& ulX, - unsigned long& ulY, - unsigned long& ulZ) const; + bool GetPositionToIndex( + unsigned long id, + unsigned long& ulX, + unsigned long& ulY, + unsigned long& ulZ + ) const; /** Returns the number of elements in a given grid. */ unsigned long GetCtElements(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const { @@ -164,25 +172,31 @@ public: /** Checks whether the point is inside the grid. In case it is inside true is returned with the * grid position, otherwise false is returned and the grid position is undefined. */ - bool CheckPosition(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + bool CheckPosition( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; /** Returns the indices of the grid this point lies in. If the point is outside the grid the * indices of the nearest grid element are taken.*/ - virtual void Position(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + virtual void Position( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; /** Checks if this is a valid grid position. */ inline bool CheckPos(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const; /** Get the indices of all elements lying in the grids around a given grid with distance \a * ulDistance. */ - void GetHull(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - unsigned long ulDistance, - std::set& raclInd) const; + void GetHull( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + unsigned long ulDistance, + std::set& raclInd + ) const; protected: /** Initializes the size of the internal structure. */ @@ -198,9 +212,8 @@ protected: protected: // NOLINTBEGIN - std::vector>>> - _aulGrid; /**< Grid data structure. */ - const MeshKernel* _pclMesh; /**< The mesh kernel. */ + std::vector>>> _aulGrid; /**< Grid data structure. */ + const MeshKernel* _pclMesh; /**< The mesh kernel. */ unsigned long _ulCtElements; /**< Number of grid elements for validation issues. */ unsigned long _ulCtGridsX; /**< Number of grid elements in z. */ unsigned long _ulCtGridsY; /**< Number of grid elements in z. */ @@ -252,21 +265,25 @@ public: unsigned long SearchNearestFromPoint(const Base::Vector3f& rclPt, float fMaxSearchArea) const; /** Searches for the nearest facet in a given grid element and returns the facet index and the * actual distance. */ - void SearchNearestFacetInGrid(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - const Base::Vector3f& rclPt, - float& rfMinDist, - ElementIndex& rulFacetInd) const; + void SearchNearestFacetInGrid( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + const Base::Vector3f& rclPt, + float& rfMinDist, + ElementIndex& rulFacetInd + ) const; /** Does basically the same as the method above unless that grid neighbours up to the order of * \a ulDistance are introduced into the search. */ - void SearchNearestFacetInHull(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - unsigned long ulDistance, - const Base::Vector3f& rclPt, - ElementIndex& rulFacetInd, - float& rfMinDist) const; + void SearchNearestFacetInHull( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + unsigned long ulDistance, + const Base::Vector3f& rclPt, + ElementIndex& rulFacetInd, + float& rfMinDist + ) const; //@} /** Validates the grid structure and rebuilds it if needed. */ @@ -278,20 +295,23 @@ public: protected: /** Returns the grid numbers to the given point \a rclPoint. */ - inline void Pos(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + inline void Pos( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; /** Returns the grid numbers to the given point \a rclPoint. */ - inline void PosWithCheck(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + inline void PosWithCheck( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; /** Adds a new facet element to the grid structure. \a rclFacet is the geometric facet and \a * ulFacetIndex the corresponding index in the mesh kernel. The facet is added to each grid * element that intersects the facet. */ - inline void - AddFacet(const MeshGeomFacet& rclFacet, ElementIndex ulFacetIndex, float fEpsilon = 0.0F); + inline void AddFacet(const MeshGeomFacet& rclFacet, ElementIndex ulFacetIndex, float fEpsilon = 0.0F); /** Returns the number of stored elements. */ unsigned long HasElements() const override { @@ -329,8 +349,7 @@ public: //@} /** Finds all points that lie in the same grid as the point \a rclPoint. */ - unsigned long FindElements(const Base::Vector3f& rclPoint, - std::set& aulElements) const; + unsigned long FindElements(const Base::Vector3f& rclPoint, std::set& aulElements) const; /** Validates the grid structure and rebuilds it if needed. */ void Validate(const MeshKernel& rclM) override; /** Validates the grid structure and rebuilds it if needed. */ @@ -343,10 +362,12 @@ protected: * ulPtIndex the corresponding index in the mesh kernel. */ void AddPoint(const MeshPoint& rclPt, ElementIndex ulPtIndex, float fEpsilon = 0.0F); /** Returns the grid numbers to the given point \a rclPoint. */ - void Pos(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + void Pos( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; /** Returns the number of stored elements. */ unsigned long HasElements() const override { @@ -373,9 +394,11 @@ public: /** Returns indices of the elements in the current grid. */ void GetElements(std::vector& raulElements) const { - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); } /** Returns the number of elements in the current grid. */ unsigned long GetCtElements() const @@ -416,14 +439,18 @@ public: /** @name Tests with rays */ //@{ /** Searches for facets around the ray. */ - bool InitOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - std::vector& raulElements); + bool InitOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + std::vector& raulElements + ); /** Searches for facets around the ray. */ - bool InitOnRay(const Base::Vector3f& rclPt, - const Base::Vector3f& rclDir, - float fMaxSearchArea, - std::vector& raulElements); + bool InitOnRay( + const Base::Vector3f& rclPt, + const Base::Vector3f& rclDir, + float fMaxSearchArea, + std::vector& raulElements + ); /** Searches for facets around the ray. */ bool NextOnRay(std::vector& raulElements); //@} @@ -478,8 +505,7 @@ private: // -------------------------------------------------------------- -inline Base::BoundBox3f -MeshGrid::GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const +inline Base::BoundBox3f MeshGrid::GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const { float fX = _fMinX + (float(ulX) * _fGridLenX); float fY = _fMinY + (float(ulY) * _fGridLenY); @@ -490,12 +516,14 @@ MeshGrid::GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) c inline Base::BoundBox3f MeshGrid::GetBoundBox() const { - return Base::BoundBox3f(_fMinX, - _fMinY, - _fMinZ, - _fMinX + (_fGridLenX * float(_ulCtGridsX)), - _fMinY + (_fGridLenY * float(_ulCtGridsY)), - _fMinZ + (_fGridLenZ * float(_ulCtGridsZ))); + return Base::BoundBox3f( + _fMinX, + _fMinY, + _fMinZ, + _fMinX + (_fGridLenX * float(_ulCtGridsX)), + _fMinY + (_fGridLenY * float(_ulCtGridsY)), + _fMinZ + (_fGridLenZ * float(_ulCtGridsZ)) + ); } inline Base::BoundBox3f MeshGrid::GetMeshBoundBox() const @@ -513,10 +541,12 @@ inline bool MeshGrid::CheckPos(unsigned long ulX, unsigned long ulY, unsigned lo // -------------------------------------------------------------- -inline void MeshFacetGrid::Pos(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +inline void MeshFacetGrid::Pos( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { rulX = static_cast((rclPoint.x - _fMinX) / _fGridLenX); rulY = static_cast((rclPoint.y - _fMinY) / _fGridLenY); @@ -525,10 +555,12 @@ inline void MeshFacetGrid::Pos(const Base::Vector3f& rclPoint, assert((rulX < _ulCtGridsX) && (rulY < _ulCtGridsY) && (rulZ < _ulCtGridsZ)); } -inline void MeshFacetGrid::PosWithCheck(const Base::Vector3f& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +inline void MeshFacetGrid::PosWithCheck( + const Base::Vector3f& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { if (rclPoint.x < _fMinX) { rulX = 0; @@ -563,9 +595,7 @@ inline void MeshFacetGrid::PosWithCheck(const Base::Vector3f& rclPoint, assert((rulX < _ulCtGridsX) && (rulY < _ulCtGridsY) && (rulZ < _ulCtGridsZ)); } -inline void MeshFacetGrid::AddFacet(const MeshGeomFacet& rclFacet, - ElementIndex ulFacetIndex, - float /*fEpsilon*/) +inline void MeshFacetGrid::AddFacet(const MeshGeomFacet& rclFacet, ElementIndex ulFacetIndex, float /*fEpsilon*/) { unsigned long ulX {}; unsigned long ulY {}; diff --git a/src/Mod/Mesh/App/Core/Helpers.h b/src/Mod/Mesh/App/Core/Helpers.h index 6891badfd1..ae06b19be0 100644 --- a/src/Mod/Mesh/App/Core/Helpers.h +++ b/src/Mod/Mesh/App/Core/Helpers.h @@ -126,16 +126,19 @@ inline bool MeshHelpPoint::operator==(const MeshHelpPoint& rclObj) const return Base::DistanceP2(_clPt, rclObj._clPt) < MeshDefinitions::_fMinPointDistanceP2; } -inline void -MeshPointBuilder::Add(FacetIndex ulCorner, FacetIndex ulFacet, const Base::Vector3f& rclPt) +inline void MeshPointBuilder::Add(FacetIndex ulCorner, FacetIndex ulFacet, const Base::Vector3f& rclPt) { MeshHelpPoint clObj; clObj.Set(ulCorner, ulFacet, rclPt); push_back(clObj); } -inline void -MeshHelpBuilderEdge::Set(PointIndex ulInd1, PointIndex ulInd2, FacetIndex ulSide, FacetIndex ulFInd) +inline void MeshHelpBuilderEdge::Set( + PointIndex ulInd1, + PointIndex ulInd2, + FacetIndex ulSide, + FacetIndex ulFInd +) { if (ulInd1 < ulInd2) { _aulInd[0] = ulInd1; @@ -169,8 +172,7 @@ inline bool MeshHelpBuilderEdge::operator!=(const MeshHelpBuilderEdge& rclObj) c } -inline void -MeshEdgeBuilder::Add(PointIndex ulInd1, PointIndex ulInd2, FacetIndex ulSide, FacetIndex ulFInd) +inline void MeshEdgeBuilder::Add(PointIndex ulInd1, PointIndex ulInd2, FacetIndex ulSide, FacetIndex ulFInd) { MeshHelpBuilderEdge clObj {}; clObj.Set(ulInd1, ulInd2, ulSide, ulFInd); diff --git a/src/Mod/Mesh/App/Core/IO/Reader3MF.cpp b/src/Mod/Mesh/App/Core/IO/Reader3MF.cpp index c182c82d68..cfc805ba11 100644 --- a/src/Mod/Mesh/App/Core/IO/Reader3MF.cpp +++ b/src/Mod/Mesh/App/Core/IO/Reader3MF.cpp @@ -151,8 +151,8 @@ bool Reader3MF::LoadModel(DOMDocument& xmlDocument, const Component& comp) bool Reader3MF::LoadResourcesAndBuild(DOMElement* node, const Component& comp) { - bool resource = - LoadResources(node->getElementsByTagName(XStrLiteral("resources").unicodeForm()), comp); + bool resource + = LoadResources(node->getElementsByTagName(XStrLiteral("resources").unicodeForm()), comp); bool build = LoadBuild(node->getElementsByTagName(XStrLiteral("build").unicodeForm())); return (resource && build); } @@ -167,8 +167,7 @@ bool Reader3MF::LoadResources(DOMNodeList* nodes, const Component& comp) DOMNode* node = nodes->item(i); if (node->getNodeType() == DOMNode::ELEMENT_NODE) { auto elem = static_cast(node); - DOMNodeList* objectList = - elem->getElementsByTagName(XStrLiteral("object").unicodeForm()); + DOMNodeList* objectList = elem->getElementsByTagName(XStrLiteral("object").unicodeForm()); return LoadObject(objectList, comp); } } @@ -225,11 +224,11 @@ void Reader3MF::LoadItem(DOMNamedNodeMap* nodeMap) it->second.second = mat.value(); } - auto jt = std::find_if(components.begin(), - components.end(), - [idValue](const Component& comp) { - return comp.id == idValue; - }); + auto jt = std::find_if( + components.begin(), + components.end(), + [idValue](const Component& comp) { return comp.id == idValue; } + ); if (jt != components.end()) { jt->transform = mat.value(); } @@ -281,19 +280,20 @@ bool Reader3MF::LoadObject(DOMNodeList* nodes, const Component& comp) for (XMLSize_t i = 0; i < nodes->getLength(); i++) { DOMNode* objectNode = nodes->item(i); if (objectNode->getNodeType() == DOMNode::ELEMENT_NODE) { - DOMNode* idAttr = - objectNode->getAttributes()->getNamedItem(XStrLiteral("id").unicodeForm()); + DOMNode* idAttr = objectNode->getAttributes()->getNamedItem( + XStrLiteral("id").unicodeForm() + ); auto elem = static_cast(objectNode); if (idAttr) { int id = std::stoi(StrX(idAttr->getNodeValue()).c_str()); - DOMNodeList* meshNode = - elem->getElementsByTagName(XStrLiteral("mesh").unicodeForm()); + DOMNodeList* meshNode = elem->getElementsByTagName(XStrLiteral("mesh").unicodeForm()); if (meshNode->getLength() > 0) { LoadMesh(meshNode, id, comp); } else { - DOMNodeList* compNode = - elem->getElementsByTagName(XStrLiteral("components").unicodeForm()); + DOMNodeList* compNode = elem->getElementsByTagName( + XStrLiteral("components").unicodeForm() + ); LoadComponents(compNode, id); } } @@ -324,8 +324,7 @@ void Reader3MF::LoadComponents(DOMNodeList* nodes, int id) DOMNode* objectNode = nodes->item(i); if (objectNode->getNodeType() == DOMNode::ELEMENT_NODE) { auto elem = static_cast(objectNode); - DOMNodeList* compNode = - elem->getElementsByTagName(XStrLiteral("component").unicodeForm()); + DOMNodeList* compNode = elem->getElementsByTagName(XStrLiteral("component").unicodeForm()); if (compNode->getLength() > 0) { LoadComponent(compNode, id); } @@ -387,8 +386,7 @@ void Reader3MF::LoadMesh(DOMNodeList* nodes, int id, const Component& comp) MeshPointArray points; MeshFacetArray facets; LoadVertices(elem->getElementsByTagName(XStrLiteral("vertices").unicodeForm()), points); - LoadTriangles(elem->getElementsByTagName(XStrLiteral("triangles").unicodeForm()), - facets); + LoadTriangles(elem->getElementsByTagName(XStrLiteral("triangles").unicodeForm()), facets); MeshCleanup meshCleanup(points, facets); meshCleanup.RemoveInvalids(); @@ -413,8 +411,7 @@ void Reader3MF::LoadVertices(DOMNodeList* nodes, MeshPointArray& points) DOMNode* node = nodes->item(i); if (node->getNodeType() == DOMNode::ELEMENT_NODE) { auto elem = static_cast(node); - DOMNodeList* vertexList = - elem->getElementsByTagName(XStrLiteral("vertex").unicodeForm()); + DOMNodeList* vertexList = elem->getElementsByTagName(XStrLiteral("vertex").unicodeForm()); if (vertexList) { ReadVertices(vertexList, points); } @@ -455,8 +452,9 @@ void Reader3MF::LoadTriangles(DOMNodeList* nodes, MeshFacetArray& facets) DOMNode* node = nodes->item(i); if (node->getNodeType() == DOMNode::ELEMENT_NODE) { auto elem = static_cast(node); - DOMNodeList* triangleList = - elem->getElementsByTagName(XStrLiteral("triangle").unicodeForm()); + DOMNodeList* triangleList = elem->getElementsByTagName( + XStrLiteral("triangle").unicodeForm() + ); if (triangleList) { ReadTriangles(triangleList, facets); } diff --git a/src/Mod/Mesh/App/Core/IO/ReaderPLY.cpp b/src/Mod/Mesh/App/Core/IO/ReaderPLY.cpp index 48e78dee34..6a7e6779dc 100644 --- a/src/Mod/Mesh/App/Core/IO/ReaderPLY.cpp +++ b/src/Mod/Mesh/App/Core/IO/ReaderPLY.cpp @@ -306,23 +306,23 @@ bool ReaderPLY::VerifyVertexProperty() { // check if valid 3d points PropertyComp property; - std::size_t num_x = std::count_if(vertex_props.begin(), - vertex_props.end(), - [&property](const std::pair& prop) { - return property(prop, coord_x); - }); + std::size_t num_x = std::count_if( + vertex_props.begin(), + vertex_props.end(), + [&property](const std::pair& prop) { return property(prop, coord_x); } + ); - std::size_t num_y = std::count_if(vertex_props.begin(), - vertex_props.end(), - [&property](const std::pair& prop) { - return property(prop, coord_y); - }); + std::size_t num_y = std::count_if( + vertex_props.begin(), + vertex_props.end(), + [&property](const std::pair& prop) { return property(prop, coord_y); } + ); - std::size_t num_z = std::count_if(vertex_props.begin(), - vertex_props.end(), - [&property](const std::pair& prop) { - return property(prop, coord_z); - }); + std::size_t num_z = std::count_if( + vertex_props.begin(), + vertex_props.end(), + [&property](const std::pair& prop) { return property(prop, coord_z); } + ); return ((num_x == 1) && (num_y == 1) && (num_z == 1)); } @@ -331,23 +331,23 @@ bool ReaderPLY::VerifyColorProperty() { // check if valid colors are set PropertyComp property; - std::size_t num_r = std::count_if(vertex_props.begin(), - vertex_props.end(), - [&property](const std::pair& prop) { - return property(prop, color_r); - }); + std::size_t num_r = std::count_if( + vertex_props.begin(), + vertex_props.end(), + [&property](const std::pair& prop) { return property(prop, color_r); } + ); - std::size_t num_g = std::count_if(vertex_props.begin(), - vertex_props.end(), - [&property](const std::pair& prop) { - return property(prop, color_g); - }); + std::size_t num_g = std::count_if( + vertex_props.begin(), + vertex_props.end(), + [&property](const std::pair& prop) { return property(prop, color_g); } + ); - std::size_t num_b = std::count_if(vertex_props.begin(), - vertex_props.end(), - [&property](const std::pair& prop) { - return property(prop, color_b); - }); + std::size_t num_b = std::count_if( + vertex_props.begin(), + vertex_props.end(), + [&property](const std::pair& prop) { return property(prop, color_b); } + ); std::size_t rgb_colors = num_r + num_g + num_b; if (rgb_colors != 0 && rgb_colors != 3) { diff --git a/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp b/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp index fefc9aea95..53f6c3c663 100644 --- a/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp +++ b/src/Mod/Mesh/App/Core/IO/WriterInventor.cpp @@ -126,12 +126,12 @@ public: auto transformColors = [](const std::vector& input) { std::vector output; output.reserve(input.size()); - std::transform(input.cbegin(), - input.cend(), - std::back_inserter(output), - [](const Base::Color& col) { - return Base::ColorRGB {col.r, col.g, col.b}; - }); + std::transform( + input.cbegin(), + input.cend(), + std::back_inserter(output), + [](const Base::Color& col) { return Base::ColorRGB {col.r, col.g, col.b}; } + ); return output; }; diff --git a/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp b/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp index 37a24d9045..2db7a4fa5d 100644 --- a/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp +++ b/src/Mod/Mesh/App/Core/IO/WriterOBJ.cpp @@ -84,8 +84,10 @@ bool WriterOBJ::Save(std::ostream& out) if (_material) { if (_material->binding == MeshIO::PER_FACE) { if (_material->diffuseColor.size() != rFacets.size()) { - Base::Console().warning("Cannot export color information because there is a " - "different number of faces and colors"); + Base::Console().warning( + "Cannot export color information because there is a " + "different number of faces and colors" + ); } else { exportColorPerFace = true; @@ -93,8 +95,10 @@ bool WriterOBJ::Save(std::ostream& out) } else if (_material->binding == MeshIO::PER_VERTEX) { if (_material->diffuseColor.size() != rPoints.size()) { - Base::Console().warning("Cannot export color information because there is a " - "different number of points and colors"); + Base::Console().warning( + "Cannot export color information because there is a " + "different number of points and colors" + ); } else { exportColorPerVertex = true; @@ -103,7 +107,8 @@ bool WriterOBJ::Save(std::ostream& out) else if (_material->binding == MeshIO::OVERALL) { if (_material->diffuseColor.empty()) { Base::Console().warning( - "Cannot export color information because there is no color defined"); + "Cannot export color information because there is no color defined" + ); } else { exportColorPerVertex = true; @@ -198,9 +203,8 @@ bool WriterOBJ::Save(std::ostream& out) // facet indices (no texture and normal indices) std::size_t faceIdx = 1; for (const auto& it : rFacets) { - out << "f " << it._aulPoints[0] + 1 << "//" << faceIdx << " " - << it._aulPoints[1] + 1 << "//" << faceIdx << " " << it._aulPoints[2] + 1 - << "//" << faceIdx << '\n'; + out << "f " << it._aulPoints[0] + 1 << "//" << faceIdx << " " << it._aulPoints[1] + 1 + << "//" << faceIdx << " " << it._aulPoints[2] + 1 << "//" << faceIdx << '\n'; seq.next(true); // allow one to cancel faceIdx++; } @@ -229,9 +233,8 @@ bool WriterOBJ::Save(std::ostream& out) } } - out << "f " << f._aulPoints[0] + 1 << "//" << it + 1 << " " - << f._aulPoints[1] + 1 << "//" << it + 1 << " " << f._aulPoints[2] + 1 - << "//" << it + 1 << '\n'; + out << "f " << f._aulPoints[0] + 1 << "//" << it + 1 << " " << f._aulPoints[1] + 1 + << "//" << it + 1 << " " << f._aulPoints[2] + 1 << "//" << it + 1 << '\n'; seq.next(true); // allow one to cancel } } @@ -241,9 +244,8 @@ bool WriterOBJ::Save(std::ostream& out) out << "g " << Base::Tools::escapedUnicodeFromUtf8(gt.name.c_str()) << '\n'; for (FacetIndex it : gt.indices) { const MeshFacet& f = rFacets[it]; - out << "f " << f._aulPoints[0] + 1 << "//" << it + 1 << " " - << f._aulPoints[1] + 1 << "//" << it + 1 << " " << f._aulPoints[2] + 1 - << "//" << it + 1 << '\n'; + out << "f " << f._aulPoints[0] + 1 << "//" << it + 1 << " " << f._aulPoints[1] + 1 + << "//" << it + 1 << " " << f._aulPoints[2] + 1 << "//" << it + 1 << '\n'; seq.next(true); // allow one to cancel } } diff --git a/src/Mod/Mesh/App/Core/Info.cpp b/src/Mod/Mesh/App/Core/Info.cpp index b3659f6501..d4f92475d5 100644 --- a/src/Mod/Mesh/App/Core/Info.cpp +++ b/src/Mod/Mesh/App/Core/Info.cpp @@ -87,10 +87,10 @@ std::ostream& MeshInfo::DetailedEdgeInfo(std::ostream& rclStream) const while (pFIter < rFacets.end()) { const MeshFacet& rFacet = *pFIter; for (int j = 0; j < 3; j++) { - PointIndex ulPt0 = - std::min(rFacet._aulPoints[j], rFacet._aulPoints[(j + 1) % 3]); - PointIndex ulPt1 = - std::max(rFacet._aulPoints[j], rFacet._aulPoints[(j + 1) % 3]); + PointIndex ulPt0 + = std::min(rFacet._aulPoints[j], rFacet._aulPoints[(j + 1) % 3]); + PointIndex ulPt1 + = std::max(rFacet._aulPoints[j], rFacet._aulPoints[(j + 1) % 3]); std::pair cEdge(ulPt0, ulPt1); lEdges[cEdge]++; } diff --git a/src/Mod/Mesh/App/Core/Iterator.h b/src/Mod/Mesh/App/Core/Iterator.h index 5caebd1c2e..89e67b77dd 100644 --- a/src/Mod/Mesh/App/Core/Iterator.h +++ b/src/Mod/Mesh/App/Core/Iterator.h @@ -172,9 +172,11 @@ public: return *_clIter; } /// Returns iterators pointing to the current facet's neighbours. - inline void GetNeighbours(MeshFacetIterator& rclN0, - MeshFacetIterator& rclN1, - MeshFacetIterator& rclN2) const; + inline void GetNeighbours( + MeshFacetIterator& rclN0, + MeshFacetIterator& rclN1, + MeshFacetIterator& rclN2 + ) const; /// Sets the iterator to the current facet's neighbour of the side \a usN. inline void SetToNeighbour(unsigned short usN); /// Returns the property information to the current facet. @@ -505,9 +507,11 @@ inline unsigned long MeshFacetIterator::GetProperty() const return _clIter->_ulProp; } -inline void MeshFacetIterator::GetNeighbours(MeshFacetIterator& rclN0, - MeshFacetIterator& rclN1, - MeshFacetIterator& rclN2) const +inline void MeshFacetIterator::GetNeighbours( + MeshFacetIterator& rclN0, + MeshFacetIterator& rclN1, + MeshFacetIterator& rclN2 +) const { if (_clIter->_aulNeighbours[0] != FACET_INDEX_MAX) { rclN0.Set(_clIter->_aulNeighbours[0]); diff --git a/src/Mod/Mesh/App/Core/KDTree.cpp b/src/Mod/Mesh/App/Core/KDTree.cpp index f185f14fd2..952a78b298 100644 --- a/src/Mod/Mesh/App/Core/KDTree.cpp +++ b/src/Mod/Mesh/App/Core/KDTree.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ #ifdef _MSC_VER -#pragma warning(disable : 4396) +# pragma warning(disable : 4396) #endif #include "KDTree.h" @@ -152,8 +152,9 @@ void MeshKDTree::Optimize() PointIndex MeshKDTree::FindNearest(const Base::Vector3f& p, Base::Vector3f& n, float& dist) const { - std::pair it = - d->kd_tree.find_nearest(Point3d(p, 0)); + std::pair it = d->kd_tree.find_nearest( + Point3d(p, 0) + ); if (it.first == d->kd_tree.end()) { return POINT_INDEX_MAX; } @@ -163,13 +164,15 @@ PointIndex MeshKDTree::FindNearest(const Base::Vector3f& p, Base::Vector3f& n, f return index; } -PointIndex MeshKDTree::FindNearest(const Base::Vector3f& p, - float max_dist, - Base::Vector3f& n, - float& dist) const +PointIndex MeshKDTree::FindNearest( + const Base::Vector3f& p, + float max_dist, + Base::Vector3f& n, + float& dist +) const { - std::pair it = - d->kd_tree.find_nearest(Point3d(p, 0), max_dist); + std::pair it + = d->kd_tree.find_nearest(Point3d(p, 0), max_dist); if (it.first == d->kd_tree.end()) { return POINT_INDEX_MAX; } @@ -189,9 +192,7 @@ PointIndex MeshKDTree::FindExact(const Base::Vector3f& p) const return index; } -void MeshKDTree::FindInRange(const Base::Vector3f& p, - float range, - std::vector& indices) const +void MeshKDTree::FindInRange(const Base::Vector3f& p, float range, std::vector& indices) const { std::vector v; d->kd_tree.find_within_range(Point3d(p, 0), range, std::back_inserter(v)); diff --git a/src/Mod/Mesh/App/Core/KDTree.h b/src/Mod/Mesh/App/Core/KDTree.h index 634124d514..5e1f7596ba 100644 --- a/src/Mod/Mesh/App/Core/KDTree.h +++ b/src/Mod/Mesh/App/Core/KDTree.h @@ -48,8 +48,7 @@ public: void Optimize(); PointIndex FindNearest(const Base::Vector3f& p, Base::Vector3f& n, float&) const; - PointIndex - FindNearest(const Base::Vector3f& p, float max_dist, Base::Vector3f& n, float&) const; + PointIndex FindNearest(const Base::Vector3f& p, float max_dist, Base::Vector3f& n, float&) const; PointIndex FindExact(const Base::Vector3f& p) const; void FindInRange(const Base::Vector3f&, float, std::vector&) const; diff --git a/src/Mod/Mesh/App/Core/MeshIO.cpp b/src/Mod/Mesh/App/Core/MeshIO.cpp index 5973a95376..453047b367 100644 --- a/src/Mod/Mesh/App/Core/MeshIO.cpp +++ b/src/Mod/Mesh/App/Core/MeshIO.cpp @@ -349,8 +349,7 @@ bool MeshInput::LoadSTL(std::istream& input) try { if (!strstr(szBuf, "SOLID") && !strstr(szBuf, "FACET") && !strstr(szBuf, "NORMAL") - && !strstr(szBuf, "VERTEX") && !strstr(szBuf, "ENDFACET") - && !strstr(szBuf, "ENDLOOP")) { + && !strstr(szBuf, "VERTEX") && !strstr(szBuf, "ENDFACET") && !strstr(szBuf, "ENDLOOP")) { // probably binary STL buf->pubseekoff(0, std::ios::beg, std::ios::in); return LoadBinarySTL(input); @@ -415,12 +414,16 @@ bool MeshInput::LoadOBJ(std::istream& input, const char* filename) /** Loads an SMF file. */ bool MeshInput::LoadSMF(std::istream& input) { - boost::regex rx_p("^v\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$"); - boost::regex rx_f3("^f\\s+([-+]?[0-9]+)" - "\\s+([-+]?[0-9]+)" - "\\s+([-+]?[0-9]+)\\s*$"); + boost::regex rx_p( + "^v\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$" + ); + boost::regex rx_f3( + "^f\\s+([-+]?[0-9]+)" + "\\s+([-+]?[0-9]+)" + "\\s+([-+]?[0-9]+)\\s*$" + ); boost::cmatch what; unsigned long segment = 0; @@ -666,9 +669,11 @@ bool MeshInput::LoadPLY(std::istream& input) bool MeshInput::LoadMeshNode(std::istream& input) { - boost::regex rx_p("^v\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$"); + boost::regex rx_p( + "^v\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$" + ); boost::regex rx_f(R"(^f\s+([0-9]+)\s+([0-9]+)\s+([0-9]+)\s*$)"); boost::regex rx_e("\\s*]\\s*"); boost::cmatch what; @@ -723,12 +728,16 @@ bool MeshInput::LoadMeshNode(std::istream& input) /** Loads an ASCII STL file. */ bool MeshInput::LoadAsciiSTL(std::istream& input) { - boost::regex rx_p("^\\s*VERTEX\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$"); - boost::regex rx_f("^\\s*FACET\\s+NORMAL\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$"); + boost::regex rx_p( + "^\\s*VERTEX\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$" + ); + boost::regex rx_f( + "^\\s*FACET\\s+NORMAL\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$" + ); boost::cmatch what; std::string line; @@ -938,21 +947,21 @@ bool MeshInput::LoadInventor(std::istream& input) MeshPointArray meshPoints; meshPoints.reserve(points.size()); - std::transform(points.begin(), - points.end(), - std::back_inserter(meshPoints), - [](const Base::Vector3f& v) { - return MeshPoint(v); - }); + std::transform( + points.begin(), + points.end(), + std::back_inserter(meshPoints), + [](const Base::Vector3f& v) { return MeshPoint(v); } + ); MeshFacetArray meshFacets; meshFacets.reserve(faces.size()); - std::transform(faces.begin(), - faces.end(), - std::back_inserter(meshFacets), - [](const Base::InventorLoader::Face& f) { - return MeshFacet(f.p1, f.p2, f.p3); - }); + std::transform( + faces.begin(), + faces.end(), + std::back_inserter(meshFacets), + [](const Base::InventorLoader::Face& f) { return MeshFacet(f.p1, f.p2, f.p3); } + ); MeshCleanup meshCleanup(meshPoints, meshFacets); meshCleanup.RemoveInvalids(); @@ -976,10 +985,14 @@ bool MeshInput::LoadNastran(std::istream& input) return false; } - boost::regex rx_t("\\s*CTRIA3\\s+([0-9]+)\\s+([0-9]+)" - "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s*"); - boost::regex rx_q("\\s*CQUAD4\\s+([0-9]+)\\s+([0-9]+)" - "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s*"); + boost::regex rx_t( + "\\s*CTRIA3\\s+([0-9]+)\\s+([0-9]+)" + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s*" + ); + boost::regex rx_q( + "\\s*CQUAD4\\s+([0-9]+)\\s+([0-9]+)" + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s*" + ); boost::cmatch what; std::string line; @@ -1049,8 +1062,7 @@ bool MeshInput::LoadNastran(std::istream& input) badElementCounter++; continue; } - index = - indexCheck.get() - 1; // Minus one so we are zero-indexed to match existing code + index = indexCheck.get() - 1; // Minus one so we are zero-indexed to match existing code // Get the high-precision versions first auto x = boost::convert(xString, converter); @@ -1070,10 +1082,12 @@ bool MeshInput::LoadNastran(std::istream& input) } else if (line.rfind("GRID", 0) == 0) { - boost::regex rx_spaceDelimited("\\s*GRID\\s+([0-9]+)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*"); + boost::regex rx_spaceDelimited( + "\\s*GRID\\s+([0-9]+)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*" + ); if (boost::regex_match(line.c_str(), what, rx_spaceDelimited)) { // insert the read-in vertex into a map to preserve the order @@ -1159,7 +1173,8 @@ bool MeshInput::LoadNastran(std::istream& input) for (int i : tri.second.iV) { if (mNode.find(i) == mNode.end()) { Base::Console().error( - "CTRIA3 element refers to a node that does not exist, or could not be read.\n"); + "CTRIA3 element refers to a node that does not exist, or could not be read.\n" + ); return false; } } @@ -1170,7 +1185,8 @@ bool MeshInput::LoadNastran(std::istream& input) for (int i : quad.second.iV) { if (mNode.find(i) == mNode.end()) { Base::Console().error( - "CQUAD4 element refers to a node that does not exist, or could not be read.\n"); + "CQUAD4 element refers to a node that does not exist, or could not be read.\n" + ); return false; } } @@ -1803,10 +1819,12 @@ bool MeshOutput::SaveAsymptote(std::ostream& out) const const MeshPointArray& rPoints = _rclMesh.GetPoints(); const MeshFacetArray& rFacets = _rclMesh.GetFacets(); - bool saveVertexColor = (_material && _material->binding == MeshIO::PER_VERTEX - && _material->diffuseColor.size() == rPoints.size()); - bool saveFaceColor = (_material && _material->binding == MeshIO::PER_FACE - && _material->diffuseColor.size() == rFacets.size()); + bool saveVertexColor + = (_material && _material->binding == MeshIO::PER_VERTEX + && _material->diffuseColor.size() == rPoints.size()); + bool saveFaceColor + = (_material && _material->binding == MeshIO::PER_FACE + && _material->diffuseColor.size() == rFacets.size()); // global mesh color Base::Color mc(0.8F, 0.8F, 0.8F); if (_material && _material->binding == MeshIO::OVERALL && _material->diffuseColor.size() == 1) { @@ -1869,13 +1887,14 @@ bool MeshOutput::SaveOFF(std::ostream& out) const bool exportColor = false; if (_material) { if (_material->binding == MeshIO::PER_FACE) { - Base::Console().warning( - "Cannot export color information because it's defined per face"); + Base::Console().warning("Cannot export color information because it's defined per face"); } else if (_material->binding == MeshIO::PER_VERTEX) { if (_material->diffuseColor.size() != rPoints.size()) { - Base::Console().warning("Cannot export color information because there is a " - "different number of points and colors"); + Base::Console().warning( + "Cannot export color information because there is a " + "different number of points and colors" + ); } else { exportColor = true; @@ -1884,7 +1903,8 @@ bool MeshOutput::SaveOFF(std::ostream& out) const else if (_material->binding == MeshIO::OVERALL) { if (_material->diffuseColor.empty()) { Base::Console().warning( - "Cannot export color information because there is no color defined"); + "Cannot export color information because there is no color defined" + ); } else { exportColor = true; @@ -1936,8 +1956,7 @@ bool MeshOutput::SaveOFF(std::ostream& out) const // facet indices (no texture and normal indices) for (const auto& it : rFacets) { - out << "3 " << it._aulPoints[0] << " " << it._aulPoints[1] << " " << it._aulPoints[2] - << '\n'; + out << "3 " << it._aulPoints[0] << " " << it._aulPoints[1] << " " << it._aulPoints[2] << '\n'; seq.next(true); // allow one to cancel } @@ -1953,8 +1972,9 @@ bool MeshOutput::SaveBinaryPLY(std::ostream& out) const if (!out || out.bad()) { return false; } - bool saveVertexColor = (_material && _material->binding == MeshIO::PER_VERTEX - && _material->diffuseColor.size() == rPoints.size()); + bool saveVertexColor + = (_material && _material->binding == MeshIO::PER_VERTEX + && _material->diffuseColor.size() == rPoints.size()); out << "ply\n" << "format binary_little_endian 1.0\n" << "comment Created by FreeCAD \n" @@ -2015,8 +2035,9 @@ bool MeshOutput::SaveAsciiPLY(std::ostream& out) const return false; } - bool saveVertexColor = (_material && _material->binding == MeshIO::PER_VERTEX - && _material->diffuseColor.size() == rPoints.size()); + bool saveVertexColor + = (_material && _material->binding == MeshIO::PER_VERTEX + && _material->diffuseColor.size() == rPoints.size()); out << "ply\n" << "format ascii 1.0\n" << "comment Created by FreeCAD \n" @@ -2121,8 +2142,7 @@ void MeshOutput::SaveXML(Base::Writer& writer) const // writer << writer.ind() << "" << '\n'; writer.incInd(); - writer.Stream() << writer.ind() << "" - << '\n'; + writer.Stream() << writer.ind() << "" << '\n'; writer.incInd(); if (this->apply_transform) { @@ -2365,10 +2385,12 @@ bool MeshOutput::SaveX3DContent(std::ostream& out, bool exportViewpoints) const mat = _material->diffuseColor.front(); } } - bool saveVertexColor = (_material && _material->binding == MeshIO::PER_VERTEX - && _material->diffuseColor.size() == pts.size()); - bool saveFaceColor = (_material && _material->binding == MeshIO::PER_FACE - && _material->diffuseColor.size() == fts.size()); + bool saveVertexColor + = (_material && _material->binding == MeshIO::PER_VERTEX + && _material->diffuseColor.size() == pts.size()); + bool saveFaceColor + = (_material && _material->binding == MeshIO::PER_FACE + && _material->diffuseColor.size() == fts.size()); Base::SequencerLauncher seq("Saving...", _rclMesh.CountFacets() + 1); out.precision(6); @@ -2389,11 +2411,13 @@ bool MeshOutput::SaveX3DContent(std::ostream& out, bool exportViewpoints) const out << " \n"; if (exportViewpoints) { - auto viewpoint = [&out](const char* text, - const Base::Vector3f& cnt, - const Base::Vector3f& pos, - const Base::Vector3f& axis, - float angle) { + auto viewpoint = [&out]( + const char* text, + const Base::Vector3f& cnt, + const Base::Vector3f& pos, + const Base::Vector3f& axis, + float angle + ) { out << " flag; - std::size_t countInvalidFacets = - std::count_if(facetArray.begin(), facetArray.end(), [flag](const MeshFacet& f) { - return flag(f, MeshFacet::INVALID); - }); + std::size_t countInvalidFacets + = std::count_if(facetArray.begin(), facetArray.end(), [flag](const MeshFacet& f) { + return flag(f, MeshFacet::INVALID); + }); if (countInvalidFacets > 0) { // adjust the material array if needed @@ -2841,12 +2878,12 @@ void MeshCleanup::RemoveInvalidFacets() MeshFacetArray copy_facets(facetArray.size() - countInvalidFacets); // copy all valid facets to the new array - std::remove_copy_if(facetArray.begin(), - facetArray.end(), - copy_facets.begin(), - [flag](const MeshFacet& f) { - return flag(f, MeshFacet::INVALID); - }); + std::remove_copy_if( + facetArray.begin(), + facetArray.end(), + copy_facets.begin(), + [flag](const MeshFacet& f) { return flag(f, MeshFacet::INVALID); } + ); facetArray.swap(copy_facets); } } @@ -2854,10 +2891,10 @@ void MeshCleanup::RemoveInvalidFacets() void MeshCleanup::RemoveInvalidPoints() { MeshIsFlag flag; - std::size_t countInvalidPoints = - std::count_if(pointArray.begin(), pointArray.end(), [flag](const MeshPoint& p) { - return flag(p, MeshPoint::INVALID); - }); + std::size_t countInvalidPoints + = std::count_if(pointArray.begin(), pointArray.end(), [flag](const MeshPoint& p) { + return flag(p, MeshPoint::INVALID); + }); if (countInvalidPoints > 0) { // generate array of decrements std::vector decrements; @@ -2900,12 +2937,12 @@ void MeshCleanup::RemoveInvalidPoints() MeshPointArray copy_points(validPoints); // copy all valid facets to the new array - std::remove_copy_if(pointArray.begin(), - pointArray.end(), - copy_points.begin(), - [flag](const MeshPoint& p) { - return flag(p, MeshPoint::INVALID); - }); + std::remove_copy_if( + pointArray.begin(), + pointArray.end(), + copy_points.begin(), + [flag](const MeshPoint& p) { return flag(p, MeshPoint::INVALID); } + ); pointArray.swap(copy_points); } } diff --git a/src/Mod/Mesh/App/Core/MeshKernel.cpp b/src/Mod/Mesh/App/Core/MeshKernel.cpp index fa91102587..9971287db3 100644 --- a/src/Mod/Mesh/App/Core/MeshKernel.cpp +++ b/src/Mod/Mesh/App/Core/MeshKernel.cpp @@ -97,9 +97,7 @@ MeshKernel& MeshKernel::operator=(const std::vector& rclFAry) return *this; } -void MeshKernel::Assign(const MeshPointArray& rPoints, - const MeshFacetArray& rFacets, - bool checkNeighbourHood) +void MeshKernel::Assign(const MeshPointArray& rPoints, const MeshFacetArray& rFacets, bool checkNeighbourHood) { _aclPointArray = rPoints; _aclFacetArray = rFacets; @@ -276,10 +274,9 @@ unsigned long MeshKernel::AddFacets(const std::vector& rclFAry, bool // Do not insert directly to the data structure because we should get the correct size of new // facets, otherwise std::vector reallocates too much memory which can't be freed so easily MeshIsNotFlag flag; - FacetIndex countValid = - std::count_if(rclFAry.begin(), rclFAry.end(), [flag](const MeshFacet& f) { - return flag(f, MeshFacet::INVALID); - }); + FacetIndex countValid = std::count_if(rclFAry.begin(), rclFAry.end(), [flag](const MeshFacet& f) { + return flag(f, MeshFacet::INVALID); + }); _aclFacetArray.reserve(_aclFacetArray.size() + countValid); // now start inserting the facets to the data structure and set the correct neighbourhood as // well @@ -358,9 +355,11 @@ unsigned long MeshKernel::AddFacets(const std::vector& rclFAry, bool return _aclFacetArray.size(); } -unsigned long MeshKernel::AddFacets(const std::vector& rclFAry, - const std::vector& rclPAry, - bool checkManifolds) +unsigned long MeshKernel::AddFacets( + const std::vector& rclFAry, + const std::vector& rclPAry, + bool checkManifolds +) { for (auto it : rclPAry) { _clBoundBox.Add(it); @@ -401,10 +400,8 @@ void MeshKernel::Merge(const MeshPointArray& rPoints, const MeshFacetArray& rFac this->_aclFacetArray.push_back(face); } - std::size_t countNewPoints = - std::count_if(increments.begin(), increments.end(), [](PointIndex v) { - return v > 0; - }); + std::size_t countNewPoints + = std::count_if(increments.begin(), increments.end(), [](PointIndex v) { return v > 0; }); // Reserve the additional memory to append the new points PointIndex index = this->_aclPointArray.size(); this->_aclPointArray.reserve(this->_aclPointArray.size() + countNewPoints); @@ -697,10 +694,10 @@ void MeshKernel::RemoveInvalids() } // delete point, number of valid points - unsigned long ulNewPts = - std::count_if(_aclPointArray.begin(), _aclPointArray.end(), [](const MeshPoint& p) { - return p.IsValid(); - }); + unsigned long ulNewPts + = std::count_if(_aclPointArray.begin(), _aclPointArray.end(), [](const MeshPoint& p) { + return p.IsValid(); + }); // tmp. point array MeshPointArray aclTempPt(ulNewPts); MeshPointArray::_TIterator pPTemp = aclTempPt.begin(); @@ -748,10 +745,10 @@ void MeshKernel::RemoveInvalids() } // delete facets, number of valid facets - unsigned long ulDelFacets = - std::count_if(_aclFacetArray.begin(), _aclFacetArray.end(), [](const MeshFacet& f) { - return f.IsValid(); - }); + unsigned long ulDelFacets + = std::count_if(_aclFacetArray.begin(), _aclFacetArray.end(), [](const MeshFacet& f) { + return f.IsValid(); + }); MeshFacetArray aclFArray(ulDelFacets); MeshFacetArray::_TIterator pFTemp = aclFArray.begin(); pFEnd = _aclFacetArray.end(); @@ -766,11 +763,13 @@ void MeshKernel::RemoveInvalids() _aclFacetArray.swap(aclFArray); } -void MeshKernel::CutFacets(const MeshFacetGrid& rclGrid, - const Base::ViewProjMethod* pclProj, - const Base::Polygon2d& rclPoly, - bool bCutInner, - std::vector& raclFacets) +void MeshKernel::CutFacets( + const MeshFacetGrid& rclGrid, + const Base::ViewProjMethod* pclProj, + const Base::Polygon2d& rclPoly, + bool bCutInner, + std::vector& raclFacets +) { std::vector aulFacets; @@ -783,11 +782,13 @@ void MeshKernel::CutFacets(const MeshFacetGrid& rclGrid, DeleteFacets(aulFacets); } -void MeshKernel::CutFacets(const MeshFacetGrid& grid, - const Base::ViewProjMethod* proj, - const Base::Polygon2d& poly, - bool bInner, - std::vector& cut) +void MeshKernel::CutFacets( + const MeshFacetGrid& grid, + const Base::ViewProjMethod* proj, + const Base::Polygon2d& poly, + bool bInner, + std::vector& cut +) { MeshAlgorithm(*this).CheckFacets(grid, proj, poly, bInner, cut); DeleteFacets(cut); @@ -888,11 +889,13 @@ void MeshKernel::Write(std::ostream& rclOut) const str << static_cast(0x010000); char szInfo[257]; // needs an additional byte for zero-termination - strcpy(szInfo, - "MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-" - "MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-" - "MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-" - "MESH-MESH-MESH-\n"); + strcpy( + szInfo, + "MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-" + "MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-" + "MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-MESH-" + "MESH-MESH-MESH-\n" + ); rclOut.write(szInfo, 256); // write the number of points and facets @@ -1216,8 +1219,9 @@ float MeshKernel::GetVolume() const p2 = rclF._aclPoints[1]; p3 = rclF._aclPoints[2]; - fVolume += (-p3.x * p2.y * p1.z + p2.x * p3.y * p1.z + p3.x * p1.y * p2.z - - p1.x * p3.y * p2.z - p2.x * p1.y * p3.z + p1.x * p2.y * p3.z); + fVolume + += (-p3.x * p2.y * p1.z + p2.x * p3.y * p1.z + p3.x * p1.y * p2.z - p1.x * p3.y * p2.z + - p2.x * p1.y * p3.z + p1.x * p2.y * p3.z); } fVolume /= 6.0F; @@ -1265,9 +1269,9 @@ void MeshKernel::GetEdges(std::vector& edges) const for (const auto& it : _aclFacetArray) { for (int i = 0; i < 3; i++) { - tmp.insert(MeshBuilder::Edge(it._aulPoints[i], - it._aulPoints[(i + 1) % 3], - it._aulNeighbours[i])); + tmp.insert( + MeshBuilder::Edge(it._aulPoints[i], it._aulPoints[(i + 1) % 3], it._aulNeighbours[i]) + ); } } diff --git a/src/Mod/Mesh/App/Core/MeshKernel.h b/src/Mod/Mesh/App/Core/MeshKernel.h index 6ef29b161a..500a7d0ee8 100644 --- a/src/Mod/Mesh/App/Core/MeshKernel.h +++ b/src/Mod/Mesh/App/Core/MeshKernel.h @@ -101,8 +101,9 @@ public: /// Returns the number of required memory in bytes unsigned int GetMemSize() const { - return static_cast(_aclPointArray.size() * sizeof(MeshPoint) - + _aclFacetArray.size() * sizeof(MeshFacet)); + return static_cast( + _aclPointArray.size() * sizeof(MeshPoint) + _aclFacetArray.size() * sizeof(MeshFacet) + ); } /// Determines the bounding box const Base::BoundBox3f& GetBoundBox() const @@ -135,22 +136,25 @@ public: inline MeshGeomFacet GetFacet(const MeshFacet& rclFacet) const; /** Returns the point indices of the given facet index. */ - inline void GetFacetPoints(FacetIndex ulFaIndex, - PointIndex& rclP0, - PointIndex& rclP1, - PointIndex& rclP2) const; + inline void GetFacetPoints( + FacetIndex ulFaIndex, + PointIndex& rclP0, + PointIndex& rclP1, + PointIndex& rclP2 + ) const; /** Returns the point indices of the given facet index. */ - inline void - SetFacetPoints(FacetIndex ulFaIndex, PointIndex rclP0, PointIndex rclP1, PointIndex rclP2); + inline void SetFacetPoints(FacetIndex ulFaIndex, PointIndex rclP0, PointIndex rclP1, PointIndex rclP2); /** Returns the point indices of the given facet indices. */ std::vector GetFacetPoints(const std::vector&) const; /** Returns the facet indices that share the given point indices. */ std::vector GetPointFacets(const std::vector&) const; /** Returns the indices of the neighbour facets of the given facet index. */ - inline void GetFacetNeighbours(FacetIndex ulIndex, - FacetIndex& rulNIdx0, - FacetIndex& rulNIdx1, - FacetIndex& rulNIdx2) const; + inline void GetFacetNeighbours( + FacetIndex ulIndex, + FacetIndex& rulNIdx0, + FacetIndex& rulNIdx1, + FacetIndex& rulNIdx2 + ) const; /** Determines all facets that are associated to this point. This method is very * slow and should be called occasionally only. @@ -244,14 +248,15 @@ public: * \note For the start facet \a ulStartFacet MeshFacetVisitor::Visit() does not get invoked * though the facet gets marked as VISIT. */ - unsigned long VisitNeighbourFacets(MeshFacetVisitor& rclFVisitor, - FacetIndex ulStartFacet) const; + unsigned long VisitNeighbourFacets(MeshFacetVisitor& rclFVisitor, FacetIndex ulStartFacet) const; /** * Does basically the same as the method above unless the facets that share just a common point * are regared as neighbours. */ - unsigned long VisitNeighbourFacetsOverCorners(MeshFacetVisitor& rclFVisitor, - FacetIndex ulStartFacet) const; + unsigned long VisitNeighbourFacetsOverCorners( + MeshFacetVisitor& rclFVisitor, + FacetIndex ulStartFacet + ) const; //@} /** @name Point visitors @@ -272,8 +277,7 @@ public: * ulStartPoint MeshPointVisitor::Visit() does not get invoked though the point gets marked as * VISIT. */ - unsigned long VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, - PointIndex ulStartPoint) const; + unsigned long VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, PointIndex ulStartPoint) const; //@} /** @name Iterators @@ -342,9 +346,11 @@ public: * that facets of \a rclFAry can also reference point indices of the internal point array. * @note This method is quite expensive and should be rarely used. */ - unsigned long AddFacets(const std::vector& rclFAry, - const std::vector& rclPAry, - bool checkManifolds); + unsigned long AddFacets( + const std::vector& rclFAry, + const std::vector& rclPAry, + bool checkManifolds + ); /** * Adds all facets and referenced points to the underlying mesh structure. The client programmer * must be sure that both meshes don't have geometric overlaps, otherwise the resulting mesh @@ -419,9 +425,11 @@ public: * point indices are correctly set but the neighbourhood gets checked and corrected if \a * checkNeighbourHood is true. */ - void Assign(const MeshPointArray& rPoints, - const MeshFacetArray& rFacets, - bool checkNeighbourHood = false); + void Assign( + const MeshPointArray& rPoints, + const MeshFacetArray& rFacets, + bool checkNeighbourHood = false + ); /** This method does basically the same as Assign() unless that it swaps the content of both * arrays. These arrays may be empty after assigning to the kernel. This method is a convenient * way to build up the mesh structure from outside and assign to a mesh kernel without copying @@ -449,20 +457,24 @@ public: * structure. The facets to be deleted are returned with their geometric representation. * @see CheckFacets(). */ - void CutFacets(const MeshFacetGrid& rclGrid, - const Base::ViewProjMethod* pclP, - const Base::Polygon2d& rclPoly, - bool bCutInner, - std::vector& raclFacets); + void CutFacets( + const MeshFacetGrid& rclGrid, + const Base::ViewProjMethod* pclP, + const Base::Polygon2d& rclPoly, + bool bCutInner, + std::vector& raclFacets + ); /** * Does basically the same as method above unless that the facets to be deleted are returned * with their index number in the facet array of the mesh structure. */ - void CutFacets(const MeshFacetGrid& grid, - const Base::ViewProjMethod* proj, - const Base::Polygon2d& poly, - bool bInner, - std::vector& cut); + void CutFacets( + const MeshFacetGrid& grid, + const Base::ViewProjMethod* proj, + const Base::Polygon2d& poly, + bool bInner, + std::vector& cut + ); //@} protected: @@ -538,10 +550,12 @@ inline MeshGeomFacet MeshKernel::GetFacet(const MeshFacet& rclFacet) const return clFacet; } -inline void MeshKernel::GetFacetNeighbours(FacetIndex ulIndex, - FacetIndex& rulNIdx0, - FacetIndex& rulNIdx1, - FacetIndex& rulNIdx2) const +inline void MeshKernel::GetFacetNeighbours( + FacetIndex ulIndex, + FacetIndex& rulNIdx0, + FacetIndex& rulNIdx1, + FacetIndex& rulNIdx2 +) const { assert(ulIndex < _aclFacetArray.size()); @@ -567,8 +581,8 @@ inline void MeshKernel::SetPoint(PointIndex ulPtIndex, float x, float y, float z inline void MeshKernel::AdjustNormal(MeshFacet& rclFacet, const Base::Vector3f& rclNormal) { - Base::Vector3f clN = - (_aclPointArray[rclFacet._aulPoints[1]] - _aclPointArray[rclFacet._aulPoints[0]]) + Base::Vector3f clN = (_aclPointArray[rclFacet._aulPoints[1]] + - _aclPointArray[rclFacet._aulPoints[0]]) % (_aclPointArray[rclFacet._aulPoints[2]] - _aclPointArray[rclFacet._aulPoints[0]]); if ((clN * rclNormal) < 0.0F) { rclFacet.FlipNormal(); @@ -577,8 +591,8 @@ inline void MeshKernel::AdjustNormal(MeshFacet& rclFacet, const Base::Vector3f& inline Base::Vector3f MeshKernel::GetNormal(const MeshFacet& rclFacet) const { - Base::Vector3f clN = - (_aclPointArray[rclFacet._aulPoints[1]] - _aclPointArray[rclFacet._aulPoints[0]]) + Base::Vector3f clN = (_aclPointArray[rclFacet._aulPoints[1]] + - _aclPointArray[rclFacet._aulPoints[0]]) % (_aclPointArray[rclFacet._aulPoints[2]] - _aclPointArray[rclFacet._aulPoints[0]]); clN.Normalize(); return clN; @@ -589,15 +603,19 @@ inline Base::Vector3f MeshKernel::GetGravityPoint(const MeshFacet& rclFacet) con const Base::Vector3f& p0 = _aclPointArray[rclFacet._aulPoints[0]]; const Base::Vector3f& p1 = _aclPointArray[rclFacet._aulPoints[1]]; const Base::Vector3f& p2 = _aclPointArray[rclFacet._aulPoints[2]]; - return Base::Vector3f((p0.x + p1.x + p2.x) / 3.0F, - (p0.y + p1.y + p2.y) / 3.0F, - (p0.z + p1.z + p2.z) / 3.0F); + return Base::Vector3f( + (p0.x + p1.x + p2.x) / 3.0F, + (p0.y + p1.y + p2.y) / 3.0F, + (p0.z + p1.z + p2.z) / 3.0F + ); } -inline void MeshKernel::GetFacetPoints(FacetIndex ulFaIndex, - PointIndex& rclP0, - PointIndex& rclP1, - PointIndex& rclP2) const +inline void MeshKernel::GetFacetPoints( + FacetIndex ulFaIndex, + PointIndex& rclP0, + PointIndex& rclP1, + PointIndex& rclP2 +) const { assert(ulFaIndex < _aclFacetArray.size()); const MeshFacet& rclFacet = _aclFacetArray[ulFaIndex]; @@ -606,10 +624,12 @@ inline void MeshKernel::GetFacetPoints(FacetIndex ulFaIndex, rclP2 = rclFacet._aulPoints[2]; } -inline void MeshKernel::SetFacetPoints(FacetIndex ulFaIndex, - PointIndex rclP0, - PointIndex rclP1, - PointIndex rclP2) +inline void MeshKernel::SetFacetPoints( + FacetIndex ulFaIndex, + PointIndex rclP0, + PointIndex rclP1, + PointIndex rclP2 +) { assert(ulFaIndex < _aclFacetArray.size()); MeshFacet& rclFacet = _aclFacetArray[ulFaIndex]; diff --git a/src/Mod/Mesh/App/Core/Projection.cpp b/src/Mod/Mesh/App/Core/Projection.cpp index 3b060ab608..a09b07512b 100644 --- a/src/Mod/Mesh/App/Core/Projection.cpp +++ b/src/Mod/Mesh/App/Core/Projection.cpp @@ -42,10 +42,12 @@ MeshProjection::MeshProjection(const MeshKernel& mesh) : kernel(mesh) {} -bool MeshProjection::bboxInsideRectangle(const Base::BoundBox3f& bbox, - const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& view) const +bool MeshProjection::bboxInsideRectangle( + const Base::BoundBox3f& bbox, + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& view +) const { Base::Vector3f dir(p2 - p1); Base::Vector3f base(p1), normal(view % dir); @@ -62,9 +64,11 @@ bool MeshProjection::bboxInsideRectangle(const Base::BoundBox3f& bbox, return false; } -bool MeshProjection::isPointInsideDistance(const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& pt) const +bool MeshProjection::isPointInsideDistance( + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& pt +) const { // project point on line Base::Vector3f proj, dir(p2 - p1); @@ -74,10 +78,12 @@ bool MeshProjection::isPointInsideDistance(const Base::Vector3f& p1, return (((p1 - proj) * (p2 - proj)) < 0.0F); } -bool MeshProjection::connectLines(std::list>& cutLines, - const Base::Vector3f& startPoint, - const Base::Vector3f& endPoint, - std::vector& polyline) const +bool MeshProjection::connectLines( + std::list>& cutLines, + const Base::Vector3f& startPoint, + const Base::Vector3f& endPoint, + std::vector& polyline +) const { const float fMaxDist = std::sqrt(std::numeric_limits::max()); // max. length of a gap const float fMinEps = 1.0e-4F; @@ -132,13 +138,15 @@ bool MeshProjection::connectLines(std::list& polyline) +bool MeshProjection::projectLineOnMesh( + const MeshFacetGrid& grid, + const Base::Vector3f& v1, + FacetIndex f1, + const Base::Vector3f& v2, + FacetIndex f2, + const Base::Vector3f& vd, + std::vector& polyline +) { Base::Vector3f dir(v2 - v1); Base::Vector3f base(v1), normal(vd % dir); diff --git a/src/Mod/Mesh/App/Core/Projection.h b/src/Mod/Mesh/App/Core/Projection.h index 21f85682ec..47e8a2fb12 100644 --- a/src/Mod/Mesh/App/Core/Projection.h +++ b/src/Mod/Mesh/App/Core/Projection.h @@ -50,26 +50,34 @@ class MeshExport MeshProjection public: explicit MeshProjection(const MeshKernel&); - bool projectLineOnMesh(const MeshFacetGrid& grid, - const Base::Vector3f& p1, - FacetIndex f1, - const Base::Vector3f& p2, - FacetIndex f2, - const Base::Vector3f& view, - std::vector& polyline); + bool projectLineOnMesh( + const MeshFacetGrid& grid, + const Base::Vector3f& p1, + FacetIndex f1, + const Base::Vector3f& p2, + FacetIndex f2, + const Base::Vector3f& view, + std::vector& polyline + ); protected: - bool bboxInsideRectangle(const Base::BoundBox3f& bbox, - const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& view) const; - bool isPointInsideDistance(const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& pt) const; - bool connectLines(std::list>& cutLines, - const Base::Vector3f& startPoint, - const Base::Vector3f& endPoint, - std::vector& polyline) const; + bool bboxInsideRectangle( + const Base::BoundBox3f& bbox, + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& view + ) const; + bool isPointInsideDistance( + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& pt + ) const; + bool connectLines( + std::list>& cutLines, + const Base::Vector3f& startPoint, + const Base::Vector3f& endPoint, + std::vector& polyline + ) const; private: const MeshKernel& kernel; diff --git a/src/Mod/Mesh/App/Core/Segmentation.cpp b/src/Mod/Mesh/App/Core/Segmentation.cpp index 844e32289e..0e2ab903c3 100644 --- a/src/Mod/Mesh/App/Core/Segmentation.cpp +++ b/src/Mod/Mesh/App/Core/Segmentation.cpp @@ -63,9 +63,11 @@ MeshSegment MeshSurfaceSegment::FindSegment(FacetIndex index) const // -------------------------------------------------------- -MeshDistancePlanarSegment::MeshDistancePlanarSegment(const MeshKernel& mesh, - unsigned long minFacets, - float tol) +MeshDistancePlanarSegment::MeshDistancePlanarSegment( + const MeshKernel& mesh, + unsigned long minFacets, + float tol +) : MeshDistanceSurfaceSegment(mesh, minFacets, tol) , fitter(new PlaneFit) {} @@ -399,10 +401,12 @@ std::vector SphereSurfaceFit::Parameters() const // -------------------------------------------------------- -MeshDistanceGenericSurfaceFitSegment::MeshDistanceGenericSurfaceFitSegment(AbstractSurfaceFit* fit, - const MeshKernel& mesh, - unsigned long minFacets, - float tol) +MeshDistanceGenericSurfaceFitSegment::MeshDistanceGenericSurfaceFitSegment( + AbstractSurfaceFit* fit, + const MeshKernel& mesh, + unsigned long minFacets, + float tol +) : MeshDistanceSurfaceSegment(mesh, minFacets, tol) , fitter(fit) {} @@ -532,19 +536,18 @@ MeshSurfaceVisitor::MeshSurfaceVisitor(MeshSurfaceSegment& segm, std::vector& ci, - unsigned long minFacets, - float tol) + MeshCurvaturePlanarSegment(const std::vector& ci, unsigned long minFacets, float tol) : MeshCurvatureSurfaceSegment(ci, minFacets) , tolerance(tol) {} @@ -299,11 +299,13 @@ private: class MeshExport MeshCurvatureCylindricalSegment: public MeshCurvatureSurfaceSegment { public: - MeshCurvatureCylindricalSegment(const std::vector& ci, - unsigned long minFacets, - float tolMin, - float tolMax, - float curv) + MeshCurvatureCylindricalSegment( + const std::vector& ci, + unsigned long minFacets, + float tolMin, + float tolMax, + float curv + ) : MeshCurvatureSurfaceSegment(ci, minFacets) , curvature(curv) , toleranceMin(tolMin) @@ -324,10 +326,12 @@ private: class MeshExport MeshCurvatureSphericalSegment: public MeshCurvatureSurfaceSegment { public: - MeshCurvatureSphericalSegment(const std::vector& ci, - unsigned long minFacets, - float tol, - float curv) + MeshCurvatureSphericalSegment( + const std::vector& ci, + unsigned long minFacets, + float tol, + float curv + ) : MeshCurvatureSurfaceSegment(ci, minFacets) , curvature(curv) , tolerance(tol) @@ -346,12 +350,14 @@ private: class MeshExport MeshCurvatureFreeformSegment: public MeshCurvatureSurfaceSegment { public: - MeshCurvatureFreeformSegment(const std::vector& ci, - unsigned long minFacets, - float tolMin, - float tolMax, - float c1, - float c2) + MeshCurvatureFreeformSegment( + const std::vector& ci, + unsigned long minFacets, + float tolMin, + float tolMax, + float c1, + float c2 + ) : MeshCurvatureSurfaceSegment(ci, minFacets) , c1(c1) , c2(c2) @@ -374,11 +380,13 @@ class MeshExport MeshSurfaceVisitor: public MeshFacetVisitor { public: MeshSurfaceVisitor(MeshSurfaceSegment& segm, std::vector& indices); - bool AllowVisit(const MeshFacet& face, - const MeshFacet&, - FacetIndex, - unsigned long, - unsigned short neighbourIndex) override; + bool AllowVisit( + const MeshFacet& face, + const MeshFacet&, + FacetIndex, + unsigned long, + unsigned short neighbourIndex + ) override; bool Visit(const MeshFacet& face, const MeshFacet&, FacetIndex ulFInd, unsigned long) override; private: diff --git a/src/Mod/Mesh/App/Core/SetOperations.cpp b/src/Mod/Mesh/App/Core/SetOperations.cpp index 9dfb92aa18..3f71d11c53 100644 --- a/src/Mod/Mesh/App/Core/SetOperations.cpp +++ b/src/Mod/Mesh/App/Core/SetOperations.cpp @@ -45,11 +45,13 @@ using namespace Base; using namespace MeshCore; -SetOperations::SetOperations(const MeshKernel& cutMesh1, - const MeshKernel& cutMesh2, - MeshKernel& result, - OperationType opType, - float minDistanceToPoint) +SetOperations::SetOperations( + const MeshKernel& cutMesh1, + const MeshKernel& cutMesh2, + MeshKernel& result, + OperationType opType, + float minDistanceToPoint +) : _cutMesh0(cutMesh1) , _cutMesh1(cutMesh2) , _resultMesh(result) @@ -171,8 +173,7 @@ void SetOperations::Do() MeshDefinitions::SetMinPointDistance(saveMinMeshDistance); } -void SetOperations::Cut(std::set& facetsCuttingEdge0, - std::set& facetsCuttingEdge1) +void SetOperations::Cut(std::set& facetsCuttingEdge0, std::set& facetsCuttingEdge1) { MeshFacetGrid grid1(_cutMesh0, 20); MeshFacetGrid grid2(_cutMesh1, 20); @@ -248,10 +249,10 @@ void SetOperations::Cut(std::set& facetsCuttingEdge0, _cutPoints.insert(mp0); _cutPoints.insert(mp1); - std::pair::iterator, bool> pit0 = - _cutPoints.insert(mp0); - std::pair::iterator, bool> pit1 = - _cutPoints.insert(mp1); + std::pair::iterator, bool> pit0 + = _cutPoints.insert(mp0); + std::pair::iterator, bool> pit1 + = _cutPoints.insert(mp1); _edges[Edge(mp0, mp1)] = EdgeInfo(); @@ -261,8 +262,8 @@ void SetOperations::Cut(std::set& facetsCuttingEdge0, _facet2points[1][fidx2].push_back(pit1.first); } else { - std::pair::iterator, bool> pit = - _cutPoints.insert(mp0); + std::pair::iterator, bool> pit + = _cutPoints.insert(mp0); // do not insert a facet when only one corner point cuts the // edge if (!((mp0 == f1._aclPoints[0]) || (mp0 == @@ -347,9 +348,11 @@ void SetOperations::TriangulateMesh(const MeshKernel& cutMesh, int side) continue; } - MeshGeomFacet facet(points[it._aulPoints[0]], - points[it._aulPoints[1]], - points[it._aulPoints[2]]); + MeshGeomFacet facet( + points[it._aulPoints[0]], + points[it._aulPoints[1]], + points[it._aulPoints[2]] + ); // if (side == 1) // _builder.addSingleTriangle(facet._aclPoints[0], facet._aclPoints[1], @@ -360,15 +363,18 @@ void SetOperations::TriangulateMesh(const MeshKernel& cutMesh, int side) // continue; // } - float dist0 = - facet._aclPoints[0].DistanceToLine(facet._aclPoints[1], - facet._aclPoints[1] - facet._aclPoints[2]); - float dist1 = - facet._aclPoints[1].DistanceToLine(facet._aclPoints[0], - facet._aclPoints[0] - facet._aclPoints[2]); - float dist2 = - facet._aclPoints[2].DistanceToLine(facet._aclPoints[0], - facet._aclPoints[0] - facet._aclPoints[1]); + float dist0 = facet._aclPoints[0].DistanceToLine( + facet._aclPoints[1], + facet._aclPoints[1] - facet._aclPoints[2] + ); + float dist1 = facet._aclPoints[1].DistanceToLine( + facet._aclPoints[0], + facet._aclPoints[0] - facet._aclPoints[2] + ); + float dist2 = facet._aclPoints[2].DistanceToLine( + facet._aclPoints[0], + facet._aclPoints[0] - facet._aclPoints[1] + ); if ((dist0 < _minDistanceToPoint) || (dist1 < _minDistanceToPoint) || (dist2 < _minDistanceToPoint)) { @@ -405,8 +411,7 @@ void SetOperations::TriangulateMesh(const MeshKernel& cutMesh, int side) eit->second.facet[side] = fidx; eit->second.facets[side][eit->second.fcounter[side]] = facet; eit->second.fcounter[side]++; - facet.SetFlag( - MeshFacet::MARKED); // set all facets connected to an edge: MARKED + facet.SetFlag(MeshFacet::MARKED); // set all facets connected to an edge: MARKED } } } @@ -465,12 +470,14 @@ void SetOperations::CollectFacets(int side, float mult) // MeshDefinitions::SetMinPointDistance(distSave); } -SetOperations::CollectFacetVisitor::CollectFacetVisitor(const MeshKernel& mesh, - std::vector& facets, - std::map& edges, - int side, - float mult, - Base::Builder3D& builder) +SetOperations::CollectFacetVisitor::CollectFacetVisitor( + const MeshKernel& mesh, + std::vector& facets, + std::map& edges, + int side, + float mult, + Base::Builder3D& builder +) : _facets(facets) , _mesh(mesh) , _edges(edges) @@ -479,10 +486,12 @@ SetOperations::CollectFacetVisitor::CollectFacetVisitor(const MeshKernel& mesh, , _builder(builder) {} -bool SetOperations::CollectFacetVisitor::Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) +bool SetOperations::CollectFacetVisitor::Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel +) { (void)rclFacet; (void)rclFrom; @@ -492,11 +501,13 @@ bool SetOperations::CollectFacetVisitor::Visit(const MeshFacet& rclFacet, } // static int matchCounter = 0; -bool SetOperations::CollectFacetVisitor::AllowVisit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel, - unsigned short neighbourIndex) +bool SetOperations::CollectFacetVisitor::AllowVisit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel, + unsigned short neighbourIndex +) { (void)ulFInd; (void)ulLevel; @@ -511,18 +522,18 @@ bool SetOperations::CollectFacetVisitor::AllowVisit(const MeshFacet& rclFacet, if (it != _edges.end()) { if (_addFacets == -1) { // determine if the facets should add or not only once - MeshGeomFacet facet = _mesh.GetFacet(rclFrom); // triangulated facet - MeshGeomFacet facetOther = - it->second - .facets[1 - _side][0]; // triangulated facet from same edge and other mesh + MeshGeomFacet facet = _mesh.GetFacet(rclFrom); // triangulated facet + MeshGeomFacet facetOther = it->second.facets[1 - _side][0]; // triangulated facet + // from same edge and + // other mesh Vector3f normalOther = facetOther.GetNormal(); // Vector3f normal = facet.GetNormal(); Vector3f edgeDir = it->first.pt1 - it->first.pt2; Vector3f ocDir = (edgeDir % (facet.GetGravityPoint() - it->first.pt1)) % edgeDir; ocDir.Normalize(); - Vector3f ocDirOther = - (edgeDir % (facetOther.GetGravityPoint() - it->first.pt1)) % edgeDir; + Vector3f ocDirOther = (edgeDir % (facetOther.GetGravityPoint() - it->first.pt1)) + % edgeDir; ocDirOther.Normalize(); // Vector3f dir = ocDir % normal; @@ -730,9 +741,11 @@ bool MeshIntersection::testIntersection(const MeshKernel& k1, const MeshKernel& return false; } -void MeshIntersection::connectLines(bool onlyclosed, - const std::list& rdata, - std::list>& lines) +void MeshIntersection::connectLines( + bool onlyclosed, + const std::list& rdata, + std::list>& lines +) { float fMinEps = minDistance * minDistance; diff --git a/src/Mod/Mesh/App/Core/SetOperations.h b/src/Mod/Mesh/App/Core/SetOperations.h index 60aa81ed2a..4d9e35f656 100644 --- a/src/Mod/Mesh/App/Core/SetOperations.h +++ b/src/Mod/Mesh/App/Core/SetOperations.h @@ -65,11 +65,13 @@ public: }; /// Construction - SetOperations(const MeshKernel& cutMesh1, - const MeshKernel& cutMesh2, - MeshKernel& result, - OperationType opType, - float minDistanceToPoint = 1e-5F); + SetOperations( + const MeshKernel& cutMesh1, + const MeshKernel& cutMesh2, + MeshKernel& result, + OperationType opType, + float minDistanceToPoint = 1e-5F + ); public: /** Cut this mesh with another one. The result is a list of polylines @@ -154,21 +156,27 @@ private: int _addFacets {-1}; // 0: add facets to the result 1: do not add facets to the result Base::Builder3D& _builder; - CollectFacetVisitor(const MeshKernel& mesh, - std::vector& facets, - std::map& edges, - int side, - float mult, - Base::Builder3D& builder); - bool Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) override; - bool AllowVisit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel, - unsigned short neighbourIndex) override; + CollectFacetVisitor( + const MeshKernel& mesh, + std::vector& facets, + std::map& edges, + int side, + float mult, + Base::Builder3D& builder + ); + bool Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel + ) override; + bool AllowVisit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel, + unsigned short neighbourIndex + ) override; }; /** all points from cut */ diff --git a/src/Mod/Mesh/App/Core/Smoothing.cpp b/src/Mod/Mesh/App/Core/Smoothing.cpp index da1943c92d..150d2e271d 100644 --- a/src/Mod/Mesh/App/Core/Smoothing.cpp +++ b/src/Mod/Mesh/App/Core/Smoothing.cpp @@ -108,8 +108,7 @@ void PlaneFitSmoothing::Smooth(unsigned int iterations) } } -void PlaneFitSmoothing::SmoothPoints(unsigned int iterations, - const std::vector& point_indices) +void PlaneFitSmoothing::SmoothPoints(unsigned int iterations, const std::vector& point_indices) { MeshCore::MeshPoint center; MeshCore::MeshPointArray PointArray = kernel.GetPoints(); @@ -169,9 +168,11 @@ LaplaceSmoothing::LaplaceSmoothing(MeshKernel& m) : AbstractSmoothing(m) {} -void LaplaceSmoothing::Umbrella(const MeshRefPointToPoints& vv_it, - const MeshRefPointToFacets& vf_it, - double stepsize) +void LaplaceSmoothing::Umbrella( + const MeshRefPointToPoints& vv_it, + const MeshRefPointToFacets& vf_it, + double stepsize +) { const MeshCore::MeshPointArray& points = kernel.GetPoints(); MeshCore::MeshPointArray::_TConstIterator v_it, v_beg = points.begin(), v_end = points.end(); @@ -206,10 +207,12 @@ void LaplaceSmoothing::Umbrella(const MeshRefPointToPoints& vv_it, } } -void LaplaceSmoothing::Umbrella(const MeshRefPointToPoints& vv_it, - const MeshRefPointToFacets& vf_it, - double stepsize, - const std::vector& point_indices) +void LaplaceSmoothing::Umbrella( + const MeshRefPointToPoints& vv_it, + const MeshRefPointToFacets& vf_it, + double stepsize, + const std::vector& point_indices +) { const MeshCore::MeshPointArray& points = kernel.GetPoints(); MeshCore::MeshPointArray::_TConstIterator v_beg = points.begin(); @@ -253,8 +256,7 @@ void LaplaceSmoothing::Smooth(unsigned int iterations) } } -void LaplaceSmoothing::SmoothPoints(unsigned int iterations, - const std::vector& point_indices) +void LaplaceSmoothing::SmoothPoints(unsigned int iterations, const std::vector& point_indices) { MeshCore::MeshRefPointToPoints vv_it(kernel); MeshCore::MeshRefPointToFacets vf_it(kernel); @@ -281,8 +283,7 @@ void TaubinSmoothing::Smooth(unsigned int iterations) } } -void TaubinSmoothing::SmoothPoints(unsigned int iterations, - const std::vector& point_indices) +void TaubinSmoothing::SmoothPoints(unsigned int iterations, const std::vector& point_indices) { MeshCore::MeshRefPointToPoints vv_it(kernel); MeshCore::MeshRefPointToFacets vf_it(kernel); @@ -304,10 +305,7 @@ inline Base::Vector3d find_median(std::vector& container) return an1.first < an2.first; }; size_t n = container.size() / 2; - std::nth_element(container.begin(), - container.begin() + n, - container.end(), - compare_angle_normal); + std::nth_element(container.begin(), container.begin() + n, container.end(), compare_angle_normal); if ((container.size() % 2) == 1) { return container[n].second; @@ -337,8 +335,10 @@ void MedianFilterSmoothing::Smooth(unsigned int iterations) } } -void MedianFilterSmoothing::SmoothPoints(unsigned int iterations, - const std::vector& point_indices) +void MedianFilterSmoothing::SmoothPoints( + unsigned int iterations, + const std::vector& point_indices +) { MeshCore::MeshRefFacetToFacets ff_it(kernel); MeshCore::MeshRefPointToFacets vf_it(kernel); @@ -348,9 +348,11 @@ void MedianFilterSmoothing::SmoothPoints(unsigned int iterations, } } -void MedianFilterSmoothing::UpdatePoints(const MeshRefFacetToFacets& ff_it, - const MeshRefPointToFacets& vf_it, - const std::vector& point_indices) +void MedianFilterSmoothing::UpdatePoints( + const MeshRefFacetToFacets& ff_it, + const MeshRefPointToFacets& vf_it, + const std::vector& point_indices +) { const MeshCore::MeshPointArray& points = kernel.GetPoints(); const MeshCore::MeshFacetArray& facets = kernel.GetFacets(); diff --git a/src/Mod/Mesh/App/Core/Smoothing.h b/src/Mod/Mesh/App/Core/Smoothing.h index ef34898d20..77956974ed 100644 --- a/src/Mod/Mesh/App/Core/Smoothing.h +++ b/src/Mod/Mesh/App/Core/Smoothing.h @@ -110,10 +110,12 @@ public: protected: void Umbrella(const MeshRefPointToPoints&, const MeshRefPointToFacets&, double); - void Umbrella(const MeshRefPointToPoints&, - const MeshRefPointToFacets&, - double, - const std::vector&); + void Umbrella( + const MeshRefPointToPoints&, + const MeshRefPointToFacets&, + double, + const std::vector& + ); private: double lambda {0.6307}; @@ -151,9 +153,11 @@ public: void SmoothPoints(unsigned int, const std::vector&) override; private: - void UpdatePoints(const MeshRefFacetToFacets&, - const MeshRefPointToFacets&, - const std::vector&); + void UpdatePoints( + const MeshRefFacetToFacets&, + const MeshRefPointToFacets&, + const std::vector& + ); private: int weights {1}; diff --git a/src/Mod/Mesh/App/Core/SphereFit.cpp b/src/Mod/Mesh/App/Core/SphereFit.cpp index f172cfbad6..1e3cdfd3eb 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.cpp +++ b/src/Mod/Mesh/App/Core/SphereFit.cpp @@ -93,9 +93,11 @@ float SphereFit::GetDistanceToSphere(const Base::Vector3f& rcPoint) const { float fResult = std::numeric_limits::max(); if (_bIsFitted) { - fResult = Base::Vector3d((double)rcPoint.x - _vCenter.x, - (double)rcPoint.y - _vCenter.y, - (double)rcPoint.z - _vCenter.z) + fResult = Base::Vector3d( + (double)rcPoint.x - _vCenter.x, + (double)rcPoint.y - _vCenter.y, + (double)rcPoint.z - _vCenter.z + ) .Length() - _dRadius; } @@ -130,9 +132,11 @@ void SphereFit::ProjectToSphere() // Because this vector is orthogonal to the sphere's surface at the // intersection point we can easily compute the projection point on the // closest surface point using the radius of the sphere - Base::Vector3d diff((double)cPnt.x - _vCenter.x, - (double)cPnt.y - _vCenter.y, - (double)cPnt.z - _vCenter.z); + Base::Vector3d diff( + (double)cPnt.x - _vCenter.x, + (double)cPnt.y - _vCenter.y, + (double)cPnt.z - _vCenter.z + ); double length = diff.Length(); if (length == 0.0) { // Point is exactly at the sphere center, so it can be projected in any direction onto @@ -169,9 +173,11 @@ void SphereFit::ComputeApproximations() _vCenter /= (double)_vPoints.size(); for (cIt = _vPoints.begin(); cIt != _vPoints.end(); ++cIt) { - Base::Vector3d diff((double)cIt->x - _vCenter.x, - (double)cIt->y - _vCenter.y, - (double)cIt->z - _vCenter.z); + Base::Vector3d diff( + (double)cIt->x - _vCenter.x, + (double)cIt->y - _vCenter.y, + (double)cIt->z - _vCenter.z + ); _dRadius += diff.Length(); } _dRadius /= (double)_vPoints.size(); @@ -253,9 +259,11 @@ float SphereFit::Fit() // Set up the normal equation matrices // atpa ... 4x4 normal matrix // atpl ... 4x1 matrix (right-hand side of equation) -void SphereFit::setupNormalEquationMatrices(const std::vector& residuals, - Matrix4x4& atpa, - Eigen::VectorXd& atpl) const +void SphereFit::setupNormalEquationMatrices( + const std::vector& residuals, + Matrix4x4& atpa, + Eigen::VectorXd& atpl +) const { // Zero matrices atpa.setZero(); @@ -284,12 +292,14 @@ void SphereFit::setupNormalEquationMatrices(const std::vector& r // f0 ... reference to f0 term // qw ... reference to quasi weight (here we are assuming equal unit weights for each observed // point coordinate) b[3] ... observation partials -void SphereFit::setupObservation(const Base::Vector3f& point, - const Base::Vector3d& residual, - double a[4], - double& f0, - double& qw, - double b[3]) const +void SphereFit::setupObservation( + const Base::Vector3f& point, + const Base::Vector3d& residual, + double a[4], + double& f0, + double& qw, + double b[3] +) const { // This adjustment requires an update of the observation approximations // because the residuals do not have a linear relationship. @@ -334,11 +344,7 @@ void SphereFit::setupObservation(const Base::Vector3f& point, // pi ... weight of observation (= quasi weight qw for this solution) // atpa ... 4x4 normal equation matrix // atpl ... 4x1 matrix/vector (right-hand side of equations) -void SphereFit::addObservationU(double a[4], - double li, - double pi, - Matrix4x4& atpa, - Eigen::VectorXd& atpl) const +void SphereFit::addObservationU(double a[4], double li, double pi, Matrix4x4& atpa, Eigen::VectorXd& atpl) const { for (int i = 0; i < 4; ++i) { double aipi = a[i] * pi; @@ -363,11 +369,13 @@ void SphereFit::setLowerPart(Matrix4x4& atpa) const } // Compute the residuals and sigma0 and check the residual convergence -bool SphereFit::computeResiduals(const Eigen::VectorXd& x, - std::vector& residuals, - double& sigma0, - double vConvLimit, - bool& vConverged) const +bool SphereFit::computeResiduals( + const Eigen::VectorXd& x, + std::vector& residuals, + double& sigma0, + double vConvLimit, + bool& vConverged +) const { vConverged = true; int nPtsUsed = 0; diff --git a/src/Mod/Mesh/App/Core/SphereFit.h b/src/Mod/Mesh/App/Core/SphereFit.h index 107443ecd6..1ef1bb54fa 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.h +++ b/src/Mod/Mesh/App/Core/SphereFit.h @@ -96,26 +96,26 @@ protected: /** * Set up the normal equations */ - void setupNormalEquationMatrices(const std::vector& residuals, - Matrix4x4& atpa, - Eigen::VectorXd& atpl) const; + void setupNormalEquationMatrices( + const std::vector& residuals, + Matrix4x4& atpa, + Eigen::VectorXd& atpl + ) const; /** * Sets up contributions of given observation to the normal equation matrices. */ - void setupObservation(const Base::Vector3f& point, - const Base::Vector3d& residual, - double a[4], - double& f0, - double& qw, - double b[3]) const; + void setupObservation( + const Base::Vector3f& point, + const Base::Vector3d& residual, + double a[4], + double& f0, + double& qw, + double b[3] + ) const; /** * Computes contribution of the given observation equation on the normal equation matrices */ - void addObservationU(double a[4], - double li, - double pi, - Matrix4x4& atpa, - Eigen::VectorXd& atpl) const; + void addObservationU(double a[4], double li, double pi, Matrix4x4& atpa, Eigen::VectorXd& atpl) const; /** * Set the lower part of the normal matrix equal to the upper part */ @@ -124,11 +124,13 @@ protected: /** * Compute the residuals and sigma0 and check the residual convergence */ - bool computeResiduals(const Eigen::VectorXd& x, - std::vector& residuals, - double& sigma0, - double vConvLimit, - bool& vConverged) const; + bool computeResiduals( + const Eigen::VectorXd& x, + std::vector& residuals, + double& sigma0, + double vConvLimit, + bool& vConverged + ) const; private: Base::Vector3d _vCenter; /**< Center of sphere. */ diff --git a/src/Mod/Mesh/App/Core/Tools.cpp b/src/Mod/Mesh/App/Core/Tools.cpp index fc6395df88..6a4eebba3e 100644 --- a/src/Mod/Mesh/App/Core/Tools.cpp +++ b/src/Mod/Mesh/App/Core/Tools.cpp @@ -49,11 +49,12 @@ void MeshSearchNeighbours::Reinit(float fSampleDistance) MeshAlgorithm(_rclMesh).ResetPointFlag(MeshPoint::MARKED); } -unsigned long -MeshSearchNeighbours::NeighboursFromFacet(FacetIndex ulFacetIdx, - float fDistance, - unsigned long ulMinPoints, - std::vector& raclResultPoints) +unsigned long MeshSearchNeighbours::NeighboursFromFacet( + FacetIndex ulFacetIdx, + float fDistance, + unsigned long ulMinPoints, + std::vector& raclResultPoints +) { bool bAddPoints = false; @@ -153,10 +154,11 @@ void MeshSearchNeighbours::SampleAllFacets() } } -unsigned long -MeshSearchNeighbours::NeighboursFromSampledFacets(FacetIndex ulFacetIdx, - float fDistance, - std::vector& raclResultPoints) +unsigned long MeshSearchNeighbours::NeighboursFromSampledFacets( + FacetIndex ulFacetIdx, + float fDistance, + std::vector& raclResultPoints +) { SampleAllFacets(); @@ -235,9 +237,11 @@ bool MeshSearchNeighbours::AccumulateNeighbours(const MeshFacet& rclF, FacetInde bool bFound = false; if (k == 3) { // add all sample points - _aclPointsResult.insert(_aclPointsResult.end(), - _aclSampledFacets[ulFIdx].begin(), - _aclSampledFacets[ulFIdx].end()); + _aclPointsResult.insert( + _aclPointsResult.end(), + _aclSampledFacets[ulFIdx].begin(), + _aclSampledFacets[ulFIdx].end() + ); bFound = true; } else { // add points inner radius @@ -275,11 +279,12 @@ bool MeshSearchNeighbours::ExpandRadius(unsigned long ulMinPoints) return false; } -unsigned long -MeshSearchNeighbours::NeighboursFacetFromFacet(FacetIndex ulFacetIdx, - float fDistance, - std::vector& raclResultPoints, - std::vector& raclResultFacets) +unsigned long MeshSearchNeighbours::NeighboursFacetFromFacet( + FacetIndex ulFacetIdx, + float fDistance, + std::vector& raclResultPoints, + std::vector& raclResultFacets +) { std::set aulFacetSet; diff --git a/src/Mod/Mesh/App/Core/Tools.h b/src/Mod/Mesh/App/Core/Tools.h index eeef4f0ef5..be4709404d 100644 --- a/src/Mod/Mesh/App/Core/Tools.h +++ b/src/Mod/Mesh/App/Core/Tools.h @@ -54,28 +54,36 @@ public: * facets lying inside a sphere of radius \a fDistance, center \a center of the original facet. * This method uses the MARKED flags. */ - unsigned long NeighboursFromFacet(FacetIndex ulFacetIdx, - float fDistance, - unsigned long ulMinPoints, - std::vector& raclResultPoints); + unsigned long NeighboursFromFacet( + FacetIndex ulFacetIdx, + float fDistance, + unsigned long ulMinPoints, + std::vector& raclResultPoints + ); /** Searches for facets from the start facet, sample the neighbour facets and accumulates the * points. */ - unsigned long NeighboursFromSampledFacets(FacetIndex ulFacetIdx, - float fDistance, - std::vector& raclResultPoints); + unsigned long NeighboursFromSampledFacets( + FacetIndex ulFacetIdx, + float fDistance, + std::vector& raclResultPoints + ); /** Searches for facets from the start facet. */ - unsigned long NeighboursFacetFromFacet(FacetIndex ulFacetIdx, - float fDistance, - std::vector& raclResultPoints, - std::vector& raclResultFacets); + unsigned long NeighboursFacetFromFacet( + FacetIndex ulFacetIdx, + float fDistance, + std::vector& raclResultPoints, + std::vector& raclResultFacets + ); protected: /** Subsamples the mesh. */ void SampleAllFacets(); - inline bool - CheckDistToFacet(const MeshFacet& rclF); // check distance to facet, add points inner radius - bool AccumulateNeighbours(const MeshFacet& rclF, - FacetIndex ulFIdx); // accumulate the sample neighbours facet + inline bool CheckDistToFacet(const MeshFacet& rclF); // check distance to facet, add points + // inner radius + bool AccumulateNeighbours( + const MeshFacet& rclF, + FacetIndex ulFIdx + ); // accumulate the sample neighbours facet inline bool InnerPoint(const Base::Vector3f& rclPt) const; inline bool TriangleCutsSphere(const MeshFacet& rclF) const; bool ExpandRadius(unsigned long ulMinPoints); @@ -193,9 +201,7 @@ class MeshNearestIndexToPlane { public: using Index = typename T::Index; - MeshNearestIndexToPlane(const MeshKernel& mesh, - const Base::Vector3f& b, - const Base::Vector3f& n) + MeshNearestIndexToPlane(const MeshKernel& mesh, const Base::Vector3f& b, const Base::Vector3f& n) : nearest_index(-1) , it(mesh) , base(b) diff --git a/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp b/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp index c971e8fab6..2aad3c1e10 100644 --- a/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp +++ b/src/Mod/Mesh/App/Core/TopoAlgorithm.cpp @@ -150,12 +150,11 @@ void MeshTopoAlgorithm::OptimizeTopology(float fMaxAngle) for (int i = 0; i < 3; i++) { // ignore open edges if (pI->_aulNeighbours[i] != FACET_INDEX_MAX) { - PointIndex ulPt0 = - std::min(pI->_aulPoints[i], pI->_aulPoints[(i + 1) % 3]); - PointIndex ulPt1 = - std::max(pI->_aulPoints[i], pI->_aulPoints[(i + 1) % 3]); + PointIndex ulPt0 = std::min(pI->_aulPoints[i], pI->_aulPoints[(i + 1) % 3]); + PointIndex ulPt1 = std::max(pI->_aulPoints[i], pI->_aulPoints[(i + 1) % 3]); aEdge2Face[std::pair(ulPt0, ulPt1)].push_back( - pI - _rclMesh._aclFacetArray.begin()); + pI - _rclMesh._aclFacetArray.begin() + ); } } } @@ -206,10 +205,8 @@ void MeshTopoAlgorithm::OptimizeTopology(float fMaxAngle) for (int i = 0; i < 3; i++) { std::map, std::vector>::iterator it; // first facet - PointIndex ulPt0 = - std::min(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); - PointIndex ulPt1 = - std::max(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); + PointIndex ulPt0 = std::min(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); + PointIndex ulPt1 = std::max(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); it = aEdge2Face.find(std::make_pair(ulPt0, ulPt1)); if (it != aEdge2Face.end()) { if (it->second[0] == pE->second[1]) { @@ -237,10 +234,14 @@ void MeshTopoAlgorithm::OptimizeTopology(float fMaxAngle) } // Now we must remove the edge and replace it through the new edge - PointIndex ulPt0 = std::min(rF1._aulPoints[(side1 + 1) % 3], - rF2._aulPoints[(side2 + 1) % 3]); - PointIndex ulPt1 = std::max(rF1._aulPoints[(side1 + 1) % 3], - rF2._aulPoints[(side2 + 1) % 3]); + PointIndex ulPt0 = std::min( + rF1._aulPoints[(side1 + 1) % 3], + rF2._aulPoints[(side2 + 1) % 3] + ); + PointIndex ulPt1 = std::max( + rF1._aulPoints[(side1 + 1) % 3], + rF2._aulPoints[(side2 + 1) % 3] + ); std::pair aNewEdge = std::make_pair(ulPt0, ulPt1); aEdge2Face[aNewEdge] = pE->second; aEdge2Face.erase(pE); @@ -249,8 +250,7 @@ void MeshTopoAlgorithm::OptimizeTopology(float fMaxAngle) } // Cosine of the maximum angle in triangle (v1,v2,v3) -static float -cos_maxangle(const Base::Vector3f& v1, const Base::Vector3f& v2, const Base::Vector3f& v3) +static float cos_maxangle(const Base::Vector3f& v1, const Base::Vector3f& v2, const Base::Vector3f& v3) { float a = Base::Distance(v2, v3); float b = Base::Distance(v3, v1); @@ -258,14 +258,15 @@ cos_maxangle(const Base::Vector3f& v1, const Base::Vector3f& v2, const Base::Vec float A = a * (b * b + c * c - a * a); float B = b * (c * c + a * a - b * b); float C = c * (a * a + b * b - c * c); - return 0.5F * std::min(std::min(A, B), C) - / (a * b * c); // min cosine == max angle + return 0.5F * std::min(std::min(A, B), C) / (a * b * c); // min cosine == max angle } -static float swap_benefit(const Base::Vector3f& v1, - const Base::Vector3f& v2, - const Base::Vector3f& v3, - const Base::Vector3f& v4) +static float swap_benefit( + const Base::Vector3f& v1, + const Base::Vector3f& v2, + const Base::Vector3f& v3, + const Base::Vector3f& v4 +) { Base::Vector3f n124 = (v4 - v2) % (v1 - v2); Base::Vector3f n234 = (v3 - v2) % (v4 - v2); @@ -386,18 +387,14 @@ void MeshTopoAlgorithm::DelaunayFlip(float fMaxAngle) for (int i = 0; i < 3; i++) { if (face_1._aulNeighbours[i] != FACET_INDEX_MAX && face_1._aulNeighbours[i] != edge.second) { - FacetIndex ulFt0 = - std::min(edge.first, face_1._aulNeighbours[i]); - FacetIndex ulFt1 = - std::max(edge.first, face_1._aulNeighbours[i]); + FacetIndex ulFt0 = std::min(edge.first, face_1._aulNeighbours[i]); + FacetIndex ulFt1 = std::max(edge.first, face_1._aulNeighbours[i]); aEdge2Face.insert(std::pair(ulFt0, ulFt1)); } if (face_2._aulNeighbours[i] != FACET_INDEX_MAX && face_2._aulNeighbours[i] != edge.first) { - FacetIndex ulFt0 = - std::min(edge.second, face_2._aulNeighbours[i]); - FacetIndex ulFt1 = - std::max(edge.second, face_2._aulNeighbours[i]); + FacetIndex ulFt0 = std::min(edge.second, face_2._aulNeighbours[i]); + FacetIndex ulFt1 = std::max(edge.second, face_2._aulNeighbours[i]); aEdge2Face.insert(std::pair(ulFt0, ulFt1)); } } @@ -477,10 +474,12 @@ void MeshTopoAlgorithm::AdjustEdgesToCurvatureDirection() } // compute vertex based curvatures - Wm4::MeshCurvature meshCurv(static_cast(_rclMesh.CountPoints()), - aPnts.data(), - static_cast(_rclMesh.CountFacets()), - aIdx.data()); + Wm4::MeshCurvature meshCurv( + static_cast(_rclMesh.CountPoints()), + aPnts.data(), + static_cast(_rclMesh.CountFacets()), + aIdx.data() + ); // get curvature information now const Wm4::Vector3* aMaxCurvDir = meshCurv.GetMaxDirections(); @@ -546,9 +545,11 @@ void MeshTopoAlgorithm::AdjustEdgesToCurvatureDirection() } } -bool MeshTopoAlgorithm::InsertVertexAndSwapEdge(FacetIndex ulFacetPos, - const Base::Vector3f& rclPoint, - float fMaxAngle) +bool MeshTopoAlgorithm::InsertVertexAndSwapEdge( + FacetIndex ulFacetPos, + const Base::Vector3f& rclPoint, + float fMaxAngle +) { if (!InsertVertex(ulFacetPos, rclPoint)) { return false; @@ -639,9 +640,7 @@ bool MeshTopoAlgorithm::IsSwapEdgeLegal(FacetIndex ulFacetPos, FacetIndex ulNeig return true; } -bool MeshTopoAlgorithm::ShouldSwapEdge(FacetIndex ulFacetPos, - FacetIndex ulNeighbour, - float fMaxAngle) const +bool MeshTopoAlgorithm::ShouldSwapEdge(FacetIndex ulFacetPos, FacetIndex ulNeighbour, float fMaxAngle) const { if (!IsSwapEdgeLegal(ulFacetPos, ulNeighbour)) { return false; @@ -697,11 +696,14 @@ void MeshTopoAlgorithm::SwapEdge(FacetIndex ulFacetPos, FacetIndex ulNeighbour) if (rclF._aulNeighbours[(uFSide + 1) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclF._aulNeighbours[(uFSide + 1) % 3]].ReplaceNeighbour( ulFacetPos, - ulNeighbour); + ulNeighbour + ); } if (rclN._aulNeighbours[(uNSide + 1) % 3] != FACET_INDEX_MAX) { - _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 1) % 3]].ReplaceNeighbour(ulNeighbour, - ulFacetPos); + _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 1) % 3]].ReplaceNeighbour( + ulNeighbour, + ulFacetPos + ); } // swap the point and neighbour indices @@ -713,9 +715,7 @@ void MeshTopoAlgorithm::SwapEdge(FacetIndex ulFacetPos, FacetIndex ulNeighbour) rclN._aulNeighbours[(uNSide + 1) % 3] = ulFacetPos; } -bool MeshTopoAlgorithm::SplitEdge(FacetIndex ulFacetPos, - FacetIndex ulNeighbour, - const Base::Vector3f& rP) +bool MeshTopoAlgorithm::SplitEdge(FacetIndex ulFacetPos, FacetIndex ulNeighbour, const Base::Vector3f& rP) { MeshFacet& rclF = _rclMesh._aclFacetArray[ulFacetPos]; MeshFacet& rclN = _rclMesh._aclFacetArray[ulNeighbour]; @@ -740,12 +740,16 @@ bool MeshTopoAlgorithm::SplitEdge(FacetIndex ulFacetPos, // adjust the neighbourhood if (rclF._aulNeighbours[(uFSide + 1) % 3] != FACET_INDEX_MAX) { - _rclMesh._aclFacetArray[rclF._aulNeighbours[(uFSide + 1) % 3]].ReplaceNeighbour(ulFacetPos, - ulSize); + _rclMesh._aclFacetArray[rclF._aulNeighbours[(uFSide + 1) % 3]].ReplaceNeighbour( + ulFacetPos, + ulSize + ); } if (rclN._aulNeighbours[(uNSide + 2) % 3] != FACET_INDEX_MAX) { - _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 2) % 3]].ReplaceNeighbour(ulNeighbour, - ulSize + 1); + _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 2) % 3]].ReplaceNeighbour( + ulNeighbour, + ulSize + 1 + ); } MeshFacet cNew1, cNew2; @@ -776,9 +780,11 @@ bool MeshTopoAlgorithm::SplitEdge(FacetIndex ulFacetPos, return true; } -bool MeshTopoAlgorithm::SplitOpenEdge(FacetIndex ulFacetPos, - unsigned short uSide, - const Base::Vector3f& rP) +bool MeshTopoAlgorithm::SplitOpenEdge( + FacetIndex ulFacetPos, + unsigned short uSide, + const Base::Vector3f& rP +) { MeshFacet& rclF = _rclMesh._aclFacetArray[ulFacetPos]; if (rclF._aulNeighbours[uSide] != FACET_INDEX_MAX) { @@ -796,8 +802,10 @@ bool MeshTopoAlgorithm::SplitOpenEdge(FacetIndex ulFacetPos, // adjust the neighbourhood if (rclF._aulNeighbours[(uSide + 1) % 3] != FACET_INDEX_MAX) { - _rclMesh._aclFacetArray[rclF._aulNeighbours[(uSide + 1) % 3]].ReplaceNeighbour(ulFacetPos, - ulSize); + _rclMesh._aclFacetArray[rclF._aulNeighbours[(uSide + 1) % 3]].ReplaceNeighbour( + ulFacetPos, + ulSize + ); } MeshFacet cNew; @@ -817,8 +825,7 @@ bool MeshTopoAlgorithm::SplitOpenEdge(FacetIndex ulFacetPos, return true; } -bool MeshTopoAlgorithm::Vertex_Less::operator()(const Base::Vector3f& u, - const Base::Vector3f& v) const +bool MeshTopoAlgorithm::Vertex_Less::operator()(const Base::Vector3f& u, const Base::Vector3f& v) const { if (std::fabs(u.x - v.x) > std::numeric_limits::epsilon()) { return u.x < v.x; @@ -865,8 +872,7 @@ PointIndex MeshTopoAlgorithm::GetOrAddIndex(const MeshPoint& rclPoint) return retval.first->second; } -std::vector MeshTopoAlgorithm::GetFacetsToPoint(FacetIndex uFacetPos, - PointIndex uPointPos) const +std::vector MeshTopoAlgorithm::GetFacetsToPoint(FacetIndex uFacetPos, PointIndex uPointPos) const { // get all facets this point is referenced by std::list aReference; @@ -1008,22 +1014,26 @@ bool MeshTopoAlgorithm::CollapseEdge(FacetIndex ulFacetPos, FacetIndex ulNeighbo if (rclF._aulNeighbours[(uFSide + 1) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclF._aulNeighbours[(uFSide + 1) % 3]].ReplaceNeighbour( ulFacetPos, - rclF._aulNeighbours[(uFSide + 2) % 3]); + rclF._aulNeighbours[(uFSide + 2) % 3] + ); } if (rclF._aulNeighbours[(uFSide + 2) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclF._aulNeighbours[(uFSide + 2) % 3]].ReplaceNeighbour( ulFacetPos, - rclF._aulNeighbours[(uFSide + 1) % 3]); + rclF._aulNeighbours[(uFSide + 1) % 3] + ); } if (rclN._aulNeighbours[(uNSide + 1) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 1) % 3]].ReplaceNeighbour( ulNeighbour, - rclN._aulNeighbours[(uNSide + 2) % 3]); + rclN._aulNeighbours[(uNSide + 2) % 3] + ); } if (rclN._aulNeighbours[(uNSide + 2) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 2) % 3]].ReplaceNeighbour( ulNeighbour, - rclN._aulNeighbours[(uNSide + 1) % 3]); + rclN._aulNeighbours[(uNSide + 1) % 3] + ); } // isolate the both facets and the point @@ -1048,11 +1058,13 @@ bool MeshTopoAlgorithm::IsCollapseEdgeLegal(const EdgeCollapse& ec) const // Check connectivity // std::vector commonPoints; - std::set_intersection(ec._adjacentFrom.begin(), - ec._adjacentFrom.end(), - ec._adjacentTo.begin(), - ec._adjacentTo.end(), - std::back_insert_iterator>(commonPoints)); + std::set_intersection( + ec._adjacentFrom.begin(), + ec._adjacentFrom.end(), + ec._adjacentTo.begin(), + ec._adjacentTo.end(), + std::back_insert_iterator>(commonPoints) + ); if (commonPoints.size() > 2) { return false; } @@ -1180,12 +1192,14 @@ bool MeshTopoAlgorithm::CollapseFacet(FacetIndex ulFacetPos) if (rclN._aulNeighbours[(uNSide + 1) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 1) % 3]].ReplaceNeighbour( nbIndex, - rclN._aulNeighbours[(uNSide + 2) % 3]); + rclN._aulNeighbours[(uNSide + 2) % 3] + ); } if (rclN._aulNeighbours[(uNSide + 2) % 3] != FACET_INDEX_MAX) { _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 2) % 3]].ReplaceNeighbour( nbIndex, - rclN._aulNeighbours[(uNSide + 1) % 3]); + rclN._aulNeighbours[(uNSide + 1) % 3] + ); } // Isolate the neighbours from the topology @@ -1208,9 +1222,11 @@ bool MeshTopoAlgorithm::CollapseFacet(FacetIndex ulFacetPos) return true; } -void MeshTopoAlgorithm::SplitFacet(FacetIndex ulFacetPos, - const Base::Vector3f& rP1, - const Base::Vector3f& rP2) +void MeshTopoAlgorithm::SplitFacet( + FacetIndex ulFacetPos, + const Base::Vector3f& rP1, + const Base::Vector3f& rP2 +) { float fEps = MESH_MIN_EDGE_LEN; MeshFacet& rFace = _rclMesh._aclFacetArray[ulFacetPos]; @@ -1282,9 +1298,11 @@ void MeshTopoAlgorithm::SplitFacetOnOneEdge(FacetIndex ulFacetPos, const Base::V } } -void MeshTopoAlgorithm::SplitFacetOnTwoEdges(FacetIndex ulFacetPos, - const Base::Vector3f& rP1, - const Base::Vector3f& rP2) +void MeshTopoAlgorithm::SplitFacetOnTwoEdges( + FacetIndex ulFacetPos, + const Base::Vector3f& rP1, + const Base::Vector3f& rP2 +) { // search for the matching edges unsigned short iEdgeNo1 = std::numeric_limits::max(); @@ -1393,10 +1411,7 @@ void MeshTopoAlgorithm::SplitFacetOnTwoEdges(FacetIndex ulFacetPos, HarmonizeNeighbours(fixIndices); } -void MeshTopoAlgorithm::SplitFacet(FacetIndex ulFacetPos, - PointIndex P1, - PointIndex P2, - PointIndex Pn) +void MeshTopoAlgorithm::SplitFacet(FacetIndex ulFacetPos, PointIndex P1, PointIndex P2, PointIndex Pn) { MeshFacet& rFace = _rclMesh._aclFacetArray[ulFacetPos]; unsigned short side = rFace.Side(P1, P2); @@ -1426,12 +1441,14 @@ void MeshTopoAlgorithm::AddFacet(PointIndex P1, PointIndex P2, PointIndex P3) _rclMesh._aclFacetArray.push_back(facet); } -void MeshTopoAlgorithm::AddFacet(PointIndex P1, - PointIndex P2, - PointIndex P3, - FacetIndex N1, - FacetIndex N2, - FacetIndex N3) +void MeshTopoAlgorithm::AddFacet( + PointIndex P1, + PointIndex P2, + PointIndex P3, + FacetIndex N1, + FacetIndex N2, + FacetIndex N3 +) { MeshFacet facet; facet._aulPoints[0] = P1; @@ -1473,9 +1490,11 @@ void MeshTopoAlgorithm::HarmonizeNeighbours(FacetIndex facet1, FacetIndex facet2 } } -void MeshTopoAlgorithm::SplitNeighbourFacet(FacetIndex ulFacetPos, - unsigned short uFSide, - const Base::Vector3f& rPoint) +void MeshTopoAlgorithm::SplitNeighbourFacet( + FacetIndex ulFacetPos, + unsigned short uFSide, + const Base::Vector3f& rPoint +) { MeshFacet& rclF = _rclMesh._aclFacetArray[ulFacetPos]; @@ -1489,8 +1508,10 @@ void MeshTopoAlgorithm::SplitNeighbourFacet(FacetIndex ulFacetPos, // adjust the neighbourhood if (rclN._aulNeighbours[(uNSide + 1) % 3] != FACET_INDEX_MAX) { - _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 1) % 3]].ReplaceNeighbour(ulNeighbour, - ulSize); + _rclMesh._aclFacetArray[rclN._aulNeighbours[(uNSide + 1) % 3]].ReplaceNeighbour( + ulNeighbour, + ulSize + ); } MeshFacet cNew; @@ -1640,10 +1661,12 @@ bool MeshTopoAlgorithm::RemoveCorruptedFacet(FacetIndex index) return false; } -void MeshTopoAlgorithm::FillupHoles(unsigned long length, - int level, - AbstractPolygonTriangulator& cTria, - std::list>& aFailed) +void MeshTopoAlgorithm::FillupHoles( + unsigned long length, + int level, + AbstractPolygonTriangulator& cTria, + std::list>& aFailed +) { // get the mesh boundaries as an array of point indices std::list> aBorders, aFillBorders; @@ -1664,10 +1687,12 @@ void MeshTopoAlgorithm::FillupHoles(unsigned long length, } } -void MeshTopoAlgorithm::FillupHoles(int level, - AbstractPolygonTriangulator& cTria, - const std::list>& aBorders, - std::list>& aFailed) +void MeshTopoAlgorithm::FillupHoles( + int level, + AbstractPolygonTriangulator& cTria, + const std::list>& aBorders, + std::list>& aFailed +) { // get the facets to a point MeshRefPointToFacets cPt2Fac(_rclMesh); @@ -1715,9 +1740,7 @@ void MeshTopoAlgorithm::FillupHoles(int level, } // insert new points and faces into the mesh structure - _rclMesh._aclPointArray.insert(_rclMesh._aclPointArray.end(), - newPoints.begin(), - newPoints.end()); + _rclMesh._aclPointArray.insert(_rclMesh._aclPointArray.end(), newPoints.begin(), newPoints.end()); for (const auto& newPoint : newPoints) { _rclMesh._clBoundBox.Add(newPoint); } @@ -1729,11 +1752,13 @@ void MeshTopoAlgorithm::FillupHoles(int level, for (auto& newFacet : newFacets) { if (newFacet._aulPoints[0] >= ctPoints || newFacet._aulPoints[1] >= ctPoints || newFacet._aulPoints[2] >= ctPoints) { - Base::Console().log("Ignore invalid face <%d, %d, %d> (%d vertices)\n", - newFacet._aulPoints[0], - newFacet._aulPoints[1], - newFacet._aulPoints[2], - ctPoints); + Base::Console().log( + "Ignore invalid face <%d, %d, %d> (%d vertices)\n", + newFacet._aulPoints[0], + newFacet._aulPoints[1], + newFacet._aulPoints[2], + ctPoints + ); } else { addFacets.push_back(newFacet); @@ -1743,8 +1768,7 @@ void MeshTopoAlgorithm::FillupHoles(int level, } } -void MeshTopoAlgorithm::FindHoles(unsigned long length, - std::list>& aBorders) const +void MeshTopoAlgorithm::FindHoles(unsigned long length, std::list>& aBorders) const { std::list> border; MeshAlgorithm cAlgo(_rclMesh); @@ -1822,8 +1846,7 @@ MeshComponents::MeshComponents(const MeshKernel& rclMesh) : _rclMesh(rclMesh) {} -void MeshComponents::SearchForComponents(TMode tMode, - std::vector>& aclT) const +void MeshComponents::SearchForComponents(TMode tMode, std::vector>& aclT) const { // all facets std::vector aulAllFacets(_rclMesh.CountFacets()); @@ -1835,9 +1858,11 @@ void MeshComponents::SearchForComponents(TMode tMode, SearchForComponents(tMode, aulAllFacets, aclT); } -void MeshComponents::SearchForComponents(TMode tMode, - const std::vector& aSegment, - std::vector>& aclT) const +void MeshComponents::SearchForComponents( + TMode tMode, + const std::vector& aSegment, + std::vector>& aclT +) const { FacetIndex ulStartFacet {}; @@ -1858,9 +1883,7 @@ void MeshComponents::SearchForComponents(TMode tMode, // start from the first not visited facet unsigned long ulVisited = cAlgo.CountFacetFlag(MeshFacet::VISIT); MeshIsNotFlag flag; - iTri = std::find_if(iTri, iEnd, [flag](const MeshFacet& f) { - return flag(f, MeshFacet::VISIT); - }); + iTri = std::find_if(iTri, iEnd, [flag](const MeshFacet& f) { return flag(f, MeshFacet::VISIT); }); ulStartFacet = iTri - iBeg; // visitor diff --git a/src/Mod/Mesh/App/Core/TopoAlgorithm.h b/src/Mod/Mesh/App/Core/TopoAlgorithm.h index ea4d729db5..b8713af766 100644 --- a/src/Mod/Mesh/App/Core/TopoAlgorithm.h +++ b/src/Mod/Mesh/App/Core/TopoAlgorithm.h @@ -75,8 +75,7 @@ public: * edges to build more well-formed triangles. * @see InsertVertex(), ShouldSwapEdge(), SwapEdge(). */ - bool - InsertVertexAndSwapEdge(FacetIndex ulFacetPos, const Base::Vector3f& rclPoint, float fMaxAngle); + bool InsertVertexAndSwapEdge(FacetIndex ulFacetPos, const Base::Vector3f& rclPoint, float fMaxAngle); /** * Swaps the common edge of two adjacent facets even if the operation might * be illegal. To be sure that this operation is legal, check either with @@ -244,18 +243,22 @@ public: * needs to be done then the points of the neighbours of \a level rings will be used. * Holes for which the triangulation failed are returned in \a aFailed. */ - void FillupHoles(unsigned long length, - int level, - AbstractPolygonTriangulator&, - std::list>& aFailed); + void FillupHoles( + unsigned long length, + int level, + AbstractPolygonTriangulator&, + std::list>& aFailed + ); /** * This is an overloaded method provided for convenience. It takes as first argument * the boundaries which must be filled up. */ - void FillupHoles(int level, - AbstractPolygonTriangulator&, - const std::list>& aBorders, - std::list>& aFailed); + void FillupHoles( + int level, + AbstractPolygonTriangulator&, + const std::list>& aBorders, + std::list>& aFailed + ); /** * Find holes which consists of up to \a length edges. */ @@ -287,20 +290,12 @@ private: /** * Splits the neighbour facet of \a ulFacetPos on side \a uSide. */ - void - SplitNeighbourFacet(FacetIndex ulFacetPos, unsigned short uFSide, const Base::Vector3f& rPoint); + void SplitNeighbourFacet(FacetIndex ulFacetPos, unsigned short uFSide, const Base::Vector3f& rPoint); void SplitFacetOnOneEdge(FacetIndex ulFacetPos, const Base::Vector3f& rP1); - void SplitFacetOnTwoEdges(FacetIndex ulFacetPos, - const Base::Vector3f& rP1, - const Base::Vector3f& rP2); + void SplitFacetOnTwoEdges(FacetIndex ulFacetPos, const Base::Vector3f& rP1, const Base::Vector3f& rP2); void SplitFacet(FacetIndex ulFacetPos, PointIndex P1, PointIndex P2, PointIndex Pn); void AddFacet(PointIndex P1, PointIndex P2, PointIndex P3); - void AddFacet(PointIndex P1, - PointIndex P2, - PointIndex P3, - FacetIndex N1, - FacetIndex N2, - FacetIndex N3); + void AddFacet(PointIndex P1, PointIndex P2, PointIndex P3, FacetIndex N1, FacetIndex N2, FacetIndex N3); void HarmonizeNeighbours(FacetIndex facet1, FacetIndex facet2); void HarmonizeNeighbours(const std::vector& ulFacets); /** @@ -353,9 +348,11 @@ public: * Does basically the same as the method above escept that only the faces in * \a aSegment are regarded. */ - void SearchForComponents(TMode tMode, - const std::vector& aSegment, - std::vector>& aclT) const; + void SearchForComponents( + TMode tMode, + const std::vector& aSegment, + std::vector>& aclT + ) const; protected: // for sorting of elements diff --git a/src/Mod/Mesh/App/Core/Triangulation.cpp b/src/Mod/Mesh/App/Core/Triangulation.cpp index 4f58a82796..83ccd4450c 100644 --- a/src/Mod/Mesh/App/Core/Triangulation.cpp +++ b/src/Mod/Mesh/App/Core/Triangulation.cpp @@ -39,10 +39,12 @@ using namespace MeshCore; -bool TriangulationVerifier::Accept(const Base::Vector3f& n, - const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& p3) const +bool TriangulationVerifier::Accept( + const Base::Vector3f& n, + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& p3 +) const { float ref_dist = (p2 - p1) * n; float tri_dist = (p3 - p1) * n; @@ -54,10 +56,12 @@ bool TriangulationVerifier::MustFlip(const Base::Vector3f& n1, const Base::Vecto return n1.Dot(n2) <= 0.0F; } -bool TriangulationVerifierV2::Accept(const Base::Vector3f& n, - const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& p3) const +bool TriangulationVerifierV2::Accept( + const Base::Vector3f& n, + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& p3 +) const { float ref_dist = (p2 - p1) * n; float tri_dist = (p3 - p1) * n; @@ -179,15 +183,21 @@ std::vector AbstractPolygonTriangulator::ProjectToFitPlane() { std::vector proj = _points; _inverse = GetTransformToFitPlane(); - Base::Vector3f bs(static_cast(_inverse[0][3]), - static_cast(_inverse[1][3]), - static_cast(_inverse[2][3])); - Base::Vector3f ex(static_cast(_inverse[0][0]), - static_cast(_inverse[1][0]), - static_cast(_inverse[2][0])); - Base::Vector3f ey(static_cast(_inverse[0][1]), - static_cast(_inverse[1][1]), - static_cast(_inverse[2][1])); + Base::Vector3f bs( + static_cast(_inverse[0][3]), + static_cast(_inverse[1][3]), + static_cast(_inverse[2][3]) + ); + Base::Vector3f ex( + static_cast(_inverse[0][0]), + static_cast(_inverse[1][0]), + static_cast(_inverse[2][0]) + ); + Base::Vector3f ey( + static_cast(_inverse[0][1]), + static_cast(_inverse[1][1]), + static_cast(_inverse[2][1]) + ); for (auto& jt : proj) { jt.TransformToCoordinateSystem(bs, ex, ey); } @@ -201,15 +211,21 @@ void AbstractPolygonTriangulator::PostProcessing(const std::vector(_inverse[0][3]), - static_cast(_inverse[1][3]), - static_cast(_inverse[2][3])); - Base::Vector3f ex(static_cast(_inverse[0][0]), - static_cast(_inverse[1][0]), - static_cast(_inverse[2][0])); - Base::Vector3f ey(static_cast(_inverse[0][1]), - static_cast(_inverse[1][1]), - static_cast(_inverse[2][1])); + Base::Vector3f bs( + static_cast(_inverse[0][3]), + static_cast(_inverse[1][3]), + static_cast(_inverse[2][3]) + ); + Base::Vector3f ex( + static_cast(_inverse[0][0]), + static_cast(_inverse[1][0]), + static_cast(_inverse[2][0]) + ); + Base::Vector3f ey( + static_cast(_inverse[0][1]), + static_cast(_inverse[1][1]), + static_cast(_inverse[2][1]) + ); for (auto pt : points) { pt.TransformToCoordinateSystem(bs, ex, ey); @@ -223,8 +239,10 @@ void AbstractPolygonTriangulator::PostProcessing(const std::vector_indices.empty() && this->_points.size() != this->_indices.size()) { - Base::Console().log("Triangulation: %d points <> %d indices\n", - _points.size(), - _indices.size()); + Base::Console() + .log("Triangulation: %d points <> %d indices\n", _points.size(), _indices.size()); return false; } bool ok = Triangulate(); @@ -349,14 +366,16 @@ float EarClippingTriangulator::Triangulate::Area(const std::vector= std::numeric_limits::epsilon()) - && (bCROSScp >= std::numeric_limits::epsilon()) - && (cCROSSap >= std::numeric_limits::epsilon())); + return ( + (aCROSSbp >= std::numeric_limits::epsilon()) + && (bCROSScp >= std::numeric_limits::epsilon()) + && (cCROSSap >= std::numeric_limits::epsilon()) + ); } -bool EarClippingTriangulator::Triangulate::Snip(const std::vector& contour, - int u, - int v, - int w, - int n, - int* V) +bool EarClippingTriangulator::Triangulate::Snip( + const std::vector& contour, + int u, + int v, + int w, + int n, + int* V +) { int p {}; float Ax {}, Ay {}, Bx {}, By {}, Cx {}, Cy {}, Px {}, Py {}; @@ -423,8 +446,10 @@ bool EarClippingTriangulator::Triangulate::Snip(const std::vector& contour, - std::vector& result) +bool EarClippingTriangulator::Triangulate::Process( + const std::vector& contour, + std::vector& result +) { /* allocate and initialize list of Vertices in polygon */ @@ -528,7 +553,8 @@ bool QuasiDelaunayTriangulator::Triangulate() // ignore borderlines of the polygon if ((ulPt1 - ulPt0) % (_points.size() - 1) > 1) { aEdge2Face[std::pair(ulPt0, ulPt1)].push_back( - pI - _facets.begin()); + pI - _facets.begin() + ); } } } @@ -605,10 +631,8 @@ bool QuasiDelaunayTriangulator::Triangulate() for (int i = 0; i < 3; i++) { std::map, std::vector>::iterator it; // first facet - PointIndex ulPt0 = - std::min(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); - PointIndex ulPt1 = - std::max(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); + PointIndex ulPt0 = std::min(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); + PointIndex ulPt1 = std::max(rF1._aulPoints[i], rF1._aulPoints[(i + 1) % 3]); it = aEdge2Face.find(std::make_pair(ulPt0, ulPt1)); if (it != aEdge2Face.end()) { if (it->second[0] == pE->second[1]) { @@ -636,10 +660,14 @@ bool QuasiDelaunayTriangulator::Triangulate() } // Now we must remove the edge and replace it through the new edge - PointIndex ulPt0 = std::min(rF1._aulPoints[(side1 + 1) % 3], - rF2._aulPoints[(side2 + 1) % 3]); - PointIndex ulPt1 = std::max(rF1._aulPoints[(side1 + 1) % 3], - rF2._aulPoints[(side2 + 1) % 3]); + PointIndex ulPt0 = std::min( + rF1._aulPoints[(side1 + 1) % 3], + rF2._aulPoints[(side2 + 1) % 3] + ); + PointIndex ulPt1 = std::max( + rF1._aulPoints[(side1 + 1) % 3], + rF2._aulPoints[(side2 + 1) % 3] + ); std::pair aNewEdge = std::make_pair(ulPt0, ulPt1); aEdge2Face[aNewEdge] = pE->second; aEdge2Face.erase(pE); @@ -709,11 +737,8 @@ bool DelaunayTriangulator::Triangulate() akVertex.emplace_back(static_cast(point.x), static_cast(point.y)); } - Wm4::Delaunay2d del(static_cast(akVertex.size()), - akVertex.data(), - 0.001, - false, - Wm4::Query::QT_INT64); + Wm4::Delaunay2d + del(static_cast(akVertex.size()), akVertex.data(), 0.001, false, Wm4::Query::QT_INT64); int iTQuantity = del.GetSimplexQuantity(); auto numFaces = static_cast(iTQuantity); std::vector aiTVertex(3 * numFaces); diff --git a/src/Mod/Mesh/App/Core/Triangulation.h b/src/Mod/Mesh/App/Core/Triangulation.h index c3fa5021cf..57abf26c22 100644 --- a/src/Mod/Mesh/App/Core/Triangulation.h +++ b/src/Mod/Mesh/App/Core/Triangulation.h @@ -42,20 +42,24 @@ public: TriangulationVerifier& operator=(const TriangulationVerifier&) = delete; TriangulationVerifier& operator=(TriangulationVerifier&&) = delete; - virtual bool Accept(const Base::Vector3f& n, - const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& p3) const; + virtual bool Accept( + const Base::Vector3f& n, + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& p3 + ) const; virtual bool MustFlip(const Base::Vector3f& n1, const Base::Vector3f& n2) const; }; class MeshExport TriangulationVerifierV2: public TriangulationVerifier { public: - bool Accept(const Base::Vector3f& n, - const Base::Vector3f& p1, - const Base::Vector3f& p2, - const Base::Vector3f& p3) const override; + bool Accept( + const Base::Vector3f& n, + const Base::Vector3f& p1, + const Base::Vector3f& p2, + const Base::Vector3f& p3 + ) const override; bool MustFlip(const Base::Vector3f& n1, const Base::Vector3f& n2) const override; }; @@ -191,28 +195,28 @@ private: public: // triangulate a contour/polygon, places results in STL vector // as series of triangles.indicating the points - static bool Process(const std::vector& contour, - std::vector& result); + static bool Process(const std::vector& contour, std::vector& result); // compute area of a contour/polygon static float Area(const std::vector& contour); // decide if point Px/Py is inside triangle defined by // (Ax,Ay) (Bx,By) (Cx,Cy) - static bool InsideTriangle(float Ax, - float Ay, - float Bx, - float By, - float Cx, - float Cy, - float Px, - float Py); + static bool InsideTriangle( + float Ax, + float Ay, + float Bx, + float By, + float Cx, + float Cy, + float Px, + float Py + ); static bool _invert; private: - static bool - Snip(const std::vector& contour, int u, int v, int w, int n, int* V); + static bool Snip(const std::vector& contour, int u, int v, int w, int n, int* V); }; }; diff --git a/src/Mod/Mesh/App/Core/Trim.cpp b/src/Mod/Mesh/App/Core/Trim.cpp index 96f940b7a3..afa6fbaa48 100644 --- a/src/Mod/Mesh/App/Core/Trim.cpp +++ b/src/Mod/Mesh/App/Core/Trim.cpp @@ -35,9 +35,7 @@ using namespace MeshCore; -MeshTrimming::MeshTrimming(MeshKernel& mesh, - const Base::ViewProjMethod* proj, - const Base::Polygon2d& poly) +MeshTrimming::MeshTrimming(MeshKernel& mesh, const Base::ViewProjMethod* proj, const Base::Polygon2d& poly) : myMesh(mesh) , myProj(proj) , myPoly(poly) @@ -55,8 +53,7 @@ void MeshTrimming::SetInnerOrOuter(TMode tMode) } } -void MeshTrimming::CheckFacets(const MeshFacetGrid& rclGrid, - std::vector& raulFacets) const +void MeshTrimming::CheckFacets(const MeshFacetGrid& rclGrid, std::vector& raulFacets) const { std::vector::iterator it; MeshFacetIterator clIter(myMesh, 0); @@ -82,8 +79,10 @@ void MeshTrimming::CheckFacets(const MeshFacetGrid& rclGrid, // remove double elements std::sort(aulAllElements.begin(), aulAllElements.end()); - aulAllElements.erase(std::unique(aulAllElements.begin(), aulAllElements.end()), - aulAllElements.end()); + aulAllElements.erase( + std::unique(aulAllElements.begin(), aulAllElements.end()), + aulAllElements.end() + ); Base::SequencerLauncher seq("Check facets for intersection...", aulAllElements.size()); @@ -177,19 +176,23 @@ bool MeshTrimming::IsPolygonPointInFacet(FacetIndex ulIndex, Base::Vector3f& clP A = clFacPoly[0]; B = clFacPoly[1]; C = clFacPoly[2]; - fDetABC = - static_cast(A.x * B.y + A.y * C.x + B.x * C.y - (B.y * C.x + A.y * B.x + A.x * C.y)); + fDetABC = static_cast( + A.x * B.y + A.y * C.x + B.x * C.y - (B.y * C.x + A.y * B.x + A.x * C.y) + ); for (size_t j = 0; j < myPoly.GetCtVectors(); j++) { // facet contains a polygon point -> calculate the corresponding 3d-point if (clFacPoly.Contains(myPoly[j])) { P = myPoly[j]; - fDetPAC = static_cast(A.x * P.y + A.y * C.x + P.x * C.y - - (P.y * C.x + A.y * P.x + A.x * C.y)); - fDetPBC = static_cast(P.x * B.y + P.y * C.x + B.x * C.y - - (B.y * C.x + P.y * B.x + P.x * C.y)); - fDetPAB = static_cast(A.x * B.y + A.y * P.x + B.x * P.y - - (B.y * P.x + A.y * B.x + A.x * P.y)); + fDetPAC = static_cast( + A.x * P.y + A.y * C.x + P.x * C.y - (P.y * C.x + A.y * P.x + A.x * C.y) + ); + fDetPBC = static_cast( + P.x * B.y + P.y * C.x + B.x * C.y - (B.y * C.x + P.y * B.x + P.x * C.y) + ); + fDetPAB = static_cast( + A.x * B.y + A.y * P.x + B.x * P.y - (B.y * P.x + A.y * B.x + A.x * P.y) + ); u = fDetPBC / fDetABC; v = fDetPAC / fDetABC; w = fDetPAB / fDetABC; @@ -212,7 +215,8 @@ bool MeshTrimming::IsPolygonPointInFacet(FacetIndex ulIndex, Base::Vector3f& clP bool MeshTrimming::GetIntersectionPointsOfPolygonAndFacet( FacetIndex ulIndex, int& iSide, - std::vector& raclPoints) const + std::vector& raclPoints +) const { MeshGeomFacet clFac(myMesh.GetFacet(ulIndex)); Base::Vector2d S; @@ -267,8 +271,9 @@ bool MeshTrimming::GetIntersectionPointsOfPolygonAndFacet( // is intersection point convex combination? if ((std::fabs(l + m - 1.0F) < 0.001F) && (std::fabs(r + s - 1.0F) < 0.001F)) { - Base::Vector3f clIntersection(m * clFac._aclPoints[j] - + l * clFac._aclPoints[(j + 1) % 3]); + Base::Vector3f clIntersection( + m * clFac._aclPoints[j] + l * clFac._aclPoints[(j + 1) % 3] + ); iIntersections++; @@ -370,10 +375,12 @@ void MeshTrimming::AdjustFacet(MeshFacet& facet, int iInd) } } -bool MeshTrimming::CreateFacets(FacetIndex ulFacetPos, - int iSide, - const std::vector& raclPoints, - std::vector& aclNewFacets) +bool MeshTrimming::CreateFacets( + FacetIndex ulFacetPos, + int iSide, + const std::vector& raclPoints, + std::vector& aclNewFacets +) { MeshGeomFacet clFac; @@ -651,11 +658,13 @@ bool MeshTrimming::CreateFacets(FacetIndex ulFacetPos, return true; } -bool MeshTrimming::CreateFacets(FacetIndex ulFacetPos, - int iSide, - const std::vector& raclPoints, - Base::Vector3f& clP3, - std::vector& aclNewFacets) +bool MeshTrimming::CreateFacets( + FacetIndex ulFacetPos, + int iSide, + const std::vector& raclPoints, + Base::Vector3f& clP3, + std::vector& aclNewFacets +) { // no valid triangulation possible if (iSide == -1 || raclPoints.size() < 2) { @@ -670,11 +679,15 @@ bool MeshTrimming::CreateFacets(FacetIndex ulFacetPos, MeshGeomFacet clFac; - float fDistEdgeP1 = clP1.DistanceToLineSegment(myMesh._aclPointArray[facet._aulPoints[1]], - myMesh._aclPointArray[facet._aulPoints[2]]) + float fDistEdgeP1 = clP1.DistanceToLineSegment( + myMesh._aclPointArray[facet._aulPoints[1]], + myMesh._aclPointArray[facet._aulPoints[2]] + ) .Length(); - float fDistEdgeP2 = clP2.DistanceToLineSegment(myMesh._aclPointArray[facet._aulPoints[1]], - myMesh._aclPointArray[facet._aulPoints[2]]) + float fDistEdgeP2 = clP2.DistanceToLineSegment( + myMesh._aclPointArray[facet._aulPoints[1]], + myMesh._aclPointArray[facet._aulPoints[2]] + ) .Length(); // swap P1 and P2 @@ -769,8 +782,10 @@ bool MeshTrimming::CreateFacets(FacetIndex ulFacetPos, return true; } -void MeshTrimming::TrimFacets(const std::vector& raulFacets, - std::vector& aclNewFacets) +void MeshTrimming::TrimFacets( + const std::vector& raulFacets, + std::vector& aclNewFacets +) { Base::Vector3f clP; std::vector clIntsct; diff --git a/src/Mod/Mesh/App/Core/Trim.h b/src/Mod/Mesh/App/Core/Trim.h index aae7691e37..0eb93d63c8 100644 --- a/src/Mod/Mesh/App/Core/Trim.h +++ b/src/Mod/Mesh/App/Core/Trim.h @@ -59,8 +59,7 @@ public: * The facets from raulFacets will be trimmed or deleted and aclNewFacets gives the new * generated facets */ - void TrimFacets(const std::vector& raulFacets, - std::vector& aclNewFacets); + void TrimFacets(const std::vector& raulFacets, std::vector& aclNewFacets); /** * Setter: Trimm INNER or OUTER @@ -81,19 +80,23 @@ private: /** * Creates new facets from edge points of the facet */ - bool CreateFacets(FacetIndex ulFacetPos, - int iSide, - const std::vector& raclPoints, - std::vector& aclNewFacets); + bool CreateFacets( + FacetIndex ulFacetPos, + int iSide, + const std::vector& raclPoints, + std::vector& aclNewFacets + ); /** * Creates new facets from edge points of the facet and a point inside the facet */ - bool CreateFacets(FacetIndex ulFacetPos, - int iSide, - const std::vector& raclPoints, - Base::Vector3f& clP3, - std::vector& aclNewFacets); + bool CreateFacets( + FacetIndex ulFacetPos, + int iSide, + const std::vector& raclPoints, + Base::Vector3f& clP3, + std::vector& aclNewFacets + ); /** * Checks if a polygon point lies within a facet @@ -104,9 +107,11 @@ private: * Calculates the two intersection points between polygonline and facet in 2D * and project the points back into 3D (not very exactly) */ - bool GetIntersectionPointsOfPolygonAndFacet(FacetIndex ulIndex, - int& iSide, - std::vector& raclPoints) const; + bool GetIntersectionPointsOfPolygonAndFacet( + FacetIndex ulIndex, + int& iSide, + std::vector& raclPoints + ) const; void AdjustFacet(MeshFacet& facet, int iInd); diff --git a/src/Mod/Mesh/App/Core/TrimByPlane.cpp b/src/Mod/Mesh/App/Core/TrimByPlane.cpp index e03a5f7ac2..0e86557b79 100644 --- a/src/Mod/Mesh/App/Core/TrimByPlane.cpp +++ b/src/Mod/Mesh/App/Core/TrimByPlane.cpp @@ -36,11 +36,13 @@ MeshTrimByPlane::MeshTrimByPlane(MeshKernel& mesh) : myMesh(mesh) {} -void MeshTrimByPlane::CheckFacets(const MeshFacetGrid& rclGrid, - const Base::Vector3f& base, - const Base::Vector3f& normal, - std::vector& trimFacets, - std::vector& removeFacets) const +void MeshTrimByPlane::CheckFacets( + const MeshFacetGrid& rclGrid, + const Base::Vector3f& base, + const Base::Vector3f& normal, + std::vector& trimFacets, + std::vector& removeFacets +) const { // Go through the grid and check for each cell if its bounding box intersects the plane. // If the box is completely below the plane all facets will be kept, if it's above the @@ -61,8 +63,7 @@ void MeshTrimByPlane::CheckFacets(const MeshFacetGrid& rclGrid, // remove double elements std::sort(checkElements.begin(), checkElements.end()); - checkElements.erase(std::unique(checkElements.begin(), checkElements.end()), - checkElements.end()); + checkElements.erase(std::unique(checkElements.begin(), checkElements.end()), checkElements.end()); trimFacets.reserve(checkElements.size() / 2); // reserve some memory for (FacetIndex element : checkElements) { @@ -81,11 +82,13 @@ void MeshTrimByPlane::CheckFacets(const MeshFacetGrid& rclGrid, removeFacets.erase(std::unique(removeFacets.begin(), removeFacets.end()), removeFacets.end()); } -void MeshTrimByPlane::CreateOneFacet(const Base::Vector3f& base, - const Base::Vector3f& normal, - unsigned short shift, - const MeshGeomFacet& facet, - std::vector& trimmedFacets) const +void MeshTrimByPlane::CreateOneFacet( + const Base::Vector3f& base, + const Base::Vector3f& normal, + unsigned short shift, + const MeshGeomFacet& facet, + std::vector& trimmedFacets +) const { unsigned short nul = shift % 3; unsigned short one = (shift + 1) % 3; @@ -109,11 +112,13 @@ void MeshTrimByPlane::CreateOneFacet(const Base::Vector3f& base, trimmedFacets.push_back(create); } -void MeshTrimByPlane::CreateTwoFacet(const Base::Vector3f& base, - const Base::Vector3f& normal, - unsigned short shift, - const MeshGeomFacet& facet, - std::vector& trimmedFacets) const +void MeshTrimByPlane::CreateTwoFacet( + const Base::Vector3f& base, + const Base::Vector3f& normal, + unsigned short shift, + const MeshGeomFacet& facet, + std::vector& trimmedFacets +) const { unsigned short nul = shift % 3; unsigned short one = (shift + 1) % 3; @@ -142,10 +147,12 @@ void MeshTrimByPlane::CreateTwoFacet(const Base::Vector3f& base, trimmedFacets.push_back(create); } -void MeshTrimByPlane::TrimFacets(const std::vector& trimFacets, - const Base::Vector3f& base, - const Base::Vector3f& normal, - std::vector& trimmedFacets) +void MeshTrimByPlane::TrimFacets( + const std::vector& trimFacets, + const Base::Vector3f& base, + const Base::Vector3f& normal, + std::vector& trimmedFacets +) { trimmedFacets.reserve(2 * trimFacets.size()); for (FacetIndex index : trimFacets) { diff --git a/src/Mod/Mesh/App/Core/TrimByPlane.h b/src/Mod/Mesh/App/Core/TrimByPlane.h index db137264f9..a26245c67c 100644 --- a/src/Mod/Mesh/App/Core/TrimByPlane.h +++ b/src/Mod/Mesh/App/Core/TrimByPlane.h @@ -45,32 +45,40 @@ public: * Checks all facets for intersection with the plane and writes all touched facets into the * vector */ - void CheckFacets(const MeshFacetGrid& rclGrid, - const Base::Vector3f& base, - const Base::Vector3f& normal, - std::vector& trimFacets, - std::vector& removeFacets) const; + void CheckFacets( + const MeshFacetGrid& rclGrid, + const Base::Vector3f& base, + const Base::Vector3f& normal, + std::vector& trimFacets, + std::vector& removeFacets + ) const; /** * The facets from \a trimFacets will be trimmed or deleted and \a trimmedFacets holds the newly * generated facets */ - void TrimFacets(const std::vector& trimFacets, - const Base::Vector3f& base, - const Base::Vector3f& normal, - std::vector& trimmedFacets); + void TrimFacets( + const std::vector& trimFacets, + const Base::Vector3f& base, + const Base::Vector3f& normal, + std::vector& trimmedFacets + ); private: - void CreateOneFacet(const Base::Vector3f& base, - const Base::Vector3f& normal, - unsigned short shift, - const MeshGeomFacet& facet, - std::vector& trimmedFacets) const; - void CreateTwoFacet(const Base::Vector3f& base, - const Base::Vector3f& normal, - unsigned short shift, - const MeshGeomFacet& facet, - std::vector& trimmedFacets) const; + void CreateOneFacet( + const Base::Vector3f& base, + const Base::Vector3f& normal, + unsigned short shift, + const MeshGeomFacet& facet, + std::vector& trimmedFacets + ) const; + void CreateTwoFacet( + const Base::Vector3f& base, + const Base::Vector3f& normal, + unsigned short shift, + const MeshGeomFacet& facet, + std::vector& trimmedFacets + ) const; private: MeshKernel& myMesh; diff --git a/src/Mod/Mesh/App/Core/Visitor.cpp b/src/Mod/Mesh/App/Core/Visitor.cpp index c26e8a409a..1edbc08133 100644 --- a/src/Mod/Mesh/App/Core/Visitor.cpp +++ b/src/Mod/Mesh/App/Core/Visitor.cpp @@ -34,8 +34,7 @@ using namespace MeshCore; -unsigned long MeshKernel::VisitNeighbourFacets(MeshFacetVisitor& rclFVisitor, - FacetIndex ulStartFacet) const +unsigned long MeshKernel::VisitNeighbourFacets(MeshFacetVisitor& rclFVisitor, FacetIndex ulStartFacet) const { unsigned long ulVisited = 0, ulLevel = 0; unsigned long ulCount = _aclFacetArray.size(); @@ -95,8 +94,10 @@ unsigned long MeshKernel::VisitNeighbourFacets(MeshFacetVisitor& rclFVisitor, return ulVisited; } -unsigned long MeshKernel::VisitNeighbourFacetsOverCorners(MeshFacetVisitor& rclFVisitor, - FacetIndex ulStartFacet) const +unsigned long MeshKernel::VisitNeighbourFacetsOverCorners( + MeshFacetVisitor& rclFVisitor, + FacetIndex ulStartFacet +) const { unsigned long ulVisited = 0, ulLevel = 0; MeshRefPointToFacets clRPF(*this); @@ -125,10 +126,7 @@ unsigned long MeshKernel::VisitNeighbourFacetsOverCorners(MeshFacetVisitor& rclF FacetIndex ulFInd = pINb; aclNextLevel.push_back(ulFInd); pFBegin[pINb].SetFlag(MeshFacet::VISIT); - if (!rclFVisitor.Visit(pFBegin[pINb], - raclFAry[*pCurrFacet], - ulFInd, - ulLevel)) { + if (!rclFVisitor.Visit(pFBegin[pINb], raclFAry[*pCurrFacet], ulFInd, ulLevel)) { return ulVisited; } } @@ -143,8 +141,7 @@ unsigned long MeshKernel::VisitNeighbourFacetsOverCorners(MeshFacetVisitor& rclF return ulVisited; } -unsigned long MeshKernel::VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, - PointIndex ulStartPoint) const +unsigned long MeshKernel::VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, PointIndex ulStartPoint) const { unsigned long ulVisited = 0, ulLevel = 0; std::vector aclCurrentLevel, aclNextLevel; @@ -157,8 +154,7 @@ unsigned long MeshKernel::VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, while (!aclCurrentLevel.empty()) { // visit all neighbours of the current level - for (clCurrIter = aclCurrentLevel.begin(); clCurrIter < aclCurrentLevel.end(); - ++clCurrIter) { + for (clCurrIter = aclCurrentLevel.begin(); clCurrIter < aclCurrentLevel.end(); ++clCurrIter) { const std::set& raclNB = clNPs[*clCurrIter]; for (PointIndex pINb : raclNB) { if (!pPBegin[pINb].IsFlag(MeshPoint::VISIT)) { @@ -167,10 +163,7 @@ unsigned long MeshKernel::VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, PointIndex ulPInd = pINb; aclNextLevel.push_back(ulPInd); pPBegin[pINb].SetFlag(MeshPoint::VISIT); - if (!rclPVisitor.Visit(pPBegin[pINb], - *(pPBegin + (*clCurrIter)), - ulPInd, - ulLevel)) { + if (!rclPVisitor.Visit(pPBegin[pINb], *(pPBegin + (*clCurrIter)), ulPInd, ulLevel)) { return ulVisited; } } @@ -186,9 +179,11 @@ unsigned long MeshKernel::VisitNeighbourPoints(MeshPointVisitor& rclPVisitor, // ------------------------------------------------------------------------- -MeshSearchNeighbourFacetsVisitor::MeshSearchNeighbourFacetsVisitor(const MeshKernel& rclMesh, - float fRadius, - FacetIndex ulStartFacetIdx) +MeshSearchNeighbourFacetsVisitor::MeshSearchNeighbourFacetsVisitor( + const MeshKernel& rclMesh, + float fRadius, + FacetIndex ulStartFacetIdx +) : _rclMeshBase(rclMesh) , _clCenter(rclMesh.GetFacet(ulStartFacetIdx).GetGravityPoint()) , _fRadius(fRadius) @@ -202,10 +197,12 @@ std::vector MeshSearchNeighbourFacetsVisitor::GetAndReset() // ------------------------------------------------------------------------- -MeshPlaneVisitor::MeshPlaneVisitor(const MeshKernel& mesh, - FacetIndex index, - float deviation, - std::vector& indices) +MeshPlaneVisitor::MeshPlaneVisitor( + const MeshKernel& mesh, + FacetIndex index, + float deviation, + std::vector& indices +) : mesh(mesh) , indices(indices) , max_deviation(deviation) @@ -224,11 +221,13 @@ MeshPlaneVisitor::~MeshPlaneVisitor() delete fitter; } -bool MeshPlaneVisitor::AllowVisit(const MeshFacet& face, - const MeshFacet&, - FacetIndex, - unsigned long, - unsigned short) +bool MeshPlaneVisitor::AllowVisit( + const MeshFacet& face, + const MeshFacet&, + FacetIndex, + unsigned long, + unsigned short +) { if (!fitter->Done()) { fitter->Fit(); @@ -242,10 +241,7 @@ bool MeshPlaneVisitor::AllowVisit(const MeshFacet& face, return true; } -bool MeshPlaneVisitor::Visit(const MeshFacet& face, - const MeshFacet&, - FacetIndex ulFInd, - unsigned long) +bool MeshPlaneVisitor::Visit(const MeshFacet& face, const MeshFacet&, FacetIndex ulFInd, unsigned long) { MeshGeomFacet triangle = mesh.GetFacet(face); indices.push_back(ulFInd); diff --git a/src/Mod/Mesh/App/Core/Visitor.h b/src/Mod/Mesh/App/Core/Visitor.h index 0a047eb400..be47edb930 100644 --- a/src/Mod/Mesh/App/Core/Visitor.h +++ b/src/Mod/Mesh/App/Core/Visitor.h @@ -56,19 +56,23 @@ public: * If \a true is returned the next iteration is done if there are still facets to visit. * If \a false is returned the calling method stops immediately visiting further facets. */ - virtual bool Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) = 0; + virtual bool Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel + ) = 0; /** Test before a facet will be flagged as VISIT, return false means: go on with * visiting the facets but not this one and set not the VISIT flag */ - virtual bool AllowVisit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel, - unsigned short neighbourIndex) + virtual bool AllowVisit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel, + unsigned short neighbourIndex + ) { (void)rclFacet; (void)rclFrom; @@ -85,15 +89,15 @@ public: class MeshExport MeshSearchNeighbourFacetsVisitor: public MeshFacetVisitor { public: - MeshSearchNeighbourFacetsVisitor(const MeshKernel& rclMesh, - float fRadius, - FacetIndex ulStartFacetIdx); + MeshSearchNeighbourFacetsVisitor(const MeshKernel& rclMesh, float fRadius, FacetIndex ulStartFacetIdx); ~MeshSearchNeighbourFacetsVisitor() override = default; /** Checks the facet if it lies inside the search radius. */ - inline bool Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) override; + inline bool Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel + ) override; /** Resets the VISIT flag of already visited facets. */ inline std::vector GetAndReset(); @@ -106,10 +110,12 @@ protected: std::vector _vecFacets; /**< Found facets. */ }; -inline bool MeshSearchNeighbourFacetsVisitor::Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long ulLevel) +inline bool MeshSearchNeighbourFacetsVisitor::Visit( + const MeshFacet& rclFacet, + const MeshFacet& rclFrom, + FacetIndex ulFInd, + unsigned long ulLevel +) { (void)rclFrom; if (ulLevel > _ulCurrentLevel) { @@ -142,10 +148,7 @@ public: {} ~MeshTopFacetVisitor() override = default; /** Collects the facet indices. */ - bool Visit(const MeshFacet& rclFacet, - const MeshFacet& rclFrom, - FacetIndex ulFInd, - unsigned long) override + bool Visit(const MeshFacet& rclFacet, const MeshFacet& rclFrom, FacetIndex ulFInd, unsigned long) override { (void)rclFacet; (void)rclFrom; @@ -166,16 +169,20 @@ protected: class MeshPlaneVisitor: public MeshFacetVisitor { public: - MeshPlaneVisitor(const MeshKernel& mesh, - FacetIndex index, - float deviation, - std::vector& indices); + MeshPlaneVisitor( + const MeshKernel& mesh, + FacetIndex index, + float deviation, + std::vector& indices + ); ~MeshPlaneVisitor() override; - bool AllowVisit(const MeshFacet& face, - const MeshFacet&, - FacetIndex, - unsigned long, - unsigned short neighbourIndex) override; + bool AllowVisit( + const MeshFacet& face, + const MeshFacet&, + FacetIndex, + unsigned long, + unsigned short neighbourIndex + ) override; bool Visit(const MeshFacet& face, const MeshFacet&, FacetIndex ulFInd, unsigned long) override; protected: @@ -205,10 +212,12 @@ public: * If \a true is returned the next iteration is done if there are still point to visit. If * \a false is returned the calling method stops immediately visiting further points. */ - virtual bool Visit(const MeshPoint& rclPoint, - const MeshPoint& rclFrom, - FacetIndex ulPInd, - unsigned long ulLevel) = 0; + virtual bool Visit( + const MeshPoint& rclPoint, + const MeshPoint& rclFrom, + FacetIndex ulPInd, + unsigned long ulLevel + ) = 0; }; } // namespace MeshCore diff --git a/src/Mod/Mesh/App/EdgePyImp.cpp b/src/Mod/Mesh/App/EdgePyImp.cpp index 7825e1c79d..31abf1318e 100644 --- a/src/Mod/Mesh/App/EdgePyImp.cpp +++ b/src/Mod/Mesh/App/EdgePyImp.cpp @@ -69,22 +69,19 @@ int EdgePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* pt1 = nullptr; PyObject* pt2 = nullptr; - if (!PyArg_ParseTuple(args, - "|O!O!", - &Base::VectorPy::Type, - &pt1, - &Base::VectorPy::Type, - &pt2)) { + if (!PyArg_ParseTuple(args, "|O!O!", &Base::VectorPy::Type, &pt1, &Base::VectorPy::Type, &pt2)) { return -1; } if (pt1) { - getEdgePtr()->_aclPoints[0] = - Base::convertTo(Py::Vector(pt1, false).toVector()); + getEdgePtr()->_aclPoints[0] = Base::convertTo( + Py::Vector(pt1, false).toVector() + ); } if (pt2) { - getEdgePtr()->_aclPoints[1] = - Base::convertTo(Py::Vector(pt2, false).toVector()); + getEdgePtr()->_aclPoints[1] = Base::convertTo( + Py::Vector(pt2, false).toVector() + ); } return 0; } diff --git a/src/Mod/Mesh/App/Exporter.cpp b/src/Mod/Mesh/App/Exporter.cpp index 90d5da9b75..e4e90613bb 100644 --- a/src/Mod/Mesh/App/Exporter.cpp +++ b/src/Mod/Mesh/App/Exporter.cpp @@ -51,7 +51,8 @@ using namespace MeshCore; static std::vector expandSubObjectNames( const App::DocumentObject* obj, std::map>& subObjectNameCache, - int depth) + int depth +) { if (!App::GetApplication().checkLinkDepth(depth)) { return {}; @@ -111,8 +112,7 @@ int Exporter::addObject(App::DocumentObject* obj, float tol) auto it = meshCache.find(linked); if (it == meshCache.end()) { if (linked->isDerivedFrom()) { - it = meshCache.emplace(linked, static_cast(linked)->Mesh.getValue()) - .first; + it = meshCache.emplace(linked, static_cast(linked)->Mesh.getValue()).first; it->second.setTransform(matrix); } else { @@ -125,8 +125,7 @@ int Exporter::addObject(App::DocumentObject* obj, float tol) if (PyObject_TypeCheck(pyobj, &Data::ComplexGeoDataPy::Type)) { std::vector aPoints; std::vector aTopo; - auto geoData = - static_cast(pyobj)->getComplexGeoDataPtr(); + auto geoData = static_cast(pyobj)->getComplexGeoDataPtr(); geoData->getFaces(aPoints, aTopo, tol); it = meshCache.emplace(linked, MeshObject()).first; it->second.setFacets(aTopo, aPoints); @@ -328,9 +327,7 @@ void Exporter3MF::write() // ---------------------------------------------------------------------------- -ExporterAMF::ExporterAMF(std::string fileName, - const std::map& meta, - bool compress) +ExporterAMF::ExporterAMF(std::string fileName, const std::map& meta, bool compress) { // ask for write permission throwIfNoPermission(fileName); diff --git a/src/Mod/Mesh/App/Exporter.h b/src/Mod/Mesh/App/Exporter.h index f16d5c7554..17dbc1ac33 100644 --- a/src/Mod/Mesh/App/Exporter.h +++ b/src/Mod/Mesh/App/Exporter.h @@ -244,9 +244,11 @@ public: /*! * meta information passed in is applied at the tag level */ - ExporterAMF(std::string fileName, - const std::map& meta, - bool compress = true); + ExporterAMF( + std::string fileName, + const std::map& meta, + bool compress = true + ); /// Writes AMF footer ~ExporterAMF() override; diff --git a/src/Mod/Mesh/App/Facet.cpp b/src/Mod/Mesh/App/Facet.cpp index 0e95d7358f..d622232ed5 100644 --- a/src/Mod/Mesh/App/Facet.cpp +++ b/src/Mod/Mesh/App/Facet.cpp @@ -31,9 +31,11 @@ using namespace Mesh; -Facet::Facet(const MeshCore::MeshFacet& face, // NOLINT - const MeshObject* obj, - MeshCore::FacetIndex index) +Facet::Facet( + const MeshCore::MeshFacet& face, // NOLINT + const MeshObject* obj, + MeshCore::FacetIndex index +) : Index(index) , Mesh(obj) { diff --git a/src/Mod/Mesh/App/Facet.h b/src/Mod/Mesh/App/Facet.h index 198df8aa19..a8bbc5bff7 100644 --- a/src/Mod/Mesh/App/Facet.h +++ b/src/Mod/Mesh/App/Facet.h @@ -41,9 +41,11 @@ class MeshObject; class MeshExport Facet: public MeshCore::MeshGeomFacet { public: - explicit Facet(const MeshCore::MeshFacet& face = MeshCore::MeshFacet(), - const MeshObject* obj = nullptr, - MeshCore::FacetIndex index = MeshCore::FACET_INDEX_MAX); + explicit Facet( + const MeshCore::MeshFacet& face = MeshCore::MeshFacet(), + const MeshObject* obj = nullptr, + MeshCore::FacetIndex index = MeshCore::FACET_INDEX_MAX + ); Facet(const Facet& f); Facet(Facet&& f); ~Facet(); diff --git a/src/Mod/Mesh/App/FeatureMeshExport.h b/src/Mod/Mesh/App/FeatureMeshExport.h index 48b9c5f95a..33da53d337 100644 --- a/src/Mod/Mesh/App/FeatureMeshExport.h +++ b/src/Mod/Mesh/App/FeatureMeshExport.h @@ -29,7 +29,7 @@ #include #ifndef MESH_GLOBAL_H -#include +# include #endif namespace Mesh diff --git a/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp b/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp index 122389323d..505adb0091 100644 --- a/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp +++ b/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp @@ -88,15 +88,19 @@ App::DocumentObjectExecReturn* SetOperations::execute() type = MeshCore::SetOperations::Outer; } else { - throw Base::ValueError("Operation type must either be 'union' or 'intersection'" - " or 'difference' or 'inner' or 'outer'"); + throw Base::ValueError( + "Operation type must either be 'union' or 'intersection'" + " or 'difference' or 'inner' or 'outer'" + ); } - MeshCore::SetOperations setOp(meshKernel1.getKernel(), - meshKernel2.getKernel(), - pcKernel->getKernel(), - type, - 1.0e-5F); + MeshCore::SetOperations setOp( + meshKernel1.getKernel(), + meshKernel2.getKernel(), + pcKernel->getKernel(), + type, + 1.0e-5F + ); setOp.Do(); Mesh.setValuePtr(pcKernel.release()); } diff --git a/src/Mod/Mesh/App/FeatureMeshSolid.cpp b/src/Mod/Mesh/App/FeatureMeshSolid.cpp index 83868d6de6..3b28b45f9f 100644 --- a/src/Mod/Mesh/App/FeatureMeshSolid.cpp +++ b/src/Mod/Mesh/App/FeatureMeshSolid.cpp @@ -31,9 +31,7 @@ namespace Mesh { -const App::PropertyIntegerConstraint::Constraints intSampling = {0, - std::numeric_limits::max(), - 1}; +const App::PropertyIntegerConstraint::Constraints intSampling = {0, std::numeric_limits::max(), 1}; const App::PropertyLength::Constraints floatRange = {0.0, std::numeric_limits::max(), 1.0}; } // namespace Mesh @@ -61,7 +59,8 @@ short Sphere::mustExecute() const App::DocumentObjectExecReturn* Sphere::execute() { std::unique_ptr mesh( - MeshObject::createSphere((float)Radius.getValue(), Sampling.getValue())); + MeshObject::createSphere((float)Radius.getValue(), Sampling.getValue()) + ); if (mesh) { mesh->setPlacement(this->Placement.getValue()); Mesh.setValue(mesh->getKernel()); @@ -71,9 +70,7 @@ App::DocumentObjectExecReturn* Sphere::execute() return new App::DocumentObjectExecReturn("Cannot create sphere", this); } -void Sphere::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Sphere::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { if (prop == &Radius && strcmp(TypeName, "App::PropertyFloatConstraint") == 0) { App::PropertyFloatConstraint r; @@ -109,9 +106,13 @@ short Ellipsoid::mustExecute() const App::DocumentObjectExecReturn* Ellipsoid::execute() { - std::unique_ptr mesh(MeshObject::createEllipsoid((float)Radius1.getValue(), - (float)Radius2.getValue(), - Sampling.getValue())); + std::unique_ptr mesh( + MeshObject::createEllipsoid( + (float)Radius1.getValue(), + (float)Radius2.getValue(), + Sampling.getValue() + ) + ); if (mesh) { mesh->setPlacement(this->Placement.getValue()); Mesh.setValue(mesh->getKernel()); @@ -121,9 +122,11 @@ App::DocumentObjectExecReturn* Ellipsoid::execute() return new App::DocumentObjectExecReturn("Cannot create ellipsoid", this); } -void Ellipsoid::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Ellipsoid::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { if ((prop == &Radius1 || prop == &Radius2) && strcmp(TypeName, "App::PropertyFloatConstraint") == 0) { @@ -164,11 +167,15 @@ short Cylinder::mustExecute() const App::DocumentObjectExecReturn* Cylinder::execute() { - std::unique_ptr mesh(MeshObject::createCylinder((float)Radius.getValue(), - (float)Length.getValue(), - Closed.getValue(), - (float)EdgeLength.getValue(), - Sampling.getValue())); + std::unique_ptr mesh( + MeshObject::createCylinder( + (float)Radius.getValue(), + (float)Length.getValue(), + Closed.getValue(), + (float)EdgeLength.getValue(), + Sampling.getValue() + ) + ); if (mesh) { mesh->setPlacement(this->Placement.getValue()); Mesh.setValue(mesh->getKernel()); @@ -178,9 +185,7 @@ App::DocumentObjectExecReturn* Cylinder::execute() return new App::DocumentObjectExecReturn("Cannot create cylinder", this); } -void Cylinder::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Cylinder::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { if ((prop == &Radius || prop == &Length || prop == &EdgeLength) && strcmp(TypeName, "App::PropertyFloatConstraint") == 0) { @@ -223,12 +228,16 @@ short Cone::mustExecute() const App::DocumentObjectExecReturn* Cone::execute() { - std::unique_ptr mesh(MeshObject::createCone((float)Radius1.getValue(), - (float)Radius2.getValue(), - (float)Length.getValue(), - Closed.getValue(), - (float)EdgeLength.getValue(), - Sampling.getValue())); + std::unique_ptr mesh( + MeshObject::createCone( + (float)Radius1.getValue(), + (float)Radius2.getValue(), + (float)Length.getValue(), + Closed.getValue(), + (float)EdgeLength.getValue(), + Sampling.getValue() + ) + ); if (mesh) { mesh->setPlacement(this->Placement.getValue()); Mesh.setValue(mesh->getKernel()); @@ -238,9 +247,7 @@ App::DocumentObjectExecReturn* Cone::execute() return new App::DocumentObjectExecReturn("Cannot create cone", this); } -void Cone::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Cone::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { if ((prop == &Radius1 || prop == &Radius2 || prop == &Length || prop == &EdgeLength) && strcmp(TypeName, "App::PropertyFloatConstraint") == 0) { @@ -277,9 +284,9 @@ short Torus::mustExecute() const App::DocumentObjectExecReturn* Torus::execute() { - std::unique_ptr mesh(MeshObject::createTorus((float)Radius1.getValue(), - (float)Radius2.getValue(), - Sampling.getValue())); + std::unique_ptr mesh( + MeshObject::createTorus((float)Radius1.getValue(), (float)Radius2.getValue(), Sampling.getValue()) + ); if (mesh) { mesh->setPlacement(this->Placement.getValue()); Mesh.setValue(mesh->getKernel()); @@ -289,9 +296,7 @@ App::DocumentObjectExecReturn* Torus::execute() return new App::DocumentObjectExecReturn("Cannot create torus", this); } -void Torus::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Torus::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { if ((prop == &Radius1 || prop == &Radius2) && strcmp(TypeName, "App::PropertyFloatConstraint") == 0) { @@ -328,9 +333,9 @@ short Cube::mustExecute() const App::DocumentObjectExecReturn* Cube::execute() { - std::unique_ptr mesh(MeshObject::createCube((float)Length.getValue(), - (float)Width.getValue(), - (float)Height.getValue())); + std::unique_ptr mesh( + MeshObject::createCube((float)Length.getValue(), (float)Width.getValue(), (float)Height.getValue()) + ); if (mesh) { mesh->setPlacement(this->Placement.getValue()); Mesh.setValue(mesh->getKernel()); @@ -340,9 +345,7 @@ App::DocumentObjectExecReturn* Cube::execute() return new App::DocumentObjectExecReturn("Cannot create cube", this); } -void Cube::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Cube::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { if ((prop == &Length || prop == &Width || prop == &Height) && strcmp(TypeName, "App::PropertyFloatConstraint") == 0) { diff --git a/src/Mod/Mesh/App/FeatureMeshSolid.h b/src/Mod/Mesh/App/FeatureMeshSolid.h index 07220c66be..c77668d989 100644 --- a/src/Mod/Mesh/App/FeatureMeshSolid.h +++ b/src/Mod/Mesh/App/FeatureMeshSolid.h @@ -51,9 +51,11 @@ public: /// recalculate the Feature App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; //@} }; @@ -75,9 +77,11 @@ public: /// recalculate the Feature App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; //@} }; @@ -101,9 +105,11 @@ public: /// recalculate the Feature App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; //@} }; @@ -128,9 +134,11 @@ public: /// recalculate the Feature App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; //@} }; @@ -152,9 +160,11 @@ public: /// recalculate the Feature App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; //@} }; @@ -176,9 +186,11 @@ public: /// recalculate the Feature App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; //@} }; diff --git a/src/Mod/Mesh/App/Importer.cpp b/src/Mod/Mesh/App/Importer.cpp index bb027b89f4..96ba80444e 100644 --- a/src/Mod/Mesh/App/Importer.cpp +++ b/src/Mod/Mesh/App/Importer.cpp @@ -76,20 +76,21 @@ void Importer::addFaceColors(Feature* feature, const std::vector& c addColors(feature, "FaceColors", colors); } -void Importer::addColors(Feature* feature, - const std::string& property, - const std::vector& colors) +void Importer::addColors( + Feature* feature, + const std::string& property, + const std::vector& colors +) { App::PropertyColorList* prop = static_cast( - feature->addDynamicProperty("App::PropertyColorList", property.c_str())); + feature->addDynamicProperty("App::PropertyColorList", property.c_str()) + ); if (prop) { prop->setValues(colors); } } -void Importer::createMeshFromSegments(const std::string& name, - MeshCore::Material& mat, - MeshObject& mesh) +void Importer::createMeshFromSegments(const std::string& name, MeshCore::Material& mat, MeshObject& mesh) { unsigned long segmct = mesh.countSegments(); for (unsigned long i = 0; i < segmct; i++) { diff --git a/src/Mod/Mesh/App/Mesh.cpp b/src/Mod/Mesh/App/Mesh.cpp index a33f4748d3..8734244490 100644 --- a/src/Mod/Mesh/App/Mesh.cpp +++ b/src/Mod/Mesh/App/Mesh.cpp @@ -127,25 +127,30 @@ Data::Segment* MeshObject::getSubElement(const char* Type, unsigned long n) cons MeshSegment* segm = new MeshSegment(); segm->mesh = new MeshObject(*this); const Segment& faces = getSegment(n); - segm->segment = std::make_unique(static_cast(segm->mesh), - faces.getIndices(), - false); + segm->segment = std::make_unique( + static_cast(segm->mesh), + faces.getIndices(), + false + ); return segm; } return nullptr; } -void MeshObject::getFacesFromSubElement(const Data::Segment* element, - std::vector& points, - std::vector& /*pointNormals*/, - std::vector& faces) const +void MeshObject::getFacesFromSubElement( + const Data::Segment* element, + std::vector& points, + std::vector& /*pointNormals*/, + std::vector& faces +) const { if (element && element->is()) { const MeshSegment* segm = static_cast(element); if (segm->segment) { Base::Reference submesh( - segm->mesh->meshFromSegment(segm->segment->getIndices())); + segm->mesh->meshFromSegment(segm->segment->getIndices()) + ); submesh->getFaces(points, faces, 0.0); } else { @@ -328,10 +333,12 @@ MeshPoint MeshObject::getMeshPoint(PointIndex index) const return point; } -void MeshObject::getPoints(std::vector& Points, - std::vector& Normals, - double /*Accuracy*/, - uint16_t /*flags*/) const +void MeshObject::getPoints( + std::vector& Points, + std::vector& Normals, + double /*Accuracy*/, + uint16_t /*flags*/ +) const { Points = transformPointsToOutside(_kernel.GetPoints()); MeshCore::MeshRefNormalToPoints ptNormals(_kernel); @@ -344,10 +351,8 @@ Mesh::Facet MeshObject::getMeshFacet(FacetIndex index) const return face; } -void MeshObject::getFaces(std::vector& Points, - std::vector& Topo, - double /*Accuracy*/, - uint16_t /*flags*/) const +void MeshObject:: + getFaces(std::vector& Points, std::vector& Topo, double /*Accuracy*/, uint16_t /*flags*/) const { unsigned long ctpoints = _kernel.CountPoints(); Points.reserve(ctpoints); @@ -392,10 +397,12 @@ void MeshObject::RestoreDocFile(Base::Reader& reader) load(reader); } -void MeshObject::save(const char* file, - MeshCore::MeshIO::Format f, - const MeshCore::Material* mat, - const char* objectname) const +void MeshObject::save( + const char* file, + MeshCore::MeshIO::Format f, + const MeshCore::Material* mat, + const char* objectname +) const { MeshCore::MeshOutput aWriter(this->_kernel, mat); if (objectname) { @@ -423,10 +430,12 @@ void MeshObject::save(const char* file, aWriter.SaveAny(file, f); } -void MeshObject::save(std::ostream& str, - MeshCore::MeshIO::Format f, - const MeshCore::Material* mat, - const char* objectname) const +void MeshObject::save( + std::ostream& str, + MeshCore::MeshIO::Format f, + const MeshCore::Material* mat, + const char* objectname +) const { MeshCore::MeshOutput aWriter(this->_kernel, mat); if (objectname) { @@ -586,16 +595,20 @@ void MeshObject::addFacets(const std::vector& facets, bool _kernel.AddFacets(facets, checkManifolds); } -void MeshObject::addFacets(const std::vector& facets, - const std::vector& points, - bool checkManifolds) +void MeshObject::addFacets( + const std::vector& facets, + const std::vector& points, + bool checkManifolds +) { _kernel.AddFacets(facets, points, checkManifolds); } -void MeshObject::addFacets(const std::vector& facets, - const std::vector& points, - bool checkManifolds) +void MeshObject::addFacets( + const std::vector& facets, + const std::vector& points, + bool checkManifolds +) { std::vector facet_v; facet_v.reserve(facets.size()); @@ -622,8 +635,10 @@ void MeshObject::setFacets(const std::vector& facets) _kernel = facets; } -void MeshObject::setFacets(const std::vector& facets, - const std::vector& points) +void MeshObject::setFacets( + const std::vector& facets, + const std::vector& points +) { MeshCore::MeshFacetArray facet_v; facet_v.reserve(facets.size()); @@ -792,9 +807,11 @@ std::vector MeshObject::getPointsFromFacets(const std::vector(ray.first); Base::Vector3f dir = Base::toVector(ray.second); @@ -898,8 +915,10 @@ void MeshObject::removeComponents(unsigned long count) deletedFacets(removeIndices); } -unsigned long MeshObject::getPointDegree(const std::vector& indices, - std::vector& point_degree) const +unsigned long MeshObject::getPointDegree( + const std::vector& indices, + std::vector& point_degree +) const { const MeshCore::MeshFacetArray& faces = _kernel.GetFacets(); std::vector pointDeg(_kernel.CountPoints()); @@ -925,9 +944,7 @@ unsigned long MeshObject::getPointDegree(const std::vector& indices, return countInvalids; } -void MeshObject::fillupHoles(unsigned long length, - int level, - MeshCore::AbstractPolygonTriangulator& cTria) +void MeshObject::fillupHoles(unsigned long length, int level, MeshCore::AbstractPolygonTriangulator& cTria) { std::list> aFailed; MeshCore::MeshTopoAlgorithm topalg(_kernel); @@ -979,14 +996,18 @@ void MeshObject::offsetSpecial2(float fSize) continue; } // calculate the angle between them - float angle = acos((FaceNormals[i] * it->GetNormal()) - / (it->GetNormal().Length() * FaceNormals[i].Length())); + float angle = acos( + (FaceNormals[i] * it->GetNormal()) + / (it->GetNormal().Length() * FaceNormals[i].Length()) + ); if (angle > 1.6) { Base::DrawStyle drawStyle; drawStyle.pointSize = 4.0F; - Base::PointItem item {it->GetGravityPoint(), - drawStyle, - Base::ColorRGB {1.0F, 0.0F, 0.0F}}; + Base::PointItem item { + it->GetGravityPoint(), + drawStyle, + Base::ColorRGB {1.0F, 0.0F, 0.0F} + }; builder.addNode(item); flipped.insert(it.Position()); } @@ -1107,10 +1128,12 @@ std::vector MeshObject::getPointNormals() const return normals; } -void MeshObject::crossSections(const std::vector& planes, - std::vector& sections, - float fMinEps, - bool bConnectPolygons) const +void MeshObject::crossSections( + const std::vector& planes, + std::vector& sections, + float fMinEps, + bool bConnectPolygons +) const { MeshCore::MeshKernel kernel(this->_kernel); kernel.Transform(this->_Mtrx); @@ -1124,9 +1147,11 @@ void MeshObject::crossSections(const std::vector& planes, } } -void MeshObject::cut(const Base::Polygon2d& polygon2d, - const Base::ViewProjMethod& proj, - MeshObject::CutType type) +void MeshObject::cut( + const Base::Polygon2d& polygon2d, + const Base::ViewProjMethod& proj, + MeshObject::CutType type +) { MeshCore::MeshKernel kernel(this->_kernel); kernel.Transform(getTransform()); @@ -1154,9 +1179,11 @@ void MeshObject::cut(const Base::Polygon2d& polygon2d, } } -void MeshObject::trim(const Base::Polygon2d& polygon2d, - const Base::ViewProjMethod& proj, - MeshObject::CutType type) +void MeshObject::trim( + const Base::Polygon2d& polygon2d, + const Base::ViewProjMethod& proj, + MeshObject::CutType type +) { MeshCore::MeshKernel kernel(this->_kernel); kernel.Transform(getTransform()); @@ -1224,11 +1251,7 @@ MeshObject* MeshObject::unite(const MeshObject& mesh) const kernel1.Transform(this->_Mtrx); MeshCore::MeshKernel kernel2(mesh._kernel); kernel2.Transform(mesh._Mtrx); - MeshCore::SetOperations setOp(kernel1, - kernel2, - result, - MeshCore::SetOperations::Union, - Epsilon); + MeshCore::SetOperations setOp(kernel1, kernel2, result, MeshCore::SetOperations::Union, Epsilon); setOp.Do(); return new MeshObject(result); } @@ -1240,11 +1263,7 @@ MeshObject* MeshObject::intersect(const MeshObject& mesh) const kernel1.Transform(this->_Mtrx); MeshCore::MeshKernel kernel2(mesh._kernel); kernel2.Transform(mesh._Mtrx); - MeshCore::SetOperations setOp(kernel1, - kernel2, - result, - MeshCore::SetOperations::Intersect, - Epsilon); + MeshCore::SetOperations setOp(kernel1, kernel2, result, MeshCore::SetOperations::Intersect, Epsilon); setOp.Do(); return new MeshObject(result); } @@ -1256,11 +1275,7 @@ MeshObject* MeshObject::subtract(const MeshObject& mesh) const kernel1.Transform(this->_Mtrx); MeshCore::MeshKernel kernel2(mesh._kernel); kernel2.Transform(mesh._Mtrx); - MeshCore::SetOperations setOp(kernel1, - kernel2, - result, - MeshCore::SetOperations::Difference, - Epsilon); + MeshCore::SetOperations setOp(kernel1, kernel2, result, MeshCore::SetOperations::Difference, Epsilon); setOp.Do(); return new MeshObject(result); } @@ -1272,11 +1287,7 @@ MeshObject* MeshObject::inner(const MeshObject& mesh) const kernel1.Transform(this->_Mtrx); MeshCore::MeshKernel kernel2(mesh._kernel); kernel2.Transform(mesh._Mtrx); - MeshCore::SetOperations setOp(kernel1, - kernel2, - result, - MeshCore::SetOperations::Inner, - Epsilon); + MeshCore::SetOperations setOp(kernel1, kernel2, result, MeshCore::SetOperations::Inner, Epsilon); setOp.Do(); return new MeshObject(result); } @@ -1288,17 +1299,16 @@ MeshObject* MeshObject::outer(const MeshObject& mesh) const kernel1.Transform(this->_Mtrx); MeshCore::MeshKernel kernel2(mesh._kernel); kernel2.Transform(mesh._Mtrx); - MeshCore::SetOperations setOp(kernel1, - kernel2, - result, - MeshCore::SetOperations::Outer, - Epsilon); + MeshCore::SetOperations setOp(kernel1, kernel2, result, MeshCore::SetOperations::Outer, Epsilon); setOp.Do(); return new MeshObject(result); } -std::vector> -MeshObject::section(const MeshObject& mesh, bool connectLines, float fMinDist) const +std::vector> MeshObject::section( + const MeshObject& mesh, + bool connectLines, + float fMinDist +) const { MeshCore::MeshKernel kernel1(this->_kernel); kernel1.Transform(this->_Mtrx); @@ -1402,8 +1412,7 @@ void MeshObject::splitEdges() int id = 2; if (pF->_aulNeighbours[id] != MeshCore::FACET_INDEX_MAX) { const MeshCore::MeshFacet& rFace = rFacets[pF->_aulNeighbours[id]]; - if (!pF->IsFlag(MeshCore::MeshFacet::VISIT) - && !rFace.IsFlag(MeshCore::MeshFacet::VISIT)) { + if (!pF->IsFlag(MeshCore::MeshFacet::VISIT) && !rFace.IsFlag(MeshCore::MeshFacet::VISIT)) { pF->SetFlag(MeshCore::MeshFacet::VISIT); rFace.SetFlag(MeshCore::MeshFacet::VISIT); adjacentFacet.emplace_back(pF - rFacets.begin(), pF->_aulNeighbours[id]); @@ -1544,8 +1553,7 @@ MeshObject::TFacePairs MeshObject::getSelfIntersections() const return pairs; } -std::vector -MeshObject::getSelfIntersections(const MeshObject::TFacePairs& facets) const +std::vector MeshObject::getSelfIntersections(const MeshObject::TFacePairs& facets) const { MeshCore::MeshEvalSelfIntersection eval(getKernel()); using Section = std::pair; @@ -1556,13 +1564,17 @@ MeshObject::getSelfIntersections(const MeshObject::TFacePairs& facets) const lines.reserve(selfPoints.size()); Base::Matrix4D mat(getTransform()); - std::transform(selfPoints.begin(), - selfPoints.end(), - std::back_inserter(lines), - [&mat](const Section& l) { - return Base::Line3d(mat * Base::convertTo(l.first), - mat * Base::convertTo(l.second)); - }); + std::transform( + selfPoints.begin(), + selfPoints.end(), + std::back_inserter(lines), + [&mat](const Section& l) { + return Base::Line3d( + mat * Base::convertTo(l.first), + mat * Base::convertTo(l.second) + ); + } + ); return lines; } @@ -1585,11 +1597,11 @@ void MeshObject::removeSelfIntersections(const std::vector& indices) return; } unsigned long cntfacets = _kernel.CountFacets(); - if (std::find_if(indices.begin(), - indices.end(), - [cntfacets](FacetIndex v) { - return v >= cntfacets; - }) + if (std::find_if( + indices.begin(), + indices.end(), + [cntfacets](FacetIndex v) { return v >= cntfacets; } + ) < indices.end()) { return; } @@ -1745,11 +1757,8 @@ bool MeshObject::hasCorruptedFacets() const void MeshObject::validateDeformations(float fMaxAngle, float fEps) { unsigned long count = _kernel.CountFacets(); - MeshCore::MeshFixDeformedFacets eval(_kernel, - Base::toRadians(15.0F), - Base::toRadians(150.0F), - fMaxAngle, - fEps); + MeshCore::MeshFixDeformedFacets + eval(_kernel, Base::toRadians(15.0F), Base::toRadians(150.0F), fMaxAngle, fEps); eval.Fixup(); if (_kernel.CountFacets() < count) { this->_segments.clear(); @@ -1860,8 +1869,7 @@ MeshObject* MeshObject::createEllipsoid(float radius1, float radius2, int sampli return nullptr; } -MeshObject* -MeshObject::createCylinder(float radius, float length, int closed, float edgelen, int sampling) +MeshObject* MeshObject::createCylinder(float radius, float length, int closed, float edgelen, int sampling) { // load the 'BuildRegularGeoms' module Base::PyGILStateLocker lock; @@ -1888,12 +1896,14 @@ MeshObject::createCylinder(float radius, float length, int closed, float edgelen return nullptr; } -MeshObject* MeshObject::createCone(float radius1, - float radius2, - float len, - int closed, - float edgelen, - int sampling) +MeshObject* MeshObject::createCone( + float radius1, + float radius2, + float len, + int closed, + float edgelen, + int sampling +) { // load the 'BuildRegularGeoms' module Base::PyGILStateLocker lock; @@ -2076,9 +2086,11 @@ MeshObject* MeshObject::meshFromSegment(const std::vector& indices) return new MeshObject(kernel, _Mtrx); } -std::vector MeshObject::getSegmentsOfType(MeshObject::GeometryType type, - float dev, - unsigned long minFacets) const +std::vector MeshObject::getSegmentsOfType( + MeshObject::GeometryType type, + float dev, + unsigned long minFacets +) const { std::vector segm; if (this->_kernel.CountFacets() == 0) { @@ -2089,25 +2101,28 @@ std::vector MeshObject::getSegmentsOfType(MeshObject::GeometryType type std::shared_ptr surf; switch (type) { case PLANE: - surf.reset( - new MeshCore::MeshDistanceGenericSurfaceFitSegment(new MeshCore::PlaneSurfaceFit, - this->_kernel, - minFacets, - dev)); + surf.reset(new MeshCore::MeshDistanceGenericSurfaceFitSegment( + new MeshCore::PlaneSurfaceFit, + this->_kernel, + minFacets, + dev + )); break; case CYLINDER: - surf.reset( - new MeshCore::MeshDistanceGenericSurfaceFitSegment(new MeshCore::CylinderSurfaceFit, - this->_kernel, - minFacets, - dev)); + surf.reset(new MeshCore::MeshDistanceGenericSurfaceFitSegment( + new MeshCore::CylinderSurfaceFit, + this->_kernel, + minFacets, + dev + )); break; case SPHERE: - surf.reset( - new MeshCore::MeshDistanceGenericSurfaceFitSegment(new MeshCore::SphereSurfaceFit, - this->_kernel, - minFacets, - dev)); + surf.reset(new MeshCore::MeshDistanceGenericSurfaceFitSegment( + new MeshCore::SphereSurfaceFit, + this->_kernel, + minFacets, + dev + )); break; default: break; @@ -2138,19 +2153,21 @@ MeshObject::const_point_iterator::const_point_iterator(const MeshObject* mesh, P this->_point.Mesh = _mesh; } -MeshObject::const_point_iterator::const_point_iterator(const MeshObject::const_point_iterator& pi) = - default; +MeshObject::const_point_iterator::const_point_iterator( + const MeshObject::const_point_iterator& pi +) = default; -MeshObject::const_point_iterator::const_point_iterator(MeshObject::const_point_iterator&& pi) = - default; +MeshObject::const_point_iterator::const_point_iterator(MeshObject::const_point_iterator&& pi) = default; MeshObject::const_point_iterator::~const_point_iterator() = default; -MeshObject::const_point_iterator& -MeshObject::const_point_iterator::operator=(const MeshObject::const_point_iterator& pi) = default; +MeshObject::const_point_iterator& MeshObject::const_point_iterator::operator=( + const MeshObject::const_point_iterator& pi +) = default; -MeshObject::const_point_iterator& -MeshObject::const_point_iterator::operator=(MeshObject::const_point_iterator&& pi) = default; +MeshObject::const_point_iterator& MeshObject::const_point_iterator::operator=( + MeshObject::const_point_iterator&& pi +) = default; void MeshObject::const_point_iterator::dereference() { @@ -2205,19 +2222,21 @@ MeshObject::const_facet_iterator::const_facet_iterator(const MeshObject* mesh, F this->_facet.Mesh = _mesh; } -MeshObject::const_facet_iterator::const_facet_iterator(const MeshObject::const_facet_iterator& fi) = - default; +MeshObject::const_facet_iterator::const_facet_iterator( + const MeshObject::const_facet_iterator& fi +) = default; -MeshObject::const_facet_iterator::const_facet_iterator(MeshObject::const_facet_iterator&& fi) = - default; +MeshObject::const_facet_iterator::const_facet_iterator(MeshObject::const_facet_iterator&& fi) = default; MeshObject::const_facet_iterator::~const_facet_iterator() = default; -MeshObject::const_facet_iterator& -MeshObject::const_facet_iterator::operator=(const MeshObject::const_facet_iterator& fi) = default; +MeshObject::const_facet_iterator& MeshObject::const_facet_iterator::operator=( + const MeshObject::const_facet_iterator& fi +) = default; -MeshObject::const_facet_iterator& -MeshObject::const_facet_iterator::operator=(MeshObject::const_facet_iterator&& fi) = default; +MeshObject::const_facet_iterator& MeshObject::const_facet_iterator::operator=( + MeshObject::const_facet_iterator&& fi +) = default; void MeshObject::const_facet_iterator::dereference() { diff --git a/src/Mod/Mesh/App/Mesh.h b/src/Mod/Mesh/App/Mesh.h index 8aa6bf4ce5..674273e64d 100644 --- a/src/Mod/Mesh/App/Mesh.h +++ b/src/Mod/Mesh/App/Mesh.h @@ -133,10 +133,12 @@ public: /// get the subelement by type and number Data::Segment* getSubElement(const char* Type, unsigned long) const override; /** Get faces from segment */ - void getFacesFromSubElement(const Data::Segment*, - std::vector& Points, - std::vector& PointNormals, - std::vector& faces) const override; + void getFacesFromSubElement( + const Data::Segment*, + std::vector& Points, + std::vector& PointNormals, + std::vector& faces + ) const override; //@} void setTransform(const Base::Matrix4D& rclTrf) override; @@ -164,14 +166,18 @@ public: double getSurface() const; double getVolume() const; /** Get points from object with given accuracy */ - void getPoints(std::vector& Points, - std::vector& Normals, - double Accuracy, - uint16_t flags = 0) const override; - void getFaces(std::vector& Points, - std::vector& Topo, - double Accuracy, - uint16_t flags = 0) const override; + void getPoints( + std::vector& Points, + std::vector& Normals, + double Accuracy, + uint16_t flags = 0 + ) const override; + void getFaces( + std::vector& Points, + std::vector& Topo, + double Accuracy, + uint16_t flags = 0 + ) const override; std::vector getPointsFromFacets(const std::vector& facets) const; bool nearestFacetOnRay(const TRay& ray, double maxAngle, TFaceSection& output) const; std::vector foraminate(const TRay& ray, double maxAngle) const; @@ -198,14 +204,18 @@ public: void SaveDocFile(Base::Writer& writer) const override; void Restore(Base::XMLReader& reader) override; void RestoreDocFile(Base::Reader& reader) override; - void save(const char* file, - MeshCore::MeshIO::Format f = MeshCore::MeshIO::Undefined, - const MeshCore::Material* mat = nullptr, - const char* objectname = nullptr) const; - void save(std::ostream&, - MeshCore::MeshIO::Format f, - const MeshCore::Material* mat = nullptr, - const char* objectname = nullptr) const; + void save( + const char* file, + MeshCore::MeshIO::Format f = MeshCore::MeshIO::Undefined, + const MeshCore::Material* mat = nullptr, + const char* objectname = nullptr + ) const; + void save( + std::ostream&, + MeshCore::MeshIO::Format f, + const MeshCore::Material* mat = nullptr, + const char* objectname = nullptr + ) const; bool load(const char* file, MeshCore::Material* mat = nullptr); bool load(std::istream&, MeshCore::MeshIO::Format f, MeshCore::Material* mat = nullptr); // Save and load in internal format @@ -219,15 +229,21 @@ public: void addFacet(const MeshCore::MeshGeomFacet& facet); void addFacets(const std::vector& facets); void addFacets(const std::vector& facets, bool checkManifolds); - void addFacets(const std::vector& facets, - const std::vector& points, - bool checkManifolds); - void addFacets(const std::vector& facets, - const std::vector& points, - bool checkManifolds); + void addFacets( + const std::vector& facets, + const std::vector& points, + bool checkManifolds + ); + void addFacets( + const std::vector& facets, + const std::vector& points, + bool checkManifolds + ); void setFacets(const std::vector& facets); - void setFacets(const std::vector& facets, - const std::vector& points); + void setFacets( + const std::vector& facets, + const std::vector& points + ); /** * Combines two independent mesh objects. * @note The mesh object we want to add must not overlap or intersect with @@ -251,8 +267,10 @@ public: * The point degree information is stored in \a point_degree. The return value * gives the number of points which will have a degree of zero. */ - unsigned long getPointDegree(const std::vector& indices, - std::vector& point_degree) const; + unsigned long getPointDegree( + const std::vector& indices, + std::vector& point_degree + ) const; void fillupHoles(unsigned long, int, MeshCore::AbstractPolygonTriangulator&); void offset(float fSize); void offsetSpecial2(float fSize); @@ -268,10 +286,12 @@ public: void decimate(int targetSize); Base::Vector3d getPointNormal(PointIndex) const; std::vector getPointNormals() const; - void crossSections(const std::vector&, - std::vector& sections, - float fMinEps = 1.0e-2F, - bool bConnectPolygons = false) const; + void crossSections( + const std::vector&, + std::vector& sections, + float fMinEps = 1.0e-2F, + bool bConnectPolygons = false + ) const; void cut(const Base::Polygon2d& polygon, const Base::ViewProjMethod& proj, CutType); void trim(const Base::Polygon2d& polygon, const Base::ViewProjMethod& proj, CutType); void trimByPlane(const Base::Vector3f& base, const Base::Vector3f& normal); @@ -302,8 +322,11 @@ public: MeshObject* subtract(const MeshObject&) const; MeshObject* inner(const MeshObject&) const; MeshObject* outer(const MeshObject&) const; - std::vector> - section(const MeshObject&, bool connectLines, float fMinDist) const; + std::vector> section( + const MeshObject&, + bool connectLines, + float fMinDist + ) const; //@} /** @name Topological operations */ diff --git a/src/Mod/Mesh/App/MeshFeaturePyImp.cpp b/src/Mod/Mesh/App/MeshFeaturePyImp.cpp index 7e80078aba..b5f2f65dc2 100644 --- a/src/Mod/Mesh/App/MeshFeaturePyImp.cpp +++ b/src/Mod/Mesh/App/MeshFeaturePyImp.cpp @@ -124,8 +124,10 @@ PyObject* MeshFeaturePy::decimate(PyObject* args) Py_Return; } - PyErr_SetString(PyExc_ValueError, - "decimate(tolerance=float, reduction=float) or decimate(targetSize=int)"); + PyErr_SetString( + PyExc_ValueError, + "decimate(tolerance=float, reduction=float) or decimate(targetSize=int)" + ); return nullptr; } diff --git a/src/Mod/Mesh/App/MeshPoint.h b/src/Mod/Mesh/App/MeshPoint.h index eda3e33786..a6886145d1 100644 --- a/src/Mod/Mesh/App/MeshPoint.h +++ b/src/Mod/Mesh/App/MeshPoint.h @@ -31,7 +31,7 @@ #include #ifndef MESH_GLOBAL_H -#include +# include #endif using Base::Vector3d; @@ -51,9 +51,11 @@ class MeshExport MeshPoint: public Vector3d public: /// simple constructor - explicit MeshPoint(const Vector3d& vec = Vector3d(), - const MeshObject* obj = nullptr, - unsigned int index = std::numeric_limits::max()) + explicit MeshPoint( + const Vector3d& vec = Vector3d(), + const MeshObject* obj = nullptr, + unsigned int index = std::numeric_limits::max() + ) : Vector3d(vec) , Index(index) , Mesh(obj) diff --git a/src/Mod/Mesh/App/MeshPointPyImp.cpp b/src/Mod/Mesh/App/MeshPointPyImp.cpp index b237edde76..2e3f95ea55 100644 --- a/src/Mod/Mesh/App/MeshPointPyImp.cpp +++ b/src/Mod/Mesh/App/MeshPointPyImp.cpp @@ -105,14 +105,16 @@ Py::Object MeshPointPy::getNormal() const { if (!getMeshPointPtr()->isBound()) { throw Py::RuntimeError( - "This object is not bound to a mesh, so no topological operation is possible!"); + "This object is not bound to a mesh, so no topological operation is possible!" + ); } if (getMeshPointPtr()->Mesh->countPoints() <= getMeshPointPtr()->Index) { throw Py::IndexError("Index out of range"); } - Base::Vector3d* v = - new Base::Vector3d(getMeshPointPtr()->Mesh->getPointNormal(getMeshPointPtr()->Index)); + Base::Vector3d* v = new Base::Vector3d( + getMeshPointPtr()->Mesh->getPointNormal(getMeshPointPtr()->Index) + ); Base::VectorPy* normal = new Base::VectorPy(v); normal->setConst(); return Py::Object(normal, true); diff --git a/src/Mod/Mesh/App/MeshProperties.cpp b/src/Mod/Mesh/App/MeshProperties.cpp index fe9e03070b..5d6110548c 100644 --- a/src/Mod/Mesh/App/MeshProperties.cpp +++ b/src/Mod/Mesh/App/MeshProperties.cpp @@ -823,8 +823,7 @@ void PropertyMeshKernel::transformGeometry(const Base::Matrix4D& rclMat) hasSetValue(); } -void PropertyMeshKernel::setPointIndices( - const std::vector>& inds) +void PropertyMeshKernel::setPointIndices(const std::vector>& inds) { aboutToSetValue(); MeshCore::MeshKernel& kernel = _meshObject->getKernel(); @@ -847,10 +846,10 @@ Base::Matrix4D PropertyMeshKernel::getTransform() const PyObject* PropertyMeshKernel::getPyObject() { if (!meshPyObject) { - meshPyObject = new MeshPy( - &*_meshObject); // Lgtm[cpp/resource-not-released-in-destructor] ** Not destroyed in - // this class because it is reference-counted and destroyed elsewhere - meshPyObject->setConst(); // set immutable + meshPyObject = new MeshPy(&*_meshObject); // Lgtm[cpp/resource-not-released-in-destructor] + // ** Not destroyed in this class because it is + // reference-counted and destroyed elsewhere + meshPyObject->setConst(); // set immutable meshPyObject->parentProperty = this; } diff --git a/src/Mod/Mesh/App/MeshPyImp.cpp b/src/Mod/Mesh/App/MeshPyImp.cpp index a4f081d299..66e2979001 100644 --- a/src/Mod/Mesh/App/MeshPyImp.cpp +++ b/src/Mod/Mesh/App/MeshPyImp.cpp @@ -106,9 +106,7 @@ int MeshPy::PyInit(PyObject* args, PyObject*) getMeshObjectPtr()->load(PyUnicode_AsUTF8(pcObj)); } else { - PyErr_Format(PyExc_TypeError, - "Cannot create a mesh out of a '%s'", - pcObj->ob_type->tp_name); + PyErr_Format(PyExc_TypeError, "Cannot create a mesh out of a '%s'", pcObj->ob_type->tp_name); return -1; } } @@ -235,20 +233,19 @@ PyObject* MeshPy::write(PyObject* args, PyObject* kwds) const ext["ASY"] = MeshCore::MeshIO::ASY; ext["3MF"] = MeshCore::MeshIO::ThreeMF; - static const std::array keywords_path {"Filename", - "Format", - "Name", - "Material", - nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "et|ssO", - keywords_path, - "utf-8", - &Name, - &Ext, - &ObjName, - &List)) { + static const std::array + keywords_path {"Filename", "Format", "Name", "Material", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "et|ssO", + keywords_path, + "utf-8", + &Name, + &Ext, + &ObjName, + &List + )) { if (Ext) { std::string fmt(Ext); boost::to_upper(fmt); @@ -289,20 +286,19 @@ PyObject* MeshPy::write(PyObject* args, PyObject* kwds) const PyErr_Clear(); - static const std::array keywords_stream {"Stream", - "Format", - "Name", - "Material", - nullptr}; + static const std::array + keywords_stream {"Stream", "Format", "Name", "Material", nullptr}; PyObject* input; - if (Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "Os|sO", - keywords_stream, - &input, - &Ext, - &ObjName, - &List)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "Os|sO", + keywords_stream, + &input, + &Ext, + &ObjName, + &List + )) { std::string fmt(Ext); boost::to_upper(fmt); if (ext.find(fmt) != ext.end()) { @@ -560,28 +556,28 @@ PyObject* MeshPy::section(PyObject* args, PyObject* kwds) const PyObject* connectLines = Py_True; float fMinDist = 0.0001F; - static const std::array keywords_section {"Mesh", - "ConnectLines", - "MinDist", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "O!|O!f", - keywords_section, - &(MeshPy::Type), - &pcObj, - &PyBool_Type, - &connectLines, - &fMinDist)) { + static const std::array keywords_section {"Mesh", "ConnectLines", "MinDist", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|O!f", + keywords_section, + &(MeshPy::Type), + &pcObj, + &PyBool_Type, + &connectLines, + &fMinDist + )) { return nullptr; } MeshPy* pcObject = static_cast(pcObj); - std::vector> curves = - getMeshObjectPtr()->section(*pcObject->getMeshObjectPtr(), - Base::asBoolean(connectLines), - fMinDist); + std::vector> curves = getMeshObjectPtr()->section( + *pcObject->getMeshObjectPtr(), + Base::asBoolean(connectLines), + fMinDist + ); Py::List outer; for (const auto& it : curves) { Py::List inner; @@ -687,9 +683,12 @@ PyObject* MeshPy::addFacet(PyObject* args) double z3 {}; if (PyArg_ParseTuple(args, "ddddddddd", &x1, &y1, &z1, &x2, &y2, &z2, &x3, &y3, &z3)) { getMeshObjectPtr()->addFacet( - MeshCore::MeshGeomFacet(Base::Vector3f((float)x1, (float)y1, (float)z1), - Base::Vector3f((float)x2, (float)y2, (float)z2), - Base::Vector3f((float)x3, (float)y3, (float)z3))); + MeshCore::MeshGeomFacet( + Base::Vector3f((float)x1, (float)y1, (float)z1), + Base::Vector3f((float)x2, (float)y2, (float)z2), + Base::Vector3f((float)x3, (float)y3, (float)z3) + ) + ); Py_Return; } @@ -697,21 +696,26 @@ PyObject* MeshPy::addFacet(PyObject* args) PyObject* v1 {}; PyObject* v2 {}; PyObject* v3 {}; - if (PyArg_ParseTuple(args, - "O!O!O!", - &(Base::VectorPy::Type), - &v1, - &(Base::VectorPy::Type), - &v2, - &(Base::VectorPy::Type), - &v3)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &(Base::VectorPy::Type), + &v1, + &(Base::VectorPy::Type), + &v2, + &(Base::VectorPy::Type), + &v3 + )) { Base::Vector3d* p1 = static_cast(v1)->getVectorPtr(); Base::Vector3d* p2 = static_cast(v2)->getVectorPtr(); Base::Vector3d* p3 = static_cast(v3)->getVectorPtr(); getMeshObjectPtr()->addFacet( - MeshCore::MeshGeomFacet(Base::Vector3f((float)p1->x, (float)p1->y, (float)p1->z), - Base::Vector3f((float)p2->x, (float)p2->y, (float)p2->z), - Base::Vector3f((float)p3->x, (float)p3->y, (float)p3->z))); + MeshCore::MeshGeomFacet( + Base::Vector3f((float)p1->x, (float)p1->y, (float)p1->z), + Base::Vector3f((float)p2->x, (float)p2->y, (float)p2->z), + Base::Vector3f((float)p3->x, (float)p3->y, (float)p3->z) + ) + ); Py_Return; } @@ -822,10 +826,12 @@ PyObject* MeshPy::addFacets(PyObject* args) Py_Return; } - PyErr_SetString(PyExc_TypeError, - "either expect\n" - "-- [Vector] (3 of them define a facet)\n" - "-- ([Vector],[(int,int,int)])"); + PyErr_SetString( + PyExc_TypeError, + "either expect\n" + "-- [Vector] (3 of them define a facet)\n" + "-- ([Vector],[(int,int,int)])" + ); return nullptr; } @@ -1278,12 +1284,7 @@ PyObject* MeshPy::removePointsOnEdge(PyObject* args, PyObject* kwds) { PyObject* fillBoundary = Py_False; // NOLINT static const std::array keywords {"FillBoundary", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "|O!", - keywords, - &PyBool_Type, - &fillBoundary)) { + if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|O!", keywords, &PyBool_Type, &fillBoundary)) { return nullptr; } try { @@ -1403,11 +1404,13 @@ PyObject* MeshPy::fillupHoles(PyObject* args) const std::unique_ptr tria; if (max_area > 0.0F) { tria = std::unique_ptr( - new MeshCore::ConstraintDelaunayTriangulator(max_area)); + new MeshCore::ConstraintDelaunayTriangulator(max_area) + ); } else { tria = std::unique_ptr( - new MeshCore::FlatTriangulator()); + new MeshCore::FlatTriangulator() + ); } MeshPropertyLock lock(this->parentProperty); @@ -1584,7 +1587,8 @@ PyObject* MeshPy::optimizeTopology(PyObject* args) const if (!PyArg_ParseTuple( args, "|f; specify the maximum allowed angle between the normals of two adjacent facets", - &fMaxAngle)) { + &fMaxAngle + )) { return nullptr; } @@ -1673,13 +1677,15 @@ PyObject* MeshPy::splitFacet(PyObject* args) unsigned long facet {}; PyObject* vertex1 {}; PyObject* vertex2 {}; - if (!PyArg_ParseTuple(args, - "kO!O!", - &facet, - &Base::VectorPy::Type, - &vertex1, - &Base::VectorPy::Type, - &vertex2)) { + if (!PyArg_ParseTuple( + args, + "kO!O!", + &facet, + &Base::VectorPy::Type, + &vertex1, + &Base::VectorPy::Type, + &vertex2 + )) { return nullptr; } @@ -1989,20 +1995,17 @@ PyObject* MeshPy::trimByPlane(PyObject* args) { PyObject* base {}; PyObject* norm {}; - if (!PyArg_ParseTuple(args, - "O!O!", - &Base::VectorPy::Type, - &base, - &Base::VectorPy::Type, - &norm)) { + if (!PyArg_ParseTuple(args, "O!O!", &Base::VectorPy::Type, &base, &Base::VectorPy::Type, &norm)) { return nullptr; } Base::Vector3d pnt = Py::Vector(base, false).toVector(); Base::Vector3d dir = Py::Vector(norm, false).toVector(); - getMeshObjectPtr()->trimByPlane(Base::convertTo(pnt), - Base::convertTo(dir)); + getMeshObjectPtr()->trimByPlane( + Base::convertTo(pnt), + Base::convertTo(dir) + ); Py_Return; } @@ -2017,16 +2020,18 @@ PyObject* MeshPy::smooth(PyObject* args, PyObject* kwds) const int weight = 1; static const std::array keywords_smooth {"Method", "Iteration", "Lambda", "Micro", "Maximum", "Weight", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwds, - "|sidddi", - keywords_smooth, - &method, - &iter, - &lambda, - µ, - &maximum, - &weight)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|sidddi", + keywords_smooth, + &method, + &iter, + &lambda, + µ, + &maximum, + &weight + )) { return nullptr; } @@ -2096,8 +2101,10 @@ PyObject* MeshPy::decimate(PyObject* args) Py_Return; } - PyErr_SetString(PyExc_ValueError, - "decimate(tolerance=float, reduction=float) or decimate(targetSize=int)"); + PyErr_SetString( + PyExc_ValueError, + "decimate(tolerance=float, reduction=float) or decimate(targetSize=int)" + ); return nullptr; } @@ -2141,8 +2148,8 @@ PyObject* MeshPy::getPlanarSegments(PyObject* args) const } Mesh::MeshObject* mesh = getMeshObjectPtr(); - std::vector segments = - mesh->getSegmentsOfType(Mesh::MeshObject::PLANE, dev, minFacets); + std::vector segments + = mesh->getSegmentsOfType(Mesh::MeshObject::PLANE, dev, minFacets); Py::List s; for (const auto& segment : segments) { @@ -2219,12 +2226,15 @@ PyObject* MeshPy::getSegmentsByCurvature(PyObject* args) const float tol2 = Py::Float(t[3]); int num = (int)Py::Long(t[4]); segm.emplace_back( - std::make_shared(meshCurv.GetCurvature(), - num, - tol1, - tol2, - c1, - c2)); + std::make_shared( + meshCurv.GetCurvature(), + num, + tol1, + tol2, + c1, + c2 + ) + ); } finder.FindSegments(segm); @@ -2316,10 +2326,10 @@ Py::List MeshPy::getPoints() const Py::List PointList; unsigned int Index = 0; MeshObject* mesh = getMeshObjectPtr(); - for (MeshObject::const_point_iterator it = mesh->points_begin(); it != mesh->points_end(); - ++it) { + for (MeshObject::const_point_iterator it = mesh->points_begin(); it != mesh->points_end(); ++it) { PointList.append( - Py::Object(new MeshPointPy(new MeshPoint(*it, getMeshObjectPtr(), Index++)), true)); + Py::Object(new MeshPointPy(new MeshPoint(*it, getMeshObjectPtr(), Index++)), true) + ); } return PointList; } @@ -2328,8 +2338,7 @@ Py::List MeshPy::getFacets() const { Py::List FacetList; MeshObject* mesh = getMeshObjectPtr(); - for (MeshObject::const_facet_iterator it = mesh->facets_begin(); it != mesh->facets_end(); - ++it) { + for (MeshObject::const_facet_iterator it = mesh->facets_begin(); it != mesh->facets_end(); ++it) { FacetList.append(Py::Object(new FacetPy(new Facet(*it)), true)); } return FacetList; diff --git a/src/Mod/Mesh/App/MeshTexture.cpp b/src/Mod/Mesh/App/MeshTexture.cpp index 20d83312cc..393531b854 100644 --- a/src/Mod/Mesh/App/MeshTexture.cpp +++ b/src/Mod/Mesh/App/MeshTexture.cpp @@ -47,17 +47,21 @@ MeshTexture::MeshTexture(const Mesh::MeshObject& mesh, const MeshCore::Material& } } -void MeshTexture::apply(const Mesh::MeshObject& mesh, - const Base::Color& defaultColor, - MeshCore::Material& material) +void MeshTexture::apply( + const Mesh::MeshObject& mesh, + const Base::Color& defaultColor, + MeshCore::Material& material +) { apply(mesh, true, defaultColor, -1.0F, material); } -void MeshTexture::apply(const Mesh::MeshObject& mesh, - const Base::Color& defaultColor, - float max_dist, - MeshCore::Material& material) +void MeshTexture::apply( + const Mesh::MeshObject& mesh, + const Base::Color& defaultColor, + float max_dist, + MeshCore::Material& material +) { apply(mesh, true, defaultColor, max_dist, material); } @@ -74,11 +78,13 @@ void MeshTexture::apply(const Mesh::MeshObject& mesh, float max_dist, MeshCore:: apply(mesh, false, defaultColor, max_dist, material); } -void MeshTexture::apply(const Mesh::MeshObject& mesh, - bool addDefaultColor, - const Base::Color& defaultColor, - float max_dist, - MeshCore::Material& material) +void MeshTexture::apply( + const Mesh::MeshObject& mesh, + bool addDefaultColor, + const Base::Color& defaultColor, + float max_dist, + MeshCore::Material& material +) { // copy the color values because the passed material could be the same instance as // 'materialRefMesh' @@ -132,8 +138,7 @@ void MeshTexture::apply(const Mesh::MeshObject& mesh, PointIndex index3 = pointMap[it._aulPoints[2]]; if (index1 != MeshCore::POINT_INDEX_MAX && index2 != MeshCore::POINT_INDEX_MAX && index3 != MeshCore::POINT_INDEX_MAX) { - std::vector found = - refPnt2Fac->GetIndices(index1, index2, index3); + std::vector found = refPnt2Fac->GetIndices(index1, index2, index3); if (found.size() == 1) { diffuseColor.push_back(textureColor[found.front()]); } diff --git a/src/Mod/Mesh/App/MeshTexture.h b/src/Mod/Mesh/App/MeshTexture.h index 34530a52e1..854c1b85da 100644 --- a/src/Mod/Mesh/App/MeshTexture.h +++ b/src/Mod/Mesh/App/MeshTexture.h @@ -54,18 +54,22 @@ public: that don't match \a defaultColor will be used instead, otherwise the color of the original material is used. */ - void apply(const Mesh::MeshObject& mesh, - const Base::Color& defaultColor, - MeshCore::Material& material); + void apply( + const Mesh::MeshObject& mesh, + const Base::Color& defaultColor, + MeshCore::Material& material + ); /*! Find common points or facets of this to the original mesh. For points or facets that don't match \a defaultColor will be used instead, otherwise the color of the original material is used. */ - void apply(const Mesh::MeshObject& mesh, - const Base::Color& defaultColor, - float max_dist, - MeshCore::Material& material); + void apply( + const Mesh::MeshObject& mesh, + const Base::Color& defaultColor, + float max_dist, + MeshCore::Material& material + ); /*! Find common points or facets of this to the original mesh and use the color of the original material. If for a point of \a mesh no matching point of the original mesh can be found the @@ -80,11 +84,13 @@ public: void apply(const Mesh::MeshObject& mesh, float max_dist, MeshCore::Material& material); private: - void apply(const Mesh::MeshObject& mesh, - bool addDefaultColor, - const Base::Color& defaultColor, - float max_dist, - MeshCore::Material& material); + void apply( + const Mesh::MeshObject& mesh, + bool addDefaultColor, + const Base::Color& defaultColor, + float max_dist, + MeshCore::Material& material + ); PointIndex findIndex(const Base::Vector3f& p, float max_dist) const { if (max_dist < 0.0F) { diff --git a/src/Mod/Mesh/App/Segment.cpp b/src/Mod/Mesh/App/Segment.cpp index fe81e7042f..ea7ec65f77 100644 --- a/src/Mod/Mesh/App/Segment.cpp +++ b/src/Mod/Mesh/App/Segment.cpp @@ -66,11 +66,13 @@ void Segment::removeIndices(const std::vector& inds) std::vector result; std::set s1(_indices.begin(), _indices.end()); std::set s2(inds.begin(), inds.end()); - std::set_difference(s1.begin(), - s1.end(), - s2.begin(), - s2.end(), - std::back_insert_iterator>(result)); + std::set_difference( + s1.begin(), + s1.end(), + s2.begin(), + s2.end(), + std::back_insert_iterator>(result) + ); _indices = result; if (_modifykernel) { diff --git a/src/Mod/Mesh/Gui/AppMeshGui.cpp b/src/Mod/Mesh/Gui/AppMeshGui.cpp index 45087c928a..961eb2f2e9 100644 --- a/src/Mod/Mesh/Gui/AppMeshGui.cpp +++ b/src/Mod/Mesh/Gui/AppMeshGui.cpp @@ -153,9 +153,11 @@ PyMOD_INIT_FUNC(MeshGui) // register preferences pages (void)new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Display")); + QT_TRANSLATE_NOOP("QObject", "Display") + ); (void)new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Import-Export")); + QT_TRANSLATE_NOOP("QObject", "Import-Export") + ); Mesh::Extension3MFFactory::addProducer(new MeshGui::ThumbnailExtensionProducer); // NOLINTEND diff --git a/src/Mod/Mesh/Gui/Command.cpp b/src/Mod/Mesh/Gui/Command.cpp index 98ddd1ba3f..761b92b7d6 100644 --- a/src/Mod/Mesh/Gui/Command.cpp +++ b/src/Mod/Mesh/Gui/Command.cpp @@ -25,7 +25,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif #include #include @@ -93,25 +93,28 @@ CmdMeshUnion::CmdMeshUnion() void CmdMeshUnion::activated(int) { - std::vector obj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); std::string name1 = obj.front()->getNameInDocument(); std::string name2 = obj.back()->getNameInDocument(); std::string name3 = getUniqueObjectName("Union"); try { openCommand(QT_TRANSLATE_NOOP("Command", "Mesh union")); - doCommand(Doc, - "import OpenSCADUtils\n" - "mesh = " - "OpenSCADUtils.meshoptempfile('union',(App.ActiveDocument.%s.Mesh,App." - "ActiveDocument.%s.Mesh))\n" - "App.ActiveDocument.addObject(\"Mesh::Feature\",\"%s\")\n" - "App.ActiveDocument.%s.Mesh = mesh\n", - name1.c_str(), - name2.c_str(), - name3.c_str(), - name3.c_str()); + doCommand( + Doc, + "import OpenSCADUtils\n" + "mesh = " + "OpenSCADUtils.meshoptempfile('union',(App.ActiveDocument.%s.Mesh,App." + "ActiveDocument.%s.Mesh))\n" + "App.ActiveDocument.addObject(\"Mesh::Feature\",\"%s\")\n" + "App.ActiveDocument.%s.Mesh = mesh\n", + name1.c_str(), + name2.c_str(), + name3.c_str(), + name3.c_str() + ); updateActive(); commitCommand(); @@ -136,14 +139,19 @@ void CmdMeshUnion::activated(int) QMessageBox::critical( Gui::getMainWindow(), qApp->translate("Mesh_Union", "OpenSCAD"), - qApp->translate("Mesh_Union", "Unknown error occurred while running OpenSCAD.")); + qApp->translate("Mesh_Union", "Unknown error occurred while running OpenSCAD.") + ); } else { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Mesh_Union", "OpenSCAD"), - qApp->translate("Mesh_Union", - "OpenSCAD cannot be found on the system.\n" - "Visit https://openscad.org/ to install it.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Mesh_Union", "OpenSCAD"), + qApp->translate( + "Mesh_Union", + "OpenSCAD cannot be found on the system.\n" + "Visit https://openscad.org/ to install it." + ) + ); } } } @@ -171,25 +179,28 @@ CmdMeshDifference::CmdMeshDifference() void CmdMeshDifference::activated(int) { - std::vector obj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); std::string name1 = obj.front()->getNameInDocument(); std::string name2 = obj.back()->getNameInDocument(); std::string name3 = getUniqueObjectName("Difference"); openCommand(QT_TRANSLATE_NOOP("Command", "Mesh difference")); try { - doCommand(Doc, - "import OpenSCADUtils\n" - "mesh = " - "OpenSCADUtils.meshoptempfile('difference',(App.ActiveDocument.%s.Mesh,App." - "ActiveDocument.%s.Mesh))\n" - "App.ActiveDocument.addObject(\"Mesh::Feature\",\"%s\")\n" - "App.ActiveDocument.%s.Mesh = mesh\n", - name1.c_str(), - name2.c_str(), - name3.c_str(), - name3.c_str()); + doCommand( + Doc, + "import OpenSCADUtils\n" + "mesh = " + "OpenSCADUtils.meshoptempfile('difference',(App.ActiveDocument.%s.Mesh,App." + "ActiveDocument.%s.Mesh))\n" + "App.ActiveDocument.addObject(\"Mesh::Feature\",\"%s\")\n" + "App.ActiveDocument.%s.Mesh = mesh\n", + name1.c_str(), + name2.c_str(), + name3.c_str(), + name3.c_str() + ); updateActive(); commitCommand(); @@ -214,14 +225,19 @@ void CmdMeshDifference::activated(int) QMessageBox::critical( Gui::getMainWindow(), qApp->translate("Mesh_Union", "OpenSCAD"), - qApp->translate("Mesh_Union", "Unknown error occurred while running OpenSCAD.")); + qApp->translate("Mesh_Union", "Unknown error occurred while running OpenSCAD.") + ); } else { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Mesh_Union", "OpenSCAD"), - qApp->translate("Mesh_Union", - "OpenSCAD cannot be found on the system.\n" - "Visit https://openscad.org/ to install it.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Mesh_Union", "OpenSCAD"), + qApp->translate( + "Mesh_Union", + "OpenSCAD cannot be found on the system.\n" + "Visit https://openscad.org/ to install it." + ) + ); } } } @@ -249,25 +265,28 @@ CmdMeshIntersection::CmdMeshIntersection() void CmdMeshIntersection::activated(int) { - std::vector obj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); std::string name1 = obj.front()->getNameInDocument(); std::string name2 = obj.back()->getNameInDocument(); std::string name3 = getUniqueObjectName("Intersection"); openCommand(QT_TRANSLATE_NOOP("Command", "Mesh intersection")); try { - doCommand(Doc, - "import OpenSCADUtils\n" - "mesh = " - "OpenSCADUtils.meshoptempfile('intersection',(App.ActiveDocument.%s.Mesh,App." - "ActiveDocument.%s.Mesh))\n" - "App.ActiveDocument.addObject(\"Mesh::Feature\",\"%s\")\n" - "App.ActiveDocument.%s.Mesh = mesh\n", - name1.c_str(), - name2.c_str(), - name3.c_str(), - name3.c_str()); + doCommand( + Doc, + "import OpenSCADUtils\n" + "mesh = " + "OpenSCADUtils.meshoptempfile('intersection',(App.ActiveDocument.%s.Mesh,App." + "ActiveDocument.%s.Mesh))\n" + "App.ActiveDocument.addObject(\"Mesh::Feature\",\"%s\")\n" + "App.ActiveDocument.%s.Mesh = mesh\n", + name1.c_str(), + name2.c_str(), + name3.c_str(), + name3.c_str() + ); updateActive(); commitCommand(); @@ -292,14 +311,19 @@ void CmdMeshIntersection::activated(int) QMessageBox::critical( Gui::getMainWindow(), qApp->translate("Mesh_Union", "OpenSCAD"), - qApp->translate("Mesh_Union", "Unknown error occurred while running OpenSCAD.")); + qApp->translate("Mesh_Union", "Unknown error occurred while running OpenSCAD.") + ); } else { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Mesh_Union", "OpenSCAD"), - qApp->translate("Mesh_Union", - "OpenSCAD cannot be found on the system.\n" - "Visit https://openscad.org/ to install it.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Mesh_Union", "OpenSCAD"), + qApp->translate( + "Mesh_Union", + "OpenSCAD cannot be found on the system.\n" + "Visit https://openscad.org/ to install it." + ) + ); } } } @@ -342,10 +366,12 @@ void CmdMeshImport::activated(int) filter << QStringLiteral("%1 (*.*)").arg(QObject::tr("All Files")); // Allow multi selection - QStringList fn = Gui::FileDialog::getOpenFileNames(Gui::getMainWindow(), - QObject::tr("Import Mesh"), - QString(), - filter.join(QLatin1String(";;"))); + QStringList fn = Gui::FileDialog::getOpenFileNames( + Gui::getMainWindow(), + QObject::tr("Import Mesh"), + QString(), + filter.join(QLatin1String(";;")) + ); for (const auto& it : fn) { std::string unicodepath = Base::Tools::escapedUnicodeFromUtf8(it.toUtf8().data()); unicodepath = Base::Tools::escapeEncodeFilename(unicodepath); @@ -380,8 +406,9 @@ CmdMeshExport::CmdMeshExport() void CmdMeshExport::activated(int) { - std::vector docObjs = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector docObjs = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); if (docObjs.size() != 1) { return; } @@ -417,11 +444,13 @@ void CmdMeshExport::activated(int) } QString format; - QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), - QObject::tr("Export Mesh"), - dir, - filter.join(QLatin1String(";;")), - &format); + QString fn = Gui::FileDialog::getSaveFileName( + Gui::getMainWindow(), + QObject::tr("Export Mesh"), + dir, + filter.join(QLatin1String(";;")), + &format + ); if (!fn.isEmpty()) { QFileInfo fi(fn); QByteArray extension = fi.suffix().toLatin1(); @@ -433,7 +462,8 @@ void CmdMeshExport::activated(int) } MeshGui::ViewProviderMesh* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(docObj)); + Gui::Application::Instance->getViewProvider(docObj) + ); if (vp) { vp->exportMesh((const char*)fn.toUtf8(), (const char*)extension); } @@ -463,22 +493,25 @@ CmdMeshFromGeometry::CmdMeshFromGeometry() void CmdMeshFromGeometry::activated(int) { bool ok {}; - double tol = QInputDialog::getDouble(Gui::getMainWindow(), - QObject::tr("Meshing Tolerance"), - QObject::tr("Enter tolerance for meshing geometry:"), - 0.1, - 0.01, - 10.0, - 2, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + double tol = QInputDialog::getDouble( + Gui::getMainWindow(), + QObject::tr("Meshing Tolerance"), + QObject::tr("Enter tolerance for meshing geometry:"), + 0.1, + 0.01, + 10.0, + 2, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok) { return; } App::Document* doc = App::GetApplication().getActiveDocument(); - std::vector geo = - Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); + std::vector geo = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); for (auto it : geo) { if (!it->isDerivedFrom()) { // exclude meshes @@ -486,12 +519,11 @@ void CmdMeshFromGeometry::activated(int) it->getPropertyMap(Map); Mesh::MeshObject mesh; for (const auto& jt : Map) { - if (jt.first == "Shape" - && jt.second->isDerivedFrom()) { + if (jt.first == "Shape" && jt.second->isDerivedFrom()) { std::vector aPoints; std::vector aTopo; - const Data::ComplexGeoData* data = - static_cast(jt.second)->getComplexData(); + const Data::ComplexGeoData* data + = static_cast(jt.second)->getComplexData(); if (data) { data->getFaces(aPoints, aTopo, (float)tol); mesh.setFacets(aTopo, aPoints); @@ -560,8 +592,9 @@ CmdMeshVertexCurvature::CmdMeshVertexCurvature() void CmdMeshVertexCurvature::activated(int) { - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto it : meshes) { std::string fName = it->getNameInDocument(); fName += "_Curvature"; @@ -574,17 +607,18 @@ void CmdMeshVertexCurvature::activated(int) Doc, "App.activeDocument().getObject(\"%s\").newObject(\"Mesh::Curvature\",\"%s\")", grp->getNameInDocument(), - fName.c_str()); + fName.c_str() + ); } else { - doCommand(Doc, - "App.activeDocument().addObject(\"Mesh::Curvature\",\"%s\")", - fName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Mesh::Curvature\",\"%s\")", fName.c_str()); } - doCommand(Doc, - "App.activeDocument().%s.Source = App.activeDocument().%s", - fName.c_str(), - it->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().%s.Source = App.activeDocument().%s", + fName.c_str(), + it->getNameInDocument() + ); } commitCommand(); @@ -623,9 +657,12 @@ void CmdMeshVertexCurvatureInfo::activated(int) viewer->setRedirectToSceneGraph(true); viewer->setSelectionEnabled(false); viewer->setEditingCursor( - QCursor(Gui::BitmapFactory().pixmapFromSvg("Mesh_Pipette", QSize(32, 32)), 4, 29)); - viewer->addEventCallback(SoEvent::getClassTypeId(), - MeshGui::ViewProviderMeshCurvature::curvatureInfoCallback); + QCursor(Gui::BitmapFactory().pixmapFromSvg("Mesh_Pipette", QSize(32, 32)), 4, 29) + ); + viewer->addEventCallback( + SoEvent::getClassTypeId(), + MeshGui::ViewProviderMeshCurvature::curvatureInfoCallback + ); } } @@ -663,10 +700,10 @@ CmdMeshPolySegm::CmdMeshPolySegm() void CmdMeshPolySegm::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -674,8 +711,10 @@ void CmdMeshPolySegm::activated(int) Gui::View3DInventorViewer* viewer = ((Gui::View3DInventor*)view)->getViewer(); viewer->setEditing(true); viewer->startSelection(Gui::View3DInventorViewer::Clip); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::segmMeshCallback); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::segmMeshCallback + ); } else { return; @@ -722,16 +761,19 @@ CmdMeshAddFacet::CmdMeshAddFacet() void CmdMeshAddFacet::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto it : docObj) { Gui::Document* doc = Gui::Application::Instance->getDocument(it->getDocument()); Gui::MDIView* view = doc->getActiveView(); if (view->isDerivedFrom()) { - MeshGui::MeshFaceAddition* edit = - new MeshGui::MeshFaceAddition(static_cast(view)); - edit->startEditing(static_cast( - Gui::Application::Instance->getViewProvider(it))); + MeshGui::MeshFaceAddition* edit = new MeshGui::MeshFaceAddition( + static_cast(view) + ); + edit->startEditing( + static_cast(Gui::Application::Instance->getViewProvider(it)) + ); break; } } @@ -771,10 +813,10 @@ CmdMeshPolyCut::CmdMeshPolyCut() void CmdMeshPolyCut::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -787,8 +829,10 @@ void CmdMeshPolyCut::activated(int) clip->setColor(0.0f, 0.0f, 1.0f); clip->setLineWidth(1.0f); viewer->navigationStyle()->startSelection(clip); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::clipMeshCallback); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::clipMeshCallback + ); } else { return; @@ -836,10 +880,10 @@ CmdMeshPolyTrim::CmdMeshPolyTrim() void CmdMeshPolyTrim::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -852,8 +896,10 @@ void CmdMeshPolyTrim::activated(int) clip->setColor(0.0f, 0.0f, 1.0f); clip->setLineWidth(1.0f); viewer->navigationStyle()->startSelection(clip); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::trimMeshCallback); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::trimMeshCallback + ); } else { return; @@ -966,8 +1012,7 @@ void CmdMeshCrossSections::activated(int) bool CmdMeshCrossSections::isActive() { - return (Gui::Selection().countObjectsOfType() > 0 - && !Gui::Control().activeDialog()); + return (Gui::Selection().countObjectsOfType() > 0 && !Gui::Control().activeDialog()); } //-------------------------------------------------------------------------------------- @@ -987,10 +1032,10 @@ CmdMeshPolySplit::CmdMeshPolySplit() void CmdMeshPolySplit::activated(int) { - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -998,8 +1043,10 @@ void CmdMeshPolySplit::activated(int) Gui::View3DInventorViewer* viewer = ((Gui::View3DInventor*)view)->getViewer(); viewer->setEditing(true); viewer->startSelection(Gui::View3DInventorViewer::Clip); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::partMeshCallback); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::partMeshCallback + ); } else { return; @@ -1053,8 +1100,9 @@ void CmdMeshEvaluation::activated(int) MeshGui::DlgEvaluateMeshImp* dlg = MeshGui::DockEvaluateMeshImp::instance(); dlg->setAttribute(Qt::WA_DeleteOnClose); - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto it : meshes) { dlg->setMesh((Mesh::Feature*)(it)); break; @@ -1096,9 +1144,12 @@ void CmdMeshEvaluateFacet::activated(int) Gui::View3DInventorViewer* viewer = view->getViewer(); viewer->setEditing(true); viewer->setEditingCursor( - QCursor(Gui::BitmapFactory().pixmapFromSvg("Mesh_Pipette", QSize(32, 32)), 4, 29)); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::faceInfoCallback); + QCursor(Gui::BitmapFactory().pixmapFromSvg("Mesh_Pipette", QSize(32, 32)), 4, 29) + ); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::faceInfoCallback + ); } } @@ -1224,8 +1275,10 @@ void CmdMeshRemoveCompByHand::activated(int) Gui::View3DInventorViewer* viewer = view->getViewer(); viewer->setEditing(true); viewer->setEditingCursor(QCursor(Qt::OpenHandCursor)); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::markPartCallback); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::markPartCallback + ); viewer->setSelectionEnabled(false); } } @@ -1237,8 +1290,9 @@ bool CmdMeshRemoveCompByHand::isActive() return false; } - Gui::View3DInventor* view = - dynamic_cast(Gui::getMainWindow()->activeWindow()); + Gui::View3DInventor* view = dynamic_cast( + Gui::getMainWindow()->activeWindow() + ); if (view) { Gui::View3DInventorViewer* viewer = view->getViewer(); return !viewer->isEditing(); @@ -1265,8 +1319,9 @@ CmdMeshEvaluateSolid::CmdMeshEvaluateSolid() void CmdMeshEvaluateSolid::activated(int) { - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto it : meshes) { Mesh::Feature* mesh = (Mesh::Feature*)(it); QString msg; @@ -1367,13 +1422,16 @@ CmdMeshHarmonizeNormals::CmdMeshHarmonizeNormals() void CmdMeshHarmonizeNormals::activated(int) { - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); openCommand(QT_TRANSLATE_NOOP("Command", "Harmonize mesh normals")); for (auto it : meshes) { - doCommand(Doc, - "App.activeDocument().getObject(\"%s\").Mesh.harmonizeNormals()", - it->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().getObject(\"%s\").Mesh.harmonizeNormals()", + it->getNameInDocument() + ); } commitCommand(); updateActive(); @@ -1403,13 +1461,16 @@ CmdMeshFlipNormals::CmdMeshFlipNormals() void CmdMeshFlipNormals::activated(int) { - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); openCommand(QT_TRANSLATE_NOOP("Command", "Flip mesh normals")); for (auto it : meshes) { - doCommand(Doc, - "App.activeDocument().getObject(\"%s\").Mesh.flipNormals()", - it->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().getObject(\"%s\").Mesh.flipNormals()", + it->getNameInDocument() + ); } commitCommand(); updateActive(); @@ -1439,19 +1500,22 @@ CmdMeshBoundingBox::CmdMeshBoundingBox() void CmdMeshBoundingBox::activated(int) { - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto it : meshes) { const MeshCore::MeshKernel& rMesh = ((Mesh::Feature*)it)->Mesh.getValue().getKernel(); const Base::BoundBox3f& box = rMesh.GetBoundBox(); - Base::Console().message("Boundings: Min=<%f,%f,%f>, Max=<%f,%f,%f>\n", - box.MinX, - box.MinY, - box.MinZ, - box.MaxX, - box.MaxY, - box.MaxZ); + Base::Console().message( + "Boundings: Min=<%f,%f,%f>, Max=<%f,%f,%f>\n", + box.MinX, + box.MinY, + box.MinZ, + box.MaxX, + box.MaxY, + box.MaxZ + ); QString bound = qApp->translate("Mesh_BoundingBox", "Boundings of %1:") .arg(QString::fromUtf8(it->Label.getValue())); @@ -1523,28 +1587,32 @@ CmdMeshFillupHoles::CmdMeshFillupHoles() void CmdMeshFillupHoles::activated(int) { - std::vector meshes = - getSelection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector meshes = getSelection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); bool ok {}; - int FillupHolesOfLength = - QInputDialog::getInt(Gui::getMainWindow(), - QObject::tr("Fill Holes"), - QObject::tr("Fill holes with maximum number of edges"), - 3, - 3, - 10000, - 1, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + int FillupHolesOfLength = QInputDialog::getInt( + Gui::getMainWindow(), + QObject::tr("Fill Holes"), + QObject::tr("Fill holes with maximum number of edges"), + 3, + 3, + 10000, + 1, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok) { return; } openCommand(QT_TRANSLATE_NOOP("Command", "Fill up holes")); for (auto mesh : meshes) { - doCommand(Doc, - "App.activeDocument().getObject(\"%s\").Mesh.fillupHoles(%d)", - mesh->getNameInDocument(), - FillupHolesOfLength); + doCommand( + Doc, + "App.activeDocument().getObject(\"%s\").Mesh.fillupHoles(%d)", + mesh->getNameInDocument(), + FillupHolesOfLength + ); } commitCommand(); updateActive(); @@ -1580,11 +1648,12 @@ void CmdMeshFillInteractiveHole::activated(int) Gui::View3DInventorViewer* viewer = view->getViewer(); viewer->setEditing(true); viewer->setEditingCursor( - QCursor(Gui::BitmapFactory().pixmapFromSvg("Mesh_CursorFillInteractive", QSize(32, 32)), - 6, - 6)); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - MeshGui::ViewProviderMeshFaceSet::fillHoleCallback); + QCursor(Gui::BitmapFactory().pixmapFromSvg("Mesh_CursorFillInteractive", QSize(32, 32)), 6, 6) + ); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + MeshGui::ViewProviderMeshFaceSet::fillHoleCallback + ); viewer->setSelectionEnabled(false); } } @@ -1621,8 +1690,9 @@ CmdMeshSegmentation::CmdMeshSegmentation() void CmdMeshSegmentation::activated(int) { - std::vector objs = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); Mesh::Feature* mesh = static_cast(objs.front()); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (!dlg) { @@ -1657,8 +1727,9 @@ CmdMeshSegmentationBestFit::CmdMeshSegmentationBestFit() void CmdMeshSegmentationBestFit::activated(int) { - std::vector objs = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); Mesh::Feature* mesh = static_cast(objs.front()); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (!dlg) { @@ -1701,8 +1772,9 @@ void CmdMeshMerge::activated(int) openCommand(QT_TRANSLATE_NOOP("Command", "Mesh merge")); Mesh::Feature* pcFeature = pcDoc->addObject("Mesh"); Mesh::MeshObject* newMesh = pcFeature->Mesh.startEditing(); - std::vector objs = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto obj : objs) { const MeshObject& mesh = static_cast(obj)->Mesh.getValue(); MeshCore::MeshKernel kernel = mesh.getKernel(); @@ -1744,8 +1816,9 @@ void CmdMeshSplitComponents::activated(int) } openCommand(QT_TRANSLATE_NOOP("Command", "Mesh split")); - std::vector objs = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto obj : objs) { const MeshObject& mesh = static_cast(obj)->Mesh.getValue(); std::vector> comps = mesh.getComponents(); @@ -1792,22 +1865,25 @@ void CmdMeshScale::activated(int) } bool ok {}; - double factor = QInputDialog::getDouble(Gui::getMainWindow(), - QObject::tr("Scaling"), - QObject::tr("Enter scaling factor:"), - 1, - 0, - std::numeric_limits::max(), - 5, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + double factor = QInputDialog::getDouble( + Gui::getMainWindow(), + QObject::tr("Scaling"), + QObject::tr("Enter scaling factor:"), + 1, + 0, + std::numeric_limits::max(), + 5, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok || factor == 0) { return; } openCommand(QT_TRANSLATE_NOOP("Command", "Mesh scale")); - std::vector objs = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); Base::Matrix4D mat; mat.scale(factor, factor, factor); for (auto obj : objs) { diff --git a/src/Mod/Mesh/Gui/DlgDecimating.cpp b/src/Mod/Mesh/Gui/DlgDecimating.cpp index b34b1db243..246402bd8f 100644 --- a/src/Mod/Mesh/Gui/DlgDecimating.cpp +++ b/src/Mod/Mesh/Gui/DlgDecimating.cpp @@ -41,10 +41,12 @@ DlgDecimating::DlgDecimating(QWidget* parent, Qt::WindowFlags fl) , ui(new Ui_DlgDecimating) { ui->setupUi(this); - connect(ui->checkAbsoluteNumber, - &QCheckBox::toggled, - this, - &DlgDecimating::onCheckAbsoluteNumberToggled); + connect( + ui->checkAbsoluteNumber, + &QCheckBox::toggled, + this, + &DlgDecimating::onCheckAbsoluteNumberToggled + ); ui->spinBoxReduction->setMinimumWidth(60); ui->checkAbsoluteNumber->setEnabled(false); onCheckAbsoluteNumberToggled(false); @@ -81,33 +83,40 @@ void DlgDecimating::onCheckAbsoluteNumberToggled(bool on) ui->groupBoxTolerance->setDisabled(on); if (on) { - disconnect(ui->sliderReduction, - qOverload(&QSlider::valueChanged), - ui->spinBoxReduction, - &QSpinBox::setValue); - disconnect(ui->spinBoxReduction, - qOverload(&QSpinBox::valueChanged), - ui->sliderReduction, - &QSlider::setValue); + disconnect( + ui->sliderReduction, + qOverload(&QSlider::valueChanged), + ui->spinBoxReduction, + &QSpinBox::setValue + ); + disconnect( + ui->spinBoxReduction, + qOverload(&QSpinBox::valueChanged), + ui->sliderReduction, + &QSlider::setValue + ); ui->spinBoxReduction->setRange(1, numberOfTriangles); ui->spinBoxReduction->setValue(int(numberOfTriangles * (1.0 - reduction()))); ui->spinBoxReduction->setSuffix(QString()); - ui->checkAbsoluteNumber->setText( - tr("Absolute number (Maximum: %1)").arg(numberOfTriangles)); + ui->checkAbsoluteNumber->setText(tr("Absolute number (Maximum: %1)").arg(numberOfTriangles)); } else { ui->spinBoxReduction->setRange(0, 100); ui->spinBoxReduction->setValue(ui->sliderReduction->value()); ui->spinBoxReduction->setSuffix(QStringLiteral("%")); ui->checkAbsoluteNumber->setText(tr("Absolute number")); - connect(ui->sliderReduction, - qOverload(&QSlider::valueChanged), - ui->spinBoxReduction, - &QSpinBox::setValue); - connect(ui->spinBoxReduction, - qOverload(&QSpinBox::valueChanged), - ui->sliderReduction, - &QSlider::setValue); + connect( + ui->sliderReduction, + qOverload(&QSlider::valueChanged), + ui->spinBoxReduction, + &QSpinBox::setValue + ); + connect( + ui->spinBoxReduction, + qOverload(&QSpinBox::valueChanged), + ui->sliderReduction, + &QSlider::setValue + ); } } diff --git a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp index 52e44d26c0..5fc435d2a4 100644 --- a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp +++ b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp @@ -124,7 +124,8 @@ DlgEvaluateMeshImp::DlgEvaluateMeshImp(QWidget* parent, Qt::WindowFlags fl) d->ui.line_8->setFrameShadow(QFrame::Sunken); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh/Evaluation"); + "User parameter:BaseApp/Preferences/Mod/Mesh/Evaluation" + ); d->checkNonManfoldPoints = hGrp->GetBool("CheckNonManifoldPoints", false); d->enableFoldsCheck = hGrp->GetBool("EnableFoldsCheck", false); d->strictlyDegenerated = hGrp->GetBool("StrictlyDegenerated", true); @@ -159,7 +160,8 @@ DlgEvaluateMeshImp::~DlgEvaluateMeshImp() try { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh/Evaluation"); + "User parameter:BaseApp/Preferences/Mod/Mesh/Evaluation" + ); hGrp->SetBool("CheckNonManifoldPoints", d->checkNonManfoldPoints); hGrp->SetBool("EnableFoldsCheck", d->enableFoldsCheck); hGrp->SetBool("StrictlyDegenerated", d->strictlyDegenerated); @@ -286,8 +288,7 @@ void DlgEvaluateMeshImp::slotDeletedObject(const App::DocumentObject& Obj) } } -void DlgEvaluateMeshImp::slotChangedObject(const App::DocumentObject& Obj, - const App::Property& Prop) +void DlgEvaluateMeshImp::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) { // if the current mesh object was modified update everything if (&Obj == d->meshFeature && Prop.is()) { @@ -344,8 +345,7 @@ void DlgEvaluateMeshImp::setMesh(Mesh::Feature* m) } } -void DlgEvaluateMeshImp::addViewProvider(const char* name, - const std::vector& indices) +void DlgEvaluateMeshImp::addViewProvider(const char* name, const std::vector& indices) { removeViewProvider(name); @@ -387,8 +387,9 @@ void DlgEvaluateMeshImp::onMeshNameButtonActivated(int i) QString item = d->ui.meshNameButton->itemData(i).toString(); d->meshFeature = nullptr; - std::vector objs = - getDocument()->getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = getDocument()->getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto obj : objs) { if (item == QLatin1String(obj->getNameInDocument())) { d->meshFeature = static_cast(obj); @@ -408,11 +409,14 @@ void DlgEvaluateMeshImp::refreshList() { QVector> items; if (this->getDocument()) { - std::vector objs = - this->getDocument()->getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector objs = this->getDocument()->getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto obj : objs) { - items.push_back(qMakePair(QString::fromUtf8(obj->Label.getValue()), - QString::fromLatin1(obj->getNameInDocument()))); + items.push_back(qMakePair( + QString::fromUtf8(obj->Label.getValue()), + QString::fromLatin1(obj->getNameInDocument()) + )); } } @@ -547,10 +551,12 @@ void DlgEvaluateMeshImp::onRepairOrientationButtonClicked() Gui::Document* doc = Gui::Application::Instance->getDocument(docName); doc->openCommand(QT_TRANSLATE_NOOP("Command", "Harmonize normals")); try { - Gui::Command::doCommand(Gui::Command::App, - R"(App.getDocument("%s").getObject("%s").harmonizeNormals())", - docName, - objName); + Gui::Command::doCommand( + Gui::Command::App, + R"(App.getDocument("%s").getObject("%s").harmonizeNormals())", + docName, + objName + ); } catch (const Base::Exception& e) { QMessageBox::warning(this, tr("Orientation"), QString::fromLatin1(e.what())); @@ -621,14 +627,15 @@ void DlgEvaluateMeshImp::onAnalyzeNonmanifoldsButtonClicked() } else { d->ui.checkNonmanifoldsButton->setText( - tr("%1 non-manifolds").arg(f_eval.CountManifolds() + point_indices.size())); + tr("%1 non-manifolds").arg(f_eval.CountManifolds() + point_indices.size()) + ); d->ui.checkNonmanifoldsButton->setChecked(true); d->ui.repairNonmanifoldsButton->setEnabled(true); d->ui.repairAllTogether->setEnabled(true); if (!ok1) { - const std::vector>& inds = - f_eval.GetIndices(); + const std::vector>& inds + = f_eval.GetIndices(); std::vector indices; indices.reserve(2 * inds.size()); std::vector>::const_iterator it; @@ -658,17 +665,20 @@ void DlgEvaluateMeshImp::onRepairNonmanifoldsButtonClicked() Gui::Document* doc = Gui::Application::Instance->getDocument(docName); doc->openCommand(QT_TRANSLATE_NOOP("Command", "Remove non-manifolds")); try { - Gui::Command::doCommand(Gui::Command::App, - R"(App.getDocument("%s").getObject("%s").removeNonManifolds())", - docName, - objName); + Gui::Command::doCommand( + Gui::Command::App, + R"(App.getDocument("%s").getObject("%s").removeNonManifolds())", + docName, + objName + ); if (d->checkNonManfoldPoints) { Gui::Command::doCommand( Gui::Command::App, R"(App.getDocument("%s").getObject("%s").removeNonManifoldPoints())", docName, - objName); + objName + ); } } catch (const Base::Exception& e) { @@ -762,10 +772,12 @@ void DlgEvaluateMeshImp::onRepairIndicesButtonClicked() Gui::Document* doc = Gui::Application::Instance->getDocument(docName); doc->openCommand(QT_TRANSLATE_NOOP("Command", "Fix indices")); try { - Gui::Command::doCommand(Gui::Command::App, - R"(App.getDocument("%s").getObject("%s").fixIndices())", - docName, - objName); + Gui::Command::doCommand( + Gui::Command::App, + R"(App.getDocument("%s").getObject("%s").fixIndices())", + docName, + objName + ); } catch (const Base::Exception& e) { QMessageBox::warning(this, tr("Indices"), QString::fromLatin1(e.what())); @@ -831,11 +843,13 @@ void DlgEvaluateMeshImp::onRepairDegeneratedButtonClicked() Gui::Document* doc = Gui::Application::Instance->getDocument(docName); doc->openCommand(QT_TRANSLATE_NOOP("Command", "Remove degenerated faces")); try { - Gui::Command::doCommand(Gui::Command::App, - R"(App.getDocument("%s").getObject("%s").fixDegenerations(%f))", - docName, - objName, - d->epsilonDegenerated); + Gui::Command::doCommand( + Gui::Command::App, + R"(App.getDocument("%s").getObject("%s").fixDegenerations(%f))", + docName, + objName, + d->epsilonDegenerated + ); } catch (const Base::Exception& e) { QMessageBox::warning(this, tr("Degenerations"), QString::fromLatin1(e.what())); @@ -906,7 +920,8 @@ void DlgEvaluateMeshImp::onRepairDuplicatedFacesButtonClicked() Gui::Command::App, R"(App.getDocument("%s").getObject("%s").removeDuplicatedFacets())", docName, - objName); + objName + ); } catch (const Base::Exception& e) { QMessageBox::warning(this, tr("Duplicated faces"), QString::fromLatin1(e.what())); @@ -975,7 +990,8 @@ void DlgEvaluateMeshImp::onRepairDuplicatedPointsButtonClicked() Gui::Command::App, R"(App.getDocument("%s").getObject("%s").removeDuplicatedPoints())", docName, - objName); + objName + ); } catch (const Base::Exception& e) { QMessageBox::warning(this, tr("Duplicated points"), QString::fromLatin1(e.what())); @@ -1138,7 +1154,8 @@ void DlgEvaluateMeshImp::onRepairFoldsButtonClicked() Gui::Command::App, R"(App.getDocument("%s").getObject("%s").removeFoldsOnSurface())", docName, - objName); + objName + ); } catch (const Base::Exception& e) { QMessageBox::warning(this, tr("Folds"), QString::fromLatin1(e.what())); @@ -1373,8 +1390,8 @@ DockEvaluateMeshImp::DockEvaluateMeshImp(QWidget* parent, Qt::WindowFlags fl) // embed this dialog into a dockable widget container Gui::DockWindowManager* pDockMgr = Gui::DockWindowManager::instance(); // use Qt macro for preparing for translation stuff (but not translating yet) - QDockWidget* dw = - pDockMgr->addDockWindow("Evaluate & Repair Mesh", scrollArea, Qt::RightDockWidgetArea); + QDockWidget* dw + = pDockMgr->addDockWindow("Evaluate & Repair Mesh", scrollArea, Qt::RightDockWidgetArea); dw->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); dw->show(); } diff --git a/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.cpp b/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.cpp index 9e7b0ce4c0..2177e608dc 100644 --- a/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.cpp +++ b/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.cpp @@ -37,8 +37,10 @@ DlgSettingsImportExport::DlgSettingsImportExport(QWidget* parent) , ui(new Ui_DlgSettingsImportExport) { ui->setupUi(this); - ui->exportAmfCompressed->setToolTip(tr("This parameter indicates whether ZIP compression\n" - "is used when writing a file in AMF format")); + ui->exportAmfCompressed->setToolTip( + tr("This parameter indicates whether ZIP compression\n" + "is used when writing a file in AMF format") + ); } DlgSettingsImportExport::~DlgSettingsImportExport() @@ -50,7 +52,8 @@ DlgSettingsImportExport::~DlgSettingsImportExport() void DlgSettingsImportExport::saveSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh"); + "User parameter:BaseApp/Preferences/Mod/Mesh" + ); double value = ui->maxDeviationExport->value().getValue(); handle->SetFloat("MaxDeviationExport", value); @@ -61,14 +64,17 @@ void DlgSettingsImportExport::saveSettings() asy->SetASCII("Width", ui->asymptoteWidth->text().toLatin1()); asy->SetASCII("Height", ui->asymptoteHeight->text().toLatin1()); - MeshCore::MeshOutput::SetAsymptoteSize(ui->asymptoteWidth->text().toStdString(), - ui->asymptoteHeight->text().toStdString()); + MeshCore::MeshOutput::SetAsymptoteSize( + ui->asymptoteWidth->text().toStdString(), + ui->asymptoteHeight->text().toStdString() + ); } void DlgSettingsImportExport::loadSettings() { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh"); + "User parameter:BaseApp/Preferences/Mod/Mesh" + ); double value = ui->maxDeviationExport->value().getValue(); value = handle->GetFloat("MaxDeviationExport", value); ui->maxDeviationExport->setValue(value); diff --git a/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h b/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h index 52a1c8cba2..912c696a8b 100644 --- a/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h +++ b/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h @@ -26,7 +26,7 @@ #define MESHGUI_DLGSETTINGSIMPORTEXPORTIMP_H #ifndef MESH_GLOBAL_H -#include +# include #endif #include diff --git a/src/Mod/Mesh/Gui/DlgSettingsMeshView.h b/src/Mod/Mesh/Gui/DlgSettingsMeshView.h index 81c550a322..dfa60fd839 100644 --- a/src/Mod/Mesh/Gui/DlgSettingsMeshView.h +++ b/src/Mod/Mesh/Gui/DlgSettingsMeshView.h @@ -26,7 +26,7 @@ #define MESHGUI_DLGSETTINGSMESHVIEW_H #ifndef MESH_GLOBAL_H -#include +# include #endif #include diff --git a/src/Mod/Mesh/Gui/DlgSmoothing.cpp b/src/Mod/Mesh/Gui/DlgSmoothing.cpp index d2f75841c2..cc17aa0890 100644 --- a/src/Mod/Mesh/Gui/DlgSmoothing.cpp +++ b/src/Mod/Mesh/Gui/DlgSmoothing.cpp @@ -150,8 +150,7 @@ TaskSmoothing::TaskSmoothing() addTaskBox(widget, false, nullptr); selection = new Selection(); // NOLINT - selection->setObjects( - Gui::Selection().getSelectionEx(nullptr, Mesh::Feature::getClassTypeId())); + selection->setObjects(Gui::Selection().getSelectionEx(nullptr, Mesh::Feature::getClassTypeId())); Gui::Selection().clearSelection(); QWidget* box = addTaskBoxWithoutHeader(selection); box->hide(); diff --git a/src/Mod/Mesh/Gui/DlgSmoothing.h b/src/Mod/Mesh/Gui/DlgSmoothing.h index a4a8d377b6..02be703035 100644 --- a/src/Mod/Mesh/Gui/DlgSmoothing.h +++ b/src/Mod/Mesh/Gui/DlgSmoothing.h @@ -31,7 +31,7 @@ #include #ifndef MESH_GLOBAL_H -#include +# include #endif class QButtonGroup; diff --git a/src/Mod/Mesh/Gui/MeshEditor.cpp b/src/Mod/Mesh/Gui/MeshEditor.cpp index 912eb434ea..de03077ee9 100644 --- a/src/Mod/Mesh/Gui/MeshEditor.cpp +++ b/src/Mod/Mesh/Gui/MeshEditor.cpp @@ -161,8 +161,10 @@ std::vector ViewProviderFace::getDisplayModes() const return modes; } -SoPickedPoint* ViewProviderFace::getPickedPoint(const SbVec2s& pos, - const Gui::View3DInventorViewer* viewer) const +SoPickedPoint* ViewProviderFace::getPickedPoint( + const SbVec2s& pos, + const Gui::View3DInventorViewer* viewer +) const { SoSeparator* root = new SoSeparator; root->ref(); @@ -222,9 +224,7 @@ void MeshFaceAddition::finishEditing() viewer->removeViewProvider(faceView); // faceView->mesh->finishEditing(); - viewer->removeEventCallback(SoEvent::getClassTypeId(), - MeshFaceAddition::addFacetCallback, - this); + viewer->removeEventCallback(SoEvent::getClassTypeId(), MeshFaceAddition::addFacetCallback, this); this->deleteLater(); } @@ -291,10 +291,8 @@ void MeshFaceAddition::showMarker(SoPickedPoint* pp) if (detail->isOfType(SoFaceDetail::getClassTypeId())) { const SoFaceDetail* fd = static_cast(detail); Mesh::Feature* mf = faceView->mesh->getObject(); - const MeshCore::MeshFacetArray& facets = - mf->Mesh.getValuePtr()->getKernel().GetFacets(); - const MeshCore::MeshPointArray& points = - mf->Mesh.getValuePtr()->getKernel().GetPoints(); + const MeshCore::MeshFacetArray& facets = mf->Mesh.getValuePtr()->getKernel().GetFacets(); + const MeshCore::MeshPointArray& points = mf->Mesh.getValuePtr()->getKernel().GetPoints(); // is the face index valid? int face_index = fd->getFaceIndex(); if (face_index >= (int)facets.size()) { @@ -435,8 +433,7 @@ namespace MeshGui // for sorting of elements struct NofFacetsCompare { - bool operator()(const std::vector& rclC1, - const std::vector& rclC2) + bool operator()(const std::vector& rclC1, const std::vector& rclC2) { return rclC1.size() < rclC2.size(); } @@ -493,7 +490,8 @@ void MeshFillHole::startEditing(MeshGui::ViewProviderMesh* vp) viewer->addEventCallback(SoEvent::getClassTypeId(), MeshFillHole::fileHoleCallback, this); // NOLINTBEGIN myConnection = App::GetApplication().signalChangedObject.connect( - std::bind(&MeshFillHole::slotChangedObject, this, sp::_1, sp::_2)); + std::bind(&MeshFillHole::slotChangedObject, this, sp::_1, sp::_2) + ); // NOLINTEND Gui::coinRemoveAllChildren(myBoundariesRoot); @@ -624,8 +622,7 @@ void MeshFillHole::createPolygons() } } -SoNode* MeshFillHole::getPickedPolygon( - const SoRayPickAction& action /*SoNode* root, const SbVec2s& pos*/) const +SoNode* MeshFillHole::getPickedPolygon(const SoRayPickAction& action /*SoNode* root, const SbVec2s& pos*/) const { SoPolygon* poly = nullptr; const SoPickedPointList& points = action.getPickedPointList(); @@ -648,10 +645,12 @@ SoNode* MeshFillHole::getPickedPolygon( return poly; } -float MeshFillHole::findClosestPoint(const SbLine& ray, - const TBoundary& polygon, - Mesh::PointIndex& vertex_index, - SbVec3f& closestPoint) const +float MeshFillHole::findClosestPoint( + const SbLine& ray, + const TBoundary& polygon, + Mesh::PointIndex& vertex_index, + SbVec3f& closestPoint +) const { // now check which vertex of the polygon is closest to the ray float minDist = std::numeric_limits::max(); @@ -699,8 +698,8 @@ void MeshFillHole::fileHoleCallback(void* ud, SoEventCallback* n) // now check which vertex of the polygon is closest to the ray Mesh::PointIndex vertex_index {}; SbVec3f closestPoint; - float minDist = - self->findClosestPoint(rp.getLine(), it->second, vertex_index, closestPoint); + float minDist + = self->findClosestPoint(rp.getLine(), it->second, vertex_index, closestPoint); if (minDist < 1.0F) { if (self->myNumPoints == 0) { self->myVertex->point.set1Value(0, closestPoint); @@ -715,8 +714,7 @@ void MeshFillHole::fileHoleCallback(void* ud, SoEventCallback* n) else if (ev->getTypeId() == SoMouseButtonEvent::getClassTypeId()) { n->setHandled(); const SoMouseButtonEvent* mbe = static_cast(ev); - if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 - && mbe->getState() == SoButtonEvent::UP) { + if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::UP) { if (self->myNumPoints > 1) { return; } @@ -736,10 +734,8 @@ void MeshFillHole::fileHoleCallback(void* ud, SoEventCallback* n) // now check which vertex of the polygon is closest to the ray Mesh::PointIndex vertex_index {}; SbVec3f closestPoint; - float minDist = self->findClosestPoint(rp.getLine(), - it->second, - vertex_index, - closestPoint); + float minDist + = self->findClosestPoint(rp.getLine(), it->second, vertex_index, closestPoint); if (minDist < 1.0F) { if (self->myNumPoints == 0) { self->myBoundaryRoot->addChild(node); diff --git a/src/Mod/Mesh/Gui/MeshEditor.h b/src/Mod/Mesh/Gui/MeshEditor.h index d9dd31fe24..26959f647a 100644 --- a/src/Mod/Mesh/Gui/MeshEditor.h +++ b/src/Mod/Mesh/Gui/MeshEditor.h @@ -73,8 +73,7 @@ public: void setDisplayMode(const char* ModeName) override; const char* getDefaultDisplayMode() const override; std::vector getDisplayModes() const override; - SoPickedPoint* getPickedPoint(const SbVec2s& pos, - const Gui::View3DInventorViewer* viewer) const; + SoPickedPoint* getPickedPoint(const SbVec2s& pos, const Gui::View3DInventorViewer* viewer) const; ViewProviderMesh* mesh {nullptr}; std::vector index; @@ -129,10 +128,12 @@ public: MeshHoleFiller(MeshHoleFiller&&) = delete; MeshHoleFiller& operator=(const MeshHoleFiller&) = delete; MeshHoleFiller& operator=(MeshHoleFiller&&) = delete; - virtual bool fillHoles(Mesh::MeshObject&, - const std::list>&, - Mesh::PointIndex, - Mesh::PointIndex) + virtual bool fillHoles( + Mesh::MeshObject&, + const std::list>&, + Mesh::PointIndex, + Mesh::PointIndex + ) { return false; } @@ -165,10 +166,7 @@ private: static void fileHoleCallback(void* ud, SoEventCallback* n); void createPolygons(); SoNode* getPickedPolygon(const SoRayPickAction& action) const; - float findClosestPoint(const SbLine& ray, - const TBoundary& polygon, - Mesh::PointIndex&, - SbVec3f&) const; + float findClosestPoint(const SbLine& ray, const TBoundary& polygon, Mesh::PointIndex&, SbVec3f&) const; void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); private: diff --git a/src/Mod/Mesh/Gui/MeshSelection.cpp b/src/Mod/Mesh/Gui/MeshSelection.cpp index 0ffb60800c..5fe80baae1 100644 --- a/src/Mod/Mesh/Gui/MeshSelection.cpp +++ b/src/Mod/Mesh/Gui/MeshSelection.cpp @@ -170,8 +170,7 @@ Gui::View3DInventorViewer* MeshSelection::getViewer() const return nullptr; } -void MeshSelection::startInteractiveCallback(Gui::View3DInventorViewer* viewer, - SoEventCallbackCB* cb) +void MeshSelection::startInteractiveCallback(Gui::View3DInventorViewer* viewer, SoEventCallbackCB* cb) { if (this->activeCB) { return; @@ -221,9 +220,7 @@ void MeshSelection::prepareFreehandSelection(bool add, SoEventCallbackCB* cb) viewer->setComponentCursor(custom); }; - QObject::connect(viewer, - &Gui::View3DInventorViewer::devicePixelRatioChanged, - setComponentCursor); + QObject::connect(viewer, &Gui::View3DInventorViewer::devicePixelRatioChanged, setComponentCursor); setComponentCursor(); this->addToSelection = add; } @@ -502,10 +499,11 @@ void MeshSelection::selectGLCallback(void* ud, SoEventCallback* n) } std::vector rf; rf.swap(faces); - std::vector vf = - vp->getVisibleFacetsAfterZoom(rect, - view->getSoRenderManager()->getViewportRegion(), - view->getSoRenderManager()->getCamera()); + std::vector vf = vp->getVisibleFacetsAfterZoom( + rect, + view->getSoRenderManager()->getViewportRegion(), + view->getSoRenderManager()->getCamera() + ); // get common facets of the viewport and the visible one std::sort(vf.begin(), vf.end()); diff --git a/src/Mod/Mesh/Gui/MeshSelection.h b/src/Mod/Mesh/Gui/MeshSelection.h index cae12c2ce8..7ecc22a080 100644 --- a/src/Mod/Mesh/Gui/MeshSelection.h +++ b/src/Mod/Mesh/Gui/MeshSelection.h @@ -31,7 +31,7 @@ #include #include #ifndef MESH_GLOBAL_H -#include +# include #endif diff --git a/src/Mod/Mesh/Gui/PreCompiled.h b/src/Mod/Mesh/Gui/PreCompiled.h index 6164c6352f..08e3c7743a 100644 --- a/src/Mod/Mesh/Gui/PreCompiled.h +++ b/src/Mod/Mesh/Gui/PreCompiled.h @@ -47,7 +47,7 @@ #include #if defined(FC_OS_WIN32) -#include +# include #endif #endif // MESHGUI_PRECOMPILED_H diff --git a/src/Mod/Mesh/Gui/PropertyEditorMesh.cpp b/src/Mod/Mesh/Gui/PropertyEditorMesh.cpp index 274bd482e4..621f234930 100644 --- a/src/Mod/Mesh/Gui/PropertyEditorMesh.cpp +++ b/src/Mod/Mesh/Gui/PropertyEditorMesh.cpp @@ -38,17 +38,20 @@ PropertyMeshKernelItem::PropertyMeshKernelItem() { // NOLINTBEGIN m_p = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_p->setParent(this); m_p->setPropertyName(QLatin1String("Points")); this->appendChild(m_p); m_e = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_e->setParent(this); m_e->setPropertyName(QLatin1String("Edges")); this->appendChild(m_e); m_f = static_cast( - Gui::PropertyEditor::PropertyIntegerItem::create()); + Gui::PropertyEditor::PropertyIntegerItem::create() + ); m_f->setParent(this); m_f->setPropertyName(QLatin1String("Faces")); this->appendChild(m_f); @@ -89,9 +92,11 @@ void PropertyMeshKernelItem::setValue(const QVariant& value) Q_UNUSED(value); } -QWidget* PropertyMeshKernelItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyMeshKernelItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { Q_UNUSED(parent); Q_UNUSED(method); diff --git a/src/Mod/Mesh/Gui/PropertyEditorMesh.h b/src/Mod/Mesh/Gui/PropertyEditorMesh.h index 2e13450a1a..fc84042cc6 100644 --- a/src/Mod/Mesh/Gui/PropertyEditorMesh.h +++ b/src/Mod/Mesh/Gui/PropertyEditorMesh.h @@ -27,7 +27,7 @@ #include #ifndef MESH_GLOBAL_H -#include +# include #endif diff --git a/src/Mod/Mesh/Gui/RemeshGmsh.cpp b/src/Mod/Mesh/Gui/RemeshGmsh.cpp index 661eb0c736..59a37d9af6 100644 --- a/src/Mod/Mesh/Gui/RemeshGmsh.cpp +++ b/src/Mod/Mesh/Gui/RemeshGmsh.cpp @@ -54,8 +54,9 @@ public: void appendText(const QString& text, bool error) { - syntax->setParagraphType(error ? Gui::DockWnd::ReportHighlighter::Error - : Gui::DockWnd::ReportHighlighter::Message); + syntax->setParagraphType( + error ? Gui::DockWnd::ReportHighlighter::Error : Gui::DockWnd::ReportHighlighter::Message + ); QTextCursor cursor(ui.outputWindow->document()); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::End); diff --git a/src/Mod/Mesh/Gui/RemeshGmsh.h b/src/Mod/Mesh/Gui/RemeshGmsh.h index 6ff80c8048..3a805a4590 100644 --- a/src/Mod/Mesh/Gui/RemeshGmsh.h +++ b/src/Mod/Mesh/Gui/RemeshGmsh.h @@ -99,9 +99,11 @@ class MeshGuiExport RemeshGmsh: public GmshWidget Q_OBJECT public: - explicit RemeshGmsh(Mesh::Feature* mesh, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit RemeshGmsh( + Mesh::Feature* mesh, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~RemeshGmsh() override; protected: diff --git a/src/Mod/Mesh/Gui/RemoveComponents.h b/src/Mod/Mesh/Gui/RemoveComponents.h index 28565152a9..d40d1b96c5 100644 --- a/src/Mod/Mesh/Gui/RemoveComponents.h +++ b/src/Mod/Mesh/Gui/RemoveComponents.h @@ -87,8 +87,7 @@ class MeshGuiExport RemoveComponentsDialog: public QDialog Q_OBJECT public: - explicit RemoveComponentsDialog(QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit RemoveComponentsDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); ~RemoveComponentsDialog() override; void reject() override; diff --git a/src/Mod/Mesh/Gui/Segmentation.cpp b/src/Mod/Mesh/Gui/Segmentation.cpp index c4d74f936c..1e246297cf 100644 --- a/src/Mod/Mesh/Gui/Segmentation.cpp +++ b/src/Mod/Mesh/Gui/Segmentation.cpp @@ -86,33 +86,45 @@ void Segmentation::accept() std::vector segm; if (ui->groupBoxFree->isChecked()) { segm.emplace_back( - std::make_shared(meshCurv.GetCurvature(), - ui->numFree->value(), - ui->tol1Free->value(), - ui->tol2Free->value(), - ui->crv1Free->value(), - ui->crv2Free->value())); + std::make_shared( + meshCurv.GetCurvature(), + ui->numFree->value(), + ui->tol1Free->value(), + ui->tol2Free->value(), + ui->crv1Free->value(), + ui->crv2Free->value() + ) + ); } if (ui->groupBoxCyl->isChecked()) { segm.emplace_back( - std::make_shared(meshCurv.GetCurvature(), - ui->numCyl->value(), - ui->tol1Cyl->value(), - ui->tol2Cyl->value(), - ui->crvCyl->value())); + std::make_shared( + meshCurv.GetCurvature(), + ui->numCyl->value(), + ui->tol1Cyl->value(), + ui->tol2Cyl->value(), + ui->crvCyl->value() + ) + ); } if (ui->groupBoxSph->isChecked()) { segm.emplace_back( - std::make_shared(meshCurv.GetCurvature(), - ui->numSph->value(), - ui->tolSph->value(), - ui->crvSph->value())); + std::make_shared( + meshCurv.GetCurvature(), + ui->numSph->value(), + ui->tolSph->value(), + ui->crvSph->value() + ) + ); } if (ui->groupBoxPln->isChecked()) { segm.emplace_back( - std::make_shared(meshCurv.GetCurvature(), - ui->numPln->value(), - ui->tolPln->value())); + std::make_shared( + meshCurv.GetCurvature(), + ui->numPln->value(), + ui->tolPln->value() + ) + ); } finder.FindSegments(segm); diff --git a/src/Mod/Mesh/Gui/Segmentation.h b/src/Mod/Mesh/Gui/Segmentation.h index f41d9c492b..fff3b11811 100644 --- a/src/Mod/Mesh/Gui/Segmentation.h +++ b/src/Mod/Mesh/Gui/Segmentation.h @@ -30,7 +30,7 @@ #include #include #ifndef MESH_GLOBAL_H -#include +# include #endif @@ -47,9 +47,11 @@ class Ui_Segmentation; class MeshGuiExport Segmentation: public QWidget { public: - explicit Segmentation(Mesh::Feature* mesh, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit Segmentation( + Mesh::Feature* mesh, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~Segmentation() override; void accept(); diff --git a/src/Mod/Mesh/Gui/SegmentationBestFit.cpp b/src/Mod/Mesh/Gui/SegmentationBestFit.cpp index 84b60a8dfd..47454d07e9 100644 --- a/src/Mod/Mesh/Gui/SegmentationBestFit.cpp +++ b/src/Mod/Mesh/Gui/SegmentationBestFit.cpp @@ -121,12 +121,14 @@ public: base.z, axis.x, axis.y, - axis.z); + axis.z + ); Gui::Command::doCommand( Gui::Command::App, "axis = cyl.Placement.Rotation.multVec(App.Vector(0,0,1))\n" - "print('Final axis: ({}, {}, {})'.format(axis.x, axis.y, axis.z))\n"); + "print('Final axis: ({}, {}, {})'.format(axis.x, axis.y, axis.z))\n" + ); } catch (...) { } @@ -158,11 +160,13 @@ public: }; } // namespace MeshGui -ParametersDialog::ParametersDialog(std::vector& val, - FitParameter* fitPar, - ParameterList par, - Mesh::Feature* mesh, - QWidget* parent) +ParametersDialog::ParametersDialog( + std::vector& val, + FitParameter* fitPar, + ParameterList par, + Mesh::Feature* mesh, + QWidget* parent +) : QDialog(parent) , values(val) , fitParameter(fitPar) @@ -301,9 +305,7 @@ void ParametersDialog::onComputeClicked() meshSel.clearSelection(); } else { - QMessageBox::warning(this, - tr("No selection"), - tr("Before fitting the surface select an area.")); + QMessageBox::warning(this, tr("No selection"), tr("Before fitting the surface select an area.")); } } @@ -412,8 +414,7 @@ void SegmentationBestFit::onCylinderParametersClicked() static QPointer dialog = nullptr; if (!dialog) { - dialog = - new ParametersDialog(cylinderParameter, new CylinderFitParameter, list, myMesh, this); + dialog = new ParametersDialog(cylinderParameter, new CylinderFitParameter, list, myMesh, this); } dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->show(); @@ -454,18 +455,23 @@ void SegmentationBestFit::accept() MeshCore::AbstractSurfaceFit* fitter {}; if (cylinderParameter.size() == 7) { std::vector& p = cylinderParameter; - fitter = new MeshCore::CylinderSurfaceFit(Base::Vector3f(p[0], p[1], p[2]), - Base::Vector3f(p[3], p[4], p[5]), - p[6]); + fitter = new MeshCore::CylinderSurfaceFit( + Base::Vector3f(p[0], p[1], p[2]), + Base::Vector3f(p[3], p[4], p[5]), + p[6] + ); } else { fitter = new MeshCore::CylinderSurfaceFit; } segm.emplace_back( - std::make_shared(fitter, - kernel, - ui->numCyl->value(), - ui->tolCyl->value())); + std::make_shared( + fitter, + kernel, + ui->numCyl->value(), + ui->tolCyl->value() + ) + ); } if (ui->groupBoxSph->isChecked()) { MeshCore::AbstractSurfaceFit* fitter {}; @@ -477,26 +483,34 @@ void SegmentationBestFit::accept() fitter = new MeshCore::SphereSurfaceFit; } segm.emplace_back( - std::make_shared(fitter, - kernel, - ui->numSph->value(), - ui->tolSph->value())); + std::make_shared( + fitter, + kernel, + ui->numSph->value(), + ui->tolSph->value() + ) + ); } if (ui->groupBoxPln->isChecked()) { MeshCore::AbstractSurfaceFit* fitter {}; if (planeParameter.size() == 6) { std::vector& p = planeParameter; - fitter = new MeshCore::PlaneSurfaceFit(Base::Vector3f(p[0], p[1], p[2]), - Base::Vector3f(p[3], p[4], p[5])); + fitter = new MeshCore::PlaneSurfaceFit( + Base::Vector3f(p[0], p[1], p[2]), + Base::Vector3f(p[3], p[4], p[5]) + ); } else { fitter = new MeshCore::PlaneSurfaceFit; } segm.emplace_back( - std::make_shared(fitter, - kernel, - ui->numPln->value(), - ui->tolPln->value())); + std::make_shared( + fitter, + kernel, + ui->numPln->value(), + ui->tolPln->value() + ) + ); } finder.FindSegments(segm); diff --git a/src/Mod/Mesh/Gui/SegmentationBestFit.h b/src/Mod/Mesh/Gui/SegmentationBestFit.h index 2af0ee90c7..d686458a84 100644 --- a/src/Mod/Mesh/Gui/SegmentationBestFit.h +++ b/src/Mod/Mesh/Gui/SegmentationBestFit.h @@ -70,11 +70,13 @@ class ParametersDialog: public QDialog Q_OBJECT public: - ParametersDialog(std::vector&, - FitParameter*, - ParameterList, - Mesh::Feature* mesh, - QWidget* parent = nullptr); + ParametersDialog( + std::vector&, + FitParameter*, + ParameterList, + Mesh::Feature* mesh, + QWidget* parent = nullptr + ); ~ParametersDialog() override; void accept() override; void reject() override; @@ -101,9 +103,11 @@ class MeshGuiExport SegmentationBestFit: public QWidget Q_OBJECT public: - explicit SegmentationBestFit(Mesh::Feature* mesh, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit SegmentationBestFit( + Mesh::Feature* mesh, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~SegmentationBestFit() override; void accept(); diff --git a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp index b3b7ce9c0a..610ad2f6ff 100644 --- a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp +++ b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp @@ -25,23 +25,23 @@ #include #ifndef FC_OS_WIN32 -#ifndef GL_GLEXT_PROTOTYPES -#define GL_GLEXT_PROTOTYPES 1 -#endif +# ifndef GL_GLEXT_PROTOTYPES +# define GL_GLEXT_PROTOTYPES 1 +# endif #else -#include +# include #endif #include #include #ifdef FC_OS_MACOSX -#include -#include -#include +# include +# include +# include #else -#include -#include -#include +# include +# include +# include #endif #include #include @@ -84,10 +84,12 @@ public: Private(); bool canRenderGLArray(SoGLRenderAction*) const; - void generateGLArrays(SoGLRenderAction* action, - SoMaterialBindingElement::Binding matbind, - std::vector& vertex, - std::vector& index); + void generateGLArrays( + SoGLRenderAction* action, + SoMaterialBindingElement::Binding matbind, + std::vector& vertex, + std::vector& index + ); void renderFacesGLArray(SoGLRenderAction*); void renderCoordsGLArray(SoGLRenderAction*); void update(); @@ -109,8 +111,7 @@ bool MeshRenderer::Private::canRenderGLArray(SoGLRenderAction* action) const if (!init) { vboAvailable = Gui::OpenGLBuffer::isVBOSupported(action->getCacheContext()); if (!vboAvailable) { - SoDebugError::postInfo("MeshRenderer", - "GL_ARB_vertex_buffer_object extension not supported"); + SoDebugError::postInfo("MeshRenderer", "GL_ARB_vertex_buffer_object extension not supported"); } init = true; } @@ -118,10 +119,12 @@ bool MeshRenderer::Private::canRenderGLArray(SoGLRenderAction* action) const return vboAvailable; } -void MeshRenderer::Private::generateGLArrays(SoGLRenderAction* action, - SoMaterialBindingElement::Binding matbind, - std::vector& vertex, - std::vector& index) +void MeshRenderer::Private::generateGLArrays( + SoGLRenderAction* action, + SoMaterialBindingElement::Binding matbind, + std::vector& vertex, + std::vector& index +) { if (vertex.empty() || index.empty()) { return; @@ -215,10 +218,12 @@ public: {} bool canRenderGLArray(SoGLRenderAction*) const; - void generateGLArrays(SoGLRenderAction* action, - SoMaterialBindingElement::Binding matbind, - std::vector& vertex, - std::vector& index); + void generateGLArrays( + SoGLRenderAction* action, + SoMaterialBindingElement::Binding matbind, + std::vector& vertex, + std::vector& index + ); void renderFacesGLArray(SoGLRenderAction* action); void renderCoordsGLArray(SoGLRenderAction* action); void update() @@ -234,10 +239,12 @@ bool MeshRenderer::Private::canRenderGLArray(SoGLRenderAction*) const return true; } -void MeshRenderer::Private::generateGLArrays(SoGLRenderAction*, - SoMaterialBindingElement::Binding matbind, - std::vector& vertex, - std::vector& index) +void MeshRenderer::Private::generateGLArrays( + SoGLRenderAction*, + SoMaterialBindingElement::Binding matbind, + std::vector& vertex, + std::vector& index +) { if (vertex.empty() || index.empty()) { return; @@ -305,10 +312,12 @@ public: { return false; } - void generateGLArrays(SoGLRenderAction*, - SoMaterialBindingElement::Binding, - std::vector&, - std::vector&) + void generateGLArrays( + SoGLRenderAction*, + SoMaterialBindingElement::Binding, + std::vector&, + std::vector& + ) {} void renderFacesGLArray(SoGLRenderAction*) {} @@ -342,10 +351,12 @@ bool MeshRenderer::needUpdate(SoGLRenderAction* action) return p->needUpdate(action); } -void MeshRenderer::generateGLArrays(SoGLRenderAction* action, - SoMaterialBindingElement::Binding matbind, - std::vector& vertex, - std::vector& index) +void MeshRenderer::generateGLArrays( + SoGLRenderAction* action, + SoMaterialBindingElement::Binding matbind, + std::vector& vertex, + std::vector& index +) { SoGLLazyElement* gl = SoGLLazyElement::getInstance(action->getState()); if (gl) { @@ -580,29 +591,33 @@ void SoFCIndexedFaceSet::drawFaces(SoGLRenderAction* action) SoTextureCoordinateBundle tb(action, true, false); SbBool sendNormals = !mb.isColorOnly() || tb.isFunction(); - this->getVertexData(state, - coords, - normals, - cindices, - nindices, - tindices, - mindices, - numindices, - sendNormals, - normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); mb.sendFirst(); // make sure we have the correct material - drawCoords(static_cast(coords), - cindices, - numindices, - normals, - nindices, - &mb, - mindices, - binding, - &tb, - tindices); + drawCoords( + static_cast(coords), + cindices, + numindices, + normals, + nindices, + &mb, + mindices, + binding, + &tb, + tindices + ); // getVertexData() internally calls readLockNormalCache() that read locks // the normal cache. When the cache is not needed any more we must call @@ -617,16 +632,18 @@ void SoFCIndexedFaceSet::drawFaces(SoGLRenderAction* action) } } -void SoFCIndexedFaceSet::drawCoords(const SoGLCoordinateElement* const vertexlist, - const int32_t* vertexindices, - int numindices, - const SbVec3f* normals, - const int32_t* normalindices, - SoMaterialBundle* materials, - const int32_t* /*matindices*/, - const int32_t binding, - const SoTextureCoordinateBundle* const /*texcoords*/, - const int32_t* /*texindices*/) +void SoFCIndexedFaceSet::drawCoords( + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int numindices, + const SbVec3f* normals, + const int32_t* normalindices, + SoMaterialBundle* materials, + const int32_t* /*matindices*/, + const int32_t binding, + const SoTextureCoordinateBundle* const /*texcoords*/, + const int32_t* /*texindices*/ +) { const SbVec3f* coords3d = nullptr; coords3d = vertexlist->getArrayPtr3(); @@ -736,16 +753,18 @@ void SoFCIndexedFaceSet::generateGLArrays(SoGLRenderAction* action) SbBool sendNormals = true; SoState* state = action->getState(); - this->getVertexData(state, - coords, - normals, - cindices, - nindices, - tindices, - mindices, - numindices, - sendNormals, - normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); const SbVec3f* points = coords->getArrayPtr3(); @@ -771,8 +790,7 @@ void SoFCIndexedFaceSet::generateGLArrays(SoGLRenderAction* action) SoNormalBindingElement::Binding normbind = SoNormalBindingElement::get(state); if (normbind == SoNormalBindingElement::PER_VERTEX_INDEXED) { if (matbind == SoMaterialBindingElement::PER_FACE) { - face_vertices.reserve(3 * numTria - * 10); // duplicate each vertex (rgba, normal, vertex) + face_vertices.reserve(3 * numTria * 10); // duplicate each vertex (rgba, normal, vertex) face_indices.resize(3 * numTria); if (numcolors != static_cast(numTria)) { @@ -780,7 +798,8 @@ void SoFCIndexedFaceSet::generateGLArrays(SoGLRenderAction* action) "SoFCIndexedFaceSet::generateGLArrays", "The number of faces (%d) does not match with the number of colors (%d).", numTria, - numcolors); + numcolors + ); } // the nindices must have the length of numindices @@ -813,8 +832,7 @@ void SoFCIndexedFaceSet::generateGLArrays(SoGLRenderAction* action) } } else if (matbind == SoMaterialBindingElement::PER_VERTEX_INDEXED) { - face_vertices.reserve(3 * numTria - * 10); // duplicate each vertex (rgba, normal, vertex) + face_vertices.reserve(3 * numTria * 10); // duplicate each vertex (rgba, normal, vertex) face_indices.resize(3 * numTria); if (numcolors != coords->getNum()) { @@ -822,7 +840,8 @@ void SoFCIndexedFaceSet::generateGLArrays(SoGLRenderAction* action) "SoFCIndexedFaceSet::generateGLArrays", "The number of points (%d) does not match with the number of colors (%d).", coords->getNum(), - numcolors); + numcolors + ); } // the nindices must have the length of numindices @@ -996,10 +1015,8 @@ void SoFCIndexedFaceSet::startSelection(SoAction* action) int bufSize = 5 * (this->coordIndex.getNum() / 4); // make the buffer big enough this->selectBuf = new GLuint[bufSize]; - SbMatrix view = - SoViewingMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft - SbMatrix proj = - SoProjectionMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft + SbMatrix view = SoViewingMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft + SbMatrix proj = SoProjectionMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft glSelectBuffer(bufSize, selectBuf); glRenderMode(GL_SELECT); @@ -1015,9 +1032,11 @@ void SoFCIndexedFaceSet::startSelection(SoAction* action) glLoadIdentity(); if (w > 0 && h > 0) { - glTranslatef((viewport[2] - 2 * (x - viewport[0])) / w, - (viewport[3] - 2 * (y - viewport[1])) / h, - 0); + glTranslatef( + (viewport[2] - 2 * (x - viewport[0])) / w, + (viewport[3] - 2 * (y - viewport[1])) / h, + 0 + ); glScalef(viewport[2] / w, viewport[3] / h, 1.0); } glMultMatrixf(/*mp*/ (float*)proj); @@ -1081,10 +1100,8 @@ void SoFCIndexedFaceSet::renderSelectionGeometry(const SbVec3f* coords3d) void SoFCIndexedFaceSet::startVisibility(SoAction* action) { - SbMatrix view = - SoViewingMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft - SbMatrix proj = - SoProjectionMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft + SbMatrix view = SoViewingMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft + SbMatrix proj = SoProjectionMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft glMatrixMode(GL_PROJECTION); glPushMatrix(); diff --git a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h index f00c48790f..2e578d0560 100644 --- a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h +++ b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h @@ -31,7 +31,7 @@ #include #include #ifndef MESH_GLOBAL_H -#include +# include #endif @@ -51,10 +51,12 @@ class MeshRenderer public: MeshRenderer(); ~MeshRenderer(); - void generateGLArrays(SoGLRenderAction*, - SoMaterialBindingElement::Binding binding, - std::vector& vertex, - std::vector& index); + void generateGLArrays( + SoGLRenderAction*, + SoMaterialBindingElement::Binding binding, + std::vector& vertex, + std::vector& index + ); void renderFacesGLArray(SoGLRenderAction* action); void renderCoordsGLArray(SoGLRenderAction* action); bool canRenderGLArray(SoGLRenderAction* action) const; @@ -119,16 +121,18 @@ protected: ~SoFCIndexedFaceSet() override = default; void GLRender(SoGLRenderAction* action) override; void drawFaces(SoGLRenderAction* action); - void drawCoords(const SoGLCoordinateElement* const vertexlist, - const int32_t* vertexindices, - int numindices, - const SbVec3f* normals, - const int32_t* normalindices, - SoMaterialBundle* materials, - const int32_t* matindices, - const int32_t binding, - const SoTextureCoordinateBundle* const texcoords, - const int32_t* texindices); + void drawCoords( + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int numindices, + const SbVec3f* normals, + const int32_t* normalindices, + SoMaterialBundle* materials, + const int32_t* matindices, + const int32_t binding, + const SoTextureCoordinateBundle* const texcoords, + const int32_t* texindices + ); void doAction(SoAction* action) override; diff --git a/src/Mod/Mesh/Gui/SoFCMeshObject.cpp b/src/Mod/Mesh/Gui/SoFCMeshObject.cpp index d8fe1f66b1..3f5e60e836 100644 --- a/src/Mod/Mesh/Gui/SoFCMeshObject.cpp +++ b/src/Mod/Mesh/Gui/SoFCMeshObject.cpp @@ -27,14 +27,14 @@ #include #include #ifdef FC_OS_WIN32 -#include +# include #endif #ifdef FC_OS_MACOSX -#include -#include +# include +# include #else -#include -#include +# include +# include #endif #include #include @@ -178,9 +178,11 @@ private: // Defines all required member variables and functions for a // single-value field -SO_SFIELD_SOURCE(SoSFMeshObject, - Base::Reference, - Base::Reference) +SO_SFIELD_SOURCE( + SoSFMeshObject, + Base::Reference, + Base::Reference +) void SoSFMeshObject::initClass() @@ -316,12 +318,11 @@ void SoFCMeshObjectElement::init(SoState* state) SoFCMeshObjectElement::~SoFCMeshObjectElement() = default; -void SoFCMeshObjectElement::set(SoState* const state, - SoNode* const node, - const Mesh::MeshObject* const mesh) +void SoFCMeshObjectElement::set(SoState* const state, SoNode* const node, const Mesh::MeshObject* const mesh) { SoFCMeshObjectElement* elem = static_cast( - SoReplacedElement::getElement(state, classStackIndex, node)); + SoReplacedElement::getElement(state, classStackIndex, node) + ); if (elem) { elem->mesh = mesh; elem->nodeId = node->getNodeId(); @@ -336,7 +337,8 @@ const Mesh::MeshObject* SoFCMeshObjectElement::get(SoState* const state) const SoFCMeshObjectElement* SoFCMeshObjectElement::getInstance(SoState* state) { return static_cast( - SoElement::getConstElement(state, classStackIndex)); + SoElement::getConstElement(state, classStackIndex) + ); } void SoFCMeshObjectElement::print(FILE* /* file */) const @@ -720,11 +722,13 @@ SoFCMeshObjectShape::Binding SoFCMeshObjectShape::findMaterialBinding(SoState* c * defines * FIXME: Implement using different values of transparency for each vertex or face */ -void SoFCMeshObjectShape::drawFaces(const Mesh::MeshObject* mesh, - SoMaterialBundle* mb, - Binding bind, - SbBool needNormals, - SbBool ccw) const +void SoFCMeshObjectShape::drawFaces( + const Mesh::MeshObject* mesh, + SoMaterialBundle* mb, + Binding bind, + SbBool needNormals, + SbBool ccw +) const { const MeshCore::MeshPointArray& rPoints = mesh->getKernel().GetPoints(); const MeshCore::MeshFacetArray& rFacets = mesh->getKernel().GetFacets(); @@ -799,9 +803,7 @@ void SoFCMeshObjectShape::drawFaces(const Mesh::MeshObject* mesh, /** * Renders the gravity points of a subset of triangles. */ -void SoFCMeshObjectShape::drawPoints(const Mesh::MeshObject* mesh, - SbBool needNormals, - SbBool ccw) const +void SoFCMeshObjectShape::drawPoints(const Mesh::MeshObject* mesh, SbBool needNormals, SbBool ccw) const { const MeshCore::MeshPointArray& rPoints = mesh->getKernel().GetPoints(); const MeshCore::MeshFacetArray& rFacets = mesh->getKernel().GetFacets(); @@ -1007,9 +1009,11 @@ void SoFCMeshObjectShape::startSelection(SoAction* action, const Mesh::MeshObjec glPushMatrix(); glLoadIdentity(); if (w > 0 && h > 0) { - glTranslatef((viewport[2] - 2 * (x - viewport[0])) / w, - (viewport[3] - 2 * (y - viewport[1])) / h, - 0); + glTranslatef( + (viewport[2] - 2 * (x - viewport[0])) / w, + (viewport[3] - 2 * (y - viewport[1])) / h, + 0 + ); glScalef(viewport[2] / w, viewport[3] / h, 1.0); } glMultMatrixf(/*mp*/ this->projection); @@ -1172,11 +1176,13 @@ void SoFCMeshObjectShape::generatePrimitives(SoAction* action) * Against the default OpenInventor implementation which returns 0 as well * Coin3d fills in the point and face indices. */ -SoDetail* SoFCMeshObjectShape::createTriangleDetail(SoRayPickAction* action, - const SoPrimitiveVertex* v1, - const SoPrimitiveVertex* v2, - const SoPrimitiveVertex* v3, - SoPickedPoint* pp) +SoDetail* SoFCMeshObjectShape::createTriangleDetail( + SoRayPickAction* action, + const SoPrimitiveVertex* v1, + const SoPrimitiveVertex* v2, + const SoPrimitiveVertex* v3, + SoPickedPoint* pp +) { SoDetail* detail = inherited::createTriangleDetail(action, v1, v2, v3, pp); return detail; @@ -1191,8 +1197,10 @@ void SoFCMeshObjectShape::computeBBox(SoAction* action, SbBox3f& box, SbVec3f& c const Mesh::MeshObject* mesh = SoFCMeshObjectElement::get(state); if (mesh && mesh->countPoints() > 0) { Base::BoundBox3f cBox = mesh->getKernel().GetBoundBox(); - box.setBounds(SbVec3f(cBox.MinX, cBox.MinY, cBox.MinZ), - SbVec3f(cBox.MaxX, cBox.MaxY, cBox.MaxZ)); + box.setBounds( + SbVec3f(cBox.MinX, cBox.MinY, cBox.MinZ), + SbVec3f(cBox.MaxX, cBox.MaxY, cBox.MaxZ) + ); Base::Vector3f mid = cBox.GetCenter(); center.setValue(mid.x, mid.y, mid.z); } @@ -1321,19 +1329,20 @@ SoFCMeshSegmentShape::Binding SoFCMeshSegmentShape::findMaterialBinding(SoState* * defines * FIXME: Implement using different values of transparency for each vertex or face */ -void SoFCMeshSegmentShape::drawFaces(const Mesh::MeshObject* mesh, - SoMaterialBundle* mb, - Binding bind, - SbBool needNormals, - SbBool ccw) const +void SoFCMeshSegmentShape::drawFaces( + const Mesh::MeshObject* mesh, + SoMaterialBundle* mb, + Binding bind, + SbBool needNormals, + SbBool ccw +) const { const MeshCore::MeshPointArray& rPoints = mesh->getKernel().GetPoints(); const MeshCore::MeshFacetArray& rFacets = mesh->getKernel().GetFacets(); if (mesh->countSegments() <= this->index.getValue()) { return; } - const std::vector rSegm = - mesh->getSegment(this->index.getValue()).getIndices(); + const std::vector rSegm = mesh->getSegment(this->index.getValue()).getIndices(); bool perVertex = (mb && bind == PER_VERTEX_INDEXED); bool perFace = (mb && bind == PER_FACE_INDEXED); @@ -1408,17 +1417,14 @@ void SoFCMeshSegmentShape::drawFaces(const Mesh::MeshObject* mesh, /** * Renders the gravity points of a subset of triangles. */ -void SoFCMeshSegmentShape::drawPoints(const Mesh::MeshObject* mesh, - SbBool needNormals, - SbBool ccw) const +void SoFCMeshSegmentShape::drawPoints(const Mesh::MeshObject* mesh, SbBool needNormals, SbBool ccw) const { const MeshCore::MeshPointArray& rPoints = mesh->getKernel().GetPoints(); const MeshCore::MeshFacetArray& rFacets = mesh->getKernel().GetFacets(); if (mesh->countSegments() <= this->index.getValue()) { return; } - const std::vector rSegm = - mesh->getSegment(this->index.getValue()).getIndices(); + const std::vector rSegm = mesh->getSegment(this->index.getValue()).getIndices(); int mod = rSegm.size() / renderTriangleLimit + 1; float size = std::min((float)mod, 3.0F); @@ -1521,8 +1527,7 @@ void SoFCMeshSegmentShape::generatePrimitives(SoAction* action) if (mesh->countSegments() <= this->index.getValue()) { return; } - const std::vector rSegm = - mesh->getSegment(this->index.getValue()).getIndices(); + const std::vector rSegm = mesh->getSegment(this->index.getValue()).getIndices(); // get material binding Binding mbind = this->findMaterialBinding(state); @@ -1614,8 +1619,10 @@ void SoFCMeshSegmentShape::computeBBox(SoAction* action, SbBox3f& box, SbVec3f& cBox.Add(rPoint[face._aulPoints[2]]); } - box.setBounds(SbVec3f(cBox.MinX, cBox.MinY, cBox.MinZ), - SbVec3f(cBox.MaxX, cBox.MaxY, cBox.MaxZ)); + box.setBounds( + SbVec3f(cBox.MinX, cBox.MinY, cBox.MinZ), + SbVec3f(cBox.MaxX, cBox.MaxY, cBox.MaxZ) + ); Base::Vector3f mid = cBox.GetCenter(); center.setValue(mid.x, mid.y, mid.z); } @@ -1762,8 +1769,10 @@ void SoFCMeshObjectBoundary::computeBBox(SoAction* action, SbBox3f& box, SbVec3f for (const auto& rPoint : rPoints) { cBox.Add(rPoint); } - box.setBounds(SbVec3f(cBox.MinX, cBox.MinY, cBox.MinZ), - SbVec3f(cBox.MaxX, cBox.MaxY, cBox.MaxZ)); + box.setBounds( + SbVec3f(cBox.MinX, cBox.MinY, cBox.MinZ), + SbVec3f(cBox.MaxX, cBox.MaxY, cBox.MaxZ) + ); Base::Vector3f mid = cBox.GetCenter(); center.setValue(mid.x, mid.y, mid.z); } diff --git a/src/Mod/Mesh/Gui/SoFCMeshObject.h b/src/Mod/Mesh/Gui/SoFCMeshObject.h index 47cb7b8e64..084349b0ae 100644 --- a/src/Mod/Mesh/Gui/SoFCMeshObject.h +++ b/src/Mod/Mesh/Gui/SoFCMeshObject.h @@ -51,9 +51,11 @@ class MeshGuiExport SoSFMeshObject: public SoSField { using inherited = SoSField; - SO_SFIELD_HEADER(SoSFMeshObject, - Base::Reference, - Base::Reference) + SO_SFIELD_HEADER( + SoSFMeshObject, + Base::Reference, + Base::Reference + ) public: static void initClass(); @@ -195,11 +197,13 @@ protected: void getPrimitiveCount(SoGetPrimitiveCountAction* action) override; void rayPick(SoRayPickAction* action) override; void generatePrimitives(SoAction* action) override; - SoDetail* createTriangleDetail(SoRayPickAction* action, - const SoPrimitiveVertex* v1, - const SoPrimitiveVertex* v2, - const SoPrimitiveVertex* v3, - SoPickedPoint* pp) override; + SoDetail* createTriangleDetail( + SoRayPickAction* action, + const SoPrimitiveVertex* v1, + const SoPrimitiveVertex* v2, + const SoPrimitiveVertex* v3, + SoPickedPoint* pp + ) override; // Force using the reference count mechanism. ~SoFCMeshObjectShape() override; @@ -216,11 +220,13 @@ private: void notify(SoNotList* node) override; Binding findMaterialBinding(SoState* const state) const; // Draw faces - void drawFaces(const Mesh::MeshObject*, - SoMaterialBundle* mb, - Binding bind, - SbBool needNormals, - SbBool ccw) const; + void drawFaces( + const Mesh::MeshObject*, + SoMaterialBundle* mb, + Binding bind, + SbBool needNormals, + SbBool ccw + ) const; void drawPoints(const Mesh::MeshObject*, SbBool needNormals, SbBool ccw) const; unsigned int countTriangles(SoAction* action) const; @@ -275,11 +281,13 @@ private: private: Binding findMaterialBinding(SoState* const state) const; // Draw faces - void drawFaces(const Mesh::MeshObject*, - SoMaterialBundle* mb, - Binding bind, - SbBool needNormals, - SbBool ccw) const; + void drawFaces( + const Mesh::MeshObject*, + SoMaterialBundle* mb, + Binding bind, + SbBool needNormals, + SbBool ccw + ) const; void drawPoints(const Mesh::MeshObject*, SbBool needNormals, SbBool ccw) const; }; diff --git a/src/Mod/Mesh/Gui/SoPolygon.cpp b/src/Mod/Mesh/Gui/SoPolygon.cpp index e95e3b6ca5..d0b253c42a 100644 --- a/src/Mod/Mesh/Gui/SoPolygon.cpp +++ b/src/Mod/Mesh/Gui/SoPolygon.cpp @@ -27,12 +27,12 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif #ifdef FC_OS_MACOSX -#include +# include #else -#include +# include #endif #include diff --git a/src/Mod/Mesh/Gui/SoPolygon.h b/src/Mod/Mesh/Gui/SoPolygon.h index 99cc20f80b..f6ddc2109a 100644 --- a/src/Mod/Mesh/Gui/SoPolygon.h +++ b/src/Mod/Mesh/Gui/SoPolygon.h @@ -30,7 +30,7 @@ #include #include #ifndef MESH_GLOBAL_H -#include +# include #endif diff --git a/src/Mod/Mesh/Gui/ThumbnailExtension.cpp b/src/Mod/Mesh/Gui/ThumbnailExtension.cpp index 75cb137171..be50b3145a 100644 --- a/src/Mod/Mesh/Gui/ThumbnailExtension.cpp +++ b/src/Mod/Mesh/Gui/ThumbnailExtension.cpp @@ -77,8 +77,8 @@ Mesh::Extension3MF::Resource ThumbnailExtension3MF::addMesh(const Mesh::MeshObje Mesh::Extension3MF::Resource res; res.extension = "png"; res.contentType = "image/png"; - res.relationshipType = - "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"; + res.relationshipType + = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail"; res.fileContent = std::string(data.data(), data.size()); setContentName(res); diff --git a/src/Mod/Mesh/Gui/ViewProvider.cpp b/src/Mod/Mesh/Gui/ViewProvider.cpp index 7f24b56b4b..0ab0781002 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.cpp +++ b/src/Mod/Mesh/Gui/ViewProvider.cpp @@ -104,8 +104,7 @@ using MeshCore::MeshKernel; using MeshCore::MeshPointIterator; // NOLINTBEGIN(readability-magic-numbers,cppcoreguidelines-pro-bounds*) -void ViewProviderMeshBuilder::buildNodes(const App::Property* prop, - std::vector& nodes) const +void ViewProviderMeshBuilder::buildNodes(const App::Property* prop, std::vector& nodes) const { SoCoordinate3* pcPointsCoord = nullptr; SoIndexedFaceSet* pcFaces = nullptr; @@ -130,18 +129,22 @@ void ViewProviderMeshBuilder::buildNodes(const App::Property* prop, } } -void ViewProviderMeshBuilder::createMesh(const App::Property* prop, - SoCoordinate3* coords, - SoIndexedFaceSet* faces) const +void ViewProviderMeshBuilder::createMesh( + const App::Property* prop, + SoCoordinate3* coords, + SoIndexedFaceSet* faces +) const { const auto mesh = dynamic_cast(prop); const MeshCore::MeshKernel& rcMesh = mesh->getValue().getKernel(); createMesh(rcMesh, coords, faces); } -void ViewProviderMeshBuilder::createMesh(const MeshCore::MeshKernel& kernel, - SoCoordinate3* coords, - SoIndexedFaceSet* faces) const +void ViewProviderMeshBuilder::createMesh( + const MeshCore::MeshKernel& kernel, + SoCoordinate3* coords, + SoIndexedFaceSet* faces +) const { // set the point coordinates @@ -264,8 +267,9 @@ ViewProviderMesh::ViewProviderMesh() LineColor.touch(); // read the correct shape color from the preferences - Base::Reference hGrp = - Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); + Base::Reference hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup( + "Mod/Mesh" + ); // Mesh color Base::Color color = ShapeAppearance.getDiffuseColor(); @@ -359,8 +363,8 @@ void ViewProviderMesh::onChanged(const App::Property* prop) tryColorPerVertexOrFace(Coloring.getValue()); } else if (prop == &SelectionStyle) { - pcHighlight->style = - SelectionStyle.getValue() ? Gui::SoFCSelection::BOX : Gui::SoFCSelection::EMISSIVE; + pcHighlight->style = SelectionStyle.getValue() ? Gui::SoFCSelection::BOX + : Gui::SoFCSelection::EMISSIVE; } else { // Set the inverse color for open edges @@ -686,9 +690,7 @@ std::vector ViewProviderMesh::getDisplayModes() const return StrList; } -bool ViewProviderMesh::exportToVrml(const char* filename, - const MeshCore::Material& mat, - bool binary) const +bool ViewProviderMesh::exportToVrml(const char* filename, const MeshCore::Material& mat, bool binary) const { auto coords = new SoCoordinate3(); auto faces = new SoIndexedFaceSet(); @@ -793,27 +795,25 @@ void ViewProviderMesh::setupContextMenu(QMenu* menu, QObject* receiver, const ch auto func = new Gui::ActionFunction(menu); QAction* act = menu->addAction(QObject::tr("Display Components")); act->setCheckable(true); - act->setChecked(pcMatBinding->value.getValue() == SoMaterialBinding::PER_FACE - && highlightMode == HighlighMode::Component); - func->toggle(act, [this](bool on) { - this->setHighlightedComponents(on); - }); + act->setChecked( + pcMatBinding->value.getValue() == SoMaterialBinding::PER_FACE + && highlightMode == HighlighMode::Component + ); + func->toggle(act, [this](bool on) { this->setHighlightedComponents(on); }); QAction* seg = menu->addAction(QObject::tr("Display Segments")); seg->setCheckable(true); - seg->setChecked(pcMatBinding->value.getValue() == SoMaterialBinding::PER_FACE - && highlightMode == HighlighMode::Segment); - func->toggle(seg, [this](bool on) { - this->setHighlightedSegments(on); - }); + seg->setChecked( + pcMatBinding->value.getValue() == SoMaterialBinding::PER_FACE + && highlightMode == HighlighMode::Segment + ); + func->toggle(seg, [this](bool on) { this->setHighlightedSegments(on); }); QAction* col = menu->addAction(QObject::tr("Display Colors")); col->setVisible(canHighlightColors()); col->setCheckable(true); col->setChecked(highlightMode == HighlighMode::Color); - func->toggle(col, [this](bool on) { - this->setHighlightedColors(on); - }); + func->toggle(col, [this](bool on) { this->setHighlightedColors(on); }); } bool ViewProviderMesh::setEdit(int ModNum) @@ -837,10 +837,12 @@ void ViewProviderMesh::unsetEdit(int ModNum) } } -bool ViewProviderMesh::createToolMesh(const std::vector& rclPoly, - const SbViewVolume& vol, - const Base::Vector3f& rcNormal, - std::vector& aFaces) +bool ViewProviderMesh::createToolMesh( + const std::vector& rclPoly, + const SbViewVolume& vol, + const Base::Vector3f& rcNormal, + std::vector& aFaces +) { float fX {}; float fY {}; @@ -942,9 +944,7 @@ namespace MeshGui class MeshSplit { public: - MeshSplit(ViewProviderMesh* mesh, - std::vector poly, - const Gui::ViewVolumeProjection& proj) + MeshSplit(ViewProviderMesh* mesh, std::vector poly, const Gui::ViewVolumeProjection& proj) : mesh(mesh) , poly(std::move(poly)) , proj(proj) @@ -1009,11 +1009,11 @@ void ViewProviderMesh::clipMeshCallback(void* ud, SoEventCallback* cb) clPoly.push_back(clPoly.front()); } - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); if (!views.empty()) { - Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Cut")); + Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Cut")); bool commitCommand = false; for (auto it : views) { auto self = static_cast(it); @@ -1022,8 +1022,7 @@ void ViewProviderMesh::clipMeshCallback(void* ud, SoEventCallback* cb) SoCamera* cam = view->getSoRenderManager()->getCamera(); SbViewVolume vv = cam->getViewVolume(); Gui::ViewVolumeProjection proj(vv); - proj.setTransform( - self->getObject()->Placement.getValue().toMatrix()); + proj.setTransform(self->getObject()->Placement.getValue().toMatrix()); if (role == Gui::SelectionRole::Inner) { self->cutMesh(clPoly, proj, true); commitCommand = true; @@ -1039,9 +1038,7 @@ void ViewProviderMesh::clipMeshCallback(void* ud, SoEventCallback* cb) auto func = new Gui::TimerFunction(); func->setAutoDelete(true); auto split = new MeshSplit(self, clPoly, proj); - func->setFunction([split]() { - split->cutMesh(); - }); + func->setFunction([split]() { split->cutMesh(); }); func->singleShot(0); } } @@ -1078,11 +1075,11 @@ void ViewProviderMesh::trimMeshCallback(void* ud, SoEventCallback* cb) clPoly.push_back(clPoly.front()); } - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); if (!views.empty()) { - Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Trim")); + Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Trim")); bool commitCommand = false; for (auto it : views) { auto self = static_cast(it); @@ -1091,8 +1088,7 @@ void ViewProviderMesh::trimMeshCallback(void* ud, SoEventCallback* cb) SoCamera* cam = view->getSoRenderManager()->getCamera(); SbViewVolume vv = cam->getViewVolume(); Gui::ViewVolumeProjection proj(vv); - proj.setTransform( - self->getObject()->Placement.getValue().toMatrix()); + proj.setTransform(self->getObject()->Placement.getValue().toMatrix()); if (role == Gui::SelectionRole::Inner) { self->trimMesh(clPoly, proj, true); commitCommand = true; @@ -1108,9 +1104,7 @@ void ViewProviderMesh::trimMeshCallback(void* ud, SoEventCallback* cb) auto func = new Gui::TimerFunction(); func->setAutoDelete(true); auto split = new MeshSplit(self, clPoly, proj); - func->setFunction([split]() { - split->trimMesh(); - }); + func->setFunction([split]() { split->trimMesh(); }); func->singleShot(0); } } @@ -1158,8 +1152,10 @@ void ViewProviderMesh::partMeshCallback(void* ud, SoEventCallback* cb) // create a tool shape from these points std::vector aFaces; if (!ViewProviderMesh::createToolMesh(clPoly, vol, cNormal, aFaces)) { - Base::Console().message("The picked polygon seems to have self-overlappings. This could " - "lead to strange results."); + Base::Console().message( + "The picked polygon seems to have self-overlappings. This could " + "lead to strange results." + ); } MeshCore::MeshKernel toolMesh; @@ -1168,12 +1164,12 @@ void ViewProviderMesh::partMeshCallback(void* ud, SoEventCallback* cb) Base::Sequencer().setLocked(locked); // Open a transaction object for the undo/redo stuff - Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Split")); + Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Split")); try { - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); for (auto view : views) { auto that = static_cast(view); if (that->getEditingMode() > -1) { @@ -1231,8 +1227,10 @@ void ViewProviderMesh::segmMeshCallback(void* ud, SoEventCallback* cb) // create a tool shape from these points std::vector aFaces; if (!ViewProviderMesh::createToolMesh(clPoly, vol, cNormal, aFaces)) { - Base::Console().message("The picked polygon seems to have self-overlappings. This could " - "lead to strange results."); + Base::Console().message( + "The picked polygon seems to have self-overlappings. This could " + "lead to strange results." + ); } MeshCore::MeshKernel toolMesh; @@ -1241,12 +1239,12 @@ void ViewProviderMesh::segmMeshCallback(void* ud, SoEventCallback* cb) Base::Sequencer().setLocked(locked); // Open a transaction object for the undo/redo stuff - Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Segment")); + Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Segment")); try { - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); for (auto view : views) { auto that = static_cast(view); if (that->getEditingMode() > -1) { @@ -1325,22 +1323,26 @@ void ViewProviderMesh::selectGLCallback(void* ud, SoEventCallback* cb) auto that = static_cast(it); if (that->getEditingMode() > -1) { that->finishEditing(); - that->selectArea(x, - y, - w, - h, - view->getSoRenderManager()->getViewportRegion(), - view->getSoRenderManager()->getCamera()); + that->selectArea( + x, + y, + w, + h, + view->getSoRenderManager()->getViewportRegion(), + view->getSoRenderManager()->getCamera() + ); } } view->redraw(); } -void ViewProviderMesh::getFacetsFromPolygon(const std::vector& picked, - const Base::ViewProjMethod& proj, - SbBool inner, - std::vector& indices) const +void ViewProviderMesh::getFacetsFromPolygon( + const std::vector& picked, + const Base::ViewProjMethod& proj, + SbBool inner, + std::vector& indices +) const { const bool ok = true; Base::Polygon2d polygon; @@ -1365,14 +1367,18 @@ void ViewProviderMesh::getFacetsFromPolygon(const std::vector& picked, } if (!ok) { // note: the mouse grabbing needs to be released - Base::Console().message("The picked polygon seems to have self-overlappings. This could " - "lead to strange results."); + Base::Console().message( + "The picked polygon seems to have self-overlappings. This could " + "lead to strange results." + ); } } -std::vector ViewProviderMesh::getFacetsOfRegion(const SbViewportRegion& select, - const SbViewportRegion& region, - SoCamera* camera) const +std::vector ViewProviderMesh::getFacetsOfRegion( + const SbViewportRegion& select, + const SbViewportRegion& region, + SoCamera* camera +) const { auto root = new SoSeparator(); root->ref(); @@ -1388,11 +1394,13 @@ std::vector ViewProviderMesh::getFacetsOfRegion(const SbViewpo return faces; } -void ViewProviderMesh::panCamera(SoCamera* cam, - float aspectratio, - const SbPlane& panplane, - const SbVec2f& currpos, - const SbVec2f& prevpos) +void ViewProviderMesh::panCamera( + SoCamera* cam, + float aspectratio, + const SbPlane& panplane, + const SbVec2f& currpos, + const SbVec2f& prevpos +) { if (!cam) { // can happen for empty scenegraph return; @@ -1461,10 +1469,11 @@ void ViewProviderMesh::boxZoom(const SbBox2s& box, const SbViewportRegion& vp, S } } -std::vector -ViewProviderMesh::getVisibleFacetsAfterZoom(const SbBox2s& rect, - const SbViewportRegion& vp, - SoCamera* camera) const +std::vector ViewProviderMesh::getVisibleFacetsAfterZoom( + const SbBox2s& rect, + const SbViewportRegion& vp, + SoCamera* camera +) const { // camera copy will be deleted inside getVisibleFacets() // because the ref counter reaches 0 @@ -1488,9 +1497,11 @@ namespace MeshGui class Vertex { public: - Vertex(const MeshCore::MeshKernel& kernel, - const MeshCore::MeshFacetGrid& grid, - const Base::Vector3f& pos) + Vertex( + const MeshCore::MeshKernel& kernel, + const MeshCore::MeshFacetGrid& grid, + const Base::Vector3f& pos + ) : kernel(kernel) , grid(grid) , pos(pos) @@ -1510,8 +1521,10 @@ private: } // namespace MeshGui -std::vector ViewProviderMesh::getVisibleFacets(const SbViewportRegion& vp, - SoCamera* camera) const +std::vector ViewProviderMesh::getVisibleFacets( + const SbViewportRegion& vp, + SoCamera* camera +) const { const Mesh::MeshObject& mesh = getMeshObject(); uint32_t count = (uint32_t)mesh.countFacets(); @@ -1572,9 +1585,11 @@ std::vector ViewProviderMesh::getVisibleFacets(const SbViewpor return faces; } -void ViewProviderMesh::cutMesh(const std::vector& polygon, - const Base::ViewProjMethod& proj, - SbBool inner) +void ViewProviderMesh::cutMesh( + const std::vector& polygon, + const Base::ViewProjMethod& proj, + SbBool inner +) { // Get the facet indices inside the tool mesh std::vector indices; @@ -1582,9 +1597,11 @@ void ViewProviderMesh::cutMesh(const std::vector& polygon, removeFacets(indices); } -void ViewProviderMesh::trimMesh(const std::vector& polygon, - const Base::ViewProjMethod& proj, - SbBool inner) +void ViewProviderMesh::trimMesh( + const std::vector& polygon, + const Base::ViewProjMethod& proj, + SbBool inner +) { Mesh::PropertyMeshKernel& prop = getMeshProperty(); Mesh::MeshObject* mesh = prop.startEditing(); @@ -1600,9 +1617,11 @@ void ViewProviderMesh::trimMesh(const std::vector& polygon, getObject()->purgeTouched(); } -void ViewProviderMesh::splitMesh(const MeshCore::MeshKernel& toolMesh, - const Base::Vector3f& normal, - SbBool clip_inner) +void ViewProviderMesh::splitMesh( + const MeshCore::MeshKernel& toolMesh, + const Base::Vector3f& normal, + SbBool clip_inner +) { // Get the attached mesh property Mesh::PropertyMeshKernel& meshProp = getMeshProperty(); @@ -1635,9 +1654,11 @@ void ViewProviderMesh::splitMesh(const MeshCore::MeshKernel& toolMesh, getObject()->purgeTouched(); } -void ViewProviderMesh::segmentMesh(const MeshCore::MeshKernel& toolMesh, - const Base::Vector3f& normal, - SbBool clip_inner) +void ViewProviderMesh::segmentMesh( + const MeshCore::MeshKernel& toolMesh, + const Base::Vector3f& normal, + SbBool clip_inner +) { // Get the attached mesh property Mesh::PropertyMeshKernel& meshProp = getMeshProperty(); @@ -1683,8 +1704,9 @@ void ViewProviderMesh::faceInfoCallback(void* ud, SoEventCallback* cb) view->setEditing(false); view->getWidget()->setCursor(QCursor(Qt::ArrowCursor)); view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), faceInfoCallback, ud); - std::list glItems = - view->getGraphicsItemsOfType(Gui::GLFlagWindow::getClassTypeId()); + std::list glItems = view->getGraphicsItemsOfType( + Gui::GLFlagWindow::getClassTypeId() + ); for (auto glItem : glItems) { view->removeGraphicsItem(glItem); delete glItem; @@ -1692,7 +1714,8 @@ void ViewProviderMesh::faceInfoCallback(void* ud, SoEventCallback* cb) // See comment below ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); hGrp->SetBool("ShowNaviCube", hGrp->GetBool("ShowNaviCube", true)); } } @@ -1727,8 +1750,9 @@ void ViewProviderMesh::faceInfoCallback(void* ud, SoEventCallback* cb) Mesh::FacetIndex uFacet = faceDetail->getFaceIndex(); that->faceInfo(uFacet); Gui::GLFlagWindow* flags = nullptr; - std::list glItems = - view->getGraphicsItemsOfType(Gui::GLFlagWindow::getClassTypeId()); + std::list glItems = view->getGraphicsItemsOfType( + Gui::GLFlagWindow::getClassTypeId() + ); if (glItems.empty()) { flags = new Gui::GLFlagWindow(view); view->addGraphicsItem(flags); @@ -1737,16 +1761,18 @@ void ViewProviderMesh::faceInfoCallback(void* ud, SoEventCallback* cb) flags = static_cast(glItems.front()); } - int point1 = - static_cast(faceDetail->getPoint(0))->getCoordinateIndex(); - int point2 = - static_cast(faceDetail->getPoint(1))->getCoordinateIndex(); - int point3 = - static_cast(faceDetail->getPoint(2))->getCoordinateIndex(); + int point1 + = static_cast(faceDetail->getPoint(0))->getCoordinateIndex(); + int point2 + = static_cast(faceDetail->getPoint(1))->getCoordinateIndex(); + int point3 + = static_cast(faceDetail->getPoint(2))->getCoordinateIndex(); auto flag = new Gui::Flag; flag->setText(QObject::tr("Index: %1").arg(uFacet)); - QString toolTip = QStringLiteral("Facet index: %1\n" - "Points: <%2, %3, %4>") + QString toolTip = QStringLiteral( + "Facet index: %1\n" + "Points: <%2, %3, %4>" + ) .arg(uFacet) .arg(point1) .arg(point2) @@ -1813,8 +1839,7 @@ void ViewProviderMesh::markPartCallback(void* ud, SoEventCallback* cb) // Mark all incoming mouse button events as handled, especially, to deactivate the selection // node cb->getAction()->setHandled(); - if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 - && mbe->getState() == SoButtonEvent::UP) { + if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::UP) { cb->setHandled(); // context-menu QMenu menu; @@ -1825,28 +1850,30 @@ void ViewProviderMesh::markPartCallback(void* ud, SoEventCallback* cb) if (cl == id) { view->setEditing(false); view->setSelectionEnabled(true); - view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - markPartCallback, - ud); + view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), markPartCallback, ud); - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); for (auto view : views) { static_cast(view)->clearSelection(); } } else if (cf == id) { - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); for (auto view : views) { static_cast(view)->clearSelection(); } } else if (rm == id) { Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Delete")); - std::vector views = - view->getViewProvidersOfType(ViewProviderMesh::getClassTypeId()); + QT_TRANSLATE_NOOP("Command", "Delete") + ); + std::vector views = view->getViewProvidersOfType( + ViewProviderMesh::getClassTypeId() + ); for (auto view : views) { static_cast(view)->deleteSelection(); } @@ -1871,8 +1898,7 @@ void ViewProviderMesh::markPartCallback(void* ud, SoEventCallback* cb) const SoDetail* detail = point->getDetail(that->getShapeNode()); if (detail && detail->getTypeId() == SoFaceDetail::getClassTypeId()) { // get the boundary to the picked facet - Mesh::FacetIndex uFacet = - static_cast(detail)->getFaceIndex(); + Mesh::FacetIndex uFacet = static_cast(detail)->getFaceIndex(); that->selectComponent(uFacet); } } @@ -1906,15 +1932,17 @@ void ViewProviderMesh::faceInfo(Mesh::FacetIndex uFacet) tria._aclPoints[1].z, tria._aclPoints[2].x, tria._aclPoints[2].y, - tria._aclPoints[2].z); + tria._aclPoints[2].z + ); } } void ViewProviderMesh::fillHole(Mesh::FacetIndex uFacet) { // get parameter from user settings - Base::Reference hGrp = - Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); + Base::Reference hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup( + "Mod/Mesh" + ); int level = (int)hGrp->GetInt("FillHoleLevel", 2); // get the boundary to the picked facet @@ -1970,7 +1998,8 @@ void ViewProviderMesh::fillHole(Mesh::FacetIndex uFacet) // add the facets to the mesh and open a transaction object for the undo/redo stuff Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Fill hole")); + QT_TRANSLATE_NOOP("Command", "Fill hole") + ); auto& prop = getMeshProperty(); Mesh::MeshObject* kernel = prop.startEditing(); kernel->addFacets(newFacets, newPoints, true); @@ -2207,10 +2236,10 @@ void ViewProviderMesh::invertSelection() const Mesh::MeshObject& rMesh = getMeshObject(); const MeshCore::MeshFacetArray& faces = rMesh.getKernel().GetFacets(); MeshCore::MeshIsNotFlag flag; - unsigned long num_notsel = - std::count_if(faces.begin(), faces.end(), [flag](const MeshCore::MeshFacet& f) { - return flag(f, MeshCore::MeshFacet::SELECTED); - }); + unsigned long num_notsel + = std::count_if(faces.begin(), faces.end(), [flag](const MeshCore::MeshFacet& f) { + return flag(f, MeshCore::MeshFacet::SELECTED); + }); std::vector notselect; notselect.reserve(num_notsel); auto beg = faces.begin(); @@ -2248,12 +2277,14 @@ bool ViewProviderMesh::hasSelection() const return rMesh.hasSelectedFacets(); } -void ViewProviderMesh::selectArea(short x, - short y, - short w, - short h, - const SbViewportRegion& region, - SoCamera* camera) +void ViewProviderMesh::selectArea( + short x, + short y, + short w, + short h, + const SbViewportRegion& region, + SoCamera* camera +) { SbViewportRegion vp; vp.setViewportPixels(x, y, w, h); @@ -2419,15 +2450,13 @@ void ViewProviderMesh::highlightColors() { const Mesh::MeshObject& rMesh = getMeshObject(); { - auto prop = - freecad_cast(pcObject->getPropertyByName("FaceColors")); + auto prop = freecad_cast(pcObject->getPropertyByName("FaceColors")); if (prop && prop->getSize() == int(rMesh.countFacets())) { setColorPerFace(prop); } } { - auto prop = - freecad_cast(pcObject->getPropertyByName("VertexColors")); + auto prop = freecad_cast(pcObject->getPropertyByName("VertexColors")); if (prop && prop->getSize() == int(rMesh.countPoints())) { setColorPerVertex(prop); } @@ -2438,15 +2467,13 @@ bool ViewProviderMesh::canHighlightColors() const { const Mesh::MeshObject& rMesh = getMeshObject(); { - auto prop = - freecad_cast(pcObject->getPropertyByName("FaceColors")); + auto prop = freecad_cast(pcObject->getPropertyByName("FaceColors")); if (prop && prop->getSize() == int(rMesh.countFacets())) { return true; } } { - auto prop = - freecad_cast(pcObject->getPropertyByName("VertexColors")); + auto prop = freecad_cast(pcObject->getPropertyByName("VertexColors")); if (prop && prop->getSize() == int(rMesh.countPoints())) { return true; } @@ -2493,12 +2520,13 @@ void ViewProviderIndexedFaceSet::attach(App::DocumentObject* obj) pcHighlight->addChild(pcMeshFaces); // read the threshold from the preferences - Base::Reference hGrp = - Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); + Base::Reference hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup( + "Mod/Mesh" + ); long size = hGrp->GetInt("RenderTriangleLimit", -1); if (size > 0) { - static_cast(pcMeshFaces)->renderTriangleLimit = - (unsigned int)(pow(10.0F, size)); + static_cast(pcMeshFaces)->renderTriangleLimit + = (unsigned int)(pow(10.0F, size)); } } @@ -2584,8 +2612,9 @@ void ViewProviderMeshObject::attach(App::DocumentObject* obj) pcHighlight->addChild(pcMeshShape); // read the threshold from the preferences - Base::Reference hGrp = - Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); + Base::Reference hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup( + "Mod/Mesh" + ); long size = hGrp->GetInt("RenderTriangleLimit", -1); if (size > 0) { pcMeshShape->renderTriangleLimit = (unsigned int)(pow(10.0F, size)); @@ -2596,8 +2625,7 @@ void ViewProviderMeshObject::updateData(const App::Property* prop) { ViewProviderMesh::updateData(prop); if (const auto mesh = dynamic_cast(prop)) { - this->pcMeshNode->mesh.setValue( - Base::Reference(mesh->getValuePtr())); + this->pcMeshNode->mesh.setValue(Base::Reference(mesh->getValuePtr())); // Needs to update internal bounding box caches this->pcMeshShape->touch(); } diff --git a/src/Mod/Mesh/Gui/ViewProvider.h b/src/Mod/Mesh/Gui/ViewProvider.h index 99e7a951ff..e35110042d 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.h +++ b/src/Mod/Mesh/Gui/ViewProvider.h @@ -183,19 +183,33 @@ public: void clearSelection(); void deleteSelection(); bool hasSelection() const; - void getFacetsFromPolygon(const std::vector& picked, - const Base::ViewProjMethod& proj, - SbBool inner, - std::vector& indices) const; - std::vector - getFacetsOfRegion(const SbViewportRegion&, const SbViewportRegion&, SoCamera*) const; - std::vector - getVisibleFacetsAfterZoom(const SbBox2s&, const SbViewportRegion&, SoCamera*) const; + void getFacetsFromPolygon( + const std::vector& picked, + const Base::ViewProjMethod& proj, + SbBool inner, + std::vector& indices + ) const; + std::vector getFacetsOfRegion( + const SbViewportRegion&, + const SbViewportRegion&, + SoCamera* + ) const; + std::vector getVisibleFacetsAfterZoom( + const SbBox2s&, + const SbViewportRegion&, + SoCamera* + ) const; std::vector getVisibleFacets(const SbViewportRegion&, SoCamera*) const; - virtual void - cutMesh(const std::vector& polygon, const Base::ViewProjMethod& proj, SbBool inner); - virtual void - trimMesh(const std::vector& polygon, const Base::ViewProjMethod& proj, SbBool inner); + virtual void cutMesh( + const std::vector& polygon, + const Base::ViewProjMethod& proj, + SbBool inner + ); + virtual void trimMesh( + const std::vector& polygon, + const Base::ViewProjMethod& proj, + SbBool inner + ); virtual void appendFacets(const std::vector&); virtual void removeFacets(const std::vector&); /*! The size of the array must be equal to the number of facets. */ @@ -218,10 +232,16 @@ protected: void onChanged(const App::Property* prop) override; virtual void showOpenEdges(bool); void setOpenEdgeColorFrom(const Base::Color& col); - virtual void - splitMesh(const MeshCore::MeshKernel& toolMesh, const Base::Vector3f& normal, SbBool inner); - virtual void - segmentMesh(const MeshCore::MeshKernel& toolMesh, const Base::Vector3f& normal, SbBool inner); + virtual void splitMesh( + const MeshCore::MeshKernel& toolMesh, + const Base::Vector3f& normal, + SbBool inner + ); + virtual void segmentMesh( + const MeshCore::MeshKernel& toolMesh, + const Base::Vector3f& normal, + SbBool inner + ); virtual void faceInfo(Mesh::FacetIndex facet); virtual void fillHole(Mesh::FacetIndex facet); virtual void selectArea(short, short, short, short, const SbViewportRegion&, SoCamera*); @@ -262,10 +282,12 @@ public: static void segmMeshCallback(void* ud, SoEventCallback* cb); static void selectGLCallback(void* ud, SoEventCallback* cb); /// Creates a tool mesh from the previous picked polygon on the viewer - static bool createToolMesh(const std::vector& rclPoly, - const SbViewVolume& vol, - const Base::Vector3f& rcNormal, - std::vector&); + static bool createToolMesh( + const std::vector& rclPoly, + const SbViewVolume& vol, + const Base::Vector3f& rcNormal, + std::vector& + ); private: static void renderGLCallback(void* ud, SoAction* a); diff --git a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp index 91bcc81d70..814ccde844 100644 --- a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp @@ -135,12 +135,14 @@ ViewProviderMeshCurvature::~ViewProviderMeshCurvature() Base::Console().destructorError( "ViewProviderMeshCurvature", "ViewProviderMeshCurvature::deleteColorBar() threw an exception: %s\n", - e.what()); + e.what() + ); } catch (...) { Base::Console().destructorError( "ViewProviderInspection", - "ViewProviderInspection destructor threw an unknown exception"); + "ViewProviderInspection destructor threw an unknown exception" + ); } } @@ -148,15 +150,11 @@ void ViewProviderMeshCurvature::onChanged(const App::Property* prop) { if (prop == &TextureMaterial) { const App::Material& Mat = TextureMaterial.getValue(); - pcColorMat->ambientColor.setValue(Mat.ambientColor.r, - Mat.ambientColor.g, - Mat.ambientColor.b); - pcColorMat->specularColor.setValue(Mat.specularColor.r, - Mat.specularColor.g, - Mat.specularColor.b); - pcColorMat->emissiveColor.setValue(Mat.emissiveColor.r, - Mat.emissiveColor.g, - Mat.emissiveColor.b); + pcColorMat->ambientColor.setValue(Mat.ambientColor.r, Mat.ambientColor.g, Mat.ambientColor.b); + pcColorMat->specularColor + .setValue(Mat.specularColor.r, Mat.specularColor.g, Mat.specularColor.b); + pcColorMat->emissiveColor + .setValue(Mat.emissiveColor.r, Mat.emissiveColor.g, Mat.emissiveColor.b); pcColorMat->shininess.setValue(Mat.shininess); pcColorMat->transparency.setValue(Mat.transparency); } @@ -239,8 +237,10 @@ void ViewProviderMeshCurvature::init(const Mesh::PropertyCurvatureList* prop) pcColorBar->setRange(fMin, fMax, 3); } -void ViewProviderMeshCurvature::slotChangedObject(const App::DocumentObject& Obj, - const App::Property& Prop) +void ViewProviderMeshCurvature::slotChangedObject( + const App::DocumentObject& Obj, + const App::Property& Prop +) { // we get this for any object for that a property has changed. Thus, we must regard that object // which is linked by our link property @@ -460,10 +460,7 @@ namespace MeshGui class Annotation { public: - Annotation(Gui::ViewProviderDocumentObject* vp, - const QString& s, - const SbVec3f& p, - const SbVec3f& n) + Annotation(Gui::ViewProviderDocumentObject* vp, const QString& s, const SbVec3f& p, const SbVec3f& n) : vp(vp) , s(s) , p(p) @@ -528,8 +525,7 @@ void ViewProviderMeshCurvature::curvatureInfoCallback(void* ud, SoEventCallback* // Mark all incoming mouse button events as handled, especially, to deactivate the // selection node n->getAction()->setHandled(); - if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 - && mbe->getState() == SoButtonEvent::UP) { + if (mbe->getButton() == SoMouseButtonEvent::BUTTON2 && mbe->getState() == SoButtonEvent::UP) { n->setHandled(); // context-menu QMenu menu; @@ -611,8 +607,7 @@ void ViewProviderMeshCurvature::curvatureInfoCallback(void* ud, SoEventCallback* } } -std::string -ViewProviderMeshCurvature::curvatureInfo(bool detail, int index1, int index2, int index3) const +std::string ViewProviderMeshCurvature::curvatureInfo(bool detail, int index1, int index2, int index3) const { // get the curvature info of the three points of the picked facet App::Property* prop = pcObject->getPropertyByName("CurvInfo"); diff --git a/src/Mod/Mesh/Gui/ViewProviderDefects.cpp b/src/Mod/Mesh/Gui/ViewProviderDefects.cpp index 95cd0cb7f9..0133b5e454 100644 --- a/src/Mod/Mesh/Gui/ViewProviderDefects.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderDefects.cpp @@ -100,7 +100,8 @@ SoMarkerSet* ViewProviderMeshDefects::makeMarkerSet() const "PLUS", int(App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetInt("MarkerSize", 7))); + ->GetInt("MarkerSize", 7)) + ); return marker; } @@ -521,14 +522,18 @@ void ViewProviderMeshDegenerations::showDefects(const std::vectorpoint.set1Value(i++, - cF->_aclPoints[(j + 1) % 3].x, - cF->_aclPoints[(j + 1) % 3].y, - cF->_aclPoints[(j + 1) % 3].z); - pcCoords->point.set1Value(i++, - cF->_aclPoints[(j + 2) % 3].x, - cF->_aclPoints[(j + 2) % 3].y, - cF->_aclPoints[(j + 2) % 3].z); + pcCoords->point.set1Value( + i++, + cF->_aclPoints[(j + 1) % 3].x, + cF->_aclPoints[(j + 1) % 3].y, + cF->_aclPoints[(j + 1) % 3].z + ); + pcCoords->point.set1Value( + i++, + cF->_aclPoints[(j + 2) % 3].x, + cF->_aclPoints[(j + 2) % 3].y, + cF->_aclPoints[(j + 2) % 3].z + ); break; } } diff --git a/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.cpp b/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.cpp index ee01cc2ecb..ace6df44ec 100644 --- a/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.cpp @@ -86,8 +86,9 @@ void ViewProviderMeshFaceSet::attach(App::DocumentObject* obj) pcShapeGroup->addChild(pcMeshFaces); // read the threshold from the preferences - Base::Reference hGrp = - Gui::WindowParameter::getDefaultParameter()->GetGroup("Mod/Mesh"); + Base::Reference hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup( + "Mod/Mesh" + ); long size = hGrp->GetInt("RenderTriangleLimit", -1); if (size > 0) { unsigned int limit = (unsigned int)(pow(10.0F, size)); // NOLINT diff --git a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp index f8958bf36e..a88fcba32e 100644 --- a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp @@ -153,14 +153,15 @@ void ViewProviderMeshTransformDemolding::calcMaterialIndex(const SbRotation& rot } } -void ViewProviderMeshTransformDemolding::sValueChangedCallback(void* This, - [[maybe_unused]] SoDragger* dragger) +void ViewProviderMeshTransformDemolding::sValueChangedCallback( + void* This, + [[maybe_unused]] SoDragger* dragger +) { static_cast(This)->valueChangedCallback(); } -void ViewProviderMeshTransformDemolding::sDragEndCallback(void* This, - [[maybe_unused]] SoDragger* dragger) +void ViewProviderMeshTransformDemolding::sDragEndCallback(void* This, [[maybe_unused]] SoDragger* dragger) { static_cast(This)->DragEndCallback(); } @@ -178,11 +179,13 @@ void ViewProviderMeshTransformDemolding::valueChangedCallback() SbMatrix temp; SbRotation rot = pcTrackballDragger->rotation.getValue(); - temp.setTransform(SbVec3f(0, 0, 0), // no transformation - rot, // rotation from the dragger - SbVec3f(1, 1, 1), // no scaling - SbRotation(), // no scaling orientation - SbVec3f(center.x, center.y, center.z)); // center of rotation + temp.setTransform( + SbVec3f(0, 0, 0), // no transformation + rot, // rotation from the dragger + SbVec3f(1, 1, 1), // no scaling + SbRotation(), // no scaling orientation + SbVec3f(center.x, center.y, center.z) + ); // center of rotation pcTransformDrag->setMatrix(temp); } diff --git a/src/Mod/Mesh/Gui/Workbench.h b/src/Mod/Mesh/Gui/Workbench.h index 6a55e2e9df..b1019ca63d 100644 --- a/src/Mod/Mesh/Gui/Workbench.h +++ b/src/Mod/Mesh/Gui/Workbench.h @@ -27,7 +27,7 @@ #include #ifndef MESH_GLOBAL_H -#include +# include #endif diff --git a/src/Mod/Mesh/MeshGlobal.h b/src/Mod/Mesh/MeshGlobal.h index ba789e1cf9..76c72ed6ac 100644 --- a/src/Mod/Mesh/MeshGlobal.h +++ b/src/Mod/Mesh/MeshGlobal.h @@ -25,25 +25,25 @@ #include #ifndef MESH_GLOBAL_H -#define MESH_GLOBAL_H +# define MESH_GLOBAL_H // Mesh -#ifndef MeshExport -#ifdef Mesh_EXPORTS -#define MeshExport FREECAD_DECL_EXPORT -#else -#define MeshExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef MeshExport +# ifdef Mesh_EXPORTS +# define MeshExport FREECAD_DECL_EXPORT +# else +# define MeshExport FREECAD_DECL_IMPORT +# endif +# endif // MeshGui -#ifndef MeshGuiExport -#ifdef MeshGui_EXPORTS -#define MeshGuiExport FREECAD_DECL_EXPORT -#else -#define MeshGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef MeshGuiExport +# ifdef MeshGui_EXPORTS +# define MeshGuiExport FREECAD_DECL_EXPORT +# else +# define MeshGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // MESH_GLOBAL_H diff --git a/src/Mod/MeshPart/App/CurveProjector.cpp b/src/Mod/MeshPart/App/CurveProjector.cpp index ef86dc1e31..005e07e381 100644 --- a/src/Mod/MeshPart/App/CurveProjector.cpp +++ b/src/Mod/MeshPart/App/CurveProjector.cpp @@ -27,7 +27,7 @@ #include #ifdef FC_OS_LINUX -#include +# include #endif #include #include @@ -111,8 +111,7 @@ void CurveProjectorShape::Do() } -void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, - std::vector& vSplitEdges) +void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, std::vector& vSplitEdges) { Standard_Real fFirst, fLast; Handle(Geom_Curve) hCurve = BRep_Tool::Curve(aEdge, fFirst, fLast); @@ -124,8 +123,8 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, Base::Vector3f cStartPoint = Base::Vector3f((float)gpPt.X(), (float)gpPt.Y(), (float)gpPt.Z()); Base::Vector3f cResultPoint, cSplitPoint, cPlanePnt, cPlaneNormal; MeshCore::FacetIndex uStartFacetIdx, uCurFacetIdx; - MeshCore::FacetIndex uLastFacetIdx = - MeshCore::FACET_INDEX_MAX - 1; // use another value as FACET_INDEX_MAX + MeshCore::FacetIndex uLastFacetIdx = MeshCore::FACET_INDEX_MAX + - 1; // use another value as FACET_INDEX_MAX MeshCore::FacetIndex auNeighboursIdx[3]; bool GoOn; @@ -136,10 +135,12 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, uCurFacetIdx = uStartFacetIdx; do { MeshGeomFacet cCurFacet = _Mesh.GetFacet(uCurFacetIdx); - _Mesh.GetFacetNeighbours(uCurFacetIdx, - auNeighboursIdx[0], - auNeighboursIdx[1], - auNeighboursIdx[2]); + _Mesh.GetFacetNeighbours( + uCurFacetIdx, + auNeighboursIdx[0], + auNeighboursIdx[1], + auNeighboursIdx[2] + ); Base::Vector3f PointOnEdge[3]; GoOn = false; @@ -168,9 +169,10 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, cPlanePnt = cP0; } - Handle(Geom_Plane) hPlane = - new Geom_Plane(gp_Pln(gp_Pnt(cPlanePnt.x, cPlanePnt.y, cPlanePnt.z), - gp_Dir(cPlaneNormal.x, cPlaneNormal.y, cPlaneNormal.z))); + Handle(Geom_Plane) hPlane = new Geom_Plane(gp_Pln( + gp_Pnt(cPlanePnt.x, cPlanePnt.y, cPlanePnt.z), + gp_Dir(cPlaneNormal.x, cPlaneNormal.y, cPlaneNormal.z) + )); GeomAPI_IntCS Alg(hCurve, hPlane); @@ -199,10 +201,12 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, } else if (Alg.NbPoints() > 1) { PointOnEdge[i] = Base::Vector3f(std::numeric_limits::max(), 0, 0); - Base::Console().log("MeshAlgos::projectCurve(): More then one intersection in " - "Facet %lu, Edge %d\n", - uCurFacetIdx, - i); + Base::Console().log( + "MeshAlgos::projectCurve(): More then one intersection in " + "Facet %lu, Edge %d\n", + uCurFacetIdx, + i + ); } } } @@ -220,8 +224,10 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, GoOn = true; } else { - Base::Console().log("MeshAlgos::projectCurve(): Possible reentry in Facet %lu\n", - uCurFacetIdx); + Base::Console().log( + "MeshAlgos::projectCurve(): Possible reentry in Facet %lu\n", + uCurFacetIdx + ); } if (uCurFacetIdx == uStartFacetIdx) { @@ -231,10 +237,12 @@ void CurveProjectorShape::projectCurve(const TopoDS_Edge& aEdge, } while (GoOn); } -bool CurveProjectorShape::findStartPoint(const MeshKernel& MeshK, - const Base::Vector3f& Pnt, - Base::Vector3f& Rslt, - MeshCore::FacetIndex& FaceIndex) +bool CurveProjectorShape::findStartPoint( + const MeshKernel& MeshK, + const Base::Vector3f& Pnt, + Base::Vector3f& Rslt, + MeshCore::FacetIndex& FaceIndex +) { Base::Vector3f TempResultPoint; float MinLength = std::numeric_limits::max(); @@ -285,9 +293,11 @@ void CurveProjectorSimple::Do() } } -void CurveProjectorSimple::GetSampledCurves(const TopoDS_Edge& aEdge, - std::vector& rclPoints, - unsigned long ulNbOfPoints) +void CurveProjectorSimple::GetSampledCurves( + const TopoDS_Edge& aEdge, + std::vector& rclPoints, + unsigned long ulNbOfPoints +) { rclPoints.clear(); @@ -305,9 +315,11 @@ void CurveProjectorSimple::GetSampledCurves(const TopoDS_Edge& aEdge, // projectToNeighbours(Handle(Geom_Curve) hCurve,float pos -void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, - const std::vector&, - std::vector&) +void CurveProjectorSimple::projectCurve( + const TopoDS_Edge& aEdge, + const std::vector&, + std::vector& +) { Base::Vector3f TempResultPoint; bool bFirst = true; @@ -338,7 +350,8 @@ void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, if (It->IntersectWithLine( Base::Vector3f((float)gpPt.X(), (float)gpPt.Y(), (float)gpPt.Z()), It->GetNormal(), - TempResultPoint)) { + TempResultPoint + )) { FaceProjctMap[It.Position()].push_back(TempResultPoint); str << TempResultPoint.x << " " << TempResultPoint.y << " " << TempResultPoint.z << std::endl; @@ -354,16 +367,16 @@ void CurveProjectorSimple::projectCurve(const TopoDS_Edge& aEdge, } str.close(); - Base::Console().log("Projection map [%d facets with %d points]\n", - FaceProjctMap.size(), - PointCount); + Base::Console().log("Projection map [%d facets with %d points]\n", FaceProjctMap.size(), PointCount); } -bool CurveProjectorSimple::findStartPoint(const MeshKernel& MeshK, - const Base::Vector3f& Pnt, - Base::Vector3f& Rslt, - MeshCore::FacetIndex& FaceIndex) +bool CurveProjectorSimple::findStartPoint( + const MeshKernel& MeshK, + const Base::Vector3f& Pnt, + Base::Vector3f& Rslt, + MeshCore::FacetIndex& FaceIndex +) { Base::Vector3f TempResultPoint; float MinLength = std::numeric_limits::max(); @@ -394,9 +407,11 @@ bool CurveProjectorSimple::findStartPoint(const MeshKernel& MeshK, //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -CurveProjectorWithToolMesh::CurveProjectorWithToolMesh(const TopoDS_Shape& aShape, - const MeshKernel& pMesh, - MeshKernel& rToolMesh) +CurveProjectorWithToolMesh::CurveProjectorWithToolMesh( + const TopoDS_Shape& aShape, + const MeshKernel& pMesh, + MeshKernel& rToolMesh +) : CurveProjector(aShape, pMesh) , ToolMesh(rToolMesh) { @@ -419,8 +434,7 @@ void CurveProjectorWithToolMesh::Do() // projectToNeighbours(Handle(Geom_Curve) hCurve,float pos -void CurveProjectorWithToolMesh::makeToolMesh(const TopoDS_Edge& aEdge, - std::vector& cVAry) +void CurveProjectorWithToolMesh::makeToolMesh(const TopoDS_Edge& aEdge, std::vector& cVAry) { Standard_Real fBegin, fEnd; Handle(Geom_Curve) hCurve = BRep_Tool::Curve(aEdge, fBegin, fEnd); @@ -450,7 +464,8 @@ void CurveProjectorWithToolMesh::makeToolMesh(const TopoDS_Edge& aEdge, if (It->IntersectWithLine( Base::Vector3f((float)gpPt.X(), (float)gpPt.Y(), (float)gpPt.Z()), It->GetNormal(), - cResultPoint)) { + cResultPoint + )) { if (Base::Distance(LinePoint, cResultPoint) < 0.5) { ResultNormal += It->GetNormal(); } @@ -462,9 +477,7 @@ void CurveProjectorWithToolMesh::makeToolMesh(const TopoDS_Edge& aEdge, LineSegs.push_back(s); } - Base::Console().log("Projection map [%d facets with %d points]\n", - FaceProjctMap.size(), - PointCount); + Base::Console().log("Projection map [%d facets with %d points]\n", FaceProjctMap.size(), PointCount); // build up the new mesh @@ -497,9 +510,11 @@ MeshProjection::MeshProjection(const MeshKernel& rMesh) : _rcMesh(rMesh) {} -void MeshProjection::discretize(const TopoDS_Edge& aEdge, - std::vector& polyline, - std::size_t minPoints) const +void MeshProjection::discretize( + const TopoDS_Edge& aEdge, + std::vector& polyline, + std::size_t minPoints +) const { BRepAdaptor_Curve clCurve(aEdge); @@ -516,10 +531,7 @@ void MeshProjection::discretize(const TopoDS_Edge& aEdge, } if (polyline.size() < minPoints) { - GCPnts_UniformAbscissa clAbsc(clCurve, - static_cast(minPoints), - fFirst, - fLast); + GCPnts_UniformAbscissa clAbsc(clCurve, static_cast(minPoints), fFirst, fLast); if (clAbsc.IsDone() == Standard_True) { polyline.clear(); Standard_Integer nNbPoints = clAbsc.NbPoints(); @@ -548,10 +560,12 @@ void MeshProjection::splitMeshByShape(const TopoDS_Shape& aShape, float fMaxDist str.close(); } -bool MeshProjection::findIntersection(const Edge& edgeSegm, - const Edge& meshEdge, - const Base::Vector3f& dir, - Base::Vector3f& res) const +bool MeshProjection::findIntersection( + const Edge& edgeSegm, + const Edge& meshEdge, + const Base::Vector3f& dir, + Base::Vector3f& res +) const { Base::Vector3f planeNormal; planeNormal = dir.Cross(edgeSegm.cPt2 - edgeSegm.cPt1); @@ -572,9 +586,11 @@ bool MeshProjection::findIntersection(const Edge& edgeSegm, return false; } -void MeshProjection::findSectionParameters(const TopoDS_Edge& edge, - const Base::Vector3f& dir, - std::set& parameters) const +void MeshProjection::findSectionParameters( + const TopoDS_Edge& edge, + const Base::Vector3f& dir, + std::set& parameters +) const { MeshAlgorithm clAlg(_rcMesh); float fAvgLen = clAlg.GetAverageEdgeLength(); @@ -630,9 +646,11 @@ void MeshProjection::findSectionParameters(const TopoDS_Edge& edge, } } -void MeshProjection::projectToMesh(const TopoDS_Shape& aShape, - float fMaxDist, - std::vector& rPolyLines) const +void MeshProjection::projectToMesh( + const TopoDS_Shape& aShape, + float fMaxDist, + std::vector& rPolyLines +) const { // calculate the average edge length and create a grid MeshAlgorithm clAlg(_rcMesh); @@ -662,10 +680,12 @@ void MeshProjection::projectToMesh(const TopoDS_Shape& aShape, } } -void MeshProjection::projectOnMesh(const std::vector& pointsIn, - const Base::Vector3f& dir, - float tolerance, - std::vector& pointsOut) const +void MeshProjection::projectOnMesh( + const std::vector& pointsIn, + const Base::Vector3f& dir, + float tolerance, + std::vector& pointsOut +) const { // calculate the average edge length and create a grid MeshAlgorithm clAlg(_rcMesh); @@ -711,13 +731,15 @@ void MeshProjection::projectOnMesh(const std::vector& pointsIn, else { // go through the boundary points and check if the point can be directly projected // onto one of them - auto boundaryPnt = std::find_if(boundaryPoints.begin(), - boundaryPoints.end(), - [&it, &dir](const Base::Vector3f& pnt) -> bool { - Base::Vector3f vec = pnt - it; - float angle = vec.GetAngle(dir); - return angle < 1e-6f; - }); + auto boundaryPnt = std::find_if( + boundaryPoints.begin(), + boundaryPoints.end(), + [&it, &dir](const Base::Vector3f& pnt) -> bool { + Base::Vector3f vec = pnt - it; + float angle = vec.GetAngle(dir); + return angle < 1e-6f; + } + ); if (boundaryPnt != boundaryPoints.end()) { pointsOut.push_back(*boundaryPnt); @@ -743,9 +765,11 @@ void MeshProjection::projectOnMesh(const std::vector& pointsIn, } } -void MeshProjection::projectParallelToMesh(const TopoDS_Shape& aShape, - const Base::Vector3f& dir, - std::vector& rPolyLines) const +void MeshProjection::projectParallelToMesh( + const TopoDS_Shape& aShape, + const Base::Vector3f& dir, + std::vector& rPolyLines +) const { // calculate the average edge length and create a grid MeshAlgorithm clAlg(_rcMesh); @@ -787,13 +811,15 @@ void MeshProjection::projectParallelToMesh(const TopoDS_Shape& aShape, PolyLine polyline; for (auto it : hitPointPairs) { points.clear(); - if (meshProjection.projectLineOnMesh(cGrid, - it.first.first, - it.first.second, - it.second.first, - it.second.second, - dir, - points)) { + if (meshProjection.projectLineOnMesh( + cGrid, + it.first.first, + it.first.second, + it.second.first, + it.second.second, + dir, + points + )) { polyline.points.insert(polyline.points.end(), points.begin(), points.end()); } } @@ -803,9 +829,11 @@ void MeshProjection::projectParallelToMesh(const TopoDS_Shape& aShape, } } -void MeshProjection::projectParallelToMesh(const std::vector& aEdges, - const Base::Vector3f& dir, - std::vector& rPolyLines) const +void MeshProjection::projectParallelToMesh( + const std::vector& aEdges, + const Base::Vector3f& dir, + std::vector& rPolyLines +) const { // calculate the average edge length and create a grid MeshAlgorithm clAlg(_rcMesh); @@ -839,13 +867,15 @@ void MeshProjection::projectParallelToMesh(const std::vector& aEdges, PolyLine polyline; for (auto it : hitPointPairs) { points.clear(); - if (meshProjection.projectLineOnMesh(cGrid, - it.first.first, - it.first.second, - it.second.first, - it.second.second, - dir, - points)) { + if (meshProjection.projectLineOnMesh( + cGrid, + it.first.first, + it.first.second, + it.second.first, + it.second.second, + dir, + points + )) { polyline.points.insert(polyline.points.end(), points.begin(), points.end()); } } @@ -855,10 +885,12 @@ void MeshProjection::projectParallelToMesh(const std::vector& aEdges, } } -void MeshProjection::projectEdgeToEdge(const TopoDS_Edge& aEdge, - float fMaxDist, - const MeshFacetGrid& rGrid, - std::vector& rSplitEdges) const +void MeshProjection::projectEdgeToEdge( + const TopoDS_Edge& aEdge, + float fMaxDist, + const MeshFacetGrid& rGrid, + std::vector& rSplitEdges +) const { std::vector auFInds; std::map, std::list> @@ -878,12 +910,13 @@ void MeshProjection::projectEdgeToEdge(const TopoDS_Edge& aEdge, for (MeshCore::FacetIndex index : auFInds) { const MeshFacet& rF = rclFAry[index]; for (int i = 0; i < 3; i++) { - MeshCore::PointIndex ulPt0 = - std::min(rF._aulPoints[i], rF._aulPoints[(i + 1) % 3]); - MeshCore::PointIndex ulPt1 = - std::max(rF._aulPoints[i], rF._aulPoints[(i + 1) % 3]); - pEdgeToFace[std::pair(ulPt0, ulPt1)] - .push_front(index); + MeshCore::PointIndex ulPt0 + = std::min(rF._aulPoints[i], rF._aulPoints[(i + 1) % 3]); + MeshCore::PointIndex ulPt1 + = std::max(rF._aulPoints[i], rF._aulPoints[(i + 1) % 3]); + pEdgeToFace[std::pair(ulPt0, ulPt1)].push_front( + index + ); } } @@ -899,8 +932,8 @@ void MeshProjection::projectEdgeToEdge(const TopoDS_Edge& aEdge, MeshFacetIterator cFI(_rcMesh); Base::SequencerLauncher seq("Project curve on mesh", pEdgeToFace.size()); - std::map, - std::list>::iterator it; + std::map, std::list>::iterator + it; for (it = pEdgeToFace.begin(); it != pEdgeToFace.end(); ++it) { seq.next(); @@ -925,9 +958,9 @@ void MeshProjection::projectEdgeToEdge(const TopoDS_Edge& aEdge, // create a plane from the edge normal and point Base::Vector3f cPlaneNormal = cEdgeNormal % (cE1 - cE0); - Handle(Geom_Plane) hPlane = - new Geom_Plane(gp_Pln(gp_Pnt(cE0.x, cE0.y, cE0.z), - gp_Dir(cPlaneNormal.x, cPlaneNormal.y, cPlaneNormal.z))); + Handle(Geom_Plane) hPlane = new Geom_Plane( + gp_Pln(gp_Pnt(cE0.x, cE0.y, cE0.z), gp_Dir(cPlaneNormal.x, cPlaneNormal.y, cPlaneNormal.z)) + ); // get intersection of curve and plane GeomAPI_IntCS Alg(hCurve, hPlane); diff --git a/src/Mod/MeshPart/App/CurveProjector.h b/src/Mod/MeshPart/App/CurveProjector.h index c23e165f9a..6f5fcd9c5e 100644 --- a/src/Mod/MeshPart/App/CurveProjector.h +++ b/src/Mod/MeshPart/App/CurveProjector.h @@ -104,10 +104,12 @@ public: void projectCurve(const TopoDS_Edge& aEdge, std::vector& vSplitEdges); - bool findStartPoint(const MeshKernel& MeshK, - const Base::Vector3f& Pnt, - Base::Vector3f& Rslt, - MeshCore::FacetIndex& FaceIndex); + bool findStartPoint( + const MeshKernel& MeshK, + const Base::Vector3f& Pnt, + Base::Vector3f& Rslt, + MeshCore::FacetIndex& FaceIndex + ); protected: @@ -124,19 +126,25 @@ public: ~CurveProjectorSimple() override = default; /// helper to discredicice a Edge... - void GetSampledCurves(const TopoDS_Edge& aEdge, - std::vector& rclPoints, - unsigned long ulNbOfPoints = 30); + void GetSampledCurves( + const TopoDS_Edge& aEdge, + std::vector& rclPoints, + unsigned long ulNbOfPoints = 30 + ); - void projectCurve(const TopoDS_Edge& aEdge, - const std::vector& rclPoints, - std::vector& vSplitEdges); + void projectCurve( + const TopoDS_Edge& aEdge, + const std::vector& rclPoints, + std::vector& vSplitEdges + ); - bool findStartPoint(const MeshKernel& MeshK, - const Base::Vector3f& Pnt, - Base::Vector3f& Rslt, - MeshCore::FacetIndex& FaceIndex); + bool findStartPoint( + const MeshKernel& MeshK, + const Base::Vector3f& Pnt, + Base::Vector3f& Rslt, + MeshCore::FacetIndex& FaceIndex + ); protected: @@ -154,9 +162,7 @@ public: Base::Vector3f n; }; - CurveProjectorWithToolMesh(const TopoDS_Shape& aShape, - const MeshKernel& pMesh, - MeshKernel& rToolMesh); + CurveProjectorWithToolMesh(const TopoDS_Shape& aShape, const MeshKernel& pMesh, MeshKernel& rToolMesh); ~CurveProjectorWithToolMesh() override = default; @@ -202,20 +208,22 @@ public: * @param dir * @param parameters */ - void findSectionParameters(const TopoDS_Edge& edge, - const Base::Vector3f& dir, - std::set& parameters) const; - void discretize(const TopoDS_Edge& aEdge, - std::vector& polyline, - std::size_t minPoints = 2) const; + void findSectionParameters( + const TopoDS_Edge& edge, + const Base::Vector3f& dir, + std::set& parameters + ) const; + void discretize( + const TopoDS_Edge& aEdge, + std::vector& polyline, + std::size_t minPoints = 2 + ) const; /** * Searches all edges that intersect with the projected curve \a aShape. Therefore \a aShape * must contain shapes of type TopoDS_Edge, other shape types are ignored. A possible solution * is taken if the distance between the curve point and the projected point is <= \a fMaxDist. */ - void projectToMesh(const TopoDS_Shape& aShape, - float fMaxDist, - std::vector& rPolyLines) const; + void projectToMesh(const TopoDS_Shape& aShape, float fMaxDist, std::vector& rPolyLines) const; /** * @brief projectOnMesh * Projects the given points onto the mesh along a given direction. The points can can be @@ -226,22 +234,28 @@ public: * @param tolerance * @param pointsOut */ - void projectOnMesh(const std::vector& pointsIn, - const Base::Vector3f& dir, - float tolerance, - std::vector& pointsOut) const; + void projectOnMesh( + const std::vector& pointsIn, + const Base::Vector3f& dir, + float tolerance, + std::vector& pointsOut + ) const; /** * Project all edges of the shape onto the mesh using parallel projection. */ - void projectParallelToMesh(const TopoDS_Shape& aShape, - const Base::Vector3f& dir, - std::vector& rPolyLines) const; + void projectParallelToMesh( + const TopoDS_Shape& aShape, + const Base::Vector3f& dir, + std::vector& rPolyLines + ) const; /** * Project all polylines onto the mesh using parallel projection. */ - void projectParallelToMesh(const std::vector& aEdges, - const Base::Vector3f& dir, - std::vector& rPolyLines) const; + void projectParallelToMesh( + const std::vector& aEdges, + const Base::Vector3f& dir, + std::vector& rPolyLines + ) const; /** * Cuts the mesh at the curve defined by \a aShape. This method call @ref projectToMesh() to get * the split the facet at the found points. @see projectToMesh() for more details. @@ -249,14 +263,13 @@ public: void splitMeshByShape(const TopoDS_Shape& aShape, float fMaxDist) const; protected: - void projectEdgeToEdge(const TopoDS_Edge& aCurve, - float fMaxDist, - const MeshCore::MeshFacetGrid& rGrid, - std::vector& rSplitEdges) const; - bool findIntersection(const Edge&, - const Edge&, - const Base::Vector3f& dir, - Base::Vector3f& res) const; + void projectEdgeToEdge( + const TopoDS_Edge& aCurve, + float fMaxDist, + const MeshCore::MeshFacetGrid& rGrid, + std::vector& rSplitEdges + ) const; + bool findIntersection(const Edge&, const Edge&, const Base::Vector3f& dir, Base::Vector3f& res) const; private: const MeshKernel& _rcMesh; diff --git a/src/Mod/MeshPart/App/MeshAlgos.cpp b/src/Mod/MeshPart/App/MeshAlgos.cpp index d68909579b..635728dbc5 100644 --- a/src/Mod/MeshPart/App/MeshAlgos.cpp +++ b/src/Mod/MeshPart/App/MeshAlgos.cpp @@ -25,7 +25,7 @@ #include #ifdef FC_OS_LINUX -#include +# include #endif #include @@ -48,8 +48,7 @@ void MeshAlgos::offset(MeshCore::MeshKernel* Mesh, float fSize) unsigned int i = 0; // go through all the Vertex normals - for (std::vector::iterator It = normals.begin(); It != normals.end(); - ++It, i++) { + for (std::vector::iterator It = normals.begin(); It != normals.end(); ++It, i++) { // and move each mesh point in the normal direction Mesh->MovePoint(i, It->Normalize() * fSize); } @@ -90,14 +89,18 @@ void MeshAlgos::offsetSpecial2(MeshCore::MeshKernel* Mesh, float fSize) continue; } // calculate the angle between them - float angle = acos((FaceNormals[i] * it->GetNormal()) - / (it->GetNormal().Length() * FaceNormals[i].Length())); + float angle = acos( + (FaceNormals[i] * it->GetNormal()) + / (it->GetNormal().Length() * FaceNormals[i].Length()) + ); if (angle > 1.6) { Base::DrawStyle drawStyle; drawStyle.pointSize = 4.0F; - Base::PointItem item {it->GetGravityPoint(), - drawStyle, - Base::ColorRGB {1.0F, 0.0F, 0.0F}}; + Base::PointItem item { + it->GetGravityPoint(), + drawStyle, + Base::ColorRGB {1.0F, 0.0F, 0.0F} + }; builder.addNode(item); flipped.insert(it.Position()); } @@ -130,8 +133,7 @@ void MeshAlgos::offsetSpecial(MeshCore::MeshKernel* Mesh, float fSize, float zma unsigned int i = 0; // go through all the Vertex normals - for (std::vector::iterator It = normals.begin(); It != normals.end(); - ++It, i++) { + for (std::vector::iterator It = normals.begin(); It != normals.end(); ++It, i++) { Base::Vector3f Pnt = Mesh->GetPoint(i); if (Pnt.z < zmax && Pnt.z > zmin) { @@ -157,16 +159,20 @@ void MeshAlgos::offsetSpecial(MeshCore::MeshKernel* Mesh, float fSize, float zma #include #include -void MeshAlgos::cutByShape(const TopoDS_Shape& aShape, - const MeshCore::MeshKernel* pMesh, - MeshCore::MeshKernel* pToolMesh) +void MeshAlgos::cutByShape( + const TopoDS_Shape& aShape, + const MeshCore::MeshKernel* pMesh, + MeshCore::MeshKernel* pToolMesh +) { CurveProjectorWithToolMesh Project(aShape, *pMesh, *pToolMesh); } -void MeshAlgos::cutByCurve(MeshCore::MeshKernel* pMesh, - const std::vector& vSplitEdges) +void MeshAlgos::cutByCurve( + MeshCore::MeshKernel* pMesh, + const std::vector& vSplitEdges +) { MeshTopoAlgorithm cTopAlg(*pMesh); @@ -204,11 +210,13 @@ public: }; -void MeshAlgos::LoftOnCurve(MeshCore::MeshKernel& ResultMesh, - const TopoDS_Shape& Shape, - const std::vector& poly, - const Base::Vector3f& up, - float MaxSize) +void MeshAlgos::LoftOnCurve( + MeshCore::MeshKernel& ResultMesh, + const TopoDS_Shape& Shape, + const std::vector& poly, + const Base::Vector3f& up, + float MaxSize +) { TopExp_Explorer Ex; Standard_Real fBegin, fEnd; @@ -249,9 +257,11 @@ void MeshAlgos::LoftOnCurve(MeshCore::MeshKernel& ResultMesh, prop.SetParameter(fBegin + ((fEnd - fBegin) * float(i)) / float(res - 1)); prop.Tangent(Tangent); Base::Vector3f Tng((float)Tangent.X(), (float)Tangent.Y(), (float)Tangent.Z()); - Base::Vector3f Ptn((float)prop.Value().X(), - (float)prop.Value().Y(), - (float)prop.Value().Z()); + Base::Vector3f Ptn( + (float)prop.Value().X(), + (float)prop.Value().Y(), + (float)prop.Value().Z() + ); Base::Vector3f Up(up); // normalize and calc the third vector of the plane coordinatesystem Tng.Normalize(); diff --git a/src/Mod/MeshPart/App/MeshAlgos.h b/src/Mod/MeshPart/App/MeshAlgos.h index c0b9a6c56c..e342bb1338 100644 --- a/src/Mod/MeshPart/App/MeshAlgos.h +++ b/src/Mod/MeshPart/App/MeshAlgos.h @@ -57,30 +57,40 @@ public: /** makes a boolean add * The int Type stears the boolean oberation: 0=add;1=intersection;2=diff */ - static MeshCore::MeshKernel* boolean(MeshCore::MeshKernel* Mesh1, - MeshCore::MeshKernel* Mesh2, - MeshCore::MeshKernel* pResult, - int Type = 0); + static MeshCore::MeshKernel* boolean( + MeshCore::MeshKernel* Mesh1, + MeshCore::MeshKernel* Mesh2, + MeshCore::MeshKernel* pResult, + int Type = 0 + ); - static void cutByShape(const TopoDS_Shape& aShape, - const MeshCore::MeshKernel* pMesh, - MeshCore::MeshKernel* pToolMesh); + static void cutByShape( + const TopoDS_Shape& aShape, + const MeshCore::MeshKernel* pMesh, + MeshCore::MeshKernel* pToolMesh + ); /// helper to discredicice a Edge... - static void GetSampledCurves(const TopoDS_Edge& aEdge, - std::vector& rclPoints, - unsigned long ulNbOfPoints = 30); + static void GetSampledCurves( + const TopoDS_Edge& aEdge, + std::vector& rclPoints, + unsigned long ulNbOfPoints = 30 + ); /// creates a mesh loft on base of a curve and an up vector - static void LoftOnCurve(MeshCore::MeshKernel& ResultMesh, - const TopoDS_Shape& Shape, - const std::vector& poly, - const Base::Vector3f& up = Base::Vector3f(0, 0, 1), - float MaxSize = 0.1); + static void LoftOnCurve( + MeshCore::MeshKernel& ResultMesh, + const TopoDS_Shape& Shape, + const std::vector& poly, + const Base::Vector3f& up = Base::Vector3f(0, 0, 1), + float MaxSize = 0.1 + ); - static void cutByCurve(MeshCore::MeshKernel* pMesh, - const std::vector& vSplitEdges); + static void cutByCurve( + MeshCore::MeshKernel* pMesh, + const std::vector& vSplitEdges + ); }; } // namespace MeshPart diff --git a/src/Mod/MeshPart/App/MeshFlattening.cpp b/src/Mod/MeshPart/App/MeshFlattening.cpp index 6ddd0cf24d..050f526240 100644 --- a/src/Mod/MeshPart/App/MeshFlattening.cpp +++ b/src/Mod/MeshPart/App/MeshFlattening.cpp @@ -170,9 +170,7 @@ FaceUnwrapper::FaceUnwrapper(const TopoDS_Face& face) void FaceUnwrapper::findFlatNodes(int steps, double val) { std::vector fixed_pins; // TODO: INPUT - lscmrelax::LscmRelax mesh_flattener(this->xyz_nodes.transpose(), - this->tris.transpose(), - fixed_pins); + lscmrelax::LscmRelax mesh_flattener(this->xyz_nodes.transpose(), this->tris.transpose(), fixed_pins); mesh_flattener.lscm(); for (int j = 0; j < steps; j++) { mesh_flattener.relax(val); @@ -183,8 +181,10 @@ void FaceUnwrapper::findFlatNodes(int steps, double val) ColMat FaceUnwrapper::interpolateFlatFace(const TopoDS_Face& face) { if (this->uv_nodes.size() == 0) { - throw(std::runtime_error("no uv-coordinates found, interpolating with nurbs is only " - "possible if the flattener was constructed with a nurbs.")); + throw(std::runtime_error( + "no uv-coordinates found, interpolating with nurbs is only " + "possible if the flattener was constructed with a nurbs." + )); } // extract xyz poles, knots, weights, degree @@ -195,8 +195,10 @@ ColMat FaceUnwrapper::interpolateFlatFace(const TopoDS_Face& face) const TColStd_Array1OfReal& _vknots = _bspline->VKnotSequence(); Eigen::VectorXd weights; - weights.resize(static_cast(_bspline->NbUPoles()) - * static_cast(_bspline->NbVPoles())); + weights.resize( + static_cast(_bspline->NbUPoles()) + * static_cast(_bspline->NbVPoles()) + ); long i = 0; for (long u = 1; u <= _bspline->NbUPoles(); u++) { for (long v = 1; v <= _bspline->NbVPoles(); v++) { diff --git a/src/Mod/MeshPart/App/Mesher.cpp b/src/Mod/MeshPart/App/Mesher.cpp index be7d98723f..09e0556ed0 100644 --- a/src/Mod/MeshPart/App/Mesher.cpp +++ b/src/Mod/MeshPart/App/Mesher.cpp @@ -38,45 +38,45 @@ #include "Mesher.h" #ifdef HAVE_SMESH -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Woverloaded-virtual" -#pragma clang diagnostic ignored "-Wextra-semi" -#elif defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wpedantic" -#endif +# if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Woverloaded-virtual" +# pragma clang diagnostic ignored "-Wextra-semi" +# elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wpedantic" +# endif -#include -#include -#include -#include +# include +# include +# include +# include -#include -#include -#include -#include -#if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 -#include -#endif -#include -#include -#include -#include -#include +# include +# include +# include +# include +# if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 +# include +# endif +# include +# include +# include +# include +# include -#include -#include -#if defined(HAVE_NETGEN) -#include -#include -#include -#endif // HAVE_NETGEN -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#pragma GCC diagnostic pop -#endif +# include +# include +# if defined(HAVE_NETGEN) +# include +# include +# include +# endif // HAVE_NETGEN +# if defined(__clang__) +# pragma clang diagnostic pop +# elif defined(__GNUC__) +# pragma GCC diagnostic pop +# endif #endif // HAVE_SMESH using namespace MeshPart; @@ -143,12 +143,14 @@ public: MeshCore::MeshFacetArray faces; faces.reserve(facets.size()); - std::transform(facets.cbegin(), - facets.cend(), - std::back_inserter(faces), - [](const Part::TopoShape::Facet& face) { - return MeshCore::MeshFacet(face.I1, face.I2, face.I3); - }); + std::transform( + facets.cbegin(), + facets.cend(), + std::back_inserter(faces), + [](const Part::TopoShape::Facet& face) { + return MeshCore::MeshFacet(face.I1, face.I2, face.I3); + } + ); MeshCore::MeshPointArray verts; verts.reserve(points.size()); @@ -173,14 +175,16 @@ public: if (createSegm || this->segments) { auto segments = mesh.createSegments(); meshSegments.reserve(segments.size()); - std::transform(segments.cbegin(), - segments.cend(), - std::back_inserter(meshSegments), - [](const Part::BRepMesh::Segment& segm) { - std::vector faces; - faces.insert(faces.end(), segm.cbegin(), segm.cend()); - return faces; - }); + std::transform( + segments.cbegin(), + segments.cend(), + std::back_inserter(meshSegments), + [](const Part::BRepMesh::Segment& segm) { + std::vector faces; + faces.insert(faces.end(), segm.cbegin(), segm.cend()); + return faces; + } + ); } Mesh::MeshObject* meshdata = new Mesh::MeshObject(); @@ -251,22 +255,22 @@ Mesh::MeshObject* Mesher::createMesh() const } SMESH_Gen* meshgen = Mesher::_mesh_gen; -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 SMESH_Mesh* mesh = meshgen->CreateMesh(true); -#else +# else SMESH_Mesh* mesh = meshgen->CreateMesh(0, true); -#endif +# endif int hyp = 0; switch (method) { -#if defined(HAVE_NETGEN) +# if defined(HAVE_NETGEN) case Netgen: { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 NETGENPlugin_Hypothesis_2D* hyp2d = new NETGENPlugin_Hypothesis_2D(hyp++, meshgen); -#else +# else NETGENPlugin_Hypothesis_2D* hyp2d = new NETGENPlugin_Hypothesis_2D(hyp++, 0, meshgen); -#endif +# endif if (fineness >= 0 && fineness < 5) { hyp2d->SetFineness(NETGENPlugin_Hypothesis_2D::Fineness(fineness)); @@ -293,107 +297,103 @@ Mesh::MeshObject* Mesher::createMesh() const hyp2d->SetQuadAllowed(allowquad); hyp2d->SetOptimize(optimize); - hyp2d->SetSecondOrder( - secondOrder); // apply bisecting to create four triangles out of one + hyp2d->SetSecondOrder(secondOrder); // apply bisecting to create four triangles out of one hypoth.push_back(hyp2d); -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 NETGENPlugin_NETGEN_2D* alg2d = new NETGENPlugin_NETGEN_2D(hyp++, meshgen); -#else +# else NETGENPlugin_NETGEN_2D* alg2d = new NETGENPlugin_NETGEN_2D(hyp++, 0, meshgen); -#endif +# endif hypoth.push_back(alg2d); } break; -#endif -#if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 -#if defined(HAVE_MEFISTO) +# endif +# if SMESH_VERSION_MAJOR <= 9 && SMESH_VERSION_MINOR < 10 +# if defined(HAVE_MEFISTO) case Mefisto: { if (maxLength > 0) { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_MaxLength* hyp1d = new StdMeshers_MaxLength(hyp++, meshgen); -#else +# else StdMeshers_MaxLength* hyp1d = new StdMeshers_MaxLength(hyp++, 0, meshgen); -#endif +# endif hyp1d->SetLength(maxLength); hypoth.push_back(hyp1d); } else if (localLength > 0) { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_LocalLength* hyp1d = new StdMeshers_LocalLength(hyp++, meshgen); -#else +# else StdMeshers_LocalLength* hyp1d = new StdMeshers_LocalLength(hyp++, 0, meshgen); -#endif +# endif hyp1d->SetLength(localLength); hypoth.push_back(hyp1d); } else if (maxArea > 0) { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_MaxElementArea* hyp2d = new StdMeshers_MaxElementArea(hyp++, meshgen); -#else +# else StdMeshers_MaxElementArea* hyp2d = new StdMeshers_MaxElementArea(hyp++, 0, meshgen); -#endif +# endif hyp2d->SetMaxArea(maxArea); hypoth.push_back(hyp2d); } else if (deflection > 0) { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_Deflection1D* hyp1d = new StdMeshers_Deflection1D(hyp++, meshgen); -#else +# else StdMeshers_Deflection1D* hyp1d = new StdMeshers_Deflection1D(hyp++, 0, meshgen); -#endif +# endif hyp1d->SetDeflection(deflection); hypoth.push_back(hyp1d); } else if (minLen > 0 && maxLen > 0) { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_Arithmetic1D* hyp1d = new StdMeshers_Arithmetic1D(hyp++, meshgen); -#else +# else StdMeshers_Arithmetic1D* hyp1d = new StdMeshers_Arithmetic1D(hyp++, 0, meshgen); -#endif +# endif hyp1d->SetLength(minLen, false); hyp1d->SetLength(maxLen, true); hypoth.push_back(hyp1d); } else { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_AutomaticLength* hyp1d = new StdMeshers_AutomaticLength(hyp++, meshgen); -#else - StdMeshers_AutomaticLength* hyp1d = - new StdMeshers_AutomaticLength(hyp++, 0, meshgen); -#endif +# else + StdMeshers_AutomaticLength* hyp1d = new StdMeshers_AutomaticLength(hyp++, 0, meshgen); +# endif hypoth.push_back(hyp1d); } { -#if SMESH_VERSION_MAJOR >= 9 - StdMeshers_NumberOfSegments* hyp1d = - new StdMeshers_NumberOfSegments(hyp++, meshgen); -#else - StdMeshers_NumberOfSegments* hyp1d = - new StdMeshers_NumberOfSegments(hyp++, 0, meshgen); -#endif +# if SMESH_VERSION_MAJOR >= 9 + StdMeshers_NumberOfSegments* hyp1d = new StdMeshers_NumberOfSegments(hyp++, meshgen); +# else + StdMeshers_NumberOfSegments* hyp1d = new StdMeshers_NumberOfSegments(hyp++, 0, meshgen); +# endif hyp1d->SetNumberOfSegments(1); hypoth.push_back(hyp1d); } if (regular) { -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_Regular_1D* hyp1d = new StdMeshers_Regular_1D(hyp++, meshgen); -#else +# else StdMeshers_Regular_1D* hyp1d = new StdMeshers_Regular_1D(hyp++, 0, meshgen); -#endif +# endif hypoth.push_back(hyp1d); } -#if SMESH_VERSION_MAJOR >= 9 +# if SMESH_VERSION_MAJOR >= 9 StdMeshers_MEFISTO_2D* alg2d = new StdMeshers_MEFISTO_2D(hyp++, meshgen); -#else +# else StdMeshers_MEFISTO_2D* alg2d = new StdMeshers_MEFISTO_2D(hyp++, 0, meshgen); -#endif +# endif hypoth.push_back(alg2d); } break; -#endif -#endif +# endif +# endif default: break; } diff --git a/src/Mod/MeshPart/App/Mesher.h b/src/Mod/MeshPart/App/Mesher.h index 0bcd700336..1a133f53f0 100644 --- a/src/Mod/MeshPart/App/Mesher.h +++ b/src/Mod/MeshPart/App/Mesher.h @@ -30,7 +30,7 @@ #include #ifdef HAVE_SMESH -#include +# include #endif class TopoDS_Shape; diff --git a/src/Mod/MeshPart/Gui/Command.cpp b/src/Mod/MeshPart/Gui/Command.cpp index a2dce3fd6e..130f6f29ab 100644 --- a/src/Mod/MeshPart/Gui/Command.cpp +++ b/src/Mod/MeshPart/Gui/Command.cpp @@ -95,7 +95,8 @@ void CmdMeshPartTrimByPlane::activated(int) QMessageBox::warning( Gui::getMainWindow(), qApp->translate("MeshPart_TrimByPlane", "Select plane"), - qApp->translate("MeshPart_TrimByPlane", "Select a plane to trim the mesh with.")); + qApp->translate("MeshPart_TrimByPlane", "Select a plane to trim the mesh with.") + ); return; } @@ -103,12 +104,12 @@ void CmdMeshPartTrimByPlane::activated(int) msgBox.setIcon(QMessageBox::Question); msgBox.setWindowTitle(qApp->translate("MeshPart_TrimByPlane", "Trim With Plane")); msgBox.setText(qApp->translate("MeshPart_TrimByPlane", "Select the side to keep")); - QPushButton* inner = - msgBox.addButton(qApp->translate("MeshPart_TrimByPlane", "Below"), QMessageBox::ActionRole); - QPushButton* outer = - msgBox.addButton(qApp->translate("MeshPart_TrimByPlane", "Above"), QMessageBox::ActionRole); - QPushButton* split = - msgBox.addButton(qApp->translate("MeshPart_TrimByPlane", "Split"), QMessageBox::ActionRole); + QPushButton* inner + = msgBox.addButton(qApp->translate("MeshPart_TrimByPlane", "Below"), QMessageBox::ActionRole); + QPushButton* outer + = msgBox.addButton(qApp->translate("MeshPart_TrimByPlane", "Above"), QMessageBox::ActionRole); + QPushButton* split + = msgBox.addButton(qApp->translate("MeshPart_TrimByPlane", "Split"), QMessageBox::ActionRole); msgBox.addButton(QMessageBox::Cancel); msgBox.setDefaultButton(inner); msgBox.exec(); @@ -129,12 +130,12 @@ void CmdMeshPartTrimByPlane::activated(int) return; } - Base::Placement plnPlacement = - static_cast(plane.front())->Placement.getValue(); + Base::Placement plnPlacement = static_cast(plane.front())->Placement.getValue(); openCommand(QT_TRANSLATE_NOOP("Command", "Trim with plane")); - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); for (auto it : docObj) { Base::Vector3d normal(0, 0, 1); plnPlacement.getRotation().multVec(normal, normal); @@ -201,7 +202,8 @@ void CmdMeshPartSection::activated(int) QMessageBox::warning( Gui::getMainWindow(), qApp->translate("MeshPart_Section", "Select plane"), - qApp->translate("MeshPart_Section", "Select a plane to section the mesh with.")); + qApp->translate("MeshPart_Section", "Select a plane to section the mesh with.") + ); return; } @@ -211,8 +213,9 @@ void CmdMeshPartSection::activated(int) Base::Vector3d base = plm.getPosition(); openCommand(QT_TRANSLATE_NOOP("Command", "Section with plane")); - std::vector docObj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); Mesh::MeshObject::TPlane tplane; tplane.first = Base::convertTo(base); tplane.second = Base::convertTo(normal); @@ -283,8 +286,9 @@ void CmdMeshPartCrossSections::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (!dlg) { - std::vector obj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); Base::BoundBox3d bbox; for (auto it : obj) { bbox.Add(static_cast(it)->Mesh.getBoundingBox()); @@ -296,8 +300,7 @@ void CmdMeshPartCrossSections::activated(int iMsg) bool CmdMeshPartCrossSections::isActive() { - return (Gui::Selection().countObjectsOfType() > 0 - && !Gui::Control().activeDialog()); + return (Gui::Selection().countObjectsOfType() > 0 && !Gui::Control().activeDialog()); } DEF_STD_CMD_A(CmdMeshPartCurveOnMesh) @@ -323,7 +326,8 @@ void CmdMeshPartCurveOnMesh::activated(int) } Gui::Control().showDialog( - new MeshPartGui::TaskCurveOnMesh(static_cast(mdis.front()))); + new MeshPartGui::TaskCurveOnMesh(static_cast(mdis.front())) + ); } bool CmdMeshPartCurveOnMesh::isActive() diff --git a/src/Mod/MeshPart/Gui/CrossSections.cpp b/src/Mod/MeshPart/Gui/CrossSections.cpp index 232ab65635..8de1a2fea5 100644 --- a/src/Mod/MeshPart/Gui/CrossSections.cpp +++ b/src/Mod/MeshPart/Gui/CrossSections.cpp @@ -123,13 +123,15 @@ private: class MeshCrossSection { public: - MeshCrossSection(const MeshCore::MeshKernel& mesh, - const MeshCore::MeshFacetGrid& grid, - double x, - double y, - double z, - bool connectEdges, - double eps) + MeshCrossSection( + const MeshCore::MeshKernel& mesh, + const MeshCore::MeshFacetGrid& grid, + double x, + double y, + double z, + bool connectEdges, + double eps + ) : mesh(mesh) , grid(grid) , x(x) @@ -270,8 +272,9 @@ void CrossSections::accept() void CrossSections::apply() { - std::vector obj = - Gui::Selection().getObjectsOfType(Mesh::Feature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Mesh::Feature::getClassTypeId() + ); std::vector d; if (ui->sectionsBox->isChecked()) { @@ -307,8 +310,8 @@ void CrossSections::apply() // NOLINTBEGIN MeshCrossSection cs(kernel, grid, a, b, c, connectEdges, eps); - QFuture> future = - QtConcurrent::mapped(d, std::bind(&MeshCrossSection::section, &cs, sp::_1)); + QFuture> future + = QtConcurrent::mapped(d, std::bind(&MeshCrossSection::section, &cs, sp::_1)); future.waitForFinished(); // NOLINTEND @@ -358,13 +361,15 @@ void CrossSections::apply() "points=FreeCAD.getDocument(\"%1\").%2.Mesh.crossSections(%3, %4, %5)\n" "wires=[]\n" "for i in points:\n" - " wires.extend([Part.makePolygon(j) for j in i])\n") + " wires.extend([Part.makePolygon(j) for j in i])\n" + ) .arg(QLatin1String(doc->getName())) .arg(QLatin1String((*it)->getNameInDocument())) .arg(planes) .arg(eps) .arg(connectEdges ? QLatin1String("True") : QLatin1String("False")) - .toLatin1()); + .toLatin1() + ); Gui::Command::runCommand( Gui::Command::App, @@ -373,10 +378,12 @@ void CrossSections::apply() "slice=FreeCAD.getDocument(\"%1\").addObject(\"Part::Feature\",\"%2\")\n" "slice.Shape=comp\n" "slice.purgeTouched()\n" - "del slice,comp,wires,points") + "del slice,comp,wires,points" + ) .arg(QLatin1String(doc->getName())) .arg(QLatin1String(s.c_str())) - .toLatin1()); + .toLatin1() + ); } } catch (const Base::Exception& e) { diff --git a/src/Mod/MeshPart/Gui/CrossSections.h b/src/Mod/MeshPart/Gui/CrossSections.h index 9fe695a8ad..ca7fdcb884 100644 --- a/src/Mod/MeshPart/Gui/CrossSections.h +++ b/src/Mod/MeshPart/Gui/CrossSections.h @@ -55,9 +55,11 @@ class CrossSections: public QDialog }; public: - explicit CrossSections(const Base::BoundBox3d& bb, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit CrossSections( + const Base::BoundBox3d& bb, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~CrossSections() override; void accept() override; void apply(); diff --git a/src/Mod/MeshPart/Gui/CurveOnMesh.cpp b/src/Mod/MeshPart/Gui/CurveOnMesh.cpp index 510e438635..3f82dcc371 100644 --- a/src/Mod/MeshPart/Gui/CurveOnMesh.cpp +++ b/src/Mod/MeshPart/Gui/CurveOnMesh.cpp @@ -69,13 +69,13 @@ #ifndef HAVE_ACOSH -#define HAVE_ACOSH +# define HAVE_ACOSH #endif #ifndef HAVE_ASINH -#define HAVE_ASINH +# define HAVE_ASINH #endif #ifndef HAVE_ATANH -#define HAVE_ATANH +# define HAVE_ATANH #endif @@ -279,8 +279,7 @@ public: MeshCore::MeshProjection meshProjection(kernel); Base::Vector3f v1 = Base::convertTo(last.point); Base::Vector3f v2 = Base::convertTo(pick.point); - Base::Vector3f vd = - Base::convertTo(viewer->getViewer()->getViewDirection()); + Base::Vector3f vd = Base::convertTo(viewer->getViewer()->getViewDirection()); if (meshProjection.projectLineOnMesh(*grid, v1, last.facet, v2, pick.facet, vd, polyline)) { if (polyline.size() > 1) { if (cutLines.empty()) { @@ -344,10 +343,7 @@ void CurveOnMeshHandler::enableApproximation(bool on) d_ptr->approximate = on; } -void CurveOnMeshHandler::setParameters(int maxDegree, - GeomAbs_Shape cont, - double tol3d, - double angle) +void CurveOnMeshHandler::setParameters(int maxDegree, GeomAbs_Shape cont, double tol3d, double angle) { d_ptr->par.maxDegree = maxDegree; d_ptr->par.cont = cont; @@ -487,11 +483,7 @@ Handle(Geom_BSplineCurve) CurveOnMeshHandler::approximateSpline(const std::vecto // GeomAPI_PointsToBSpline fit(pnts, d_ptr->par.weight1, d_ptr->par.weight2, // d_ptr->par.weight3, // d_ptr->par.maxDegree, d_ptr->par.cont, d_ptr->par.tol3d); - GeomAPI_PointsToBSpline fit(pnts, - 1, - d_ptr->par.maxDegree, - d_ptr->par.cont, - d_ptr->par.tol3d); + GeomAPI_PointsToBSpline fit(pnts, 1, d_ptr->par.maxDegree, d_ptr->par.cont, d_ptr->par.tol3d); Handle(Geom_BSplineCurve) spline = fit.Curve(); return spline; } @@ -512,9 +504,11 @@ void CurveOnMeshHandler::approximateEdge(const TopoDS_Edge& edge, double toleran pts.reserve(numNodes); for (int i = aNodes.Lower(); i <= aNodes.Upper(); i++) { const gp_Pnt& p = aNodes.Value(i); - pts.emplace_back(static_cast(p.X()), - static_cast(p.Y()), - static_cast(p.Z())); + pts.emplace_back( + static_cast(p.X()), + static_cast(p.Y()), + static_cast(p.Z()) + ); } d_ptr->curve->setPoints(pts); @@ -608,8 +602,7 @@ void CurveOnMeshHandler::Private::vertexCallback(void* ud, SoEventCallback* cb) if (!self->d_ptr->wireClosed) { Gui::ViewProvider* vp = view->getViewProviderByPathFromTail(pp->getPath()); if (vp && vp->isDerivedFrom()) { - MeshGui::ViewProviderMesh* mesh = - static_cast(vp); + MeshGui::ViewProviderMesh* mesh = static_cast(vp); const SoDetail* detail = pp->getDetail(); if (detail && detail->getTypeId() == SoFaceDetail::getClassTypeId()) { // get the mesh and build a grid @@ -619,7 +612,8 @@ void CurveOnMeshHandler::Private::vertexCallback(void* ud, SoEventCallback* cb) } else if (self->d_ptr->mesh != mesh) { Gui::getMainWindow()->statusBar()->showMessage( - tr("Wrong mesh selected")); + tr("Wrong mesh selected") + ); return; } diff --git a/src/Mod/MeshPart/Gui/TaskCurveOnMesh.cpp b/src/Mod/MeshPart/Gui/TaskCurveOnMesh.cpp index e63726bb3f..5a838ce9ae 100644 --- a/src/Mod/MeshPart/Gui/TaskCurveOnMesh.cpp +++ b/src/Mod/MeshPart/Gui/TaskCurveOnMesh.cpp @@ -81,10 +81,12 @@ void CurveOnMeshWidget::onStartButtonClicked() { int cont = ui->continuity->itemData(ui->continuity->currentIndex()).toInt(); myCurveHandler->enableApproximation(ui->groupBox_2->isChecked()); - myCurveHandler->setParameters(ui->maxDegree->currentIndex() + 1, - static_cast(cont), - ui->meshTolerance->value(), - ui->splitAngle->value().getValue()); + myCurveHandler->setParameters( + ui->maxDegree->currentIndex() + 1, + static_cast(cont), + ui->meshTolerance->value(), + ui->splitAngle->value().getValue() + ); myCurveHandler->enableCallback(myView); } diff --git a/src/Mod/MeshPart/Gui/Tessellation.cpp b/src/Mod/MeshPart/Gui/Tessellation.cpp index f59dd67bb3..fe41f509d8 100644 --- a/src/Mod/MeshPart/Gui/Tessellation.cpp +++ b/src/Mod/MeshPart/Gui/Tessellation.cpp @@ -62,7 +62,8 @@ Tessellation::Tessellation(QWidget* parent) ui->stackedWidget->addTab(gmsh, tr("Gmsh")); ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh/Meshing/Standard"); + "User parameter:BaseApp/Preferences/Mod/Mesh/Meshing/Standard" + ); double value = ui->spinSurfaceDeviation->value().getValue(); value = handle->GetFloat("LinearDeflection", value); double angle = ui->spinAngularDeviation->value().getValue(); @@ -102,22 +103,20 @@ Tessellation::~Tessellation() = default; void Tessellation::setupConnections() { connect(gmsh, &Mesh2ShapeGmsh::processed, this, &Tessellation::gmshProcessed); - connect(ui->estimateMaximumEdgeLength, - &QPushButton::clicked, - this, - &Tessellation::onEstimateMaximumEdgeLengthClicked); - connect(ui->comboFineness, - qOverload(&QComboBox::currentIndexChanged), - this, - &Tessellation::onComboFinenessCurrentIndexChanged); - connect(ui->checkSecondOrder, - &QCheckBox::toggled, - this, - &Tessellation::onCheckSecondOrderToggled); - connect(ui->checkQuadDominated, - &QCheckBox::toggled, - this, - &Tessellation::onCheckQuadDominatedToggled); + connect( + ui->estimateMaximumEdgeLength, + &QPushButton::clicked, + this, + &Tessellation::onEstimateMaximumEdgeLengthClicked + ); + connect( + ui->comboFineness, + qOverload(&QComboBox::currentIndexChanged), + this, + &Tessellation::onComboFinenessCurrentIndexChanged + ); + connect(ui->checkSecondOrder, &QCheckBox::toggled, this, &Tessellation::onCheckSecondOrderToggled); + connect(ui->checkQuadDominated, &QCheckBox::toggled, this, &Tessellation::onCheckQuadDominatedToggled); } void Tessellation::meshingMethod(int id) @@ -217,10 +216,11 @@ void Tessellation::onEstimateMaximumEdgeLengthClicked() double edgeLen = 0; for (auto& sel : Gui::Selection().getSelection("*", Gui::ResolveMode::NoResolve)) { - auto shape = Part::Feature::getTopoShape(sel.pObject, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sel.SubName); + auto shape = Part::Feature::getTopoShape( + sel.pObject, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform, + sel.SubName + ); if (shape.hasSubShape(TopAbs_FACE)) { Base::BoundBox3d bbox = shape.getBoundBox(); edgeLen = std::max(edgeLen, bbox.LengthX()); @@ -252,10 +252,11 @@ bool Tessellation::accept() bool bodyWithNoTip = false; bool partWithNoFace = false; for (auto& sel : Gui::Selection().getSelection("*", Gui::ResolveMode::NoResolve)) { - auto shape = Part::Feature::getTopoShape(sel.pObject, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sel.SubName); + auto shape = Part::Feature::getTopoShape( + sel.pObject, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform, + sel.SubName + ); if (shape.hasSubShape(TopAbs_FACE)) { shapeObjects.emplace_back(sel.pObject, sel.SubName); } @@ -277,13 +278,16 @@ bool Tessellation::accept() this, windowTitle(), tr("Error: body without a tip selected.\n" - "Either set the tip of the body or select a different shape.")); + "Either set the tip of the body or select a different shape.") + ); } else if (partWithNoFace) { - QMessageBox::critical(this, - windowTitle(), - tr("Error: shape without faces selected.\n" - "Select a different shape.")); + QMessageBox::critical( + this, + windowTitle(), + tr("Error: shape without faces selected.\n" + "Select a different shape.") + ); } else { QMessageBox::critical(this, windowTitle(), tr("Select a shape for meshing, first.")); @@ -305,9 +309,7 @@ bool Tessellation::accept() return doClose; } -void Tessellation::process(int method, - App::Document* doc, - const std::list& shapeObjects) +void Tessellation::process(int method, App::Document* doc, const std::list& shapeObjects) { try { Gui::WaitCursor wc; @@ -336,13 +338,15 @@ void Tessellation::process(int method, QString param = getMeshingParameters(method, sobj); - QString cmd = QStringLiteral("__doc__=FreeCAD.getDocument(\"%1\")\n" - "__mesh__=__doc__.addObject(\"Mesh::Feature\",\"Mesh\")\n" - "__part__=__doc__.getObject(\"%2\")\n" - "__shape__=Part.getShape(__part__,\"%3\")\n" - "__mesh__.Mesh=MeshPart.meshFromShape(%4)\n" - "__mesh__.Label=\"%5 (Meshed)\"\n" - "del __doc__, __mesh__, __part__, __shape__\n") + QString cmd = QStringLiteral( + "__doc__=FreeCAD.getDocument(\"%1\")\n" + "__mesh__=__doc__.addObject(\"Mesh::Feature\",\"Mesh\")\n" + "__part__=__doc__.getObject(\"%2\")\n" + "__shape__=Part.getShape(__part__,\"%3\")\n" + "__mesh__.Mesh=MeshPart.meshFromShape(%4)\n" + "__mesh__.Label=\"%5 (Meshed)\"\n" + "del __doc__, __mesh__, __part__, __shape__\n" + ) .arg(this->document, objname, subname, param, label); Gui::Command::runCommand(Gui::Command::Doc, cmd.toUtf8()); @@ -361,7 +365,8 @@ void Tessellation::saveParameters(int method) { if (method == Standard) { ParameterGrp::handle handle = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Mesh/Meshing/Standard"); + "User parameter:BaseApp/Preferences/Mod/Mesh/Meshing/Standard" + ); double value = ui->spinSurfaceDeviation->value().getValue(); handle->SetFloat("LinearDeflection", value); double angle = ui->spinAngularDeviation->value().getValue(); @@ -376,12 +381,14 @@ void Tessellation::setFaceColors(int method, App::Document* doc, App::DocumentOb // if Standard mesher is used and face colors should be applied if (method == Standard) { if (ui->meshShapeColors->isChecked()) { - Gui::ViewProvider* vpm = - Gui::Application::Instance->getViewProvider(doc->getActiveObject()); + Gui::ViewProvider* vpm = Gui::Application::Instance->getViewProvider( + doc->getActiveObject() + ); auto vpmesh = dynamic_cast(vpm); auto svp = freecad_cast( - Gui::Application::Instance->getViewProvider(obj)); + Gui::Application::Instance->getViewProvider(obj) + ); if (vpmesh && svp) { std::vector diff_col = svp->ShapeAppearance.getDiffuseColors(); if (ui->groupsFaceColors->isChecked()) { @@ -412,7 +419,8 @@ void Tessellation::addFaceColors(Mesh::Feature* mesh, const std::vector( - mesh->addDynamicProperty(typeId.getName(), "FaceColors"))) { + mesh->addDynamicProperty(typeId.getName(), "FaceColors") + )) { prop->setValues(colorPerFace); } } @@ -458,10 +466,12 @@ QString Tessellation::getStandardParameters(App::DocumentObject* obj) const bool relative = ui->relativeDeviation->isChecked(); QString param; - param = QStringLiteral("Shape=__shape__, " - "LinearDeflection=%1, " - "AngularDeflection=%2, " - "Relative=%3") + param = QStringLiteral( + "Shape=__shape__, " + "LinearDeflection=%1, " + "AngularDeflection=%2, " + "Relative=%3" + ) .arg(devFace) .arg(devAngle) .arg(relative ? QStringLiteral("True") : QStringLiteral("False")); @@ -470,7 +480,8 @@ QString Tessellation::getStandardParameters(App::DocumentObject* obj) const } auto svp = freecad_cast( - Gui::Application::Instance->getViewProvider(obj)); + Gui::Application::Instance->getViewProvider(obj) + ); if (ui->groupsFaceColors->isChecked() && svp) { // TODO: currently, we can only retrieve part feature // color. The problem is that if the feature is linked, @@ -484,8 +495,10 @@ QString Tessellation::getStandardParameters(App::DocumentObject* obj) const // PartGui::ViewProviderPartExt::getShapeColors(). // param += QStringLiteral(",GroupColors=Gui.getDocument('%1').getObject('%2').DiffuseColor") - .arg(QString::fromLatin1(obj->getDocument()->getName()), - QString::fromLatin1(obj->getNameInDocument())); + .arg( + QString::fromLatin1(obj->getDocument()->getName()), + QString::fromLatin1(obj->getNameInDocument()) + ); } return param; @@ -511,17 +524,21 @@ QString Tessellation::getNetgenParameters() const bool optimize = ui->checkOptimizeSurface->isChecked(); bool allowquad = ui->checkQuadDominated->isChecked(); if (fineness <= int(VeryFine)) { - param = QStringLiteral("Shape=__shape__," - "Fineness=%1,SecondOrder=%2,Optimize=%3,AllowQuad=%4") + param = QStringLiteral( + "Shape=__shape__," + "Fineness=%1,SecondOrder=%2,Optimize=%3,AllowQuad=%4" + ) .arg(fineness) .arg(secondOrder ? 1 : 0) .arg(optimize ? 1 : 0) .arg(allowquad ? 1 : 0); } else { - param = QStringLiteral("Shape=__shape__," - "GrowthRate=%1,SegPerEdge=%2,SegPerRadius=%3,SecondOrder=%4," - "Optimize=%5,AllowQuad=%6") + param = QStringLiteral( + "Shape=__shape__," + "GrowthRate=%1,SegPerEdge=%2,SegPerRadius=%3,SecondOrder=%4," + "Optimize=%5,AllowQuad=%6" + ) .arg(growthRate) .arg(nbSegPerEdge) .arg(nbSegPerRadius) @@ -574,10 +591,11 @@ bool Mesh2ShapeGmsh::writeProject(QString& inpFile, QString& outFile) App::DocumentObject* part = sub.getObject(); if (part) { - Part::TopoShape shape = Part::Feature::getTopoShape(part, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sub.getSubName().c_str()); + Part::TopoShape shape = Part::Feature::getTopoShape( + part, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform, + sub.getSubName().c_str() + ); shape.exportBrep(d->cadFile.c_str()); d->label = part->Label.getStrValue() + " (Meshed)"; diff --git a/src/Mod/MeshPart/MeshPartGlobal.h b/src/Mod/MeshPart/MeshPartGlobal.h index de27c26890..65bb4d0d70 100644 --- a/src/Mod/MeshPart/MeshPartGlobal.h +++ b/src/Mod/MeshPart/MeshPartGlobal.h @@ -25,25 +25,25 @@ #include #ifndef MESHPART_GLOBAL_H -#define MESHPART_GLOBAL_H +# define MESHPART_GLOBAL_H // MeshPart -#ifndef MeshPartExport -#ifdef MeshPart_EXPORTS -#define MeshPartExport FREECAD_DECL_EXPORT -#else -#define MeshPartExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef MeshPartExport +# ifdef MeshPart_EXPORTS +# define MeshPartExport FREECAD_DECL_EXPORT +# else +# define MeshPartExport FREECAD_DECL_IMPORT +# endif +# endif // MeshPartGui -#ifndef MeshPartGuiExport -#ifdef MeshPartGui_EXPORTS -#define MeshPartGuiExport FREECAD_DECL_EXPORT -#else -#define MeshPartGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef MeshPartGuiExport +# ifdef MeshPartGui_EXPORTS +# define MeshPartGuiExport FREECAD_DECL_EXPORT +# else +# define MeshPartGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // MESHPART_GLOBAL_H diff --git a/src/Mod/Part/App/AppPart.cpp b/src/Mod/Part/App/AppPart.cpp index 54bd1ea70d..5f1414e658 100644 --- a/src/Mod/Part/App/AppPart.cpp +++ b/src/Mod/Part/App/AppPart.cpp @@ -23,10 +23,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -196,7 +196,8 @@ #include #include -namespace Part { +namespace Part +{ extern PyObject* initModule(); } diff --git a/src/Mod/Part/App/AppPartPy.cpp b/src/Mod/Part/App/AppPartPy.cpp index 60e902bc3e..64389b4ed7 100644 --- a/src/Mod/Part/App/AppPartPy.cpp +++ b/src/Mod/Part/App/AppPartPy.cpp @@ -22,54 +22,54 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include +#include #include #include @@ -108,14 +108,15 @@ #include "TopoShapeMapper.h" #ifdef FCUseFreeType -# include "FT2FC.h" +# include "FT2FC.h" #endif FC_LOG_LEVEL_INIT("Part") extern const char* BRepBuilderAPI_FaceErrorText(BRepBuilderAPI_FaceError fe); -namespace Part { +namespace Part +{ PartExport void getPyShapes(PyObject* obj, std::vector& shapes) { @@ -135,8 +136,7 @@ PartExport void getPyShapes(PyObject* obj, std::vector& shapes) shapes.push_back(*static_cast((*it).ptr())->getTopoShapePtr()); } else if (PyObject_TypeCheck((*it).ptr(), &GeometryPy::Type)) { - shapes.emplace_back( - static_cast((*it).ptr())->getGeometryPtr()->toShape()); + shapes.emplace_back(static_cast((*it).ptr())->getGeometryPtr()->toShape()); } else { throw Py::TypeError("expect shape in sequence"); @@ -148,31 +148,33 @@ PartExport void getPyShapes(PyObject* obj, std::vector& shapes) } } -PartExport std::vector getPyShapes(PyObject *obj) { +PartExport std::vector getPyShapes(PyObject* obj) +{ std::vector ret; - getPyShapes(obj,ret); + getPyShapes(obj, ret); return ret; } namespace { -struct EdgePoints { +struct EdgePoints +{ gp_Pnt v1, v2; std::list::iterator it; TopoDS_Edge edge; }; -} +} // namespace PartExport std::list sort_Edges(double tol3d, std::list& edges) { tol3d = tol3d * tol3d; - std::list edge_points; + std::list edge_points; TopExp_Explorer xp; for (std::list::iterator it = edges.begin(); it != edges.end(); ++it) { EdgePoints ep; - xp.Init(*it,TopAbs_VERTEX); + xp.Init(*it, TopAbs_VERTEX); ep.v1 = BRep_Tool::Pnt(TopoDS::Vertex(xp.Current())); xp.Next(); ep.v2 = BRep_Tool::Pnt(TopoDS::Vertex(xp.Current())); @@ -181,13 +183,14 @@ PartExport std::list sort_Edges(double tol3d, std::list sorted; gp_Pnt first, last; first = edge_points.front().v1; - last = edge_points.front().v2; + last = edge_points.front().v2; sorted.push_back(edge_points.front().edge); edges.erase(edge_points.front().it); @@ -249,78 +252,95 @@ PartExport std::list sort_Edges(double tol3d, std::list +namespace Part +{ +class BRepFeatModule: public Py::ExtensionModule { public: - BRepFeatModule() : Py::ExtensionModule("BRepFeat") + BRepFeatModule() + : Py::ExtensionModule("BRepFeat") { - initialize("This is a module working with the BRepFeat package."); // register with Python + initialize("This is a module working with the BRepFeat package."); // register with Python } }; -class BRepOffsetAPIModule : public Py::ExtensionModule +class BRepOffsetAPIModule: public Py::ExtensionModule { public: - BRepOffsetAPIModule() : Py::ExtensionModule("BRepOffsetAPI") + BRepOffsetAPIModule() + : Py::ExtensionModule("BRepOffsetAPI") { - initialize("This is a module working with the BRepOffsetAPI package."); // register with Python + initialize("This is a module working with the BRepOffsetAPI package."); // register with Python } }; -class Geom2dModule : public Py::ExtensionModule +class Geom2dModule: public Py::ExtensionModule { public: - Geom2dModule() : Py::ExtensionModule("Geom2d") + Geom2dModule() + : Py::ExtensionModule("Geom2d") { - initialize("This is a module working with 2d geometries."); // register with Python + initialize("This is a module working with 2d geometries."); // register with Python } }; -class GeomPlateModule : public Py::ExtensionModule +class GeomPlateModule: public Py::ExtensionModule { public: - GeomPlateModule() : Py::ExtensionModule("GeomPlate") + GeomPlateModule() + : Py::ExtensionModule("GeomPlate") { - initialize("This is a module working with the GeomPlate framework."); // register with Python + initialize("This is a module working with the GeomPlate framework."); // register with Python } }; -class HLRBRepModule : public Py::ExtensionModule +class HLRBRepModule: public Py::ExtensionModule { public: - HLRBRepModule() : Py::ExtensionModule("HLRBRep") + HLRBRepModule() + : Py::ExtensionModule("HLRBRep") { - initialize("This is a module working with the HLRBRep framework."); // register with Python + initialize("This is a module working with the HLRBRep framework."); // register with Python } }; -class ShapeFixModule : public Py::ExtensionModule +class ShapeFixModule: public Py::ExtensionModule { public: - ShapeFixModule() : Py::ExtensionModule("ShapeFix") + ShapeFixModule() + : Py::ExtensionModule("ShapeFix") { - add_varargs_method("sameParameter",&ShapeFixModule::sameParameter, + add_varargs_method( + "sameParameter", + &ShapeFixModule::sameParameter, "sameParameter(shape, enforce, prec=0.0)" ); - add_varargs_method("encodeRegularity",&ShapeFixModule::encodeRegularity, + add_varargs_method( + "encodeRegularity", + &ShapeFixModule::encodeRegularity, "encodeRegularity(shape, tolerance = 1e-10)\n" ); - add_varargs_method("removeSmallEdges",&ShapeFixModule::removeSmallEdges, + add_varargs_method( + "removeSmallEdges", + &ShapeFixModule::removeSmallEdges, "removeSmallEdges(shape, tolerance, ReShapeContext)\n" "Removes edges which are less than given tolerance from shape" ); - add_varargs_method("fixVertexPosition",&ShapeFixModule::fixVertexPosition, + add_varargs_method( + "fixVertexPosition", + &ShapeFixModule::fixVertexPosition, "fixVertexPosition(shape, tolerance, ReShapeContext)\n" "Fix position of the vertices having tolerance more tnan specified one" ); - add_varargs_method("leastEdgeSize",&ShapeFixModule::leastEdgeSize, + add_varargs_method( + "leastEdgeSize", + &ShapeFixModule::leastEdgeSize, "leastEdgeSize(shape)\n" "Calculate size of least edge" ); - initialize("This is a module working with the ShapeFix framework."); // register with Python + initialize("This is a module working with the ShapeFix framework."); // register with Python } private: @@ -329,8 +349,17 @@ private: PyObject* shape; PyObject* enforce; double prec = 0.0; - if (!PyArg_ParseTuple(args.ptr(), "O!O!|d", &TopoShapePy::Type, &shape, &PyBool_Type, &enforce, &prec)) + if (!PyArg_ParseTuple( + args.ptr(), + "O!O!|d", + &TopoShapePy::Type, + &shape, + &PyBool_Type, + &enforce, + &prec + )) { throw Py::Exception(); + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); bool ok = ShapeFix::SameParameter(sh, Base::asBoolean(enforce), prec); @@ -340,8 +369,9 @@ private: { PyObject* shape; double tolang = 1.0e-10; - if (!PyArg_ParseTuple(args.ptr(), "O!|d", &TopoShapePy::Type, &shape, &tolang)) + if (!PyArg_ParseTuple(args.ptr(), "O!|d", &TopoShapePy::Type, &shape, &tolang)) { throw Py::Exception(); + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); ShapeFix::EncodeRegularity(sh, tolang); @@ -351,8 +381,9 @@ private: { PyObject* shape; double tol; - if (!PyArg_ParseTuple(args.ptr(), "O!d", &TopoShapePy::Type, &shape, &tol)) + if (!PyArg_ParseTuple(args.ptr(), "O!d", &TopoShapePy::Type, &shape, &tol)) { throw Py::Exception(); + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); Handle(ShapeBuild_ReShape) reshape = new ShapeBuild_ReShape(); @@ -363,8 +394,9 @@ private: { PyObject* shape; double tol; - if (!PyArg_ParseTuple(args.ptr(), "O!d", &TopoShapePy::Type, &shape, &tol)) + if (!PyArg_ParseTuple(args.ptr(), "O!d", &TopoShapePy::Type, &shape, &tol)) { throw Py::Exception(); + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); Handle(ShapeBuild_ReShape) reshape = new ShapeBuild_ReShape(); @@ -374,8 +406,9 @@ private: Py::Object leastEdgeSize(const Py::Tuple& args) { PyObject* shape; - if (!PyArg_ParseTuple(args.ptr(), "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args.ptr(), "O!", &TopoShapePy::Type, &shape)) { throw Py::Exception(); + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); double len = ShapeFix::LeastEdgeSize(sh); @@ -383,25 +416,27 @@ private: } }; -class ShapeUpgradeModule : public Py::ExtensionModule +class ShapeUpgradeModule: public Py::ExtensionModule { public: - ShapeUpgradeModule() : Py::ExtensionModule("ShapeUpgrade") + ShapeUpgradeModule() + : Py::ExtensionModule("ShapeUpgrade") { - initialize("This is a module working with the ShapeUpgrade framework."); // register with Python + initialize("This is a module working with the ShapeUpgrade framework."); // register with Python } }; -class ChFi2dModule : public Py::ExtensionModule +class ChFi2dModule: public Py::ExtensionModule { public: - ChFi2dModule() : Py::ExtensionModule("ChFi2d") + ChFi2dModule() + : Py::ExtensionModule("ChFi2d") { - initialize("This is a module working with the ChFi2d framework."); // register with Python + initialize("This is a module working with the ChFi2d framework."); // register with Python } }; -class Module : public Py::ExtensionModule +class Module: public Py::ExtensionModule { BRepFeatModule brepFeat; BRepOffsetAPIModule brepOffsetApi; @@ -411,63 +446,97 @@ class Module : public Py::ExtensionModule ShapeFixModule shapeFix; ShapeUpgradeModule shapeUpgrade; ChFi2dModule chFi2d; + public: - Module() : Py::ExtensionModule("Part") + Module() + : Py::ExtensionModule("Part") { - add_varargs_method("open",&Module::open, + add_varargs_method( + "open", + &Module::open, "open(string) -- Create a new document and load the file into the document." ); - add_varargs_method("insert",&Module::insert, + add_varargs_method( + "insert", + &Module::insert, "insert(string,string) -- Insert the file into the given document." ); - add_varargs_method("export",&Module::exporter, + add_varargs_method( + "export", + &Module::exporter, "export(list,string) -- Export a list of objects into a single file." ); - add_varargs_method("read",&Module::read, - "read(string) -- Load the file and return the shape." - ); - add_varargs_method("show",&Module::show, - "show(shape,[string]) -- Add the shape to the active document or create one if no document exists.\n" + add_varargs_method("read", &Module::read, "read(string) -- Load the file and return the shape."); + add_varargs_method( + "show", + &Module::show, + "show(shape,[string]) -- Add the shape to the active document or create one if no " + "document exists.\n" "Returns document object." ); - add_varargs_method("getFacets",&Module::getFacets, + add_varargs_method( + "getFacets", + &Module::getFacets, "getFacets(shape): simplified mesh generation" ); - add_keyword_method("makeCompound",&Module::makeCompound, + add_keyword_method( + "makeCompound", + &Module::makeCompound, "makeCompound(list) -- Create a compound out of a list of shapes." ); - add_keyword_method("makeShell",&Module::makeShell, + add_keyword_method( + "makeShell", + &Module::makeShell, "makeShell(list) -- Create a shell out of a list of faces." ); - add_keyword_method("makeFace",&Module::makeFace, - "makeFace(list_of_shapes_or_compound, maker_class_name) -- Create a face (faces) using facemaker class.\n" + add_keyword_method( + "makeFace", + &Module::makeFace, + "makeFace(list_of_shapes_or_compound, maker_class_name) -- Create a face (faces) using " + "facemaker class.\n" "maker_class_name is a string like 'Part::FaceMakerSimple'." ); - add_keyword_method("makeFilledSurface",&Module::makeFilledSurface, - "makeFilledSurface(list of curves, tolerance) -- Create a surface out of a list of curves." + add_keyword_method( + "makeFilledSurface", + &Module::makeFilledSurface, + "makeFilledSurface(list of curves, tolerance) -- Create a surface out of a list of " + "curves." ); - add_keyword_method("makeFilledFace",&Module::makeFilledFace, + add_keyword_method( + "makeFilledFace", + &Module::makeFilledFace, "makeFilledFace(list) -- Create a face out of a list of edges." ); - add_keyword_method("makeSolid",&Module::makeSolid, - "makeSolid(shape): Create a solid out of shells of shape. If shape is a compsolid, the overall volume solid is created." + add_keyword_method( + "makeSolid", + &Module::makeSolid, + "makeSolid(shape): Create a solid out of shells of shape. If shape is a compsolid, the " + "overall volume solid is created." ); - add_varargs_method("makePlane",&Module::makePlane, + add_varargs_method( + "makePlane", + &Module::makePlane, "makePlane(length,width,[pnt,dirZ,dirX]) -- Make a plane\n" "By default pnt=Vector(0,0,0) and dirZ=Vector(0,0,1), dirX is ignored in this case" ); - add_varargs_method("makeBox",&Module::makeBox, + add_varargs_method( + "makeBox", + &Module::makeBox, "makeBox(length,width,height,[pnt,dir]) -- Make a box located\n" "in pnt with the dimensions (length,width,height)\n" "By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)" ); - add_varargs_method("makeWedge",&Module::makeWedge, + add_varargs_method( + "makeWedge", + &Module::makeWedge, "makeWedge(xmin, ymin, zmin, z2min, x2min,\n" "xmax, ymax, zmax, z2max, x2max,[pnt,dir])\n" " -- Make a wedge located in pnt\n" "By default pnt=Vector(0,0,0) and dir=Vector(0,0,1)" ); - add_varargs_method("makeLine",&Module::makeLine, + add_varargs_method( + "makeLine", + &Module::makeLine, "makeLine(startpnt,endpnt) -- Make a line between two points\n" "\n" "Args:\n" @@ -481,7 +550,9 @@ public: "Returns:\n" " Edge: Part.Edge object\n" ); - add_varargs_method("makePolygon",&Module::makePolygon, + add_varargs_method( + "makePolygon", + &Module::makePolygon, "makePolygon(pntslist) -- Make a polygon from a list of points\n" "\n" "Args:\n" @@ -493,69 +564,114 @@ public: " not the same as the first point, the Wire will not be \n" " closed and cannot be used to create a face.\n" ); - add_varargs_method("makeCircle",&Module::makeCircle, + add_varargs_method( + "makeCircle", + &Module::makeCircle, "makeCircle(radius,[pnt,dir,angle1,angle2]) -- Make a circle with a given radius\n" "By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0 and angle2=360" ); - add_varargs_method("makeSphere",&Module::makeSphere, - "makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Make a sphere with a given radius\n" + add_varargs_method( + "makeSphere", + &Module::makeSphere, + "makeSphere(radius,[pnt, dir, angle1,angle2,angle3]) -- Make a sphere with a given " + "radius\n" "By default pnt=Vector(0,0,0), dir=Vector(0,0,1), angle1=0, angle2=90 and angle3=360" ); - add_varargs_method("makeCylinder",&Module::makeCylinder, - "makeCylinder(radius,height,[pnt,dir,angle]) -- Make a cylinder with a given radius and height\n" + add_varargs_method( + "makeCylinder", + &Module::makeCylinder, + "makeCylinder(radius,height,[pnt,dir,angle]) -- Make a cylinder with a given radius " + "and height\n" "By default pnt=Vector(0,0,0),dir=Vector(0,0,1) and angle=360" ); - add_varargs_method("makeCone",&Module::makeCone, - "makeCone(radius1,radius2,height,[pnt,dir,angle]) -- Make a cone with given radii and height\n" + add_varargs_method( + "makeCone", + &Module::makeCone, + "makeCone(radius1,radius2,height,[pnt,dir,angle]) -- Make a cone with given radii and " + "height\n" "By default pnt=Vector(0,0,0), dir=Vector(0,0,1) and angle=360" ); - add_varargs_method("makeTorus",&Module::makeTorus, - "makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- Make a torus with a given radii and angles\n" + add_varargs_method( + "makeTorus", + &Module::makeTorus, + "makeTorus(radius1,radius2,[pnt,dir,angle1,angle2,angle]) -- Make a torus with a given " + "radii and angles\n" "By default pnt=Vector(0,0,0),dir=Vector(0,0,1),angle1=0,angle1=360 and angle=360" ); - add_varargs_method("makeHelix",&Module::makeHelix, - "makeHelix(pitch,height,radius,[angle]) -- Make a helix with a given pitch, height and radius\n" - "By default a cylindrical surface is used to create the helix. If the fourth parameter is set\n" + add_varargs_method( + "makeHelix", + &Module::makeHelix, + "makeHelix(pitch,height,radius,[angle]) -- Make a helix with a given pitch, height and " + "radius\n" + "By default a cylindrical surface is used to create the helix. If the fourth parameter " + "is set\n" "(the apex given in degree) a conical surface is used instead" ); - add_varargs_method("makeLongHelix",&Module::makeLongHelix, - "makeLongHelix(pitch,height,radius,[angle],[hand]) -- Make a (multi-edge) helix with a given pitch, height and radius\n" - "By default a cylindrical surface is used to create the helix. If the fourth parameter is set\n" + add_varargs_method( + "makeLongHelix", + &Module::makeLongHelix, + "makeLongHelix(pitch,height,radius,[angle],[hand]) -- Make a (multi-edge) helix with a " + "given pitch, height and radius\n" + "By default a cylindrical surface is used to create the helix. If the fourth parameter " + "is set\n" "(the apex given in degree) a conical surface is used instead." ); - add_varargs_method("makeThread",&Module::makeThread, - "makeThread(pitch,depth,height,radius) -- Make a thread with a given pitch, depth, height and radius" + add_varargs_method( + "makeThread", + &Module::makeThread, + "makeThread(pitch,depth,height,radius) -- Make a thread with a given pitch, depth, " + "height and radius" ); - add_varargs_method("makeRevolution",&Module::makeRevolution, - "makeRevolution(Curve or Edge,[vmin,vmax,angle,pnt,dir,shapetype]) -- Make a revolved shape\n" + add_varargs_method( + "makeRevolution", + &Module::makeRevolution, + "makeRevolution(Curve or Edge,[vmin,vmax,angle,pnt,dir,shapetype]) -- Make a revolved " + "shape\n" "by rotating the curve or a portion of it around an axis given by (pnt,dir).\n" "By default vmin/vmax=bounds of the curve, angle=360, pnt=Vector(0,0,0),\n" "dir=Vector(0,0,1) and shapetype=Part.Solid" ); - add_keyword_method("makeRuledSurface",&Module::makeRuledSurface, + add_keyword_method( + "makeRuledSurface", + &Module::makeRuledSurface, "makeRuledSurface(Edge|Wire,Edge|Wire) -- Make a ruled surface\n" "Create a ruled surface out of two edges or wires. If wires are used then" "these must have the same number of edges." ); - add_keyword_method("makeShellFromWires",&Module::makeShellFromWires, + add_keyword_method( + "makeShellFromWires", + &Module::makeShellFromWires, "makeShellFromWires(Wires) -- Make a shell from wires.\n" "The wires must have the same number of edges." ); - add_keyword_method("makeLoft",&Module::makeLoft, - "makeLoft(list of wires,[solid=False,ruled=False,closed=False,maxDegree=5]) -- Create a loft shape." + add_keyword_method( + "makeLoft", + &Module::makeLoft, + "makeLoft(list of wires,[solid=False,ruled=False,closed=False,maxDegree=5]) -- Create " + "a loft shape." ); - add_varargs_method("makeTube",&Module::makeTube, + add_varargs_method( + "makeTube", + &Module::makeTube, "makeTube(edge,radius,[continuity,max degree,max segments]) -- Create a tube.\n" "continuity is a string which must be 'C0','C1','C2','C3','CN','G1' or 'G1'," ); - add_varargs_method("makeSweepSurface",&Module::makeSweepSurface, + add_varargs_method( + "makeSweepSurface", + &Module::makeSweepSurface, "makeSweepSurface(edge(path),edge(profile),[float]) -- Create a profile along a path." ); - add_varargs_method("makeWireString",&Module::makeWireString, - "makeWireString(string,fontdir,fontfile,height,[track]) -- Make list of wires in the form of a string's characters." + add_varargs_method( + "makeWireString", + &Module::makeWireString, + "makeWireString(string,fontdir,fontfile,height,[track]) -- Make list of wires in the " + "form of a string's characters." ); - add_varargs_method("makeSplitShape",&Module::makeSplitShape, - "makeSplitShape(shape, list of shape pairs,[check Interior=True]) -> two lists of shapes.\n" + add_varargs_method( + "makeSplitShape", + &Module::makeSplitShape, + "makeSplitShape(shape, list of shape pairs,[check Interior=True]) -> two lists of " + "shapes.\n" "The following shape pairs are supported:\n" "* Wire, Face\n" "* Edge, Face\n" @@ -574,19 +690,32 @@ public: "Part.show(r[0][0])\n" "Part.show(r[1][0])\n" ); - add_varargs_method("exportUnits",&Module::exportUnits, - "exportUnits([string=MM|M|INCH|FT|MI|KM|MIL|UM|CM|UIN]) -- Set units for exporting STEP/IGES files and returns the units." + add_varargs_method( + "exportUnits", + &Module::exportUnits, + "exportUnits([string=MM|M|INCH|FT|MI|KM|MIL|UM|CM|UIN]) -- Set units for exporting " + "STEP/IGES files and returns the units." ); - add_varargs_method("setStaticValue",&Module::setStaticValue, - "setStaticValue(string,string|int|float) -- Set a name to a value The value can be a string, int or float." + add_varargs_method( + "setStaticValue", + &Module::setStaticValue, + "setStaticValue(string,string|int|float) -- Set a name to a value The value can be a " + "string, int or float." ); - add_varargs_method("cast_to_shape",&Module::cast_to_shape, + add_varargs_method( + "cast_to_shape", + &Module::cast_to_shape, "cast_to_shape(shape) -- Cast to the actual shape type" ); - add_varargs_method("getSortedClusters",&Module::getSortedClusters, - "getSortedClusters(list of edges) -- Helper method to sort and cluster a variety of edges" + add_varargs_method( + "getSortedClusters", + &Module::getSortedClusters, + "getSortedClusters(list of edges) -- Helper method to sort and cluster a variety of " + "edges" ); - add_varargs_method("__sortEdges__",&Module::sortEdges, + add_varargs_method( + "__sortEdges__", + &Module::sortEdges, "__sortEdges__(list of edges) -- list of edges\n" "Helper method to sort an unsorted list of edges so that afterwards\n" "the start and end vertex of two consecutive edges are geometrically coincident.\n" @@ -594,47 +723,67 @@ public: "connected edges which means that the output list can be smaller than the input list.\n" "The sorted list can be used to create a Wire." ); - add_varargs_method("sortEdges",&Module::sortEdges2, + add_varargs_method( + "sortEdges", + &Module::sortEdges2, "sortEdges(list of edges, [tol3d]) -- list of lists of edges\n" - "It does basically the same as __sortEdges__ but sorts all input edges and thus returns\n" + "It does basically the same as __sortEdges__ but sorts all input edges and thus " + "returns\n" "a list of lists of edges\n" "optional 3D tolerance defaults to Precision::Confusion" ); - add_varargs_method("__toPythonOCC__",&Module::toPythonOCC, - "__toPythonOCC__(shape) -- Helper method to convert an internal shape to pythonocc shape" + add_varargs_method( + "__toPythonOCC__", + &Module::toPythonOCC, + "__toPythonOCC__(shape) -- Helper method to convert an internal shape to pythonocc " + "shape" ); - add_varargs_method("__fromPythonOCC__",&Module::fromPythonOCC, - "__fromPythonOCC__(occ) -- Helper method to convert a pythonocc shape to an internal shape" + add_varargs_method( + "__fromPythonOCC__", + &Module::fromPythonOCC, + "__fromPythonOCC__(occ) -- Helper method to convert a pythonocc shape to an internal " + "shape" ); - add_varargs_method("clearShapeCache",&Module::clearShapeCache, + add_varargs_method( + "clearShapeCache", + &Module::clearShapeCache, "clearShapeCache() -- Clears internal shape cache" ); - add_keyword_method("getShape",&Module::getShape, + add_keyword_method( + "getShape", + &Module::getShape, "getShape(obj,subname=None,mat=None,needSubElement=False,transform=True,retType=0):\n" "Obtain the TopoShape of a given object with SubName reference\n\n" "* obj: the input object\n" "* subname: dot separated sub-object reference\n" "* mat: the current transformation matrix\n" - "* needSubElement: if False, ignore the sub-element (e.g. Face1, Edge1) reference in 'subname'\n" - "* transform: if False, then skip obj's transformation. Use this if mat already include obj's\n" + "* needSubElement: if False, ignore the sub-element (e.g. Face1, Edge1) reference in " + "'subname'\n" + "* transform: if False, then skip obj's transformation. Use this if mat already " + "include obj's\n" " transformation matrix\n" "* retType: 0: return TopoShape,\n" - " 1: return (shape,mat,subObj), where subObj is the object referenced in 'subname',\n" + " 1: return (shape,mat,subObj), where subObj is the object referenced in " + "'subname',\n" " and 'mat' is the accumulated transformation matrix of that sub-object.\n" " 2: same as 1, but make sure 'subObj' is resolved if it is a link.\n" "* refine: refine the returned shape" ); - add_varargs_method("splitSubname",&Module::splitSubname, + add_varargs_method( + "splitSubname", + &Module::splitSubname, "splitSubname(subname) -> list(sub,mapped,subElement)\n" "Split the given subname into a list\n\n" "sub: subname without any sub-element reference\n" "mapped: mapped element name, or '' if none\n" "subElement: old style element name, or '' if none" ); - add_varargs_method("joinSubname",&Module::joinSubname, + add_varargs_method( + "joinSubname", + &Module::joinSubname, "joinSubname(sub,mapped,subElement) -> subname\n" ); - initialize("This is a module working with shapes."); // register with Python + initialize("This is a module working with shapes."); // register with Python PyModule_AddObject(m_module, "BRepFeat", brepFeat.module().ptr()); PyModule_AddObject(m_module, "BRepOffsetAPI", brepOffsetApi.module().ptr()); @@ -647,23 +796,26 @@ public: } private: - Py::Object invoke_method_keyword( void *method_def, - const Py::Tuple &args, const Py::Dict &keywords ) override + Py::Object invoke_method_keyword(void* method_def, const Py::Tuple& args, const Py::Dict& keywords) override { try { return Py::ExtensionModule::invoke_method_keyword(method_def, args, keywords); } - catch (const Standard_Failure &e) { + catch (const Standard_Failure& e) { std::string str; Standard_CString msg = e.GetMessageString(); str += typeid(e).name(); str += " "; - if (msg) {str += msg;} - else {str += "No OCCT Exception Message";} + if (msg) { + str += msg; + } + else { + str += "No OCCT Exception Message"; + } Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } - catch (const Base::Exception &e) { + catch (const Base::Exception& e) { std::string str; str += "FreeCAD exception thrown ("; str += e.what(); @@ -671,7 +823,7 @@ private: e.reportException(); throw Py::RuntimeError(str); } - catch (const std::exception &e) { + catch (const std::exception& e) { std::string str; str += "C++ exception thrown ("; str += e.what(); @@ -681,22 +833,26 @@ private: } } - Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override + Py::Object invoke_method_varargs(void* method_def, const Py::Tuple& args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); } - catch (const Standard_Failure &e) { + catch (const Standard_Failure& e) { std::string str; Standard_CString msg = e.GetMessageString(); str += typeid(e).name(); str += " "; - if (msg) {str += msg;} - else {str += "No OCCT Exception Message";} + if (msg) { + str += msg; + } + else { + str += "No OCCT Exception Message"; + } Base::Console().error("%s\n", str.c_str()); throw Py::Exception(Part::PartExceptionOCCError, str); } - catch (const Base::Exception &e) { + catch (const Base::Exception& e) { std::string str; str += "FreeCAD exception thrown ("; str += e.what(); @@ -704,7 +860,7 @@ private: e.reportException(); throw Py::RuntimeError(str); } - catch (const std::exception &e) { + catch (const std::exception& e) { std::string str; str += "C++ exception thrown ("; str += e.what(); @@ -717,27 +873,29 @@ private: Py::Object open(const Py::Tuple& args) { char* Name; - if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args.ptr(), "et", "utf-8", &Name)) { throw Py::Exception(); + } std::string EncodedName = std::string(Name); PyMem_Free(Name); Base::FileInfo file(EncodedName.c_str()); // extract ending - if (file.extension().empty()) + if (file.extension().empty()) { throw Py::RuntimeError("No file extension"); + } if (file.hasExtension({"stp", "step"})) { // create new document and add Import feature - App::Document *pcDoc = App::GetApplication().newDocument(); - ImportStepParts(pcDoc,EncodedName.c_str()); + App::Document* pcDoc = App::GetApplication().newDocument(); + ImportStepParts(pcDoc, EncodedName.c_str()); pcDoc->recompute(); } else if (file.hasExtension({"igs", "iges"})) { - App::Document *pcDoc = App::GetApplication().newDocument(); - ImportIgesParts(pcDoc,EncodedName.c_str()); + App::Document* pcDoc = App::GetApplication().newDocument(); + ImportIgesParts(pcDoc, EncodedName.c_str()); pcDoc->recompute(); } else { @@ -745,9 +903,10 @@ private: shape.read(EncodedName.c_str()); // create new document set loaded shape - App::Document *pcDoc = App::GetApplication().newDocument(file.fileNamePure().c_str()); - Part::Feature *object = static_cast(pcDoc->addObject - ("Part::Feature",file.fileNamePure().c_str())); + App::Document* pcDoc = App::GetApplication().newDocument(file.fileNamePure().c_str()); + Part::Feature* object = static_cast( + pcDoc->addObject("Part::Feature", file.fileNamePure().c_str()) + ); object->Shape.setValue(shape); pcDoc->recompute(); } @@ -758,31 +917,33 @@ private: { char* Name; const char* DocName; - if (!PyArg_ParseTuple(args.ptr(), "ets","utf-8",&Name,&DocName)) + if (!PyArg_ParseTuple(args.ptr(), "ets", "utf-8", &Name, &DocName)) { throw Py::Exception(); + } std::string EncodedName = std::string(Name); PyMem_Free(Name); - //Base::Console().log("Insert in Part with %s",Name); + // Base::Console().log("Insert in Part with %s",Name); Base::FileInfo file(EncodedName.c_str()); // extract ending - if (file.extension().empty()) + if (file.extension().empty()) { throw Py::RuntimeError("No file extension"); + } - App::Document *pcDoc = App::GetApplication().getDocument(DocName); + App::Document* pcDoc = App::GetApplication().getDocument(DocName); if (!pcDoc) { pcDoc = App::GetApplication().newDocument(DocName); } if (file.hasExtension({"stp", "step"})) { - ImportStepParts(pcDoc,EncodedName.c_str()); + ImportStepParts(pcDoc, EncodedName.c_str()); pcDoc->recompute(); } else if (file.hasExtension({"igs", "iges"})) { - ImportIgesParts(pcDoc,EncodedName.c_str()); + ImportIgesParts(pcDoc, EncodedName.c_str()); pcDoc->recompute(); } else { @@ -790,8 +951,9 @@ private: TopoShape shape; shape.read(EncodedName.c_str()); - Part::Feature *object = static_cast(pcDoc->addObject - ("Part::Feature",file.fileNamePure().c_str())); + Part::Feature* object = static_cast( + pcDoc->addObject("Part::Feature", file.fileNamePure().c_str()) + ); object->Shape.setValue(shape); pcDoc->recompute(); } @@ -802,8 +964,9 @@ private: { PyObject* object; char* Name; - if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name)) + if (!PyArg_ParseTuple(args.ptr(), "Oet", &object, "utf-8", &Name)) { throw Py::Exception(); + } std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -816,15 +979,20 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); if (obj->isDerivedFrom()) { Part::Feature* part = static_cast(obj); const TopoDS_Shape& shape = part->Shape.getValue(); - if (!shape.IsNull()) + if (!shape.IsNull()) { builder.Add(comp, shape); + } } else { - Base::Console().message("'%s' is not a shape, export will be ignored.\n", obj->Label.getValue()); + Base::Console().message( + "'%s' is not a shape, export will be ignored.\n", + obj->Label.getValue() + ); } } } @@ -837,8 +1005,9 @@ private: Py::Object read(const Py::Tuple& args) { char* Name; - if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args.ptr(), "et", "utf-8", &Name)) { throw Py::Exception(); + } std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -849,26 +1018,31 @@ private: } Py::Object show(const Py::Tuple& args) { - PyObject *pcObj = nullptr; - const char *name = "Shape"; - if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(TopoShapePy::Type), &pcObj, &name)) + PyObject* pcObj = nullptr; + const char* name = "Shape"; + if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(TopoShapePy::Type), &pcObj, &name)) { throw Py::Exception(); + } - App::Document *pcDoc = App::GetApplication().getActiveDocument(); - if (!pcDoc) + App::Document* pcDoc = App::GetApplication().getActiveDocument(); + if (!pcDoc) { pcDoc = App::GetApplication().newDocument(); + } TopoShape shape; - if (PyObject_TypeCheck(pcObj, &TopoShapePy::Type)) - shape = *static_cast(pcObj)->getTopoShapePtr(); - else if (PyObject_TypeCheck(pcObj, &GeometryPy::Type)) - shape = static_cast(pcObj)->getGeometryPtr()->toShape(); + if (PyObject_TypeCheck(pcObj, &TopoShapePy::Type)) { + shape = *static_cast(pcObj)->getTopoShapePtr(); + } + else if (PyObject_TypeCheck(pcObj, &GeometryPy::Type)) { + shape = static_cast(pcObj)->getGeometryPtr()->toShape(); + } else if (PyObject_TypeCheck(pcObj, &App::DocumentObjectPy::Type)) { - auto obj = static_cast(pcObj)->getDocumentObjectPtr(); + auto obj = static_cast(pcObj)->getDocumentObjectPtr(); shape = Feature::getTopoShape(obj, ShapeOption::ResolveLink | ShapeOption::Transform); - } else { + } + else { throw Py::TypeError("Expects argument of type DocumentObject, Shape, or Geometry"); } - Part::Feature *pcFeature = pcDoc->addObject(name); + Part::Feature* pcFeature = pcDoc->addObject(name); // copy the data pcFeature->Shape.setValue(shape); pcFeature->purgeTouched(); @@ -876,10 +1050,11 @@ private: } Py::Object getFacets(const Py::Tuple& args) { - PyObject *shape; + PyObject* shape; Py::List list; - if (!PyArg_ParseTuple(args.ptr(), "O", &shape)) + if (!PyArg_ParseTuple(args.ptr(), "O", &shape)) { throw Py::Exception(); + } auto theShape = static_cast(shape)->getTopoShapePtr()->getShape(); for (TopExp_Explorer ex(theShape, TopAbs_FACE); ex.More(); ex.Next()) { TopoDS_Face currentFace = TopoDS::Face(ex.Current()); @@ -888,7 +1063,7 @@ private: std::vector facets; if (Tools::getTriangulation(currentFace, points, facets)) { for (const auto& it : facets) { - Standard_Integer n1,n2,n3; + Standard_Integer n1, n2, n3; it.Get(n1, n2, n3); gp_Pnt p1 = points[n1]; @@ -897,9 +1072,24 @@ private: // TODO: verify if tolerance should be hard coded if (!p1.IsEqual(p2, 0.01) && !p2.IsEqual(p3, 0.01) && !p3.IsEqual(p1, 0.01)) { - PyObject *t1 = PyTuple_Pack(3, PyFloat_FromDouble(p1.X()), PyFloat_FromDouble(p1.Y()), PyFloat_FromDouble(p1.Z())); - PyObject *t2 = PyTuple_Pack(3, PyFloat_FromDouble(p2.X()), PyFloat_FromDouble(p2.Y()), PyFloat_FromDouble(p2.Z())); - PyObject *t3 = PyTuple_Pack(3, PyFloat_FromDouble(p3.X()), PyFloat_FromDouble(p3.Y()), PyFloat_FromDouble(p3.Z())); + PyObject* t1 = PyTuple_Pack( + 3, + PyFloat_FromDouble(p1.X()), + PyFloat_FromDouble(p1.Y()), + PyFloat_FromDouble(p1.Z()) + ); + PyObject* t2 = PyTuple_Pack( + 3, + PyFloat_FromDouble(p2.X()), + PyFloat_FromDouble(p2.Y()), + PyFloat_FromDouble(p2.Z()) + ); + PyObject* t3 = PyTuple_Pack( + 3, + PyFloat_FromDouble(p3.X()), + PyFloat_FromDouble(p3.Y()), + PyFloat_FromDouble(p3.Z()) + ); list.append(Py::asObject(PyTuple_Pack(3, t1, t2, t3))); } } @@ -907,25 +1097,27 @@ private: } return list; } - Py::Object makeCompound(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeCompound(const Py::Tuple& args, const Py::Dict& kwds) { PyObject* pcObj; PyObject* force = Py_True; TopoShape::SingleShapeCompoundCreationPolicy policy; // = TopoShape::SingleShapeCompoundCreationPolicy::forceCompound; PyObject* module = PyImport_ImportModule("PartEnums"); - PyObject* policyEnum = - PyObject_GetAttrString(module, (char*)"SingleShapeCompoundCreationPolicy"); + PyObject* policyEnum + = PyObject_GetAttrString(module, (char*)"SingleShapeCompoundCreationPolicy"); const char* op = nullptr; const std::array kwd_list = {"shapes", "force", "op", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|O!s", - kwd_list, - &pcObj, - policyEnum, - &force, - &op)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O|O!s", + kwd_list, + &pcObj, + policyEnum, + &force, + &op + )) { throw Py::Exception(); } @@ -934,64 +1126,67 @@ private: return shape2pyshape(Part::TopoShape().makeElementCompound(getPyShapes(pcObj), op, policy)); } - Py::Object makeShell(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeShell(const Py::Tuple& args, const Py::Dict& kwds) { PyObject* obj; const char* op = nullptr; const std::array kwd_list = {"shapes", "op", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|s", - kwd_list, - &obj, - &op)) { + if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O|s", kwd_list, &obj, &op)) { throw Py::Exception(); } return shape2pyshape( - Part::TopoShape().makeElementBoolean(Part::OpCodes::Shell, getPyShapes(obj), op)); + Part::TopoShape().makeElementBoolean(Part::OpCodes::Shell, getPyShapes(obj), op) + ); } - Py::Object makeFace(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeFace(const Py::Tuple& args, const Py::Dict& kwds) { PyObject* obj; const char* className = nullptr; const char* op = nullptr; const std::array kwd_list = {"shapes", "class_name", "op", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|ss", - kwd_list, - &obj, - &className, - &op)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O|ss", + kwd_list, + &obj, + &className, + &op + )) { throw Py::Exception(); } return shape2pyshape(TopoShape().makeElementFace(getPyShapes(obj), op, className)); } template - void parseSequence(PyObject *pyObj, const char *err, F f) + void parseSequence(PyObject* pyObj, const char* err, F f) { if (pyObj != Py_None) { - if (!PySequence_Check(pyObj)) + if (!PySequence_Check(pyObj)) { throw Py::TypeError(err); + } Py::Sequence seq(pyObj); for (Py::Sequence::iterator it = seq.begin(); it != seq.end(); ++it) { - if (!PySequence_Check((*it).ptr())) + if (!PySequence_Check((*it).ptr())) { throw Py::TypeError(err); + } Py::Sequence tuple((*it).ptr()); - if (tuple.size() != 2) + if (tuple.size() != 2) { throw Py::TypeError(err); + } auto iter = tuple.begin(); - if (!PyObject_TypeCheck((*iter).ptr(), &(Part::TopoShapePy::Type))) + if (!PyObject_TypeCheck((*iter).ptr(), &(Part::TopoShapePy::Type))) { throw Py::TypeError(err); - const TopoDS_Shape& sh = static_cast((*iter).ptr())->getTopoShapePtr()->getShape(); + } + const TopoDS_Shape& sh + = static_cast((*iter).ptr())->getTopoShapePtr()->getShape(); f(sh, (*iter).ptr(), err); } } } - Py::Object makeFilledSurface(const Py::Tuple &args, const Py::Dict &kwds) + Py::Object makeFilledSurface(const Py::Tuple& args, const Py::Dict& kwds) { TopoShape::BRepFillingParams params; PyObject* obj = nullptr; @@ -1000,40 +1195,44 @@ private: PyObject* orders = Py_None; PyObject* anisotropy = params.anisotropy ? Py_True : Py_False; const char* op = nullptr; - const std::array kwd_list = {"shapes", - "surface", - "supports", - "orders", - "degree", - "ptsOnCurve", - "numIter", - "anisotropy", - "tol2d", - "tol3d", - "tolG1", - "tolG2", - "maxDegree", - "maxSegments", - "op", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|O!OOIIIOddddIIs", - kwd_list, - &obj, - &pySurface, - &orders, - ¶ms.degree, - ¶ms.ptsoncurve, - ¶ms.numiter, - &anisotropy, - ¶ms.tol2d, - ¶ms.tol3d, - ¶ms.tolG1, - ¶ms.tolG2, - ¶ms.maxdeg, - ¶ms.maxseg, - &op)) { + const std::array kwd_list = { + "shapes", + "surface", + "supports", + "orders", + "degree", + "ptsOnCurve", + "numIter", + "anisotropy", + "tol2d", + "tol3d", + "tolG1", + "tolG2", + "maxDegree", + "maxSegments", + "op", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O|O!OOIIIOddddIIs", + kwd_list, + &obj, + &pySurface, + &orders, + ¶ms.degree, + ¶ms.ptsoncurve, + ¶ms.numiter, + &anisotropy, + ¶ms.tol2d, + ¶ms.tol3d, + ¶ms.tolG1, + ¶ms.tolG2, + ¶ms.maxdeg, + ¶ms.maxseg, + &op + )) { throw Py::Exception(); } params.anisotropy = PyObject_IsTrue(anisotropy); @@ -1041,34 +1240,38 @@ private: if (pySurface != Py_None) { surface = *static_cast(pySurface)->getTopoShapePtr(); } - parseSequence(supports, - "Expects 'supports' to be a sequence of tuple(shape, shape)", - [&](const TopoDS_Shape& s, PyObject* value, const char* err) { - if (!PyObject_TypeCheck(value, &(Part::TopoShapePy::Type))) { - throw Py::TypeError(err); - } - params.supports[s] = - static_cast(value)->getTopoShapePtr()->getShape(); - }); - parseSequence(orders, - "Expects 'orders' to be a sequence of tuple(shape, PartEnums.Shape)", - [&](const TopoDS_Shape& s, PyObject* value, const char* err) { - if (!PyLong_Check(value)) { - throw Py::ValueError(err); - } - int order = Py::Long(value); - params.orders[s] = static_cast(order); - return; - }); + parseSequence( + supports, + "Expects 'supports' to be a sequence of tuple(shape, shape)", + [&](const TopoDS_Shape& s, PyObject* value, const char* err) { + if (!PyObject_TypeCheck(value, &(Part::TopoShapePy::Type))) { + throw Py::TypeError(err); + } + params.supports[s] = static_cast(value)->getTopoShapePtr()->getShape(); + } + ); + parseSequence( + orders, + "Expects 'orders' to be a sequence of tuple(shape, PartEnums.Shape)", + [&](const TopoDS_Shape& s, PyObject* value, const char* err) { + if (!PyLong_Check(value)) { + throw Py::ValueError(err); + } + int order = Py::Long(value); + params.orders[s] = static_cast(order); + return; + } + ); auto shapes = getPyShapes(obj); if (shapes.empty()) { throw Py::ValueError("No input shape"); } return shape2pyshape( - TopoShape(0, shapes.front().Hasher).makeElementFilledFace(shapes, params, op)); + TopoShape(0, shapes.front().Hasher).makeElementFilledFace(shapes, params, op) + ); } - Py::Object makeFilledFace(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeFilledFace(const Py::Tuple& args, const Py::Dict& kwds) { TopoShape::BRepFillingParams params; PyObject* obj = nullptr; @@ -1077,40 +1280,44 @@ private: PyObject* orders = Py_None; PyObject* anisotropy = params.anisotropy ? Py_True : Py_False; const char* op = nullptr; - const std::array kwd_list = {"shapes", - "surface", - "supports", - "orders", - "degree", - "ptsOnCurve", - "numIter", - "anisotropy", - "tol2d", - "tol3d", - "tolG1", - "tolG2", - "maxDegree", - "maxSegments", - "op", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|O!OOIIIOddddIIs", - kwd_list, - &obj, - &pySurface, - &orders, - ¶ms.degree, - ¶ms.ptsoncurve, - ¶ms.numiter, - &anisotropy, - ¶ms.tol2d, - ¶ms.tol3d, - ¶ms.tolG1, - ¶ms.tolG2, - ¶ms.maxdeg, - ¶ms.maxseg, - &op)) { + const std::array kwd_list = { + "shapes", + "surface", + "supports", + "orders", + "degree", + "ptsOnCurve", + "numIter", + "anisotropy", + "tol2d", + "tol3d", + "tolG1", + "tolG2", + "maxDegree", + "maxSegments", + "op", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O|O!OOIIIOddddIIs", + kwd_list, + &obj, + &pySurface, + &orders, + ¶ms.degree, + ¶ms.ptsoncurve, + ¶ms.numiter, + &anisotropy, + ¶ms.tol2d, + ¶ms.tol3d, + ¶ms.tolG1, + ¶ms.tolG2, + ¶ms.maxdeg, + ¶ms.maxseg, + &op + )) { throw Py::Exception(); } params.anisotropy = PyObject_IsTrue(anisotropy); @@ -1118,60 +1325,76 @@ private: if (pySurface != Py_None) { surface = *static_cast(pySurface)->getTopoShapePtr(); } - parseSequence(supports, - "Expects 'supports' to be a sequence of tuple(shape, shape)", - [&](const TopoDS_Shape& s, PyObject* value, const char* err) { - if (!PyObject_TypeCheck(value, &(Part::TopoShapePy::Type))) { - throw Py::TypeError(err); - } - params.supports[s] = - static_cast(value)->getTopoShapePtr()->getShape(); - }); - parseSequence(orders, - "Expects 'orders' to be a sequence of tuple(shape, PartEnums.Shape)", - [&](const TopoDS_Shape& s, PyObject* value, const char* err) { - if (!PyLong_Check(value)) { - throw Py::ValueError(err); - } - int order = Py::Long(value); - params.orders[s] = static_cast(order); - return; - }); + parseSequence( + supports, + "Expects 'supports' to be a sequence of tuple(shape, shape)", + [&](const TopoDS_Shape& s, PyObject* value, const char* err) { + if (!PyObject_TypeCheck(value, &(Part::TopoShapePy::Type))) { + throw Py::TypeError(err); + } + params.supports[s] = static_cast(value)->getTopoShapePtr()->getShape(); + } + ); + parseSequence( + orders, + "Expects 'orders' to be a sequence of tuple(shape, PartEnums.Shape)", + [&](const TopoDS_Shape& s, PyObject* value, const char* err) { + if (!PyLong_Check(value)) { + throw Py::ValueError(err); + } + int order = Py::Long(value); + params.orders[s] = static_cast(order); + return; + } + ); auto shapes = getPyShapes(obj); if (shapes.empty()) { throw Py::ValueError("No input shape"); } return shape2pyshape( - TopoShape(0, shapes.front().Hasher).makeElementFilledFace(shapes, params, op)); + TopoShape(0, shapes.front().Hasher).makeElementFilledFace(shapes, params, op) + ); } - Py::Object makeSolid(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeSolid(const Py::Tuple& args, const Py::Dict& kwds) { PyObject* obj; const char* op = nullptr; const std::array kwd_list = {"shape", "op", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O!|s", - kwd_list, - &(TopoShapePy::Type), - &obj, - &op)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O!|s", + kwd_list, + &(TopoShapePy::Type), + &obj, + &op + )) { throw Py::Exception(); } return shape2pyshape( - TopoShape().makeElementSolid(*static_cast(obj)->getTopoShapePtr(), op)); + TopoShape().makeElementSolid(*static_cast(obj)->getTopoShapePtr(), op) + ); } Py::Object makePlane(const Py::Tuple& args) { double length, width; - PyObject *pPnt=nullptr, *pDirZ=nullptr, *pDirX=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "dd|O!O!O!", &length, &width, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDirZ, - &(Base::VectorPy::Type), &pDirX)) + PyObject *pPnt = nullptr, *pDirZ = nullptr, *pDirX = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "dd|O!O!O!", + &length, + &width, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDirZ, + &(Base::VectorPy::Type), + &pDirX + )) { throw Py::Exception(); + } if (length < Precision::Confusion()) { throw Py::ValueError("length of plane too small"); @@ -1181,8 +1404,8 @@ private: } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1202,7 +1425,7 @@ private: aPlane = new Geom_Plane(p, d); } - BRepBuilderAPI_MakeFace Face(aPlane, 0.0, length, 0.0, width, Precision::Confusion() ); + BRepBuilderAPI_MakeFace Face(aPlane, 0.0, length, 0.0, width, Precision::Confusion()); return Py::asObject(new TopoShapeFacePy(new TopoShape((Face.Face())))); } catch (Standard_DomainError&) { @@ -1215,12 +1438,20 @@ private: Py::Object makeBox(const Py::Tuple& args) { double length, width, height; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "ddd|O!O!", - &length, &width, &height, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir)) + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "ddd|O!O!", + &length, + &width, + &height, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir + )) { throw Py::Exception(); + } if (length < Precision::Confusion()) { throw Py::ValueError("length of box too small"); @@ -1233,8 +1464,8 @@ private: } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1243,7 +1474,7 @@ private: Base::Vector3d vec = static_cast(pDir)->value(); d.SetCoord(vec.x, vec.y, vec.z); } - BRepPrimAPI_MakeBox mkBox(gp_Ax2(p,d), length, width, height); + BRepPrimAPI_MakeBox mkBox(gp_Ax2(p, d), length, width, height); TopoDS_Shape ResultShape = mkBox.Shape(); return Py::asObject(new TopoShapeSolidPy(new TopoShape(ResultShape))); } @@ -1254,17 +1485,33 @@ private: Py::Object makeWedge(const Py::Tuple& args) { double xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "dddddddddd|O!O!", - &xmin, &ymin, &zmin, &z2min, &x2min, &xmax, &ymax, &zmax, &z2max, &x2max, - &(Base::VectorPy::Type), &pPnt, &(Base::VectorPy::Type), &pDir)) + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "dddddddddd|O!O!", + &xmin, + &ymin, + &zmin, + &z2min, + &x2min, + &xmax, + &ymax, + &zmax, + &z2max, + &x2max, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir + )) { throw Py::Exception(); + } - double dx = xmax-xmin; - double dy = ymax-ymin; - double dz = zmax-zmin; - double dz2 = z2max-z2min; - double dx2 = x2max-x2min; + double dx = xmax - xmin; + double dy = ymax - ymin; + double dz = zmax - zmin; + double dz2 = z2max - z2min; + double dx2 = x2max - x2min; if (dx < Precision::Confusion()) { throw Py::ValueError("delta x of wedge too small"); } @@ -1282,8 +1529,8 @@ private: } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1292,7 +1539,8 @@ private: Base::Vector3d vec = static_cast(pDir)->value(); d.SetCoord(vec.x, vec.y, vec.z); } - BRepPrim_Wedge mkWedge(gp_Ax2(p,d), xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max); + BRepPrim_Wedge + mkWedge(gp_Ax2(p, d), xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max); BRepBuilderAPI_MakeSolid mkSolid; mkSolid.Add(mkWedge.Shell()); return Py::asObject(new TopoShapeSolidPy(new TopoShape(mkSolid.Solid()))); @@ -1304,8 +1552,9 @@ private: Py::Object makeLine(const Py::Tuple& args) { PyObject *obj1, *obj2; - if (!PyArg_ParseTuple(args.ptr(), "OO", &obj1, &obj2)) + if (!PyArg_ParseTuple(args.ptr(), "OO", &obj1, &obj2)) { throw Py::Exception(); + } Base::Vector3d pnt1, pnt2; if (PyObject_TypeCheck(obj1, &(Base::VectorPy::Type))) { @@ -1328,32 +1577,30 @@ private: } // Create directly the underlying line geometry - BRepBuilderAPI_MakeEdge makeEdge(gp_Pnt(pnt1.x, pnt1.y, pnt1.z), - gp_Pnt(pnt2.x, pnt2.y, pnt2.z)); + BRepBuilderAPI_MakeEdge makeEdge(gp_Pnt(pnt1.x, pnt1.y, pnt1.z), gp_Pnt(pnt2.x, pnt2.y, pnt2.z)); - const char *error=nullptr; - switch (makeEdge.Error()) - { - case BRepBuilderAPI_EdgeDone: - break; // ok - case BRepBuilderAPI_PointProjectionFailed: - error = "Point projection failed"; - break; - case BRepBuilderAPI_ParameterOutOfRange: - error = "Parameter out of range"; - break; - case BRepBuilderAPI_DifferentPointsOnClosedCurve: - error = "Different points on closed curve"; - break; - case BRepBuilderAPI_PointWithInfiniteParameter: - error = "Point with infinite parameter"; - break; - case BRepBuilderAPI_DifferentsPointAndParameter: - error = "Different point and parameter"; - break; - case BRepBuilderAPI_LineThroughIdenticPoints: - error = "Line through identical points"; - break; + const char* error = nullptr; + switch (makeEdge.Error()) { + case BRepBuilderAPI_EdgeDone: + break; // ok + case BRepBuilderAPI_PointProjectionFailed: + error = "Point projection failed"; + break; + case BRepBuilderAPI_ParameterOutOfRange: + error = "Parameter out of range"; + break; + case BRepBuilderAPI_DifferentPointsOnClosedCurve: + error = "Different points on closed curve"; + break; + case BRepBuilderAPI_PointWithInfiniteParameter: + error = "Point with infinite parameter"; + break; + case BRepBuilderAPI_DifferentsPointAndParameter: + error = "Different point and parameter"; + break; + case BRepBuilderAPI_LineThroughIdenticPoints: + error = "Line through identical points"; + break; } // Error if (error) { @@ -1365,10 +1612,11 @@ private: } Py::Object makePolygon(const Py::Tuple& args) { - PyObject *pcObj; - PyObject *pclosed=Py_False; - if (!PyArg_ParseTuple(args.ptr(), "O|O!", &pcObj, &(PyBool_Type), &pclosed)) + PyObject* pcObj; + PyObject* pclosed = Py_False; + if (!PyArg_ParseTuple(args.ptr(), "O|O!", &pcObj, &(PyBool_Type), &pclosed)) { throw Py::Exception(); + } BRepBuilderAPI_MakePolygon mkPoly; try { @@ -1376,16 +1624,19 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast((*it).ptr())->value(); - mkPoly.Add(gp_Pnt(v.x,v.y,v.z)); + mkPoly.Add(gp_Pnt(v.x, v.y, v.z)); } else if (PyObject_TypeCheck((*it).ptr(), &PyTuple_Type)) { Base::Vector3d v = Base::getVectorFromTuple((*it).ptr()); - mkPoly.Add(gp_Pnt(v.x,v.y,v.z)); + mkPoly.Add(gp_Pnt(v.x, v.y, v.z)); } } - if (!mkPoly.IsDone()) - Standard_Failure::Raise("Cannot create polygon because less than two vertices are given"); + if (!mkPoly.IsDone()) { + Standard_Failure::Raise( + "Cannot create polygon because less than two vertices are given" + ); + } // if the polygon should be closed if (Base::asBoolean(pclosed)) { @@ -1402,18 +1653,25 @@ private: } Py::Object makeCircle(const Py::Tuple& args) { - double radius, angle1=0.0, angle2=360; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "d|O!O!dd", - &radius, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &angle1, &angle2)) + double radius, angle1 = 0.0, angle2 = 360; + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "d|O!O!dd", + &radius, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &angle1, + &angle2 + )) { throw Py::Exception(); + } try { - gp_Pnt loc(0,0,0); - gp_Dir dir(0,0,1); + gp_Pnt loc(0, 0, 0); + gp_Dir dir(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); loc.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1427,10 +1685,12 @@ private: circle.SetAxis(axis); circle.SetRadius(radius); - Handle(Geom_Circle) hCircle = new Geom_Circle (circle); - BRepBuilderAPI_MakeEdge aMakeEdge(hCircle, - Base::toRadians(angle1), - Base::toRadians(angle2)); + Handle(Geom_Circle) hCircle = new Geom_Circle(circle); + BRepBuilderAPI_MakeEdge aMakeEdge( + hCircle, + Base::toRadians(angle1), + Base::toRadians(angle2) + ); TopoDS_Edge edge = aMakeEdge.Edge(); return Py::asObject(new TopoShapeEdgePy(new TopoShape(edge))); } @@ -1440,18 +1700,26 @@ private: } Py::Object makeSphere(const Py::Tuple& args) { - double radius, angle1=-90, angle2=90, angle3=360; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "d|O!O!ddd", - &radius, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &angle1, &angle2, &angle3)) + double radius, angle1 = -90, angle2 = 90, angle3 = 360; + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "d|O!O!ddd", + &radius, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &angle1, + &angle2, + &angle3 + )) { throw Py::Exception(); + } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1460,10 +1728,13 @@ private: Base::Vector3d vec = static_cast(pDir)->value(); d.SetCoord(vec.x, vec.y, vec.z); } - BRepPrimAPI_MakeSphere mkSphere(gp_Ax2(p,d), radius, - Base::toRadians(angle1), - Base::toRadians(angle2), - Base::toRadians(angle3)); + BRepPrimAPI_MakeSphere mkSphere( + gp_Ax2(p, d), + radius, + Base::toRadians(angle1), + Base::toRadians(angle2), + Base::toRadians(angle3) + ); TopoDS_Shape shape = mkSphere.Shape(); return Py::asObject(new TopoShapeSolidPy(new TopoShape(shape))); } @@ -1473,18 +1744,25 @@ private: } Py::Object makeCylinder(const Py::Tuple& args) { - double radius, height, angle=360; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "dd|O!O!d", - &radius, &height, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &angle)) + double radius, height, angle = 360; + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "dd|O!O!d", + &radius, + &height, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &angle + )) { throw Py::Exception(); + } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1493,8 +1771,7 @@ private: Base::Vector3d vec = static_cast(pDir)->value(); d.SetCoord(vec.x, vec.y, vec.z); } - BRepPrimAPI_MakeCylinder mkCyl(gp_Ax2(p,d),radius, height, - Base::toRadians(angle)); + BRepPrimAPI_MakeCylinder mkCyl(gp_Ax2(p, d), radius, height, Base::toRadians(angle)); TopoDS_Shape shape = mkCyl.Shape(); return Py::asObject(new TopoShapeSolidPy(new TopoShape(shape))); } @@ -1504,18 +1781,26 @@ private: } Py::Object makeCone(const Py::Tuple& args) { - double radius1, radius2, height, angle=360; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "ddd|O!O!d", - &radius1, &radius2, &height, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &angle)) + double radius1, radius2, height, angle = 360; + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "ddd|O!O!d", + &radius1, + &radius2, + &height, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &angle + )) { throw Py::Exception(); + } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1524,8 +1809,8 @@ private: Base::Vector3d vec = static_cast(pDir)->value(); d.SetCoord(vec.x, vec.y, vec.z); } - BRepPrimAPI_MakeCone mkCone(gp_Ax2(p,d),radius1, radius2, height, - Base::toRadians(angle)); + BRepPrimAPI_MakeCone + mkCone(gp_Ax2(p, d), radius1, radius2, height, Base::toRadians(angle)); TopoDS_Shape shape = mkCone.Shape(); return Py::asObject(new TopoShapeSolidPy(new TopoShape(shape))); } @@ -1535,18 +1820,27 @@ private: } Py::Object makeTorus(const Py::Tuple& args) { - double radius1, radius2, angle1=0.0, angle2=360, angle=360; - PyObject *pPnt=nullptr, *pDir=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "dd|O!O!ddd", - &radius1, &radius2, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &angle1, &angle2, &angle)) + double radius1, radius2, angle1 = 0.0, angle2 = 360, angle = 360; + PyObject *pPnt = nullptr, *pDir = nullptr; + if (!PyArg_ParseTuple( + args.ptr(), + "dd|O!O!ddd", + &radius1, + &radius2, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &angle1, + &angle2, + &angle + )) { throw Py::Exception(); + } try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1555,10 +1849,14 @@ private: Base::Vector3d vec = static_cast(pDir)->value(); d.SetCoord(vec.x, vec.y, vec.z); } - BRepPrimAPI_MakeTorus mkTorus(gp_Ax2(p,d), radius1, radius2, - Base::toRadians(angle1), - Base::toRadians(angle2), - Base::toRadians(angle)); + BRepPrimAPI_MakeTorus mkTorus( + gp_Ax2(p, d), + radius1, + radius2, + Base::toRadians(angle1), + Base::toRadians(angle2), + Base::toRadians(angle) + ); const TopoDS_Shape& shape = mkTorus.Shape(); return Py::asObject(new TopoShapeSolidPy(new TopoShape(shape))); } @@ -1568,21 +1866,29 @@ private: } Py::Object makeHelix(const Py::Tuple& args) { - double pitch, height, radius, angle=-1.0; - PyObject *pleft=Py_False; - PyObject *pvertHeight=Py_False; - if (!PyArg_ParseTuple(args.ptr(), "ddd|dO!O!", - &pitch, &height, &radius, &angle, - &(PyBool_Type), &pleft, - &(PyBool_Type), &pvertHeight)) + double pitch, height, radius, angle = -1.0; + PyObject* pleft = Py_False; + PyObject* pvertHeight = Py_False; + if (!PyArg_ParseTuple( + args.ptr(), + "ddd|dO!O!", + &pitch, + &height, + &radius, + &angle, + &(PyBool_Type), + &pleft, + &(PyBool_Type), + &pvertHeight + )) { throw Py::Exception(); + } try { TopoShape helix; Standard_Boolean anIsLeft = Base::asBoolean(pleft); Standard_Boolean anIsVertHeight = Base::asBoolean(pvertHeight); - TopoDS_Shape wire = helix.makeHelix(pitch, height, radius, angle, - anIsLeft, anIsVertHeight); + TopoDS_Shape wire = helix.makeHelix(pitch, height, radius, angle, anIsLeft, anIsVertHeight); return Py::asObject(new TopoShapeWirePy(new TopoShape(wire))); } catch (Standard_Failure& e) { @@ -1591,10 +1897,9 @@ private: } Py::Object makeLongHelix(const Py::Tuple& args) { - double pitch, height, radius, angle=-1.0; - PyObject *pleft=Py_False; - if (!PyArg_ParseTuple(args.ptr(), "ddd|dO!", &pitch, &height, &radius, &angle, - &(PyBool_Type), &pleft)) { + double pitch, height, radius, angle = -1.0; + PyObject* pleft = Py_False; + if (!PyArg_ParseTuple(args.ptr(), "ddd|dO!", &pitch, &height, &radius, &angle, &(PyBool_Type), &pleft)) { throw Py::RuntimeError("Part.makeLongHelix fails on parms"); } @@ -1611,8 +1916,9 @@ private: Py::Object makeThread(const Py::Tuple& args) { double pitch, depth, height, radius; - if (!PyArg_ParseTuple(args.ptr(), "dddd", &pitch, &depth, &height, &radius)) + if (!PyArg_ParseTuple(args.ptr(), "dddd", &pitch, &depth, &height, &radius)) { throw Py::Exception(); + } try { TopoShape helix; @@ -1626,40 +1932,62 @@ private: Py::Object makeRevolution(const Py::Tuple& args) { constexpr double doubleMax = std::numeric_limits::max(); - double vmin = doubleMax, vmax=-doubleMax; - double angle=360; - PyObject *pPnt=nullptr, *pDir=nullptr, *pCrv; + double vmin = doubleMax, vmax = -doubleMax; + double angle = 360; + PyObject *pPnt = nullptr, *pDir = nullptr, *pCrv; Handle(Geom_Curve) curve; PyObject* defaultType = Base::getTypeAsObject(&Part::TopoShapeSolidPy::Type); PyObject* type = defaultType; do { - if (PyArg_ParseTuple(args.ptr(), "O!|dddO!O!O!", &(GeometryPy::Type), &pCrv, - &vmin, &vmax, &angle, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &(PyType_Type), &type)) { + if (PyArg_ParseTuple( + args.ptr(), + "O!|dddO!O!O!", + &(GeometryPy::Type), + &pCrv, + &vmin, + &vmax, + &angle, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &(PyType_Type), + &type + )) { GeometryPy* pcGeo = static_cast(pCrv); - curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { throw Py::Exception(PyExc_TypeError, "geometry is not a curve"); } - if (vmin == doubleMax) + if (vmin == doubleMax) { vmin = curve->FirstParameter(); + } - if (vmax == -doubleMax) + if (vmax == -doubleMax) { vmax = curve->LastParameter(); + } break; } PyErr_Clear(); - if (PyArg_ParseTuple(args.ptr(), "O!|dddO!O!O!", &(TopoShapePy::Type), &pCrv, - &vmin, &vmax, &angle, - &(Base::VectorPy::Type), &pPnt, - &(Base::VectorPy::Type), &pDir, - &(PyType_Type), &type)) { - const TopoDS_Shape& shape = static_cast(pCrv)->getTopoShapePtr()->getShape(); + if (PyArg_ParseTuple( + args.ptr(), + "O!|dddO!O!O!", + &(TopoShapePy::Type), + &pCrv, + &vmin, + &vmax, + &angle, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir, + &(PyType_Type), + &type + )) { + const TopoDS_Shape& shape + = static_cast(pCrv)->getTopoShapePtr()->getShape(); if (shape.IsNull()) { throw Py::Exception(PartExceptionOCCError, "shape is empty"); } @@ -1671,7 +1999,7 @@ private: const TopoDS_Edge& edge = TopoDS::Edge(shape); BRepAdaptor_Curve adapt(edge); - const Handle(Geom_Curve)& hCurve = adapt.Curve().Curve(); + const Handle(Geom_Curve) & hCurve = adapt.Curve().Curve(); // Apply placement of the shape to the curve TopLoc_Location loc = edge.Location(); curve = Handle(Geom_Curve)::DownCast(hCurve->Transformed(loc.Transformation())); @@ -1679,22 +2007,25 @@ private: throw Py::Exception(PartExceptionOCCError, "invalid curve in edge"); } - if (vmin == doubleMax) + if (vmin == doubleMax) { vmin = adapt.FirstParameter(); - if (vmax == -doubleMax) + } + if (vmax == -doubleMax) { vmax = adapt.LastParameter(); + } break; } // invalid arguments - throw Py::TypeError("Expected arguments are:\n" - "Curve or Edge, [float, float, float, Vector, Vector, ShapeType]"); - } - while(false); + throw Py::TypeError( + "Expected arguments are:\n" + "Curve or Edge, [float, float, float, Vector, Vector, ShapeType]" + ); + } while (false); try { - gp_Pnt p(0,0,0); - gp_Dir d(0,0,1); + gp_Pnt p(0, 0, 0); + gp_Dir d(0, 0, 1); if (pPnt) { Base::Vector3d pnt = static_cast(pPnt)->value(); p.SetCoord(pnt.x, pnt.y, pnt.z); @@ -1707,8 +2038,8 @@ private: PyObject* shellType = Base::getTypeAsObject(&Part::TopoShapeShellPy::Type); PyObject* faceType = Base::getTypeAsObject(&Part::TopoShapeFacePy::Type); - BRepPrimAPI_MakeRevolution mkRev(gp_Ax2(p,d),curve, vmin, vmax, - Base::toRadians(angle)); + BRepPrimAPI_MakeRevolution + mkRev(gp_Ax2(p, d), curve, vmin, vmax, Base::toRadians(angle)); if (type == defaultType) { TopoDS_Shape shape = mkRev.Solid(); return Py::asObject(new TopoShapeSolidPy(new TopoShape(shape))); @@ -1731,26 +2062,24 @@ private: } } - Py::Object makeRuledSurface(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeRuledSurface(const Py::Tuple& args, const Py::Dict& kwds) { const char* op = nullptr; int orientation = 0; PyObject *sh1, *sh2; - const std::array kwd_list = {"path", - "profile", - "orientation", - "op", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O!O!|is", - kwd_list, - &(TopoShapePy::Type), - &sh1, - &(TopoShapePy::Type), - &sh2, - &orientation, - &op)) { + const std::array kwd_list = {"path", "profile", "orientation", "op", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O!O!|is", + kwd_list, + &(TopoShapePy::Type), + &sh1, + &(TopoShapePy::Type), + &sh2, + &orientation, + &op + )) { throw Py::Exception(); } @@ -1760,22 +2089,18 @@ private: return shape2pyshape(TopoShape().makeElementRuledSurface(shapes, orientation, op)); } - Py::Object makeShellFromWires(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeShellFromWires(const Py::Tuple& args, const Py::Dict& kwds) { - PyObject *pylist; + PyObject* pylist; const char* op = nullptr; const std::array kwd_list = {"shape", "op", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O|s", - kwd_list, - &pylist, - &op)) { + if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O|s", kwd_list, &pylist, &op)) { throw Py::Exception(); } try { return shape2pyshape( - TopoShape().makeElementShellFromWires(getPyShapes(pylist), /*silent*/ false, op)); + TopoShape().makeElementShellFromWires(getPyShapes(pylist), /*silent*/ false, op) + ); } catch (Standard_Failure&) { throw Py::Exception(PartExceptionOCCError, "creation of shell failed"); @@ -1784,38 +2109,57 @@ private: Py::Object makeTube(const Py::Tuple& args) { - PyObject *pshape; + PyObject* pshape; double radius; - double tolerance=0.001; + double tolerance = 0.001; const char* scont = "C0"; int maxdegree = 3; int maxsegment = 30; // Path + radius - if (!PyArg_ParseTuple(args.ptr(), "O!d|sii", &(TopoShapePy::Type), &pshape, &radius, &scont, &maxdegree, &maxsegment)) + if (!PyArg_ParseTuple( + args.ptr(), + "O!d|sii", + &(TopoShapePy::Type), + &pshape, + &radius, + &scont, + &maxdegree, + &maxsegment + )) { throw Py::Exception(); + } std::string str_cont = scont; int cont; - if (str_cont == "C0") + if (str_cont == "C0") { cont = (int)GeomAbs_C0; - else if (str_cont == "C1") + } + else if (str_cont == "C1") { cont = (int)GeomAbs_C1; - else if (str_cont == "C2") + } + else if (str_cont == "C2") { cont = (int)GeomAbs_C2; - else if (str_cont == "C3") + } + else if (str_cont == "C3") { cont = (int)GeomAbs_C3; - else if (str_cont == "CN") + } + else if (str_cont == "CN") { cont = (int)GeomAbs_CN; - else if (str_cont == "G1") + } + else if (str_cont == "G1") { cont = (int)GeomAbs_G1; - else if (str_cont == "G2") + } + else if (str_cont == "G2") { cont = (int)GeomAbs_G2; - else + } + else { cont = (int)GeomAbs_C0; + } try { - const TopoDS_Shape& path_shape = static_cast(pshape)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& path_shape + = static_cast(pshape)->getTopoShapePtr()->getShape(); TopoShape myShape(path_shape); TopoDS_Shape face = myShape.makeTube(radius, tolerance, cont, maxdegree, maxsegment); return Py::asObject(new TopoShapeFacePy(new TopoShape(face))); @@ -1827,71 +2171,85 @@ private: Py::Object makeSweepSurface(const Py::Tuple& args) { PyObject *path, *profile; - double tolerance=0.001; + double tolerance = 0.001; int fillMode = 0; // Path + profile - if (!PyArg_ParseTuple(args.ptr(), "O!O!|di", &(TopoShapePy::Type), &path, - &(TopoShapePy::Type), &profile, - &tolerance, &fillMode)) + if (!PyArg_ParseTuple( + args.ptr(), + "O!O!|di", + &(TopoShapePy::Type), + &path, + &(TopoShapePy::Type), + &profile, + &tolerance, + &fillMode + )) { throw Py::Exception(); + } try { TopoShape mShape = *static_cast(path)->getTopoShapePtr(); // makeSweep uses GeomFill_Pipe which does not support shape // history. So use makEPipeShell() as a replacement - return shape2pyshape( - TopoShape(0, mShape.Hasher) - .makeElementPipeShell( - {mShape, *static_cast(profile)->getTopoShapePtr()}, - Part::MakeSolid::noSolid, - Standard_False, - TransitionMode::Transformed, - nullptr, - tolerance)); + return shape2pyshape(TopoShape(0, mShape.Hasher) + .makeElementPipeShell( + {mShape, + *static_cast(profile)->getTopoShapePtr()}, + Part::MakeSolid::noSolid, + Standard_False, + TransitionMode::Transformed, + nullptr, + tolerance + )); } catch (Standard_Failure& e) { throw Py::Exception(PartExceptionOCCError, e.GetMessageString()); } } - Py::Object makeLoft(const Py::Tuple& args, const Py::Dict &kwds) + Py::Object makeLoft(const Py::Tuple& args, const Py::Dict& kwds) { - PyObject *pcObj; - PyObject *psolid=Py_False; - PyObject *pruled=Py_False; - PyObject *pclosed=Py_False; + PyObject* pcObj; + PyObject* psolid = Py_False; + PyObject* pruled = Py_False; + PyObject* pclosed = Py_False; int degMax = 5; const char* op = nullptr; - const std::array kwd_list = - {"shapes", "solid", "ruled", "closed", "max_degree", "op", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), - kwds.ptr(), - "O!|O!O!O!is", - kwd_list, - &(PyList_Type), - &pcObj, - &(PyBool_Type), - &psolid, - &(PyBool_Type), - &pruled, - &(PyBool_Type), - &pclosed, - °Max, - &op)) { + const std::array kwd_list + = {"shapes", "solid", "ruled", "closed", "max_degree", "op", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O!|O!O!O!is", + kwd_list, + &(PyList_Type), + &pcObj, + &(PyBool_Type), + &psolid, + &(PyBool_Type), + &pruled, + &(PyBool_Type), + &pclosed, + °Max, + &op + )) { throw Py::Exception(); } Standard_Boolean anIsSolid = PyObject_IsTrue(psolid) ? Standard_True : Standard_False; Standard_Boolean anIsRuled = PyObject_IsTrue(pruled) ? Standard_True : Standard_False; Standard_Boolean anIsClosed = PyObject_IsTrue(pclosed) ? Standard_True : Standard_False; - return shape2pyshape(TopoShape().makeElementLoft( - getPyShapes(pcObj), - anIsSolid ? Part::IsSolid::solid : Part::IsSolid::notSolid, - anIsRuled ? Part::IsRuled::ruled : Part::IsRuled::notRuled, - anIsClosed ? Part::IsClosed::closed : Part::IsClosed::notClosed, - degMax, - op)); + return shape2pyshape( + TopoShape().makeElementLoft( + getPyShapes(pcObj), + anIsSolid ? Part::IsSolid::solid : Part::IsSolid::notSolid, + anIsRuled ? Part::IsRuled::ruled : Part::IsRuled::notRuled, + anIsClosed ? Part::IsClosed::closed : Part::IsClosed::notClosed, + degMax, + op + ) + ); } Py::Object makeSplitShape(const Py::Tuple& args) @@ -1899,15 +2257,22 @@ private: PyObject* shape; PyObject* list; PyObject* checkInterior = Py_True; - if (!PyArg_ParseTuple(args.ptr(), "O!O|O!", &(TopoShapePy::Type), &shape, &list, - &PyBool_Type, &checkInterior)) + if (!PyArg_ParseTuple( + args.ptr(), + "O!O|O!", + &(TopoShapePy::Type), + &shape, + &list, + &PyBool_Type, + &checkInterior + )) { throw Py::Exception(); + } try { std::vector sources; sources.push_back(*static_cast(shape)->getTopoShapePtr()); - TopoDS_Shape initShape = static_cast - (shape)->getTopoShapePtr()->getShape(); + TopoDS_Shape initShape = static_cast(shape)->getTopoShapePtr()->getShape(); BRepFeat_SplitShape splitShape(initShape); splitShape.SetCheckInterior(Base::asBoolean(checkInterior)); @@ -1917,10 +2282,11 @@ private: Py::TopoShape sh1(tuple[0]); Py::TopoShape sh2(tuple[1]); sources.push_back(*sh1.extensionObject()->getTopoShapePtr()); - const TopoDS_Shape& shape1= sh1.extensionObject()->getTopoShapePtr()->getShape(); - const TopoDS_Shape& shape2= sh2.extensionObject()->getTopoShapePtr()->getShape(); - if (shape1.IsNull() || shape2.IsNull()) + const TopoDS_Shape& shape1 = sh1.extensionObject()->getTopoShapePtr()->getShape(); + const TopoDS_Shape& shape2 = sh2.extensionObject()->getTopoShapePtr()->getShape(); + if (shape1.IsNull() || shape2.IsNull()) { throw Py::RuntimeError("Cannot add null shape"); + } if (shape2.ShapeType() == TopAbs_FACE) { if (shape1.ShapeType() == TopAbs_EDGE) { splitShape.Add(TopoDS::Edge(shape1), TopoDS::Face(shape2)); @@ -1958,12 +2324,14 @@ private: for (TopTools_ListIteratorOfListOfShape it(d); it.More(); it.Next()) { TopoShape s(0, sources.front().Hasher); list1.append(shape2pyshape( - s.makeShapeWithElementMap(it.Value(), mapper, sources, Part::OpCodes::Split))); + s.makeShapeWithElementMap(it.Value(), mapper, sources, Part::OpCodes::Split) + )); } for (TopTools_ListIteratorOfListOfShape it(l); it.More(); it.Next()) { TopoShape s(0, sources.front().Hasher); list2.append(shape2pyshape( - s.makeShapeWithElementMap(it.Value(), mapper, sources, Part::OpCodes::Split))); + s.makeShapeWithElementMap(it.Value(), mapper, sources, Part::OpCodes::Split) + )); } Py::Tuple tuple(2); tuple.setItem(0, list1); @@ -1977,7 +2345,7 @@ private: Py::Object makeWireString(const Py::Tuple& args) { #ifdef FCUseFreeType - PyObject *intext; + PyObject* intext; const char* dir; const char* fontfile; const char* fontspec; @@ -1985,24 +2353,25 @@ private: double height; double track = 0; - Py_UCS4 *unichars = nullptr; + Py_UCS4* unichars = nullptr; Py_ssize_t pysize; - PyObject *CharList; + PyObject* CharList; - if (PyArg_ParseTuple(args.ptr(), "Ossd|d", &intext, // compatibility with old version - &dir, - &fontfile, - &height, - &track)) { + if (PyArg_ParseTuple( + args.ptr(), + "Ossd|d", + &intext, // compatibility with old version + &dir, + &fontfile, + &height, + &track + )) { useFontSpec = false; } else { PyErr_Clear(); - if (PyArg_ParseTuple(args.ptr(), "Osd|d", &intext, - &fontspec, - &height, - &track)) { + if (PyArg_ParseTuple(args.ptr(), "Osd|d", &intext, &fontspec, &height, &track)) { useFontSpec = true; } else { @@ -2010,9 +2379,9 @@ private: } } - //FIXME: Test this! + // FIXME: Test this! if (PyBytes_Check(intext)) { - PyObject *p = Base::PyAsUnicodeObject(PyBytes_AsString(intext)); + PyObject* p = Base::PyAsUnicodeObject(PyBytes_AsString(intext)); if (!p) { throw Py::TypeError("** makeWireString can't convert PyString."); } @@ -2030,19 +2399,22 @@ private: try { if (useFontSpec) { - CharList = FT2FC(unichars,pysize,fontspec,height,track); + CharList = FT2FC(unichars, pysize, fontspec, height, track); } else { - CharList = FT2FC(unichars,pysize,dir,fontfile,height,track); + CharList = FT2FC(unichars, pysize, dir, fontfile, height, track); } if (unichars) { PyMem_Free(unichars); } } - catch (Standard_DomainError&) { // Standard_DomainError is OCC error. - throw Py::Exception(PartExceptionOCCDomainError, "makeWireString failed - Standard_DomainError"); + catch (Standard_DomainError&) { // Standard_DomainError is OCC error. + throw Py::Exception( + PartExceptionOCCDomainError, + "makeWireString failed - Standard_DomainError" + ); } - catch (std::runtime_error& e) { // FT2 or FT2FC errors + catch (std::runtime_error& e) { // FT2 or FT2FC errors throw Py::Exception(PartExceptionOCCError, e.what()); } @@ -2053,9 +2425,10 @@ private: } Py::Object exportUnits(const Py::Tuple& args) { - char* unit=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "|s", &unit)) + char* unit = nullptr; + if (!PyArg_ParseTuple(args.ptr(), "|s", &unit)) { throw Py::Exception(); + } if (unit) { if (!Interface::writeIgesUnit(unit)) { @@ -2110,8 +2483,8 @@ private: } Py::Object cast_to_shape(const Py::Tuple& args) { - PyObject *object; - if (PyArg_ParseTuple(args.ptr(),"O!",&(Part::TopoShapePy::Type), &object)) { + PyObject* object; + if (PyArg_ParseTuple(args.ptr(), "O!", &(Part::TopoShapePy::Type), &object)) { TopoShape* ptr = static_cast(object)->getTopoShapePtr(); return Py::asObject(ptr->getPyObject()); } @@ -2120,7 +2493,7 @@ private: } Py::Object getSortedClusters(const Py::Tuple& args) { - PyObject *obj; + PyObject* obj; if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) { throw Py::Exception(PartExceptionOCCError, "list of edges expected"); } @@ -2130,9 +2503,11 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); - if (sh.ShapeType() == TopAbs_EDGE) + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); + if (sh.ShapeType() == TopAbs_EDGE) { edges.push_back(TopoDS::Edge(sh)); + } else { throw Py::TypeError("shape is not an edge"); } @@ -2146,10 +2521,10 @@ private: tEdgeClusterVector aclusteroutput = acluster.GetClusters(); Py::List root_list; - for (const auto & it : aclusteroutput) { + for (const auto& it : aclusteroutput) { Py::List add_list; for (const auto& it1 : it) { - add_list.append(Py::Object(new TopoShapeEdgePy(new TopoShape(it1)),true)); + add_list.append(Py::Object(new TopoShapeEdgePy(new TopoShape(it1)), true)); } root_list.append(add_list); } @@ -2158,7 +2533,7 @@ private: } Py::Object sortEdges(const Py::Tuple& args) { - PyObject *obj; + PyObject* obj; if (!PyArg_ParseTuple(args.ptr(), "O", &obj)) { throw Py::TypeError("list of edges expected"); } @@ -2168,9 +2543,11 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); - if (sh.ShapeType() == TopAbs_EDGE) + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); + if (sh.ShapeType() == TopAbs_EDGE) { edges.push_back(TopoDS::Edge(sh)); + } else { throw Py::TypeError("shape is not an edge"); } @@ -2182,15 +2559,15 @@ private: std::list sorted = sort_Edges(Precision::Confusion(), edges); Py::List sorted_list; - for (const auto & it : sorted) { - sorted_list.append(Py::Object(new TopoShapeEdgePy(new TopoShape(it)),true)); + for (const auto& it : sorted) { + sorted_list.append(Py::Object(new TopoShapeEdgePy(new TopoShape(it)), true)); } return sorted_list; } Py::Object sortEdges2(const Py::Tuple& args) { - PyObject *obj; + PyObject* obj; double tol3d = Precision::Confusion(); if (!PyArg_ParseTuple(args.ptr(), "O|d", &obj, &tol3d)) { throw Py::Exception(PartExceptionOCCError, "list of edges expected"); @@ -2201,9 +2578,11 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); - if (sh.ShapeType() == TopAbs_EDGE) + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); + if (sh.ShapeType() == TopAbs_EDGE) { edges.push_back(TopoDS::Edge(sh)); + } else { throw Py::TypeError("shape is not an edge"); } @@ -2214,11 +2593,11 @@ private: } Py::List root_list; - while(!edges.empty()) { + while (!edges.empty()) { std::list sorted = sort_Edges(tol3d, edges); Py::List sorted_list; - for (const auto & it : sorted) { - sorted_list.append(Py::Object(new TopoShapeEdgePy(new TopoShape(it)),true)); + for (const auto& it : sorted) { + sorted_list.append(Py::Object(new TopoShapeEdgePy(new TopoShape(it)), true)); } root_list.append(sorted_list); } @@ -2226,15 +2605,21 @@ private: } Py::Object toPythonOCC(const Py::Tuple& args) { - PyObject *pcObj; - if (!PyArg_ParseTuple(args.ptr(), "O!", &(TopoShapePy::Type), &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args.ptr(), "O!", &(TopoShapePy::Type), &pcObj)) { throw Py::Exception(); + } try { TopoDS_Shape* shape = new TopoDS_Shape(); (*shape) = static_cast(pcObj)->getTopoShapePtr()->getShape(); PyObject* proxy = nullptr; - proxy = Base::Interpreter().createSWIGPointerObj("OCC.TopoDS", "TopoDS_Shape *", static_cast(shape), 1); + proxy = Base::Interpreter().createSWIGPointerObj( + "OCC.TopoDS", + "TopoDS_Shape *", + static_cast(shape), + 1 + ); return Py::asObject(proxy); } catch (const Base::Exception& e) { @@ -2243,14 +2628,15 @@ private: } Py::Object fromPythonOCC(const Py::Tuple& args) { - PyObject *proxy; - if (!PyArg_ParseTuple(args.ptr(), "O", &proxy)) + PyObject* proxy; + if (!PyArg_ParseTuple(args.ptr(), "O", &proxy)) { throw Py::Exception(); + } void* ptr; try { TopoShape* shape = new TopoShape(); - Base::Interpreter().convertSWIGPointerObj("OCC.TopoDS","TopoDS_Shape *", proxy, &ptr, 0); + Base::Interpreter().convertSWIGPointerObj("OCC.TopoDS", "TopoDS_Shape *", proxy, &ptr, 0); if (!ptr) { throw Py::RuntimeError("Conversion of OCC.TopoDS.TopoDS_Shape failed"); } @@ -2263,105 +2649,148 @@ private: } } - Py::Object getShape(const Py::Tuple& args, const Py::Dict &kwds) { - PyObject *pObj; - const char *subname = nullptr; - PyObject *pyMat = nullptr; - PyObject *needSubElement = Py_False; - PyObject *transform = Py_True; - PyObject *noElementMap = Py_False; - PyObject *refine = Py_False; + Py::Object getShape(const Py::Tuple& args, const Py::Dict& kwds) + { + PyObject* pObj; + const char* subname = nullptr; + PyObject* pyMat = nullptr; + PyObject* needSubElement = Py_False; + PyObject* transform = Py_True; + PyObject* noElementMap = Py_False; + PyObject* refine = Py_False; short retType = 0; - static const std::array kwd_list{"obj", "subname", "mat", - "needSubElement", "transform", "retType", "noElementMap", - "refine", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), "O!|sO!O!O!hO!O!", kwd_list, - &App::DocumentObjectPy::Type, &pObj, &subname, - &Base::MatrixPy::Type, &pyMat, - &PyBool_Type, &needSubElement, - &PyBool_Type, &transform, &retType, - &PyBool_Type, &noElementMap, - &PyBool_Type, &refine)) { + static const std::array kwd_list { + "obj", + "subname", + "mat", + "needSubElement", + "transform", + "retType", + "noElementMap", + "refine", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args.ptr(), + kwds.ptr(), + "O!|sO!O!O!hO!O!", + kwd_list, + &App::DocumentObjectPy::Type, + &pObj, + &subname, + &Base::MatrixPy::Type, + &pyMat, + &PyBool_Type, + &needSubElement, + &PyBool_Type, + &transform, + &retType, + &PyBool_Type, + &noElementMap, + &PyBool_Type, + &refine + )) { throw Py::Exception(); } - App::DocumentObject *obj = - static_cast(pObj)->getDocumentObjectPtr(); - App::DocumentObject *subObj = nullptr; + App::DocumentObject* obj = static_cast(pObj)->getDocumentObjectPtr(); + App::DocumentObject* subObj = nullptr; Base::Matrix4D mat; - if(pyMat) + if (pyMat) { mat = *static_cast(pyMat)->getMatrixPtr(); + } bool resolveLink = (retType == 2); - auto shape = Feature::getTopoShape(obj, - (resolveLink ? ShapeOption::ResolveLink : ShapeOption::NoFlag) - | (Base::asBoolean(needSubElement) ? ShapeOption::NeedSubElement : ShapeOption::NoFlag) - | (Base::asBoolean(transform) ? ShapeOption::Transform : ShapeOption::NoFlag) - | (Base::asBoolean(noElementMap) ? ShapeOption::NoElementMap : ShapeOption::NoFlag), - subname, - &mat, - &subObj); + auto shape = Feature::getTopoShape( + obj, + (resolveLink ? ShapeOption::ResolveLink : ShapeOption::NoFlag) + | (Base::asBoolean(needSubElement) ? ShapeOption::NeedSubElement : ShapeOption::NoFlag) + | (Base::asBoolean(transform) ? ShapeOption::Transform : ShapeOption::NoFlag) + | (Base::asBoolean(noElementMap) ? ShapeOption::NoElementMap : ShapeOption::NoFlag), + subname, + &mat, + &subObj + ); if (Base::asBoolean(refine)) { shape = TopoShape(0, shape.Hasher).makeElementRefine(shape); } Py::Object sret(shape2pyshape(shape)); - if(retType==0) + if (retType == 0) { return sret; + } - return Py::TupleN(sret,Py::asObject(new Base::MatrixPy(new Base::Matrix4D(mat))), - subObj?Py::Object(subObj->getPyObject(),true):Py::Object()); + return Py::TupleN( + sret, + Py::asObject(new Base::MatrixPy(new Base::Matrix4D(mat))), + subObj ? Py::Object(subObj->getPyObject(), true) : Py::Object() + ); } - Py::Object clearShapeCache(const Py::Tuple &args) { - if (!PyArg_ParseTuple(args.ptr(),"")) + Py::Object clearShapeCache(const Py::Tuple& args) + { + if (!PyArg_ParseTuple(args.ptr(), "")) { throw Py::Exception(); + } Part::Feature::clearShapeCache(); return Py::Object(); } - Py::Object splitSubname(const Py::Tuple& args) { - const char *subname; - if (!PyArg_ParseTuple(args.ptr(), "s",&subname)) + Py::Object splitSubname(const Py::Tuple& args) + { + const char* subname; + if (!PyArg_ParseTuple(args.ptr(), "s", &subname)) { throw Py::Exception(); + } auto element = Data::findElementName(subname); - std::string sub(subname,element-subname); + std::string sub(subname, element - subname); Py::List list; list.append(Py::String(sub)); - const char *dot = strchr(element,'.'); - if(!dot) - dot = element+strlen(element); - const char *mapped = Data::isMappedElement(element); - if(mapped) - list.append(Py::String(std::string(mapped,dot-mapped))); - else + const char* dot = strchr(element, '.'); + if (!dot) { + dot = element + strlen(element); + } + const char* mapped = Data::isMappedElement(element); + if (mapped) { + list.append(Py::String(std::string(mapped, dot - mapped))); + } + else { list.append(Py::String()); - if(*dot=='.') - list.append(Py::String(dot+1)); - else if(!mapped) + } + if (*dot == '.') { + list.append(Py::String(dot + 1)); + } + else if (!mapped) { list.append(Py::String(element)); - else + } + else { list.append(Py::String()); + } return list; } - Py::Object joinSubname(const Py::Tuple& args) { - const char *sub; - const char *mapped; - const char *element; - if (!PyArg_ParseTuple(args.ptr(), "sss",&sub,&mapped,&element)) + Py::Object joinSubname(const Py::Tuple& args) + { + const char* sub; + const char* mapped; + const char* element; + if (!PyArg_ParseTuple(args.ptr(), "sss", &sub, &mapped, &element)) { throw Py::Exception(); + } std::string subname(sub); - if (!subname.empty() && subname[subname.size()-1]!='.') + if (!subname.empty() && subname[subname.size() - 1] != '.') { subname += '.'; + } if (!Base::Tools::isNullOrEmpty(mapped)) { - if (!Data::isMappedElement(mapped)) + if (!Data::isMappedElement(mapped)) { subname += Data::ELEMENT_MAP_PREFIX; + } subname += mapped; } if (!Base::Tools::isNullOrEmpty(element)) { - if (!subname.empty() && subname[subname.size()-1]!='.') + if (!subname.empty() && subname[subname.size() - 1] != '.') { subname += '.'; + } subname += element; } return Py::String(subname); @@ -2373,4 +2802,4 @@ PyObject* initModule() return Base::Interpreter().addModule(new Module); } -} // namespace Part +} // namespace Part diff --git a/src/Mod/Part/App/Arc.pyi b/src/Mod/Part/App/Arc.pyi index cf31913405..340e2f6329 100644 --- a/src/Mod/Part/App/Arc.pyi +++ b/src/Mod/Part/App/Arc.pyi @@ -3,7 +3,6 @@ from TrimmedCurve import TrimmedCurve from Geometry import Geom_Circle, Geom_Ellipse from typing import overload - @export( Father="TrimmedCurvePy", PythonName="Part.Arc", @@ -23,6 +22,5 @@ class Arc(TrimmedCurve): @overload def __init__(self, circ: Geom_Circle, T: type = ...) -> None: ... - @overload def __init__(self, circ: Geom_Ellipse, T: type = ...) -> None: ... diff --git a/src/Mod/Part/App/ArcOfCircle.pyi b/src/Mod/Part/App/ArcOfCircle.pyi index 1599037ffa..a1ad2bff4a 100644 --- a/src/Mod/Part/App/ArcOfCircle.pyi +++ b/src/Mod/Part/App/ArcOfCircle.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from ArcOfConic import ArcOfConic from typing import Final - @export( PythonName="Part.ArcOfCircle", Twin="GeomArcOfCircle", diff --git a/src/Mod/Part/App/ArcOfCirclePyImp.cpp b/src/Mod/Part/App/ArcOfCirclePyImp.cpp index fde881a302..a361920fb2 100644 --- a/src/Mod/Part/App/ArcOfCirclePyImp.cpp +++ b/src/Mod/Part/App/ArcOfCirclePyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -42,8 +42,9 @@ extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python std::string ArcOfCirclePy::representation() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfCirclePtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfCirclePtr()->handle() + ); Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(trim->BasisCurve()); gp_Ax1 axis = circle->Axis(); @@ -56,15 +57,15 @@ std::string ArcOfCirclePy::representation() const std::stringstream str; str << "ArcOfCircle ("; str << "Radius : " << fRad << ", "; - str << "Position : (" << loc.X() << ", "<< loc.Y() << ", "<< loc.Z() << "), "; - str << "Direction : (" << dir.X() << ", "<< dir.Y() << ", "<< dir.Z() << "), "; + str << "Position : (" << loc.X() << ", " << loc.Y() << ", " << loc.Z() << "), "; + str << "Direction : (" << dir.X() << ", " << dir.Y() << ", " << dir.Z() << "), "; str << "Parameter : (" << u1 << ", " << u2 << ")"; str << ")"; return str.str(); } -PyObject *ArcOfCirclePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfCirclePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfCirclePy and the Twin object return new ArcOfCirclePy(new GeomArcOfCircle); @@ -75,11 +76,12 @@ int ArcOfCirclePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::CirclePy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast - (static_cast(o)->getGeomCirclePtr()->handle()); + Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( + static_cast(o)->getGeomCirclePtr()->handle() + ); GC_MakeArcOfCircle arc(circle->Circ(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -101,16 +103,25 @@ int ArcOfCirclePy::PyInit(PyObject* args, PyObject* /*kwds*/) PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (PyArg_ParseTuple(args, "O!O!O!", &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakeArcOfCircle arc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakeArcOfCircle arc( + gp_Pnt(v1.x, v1.y, v1.z), + gp_Pnt(v2.x, v2.y, v2.z), + gp_Pnt(v3.x, v3.y, v3.z) + ); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); return -1; @@ -121,8 +132,10 @@ int ArcOfCirclePy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfCircle constructor expects a circle curve and a parameter range or three points"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfCircle constructor expects a circle curve and a parameter range or three points" + ); return -1; } @@ -131,25 +144,26 @@ Py::Float ArcOfCirclePy::getRadius() const return Py::Float(getGeomArcOfCirclePtr()->getRadius()); } -void ArcOfCirclePy::setRadius(Py::Float arg) +void ArcOfCirclePy::setRadius(Py::Float arg) { getGeomArcOfCirclePtr()->setRadius((double)arg); } Py::Object ArcOfCirclePy::getCircle() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfCirclePtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfCirclePtr()->handle() + ); Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(trim->BasisCurve()); return Py::Object(new CirclePy(new GeomCircle(circle)), true); } -PyObject *ArcOfCirclePy::getCustomAttributes(const char* ) const +PyObject* ArcOfCirclePy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfCirclePy::setCustomAttributes(const char* , PyObject *) +int ArcOfCirclePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/ArcOfConic.pyi b/src/Mod/Part/App/ArcOfConic.pyi index 903a2b9e1a..8c46f2aa34 100644 --- a/src/Mod/Part/App/ArcOfConic.pyi +++ b/src/Mod/Part/App/ArcOfConic.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from TrimmedCurve import TrimmedCurve from typing import overload - @export( Father="TrimmedCurvePy", PythonName="Part.ArcOfConic", diff --git a/src/Mod/Part/App/ArcOfConicPyImp.cpp b/src/Mod/Part/App/ArcOfConicPyImp.cpp index 8291772919..0cca68d334 100644 --- a/src/Mod/Part/App/ArcOfConicPyImp.cpp +++ b/src/Mod/Part/App/ArcOfConicPyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -41,11 +41,13 @@ std::string ArcOfConicPy::representation() const return ""; } -PyObject *ArcOfConicPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfConicPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'ArcOfConic'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'ArcOfConic'." + ); return nullptr; } @@ -65,7 +67,7 @@ Py::Object ArcOfConicPy::getCenter() const return Py::Vector(getGeomArcOfConicPtr()->getCenter()); } -void ArcOfConicPy::setLocation(Py::Object arg) +void ArcOfConicPy::setLocation(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { @@ -83,7 +85,7 @@ void ArcOfConicPy::setLocation(Py::Object arg) } } -void ArcOfConicPy::setCenter(Py::Object arg) +void ArcOfConicPy::setCenter(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { @@ -113,15 +115,16 @@ void ArcOfConicPy::setAngleXU(Py::Float arg) Py::Object ArcOfConicPy::getAxis() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfConicPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfConicPtr()->handle() + ); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(trim->BasisCurve()); gp_Ax1 axis = conic->Axis(); gp_Dir dir = axis.Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void ArcOfConicPy::setAxis(Py::Object arg) +void ArcOfConicPy::setAxis(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d val; @@ -137,8 +140,9 @@ void ArcOfConicPy::setAxis(Py::Object arg) throw Py::TypeError(error); } - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfConicPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfConicPtr()->handle() + ); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(trim->BasisCurve()); try { gp_Ax1 axis; @@ -153,15 +157,16 @@ void ArcOfConicPy::setAxis(Py::Object arg) Py::Object ArcOfConicPy::getXAxis() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfConicPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfConicPtr()->handle() + ); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(trim->BasisCurve()); gp_Ax1 axis = conic->XAxis(); gp_Dir dir = axis.Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void ArcOfConicPy::setXAxis(Py::Object arg) +void ArcOfConicPy::setXAxis(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d val; @@ -177,8 +182,9 @@ void ArcOfConicPy::setXAxis(Py::Object arg) throw Py::TypeError(error); } - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfConicPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfConicPtr()->handle() + ); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(trim->BasisCurve()); try { gp_Ax2 pos; @@ -193,15 +199,16 @@ void ArcOfConicPy::setXAxis(Py::Object arg) Py::Object ArcOfConicPy::getYAxis() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfConicPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfConicPtr()->handle() + ); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(trim->BasisCurve()); gp_Ax1 axis = conic->YAxis(); gp_Dir dir = axis.Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void ArcOfConicPy::setYAxis(Py::Object arg) +void ArcOfConicPy::setYAxis(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d val; @@ -217,8 +224,9 @@ void ArcOfConicPy::setYAxis(Py::Object arg) throw Py::TypeError(error); } - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfConicPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfConicPtr()->handle() + ); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(trim->BasisCurve()); try { gp_Ax2 pos; @@ -231,12 +239,12 @@ void ArcOfConicPy::setYAxis(Py::Object arg) } } -PyObject *ArcOfConicPy::getCustomAttributes(const char* ) const +PyObject* ArcOfConicPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfConicPy::setCustomAttributes(const char* , PyObject *) +int ArcOfConicPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/ArcOfEllipse.pyi b/src/Mod/Part/App/ArcOfEllipse.pyi index 664a0c7d66..f111c0ba69 100644 --- a/src/Mod/Part/App/ArcOfEllipse.pyi +++ b/src/Mod/Part/App/ArcOfEllipse.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from ArcOfConic import ArcOfConic from typing import Final - @export( PythonName="Part.ArcOfEllipse", Twin="GeomArcOfEllipse", diff --git a/src/Mod/Part/App/ArcOfEllipsePyImp.cpp b/src/Mod/Part/App/ArcOfEllipsePyImp.cpp index 016e11b265..e75ed6a6ca 100644 --- a/src/Mod/Part/App/ArcOfEllipsePyImp.cpp +++ b/src/Mod/Part/App/ArcOfEllipsePyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "ArcOfEllipsePy.h" @@ -40,8 +40,9 @@ extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python std::string ArcOfEllipsePy::representation() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfEllipsePtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfEllipsePtr()->handle() + ); Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(trim->BasisCurve()); gp_Ax1 axis = ellipse->Axis(); @@ -55,9 +56,9 @@ std::string ArcOfEllipsePy::representation() const gp_Dir normal = ellipse->Axis().Direction(); gp_Dir xdir = ellipse->XAxis().Direction(); - gp_Ax2 xdirref(loc, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(loc, normal); // this is a reference XY for the ellipse - Standard_Real fAngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + Standard_Real fAngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); std::stringstream str; @@ -65,15 +66,15 @@ std::string ArcOfEllipsePy::representation() const str << "MajorRadius : " << fMajRad << ", "; str << "MinorRadius : " << fMinRad << ", "; str << "AngleXU : " << fAngleXU << ", "; - str << "Position : (" << loc.X() << ", "<< loc.Y() << ", "<< loc.Z() << "), "; - str << "Direction : (" << dir.X() << ", "<< dir.Y() << ", "<< dir.Z() << "), "; + str << "Position : (" << loc.X() << ", " << loc.Y() << ", " << loc.Z() << "), "; + str << "Direction : (" << dir.X() << ", " << dir.Y() << ", " << dir.Z() << "), "; str << "Parameter : (" << u1 << ", " << u2 << ")"; str << ")"; return str.str(); } -PyObject *ArcOfEllipsePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfEllipsePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfEllipsePy and the Twin object return new ArcOfEllipsePy(new GeomArcOfEllipse); @@ -84,11 +85,12 @@ int ArcOfEllipsePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::EllipsePy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast - (static_cast(o)->getGeomEllipsePtr()->handle()); + Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast( + static_cast(o)->getGeomEllipsePtr()->handle() + ); GC_MakeArcOfEllipse arc(ellipse->Elips(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -109,8 +111,10 @@ int ArcOfEllipsePy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfEllipse constructor expects an ellipse curve and a parameter range"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfEllipse constructor expects an ellipse curve and a parameter range" + ); return -1; } @@ -119,7 +123,7 @@ Py::Float ArcOfEllipsePy::getMajorRadius() const return Py::Float(getGeomArcOfEllipsePtr()->getMajorRadius()); } -void ArcOfEllipsePy::setMajorRadius(Py::Float arg) +void ArcOfEllipsePy::setMajorRadius(Py::Float arg) { getGeomArcOfEllipsePtr()->setMajorRadius((double)arg); } @@ -129,25 +133,26 @@ Py::Float ArcOfEllipsePy::getMinorRadius() const return Py::Float(getGeomArcOfEllipsePtr()->getMinorRadius()); } -void ArcOfEllipsePy::setMinorRadius(Py::Float arg) +void ArcOfEllipsePy::setMinorRadius(Py::Float arg) { getGeomArcOfEllipsePtr()->setMinorRadius((double)arg); } Py::Object ArcOfEllipsePy::getEllipse() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfEllipsePtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfEllipsePtr()->handle() + ); Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(trim->BasisCurve()); return Py::Object(new EllipsePy(new GeomEllipse(ellipse)), true); } -PyObject *ArcOfEllipsePy::getCustomAttributes(const char* ) const +PyObject* ArcOfEllipsePy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfEllipsePy::setCustomAttributes(const char* , PyObject *) +int ArcOfEllipsePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/ArcOfHyperbola.pyi b/src/Mod/Part/App/ArcOfHyperbola.pyi index bc489e0d34..15ef3eee52 100644 --- a/src/Mod/Part/App/ArcOfHyperbola.pyi +++ b/src/Mod/Part/App/ArcOfHyperbola.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from Part.ArcOfConic import ArcOfConic from typing import Final - @export( Father="ArcOfConicPy", Name="ArcOfHyperbolaPy", diff --git a/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp b/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp index 973be9ec00..583bc08cd2 100644 --- a/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp +++ b/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "ArcOfHyperbolaPy.h" @@ -40,8 +40,9 @@ extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python std::string ArcOfHyperbolaPy::representation() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfHyperbolaPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfHyperbolaPtr()->handle() + ); Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(trim->BasisCurve()); gp_Ax1 axis = hyperbola->Axis(); @@ -55,9 +56,9 @@ std::string ArcOfHyperbolaPy::representation() const gp_Dir normal = hyperbola->Axis().Direction(); gp_Dir xdir = hyperbola->XAxis().Direction(); - gp_Ax2 xdirref(loc, normal); // this is a reference XY for the hyperbola + gp_Ax2 xdirref(loc, normal); // this is a reference XY for the hyperbola - Standard_Real fAngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + Standard_Real fAngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); std::stringstream str; @@ -65,15 +66,15 @@ std::string ArcOfHyperbolaPy::representation() const str << "MajorRadius : " << fMajRad << ", "; str << "MinorRadius : " << fMinRad << ", "; str << "AngleXU : " << fAngleXU << ", "; - str << "Position : (" << loc.X() << ", "<< loc.Y() << ", "<< loc.Z() << "), "; - str << "Direction : (" << dir.X() << ", "<< dir.Y() << ", "<< dir.Z() << "), "; + str << "Position : (" << loc.X() << ", " << loc.Y() << ", " << loc.Z() << "), "; + str << "Direction : (" << dir.X() << ", " << dir.Y() << ", " << dir.Z() << "), "; str << "Parameter : (" << u1 << ", " << u2 << ")"; str << ")"; return str.str(); } -PyObject *ArcOfHyperbolaPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfHyperbolaPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfHyperbolaPy and the Twin object return new ArcOfHyperbolaPy(new GeomArcOfHyperbola); @@ -84,11 +85,12 @@ int ArcOfHyperbolaPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::HyperbolaPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast - (static_cast(o)->getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + static_cast(o)->getGeomHyperbolaPtr()->handle() + ); GC_MakeArcOfHyperbola arc(hyperbola->Hypr(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -109,8 +111,10 @@ int ArcOfHyperbolaPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfHyperbola constructor expects an hyperbola curve and a parameter range"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfHyperbola constructor expects an hyperbola curve and a parameter range" + ); return -1; } @@ -119,7 +123,7 @@ Py::Float ArcOfHyperbolaPy::getMajorRadius() const return Py::Float(getGeomArcOfHyperbolaPtr()->getMajorRadius()); } -void ArcOfHyperbolaPy::setMajorRadius(Py::Float arg) +void ArcOfHyperbolaPy::setMajorRadius(Py::Float arg) { getGeomArcOfHyperbolaPtr()->setMajorRadius((double)arg); } @@ -129,25 +133,26 @@ Py::Float ArcOfHyperbolaPy::getMinorRadius() const return Py::Float(getGeomArcOfHyperbolaPtr()->getMinorRadius()); } -void ArcOfHyperbolaPy::setMinorRadius(Py::Float arg) +void ArcOfHyperbolaPy::setMinorRadius(Py::Float arg) { getGeomArcOfHyperbolaPtr()->setMinorRadius((double)arg); } Py::Object ArcOfHyperbolaPy::getHyperbola() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfHyperbolaPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfHyperbolaPtr()->handle() + ); Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(trim->BasisCurve()); return Py::Object(new HyperbolaPy(new GeomHyperbola(hyperbola)), true); } -PyObject *ArcOfHyperbolaPy::getCustomAttributes(const char* ) const +PyObject* ArcOfHyperbolaPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfHyperbolaPy::setCustomAttributes(const char* , PyObject *) +int ArcOfHyperbolaPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/ArcOfParabola.pyi b/src/Mod/Part/App/ArcOfParabola.pyi index 75d12a300a..886cb96fa9 100644 --- a/src/Mod/Part/App/ArcOfParabola.pyi +++ b/src/Mod/Part/App/ArcOfParabola.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from ArcOfConic import ArcOfConic from typing import Final - @export( Father="ArcOfConicPy", Name="ArcOfParabolaPy", diff --git a/src/Mod/Part/App/ArcOfParabolaPyImp.cpp b/src/Mod/Part/App/ArcOfParabolaPyImp.cpp index 8ad63c19a7..504b152d32 100644 --- a/src/Mod/Part/App/ArcOfParabolaPyImp.cpp +++ b/src/Mod/Part/App/ArcOfParabolaPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "ArcOfParabolaPy.h" @@ -40,8 +40,9 @@ extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python std::string ArcOfParabolaPy::representation() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfParabolaPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfParabolaPtr()->handle() + ); Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast(trim->BasisCurve()); gp_Ax1 axis = parabola->Axis(); @@ -54,24 +55,24 @@ std::string ArcOfParabolaPy::representation() const gp_Dir normal = parabola->Axis().Direction(); gp_Dir xdir = parabola->XAxis().Direction(); - gp_Ax2 xdirref(loc, normal); // this is a reference XY for the parabola + gp_Ax2 xdirref(loc, normal); // this is a reference XY for the parabola - Standard_Real fAngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + Standard_Real fAngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); std::stringstream str; str << "ArcOfParabola ("; str << "Focal : " << fFocal << ", "; str << "AngleXU : " << fAngleXU << ", "; - str << "Position : (" << loc.X() << ", "<< loc.Y() << ", "<< loc.Z() << "), "; - str << "Direction : (" << dir.X() << ", "<< dir.Y() << ", "<< dir.Z() << "), "; + str << "Position : (" << loc.X() << ", " << loc.Y() << ", " << loc.Z() << "), "; + str << "Direction : (" << dir.X() << ", " << dir.Y() << ", " << dir.Z() << "), "; str << "Parameter : (" << u1 << ", " << u2 << ")"; str << ")"; return str.str(); } -PyObject *ArcOfParabolaPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfParabolaPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfParabolaPy and the Twin object return new ArcOfParabolaPy(new GeomArcOfParabola); @@ -82,11 +83,12 @@ int ArcOfParabolaPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::ParabolaPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast - (static_cast(o)->getGeomParabolaPtr()->handle()); + Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast( + static_cast(o)->getGeomParabolaPtr()->handle() + ); GC_MakeArcOfParabola arc(parabola->Parab(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -107,8 +109,10 @@ int ArcOfParabolaPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfParabola constructor expects an parabola curve and a parameter range"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfParabola constructor expects an parabola curve and a parameter range" + ); return -1; } @@ -117,25 +121,26 @@ Py::Float ArcOfParabolaPy::getFocal() const return Py::Float(getGeomArcOfParabolaPtr()->getFocal()); } -void ArcOfParabolaPy::setFocal(Py::Float arg) +void ArcOfParabolaPy::setFocal(Py::Float arg) { getGeomArcOfParabolaPtr()->setFocal((double)arg); } Py::Object ArcOfParabolaPy::getParabola() const { - Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast - (getGeomArcOfParabolaPtr()->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast( + getGeomArcOfParabolaPtr()->handle() + ); Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast(trim->BasisCurve()); return Py::Object(new ParabolaPy(new GeomParabola(parabola)), true); } -PyObject *ArcOfParabolaPy::getCustomAttributes(const char* ) const +PyObject* ArcOfParabolaPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfParabolaPy::setCustomAttributes(const char* , PyObject *) +int ArcOfParabolaPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/ArcPyImp.cpp b/src/Mod/Part/App/ArcPyImp.cpp index acaf9f9b72..4c2b732c3e 100644 --- a/src/Mod/Part/App/ArcPyImp.cpp +++ b/src/Mod/Part/App/ArcPyImp.cpp @@ -22,14 +22,14 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -53,7 +53,7 @@ std::string ArcPy::representation() const return ""; } -PyObject *ArcPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor return new ArcPy(new GeomTrimmedCurve()); @@ -64,11 +64,12 @@ int ArcPy::PyInit(PyObject* args, PyObject* /*kwd*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::CirclePy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast - (static_cast(o)->getGeomCirclePtr()->handle()); + Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( + static_cast(o)->getGeomCirclePtr()->handle() + ); GC_MakeArcOfCircle arc(circle->Circ(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -90,16 +91,25 @@ int ArcPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (PyArg_ParseTuple(args, "O!O!O!", &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakeArcOfCircle arc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakeArcOfCircle arc( + gp_Pnt(v1.x, v1.y, v1.z), + gp_Pnt(v2.x, v2.y, v2.z), + gp_Pnt(v3.x, v3.y, v3.z) + ); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); return -1; @@ -112,8 +122,9 @@ int ArcPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::EllipsePy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast - (static_cast(o)->getGeomEllipsePtr()->handle()); + Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast( + static_cast(o)->getGeomEllipsePtr()->handle() + ); GC_MakeArcOfEllipse arc(ellipse->Elips(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -137,8 +148,9 @@ int ArcPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::ParabolaPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast - (static_cast(o)->getGeomParabolaPtr()->handle()); + Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast( + static_cast(o)->getGeomParabolaPtr()->handle() + ); GC_MakeArcOfParabola arc(parabola->Parab(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -162,8 +174,9 @@ int ArcPy::PyInit(PyObject* args, PyObject* /*kwd*/) if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::HyperbolaPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast - (static_cast(o)->getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + static_cast(o)->getGeomHyperbolaPtr()->handle() + ); GC_MakeArcOfHyperbola arc(hyperbola->Hypr(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -188,7 +201,7 @@ int ArcPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -PyObject *ArcPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ArcPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/AttachEngine.pyi b/src/Mod/Part/App/AttachEngine.pyi index 65d1f01278..637431f483 100644 --- a/src/Mod/Part/App/AttachEngine.pyi +++ b/src/Mod/Part/App/AttachEngine.pyi @@ -4,7 +4,6 @@ from Base.Placement import Placement from App.DocumentObject import DocumentObject from typing import Final, Optional - @export( Include="Mod/Part/App/Attacher.h", Namespace="Attacher", @@ -78,7 +77,7 @@ class AttachEngine(BaseClass): ... @constmethod - def copy(self) -> 'AttachEngine': + def copy(self) -> "AttachEngine": """ copy(): returns a new instance of AttachEngine. """ @@ -147,4 +146,3 @@ class AttachEngine(BaseClass): will crash FreeCAD. """ ... - diff --git a/src/Mod/Part/App/AttachEnginePyImp.cpp b/src/Mod/Part/App/AttachEnginePyImp.cpp index 8324188d33..ecb0c03175 100644 --- a/src/Mod/Part/App/AttachEnginePyImp.cpp +++ b/src/Mod/Part/App/AttachEnginePyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -43,7 +43,7 @@ std::string AttachEnginePy::representation() const return {""}; } -PyObject* AttachEnginePy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* AttachEnginePy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of AttachEngine3D return new AttachEnginePy(new AttachEngine3D); @@ -71,8 +71,10 @@ int AttachEnginePy::PyInit(PyObject* args, PyObject* /*kwd*/) if (PyArg_ParseTuple(args, "s", &typeName)) { Base::Type t = Base::Type::fromName(typeName); AttachEngine* pNewAttacher = nullptr; - if (t.isDerivedFrom(AttachEngine::getClassTypeId())){ - pNewAttacher = static_cast(Base::Type::createInstanceByName(typeName)); + if (t.isDerivedFrom(AttachEngine::getClassTypeId())) { + pNewAttacher = static_cast( + Base::Type::createInstanceByName(typeName) + ); } if (!pNewAttacher) { std::stringstream errMsg; @@ -86,9 +88,13 @@ int AttachEnginePy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, "Wrong set of constructor arguments. Can be: (), ('Attacher::AttachEngine3D'), ('Attacher::AttachEnginePlane'), ('Attacher::AttachEngineLine'), ('Attacher::AttachEnginePoint'), (other_attacher_instance)."); + PyErr_SetString( + PyExc_TypeError, + "Wrong set of constructor arguments. Can be: (), ('Attacher::AttachEngine3D'), " + "('Attacher::AttachEnginePlane'), ('Attacher::AttachEngineLine'), " + "('Attacher::AttachEnginePoint'), (other_attacher_instance)." + ); return -1; - } @@ -98,111 +104,127 @@ Py::String AttachEnginePy::getAttacherType() const } /** - * @brief macro ATTACHERPY_STDCATCH_ATTR: catch for exceptions in attribute - * code (re-throws the exception converted to Py::Exception). It is a helper - * to avoid repeating the same error handling code over and over again. - */ + * @brief macro ATTACHERPY_STDCATCH_ATTR: catch for exceptions in attribute + * code (re-throws the exception converted to Py::Exception). It is a helper + * to avoid repeating the same error handling code over and over again. + */ #define ATTACHERPY_STDCATCH_ATTR \ - catch (Standard_Failure& e) {\ - throw Py::Exception(Part::PartExceptionOCCError, e.GetMessageString());\ - } catch (Base::Exception &e) {\ - e.setPyException();\ - throw Py::Exception();\ + catch (Standard_Failure & e) \ + { \ + throw Py::Exception(Part::PartExceptionOCCError, e.GetMessageString()); \ + } \ + catch (Base::Exception & e) \ + { \ + e.setPyException(); \ + throw Py::Exception(); \ } Py::String AttachEnginePy::getMode() const { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); return {attacher.getModeName(attacher.mapMode)}; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } void AttachEnginePy::setMode(Py::String arg) { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); std::string modeName = static_cast(arg); attacher.mapMode = attacher.getModeByName(modeName); - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } Py::Object AttachEnginePy::getReferences() const { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); Py::List ret; - int i=0; - for(auto obj : attacher.getRefObjects()) - ret.append(Py::TupleN(Py::asObject(obj->getPyObject()), - Py::String(attacher.subnames[i++]))); + int i = 0; + for (auto obj : attacher.getRefObjects()) { + ret.append( + Py::TupleN(Py::asObject(obj->getPyObject()), Py::String(attacher.subnames[i++])) + ); + } return ret; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } void AttachEnginePy::setReferences(Py::Object arg) { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); App::PropertyLinkSubList references; references.setPyObject(arg.ptr()); attacher.setReferences(references); - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } Py::Object AttachEnginePy::getAttachmentOffset() const { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); - return Py::Object(new Base::PlacementPy(new Base::Placement(attacher.attachmentOffset)),true); - } ATTACHERPY_STDCATCH_ATTR; + AttachEngine& attacher = *(this->getAttachEnginePtr()); + return Py::Object(new Base::PlacementPy(new Base::Placement(attacher.attachmentOffset)), true); + } + ATTACHERPY_STDCATCH_ATTR; } void AttachEnginePy::setAttachmentOffset(Py::Object arg) { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); if (PyObject_TypeCheck(arg.ptr(), &(Base::PlacementPy::Type))) { const Base::PlacementPy* plmPy = static_cast(arg.ptr()); attacher.attachmentOffset = *(plmPy->getPlacementPtr()); - } else { + } + else { std::string error = std::string("type must be 'Placement', not "); error += arg.type().as_string(); throw Py::TypeError(error); } - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } Py::Boolean AttachEnginePy::getReverse() const { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); return {attacher.mapReverse}; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } void AttachEnginePy::setReverse(Py::Boolean arg) { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); attacher.mapReverse = arg.isTrue(); - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } Py::Float AttachEnginePy::getParameter() const { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); return Py::Float(attacher.attachParameter); - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } void AttachEnginePy::setParameter(Py::Float arg) { try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); attacher.attachParameter = (double)arg; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } @@ -210,72 +232,81 @@ Py::List AttachEnginePy::getCompleteModeList() const { try { Py::List ret; - AttachEngine &attacher = *(this->getAttachEnginePtr()); - for(int imode = 0 ; imode < mmDummy_NumberOfModes ; imode++){ + AttachEngine& attacher = *(this->getAttachEnginePtr()); + for (int imode = 0; imode < mmDummy_NumberOfModes; imode++) { ret.append(Py::String(attacher.getModeName(eMapMode(imode)))); } return ret; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } Py::List AttachEnginePy::getCompleteRefTypeList() const { try { Py::List ret; - AttachEngine &attacher = *(this->getAttachEnginePtr()); - for(int irt = 0 ; irt < rtDummy_numberOfShapeTypes ; irt++){ + AttachEngine& attacher = *(this->getAttachEnginePtr()); + for (int irt = 0; irt < rtDummy_numberOfShapeTypes; irt++) { ret.append(Py::String(attacher.getRefTypeName(eRefType(irt)))); } return ret; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } Py::List AttachEnginePy::getImplementedModes() const { try { Py::List ret; - AttachEngine &attacher = *(this->getAttachEnginePtr()); - for(int imode = 0 ; imode < mmDummy_NumberOfModes ; imode++){ - if(!attacher.modeRefTypes[imode].empty()){ + AttachEngine& attacher = *(this->getAttachEnginePtr()); + for (int imode = 0; imode < mmDummy_NumberOfModes; imode++) { + if (!attacher.modeRefTypes[imode].empty()) { ret.append(Py::String(attacher.getModeName(eMapMode(imode)))); } } return ret; - } ATTACHERPY_STDCATCH_ATTR; + } + ATTACHERPY_STDCATCH_ATTR; } /** - * @brief macro ATTACHERPY_STDCATCH_METH: catch for exceptions in method code - * (returns NULL if an exception is caught). It is a helper to avoid repeating - * the same error handling code over and over again. - */ + * @brief macro ATTACHERPY_STDCATCH_METH: catch for exceptions in method code + * (returns NULL if an exception is caught). It is a helper to avoid repeating + * the same error handling code over and over again. + */ #define ATTACHERPY_STDCATCH_METH \ - catch (Standard_Failure& e) {\ - PyErr_SetString(Part::PartExceptionOCCError, e.GetMessageString());\ - return NULL;\ - } catch (Base::Exception &e) {\ - PyErr_SetString(Base::PyExc_FC_GeneralError, e.what());\ - return NULL;\ - } catch (const Py::Exception &){\ - return NULL;\ + catch (Standard_Failure & e) \ + { \ + PyErr_SetString(Part::PartExceptionOCCError, e.GetMessageString()); \ + return NULL; \ + } \ + catch (Base::Exception & e) \ + { \ + PyErr_SetString(Base::PyExc_FC_GeneralError, e.what()); \ + return NULL; \ + } \ + catch (const Py::Exception&) \ + { \ + return NULL; \ } PyObject* AttachEnginePy::getModeInfo(PyObject* args) { char* modeName; - if (!PyArg_ParseTuple(args, "s", &modeName)) + if (!PyArg_ParseTuple(args, "s", &modeName)) { return nullptr; + } try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); eMapMode mmode = attacher.getModeByName(modeName); Py::List pyListOfCombinations; Py::List pyCombination; - refTypeStringList &listOfCombinations = attacher.modeRefTypes.at(mmode); - for(const refTypeString &combination: listOfCombinations){ + refTypeStringList& listOfCombinations = attacher.modeRefTypes.at(mmode); + for (const refTypeString& combination : listOfCombinations) { pyCombination = Py::List(combination.size()); - for(std::size_t iref = 0; iref < combination.size(); iref++) { + for (std::size_t iref = 0; iref < combination.size(); iref++) { pyCombination[iref] = Py::String(AttachEngine::getRefTypeName(combination[iref])); } pyListOfCombinations.append(pyCombination); @@ -284,10 +315,13 @@ PyObject* AttachEnginePy::getModeInfo(PyObject* args) ret["ReferenceCombinations"] = pyListOfCombinations; ret["ModeIndex"] = Py::Long(mmode); try { - Py::Module module(PyImport_ImportModule("PartGui"),true); + Py::Module module(PyImport_ImportModule("PartGui"), true); if (module.isNull() || !module.hasAttr("AttachEngineResources")) { - // in v0.14+, the GUI module can be loaded in console mode (but doesn't have all its document methods) - throw Py::RuntimeError("Gui is not up");//DeepSOIC: wanted to throw ImportError here, but it's not defined, so I don't know... + // in v0.14+, the GUI module can be loaded in console mode (but doesn't have all its + // document methods) + throw Py::RuntimeError("Gui is not up"); // DeepSOIC: wanted to throw ImportError + // here, but it's not defined, so I don't + // know... } Py::Object submod(module.getAttr("AttachEngineResources")); Py::Callable method(submod.getAttr("getModeStrings")); @@ -298,82 +332,98 @@ PyObject* AttachEnginePy::getModeInfo(PyObject* args) assert(strs.size() == 2); ret["UserFriendlyName"] = strs[0]; ret["BriefDocu"] = strs[1]; - } catch (Py::Exception& e) { + } + catch (Py::Exception& e) { if (PyErr_ExceptionMatches(PyExc_ImportError)) { // the GUI is not up. - Base::Console().warning("AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n"); + Base::Console().warning( + "AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n" + ); e.clear(); - } else { + } + else { Base::Console().warning("AttachEngine.getModeInfo: error obtaining GUI strings\n"); e.clear(); } - } catch (Base::Exception &e){ + } + catch (Base::Exception& e) { Base::Console().warning("AttachEngine.getModeInfo: error obtaining GUI strings:"); Base::Console().warning(e.what()); Base::Console().warning("\n"); } return Py::new_reference_to(ret); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::getRefTypeOfShape(PyObject* args) { - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pcObj)) { return nullptr; + } - try{ + try { TopoDS_Shape shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); eRefType rt = AttachEngine::getShapeType(shape); return Py::new_reference_to(Py::String(AttachEngine::getRefTypeName(rt))); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::isFittingRefType(PyObject* args) { char* type_shape_str; char* type_need_str; - if (!PyArg_ParseTuple(args, "ss", &type_shape_str, &type_need_str)) + if (!PyArg_ParseTuple(args, "ss", &type_shape_str, &type_need_str)) { return nullptr; + } try { eRefType type_shape = AttachEngine::getRefTypeByName(std::string(type_shape_str)); eRefType type_need = AttachEngine::getRefTypeByName(std::string(type_need_str)); bool result = AttachEngine::isShapeOfType(type_shape, type_need) > -1; return Py::new_reference_to(Py::Boolean(result)); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::downgradeRefType(PyObject* args) { char* type_shape_str; - if (!PyArg_ParseTuple(args, "s", &type_shape_str)) + if (!PyArg_ParseTuple(args, "s", &type_shape_str)) { return nullptr; + } try { eRefType type_shape = AttachEngine::getRefTypeByName(std::string(type_shape_str)); eRefType result = AttachEngine::downgradeType(type_shape); return Py::new_reference_to(Py::String(AttachEngine::getRefTypeName(result))); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::getRefTypeInfo(PyObject* args) { char* typeName; - if (!PyArg_ParseTuple(args, "s", &typeName)) + if (!PyArg_ParseTuple(args, "s", &typeName)) { return nullptr; + } try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); eRefType rt = attacher.getRefTypeByName(typeName); Py::Dict ret; ret["TypeIndex"] = Py::Long(rt); ret["Rank"] = Py::Long(AttachEngine::getTypeRank(rt)); try { - Py::Module module(PyImport_ImportModule("PartGui"),true); + Py::Module module(PyImport_ImportModule("PartGui"), true); if (module.isNull() || !module.hasAttr("AttachEngineResources")) { - // in v0.14+, the GUI module can be loaded in console mode (but doesn't have all its document methods) - throw Py::RuntimeError("Gui is not up");//DeepSOIC: wanted to throw ImportError here, but it's not defined, so I don't know... + // in v0.14+, the GUI module can be loaded in console mode (but doesn't have all its + // document methods) + throw Py::RuntimeError("Gui is not up"); // DeepSOIC: wanted to throw ImportError + // here, but it's not defined, so I don't + // know... } Py::Object submod(module.getAttr("AttachEngineResources")); Py::Callable method(submod.getAttr("getRefTypeUserFriendlyName")); @@ -381,115 +431,126 @@ PyObject* AttachEnginePy::getRefTypeInfo(PyObject* args) arg.setItem(0, Py::Long(rt)); Py::String st = method.apply(arg); ret["UserFriendlyName"] = st; - } catch (Py::Exception& e) { + } + catch (Py::Exception& e) { if (PyErr_ExceptionMatches(PyExc_ImportError)) { // the GUI is not up. - Base::Console().warning("AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n"); + Base::Console().warning( + "AttachEngine: Gui not up, so no gui-related entries in getModeInfo.\n" + ); e.clear(); - } else { + } + else { Base::Console().warning("AttachEngine.getRefTypeInfo: error obtaining GUI strings\n"); e.clear(); } - } catch (Base::Exception &e){ + } + catch (Base::Exception& e) { Base::Console().warning("AttachEngine.getRefTypeInfo: error obtaining GUI strings:"); Base::Console().warning(e.what()); Base::Console().warning("\n"); } return Py::new_reference_to(ret); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::copy(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } return new AttachEnginePy(this->getAttachEnginePtr()->copy()); } PyObject* AttachEnginePy::calculateAttachedPlacement(PyObject* args) const { - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &pcObj)) { return nullptr; - try{ + } + try { const Base::Placement& plm = *(static_cast(pcObj)->getPlacementPtr()); Base::Placement result; - try{ + try { result = this->getAttachEnginePtr()->calculateAttachedPlacement(plm); - } catch (ExceptionCancel&) { + } + catch (ExceptionCancel&) { Py_IncRef(Py_None); return Py_None; } return new Base::PlacementPy(new Base::Placement(result)); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; return nullptr; } PyObject* AttachEnginePy::suggestModes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - AttachEngine &attacher = *(this->getAttachEnginePtr()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); SuggestResult sugr; attacher.suggestMapModes(sugr); Py::Dict result; - { //sugr.allApplicableModes + { // sugr.allApplicableModes Py::List pyList; - for(eMapMode mmode: sugr.allApplicableModes){ + for (eMapMode mmode : sugr.allApplicableModes) { pyList.append(Py::String(AttachEngine::getModeName(mmode))); } result["allApplicableModes"] = pyList; } - { //sugr.bestFitMode + { // sugr.bestFitMode result["bestFitMode"] = Py::String(AttachEngine::getModeName(sugr.bestFitMode)); } - {//sugr.error + { // sugr.error bool isError = sugr.message == SuggestResult::srUnexpectedError - || sugr.message == SuggestResult::srLinkBroken; + || sugr.message == SuggestResult::srLinkBroken; result["error"] = Py::String(isError ? sugr.error.what() : ""); } - {//sugr.message + { // sugr.message std::string msg; - switch(sugr.message){ - case SuggestResult::srIncompatibleGeometry: - msg = "IncompatibleGeometry"; - break; - case SuggestResult::srLinkBroken: - msg = "LinkBroken"; - break; - case SuggestResult::srNoModesFit: - msg = "NoModesFit"; - break; - case SuggestResult::srOK: - msg = "OK"; - break; - case SuggestResult::srUnexpectedError: - msg = "UnexpectedError"; - break; - default: - msg = ""; + switch (sugr.message) { + case SuggestResult::srIncompatibleGeometry: + msg = "IncompatibleGeometry"; + break; + case SuggestResult::srLinkBroken: + msg = "LinkBroken"; + break; + case SuggestResult::srNoModesFit: + msg = "NoModesFit"; + break; + case SuggestResult::srOK: + msg = "OK"; + break; + case SuggestResult::srUnexpectedError: + msg = "UnexpectedError"; + break; + default: + msg = ""; } result["message"] = Py::String(msg); } - {//sugr.nextRefTypeHint + { // sugr.nextRefTypeHint Py::List pyList; - for(eRefType rt : sugr.nextRefTypeHint){ + for (eRefType rt : sugr.nextRefTypeHint) { pyList.append(Py::String(AttachEngine::getRefTypeName(rt))); } result["nextRefTypeHint"] = pyList; } - {//sugr.reachableModes + { // sugr.reachableModes Py::Dict pyRM; - for(std::pair &rm: sugr.reachableModes){ + for (std::pair& rm : sugr.reachableModes) { Py::List pyListOfCombinations; - for(refTypeString &rts : rm.second){ + for (refTypeString& rts : rm.second) { Py::List pyCombination; - for(eRefType rt : rts){ + for (eRefType rt : rts) { pyCombination.append(Py::String(AttachEngine::getRefTypeName(rt))); } pyListOfCombinations.append(pyCombination); @@ -498,63 +559,71 @@ PyObject* AttachEnginePy::suggestModes(PyObject* args) } result["reachableModes"] = pyRM; } - {//sugr.references_Types + { // sugr.references_Types Py::List pyList; - for(eRefType rt : sugr.references_Types){ + for (eRefType rt : sugr.references_Types) { pyList.append(Py::String(AttachEngine::getRefTypeName(rt))); } result["references_Types"] = pyList; } return Py::new_reference_to(result); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::readParametersFromFeature(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type),&obj)) + if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &obj)) { return nullptr; + } - try{ + try { App::DocumentObjectPy* dobjpy = static_cast(obj); App::DocumentObject* dobj = dobjpy->getDocumentObjectPtr(); - if (! dobj->hasExtension(Part::AttachExtension::getExtensionClassTypeId())){ + if (!dobj->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) { throw Py::TypeError("Supplied object has no Part::AttachExtension"); } Part::AttachExtension* feat = dobj->getExtensionByType(); - AttachEngine &attacher = *(this->getAttachEnginePtr()); - attacher.setUp(feat->AttachmentSupport, - eMapMode(feat->MapMode.getValue()), - feat->MapReversed.getValue(), - feat->MapPathParameter.getValue(), - 0.0,0.0, - feat->AttachmentOffset.getValue()); + AttachEngine& attacher = *(this->getAttachEnginePtr()); + attacher.setUp( + feat->AttachmentSupport, + eMapMode(feat->MapMode.getValue()), + feat->MapReversed.getValue(), + feat->MapPathParameter.getValue(), + 0.0, + 0.0, + feat->AttachmentOffset.getValue() + ); return Py::new_reference_to(Py::None()); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::writeParametersToFeature(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O!",&(App::DocumentObjectPy::Type),&obj)) + if (!PyArg_ParseTuple(args, "O!", &(App::DocumentObjectPy::Type), &obj)) { return nullptr; + } - try{ + try { App::DocumentObjectPy* dobjpy = static_cast(obj); App::DocumentObject* dobj = dobjpy->getDocumentObjectPtr(); - if (! dobj->hasExtension(Part::AttachExtension::getExtensionClassTypeId())){ + if (!dobj->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) { throw Py::TypeError("Supplied object has no Part::AttachExtension"); } Part::AttachExtension* feat = dobj->getExtensionByType(); - const AttachEngine &attacher = *(this->getAttachEnginePtr()); - feat->AttachmentSupport.setValues(attacher.getRefObjects(),attacher.getSubValues()); + const AttachEngine& attacher = *(this->getAttachEnginePtr()); + feat->AttachmentSupport.setValues(attacher.getRefObjects(), attacher.getSubValues()); feat->MapMode.setValue(attacher.mapMode); feat->MapReversed.setValue(attacher.mapReverse); feat->MapPathParameter.setValue(attacher.attachParameter); feat->AttachmentOffset.setValue(attacher.attachmentOffset); return Py::new_reference_to(Py::None()); - } ATTACHERPY_STDCATCH_METH; + } + ATTACHERPY_STDCATCH_METH; } PyObject* AttachEnginePy::getCustomAttributes(const char*) const @@ -562,7 +631,7 @@ PyObject* AttachEnginePy::getCustomAttributes(const char*) const return nullptr; } -int AttachEnginePy::setCustomAttributes(const char*,PyObject*) +int AttachEnginePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/AttachExtension.cpp b/src/Mod/Part/App/AttachExtension.cpp index 0736dd56ff..cd812a61d3 100644 --- a/src/Mod/Part/App/AttachExtension.cpp +++ b/src/Mod/Part/App/AttachExtension.cpp @@ -41,109 +41,119 @@ using namespace Attacher; namespace { - std::vector EngineEnums = {"Engine 3D", - "Engine Plane", - "Engine Line", - "Engine Point"}; - - const char* enumToClass(const char* mode) - { - if (EngineEnums.at(0) == mode) { - return "Attacher::AttachEngine3D"; - } - if (EngineEnums.at(1) == mode) { - return "Attacher::AttachEnginePlane"; - } - if (EngineEnums.at(2) == mode) { - return "Attacher::AttachEngineLine"; - } - if (EngineEnums.at(3) == mode) { - return "Attacher::AttachEnginePoint"; - } +std::vector EngineEnums = {"Engine 3D", "Engine Plane", "Engine Line", "Engine Point"}; +const char* enumToClass(const char* mode) +{ + if (EngineEnums.at(0) == mode) { return "Attacher::AttachEngine3D"; } + if (EngineEnums.at(1) == mode) { + return "Attacher::AttachEnginePlane"; + } + if (EngineEnums.at(2) == mode) { + return "Attacher::AttachEngineLine"; + } + if (EngineEnums.at(3) == mode) { + return "Attacher::AttachEnginePoint"; + } - const char* classToEnum(const char* type) - { - if (strcmp(type, "Attacher::AttachEngine3D") == 0) { - return EngineEnums.at(0).c_str(); - } - if (strcmp(type, "Attacher::AttachEnginePlane") == 0) { - return EngineEnums.at(1).c_str(); - } - if (strcmp(type, "Attacher::AttachEngineLine") == 0) { - return EngineEnums.at(2).c_str(); - } - if (strcmp(type, "Attacher::AttachEnginePoint") == 0) { - return EngineEnums.at(3).c_str(); - } + return "Attacher::AttachEngine3D"; +} +const char* classToEnum(const char* type) +{ + if (strcmp(type, "Attacher::AttachEngine3D") == 0) { return EngineEnums.at(0).c_str(); } + if (strcmp(type, "Attacher::AttachEnginePlane") == 0) { + return EngineEnums.at(1).c_str(); + } + if (strcmp(type, "Attacher::AttachEngineLine") == 0) { + return EngineEnums.at(2).c_str(); + } + if (strcmp(type, "Attacher::AttachEnginePoint") == 0) { + return EngineEnums.at(3).c_str(); + } - void restoreAttacherEngine(AttachExtension* self) - { - const char* mode = enumToClass(self->AttacherEngine.getValueAsString()); - const char* type = self->AttacherType.getValue(); - if (strcmp(mode, type) != 0) { - self->AttacherEngine.setValue(classToEnum(type)); - } + return EngineEnums.at(0).c_str(); +} + +void restoreAttacherEngine(AttachExtension* self) +{ + const char* mode = enumToClass(self->AttacherEngine.getValueAsString()); + const char* type = self->AttacherType.getValue(); + if (strcmp(mode, type) != 0) { + self->AttacherEngine.setValue(classToEnum(type)); } } +} // namespace EXTENSION_PROPERTY_SOURCE(Part::AttachExtension, App::DocumentObjectExtension) AttachExtension::AttachExtension() { - EXTENSION_ADD_PROPERTY_TYPE(AttacherType, - ("Attacher::AttachEngine3D"), - "Attachment", - (App::PropertyType)(App::Prop_ReadOnly | App::Prop_Hidden), - "Class name of attach engine object driving the attachment."); + EXTENSION_ADD_PROPERTY_TYPE( + AttacherType, + ("Attacher::AttachEngine3D"), + "Attachment", + (App::PropertyType)(App::Prop_ReadOnly | App::Prop_Hidden), + "Class name of attach engine object driving the attachment." + ); - EXTENSION_ADD_PROPERTY_TYPE(AttacherEngine, - (0L), - "Attachment", - (App::PropertyType)(App::Prop_None), - "Attach engine object driving the attachment."); + EXTENSION_ADD_PROPERTY_TYPE( + AttacherEngine, + (0L), + "Attachment", + (App::PropertyType)(App::Prop_None), + "Attach engine object driving the attachment." + ); AttacherEngine.setEnums(EngineEnums); - EXTENSION_ADD_PROPERTY_TYPE(AttachmentSupport, - (nullptr, nullptr), - "Attachment", - (App::PropertyType)(App::Prop_None), - "Support of the 2D geometry"); + EXTENSION_ADD_PROPERTY_TYPE( + AttachmentSupport, + (nullptr, nullptr), + "Attachment", + (App::PropertyType)(App::Prop_None), + "Support of the 2D geometry" + ); AttachmentSupport.setScope(App::LinkScope::Global); - EXTENSION_ADD_PROPERTY_TYPE(MapMode, - (mmDeactivated), - "Attachment", - App::Prop_None, - "Mode of attachment to other object"); + EXTENSION_ADD_PROPERTY_TYPE( + MapMode, + (mmDeactivated), + "Attachment", + App::Prop_None, + "Mode of attachment to other object" + ); MapMode.setEditorName("PartGui::PropertyEnumAttacherItem"); MapMode.setEnums(AttachEngine::eMapModeStrings); // a rough test if mode string list in Attacher.cpp is in sync with eMapMode enum. assert(MapMode.getEnumVector().size() == mmDummy_NumberOfModes); - EXTENSION_ADD_PROPERTY_TYPE(MapReversed, - (false), - "Attachment", - App::Prop_None, - "Reverse Z-direction (flip sketch upside down)"); + EXTENSION_ADD_PROPERTY_TYPE( + MapReversed, + (false), + "Attachment", + App::Prop_None, + "Reverse Z-direction (flip sketch upside down)" + ); - EXTENSION_ADD_PROPERTY_TYPE(MapPathParameter, - (0.0), - "Attachment", - App::Prop_None, - "Sets point of curve to map the sketch to. 0..1 = start..end"); + EXTENSION_ADD_PROPERTY_TYPE( + MapPathParameter, + (0.0), + "Attachment", + App::Prop_None, + "Sets point of curve to map the sketch to. 0..1 = start..end" + ); EXTENSION_ADD_PROPERTY_TYPE( AttachmentOffset, (Base::Placement()), "Attachment", App::Prop_None, - "Extra placement to apply in addition to attachment (in local coordinates)"); + "Extra placement to apply in addition to attachment (in local coordinates)" + ); // Only show these properties when applicable. Controlled by extensionOnChanged this->MapPathParameter.setStatus(App::Property::Status::Hidden, true); @@ -168,12 +178,14 @@ AttachExtension::~AttachExtension() {} template -static inline bool getProp(bool force, - T*& prop, - Base::Type type, - App::PropertyContainer* owner, - const char* name, - const char* doc) +static inline bool getProp( + bool force, + T*& prop, + Base::Type type, + App::PropertyContainer* owner, + const char* name, + const char* doc +) { prop = freecad_cast(owner->getDynamicPropertyByName(name)); if (prop || !force) { @@ -189,8 +201,13 @@ static inline bool getProp(bool force, } template -static inline bool -getProp(bool force, T*& prop, App::PropertyContainer* owner, const char* name, const char* doc) +static inline bool getProp( + bool force, + T*& prop, + App::PropertyContainer* owner, + const char* name, + const char* doc +) { return getProp(force, prop, T::getClassTypeId(), owner, name, doc); } @@ -211,25 +228,30 @@ void AttachExtension::initBase(bool force) props.attacherType, obj, "BaseAttacherType", - "Class name of attach engine object driving the attachment for base geometry.")) { + "Class name of attach engine object driving the attachment for base geometry." + )) { props.attacherType->setValue(_baseProps.attacher->getTypeId().getName()); } else if (!props.attacherType) { return; } - getProp(force, - props.attachment, - App::PropertyLinkSubListHidden::getClassTypeId(), - obj, - "BaseAttachment", - "Link to base geometry."); + getProp( + force, + props.attachment, + App::PropertyLinkSubListHidden::getClassTypeId(), + obj, + "BaseAttachment", + "Link to base geometry." + ); - if (getProp(force, - props.mapMode, - obj, - "BaseMapMode", - "Mode of attachment for the base geometry")) { + if (getProp( + force, + props.mapMode, + obj, + "BaseMapMode", + "Mode of attachment for the base geometry" + )) { props.mapMode->setStatus(App::Property::Status::Hidden, false); } if (props.mapMode) { @@ -237,17 +259,21 @@ void AttachExtension::initBase(bool force) props.mapMode->setEnums(AttachEngine::eMapModeStrings); } - getProp(force, - props.mapReversed, - obj, - "BaseMapReversed", - "Reverse Z-direction of the base geometry attachment"); + getProp( + force, + props.mapReversed, + obj, + "BaseMapReversed", + "Reverse Z-direction of the base geometry attachment" + ); - getProp(force, - props.mapPathParameter, - obj, - "BaseMapPathParameter", - "Sets point of base curve to map 0..1 = start..end"); + getProp( + force, + props.mapPathParameter, + obj, + "BaseMapPathParameter", + "Sets point of base curve to map 0..1 = start..end" + ); static_cast(_baseProps) = props; } @@ -297,8 +323,9 @@ bool AttachExtension::changeAttacherType(const char* typeName, bool base) } Base::Type t = Base::Type::fromName(typeName); if (t.isDerivedFrom(AttachEngine::getClassTypeId())) { - AttachEngine* pNewAttacher = - static_cast(Base::Type::createInstanceByName(typeName)); + AttachEngine* pNewAttacher = static_cast( + Base::Type::createInstanceByName(typeName) + ); this->setAttacher(pNewAttacher, base); return true; } @@ -313,7 +340,8 @@ bool AttachExtension::positionBySupport() _active = 0; if (!_props.attacher) { throw Base::RuntimeError( - "AttachExtension: can't positionBySupport, because no AttachEngine is set."); + "AttachExtension: can't positionBySupport, because no AttachEngine is set." + ); } updateAttacherVals(); Base::Placement plaOriginal = getPlacement().getValue(); @@ -327,11 +355,13 @@ bool AttachExtension::positionBySupport() Base::Placement basePlacement; if (_baseProps.attacher && _baseProps.attacher->mapMode != mmDeactivated) { - basePlacement = - _baseProps.attacher->calculateAttachedPlacement(Base::Placement(), &subChanged); + basePlacement + = _baseProps.attacher->calculateAttachedPlacement(Base::Placement(), &subChanged); if (subChanged) { - _baseProps.attachment->setValues(_baseProps.attachment->getValues(), - _baseProps.attacher->getSubValues()); + _baseProps.attachment->setValues( + _baseProps.attachment->getValues(), + _baseProps.attacher->getSubValues() + ); } } @@ -341,9 +371,9 @@ bool AttachExtension::positionBySupport() if (subChanged) { Base::ObjectStatusLocker guard( App::Property::User3, - &AttachmentSupport); - AttachmentSupport.setValues(AttachmentSupport.getValues(), - _props.attacher->getSubValues()); + &AttachmentSupport + ); + AttachmentSupport.setValues(AttachmentSupport.getValues(), _props.attacher->getSubValues()); } getPlacement().setValue(placement); _active = 1; @@ -410,23 +440,20 @@ void AttachExtension::extensionOnChanged(const App::Property* prop) if (!getExtendedObject()->isRestoring()) { // If we change anything that affects our position, update it immediately so you can see it // interactively. - if ((prop == &AttachmentSupport - || prop == &MapMode - || prop == &MapPathParameter - || prop == &MapReversed - || prop == &AttachmentOffset)){ + if ((prop == &AttachmentSupport || prop == &MapMode || prop == &MapPathParameter + || prop == &MapReversed || prop == &AttachmentOffset)) { bool bAttached = false; - try{ + try { bAttached = positionBySupport(); } - catch (Base::Exception &e) { + catch (Base::Exception& e) { getExtendedObject()->setStatus(App::Error, true); - Base::Console().error("PositionBySupport: %s\n",e.what()); - //set error message - how? + Base::Console().error("PositionBySupport: %s\n", e.what()); + // set error message - how? } - catch (Standard_Failure &e){ + catch (Standard_Failure& e) { getExtendedObject()->setStatus(App::Error, true); - Base::Console().error("PositionBySupport: %s\n",e.GetMessageString()); + Base::Console().error("PositionBySupport: %s\n", e.GetMessageString()); } updateSinglePropertyStatus(bAttached); @@ -455,9 +482,11 @@ void AttachExtension::extensionOnChanged(const App::Property* prop) App::DocumentObjectExtension::extensionOnChanged(prop); } -bool AttachExtension::extensionHandleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) +bool AttachExtension::extensionHandleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName +) { Base::Type type = Base::Type::fromName(TypeName); // superPlacement -> AttachmentOffset @@ -494,7 +523,8 @@ void AttachExtension::handleLegacyTangentPlaneOrientation() // check stored document program version (applies to v1.0 and earlier only) int major, minor; - if (sscanf(getExtendedObject()->getDocument()->getProgramVersion(), "%d.%d", &major, &minor) != 2) { + if (sscanf(getExtendedObject()->getDocument()->getProgramVersion(), "%d.%d", &major, &minor) + != 2) { return; } if (major > 1 || (major == 1 && minor > 0)) { @@ -540,8 +570,7 @@ void AttachExtension::handleLegacyTangentPlaneOrientation() */ App::DocumentObject* owner = getExtendedObject(); - Base::Console().message("Converting attachment offset of %s\n", - owner->getNameInDocument()); + Base::Console().message("Converting attachment offset of %s\n", owner->getNameInDocument()); try { // extract current attachment offset values @@ -552,25 +581,27 @@ void AttachExtension::handleLegacyTangentPlaneOrientation() rotation.getYawPitchRoll(yaw, pitch, roll); // extract existing expressions - auto buildOID = [owner](const std::vector& path) { + auto buildOID = [owner](const std::vector& path) { App::ObjectIdentifier oid(owner, true); for (const auto& name : path) { oid.addComponent(App::ObjectIdentifier::SimpleComponent(name)); } return oid; }; - App::ObjectIdentifier oidX = buildOID ({"AttachmentOffset", "Base", "x"}); - App::ObjectIdentifier oidY = buildOID ({"AttachmentOffset", "Base", "y"}); - App::ObjectIdentifier oidYaw = buildOID ({"AttachmentOffset", "Rotation", "Yaw"}); + App::ObjectIdentifier oidX = buildOID({"AttachmentOffset", "Base", "x"}); + App::ObjectIdentifier oidY = buildOID({"AttachmentOffset", "Base", "y"}); + App::ObjectIdentifier oidYaw = buildOID({"AttachmentOffset", "Rotation", "Yaw"}); const App::Expression* exprX = nullptr; const App::Expression* exprY = nullptr; const App::Expression* exprYaw = nullptr; for (const auto& [oid, expr] : owner->ExpressionEngine.getExpressions()) { if (oid == oidX) { exprX = expr; - } else if (oid == oidY) { + } + else if (oid == oidY) { exprY = expr; - } else if (oid == oidYaw) { + } + else if (oid == oidYaw) { exprYaw = expr; } } @@ -579,7 +610,7 @@ void AttachExtension::handleLegacyTangentPlaneOrientation() App::Expression* newExprX = nullptr; App::Expression* newExprY = nullptr; App::Expression* newExprYaw = nullptr; - if (axis == 0) { // normal mostly X + if (axis == 0) { // normal mostly X // values std::swap(position.x, position.y); position.x = -position.x; @@ -598,7 +629,7 @@ void AttachExtension::handleLegacyTangentPlaneOrientation() newExprYaw = App::ExpressionParser::parse(owner, expr.c_str()); } } - else if (axis == 1) { // normal mostly Y + else if (axis == 1) { // normal mostly Y // values std::swap(position.x, position.y); position.y = -position.y; @@ -633,11 +664,13 @@ void AttachExtension::handleLegacyTangentPlaneOrientation() placement.setPosition(position); placement.setRotation(rotation); this->AttachmentOffset.setValue(placement); - - } catch (const Base::Exception& e) { - Base::Console().error("Error converting legacy attachment offset of %s: %s\n", - owner->getNameInDocument(), - e.what()); + } + catch (const Base::Exception& e) { + Base::Console().error( + "Error converting legacy attachment offset of %s: %s\n", + owner->getNameInDocument(), + e.what() + ); } } @@ -679,14 +712,17 @@ void AttachExtension::updateSinglePropertyStatus(bool bAttached, bool base) // Hide properties when not applicable to reduce user confusion eMapMode mmode = eMapMode(props.mapMode->getValue()); - bool modeIsPointOnCurve = - (mmode == mmNormalToPath || mmode == mmFrenetNB || mmode == mmFrenetTN - || mmode == mmFrenetTB || mmode == mmRevolutionSection || mmode == mmConcentric); + bool modeIsPointOnCurve + = (mmode == mmNormalToPath || mmode == mmFrenetNB || mmode == mmFrenetTN + || mmode == mmFrenetTB || mmode == mmRevolutionSection || mmode == mmConcentric); // MapPathParameter is only used if there is a reference to one edge and not edge + vertex bool hasOneRef = props.attacher && props.attacher->subnames.size() == 1; - props.mapPathParameter->setStatus(App::Property::Status::Hidden, !bAttached || !(modeIsPointOnCurve && hasOneRef)); + props.mapPathParameter->setStatus( + App::Property::Status::Hidden, + !bAttached || !(modeIsPointOnCurve && hasOneRef) + ); props.mapReversed->setStatus(App::Property::Status::Hidden, !bAttached); if (base) { @@ -716,12 +752,14 @@ void AttachExtension::updateAttacherVals(bool base) const if (!props.attachment) { return; } - attacher(base).setUp(*props.attachment, - eMapMode(props.mapMode->getValue()), - props.mapReversed->getValue(), - props.mapPathParameter->getValue(), - 0.0, - 0.0); + attacher(base).setUp( + *props.attachment, + eMapMode(props.mapMode->getValue()), + props.mapReversed->getValue(), + props.mapPathParameter->getValue(), + 0.0, + 0.0 + ); } AttachExtension::Properties AttachExtension::getProperties(bool base) const @@ -741,7 +779,8 @@ AttachExtension::Properties AttachExtension::getInitedProperties(bool base) App::PropertyPlacement& AttachExtension::getPlacement() const { auto pla = freecad_cast( - getExtendedObject()->getPropertyByName("Placement")); + getExtendedObject()->getPropertyByName("Placement") + ); if (!pla) { throw Base::RuntimeError("AttachExtension cannot find placement property"); } @@ -782,12 +821,12 @@ AttachEngineException::AttachEngineException(const std::string& sMessage) : Base::Exception(sMessage) {} -namespace App { +namespace App +{ /// @cond DOXERR - EXTENSION_PROPERTY_SOURCE_TEMPLATE(Part::AttachExtensionPython, Part::AttachExtension) +EXTENSION_PROPERTY_SOURCE_TEMPLATE(Part::AttachExtensionPython, Part::AttachExtension) /// @endcond // explicit template instantiation - template class PartExport ExtensionPythonT; -} - +template class PartExport ExtensionPythonT; +} // namespace App diff --git a/src/Mod/Part/App/AttachExtension.h b/src/Mod/Part/App/AttachExtension.h index 6969260e2a..83d79c325e 100644 --- a/src/Mod/Part/App/AttachExtension.h +++ b/src/Mod/Part/App/AttachExtension.h @@ -22,9 +22,9 @@ * * ***************************************************************************/ /** - * AttachExtensionh, .cpp contain a extension class to derive other features from, to make - * them attachable. - */ + * AttachExtensionh, .cpp contain a extension class to derive other features from, to make + * them attachable. + */ #ifndef PARTATTACHABLEOBJECT_H #define PARTATTACHABLEOBJECT_H @@ -140,9 +140,11 @@ public: protected: void extensionOnChanged(const App::Property* /*prop*/) override; - virtual bool extensionHandleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + virtual bool extensionHandleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; App::PropertyPlacement& getPlacement() const; void initBase(bool force); @@ -170,6 +172,6 @@ private: using AttachExtensionPython = App::ExtensionPythonT; -} // namespace Part +} // namespace Part -#endif // PARTATTACHABLEOBJECT_H +#endif // PARTATTACHABLEOBJECT_H diff --git a/src/Mod/Part/App/AttachExtension.pyi b/src/Mod/Part/App/AttachExtension.pyi index f31bce5873..37160ef4cd 100644 --- a/src/Mod/Part/App/AttachExtension.pyi +++ b/src/Mod/Part/App/AttachExtension.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from App.DocumentObjectExtension import DocumentObjectExtension from typing import Any, Final - @export( Twin="AttachExtension", TwinPointer="AttachExtension", diff --git a/src/Mod/Part/App/AttachExtensionPyImp.cpp b/src/Mod/Part/App/AttachExtensionPyImp.cpp index 7f0c23072c..9d0d98b96a 100644 --- a/src/Mod/Part/App/AttachExtensionPyImp.cpp +++ b/src/Mod/Part/App/AttachExtensionPyImp.cpp @@ -36,35 +36,41 @@ std::string AttachExtensionPy::representation() const return {""}; } -PyObject* AttachExtensionPy::positionBySupport(PyObject *args) +PyObject* AttachExtensionPy::positionBySupport(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } bool bAttached = false; - try{ + try { bAttached = this->getAttachExtensionPtr()->positionBySupport(); - } catch (Standard_Failure& e) { + } + catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); return nullptr; - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.setPyException(); return nullptr; } return Py::new_reference_to(Py::Boolean(bAttached)); } -PyObject* AttachExtensionPy::changeAttacherType(PyObject *args) +PyObject* AttachExtensionPy::changeAttacherType(PyObject* args) { const char* typeName; - if (!PyArg_ParseTuple(args, "s", &typeName)) + if (!PyArg_ParseTuple(args, "s", &typeName)) { return nullptr; + } bool ret; - try{ + try { ret = this->getAttachExtensionPtr()->changeAttacherType(typeName); - } catch (Standard_Failure& e) { + } + catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); return nullptr; - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.setPyException(); return nullptr; } @@ -74,23 +80,28 @@ PyObject* AttachExtensionPy::changeAttacherType(PyObject *args) Py::Object AttachExtensionPy::getAttacher() const { try { - this->getAttachExtensionPtr()->attacher(); //throws if attacher is not set - } catch (Base::Exception&) { + this->getAttachExtensionPtr()->attacher(); // throws if attacher is not set + } + catch (Base::Exception&) { return Py::None(); } try { - return Py::Object( new Attacher::AttachEnginePy(this->getAttachExtensionPtr()->attacher().copy()), true); - } catch (Standard_Failure& e) { + return Py::Object( + new Attacher::AttachEnginePy(this->getAttachExtensionPtr()->attacher().copy()), + true + ); + } + catch (Standard_Failure& e) { throw Py::Exception(Part::PartExceptionOCCError, e.GetMessageString()); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.setPyException(); throw Py::Exception(); } - } -PyObject *AttachExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* AttachExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -99,5 +110,3 @@ int AttachExtensionPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj { return 0; } - - diff --git a/src/Mod/Part/App/Attacher.cpp b/src/Mod/Part/App/Attacher.cpp index 27238c5682..8c2ad1c43d 100644 --- a/src/Mod/Part/App/Attacher.cpp +++ b/src/Mod/Part/App/Attacher.cpp @@ -22,45 +22,45 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -77,8 +77,8 @@ using namespace Part; using namespace Attacher; -//These strings are for mode list enum property. -const char* AttachEngine::eMapModeStrings[]= { +// These strings are for mode list enum property. +const char* AttachEngine::eMapModeStrings[] = { "Deactivated", "Translate", "ObjectXY", @@ -142,39 +142,21 @@ const char* AttachEngine::eMapModeStrings[]= { "ParallelPlane", "MidPoint", - nullptr}; - -//this list must be in sync with eRefType enum. -//These strings are used only by Py interface of Attacher. Strings for use in Gui are in Mod/Part/Gui/AttacherTexts.cpp -const char* AttachEngine::eRefTypeStrings[]= { - "Any", - "Vertex", - "Edge", - "Face", - - "Line", - "Curve", - "Circle", - "Conic", - "Ellipse", - "Parabola", - "Hyperbola", - - "Plane", - "Sphere", - "Revolve", - "Cylinder", - "Torus", - "Cone", - - "Object", - "Solid", - "Wire", nullptr }; +// this list must be in sync with eRefType enum. +// These strings are used only by Py interface of Attacher. Strings for use in Gui are in +// Mod/Part/Gui/AttacherTexts.cpp +const char* AttachEngine::eRefTypeStrings[] = {"Any", "Vertex", "Edge", "Face", + "Line", "Curve", "Circle", "Conic", + "Ellipse", "Parabola", "Hyperbola", + "Plane", "Sphere", "Revolve", "Cylinder", + "Torus", "Cone", + + "Object", "Solid", "Wire", nullptr}; TYPESYSTEM_SOURCE_ABSTRACT(Attacher::AttachEngine, Base::BaseClass) @@ -218,8 +200,10 @@ void AttachEngine::setReferences(const std::vector& references) std::vector shadowSubs; for (auto& ref : references) { if (!ref.getSubObject()) { - FC_THROWM(AttachEngineException, - "AttachEngine::invalid object " << ref.getSubObjectFullName()); + FC_THROWM( + AttachEngineException, + "AttachEngine::invalid object " << ref.getSubObjectFullName() + ); } if (docname.empty()) { docname = ref.getDocumentName(); @@ -237,11 +221,15 @@ void AttachEngine::setReferences(const std::vector& references) this->shadowSubs = std::move(shadowSubs); } -void AttachEngine::setUp(const App::PropertyLinkSubList &references, - eMapMode mapMode, bool mapReverse, - double attachParameter, - double surfU, double surfV, - const Base::Placement &attachmentOffset) +void AttachEngine::setUp( + const App::PropertyLinkSubList& references, + eMapMode mapMode, + bool mapReverse, + double attachParameter, + double surfU, + double surfV, + const Base::Placement& attachmentOffset +) { setReferences(references); this->mapMode = mapMode; @@ -252,7 +240,7 @@ void AttachEngine::setUp(const App::PropertyLinkSubList &references, this->attachmentOffset = attachmentOffset; } -void AttachEngine::setUp(const AttachEngine &another) +void AttachEngine::setUp(const AttachEngine& another) { this->docName = another.docName; this->objNames = another.objNames; @@ -266,67 +254,70 @@ void AttachEngine::setUp(const AttachEngine &another) this->attachmentOffset = another.attachmentOffset; } -void AttachEngine::setOffset(const Base::Placement &offset) +void AttachEngine::setOffset(const Base::Placement& offset) { this->attachmentOffset = offset; } -Base::Placement AttachEngine::placementFactory(const gp_Dir &ZAxis, - gp_Vec XAxis, - gp_Pnt Origin, - gp_Pnt refOrg, - bool useRefOrg_Line, - bool useRefOrg_Plane, - bool makeYVertical, - bool makeLegacyFlatFaceOrientation, - Base::Placement* placeOfRef) const +Base::Placement AttachEngine::placementFactory( + const gp_Dir& ZAxis, + gp_Vec XAxis, + gp_Pnt Origin, + gp_Pnt refOrg, + bool useRefOrg_Line, + bool useRefOrg_Plane, + bool makeYVertical, + bool makeLegacyFlatFaceOrientation, + Base::Placement* placeOfRef +) const { - if(useRefOrg_Line){ - //move Origin to projection of refOrg onto ZAxis + if (useRefOrg_Line) { + // move Origin to projection of refOrg onto ZAxis gp_Vec refOrgV = gp_Vec(refOrg.XYZ()); gp_Vec OriginV = gp_Vec(Origin.XYZ()); gp_Vec ZAxisV = gp_Vec(ZAxis); - Origin = gp_Pnt(( - OriginV + ZAxisV*ZAxisV.Dot(refOrgV-OriginV) - ).XYZ()); + Origin = gp_Pnt((OriginV + ZAxisV * ZAxisV.Dot(refOrgV - OriginV)).XYZ()); } - if(useRefOrg_Plane){ - //move Origin to projection of refOrg onto plane (ZAxis, Origin) + if (useRefOrg_Plane) { + // move Origin to projection of refOrg onto plane (ZAxis, Origin) gp_Vec refOrgV = gp_Vec(refOrg.XYZ()); gp_Vec OriginV = gp_Vec(Origin.XYZ()); gp_Vec ZAxisV = gp_Vec(ZAxis); - Origin = gp_Pnt(( - refOrgV + ZAxisV*ZAxisV.Dot(OriginV-refOrgV) - ).XYZ()); + Origin = gp_Pnt((refOrgV + ZAxisV * ZAxisV.Dot(OriginV - refOrgV)).XYZ()); } - if (XAxis.Magnitude() < Precision::Confusion()) + if (XAxis.Magnitude() < Precision::Confusion()) { makeYVertical = true; + } - gp_Ax3 ax3;//OCC representation of the final placement + gp_Ax3 ax3; // OCC representation of the final placement if (!makeYVertical) { ax3 = gp_Ax3(Origin, ZAxis, XAxis); } else if (!makeLegacyFlatFaceOrientation) { - //align Y along Z, if possible - gp_Vec YAxis(0.0,0.0,1.0); + // align Y along Z, if possible + gp_Vec YAxis(0.0, 0.0, 1.0); XAxis = YAxis.Crossed(gp_Vec(ZAxis)); - if (XAxis.Magnitude() < Precision::Confusion()){ - //ZAxis is along true ZAxis - XAxis = (gp_Vec(1,0,0)*ZAxis.Z()).Normalized(); + if (XAxis.Magnitude() < Precision::Confusion()) { + // ZAxis is along true ZAxis + XAxis = (gp_Vec(1, 0, 0) * ZAxis.Z()).Normalized(); } ax3 = gp_Ax3(Origin, ZAxis, XAxis); } else if (makeLegacyFlatFaceOrientation) { - //find out, to which axis of support Normal is closest to. - //The result will be written into pos variable (0..2 = X..Z) - if (!placeOfRef) - throw AttachEngineException("AttachEngine::placementFactory: for Legacy mode, placement of the reference must be supplied. Got null instead!"); - Base::Placement &Place = *placeOfRef; - Base::Vector3d dX,dY,dZ;//internal axes of support object, as they are in global space - Place.getRotation().multVec(Base::Vector3d(1,0,0),dX); - Place.getRotation().multVec(Base::Vector3d(0,1,0),dY); - Place.getRotation().multVec(Base::Vector3d(0,0,1),dZ); + // find out, to which axis of support Normal is closest to. + // The result will be written into pos variable (0..2 = X..Z) + if (!placeOfRef) { + throw AttachEngineException( + "AttachEngine::placementFactory: for Legacy mode, placement of the reference must " + "be supplied. Got null instead!" + ); + } + Base::Placement& Place = *placeOfRef; + Base::Vector3d dX, dY, dZ; // internal axes of support object, as they are in global space + Place.getRotation().multVec(Base::Vector3d(1, 0, 0), dX); + Place.getRotation().multVec(Base::Vector3d(0, 1, 0), dY); + Place.getRotation().multVec(Base::Vector3d(0, 0, 1), dZ); gp_Dir dirX(dX.x, dX.y, dX.z); gp_Dir dirY(dY.x, dY.y, dY.z); gp_Dir dirZ(dZ.x, dZ.y, dZ.z); @@ -342,17 +333,21 @@ Base::Placement AttachEngine::placementFactory(const gp_Dir &ZAxis, // +X/-X if (pos == 0) { - if (cosNX > 0) + if (cosNX > 0) { ax3 = gp_Ax3(Origin, ZAxis, dirY); - else + } + else { ax3 = gp_Ax3(Origin, ZAxis, -dirY); + } } // +Y/-Y else if (pos == 1) { - if (cosNY > 0) + if (cosNY > 0) { ax3 = gp_Ax3(Origin, ZAxis, -dirX); - else + } + else { ax3 = gp_Ax3(Origin, ZAxis, dirX); + } } // +Z/-Z else { @@ -360,34 +355,33 @@ Base::Placement AttachEngine::placementFactory(const gp_Dir &ZAxis, } } - if(this->mapReverse){ + if (this->mapReverse) { ax3.ZReverse(); ax3.XReverse(); } - //convert ax3 into Base::Placement + // convert ax3 into Base::Placement gp_Trsf Trf; Trf.SetTransformation(ax3); Trf.Invert(); Trf.SetScaleFactor(Standard_Real(1.0)); Base::Matrix4D mtrx; - TopoShape::convertToMatrix(Trf,mtrx); + TopoShape::convertToMatrix(Trf, mtrx); return Base::Placement(mtrx); - } -void AttachEngine::suggestMapModes(SuggestResult &result) const +void AttachEngine::suggestMapModes(SuggestResult& result) const { - std::vector &mlist = result.allApplicableModes; + std::vector& mlist = result.allApplicableModes; mlist.clear(); mlist.reserve(mmDummy_NumberOfModes); - std::set &hints = result.nextRefTypeHint; + std::set& hints = result.nextRefTypeHint; hints.clear(); - std::map &mlist_reachable = result.reachableModes; + std::map& mlist_reachable = result.reachableModes; mlist_reachable.clear(); result.message = SuggestResult::srLinkBroken; @@ -396,29 +390,32 @@ void AttachEngine::suggestMapModes(SuggestResult &result) const std::vector shapes; std::vector shapeStorage; std::vector typeStr; - try{ - readLinks(getRefObjects(),subnames, shapes, shapeStorage, typeStr); - } catch (Base::Exception &err) { + try { + readLinks(getRefObjects(), subnames, shapes, shapeStorage, typeStr); + } + catch (Base::Exception& err) { result.references_Types = typeStr; result.message = SuggestResult::srLinkBroken; - result.error.Exception::operator = (err); + result.error.Exception::operator=(err); return; } result.references_Types = typeStr; - //search valid modes. + // search valid modes. int bestMatchScore = -1; result.message = SuggestResult::srNoModesFit; for (std::size_t iMode = 0; iMode < this->modeRefTypes.size(); ++iMode) { - if (! this->modeEnabled[iMode]) + if (!this->modeEnabled[iMode]) { continue; - const refTypeStringList &listStrings = modeRefTypes[iMode]; - for (const auto & str : listStrings) { - int score = 1; //-1 = topo incompatible, 0 = topo compatible, geom incompatible; 1+ = compatible (the higher - the more specific is the mode for the support) + } + const refTypeStringList& listStrings = modeRefTypes[iMode]; + for (const auto& str : listStrings) { + int score = 1; //-1 = topo incompatible, 0 = topo compatible, geom incompatible; 1+ = + // compatible (the higher - the more specific is the mode for the support) for (std::size_t iChr = 0; iChr < str.size() && iChr < typeStr.size(); ++iChr) { int match = AttachEngine::isShapeOfType(typeStr[iChr], str[iChr]); - switch(match){ + switch (match) { case -1: score = -1; break; @@ -426,60 +423,71 @@ void AttachEngine::suggestMapModes(SuggestResult &result) const score = 0; break; case 1: - //keep score + // keep score + break; + default: // 2 and above + if (score > 0) { + score += match; + } break; - default: //2 and above - if (score > 0) - score += match; - break; } } - if (score > 0 && str.size() > typeStr.size()){ - //mode does not fit, but adding more references will make this mode fit. + if (score > 0 && str.size() > typeStr.size()) { + // mode does not fit, but adding more references will make this mode fit. hints.insert(str[typeStr.size()]); - //build string of references to be added to fit this mode + // build string of references to be added to fit this mode refTypeString extraRefs; extraRefs.resize(str.size() - typeStr.size()); for (std::size_t iChr = typeStr.size(); iChr < str.size(); iChr++) { extraRefs[iChr - typeStr.size()] = str[iChr]; } - //add reachable mode + // add reachable mode auto it_r = mlist_reachable.find(eMapMode(iMode)); - if (it_r == mlist_reachable.end()){ - it_r = mlist_reachable.insert(std::pair(eMapMode(iMode),refTypeStringList())).first; + if (it_r == mlist_reachable.end()) { + it_r = mlist_reachable + .insert( + std::pair( + eMapMode(iMode), + refTypeStringList() + ) + ) + .first; } - refTypeStringList &list = it_r->second; + refTypeStringList& list = it_r->second; list.push_back(extraRefs); } - //size check is last, because we needed to collect hints - if (str.size() != typeStr.size()) + // size check is last, because we needed to collect hints + if (str.size() != typeStr.size()) { score = -1; + } - if (score > -1){//still output a best match, even if it is not completely compatible - if (score > bestMatchScore){ + if (score > -1) { // still output a best match, even if it is not completely compatible + if (score > bestMatchScore) { bestMatchScore = score; result.bestFitMode = eMapMode(iMode); - result.message = score > 0 ? SuggestResult::srOK : SuggestResult::srIncompatibleGeometry; + result.message = score > 0 ? SuggestResult::srOK + : SuggestResult::srIncompatibleGeometry; } } - if (score > 0){ - if(mlist.empty()) + if (score > 0) { + if (mlist.empty()) { mlist.push_back(eMapMode(iMode)); - else if (mlist.back() != eMapMode(iMode)) + } + else if (mlist.back() != eMapMode(iMode)) { mlist.push_back(eMapMode(iMode)); + } } } } - } void AttachEngine::EnableAllSupportedModes() { - this->modeEnabled.resize(mmDummy_NumberOfModes,false); + this->modeEnabled.resize(mmDummy_NumberOfModes, false); assert(modeRefTypes.size() > 0); for (std::size_t i = 0; i < this->modeEnabled.size(); i++) { modeEnabled[i] = !modeRefTypes[i].empty(); @@ -488,99 +496,106 @@ void AttachEngine::EnableAllSupportedModes() eRefType AttachEngine::getShapeType(const TopoDS_Shape& sh) { - if(sh.IsNull()) + if (sh.IsNull()) { return rtAnything; + } - switch (sh.ShapeType()){ - case TopAbs_SHAPE: - return rtAnything; //note: there's no rtPart detection here - not enough data! - break; - case TopAbs_SOLID: - return rtSolid; - break; - case TopAbs_COMPOUND:{ - const TopoDS_Compound &cmpd = TopoDS::Compound(sh); - TopoDS_Iterator it (cmpd, Standard_False, Standard_False);//don't mess with placements, to hopefully increase speed - if (! it.More())//empty compound + switch (sh.ShapeType()) { + case TopAbs_SHAPE: + return rtAnything; // note: there's no rtPart detection here - not enough data! + break; + case TopAbs_SOLID: + return rtSolid; + break; + case TopAbs_COMPOUND: { + const TopoDS_Compound& cmpd = TopoDS::Compound(sh); + TopoDS_Iterator it(cmpd, Standard_False, Standard_False); // don't mess with placements, + // to hopefully increase speed + if (!it.More()) { // empty compound + return rtAnything; + } + const TopoDS_Shape& sh1 = it.Value(); + it.Next(); + if (it.More()) { + // more than one object, a true compound + return rtAnything; + } + else { + // just one object, let's take a look inside + return getShapeType(sh1); + } + } break; + case TopAbs_COMPSOLID: + case TopAbs_SHELL: return rtAnything; - const TopoDS_Shape &sh1 = it.Value(); - it.Next(); - if (it.More()){ - //more than one object, a true compound - return rtAnything; - } else { - //just one object, let's take a look inside - return getShapeType(sh1); - } - }break; - case TopAbs_COMPSOLID: - case TopAbs_SHELL: - return rtAnything; - break; - case TopAbs_FACE:{ - const TopoDS_Face &f = TopoDS::Face(sh); - BRepAdaptor_Surface surf(f, /*restriction=*/Standard_False); - switch(surf.GetType()) { - case GeomAbs_Plane: - return rtFlatFace; - case GeomAbs_Cylinder: - return rtCylindricalFace; - case GeomAbs_Cone: - return rtConicalFace; - case GeomAbs_Sphere: - return rtSphericalFace; - case GeomAbs_Torus: - return rtToroidalFace; - case GeomAbs_BezierSurface: break; - case GeomAbs_BSplineSurface: - break; - case GeomAbs_SurfaceOfRevolution: - return rtSurfaceRev; - case GeomAbs_SurfaceOfExtrusion: - break; - case GeomAbs_OffsetSurface: - break; - case GeomAbs_OtherSurface: - break; - } - return rtFace; - }break; - case TopAbs_EDGE:{ - const TopoDS_Edge &e = TopoDS::Edge(sh); - BRepAdaptor_Curve crv(e); - switch (crv.GetType()){ - case GeomAbs_Line: - return rtLine; - case GeomAbs_Circle: - return rtCircle; - case GeomAbs_Ellipse: - return rtEllipse; - case GeomAbs_Hyperbola: - return rtHyperbola; - case GeomAbs_Parabola: - return rtParabola; - case GeomAbs_BezierCurve: - case GeomAbs_BSplineCurve: - case GeomAbs_OtherCurve: - case GeomAbs_OffsetCurve: - return rtCurve; - } - }break; - case TopAbs_WIRE: - return rtWire; - case TopAbs_VERTEX: - return rtVertex; - default: - throw AttachEngineException("AttachEngine::getShapeType: unexpected TopoDS_Shape::ShapeType"); - }//switch shapetype - return rtAnything;//shouldn't happen, it's here to shut up compiler warning + case TopAbs_FACE: { + const TopoDS_Face& f = TopoDS::Face(sh); + BRepAdaptor_Surface surf(f, /*restriction=*/Standard_False); + switch (surf.GetType()) { + case GeomAbs_Plane: + return rtFlatFace; + case GeomAbs_Cylinder: + return rtCylindricalFace; + case GeomAbs_Cone: + return rtConicalFace; + case GeomAbs_Sphere: + return rtSphericalFace; + case GeomAbs_Torus: + return rtToroidalFace; + case GeomAbs_BezierSurface: + break; + case GeomAbs_BSplineSurface: + break; + case GeomAbs_SurfaceOfRevolution: + return rtSurfaceRev; + case GeomAbs_SurfaceOfExtrusion: + break; + case GeomAbs_OffsetSurface: + break; + case GeomAbs_OtherSurface: + break; + } + return rtFace; + } break; + case TopAbs_EDGE: { + const TopoDS_Edge& e = TopoDS::Edge(sh); + BRepAdaptor_Curve crv(e); + switch (crv.GetType()) { + case GeomAbs_Line: + return rtLine; + case GeomAbs_Circle: + return rtCircle; + case GeomAbs_Ellipse: + return rtEllipse; + case GeomAbs_Hyperbola: + return rtHyperbola; + case GeomAbs_Parabola: + return rtParabola; + case GeomAbs_BezierCurve: + case GeomAbs_BSplineCurve: + case GeomAbs_OtherCurve: + case GeomAbs_OffsetCurve: + return rtCurve; + } + } break; + case TopAbs_WIRE: + return rtWire; + case TopAbs_VERTEX: + return rtVertex; + default: + throw AttachEngineException( + "AttachEngine::getShapeType: unexpected TopoDS_Shape::ShapeType" + ); + } // switch shapetype + return rtAnything; // shouldn't happen, it's here to shut up compiler warning } -eRefType AttachEngine::getShapeType(const App::DocumentObject *obj, const std::string &subshape) +eRefType AttachEngine::getShapeType(const App::DocumentObject* obj, const std::string& subshape) { App::PropertyLinkSubList tmpLink; - //const_cast is worth here, to keep obj argument const. We are not going to write anything to obj through this temporary link. + // const_cast is worth here, to keep obj argument const. We are not going to write anything to + // obj through this temporary link. tmpLink.setValue(const_cast(obj), subshape.c_str()); std::vector shapes; @@ -594,110 +609,115 @@ eRefType AttachEngine::getShapeType(const App::DocumentObject *obj, const std::s eRefType AttachEngine::downgradeType(eRefType type) { - //get rid of hasplacement flags, to simplify the rest + // get rid of hasplacement flags, to simplify the rest type = eRefType(type & (rtFlagHasPlacement - 1)); - //FIXME: reintroduce the flag when returning a value. + // FIXME: reintroduce the flag when returning a value. - switch(type){ - case rtVertex: - case rtEdge: - case rtFace: - return rtAnything; - case rtAnything: - return rtAnything; - case rtLine: - case rtCurve: - return rtEdge; - case rtConic: - case rtCircle: - return rtCurve; - case rtEllipse: - case rtParabola: - case rtHyperbola: - return rtConic; - case rtFlatFace: - case rtSphericalFace: - case rtSurfaceRev: - return rtFace; - case rtCylindricalFace: - case rtToroidalFace: - case rtConicalFace: - return rtSurfaceRev; - case rtSolid: - case rtWire: - return rtPart; - case rtPart: - return rtAnything; - default: - throw AttachEngineException("AttachEngine::downgradeType: unknown type"); + switch (type) { + case rtVertex: + case rtEdge: + case rtFace: + return rtAnything; + case rtAnything: + return rtAnything; + case rtLine: + case rtCurve: + return rtEdge; + case rtConic: + case rtCircle: + return rtCurve; + case rtEllipse: + case rtParabola: + case rtHyperbola: + return rtConic; + case rtFlatFace: + case rtSphericalFace: + case rtSurfaceRev: + return rtFace; + case rtCylindricalFace: + case rtToroidalFace: + case rtConicalFace: + return rtSurfaceRev; + case rtSolid: + case rtWire: + return rtPart; + case rtPart: + return rtAnything; + default: + throw AttachEngineException("AttachEngine::downgradeType: unknown type"); } } int AttachEngine::getTypeRank(eRefType type) { - //get rid of hasplacement flags, to simplify the rest + // get rid of hasplacement flags, to simplify the rest type = eRefType(type & (rtFlagHasPlacement - 1)); int rank = 0; while (type != rtAnything) { type = downgradeType(type); rank++; - assert(rank<8);//downgrading never yields rtAnything, something's wrong with downgrader. + assert(rank < 8); // downgrading never yields rtAnything, something's wrong with downgrader. } return rank; } int AttachEngine::isShapeOfType(eRefType shapeType, eRefType requirement) { - //first up, check for hasplacement flag + // first up, check for hasplacement flag if (requirement & rtFlagHasPlacement) { - if(! (shapeType & rtFlagHasPlacement)) + if (!(shapeType & rtFlagHasPlacement)) { return -1; + } } - //get rid of hasplacement flags, to simplify the rest + // get rid of hasplacement flags, to simplify the rest shapeType = eRefType(shapeType & (rtFlagHasPlacement - 1)); requirement = eRefType(requirement & (rtFlagHasPlacement - 1)); - if (requirement == rtAnything) + if (requirement == rtAnything) { return 1; + } int reqRank = getTypeRank(requirement); - //test for valid match + // test for valid match eRefType shDeg = shapeType; - while(shDeg != rtAnything){ - if (shDeg == requirement) + while (shDeg != rtAnything) { + if (shDeg == requirement) { return reqRank; + } shDeg = downgradeType(shDeg); } - //test for slightly invalid match (e.g. requirement==line, shapeType == curve) + // test for slightly invalid match (e.g. requirement==line, shapeType == curve) requirement = downgradeType(requirement); if (requirement != rtAnything) { eRefType shDeg = shapeType; - while(shDeg != rtAnything){ - if (shDeg == requirement) + while (shDeg != rtAnything) { + if (shDeg == requirement) { return 0; + } shDeg = downgradeType(shDeg); } } - //complete mismatch! + // complete mismatch! return -1; } std::string AttachEngine::getModeName(eMapMode mmode) { - if(mmode < 0 || mmode >= mmDummy_NumberOfModes) + if (mmode < 0 || mmode >= mmDummy_NumberOfModes) { throw AttachEngineException("AttachEngine::getModeName: Attachment Mode index is out of range"); + } return {AttachEngine::eMapModeStrings[mmode]}; } -eMapMode AttachEngine::getModeByName(const std::string &modeName) +eMapMode AttachEngine::getModeByName(const std::string& modeName) { - for (int mmode = 0 ; mmode < mmDummy_NumberOfModes ; mmode++){ - if (strcmp(eMapModeStrings[mmode],modeName.c_str())==0) { + for (int mmode = 0; mmode < mmDummy_NumberOfModes; mmode++) { + if (strcmp(eMapModeStrings[mmode], modeName.c_str()) == 0) { return eMapMode(mmode); } } @@ -709,10 +729,11 @@ eMapMode AttachEngine::getModeByName(const std::string &modeName) std::string AttachEngine::getRefTypeName(eRefType shapeType) { eRefType flagless = eRefType(shapeType & 0xFF); - if(flagless < 0 || flagless >= rtDummy_numberOfShapeTypes) + if (flagless < 0 || flagless >= rtDummy_numberOfShapeTypes) { throw AttachEngineException("eRefType value is out of range"); + } std::string result = std::string(eRefTypeStrings[flagless]); - if (shapeType & rtFlagHasPlacement){ + if (shapeType & rtFlagHasPlacement) { result.append("|Placement"); } return result; @@ -724,16 +745,18 @@ eRefType AttachEngine::getRefTypeByName(const std::string& typeName) std::string flags; size_t seppos = typeName.find('|'); flagless = typeName.substr(0, seppos); - if(seppos != std::string::npos ){ - flags = typeName.substr(seppos+1); + if (seppos != std::string::npos) { + flags = typeName.substr(seppos + 1); } - for(int irt = 0 ; irt < rtDummy_numberOfShapeTypes ; irt++){ - if(strcmp(flagless.c_str(),eRefTypeStrings[irt]) == 0){ - if(strcmp("Placement",flags.c_str()) == 0){ + for (int irt = 0; irt < rtDummy_numberOfShapeTypes; irt++) { + if (strcmp(flagless.c_str(), eRefTypeStrings[irt]) == 0) { + if (strcmp("Placement", flags.c_str()) == 0) { return eRefType(irt | rtFlagHasPlacement); - } else if (flags.length() == 0){ + } + else if (flags.length() == 0) { return eRefType(irt); - } else { + } + else { std::stringstream errmsg; errmsg << "RefType flag not recognized: " << flags; throw AttachEngineException(errmsg.str()); @@ -745,90 +768,119 @@ eRefType AttachEngine::getRefTypeByName(const std::string& typeName) throw AttachEngineException(errmsg.str()); } -GProp_GProps AttachEngine::getInertialPropsOfShape(const std::vector &shapes) +GProp_GProps AttachEngine::getInertialPropsOfShape(const std::vector& shapes) { - //explode compounds + // explode compounds TopTools_HSequenceOfShape totalSeq; for (auto tSh : shapes) { auto pSh = tSh->getShape(); ShapeExtend_Explorer xp; - totalSeq.Append( xp.SeqFromCompound(pSh, /*recursive=*/true)); + totalSeq.Append(xp.SeqFromCompound(pSh, /*recursive=*/true)); } - if (totalSeq.Length() == 0) + if (totalSeq.Length() == 0) { throw AttachEngineException("AttachEngine::getInertialPropsOfShape: no geometry provided"); - const TopoDS_Shape &sh0 = totalSeq.Value(1); - switch (sh0.ShapeType()){ - case TopAbs_VERTEX:{ - GProp_PGProps gpr; - for (int i = 0 ; i < totalSeq.Length() ; i++){ - const TopoDS_Shape &sh = totalSeq.Value(i+1); - if (sh.ShapeType() != TopAbs_VERTEX) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only vertices)"); - gpr.AddPoint(BRep_Tool::Pnt(TopoDS::Vertex(sh))); - } - return gpr; - } break; - case TopAbs_EDGE: - case TopAbs_WIRE:{ - GProp_GProps gpr_acc; - GProp_GProps gpr; - for (int i = 0 ; i < totalSeq.Length() ; i++){ - const TopoDS_Shape &sh = totalSeq.Value(i+1); - if (sh.ShapeType() != TopAbs_EDGE && sh.ShapeType() != TopAbs_WIRE) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only edges/wires)"); - if (sh.Infinite()) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: infinite shape provided"); - BRepGProp::LinearProperties(sh,gpr); - gpr_acc.Add(gpr); - } - return gpr_acc; - } break; - case TopAbs_FACE: - case TopAbs_SHELL:{ - GProp_GProps gpr_acc; - GProp_GProps gpr; - for (int i = 0 ; i < totalSeq.Length() ; i++){ - const TopoDS_Shape &sh = totalSeq.Value(i+1); - if (sh.ShapeType() != TopAbs_FACE && sh.ShapeType() != TopAbs_SHELL) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only faces/shells)"); - if (sh.Infinite()) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: infinite shape provided"); - BRepGProp::SurfaceProperties(sh,gpr); - gpr_acc.Add(gpr); - } - return gpr_acc; - } break; - case TopAbs_SOLID: - case TopAbs_COMPSOLID:{ - GProp_GProps gpr_acc; - GProp_GProps gpr; - for (int i = 0 ; i < totalSeq.Length() ; i++){ - const TopoDS_Shape &sh = totalSeq.Value(i+1); - if (sh.ShapeType() != TopAbs_SOLID && sh.ShapeType() != TopAbs_COMPSOLID) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: provided shapes are incompatible (not only solids/compsolids)"); - if (sh.Infinite()) - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: infinite shape provided"); - BRepGProp::VolumeProperties(sh,gpr); - gpr_acc.Add(gpr); - } - return gpr_acc; - } break; - default: - throw AttachEngineException("AttachEngine::getInertialPropsOfShape: unexpected shape type"); + } + const TopoDS_Shape& sh0 = totalSeq.Value(1); + switch (sh0.ShapeType()) { + case TopAbs_VERTEX: { + GProp_PGProps gpr; + for (int i = 0; i < totalSeq.Length(); i++) { + const TopoDS_Shape& sh = totalSeq.Value(i + 1); + if (sh.ShapeType() != TopAbs_VERTEX) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: provided shapes are incompatible " + "(not only vertices)" + ); + } + gpr.AddPoint(BRep_Tool::Pnt(TopoDS::Vertex(sh))); + } + return gpr; + } break; + case TopAbs_EDGE: + case TopAbs_WIRE: { + GProp_GProps gpr_acc; + GProp_GProps gpr; + for (int i = 0; i < totalSeq.Length(); i++) { + const TopoDS_Shape& sh = totalSeq.Value(i + 1); + if (sh.ShapeType() != TopAbs_EDGE && sh.ShapeType() != TopAbs_WIRE) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: provided shapes are incompatible " + "(not only edges/wires)" + ); + } + if (sh.Infinite()) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: infinite shape provided" + ); + } + BRepGProp::LinearProperties(sh, gpr); + gpr_acc.Add(gpr); + } + return gpr_acc; + } break; + case TopAbs_FACE: + case TopAbs_SHELL: { + GProp_GProps gpr_acc; + GProp_GProps gpr; + for (int i = 0; i < totalSeq.Length(); i++) { + const TopoDS_Shape& sh = totalSeq.Value(i + 1); + if (sh.ShapeType() != TopAbs_FACE && sh.ShapeType() != TopAbs_SHELL) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: provided shapes are incompatible " + "(not only faces/shells)" + ); + } + if (sh.Infinite()) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: infinite shape provided" + ); + } + BRepGProp::SurfaceProperties(sh, gpr); + gpr_acc.Add(gpr); + } + return gpr_acc; + } break; + case TopAbs_SOLID: + case TopAbs_COMPSOLID: { + GProp_GProps gpr_acc; + GProp_GProps gpr; + for (int i = 0; i < totalSeq.Length(); i++) { + const TopoDS_Shape& sh = totalSeq.Value(i + 1); + if (sh.ShapeType() != TopAbs_SOLID && sh.ShapeType() != TopAbs_COMPSOLID) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: provided shapes are incompatible " + "(not only solids/compsolids)" + ); + } + if (sh.Infinite()) { + throw AttachEngineException( + "AttachEngine::getInertialPropsOfShape: infinite shape provided" + ); + } + BRepGProp::VolumeProperties(sh, gpr); + gpr_acc.Add(gpr); + } + return gpr_acc; + } break; + default: + throw AttachEngineException("AttachEngine::getInertialPropsOfShape: unexpected shape type"); } } /*! * \brief AttachEngine3D::readLinks * \param shapes - * \param storage is a buffer storing what some of the pointers in shapes point to. It is needed, since - * subshapes are copied in the process (but copying a whole shape of an object can potentially be slow). + * \param storage is a buffer storing what some of the pointers in shapes point to. It is needed, + * since subshapes are copied in the process (but copying a whole shape of an object can potentially + * be slow). */ -void AttachEngine::readLinks(const std::vector& objs, - const std::vector &subs, - std::vector &shapes, - std::vector &storage, - std::vector &types) +void AttachEngine::readLinks( + const std::vector& objs, + const std::vector& subs, + std::vector& shapes, + std::vector& storage, + std::vector& types +) { storage.reserve(objs.size()); shapes.resize(objs.size()); @@ -837,9 +889,11 @@ void AttachEngine::readLinks(const std::vector& objs, for (std::size_t i = 0; i < objs.size(); i++) { auto geof = extractGeoFeature(objs[i]); if (!geof) { - FC_THROWM(AttachEngineException, - "AttachEngine3D: attached to a non App::GeoFeature '" - << objs[i]->getNameInDocument() << "'"); + FC_THROWM( + AttachEngineException, + "AttachEngine3D: attached to a non App::GeoFeature '" + << objs[i]->getNameInDocument() << "'" + ); } auto shape = extractSubShape(objs[i], subs[i]); @@ -853,9 +907,10 @@ void AttachEngine::readLinks(const std::vector& objs, else { // This case should now be unreachable because extractSubShape would have thrown // for a missing subname. But it's good defensive programming. - FC_THROWM(AttachEngineException, - "AttachEngine3D: null subshape " << objs[i]->getNameInDocument() << '.' - << subs[i]); + FC_THROWM( + AttachEngineException, + "AttachEngine3D: null subshape " << objs[i]->getNameInDocument() << '.' << subs[i] + ); } } @@ -872,7 +927,7 @@ void AttachEngine::readLinks(const std::vector& objs, } } -App::GeoFeature* AttachEngine::extractGeoFeature(App::DocumentObject *obj) +App::GeoFeature* AttachEngine::extractGeoFeature(App::DocumentObject* obj) { if (auto geof = dynamic_cast(obj)) { return geof; @@ -893,11 +948,11 @@ TopoShape AttachEngine::extractSubShape(App::DocumentObject* obj, const std::str try { // getTopoShape support fully qualified subnames and should return shape with correct // global placement. - shape = Feature::getTopoShape(obj, - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - subname.c_str()); + shape = Feature::getTopoShape( + obj, + ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform, + subname.c_str() + ); for (;;) { if (shape.isNull()) { @@ -913,9 +968,11 @@ TopoShape AttachEngine::extractSubShape(App::DocumentObject* obj, const std::str else { // The user specified a subname (e.g., "Edge1"), but it couldn't be found. // This is a genuine error. - FC_THROWM(AttachEngineException, - "AttachEngine3D: subshape not found " << obj->getNameInDocument() - << '.' << subname); + FC_THROWM( + AttachEngineException, + "AttachEngine3D: subshape not found " << obj->getNameInDocument() << '.' + << subname + ); } } @@ -928,16 +985,20 @@ TopoShape AttachEngine::extractSubShape(App::DocumentObject* obj, const std::str } } catch (Standard_Failure& e) { - FC_THROWM(AttachEngineException, - "AttachEngine3D: subshape not found " << obj->getNameInDocument() << '.' - << subname << std::endl - << e.GetMessageString()); + FC_THROWM( + AttachEngineException, + "AttachEngine3D: subshape not found " << obj->getNameInDocument() << '.' << subname + << std::endl + << e.GetMessageString() + ); } catch (Base::CADKernelError& e) { - FC_THROWM(AttachEngineException, - "AttachEngine3D: subshape not found " << obj->getNameInDocument() << '.' - << subname << std::endl - << e.what()); + FC_THROWM( + AttachEngineException, + "AttachEngine3D: subshape not found " << obj->getNameInDocument() << '.' << subname + << std::endl + << e.what() + ); } return shape; @@ -946,31 +1007,36 @@ TopoShape AttachEngine::extractSubShape(App::DocumentObject* obj, const std::str void AttachEngine::throwWrongMode(eMapMode mmode) { std::stringstream errmsg; - if (mmode >= 0 && mmode= 0 && mmode < mmDummy_NumberOfModes) { if (AttachEngine::eMapModeStrings[mmode]) { - errmsg << "Attachment mode " << AttachEngine::eMapModeStrings[mmode] << " is not implemented." ; - } else { - errmsg << "Attachment mode " << int(mmode) << " is undefined." ; + errmsg << "Attachment mode " << AttachEngine::eMapModeStrings[mmode] + << " is not implemented."; } - } else { - errmsg << "Attachment mode index (" << int(mmode) << ") is out of range." ; + else { + errmsg << "Attachment mode " << int(mmode) << " is undefined."; + } + } + else { + errmsg << "Attachment mode index (" << int(mmode) << ") is out of range."; } throw Base::ValueError(errmsg.str().c_str()); } -void AttachEngine::verifyReferencesAreSafe(const App::PropertyLinkSubList &references) +void AttachEngine::verifyReferencesAreSafe(const App::PropertyLinkSubList& references) { - const std::vector links = references.getValues(); + const std::vector links = references.getValues(); const std::vector docs = App::GetApplication().getDocuments(); - for(App::DocumentObject* lnk : links){ + for (App::DocumentObject* lnk : links) { bool found = false; - for(App::Document* doc : docs){ - if(doc->isIn(lnk)){ + for (App::Document* doc : docs) { + if (doc->isIn(lnk)) { found = true; } } - if (!found){ - throw AttachEngineException("AttachEngine: verifyReferencesAreSafe: references point to deleted object."); + if (!found) { + throw AttachEngineException( + "AttachEngine: verifyReferencesAreSafe: references point to deleted object." + ); } } } @@ -989,15 +1055,19 @@ std::vector AttachEngine::getRefObjects() const for (auto& name : objNames) { objs.push_back(doc->getObject(name.c_str())); if (!objs.back()) { - FC_THROWM(AttachEngineException, - "AttachEngine: object '" << docName << "#" << name << "' not found"); + FC_THROWM( + AttachEngineException, + "AttachEngine: object '" << docName << "#" << name << "' not found" + ); } } return objs; } -Base::Placement AttachEngine::calculateAttachedPlacement(const Base::Placement& origPlacement, - bool* subChanged) +Base::Placement AttachEngine::calculateAttachedPlacement( + const Base::Placement& origPlacement, + bool* subChanged +) { std::map> subChanges; int i = -1; @@ -1010,10 +1080,12 @@ Base::Placement AttachEngine::calculateAttachedPlacement(const Base::Placement& if (shadow.empty() || !Data::hasMissingElement(sub.c_str())) { continue; } - auto related = Part::Feature::getRelatedElements(obj, - shadow.c_str(), - Part::HistoryTraceType::followTypeChange, - false); + auto related = Part::Feature::getRelatedElements( + obj, + shadow.c_str(), + Part::HistoryTraceType::followTypeChange, + false + ); if (!related.empty()) { auto& res = subChanges[i]; res.first = Data::ComplexGeoData::elementMapPrefix(); @@ -1040,13 +1112,13 @@ Base::Placement AttachEngine::calculateAttachedPlacement(const Base::Placement& // attention. auto subs = subnames; for (auto& change : subChanges) { - auto [subkey, namechange] =change; + auto [subkey, namechange] = change; auto [_oldname, newname] = namechange; subs[subkey] = newname; } auto pla = _calculateAttachedPlacement(objs, subs, origPlacement); // check equal placement with some tolerance - if (pla.getPosition().IsEqual(origPlacement.getPosition(), Precision::Confusion()) + if (pla.getPosition().IsEqual(origPlacement.getPosition(), Precision::Confusion()) && pla.getRotation().isSame(origPlacement.getRotation(), Precision::Angular())) { // Only make changes if the caller supplies 'subChanged', because // otherwise it means the caller just want to do an immutable test. @@ -1072,7 +1144,7 @@ TYPESYSTEM_SOURCE(Attacher::AttachEngine3D, Attacher::AttachEngine) AttachEngine3D::AttachEngine3D() { - //fill type lists for modes + // fill type lists for modes modeRefTypes.resize(mmDummy_NumberOfModes); refTypeString s; refTypeStringList ss; @@ -1086,15 +1158,13 @@ AttachEngine3D::AttachEngine3D() modeRefTypes[mmObjectXZ] = ss; modeRefTypes[mmObjectYZ] = ss; - modeRefTypes[mmParallelPlane].push_back( - cat(eRefType(rtFlatFace | rtFlagHasPlacement), rtVertex)); - modeRefTypes[mmParallelPlane].push_back( - cat(eRefType(rtAnything | rtFlagHasPlacement), rtVertex)); + modeRefTypes[mmParallelPlane].push_back(cat(eRefType(rtFlatFace | rtFlagHasPlacement), rtVertex)); + modeRefTypes[mmParallelPlane].push_back(cat(eRefType(rtAnything | rtFlagHasPlacement), rtVertex)); modeRefTypes[mmInertialCS].push_back(cat(rtAnything)); - modeRefTypes[mmInertialCS].push_back(cat(rtAnything,rtAnything)); - modeRefTypes[mmInertialCS].push_back(cat(rtAnything,rtAnything,rtAnything)); - modeRefTypes[mmInertialCS].push_back(cat(rtAnything,rtAnything,rtAnything,rtAnything)); + modeRefTypes[mmInertialCS].push_back(cat(rtAnything, rtAnything)); + modeRefTypes[mmInertialCS].push_back(cat(rtAnything, rtAnything, rtAnything)); + modeRefTypes[mmInertialCS].push_back(cat(rtAnything, rtAnything, rtAnything, rtAnything)); modeRefTypes[mmFlatFace].push_back(cat(rtFlatFace)); @@ -1103,7 +1173,7 @@ AttachEngine3D::AttachEngine3D() //---------Edge-driven - s=cat(rtEdge); + s = cat(rtEdge); modeRefTypes[mmNormalToPath].push_back(s); s = cat(rtCurve); @@ -1113,34 +1183,34 @@ AttachEngine3D::AttachEngine3D() modeRefTypes[mmRevolutionSection].push_back(s); modeRefTypes[mmConcentric].push_back(s); s = cat(rtCircle); - modeRefTypes[mmRevolutionSection].push_back(s);//for this mode to get best score on circles + modeRefTypes[mmRevolutionSection].push_back(s); // for this mode to get best score on circles modeRefTypes[mmConcentric].push_back(s); //-----------Edge-driven at vertex - s=cat(rtEdge, rtVertex); + s = cat(rtEdge, rtVertex); modeRefTypes[mmNormalToPath].push_back(s); - s=cat(rtVertex, rtEdge); + s = cat(rtVertex, rtEdge); modeRefTypes[mmNormalToPath].push_back(s); - s=cat(rtCurve, rtVertex); + s = cat(rtCurve, rtVertex); modeRefTypes[mmFrenetNB].push_back(s); modeRefTypes[mmFrenetTN].push_back(s); modeRefTypes[mmFrenetTB].push_back(s); modeRefTypes[mmRevolutionSection].push_back(s); modeRefTypes[mmConcentric].push_back(s); s = cat(rtCircle, rtVertex); - modeRefTypes[mmRevolutionSection].push_back(s);//for this mode to get best score on circles + modeRefTypes[mmRevolutionSection].push_back(s); // for this mode to get best score on circles modeRefTypes[mmConcentric].push_back(s); - s=cat(rtVertex, rtCurve); + s = cat(rtVertex, rtCurve); modeRefTypes[mmFrenetNB].push_back(s); modeRefTypes[mmFrenetTN].push_back(s); modeRefTypes[mmFrenetTB].push_back(s); modeRefTypes[mmRevolutionSection].push_back(s); modeRefTypes[mmConcentric].push_back(s); s = cat(rtVertex, rtCircle); - modeRefTypes[mmRevolutionSection].push_back(s);//for this mode to get best score on circles + modeRefTypes[mmRevolutionSection].push_back(s); // for this mode to get best score on circles modeRefTypes[mmConcentric].push_back(s); //------------ThreePoints @@ -1162,7 +1232,7 @@ AttachEngine3D::AttachEngine3D() modeRefTypes[mmThreePointsNormal].push_back(s); //------------origin-axis-axis modes - for (int mmode = mmOZX; mmode <= mmOYX; ++mmode){ + for (int mmode = mmOZX; mmode <= mmOYX; ++mmode) { modeRefTypes[mmode].push_back(cat(rtVertex, rtVertex, rtVertex)); modeRefTypes[mmode].push_back(cat(rtVertex, rtVertex, rtLine)); modeRefTypes[mmode].push_back(cat(rtVertex, rtLine, rtVertex)); @@ -1184,10 +1254,11 @@ AttachEngine3D* AttachEngine3D::copy() const return p; } -Base::Placement -AttachEngine3D::_calculateAttachedPlacement(const std::vector& objs, - const std::vector& subs, - const Base::Placement& origPlacement) const +Base::Placement AttachEngine3D::_calculateAttachedPlacement( + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement +) const { const eMapMode mmode = this->mapMode; if (mmode == mmDeactivated) { @@ -1223,17 +1294,20 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vectorgetShape(); if (sh.IsNull()) { - throw Base::ValueError( - "Null shape in AttachEngine3D::calculateAttachedPlacement()!"); + throw Base::ValueError("Null shape in AttachEngine3D::calculateAttachedPlacement()!"); } if (sh.ShapeType() != TopAbs_VERTEX) { - throw Base::ValueError("AttachEngine3D::calculateAttachedPlacement: no subobjects " - "specified (need one vertex)."); + throw Base::ValueError( + "AttachEngine3D::calculateAttachedPlacement: no subobjects " + "specified (need one vertex)." + ); } gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(sh)); Base::Placement plm = Base::Placement(); @@ -1257,8 +1331,8 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector 0) { const TopoDS_Edge& e = TopoDS::Edge(shapes[0]->getShape()); @@ -1289,7 +1363,8 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector Precision::SquareConfusion()) { N.Normalize(); B = T.Crossed(N); @@ -1621,7 +1716,8 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector points; - for (const auto & shape : shapes) { - const TopoDS_Shape &sh = shape->getShape(); + for (const auto& shape : shapes) { + const TopoDS_Shape& sh = shape->getShape(); if (sh.IsNull()) { throw Base::ValueError( - "Null shape in AttachEngine3D::calculateAttachedPlacement()!"); + "Null shape in AttachEngine3D::calculateAttachedPlacement()!" + ); } if (sh.ShapeType() == TopAbs_VERTEX) { const TopoDS_Vertex& v = TopoDS::Vertex(sh); @@ -1714,8 +1814,10 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vectorIsNull()) { throw Base::ValueError( - "Null edge in AttachEngine3D::calculateAttachedPlacement()!"); + "Null edge in AttachEngine3D::calculateAttachedPlacement()!" + ); } adapts[i] = BRepAdaptor_Curve(*(edges[i])); if (adapts[i].GetType() != GeomAbs_Line) { throw Base::ValueError( - "AttachEngine3D::calculateAttachedPlacement: Folding - non-straight edge."); + "AttachEngine3D::calculateAttachedPlacement: Folding - non-straight edge." + ); } lines[i] = adapts[i].Line(); } @@ -1826,8 +1939,10 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vectorshapeType() != TopAbs_VERTEX) { - THROWM(Base::TypeError, - "AttachEngine3D::calculateAttachedPlacement: first reference must be a " - "vertex, it's not") + THROWM( + Base::TypeError, + "AttachEngine3D::calculateAttachedPlacement: first reference must be a " + "vertex, it's not" + ) } SketchBasePoint = BRep_Tool::Pnt(TopoDS::Vertex(shapes[0]->getShape())); // read out axes directions for (size_t i = 1; i < 3 && i < shapes.size(); ++i) { if (shapes[i]->isNull()) { - THROWM(Base::TypeError, - "AttachEngine3D::calculateAttachedPlacement: null shape!") + THROWM(Base::TypeError, "AttachEngine3D::calculateAttachedPlacement: null shape!") } if (shapes[i]->shapeType() == TopAbs_VERTEX) { gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(shapes[i]->getShape())); @@ -1939,14 +2059,16 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vectormapReverse) { rot = rot * Base::Rotation(Base::Vector3d(0, 1, 0), std::numbers::pi); } Base::Placement plm = Base::Placement( Base::Vector3d(SketchBasePoint.X(), SketchBasePoint.Y(), SketchBasePoint.Z()), - rot); + rot + ); plm *= this->attachmentOffset; return plm; } break; @@ -1966,14 +2088,14 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector(geom.get())) { placement.setPosition(point->getPoint()); } - } - break; + } break; case TopAbs_EDGE: { if (auto conic = freecad_cast(geom.get())) { placement.setPosition(conic->getLocation()); placement.setRotation(conic->getRotation().value_or(Base::Rotation {})); - } else if (auto line = freecad_cast(geom.get())) { + } + else if (auto line = freecad_cast(geom.get())) { auto u1 = line->getFirstParameter(); auto u2 = line->getLastParameter(); @@ -1998,16 +2120,18 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector(center)); - placement.setRotation(Base::Rotation::fromNormalVector( - Base::convertTo(axisDir))); + placement.setRotation( + Base::Rotation::fromNormalVector( + Base::convertTo(axisDir) + ) + ); break; } } - } - break; + } break; case TopAbs_FACE: { auto surface = freecad_cast(geom.get()); @@ -2034,24 +2158,29 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector(axisCenter)); - placement.setRotation(Base::Rotation::fromNormalVector( - Base::convertTo(axisDir))); + placement.setRotation( + Base::Rotation::fromNormalVector(Base::convertTo(axisDir)) + ); break; } if (auto sphere = freecad_cast(geom.get())) { placement.setPosition(sphere->getLocation()); - } else if (auto cone = freecad_cast(geom.get())) { + } + else if (auto cone = freecad_cast(geom.get())) { placement.setPosition(cone->getApex()); - } else if (auto point = surface->point(midU, midV)) { + } + else if (auto point = surface->point(midU, midV)) { placement.setPosition(*point); - } else if (auto com = shape->centerOfGravity()) { + } + else if (auto com = shape->centerOfGravity()) { placement.setPosition(*com); - } else { + } + else { placement.setPosition(shape->getBoundBox().GetCenter()); } @@ -2063,14 +2192,17 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vector(dir))); - } - break; + placement.setRotation( + Base::Rotation::fromNormalVector(Base::convertTo(dir)) + ); + } break; default: - THROWM(Base::TypeError, - "AttachEngine3D::calculateAttachedPlacement: Unsupported shape type, " - "must be one of: Vertex, Edge, Face"); + THROWM( + Base::TypeError, + "AttachEngine3D::calculateAttachedPlacement: Unsupported shape type, " + "must be one of: Vertex, Edge, Face" + ); break; } @@ -2084,49 +2216,59 @@ AttachEngine3D::_calculateAttachedPlacement(const std::vectorplacementFactory(SketchNormal, - SketchXAxis, - SketchBasePoint, - gp_Pnt(), - /*useRefOrg_Line = */ false, - /*useRefOrg_Plane = */ false, - /*makeYVertical = */ false, - /*makeLegacyFlatFaceOrientation = */ mmode == mmFlatFace, - &Place); + Base::Placement plm = this->placementFactory( + SketchNormal, + SketchXAxis, + SketchBasePoint, + gp_Pnt(), + /*useRefOrg_Line = */ false, + /*useRefOrg_Plane = */ false, + /*makeYVertical = */ false, + /*makeLegacyFlatFaceOrientation = */ mmode == mmFlatFace, + &Place + ); plm *= this->attachmentOffset; return plm; } double AttachEngine3D::calculateFoldAngle(gp_Vec axA, gp_Vec axB, gp_Vec edA, gp_Vec edB) const { - //DeepSOIC: this hardcore math can probably be replaced with a couple of - //clever OCC calls... See forum thread "Sketch mapping enhancement" for a - //picture on how this math was derived. - //https://forum.freecad.org/viewtopic.php?f=8&t=10511&sid=007946a934530ff2a6c9259fb32624ec&start=40#p87584 + // DeepSOIC: this hardcore math can probably be replaced with a couple of + // clever OCC calls... See forum thread "Sketch mapping enhancement" for a + // picture on how this math was derived. + // https://forum.freecad.org/viewtopic.php?f=8&t=10511&sid=007946a934530ff2a6c9259fb32624ec&start=40#p87584 axA.Normalize(); axB.Normalize(); edA.Normalize(); edB.Normalize(); gp_Vec norm = axA.Crossed(axB); - if (norm.Magnitude() < Precision::Confusion()) - throw AttachEngineException("calculateFoldAngle: Folding axes are parallel, folding angle cannot be computed."); + if (norm.Magnitude() < Precision::Confusion()) { + throw AttachEngineException( + "calculateFoldAngle: Folding axes are parallel, folding angle cannot be computed." + ); + } norm.Normalize(); double a = edA.Dot(axA); double ra = edA.Crossed(axA).Magnitude(); - if (fabs(ra) < Precision::Confusion()) - throw AttachEngineException("calculateFoldAngle: axisA and edgeA are parallel, folding can't be computed."); + if (fabs(ra) < Precision::Confusion()) { + throw AttachEngineException( + "calculateFoldAngle: axisA and edgeA are parallel, folding can't be computed." + ); + } double b = edB.Dot(axB); double costheta = axB.Dot(axA); double sintheta = axA.Crossed(axB).Dot(norm); double singama = -costheta; double cosgama = sintheta; - double k = b*cosgama; - double l = a + b*singama; - double xa = k + l*singama/cosgama; - double cos_unfold = -xa/ra; - if (fabs(cos_unfold)>0.999) - throw AttachEngineException("calculateFoldAngle: cosine of folding angle is too close to or above 1."); + double k = b * cosgama; + double l = a + b * singama; + double xa = k + l * singama / cosgama; + double cos_unfold = -xa / ra; + if (fabs(cos_unfold) > 0.999) { + throw AttachEngineException( + "calculateFoldAngle: cosine of folding angle is too close to or above 1." + ); + } return acos(cos_unfold); } @@ -2137,13 +2279,13 @@ TYPESYSTEM_SOURCE(Attacher::AttachEnginePlane, Attacher::AttachEngine) AttachEnginePlane::AttachEnginePlane() { - //reused 3d modes: all of Attacher3d + // reused 3d modes: all of Attacher3d AttachEngine3D attacher3D; this->modeRefTypes = attacher3D.modeRefTypes; this->EnableAllSupportedModes(); } -AttachEnginePlane *AttachEnginePlane::copy() const +AttachEnginePlane* AttachEnginePlane::copy() const { AttachEnginePlane* p = new AttachEnginePlane; p->setUp(*this); @@ -2151,16 +2293,17 @@ AttachEnginePlane *AttachEnginePlane::copy() const } Base::Placement AttachEnginePlane::_calculateAttachedPlacement( - const std::vector&objs, - const std::vector &subs, - const Base::Placement &origPlacement) const + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement +) const { - //reuse Attacher3d + // reuse Attacher3d Base::Placement plm; AttachEngine3D attacher3D; attacher3D.precision = precision; attacher3D.setUp(*this); - plm = attacher3D._calculateAttachedPlacement(objs,subs,origPlacement); + plm = attacher3D._calculateAttachedPlacement(objs, subs, origPlacement); return plm; } @@ -2175,11 +2318,11 @@ TYPESYSTEM_SOURCE(Attacher::AttachEngineLine, Attacher::AttachEngine) AttachEngineLine::AttachEngineLine() { - //fill type lists for modes + // fill type lists for modes modeRefTypes.resize(mmDummy_NumberOfModes); refTypeString s; - //reused 3d modes + // reused 3d modes AttachEngine3D attacher3D; modeRefTypes[mm1AxisX] = attacher3D.modeRefTypes[mmObjectYZ]; modeRefTypes[mm1AxisY] = attacher3D.modeRefTypes[mmObjectXZ]; @@ -2189,7 +2332,7 @@ AttachEngineLine::AttachEngineLine() modeRefTypes[mm1Normal] = attacher3D.modeRefTypes[mmFrenetTB]; modeRefTypes[mm1Tangent] = attacher3D.modeRefTypes[mmNormalToPath]; - modeRefTypes[mm1TwoPoints].push_back(cat(rtVertex,rtVertex)); + modeRefTypes[mm1TwoPoints].push_back(cat(rtVertex, rtVertex)); modeRefTypes[mm1TwoPoints].push_back(cat(rtLine)); modeRefTypes[mm1Asymptote1].push_back(cat(rtHyperbola)); @@ -2203,30 +2346,31 @@ AttachEngineLine::AttachEngineLine() modeRefTypes[mm1Proximity].push_back(cat(rtAnything, rtAnything)); modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything)); - modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything,rtAnything)); - modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything,rtAnything,rtAnything)); - modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything,rtAnything,rtAnything,rtAnything)); + modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything, rtAnything)); + modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything, rtAnything, rtAnything)); + modeRefTypes[mm1AxisInertia1].push_back(cat(rtAnything, rtAnything, rtAnything, rtAnything)); modeRefTypes[mm1AxisInertia2] = modeRefTypes[mm1AxisInertia1]; modeRefTypes[mm1AxisInertia3] = modeRefTypes[mm1AxisInertia1]; modeRefTypes[mm1FaceNormal] = attacher3D.modeRefTypes[mmTangentPlane]; - modeRefTypes[mm1Intersection].push_back(cat(rtFace,rtFace)); + modeRefTypes[mm1Intersection].push_back(cat(rtFace, rtFace)); this->EnableAllSupportedModes(); } -AttachEngineLine *AttachEngineLine::copy() const +AttachEngineLine* AttachEngineLine::copy() const { AttachEngineLine* p = new AttachEngineLine; p->setUp(*this); return p; } -Base::Placement -AttachEngineLine::_calculateAttachedPlacement(const std::vector& objs, - const std::vector& subs, - const Base::Placement& origPlacement) const +Base::Placement AttachEngineLine::_calculateAttachedPlacement( + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement +) const { eMapMode mmode = this->mapMode; @@ -2250,7 +2394,8 @@ AttachEngineLine::_calculateAttachedPlacement(const std::vector points; - for (const auto & shape : shapes) { - const TopoDS_Shape &sh = shape->getShape(); + for (const auto& shape : shapes) { + const TopoDS_Shape& sh = shape->getShape(); if (sh.IsNull()) { throw Base::ValueError( - "Null shape in AttachEngineLine::calculateAttachedPlacement()!"); + "Null shape in AttachEngineLine::calculateAttachedPlacement()!" + ); } if (sh.ShapeType() == TopAbs_VERTEX) { const TopoDS_Vertex& v = TopoDS::Vertex(sh); @@ -2372,8 +2522,10 @@ AttachEngineLine::_calculateAttachedPlacement(const std::vectorisNull()) { throw Base::ValueError( - "Null shape in AttachEngineLine::calculateAttachedPlacement()!"); + "Null shape in AttachEngineLine::calculateAttachedPlacement()!" + ); } TopoDS_Edge e; try { @@ -2397,13 +2550,15 @@ AttachEngineLine::_calculateAttachedPlacement(const std::vectorisNull()) { throw Base::ValueError( - "Null shape in AttachEngineLine::calculateAttachedPlacement()!"); + "Null shape in AttachEngineLine::calculateAttachedPlacement()!" + ); } TopoDS_Edge e; try { @@ -2428,7 +2584,8 @@ AttachEngineLine::_calculateAttachedPlacement(const std::vectorisNull() || shapes[1]->isNull()) { throw Base::ValueError( - "Null shape in AttachEngineLine::calculateAttachedPlacement()!"); + "Null shape in AttachEngineLine::calculateAttachedPlacement()!" + ); } const TopoDS_Face& face1 = TopoDS::Face(shapes[0]->getShape()); @@ -2484,23 +2646,30 @@ AttachEngineLine::_calculateAttachedPlacement(const std::vectorisNull()) { throw Base::ValueError( - "Null shape in AttachEngineLine::calculateAttachedPlacement()!"); + "Null shape in AttachEngineLine::calculateAttachedPlacement()!" + ); } if (shapes[1]->isNull()) { throw Base::ValueError( - "Null shape in AttachEngineLine::calculateAttachedPlacement()!"); + "Null shape in AttachEngineLine::calculateAttachedPlacement()!" + ); } BRepExtrema_DistShapeShape distancer(shapes[0]->getShape(), shapes[1]->getShape()); if (!distancer.IsDone()) { - throw Base::ValueError("AttachEngineLine::calculateAttachedPlacement: " - "proximity calculation failed."); + throw Base::ValueError( + "AttachEngineLine::calculateAttachedPlacement: " + "proximity calculation failed." + ); } if (distancer.NbSolution() > 1) { - Base::Console().warning("AttachEngineLine::calculateAttachedPlacement: " - "proximity calculation gave %i solutions, ambiguous.\n", - int(distancer.NbSolution())); + Base::Console().warning( + "AttachEngineLine::calculateAttachedPlacement: " + "proximity calculation gave %i solutions, ambiguous.\n", + int(distancer.NbSolution()) + ); } gp_Pnt p1 = distancer.PointOnShape1(1); gp_Pnt p2 = distancer.PointOnShape2(1); @@ -2537,7 +2713,8 @@ AttachEngineLine::_calculateAttachedPlacement(const std::vectorplacementFactory(LineDir, - gp_Vec(), - LineBasePoint, - refOrg, - /*useRefOrg_Line = */ true); + plm = this->placementFactory( + LineDir, + gp_Vec(), + LineBasePoint, + refOrg, + /*useRefOrg_Line = */ true + ); } else { // reuse 3d mode AttachEngine3D attacher3D; attacher3D.setUp(*this); attacher3D.mapMode = mmode; - attacher3D.attachmentOffset = - Base::Placement(); // AttachmentOffset is applied separately here, afterwards. So we - // are resetting it in sub-attacher to avoid applying it twice! + attacher3D.attachmentOffset + = Base::Placement(); // AttachmentOffset is applied separately here, afterwards. So we + // are resetting it in sub-attacher to avoid applying it twice! plm = attacher3D._calculateAttachedPlacement(objs, subs, origPlacement); plm *= presuperPlacement; } @@ -2572,11 +2751,11 @@ TYPESYSTEM_SOURCE(Attacher::AttachEnginePoint, Attacher::AttachEngine) AttachEnginePoint::AttachEnginePoint() { - //fill type lists for modes + // fill type lists for modes modeRefTypes.resize(mmDummy_NumberOfModes); refTypeString s; - //reused 3d modes + // reused 3d modes AttachEngine3D attacher3D; modeRefTypes[mm0Origin] = attacher3D.modeRefTypes[mmObjectXY]; modeRefTypes[mm0CenterOfCurvature] = attacher3D.modeRefTypes[mmRevolutionSection]; @@ -2595,24 +2774,25 @@ AttachEnginePoint::AttachEnginePoint() modeRefTypes[mm0ProximityPoint2].push_back(s); modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything)); - modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything,rtAnything)); - modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything,rtAnything,rtAnything)); - modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything,rtAnything,rtAnything,rtAnything)); + modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything, rtAnything)); + modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything, rtAnything, rtAnything)); + modeRefTypes[mm0CenterOfMass].push_back(cat(rtAnything, rtAnything, rtAnything, rtAnything)); this->EnableAllSupportedModes(); } -AttachEnginePoint *AttachEnginePoint::copy() const +AttachEnginePoint* AttachEnginePoint::copy() const { AttachEnginePoint* p = new AttachEnginePoint; p->setUp(*this); return p; } -Base::Placement -AttachEnginePoint::_calculateAttachedPlacement(const std::vector& objs, - const std::vector& subs, - const Base::Placement& origPlacement) const +Base::Placement AttachEnginePoint::_calculateAttachedPlacement( + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement +) const { eMapMode mmode = this->mapMode; @@ -2661,7 +2841,8 @@ AttachEnginePoint::_calculateAttachedPlacement(const std::vectorgetShape(); if (sh.IsNull()) { throw Base::ValueError( - "Null shape in AttachEnginePoint::calculateAttachedPlacement()!"); + "Null shape in AttachEnginePoint::calculateAttachedPlacement()!" + ); } if (sh.ShapeType() == TopAbs_VERTEX) { const TopoDS_Vertex& v = TopoDS::Vertex(sh); @@ -2682,7 +2863,8 @@ AttachEnginePoint::_calculateAttachedPlacement(const std::vectorisNull()) { throw Base::ValueError( - "Null shape in AttachEnginePoint::calculateAttachedPlacement()!"); + "Null shape in AttachEnginePoint::calculateAttachedPlacement()!" + ); } TopoDS_Edge e; try { @@ -2692,7 +2874,8 @@ AttachEnginePoint::_calculateAttachedPlacement(const std::vectorisNull()) { throw Base::ValueError( - "Null shape in AttachEnginePoint::calculateAttachedPlacement()!"); + "Null shape in AttachEnginePoint::calculateAttachedPlacement()!" + ); } if (shapes[1]->isNull()) { throw Base::ValueError( - "Null shape in AttachEnginePoint::calculateAttachedPlacement()!"); + "Null shape in AttachEnginePoint::calculateAttachedPlacement()!" + ); } BasePoint = getProximityPoint(mmode, shapes[0]->getShape(), shapes[1]->getShape()); @@ -2753,25 +2942,26 @@ AttachEnginePoint::_calculateAttachedPlacement(const std::vectorplacementFactory(gp_Vec(0.0, 0.0, 1.0), - gp_Vec(1.0, 0.0, 0.0), - BasePoint, - gp_Pnt()); + plm = this->placementFactory(gp_Vec(0.0, 0.0, 1.0), gp_Vec(1.0, 0.0, 0.0), BasePoint, gp_Pnt()); } else { // reuse 3d mode AttachEngine3D attacher3D; attacher3D.setUp(*this); attacher3D.mapMode = mmode; - attacher3D.attachmentOffset = - Base::Placement(); // AttachmentOffset is applied separately here, afterwards. So we - // are resetting it in sub-attacher to avoid applying it twice! + attacher3D.attachmentOffset + = Base::Placement(); // AttachmentOffset is applied separately here, afterwards. So we + // are resetting it in sub-attacher to avoid applying it twice! plm = attacher3D._calculateAttachedPlacement(objs, subs, origPlacement); } plm *= this->attachmentOffset; return plm; } -gp_Pnt AttachEnginePoint::getProximityPoint(eMapMode mmode, const TopoDS_Shape& s1, const TopoDS_Shape& s2) const +gp_Pnt AttachEnginePoint::getProximityPoint( + eMapMode mmode, + const TopoDS_Shape& s1, + const TopoDS_Shape& s2 +) const { // #0003921: Crash when opening document with datum point intersecting line and plane // @@ -2781,13 +2971,11 @@ gp_Pnt AttachEnginePoint::getProximityPoint(eMapMode mmode, const TopoDS_Shape& // try to determine intersection points. try { TopoDS_Shape face, edge; - if (s1.ShapeType() == TopAbs_FACE && - s2.ShapeType() == TopAbs_EDGE) { + if (s1.ShapeType() == TopAbs_FACE && s2.ShapeType() == TopAbs_EDGE) { face = s1; edge = s2; } - else if (s1.ShapeType() == TopAbs_EDGE && - s2.ShapeType() == TopAbs_FACE) { + else if (s1.ShapeType() == TopAbs_EDGE && s2.ShapeType() == TopAbs_FACE) { edge = s1; face = s2; } @@ -2801,8 +2989,8 @@ gp_Pnt AttachEnginePoint::getProximityPoint(eMapMode mmode, const TopoDS_Shape& try { // Important note about BRepIntCurveSurface_Inter and GeomAdaptor_Curve // - // A GeomAdaptor_Curve obtained directly from BRepAdaptor_Curve will lose the information - // about Location/orientation of the edge. + // A GeomAdaptor_Curve obtained directly from BRepAdaptor_Curve will lose the + // information about Location/orientation of the edge. // // That's why GeomAdaptor::MakeCurve() is used to create a new geometry with the // transformation applied. @@ -2829,29 +3017,45 @@ gp_Pnt AttachEnginePoint::getProximityPoint(eMapMode mmode, const TopoDS_Shape& points.push_back(pnt); } - if (points.size() > 1) - Base::Console().warning("AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %d solutions, ambiguous.\n", int(points.size())); + if (points.size() > 1) { + Base::Console().warning( + "AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %d " + "solutions, ambiguous.\n", + int(points.size()) + ); + } // if an intersection is found return the first hit // otherwise continue with BRepExtrema_DistShapeShape - if (!points.empty()) + if (!points.empty()) { return points.front(); + } } } catch (const Standard_Failure&) { // ignore } - BRepExtrema_DistShapeShape distancer (s1, s2); - if (!distancer.IsDone()) - throw Base::ValueError("AttachEnginePoint::calculateAttachedPlacement: proximity calculation failed."); - if (distancer.NbSolution() > 1) - Base::Console().warning("AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %i solutions, ambiguous.\n",int(distancer.NbSolution())); + BRepExtrema_DistShapeShape distancer(s1, s2); + if (!distancer.IsDone()) { + throw Base::ValueError( + "AttachEnginePoint::calculateAttachedPlacement: proximity calculation failed." + ); + } + if (distancer.NbSolution() > 1) { + Base::Console().warning( + "AttachEnginePoint::calculateAttachedPlacement: proximity calculation gave %i " + "solutions, ambiguous.\n", + int(distancer.NbSolution()) + ); + } gp_Pnt p1 = distancer.PointOnShape1(1); gp_Pnt p2 = distancer.PointOnShape2(1); - if (mmode == mm0ProximityPoint1) + if (mmode == mm0ProximityPoint1) { return p1; - else + } + else { return p2; + } } diff --git a/src/Mod/Part/App/Attacher.h b/src/Mod/Part/App/Attacher.h index e6e543aebc..2b2263bed0 100644 --- a/src/Mod/Part/App/Attacher.h +++ b/src/Mod/Part/App/Attacher.h @@ -22,10 +22,10 @@ * * ***************************************************************************/ /** - *Attacher.h, Attacher.cpp contain the functionality of deriving placement - *from a set of geometric subelements. Examples are: sketch attachment, datum - *plane placement. - */ + *Attacher.h, Attacher.cpp contain the functionality of deriving placement + *from a set of geometric subelements. Examples are: sketch attachment, datum + *plane placement. + */ #ifndef PARTATTACHER_H #define PARTATTACHER_H @@ -49,8 +49,10 @@ namespace Attacher class AttachEngine; -//Attention! The numbers associated to the modes are permanent, because they are what get written into files. -enum eMapMode { +// Attention! The numbers associated to the modes are permanent, because they are what get written +// into files. +enum eMapMode +{ mmDeactivated, mmTranslate, mmObjectXY, @@ -114,8 +116,8 @@ enum eMapMode { mmParallelPlane, mmMidpoint, - mmDummy_NumberOfModes//a value useful to check the validity of mode value -};//see also eMapModeStrings[] definition in .cpp + mmDummy_NumberOfModes // a value useful to check the validity of mode value +}; // see also eMapModeStrings[] definition in .cpp /** @@ -123,62 +125,73 @@ enum eMapMode { * also AttachEngine::eRefTypeStrings, AttachEngine::getShapeType(), * AttachEngine::downgradeType(), AttacherTexts.cpp/getShTypeText() */ -enum eRefType { - //topo //ranks: (number of times the type is downgradable) - rtAnything, //0 - rtVertex, //1 - rtEdge, //1 - rtFace, //1 - //edges: - rtLine, //2 - rtCurve, //2 - rtCircle, //3 - rtConic, //3 - rtEllipse, //4 - rtParabola, //4 - rtHyperbola, //4 - //faces: - rtFlatFace, //2 - rtSphericalFace, //2//flatface, shericalface are also surfaces of revolution, but the axis isn't defined. - rtSurfaceRev, //2 - rtCylindricalFace, //3 - rtToroidalFace, //3 - rtConicalFace, //3 - //shapes: - rtPart, //1 - rtSolid, //2 - rtWire, //2 - rtDummy_numberOfShapeTypes,//a value useful to check the validity of value - rtFlagHasPlacement = 0x0100 //indicates that the linked shape is a whole FreeCAD object that has placement available. +enum eRefType +{ + // topo //ranks: (number of times the type is downgradable) + rtAnything, // 0 + rtVertex, // 1 + rtEdge, // 1 + rtFace, // 1 + // edges: + rtLine, // 2 + rtCurve, // 2 + rtCircle, // 3 + rtConic, // 3 + rtEllipse, // 4 + rtParabola, // 4 + rtHyperbola, // 4 + // faces: + rtFlatFace, // 2 + rtSphericalFace, // 2//flatface, shericalface are also surfaces of revolution, but the axis + // isn't defined. + rtSurfaceRev, // 2 + rtCylindricalFace, // 3 + rtToroidalFace, // 3 + rtConicalFace, // 3 + // shapes: + rtPart, // 1 + rtSolid, // 2 + rtWire, // 2 + rtDummy_numberOfShapeTypes, // a value useful to check the validity of value + rtFlagHasPlacement = 0x0100 // indicates that the linked shape is a whole FreeCAD object that + // has placement available. }; -using refTypeString = std::vector; //a sequence of ref types, according to AttachmentSupport contents for example -using refTypeStringList = std::vector; //a set of type strings, defines which selection sets are supported by a certain mode +using refTypeString = std::vector; // a sequence of ref types, according to + // AttachmentSupport contents for example +using refTypeStringList = std::vector; // a set of type strings, defines which + // selection sets are supported by a certain + // mode /** - * @brief The SuggestResult struct is a container for output information of AttachEngine mode suggesting routine. + * @brief The SuggestResult struct is a container for output information of AttachEngine mode + * suggesting routine. */ -struct SuggestResult{ +struct SuggestResult +{ /** * @brief message contains overall verdict of suggestor on current reference set */ - enum eSuggestResult{ - srOK, //references are valid for at least one mode - srLinkBroken, //failed to resolve out some of current references. Exception info is stored in SuggestResult::error. + enum eSuggestResult + { + srOK, // references are valid for at least one mode + srLinkBroken, // failed to resolve out some of current references. Exception info is stored + // in SuggestResult::error. srUnexpectedError, - srNoModesFit,//none of the available mapping modes accepts the set of topological type - srIncompatibleGeometry,//there is a mode that could fit, but geometry is wrong (e.g. a line is required, but a curve was passed). + srNoModesFit, // none of the available mapping modes accepts the set of topological type + srIncompatibleGeometry, // there is a mode that could fit, but geometry is wrong (e.g. a + // line is required, but a curve was passed). }; eSuggestResult message; /** - * @brief allApplicableModes. Vector array that will receive the list of - * all modes that are applicable to current set of references. It doesn't - * guarantee that all modes will work, it only checks that subelemnts are - * of right type. - */ + * @brief allApplicableModes. Vector array that will receive the list of + * all modes that are applicable to current set of references. It doesn't + * guarantee that all modes will work, it only checks that subelemnts are + * of right type. + */ std::vector allApplicableModes; /** @@ -218,33 +231,41 @@ struct SuggestResult{ * hints and so on. It can be used separately, without deriving from * AttachableObject. */ -class PartExport AttachEngine : public Base::BaseClass +class PartExport AttachEngine: public Base::BaseClass { TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: //methods - AttachEngine(); - virtual void setUp(const App::PropertyLinkSubList &references, - eMapMode mapMode = mmDeactivated, - bool mapReverse = false, - double attachParameter = 0.0, - double surfU = 0.0, double surfV = 0.0, - const Base::Placement &attachmentOffset = Base::Placement()); - virtual void setUp(const AttachEngine &another); - void setOffset(const Base::Placement &offset); +public: // methods + AttachEngine(); + virtual void setUp( + const App::PropertyLinkSubList& references, + eMapMode mapMode = mmDeactivated, + bool mapReverse = false, + double attachParameter = 0.0, + double surfU = 0.0, + double surfV = 0.0, + const Base::Placement& attachmentOffset = Base::Placement() + ); + virtual void setUp(const AttachEngine& another); + + void setOffset(const Base::Placement& offset); virtual AttachEngine* copy() const = 0; Base::Placement calculateAttachedPlacement( - const Base::Placement &origPlacement, bool *subChanged=0); + const Base::Placement& origPlacement, + bool* subChanged = 0 + ); virtual Base::Placement _calculateAttachedPlacement( - const std::vector &objs, - const std::vector &subs, - const Base::Placement &origPlacement) const = 0; + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement + ) const + = 0; - void setReferences(const App::PropertyLinkSubList &references); - void setReferences(const std::vector &references); + void setReferences(const App::PropertyLinkSubList& references); + void setReferences(const std::vector& references); /** * @brief placementFactory calculates placement from Z axis direction, @@ -281,15 +302,17 @@ public: //methods * * @return the resulting placement. ReverseXY property of Attacher will be automatically applied. */ - Base::Placement placementFactory(const gp_Dir &ZAxis, - gp_Vec XAxis, - gp_Pnt Origin, - gp_Pnt refOrg = gp_Pnt(), - bool useRefOrg_Line = false, - bool useRefOrg_Plane = false, - bool makeYVertical = false, - bool makeLegacyFlatFaceOrientation = false, - Base::Placement* placeOfRef = nullptr) const; + Base::Placement placementFactory( + const gp_Dir& ZAxis, + gp_Vec XAxis, + gp_Pnt Origin, + gp_Pnt refOrg = gp_Pnt(), + bool useRefOrg_Line = false, + bool useRefOrg_Plane = false, + bool makeYVertical = false, + bool makeLegacyFlatFaceOrientation = false, + Base::Placement* placeOfRef = nullptr + ) const; /** * @brief suggestMapModes is the procedure that knows everything about @@ -300,31 +323,32 @@ public: //methods * @param result (output). Returns results of suggestion, such as best fit * mode, list of all modes that apply, hints, etc. */ - virtual void suggestMapModes(SuggestResult &result) const; + virtual void suggestMapModes(SuggestResult& result) const; /** - * @brief EnableAllModes enables all modes that have shape type lists filled. The function acts on modeEnabled array. + * @brief EnableAllModes enables all modes that have shape type lists filled. The function acts + * on modeEnabled array. */ void EnableAllSupportedModes(); ~AttachEngine() override = default; -public://helper functions that may be useful outside of the class +public: // helper functions that may be useful outside of the class /** * @brief getShapeType by shape. Will never set rtFlagHasPlacement. * @param sh * @return */ - static eRefType getShapeType(const TopoDS_Shape &sh); + static eRefType getShapeType(const TopoDS_Shape& sh); /** * @brief getShapeType by link content. Will include rtFlagHasPlacement, if applies. * @param obj - * @param subshape (input). Can be empty string (then, whole object will be used for shape type testing) + * @param subshape (input). Can be empty string (then, whole object will be used for shape type + * testing) * @return */ - static eRefType getShapeType(const App::DocumentObject* obj, - const std::string &subshape); + static eRefType getShapeType(const App::DocumentObject* obj, const std::string& subshape); /** * @brief downgradeType converts a more-specific type into a less-specific @@ -345,7 +369,8 @@ public://helper functions that may be useful outside of the class static int getTypeRank(eRefType type); /** - * @brief isShapeOfType tests if a shape fulfills the requirement of a mode, and returns a score of how spot on was the requirement. + * @brief isShapeOfType tests if a shape fulfills the requirement of a mode, and returns a score + * of how spot on was the requirement. * @param shapeType (use return value of AttachEngine::getShapeType) * @param requirement * @return : -1 - doesn't fulfill, @@ -362,16 +387,19 @@ public://helper functions that may be useful outside of the class */ static std::string getModeName(eMapMode mmode); - static eMapMode getModeByName(const std::string &modeName); + static eMapMode getModeByName(const std::string& modeName); static std::string getRefTypeName(eRefType shapeType); - static eRefType getRefTypeByName(const std::string &typeName); + static eRefType getRefTypeByName(const std::string& typeName); - static GProp_GProps getInertialPropsOfShape(const std::vector &shapes); + static GProp_GProps getInertialPropsOfShape(const std::vector& shapes); std::vector getRefObjects() const; - const std::vector &getSubValues() const {return subnames;} + const std::vector& getSubValues() const + { + return subnames; + } /** * @brief verifyReferencesAreSafe: checks if pointers in references still @@ -380,12 +408,12 @@ public://helper functions that may be useful outside of the class */ static void verifyReferencesAreSafe(const App::PropertyLinkSubList& references); -public: //enums +public: // enums static const char* eMapModeStrings[]; static const char* eRefTypeStrings[]; -public: //members +public: // members std::string docName; std::vector objNames; std::vector subnames; @@ -405,28 +433,33 @@ public: //members */ std::vector modeEnabled; - std::vector modeRefTypes; //a complete data structure, containing info on which modes support what selection + std::vector modeRefTypes; // a complete data structure, containing info on + // which modes support what selection protected: - refTypeString cat(eRefType rt1){ + refTypeString cat(eRefType rt1) + { refTypeString ret; ret.push_back(rt1); return ret; } - refTypeString cat(eRefType rt1, eRefType rt2){ + refTypeString cat(eRefType rt1, eRefType rt2) + { refTypeString ret; ret.push_back(rt1); ret.push_back(rt2); return ret; } - refTypeString cat(eRefType rt1, eRefType rt2, eRefType rt3){ + refTypeString cat(eRefType rt1, eRefType rt2, eRefType rt3) + { refTypeString ret; ret.push_back(rt1); ret.push_back(rt2); ret.push_back(rt3); return ret; } - refTypeString cat(eRefType rt1, eRefType rt2, eRefType rt3, eRefType rt4){ + refTypeString cat(eRefType rt1, eRefType rt2, eRefType rt3, eRefType rt4) + { refTypeString ret; ret.push_back(rt1); ret.push_back(rt2); @@ -434,12 +467,14 @@ protected: ret.push_back(rt4); return ret; } - static void readLinks(const std::vector &objs, - const std::vector &subs, + static void readLinks( + const std::vector& objs, + const std::vector& subs, - std::vector& shapes, - std::vector &storage, - std::vector &types); + std::vector& shapes, + std::vector& storage, + std::vector& types + ); static void throwWrongMode(eMapMode mmode); @@ -469,58 +504,67 @@ protected: }; -class PartExport AttachEngine3D : public AttachEngine +class PartExport AttachEngine3D: public AttachEngine { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: AttachEngine3D(); AttachEngine3D* copy() const override; Base::Placement _calculateAttachedPlacement( - const std::vector &objs, - const std::vector &subs, - const Base::Placement &origPlacement) const override; + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement + ) const override; + private: double calculateFoldAngle(gp_Vec axA, gp_Vec axB, gp_Vec edA, gp_Vec edB) const; }; -//attacher specialized for datum planes -class PartExport AttachEnginePlane : public AttachEngine +// attacher specialized for datum planes +class PartExport AttachEnginePlane: public AttachEngine { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: AttachEnginePlane(); AttachEnginePlane* copy() const override; Base::Placement _calculateAttachedPlacement( - const std::vector &objs, - const std::vector &subs, - const Base::Placement &origPlacement) const override; + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement + ) const override; static double planarPrecision(); }; -//attacher specialized for datum lines -class PartExport AttachEngineLine : public AttachEngine +// attacher specialized for datum lines +class PartExport AttachEngineLine: public AttachEngine { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: AttachEngineLine(); AttachEngineLine* copy() const override; Base::Placement _calculateAttachedPlacement( - const std::vector &objs, - const std::vector &subs, - const Base::Placement &origPlacement) const override; + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement + ) const override; }; -//attacher specialized for datum points -class PartExport AttachEnginePoint : public AttachEngine +// attacher specialized for datum points +class PartExport AttachEnginePoint: public AttachEngine { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: AttachEnginePoint(); AttachEnginePoint* copy() const override; Base::Placement _calculateAttachedPlacement( - const std::vector &objs, - const std::vector &subs, - const Base::Placement &origPlacement) const override; + const std::vector& objs, + const std::vector& subs, + const Base::Placement& origPlacement + ) const override; private: gp_Pnt getProximityPoint(eMapMode mode, const TopoDS_Shape& s1, const TopoDS_Shape& s2) const; @@ -528,14 +572,17 @@ private: //==================================================================== -class ExceptionCancel : public Base::Exception +class ExceptionCancel: public Base::Exception { public: ExceptionCancel() = default; - explicit ExceptionCancel(char* msg){this->setMessage(msg);} + explicit ExceptionCancel(char* msg) + { + this->setMessage(msg); + } ~ExceptionCancel() noexcept override = default; }; -} // namespace Attacher +} // namespace Attacher -#endif // PARTATTACHER_H +#endif // PARTATTACHER_H diff --git a/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp b/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp index 08dd563985..592af39647 100644 --- a/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp +++ b/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp @@ -24,9 +24,9 @@ #include -# include -# include -# include +#include +#include +#include #include @@ -41,7 +41,7 @@ using namespace Part; -PyObject *MakePrismPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* MakePrismPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of MakePrismPy return new MakePrismPy(nullptr); @@ -56,21 +56,40 @@ int MakePrismPy::PyInit(PyObject* args, PyObject* kwds) PyObject* Direction; int Fuse; PyObject* Modify; - static const std::array keywords{"Sbase", "Pbase", "Skface", "Direction", "Fuse", "Modify", - nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!O!iO!", keywords, - &(TopoShapePy::Type), &Sbase, - &(TopoShapePy::Type), &Pbase, - &(TopoShapeFacePy::Type), &Skface, - &(Base::VectorPy::Type), &Direction, &Fuse, - &(PyBool_Type), &Modify)) { + static const std::array + keywords {"Sbase", "Pbase", "Skface", "Direction", "Fuse", "Modify", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!O!iO!", + keywords, + &(TopoShapePy::Type), + &Sbase, + &(TopoShapePy::Type), + &Pbase, + &(TopoShapeFacePy::Type), + &Skface, + &(Base::VectorPy::Type), + &Direction, + &Fuse, + &(PyBool_Type), + &Modify + )) { try { TopoDS_Shape sbase = static_cast(Sbase)->getTopoShapePtr()->getShape(); TopoDS_Shape pbase = static_cast(Pbase)->getTopoShapePtr()->getShape(); - TopoDS_Face skface = TopoDS::Face(static_cast(Skface)->getTopoShapePtr()->getShape()); + TopoDS_Face skface = TopoDS::Face( + static_cast(Skface)->getTopoShapePtr()->getShape() + ); Base::Vector3d dir = static_cast(Direction)->value(); - std::unique_ptr ptr(new BRepFeat_MakePrism(sbase, pbase, skface, gp_Dir(dir.x, dir.y, dir.z), Fuse, - Base::asBoolean(Modify))); + std::unique_ptr ptr(new BRepFeat_MakePrism( + sbase, + pbase, + skface, + gp_Dir(dir.x, dir.y, dir.z), + Fuse, + Base::asBoolean(Modify) + )); setTwinPointer(ptr.release()); return 0; @@ -94,9 +113,13 @@ int MakePrismPy::PyInit(PyObject* args, PyObject* kwds) } } - PyErr_SetString(PyExc_TypeError, "supported signatures:\n" - "MakePrism()\n" - "MakePrism(Sbase [shape], Pbase [shape], Skface [face], Direction [Vector], Fuse [int={0, 1}], Modify [bool])\n"); + PyErr_SetString( + PyExc_TypeError, + "supported signatures:\n" + "MakePrism()\n" + "MakePrism(Sbase [shape], Pbase [shape], Skface [face], Direction [Vector], Fuse [int={0, " + "1}], Modify [bool])\n" + ); return -1; } @@ -106,7 +129,7 @@ std::string MakePrismPy::representation() const return {""}; } -PyObject* MakePrismPy::init(PyObject *args, PyObject* kwds) +PyObject* MakePrismPy::init(PyObject* args, PyObject* kwds) { PyObject* Sbase; PyObject* Pbase; @@ -114,14 +137,25 @@ PyObject* MakePrismPy::init(PyObject *args, PyObject* kwds) PyObject* Direction; int Fuse; PyObject* Modify; - static const std::array keywords{"Sbase", "Pbase", "Skface", "Direction", "Fuse", "Modify", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!O!iO!", keywords, - &(TopoShapePy::Type), &Sbase, - &(TopoShapePy::Type), &Pbase, - &(TopoShapeFacePy::Type), &Skface, - &(Base::VectorPy::Type), &Direction, &Fuse, - &(PyBool_Type), &Modify)) { + static const std::array + keywords {"Sbase", "Pbase", "Skface", "Direction", "Fuse", "Modify", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!O!iO!", + keywords, + &(TopoShapePy::Type), + &Sbase, + &(TopoShapePy::Type), + &Pbase, + &(TopoShapeFacePy::Type), + &Skface, + &(Base::VectorPy::Type), + &Direction, + &Fuse, + &(PyBool_Type), + &Modify + )) { return nullptr; } @@ -129,10 +163,12 @@ PyObject* MakePrismPy::init(PyObject *args, PyObject* kwds) try { TopoDS_Shape sbase = static_cast(Sbase)->getTopoShapePtr()->getShape(); TopoDS_Shape pbase = static_cast(Pbase)->getTopoShapePtr()->getShape(); - TopoDS_Face skface = TopoDS::Face(static_cast(Skface)->getTopoShapePtr()->getShape()); + TopoDS_Face skface = TopoDS::Face( + static_cast(Skface)->getTopoShapePtr()->getShape() + ); Base::Vector3d dir = static_cast(Direction)->value(); - getBRepFeat_MakePrismPtr()->Init(sbase, pbase, skface, gp_Dir(dir.x, dir.y, dir.z), Fuse, - Base::asBoolean(Modify)); + getBRepFeat_MakePrismPtr() + ->Init(sbase, pbase, skface, gp_Dir(dir.x, dir.y, dir.z), Fuse, Base::asBoolean(Modify)); Py_Return; } @@ -142,14 +178,21 @@ PyObject* MakePrismPy::init(PyObject *args, PyObject* kwds) } } -PyObject* MakePrismPy::add(PyObject *args, PyObject* kwds) +PyObject* MakePrismPy::add(PyObject* args, PyObject* kwds) { PyObject* Edge; PyObject* Face; - static const std::array keywords{"Edge", "Face", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!", keywords, - &(TopoShapeEdgePy::Type), &Edge, - &(TopoShapeFacePy::Type), &Face)) { + static const std::array keywords {"Edge", "Face", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!", + keywords, + &(TopoShapeEdgePy::Type), + &Edge, + &(TopoShapeFacePy::Type), + &Face + )) { return nullptr; } @@ -167,14 +210,21 @@ PyObject* MakePrismPy::add(PyObject *args, PyObject* kwds) } } -PyObject* MakePrismPy::perform(PyObject *args, PyObject* kwds) +PyObject* MakePrismPy::perform(PyObject* args, PyObject* kwds) { PyObject* From; PyObject* Until; - static const std::array keywords_fu{"From", "Until", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!", keywords_fu, - &(TopoShapePy::Type), &From, - &(TopoShapePy::Type), &Until)) { + static const std::array keywords_fu {"From", "Until", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!", + keywords_fu, + &(TopoShapePy::Type), + &From, + &(TopoShapePy::Type), + &Until + )) { try { TopoDS_Shape from = static_cast(From)->getTopoShapePtr()->getShape(); TopoDS_Shape until = static_cast(Until)->getTopoShapePtr()->getShape(); @@ -188,8 +238,8 @@ PyObject* MakePrismPy::perform(PyObject *args, PyObject* kwds) } PyErr_Clear(); - static const std::array keywords_u {"Until", nullptr}; - if (Base:: Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_u, &(TopoShapePy::Type), &Until)) { + static const std::array keywords_u {"Until", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_u, &(TopoShapePy::Type), &Until)) { try { TopoDS_Shape until = static_cast(Until)->getTopoShapePtr()->getShape(); getBRepFeat_MakePrismPtr()->Perform(until); @@ -203,7 +253,7 @@ PyObject* MakePrismPy::perform(PyObject *args, PyObject* kwds) PyErr_Clear(); double length; - static const std::array keywords_l {"Length", nullptr}; + static const std::array keywords_l {"Length", nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d", keywords_l, &length)) { try { getBRepFeat_MakePrismPtr()->Perform(length); @@ -215,17 +265,21 @@ PyObject* MakePrismPy::perform(PyObject *args, PyObject* kwds) } } - PyErr_SetString(PyExc_TypeError, "supported signatures:\n" - "perform(From [shape], Until [shape])\n" - "perform(Until [shape])\n" - "perform(Length [float])\n"); + PyErr_SetString( + PyExc_TypeError, + "supported signatures:\n" + "perform(From [shape], Until [shape])\n" + "perform(Until [shape])\n" + "perform(Length [float])\n" + ); return nullptr; } -PyObject* MakePrismPy::performUntilEnd(PyObject *args) +PyObject* MakePrismPy::performUntilEnd(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { getBRepFeat_MakePrismPtr()->PerformUntilEnd(); @@ -237,11 +291,12 @@ PyObject* MakePrismPy::performUntilEnd(PyObject *args) } } -PyObject* MakePrismPy::performFromEnd(PyObject *args) +PyObject* MakePrismPy::performFromEnd(PyObject* args) { PyObject* Until; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &Until)) + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &Until)) { return nullptr; + } try { TopoDS_Shape until = static_cast(Until)->getTopoShapePtr()->getShape(); @@ -254,10 +309,11 @@ PyObject* MakePrismPy::performFromEnd(PyObject *args) } } -PyObject* MakePrismPy::performThruAll(PyObject *args) +PyObject* MakePrismPy::performThruAll(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { getBRepFeat_MakePrismPtr()->PerformThruAll(); @@ -269,12 +325,13 @@ PyObject* MakePrismPy::performThruAll(PyObject *args) } } -PyObject* MakePrismPy::performUntilHeight(PyObject *args) +PyObject* MakePrismPy::performUntilHeight(PyObject* args) { PyObject* Until; double length; - if (!PyArg_ParseTuple(args, "O!d", &(TopoShapePy::Type), &Until, &length)) + if (!PyArg_ParseTuple(args, "O!d", &(TopoShapePy::Type), &Until, &length)) { return nullptr; + } try { TopoDS_Shape until = static_cast(Until)->getTopoShapePtr()->getShape(); @@ -287,10 +344,11 @@ PyObject* MakePrismPy::performUntilHeight(PyObject *args) } } -PyObject* MakePrismPy::curves(PyObject *args) const +PyObject* MakePrismPy::curves(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TColGeom_SequenceOfCurve S; getBRepFeat_MakePrismPtr()->Curves(S); @@ -298,8 +356,9 @@ PyObject* MakePrismPy::curves(PyObject *args) const Py::Tuple tuple(S.Length()); for (int i = S.Lower(); i <= S.Upper(); ++i) { Handle(Geom_Curve) hC = S.Value(i); - if (hC.IsNull()) + if (hC.IsNull()) { continue; + } std::unique_ptr gc(Part::makeFromCurve(hC)); tuple.setItem(i, Py::asObject(gc->getPyObject())); } @@ -307,22 +366,25 @@ PyObject* MakePrismPy::curves(PyObject *args) const return Py::new_reference_to(tuple); } -PyObject* MakePrismPy::barycCurve(PyObject *args) const +PyObject* MakePrismPy::barycCurve(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(Geom_Curve) hC = getBRepFeat_MakePrismPtr()->BarycCurve(); - if (hC.IsNull()) + if (hC.IsNull()) { Py_Return; + } std::unique_ptr gc(Part::makeFromCurve(hC)); return gc->getPyObject(); } -PyObject* MakePrismPy::shape(PyObject *args) const +PyObject* MakePrismPy::shape(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { TopoShape shape(getBRepFeat_MakePrismPtr()->Shape()); @@ -334,7 +396,7 @@ PyObject* MakePrismPy::shape(PyObject *args) const } } -PyObject *MakePrismPy::getCustomAttributes(const char* /*attr*/) const +PyObject* MakePrismPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/BRepMesh.cpp b/src/Mod/Part/App/BRepMesh.cpp index 96a658593b..f7b1c6a983 100644 --- a/src/Mod/Part/App/BRepMesh.cpp +++ b/src/Mod/Part/App/BRepMesh.cpp @@ -31,7 +31,8 @@ using namespace Part; -namespace { +namespace +{ struct MeshVertex { Base::Vector3d p; @@ -39,15 +40,14 @@ struct MeshVertex explicit MeshVertex(const Base::Vector3d& p) : p(p) - { - } + {} Base::Vector3d toPoint() const { return p; } - bool operator < (const MeshVertex &v) const + bool operator<(const MeshVertex& v) const { if (p.x != v.p.x) { return p.x < v.p.x; @@ -69,12 +69,10 @@ class MergeVertex public: using Facet = BRepMesh::Facet; - MergeVertex(std::vector points, - std::vector faces, - double tolerance) - : points{std::move(points)} - , faces{std::move(faces)} - , tolerance{tolerance} + MergeVertex(std::vector points, std::vector faces, double tolerance) + : points {std::move(points)} + , faces {std::move(faces)} + , tolerance {tolerance} { setDefaultMap(); check(); @@ -113,9 +111,7 @@ private: { // by default map point index to itself mapPointIndex.resize(points.size()); - std::generate(mapPointIndex.begin(), - mapPointIndex.end(), - Base::iotaGen(0)); + std::generate(mapPointIndex.begin(), mapPointIndex.end(), Base::iotaGen(0)); } void reset() @@ -129,9 +125,7 @@ private: using VertexIterator = std::vector::const_iterator; double tol3d = tolerance; - auto vertexLess = [tol3d](const VertexIterator& v1, - const VertexIterator& v2) - { + auto vertexLess = [tol3d](const VertexIterator& v1, const VertexIterator& v2) { if (fabs(v1->x - v2->x) >= tol3d) { return v1->x < v2->x; } @@ -143,9 +137,7 @@ private: } return false; // points are considered to be equal }; - auto vertexEqual = [&](const VertexIterator& v1, - const VertexIterator& v2) - { + auto vertexEqual = [&](const VertexIterator& v1, const VertexIterator& v2) { if (vertexLess(v1, v2)) { return false; } @@ -244,11 +236,13 @@ private: std::vector mapPointIndex; }; -} +} // namespace -void BRepMesh::getFacesFromDomains(const std::vector& domains, - std::vector& points, - std::vector& faces) +void BRepMesh::getFacesFromDomains( + const std::vector& domains, + std::vector& points, + std::vector& faces +) { std::size_t numFaces = 0; for (const auto& it : domains) { @@ -264,7 +258,7 @@ void BRepMesh::getFacesFromDomains(const std::vector& domains, pointIndex = it.first->i; }; - for (const auto & domain : domains) { + for (const auto& domain : domains) { std::size_t numDomainFaces = 0; for (const Facet& df : domain.facets) { Facet face; @@ -279,9 +273,7 @@ void BRepMesh::getFacesFromDomains(const std::vector& domains, addVertex(domain.points[df.I3], face.I3); // make sure that we don't insert invalid facets - if (face.I1 != face.I2 && - face.I2 != face.I3 && - face.I3 != face.I1) { + if (face.I1 != face.I2 && face.I2 != face.I3 && face.I3 != face.I1) { faces.push_back(face); numDomainFaces++; } @@ -292,7 +284,7 @@ void BRepMesh::getFacesFromDomains(const std::vector& domains, std::vector meshPoints; meshPoints.resize(vertices.size()); - for (const auto & vertex : vertices) { + for (const auto& vertex : vertices) { meshPoints[vertex.i] = vertex.toPoint(); } points.swap(meshPoints); @@ -311,9 +303,7 @@ std::vector BRepMesh::createSegments() const std::vector segm; for (size_t numDomainFaces : domainSizes) { Segment segment(numDomainFaces); - std::generate(segment.begin(), - segment.end(), - Base::iotaGen(numMeshFaces)); + std::generate(segment.begin(), segment.end(), Base::iotaGen(numMeshFaces)); numMeshFaces += numDomainFaces; segm.push_back(segment); } diff --git a/src/Mod/Part/App/BRepMesh.h b/src/Mod/Part/App/BRepMesh.h index e5edeaa9fe..7322ad3aa9 100644 --- a/src/Mod/Part/App/BRepMesh.h +++ b/src/Mod/Part/App/BRepMesh.h @@ -27,7 +27,8 @@ #include #include -namespace Part { +namespace Part +{ class PartExport BRepMesh { @@ -36,15 +37,17 @@ public: using Domain = Data::ComplexGeoData::Domain; using Segment = std::vector; - void getFacesFromDomains(const std::vector& domains, - std::vector& points, - std::vector& faces); + void getFacesFromDomains( + const std::vector& domains, + std::vector& points, + std::vector& faces + ); std::vector createSegments() const; private: std::vector domainSizes; }; -} +} // namespace Part #endif // PART_BREPMESH_H diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeFilling.pyi b/src/Mod/Part/App/BRepOffsetAPI_MakeFilling.pyi index 22a8d9d142..a6bae6597c 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeFilling.pyi +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeFilling.pyi @@ -6,7 +6,6 @@ from Part.App.TopoShapeEdge import TopoShapeEdge from Part.App.TopoShapeFace import TopoShapeFace from typing import overload, Final - @export( PythonName="Part.BRepOffsetAPI_MakeFilling", Include="BRepOffsetAPI_MakeFilling.hxx", @@ -21,14 +20,23 @@ class BRepOffsetAPI_MakeFilling(PyObjectBase): Licence: LGPL """ - def setConstrParam(self, *, Tol2d: float = 0.00001, Tol3d: float = 0.0001, TolAng: float = 0.01, TolCurv: float = 0.1) -> None: + def setConstrParam( + self, + *, + Tol2d: float = 0.00001, + Tol3d: float = 0.0001, + TolAng: float = 0.01, + TolCurv: float = 0.1 + ) -> None: """ setConstrParam(Tol2d=0.00001, Tol3d=0.0001, TolAng=0.01, TolCurv=0.1) Sets the values of Tolerances used to control the constraint. """ ... - def setResolParam(self, *, Degree: int = 3, NbPtsOnCur: int = 15, NbIter: int = 2, Anisotropy: bool = False) -> None: + def setResolParam( + self, *, Degree: int = 3, NbPtsOnCur: int = 15, NbIter: int = 2, Anisotropy: bool = False + ) -> None: """ setResolParam(Degree=3, NbPtsOnCur=15, NbIter=2, Anisotropy=False) Sets the parameters used for resolution. @@ -50,25 +58,17 @@ class BRepOffsetAPI_MakeFilling(PyObjectBase): ... @overload - def add(self, Edge: TopoShapeEdge, Order: int, *, IsBound: bool = True) -> None: - ... - + def add(self, Edge: TopoShapeEdge, Order: int, *, IsBound: bool = True) -> None: ... @overload - def add(self, Edge: TopoShapeEdge, Support: TopoShapeFace, Order: int, *, IsBound: bool = True) -> None: - ... - + def add( + self, Edge: TopoShapeEdge, Support: TopoShapeFace, Order: int, *, IsBound: bool = True + ) -> None: ... @overload - def add(self, Support: TopoShapeFace, Order: int) -> None: - ... - + def add(self, Support: TopoShapeFace, Order: int) -> None: ... @overload - def add(self, Point: Point) -> None: - ... - + def add(self, Point: Point) -> None: ... @overload - def add(self, U: float, V: float, Support: TopoShapeFace, Order: int) -> None: - ... - + def add(self, U: float, V: float, Support: TopoShapeFace, Order: int) -> None: ... def add(self, **kwargs) -> None: """ add(Edge, Order, IsBound=True) @@ -93,13 +93,9 @@ class BRepOffsetAPI_MakeFilling(PyObjectBase): ... @overload - def G0Error(self) -> float: - ... - + def G0Error(self) -> float: ... @overload - def G0Error(self, arg: int) -> float: - ... - + def G0Error(self, arg: int) -> float: ... def G0Error(self, arg: int = 0) -> float: """ G0Error([int]) @@ -108,13 +104,9 @@ class BRepOffsetAPI_MakeFilling(PyObjectBase): ... @overload - def G1Error(self) -> float: - ... - + def G1Error(self) -> float: ... @overload - def G1Error(self, arg: int) -> float: - ... - + def G1Error(self, arg: int) -> float: ... def G1Error(self, arg: int = 0) -> float: """ G1Error([int]) @@ -123,13 +115,9 @@ class BRepOffsetAPI_MakeFilling(PyObjectBase): ... @overload - def G2Error(self) -> float: - ... - + def G2Error(self) -> float: ... @overload - def G2Error(self, arg: int) -> float: - ... - + def G2Error(self, arg: int) -> float: ... def G2Error(self, arg: int = 0) -> float: """ G2Error([int]) diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp b/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp index 26b517fda2..b71558f352 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp @@ -24,12 +24,12 @@ #include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -74,7 +74,8 @@ bp.surfInit() * \endcode */ -PyObject *BRepOffsetAPI_MakeFillingPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BRepOffsetAPI_MakeFillingPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python + // wrapper { // create a new instance of BRepOffsetAPI_MakeFillingPy return new BRepOffsetAPI_MakeFillingPy(nullptr); @@ -94,18 +95,52 @@ int BRepOffsetAPI_MakeFillingPy::PyInit(PyObject* args, PyObject* kwds) double tolCurv = 0.1; PyObject* anisotropy = Py_False; - static const std::array keywords{"Degree", "NbPtsOnCur", "NbIter", "MaxDegree", "MaxSegments", - "Tol2d", "Tol3d", "TolAng", "TolCurv", "Anisotropy", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|iiiiiddddO!", keywords, - °ree, &nbPtsOnCur, &nbIter, &maxDeg, &maxSegments, - &tol2d, &tol3d, &tolAng, &tolCurv, &PyBool_Type, &anisotropy)) { + static const std::array keywords { + "Degree", + "NbPtsOnCur", + "NbIter", + "MaxDegree", + "MaxSegments", + "Tol2d", + "Tol3d", + "TolAng", + "TolCurv", + "Anisotropy", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|iiiiiddddO!", + keywords, + °ree, + &nbPtsOnCur, + &nbIter, + &maxDeg, + &maxSegments, + &tol2d, + &tol3d, + &tolAng, + &tolCurv, + &PyBool_Type, + &anisotropy + )) { return -1; } try { - std::unique_ptr ptr(new BRepOffsetAPI_MakeFilling(degree, nbPtsOnCur, nbIter, - Base::asBoolean(anisotropy), - tol2d, tol3d, tolAng, tolCurv, maxDeg, maxSegments)); + std::unique_ptr ptr(new BRepOffsetAPI_MakeFilling( + degree, + nbPtsOnCur, + nbIter, + Base::asBoolean(anisotropy), + tol2d, + tol3d, + tolAng, + tolCurv, + maxDeg, + maxSegments + )); setTwinPointer(ptr.release()); @@ -123,16 +158,15 @@ std::string BRepOffsetAPI_MakeFillingPy::representation() const return {""}; } -PyObject* BRepOffsetAPI_MakeFillingPy::setConstrParam(PyObject *args, PyObject *kwds) +PyObject* BRepOffsetAPI_MakeFillingPy::setConstrParam(PyObject* args, PyObject* kwds) { double tol2d = 0.00001; double tol3d = 0.0001; double tolAng = 0.01; double tolCurv = 0.1; - static const std::array keywords {"Tol2d", "Tol3d", "TolAng", "TolCurv", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|dddd", keywords, - &tol2d, &tol3d, &tolAng, &tolCurv)) { + static const std::array keywords {"Tol2d", "Tol3d", "TolAng", "TolCurv", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|dddd", keywords, &tol2d, &tol3d, &tolAng, &tolCurv)) { return nullptr; } @@ -146,22 +180,32 @@ PyObject* BRepOffsetAPI_MakeFillingPy::setConstrParam(PyObject *args, PyObject * } } -PyObject* BRepOffsetAPI_MakeFillingPy::setResolParam(PyObject *args, PyObject *kwds) +PyObject* BRepOffsetAPI_MakeFillingPy::setResolParam(PyObject* args, PyObject* kwds) { int degree = 3; int nbPtsOnCur = 15; int nbIter = 2; PyObject* anisotropy = Py_False; - static const std::array keywords {"Degree", "NbPtsOnCur", "NbIter", "Anisotropy", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|iiiO!", keywords, - °ree, &nbPtsOnCur, &nbIter, &PyBool_Type, &anisotropy)) { + static const std::array + keywords {"Degree", "NbPtsOnCur", "NbIter", "Anisotropy", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|iiiO!", + keywords, + °ree, + &nbPtsOnCur, + &nbIter, + &PyBool_Type, + &anisotropy + )) { return nullptr; } try { - getBRepOffsetAPI_MakeFillingPtr()->SetResolParam(degree, nbPtsOnCur, nbIter, - Base::asBoolean(anisotropy)); + getBRepOffsetAPI_MakeFillingPtr() + ->SetResolParam(degree, nbPtsOnCur, nbIter, Base::asBoolean(anisotropy)); Py_Return; } catch (const Standard_Failure& e) { @@ -170,14 +214,13 @@ PyObject* BRepOffsetAPI_MakeFillingPy::setResolParam(PyObject *args, PyObject *k } } -PyObject* BRepOffsetAPI_MakeFillingPy::setApproxParam(PyObject *args, PyObject *kwds) +PyObject* BRepOffsetAPI_MakeFillingPy::setApproxParam(PyObject* args, PyObject* kwds) { int maxDeg = 8; int maxSegments = 9; - static const std::array keywords {"MaxDegree", "MaxSegments", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|ii", keywords, - &maxDeg, &maxSegments)) { + static const std::array keywords {"MaxDegree", "MaxSegments", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|ii", keywords, &maxDeg, &maxSegments)) { return nullptr; } @@ -191,13 +234,16 @@ PyObject* BRepOffsetAPI_MakeFillingPy::setApproxParam(PyObject *args, PyObject * } } -PyObject* BRepOffsetAPI_MakeFillingPy::loadInitSurface(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::loadInitSurface(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapeFacePy::Type), &shape)) + if (!PyArg_ParseTuple(args, "O!", &(TopoShapeFacePy::Type), &shape)) { return nullptr; + } - TopoDS_Face face = TopoDS::Face(static_cast(shape)->getTopoShapePtr()->getShape()); + TopoDS_Face face = TopoDS::Face( + static_cast(shape)->getTopoShapePtr()->getShape() + ); if (face.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid face"); return nullptr; @@ -213,13 +259,12 @@ PyObject* BRepOffsetAPI_MakeFillingPy::loadInitSurface(PyObject *args) } } -PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject *args, PyObject *kwds) +PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject* args, PyObject* kwds) { // 1st PyObject* pnt; - static const std::array keywords_pnt {"Point", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_pnt, - &Base::VectorPy::Type, &pnt)) { + static const std::array keywords_pnt {"Point", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_pnt, &Base::VectorPy::Type, &pnt)) { try { Base::Vector3d vec = static_cast(pnt)->value(); getBRepOffsetAPI_MakeFillingPtr()->Add(gp_Pnt(vec.x, vec.y, vec.z)); @@ -234,19 +279,31 @@ PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject *args, PyObject *kwds) // 2nd PyObject* support; int order; - static const std::array keywords_sup_ord {"Support", "Order", nullptr}; + static const std::array keywords_sup_ord {"Support", "Order", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!i", keywords_sup_ord, - &TopoShapeFacePy::Type, &support, &order)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!i", + keywords_sup_ord, + &TopoShapeFacePy::Type, + &support, + &order + )) { try { - TopoDS_Face face = TopoDS::Face(static_cast(support)->getTopoShapePtr()->getShape()); + TopoDS_Face face = TopoDS::Face( + static_cast(support)->getTopoShapePtr()->getShape() + ); if (face.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid face"); return nullptr; } if (order < 0 || order > 2) { - PyErr_SetString(PyExc_ReferenceError, "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2"); + PyErr_SetString( + PyExc_ReferenceError, + "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2" + ); return nullptr; } @@ -262,25 +319,38 @@ PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject *args, PyObject *kwds) // 3rd PyObject* constr; PyObject* isbound = Py_True; - static const std::array keywords_const {"Constraint", "Order", "IsBound", nullptr}; + static const std::array keywords_const {"Constraint", "Order", "IsBound", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!i|O!", keywords_const, - &TopoShapeEdgePy::Type, &constr, - &order, &PyBool_Type, isbound)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!i|O!", + keywords_const, + &TopoShapeEdgePy::Type, + &constr, + &order, + &PyBool_Type, + isbound + )) { try { - TopoDS_Edge edge = TopoDS::Edge(static_cast(constr)->getTopoShapePtr()->getShape()); + TopoDS_Edge edge = TopoDS::Edge( + static_cast(constr)->getTopoShapePtr()->getShape() + ); if (edge.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid constraint edge"); return nullptr; } if (order < 0 || order > 2) { - PyErr_SetString(PyExc_ReferenceError, "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2"); + PyErr_SetString( + PyExc_ReferenceError, + "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2" + ); return nullptr; } - getBRepOffsetAPI_MakeFillingPtr()->Add(edge, static_cast(order), - Base::asBoolean(isbound)); + getBRepOffsetAPI_MakeFillingPtr() + ->Add(edge, static_cast(order), Base::asBoolean(isbound)); Py_Return; } catch (const Standard_Failure& e) { @@ -290,31 +360,48 @@ PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject *args, PyObject *kwds) } // 4th - static const std::array keywords_const_sup {"Constraint", "Support", "Order", "IsBound", nullptr}; + static const std::array + keywords_const_sup {"Constraint", "Support", "Order", "IsBound", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!i|O!", keywords_const_sup, - &TopoShapeEdgePy::Type, &constr, - &TopoShapeFacePy::Type, &support, - &order, &PyBool_Type, isbound)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!i|O!", + keywords_const_sup, + &TopoShapeEdgePy::Type, + &constr, + &TopoShapeFacePy::Type, + &support, + &order, + &PyBool_Type, + isbound + )) { try { - TopoDS_Edge edge = TopoDS::Edge(static_cast(constr)->getTopoShapePtr()->getShape()); + TopoDS_Edge edge = TopoDS::Edge( + static_cast(constr)->getTopoShapePtr()->getShape() + ); if (edge.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid constraint edge"); return nullptr; } - TopoDS_Face face = TopoDS::Face(static_cast(support)->getTopoShapePtr()->getShape()); + TopoDS_Face face = TopoDS::Face( + static_cast(support)->getTopoShapePtr()->getShape() + ); if (face.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid face"); return nullptr; } if (order < 0 || order > 2) { - PyErr_SetString(PyExc_ReferenceError, "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2"); + PyErr_SetString( + PyExc_ReferenceError, + "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2" + ); return nullptr; } - getBRepOffsetAPI_MakeFillingPtr()->Add(edge, face, static_cast(order), - Base::asBoolean(isbound)); + getBRepOffsetAPI_MakeFillingPtr() + ->Add(edge, face, static_cast(order), Base::asBoolean(isbound)); Py_Return; } catch (const Standard_Failure& e) { @@ -325,19 +412,33 @@ PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject *args, PyObject *kwds) // 5th double u, v; - static const std::array keywords_uv {"U", "V", "Support", "Order", nullptr}; + static const std::array keywords_uv {"U", "V", "Support", "Order", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "ddO!i", keywords_uv, - &u, &v, &TopoShapeFacePy::Type, &support, &order)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "ddO!i", + keywords_uv, + &u, + &v, + &TopoShapeFacePy::Type, + &support, + &order + )) { try { - TopoDS_Face face = TopoDS::Face(static_cast(support)->getTopoShapePtr()->getShape()); + TopoDS_Face face = TopoDS::Face( + static_cast(support)->getTopoShapePtr()->getShape() + ); if (face.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid face"); return nullptr; } if (order < 0 || order > 2) { - PyErr_SetString(PyExc_ReferenceError, "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2"); + PyErr_SetString( + PyExc_ReferenceError, + "Order must be in the [0, 2] with 0 -> C0, 1 -> G1, 2 -> G2" + ); return nullptr; } @@ -354,10 +455,11 @@ PyObject* BRepOffsetAPI_MakeFillingPy::add(PyObject *args, PyObject *kwds) return nullptr; } -PyObject* BRepOffsetAPI_MakeFillingPy::build(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::build(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { getBRepOffsetAPI_MakeFillingPtr()->Build(); @@ -369,10 +471,11 @@ PyObject* BRepOffsetAPI_MakeFillingPy::build(PyObject *args) } } -PyObject* BRepOffsetAPI_MakeFillingPy::isDone(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::isDone(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Boolean ok = getBRepOffsetAPI_MakeFillingPtr()->IsDone(); @@ -384,11 +487,12 @@ PyObject* BRepOffsetAPI_MakeFillingPy::isDone(PyObject *args) } } -PyObject* BRepOffsetAPI_MakeFillingPy::G0Error(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::G0Error(PyObject* args) { int index = 0; - if (!PyArg_ParseTuple(args, "|i", &index)) + if (!PyArg_ParseTuple(args, "|i", &index)) { return nullptr; + } try { Standard_Real v = index < 1 ? getBRepOffsetAPI_MakeFillingPtr()->G0Error() @@ -401,11 +505,12 @@ PyObject* BRepOffsetAPI_MakeFillingPy::G0Error(PyObject *args) } } -PyObject* BRepOffsetAPI_MakeFillingPy::G1Error(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::G1Error(PyObject* args) { int index = 0; - if (!PyArg_ParseTuple(args, "|i", &index)) + if (!PyArg_ParseTuple(args, "|i", &index)) { return nullptr; + } try { Standard_Real v = index < 1 ? getBRepOffsetAPI_MakeFillingPtr()->G1Error() @@ -418,11 +523,12 @@ PyObject* BRepOffsetAPI_MakeFillingPy::G1Error(PyObject *args) } } -PyObject* BRepOffsetAPI_MakeFillingPy::G2Error(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::G2Error(PyObject* args) { int index = 0; - if (!PyArg_ParseTuple(args, "|i", &index)) + if (!PyArg_ParseTuple(args, "|i", &index)) { return nullptr; + } try { Standard_Real v = index < 1 ? getBRepOffsetAPI_MakeFillingPtr()->G2Error() @@ -435,10 +541,11 @@ PyObject* BRepOffsetAPI_MakeFillingPy::G2Error(PyObject *args) } } -PyObject* BRepOffsetAPI_MakeFillingPy::shape(PyObject *args) +PyObject* BRepOffsetAPI_MakeFillingPy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { const TopoDS_Shape& shape = this->getBRepOffsetAPI_MakeFillingPtr()->Shape(); @@ -450,7 +557,7 @@ PyObject* BRepOffsetAPI_MakeFillingPy::shape(PyObject *args) } } -PyObject *BRepOffsetAPI_MakeFillingPy::getCustomAttributes(const char* /*attr*/) const +PyObject* BRepOffsetAPI_MakeFillingPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp index 2dcc913209..fba1144aae 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp @@ -22,24 +22,24 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "BRepOffsetAPI_MakeOffsetFix.h" @@ -49,7 +49,10 @@ using namespace Part; BRepOffsetAPI_MakeOffsetFix::BRepOffsetAPI_MakeOffsetFix() = default; -BRepOffsetAPI_MakeOffsetFix::BRepOffsetAPI_MakeOffsetFix(const GeomAbs_JoinType Join, const Standard_Boolean IsOpenResult) +BRepOffsetAPI_MakeOffsetFix::BRepOffsetAPI_MakeOffsetFix( + const GeomAbs_JoinType Join, + const Standard_Boolean IsOpenResult +) { mkOffset.Init(Join, IsOpenResult); } @@ -94,7 +97,7 @@ void BRepOffsetAPI_MakeOffsetFix::AddWire(const TopoDS_Wire& Spine) myResult.Nullify(); } -void BRepOffsetAPI_MakeOffsetFix::Perform (const Standard_Real Offset, const Standard_Real Alt) +void BRepOffsetAPI_MakeOffsetFix::Perform(const Standard_Real Offset, const Standard_Real Alt) { mkOffset.Perform(Offset, Alt); } @@ -108,8 +111,11 @@ void BRepOffsetAPI_MakeOffsetFix::Build() mkOffset.Build(); } -void BRepOffsetAPI_MakeOffsetFix::Init(const TopoDS_Face& Spine, const GeomAbs_JoinType Join, - const Standard_Boolean IsOpenResult) +void BRepOffsetAPI_MakeOffsetFix::Init( + const TopoDS_Face& Spine, + const GeomAbs_JoinType Join, + const Standard_Boolean IsOpenResult +) { mkOffset.Init(Spine, Join, IsOpenResult); } @@ -176,8 +182,7 @@ void BRepOffsetAPI_MakeOffsetFix::MakeWire(TopoDS_Shape& wire) break; } } - } - while (found); + } while (found); } } @@ -219,24 +224,26 @@ const TopTools_ListOfShape& BRepOffsetAPI_MakeOffsetFix::Generated(const TopoDS_ return mkOffset.Generated(S); } -const TopTools_ListOfShape& BRepOffsetAPI_MakeOffsetFix::Modified (const TopoDS_Shape& S) +const TopTools_ListOfShape& BRepOffsetAPI_MakeOffsetFix::Modified(const TopoDS_Shape& S) { return mkOffset.Modified(S); } -Standard_Boolean BRepOffsetAPI_MakeOffsetFix::IsDeleted (const TopoDS_Shape& S) +Standard_Boolean BRepOffsetAPI_MakeOffsetFix::IsDeleted(const TopoDS_Shape& S) { return mkOffset.IsDeleted(S); } TopoDS_Shape BRepOffsetAPI_MakeOffsetFix::Replace(GeomAbs_CurveType type, const TopoDS_Shape& S) const { - if (S.IsNull()) + if (S.IsNull()) { throw Standard_ConstructionError("Input shape is null"); + } // Nothing to do - if (type == GeomAbs_BSplineCurve) + if (type == GeomAbs_BSplineCurve) { return S; + } if (S.ShapeType() == TopAbs_COMPOUND) { BRep_Builder builder; @@ -275,7 +282,8 @@ TopoDS_Wire BRepOffsetAPI_MakeOffsetFix::ReplaceEdges(GeomAbs_CurveType type, co ShapeConstruct_Curve scc; double u = curve.FirstParameter(); double v = curve.LastParameter(); - Handle(Geom_BSplineCurve) spline = scc.ConvertToBSpline(curve.Curve().Curve(), u, v, Precision::Confusion()); + Handle(Geom_BSplineCurve) spline + = scc.ConvertToBSpline(curve.Curve().Curve(), u, v, Precision::Confusion()); if (!spline.IsNull()) { BRepBuilderAPI_MakeEdge mkEdge(spline, u, v); edge = mkEdge.Edge(); diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h index cf9c4edaa4..5d2e4185ce 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h @@ -35,14 +35,15 @@ #include -namespace Part { +namespace Part +{ /*! * \brief The BRepOffsetAPI_MakeOffsetFix class * This class works around a limitation of the BRepOffsetAPI_MakeOffset which * returns unexpected results when an input wire has set a placement and consists * of a single edge only. */ -class PartExport BRepOffsetAPI_MakeOffsetFix : public BRepBuilderAPI_MakeShape +class PartExport BRepOffsetAPI_MakeOffsetFix: public BRepBuilderAPI_MakeShape { public: BRepOffsetAPI_MakeOffsetFix(); @@ -50,13 +51,13 @@ public: ~BRepOffsetAPI_MakeOffsetFix() override; //! Initializes the algorithm to construct parallels to the wire Spine. - void AddWire (const TopoDS_Wire& Spine); + void AddWire(const TopoDS_Wire& Spine); //! Computes a parallel to the spine at distance Offset and //! at an altitude Alt from the plane of the spine in relation //! to the normal to the spine. //! Exceptions: StdFail_NotDone if the offset is not built. - void Perform (const Standard_Real Offset, const Standard_Real Alt = 0.0); + void Perform(const Standard_Real Offset, const Standard_Real Alt = 0.0); //! Builds the resulting shape (redefined from MakeShape). #if OCC_VERSION_HEX >= 0x070600 @@ -73,10 +74,17 @@ public: //! If join type is GeomAbs_Intersection, the edges that //! intersect in a salient vertex generate the edges //! prolonged until intersection. - void Init(const TopoDS_Face& Spine, const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean IsOpenResult = Standard_False); + void Init( + const TopoDS_Face& Spine, + const GeomAbs_JoinType Join = GeomAbs_Arc, + const Standard_Boolean IsOpenResult = Standard_False + ); //! Initialize the evaluation of Offsetting. - void Init(const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean IsOpenResult = Standard_False); + void Init( + const GeomAbs_JoinType Join = GeomAbs_Arc, + const Standard_Boolean IsOpenResult = Standard_False + ); Standard_Boolean IsDone() const override; @@ -86,14 +94,14 @@ public: //! returns a list of the created shapes //! from the shape . - const TopTools_ListOfShape& Generated (const TopoDS_Shape& S) override; + const TopTools_ListOfShape& Generated(const TopoDS_Shape& S) override; //! Returns the list of shapes modified from the shape //! . - const TopTools_ListOfShape& Modified (const TopoDS_Shape& S) override; + const TopTools_ListOfShape& Modified(const TopoDS_Shape& S) override; //! Returns true if the shape S has been deleted. - Standard_Boolean IsDeleted (const TopoDS_Shape& S) override; + Standard_Boolean IsDeleted(const TopoDS_Shape& S) override; //! Replaces the given curve type with a B-Spline. Input shape //! must be a wire or a compound of wires @@ -105,10 +113,10 @@ private: private: BRepOffsetAPI_MakeOffset mkOffset; - std::list > myLocations; + std::list> myLocations; TopoDS_Shape myResult; }; -} +} // namespace Part -#endif // PART_BREPOFFSETAPI_MAKEOFFSETFIX_H +#endif // PART_BREPOFFSETAPI_MAKEOFFSETFIX_H diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakePipeShell.pyi b/src/Mod/Part/App/BRepOffsetAPI_MakePipeShell.pyi index 37f58198cb..192bb89d38 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakePipeShell.pyi +++ b/src/Mod/Part/App/BRepOffsetAPI_MakePipeShell.pyi @@ -53,7 +53,9 @@ class BRepOffsetAPI_MakePipeShell(PyObjectBase): """ ... - def setAuxiliarySpine(self, wire: TopoShape, CurvilinearEquivalence: bool, TypeOfContact: int) -> None: + def setAuxiliarySpine( + self, wire: TopoShape, CurvilinearEquivalence: bool, TypeOfContact: int + ) -> None: """ setAuxiliarySpine(wire, CurvilinearEquivalence, TypeOfContact) Sets an auxiliary spine to define the Normal. @@ -71,11 +73,18 @@ class BRepOffsetAPI_MakePipeShell(PyObjectBase): ... @overload - def add(self, Profile: TopoShape, *, WithContact: bool = False, WithCorrection: bool = False) -> None: ... - + def add( + self, Profile: TopoShape, *, WithContact: bool = False, WithCorrection: bool = False + ) -> None: ... @overload - def add(self, Profile: TopoShape, Location: TopoShape, *, WithContact: bool = False, WithCorrection: bool = False) -> None: ... - + def add( + self, + Profile: TopoShape, + Location: TopoShape, + *, + WithContact: bool = False, + WithCorrection: bool = False + ) -> None: ... def add(self, **kwargs) -> None: """ add(shape Profile, bool WithContact=False, bool WithCorrection=False) diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp b/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp index 92e6272405..40ff6f448a 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp +++ b/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp @@ -24,13 +24,13 @@ #include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -47,12 +47,13 @@ using namespace Part; -PyObject *BRepOffsetAPI_MakePipeShellPy::PyMake(struct _typeobject *, PyObject *args, PyObject *) // Python wrapper +PyObject* BRepOffsetAPI_MakePipeShellPy::PyMake(struct _typeobject*, PyObject* args, PyObject*) // Python wrapper { // create a new instance of BRepOffsetAPI_MakePipeShellPy and the Twin object PyObject* obj; - if (!PyArg_ParseTuple(args, "O!",&(TopoShapePy::Type),&obj)) + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &obj)) { return nullptr; + } const TopoDS_Shape& wire = static_cast(obj)->getTopoShapePtr()->getShape(); if (!wire.IsNull() && wire.ShapeType() == TopAbs_WIRE) { return new BRepOffsetAPI_MakePipeShellPy(new BRepOffsetAPI_MakePipeShell(TopoDS::Wire(wire))); @@ -74,11 +75,12 @@ std::string BRepOffsetAPI_MakePipeShellPy::representation() const return {""}; } -PyObject* BRepOffsetAPI_MakePipeShellPy::setFrenetMode(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setFrenetMode(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!",&PyBool_Type,&obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &obj)) { return nullptr; + } try { this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(Base::asBoolean(obj)); @@ -90,17 +92,17 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setFrenetMode(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setTrihedronMode(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setTrihedronMode(PyObject* args) { PyObject *pnt, *dir; - if (!PyArg_ParseTuple(args, "O!O!",&Base::VectorPy::Type,&pnt - ,&Base::VectorPy::Type,&dir)) + if (!PyArg_ParseTuple(args, "O!O!", &Base::VectorPy::Type, &pnt, &Base::VectorPy::Type, &dir)) { return nullptr; + } try { - gp_Pnt p = Base::convertTo(Py::Vector(pnt,false).toVector()); - gp_Dir d = Base::convertTo(Py::Vector(dir,false).toVector()); - this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(gp_Ax2(p,d)); + gp_Pnt p = Base::convertTo(Py::Vector(pnt, false).toVector()); + gp_Dir d = Base::convertTo(Py::Vector(dir, false).toVector()); + this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(gp_Ax2(p, d)); Py_Return; } catch (Standard_Failure& e) { @@ -109,14 +111,15 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setTrihedronMode(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setBiNormalMode(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setBiNormalMode(PyObject* args) { - PyObject *dir; - if (!PyArg_ParseTuple(args, "O!",&Base::VectorPy::Type,&dir)) + PyObject* dir; + if (!PyArg_ParseTuple(args, "O!", &Base::VectorPy::Type, &dir)) { return nullptr; + } try { - gp_Dir d = Base::convertTo(Py::Vector(dir,false).toVector()); + gp_Dir d = Base::convertTo(Py::Vector(dir, false).toVector()); this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode(d); Py_Return; } @@ -126,11 +129,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setBiNormalMode(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setSpineSupport(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setSpineSupport(PyObject* args) { - PyObject *shape; - if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&shape)) + PyObject* shape; + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } try { const TopoDS_Shape& s = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -143,13 +147,21 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setSpineSupport(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setAuxiliarySpine(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setAuxiliarySpine(PyObject* args) { PyObject *spine, *curv, *keep; - if (!PyArg_ParseTuple(args, "O!O!O!",&Part::TopoShapePy::Type,&spine - ,&PyBool_Type,&curv - ,&PyLong_Type,&keep)) + if (!PyArg_ParseTuple( + args, + "O!O!O!", + &Part::TopoShapePy::Type, + &spine, + &PyBool_Type, + &curv, + &PyLong_Type, + &keep + )) { return nullptr; + } try { const TopoDS_Shape& s = static_cast(spine)->getTopoShapePtr()->getShape(); @@ -160,20 +172,18 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setAuxiliarySpine(PyObject *args) BRepFill_TypeOfContact typeOfCantact; switch (PyLong_AsLong(keep)) { - case 1: - typeOfCantact = BRepFill_Contact; - break; - case 2: - typeOfCantact = BRepFill_ContactOnBorder; - break; - default: - typeOfCantact = BRepFill_NoContact; - break; + case 1: + typeOfCantact = BRepFill_Contact; + break; + case 2: + typeOfCantact = BRepFill_ContactOnBorder; + break; + default: + typeOfCantact = BRepFill_NoContact; + break; } - this->getBRepOffsetAPI_MakePipeShellPtr()->SetMode( - TopoDS::Wire(s), - Base::asBoolean(curv), - typeOfCantact); + this->getBRepOffsetAPI_MakePipeShellPtr() + ->SetMode(TopoDS::Wire(s), Base::asBoolean(curv), typeOfCantact); Py_Return; } catch (Standard_Failure& e) { @@ -182,15 +192,32 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setAuxiliarySpine(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::add(PyObject *args, PyObject *kwds) +PyObject* BRepOffsetAPI_MakePipeShellPy::add(PyObject* args, PyObject* kwds) { - PyObject *profile, *withContact=Py_False, *withCorrection=Py_False; - static const std::array keywords_pro{"Profile", "WithContact", "WithCorrection", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|O!O!", keywords_pro, &Part::TopoShapePy::Type, &profile, - &PyBool_Type, &withContact, &PyBool_Type, &withCorrection)) { + PyObject *profile, *withContact = Py_False, *withCorrection = Py_False; + static const std::array keywords_pro { + "Profile", + "WithContact", + "WithCorrection", + nullptr + }; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|O!O!", + keywords_pro, + &Part::TopoShapePy::Type, + &profile, + &PyBool_Type, + &withContact, + &PyBool_Type, + &withCorrection + )) { try { - const TopoDS_Shape& s = static_cast(profile)->getTopoShapePtr()->getShape(); - this->getBRepOffsetAPI_MakePipeShellPtr()->Add(s, Base::asBoolean(withContact), Base::asBoolean(withCorrection)); + const TopoDS_Shape& s + = static_cast(profile)->getTopoShapePtr()->getShape(); + this->getBRepOffsetAPI_MakePipeShellPtr() + ->Add(s, Base::asBoolean(withContact), Base::asBoolean(withCorrection)); Py_Return; } catch (Standard_Failure& e) { @@ -200,16 +227,31 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::add(PyObject *args, PyObject *kwds) } PyErr_Clear(); - PyObject *location; - static const std::array keywords_loc{"Profile", "Location", "WithContact", "WithCorrection", - nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!|O!O!", keywords_loc, &Part::TopoShapePy::Type, &profile, - &Part::TopoShapeVertexPy::Type, &location, &PyBool_Type, &withContact, &PyBool_Type, - &withCorrection)) { + PyObject* location; + static const std::array + keywords_loc {"Profile", "Location", "WithContact", "WithCorrection", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!|O!O!", + keywords_loc, + &Part::TopoShapePy::Type, + &profile, + &Part::TopoShapeVertexPy::Type, + &location, + &PyBool_Type, + &withContact, + &PyBool_Type, + &withCorrection + )) { try { - const TopoDS_Shape& s = static_cast(profile)->getTopoShapePtr()->getShape(); - const TopoDS_Vertex& v = TopoDS::Vertex(static_cast(location)->getTopoShapePtr()->getShape()); - this->getBRepOffsetAPI_MakePipeShellPtr()->Add(s, v, Base::asBoolean(withContact), Base::asBoolean(withCorrection)); + const TopoDS_Shape& s + = static_cast(profile)->getTopoShapePtr()->getShape(); + const TopoDS_Vertex& v = TopoDS::Vertex( + static_cast(location)->getTopoShapePtr()->getShape() + ); + this->getBRepOffsetAPI_MakePipeShellPtr() + ->Add(s, v, Base::asBoolean(withContact), Base::asBoolean(withCorrection)); Py_Return; } catch (Standard_Failure& e) { @@ -218,18 +260,21 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::add(PyObject *args, PyObject *kwds) } } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "add(Profile, WithContact=False, WithCorrection=False)\n" - "add(Profile, Location, WithContact=False, WithCorrection=False)" + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "add(Profile, WithContact=False, WithCorrection=False)\n" + "add(Profile, Location, WithContact=False, WithCorrection=False)" ); return nullptr; } -PyObject* BRepOffsetAPI_MakePipeShellPy::remove(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::remove(PyObject* args) { - PyObject *prof; - if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&prof)) + PyObject* prof; + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &prof)) { return nullptr; + } try { const TopoDS_Shape& s = static_cast(prof)->getTopoShapePtr()->getShape(); @@ -242,10 +287,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::remove(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::isReady(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::isReady(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->IsReady(); @@ -257,10 +303,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::isReady(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::getStatus(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::getStatus(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Integer val = this->getBRepOffsetAPI_MakePipeShellPtr()->GetStatus(); @@ -272,10 +319,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::getStatus(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::makeSolid(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::makeSolid(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Boolean ok = this->getBRepOffsetAPI_MakePipeShellPtr()->MakeSolid(); @@ -287,10 +335,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::makeSolid(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::build(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::build(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { this->getBRepOffsetAPI_MakePipeShellPtr()->Build(); @@ -302,10 +351,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::build(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::shape(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { const TopoDS_Shape& shape = this->getBRepOffsetAPI_MakePipeShellPtr()->Shape(); @@ -317,10 +367,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::shape(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::firstShape(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::firstShape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { TopoDS_Shape shape = this->getBRepOffsetAPI_MakePipeShellPtr()->FirstShape(); @@ -332,10 +383,11 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::firstShape(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::lastShape(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::lastShape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { TopoDS_Shape shape = this->getBRepOffsetAPI_MakePipeShellPtr()->LastShape(); @@ -347,11 +399,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::lastShape(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::generated(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::generated(PyObject* args) { - PyObject *shape; - if (!PyArg_ParseTuple(args, "O!",&Part::TopoShapePy::Type,&shape)) + PyObject* shape; + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } try { const TopoDS_Shape& s = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -371,11 +424,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::generated(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setTolerance(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setTolerance(PyObject* args) { double tol3d, boundTol, tolAngular; - if (!PyArg_ParseTuple(args, "ddd",&tol3d,&boundTol,&tolAngular)) + if (!PyArg_ParseTuple(args, "ddd", &tol3d, &boundTol, &tolAngular)) { return nullptr; + } try { this->getBRepOffsetAPI_MakePipeShellPtr()->SetTolerance(tol3d, boundTol, tolAngular); @@ -387,14 +441,17 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setTolerance(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setTransitionMode(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setTransitionMode(PyObject* args) { int mode; - if (!PyArg_ParseTuple(args, "i",&mode)) + if (!PyArg_ParseTuple(args, "i", &mode)) { return nullptr; + } try { - this->getBRepOffsetAPI_MakePipeShellPtr()->SetTransitionMode(BRepBuilderAPI_TransitionMode(mode)); + this->getBRepOffsetAPI_MakePipeShellPtr()->SetTransitionMode( + BRepBuilderAPI_TransitionMode(mode) + ); Py_Return; } catch (Standard_Failure& e) { @@ -403,11 +460,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setTransitionMode(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxDegree(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxDegree(PyObject* args) { int degree; - if (!PyArg_ParseTuple(args, "i",°ree)) + if (!PyArg_ParseTuple(args, "i", °ree)) { return nullptr; + } try { this->getBRepOffsetAPI_MakePipeShellPtr()->SetMaxDegree(degree); @@ -419,11 +477,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxDegree(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxSegments(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxSegments(PyObject* args) { int nbseg; - if (!PyArg_ParseTuple(args, "i",&nbseg)) + if (!PyArg_ParseTuple(args, "i", &nbseg)) { return nullptr; + } try { this->getBRepOffsetAPI_MakePipeShellPtr()->SetMaxSegments(nbseg); @@ -435,11 +494,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setMaxSegments(PyObject *args) } } -PyObject* BRepOffsetAPI_MakePipeShellPy::setForceApproxC1(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::setForceApproxC1(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!",&PyBool_Type,&obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &obj)) { return nullptr; + } try { this->getBRepOffsetAPI_MakePipeShellPtr()->SetForceApproxC1(Base::asBoolean(obj)); @@ -452,11 +512,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::setForceApproxC1(PyObject *args) } -PyObject* BRepOffsetAPI_MakePipeShellPy::simulate(PyObject *args) +PyObject* BRepOffsetAPI_MakePipeShellPy::simulate(PyObject* args) { int nbsec; - if (!PyArg_ParseTuple(args, "i",&nbsec)) + if (!PyArg_ParseTuple(args, "i", &nbsec)) { return nullptr; + } try { TopTools_ListOfShape list; @@ -477,12 +538,12 @@ PyObject* BRepOffsetAPI_MakePipeShellPy::simulate(PyObject *args) } -PyObject *BRepOffsetAPI_MakePipeShellPy::getCustomAttributes(const char* ) const +PyObject* BRepOffsetAPI_MakePipeShellPy::getCustomAttributes(const char*) const { return nullptr; } -int BRepOffsetAPI_MakePipeShellPy::setCustomAttributes(const char* , PyObject *) +int BRepOffsetAPI_MakePipeShellPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/BSplineCurve.pyi b/src/Mod/Part/App/BSplineCurve.pyi index 0ec0d21992..9f09f6d12d 100644 --- a/src/Mod/Part/App/BSplineCurve.pyi +++ b/src/Mod/Part/App/BSplineCurve.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from BoundedCurve import BoundedCurve from typing import Final, List, overload - @export( PythonName="Part.BSplineCurve", Twin="GeomBSplineCurve", @@ -102,10 +101,8 @@ class BSplineCurve(BoundedCurve): @overload def increaseMultiplicity(self, index: int, mult: int) -> None: ... - @overload def increaseMultiplicity(self, start: int, end: int, mult: int) -> None: ... - def increaseMultiplicity(self, *args, **kwargs) -> None: """ increaseMultiplicity(int index, int mult) @@ -276,9 +273,7 @@ class BSplineCurve(BoundedCurve): """ ... - def movePoint( - self, U: float, P: Vector, Index1: int, Index2: int - ) -> tuple[int, int]: + def movePoint(self, U: float, P: Vector, Index1: int, Index2: int) -> tuple[int, int]: """ movePoint(U, P, Index1, Index2) @@ -341,7 +336,6 @@ class BSplineCurve(BoundedCurve): Parameters: List[float] = None, ParamType: str = "Uniform", ) -> None: ... - def approximate(self, **kwargs) -> None: """ Replaces this B-Spline curve by approximating a set of points. @@ -379,7 +373,6 @@ class BSplineCurve(BoundedCurve): @overload @constmethod def getCardinalSplineTangents(self, **kwargs) -> List[Vector]: ... - @constmethod def getCardinalSplineTangents(self, **kwargs) -> List[Vector]: """ @@ -399,7 +392,6 @@ class BSplineCurve(BoundedCurve): Tangents: List[Vector] = None, TangentFlags: List[bool] = None, ) -> None: ... - def interpolate(self, **kwargs) -> None: """ Replaces this B-Spline curve by interpolating a set of points. @@ -476,7 +468,6 @@ class BSplineCurve(BoundedCurve): weights: List[float] = None, CheckRational: bool = False, ) -> None: ... - def buildFromPolesMultsKnots(self, **kwargs) -> None: """ Builds a B-Spline by a lists of Poles, Mults, Knots. @@ -526,9 +517,7 @@ class BSplineCurve(BoundedCurve): """ ... - def makeC1Continuous( - self, tol: float = 1e-6, ang_tol: float = 1e-7 - ) -> "BSplineCurve": + def makeC1Continuous(self, tol: float = 1e-6, ang_tol: float = 1e-7) -> "BSplineCurve": """ makeC1Continuous(tol = 1e-6, ang_tol = 1e-7) Reduces as far as possible the multiplicities of the knots of this BSpline diff --git a/src/Mod/Part/App/BSplineCurveBiArcs.cpp b/src/Mod/Part/App/BSplineCurveBiArcs.cpp index e60410726b..9b6b46b827 100644 --- a/src/Mod/Part/App/BSplineCurveBiArcs.cpp +++ b/src/Mod/Part/App/BSplineCurveBiArcs.cpp @@ -29,10 +29,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -# include -# include -# include -# include +#include +#include +#include +#include #include "BSplineCurveBiArcs.h" @@ -45,12 +45,12 @@ using Part::GeomBSplineCurve; using Part::Geometry; // Algorithm taken from HeeksCAD -namespace Part { +namespace Part +{ bool tangentialArc(const gp_Pnt& p0, const gp_Vec& v0, const gp_Pnt& p1, gp_Pnt& c, gp_Dir& axis) { - if (p0.Distance(p1) > Precision::Intersection() && - v0.Magnitude() > Precision::Intersection()){ + if (p0.Distance(p1) > Precision::Intersection() && v0.Magnitude() > Precision::Intersection()) { gp_Vec v1(p0, p1); gp_Pnt halfway(p0.XYZ() + v1.XYZ() * 0.5); gp_Pln pln1(halfway, v1); @@ -71,39 +71,45 @@ bool tangentialArc(const gp_Pnt& p0, const gp_Vec& v0, const gp_Pnt& p1, gp_Pnt& class TangentialArc { public: - gp_Pnt m_p0; // start point - gp_Vec m_v0; // start direction - gp_Pnt m_p1; // end point - gp_Pnt m_c; // centre point - gp_Dir m_a; // axis + gp_Pnt m_p0; // start point + gp_Vec m_v0; // start direction + gp_Pnt m_p1; // end point + gp_Pnt m_c; // centre point + gp_Dir m_a; // axis bool m_is_a_line; TangentialArc(const gp_Pnt& p0, const gp_Vec& v0, const gp_Pnt& p1) - : m_p0(p0), m_v0(v0), m_p1(p1) + : m_p0(p0) + , m_v0(v0) + , m_p1(p1) { // calculate a tangential arc that goes through p0 and p1, with a direction of v0 at p0 m_is_a_line = !Part::tangentialArc(m_p0, m_v0, m_p1, m_c, m_a); } - bool isRadiusEqual(const gp_Pnt &p, double tolerance) const + bool isRadiusEqual(const gp_Pnt& p, double tolerance) const { - if (m_is_a_line) + if (m_is_a_line) { return true; + } double point_radius = gp_Vec(m_c.XYZ() - p.XYZ()).Magnitude(); - double diff = fabs(point_radius - radius()); + double diff = fabs(point_radius - radius()); return diff <= tolerance; } double radius() const { double r0 = gp_Vec(m_p0.XYZ() - m_c.XYZ()).Magnitude(); double r1 = gp_Vec(m_p1.XYZ() - m_c.XYZ()).Magnitude(); - double r = (r0 + r1)/2; + double r = (r0 + r1) / 2; return r; } Geometry* makeArc() const { if (m_is_a_line) { GeomLineSegment* line = new GeomLineSegment(); - line->setPoints(Base::convertTo(m_p0),Base::convertTo(m_p1)); + line->setPoints( + Base::convertTo(m_p0), + Base::convertTo(m_p1) + ); return line; } @@ -115,17 +121,25 @@ public: } }; -} +} // namespace Part -void BSplineCurveBiArcs::createArcs(double tolerance, std::list& new_spans, - const gp_Pnt& p_start, const gp_Vec& v_start, - double t_start, double t_end, gp_Pnt& p_end, gp_Vec& v_end) const +void BSplineCurveBiArcs::createArcs( + double tolerance, + std::list& new_spans, + const gp_Pnt& p_start, + const gp_Vec& v_start, + double t_start, + double t_end, + gp_Pnt& p_end, + gp_Vec& v_end +) const { this->myCurve->D1(t_end, p_end, v_end); gp_Pnt p1, p2, p3; - Type can_do_spline_whole = calculateBiArcPoints(t_start, p_start, v_start, t_end, p_end, v_end, p1, p2, p3); + Type can_do_spline_whole + = calculateBiArcPoints(t_start, p_start, v_start, t_end, p_end, v_end, p1, p2, p3); Geometry* arc_object1 = nullptr; Geometry* arc_object2 = nullptr; @@ -138,8 +152,7 @@ void BSplineCurveBiArcs::createArcs(double tolerance, std::list& new_ this->myCurve->D0(t_start + ((t_end - t_start) * 0.25), p_middle1); this->myCurve->D0(t_start + ((t_end - t_start) * 0.75), p_middle2); - if (!arc1.isRadiusEqual(p_middle1, tolerance) || - !arc2.isRadiusEqual(p_middle2, tolerance)) { + if (!arc1.isRadiusEqual(p_middle1, tolerance) || !arc2.isRadiusEqual(p_middle2, tolerance)) { can_do_spline_whole = Type::SplitCurve; } else { @@ -156,7 +169,7 @@ void BSplineCurveBiArcs::createArcs(double tolerance, std::list& new_ double t_middle = t_start + ((t_end - t_start) * 0.5); gp_Pnt p_middle; gp_Vec v_middle; - createArcs(tolerance, new_spans, p_start, v_start, t_start, t_middle, p_middle, v_middle);// recursive + createArcs(tolerance, new_spans, p_start, v_start, t_start, t_middle, p_middle, v_middle); // recursive gp_Pnt new_p_end; gp_Vec new_v_end; createArcs(tolerance, new_spans, p_middle, v_middle, t_middle, t_end, new_p_end, new_v_end); @@ -164,29 +177,41 @@ void BSplineCurveBiArcs::createArcs(double tolerance, std::list& new_ else { // calculate_biarc_points failed, just add a line Part::GeomLineSegment* line = new Part::GeomLineSegment(); - line->setPoints(Base::convertTo(p_start),Base::convertTo(p_end)); + line->setPoints( + Base::convertTo(p_start), + Base::convertTo(p_end) + ); new_spans.push_back(line); } } -BSplineCurveBiArcs::Type -BSplineCurveBiArcs::calculateBiArcPoints(double t_start, const gp_Pnt& p0, gp_Vec v_start, - double t_end, const gp_Pnt& p4, gp_Vec v_end, - gp_Pnt& p1, gp_Pnt& p2, gp_Pnt& p3) const +BSplineCurveBiArcs::Type BSplineCurveBiArcs::calculateBiArcPoints( + double t_start, + const gp_Pnt& p0, + gp_Vec v_start, + double t_end, + const gp_Pnt& p4, + gp_Vec v_end, + gp_Pnt& p1, + gp_Pnt& p2, + gp_Pnt& p3 +) const { - if (v_start.Magnitude() < Precision::Intersection()) + if (v_start.Magnitude() < Precision::Intersection()) { v_start = gp_Vec(p0, p1); - if (v_end.Magnitude() < Precision::Intersection()) + } + if (v_end.Magnitude() < Precision::Intersection()) { v_end = gp_Vec(p3, p4); + } v_start.Normalize(); v_end.Normalize(); gp_Vec v = p0.XYZ() - p4.XYZ(); - double a = 2*(v_start*v_end-1); - double c = v*v; - double b = (v*2)*(v_start+v_end); + double a = 2 * (v_start * v_end - 1); + double c = v * v; + double b = (v * 2) * (v_start + v_end); if (fabs(a) < Precision::Intersection()) { // Check the tangent of a value between t_start and t_end double t_mid = 0.9 * t_start + 0.1 * t_end; @@ -195,7 +220,7 @@ BSplineCurveBiArcs::calculateBiArcPoints(double t_start, const gp_Pnt& p0, gp_Ve gp_Vec v_mid; this->myCurve->D1(t_mid, p_mid, v_mid); v_mid.Normalize(); - double a = 2*(v_start*v_mid-1); + double a = 2 * (v_start * v_mid - 1); if (fabs(a) >= Precision::Intersection()) { return Type::SplitCurve; } @@ -204,21 +229,25 @@ BSplineCurveBiArcs::calculateBiArcPoints(double t_start, const gp_Pnt& p0, gp_Ve } - double d = b*b-4*a*c; - if (d < 0.0) + double d = b * b - 4 * a * c; + if (d < 0.0) { return Type::SingleLine; + } double sd = sqrt(d); double e1 = (-b - sd) / (2.0 * a); double e2 = (-b + sd) / (2.0 * a); - if (e1 > 0 && e2 > 0) + if (e1 > 0 && e2 > 0) { return Type::SingleLine; + } double e = e1; - if (e2 > e) + if (e2 > e) { e = e2; - if (e < 0) + } + if (e < 0) { return Type::SingleLine; + } p1 = p0.XYZ() + v_start.XYZ() * e; p3 = p4.XYZ() - v_end.XYZ() * e; @@ -228,11 +257,9 @@ BSplineCurveBiArcs::calculateBiArcPoints(double t_start, const gp_Pnt& p0, gp_Ve return Type::SingleArc; } -BSplineCurveBiArcs::BSplineCurveBiArcs(const Handle(Geom_Curve)& c) +BSplineCurveBiArcs::BSplineCurveBiArcs(const Handle(Geom_Curve) & c) : myCurve(c) -{ - -} +{} std::list BSplineCurveBiArcs::toBiArcs(double tolerance) const { @@ -248,16 +275,40 @@ std::list BSplineCurveBiArcs::toBiArcs(double tolerance) const // the spline is closed if (p_start.Distance(p_end) < Precision::Intersection()) { this->myCurve->D1(this->myCurve->FirstParameter(), p_start, v_start); - createArcs(tolerance, list, p_start, v_start, this->myCurve->FirstParameter(), - this->myCurve->LastParameter()/2, p_end, v_end); - this->myCurve->D1(this->myCurve->LastParameter()/2, p_start, v_start); - createArcs(tolerance, list, p_start, v_start, this->myCurve->LastParameter()/2, - this->myCurve->LastParameter(), p_end, v_end); + createArcs( + tolerance, + list, + p_start, + v_start, + this->myCurve->FirstParameter(), + this->myCurve->LastParameter() / 2, + p_end, + v_end + ); + this->myCurve->D1(this->myCurve->LastParameter() / 2, p_start, v_start); + createArcs( + tolerance, + list, + p_start, + v_start, + this->myCurve->LastParameter() / 2, + this->myCurve->LastParameter(), + p_end, + v_end + ); } else { this->myCurve->D1(this->myCurve->FirstParameter(), p_start, v_start); - createArcs(tolerance, list, p_start, v_start, this->myCurve->FirstParameter(), - this->myCurve->LastParameter(), p_end, v_end); + createArcs( + tolerance, + list, + p_start, + v_start, + this->myCurve->FirstParameter(), + this->myCurve->LastParameter(), + p_end, + v_end + ); } return list; diff --git a/src/Mod/Part/App/BSplineCurveBiArcs.h b/src/Mod/Part/App/BSplineCurveBiArcs.h index e78e188b0d..c33174c4c1 100644 --- a/src/Mod/Part/App/BSplineCurveBiArcs.h +++ b/src/Mod/Part/App/BSplineCurveBiArcs.h @@ -37,34 +37,51 @@ #include -namespace Part { +namespace Part +{ class Geometry; class PartExport BSplineCurveBiArcs { public: - BSplineCurveBiArcs(const Handle(Geom_Curve)&); + BSplineCurveBiArcs(const Handle(Geom_Curve) &); std::list toBiArcs(double tolerance) const; private: - void createArcs(double tolerance, std::list& new_spans, - const gp_Pnt &p_start, const gp_Vec &v_start, - double t_start, double t_end, gp_Pnt &p_end, gp_Vec &v_end) const; - enum class Type { + void createArcs( + double tolerance, + std::list& new_spans, + const gp_Pnt& p_start, + const gp_Vec& v_start, + double t_start, + double t_end, + gp_Pnt& p_end, + gp_Vec& v_end + ) const; + enum class Type + { SingleArc, SplitCurve, SingleLine }; - Type calculateBiArcPoints(double t_start, const gp_Pnt& p0, gp_Vec v_start, - double t_end, const gp_Pnt& p4, gp_Vec v_end, - gp_Pnt& p1, gp_Pnt& p2, gp_Pnt& p3) const; + Type calculateBiArcPoints( + double t_start, + const gp_Pnt& p0, + gp_Vec v_start, + double t_end, + const gp_Pnt& p4, + gp_Vec v_end, + gp_Pnt& p1, + gp_Pnt& p2, + gp_Pnt& p3 + ) const; private: Handle(Geom_Curve) myCurve; }; -} +} // namespace Part -#endif // PART_BSPLINECURVEBIARCS_H +#endif // PART_BSPLINECURVEBIARCS_H diff --git a/src/Mod/Part/App/BSplineCurvePyImp.cpp b/src/Mod/Part/App/BSplineCurvePyImp.cpp index 3dd51aefd1..2b0d7b93f0 100644 --- a/src/Mod/Part/App/BSplineCurvePyImp.cpp +++ b/src/Mod/Part/App/BSplineCurvePyImp.cpp @@ -22,20 +22,20 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -56,7 +56,7 @@ std::string BSplineCurvePy::representation() const return ""; } -PyObject *BSplineCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BSplineCurvePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BSplineCurvePy and the Twin object return new BSplineCurvePy(new GeomBSplineCurve); @@ -83,16 +83,20 @@ int BSplineCurvePy::PyInit(PyObject* args, PyObject* kwd) return -1; } - PyErr_SetString(PyExc_TypeError, "B-spline constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "B-spline constructor accepts:\n" "-- poles, [ periodic, degree, interpolate ]\n" - "-- empty parameter list\n"); + "-- empty parameter list\n" + ); return -1; } -PyObject* BSplineCurvePy::__reduce__(PyObject *args) const +PyObject* BSplineCurvePy::__reduce__(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Py::Tuple tuple(2); @@ -115,59 +119,65 @@ PyObject* BSplineCurvePy::__reduce__(PyObject *args) const return Py::new_reference_to(tuple); } -PyObject* BSplineCurvePy::isRational(PyObject *args) const +PyObject* BSplineCurvePy::isRational(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = curve->IsRational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineCurvePy::isPeriodic(PyObject *args) const +PyObject* BSplineCurvePy::isPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = curve->IsPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineCurvePy::isClosed(PyObject *args) const +PyObject* BSplineCurvePy::isClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = curve->IsClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineCurvePy::increaseDegree(PyObject * args) +PyObject* BSplineCurvePy::increaseDegree(PyObject* args) { int degree; - if (!PyArg_ParseTuple(args, "i", °ree)) + if (!PyArg_ParseTuple(args, "i", °ree)) { return nullptr; - PY_TRY { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + } + PY_TRY + { + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->IncreaseDegree(degree); Py_Return; - } PY_CATCH_OCC; + } + PY_CATCH_OCC; } -PyObject* BSplineCurvePy::increaseMultiplicity(PyObject * args) +PyObject* BSplineCurvePy::increaseMultiplicity(PyObject* args) { - int mult=-1; + int mult = -1; int start, end; - if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); if (mult == -1) { mult = end; curve->IncreaseMultiplicity(start, mult); @@ -184,15 +194,17 @@ PyObject* BSplineCurvePy::increaseMultiplicity(PyObject * args) } } -PyObject* BSplineCurvePy::incrementMultiplicity(PyObject * args) +PyObject* BSplineCurvePy::incrementMultiplicity(PyObject* args) { int start, end, mult; - if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->IncrementMultiplicity(start, end, mult); } catch (Standard_Failure& e) { @@ -203,17 +215,19 @@ PyObject* BSplineCurvePy::incrementMultiplicity(PyObject * args) Py_Return; } -PyObject* BSplineCurvePy::insertKnot(PyObject * args) +PyObject* BSplineCurvePy::insertKnot(PyObject* args) { double U, tol = 0.0; - int M=1; + int M = 1; PyObject* add = Py_True; - if (!PyArg_ParseTuple(args, "d|idO!", &U, &M, &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "d|idO!", &U, &M, &tol, &PyBool_Type, &add)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->InsertKnot(U, M, tol, Base::asBoolean(add)); } catch (Standard_Failure& e) { @@ -224,35 +238,35 @@ PyObject* BSplineCurvePy::insertKnot(PyObject * args) Py_Return; } -PyObject* BSplineCurvePy::insertKnots(PyObject * args) +PyObject* BSplineCurvePy::insertKnots(PyObject* args) { double tol = 0.0; PyObject* add = Py_True; PyObject* obj1; PyObject* obj2; - if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, - &obj2, - &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, &obj2, &tol, &PyBool_Type, &add)) { return nullptr; + } try { Py::Sequence knots(obj1); TColStd_Array1OfReal k(1, knots.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = knots.begin(); it != knots.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } Py::Sequence mults(obj2); TColStd_Array1OfInteger m(1, mults.size()); - index=1; + index = 1; for (Py::Sequence::iterator it = mults.begin(); it != mults.end(); ++it) { Py::Long val(*it); m(index++) = (int)val; } - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->InsertKnots(k, m, tol, Base::asBoolean(add)); Py_Return; } @@ -264,16 +278,18 @@ PyObject* BSplineCurvePy::insertKnots(PyObject * args) Py_Return; } -PyObject* BSplineCurvePy::removeKnot(PyObject * args) +PyObject* BSplineCurvePy::removeKnot(PyObject* args) { double tol; int Index, M; - if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) + if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean ok = curve->RemoveKnot(Index, M, tol); return PyBool_FromLong(ok ? 1 : 0); } @@ -283,19 +299,20 @@ PyObject* BSplineCurvePy::removeKnot(PyObject * args) } } -PyObject* BSplineCurvePy::segment(PyObject * args) +PyObject* BSplineCurvePy::segment(PyObject* args) { double u1, u2; - if (!PyArg_ParseTuple(args, "dd", &u1, &u2)) + if (!PyArg_ParseTuple(args, "dd", &u1, &u2)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - Handle(Geom_BSplineCurve) tempCurve = Handle(Geom_BSplineCurve)::DownCast - (curve->Copy()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + Handle(Geom_BSplineCurve) tempCurve = Handle(Geom_BSplineCurve)::DownCast(curve->Copy()); tempCurve->Segment(u1, u2); - if (std::abs(tempCurve->FirstParameter()-u1) > Precision::Approximation() || - std::abs(tempCurve->LastParameter()-u2) > Precision::Approximation()) { + if (std::abs(tempCurve->FirstParameter() - u1) > Precision::Approximation() + || std::abs(tempCurve->LastParameter() - u2) > Precision::Approximation()) { Standard_Failure::Raise("Failed to segment BSpline curve"); return nullptr; } @@ -310,16 +327,18 @@ PyObject* BSplineCurvePy::segment(PyObject * args) } } -PyObject* BSplineCurvePy::setKnot(PyObject * args) +PyObject* BSplineCurvePy::setKnot(PyObject* args) { - int Index, M=-1; + int Index, M = -1; double K; - if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) + if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); if (M == -1) { curve->SetKnot(Index, K); } @@ -335,18 +354,20 @@ PyObject* BSplineCurvePy::setKnot(PyObject * args) } } -PyObject* BSplineCurvePy::getKnot(PyObject * args) const +PyObject* BSplineCurvePy::getKnot(PyObject* args) const { int Index; - if (!PyArg_ParseTuple(args, "i", &Index)) + if (!PyArg_ParseTuple(args, "i", &Index)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); double M = curve->Knot(Index); - return Py_BuildValue("d",M); + return Py_BuildValue("d", M); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -354,22 +375,24 @@ PyObject* BSplineCurvePy::getKnot(PyObject * args) const } } -PyObject* BSplineCurvePy::setKnots(PyObject * args) +PyObject* BSplineCurvePy::setKnots(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } try { Py::Sequence list(obj); - TColStd_Array1OfReal k(1,list.size()); - int index=1; + TColStd_Array1OfReal k(1, list.size()); + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->SetKnots(k); Py_Return; } @@ -379,17 +402,19 @@ PyObject* BSplineCurvePy::setKnots(PyObject * args) } } -PyObject* BSplineCurvePy::getKnots(PyObject * args) const +PyObject* BSplineCurvePy::getKnots(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfReal w(1,curve->NbKnots()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfReal w(1, curve->NbKnots()); curve->Knots(w); Py::List knots; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { knots.append(Py::Float(w(i))); } return Py::new_reference_to(knots); @@ -400,22 +425,26 @@ PyObject* BSplineCurvePy::getKnots(PyObject * args) const } } -PyObject* BSplineCurvePy::setPole(PyObject * args) +PyObject* BSplineCurvePy::setPole(PyObject* args) { int index; - double weight=-1.0; + double weight = -1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) { return nullptr; + } Base::Vector3d vec = static_cast(p)->value(); gp_Pnt pnt(vec.x, vec.y, vec.z); try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - if (weight < 0.0) - curve->SetPole(index,pnt); - else - curve->SetPole(index,pnt,weight); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + if (weight < 0.0) { + curve->SetPole(index, pnt); + } + else { + curve->SetPole(index, pnt, weight); + } Py_Return; } catch (Standard_Failure& e) { @@ -424,19 +453,19 @@ PyObject* BSplineCurvePy::setPole(PyObject * args) } } -PyObject* BSplineCurvePy::getPole(PyObject * args) const +PyObject* BSplineCurvePy::getPole(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles(), "Pole index out of range"); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Pole index out of range"); gp_Pnt pnt = curve->Pole(index); - Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d( - pnt.X(), pnt.Y(), pnt.Z())); + Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); return vec; } catch (Standard_Failure& e) { @@ -445,20 +474,21 @@ PyObject* BSplineCurvePy::getPole(PyObject * args) const } } -PyObject* BSplineCurvePy::getPoles(PyObject * args) const +PyObject* BSplineCurvePy::getPoles(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - TColgp_Array1OfPnt p(1,curve->NbPoles()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + TColgp_Array1OfPnt p(1, curve->NbPoles()); curve->Poles(p); Py::List poles; - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { gp_Pnt pnt = p(i); - Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d( - pnt.X(), pnt.Y(), pnt.Z())); + Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); poles.append(Py::asObject(vec)); } return Py::new_reference_to(poles); @@ -469,20 +499,22 @@ PyObject* BSplineCurvePy::getPoles(PyObject * args) const } } -PyObject* BSplineCurvePy::getPolesAndWeights(PyObject * args) const +PyObject* BSplineCurvePy::getPolesAndWeights(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - TColgp_Array1OfPnt p(1,curve->NbPoles()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + TColgp_Array1OfPnt p(1, curve->NbPoles()); curve->Poles(p); - TColStd_Array1OfReal w(1,curve->NbPoles()); + TColStd_Array1OfReal w(1, curve->NbPoles()); curve->Weights(w); Py::List poles; - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { gp_Pnt pnt = p(i); double weight = w(i); Py::Tuple t(4); @@ -500,16 +532,18 @@ PyObject* BSplineCurvePy::getPolesAndWeights(PyObject * args) const } } -PyObject* BSplineCurvePy::setWeight(PyObject * args) +PyObject* BSplineCurvePy::setWeight(PyObject* args) { int index; double weight; - if (!PyArg_ParseTuple(args, "id", &index,&weight)) + if (!PyArg_ParseTuple(args, "id", &index, &weight)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - curve->SetWeight(index,weight); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + curve->SetWeight(index, weight); Py_Return; } catch (Standard_Failure& e) { @@ -518,16 +552,17 @@ PyObject* BSplineCurvePy::setWeight(PyObject * args) } } -PyObject* BSplineCurvePy::getWeight(PyObject * args) const +PyObject* BSplineCurvePy::getWeight(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles() , "Weight index out of range"); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Weight index out of range"); double weight = curve->Weight(index); return Py_BuildValue("d", weight); } @@ -537,17 +572,19 @@ PyObject* BSplineCurvePy::getWeight(PyObject * args) const } } -PyObject* BSplineCurvePy::getWeights(PyObject * args) const +PyObject* BSplineCurvePy::getWeights(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfReal w(1,curve->NbPoles()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfReal w(1, curve->NbPoles()); curve->Weights(w); Py::List weights; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { weights.append(Py::Float(w(i))); } return Py::new_reference_to(weights); @@ -558,17 +595,19 @@ PyObject* BSplineCurvePy::getWeights(PyObject * args) const } } -PyObject* BSplineCurvePy::getResolution(PyObject * args) const +PyObject* BSplineCurvePy::getResolution(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); double utol; - curve->Resolution(tol,utol); - return Py_BuildValue("d",utol); + curve->Resolution(tol, utol); + return Py_BuildValue("d", utol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -576,20 +615,22 @@ PyObject* BSplineCurvePy::getResolution(PyObject * args) const } } -PyObject* BSplineCurvePy::movePoint(PyObject * args) +PyObject* BSplineCurvePy::movePoint(PyObject* args) { double U; int index1, index2; PyObject* pnt; - if (!PyArg_ParseTuple(args, "dO!ii", &U, &(Base::VectorPy::Type),&pnt, &index1, &index2)) + if (!PyArg_ParseTuple(args, "dO!ii", &U, &(Base::VectorPy::Type), &pnt, &index1, &index2)) { return nullptr; + } try { Base::Vector3d p = static_cast(pnt)->value(); - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); int first, last; - curve->MovePoint(U, gp_Pnt(p.x,p.y,p.z), index1, index2, first, last); - return Py_BuildValue("(ii)",first, last); + curve->MovePoint(U, gp_Pnt(p.x, p.y, p.z), index1, index2, first, last); + return Py_BuildValue("(ii)", first, last); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -597,13 +638,15 @@ PyObject* BSplineCurvePy::movePoint(PyObject * args) } } -PyObject* BSplineCurvePy::setNotPeriodic(PyObject * args) +PyObject* BSplineCurvePy::setNotPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->SetNotPeriodic(); Py_Return; } @@ -613,13 +656,15 @@ PyObject* BSplineCurvePy::setNotPeriodic(PyObject * args) } } -PyObject* BSplineCurvePy::setPeriodic(PyObject * args) +PyObject* BSplineCurvePy::setPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->SetPeriodic(); Py_Return; } @@ -629,14 +674,16 @@ PyObject* BSplineCurvePy::setPeriodic(PyObject * args) } } -PyObject* BSplineCurvePy::setOrigin(PyObject * args) +PyObject* BSplineCurvePy::setOrigin(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); curve->SetOrigin(index); Py_Return; } @@ -646,14 +693,16 @@ PyObject* BSplineCurvePy::setOrigin(PyObject * args) } } -PyObject* BSplineCurvePy::getMultiplicity(PyObject * args) const +PyObject* BSplineCurvePy::getMultiplicity(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); int mult = curve->Multiplicity(index); return Py_BuildValue("i", mult); } @@ -663,17 +712,19 @@ PyObject* BSplineCurvePy::getMultiplicity(PyObject * args) const } } -PyObject* BSplineCurvePy::getMultiplicities(PyObject * args) const +PyObject* BSplineCurvePy::getMultiplicities(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfInteger m(1,curve->NbKnots()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfInteger m(1, curve->NbKnots()); curve->Multiplicities(m); Py::List mults; - for (Standard_Integer i=m.Lower(); i<=m.Upper(); i++) { + for (Standard_Integer i = m.Lower(); i <= m.Upper(); i++) { mults.append(Py::Long(m(i))); } return Py::new_reference_to(mults); @@ -685,91 +736,84 @@ PyObject* BSplineCurvePy::getMultiplicities(PyObject * args) const } Py::Long BSplineCurvePy::getDegree() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->Degree()); } Py::Long BSplineCurvePy::getMaxDegree() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->MaxDegree()); } Py::Long BSplineCurvePy::getNbPoles() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->NbPoles()); } Py::Long BSplineCurvePy::getNbKnots() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->NbKnots()); } Py::Object BSplineCurvePy::getStartPoint() const { - Handle(Geom_BSplineCurve) c = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) c = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); gp_Pnt pnt = c->StartPoint(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } Py::Object BSplineCurvePy::getEndPoint() const { - Handle(Geom_BSplineCurve) c = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) c = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); gp_Pnt pnt = c->EndPoint(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } Py::Long BSplineCurvePy::getFirstUKnotIndex() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->FirstUKnotIndex()); } Py::Long BSplineCurvePy::getLastUKnotIndex() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->LastUKnotIndex()); } Py::List BSplineCurvePy::getKnotSequence() const { - Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(getGeometryPtr()->handle()); Standard_Integer m = 0; if (curve->IsPeriodic()) { // knots=poles+2*degree-mult(1)+2 - m = curve->NbPoles() + 2*curve->Degree() - curve->Multiplicity(1) + 2; + m = curve->NbPoles() + 2 * curve->Degree() - curve->Multiplicity(1) + 2; } else { // knots=poles+degree+1 - for (int i=1; i<= curve->NbKnots(); i++) + for (int i = 1; i <= curve->NbKnots(); i++) { m += curve->Multiplicity(i); + } } - TColStd_Array1OfReal k(1,m); + TColStd_Array1OfReal k(1, m); curve->KnotSequence(k); Py::List list; - for (Standard_Integer i=k.Lower(); i<=k.Upper(); i++) { + for (Standard_Integer i = k.Lower(); i <= k.Upper(); i++) { list.append(Py::Float(k(i))); } return list; } -PyObject* BSplineCurvePy::toBiArcs(PyObject * args) const +PyObject* BSplineCurvePy::toBiArcs(PyObject* args) const { double tolerance = 0.001; - if (!PyArg_ParseTuple(args, "d", &tolerance)) + if (!PyArg_ParseTuple(args, "d", &tolerance)) { return nullptr; + } try { GeomBSplineCurve* curve = getGeomBSplineCurvePtr(); std::list arcs; @@ -789,44 +833,60 @@ PyObject* BSplineCurvePy::toBiArcs(PyObject * args) const } } -PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) +PyObject* BSplineCurvePy::approximate(PyObject* args, PyObject* kwds) { - PyObject *obj; + PyObject* obj; Standard_Integer degMin = 3; Standard_Integer degMax = 8; Standard_Integer segMax = 8; - const char *continuity = "C2"; + const char* continuity = "C2"; double tol3d = 1e-3; - const char *parType = "ChordLength"; - PyObject *par = nullptr; + const char* parType = "ChordLength"; + PyObject* par = nullptr; double weight1 = 0; double weight2 = 0; double weight3 = 0; // Approximate this curve with a given continuity and degree - static const std::array kwds_reapprox{"MaxDegree", "MaxSegments", "Continuity", "Tolerance", - nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|isd", kwds_reapprox, - &tol3d, °Max, &segMax, &continuity)) { + static const std::array + kwds_reapprox {"MaxDegree", "MaxSegments", "Continuity", "Tolerance", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|isd", + kwds_reapprox, + &tol3d, + °Max, + &segMax, + &continuity + )) { GeomAbs_Shape c; std::string str = continuity; - if (str == "C0") + if (str == "C0") { c = GeomAbs_C0; - else if (str == "G1") + } + else if (str == "G1") { c = GeomAbs_G1; - else if (str == "C1") + } + else if (str == "C1") { c = GeomAbs_C1; - else if (str == "G2") + } + else if (str == "G2") { c = GeomAbs_G2; - else if (str == "C2") + } + else if (str == "C2") { c = GeomAbs_C2; - else if (str == "C3") + } + else if (str == "C3") { c = GeomAbs_C3; - else if (str == "CN") + } + else if (str == "CN") { c = GeomAbs_CN; - else + } + else { c = GeomAbs_C2; + } this->getGeomBSplineCurvePtr()->approximate(tol3d, segMax, degMax, c); Py_Return; @@ -834,16 +894,37 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) // Approximate a list of points // - static const std::array kwds_interp{"Points", "DegMax", "Continuity", "Tolerance", "DegMin", - "ParamType", "Parameters", "LengthWeight", "CurvatureWeight", - "TorsionWeight", nullptr}; + static const std::array kwds_interp { + "Points", + "DegMax", + "Continuity", + "Tolerance", + "DegMin", + "ParamType", + "Parameters", + "LengthWeight", + "CurvatureWeight", + "TorsionWeight", + nullptr + }; PyErr_Clear(); - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O|isdisOddd", kwds_interp, - &obj, °Max, - &continuity, &tol3d, °Min, - &parType, &par, - &weight1, &weight2, &weight3)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O|isdisOddd", + kwds_interp, + &obj, + °Max, + &continuity, + &tol3d, + °Min, + &parType, + &par, + &weight1, + &weight2, + &weight3 + )) { return nullptr; } @@ -853,7 +934,7 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) Standard_Integer index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector3d vec = Py::Vector(*it).toVector(); - pnts(index++) = gp_Pnt(vec.x,vec.y,vec.z); + pnts(index++) = gp_Pnt(vec.x, vec.y, vec.z); } if (degMin > degMax) { @@ -862,22 +943,30 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) GeomAbs_Shape c; std::string str = continuity; - if (str == "C0") + if (str == "C0") { c = GeomAbs_C0; - else if (str == "G1") + } + else if (str == "G1") { c = GeomAbs_G1; - else if (str == "C1") + } + else if (str == "C1") { c = GeomAbs_C1; - else if (str == "G2") + } + else if (str == "G2") { c = GeomAbs_G2; - else if (str == "C2") + } + else if (str == "C2") { c = GeomAbs_C2; - else if (str == "C3") + } + else if (str == "C3") { c = GeomAbs_C3; - else if (str == "CN") + } + else if (str == "CN") { c = GeomAbs_CN; - else + } + else { c = GeomAbs_C2; + } if (weight1 || weight2 || weight3) { // It seems that this function only works with Continuity = C0, C1 or C2 @@ -889,13 +978,13 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("Smoothing approximation failed"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } if (par) { Py::Sequence plist(par); - TColStd_Array1OfReal parameters(1,plist.size()); + TColStd_Array1OfReal parameters(1, plist.size()); Standard_Integer index = 1; for (Py::Sequence::iterator it = plist.begin(); it != plist.end(); ++it) { Py::Float f(*it); @@ -910,18 +999,21 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("Approximation with parameters failed"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } Approx_ParametrizationType pt; std::string pstr = parType; - if (pstr == "Uniform") + if (pstr == "Uniform") { pt = Approx_IsoParametric; - else if (pstr == "Centripetal") + } + else if (pstr == "Centripetal") { pt = Approx_Centripetal; - else + } + else { pt = Approx_ChordLength; + } GeomAPI_PointsToBSpline fit(pnts, pt, degMin, degMax, c, tol3d); Handle(Geom_BSplineCurve) spline = fit.Curve(); @@ -931,7 +1023,7 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("failed to approximate points"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } catch (Standard_Failure& e) { @@ -940,21 +1032,21 @@ PyObject* BSplineCurvePy::approximate(PyObject *args, PyObject *kwds) } } -PyObject* BSplineCurvePy::getCardinalSplineTangents(PyObject *args, PyObject *kwds) const +PyObject* BSplineCurvePy::getCardinalSplineTangents(PyObject* args, PyObject* kwds) const { PyObject* pts; PyObject* tgs; double parameter; - static const std::array kwds_interp1 {"Points", "Parameter", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "Od",kwds_interp1, &pts, ¶meter)) { + static const std::array kwds_interp1 {"Points", "Parameter", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "Od", kwds_interp1, &pts, ¶meter)) { Py::Sequence list(pts); std::vector interpPoints; interpPoints.reserve(list.size()); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector v(*it); Base::Vector3d pnt = v.toVector(); - interpPoints.emplace_back(pnt.x,pnt.y,pnt.z); + interpPoints.emplace_back(pnt.x, pnt.y, pnt.z); } GeomBSplineCurve* bspline = this->getGeomBSplineCurvePtr(); @@ -962,21 +1054,22 @@ PyObject* BSplineCurvePy::getCardinalSplineTangents(PyObject *args, PyObject *kw bspline->getCardinalSplineTangents(interpPoints, parameter, tangents); Py::List vec; - for (gp_Vec it : tangents) + for (gp_Vec it : tangents) { vec.append(Py::Vector(Base::Vector3d(it.X(), it.Y(), it.Z()))); + } return Py::new_reference_to(vec); } PyErr_Clear(); - static const std::array kwds_interp2 {"Points", "Parameters", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "OO",kwds_interp2, &pts, &tgs)) { + static const std::array kwds_interp2 {"Points", "Parameters", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "OO", kwds_interp2, &pts, &tgs)) { Py::Sequence list(pts); std::vector interpPoints; interpPoints.reserve(list.size()); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector v(*it); Base::Vector3d pnt = v.toVector(); - interpPoints.emplace_back(pnt.x,pnt.y,pnt.z); + interpPoints.emplace_back(pnt.x, pnt.y, pnt.z); } Py::Sequence list2(tgs); @@ -992,33 +1085,59 @@ PyObject* BSplineCurvePy::getCardinalSplineTangents(PyObject *args, PyObject *kw bspline->getCardinalSplineTangents(interpPoints, parameters, tangents); Py::List vec; - for (gp_Vec it : tangents) + for (gp_Vec it : tangents) { vec.append(Py::Vector(Base::Vector3d(it.X(), it.Y(), it.Z()))); + } return Py::new_reference_to(vec); } return nullptr; } -PyObject* BSplineCurvePy::interpolate(PyObject *args, PyObject *kwds) +PyObject* BSplineCurvePy::interpolate(PyObject* args, PyObject* kwds) { PyObject* obj; PyObject* par = nullptr; double tol3d = Precision::Approximation(); PyObject* periodic = Py_False; - PyObject* t1 = nullptr; PyObject* t2 = nullptr; - PyObject* ts = nullptr; PyObject* fl = nullptr; + PyObject* t1 = nullptr; + PyObject* t2 = nullptr; + PyObject* ts = nullptr; + PyObject* fl = nullptr; PyObject* scale = Py_True; - static const std::array kwds_interp{"Points", "PeriodicFlag", "Tolerance", "InitialTangent", - "FinalTangent", "Tangents", "TangentFlags", "Parameters", - "Scale", nullptr}; + static const std::array kwds_interp { + "Points", + "PeriodicFlag", + "Tolerance", + "InitialTangent", + "FinalTangent", + "Tangents", + "TangentFlags", + "Parameters", + "Scale", + nullptr + }; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O|O!dO!O!OOOO!", kwds_interp, - &obj, &PyBool_Type, &periodic, &tol3d, - &Base::VectorPy::Type, &t1, - &Base::VectorPy::Type, &t2, - &ts, &fl, &par, &PyBool_Type, &scale)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O|O!dO!O!OOOO!", + kwds_interp, + &obj, + &PyBool_Type, + &periodic, + &tol3d, + &Base::VectorPy::Type, + &t1, + &Base::VectorPy::Type, + &t2, + &ts, + &fl, + &par, + &PyBool_Type, + &scale + )) { return nullptr; } @@ -1029,7 +1148,7 @@ PyObject* BSplineCurvePy::interpolate(PyObject *args, PyObject *kwds) for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector v(*it); Base::Vector3d pnt = v.toVector(); - interpolationPoints->SetValue(index++, gp_Pnt(pnt.x,pnt.y,pnt.z)); + interpolationPoints->SetValue(index++, gp_Pnt(pnt.x, pnt.y, pnt.z)); } if (interpolationPoints->Length() < 2) { @@ -1049,18 +1168,25 @@ PyObject* BSplineCurvePy::interpolate(PyObject *args, PyObject *kwds) std::unique_ptr aBSplineInterpolation; if (parameters.IsNull()) { - aBSplineInterpolation = std::make_unique(interpolationPoints, - Base::asBoolean(periodic), tol3d); + aBSplineInterpolation = std::make_unique( + interpolationPoints, + Base::asBoolean(periodic), + tol3d + ); } else { - aBSplineInterpolation = std::make_unique(interpolationPoints, parameters, - Base::asBoolean(periodic), tol3d); + aBSplineInterpolation = std::make_unique( + interpolationPoints, + parameters, + Base::asBoolean(periodic), + tol3d + ); } if (t1 && t2) { - Base::Vector3d v1 = Py::Vector(t1,false).toVector(); - Base::Vector3d v2 = Py::Vector(t2,false).toVector(); - gp_Vec initTangent(v1.x,v1.y,v1.z), finalTangent(v2.x,v2.y,v2.z); + Base::Vector3d v1 = Py::Vector(t1, false).toVector(); + Base::Vector3d v2 = Py::Vector(t2, false).toVector(); + gp_Vec initTangent(v1.x, v1.y, v1.z), finalTangent(v2.x, v2.y, v2.z); aBSplineInterpolation->Load(initTangent, finalTangent, Base::asBoolean(scale)); } else if (ts && fl) { @@ -1070,15 +1196,19 @@ PyObject* BSplineCurvePy::interpolate(PyObject *args, PyObject *kwds) for (Py::Sequence::iterator it = tlist.begin(); it != tlist.end(); ++it) { Py::Vector v(*it); Base::Vector3d vec = v.toVector(); - tangents.SetValue(index++, gp_Vec(vec.x,vec.y,vec.z)); + tangents.SetValue(index++, gp_Vec(vec.x, vec.y, vec.z)); } Py::Sequence flist(fl); - Handle(TColStd_HArray1OfBoolean) tangentFlags = new TColStd_HArray1OfBoolean(1, flist.size()); + Handle(TColStd_HArray1OfBoolean) tangentFlags + = new TColStd_HArray1OfBoolean(1, flist.size()); Standard_Integer findex = 1; for (Py::Sequence::iterator it = flist.begin(); it != flist.end(); ++it) { Py::Boolean flag(*it); - tangentFlags->SetValue(findex++, static_cast(flag) ? Standard_True : Standard_False); + tangentFlags->SetValue( + findex++, + static_cast(flag) ? Standard_True : Standard_False + ); } aBSplineInterpolation->Load(tangents, tangentFlags, Base::asBoolean(scale)); @@ -1092,25 +1222,28 @@ PyObject* BSplineCurvePy::interpolate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("failed to interpolate points"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } } -PyObject* BSplineCurvePy::buildFromPoles(PyObject *args) +PyObject* BSplineCurvePy::buildFromPoles(PyObject* args) { PyObject* obj; int degree = 3; PyObject* periodic = Py_False; PyObject* interpolate = Py_False; - if (!PyArg_ParseTuple(args, "O|O!iO!",&obj, &PyBool_Type, &periodic, °ree, &PyBool_Type, interpolate)) + if (!PyArg_ParseTuple(args, "O|O!iO!", &obj, &PyBool_Type, &periodic, °ree, &PyBool_Type, interpolate)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); @@ -1118,11 +1251,12 @@ PyObject* BSplineCurvePy::buildFromPoles(PyObject *args) for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector v(*it); Base::Vector3d pnt = v.toVector(); - poles(index++) = gp_Pnt(pnt.x,pnt.y,pnt.z); + poles(index++) = gp_Pnt(pnt.x, pnt.y, pnt.z); } - if (poles.Length() <= degree) - degree = poles.Length()-1; + if (poles.Length() <= degree) { + degree = poles.Length() - 1; + } if (Base::asBoolean(periodic)) { int mult; @@ -1137,41 +1271,43 @@ PyObject* BSplineCurvePy::buildFromPoles(PyObject *args) } TColStd_Array1OfReal knots(1, len); TColStd_Array1OfInteger mults(1, len); - for (int i=1; i<=knots.Length(); i++){ - knots.SetValue(i,(double)(i-1)/(knots.Length()-1)); - mults.SetValue(i,1); + for (int i = 1; i <= knots.Length(); i++) { + knots.SetValue(i, (double)(i - 1) / (knots.Length() - 1)); + mults.SetValue(i, 1); } mults.SetValue(1, mult); mults.SetValue(knots.Length(), mult); - Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve(poles, knots, mults, degree, Standard_True); + Handle(Geom_BSplineCurve) spline + = new Geom_BSplineCurve(poles, knots, mults, degree, Standard_True); if (!spline.IsNull()) { this->getGeomBSplineCurvePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } else { - TColStd_Array1OfReal knots(1, poles.Length()+degree+1-2*(degree)); - TColStd_Array1OfInteger mults(1, poles.Length()+degree+1-2*(degree)); - for (int i=1; i<=knots.Length(); i++){ - knots.SetValue(i,(double)(i-1)/(knots.Length()-1)); - mults.SetValue(i,1); + TColStd_Array1OfReal knots(1, poles.Length() + degree + 1 - 2 * (degree)); + TColStd_Array1OfInteger mults(1, poles.Length() + degree + 1 - 2 * (degree)); + for (int i = 1; i <= knots.Length(); i++) { + knots.SetValue(i, (double)(i - 1) / (knots.Length() - 1)); + mults.SetValue(i, 1); } - mults.SetValue(1, degree+1); - mults.SetValue(knots.Length(), degree+1); + mults.SetValue(1, degree + 1); + mults.SetValue(knots.Length(), degree + 1); - Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve(poles, knots, mults, degree, Standard_False); + Handle(Geom_BSplineCurve) spline + = new Geom_BSplineCurve(poles, knots, mults, degree, Standard_False); if (!spline.IsNull()) { this->getGeomBSplineCurvePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } } @@ -1181,12 +1317,12 @@ PyObject* BSplineCurvePy::buildFromPoles(PyObject *args) } } -PyObject* BSplineCurvePy::buildFromPolesMultsKnots(PyObject *args, PyObject *keywds) +PyObject* BSplineCurvePy::buildFromPolesMultsKnots(PyObject* args, PyObject* keywds) { - static const std::array kwlist{"poles", "mults", "knots", "periodic", "degree", "weights", - "CheckRational", nullptr}; - PyObject* periodic = Py_False; // NOLINT - PyObject* CheckRational = Py_True; // NOLINT + static const std::array + kwlist {"poles", "mults", "knots", "periodic", "degree", "weights", "CheckRational", nullptr}; + PyObject* periodic = Py_False; // NOLINT + PyObject* CheckRational = Py_True; // NOLINT PyObject* poles = Py_None; PyObject* mults = Py_None; PyObject* knots = Py_None; @@ -1195,11 +1331,21 @@ PyObject* BSplineCurvePy::buildFromPolesMultsKnots(PyObject *args, PyObject *key int number_of_poles = 0; int number_of_knots = 0; int sum_of_mults = 0; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "O|OOO!iOO!", kwlist, - &poles, &mults, &knots, - &PyBool_Type, &periodic, - °ree, &weights, - &PyBool_Type, &CheckRational)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "O|OOO!iOO!", + kwlist, + &poles, + &mults, + &knots, + &PyBool_Type, + &periodic, + °ree, + &weights, + &PyBool_Type, + &CheckRational + )) { return nullptr; } try { @@ -1216,9 +1362,9 @@ PyObject* BSplineCurvePy::buildFromPolesMultsKnots(PyObject *args, PyObject *key for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector v(*it); Base::Vector3d pnt = v.toVector(); - occpoles(index++) = gp_Pnt(pnt.x,pnt.y,pnt.z); + occpoles(index++) = gp_Pnt(pnt.x, pnt.y, pnt.z); } - //Calculate the number of knots + // Calculate the number of knots if (mults != Py_None && knots != Py_None) { number_of_knots = PyObject_Length(mults); if (PyObject_Length(knots) != number_of_knots) { @@ -1231,70 +1377,81 @@ PyObject* BSplineCurvePy::buildFromPolesMultsKnots(PyObject *args, PyObject *key number_of_knots = PyObject_Length(mults); } else { - if (knots != Py_None) { number_of_knots = PyObject_Length(knots); } - else { //guess number of knots + if (knots != Py_None) { + number_of_knots = PyObject_Length(knots); + } + else { // guess number of knots if (Base::asBoolean(periodic)) { - if (number_of_poles < degree) {degree = number_of_poles;} - number_of_knots = number_of_poles+1; + if (number_of_poles < degree) { + degree = number_of_poles; + } + number_of_knots = number_of_poles + 1; } else { - if (number_of_poles <= degree) {degree = number_of_poles-1;} - number_of_knots = number_of_poles-degree+1; + if (number_of_poles <= degree) { + degree = number_of_poles - 1; + } + number_of_knots = number_of_poles - degree + 1; } } } } - TColStd_Array1OfInteger occmults(1,number_of_knots); - TColStd_Array1OfReal occknots(1,number_of_knots); - TColStd_Array1OfReal occweights(1,number_of_poles); - if (mults != Py_None) { //mults are given + TColStd_Array1OfInteger occmults(1, number_of_knots); + TColStd_Array1OfReal occknots(1, number_of_knots); + TColStd_Array1OfReal occweights(1, number_of_poles); + if (mults != Py_None) { // mults are given Py::Sequence multssq(mults); Standard_Integer index = 1; - for (Py::Sequence::iterator it = multssq.begin(); it != multssq.end() && index <= occmults.Length(); ++it) { + for (Py::Sequence::iterator it = multssq.begin(); + it != multssq.end() && index <= occmults.Length(); + ++it) { Py::Long mult(*it); if (index < occmults.Length() || !Base::asBoolean(periodic)) { - sum_of_mults += static_cast(mult); //sum up the mults to compare them against the number of poles later + sum_of_mults += static_cast(mult); // sum up the mults to compare them + // against the number of poles later } occmults(index++) = static_cast(mult); } } - else { //mults are 1 or degree+1 at the ends - for (int i=1; i<=occmults.Length(); i++){ - occmults.SetValue(i,1); + else { // mults are 1 or degree+1 at the ends + for (int i = 1; i <= occmults.Length(); i++) { + occmults.SetValue(i, 1); } if (!Base::asBoolean(periodic) && occmults.Length() > 0) { - occmults.SetValue(1, degree+1); - occmults.SetValue(occmults.Length(), degree+1); - sum_of_mults = occmults.Length()+2*degree; + occmults.SetValue(1, degree + 1); + occmults.SetValue(occmults.Length(), degree + 1); + sum_of_mults = occmults.Length() + 2 * degree; } else { - sum_of_mults = occmults.Length()-1; + sum_of_mults = occmults.Length() - 1; } } // check multiplicity of inner knots - for (Standard_Integer i=2; i < occmults.Length(); i++) { + for (Standard_Integer i = 2; i < occmults.Length(); i++) { if (occmults(i) > degree) { Standard_Failure::Raise("multiplicity of inner knot higher than degree"); } } - if (knots != Py_None) { //knots are given + if (knots != Py_None) { // knots are given Py::Sequence knotssq(knots); index = 1; - for (Py::Sequence::iterator it = knotssq.begin(); it != knotssq.end() && index <= occknots.Length(); ++it) { + for (Py::Sequence::iterator it = knotssq.begin(); + it != knotssq.end() && index <= occknots.Length(); + ++it) { Py::Float knot(*it); occknots(index++) = knot; } } - else { // knotes are uniformly spaced 0..1 if not given - for (int i=1; i<=occknots.Length(); i++){ - occknots.SetValue(i,(double)(i-1)/(occknots.Length()-1)); + else { // knotes are uniformly spaced 0..1 if not given + for (int i = 1; i <= occknots.Length(); i++) { + occknots.SetValue(i, (double)(i - 1) / (occknots.Length() - 1)); } } - if (weights != Py_None) { //weights are given + if (weights != Py_None) { // weights are given if (PyObject_Length(weights) != number_of_poles) { Standard_Failure::Raise("number of poles and weights mismatch"); return nullptr; - } //complain about mismatch + } // complain about mismatch Py::Sequence weightssq(weights); Standard_Integer index = 1; for (Py::Sequence::iterator it = weightssq.begin(); it != weightssq.end(); ++it) { @@ -1302,50 +1459,59 @@ PyObject* BSplineCurvePy::buildFromPolesMultsKnots(PyObject *args, PyObject *key occweights(index++) = weight; } } - else { // weights are 1.0 - for (int i=1; i<=occweights.Length(); i++){ - occweights.SetValue(i,1.0); + else { // weights are 1.0 + for (int i = 1; i <= occweights.Length(); i++) { + occweights.SetValue(i, 1.0); } } // check if the number of poles matches the sum of mults - if ((Base::asBoolean(periodic) && sum_of_mults != number_of_poles) || - (!Base::asBoolean(periodic) && sum_of_mults - degree -1 != number_of_poles)) { + if ((Base::asBoolean(periodic) && sum_of_mults != number_of_poles) + || (!Base::asBoolean(periodic) && sum_of_mults - degree - 1 != number_of_poles)) { Standard_Failure::Raise("number of poles and sum of mults mismatch"); - return(nullptr); + return (nullptr); } - Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve(occpoles,occweights,occknots,occmults,degree, - Base::asBoolean(periodic), Base::asBoolean(CheckRational)); + Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve( + occpoles, + occweights, + occknots, + occmults, + degree, + Base::asBoolean(periodic), + Base::asBoolean(CheckRational) + ); if (!spline.IsNull()) { this->getGeomBSplineCurvePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } catch (const Standard_Failure& e) { Standard_CString msg = e.GetMessageString(); - PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); + PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); return nullptr; } } -PyObject* BSplineCurvePy::toBezier(PyObject *args) const +PyObject* BSplineCurvePy::toBezier(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineCurve) spline = Handle(Geom_BSplineCurve)::DownCast - (this->getGeomBSplineCurvePtr()->handle()); + Handle(Geom_BSplineCurve) spline = Handle(Geom_BSplineCurve)::DownCast( + this->getGeomBSplineCurvePtr()->handle() + ); GeomConvert_BSplineCurveToBezierCurve crt(spline); Py::List list; Standard_Integer arcs = crt.NbArcs(); - for (Standard_Integer i=1; i<=arcs; i++) { + for (Standard_Integer i = 1; i <= arcs; i++) { Handle(Geom_BezierCurve) bezier = crt.Arc(i); list.append(Py::asObject(new BezierCurvePy(new GeomBezierCurve(bezier)))); } @@ -1358,17 +1524,19 @@ PyObject* BSplineCurvePy::toBezier(PyObject *args) const } } -PyObject* BSplineCurvePy::join(PyObject *args) +PyObject* BSplineCurvePy::join(PyObject* args) { PyObject* c; - if (!PyArg_ParseTuple(args, "O!", &BSplineCurvePy::Type, &c)) + if (!PyArg_ParseTuple(args, "O!", &BSplineCurvePy::Type, &c)) { return nullptr; + } try { GeomBSplineCurve* curve1 = this->getGeomBSplineCurvePtr(); BSplineCurvePy* curve2 = static_cast(c); - Handle(Geom_BSplineCurve) spline = Handle(Geom_BSplineCurve)::DownCast - (curve2->getGeomBSplineCurvePtr()->handle()); + Handle(Geom_BSplineCurve) spline = Handle(Geom_BSplineCurve)::DownCast( + curve2->getGeomBSplineCurvePtr()->handle() + ); bool ok = curve1->join(spline); @@ -1380,12 +1548,13 @@ PyObject* BSplineCurvePy::join(PyObject *args) } } -PyObject* BSplineCurvePy::makeC1Continuous(PyObject *args) +PyObject* BSplineCurvePy::makeC1Continuous(PyObject* args) { double tol = Precision::Approximation(); double ang_tol = 1.0e-7; - if (!PyArg_ParseTuple(args, "|dd", &tol, &ang_tol)) + if (!PyArg_ParseTuple(args, "|dd", &tol, &ang_tol)) { return nullptr; + } try { GeomBSplineCurve* spline = this->getGeomBSplineCurvePtr(); @@ -1394,18 +1563,21 @@ PyObject* BSplineCurvePy::makeC1Continuous(PyObject *args) } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } } -PyObject* BSplineCurvePy::scaleKnotsToBounds(PyObject *args) +PyObject* BSplineCurvePy::scaleKnotsToBounds(PyObject* args) { - double u0=0.0; - double u1=1.0; - if (!PyArg_ParseTuple(args, "|dd", &u0, &u1)) + double u0 = 0.0; + double u1 = 1.0; + if (!PyArg_ParseTuple(args, "|dd", &u0, &u1)) { return nullptr; + } try { if (u0 >= u1) { Standard_Failure::Raise("Bad parameter range"); @@ -1417,7 +1589,9 @@ PyObject* BSplineCurvePy::scaleKnotsToBounds(PyObject *args) } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } diff --git a/src/Mod/Part/App/BSplineSurface.pyi b/src/Mod/Part/App/BSplineSurface.pyi index 18a4f36b5f..e9e9f0fbc7 100644 --- a/src/Mod/Part/App/BSplineSurface.pyi +++ b/src/Mod/Part/App/BSplineSurface.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from GeometrySurface import GeometrySurface from typing import Final, List, Any - @export( PythonName="Part.BSplineSurface", Twin="GeomBSplineSurface", @@ -375,9 +374,7 @@ class BSplineSurface(GeometrySurface): """ ... - def setPoleCol( - self, VIndex: int, values: List[Any], CPoleWeights: List[float] - ) -> None: + def setPoleCol(self, VIndex: int, values: List[Any], CPoleWeights: List[float]) -> None: """ Modifies this B-Spline surface by assigning values to all or part of the column of poles of index VIndex, of this B-Spline surface. @@ -387,9 +384,7 @@ class BSplineSurface(GeometrySurface): """ ... - def setPoleRow( - self, UIndex: int, values: List[Any], CPoleWeights: List[float] - ) -> None: + def setPoleRow(self, UIndex: int, values: List[Any], CPoleWeights: List[float]) -> None: """ Modifies this B-Spline surface by assigning values to all or part of the row of poles of index UIndex, of this B-Spline surface. diff --git a/src/Mod/Part/App/BSplineSurfacePyImp.cpp b/src/Mod/Part/App/BSplineSurfacePyImp.cpp index a6b5811ca1..ffb0bb2137 100644 --- a/src/Mod/Part/App/BSplineSurfacePyImp.cpp +++ b/src/Mod/Part/App/BSplineSurfacePyImp.cpp @@ -22,17 +22,17 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include +#include #include #include @@ -52,7 +52,7 @@ std::string BSplineSurfacePy::representation() const return ""; } -PyObject *BSplineSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BSplineSurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BSplineSurfacePy and the Twin object return new BSplineSurfacePy(new GeomBSplineSurface); @@ -64,110 +64,128 @@ int BSplineSurfacePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* BSplineSurfacePy::bounds(PyObject *args) const +PyObject* BSplineSurfacePy::bounds(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Py::Tuple bound(4); - Standard_Real u1,u2,v1,v2; - surf->Bounds(u1,u2,v1,v2); - bound.setItem(0,Py::Float(u1)); - bound.setItem(1,Py::Float(u2)); - bound.setItem(2,Py::Float(v1)); - bound.setItem(3,Py::Float(v2)); + Standard_Real u1, u2, v1, v2; + surf->Bounds(u1, u2, v1, v2); + bound.setItem(0, Py::Float(u1)); + bound.setItem(1, Py::Float(u2)); + bound.setItem(2, Py::Float(v1)); + bound.setItem(3, Py::Float(v2)); return Py::new_reference_to(bound); } -PyObject* BSplineSurfacePy::isURational(PyObject *args) const +PyObject* BSplineSurfacePy::isURational(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean val = surf->IsURational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineSurfacePy::isVRational(PyObject *args) const +PyObject* BSplineSurfacePy::isVRational(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean val = surf->IsVRational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineSurfacePy::isUPeriodic(PyObject *args) const +PyObject* BSplineSurfacePy::isUPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean val = surf->IsUPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineSurfacePy::isVPeriodic(PyObject *args) const +PyObject* BSplineSurfacePy::isVPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean val = surf->IsVPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineSurfacePy::isUClosed(PyObject *args) const +PyObject* BSplineSurfacePy::isUClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean val = surf->IsUClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineSurfacePy::isVClosed(PyObject *args) const +PyObject* BSplineSurfacePy::isVClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Boolean val = surf->IsVPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineSurfacePy::increaseDegree(PyObject *args) +PyObject* BSplineSurfacePy::increaseDegree(PyObject* args) { int udegree, vdegree; - if (!PyArg_ParseTuple(args, "ii",&udegree,&vdegree)) + if (!PyArg_ParseTuple(args, "ii", &udegree, &vdegree)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - surf->IncreaseDegree(udegree,vdegree); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + surf->IncreaseDegree(udegree, vdegree); Py_Return; } -PyObject* BSplineSurfacePy::increaseUMultiplicity(PyObject *args) +PyObject* BSplineSurfacePy::increaseUMultiplicity(PyObject* args) { - int mult=-1; + int mult = -1; int start, end; - if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); if (mult == -1) { mult = end; surf->IncreaseUMultiplicity(start, mult); @@ -179,15 +197,17 @@ PyObject* BSplineSurfacePy::increaseUMultiplicity(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::increaseVMultiplicity(PyObject *args) +PyObject* BSplineSurfacePy::increaseVMultiplicity(PyObject* args) { - int mult=-1; + int mult = -1; int start, end; - if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); if (mult == -1) { mult = end; surf->IncreaseVMultiplicity(start, mult); @@ -199,15 +219,17 @@ PyObject* BSplineSurfacePy::increaseVMultiplicity(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::incrementUMultiplicity(PyObject *args) +PyObject* BSplineSurfacePy::incrementUMultiplicity(PyObject* args) { int start, end, mult; - if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->IncrementUMultiplicity(start, end, mult); } catch (Standard_Failure& e) { @@ -218,15 +240,17 @@ PyObject* BSplineSurfacePy::incrementUMultiplicity(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::incrementVMultiplicity(PyObject *args) +PyObject* BSplineSurfacePy::incrementVMultiplicity(PyObject* args) { int start, end, mult; - if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->IncrementVMultiplicity(start, end, mult); } catch (Standard_Failure& e) { @@ -237,17 +261,19 @@ PyObject* BSplineSurfacePy::incrementVMultiplicity(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::insertUKnot(PyObject *args) +PyObject* BSplineSurfacePy::insertUKnot(PyObject* args) { double U, tol = 0.0; - int M=1; + int M = 1; PyObject* add = Py_True; - if (!PyArg_ParseTuple(args, "did|O!", &U, &M, &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "did|O!", &U, &M, &tol, &PyBool_Type, &add)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->InsertUKnot(U, M, tol, Base::asBoolean(add)); } catch (Standard_Failure& e) { @@ -258,35 +284,35 @@ PyObject* BSplineSurfacePy::insertUKnot(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::insertUKnots(PyObject *args) +PyObject* BSplineSurfacePy::insertUKnots(PyObject* args) { double tol = 0.0; PyObject* add = Py_True; PyObject* obj1; PyObject* obj2; - if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, - &obj2, - &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, &obj2, &tol, &PyBool_Type, &add)) { return nullptr; + } try { Py::Sequence knots(obj1); - TColStd_Array1OfReal k(1,knots.size()); - int index=1; + TColStd_Array1OfReal k(1, knots.size()); + int index = 1; for (Py::Sequence::iterator it = knots.begin(); it != knots.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } Py::Sequence mults(obj2); - TColStd_Array1OfInteger m(1,mults.size()); - index=1; + TColStd_Array1OfInteger m(1, mults.size()); + index = 1; for (Py::Sequence::iterator it = mults.begin(); it != mults.end(); ++it) { Py::Long val(*it); m(index++) = (int)val; } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->InsertUKnots(k, m, tol, Base::asBoolean(add)); Py_Return; } @@ -298,17 +324,19 @@ PyObject* BSplineSurfacePy::insertUKnots(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::insertVKnot(PyObject *args) +PyObject* BSplineSurfacePy::insertVKnot(PyObject* args) { double V, tol = 0.0; - int M=1; + int M = 1; PyObject* add = Py_True; - if (!PyArg_ParseTuple(args, "did|O!", &V, &M, &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "did|O!", &V, &M, &tol, &PyBool_Type, &add)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->InsertVKnot(V, M, tol, Base::asBoolean(add)); } catch (Standard_Failure& e) { @@ -319,35 +347,35 @@ PyObject* BSplineSurfacePy::insertVKnot(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::insertVKnots(PyObject *args) +PyObject* BSplineSurfacePy::insertVKnots(PyObject* args) { double tol = 0.0; PyObject* add = Py_True; PyObject* obj1; PyObject* obj2; - if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, - &obj2, - &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, &obj2, &tol, &PyBool_Type, &add)) { return nullptr; + } try { Py::Sequence knots(obj1); - TColStd_Array1OfReal k(1,knots.size()); - int index=1; + TColStd_Array1OfReal k(1, knots.size()); + int index = 1; for (Py::Sequence::iterator it = knots.begin(); it != knots.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } Py::Sequence mults(obj2); - TColStd_Array1OfInteger m(1,mults.size()); - index=1; + TColStd_Array1OfInteger m(1, mults.size()); + index = 1; for (Py::Sequence::iterator it = mults.begin(); it != mults.end(); ++it) { Py::Long val(*it); m(index++) = (int)val; } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->InsertVKnots(k, m, tol, Base::asBoolean(add)); Py_Return; } @@ -359,17 +387,19 @@ PyObject* BSplineSurfacePy::insertVKnots(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::removeUKnot(PyObject *args) +PyObject* BSplineSurfacePy::removeUKnot(PyObject* args) { double tol; - int Index,M; - if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) + int Index, M; + if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - Standard_Boolean ok = surf->RemoveUKnot(Index,M,tol); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + Standard_Boolean ok = surf->RemoveUKnot(Index, M, tol); return PyBool_FromLong(ok ? 1 : 0); } catch (Standard_Failure& e) { @@ -378,17 +408,19 @@ PyObject* BSplineSurfacePy::removeUKnot(PyObject *args) } } -PyObject* BSplineSurfacePy::removeVKnot(PyObject *args) +PyObject* BSplineSurfacePy::removeVKnot(PyObject* args) { double tol; - int Index,M; - if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) + int Index, M; + if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - Standard_Boolean ok = surf->RemoveVKnot(Index,M,tol); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + Standard_Boolean ok = surf->RemoveVKnot(Index, M, tol); return PyBool_FromLong(ok ? 1 : 0); } catch (Standard_Failure& e) { @@ -397,15 +429,17 @@ PyObject* BSplineSurfacePy::removeVKnot(PyObject *args) } } -PyObject* BSplineSurfacePy::segment(PyObject *args) +PyObject* BSplineSurfacePy::segment(PyObject* args) { - double u1,u2,v1,v2; - if (!PyArg_ParseTuple(args, "dddd", &u1,&u2,&v1,&v2)) + double u1, u2, v1, v2; + if (!PyArg_ParseTuple(args, "dddd", &u1, &u2, &v1, &v2)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - surf->Segment(u1,u2,v1,v2); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + surf->Segment(u1, u2, v1, v2); Py_Return; } catch (Standard_Failure& e) { @@ -415,15 +449,17 @@ PyObject* BSplineSurfacePy::segment(PyObject *args) } } -PyObject* BSplineSurfacePy::setUKnot(PyObject *args) +PyObject* BSplineSurfacePy::setUKnot(PyObject* args) { - int Index, M=-1; + int Index, M = -1; double K; - if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) + if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); if (M == -1) { surf->SetUKnot(Index, K); } @@ -434,15 +470,17 @@ PyObject* BSplineSurfacePy::setUKnot(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::setVKnot(PyObject *args) +PyObject* BSplineSurfacePy::setVKnot(PyObject* args) { - int Index, M=-1; + int Index, M = -1; double K; - if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) + if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); if (M == -1) { surf->SetVKnot(Index, K); } @@ -453,48 +491,54 @@ PyObject* BSplineSurfacePy::setVKnot(PyObject *args) Py_Return; } -PyObject* BSplineSurfacePy::getUKnot(PyObject *args) const +PyObject* BSplineSurfacePy::getUKnot(PyObject* args) const { int Index; - if (!PyArg_ParseTuple(args, "i", &Index)) + if (!PyArg_ParseTuple(args, "i", &Index)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); double M = surf->UKnot(Index); - return Py_BuildValue("d",M); + return Py_BuildValue("d", M); } -PyObject* BSplineSurfacePy::getVKnot(PyObject *args) const +PyObject* BSplineSurfacePy::getVKnot(PyObject* args) const { int Index; - if (!PyArg_ParseTuple(args, "i", &Index)) + if (!PyArg_ParseTuple(args, "i", &Index)) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); double M = surf->VKnot(Index); - return Py_BuildValue("d",M); + return Py_BuildValue("d", M); } -PyObject* BSplineSurfacePy::setUKnots(PyObject *args) +PyObject* BSplineSurfacePy::setUKnots(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } try { Py::Sequence list(obj); - TColStd_Array1OfReal k(1,list.size()); - int index=1; + TColStd_Array1OfReal k(1, list.size()); + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetUKnots(k); Py_Return; } @@ -504,22 +548,24 @@ PyObject* BSplineSurfacePy::setUKnots(PyObject *args) } } -PyObject* BSplineSurfacePy::setVKnots(PyObject *args) +PyObject* BSplineSurfacePy::setVKnots(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } try { Py::Sequence list(obj); - TColStd_Array1OfReal k(1,list.size()); - int index=1; + TColStd_Array1OfReal k(1, list.size()); + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetVKnots(k); Py_Return; } @@ -529,17 +575,19 @@ PyObject* BSplineSurfacePy::setVKnots(PyObject *args) } } -PyObject* BSplineSurfacePy::getUKnots(PyObject *args) const +PyObject* BSplineSurfacePy::getUKnots(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfReal w(1,surf->NbUKnots()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfReal w(1, surf->NbUKnots()); surf->UKnots(w); Py::List knots; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { knots.append(Py::Float(w(i))); } return Py::new_reference_to(knots); @@ -550,17 +598,19 @@ PyObject* BSplineSurfacePy::getUKnots(PyObject *args) const } } -PyObject* BSplineSurfacePy::getVKnots(PyObject *args) const +PyObject* BSplineSurfacePy::getVKnots(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfReal w(1,surf->NbVKnots()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfReal w(1, surf->NbVKnots()); surf->VKnots(w); Py::List knots; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { knots.append(Py::Float(w(i))); } return Py::new_reference_to(knots); @@ -571,22 +621,26 @@ PyObject* BSplineSurfacePy::getVKnots(PyObject *args) const } } -PyObject* BSplineSurfacePy::setPole(PyObject *args) +PyObject* BSplineSurfacePy::setPole(PyObject* args) { int uindex, vindex; - double weight=-1.0; + double weight = -1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iiO!|d", &uindex,&vindex,&(Base::VectorPy::Type),&p,&weight)) + if (!PyArg_ParseTuple(args, "iiO!|d", &uindex, &vindex, &(Base::VectorPy::Type), &p, &weight)) { return nullptr; + } Base::Vector3d vec = static_cast(p)->value(); gp_Pnt pnt(vec.x, vec.y, vec.z); try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - if (weight < 0.0) - surf->SetPole(uindex,vindex,pnt); - else - surf->SetPole(uindex,vindex,pnt,weight); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + if (weight < 0.0) { + surf->SetPole(uindex, vindex, pnt); + } + else { + surf->SetPole(uindex, vindex, pnt, weight); + } Py_Return; } catch (Standard_Failure& e) { @@ -595,32 +649,34 @@ PyObject* BSplineSurfacePy::setPole(PyObject *args) } } -PyObject* BSplineSurfacePy::setPoleCol(PyObject *args) +PyObject* BSplineSurfacePy::setPoleCol(PyObject* args) { int vindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&vindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &vindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->SetPoleCol(vindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -635,32 +691,34 @@ PyObject* BSplineSurfacePy::setPoleCol(PyObject *args) } } -PyObject* BSplineSurfacePy::setPoleRow(PyObject *args) +PyObject* BSplineSurfacePy::setPoleRow(PyObject* args) { int uindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&uindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &uindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->SetPoleRow(uindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -675,20 +733,22 @@ PyObject* BSplineSurfacePy::setPoleRow(PyObject *args) } } -PyObject* BSplineSurfacePy::getPole(PyObject *args) const +PyObject* BSplineSurfacePy::getPole(PyObject* args) const { - int uindex,vindex; - if (!PyArg_ParseTuple(args, "ii", &uindex,&vindex)) + int uindex, vindex; + if (!PyArg_ParseTuple(args, "ii", &uindex, &vindex)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (uindex < 1 || uindex > surf->NbUPoles() || - vindex < 1 || vindex > surf->NbVPoles(), "Pole index out of range"); - gp_Pnt pnt = surf->Pole(uindex,vindex); - Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d( - pnt.X(), pnt.Y(), pnt.Z())); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + Standard_OutOfRange_Raise_if( + uindex < 1 || uindex > surf->NbUPoles() || vindex < 1 || vindex > surf->NbVPoles(), + "Pole index out of range" + ); + gp_Pnt pnt = surf->Pole(uindex, vindex); + Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); return vec; } catch (Standard_Failure& e) { @@ -697,22 +757,25 @@ PyObject* BSplineSurfacePy::getPole(PyObject *args) const } } -PyObject* BSplineSurfacePy::getPoles(PyObject *args) const +PyObject* BSplineSurfacePy::getPoles(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColgp_Array2OfPnt p(1,surf->NbUPoles(),1,surf->NbVPoles()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColgp_Array2OfPnt p(1, surf->NbUPoles(), 1, surf->NbVPoles()); surf->Poles(p); Py::List poles; - for (Standard_Integer i=p.LowerRow(); i<=p.UpperRow(); i++) { + for (Standard_Integer i = p.LowerRow(); i <= p.UpperRow(); i++) { Py::List row; - for (Standard_Integer j=p.LowerCol(); j<=p.UpperCol(); j++) { - const gp_Pnt& pole = p(i,j); - row.append(Py::asObject(new Base::VectorPy( - Base::Vector3d(pole.X(),pole.Y(),pole.Z())))); + for (Standard_Integer j = p.LowerCol(); j <= p.UpperCol(); j++) { + const gp_Pnt& pole = p(i, j); + row.append( + Py::asObject(new Base::VectorPy(Base::Vector3d(pole.X(), pole.Y(), pole.Z()))) + ); } poles.append(row); } @@ -724,16 +787,18 @@ PyObject* BSplineSurfacePy::getPoles(PyObject *args) const } } -PyObject* BSplineSurfacePy::setWeight(PyObject *args) +PyObject* BSplineSurfacePy::setWeight(PyObject* args) { - int uindex,vindex; + int uindex, vindex; double weight; - if (!PyArg_ParseTuple(args, "iid",&uindex,&vindex,&weight)) + if (!PyArg_ParseTuple(args, "iid", &uindex, &vindex, &weight)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - surf->SetWeight(uindex,vindex,weight); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + surf->SetWeight(uindex, vindex, weight); Py_Return; } catch (Standard_Failure& e) { @@ -742,22 +807,24 @@ PyObject* BSplineSurfacePy::setWeight(PyObject *args) } } -PyObject* BSplineSurfacePy::setWeightCol(PyObject *args) +PyObject* BSplineSurfacePy::setWeightCol(PyObject* args) { int vindex; PyObject* obj; - if (!PyArg_ParseTuple(args, "iO",&vindex,&obj)) + if (!PyArg_ParseTuple(args, "iO", &vindex, &obj)) { return nullptr; + } try { Py::Sequence list(obj); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetWeightCol(vindex, weights); Py_Return; } @@ -767,22 +834,24 @@ PyObject* BSplineSurfacePy::setWeightCol(PyObject *args) } } -PyObject* BSplineSurfacePy::setWeightRow(PyObject *args) +PyObject* BSplineSurfacePy::setWeightRow(PyObject* args) { int uindex; PyObject* obj; - if (!PyArg_ParseTuple(args, "iO",&uindex,&obj)) + if (!PyArg_ParseTuple(args, "iO", &uindex, &obj)) { return nullptr; + } try { Py::Sequence list(obj); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetWeightRow(uindex, weights); Py_Return; } @@ -792,18 +861,21 @@ PyObject* BSplineSurfacePy::setWeightRow(PyObject *args) } } -PyObject* BSplineSurfacePy::getWeight(PyObject *args) const +PyObject* BSplineSurfacePy::getWeight(PyObject* args) const { - int uindex,vindex; - if (!PyArg_ParseTuple(args, "ii",&uindex,&vindex)) + int uindex, vindex; + if (!PyArg_ParseTuple(args, "ii", &uindex, &vindex)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (uindex < 1 || uindex > surf->NbUPoles() || - vindex < 1 || vindex > surf->NbVPoles(), "Weight index out of range"); - double w = surf->Weight(uindex,vindex); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + Standard_OutOfRange_Raise_if( + uindex < 1 || uindex > surf->NbUPoles() || vindex < 1 || vindex > surf->NbVPoles(), + "Weight index out of range" + ); + double w = surf->Weight(uindex, vindex); return Py_BuildValue("d", w); } catch (Standard_Failure& e) { @@ -812,20 +884,22 @@ PyObject* BSplineSurfacePy::getWeight(PyObject *args) const } } -PyObject* BSplineSurfacePy::getWeights(PyObject *args) const +PyObject* BSplineSurfacePy::getWeights(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array2OfReal w(1,surf->NbUPoles(),1,surf->NbVPoles()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array2OfReal w(1, surf->NbUPoles(), 1, surf->NbVPoles()); surf->Weights(w); Py::List weights; - for (Standard_Integer i=w.LowerRow(); i<=w.UpperRow(); i++) { + for (Standard_Integer i = w.LowerRow(); i <= w.UpperRow(); i++) { Py::List row; - for (Standard_Integer j=w.LowerCol(); j<=w.UpperCol(); j++) { - row.append(Py::Float(w(i,j))); + for (Standard_Integer j = w.LowerCol(); j <= w.UpperCol(); j++) { + row.append(Py::Float(w(i, j))); } weights.append(row); } @@ -837,24 +911,26 @@ PyObject* BSplineSurfacePy::getWeights(PyObject *args) const } } -PyObject* BSplineSurfacePy::getPolesAndWeights(PyObject *args) const +PyObject* BSplineSurfacePy::getPolesAndWeights(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColgp_Array2OfPnt p(1,surf->NbUPoles(),1,surf->NbVPoles()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColgp_Array2OfPnt p(1, surf->NbUPoles(), 1, surf->NbVPoles()); surf->Poles(p); - TColStd_Array2OfReal w(1,surf->NbUPoles(),1,surf->NbVPoles()); + TColStd_Array2OfReal w(1, surf->NbUPoles(), 1, surf->NbVPoles()); surf->Weights(w); Py::List poles; - for (Standard_Integer i=p.LowerRow(); i<=p.UpperRow(); i++) { + for (Standard_Integer i = p.LowerRow(); i <= p.UpperRow(); i++) { Py::List row; - for (Standard_Integer j=p.LowerCol(); j<=p.UpperCol(); j++) { - const gp_Pnt& pole = p(i,j); - double weight = w(i,j); + for (Standard_Integer j = p.LowerCol(); j <= p.UpperCol(); j++) { + const gp_Pnt& pole = p(i, j); + double weight = w(i, j); Py::Tuple t(4); t.setItem(0, Py::Float(pole.X())); t.setItem(1, Py::Float(pole.Y())); @@ -872,17 +948,19 @@ PyObject* BSplineSurfacePy::getPolesAndWeights(PyObject *args) const } } -PyObject* BSplineSurfacePy::getResolution(PyObject *args) const +PyObject* BSplineSurfacePy::getResolution(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); double utol, vtol; - surf->Resolution(tol,utol,vtol); - return Py_BuildValue("(dd)",utol,vtol); + surf->Resolution(tol, utol, vtol); + return Py_BuildValue("(dd)", utol, vtol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -890,23 +968,46 @@ PyObject* BSplineSurfacePy::getResolution(PyObject *args) const } } -PyObject* BSplineSurfacePy::movePoint(PyObject *args) +PyObject* BSplineSurfacePy::movePoint(PyObject* args) { - double U,V; + double U, V; int uindex1, uindex2; int vindex1, vindex2; PyObject* pnt; - if (!PyArg_ParseTuple(args, "ddO!iiii", &U, &V, &(Base::VectorPy::Type),&pnt, - &uindex1, &uindex2,&vindex1, &vindex2)) + if (!PyArg_ParseTuple( + args, + "ddO!iiii", + &U, + &V, + &(Base::VectorPy::Type), + &pnt, + &uindex1, + &uindex2, + &vindex1, + &vindex2 + )) { return nullptr; + } try { Base::Vector3d p = static_cast(pnt)->value(); - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int ufirst, ulast, vfirst, vlast; - surf->MovePoint(U, V, gp_Pnt(p.x,p.y,p.z), uindex1, uindex2, vindex1, vindex2, - ufirst, ulast, vfirst, vlast); - return Py_BuildValue("(iiii)",ufirst, ulast, vfirst, vlast); + surf->MovePoint( + U, + V, + gp_Pnt(p.x, p.y, p.z), + uindex1, + uindex2, + vindex1, + vindex2, + ufirst, + ulast, + vfirst, + vlast + ); + return Py_BuildValue("(iiii)", ufirst, ulast, vfirst, vlast); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -914,13 +1015,15 @@ PyObject* BSplineSurfacePy::movePoint(PyObject *args) } } -PyObject* BSplineSurfacePy::setUNotPeriodic(PyObject *args) +PyObject* BSplineSurfacePy::setUNotPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetUNotPeriodic(); Py_Return; } @@ -930,13 +1033,15 @@ PyObject* BSplineSurfacePy::setUNotPeriodic(PyObject *args) } } -PyObject* BSplineSurfacePy::setVNotPeriodic(PyObject *args) +PyObject* BSplineSurfacePy::setVNotPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetVNotPeriodic(); Py_Return; } @@ -946,13 +1051,15 @@ PyObject* BSplineSurfacePy::setVNotPeriodic(PyObject *args) } } -PyObject* BSplineSurfacePy::setUPeriodic(PyObject *args) +PyObject* BSplineSurfacePy::setUPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetUPeriodic(); Py_Return; } @@ -962,13 +1069,15 @@ PyObject* BSplineSurfacePy::setUPeriodic(PyObject *args) } } -PyObject* BSplineSurfacePy::setVPeriodic(PyObject *args) +PyObject* BSplineSurfacePy::setVPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetVPeriodic(); Py_Return; } @@ -978,14 +1087,16 @@ PyObject* BSplineSurfacePy::setVPeriodic(PyObject *args) } } -PyObject* BSplineSurfacePy::setUOrigin(PyObject *args) +PyObject* BSplineSurfacePy::setUOrigin(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetUOrigin(index); Py_Return; } @@ -995,14 +1106,16 @@ PyObject* BSplineSurfacePy::setUOrigin(PyObject *args) } } -PyObject* BSplineSurfacePy::setVOrigin(PyObject *args) +PyObject* BSplineSurfacePy::setVOrigin(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetVOrigin(index); Py_Return; } @@ -1012,14 +1125,16 @@ PyObject* BSplineSurfacePy::setVOrigin(PyObject *args) } } -PyObject* BSplineSurfacePy::getUMultiplicity(PyObject *args) const +PyObject* BSplineSurfacePy::getUMultiplicity(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int mult = surf->UMultiplicity(index); return Py_BuildValue("i", mult); } @@ -1029,14 +1144,16 @@ PyObject* BSplineSurfacePy::getUMultiplicity(PyObject *args) const } } -PyObject* BSplineSurfacePy::getVMultiplicity(PyObject *args) const +PyObject* BSplineSurfacePy::getVMultiplicity(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int mult = surf->VMultiplicity(index); return Py_BuildValue("i", mult); } @@ -1046,17 +1163,19 @@ PyObject* BSplineSurfacePy::getVMultiplicity(PyObject *args) const } } -PyObject* BSplineSurfacePy::getUMultiplicities(PyObject *args) const +PyObject* BSplineSurfacePy::getUMultiplicities(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfInteger m(1,surf->NbUKnots()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfInteger m(1, surf->NbUKnots()); surf->UMultiplicities(m); Py::List mults; - for (Standard_Integer i=m.Lower(); i<=m.Upper(); i++) { + for (Standard_Integer i = m.Lower(); i <= m.Upper(); i++) { mults.append(Py::Long(m(i))); } return Py::new_reference_to(mults); @@ -1067,17 +1186,19 @@ PyObject* BSplineSurfacePy::getUMultiplicities(PyObject *args) const } } -PyObject* BSplineSurfacePy::getVMultiplicities(PyObject *args) const +PyObject* BSplineSurfacePy::getVMultiplicities(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfInteger m(1,surf->NbVKnots()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array1OfInteger m(1, surf->NbVKnots()); surf->VMultiplicities(m); Py::List mults; - for (Standard_Integer i=m.Lower(); i<=m.Upper(); i++) { + for (Standard_Integer i = m.Lower(); i <= m.Upper(); i++) { mults.append(Py::Long(m(i))); } return Py::new_reference_to(mults); @@ -1088,58 +1209,61 @@ PyObject* BSplineSurfacePy::getVMultiplicities(PyObject *args) const } } -PyObject* BSplineSurfacePy::exchangeUV(PyObject *args) +PyObject* BSplineSurfacePy::exchangeUV(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->ExchangeUV(); Py_Return; } -PyObject* BSplineSurfacePy::reparametrize(PyObject * args) const +PyObject* BSplineSurfacePy::reparametrize(PyObject* args) const { - int u,v; + int u, v; double tol = 0.000001; - if (!PyArg_ParseTuple(args, "ii|d", &u, &v, &tol)) + if (!PyArg_ParseTuple(args, "ii|d", &u, &v, &tol)) { return nullptr; + } // u,v must be at least 2 u = std::max(u, 2); v = std::max(v, 2); try { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); - double maxU = surf->UKnot(surf->NbUKnots()); // 1.0 if normalized surface - double maxV = surf->VKnot(surf->NbVKnots()); // 1.0 if normalized surface + double maxU = surf->UKnot(surf->NbUKnots()); // 1.0 if normalized surface + double maxV = surf->VKnot(surf->NbVKnots()); // 1.0 if normalized surface GeomBSplineSurface* geom = new GeomBSplineSurface(); - Handle(Geom_BSplineSurface) spline = Handle(Geom_BSplineSurface)::DownCast - (geom->handle()); - for (int i=1; iInsertUKnot(U,i,tol,Standard_True); + Handle(Geom_BSplineSurface) spline = Handle(Geom_BSplineSurface)::DownCast(geom->handle()); + for (int i = 1; i < u - 1; i++) { + double U = i * 1.0 / (u - 1.0); + spline->InsertUKnot(U, i, tol, Standard_True); } - for (int i=1; iInsertVKnot(V,i,tol,Standard_True); + for (int i = 1; i < v - 1; i++) { + double V = i * 1.0 / (v - 1.0); + spline->InsertVKnot(V, i, tol, Standard_True); } - for (int j=0; jValue(U,V); + gp_Pnt point = surf->Value(U, V); int ufirst, ulast, vfirst, vlast; - spline->MovePoint(newU, newV, point, j+1, j+1, k+1, k+1, ufirst, ulast, vfirst, vlast); + spline->MovePoint(newU, newV, point, j + 1, j + 1, k + 1, k + 1, ufirst, ulast, vfirst, vlast); } } @@ -1151,29 +1275,58 @@ PyObject* BSplineSurfacePy::reparametrize(PyObject * args) const } } -PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) +PyObject* BSplineSurfacePy::approximate(PyObject* args, PyObject* kwds) { PyObject* obj; - Standard_Integer degMin=3; - Standard_Integer degMax=8; - Standard_Integer continuity=2; + Standard_Integer degMin = 3; + Standard_Integer degMax = 8; + Standard_Integer continuity = 2; Standard_Real tol3d = Precision::Approximation(); const char* parType = "None"; Standard_Real weight1 = 1.0; Standard_Real weight2 = 1.0; Standard_Real weight3 = 1.0; - Standard_Real X0=0; - Standard_Real dX=0; - Standard_Real Y0=0; - Standard_Real dY=0; + Standard_Real X0 = 0; + Standard_Real dX = 0; + Standard_Real Y0 = 0; + Standard_Real dY = 0; - static const std::array kwds_interp{"Points", "DegMin", "DegMax", "Continuity", "Tolerance", "X0", - "dX", "Y0", "dY", "ParamType", "LengthWeight", - "CurvatureWeight", "TorsionWeight", nullptr}; + static const std::array kwds_interp { + "Points", + "DegMin", + "DegMax", + "Continuity", + "Tolerance", + "X0", + "dX", + "Y0", + "dY", + "ParamType", + "LengthWeight", + "CurvatureWeight", + "TorsionWeight", + nullptr + }; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O|iiidddddsddd", kwds_interp, &obj, °Min, °Max, - &continuity, &tol3d, &X0, &dX, &Y0, &dY, &parType, &weight1, &weight2, - &weight3)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O|iiidddddsddd", + kwds_interp, + &obj, + °Min, + °Max, + &continuity, + &tol3d, + &X0, + &dX, + &Y0, + &dY, + &parType, + &weight1, + &weight2, + &weight3 + )) { return nullptr; } try { @@ -1183,20 +1336,20 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) Standard_Integer lv = col.size(); TColgp_Array2OfPnt interpolationPoints(1, lu, 1, lv); TColStd_Array2OfReal zPoints(1, lu, 1, lv); - //Base::Console().message("lu=%d, lv=%d\n", lu, lv); + // Base::Console().message("lu=%d, lv=%d\n", lu, lv); Standard_Integer index1 = 0; Standard_Integer index2 = 0; for (Py::Sequence::iterator it1 = list.begin(); it1 != list.end(); ++it1) { index1++; - index2=0; + index2 = 0; Py::Sequence row(*it1); for (Py::Sequence::iterator it2 = row.begin(); it2 != row.end(); ++it2) { index2++; - if ((dX == 0) || (dY == 0)){ + if ((dX == 0) || (dY == 0)) { Py::Vector v(*it2); Base::Vector3d pnt = v.toVector(); - gp_Pnt newPoint(pnt.x,pnt.y,pnt.z); + gp_Pnt newPoint(pnt.x, pnt.y, pnt.z); interpolationPoints.SetValue(index1, index2, newPoint); } else { @@ -1206,7 +1359,7 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) } } - if (continuity<0 || continuity>2) { + if (continuity < 0 || continuity > 2) { Standard_Failure::Raise("continuity must be between 0 and 2"); } @@ -1215,29 +1368,33 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) } GeomAbs_Shape c = GeomAbs_C2; - switch(continuity){ - case 0: - c = GeomAbs_C0; - break; - case 1: - c = GeomAbs_C1; - break; - case 2: - c = GeomAbs_C2; - break; + switch (continuity) { + case 0: + c = GeomAbs_C0; + break; + case 1: + c = GeomAbs_C1; + break; + case 2: + c = GeomAbs_C2; + break; } Approx_ParametrizationType pt; std::string pstr = parType; Standard_Boolean useParam = Standard_True; - if (pstr == "Uniform" ) + if (pstr == "Uniform") { pt = Approx_IsoParametric; - else if (pstr == "Centripetal" ) + } + else if (pstr == "Centripetal") { pt = Approx_Centripetal; - else if (pstr == "ChordLength" ) + } + else if (pstr == "ChordLength") { pt = Approx_ChordLength; - else + } + else { useParam = Standard_False; + } GeomAPI_PointsToBSplineSurface surInterpolation; if (!(dX == 0) && !(dY == 0)) { @@ -1262,24 +1419,27 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } } -PyObject* BSplineSurfacePy::interpolate(PyObject *args) +PyObject* BSplineSurfacePy::interpolate(PyObject* args) { PyObject* obj; - Standard_Real X0=0; - Standard_Real dX=0; - Standard_Real Y0=0; - Standard_Real dY=0; + Standard_Real X0 = 0; + Standard_Real dX = 0; + Standard_Real Y0 = 0; + Standard_Real dY = 0; int len = PyTuple_GET_SIZE(args); - if (!PyArg_ParseTuple(args, "O|dddd", &obj, &X0, &dX, &Y0, &dY)) + if (!PyArg_ParseTuple(args, "O|dddd", &obj, &X0, &dX, &Y0, &dY)) { return nullptr; + } try { Py::Sequence list(obj); Standard_Integer lu = list.size(); @@ -1292,14 +1452,14 @@ PyObject* BSplineSurfacePy::interpolate(PyObject *args) Standard_Integer index2 = 0; for (Py::Sequence::iterator it1 = list.begin(); it1 != list.end(); ++it1) { index1++; - index2=0; + index2 = 0; Py::Sequence row(*it1); for (Py::Sequence::iterator it2 = row.begin(); it2 != row.end(); ++it2) { index2++; - if(len == 1){ + if (len == 1) { Py::Vector v(*it2); Base::Vector3d pnt = v.toVector(); - gp_Pnt newPoint(pnt.x,pnt.y,pnt.z); + gp_Pnt newPoint(pnt.x, pnt.y, pnt.z); interpolationPoints.SetValue(index1, index2, newPoint); } else { @@ -1314,8 +1474,8 @@ PyObject* BSplineSurfacePy::interpolate(PyObject *args) } GeomAPI_PointsToBSplineSurface surInterpolation; - if(len == 1){ - surInterpolation.Interpolate (interpolationPoints); + if (len == 1) { + surInterpolation.Interpolate(interpolationPoints); } else { surInterpolation.Interpolate(zPoints, X0, dX, Y0, dY); @@ -1326,18 +1486,31 @@ PyObject* BSplineSurfacePy::interpolate(PyObject *args) } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } } -PyObject* BSplineSurfacePy::buildFromPolesMultsKnots(PyObject *args, PyObject *keywds) +PyObject* BSplineSurfacePy::buildFromPolesMultsKnots(PyObject* args, PyObject* keywds) { - static const std::array kwlist{"poles", "umults", "vmults", "uknots", "vknots", "uperiodic", - "vperiodic", "udegree", "vdegree", "weights", nullptr}; - PyObject* uperiodic = Py_False; // NOLINT - PyObject* vperiodic = Py_False; // NOLINT + static const std::array kwlist { + "poles", + "umults", + "vmults", + "uknots", + "vknots", + "uperiodic", + "vperiodic", + "udegree", + "vdegree", + "weights", + nullptr + }; + PyObject* uperiodic = Py_False; // NOLINT + PyObject* vperiodic = Py_False; // NOLINT PyObject* poles = Py_None; PyObject* umults = Py_None; PyObject* vmults = Py_None; @@ -1351,11 +1524,24 @@ PyObject* BSplineSurfacePy::buildFromPolesMultsKnots(PyObject *args, PyObject *k int sum_of_umults = 0; int sum_of_vmults = 0; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "OOO|OOO!O!iiO", kwlist, - &poles, &umults, &vmults, //required - &uknots, &vknots, //optional - &PyBool_Type, &uperiodic, &PyBool_Type, &vperiodic, //optional - &udegree, &vdegree, &weights)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "OOO|OOO!O!iiO", + kwlist, + &poles, + &umults, + &vmults, // required + &uknots, + &vknots, // optional + &PyBool_Type, + &uperiodic, + &PyBool_Type, + &vperiodic, // optional + &udegree, + &vdegree, + &weights + )) { return nullptr; } try { @@ -1365,36 +1551,40 @@ PyObject* BSplineSurfacePy::buildFromPolesMultsKnots(PyObject *args, PyObject *k Standard_Integer lv = col.size(); TColgp_Array2OfPnt occpoles(1, lu, 1, lv); TColStd_Array2OfReal occweights(1, lu, 1, lv); - Standard_Boolean genweights = (weights==Py_None) ? Standard_True : Standard_False; //cache + Standard_Boolean genweights = (weights == Py_None) ? Standard_True : Standard_False; // cache Standard_Integer index1 = 0; Standard_Integer index2 = 0; for (Py::Sequence::iterator it1 = list.begin(); it1 != list.end(); ++it1) { index1++; - index2=0; + index2 = 0; Py::Sequence row(*it1); for (Py::Sequence::iterator it2 = row.begin(); it2 != row.end(); ++it2) { index2++; Py::Vector v(*it2); Base::Vector3d pnt = v.toVector(); - gp_Pnt newPoint(pnt.x,pnt.y,pnt.z); + gp_Pnt newPoint(pnt.x, pnt.y, pnt.z); occpoles.SetValue(index1, index2, newPoint); - if (genweights) occweights.SetValue(index1, index2, 1.0); //set weights if they are not given + if (genweights) { + occweights.SetValue(index1, index2, 1.0); // set weights if they are not given + } } } if (occpoles.RowLength() < 2 || occpoles.ColLength() < 2) { Standard_Failure::Raise("not enough points given"); } - if (!genweights) {//copy the weights + if (!genweights) { // copy the weights Py::Sequence list(weights); Standard_Integer lwu = list.size(); Py::Sequence col(list.getItem(0)); Standard_Integer lwv = col.size(); - if (lwu != lu || lwv != lv) { Standard_Failure::Raise("weights and poles mismatch");} + if (lwu != lu || lwv != lv) { + Standard_Failure::Raise("weights and poles mismatch"); + } Standard_Integer index1 = 0; Standard_Integer index2 = 0; for (Py::Sequence::iterator it1 = list.begin(); it1 != list.end(); ++it1) { index1++; - index2=0; + index2 = 0; Py::Sequence row(*it1); for (Py::Sequence::iterator it2 = row.begin(); it2 != row.end(); ++it2) { index2++; @@ -1405,96 +1595,113 @@ PyObject* BSplineSurfacePy::buildFromPolesMultsKnots(PyObject *args, PyObject *k } number_of_uknots = PyObject_Length(umults); number_of_vknots = PyObject_Length(vmults); - if (((uknots != Py_None) && PyObject_Length(uknots) != number_of_uknots) || - ((vknots != Py_None) && PyObject_Length(vknots) != number_of_vknots)){ + if (((uknots != Py_None) && PyObject_Length(uknots) != number_of_uknots) + || ((vknots != Py_None) && PyObject_Length(vknots) != number_of_vknots)) { Standard_Failure::Raise("number of knots and mults mismatch"); return nullptr; } - //copy mults - TColStd_Array1OfInteger occumults(1,number_of_uknots); - TColStd_Array1OfInteger occvmults(1,number_of_vknots); - TColStd_Array1OfReal occuknots(1,number_of_uknots); - TColStd_Array1OfReal occvknots(1,number_of_vknots); + // copy mults + TColStd_Array1OfInteger occumults(1, number_of_uknots); + TColStd_Array1OfInteger occvmults(1, number_of_vknots); + TColStd_Array1OfReal occuknots(1, number_of_uknots); + TColStd_Array1OfReal occvknots(1, number_of_vknots); Py::Sequence umultssq(umults); Standard_Integer index = 1; - for (Py::Sequence::iterator it = umultssq.begin(); it != umultssq.end() && index <= occumults.Length(); ++it) { + for (Py::Sequence::iterator it = umultssq.begin(); + it != umultssq.end() && index <= occumults.Length(); + ++it) { Py::Long mult(*it); if (index < occumults.Length() || !Base::asBoolean(uperiodic)) { - sum_of_umults += static_cast(mult); //sum up the mults to compare them against the number of poles later + sum_of_umults += static_cast(mult); // sum up the mults to compare them + // against the number of poles later } occumults(index++) = static_cast(mult); } Py::Sequence vmultssq(vmults); index = 1; - for (Py::Sequence::iterator it = vmultssq.begin(); it != vmultssq.end() && index <= occvmults.Length(); ++it) { + for (Py::Sequence::iterator it = vmultssq.begin(); + it != vmultssq.end() && index <= occvmults.Length(); + ++it) { Py::Long mult(*it); if (index < occvmults.Length() || !Base::asBoolean(vperiodic)) { - sum_of_vmults += static_cast(mult); //sum up the mults to compare them against the number of poles later + sum_of_vmults += static_cast(mult); // sum up the mults to compare them + // against the number of poles later } occvmults(index++) = static_cast(mult); } - //copy or generate knots - if (uknots != Py_None) { //uknots are given + // copy or generate knots + if (uknots != Py_None) { // uknots are given Py::Sequence uknotssq(uknots); index = 1; - for (Py::Sequence::iterator it = uknotssq.begin(); it != uknotssq.end() && index <= occuknots.Length(); ++it) { + for (Py::Sequence::iterator it = uknotssq.begin(); + it != uknotssq.end() && index <= occuknots.Length(); + ++it) { Py::Float knot(*it); occuknots(index++) = knot; } } - else { // knotes are uniformly spaced 0..1 if not given - for (int i=1; i<=occuknots.Length(); i++){ - occuknots.SetValue(i,(double)(i-1)/(occuknots.Length()-1)); + else { // knotes are uniformly spaced 0..1 if not given + for (int i = 1; i <= occuknots.Length(); i++) { + occuknots.SetValue(i, (double)(i - 1) / (occuknots.Length() - 1)); } } - if (vknots != Py_None) { //vknots are given + if (vknots != Py_None) { // vknots are given Py::Sequence vknotssq(vknots); index = 1; - for (Py::Sequence::iterator it = vknotssq.begin(); it != vknotssq.end() && index <= occvknots.Length(); ++it) { + for (Py::Sequence::iterator it = vknotssq.begin(); + it != vknotssq.end() && index <= occvknots.Length(); + ++it) { Py::Float knot(*it); occvknots(index++) = knot; } } - else { // knotes are uniformly spaced 0..1 if not given - for (int i=1; i<=occvknots.Length(); i++){ - occvknots.SetValue(i,(double)(i-1)/(occvknots.Length()-1)); + else { // knotes are uniformly spaced 0..1 if not given + for (int i = 1; i <= occvknots.Length(); i++) { + occvknots.SetValue(i, (double)(i - 1) / (occvknots.Length() - 1)); } } - if ((Base::asBoolean(uperiodic) && sum_of_umults != lu) || - (!Base::asBoolean(uperiodic) && sum_of_umults - udegree -1 != lu) || - (Base::asBoolean(vperiodic) && sum_of_vmults != lv) || - (!Base::asBoolean(vperiodic) && sum_of_vmults - vdegree -1 != lv)) { + if ((Base::asBoolean(uperiodic) && sum_of_umults != lu) + || (!Base::asBoolean(uperiodic) && sum_of_umults - udegree - 1 != lu) + || (Base::asBoolean(vperiodic) && sum_of_vmults != lv) + || (!Base::asBoolean(vperiodic) && sum_of_vmults - vdegree - 1 != lv)) { Standard_Failure::Raise("number of poles and sum of mults mismatch"); } // check multiplicity of inner knots - for (Standard_Integer i=2; i < occumults.Length(); i++) { + for (Standard_Integer i = 2; i < occumults.Length(); i++) { if (occumults(i) > udegree) { Standard_Failure::Raise("multiplicity of inner knot higher than degree"); } } - for (Standard_Integer i=2; i < occvmults.Length(); i++) { + for (Standard_Integer i = 2; i < occvmults.Length(); i++) { if (occvmults(i) > vdegree) { Standard_Failure::Raise("multiplicity of inner knot higher than degree"); } } - Handle(Geom_BSplineSurface) spline = new Geom_BSplineSurface(occpoles,occweights, - occuknots,occvknots,occumults,occvmults,udegree,vdegree, + Handle(Geom_BSplineSurface) spline = new Geom_BSplineSurface( + occpoles, + occweights, + occuknots, + occvknots, + occumults, + occvmults, + udegree, + vdegree, Base::asBoolean(uperiodic), - Base::asBoolean(vperiodic)); + Base::asBoolean(vperiodic) + ); if (!spline.IsNull()) { this->getGeomBSplineSurfacePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } - } catch (const Standard_Failure& e) { Standard_CString msg = e.GetMessageString(); - PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); + PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); return nullptr; } } @@ -1522,12 +1729,13 @@ bs = Part.BSplineSurface() bs.buildFromNSections([c, e1, e2]) * \endcode */ -PyObject* BSplineSurfacePy::buildFromNSections(PyObject *args) +PyObject* BSplineSurfacePy::buildFromNSections(PyObject* args) { PyObject* list; PyObject* refSurf = Py_False; - if (!PyArg_ParseTuple(args, "O|O!", &list, &PyBool_Type, &refSurf)) + if (!PyArg_ParseTuple(args, "O|O!", &list, &PyBool_Type, &refSurf)) { return nullptr; + } try { TColGeom_SequenceOfCurve curveSeq; @@ -1542,8 +1750,9 @@ PyObject* BSplineSurfacePy::buildFromNSections(PyObject *args) GeomFill_NSections fillOp(curveSeq); if (Base::asBoolean(refSurf)) { - Handle(Geom_BSplineSurface) ref = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) ref = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); fillOp.SetSurface(ref); } @@ -1555,111 +1764,124 @@ PyObject* BSplineSurfacePy::buildFromNSections(PyObject *args) } catch (const Standard_Failure& e) { Standard_CString msg = e.GetMessageString(); - PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); + PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); return nullptr; } } Py::Long BSplineSurfacePy::getUDegree() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int deg = surf->UDegree(); return Py::Long(deg); } Py::Long BSplineSurfacePy::getVDegree() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int deg = surf->VDegree(); return Py::Long(deg); } Py::Long BSplineSurfacePy::getMaxDegree() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); return Py::Long(surf->MaxDegree()); } Py::Long BSplineSurfacePy::getNbUPoles() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); return Py::Long(surf->NbUPoles()); } Py::Long BSplineSurfacePy::getNbVPoles() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); return Py::Long(surf->NbVPoles()); } Py::Long BSplineSurfacePy::getNbUKnots() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); return Py::Long(surf->NbUKnots()); } Py::Long BSplineSurfacePy::getNbVKnots() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); return Py::Long(surf->NbVKnots()); } Py::Object BSplineSurfacePy::getFirstUKnotIndex() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int index = surf->FirstUKnotIndex(); return Py::Long(index); } Py::Object BSplineSurfacePy::getLastUKnotIndex() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int index = surf->LastUKnotIndex(); return Py::Long(index); } Py::Object BSplineSurfacePy::getFirstVKnotIndex() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int index = surf->FirstVKnotIndex(); return Py::Long(index); } Py::Object BSplineSurfacePy::getLastVKnotIndex() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); int index = surf->LastVKnotIndex(); return Py::Long(index); } Py::List BSplineSurfacePy::getUKnotSequence() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Integer m = 0; if (surf->IsUPeriodic()) { // knots=poles+2*degree-mult(1)+2 - m = surf->NbUPoles() + 2*surf->UDegree() - surf->UMultiplicity(1) + 2; + m = surf->NbUPoles() + 2 * surf->UDegree() - surf->UMultiplicity(1) + 2; } else { - for (int i=1; i<= surf->NbUKnots(); i++) + for (int i = 1; i <= surf->NbUKnots(); i++) { m += surf->UMultiplicity(i); + } } - TColStd_Array1OfReal k(1,m); + TColStd_Array1OfReal k(1, m); surf->UKnotSequence(k); Py::List list; - for (Standard_Integer i=k.Lower(); i<=k.Upper(); i++) { + for (Standard_Integer i = k.Lower(); i <= k.Upper(); i++) { list.append(Py::Float(k(i))); } return list; @@ -1667,39 +1889,43 @@ Py::List BSplineSurfacePy::getUKnotSequence() const Py::List BSplineSurfacePy::getVKnotSequence() const { - Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast( + getGeometryPtr()->handle() + ); Standard_Integer m = 0; if (surf->IsVPeriodic()) { // knots=poles+2*degree-mult(1)+2 - m = surf->NbVPoles() + 2*surf->VDegree() - surf->VMultiplicity(1) + 2; + m = surf->NbVPoles() + 2 * surf->VDegree() - surf->VMultiplicity(1) + 2; } else { - for (int i=1; i<= surf->NbVKnots(); i++) + for (int i = 1; i <= surf->NbVKnots(); i++) { m += surf->VMultiplicity(i); + } } - TColStd_Array1OfReal k(1,m); + TColStd_Array1OfReal k(1, m); surf->VKnotSequence(k); Py::List list; - for (Standard_Integer i=k.Lower(); i<=k.Upper(); i++) { + for (Standard_Integer i = k.Lower(); i <= k.Upper(); i++) { list.append(Py::Float(k(i))); } return list; } -PyObject* BSplineSurfacePy::scaleKnotsToBounds(PyObject *args) +PyObject* BSplineSurfacePy::scaleKnotsToBounds(PyObject* args) { - double u0=0.0; - double u1=1.0; - double v0=0.0; - double v1=1.0; + double u0 = 0.0; + double u1 = 1.0; + double v0 = 0.0; + double v1 = 1.0; - if (!PyArg_ParseTuple(args, "|dddd", &u0, &u1, &v0, &v1)) + if (!PyArg_ParseTuple(args, "|dddd", &u0, &u1, &v0, &v1)) { return nullptr; + } try { if (u0 >= u1 || v0 >= v1) { Standard_Failure::Raise("Bad parameter range"); - return nullptr;; + return nullptr; + ; } GeomBSplineSurface* surf = getGeomBSplineSurfacePtr(); surf->scaleKnotsToBounds(u0, u1, v0, v1); @@ -1707,13 +1933,15 @@ PyObject* BSplineSurfacePy::scaleKnotsToBounds(PyObject *args) } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } } -PyObject *BSplineSurfacePy::getCustomAttributes(const char* attr) const +PyObject* BSplineSurfacePy::getCustomAttributes(const char* attr) const { // for backward compatibility if (strcmp(attr, "setBounds") == 0) { diff --git a/src/Mod/Part/App/BezierCurve.pyi b/src/Mod/Part/App/BezierCurve.pyi index b47c8f224d..2542a3cba0 100644 --- a/src/Mod/Part/App/BezierCurve.pyi +++ b/src/Mod/Part/App/BezierCurve.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from BoundedCurve import BoundedCurve from typing import Final, List - @export( Twin="GeomBezierCurve", TwinPointer="GeomBezierCurve", @@ -165,9 +164,7 @@ class BezierCurve(BoundedCurve): """ ... - def interpolate( - self, constraints: List[List], parameters: List[float] = ... - ) -> None: + def interpolate(self, constraints: List[List], parameters: List[float] = ...) -> None: """ Interpolates a list of constraints. Each constraint is a list of a point and some optional derivatives diff --git a/src/Mod/Part/App/BezierCurvePyImp.cpp b/src/Mod/Part/App/BezierCurvePyImp.cpp index 537f290d6a..80a29325c1 100644 --- a/src/Mod/Part/App/BezierCurvePyImp.cpp +++ b/src/Mod/Part/App/BezierCurvePyImp.cpp @@ -22,13 +22,13 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -47,7 +47,7 @@ std::string BezierCurvePy::representation() const return ""; } -PyObject *BezierCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BezierCurvePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BezierCurvePy and the Twin object return new BezierCurvePy(new GeomBezierCurve); @@ -59,60 +59,60 @@ int BezierCurvePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* BezierCurvePy::isRational(PyObject *args) const +PyObject* BezierCurvePy::isRational(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = curve->IsRational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierCurvePy::isPeriodic(PyObject *args) const +PyObject* BezierCurvePy::isPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = curve->IsPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierCurvePy::isClosed(PyObject *args) const +PyObject* BezierCurvePy::isClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = curve->IsClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierCurvePy::increase(PyObject * args) +PyObject* BezierCurvePy::increase(PyObject* args) { int degree; - if (!PyArg_ParseTuple(args, "i", °ree)) + if (!PyArg_ParseTuple(args, "i", °ree)) { return nullptr; - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + } + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); curve->Increase(degree); Py_Return; } -PyObject* BezierCurvePy::insertPoleAfter(PyObject * args) +PyObject* BezierCurvePy::insertPoleAfter(PyObject* args) { int index; - double weight=1.0; + double weight = 1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) { return nullptr; + } Base::Vector3d vec = static_cast(p)->value(); gp_Pnt pnt(vec.x, vec.y, vec.z); try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - curve->InsertPoleAfter(index,pnt,weight); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + curve->InsertPoleAfter(index, pnt, weight); Py_Return; } catch (Standard_Failure& e) { @@ -121,19 +121,19 @@ PyObject* BezierCurvePy::insertPoleAfter(PyObject * args) } } -PyObject* BezierCurvePy::insertPoleBefore(PyObject * args) +PyObject* BezierCurvePy::insertPoleBefore(PyObject* args) { int index; - double weight=1.0; + double weight = 1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) { return nullptr; + } Base::Vector3d vec = static_cast(p)->value(); gp_Pnt pnt(vec.x, vec.y, vec.z); try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - curve->InsertPoleBefore(index,pnt,weight); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + curve->InsertPoleBefore(index, pnt, weight); Py_Return; } catch (Standard_Failure& e) { @@ -142,14 +142,14 @@ PyObject* BezierCurvePy::insertPoleBefore(PyObject * args) } } -PyObject* BezierCurvePy::removePole(PyObject * args) +PyObject* BezierCurvePy::removePole(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); curve->RemovePole(index); Py_Return; } @@ -159,15 +159,15 @@ PyObject* BezierCurvePy::removePole(PyObject * args) } } -PyObject* BezierCurvePy::segment(PyObject * args) +PyObject* BezierCurvePy::segment(PyObject* args) { - double u1,u2; - if (!PyArg_ParseTuple(args, "dd", &u1,&u2)) + double u1, u2; + if (!PyArg_ParseTuple(args, "dd", &u1, &u2)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - curve->Segment(u1,u2); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + curve->Segment(u1, u2); Py_Return; } catch (Standard_Failure& e) { @@ -176,22 +176,24 @@ PyObject* BezierCurvePy::segment(PyObject * args) } } -PyObject* BezierCurvePy::setPole(PyObject * args) +PyObject* BezierCurvePy::setPole(PyObject* args) { int index; - double weight=-1.0; + double weight = -1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, &(Base::VectorPy::Type), &p, &weight)) { return nullptr; + } Base::Vector3d vec = static_cast(p)->value(); gp_Pnt pnt(vec.x, vec.y, vec.z); try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - if (weight < 0.0) - curve->SetPole(index,pnt); - else - curve->SetPole(index,pnt,weight); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + if (weight < 0.0) { + curve->SetPole(index, pnt); + } + else { + curve->SetPole(index, pnt, weight); + } Py_Return; } catch (Standard_Failure& e) { @@ -200,19 +202,17 @@ PyObject* BezierCurvePy::setPole(PyObject * args) } } -PyObject* BezierCurvePy::getPole(PyObject * args) const +PyObject* BezierCurvePy::getPole(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles(), "Pole index out of range"); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Pole index out of range"); gp_Pnt pnt = curve->Pole(index); - Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d( - pnt.X(), pnt.Y(), pnt.Z())); + Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); return vec; } catch (Standard_Failure& e) { @@ -221,20 +221,19 @@ PyObject* BezierCurvePy::getPole(PyObject * args) const } } -PyObject* BezierCurvePy::getPoles(PyObject * args) const +PyObject* BezierCurvePy::getPoles(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - TColgp_Array1OfPnt p(1,curve->NbPoles()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + TColgp_Array1OfPnt p(1, curve->NbPoles()); curve->Poles(p); Py::List poles; - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { gp_Pnt pnt = p(i); - Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d( - pnt.X(), pnt.Y(), pnt.Z())); + Base::VectorPy* vec = new Base::VectorPy(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); poles.append(Py::asObject(vec)); } return Py::new_reference_to(poles); @@ -245,19 +244,20 @@ PyObject* BezierCurvePy::getPoles(PyObject * args) const } } -PyObject* BezierCurvePy::setPoles(PyObject * args) +PyObject* BezierCurvePy::setPoles(PyObject* args) { PyObject* plist; - if (!PyArg_ParseTuple(args, "O", &plist)) + if (!PyArg_ParseTuple(args, "O", &plist)) { return nullptr; + } try { Py::Sequence list(plist); - TColgp_Array1OfPnt poles(1,list.size()); + TColgp_Array1OfPnt poles(1, list.size()); int index = poles.Lower(); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector v(*it); Base::Vector3d pole = v.toVector(); - poles.SetValue(index++, gp_Pnt(pole.x,pole.y,pole.z)); + poles.SetValue(index++, gp_Pnt(pole.x, pole.y, pole.z)); } Handle(Geom_BezierCurve) bezier = new Geom_BezierCurve(poles); @@ -270,16 +270,16 @@ PyObject* BezierCurvePy::setPoles(PyObject * args) } } -PyObject* BezierCurvePy::setWeight(PyObject * args) +PyObject* BezierCurvePy::setWeight(PyObject* args) { int index; double weight; - if (!PyArg_ParseTuple(args, "id", &index,&weight)) + if (!PyArg_ParseTuple(args, "id", &index, &weight)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - curve->SetWeight(index,weight); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + curve->SetWeight(index, weight); Py_Return; } catch (Standard_Failure& e) { @@ -288,16 +288,15 @@ PyObject* BezierCurvePy::setWeight(PyObject * args) } } -PyObject* BezierCurvePy::getWeight(PyObject * args) const +PyObject* BezierCurvePy::getWeight(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles() , "Weight index out of range"); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Weight index out of range"); double weight = curve->Weight(index); return Py_BuildValue("d", weight); } @@ -307,17 +306,17 @@ PyObject* BezierCurvePy::getWeight(PyObject * args) const } } -PyObject* BezierCurvePy::getWeights(PyObject * args) const +PyObject* BezierCurvePy::getWeights(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array1OfReal w(1,curve->NbPoles()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); + TColStd_Array1OfReal w(1, curve->NbPoles()); curve->Weights(w); Py::List weights; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { weights.append(Py::Float(w(i))); } return Py::new_reference_to(weights); @@ -331,14 +330,14 @@ PyObject* BezierCurvePy::getWeights(PyObject * args) const PyObject* BezierCurvePy::getResolution(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); double utol; - curve->Resolution(tol,utol); - return Py_BuildValue("d",utol); + curve->Resolution(tol, utol); + return Py_BuildValue("d", utol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -347,70 +346,67 @@ PyObject* BezierCurvePy::getResolution(PyObject* args) const } Py::Long BezierCurvePy::getDegree() const { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->Degree()); } Py::Long BezierCurvePy::getMaxDegree() const { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->MaxDegree()); } Py::Long BezierCurvePy::getNbPoles() const { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); return Py::Long(curve->NbPoles()); } Py::Object BezierCurvePy::getStartPoint() const { - Handle(Geom_BezierCurve) c = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) c = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); gp_Pnt pnt = c->StartPoint(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } Py::Object BezierCurvePy::getEndPoint() const { - Handle(Geom_BezierCurve) c = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) c = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); gp_Pnt pnt = c->EndPoint(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } -PyObject* BezierCurvePy::interpolate(PyObject * args) +PyObject* BezierCurvePy::interpolate(PyObject* args) { PyObject* obj; - PyObject* par=nullptr; - if (!PyArg_ParseTuple(args, "O|O", &obj, &par)) + PyObject* par = nullptr; + if (!PyArg_ParseTuple(args, "O|O", &obj, &par)) { return nullptr; + } try { - Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast(getGeometryPtr()->handle()); Py::Sequence constraints(obj); int nb_pts = constraints.size(); - if (nb_pts < 2) + if (nb_pts < 2) { Standard_Failure::Raise("not enough points given"); + } TColStd_Array1OfReal params(1, nb_pts); if (par) { Py::Sequence plist(par); int param_size = plist.size(); - if (param_size != nb_pts) + if (param_size != nb_pts) { Standard_Failure::Raise("number of points and parameters don't match"); - int idx=1; + } + int idx = 1; for (Py::Sequence::iterator pit = plist.begin(); pit != plist.end(); ++pit) { Py::Float val(*pit); params(idx++) = (double)val; } } else { - for (int idx=0; idx curve->MaxDegree()) + if (num_poles > curve->MaxDegree()) { Standard_Failure::Raise("number of constraints exceeds bezier curve capacity"); + } // create a bezier-type knot sequence - TColStd_Array1OfReal knots(1, 2*num_poles); - for (int idx=1; idx<=num_poles; ++idx) { + TColStd_Array1OfReal knots(1, 2 * num_poles); + for (int idx = 1; idx <= num_poles; ++idx) { knots(idx) = params(1); - knots(num_poles+idx) = params(nb_pts); + knots(num_poles + idx) = params(nb_pts); } math_Matrix OCCmatrix(1, num_poles, 1, num_poles, 0.0); math_Vector res_x(1, num_poles, 0.0); @@ -437,7 +434,15 @@ PyObject* BezierCurvePy::interpolate(PyObject * args) Py::Sequence row(*it1); math_Matrix bezier_eval(1, row.size(), 1, num_poles, 0.0); Standard_Integer first_non_zero; - BSplCLib::EvalBsplineBasis(row.size()-1, num_poles, knots, params(cons_idx), first_non_zero, bezier_eval, Standard_False); + BSplCLib::EvalBsplineBasis( + row.size() - 1, + num_poles, + knots, + params(cons_idx), + first_non_zero, + bezier_eval, + Standard_False + ); int idx2 = 1; for (Py::Sequence::iterator it2 = row.begin(); it2 != row.end(); ++it2) { OCCmatrix.SetRow(row_idx, bezier_eval.Row(idx2)); @@ -453,18 +458,21 @@ PyObject* BezierCurvePy::interpolate(PyObject * args) } math_Gauss gauss(OCCmatrix); gauss.Solve(res_x); - if (!gauss.IsDone()) + if (!gauss.IsDone()) { Standard_Failure::Raise("Failed to solve equations"); + } gauss.Solve(res_y); - if (!gauss.IsDone()) + if (!gauss.IsDone()) { Standard_Failure::Raise("Failed to solve equations"); + } gauss.Solve(res_z); - if (!gauss.IsDone()) + if (!gauss.IsDone()) { Standard_Failure::Raise("Failed to solve equations"); + } - TColgp_Array1OfPnt poles(1,num_poles); - for (int idx=1; idx<=num_poles; ++idx) { - poles.SetValue(idx, gp_Pnt(res_x(idx),res_y(idx),res_z(idx))); + TColgp_Array1OfPnt poles(1, num_poles); + for (int idx = 1; idx <= num_poles; ++idx) { + poles.SetValue(idx, gp_Pnt(res_x(idx), res_y(idx), res_z(idx))); } Handle(Geom_BezierCurve) bezier = new Geom_BezierCurve(poles); @@ -477,7 +485,7 @@ PyObject* BezierCurvePy::interpolate(PyObject * args) } } -PyObject *BezierCurvePy::getCustomAttributes(const char* /*attr*/) const +PyObject* BezierCurvePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/BezierSurface.pyi b/src/Mod/Part/App/BezierSurface.pyi index e4d0db0c1a..7d19718587 100644 --- a/src/Mod/Part/App/BezierSurface.pyi +++ b/src/Mod/Part/App/BezierSurface.pyi @@ -8,7 +8,6 @@ from Base.Metadata import ( from GeometrySurface import GeometrySurface from typing import Final, Tuple - @export( Twin="GeomBezierSurface", TwinPointer="GeomBezierSurface", diff --git a/src/Mod/Part/App/BezierSurfacePyImp.cpp b/src/Mod/Part/App/BezierSurfacePyImp.cpp index 14b4580a3c..ff4a81b46f 100644 --- a/src/Mod/Part/App/BezierSurfacePyImp.cpp +++ b/src/Mod/Part/App/BezierSurfacePyImp.cpp @@ -22,11 +22,11 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -46,7 +46,7 @@ std::string BezierSurfacePy::representation() const return ""; } -PyObject *BezierSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BezierSurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BezierSurfacePy and the Twin object return new BezierSurfacePy(new GeomBezierSurface); @@ -58,97 +58,99 @@ int BezierSurfacePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* BezierSurfacePy::bounds(PyObject *args) const +PyObject* BezierSurfacePy::bounds(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Py::Tuple bound(4); - Standard_Real u1,u2,v1,v2; - surf->Bounds(u1,u2,v1,v2); - bound.setItem(0,Py::Float(u1)); - bound.setItem(1,Py::Float(u2)); - bound.setItem(2,Py::Float(v1)); - bound.setItem(3,Py::Float(v2)); + Standard_Real u1, u2, v1, v2; + surf->Bounds(u1, u2, v1, v2); + bound.setItem(0, Py::Float(u1)); + bound.setItem(1, Py::Float(u2)); + bound.setItem(2, Py::Float(v1)); + bound.setItem(3, Py::Float(v2)); return Py::new_reference_to(bound); } -PyObject* BezierSurfacePy::isURational(PyObject *args) const +PyObject* BezierSurfacePy::isURational(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsURational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierSurfacePy::isVRational(PyObject *args) const +PyObject* BezierSurfacePy::isVRational(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsVRational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierSurfacePy::isUPeriodic(PyObject *args) const +PyObject* BezierSurfacePy::isUPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsUPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierSurfacePy::isVPeriodic(PyObject *args) const +PyObject* BezierSurfacePy::isVPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsVPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierSurfacePy::isUClosed(PyObject *args) const +PyObject* BezierSurfacePy::isUClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsUClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierSurfacePy::isVClosed(PyObject *args) const +PyObject* BezierSurfacePy::isVClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsVPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierSurfacePy::increase(PyObject *args) +PyObject* BezierSurfacePy::increase(PyObject* args) { - int udegree,vdegree; - if (!PyArg_ParseTuple(args, "ii", &udegree, &vdegree)) + int udegree, vdegree; + if (!PyArg_ParseTuple(args, "ii", &udegree, &vdegree)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->Increase(udegree, vdegree); Py_Return; } @@ -159,32 +161,34 @@ PyObject* BezierSurfacePy::increase(PyObject *args) } } -PyObject* BezierSurfacePy::insertPoleColAfter(PyObject *args) +PyObject* BezierSurfacePy::insertPoleColAfter(PyObject* args) { int vindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&vindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &vindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->InsertPoleColAfter(vindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -199,32 +203,34 @@ PyObject* BezierSurfacePy::insertPoleColAfter(PyObject *args) } } -PyObject* BezierSurfacePy::insertPoleRowAfter(PyObject *args) +PyObject* BezierSurfacePy::insertPoleRowAfter(PyObject* args) { int uindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&uindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &uindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->InsertPoleRowAfter(uindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -239,32 +245,34 @@ PyObject* BezierSurfacePy::insertPoleRowAfter(PyObject *args) } } -PyObject* BezierSurfacePy::insertPoleColBefore(PyObject *args) +PyObject* BezierSurfacePy::insertPoleColBefore(PyObject* args) { int vindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&vindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &vindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->InsertPoleColBefore(vindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -279,32 +287,34 @@ PyObject* BezierSurfacePy::insertPoleColBefore(PyObject *args) } } -PyObject* BezierSurfacePy::insertPoleRowBefore(PyObject *args) +PyObject* BezierSurfacePy::insertPoleRowBefore(PyObject* args) { int uindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&uindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &uindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->InsertPoleRowBefore(uindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -319,14 +329,16 @@ PyObject* BezierSurfacePy::insertPoleRowBefore(PyObject *args) } } -PyObject* BezierSurfacePy::removePoleCol(PyObject *args) +PyObject* BezierSurfacePy::removePoleCol(PyObject* args) { int vindex; - if (!PyArg_ParseTuple(args, "i",&vindex)) + if (!PyArg_ParseTuple(args, "i", &vindex)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->RemovePoleCol(vindex); Py_Return; } @@ -336,14 +348,16 @@ PyObject* BezierSurfacePy::removePoleCol(PyObject *args) } } -PyObject* BezierSurfacePy::removePoleRow(PyObject *args) +PyObject* BezierSurfacePy::removePoleRow(PyObject* args) { int uindex; - if (!PyArg_ParseTuple(args, "i",&uindex)) + if (!PyArg_ParseTuple(args, "i", &uindex)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->RemovePoleRow(uindex); Py_Return; } @@ -353,15 +367,17 @@ PyObject* BezierSurfacePy::removePoleRow(PyObject *args) } } -PyObject* BezierSurfacePy::segment(PyObject *args) +PyObject* BezierSurfacePy::segment(PyObject* args) { - Standard_Real u1,u2,v1,v2; - if (!PyArg_ParseTuple(args, "dddd",&u1,&u2,&v1,&v2)) + Standard_Real u1, u2, v1, v2; + if (!PyArg_ParseTuple(args, "dddd", &u1, &u2, &v1, &v2)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - surf->Segment(u1,u2,v1,v2); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + surf->Segment(u1, u2, v1, v2); Py_Return; } catch (Standard_Failure& e) { @@ -370,21 +386,25 @@ PyObject* BezierSurfacePy::segment(PyObject *args) } } -PyObject* BezierSurfacePy::setPole(PyObject *args) +PyObject* BezierSurfacePy::setPole(PyObject* args) { - int uindex,vindex; + int uindex, vindex; PyObject* obj; - double weight=0.0; - if (!PyArg_ParseTuple(args, "iiO!|d",&uindex,&vindex,&(Base::VectorPy::Type),&obj,&weight)) + double weight = 0.0; + if (!PyArg_ParseTuple(args, "iiO!|d", &uindex, &vindex, &(Base::VectorPy::Type), &obj, &weight)) { return nullptr; + } try { Base::Vector3d pole = static_cast(obj)->value(); - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - if (weight <= gp::Resolution()) - surf->SetPole(uindex,vindex,gp_Pnt(pole.x,pole.y,pole.z)); - else - surf->SetPole(uindex,vindex,gp_Pnt(pole.x,pole.y,pole.z),weight); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + if (weight <= gp::Resolution()) { + surf->SetPole(uindex, vindex, gp_Pnt(pole.x, pole.y, pole.z)); + } + else { + surf->SetPole(uindex, vindex, gp_Pnt(pole.x, pole.y, pole.z), weight); + } Py_Return; } catch (Standard_Failure& e) { @@ -393,32 +413,34 @@ PyObject* BezierSurfacePy::setPole(PyObject *args) } } -PyObject* BezierSurfacePy::setPoleCol(PyObject *args) +PyObject* BezierSurfacePy::setPoleCol(PyObject* args) { int vindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&vindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &vindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->SetPoleCol(vindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -433,32 +455,34 @@ PyObject* BezierSurfacePy::setPoleCol(PyObject *args) } } -PyObject* BezierSurfacePy::setPoleRow(PyObject *args) +PyObject* BezierSurfacePy::setPoleRow(PyObject* args) { int uindex; PyObject* obj; - PyObject* obj2=nullptr; - if (!PyArg_ParseTuple(args, "iO|O",&uindex,&obj,&obj2)) + PyObject* obj2 = nullptr; + if (!PyArg_ParseTuple(args, "iO|O", &uindex, &obj, &obj2)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt poles(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Vector p(*it); Base::Vector3d v = p.toVector(); - poles(index++) = gp_Pnt(v.x,v.y,v.z); + poles(index++) = gp_Pnt(v.x, v.y, v.z); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); if (!obj2) { surf->SetPoleRow(uindex, poles); } else { Py::Sequence list(obj2); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } @@ -473,19 +497,22 @@ PyObject* BezierSurfacePy::setPoleRow(PyObject *args) } } -PyObject* BezierSurfacePy::getPole(PyObject *args) const +PyObject* BezierSurfacePy::getPole(PyObject* args) const { - int uindex,vindex; - if (!PyArg_ParseTuple(args, "ii",&uindex,&vindex)) + int uindex, vindex; + if (!PyArg_ParseTuple(args, "ii", &uindex, &vindex)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (uindex < 1 || uindex > surf->NbUPoles() || - vindex < 1 || vindex > surf->NbVPoles(), "Pole index out of range"); - gp_Pnt p = surf->Pole(uindex,vindex); - return new Base::VectorPy(Base::Vector3d(p.X(),p.Y(),p.Z())); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + Standard_OutOfRange_Raise_if( + uindex < 1 || uindex > surf->NbUPoles() || vindex < 1 || vindex > surf->NbVPoles(), + "Pole index out of range" + ); + gp_Pnt p = surf->Pole(uindex, vindex); + return new Base::VectorPy(Base::Vector3d(p.X(), p.Y(), p.Z())); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -493,22 +520,25 @@ PyObject* BezierSurfacePy::getPole(PyObject *args) const } } -PyObject* BezierSurfacePy::getPoles(PyObject *args) const +PyObject* BezierSurfacePy::getPoles(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - TColgp_Array2OfPnt p(1,surf->NbUPoles(),1,surf->NbVPoles()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColgp_Array2OfPnt p(1, surf->NbUPoles(), 1, surf->NbVPoles()); surf->Poles(p); Py::List poles; - for (Standard_Integer i=p.LowerRow(); i<=p.UpperRow(); i++) { + for (Standard_Integer i = p.LowerRow(); i <= p.UpperRow(); i++) { Py::List row; - for (Standard_Integer j=p.LowerCol(); j<=p.UpperCol(); j++) { - const gp_Pnt& pole = p(i,j); - row.append(Py::asObject(new Base::VectorPy( - Base::Vector3d(pole.X(),pole.Y(),pole.Z())))); + for (Standard_Integer j = p.LowerCol(); j <= p.UpperCol(); j++) { + const gp_Pnt& pole = p(i, j); + row.append( + Py::asObject(new Base::VectorPy(Base::Vector3d(pole.X(), pole.Y(), pole.Z()))) + ); } poles.append(row); } @@ -520,16 +550,18 @@ PyObject* BezierSurfacePy::getPoles(PyObject *args) const } } -PyObject* BezierSurfacePy::setWeight(PyObject *args) +PyObject* BezierSurfacePy::setWeight(PyObject* args) { - int uindex,vindex; + int uindex, vindex; double weight; - if (!PyArg_ParseTuple(args, "iid",&uindex,&vindex,&weight)) + if (!PyArg_ParseTuple(args, "iid", &uindex, &vindex, &weight)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - surf->SetWeight(uindex,vindex,weight); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + surf->SetWeight(uindex, vindex, weight); Py_Return; } catch (Standard_Failure& e) { @@ -538,22 +570,24 @@ PyObject* BezierSurfacePy::setWeight(PyObject *args) } } -PyObject* BezierSurfacePy::setWeightCol(PyObject *args) +PyObject* BezierSurfacePy::setWeightCol(PyObject* args) { int vindex; PyObject* obj; - if (!PyArg_ParseTuple(args, "iO",&vindex,&obj)) + if (!PyArg_ParseTuple(args, "iO", &vindex, &obj)) { return nullptr; + } try { Py::Sequence list(obj); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetWeightCol(vindex, weights); Py_Return; } @@ -563,22 +597,24 @@ PyObject* BezierSurfacePy::setWeightCol(PyObject *args) } } -PyObject* BezierSurfacePy::setWeightRow(PyObject *args) +PyObject* BezierSurfacePy::setWeightRow(PyObject* args) { int uindex; PyObject* obj; - if (!PyArg_ParseTuple(args, "iO",&uindex,&obj)) + if (!PyArg_ParseTuple(args, "iO", &uindex, &obj)) { return nullptr; + } try { Py::Sequence list(obj); TColStd_Array1OfReal weights(1, list.size()); - int index=1; + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { weights(index++) = (double)Py::Float(*it); } - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); surf->SetWeightRow(uindex, weights); Py_Return; } @@ -588,18 +624,21 @@ PyObject* BezierSurfacePy::setWeightRow(PyObject *args) } } -PyObject* BezierSurfacePy::getWeight(PyObject *args) const +PyObject* BezierSurfacePy::getWeight(PyObject* args) const { - int uindex,vindex; - if (!PyArg_ParseTuple(args, "ii",&uindex,&vindex)) + int uindex, vindex; + if (!PyArg_ParseTuple(args, "ii", &uindex, &vindex)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - Standard_OutOfRange_Raise_if - (uindex < 1 || uindex > surf->NbUPoles() || - vindex < 1 || vindex > surf->NbVPoles(), "Weight index out of range"); - double w = surf->Weight(uindex,vindex); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + Standard_OutOfRange_Raise_if( + uindex < 1 || uindex > surf->NbUPoles() || vindex < 1 || vindex > surf->NbVPoles(), + "Weight index out of range" + ); + double w = surf->Weight(uindex, vindex); return Py_BuildValue("d", w); } catch (Standard_Failure& e) { @@ -608,20 +647,22 @@ PyObject* BezierSurfacePy::getWeight(PyObject *args) const } } -PyObject* BezierSurfacePy::getWeights(PyObject *args) const +PyObject* BezierSurfacePy::getWeights(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - TColStd_Array2OfReal w(1,surf->NbUPoles(),1,surf->NbVPoles()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + TColStd_Array2OfReal w(1, surf->NbUPoles(), 1, surf->NbVPoles()); surf->Weights(w); Py::List weights; - for (Standard_Integer i=w.LowerRow(); i<=w.UpperRow(); i++) { + for (Standard_Integer i = w.LowerRow(); i <= w.UpperRow(); i++) { Py::List row; - for (Standard_Integer j=w.LowerCol(); j<=w.UpperCol(); j++) { - row.append(Py::Float(w(i,j))); + for (Standard_Integer j = w.LowerCol(); j <= w.UpperCol(); j++) { + row.append(Py::Float(w(i, j))); } weights.append(row); } @@ -633,17 +674,19 @@ PyObject* BezierSurfacePy::getWeights(PyObject *args) const } } -PyObject* BezierSurfacePy::getResolution(PyObject *args) const +PyObject* BezierSurfacePy::getResolution(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); double utol, vtol; - surf->Resolution(tol,utol,vtol); - return Py_BuildValue("(dd)",utol,vtol); + surf->Resolution(tol, utol, vtol); + return Py_BuildValue("(dd)", utol, vtol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -651,15 +694,17 @@ PyObject* BezierSurfacePy::getResolution(PyObject *args) const } } -PyObject* BezierSurfacePy::exchangeUV(PyObject *args) +PyObject* BezierSurfacePy::exchangeUV(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); - //FIXME: Crashes + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast( + getGeometryPtr()->handle() + ); + // FIXME: Crashes surf->ExchangeUV(); Py_Return; } @@ -671,40 +716,35 @@ PyObject* BezierSurfacePy::exchangeUV(PyObject *args) Py::Long BezierSurfacePy::getUDegree() const { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); return Py::Long(surf->UDegree()); } Py::Long BezierSurfacePy::getVDegree() const { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); return Py::Long(surf->VDegree()); } Py::Long BezierSurfacePy::getMaxDegree() const { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); return Py::Long(surf->MaxDegree()); } Py::Long BezierSurfacePy::getNbUPoles() const { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); return Py::Long(surf->NbUPoles()); } Py::Long BezierSurfacePy::getNbVPoles() const { - Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast(getGeometryPtr()->handle()); return Py::Long(surf->NbVPoles()); } -PyObject *BezierSurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* BezierSurfacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/BodyBase.cpp b/src/Mod/Part/App/BodyBase.cpp index 911f043ebe..cb91bf6e34 100644 --- a/src/Mod/Part/App/BodyBase.cpp +++ b/src/Mod/Part/App/BodyBase.cpp @@ -29,16 +29,17 @@ #include "BodyBasePy.h" -namespace Part { +namespace Part +{ PROPERTY_SOURCE_WITH_EXTENSIONS(Part::BodyBase, Part::Feature) BodyBase::BodyBase() { - ADD_PROPERTY(Tip , (nullptr) ); + ADD_PROPERTY(Tip, (nullptr)); Tip.setScope(App::LinkScope::Child); - ADD_PROPERTY(BaseFeature , (nullptr) ); + ADD_PROPERTY(BaseFeature, (nullptr)); App::OriginGroupExtension::initExtension(this); } @@ -50,23 +51,25 @@ BodyBase* BodyBase::findBodyOf(const App::DocumentObject* f) std::vector bodies = doc->getObjectsOfType(BodyBase::getClassTypeId()); for (auto it : bodies) { BodyBase* body = static_cast(it); - if (body->hasObject(f)) + if (body->hasObject(f)) { return body; + } } } return nullptr; } -bool BodyBase::isAfter(const App::DocumentObject *feature, const App::DocumentObject* target) const { - assert (feature); +bool BodyBase::isAfter(const App::DocumentObject* feature, const App::DocumentObject* target) const +{ + assert(feature); if (feature == target) { return false; } - if (!target || target == BaseFeature.getValue() ) { - return hasObject (feature); + if (!target || target == BaseFeature.getValue()) { + return hasObject(feature); } const std::vector& features = Group.getValues(); @@ -74,30 +77,30 @@ bool BodyBase::isAfter(const App::DocumentObject *feature, const App::DocumentOb const auto targetIt = std::ranges::find(features, target); return featureIt == features.end() ? false : featureIt > targetIt; - } - -void BodyBase::onBeforeChange (const App::Property* prop) { - - //Tip can't point outside the body, hence no base feature tip - /*// If we are changing the base feature and tip point to it reset it - if ( prop == &BaseFeature && BaseFeature.getValue() == Tip.getValue() && BaseFeature.getValue() ) { - Tip.setValue( nullptr ); - }*/ - Part::Feature::onBeforeChange ( prop ); } -void BodyBase::onChanged (const App::Property* prop) { - //Tip can't point outside the body, hence no base feature tip +void BodyBase::onBeforeChange(const App::Property* prop) +{ + + // Tip can't point outside the body, hence no base feature tip + /*// If we are changing the base feature and tip point to it reset it + if ( prop == &BaseFeature && BaseFeature.getValue() == Tip.getValue() && BaseFeature.getValue() + ) { Tip.setValue( nullptr ); + }*/ + Part::Feature::onBeforeChange(prop); +} + +void BodyBase::onChanged(const App::Property* prop) +{ + // Tip can't point outside the body, hence no base feature tip /*// If the tip is zero and we are adding a base feature to the body set it to be the tip if ( prop == &BaseFeature && !Tip.getValue() && BaseFeature.getValue() ) { Tip.setValue( BaseFeature.getValue () ); }*/ - Part::Feature::onChanged ( prop ); + Part::Feature::onChanged(prop); } -void BodyBase::handleChangedPropertyName(Base::XMLReader &reader, - const char * TypeName, - const char *PropName) +void BodyBase::handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, const char* PropName) { // The App::PropertyLinkList property was Model in the past (#0002642) Base::Type type = Base::Type::fromName(TypeName); @@ -111,11 +114,11 @@ void BodyBase::handleChangedPropertyName(Base::XMLReader &reader, PyObject* BodyBase::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new BodyBasePy(this),true); + PythonObject = Py::Object(new BodyBasePy(this), true); } return Py::new_reference_to(PythonObject); } -} /* Part */ +} // namespace Part diff --git a/src/Mod/Part/App/BodyBase.h b/src/Mod/Part/App/BodyBase.h index 9bfc9281b2..5d9bff79ec 100644 --- a/src/Mod/Part/App/BodyBase.h +++ b/src/Mod/Part/App/BodyBase.h @@ -41,7 +41,7 @@ namespace Part * in edit or active on a workbench, the body shows only the * resulting shape to the outside (Tip link). */ -class PartExport BodyBase : public Part::Feature, public App::OriginGroupExtension +class PartExport BodyBase: public Part::Feature, public App::OriginGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::BodyBase); @@ -61,17 +61,18 @@ public: App::PropertyLink BaseFeature; /// Returns all Group objects prepanded by BaseFeature (if any) - std::vector getFullModel () { - std::vector rv; - if ( BaseFeature.getValue () ) { - rv.push_back ( BaseFeature.getValue () ); + std::vector getFullModel() + { + std::vector rv; + if (BaseFeature.getValue()) { + rv.push_back(BaseFeature.getValue()); } - std::copy ( Group.getValues ().begin (), Group.getValues ().end (), std::back_inserter (rv) ); + std::copy(Group.getValues().begin(), Group.getValues().end(), std::back_inserter(rv)); return rv; } /// Return true if the feature belongs to the body and is located after the target - bool isAfter(const App::DocumentObject *feature, const App::DocumentObject *target) const; + bool isAfter(const App::DocumentObject* feature, const App::DocumentObject* target) const; /** * Return the body which this feature belongs too, or NULL. @@ -85,16 +86,17 @@ public: protected: /// If BaseFeature is getting changed and Tip points to it reset the Tip - void onBeforeChange (const App::Property* prop) override; + void onBeforeChange(const App::Property* prop) override; /// If BaseFeature is set and Tip is null set the Tip to it - void onChanged (const App::Property* prop) override; - void handleChangedPropertyName(Base::XMLReader &reader, - const char * TypeName, - const char *PropName) override; - + void onChanged(const App::Property* prop) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; }; -} //namespace Part +} // namespace Part -#endif // PART_BodyBase_H +#endif // PART_BodyBase_H diff --git a/src/Mod/Part/App/BodyBase.pyi b/src/Mod/Part/App/BodyBase.pyi index 668fafddf1..d4da3c618e 100644 --- a/src/Mod/Part/App/BodyBase.pyi +++ b/src/Mod/Part/App/BodyBase.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export, constmethod from PartFeature import PartFeature - @export( Twin="BodyBase", TwinPointer="BodyBase", diff --git a/src/Mod/Part/App/BodyBasePyImp.cpp b/src/Mod/Part/App/BodyBasePyImp.cpp index 8463832a4a..29ffd518ff 100644 --- a/src/Mod/Part/App/BodyBasePyImp.cpp +++ b/src/Mod/Part/App/BodyBasePyImp.cpp @@ -37,7 +37,7 @@ std::string BodyBasePy::representation() const return {""}; } -PyObject *BodyBasePy::getCustomAttributes(const char* /*attr*/) const +PyObject* BodyBasePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -46,5 +46,3 @@ int BodyBasePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Mod/Part/App/BoundedCurve.pyi b/src/Mod/Part/App/BoundedCurve.pyi index 205bfff72e..a4235a85e1 100644 --- a/src/Mod/Part/App/BoundedCurve.pyi +++ b/src/Mod/Part/App/BoundedCurve.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from GeometryCurve import GeometryCurve from typing import Any, Final - @export( Twin="GeomBoundedCurve", TwinPointer="GeomBoundedCurve", diff --git a/src/Mod/Part/App/BoundedCurvePyImp.cpp b/src/Mod/Part/App/BoundedCurvePyImp.cpp index 82f4fc664c..089f69885d 100644 --- a/src/Mod/Part/App/BoundedCurvePyImp.cpp +++ b/src/Mod/Part/App/BoundedCurvePyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -39,11 +39,13 @@ std::string BoundedCurvePy::representation() const return ""; } -PyObject *BoundedCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BoundedCurvePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'BoundedCurve'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'BoundedCurve'." + ); return nullptr; } @@ -63,7 +65,7 @@ Py::Object BoundedCurvePy::getEndPoint() const return Py::Vector(getGeomBoundedCurvePtr()->getEndPoint()); } -PyObject *BoundedCurvePy::getCustomAttributes(const char* /*attr*/) const +PyObject* BoundedCurvePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ChFi2d/ChFi2d_AnaFilletAlgoPyImp.cpp b/src/Mod/Part/App/ChFi2d/ChFi2d_AnaFilletAlgoPyImp.cpp index 78fea2b671..8b096b3965 100644 --- a/src/Mod/Part/App/ChFi2d/ChFi2d_AnaFilletAlgoPyImp.cpp +++ b/src/Mod/Part/App/ChFi2d/ChFi2d_AnaFilletAlgoPyImp.cpp @@ -24,9 +24,9 @@ #include -# include -# include -# include +#include +#include +#include #include "ChFi2d/ChFi2d_AnaFilletAlgoPy.h" @@ -38,7 +38,7 @@ using namespace Part; -PyObject *ChFi2d_AnaFilletAlgoPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ChFi2d_AnaFilletAlgoPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ChFi2d_AnaFilletAlgoPy and the Twin object return new ChFi2d_AnaFilletAlgoPy(new ChFi2d_AnaFilletAlgo); @@ -47,15 +47,18 @@ PyObject *ChFi2d_AnaFilletAlgoPy::PyMake(struct _typeobject *, PyObject *, PyObj // constructor method int ChFi2d_AnaFilletAlgoPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - if (PyArg_ParseTuple(args, "")) + if (PyArg_ParseTuple(args, "")) { return 0; + } PyErr_Clear(); PyObject* wire; PyObject* plane; if (PyArg_ParseTuple(args, "O!O!", &TopoShapeWirePy::Type, &wire, &PlanePy::Type, &plane)) { TopoDS_Shape shape = static_cast(wire)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_AnaFilletAlgoPtr()->Init(TopoDS::Wire(shape), hPlane->Pln()); return 0; } @@ -63,20 +66,32 @@ int ChFi2d_AnaFilletAlgoPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2, - &PlanePy::Type, &plane)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge1, + &TopoShapeEdgePy::Type, + &edge2, + &PlanePy::Type, + &plane + )) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_AnaFilletAlgoPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2), hPlane->Pln()); return 0; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- AnaFilletAlgo()\n" - "-- AnaFilletAlgo(wire, plane)" - "-- AnaFilletAlgo(edge, edge, plane)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- AnaFilletAlgo()\n" + "-- AnaFilletAlgo(wire, plane)" + "-- AnaFilletAlgo(edge, edge, plane)\n" + ); return -1; } @@ -86,13 +101,15 @@ std::string ChFi2d_AnaFilletAlgoPy::representation() const return {""}; } -PyObject* ChFi2d_AnaFilletAlgoPy::init(PyObject *args) +PyObject* ChFi2d_AnaFilletAlgoPy::init(PyObject* args) { PyObject* wire; PyObject* plane; if (PyArg_ParseTuple(args, "O!O!", &TopoShapeWirePy::Type, &wire, &PlanePy::Type, &plane)) { TopoDS_Shape shape = static_cast(wire)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_AnaFilletAlgoPtr()->Init(TopoDS::Wire(shape), hPlane->Pln()); Py_Return; } @@ -100,27 +117,40 @@ PyObject* ChFi2d_AnaFilletAlgoPy::init(PyObject *args) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2, - &PlanePy::Type, &plane)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge1, + &TopoShapeEdgePy::Type, + &edge2, + &PlanePy::Type, + &plane + )) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_AnaFilletAlgoPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2), hPlane->Pln()); Py_Return; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- init(wire, plane)" - "-- init(edge, edge, plane)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- init(wire, plane)" + "-- init(edge, edge, plane)\n" + ); return nullptr; } -PyObject* ChFi2d_AnaFilletAlgoPy::perform(PyObject *args) +PyObject* ChFi2d_AnaFilletAlgoPy::perform(PyObject* args) { double radius; - if (!PyArg_ParseTuple(args, "d", &radius)) + if (!PyArg_ParseTuple(args, "d", &radius)) { return nullptr; + } try { bool ok = getChFi2d_AnaFilletAlgoPtr()->Perform(radius); @@ -132,18 +162,21 @@ PyObject* ChFi2d_AnaFilletAlgoPy::perform(PyObject *args) } } -PyObject* ChFi2d_AnaFilletAlgoPy::result(PyObject *args) +PyObject* ChFi2d_AnaFilletAlgoPy::result(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { TopoDS_Edge theEdge1, theEdge2; TopoDS_Shape res_edge = getChFi2d_AnaFilletAlgoPtr()->Result(theEdge1, theEdge2); - Py::TupleN tuple(Py::asObject(TopoShape(res_edge).getPyObject()), - Py::asObject(TopoShape(theEdge1).getPyObject()), - Py::asObject(TopoShape(theEdge2).getPyObject())); + Py::TupleN tuple( + Py::asObject(TopoShape(res_edge).getPyObject()), + Py::asObject(TopoShape(theEdge1).getPyObject()), + Py::asObject(TopoShape(theEdge2).getPyObject()) + ); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { @@ -152,7 +185,7 @@ PyObject* ChFi2d_AnaFilletAlgoPy::result(PyObject *args) } } -PyObject *ChFi2d_AnaFilletAlgoPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ChFi2d_AnaFilletAlgoPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ChFi2d/ChFi2d_ChamferAPIPyImp.cpp b/src/Mod/Part/App/ChFi2d/ChFi2d_ChamferAPIPyImp.cpp index 633c822411..bd6d0a2275 100644 --- a/src/Mod/Part/App/ChFi2d/ChFi2d_ChamferAPIPyImp.cpp +++ b/src/Mod/Part/App/ChFi2d/ChFi2d_ChamferAPIPyImp.cpp @@ -24,9 +24,9 @@ #include -# include -# include -# include +#include +#include +#include #include "ChFi2d/ChFi2d_ChamferAPIPy.h" @@ -37,7 +37,7 @@ using namespace Part; -PyObject *ChFi2d_ChamferAPIPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ChFi2d_ChamferAPIPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ChFi2d_ChamferAPIPy and the Twin object return new ChFi2d_ChamferAPIPy(new ChFi2d_ChamferAPI); @@ -59,18 +59,20 @@ int ChFi2d_ChamferAPIPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2)) { + if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge1, &TopoShapeEdgePy::Type, &edge2)) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); getChFi2d_ChamferAPIPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2)); return 0; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- ChamferAPI()\n" - "-- ChamferAPI(wire)" - "-- ChamferAPI(edge, edge)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- ChamferAPI()\n" + "-- ChamferAPI(wire)" + "-- ChamferAPI(edge, edge)\n" + ); return -1; } @@ -80,7 +82,7 @@ std::string ChFi2d_ChamferAPIPy::representation() const return {""}; } -PyObject* ChFi2d_ChamferAPIPy::init(PyObject *args) +PyObject* ChFi2d_ChamferAPIPy::init(PyObject* args) { PyObject* wire; if (PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) { @@ -92,24 +94,27 @@ PyObject* ChFi2d_ChamferAPIPy::init(PyObject *args) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2)) { + if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge1, &TopoShapeEdgePy::Type, &edge2)) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); getChFi2d_ChamferAPIPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2)); Py_Return; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- init(wire)" - "-- init(edge, edge)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- init(wire)" + "-- init(edge, edge)\n" + ); return nullptr; } -PyObject* ChFi2d_ChamferAPIPy::perform(PyObject *args) +PyObject* ChFi2d_ChamferAPIPy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { bool ok = getChFi2d_ChamferAPIPtr()->Perform(); @@ -121,19 +126,22 @@ PyObject* ChFi2d_ChamferAPIPy::perform(PyObject *args) } } -PyObject* ChFi2d_ChamferAPIPy::result(PyObject *args) +PyObject* ChFi2d_ChamferAPIPy::result(PyObject* args) { double length1, length2; - if (!PyArg_ParseTuple(args, "dd", &length1, &length2)) + if (!PyArg_ParseTuple(args, "dd", &length1, &length2)) { return nullptr; + } try { TopoDS_Edge theEdge1, theEdge2; TopoDS_Shape res_edge = getChFi2d_ChamferAPIPtr()->Result(theEdge1, theEdge2, length1, length2); - Py::TupleN tuple(Py::asObject(TopoShape(res_edge).getPyObject()), - Py::asObject(TopoShape(theEdge1).getPyObject()), - Py::asObject(TopoShape(theEdge2).getPyObject())); + Py::TupleN tuple( + Py::asObject(TopoShape(res_edge).getPyObject()), + Py::asObject(TopoShape(theEdge1).getPyObject()), + Py::asObject(TopoShape(theEdge2).getPyObject()) + ); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { @@ -142,7 +150,7 @@ PyObject* ChFi2d_ChamferAPIPy::result(PyObject *args) } } -PyObject *ChFi2d_ChamferAPIPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ChFi2d_ChamferAPIPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPI.pyi b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPI.pyi index da521f94d7..a4e053d863 100644 --- a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPI.pyi +++ b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPI.pyi @@ -4,7 +4,6 @@ from typing import overload from Part.TopoShapeEdgePy import TopoShapeEdge from Part.PointPy import Point - @export( PythonName="Part.ChFi2d.FilletAPI", Twin="ChFi2d_FilletAPI", @@ -41,7 +40,9 @@ class ChFi2d_FilletAPI(PyObjectBase): """ ... - def result(self, point: Point, solution: int = -1) -> tuple[TopoShapeEdge, TopoShapeEdge, TopoShapeEdge]: + def result( + self, point: Point, solution: int = -1 + ) -> tuple[TopoShapeEdge, TopoShapeEdge, TopoShapeEdge]: """ result(point, solution=-1) diff --git a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPIPyImp.cpp b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPIPyImp.cpp index 19150b771c..696e3e6269 100644 --- a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPIPyImp.cpp +++ b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAPIPyImp.cpp @@ -24,9 +24,9 @@ #include -# include -# include -# include +#include +#include +#include #include @@ -41,7 +41,7 @@ using namespace Part; -PyObject *ChFi2d_FilletAPIPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ChFi2d_FilletAPIPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ChFi2d_FilletAPIPy and the Twin object return new ChFi2d_FilletAPIPy(new ChFi2d_FilletAPI); @@ -50,15 +50,18 @@ PyObject *ChFi2d_FilletAPIPy::PyMake(struct _typeobject *, PyObject *, PyObject // constructor method int ChFi2d_FilletAPIPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - if (PyArg_ParseTuple(args, "")) + if (PyArg_ParseTuple(args, "")) { return 0; + } PyErr_Clear(); PyObject* wire; PyObject* plane; if (PyArg_ParseTuple(args, "O!O!", &TopoShapeWirePy::Type, &wire, &PlanePy::Type, &plane)) { TopoDS_Shape shape = static_cast(wire)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAPIPtr()->Init(TopoDS::Wire(shape), hPlane->Pln()); return 0; } @@ -66,20 +69,32 @@ int ChFi2d_FilletAPIPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2, - &PlanePy::Type, &plane)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge1, + &TopoShapeEdgePy::Type, + &edge2, + &PlanePy::Type, + &plane + )) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAPIPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2), hPlane->Pln()); return 0; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- FilletAPI()\n" - "-- FilletAPI(wire, plane)" - "-- FilletAPI(edge, edge, plane)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- FilletAPI()\n" + "-- FilletAPI(wire, plane)" + "-- FilletAPI(edge, edge, plane)\n" + ); return -1; } @@ -89,13 +104,15 @@ std::string ChFi2d_FilletAPIPy::representation() const return {""}; } -PyObject* ChFi2d_FilletAPIPy::init(PyObject *args) +PyObject* ChFi2d_FilletAPIPy::init(PyObject* args) { PyObject* wire; PyObject* plane; if (PyArg_ParseTuple(args, "O!O!", &TopoShapeWirePy::Type, &wire, &PlanePy::Type, &plane)) { TopoDS_Shape shape = static_cast(wire)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAPIPtr()->Init(TopoDS::Wire(shape), hPlane->Pln()); Py_Return; } @@ -103,27 +120,40 @@ PyObject* ChFi2d_FilletAPIPy::init(PyObject *args) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2, - &PlanePy::Type, &plane)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge1, + &TopoShapeEdgePy::Type, + &edge2, + &PlanePy::Type, + &plane + )) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAPIPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2), hPlane->Pln()); Py_Return; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- init(wire, plane)" - "-- init(edge, edge, plane)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- init(wire, plane)" + "-- init(edge, edge, plane)\n" + ); return nullptr; } -PyObject* ChFi2d_FilletAPIPy::perform(PyObject *args) +PyObject* ChFi2d_FilletAPIPy::perform(PyObject* args) { double radius; - if (!PyArg_ParseTuple(args, "d", &radius)) + if (!PyArg_ParseTuple(args, "d", &radius)) { return nullptr; + } try { bool ok = getChFi2d_FilletAPIPtr()->Perform(radius); @@ -135,11 +165,12 @@ PyObject* ChFi2d_FilletAPIPy::perform(PyObject *args) } } -PyObject* ChFi2d_FilletAPIPy::numberOfResults(PyObject *args) +PyObject* ChFi2d_FilletAPIPy::numberOfResults(PyObject* args) { PyObject* pnt; - if (!PyArg_ParseTuple(args, "O!", &Base::VectorPy::Type, &pnt)) + if (!PyArg_ParseTuple(args, "O!", &Base::VectorPy::Type, &pnt)) { return nullptr; + } try { Base::Vector3d* vec = static_cast(pnt)->getVectorPtr(); @@ -152,22 +183,30 @@ PyObject* ChFi2d_FilletAPIPy::numberOfResults(PyObject *args) } } -PyObject* ChFi2d_FilletAPIPy::result(PyObject *args) +PyObject* ChFi2d_FilletAPIPy::result(PyObject* args) { PyObject* pnt; int solution = -1; - if (!PyArg_ParseTuple(args, "O!|i", &Base::VectorPy::Type, &pnt, &solution)) + if (!PyArg_ParseTuple(args, "O!|i", &Base::VectorPy::Type, &pnt, &solution)) { return nullptr; + } Base::Vector3d* vec = static_cast(pnt)->getVectorPtr(); try { TopoDS_Edge theEdge1, theEdge2; - TopoDS_Shape res_edge = getChFi2d_FilletAPIPtr()->Result(Base::convertTo(*vec), theEdge1, theEdge2, solution); + TopoDS_Shape res_edge = getChFi2d_FilletAPIPtr()->Result( + Base::convertTo(*vec), + theEdge1, + theEdge2, + solution + ); - Py::TupleN tuple(Py::asObject(TopoShape(res_edge).getPyObject()), - Py::asObject(TopoShape(theEdge1).getPyObject()), - Py::asObject(TopoShape(theEdge2).getPyObject())); + Py::TupleN tuple( + Py::asObject(TopoShape(res_edge).getPyObject()), + Py::asObject(TopoShape(theEdge1).getPyObject()), + Py::asObject(TopoShape(theEdge2).getPyObject()) + ); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { @@ -176,7 +215,7 @@ PyObject* ChFi2d_FilletAPIPy::result(PyObject *args) } } -PyObject *ChFi2d_FilletAPIPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ChFi2d_FilletAPIPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgo.pyi b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgo.pyi index a17726ca0e..81d5535910 100644 --- a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgo.pyi +++ b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgo.pyi @@ -3,7 +3,6 @@ from Base.PyObjectBase import PyObjectBase from Base.Vector import Vector from typing import Final - @export( Name="ChFi2d_FilletAlgoPy", PythonName="Part.ChFi2d.FilletAlgo", diff --git a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgoPyImp.cpp b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgoPyImp.cpp index cf337db6c6..03edd9a6ed 100644 --- a/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgoPyImp.cpp +++ b/src/Mod/Part/App/ChFi2d/ChFi2d_FilletAlgoPyImp.cpp @@ -24,10 +24,10 @@ #include -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -42,7 +42,7 @@ using namespace Part; -PyObject *ChFi2d_FilletAlgoPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ChFi2d_FilletAlgoPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ChFi2d_FilletAlgoPy and the Twin object return new ChFi2d_FilletAlgoPy(new ChFi2d_FilletAlgo); @@ -51,15 +51,18 @@ PyObject *ChFi2d_FilletAlgoPy::PyMake(struct _typeobject *, PyObject *, PyObject // constructor method int ChFi2d_FilletAlgoPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - if (PyArg_ParseTuple(args, "")) + if (PyArg_ParseTuple(args, "")) { return 0; + } PyErr_Clear(); PyObject* wire; PyObject* plane; if (PyArg_ParseTuple(args, "O!O!", &TopoShapeWirePy::Type, &wire, &PlanePy::Type, &plane)) { TopoDS_Shape shape = static_cast(wire)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAlgoPtr()->Init(TopoDS::Wire(shape), hPlane->Pln()); return 0; } @@ -67,20 +70,32 @@ int ChFi2d_FilletAlgoPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2, - &PlanePy::Type, &plane)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge1, + &TopoShapeEdgePy::Type, + &edge2, + &PlanePy::Type, + &plane + )) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAlgoPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2), hPlane->Pln()); return 0; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- FilletAlgo()\n" - "-- FilletAlgo(wire, plane)" - "-- FilletAlgo(edge, edge, plane)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- FilletAlgo()\n" + "-- FilletAlgo(wire, plane)" + "-- FilletAlgo(edge, edge, plane)\n" + ); return -1; } @@ -90,13 +105,15 @@ std::string ChFi2d_FilletAlgoPy::representation() const return {""}; } -PyObject* ChFi2d_FilletAlgoPy::init(PyObject *args) +PyObject* ChFi2d_FilletAlgoPy::init(PyObject* args) { PyObject* wire; PyObject* plane; if (PyArg_ParseTuple(args, "O!O!", &TopoShapeWirePy::Type, &wire, &PlanePy::Type, &plane)) { TopoDS_Shape shape = static_cast(wire)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAlgoPtr()->Init(TopoDS::Wire(shape), hPlane->Pln()); Py_Return; } @@ -104,27 +121,40 @@ PyObject* ChFi2d_FilletAlgoPy::init(PyObject *args) PyErr_Clear(); PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2, - &PlanePy::Type, &plane)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge1, + &TopoShapeEdgePy::Type, + &edge2, + &PlanePy::Type, + &plane + )) { TopoDS_Shape shape1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape shape2 = static_cast(edge2)->getTopoShapePtr()->getShape(); - Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast(static_cast(plane)->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) hPlane = Handle(Geom_Plane)::DownCast( + static_cast(plane)->getGeomPlanePtr()->handle() + ); getChFi2d_FilletAlgoPtr()->Init(TopoDS::Edge(shape1), TopoDS::Edge(shape2), hPlane->Pln()); Py_Return; } - PyErr_SetString(PyExc_TypeError, "Wrong arguments:\n" - "-- init(wire, plane)" - "-- init(edge, edge, plane)\n"); + PyErr_SetString( + PyExc_TypeError, + "Wrong arguments:\n" + "-- init(wire, plane)" + "-- init(edge, edge, plane)\n" + ); return nullptr; } -PyObject* ChFi2d_FilletAlgoPy::perform(PyObject *args) +PyObject* ChFi2d_FilletAlgoPy::perform(PyObject* args) { double radius; - if (!PyArg_ParseTuple(args, "d", &radius)) + if (!PyArg_ParseTuple(args, "d", &radius)) { return nullptr; + } try { bool ok = getChFi2d_FilletAlgoPtr()->Perform(radius); @@ -136,11 +166,12 @@ PyObject* ChFi2d_FilletAlgoPy::perform(PyObject *args) } } -PyObject* ChFi2d_FilletAlgoPy::numberOfResults(PyObject *args) +PyObject* ChFi2d_FilletAlgoPy::numberOfResults(PyObject* args) { PyObject* pnt; - if (!PyArg_ParseTuple(args, "O!", &Base::VectorPy::Type, &pnt)) + if (!PyArg_ParseTuple(args, "O!", &Base::VectorPy::Type, &pnt)) { return nullptr; + } try { Base::Vector3d* vec = static_cast(pnt)->getVectorPtr(); @@ -153,22 +184,30 @@ PyObject* ChFi2d_FilletAlgoPy::numberOfResults(PyObject *args) } } -PyObject* ChFi2d_FilletAlgoPy::result(PyObject *args) +PyObject* ChFi2d_FilletAlgoPy::result(PyObject* args) { PyObject* pnt; int solution = -1; - if (!PyArg_ParseTuple(args, "O!|i", &Base::VectorPy::Type, &pnt, &solution)) + if (!PyArg_ParseTuple(args, "O!|i", &Base::VectorPy::Type, &pnt, &solution)) { return nullptr; + } Base::Vector3d* vec = static_cast(pnt)->getVectorPtr(); try { TopoDS_Edge theEdge1, theEdge2; - TopoDS_Shape res_edge = getChFi2d_FilletAlgoPtr()->Result(Base::convertTo(*vec), theEdge1, theEdge2, solution); + TopoDS_Shape res_edge = getChFi2d_FilletAlgoPtr()->Result( + Base::convertTo(*vec), + theEdge1, + theEdge2, + solution + ); - Py::TupleN tuple(Py::asObject(TopoShape(res_edge).getPyObject()), - Py::asObject(TopoShape(theEdge1).getPyObject()), - Py::asObject(TopoShape(theEdge2).getPyObject())); + Py::TupleN tuple( + Py::asObject(TopoShape(res_edge).getPyObject()), + Py::asObject(TopoShape(theEdge1).getPyObject()), + Py::asObject(TopoShape(theEdge2).getPyObject()) + ); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { @@ -177,7 +216,7 @@ PyObject* ChFi2d_FilletAlgoPy::result(PyObject *args) } } -PyObject *ChFi2d_FilletAlgoPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ChFi2d_FilletAlgoPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Circle.pyi b/src/Mod/Part/App/Circle.pyi index 1fd7f5f28b..1a3e9d0286 100644 --- a/src/Mod/Part/App/Circle.pyi +++ b/src/Mod/Part/App/Circle.pyi @@ -4,7 +4,6 @@ from Conic import Conic from Point import Point from typing import overload - @export( PythonName="Part.Circle", Twin="GeomCircle", @@ -39,15 +38,11 @@ class Circle(Conic): @overload def __init__(self) -> None: ... - @overload def __init__(self, circle: "Circle") -> None: ... - @overload def __init__(self, circle: "Circle", distance: float) -> None: ... - @overload def __init__(self, center: Point, normal: Vector, radius: float) -> None: ... - @overload def __init__(self, point1: Point, point2: Point, point3: Point) -> None: ... diff --git a/src/Mod/Part/App/CirclePyImp.cpp b/src/Mod/Part/App/CirclePyImp.cpp index 92bb36cc26..810e95cfb4 100644 --- a/src/Mod/Part/App/CirclePyImp.cpp +++ b/src/Mod/Part/App/CirclePyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -51,14 +51,14 @@ std::string CirclePy::representation() const std::stringstream str; str << "Circle ("; str << "Radius : " << fRad << ", "; - str << "Position : (" << loc.X() << ", "<< loc.Y() << ", "<< loc.Z() << "), "; - str << "Direction : (" << dir.X() << ", "<< dir.Y() << ", "<< dir.Z() << ")"; + str << "Position : (" << loc.X() << ", " << loc.Y() << ", " << loc.Z() << "), "; + str << "Direction : (" << dir.X() << ", " << dir.Y() << ", " << dir.Z() << ")"; str << ")"; return str.str(); } -PyObject *CirclePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* CirclePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of CirclePy and the Twin object Handle(Geom_Circle) circle = new Geom_Circle(gp_Circ()); @@ -69,13 +69,14 @@ PyObject *CirclePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pyt int CirclePy::PyInit(PyObject* args, PyObject* kwds) { // circle and distance for offset - PyObject *pCirc; + PyObject* pCirc; double dist; - static const std::array keywords_cd {"Circle", "Distance", nullptr}; + static const std::array keywords_cd {"Circle", "Distance", nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", keywords_cd, &(CirclePy::Type), &pCirc, &dist)) { CirclePy* pcCircle = static_cast(pCirc); - Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast - (pcCircle->getGeomCirclePtr()->handle()); + Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( + pcCircle->getGeomCirclePtr()->handle() + ); GC_MakeCircle mc(circle->Circ(), dist); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); @@ -89,17 +90,22 @@ int CirclePy::PyInit(PyObject* args, PyObject* kwds) // center, normal and radius PyObject *pV1, *pV2, *pV3; - static const std::array keywords_cnr {"Center", "Normal", "Radius", nullptr}; + static const std::array keywords_cnr {"Center", "Normal", "Radius", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!d", keywords_cnr, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &dist)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!d", + keywords_cnr, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &dist + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); - GC_MakeCircle mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Dir(v2.x,v2.y,v2.z), - dist); + GC_MakeCircle mc(gp_Pnt(v1.x, v1.y, v1.z), gp_Dir(v2.x, v2.y, v2.z), dist); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -110,30 +116,36 @@ int CirclePy::PyInit(PyObject* args, PyObject* kwds) return 0; } - static const std::array keywords_c {"Circle", nullptr}; + static const std::array keywords_c {"Circle", nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_c, &(CirclePy::Type), &pCirc)) { CirclePy* pcCircle = static_cast(pCirc); - Handle(Geom_Circle) circ1 = Handle(Geom_Circle)::DownCast - (pcCircle->getGeomCirclePtr()->handle()); - Handle(Geom_Circle) circ2 = Handle(Geom_Circle)::DownCast - (this->getGeomCirclePtr()->handle()); + Handle(Geom_Circle) circ1 = Handle(Geom_Circle)::DownCast( + pcCircle->getGeomCirclePtr()->handle() + ); + Handle(Geom_Circle) circ2 = Handle(Geom_Circle)::DownCast(this->getGeomCirclePtr()->handle()); circ2->SetCirc(circ1->Circ()); return 0; } - static const std::array keywords_ppp {"Point1", "Point2", "Point3", nullptr}; + static const std::array keywords_ppp {"Point1", "Point2", "Point3", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ppp, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ppp, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakeCircle mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakeCircle mc(gp_Pnt(v1.x, v1.y, v1.z), gp_Pnt(v2.x, v2.y, v2.z), gp_Pnt(v3.x, v3.y, v3.z)); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -145,7 +157,7 @@ int CirclePy::PyInit(PyObject* args, PyObject* kwds) } // default circle - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(getGeomCirclePtr()->handle()); @@ -153,12 +165,15 @@ int CirclePy::PyInit(PyObject* args, PyObject* kwds) return 0; } - PyErr_SetString(PyExc_TypeError, "Circle constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Circle constructor accepts:\n" "-- empty parameter list\n" "-- Circle\n" "-- Circle, Distance\n" "-- Center, Normal, Radius\n" - "-- Point1, Point2, Point3"); + "-- Point1, Point2, Point3" + ); return -1; } @@ -168,18 +183,18 @@ Py::Float CirclePy::getRadius() const return Py::Float(circle->Radius()); } -void CirclePy::setRadius(Py::Float arg) +void CirclePy::setRadius(Py::Float arg) { Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(getGeomCirclePtr()->handle()); circle->SetRadius((double)arg); } -PyObject *CirclePy::getCustomAttributes(const char* ) const +PyObject* CirclePy::getCustomAttributes(const char*) const { return nullptr; } -int CirclePy::setCustomAttributes(const char* , PyObject *) +int CirclePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Cone.pyi b/src/Mod/Part/App/Cone.pyi index f9c119ced7..4e7138d3b3 100644 --- a/src/Mod/Part/App/Cone.pyi +++ b/src/Mod/Part/App/Cone.pyi @@ -4,7 +4,6 @@ from Base.Axis import Axis as AxisPy from GeometrySurface import GeometrySurface from typing import Final - @export( PythonName="Part.Cone", Twin="GeomCone", diff --git a/src/Mod/Part/App/ConePyImp.cpp b/src/Mod/Part/App/ConePyImp.cpp index ac998f677d..f05c106904 100644 --- a/src/Mod/Part/App/ConePyImp.cpp +++ b/src/Mod/Part/App/ConePyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -47,7 +47,7 @@ std::string ConePy::representation() const return ""; } -PyObject *ConePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ConePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ConePy and the Twin object return new ConePy(new GeomCone); @@ -56,133 +56,154 @@ PyObject *ConePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pytho // constructor method int ConePy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array keywords_n{nullptr}; + static const std::array keywords_n {nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { - Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast( + getGeometryPtr()->handle() + ); s->SetRadius(1.0); return 0; } PyObject *pV1, *pV2; double radius1, radius2; - static const std::array keywords_pprr {"Point1", "Point2", "Radius1", "Radius2", nullptr}; + static const std::array + keywords_pprr {"Point1", "Point2", "Radius1", "Radius2", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!dd", keywords_pprr, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &radius1, &radius2)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!dd", + keywords_pprr, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &radius1, + &radius2 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); - GC_MakeConicalSurface mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - radius1, radius2); + GC_MakeConicalSurface mc(gp_Pnt(v1.x, v1.y, v1.z), gp_Pnt(v2.x, v2.y, v2.z), radius1, radius2); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_ConicalSurface) cone = Handle(Geom_ConicalSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ConicalSurface) cone = Handle(Geom_ConicalSurface)::DownCast( + getGeometryPtr()->handle() + ); cone->SetCone(mc.Value()->Cone()); return 0; } PyObject *pV3, *pV4; - static const std::array keywords_pppp{"Point1", "Point2", "Point3", "Point4", nullptr}; + static const std::array keywords_pppp {"Point1", "Point2", "Point3", "Point4", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!O!", keywords_pppp, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3, - &(Base::VectorPy::Type), &pV4)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!O!", + keywords_pppp, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3, + &(Base::VectorPy::Type), + &pV4 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); Base::Vector3d v4 = static_cast(pV4)->value(); - GC_MakeConicalSurface mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z), - gp_Pnt(v4.x,v4.y,v4.z)); + GC_MakeConicalSurface mc( + gp_Pnt(v1.x, v1.y, v1.z), + gp_Pnt(v2.x, v2.y, v2.z), + gp_Pnt(v3.x, v3.y, v3.z), + gp_Pnt(v4.x, v4.y, v4.z) + ); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_ConicalSurface) cone = Handle(Geom_ConicalSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ConicalSurface) cone = Handle(Geom_ConicalSurface)::DownCast( + getGeometryPtr()->handle() + ); cone->SetCone(mc.Value()->Cone()); return 0; } - PyObject *pCone; - static const std::array keywords_c{"Cone", nullptr}; + PyObject* pCone; + static const std::array keywords_c {"Cone", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_c, - &(ConePy::Type), &pCone)) { + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_c, &(ConePy::Type), &pCone)) { ConePy* pcCone = static_cast(pCone); - Handle(Geom_ConicalSurface) pcone = Handle(Geom_ConicalSurface)::DownCast - (pcCone->getGeometryPtr()->handle()); + Handle(Geom_ConicalSurface) pcone = Handle(Geom_ConicalSurface)::DownCast( + pcCone->getGeometryPtr()->handle() + ); GC_MakeConicalSurface mc(pcone->Cone()); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_ConicalSurface) cone = Handle(Geom_ConicalSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ConicalSurface) cone = Handle(Geom_ConicalSurface)::DownCast( + getGeometryPtr()->handle() + ); cone->SetCone(mc.Value()->Cone()); return 0; } - PyErr_SetString(PyExc_TypeError, "Cone constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Cone constructor accepts:\n" "-- empty parameter list\n" "-- Cone\n" "-- Point1, Point2, Radius1, Radius2\n" - "-- Point1, Point2, Point3, Point4"); + "-- Point1, Point2, Point3, Point4" + ); return -1; } Py::Object ConePy::getApex() const { - Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast(getGeomConePtr()->handle()); gp_Pnt loc = s->Apex(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } Py::Float ConePy::getRadius() const { - Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast(getGeomConePtr()->handle()); return Py::Float(s->RefRadius()); } void ConePy::setRadius(Py::Float arg) { - Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast(getGeomConePtr()->handle()); s->SetRadius((double)arg); } Py::Float ConePy::getSemiAngle() const { - Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast(getGeomConePtr()->handle()); return Py::Float(s->SemiAngle()); } void ConePy::setSemiAngle(Py::Float arg) { - Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast(getGeomConePtr()->handle()); s->SetSemiAngle((double)arg); } Py::Object ConePy::getCenter() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeomConePtr()->handle() + ); gp_Pnt loc = s->Location(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } @@ -192,14 +213,16 @@ void ConePy::setCenter(Py::Object arg) PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d loc = static_cast(p)->value(); - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeomConePtr()->handle() + ); s->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d loc = Base::getVectorFromTuple(p); - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeomConePtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeomConePtr()->handle() + ); s->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else { @@ -211,8 +234,9 @@ void ConePy::setCenter(Py::Object arg) Py::Object ConePy::getAxis() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeometryPtr()->handle() + ); gp_Dir dir = s->Axis().Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } @@ -220,7 +244,7 @@ Py::Object ConePy::getAxis() const void ConePy::setAxis(Py::Object arg) { Standard_Real dir_x, dir_y, dir_z; - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); dir_x = v.x; @@ -240,8 +264,9 @@ void ConePy::setAxis(Py::Object arg) } try { - Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast - (this->getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast( + this->getGeometryPtr()->handle() + ); gp_Ax1 axis; axis.SetLocation(this_surf->Location()); axis.SetDirection(gp_Dir(dir_x, dir_y, dir_z)); @@ -252,7 +277,7 @@ void ConePy::setAxis(Py::Object arg) } } -PyObject *ConePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ConePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -261,5 +286,3 @@ int ConePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Mod/Part/App/Conic.pyi b/src/Mod/Part/App/Conic.pyi index 619f1823e7..3d82016533 100644 --- a/src/Mod/Part/App/Conic.pyi +++ b/src/Mod/Part/App/Conic.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from GeometryCurve import GeometryCurve from typing import Final - @export( PythonName="Part.Conic", Twin="GeomConic", diff --git a/src/Mod/Part/App/ConicPyImp.cpp b/src/Mod/Part/App/ConicPyImp.cpp index 86b4c2f239..2e514a8034 100644 --- a/src/Mod/Part/App/ConicPyImp.cpp +++ b/src/Mod/Part/App/ConicPyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -41,11 +41,10 @@ std::string ConicPy::representation() const return ""; } -PyObject *ConicPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ConicPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'Conic'."); + PyErr_SetString(PyExc_RuntimeError, "You cannot create an instance of the abstract class 'Conic'."); return nullptr; } @@ -69,7 +68,7 @@ Py::Object ConicPy::getLocation() const return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -void ConicPy::setCenter(Py::Object arg) +void ConicPy::setCenter(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { @@ -79,14 +78,15 @@ void ConicPy::setCenter(Py::Object arg) else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d loc = Base::getVectorFromTuple(p); getGeomConicPtr()->setLocation(loc); - } else { + } + else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); } } -void ConicPy::setLocation(Py::Object arg) +void ConicPy::setLocation(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { @@ -96,7 +96,8 @@ void ConicPy::setLocation(Py::Object arg) else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d loc = Base::getVectorFromTuple(p); getGeomConicPtr()->setLocation(loc); - } else { + } + else { std::string error = std::string("type must be 'Vector', not "); error += p->ob_type->tp_name; throw Py::TypeError(error); @@ -127,7 +128,7 @@ Py::Object ConicPy::getAxis() const return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void ConicPy::setAxis(Py::Object arg) +void ConicPy::setAxis(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d val; @@ -163,7 +164,7 @@ Py::Object ConicPy::getXAxis() const return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void ConicPy::setXAxis(Py::Object arg) +void ConicPy::setXAxis(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d val; @@ -199,7 +200,7 @@ Py::Object ConicPy::getYAxis() const return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void ConicPy::setYAxis(Py::Object arg) +void ConicPy::setYAxis(Py::Object arg) { PyObject* p = arg.ptr(); Base::Vector3d val; @@ -227,12 +228,12 @@ void ConicPy::setYAxis(Py::Object arg) } } -PyObject *ConicPy::getCustomAttributes(const char* ) const +PyObject* ConicPy::getCustomAttributes(const char*) const { return nullptr; } -int ConicPy::setCustomAttributes(const char* , PyObject *) +int ConicPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/CrossSection.cpp b/src/Mod/Part/App/CrossSection.cpp index 4c064fc85b..f0190164fe 100644 --- a/src/Mod/Part/App/CrossSection.cpp +++ b/src/Mod/Part/App/CrossSection.cpp @@ -22,25 +22,25 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "CrossSection.h" @@ -50,9 +50,11 @@ using namespace Part; CrossSection::CrossSection(double a, double b, double c, const TopoDS_Shape& s) - : a(a), b(b), c(c), s(s) -{ -} + : a(a) + , b(b) + , c(c) + , s(s) +{} std::list CrossSection::slice(double d) const { @@ -81,24 +83,30 @@ std::list CrossSection::removeDuplicates(const std::list CrossSection::removeDuplicates(const std::list& wires) const { - FCBRepAlgoAPI_Section cs(shape, gp_Pln(a,b,c,-d)); + FCBRepAlgoAPI_Section cs(shape, gp_Pln(a, b, c, -d)); if (cs.IsDone()) { std::list edges; TopExp_Explorer xp; - for (xp.Init(cs.Shape(), TopAbs_EDGE); xp.More(); xp.Next()) + for (xp.Init(cs.Shape(), TopAbs_EDGE); xp.More(); xp.Next()) { edges.push_back(TopoDS::Edge(xp.Current())); + } connectEdges(edges, wires); } } void CrossSection::sliceSolid(double d, const TopoDS_Shape& shape, std::list& wires) const { - gp_Pln slicePlane(a,b,c,-d); + gp_Pln slicePlane(a, b, c, -d); BRepBuilderAPI_MakeFace mkFace(slicePlane); TopoDS_Face face = mkFace.Face(); // Make sure to choose a point that does not lie on the plane (fixes #0001228) - gp_Vec tempVector(a,b,c); - tempVector.Normalize();//just in case. - tempVector *= (d+1.0); + gp_Vec tempVector(a, b, c); + tempVector.Normalize(); // just in case. + tempVector *= (d + 1.0); gp_Pnt refPoint(0.0, 0.0, 0.0); refPoint.Translate(tempVector); @@ -139,13 +148,13 @@ void CrossSection::sliceSolid(double d, const TopoDS_Shape& shape, std::list& edges, std::list& wires) const +void CrossSection::connectEdges(const std::list& edges, std::list& wires) const { // Hint: Use ShapeAnalysis_FreeBounds::ConnectEdgesToWires() as an alternative std::list edge_list = edges; @@ -172,7 +181,8 @@ void CrossSection::connectEdges (const std::list& edges, std::list< bool found = false; do { found = false; - for (std::list::iterator pE = edge_list.begin(); pE != edge_list.end();++pE) { + for (std::list::iterator pE = edge_list.begin(); pE != edge_list.end(); + ++pE) { mkWire.Add(*pE); if (mkWire.Error() != BRepBuilderAPI_DisconnectedWire) { // edge added ==> remove it from list @@ -182,18 +192,20 @@ void CrossSection::connectEdges (const std::list& edges, std::list< break; } } - } - while (found); + } while (found); // Fix any topological issues of the wire wires.push_back(fixWire(new_wire)); } } -void CrossSection::connectWires (const TopTools_IndexedMapOfShape& wireMap, std::list& wires) const +void CrossSection::connectWires( + const TopTools_IndexedMapOfShape& wireMap, + std::list& wires +) const { Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); - for (int i=1; i<=wireMap.Extent(); i++) { + for (int i = 1; i <= wireMap.Extent(); i++) { const TopoDS_Shape& wire = wireMap.FindKey(i); hWires->Append(wire); } @@ -201,7 +213,7 @@ void CrossSection::connectWires (const TopTools_IndexedMapOfShape& wireMap, std: Handle(TopTools_HSequenceOfShape) hSorted = new TopTools_HSequenceOfShape(); ShapeAnalysis_FreeBounds::ConnectWiresToWires(hWires, Precision::Confusion(), false, hSorted); - for (int i=1; i<=hSorted->Length(); i++) { + for (int i = 1; i <= hSorted->Length(); i++) { const TopoDS_Wire& new_wire = TopoDS::Wire(hSorted->Value(i)); // Fix any topological issues of the wire wires.push_back(fixWire(new_wire)); @@ -220,10 +232,13 @@ TopoDS_Wire CrossSection::fixWire(const TopoDS_Wire& wire) const return aFix.Wire(); } -TopoCrossSection::TopoCrossSection(double a, double b, double c, const TopoShape& s, const char *op) - : a(a), b(b), c(c), shape(s), op(op?op:Part::OpCodes::Slice) -{ -} +TopoCrossSection::TopoCrossSection(double a, double b, double c, const TopoShape& s, const char* op) + : a(a) + , b(b) + , c(c) + , shape(s) + , op(op ? op : Part::OpCodes::Slice) +{} void TopoCrossSection::slice(int idx, double d, std::vector& wires) const { @@ -251,16 +266,16 @@ TopoShape TopoCrossSection::slice(int idx, double d) const { std::vector wires; slice(idx, d, wires); - return TopoShape().makeElementCompound( - wires, - 0, - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + return TopoShape() + .makeElementCompound(wires, 0, TopoShape::SingleShapeCompoundCreationPolicy::returnShape); } -void TopoCrossSection::sliceNonSolid(int idx, - double d, - const TopoShape& shape, - std::vector& wires) const +void TopoCrossSection::sliceNonSolid( + int idx, + double d, + const TopoShape& shape, + std::vector& wires +) const { FCBRepAlgoAPI_Section cs(shape.getShape(), gp_Pln(a, b, c, -d)); if (cs.IsDone()) { @@ -274,10 +289,12 @@ void TopoCrossSection::sliceNonSolid(int idx, } } -void TopoCrossSection::sliceSolid(int idx, - double d, - const TopoShape& shape, - std::vector& wires) const +void TopoCrossSection::sliceSolid( + int idx, + double d, + const TopoShape& shape, + std::vector& wires +) const { gp_Pln slicePlane(a, b, c, -d); BRepBuilderAPI_MakeFace mkFace(slicePlane); @@ -311,9 +328,11 @@ void TopoCrossSection::sliceSolid(int idx, if (plane.Axis().IsParallel(slicePlane.Axis(), Precision::Confusion()) && plane.Distance(slicePlane.Location()) < Precision::Confusion()) { auto repaired_wires = TopoShape(face.Tag) - .makeElementWires(face.getSubTopoShapes(TopAbs_EDGE), - prefix.c_str(), - true) + .makeElementWires( + face.getSubTopoShapes(TopAbs_EDGE), + prefix.c_str(), + true + ) .getSubTopoShapes(TopAbs_WIRE); wires.insert(wires.end(), repaired_wires.begin(), repaired_wires.end()); } diff --git a/src/Mod/Part/App/CrossSection.h b/src/Mod/Part/App/CrossSection.h index 0fbe6e8ba8..9a9d255262 100644 --- a/src/Mod/Part/App/CrossSection.h +++ b/src/Mod/Part/App/CrossSection.h @@ -34,7 +34,8 @@ class TopoDS_Shape; class TopoDS_Wire; -namespace Part { +namespace Part +{ class PartExport CrossSection { @@ -45,13 +46,13 @@ public: private: void sliceNonSolid(double d, const TopoDS_Shape&, std::list& wires) const; void sliceSolid(double d, const TopoDS_Shape&, std::list& wires) const; - void connectEdges (const std::list& edges, std::list& wires) const; - void connectWires (const TopTools_IndexedMapOfShape& wireMap, std::list& wires) const; + void connectEdges(const std::list& edges, std::list& wires) const; + void connectWires(const TopTools_IndexedMapOfShape& wireMap, std::list& wires) const; TopoDS_Wire fixWire(const TopoDS_Wire& wire) const; std::list removeDuplicates(const std::list& wires) const; private: - double a,b,c; + double a, b, c; const TopoDS_Shape& s; }; @@ -74,4 +75,4 @@ private: } // namespace Part -#endif // PART_CROSSSECTION_H +#endif // PART_CROSSSECTION_H diff --git a/src/Mod/Part/App/CustomFeature.cpp b/src/Mod/Part/App/CustomFeature.cpp index 4f9a63ed6b..40494e78d6 100644 --- a/src/Mod/Part/App/CustomFeature.cpp +++ b/src/Mod/Part/App/CustomFeature.cpp @@ -41,22 +41,24 @@ short CustomFeature::mustExecute() const return Part::Feature::mustExecute(); } -App::DocumentObjectExecReturn *CustomFeature::execute() +App::DocumentObjectExecReturn* CustomFeature::execute() { return App::DocumentObject::StdReturn; } // --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Part::CustomFeaturePython, Part::CustomFeature) -template<> const char* Part::CustomFeaturePython::getViewProviderName() const { +template<> +const char* Part::CustomFeaturePython::getViewProviderName() const +{ return "PartGui::ViewProviderCustomPython"; } /// @endcond // explicit template instantiation template class PartExport FeaturePythonT; -} - +} // namespace App diff --git a/src/Mod/Part/App/CustomFeature.h b/src/Mod/Part/App/CustomFeature.h index e5a1d531dd..91e2ffd428 100644 --- a/src/Mod/Part/App/CustomFeature.h +++ b/src/Mod/Part/App/CustomFeature.h @@ -36,7 +36,7 @@ namespace Part /** Base class of all custom feature classes which are almost used as base * for python feature classes. */ -class PartExport CustomFeature : public Part::Feature +class PartExport CustomFeature: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::CustomFeature); @@ -48,19 +48,20 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderCustom"; } }; using CustomFeaturePython = App::FeaturePythonT; -} //namespace Part +} // namespace Part -#endif // PART_CUSTOMFEATURE_H +#endif // PART_CUSTOMFEATURE_H diff --git a/src/Mod/Part/App/Cylinder.pyi b/src/Mod/Part/App/Cylinder.pyi index b3638c36db..5eff313747 100644 --- a/src/Mod/Part/App/Cylinder.pyi +++ b/src/Mod/Part/App/Cylinder.pyi @@ -4,7 +4,6 @@ from Circle import Circle from GeometrySurface import GeometrySurface from typing import overload - @export( PythonName="Part.Cylinder", Twin="GeomCylinder", @@ -49,15 +48,11 @@ class Cylinder(GeometrySurface): @overload def __init__(self) -> None: ... - @overload def __init__(self, cylinder: "Cylinder") -> None: ... - @overload def __init__(self, cylinder: "Cylinder", distance: float) -> None: ... - @overload def __init__(self, point1: Vector, point2: Vector, point3: Vector) -> None: ... - @overload def __init__(self, circle: Circle) -> None: ... diff --git a/src/Mod/Part/App/CylinderPyImp.cpp b/src/Mod/Part/App/CylinderPyImp.cpp index 3a69425fb4..ca19835e92 100644 --- a/src/Mod/Part/App/CylinderPyImp.cpp +++ b/src/Mod/Part/App/CylinderPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -48,7 +48,7 @@ std::string CylinderPy::representation() const return ""; } -PyObject *CylinderPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* CylinderPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of CylinderPy and the Twin object return new CylinderPy(new GeomCylinder); @@ -58,117 +58,149 @@ PyObject *CylinderPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // P int CylinderPy::PyInit(PyObject* args, PyObject* kwds) { // cylinder and distance for offset - PyObject *pCyl; + PyObject* pCyl; double dist; - static const std::array keywords_cd{"Cylinder", "Distance", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", keywords_cd, &(CylinderPy::Type), &pCyl, &dist)) { + static const std::array keywords_cd {"Cylinder", "Distance", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!d", + keywords_cd, + &(CylinderPy::Type), + &pCyl, + &dist + )) { CylinderPy* pcCylinder = static_cast(pCyl); - Handle(Geom_CylindricalSurface) cylinder = Handle(Geom_CylindricalSurface)::DownCast - (pcCylinder->getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cylinder = Handle(Geom_CylindricalSurface)::DownCast( + pcCylinder->getGeomCylinderPtr()->handle() + ); GC_MakeCylindricalSurface mc(cylinder->Cylinder(), dist); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetCylinder(mc.Value()->Cylinder()); return 0; } - static const std::array keywords_c {"Cylinder", nullptr}; + static const std::array keywords_c {"Cylinder", nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_c, &(CylinderPy::Type), &pCyl)) { CylinderPy* pcCylinder = static_cast(pCyl); - Handle(Geom_CylindricalSurface) cyl1 = Handle(Geom_CylindricalSurface)::DownCast - (pcCylinder->getGeomCylinderPtr()->handle()); - Handle(Geom_CylindricalSurface) cyl2 = Handle(Geom_CylindricalSurface)::DownCast - (this->getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl1 = Handle(Geom_CylindricalSurface)::DownCast( + pcCylinder->getGeomCylinderPtr()->handle() + ); + Handle(Geom_CylindricalSurface) cyl2 = Handle(Geom_CylindricalSurface)::DownCast( + this->getGeomCylinderPtr()->handle() + ); cyl2->SetCylinder(cyl1->Cylinder()); return 0; } PyObject *pV1, *pV2, *pV3; - static const std::array keywords_ppp {"Point1", "Point2", "Point3", nullptr}; + static const std::array keywords_ppp {"Point1", "Point2", "Point3", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ppp, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ppp, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakeCylindricalSurface mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakeCylindricalSurface mc( + gp_Pnt(v1.x, v1.y, v1.z), + gp_Pnt(v2.x, v2.y, v2.z), + gp_Pnt(v3.x, v3.y, v3.z) + ); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetCylinder(mc.Value()->Cylinder()); return 0; } - static const std::array keywords_cc {"Circle", nullptr}; + static const std::array keywords_cc {"Circle", nullptr}; PyErr_Clear(); - PyObject *pCirc; + PyObject* pCirc; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_cc, &(CirclePy::Type), &pCirc)) { CirclePy* pcCircle = static_cast(pCirc); - Handle(Geom_Circle) circ = Handle(Geom_Circle)::DownCast - (pcCircle->getGeomCirclePtr()->handle()); + Handle(Geom_Circle) circ = Handle(Geom_Circle)::DownCast( + pcCircle->getGeomCirclePtr()->handle() + ); GC_MakeCylindricalSurface mc(circ->Circ()); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetCylinder(mc.Value()->Cylinder()); return 0; } - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetRadius(1.0); return 0; } // All checks failed - PyErr_SetString(PyExc_TypeError, "Cylinder constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Cylinder constructor accepts:\n" "-- empty parameter list\n" "-- Cylinder\n" "-- Cylinder, Distance\n" "-- Point1, Point2, Point3\n" - "-- Circle"); + "-- Circle" + ); return -1; } Py::Float CylinderPy::getRadius() const { - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); return Py::Float(cyl->Radius()); } void CylinderPy::setRadius(Py::Float arg) { - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetRadius((double)arg); } Py::Object CylinderPy::getCenter() const { - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); gp_Pnt loc = cyl->Location(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } @@ -178,14 +210,16 @@ void CylinderPy::setCenter(Py::Object arg) PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d loc = static_cast(p)->value(); - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d loc = Base::getVectorFromTuple(p); - Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast - (getGeomCylinderPtr()->handle()); + Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast( + getGeomCylinderPtr()->handle() + ); cyl->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else { @@ -197,8 +231,9 @@ void CylinderPy::setCenter(Py::Object arg) Py::Object CylinderPy::getAxis() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeometryPtr()->handle() + ); gp_Dir dir = s->Axis().Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } @@ -206,7 +241,7 @@ Py::Object CylinderPy::getAxis() const void CylinderPy::setAxis(Py::Object arg) { Standard_Real dir_x, dir_y, dir_z; - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); dir_x = v.x; @@ -226,8 +261,9 @@ void CylinderPy::setAxis(Py::Object arg) } try { - Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast - (this->getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast( + this->getGeometryPtr()->handle() + ); gp_Ax1 axis; axis.SetLocation(this_surf->Location()); axis.SetDirection(gp_Dir(dir_x, dir_y, dir_z)); @@ -238,7 +274,7 @@ void CylinderPy::setAxis(Py::Object arg) } } -PyObject *CylinderPy::getCustomAttributes(const char* /*attr*/) const +PyObject* CylinderPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -247,5 +283,3 @@ int CylinderPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Mod/Part/App/DatumFeature.cpp b/src/Mod/Part/App/DatumFeature.cpp index 23540f022e..a1a9c4090c 100644 --- a/src/Mod/Part/App/DatumFeature.cpp +++ b/src/Mod/Part/App/DatumFeature.cpp @@ -56,8 +56,13 @@ TopoDS_Shape Datum::getShape() const return sh.getShape(); } -App::DocumentObject *Datum::getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const +App::DocumentObject* Datum::getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth +) const { // For the sake of simplicity, we don't bother to check for subname, just // return the shape as it is, because a datum object only holds shape with @@ -65,22 +70,28 @@ App::DocumentObject *Datum::getSubObject(const char *subname, (void)subname; (void)depth; - if(pmat && transform) + if (pmat && transform) { *pmat *= Placement.getValue().toMatrix(); + } - if(!pyObj) + if (!pyObj) { return const_cast(this); + } Base::PyGILStateLocker lock; - PY_TRY { + PY_TRY + { TopoShape ts(getShape().Located(TopLoc_Location())); - if(pmat && !ts.isNull()) - ts.transformShape(*pmat,false,true); - *pyObj = Py::new_reference_to(shape2pyshape(ts.getShape())); + if (pmat && !ts.isNull()) { + ts.transformShape(*pmat, false, true); + } + *pyObj = Py::new_reference_to(shape2pyshape(ts.getShape())); return const_cast(this); - } PY_CATCH_OCC + } + PY_CATCH_OCC } -Base::Vector3d Datum::getBasePoint () const { +Base::Vector3d Datum::getBasePoint() const +{ return Placement.getValue().getPosition(); } diff --git a/src/Mod/Part/App/DatumFeature.h b/src/Mod/Part/App/DatumFeature.h index 05b858df31..e1ffecfc00 100644 --- a/src/Mod/Part/App/DatumFeature.h +++ b/src/Mod/Part/App/DatumFeature.h @@ -37,14 +37,14 @@ namespace Part // This generic class is defined here so that the Sketcher module can access datum features // without creating a dependency on PartDesign -class PartExport Datum : public Part::Feature, public Part::AttachExtension +class PartExport Datum: public Part::Feature, public Part::AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::Datum); public: Datum(); ~Datum() override; - //short mustExecute(); + // short mustExecute(); /// returns the type name of the view provider const char* getViewProviderName() const override = 0; @@ -53,15 +53,21 @@ public: virtual TopoDS_Shape getShape() const; /// Returns a point of the feature it counts as it's base - virtual Base::Vector3d getBasePoint () const; + virtual Base::Vector3d getBasePoint() const; + + App::DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* mat, + bool transform, + int depth + ) const override; - App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, - Base::Matrix4D *mat, bool transform, int depth) const override; protected: void onDocumentRestored() override; }; -} //namespace Part +} // namespace Part -#endif // PART_DATUMFEATURE_H +#endif // PART_DATUMFEATURE_H diff --git a/src/Mod/Part/App/Datums.h b/src/Mod/Part/App/Datums.h index 4883ec441d..750d4bb59f 100644 --- a/src/Mod/Part/App/Datums.h +++ b/src/Mod/Part/App/Datums.h @@ -34,55 +34,59 @@ namespace Part { -class PartExport DatumPlane : public App::Plane, public AttachExtension +class PartExport DatumPlane: public App::Plane, public AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::DatumPlane); public: DatumPlane(); ~DatumPlane() override = default; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPlane"; } }; -class PartExport DatumLine : public App::Line, public AttachExtension +class PartExport DatumLine: public App::Line, public AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::DatumLine); public: DatumLine(); ~DatumLine() override = default; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderLine"; } }; -class PartExport DatumPoint : public App::Point, public AttachExtension +class PartExport DatumPoint: public App::Point, public AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::DatumPoint); public: DatumPoint(); ~DatumPoint() override = default; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPoint"; } }; -class PartExport LocalCoordinateSystem : public App::LocalCoordinateSystem, public AttachExtension +class PartExport LocalCoordinateSystem: public App::LocalCoordinateSystem, public AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::LocalCoordinateSystem); public: LocalCoordinateSystem(); ~LocalCoordinateSystem() override = default; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderLCS"; } }; -} //namespace Part +} // namespace Part -#endif // PART_DATUMS_H +#endif // PART_DATUMS_H diff --git a/src/Mod/Part/App/Ellipse.pyi b/src/Mod/Part/App/Ellipse.pyi index 8e94479a8d..8ede6845f8 100644 --- a/src/Mod/Part/App/Ellipse.pyi +++ b/src/Mod/Part/App/Ellipse.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from Conic import Conic from typing import Final - @export( Twin="GeomEllipse", TwinPointer="GeomEllipse", diff --git a/src/Mod/Part/App/EllipsePyImp.cpp b/src/Mod/Part/App/EllipsePyImp.cpp index 0dc3286bb1..708d39c4e2 100644 --- a/src/Mod/Part/App/EllipsePyImp.cpp +++ b/src/Mod/Part/App/EllipsePyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -45,7 +45,7 @@ std::string EllipsePy::representation() const return ""; } -PyObject *EllipsePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* EllipsePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of EllipsePy and the Twin object return new EllipsePy(new GeomEllipse); @@ -54,7 +54,7 @@ PyObject *EllipsePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Py // constructor method int EllipsePy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(getGeomEllipsePtr()->handle()); ellipse->SetMajorRadius(2.0); @@ -62,32 +62,40 @@ int EllipsePy::PyInit(PyObject* args, PyObject* kwds) return 0; } - static const std::array keywords_e {"Ellipse", nullptr}; + static const std::array keywords_e {"Ellipse", nullptr}; PyErr_Clear(); - PyObject *pElips; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!",keywords_e, &(EllipsePy::Type), &pElips)) { + PyObject* pElips; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_e, &(EllipsePy::Type), &pElips)) { EllipsePy* pEllipse = static_cast(pElips); - Handle(Geom_Ellipse) Elips1 = Handle(Geom_Ellipse)::DownCast - (pEllipse->getGeomEllipsePtr()->handle()); - Handle(Geom_Ellipse) Elips2 = Handle(Geom_Ellipse)::DownCast - (this->getGeomEllipsePtr()->handle()); + Handle(Geom_Ellipse) Elips1 = Handle(Geom_Ellipse)::DownCast( + pEllipse->getGeomEllipsePtr()->handle() + ); + Handle(Geom_Ellipse) Elips2 = Handle(Geom_Ellipse)::DownCast( + this->getGeomEllipsePtr()->handle() + ); Elips2->SetElips(Elips1->Elips()); return 0; } - static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; + static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ssc, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ssc, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakeEllipse me(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakeEllipse me(gp_Pnt(v1.x, v1.y, v1.z), gp_Pnt(v2.x, v2.y, v2.z), gp_Pnt(v3.x, v3.y, v3.z)); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; @@ -98,16 +106,22 @@ int EllipsePy::PyInit(PyObject* args, PyObject* kwds) return 0; } - static const std::array keywords_cmm {"Center", "MajorRadius", "MinorRadius", nullptr}; + static const std::array keywords_cmm {"Center", "MajorRadius", "MinorRadius", nullptr}; PyErr_Clear(); - PyObject *pV; + PyObject* pV; double major, minor; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!dd", keywords_cmm, - &(Base::VectorPy::Type), &pV, - &major, &minor)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!dd", + keywords_cmm, + &(Base::VectorPy::Type), + &pV, + &major, + &minor + )) { Base::Vector3d c = static_cast(pV)->value(); - GC_MakeEllipse me(gp_Ax2(gp_Pnt(c.x,c.y,c.z), gp_Dir(0.0,0.0,1.0)), - major, minor); + GC_MakeEllipse me(gp_Ax2(gp_Pnt(c.x, c.y, c.z), gp_Dir(0.0, 0.0, 1.0)), major, minor); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; @@ -118,11 +132,14 @@ int EllipsePy::PyInit(PyObject* args, PyObject* kwds) return 0; } - PyErr_SetString(PyExc_TypeError, "Ellipse constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Ellipse constructor accepts:\n" "-- empty parameter list\n" "-- Ellipse\n" "-- Point, double, double\n" - "-- Point, Point, Point"); + "-- Point, Point, Point" + ); return -1; } @@ -170,7 +187,7 @@ Py::Object EllipsePy::getFocus2() const return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -PyObject *EllipsePy::getCustomAttributes(const char* /*attr*/) const +PyObject* EllipsePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ExtrusionHelper.cpp b/src/Mod/Part/App/ExtrusionHelper.cpp index bc3b273192..a8548d27ea 100644 --- a/src/Mod/Part/App/ExtrusionHelper.cpp +++ b/src/Mod/Part/App/ExtrusionHelper.cpp @@ -24,21 +24,21 @@ #include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -55,15 +55,17 @@ using namespace Part; ExtrusionHelper::ExtrusionHelper() = default; -void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, - const gp_Dir& direction, - const double LengthFwd, - const double LengthRev, - const double AngleFwd, - const double AngleRev, - bool isSolid, - std::list& drafts, - bool isPartDesign) +void ExtrusionHelper::makeDraft( + const TopoDS_Shape& shape, + const gp_Dir& direction, + const double LengthFwd, + const double LengthRev, + const double AngleFwd, + const double AngleRev, + bool isSolid, + std::list& drafts, + bool isPartDesign +) { std::vector> wiresections; @@ -89,13 +91,15 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, // we can omit the source shape as loft section bool bMid = !bFwd || !bRev || -1.0 * AngleFwd != AngleRev; - if (shape.IsNull()) + if (shape.IsNull()) { Standard_Failure::Raise("Not a valid shape"); + } // store all wires of the shape into an array size_t numWires = addWiresToWireSections(wiresections); - if (numWires == 0) + if (numWires == 0) { Standard_Failure::Raise("Extrusion: Input must not only consist if a vertex"); + } // to store the sections for the loft std::list list_of_sections; @@ -103,7 +107,10 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, // we need for all found wires an offset copy of them // we store them in an array TopoDS_Wire offsetWire; - std::vector> extrusionSections(wiresections.size(), std::vector()); + std::vector> extrusionSections( + wiresections.size(), + std::vector() + ); size_t rows = 0; int numEdges = 0; @@ -120,8 +127,9 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, BRepBuilderAPI_MakeFace mkFace(TopoDS::Wire(singleWire)); auto tempFace = mkFace.Shape(); BRepPrimAPI_MakePrism mkPrism(tempFace, vecFwd); - if (!mkPrism.IsDone()) + if (!mkPrism.IsDone()) { Standard_Failure::Raise("Extrusion: Generating prism failed"); + } singlePrism = mkPrism.Shape(); resultPrisms.push_back(singlePrism); } @@ -135,8 +143,9 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, // count the number of inner wires int numInnerWires = 0; for (auto isInner : isInnerWire) { - if (isInner) + if (isInner) { ++numInnerWires; + } } // at first create offset wires for the reversed part of extrusion @@ -159,16 +168,32 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, createTaperedPrismOffset(TopoDS::Wire(singleWire), vecRev, distanceRev, true, offsetWire); } else { - // there is an OCC bug with single-edge wires (circles), see inside createTaperedPrismOffset - if (numEdges > 1 || !isPartDesign) + // there is an OCC bug with single-edge wires (circles), see inside + // createTaperedPrismOffset + if (numEdges > 1 || !isPartDesign) { // inner wires must get the negated offset - createTaperedPrismOffset(TopoDS::Wire(singleWire), vecRev, -distanceRev, true, offsetWire); - else + createTaperedPrismOffset( + TopoDS::Wire(singleWire), + vecRev, + -distanceRev, + true, + offsetWire + ); + } + else { // circles in PartDesign must not get the negated offset - createTaperedPrismOffset(TopoDS::Wire(singleWire), vecRev, distanceRev, true, offsetWire); + createTaperedPrismOffset( + TopoDS::Wire(singleWire), + vecRev, + distanceRev, + true, + offsetWire + ); + } } - if (offsetWire.IsNull()) + if (offsetWire.IsNull()) { return; + } extrusionSections[rows].push_back(offsetWire); } ++rows; @@ -204,19 +229,41 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, // create an offset copy of the wire if (!isInnerWire[rows]) { // this is an outer wire - createTaperedPrismOffset(TopoDS::Wire(singleWire), vecFwd, distanceFwd, false, offsetWire); + createTaperedPrismOffset( + TopoDS::Wire(singleWire), + vecFwd, + distanceFwd, + false, + offsetWire + ); } else { - // there is an OCC bug with single-edge wires (circles), see inside createTaperedPrismOffset - if (numEdges > 1 || !isPartDesign) + // there is an OCC bug with single-edge wires (circles), see inside + // createTaperedPrismOffset + if (numEdges > 1 || !isPartDesign) { // inner wires must get the negated offset - createTaperedPrismOffset(TopoDS::Wire(singleWire), vecFwd, -distanceFwd, false, offsetWire); - else + createTaperedPrismOffset( + TopoDS::Wire(singleWire), + vecFwd, + -distanceFwd, + false, + offsetWire + ); + } + else { // circles in PartDesign must not get the negated offset - createTaperedPrismOffset(TopoDS::Wire(singleWire), vecFwd, distanceFwd, false, offsetWire); + createTaperedPrismOffset( + TopoDS::Wire(singleWire), + vecFwd, + distanceFwd, + false, + offsetWire + ); + } } - if (offsetWire.IsNull()) + if (offsetWire.IsNull()) { return; + } extrusionSections[rows].push_back(offsetWire); } ++rows; @@ -231,14 +278,17 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, BRepOffsetAPI_ThruSections mkTS(isSolid, /*ruled=*/Standard_True, Precision::Confusion()); for (auto& singleWire : wires) { - if (singleWire.ShapeType() == TopAbs_VERTEX) + if (singleWire.ShapeType() == TopAbs_VERTEX) { mkTS.AddVertex(TopoDS::Vertex(singleWire)); - else + } + else { mkTS.AddWire(TopoDS::Wire(singleWire)); + } } mkTS.Build(); - if (!mkTS.IsDone()) + if (!mkTS.IsDone()) { Standard_Failure::Raise("Extrusion: Loft could not be built"); + } shells.push_back(mkTS.Shape()); } @@ -246,8 +296,8 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, if (isSolid) { // we only need to cut if we have inner wires if (numInnerWires > 0) { - // we take every outer wire prism and cut subsequently all inner wires prisms from it - // every resulting shape is the final drafted extrusion shape + // we take every outer wire prism and cut subsequently all inner wires prisms from + // it every resulting shape is the final drafted extrusion shape GProp_GProps tempProperties; Standard_Real momentOfInertiaInitial; Standard_Real momentOfInertiaFinal; @@ -266,17 +316,24 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, } // get MomentOfInertia of first shape BRepGProp::VolumeProperties(*itOuter, tempProperties); - momentOfInertiaInitial = tempProperties.MomentOfInertia(gp_Ax1(gp_Pnt(), direction)); + momentOfInertiaInitial = tempProperties.MomentOfInertia( + gp_Ax1(gp_Pnt(), direction) + ); FCBRepAlgoAPI_Cut mkCut(*itOuter, *itInner); - if (!mkCut.IsDone()) + if (!mkCut.IsDone()) { Standard_Failure::Raise("Extrusion: Final cut out failed"); + } BRepGProp::VolumeProperties(mkCut.Shape(), tempProperties); - momentOfInertiaFinal = tempProperties.MomentOfInertia(gp_Ax1(gp_Pnt(), direction)); - // if the whole shape was cut away the resulting shape is not Null but its MomentOfInertia is 0.0 - // therefore we have a valid cut if the MomentOfInertia is not zero and changed + momentOfInertiaFinal = tempProperties.MomentOfInertia( + gp_Ax1(gp_Pnt(), direction) + ); + // if the whole shape was cut away the resulting shape is not Null but its + // MomentOfInertia is 0.0 therefore we have a valid cut if the + // MomentOfInertia is not zero and changed if ((momentOfInertiaInitial != momentOfInertiaFinal) && (momentOfInertiaFinal > Precision::Confusion())) { - // immediately update the outer shape since more inner wire prism might cut it + // immediately update the outer shape since more inner wire prism might + // cut it *itOuter = mkCut.Shape(); } ++isInnerWireIteratorLoop; @@ -285,16 +342,19 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, ++isInnerWireIterator; } } - else + else { // we already have the results - for (const auto & shell : shells) + for (const auto& shell : shells) { drafts.push_back(shell); + } + } } - else { // no solid + else { // no solid BRepBuilderAPI_Sewing sewer; sewer.SetTolerance(Precision::Confusion()); - for (TopoDS_Shape& s : shells) + for (TopoDS_Shape& s : shells) { sewer.Add(s); + } sewer.Perform(); drafts.push_back(sewer.SewedShape()); } @@ -310,14 +370,20 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, } } -void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_Dir direction, - std::vector&checklist, bool forInner, std::vector prisms) +void ExtrusionHelper::checkInnerWires( + std::vector& isInnerWire, + const gp_Dir direction, + std::vector& checklist, + bool forInner, + std::vector prisms +) { // store the number of wires to be checked size_t numCheckWiresInitial = 0; for (auto checks : checklist) { - if (checks) + if (checks) { ++numCheckWiresInitial; + } } GProp_GProps tempProperties; Standard_Real momentOfInertiaInitial; @@ -348,12 +414,13 @@ void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_D BRepGProp::VolumeProperties(*itInner, tempProperties); momentOfInertiaInitial = tempProperties.MomentOfInertia(gp_Ax1(gp_Pnt(), direction)); FCBRepAlgoAPI_Cut mkCut(*itInner, *itOuter); - if (!mkCut.IsDone()) + if (!mkCut.IsDone()) { Standard_Failure::Raise("Extrusion: Cut out failed"); + } BRepGProp::VolumeProperties(mkCut.Shape(), tempProperties); momentOfInertiaFinal = tempProperties.MomentOfInertia(gp_Ax1(gp_Pnt(), direction)); - // if the whole shape was cut away the resulting shape is not Null but its MomentOfInertia is 0.0 - // therefore we have an inner wire if the MomentOfInertia is not zero and changed + // if the whole shape was cut away the resulting shape is not Null but its MomentOfInertia + // is 0.0 therefore we have an inner wire if the MomentOfInertia is not zero and changed if ((momentOfInertiaInitial != momentOfInertiaFinal) && (momentOfInertiaFinal > Precision::Confusion())) { *isInnerWireIterator = !forInner; @@ -363,10 +430,11 @@ void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_D } ++toCheckIteratorInner; } - if (saveIsInnerWireIterator == *isInnerWireIterator) + if (saveIsInnerWireIterator == *isInnerWireIterator) { // nothing was changed and we can remove it from the list to be checked // but we cannot do this before the for loop was fully run toDisable[outer] = true; + } ++isInnerWireIterator; ++toCheckIterator; } @@ -374,8 +442,9 @@ void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_D // cancel prisms from the checklist whose wire state did not change size_t i = 0; for (auto disable : toDisable) { - if (disable) + if (disable) { checklist[i] = false; + } ++i; } @@ -401,27 +470,34 @@ void ExtrusionHelper::checkInnerWires(std::vector& isInnerWire, const gp_D } ++i; } - Base::Console().warning("Extrusion: too many self-intersection structures!\n\ + Base::Console().warning( + "Extrusion: too many self-intersection structures!\n\ Impossible to determine what structure is an inner one.\n\ - All undeterminable structures will therefore be taken as outer ones.\n"); + All undeterminable structures will therefore be taken as outer ones.\n" + ); } // recursively call the function until all wires are checked - if (numCheckWires > 1) + if (numCheckWires > 1) { checkInnerWires(isInnerWire, direction, checklist, !forInner, prisms); + } } -void ExtrusionHelper::createTaperedPrismOffset(TopoDS_Wire sourceWire, - const gp_Vec& translation, - double offset, - bool isSecond, - TopoDS_Wire& result) { +void ExtrusionHelper::createTaperedPrismOffset( + TopoDS_Wire sourceWire, + const gp_Vec& translation, + double offset, + bool isSecond, + TopoDS_Wire& result +) +{ // if the wire consists of a single edge which has applied a placement // then this placement must be reset because otherwise // BRepOffsetAPI_MakeOffset shows weird behaviour by applying the placement, see // https://dev.opencascade.org/content/brepoffsetapimakeoffset-wire-and-face-odd-occt-740 - // therefore we use here the workaround of BRepOffsetAPI_MakeOffsetFix and not BRepOffsetAPI_MakeOffset + // therefore we use here the workaround of BRepOffsetAPI_MakeOffsetFix and not + // BRepOffsetAPI_MakeOffset gp_Trsf tempTransform; tempTransform.SetTranslation(translation); @@ -451,12 +527,18 @@ void ExtrusionHelper::createTaperedPrismOffset(TopoDS_Wire sourceWire, offsetShape = movedSourceWire; } if (offsetShape.IsNull()) { - if (isSecond) - Base::Console().error("Extrusion: end face of tapered against extrusion is empty\n" \ - "This means most probably that the against taper angle is too large or small.\n"); - else - Base::Console().error("Extrusion: end face of tapered along extrusion is empty\n" \ - "This means most probably that the along taper angle is too large or small.\n"); + if (isSecond) { + Base::Console().error( + "Extrusion: end face of tapered against extrusion is empty\n" + "This means most probably that the against taper angle is too large or small.\n" + ); + } + else { + Base::Console().error( + "Extrusion: end face of tapered along extrusion is empty\n" + "This means most probably that the along taper angle is too large or small.\n" + ); + } Standard_Failure::Raise("Extrusion: end face of tapered extrusion is empty"); } // assure we return a wire and no edge @@ -471,22 +553,30 @@ void ExtrusionHelper::createTaperedPrismOffset(TopoDS_Wire sourceWire, else { // this happens usually if type == TopAbs_COMPOUND and means the angle is too small // since this is a common mistake users will quickly do, issue a warning dialog - // FIXME: Standard_Failure::Raise or App::DocumentObjectExecReturn don't output the message to the user + // FIXME: Standard_Failure::Raise or App::DocumentObjectExecReturn don't output the message + // to the user result = TopoDS_Wire(); - if (isSecond) - Base::Console().error("Extrusion: type of against extrusion end face is not supported.\n" \ - "This means most probably that the against taper angle is too large or small.\n"); - else - Base::Console().error("Extrusion: type of along extrusion is not supported.\n" \ - "This means most probably that the along taper angle is too large or small.\n"); + if (isSecond) { + Base::Console().error( + "Extrusion: type of against extrusion end face is not supported.\n" + "This means most probably that the against taper angle is too large or small.\n" + ); + } + else { + Base::Console().error( + "Extrusion: type of along extrusion is not supported.\n" + "This means most probably that the along taper angle is too large or small.\n" + ); + } } - } -void ExtrusionHelper::makeElementDraft(const ExtrusionParameters& params, - const TopoShape& _shape, - std::vector& drafts, - App::StringHasherRef hasher) +void ExtrusionHelper::makeElementDraft( + const ExtrusionParameters& params, + const TopoShape& _shape, + std::vector& drafts, + App::StringHasherRef hasher +) { double distanceFwd = tan(params.taperAngleFwd) * params.lengthFwd; double distanceRev = tan(params.taperAngleRev) * params.lengthRev; @@ -529,7 +619,8 @@ void ExtrusionHelper::makeElementDraft(const ExtrusionParameters& params, innerWires.makeElementCompound( wires, "", - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); makeElementDraft(params, innerWires, inner, hasher); if (inner.empty()) { Standard_Failure::Raise("Failed to make drafted extrusion with inner hole"); @@ -563,11 +654,13 @@ void ExtrusionHelper::makeElementDraft(const ExtrusionParameters& params, std::vector list_of_sections; if (bRev) { TopoDS_Wire offsetWire; - createTaperedPrismOffset(TopoDS::Wire(sourceWire.getShape()), - vecRev, - distanceRev, - false, - offsetWire); + createTaperedPrismOffset( + TopoDS::Wire(sourceWire.getShape()), + vecRev, + distanceRev, + false, + offsetWire + ); list_of_sections.push_back(TopoShape(offsetWire, sourceWire.Tag)); } @@ -579,11 +672,13 @@ void ExtrusionHelper::makeElementDraft(const ExtrusionParameters& params, // finally. Forward extrusion offset wire. if (bFwd) { TopoDS_Wire offsetWire; - createTaperedPrismOffset(TopoDS::Wire(sourceWire.getShape()), - vecFwd, - distanceFwd, - false, - offsetWire); + createTaperedPrismOffset( + TopoDS::Wire(sourceWire.getShape()), + vecFwd, + distanceFwd, + false, + offsetWire + ); list_of_sections.push_back(TopoShape(offsetWire, sourceWire.Tag)); } @@ -593,8 +688,10 @@ void ExtrusionHelper::makeElementDraft(const ExtrusionParameters& params, #endif // make loft - BRepOffsetAPI_ThruSections mkGenerator(params.solid ? Standard_True : Standard_False, - /*ruled=*/Standard_True); + BRepOffsetAPI_ThruSections mkGenerator( + params.solid ? Standard_True : Standard_False, + /*ruled=*/Standard_True + ); for (auto& s : list_of_sections) { mkGenerator.AddWire(TopoDS::Wire(s.getShape())); } diff --git a/src/Mod/Part/App/ExtrusionHelper.h b/src/Mod/Part/App/ExtrusionHelper.h index 9c59630aa1..61953cb718 100644 --- a/src/Mod/Part/App/ExtrusionHelper.h +++ b/src/Mod/Part/App/ExtrusionHelper.h @@ -63,40 +63,52 @@ public: /** * @brief makeDraft: creates a drafted extrusion shape out of the input 2D shape */ - static void makeDraft(const TopoDS_Shape& shape, - const gp_Dir& direction, - const double LengthFwd, - const double LengthRev, - const double AngleFwd, - const double AngleRev, - bool isSolid, - std::list& drafts, - bool isPartDesign); + static void makeDraft( + const TopoDS_Shape& shape, + const gp_Dir& direction, + const double LengthFwd, + const double LengthRev, + const double AngleFwd, + const double AngleRev, + bool isSolid, + std::list& drafts, + bool isPartDesign + ); /** - * @brief checkInnerWires: Checks what wires are inner ones by taking a set of prisms created with every wire. - * The prisms are cut from each other. If the moment of inertia thereby changes, the prism wire is an inner wire. - * Inner wires can have nested inner wires that are then in fact outer wires. - * Therefore checkInnerWires is called recursively until all wires are checked. + * @brief checkInnerWires: Checks what wires are inner ones by taking a set of prisms created + * with every wire. The prisms are cut from each other. If the moment of inertia thereby + * changes, the prism wire is an inner wire. Inner wires can have nested inner wires that are + * then in fact outer wires. Therefore checkInnerWires is called recursively until all wires are + * checked. */ - static void checkInnerWires(std::vector& isInnerWire, const gp_Dir direction, - std::vector& checklist, bool forInner, std::vector prisms); + static void checkInnerWires( + std::vector& isInnerWire, + const gp_Dir direction, + std::vector& checklist, + bool forInner, + std::vector prisms + ); /** * @brief createTaperedPrismOffset: creates an offset wire from the sourceWire in the specified * translation. isSecond determines if the wire is used for the 2nd extrusion direction. */ - static void createTaperedPrismOffset(TopoDS_Wire sourceWire, - const gp_Vec& translation, - double offset, - bool isSecond, - TopoDS_Wire& result); + static void createTaperedPrismOffset( + TopoDS_Wire sourceWire, + const gp_Vec& translation, + double offset, + bool isSecond, + TopoDS_Wire& result + ); /** Same as makeDraft() with support of element mapping */ - static void makeElementDraft(const ExtrusionParameters& params, - const TopoShape&, - std::vector&, - App::StringHasherRef hasher); + static void makeElementDraft( + const ExtrusionParameters& params, + const TopoShape&, + std::vector&, + App::StringHasherRef hasher + ); }; -} //namespace Part +} // namespace Part -#endif // PART_EXTRUSIONHELPER_H +#endif // PART_EXTRUSIONHELPER_H diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.cpp b/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.cpp index 7068225c41..6fcba9efc5 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.cpp +++ b/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.cpp @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #include #include @@ -44,10 +44,12 @@ FCBRepAlgoAPI_BooleanOperation::FCBRepAlgoAPI_BooleanOperation() } -FCBRepAlgoAPI_BooleanOperation::FCBRepAlgoAPI_BooleanOperation(const TopoDS_Shape& theS1, - const TopoDS_Shape& theS2, - const BOPAlgo_Operation theOperation) -: BRepAlgoAPI_BooleanOperation(theS1, theS2, theOperation) +FCBRepAlgoAPI_BooleanOperation::FCBRepAlgoAPI_BooleanOperation( + const TopoDS_Shape& theS1, + const TopoDS_Shape& theS2, + const BOPAlgo_Operation theOperation +) + : BRepAlgoAPI_BooleanOperation(theS1, theS2, theOperation) { if (!BRepCheck_Analyzer(theS1).IsValid()) { Base::Console().warning("Base shape is not valid for boolean operation"); @@ -68,46 +70,59 @@ void FCBRepAlgoAPI_BooleanOperation::setAutoFuzzy() } -void FCBRepAlgoAPIHelper::setAutoFuzzy(BRepAlgoAPI_BooleanOperation* op) { +void FCBRepAlgoAPIHelper::setAutoFuzzy(BRepAlgoAPI_BooleanOperation* op) +{ Bnd_Box bounds; - for (TopTools_ListOfShape::Iterator it(op->Arguments()); it.More(); it.Next()) + for (TopTools_ListOfShape::Iterator it(op->Arguments()); it.More(); it.Next()) { BRepBndLib::Add(it.Value(), bounds); - for (TopTools_ListOfShape::Iterator it(op->Tools()); it.More(); it.Next()) + } + for (TopTools_ListOfShape::Iterator it(op->Tools()); it.More(); it.Next()) { BRepBndLib::Add(it.Value(), bounds); - op->SetFuzzyValue(Part::FuzzyHelper::getBooleanFuzzy() * sqrt(bounds.SquareExtent()) * Precision::Confusion()); + } + op->SetFuzzyValue( + Part::FuzzyHelper::getBooleanFuzzy() * sqrt(bounds.SquareExtent()) * Precision::Confusion() + ); } -void FCBRepAlgoAPIHelper::setAutoFuzzy(BRepAlgoAPI_BuilderAlgo* op) { +void FCBRepAlgoAPIHelper::setAutoFuzzy(BRepAlgoAPI_BuilderAlgo* op) +{ Bnd_Box bounds; - for (TopTools_ListOfShape::Iterator it(op->Arguments()); it.More(); it.Next()) + for (TopTools_ListOfShape::Iterator it(op->Arguments()); it.More(); it.Next()) { BRepBndLib::Add(it.Value(), bounds); - op->SetFuzzyValue(Part::FuzzyHelper::getBooleanFuzzy() * sqrt(bounds.SquareExtent()) * Precision::Confusion()); + } + op->SetFuzzyValue( + Part::FuzzyHelper::getBooleanFuzzy() * sqrt(bounds.SquareExtent()) * Precision::Confusion() + ); } -void FCBRepAlgoAPI_BooleanOperation::Build() { +void FCBRepAlgoAPI_BooleanOperation::Build() +{ Message_ProgressRange progressRange; Build(progressRange); } -void FCBRepAlgoAPI_BooleanOperation::Build(const Message_ProgressRange& progressRange) { +void FCBRepAlgoAPI_BooleanOperation::Build(const Message_ProgressRange& progressRange) +{ if (progressRange.UserBreak()) { Standard_ConstructionError::Raise("User aborted"); } - if (myOperation == BOPAlgo_CUT && myArguments.Size() == 1 && myTools.Size() == 1 && myTools.First().ShapeType() == TopAbs_COMPOUND) { + if (myOperation == BOPAlgo_CUT && myArguments.Size() == 1 && myTools.Size() == 1 + && myTools.First().ShapeType() == TopAbs_COMPOUND) { // cut argument and compound tool TopTools_ListOfShape myOriginalArguments = myArguments; TopTools_ListOfShape myOriginalTools = myTools; RecursiveCutFusedTools(myOriginalArguments, myOriginalTools.First()); myArguments = myOriginalArguments; myTools = myOriginalTools; - - } else if (myOperation==BOPAlgo_CUT && myArguments.Size()==1 && myArguments.First().ShapeType() == TopAbs_COMPOUND) { + } + else if (myOperation == BOPAlgo_CUT && myArguments.Size() == 1 + && myArguments.First().ShapeType() == TopAbs_COMPOUND) { // cut compound argument TopTools_ListOfShape myOriginalArguments = myArguments; RecursiveCutCompound(myOriginalArguments.First()); myArguments = myOriginalArguments; - - } else { + } + else { #if OCC_VERSION_HEX >= 0x070600 BRepAlgoAPI_BooleanOperation::Build(progressRange); #else @@ -119,18 +134,23 @@ void FCBRepAlgoAPI_BooleanOperation::Build(const Message_ProgressRange& progress } } -void FCBRepAlgoAPI_BooleanOperation::RecursiveAddTools(const TopoDS_Shape& theTool) { +void FCBRepAlgoAPI_BooleanOperation::RecursiveAddTools(const TopoDS_Shape& theTool) +{ TopoDS_Iterator it(theTool); for (; it.More(); it.Next()) { if (it.Value().ShapeType() == TopAbs_COMPOUND) { RecursiveAddTools(it.Value()); - } else { + } + else { myTools.Append(it.Value()); } } } -void FCBRepAlgoAPI_BooleanOperation::RecursiveCutFusedTools(const TopTools_ListOfShape& theOriginalArguments, const TopoDS_Shape& theTool) +void FCBRepAlgoAPI_BooleanOperation::RecursiveCutFusedTools( + const TopTools_ListOfShape& theOriginalArguments, + const TopoDS_Shape& theTool +) { // get a list of shapes in the tool compound myTools.Clear(); @@ -164,7 +184,8 @@ void FCBRepAlgoAPI_BooleanOperation::RecursiveCutFusedTools(const TopTools_ListO Build(); } -void FCBRepAlgoAPI_BooleanOperation::RecursiveCutCompound(const TopoDS_Shape& theArgument) { +void FCBRepAlgoAPI_BooleanOperation::RecursiveCutCompound(const TopoDS_Shape& theArgument) +{ BRep_Builder builder; TopoDS_Compound comp; builder.MakeCompound(comp); @@ -187,4 +208,3 @@ void FCBRepAlgoAPI_BooleanOperation::RecursiveCutCompound(const TopoDS_Shape& th // result is a compound of individual cuts myShape = comp; } - diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.h b/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.h index 6ab1fb5ae3..0167625976 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.h +++ b/src/Mod/Part/App/FCBRepAlgoAPI_BooleanOperation.h @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #ifndef FCREPALGOAPIBOOLEANOPERATION_H #define FCREPALGOAPIBOOLEANOPERATION_H @@ -39,10 +39,9 @@ public: static void setAutoFuzzy(BRepAlgoAPI_BuilderAlgo* op); }; -class FCBRepAlgoAPI_BooleanOperation : public BRepAlgoAPI_BooleanOperation +class FCBRepAlgoAPI_BooleanOperation: public BRepAlgoAPI_BooleanOperation { public: - DEFINE_STANDARD_ALLOC //! Empty constructor @@ -51,8 +50,10 @@ public: // set fuzzyness based on size void setAutoFuzzy(); - // not an override - real Build() has optionals, sadly type of those optionals that are differs between OCCT versions - Standard_EXPORT virtual void Build(); // NOLINT(clang-diagnostic-overloaded-virtual, -Woverloaded-virtual) + // not an override - real Build() has optionals, sadly type of those optionals that are differs + // between OCCT versions + Standard_EXPORT virtual void Build(); // NOLINT(clang-diagnostic-overloaded-virtual, + // -Woverloaded-virtual) #if OCC_VERSION_HEX >= 0x070600 Standard_EXPORT void Build(const Message_ProgressRange& progressRange) Standard_OVERRIDE; @@ -60,18 +61,21 @@ public: Standard_EXPORT virtual void Build(const Message_ProgressRange& progressRange); #endif -protected: //! @name Constructors - - //! Constructor to perform Boolean operation on only two arguments. - //! Obsolete - Standard_EXPORT FCBRepAlgoAPI_BooleanOperation(const TopoDS_Shape& theS1, - const TopoDS_Shape& theS2, - BOPAlgo_Operation theOperation); +protected: //! @name Constructors + //! Constructor to perform Boolean operation on only two arguments. + //! Obsolete + Standard_EXPORT FCBRepAlgoAPI_BooleanOperation( + const TopoDS_Shape& theS1, + const TopoDS_Shape& theS2, + BOPAlgo_Operation theOperation + ); private: - Standard_EXPORT void RecursiveAddTools(const TopoDS_Shape& theTool); - Standard_EXPORT void RecursiveCutFusedTools(const TopTools_ListOfShape& theOriginalArguments, - const TopoDS_Shape& theTool); - Standard_EXPORT void RecursiveCutCompound(const TopoDS_Shape& theArgument); + Standard_EXPORT void RecursiveAddTools(const TopoDS_Shape& theTool); + Standard_EXPORT void RecursiveCutFusedTools( + const TopTools_ListOfShape& theOriginalArguments, + const TopoDS_Shape& theTool + ); + Standard_EXPORT void RecursiveCutCompound(const TopoDS_Shape& theArgument); }; #endif diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Common.cpp b/src/Mod/Part/App/FCBRepAlgoAPI_Common.cpp index dfeec78f07..f4d72f74cc 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Common.cpp +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Common.cpp @@ -23,20 +23,19 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #include #include FCBRepAlgoAPI_Common::FCBRepAlgoAPI_Common() { - myOperation=BOPAlgo_COMMON; + myOperation = BOPAlgo_COMMON; } -FCBRepAlgoAPI_Common::FCBRepAlgoAPI_Common(const TopoDS_Shape& S1, - const TopoDS_Shape& S2) -: FCBRepAlgoAPI_BooleanOperation(S1, S2, BOPAlgo_COMMON) +FCBRepAlgoAPI_Common::FCBRepAlgoAPI_Common(const TopoDS_Shape& S1, const TopoDS_Shape& S2) + : FCBRepAlgoAPI_BooleanOperation(S1, S2, BOPAlgo_COMMON) { - Build(); + Build(); } diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Common.h b/src/Mod/Part/App/FCBRepAlgoAPI_Common.h index 38c5e3dc7f..83693acc22 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Common.h +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Common.h @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #ifndef FCREPALGOAPICOMMON_H #define FCREPALGOAPICOMMON_H @@ -32,21 +32,18 @@ #include -class FCBRepAlgoAPI_Common : public FCBRepAlgoAPI_BooleanOperation +class FCBRepAlgoAPI_Common: public FCBRepAlgoAPI_BooleanOperation { public: - DEFINE_STANDARD_ALLOC - + //! Empty constructor Standard_EXPORT FCBRepAlgoAPI_Common(); - + //! Constructor with two shapes //! -argument //! -tool //! - the type of the operation - Standard_EXPORT FCBRepAlgoAPI_Common(const TopoDS_Shape& S1, - const TopoDS_Shape& S2); - + Standard_EXPORT FCBRepAlgoAPI_Common(const TopoDS_Shape& S1, const TopoDS_Shape& S2); }; #endif diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Cut.cpp b/src/Mod/Part/App/FCBRepAlgoAPI_Cut.cpp index 04ce957704..33543541f3 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Cut.cpp +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Cut.cpp @@ -23,20 +23,19 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #include #include FCBRepAlgoAPI_Cut::FCBRepAlgoAPI_Cut() { - myOperation=BOPAlgo_CUT; + myOperation = BOPAlgo_CUT; } -FCBRepAlgoAPI_Cut::FCBRepAlgoAPI_Cut(const TopoDS_Shape& S1, - const TopoDS_Shape& S2) -: FCBRepAlgoAPI_BooleanOperation(S1, S2, BOPAlgo_CUT) +FCBRepAlgoAPI_Cut::FCBRepAlgoAPI_Cut(const TopoDS_Shape& S1, const TopoDS_Shape& S2) + : FCBRepAlgoAPI_BooleanOperation(S1, S2, BOPAlgo_CUT) { - Build(); + Build(); } diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Cut.h b/src/Mod/Part/App/FCBRepAlgoAPI_Cut.h index ba021a5668..a39322dae7 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Cut.h +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Cut.h @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #ifndef FCREPALGOAPICUT_H #define FCREPALGOAPICUT_H @@ -32,21 +32,18 @@ #include -class FCBRepAlgoAPI_Cut : public FCBRepAlgoAPI_BooleanOperation +class FCBRepAlgoAPI_Cut: public FCBRepAlgoAPI_BooleanOperation { public: - DEFINE_STANDARD_ALLOC - + //! Empty constructor Standard_EXPORT FCBRepAlgoAPI_Cut(); - + //! Constructor with two shapes //! -argument //! -tool //! - the type of the operation - Standard_EXPORT FCBRepAlgoAPI_Cut(const TopoDS_Shape& S1, - const TopoDS_Shape& S2); - + Standard_EXPORT FCBRepAlgoAPI_Cut(const TopoDS_Shape& S1, const TopoDS_Shape& S2); }; #endif diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.cpp b/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.cpp index 80e2967fbe..50ba009027 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.cpp +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.cpp @@ -23,20 +23,19 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #include #include FCBRepAlgoAPI_Fuse::FCBRepAlgoAPI_Fuse() { - myOperation=BOPAlgo_FUSE; + myOperation = BOPAlgo_FUSE; } -FCBRepAlgoAPI_Fuse::FCBRepAlgoAPI_Fuse(const TopoDS_Shape& S1, - const TopoDS_Shape& S2) -: FCBRepAlgoAPI_BooleanOperation(S1, S2, BOPAlgo_FUSE) +FCBRepAlgoAPI_Fuse::FCBRepAlgoAPI_Fuse(const TopoDS_Shape& S1, const TopoDS_Shape& S2) + : FCBRepAlgoAPI_BooleanOperation(S1, S2, BOPAlgo_FUSE) { - Build(); + Build(); } diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.h b/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.h index ffd233fb5b..cf98d71eee 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.h +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Fuse.h @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #ifndef FCREPALGOAPIFUSE_H #define FCREPALGOAPIFUSE_H @@ -32,22 +32,19 @@ #include -class FCBRepAlgoAPI_Fuse : public FCBRepAlgoAPI_BooleanOperation +class FCBRepAlgoAPI_Fuse: public FCBRepAlgoAPI_BooleanOperation { public: - DEFINE_STANDARD_ALLOC - + //! Empty constructor Standard_EXPORT FCBRepAlgoAPI_Fuse(); - + //! Constructor with two shapes //! -argument //! -tool //! - the type of the operation - Standard_EXPORT FCBRepAlgoAPI_Fuse(const TopoDS_Shape& S1, - const TopoDS_Shape& S2); - + Standard_EXPORT FCBRepAlgoAPI_Fuse(const TopoDS_Shape& S1, const TopoDS_Shape& S2); }; #endif diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp b/src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp index 3c32870874..eea94bea3c 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #include #include @@ -40,34 +40,42 @@ FCBRepAlgoAPI_Section::FCBRepAlgoAPI_Section() SetNonDestructive(Standard_True); } -FCBRepAlgoAPI_Section::FCBRepAlgoAPI_Section(const TopoDS_Shape& S1, const TopoDS_Shape& S2, const Standard_Boolean PerformNow) -: BRepAlgoAPI_Section(S1,S2,false) +FCBRepAlgoAPI_Section::FCBRepAlgoAPI_Section( + const TopoDS_Shape& S1, + const TopoDS_Shape& S2, + const Standard_Boolean PerformNow +) + : BRepAlgoAPI_Section(S1, S2, false) { - if (!BRepCheck_Analyzer(S1).IsValid()){ + if (!BRepCheck_Analyzer(S1).IsValid()) { Standard_ConstructionError::Raise("Base shape is not valid for boolean operation"); } - if (! BRepCheck_Analyzer(S2).IsValid()){ + if (!BRepCheck_Analyzer(S2).IsValid()) { Standard_ConstructionError::Raise("Tool shape is not valid for boolean operation"); } setAutoFuzzy(); SetRunParallel(Standard_True); SetNonDestructive(Standard_True); - if (PerformNow) Build(); + if (PerformNow) { + Build(); + } } -FCBRepAlgoAPI_Section::FCBRepAlgoAPI_Section -(const TopoDS_Shape& Sh, -const gp_Pln& Pl, -const Standard_Boolean PerformNow) -: -BRepAlgoAPI_Section(Sh,Pl,false) +FCBRepAlgoAPI_Section::FCBRepAlgoAPI_Section( + const TopoDS_Shape& Sh, + const gp_Pln& Pl, + const Standard_Boolean PerformNow +) + : BRepAlgoAPI_Section(Sh, Pl, false) { - if (!BRepCheck_Analyzer(Sh).IsValid()){ + if (!BRepCheck_Analyzer(Sh).IsValid()) { Standard_ConstructionError::Raise("Base shape is not valid for boolean operation"); } setAutoFuzzy(); SetRunParallel(Standard_True); - if (PerformNow) Build(); + if (PerformNow) { + Build(); + } } diff --git a/src/Mod/Part/App/FCBRepAlgoAPI_Section.h b/src/Mod/Part/App/FCBRepAlgoAPI_Section.h index 5951cbaa16..9cf3654f7a 100644 --- a/src/Mod/Part/App/FCBRepAlgoAPI_Section.h +++ b/src/Mod/Part/App/FCBRepAlgoAPI_Section.h @@ -23,8 +23,8 @@ **************************************************************************/ /** - * FCBRepAlgoAPI provides a wrapper for various OCCT functions. - */ + * FCBRepAlgoAPI provides a wrapper for various OCCT functions. + */ #ifndef FCREPALGOAPISECTION_H #define FCREPALGOAPISECTION_H @@ -33,23 +33,26 @@ #include -class FCBRepAlgoAPI_Section : public BRepAlgoAPI_Section +class FCBRepAlgoAPI_Section: public BRepAlgoAPI_Section { public: - DEFINE_STANDARD_ALLOC - + //! Empty constructor Standard_EXPORT FCBRepAlgoAPI_Section(); - + //! Constructor with two shapes //! -argument //! -tool //! - the flag: //! if =True - the algorithm is performed immediately //! Obsolete - Standard_EXPORT FCBRepAlgoAPI_Section(const TopoDS_Shape& S1, const TopoDS_Shape& S2, const Standard_Boolean PerformNow = Standard_True); + Standard_EXPORT FCBRepAlgoAPI_Section( + const TopoDS_Shape& S1, + const TopoDS_Shape& S2, + const Standard_Boolean PerformNow = Standard_True + ); //! Constructor with two shapes //! - argument @@ -57,7 +60,11 @@ public: //! - the flag: //! if =True - the algorithm is performed immediately //! Obsolete - Standard_EXPORT FCBRepAlgoAPI_Section(const TopoDS_Shape& S1, const gp_Pln& Pl, const Standard_Boolean PerformNow = Standard_True); + Standard_EXPORT FCBRepAlgoAPI_Section( + const TopoDS_Shape& S1, + const gp_Pln& Pl, + const Standard_Boolean PerformNow = Standard_True + ); // set fuzzyness based on size void setAutoFuzzy(); diff --git a/src/Mod/Part/App/FT2FC.cpp b/src/Mod/Part/App/FT2FC.cpp index 620fcaf0ad..2e63a981b3 100644 --- a/src/Mod/Part/App/FT2FC.cpp +++ b/src/Mod/Part/App/FT2FC.cpp @@ -57,63 +57,75 @@ # include # include -#include -#include +# include +# include -#include "TopoShapeWirePy.h" +# include "TopoShapeWirePy.h" -#include -#include FT_FREETYPE_H -#include FT_OUTLINE_H -#include FT_GLYPH_H -#include FT_TYPES_H +# include +# include FT_FREETYPE_H +# include FT_OUTLINE_H +# include FT_GLYPH_H +# include FT_TYPES_H -#include "FT2FC.h" +# include "FT2FC.h" -#define CLOCKWISE 0 -#define ANTICLOCKWISE 1 +# define CLOCKWISE 0 +# define ANTICLOCKWISE 1 using namespace Part; // Private function prototypes -PyObject* getGlyphContours(FT_Face FTFace, FT_ULong currchar, double PenPos, double Scale,int charNum, double tracking); +PyObject* getGlyphContours( + FT_Face FTFace, + FT_ULong currchar, + double PenPos, + double Scale, + int charNum, + double tracking +); FT_Vector getKerning(FT_Face FTFace, FT_ULong lc, FT_ULong rc); TopoDS_Wire edgesToWire(std::vector Edges); int calcClockDir(std::vector points); // for compatibility with old version - separate path & filename -PyObject* FT2FC(const Py_UCS4 *PyUString, - const size_t length, - const char *FontPath, - const char *FontName, - const double stringheight, - const double tracking) { - std::string FontSpec; - std::string tmpPath = FontPath; // can't concat const char* - std::string tmpName = FontName; - FontSpec = tmpPath + tmpName; - return (FT2FC(PyUString,length,FontSpec.c_str(),stringheight,tracking)); +PyObject* FT2FC( + const Py_UCS4* PyUString, + const size_t length, + const char* FontPath, + const char* FontName, + const double stringheight, + const double tracking +) +{ + std::string FontSpec; + std::string tmpPath = FontPath; // can't concat const char* + std::string tmpName = FontName; + FontSpec = tmpPath + tmpName; + return (FT2FC(PyUString, length, FontSpec.c_str(), stringheight, tracking)); } // get string's wires (contours) in FC/OCC coords -PyObject* FT2FC(const Py_UCS4 *PyUString, - const size_t length, - const char *FontSpec, - const double stringheight, // fc coords - const double tracking) // fc coords +PyObject* FT2FC( + const Py_UCS4* PyUString, + const size_t length, + const char* FontSpec, + const double stringheight, // fc coords + const double tracking +) // fc coords { - FT_Library FTLib; - FT_Face FTFace; - FT_Error error; - FT_Long FaceIndex = 0; // some fonts have multiple faces - FT_Vector kern; - FT_UInt FTLoadFlags = FT_LOAD_DEFAULT | FT_LOAD_NO_BITMAP; + FT_Library FTLib; + FT_Face FTFace; + FT_Error error; + FT_Long FaceIndex = 0; // some fonts have multiple faces + FT_Vector kern; + FT_UInt FTLoadFlags = FT_LOAD_DEFAULT | FT_LOAD_NO_BITMAP; std::stringstream ErrorMsg; double PenPos = 0, scalefactor; FT_ULong prevchar = 0, currchar = 0; - int cadv; + int cadv; size_t i; Py::List CharList; @@ -125,25 +137,25 @@ PyObject* FT2FC(const Py_UCS4 *PyUString, std::ifstream fontfile; -#ifdef FC_OS_WIN32 +# ifdef FC_OS_WIN32 Base::FileInfo winFI(FontSpec); fontfile.open(winFI.toStdWString().c_str(), std::ios::binary | std::ios::in); -#else +# else fontfile.open(FontSpec, std::ios::binary | std::ios::in); -#endif +# endif if (!fontfile.is_open()) { - //get indignant + // get indignant ErrorMsg << "Can not open font file: " << FontSpec; throw std::runtime_error(ErrorMsg.str()); } - fontfile.seekg (0, fontfile.end); + fontfile.seekg(0, fontfile.end); int bytesNeeded = fontfile.tellg(); fontfile.clear(); - fontfile.seekg (0, fontfile.beg); - std::unique_ptr buffer (new char[bytesNeeded]); + fontfile.seekg(0, fontfile.beg); + std::unique_ptr buffer(new char[bytesNeeded]); fontfile.read(buffer.get(), bytesNeeded); if (!fontfile) { - //get indignant + // get indignant ErrorMsg << "Can not read font file: " << FontSpec; throw std::runtime_error(ErrorMsg.str()); } @@ -156,33 +168,35 @@ PyObject* FT2FC(const Py_UCS4 *PyUString, throw std::runtime_error(ErrorMsg.str()); } - //TODO: check that FTFace is scalable? only relevant for hinting etc? + // TODO: check that FTFace is scalable? only relevant for hinting etc? // FT2 blows up if char size is not set to some non-zero value. // This sets size to 48 point. Magic. - error = FT_Set_Char_Size(FTFace, - 0, /* char_width in 1/64th of points */ - 48*64*10, /* char_height in 1/64th of points */ // increased 10X to preserve very small details - 0, /* horizontal device resolution */ - 0 ); /* vertical device resolution */ + error = FT_Set_Char_Size( + FTFace, + 0, /* char_width in 1/64th of points */ + 48 * 64 * 10, + /* char_height in 1/64th of points */ // increased 10X to preserve very small details + 0, /* horizontal device resolution */ + 0 + ); /* vertical device resolution */ if (error) { ErrorMsg << "FT_Set_Char_Size failed: " << error; throw std::runtime_error(ErrorMsg.str()); } - scalefactor = (stringheight/float(FTFace->height))/10; // divide scale by 10 to offset the 10X increased scale in FT_Set_Char_Size above - for (i=0; iheight)) + / 10; // divide scale by 10 to offset the 10X increased scale in FT_Set_Char_Size above + for (i = 0; i < length; i++) { currchar = PyUString[i]; - error = FT_Load_Char(FTFace, - currchar, - FTLoadFlags); + error = FT_Load_Char(FTFace, currchar, FTLoadFlags); if (error) { ErrorMsg << "FT_Load_Char failed: " << error; throw std::runtime_error(ErrorMsg.str()); } cadv = FTFace->glyph->advance.x; - kern = getKerning(FTFace,prevchar,currchar); + kern = getKerning(FTFace, prevchar, currchar); PenPos += kern.x; try { Py::List WireList(getGlyphContours(FTFace, currchar, PenPos, scalefactor, i, tracking), true); @@ -208,212 +222,232 @@ PyObject* FT2FC(const Py_UCS4 *PyUString, //********** FT Decompose callbacks and data defns // FT Decomp Context for 1 char -struct FTDC_Ctx { - std::vector Wires; - std::vector wDir; - std::vector Edges; - std::vector polyPoints; - FT_ULong currchar; - FT_Vector LastVert; - Handle(Geom_Surface) surf; +struct FTDC_Ctx +{ + std::vector Wires; + std::vector wDir; + std::vector Edges; + std::vector polyPoints; + FT_ULong currchar; + FT_Vector LastVert; + Handle(Geom_Surface) surf; }; // move_cb called for start of new contour. pt is xy of contour start. // p points to the context where we remember what happened previously (last point, etc) -static int move_cb(const FT_Vector* pt, void* p) { - FTDC_Ctx* dc = static_cast(p); - if (!dc->Edges.empty()){ - TopoDS_Wire newwire = edgesToWire(dc->Edges); - dc->Wires.push_back(newwire); - dc->Edges.clear(); - dc->wDir.push_back(calcClockDir(dc->polyPoints)); - dc->polyPoints.clear(); - } - dc->LastVert = *pt; - if (dc->polyPoints.empty()) { +static int move_cb(const FT_Vector* pt, void* p) +{ + FTDC_Ctx* dc = static_cast(p); + if (!dc->Edges.empty()) { + TopoDS_Wire newwire = edgesToWire(dc->Edges); + dc->Wires.push_back(newwire); + dc->Edges.clear(); + dc->wDir.push_back(calcClockDir(dc->polyPoints)); + dc->polyPoints.clear(); + } + dc->LastVert = *pt; + if (dc->polyPoints.empty()) { dc->polyPoints.emplace_back(pt->x, pt->y, 0.0); - } + } - return 0; + return 0; } // line_cb called for line segment in the current contour: line(LastVert -- pt) -static int line_cb(const FT_Vector* pt, void* p) { - FTDC_Ctx* dc = static_cast(p); - gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y); - gp_Pnt2d v2(pt->x, pt->y); - if (!v1.IsEqual(v2, Precision::Confusion())) { - Handle(Geom2d_TrimmedCurve) lseg = GCE2d_MakeSegment(v1,v2); - TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(lseg , dc->surf); - dc->Edges.push_back(edge); - dc->LastVert = *pt; - dc->polyPoints.emplace_back(pt->x, pt->y, 0.0); - } - return 0; +static int line_cb(const FT_Vector* pt, void* p) +{ + FTDC_Ctx* dc = static_cast(p); + gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y); + gp_Pnt2d v2(pt->x, pt->y); + if (!v1.IsEqual(v2, Precision::Confusion())) { + Handle(Geom2d_TrimmedCurve) lseg = GCE2d_MakeSegment(v1, v2); + TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(lseg, dc->surf); + dc->Edges.push_back(edge); + dc->LastVert = *pt; + dc->polyPoints.emplace_back(pt->x, pt->y, 0.0); + } + return 0; } // quad_cb called for quadratic (conic) BCurve segment in the current contour // (ie V-C-V in TTF fonts). BCurve(LastVert -- pt0 -- pt1) -static int quad_cb(const FT_Vector* pt0, const FT_Vector* pt1, void* p) { - FTDC_Ctx* dc = static_cast(p); - TColgp_Array1OfPnt2d Poles(1,3); - gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y); - gp_Pnt2d c1(pt0->x, pt0->y); - gp_Pnt2d v2(pt1->x, pt1->y); - Poles.SetValue(1, v1); - Poles.SetValue(2, c1); - Poles.SetValue(3, v2); - Handle(Geom2d_BezierCurve) bcseg = new Geom2d_BezierCurve(Poles); - double u,v; - u = bcseg->FirstParameter(); - v = bcseg->LastParameter(); - ShapeConstruct_Curve scc; - Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion()); - if (spline.IsNull()) { - Base::Console().message("Conversion to B-spline failed"); - } - TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf); - dc->Edges.push_back(edge); - dc->LastVert = *pt1; - dc->polyPoints.emplace_back(pt1->x, pt1->y, 0.0); - return 0; +static int quad_cb(const FT_Vector* pt0, const FT_Vector* pt1, void* p) +{ + FTDC_Ctx* dc = static_cast(p); + TColgp_Array1OfPnt2d Poles(1, 3); + gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y); + gp_Pnt2d c1(pt0->x, pt0->y); + gp_Pnt2d v2(pt1->x, pt1->y); + Poles.SetValue(1, v1); + Poles.SetValue(2, c1); + Poles.SetValue(3, v2); + Handle(Geom2d_BezierCurve) bcseg = new Geom2d_BezierCurve(Poles); + double u, v; + u = bcseg->FirstParameter(); + v = bcseg->LastParameter(); + ShapeConstruct_Curve scc; + Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion()); + if (spline.IsNull()) { + Base::Console().message("Conversion to B-spline failed"); + } + TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline, dc->surf); + dc->Edges.push_back(edge); + dc->LastVert = *pt1; + dc->polyPoints.emplace_back(pt1->x, pt1->y, 0.0); + return 0; } // cubic_cb called for cubic BCurve segment in the current contour (ie V-C-C-V in // Type 1 fonts). BCurve(LastVert -- pt0 -- pt1 -- pt2) -static int cubic_cb(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* pt2, void* p) { - FTDC_Ctx* dc = static_cast(p); - TColgp_Array1OfPnt2d Poles(1,4); - gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y); - gp_Pnt2d c1(pt0->x, pt0->y); - gp_Pnt2d c2(pt1->x, pt1->y); - gp_Pnt2d v2(pt2->x, pt2->y); - Poles.SetValue(1, v1); - Poles.SetValue(2, c1); - Poles.SetValue(3, c2); - Poles.SetValue(4, v2); - Handle(Geom2d_BezierCurve) bcseg = new Geom2d_BezierCurve(Poles); - double u,v; - u = bcseg->FirstParameter(); - v = bcseg->LastParameter(); - ShapeConstruct_Curve scc; - Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion()); - if (spline.IsNull()) { - Base::Console().message("Conversion to B-spline failed"); - } - TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf); - dc->Edges.push_back(edge); - dc->LastVert = *pt2; - dc->polyPoints.emplace_back(pt2->x, pt2->y, 0.0); - return 0; +static int cubic_cb(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* pt2, void* p) +{ + FTDC_Ctx* dc = static_cast(p); + TColgp_Array1OfPnt2d Poles(1, 4); + gp_Pnt2d v1(dc->LastVert.x, dc->LastVert.y); + gp_Pnt2d c1(pt0->x, pt0->y); + gp_Pnt2d c2(pt1->x, pt1->y); + gp_Pnt2d v2(pt2->x, pt2->y); + Poles.SetValue(1, v1); + Poles.SetValue(2, c1); + Poles.SetValue(3, c2); + Poles.SetValue(4, v2); + Handle(Geom2d_BezierCurve) bcseg = new Geom2d_BezierCurve(Poles); + double u, v; + u = bcseg->FirstParameter(); + v = bcseg->LastParameter(); + ShapeConstruct_Curve scc; + Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(bcseg, u, v, Precision::Confusion()); + if (spline.IsNull()) { + Base::Console().message("Conversion to B-spline failed"); + } + TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline, dc->surf); + dc->Edges.push_back(edge); + dc->LastVert = *pt2; + dc->polyPoints.emplace_back(pt2->x, pt2->y, 0.0); + return 0; } // FT Callbacks structure static FT_Outline_Funcs FTcbFuncs = { - (FT_Outline_MoveToFunc)move_cb, - (FT_Outline_LineToFunc)line_cb, - (FT_Outline_ConicToFunc)quad_cb, - (FT_Outline_CubicToFunc)cubic_cb, - 0, 0 // not needed for FC + (FT_Outline_MoveToFunc)move_cb, + (FT_Outline_LineToFunc)line_cb, + (FT_Outline_ConicToFunc)quad_cb, + (FT_Outline_CubicToFunc)cubic_cb, + 0, + 0 // not needed for FC }; //********** FT2FC Helpers // get glyph outline in wires -PyObject* getGlyphContours(FT_Face FTFace, FT_ULong currchar, double PenPos, double Scale, int charNum, double tracking) { - FT_Error error = 0; - std::stringstream ErrorMsg; - gp_Pnt origin = gp_Pnt(0.0,0.0,0.0); - FTDC_Ctx ctx; +PyObject* getGlyphContours( + FT_Face FTFace, + FT_ULong currchar, + double PenPos, + double Scale, + int charNum, + double tracking +) +{ + FT_Error error = 0; + std::stringstream ErrorMsg; + gp_Pnt origin = gp_Pnt(0.0, 0.0, 0.0); + FTDC_Ctx ctx; - ctx.currchar = currchar; - ctx.surf = new Geom_Plane(origin,gp::DZ()); + ctx.currchar = currchar; + ctx.surf = new Geom_Plane(origin, gp::DZ()); - error = FT_Outline_Decompose(&FTFace->glyph->outline, - &FTcbFuncs, - &ctx); - if(error) { - ErrorMsg << "FT_Decompose failed: " << error; - throw std::runtime_error(ErrorMsg.str()); - } + error = FT_Outline_Decompose(&FTFace->glyph->outline, &FTcbFuncs, &ctx); + if (error) { + ErrorMsg << "FT_Decompose failed: " << error; + throw std::runtime_error(ErrorMsg.str()); + } -// make the last TopoDS_Wire - if (!ctx.Edges.empty()){ - ctx.Wires.push_back(edgesToWire(ctx.Edges)); - ctx.wDir.push_back(calcClockDir(ctx.polyPoints)); - } + // make the last TopoDS_Wire + if (!ctx.Edges.empty()) { + ctx.Wires.push_back(edgesToWire(ctx.Edges)); + ctx.wDir.push_back(calcClockDir(ctx.polyPoints)); + } -//a ttf outer contour is clockwise with material on the right. -//an occ outer contour has material on the left, so it must be reversed? + // a ttf outer contour is clockwise with material on the right. + // an occ outer contour has material on the left, so it must be reversed? - FT_Orientation ftOrient = FT_Outline_Get_Orientation(&FTFace->glyph->outline); - bool isTTF = false; - if (ftOrient == FT_ORIENTATION_TRUETYPE) { + FT_Orientation ftOrient = FT_Outline_Get_Orientation(&FTFace->glyph->outline); + bool isTTF = false; + if (ftOrient == FT_ORIENTATION_TRUETYPE) { isTTF = true; - } + } - Py::List list; + Py::List list; - gp_Vec pointer = gp_Vec(PenPos * Scale + charNum*tracking,0.0,0.0); - gp_Trsf xForm; - xForm.SetScale(origin,Scale); - xForm.SetTranslationPart(pointer); - BRepBuilderAPI_Transform BRepScale(xForm); - bool bCopy = true; // no effect? + gp_Vec pointer = gp_Vec(PenPos * Scale + charNum * tracking, 0.0, 0.0); + gp_Trsf xForm; + xForm.SetScale(origin, Scale); + xForm.SetTranslationPart(pointer); + BRepBuilderAPI_Transform BRepScale(xForm); + bool bCopy = true; // no effect? - int wCount = 0; - for(std::vector::iterator iWire=ctx.Wires.begin();iWire != ctx.Wires.end(); ++iWire, wCount++) { - if ((ctx.wDir[wCount] == CLOCKWISE) && isTTF) { //ttf outer wire. fill inside / right - (*iWire).Orientation(TopAbs_REVERSED); - } else if ((ctx.wDir[wCount] == CLOCKWISE) && !isTTF) { //ps inner wire. fill outside / right - (*iWire).Orientation(TopAbs_REVERSED); - } else if ((ctx.wDir[wCount] == ANTICLOCKWISE) && isTTF) { //ttf inner wire. fill outside / left - (*iWire).Orientation(TopAbs_REVERSED); - } else if ((ctx.wDir[wCount] == ANTICLOCKWISE) && !isTTF) { //ps outer wire. fill inside / left - (*iWire).Orientation(TopAbs_REVERSED); - } else { - //this is likely a poorly constructed font (ex a ttf with outer wires ACW ) + int wCount = 0; + for (std::vector::iterator iWire = ctx.Wires.begin(); iWire != ctx.Wires.end(); + ++iWire, wCount++) { + if ((ctx.wDir[wCount] == CLOCKWISE) && isTTF) { // ttf outer wire. fill inside / right + (*iWire).Orientation(TopAbs_REVERSED); + } + else if ((ctx.wDir[wCount] == CLOCKWISE) && !isTTF) { // ps inner wire. fill outside / right + (*iWire).Orientation(TopAbs_REVERSED); + } + else if ((ctx.wDir[wCount] == ANTICLOCKWISE) + && isTTF) { // ttf inner wire. fill outside / left + (*iWire).Orientation(TopAbs_REVERSED); + } + else if ((ctx.wDir[wCount] == ANTICLOCKWISE) && !isTTF) { // ps outer wire. fill inside / left + (*iWire).Orientation(TopAbs_REVERSED); + } + else { + // this is likely a poorly constructed font (ex a ttf with outer wires ACW ) Base::Console().message("FT2FC::getGlyphContours - indeterminate wire direction\n"); - } + } - BRepScale.Perform(*iWire,bCopy); - if (!BRepScale.IsDone()) { - ErrorMsg << "FT2FC OCC BRepScale failed \n"; - throw std::runtime_error(ErrorMsg.str()); - } + BRepScale.Perform(*iWire, bCopy); + if (!BRepScale.IsDone()) { + ErrorMsg << "FT2FC OCC BRepScale failed \n"; + throw std::runtime_error(ErrorMsg.str()); + } - PyObject* wire = new TopoShapeWirePy(new TopoShape(TopoDS::Wire(BRepScale.Shape()))); - list.append(Py::asObject(wire)); - } - return Py::new_reference_to(list); + PyObject* wire = new TopoShapeWirePy(new TopoShape(TopoDS::Wire(BRepScale.Shape()))); + list.append(Py::asObject(wire)); + } + return Py::new_reference_to(list); } // get kerning values for this char pair -//TODO: should check FT_HASKERNING flag? returns (0,0) if no kerning? -FT_Vector getKerning(FT_Face FTFace, FT_ULong lc, FT_ULong rc) { - FT_Vector retXY; - FT_Error error; - std::stringstream ErrorMsg; - FT_Vector ftKern; - FT_UInt lcx = FT_Get_Char_Index(FTFace, lc); - FT_UInt rcx = FT_Get_Char_Index(FTFace, rc); - error = FT_Get_Kerning(FTFace,lcx,rcx,FT_KERNING_DEFAULT,&ftKern); - if(error) { - ErrorMsg << "FT_Get_Kerning failed: " << error; - throw std::runtime_error(ErrorMsg.str()); - } - retXY.x = ftKern.x; - retXY.y = ftKern.y; - return(retXY); +// TODO: should check FT_HASKERNING flag? returns (0,0) if no kerning? +FT_Vector getKerning(FT_Face FTFace, FT_ULong lc, FT_ULong rc) +{ + FT_Vector retXY; + FT_Error error; + std::stringstream ErrorMsg; + FT_Vector ftKern; + FT_UInt lcx = FT_Get_Char_Index(FTFace, lc); + FT_UInt rcx = FT_Get_Char_Index(FTFace, rc); + error = FT_Get_Kerning(FTFace, lcx, rcx, FT_KERNING_DEFAULT, &ftKern); + if (error) { + ErrorMsg << "FT_Get_Kerning failed: " << error; + throw std::runtime_error(ErrorMsg.str()); + } + retXY.x = ftKern.x; + retXY.y = ftKern.y; + return (retXY); } // Make a TopoDS_Wire from a list of TopoDS_Edges -TopoDS_Wire edgesToWire(std::vector Edges) { +TopoDS_Wire edgesToWire(std::vector Edges) +{ TopoDS_Wire occwire; std::vector::iterator iEdge; BRepBuilderAPI_MakeWire mkWire; - for (iEdge = Edges.begin(); iEdge != Edges.end(); ++iEdge){ + for (iEdge = Edges.begin(); iEdge != Edges.end(); ++iEdge) { mkWire.Add(*iEdge); if (!mkWire.IsDone()) { Base::Console().message("FT2FC Trace edgesToWire failed to add wire\n"); @@ -421,23 +455,22 @@ TopoDS_Wire edgesToWire(std::vector Edges) { } occwire = mkWire.Wire(); BRepLib::BuildCurves3d(occwire); - return(occwire); + return (occwire); } -//is polygon formed by points clockwise (0) or anticlockwise(1) +// is polygon formed by points clockwise (0) or anticlockwise(1) int calcClockDir(std::vector points) { int result = CLOCKWISE; int stop = points.size() - 1; int iPoint = 0; double bigArea = 0; - for ( ; iPoint < stop; iPoint++) { - double area = points[iPoint].x * points[iPoint + 1].y - - points[iPoint + 1].x * points[iPoint].y; + for (; iPoint < stop; iPoint++) { + double area = points[iPoint].x * points[iPoint + 1].y + - points[iPoint + 1].x * points[iPoint].y; bigArea += area; } - double area = points.back().x * points.front().y - - points.front().x * points.back().y; + double area = points.back().x * points.front().y - points.front().x * points.back().y; bigArea += area; if (bigArea < 0) { result = ANTICLOCKWISE; @@ -445,4 +478,4 @@ int calcClockDir(std::vector points) return result; } -#endif //#ifdef FCUseFreeType +#endif // #ifdef FCUseFreeType diff --git a/src/Mod/Part/App/FT2FC.h b/src/Mod/Part/App/FT2FC.h index 7bb4b8b138..c322121bd0 100644 --- a/src/Mod/Part/App/FT2FC.h +++ b/src/Mod/Part/App/FT2FC.h @@ -32,17 +32,21 @@ #ifndef FT2FC_H #define FT2FC_H // public functions -PyObject* FT2FC(const Py_UCS4 *unichars, - const size_t length, - const char *FontPath, - const char *FontName, - const double stringheight, - const double tracking); +PyObject* FT2FC( + const Py_UCS4* unichars, + const size_t length, + const char* FontPath, + const char* FontName, + const double stringheight, + const double tracking +); -PyObject* FT2FC(const Py_UCS4 *unichars, - const size_t length, - const char *FontSpec, - const double stringheight, - const double tracking); +PyObject* FT2FC( + const Py_UCS4* unichars, + const size_t length, + const char* FontSpec, + const double stringheight, + const double tracking +); -#endif // FT2FC_H +#endif // FT2FC_H diff --git a/src/Mod/Part/App/FaceMaker.cpp b/src/Mod/Part/App/FaceMaker.cpp index 83afa725bd..0cad34fc1c 100644 --- a/src/Mod/Part/App/FaceMaker.cpp +++ b/src/Mod/Part/App/FaceMaker.cpp @@ -22,12 +22,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -51,33 +51,37 @@ void Part::FaceMaker::addShape(const TopoDS_Shape& sh) addTopoShape(sh); } -void Part::FaceMaker::addTopoShape(const TopoShape& shape) { - const TopoDS_Shape &sh = shape.getShape(); - if(sh.IsNull()) +void Part::FaceMaker::addTopoShape(const TopoShape& shape) +{ + const TopoDS_Shape& sh = shape.getShape(); + if (sh.IsNull()) { throw Base::ValueError("Input shape is null."); - switch(sh.ShapeType()){ + } + switch (sh.ShapeType()) { case TopAbs_COMPOUND: this->myCompounds.push_back(TopoDS::Compound(sh)); - break; + break; case TopAbs_WIRE: this->myWires.push_back(TopoDS::Wire(sh)); this->myTopoWires.push_back(shape); - break; + break; case TopAbs_EDGE: this->myWires.push_back(BRepBuilderAPI_MakeWire(TopoDS::Edge(sh)).Wire()); this->myTopoWires.push_back(shape); this->myTopoWires.back().setShape(this->myWires.back(), false); - break; + break; case TopAbs_FACE: this->myInputFaces.push_back(sh); - break; + break; case TopAbs_VERTEX: // This is a special case, since this is generally a stand-alone point in a sketch. We // need to ignore it rather than throw an error - break; + break; default: - throw Base::TypeError(tr("Shape must be a wire, edge or compound. Something else was supplied.").toStdString()); - break; + throw Base::TypeError( + tr("Shape must be a wire, edge or compound. Something else was supplied.").toStdString() + ); + break; } this->mySourceShapes.push_back(shape); } @@ -85,15 +89,16 @@ void Part::FaceMaker::addTopoShape(const TopoShape& shape) { void Part::FaceMaker::useCompound(const TopoDS_Compound& comp) { TopoDS_Iterator it(comp); - for(; it.More(); it.Next()){ + for (; it.More(); it.Next()) { this->addShape(it.Value()); } } void Part::FaceMaker::useTopoCompound(const TopoShape& comp) { - for(auto &s : comp.getSubTopoShapes()) + for (auto& s : comp.getSubTopoShapes()) { this->addTopoShape(s); + } } const TopoDS_Face& Part::FaceMaker::Face() @@ -101,17 +106,22 @@ const TopoDS_Face& Part::FaceMaker::Face() return TopoDS::Face(TopoFace().getShape()); } -const Part::TopoShape &Part::FaceMaker::TopoFace() const{ - if(this->myTopoShape.isNull()) +const Part::TopoShape& Part::FaceMaker::TopoFace() const +{ + if (this->myTopoShape.isNull()) { throw NullShapeException("Part::FaceMaker: result shape is null."); - if (this->myTopoShape.getShape().ShapeType() != TopAbs_FACE) + } + if (this->myTopoShape.getShape().ShapeType() != TopAbs_FACE) { throw Base::TypeError("Part::FaceMaker: return shape is not a single face."); + } return this->myTopoShape; } -const Part::TopoShape &Part::FaceMaker::getTopoShape() const{ - if(this->myTopoShape.isNull()) +const Part::TopoShape& Part::FaceMaker::getTopoShape() const +{ + if (this->myTopoShape.isNull()) { throw NullShapeException("Part::FaceMaker: result shape is null."); + } return this->myTopoShape; } @@ -125,40 +135,45 @@ void Part::FaceMaker::Build() this->myShapesToReturn = this->myInputFaces; this->myGenerated.Clear(); - this->Build_Essence();//adds stuff to myShapesToReturn + this->Build_Essence(); // adds stuff to myShapesToReturn - for(const TopoDS_Compound& cmp : this->myCompounds){ + for (const TopoDS_Compound& cmp : this->myCompounds) { std::unique_ptr facemaker = Part::FaceMaker::ConstructFromType(this->getTypeId()); facemaker->useCompound(cmp); facemaker->Build(); - const TopoDS_Shape &subfaces = facemaker->Shape(); - if (subfaces.IsNull()) + const TopoDS_Shape& subfaces = facemaker->Shape(); + if (subfaces.IsNull()) { continue; - if (subfaces.ShapeType() == TopAbs_COMPOUND){ + } + if (subfaces.ShapeType() == TopAbs_COMPOUND) { this->myShapesToReturn.push_back(subfaces); - } else { - //result is not a compound (probably, a face)... but we want to follow compounding structure of input, so wrap it into compound. + } + else { + // result is not a compound (probably, a face)... but we want to follow compounding + // structure of input, so wrap it into compound. TopoDS_Builder builder; TopoDS_Compound cmp_res; builder.MakeCompound(cmp_res); - builder.Add(cmp_res,subfaces); + builder.Add(cmp_res, subfaces); this->myShapesToReturn.push_back(cmp_res); } } - if(this->myShapesToReturn.empty()){ - //nothing to do, null shape will be returned. + if (this->myShapesToReturn.empty()) { + // nothing to do, null shape will be returned. this->myShape = TopoDS_Shape(); - } else if (this->myShapesToReturn.size() == 1){ + } + else if (this->myShapesToReturn.size() == 1) { this->myShape = this->myShapesToReturn[0]; - } else { + } + else { TopoDS_Builder builder; TopoDS_Compound cmp_res; builder.MakeCompound(cmp_res); - for(TopoDS_Shape &sh: this->myShapesToReturn){ - builder.Add(cmp_res,sh); + for (TopoDS_Shape& sh : this->myShapesToReturn) { + builder.Add(cmp_res, sh); } this->myShape = cmp_res; } @@ -166,36 +181,44 @@ void Part::FaceMaker::Build() postBuild(); } -struct ElementName { +struct ElementName +{ long tag; Data::MappedName name; Data::ElementIDRefs sids; - ElementName(long t, const Data::MappedName &n, const Data::ElementIDRefs &sids) - :tag(t),name(n), sids(sids) + ElementName(long t, const Data::MappedName& n, const Data::ElementIDRefs& sids) + : tag(t) + , name(n) + , sids(sids) {} - inline bool operator<(const ElementName &other) const { - if(tagother.tag) + } + if (tag > other.tag) { return false; - return Data::ElementNameComparator()(name,other.name); + } + return Data::ElementNameComparator()(name, other.name); } }; -void Part::FaceMaker::postBuild() { +void Part::FaceMaker::postBuild() +{ this->myTopoShape.setShape(this->myShape); this->myTopoShape.Hasher = this->MyHasher; this->myTopoShape.mapSubElement(this->mySourceShapes); int index = 0; - const char *op = this->MyOp; - if(!op) + const char* op = this->MyOp; + if (!op) { op = Part::OpCodes::Face; - const auto &faces = this->myTopoShape.getSubTopoShapes(TopAbs_FACE); + } + const auto& faces = this->myTopoShape.getSubTopoShapes(TopAbs_FACE); std::set namesUsed; // name the face using the edges of its outer wire - for(auto &face : faces) { + for (auto& face : faces) { ++index; TopoShape wire = face.splitWires(); wire.mapSubElement(face); @@ -203,8 +226,8 @@ void Part::FaceMaker::postBuild() { int count = wire.countSubShapes(TopAbs_EDGE); for (int index2 = 1; index2 <= count; ++index2) { Data::ElementIDRefs sids; - Data::MappedName name = - face.getMappedName(Data::IndexedName::fromConst("Edge", index2), false, &sids); + Data::MappedName name + = face.getMappedName(Data::IndexedName::fromConst("Edge", index2), false, &sids); if (!name) { continue; } @@ -220,16 +243,22 @@ void Part::FaceMaker::postBuild() { // to use at least 'minElementNames' number of unused element names to // generate the face name. int nameCount = 0; - for (const auto &e : edgeNames) { + for (const auto& e : edgeNames) { names.push_back(e.name); sids += e.sids; if (namesUsed.insert(e.name).second) { - if (++nameCount >= minElementNames) + if (++nameCount >= minElementNames) { break; + } } } this->myTopoShape.setElementComboName( - Data::IndexedName::fromConst("Face",index),names,op,nullptr,&sids); + Data::IndexedName::fromConst("Face", index), + names, + op, + nullptr, + &sids + ); } this->myTopoShape.initCache(true); this->Done(); @@ -238,9 +267,9 @@ void Part::FaceMaker::postBuild() { std::unique_ptr Part::FaceMaker::ConstructFromType(const char* className) { Base::Type fmType = Base::Type::fromName(className); - if (fmType.isBad()){ + if (fmType.isBad()) { std::stringstream ss; - ss << "Class '"<< className <<"' not found."; + ss << "Class '" << className << "' not found."; throw Base::TypeError(ss.str().c_str()); } return Part::FaceMaker::ConstructFromType(fmType); @@ -248,13 +277,13 @@ std::unique_ptr Part::FaceMaker::ConstructFromType(const char* std::unique_ptr Part::FaceMaker::ConstructFromType(Base::Type type) { - if (!type.isDerivedFrom(Part::FaceMaker::getClassTypeId())){ + if (!type.isDerivedFrom(Part::FaceMaker::getClassTypeId())) { std::stringstream ss; ss << "Class '" << type.getName() << "' is not derived from Part::FaceMaker."; throw Base::TypeError(ss.str().c_str()); } std::unique_ptr instance(static_cast(type.createInstance())); - if (!instance){ + if (!instance) { std::stringstream ss; ss << "Cannot create FaceMaker from abstract type '" << type.getName() << "'"; throw Base::TypeError(ss.str().c_str()); @@ -280,13 +309,14 @@ std::string Part::FaceMakerSimple::getUserFriendlyName() const std::string Part::FaceMakerSimple::getBriefExplanation() const { - return {tr("Makes separate plane face from every wire independently. No support for holes; wires can be on different planes.").toStdString()}; - + return {tr("Makes separate plane face from every wire independently. No support for holes; " + "wires can be on different planes.") + .toStdString()}; } void Part::FaceMakerSimple::Build_Essence() { - for(TopoDS_Wire &w: myWires){ + for (TopoDS_Wire& w : myWires) { this->myShapesToReturn.push_back(BRepBuilderAPI_MakeFace(w).Shape()); } } diff --git a/src/Mod/Part/App/FaceMaker.h b/src/Mod/Part/App/FaceMaker.h index 215b3939d6..4632ef0699 100644 --- a/src/Mod/Part/App/FaceMaker.h +++ b/src/Mod/Part/App/FaceMaker.h @@ -56,13 +56,15 @@ class PartExport FaceMaker: public BRepBuilderAPI_MakeShape, public Base::BaseCl TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - FaceMaker() {} - ~FaceMaker() override {} + FaceMaker() + {} + ~FaceMaker() override + {} - void addTopoShape(const TopoShape &s); - void useTopoCompound(const TopoShape &comp); - const TopoShape &getTopoShape() const; - const TopoShape &TopoFace() const; + void addTopoShape(const TopoShape& s); + void useTopoCompound(const TopoShape& comp); + const TopoShape& getTopoShape() const; + const TopoShape& TopoFace() const; virtual void addWire(const TopoDS_Wire& w); /** @@ -78,9 +80,10 @@ public: * is NOT expanded recursively. * @param comp */ - virtual void useCompound(const TopoDS_Compound &comp); + virtual void useCompound(const TopoDS_Compound& comp); - virtual void setPlane(const gp_Pln &) {} + virtual void setPlane(const gp_Pln&) + {} /** * @brief Face: returns the face (result). If result is not a single face, @@ -95,22 +98,23 @@ public: void Build() override; #endif - //fails to compile, huh! - //virtual const TopTools_ListOfShape& Generated(const TopoDS_Shape &S) override {throwNotImplemented();} - //virtual const TopTools_ListOfShape& Modified(const TopoDS_Shape &S) override {throwNotImplemented();} - //virtual Standard_Boolean IsDeleted(const TopoDS_Shape &S) override {throwNotImplemented();} + // fails to compile, huh! + // virtual const TopTools_ListOfShape& Generated(const TopoDS_Shape &S) override + // {throwNotImplemented();} virtual const TopTools_ListOfShape& Modified(const TopoDS_Shape &S) + // override {throwNotImplemented();} virtual Standard_Boolean IsDeleted(const TopoDS_Shape &S) + // override {throwNotImplemented();} static std::unique_ptr ConstructFromType(const char* className); static std::unique_ptr ConstructFromType(Base::Type type); - const char *MyOp = 0; + const char* MyOp = 0; App::StringHasherRef MyHasher; protected: - std::vector mySourceShapes; //wire or compound - std::vector myWires; //wires from mySourceShapes + std::vector mySourceShapes; // wire or compound + std::vector myWires; // wires from mySourceShapes std::vector myTopoWires; - std::vector myCompounds; //compounds, for recursive processing + std::vector myCompounds; // compounds, for recursive processing std::vector myShapesToReturn; std::vector myInputFaces; TopoShape myTopoShape; @@ -132,18 +136,19 @@ protected: }; /** - * @brief The FaceMakerPublic class: derive from it if you want the face maker to be listed in tools that allow choosing one. + * @brief The FaceMakerPublic class: derive from it if you want the face maker to be listed in tools + * that allow choosing one. */ -class PartExport FaceMakerPublic : public FaceMaker +class PartExport FaceMakerPublic: public FaceMaker { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: virtual std::string getUserFriendlyName() const = 0; virtual std::string getBriefExplanation() const = 0; }; - /** * @brief The FaceMakerSimple class: make plane faces from all closed wires * supplied, ignoring overlaps. @@ -158,16 +163,18 @@ public: * for BOPs, but the faces themselves are valid, provided that the source wires * are valid. */ -class PartExport FaceMakerSimple : public FaceMakerPublic +class PartExport FaceMakerSimple: public FaceMakerPublic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: std::string getUserFriendlyName() const override; std::string getBriefExplanation() const override; + protected: void Build_Essence() override; }; -}//namespace Part -#endif // PART_FACEMAKER_H +} // namespace Part +#endif // PART_FACEMAKER_H diff --git a/src/Mod/Part/App/FaceMakerBullseye.cpp b/src/Mod/Part/App/FaceMakerBullseye.cpp index 9b603c8ebb..c543196730 100644 --- a/src/Mod/Part/App/FaceMakerBullseye.cpp +++ b/src/Mod/Part/App/FaceMakerBullseye.cpp @@ -22,22 +22,22 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "FaceMakerBullseye.h" #include "FaceMakerCheese.h" @@ -198,8 +198,9 @@ FaceMakerBullseye::FaceDriller::FaceDriller(const gp_Pln& plane, TopoDS_Wire out this->myTopoFace = TopoShape(this->myFace); } -FaceMakerBullseye::FaceDriller::HitTest -FaceMakerBullseye::FaceDriller::hitTest(const TopoShape& shape) const +FaceMakerBullseye::FaceDriller::HitTest FaceMakerBullseye::FaceDriller::hitTest( + const TopoShape& shape +) const { auto vertex = TopoDS::Vertex(shape.getSubShape(TopAbs_VERTEX, 1)); if (!myFaceBound.IsNull()) { @@ -256,9 +257,11 @@ FaceMakerBullseye::FaceDriller::hitTest(const TopoShape& shape) const } } -void FaceMakerBullseye::FaceDriller::copyFaceBound(TopoDS_Face& face, - TopoShape& topoFace, - const TopoShape& source) +void FaceMakerBullseye::FaceDriller::copyFaceBound( + TopoDS_Face& face, + TopoShape& topoFace, + const TopoShape& source +) { face = BRepBuilderAPI_MakeFace(myHPlane, TopoDS::Wire(source.getSubShape(TopAbs_WIRE, 1))); topoFace = TopoShape(face); @@ -279,8 +282,7 @@ void FaceMakerBullseye::FaceDriller::addHole(TopoDS_Wire w) builder.Add(this->myFace, w); } -void FaceMakerBullseye::FaceDriller::addHole(const WireInfo& wireInfo, - std::vector& sources) +void FaceMakerBullseye::FaceDriller::addHole(const WireInfo& wireInfo, std::vector& sources) { if (this->myFaceBound.IsNull()) { copyFaceBound(this->myFaceBound, this->myTopoFaceBound, this->myTopoFace); @@ -336,18 +338,19 @@ void FaceMakerBullseye::FaceDriller::addHole(const WireInfo& wireInfo, int FaceMakerBullseye::FaceDriller::getWireDirection(const gp_Pln& plane, const TopoDS_Wire& wire) { - //make a test face + // make a test face BRepBuilderAPI_MakeFace mkFace(wire, /*onlyplane=*/Standard_True); TopoDS_Face tmpFace = mkFace.Face(); if (tmpFace.IsNull()) { throw Standard_Failure("getWireDirection: Failed to create face from wire"); } - //compare face surface normal with our plane's one + // compare face surface normal with our plane's one BRepAdaptor_Surface surf(tmpFace); bool normal_co = surf.Plane().Axis().Direction().Dot(plane.Axis().Direction()) > 0; - //unlikely, but just in case OCC decided to reverse our wire for the face... take that into account! + // unlikely, but just in case OCC decided to reverse our wire for the face... take that into + // account! TopoDS_Iterator it(tmpFace, /*CumOri=*/Standard_False); normal_co ^= it.Value().Orientation() != wire.Orientation(); diff --git a/src/Mod/Part/App/FaceMakerBullseye.h b/src/Mod/Part/App/FaceMakerBullseye.h index 9503caf228..4df5ad609e 100644 --- a/src/Mod/Part/App/FaceMakerBullseye.h +++ b/src/Mod/Part/App/FaceMakerBullseye.h @@ -50,9 +50,11 @@ class WireJoiner; class PartExport FaceMakerBullseye: public FaceMakerPublic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - FaceMakerBullseye(): - planeSupplied(false){} + FaceMakerBullseye() + : planeSupplied(false) + {} /** * @brief setPlane: sets the plane to use when making faces. This is * optional. If the plane was set, it is not tested that the wires are @@ -68,7 +70,7 @@ protected: void Build_Essence() override; protected: - gp_Pln myPlane; //externally supplied plane (if any) + gp_Pln myPlane; // externally supplied plane (if any) bool planeSupplied {false}; bool reuseInnerWire {false}; @@ -117,7 +119,11 @@ protected: void addHole(const WireInfo& info, std::vector& sources); void copyFaceBound(TopoDS_Face& f, TopoShape& tf, const TopoShape& source); - const TopoDS_Face& Face() const {return myFace;} + const TopoDS_Face& Face() const + { + return myFace; + } + public: /** * @brief wireDirection: determines direction of wire with respect to @@ -125,7 +131,8 @@ protected: * @param w * @return 1 = CCW (suits as outer wire), -1 = CW (suits as hole) */ - static int getWireDirection(const gp_Pln &plane, const TopoDS_Wire &w); + static int getWireDirection(const gp_Pln& plane, const TopoDS_Wire& w); + private: gp_Pln myPlane; TopoDS_Face myFace; @@ -159,5 +166,5 @@ public: virtual std::string getBriefExplanation() const override; }; -}//namespace Part -#endif // PART_FACEMAKER_BULLSEYE_H +} // namespace Part +#endif // PART_FACEMAKER_BULLSEYE_H diff --git a/src/Mod/Part/App/FaceMakerCheese.cpp b/src/Mod/Part/App/FaceMakerCheese.cpp index 9602e53ef0..ac12b790ba 100644 --- a/src/Mod/Part/App/FaceMakerCheese.cpp +++ b/src/Mod/Part/App/FaceMakerCheese.cpp @@ -22,27 +22,27 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "FaceMakerCheese.h" @@ -61,7 +61,7 @@ TopoDS_Face FaceMakerCheese::validateFace(const TopoDS_Face& face) TopTools_IndexedMapOfShape myMap; myMap.Add(outerwire); - TopExp_Explorer xp(face,TopAbs_WIRE); + TopExp_Explorer xp(face, TopAbs_WIRE); ShapeFix_Wire fix; fix.SetFace(face); fix.Load(outerwire); @@ -87,8 +87,9 @@ TopoDS_Face FaceMakerCheese::validateFace(const TopoDS_Face& face) fix.FixFaceTool()->Perform(); TopoDS_Face fixedFace = TopoDS::Face(fix.Shape()); aChecker.Init(fixedFace); - if (!aChecker.IsValid()) + if (!aChecker.IsValid()) { Standard_Failure::Raise("Failed to validate broken face"); + } return fixedFace; } return mkFace.Face(); @@ -97,7 +98,7 @@ TopoDS_Face FaceMakerCheese::validateFace(const TopoDS_Face& face) return face; } -bool FaceMakerCheese::Wire_Compare::operator() (const TopoDS_Wire& w1, const TopoDS_Wire& w2) +bool FaceMakerCheese::Wire_Compare::operator()(const TopoDS_Wire& w1, const TopoDS_Wire& w2) { Bnd_Box box1, box2; if (!w1.IsNull()) { @@ -123,32 +124,36 @@ bool FaceMakerCheese::isInside(const TopoDS_Wire& wire1, const TopoDS_Wire& wire BRepBndLib::Add(wire2, box2); box2.SetGap(0.0); - if (box1.IsOut(box2)) + if (box1.IsOut(box2)) { return false; + } double prec = Precision::Confusion(); BRepBuilderAPI_MakeFace mkFace(wire1); - if (!mkFace.IsDone()) + if (!mkFace.IsDone()) { Standard_Failure::Raise("Failed to create a face from wire in sketch"); + } TopoDS_Face face = validateFace(mkFace.Face()); BRepAdaptor_Surface adapt(face); IntTools_FClass2d class2d(face, prec); Handle(Geom_Surface) surf = new Geom_Plane(adapt.Plane()); ShapeAnalysis_Surface as(surf); - TopExp_Explorer xp(wire2,TopAbs_VERTEX); - while (xp.More()) { + TopExp_Explorer xp(wire2, TopAbs_VERTEX); + while (xp.More()) { TopoDS_Vertex v = TopoDS::Vertex(xp.Current()); gp_Pnt p = BRep_Tool::Pnt(v); gp_Pnt2d uv = as.ValueOfUV(p, prec); - if (class2d.Perform(uv) == TopAbs_IN) + if (class2d.Perform(uv) == TopAbs_IN) { return true; + } // TODO: We can make a check to see if all points are inside or all outside // because otherwise we have some intersections which is not allowed - else + else { return false; - //xp.Next(); + } + // xp.Next(); } return false; @@ -158,9 +163,10 @@ TopoDS_Shape FaceMakerCheese::makeFace(std::list& wires) { BRepBuilderAPI_MakeFace mkFace(wires.front()); const TopoDS_Face& face = mkFace.Face(); - if (face.IsNull()) + if (face.IsNull()) { return face; - gp_Dir axis(0,0,1); + } + gp_Dir axis(0, 0, 1); BRepAdaptor_Surface adapt(face); if (adapt.GetType() == GeomAbs_Plane) { axis = adapt.Plane().Axis().Direction(); @@ -170,17 +176,19 @@ TopoDS_Shape FaceMakerCheese::makeFace(std::list& wires) for (auto wire : wires) { BRepBuilderAPI_MakeFace mkInnerFace(wire); const TopoDS_Face& inner_face = mkInnerFace.Face(); - if (inner_face.IsNull()) - return inner_face; // failure - gp_Dir inner_axis(0,0,1); + if (inner_face.IsNull()) { + return inner_face; // failure + } + gp_Dir inner_axis(0, 0, 1); BRepAdaptor_Surface adapt(inner_face); if (adapt.GetType() == GeomAbs_Plane) { inner_axis = adapt.Plane().Axis().Direction(); } // It seems that orientation is always 'Forward' and we only have to reverse // if the underlying plane have opposite normals. - if (axis.Dot(inner_axis) < 0) + if (axis.Dot(inner_axis) < 0) { wire.Reverse(); + } mkFace.Add(wire); } return validateFace(mkFace.Face()); @@ -188,18 +196,19 @@ TopoDS_Shape FaceMakerCheese::makeFace(std::list& wires) TopoDS_Shape FaceMakerCheese::makeFace(const std::vector& w) { - if (w.empty()) + if (w.empty()) { return {}; + } - //FIXME: Need a safe method to sort wire that the outermost one comes last - // Currently it's done with the diagonal lengths of the bounding boxes + // FIXME: Need a safe method to sort wire that the outermost one comes last + // Currently it's done with the diagonal lengths of the bounding boxes std::vector wires = w; std::sort(wires.begin(), wires.end(), Wire_Compare()); std::list wire_list; wire_list.insert(wire_list.begin(), wires.rbegin(), wires.rend()); // separate the wires into several independent faces - std::list< std::list > sep_wire_list; + std::list> sep_wire_list; while (!wire_list.empty()) { std::list sep_list; TopoDS_Wire wire = wire_list.front(); @@ -228,16 +237,17 @@ TopoDS_Shape FaceMakerCheese::makeFace(const std::vector& w) TopoDS_Compound comp; BRep_Builder builder; builder.MakeCompound(comp); - for (auto & it : sep_wire_list) { + for (auto& it : sep_wire_list) { TopoDS_Shape aFace = makeFace(it); - if (!aFace.IsNull()) + if (!aFace.IsNull()) { builder.Add(comp, aFace); + } } return TopoDS_Shape(std::move(comp)); } else { - return {}; // error + return {}; // error } } @@ -257,7 +267,7 @@ void FaceMakerCheese::Build_Essence() TopoDS_Shape faces = makeFace(this->myWires); ShapeExtend_Explorer xp; Handle(TopTools_HSequenceOfShape) seq = xp.SeqFromCompound(faces, Standard_True); - for(int i = 0 ; i < seq->Length() ; i++){ - this->myShapesToReturn.push_back(seq->Value(i+1)); + for (int i = 0; i < seq->Length(); i++) { + this->myShapesToReturn.push_back(seq->Value(i + 1)); } } diff --git a/src/Mod/Part/App/FaceMakerCheese.h b/src/Mod/Part/App/FaceMakerCheese.h index 6bf65da2f2..7a7c565830 100644 --- a/src/Mod/Part/App/FaceMakerCheese.h +++ b/src/Mod/Part/App/FaceMakerCheese.h @@ -45,18 +45,20 @@ namespace Part class PartExport FaceMakerCheese: public FaceMakerPublic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: std::string getUserFriendlyName() const override; std::string getBriefExplanation() const override; -public: //in Extrusion, they used to be private. but they are also used by PartDesign, so made public. +public + : // in Extrusion, they used to be private. but they are also used by PartDesign, so made public. /** * @brief The Wire_Compare class is for sorting wires by bounding box diagonal length */ class Wire_Compare { public: - bool operator() (const TopoDS_Wire& w1, const TopoDS_Wire& w2); + bool operator()(const TopoDS_Wire& w1, const TopoDS_Wire& w2); }; static TopoDS_Shape makeFace(const std::vector&); @@ -64,12 +66,12 @@ public: //in Extrusion, they used to be private. but they are also used by PartD static bool isInside(const TopoDS_Wire&, const TopoDS_Wire&); private: - static TopoDS_Shape makeFace(std::list&); // for internal use only + static TopoDS_Shape makeFace(std::list&); // for internal use only protected: void Build_Essence() override; }; -}//namespace Part -#endif // PART_FACEMAKER_CHEESE_H +} // namespace Part +#endif // PART_FACEMAKER_CHEESE_H diff --git a/src/Mod/Part/App/FeatureChamfer.cpp b/src/Mod/Part/App/FeatureChamfer.cpp index 916ab3af0d..064cd645d1 100644 --- a/src/Mod/Part/App/FeatureChamfer.cpp +++ b/src/Mod/Part/App/FeatureChamfer.cpp @@ -22,13 +22,13 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include "FeatureChamfer.h" @@ -41,15 +41,17 @@ PROPERTY_SOURCE(Part::Chamfer, Part::FilletBase) Chamfer::Chamfer() = default; -App::DocumentObjectExecReturn *Chamfer::execute() +App::DocumentObjectExecReturn* Chamfer::execute() { App::DocumentObject* link = Base.getValue(); - if (!link) + if (!link) { return new App::DocumentObjectExecReturn("No object linked"); + } try { - TopoShape baseTopoShape = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); - const auto & baseShape = baseTopoShape.getShape(); + TopoShape baseTopoShape + = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); + const auto& baseShape = baseTopoShape.getShape(); BRepFilletAPI_MakeChamfer mkChamfer(baseShape); TopTools_IndexedDataMapOfShapeListOfShape mapEdgeFace; TopExp::MapShapesAndAncestors(baseShape, TopAbs_EDGE, TopAbs_FACE, mapEdgeFace); @@ -58,15 +60,16 @@ App::DocumentObjectExecReturn *Chamfer::execute() TopExp::MapShapes(baseShape, TopAbs_EDGE, mapOfEdges); std::string fullErrMsg; - const auto &vals = EdgeLinks.getSubValues(); - const auto &subs = EdgeLinks.getShadowSubs(); - if(subs.size()!=(size_t)Edges.getSize()) + const auto& vals = EdgeLinks.getSubValues(); + const auto& subs = EdgeLinks.getShadowSubs(); + if (subs.size() != (size_t)Edges.getSize()) { return new App::DocumentObjectExecReturn("Edge link size mismatch"); - size_t i=0; - for(const auto &info : edges) { - auto &sub = subs[i]; - auto &ref = sub.newName.empty() ? vals[i] : sub.newName; - auto &oldName = sub.oldName.empty() ? "" : sub.oldName; + } + size_t i = 0; + for (const auto& info : edges) { + auto& sub = subs[i]; + auto& ref = sub.newName.empty() ? vals[i] : sub.newName; + auto& oldName = sub.oldName.empty() ? "" : sub.oldName; ++i; if (Data::hasMissingElement(ref.c_str()) || Data::hasMissingElement(oldName.c_str())) { @@ -80,14 +83,15 @@ App::DocumentObjectExecReturn *Chamfer::execute() continue; } // Toponaming project March 2024: Replaced this code because it wouldn't work: -// TopoDS_Shape edge; -// try { -// edge = baseTopoShape.getSubShape(ref.c_str()); -// }catch(...){} + // TopoDS_Shape edge; + // try { + // edge = baseTopoShape.getSubShape(ref.c_str()); + // }catch(...){} auto id = Data::MappedName(ref.c_str()).toIndexedName().getIndex(); const TopoDS_Edge& edge = TopoDS::Edge(mapOfEdges.FindKey(id)); - if(edge.IsNull()) + if (edge.IsNull()) { return new App::DocumentObjectExecReturn("Invalid edge link"); + } double radius1 = info.radius1; double radius2 = info.radius2; const TopoDS_Face& face = TopoDS::Face(mapEdgeFace.FindFromKey(edge).First()); @@ -100,15 +104,15 @@ App::DocumentObjectExecReturn *Chamfer::execute() Edges.setValues(edges); TopoDS_Shape shape = mkChamfer.Shape(); - if (shape.IsNull()) + if (shape.IsNull()) { return new App::DocumentObjectExecReturn("Resulting shape is null"); + } TopoShape res(0); - this->Shape.setValue(res.makeElementShape(mkChamfer,baseTopoShape,Part::OpCodes::Chamfer)); + this->Shape.setValue(res.makeElementShape(mkChamfer, baseTopoShape, Part::OpCodes::Chamfer)); return Part::FilletBase::execute(); } catch (Standard_Failure& e) { return new App::DocumentObjectExecReturn(e.GetMessageString()); } } - diff --git a/src/Mod/Part/App/FeatureChamfer.h b/src/Mod/Part/App/FeatureChamfer.h index fd5b187403..81d0e7aa37 100644 --- a/src/Mod/Part/App/FeatureChamfer.h +++ b/src/Mod/Part/App/FeatureChamfer.h @@ -32,7 +32,7 @@ namespace Part { -class PartExport Chamfer : public Part::FilletBase +class PartExport Chamfer: public Part::FilletBase { PROPERTY_HEADER_WITH_OVERRIDE(Part::Chamfer); @@ -42,16 +42,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderChamfer"; } //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATURECHAMFER_H - +#endif // PART_FEATURECHAMFER_H diff --git a/src/Mod/Part/App/FeatureCompound.cpp b/src/Mod/Part/App/FeatureCompound.cpp index 85a0aa6405..19a296408f 100644 --- a/src/Mod/Part/App/FeatureCompound.cpp +++ b/src/Mod/Part/App/FeatureCompound.cpp @@ -22,11 +22,11 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include "FeatureCompound.h" @@ -38,7 +38,7 @@ PROPERTY_SOURCE(Part::Compound, Part::Feature) Compound::Compound() { - ADD_PROPERTY(Links,(nullptr)); + ADD_PROPERTY(Links, (nullptr)); Links.setSize(0); } @@ -46,12 +46,13 @@ Compound::~Compound() = default; short Compound::mustExecute() const { - if (Links.isTouched()) + if (Links.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *Compound::execute() +App::DocumentObjectExecReturn* Compound::execute() { try { // avoid duplicates without changing the order @@ -84,11 +85,13 @@ App::DocumentObjectExecReturn *Compound::execute() PROPERTY_SOURCE(Part::Compound2, Part::Compound) -Compound2::Compound2() { - Shape.setStatus(App::Property::Transient,true); +Compound2::Compound2() +{ + Shape.setStatus(App::Property::Transient, true); } -void Compound2::onDocumentRestored() { +void Compound2::onDocumentRestored() +{ Base::Placement pla = Placement.getValue(); auto res = execute(); delete res; diff --git a/src/Mod/Part/App/FeatureCompound.h b/src/Mod/Part/App/FeatureCompound.h index 28c6116b86..322327aef9 100644 --- a/src/Mod/Part/App/FeatureCompound.h +++ b/src/Mod/Part/App/FeatureCompound.h @@ -35,7 +35,7 @@ namespace Part { -class PartExport Compound : public Part::Feature +class PartExport Compound: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Compound); @@ -49,24 +49,26 @@ public: //@{ short mustExecute() const override; /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderCompound"; } //@} }; /// Same as Part::Compound, except it marks the Shape as transient, and rebuild it during restore -class Compound2 : public Compound { +class Compound2: public Compound +{ PROPERTY_HEADER_WITH_OVERRIDE(Part::Compound2); + public: Compound2(); void onDocumentRestored() override; }; -} //namespace Part +} // namespace Part -#endif // PART_FEATURECOMPOUND_H - +#endif // PART_FEATURECOMPOUND_H diff --git a/src/Mod/Part/App/FeatureExtrusion.cpp b/src/Mod/Part/App/FeatureExtrusion.cpp index 1eea10a8ee..438dfe5fc8 100644 --- a/src/Mod/Part/App/FeatureExtrusion.cpp +++ b/src/Mod/Part/App/FeatureExtrusion.cpp @@ -24,19 +24,19 @@ #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 @@ -52,64 +52,57 @@ using namespace Part; PROPERTY_SOURCE(Part::Extrusion, Part::Feature) -const char* Extrusion::eDirModeStrings[] = { - "Custom", - "Edge", - "Normal", - nullptr }; +const char* Extrusion::eDirModeStrings[] = {"Custom", "Edge", "Normal", nullptr}; namespace { - std::vector MakerEnums = {"Simple", - "Cheese", - "Extrusion", - "Bullseye"}; - - const char* enumToClass(const char* mode) - { - if (MakerEnums.at(0) == mode) { - return "Part::FaceMakerSimple"; - } - if (MakerEnums.at(1) == mode) { - return "Part::FaceMakerCheese"; - } - if (MakerEnums.at(2) == mode) { - return "Part::FaceMakerExtrusion"; - } - if (MakerEnums.at(3) == mode) { - return "Part::FaceMakerBullseye"; - } +std::vector MakerEnums = {"Simple", "Cheese", "Extrusion", "Bullseye"}; +const char* enumToClass(const char* mode) +{ + if (MakerEnums.at(0) == mode) { + return "Part::FaceMakerSimple"; + } + if (MakerEnums.at(1) == mode) { + return "Part::FaceMakerCheese"; + } + if (MakerEnums.at(2) == mode) { + return "Part::FaceMakerExtrusion"; + } + if (MakerEnums.at(3) == mode) { return "Part::FaceMakerBullseye"; } - const char* classToEnum(const char* type) - { - if (strcmp(type, "Part::FaceMakerSimple") == 0) { - return MakerEnums.at(0).c_str(); - } - if (strcmp(type, "Part::FaceMakerCheese") == 0) { - return MakerEnums.at(1).c_str(); - } - if (strcmp(type, "Part::FaceMakerExtrusion") == 0) { - return MakerEnums.at(2).c_str(); - } - if (strcmp(type, "Part::FaceMakerBullseye") == 0) { - return MakerEnums.at(3).c_str(); - } + return "Part::FaceMakerBullseye"; +} +const char* classToEnum(const char* type) +{ + if (strcmp(type, "Part::FaceMakerSimple") == 0) { + return MakerEnums.at(0).c_str(); + } + if (strcmp(type, "Part::FaceMakerCheese") == 0) { + return MakerEnums.at(1).c_str(); + } + if (strcmp(type, "Part::FaceMakerExtrusion") == 0) { + return MakerEnums.at(2).c_str(); + } + if (strcmp(type, "Part::FaceMakerBullseye") == 0) { return MakerEnums.at(3).c_str(); } - void restoreFaceMakerMode(Extrusion* self) - { - const char* mode = enumToClass(self->FaceMakerMode.getValueAsString()); - const char* type = self->FaceMakerClass.getValue(); - if (strcmp(mode, type) != 0) { - self->FaceMakerMode.setValue(classToEnum(type)); - } + return MakerEnums.at(3).c_str(); +} + +void restoreFaceMakerMode(Extrusion* self) +{ + const char* mode = enumToClass(self->FaceMakerMode.getValueAsString()); + const char* type = self->FaceMakerClass.getValue(); + if (strcmp(mode, type) != 0) { + self->FaceMakerMode.setValue(classToEnum(type)); } } +} // namespace Extrusion::Extrusion() { @@ -148,45 +141,46 @@ Extrusion::Extrusion() short Extrusion::mustExecute() const { - if (Base.isTouched() || - Dir.isTouched() || - DirMode.isTouched() || - DirLink.isTouched() || - LengthFwd.isTouched() || - LengthRev.isTouched() || - Solid.isTouched() || - Reversed.isTouched() || - Symmetric.isTouched() || - TaperAngle.isTouched() || - TaperAngleRev.isTouched() || - FaceMakerClass.isTouched()) + if (Base.isTouched() || Dir.isTouched() || DirMode.isTouched() || DirLink.isTouched() + || LengthFwd.isTouched() || LengthRev.isTouched() || Solid.isTouched() + || Reversed.isTouched() || Symmetric.isTouched() || TaperAngle.isTouched() + || TaperAngleRev.isTouched() || FaceMakerClass.isTouched()) { return 1; + } return 0; } -bool Extrusion::fetchAxisLink(const App::PropertyLinkSub& axisLink, Base::Vector3d& basepoint, Base::Vector3d& dir) +bool Extrusion::fetchAxisLink( + const App::PropertyLinkSub& axisLink, + Base::Vector3d& basepoint, + Base::Vector3d& dir +) { - if (!axisLink.getValue()) + if (!axisLink.getValue()) { return false; + } auto linked = axisLink.getValue(); TopoDS_Shape axEdge; if (!axisLink.getSubValues().empty() && axisLink.getSubValues()[0].length() > 0) { - axEdge = Feature::getTopoShape(linked, - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - axisLink.getSubValues()[0].c_str()).getShape(); + axEdge = Feature::getTopoShape( + linked, + ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform, + axisLink.getSubValues()[0].c_str() + ) + .getShape(); } else { axEdge = Feature::getShape(linked, ShapeOption::ResolveLink | ShapeOption::Transform); } - if (axEdge.IsNull()) + if (axEdge.IsNull()) { throw Base::ValueError("DirLink shape is null"); - if (axEdge.ShapeType() != TopAbs_EDGE) + } + if (axEdge.ShapeType() != TopAbs_EDGE) { throw Base::TypeError("DirLink shape is not an edge"); + } BRepAdaptor_Curve crv(TopoDS::Edge(axEdge)); gp_Pnt startpoint; @@ -194,8 +188,9 @@ bool Extrusion::fetchAxisLink(const App::PropertyLinkSub& axisLink, Base::Vector if (crv.GetType() == GeomAbs_Line) { startpoint = crv.Value(crv.FirstParameter()); endpoint = crv.Value(crv.LastParameter()); - if (axEdge.Orientation() == TopAbs_REVERSED) + if (axEdge.Orientation() == TopAbs_REVERSED) { std::swap(startpoint, endpoint); + } } else { throw Base::TypeError("DirLink edge is not a line."); @@ -213,29 +208,32 @@ ExtrusionParameters Extrusion::computeFinalParameters() ExtrusionParameters result; Base::Vector3d dir; switch (this->DirMode.getValue()) { - case dmCustom: - dir = this->Dir.getValue(); - break; - case dmEdge: { - bool fetched; - Base::Vector3d base; - fetched = fetchAxisLink(this->DirLink, base, dir); - if (!fetched) - throw Base::ValueError("DirMode is set to use edge, but no edge is linked."); - this->Dir.setValue(dir); - } break; - case dmNormal: - dir = calculateShapeNormal(this->Base); - this->Dir.setValue(dir); - break; - default: - throw Base::ValueError("Unexpected enum value"); + case dmCustom: + dir = this->Dir.getValue(); + break; + case dmEdge: { + bool fetched; + Base::Vector3d base; + fetched = fetchAxisLink(this->DirLink, base, dir); + if (!fetched) { + throw Base::ValueError("DirMode is set to use edge, but no edge is linked."); + } + this->Dir.setValue(dir); + } break; + case dmNormal: + dir = calculateShapeNormal(this->Base); + this->Dir.setValue(dir); + break; + default: + throw Base::ValueError("Unexpected enum value"); } - if (dir.Length() < Precision::Confusion()) + if (dir.Length() < Precision::Confusion()) { throw Base::ValueError("Direction is zero-length"); + } result.dir = gp_Dir(dir.x, dir.y, dir.z); - if (this->Reversed.getValue()) + if (this->Reversed.getValue()) { result.dir.Reverse(); + } result.lengthFwd = this->LengthFwd.getValue(); result.lengthRev = this->LengthRev.getValue(); @@ -249,17 +247,24 @@ ExtrusionParameters Extrusion::computeFinalParameters() result.lengthFwd = result.lengthFwd * 0.5; } - if (fabs(result.lengthFwd + result.lengthRev) < Precision::Confusion()) + if (fabs(result.lengthFwd + result.lengthRev) < Precision::Confusion()) { throw Base::ValueError("Total length of extrusion is zero."); + } result.solid = this->Solid.getValue(); result.taperAngleFwd = Base::toRadians(this->TaperAngle.getValue()); - if (fabs(result.taperAngleFwd) > pi * 0.5 - Precision::Angular()) - throw Base::ValueError("Magnitude of taper angle matches or exceeds 90 degrees. That is too much."); + if (fabs(result.taperAngleFwd) > pi * 0.5 - Precision::Angular()) { + throw Base::ValueError( + "Magnitude of taper angle matches or exceeds 90 degrees. That is too much." + ); + } result.taperAngleRev = Base::toRadians(this->TaperAngleRev.getValue()); - if (fabs(result.taperAngleRev) > pi * 0.5 - Precision::Angular()) - throw Base::ValueError("Magnitude of taper angle matches or exceeds 90 degrees. That is too much."); + if (fabs(result.taperAngleRev) > pi * 0.5 - Precision::Angular()) { + throw Base::ValueError( + "Magnitude of taper angle matches or exceeds 90 degrees. That is too much." + ); + } result.faceMakerClass = this->FaceMakerClass.getValue(); @@ -270,17 +275,19 @@ Base::Vector3d Extrusion::calculateShapeNormal(const App::PropertyLink& shapeLin { App::DocumentObject* docobj = nullptr; Base::Matrix4D mat; - TopoDS_Shape sh = Feature::getShape(shapeLink.getValue(), - ShapeOption::ResolveLink - | ShapeOption::Transform, - nullptr, - &mat, - &docobj); + TopoDS_Shape sh = Feature::getShape( + shapeLink.getValue(), + ShapeOption::ResolveLink | ShapeOption::Transform, + nullptr, + &mat, + &docobj + ); - if (!docobj) + if (!docobj) { throw Base::ValueError("calculateShapeNormal: link is empty"); + } - //special case for sketches and the like: no matter what shape they have, use their local Z axis. + // special case for sketches and the like: no matter what shape they have, use their local Z axis. if (docobj->isDerivedFrom()) { Base::Vector3d OZ(0.0, 0.0, 1.0); Base::Vector3d result; @@ -288,21 +295,25 @@ Base::Vector3d Extrusion::calculateShapeNormal(const App::PropertyLink& shapeLin return result; } - if (sh.IsNull()) - throw NullShapeException("calculateShapeNormal: link points to a valid object, but its shape is null."); + if (sh.IsNull()) { + throw NullShapeException( + "calculateShapeNormal: link points to a valid object, but its shape is null." + ); + } - //find plane + // find plane BRepLib_FindSurface planeFinder(sh, -1, /*OnlyPlane=*/true); - if (!planeFinder.Found()) + if (!planeFinder.Found()) { throw Base::ValueError("Can't find normal direction, because the shape is not on a plane."); + } - //find plane normal and return result. + // find plane normal and return result. GeomAdaptor_Surface surf(planeFinder.Surface()); gp_Dir normal = surf.Plane().Axis().Direction(); - //now we know the plane. But if there are faces, the - //plane normal direction is not dependent on face orientation (because findPlane only uses edges). - //let's fix that. + // now we know the plane. But if there are faces, the + // plane normal direction is not dependent on face orientation (because findPlane only uses + // edges). let's fix that. TopExp_Explorer ex(sh, TopAbs_FACE); if (ex.More()) { BRepAdaptor_Surface surf(TopoDS::Face(ex.Current())); @@ -315,9 +326,10 @@ Base::Vector3d Extrusion::calculateShapeNormal(const App::PropertyLink& shapeLin return Base::Vector3d(normal.X(), normal.Y(), normal.Z()); } -void Extrusion::extrudeShape(TopoShape &result, const TopoShape &source, const ExtrusionParameters& params) +void Extrusion::extrudeShape(TopoShape& result, const TopoShape& source, const ExtrusionParameters& params) { - gp_Vec vec = gp_Vec(params.dir).Multiplied(params.lengthFwd + params.lengthRev);//total vector of extrusion + gp_Vec vec = gp_Vec(params.dir).Multiplied(params.lengthFwd + params.lengthRev); // total vector + // of extrusion // #0000910: Circles Extrude Only Surfaces, thus use BRepBuilderAPI_Copy TopoShape myShape(source.makeElementCopy()); @@ -334,9 +346,11 @@ void Extrusion::extrudeShape(TopoShape &result, const TopoShape &source, const E Standard_Failure::Raise("Drafting shape failed"); } else { - result.makeElementCompound(drafts, - 0, - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + result.makeElementCompound( + drafts, + 0, + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); } } else { @@ -378,8 +392,12 @@ App::DocumentObjectExecReturn* Extrusion::execute() try { ExtrusionParameters params = computeFinalParameters(); TopoShape result(0, getDocument()->getStringHasher()); - - extrudeShape(result, Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform), params); + + extrudeShape( + result, + Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform), + params + ); this->Shape.setValue(result); return App::DocumentObject::StdReturn; } @@ -413,8 +431,9 @@ void FaceMakerExtrusion::Build() this->myShapesToReturn.clear(); this->myShape = TopoDS_Shape(); TopoDS_Shape inputShape; - if (mySourceShapes.empty()) + if (mySourceShapes.empty()) { throw Base::ValueError("No input shapes!"); + } if (mySourceShapes.size() == 1) { inputShape = mySourceShapes[0].getShape(); } @@ -422,7 +441,7 @@ void FaceMakerExtrusion::Build() TopoDS_Builder builder; TopoDS_Compound cmp; builder.MakeCompound(cmp); - for (const auto &sh : mySourceShapes) { + for (const auto& sh : mySourceShapes) { builder.Add(cmp, sh.getShape()); } inputShape = cmp; @@ -449,24 +468,24 @@ void FaceMakerExtrusion::Build() } if (!wires.empty()) { - //try { + // try { TopoDS_Shape res = FaceMakerCheese::makeFace(wires); - if (!res.IsNull()) + if (!res.IsNull()) { this->myShape = res; + } //} - //catch (...) { + // catch (...) { //} } this->Done(); - } void Part::Extrusion::setupObject() { Part::Feature::setupObject(); - //default for newly created features + // default for newly created features this->FaceMakerMode.setValue(MakerEnums.at(3).c_str()); this->FaceMakerClass.setValue("Part::FaceMakerBullseye"); } diff --git a/src/Mod/Part/App/FeatureExtrusion.h b/src/Mod/Part/App/FeatureExtrusion.h index 984d9c2f5b..2fa025bc3c 100644 --- a/src/Mod/Part/App/FeatureExtrusion.h +++ b/src/Mod/Part/App/FeatureExtrusion.h @@ -38,7 +38,7 @@ namespace Part { -class PartExport Extrusion : public Part::Feature +class PartExport Extrusion: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Extrusion); @@ -62,10 +62,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderExtrusion"; } //@} @@ -76,7 +77,11 @@ public: * @param source: the shape to be extruded * @param params: extrusion parameters */ - static void extrudeShape(TopoShape &result, const TopoShape &source, const ExtrusionParameters& params); + static void extrudeShape( + TopoShape& result, + const TopoShape& source, + const ExtrusionParameters& params + ); /** * @brief fetchAxisLink: read AxisLink to obtain the direction and @@ -88,9 +93,11 @@ public: * @return true if link was fetched. false if link was empty. Throws if the * link is wrong. */ - static bool fetchAxisLink(const App::PropertyLinkSub& axisLink, - Base::Vector3d& basepoint, - Base::Vector3d& dir); + static bool fetchAxisLink( + const App::PropertyLinkSub& axisLink, + Base::Vector3d& basepoint, + Base::Vector3d& dir + ); /** * @brief computeFinalParameters: applies mode logic and fetches links, to @@ -102,8 +109,9 @@ public: static Base::Vector3d calculateShapeNormal(const App::PropertyLink& shapeLink); void onDocumentRestored() override; -public: //mode enumerations - enum eDirMode{ +public: // mode enumerations + enum eDirMode + { dmCustom, dmEdge, dmNormal @@ -116,13 +124,14 @@ protected: }; /** - * @brief FaceMakerExtrusion provides legacy compounding-structure-ignorant behavior of facemaker of Part Extrude. - * Strengths: makes faces with holes - * Weaknesses: can't make islands in holes. Ignores compounding nesting. All faces must be on same plane. + * @brief FaceMakerExtrusion provides legacy compounding-structure-ignorant behavior of facemaker of + * Part Extrude. Strengths: makes faces with holes Weaknesses: can't make islands in holes. Ignores + * compounding nesting. All faces must be on same plane. */ class FaceMakerExtrusion: public FaceMakerCheese { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: std::string getUserFriendlyName() const override; std::string getBriefExplanation() const override; @@ -134,10 +143,11 @@ public: #endif protected: - void Build_Essence() override {} + void Build_Essence() override + {} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREEXTRUSION_H +#endif // PART_FEATUREEXTRUSION_H diff --git a/src/Mod/Part/App/FeatureFace.cpp b/src/Mod/Part/App/FeatureFace.cpp index 817e91e00e..311e76c919 100644 --- a/src/Mod/Part/App/FeatureFace.cpp +++ b/src/Mod/Part/App/FeatureFace.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include "FeatureFace.h" @@ -37,17 +37,21 @@ PROPERTY_SOURCE(Part::Face, Part::Feature) Face::Face() { - ADD_PROPERTY(Sources,(nullptr)); - ADD_PROPERTY(FaceMakerClass,("Part::FaceMakerCheese"));//default value here is for legacy documents. Default for new objects is set in setupObject. + ADD_PROPERTY(Sources, (nullptr)); + ADD_PROPERTY(FaceMakerClass, ("Part::FaceMakerCheese")); // default value here is for legacy + // documents. Default for new objects + // is set in setupObject. Sources.setSize(0); } short Face::mustExecute() const { - if (FaceMakerClass.isTouched()) + if (FaceMakerClass.isTouched()) { return 1; - if (Sources.isTouched()) + } + if (Sources.isTouched()) { return 1; + } return Part::Feature::mustExecute(); } @@ -57,20 +61,27 @@ void Face::setupObject() Feature::setupObject(); } -App::DocumentObjectExecReturn *Face::execute() +App::DocumentObjectExecReturn* Face::execute() { std::vector links = Sources.getValues(); - if (links.empty()) + if (links.empty()) { return new App::DocumentObjectExecReturn("No shapes linked"); + } - std::unique_ptr facemaker = FaceMaker::ConstructFromType(this->FaceMakerClass.getValue()); + std::unique_ptr facemaker = FaceMaker::ConstructFromType( + this->FaceMakerClass.getValue() + ); for (std::vector::iterator it = links.begin(); it != links.end(); ++it) { - if (!(*it)) - return new App::DocumentObjectExecReturn("Linked object is not a Part object (has no Shape)."); + if (!(*it)) { + return new App::DocumentObjectExecReturn( + "Linked object is not a Part object (has no Shape)." + ); + } TopoDS_Shape shape = Feature::getShape(*it, ShapeOption::ResolveLink | ShapeOption::Transform); - if (shape.IsNull()) + if (shape.IsNull()) { return new App::DocumentObjectExecReturn("Linked shape object is empty"); + } // this is a workaround for an obscure OCC bug which leads to empty tessellations // for some faces. Making an explicit copy of the linked shape seems to fix it. @@ -82,19 +93,21 @@ App::DocumentObjectExecReturn *Face::execute() return new App::DocumentObjectExecReturn("Linked shape object is empty"); }*/ - if(links.size() == 1 && shape.ShapeType() == TopAbs_COMPOUND) + if (links.size() == 1 && shape.ShapeType() == TopAbs_COMPOUND) { facemaker->useCompound(TopoDS::Compound(shape)); - else + } + else { facemaker->addShape(shape); + } } facemaker->Build(); TopoDS_Shape aFace = facemaker->Shape(); - if (aFace.IsNull()) + if (aFace.IsNull()) { return new App::DocumentObjectExecReturn("Creating face failed (null shape result)"); + } this->Shape.setValue(aFace); return App::DocumentObject::StdReturn; } - diff --git a/src/Mod/Part/App/FeatureFace.h b/src/Mod/Part/App/FeatureFace.h index 6af571af8d..5c771fb378 100644 --- a/src/Mod/Part/App/FeatureFace.h +++ b/src/Mod/Part/App/FeatureFace.h @@ -33,30 +33,31 @@ namespace Part { -class PartExport Face : public Part::Feature +class PartExport Face: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Face); public: Face(); - App::PropertyLinkList Sources; + App::PropertyLinkList Sources; App::PropertyString FaceMakerClass; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderFace"; } void setupObject() override; //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FACE_H +#endif // PART_FACE_H diff --git a/src/Mod/Part/App/FeatureFillet.cpp b/src/Mod/Part/App/FeatureFillet.cpp index bd9220435f..0f9e680b8f 100644 --- a/src/Mod/Part/App/FeatureFillet.cpp +++ b/src/Mod/Part/App/FeatureFillet.cpp @@ -24,13 +24,13 @@ #include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -45,18 +45,20 @@ PROPERTY_SOURCE(Part::Fillet, Part::FilletBase) Fillet::Fillet() = default; -App::DocumentObjectExecReturn *Fillet::execute() +App::DocumentObjectExecReturn* Fillet::execute() { App::DocumentObject* link = Base.getValue(); - if (!link) + if (!link) { return new App::DocumentObjectExecReturn("No object linked"); + } try { -#if defined(__GNUC__) && defined (FC_OS_LINUX) +#if defined(__GNUC__) && defined(FC_OS_LINUX) Base::SignalException se; #endif - TopoShape baseTopoShape = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); + TopoShape baseTopoShape + = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); auto baseShape = baseTopoShape.getShape(); BRepFilletAPI_MakeFillet mkFillet(baseShape); TopTools_IndexedMapOfShape mapOfShape; @@ -66,15 +68,16 @@ App::DocumentObjectExecReturn *Fillet::execute() std::vector edges = Edges.getValues(); std::string fullErrMsg; - const auto &vals = EdgeLinks.getSubValues(true); - const auto &subs = EdgeLinks.getShadowSubs(); - if(subs.size()!=(size_t)Edges.getSize()) + const auto& vals = EdgeLinks.getSubValues(true); + const auto& subs = EdgeLinks.getShadowSubs(); + if (subs.size() != (size_t)Edges.getSize()) { return new App::DocumentObjectExecReturn("Edge link size mismatch"); - size_t i=0; - for(const auto &info : edges) { - auto &sub = subs[i]; - auto &ref = sub.newName.empty() ? vals[i] : sub.newName; - auto &oldName = sub.oldName.empty() ? "" : sub.oldName; + } + size_t i = 0; + for (const auto& info : edges) { + auto& sub = subs[i]; + auto& ref = sub.newName.empty() ? vals[i] : sub.newName; + auto& oldName = sub.oldName.empty() ? "" : sub.oldName; ++i; if (Data::hasMissingElement(ref.c_str()) || Data::hasMissingElement(oldName.c_str())) { @@ -89,15 +92,16 @@ App::DocumentObjectExecReturn *Fillet::execute() } // Toponaming project March 2024: Replaced this code because it wouldn't work: -// TopoDS_Shape edge; -// try { -// edge = baseTopoShape.getSubShape(ref.c_str()); -// }catch(...){} + // TopoDS_Shape edge; + // try { + // edge = baseTopoShape.getSubShape(ref.c_str()); + // }catch(...){} auto id = Data::MappedName(ref.c_str()).toIndexedName().getIndex(); const TopoDS_Edge& edge = TopoDS::Edge(mapOfEdges.FindKey(id)); - if(edge.IsNull()) - return new App::DocumentObjectExecReturn("Invalid edge link"); + if (edge.IsNull()) { + return new App::DocumentObjectExecReturn("Invalid edge link"); + } double radius1 = info.radius1; double radius2 = info.radius2; @@ -110,8 +114,9 @@ App::DocumentObjectExecReturn *Fillet::execute() Edges.setValues(edges); TopoDS_Shape shape = mkFillet.Shape(); - if (shape.IsNull()) + if (shape.IsNull()) { return new App::DocumentObjectExecReturn("Resulting shape is null"); + } TopoShape res(0); this->Shape.setValue(res.makeElementShape(mkFillet, baseTopoShape, Part::OpCodes::Fillet)); diff --git a/src/Mod/Part/App/FeatureFillet.h b/src/Mod/Part/App/FeatureFillet.h index 8b9e1ddfcc..a53fc9bf27 100644 --- a/src/Mod/Part/App/FeatureFillet.h +++ b/src/Mod/Part/App/FeatureFillet.h @@ -33,7 +33,7 @@ namespace Part { -class PartExport Fillet : public Part::FilletBase +class PartExport Fillet: public Part::FilletBase { PROPERTY_HEADER_WITH_OVERRIDE(Part::Fillet); @@ -43,15 +43,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderFillet"; } //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREFILLET_H +#endif // PART_FEATUREFILLET_H diff --git a/src/Mod/Part/App/FeatureGeometrySet.cpp b/src/Mod/Part/App/FeatureGeometrySet.cpp index 83a6798314..c6b9b8d0cc 100644 --- a/src/Mod/Part/App/FeatureGeometrySet.cpp +++ b/src/Mod/Part/App/FeatureGeometrySet.cpp @@ -34,18 +34,18 @@ PROPERTY_SOURCE(Part::FeatureGeometrySet, Part::Feature) FeatureGeometrySet::FeatureGeometrySet() { - ADD_PROPERTY(GeometrySet,(nullptr)); + ADD_PROPERTY(GeometrySet, (nullptr)); } -App::DocumentObjectExecReturn *FeatureGeometrySet::execute() +App::DocumentObjectExecReturn* FeatureGeometrySet::execute() { TopoShape result; - const std::vector &Geoms = GeometrySet.getValues(); + const std::vector& Geoms = GeometrySet.getValues(); bool first = true; - for(auto Geom : Geoms) { + for (auto Geom : Geoms) { TopoDS_Shape sh = Geom->toShape(); if (first) { first = false; diff --git a/src/Mod/Part/App/FeatureGeometrySet.h b/src/Mod/Part/App/FeatureGeometrySet.h index e6e268e54a..8447d1b2ca 100644 --- a/src/Mod/Part/App/FeatureGeometrySet.h +++ b/src/Mod/Part/App/FeatureGeometrySet.h @@ -34,7 +34,7 @@ namespace Part { -class PartExport FeatureGeometrySet :public Part::Feature +class PartExport FeatureGeometrySet: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::FeatureGeometrySet); @@ -46,16 +46,16 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; - /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + App::DocumentObjectExecReturn* execute() override; + /// returns the type name of the ViewProvider + const char* getViewProviderName() const override + { return "PartGui::ViewProviderGeometrySet"; } //@} - }; -} //namespace Part +} // namespace Part -#endif // PART_FeatureGeometrySet_H +#endif // PART_FeatureGeometrySet_H diff --git a/src/Mod/Part/App/FeatureMirroring.cpp b/src/Mod/Part/App/FeatureMirroring.cpp index 0903d3a23a..2727f6a765 100644 --- a/src/Mod/Part/App/FeatureMirroring.cpp +++ b/src/Mod/Part/App/FeatureMirroring.cpp @@ -22,20 +22,20 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -46,29 +46,39 @@ #include "DatumFeature.h" - using namespace Part; PROPERTY_SOURCE(Part::Mirroring, Part::Feature) Mirroring::Mirroring() { - ADD_PROPERTY(Source,(nullptr)); - ADD_PROPERTY_TYPE(Base,(Base::Vector3d()),"Plane",App::Prop_None,"The base point of the plane"); - ADD_PROPERTY_TYPE(Normal,(Base::Vector3d(0,0,1)),"Plane",App::Prop_None,"The normal of the plane"); - ADD_PROPERTY_TYPE(MirrorPlane,(nullptr),"Plane",App::Prop_None,"A reference for the mirroring plane, overrides Base and Normal if set, can be face or circle"); + ADD_PROPERTY(Source, (nullptr)); + ADD_PROPERTY_TYPE(Base, (Base::Vector3d()), "Plane", App::Prop_None, "The base point of the plane"); + ADD_PROPERTY_TYPE(Normal, (Base::Vector3d(0, 0, 1)), "Plane", App::Prop_None, "The normal of the plane"); + ADD_PROPERTY_TYPE( + MirrorPlane, + (nullptr), + "Plane", + App::Prop_None, + "A reference for the mirroring plane, overrides Base and Normal if set, can be face or " + "circle" + ); } short Mirroring::mustExecute() const { - if (Source.isTouched()) + if (Source.isTouched()) { return 1; - if (Base.isTouched()) + } + if (Base.isTouched()) { return 1; - if (Normal.isTouched()) + } + if (Normal.isTouched()) { return 1; - if (MirrorPlane.isTouched()) + } + if (MirrorPlane.isTouched()) { return 1; + } return 0; } @@ -86,22 +96,23 @@ void Mirroring::onChanged(const App::Property* prop) if (!isRestoring()) { bool needsRecompute = false; App::DocumentObject* refObject = MirrorPlane.getValue(); - if (!refObject){ + if (!refObject) { Base.setStatus(App::Property::ReadOnly, false); Normal.setStatus(App::Property::ReadOnly, false); if (prop == &Base || prop == &Normal) { needsRecompute = true; } - } else { - if (prop == &MirrorPlane){ + } + else { + if (prop == &MirrorPlane) { Base.setStatus(App::Property::ReadOnly, true); Normal.setStatus(App::Property::ReadOnly, true); needsRecompute = true; } } - if (needsRecompute){ + if (needsRecompute) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -111,7 +122,11 @@ void Mirroring::onChanged(const App::Property* prop) Part::Feature::onChanged(prop); } -void Mirroring::handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop) +void Mirroring::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { if (prop == &Base && strcmp(TypeName, "App::PropertyVector") == 0) { App::PropertyVector v; @@ -132,11 +147,12 @@ void Mirroring::handleChangedPropertyType(Base::XMLReader &reader, const char *T } } -App::DocumentObjectExecReturn *Mirroring::execute() +App::DocumentObjectExecReturn* Mirroring::execute() { App::DocumentObject* link = Source.getValue(); - if (!link) + if (!link) { return new App::DocumentObjectExecReturn("No object linked"); + } App::DocumentObject* refObject = MirrorPlane.getValue(); @@ -149,107 +165,141 @@ App::DocumentObjectExecReturn *Mirroring::execute() DatumPlanes, Part::Planes, Origin planes, Faces, Circles Can also be App::Links to such objects */ - if (refObject){ - if (refObject->isDerivedFrom() || refObject->isDerivedFrom() || (strstr(refObject->getNameInDocument(), "Plane") - && refObject->isDerivedFrom())) { + if (refObject) { + if (refObject->isDerivedFrom() || refObject->isDerivedFrom() + || (strstr(refObject->getNameInDocument(), "Plane") + && refObject->isDerivedFrom())) { Part::Feature* plane = static_cast(refObject); Base::Vector3d base = plane->Placement.getValue().getPosition(); axbase = gp_Pnt(base.x, base.y, base.z); Base::Rotation rot = plane->Placement.getValue().getRotation(); Base::Vector3d dir; - rot.multVec(Base::Vector3d(0,0,1), dir); + rot.multVec(Base::Vector3d(0, 0, 1), dir); axdir = gp_Dir(dir.x, dir.y, dir.z); // reference is an app::link or a part::feature or some subobject - } else if (refObject->isDerivedFrom() || refObject->isDerivedFrom()) { - if (subStrings.size() > 1){ - throw Base::ValueError(std::string(this->getFullLabel()) + ": Only 1 subobject is supported for Mirror Plane reference, either a plane face or a circle edge."); - + } + else if (refObject->isDerivedFrom() || refObject->isDerivedFrom()) { + if (subStrings.size() > 1) { + throw Base::ValueError( + std::string(this->getFullLabel()) + ": Only 1 subobject is supported for Mirror Plane reference, either a plane face or a circle edge." + ); } auto linked = MirrorPlane.getValue(); - bool isFace = false; //will be true if user selected face subobject or if object only has 1 face - bool isEdge = false; //will be true if user selected edge subobject or if object only has 1 edge + bool isFace = false; // will be true if user selected face subobject or if object only + // has 1 face + bool isEdge = false; // will be true if user selected edge subobject or if object only + // has 1 edge TopoDS_Shape shape; - if (!subStrings.empty() && subStrings[0].length() > 0){ + if (!subStrings.empty() && subStrings[0].length() > 0) { - shape = Feature::getTopoShape(linked, - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - subStrings[0].c_str()).getShape(); - - if (strstr(subStrings[0].c_str(), "Face")){ - isFace = true; //was face subobject, e.g. Face3 - } else { - if (strstr(subStrings[0].c_str(), "Edge")){ - isEdge = true; //was edge subobject, e.g. Edge7 + shape = Feature::getTopoShape( + linked, + ShapeOption::NeedSubElement | ShapeOption::ResolveLink + | ShapeOption::Transform, + subStrings[0].c_str() + ) + .getShape(); + + if (strstr(subStrings[0].c_str(), "Face")) { + isFace = true; // was face subobject, e.g. Face3 + } + else { + if (strstr(subStrings[0].c_str(), "Edge")) { + isEdge = true; // was edge subobject, e.g. Edge7 } } - } else { - //no subobjects were selected, so this is entire shape of feature - shape = Feature::getShape(linked, ShapeOption::ResolveLink | ShapeOption::Transform); + } + else { + // no subobjects were selected, so this is entire shape of feature + shape = Feature::getShape(linked, ShapeOption::ResolveLink | ShapeOption::Transform); } - // if there is only 1 face or 1 edge, then we don't need to force the user to select that face or edge - // instead we can infer what was intended + // if there is only 1 face or 1 edge, then we don't need to force the user to select + // that face or edge instead we can infer what was intended int faceCount = Part::TopoShape(shape).countSubShapes(TopAbs_FACE); int edgeCount = Part::TopoShape(shape).countSubShapes(TopAbs_EDGE); TopoDS_Face face; TopoDS_Edge edge; - if (isFace) { //user selected a face, so use shape to get the TopoDS::Face + if (isFace) { // user selected a face, so use shape to get the TopoDS::Face face = TopoDS::Face(shape); - } else { - if (faceCount == 1) { //entire feature selected, but it only has 1 face, so get that face - TopoDS_Shape tdface = Part::TopoShape(shape).getSubShape(std::string("Face1").c_str()); + } + else { + if (faceCount == 1) { // entire feature selected, but it only has 1 face, so get + // that face + TopoDS_Shape tdface = Part::TopoShape(shape).getSubShape( + std::string("Face1").c_str() + ); face = TopoDS::Face(tdface); isFace = true; } } - if (!isFace && isEdge){ //don't bother with edge if we already have a face to work with - edge = TopoDS::Edge(shape); //isEdge means an edge was selected - } else { - if (edgeCount == 1){ //we don't have a face yet and there were no edges in the subobject selection - //but since this object only has 1 edge, we use it - TopoDS_Shape tdedge = Part::TopoShape(shape).getSubShape(std::string("Edge1").c_str()); + if (!isFace && isEdge) { // don't bother with edge if we already have a face to work with + edge = TopoDS::Edge(shape); // isEdge means an edge was selected + } + else { + if (edgeCount == 1) { // we don't have a face yet and there were no edges in the + // subobject selection + // but since this object only has 1 edge, we use it + TopoDS_Shape tdedge = Part::TopoShape(shape).getSubShape( + std::string("Edge1").c_str() + ); edge = TopoDS::Edge(tdedge); isEdge = true; } } - if (isFace && face.IsNull()) { //ensure we have a good face to work with - throw Base::ValueError(std::string(this->getFullLabel()) + ": Failed to extract mirror plane because face is null"); + if (isFace && face.IsNull()) { // ensure we have a good face to work with + throw Base::ValueError( + std::string(this->getFullLabel()) + + ": Failed to extract mirror plane because face is null" + ); } - if (isEdge && edge.IsNull()){ //ensure we have a good edge to work with - throw Base::ValueError(std::string(this->getFullLabel()) + ": Failed to extract mirror plane because edge is null"); + if (isEdge && edge.IsNull()) { // ensure we have a good edge to work with + throw Base::ValueError( + std::string(this->getFullLabel()) + + ": Failed to extract mirror plane because edge is null" + ); } - if (!isFace && !isEdge){ - throw Base::ValueError(std::string(this->getFullLabel()) + ": Failed to extract mirror plane, unable to determine which face or edge to use."); + if (!isFace && !isEdge) { + throw Base::ValueError( + std::string(this->getFullLabel()) + ": Failed to extract mirror plane, unable to determine which face or edge to use." + ); } if (isFace) { BRepAdaptor_Surface adapt(face); - if (adapt.GetType() != GeomAbs_Plane) - throw Base::TypeError(std::string(this->getFullLabel()) + ": Mirror plane face must be planar"); + if (adapt.GetType() != GeomAbs_Plane) { + throw Base::TypeError( + std::string(this->getFullLabel()) + ": Mirror plane face must be planar" + ); + } TopExp_Explorer exp; exp.Init(face, TopAbs_VERTEX); if (exp.More()) { axbase = BRep_Tool::Pnt(TopoDS::Vertex(exp.Current())); } axdir = adapt.Plane().Axis().Direction(); - } else { - if (isEdge){ + } + else { + if (isEdge) { BRepAdaptor_Curve curve(edge); if (!(curve.GetType() == GeomAbs_Circle)) { - throw Base::TypeError(std::string(this->getFullLabel()) + ": Only circle edge types are supported"); + throw Base::TypeError( + std::string(this->getFullLabel()) + ": Only circle edge types are supported" + ); } gp_Circ circle = curve.Circle(); axdir = circle.Axis().Direction(); axbase = circle.Location(); } } - } else { - throw Base::ValueError(std::string(this->getFullLabel()) + ": Mirror plane reference must be a face of a feature or a plane object or a circle"); + } + else { + throw Base::ValueError( + std::string(this->getFullLabel()) + ": Mirror plane reference must be a face of a feature or a plane object or a circle" + ); } Base.setValue(axbase.X(), axbase.Y(), axbase.Z()); Normal.setValue(axdir.X(), axdir.Y(), axdir.Z()); @@ -259,11 +309,12 @@ App::DocumentObjectExecReturn *Mirroring::execute() Base::Vector3d norm = Normal.getValue(); try { - gp_Ax2 ax2(gp_Pnt(base.x,base.y,base.z), gp_Dir(norm.x,norm.y,norm.z)); + gp_Ax2 ax2(gp_Pnt(base.x, base.y, base.z), gp_Dir(norm.x, norm.y, norm.z)); auto shape = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); - if (shape.isNull()) + if (shape.isNull()) { Standard_Failure::Raise("Cannot mirror empty shape"); - this->Shape.setValue(TopoShape(0).makeElementMirror(shape,ax2)); + } + this->Shape.setValue(TopoShape(0).makeElementMirror(shape, ax2)); copyMaterial(link); return Part::Feature::execute(); diff --git a/src/Mod/Part/App/FeatureMirroring.h b/src/Mod/Part/App/FeatureMirroring.h index 45ca257824..73909c1642 100644 --- a/src/Mod/Part/App/FeatureMirroring.h +++ b/src/Mod/Part/App/FeatureMirroring.h @@ -35,7 +35,7 @@ namespace Part { -class PartExport Mirroring : public Part::Feature +class PartExport Mirroring: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Mirroring); @@ -50,22 +50,26 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderMirror"; } //@} protected: - void onChanged (const App::Property* prop) override; - - void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; + void onChanged(const App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREMIRRORING_H +#endif // PART_FEATUREMIRRORING_H diff --git a/src/Mod/Part/App/FeatureOffset.cpp b/src/Mod/Part/App/FeatureOffset.cpp index 65bb612b87..428a7605b7 100644 --- a/src/Mod/Part/App/FeatureOffset.cpp +++ b/src/Mod/Part/App/FeatureOffset.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -33,22 +33,22 @@ using namespace Part; -const char* Part::Offset::ModeEnums[]= {"Skin","Pipe", "RectoVerso",nullptr}; -const char* Part::Offset::JoinEnums[]= {"Arc","Tangent", "Intersection",nullptr}; +const char* Part::Offset::ModeEnums[] = {"Skin", "Pipe", "RectoVerso", nullptr}; +const char* Part::Offset::JoinEnums[] = {"Arc", "Tangent", "Intersection", nullptr}; PROPERTY_SOURCE(Part::Offset, Part::Feature) Offset::Offset() { - ADD_PROPERTY_TYPE(Source,(nullptr),"Offset",App::Prop_None,"Source shape"); - ADD_PROPERTY_TYPE(Value,(1.0),"Offset",App::Prop_None,"Offset value"); - ADD_PROPERTY_TYPE(Mode,(long(0)),"Offset",App::Prop_None,"Mode"); + ADD_PROPERTY_TYPE(Source, (nullptr), "Offset", App::Prop_None, "Source shape"); + ADD_PROPERTY_TYPE(Value, (1.0), "Offset", App::Prop_None, "Offset value"); + ADD_PROPERTY_TYPE(Mode, (long(0)), "Offset", App::Prop_None, "Mode"); Mode.setEnums(ModeEnums); - ADD_PROPERTY_TYPE(Join,(long(0)),"Offset",App::Prop_None,"Join type"); + ADD_PROPERTY_TYPE(Join, (long(0)), "Offset", App::Prop_None, "Join type"); Join.setEnums(JoinEnums); - ADD_PROPERTY_TYPE(Intersection,(false),"Offset",App::Prop_None,"Intersection"); - ADD_PROPERTY_TYPE(SelfIntersection,(false),"Offset",App::Prop_None,"Self Intersection"); - ADD_PROPERTY_TYPE(Fill,(false),"Offset",App::Prop_None,"Fill offset"); + ADD_PROPERTY_TYPE(Intersection, (false), "Offset", App::Prop_None, "Intersection"); + ADD_PROPERTY_TYPE(SelfIntersection, (false), "Offset", App::Prop_None, "Self Intersection"); + ADD_PROPERTY_TYPE(Fill, (false), "Offset", App::Prop_None, "Fill offset"); Source.setScope(App::LinkScope::Global); } @@ -57,28 +57,36 @@ Offset::~Offset() = default; short Offset::mustExecute() const { - if (Source.isTouched()) + if (Source.isTouched()) { return 1; - if (Value.isTouched()) + } + if (Value.isTouched()) { return 1; - if (Mode.isTouched()) + } + if (Mode.isTouched()) { return 1; - if (Join.isTouched()) + } + if (Join.isTouched()) { return 1; - if (Intersection.isTouched()) + } + if (Intersection.isTouched()) { return 1; - if (SelfIntersection.isTouched()) + } + if (SelfIntersection.isTouched()) { return 1; - if (Fill.isTouched()) + } + if (Fill.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *Offset::execute() +App::DocumentObjectExecReturn* Offset::execute() { App::DocumentObject* source = Source.getValue(); - if (!source) + if (!source) { return new App::DocumentObjectExecReturn("No source shape linked."); + } double offset = Value.getValue(); double tol = Precision::Confusion(); bool inter = Intersection.getValue(); @@ -86,11 +94,20 @@ App::DocumentObjectExecReturn *Offset::execute() short mode = (short)Mode.getValue(); bool fill = Fill.getValue(); auto shape = Feature::getTopoShape(source, ShapeOption::ResolveLink | ShapeOption::Transform); - if(shape.isNull()) + if (shape.isNull()) { return new App::DocumentObjectExecReturn("Invalid source link"); + } auto join = static_cast(Join.getValue()); this->Shape.setValue(TopoShape(0).makeElementOffset( - shape,offset,tol,inter,self,mode,join,fill ? FillType::fill : FillType::noFill)); + shape, + offset, + tol, + inter, + self, + mode, + join, + fill ? FillType::fill : FillType::noFill + )); return App::DocumentObject::StdReturn; } @@ -103,34 +120,41 @@ PROPERTY_SOURCE(Part::Offset2D, Part::Offset) Offset2D::Offset2D() { this->SelfIntersection.setStatus(App::Property::Status::Hidden, true); - this->Mode.setValue(1); //switch to Pipe mode by default, because skin mode does not function properly on closed profiles. + this->Mode.setValue(1); // switch to Pipe mode by default, because skin mode does not function + // properly on closed profiles. } Offset2D::~Offset2D() = default; short Offset2D::mustExecute() const { - if (Source.isTouched()) + if (Source.isTouched()) { return 1; - if (Value.isTouched()) + } + if (Value.isTouched()) { return 1; - if (Mode.isTouched()) + } + if (Mode.isTouched()) { return 1; - if (Join.isTouched()) + } + if (Join.isTouched()) { return 1; - if (Fill.isTouched()) + } + if (Fill.isTouched()) { return 1; - if (Intersection.isTouched()) + } + if (Intersection.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *Offset2D::execute() +App::DocumentObjectExecReturn* Offset2D::execute() { App::DocumentObject* source = Source.getValue(); if (!source) { - return new App::DocumentObjectExecReturn("No source shape linked."); + return new App::DocumentObjectExecReturn("No source shape linked."); } auto shape = Feature::getTopoShape(source, ShapeOption::ResolveLink | ShapeOption::Transform); if (shape.isNull()) { @@ -139,11 +163,14 @@ App::DocumentObjectExecReturn *Offset2D::execute() double offset = Value.getValue(); short mode = (short)Mode.getValue(); auto openresult = mode == 0 ? OpenResult::allowOpenResult : OpenResult::noOpenResult; - if (mode == 2) + if (mode == 2) { return new App::DocumentObjectExecReturn("Mode 'Recto-Verso' is not supported for 2D offset."); + } auto join = static_cast(Join.getValue()); auto fill = Fill.getValue() ? FillType::fill : FillType::noFill; bool inter = Intersection.getValue(); - this->Shape.setValue(TopoShape(0).makeElementOffset2D(shape, offset, join, fill, openresult, inter)); + this->Shape.setValue( + TopoShape(0).makeElementOffset2D(shape, offset, join, fill, openresult, inter) + ); return App::DocumentObject::StdReturn; } diff --git a/src/Mod/Part/App/FeatureOffset.h b/src/Mod/Part/App/FeatureOffset.h index a6798bdc15..d9138bc282 100644 --- a/src/Mod/Part/App/FeatureOffset.h +++ b/src/Mod/Part/App/FeatureOffset.h @@ -35,7 +35,7 @@ namespace Part { -class PartExport Offset : public Part::Feature +class PartExport Offset: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Offset); @@ -43,7 +43,7 @@ public: Offset(); ~Offset() override; - App::PropertyLink Source; + App::PropertyLink Source; App::PropertyFloat Value; App::PropertyEnumeration Mode; App::PropertyEnumeration Join; @@ -54,9 +54,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderOffset"; } //@} @@ -66,9 +67,10 @@ private: static const char* JoinEnums[]; }; -class PartExport Offset2D : public Offset +class PartExport Offset2D: public Offset { PROPERTY_HEADER_WITH_OVERRIDE(Part::Offset2D); + public: Offset2D(); ~Offset2D() override; @@ -76,13 +78,14 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderOffset2D"; } //@} }; -} -#endif // PART_FEATUREOFFSET_H +} // namespace Part +#endif // PART_FEATUREOFFSET_H diff --git a/src/Mod/Part/App/FeaturePartBoolean.cpp b/src/Mod/Part/App/FeaturePartBoolean.cpp index 6be98f0511..cea44d8866 100644 --- a/src/Mod/Part/App/FeaturePartBoolean.cpp +++ b/src/Mod/Part/App/FeaturePartBoolean.cpp @@ -24,11 +24,11 @@ #include -# include +#include -# include -# include -# include +#include +#include +#include #include #include @@ -61,25 +61,39 @@ void throwIfInvalidIfCheckModel(const TopoDS_Shape& shape) bool getRefineModelParameter() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part/Boolean"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/Part/Boolean"); return hGrp->GetBool("RefineModel", true); } -} +} // namespace Part PROPERTY_SOURCE_ABSTRACT(Part::Boolean, Part::Feature) Boolean::Boolean() { - ADD_PROPERTY(Base,(nullptr)); - ADD_PROPERTY(Tool,(nullptr)); - ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType) - (App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history"); + ADD_PROPERTY(Base, (nullptr)); + ADD_PROPERTY(Tool, (nullptr)); + ADD_PROPERTY_TYPE( + History, + (ShapeHistory()), + "Boolean", + (App::PropertyType)(App::Prop_Output | App::Prop_Transient | App::Prop_Hidden), + "Shape history" + ); History.setSize(0); - ADD_PROPERTY_TYPE(Refine,(0),"Boolean",(App::PropertyType)(App::Prop_None),"Refine shape (clean up redundant edges) after this boolean operation"); + ADD_PROPERTY_TYPE( + Refine, + (0), + "Boolean", + (App::PropertyType)(App::Prop_None), + "Refine shape (clean up redundant edges) after this boolean operation" + ); this->Refine.setValue(getRefineModelParameter()); } @@ -97,7 +111,7 @@ short Boolean::mustExecute() const return 0; } -const char *Boolean::opCode() const +const char* Boolean::opCode() const { return Part::OpCodes::Boolean; } @@ -117,12 +131,16 @@ App::DocumentObjectExecReturn* Boolean::execute() std::vector shapes; shapes.reserve(2); // Now, let's get the TopoDS_Shape - shapes.push_back(Feature::getTopoShape(Base.getValue(), ShapeOption::ResolveLink | ShapeOption::Transform)); + shapes.push_back( + Feature::getTopoShape(Base.getValue(), ShapeOption::ResolveLink | ShapeOption::Transform) + ); auto BaseShape = shapes[0].getShape(); if (BaseShape.IsNull()) { throw NullShapeException("Base shape is null"); } - shapes.push_back(Feature::getTopoShape(Tool.getValue(), ShapeOption::ResolveLink | ShapeOption::Transform)); + shapes.push_back( + Feature::getTopoShape(Tool.getValue(), ShapeOption::ResolveLink | ShapeOption::Transform) + ); auto ToolShape = shapes[1].getShape(); if (ToolShape.IsNull()) { throw NullShapeException("Tool shape is null"); @@ -161,6 +179,7 @@ App::DocumentObjectExecReturn* Boolean::execute() } catch (...) { return new App::DocumentObjectExecReturn( - "A fatal error occurred when running boolean operation"); + "A fatal error occurred when running boolean operation" + ); } } diff --git a/src/Mod/Part/App/FeaturePartBoolean.h b/src/Mod/Part/App/FeaturePartBoolean.h index 5cf8ed94e3..bf6a6b28fd 100644 --- a/src/Mod/Part/App/FeaturePartBoolean.h +++ b/src/Mod/Part/App/FeaturePartBoolean.h @@ -37,7 +37,7 @@ class FCBRepAlgoAPI_BooleanOperation; namespace Part { -class PartExport Boolean : public Part::Feature +class PartExport Boolean: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Boolean); @@ -52,20 +52,22 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderBoolean"; } protected: - virtual BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const = 0; - virtual const char *opCode() const = 0; + virtual BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const + = 0; + virtual const char* opCode() const = 0; }; -} +} // namespace Part -#endif // PART_FEATUREPARTBOOLEAN_H +#endif // PART_FEATUREPARTBOOLEAN_H diff --git a/src/Mod/Part/App/FeaturePartBox.cpp b/src/Mod/Part/App/FeaturePartBox.cpp index 1d5e7d1e1d..a714662ff0 100644 --- a/src/Mod/Part/App/FeaturePartBox.cpp +++ b/src/Mod/Part/App/FeaturePartBox.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -38,34 +38,36 @@ PROPERTY_SOURCE(Part::Box, Part::Primitive) Box::Box() { - ADD_PROPERTY_TYPE(Length,(10.0f),"Box",App::Prop_None,"The length of the box"); - ADD_PROPERTY_TYPE(Width ,(10.0f),"Box",App::Prop_None,"The width of the box"); - ADD_PROPERTY_TYPE(Height,(10.0f),"Box",App::Prop_None,"The height of the box"); + ADD_PROPERTY_TYPE(Length, (10.0f), "Box", App::Prop_None, "The length of the box"); + ADD_PROPERTY_TYPE(Width, (10.0f), "Box", App::Prop_None, "The width of the box"); + ADD_PROPERTY_TYPE(Height, (10.0f), "Box", App::Prop_None, "The height of the box"); } short Box::mustExecute() const { - if (Length.isTouched() || - Height.isTouched() || - Width.isTouched() ) + if (Length.isTouched() || Height.isTouched() || Width.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Box::execute() +App::DocumentObjectExecReturn* Box::execute() { double L = Length.getValue(); double W = Width.getValue(); double H = Height.getValue(); - if (L < Precision::Confusion()) + if (L < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Length of box too small"); + } - if (W < Precision::Confusion()) + if (W < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Width of box too small"); + } - if (H < Precision::Confusion()) + if (H < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Height of box too small"); + } try { // Build a box using the dimension attributes @@ -84,49 +86,51 @@ App::DocumentObjectExecReturn *Box::execute() * of Box we had the properties x,y,z and l,h,w which have changed to * Location -- as replacement for x,y and z and Length, Height and Width. */ -void Box::Restore(Base::XMLReader &reader) +void Box::Restore(Base::XMLReader& reader) { reader.readElement("Properties"); int Cnt = reader.getAttribute("Count"); int transientCount = 0; - if(reader.hasAttribute("TransientCount")) + if (reader.hasAttribute("TransientCount")) { transientCount = reader.getAttribute("TransientCount"); + } - for (int i=0;i("name")); - if(prop && reader.hasAttribute("status")) + if (prop && reader.hasAttribute("status")) { prop->setStatusValue(reader.getAttribute("status")); + } } bool location_xyz = false; bool location_axis = false; bool distance_lhw = false; Base::Placement plm; - App::PropertyDistance x,y,z; - App::PropertyDistance l,w,h; + App::PropertyDistance x, y, z; + App::PropertyDistance l, w, h; App::PropertyVector Axis, Location; - Axis.setValue(0.0f,0.0f,1.0f); - for (int i=0 ;i("name"); const char* TypeName = reader.getAttribute("type"); - auto prop = dynamicProps.restore(*this,PropName,TypeName,reader); - if(!prop) + auto prop = dynamicProps.restore(*this, PropName, TypeName, reader); + if (!prop) { prop = getPropertyByName(PropName); + } std::bitset<32> status; - if(reader.hasAttribute("status")) { + if (reader.hasAttribute("status")) { status = reader.getAttribute("status"); - if(prop) + if (prop) { prop->setStatusValue(status.to_ulong()); + } } if (prop && strcmp(prop->getTypeId().getName(), TypeName) == 0) { - if (!prop->testStatus(App::Property::Transient) - && !status.test(App::Property::Transient) - && !status.test(App::Property::PropTransient) - && !(getPropertyType(prop) & App::Prop_Transient)) - { + if (!prop->testStatus(App::Property::Transient) && !status.test(App::Property::Transient) + && !status.test(App::Property::PropTransient) + && !(getPropertyType(prop) & App::Prop_Transient)) { prop->Restore(reader); } reader.readEndElement("Property"); @@ -140,11 +144,11 @@ void Box::Restore(Base::XMLReader &reader) } else if (strcmp(PropName, "w") == 0) { distance_lhw = true; - prop = &h; // by mistake w was considered as height + prop = &h; // by mistake w was considered as height } else if (strcmp(PropName, "h") == 0) { distance_lhw = true; - prop = &w; // by mistake h was considered as width + prop = &w; // by mistake h was considered as width } else if (strcmp(PropName, "x") == 0) { location_xyz = true; @@ -167,15 +171,15 @@ void Box::Restore(Base::XMLReader &reader) prop = &Location; } } - else if (strcmp(PropName, "Length") == 0 && strcmp(TypeName,"PropertyDistance") == 0) { + else if (strcmp(PropName, "Length") == 0 && strcmp(TypeName, "PropertyDistance") == 0) { distance_lhw = true; prop = &l; } - else if (strcmp(PropName, "Height") == 0 && strcmp(TypeName,"PropertyDistance") == 0) { + else if (strcmp(PropName, "Height") == 0 && strcmp(TypeName, "PropertyDistance") == 0) { distance_lhw = true; prop = &h; } - else if (strcmp(PropName, "Width") == 0 && strcmp(TypeName,"PropertyDistance") == 0) { + else if (strcmp(PropName, "Width") == 0 && strcmp(TypeName, "PropertyDistance") == 0) { distance_lhw = true; prop = &w; } @@ -185,10 +189,12 @@ void Box::Restore(Base::XMLReader &reader) // In this case we would force to read-in a wrong property type and the behaviour // would be undefined. std::string tn = TypeName; - if (strcmp(TypeName,"PropertyDistance") == 0) // missing prefix App:: + if (strcmp(TypeName, "PropertyDistance") == 0) { // missing prefix App:: tn = std::string("App::") + tn; - if (prop && strcmp(prop->getTypeId().getName(), tn.c_str()) == 0) + } + if (prop && strcmp(prop->getTypeId().getName(), tn.c_str()) == 0) { prop->Restore(reader); + } reader.readEndElement("Property"); } @@ -201,20 +207,19 @@ void Box::Restore(Base::XMLReader &reader) // for 0.7 releases or earlier if (location_xyz) { - plm.setPosition(Base::Vector3d(x.getValue(),y.getValue(),z.getValue())); + plm.setPosition(Base::Vector3d(x.getValue(), y.getValue(), z.getValue())); this->Placement.setValue(this->Placement.getValue() * plm); - this->Shape.setStatus(App::Property::User1, true); // override the shape's location later on + this->Shape.setStatus(App::Property::User1, true); // override the shape's location later on } // for 0.8 releases else if (location_axis) { Base::Vector3d d = Axis.getValue(); Base::Vector3d p = Location.getValue(); - Base::Rotation rot(Base::Vector3d(0.0,0.0,1.0), - Base::Vector3d(d.x,d.y,d.z)); + Base::Rotation rot(Base::Vector3d(0.0, 0.0, 1.0), Base::Vector3d(d.x, d.y, d.z)); plm.setRotation(rot); - plm.setPosition(Base::Vector3d(p.x,p.y,p.z)); + plm.setPosition(Base::Vector3d(p.x, p.y, p.z)); this->Placement.setValue(this->Placement.getValue() * plm); - this->Shape.setStatus(App::Property::User1, true); // override the shape's location later on + this->Shape.setStatus(App::Property::User1, true); // override the shape's location later on } reader.readEndElement("Properties"); @@ -224,7 +229,7 @@ void Box::onChanged(const App::Property* prop) { if (prop == &Length || prop == &Width || prop == &Height) { if (!isRestoring()) { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } } @@ -232,7 +237,7 @@ void Box::onChanged(const App::Property* prop) // see Box::Restore if (this->Shape.testStatus(App::Property::User1)) { this->Shape.setStatus(App::Property::User1, false); - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; return; } diff --git a/src/Mod/Part/App/FeaturePartBox.h b/src/Mod/Part/App/FeaturePartBox.h index fb65fcddcd..8d0a4eec7b 100644 --- a/src/Mod/Part/App/FeaturePartBox.h +++ b/src/Mod/Part/App/FeaturePartBox.h @@ -35,33 +35,35 @@ namespace Part { -class PartExport Box :public Part::Primitive +class PartExport Box: public Part::Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Box); public: Box(); - App::PropertyLength Length,Height,Width; + App::PropertyLength Length, Height, Width; /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderBox"; } + protected: - void Restore(Base::XMLReader &reader) override; + void Restore(Base::XMLReader& reader) override; /// get called by the container when a property has changed - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREPARTBOX_H +#endif // PART_FEATUREPARTBOX_H diff --git a/src/Mod/Part/App/FeaturePartCircle.cpp b/src/Mod/Part/App/FeaturePartCircle.cpp index 157bf087bf..e91048afbd 100644 --- a/src/Mod/Part/App/FeaturePartCircle.cpp +++ b/src/Mod/Part/App/FeaturePartCircle.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -34,17 +34,17 @@ using namespace Part; -App::PropertyQuantityConstraint::Constraints Circle::angleRange = {0.0,360.0,1.0}; +App::PropertyQuantityConstraint::Constraints Circle::angleRange = {0.0, 360.0, 1.0}; PROPERTY_SOURCE(Part::Circle, Part::Primitive) Circle::Circle() { - ADD_PROPERTY(Radius,(2.0f)); - ADD_PROPERTY(Angle1,(0.0f)); + ADD_PROPERTY(Radius, (2.0f)); + ADD_PROPERTY(Angle1, (0.0f)); Angle1.setConstraints(&angleRange); - ADD_PROPERTY(Angle2,(360.0f)); + ADD_PROPERTY(Angle2, (360.0f)); Angle2.setConstraints(&angleRange); } @@ -52,20 +52,22 @@ Circle::~Circle() = default; short Circle::mustExecute() const { - if (Angle1.isTouched() || - Angle2.isTouched() || - Radius.isTouched()) + if (Angle1.isTouched() || Angle2.isTouched() || Radius.isTouched()) { return 1; + } return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Circle::execute() +App::DocumentObjectExecReturn* Circle::execute() { gp_Circ circle; circle.SetRadius(this->Radius.getValue()); - BRepBuilderAPI_MakeEdge clMakeEdge(circle, Base::toRadians(this->Angle1.getValue()), - Base::toRadians(this->Angle2.getValue())); + BRepBuilderAPI_MakeEdge clMakeEdge( + circle, + Base::toRadians(this->Angle1.getValue()), + Base::toRadians(this->Angle2.getValue()) + ); const TopoDS_Edge& edge = clMakeEdge.Edge(); this->Shape.setValue(edge); return Primitive::execute(); @@ -74,21 +76,25 @@ App::DocumentObjectExecReturn *Circle::execute() void Circle::onChanged(const App::Property* prop) { if (!isRestoring()) { - if (prop == &Radius || prop == &Angle1 || prop == &Angle2){ + if (prop == &Radius || prop == &Angle1 || prop == &Angle2) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { } } } - Part::Feature::onChanged(prop); // clazy:exclude=skipped-base-method + Part::Feature::onChanged(prop); // clazy:exclude=skipped-base-method } -void Circle::Restore(Base::XMLReader &reader) +void Circle::Restore(Base::XMLReader& reader) { - Base::ObjectStatusLocker lock(App::Property::User1, &Angle2, false); + Base::ObjectStatusLocker lock( + App::Property::User1, + &Angle2, + false + ); Primitive::Restore(reader); if (Angle2.testStatus(App::Property::User1)) { @@ -98,7 +104,7 @@ void Circle::Restore(Base::XMLReader &reader) } } -void Circle::handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) +void Circle::handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, const char* PropName) { Base::Type type = Base::Type::fromName(TypeName); if (Angle2.getTypeId() == type && strcmp(PropName, "Angle0") == 0) { diff --git a/src/Mod/Part/App/FeaturePartCircle.h b/src/Mod/Part/App/FeaturePartCircle.h index 264a80aaf7..08a4a3c81c 100644 --- a/src/Mod/Part/App/FeaturePartCircle.h +++ b/src/Mod/Part/App/FeaturePartCircle.h @@ -33,7 +33,7 @@ namespace Part { -class PartExport Circle : public Part::Primitive +class PartExport Circle: public Part::Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Circle); @@ -48,23 +48,28 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderCircleParametric"; } protected: - void Restore(Base::XMLReader &reader) override; - void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; + void Restore(Base::XMLReader& reader) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; private: static App::PropertyQuantityConstraint::Constraints angleRange; //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREPARTCIRCLE_H +#endif // PART_FEATUREPARTCIRCLE_H diff --git a/src/Mod/Part/App/FeaturePartCommon.cpp b/src/Mod/Part/App/FeaturePartCommon.cpp index a659286442..fd05813763 100644 --- a/src/Mod/Part/App/FeaturePartCommon.cpp +++ b/src/Mod/Part/App/FeaturePartCommon.cpp @@ -22,12 +22,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include "FeaturePartCommon.h" @@ -39,16 +39,16 @@ using namespace Part; namespace Part { - extern void throwIfInvalidIfCheckModel(const TopoDS_Shape& shape); - extern bool getRefineModelParameter(); -} +extern void throwIfInvalidIfCheckModel(const TopoDS_Shape& shape); +extern bool getRefineModelParameter(); +} // namespace Part PROPERTY_SOURCE(Part::Common, Part::Boolean) Common::Common() = default; -const char *Common::opCode() const +const char* Common::opCode() const { return Part::OpCodes::Common; } @@ -66,25 +66,37 @@ PROPERTY_SOURCE(Part::MultiCommon, Part::Feature) MultiCommon::MultiCommon() { - ADD_PROPERTY(Shapes,(nullptr)); + ADD_PROPERTY(Shapes, (nullptr)); Shapes.setSize(0); - ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType) - (App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history"); + ADD_PROPERTY_TYPE( + History, + (ShapeHistory()), + "Boolean", + (App::PropertyType)(App::Prop_Output | App::Prop_Transient | App::Prop_Hidden), + "Shape history" + ); History.setSize(0); - ADD_PROPERTY_TYPE(Refine,(0),"Boolean",(App::PropertyType)(App::Prop_None),"Refine shape (clean up redundant edges) after this boolean operation"); + ADD_PROPERTY_TYPE( + Refine, + (0), + "Boolean", + (App::PropertyType)(App::Prop_None), + "Refine shape (clean up redundant edges) after this boolean operation" + ); this->Refine.setValue(getRefineModelParameter()); } short MultiCommon::mustExecute() const { - if (Shapes.isTouched()) + if (Shapes.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *MultiCommon::execute() +App::DocumentObjectExecReturn* MultiCommon::execute() { std::vector shapes; for (auto obj : Shapes.getValues()) { diff --git a/src/Mod/Part/App/FeaturePartCommon.h b/src/Mod/Part/App/FeaturePartCommon.h index be51a159dd..2f4fd501da 100644 --- a/src/Mod/Part/App/FeaturePartCommon.h +++ b/src/Mod/Part/App/FeaturePartCommon.h @@ -33,7 +33,7 @@ namespace Part { -class Common : public Boolean +class Common: public Boolean { PROPERTY_HEADER_WITH_OVERRIDE(Part::Common); @@ -45,11 +45,11 @@ public: /// recalculate the Feature protected: BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; - const char *opCode() const override; + const char* opCode() const override; //@} }; -class PartExport MultiCommon : public Part::Feature +class PartExport MultiCommon: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::MultiCommon); @@ -63,16 +63,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderMultiCommon"; } - }; -} +} // namespace Part -#endif // PART_FEATUREPARTCOMMON_H +#endif // PART_FEATUREPARTCOMMON_H diff --git a/src/Mod/Part/App/FeaturePartCurveNet.cpp b/src/Mod/Part/App/FeaturePartCurveNet.cpp index 56f327ce52..4f82287a25 100644 --- a/src/Mod/Part/App/FeaturePartCurveNet.cpp +++ b/src/Mod/Part/App/FeaturePartCurveNet.cpp @@ -34,21 +34,22 @@ PROPERTY_SOURCE(Part::CurveNet, Part::Feature) CurveNet::CurveNet() { - ADD_PROPERTY(FileName,("")); + ADD_PROPERTY(FileName, ("")); } short CurveNet::mustExecute() const { - if (FileName.isTouched()) + if (FileName.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *CurveNet::execute() +App::DocumentObjectExecReturn* CurveNet::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().log("CurveNet::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("CurveNet::execute() not able to open %s!\n", FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } diff --git a/src/Mod/Part/App/FeaturePartCurveNet.h b/src/Mod/Part/App/FeaturePartCurveNet.h index 5d7d116e7a..35227fb5a5 100644 --- a/src/Mod/Part/App/FeaturePartCurveNet.h +++ b/src/Mod/Part/App/FeaturePartCurveNet.h @@ -31,7 +31,7 @@ namespace Part { -class CurveNet :public Part::Feature +class CurveNet: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::CurveNet); @@ -43,16 +43,17 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderCurveNet"; } //@} }; -} +} // namespace Part -#endif // PART_FeaturePartCurveNet_H +#endif // PART_FeaturePartCurveNet_H diff --git a/src/Mod/Part/App/FeaturePartCut.cpp b/src/Mod/Part/App/FeaturePartCut.cpp index d609c3f154..a7bf36e29e 100644 --- a/src/Mod/Part/App/FeaturePartCut.cpp +++ b/src/Mod/Part/App/FeaturePartCut.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include "FeaturePartCut.h" @@ -35,7 +35,7 @@ PROPERTY_SOURCE(Part::Cut, Part::Boolean) Cut::Cut() = default; -const char *Cut::opCode() const +const char* Cut::opCode() const { return Part::OpCodes::Cut; } diff --git a/src/Mod/Part/App/FeaturePartCut.h b/src/Mod/Part/App/FeaturePartCut.h index f8c3106c2e..050ce171bf 100644 --- a/src/Mod/Part/App/FeaturePartCut.h +++ b/src/Mod/Part/App/FeaturePartCut.h @@ -31,7 +31,7 @@ namespace Part { -class Cut : public Boolean +class Cut: public Boolean { PROPERTY_HEADER_WITH_OVERRIDE(Part::Cut); @@ -43,10 +43,10 @@ public: /// recalculate the Feature protected: BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; - const char *opCode() const override; + const char* opCode() const override; //@} }; -} +} // namespace Part -#endif // PART_FEATUREPARTCUT_H +#endif // PART_FEATUREPARTCUT_H diff --git a/src/Mod/Part/App/FeaturePartFuse.cpp b/src/Mod/Part/App/FeaturePartFuse.cpp index 0e8109c491..232e2115ff 100644 --- a/src/Mod/Part/App/FeaturePartFuse.cpp +++ b/src/Mod/Part/App/FeaturePartFuse.cpp @@ -22,12 +22,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include "FeaturePartFuse.h" @@ -35,15 +35,15 @@ #include "modelRefine.h" #include "TopoShapeOpCode.h" -FC_LOG_LEVEL_INIT("Part",true,true); +FC_LOG_LEVEL_INIT("Part", true, true); using namespace Part; namespace Part { - extern void throwIfInvalidIfCheckModel(const TopoDS_Shape& shape); - extern bool getRefineModelParameter(); -} +extern void throwIfInvalidIfCheckModel(const TopoDS_Shape& shape); +extern bool getRefineModelParameter(); +} // namespace Part PROPERTY_SOURCE(Part::Fuse, Part::Boolean) @@ -56,7 +56,7 @@ BRepAlgoAPI_BooleanOperation* Fuse::makeOperation(const TopoDS_Shape& base, cons return new FCBRepAlgoAPI_Fuse(base, tool); } -const char *Fuse::opCode() const +const char* Fuse::opCode() const { return Part::OpCodes::Fuse; } @@ -68,25 +68,37 @@ PROPERTY_SOURCE(Part::MultiFuse, Part::Feature) MultiFuse::MultiFuse() { - ADD_PROPERTY(Shapes,(nullptr)); + ADD_PROPERTY(Shapes, (nullptr)); Shapes.setSize(0); - ADD_PROPERTY_TYPE(History,(ShapeHistory()), "Boolean", (App::PropertyType) - (App::Prop_Output|App::Prop_Transient|App::Prop_Hidden), "Shape history"); + ADD_PROPERTY_TYPE( + History, + (ShapeHistory()), + "Boolean", + (App::PropertyType)(App::Prop_Output | App::Prop_Transient | App::Prop_Hidden), + "Shape history" + ); History.setSize(0); - ADD_PROPERTY_TYPE(Refine,(0),"Boolean",(App::PropertyType)(App::Prop_None),"Refine shape (clean up redundant edges) after this boolean operation"); + ADD_PROPERTY_TYPE( + Refine, + (0), + "Boolean", + (App::PropertyType)(App::Prop_None), + "Refine shape (clean up redundant edges) after this boolean operation" + ); this->Refine.setValue(getRefineModelParameter()); } short MultiFuse::mustExecute() const { - if (Shapes.isTouched()) + if (Shapes.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *MultiFuse::execute() +App::DocumentObjectExecReturn* MultiFuse::execute() { std::vector shapes; std::vector obj = Shapes.getValues(); @@ -100,7 +112,8 @@ App::DocumentObjectExecReturn *MultiFuse::execute() TopoShape compoundOfArguments; // if only one source shape, and it is a compound - fuse children of the compound - const int maxIterations = 1'000'000; // will trigger "not enough shape objects linked" error below if ever reached + const int maxIterations = 1'000'000; // will trigger "not enough shape objects linked" error + // below if ever reached for (int i = 0; shapes.size() == 1 && i < maxIterations; ++i) { compoundOfArguments = shapes[0]; TopoDS_Shape shape = compoundOfArguments.getShape(); @@ -108,7 +121,8 @@ App::DocumentObjectExecReturn *MultiFuse::execute() shapes.clear(); shapes = compoundOfArguments.getSubTopoShapes(); argumentsAreInCompound = true; - } else { + } + else { break; } } @@ -143,8 +157,7 @@ App::DocumentObjectExecReturn *MultiFuse::execute() TopoShape res(0); res = res.makeShapeWithElementMap(mkFuse.Shape(), MapperMaker(mkFuse), shapes, OpCodes::Fuse); for (const auto& it2 : shapes) { - history.push_back( - buildHistory(mkFuse, TopAbs_FACE, res.getShape(), it2.getShape())); + history.push_back(buildHistory(mkFuse, TopAbs_FACE, res.getShape(), it2.getShape())); } if (res.isNull()) { throw Base::RuntimeError("Resulting shape is null"); @@ -158,8 +171,7 @@ App::DocumentObjectExecReturn *MultiFuse::execute() BRepBuilderAPI_RefineModel mkRefine(oldShape); // We just built an element map above for the fuse, don't erase it for a refine. res.setShape(mkRefine.Shape(), false); - ShapeHistory hist = - buildHistory(mkRefine, TopAbs_FACE, res.getShape(), oldShape); + ShapeHistory hist = buildHistory(mkRefine, TopAbs_FACE, res.getShape(), oldShape); for (auto& jt : history) { jt = joinHistory(jt, hist); } @@ -187,14 +199,14 @@ App::DocumentObjectExecReturn *MultiFuse::execute() int iFaceInChild = histitem.first; ShapeHistory::List& iFacesInResult = histitem.second; const TopoDS_Shape& srcFace = facesOfChild( - iFaceInChild - + 1); //+1 to convert our 0-based to OCC 1-bsed conventions + iFaceInChild + 1 + ); //+1 to convert our 0-based to OCC 1-bsed conventions int iFaceInCompound = facesOfCompound.FindIndex(srcFace) - 1; - overallHist.shapeMap[iFaceInCompound] = - iFacesInResult; // this may overwrite existing info if the same face is - // used in several children of compound. This shouldn't - // be a problem, because the histories should match - // anyway... + overallHist.shapeMap[iFaceInCompound] + = iFacesInResult; // this may overwrite existing info if the same face + // is used in several children of compound. This + // shouldn't be a problem, because the histories + // should match anyway... } } history.clear(); diff --git a/src/Mod/Part/App/FeaturePartFuse.h b/src/Mod/Part/App/FeaturePartFuse.h index 0c5f1653f4..10582e9169 100644 --- a/src/Mod/Part/App/FeaturePartFuse.h +++ b/src/Mod/Part/App/FeaturePartFuse.h @@ -33,7 +33,7 @@ namespace Part { -class Fuse : public Boolean +class Fuse: public Boolean { PROPERTY_HEADER_WITH_OVERRIDE(Part::Fuse); @@ -45,11 +45,11 @@ public: /// recalculate the Feature protected: BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; - const char *opCode() const override; + const char* opCode() const override; //@} }; -class PartExport MultiFuse : public Part::Feature +class PartExport MultiFuse: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::MultiFuse); @@ -63,16 +63,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderMultiFuse"; } - }; -} +} // namespace Part -#endif // PART_FEATUREPARTFUSE_H +#endif // PART_FEATUREPARTFUSE_H diff --git a/src/Mod/Part/App/FeaturePartImportBrep.cpp b/src/Mod/Part/App/FeaturePartImportBrep.cpp index d928a3e715..42503b565e 100644 --- a/src/Mod/Part/App/FeaturePartImportBrep.cpp +++ b/src/Mod/Part/App/FeaturePartImportBrep.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -38,21 +38,22 @@ PROPERTY_SOURCE(Part::ImportBrep, Part::Feature) ImportBrep::ImportBrep() { - ADD_PROPERTY(FileName,("")); + ADD_PROPERTY(FileName, ("")); } short ImportBrep::mustExecute() const { - if (FileName.isTouched()) + if (FileName.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *ImportBrep::execute() +App::DocumentObjectExecReturn* ImportBrep::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().log("ImportBrep::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("ImportBrep::execute() not able to open %s!\n", FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } @@ -63,4 +64,3 @@ App::DocumentObjectExecReturn *ImportBrep::execute() return App::DocumentObject::StdReturn; } - diff --git a/src/Mod/Part/App/FeaturePartImportBrep.h b/src/Mod/Part/App/FeaturePartImportBrep.h index 41e0f44754..33b27aa1fd 100644 --- a/src/Mod/Part/App/FeaturePartImportBrep.h +++ b/src/Mod/Part/App/FeaturePartImportBrep.h @@ -31,7 +31,7 @@ namespace Part { -class ImportBrep :public Part::Feature +class ImportBrep: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::ImportBrep); @@ -43,16 +43,17 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderImport"; } //@} }; -} +} // namespace Part -#endif // PART_FEATUREPARTIMPORTBREP_H +#endif // PART_FEATUREPARTIMPORTBREP_H diff --git a/src/Mod/Part/App/FeaturePartImportIges.cpp b/src/Mod/Part/App/FeaturePartImportIges.cpp index 24f419356a..d7cf13d389 100644 --- a/src/Mod/Part/App/FeaturePartImportIges.cpp +++ b/src/Mod/Part/App/FeaturePartImportIges.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -38,21 +38,22 @@ PROPERTY_SOURCE(Part::ImportIges, Part::Feature) ImportIges::ImportIges() { - ADD_PROPERTY(FileName,("")); + ADD_PROPERTY(FileName, ("")); } short ImportIges::mustExecute() const { - if (FileName.isTouched()) + if (FileName.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *ImportIges::execute() +App::DocumentObjectExecReturn* ImportIges::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().log("ImportIges::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("ImportIges::execute() not able to open %s!\n", FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } @@ -63,5 +64,3 @@ App::DocumentObjectExecReturn *ImportIges::execute() return App::DocumentObject::StdReturn; } - - diff --git a/src/Mod/Part/App/FeaturePartImportIges.h b/src/Mod/Part/App/FeaturePartImportIges.h index dfc61cd6cd..0f79e2ce47 100644 --- a/src/Mod/Part/App/FeaturePartImportIges.h +++ b/src/Mod/Part/App/FeaturePartImportIges.h @@ -31,7 +31,7 @@ namespace Part { -class ImportIges :public Part::Feature +class ImportIges: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::ImportIges); @@ -43,16 +43,17 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderImport"; } //@} }; -} +} // namespace Part -#endif // PART_FEATUREPARTIMPORTIGES_H +#endif // PART_FEATUREPARTIMPORTIGES_H diff --git a/src/Mod/Part/App/FeaturePartImportStep.cpp b/src/Mod/Part/App/FeaturePartImportStep.cpp index 64b7297d80..b5f0b20140 100644 --- a/src/Mod/Part/App/FeaturePartImportStep.cpp +++ b/src/Mod/Part/App/FeaturePartImportStep.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -38,21 +38,22 @@ PROPERTY_SOURCE(Part::ImportStep, Part::Feature) ImportStep::ImportStep() { - ADD_PROPERTY(FileName,("")); + ADD_PROPERTY(FileName, ("")); } short ImportStep::mustExecute() const { - if (FileName.isTouched()) + if (FileName.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *ImportStep::execute() +App::DocumentObjectExecReturn* ImportStep::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { - Base::Console().log("ImportStep::execute() not able to open %s!\n",FileName.getValue()); + Base::Console().log("ImportStep::execute() not able to open %s!\n", FileName.getValue()); std::string error = std::string("Cannot open file ") + FileName.getValue(); return new App::DocumentObjectExecReturn(error); } @@ -63,5 +64,3 @@ App::DocumentObjectExecReturn *ImportStep::execute() return App::DocumentObject::StdReturn; } - - diff --git a/src/Mod/Part/App/FeaturePartImportStep.h b/src/Mod/Part/App/FeaturePartImportStep.h index 3353daab35..30637eb5ce 100644 --- a/src/Mod/Part/App/FeaturePartImportStep.h +++ b/src/Mod/Part/App/FeaturePartImportStep.h @@ -33,7 +33,7 @@ namespace Part { -class ImportStep :public Part::Feature +class ImportStep: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::ImportStep); @@ -45,16 +45,17 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderImport"; } //@} }; -} +} // namespace Part -#endif // PART_FEATUREPARTIMPORTSTEP_H +#endif // PART_FEATUREPARTIMPORTSTEP_H diff --git a/src/Mod/Part/App/FeaturePartPolygon.cpp b/src/Mod/Part/App/FeaturePartPolygon.cpp index bbb5f6bbf1..07329744e7 100644 --- a/src/Mod/Part/App/FeaturePartPolygon.cpp +++ b/src/Mod/Part/App/FeaturePartPolygon.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include "FeaturePartPolygon.h" @@ -35,34 +35,37 @@ PROPERTY_SOURCE(Part::Polygon, Part::Feature) Part::Polygon::Polygon() { - ADD_PROPERTY(Nodes,(Base::Vector3d())); - ADD_PROPERTY(Close,(false)); + ADD_PROPERTY(Nodes, (Base::Vector3d())); + ADD_PROPERTY(Close, (false)); } Part::Polygon::~Polygon() = default; short Part::Polygon::mustExecute() const { - if (Nodes.isTouched() || Close.isTouched()) + if (Nodes.isTouched() || Close.isTouched()) { return 1; + } return 0; } -App::DocumentObjectExecReturn *Part::Polygon::execute() +App::DocumentObjectExecReturn* Part::Polygon::execute() { BRepBuilderAPI_MakePolygon poly; const std::vector nodes = Nodes.getValues(); - for (const auto & node : nodes) { + for (const auto& node : nodes) { gp_Pnt pnt(node.x, node.y, node.z); poly.Add(pnt); } - if (Close.getValue()) + if (Close.getValue()) { poly.Close(); + } - if (!poly.IsDone()) + if (!poly.IsDone()) { throw Base::CADKernelError("Cannot create polygon because less than two vertices are given"); + } TopoDS_Wire wire = poly.Wire(); this->Shape.setValue(wire); diff --git a/src/Mod/Part/App/FeaturePartPolygon.h b/src/Mod/Part/App/FeaturePartPolygon.h index a56d9d7e61..26735e31e2 100644 --- a/src/Mod/Part/App/FeaturePartPolygon.h +++ b/src/Mod/Part/App/FeaturePartPolygon.h @@ -33,7 +33,7 @@ namespace Part { -class Polygon : public Part::Feature +class Polygon: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Polygon); @@ -42,16 +42,16 @@ public: ~Polygon() override; App::PropertyVectorList Nodes; - App::PropertyBool Close; + App::PropertyBool Close; /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREPARTPOLYGON_H +#endif // PART_FEATUREPARTPOLYGON_H diff --git a/src/Mod/Part/App/FeaturePartSection.cpp b/src/Mod/Part/App/FeaturePartSection.cpp index 0bbc70d0c2..f0fcf9659d 100644 --- a/src/Mod/Part/App/FeaturePartSection.cpp +++ b/src/Mod/Part/App/FeaturePartSection.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include "FeaturePartSection.h" @@ -36,23 +36,27 @@ PROPERTY_SOURCE(Part::Section, Part::Boolean) Section::Section() { - ADD_PROPERTY_TYPE(Approximation,(false),"Section",App::Prop_None,"Approximate the output edges"); + ADD_PROPERTY_TYPE(Approximation, (false), "Section", App::Prop_None, "Approximate the output edges"); } short Section::mustExecute() const { - if (Approximation.isTouched()) + if (Approximation.isTouched()) { return 1; + } return 0; } -const char *Section::opCode() const +const char* Section::opCode() const { return Part::OpCodes::Section; } -BRepAlgoAPI_BooleanOperation* Section::makeOperation(const TopoDS_Shape& base, const TopoDS_Shape& tool) const +BRepAlgoAPI_BooleanOperation* Section::makeOperation( + const TopoDS_Shape& base, + const TopoDS_Shape& tool +) const { // Let's call algorithm computing a section operation: @@ -63,7 +67,8 @@ BRepAlgoAPI_BooleanOperation* Section::makeOperation(const TopoDS_Shape& base, c mkSection->Approximation(approx); mkSection->setAutoFuzzy(); mkSection->Build(); - if (!mkSection->IsDone()) + if (!mkSection->IsDone()) { throw Base::RuntimeError("Section failed"); + } return mkSection.release(); } diff --git a/src/Mod/Part/App/FeaturePartSection.h b/src/Mod/Part/App/FeaturePartSection.h index 242dc1000b..0a764d6d63 100644 --- a/src/Mod/Part/App/FeaturePartSection.h +++ b/src/Mod/Part/App/FeaturePartSection.h @@ -33,7 +33,7 @@ namespace Part { -class Section : public Boolean +class Section: public Boolean { PROPERTY_HEADER_WITH_OVERRIDE(Part::Section); @@ -48,12 +48,11 @@ public: short mustExecute() const override; protected: - BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, - const TopoDS_Shape&) const override; - const char *opCode() const override; + BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; + const char* opCode() const override; //@} }; -} +} // namespace Part -#endif // PART_FEATUREPARTSECTION_H +#endif // PART_FEATUREPARTSECTION_H diff --git a/src/Mod/Part/App/FeaturePartSpline.cpp b/src/Mod/Part/App/FeaturePartSpline.cpp index ffaaf1be62..8d445d3b1f 100644 --- a/src/Mod/Part/App/FeaturePartSpline.cpp +++ b/src/Mod/Part/App/FeaturePartSpline.cpp @@ -32,5 +32,3 @@ PROPERTY_SOURCE(Part::Spline, Part::Feature) Spline::Spline() = default; - - diff --git a/src/Mod/Part/App/FeaturePartSpline.h b/src/Mod/Part/App/FeaturePartSpline.h index 6703065f09..a05879e6f3 100644 --- a/src/Mod/Part/App/FeaturePartSpline.h +++ b/src/Mod/Part/App/FeaturePartSpline.h @@ -33,20 +33,20 @@ namespace Part { -class PartExport Spline :public Part::Feature +class PartExport Spline: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Spline); public: Spline(); /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderSpline"; } }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREPARTSPLINE_H - +#endif // PART_FEATUREPARTSPLINE_H diff --git a/src/Mod/Part/App/FeatureProjectOnSurface.cpp b/src/Mod/Part/App/FeatureProjectOnSurface.cpp index c3421ee17f..d7442372d8 100644 --- a/src/Mod/Part/App/FeatureProjectOnSurface.cpp +++ b/src/Mod/Part/App/FeatureProjectOnSurface.cpp @@ -54,13 +54,25 @@ static std::array modes = {"All", "Faces", "Edges", nullptr}; / ProjectOnSurface::ProjectOnSurface() { - ADD_PROPERTY_TYPE(Mode,(0L), "Projection", App::Prop_None, "Projection mode"); + ADD_PROPERTY_TYPE(Mode, (0L), "Projection", App::Prop_None, "Projection mode"); Mode.setEnums(modes.data()); - ADD_PROPERTY_TYPE(Height,(0.0), "Projection", App::Prop_None, "Extrusion height"); - ADD_PROPERTY_TYPE(Offset,(0.0), "Projection", App::Prop_None, "Offset of solid"); - ADD_PROPERTY_TYPE(Direction,(Base::Vector3d(0, 0, 1)), "Projection", App::Prop_None, "Direction of projection"); - ADD_PROPERTY_TYPE(SupportFace,(nullptr), "Projection", App::Prop_None, "Support faceo"); - ADD_PROPERTY_TYPE(Projection,(nullptr), "Projection", App::Prop_None, "Shapes to project onto support face"); + ADD_PROPERTY_TYPE(Height, (0.0), "Projection", App::Prop_None, "Extrusion height"); + ADD_PROPERTY_TYPE(Offset, (0.0), "Projection", App::Prop_None, "Offset of solid"); + ADD_PROPERTY_TYPE( + Direction, + (Base::Vector3d(0, 0, 1)), + "Projection", + App::Prop_None, + "Direction of projection" + ); + ADD_PROPERTY_TYPE(SupportFace, (nullptr), "Projection", App::Prop_None, "Support faceo"); + ADD_PROPERTY_TYPE( + Projection, + (nullptr), + "Projection", + App::Prop_None, + "Shapes to project onto support face" + ); } App::DocumentObjectExecReturn* ProjectOnSurface::execute() @@ -106,11 +118,11 @@ TopoDS_Face ProjectOnSurface::getSupportFace() const throw Base::ValueError("Expect exactly one support face"); } - auto topoSupport = Feature::getTopoShape(support, - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - subStrings[0].c_str()); + auto topoSupport = Feature::getTopoShape( + support, + ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform, + subStrings[0].c_str() + ); return TopoDS::Face(topoSupport.getShape()); } @@ -124,19 +136,18 @@ std::vector ProjectOnSurface::getProjectionShapes() const } for (std::size_t index = 0; index < objects.size(); index++) { - auto topoSupport = Feature::getTopoShape(objects[index], - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - subvalues[index].c_str()); + auto topoSupport = Feature::getTopoShape( + objects[index], + ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform, + subvalues[index].c_str() + ); shapes.push_back(topoSupport.getShape()); } return shapes; } -std::vector -ProjectOnSurface::filterShapes(const std::vector& shapes) const +std::vector ProjectOnSurface::filterShapes(const std::vector& shapes) const { std::vector filtered; const char* mode = Mode.getValueAsString(); @@ -194,9 +205,11 @@ TopoDS_Shape ProjectOnSurface::createCompound(const std::vector& s return {std::move(aCompound)}; } -std::vector ProjectOnSurface::createProjectedWire(const TopoDS_Shape& shape, - const TopoDS_Face& supportFace, - const gp_Dir& dir) +std::vector ProjectOnSurface::createProjectedWire( + const TopoDS_Shape& shape, + const TopoDS_Face& supportFace, + const gp_Dir& dir +) { if (shape.IsNull()) { return {}; @@ -221,8 +234,10 @@ std::vector ProjectOnSurface::createProjectedWire(const TopoDS_Sha return {}; } -TopoDS_Face ProjectOnSurface::createFaceFromWire(const std::vector& wires, - const TopoDS_Face& supportFace) const +TopoDS_Face ProjectOnSurface::createFaceFromWire( + const std::vector& wires, + const TopoDS_Face& supportFace +) const { if (wires.empty()) { return {}; @@ -232,9 +247,10 @@ TopoDS_Face ProjectOnSurface::createFaceFromWire(const std::vector return createFaceFromParametricWire(wiresInParametricSpace, supportFace); } -TopoDS_Face -ProjectOnSurface::createFaceFromParametricWire(const std::vector& wires, - const TopoDS_Face& supportFace) const +TopoDS_Face ProjectOnSurface::createFaceFromParametricWire( + const std::vector& wires, + const TopoDS_Face& supportFace +) const { auto surface = BRep_Tool::Surface(supportFace); @@ -280,9 +296,10 @@ ProjectOnSurface::createFaceFromParametricWire(const std::vector& w return faceMaker.Face(); } -std::vector -ProjectOnSurface::createWiresFromWires(const std::vector& wires, - const TopoDS_Face& supportFace) const +std::vector ProjectOnSurface::createWiresFromWires( + const std::vector& wires, + const TopoDS_Face& supportFace +) const { auto surface = BRep_Tool::Surface(supportFace); @@ -303,10 +320,7 @@ ProjectOnSurface::createWiresFromWires(const std::vector& wires, for (const auto& edge : edges) { Standard_Real first {}; Standard_Real last {}; - auto currentCurve = BRep_Tool::CurveOnSurface(TopoDS::Edge(edge), - supportFace, - first, - last); + auto currentCurve = BRep_Tool::CurveOnSurface(TopoDS::Edge(edge), supportFace, first, last); if (!currentCurve) { continue; } @@ -357,8 +371,7 @@ std::vector ProjectOnSurface::getWires(const TopoDS_Face& face) con return wires; } -TopoDS_Wire ProjectOnSurface::fixWire(const TopoDS_Shape& shape, - const TopoDS_Face& supportFace) const +TopoDS_Wire ProjectOnSurface::fixWire(const TopoDS_Shape& shape, const TopoDS_Face& supportFace) const { std::vector edges; for (TopExp_Explorer xp(shape, TopAbs_EDGE); xp.More(); xp.Next()) { @@ -367,8 +380,10 @@ TopoDS_Wire ProjectOnSurface::fixWire(const TopoDS_Shape& shape, return fixWire(edges, supportFace); } -TopoDS_Wire ProjectOnSurface::fixWire(const std::vector& edges, - const TopoDS_Face& supportFace) const +TopoDS_Wire ProjectOnSurface::fixWire( + const std::vector& edges, + const TopoDS_Face& supportFace +) const { // try to sort and heal all wires // if the wires are not clean making a face will fail! @@ -402,7 +417,8 @@ TopoDS_Wire ProjectOnSurface::fixWire(const std::vector& edges, return {}; } -namespace { +namespace +{ TopoDS_Wire getProjectedWire(BRepProj_Projection& projection, const TopoDS_Shape& reference) { double minDistance = std::numeric_limits::max(); @@ -421,11 +437,13 @@ TopoDS_Wire getProjectedWire(BRepProj_Projection& projection, const TopoDS_Shape return wireToTake; } -} +} // namespace -std::vector ProjectOnSurface::projectFace(const TopoDS_Face& face, - const TopoDS_Face& supportFace, - const gp_Dir& dir) +std::vector ProjectOnSurface::projectFace( + const TopoDS_Face& face, + const TopoDS_Face& supportFace, + const gp_Dir& dir +) { std::vector shapes; std::vector wires = getWires(face); @@ -439,9 +457,11 @@ std::vector ProjectOnSurface::projectFace(const TopoDS_Face& face, return shapes; } -std::vector ProjectOnSurface::projectWire(const TopoDS_Shape& wire, - const TopoDS_Face& supportFace, - const gp_Dir& dir) +std::vector ProjectOnSurface::projectWire( + const TopoDS_Shape& wire, + const TopoDS_Face& supportFace, + const gp_Dir& dir +) { std::vector shapes; BRepProj_Projection aProjection(wire, supportFace, dir); diff --git a/src/Mod/Part/App/FeatureProjectOnSurface.h b/src/Mod/Part/App/FeatureProjectOnSurface.h index 34a6e60d49..de24a9482a 100644 --- a/src/Mod/Part/App/FeatureProjectOnSurface.h +++ b/src/Mod/Part/App/FeatureProjectOnSurface.h @@ -34,7 +34,7 @@ namespace Part { -class PartExport ProjectOnSurface : public Part::Feature +class PartExport ProjectOnSurface: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::ProjectOnSurface); @@ -55,7 +55,7 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; const char* getViewProviderName() const override; //@} @@ -63,33 +63,43 @@ private: void tryExecute(); TopoDS_Face getSupportFace() const; std::vector getProjectionShapes() const; - std::vector createProjectedWire(const TopoDS_Shape& shape, - const TopoDS_Face& supportFace, - const gp_Dir& dir); - TopoDS_Face createFaceFromWire(const std::vector& wires, - const TopoDS_Face& supportFace) const; - TopoDS_Face createFaceFromParametricWire(const std::vector& wires, - const TopoDS_Face& supportFace) const; + std::vector createProjectedWire( + const TopoDS_Shape& shape, + const TopoDS_Face& supportFace, + const gp_Dir& dir + ); + TopoDS_Face createFaceFromWire( + const std::vector& wires, + const TopoDS_Face& supportFace + ) const; + TopoDS_Face createFaceFromParametricWire( + const std::vector& wires, + const TopoDS_Face& supportFace + ) const; TopoDS_Shape createSolidIfHeight(const TopoDS_Face& face) const; - std::vector createWiresFromWires(const std::vector& wires, - const TopoDS_Face& supportFace) const; + std::vector createWiresFromWires( + const std::vector& wires, + const TopoDS_Face& supportFace + ) const; std::vector getWires(const TopoDS_Face& face) const; - std::vector projectFace(const TopoDS_Face& face, - const TopoDS_Face& supportFace, - const gp_Dir& dir); - std::vector projectWire(const TopoDS_Shape& wire, - const TopoDS_Face& supportFace, - const gp_Dir& dir); - TopoDS_Wire fixWire(const TopoDS_Shape& shape, - const TopoDS_Face& supportFace) const; - TopoDS_Wire fixWire(const std::vector& edges, - const TopoDS_Face& supportFace) const; + std::vector projectFace( + const TopoDS_Face& face, + const TopoDS_Face& supportFace, + const gp_Dir& dir + ); + std::vector projectWire( + const TopoDS_Shape& wire, + const TopoDS_Face& supportFace, + const gp_Dir& dir + ); + TopoDS_Wire fixWire(const TopoDS_Shape& shape, const TopoDS_Face& supportFace) const; + TopoDS_Wire fixWire(const std::vector& edges, const TopoDS_Face& supportFace) const; std::vector filterShapes(const std::vector& shapes) const; TopoDS_Shape createCompound(const std::vector& shapes); TopLoc_Location getOffsetPlacement() const; }; -} //namespace Part +} // namespace Part #endif // PART_FEATUREPROJECTONSURFACE_H diff --git a/src/Mod/Part/App/FeatureRevolution.cpp b/src/Mod/Part/App/FeatureRevolution.cpp index 024e3cc1d4..8a9f80f481 100644 --- a/src/Mod/Part/App/FeatureRevolution.cpp +++ b/src/Mod/Part/App/FeatureRevolution.cpp @@ -22,12 +22,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -38,41 +38,74 @@ using namespace Part; -App::PropertyFloatConstraint::Constraints Revolution::angleRangeU = {-360.0,360.0,1.0}; +App::PropertyFloatConstraint::Constraints Revolution::angleRangeU = {-360.0, 360.0, 1.0}; PROPERTY_SOURCE(Part::Revolution, Part::Feature) Revolution::Revolution() { - ADD_PROPERTY_TYPE(Source,(nullptr), "Revolve", App::Prop_None, "Shape to revolve"); - ADD_PROPERTY_TYPE(Base,(Base::Vector3d(0.0,0.0,0.0)), "Revolve", App::Prop_None, "Base point of revolution axis"); - ADD_PROPERTY_TYPE(Axis,(Base::Vector3d(0.0,0.0,1.0)), "Revolve", App::Prop_None, "Direction of revolution axis"); - ADD_PROPERTY_TYPE(AxisLink,(nullptr),"Revolve",App::Prop_None,"Link to edge to use as revolution axis."); - ADD_PROPERTY_TYPE(Angle,(360.0), "Revolve", App::Prop_None, "Angle span of revolution. If angle is zero, and an arc is used for axis link, angle span of arc will be used."); + ADD_PROPERTY_TYPE(Source, (nullptr), "Revolve", App::Prop_None, "Shape to revolve"); + ADD_PROPERTY_TYPE( + Base, + (Base::Vector3d(0.0, 0.0, 0.0)), + "Revolve", + App::Prop_None, + "Base point of revolution axis" + ); + ADD_PROPERTY_TYPE( + Axis, + (Base::Vector3d(0.0, 0.0, 1.0)), + "Revolve", + App::Prop_None, + "Direction of revolution axis" + ); + ADD_PROPERTY_TYPE( + AxisLink, + (nullptr), + "Revolve", + App::Prop_None, + "Link to edge to use as revolution axis." + ); + ADD_PROPERTY_TYPE( + Angle, + (360.0), + "Revolve", + App::Prop_None, + "Angle span of revolution. If angle is zero, and an arc is used for axis link, angle span " + "of arc will be used." + ); Angle.setConstraints(&angleRangeU); - ADD_PROPERTY_TYPE(Symmetric,(false),"Revolve",App::Prop_None,"Extend revolution symmetrically from the profile."); - ADD_PROPERTY_TYPE(Solid,(false),"Revolve",App::Prop_None,"Make revolution a solid if possible"); - ADD_PROPERTY_TYPE(FaceMakerClass,(""),"Revolve",App::Prop_None,"Facemaker to use if Solid is true."); //default for old documents. For default for new objects, refer to setupObject(). + ADD_PROPERTY_TYPE( + Symmetric, + (false), + "Revolve", + App::Prop_None, + "Extend revolution symmetrically from the profile." + ); + ADD_PROPERTY_TYPE(Solid, (false), "Revolve", App::Prop_None, "Make revolution a solid if possible"); + ADD_PROPERTY_TYPE( + FaceMakerClass, + (""), + "Revolve", + App::Prop_None, + "Facemaker to use if Solid is true." + ); // default for old documents. For default for new objects, refer to setupObject(). } short Revolution::mustExecute() const { - if (Base.isTouched() || - Axis.isTouched() || - Angle.isTouched() || - Source.isTouched() || - Solid.isTouched() || - AxisLink.isTouched() || - Symmetric.isTouched() || - FaceMakerClass.isTouched()) + if (Base.isTouched() || Axis.isTouched() || Angle.isTouched() || Source.isTouched() + || Solid.isTouched() || AxisLink.isTouched() || Symmetric.isTouched() + || FaceMakerClass.isTouched()) { return 1; + } return 0; } void Revolution::onChanged(const App::Property* prop) { - if(! this->isRestoring()){ - if(prop == &AxisLink){ + if (!this->isRestoring()) { + if (prop == &AxisLink) { Base.setReadOnly(AxisLink.getValue() != nullptr); Axis.setReadOnly(AxisLink.getValue() != nullptr); } @@ -80,93 +113,109 @@ void Revolution::onChanged(const App::Property* prop) Part::Feature::onChanged(prop); } -bool Revolution::fetchAxisLink(const App::PropertyLinkSub &axisLink, - Base::Vector3d& center, - Base::Vector3d& dir, - double& angle) +bool Revolution::fetchAxisLink( + const App::PropertyLinkSub& axisLink, + Base::Vector3d& center, + Base::Vector3d& dir, + double& angle +) { - if (!axisLink.getValue()) + if (!axisLink.getValue()) { return false; + } auto linked = axisLink.getValue(); TopoDS_Shape axEdge; - if (!axisLink.getSubValues().empty() && axisLink.getSubValues()[0].length() > 0){ - axEdge = Feature::getTopoShape(linked, - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - axisLink.getSubValues()[0].c_str()).getShape(); - } else { + if (!axisLink.getSubValues().empty() && axisLink.getSubValues()[0].length() > 0) { + axEdge = Feature::getTopoShape( + linked, + ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform, + axisLink.getSubValues()[0].c_str() + ) + .getShape(); + } + else { axEdge = Feature::getShape(linked, ShapeOption::ResolveLink | ShapeOption::Transform); } - if (axEdge.IsNull()) + if (axEdge.IsNull()) { throw Base::ValueError("AxisLink shape is null"); - if (axEdge.ShapeType() != TopAbs_EDGE) + } + if (axEdge.ShapeType() != TopAbs_EDGE) { throw Base::TypeError("AxisLink shape is not an edge"); + } BRepAdaptor_Curve crv(TopoDS::Edge(axEdge)); gp_Pnt base; gp_Dir occdir; bool reversed = axEdge.Orientation() == TopAbs_REVERSED; - if (crv.GetType() == GeomAbs_Line){ + if (crv.GetType() == GeomAbs_Line) { base = crv.Value(reversed ? crv.FirstParameter() : crv.LastParameter()); occdir = crv.Line().Direction(); - } else if (crv.GetType() == GeomAbs_Circle) { + } + else if (crv.GetType() == GeomAbs_Circle) { base = crv.Circle().Axis().Location(); occdir = crv.Circle().Axis().Direction(); angle = crv.LastParameter() - crv.FirstParameter(); - } else { + } + else { throw Base::TypeError("AxisLink edge is neither line nor arc of circle."); } - if (reversed) + if (reversed) { occdir.Reverse(); - center.Set(base.X(), base.Y(),base.Z()); + } + center.Set(base.X(), base.Y(), base.Z()); dir.Set(occdir.X(), occdir.Y(), occdir.Z()); return true; } -App::DocumentObjectExecReturn *Revolution::execute() +App::DocumentObjectExecReturn* Revolution::execute() { App::DocumentObject* link = Source.getValue(); - if (!link) + if (!link) { return new App::DocumentObjectExecReturn("No object linked"); + } try { - //read out axis link + // read out axis link double angle_edge = 0; Base::Vector3d b = Base.getValue(); Base::Vector3d v = Axis.getValue(); bool linkFetched = this->fetchAxisLink(this->AxisLink, b, v, angle_edge); - if (linkFetched){ + if (linkFetched) { this->Base.setValue(b); this->Axis.setValue(v); } - gp_Pnt pnt(b.x,b.y,b.z); - gp_Dir dir(v.x,v.y,v.z); + gp_Pnt pnt(b.x, b.y, b.z); + gp_Dir dir(v.x, v.y, v.z); gp_Ax1 revAx(pnt, dir); - //read out revolution angle + // read out revolution angle double angle = Base::toRadians(Angle.getValue()); - if (fabs(angle) < Precision::Angular()) + if (fabs(angle) < Precision::Angular()) { angle = angle_edge; + } - //apply "midplane" symmetry - TopoShape sourceShape = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); + // apply "midplane" symmetry + TopoShape sourceShape + = Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform); if (Symmetric.getValue()) { - //rotate source shape backwards by half angle, to make resulting revolution symmetric to the profile + // rotate source shape backwards by half angle, to make resulting revolution symmetric + // to the profile gp_Trsf mov; mov.SetRotation(revAx, angle * (-0.5)); TopLoc_Location loc(mov); sourceShape.setShape(sourceShape.getShape().Moved(loc)); } TopoShape revolve(0, getDocument()->getStringHasher()); - revolve.makeElementRevolve(sourceShape, - revAx, - angle, - Solid.getValue() ? FaceMakerClass.getValue() : 0); + revolve.makeElementRevolve( + sourceShape, + revAx, + angle, + Solid.getValue() ? FaceMakerClass.getValue() : 0 + ); if (revolve.isNull()) { return new App::DocumentObjectExecReturn("Resulting shape is null"); } @@ -181,5 +230,5 @@ App::DocumentObjectExecReturn *Revolution::execute() void Part::Revolution::setupObject() { Part::Feature::setupObject(); - this->FaceMakerClass.setValue("Part::FaceMakerBullseye"); //default for newly created features + this->FaceMakerClass.setValue("Part::FaceMakerBullseye"); // default for newly created features } diff --git a/src/Mod/Part/App/FeatureRevolution.h b/src/Mod/Part/App/FeatureRevolution.h index 9c3339fef0..522895a76e 100644 --- a/src/Mod/Part/App/FeatureRevolution.h +++ b/src/Mod/Part/App/FeatureRevolution.h @@ -36,7 +36,7 @@ namespace Part { -class PartExport Revolution : public Part::Feature +class PartExport Revolution: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Revolution); @@ -48,20 +48,21 @@ public: App::PropertyVector Axis; App::PropertyLinkSub AxisLink; App::PropertyFloatConstraint Angle; - App::PropertyBool Symmetric; //like "Midplane" in PartDesign + App::PropertyBool Symmetric; // like "Midplane" in PartDesign App::PropertyBool Solid; App::PropertyString FaceMakerClass; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; void onChanged(const App::Property* prop) override; /// returns the type name of the view provider - const char* getViewProviderName() const override{ + const char* getViewProviderName() const override + { return "PartGui::ViewProviderRevolution"; } //@} @@ -78,10 +79,12 @@ public: * @return true if link was fetched. false if link was empty. Throws if the * link is wrong. */ - static bool fetchAxisLink(const App::PropertyLinkSub& axisLink, - Base::Vector3d ¢er, - Base::Vector3d &dir, - double &angle); + static bool fetchAxisLink( + const App::PropertyLinkSub& axisLink, + Base::Vector3d& center, + Base::Vector3d& dir, + double& angle + ); private: static App::PropertyFloatConstraint::Constraints angleRangeU; @@ -90,7 +93,7 @@ protected: void setupObject() override; }; -} //namespace Part +} // namespace Part -#endif // PART_FEATUREREVOLUTION_H +#endif // PART_FEATUREREVOLUTION_H diff --git a/src/Mod/Part/App/FeatureScale.cpp b/src/Mod/Part/App/FeatureScale.cpp index 39f498ba0e..70d6f9d0eb 100644 --- a/src/Mod/Part/App/FeatureScale.cpp +++ b/src/Mod/Part/App/FeatureScale.cpp @@ -43,20 +43,40 @@ Scale::Scale() { ADD_PROPERTY_TYPE(Base, (nullptr), "Scale", App::Prop_None, "Shape to scale"); ADD_PROPERTY_TYPE(Uniform, (true), "Scale", App::Prop_None, "If true, scale equally in all directions"); - ADD_PROPERTY_TYPE(UniformScale, (1.0), "Scale", App::Prop_None, "Uniform scale factor - 1.0 means no scaling"); - ADD_PROPERTY_TYPE(XScale, (1.0), "Scale", App::Prop_None, "Scale factor in X-direction - 1.0 means no scaling"); - ADD_PROPERTY_TYPE(YScale, (1.0), "Scale", App::Prop_None, "Scale factor in Y-direction - 1.0 means no scaling"); - ADD_PROPERTY_TYPE(ZScale, (1.0), "Scale", App::Prop_None, "Scale factor in Z-direction - 1.0 means no scaling"); + ADD_PROPERTY_TYPE( + UniformScale, + (1.0), + "Scale", + App::Prop_None, + "Uniform scale factor - 1.0 means no scaling" + ); + ADD_PROPERTY_TYPE( + XScale, + (1.0), + "Scale", + App::Prop_None, + "Scale factor in X-direction - 1.0 means no scaling" + ); + ADD_PROPERTY_TYPE( + YScale, + (1.0), + "Scale", + App::Prop_None, + "Scale factor in Y-direction - 1.0 means no scaling" + ); + ADD_PROPERTY_TYPE( + ZScale, + (1.0), + "Scale", + App::Prop_None, + "Scale factor in Z-direction - 1.0 means no scaling" + ); } short Scale::mustExecute() const { - if (Base.isTouched() || - Uniform.isTouched() || - UniformScale.isTouched() || - XScale.isTouched() || - YScale.isTouched() || - ZScale.isTouched()) { + if (Base.isTouched() || Uniform.isTouched() || UniformScale.isTouched() || XScale.isTouched() + || YScale.isTouched() || ZScale.isTouched()) { return 1; } return 0; @@ -88,7 +108,7 @@ TopoShape Scale::scaleShape(const TopoShape& source, const Scale::ScaleParameter TopoShape Scale::uniformScale(const TopoShape& source, const double& factor) { -// Base::Console().message("FS::uniformScale()\n"); + // Base::Console().message("FS::uniformScale()\n"); TopoDS_Shape transShape; TopoShape transTopo; try { @@ -107,24 +127,24 @@ TopoShape Scale::uniformScale(const TopoShape& source, const double& factor) TopoShape Scale::nonuniformScale(const TopoShape& source, const Scale::ScaleParameters& params) { -// Base::Console().message("FS::nonuniformScale()\n"); + // Base::Console().message("FS::nonuniformScale()\n"); Base::Matrix4D matScale; matScale.scale(params.XScale, params.YScale, params.ZScale); // copy the FreeCAD matrix cell values to an OCC matrix gp_GTrsf mat; - mat.SetValue(1,1,matScale[0][0]); - mat.SetValue(2,1,matScale[1][0]); - mat.SetValue(3,1,matScale[2][0]); - mat.SetValue(1,2,matScale[0][1]); - mat.SetValue(2,2,matScale[1][1]); - mat.SetValue(3,2,matScale[2][1]); - mat.SetValue(1,3,matScale[0][2]); - mat.SetValue(2,3,matScale[1][2]); - mat.SetValue(3,3,matScale[2][2]); - mat.SetValue(1,4,matScale[0][3]); - mat.SetValue(2,4,matScale[1][3]); - mat.SetValue(3,4,matScale[2][3]); + mat.SetValue(1, 1, matScale[0][0]); + mat.SetValue(2, 1, matScale[1][0]); + mat.SetValue(3, 1, matScale[2][0]); + mat.SetValue(1, 2, matScale[0][1]); + mat.SetValue(2, 2, matScale[1][1]); + mat.SetValue(3, 2, matScale[2][1]); + mat.SetValue(1, 3, matScale[0][2]); + mat.SetValue(2, 3, matScale[1][2]); + mat.SetValue(3, 3, matScale[2][2]); + mat.SetValue(1, 4, matScale[0][3]); + mat.SetValue(2, 4, matScale[1][3]); + mat.SetValue(3, 4, matScale[2][3]); // this copy step seems to eliminate Part.OCCError: gp_GTrsf::Trsf() - non-orthogonal GTrsf // which may to be related to the tessellation of the input shape. See Github issue #9651 @@ -144,14 +164,18 @@ TopoShape Scale::nonuniformScale(const TopoShape& source, const Scale::ScalePara App::DocumentObjectExecReturn* Scale::execute() { -// Base::Console().message("FS::execute()\n"); + // Base::Console().message("FS::execute()\n"); App::DocumentObject* link = Base.getValue(); - if (!link) + if (!link) { return new App::DocumentObjectExecReturn("No object linked"); + } try { Scale::ScaleParameters params = computeFinalParameters(); - TopoShape result = scaleShape(Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform), params); + TopoShape result = scaleShape( + Feature::getTopoShape(link, ShapeOption::ResolveLink | ShapeOption::Transform), + params + ); this->Shape.setValue(result); return App::DocumentObject::StdReturn; } @@ -159,4 +183,3 @@ App::DocumentObjectExecReturn* Scale::execute() return new App::DocumentObjectExecReturn(e.GetMessageString()); } } - diff --git a/src/Mod/Part/App/FeatureScale.h b/src/Mod/Part/App/FeatureScale.h index ab8efe7a6d..330f8e4686 100644 --- a/src/Mod/Part/App/FeatureScale.h +++ b/src/Mod/Part/App/FeatureScale.h @@ -37,7 +37,7 @@ namespace Part { -class PartExport Scale : public Part::Feature +class PartExport Scale: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Scale); @@ -55,21 +55,23 @@ public: * @brief The ScaleParameters struct is supposed to be filled with final * scale parameters and be passed to scaleShape. */ - struct ScaleParameters { - bool uniform{true}; - double uniformScale{1.0}; - double XScale{1.0}; - double YScale{1.0}; - double ZScale{1.0}; + struct ScaleParameters + { + bool uniform {true}; + double uniformScale {1.0}; + double XScale {1.0}; + double YScale {1.0}; + double ZScale {1.0}; }; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderScale"; } //@} @@ -86,8 +88,7 @@ public: static TopoShape nonuniformScale(const TopoShape& source, const Scale::ScaleParameters& params); }; -} //namespace Part +} // namespace Part -#endif // PART_FEATURESCALE_H - +#endif // PART_FEATURESCALE_H diff --git a/src/Mod/Part/App/FuzzyHelper.cpp b/src/Mod/Part/App/FuzzyHelper.cpp index 1d2548499a..954de855de 100644 --- a/src/Mod/Part/App/FuzzyHelper.cpp +++ b/src/Mod/Part/App/FuzzyHelper.cpp @@ -26,19 +26,23 @@ using namespace Part; -namespace { - double BooleanFuzzy = 1.0; +namespace +{ +double BooleanFuzzy = 1.0; } -double FuzzyHelper::getBooleanFuzzy() { +double FuzzyHelper::getBooleanFuzzy() +{ return BooleanFuzzy; } -void FuzzyHelper::setBooleanFuzzy(const double base) { +void FuzzyHelper::setBooleanFuzzy(const double base) +{ BooleanFuzzy = base; } -void FuzzyHelper::withBooleanFuzzy(double base, std::function func) { +void FuzzyHelper::withBooleanFuzzy(double base, std::function func) +{ double oldValue = getBooleanFuzzy(); setBooleanFuzzy(base); func(); diff --git a/src/Mod/Part/App/FuzzyHelper.h b/src/Mod/Part/App/FuzzyHelper.h index 96ffbd8c45..735e506229 100644 --- a/src/Mod/Part/App/FuzzyHelper.h +++ b/src/Mod/Part/App/FuzzyHelper.h @@ -36,11 +36,11 @@ namespace Part */ namespace FuzzyHelper { - double PartExport getBooleanFuzzy(); - void PartExport setBooleanFuzzy(double base); - void PartExport withBooleanFuzzy(double base, std::function func); -} +double PartExport getBooleanFuzzy(); +void PartExport setBooleanFuzzy(double base); +void PartExport withBooleanFuzzy(double base, std::function func); +} // namespace FuzzyHelper -} +} // namespace Part -#endif // PART_FUZZYHELPER_H +#endif // PART_FUZZYHELPER_H diff --git a/src/Mod/Part/App/Geom2d/ArcOfCircle2d.pyi b/src/Mod/Part/App/Geom2d/ArcOfCircle2d.pyi index 09edd36b7c..d75e932b93 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfCircle2d.pyi +++ b/src/Mod/Part/App/Geom2d/ArcOfCircle2d.pyi @@ -37,4 +37,4 @@ class ArcOfCircle2d(ArcOfConic2d): Circle : object The internal circle representation. """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp index 5173dab7d6..290f402a5b 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -46,7 +46,7 @@ std::string ArcOfCircle2dPy::representation() const return ""; } -PyObject *ArcOfCircle2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfCircle2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfCirclePy and the Twin object return new ArcOfCircle2dPy(new Geom2dArcOfCircle); @@ -57,11 +57,12 @@ int ArcOfCircle2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::Circle2dPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast - (static_cast(o)->getGeom2dCirclePtr()->handle()); + Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast( + static_cast(o)->getGeom2dCirclePtr()->handle() + ); GCE2d_MakeArcOfCircle arc(circle->Circ2d(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -83,16 +84,21 @@ int ArcOfCircle2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (PyArg_ParseTuple(args, "O!O!O!", Base::Vector2dPy::type_object(), &pV1, - Base::Vector2dPy::type_object(), &pV2, - Base::Vector2dPy::type_object(), &pV3)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + Base::Vector2dPy::type_object(), + &pV1, + Base::Vector2dPy::type_object(), + &pV2, + Base::Vector2dPy::type_object(), + &pV3 + )) { Base::Vector2d v1 = Py::toVector2d(pV1); Base::Vector2d v2 = Py::toVector2d(pV2); Base::Vector2d v3 = Py::toVector2d(pV3); - GCE2d_MakeArcOfCircle arc(gp_Pnt2d(v1.x,v1.y), - gp_Pnt2d(v2.x,v2.y), - gp_Pnt2d(v3.x,v3.y)); + GCE2d_MakeArcOfCircle arc(gp_Pnt2d(v1.x, v1.y), gp_Pnt2d(v2.x, v2.y), gp_Pnt2d(v3.x, v3.y)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); return -1; @@ -103,8 +109,10 @@ int ArcOfCircle2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfCircle2d constructor expects a circle curve and a parameter range or three points"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfCircle2d constructor expects a circle curve and a parameter range or three points" + ); return -1; } @@ -113,24 +121,26 @@ Py::Float ArcOfCircle2dPy::getRadius() const return Py::Float(getGeom2dArcOfCirclePtr()->getRadius()); } -void ArcOfCircle2dPy::setRadius(Py::Float arg) +void ArcOfCircle2dPy::setRadius(Py::Float arg) { getGeom2dArcOfCirclePtr()->setRadius((double)arg); } Py::Object ArcOfCircle2dPy::getCircle() const { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(curve->BasisCurve()); return Py::asObject(new Circle2dPy(new Geom2dCircle(circle))); } -PyObject *ArcOfCircle2dPy::getCustomAttributes(const char* ) const +PyObject* ArcOfCircle2dPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfCircle2dPy::setCustomAttributes(const char* , PyObject *) +int ArcOfCircle2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp index 71d489f0a5..6a351e99d6 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -41,11 +41,13 @@ std::string ArcOfConic2dPy::representation() const return ""; } -PyObject *ArcOfConic2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfConic2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'ArcOfConic2d'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'ArcOfConic2d'." + ); return nullptr; } @@ -61,7 +63,7 @@ Py::Object ArcOfConic2dPy::getLocation() const return Base::Vector2dPy::create(loc); } -void ArcOfConic2dPy::setLocation(Py::Object arg) +void ArcOfConic2dPy::setLocation(Py::Object arg) { Base::Vector2d loc = Py::toVector2d(arg.ptr()); getGeom2dArcOfConicPtr()->setLocation(loc); @@ -69,22 +71,28 @@ void ArcOfConic2dPy::setLocation(Py::Object arg) Py::Float ArcOfConic2dPy::getEccentricity() const { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); return Py::Float(conic->Eccentricity()); } Py::Object ArcOfConic2dPy::getXAxis() const { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); gp_Dir2d xdir = conic->XAxis().Direction(); return Base::Vector2dPy::create(xdir.X(), xdir.Y()); } -void ArcOfConic2dPy::setXAxis(Py::Object arg) +void ArcOfConic2dPy::setXAxis(Py::Object arg) { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); Base::Vector2d dir = Py::toVector2d(arg.ptr()); gp_Ax2d xaxis = conic->XAxis(); @@ -94,15 +102,19 @@ void ArcOfConic2dPy::setXAxis(Py::Object arg) Py::Object ArcOfConic2dPy::getYAxis() const { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); gp_Dir2d ydir = conic->YAxis().Direction(); return Base::Vector2dPy::create(ydir.X(), ydir.Y()); } -void ArcOfConic2dPy::setYAxis(Py::Object arg) +void ArcOfConic2dPy::setYAxis(Py::Object arg) { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); Base::Vector2d dir = Py::toVector2d(arg.ptr()); gp_Ax2d yaxis = conic->YAxis(); @@ -110,12 +122,12 @@ void ArcOfConic2dPy::setYAxis(Py::Object arg) conic->SetYAxis(yaxis); } -PyObject *ArcOfConic2dPy::getCustomAttributes(const char* ) const +PyObject* ArcOfConic2dPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfConic2dPy::setCustomAttributes(const char* , PyObject *) +int ArcOfConic2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/ArcOfEllipse2d.pyi b/src/Mod/Part/App/Geom2d/ArcOfEllipse2d.pyi index 62a4613216..1c4b12f80d 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfEllipse2d.pyi +++ b/src/Mod/Part/App/Geom2d/ArcOfEllipse2d.pyi @@ -27,5 +27,4 @@ class ArcOfEllipse2d(ArcOfConic2d): """The internal ellipse representation""" @overload - def __init__(self) -> None: - ... + def __init__(self) -> None: ... diff --git a/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp index 8d197aa9c4..52c8729f0d 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Geom2d/ArcOfEllipse2dPy.h" @@ -44,7 +44,7 @@ std::string ArcOfEllipse2dPy::representation() const return ""; } -PyObject *ArcOfEllipse2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfEllipse2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfEllipse2dPy and the Twin object return new ArcOfEllipse2dPy(new Geom2dArcOfEllipse); @@ -55,11 +55,12 @@ int ArcOfEllipse2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::Ellipse2dPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast - (static_cast(o)->getGeom2dEllipsePtr()->handle()); + Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast( + static_cast(o)->getGeom2dEllipsePtr()->handle() + ); GCE2d_MakeArcOfEllipse arc(ellipse->Elips2d(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -81,8 +82,10 @@ int ArcOfEllipse2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfEllipse2d constructor expects an ellipse curve and a parameter range"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfEllipse2d constructor expects an ellipse curve and a parameter range" + ); return -1; } @@ -91,7 +94,7 @@ Py::Float ArcOfEllipse2dPy::getMajorRadius() const return Py::Float(getGeom2dArcOfEllipsePtr()->getMajorRadius()); } -void ArcOfEllipse2dPy::setMajorRadius(Py::Float arg) +void ArcOfEllipse2dPy::setMajorRadius(Py::Float arg) { getGeom2dArcOfEllipsePtr()->setMajorRadius((double)arg); } @@ -101,24 +104,26 @@ Py::Float ArcOfEllipse2dPy::getMinorRadius() const return Py::Float(getGeom2dArcOfEllipsePtr()->getMinorRadius()); } -void ArcOfEllipse2dPy::setMinorRadius(Py::Float arg) +void ArcOfEllipse2dPy::setMinorRadius(Py::Float arg) { getGeom2dArcOfEllipsePtr()->setMinorRadius((double)arg); } Py::Object ArcOfEllipse2dPy::getEllipse() const { - Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); + Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfConicPtr()->handle() + ); Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(curve->BasisCurve()); return Py::asObject(new Ellipse2dPy(new Geom2dEllipse(ellipse))); } -PyObject *ArcOfEllipse2dPy::getCustomAttributes(const char* ) const +PyObject* ArcOfEllipse2dPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfEllipse2dPy::setCustomAttributes(const char* , PyObject *) +int ArcOfEllipse2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/ArcOfHyperbola2d.pyi b/src/Mod/Part/App/Geom2d/ArcOfHyperbola2d.pyi index 84dc9e95e8..b85a9e0723 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfHyperbola2d.pyi +++ b/src/Mod/Part/App/Geom2d/ArcOfHyperbola2d.pyi @@ -26,5 +26,4 @@ class ArcOfHyperbola2d(ArcOfConic2d): """The internal hyperbola representation""" @overload - def __init__(self) -> None: - ... + def __init__(self) -> None: ... diff --git a/src/Mod/Part/App/Geom2d/ArcOfHyperbola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfHyperbola2dPyImp.cpp index 68e260a575..94b038f6bb 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfHyperbola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfHyperbola2dPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Geom2d/ArcOfHyperbola2dPy.h" @@ -44,7 +44,7 @@ std::string ArcOfHyperbola2dPy::representation() const return ""; } -PyObject *ArcOfHyperbola2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfHyperbola2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfHyperbola2dPy and the Twin object return new ArcOfHyperbola2dPy(new Geom2dArcOfHyperbola); @@ -55,11 +55,12 @@ int ArcOfHyperbola2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::Hyperbola2dPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast - (static_cast(o)->getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + static_cast(o)->getGeom2dHyperbolaPtr()->handle() + ); GCE2d_MakeArcOfHyperbola arc(hyperbola->Hypr2d(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -81,8 +82,10 @@ int ArcOfHyperbola2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfHyperbola constructor expects an hyperbola curve and a parameter range"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfHyperbola constructor expects an hyperbola curve and a parameter range" + ); return -1; } @@ -91,7 +94,7 @@ Py::Float ArcOfHyperbola2dPy::getMajorRadius() const return Py::Float(getGeom2dArcOfHyperbolaPtr()->getMajorRadius()); } -void ArcOfHyperbola2dPy::setMajorRadius(Py::Float arg) +void ArcOfHyperbola2dPy::setMajorRadius(Py::Float arg) { getGeom2dArcOfHyperbolaPtr()->setMajorRadius((double)arg); } @@ -101,25 +104,26 @@ Py::Float ArcOfHyperbola2dPy::getMinorRadius() const return Py::Float(getGeom2dArcOfHyperbolaPtr()->getMinorRadius()); } -void ArcOfHyperbola2dPy::setMinorRadius(Py::Float arg) +void ArcOfHyperbola2dPy::setMinorRadius(Py::Float arg) { getGeom2dArcOfHyperbolaPtr()->setMinorRadius((double)arg); } Py::Object ArcOfHyperbola2dPy::getHyperbola() const { - Handle(Geom2d_TrimmedCurve) trim = Handle(Geom2d_TrimmedCurve)::DownCast - (getGeom2dArcOfHyperbolaPtr()->handle()); + Handle(Geom2d_TrimmedCurve) trim = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfHyperbolaPtr()->handle() + ); Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(trim->BasisCurve()); return Py::asObject(new Hyperbola2dPy(new Geom2dHyperbola(hyperbola))); } -PyObject *ArcOfHyperbola2dPy::getCustomAttributes(const char* ) const +PyObject* ArcOfHyperbola2dPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfHyperbola2dPy::setCustomAttributes(const char* , PyObject *) +int ArcOfHyperbola2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/ArcOfParabola2d.pyi b/src/Mod/Part/App/Geom2d/ArcOfParabola2d.pyi index 1e545310b9..286597a55a 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfParabola2d.pyi +++ b/src/Mod/Part/App/Geom2d/ArcOfParabola2d.pyi @@ -25,5 +25,4 @@ class ArcOfParabola2d(ArcOfConic2d): """The internal parabola representation.""" @overload - def __init__(self) -> None: - ... + def __init__(self) -> None: ... diff --git a/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp index 76c6d20e3e..c74e0ebf4d 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "Geom2d/ArcOfParabola2dPy.h" @@ -44,7 +44,7 @@ std::string ArcOfParabola2dPy::representation() const return ""; } -PyObject *ArcOfParabola2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ArcOfParabola2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ArcOfParabola2dPy and the Twin object return new ArcOfParabola2dPy(new Geom2dArcOfParabola); @@ -55,11 +55,12 @@ int ArcOfParabola2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* o; double u1, u2; - PyObject *sense=Py_True; + PyObject* sense = Py_True; if (PyArg_ParseTuple(args, "O!dd|O!", &(Part::Parabola2dPy::Type), &o, &u1, &u2, &PyBool_Type, &sense)) { try { - Handle(Geom2d_Parabola) parabola = Handle(Geom2d_Parabola)::DownCast - (static_cast(o)->getGeom2dParabolaPtr()->handle()); + Handle(Geom2d_Parabola) parabola = Handle(Geom2d_Parabola)::DownCast( + static_cast(o)->getGeom2dParabolaPtr()->handle() + ); GCE2d_MakeArcOfParabola arc(parabola->Parab2d(), u1, u2, Base::asBoolean(sense)); if (!arc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(arc.Status())); @@ -81,8 +82,10 @@ int ArcOfParabola2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // All checks failed - PyErr_SetString(PyExc_TypeError, - "ArcOfParabola2d constructor expects an parabola curve and a parameter range"); + PyErr_SetString( + PyExc_TypeError, + "ArcOfParabola2d constructor expects an parabola curve and a parameter range" + ); return -1; } @@ -91,25 +94,26 @@ Py::Float ArcOfParabola2dPy::getFocal() const return Py::Float(getGeom2dArcOfParabolaPtr()->getFocal()); } -void ArcOfParabola2dPy::setFocal(Py::Float arg) +void ArcOfParabola2dPy::setFocal(Py::Float arg) { getGeom2dArcOfParabolaPtr()->setFocal((double)arg); } Py::Object ArcOfParabola2dPy::getParabola() const { - Handle(Geom2d_TrimmedCurve) trim = Handle(Geom2d_TrimmedCurve)::DownCast - (getGeom2dArcOfParabolaPtr()->handle()); + Handle(Geom2d_TrimmedCurve) trim = Handle(Geom2d_TrimmedCurve)::DownCast( + getGeom2dArcOfParabolaPtr()->handle() + ); Handle(Geom2d_Parabola) parabola = Handle(Geom2d_Parabola)::DownCast(trim->BasisCurve()); return Py::asObject(new Parabola2dPy(new Geom2dParabola(parabola))); } -PyObject *ArcOfParabola2dPy::getCustomAttributes(const char* ) const +PyObject* ArcOfParabola2dPy::getCustomAttributes(const char*) const { return nullptr; } -int ArcOfParabola2dPy::setCustomAttributes(const char* , PyObject *) +int ArcOfParabola2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/BSplineCurve2d.pyi b/src/Mod/Part/App/Geom2d/BSplineCurve2d.pyi index 0b3448af6a..c25668c688 100644 --- a/src/Mod/Part/App/Geom2d/BSplineCurve2d.pyi +++ b/src/Mod/Part/App/Geom2d/BSplineCurve2d.pyi @@ -83,13 +83,9 @@ class BSplineCurve2d(Curve2d): ... @overload - def increaseMultiplicity(self, index: int, mult: int) -> None: - ... - + def increaseMultiplicity(self, index: int, mult: int) -> None: ... @overload - def increaseMultiplicity(self, start: int, end: int, mult: int) -> None: - ... - + def increaseMultiplicity(self, start: int, end: int, mult: int) -> None: ... def increaseMultiplicity(self, *args, **kwargs) -> None: """ increaseMultiplicity(int index, int mult) @@ -120,7 +116,13 @@ class BSplineCurve2d(Curve2d): """ ... - def insertKnots(self, list_of_floats: list[float], list_of_ints: list[int], tol: float = 0.0, bool_add: bool = True) -> None: + def insertKnots( + self, + list_of_floats: list[float], + list_of_ints: list[int], + tol: float = 0.0, + bool_add: bool = True, + ) -> None: """ insertKnots(list_of_floats, list_of_ints, tol = 0.0, bool_add = True) @@ -368,13 +370,25 @@ class BSplineCurve2d(Curve2d): ... @overload - def buildFromPolesMultsKnots(self, poles: list[Vector], mults: tuple[int, ...], knots: tuple[float, ...], periodic: bool, degree: int) -> None: - ... - + def buildFromPolesMultsKnots( + self, + poles: list[Vector], + mults: tuple[int, ...], + knots: tuple[float, ...], + periodic: bool, + degree: int, + ) -> None: ... @overload - def buildFromPolesMultsKnots(self, poles: list[Vector], mults: tuple[int, ...], knots: tuple[float, ...], periodic: bool, degree: int, weights: tuple[float, ...], CheckRational: bool) -> None: - ... - + def buildFromPolesMultsKnots( + self, + poles: list[Vector], + mults: tuple[int, ...], + knots: tuple[float, ...], + periodic: bool, + degree: int, + weights: tuple[float, ...], + CheckRational: bool, + ) -> None: ... def buildFromPolesMultsKnots(self, **kwargs) -> None: """ Builds a B-Spline by a lists of Poles, Mults, Knots. @@ -434,4 +448,4 @@ class BSplineCurve2d(Curve2d): of the tangents on the left and on the right to decide if the curve is G1 or not at a given point. """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp index f9fcb5c59c..4679abbe0b 100644 --- a/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp @@ -22,19 +22,19 @@ * * ***************************************************************************/ -# 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 @@ -54,7 +54,7 @@ std::string BSplineCurve2dPy::representation() const return ""; } -PyObject *BSplineCurve2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BSplineCurve2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BSplineCurve2dPy and the Twin object return new BSplineCurve2dPy(new Geom2dBSplineCurve); @@ -67,49 +67,60 @@ int BSplineCurve2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, "B-spline constructor accepts:\n" - "-- empty parameter list\n"); + PyErr_SetString( + PyExc_TypeError, + "B-spline constructor accepts:\n" + "-- empty parameter list\n" + ); return -1; } -PyObject* BSplineCurve2dPy::isRational(PyObject *args) +PyObject* BSplineCurve2dPy::isRational(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Boolean val = curve->IsRational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineCurve2dPy::isPeriodic(PyObject *args) +PyObject* BSplineCurve2dPy::isPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Boolean val = curve->IsPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineCurve2dPy::isClosed(PyObject *args) +PyObject* BSplineCurve2dPy::isClosed(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Boolean val = curve->IsClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BSplineCurve2dPy::increaseDegree(PyObject * args) +PyObject* BSplineCurve2dPy::increaseDegree(PyObject* args) { int degree; - if (!PyArg_ParseTuple(args, "i", °ree)) + if (!PyArg_ParseTuple(args, "i", °ree)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->IncreaseDegree(degree); Py_Return; } @@ -119,16 +130,18 @@ PyObject* BSplineCurve2dPy::increaseDegree(PyObject * args) } } -PyObject* BSplineCurve2dPy::increaseMultiplicity(PyObject * args) +PyObject* BSplineCurve2dPy::increaseMultiplicity(PyObject* args) { - int mult=-1; + int mult = -1; int start, end; - if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "ii|i", &start, &end, &mult)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); if (mult == -1) { mult = end; curve->IncreaseMultiplicity(start, mult); @@ -145,15 +158,17 @@ PyObject* BSplineCurve2dPy::increaseMultiplicity(PyObject * args) } } -PyObject* BSplineCurve2dPy::incrementMultiplicity(PyObject * args) +PyObject* BSplineCurve2dPy::incrementMultiplicity(PyObject* args) { int start, end, mult; - if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) + if (!PyArg_ParseTuple(args, "iii", &start, &end, &mult)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->IncrementMultiplicity(start, end, mult); } catch (Standard_Failure& e) { @@ -164,19 +179,20 @@ PyObject* BSplineCurve2dPy::incrementMultiplicity(PyObject * args) Py_Return; } -PyObject* BSplineCurve2dPy::insertKnot(PyObject * args) +PyObject* BSplineCurve2dPy::insertKnot(PyObject* args) { double U; double tol = 0.0; - int M=1; + int M = 1; if (!PyArg_ParseTuple(args, "d|id", &U, &M, &tol)) { return nullptr; } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->InsertKnot(U,M,tol); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->InsertKnot(U, M, tol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -186,35 +202,35 @@ PyObject* BSplineCurve2dPy::insertKnot(PyObject * args) Py_Return; } -PyObject* BSplineCurve2dPy::insertKnots(PyObject * args) +PyObject* BSplineCurve2dPy::insertKnots(PyObject* args) { double tol = 0.0; PyObject* add = Py_True; PyObject* obj1; PyObject* obj2; - if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, - &obj2, - &tol, &PyBool_Type, &add)) + if (!PyArg_ParseTuple(args, "OO|dO!", &obj1, &obj2, &tol, &PyBool_Type, &add)) { return nullptr; + } try { Py::Sequence knots(obj1); - TColStd_Array1OfReal k(1,knots.size()); - int index=1; + TColStd_Array1OfReal k(1, knots.size()); + int index = 1; for (Py::Sequence::iterator it = knots.begin(); it != knots.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } Py::Sequence mults(obj2); - TColStd_Array1OfInteger m(1,mults.size()); - index=1; + TColStd_Array1OfInteger m(1, mults.size()); + index = 1; for (Py::Sequence::iterator it = mults.begin(); it != mults.end(); ++it) { Py::Long val(*it); m(index++) = (int)val; } - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->InsertKnots(k, m, tol, Base::asBoolean(add)); Py_Return; } @@ -226,17 +242,19 @@ PyObject* BSplineCurve2dPy::insertKnots(PyObject * args) Py_Return; } -PyObject* BSplineCurve2dPy::removeKnot(PyObject * args) +PyObject* BSplineCurve2dPy::removeKnot(PyObject* args) { double tol; - int Index,M; - if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) + int Index, M; + if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - Standard_Boolean ok = curve->RemoveKnot(Index,M,tol); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + Standard_Boolean ok = curve->RemoveKnot(Index, M, tol); return PyBool_FromLong(ok ? 1 : 0); } catch (Standard_Failure& e) { @@ -245,15 +263,17 @@ PyObject* BSplineCurve2dPy::removeKnot(PyObject * args) } } -PyObject* BSplineCurve2dPy::segment(PyObject * args) +PyObject* BSplineCurve2dPy::segment(PyObject* args) { - double u1,u2; - if (!PyArg_ParseTuple(args, "dd", &u1,&u2)) + double u1, u2; + if (!PyArg_ParseTuple(args, "dd", &u1, &u2)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->Segment(u1,u2); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->Segment(u1, u2); Py_Return; } catch (Standard_Failure& e) { @@ -262,15 +282,17 @@ PyObject* BSplineCurve2dPy::segment(PyObject * args) } } -PyObject* BSplineCurve2dPy::setKnot(PyObject * args) +PyObject* BSplineCurve2dPy::setKnot(PyObject* args) { - int Index, M=-1; + int Index, M = -1; double K; - if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) + if (!PyArg_ParseTuple(args, "id|i", &Index, &K, &M)) { return nullptr; + } - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); if (M == -1) { curve->SetKnot(Index, K); } @@ -281,35 +303,39 @@ PyObject* BSplineCurve2dPy::setKnot(PyObject * args) Py_Return; } -PyObject* BSplineCurve2dPy::getKnot(PyObject * args) +PyObject* BSplineCurve2dPy::getKnot(PyObject* args) { int Index; - if (!PyArg_ParseTuple(args, "i", &Index)) + if (!PyArg_ParseTuple(args, "i", &Index)) { return nullptr; + } - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); double M = curve->Knot(Index); - return Py_BuildValue("d",M); + return Py_BuildValue("d", M); } -PyObject* BSplineCurve2dPy::setKnots(PyObject * args) +PyObject* BSplineCurve2dPy::setKnots(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } try { Py::Sequence list(obj); - TColStd_Array1OfReal k(1,list.size()); - int index=1; + TColStd_Array1OfReal k(1, list.size()); + int index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->SetKnots(k); Py_Return; } @@ -319,17 +345,19 @@ PyObject* BSplineCurve2dPy::setKnots(PyObject * args) } } -PyObject* BSplineCurve2dPy::getKnots(PyObject * args) +PyObject* BSplineCurve2dPy::getKnots(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - TColStd_Array1OfReal w(1,curve->NbKnots()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + TColStd_Array1OfReal w(1, curve->NbKnots()); curve->Knots(w); Py::List knots; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { knots.append(Py::Float(w(i))); } return Py::new_reference_to(knots); @@ -340,22 +368,26 @@ PyObject* BSplineCurve2dPy::getKnots(PyObject * args) } } -PyObject* BSplineCurve2dPy::setPole(PyObject * args) +PyObject* BSplineCurve2dPy::setPole(PyObject* args) { int index; - double weight=-1.0; + double weight = -1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) { return nullptr; + } Base::Vector2d vec = Py::toVector2d(p); gp_Pnt2d pnt(vec.x, vec.y); try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - if (weight < 0.0) - curve->SetPole(index,pnt); - else - curve->SetPole(index,pnt,weight); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + if (weight < 0.0) { + curve->SetPole(index, pnt); + } + else { + curve->SetPole(index, pnt, weight); + } Py_Return; } catch (Standard_Failure& e) { @@ -364,16 +396,17 @@ PyObject* BSplineCurve2dPy::setPole(PyObject * args) } } -PyObject* BSplineCurve2dPy::getPole(PyObject * args) +PyObject* BSplineCurve2dPy::getPole(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles(), "Pole index out of range"); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Pole index out of range"); gp_Pnt2d pnt = curve->Pole(index); return Py::new_reference_to(Base::Vector2dPy::create(pnt.X(), pnt.Y())); } @@ -383,18 +416,20 @@ PyObject* BSplineCurve2dPy::getPole(PyObject * args) } } -PyObject* BSplineCurve2dPy::getPoles(PyObject * args) +PyObject* BSplineCurve2dPy::getPoles(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); TColgp_Array1OfPnt2d p(1, (int)curve->NbPoles()); curve->Poles(p); Py::List poles; - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { gp_Pnt2d pnt = p(i); poles.append(Base::Vector2dPy::create(pnt.X(), pnt.Y())); } @@ -406,20 +441,22 @@ PyObject* BSplineCurve2dPy::getPoles(PyObject * args) } } -PyObject* BSplineCurve2dPy::getPolesAndWeights(PyObject * args) +PyObject* BSplineCurve2dPy::getPolesAndWeights(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - TColgp_Array1OfPnt2d p(1,curve->NbPoles()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + TColgp_Array1OfPnt2d p(1, curve->NbPoles()); curve->Poles(p); - TColStd_Array1OfReal w(1,curve->NbPoles()); + TColStd_Array1OfReal w(1, curve->NbPoles()); curve->Weights(w); Py::List poles; - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { gp_Pnt2d pnt = p(i); double weight = w(i); Py::Tuple t(3); @@ -436,16 +473,18 @@ PyObject* BSplineCurve2dPy::getPolesAndWeights(PyObject * args) } } -PyObject* BSplineCurve2dPy::setWeight(PyObject * args) +PyObject* BSplineCurve2dPy::setWeight(PyObject* args) { int index; double weight; - if (!PyArg_ParseTuple(args, "id", &index,&weight)) + if (!PyArg_ParseTuple(args, "id", &index, &weight)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->SetWeight(index,weight); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->SetWeight(index, weight); Py_Return; } catch (Standard_Failure& e) { @@ -454,16 +493,17 @@ PyObject* BSplineCurve2dPy::setWeight(PyObject * args) } } -PyObject* BSplineCurve2dPy::getWeight(PyObject * args) +PyObject* BSplineCurve2dPy::getWeight(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles() , "Weight index out of range"); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Weight index out of range"); double weight = curve->Weight(index); return Py_BuildValue("d", weight); } @@ -473,17 +513,19 @@ PyObject* BSplineCurve2dPy::getWeight(PyObject * args) } } -PyObject* BSplineCurve2dPy::getWeights(PyObject * args) +PyObject* BSplineCurve2dPy::getWeights(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - TColStd_Array1OfReal w(1,curve->NbPoles()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + TColStd_Array1OfReal w(1, curve->NbPoles()); curve->Weights(w); Py::List weights; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { weights.append(Py::Float(w(i))); } return Py::new_reference_to(weights); @@ -494,17 +536,19 @@ PyObject* BSplineCurve2dPy::getWeights(PyObject * args) } } -PyObject* BSplineCurve2dPy::getResolution(PyObject * args) const +PyObject* BSplineCurve2dPy::getResolution(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); double utol; - curve->Resolution(tol,utol); - return Py_BuildValue("d",utol); + curve->Resolution(tol, utol); + return Py_BuildValue("d", utol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -512,20 +556,22 @@ PyObject* BSplineCurve2dPy::getResolution(PyObject * args) const } } -PyObject* BSplineCurve2dPy::movePoint(PyObject * args) +PyObject* BSplineCurve2dPy::movePoint(PyObject* args) { double U; int index1, index2; PyObject* pnt; - if (!PyArg_ParseTuple(args, "dO!ii", &U, Base::Vector2dPy::type_object(),&pnt, &index1, &index2)) + if (!PyArg_ParseTuple(args, "dO!ii", &U, Base::Vector2dPy::type_object(), &pnt, &index1, &index2)) { return nullptr; + } try { Base::Vector2d p = Py::toVector2d(pnt); - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); int first, last; - curve->MovePoint(U, gp_Pnt2d(p.x,p.y), index1, index2, first, last); - return Py_BuildValue("(ii)",first, last); + curve->MovePoint(U, gp_Pnt2d(p.x, p.y), index1, index2, first, last); + return Py_BuildValue("(ii)", first, last); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -533,13 +579,15 @@ PyObject* BSplineCurve2dPy::movePoint(PyObject * args) } } -PyObject* BSplineCurve2dPy::setNotPeriodic(PyObject * args) +PyObject* BSplineCurve2dPy::setNotPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->SetNotPeriodic(); Py_Return; } @@ -549,13 +597,15 @@ PyObject* BSplineCurve2dPy::setNotPeriodic(PyObject * args) } } -PyObject* BSplineCurve2dPy::setPeriodic(PyObject * args) +PyObject* BSplineCurve2dPy::setPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->SetPeriodic(); Py_Return; } @@ -565,14 +615,16 @@ PyObject* BSplineCurve2dPy::setPeriodic(PyObject * args) } } -PyObject* BSplineCurve2dPy::setOrigin(PyObject * args) +PyObject* BSplineCurve2dPy::setOrigin(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->SetOrigin(index); Py_Return; } @@ -582,14 +634,16 @@ PyObject* BSplineCurve2dPy::setOrigin(PyObject * args) } } -PyObject* BSplineCurve2dPy::getMultiplicity(PyObject * args) +PyObject* BSplineCurve2dPy::getMultiplicity(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); int mult = curve->Multiplicity(index); return Py_BuildValue("i", mult); } @@ -600,17 +654,19 @@ PyObject* BSplineCurve2dPy::getMultiplicity(PyObject * args) } } -PyObject* BSplineCurve2dPy::getMultiplicities(PyObject * args) +PyObject* BSplineCurve2dPy::getMultiplicities(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); - TColStd_Array1OfInteger m(1,curve->NbKnots()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + TColStd_Array1OfInteger m(1, curve->NbKnots()); curve->Multiplicities(m); Py::List mults; - for (Standard_Integer i=m.Lower(); i<=m.Upper(); i++) { + for (Standard_Integer i = m.Lower(); i <= m.Upper(); i++) { mults.append(Py::Long(m(i))); } return Py::new_reference_to(mults); @@ -623,91 +679,98 @@ PyObject* BSplineCurve2dPy::getMultiplicities(PyObject * args) Py::Long BSplineCurve2dPy::getDegree() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->Degree()); } Py::Long BSplineCurve2dPy::getMaxDegree() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->MaxDegree()); } Py::Long BSplineCurve2dPy::getNbPoles() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->NbPoles()); } Py::Long BSplineCurve2dPy::getNbKnots() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->NbKnots()); } Py::Object BSplineCurve2dPy::getStartPoint() const { - Handle(Geom2d_BSplineCurve) c = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) c = Handle(Geom2d_BSplineCurve)::DownCast(getGeometry2dPtr()->handle()); gp_Pnt2d pnt = c->StartPoint(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } Py::Object BSplineCurve2dPy::getEndPoint() const { - Handle(Geom2d_BSplineCurve) c = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) c = Handle(Geom2d_BSplineCurve)::DownCast(getGeometry2dPtr()->handle()); gp_Pnt2d pnt = c->EndPoint(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } Py::Object BSplineCurve2dPy::getFirstUKnotIndex() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->FirstUKnotIndex()); } Py::Object BSplineCurve2dPy::getLastUKnotIndex() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->LastUKnotIndex()); } Py::List BSplineCurve2dPy::getKnotSequence() const { - Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Integer m = 0; if (curve->IsPeriodic()) { // knots=poles+2*degree-mult(1)+2 - m = (int)(curve->NbPoles() + 2*curve->Degree() - curve->Multiplicity(1) + 2); + m = (int)(curve->NbPoles() + 2 * curve->Degree() - curve->Multiplicity(1) + 2); } else { // knots=poles+degree+1 - for (int i=1; i<= curve->NbKnots(); i++) + for (int i = 1; i <= curve->NbKnots(); i++) { m += (int)curve->Multiplicity(i); + } } - TColStd_Array1OfReal k(1,m); + TColStd_Array1OfReal k(1, m); curve->KnotSequence(k); Py::List list; - for (Standard_Integer i=k.Lower(); i<=k.Upper(); i++) { + for (Standard_Integer i = k.Lower(); i <= k.Upper(); i++) { list.append(Py::Float(k(i))); } return list; } -PyObject* BSplineCurve2dPy::toBiArcs(PyObject * args) +PyObject* BSplineCurve2dPy::toBiArcs(PyObject* args) { double tolerance = 0.001; - if (!PyArg_ParseTuple(args, "d", &tolerance)) + if (!PyArg_ParseTuple(args, "d", &tolerance)) { return nullptr; + } try { Geom2dBSplineCurve* curve = getGeom2dBSplineCurvePtr(); std::list arcs; @@ -727,11 +790,11 @@ PyObject* BSplineCurve2dPy::toBiArcs(PyObject * args) } } -PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) +PyObject* BSplineCurve2dPy::approximate(PyObject* args, PyObject* kwds) { PyObject* obj; - Standard_Integer degMin=3; - Standard_Integer degMax=8; + Standard_Integer degMin = 3; + Standard_Integer degMax = 8; const char* continuity = "C2"; double tol3d = 1e-3; const char* parType = "ChordLength"; @@ -740,25 +803,46 @@ PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) double weight2 = 0; double weight3 = 0; - static const std::array kwds_interp{"Points", "DegMax", "Continuity", "Tolerance", "DegMin", - "ParamType", "Parameters", "LengthWeight", "CurvatureWeight", - "TorsionWeight", nullptr}; + static const std::array kwds_interp { + "Points", + "DegMax", + "Continuity", + "Tolerance", + "DegMin", + "ParamType", + "Parameters", + "LengthWeight", + "CurvatureWeight", + "TorsionWeight", + nullptr + }; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O|isdisOddd",kwds_interp, - &obj, °Max, - &continuity, &tol3d, °Min, - &parType, &par, - &weight1, &weight2, &weight3)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O|isdisOddd", + kwds_interp, + &obj, + °Max, + &continuity, + &tol3d, + °Min, + &parType, + &par, + &weight1, + &weight2, + &weight3 + )) { return nullptr; } try { Py::Sequence list(obj); - TColgp_Array1OfPnt2d pnts(1,list.size()); + TColgp_Array1OfPnt2d pnts(1, list.size()); Standard_Integer index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d vec = Py::toVector2d(*it); - pnts(index++) = gp_Pnt2d(vec.x,vec.y); + pnts(index++) = gp_Pnt2d(vec.x, vec.y); } if (degMin > degMax) { @@ -767,22 +851,30 @@ PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) GeomAbs_Shape c; std::string str = continuity; - if (str == "C0") + if (str == "C0") { c = GeomAbs_C0; - else if (str == "G1") + } + else if (str == "G1") { c = GeomAbs_G1; - else if (str == "C1") + } + else if (str == "C1") { c = GeomAbs_C1; - else if (str == "G2") + } + else if (str == "G2") { c = GeomAbs_G2; - else if (str == "C2") + } + else if (str == "C2") { c = GeomAbs_C2; - else if (str == "C3") + } + else if (str == "C3") { c = GeomAbs_C3; - else if (str == "CN") + } + else if (str == "CN") { c = GeomAbs_CN; - else + } + else { c = GeomAbs_C2; + } if (weight1 || weight2 || weight3) { // It seems that this function only works with Continuity = C0, C1 or C2 @@ -798,13 +890,13 @@ PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("Smoothing approximation failed"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } if (par) { Py::Sequence plist(par); - TColStd_Array1OfReal parameters(1,plist.size()); + TColStd_Array1OfReal parameters(1, plist.size()); Standard_Integer index = 1; for (Py::Sequence::iterator it = plist.begin(); it != plist.end(); ++it) { Py::Float f(*it); @@ -819,18 +911,21 @@ PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("Approximation with parameters failed"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } Approx_ParametrizationType pt; std::string pstr = parType; - if (pstr == "Uniform") + if (pstr == "Uniform") { pt = Approx_IsoParametric; - else if (pstr == "Centripetal") + } + else if (pstr == "Centripetal") { pt = Approx_Centripetal; - else + } + else { pt = Approx_ChordLength; + } Geom2dAPI_PointsToBSpline fit(pnts, pt, degMin, degMax, c, tol3d); Handle(Geom2d_BSplineCurve) spline = fit.Curve(); @@ -840,7 +935,7 @@ PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("failed to approximate points"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } catch (Standard_Failure& e) { @@ -849,20 +944,20 @@ PyObject* BSplineCurve2dPy::approximate(PyObject *args, PyObject *kwds) } } -PyObject* BSplineCurve2dPy::getCardinalSplineTangents(PyObject *args, PyObject *kwds) +PyObject* BSplineCurve2dPy::getCardinalSplineTangents(PyObject* args, PyObject* kwds) { PyObject* pts; PyObject* tgs; double parameter; - static const std::array kwds_interp1 {"Points", "Parameter", nullptr}; + static const std::array kwds_interp1 {"Points", "Parameter", nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "Od", kwds_interp1, &pts, ¶meter)) { Py::Sequence list(pts); std::vector interpPoints; interpPoints.reserve(list.size()); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d pnt = Py::toVector2d(*it); - interpPoints.emplace_back(pnt.x,pnt.y); + interpPoints.emplace_back(pnt.x, pnt.y); } Geom2dBSplineCurve* bspline = this->getGeom2dBSplineCurvePtr(); @@ -877,14 +972,14 @@ PyObject* BSplineCurve2dPy::getCardinalSplineTangents(PyObject *args, PyObject * } PyErr_Clear(); - static const std::array kwds_interp2 {"Points", "Parameters", nullptr}; + static const std::array kwds_interp2 {"Points", "Parameters", nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "OO", kwds_interp2, &pts, &tgs)) { Py::Sequence list(pts); std::vector interpPoints; interpPoints.reserve(list.size()); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d pnt = Py::toVector2d(*it); - interpPoints.emplace_back(pnt.x,pnt.y); + interpPoints.emplace_back(pnt.x, pnt.y); } Py::Sequence list2(tgs); @@ -909,24 +1004,46 @@ PyObject* BSplineCurve2dPy::getCardinalSplineTangents(PyObject *args, PyObject * return nullptr; } -PyObject* BSplineCurve2dPy::interpolate(PyObject *args, PyObject *kwds) +PyObject* BSplineCurve2dPy::interpolate(PyObject* args, PyObject* kwds) { PyObject* obj; PyObject* par = nullptr; double tol3d = Precision::Approximation(); PyObject* periodic = Py_False; - PyObject* t1 = nullptr; PyObject* t2 = nullptr; - PyObject* ts = nullptr; PyObject* fl = nullptr; + PyObject* t1 = nullptr; + PyObject* t2 = nullptr; + PyObject* ts = nullptr; + PyObject* fl = nullptr; - static const std::array kwds_interp{"Points", "PeriodicFlag", "Tolerance", "InitialTangent", - "FinalTangent", "Tangents", "TangentFlags", "Parameters", - nullptr}; + static const std::array kwds_interp { + "Points", + "PeriodicFlag", + "Tolerance", + "InitialTangent", + "FinalTangent", + "Tangents", + "TangentFlags", + "Parameters", + nullptr + }; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O|O!dO!O!OOO",kwds_interp, - &obj, &PyBool_Type, &periodic, &tol3d, - Base::Vector2dPy::type_object(), &t1, - Base::Vector2dPy::type_object(), &t2, - &ts, &fl, &par)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O|O!dO!O!OOO", + kwds_interp, + &obj, + &PyBool_Type, + &periodic, + &tol3d, + Base::Vector2dPy::type_object(), + &t1, + Base::Vector2dPy::type_object(), + &t2, + &ts, + &fl, + &par + )) { return nullptr; } @@ -936,7 +1053,7 @@ PyObject* BSplineCurve2dPy::interpolate(PyObject *args, PyObject *kwds) Standard_Integer index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d pnt = Py::toVector2d(*it); - interpolationPoints->SetValue(index++, gp_Pnt2d(pnt.x,pnt.y)); + interpolationPoints->SetValue(index++, gp_Pnt2d(pnt.x, pnt.y)); } if (interpolationPoints->Length() < 2) { @@ -958,20 +1075,23 @@ PyObject* BSplineCurve2dPy::interpolate(PyObject *args, PyObject *kwds) if (parameters.IsNull()) { aBSplineInterpolation = std::make_unique( interpolationPoints, - Base::asBoolean(periodic), tol3d + Base::asBoolean(periodic), + tol3d ); } else { aBSplineInterpolation = std::make_unique( - interpolationPoints, parameters, - Base::asBoolean(periodic), tol3d + interpolationPoints, + parameters, + Base::asBoolean(periodic), + tol3d ); } if (t1 && t2) { Base::Vector2d v1 = Py::toVector2d(t1); Base::Vector2d v2 = Py::toVector2d(t2); - gp_Vec2d initTangent(v1.x,v1.y), finalTangent(v2.x,v2.y); + gp_Vec2d initTangent(v1.x, v1.y), finalTangent(v2.x, v2.y); aBSplineInterpolation->Load(initTangent, finalTangent); } else if (ts && fl) { @@ -980,15 +1100,19 @@ PyObject* BSplineCurve2dPy::interpolate(PyObject *args, PyObject *kwds) Standard_Integer index = 1; for (Py::Sequence::iterator it = tlist.begin(); it != tlist.end(); ++it) { Base::Vector2d vec = Py::toVector2d(*it); - tangents.SetValue(index++, gp_Vec2d(vec.x,vec.y)); + tangents.SetValue(index++, gp_Vec2d(vec.x, vec.y)); } Py::Sequence flist(fl); - Handle(TColStd_HArray1OfBoolean) tangentFlags = new TColStd_HArray1OfBoolean(1, flist.size()); + Handle(TColStd_HArray1OfBoolean) tangentFlags + = new TColStd_HArray1OfBoolean(1, flist.size()); Standard_Integer findex = 1; for (Py::Sequence::iterator it = flist.begin(); it != flist.end(); ++it) { Py::Boolean flag(*it); - tangentFlags->SetValue(findex++, static_cast(flag) ? Standard_True : Standard_False); + tangentFlags->SetValue( + findex++, + static_cast(flag) ? Standard_True : Standard_False + ); } aBSplineInterpolation->Load(tangents, tangentFlags); @@ -1002,36 +1126,40 @@ PyObject* BSplineCurve2dPy::interpolate(PyObject *args, PyObject *kwds) } else { Standard_Failure::Raise("failed to interpolate points"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } } -PyObject* BSplineCurve2dPy::buildFromPoles(PyObject *args) +PyObject* BSplineCurve2dPy::buildFromPoles(PyObject* args) { PyObject* obj; int degree = 3; PyObject* periodic = Py_False; PyObject* interpolate = Py_False; - if (!PyArg_ParseTuple(args, "O|O!iO!",&obj, &PyBool_Type, &periodic, °ree, &PyBool_Type, interpolate)) + if (!PyArg_ParseTuple(args, "O|O!iO!", &obj, &PyBool_Type, &periodic, °ree, &PyBool_Type, interpolate)) { return nullptr; + } try { Py::Sequence list(obj); TColgp_Array1OfPnt2d poles(1, list.size()); Standard_Integer index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d pnt = Py::toVector2d(*it); - poles(index++) = gp_Pnt2d(pnt.x,pnt.y); + poles(index++) = gp_Pnt2d(pnt.x, pnt.y); } - if (poles.Length() <= degree) - degree = poles.Length()-1; + if (poles.Length() <= degree) { + degree = poles.Length() - 1; + } if (Base::asBoolean(periodic)) { int mult; @@ -1046,41 +1174,43 @@ PyObject* BSplineCurve2dPy::buildFromPoles(PyObject *args) } TColStd_Array1OfReal knots(1, len); TColStd_Array1OfInteger mults(1, len); - for (int i=1; i<=knots.Length(); i++){ - knots.SetValue(i,(double)(i-1)/(knots.Length()-1)); - mults.SetValue(i,1); + for (int i = 1; i <= knots.Length(); i++) { + knots.SetValue(i, (double)(i - 1) / (knots.Length() - 1)); + mults.SetValue(i, 1); } mults.SetValue(1, mult); mults.SetValue(knots.Length(), mult); - Handle(Geom2d_BSplineCurve) spline = new Geom2d_BSplineCurve(poles, knots, mults, degree, Standard_True); + Handle(Geom2d_BSplineCurve) spline + = new Geom2d_BSplineCurve(poles, knots, mults, degree, Standard_True); if (!spline.IsNull()) { this->getGeom2dBSplineCurvePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } else { - TColStd_Array1OfReal knots(1, poles.Length()+degree+1-2*(degree)); - TColStd_Array1OfInteger mults(1, poles.Length()+degree+1-2*(degree)); - for (int i=1; i<=knots.Length(); i++){ - knots.SetValue(i,(double)(i-1)/(knots.Length()-1)); - mults.SetValue(i,1); + TColStd_Array1OfReal knots(1, poles.Length() + degree + 1 - 2 * (degree)); + TColStd_Array1OfInteger mults(1, poles.Length() + degree + 1 - 2 * (degree)); + for (int i = 1; i <= knots.Length(); i++) { + knots.SetValue(i, (double)(i - 1) / (knots.Length() - 1)); + mults.SetValue(i, 1); } - mults.SetValue(1, degree+1); - mults.SetValue(knots.Length(), degree+1); + mults.SetValue(1, degree + 1); + mults.SetValue(knots.Length(), degree + 1); - Handle(Geom2d_BSplineCurve) spline = new Geom2d_BSplineCurve(poles, knots, mults, degree, Standard_False); + Handle(Geom2d_BSplineCurve) spline + = new Geom2d_BSplineCurve(poles, knots, mults, degree, Standard_False); if (!spline.IsNull()) { this->getGeom2dBSplineCurvePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } } @@ -1090,10 +1220,10 @@ PyObject* BSplineCurve2dPy::buildFromPoles(PyObject *args) } } -PyObject* BSplineCurve2dPy::buildFromPolesMultsKnots(PyObject *args, PyObject *keywds) +PyObject* BSplineCurve2dPy::buildFromPolesMultsKnots(PyObject* args, PyObject* keywds) { - static const std::array kwlist{"poles", "mults", "knots", "periodic", "degree", "weights", - nullptr}; + static const std::array + kwlist {"poles", "mults", "knots", "periodic", "degree", "weights", nullptr}; PyObject* periodic = Py_False; PyObject* poles = Py_None; PyObject* mults = Py_None; @@ -1103,10 +1233,19 @@ PyObject* BSplineCurve2dPy::buildFromPolesMultsKnots(PyObject *args, PyObject *k int number_of_poles = 0; int number_of_knots = 0; int sum_of_mults = 0; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "O|OOO!iO", kwlist, - &poles, &mults, &knots, - &PyBool_Type, &periodic, - °ree, &weights)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "O|OOO!iO", + kwlist, + &poles, + &mults, + &knots, + &PyBool_Type, + &periodic, + °ree, + &weights + )) { return nullptr; } try { @@ -1122,9 +1261,9 @@ PyObject* BSplineCurve2dPy::buildFromPolesMultsKnots(PyObject *args, PyObject *k Standard_Integer index = 1; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d pnt = Py::toVector2d(*it); - occpoles(index++) = gp_Pnt2d(pnt.x,pnt.y); + occpoles(index++) = gp_Pnt2d(pnt.x, pnt.y); } - //Calculate the number of knots + // Calculate the number of knots if (mults != Py_None && knots != Py_None) { number_of_knots = PyObject_Length(mults); if (PyObject_Length(knots) != number_of_knots) { @@ -1137,62 +1276,75 @@ PyObject* BSplineCurve2dPy::buildFromPolesMultsKnots(PyObject *args, PyObject *k number_of_knots = PyObject_Length(mults); } else { - if (knots != Py_None) { number_of_knots = PyObject_Length(knots); } - else { //guess number of knots + if (knots != Py_None) { + number_of_knots = PyObject_Length(knots); + } + else { // guess number of knots if (Base::asBoolean(periodic)) { - if (number_of_poles < degree) {degree = number_of_poles+1;} - number_of_knots = number_of_poles+1; + if (number_of_poles < degree) { + degree = number_of_poles + 1; + } + number_of_knots = number_of_poles + 1; } else { - if (number_of_poles <= degree) {degree = number_of_poles-1;} - number_of_knots = number_of_poles-degree+1; + if (number_of_poles <= degree) { + degree = number_of_poles - 1; + } + number_of_knots = number_of_poles - degree + 1; } } } } - TColStd_Array1OfInteger occmults(1,number_of_knots); - TColStd_Array1OfReal occknots(1,number_of_knots); - TColStd_Array1OfReal occweights(1,number_of_poles); - if (mults != Py_None) { //mults are given + TColStd_Array1OfInteger occmults(1, number_of_knots); + TColStd_Array1OfReal occknots(1, number_of_knots); + TColStd_Array1OfReal occweights(1, number_of_poles); + if (mults != Py_None) { // mults are given Py::Sequence multssq(mults); Standard_Integer index = 1; - for (Py::Sequence::iterator it = multssq.begin(); it != multssq.end() && index <= occmults.Length(); ++it) { + for (Py::Sequence::iterator it = multssq.begin(); + it != multssq.end() && index <= occmults.Length(); + ++it) { Py::Long mult(*it); if (index < occmults.Length() || !Base::asBoolean(periodic)) { - sum_of_mults += (int)mult; //sum up the mults to compare them against the number of poles later + sum_of_mults += (int)mult; // sum up the mults to compare them against the + // number of poles later } occmults(index++) = mult; } } - else { //mults are 1 or degree+1 at the ends - for (int i=1; i<=occmults.Length(); i++){ - occmults.SetValue(i,1); + else { // mults are 1 or degree+1 at the ends + for (int i = 1; i <= occmults.Length(); i++) { + occmults.SetValue(i, 1); } if (!Base::asBoolean(periodic) && occmults.Length() > 0) { - occmults.SetValue(1, degree+1); - occmults.SetValue(occmults.Length(), degree+1); - sum_of_mults = occmults.Length()+2*degree; + occmults.SetValue(1, degree + 1); + occmults.SetValue(occmults.Length(), degree + 1); + sum_of_mults = occmults.Length() + 2 * degree; + } + else { + sum_of_mults = occmults.Length() - 1; } - else { sum_of_mults = occmults.Length()-1;} } - if (knots != Py_None) { //knots are given + if (knots != Py_None) { // knots are given Py::Sequence knotssq(knots); index = 1; - for (Py::Sequence::iterator it = knotssq.begin(); it != knotssq.end() && index <= occknots.Length(); ++it) { + for (Py::Sequence::iterator it = knotssq.begin(); + it != knotssq.end() && index <= occknots.Length(); + ++it) { Py::Float knot(*it); occknots(index++) = knot; } } - else { // knotes are uniformly spaced 0..1 if not given - for (int i=1; i<=occknots.Length(); i++){ - occknots.SetValue(i,(double)(i-1)/(occknots.Length()-1)); + else { // knotes are uniformly spaced 0..1 if not given + for (int i = 1; i <= occknots.Length(); i++) { + occknots.SetValue(i, (double)(i - 1) / (occknots.Length() - 1)); } } - if (weights != Py_None) { //weights are given + if (weights != Py_None) { // weights are given if (PyObject_Length(weights) != number_of_poles) { Standard_Failure::Raise("number of poles and weights mismatch"); return nullptr; - } //complain about mismatch + } // complain about mismatch Py::Sequence weightssq(weights); Standard_Integer index = 1; for (Py::Sequence::iterator it = weightssq.begin(); it != weightssq.end(); ++it) { @@ -1200,48 +1352,56 @@ PyObject* BSplineCurve2dPy::buildFromPolesMultsKnots(PyObject *args, PyObject *k occweights(index++) = weight; } } - else { // weights are 1.0 - for (int i=1; i<=occweights.Length(); i++){ - occweights.SetValue(i,1.0); + else { // weights are 1.0 + for (int i = 1; i <= occweights.Length(); i++) { + occweights.SetValue(i, 1.0); } } // check if the number of poles matches the sum of mults - if (((Base::asBoolean(periodic)) && sum_of_mults != number_of_poles) || - (!Base::asBoolean(periodic) && sum_of_mults - degree -1 != number_of_poles)) { + if (((Base::asBoolean(periodic)) && sum_of_mults != number_of_poles) + || (!Base::asBoolean(periodic) && sum_of_mults - degree - 1 != number_of_poles)) { Standard_Failure::Raise("number of poles and sum of mults mismatch"); - return(nullptr); + return (nullptr); } - Handle(Geom2d_BSplineCurve) spline = new Geom2d_BSplineCurve(occpoles, occweights, occknots, - occmults, degree, Base::asBoolean(periodic)); + Handle(Geom2d_BSplineCurve) spline = new Geom2d_BSplineCurve( + occpoles, + occweights, + occknots, + occmults, + degree, + Base::asBoolean(periodic) + ); if (!spline.IsNull()) { this->getGeom2dBSplineCurvePtr()->setHandle(spline); Py_Return; } else { Standard_Failure::Raise("failed to create spline"); - return nullptr; // goes to the catch block + return nullptr; // goes to the catch block } } catch (const Standard_Failure& e) { Standard_CString msg = e.GetMessageString(); - PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); + PyErr_SetString(PartExceptionOCCError, msg ? msg : ""); return nullptr; } } -PyObject* BSplineCurve2dPy::toBezier(PyObject *args) +PyObject* BSplineCurve2dPy::toBezier(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom2d_BSplineCurve) spline = Handle(Geom2d_BSplineCurve)::DownCast - (this->getGeom2dBSplineCurvePtr()->handle()); + Handle(Geom2d_BSplineCurve) spline = Handle(Geom2d_BSplineCurve)::DownCast( + this->getGeom2dBSplineCurvePtr()->handle() + ); Geom2dConvert_BSplineCurveToBezierCurve crt(spline); Py::List list; Standard_Integer arcs = crt.NbArcs(); - for (Standard_Integer i=1; i<=arcs; i++) { + for (Standard_Integer i = 1; i <= arcs; i++) { Handle(Geom2d_BezierCurve) bezier = crt.Arc(i); list.append(Py::asObject(new BezierCurve2dPy(new Geom2dBezierCurve(bezier)))); } @@ -1249,27 +1409,30 @@ PyObject* BSplineCurve2dPy::toBezier(PyObject *args) return Py::new_reference_to(list); } -PyObject* BSplineCurve2dPy::join(PyObject *args) +PyObject* BSplineCurve2dPy::join(PyObject* args) { PyObject* c; - if (!PyArg_ParseTuple(args, "O!", &BSplineCurve2dPy::Type, &c)) + if (!PyArg_ParseTuple(args, "O!", &BSplineCurve2dPy::Type, &c)) { return nullptr; + } Geom2dBSplineCurve* curve1 = this->getGeom2dBSplineCurvePtr(); BSplineCurve2dPy* curve2 = static_cast(c); - Handle(Geom2d_BSplineCurve) spline = Handle(Geom2d_BSplineCurve)::DownCast - (curve2->getGeom2dBSplineCurvePtr()->handle()); + Handle(Geom2d_BSplineCurve) spline = Handle(Geom2d_BSplineCurve)::DownCast( + curve2->getGeom2dBSplineCurvePtr()->handle() + ); bool ok = curve1->join(spline); return PyBool_FromLong(ok ? 1 : 0); } -PyObject* BSplineCurve2dPy::makeC1Continuous(PyObject *args) +PyObject* BSplineCurve2dPy::makeC1Continuous(PyObject* args) { double tol = Precision::Approximation(); - if (!PyArg_ParseTuple(args, "|d", &tol)) + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; + } try { Geom2dBSplineCurve* spline = this->getGeom2dBSplineCurvePtr(); @@ -1278,7 +1441,9 @@ PyObject* BSplineCurve2dPy::makeC1Continuous(PyObject *args) } catch (Standard_Failure& e) { std::string err = e.GetMessageString(); - if (err.empty()) err = e.DynamicType()->Name(); + if (err.empty()) { + err = e.DynamicType()->Name(); + } PyErr_SetString(PartExceptionOCCError, err.c_str()); return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp index 136f53f719..104208b875 100644 --- a/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -43,7 +43,7 @@ std::string BezierCurve2dPy::representation() const return ""; } -PyObject *BezierCurve2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BezierCurve2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BezierCurve2dPy and the Twin object return new BezierCurve2dPy(new Geom2dBezierCurve); @@ -55,60 +55,70 @@ int BezierCurve2dPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* BezierCurve2dPy::isRational(PyObject *args) +PyObject* BezierCurve2dPy::isRational(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Boolean val = curve->IsRational(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierCurve2dPy::isPeriodic(PyObject *args) +PyObject* BezierCurve2dPy::isPeriodic(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Boolean val = curve->IsPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierCurve2dPy::isClosed(PyObject *args) +PyObject* BezierCurve2dPy::isClosed(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Standard_Boolean val = curve->IsClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* BezierCurve2dPy::increase(PyObject * args) +PyObject* BezierCurve2dPy::increase(PyObject* args) { int degree; - if (!PyArg_ParseTuple(args, "i", °ree)) + if (!PyArg_ParseTuple(args, "i", °ree)) { return nullptr; - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + } + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->Increase(degree); Py_Return; } -PyObject* BezierCurve2dPy::insertPoleAfter(PyObject * args) +PyObject* BezierCurve2dPy::insertPoleAfter(PyObject* args) { int index; - double weight=1.0; + double weight = 1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) { return nullptr; + } Base::Vector2d vec = Py::toVector2d(p); gp_Pnt2d pnt(vec.x, vec.y); try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->InsertPoleAfter(index,pnt,weight); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->InsertPoleAfter(index, pnt, weight); Py_Return; } catch (Standard_Failure& e) { @@ -117,19 +127,21 @@ PyObject* BezierCurve2dPy::insertPoleAfter(PyObject * args) } } -PyObject* BezierCurve2dPy::insertPoleBefore(PyObject * args) +PyObject* BezierCurve2dPy::insertPoleBefore(PyObject* args) { int index; - double weight=1.0; + double weight = 1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) { return nullptr; + } Base::Vector2d vec = Py::toVector2d(p); gp_Pnt2d pnt(vec.x, vec.y); try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->InsertPoleBefore(index,pnt,weight); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->InsertPoleBefore(index, pnt, weight); Py_Return; } catch (Standard_Failure& e) { @@ -138,14 +150,16 @@ PyObject* BezierCurve2dPy::insertPoleBefore(PyObject * args) } } -PyObject* BezierCurve2dPy::removePole(PyObject * args) +PyObject* BezierCurve2dPy::removePole(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->RemovePole(index); Py_Return; } @@ -155,15 +169,17 @@ PyObject* BezierCurve2dPy::removePole(PyObject * args) } } -PyObject* BezierCurve2dPy::segment(PyObject * args) +PyObject* BezierCurve2dPy::segment(PyObject* args) { - double u1,u2; - if (!PyArg_ParseTuple(args, "dd", &u1,&u2)) + double u1, u2; + if (!PyArg_ParseTuple(args, "dd", &u1, &u2)) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->Segment(u1,u2); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->Segment(u1, u2); Py_Return; } catch (Standard_Failure& e) { @@ -172,22 +188,26 @@ PyObject* BezierCurve2dPy::segment(PyObject * args) } } -PyObject* BezierCurve2dPy::setPole(PyObject * args) +PyObject* BezierCurve2dPy::setPole(PyObject* args) { int index; - double weight=-1.0; + double weight = -1.0; PyObject* p; - if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) + if (!PyArg_ParseTuple(args, "iO!|d", &index, Base::Vector2dPy::type_object(), &p, &weight)) { return nullptr; + } Base::Vector2d vec = Py::toVector2d(p); gp_Pnt2d pnt(vec.x, vec.y); try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - if (weight < 0.0) - curve->SetPole(index,pnt); - else - curve->SetPole(index,pnt,weight); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + if (weight < 0.0) { + curve->SetPole(index, pnt); + } + else { + curve->SetPole(index, pnt, weight); + } Py_Return; } catch (Standard_Failure& e) { @@ -196,16 +216,17 @@ PyObject* BezierCurve2dPy::setPole(PyObject * args) } } -PyObject* BezierCurve2dPy::getPole(PyObject * args) +PyObject* BezierCurve2dPy::getPole(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles(), "Pole index out of range"); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Pole index out of range"); gp_Pnt2d pnt = curve->Pole(index); return Py::new_reference_to(Base::Vector2dPy::create(pnt.X(), pnt.Y())); } @@ -215,18 +236,20 @@ PyObject* BezierCurve2dPy::getPole(PyObject * args) } } -PyObject* BezierCurve2dPy::getPoles(PyObject * args) +PyObject* BezierCurve2dPy::getPoles(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - TColgp_Array1OfPnt2d p(1,curve->NbPoles()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + TColgp_Array1OfPnt2d p(1, curve->NbPoles()); curve->Poles(p); Py::List poles; - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { gp_Pnt2d pnt = p(i); poles.append(Base::Vector2dPy::create(pnt.X(), pnt.Y())); } @@ -238,18 +261,19 @@ PyObject* BezierCurve2dPy::getPoles(PyObject * args) } } -PyObject* BezierCurve2dPy::setPoles(PyObject * args) +PyObject* BezierCurve2dPy::setPoles(PyObject* args) { PyObject* plist; - if (!PyArg_ParseTuple(args, "O", &plist)) + if (!PyArg_ParseTuple(args, "O", &plist)) { return nullptr; + } try { Py::Sequence list(plist); - TColgp_Array1OfPnt2d poles(1,list.size()); + TColgp_Array1OfPnt2d poles(1, list.size()); int index = poles.Lower(); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector2d pole = Py::toVector2d(*it); - poles.SetValue(index++, gp_Pnt2d(pole.x,pole.y)); + poles.SetValue(index++, gp_Pnt2d(pole.x, pole.y)); } Handle(Geom2d_BezierCurve) bezier = new Geom2d_BezierCurve(poles); @@ -262,16 +286,18 @@ PyObject* BezierCurve2dPy::setPoles(PyObject * args) } } -PyObject* BezierCurve2dPy::setWeight(PyObject * args) +PyObject* BezierCurve2dPy::setWeight(PyObject* args) { int index; double weight; - if (!PyArg_ParseTuple(args, "id", &index,&weight)) + if (!PyArg_ParseTuple(args, "id", &index, &weight)) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - curve->SetWeight(index,weight); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + curve->SetWeight(index, weight); Py_Return; } catch (Standard_Failure& e) { @@ -280,16 +306,17 @@ PyObject* BezierCurve2dPy::setWeight(PyObject * args) } } -PyObject* BezierCurve2dPy::getWeight(PyObject * args) +PyObject* BezierCurve2dPy::getWeight(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - Standard_OutOfRange_Raise_if - (index < 1 || index > curve->NbPoles() , "Weight index out of range"); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + Standard_OutOfRange_Raise_if(index < 1 || index > curve->NbPoles(), "Weight index out of range"); double weight = curve->Weight(index); return Py_BuildValue("d", weight); } @@ -299,17 +326,19 @@ PyObject* BezierCurve2dPy::getWeight(PyObject * args) } } -PyObject* BezierCurve2dPy::getWeights(PyObject * args) +PyObject* BezierCurve2dPy::getWeights(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); - TColStd_Array1OfReal w(1,curve->NbPoles()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); + TColStd_Array1OfReal w(1, curve->NbPoles()); curve->Weights(w); Py::List weights; - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { weights.append(Py::Float(w(i))); } return Py::new_reference_to(weights); @@ -323,14 +352,16 @@ PyObject* BezierCurve2dPy::getWeights(PyObject * args) PyObject* BezierCurve2dPy::getResolution(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } try { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); double utol; - curve->Resolution(tol,utol); - return Py_BuildValue("d",utol); + curve->Resolution(tol, utol); + return Py_BuildValue("d", utol); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -339,42 +370,43 @@ PyObject* BezierCurve2dPy::getResolution(PyObject* args) const } Py::Long BezierCurve2dPy::getDegree() const { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->Degree()); } Py::Long BezierCurve2dPy::getMaxDegree() const { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->MaxDegree()); } Py::Long BezierCurve2dPy::getNbPoles() const { - Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Long(curve->NbPoles()); } Py::Object BezierCurve2dPy::getStartPoint() const { - Handle(Geom2d_BezierCurve) c = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) c = Handle(Geom2d_BezierCurve)::DownCast(getGeometry2dPtr()->handle()); gp_Pnt2d pnt = c->StartPoint(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } Py::Object BezierCurve2dPy::getEndPoint() const { - Handle(Geom2d_BezierCurve) c = Handle(Geom2d_BezierCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_BezierCurve) c = Handle(Geom2d_BezierCurve)::DownCast(getGeometry2dPtr()->handle()); gp_Pnt2d pnt = c->EndPoint(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } -PyObject *BezierCurve2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* BezierCurve2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/Circle2d.pyi b/src/Mod/Part/App/Geom2d/Circle2d.pyi index 4effcc51e7..28fb16297a 100644 --- a/src/Mod/Part/App/Geom2d/Circle2d.pyi +++ b/src/Mod/Part/App/Geom2d/Circle2d.pyi @@ -38,19 +38,16 @@ class Circle2d(Conic2d): @overload def __init__(self) -> None: ... - @overload def __init__(self, circle: "Circle2d") -> None: ... - @overload def __init__(self, circle: "Circle2d", Distance: float) -> None: ... - @overload def __init__(self, Center: Tuple[float, float], Radius: float) -> None: ... - @overload - def __init__(self, Point1: Tuple[float, float], Point2: Tuple[float, float], Point3: Tuple[float, float]) -> None: ... - + def __init__( + self, Point1: Tuple[float, float], Point2: Tuple[float, float], Point3: Tuple[float, float] + ) -> None: ... @overload def __init__(self, *args, **kwargs) -> None: """ @@ -78,4 +75,4 @@ class Circle2d(Conic2d): """ Get the circle center defined by three points """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp index b42ef9106c..efa490f282 100644 --- a/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -45,7 +45,7 @@ std::string Circle2dPy::representation() const return ""; } -PyObject *Circle2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Circle2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of Circle2dPy and the Twin object return new Circle2dPy(new Geom2dCircle()); @@ -55,13 +55,22 @@ PyObject *Circle2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // P int Circle2dPy::PyInit(PyObject* args, PyObject* kwds) { // circle and distance for offset - PyObject *pCirc; + PyObject* pCirc; double dist; - static const std::array keywords_cd {"Circle","Distance",nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", keywords_cd, &(Circle2dPy::Type), &pCirc, &dist)) { + static const std::array keywords_cd {"Circle", "Distance", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!d", + keywords_cd, + &(Circle2dPy::Type), + &pCirc, + &dist + )) { Circle2dPy* pcCircle = static_cast(pCirc); - Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast - (pcCircle->getGeom2dCirclePtr()->handle()); + Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast( + pcCircle->getGeom2dCirclePtr()->handle() + ); GCE2d_MakeCircle mc(circle->Circ2d(), dist); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); @@ -75,13 +84,19 @@ int Circle2dPy::PyInit(PyObject* args, PyObject* kwds) // center and radius PyObject *pV1, *pV2, *pV3; - static const std::array keywords_cnr {"Center","Radius",nullptr}; + static const std::array keywords_cnr {"Center", "Radius", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", keywords_cnr, - Base::Vector2dPy::type_object(), &pV1, - &dist)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!d", + keywords_cnr, + Base::Vector2dPy::type_object(), + &pV1, + &dist + )) { Base::Vector2d v1 = Py::toVector2d(pV1); - GCE2d_MakeCircle mc(gp_Pnt2d(v1.x,v1.y), dist); + GCE2d_MakeCircle mc(gp_Pnt2d(v1.x, v1.y), dist); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -92,30 +107,38 @@ int Circle2dPy::PyInit(PyObject* args, PyObject* kwds) return 0; } - static const std::array keywords_c {"Circle",nullptr}; + static const std::array keywords_c {"Circle", nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_c, &(Circle2dPy::Type), &pCirc)) { Circle2dPy* pcCircle = static_cast(pCirc); - Handle(Geom2d_Circle) circ1 = Handle(Geom2d_Circle)::DownCast - (pcCircle->getGeom2dCirclePtr()->handle()); - Handle(Geom2d_Circle) circ2 = Handle(Geom2d_Circle)::DownCast - (this->getGeom2dCirclePtr()->handle()); + Handle(Geom2d_Circle) circ1 = Handle(Geom2d_Circle)::DownCast( + pcCircle->getGeom2dCirclePtr()->handle() + ); + Handle(Geom2d_Circle) circ2 = Handle(Geom2d_Circle)::DownCast( + this->getGeom2dCirclePtr()->handle() + ); circ2->SetCirc2d(circ1->Circ2d()); return 0; } - static const std::array keywords_ppp {"Point1","Point2","Point3",nullptr}; + static const std::array keywords_ppp {"Point1", "Point2", "Point3", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ppp, - Base::Vector2dPy::type_object(), &pV1, - Base::Vector2dPy::type_object(), &pV2, - Base::Vector2dPy::type_object(), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ppp, + Base::Vector2dPy::type_object(), + &pV1, + Base::Vector2dPy::type_object(), + &pV2, + Base::Vector2dPy::type_object(), + &pV3 + )) { Base::Vector2d v1 = Py::toVector2d(pV1); Base::Vector2d v2 = Py::toVector2d(pV2); Base::Vector2d v3 = Py::toVector2d(pV3); - GCE2d_MakeCircle mc(gp_Pnt2d(v1.x,v1.y), - gp_Pnt2d(v2.x,v2.y), - gp_Pnt2d(v3.x,v3.y)); + GCE2d_MakeCircle mc(gp_Pnt2d(v1.x, v1.y), gp_Pnt2d(v2.x, v2.y), gp_Pnt2d(v3.x, v3.y)); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -127,7 +150,7 @@ int Circle2dPy::PyInit(PyObject* args, PyObject* kwds) } // default circle - static const std::array keywords_n = {nullptr}; + static const std::array keywords_n = {nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n) != 0) { Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(getGeom2dCirclePtr()->handle()); @@ -135,24 +158,35 @@ int Circle2dPy::PyInit(PyObject* args, PyObject* kwds) return 0; } - PyErr_SetString(PyExc_TypeError, "Circle constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Circle constructor accepts:\n" "-- empty parameter list\n" "-- Circle\n" "-- Circle, Distance\n" "-- Center, Radius\n" - "-- Point1, Point2, Point3"); + "-- Point1, Point2, Point3" + ); return -1; } -PyObject* Circle2dPy::getCircleCenter(PyObject *args) +PyObject* Circle2dPy::getCircleCenter(PyObject* args) { PyObject* p1; PyObject* p2; PyObject* p3; - if (!PyArg_ParseTuple(args, "O!O!O!", Base::Vector2dPy::type_object(), &p1 - , Base::Vector2dPy::type_object(), &p2 - , Base::Vector2dPy::type_object(), &p3)) + if (!PyArg_ParseTuple( + args, + "O!O!O!", + Base::Vector2dPy::type_object(), + &p1, + Base::Vector2dPy::type_object(), + &p2, + Base::Vector2dPy::type_object(), + &p3 + )) { return nullptr; + } Base::Vector2d v1 = Py::toVector2d(p1); Base::Vector2d v2 = Py::toVector2d(p2); @@ -168,18 +202,18 @@ Py::Float Circle2dPy::getRadius() const return Py::Float(circle->Radius()); } -void Circle2dPy::setRadius(Py::Float arg) +void Circle2dPy::setRadius(Py::Float arg) { Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(getGeom2dCirclePtr()->handle()); circle->SetRadius((double)arg); } -PyObject *Circle2dPy::getCustomAttributes(const char* ) const +PyObject* Circle2dPy::getCustomAttributes(const char*) const { return nullptr; } -int Circle2dPy::setCustomAttributes(const char* , PyObject *) +int Circle2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/Conic2d.pyi b/src/Mod/Part/App/Geom2d/Conic2d.pyi index 482ddc8158..2c725bd4aa 100644 --- a/src/Mod/Part/App/Geom2d/Conic2d.pyi +++ b/src/Mod/Part/App/Geom2d/Conic2d.pyi @@ -22,7 +22,7 @@ class Conic2d(Curve2d): """Location of the conic.""" Eccentricity: Final[float] = ... - """ + """ returns the eccentricity value of the conic e. e = 0 for a circle 0 < e < 1 for an ellipse (e = 0 if MajorRadius = MinorRadius) diff --git a/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp index c26902d343..6f3399c2de 100644 --- a/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -40,11 +40,10 @@ std::string Conic2dPy::representation() const return ""; } -PyObject *Conic2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Conic2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'Conic2d'."); + PyErr_SetString(PyExc_RuntimeError, "You cannot create an instance of the abstract class 'Conic2d'."); return nullptr; } @@ -60,7 +59,7 @@ Py::Object Conic2dPy::getLocation() const return Base::Vector2dPy::create(loc); } -void Conic2dPy::setLocation(Py::Object arg) +void Conic2dPy::setLocation(Py::Object arg) { Base::Vector2d loc = Py::toVector2d(arg.ptr()); getGeom2dConicPtr()->setLocation(loc); @@ -79,7 +78,7 @@ Py::Object Conic2dPy::getXAxis() const return Base::Vector2dPy::create(xdir.X(), xdir.Y()); } -void Conic2dPy::setXAxis(Py::Object arg) +void Conic2dPy::setXAxis(Py::Object arg) { Base::Vector2d dir = Py::toVector2d(arg.ptr()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(getGeom2dConicPtr()->handle()); @@ -95,7 +94,7 @@ Py::Object Conic2dPy::getYAxis() const return Base::Vector2dPy::create(ydir.X(), ydir.Y()); } -void Conic2dPy::setYAxis(Py::Object arg) +void Conic2dPy::setYAxis(Py::Object arg) { Base::Vector2d dir = Py::toVector2d(arg.ptr()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(getGeom2dConicPtr()->handle()); @@ -104,12 +103,12 @@ void Conic2dPy::setYAxis(Py::Object arg) conic->SetYAxis(yaxis); } -PyObject *Conic2dPy::getCustomAttributes(const char* ) const +PyObject* Conic2dPy::getCustomAttributes(const char*) const { return nullptr; } -int Conic2dPy::setCustomAttributes(const char* , PyObject *) +int Conic2dPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/Geom2d/Curve2d.pyi b/src/Mod/Part/App/Geom2d/Curve2d.pyi index a3b3914d7b..a43d1a8f24 100644 --- a/src/Mod/Part/App/Geom2d/Curve2d.pyi +++ b/src/Mod/Part/App/Geom2d/Curve2d.pyi @@ -49,34 +49,22 @@ class Curve2d(Geometry2d): @overload @constmethod - def discretize(self, *, Number: int) -> List[Vector]: - ... - + def discretize(self, *, Number: int) -> List[Vector]: ... @overload @constmethod - def discretize(self, *, QuasiNumber: int) -> List[Vector]: - ... - + def discretize(self, *, QuasiNumber: int) -> List[Vector]: ... @overload @constmethod - def discretize(self, *, Distance: float) -> List[Vector]: - ... - + def discretize(self, *, Distance: float) -> List[Vector]: ... @overload @constmethod - def discretize(self, *, Deflection: float) -> List[Vector]: - ... - + def discretize(self, *, Deflection: float) -> List[Vector]: ... @overload @constmethod - def discretize(self, *, QuasiDeflection: float) -> List[Vector]: - ... - + def discretize(self, *, QuasiDeflection: float) -> List[Vector]: ... @overload @constmethod - def discretize(self, *, Angular: float, Curvature: float, Minimum: int = 2) -> List[Vector]: - ... - + def discretize(self, *, Angular: float, Curvature: float, Minimum: int = 2) -> List[Vector]: ... @constmethod def discretize(self, **kwargs) -> List[Vector]: """ @@ -115,21 +103,13 @@ class Curve2d(Geometry2d): ... @overload - def length(self) -> float: - ... - + def length(self) -> float: ... @overload - def length(self, uMin: float) -> float: - ... - + def length(self, uMin: float) -> float: ... @overload - def length(self, uMin: float, uMax: float) -> float: - ... - + def length(self, uMin: float, uMax: float) -> float: ... @overload - def length(self, uMin: float, uMax: float, Tol: float) -> float: - ... - + def length(self, uMin: float, uMax: float, Tol: float) -> float: ... def length(self, *args: float) -> float: """ Computes the length of a curve @@ -138,13 +118,9 @@ class Curve2d(Geometry2d): ... @overload - def parameterAtDistance(self, abscissa: float) -> float: - ... - + def parameterAtDistance(self, abscissa: float) -> float: ... @overload - def parameterAtDistance(self, abscissa: float, startingParameter: float) -> float: - ... - + def parameterAtDistance(self, abscissa: float, startingParameter: float) -> float: ... def parameterAtDistance(self, *args: float) -> float: """ Returns the parameter on the curve of a point at @@ -201,13 +177,9 @@ class Curve2d(Geometry2d): ... @overload - def toBSpline(self) -> BSplineCurve: - ... - + def toBSpline(self) -> BSplineCurve: ... @overload - def toBSpline(self, First: float, Last: float) -> BSplineCurve: - ... - + def toBSpline(self, First: float, Last: float) -> BSplineCurve: ... def toBSpline(self, *args: float) -> BSplineCurve: """ Converts a curve of any type (only part from First to Last) @@ -215,9 +187,11 @@ class Curve2d(Geometry2d): """ ... - def approximateBSpline(self, Tolerance: float, MaxSegments: int, MaxDegree: int, Order: str = "C2") -> BSplineCurve: + def approximateBSpline( + self, Tolerance: float, MaxSegments: int, MaxDegree: int, Order: str = "C2" + ) -> BSplineCurve: """ Approximates a curve of any type to a B-Spline curve approximateBSpline(Tolerance, MaxSegments, MaxDegree, [Order='C2']) -> B-Spline curve """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp index ba3d1ddec9..4559ebc501 100644 --- a/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp @@ -22,35 +22,35 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -63,8 +63,9 @@ #include "TopoShapeFacePy.h" -namespace Part { -extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); +namespace Part +{ +extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve) & c); } using namespace Part; @@ -75,11 +76,10 @@ std::string Curve2dPy::representation() const return ""; } -PyObject *Curve2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Curve2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'Curve2d'."); + PyErr_SetString(PyExc_RuntimeError, "You cannot create an instance of the abstract class 'Curve2d'."); return nullptr; } @@ -89,7 +89,7 @@ int Curve2dPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* Curve2dPy::reverse(PyObject * args) +PyObject* Curve2dPy::reverse(PyObject* args) { if (PyArg_ParseTuple(args, "")) { try { @@ -106,60 +106,67 @@ PyObject* Curve2dPy::reverse(PyObject * args) return nullptr; } -namespace Part { -extern Py::Object shape2pyshape(const TopoDS_Shape &shape); +namespace Part +{ +extern Py::Object shape2pyshape(const TopoDS_Shape& shape); void create3dCurve(const TopoDS_Edge& edge) { TopoDS_Edge edge3d; BRepAdaptor_Curve adapt_curve(edge); - switch(adapt_curve.GetType()) { - case GeomAbs_Line: - { - BRepBuilderAPI_MakeEdge mkBuilder3d(adapt_curve.Line(), - adapt_curve.FirstParameter(), - adapt_curve.LastParameter()); - edge3d = mkBuilder3d.Edge(); + switch (adapt_curve.GetType()) { + case GeomAbs_Line: { + BRepBuilderAPI_MakeEdge mkBuilder3d( + adapt_curve.Line(), + adapt_curve.FirstParameter(), + adapt_curve.LastParameter() + ); + edge3d = mkBuilder3d.Edge(); } break; - case GeomAbs_Circle: - { - BRepBuilderAPI_MakeEdge mkBuilder3d(adapt_curve.Circle(), - adapt_curve.FirstParameter(), - adapt_curve.LastParameter()); - edge3d = mkBuilder3d.Edge(); + case GeomAbs_Circle: { + BRepBuilderAPI_MakeEdge mkBuilder3d( + adapt_curve.Circle(), + adapt_curve.FirstParameter(), + adapt_curve.LastParameter() + ); + edge3d = mkBuilder3d.Edge(); } break; - case GeomAbs_Ellipse: - { - BRepBuilderAPI_MakeEdge mkBuilder3d(adapt_curve.Ellipse(), - adapt_curve.FirstParameter(), - adapt_curve.LastParameter()); - edge3d = mkBuilder3d.Edge(); + case GeomAbs_Ellipse: { + BRepBuilderAPI_MakeEdge mkBuilder3d( + adapt_curve.Ellipse(), + adapt_curve.FirstParameter(), + adapt_curve.LastParameter() + ); + edge3d = mkBuilder3d.Edge(); } break; - case GeomAbs_Hyperbola: - { - BRepBuilderAPI_MakeEdge mkBuilder3d(adapt_curve.Hyperbola(), - adapt_curve.FirstParameter(), - adapt_curve.LastParameter()); - edge3d = mkBuilder3d.Edge(); + case GeomAbs_Hyperbola: { + BRepBuilderAPI_MakeEdge mkBuilder3d( + adapt_curve.Hyperbola(), + adapt_curve.FirstParameter(), + adapt_curve.LastParameter() + ); + edge3d = mkBuilder3d.Edge(); } break; - case GeomAbs_Parabola: - { - BRepBuilderAPI_MakeEdge mkBuilder3d(adapt_curve.Parabola(), - adapt_curve.FirstParameter(), - adapt_curve.LastParameter()); - edge3d = mkBuilder3d.Edge(); + case GeomAbs_Parabola: { + BRepBuilderAPI_MakeEdge mkBuilder3d( + adapt_curve.Parabola(), + adapt_curve.FirstParameter(), + adapt_curve.LastParameter() + ); + edge3d = mkBuilder3d.Edge(); } break; - case GeomAbs_BezierCurve: - { - BRepBuilderAPI_MakeEdge mkBuilder3d(adapt_curve.Bezier(), - adapt_curve.FirstParameter(), - adapt_curve.LastParameter()); - edge3d = mkBuilder3d.Edge(); + case GeomAbs_BezierCurve: { + BRepBuilderAPI_MakeEdge mkBuilder3d( + adapt_curve.Bezier(), + adapt_curve.FirstParameter(), + adapt_curve.LastParameter() + ); + edge3d = mkBuilder3d.Edge(); } break; - default: - edge3d = edge; - BRepLib::BuildCurves3d(edge3d, Precision::Confusion(), GeomAbs_Shape::GeomAbs_C1, 14, 10000); - break; + default: + edge3d = edge; + BRepLib::BuildCurves3d(edge3d, Precision::Confusion(), GeomAbs_Shape::GeomAbs_C1, 14, 10000); + break; } Standard_Real aFirst, aLast; Handle(Geom_Curve) curve = BRep_Tool::Curve(edge3d, aFirst, aLast); @@ -168,16 +175,16 @@ void create3dCurve(const TopoDS_Edge& edge) builder.Range(edge, aFirst, aLast, true); return; } -} +} // namespace Part -PyObject* Curve2dPy::toShape(PyObject *args) const +PyObject* Curve2dPy::toShape(PyObject* args) const { if (PyArg_ParseTuple(args, "")) { try { Handle(Geom2d_Curve) curv = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); BRepBuilderAPI_MakeEdge2d mkBuilder(curv); - TopoDS_Shape edge = mkBuilder.Shape(); + TopoDS_Shape edge = mkBuilder.Shape(); return Py::new_reference_to(shape2pyshape(edge)); } catch (Standard_Failure& e) { @@ -193,7 +200,7 @@ PyObject* Curve2dPy::toShape(PyObject *args) const Handle(Geom2d_Curve) curv = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); BRepBuilderAPI_MakeEdge2d mkBuilder(curv, u1, u2); - TopoDS_Shape edge = mkBuilder.Shape(); + TopoDS_Shape edge = mkBuilder.Shape(); return Py::new_reference_to(shape2pyshape(edge)); } catch (Standard_Failure& e) { @@ -207,11 +214,12 @@ PyObject* Curve2dPy::toShape(PyObject *args) const if (PyArg_ParseTuple(args, "O!", &(Part::GeometrySurfacePy::Type), &p)) { try { Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( - static_cast(p)->getGeomSurfacePtr()->handle()); + static_cast(p)->getGeomSurfacePtr()->handle() + ); Handle(Geom2d_Curve) curv = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); BRepBuilderAPI_MakeEdge mkBuilder(curv, surf); - TopoDS_Edge edge = mkBuilder.Edge(); + TopoDS_Edge edge = mkBuilder.Edge(); create3dCurve(edge); return Py::new_reference_to(shape2pyshape(edge)); @@ -226,11 +234,12 @@ PyObject* Curve2dPy::toShape(PyObject *args) const if (PyArg_ParseTuple(args, "O!dd", &(Part::GeometrySurfacePy::Type), &p, &u1, &u2)) { try { Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( - static_cast(p)->getGeomSurfacePtr()->handle()); + static_cast(p)->getGeomSurfacePtr()->handle() + ); Handle(Geom2d_Curve) curv = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); BRepBuilderAPI_MakeEdge mkBuilder(curv, surf, u1, u2); - TopoDS_Edge edge = mkBuilder.Edge(); + TopoDS_Edge edge = mkBuilder.Edge(); create3dCurve(edge); return Py::new_reference_to(shape2pyshape(edge)); @@ -245,12 +254,14 @@ PyObject* Curve2dPy::toShape(PyObject *args) const PyErr_Clear(); if (PyArg_ParseTuple(args, "O!", &(Part::TopoShapeFacePy::Type), &p)) { try { - const TopoDS_Face& face = TopoDS::Face(static_cast(p)->getTopoShapePtr()->getShape()); + const TopoDS_Face& face = TopoDS::Face( + static_cast(p)->getTopoShapePtr()->getShape() + ); Handle(Geom2d_Curve) curv = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); BRepAdaptor_Surface adapt(face); BRepBuilderAPI_MakeEdge mkBuilder(curv, adapt.Surface().Surface()); - TopoDS_Edge edge = mkBuilder.Edge(); + TopoDS_Edge edge = mkBuilder.Edge(); create3dCurve(edge); return Py::new_reference_to(shape2pyshape(edge)); @@ -264,12 +275,14 @@ PyObject* Curve2dPy::toShape(PyObject *args) const PyErr_Clear(); if (PyArg_ParseTuple(args, "O!dd", &(Part::TopoShapeFacePy::Type), &p, &u1, &u2)) { try { - const TopoDS_Face& face = TopoDS::Face(static_cast(p)->getTopoShapePtr()->getShape()); + const TopoDS_Face& face = TopoDS::Face( + static_cast(p)->getTopoShapePtr()->getShape() + ); Handle(Geom2d_Curve) curv = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); BRepAdaptor_Surface adapt(face); BRepBuilderAPI_MakeEdge mkBuilder(curv, adapt.Surface().Surface(), u1, u2); - TopoDS_Edge edge = mkBuilder.Edge(); + TopoDS_Edge edge = mkBuilder.Edge(); create3dCurve(edge); return Py::new_reference_to(shape2pyshape(edge)); @@ -284,7 +297,7 @@ PyObject* Curve2dPy::toShape(PyObject *args) const return nullptr; } -PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const +PyObject* Curve2dPy::discretize(PyObject* args, PyObject* kwds) const { try { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); @@ -299,19 +312,27 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const double last = adapt.LastParameter(); // use Number kwds - static const std::array kwds_numPoints {"Number", "First", "Last", nullptr}; + static const std::array kwds_numPoints {"Number", "First", "Last", nullptr}; PyErr_Clear(); int numPoints = -1; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_numPoints, &numPoints, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_numPoints, + &numPoints, + &first, + &last + )) { GCPnts_UniformAbscissa discretizer; - discretizer.Initialize (adapt, numPoints, first, last); + discretizer.Initialize(adapt, numPoints, first, last); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); + int nbPoints = discretizer.NbPoints(); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt2d p = adapt.Value (discretizer.Parameter (i)); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt2d p = adapt.Value(discretizer.Parameter(i)); points.append(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -324,19 +345,19 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const } // use Distance kwds - static const std::array kwds_Distance{"Distance", "First", "Last", nullptr}; + static const std::array kwds_Distance {"Distance", "First", "Last", nullptr}; PyErr_Clear(); double distance = -1; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Distance, &distance, &first, &last)) { GCPnts_UniformAbscissa discretizer; - discretizer.Initialize (adapt, distance, first, last); + discretizer.Initialize(adapt, distance, first, last); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); + int nbPoints = discretizer.NbPoints(); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt2d p = adapt.Value (discretizer.Parameter (i)); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt2d p = adapt.Value(discretizer.Parameter(i)); points.append(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -349,17 +370,25 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const } // use Deflection kwds - static const std::array kwds_Deflection{"Deflection", "First", "Last", nullptr}; + static const std::array kwds_Deflection {"Deflection", "First", "Last", nullptr}; PyErr_Clear(); double deflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Deflection, &deflection, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Deflection, + &deflection, + &first, + &last + )) { GCPnts_UniformDeflection discretizer(adapt, deflection, first, last); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); + int nbPoints = discretizer.NbPoints(); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); points.append(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -372,21 +401,30 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const } // use TangentialDeflection kwds - static const std::array kwds_TangentialDeflection{"Angular", "Curvature", "First", "Last", - "Minimum", nullptr}; + static const std::array + kwds_TangentialDeflection {"Angular", "Curvature", "First", "Last", "Minimum", nullptr}; PyErr_Clear(); double angular; double curvature; int minimumPoints = 2; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "dd|ddi", kwds_TangentialDeflection, &angular, &curvature, - &first, &last, &minimumPoints)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "dd|ddi", + kwds_TangentialDeflection, + &angular, + &curvature, + &first, + &last, + &minimumPoints + )) { GCPnts_TangentialDeflection discretizer(adapt, first, last, angular, curvature, minimumPoints); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); + int nbPoints = discretizer.NbPoints(); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); points.append(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -399,18 +437,30 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiNumber kwds - static const std::array kwds_QuasiNumPoints{"QuasiNumber", "First", "Last", nullptr}; + static const std::array kwds_QuasiNumPoints { + "QuasiNumber", + "First", + "Last", + nullptr + }; PyErr_Clear(); int quasiNumPoints; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_QuasiNumPoints, &quasiNumPoints, &first, - &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_QuasiNumPoints, + &quasiNumPoints, + &first, + &last + )) { GCPnts_QuasiUniformAbscissa discretizer(adapt, quasiNumPoints, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); + int nbPoints = discretizer.NbPoints(); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt2d p = adapt.Value (discretizer.Parameter (i)); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt2d p = adapt.Value(discretizer.Parameter(i)); points.append(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -423,17 +473,29 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiDeflection kwds - static const std::array kwds_QuasiDeflection {"QuasiDeflection","First","Last",nullptr}; + static const std::array kwds_QuasiDeflection { + "QuasiDeflection", + "First", + "Last", + nullptr + }; PyErr_Clear(); double quasiDeflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_QuasiDeflection, &quasiDeflection, &first, - &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_QuasiDeflection, + &quasiDeflection, + &first, + &last + )) { GCPnts_QuasiUniformDeflection discretizer(adapt, quasiDeflection, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); points.append(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -450,23 +512,24 @@ PyObject* Curve2dPy::discretize(PyObject *args, PyObject *kwds) const return nullptr; } - PyErr_SetString(PartExceptionOCCError,"Wrong arguments"); + PyErr_SetString(PartExceptionOCCError, "Wrong arguments"); return nullptr; } -PyObject* Curve2dPy::length(PyObject *args) +PyObject* Curve2dPy::length(PyObject* args) { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u=c->FirstParameter(); - double v=c->LastParameter(); - double t=Precision::Confusion(); - if (!PyArg_ParseTuple(args, "|ddd", &u,&v,&t)) + double u = c->FirstParameter(); + double v = c->LastParameter(); + double t = Precision::Confusion(); + if (!PyArg_ParseTuple(args, "|ddd", &u, &v, &t)) { return nullptr; + } Geom2dAdaptor_Curve adapt(c); - double len = GCPnts_AbscissaPoint::Length(adapt,u,v,t); + double len = GCPnts_AbscissaPoint::Length(adapt, u, v, t); return PyFloat_FromDouble(len); } } @@ -479,7 +542,7 @@ PyObject* Curve2dPy::length(PyObject *args) return nullptr; } -PyObject* Curve2dPy::parameterAtDistance(PyObject *args) +PyObject* Curve2dPy::parameterAtDistance(PyObject* args) { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); @@ -487,10 +550,11 @@ PyObject* Curve2dPy::parameterAtDistance(PyObject *args) if (!c.IsNull()) { double abscissa; double u = 0; - if (!PyArg_ParseTuple(args, "d|d", &abscissa,&u)) + if (!PyArg_ParseTuple(args, "d|d", &abscissa, &u)) { return nullptr; + } Geom2dAdaptor_Curve adapt(c); - GCPnts_AbscissaPoint abscissaPoint(adapt,abscissa,u); + GCPnts_AbscissaPoint abscissaPoint(adapt, abscissa, u); double parm = abscissaPoint.Parameter(); return PyFloat_FromDouble(parm); } @@ -504,15 +568,16 @@ PyObject* Curve2dPy::parameterAtDistance(PyObject *args) return nullptr; } -PyObject* Curve2dPy::value(PyObject *args) +PyObject* Curve2dPy::value(PyObject* args) { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Pnt2d p = c->Value(u); return Py::new_reference_to(Base::Vector2dPy::create(p.X(), p.Y())); } @@ -526,17 +591,18 @@ PyObject* Curve2dPy::value(PyObject *args) return nullptr; } -PyObject* Curve2dPy::tangent(PyObject *args) +PyObject* Curve2dPy::tangent(PyObject* args) { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Dir2d dir; - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); if (prop.IsTangentDefined()) { prop.Tangent(dir); } @@ -553,17 +619,18 @@ PyObject* Curve2dPy::tangent(PyObject *args) return nullptr; } -PyObject* Curve2dPy::normal(PyObject *args) const +PyObject* Curve2dPy::normal(PyObject* args) const { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Dir2d dir; - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); prop.Normal(dir); return Py::new_reference_to(Base::Vector2dPy::create(dir.X(), dir.Y())); @@ -578,16 +645,17 @@ PyObject* Curve2dPy::normal(PyObject *args) const return nullptr; } -PyObject* Curve2dPy::curvature(PyObject *args) const +PyObject* Curve2dPy::curvature(PyObject* args) const { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); + } + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); double C = prop.Curvature(); return Py::new_reference_to(Py::Float(C)); } @@ -601,17 +669,18 @@ PyObject* Curve2dPy::curvature(PyObject *args) const return nullptr; } -PyObject* Curve2dPy::centerOfCurvature(PyObject *args) const +PyObject* Curve2dPy::centerOfCurvature(PyObject* args) const { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); - gp_Pnt2d pnt ; + } + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); + gp_Pnt2d pnt; prop.CentreOfCurvature(pnt); return Py::new_reference_to(Base::Vector2dPy::create(pnt.X(), pnt.Y())); @@ -626,17 +695,18 @@ PyObject* Curve2dPy::centerOfCurvature(PyObject *args) const return nullptr; } -PyObject* Curve2dPy::parameter(PyObject *args) +PyObject* Curve2dPy::parameter(PyObject* args) { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { - PyObject *p; - if (!PyArg_ParseTuple(args, "O!", Base::Vector2dPy::type_object(), &p)) + PyObject* p; + if (!PyArg_ParseTuple(args, "O!", Base::Vector2dPy::type_object(), &p)) { return nullptr; + } Base::Vector2d v = Py::toVector2d(p); - gp_Pnt2d pnt(v.x,v.y); + gp_Pnt2d pnt(v.x, v.y); Geom2dAPI_ProjectPointOnCurve ppc(pnt, c); double val = ppc.LowerDistanceParameter(); return Py::new_reference_to(Py::Float(val)); @@ -652,21 +722,23 @@ PyObject* Curve2dPy::parameter(PyObject *args) return nullptr; } -PyObject* Curve2dPy::toBSpline(PyObject * args) +PyObject* Curve2dPy::toBSpline(PyObject* args) { Handle(Geom2d_Geometry) g = getGeometry2dPtr()->handle(); Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u,v; - u=c->FirstParameter(); - v=c->LastParameter(); - if (!PyArg_ParseTuple(args, "|dd", &u,&v)) + double u, v; + u = c->FirstParameter(); + v = c->LastParameter(); + if (!PyArg_ParseTuple(args, "|dd", &u, &v)) { return nullptr; + } ShapeConstruct_Curve scc; Handle(Geom2d_BSplineCurve) spline = scc.ConvertToBSpline(c, u, v, Precision::Confusion()); - if (spline.IsNull()) + if (spline.IsNull()) { Standard_NullValue::Raise("Conversion to B-spline failed"); + } return new BSplineCurve2dPy(new Geom2dBSplineCurve(spline)); } } @@ -679,32 +751,41 @@ PyObject* Curve2dPy::toBSpline(PyObject * args) return nullptr; } -PyObject* Curve2dPy::approximateBSpline(PyObject *args) +PyObject* Curve2dPy::approximateBSpline(PyObject* args) { double tolerance; int maxSegment, maxDegree; const char* order = "C2"; - if (!PyArg_ParseTuple(args, "dii|s", &tolerance, &maxSegment, &maxDegree, &order)) + if (!PyArg_ParseTuple(args, "dii|s", &tolerance, &maxSegment, &maxDegree, &order)) { return nullptr; + } GeomAbs_Shape absShape; std::string str = order; - if (str == "C0") + if (str == "C0") { absShape = GeomAbs_C0; - else if (str == "G1") + } + else if (str == "G1") { absShape = GeomAbs_G1; - else if (str == "C1") + } + else if (str == "C1") { absShape = GeomAbs_C1; - else if (str == "G2") + } + else if (str == "G2") { absShape = GeomAbs_G2; - else if (str == "C2") + } + else if (str == "C2") { absShape = GeomAbs_C2; - else if (str == "C3") + } + else if (str == "C3") { absShape = GeomAbs_C3; - else if (str == "CN") + } + else if (str == "CN") { absShape = GeomAbs_CN; - else + } + else { absShape = GeomAbs_C2; + } try { Handle(Geom2d_Curve) self = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); @@ -731,63 +812,62 @@ PyObject* Curve2dPy::approximateBSpline(PyObject *args) Py::String Curve2dPy::getContinuity() const { - GeomAbs_Shape c = Handle(Geom2d_Curve)::DownCast - (getGeometry2dPtr()->handle())->Continuity(); + GeomAbs_Shape c = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle())->Continuity(); std::string str; switch (c) { - case GeomAbs_C0: - str = "C0"; - break; - case GeomAbs_G1: - str = "G1"; - break; - case GeomAbs_C1: - str = "C1"; - break; - case GeomAbs_G2: - str = "G2"; - break; - case GeomAbs_C2: - str = "C2"; - break; - case GeomAbs_C3: - str = "C3"; - break; - case GeomAbs_CN: - str = "CN"; - break; - default: - str = "Unknown"; - break; + case GeomAbs_C0: + str = "C0"; + break; + case GeomAbs_G1: + str = "G1"; + break; + case GeomAbs_C1: + str = "C1"; + break; + case GeomAbs_G2: + str = "G2"; + break; + case GeomAbs_C2: + str = "C2"; + break; + case GeomAbs_C3: + str = "C3"; + break; + case GeomAbs_CN: + str = "CN"; + break; + default: + str = "Unknown"; + break; } return Py::String(str); } Py::Boolean Curve2dPy::getClosed() const { - return Py::Boolean(Handle(Geom2d_Curve)::DownCast - (getGeometry2dPtr()->handle())->IsClosed() ? true : false); + return Py::Boolean( + Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle())->IsClosed() ? true : false + ); } Py::Boolean Curve2dPy::getPeriodic() const { - return Py::Boolean(Handle(Geom2d_Curve)::DownCast - (getGeometry2dPtr()->handle())->IsPeriodic() ? true : false); + return Py::Boolean( + Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle())->IsPeriodic() ? true : false + ); } Py::Float Curve2dPy::getFirstParameter() const { - return Py::Float(Handle(Geom2d_Curve)::DownCast - (getGeometry2dPtr()->handle())->FirstParameter()); + return Py::Float(Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle())->FirstParameter()); } Py::Float Curve2dPy::getLastParameter() const { - return Py::Float(Handle(Geom2d_Curve)::DownCast - (getGeometry2dPtr()->handle())->LastParameter()); + return Py::Float(Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle())->LastParameter()); } -PyObject *Curve2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Curve2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -797,17 +877,20 @@ int Curve2dPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -PyObject* Curve2dPy::intersectCC(PyObject *args) const +PyObject* Curve2dPy::intersectCC(PyObject* args) const { Handle(Geom2d_Curve) curve1 = Handle(Geom2d_Curve)::DownCast(getGeometry2dPtr()->handle()); try { if (!curve1.IsNull()) { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d", &(Part::Curve2dPy::Type), &p, &prec)) + if (!PyArg_ParseTuple(args, "O!|d", &(Part::Curve2dPy::Type), &p, &prec)) { return nullptr; + } - Handle(Geom2d_Curve) curve2 = Handle(Geom2d_Curve)::DownCast(static_cast(p)->getGeometry2dPtr()->handle()); + Handle(Geom2d_Curve) curve2 = Handle(Geom2d_Curve)::DownCast( + static_cast(p)->getGeometry2dPtr()->handle() + ); Py::List points; Geom2dAPI_InterCurveCurve intersector(curve1, curve2, prec); if ((intersector.NbPoints() == 0) && (intersector.NbSegments() == 0)) { @@ -823,14 +906,18 @@ PyObject* Curve2dPy::intersectCC(PyObject *args) const } if (intersector.NbSegments() > 0) { // Tangential intersections - Geom2dAPI_ExtremaCurveCurve intersector2(curve1, curve2, - curve1->FirstParameter(), - curve1->LastParameter(), - curve2->FirstParameter(), - curve2->LastParameter()); + Geom2dAPI_ExtremaCurveCurve intersector2( + curve1, + curve2, + curve1->FirstParameter(), + curve1->LastParameter(), + curve2->FirstParameter(), + curve2->LastParameter() + ); for (int i = 1; i <= intersector2.NbExtrema(); i++) { - if (intersector2.Distance(i) > prec) + if (intersector2.Distance(i) > prec) { continue; + } gp_Pnt2d p1, p2; intersector2.Points(i, p1, p2); points.append(Base::Vector2dPy::create(p1.X(), p1.Y())); diff --git a/src/Mod/Part/App/Geom2d/Ellipse2d.pyi b/src/Mod/Part/App/Geom2d/Ellipse2d.pyi index 8ea0792086..9170c5a3bd 100644 --- a/src/Mod/Part/App/Geom2d/Ellipse2d.pyi +++ b/src/Mod/Part/App/Geom2d/Ellipse2d.pyi @@ -52,16 +52,11 @@ class Ellipse2d(Conic2d): @overload def __init__(self) -> None: ... - @overload def __init__(self, Ellipse: "Ellipse2d") -> None: ... - @overload def __init__(self, S1: object, S2: object, Center: object) -> None: ... - @overload def __init__(self, Center: object, MajorRadius: float, MinorRadius: float) -> None: ... - @overload - def __init__(self, *args, **kwargs) -> None: - ... + def __init__(self, *args, **kwargs) -> None: ... diff --git a/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp index aa742ce3cf..61d44dcaf3 100644 --- a/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -45,7 +45,7 @@ std::string Ellipse2dPy::representation() const return ""; } -PyObject *Ellipse2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Ellipse2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of Ellipse2dPy and the Twin object return new Ellipse2dPy(new Geom2dEllipse); @@ -54,75 +54,98 @@ PyObject *Ellipse2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // // constructor method int Ellipse2dPy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { - Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); + Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast( + getGeom2dEllipsePtr()->handle() + ); ellipse->SetMajorRadius(2.0); ellipse->SetMinorRadius(1.0); return 0; } - static const std::array keywords_e {"Ellipse",nullptr}; + static const std::array keywords_e {"Ellipse", nullptr}; PyErr_Clear(); - PyObject *pElips; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!",keywords_e, &(Ellipse2dPy::Type), &pElips)) { + PyObject* pElips; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_e, &(Ellipse2dPy::Type), &pElips)) { Ellipse2dPy* pEllipse = static_cast(pElips); - Handle(Geom2d_Ellipse) Elips1 = Handle(Geom2d_Ellipse)::DownCast - (pEllipse->getGeom2dEllipsePtr()->handle()); - Handle(Geom2d_Ellipse) Elips2 = Handle(Geom2d_Ellipse)::DownCast - (this->getGeom2dEllipsePtr()->handle()); + Handle(Geom2d_Ellipse) Elips1 = Handle(Geom2d_Ellipse)::DownCast( + pEllipse->getGeom2dEllipsePtr()->handle() + ); + Handle(Geom2d_Ellipse) Elips2 = Handle(Geom2d_Ellipse)::DownCast( + this->getGeom2dEllipsePtr()->handle() + ); Elips2->SetElips2d(Elips1->Elips2d()); return 0; } - static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; + static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ssc, - Base::Vector2dPy::type_object(), &pV1, - Base::Vector2dPy::type_object(), &pV2, - Base::Vector2dPy::type_object(), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ssc, + Base::Vector2dPy::type_object(), + &pV1, + Base::Vector2dPy::type_object(), + &pV2, + Base::Vector2dPy::type_object(), + &pV3 + )) { Base::Vector2d v1 = Py::toVector2d(pV1); Base::Vector2d v2 = Py::toVector2d(pV2); Base::Vector2d v3 = Py::toVector2d(pV3); - GCE2d_MakeEllipse me(gp_Pnt2d(v1.x,v1.y), - gp_Pnt2d(v2.x,v2.y), - gp_Pnt2d(v3.x,v3.y)); + GCE2d_MakeEllipse me(gp_Pnt2d(v1.x, v1.y), gp_Pnt2d(v2.x, v2.y), gp_Pnt2d(v3.x, v3.y)); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; } - Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); + Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast( + getGeom2dEllipsePtr()->handle() + ); ellipse->SetElips2d(me.Value()->Elips2d()); return 0; } - static const std::array keywords_cmm {"Center","MajorRadius","MinorRadius",nullptr}; + static const std::array keywords_cmm {"Center", "MajorRadius", "MinorRadius", nullptr}; PyErr_Clear(); - PyObject *pV; + PyObject* pV; double major, minor; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!dd", keywords_cmm, - Base::Vector2dPy::type_object(), &pV, - &major, &minor)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!dd", + keywords_cmm, + Base::Vector2dPy::type_object(), + &pV, + &major, + &minor + )) { Base::Vector2d c = Py::toVector2d(pV); - GCE2d_MakeEllipse me(gp_Ax2d(gp_Pnt2d(c.x,c.y), gp_Dir2d(0.0,1.0)), - major, minor); + GCE2d_MakeEllipse me(gp_Ax2d(gp_Pnt2d(c.x, c.y), gp_Dir2d(0.0, 1.0)), major, minor); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; } - Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); + Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast( + getGeom2dEllipsePtr()->handle() + ); ellipse->SetElips2d(me.Value()->Elips2d()); return 0; } - PyErr_SetString(PyExc_TypeError, "Ellipse constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Ellipse constructor accepts:\n" "-- empty parameter list\n" "-- Ellipse\n" "-- Point, double, double\n" - "-- Point, Point, Point"); + "-- Point, Point, Point" + ); return -1; } @@ -170,7 +193,7 @@ Py::Object Ellipse2dPy::getFocus2() const return Base::Vector2dPy::create(loc.X(), loc.Y()); } -PyObject *Ellipse2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Ellipse2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp index 47587ed244..0dd23b1a98 100644 --- a/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp @@ -22,11 +22,11 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -44,11 +44,13 @@ std::string Geometry2dPy::representation() const return ""; } -PyObject *Geometry2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Geometry2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'Geometry'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'Geometry'." + ); return nullptr; } @@ -58,10 +60,10 @@ int Geometry2dPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* Geometry2dPy::mirror(PyObject *args) +PyObject* Geometry2dPy::mirror(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", Base::Vector2dPy::type_object(),&o)) { + if (PyArg_ParseTuple(args, "O!", Base::Vector2dPy::type_object(), &o)) { Base::Vector2d vec = Py::toVector2d(o); gp_Pnt2d pnt(vec.x, vec.y); getGeometry2dPtr()->handle()->Mirror(pnt); @@ -70,20 +72,29 @@ PyObject* Geometry2dPy::mirror(PyObject *args) PyErr_Clear(); PyObject* axis; - if (PyArg_ParseTuple(args, "O!O!", Base::Vector2dPy::type_object(),&o, - Base::Vector2dPy::type_object(),&axis)) { + if (PyArg_ParseTuple( + args, + "O!O!", + Base::Vector2dPy::type_object(), + &o, + Base::Vector2dPy::type_object(), + &axis + )) { Base::Vector2d pnt = Py::toVector2d(o); Base::Vector2d dir = Py::toVector2d(axis); - gp_Ax2d ax1(gp_Pnt2d(pnt.x,pnt.y), gp_Dir2d(dir.x,dir.y)); + gp_Ax2d ax1(gp_Pnt2d(pnt.x, pnt.y), gp_Dir2d(dir.x, dir.y)); getGeometry2dPtr()->handle()->Mirror(ax1); Py_Return; } - PyErr_SetString(PartExceptionOCCError, "either a point (vector) or axis (vector, vector) must be given"); + PyErr_SetString( + PartExceptionOCCError, + "either a point (vector) or axis (vector, vector) must be given" + ); return nullptr; } -PyObject* Geometry2dPy::rotate(PyObject *args) +PyObject* Geometry2dPy::rotate(PyObject* args) { PyObject* o; double angle; @@ -99,7 +110,7 @@ PyObject* Geometry2dPy::rotate(PyObject *args) return nullptr; } -PyObject* Geometry2dPy::scale(PyObject *args) +PyObject* Geometry2dPy::scale(PyObject* args) { PyObject* o; double scale; @@ -115,11 +126,12 @@ PyObject* Geometry2dPy::scale(PyObject *args) return nullptr; } -PyObject* Geometry2dPy::transform(PyObject *args) +PyObject* Geometry2dPy::transform(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O", &o)) + if (!PyArg_ParseTuple(args, "O", &o)) { return nullptr; + } Py::Sequence list(o); double a11 = static_cast(Py::Float(list.getItem(0))); double a12 = static_cast(Py::Float(list.getItem(1))); @@ -136,11 +148,11 @@ PyObject* Geometry2dPy::transform(PyObject *args) Py_Return; } -PyObject* Geometry2dPy::translate(PyObject *args) +PyObject* Geometry2dPy::translate(PyObject* args) { PyObject* o; Base::Vector2d vec; - if (PyArg_ParseTuple(args, "O!", Base::Vector2dPy::type_object(),&o)) { + if (PyArg_ParseTuple(args, "O!", Base::Vector2dPy::type_object(), &o)) { vec = Py::toVector2d(o); gp_Vec2d trl(vec.x, vec.y); getGeometry2dPtr()->handle()->Translate(trl); @@ -151,17 +163,19 @@ PyObject* Geometry2dPy::translate(PyObject *args) return nullptr; } -PyObject* Geometry2dPy::copy(PyObject *args) const +PyObject* Geometry2dPy::copy(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Part::Geometry2d* geom = this->getGeometry2dPtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = nullptr; // let the type object decide - if (type->tp_new) + if (type->tp_new) { cpy = type->tp_new(type, const_cast(this), nullptr); + } if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create copy of geometry"); return nullptr; @@ -178,7 +192,7 @@ PyObject* Geometry2dPy::copy(PyObject *args) const return cpy; } -PyObject *Geometry2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Geometry2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/Hyperbola2d.pyi b/src/Mod/Part/App/Geom2d/Hyperbola2d.pyi index a27fa36323..a6200783d4 100644 --- a/src/Mod/Part/App/Geom2d/Hyperbola2d.pyi +++ b/src/Mod/Part/App/Geom2d/Hyperbola2d.pyi @@ -8,7 +8,7 @@ from typing import Final, overload PythonName="Part.Geom2d.Hyperbola2d", FatherInclude="Mod/Part/App/Geom2d/Conic2dPy.h", Include="Mod/Part/App/Geometry2d.h", - Constructor=True + Constructor=True, ) class Hyperbola2d(Conic2d): """ diff --git a/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp index 67687ae7a6..7fb8fd3acd 100644 --- a/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -45,7 +45,7 @@ std::string Hyperbola2dPy::representation() const return ""; } -PyObject *Hyperbola2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Hyperbola2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of Hyperbola2dPy and the Twin object return new Hyperbola2dPy(new Geom2dHyperbola); @@ -54,123 +54,160 @@ PyObject *Hyperbola2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) / // constructor method int Hyperbola2dPy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); hyperbola->SetMajorRadius(2.0); hyperbola->SetMinorRadius(1.0); return 0; } - static const std::array keywords_e = {"Hyperbola", nullptr}; + static const std::array keywords_e = {"Hyperbola", nullptr}; PyErr_Clear(); - PyObject *pHypr; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!",keywords_e, &(Hyperbola2dPy::Type), &pHypr)) { + PyObject* pHypr; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_e, &(Hyperbola2dPy::Type), &pHypr)) { Hyperbola2dPy* pHyperbola = static_cast(pHypr); - Handle(Geom2d_Hyperbola) Hypr1 = Handle(Geom2d_Hyperbola)::DownCast - (pHyperbola->getGeom2dHyperbolaPtr()->handle()); - Handle(Geom2d_Hyperbola) Hypr2 = Handle(Geom2d_Hyperbola)::DownCast - (this->getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) Hypr1 = Handle(Geom2d_Hyperbola)::DownCast( + pHyperbola->getGeom2dHyperbolaPtr()->handle() + ); + Handle(Geom2d_Hyperbola) Hypr2 = Handle(Geom2d_Hyperbola)::DownCast( + this->getGeom2dHyperbolaPtr()->handle() + ); Hypr2->SetHypr2d(Hypr1->Hypr2d()); return 0; } - static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; + static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ssc, - Base::Vector2dPy::type_object(), &pV1, - Base::Vector2dPy::type_object(), &pV2, - Base::Vector2dPy::type_object(), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ssc, + Base::Vector2dPy::type_object(), + &pV1, + Base::Vector2dPy::type_object(), + &pV2, + Base::Vector2dPy::type_object(), + &pV3 + )) { Base::Vector2d v1 = Py::toVector2d(pV1); Base::Vector2d v2 = Py::toVector2d(pV2); Base::Vector2d v3 = Py::toVector2d(pV3); - GCE2d_MakeHyperbola me(gp_Pnt2d(v1.x,v1.y), - gp_Pnt2d(v2.x,v2.y), - gp_Pnt2d(v3.x,v3.y)); + GCE2d_MakeHyperbola me(gp_Pnt2d(v1.x, v1.y), gp_Pnt2d(v2.x, v2.y), gp_Pnt2d(v3.x, v3.y)); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; } - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); hyperbola->SetHypr2d(me.Value()->Hypr2d()); return 0; } - static const std::array keywords_cmm {"Center", "MajorRadius", "MinorRadius", nullptr}; + static const std::array keywords_cmm {"Center", "MajorRadius", "MinorRadius", nullptr}; PyErr_Clear(); - PyObject *pV; + PyObject* pV; double major, minor; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!dd", keywords_cmm, - Base::Vector2dPy::type_object(), &pV, - &major, &minor)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!dd", + keywords_cmm, + Base::Vector2dPy::type_object(), + &pV, + &major, + &minor + )) { Base::Vector2d c = Py::toVector2d(pV); - GCE2d_MakeHyperbola me(gp_Ax2d(gp_Pnt2d(c.x,c.y), gp_Dir2d(0.0,1.0)), - major, minor); + GCE2d_MakeHyperbola me(gp_Ax2d(gp_Pnt2d(c.x, c.y), gp_Dir2d(0.0, 1.0)), major, minor); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; } - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); hyperbola->SetHypr2d(me.Value()->Hypr2d()); return 0; } - PyErr_SetString(PyExc_TypeError, "Hyperbola constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Hyperbola constructor accepts:\n" "-- empty parameter list\n" "-- Hyperbola\n" "-- Point, double, double\n" - "-- Point, Point, Point"); + "-- Point, Point, Point" + ); return -1; } Py::Float Hyperbola2dPy::getMajorRadius() const { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); return Py::Float(hyperbola->MajorRadius()); } void Hyperbola2dPy::setMajorRadius(Py::Float arg) { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); hyperbola->SetMajorRadius((double)arg); } Py::Float Hyperbola2dPy::getMinorRadius() const { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); return Py::Float(hyperbola->MinorRadius()); } void Hyperbola2dPy::setMinorRadius(Py::Float arg) { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); hyperbola->SetMinorRadius((double)arg); } Py::Float Hyperbola2dPy::getFocal() const { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); return Py::Float(hyperbola->Focal()); } Py::Object Hyperbola2dPy::getFocus1() const { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); gp_Pnt2d loc = hyperbola->Focus1(); return Base::Vector2dPy::create(loc.X(), loc.Y()); } Py::Object Hyperbola2dPy::getFocus2() const { - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + getGeom2dHyperbolaPtr()->handle() + ); gp_Pnt2d loc = hyperbola->Focus2(); return Base::Vector2dPy::create(loc.X(), loc.Y()); } -PyObject *Hyperbola2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Hyperbola2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp index 3609b3b5f7..dbc9d9ab74 100644 --- a/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -44,7 +44,7 @@ std::string Line2dPy::representation() const return ""; } -PyObject *Line2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Line2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of Line2dPy and the Twin object return new Line2dPy(new Geom2dLine); @@ -59,16 +59,18 @@ int Line2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pLine; + PyObject* pLine; if (PyArg_ParseTuple(args, "O!", &(Line2dPy::Type), &pLine)) { // Copy line Line2dPy* pcLine = static_cast(pLine); // get Geom_Line of line - Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast - (pcLine->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast( + pcLine->getGeom2dLinePtr()->handle() + ); // get Geom_Line of line - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast( + this->getGeom2dLinePtr()->handle() + ); // Assign the lines this_line->SetLin2d(that_line->Lin2d()); @@ -77,25 +79,32 @@ int Line2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject *pV1, *pV2; - if (PyArg_ParseTuple(args, "O!O!", Base::Vector2dPy::type_object(), &pV1, - Base::Vector2dPy::type_object(), &pV2)) { + if (PyArg_ParseTuple( + args, + "O!O!", + Base::Vector2dPy::type_object(), + &pV1, + Base::Vector2dPy::type_object(), + &pV2 + )) { Base::Vector2d v1 = Py::toVector2d(pV1); Base::Vector2d v2 = Py::toVector2d(pV2); try { // Create line out of two points - double distance = (v1-v2).Length(); - if (distance < gp::Resolution()) + double distance = (v1 - v2).Length(); + if (distance < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); - GCE2d_MakeLine ms(gp_Pnt2d(v1.x,v1.y), - gp_Pnt2d(v2.x,v2.y)); + } + GCE2d_MakeLine ms(gp_Pnt2d(v1.x, v1.y), gp_Pnt2d(v2.x, v2.y)); if (!ms.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(ms.Status())); return -1; } // get Geom_Line of line - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast( + this->getGeom2dLinePtr()->handle() + ); Handle(Geom2d_Line) that_line = ms.Value(); this_line->SetLin2d(that_line->Lin2d()); return 0; @@ -111,17 +120,19 @@ int Line2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } - PyErr_SetString(PyExc_TypeError, "Line constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Line constructor accepts:\n" "-- empty parameter list\n" "-- Line\n" - "-- Point, Point"); + "-- Point, Point" + ); return -1; } Py::Object Line2dPy::getLocation() const { - Handle(Geom2d_Line) this_curve = Handle(Geom2d_Line)::DownCast - (this->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) this_curve = Handle(Geom2d_Line)::DownCast(this->getGeom2dLinePtr()->handle()); gp_Pnt2d pnt = this_curve->Location(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } @@ -130,11 +141,10 @@ void Line2dPy::setLocation(Py::Object arg) { gp_Pnt2d pnt; gp_Dir2d dir; - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this->getGeom2dLinePtr()->handle()); dir = this_line->Direction(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, Base::Vector2dPy::type_object())) { Base::Vector2d v = Py::toVector2d(p); pnt.SetX(v.x); @@ -168,8 +178,7 @@ void Line2dPy::setLocation(Py::Object arg) Py::Object Line2dPy::getDirection() const { - Handle(Geom2d_Line) this_curve = Handle(Geom2d_Line)::DownCast - (this->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) this_curve = Handle(Geom2d_Line)::DownCast(this->getGeom2dLinePtr()->handle()); gp_Dir2d dir = this_curve->Direction(); return Base::Vector2dPy::create(dir.X(), dir.Y()); } @@ -178,20 +187,19 @@ void Line2dPy::setDirection(Py::Object arg) { gp_Pnt2d pnt; gp_Dir2d dir; - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this->getGeom2dLinePtr()->handle()); pnt = this_line->Location(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, Base::Vector2dPy::type_object())) { Base::Vector2d v = Py::toVector2d(p); - dir = gp_Dir2d(v.x,v.y); + dir = gp_Dir2d(v.x, v.y); } else if (PyTuple_Check(p)) { Py::Tuple tuple(arg); double x = (double)Py::Float(tuple.getItem(0)); double y = (double)Py::Float(tuple.getItem(1)); - dir = gp_Dir2d(x,y); + dir = gp_Dir2d(x, y); } else { std::string error = std::string("type must be 'Vector2d' or tuple, not "); @@ -214,7 +222,7 @@ void Line2dPy::setDirection(Py::Object arg) } } -PyObject *Line2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Line2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/Line2dSegment.pyi b/src/Mod/Part/App/Geom2d/Line2dSegment.pyi index 6e04f1c092..5efde42b56 100644 --- a/src/Mod/Part/App/Geom2d/Line2dSegment.pyi +++ b/src/Mod/Part/App/Geom2d/Line2dSegment.pyi @@ -12,17 +12,17 @@ from Part.Geom2d import Curve2d ) class Line2dSegment(Curve2d): """ - Describes a line segment in 2D space. + Describes a line segment in 2D space. -To create a line there are several ways: -Part.Geom2d.Line2dSegment() - Creates a default line + To create a line there are several ways: + Part.Geom2d.Line2dSegment() + Creates a default line -Part.Geom2d.Line2dSegment(Line) - Creates a copy of the given line + Part.Geom2d.Line2dSegment(Line) + Creates a copy of the given line -Part.Geom2d.Line2dSegment(Point1,Point2) - Creates a line that goes through two given points. + Part.Geom2d.Line2dSegment(Point1,Point2) + Creates a line that goes through two given points. """ StartPoint: object = ... @@ -33,13 +33,10 @@ Part.Geom2d.Line2dSegment(Point1,Point2) @overload def __init__(self) -> None: ... - @overload def __init__(self, Line: "Line2dSegment") -> None: ... - @overload def __init__(self, Point1: object, Point2: object) -> None: ... - def setParameterRange(self) -> None: """ Set the parameter range of the underlying line segment geometry. diff --git a/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp b/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp index 6f94dd6b09..4fa27523a2 100644 --- a/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -46,7 +46,7 @@ std::string Line2dSegmentPy::representation() const return ""; } -PyObject *Line2dSegmentPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Line2dSegmentPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of Line2dSegmentPy and the Twin object return new Line2dSegmentPy(new Geom2dLineSegment); @@ -61,20 +61,20 @@ int Line2dSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pLine; + PyObject* pLine; if (PyArg_ParseTuple(args, "O!", &(Line2dSegmentPy::Type), &pLine)) { // Copy line Line2dSegmentPy* pcLine = static_cast(pLine); // get Geom_Line of line segment - Handle(Geom2d_TrimmedCurve) that_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (pcLine->getGeom2dLineSegmentPtr()->handle()); - Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast - (that_curv->BasisCurve()); + Handle(Geom2d_TrimmedCurve) that_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + pcLine->getGeom2dLineSegmentPtr()->handle() + ); + Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast(that_curv->BasisCurve()); // get Geom_Line of line segment - Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); // Assign the lines this_line->SetLin2d(that_line->Lin2d()); @@ -88,15 +88,15 @@ int Line2dSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) // Copy line Line2dSegmentPy* pcLine = static_cast(pLine); // get Geom_Line of line segment - Handle(Geom2d_TrimmedCurve) that_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (pcLine->getGeom2dLineSegmentPtr()->handle()); - Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast - (that_curv->BasisCurve()); + Handle(Geom2d_TrimmedCurve) that_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + pcLine->getGeom2dLineSegmentPtr()->handle() + ); + Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast(that_curv->BasisCurve()); // get Geom_Line of line segment - Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); // Assign the lines this_line->SetLin2d(that_line->Lin2d()); @@ -109,13 +109,14 @@ int Line2dSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) // Copy line Line2dPy* pcLine = static_cast(pLine); // get Geom_Line of line - Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast - (pcLine->getGeom2dLinePtr()->handle()); + Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast( + pcLine->getGeom2dLinePtr()->handle() + ); // get Geom_Line of line segment - Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); // Assign the lines this_line->SetLin2d(that_line->Lin2d()); @@ -125,27 +126,33 @@ int Line2dSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject *pV1, *pV2; - if (PyArg_ParseTuple(args, "O!O!", Base::Vector2dPy::type_object(), &pV1, - Base::Vector2dPy::type_object(), &pV2)) { + if (PyArg_ParseTuple( + args, + "O!O!", + Base::Vector2dPy::type_object(), + &pV1, + Base::Vector2dPy::type_object(), + &pV2 + )) { Base::Vector2d v1 = Py::toVector2d(pV1); Base::Vector2d v2 = Py::toVector2d(pV2); try { // Create line out of two points - double distance = (v1-v2).Length(); - if (distance < gp::Resolution()) + double distance = (v1 - v2).Length(); + if (distance < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); - GCE2d_MakeSegment ms(gp_Pnt2d(v1.x,v1.y), - gp_Pnt2d(v2.x,v2.y)); + } + GCE2d_MakeSegment ms(gp_Pnt2d(v1.x, v1.y), gp_Pnt2d(v2.x, v2.y)); if (!ms.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(ms.Status())); return -1; } // get Geom_Line of line segment - Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom2d_TrimmedCurve) that_curv = ms.Value(); Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin2d(that_line->Lin2d()); @@ -163,24 +170,29 @@ int Line2dSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } - PyErr_SetString(PyExc_TypeError, "Line2dSegment constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Line2dSegment constructor accepts:\n" "-- empty parameter list\n" "-- Line2dSegment\n" "-- Line2dSegment, float, float\n" "-- Line2d, float, float\n" - "-- Point, Point"); + "-- Point, Point" + ); return -1; } -PyObject* Line2dSegmentPy::setParameterRange(PyObject *args) +PyObject* Line2dSegmentPy::setParameterRange(PyObject* args) { double first, last; - if (!PyArg_ParseTuple(args, "dd", &first, &last)) + if (!PyArg_ParseTuple(args, "dd", &first, &last)) { return nullptr; + } try { - Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); + Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); this_curve->SetTrim(first, last); } catch (Standard_Failure& e) { @@ -194,8 +206,9 @@ PyObject* Line2dSegmentPy::setParameterRange(PyObject *args) Py::Object Line2dSegmentPy::getStartPoint() const { - Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); + Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); gp_Pnt2d pnt = this_curve->StartPoint(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } @@ -203,11 +216,12 @@ Py::Object Line2dSegmentPy::getStartPoint() const void Line2dSegmentPy::setStartPoint(Py::Object arg) { gp_Pnt2d p1, p2; - Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); + Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); p2 = this_curv->EndPoint(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, Base::Vector2dPy::type_object())) { Base::Vector2d v = Py::toVector2d(p); p1.SetX(v.x); @@ -226,16 +240,16 @@ void Line2dSegmentPy::setStartPoint(Py::Object arg) try { // Create line out of two points - if (p1.Distance(p2) < gp::Resolution()) + if (p1.Distance(p2) < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); + } GCE2d_MakeSegment ms(p1, p2); if (!ms.IsDone()) { throw Py::RuntimeError(gce_ErrorStatusText(ms.Status())); } // get Geom_Line of line segment - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom2d_TrimmedCurve) that_curv = ms.Value(); Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin2d(that_line->Lin2d()); @@ -248,8 +262,9 @@ void Line2dSegmentPy::setStartPoint(Py::Object arg) Py::Object Line2dSegmentPy::getEndPoint() const { - Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); + Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); gp_Pnt2d pnt = this_curve->EndPoint(); return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } @@ -257,11 +272,12 @@ Py::Object Line2dSegmentPy::getEndPoint() const void Line2dSegmentPy::setEndPoint(Py::Object arg) { gp_Pnt2d p1, p2; - Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast - (this->getGeom2dLineSegmentPtr()->handle()); + Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast( + this->getGeom2dLineSegmentPtr()->handle() + ); p1 = this_curv->StartPoint(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, Base::Vector2dPy::type_object())) { Base::Vector2d v = Py::toVector2d(p); p2.SetX(v.x); @@ -280,16 +296,16 @@ void Line2dSegmentPy::setEndPoint(Py::Object arg) try { // Create line out of two points - if (p1.Distance(p2) < gp::Resolution()) + if (p1.Distance(p2) < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); + } GCE2d_MakeSegment ms(p1, p2); if (!ms.IsDone()) { throw Py::RuntimeError(gce_ErrorStatusText(ms.Status())); } // get Geom_Line of line segment - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom2d_TrimmedCurve) that_curv = ms.Value(); Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin2d(that_line->Lin2d()); @@ -300,7 +316,7 @@ void Line2dSegmentPy::setEndPoint(Py::Object arg) } } -PyObject *Line2dSegmentPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Line2dSegmentPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/OffsetCurve2d.pyi b/src/Mod/Part/App/Geom2d/OffsetCurve2d.pyi index 1363db5d1c..c08abfe716 100644 --- a/src/Mod/Part/App/Geom2d/OffsetCurve2d.pyi +++ b/src/Mod/Part/App/Geom2d/OffsetCurve2d.pyi @@ -24,4 +24,4 @@ class OffsetCurve2d(Curve2d): """Sets or gets the offset value to offset the underlying curve.""" BasisCurve: object = ... - """Sets or gets the basic curve.""" \ No newline at end of file + """Sets or gets the basic curve.""" diff --git a/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp index 982ffd68f9..e88073df56 100644 --- a/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include "Geom2d/OffsetCurve2dPy.h" @@ -38,7 +38,7 @@ std::string OffsetCurve2dPy::representation() const return ""; } -PyObject *OffsetCurve2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* OffsetCurve2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of OffsetCurve2dPy and the Twin object return new OffsetCurve2dPy(new Geom2dOffsetCurve); @@ -49,14 +49,12 @@ int OffsetCurve2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) { PyObject* pGeom; double offset; - if (!PyArg_ParseTuple(args, "O!d", - &(Curve2dPy::Type), &pGeom, - &offset)) + if (!PyArg_ParseTuple(args, "O!d", &(Curve2dPy::Type), &pGeom, &offset)) { return -1; + } Curve2dPy* pcGeo = static_cast(pGeom); - Handle(Geom2d_Curve) curve = Handle(Geom2d_Curve)::DownCast - (pcGeo->getGeometry2dPtr()->handle()); + Handle(Geom2d_Curve) curve = Handle(Geom2d_Curve)::DownCast(pcGeo->getGeometry2dPtr()->handle()); if (curve.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a curve"); return -1; @@ -76,25 +74,33 @@ int OffsetCurve2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::Float OffsetCurve2dPy::getOffsetValue() const { - Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast(getGeometry2dPtr()->handle()); + Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast( + getGeometry2dPtr()->handle() + ); return Py::Float(curve->Offset()); } void OffsetCurve2dPy::setOffsetValue(Py::Float arg) { - Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast(getGeometry2dPtr()->handle()); + Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast( + getGeometry2dPtr()->handle() + ); curve->SetOffsetValue((double)arg); } Py::Object OffsetCurve2dPy::getBasisCurve() const { - Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast(getGeometry2dPtr()->handle()); + Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast( + getGeometry2dPtr()->handle() + ); Handle(Geom2d_Curve) basis = curve->BasisCurve(); - if (basis.IsNull()) + if (basis.IsNull()) { return Py::None(); + } std::unique_ptr geo2d = makeFromCurve2d(basis); - if (!geo2d) + if (!geo2d) { throw Py::RuntimeError("Unknown curve type"); + } return Py::asObject(geo2d->getPyObject()); } @@ -103,14 +109,16 @@ void OffsetCurve2dPy::setBasisCurve(Py::Object arg) PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Curve2dPy::Type))) { Curve2dPy* pcGeo = static_cast(p); - Handle(Geom2d_Curve) curve = Handle(Geom2d_Curve)::DownCast - (pcGeo->getGeometry2dPtr()->handle()); + Handle(Geom2d_Curve) curve = Handle(Geom2d_Curve)::DownCast( + pcGeo->getGeometry2dPtr()->handle() + ); if (curve.IsNull()) { throw Py::TypeError("geometry is not a curve"); } - Handle(Geom2d_OffsetCurve) curve2 = Handle(Geom2d_OffsetCurve)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_OffsetCurve) curve2 = Handle(Geom2d_OffsetCurve)::DownCast( + getGeometry2dPtr()->handle() + ); if (curve == curve2) { throw Py::RuntimeError("cannot set this curve as basis"); } @@ -124,7 +132,7 @@ void OffsetCurve2dPy::setBasisCurve(Py::Object arg) } } -PyObject *OffsetCurve2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* OffsetCurve2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geom2d/Parabola2d.pyi b/src/Mod/Part/App/Geom2d/Parabola2d.pyi index 490929dcfc..e74e12f617 100644 --- a/src/Mod/Part/App/Geom2d/Parabola2d.pyi +++ b/src/Mod/Part/App/Geom2d/Parabola2d.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from Part.App.Geom2d.Conic2d import Conic2d from typing import Final - @export( Include="Mod/Part/App/Geometry2d.h", FatherInclude="Mod/Part/App/Geom2d/Conic2dPy.h", diff --git a/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp index d091eb51ee..5fd6c68f20 100644 --- a/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -40,7 +40,7 @@ std::string Parabola2dPy::representation() const return ""; } -PyObject *Parabola2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* Parabola2dPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of Parabola2dPy and the Twin object return new Parabola2dPy(new Geom2dParabola); @@ -50,8 +50,7 @@ PyObject *Parabola2dPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // int Parabola2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) { if (PyArg_ParseTuple(args, "")) { - Handle(Geom2d_Parabola) c = Handle(Geom2d_Parabola)::DownCast - (getGeometry2dPtr()->handle()); + Handle(Geom2d_Parabola) c = Handle(Geom2d_Parabola)::DownCast(getGeometry2dPtr()->handle()); c->SetFocal(1.0); return 0; } @@ -84,7 +83,7 @@ Py::Float Parabola2dPy::getParameter() const return Py::Float(curve->Parameter()); } -PyObject *Parabola2dPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Parabola2dPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePyImp.cpp b/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePyImp.cpp index e0e6ddab7d..434185f584 100644 --- a/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePyImp.cpp +++ b/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "GeomPlate/BuildPlateSurfacePy.h" @@ -77,7 +77,7 @@ Part.show(l4.toShape()) bp.surfInit() * \endcode */ -PyObject *BuildPlateSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* BuildPlateSurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of BuildPlateSurfacePy return new BuildPlateSurfacePy(nullptr); @@ -86,7 +86,7 @@ PyObject *BuildPlateSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject // constructor method int BuildPlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) { - PyObject *surf = nullptr; + PyObject* surf = nullptr; int degree = 3; int nbPtsOnCur = 10; int nbIter = 3; @@ -96,19 +96,49 @@ int BuildPlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) double tolCurv = 0.1; PyObject* anisotropy = Py_False; - static const std::array keywords{"Surface", "Degree", "NbPtsOnCur", "NbIter", "Tol2d", "Tol3d", - "TolAng", "TolCurv", "Anisotropy", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|O!iiiddddO!", keywords, - &(GeometrySurfacePy::Type), &surf, °ree, - &nbPtsOnCur, &nbIter, &tol2d, &tol3d, - &tolAng, &tolCurv, &PyBool_Type, &anisotropy)) { + static const std::array keywords { + "Surface", + "Degree", + "NbPtsOnCur", + "NbIter", + "Tol2d", + "Tol3d", + "TolAng", + "TolCurv", + "Anisotropy", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|O!iiiddddO!", + keywords, + &(GeometrySurfacePy::Type), + &surf, + °ree, + &nbPtsOnCur, + &nbIter, + &tol2d, + &tol3d, + &tolAng, + &tolCurv, + &PyBool_Type, + &anisotropy + )) { return -1; } try { - std::unique_ptr ptr(new GeomPlate_BuildPlateSurface - (degree, nbPtsOnCur, nbIter, tol2d, tol3d, tolAng, tolCurv, - Base::asBoolean(anisotropy))); + std::unique_ptr ptr(new GeomPlate_BuildPlateSurface( + degree, + nbPtsOnCur, + nbIter, + tol2d, + tol3d, + tolAng, + tolCurv, + Base::asBoolean(anisotropy) + )); if (surf) { GeomSurface* surface = static_cast(surf)->getGeomSurfacePtr(); @@ -136,10 +166,11 @@ std::string BuildPlateSurfacePy::representation() const return {""}; } -PyObject* BuildPlateSurfacePy::init(PyObject *args) +PyObject* BuildPlateSurfacePy::init(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { getGeomPlate_BuildPlateSurfacePtr()->Init(); @@ -151,11 +182,12 @@ PyObject* BuildPlateSurfacePy::init(PyObject *args) } } -PyObject* BuildPlateSurfacePy::loadInitSurface(PyObject *args) +PyObject* BuildPlateSurfacePy::loadInitSurface(PyObject* args) { PyObject* surf; - if (!PyArg_ParseTuple(args, "O!", &(GeometrySurfacePy::Type), &surf)) + if (!PyArg_ParseTuple(args, "O!", &(GeometrySurfacePy::Type), &surf)) { return nullptr; + } GeomSurface* surface = static_cast(surf)->getGeomSurfacePtr(); Handle(Geom_Surface) handle = Handle(Geom_Surface)::DownCast(surface->handle()); @@ -174,20 +206,23 @@ PyObject* BuildPlateSurfacePy::loadInitSurface(PyObject *args) } } -PyObject* BuildPlateSurfacePy::add(PyObject *args) +PyObject* BuildPlateSurfacePy::add(PyObject* args) { PyObject* cont; - if (!PyArg_ParseTuple(args, "O", &cont)) + if (!PyArg_ParseTuple(args, "O", &cont)) { return nullptr; + } try { if (PyObject_TypeCheck(cont, &PointConstraintPy::Type)) { - GeomPlate_PointConstraint* pc = static_cast(cont)->getGeomPlate_PointConstraintPtr(); + GeomPlate_PointConstraint* pc + = static_cast(cont)->getGeomPlate_PointConstraintPtr(); getGeomPlate_BuildPlateSurfacePtr()->Add(new GeomPlate_PointConstraint(*pc)); Py_Return; } else if (PyObject_TypeCheck(cont, &CurveConstraintPy::Type)) { - GeomPlate_CurveConstraint* cc = static_cast(cont)->getGeomPlate_CurveConstraintPtr(); + GeomPlate_CurveConstraint* cc + = static_cast(cont)->getGeomPlate_CurveConstraintPtr(); getGeomPlate_BuildPlateSurfacePtr()->Add(new GeomPlate_CurveConstraint(*cc)); Py_Return; } @@ -202,11 +237,12 @@ PyObject* BuildPlateSurfacePy::add(PyObject *args) } } -PyObject* BuildPlateSurfacePy::setNbBounds(PyObject *args) +PyObject* BuildPlateSurfacePy::setNbBounds(PyObject* args) { int count; - if (!PyArg_ParseTuple(args, "i", &count)) + if (!PyArg_ParseTuple(args, "i", &count)) { return nullptr; + } try { getGeomPlate_BuildPlateSurfacePtr()->SetNbBounds(count); @@ -218,10 +254,11 @@ PyObject* BuildPlateSurfacePy::setNbBounds(PyObject *args) } } -PyObject* BuildPlateSurfacePy::perform(PyObject *args) +PyObject* BuildPlateSurfacePy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { getGeomPlate_BuildPlateSurfacePtr()->Perform(); @@ -233,10 +270,11 @@ PyObject* BuildPlateSurfacePy::perform(PyObject *args) } } -PyObject* BuildPlateSurfacePy::isDone(PyObject *args) const +PyObject* BuildPlateSurfacePy::isDone(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Boolean ok = getGeomPlate_BuildPlateSurfacePtr()->IsDone(); @@ -248,15 +286,17 @@ PyObject* BuildPlateSurfacePy::isDone(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::surface(PyObject *args) const +PyObject* BuildPlateSurfacePy::surface(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom_Surface) hSurf = getGeomPlate_BuildPlateSurfacePtr()->Surface(); - if (hSurf.IsNull()) + if (hSurf.IsNull()) { Py_Return; + } std::unique_ptr geo(makeFromSurface(hSurf)); return geo->getPyObject(); @@ -267,15 +307,17 @@ PyObject* BuildPlateSurfacePy::surface(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::surfInit(PyObject *args) const +PyObject* BuildPlateSurfacePy::surfInit(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom_Surface) hSurf = getGeomPlate_BuildPlateSurfacePtr()->SurfInit(); - if (hSurf.IsNull()) + if (hSurf.IsNull()) { Py_Return; + } std::unique_ptr geo(makeFromSurface(hSurf)); return geo->getPyObject(); @@ -286,16 +328,20 @@ PyObject* BuildPlateSurfacePy::surfInit(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::curveConstraint(PyObject *args) const +PyObject* BuildPlateSurfacePy::curveConstraint(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(GeomPlate_CurveConstraint) hCC = getGeomPlate_BuildPlateSurfacePtr()->CurveConstraint(index); - if (hCC.IsNull()) + Handle(GeomPlate_CurveConstraint) hCC = getGeomPlate_BuildPlateSurfacePtr()->CurveConstraint( + index + ); + if (hCC.IsNull()) { Py_Return; + } std::unique_ptr ptr(new GeomPlate_CurveConstraint(*hCC)); return new CurveConstraintPy(ptr.release()); @@ -306,16 +352,20 @@ PyObject* BuildPlateSurfacePy::curveConstraint(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::pointConstraint(PyObject *args) const +PyObject* BuildPlateSurfacePy::pointConstraint(PyObject* args) const { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { - Handle(GeomPlate_PointConstraint) hPC = getGeomPlate_BuildPlateSurfacePtr()->PointConstraint(index); - if (hPC.IsNull()) + Handle(GeomPlate_PointConstraint) hPC = getGeomPlate_BuildPlateSurfacePtr()->PointConstraint( + index + ); + if (hPC.IsNull()) { Py_Return; + } std::unique_ptr ptr(new GeomPlate_PointConstraint(*hPC)); return new PointConstraintPy(ptr.release()); @@ -326,11 +376,12 @@ PyObject* BuildPlateSurfacePy::pointConstraint(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::disc2dContour(PyObject *args) +PyObject* BuildPlateSurfacePy::disc2dContour(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } try { TColgp_SequenceOfXY seq2d; @@ -353,11 +404,12 @@ PyObject* BuildPlateSurfacePy::disc2dContour(PyObject *args) } } -PyObject* BuildPlateSurfacePy::disc3dContour(PyObject *args) +PyObject* BuildPlateSurfacePy::disc3dContour(PyObject* args) { int index, order; - if (!PyArg_ParseTuple(args, "ii", &index, &order)) + if (!PyArg_ParseTuple(args, "ii", &index, &order)) { return nullptr; + } try { TColgp_SequenceOfXYZ seq3d; @@ -381,10 +433,11 @@ PyObject* BuildPlateSurfacePy::disc3dContour(PyObject *args) } } -PyObject* BuildPlateSurfacePy::sense(PyObject *args) const +PyObject* BuildPlateSurfacePy::sense(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(TColStd_HArray1OfInteger) hOrder = getGeomPlate_BuildPlateSurfacePtr()->Sense(); @@ -402,10 +455,11 @@ PyObject* BuildPlateSurfacePy::sense(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::curves2d(PyObject *args) const +PyObject* BuildPlateSurfacePy::curves2d(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(TColGeom2d_HArray1OfCurve) hCurves = getGeomPlate_BuildPlateSurfacePtr()->Curves2d(); @@ -414,8 +468,9 @@ PyObject* BuildPlateSurfacePy::curves2d(PyObject *args) const for (auto i = hCurves->Lower(); i <= hCurves->Upper(); ++i) { Handle(Geom2d_Curve) hCurve = hCurves->Value(i); std::unique_ptr ptr(makeFromCurve2d(hCurve)); - if (ptr) + if (ptr) { list.append(Py::asObject(ptr->getPyObject())); + } } } return Py::new_reference_to(list); @@ -426,10 +481,11 @@ PyObject* BuildPlateSurfacePy::curves2d(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::order(PyObject *args) const +PyObject* BuildPlateSurfacePy::order(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(TColStd_HArray1OfInteger) hOrder = getGeomPlate_BuildPlateSurfacePtr()->Order(); @@ -447,11 +503,12 @@ PyObject* BuildPlateSurfacePy::order(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::G0Error(PyObject *args) const +PyObject* BuildPlateSurfacePy::G0Error(PyObject* args) const { int index = 0; - if (!PyArg_ParseTuple(args, "|i", &index)) + if (!PyArg_ParseTuple(args, "|i", &index)) { return nullptr; + } try { Standard_Real v = index < 1 ? getGeomPlate_BuildPlateSurfacePtr()->G0Error() @@ -464,11 +521,12 @@ PyObject* BuildPlateSurfacePy::G0Error(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::G1Error(PyObject *args) const +PyObject* BuildPlateSurfacePy::G1Error(PyObject* args) const { int index = 0; - if (!PyArg_ParseTuple(args, "|i", &index)) + if (!PyArg_ParseTuple(args, "|i", &index)) { return nullptr; + } try { Standard_Real v = index < 1 ? getGeomPlate_BuildPlateSurfacePtr()->G1Error() @@ -481,11 +539,12 @@ PyObject* BuildPlateSurfacePy::G1Error(PyObject *args) const } } -PyObject* BuildPlateSurfacePy::G2Error(PyObject *args) const +PyObject* BuildPlateSurfacePy::G2Error(PyObject* args) const { int index = 0; - if (!PyArg_ParseTuple(args, "|i", &index)) + if (!PyArg_ParseTuple(args, "|i", &index)) { return nullptr; + } try { Standard_Real v = index < 1 ? getGeomPlate_BuildPlateSurfacePtr()->G2Error() @@ -498,7 +557,7 @@ PyObject* BuildPlateSurfacePy::G2Error(PyObject *args) const } } -PyObject *BuildPlateSurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* BuildPlateSurfacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp b/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp index 57ce3e6f13..e21394848c 100644 --- a/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp +++ b/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp @@ -24,14 +24,14 @@ #include -# include -# include -# include -# include -# if OCC_VERSION_HEX < 0x070600 +#include +#include +#include +#include +#if OCC_VERSION_HEX < 0x070600 # include # include -# endif +#endif #include "GeomPlate/CurveConstraintPy.h" #include "GeomPlate/CurveConstraintPy.cpp" @@ -42,7 +42,7 @@ using namespace Part; -PyObject *CurveConstraintPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* CurveConstraintPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of CurveConstraintPy and the Twin object return new CurveConstraintPy(nullptr); @@ -51,7 +51,7 @@ PyObject *CurveConstraintPy::PyMake(struct _typeobject *, PyObject *, PyObject * // constructor method int CurveConstraintPy::PyInit(PyObject* args, PyObject* kwds) { - PyObject *bound = nullptr; + PyObject* bound = nullptr; int order = 0; int nbPts = 10; double tolDist = 0.0001; @@ -63,11 +63,21 @@ int CurveConstraintPy::PyInit(PyObject* args, PyObject* kwds) // Length(), FirstParameter(), LastParameter(), ... // Thus, we don't allow one to create an empty GeomPlate_CurveConstraint instance - static const std::array keywords{"Boundary", "Order", "NbPts", "TolDist", "TolAng", "TolCurv", - nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|iiddd", keywords, - &(GeometryCurvePy::Type), &bound, &order, - &nbPts, &tolDist, &tolAng, &tolCurv)) { + static const std::array + keywords {"Boundary", "Order", "NbPts", "TolDist", "TolAng", "TolCurv", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|iiddd", + keywords, + &(GeometryCurvePy::Type), + &bound, + &order, + &nbPts, + &tolDist, + &tolAng, + &tolCurv + )) { return -1; } @@ -85,7 +95,11 @@ int CurveConstraintPy::PyInit(PyObject* args, PyObject* kwds) Handle(Adaptor3d_Curve) hCurve; if (curve->isDerivedFrom()) { GeomTrimmedCurve* trim = static_cast(curve); - hCurve = new GeomAdaptor_Curve(handle, trim->getFirstParameter(), trim->getLastParameter()); + hCurve = new GeomAdaptor_Curve( + handle, + trim->getFirstParameter(), + trim->getLastParameter() + ); } else { hCurve = new GeomAdaptor_Curve(handle); @@ -125,11 +139,12 @@ std::string CurveConstraintPy::representation() const return {""}; } -PyObject* CurveConstraintPy::setOrder(PyObject *args) +PyObject* CurveConstraintPy::setOrder(PyObject* args) { int order; - if (!PyArg_ParseTuple(args, "i", &order)) + if (!PyArg_ParseTuple(args, "i", &order)) { return nullptr; + } try { getGeomPlate_CurveConstraintPtr()->SetOrder(order); @@ -141,10 +156,11 @@ PyObject* CurveConstraintPy::setOrder(PyObject *args) } } -PyObject* CurveConstraintPy::order(PyObject *args) +PyObject* CurveConstraintPy::order(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Integer v = getGeomPlate_CurveConstraintPtr()->Order(); @@ -156,11 +172,12 @@ PyObject* CurveConstraintPy::order(PyObject *args) } } -PyObject* CurveConstraintPy::G0Criterion(PyObject *args) +PyObject* CurveConstraintPy::G0Criterion(PyObject* args) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } try { Standard_Real v = getGeomPlate_CurveConstraintPtr()->G0Criterion(u); @@ -172,11 +189,12 @@ PyObject* CurveConstraintPy::G0Criterion(PyObject *args) } } -PyObject* CurveConstraintPy::G1Criterion(PyObject *args) +PyObject* CurveConstraintPy::G1Criterion(PyObject* args) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } try { Standard_Real v = getGeomPlate_CurveConstraintPtr()->G1Criterion(u); @@ -188,11 +206,12 @@ PyObject* CurveConstraintPy::G1Criterion(PyObject *args) } } -PyObject* CurveConstraintPy::G2Criterion(PyObject *args) +PyObject* CurveConstraintPy::G2Criterion(PyObject* args) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } try { Standard_Real v = getGeomPlate_CurveConstraintPtr()->G2Criterion(u); @@ -204,33 +223,35 @@ PyObject* CurveConstraintPy::G2Criterion(PyObject *args) } } -PyObject* CurveConstraintPy::setG0Criterion(PyObject *) +PyObject* CurveConstraintPy::setG0Criterion(PyObject*) { PyErr_SetString(PyExc_NotImplementedError, "Not yet implemented"); return nullptr; } -PyObject* CurveConstraintPy::setG1Criterion(PyObject *) +PyObject* CurveConstraintPy::setG1Criterion(PyObject*) { PyErr_SetString(PyExc_NotImplementedError, "Not yet implemented"); return nullptr; } -PyObject* CurveConstraintPy::setG2Criterion(PyObject *) +PyObject* CurveConstraintPy::setG2Criterion(PyObject*) { PyErr_SetString(PyExc_NotImplementedError, "Not yet implemented"); return nullptr; } -PyObject* CurveConstraintPy::curve3d(PyObject *args) +PyObject* CurveConstraintPy::curve3d(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { auto hAdapt = getGeomPlate_CurveConstraintPtr()->Curve3d(); - if (hAdapt.IsNull()) + if (hAdapt.IsNull()) { Py_Return; + } #if OCC_VERSION_HEX >= 0x070600 const Adaptor3d_Curve& a3d = *hAdapt; @@ -246,14 +267,17 @@ PyObject* CurveConstraintPy::curve3d(PyObject *args) } } -PyObject* CurveConstraintPy::setCurve2dOnSurf(PyObject *args) +PyObject* CurveConstraintPy::setCurve2dOnSurf(PyObject* args) { PyObject* c; - if (!PyArg_ParseTuple(args, "O!", &Part::Curve2dPy::Type, &c)) + if (!PyArg_ParseTuple(args, "O!", &Part::Curve2dPy::Type, &c)) { return nullptr; + } try { - Handle(Geom2d_Curve) curve2 = Handle(Geom2d_Curve)::DownCast(static_cast(c)->getGeometry2dPtr()->handle()); + Handle(Geom2d_Curve) curve2 = Handle(Geom2d_Curve)::DownCast( + static_cast(c)->getGeometry2dPtr()->handle() + ); if (curve2.IsNull()) { PyErr_SetString(PyExc_ReferenceError, "No valid curve handle"); return nullptr; @@ -268,15 +292,17 @@ PyObject* CurveConstraintPy::setCurve2dOnSurf(PyObject *args) } } -PyObject* CurveConstraintPy::curve2dOnSurf(PyObject *args) +PyObject* CurveConstraintPy::curve2dOnSurf(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom2d_Curve) curve2 = getGeomPlate_CurveConstraintPtr()->Curve2dOnSurf(); - if (curve2.IsNull()) + if (curve2.IsNull()) { Py_Return; + } std::unique_ptr ptr(Part::makeFromCurve2d(curve2)); return ptr->getPyObject(); @@ -287,12 +313,13 @@ PyObject* CurveConstraintPy::curve2dOnSurf(PyObject *args) } } -PyObject* CurveConstraintPy::setProjectedCurve(PyObject *args) +PyObject* CurveConstraintPy::setProjectedCurve(PyObject* args) { PyObject* c; double tolU, tolV; - if (!PyArg_ParseTuple(args, "O!dd", &Part::Curve2dPy::Type, &c, &tolU, &tolV)) + if (!PyArg_ParseTuple(args, "O!dd", &Part::Curve2dPy::Type, &c, &tolU, &tolV)) { return nullptr; + } try { Geom2dCurve* curve2 = static_cast(c)->getGeom2dCurvePtr(); @@ -305,7 +332,7 @@ PyObject* CurveConstraintPy::setProjectedCurve(PyObject *args) #if OCC_VERSION_HEX >= 0x070600 Handle(Adaptor2d_Curve2d) hCurve; if (handle->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))) { - Handle(Geom2d_TrimmedCurve) aTC (Handle(Geom2d_TrimmedCurve)::DownCast (handle)); + Handle(Geom2d_TrimmedCurve) aTC(Handle(Geom2d_TrimmedCurve)::DownCast(handle)); hCurve = new Geom2dAdaptor_Curve(handle, aTC->FirstParameter(), aTC->LastParameter()); } else { @@ -314,7 +341,7 @@ PyObject* CurveConstraintPy::setProjectedCurve(PyObject *args) #else Handle(Adaptor2d_HCurve2d) hCurve; if (handle->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))) { - Handle(Geom2d_TrimmedCurve) aTC (Handle(Geom2d_TrimmedCurve)::DownCast (handle)); + Handle(Geom2d_TrimmedCurve) aTC(Handle(Geom2d_TrimmedCurve)::DownCast(handle)); Geom2dAdaptor_Curve adapt(handle, aTC->FirstParameter(), aTC->LastParameter()); hCurve = new Geom2dAdaptor_HCurve(adapt); } @@ -333,15 +360,17 @@ PyObject* CurveConstraintPy::setProjectedCurve(PyObject *args) } } -PyObject* CurveConstraintPy::projectedCurve(PyObject *args) +PyObject* CurveConstraintPy::projectedCurve(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { auto hAdapt = getGeomPlate_CurveConstraintPtr()->ProjectedCurve(); - if (hAdapt.IsNull()) + if (hAdapt.IsNull()) { Py_Return; + } #if OCC_VERSION_HEX >= 0x070600 const Adaptor2d_Curve2d& a2d = *hAdapt; @@ -368,7 +397,7 @@ Py::Long CurveConstraintPy::getNbPoints() const } } -void CurveConstraintPy::setNbPoints(Py::Long arg) +void CurveConstraintPy::setNbPoints(Py::Long arg) { try { getGeomPlate_CurveConstraintPtr()->SetNbPoints(static_cast(arg)); @@ -411,7 +440,7 @@ Py::Float CurveConstraintPy::getLength() const } } -PyObject *CurveConstraintPy::getCustomAttributes(const char* /*attr*/) const +PyObject* CurveConstraintPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp b/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp index 902a7e5657..90967a69f6 100644 --- a/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp +++ b/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp @@ -24,8 +24,8 @@ #include -# include -# include +#include +#include #include @@ -37,7 +37,7 @@ using namespace Part; -PyObject *PointConstraintPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PointConstraintPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of PointConstraintPy return new PointConstraintPy(nullptr); @@ -46,13 +46,21 @@ PyObject *PointConstraintPy::PyMake(struct _typeobject *, PyObject *, PyObject * // constructor method int PointConstraintPy::PyInit(PyObject* args, PyObject* kwds) { - PyObject *pt; + PyObject* pt; int order = 0; double tolDist = 0.0001; - static const std::array keywords {"Point", "Order", "TolDist", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|id", keywords, &(Base::VectorPy::Type), &pt, &order, - &tolDist)) { + static const std::array keywords {"Point", "Order", "TolDist", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|id", + keywords, + &(Base::VectorPy::Type), + &pt, + &order, + &tolDist + )) { return -1; } @@ -77,11 +85,12 @@ std::string PointConstraintPy::representation() const return {""}; } -PyObject* PointConstraintPy::setOrder(PyObject *args) +PyObject* PointConstraintPy::setOrder(PyObject* args) { int order; - if (!PyArg_ParseTuple(args, "i", &order)) + if (!PyArg_ParseTuple(args, "i", &order)) { return nullptr; + } try { getGeomPlate_PointConstraintPtr()->SetOrder(order); @@ -93,10 +102,11 @@ PyObject* PointConstraintPy::setOrder(PyObject *args) } } -PyObject* PointConstraintPy::order(PyObject *args) +PyObject* PointConstraintPy::order(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Integer v = getGeomPlate_PointConstraintPtr()->Order(); @@ -108,10 +118,11 @@ PyObject* PointConstraintPy::order(PyObject *args) } } -PyObject* PointConstraintPy::G0Criterion(PyObject *args) +PyObject* PointConstraintPy::G0Criterion(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Real v = getGeomPlate_PointConstraintPtr()->G0Criterion(); @@ -123,10 +134,11 @@ PyObject* PointConstraintPy::G0Criterion(PyObject *args) } } -PyObject* PointConstraintPy::G1Criterion(PyObject *args) +PyObject* PointConstraintPy::G1Criterion(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Real v = getGeomPlate_PointConstraintPtr()->G1Criterion(); @@ -138,10 +150,11 @@ PyObject* PointConstraintPy::G1Criterion(PyObject *args) } } -PyObject* PointConstraintPy::G2Criterion(PyObject *args) +PyObject* PointConstraintPy::G2Criterion(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Real v = getGeomPlate_PointConstraintPtr()->G2Criterion(); @@ -153,11 +166,12 @@ PyObject* PointConstraintPy::G2Criterion(PyObject *args) } } -PyObject* PointConstraintPy::setG0Criterion(PyObject *args) +PyObject* PointConstraintPy::setG0Criterion(PyObject* args) { double tolDist; - if (!PyArg_ParseTuple(args, "d", &tolDist)) + if (!PyArg_ParseTuple(args, "d", &tolDist)) { return nullptr; + } try { getGeomPlate_PointConstraintPtr()->SetG0Criterion(tolDist); @@ -169,11 +183,12 @@ PyObject* PointConstraintPy::setG0Criterion(PyObject *args) } } -PyObject* PointConstraintPy::setG1Criterion(PyObject *args) +PyObject* PointConstraintPy::setG1Criterion(PyObject* args) { double tolAng; - if (!PyArg_ParseTuple(args, "d", &tolAng)) + if (!PyArg_ParseTuple(args, "d", &tolAng)) { return nullptr; + } try { getGeomPlate_PointConstraintPtr()->SetG1Criterion(tolAng); @@ -185,11 +200,12 @@ PyObject* PointConstraintPy::setG1Criterion(PyObject *args) } } -PyObject* PointConstraintPy::setG2Criterion(PyObject *args) +PyObject* PointConstraintPy::setG2Criterion(PyObject* args) { double tolCurv; - if (!PyArg_ParseTuple(args, "d", &tolCurv)) + if (!PyArg_ParseTuple(args, "d", &tolCurv)) { return nullptr; + } try { getGeomPlate_PointConstraintPtr()->SetG2Criterion(tolCurv); @@ -201,10 +217,11 @@ PyObject* PointConstraintPy::setG2Criterion(PyObject *args) } } -PyObject* PointConstraintPy::hasPnt2dOnSurf(PyObject *args) +PyObject* PointConstraintPy::hasPnt2dOnSurf(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Standard_Boolean ok = getGeomPlate_PointConstraintPtr()->HasPnt2dOnSurf(); @@ -216,11 +233,12 @@ PyObject* PointConstraintPy::hasPnt2dOnSurf(PyObject *args) } } -PyObject* PointConstraintPy::setPnt2dOnSurf(PyObject *args) +PyObject* PointConstraintPy::setPnt2dOnSurf(PyObject* args) { double x, y; - if (!PyArg_ParseTuple(args, "dd", &x, &y)) + if (!PyArg_ParseTuple(args, "dd", &x, &y)) { return nullptr; + } try { getGeomPlate_PointConstraintPtr()->SetPnt2dOnSurf(gp_Pnt2d(x, y)); @@ -232,10 +250,11 @@ PyObject* PointConstraintPy::setPnt2dOnSurf(PyObject *args) } } -PyObject* PointConstraintPy::pnt2dOnSurf(PyObject *args) +PyObject* PointConstraintPy::pnt2dOnSurf(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { gp_Pnt2d pt = getGeomPlate_PointConstraintPtr()->Pnt2dOnSurf(); @@ -250,7 +269,7 @@ PyObject* PointConstraintPy::pnt2dOnSurf(PyObject *args) } } -PyObject *PointConstraintPy::getCustomAttributes(const char* /*attr*/) const +PyObject* PointConstraintPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Geometry.cpp b/src/Mod/Part/App/Geometry.cpp index d193cb50d8..b93a11b2d3 100644 --- a/src/Mod/Part/App/Geometry.cpp +++ b/src/Mod/Part/App/Geometry.cpp @@ -22,90 +22,90 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# if OCC_VERSION_HEX < 0x070600 +#if OCC_VERSION_HEX < 0x070600 # include # include -# endif +#endif -# include -# include -# include -# include +#include +#include +#include +#include #include #include @@ -161,46 +161,45 @@ using namespace Part; const char* gce_ErrorStatusText(gce_ErrorType et) { - switch (et) - { - case gce_Done: - return "Construction was successful"; - case gce_ConfusedPoints: - return "Two points are coincident"; - case gce_NegativeRadius: - return "Radius value is negative"; - case gce_ColinearPoints: - return "Three points are collinear"; - case gce_IntersectionError: - return "Intersection cannot be computed"; - case gce_NullAxis: - return "Axis is undefined"; - case gce_NullAngle: - return "Angle value is invalid (usually null)"; - case gce_NullRadius: - return "Radius is null"; - case gce_InvertAxis: - return "Axis value is invalid"; - case gce_BadAngle: - return "Angle value is invalid"; - case gce_InvertRadius: - return "Radius value is incorrect (usually with respect to another radius)"; - case gce_NullFocusLength: - return "Focal distance is null"; - case gce_NullVector: - return "Vector is null"; - case gce_BadEquation: - return "Coefficients are incorrect (applies to the equation of a geometric object)"; - default: - return "Creation of geometry failed"; + switch (et) { + case gce_Done: + return "Construction was successful"; + case gce_ConfusedPoints: + return "Two points are coincident"; + case gce_NegativeRadius: + return "Radius value is negative"; + case gce_ColinearPoints: + return "Three points are collinear"; + case gce_IntersectionError: + return "Intersection cannot be computed"; + case gce_NullAxis: + return "Axis is undefined"; + case gce_NullAngle: + return "Angle value is invalid (usually null)"; + case gce_NullRadius: + return "Radius is null"; + case gce_InvertAxis: + return "Axis value is invalid"; + case gce_BadAngle: + return "Angle value is invalid"; + case gce_InvertRadius: + return "Radius value is incorrect (usually with respect to another radius)"; + case gce_NullFocusLength: + return "Focal distance is null"; + case gce_NullVector: + return "Vector is null"; + case gce_BadEquation: + return "Coefficients are incorrect (applies to the equation of a geometric object)"; + default: + return "Creation of geometry failed"; } } // --------------------------------------------------------------- -TYPESYSTEM_SOURCE_ABSTRACT(Part::Geometry,Base::Persistence) // NOLINT +TYPESYSTEM_SOURCE_ABSTRACT(Part::Geometry, Base::Persistence) // NOLINT -Geometry::Geometry() // NOLINT +Geometry::Geometry() // NOLINT { createNewTag(); } @@ -213,11 +212,11 @@ bool Geometry::hasSameExtensions(const Geometry& other) const // this will cause any problem. size_t index = 0; for (const auto& ext : extensions) { - if (auto persistExt = - freecad_cast(ext.get())) { + if (auto persistExt = freecad_cast(ext.get())) { for (; index < other.extensions.size(); ++index) { if (auto extOther = freecad_cast( - other.extensions[index].get())) { + other.extensions[index].get() + )) { if (!persistExt->isSame(*extOther)) { return false; } @@ -231,8 +230,7 @@ bool Geometry::hasSameExtensions(const Geometry& other) const } } for (; index < other.extensions.size(); ++index) { - if (freecad_cast( - other.extensions[index].get())) { + if (freecad_cast(other.extensions[index].get())) { return false; } } @@ -240,77 +238,84 @@ bool Geometry::hasSameExtensions(const Geometry& other) const } // Persistence implementer -unsigned int Geometry::getMemSize () const +unsigned int Geometry::getMemSize() const { return 1; } -std::unique_ptr Geometry::fromShape(const TopoDS_Shape &shape, bool silent) +std::unique_ptr Geometry::fromShape(const TopoDS_Shape& shape, bool silent) { std::unique_ptr geom; if (shape.IsNull()) { - if(!silent) + if (!silent) { throw Base::ValueError("Null shape"); + } return geom; } switch (shape.ShapeType()) { - case TopAbs_VERTEX: { - gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(shape)); - geom = std::make_unique(Base::Vector3d(p.X(),p.Y(),p.Z())); - break; - } - case TopAbs_EDGE: { - const TopoDS_Edge& e = TopoDS::Edge(shape); - BRepAdaptor_Curve adapt(e); - geom = makeFromCurveAdaptor(adapt, silent); - break; - } - case TopAbs_FACE: { - const TopoDS_Face& f = TopoDS::Face(shape); - BRepAdaptor_Surface adapt(f); - geom = makeFromSurfaceAdaptor(adapt, silent); - break; - } - default: - if(!silent) - FC_THROWM(Base::TypeError, "Unsupported shape type " << TopoShape::shapeName(shape.ShapeType())); + case TopAbs_VERTEX: { + gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(shape)); + geom = std::make_unique(Base::Vector3d(p.X(), p.Y(), p.Z())); + break; + } + case TopAbs_EDGE: { + const TopoDS_Edge& e = TopoDS::Edge(shape); + BRepAdaptor_Curve adapt(e); + geom = makeFromCurveAdaptor(adapt, silent); + break; + } + case TopAbs_FACE: { + const TopoDS_Face& f = TopoDS::Face(shape); + BRepAdaptor_Surface adapt(f); + geom = makeFromSurfaceAdaptor(adapt, silent); + break; + } + default: + if (!silent) { + FC_THROWM( + Base::TypeError, + "Unsupported shape type " << TopoShape::shapeName(shape.ShapeType()) + ); + } } return geom; } -void Geometry::Save(Base::Writer &writer) const +void Geometry::Save(Base::Writer& writer) const { // We always store an extension array even if empty, so that restoring is consistent. // Get the number of persistent extensions int counter = 0; - for(const auto& att : extensions) { - if(att->isDerivedFrom()) + for (const auto& att : extensions) { + if (att->isDerivedFrom()) { counter++; + } } writer.Stream() << writer.ind() << "" << std::endl; writer.incInd(); - for(const auto& att : extensions) { - if(att->isDerivedFrom()) + for (const auto& att : extensions) { + if (att->isDerivedFrom()) { std::static_pointer_cast(att)->Save(writer); + } } writer.decInd(); writer.Stream() << writer.ind() << "" << std::endl; } -void Geometry::Restore(Base::XMLReader &reader) +void Geometry::Restore(Base::XMLReader& reader) { // In legacy file format, there are no extensions and there is a construction XML tag // In the new format, this is migrated into extensions, and we get an array with extensions reader.readElement(); - if(strcmp(reader.localName(),"GeoExtensions") == 0) { // new format + if (strcmp(reader.localName(), "GeoExtensions") == 0) { // new format long count = reader.getAttribute("count"); @@ -318,7 +323,7 @@ void Geometry::Restore(Base::XMLReader &reader) reader.readElement("GeoExtension"); const char* TypeName = reader.getAttribute("type"); Base::Type type = Base::Type::fromName(TypeName); - auto *newExtension = static_cast(type.createInstance()); + auto* newExtension = static_cast(type.createInstance()); if (newExtension) { newExtension->Restore(reader); @@ -331,21 +336,22 @@ void Geometry::Restore(Base::XMLReader &reader) reader.readEndElement("GeoExtensions"); } - else if(strcmp(reader.localName(),"Construction") == 0) { // legacy + else if (strcmp(reader.localName(), "Construction") == 0) { // legacy bool construction = (int)reader.getAttribute("value") != 0; // prepare migration - if(!this->hasExtension(GeometryMigrationExtension::getClassTypeId())) + if (!this->hasExtension(GeometryMigrationExtension::getClassTypeId())) { this->setExtension(std::make_unique()); + } - auto ext = std::static_pointer_cast(this->getExtension(GeometryMigrationExtension::getClassTypeId()).lock()); + auto ext = std::static_pointer_cast( + this->getExtension(GeometryMigrationExtension::getClassTypeId()).lock() + ); ext->setMigrationType(GeometryMigrationExtension::Construction); ext->setConstruction(construction); - } - } boost::uuids::uuid Geometry::getTag() const @@ -364,96 +370,97 @@ std::vector> Geometry::getExtensions() co return wp; } -bool Geometry::hasExtension(const Base::Type & type) const +bool Geometry::hasExtension(const Base::Type& type) const { - return std::any_of(extensions.begin(), - extensions.end(), - [type](auto geoExt) { - return geoExt->getTypeId() == type; - }); + return std::any_of(extensions.begin(), extensions.end(), [type](auto geoExt) { + return geoExt->getTypeId() == type; + }); } -bool Geometry::hasExtension(const std::string & name) const +bool Geometry::hasExtension(const std::string& name) const { - return std::any_of(extensions.begin(), - extensions.end(), - [name](auto geoExt) { - return geoExt->getName() == name; - }); + return std::any_of(extensions.begin(), extensions.end(), [name](auto geoExt) { + return geoExt->getName() == name; + }); } -std::weak_ptr Geometry::getExtension(const Base::Type & type) +std::weak_ptr Geometry::getExtension(const Base::Type& type) { - for(const auto& ext : extensions) { - if(ext->getTypeId() == type) + for (const auto& ext : extensions) { + if (ext->getTypeId() == type) { return ext; + } } throw Base::ValueError("No geometry extension of the requested type."); } -std::weak_ptr Geometry::getExtension(const std::string & name) +std::weak_ptr Geometry::getExtension(const std::string& name) { - for(const auto& ext : extensions) { - if(ext->getName() == name) + for (const auto& ext : extensions) { + if (ext->getName() == name) { return ext; + } } throw Base::ValueError("No geometry extension with the requested name."); } -std::weak_ptr Geometry::getExtension(const Base::Type & type) const +std::weak_ptr Geometry::getExtension(const Base::Type& type) const { return const_cast(this)->getExtension(type).lock(); } -std::weak_ptr Geometry::getExtension(const std::string & name) const +std::weak_ptr Geometry::getExtension(const std::string& name) const { return const_cast(this)->getExtension(name).lock(); } -void Geometry::setExtension(std::unique_ptr && geoext ) +void Geometry::setExtension(std::unique_ptr&& geoext) { - bool hasext=false; + bool hasext = false; - for( auto & ext : extensions) { + for (auto& ext : extensions) { // if same type and name, this modifies the existing extension. - if( ext->getTypeId() == geoext->getTypeId() && - ext->getName() == geoext->getName()){ - ext = std::move( geoext ); + if (ext->getTypeId() == geoext->getTypeId() && ext->getName() == geoext->getName()) { + ext = std::move(geoext); ext->notifyAttachment(this); hasext = true; break; } } - if(!hasext) { // new type-name unique id, so add. - extensions.push_back(std::move( geoext )); + if (!hasext) { // new type-name unique id, so add. + extensions.push_back(std::move(geoext)); extensions.back()->notifyAttachment(this); } } -void Geometry::deleteExtension(const Base::Type & type) +void Geometry::deleteExtension(const Base::Type& type) { extensions.erase( - std::remove_if( extensions.begin(), - extensions.end(), - [&type](const std::shared_ptr& ext){ - return ext->getTypeId() == type; - }), - extensions.end()); + std::remove_if( + extensions.begin(), + extensions.end(), + [&type](const std::shared_ptr& ext) { + return ext->getTypeId() == type; + } + ), + extensions.end() + ); } -void Geometry::deleteExtension(const std::string & name) +void Geometry::deleteExtension(const std::string& name) { extensions.erase( - std::remove_if( extensions.begin(), - extensions.end(), - [&name](const std::shared_ptr& ext){ - return ext->getName() == name; - }), - extensions.end()); + std::remove_if( + extensions.begin(), + extensions.end(), + [&name](const std::shared_ptr& ext) { return ext->getName() == name; } + ), + extensions.end() + ); } @@ -477,12 +484,14 @@ void Geometry::createNewTag() tag = gen(); } -void Geometry::assignTag(const Part::Geometry * geo) +void Geometry::assignTag(const Part::Geometry* geo) { - if(geo->getTypeId() == this->getTypeId()) + if (geo->getTypeId() == this->getTypeId()) { this->tag = geo->tag; - else + } + else { throw Base::TypeError("Geometry tag can not be assigned as geometry types do not match."); + } } void Geometry::copyNonTag(const Part::Geometry* src) @@ -493,7 +502,7 @@ void Geometry::copyNonTag(const Part::Geometry* src) } } -Geometry *Geometry::clone() const +Geometry* Geometry::clone() const { Geometry* cpy = this->copy(); cpy->tag = this->tag; @@ -511,7 +520,7 @@ void Geometry::mirror(const Base::Vector3d& point) const void Geometry::mirror(const Base::Vector3d& point, const Base::Vector3d& dir) const { - gp_Ax1 ax1(gp_Pnt(point.x,point.y,point.z), gp_Dir(dir.x,dir.y,dir.z)); + gp_Ax1 ax1(gp_Pnt(point.x, point.y, point.z), gp_Dir(dir.x, dir.y, dir.z)); handle()->Mirror(ax1); } @@ -525,7 +534,7 @@ void Geometry::rotate(const Base::Placement& plm) const rot.getValue(dir, angle); pnt = plm.getPosition(); - gp_Ax1 ax1(gp_Pnt(pnt.x,pnt.y,pnt.z), gp_Dir(dir.x,dir.y,dir.z)); + gp_Ax1 ax1(gp_Pnt(pnt.x, pnt.y, pnt.z), gp_Dir(dir.x, dir.y, dir.z)); handle()->Rotate(ax1, angle); } @@ -538,9 +547,20 @@ void Geometry::scale(const Base::Vector3d& vec, double scale) const void Geometry::transform(const Base::Matrix4D& mat) const { gp_Trsf trf; - trf.SetValues(mat[0][0],mat[0][1],mat[0][2],mat[0][3], - mat[1][0],mat[1][1],mat[1][2],mat[1][3], - mat[2][0],mat[2][1],mat[2][2],mat[2][3]); + trf.SetValues( + mat[0][0], + mat[0][1], + mat[0][2], + mat[0][3], + mat[1][0], + mat[1][1], + mat[1][2], + mat[1][3], + mat[2][0], + mat[2][1], + mat[2][2], + mat[2][3] + ); handle()->Transform(trf); } @@ -553,37 +573,37 @@ void Geometry::translate(const Base::Vector3d& vec) const // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomPoint,Part::Geometry) +TYPESYSTEM_SOURCE(Part::GeomPoint, Part::Geometry) GeomPoint::GeomPoint() { - this->myPoint = new Geom_CartesianPoint(0,0,0); + this->myPoint = new Geom_CartesianPoint(0, 0, 0); } -GeomPoint::GeomPoint(const Handle(Geom_CartesianPoint)& p) +GeomPoint::GeomPoint(const Handle(Geom_CartesianPoint) & p) { setHandle(p); } GeomPoint::GeomPoint(const Base::Vector3d& p) { - this->myPoint = new Geom_CartesianPoint(p.x,p.y,p.z); + this->myPoint = new Geom_CartesianPoint(p.x, p.y, p.z); } GeomPoint::~GeomPoint() = default; -const Handle(Geom_Geometry)& GeomPoint::handle() const +const Handle(Geom_Geometry) & GeomPoint::handle() const { return myPoint; } -void GeomPoint::setHandle(const Handle(Geom_CartesianPoint)& p) +void GeomPoint::setHandle(const Handle(Geom_CartesianPoint) & p) { myPoint = Handle(Geom_CartesianPoint)::DownCast(p->Copy()); } -Geometry *GeomPoint::copy() const +Geometry* GeomPoint::copy() const { auto newPoint = new GeomPoint(myPoint); newPoint->copyNonTag(this); @@ -595,43 +615,39 @@ TopoDS_Shape GeomPoint::toShape() const return BRepBuilderAPI_MakeVertex(myPoint->Pnt()); } -Base::Vector3d GeomPoint::getPoint()const +Base::Vector3d GeomPoint::getPoint() const { - return Base::Vector3d(myPoint->X(),myPoint->Y(),myPoint->Z()); + return Base::Vector3d(myPoint->X(), myPoint->Y(), myPoint->Z()); } void GeomPoint::setPoint(const Base::Vector3d& p) { - this->myPoint->SetCoord(p.x,p.y,p.z); + this->myPoint->SetCoord(p.x, p.y, p.z); } // Persistence implementer -unsigned int GeomPoint::getMemSize () const +unsigned int GeomPoint::getMemSize() const { return sizeof(Geom_CartesianPoint); } -void GeomPoint::Save(Base::Writer &writer) const +void GeomPoint::Save(Base::Writer& writer) const { // save the attributes of the father class Geometry::Save(writer); - Base::Vector3d Point = getPoint(); - writer.Stream() - << writer.ind() - << "" << std::endl; + Base::Vector3d Point = getPoint(); + writer.Stream() << writer.ind() << "" + << std::endl; } -void GeomPoint::Restore(Base::XMLReader &reader) +void GeomPoint::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geometry::Restore(reader); - double X,Y,Z; + double X, Y, Z; // read my Element reader.readElement("GeomPoint"); // get the value of my Attribute @@ -640,23 +656,24 @@ void GeomPoint::Restore(Base::XMLReader &reader) Z = reader.getAttribute("Z"); // set the read geometry - setPoint(Base::Vector3d(X,Y,Z) ); + setPoint(Base::Vector3d(X, Y, Z)); } -PyObject *GeomPoint::getPyObject() +PyObject* GeomPoint::getPyObject() { return new PointPy(new GeomPoint(getPoint())); } -bool GeomPoint::isSame(const Geometry &other, double tol, double) const +bool GeomPoint::isSame(const Geometry& other, double tol, double) const { return other.getTypeId() == getTypeId() - && Base::DistanceP2(dynamic_cast(other).getPoint(),getPoint()) <= tol*tol; + && Base::DistanceP2(dynamic_cast(other).getPoint(), getPoint()) + <= tol * tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomCurve,Part::Geometry) +TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomCurve, Part::Geometry) GeomCurve::GeomCurve() = default; @@ -677,40 +694,37 @@ TopoDS_Shape GeomCurve::toShape() const static Standard_Boolean IsLinear(const Adaptor3d_Curve& theC) { const GeomAbs_CurveType aCT = theC.GetType(); - if(aCT == GeomAbs_OffsetCurve) - { + if (aCT == GeomAbs_OffsetCurve) { return IsLinear(GeomAdaptor_Curve(theC.OffsetCurve()->BasisCurve())); } - if((aCT == GeomAbs_BSplineCurve) || (aCT == GeomAbs_BezierCurve)) - { + if ((aCT == GeomAbs_BSplineCurve) || (aCT == GeomAbs_BezierCurve)) { // Indeed, curves with C0-continuity and degree==1, may be // represented with set of points. It will be possible made // in the future. - return ((theC.Degree() == 1) && - (theC.Continuity() != GeomAbs_C0)); + return ((theC.Degree() == 1) && (theC.Continuity() != GeomAbs_C0)); } - if(aCT == GeomAbs_Line) - { + if (aCT == GeomAbs_Line) { return Standard_True; } return Standard_False; } -bool GeomCurve::isLinear(Base::Vector3d *dir, Base::Vector3d *base) const +bool GeomCurve::isLinear(Base::Vector3d* dir, Base::Vector3d* base) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); return isLinear(curve, dir, base); } -bool GeomCurve::isLinear(const Handle(Geom_Curve) &curve, Base::Vector3d *dir, Base::Vector3d *base) +bool GeomCurve::isLinear(const Handle(Geom_Curve) & curve, Base::Vector3d* dir, Base::Vector3d* base) { GeomAdaptor_Curve adaptor(curve); - if (!IsLinear(adaptor)) + if (!IsLinear(adaptor)) { return false; + } if (dir || base) { if (adaptor.GetType() == GeomAbs_Line) { @@ -727,17 +741,19 @@ bool GeomCurve::isLinear(const Handle(Geom_Curve) &curve, Base::Vector3d *dir, B return true; } try { - GeomLProp_CLProps prop1(curve,curve->FirstParameter(),0,Precision::Confusion()); - GeomLProp_CLProps prop2(curve,curve->LastParameter(),0,Precision::Confusion()); - const gp_Pnt &p1 = prop1.Value(); - const gp_Pnt &p2 = prop2.Value(); - if (base) + GeomLProp_CLProps prop1(curve, curve->FirstParameter(), 0, Precision::Confusion()); + GeomLProp_CLProps prop2(curve, curve->LastParameter(), 0, Precision::Confusion()); + const gp_Pnt& p1 = prop1.Value(); + const gp_Pnt& p2 = prop2.Value(); + if (base) { *base = Base::Vector3d(p1.X(), p1.Y(), p1.Z()); - if (dir) + } + if (dir) { *dir = Base::Vector3d(p2.X() - p1.X(), p2.Y() - p1.Y(), p2.Z() - p1.Z()); + } } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } return true; @@ -745,12 +761,13 @@ bool GeomCurve::isLinear(const Handle(Geom_Curve) &curve, Base::Vector3d *dir, B GeomLine* GeomCurve::toLine(KeepTag clone) const { - if (!isLinear()) + if (!isLinear()) { return nullptr; + } auto p1 = pointAtParameter(getFirstParameter()); auto p2 = pointAtParameter(getLastParameter()); - auto res = new GeomLine(p1, p2-p1); + auto res = new GeomLine(p1, p2 - p1); res->copyNonTag(this); if (clone == CopyTag) { res->tag = this->tag; @@ -760,14 +777,16 @@ GeomLine* GeomCurve::toLine(KeepTag clone) const GeomLineSegment* GeomCurve::toLineSegment(KeepTag clone) const { - if (!isLinear()) + if (!isLinear()) { return nullptr; + } Base::Vector3d start, end; if (isDerivedFrom()) { start = static_cast(this)->getStartPoint(); end = static_cast(this)->getEndPoint(); - } else { + } + else { start = pointAtParameter(getFirstParameter()); end = pointAtParameter(getLastParameter()); } @@ -785,8 +804,9 @@ GeomBSplineCurve* GeomCurve::toBSpline(double first, double last) const ShapeConstruct_Curve scc; Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(handle()); Handle(Geom_BSplineCurve) spline = scc.ConvertToBSpline(c, first, last, Precision::Confusion()); - if (spline.IsNull()) - THROWM(Base::CADKernelError,"Conversion to B-spline failed") + if (spline.IsNull()) { + THROWM(Base::CADKernelError, "Conversion to B-spline failed") + } return new GeomBSplineCurve(spline); } @@ -803,7 +823,7 @@ GeomCurve* GeomCurve::createArc([[maybe_unused]] double first, [[maybe_unused]] bool GeomCurve::tangent(double u, gp_Dir& dir) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); - GeomLProp_CLProps prop(curve, u,1,Precision::Confusion()); + GeomLProp_CLProps prop(curve, u, 1, Precision::Confusion()); if (prop.IsTangentDefined()) { prop.Tangent(dir); return true; @@ -817,7 +837,7 @@ bool GeomCurve::tangent(double u, Base::Vector3d& dir) const gp_Dir gdir; if (tangent(u, gdir)) { - dir = Base::Vector3d(gdir.X(),gdir.Y(),gdir.Z()); + dir = Base::Vector3d(gdir.X(), gdir.Y(), gdir.Z()); return true; } @@ -829,39 +849,39 @@ Base::Vector3d GeomCurve::value(double u) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); - const gp_Pnt &point = curve->Value(u); + const gp_Pnt& point = curve->Value(u); - return Base::Vector3d(point.X(),point.Y(),point.Z()); + return Base::Vector3d(point.X(), point.Y(), point.Z()); } Base::Vector3d GeomCurve::pointAtParameter(double u) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); - GeomLProp_CLProps prop(curve, u,0,Precision::Confusion()); + GeomLProp_CLProps prop(curve, u, 0, Precision::Confusion()); - const gp_Pnt &point=prop.Value(); + const gp_Pnt& point = prop.Value(); - return Base::Vector3d(point.X(),point.Y(),point.Z()); + return Base::Vector3d(point.X(), point.Y(), point.Z()); } Base::Vector3d GeomCurve::firstDerivativeAtParameter(double u) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); - GeomLProp_CLProps prop(curve, u,1,Precision::Confusion()); + GeomLProp_CLProps prop(curve, u, 1, Precision::Confusion()); - const gp_Vec &vec=prop.D1(); + const gp_Vec& vec = prop.D1(); - return Base::Vector3d(vec.X(),vec.Y(),vec.Z()); + return Base::Vector3d(vec.X(), vec.Y(), vec.Z()); } Base::Vector3d GeomCurve::secondDerivativeAtParameter(double u) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); - GeomLProp_CLProps prop(curve, u,2,Precision::Confusion()); + GeomLProp_CLProps prop(curve, u, 2, Precision::Confusion()); - const gp_Vec &vec=prop.D2(); + const gp_Vec& vec = prop.D2(); - return Base::Vector3d(vec.X(),vec.Y(),vec.Z()); + return Base::Vector3d(vec.X(), vec.Y(), vec.Z()); } bool GeomCurve::normalAt(double u, Base::Vector3d& dir) const @@ -870,7 +890,7 @@ bool GeomCurve::normalAt(double u, Base::Vector3d& dir) const try { if (!curve.IsNull()) { - GeomLProp_CLProps prop(curve, u,2,Precision::Confusion()); + GeomLProp_CLProps prop(curve, u, 2, Precision::Confusion()); gp_Dir gdir; prop.Normal(gdir); dir = Base::Vector3d(gdir.X(), gdir.Y(), gdir.Z()); @@ -879,7 +899,7 @@ bool GeomCurve::normalAt(double u, Base::Vector3d& dir) const } } catch (const LProp_NotDefined&) { - dir.Set(0,0,0); + dir.Set(0, 0, 0); return false; } catch (Standard_Failure& exc) { @@ -889,7 +909,7 @@ bool GeomCurve::normalAt(double u, Base::Vector3d& dir) const return false; } -bool GeomCurve::normalAt(const Base::Vector3d & curvepoint, Base::Vector3d & dir) const +bool GeomCurve::normalAt(const Base::Vector3d& curvepoint, Base::Vector3d& dir) const { double u; closestParameter(curvepoint, u); @@ -897,28 +917,33 @@ bool GeomCurve::normalAt(const Base::Vector3d & curvepoint, Base::Vector3d & dir return normalAt(u, dir); } -bool GeomCurve::intersect( const GeomCurve *curve, - std::vector>& points, - double tol) const +bool GeomCurve::intersect( + const GeomCurve* curve, + std::vector>& points, + double tol +) const { Handle(Geom_Curve) curve1 = Handle(Geom_Curve)::DownCast(handle()); Handle(Geom_Curve) curve2 = Handle(Geom_Curve)::DownCast(curve->handle()); - if(!curve1.IsNull() && !curve2.IsNull()) { - return intersect(curve1,curve2,points, tol); + if (!curve1.IsNull() && !curve2.IsNull()) { + return intersect(curve1, curve2, points, tol); } - else + else { return false; - + } } -bool GeomCurve::intersect(const Handle(Geom_Curve)& curve1, const Handle(Geom_Curve)& curve2, - std::vector>& points, - double tol) +bool GeomCurve::intersect( + const Handle(Geom_Curve) & curve1, + const Handle(Geom_Curve) & curve2, + std::vector>& points, + double tol +) { // https://forum.freecad.org/viewtopic.php?f=10&t=31700 - if (curve1->IsKind(STANDARD_TYPE(Geom_BoundedCurve)) && - curve2->IsKind(STANDARD_TYPE(Geom_BoundedCurve))){ + if (curve1->IsKind(STANDARD_TYPE(Geom_BoundedCurve)) + && curve2->IsKind(STANDARD_TYPE(Geom_BoundedCurve))) { Handle(Geom_BoundedCurve) bcurve1 = Handle(Geom_BoundedCurve)::DownCast(curve1); Handle(Geom_BoundedCurve) bcurve2 = Handle(Geom_BoundedCurve)::DownCast(curve2); @@ -928,16 +953,19 @@ bool GeomCurve::intersect(const Handle(Geom_Curve)& curve1, const Handle(Geom_Cu gp_Pnt c1e = bcurve1->EndPoint(); gp_Pnt c2e = bcurve2->EndPoint(); - auto checkendpoints = [&points,tol]( gp_Pnt p1, gp_Pnt p2) { - if(p1.Distance(p2) < tol) - points.emplace_back(Base::Vector3d(p1.X(),p1.Y(),p1.Z()),Base::Vector3d(p2.X(),p2.Y(),p2.Z())); + auto checkendpoints = [&points, tol](gp_Pnt p1, gp_Pnt p2) { + if (p1.Distance(p2) < tol) { + points.emplace_back( + Base::Vector3d(p1.X(), p1.Y(), p1.Z()), + Base::Vector3d(p2.X(), p2.Y(), p2.Z()) + ); + } }; - checkendpoints(c1s,c2s); - checkendpoints(c1s,c2e); - checkendpoints(c1e,c2s); - checkendpoints(c1e,c2e); - + checkendpoints(c1s, c2s); + checkendpoints(c1s, c2e); + checkendpoints(c1e, c2s); + checkendpoints(c1e, c2e); } try { @@ -950,49 +978,58 @@ bool GeomCurve::intersect(const Handle(Geom_Curve)& curve1, const Handle(Geom_Cu } for (int index = 1; index <= intersector.NbExtrema(); index++) { - if (intersector.Distance(index) > tol) + if (intersector.Distance(index) > tol) { continue; + } gp_Pnt p1, p2; intersector.Points(index, p1, p2); - points.emplace_back(Base::Vector3d(p1.X(),p1.Y(),p1.Z()),Base::Vector3d(p2.X(),p2.Y(),p2.Z())); + points.emplace_back( + Base::Vector3d(p1.X(), p1.Y(), p1.Z()), + Base::Vector3d(p2.X(), p2.Y(), p2.Z()) + ); } } catch (Standard_Failure& exc) { // Yes Extrema finding failed, but if we got an intersection then go on with it - if(!points.empty()) + if (!points.empty()) { return !points.empty(); - else - THROWM(Base::CADKernelError,exc.GetMessageString()) + } + else { + THROWM(Base::CADKernelError, exc.GetMessageString()) + } } return !points.empty(); } -bool GeomCurve::closestParameter(const Base::Vector3d& point, double &u) const +bool GeomCurve::closestParameter(const Base::Vector3d& point, double& u) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); try { if (!curve.IsNull()) { - gp_Pnt pnt(point.x,point.y,point.z); + gp_Pnt pnt(point.x, point.y, point.z); GeomAPI_ProjectPointOnCurve ppc(pnt, curve); u = ppc.LowerDistanceParameter(); return true; } } catch (StdFail_NotDone& exc) { - if (curve->IsKind(STANDARD_TYPE(Geom_BoundedCurve))){ + if (curve->IsKind(STANDARD_TYPE(Geom_BoundedCurve))) { Base::Vector3d firstpoint = this->pointAtParameter(curve->FirstParameter()); Base::Vector3d lastpoint = this->pointAtParameter(curve->LastParameter()); - if((firstpoint-point).Length() < (lastpoint-point).Length()) + if ((firstpoint - point).Length() < (lastpoint - point).Length()) { u = curve->FirstParameter(); - else + } + else { u = curve->LastParameter(); + } } - else + else { THROWM(Base::CADKernelError, exc.GetMessageString()) + } return true; } @@ -1003,16 +1040,16 @@ bool GeomCurve::closestParameter(const Base::Vector3d& point, double &u) const return false; } -bool GeomCurve::closestParameterToBasisCurve(const Base::Vector3d& point, double &u) const +bool GeomCurve::closestParameterToBasisCurve(const Base::Vector3d& point, double& u) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); - if (curve->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))){ + if (curve->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) { Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Curve) bc = tc->BasisCurve(); try { if (!bc.IsNull()) { - gp_Pnt pnt(point.x,point.y,point.z); + gp_Pnt pnt(point.x, point.y, point.z); GeomAPI_ProjectPointOnCurve ppc(pnt, bc); u = ppc.LowerDistanceParameter(); return true; @@ -1062,7 +1099,7 @@ double GeomCurve::curvatureAt(double u) const Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(handle()); try { - GeomLProp_CLProps prop(curve, u,2,Precision::Confusion()); + GeomLProp_CLProps prop(curve, u, 2, Precision::Confusion()); return prop.Curvature(); } catch (Standard_Failure& exc) { @@ -1078,7 +1115,7 @@ double GeomCurve::length(double u, double v) const try { GeomAdaptor_Curve adaptor(curve); - return GCPnts_AbscissaPoint::Length(adaptor,u,v,Precision::Confusion()); + return GCPnts_AbscissaPoint::Length(adaptor, u, v, Precision::Confusion()); } catch (Standard_Failure& exc) { @@ -1110,7 +1147,7 @@ GeomBoundedCurve::~GeomBoundedCurve() = default; Base::Vector3d GeomBoundedCurve::getStartPoint() const { - Handle(Geom_BoundedCurve) curve = Handle(Geom_BoundedCurve)::DownCast(handle()); + Handle(Geom_BoundedCurve) curve = Handle(Geom_BoundedCurve)::DownCast(handle()); gp_Pnt pnt = curve->StartPoint(); return Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()); @@ -1118,7 +1155,7 @@ Base::Vector3d GeomBoundedCurve::getStartPoint() const Base::Vector3d GeomBoundedCurve::getEndPoint() const { - Handle(Geom_BoundedCurve) curve = Handle(Geom_BoundedCurve)::DownCast(handle()); + Handle(Geom_BoundedCurve) curve = Handle(Geom_BoundedCurve)::DownCast(handle()); gp_Pnt pnt = curve->EndPoint(); return Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()); @@ -1131,47 +1168,51 @@ TYPESYSTEM_SOURCE(Part::GeomBezierCurve, Part::GeomBoundedCurve) GeomBezierCurve::GeomBezierCurve() { - TColgp_Array1OfPnt poles(1,2); - poles(1) = gp_Pnt(0.0,0.0,0.0); - poles(2) = gp_Pnt(0.0,0.0,1.0); + TColgp_Array1OfPnt poles(1, 2); + poles(1) = gp_Pnt(0.0, 0.0, 0.0); + poles(2) = gp_Pnt(0.0, 0.0, 1.0); Handle(Geom_BezierCurve) bezier = new Geom_BezierCurve(poles); this->myCurve = bezier; } -GeomBezierCurve::GeomBezierCurve(const Handle(Geom_BezierCurve)& bezier) +GeomBezierCurve::GeomBezierCurve(const Handle(Geom_BezierCurve) & bezier) { setHandle(bezier); } -GeomBezierCurve::GeomBezierCurve( const std::vector& poles, const std::vector& weights) +GeomBezierCurve::GeomBezierCurve( + const std::vector& poles, + const std::vector& weights +) { - if (poles.size() != weights.size()) + if (poles.size() != weights.size()) { throw Base::ValueError("poles and weights mismatch"); - - TColgp_Array1OfPnt poleArray(1,poles.size()); - TColStd_Array1OfReal weightArray(1,poles.size()); - for (std::size_t index = 1; index <= poles.size(); index++) { - poleArray.SetValue(index, gp_Pnt(poles[index-1].x,poles[index-1].y,poles[index-1].z)); - weightArray.SetValue(index, weights[index-1]); } - this->myCurve = new Geom_BezierCurve (poleArray, weightArray); + + TColgp_Array1OfPnt poleArray(1, poles.size()); + TColStd_Array1OfReal weightArray(1, poles.size()); + for (std::size_t index = 1; index <= poles.size(); index++) { + poleArray.SetValue(index, gp_Pnt(poles[index - 1].x, poles[index - 1].y, poles[index - 1].z)); + weightArray.SetValue(index, weights[index - 1]); + } + this->myCurve = new Geom_BezierCurve(poleArray, weightArray); } GeomBezierCurve::~GeomBezierCurve() = default; -void GeomBezierCurve::setHandle(const Handle(Geom_BezierCurve)& curve) +void GeomBezierCurve::setHandle(const Handle(Geom_BezierCurve) & curve) { myCurve = Handle(Geom_BezierCurve)::DownCast(curve->Copy()); } -const Handle(Geom_Geometry)& GeomBezierCurve::handle() const +const Handle(Geom_Geometry) & GeomBezierCurve::handle() const { return myCurve; } -Geometry *GeomBezierCurve::copy() const +Geometry* GeomBezierCurve::copy() const { - auto *newCurve = new GeomBezierCurve(myCurve); + auto* newCurve = new GeomBezierCurve(myCurve); newCurve->copyNonTag(this); return newCurve; } @@ -1180,10 +1221,10 @@ std::vector GeomBezierCurve::getPoles() const { std::vector poles; poles.reserve(myCurve->NbPoles()); - TColgp_Array1OfPnt poleArray(1,myCurve->NbPoles()); + TColgp_Array1OfPnt poleArray(1, myCurve->NbPoles()); myCurve->Poles(poleArray); - for (Standard_Integer index=poleArray.Lower(); index<=poleArray.Upper(); index++) { + for (Standard_Integer index = poleArray.Lower(); index <= poleArray.Upper(); index++) { const gp_Pnt& pnt = poleArray(index); poles.emplace_back(pnt.X(), pnt.Y(), pnt.Z()); } @@ -1194,10 +1235,10 @@ std::vector GeomBezierCurve::getWeights() const { std::vector weights; weights.reserve(myCurve->NbPoles()); - TColStd_Array1OfReal weightArray(1,myCurve->NbPoles()); + TColStd_Array1OfReal weightArray(1, myCurve->NbPoles()); myCurve->Weights(weightArray); - for (Standard_Integer index=weightArray.Lower(); index<=weightArray.Upper(); index++) { + for (Standard_Integer index = weightArray.Lower(); index <= weightArray.Upper(); index++) { const Standard_Real& real = weightArray(index); weights.push_back(real); } @@ -1205,7 +1246,7 @@ std::vector GeomBezierCurve::getWeights() const } // Persistence implementer -unsigned int GeomBezierCurve::getMemSize () const +unsigned int GeomBezierCurve::getMemSize() const { return sizeof(Geom_BezierCurve); } @@ -1215,33 +1256,26 @@ void GeomBezierCurve::Save(Base::Writer& writer) const // save the attributes of the father class GeomCurve::Save(writer); - std::vector poles = this->getPoles(); - std::vector weights = this->getWeights(); + std::vector poles = this->getPoles(); + std::vector weights = this->getWeights(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; writer.incInd(); std::vector::const_iterator itp; std::vector::const_iterator itw; - for (itp = poles.begin(), itw = weights.begin(); itp != poles.end() && itw != weights.end(); ++itp, ++itw) { - writer.Stream() - << writer.ind() - << "" << std::endl; + for (itp = poles.begin(), itw = weights.begin(); itp != poles.end() && itw != weights.end(); + ++itp, ++itw) { + writer.Stream() << writer.ind() << "" << std::endl; } writer.decInd(); - writer.Stream() << writer.ind() << "" << std::endl ; + writer.Stream() << writer.ind() << "" << std::endl; } void GeomBezierCurve::Restore(Base::XMLReader& reader) @@ -1253,8 +1287,8 @@ void GeomBezierCurve::Restore(Base::XMLReader& reader) // get the value of my attribute int polescount = reader.getAttribute("PolesCount"); - TColgp_Array1OfPnt poleArray(1,polescount); - TColStd_Array1OfReal weightArray(1,polescount); + TColgp_Array1OfPnt poleArray(1, polescount); + TColStd_Array1OfReal weightArray(1, polescount); for (int index = 1; index <= polescount; index++) { reader.readElement("Pole"); @@ -1262,7 +1296,7 @@ void GeomBezierCurve::Restore(Base::XMLReader& reader) double Y = reader.getAttribute("Y"); double Z = reader.getAttribute("Z"); double W = reader.getAttribute("Weight"); - poleArray.SetValue(index, gp_Pnt(X,Y,Z)); + poleArray.SetValue(index, gp_Pnt(X, Y, Z)); weightArray.SetValue(index, W); } @@ -1271,10 +1305,12 @@ void GeomBezierCurve::Restore(Base::XMLReader& reader) try { Handle(Geom_BezierCurve) bezier = new Geom_BezierCurve(poleArray, weightArray); - if (!bezier.IsNull()) + if (!bezier.IsNull()) { this->myCurve = bezier; - else - THROWM(Base::CADKernelError,"BezierCurve restore failed") + } + else { + THROWM(Base::CADKernelError, "BezierCurve restore failed") + } } catch (Standard_Failure& exc) { @@ -1282,103 +1318,121 @@ void GeomBezierCurve::Restore(Base::XMLReader& reader) } } -PyObject *GeomBezierCurve::getPyObject() +PyObject* GeomBezierCurve::getPyObject() { return new BezierCurvePy(freecad_cast(this->clone())); } -bool GeomBezierCurve::isSame(const Geometry &_other, double tol, double) const +bool GeomBezierCurve::isSame(const Geometry& _other, double tol, double) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = dynamic_cast(_other); + auto& other = dynamic_cast(_other); Standard_Integer c = myCurve->NbPoles(); - if(c!= other.myCurve->NbPoles()) + if (c != other.myCurve->NbPoles()) { return false; + } - double tol2 = tol*tol; - for(Standard_Integer index =1; index <=c; ++index) { - if(myCurve->Pole(index).SquareDistance(other.myCurve->Pole(index)) > tol2 - || fabs(myCurve->Weight(index) - other.myCurve->Weight(index)) > tol) + double tol2 = tol * tol; + for (Standard_Integer index = 1; index <= c; ++index) { + if (myCurve->Pole(index).SquareDistance(other.myCurve->Pole(index)) > tol2 + || fabs(myCurve->Weight(index) - other.myCurve->Weight(index)) > tol) { return false; + } } return true; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomBSplineCurve,Part::GeomBoundedCurve) +TYPESYSTEM_SOURCE(Part::GeomBSplineCurve, Part::GeomBoundedCurve) GeomBSplineCurve::GeomBSplineCurve() { - TColgp_Array1OfPnt poles(1,2); - poles(1) = gp_Pnt(0.0,0.0,0.0); - poles(2) = gp_Pnt(1.0,0.0,0.0); + TColgp_Array1OfPnt poles(1, 2); + poles(1) = gp_Pnt(0.0, 0.0, 0.0); + poles(2) = gp_Pnt(1.0, 0.0, 0.0); - TColStd_Array1OfReal knots(1,2); + TColStd_Array1OfReal knots(1, 2); knots(1) = 0.0; knots(2) = 1.0; - TColStd_Array1OfInteger mults(1,2); + TColStd_Array1OfInteger mults(1, 2); mults(1) = 2; mults(2) = 2; this->myCurve = new Geom_BSplineCurve(poles, knots, mults, 1); } -GeomBSplineCurve::GeomBSplineCurve(const Handle(Geom_BSplineCurve)& b) +GeomBSplineCurve::GeomBSplineCurve(const Handle(Geom_BSplineCurve) & b) { setHandle(b); } -GeomBSplineCurve::GeomBSplineCurve( const std::vector& poles, const std::vector& weights, - const std::vector& knots, const std::vector& multiplicities, - int degree, bool periodic, bool checkrational) +GeomBSplineCurve::GeomBSplineCurve( + const std::vector& poles, + const std::vector& weights, + const std::vector& knots, + const std::vector& multiplicities, + int degree, + bool periodic, + bool checkrational +) { - if (poles.size() != weights.size()) + if (poles.size() != weights.size()) { throw Base::ValueError("poles and weights mismatch"); + } - if (knots.size() != multiplicities.size()) + if (knots.size() != multiplicities.size()) { throw Base::ValueError("knots and multiplicities mismatch"); + } - TColgp_Array1OfPnt p(1,poles.size()); - TColStd_Array1OfReal w(1,poles.size()); - TColStd_Array1OfReal k(1,knots.size()); - TColStd_Array1OfInteger m(1,knots.size()); + TColgp_Array1OfPnt p(1, poles.size()); + TColStd_Array1OfReal w(1, poles.size()); + TColStd_Array1OfReal k(1, knots.size()); + TColStd_Array1OfInteger m(1, knots.size()); for (std::size_t index = 1; index <= poles.size(); index++) { - p.SetValue(index, gp_Pnt(poles[index -1].x,poles[index -1].y,poles[index -1].z)); - w.SetValue(index, weights[index -1]); + p.SetValue(index, gp_Pnt(poles[index - 1].x, poles[index - 1].y, poles[index - 1].z)); + w.SetValue(index, weights[index - 1]); } for (std::size_t index = 1; index <= knots.size(); index++) { - k.SetValue(index, knots[index -1]); - m.SetValue(index, multiplicities[index -1]); + k.SetValue(index, knots[index - 1]); + m.SetValue(index, multiplicities[index - 1]); } - this->myCurve = new Geom_BSplineCurve (p, w, k, m, degree, periodic?Standard_True:Standard_False, checkrational?Standard_True:Standard_False); - + this->myCurve = new Geom_BSplineCurve( + p, + w, + k, + m, + degree, + periodic ? Standard_True : Standard_False, + checkrational ? Standard_True : Standard_False + ); } GeomBSplineCurve::~GeomBSplineCurve() = default; -void GeomBSplineCurve::setHandle(const Handle(Geom_BSplineCurve)& curve) +void GeomBSplineCurve::setHandle(const Handle(Geom_BSplineCurve) & curve) { myCurve = Handle(Geom_BSplineCurve)::DownCast(curve->Copy()); } -const Handle(Geom_Geometry)& GeomBSplineCurve::handle() const +const Handle(Geom_Geometry) & GeomBSplineCurve::handle() const { return myCurve; } -Geometry *GeomBSplineCurve::copy() const +Geometry* GeomBSplineCurve::copy() const { try { - auto *newCurve = new GeomBSplineCurve(myCurve); + auto* newCurve = new GeomBSplineCurve(myCurve); newCurve->copyNonTag(this); return newCurve; } @@ -1389,10 +1443,10 @@ Geometry *GeomBSplineCurve::copy() const GeomCurve* GeomBSplineCurve::createArc(double first, double last) const { - auto newBsp = static_cast(this->copy()); - newBsp->Trim(first, last); + auto newBsp = static_cast(this->copy()); + newBsp->Trim(first, last); - return newBsp; + return newBsp; } int GeomBSplineCurve::countPoles() const @@ -1408,14 +1462,16 @@ int GeomBSplineCurve::countKnots() const void GeomBSplineCurve::setPole(int index, const Base::Vector3d& pole, double weight) { try { - gp_Pnt pnt(pole.x,pole.y,pole.z); - if (weight < 0.0) - myCurve->SetPole(index,pnt); - else - myCurve->SetPole(index,pnt,weight); + gp_Pnt pnt(pole.x, pole.y, pole.z); + if (weight < 0.0) { + myCurve->SetPole(index, pnt); + } + else { + myCurve->SetPole(index, pnt, weight); + } } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -1433,25 +1489,31 @@ void GeomBSplineCurve::workAroundOCCTBug(const std::vector& weights) // to 1.0 (nonrational b-splines have 1.0 weights). This may lead to the assignment of wrong // of weight values. // - // Little hack is to set the last weight to a value different from last but one current and to-be-assigned + // Little hack is to set the last weight to a value different from last but one current and + // to-be-assigned - if (weights.size() < 2) // at least two poles/weights + if (weights.size() < 2) { // at least two poles/weights return; + } - auto lastindex = myCurve->NbPoles(); // OCCT is base-1 - auto lastbutonevalue = myCurve->Weight(lastindex-1); - double fakelastvalue = lastbutonevalue + weights[weights.size()-2]; - myCurve->SetWeight(weights.size(),fakelastvalue); + auto lastindex = myCurve->NbPoles(); // OCCT is base-1 + auto lastbutonevalue = myCurve->Weight(lastindex - 1); + double fakelastvalue = lastbutonevalue + weights[weights.size() - 2]; + myCurve->SetWeight(weights.size(), fakelastvalue); } -void GeomBSplineCurve::setPoles(const std::vector& poles, const std::vector& weights) +void GeomBSplineCurve::setPoles( + const std::vector& poles, + const std::vector& weights +) { - if (poles.size() != weights.size()) + if (poles.size() != weights.size()) { throw Base::ValueError("poles and weights mismatch"); + } workAroundOCCTBug(weights); - Standard_Integer index=1; + Standard_Integer index = 1; for (std::size_t i = 0; i < poles.size(); i++, index++) { setPole(index, poles[i], weights[i]); @@ -1460,9 +1522,9 @@ void GeomBSplineCurve::setPoles(const std::vector& poles, const void GeomBSplineCurve::setPoles(const std::vector& poles) { - Standard_Integer index=1; + Standard_Integer index = 1; - for (auto it = poles.begin(); it != poles.end(); ++it, index++){ + for (auto it = poles.begin(); it != poles.end(); ++it, index++) { setPole(index, *it); } } @@ -1471,10 +1533,10 @@ std::vector GeomBSplineCurve::getPoles() const { std::vector poles; poles.reserve(myCurve->NbPoles()); - TColgp_Array1OfPnt p(1,myCurve->NbPoles()); + TColgp_Array1OfPnt p(1, myCurve->NbPoles()); myCurve->Poles(p); - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { const gp_Pnt& pnt = p(i); poles.emplace_back(pnt.X(), pnt.Y(), pnt.Z()); } @@ -1485,10 +1547,10 @@ std::vector GeomBSplineCurve::getWeights() const { std::vector weights; weights.reserve(myCurve->NbPoles()); - TColStd_Array1OfReal w(1,myCurve->NbPoles()); + TColStd_Array1OfReal w(1, myCurve->NbPoles()); myCurve->Weights(w); - for (Standard_Integer i=w.Lower(); i<=w.Upper(); i++) { + for (Standard_Integer i = w.Lower(); i <= w.Upper(); i++) { const Standard_Real& real = w(i); weights.push_back(real); } @@ -1500,35 +1562,37 @@ void GeomBSplineCurve::setWeights(const std::vector& weights) workAroundOCCTBug(weights); try { - Standard_Integer index=1; + Standard_Integer index = 1; - for (auto it = weights.begin(); it != weights.end(); ++it, index++){ + for (auto it = weights.begin(); it != weights.end(); ++it, index++) { myCurve->SetWeight(index, *it); } } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } void GeomBSplineCurve::setKnot(int index, const double val, int mult) { try { - if (mult < 0) + if (mult < 0) { myCurve->SetKnot(index, val); - else + } + else { myCurve->SetKnot(index, val, mult); + } } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } void GeomBSplineCurve::setKnots(const std::vector& knots) { - Standard_Integer index=1; + Standard_Integer index = 1; for (auto it = knots.begin(); it != knots.end(); ++it, index++) { setKnot(index, *it); @@ -1537,10 +1601,11 @@ void GeomBSplineCurve::setKnots(const std::vector& knots) void GeomBSplineCurve::setKnots(const std::vector& knots, const std::vector& multiplicities) { - if (knots.size() != multiplicities.size()) + if (knots.size() != multiplicities.size()) { throw Base::ValueError("knots and multiplicities mismatch"); + } - Standard_Integer index=1; + Standard_Integer index = 1; for (std::size_t it = 0; it < knots.size(); it++, index++) { setKnot(index, knots[it], multiplicities[it]); @@ -1551,10 +1616,10 @@ std::vector GeomBSplineCurve::getKnots() const { std::vector knots; knots.reserve(myCurve->NbKnots()); - TColStd_Array1OfReal k(1,myCurve->NbKnots()); + TColStd_Array1OfReal k(1, myCurve->NbKnots()); myCurve->Knots(k); - for (Standard_Integer i=k.Lower(); i<=k.Upper(); i++) { + for (Standard_Integer i = k.Lower(); i <= k.Upper(); i++) { const Standard_Real& real = k(i); knots.push_back(real); } @@ -1565,10 +1630,10 @@ std::vector GeomBSplineCurve::getMultiplicities() const { std::vector mults; mults.reserve(myCurve->NbKnots()); - TColStd_Array1OfInteger m(1,myCurve->NbKnots()); + TColStd_Array1OfInteger m(1, myCurve->NbKnots()); myCurve->Multiplicities(m); - for (Standard_Integer i=m.Lower(); i<=m.Upper(); i++) { + for (Standard_Integer i = m.Lower(); i <= m.Upper(); i++) { const Standard_Integer& nm = m(i); mults.push_back(nm); } @@ -1582,7 +1647,7 @@ int GeomBSplineCurve::getMultiplicity(int index) const } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -1593,7 +1658,7 @@ int GeomBSplineCurve::getDegree() const bool GeomBSplineCurve::isPeriodic() const { - return myCurve->IsPeriodic()==Standard_True; + return myCurve->IsPeriodic() == Standard_True; } void GeomBSplineCurve::setPeriodic() const @@ -1603,27 +1668,29 @@ void GeomBSplineCurve::setPeriodic() const bool GeomBSplineCurve::isRational() const { - return myCurve->IsRational()==Standard_True; + return myCurve->IsRational() == Standard_True; } -bool GeomBSplineCurve::join(const Handle(Geom_BoundedCurve)& other) +bool GeomBSplineCurve::join(const Handle(Geom_BoundedCurve) & other) { GeomConvert_CompCurveToBSplineCurve ccbc(this->myCurve); - if (!ccbc.Add(other, Precision::Approximation())) + if (!ccbc.Add(other, Precision::Approximation())) { return false; + } this->myCurve = ccbc.BSplineCurve(); return true; } void GeomBSplineCurve::interpolate(const std::vector& p, Standard_Boolean periodic) { - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); + } double tol3d = Precision::Approximation(); Handle(TColgp_HArray1OfPnt) pts = new TColgp_HArray1OfPnt(1, p.size()); - for (std::size_t i=0; iSetValue(i+1, p[i]); + for (std::size_t i = 0; i < p.size(); i++) { + pts->SetValue(i + 1, p[i]); } GeomAPI_Interpolate interpolate(pts, periodic, tol3d); @@ -1631,25 +1698,26 @@ void GeomBSplineCurve::interpolate(const std::vector& p, Standard_Boolea this->myCurve = interpolate.Curve(); } -void GeomBSplineCurve::interpolate(const std::vector& p, - const std::vector& t) +void GeomBSplineCurve::interpolate(const std::vector& p, const std::vector& t) { - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); - if (p.size() != t.size()) + } + if (p.size() != t.size()) { Standard_ConstructionError::Raise(); + } double tol3d = Precision::Approximation(); Handle(TColgp_HArray1OfPnt) pts = new TColgp_HArray1OfPnt(1, p.size()); - for (std::size_t i=0; iSetValue(i+1, p[i]); + for (std::size_t i = 0; i < p.size(); i++) { + pts->SetValue(i + 1, p[i]); } TColgp_Array1OfVec tgs(1, t.size()); Handle(TColStd_HArray1OfBoolean) fgs = new TColStd_HArray1OfBoolean(1, t.size()); - for (std::size_t i=0; iSetValue(i+1, Standard_True); + for (std::size_t i = 0; i < p.size(); i++) { + tgs.SetValue(i + 1, t[i]); + fgs->SetValue(i + 1, Standard_True); } GeomAPI_Interpolate interpolate(pts, Standard_False, tol3d); @@ -1658,15 +1726,19 @@ void GeomBSplineCurve::interpolate(const std::vector& p, this->myCurve = interpolate.Curve(); } -void GeomBSplineCurve::getCardinalSplineTangents(const std::vector& p, - const std::vector& c, - std::vector& t) const +void GeomBSplineCurve::getCardinalSplineTangents( + const std::vector& p, + const std::vector& c, + std::vector& t +) const { // https://de.wikipedia.org/wiki/Kubisch_Hermitescher_Spline#Cardinal_Spline - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); - if (p.size() != c.size()) + } + if (p.size() != c.size()) { Standard_ConstructionError::Raise(); + } t.resize(p.size()); if (p.size() == 2) { @@ -1677,23 +1749,27 @@ void GeomBSplineCurve::getCardinalSplineTangents(const std::vector& p, std::size_t e = p.size() - 1; for (std::size_t i = 1; i < e; i++) { - gp_Vec v = gp_Vec(p[i-1], p[i+1]); - double f = 0.5 * (1-c[i]); + gp_Vec v = gp_Vec(p[i - 1], p[i + 1]); + double f = 0.5 * (1 - c[i]); v.Scale(f); t[i] = v; } t[0] = t[1]; - t[t.size()-1] = t[t.size()-2]; + t[t.size() - 1] = t[t.size() - 2]; } } -void GeomBSplineCurve::getCardinalSplineTangents(const std::vector& p, double c, - std::vector& t) const +void GeomBSplineCurve::getCardinalSplineTangents( + const std::vector& p, + double c, + std::vector& t +) const { // https://de.wikipedia.org/wiki/Kubisch_Hermitescher_Spline#Cardinal_Spline - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); + } t.resize(p.size()); if (p.size() == 2) { @@ -1702,16 +1778,16 @@ void GeomBSplineCurve::getCardinalSplineTangents(const std::vector& p, d } else { std::size_t e = p.size() - 1; - double f = 0.5 * (1-c); + double f = 0.5 * (1 - c); for (std::size_t i = 1; i < e; i++) { - gp_Vec v = gp_Vec(p[i-1], p[i+1]); + gp_Vec v = gp_Vec(p[i - 1], p[i + 1]); v.Scale(f); t[i] = v; } t[0] = t[1]; - t[t.size()-1] = t[t.size()-2]; + t[t.size() - 1] = t[t.size() - 2]; } } @@ -1727,7 +1803,7 @@ void GeomBSplineCurve::increaseDegree(int degree) curve->IncreaseDegree(degree); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -1738,8 +1814,7 @@ void GeomBSplineCurve::increaseDegree(int degree) * \param maxDegree * \param continuity */ -void GeomBSplineCurve::approximate(double tol3d, int maxSegments, int maxDegree, - GeomAbs_Shape continuity) +void GeomBSplineCurve::approximate(double tol3d, int maxSegments, int maxDegree, GeomAbs_Shape continuity) { try { GeomAdaptor_Curve adapt(myCurve); @@ -1760,9 +1835,13 @@ void GeomBSplineCurve::approximate(double tol3d, int maxSegments, int maxDegree, } } -void GeomBSplineCurve::approximate(const std::vector& pnts, - int minDegree, int maxDegree, - GeomAbs_Shape continuity, double tol3d) +void GeomBSplineCurve::approximate( + const std::vector& pnts, + int minDegree, + int maxDegree, + GeomAbs_Shape continuity, + double tol3d +) { try { TColgp_Array1OfPnt coords(1, static_cast(pnts.size())); @@ -1772,7 +1851,7 @@ void GeomBSplineCurve::approximate(const std::vector& pnts, } GeomAPI_PointsToBSpline fit(coords, minDegree, maxDegree, continuity, tol3d); - const Handle(Geom_BSplineCurve)& spline = fit.Curve(); + const Handle(Geom_BSplineCurve) & spline = fit.Curve(); if (!spline.IsNull()) { setHandle(spline); } @@ -1785,10 +1864,14 @@ void GeomBSplineCurve::approximate(const std::vector& pnts, } } -void GeomBSplineCurve::approximate(const std::vector& pnts, - Approx_ParametrizationType parType, - int minDegree, int maxDegree, - GeomAbs_Shape continuity, double tol3d) +void GeomBSplineCurve::approximate( + const std::vector& pnts, + Approx_ParametrizationType parType, + int minDegree, + int maxDegree, + GeomAbs_Shape continuity, + double tol3d +) { try { TColgp_Array1OfPnt coords(1, static_cast(pnts.size())); @@ -1798,7 +1881,7 @@ void GeomBSplineCurve::approximate(const std::vector& pnts, } GeomAPI_PointsToBSpline fit(coords, parType, minDegree, maxDegree, continuity, tol3d); - const Handle(Geom_BSplineCurve)& spline = fit.Curve(); + const Handle(Geom_BSplineCurve) & spline = fit.Curve(); if (!spline.IsNull()) { setHandle(spline); } @@ -1822,9 +1905,15 @@ void GeomBSplineCurve::approximate(const std::vector& pnts, * \param continuity Continuity of the spline * \param tol3d Tolerance to the data points */ -void GeomBSplineCurve::approximate(const std::vector& pnts, - double weight1, double weight2, double weight3, - int maxDegree, GeomAbs_Shape continuity, double tol3d) +void GeomBSplineCurve::approximate( + const std::vector& pnts, + double weight1, + double weight2, + double weight3, + int maxDegree, + GeomAbs_Shape continuity, + double tol3d +) { try { TColgp_Array1OfPnt coords(1, static_cast(pnts.size())); @@ -1833,9 +1922,8 @@ void GeomBSplineCurve::approximate(const std::vector& pnts, coords(index++) = gp_Pnt(it.x, it.y, it.z); } - GeomAPI_PointsToBSpline fit(coords, weight1, weight2, weight3, - maxDegree, continuity, tol3d); - const Handle(Geom_BSplineCurve)& spline = fit.Curve(); + GeomAPI_PointsToBSpline fit(coords, weight1, weight2, weight3, maxDegree, continuity, tol3d); + const Handle(Geom_BSplineCurve) & spline = fit.Curve(); if (!spline.IsNull()) { setHandle(spline); } @@ -1855,7 +1943,7 @@ void GeomBSplineCurve::increaseMultiplicity(int index, int multiplicity) curve->IncreaseMultiplicity(index, multiplicity); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -1867,23 +1955,25 @@ void GeomBSplineCurve::insertKnot(double param, int multiplicity) return; } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } bool GeomBSplineCurve::removeKnot(int index, int multiplicity, double tolerance) { try { - Handle(Geom_BSplineCurve) curve =Handle(Geom_BSplineCurve)::DownCast(myCurve->Copy()); + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(myCurve->Copy()); if (curve->RemoveKnot(index, multiplicity, tolerance)) { - // It can happen that OCCT computes a negative weight but still claims the removal was successful + // It can happen that OCCT computes a negative weight but still claims the removal was + // successful TColStd_Array1OfReal weights(1, curve->NbPoles()); curve->Weights(weights); for (Standard_Integer i = weights.Lower(); i <= weights.Upper(); i++) { double v = weights(i); - if (v <= gp::Resolution()) + if (v <= gp::Resolution()) { return false; + } } myCurve = curve; @@ -1893,7 +1983,7 @@ bool GeomBSplineCurve::removeKnot(int index, int multiplicity, double tolerance) return false; } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -1901,22 +1991,18 @@ void GeomBSplineCurve::Trim(double u, double v) { auto splitUnwrappedBSpline = [this](double u, double v) { // it makes a copy internally (checked in the source code of OCCT) - auto handle = GeomConvert::SplitBSplineCurve ( myCurve, - u, - v, - Precision::Confusion() - ); + auto handle = GeomConvert::SplitBSplineCurve(myCurve, u, v, Precision::Confusion()); setHandle(handle); }; try { if (isPeriodic() && (v < u)) { - v = v + (getLastParameter() - getFirstParameter()); // v needs one extra lap + v = v + (getLastParameter() - getFirstParameter()); // v needs one extra lap } splitUnwrappedBSpline(u, v); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -1924,10 +2010,11 @@ void GeomBSplineCurve::scaleKnotsToBounds(double u0, double u1) { try { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(myCurve->Copy()); - Standard_RangeError_Raise_if (u1 <= u0, " "); - TColStd_Array1OfReal k(1,curve->NbKnots()); + Standard_RangeError_Raise_if(u1 <= u0, " "); + TColStd_Array1OfReal k(1, curve->NbKnots()); curve->Knots(k); - if ((abs(u0-k.First()) > Precision::Confusion()) || (abs(u1-k.Last()) > Precision::Confusion())) { + if ((abs(u0 - k.First()) > Precision::Confusion()) + || (abs(u1 - k.Last()) > Precision::Confusion())) { BSplCLib::Reparametrize(u0, u1, k); curve->SetKnots(k); } @@ -1935,12 +2022,12 @@ void GeomBSplineCurve::scaleKnotsToBounds(double u0, double u1) return; } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomBSplineCurve::getMemSize () const +unsigned int GeomBSplineCurve::getMemSize() const { return sizeof(Geom_BSplineCurve); } @@ -1950,52 +2037,41 @@ void GeomBSplineCurve::Save(Base::Writer& writer) const // save the attributes of the father class GeomCurve::Save(writer); - std::vector poles = this->getPoles(); - std::vector weights = this->getWeights(); - std::vector knots = this->getKnots(); - std::vector mults = this->getMultiplicities(); - int degree = this->getDegree(); - bool isperiodic = this->isPeriodic(); + std::vector poles = this->getPoles(); + std::vector weights = this->getWeights(); + std::vector knots = this->getKnots(); + std::vector mults = this->getMultiplicities(); + int degree = this->getDegree(); + bool isperiodic = this->isPeriodic(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" + << std::endl; writer.incInd(); std::vector::const_iterator itp; std::vector::const_iterator itw; - for (itp = poles.begin(), itw = weights.begin(); itp != poles.end() && itw != weights.end(); ++itp, ++itw) { - writer.Stream() - << writer.ind() - << "" << std::endl; + for (itp = poles.begin(), itw = weights.begin(); itp != poles.end() && itw != weights.end(); + ++itp, ++itw) { + writer.Stream() << writer.ind() << "" << std::endl; } std::vector::const_iterator itk; std::vector::const_iterator itm; - for (itk = knots.begin(), itm = mults.begin(); itk != knots.end() && itm != mults.end(); ++itk, ++itm) { - writer.Stream() - << writer.ind() - << "" << std::endl; + for (itk = knots.begin(), itm = mults.begin(); itk != knots.end() && itm != mults.end(); + ++itk, ++itm) { + writer.Stream() << writer.ind() << "" << std::endl; } writer.decInd(); - writer.Stream() << writer.ind() << "" << std::endl ; + writer.Stream() << writer.ind() << "" << std::endl; } void GeomBSplineCurve::Restore(Base::XMLReader& reader) @@ -2015,10 +2091,10 @@ void GeomBSplineCurve::Restore(Base::XMLReader& reader) // Base::asBoolean(periodic), // Base::asBoolean(CheckRational)); - TColgp_Array1OfPnt p(1,polescount); - TColStd_Array1OfReal w(1,polescount); - TColStd_Array1OfReal k(1,knotscount); - TColStd_Array1OfInteger m(1,knotscount); + TColgp_Array1OfPnt p(1, polescount); + TColStd_Array1OfReal w(1, polescount); + TColStd_Array1OfReal k(1, knotscount); + TColStd_Array1OfInteger m(1, knotscount); for (int i = 1; i <= polescount; i++) { reader.readElement("Pole"); @@ -2026,7 +2102,7 @@ void GeomBSplineCurve::Restore(Base::XMLReader& reader) double Y = reader.getAttribute("Y"); double Z = reader.getAttribute("Z"); double W = reader.getAttribute("Weight"); - p.SetValue(i, gp_Pnt(X,Y,Z)); + p.SetValue(i, gp_Pnt(X, Y, Z)); w.SetValue(i, W); } @@ -2042,56 +2118,68 @@ void GeomBSplineCurve::Restore(Base::XMLReader& reader) // Geom_BSplineCurve(occpoles,occweights,occknots,occmults,degree,periodic,CheckRational try { - Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve(p, w, k, m, degree, isperiodic ? Standard_True : Standard_False, Standard_False); + Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve( + p, + w, + k, + m, + degree, + isperiodic ? Standard_True : Standard_False, + Standard_False + ); - if (!spline.IsNull()) + if (!spline.IsNull()) { this->myCurve = spline; - else - THROWM(Base::CADKernelError,"BSpline restore failed") + } + else { + THROWM(Base::CADKernelError, "BSpline restore failed") + } } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomBSplineCurve::getPyObject() +PyObject* GeomBSplineCurve::getPyObject() { return new BSplineCurvePy(freecad_cast(this->clone())); } -bool GeomBSplineCurve::isSame(const Geometry &_other, double tol, double atol) const +bool GeomBSplineCurve::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) { + if (_other.getTypeId() != getTypeId()) { if (isLinear() && _other.isDerivedFrom()) { std::unique_ptr geo(toLineSegment()); - if (geo) + if (geo) { return geo->isSame(_other, tol, atol); + } } return false; } - auto &other = dynamic_cast(_other); + auto& other = dynamic_cast(_other); (void)atol; - if(countPoles() != other.countPoles() - || countKnots() != other.countKnots() - || getDegree() != other.getDegree() - || isPeriodic() != other.isPeriodic()) + if (countPoles() != other.countPoles() || countKnots() != other.countKnots() + || getDegree() != other.getDegree() || isPeriodic() != other.isPeriodic()) { return false; + } - double tol2 = tol*tol; - for(int i=1, c=countPoles(); i<=c; ++i) { - if(myCurve->Pole(i).SquareDistance(other.myCurve->Pole(i)) > tol2 - || fabs(myCurve->Weight(i) - other.myCurve->Weight(i)) > tol) + double tol2 = tol * tol; + for (int i = 1, c = countPoles(); i <= c; ++i) { + if (myCurve->Pole(i).SquareDistance(other.myCurve->Pole(i)) > tol2 + || fabs(myCurve->Weight(i) - other.myCurve->Weight(i)) > tol) { return false; + } } - for(int i=1, c=countKnots(); i<=c; ++i) { - if(fabs(myCurve->Knot(i) - other.myCurve->Knot(i)) > tol) + for (int i = 1, c = countKnots(); i <= c; ++i) { + if (fabs(myCurve->Knot(i) - other.myCurve->Knot(i)) > tol) { return false; + } } return true; } @@ -2107,23 +2195,23 @@ GeomConic::~GeomConic() = default; Base::Vector3d GeomConic::getLocation() const { - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); gp_Ax1 axis = conic->Axis(); const gp_Pnt& loc = axis.Location(); - return Base::Vector3d(loc.X(),loc.Y(),loc.Z()); + return Base::Vector3d(loc.X(), loc.Y(), loc.Z()); } void GeomConic::setLocation(const Base::Vector3d& Center) { - gp_Pnt p1(Center.x,Center.y,Center.z); - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + gp_Pnt p1(Center.x, Center.y, Center.z); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); try { conic->SetLocation(p1); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -2152,23 +2240,23 @@ std::optional GeomConic::getRotation() const void GeomConic::setCenter(const Base::Vector3d& Center) { - gp_Pnt p1(Center.x,Center.y,Center.z); - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + gp_Pnt p1(Center.x, Center.y, Center.z); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); try { conic->SetLocation(p1); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } Base::Vector3d GeomConic::getAxisDirection() const { - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); gp_Ax1 axis = conic->Axis(); const gp_Dir& dir = axis.Direction(); - return Base::Vector3d( dir.X(),dir.Y(),dir.Z()); + return Base::Vector3d(dir.X(), dir.Y(), dir.Z()); } /*! @@ -2183,17 +2271,17 @@ Base::Vector3d GeomConic::getAxisDirection() const */ double GeomConic::getAngleXU() const { - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); gp_Pnt center = conic->Axis().Location(); gp_Dir normal = conic->Axis().Direction(); gp_Dir xdir = conic->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference system, might be CCW or CW depending on the creation method - - return -xdir.AngleWithRef(xdirref.XDirection(),normal); + gp_Ax2 xdirref(center, normal); // this is a reference system, might be CCW or CW depending on + // the creation method + return -xdir.AngleWithRef(xdirref.XDirection(), normal); } /*! @@ -2202,7 +2290,8 @@ double GeomConic::getAngleXU() const */ void GeomConic::setAngleXU(double angle) { - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle());; + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + ; try { gp_Pnt center = conic->Axis().Location(); @@ -2211,12 +2300,12 @@ void GeomConic::setAngleXU(double angle) gp_Ax1 normaxis(center, normal); gp_Ax2 xdirref(center, normal); - xdirref.Rotate(normaxis,angle); + xdirref.Rotate(normaxis, angle); conic->SetPosition(xdirref); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -2228,7 +2317,7 @@ void GeomConic::setAngleXU(double angle) */ bool GeomConic::isReversed() const { - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); assert(!conic.IsNull()); return conic->Axis().Direction().Z() < 0; } @@ -2245,7 +2334,7 @@ bool GeomConic::reverseIfReversed() GeomBSplineCurve* GeomConic::toNurbs(double first, double last) const { - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); Handle(Geom_Curve) curve = new Geom_TrimmedCurve(conic, first, last); // pass the trimmed conic @@ -2254,7 +2343,7 @@ GeomBSplineCurve* GeomConic::toNurbs(double first, double last) const if (!bspline->IsPeriodic()) { bspline->Resolution(Precision::Confusion(), UTol); if (Abs(first - fnew) > UTol || Abs(last - lnew) > UTol) { - TColStd_Array1OfReal knots(1,bspline->NbKnots()); + TColStd_Array1OfReal knots(1, bspline->NbKnots()); bspline->Knots(knots); BSplCLib::Reparametrize(first, last, knots); bspline->SetKnots(knots); @@ -2264,47 +2353,48 @@ GeomBSplineCurve* GeomConic::toNurbs(double first, double last) const return new GeomBSplineCurve(bspline); } -bool GeomConic::isSame(const Geometry &_other, double tol, double atol) const +bool GeomConic::isSame(const Geometry& _other, double tol, double atol) const { - if(!_other.isDerivedFrom()) + if (!_other.isDerivedFrom()) { return false; + } - auto &other = static_cast(_other); + auto& other = static_cast(_other); - Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); - Handle(Geom_Conic) conic2 = Handle(Geom_Conic)::DownCast(other.handle()); + Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); + Handle(Geom_Conic) conic2 = Handle(Geom_Conic)::DownCast(other.handle()); return conic->Position().XDirection().Angle(conic2->Position().XDirection()) <= atol && conic->Position().YDirection().Angle(conic2->Position().YDirection()) <= atol - && Base::DistanceP2(getLocation(),other.getLocation()) <= tol*tol; + && Base::DistanceP2(getLocation(), other.getLocation()) <= tol * tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomTrimmedCurve,Part::GeomBoundedCurve) +TYPESYSTEM_SOURCE(Part::GeomTrimmedCurve, Part::GeomBoundedCurve) GeomTrimmedCurve::GeomTrimmedCurve() = default; -GeomTrimmedCurve::GeomTrimmedCurve(const Handle(Geom_TrimmedCurve)& c) +GeomTrimmedCurve::GeomTrimmedCurve(const Handle(Geom_TrimmedCurve) & c) { setHandle(c); } GeomTrimmedCurve::~GeomTrimmedCurve() = default; -void GeomTrimmedCurve::setHandle(const Handle(Geom_TrimmedCurve)& c) +void GeomTrimmedCurve::setHandle(const Handle(Geom_TrimmedCurve) & c) { this->myCurve = Handle(Geom_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom_Geometry)& GeomTrimmedCurve::handle() const +const Handle(Geom_Geometry) & GeomTrimmedCurve::handle() const { return myCurve; } -Geometry *GeomTrimmedCurve::copy() const +Geometry* GeomTrimmedCurve::copy() const { - GeomTrimmedCurve *newCurve = new GeomTrimmedCurve(myCurve); + GeomTrimmedCurve* newCurve = new GeomTrimmedCurve(myCurve); newCurve->copyNonTag(this); return newCurve; } @@ -2318,73 +2408,79 @@ GeomCurve* GeomTrimmedCurve::createArc(double first, double last) const } // Persistence implementer -unsigned int GeomTrimmedCurve::getMemSize () const +unsigned int GeomTrimmedCurve::getMemSize() const { return sizeof(Geom_TrimmedCurve); } -void GeomTrimmedCurve::Save(Base::Writer &/*writer*/) const +void GeomTrimmedCurve::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomTrimmedCurve::Save"); } -void GeomTrimmedCurve::Restore(Base::XMLReader &/*reader*/) +void GeomTrimmedCurve::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomTrimmedCurve::Restore"); } -PyObject *GeomTrimmedCurve::getPyObject() +PyObject* GeomTrimmedCurve::getPyObject() { return new TrimmedCurvePy(static_cast(this->clone())); } -bool GeomTrimmedCurve::isSame(const Geometry &_other, double tol, double atol) const +bool GeomTrimmedCurve::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = static_cast(_other); - double u,v,u1,v1; - getRange(u,v); - other.getRange(u1,v1); - if(fabs(u-u1)>tol || fabs(v-v1)>tol) + auto& other = static_cast(_other); + double u, v, u1, v1; + getRange(u, v); + other.getRange(u1, v1); + if (fabs(u - u1) > tol || fabs(v - v1) > tol) { return false; + } Handle(Geom_Curve) basis = myCurve->BasisCurve(); Handle(Geom_Curve) basis1 = other.myCurve->BasisCurve(); - if(basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) + if (basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) { return false; + } std::unique_ptr b(makeFromCurve(basis)); std::unique_ptr b1(makeFromCurve(basis1)); - if (b && b1 && b->isSame(*b1, tol, atol)) + if (b && b1 && b->isSame(*b1, tol, atol)) { return true; + } return false; } -bool GeomTrimmedCurve::intersectBasisCurves( const GeomTrimmedCurve * c, - std::vector>& points, - double tol) const +bool GeomTrimmedCurve::intersectBasisCurves( + const GeomTrimmedCurve* c, + std::vector>& points, + double tol +) const { - Handle(Geom_TrimmedCurve) curve1 = Handle(Geom_TrimmedCurve)::DownCast(handle()); - Handle(Geom_TrimmedCurve) curve2 = Handle(Geom_TrimmedCurve)::DownCast(c->handle()); + Handle(Geom_TrimmedCurve) curve1 = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve2 = Handle(Geom_TrimmedCurve)::DownCast(c->handle()); Handle(Geom_Curve) bcurve1 = curve1->BasisCurve(); Handle(Geom_Curve) bcurve2 = curve2->BasisCurve(); - if(!bcurve1.IsNull() && !bcurve2.IsNull()) { + if (!bcurve1.IsNull() && !bcurve2.IsNull()) { return intersect(bcurve1, bcurve2, points, tol); } - else + else { return false; - + } } void GeomTrimmedCurve::getRange(double& u, double& v) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); u = curve->FirstParameter(); v = curve->LastParameter(); } @@ -2392,17 +2488,17 @@ void GeomTrimmedCurve::getRange(double& u, double& v) const void GeomTrimmedCurve::setRange(double u, double v) { try { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); curve->SetTrim(u, v); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // ------------------------------------------------- -TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomArcOfConic,Part::GeomTrimmedCurve) +TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomArcOfConic, Part::GeomTrimmedCurve) GeomArcOfConic::GeomArcOfConic() = default; @@ -2416,11 +2512,12 @@ GeomArcOfConic::~GeomArcOfConic() = default; */ Base::Vector3d GeomArcOfConic::getStartPoint(bool emulateCCWXY) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); gp_Pnt pnt = curve->StartPoint(); if (emulateCCWXY) { - if (isReversed()) + if (isReversed()) { pnt = curve->EndPoint(); + } } return Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()); } @@ -2433,37 +2530,38 @@ Base::Vector3d GeomArcOfConic::getStartPoint(bool emulateCCWXY) const */ Base::Vector3d GeomArcOfConic::getEndPoint(bool emulateCCWXY) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); gp_Pnt pnt = curve->EndPoint(); if (emulateCCWXY) { - if (isReversed()) + if (isReversed()) { pnt = curve->StartPoint(); + } } return Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()); } Base::Vector3d GeomArcOfConic::getCenter() const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); gp_Ax1 axis = conic->Axis(); const gp_Pnt& loc = axis.Location(); - return Base::Vector3d(loc.X(),loc.Y(),loc.Z()); + return Base::Vector3d(loc.X(), loc.Y(), loc.Z()); } Base::Vector3d GeomArcOfConic::getLocation() const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); gp_Ax1 axis = conic->Axis(); const gp_Pnt& loc = axis.Location(); - return Base::Vector3d(loc.X(),loc.Y(),loc.Z()); + return Base::Vector3d(loc.X(), loc.Y(), loc.Z()); } void GeomArcOfConic::setCenter(const Base::Vector3d& Center) { - gp_Pnt p1(Center.x,Center.y,Center.z); - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + gp_Pnt p1(Center.x, Center.y, Center.z); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); try { @@ -2471,14 +2569,14 @@ void GeomArcOfConic::setCenter(const Base::Vector3d& Center) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } void GeomArcOfConic::setLocation(const Base::Vector3d& Center) { - gp_Pnt p1(Center.x,Center.y,Center.z); - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + gp_Pnt p1(Center.x, Center.y, Center.z); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); try { @@ -2486,17 +2584,17 @@ void GeomArcOfConic::setLocation(const Base::Vector3d& Center) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } Base::Vector3d GeomArcOfConic::getAxisDirection() const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); gp_Ax1 axis = conic->Axis(); const gp_Dir& dir = axis.Direction(); - return Base::Vector3d( dir.X(),dir.Y(),dir.Z()); + return Base::Vector3d(dir.X(), dir.Y(), dir.Z()); } /*! @@ -2507,7 +2605,7 @@ Base::Vector3d GeomArcOfConic::getAxisDirection() const */ bool GeomArcOfConic::isReversed() const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); assert(!conic.IsNull()); return conic->Axis().Direction().Z() < 0; @@ -2537,16 +2635,17 @@ bool GeomArcOfConic::reverseIfReversed() */ double GeomArcOfConic::getAngleXU() const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); gp_Pnt center = conic->Axis().Location(); gp_Dir normal = conic->Axis().Direction(); gp_Dir xdir = conic->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference system, might be CCW or CW depending on the creation method + gp_Ax2 xdirref(center, normal); // this is a reference system, might be CCW or CW depending on + // the creation method - return -xdir.AngleWithRef(xdirref.XDirection(),normal); + return -xdir.AngleWithRef(xdirref.XDirection(), normal); } /*! @@ -2554,7 +2653,7 @@ double GeomArcOfConic::getAngleXU() const */ void GeomArcOfConic::setAngleXU(double angle) { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); try { @@ -2564,12 +2663,12 @@ void GeomArcOfConic::setAngleXU(double angle) gp_Ax1 normaxis(center, normal); gp_Ax2 xdirref(center, normal); - xdirref.Rotate(normaxis,angle); + xdirref.Rotate(normaxis, angle); conic->SetPosition(xdirref); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -2580,8 +2679,8 @@ void GeomArcOfConic::setAngleXU(double angle) */ Base::Vector3d GeomArcOfConic::getXAxisDir() const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); - Handle(Geom_Conic) c = Handle(Geom_Conic)::DownCast( curve->BasisCurve() ); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_Conic) c = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); assert(!c.IsNull()); gp_Dir xdir = c->XAxis().Direction(); return Base::Vector3d(xdir.X(), xdir.Y(), xdir.Z()); @@ -2597,28 +2696,30 @@ Base::Vector3d GeomArcOfConic::getXAxisDir() const */ void GeomArcOfConic::setXAxisDir(const Base::Vector3d& newdir) { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); - Handle(Geom_Conic) c = Handle(Geom_Conic)::DownCast( curve->BasisCurve() ); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_Conic) c = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); assert(!c.IsNull()); - if (newdir.Sqr() < Precision::SquareConfusion()) - return;//zero vector was passed. Keep the old orientation. + if (newdir.Sqr() < Precision::SquareConfusion()) { + return; // zero vector was passed. Keep the old orientation. + } try { gp_Ax2 pos = c->Position(); - //OCC should keep the old main Direction (Z), and change YDirection to accommodate the new XDirection. + // OCC should keep the old main Direction (Z), and change YDirection to accommodate the new + // XDirection. pos.SetXDirection(gp_Dir(newdir.x, newdir.y, newdir.z)); c->SetPosition(pos); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomCircle,Part::GeomConic) +TYPESYSTEM_SOURCE(Part::GeomCircle, Part::GeomConic) GeomCircle::GeomCircle() { @@ -2626,27 +2727,27 @@ GeomCircle::GeomCircle() this->myCurve = c; } -GeomCircle::GeomCircle(const Handle(Geom_Circle)& c) +GeomCircle::GeomCircle(const Handle(Geom_Circle) & c) { setHandle(c); } GeomCircle::~GeomCircle() = default; -const Handle(Geom_Geometry)& GeomCircle::handle() const +const Handle(Geom_Geometry) & GeomCircle::handle() const { return myCurve; } -void GeomCircle::setHandle(const Handle(Geom_Circle)& c) +void GeomCircle::setHandle(const Handle(Geom_Circle) & c) { myCurve = Handle(Geom_Circle)::DownCast(c->Copy()); } -Geometry *GeomCircle::copy() const +Geometry* GeomCircle::copy() const { - GeomCircle *newCirc = new GeomCircle(myCurve); + GeomCircle* newCirc = new GeomCircle(myCurve); newCirc->copyNonTag(this); return newCirc; } @@ -2666,22 +2767,22 @@ GeomBSplineCurve* GeomCircle::toNurbs(double first, double last) const return GeomConic::toNurbs(first, last); } - Handle(Geom_Circle) conic = Handle(Geom_Circle)::DownCast(handle()); + Handle(Geom_Circle) conic = Handle(Geom_Circle)::DownCast(handle()); double radius = conic->Radius(); TColgp_Array1OfPnt poles(1, 7); poles(1) = gp_Pnt(radius, 0, 0); - poles(2) = gp_Pnt(radius, 2*radius, 0); - poles(3) = gp_Pnt(-radius, 2*radius, 0); + poles(2) = gp_Pnt(radius, 2 * radius, 0); + poles(3) = gp_Pnt(-radius, 2 * radius, 0); poles(4) = gp_Pnt(-radius, 0, 0); - poles(5) = gp_Pnt(-radius, -2*radius, 0); - poles(6) = gp_Pnt(radius, -2*radius, 0); + poles(5) = gp_Pnt(-radius, -2 * radius, 0); + poles(6) = gp_Pnt(radius, -2 * radius, 0); poles(7) = gp_Pnt(radius, 0, 0); gp_Trsf trsf; trsf.SetTransformation(conic->Position(), gp_Ax3()); - TColStd_Array1OfReal weights(1,7); - for (int i=1; i<=7; i++) { + TColStd_Array1OfReal weights(1, 7); + for (int i = 1; i <= 7; i++) { poles(i).Transform(trsf); weights(i) = 1; } @@ -2699,8 +2800,8 @@ GeomBSplineCurve* GeomCircle::toNurbs(double first, double last) const knots(2) = std::numbers::pi; knots(3) = 2 * std::numbers::pi; - Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve(poles, weights,knots, mults, 3, - Standard_False, Standard_True); + Handle(Geom_BSplineCurve) spline + = new Geom_BSplineCurve(poles, weights, knots, mults, 3, Standard_False, Standard_True); return new GeomBSplineCurve(spline); } @@ -2721,12 +2822,12 @@ void GeomCircle::setRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomCircle::getMemSize () const +unsigned int GeomCircle::getMemSize() const { return sizeof(Geom_Circle); } @@ -2740,21 +2841,14 @@ void GeomCircle::Save(Base::Writer& writer) const gp_Dir normal = this->myCurve->Axis().Direction(); gp_Dir xdir = this->myCurve->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the circle - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + gp_Ax2 xdirref(center, normal); // this is a reference XY for the circle + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "myCurve->Radius() << - "\"/>" << std::endl; + writer.Stream() << writer.ind() << "myCurve->Radius() << "\"/>" << std::endl; } void GeomCircle::Restore(Base::XMLReader& reader) @@ -2762,8 +2856,8 @@ void GeomCircle::Restore(Base::XMLReader& reader) // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,Radius; - double AngleXU=0; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, Radius; + double AngleXU = 0; // read my Element reader.readElement("Circle"); // get the value of my Attribute @@ -2773,83 +2867,87 @@ void GeomCircle::Restore(Base::XMLReader& reader) NormalX = reader.getAttribute("NormalX"); NormalY = reader.getAttribute("NormalY"); NormalZ = reader.getAttribute("NormalZ"); - if (reader.hasAttribute("AngleXU")) + if (reader.hasAttribute("AngleXU")) { AngleXU = reader.getAttribute("AngleXU"); + } Radius = reader.getAttribute("Radius"); // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { GC_MakeCircle mc(xdir, Radius); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } this->myCurve = mc.Value(); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomCircle::getPyObject() +PyObject* GeomCircle::getPyObject() { return new CirclePy(static_cast(this->clone())); } -bool GeomCircle::isSame(const Geometry &_other, double tol, double atol) const +bool GeomCircle::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomConic::isSame(other,tol,atol) && fabs(getRadius() - other.getRadius()) <= tol; + auto& other = static_cast(_other); + return GeomConic::isSame(other, tol, atol) && fabs(getRadius() - other.getRadius()) <= tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomArcOfCircle,Part::GeomArcOfConic) +TYPESYSTEM_SOURCE(Part::GeomArcOfCircle, Part::GeomArcOfConic) GeomArcOfCircle::GeomArcOfCircle() { Handle(Geom_Circle) c = new Geom_Circle(gp_Circ()); - this->myCurve = new Geom_TrimmedCurve(c, c->FirstParameter(),c->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(c, c->FirstParameter(), c->LastParameter()); } -GeomArcOfCircle::GeomArcOfCircle(const Handle(Geom_Circle)& c) +GeomArcOfCircle::GeomArcOfCircle(const Handle(Geom_Circle) & c) { setHandle(c); } GeomArcOfCircle::~GeomArcOfCircle() = default; -void GeomArcOfCircle::setHandle(const Handle(Geom_TrimmedCurve)& c) +void GeomArcOfCircle::setHandle(const Handle(Geom_TrimmedCurve) & c) { Handle(Geom_Circle) basis = Handle(Geom_Circle)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not a circle"); + } this->myCurve = Handle(Geom_TrimmedCurve)::DownCast(c->Copy()); } -void GeomArcOfCircle::setHandle(const Handle(Geom_Circle)& c) +void GeomArcOfCircle::setHandle(const Handle(Geom_Circle) & c) { - this->myCurve = new Geom_TrimmedCurve(c, c->FirstParameter(),c->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(c, c->FirstParameter(), c->LastParameter()); } -const Handle(Geom_Geometry)& GeomArcOfCircle::handle() const +const Handle(Geom_Geometry) & GeomArcOfCircle::handle() const { return myCurve; } -Geometry *GeomArcOfCircle::copy() const +Geometry* GeomArcOfCircle::copy() const { GeomArcOfCircle* copy = new GeomArcOfCircle(); copy->setHandle(this->myCurve); @@ -2859,7 +2957,7 @@ Geometry *GeomArcOfCircle::copy() const GeomBSplineCurve* GeomArcOfCircle::toNurbs(double first, double last) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(curve->BasisCurve()); return GeomCircle(circle).toNurbs(first, last); } @@ -2881,7 +2979,7 @@ void GeomArcOfCircle::setRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -2909,28 +3007,34 @@ double GeomArcOfCircle::getAngle(bool emulateCCWXY) const */ void GeomArcOfCircle::getRange(double& u, double& v, bool emulateCCWXY) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); u = curve->FirstParameter(); v = curve->LastParameter(); - if (emulateCCWXY){ + if (emulateCCWXY) { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); - double angleXU = -conic->Position().XDirection().AngleWithRef(gp_Dir(1.0,0.0,0.0), gp_Dir(0.0,0.0,1.0)); - double u1 = u, v1 = v;//the true arc curve parameters, cached. u,v will contain the rotation-corrected and swapped angles. - if (conic->Axis().Direction().Z() > 0.0){ - //normal CCW arc + double angleXU = -conic->Position().XDirection().AngleWithRef( + gp_Dir(1.0, 0.0, 0.0), + gp_Dir(0.0, 0.0, 1.0) + ); + double u1 = u, v1 = v; // the true arc curve parameters, cached. u,v will contain the + // rotation-corrected and swapped angles. + if (conic->Axis().Direction().Z() > 0.0) { + // normal CCW arc u = u1 + angleXU; v = v1 + angleXU; } else { - //reversed (CW) arc + // reversed (CW) arc u = angleXU - v1; v = angleXU - u1; } - if (v < u) + if (v < u) { v += 2 * std::numbers::pi; - if (v-u > 2 * std::numbers::pi) + } + if (v - u > 2 * std::numbers::pi) { v -= 2 * std::numbers::pi; + } } } @@ -2946,18 +3050,22 @@ void GeomArcOfCircle::getRange(double& u, double& v, bool emulateCCWXY) const void GeomArcOfCircle::setRange(double u, double v, bool emulateCCWXY) { try { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); - if (emulateCCWXY){ + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + if (emulateCCWXY) { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); - double angleXU = -conic->Position().XDirection().AngleWithRef(gp_Dir(1.0,0.0,0.0), gp_Dir(0.0,0.0,1.0)); - double u1 = u, v1 = v;//the values that were passed, ccw angles from X axis. u,v will contain the rotation-corrected and swapped angles. - if (conic->Axis().Direction().Z() > 0.0){ - //normal CCW arc + double angleXU = -conic->Position().XDirection().AngleWithRef( + gp_Dir(1.0, 0.0, 0.0), + gp_Dir(0.0, 0.0, 1.0) + ); + double u1 = u, v1 = v; // the values that were passed, ccw angles from X axis. u,v will + // contain the rotation-corrected and swapped angles. + if (conic->Axis().Direction().Z() > 0.0) { + // normal CCW arc u = u1 - angleXU; v = v1 - angleXU; } else { - //reversed (CW) arc + // reversed (CW) arc u = angleXU - v1; v = angleXU - u1; } @@ -2967,17 +3075,17 @@ void GeomArcOfCircle::setRange(double u, double v, bool emulateCCWXY) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomArcOfCircle::getMemSize () const +unsigned int GeomArcOfCircle::getMemSize() const { - return sizeof(Geom_Circle) + 2 *sizeof(double); + return sizeof(Geom_Circle) + 2 * sizeof(double); } -void GeomArcOfCircle::Save(Base::Writer &writer) const +void GeomArcOfCircle::Save(Base::Writer& writer) const { // save the attributes of the father class Geometry::Save(writer); @@ -2988,32 +3096,24 @@ void GeomArcOfCircle::Save(Base::Writer &writer) const gp_Dir normal = circle->Axis().Direction(); gp_Dir xdir = circle->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the arc - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + gp_Ax2 xdirref(center, normal); // this is a reference XY for the arc + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "Radius() << - "\" StartAngle=\"" << this->myCurve->FirstParameter() << - "\" EndAngle=\"" << this->myCurve->LastParameter() << - "\"/>" << std::endl; + writer.Stream() << writer.ind() << "Radius() << "\" StartAngle=\"" << this->myCurve->FirstParameter() + << "\" EndAngle=\"" << this->myCurve->LastParameter() << "\"/>" << std::endl; } -void GeomArcOfCircle::Restore(Base::XMLReader &reader) +void GeomArcOfCircle::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geometry::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,Radius,StartAngle,EndAngle; - double AngleXU=0; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, Radius, StartAngle, EndAngle; + double AngleXU = 0; // read my Element reader.readElement("ArcOfCircle"); // get the value of my Attribute @@ -3023,27 +3123,30 @@ void GeomArcOfCircle::Restore(Base::XMLReader &reader) NormalX = reader.getAttribute("NormalX"); NormalY = reader.getAttribute("NormalY"); NormalZ = reader.getAttribute("NormalZ"); - if (reader.hasAttribute("AngleXU")) + if (reader.hasAttribute("AngleXU")) { AngleXU = reader.getAttribute("AngleXU"); + } Radius = reader.getAttribute("Radius"); StartAngle = reader.getAttribute("StartAngle"); EndAngle = reader.getAttribute("EndAngle"); // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { GC_MakeCircle mc(xdir, Radius); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } GC_MakeArcOfCircle ma(mc.Value()->Circ(), StartAngle, EndAngle, Standard_True); - if (!ma.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(ma.Status())) + if (!ma.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(ma.Status())) + } Handle(Geom_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom_Circle) tmpcircle = Handle(Geom_Circle)::DownCast(tmpcurve->BasisCurve()); @@ -3054,18 +3157,18 @@ void GeomArcOfCircle::Restore(Base::XMLReader &reader) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomArcOfCircle::getPyObject() +PyObject* GeomArcOfCircle::getPyObject() { return new ArcOfCirclePy(static_cast(this->clone())); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomEllipse,Part::GeomConic) +TYPESYSTEM_SOURCE(Part::GeomEllipse, Part::GeomConic) GeomEllipse::GeomEllipse() { @@ -3073,26 +3176,26 @@ GeomEllipse::GeomEllipse() this->myCurve = e; } -GeomEllipse::GeomEllipse(const Handle(Geom_Ellipse)& e) +GeomEllipse::GeomEllipse(const Handle(Geom_Ellipse) & e) { setHandle(e); } GeomEllipse::~GeomEllipse() = default; -const Handle(Geom_Geometry)& GeomEllipse::handle() const +const Handle(Geom_Geometry) & GeomEllipse::handle() const { return myCurve; } -void GeomEllipse::setHandle(const Handle(Geom_Ellipse) &e) +void GeomEllipse::setHandle(const Handle(Geom_Ellipse) & e) { this->myCurve = Handle(Geom_Ellipse)::DownCast(e->Copy()); } -Geometry *GeomEllipse::copy() const +Geometry* GeomEllipse::copy() const { - GeomEllipse *newEllipse = new GeomEllipse(myCurve); + GeomEllipse* newEllipse = new GeomEllipse(myCurve); newEllipse->copyNonTag(this); return newEllipse; } @@ -3112,23 +3215,23 @@ GeomBSplineCurve* GeomEllipse::toNurbs(double first, double last) const return GeomConic::toNurbs(first, last); } - Handle(Geom_Ellipse) conic = Handle(Geom_Ellipse)::DownCast(handle()); + Handle(Geom_Ellipse) conic = Handle(Geom_Ellipse)::DownCast(handle()); Standard_Real majorRadius = conic->MajorRadius(); Standard_Real minorRadius = conic->MinorRadius(); TColgp_Array1OfPnt poles(1, 7); poles(1) = gp_Pnt(majorRadius, 0, 0); - poles(2) = gp_Pnt(majorRadius, 2*minorRadius, 0); - poles(3) = gp_Pnt(-majorRadius, 2*minorRadius, 0); + poles(2) = gp_Pnt(majorRadius, 2 * minorRadius, 0); + poles(3) = gp_Pnt(-majorRadius, 2 * minorRadius, 0); poles(4) = gp_Pnt(-majorRadius, 0, 0); - poles(5) = gp_Pnt(-majorRadius, -2*minorRadius, 0); - poles(6) = gp_Pnt(majorRadius, -2*minorRadius, 0); + poles(5) = gp_Pnt(-majorRadius, -2 * minorRadius, 0); + poles(6) = gp_Pnt(majorRadius, -2 * minorRadius, 0); poles(7) = gp_Pnt(majorRadius, 0, 0); gp_Trsf trsf; trsf.SetTransformation(conic->Position(), gp_Ax3()); - TColStd_Array1OfReal weights(1,7); - for (int i=1; i<=7; i++) { + TColStd_Array1OfReal weights(1, 7); + for (int i = 1; i <= 7; i++) { poles(i).Transform(trsf); weights(i) = 1; } @@ -3146,8 +3249,8 @@ GeomBSplineCurve* GeomEllipse::toNurbs(double first, double last) const knots(2) = 1; knots(3) = 2; - Handle(Geom_BSplineCurve) spline = new Geom_BSplineCurve(poles, weights,knots, mults, 3, - Standard_False, Standard_True); + Handle(Geom_BSplineCurve) spline + = new Geom_BSplineCurve(poles, weights, knots, mults, 3, Standard_False, Standard_True); return new GeomBSplineCurve(spline); } @@ -3166,7 +3269,7 @@ void GeomEllipse::setMajorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3185,7 +3288,7 @@ void GeomEllipse::setMinorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3221,21 +3324,25 @@ Base::Vector3d GeomEllipse::getMinorAxisDir() const */ void GeomEllipse::setMajorAxisDir(Base::Vector3d newdir) { - if (newdir.Sqr() < Precision::SquareConfusion()) - return;//zero vector was passed. Keep the old orientation. + if (newdir.Sqr() < Precision::SquareConfusion()) { + return; // zero vector was passed. Keep the old orientation. + } try { gp_Ax2 pos = myCurve->Position(); - pos.SetXDirection(gp_Dir(newdir.x, newdir.y, newdir.z));//OCC should keep the old main Direction (Z), and change YDirection to accommodate the new XDirection. + pos.SetXDirection( + gp_Dir(newdir.x, newdir.y, newdir.z) + ); // OCC should keep the old main Direction (Z), and change YDirection to accommodate the + // new XDirection. myCurve->SetPosition(pos); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomEllipse::getMemSize () const +unsigned int GeomEllipse::getMemSize() const { return sizeof(Geom_Ellipse); } @@ -3249,24 +3356,22 @@ void GeomEllipse::Save(Base::Writer& writer) const gp_Dir normal = this->myCurve->Axis().Direction(); gp_Dir xdir = this->myCurve->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "myCurve->MajorRadius() << "\" " - << "MinorRadius=\"" << this->myCurve->MinorRadius() << "\" " - << "AngleXU=\"" << AngleXU << "\" " - << "/>" << std::endl; + writer.Stream() << writer.ind() << "myCurve->MajorRadius() << "\" " + << "MinorRadius=\"" << this->myCurve->MinorRadius() << "\" " + << "AngleXU=\"" << AngleXU << "\" " + << "/>" << std::endl; } void GeomEllipse::Restore(Base::XMLReader& reader) @@ -3274,7 +3379,7 @@ void GeomEllipse::Restore(Base::XMLReader& reader) // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,MajorRadius,MinorRadius,AngleXU; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, MajorRadius, MinorRadius, AngleXU; // read my Element reader.readElement("Ellipse"); // get the value of my Attribute @@ -3288,87 +3393,92 @@ void GeomEllipse::Restore(Base::XMLReader& reader) MinorRadius = reader.getAttribute("MinorRadius"); // This is for backwards compatibility - if(reader.hasAttribute("AngleXU")) + if (reader.hasAttribute("AngleXU")) { AngleXU = reader.getAttribute("AngleXU"); - else + } + else { AngleXU = 0; + } // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { GC_MakeEllipse mc(xdir, MajorRadius, MinorRadius); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } this->myCurve = mc.Value(); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomEllipse::getPyObject() +PyObject* GeomEllipse::getPyObject() { return new EllipsePy(static_cast(this->clone())); } -bool GeomEllipse::isSame(const Geometry &_other, double tol, double atol) const +bool GeomEllipse::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomConic::isSame(other,tol,atol) + auto& other = static_cast(_other); + return GeomConic::isSame(other, tol, atol) && fabs(getMajorRadius() - other.getMajorRadius()) <= tol && fabs(getMinorRadius() - other.getMinorRadius()) <= tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomArcOfEllipse,Part::GeomArcOfConic) +TYPESYSTEM_SOURCE(Part::GeomArcOfEllipse, Part::GeomArcOfConic) GeomArcOfEllipse::GeomArcOfEllipse() { Handle(Geom_Ellipse) e = new Geom_Ellipse(gp_Elips()); - this->myCurve = new Geom_TrimmedCurve(e, e->FirstParameter(),e->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(e, e->FirstParameter(), e->LastParameter()); } -GeomArcOfEllipse::GeomArcOfEllipse(const Handle(Geom_Ellipse)& e) +GeomArcOfEllipse::GeomArcOfEllipse(const Handle(Geom_Ellipse) & e) { setHandle(e); } GeomArcOfEllipse::~GeomArcOfEllipse() = default; -void GeomArcOfEllipse::setHandle(const Handle(Geom_TrimmedCurve)& c) +void GeomArcOfEllipse::setHandle(const Handle(Geom_TrimmedCurve) & c) { Handle(Geom_Ellipse) basis = Handle(Geom_Ellipse)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not an ellipse"); + } this->myCurve = Handle(Geom_TrimmedCurve)::DownCast(c->Copy()); } -void GeomArcOfEllipse::setHandle(const Handle(Geom_Ellipse)& e) +void GeomArcOfEllipse::setHandle(const Handle(Geom_Ellipse) & e) { - this->myCurve = new Geom_TrimmedCurve(e, e->FirstParameter(),e->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(e, e->FirstParameter(), e->LastParameter()); } -const Handle(Geom_Geometry)& GeomArcOfEllipse::handle() const +const Handle(Geom_Geometry) & GeomArcOfEllipse::handle() const { return myCurve; } -Geometry *GeomArcOfEllipse::copy() const +Geometry* GeomArcOfEllipse::copy() const { GeomArcOfEllipse* copy = new GeomArcOfEllipse(); copy->setHandle(this->myCurve); @@ -3378,7 +3488,7 @@ Geometry *GeomArcOfEllipse::copy() const GeomBSplineCurve* GeomArcOfEllipse::toNurbs(double first, double last) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(curve->BasisCurve()); return GeomEllipse(ellipse).toNurbs(first, last); } @@ -3398,7 +3508,7 @@ void GeomArcOfEllipse::setMajorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3417,7 +3527,7 @@ void GeomArcOfEllipse::setMinorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3428,7 +3538,7 @@ void GeomArcOfEllipse::setMinorRadius(double Radius) */ Base::Vector3d GeomArcOfEllipse::getMajorAxisDir() const { - Handle(Geom_Ellipse) c = Handle(Geom_Ellipse)::DownCast( myCurve->BasisCurve() ); + Handle(Geom_Ellipse) c = Handle(Geom_Ellipse)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); gp_Dir xdir = c->XAxis().Direction(); return Base::Vector3d(xdir.X(), xdir.Y(), xdir.Z()); @@ -3456,18 +3566,22 @@ Base::Vector3d GeomArcOfEllipse::getMinorAxisDir() const */ void GeomArcOfEllipse::setMajorAxisDir(Base::Vector3d newdir) { - Handle(Geom_Ellipse) c = Handle(Geom_Ellipse)::DownCast( myCurve->BasisCurve() ); + Handle(Geom_Ellipse) c = Handle(Geom_Ellipse)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); - if (newdir.Sqr() < Precision::SquareConfusion()) - return;//zero vector was passed. Keep the old orientation. + if (newdir.Sqr() < Precision::SquareConfusion()) { + return; // zero vector was passed. Keep the old orientation. + } try { gp_Ax2 pos = c->Position(); - pos.SetXDirection(gp_Dir(newdir.x, newdir.y, newdir.z));//OCC should keep the old main Direction (Z), and change YDirection to accommodate the new XDirection. + pos.SetXDirection( + gp_Dir(newdir.x, newdir.y, newdir.z) + ); // OCC should keep the old main Direction (Z), and change YDirection to accommodate the + // new XDirection. c->SetPosition(pos); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3484,12 +3598,15 @@ void GeomArcOfEllipse::getRange(double& u, double& v, bool emulateCCWXY) const v = myCurve->LastParameter(); if (emulateCCWXY) { if (isReversed()) { - std::swap(u,v); - u = -u; v = -v; - if (v < u) + std::swap(u, v); + u = -u; + v = -v; + if (v < u) { v += 2 * std::numbers::pi; - if (v-u > 2 * std::numbers::pi) + } + if (v - u > 2 * std::numbers::pi) { v -= 2 * std::numbers::pi; + } } } } @@ -3506,25 +3623,26 @@ void GeomArcOfEllipse::setRange(double u, double v, bool emulateCCWXY) try { if (emulateCCWXY) { if (isReversed()) { - std::swap(u,v); - u = -u; v = -v; + std::swap(u, v); + u = -u; + v = -v; } } myCurve->SetTrim(u, v); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomArcOfEllipse::getMemSize () const +unsigned int GeomArcOfEllipse::getMemSize() const { - return sizeof(Geom_Ellipse) + 2 *sizeof(double); + return sizeof(Geom_Ellipse) + 2 * sizeof(double); } -void GeomArcOfEllipse::Save(Base::Writer &writer) const +void GeomArcOfEllipse::Save(Base::Writer& writer) const { // save the attributes of the father class GeomCurve::Save(writer); @@ -3535,34 +3653,33 @@ void GeomArcOfEllipse::Save(Base::Writer &writer) const gp_Dir normal = ellipse->Axis().Direction(); gp_Dir xdir = ellipse->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "MajorRadius() << "\" " - << "MinorRadius=\"" << ellipse->MinorRadius() << "\" " - << "AngleXU=\"" << AngleXU << "\" " - << "StartAngle=\"" << this->myCurve->FirstParameter() << "\" " - << "EndAngle=\"" << this->myCurve->LastParameter() << "\" " - << "/>" << std::endl; + writer.Stream() << writer.ind() << "MajorRadius() << "\" " + << "MinorRadius=\"" << ellipse->MinorRadius() << "\" " + << "AngleXU=\"" << AngleXU << "\" " + << "StartAngle=\"" << this->myCurve->FirstParameter() << "\" " + << "EndAngle=\"" << this->myCurve->LastParameter() << "\" " + << "/>" << std::endl; } -void GeomArcOfEllipse::Restore(Base::XMLReader &reader) +void GeomArcOfEllipse::Restore(Base::XMLReader& reader) { // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,MajorRadius,MinorRadius,AngleXU,StartAngle,EndAngle; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, MajorRadius, MinorRadius, AngleXU, + StartAngle, EndAngle; // read my Element reader.readElement("ArcOfEllipse"); // get the value of my Attribute @@ -3580,23 +3697,25 @@ void GeomArcOfEllipse::Restore(Base::XMLReader &reader) // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { GC_MakeEllipse mc(xdir, MajorRadius, MinorRadius); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } GC_MakeArcOfEllipse ma(mc.Value()->Elips(), StartAngle, EndAngle, Standard_True); - if (!ma.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(ma.Status())) + if (!ma.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(ma.Status())) + } Handle(Geom_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom_Ellipse) tmpellipse = Handle(Geom_Ellipse)::DownCast(tmpcurve->BasisCurve()); @@ -3607,18 +3726,18 @@ void GeomArcOfEllipse::Restore(Base::XMLReader &reader) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomArcOfEllipse::getPyObject() +PyObject* GeomArcOfEllipse::getPyObject() { return new ArcOfEllipsePy(static_cast(this->clone())); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomHyperbola,Part::GeomConic) +TYPESYSTEM_SOURCE(Part::GeomHyperbola, Part::GeomConic) GeomHyperbola::GeomHyperbola() { @@ -3626,27 +3745,27 @@ GeomHyperbola::GeomHyperbola() this->myCurve = h; } -GeomHyperbola::GeomHyperbola(const Handle(Geom_Hyperbola)& h) +GeomHyperbola::GeomHyperbola(const Handle(Geom_Hyperbola) & h) { setHandle(h); } GeomHyperbola::~GeomHyperbola() = default; -const Handle(Geom_Geometry)& GeomHyperbola::handle() const +const Handle(Geom_Geometry) & GeomHyperbola::handle() const { return myCurve; } -void GeomHyperbola::setHandle(const Handle(Geom_Hyperbola)& c) +void GeomHyperbola::setHandle(const Handle(Geom_Hyperbola) & c) { myCurve = Handle(Geom_Hyperbola)::DownCast(c->Copy()); } Geometry* GeomHyperbola::copy() const { - GeomHyperbola *newHyp = new GeomHyperbola(myCurve); + GeomHyperbola* newHyp = new GeomHyperbola(myCurve); newHyp->copyNonTag(this); return newHyp; } @@ -3679,7 +3798,7 @@ void GeomHyperbola::setMajorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3698,12 +3817,12 @@ void GeomHyperbola::setMinorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomHyperbola::getMemSize () const +unsigned int GeomHyperbola::getMemSize() const { return sizeof(Geom_Hyperbola); } @@ -3717,23 +3836,21 @@ void GeomHyperbola::Save(Base::Writer& writer) const gp_Dir normal = this->myCurve->Axis().Direction(); gp_Dir xdir = this->myCurve->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "myCurve->MajorRadius() << "\" " - << "MinorRadius=\"" << this->myCurve->MinorRadius() << "\" " - << "AngleXU=\"" << AngleXU << "\" " - << "/>" << std::endl; + writer.Stream() << writer.ind() << "myCurve->MajorRadius() << "\" " + << "MinorRadius=\"" << this->myCurve->MinorRadius() << "\" " + << "AngleXU=\"" << AngleXU << "\" " + << "/>" << std::endl; } void GeomHyperbola::Restore(Base::XMLReader& reader) @@ -3741,7 +3858,7 @@ void GeomHyperbola::Restore(Base::XMLReader& reader) // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,MajorRadius,MinorRadius,AngleXU; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, MajorRadius, MinorRadius, AngleXU; // read my Element reader.readElement("Hyperbola"); // get the value of my Attribute @@ -3756,82 +3873,85 @@ void GeomHyperbola::Restore(Base::XMLReader& reader) AngleXU = reader.getAttribute("AngleXU"); // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { GC_MakeHyperbola mc(xdir, MajorRadius, MinorRadius); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } this->myCurve = mc.Value(); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomHyperbola::getPyObject() +PyObject* GeomHyperbola::getPyObject() { return new HyperbolaPy(static_cast(this->clone())); } -bool GeomHyperbola::isSame(const Geometry &_other, double tol, double atol) const +bool GeomHyperbola::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomConic::isSame(other,tol,atol) + auto& other = static_cast(_other); + return GeomConic::isSame(other, tol, atol) && fabs(getMajorRadius() - other.getMajorRadius()) <= tol && fabs(getMinorRadius() - other.getMinorRadius()) <= tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomArcOfHyperbola,Part::GeomArcOfConic) +TYPESYSTEM_SOURCE(Part::GeomArcOfHyperbola, Part::GeomArcOfConic) GeomArcOfHyperbola::GeomArcOfHyperbola() { gp_Ax2 ax2 = gp_Ax2(); - Handle(Geom_Hyperbola) h = new Geom_Hyperbola(gp_Hypr(ax2, 1,1)); - this->myCurve = new Geom_TrimmedCurve(h, h->FirstParameter(),h->LastParameter()); + Handle(Geom_Hyperbola) h = new Geom_Hyperbola(gp_Hypr(ax2, 1, 1)); + this->myCurve = new Geom_TrimmedCurve(h, h->FirstParameter(), h->LastParameter()); } -GeomArcOfHyperbola::GeomArcOfHyperbola(const Handle(Geom_Hyperbola)& h) +GeomArcOfHyperbola::GeomArcOfHyperbola(const Handle(Geom_Hyperbola) & h) { setHandle(h); } GeomArcOfHyperbola::~GeomArcOfHyperbola() = default; -void GeomArcOfHyperbola::setHandle(const Handle(Geom_TrimmedCurve)& c) +void GeomArcOfHyperbola::setHandle(const Handle(Geom_TrimmedCurve) & c) { Handle(Geom_Hyperbola) basis = Handle(Geom_Hyperbola)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not an hyperbola"); + } this->myCurve = Handle(Geom_TrimmedCurve)::DownCast(c->Copy()); } -void GeomArcOfHyperbola::setHandle(const Handle(Geom_Hyperbola)& h) +void GeomArcOfHyperbola::setHandle(const Handle(Geom_Hyperbola) & h) { - this->myCurve = new Geom_TrimmedCurve(h, h->FirstParameter(),h->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(h, h->FirstParameter(), h->LastParameter()); } -const Handle(Geom_Geometry)& GeomArcOfHyperbola::handle() const +const Handle(Geom_Geometry) & GeomArcOfHyperbola::handle() const { return myCurve; } -Geometry *GeomArcOfHyperbola::copy() const +Geometry* GeomArcOfHyperbola::copy() const { GeomArcOfHyperbola* copy = new GeomArcOfHyperbola(); copy->setHandle(this->myCurve); @@ -3841,7 +3961,7 @@ Geometry *GeomArcOfHyperbola::copy() const GeomBSplineCurve* GeomArcOfHyperbola::toNurbs(double first, double last) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(curve->BasisCurve()); return GeomHyperbola(hyperbola).toNurbs(first, last); } @@ -3861,7 +3981,7 @@ void GeomArcOfHyperbola::setMajorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3880,7 +4000,7 @@ void GeomArcOfHyperbola::setMinorRadius(double Radius) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -3891,7 +4011,7 @@ void GeomArcOfHyperbola::setMinorRadius(double Radius) */ Base::Vector3d GeomArcOfHyperbola::getMajorAxisDir() const { - Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast( myCurve->BasisCurve() ); + Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); gp_Dir xdir = c->XAxis().Direction(); return Base::Vector3d(xdir.X(), xdir.Y(), xdir.Z()); @@ -3903,7 +4023,7 @@ Base::Vector3d GeomArcOfHyperbola::getMajorAxisDir() const */ Base::Vector3d GeomArcOfHyperbola::getMinorAxisDir() const { - Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast( myCurve->BasisCurve() ); + Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); gp_Dir ydir = c->YAxis().Direction(); return Base::Vector3d(ydir.X(), ydir.Y(), ydir.Z()); @@ -3919,26 +4039,30 @@ Base::Vector3d GeomArcOfHyperbola::getMinorAxisDir() const */ void GeomArcOfHyperbola::setMajorAxisDir(Base::Vector3d newdir) { - Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast( myCurve->BasisCurve() ); + Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); - if (newdir.Sqr() < Precision::SquareConfusion()) - return;//zero vector was passed. Keep the old orientation. + if (newdir.Sqr() < Precision::SquareConfusion()) { + return; // zero vector was passed. Keep the old orientation. + } try { gp_Ax2 pos = c->Position(); - pos.SetXDirection(gp_Dir(newdir.x, newdir.y, newdir.z));//OCC should keep the old main Direction (Z), and change YDirection to accommodate the new XDirection. + pos.SetXDirection( + gp_Dir(newdir.x, newdir.y, newdir.z) + ); // OCC should keep the old main Direction (Z), and change YDirection to accommodate the + // new XDirection. c->SetPosition(pos); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } void GeomArcOfHyperbola::getRange(double& u, double& v, bool emulateCCWXY) const { try { - if (emulateCCWXY){ + if (emulateCCWXY) { if (isReversed()) { Handle(Geom_Hyperbola) c = Handle(Geom_Hyperbola)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); @@ -3948,7 +4072,7 @@ void GeomArcOfHyperbola::getRange(double& u, double& v, bool emulateCCWXY) const } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } u = myCurve->FirstParameter(); @@ -3970,17 +4094,17 @@ void GeomArcOfHyperbola::setRange(double u, double v, bool emulateCCWXY) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomArcOfHyperbola::getMemSize () const +unsigned int GeomArcOfHyperbola::getMemSize() const { - return sizeof(Geom_Hyperbola) + 2 *sizeof(double); + return sizeof(Geom_Hyperbola) + 2 * sizeof(double); } -void GeomArcOfHyperbola::Save(Base::Writer &writer) const +void GeomArcOfHyperbola::Save(Base::Writer& writer) const { // save the attributes of the father class GeomCurve::Save(writer); @@ -3991,33 +4115,32 @@ void GeomArcOfHyperbola::Save(Base::Writer &writer) const gp_Dir normal = h->Axis().Direction(); gp_Dir xdir = h->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "MajorRadius() << "\" " - << "MinorRadius=\"" << h->MinorRadius() << "\" " - << "AngleXU=\"" << AngleXU << "\" " - << "StartAngle=\"" << this->myCurve->FirstParameter() << "\" " - << "EndAngle=\"" << this->myCurve->LastParameter() << "\" " - << "/>" << std::endl; + writer.Stream() << writer.ind() << "MajorRadius() << "\" " + << "MinorRadius=\"" << h->MinorRadius() << "\" " + << "AngleXU=\"" << AngleXU << "\" " + << "StartAngle=\"" << this->myCurve->FirstParameter() << "\" " + << "EndAngle=\"" << this->myCurve->LastParameter() << "\" " + << "/>" << std::endl; } -void GeomArcOfHyperbola::Restore(Base::XMLReader &reader) +void GeomArcOfHyperbola::Restore(Base::XMLReader& reader) { // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,MajorRadius,MinorRadius,AngleXU,StartAngle,EndAngle; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, MajorRadius, MinorRadius, AngleXU, + StartAngle, EndAngle; // read my Element reader.readElement("ArcOfHyperbola"); // get the value of my Attribute @@ -4035,44 +4158,48 @@ void GeomArcOfHyperbola::Restore(Base::XMLReader &reader) // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { GC_MakeHyperbola mc(xdir, MajorRadius, MinorRadius); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } GC_MakeArcOfHyperbola ma(mc.Value()->Hypr(), StartAngle, EndAngle, Standard_True); - if (!ma.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(ma.Status())) + if (!ma.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(ma.Status())) + } Handle(Geom_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom_Hyperbola) tmphyperbola = Handle(Geom_Hyperbola)::DownCast(tmpcurve->BasisCurve()); - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(this->myCurve->BasisCurve()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + this->myCurve->BasisCurve() + ); hyperbola->SetHypr(tmphyperbola->Hypr()); this->myCurve->SetTrim(tmpcurve->FirstParameter(), tmpcurve->LastParameter()); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomArcOfHyperbola::getPyObject() +PyObject* GeomArcOfHyperbola::getPyObject() { return new ArcOfHyperbolaPy(static_cast(this->clone())); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomParabola,Part::GeomConic) +TYPESYSTEM_SOURCE(Part::GeomParabola, Part::GeomConic) GeomParabola::GeomParabola() { @@ -4080,26 +4207,26 @@ GeomParabola::GeomParabola() this->myCurve = p; } -GeomParabola::GeomParabola(const Handle(Geom_Parabola)& p) +GeomParabola::GeomParabola(const Handle(Geom_Parabola) & p) { setHandle(p); } GeomParabola::~GeomParabola() = default; -const Handle(Geom_Geometry)& GeomParabola::handle() const +const Handle(Geom_Geometry) & GeomParabola::handle() const { return myCurve; } -void GeomParabola::setHandle(const Handle(Geom_Parabola)& c) +void GeomParabola::setHandle(const Handle(Geom_Parabola) & c) { myCurve = Handle(Geom_Parabola)::DownCast(c->Copy()); } -Geometry *GeomParabola::copy() const +Geometry* GeomParabola::copy() const { - GeomParabola *newPar = new GeomParabola(myCurve); + GeomParabola* newPar = new GeomParabola(myCurve); newPar->copyNonTag(this); return newPar; } @@ -4116,7 +4243,7 @@ GeomBSplineCurve* GeomParabola::toNurbs(double first, double last) const { // the default implementation suffices because a non-rational B-spline with // one segment is a parabola - return GeomCurve::toNurbs(first, last); // NOLINT + return GeomCurve::toNurbs(first, last); // NOLINT } double GeomParabola::getFocal() const @@ -4134,12 +4261,12 @@ void GeomParabola::setFocal(double length) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomParabola::getMemSize () const +unsigned int GeomParabola::getMemSize() const { return sizeof(Geom_Parabola); } @@ -4153,22 +4280,20 @@ void GeomParabola::Save(Base::Writer& writer) const gp_Dir normal = this->myCurve->Axis().Direction(); gp_Dir xdir = this->myCurve->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "myCurve->Focal() << "\" " - << "AngleXU=\"" << AngleXU << "\" " - << "/>" << std::endl; + writer.Stream() << writer.ind() << "myCurve->Focal() << "\" " + << "AngleXU=\"" << AngleXU << "\" " + << "/>" << std::endl; } void GeomParabola::Restore(Base::XMLReader& reader) @@ -4176,7 +4301,7 @@ void GeomParabola::Restore(Base::XMLReader& reader) // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,Focal,AngleXU; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, Focal, AngleXU; // read my Element reader.readElement("Parabola"); // get the value of my Attribute @@ -4190,78 +4315,81 @@ void GeomParabola::Restore(Base::XMLReader& reader) AngleXU = reader.getAttribute("AngleXU"); // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { gce_MakeParab mc(xdir, Focal); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } this->myCurve = new Geom_Parabola(mc.Value()); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomParabola::getPyObject() +PyObject* GeomParabola::getPyObject() { return new ParabolaPy(static_cast(this->clone())); } -bool GeomParabola::isSame(const Geometry &_other, double tol, double atol) const +bool GeomParabola::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomConic::isSame(other,tol,atol) && fabs(getFocal() - other.getFocal()) < tol; + auto& other = static_cast(_other); + return GeomConic::isSame(other, tol, atol) && fabs(getFocal() - other.getFocal()) < tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomArcOfParabola,Part::GeomArcOfConic) +TYPESYSTEM_SOURCE(Part::GeomArcOfParabola, Part::GeomArcOfConic) GeomArcOfParabola::GeomArcOfParabola() { Handle(Geom_Parabola) p = new Geom_Parabola(gp_Parab()); - this->myCurve = new Geom_TrimmedCurve(p, p->FirstParameter(),p->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(p, p->FirstParameter(), p->LastParameter()); } -GeomArcOfParabola::GeomArcOfParabola(const Handle(Geom_Parabola)& h) +GeomArcOfParabola::GeomArcOfParabola(const Handle(Geom_Parabola) & h) { setHandle(h); } GeomArcOfParabola::~GeomArcOfParabola() = default; -void GeomArcOfParabola::setHandle(const Handle(Geom_TrimmedCurve)& c) +void GeomArcOfParabola::setHandle(const Handle(Geom_TrimmedCurve) & c) { Handle(Geom_Parabola) basis = Handle(Geom_Parabola)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not a parabola"); + } this->myCurve = Handle(Geom_TrimmedCurve)::DownCast(c->Copy()); } -void GeomArcOfParabola::setHandle(const Handle(Geom_Parabola)& h) +void GeomArcOfParabola::setHandle(const Handle(Geom_Parabola) & h) { - this->myCurve = new Geom_TrimmedCurve(h, h->FirstParameter(),h->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(h, h->FirstParameter(), h->LastParameter()); } -const Handle(Geom_Geometry)& GeomArcOfParabola::handle() const +const Handle(Geom_Geometry) & GeomArcOfParabola::handle() const { return myCurve; } -Geometry *GeomArcOfParabola::copy() const +Geometry* GeomArcOfParabola::copy() const { GeomArcOfParabola* copy = new GeomArcOfParabola(); copy->setHandle(this->myCurve); @@ -4271,7 +4399,7 @@ Geometry *GeomArcOfParabola::copy() const GeomBSplineCurve* GeomArcOfParabola::toNurbs(double first, double last) const { - Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); + Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast(curve->BasisCurve()); return GeomParabola(parabola).toNurbs(first, last); } @@ -4291,7 +4419,7 @@ void GeomArcOfParabola::setFocal(double length) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } @@ -4300,7 +4428,7 @@ Base::Vector3d GeomArcOfParabola::getFocus() const Handle(Geom_Parabola) p = Handle(Geom_Parabola)::DownCast(myCurve->BasisCurve()); gp_Pnt gp = p->Focus(); - return Base::Vector3d(gp.X(),gp.Y(),gp.Z()); + return Base::Vector3d(gp.X(), gp.Y(), gp.Z()); } void GeomArcOfParabola::getRange(double& u, double& v, bool emulateCCWXY) const @@ -4316,7 +4444,7 @@ void GeomArcOfParabola::getRange(double& u, double& v, bool emulateCCWXY) const } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } u = myCurve->FirstParameter(); @@ -4337,17 +4465,17 @@ void GeomArcOfParabola::setRange(double u, double v, bool emulateCCWXY) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomArcOfParabola::getMemSize () const +unsigned int GeomArcOfParabola::getMemSize() const { - return sizeof(Geom_Parabola) + 2 *sizeof(double); + return sizeof(Geom_Parabola) + 2 * sizeof(double); } -void GeomArcOfParabola::Save(Base::Writer &writer) const +void GeomArcOfParabola::Save(Base::Writer& writer) const { // save the attributes of the father class GeomCurve::Save(writer); @@ -4358,32 +4486,30 @@ void GeomArcOfParabola::Save(Base::Writer &writer) const gp_Dir normal = p->Axis().Direction(); gp_Dir xdir = p->XAxis().Direction(); - gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse + gp_Ax2 xdirref(center, normal); // this is a reference XY for the ellipse - double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(),normal); + double AngleXU = -xdir.AngleWithRef(xdirref.XDirection(), normal); - writer.Stream() - << writer.ind() - << "Focal() << "\" " - << "AngleXU=\"" << AngleXU << "\" " - << "StartAngle=\"" << this->myCurve->FirstParameter() << "\" " - << "EndAngle=\"" << this->myCurve->LastParameter() << "\" " - << "/>" << std::endl; + writer.Stream() << writer.ind() << "Focal() << "\" " + << "AngleXU=\"" << AngleXU << "\" " + << "StartAngle=\"" << this->myCurve->FirstParameter() << "\" " + << "EndAngle=\"" << this->myCurve->LastParameter() << "\" " + << "/>" << std::endl; } -void GeomArcOfParabola::Restore(Base::XMLReader &reader) +void GeomArcOfParabola::Restore(Base::XMLReader& reader) { // read the attributes of the father class GeomCurve::Restore(reader); - double CenterX,CenterY,CenterZ,NormalX,NormalY,NormalZ,Focal,AngleXU,StartAngle,EndAngle; + double CenterX, CenterY, CenterZ, NormalX, NormalY, NormalZ, Focal, AngleXU, StartAngle, EndAngle; // read my Element reader.readElement("ArcOfParabola"); // get the value of my Attribute @@ -4400,23 +4526,25 @@ void GeomArcOfParabola::Restore(Base::XMLReader &reader) // set the read geometry - gp_Pnt p1(CenterX,CenterY,CenterZ); - gp_Dir norm(NormalX,NormalY,NormalZ); + gp_Pnt p1(CenterX, CenterY, CenterZ); + gp_Dir norm(NormalX, NormalY, NormalZ); - gp_Ax1 normaxis(p1,norm); + gp_Ax1 normaxis(p1, norm); gp_Ax2 xdir(p1, norm); - xdir.Rotate(normaxis,AngleXU); + xdir.Rotate(normaxis, AngleXU); try { gce_MakeParab mc(xdir, Focal); - if (!mc.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(mc.Status())) + if (!mc.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(mc.Status())) + } GC_MakeArcOfParabola ma(mc.Value(), StartAngle, EndAngle, Standard_True); - if (!ma.IsDone()) - THROWM(Base::CADKernelError,gce_ErrorStatusText(ma.Status())) + if (!ma.IsDone()) { + THROWM(Base::CADKernelError, gce_ErrorStatusText(ma.Status())) + } Handle(Geom_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom_Parabola) tmpparabola = Handle(Geom_Parabola)::DownCast(tmpcurve->BasisCurve()); @@ -4427,18 +4555,18 @@ void GeomArcOfParabola::Restore(Base::XMLReader &reader) } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } -PyObject *GeomArcOfParabola::getPyObject() +PyObject* GeomArcOfParabola::getPyObject() { return new ArcOfParabolaPy(static_cast(this->clone())); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomLine,Part::GeomCurve) +TYPESYSTEM_SOURCE(Part::GeomLine, Part::GeomCurve) GeomLine::GeomLine() { @@ -4446,14 +4574,14 @@ GeomLine::GeomLine() this->myCurve = c; } -GeomLine::GeomLine(const Handle(Geom_Line)& l) +GeomLine::GeomLine(const Handle(Geom_Line) & l) { setHandle(l); } GeomLine::GeomLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir) { - this->myCurve = new Geom_Line(gp_Pnt(Pos.x,Pos.y,Pos.z),gp_Dir(Dir.x,Dir.y,Dir.z)); + this->myCurve = new Geom_Line(gp_Pnt(Pos.x, Pos.y, Pos.z), gp_Dir(Dir.x, Dir.y, Dir.z)); } @@ -4461,71 +4589,65 @@ GeomLine::~GeomLine() = default; void GeomLine::setLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir) { - this->myCurve->SetLocation(gp_Pnt(Pos.x,Pos.y,Pos.z)); - this->myCurve->SetDirection(gp_Dir(Dir.x,Dir.y,Dir.z)); + this->myCurve->SetLocation(gp_Pnt(Pos.x, Pos.y, Pos.z)); + this->myCurve->SetDirection(gp_Dir(Dir.x, Dir.y, Dir.z)); } Base::Vector3d GeomLine::getPos() const { gp_Pnt Pos = this->myCurve->Lin().Location(); - return Base::Vector3d(Pos.X(),Pos.Y(),Pos.Z()); + return Base::Vector3d(Pos.X(), Pos.Y(), Pos.Z()); } Base::Vector3d GeomLine::getDir() const { gp_Dir Dir = this->myCurve->Lin().Direction(); - return Base::Vector3d(Dir.X(),Dir.Y(),Dir.Z()); + return Base::Vector3d(Dir.X(), Dir.Y(), Dir.Z()); } -const Handle(Geom_Geometry)& GeomLine::handle() const +const Handle(Geom_Geometry) & GeomLine::handle() const { return myCurve; } -void GeomLine::setHandle(const Handle(Geom_Line)& l) +void GeomLine::setHandle(const Handle(Geom_Line) & l) { this->myCurve = Handle(Geom_Line)::DownCast(l->Copy()); } -Geometry *GeomLine::copy() const +Geometry* GeomLine::copy() const { - GeomLine *newLine = new GeomLine(myCurve); + GeomLine* newLine = new GeomLine(myCurve); newLine->copyNonTag(this); return newLine; } // Persistence implementer -unsigned int GeomLine::getMemSize () const +unsigned int GeomLine::getMemSize() const { return sizeof(Geom_Line); } -void GeomLine::Save(Base::Writer &writer) const +void GeomLine::Save(Base::Writer& writer) const { // save the attributes of the father class Geometry::Save(writer); - Base::Vector3d Pos = getPos(); - Base::Vector3d Dir = getDir(); + Base::Vector3d Pos = getPos(); + Base::Vector3d Dir = getDir(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; } -void GeomLine::Restore(Base::XMLReader &reader) +void GeomLine::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geometry::Restore(reader); - double PosX,PosY,PosZ,DirX,DirY,DirZ; + double PosX, PosY, PosZ, DirX, DirY, DirZ; // read my Element reader.readElement("GeomLine"); // get the value of my Attribute @@ -4537,71 +4659,73 @@ void GeomLine::Restore(Base::XMLReader &reader) DirZ = reader.getAttribute("DirZ"); // set the read geometry - setLine(Base::Vector3d(PosX,PosY,PosZ),Base::Vector3d(DirX,DirY,DirZ) ); + setLine(Base::Vector3d(PosX, PosY, PosZ), Base::Vector3d(DirX, DirY, DirZ)); } -PyObject *GeomLine::getPyObject() +PyObject* GeomLine::getPyObject() { return new LinePy(static_cast(this->clone())); } -bool GeomLine::isSame(const Geometry &_other, double tol, double atol) const +bool GeomLine::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) { + if (_other.getTypeId() != getTypeId()) { if (_other.isDerivedFrom()) { std::unique_ptr geo(static_cast(_other).toLine()); - if (geo) + if (geo) { return isSame(*geo, tol, atol); + } } return false; } - auto &other = dynamic_cast(_other); + auto& other = dynamic_cast(_other); return getDir().GetAngle(other.getDir()) <= atol - && Base::DistanceP2(getPos(), other.getPos()) <= tol*tol; + && Base::DistanceP2(getPos(), other.getPos()) <= tol * tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomLineSegment,Part::GeomTrimmedCurve) +TYPESYSTEM_SOURCE(Part::GeomLineSegment, Part::GeomTrimmedCurve) GeomLineSegment::GeomLineSegment() { gp_Lin line; - line.SetLocation(gp_Pnt(0.0,0.0,0.0)); - line.SetDirection(gp_Dir(0.0,0.0,1.0)); + line.SetLocation(gp_Pnt(0.0, 0.0, 0.0)); + line.SetDirection(gp_Dir(0.0, 0.0, 1.0)); Handle(Geom_Line) c = new Geom_Line(line); - this->myCurve = new Geom_TrimmedCurve(c, 0.0,1.0); + this->myCurve = new Geom_TrimmedCurve(c, 0.0, 1.0); } -GeomLineSegment::GeomLineSegment(const Handle(Geom_Line)& l) +GeomLineSegment::GeomLineSegment(const Handle(Geom_Line) & l) { setHandle(l); } GeomLineSegment::~GeomLineSegment() = default; -void GeomLineSegment::setHandle(const Handle(Geom_TrimmedCurve)& c) +void GeomLineSegment::setHandle(const Handle(Geom_TrimmedCurve) & c) { Handle(Geom_Line) basis = Handle(Geom_Line)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not a line"); + } this->myCurve = Handle(Geom_TrimmedCurve)::DownCast(c->Copy()); } -void GeomLineSegment::setHandle(const Handle(Geom_Line)& l) +void GeomLineSegment::setHandle(const Handle(Geom_Line) & l) { - this->myCurve = new Geom_TrimmedCurve(l, l->FirstParameter(),l->LastParameter()); + this->myCurve = new Geom_TrimmedCurve(l, l->FirstParameter(), l->LastParameter()); } -const Handle(Geom_Geometry)& GeomLineSegment::handle() const +const Handle(Geom_Geometry) & GeomLineSegment::handle() const { return myCurve; } -Geometry *GeomLineSegment::copy()const +Geometry* GeomLineSegment::copy() const { - auto *tempCurve = new GeomLineSegment(); + auto* tempCurve = new GeomLineSegment(); tempCurve->myCurve = Handle(Geom_TrimmedCurve)::DownCast(myCurve->Copy()); tempCurve->copyNonTag(this); return tempCurve; @@ -4623,90 +4747,85 @@ Base::Vector3d GeomLineSegment::getEndPoint() const void GeomLineSegment::setPoints(const Base::Vector3d& Start, const Base::Vector3d& End) { - gp_Pnt p1(Start.x,Start.y,Start.z), p2(End.x,End.y,End.z); + gp_Pnt p1(Start.x, Start.y, Start.z), p2(End.x, End.y, End.z); Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast(handle()); try { // Create line out of two points - if (p1.Distance(p2) < gp::Resolution()) - THROWM(Base::ValueError,"Both points are equal"); + if (p1.Distance(p2) < gp::Resolution()) { + THROWM(Base::ValueError, "Both points are equal"); + } GC_MakeSegment ms(p1, p2); if (!ms.IsDone()) { - THROWM(Base::CADKernelError,gce_ErrorStatusText(ms.Status())) + THROWM(Base::CADKernelError, gce_ErrorStatusText(ms.Status())) } // get Geom_Line of line segment - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); - Handle(Geom_TrimmedCurve)& that_curv = - const_cast&>(ms.Value()); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) & that_curv = const_cast&>( + ms.Value() + ); Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin(that_line->Lin()); this_curv->SetTrim(that_curv->FirstParameter(), that_curv->LastParameter()); } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomLineSegment::getMemSize () const +unsigned int GeomLineSegment::getMemSize() const { return sizeof(Geom_TrimmedCurve) + sizeof(Geom_Line); } -void GeomLineSegment::Save (Base::Writer &writer) const +void GeomLineSegment::Save(Base::Writer& writer) const { // save the attributes of the father class Geometry::Save(writer); - Base::Vector3d End = getEndPoint(); - Base::Vector3d Start = getStartPoint(); + Base::Vector3d End = getEndPoint(); + Base::Vector3d Start = getStartPoint(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; } -void GeomLineSegment::Restore (Base::XMLReader &reader) +void GeomLineSegment::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geometry::Restore(reader); - double StartX,StartY,StartZ,EndX,EndY,EndZ; + double StartX, StartY, StartZ, EndX, EndY, EndZ; // read my Element reader.readElement("LineSegment"); // get the value of my Attribute StartX = reader.getAttribute("StartX"); StartY = reader.getAttribute("StartY"); StartZ = reader.getAttribute("StartZ"); - EndX = reader.getAttribute("EndX"); - EndY = reader.getAttribute("EndY"); - EndZ = reader.getAttribute("EndZ"); + EndX = reader.getAttribute("EndX"); + EndY = reader.getAttribute("EndY"); + EndZ = reader.getAttribute("EndZ"); - Base::Vector3d start(StartX,StartY,StartZ); - Base::Vector3d end(EndX,EndY,EndZ); + Base::Vector3d start(StartX, StartY, StartZ); + Base::Vector3d end(EndX, EndY, EndZ); // set the read geometry try { setPoints(start, end); } - catch(Base::ValueError&) { + catch (Base::ValueError&) { // for a line segment construction, the only possibility of a value error is that // the points are too close. The best try to restore is incrementing the distance. // for other objects, the best effort may be just to leave default values. reader.setPartialRestore(true); - constexpr double increment{std::numeric_limits::epsilon()}; - if(start.x == 0) { + constexpr double increment {std::numeric_limits::epsilon()}; + if (start.x == 0) { end = start + Base::Vector3d(increment, 0, 0); } else { @@ -4717,36 +4836,36 @@ void GeomLineSegment::Restore (Base::XMLReader &reader) } } -PyObject *GeomLineSegment::getPyObject() +PyObject* GeomLineSegment::getPyObject() { return new LineSegmentPy(freecad_cast(this->clone())); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomOffsetCurve,Part::GeomCurve) +TYPESYSTEM_SOURCE(Part::GeomOffsetCurve, Part::GeomCurve) GeomOffsetCurve::GeomOffsetCurve() = default; -GeomOffsetCurve::GeomOffsetCurve(const Handle(Geom_Curve)& c, double offset, const gp_Dir& dir) +GeomOffsetCurve::GeomOffsetCurve(const Handle(Geom_Curve) & c, double offset, const gp_Dir& dir) { this->myCurve = new Geom_OffsetCurve(c, offset, dir); } -GeomOffsetCurve::GeomOffsetCurve(const Handle(Geom_Curve)& c, double offset, Base::Vector3d& dir):GeomOffsetCurve(c,offset,gp_Dir(dir.x,dir.y,dir.z)) -{ -} +GeomOffsetCurve::GeomOffsetCurve(const Handle(Geom_Curve) & c, double offset, Base::Vector3d& dir) + : GeomOffsetCurve(c, offset, gp_Dir(dir.x, dir.y, dir.z)) +{} -GeomOffsetCurve::GeomOffsetCurve(const Handle(Geom_OffsetCurve)& c) +GeomOffsetCurve::GeomOffsetCurve(const Handle(Geom_OffsetCurve) & c) { setHandle(c); } GeomOffsetCurve::~GeomOffsetCurve() = default; -Geometry *GeomOffsetCurve::copy() const +Geometry* GeomOffsetCurve::copy() const { - auto *newCurve = new GeomOffsetCurve(myCurve); + auto* newCurve = new GeomOffsetCurve(myCurve); newCurve->copyNonTag(this); return newCurve; } @@ -4754,7 +4873,7 @@ Geometry *GeomOffsetCurve::copy() const Base::Vector3d GeomOffsetCurve::getDir() const { gp_Dir Dir = this->myCurve->Direction(); - return Base::Vector3d(Dir.X(),Dir.Y(),Dir.Z()); + return Base::Vector3d(Dir.X(), Dir.Y(), Dir.Z()); } double GeomOffsetCurve::getOffset() const @@ -4762,50 +4881,54 @@ double GeomOffsetCurve::getOffset() const return this->myCurve->Offset(); } -void GeomOffsetCurve::setHandle(const Handle(Geom_OffsetCurve)& c) +void GeomOffsetCurve::setHandle(const Handle(Geom_OffsetCurve) & c) { this->myCurve = Handle(Geom_OffsetCurve)::DownCast(c->Copy()); } -const Handle(Geom_Geometry)& GeomOffsetCurve::handle() const +const Handle(Geom_Geometry) & GeomOffsetCurve::handle() const { return this->myCurve; } // Persistence implementer -unsigned int GeomOffsetCurve::getMemSize () const +unsigned int GeomOffsetCurve::getMemSize() const { return sizeof(Geom_OffsetCurve); } -void GeomOffsetCurve::Save(Base::Writer &/*writer*/) const +void GeomOffsetCurve::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomOffsetCurve::Save"); } -void GeomOffsetCurve::Restore(Base::XMLReader &/*reader*/) +void GeomOffsetCurve::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomOffsetCurve::Restore"); } -PyObject *GeomOffsetCurve::getPyObject() +PyObject* GeomOffsetCurve::getPyObject() { return new OffsetCurvePy(freecad_cast(this->clone())); } -bool GeomOffsetCurve::isSame(const Geometry &_other, double tol, double atol) const +bool GeomOffsetCurve::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = dynamic_cast(_other); - if(myCurve->Direction().Angle(other.myCurve->Direction()) > atol || fabs(getOffset() - other.getOffset()) > tol) + auto& other = dynamic_cast(_other); + if (myCurve->Direction().Angle(other.myCurve->Direction()) > atol + || fabs(getOffset() - other.getOffset()) > tol) { return false; + } Handle(Geom_Curve) basis = myCurve->BasisCurve(); Handle(Geom_Curve) basis1 = other.myCurve->BasisCurve(); - if(basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) + if (basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) { return false; + } std::unique_ptr b(makeFromCurve(basis)); std::unique_ptr b1(makeFromCurve(basis1)); @@ -4815,25 +4938,27 @@ bool GeomOffsetCurve::isSame(const Geometry &_other, double tol, double atol) co // ------------------------------------------------- -TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomSurface,Part::Geometry) +TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomSurface, Part::Geometry) GeomSurface::GeomSurface() = default; GeomSurface::~GeomSurface() = default; -bool GeomSurface::isPlanar(gp_Pln *pln, double tol) const +bool GeomSurface::isPlanar(gp_Pln* pln, double tol) const { Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(handle()); return isPlanar(s, pln, tol); } -bool GeomSurface::isPlanar(const Handle(Geom_Surface) &s, gp_Pln *pln, double tol) +bool GeomSurface::isPlanar(const Handle(Geom_Surface) & s, gp_Pln* pln, double tol) { GeomLib_IsPlanarSurface check(s, tol); - if (!check.IsPlanar()) + if (!check.IsPlanar()) { return false; - if (pln) + } + if (pln) { *pln = check.Plan(); + } return true; } @@ -4878,7 +5003,7 @@ TopoDS_Shape GeomSurface::toShape() const bool GeomSurface::tangentU(double u, double v, gp_Dir& dirU) const { Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(handle()); - GeomLProp_SLProps prop(s,u,v,2,Precision::Confusion()); + GeomLProp_SLProps prop(s, u, v, 2, Precision::Confusion()); if (prop.IsTangentUDefined()) { prop.TangentU(dirU); return true; @@ -4889,7 +5014,7 @@ bool GeomSurface::tangentU(double u, double v, gp_Dir& dirU) const bool GeomSurface::tangentV(double u, double v, gp_Dir& dirV) const { Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(handle()); - GeomLProp_SLProps prop(s,u,v,2,Precision::Confusion()); + GeomLProp_SLProps prop(s, u, v, 2, Precision::Confusion()); if (prop.IsTangentVDefined()) { prop.TangentV(dirV); return true; @@ -4927,93 +5052,93 @@ gp_Vec GeomSurface::getDN(double u, double v, int Nu, int Nv) const bool GeomSurface::isUmbillic(double u, double v) const { Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(handle()); - GeomLProp_SLProps prop(s,u,v,2,Precision::Confusion()); + GeomLProp_SLProps prop(s, u, v, 2, Precision::Confusion()); if (prop.IsCurvatureDefined()) { return prop.IsUmbilic(); } - THROWM(Base::RuntimeError,"No curvature defined") + THROWM(Base::RuntimeError, "No curvature defined") } double GeomSurface::curvature(double u, double v, Curvature type) const { Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(handle()); - GeomLProp_SLProps prop(s,u,v,2,Precision::Confusion()); + GeomLProp_SLProps prop(s, u, v, 2, Precision::Confusion()); if (prop.IsCurvatureDefined()) { double value = 0; switch (type) { - case Maximum: - value = prop.MaxCurvature(); - break; - case Minimum: - value = prop.MinCurvature(); - break; - case Mean: - value = prop.MeanCurvature(); - break; - case Gaussian: - value = prop.GaussianCurvature(); - break; + case Maximum: + value = prop.MaxCurvature(); + break; + case Minimum: + value = prop.MinCurvature(); + break; + case Mean: + value = prop.MeanCurvature(); + break; + case Gaussian: + value = prop.GaussianCurvature(); + break; } return value; } - THROWM(Base::RuntimeError,"No curvature defined") + THROWM(Base::RuntimeError, "No curvature defined") } void GeomSurface::curvatureDirections(double u, double v, gp_Dir& maxD, gp_Dir& minD) const { Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(handle()); - GeomLProp_SLProps prop(s,u,v,2,Precision::Confusion()); + GeomLProp_SLProps prop(s, u, v, 2, Precision::Confusion()); if (prop.IsCurvatureDefined()) { prop.CurvatureDirections(maxD, minD); return; } - THROWM(Base::RuntimeError,"No curvature defined") + THROWM(Base::RuntimeError, "No curvature defined") } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomBezierSurface,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomBezierSurface, Part::GeomSurface) GeomBezierSurface::GeomBezierSurface() { - TColgp_Array2OfPnt poles(1,2,1,2); - poles(1,1) = gp_Pnt(0.0,0.0,0.0); - poles(2,1) = gp_Pnt(1.0,0.0,0.0); - poles(1,2) = gp_Pnt(0.0,1.0,0.0); - poles(2,2) = gp_Pnt(1.0,1.0,0.0); + TColgp_Array2OfPnt poles(1, 2, 1, 2); + poles(1, 1) = gp_Pnt(0.0, 0.0, 0.0); + poles(2, 1) = gp_Pnt(1.0, 0.0, 0.0); + poles(1, 2) = gp_Pnt(0.0, 1.0, 0.0); + poles(2, 2) = gp_Pnt(1.0, 1.0, 0.0); this->mySurface = new Geom_BezierSurface(poles); } -GeomBezierSurface::GeomBezierSurface(const Handle(Geom_BezierSurface)& b) +GeomBezierSurface::GeomBezierSurface(const Handle(Geom_BezierSurface) & b) { setHandle(b); } GeomBezierSurface::~GeomBezierSurface() = default; -const Handle(Geom_Geometry)& GeomBezierSurface::handle() const +const Handle(Geom_Geometry) & GeomBezierSurface::handle() const { return mySurface; } -void GeomBezierSurface::setHandle(const Handle(Geom_BezierSurface)& b) +void GeomBezierSurface::setHandle(const Handle(Geom_BezierSurface) & b) { this->mySurface = Handle(Geom_BezierSurface)::DownCast(b->Copy()); } -Geometry *GeomBezierSurface::copy() const +Geometry* GeomBezierSurface::copy() const { - auto *newSurf = new GeomBezierSurface(mySurface); + auto* newSurf = new GeomBezierSurface(mySurface); newSurf->copyNonTag(this); return newSurf; } // Persistence implementer -unsigned int GeomBezierSurface::getMemSize () const +unsigned int GeomBezierSurface::getMemSize() const { unsigned int size = sizeof(Geom_BezierSurface); if (!mySurface.IsNull()) { @@ -5025,42 +5150,44 @@ unsigned int GeomBezierSurface::getMemSize () const return size; } -void GeomBezierSurface::Save(Base::Writer &/*writer*/) const +void GeomBezierSurface::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomBezierSurface::Save"); } -void GeomBezierSurface::Restore(Base::XMLReader &/*reader*/) +void GeomBezierSurface::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomBezierSurface::Restore"); } -PyObject *GeomBezierSurface::getPyObject() +PyObject* GeomBezierSurface::getPyObject() { return new BezierSurfacePy(static_cast(this->clone())); } -bool GeomBezierSurface::isSame(const Geometry &_other, double tol, double atol) const +bool GeomBezierSurface::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = static_cast(_other); + auto& other = static_cast(_other); Standard_Integer uc = mySurface->NbUPoles(); Standard_Integer vc = mySurface->NbVPoles(); - if(uc != other.mySurface->NbUPoles() - || vc != other.mySurface->NbVPoles() - || mySurface->UDegree() != other.mySurface->UDegree() - || mySurface->VDegree() != other.mySurface->VDegree()) + if (uc != other.mySurface->NbUPoles() || vc != other.mySurface->NbVPoles() + || mySurface->UDegree() != other.mySurface->UDegree() + || mySurface->VDegree() != other.mySurface->VDegree()) { return false; + } (void)atol; - double tol2 = tol*tol; - for(Standard_Integer u=1; u<=uc; ++u) { - for(Standard_Integer v=1; v<=vc; ++v) { - if(mySurface->Pole(u,v).SquareDistance(other.mySurface->Pole(u,v)) > tol2 - || fabs(mySurface->Weight(u,v) - other.mySurface->Weight(u,v)) > tol) + double tol2 = tol * tol; + for (Standard_Integer u = 1; u <= uc; ++u) { + for (Standard_Integer v = 1; v <= vc; ++v) { + if (mySurface->Pole(u, v).SquareDistance(other.mySurface->Pole(u, v)) > tol2 + || fabs(mySurface->Weight(u, v) - other.mySurface->Weight(u, v)) > tol) { return false; + } } } return true; @@ -5068,47 +5195,47 @@ bool GeomBezierSurface::isSame(const Geometry &_other, double tol, double atol) // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomBSplineSurface,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomBSplineSurface, Part::GeomSurface) GeomBSplineSurface::GeomBSplineSurface() { - TColgp_Array2OfPnt poles(1,2,1,2); - poles(1,1) = gp_Pnt(0.0,0.0,0.0); - poles(2,1) = gp_Pnt(1.0,0.0,0.0); - poles(1,2) = gp_Pnt(0.0,1.0,0.0); - poles(2,2) = gp_Pnt(1.0,1.0,0.0); + TColgp_Array2OfPnt poles(1, 2, 1, 2); + poles(1, 1) = gp_Pnt(0.0, 0.0, 0.0); + poles(2, 1) = gp_Pnt(1.0, 0.0, 0.0); + poles(1, 2) = gp_Pnt(0.0, 1.0, 0.0); + poles(2, 2) = gp_Pnt(1.0, 1.0, 0.0); - TColStd_Array1OfReal knots(1,2); + TColStd_Array1OfReal knots(1, 2); knots(1) = 0.0; knots(2) = 1.0; - TColStd_Array1OfInteger mults(1,2); + TColStd_Array1OfInteger mults(1, 2); mults(1) = 2; mults(2) = 2; this->mySurface = new Geom_BSplineSurface(poles, knots, knots, mults, mults, 1, 1); } -GeomBSplineSurface::GeomBSplineSurface(const Handle(Geom_BSplineSurface)& b) +GeomBSplineSurface::GeomBSplineSurface(const Handle(Geom_BSplineSurface) & b) { setHandle(b); } GeomBSplineSurface::~GeomBSplineSurface() = default; -void GeomBSplineSurface::setHandle(const Handle(Geom_BSplineSurface)& s) +void GeomBSplineSurface::setHandle(const Handle(Geom_BSplineSurface) & s) { mySurface = Handle(Geom_BSplineSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomBSplineSurface::handle() const +const Handle(Geom_Geometry) & GeomBSplineSurface::handle() const { return mySurface; } -Geometry *GeomBSplineSurface::copy() const +Geometry* GeomBSplineSurface::copy() const { - GeomBSplineSurface *newSurf = new GeomBSplineSurface(mySurface); + GeomBSplineSurface* newSurf = new GeomBSplineSurface(mySurface); newSurf->copyNonTag(this); return newSurf; } @@ -5117,17 +5244,17 @@ void GeomBSplineSurface::scaleKnotsToBounds(double u0, double u1, double v0, dou { try { Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast(mySurface->Copy()); - Standard_RangeError_Raise_if (u1 <= u0 || v1 <= v0, " "); - Standard_Real bu0,bu1,bv0,bv1; - surf->Bounds(bu0,bu1,bv0,bv1); - if ((abs(u0-bu0) > Precision::Confusion()) || (abs(u1-bu1) > Precision::Confusion())) { - TColStd_Array1OfReal uk(1,surf->NbUKnots()); + Standard_RangeError_Raise_if(u1 <= u0 || v1 <= v0, " "); + Standard_Real bu0, bu1, bv0, bv1; + surf->Bounds(bu0, bu1, bv0, bv1); + if ((abs(u0 - bu0) > Precision::Confusion()) || (abs(u1 - bu1) > Precision::Confusion())) { + TColStd_Array1OfReal uk(1, surf->NbUKnots()); surf->UKnots(uk); BSplCLib::Reparametrize(u0, u1, uk); surf->SetUKnots(uk); } - if ((abs(v0-bv0) > Precision::Confusion()) || (abs(v1-bv1) > Precision::Confusion())) { - TColStd_Array1OfReal vk(1,surf->NbVKnots()); + if ((abs(v0 - bv0) > Precision::Confusion()) || (abs(v1 - bv1) > Precision::Confusion())) { + TColStd_Array1OfReal vk(1, surf->NbVKnots()); surf->VKnots(vk); BSplCLib::Reparametrize(v0, v1, vk); surf->SetVKnots(vk); @@ -5136,12 +5263,12 @@ void GeomBSplineSurface::scaleKnotsToBounds(double u0, double u1, double v0, dou return; } catch (Standard_Failure& e) { - THROWM(Base::CADKernelError,e.GetMessageString()) + THROWM(Base::CADKernelError, e.GetMessageString()) } } // Persistence implementer -unsigned int GeomBSplineSurface::getMemSize () const +unsigned int GeomBSplineSurface::getMemSize() const { unsigned int size = sizeof(Geom_BSplineSurface); if (!mySurface.IsNull()) { @@ -5157,65 +5284,68 @@ unsigned int GeomBSplineSurface::getMemSize () const return size; } -void GeomBSplineSurface::Save(Base::Writer &/*writer*/) const +void GeomBSplineSurface::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomBSplineSurface::Save"); } -void GeomBSplineSurface::Restore(Base::XMLReader &/*reader*/) +void GeomBSplineSurface::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomBSplineSurface::Restore"); } -PyObject *GeomBSplineSurface::getPyObject() +PyObject* GeomBSplineSurface::getPyObject() { return new BSplineSurfacePy(static_cast(this->clone())); } -bool GeomBSplineSurface::isSame(const Geometry &_other, double tol, double atol) const +bool GeomBSplineSurface::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) { + if (_other.getTypeId() != getTypeId()) { if (_other.isDerivedFrom() && isPlanar()) { std::unique_ptr geo(toPlane()); - if (geo) + if (geo) { return geo->isSame(_other, tol, atol); + } } return false; } - auto &other = static_cast(_other); + auto& other = static_cast(_other); Standard_Integer uc = mySurface->NbUPoles(); Standard_Integer vc = mySurface->NbVPoles(); Standard_Integer ukc = mySurface->NbUKnots(); Standard_Integer vkc = mySurface->NbVKnots(); - if(uc != other.mySurface->NbUPoles() - || vc != other.mySurface->NbVPoles() - || ukc != other.mySurface->NbUKnots() - || vkc != other.mySurface->NbVKnots() - || mySurface->UDegree() != other.mySurface->UDegree() - || mySurface->VDegree() != other.mySurface->VDegree() - || mySurface->IsUPeriodic() != other.mySurface->IsUPeriodic() - || mySurface->IsVPeriodic() != other.mySurface->IsVPeriodic()) + if (uc != other.mySurface->NbUPoles() || vc != other.mySurface->NbVPoles() + || ukc != other.mySurface->NbUKnots() || vkc != other.mySurface->NbVKnots() + || mySurface->UDegree() != other.mySurface->UDegree() + || mySurface->VDegree() != other.mySurface->VDegree() + || mySurface->IsUPeriodic() != other.mySurface->IsUPeriodic() + || mySurface->IsVPeriodic() != other.mySurface->IsVPeriodic()) { return false; + } (void)atol; - double tol2 = tol*tol; - for(Standard_Integer u=1; u<=uc; ++u) { - for(Standard_Integer v=1; v<=vc; ++v) { - if(mySurface->Pole(u,v).SquareDistance(other.mySurface->Pole(u,v)) > tol2 - || fabs(mySurface->Weight(u,v) - other.mySurface->Weight(u,v)) > tol) + double tol2 = tol * tol; + for (Standard_Integer u = 1; u <= uc; ++u) { + for (Standard_Integer v = 1; v <= vc; ++v) { + if (mySurface->Pole(u, v).SquareDistance(other.mySurface->Pole(u, v)) > tol2 + || fabs(mySurface->Weight(u, v) - other.mySurface->Weight(u, v)) > tol) { return false; + } } } - for(Standard_Integer u=1; u<=ukc; ++u) { - if(fabs(mySurface->UKnot(u) - other.mySurface->UKnot(u)) > tol - || fabs(mySurface->UMultiplicity(u) - other.mySurface->UMultiplicity(u)) > tol) + for (Standard_Integer u = 1; u <= ukc; ++u) { + if (fabs(mySurface->UKnot(u) - other.mySurface->UKnot(u)) > tol + || fabs(mySurface->UMultiplicity(u) - other.mySurface->UMultiplicity(u)) > tol) { return false; + } } - for(Standard_Integer v=1; v<=ukc; ++v) { - if(fabs(mySurface->VKnot(v) - other.mySurface->VKnot(v)) > tol - || fabs(mySurface->VMultiplicity(v) - other.mySurface->VMultiplicity(v)) > tol) + for (Standard_Integer v = 1; v <= ukc; ++v) { + if (fabs(mySurface->VKnot(v) - other.mySurface->VKnot(v)) > tol + || fabs(mySurface->VMultiplicity(v) - other.mySurface->VMultiplicity(v)) > tol) { return false; + } } return true; } @@ -5225,12 +5355,10 @@ bool GeomBSplineSurface::isSame(const Geometry &_other, double tol, double atol) TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomElementarySurface, Part::GeomSurface) GeomElementarySurface::GeomElementarySurface() -{ -} +{} GeomElementarySurface::~GeomElementarySurface() -{ -} +{} Base::Vector3d GeomElementarySurface::getLocation(void) const { @@ -5248,43 +5376,43 @@ std::optional GeomPlane::getRotation() const } gp_Trsf trsf; - trsf.SetTransformation(s->Position().Ax2(),gp_Ax3()); + trsf.SetTransformation(s->Position().Ax2(), gp_Ax3()); auto q = trsf.GetRotation(); - return Base::Rotation(q.X(),q.Y(),q.Z(),q.W()); + return Base::Rotation(q.X(), q.Y(), q.Z(), q.W()); } Base::Vector3d GeomElementarySurface::getDir(void) const { - Handle(Geom_ElementarySurface) surf = Handle(Geom_ElementarySurface)::DownCast(handle()); - const gp_Dir &dir = surf->Position().Direction(); - return Base::Vector3d(dir.X(),dir.Y(),dir.Z()); + Handle(Geom_ElementarySurface) surf = Handle(Geom_ElementarySurface)::DownCast(handle()); + const gp_Dir& dir = surf->Position().Direction(); + return Base::Vector3d(dir.X(), dir.Y(), dir.Z()); } Base::Vector3d GeomElementarySurface::getXDir(void) const { - Handle(Geom_ElementarySurface) surf = Handle(Geom_ElementarySurface)::DownCast(handle()); - const gp_Dir &dir = surf->Position().XDirection(); - return Base::Vector3d(dir.X(),dir.Y(),dir.Z()); + Handle(Geom_ElementarySurface) surf = Handle(Geom_ElementarySurface)::DownCast(handle()); + const gp_Dir& dir = surf->Position().XDirection(); + return Base::Vector3d(dir.X(), dir.Y(), dir.Z()); } Base::Vector3d GeomElementarySurface::getYDir(void) const { - Handle(Geom_ElementarySurface) surf = Handle(Geom_ElementarySurface)::DownCast(handle()); - const gp_Dir &dir = surf->Position().YDirection(); - return Base::Vector3d(dir.X(),dir.Y(),dir.Z()); + Handle(Geom_ElementarySurface) surf = Handle(Geom_ElementarySurface)::DownCast(handle()); + const gp_Dir& dir = surf->Position().YDirection(); + return Base::Vector3d(dir.X(), dir.Y(), dir.Z()); } -bool GeomElementarySurface::isSame(const Geometry &_other, double tol, double atol) const +bool GeomElementarySurface::isSame(const Geometry& _other, double tol, double atol) const { - if(!_other.isDerivedFrom()) + if (!_other.isDerivedFrom()) { return false; + } - auto &other = static_cast(_other); - return Base::DistanceP2(getLocation(), other.getLocation()) <= tol*tol + auto& other = static_cast(_other); + return Base::DistanceP2(getLocation(), other.getLocation()) <= tol * tol && getDir().GetAngle(other.getDir()) <= atol - && ((getXDir().GetAngle(other.getXDir()) <= atol - && getYDir().GetAngle(other.getYDir()) <= atol) + && ((getXDir().GetAngle(other.getXDir()) <= atol && getYDir().GetAngle(other.getYDir()) <= atol) // It seems that OCC may change some surface Position (gp_Ax3) to // right hand coordinate. The following checks is to detect such cases. || (getXDir().GetAngle(other.getYDir()) <= atol @@ -5295,7 +5423,7 @@ bool GeomElementarySurface::isSame(const Geometry &_other, double tol, double at // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomCylinder,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomCylinder, Part::GeomSurface) GeomCylinder::GeomCylinder() { @@ -5303,48 +5431,48 @@ GeomCylinder::GeomCylinder() this->mySurface = s; } -GeomCylinder::GeomCylinder(const Handle(Geom_CylindricalSurface)& c) +GeomCylinder::GeomCylinder(const Handle(Geom_CylindricalSurface) & c) { setHandle(c); } GeomCylinder::~GeomCylinder() = default; -void GeomCylinder::setHandle(const Handle(Geom_CylindricalSurface)& s) +void GeomCylinder::setHandle(const Handle(Geom_CylindricalSurface) & s) { mySurface = Handle(Geom_CylindricalSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomCylinder::handle() const +const Handle(Geom_Geometry) & GeomCylinder::handle() const { return mySurface; } -Geometry *GeomCylinder::copy() const +Geometry* GeomCylinder::copy() const { - GeomCylinder *tempCurve = new GeomCylinder(); + GeomCylinder* tempCurve = new GeomCylinder(); tempCurve->mySurface = Handle(Geom_CylindricalSurface)::DownCast(mySurface->Copy()); tempCurve->copyNonTag(this); return tempCurve; } // Persistence implementer -unsigned int GeomCylinder::getMemSize () const +unsigned int GeomCylinder::getMemSize() const { return sizeof(Geom_CylindricalSurface); } -void GeomCylinder::Save(Base::Writer &/*writer*/) const +void GeomCylinder::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomCylinder::Save"); } -void GeomCylinder::Restore(Base::XMLReader &/*reader*/) +void GeomCylinder::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomCylinder::Restore"); } -PyObject *GeomCylinder::getPyObject() +PyObject* GeomCylinder::getPyObject() { return new CylinderPy(static_cast(this->clone())); } @@ -5354,21 +5482,22 @@ double GeomCylinder::getRadius() const return mySurface->Radius(); } -bool GeomCylinder::isSame(const Geometry &_other, double tol, double atol) const +bool GeomCylinder::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomElementarySurface::isSame(other,tol,atol) + auto& other = static_cast(_other); + return GeomElementarySurface::isSame(other, tol, atol) && fabs(getRadius() - other.getRadius()) <= tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomCone,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomCone, Part::GeomSurface) GeomCone::GeomCone() { @@ -5376,48 +5505,48 @@ GeomCone::GeomCone() this->mySurface = s; } -GeomCone::GeomCone(const Handle(Geom_ConicalSurface)& c) +GeomCone::GeomCone(const Handle(Geom_ConicalSurface) & c) { setHandle(c); } GeomCone::~GeomCone() = default; -void GeomCone::setHandle(const Handle(Geom_ConicalSurface)& s) +void GeomCone::setHandle(const Handle(Geom_ConicalSurface) & s) { mySurface = Handle(Geom_ConicalSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomCone::handle() const +const Handle(Geom_Geometry) & GeomCone::handle() const { return mySurface; } -Geometry *GeomCone::copy() const +Geometry* GeomCone::copy() const { - GeomCone *tempCurve = new GeomCone(); + GeomCone* tempCurve = new GeomCone(); tempCurve->mySurface = Handle(Geom_ConicalSurface)::DownCast(mySurface->Copy()); tempCurve->copyNonTag(this); return tempCurve; } // Persistence implementer -unsigned int GeomCone::getMemSize () const +unsigned int GeomCone::getMemSize() const { return sizeof(Geom_ConicalSurface); } -void GeomCone::Save(Base::Writer &/*writer*/) const +void GeomCone::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomCone::Save"); } -void GeomCone::Restore(Base::XMLReader &/*reader*/) +void GeomCone::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomCone::Restore"); } -PyObject *GeomCone::getPyObject() +PyObject* GeomCone::getPyObject() { return new ConePy(static_cast(this->clone())); } @@ -5435,37 +5564,39 @@ gp_Vec GeomCone::getDN(double u, double v, int Nu, int Nv) const const Standard_Real Radius, const Standard_Real SAngle, const Standard_Integer Nu, - const Standard_Integer Nv) - { - gp_XYZ Xdir = Pos.XDirection().XYZ(); - gp_XYZ Ydir = Pos.YDirection().XYZ(); - Standard_Real Um = U + Nu * std::numbers::pi/2; - Xdir.Multiply(cos(Um)); - Ydir.Multiply(sin(Um)); - Xdir.Add(Ydir); - if(Nv == 0) { - Xdir.Multiply(Radius + V * sin(SAngle)); - if(Nu == 0) Xdir.Add(Pos.Location().XYZ()); - return gp_Vec(Xdir); - } - else if(Nv == 1) { - Xdir.Multiply(sin(SAngle)); - if (Nu == 0) - Xdir.Add(Pos.Direction().XYZ() * cos(SAngle)); - return gp_Vec(Xdir); - } - return gp_Vec(0.0,0.0,0.0); + const Standard_Integer Nv) { + gp_XYZ Xdir = Pos.XDirection().XYZ(); + gp_XYZ Ydir = Pos.YDirection().XYZ(); + Standard_Real Um = U + Nu * std::numbers::pi / 2; + Xdir.Multiply(cos(Um)); + Ydir.Multiply(sin(Um)); + Xdir.Add(Ydir); + if (Nv == 0) { + Xdir.Multiply(Radius + V * sin(SAngle)); + if (Nu == 0) { + Xdir.Add(Pos.Location().XYZ()); + } + return gp_Vec(Xdir); + } + else if (Nv == 1) { + Xdir.Multiply(sin(SAngle)); + if (Nu == 0) { + Xdir.Add(Pos.Direction().XYZ() * cos(SAngle)); + } + return gp_Vec(Xdir); + } + return gp_Vec(0.0, 0.0, 0.0); }; // Workaround for cones to get the correct derivatives // https://forum.freecad.org/viewtopic.php?f=10&t=66677 Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast(handle()); - Standard_RangeError_Raise_if (Nu + Nv < 1 || Nu < 0 || Nv < 0, " "); + Standard_RangeError_Raise_if(Nu + Nv < 1 || Nu < 0 || Nv < 0, " "); if (Nv > 1) { return {0.0, 0.0, 0.0}; } else { - return ElSLib__ConeDN(u, v, s->Position(), s->RefRadius(), s->SemiAngle(), Nu, Nv); + return ElSLib__ConeDN(u, v, s->Position(), s->RefRadius(), s->SemiAngle(), Nu, Nv); } #endif } @@ -5486,20 +5617,21 @@ Base::Vector3d GeomCone::getApex() const return Base::convertTo(s->Apex()); } -bool GeomCone::isSame(const Geometry &_other, double tol, double atol) const +bool GeomCone::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = static_cast(_other); - return GeomElementarySurface::isSame(other,tol,atol) + auto& other = static_cast(_other); + return GeomElementarySurface::isSame(other, tol, atol) && fabs(getRadius() - other.getRadius()) <= tol && fabs(getSemiAngle() - other.getSemiAngle()) <= atol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomToroid,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomToroid, Part::GeomSurface) GeomToroid::GeomToroid() { @@ -5507,48 +5639,48 @@ GeomToroid::GeomToroid() this->mySurface = s; } -GeomToroid::GeomToroid(const Handle(Geom_ToroidalSurface)& t) +GeomToroid::GeomToroid(const Handle(Geom_ToroidalSurface) & t) { setHandle(t); } GeomToroid::~GeomToroid() = default; -void GeomToroid::setHandle(const Handle(Geom_ToroidalSurface)& s) +void GeomToroid::setHandle(const Handle(Geom_ToroidalSurface) & s) { mySurface = Handle(Geom_ToroidalSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomToroid::handle() const +const Handle(Geom_Geometry) & GeomToroid::handle() const { return mySurface; } -Geometry *GeomToroid::copy() const +Geometry* GeomToroid::copy() const { - GeomToroid *tempCurve = new GeomToroid(); + GeomToroid* tempCurve = new GeomToroid(); tempCurve->mySurface = Handle(Geom_ToroidalSurface)::DownCast(mySurface->Copy()); tempCurve->copyNonTag(this); return tempCurve; } // Persistence implementer -unsigned int GeomToroid::getMemSize () const +unsigned int GeomToroid::getMemSize() const { return sizeof(Geom_ToroidalSurface); } -void GeomToroid::Save(Base::Writer &/*writer*/) const +void GeomToroid::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomToroid::Save"); } -void GeomToroid::Restore(Base::XMLReader &/*reader*/) +void GeomToroid::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomToroid::Restore"); } -PyObject *GeomToroid::getPyObject() +PyObject* GeomToroid::getPyObject() { return new ToroidPy(static_cast(this->clone())); } @@ -5563,14 +5695,15 @@ double GeomToroid::getMinorRadius() const return mySurface->MinorRadius(); } -bool GeomToroid::isSame(const Geometry &_other, double tol, double atol) const +bool GeomToroid::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomElementarySurface::isSame(other,tol,atol) + auto& other = static_cast(_other); + return GeomElementarySurface::isSame(other, tol, atol) && fabs(getMajorRadius() - other.getMajorRadius()) <= tol && fabs(getMinorRadius() - other.getMinorRadius()) <= tol; } @@ -5578,7 +5711,7 @@ bool GeomToroid::isSame(const Geometry &_other, double tol, double atol) const // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomSphere,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomSphere, Part::GeomSurface) GeomSphere::GeomSphere() { @@ -5586,48 +5719,48 @@ GeomSphere::GeomSphere() this->mySurface = s; } -GeomSphere::GeomSphere(const Handle(Geom_SphericalSurface)& s) +GeomSphere::GeomSphere(const Handle(Geom_SphericalSurface) & s) { setHandle(s); } GeomSphere::~GeomSphere() = default; -void GeomSphere::setHandle(const Handle(Geom_SphericalSurface)& s) +void GeomSphere::setHandle(const Handle(Geom_SphericalSurface) & s) { mySurface = Handle(Geom_SphericalSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomSphere::handle() const +const Handle(Geom_Geometry) & GeomSphere::handle() const { return mySurface; } -Geometry *GeomSphere::copy() const +Geometry* GeomSphere::copy() const { - GeomSphere *tempCurve = new GeomSphere(); + GeomSphere* tempCurve = new GeomSphere(); tempCurve->mySurface = Handle(Geom_SphericalSurface)::DownCast(mySurface->Copy()); tempCurve->copyNonTag(this); return tempCurve; } // Persistence implementer -unsigned int GeomSphere::getMemSize () const +unsigned int GeomSphere::getMemSize() const { return sizeof(Geom_SphericalSurface); } -void GeomSphere::Save(Base::Writer &/*writer*/) const +void GeomSphere::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomSphere::Save"); } -void GeomSphere::Restore(Base::XMLReader &/*reader*/) +void GeomSphere::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomSphere::Restore"); } -PyObject *GeomSphere::getPyObject() +PyObject* GeomSphere::getPyObject() { return new SpherePy(static_cast(this->clone())); } @@ -5637,21 +5770,22 @@ double GeomSphere::getRadius() const return mySurface->Radius(); } -bool GeomSphere::isSame(const Geometry &_other, double tol, double atol) const +bool GeomSphere::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } (void)atol; - auto &other = static_cast(_other); - return GeomElementarySurface::isSame(other,tol,atol) + auto& other = static_cast(_other); + return GeomElementarySurface::isSame(other, tol, atol) && fabs(getRadius() - other.getRadius()) <= tol; } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomPlane,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomPlane, Part::GeomSurface) GeomPlane::GeomPlane() { @@ -5659,125 +5793,126 @@ GeomPlane::GeomPlane() this->mySurface = s; } -GeomPlane::GeomPlane(const gp_Pln &pln) +GeomPlane::GeomPlane(const gp_Pln& pln) { Handle(Geom_Plane) s = new Geom_Plane(pln); this->mySurface = s; } -GeomPlane::GeomPlane(const Handle(Geom_Plane)& p) +GeomPlane::GeomPlane(const Handle(Geom_Plane) & p) { setHandle(p); } GeomPlane::~GeomPlane() = default; -void GeomPlane::setHandle(const Handle(Geom_Plane)& s) +void GeomPlane::setHandle(const Handle(Geom_Plane) & s) { mySurface = Handle(Geom_Plane)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomPlane::handle() const +const Handle(Geom_Geometry) & GeomPlane::handle() const { return mySurface; } -Geometry *GeomPlane::copy() const +Geometry* GeomPlane::copy() const { - GeomPlane *tempCurve = new GeomPlane(); + GeomPlane* tempCurve = new GeomPlane(); tempCurve->mySurface = Handle(Geom_Plane)::DownCast(mySurface->Copy()); tempCurve->copyNonTag(this); return tempCurve; } // Persistence implementer -unsigned int GeomPlane::getMemSize () const +unsigned int GeomPlane::getMemSize() const { return sizeof(Geom_Plane); } -void GeomPlane::Save(Base::Writer &/*writer*/) const +void GeomPlane::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomPlane::Save"); } -void GeomPlane::Restore(Base::XMLReader &/*reader*/) +void GeomPlane::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomPlane::Restore"); } -PyObject *GeomPlane::getPyObject() +PyObject* GeomPlane::getPyObject() { return new PlanePy(static_cast(this->clone())); } -bool GeomPlane::isSame(const Geometry &_other, double tol, double atol) const +bool GeomPlane::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) { + if (_other.getTypeId() != getTypeId()) { if (_other.isDerivedFrom()) { std::unique_ptr geo(static_cast(_other).toPlane()); - if (geo) + if (geo) { return isSame(*geo, tol, atol); + } } return false; } - auto &other = static_cast(_other); - return GeomElementarySurface::isSame(other,tol,atol); + auto& other = static_cast(_other); + return GeomElementarySurface::isSame(other, tol, atol); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomOffsetSurface,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomOffsetSurface, Part::GeomSurface) GeomOffsetSurface::GeomOffsetSurface() = default; -GeomOffsetSurface::GeomOffsetSurface(const Handle(Geom_Surface)& s, double offset) +GeomOffsetSurface::GeomOffsetSurface(const Handle(Geom_Surface) & s, double offset) { this->mySurface = new Geom_OffsetSurface(s, offset); } -GeomOffsetSurface::GeomOffsetSurface(const Handle(Geom_OffsetSurface)& s) +GeomOffsetSurface::GeomOffsetSurface(const Handle(Geom_OffsetSurface) & s) { setHandle(s); } GeomOffsetSurface::~GeomOffsetSurface() = default; -void GeomOffsetSurface::setHandle(const Handle(Geom_OffsetSurface)& s) +void GeomOffsetSurface::setHandle(const Handle(Geom_OffsetSurface) & s) { mySurface = Handle(Geom_OffsetSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomOffsetSurface::handle() const +const Handle(Geom_Geometry) & GeomOffsetSurface::handle() const { return mySurface; } -Geometry *GeomOffsetSurface::copy() const +Geometry* GeomOffsetSurface::copy() const { - GeomOffsetSurface *newSurf = new GeomOffsetSurface(mySurface); + GeomOffsetSurface* newSurf = new GeomOffsetSurface(mySurface); newSurf->copyNonTag(this); return newSurf; } // Persistence implementer -unsigned int GeomOffsetSurface::getMemSize () const +unsigned int GeomOffsetSurface::getMemSize() const { return sizeof(Geom_OffsetSurface); } -void GeomOffsetSurface::Save(Base::Writer &/*writer*/) const +void GeomOffsetSurface::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomOffsetSurface::Save"); } -void GeomOffsetSurface::Restore(Base::XMLReader &/*reader*/) +void GeomOffsetSurface::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomOffsetSurface::Restore"); } -PyObject *GeomOffsetSurface::getPyObject() +PyObject* GeomOffsetSurface::getPyObject() { return new OffsetSurfacePy(static_cast(this->clone())); } @@ -5787,32 +5922,35 @@ double GeomOffsetSurface::getOffset() const return mySurface->Offset(); } -bool GeomOffsetSurface::isSame(const Geometry &_other, double tol, double atol) const +bool GeomOffsetSurface::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = static_cast(_other); - if(fabs(getOffset() - other.getOffset()) > tol) + auto& other = static_cast(_other); + if (fabs(getOffset() - other.getOffset()) > tol) { return false; + } Handle(Geom_Surface) basis = mySurface->BasisSurface(); Handle(Geom_Surface) basis1 = other.mySurface->BasisSurface(); - if(basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) + if (basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) { return false; + } std::unique_ptr b(makeFromSurface(basis)); std::unique_ptr b1(makeFromSurface(basis1)); - return b && b1 && b->isSame(*b1,tol,atol); + return b && b1 && b->isSame(*b1, tol, atol); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomPlateSurface,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomPlateSurface, Part::GeomSurface) GeomPlateSurface::GeomPlateSurface() = default; -GeomPlateSurface::GeomPlateSurface(const Handle(Geom_Surface)& s, const Plate_Plate& plate) +GeomPlateSurface::GeomPlateSurface(const Handle(Geom_Surface) & s, const Plate_Plate& plate) { this->mySurface = new GeomPlate_Surface(s, plate); } @@ -5823,52 +5961,52 @@ GeomPlateSurface::GeomPlateSurface(const GeomPlate_BuildPlateSurface& buildPlate this->mySurface = Handle(GeomPlate_Surface)::DownCast(s->Copy()); } -GeomPlateSurface::GeomPlateSurface(const Handle(GeomPlate_Surface)& s) +GeomPlateSurface::GeomPlateSurface(const Handle(GeomPlate_Surface) & s) { setHandle(s); } GeomPlateSurface::~GeomPlateSurface() = default; -void GeomPlateSurface::setHandle(const Handle(GeomPlate_Surface)& s) +void GeomPlateSurface::setHandle(const Handle(GeomPlate_Surface) & s) { mySurface = Handle(GeomPlate_Surface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomPlateSurface::handle() const +const Handle(Geom_Geometry) & GeomPlateSurface::handle() const { return mySurface; } -Geometry *GeomPlateSurface::copy() const +Geometry* GeomPlateSurface::copy() const { - GeomPlateSurface *newSurf = new GeomPlateSurface(mySurface); + GeomPlateSurface* newSurf = new GeomPlateSurface(mySurface); newSurf->copyNonTag(this); return newSurf; } // Persistence implementer -unsigned int GeomPlateSurface::getMemSize () const +unsigned int GeomPlateSurface::getMemSize() const { throw Base::NotImplementedError("GeomPlateSurface::getMemSize"); } -void GeomPlateSurface::Save(Base::Writer &/*writer*/) const +void GeomPlateSurface::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomPlateSurface::Save"); } -void GeomPlateSurface::Restore(Base::XMLReader &/*reader*/) +void GeomPlateSurface::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomPlateSurface::Restore"); } -PyObject *GeomPlateSurface::getPyObject() +PyObject* GeomPlateSurface::getPyObject() { return new PlateSurfacePy(static_cast(this->clone())); } -bool GeomPlateSurface::isSame(const Geometry &, double, double) const +bool GeomPlateSurface::isSame(const Geometry&, double, double) const { // TODO: How to compare this type of surface? return false; @@ -5876,227 +6014,231 @@ bool GeomPlateSurface::isSame(const Geometry &, double, double) const // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomTrimmedSurface,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomTrimmedSurface, Part::GeomSurface) GeomTrimmedSurface::GeomTrimmedSurface() = default; -GeomTrimmedSurface::GeomTrimmedSurface(const Handle(Geom_RectangularTrimmedSurface)& s) +GeomTrimmedSurface::GeomTrimmedSurface(const Handle(Geom_RectangularTrimmedSurface) & s) { - setHandle(s); + setHandle(s); } GeomTrimmedSurface::~GeomTrimmedSurface() = default; -void GeomTrimmedSurface::setHandle(const Handle(Geom_RectangularTrimmedSurface)& s) +void GeomTrimmedSurface::setHandle(const Handle(Geom_RectangularTrimmedSurface) & s) { mySurface = Handle(Geom_RectangularTrimmedSurface)::DownCast(s->Copy()); } -const Handle(Geom_Geometry)& GeomTrimmedSurface::handle() const +const Handle(Geom_Geometry) & GeomTrimmedSurface::handle() const { return mySurface; } -Geometry *GeomTrimmedSurface::copy() const +Geometry* GeomTrimmedSurface::copy() const { - GeomTrimmedSurface *newSurf = new GeomTrimmedSurface(mySurface); + GeomTrimmedSurface* newSurf = new GeomTrimmedSurface(mySurface); newSurf->copyNonTag(this); return newSurf; } // Persistence implementer -unsigned int GeomTrimmedSurface::getMemSize () const +unsigned int GeomTrimmedSurface::getMemSize() const { return sizeof(Geom_RectangularTrimmedSurface); } -void GeomTrimmedSurface::Save(Base::Writer &/*writer*/) const +void GeomTrimmedSurface::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomTrimmedSurface::Save"); } -void GeomTrimmedSurface::Restore(Base::XMLReader &/*reader*/) +void GeomTrimmedSurface::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomTrimmedSurface::Restore"); } -PyObject *GeomTrimmedSurface::getPyObject() +PyObject* GeomTrimmedSurface::getPyObject() { return new RectangularTrimmedSurfacePy(static_cast(this->clone())); } -bool GeomTrimmedSurface::isSame(const Geometry &_other, double tol, double atol) const +bool GeomTrimmedSurface::isSame(const Geometry& _other, double tol, double atol) const { - if(_other.getTypeId() != getTypeId()) + if (_other.getTypeId() != getTypeId()) { return false; + } - auto &other = static_cast(_other); + auto& other = static_cast(_other); - Standard_Real u1[2],u2[2],v1[2],v2[2]; - mySurface->Bounds(u1[0],u2[0],v1[0],v2[0]); - other.mySurface->Bounds(u1[1],u2[1],v1[1],v2[1]); + Standard_Real u1[2], u2[2], v1[2], v2[2]; + mySurface->Bounds(u1[0], u2[0], v1[0], v2[0]); + other.mySurface->Bounds(u1[1], u2[1], v1[1], v2[1]); - if(fabs(u1[0]-u1[1])>tol || fabs(u2[0]-u2[1])>tol - || fabs(v1[0]-v1[1])>tol || fabs(v2[0]-v2[1])>tol) + if (fabs(u1[0] - u1[1]) > tol || fabs(u2[0] - u2[1]) > tol || fabs(v1[0] - v1[1]) > tol + || fabs(v2[0] - v2[1]) > tol) { return false; + } Handle(Geom_Surface) basis = mySurface->BasisSurface(); Handle(Geom_Surface) basis1 = other.mySurface->BasisSurface(); - if(basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) + if (basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) { return false; + } std::unique_ptr b(makeFromSurface(basis)); std::unique_ptr b1(makeFromSurface(basis1)); - return b && b1 && b->isSame(*b1,tol,atol); + return b && b1 && b->isSame(*b1, tol, atol); } // ------------------------------------------------- TYPESYSTEM_SOURCE_ABSTRACT(Part::GeomSweptSurface, Part::GeomSurface) GeomSweptSurface::GeomSweptSurface() -{ -} +{} GeomSweptSurface::~GeomSweptSurface() -{ -} +{} Base::Vector3d GeomSweptSurface::getDir(void) const { - Handle(Geom_SweptSurface) surf = Handle(Geom_SweptSurface)::DownCast(handle()); - const gp_Dir &dir = surf->Direction(); - return Base::Vector3d(dir.X(),dir.Y(),dir.Z()); + Handle(Geom_SweptSurface) surf = Handle(Geom_SweptSurface)::DownCast(handle()); + const gp_Dir& dir = surf->Direction(); + return Base::Vector3d(dir.X(), dir.Y(), dir.Z()); } -bool GeomSweptSurface::isSame(const Geometry &_other, double tol, double atol) const +bool GeomSweptSurface::isSame(const Geometry& _other, double tol, double atol) const { - if(!_other.isDerivedFrom()) + if (!_other.isDerivedFrom()) { return false; + } - auto &other = static_cast(_other); - if(getDir().GetAngle(other.getDir()) > atol) + auto& other = static_cast(_other); + if (getDir().GetAngle(other.getDir()) > atol) { return false; + } - Handle(Geom_SweptSurface) surf = Handle(Geom_SweptSurface)::DownCast(handle()); - Handle(Geom_SweptSurface) surf1 = Handle(Geom_SweptSurface)::DownCast(other.handle()); + Handle(Geom_SweptSurface) surf = Handle(Geom_SweptSurface)::DownCast(handle()); + Handle(Geom_SweptSurface) surf1 = Handle(Geom_SweptSurface)::DownCast(other.handle()); Handle(Geom_Curve) basis = surf->BasisCurve(); Handle(Geom_Curve) basis1 = surf1->BasisCurve(); - if(basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) + if (basis.IsNull() || basis1.IsNull() || basis->DynamicType() != basis1->DynamicType()) { return false; + } std::unique_ptr b(makeFromCurve(basis)); std::unique_ptr b1(makeFromCurve(basis1)); - return b && b1 && b->isSame(*b1,tol,atol); + return b && b1 && b->isSame(*b1, tol, atol); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomSurfaceOfRevolution,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomSurfaceOfRevolution, Part::GeomSurface) GeomSurfaceOfRevolution::GeomSurfaceOfRevolution() = default; -GeomSurfaceOfRevolution::GeomSurfaceOfRevolution(const Handle(Geom_Curve)& c, const gp_Ax1& a) +GeomSurfaceOfRevolution::GeomSurfaceOfRevolution(const Handle(Geom_Curve) & c, const gp_Ax1& a) { - this->mySurface = new Geom_SurfaceOfRevolution(c,a); + this->mySurface = new Geom_SurfaceOfRevolution(c, a); } -GeomSurfaceOfRevolution::GeomSurfaceOfRevolution(const Handle(Geom_SurfaceOfRevolution)& s) +GeomSurfaceOfRevolution::GeomSurfaceOfRevolution(const Handle(Geom_SurfaceOfRevolution) & s) { setHandle(s); } GeomSurfaceOfRevolution::~GeomSurfaceOfRevolution() = default; -void GeomSurfaceOfRevolution::setHandle(const Handle(Geom_SurfaceOfRevolution)& c) +void GeomSurfaceOfRevolution::setHandle(const Handle(Geom_SurfaceOfRevolution) & c) { mySurface = Handle(Geom_SurfaceOfRevolution)::DownCast(c->Copy()); } -const Handle(Geom_Geometry)& GeomSurfaceOfRevolution::handle() const +const Handle(Geom_Geometry) & GeomSurfaceOfRevolution::handle() const { return mySurface; } -Geometry *GeomSurfaceOfRevolution::copy() const +Geometry* GeomSurfaceOfRevolution::copy() const { - GeomSurfaceOfRevolution *newSurf = new GeomSurfaceOfRevolution(mySurface); + GeomSurfaceOfRevolution* newSurf = new GeomSurfaceOfRevolution(mySurface); newSurf->copyNonTag(this); return newSurf; } // Persistence implementer -unsigned int GeomSurfaceOfRevolution::getMemSize () const +unsigned int GeomSurfaceOfRevolution::getMemSize() const { return sizeof(Geom_SurfaceOfRevolution); } -void GeomSurfaceOfRevolution::Save(Base::Writer &/*writer*/) const +void GeomSurfaceOfRevolution::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomSurfaceOfRevolution::Save"); } -void GeomSurfaceOfRevolution::Restore(Base::XMLReader &/*reader*/) +void GeomSurfaceOfRevolution::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomSurfaceOfRevolution::Restore"); } -PyObject *GeomSurfaceOfRevolution::getPyObject() +PyObject* GeomSurfaceOfRevolution::getPyObject() { return new SurfaceOfRevolutionPy(static_cast(this->clone())); } // ------------------------------------------------- -TYPESYSTEM_SOURCE(Part::GeomSurfaceOfExtrusion,Part::GeomSurface) +TYPESYSTEM_SOURCE(Part::GeomSurfaceOfExtrusion, Part::GeomSurface) GeomSurfaceOfExtrusion::GeomSurfaceOfExtrusion() = default; -GeomSurfaceOfExtrusion::GeomSurfaceOfExtrusion(const Handle(Geom_Curve)& c, const gp_Dir& d) +GeomSurfaceOfExtrusion::GeomSurfaceOfExtrusion(const Handle(Geom_Curve) & c, const gp_Dir& d) { - this->mySurface = new Geom_SurfaceOfLinearExtrusion(c,d); + this->mySurface = new Geom_SurfaceOfLinearExtrusion(c, d); } -GeomSurfaceOfExtrusion::GeomSurfaceOfExtrusion(const Handle(Geom_SurfaceOfLinearExtrusion)& s) +GeomSurfaceOfExtrusion::GeomSurfaceOfExtrusion(const Handle(Geom_SurfaceOfLinearExtrusion) & s) { setHandle(s); } GeomSurfaceOfExtrusion::~GeomSurfaceOfExtrusion() = default; -void GeomSurfaceOfExtrusion::setHandle(const Handle(Geom_SurfaceOfLinearExtrusion)& c) +void GeomSurfaceOfExtrusion::setHandle(const Handle(Geom_SurfaceOfLinearExtrusion) & c) { mySurface = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(c->Copy()); } -const Handle(Geom_Geometry)& GeomSurfaceOfExtrusion::handle() const +const Handle(Geom_Geometry) & GeomSurfaceOfExtrusion::handle() const { return mySurface; } -Geometry *GeomSurfaceOfExtrusion::copy() const +Geometry* GeomSurfaceOfExtrusion::copy() const { - GeomSurfaceOfExtrusion *newSurf = new GeomSurfaceOfExtrusion(mySurface); + GeomSurfaceOfExtrusion* newSurf = new GeomSurfaceOfExtrusion(mySurface); newSurf->copyNonTag(this); return newSurf; } // Persistence implementer -unsigned int GeomSurfaceOfExtrusion::getMemSize () const +unsigned int GeomSurfaceOfExtrusion::getMemSize() const { - return sizeof(Geom_SurfaceOfLinearExtrusion); + return sizeof(Geom_SurfaceOfLinearExtrusion); } -void GeomSurfaceOfExtrusion::Save(Base::Writer &/*writer*/) const +void GeomSurfaceOfExtrusion::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("GeomSurfaceOfExtrusion::Save"); } -void GeomSurfaceOfExtrusion::Restore(Base::XMLReader &/*reader*/) +void GeomSurfaceOfExtrusion::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("GeomSurfaceOfExtrusion::Restore"); } -PyObject *GeomSurfaceOfExtrusion::getPyObject() +PyObject* GeomSurfaceOfExtrusion::getPyObject() { return new SurfaceOfExtrusionPy(static_cast(this->clone())); } @@ -6104,45 +6246,64 @@ PyObject *GeomSurfaceOfExtrusion::getPyObject() // Helper functions for fillet tools // ------------------------------------------------- -namespace Part { - -bool find2DLinesIntersection(const Base::Vector3d &orig1, const Base::Vector3d &dir1, - const Base::Vector3d &orig2, const Base::Vector3d &dir2, - Base::Vector3d &point) +namespace Part { - double det = dir1.x*dir2.y - dir1.y*dir2.x; - if ((det > 0 ? det : -det) < 1e-10) + +bool find2DLinesIntersection( + const Base::Vector3d& orig1, + const Base::Vector3d& dir1, + const Base::Vector3d& orig2, + const Base::Vector3d& dir2, + Base::Vector3d& point +) +{ + double det = dir1.x * dir2.y - dir1.y * dir2.x; + if ((det > 0 ? det : -det) < 1e-10) { return false; - double c1 = dir1.y*orig1.x - dir1.x*orig1.y; - double c2 = dir2.y*orig2.x - dir2.x*orig2.y; - double x = (dir1.x*c2 - dir2.x*c1)/det; - double y = (dir1.y*c2 - dir2.y*c1)/det; - point = Base::Vector3d(x,y,0.f); + } + double c1 = dir1.y * orig1.x - dir1.x * orig1.y; + double c2 = dir2.y * orig2.x - dir2.x * orig2.y; + double x = (dir1.x * c2 - dir2.x * c1) / det; + double y = (dir1.y * c2 - dir2.y * c1) / det; + point = Base::Vector3d(x, y, 0.f); return true; } -bool find2DLinesIntersection(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, - Base::Vector3d &point) +bool find2DLinesIntersection( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + Base::Vector3d& point +) { Base::Vector3d orig1 = lineSeg1->getStartPoint(); Base::Vector3d orig2 = lineSeg2->getStartPoint(); - Base::Vector3d dir1 = (lineSeg1->getEndPoint()-lineSeg1->getStartPoint()); - Base::Vector3d dir2 = (lineSeg2->getEndPoint()-lineSeg2->getStartPoint()); + Base::Vector3d dir1 = (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()); + Base::Vector3d dir2 = (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()); return find2DLinesIntersection(orig1, dir1, orig2, dir2, point); } -bool findFilletCenter(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, double radius, - Base::Vector3d ¢er) +bool findFilletCenter( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + double radius, + Base::Vector3d& center +) { - Base::Vector3d midPoint1 = (lineSeg1->getStartPoint()+lineSeg1->getEndPoint())/2; - Base::Vector3d midPoint2 = (lineSeg2->getStartPoint()+lineSeg2->getEndPoint())/2; + Base::Vector3d midPoint1 = (lineSeg1->getStartPoint() + lineSeg1->getEndPoint()) / 2; + Base::Vector3d midPoint2 = (lineSeg2->getStartPoint() + lineSeg2->getEndPoint()) / 2; return findFilletCenter(lineSeg1, lineSeg2, radius, midPoint1, midPoint2, center); } -bool findFilletCenter(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, double radius, - const Base::Vector3d &refPnt1, const Base::Vector3d &refPnt2, Base::Vector3d ¢er) +bool findFilletCenter( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + double radius, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2, + Base::Vector3d& center +) { - //Calculate directions and normals for each straight line + // Calculate directions and normals for each straight line Base::Vector3d l1p1, l1p2, l2p1, l2p2, dir1, dir2, norm1, norm2; l1p1 = lineSeg1->getStartPoint(); l1p2 = lineSeg1->getEndPoint(); @@ -6159,26 +6320,30 @@ bool findFilletCenter(const GeomLineSegment *lineSeg1, const GeomLineSegment *li // find intersection of lines Base::Vector3d corner; - if (!find2DLinesIntersection(lineSeg1,lineSeg2,corner)) + if (!find2DLinesIntersection(lineSeg1, lineSeg2, corner)) { return false; + } - // Just project the given reference points onto the lines, just in case they are not already lying on + // Just project the given reference points onto the lines, just in case they are not already + // lying on Base::Vector3d normPnt1, normPnt2; - normPnt1.ProjectToLine(refPnt1-l1p1, l1p2-l1p1); - normPnt2.ProjectToLine(refPnt2-l2p1, l2p2-l2p1); + normPnt1.ProjectToLine(refPnt1 - l1p1, l1p2 - l1p1); + normPnt2.ProjectToLine(refPnt2 - l2p1, l2p2 - l2p1); normPnt1 += refPnt1; normPnt2 += refPnt2; - //Angle bisector - Base::Vector3d bisectDir = ((normPnt1 - corner).Normalize() + (normPnt2-corner).Normalize()).Normalize(); + // Angle bisector + Base::Vector3d bisectDir + = ((normPnt1 - corner).Normalize() + (normPnt2 - corner).Normalize()).Normalize(); - //redefine norms pointing towards bisect line + // redefine norms pointing towards bisect line Base::Vector3d normIntersection1, normIntersection2; - if (find2DLinesIntersection(normPnt1, norm1, corner, bisectDir, normIntersection1) && - find2DLinesIntersection(normPnt2, norm2, corner, bisectDir, normIntersection2)) { + if (find2DLinesIntersection(normPnt1, norm1, corner, bisectDir, normIntersection1) + && find2DLinesIntersection(normPnt2, norm2, corner, bisectDir, normIntersection2)) { norm1 = (normIntersection1 - normPnt1).Normalize(); norm2 = (normIntersection2 - normPnt2).Normalize(); - } else { + } + else { return false; } @@ -6187,53 +6352,68 @@ bool findFilletCenter(const GeomLineSegment *lineSeg1, const GeomLineSegment *li Base::Vector3d tmpPoint2 = l2p1 + (norm2 * radius); // found center point - if (find2DLinesIntersection(tmpPoint1, dir1, tmpPoint2, dir2, center)) + if (find2DLinesIntersection(tmpPoint1, dir1, tmpPoint2, dir2, center)) { return true; - else + } + else { return false; + } } // Returns -1 if radius cannot be suggested -double suggestFilletRadius(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, - const Base::Vector3d &refPnt1, const Base::Vector3d &refPnt2) +double suggestFilletRadius( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2 +) { Base::Vector3d corner; - if (!Part::find2DLinesIntersection(lineSeg1, lineSeg2, corner)) + if (!Part::find2DLinesIntersection(lineSeg1, lineSeg2, corner)) { return -1; + } Base::Vector3d dir1 = lineSeg1->getEndPoint() - lineSeg1->getStartPoint(); Base::Vector3d dir2 = lineSeg2->getEndPoint() - lineSeg2->getStartPoint(); // Decide the line directions depending on the reference points - if (dir1*(refPnt1-corner) < 0) + if (dir1 * (refPnt1 - corner) < 0) { dir1 *= -1; - if (dir2*(refPnt2-corner) < 0) + } + if (dir2 * (refPnt2 - corner) < 0) { dir2 *= -1; + } - //Angle bisector + // Angle bisector Base::Vector3d dirBisect = (dir1.Normalize() + dir2.Normalize()).Normalize(); Base::Vector3d projPnt1, projPnt2; - projPnt1.ProjectToLine(refPnt1-corner, dir1); - projPnt2.ProjectToLine(refPnt2-corner, dir2); + projPnt1.ProjectToLine(refPnt1 - corner, dir1); + projPnt2.ProjectToLine(refPnt2 - corner, dir2); projPnt1 += refPnt1; projPnt2 += refPnt2; Base::Vector3d norm1(dir1.y, -dir1.x, 0.f); Base::Vector3d norm2(dir2.y, -dir2.x, 0.f); - double r1=-1, r2=-1; + double r1 = -1, r2 = -1; Base::Vector3d center1, center2; - if (find2DLinesIntersection(projPnt1, norm1, corner, dirBisect, center1)) + if (find2DLinesIntersection(projPnt1, norm1, corner, dirBisect, center1)) { r1 = (projPnt1 - center1).Length(); - if (find2DLinesIntersection(projPnt2, norm2, corner, dirBisect, center2)) + } + if (find2DLinesIntersection(projPnt2, norm2, corner, dirBisect, center2)) { r2 = (projPnt1 - center2).Length(); + } return r1 < r2 ? r1 : r2; } -GeomArcOfCircle* create2LinesFilletGeometry(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, - const Base::Vector3d ¢er, double radius) +GeomArcOfCircle* create2LinesFilletGeometry( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + const Base::Vector3d& center, + double radius +) { Base::Vector3d corner; if (!Part::find2DLinesIntersection(lineSeg1, lineSeg2, corner)) { @@ -6251,21 +6431,26 @@ GeomArcOfCircle* create2LinesFilletGeometry(const GeomLineSegment *lineSeg1, con double startAngle, endAngle, range; startAngle = atan2(radDir1.y, radDir1.x); - range = atan2(-radDir1.y*radDir2.x+radDir1.x*radDir2.y, - radDir1.x*radDir2.x+radDir1.y*radDir2.y); + range = atan2( + -radDir1.y * radDir2.x + radDir1.x * radDir2.y, + radDir1.x * radDir2.x + radDir1.y * radDir2.y + ); endAngle = startAngle + range; - if (endAngle < startAngle) + if (endAngle < startAngle) { std::swap(startAngle, endAngle); + } - if (endAngle > 2 * std::numbers::pi) + if (endAngle > 2 * std::numbers::pi) { endAngle -= 2 * std::numbers::pi; + } - if (startAngle < 0) + if (startAngle < 0) { endAngle += 2 * std::numbers::pi; + } // Create Arc Segment - GeomArcOfCircle *arc = new GeomArcOfCircle(); + GeomArcOfCircle* arc = new GeomArcOfCircle(); arc->setRadius(radius); arc->setCenter(center); arc->setRange(startAngle, endAngle, /*emulateCCWXY=*/true); @@ -6273,8 +6458,16 @@ GeomArcOfCircle* create2LinesFilletGeometry(const GeomLineSegment *lineSeg1, con return arc; } -GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2, const Base::Vector3d& refPnt1, - const Base::Vector3d& refPnt2, double radius, int& pos1, int& pos2, bool& reverse) +GeomArcOfCircle* createFilletGeometry( + const Geometry* geo1, + const Geometry* geo2, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2, + double radius, + int& pos1, + int& pos2, + bool& reverse +) { if (geo1->is() && geo2->is()) { auto* line1 = static_cast(geo1); @@ -6286,7 +6479,8 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } auto arc = create2LinesFilletGeometry(line1, line2, filletCenter, radius); - // Before returning arc, we find pos and reverse. Note PointPos is in sketcher only so we use int. + // Before returning arc, we find pos and reverse. Note PointPos is in sketcher only so we + // use int. Base::Vector3d intersection, dist1, dist2; find2DLinesIntersection(line1, line2, intersection); @@ -6310,33 +6504,34 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 return (ip1 - ref1).Length() + (ip2 - ref2).Length(); }; - auto selectIntersection = - [&distanceToRefPoints](std::vector>& points, - std::pair& interpoints, - const Base::Vector3d& refPnt1, - const Base::Vector3d& refPnt2) { - if (points.empty()) { - return -1; + auto selectIntersection = [&distanceToRefPoints]( + std::vector>& points, + std::pair& interpoints, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2 + ) { + if (points.empty()) { + return -1; + } + + double dist = distanceToRefPoints(points[0].first, points[0].second, refPnt1, refPnt2); + int i = 0, si = 0; + + for (auto ipoints : points) { + double d = distanceToRefPoints(ipoints.first, ipoints.second, refPnt1, refPnt2); + + if (d < dist) { + si = i; + dist = d; } - double dist = distanceToRefPoints(points[0].first, points[0].second, refPnt1, refPnt2); - int i = 0, si = 0; + i++; + } - for (auto ipoints : points) { - double d = distanceToRefPoints(ipoints.first, ipoints.second, refPnt1, refPnt2); + interpoints = points[si]; - if (d < dist) { - si = i; - dist = d; - } - - i++; - } - - interpoints = points[si]; - - return 0; - }; + return 0; + }; // NOTE: While it is not a requirement that the endpoints of the corner to trim are // coincident @@ -6367,9 +6562,11 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } catch (Base::CADKernelError& e) { e.reportException(); - THROWM(Base::CADKernelError, - "Unable to determine the parameter of the first selected curve at the reference " - "point.") + THROWM( + Base::CADKernelError, + "Unable to determine the parameter of the first selected curve at the reference " + "point." + ) } try { @@ -6379,9 +6576,11 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } catch (Base::CADKernelError& e) { e.reportException(); - THROWM(Base::CADKernelError, - "Unable to determine the parameter of the second selected curve at the " - "reference point.") + THROWM( + Base::CADKernelError, + "Unable to determine the parameter of the second selected curve at the " + "reference point." + ) } std::pair interpoints; @@ -6439,7 +6638,7 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 if (dist == INFINITY) { // no coincident was found, try basis curve intersection if GeomTrimmedCurve if (!geo1->isDerivedFrom() || !geo2->isDerivedFrom()) { - return nullptr;// not a GeomTrimmedCurve and no coincident point. + return nullptr; // not a GeomTrimmedCurve and no coincident point. } auto* tcurve1 = static_cast(geo1); @@ -6452,11 +6651,15 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } catch (Base::CADKernelError& e) { e.reportException(); - THROWMT(Base::CADKernelError, - QT_TRANSLATE_NOOP("Exceptions", + THROWMT( + Base::CADKernelError, + QT_TRANSLATE_NOOP( + "Exceptions", "Unable to guess intersection of curves. Try adding " "a coincident constraint between the vertices of the " - "curves you are intending to fillet.")) + "curves you are intending to fillet." + ) + ) } int res = selectIntersection(points, interpoints, refPnt1, refPnt2); @@ -6478,9 +6681,11 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } catch (Base::CADKernelError& e) { e.reportException(); - THROWM(Base::CADKernelError, - "Unable to determine the parameter of the first selected curve at the " - "intersection of the curves.") + THROWM( + Base::CADKernelError, + "Unable to determine the parameter of the first selected curve at the " + "intersection of the curves." + ) } try { @@ -6490,9 +6695,11 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 } catch (Base::CADKernelError& e) { e.reportException(); - THROWM(Base::CADKernelError, - "Unable to determine the parameter of the second selected curve at the " - "intersection of the curves.") + THROWM( + Base::CADKernelError, + "Unable to determine the parameter of the second selected curve at the " + "intersection of the curves." + ) } // get the starting parameters of each curve @@ -6542,12 +6749,14 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 (-dir1.x * dir2.y * refp1.y + dir2.x * dir1.y * refp2.y + dir1.y * dir2.y * refp1.x - dir1.y * dir2.y * refp2.x) / det, - 0); + 0 + ); - radius = ((refp1 - normalintersect).Length() + (refp2 - normalintersect).Length()) / 2; + radius = ((refp1 - normalintersect).Length() + (refp2 - normalintersect).Length()) + / 2; } catch (const Base::Exception&) { - radius = ref21.Length();// fall-back to simplest estimation. + radius = ref21.Length(); // fall-back to simplest estimation. } } @@ -6562,10 +6771,16 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 double sdir2 = tdir2.Cross(-ref21).Dot(vn); auto* ocurve1 = new GeomOffsetCurve( - Handle(Geom_Curve)::DownCast(curve1->handle()), (sdir1 < 0) ? radius : -radius, vn); + Handle(Geom_Curve)::DownCast(curve1->handle()), + (sdir1 < 0) ? radius : -radius, + vn + ); auto* ocurve2 = new GeomOffsetCurve( - Handle(Geom_Curve)::DownCast(curve2->handle()), (sdir2 < 0) ? radius : -radius, vn); + Handle(Geom_Curve)::DownCast(curve2->handle()), + (sdir2 < 0) ? radius : -radius, + vn + ); // Next we calculate the intersection of offset curves to get the center of the fillet std::pair filletcenterpoint; @@ -6623,8 +6838,10 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 startAngle = atan2(radDir1.y, radDir1.x); - range = atan2(-radDir1.y * radDir2.x + radDir1.x * radDir2.y, - radDir1.x * radDir2.x + radDir1.y * radDir2.y); + range = atan2( + -radDir1.y * radDir2.x + radDir1.x * radDir2.y, + radDir1.x * radDir2.x + radDir1.y * radDir2.y + ); if (fmod(fabs(range), 2 * std::numbers::pi) < Precision::Approximation()) { return nullptr; @@ -6653,7 +6870,8 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 delete ocurve1; delete ocurve2; - // Before returning arc, we find pos and reverse. Note PointPos is in sketcher only so we use int. + // Before returning arc, we find pos and reverse. Note PointPos is in sketcher only so we + // use int. auto selectend = [](double intparam, double refparam, double startparam) { if ((intparam > refparam && startparam >= refparam) || (intparam < refparam && startparam <= refparam)) { @@ -6682,13 +6900,14 @@ GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2 return nullptr; } -std::unique_ptr makeFromSurface(const Handle(Geom_Surface)& s, bool silent) +std::unique_ptr makeFromSurface(const Handle(Geom_Surface) & s, bool silent) { std::unique_ptr geoSurf; if (s.IsNull()) { - if (!silent) + if (!silent) { throw Base::ValueError("Null surface"); + } return geoSurf; } @@ -6729,7 +6948,9 @@ std::unique_ptr makeFromSurface(const Handle(Geom_Surface)& s, bool geoSurf = std::make_unique(hSurf); } else if (s->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) { - Handle(Geom_RectangularTrimmedSurface) hSurf = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) hSurf = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); geoSurf = std::make_unique(hSurf); } else if (s->IsKind(STANDARD_TYPE(Geom_SurfaceOfRevolution))) { @@ -6737,7 +6958,9 @@ std::unique_ptr makeFromSurface(const Handle(Geom_Surface)& s, bool geoSurf = std::make_unique(hSurf); } else if (s->IsKind(STANDARD_TYPE(Geom_SurfaceOfLinearExtrusion))) { - Handle(Geom_SurfaceOfLinearExtrusion) hSurf = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(s); + Handle(Geom_SurfaceOfLinearExtrusion) hSurf = Handle( + Geom_SurfaceOfLinearExtrusion + )::DownCast(s); geoSurf = std::make_unique(hSurf); } else { @@ -6753,105 +6976,110 @@ std::unique_ptr makeFromSurfaceAdaptor(const BRepAdaptor_Surface& a { std::unique_ptr geoSurf; - switch(adapt.GetType()) - { - case GeomAbs_Plane: - { + switch (adapt.GetType()) { + case GeomAbs_Plane: { geoSurf.reset(new GeomPlane()); - Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast - (geoSurf->handle()); + Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast(geoSurf->handle()); this_surf->SetPln(adapt.Plane()); break; } - case GeomAbs_Cylinder: - { + case GeomAbs_Cylinder: { geoSurf.reset(new GeomCylinder()); - Handle(Geom_CylindricalSurface) this_surf = Handle(Geom_CylindricalSurface)::DownCast - (geoSurf->handle()); + Handle(Geom_CylindricalSurface) this_surf = Handle(Geom_CylindricalSurface)::DownCast( + geoSurf->handle() + ); this_surf->SetCylinder(adapt.Cylinder()); break; } - case GeomAbs_Cone: - { + case GeomAbs_Cone: { geoSurf.reset(new GeomCone()); - Handle(Geom_ConicalSurface) this_surf = Handle(Geom_ConicalSurface)::DownCast - (geoSurf->handle()); + Handle(Geom_ConicalSurface) this_surf = Handle(Geom_ConicalSurface)::DownCast( + geoSurf->handle() + ); this_surf->SetCone(adapt.Cone()); break; } - case GeomAbs_Sphere: - { + case GeomAbs_Sphere: { geoSurf.reset(new GeomSphere()); - Handle(Geom_SphericalSurface) this_surf = Handle(Geom_SphericalSurface)::DownCast - (geoSurf->handle()); + Handle(Geom_SphericalSurface) this_surf = Handle(Geom_SphericalSurface)::DownCast( + geoSurf->handle() + ); this_surf->SetSphere(adapt.Sphere()); break; } - case GeomAbs_Torus: - { + case GeomAbs_Torus: { geoSurf.reset(new GeomToroid()); - Handle(Geom_ToroidalSurface) this_surf = Handle(Geom_ToroidalSurface)::DownCast - (geoSurf->handle()); + Handle(Geom_ToroidalSurface) this_surf = Handle(Geom_ToroidalSurface)::DownCast( + geoSurf->handle() + ); this_surf->SetTorus(adapt.Torus()); break; } - case GeomAbs_BezierSurface: - { + case GeomAbs_BezierSurface: { geoSurf.reset(new GeomBezierSurface(adapt.Bezier())); break; } - case GeomAbs_BSplineSurface: - { + case GeomAbs_BSplineSurface: { geoSurf.reset(new GeomBSplineSurface(adapt.BSpline())); break; } - case GeomAbs_SurfaceOfRevolution: - { + case GeomAbs_SurfaceOfRevolution: { Handle(Geom_Surface) s = BRep_Tool::Surface(adapt.Face()); Handle(Geom_SurfaceOfRevolution) rev = Handle(Geom_SurfaceOfRevolution)::DownCast(s); if (rev.IsNull()) { - Handle(Geom_RectangularTrimmedSurface) rect = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) rect = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); rev = Handle(Geom_SurfaceOfRevolution)::DownCast(rect->BasisSurface()); } - if (!rev.IsNull()) + if (!rev.IsNull()) { geoSurf.reset(new GeomSurfaceOfRevolution(rev)); + } break; } - case GeomAbs_SurfaceOfExtrusion: - { + case GeomAbs_SurfaceOfExtrusion: { Handle(Geom_Surface) s = BRep_Tool::Surface(adapt.Face()); - Handle(Geom_SurfaceOfLinearExtrusion) ext = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(s); + Handle(Geom_SurfaceOfLinearExtrusion) ext = Handle( + Geom_SurfaceOfLinearExtrusion + )::DownCast(s); if (ext.IsNull()) { - Handle(Geom_RectangularTrimmedSurface) rect = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) rect = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); ext = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(rect->BasisSurface()); } - if (!ext.IsNull()) + if (!ext.IsNull()) { geoSurf.reset(new GeomSurfaceOfExtrusion(ext)); + } break; } - case GeomAbs_OffsetSurface: - { + case GeomAbs_OffsetSurface: { Handle(Geom_Surface) s = BRep_Tool::Surface(adapt.Face()); Handle(Geom_OffsetSurface) off = Handle(Geom_OffsetSurface)::DownCast(s); if (off.IsNull()) { - Handle(Geom_RectangularTrimmedSurface) rect = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) rect = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); off = Handle(Geom_OffsetSurface)::DownCast(rect->BasisSurface()); } - if (!off.IsNull()) + if (!off.IsNull()) { geoSurf.reset(new GeomOffsetSurface(off)); + } break; } - default: - break; + default: + break; } if (!geoSurf && !silent) { std::string err = "Cannot convert surface type "; Handle(Geom_Surface) s = BRep_Tool::Surface(adapt.Face()); - if (s) + if (s) { err += s->DynamicType()->Name(); - else + } + else { err += " unknown"; + } throw Base::TypeError(err); } @@ -6859,13 +7087,14 @@ std::unique_ptr makeFromSurfaceAdaptor(const BRepAdaptor_Surface& a } -std::unique_ptr makeFromCurve(const Handle(Geom_Curve)& c, bool silent) +std::unique_ptr makeFromCurve(const Handle(Geom_Curve) & c, bool silent) { std::unique_ptr geoCurve; if (c.IsNull()) { - if (!silent) + if (!silent) { throw Base::ValueError("Null curve"); + } return geoCurve; } @@ -6917,21 +7146,20 @@ std::unique_ptr makeFromCurve(const Handle(Geom_Curve)& c, bool silen return geoCurve; } -std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, double f, double l, bool silent) +std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve) & c, double f, double l, bool silent) { if (c.IsNull()) { - if (!silent) + if (!silent) { throw Base::ValueError("Null curve"); + } return std::unique_ptr(); } if (c->IsKind(STANDARD_TYPE(Geom_Circle))) { Handle(Geom_Circle) circ = Handle(Geom_Circle)::DownCast(c); std::unique_ptr arc(new GeomArcOfCircle()); - Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom_Circle) this_circ = Handle(Geom_Circle)::DownCast - (this_arc->BasisCurve()); + Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom_Circle) this_circ = Handle(Geom_Circle)::DownCast(this_arc->BasisCurve()); this_circ->SetCirc(circ->Circ()); this_arc->SetTrim(f, l); return arc; @@ -6939,10 +7167,8 @@ std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, dou else if (c->IsKind(STANDARD_TYPE(Geom_Ellipse))) { Handle(Geom_Ellipse) ellp = Handle(Geom_Ellipse)::DownCast(c); std::unique_ptr arc(new GeomArcOfEllipse()); - Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom_Ellipse) this_ellp = Handle(Geom_Ellipse)::DownCast - (this_arc->BasisCurve()); + Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom_Ellipse) this_ellp = Handle(Geom_Ellipse)::DownCast(this_arc->BasisCurve()); this_ellp->SetElips(ellp->Elips()); this_arc->SetTrim(f, l); return arc; @@ -6950,10 +7176,8 @@ std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, dou else if (c->IsKind(STANDARD_TYPE(Geom_Hyperbola))) { Handle(Geom_Hyperbola) hypr = Handle(Geom_Hyperbola)::DownCast(c); std::unique_ptr arc(new GeomArcOfHyperbola()); - Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom_Hyperbola) this_hypr = Handle(Geom_Hyperbola)::DownCast - (this_arc->BasisCurve()); + Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom_Hyperbola) this_hypr = Handle(Geom_Hyperbola)::DownCast(this_arc->BasisCurve()); this_hypr->SetHypr(hypr->Hypr()); this_arc->SetTrim(f, l); return arc; @@ -6961,10 +7185,8 @@ std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, dou else if (c->IsKind(STANDARD_TYPE(Geom_Line))) { Handle(Geom_Line) line = Handle(Geom_Line)::DownCast(c); std::unique_ptr segm(new GeomLineSegment()); - Handle(Geom_TrimmedCurve) this_segm = Handle(Geom_TrimmedCurve)::DownCast - (segm->handle()); - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_segm->BasisCurve()); + Handle(Geom_TrimmedCurve) this_segm = Handle(Geom_TrimmedCurve)::DownCast(segm->handle()); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_segm->BasisCurve()); this_line->SetLin(line->Lin()); this_segm->SetTrim(f, l); return segm; @@ -6972,10 +7194,8 @@ std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, dou else if (c->IsKind(STANDARD_TYPE(Geom_Parabola))) { Handle(Geom_Parabola) para = Handle(Geom_Parabola)::DownCast(c); std::unique_ptr arc(new GeomArcOfParabola()); - Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom_Parabola) this_para = Handle(Geom_Parabola)::DownCast - (this_arc->BasisCurve()); + Handle(Geom_TrimmedCurve) this_arc = Handle(Geom_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom_Parabola) this_para = Handle(Geom_Parabola)::DownCast(this_arc->BasisCurve()); this_para->SetParab(para->Parab()); this_arc->SetTrim(f, l); return arc; @@ -6995,7 +7215,9 @@ std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, dou double v = oc->Offset(); gp_Dir dir = oc->Direction(); std::unique_ptr bc(makeFromTrimmedCurve(oc->BasisCurve(), f, l)); - return std::unique_ptr(new GeomOffsetCurve(Handle(Geom_Curve)::DownCast(bc->handle()), v, dir)); + return std::unique_ptr( + new GeomOffsetCurve(Handle(Geom_Curve)::DownCast(bc->handle()), v, dir) + ); } else if (c->IsKind(STANDARD_TYPE(Geom_TrimmedCurve))) { Handle(Geom_TrimmedCurve) trc = Handle(Geom_TrimmedCurve)::DownCast(c); @@ -7017,77 +7239,63 @@ std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)& c, dou std::unique_ptr makeFromCurveAdaptor(const Adaptor3d_Curve& adapt, bool silent) { std::unique_ptr geoCurve; - switch (adapt.GetType()) - { - case GeomAbs_Line: - { + switch (adapt.GetType()) { + case GeomAbs_Line: { geoCurve = std::make_unique(); - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (geoCurve->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(geoCurve->handle()); this_curv->SetLin(adapt.Line()); break; } - case GeomAbs_Circle: - { + case GeomAbs_Circle: { geoCurve = std::make_unique(); - Handle(Geom_Circle) this_curv = Handle(Geom_Circle)::DownCast - (geoCurve->handle()); + Handle(Geom_Circle) this_curv = Handle(Geom_Circle)::DownCast(geoCurve->handle()); this_curv->SetCirc(adapt.Circle()); break; } - case GeomAbs_Ellipse: - { + case GeomAbs_Ellipse: { geoCurve = std::make_unique(); - Handle(Geom_Ellipse) this_curv = Handle(Geom_Ellipse)::DownCast - (geoCurve->handle()); + Handle(Geom_Ellipse) this_curv = Handle(Geom_Ellipse)::DownCast(geoCurve->handle()); this_curv->SetElips(adapt.Ellipse()); break; } - case GeomAbs_Hyperbola: - { + case GeomAbs_Hyperbola: { geoCurve = std::make_unique(); - Handle(Geom_Hyperbola) this_curv = Handle(Geom_Hyperbola)::DownCast - (geoCurve->handle()); + Handle(Geom_Hyperbola) this_curv = Handle(Geom_Hyperbola)::DownCast(geoCurve->handle()); this_curv->SetHypr(adapt.Hyperbola()); break; } - case GeomAbs_Parabola: - { + case GeomAbs_Parabola: { geoCurve = std::make_unique(); - Handle(Geom_Parabola) this_curv = Handle(Geom_Parabola)::DownCast - (geoCurve->handle()); + Handle(Geom_Parabola) this_curv = Handle(Geom_Parabola)::DownCast(geoCurve->handle()); this_curv->SetParab(adapt.Parabola()); break; } - case GeomAbs_BezierCurve: - { + case GeomAbs_BezierCurve: { geoCurve = std::make_unique(adapt.Bezier()); break; } - case GeomAbs_BSplineCurve: - { + case GeomAbs_BSplineCurve: { geoCurve = std::make_unique(adapt.BSpline()); break; } - case GeomAbs_OffsetCurve: - { + case GeomAbs_OffsetCurve: { geoCurve = std::make_unique(adapt.OffsetCurve()); break; } - case GeomAbs_OtherCurve: - default: - break; + case GeomAbs_OtherCurve: + default: + break; } if (!geoCurve) { - if (!silent) + if (!silent) { throw Base::TypeError("Unhandled curve type"); + } return geoCurve; } // Check if the curve must be trimmed - Handle(Geom_Curve) curv3d = Handle(Geom_Curve)::DownCast - (geoCurve->handle()); + Handle(Geom_Curve) curv3d = Handle(Geom_Curve)::DownCast(geoCurve->handle()); double u = curv3d->FirstParameter(); double v = curv3d->LastParameter(); if (u != adapt.FirstParameter() || v != adapt.LastParameter()) { @@ -7097,6 +7305,4 @@ std::unique_ptr makeFromCurveAdaptor(const Adaptor3d_Curve& adapt, bo return geoCurve; } -} // namespace Part - - +} // namespace Part diff --git a/src/Mod/Part/App/Geometry.h b/src/Mod/Part/App/Geometry.h index f6449b2267..f38f44bc60 100644 --- a/src/Mod/Part/App/Geometry.h +++ b/src/Mod/Part/App/Geometry.h @@ -74,7 +74,8 @@ #include "GeometryExtension.h" -namespace Part { +namespace Part +{ enum KeepTag { @@ -85,44 +86,47 @@ enum KeepTag class PartExport Geometry: public Base::Persistence { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: ~Geometry() override; - static std::unique_ptr fromShape(const TopoDS_Shape &s, bool silent=false); + static std::unique_ptr fromShape(const TopoDS_Shape& s, bool silent = false); virtual TopoDS_Shape toShape() const = 0; - virtual const Handle(Geom_Geometry)& handle() const = 0; + virtual const Handle(Geom_Geometry) & handle() const = 0; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; - /// returns a copy of this object having a new randomly generated tag. If you also want to copy the tag, you may use clone() instead. - /// For creation of geometry with other handles, with or without the same tag, you may use the constructors and the sethandle functions. - /// The tag of a geometry can be copied to another geometry using the assignTag function. - virtual Geometry *copy() const = 0; - /// returns a cloned object. A cloned object has the same tag (see getTag) as the original object. - /// if you want a copy not having the same tag, you can use copy() instead. - /// If you want a clone with another geometry handle, it is possible to clone an object and then assign another handle or to create an object - /// via constructor and use assignTag to assign the tag of the other geometry. - /// If you do not desire to have the same tag, then a copy can be performed by using a constructor (which will generate another tag) - /// and then, if necessary (e.g. if the constructor did not take a handle as a parameter), set a new handle. - Geometry *clone() const; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; + /// returns a copy of this object having a new randomly generated tag. If you also want to copy + /// the tag, you may use clone() instead. For creation of geometry with other handles, with or + /// without the same tag, you may use the constructors and the sethandle functions. The tag of a + /// geometry can be copied to another geometry using the assignTag function. + virtual Geometry* copy() const = 0; + /// returns a cloned object. A cloned object has the same tag (see getTag) as the original + /// object. if you want a copy not having the same tag, you can use copy() instead. If you want + /// a clone with another geometry handle, it is possible to clone an object and then assign + /// another handle or to create an object via constructor and use assignTag to assign the tag of + /// the other geometry. If you do not desire to have the same tag, then a copy can be performed + /// by using a constructor (which will generate another tag) and then, if necessary (e.g. if the + /// constructor did not take a handle as a parameter), set a new handle. + Geometry* clone() const; /// returns the tag of the geometry object boost::uuids::uuid getTag() const; - virtual bool isSame(const Geometry &other, double tol, double atol) const = 0; - bool hasSameExtensions(const Geometry &other) const; + virtual bool isSame(const Geometry& other, double tol, double atol) const = 0; + bool hasSameExtensions(const Geometry& other) const; std::vector> getExtensions() const; - bool hasExtension(const Base::Type & type) const; - bool hasExtension(const std::string & name) const; - std::weak_ptr getExtension(const Base::Type & type) const; - std::weak_ptr getExtension(const std::string & name) const; - std::weak_ptr getExtension(const Base::Type & type); - std::weak_ptr getExtension(const std::string & name); - void setExtension(std::unique_ptr &&geo); - void deleteExtension(const Base::Type & type); - void deleteExtension(const std::string & name); + bool hasExtension(const Base::Type& type) const; + bool hasExtension(const std::string& name) const; + std::weak_ptr getExtension(const Base::Type& type) const; + std::weak_ptr getExtension(const std::string& name) const; + std::weak_ptr getExtension(const Base::Type& type); + std::weak_ptr getExtension(const std::string& name); + void setExtension(std::unique_ptr&& geo); + void deleteExtension(const Base::Type& type); + void deleteExtension(const std::string& name); void mirror(const Base::Vector3d& point) const; void mirror(const Base::Vector3d& point, const Base::Vector3d& dir) const; @@ -140,9 +144,9 @@ protected: /// create a new tag for the geometry object void createNewTag(); /// copies the tag from the geometry passed as a parameter to this object - void assignTag(const Part::Geometry *); + void assignTag(const Part::Geometry*); - void copyNonTag(const Part::Geometry *); + void copyNonTag(const Part::Geometry*); protected: Geometry(); @@ -153,24 +157,25 @@ protected: public: Geometry(const Geometry&) = delete; - Geometry& operator = (const Geometry&) = delete; + Geometry& operator=(const Geometry&) = delete; }; -class PartExport GeomPoint : public Geometry +class PartExport GeomPoint: public Geometry { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomPoint(); - explicit GeomPoint(const Handle(Geom_CartesianPoint)&); + explicit GeomPoint(const Handle(Geom_CartesianPoint) &); explicit GeomPoint(const Base::Vector3d&); ~GeomPoint() override; - Geometry *copy() const override; + Geometry* copy() const override; TopoDS_Shape toShape() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- PyObject* getPyObject() override; /** @@ -181,10 +186,10 @@ public: * @return True if a match is found. */ bool isSame(const Geometry& other, double tol, double atol) const override; - const Handle(Geom_Geometry)& handle() const override; - void setHandle(const Handle(Geom_CartesianPoint)&); + const Handle(Geom_Geometry) & handle() const override; + void setHandle(const Handle(Geom_CartesianPoint) &); - Base::Vector3d getPoint()const; + Base::Vector3d getPoint() const; void setPoint(const Base::Vector3d&); private: @@ -195,15 +200,20 @@ class GeomBSplineCurve; class GeomLine; class GeomLineSegment; -class PartExport GeomCurve : public Geometry +class PartExport GeomCurve: public Geometry { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomCurve(); ~GeomCurve() override; - static bool isLinear(const Handle(Geom_Curve) &c, Base::Vector3d *dir = nullptr, Base::Vector3d *base = nullptr); - bool isLinear(Base::Vector3d *dir = nullptr, Base::Vector3d *base = nullptr) const; + static bool isLinear( + const Handle(Geom_Curve) & c, + Base::Vector3d* dir = nullptr, + Base::Vector3d* base = nullptr + ); + bool isLinear(Base::Vector3d* dir = nullptr, Base::Vector3d* base = nullptr) const; TopoDS_Shape toShape() const override; /*! @@ -231,17 +241,19 @@ public: Base::Vector3d pointAtParameter(double u) const; Base::Vector3d firstDerivativeAtParameter(double u) const; Base::Vector3d secondDerivativeAtParameter(double u) const; - bool closestParameter(const Base::Vector3d& point, double &u) const; - bool closestParameterToBasisCurve(const Base::Vector3d& point, double &u) const; + bool closestParameter(const Base::Vector3d& point, double& u) const; + bool closestParameterToBasisCurve(const Base::Vector3d& point, double& u) const; double getFirstParameter() const; double getLastParameter() const; double curvatureAt(double u) const; double length(double u, double v) const; bool normalAt(double u, Base::Vector3d& dir) const; - bool normalAt(const Base::Vector3d & curvepoint, Base::Vector3d& dir) const; - bool intersect(const GeomCurve *c, - std::vector>& points, - double tol = Precision::Confusion()) const; + bool normalAt(const Base::Vector3d& curvepoint, Base::Vector3d& dir) const; + bool intersect( + const GeomCurve* c, + std::vector>& points, + double tol = Precision::Confusion() + ) const; void reverse(); @@ -251,14 +263,18 @@ public: GeomLineSegment* toLineSegment(KeepTag clone = CopyTag) const; protected: - static bool intersect(const Handle(Geom_Curve)& c, const Handle(Geom_Curve)& c2, - std::vector>& points, - double tol = Precision::Confusion()); + static bool intersect( + const Handle(Geom_Curve) & c, + const Handle(Geom_Curve) & c2, + std::vector>& points, + double tol = Precision::Confusion() + ); }; -class PartExport GeomBoundedCurve : public GeomCurve +class PartExport GeomBoundedCurve: public GeomCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomBoundedCurve(); ~GeomBoundedCurve() override; @@ -268,53 +284,61 @@ public: virtual Base::Vector3d getEndPoint() const; }; -class PartExport GeomBezierCurve : public GeomBoundedCurve +class PartExport GeomBezierCurve: public GeomBoundedCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomBezierCurve(); - explicit GeomBezierCurve(const Handle(Geom_BezierCurve)&); + explicit GeomBezierCurve(const Handle(Geom_BezierCurve) &); GeomBezierCurve(const std::vector&, const std::vector&); ~GeomBezierCurve() override; - Geometry *copy() const override; + Geometry* copy() const override; std::vector getPoles() const; std::vector getWeights() const; // Persistence implementer --------------------- - unsigned int getMemSize () const override; - void Save (Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + unsigned int getMemSize() const override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject(void) override; - bool isSame(const Geometry &other, double tol, double atol) const override; + PyObject* getPyObject(void) override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_BezierCurve)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_BezierCurve) &); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_BezierCurve) myCurve; }; -class PartExport GeomBSplineCurve : public GeomBoundedCurve +class PartExport GeomBSplineCurve: public GeomBoundedCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomBSplineCurve(); - explicit GeomBSplineCurve(const Handle(Geom_BSplineCurve)&); + explicit GeomBSplineCurve(const Handle(Geom_BSplineCurve) &); - GeomBSplineCurve( const std::vector& poles, const std::vector& weights, - const std::vector& knots, const std::vector& multiplicities, - int degree, bool periodic=false, bool checkrational = true); + GeomBSplineCurve( + const std::vector& poles, + const std::vector& weights, + const std::vector& knots, + const std::vector& multiplicities, + int degree, + bool periodic = false, + bool checkrational = true + ); ~GeomBSplineCurve() override; - Geometry *copy() const override; + Geometry* copy() const override; GeomCurve* createArc(double first, double last) const override; - /*! - * Interpolate a spline passing through the given points without tangency. - */ - void interpolate(const std::vector&, Standard_Boolean=Standard_False); + /*! + * Interpolate a spline passing through the given points without tangency. + */ + void interpolate(const std::vector&, Standard_Boolean = Standard_False); /*! * Set the poles and tangents for the cubic Hermite spline */ @@ -323,24 +347,25 @@ public: * Compute the tangents for a Cardinal spline using the * the cubic Hermite spline. It uses the method for Cardinal splines. */ - void getCardinalSplineTangents(const std::vector&, - const std::vector&, - std::vector&) const; + void getCardinalSplineTangents( + const std::vector&, + const std::vector&, + std::vector& + ) const; /*! * Compute the tangents for a Cardinal spline using the * the cubic Hermite spline. It uses the method for Cardinal splines. * It uses the same parameter for each tangent. */ - void getCardinalSplineTangents(const std::vector&, double, - std::vector&) const; + void getCardinalSplineTangents(const std::vector&, double, std::vector&) const; int countPoles() const; int countKnots() const; - void setPole(int index, const Base::Vector3d&, double weight=-1); + void setPole(int index, const Base::Vector3d&, double weight = -1); void setPoles(const std::vector& poles, const std::vector& weights); void setPoles(const std::vector& poles); void setWeights(const std::vector& weights); - void setKnot(int index, const double val, int mult=-1); + void setKnot(int index, const double val, int mult = -1); void setKnots(const std::vector& knots); void setKnots(const std::vector& knots, const std::vector& multiplicities); std::vector getPoles() const; @@ -352,20 +377,36 @@ public: bool isPeriodic() const; void setPeriodic() const; bool isRational() const; - bool join(const Handle(Geom_BoundedCurve)&); + bool join(const Handle(Geom_BoundedCurve) &); void makeC1Continuous(double, double); std::list toBiArcs(double tolerance) const; void increaseDegree(int degree); void approximate(double tol3d, int maxSegments, int maxDegree, GeomAbs_Shape continuity); - void approximate(const std::vector& pnts, int minDegree = 3, int maxDegree = 8, - GeomAbs_Shape continuity = GeomAbs_C2, double tol3d = 1.0e-3); - void approximate(const std::vector& pnts, Approx_ParametrizationType parType, - int minDegree = 3, int maxDegree = 8, - GeomAbs_Shape continuity = GeomAbs_C2, double tol3d = 1.0e-3); - void approximate(const std::vector& pnts, - double weight1, double weight2, double weight3, int maxDegree = 8, - GeomAbs_Shape continuity = GeomAbs_C2, double tol3d = 1.0e-3); + void approximate( + const std::vector& pnts, + int minDegree = 3, + int maxDegree = 8, + GeomAbs_Shape continuity = GeomAbs_C2, + double tol3d = 1.0e-3 + ); + void approximate( + const std::vector& pnts, + Approx_ParametrizationType parType, + int minDegree = 3, + int maxDegree = 8, + GeomAbs_Shape continuity = GeomAbs_C2, + double tol3d = 1.0e-3 + ); + void approximate( + const std::vector& pnts, + double weight1, + double weight2, + double weight3, + int maxDegree = 8, + GeomAbs_Shape continuity = GeomAbs_C2, + double tol3d = 1.0e-3 + ); void increaseMultiplicity(int index, int multiplicity); void insertKnot(double param, int multiplicity); @@ -376,31 +417,32 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_BSplineCurve)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_BSplineCurve) &); + const Handle(Geom_Geometry) & handle() const override; private: - // If during assignment of weights (during the for loop iteratively setting the poles) all weights - // become (temporarily) equal even though weights does not have equal values - // OCCT will convert all the weights (the already assigned and those not yet assigned) - // to 1.0 (nonrational b-splines have 1.0 weights). This may lead to the assignment of wrong - // of weight values. + // If during assignment of weights (during the for loop iteratively setting the poles) all + // weights become (temporarily) equal even though weights does not have equal values OCCT will + // convert all the weights (the already assigned and those not yet assigned) to 1.0 (nonrational + // b-splines have 1.0 weights). This may lead to the assignment of wrong of weight values. // - // The work-around is to temporarily set the last weight to be assigned to a value different from - // the current value and the to-be-assigned value for the weight at position last-to-be-assign but one. + // The work-around is to temporarily set the last weight to be assigned to a value different + // from the current value and the to-be-assigned value for the weight at position + // last-to-be-assign but one. void workAroundOCCTBug(const std::vector& weights); + private: Handle(Geom_BSplineCurve) myCurve; }; -class PartExport GeomConic : public GeomCurve +class PartExport GeomConic: public GeomCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -409,7 +451,7 @@ protected: public: ~GeomConic() override; - Geometry *copy() const override = 0; + Geometry* copy() const override = 0; /*! * \deprecated use getLocation @@ -432,39 +474,42 @@ public: Base::Vector3d getAxisDirection() const; unsigned int getMemSize() const override = 0; - PyObject *getPyObject() override = 0; + PyObject* getPyObject() override = 0; GeomBSplineCurve* toNurbs(double first, double last) const override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - const Handle(Geom_Geometry)& handle() const override = 0; + const Handle(Geom_Geometry) & handle() const override = 0; }; -class PartExport GeomTrimmedCurve : public GeomBoundedCurve +class PartExport GeomTrimmedCurve: public GeomBoundedCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomTrimmedCurve(); - explicit GeomTrimmedCurve(const Handle(Geom_TrimmedCurve)&); + explicit GeomTrimmedCurve(const Handle(Geom_TrimmedCurve) &); ~GeomTrimmedCurve() override; - Geometry *copy() const override; + Geometry* copy() const override; GeomCurve* createArc(double first, double last) const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject(void) override; + PyObject* getPyObject(void) override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - virtual void setHandle(const Handle(Geom_TrimmedCurve)&); - const Handle(Geom_Geometry)& handle() const override; + virtual void setHandle(const Handle(Geom_TrimmedCurve) &); + const Handle(Geom_Geometry) & handle() const override; - bool intersectBasisCurves( const GeomTrimmedCurve * c, - std::vector>& points, - double tol = Precision::Confusion()) const; + bool intersectBasisCurves( + const GeomTrimmedCurve* c, + std::vector>& points, + double tol = Precision::Confusion() + ) const; virtual void getRange(double& u, double& v) const; virtual void setRange(double u, double v); @@ -474,8 +519,7 @@ protected: }; - -class PartExport GeomArcOfConic : public GeomTrimmedCurve +class PartExport GeomArcOfConic: public GeomTrimmedCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -484,13 +528,19 @@ protected: public: ~GeomArcOfConic() override; - Geometry *copy() const override = 0; + Geometry* copy() const override = 0; Base::Vector3d getStartPoint(bool emulateCCWXY) const; Base::Vector3d getEndPoint(bool emulateCCWXY) const; - inline Base::Vector3d getStartPoint() const override {return getStartPoint(false);} - inline Base::Vector3d getEndPoint() const override {return getEndPoint(false);} + inline Base::Vector3d getStartPoint() const override + { + return getStartPoint(false); + } + inline Base::Vector3d getEndPoint() const override + { + return getEndPoint(false); + } /*! * \deprecated use getLocation * \brief getCenter @@ -509,8 +559,14 @@ public: virtual void getRange(double& u, double& v, bool emulateCCWXY) const = 0; virtual void setRange(double u, double v, bool emulateCCWXY) = 0; - inline void getRange(double& u, double& v) const override { getRange(u,v,false);} - inline void setRange(double u, double v) override { setRange(u,v,false);} + inline void getRange(double& u, double& v) const override + { + getRange(u, v, false); + } + inline void setRange(double u, double v) override + { + setRange(u, v, false); + } bool isReversed() const; bool reverseIfReversed() override; @@ -521,19 +577,20 @@ public: void setXAxisDir(const Base::Vector3d& newdir); unsigned int getMemSize() const override = 0; - PyObject *getPyObject() override = 0; + PyObject* getPyObject() override = 0; - const Handle(Geom_Geometry)& handle() const override = 0; + const Handle(Geom_Geometry) & handle() const override = 0; }; -class PartExport GeomCircle : public GeomConic +class PartExport GeomCircle: public GeomConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomCircle(); - explicit GeomCircle(const Handle(Geom_Circle)&); + explicit GeomCircle(const Handle(Geom_Circle) &); ~GeomCircle() override; - Geometry *copy() const override; + Geometry* copy() const override; GeomCurve* createArc(double first, double last) const override; double getRadius() const; @@ -541,30 +598,31 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - const Handle(Geom_Geometry)& handle() const override; + const Handle(Geom_Geometry) & handle() const override; - void setHandle(const Handle(Geom_Circle)&); + void setHandle(const Handle(Geom_Circle) &); private: Handle(Geom_Circle) myCurve; }; -class PartExport GeomArcOfCircle : public GeomArcOfConic +class PartExport GeomArcOfCircle: public GeomArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomArcOfCircle(); - explicit GeomArcOfCircle(const Handle(Geom_Circle)&); + explicit GeomArcOfCircle(const Handle(Geom_Circle) &); ~GeomArcOfCircle() override; - Geometry *copy() const override; + Geometry* copy() const override; double getRadius() const; void setRadius(double Radius); @@ -576,26 +634,26 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - void setHandle(const Handle(Geom_TrimmedCurve)&) override; - void setHandle(const Handle(Geom_Circle)&); - const Handle(Geom_Geometry)& handle() const override; - + void setHandle(const Handle(Geom_TrimmedCurve) &) override; + void setHandle(const Handle(Geom_Circle) &); + const Handle(Geom_Geometry) & handle() const override; }; -class PartExport GeomEllipse : public GeomConic +class PartExport GeomEllipse: public GeomConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomEllipse(); - explicit GeomEllipse(const Handle(Geom_Ellipse)&); + explicit GeomEllipse(const Handle(Geom_Ellipse) &); ~GeomEllipse() override; - Geometry *copy() const override; + Geometry* copy() const override; GeomCurve* createArc(double first, double last) const override; double getMajorRadius() const; @@ -608,29 +666,30 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_Ellipse) &e); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_Ellipse) & e); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_Ellipse) myCurve; }; -class PartExport GeomArcOfEllipse : public GeomArcOfConic +class PartExport GeomArcOfEllipse: public GeomArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomArcOfEllipse(); - explicit GeomArcOfEllipse(const Handle(Geom_Ellipse)&); + explicit GeomArcOfEllipse(const Handle(Geom_Ellipse) &); ~GeomArcOfEllipse() override; - Geometry *copy() const override; + Geometry* copy() const override; double getMajorRadius() const; void setMajorRadius(double Radius); @@ -645,24 +704,25 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - void setHandle(const Handle(Geom_TrimmedCurve)&) override; - void setHandle(const Handle(Geom_Ellipse)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_TrimmedCurve) &) override; + void setHandle(const Handle(Geom_Ellipse) &); + const Handle(Geom_Geometry) & handle() const override; }; -class PartExport GeomHyperbola : public GeomConic +class PartExport GeomHyperbola: public GeomConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomHyperbola(); - explicit GeomHyperbola(const Handle(Geom_Hyperbola)&); + explicit GeomHyperbola(const Handle(Geom_Hyperbola) &); ~GeomHyperbola() override; Geometry* copy() const override; GeomCurve* createArc(double first, double last) const override; @@ -674,29 +734,30 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - const Handle(Geom_Geometry)& handle() const override; - void setHandle(const Handle(Geom_Hyperbola)&); + const Handle(Geom_Geometry) & handle() const override; + void setHandle(const Handle(Geom_Hyperbola) &); private: Handle(Geom_Hyperbola) myCurve; }; -class PartExport GeomArcOfHyperbola : public GeomArcOfConic +class PartExport GeomArcOfHyperbola: public GeomArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomArcOfHyperbola(); - explicit GeomArcOfHyperbola(const Handle(Geom_Hyperbola)&); + explicit GeomArcOfHyperbola(const Handle(Geom_Hyperbola) &); ~GeomArcOfHyperbola() override; - Geometry *copy() const override; + Geometry* copy() const override; double getMajorRadius() const; void setMajorRadius(double Radius); @@ -711,23 +772,24 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - void setHandle(const Handle(Geom_TrimmedCurve)&) override; - void setHandle(const Handle(Geom_Hyperbola)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_TrimmedCurve) &) override; + void setHandle(const Handle(Geom_Hyperbola) &); + const Handle(Geom_Geometry) & handle() const override; }; -class PartExport GeomParabola : public GeomConic +class PartExport GeomParabola: public GeomConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomParabola(); - explicit GeomParabola(const Handle(Geom_Parabola)&); + explicit GeomParabola(const Handle(Geom_Parabola) &); ~GeomParabola() override; Geometry* copy() const override; GeomCurve* createArc(double first, double last) const override; @@ -737,29 +799,30 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - const Handle(Geom_Geometry)& handle() const override; - void setHandle(const Handle(Geom_Parabola)&); + const Handle(Geom_Geometry) & handle() const override; + void setHandle(const Handle(Geom_Parabola) &); private: Handle(Geom_Parabola) myCurve; }; -class PartExport GeomArcOfParabola : public GeomArcOfConic +class PartExport GeomArcOfParabola: public GeomArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomArcOfParabola(); - explicit GeomArcOfParabola(const Handle(Geom_Parabola)&); + explicit GeomArcOfParabola(const Handle(Geom_Parabola) &); ~GeomArcOfParabola() override; - Geometry *copy() const override; + Geometry* copy() const override; double getFocal() const; void setFocal(double length); @@ -771,26 +834,27 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; GeomBSplineCurve* toNurbs(double first, double last) const override; - void setHandle(const Handle(Geom_TrimmedCurve)&) override; - void setHandle(const Handle(Geom_Parabola)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_TrimmedCurve) &) override; + void setHandle(const Handle(Geom_Parabola) &); + const Handle(Geom_Geometry) & handle() const override; }; -class PartExport GeomLine : public GeomCurve +class PartExport GeomLine: public GeomCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomLine(); - explicit GeomLine(const Handle(Geom_Line)&); + explicit GeomLine(const Handle(Geom_Line) &); GeomLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir); ~GeomLine() override; - Geometry *copy() const override; + Geometry* copy() const override; void setLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir); Base::Vector3d getPos() const; @@ -798,73 +862,73 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - const Handle(Geom_Geometry)& handle() const override; - void setHandle(const Handle(Geom_Line)&); + const Handle(Geom_Geometry) & handle() const override; + void setHandle(const Handle(Geom_Line) &); private: Handle(Geom_Line) myCurve; }; -class PartExport GeomLineSegment : public GeomTrimmedCurve +class PartExport GeomLineSegment: public GeomTrimmedCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomLineSegment(); - explicit GeomLineSegment(const Handle(Geom_Line)& l); + explicit GeomLineSegment(const Handle(Geom_Line) & l); ~GeomLineSegment() override; - Geometry *copy() const override; + Geometry* copy() const override; Base::Vector3d getStartPoint() const override; Base::Vector3d getEndPoint() const override; - void setPoints(const Base::Vector3d& p1, - const Base::Vector3d& p2); + void setPoints(const Base::Vector3d& p1, const Base::Vector3d& p2); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; - - void setHandle(const Handle(Geom_TrimmedCurve)&) override; - void setHandle(const Handle(Geom_Line)&); - const Handle(Geom_Geometry)& handle() const override; + PyObject* getPyObject() override; + void setHandle(const Handle(Geom_TrimmedCurve) &) override; + void setHandle(const Handle(Geom_Line) &); + const Handle(Geom_Geometry) & handle() const override; }; -class PartExport GeomOffsetCurve : public GeomCurve +class PartExport GeomOffsetCurve: public GeomCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomOffsetCurve(); - GeomOffsetCurve(const Handle(Geom_Curve)&, double, const gp_Dir&); - GeomOffsetCurve(const Handle(Geom_Curve)&, double, Base::Vector3d&); - explicit GeomOffsetCurve(const Handle(Geom_OffsetCurve)&); + GeomOffsetCurve(const Handle(Geom_Curve) &, double, const gp_Dir&); + GeomOffsetCurve(const Handle(Geom_Curve) &, double, Base::Vector3d&); + explicit GeomOffsetCurve(const Handle(Geom_OffsetCurve) &); ~GeomOffsetCurve() override; - Geometry *copy() const override; + Geometry* copy() const override; Base::Vector3d getDir() const; double getOffset() const; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_OffsetCurve)& c); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_OffsetCurve) & c); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_OffsetCurve) myCurve; @@ -872,11 +936,13 @@ private: class GeomPlane; -class PartExport GeomSurface : public Geometry +class PartExport GeomSurface: public Geometry { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - enum Curvature { + enum Curvature + { Maximum, Minimum, Mean, @@ -886,12 +952,12 @@ public: GeomSurface(); ~GeomSurface() override; - static bool isPlanar(const Handle(Geom_Surface) &s, gp_Pln *pln=nullptr, double tol=1e-7); - bool isPlanar(gp_Pln *pln=nullptr, double tol=1e-7) const; + static bool isPlanar(const Handle(Geom_Surface) & s, gp_Pln* pln = nullptr, double tol = 1e-7); + bool isPlanar(gp_Pln* pln = nullptr, double tol = 1e-7) const; TopoDS_Shape toShape() const override; - GeomPlane *toPlane(bool clone=true, double tol=1e-7) const; + GeomPlane* toPlane(bool clone = true, double tol = 1e-7) const; virtual std::optional getRotation() const; @@ -914,58 +980,60 @@ public: //@} }; -class PartExport GeomBezierSurface : public GeomSurface +class PartExport GeomBezierSurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomBezierSurface(); - explicit GeomBezierSurface(const Handle(Geom_BezierSurface)&); + explicit GeomBezierSurface(const Handle(Geom_BezierSurface) &); ~GeomBezierSurface() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_BezierSurface)& b); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_BezierSurface) & b); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_BezierSurface) mySurface; }; -class PartExport GeomBSplineSurface : public GeomSurface +class PartExport GeomBSplineSurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomBSplineSurface(); - explicit GeomBSplineSurface(const Handle(Geom_BSplineSurface)&); + explicit GeomBSplineSurface(const Handle(Geom_BSplineSurface) &); ~GeomBSplineSurface() override; - Geometry *copy() const override; + Geometry* copy() const override; void scaleKnotsToBounds(double u0, double u1, double v0, double v1); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_BSplineSurface)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_BSplineSurface) &); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_BSplineSurface) mySurface; }; -class PartExport GeomElementarySurface : public GeomSurface +class PartExport GeomElementarySurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -981,61 +1049,63 @@ public: Base::Vector3d getXDir() const; Base::Vector3d getYDir() const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; }; -class PartExport GeomCylinder : public GeomElementarySurface +class PartExport GeomCylinder: public GeomElementarySurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomCylinder(); - explicit GeomCylinder(const Handle(Geom_CylindricalSurface)&); + explicit GeomCylinder(const Handle(Geom_CylindricalSurface) &); ~GeomCylinder() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; double getRadius() const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_CylindricalSurface)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_CylindricalSurface) &); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_CylindricalSurface) mySurface; }; -class PartExport GeomCone : public GeomElementarySurface +class PartExport GeomCone: public GeomElementarySurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomCone(); - explicit GeomCone(const Handle(Geom_ConicalSurface)&); + explicit GeomCone(const Handle(Geom_ConicalSurface) &); ~GeomCone() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; double getRadius() const; double getSemiAngle() const; Base::Vector3d getApex() const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_ConicalSurface)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_ConicalSurface) &); + const Handle(Geom_Geometry) & handle() const override; // Overloaded for Geom_ConicalSurface because of an OCC bug gp_Vec getDN(double u, double v, int Nu, int Nv) const override; @@ -1044,170 +1114,176 @@ private: Handle(Geom_ConicalSurface) mySurface; }; -class PartExport GeomSphere : public GeomElementarySurface +class PartExport GeomSphere: public GeomElementarySurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomSphere(); - explicit GeomSphere(const Handle(Geom_SphericalSurface)&); + explicit GeomSphere(const Handle(Geom_SphericalSurface) &); ~GeomSphere() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; double getRadius(void) const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_SphericalSurface)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_SphericalSurface) &); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_SphericalSurface) mySurface; }; -class PartExport GeomToroid : public GeomElementarySurface +class PartExport GeomToroid: public GeomElementarySurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomToroid(); - explicit GeomToroid(const Handle(Geom_ToroidalSurface)&); + explicit GeomToroid(const Handle(Geom_ToroidalSurface) &); ~GeomToroid() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; double getMajorRadius() const; double getMinorRadius() const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_ToroidalSurface)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_ToroidalSurface) &); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_ToroidalSurface) mySurface; }; -class PartExport GeomPlane : public GeomElementarySurface +class PartExport GeomPlane: public GeomElementarySurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomPlane(); - explicit GeomPlane(const Handle(Geom_Plane)&); - explicit GeomPlane(const gp_Pln &pln); + explicit GeomPlane(const Handle(Geom_Plane) &); + explicit GeomPlane(const gp_Pln& pln); ~GeomPlane() override; - Geometry *copy() const override; + Geometry* copy() const override; std::optional getRotation() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_Plane)&); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_Plane) &); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_Plane) mySurface; }; -class PartExport GeomOffsetSurface : public GeomSurface +class PartExport GeomOffsetSurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomOffsetSurface(); - GeomOffsetSurface(const Handle(Geom_Surface)&, double); - explicit GeomOffsetSurface(const Handle(Geom_OffsetSurface)&); + GeomOffsetSurface(const Handle(Geom_Surface) &, double); + explicit GeomOffsetSurface(const Handle(Geom_OffsetSurface) &); ~GeomOffsetSurface() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; double getOffset() const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_OffsetSurface)& s); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_OffsetSurface) & s); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_OffsetSurface) mySurface; }; -class PartExport GeomPlateSurface : public GeomSurface +class PartExport GeomPlateSurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomPlateSurface(); - GeomPlateSurface(const Handle(Geom_Surface)&, const Plate_Plate&); + GeomPlateSurface(const Handle(Geom_Surface) &, const Plate_Plate&); explicit GeomPlateSurface(const GeomPlate_BuildPlateSurface&); - explicit GeomPlateSurface(const Handle(GeomPlate_Surface)&); + explicit GeomPlateSurface(const Handle(GeomPlate_Surface) &); ~GeomPlateSurface() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(GeomPlate_Surface)& s); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(GeomPlate_Surface) & s); + const Handle(Geom_Geometry) & handle() const override; private: Handle(GeomPlate_Surface) mySurface; }; -class PartExport GeomTrimmedSurface : public GeomSurface +class PartExport GeomTrimmedSurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomTrimmedSurface(); - explicit GeomTrimmedSurface(const Handle(Geom_RectangularTrimmedSurface)&); + explicit GeomTrimmedSurface(const Handle(Geom_RectangularTrimmedSurface) &); ~GeomTrimmedSurface() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; - void setHandle(const Handle(Geom_RectangularTrimmedSurface)& s); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_RectangularTrimmedSurface) & s); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_RectangularTrimmedSurface) mySurface; }; -class PartExport GeomSweptSurface : public GeomSurface +class PartExport GeomSweptSurface: public GeomSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -1218,53 +1294,55 @@ public: ~GeomSweptSurface() override; Base::Vector3d getDir() const; - bool isSame(const Geometry &other, double tol, double atol) const override; + bool isSame(const Geometry& other, double tol, double atol) const override; }; -class PartExport GeomSurfaceOfRevolution : public GeomSweptSurface +class PartExport GeomSurfaceOfRevolution: public GeomSweptSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomSurfaceOfRevolution(); - GeomSurfaceOfRevolution(const Handle(Geom_Curve)&, const gp_Ax1&); - explicit GeomSurfaceOfRevolution(const Handle(Geom_SurfaceOfRevolution)&); + GeomSurfaceOfRevolution(const Handle(Geom_Curve) &, const gp_Ax1&); + explicit GeomSurfaceOfRevolution(const Handle(Geom_SurfaceOfRevolution) &); ~GeomSurfaceOfRevolution() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom_SurfaceOfRevolution)& c); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_SurfaceOfRevolution) & c); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_SurfaceOfRevolution) mySurface; }; -class PartExport GeomSurfaceOfExtrusion : public GeomSweptSurface +class PartExport GeomSurfaceOfExtrusion: public GeomSweptSurface { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: GeomSurfaceOfExtrusion(); - GeomSurfaceOfExtrusion(const Handle(Geom_Curve)&, const gp_Dir&); - explicit GeomSurfaceOfExtrusion(const Handle(Geom_SurfaceOfLinearExtrusion)&); + GeomSurfaceOfExtrusion(const Handle(Geom_Curve) &, const gp_Dir&); + explicit GeomSurfaceOfExtrusion(const Handle(Geom_SurfaceOfLinearExtrusion) &); ~GeomSurfaceOfExtrusion() override; - Geometry *copy() const override; + Geometry* copy() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom_SurfaceOfLinearExtrusion)& c); - const Handle(Geom_Geometry)& handle() const override; + void setHandle(const Handle(Geom_SurfaceOfLinearExtrusion) & c); + const Handle(Geom_Geometry) & handle() const override; private: Handle(Geom_SurfaceOfLinearExtrusion) mySurface; @@ -1272,43 +1350,74 @@ private: // Helper functions for fillet tools -PartExport -bool find2DLinesIntersection(const Base::Vector3d &orig1, const Base::Vector3d &dir1, - const Base::Vector3d &orig2, const Base::Vector3d &dir2, - Base::Vector3d &point); -PartExport -bool find2DLinesIntersection(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, - Base::Vector3d &point); -PartExport -bool findFilletCenter(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, double radius, - Base::Vector3d ¢er); -PartExport -bool findFilletCenter(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, double radius, - const Base::Vector3d& refPnt1, const Base::Vector3d& refPnt2, - Base::Vector3d ¢er); -PartExport -double suggestFilletRadius(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, - const Base::Vector3d &refPnt1, const Base::Vector3d &refPnt2); -PartExport -GeomArcOfCircle* create2LinesFilletGeometry(const GeomLineSegment *lineSeg1, const GeomLineSegment *lineSeg2, - const Base::Vector3d ¢er, double radius); -PartExport -GeomArcOfCircle* createFilletGeometry(const Geometry* geo1, const Geometry* geo2, const Base::Vector3d& refPnt1, - const Base::Vector3d& refPnt2, double radius, int& pos1, int& pos2, bool& reverse); -PartExport -std::unique_ptr makeFromSurface(const Handle(Geom_Surface)&, bool silent=false); +PartExport bool find2DLinesIntersection( + const Base::Vector3d& orig1, + const Base::Vector3d& dir1, + const Base::Vector3d& orig2, + const Base::Vector3d& dir2, + Base::Vector3d& point +); +PartExport bool find2DLinesIntersection( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + Base::Vector3d& point +); +PartExport bool findFilletCenter( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + double radius, + Base::Vector3d& center +); +PartExport bool findFilletCenter( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + double radius, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2, + Base::Vector3d& center +); +PartExport double suggestFilletRadius( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2 +); +PartExport GeomArcOfCircle* create2LinesFilletGeometry( + const GeomLineSegment* lineSeg1, + const GeomLineSegment* lineSeg2, + const Base::Vector3d& center, + double radius +); +PartExport GeomArcOfCircle* createFilletGeometry( + const Geometry* geo1, + const Geometry* geo2, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2, + double radius, + int& pos1, + int& pos2, + bool& reverse +); +PartExport std::unique_ptr makeFromSurface( + const Handle(Geom_Surface) &, + bool silent = false +); -PartExport - std::unique_ptr makeFromSurfaceAdaptor(const BRepAdaptor_Surface&, bool silent=false); +PartExport std::unique_ptr makeFromSurfaceAdaptor( + const BRepAdaptor_Surface&, + bool silent = false +); -PartExport -std::unique_ptr makeFromCurve(const Handle(Geom_Curve)&, bool silent=false); +PartExport std::unique_ptr makeFromCurve(const Handle(Geom_Curve) &, bool silent = false); -PartExport -std::unique_ptr makeFromTrimmedCurve(const Handle(Geom_Curve)&, double f, double l, bool silent=false); +PartExport std::unique_ptr makeFromTrimmedCurve( + const Handle(Geom_Curve) &, + double f, + double l, + bool silent = false +); -PartExport -std::unique_ptr makeFromCurveAdaptor(const Adaptor3d_Curve&, bool silent=false); -} +PartExport std::unique_ptr makeFromCurveAdaptor(const Adaptor3d_Curve&, bool silent = false); +} // namespace Part -#endif // PART_GEOMETRY_H +#endif // PART_GEOMETRY_H diff --git a/src/Mod/Part/App/Geometry.pyi b/src/Mod/Part/App/Geometry.pyi index 18d0f6b341..8b51ce5bcf 100644 --- a/src/Mod/Part/App/Geometry.pyi +++ b/src/Mod/Part/App/Geometry.pyi @@ -5,7 +5,6 @@ from Base.Vector import Vector from Base.Matrix import Matrix from typing import Final, List, Optional - @export( Include="Mod/Part/App/Geometry.h", Constructor=True, diff --git a/src/Mod/Part/App/Geometry2d.cpp b/src/Mod/Part/App/Geometry2d.cpp index b6b15e4d54..dca98049fb 100644 --- a/src/Mod/Part/App/Geometry2d.cpp +++ b/src/Mod/Part/App/Geometry2d.cpp @@ -22,39 +22,39 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -91,17 +91,17 @@ Geometry2d::Geometry2d() = default; Geometry2d::~Geometry2d() = default; -unsigned int Geometry2d::getMemSize () const +unsigned int Geometry2d::getMemSize() const { return sizeof(Geometry2d); } -void Geometry2d::Save(Base::Writer & /*writer*/) const +void Geometry2d::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("Save"); } -void Geometry2d::Restore(Base::XMLReader & /*reader*/) +void Geometry2d::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("Restore"); } @@ -112,17 +112,17 @@ TYPESYSTEM_SOURCE(Part::Geom2dPoint, Part::Geometry2d) Geom2dPoint::Geom2dPoint() { - this->myPoint = new Geom2d_CartesianPoint(0,0); + this->myPoint = new Geom2d_CartesianPoint(0, 0); } -Geom2dPoint::Geom2dPoint(const Handle(Geom2d_CartesianPoint)& p) +Geom2dPoint::Geom2dPoint(const Handle(Geom2d_CartesianPoint) & p) { this->myPoint = Handle(Geom2d_CartesianPoint)::DownCast(p->Copy()); } Geom2dPoint::Geom2dPoint(const Base::Vector2d& p) { - this->myPoint = new Geom2d_CartesianPoint(p.x,p.y); + this->myPoint = new Geom2d_CartesianPoint(p.x, p.y); } Geom2dPoint::~Geom2dPoint() = default; @@ -138,52 +138,50 @@ TopoDS_Shape Geom2dPoint::toShape() const return mkBuilder.Shape(); } -const Handle(Geom2d_Geometry)& Geom2dPoint::handle() const +const Handle(Geom2d_Geometry) & Geom2dPoint::handle() const { return myPoint; } -Geometry2d *Geom2dPoint::clone() const +Geometry2d* Geom2dPoint::clone() const { - Geom2dPoint *newPoint = new Geom2dPoint(myPoint); + Geom2dPoint* newPoint = new Geom2dPoint(myPoint); return newPoint; } -Base::Vector2d Geom2dPoint::getPoint()const +Base::Vector2d Geom2dPoint::getPoint() const { - return {myPoint->X(),myPoint->Y()}; + return {myPoint->X(), myPoint->Y()}; } void Geom2dPoint::setPoint(const Base::Vector2d& p) { - this->myPoint->SetCoord(p.x,p.y); + this->myPoint->SetCoord(p.x, p.y); } -unsigned int Geom2dPoint::getMemSize () const +unsigned int Geom2dPoint::getMemSize() const { return sizeof(Geom2d_CartesianPoint); } -void Geom2dPoint::Save(Base::Writer &writer) const +void Geom2dPoint::Save(Base::Writer& writer) const { // save the attributes of the father class Geometry2d::Save(writer); - Base::Vector2d Point = getPoint(); - writer.Stream() - << writer.ind() - << "" << std::endl; + Base::Vector2d Point = getPoint(); + writer.Stream() << writer.ind() << "" << std::endl; } -void Geom2dPoint::Restore(Base::XMLReader &reader) +void Geom2dPoint::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geometry2d::Restore(reader); - double X,Y; + double X, Y; // read my Element reader.readElement("Geom2dPoint"); // get the value of my Attribute @@ -191,10 +189,10 @@ void Geom2dPoint::Restore(Base::XMLReader &reader) Y = reader.getAttribute("Y"); // set the read geometry - setPoint(Base::Vector2d(X,Y)); + setPoint(Base::Vector2d(X, Y)); } -PyObject *Geom2dPoint::getPyObject() +PyObject* Geom2dPoint::getPyObject() { Handle(Geom2d_CartesianPoint) c = Handle(Geom2d_CartesianPoint)::DownCast(handle()); gp_Pnt2d xy = c->Pnt2d(); @@ -223,7 +221,7 @@ TopoDS_Shape Geom2dCurve::toShape() const bool Geom2dCurve::tangent(double u, gp_Dir2d& dir) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); if (prop.IsTangentDefined()) { prop.Tangent(dir); return true; @@ -235,34 +233,34 @@ bool Geom2dCurve::tangent(double u, gp_Dir2d& dir) const Base::Vector2d Geom2dCurve::pointAtParameter(double u) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); - Geom2dLProp_CLProps2d prop(c,u,0,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 0, Precision::Confusion()); - const gp_Pnt2d &point=prop.Value(); - return {point.X(),point.Y()}; + const gp_Pnt2d& point = prop.Value(); + return {point.X(), point.Y()}; } Base::Vector2d Geom2dCurve::firstDerivativeAtParameter(double u) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); - Geom2dLProp_CLProps2d prop(c,u,1,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 1, Precision::Confusion()); - const gp_Vec2d &vec=prop.D1(); - return {vec.X(),vec.Y()}; + const gp_Vec2d& vec = prop.D1(); + return {vec.X(), vec.Y()}; } Base::Vector2d Geom2dCurve::secondDerivativeAtParameter(double u) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); - const gp_Vec2d &vec=prop.D2(); - return {vec.X(),vec.Y()}; + const gp_Vec2d& vec = prop.D2(); + return {vec.X(), vec.Y()}; } bool Geom2dCurve::normal(double u, gp_Dir2d& dir) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); - Geom2dLProp_CLProps2d prop(c,u,2,Precision::Confusion()); + Geom2dLProp_CLProps2d prop(c, u, 2, Precision::Confusion()); if (prop.IsTangentDefined()) { prop.Normal(dir); return true; @@ -271,12 +269,12 @@ bool Geom2dCurve::normal(double u, gp_Dir2d& dir) const return false; } -bool Geom2dCurve::closestParameter(const Base::Vector2d& point, double &u) const +bool Geom2dCurve::closestParameter(const Base::Vector2d& point, double& u) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); try { if (!c.IsNull()) { - gp_Pnt2d pnt(point.x,point.y); + gp_Pnt2d pnt(point.x, point.y); Geom2dAPI_ProjectPointOnCurve ppc(pnt, c); u = ppc.LowerDistanceParameter(); return true; @@ -291,16 +289,16 @@ bool Geom2dCurve::closestParameter(const Base::Vector2d& point, double &u) const return false; } -bool Geom2dCurve::closestParameterToBasicCurve(const Base::Vector2d& point, double &u) const +bool Geom2dCurve::closestParameterToBasicCurve(const Base::Vector2d& point, double& u) const { Handle(Geom2d_Curve) c = Handle(Geom2d_Curve)::DownCast(handle()); - if (c->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))){ + if (c->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))) { Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(handle()); Handle(Geom2d_Curve) bc = tc->BasisCurve(); try { if (!bc.IsNull()) { - gp_Pnt2d pnt(point.x,point.y); + gp_Pnt2d pnt(point.x, point.y); Geom2dAPI_ProjectPointOnCurve ppc(pnt, bc); u = ppc.LowerDistanceParameter(); return true; @@ -313,7 +311,6 @@ bool Geom2dCurve::closestParameterToBasicCurve(const Base::Vector2d& point, doub } return false; - } else { return this->closestParameter(point, u); @@ -326,52 +323,52 @@ TYPESYSTEM_SOURCE(Part::Geom2dBezierCurve, Part::Geom2dCurve) Geom2dBezierCurve::Geom2dBezierCurve() { - TColgp_Array1OfPnt2d poles(1,2); - poles(1) = gp_Pnt2d(0.0,0.0); - poles(2) = gp_Pnt2d(0.0,1.0); + TColgp_Array1OfPnt2d poles(1, 2); + poles(1) = gp_Pnt2d(0.0, 0.0); + poles(2) = gp_Pnt2d(0.0, 1.0); Handle(Geom2d_BezierCurve) b = new Geom2d_BezierCurve(poles); this->myCurve = b; } -Geom2dBezierCurve::Geom2dBezierCurve(const Handle(Geom2d_BezierCurve)& b) +Geom2dBezierCurve::Geom2dBezierCurve(const Handle(Geom2d_BezierCurve) & b) { this->myCurve = Handle(Geom2d_BezierCurve)::DownCast(b->Copy()); } Geom2dBezierCurve::~Geom2dBezierCurve() = default; -void Geom2dBezierCurve::setHandle(const Handle(Geom2d_BezierCurve)& c) +void Geom2dBezierCurve::setHandle(const Handle(Geom2d_BezierCurve) & c) { myCurve = Handle(Geom2d_BezierCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dBezierCurve::handle() const +const Handle(Geom2d_Geometry) & Geom2dBezierCurve::handle() const { return myCurve; } -Geometry2d *Geom2dBezierCurve::clone() const +Geometry2d* Geom2dBezierCurve::clone() const { - Geom2dBezierCurve *newCurve = new Geom2dBezierCurve(myCurve); + Geom2dBezierCurve* newCurve = new Geom2dBezierCurve(myCurve); return newCurve; } -unsigned int Geom2dBezierCurve::getMemSize () const +unsigned int Geom2dBezierCurve::getMemSize() const { throw Base::NotImplementedError("Geom2dBezierCurve::getMemSize"); } -void Geom2dBezierCurve::Save(Base::Writer &/*writer*/) const +void Geom2dBezierCurve::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("Geom2dBezierCurve::Save"); } -void Geom2dBezierCurve::Restore(Base::XMLReader &/*reader*/) +void Geom2dBezierCurve::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("Geom2dBezierCurve::Restore"); } -PyObject *Geom2dBezierCurve::getPyObject() +PyObject* Geom2dBezierCurve::getPyObject() { return new BezierCurve2dPy(static_cast(this->clone())); } @@ -382,41 +379,41 @@ TYPESYSTEM_SOURCE(Part::Geom2dBSplineCurve, Part::Geom2dCurve) Geom2dBSplineCurve::Geom2dBSplineCurve() { - TColgp_Array1OfPnt2d poles(1,2); - poles(1) = gp_Pnt2d(0.0,0.0); - poles(2) = gp_Pnt2d(1.0,0.0); + TColgp_Array1OfPnt2d poles(1, 2); + poles(1) = gp_Pnt2d(0.0, 0.0); + poles(2) = gp_Pnt2d(1.0, 0.0); - TColStd_Array1OfReal knots(1,2); + TColStd_Array1OfReal knots(1, 2); knots(1) = 0.0; knots(2) = 1.0; - TColStd_Array1OfInteger mults(1,2); + TColStd_Array1OfInteger mults(1, 2); mults(1) = 2; mults(2) = 2; this->myCurve = new Geom2d_BSplineCurve(poles, knots, mults, 1); } -Geom2dBSplineCurve::Geom2dBSplineCurve(const Handle(Geom2d_BSplineCurve)& b) +Geom2dBSplineCurve::Geom2dBSplineCurve(const Handle(Geom2d_BSplineCurve) & b) { this->myCurve = Handle(Geom2d_BSplineCurve)::DownCast(b->Copy()); } Geom2dBSplineCurve::~Geom2dBSplineCurve() = default; -void Geom2dBSplineCurve::setHandle(const Handle(Geom2d_BSplineCurve)& c) +void Geom2dBSplineCurve::setHandle(const Handle(Geom2d_BSplineCurve) & c) { myCurve = Handle(Geom2d_BSplineCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dBSplineCurve::handle() const +const Handle(Geom2d_Geometry) & Geom2dBSplineCurve::handle() const { return myCurve; } -Geometry2d *Geom2dBSplineCurve::clone() const +Geometry2d* Geom2dBSplineCurve::clone() const { - Geom2dBSplineCurve *newCurve = new Geom2dBSplineCurve(myCurve); + Geom2dBSplineCurve* newCurve = new Geom2dBSplineCurve(myCurve); return newCurve; } @@ -428,11 +425,13 @@ int Geom2dBSplineCurve::countPoles() const void Geom2dBSplineCurve::setPole(int index, const Base::Vector2d& pole, double weight) { try { - gp_Pnt2d pnt(pole.x,pole.y); - if (weight < 0.0) - myCurve->SetPole(index+1,pnt); - else - myCurve->SetPole(index+1,pnt,weight); + gp_Pnt2d pnt(pole.x, pole.y); + if (weight < 0.0) { + myCurve->SetPole(index + 1, pnt); + } + else { + myCurve->SetPole(index + 1, pnt, weight); + } } catch (Standard_Failure& e) { @@ -444,44 +443,46 @@ std::vector Geom2dBSplineCurve::getPoles() const { std::vector poles; poles.reserve(myCurve->NbPoles()); - TColgp_Array1OfPnt2d p(1,myCurve->NbPoles()); + TColgp_Array1OfPnt2d p(1, myCurve->NbPoles()); myCurve->Poles(p); - for (Standard_Integer i=p.Lower(); i<=p.Upper(); i++) { + for (Standard_Integer i = p.Lower(); i <= p.Upper(); i++) { const gp_Pnt2d& pnt = p(i); poles.emplace_back(pnt.X(), pnt.Y()); } return poles; } -bool Geom2dBSplineCurve::join(const Handle(Geom2d_BSplineCurve)& spline) +bool Geom2dBSplineCurve::join(const Handle(Geom2d_BSplineCurve) & spline) { Geom2dConvert_CompCurveToBSplineCurve ccbc(this->myCurve); - if (!ccbc.Add(spline, Precision::Approximation())) + if (!ccbc.Add(spline, Precision::Approximation())) { return false; + } this->myCurve = ccbc.BSplineCurve(); return true; } -void Geom2dBSplineCurve::interpolate(const std::vector& p, - const std::vector& t) +void Geom2dBSplineCurve::interpolate(const std::vector& p, const std::vector& t) { - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); - if (p.size() != t.size()) + } + if (p.size() != t.size()) { Standard_ConstructionError::Raise(); + } double tol3d = Precision::Approximation(); Handle(TColgp_HArray1OfPnt2d) pts = new TColgp_HArray1OfPnt2d(1, p.size()); - for (std::size_t i=0; iSetValue(i+1, p[i]); + for (std::size_t i = 0; i < p.size(); i++) { + pts->SetValue(i + 1, p[i]); } TColgp_Array1OfVec2d tgs(1, t.size()); Handle(TColStd_HArray1OfBoolean) fgs = new TColStd_HArray1OfBoolean(1, t.size()); - for (std::size_t i=0; iSetValue(i+1, Standard_True); + for (std::size_t i = 0; i < p.size(); i++) { + tgs.SetValue(i + 1, t[i]); + fgs->SetValue(i + 1, Standard_True); } Geom2dAPI_Interpolate interpolate(pts, Standard_False, tol3d); @@ -490,15 +491,19 @@ void Geom2dBSplineCurve::interpolate(const std::vector& p, this->myCurve = interpolate.Curve(); } -void Geom2dBSplineCurve::getCardinalSplineTangents(const std::vector& p, - const std::vector& c, - std::vector& t) const +void Geom2dBSplineCurve::getCardinalSplineTangents( + const std::vector& p, + const std::vector& c, + std::vector& t +) const { // https://de.wikipedia.org/wiki/Kubisch_Hermitescher_Spline#Cardinal_Spline - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); - if (p.size() != c.size()) + } + if (p.size() != c.size()) { Standard_ConstructionError::Raise(); + } t.resize(p.size()); if (p.size() == 2) { @@ -509,23 +514,27 @@ void Geom2dBSplineCurve::getCardinalSplineTangents(const std::vector& std::size_t e = p.size() - 1; for (std::size_t i = 1; i < e; i++) { - gp_Vec2d v = gp_Vec2d(p[i-1], p[i+1]); - double f = 0.5 * (1-c[i]); + gp_Vec2d v = gp_Vec2d(p[i - 1], p[i + 1]); + double f = 0.5 * (1 - c[i]); v.Scale(f); t[i] = v; } t[0] = t[1]; - t[t.size()-1] = t[t.size()-2]; + t[t.size() - 1] = t[t.size() - 2]; } } -void Geom2dBSplineCurve::getCardinalSplineTangents(const std::vector& p, double c, - std::vector& t) const +void Geom2dBSplineCurve::getCardinalSplineTangents( + const std::vector& p, + double c, + std::vector& t +) const { // https://de.wikipedia.org/wiki/Kubisch_Hermitescher_Spline#Cardinal_Spline - if (p.size() < 2) + if (p.size() < 2) { Standard_ConstructionError::Raise(); + } t.resize(p.size()); if (p.size() == 2) { @@ -534,16 +543,16 @@ void Geom2dBSplineCurve::getCardinalSplineTangents(const std::vector& } else { std::size_t e = p.size() - 1; - double f = 0.5 * (1-c); + double f = 0.5 * (1 - c); for (std::size_t i = 1; i < e; i++) { - gp_Vec2d v = gp_Vec2d(p[i-1], p[i+1]); + gp_Vec2d v = gp_Vec2d(p[i - 1], p[i + 1]); v.Scale(f); t[i] = v; } t[0] = t[1]; - t[t.size()-1] = t[t.size()-2]; + t[t.size() - 1] = t[t.size() - 2]; } } @@ -563,17 +572,17 @@ unsigned int Geom2dBSplineCurve::getMemSize() const throw Base::NotImplementedError("Geom2dBSplineCurve::getMemSize"); } -void Geom2dBSplineCurve::Save(Base::Writer &/*writer*/) const +void Geom2dBSplineCurve::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("Geom2dBSplineCurve::Save"); } -void Geom2dBSplineCurve::Restore(Base::XMLReader &/*reader*/) +void Geom2dBSplineCurve::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("Geom2dBSplineCurve::Restore"); } -PyObject *Geom2dBSplineCurve::getPyObject() +PyObject* Geom2dBSplineCurve::getPyObject() { return new BSplineCurve2dPy(static_cast(this->clone())); } @@ -590,12 +599,12 @@ Base::Vector2d Geom2dConic::getLocation() const { Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(handle()); const gp_Pnt2d& loc = conic->Location(); - return {loc.X(),loc.Y()}; + return {loc.X(), loc.Y()}; } void Geom2dConic::setLocation(const Base::Vector2d& Center) { - gp_Pnt2d p1(Center.x,Center.y); + gp_Pnt2d p1(Center.x, Center.y); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(handle()); try { @@ -623,18 +632,17 @@ void Geom2dConic::SaveAxis(Base::Writer& writer, const gp_Ax22d& axis) const gp_Pnt2d center = axis.Location(); gp_Dir2d xdir = axis.XDirection(); gp_Dir2d ydir = axis.YDirection(); - writer.Stream() - << "CenterX=\"" << center.X() << "\" " - << "CenterY=\"" << center.Y() << "\" " - << "XAxisX=\"" << xdir.X() << "\" " - << "XAxisY=\"" << xdir.Y() << "\" " - << "YAxisX=\"" << ydir.X() << "\" " - << "YAxisY=\"" << ydir.Y() << "\" "; + writer.Stream() << "CenterX=\"" << center.X() << "\" " + << "CenterY=\"" << center.Y() << "\" " + << "XAxisX=\"" << xdir.X() << "\" " + << "XAxisY=\"" << xdir.Y() << "\" " + << "YAxisX=\"" << ydir.X() << "\" " + << "YAxisY=\"" << ydir.Y() << "\" "; } void Geom2dConic::RestoreAxis(Base::XMLReader& reader, gp_Ax22d& axis) { - double CenterX,CenterY,XdirX,XdirY,YdirX,YdirY; + double CenterX, CenterY, XdirX, XdirY, YdirX, YdirY; CenterX = reader.getAttribute("CenterX"); CenterY = reader.getAttribute("CenterY"); XdirX = reader.getAttribute("XAxisX"); @@ -643,9 +651,9 @@ void Geom2dConic::RestoreAxis(Base::XMLReader& reader, gp_Ax22d& axis) YdirY = reader.getAttribute("YAxisY"); // set the read geometry - gp_Pnt2d p1(CenterX,CenterY); - gp_Dir2d xdir(XdirX,XdirY); - gp_Dir2d ydir(YdirX,YdirY); + gp_Pnt2d p1(CenterX, CenterY); + gp_Dir2d xdir(XdirX, XdirY); + gp_Dir2d ydir(YdirX, YdirY); axis.SetLocation(p1); axis.SetXDirection(xdir); axis.SetYDirection(ydir); @@ -664,12 +672,12 @@ Base::Vector2d Geom2dArcOfConic::getLocation() const Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(handle()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); const gp_Pnt2d& loc = conic->Location(); - return {loc.X(),loc.Y()}; + return {loc.X(), loc.Y()}; } void Geom2dArcOfConic::setLocation(const Base::Vector2d& Center) { - gp_Pnt2d p1(Center.x,Center.y); + gp_Pnt2d p1(Center.x, Center.y); Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(handle()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); @@ -749,20 +757,19 @@ void Geom2dArcOfConic::SaveAxis(Base::Writer& writer, const gp_Ax22d& axis, doub gp_Pnt2d center = axis.Location(); gp_Dir2d xdir = axis.XDirection(); gp_Dir2d ydir = axis.YDirection(); - writer.Stream() - << "CenterX=\"" << center.X() << "\" " - << "CenterY=\"" << center.Y() << "\" " - << "XAxisX=\"" << xdir.X() << "\" " - << "XAxisY=\"" << xdir.Y() << "\" " - << "YAxisX=\"" << ydir.X() << "\" " - << "YAxisY=\"" << ydir.Y() << "\" " - << "FirstParameter=\"" << u << "\" " - << "LastParameter=\"" << v << "\" "; + writer.Stream() << "CenterX=\"" << center.X() << "\" " + << "CenterY=\"" << center.Y() << "\" " + << "XAxisX=\"" << xdir.X() << "\" " + << "XAxisY=\"" << xdir.Y() << "\" " + << "YAxisX=\"" << ydir.X() << "\" " + << "YAxisY=\"" << ydir.Y() << "\" " + << "FirstParameter=\"" << u << "\" " + << "LastParameter=\"" << v << "\" "; } -void Geom2dArcOfConic::RestoreAxis(Base::XMLReader& reader, gp_Ax22d& axis, double& u, double &v) +void Geom2dArcOfConic::RestoreAxis(Base::XMLReader& reader, gp_Ax22d& axis, double& u, double& v) { - double CenterX,CenterY,XdirX,XdirY,YdirX,YdirY; + double CenterX, CenterY, XdirX, XdirY, YdirX, YdirY; CenterX = reader.getAttribute("CenterX"); CenterY = reader.getAttribute("CenterY"); XdirX = reader.getAttribute("XAxisX"); @@ -773,9 +780,9 @@ void Geom2dArcOfConic::RestoreAxis(Base::XMLReader& reader, gp_Ax22d& axis, doub v = reader.getAttribute("LastParameter"); // set the read geometry - gp_Pnt2d p1(CenterX,CenterY); - gp_Dir2d xdir(XdirX,XdirY); - gp_Dir2d ydir(YdirX,YdirY); + gp_Pnt2d p1(CenterX, CenterY); + gp_Dir2d xdir(XdirX, XdirY); + gp_Dir2d ydir(YdirX, YdirY); axis.SetLocation(p1); axis.SetXDirection(xdir); axis.SetYDirection(ydir); @@ -791,21 +798,21 @@ Geom2dCircle::Geom2dCircle() this->myCurve = c; } -Geom2dCircle::Geom2dCircle(const Handle(Geom2d_Circle)& c) +Geom2dCircle::Geom2dCircle(const Handle(Geom2d_Circle) & c) { this->myCurve = Handle(Geom2d_Circle)::DownCast(c->Copy()); } Geom2dCircle::~Geom2dCircle() = default; -const Handle(Geom2d_Geometry)& Geom2dCircle::handle() const +const Handle(Geom2d_Geometry) & Geom2dCircle::handle() const { return myCurve; } -Geometry2d *Geom2dCircle::clone() const +Geometry2d* Geom2dCircle::clone() const { - Geom2dCircle *newCirc = new Geom2dCircle(myCurve); + Geom2dCircle* newCirc = new Geom2dCircle(myCurve); return newCirc; } @@ -829,7 +836,7 @@ void Geom2dCircle::setRadius(double Radius) } } -unsigned int Geom2dCircle::getMemSize () const +unsigned int Geom2dCircle::getMemSize() const { return sizeof(Geom2d_Circle); } @@ -843,13 +850,10 @@ void Geom2dCircle::Save(Base::Writer& writer) const gp_Circ2d c = circle->Circ2d(); gp_Ax22d axis = c.Axis(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "Radius=\"" << c.Radius() << "\" " + << "/>" << std::endl; } void Geom2dCircle::Restore(Base::XMLReader& reader) @@ -867,8 +871,9 @@ void Geom2dCircle::Restore(Base::XMLReader& reader) try { GCE2d_MakeCircle mc(axis, Radius); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } this->myCurve = mc.Value(); } @@ -877,7 +882,7 @@ void Geom2dCircle::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dCircle::getPyObject() +PyObject* Geom2dCircle::getPyObject() { return new Circle2dPy(static_cast(this->clone())); } @@ -895,23 +900,28 @@ be solved for using the midpoint of the line. This can be done for both lines. both S12p and S23p cross at the centerpoint, solving the two equations together will give the location of the centerpoint. */ -Base::Vector2d Geom2dCircle::getCircleCenter (const Base::Vector2d &p1, const Base::Vector2d &p2, const Base::Vector2d &p3) +Base::Vector2d Geom2dCircle::getCircleCenter( + const Base::Vector2d& p1, + const Base::Vector2d& p2, + const Base::Vector2d& p3 +) { - Base::Vector2d u = p2-p1; - Base::Vector2d v = p3-p2; - Base::Vector2d w = p1-p3; + Base::Vector2d u = p2 - p1; + Base::Vector2d v = p3 - p2; + Base::Vector2d w = p1 - p3; - double uu = u*u; - double vv = v*v; - double ww = w*w; + double uu = u * u; + double vv = v * v; + double ww = w * w; double eps2 = Precision::SquareConfusion(); - if (uu < eps2 || vv < eps2 || ww < eps2) - THROWM(Base::ValueError,"Two points are coincident"); + if (uu < eps2 || vv < eps2 || ww < eps2) { + THROWM(Base::ValueError, "Two points are coincident"); + } - double uv = -(u*v); - double vw = -(v*w); - double uw = -(u*w); + double uv = -(u * v); + double vw = -(v * w); + double uw = -(u * w); double w0 = (2 * sqrt(abs(uu * ww - uw * uw)) * uw / (uu * ww)); double w1 = (2 * sqrt(abs(uu * vv - uv * uv)) * uv / (uu * vv)); @@ -919,11 +929,12 @@ Base::Vector2d Geom2dCircle::getCircleCenter (const Base::Vector2d &p1, const Ba double wx = w0 + w1 + w2; - if (abs(wx) < Precision::Confusion()) - THROWM(Base::ValueError,"Points are collinear"); + if (abs(wx) < Precision::Confusion()) { + THROWM(Base::ValueError, "Points are collinear"); + } - double x = (w0*p1.x + w1*p2.x + w2*p3.x)/wx; - double y = (w0*p1.y + w1*p2.y + w2*p3.y)/wx; + double x = (w0 * p1.x + w1 * p2.x + w2 * p3.x) / wx; + double y = (w0 * p1.y + w1 * p2.y + w2 * p3.y) / wx; return {x, y}; } @@ -935,30 +946,31 @@ TYPESYSTEM_SOURCE(Part::Geom2dArcOfCircle, Part::Geom2dArcOfConic) Geom2dArcOfCircle::Geom2dArcOfCircle() { Handle(Geom2d_Circle) c = new Geom2d_Circle(gp_Circ2d()); - this->myCurve = new Geom2d_TrimmedCurve(c, c->FirstParameter(),c->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(c, c->FirstParameter(), c->LastParameter()); } -Geom2dArcOfCircle::Geom2dArcOfCircle(const Handle(Geom2d_Circle)& c) +Geom2dArcOfCircle::Geom2dArcOfCircle(const Handle(Geom2d_Circle) & c) { - this->myCurve = new Geom2d_TrimmedCurve(c, c->FirstParameter(),c->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(c, c->FirstParameter(), c->LastParameter()); } Geom2dArcOfCircle::~Geom2dArcOfCircle() = default; -void Geom2dArcOfCircle::setHandle(const Handle(Geom2d_TrimmedCurve)& c) +void Geom2dArcOfCircle::setHandle(const Handle(Geom2d_TrimmedCurve) & c) { Handle(Geom2d_Circle) basis = Handle(Geom2d_Circle)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not a circle"); + } this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dArcOfCircle::handle() const +const Handle(Geom2d_Geometry) & Geom2dArcOfCircle::handle() const { return myCurve; } -Geometry2d *Geom2dArcOfCircle::clone() const +Geometry2d* Geom2dArcOfCircle::clone() const { Geom2dArcOfCircle* copy = new Geom2dArcOfCircle(); copy->setHandle(this->myCurve); @@ -985,12 +997,12 @@ void Geom2dArcOfCircle::setRadius(double Radius) } } -unsigned int Geom2dArcOfCircle::getMemSize () const +unsigned int Geom2dArcOfCircle::getMemSize() const { - return sizeof(Geom2d_Circle) + 2 *sizeof(double); + return sizeof(Geom2d_Circle) + 2 * sizeof(double); } -void Geom2dArcOfCircle::Save(Base::Writer &writer) const +void Geom2dArcOfCircle::Save(Base::Writer& writer) const { // save the attributes of the father class Geom2dCurve::Save(writer); @@ -1002,21 +1014,18 @@ void Geom2dArcOfCircle::Save(Base::Writer &writer) const double u = this->myCurve->FirstParameter(); double v = this->myCurve->LastParameter(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "Radius=\"" << c.Radius() << "\" " + << "/>" << std::endl; } -void Geom2dArcOfCircle::Restore(Base::XMLReader &reader) +void Geom2dArcOfCircle::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geom2dCurve::Restore(reader); - double Radius,u,v; + double Radius, u, v; gp_Ax22d axis; // read my Element reader.readElement("Geom2dArcOfCircle"); @@ -1026,11 +1035,13 @@ void Geom2dArcOfCircle::Restore(Base::XMLReader &reader) try { GCE2d_MakeCircle mc(axis, Radius); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } GCE2d_MakeArcOfCircle ma(mc.Value()->Circ2d(), u, v); - if (!ma.IsDone()) + if (!ma.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(ma.Status())); + } Handle(Geom2d_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom2d_Circle) tmpcircle = Handle(Geom2d_Circle)::DownCast(tmpcurve->BasisCurve()); @@ -1044,7 +1055,7 @@ void Geom2dArcOfCircle::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfCircle::getPyObject() +PyObject* Geom2dArcOfCircle::getPyObject() { return new ArcOfCircle2dPy(static_cast(this->clone())); } @@ -1059,21 +1070,21 @@ Geom2dEllipse::Geom2dEllipse() this->myCurve = e; } -Geom2dEllipse::Geom2dEllipse(const Handle(Geom2d_Ellipse)& e) +Geom2dEllipse::Geom2dEllipse(const Handle(Geom2d_Ellipse) & e) { this->myCurve = Handle(Geom2d_Ellipse)::DownCast(e->Copy()); } Geom2dEllipse::~Geom2dEllipse() = default; -const Handle(Geom2d_Geometry)& Geom2dEllipse::handle() const +const Handle(Geom2d_Geometry) & Geom2dEllipse::handle() const { return myCurve; } -Geometry2d *Geom2dEllipse::clone() const +Geometry2d* Geom2dEllipse::clone() const { - Geom2dEllipse *newEllipse = new Geom2dEllipse(myCurve); + Geom2dEllipse* newEllipse = new Geom2dEllipse(myCurve); return newEllipse; } @@ -1134,8 +1145,9 @@ Base::Vector2d Geom2dEllipse::getMajorAxisDir() const */ void Geom2dEllipse::setMajorAxisDir(Base::Vector2d newdir) { - if (newdir.Length() < Precision::Confusion()) - return;//zero vector was passed. Keep the old orientation. + if (newdir.Length() < Precision::Confusion()) { + return; // zero vector was passed. Keep the old orientation. + } try { gp_Elips2d e = myCurve->Elips2d(); gp_Ax22d pos = e.Axis(); @@ -1148,7 +1160,7 @@ void Geom2dEllipse::setMajorAxisDir(Base::Vector2d newdir) } } -unsigned int Geom2dEllipse::getMemSize () const +unsigned int Geom2dEllipse::getMemSize() const { return sizeof(Geom2d_Ellipse); } @@ -1161,14 +1173,11 @@ void Geom2dEllipse::Save(Base::Writer& writer) const gp_Elips2d e = this->myCurve->Elips2d(); gp_Ax22d axis = e.Axis(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "MajorRadius=\"" << e.MajorRadius() << "\" " + << "MinorRadius=\"" << e.MinorRadius() << "\" " + << "/>" << std::endl; } void Geom2dEllipse::Restore(Base::XMLReader& reader) @@ -1176,7 +1185,7 @@ void Geom2dEllipse::Restore(Base::XMLReader& reader) // read the attributes of the father class Geom2dCurve::Restore(reader); - double MajorRadius,MinorRadius; + double MajorRadius, MinorRadius; gp_Ax22d axis; // read my Element reader.readElement("Geom2dEllipse"); @@ -1187,8 +1196,9 @@ void Geom2dEllipse::Restore(Base::XMLReader& reader) try { GCE2d_MakeEllipse mc(axis, MajorRadius, MinorRadius); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } this->myCurve = mc.Value(); } @@ -1197,12 +1207,12 @@ void Geom2dEllipse::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dEllipse::getPyObject() +PyObject* Geom2dEllipse::getPyObject() { return new Ellipse2dPy(static_cast(this->clone())); } -void Geom2dEllipse::setHandle(const Handle(Geom2d_Ellipse) &e) +void Geom2dEllipse::setHandle(const Handle(Geom2d_Ellipse) & e) { this->myCurve = Handle(Geom2d_Ellipse)::DownCast(e->Copy()); } @@ -1214,30 +1224,31 @@ TYPESYSTEM_SOURCE(Part::Geom2dArcOfEllipse, Part::Geom2dArcOfConic) Geom2dArcOfEllipse::Geom2dArcOfEllipse() { Handle(Geom2d_Ellipse) e = new Geom2d_Ellipse(gp_Elips2d()); - this->myCurve = new Geom2d_TrimmedCurve(e, e->FirstParameter(),e->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(e, e->FirstParameter(), e->LastParameter()); } -Geom2dArcOfEllipse::Geom2dArcOfEllipse(const Handle(Geom2d_Ellipse)& e) +Geom2dArcOfEllipse::Geom2dArcOfEllipse(const Handle(Geom2d_Ellipse) & e) { - this->myCurve = new Geom2d_TrimmedCurve(e, e->FirstParameter(),e->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(e, e->FirstParameter(), e->LastParameter()); } Geom2dArcOfEllipse::~Geom2dArcOfEllipse() = default; -void Geom2dArcOfEllipse::setHandle(const Handle(Geom2d_TrimmedCurve)& c) +void Geom2dArcOfEllipse::setHandle(const Handle(Geom2d_TrimmedCurve) & c) { Handle(Geom2d_Ellipse) basis = Handle(Geom2d_Ellipse)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not an ellipse"); + } this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dArcOfEllipse::handle() const +const Handle(Geom2d_Geometry) & Geom2dArcOfEllipse::handle() const { return myCurve; } -Geometry2d *Geom2dArcOfEllipse::clone() const +Geometry2d* Geom2dArcOfEllipse::clone() const { Geom2dArcOfEllipse* copy = new Geom2dArcOfEllipse(); copy->setHandle(this->myCurve); @@ -1305,8 +1316,9 @@ void Geom2dArcOfEllipse::setMajorAxisDir(Base::Vector2d newdir) { Handle(Geom2d_Ellipse) c = Handle(Geom2d_Ellipse)::DownCast(myCurve->BasisCurve()); assert(!c.IsNull()); - if (newdir.Length() < Precision::Confusion()) - return;//zero vector was passed. Keep the old orientation. + if (newdir.Length() < Precision::Confusion()) { + return; // zero vector was passed. Keep the old orientation. + } try { gp_Elips2d e = c->Elips2d(); gp_Ax22d pos = e.Axis(); @@ -1319,12 +1331,12 @@ void Geom2dArcOfEllipse::setMajorAxisDir(Base::Vector2d newdir) } } -unsigned int Geom2dArcOfEllipse::getMemSize () const +unsigned int Geom2dArcOfEllipse::getMemSize() const { - return sizeof(Geom2d_Ellipse) + 2 *sizeof(double); + return sizeof(Geom2d_Ellipse) + 2 * sizeof(double); } -void Geom2dArcOfEllipse::Save(Base::Writer &writer) const +void Geom2dArcOfEllipse::Save(Base::Writer& writer) const { // save the attributes of the father class Geom2dCurve::Save(writer); @@ -1336,22 +1348,19 @@ void Geom2dArcOfEllipse::Save(Base::Writer &writer) const double u = this->myCurve->FirstParameter(); double v = this->myCurve->LastParameter(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "MajorRadius=\"" << e.MajorRadius() << "\" " + << "MinorRadius=\"" << e.MinorRadius() << "\" " + << "/>" << std::endl; } -void Geom2dArcOfEllipse::Restore(Base::XMLReader &reader) +void Geom2dArcOfEllipse::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geom2dCurve::Restore(reader); - double MajorRadius,MinorRadius,u,v; + double MajorRadius, MinorRadius, u, v; gp_Ax22d axis; // read my Element reader.readElement("Geom2dArcOfEllipse"); @@ -1362,12 +1371,14 @@ void Geom2dArcOfEllipse::Restore(Base::XMLReader &reader) try { GCE2d_MakeEllipse mc(axis, MajorRadius, MinorRadius); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } GCE2d_MakeArcOfEllipse ma(mc.Value()->Elips2d(), u, v); - if (!ma.IsDone()) + if (!ma.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(ma.Status())); + } Handle(Geom2d_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom2d_Ellipse) tmpellipse = Handle(Geom2d_Ellipse)::DownCast(tmpcurve->BasisCurve()); @@ -1381,7 +1392,7 @@ void Geom2dArcOfEllipse::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfEllipse::getPyObject() +PyObject* Geom2dArcOfEllipse::getPyObject() { return new ArcOfEllipse2dPy(static_cast(this->clone())); } @@ -1396,21 +1407,21 @@ Geom2dHyperbola::Geom2dHyperbola() this->myCurve = h; } -Geom2dHyperbola::Geom2dHyperbola(const Handle(Geom2d_Hyperbola)& h) +Geom2dHyperbola::Geom2dHyperbola(const Handle(Geom2d_Hyperbola) & h) { this->myCurve = Handle(Geom2d_Hyperbola)::DownCast(h->Copy()); } Geom2dHyperbola::~Geom2dHyperbola() = default; -const Handle(Geom2d_Geometry)& Geom2dHyperbola::handle() const +const Handle(Geom2d_Geometry) & Geom2dHyperbola::handle() const { return myCurve; } -Geometry2d *Geom2dHyperbola::clone() const +Geometry2d* Geom2dHyperbola::clone() const { - Geom2dHyperbola *newHyp = new Geom2dHyperbola(myCurve); + Geom2dHyperbola* newHyp = new Geom2dHyperbola(myCurve); return newHyp; } @@ -1450,7 +1461,7 @@ void Geom2dHyperbola::setMinorRadius(double Radius) } } -unsigned int Geom2dHyperbola::getMemSize () const +unsigned int Geom2dHyperbola::getMemSize() const { return sizeof(Geom2d_Hyperbola); } @@ -1463,14 +1474,11 @@ void Geom2dHyperbola::Save(Base::Writer& writer) const gp_Hypr2d h = this->myCurve->Hypr2d(); gp_Ax22d axis = h.Axis(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "MajorRadius=\"" << h.MajorRadius() << "\" " + << "MinorRadius=\"" << h.MinorRadius() << "\" " + << "/>" << std::endl; } void Geom2dHyperbola::Restore(Base::XMLReader& reader) @@ -1478,7 +1486,7 @@ void Geom2dHyperbola::Restore(Base::XMLReader& reader) // read the attributes of the father class Geom2dCurve::Restore(reader); - double MajorRadius,MinorRadius; + double MajorRadius, MinorRadius; gp_Ax22d axis; // read my Element reader.readElement("Geom2dHyperbola"); @@ -1489,8 +1497,9 @@ void Geom2dHyperbola::Restore(Base::XMLReader& reader) try { GCE2d_MakeHyperbola mc(axis, MajorRadius, MinorRadius); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } this->myCurve = mc.Value(); } @@ -1499,7 +1508,7 @@ void Geom2dHyperbola::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dHyperbola::getPyObject() +PyObject* Geom2dHyperbola::getPyObject() { return new Hyperbola2dPy(static_cast(this->clone())); } @@ -1511,30 +1520,31 @@ TYPESYSTEM_SOURCE(Part::Geom2dArcOfHyperbola, Part::Geom2dArcOfConic) Geom2dArcOfHyperbola::Geom2dArcOfHyperbola() { Handle(Geom2d_Hyperbola) h = new Geom2d_Hyperbola(gp_Hypr2d()); - this->myCurve = new Geom2d_TrimmedCurve(h, h->FirstParameter(),h->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(h, h->FirstParameter(), h->LastParameter()); } -Geom2dArcOfHyperbola::Geom2dArcOfHyperbola(const Handle(Geom2d_Hyperbola)& h) +Geom2dArcOfHyperbola::Geom2dArcOfHyperbola(const Handle(Geom2d_Hyperbola) & h) { - this->myCurve = new Geom2d_TrimmedCurve(h, h->FirstParameter(),h->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(h, h->FirstParameter(), h->LastParameter()); } Geom2dArcOfHyperbola::~Geom2dArcOfHyperbola() = default; -void Geom2dArcOfHyperbola::setHandle(const Handle(Geom2d_TrimmedCurve)& c) +void Geom2dArcOfHyperbola::setHandle(const Handle(Geom2d_TrimmedCurve) & c) { Handle(Geom2d_Hyperbola) basis = Handle(Geom2d_Hyperbola)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not an hyperbola"); + } this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dArcOfHyperbola::handle() const +const Handle(Geom2d_Geometry) & Geom2dArcOfHyperbola::handle() const { return myCurve; } -Geometry2d *Geom2dArcOfHyperbola::clone() const +Geometry2d* Geom2dArcOfHyperbola::clone() const { Geom2dArcOfHyperbola* copy = new Geom2dArcOfHyperbola(); copy->setHandle(this->myCurve); @@ -1577,12 +1587,12 @@ void Geom2dArcOfHyperbola::setMinorRadius(double Radius) } } -unsigned int Geom2dArcOfHyperbola::getMemSize () const +unsigned int Geom2dArcOfHyperbola::getMemSize() const { - return sizeof(Geom2d_Hyperbola) + 2 *sizeof(double); + return sizeof(Geom2d_Hyperbola) + 2 * sizeof(double); } -void Geom2dArcOfHyperbola::Save(Base::Writer &writer) const +void Geom2dArcOfHyperbola::Save(Base::Writer& writer) const { // save the attributes of the father class Geom2dCurve::Save(writer); @@ -1594,22 +1604,19 @@ void Geom2dArcOfHyperbola::Save(Base::Writer &writer) const double u = this->myCurve->FirstParameter(); double v = this->myCurve->LastParameter(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "MajorRadius=\"" << h.MajorRadius() << "\" " + << "MinorRadius=\"" << h.MinorRadius() << "\" " + << "/>" << std::endl; } -void Geom2dArcOfHyperbola::Restore(Base::XMLReader &reader) +void Geom2dArcOfHyperbola::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geom2dCurve::Restore(reader); - double MajorRadius,MinorRadius,u,v; + double MajorRadius, MinorRadius, u, v; gp_Ax22d axis; // read my Element reader.readElement("Geom2dHyperbola"); @@ -1620,16 +1627,22 @@ void Geom2dArcOfHyperbola::Restore(Base::XMLReader &reader) try { GCE2d_MakeHyperbola mc(axis, MajorRadius, MinorRadius); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } GCE2d_MakeArcOfHyperbola ma(mc.Value()->Hypr2d(), u, v); - if (!ma.IsDone()) + if (!ma.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(ma.Status())); + } Handle(Geom2d_TrimmedCurve) tmpcurve = ma.Value(); - Handle(Geom2d_Hyperbola) tmphyperbola = Handle(Geom2d_Hyperbola)::DownCast(tmpcurve->BasisCurve()); - Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(this->myCurve->BasisCurve()); + Handle(Geom2d_Hyperbola) tmphyperbola = Handle(Geom2d_Hyperbola)::DownCast( + tmpcurve->BasisCurve() + ); + Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast( + this->myCurve->BasisCurve() + ); hyperbola->SetHypr2d(tmphyperbola->Hypr2d()); this->myCurve->SetTrim(tmpcurve->FirstParameter(), tmpcurve->LastParameter()); @@ -1639,7 +1652,7 @@ void Geom2dArcOfHyperbola::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfHyperbola::getPyObject() +PyObject* Geom2dArcOfHyperbola::getPyObject() { return new ArcOfHyperbola2dPy(static_cast(this->clone())); } @@ -1654,21 +1667,21 @@ Geom2dParabola::Geom2dParabola() this->myCurve = p; } -Geom2dParabola::Geom2dParabola(const Handle(Geom2d_Parabola)& p) +Geom2dParabola::Geom2dParabola(const Handle(Geom2d_Parabola) & p) { this->myCurve = Handle(Geom2d_Parabola)::DownCast(p->Copy()); } Geom2dParabola::~Geom2dParabola() = default; -const Handle(Geom2d_Geometry)& Geom2dParabola::handle() const +const Handle(Geom2d_Geometry) & Geom2dParabola::handle() const { return myCurve; } -Geometry2d *Geom2dParabola::clone() const +Geometry2d* Geom2dParabola::clone() const { - Geom2dParabola *newPar = new Geom2dParabola(myCurve); + Geom2dParabola* newPar = new Geom2dParabola(myCurve); return newPar; } @@ -1690,7 +1703,7 @@ void Geom2dParabola::setFocal(double length) } } -unsigned int Geom2dParabola::getMemSize () const +unsigned int Geom2dParabola::getMemSize() const { return sizeof(Geom2d_Parabola); } @@ -1704,13 +1717,10 @@ void Geom2dParabola::Save(Base::Writer& writer) const gp_Ax22d axis = p.Axis(); double focal = p.Focal(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "Focal=\"" << focal << "\" " + << "/>" << std::endl; } void Geom2dParabola::Restore(Base::XMLReader& reader) @@ -1728,8 +1738,9 @@ void Geom2dParabola::Restore(Base::XMLReader& reader) try { GCE2d_MakeParabola mc(axis, Focal); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } this->myCurve = mc.Value(); } @@ -1738,7 +1749,7 @@ void Geom2dParabola::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dParabola::getPyObject() +PyObject* Geom2dParabola::getPyObject() { return new Parabola2dPy(static_cast(this->clone())); } @@ -1750,30 +1761,31 @@ TYPESYSTEM_SOURCE(Part::Geom2dArcOfParabola, Part::Geom2dArcOfConic) Geom2dArcOfParabola::Geom2dArcOfParabola() { Handle(Geom2d_Parabola) p = new Geom2d_Parabola(gp_Parab2d()); - this->myCurve = new Geom2d_TrimmedCurve(p, p->FirstParameter(),p->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(p, p->FirstParameter(), p->LastParameter()); } -Geom2dArcOfParabola::Geom2dArcOfParabola(const Handle(Geom2d_Parabola)& h) +Geom2dArcOfParabola::Geom2dArcOfParabola(const Handle(Geom2d_Parabola) & h) { - this->myCurve = new Geom2d_TrimmedCurve(h, h->FirstParameter(),h->LastParameter()); + this->myCurve = new Geom2d_TrimmedCurve(h, h->FirstParameter(), h->LastParameter()); } Geom2dArcOfParabola::~Geom2dArcOfParabola() = default; -void Geom2dArcOfParabola::setHandle(const Handle(Geom2d_TrimmedCurve)& c) +void Geom2dArcOfParabola::setHandle(const Handle(Geom2d_TrimmedCurve) & c) { Handle(Geom2d_Parabola) basis = Handle(Geom2d_Parabola)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not a parabola"); + } this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dArcOfParabola::handle() const +const Handle(Geom2d_Geometry) & Geom2dArcOfParabola::handle() const { return myCurve; } -Geometry2d *Geom2dArcOfParabola::clone() const +Geometry2d* Geom2dArcOfParabola::clone() const { Geom2dArcOfParabola* copy = new Geom2dArcOfParabola(); copy->setHandle(this->myCurve); @@ -1798,12 +1810,12 @@ void Geom2dArcOfParabola::setFocal(double length) } } -unsigned int Geom2dArcOfParabola::getMemSize () const +unsigned int Geom2dArcOfParabola::getMemSize() const { - return sizeof(Geom2d_Parabola) + 2 *sizeof(double); + return sizeof(Geom2d_Parabola) + 2 * sizeof(double); } -void Geom2dArcOfParabola::Save(Base::Writer &writer) const +void Geom2dArcOfParabola::Save(Base::Writer& writer) const { // save the attributes of the father class Geom2dCurve::Save(writer); @@ -1815,21 +1827,18 @@ void Geom2dArcOfParabola::Save(Base::Writer &writer) const double v = this->myCurve->LastParameter(); double focal = p.Focal(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << "Focal=\"" << focal << "\" " + << "/>" << std::endl; } -void Geom2dArcOfParabola::Restore(Base::XMLReader &reader) +void Geom2dArcOfParabola::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geom2dCurve::Restore(reader); - double Focal,u,v; + double Focal, u, v; gp_Ax22d axis; // read my Element reader.readElement("Geom2dParabola"); @@ -1839,16 +1848,20 @@ void Geom2dArcOfParabola::Restore(Base::XMLReader &reader) try { GCE2d_MakeParabola mc(axis, Focal); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } GCE2d_MakeArcOfParabola ma(mc.Value()->Parab2d(), u, v); - if (!ma.IsDone()) + if (!ma.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(ma.Status())); + } Handle(Geom2d_TrimmedCurve) tmpcurve = ma.Value(); Handle(Geom2d_Parabola) tmpparabola = Handle(Geom2d_Parabola)::DownCast(tmpcurve->BasisCurve()); - Handle(Geom2d_Parabola) parabola = Handle(Geom2d_Parabola)::DownCast(this->myCurve->BasisCurve()); + Handle(Geom2d_Parabola) parabola = Handle(Geom2d_Parabola)::DownCast( + this->myCurve->BasisCurve() + ); parabola->SetParab2d(tmpparabola->Parab2d()); this->myCurve->SetTrim(tmpcurve->FirstParameter(), tmpcurve->LastParameter()); @@ -1858,7 +1871,7 @@ void Geom2dArcOfParabola::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfParabola::getPyObject() +PyObject* Geom2dArcOfParabola::getPyObject() { return new ArcOfParabola2dPy(static_cast(this->clone())); } @@ -1873,53 +1886,53 @@ Geom2dLine::Geom2dLine() this->myCurve = c; } -Geom2dLine::Geom2dLine(const Handle(Geom2d_Line)& l) +Geom2dLine::Geom2dLine(const Handle(Geom2d_Line) & l) { this->myCurve = Handle(Geom2d_Line)::DownCast(l->Copy()); } Geom2dLine::Geom2dLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir) { - this->myCurve = new Geom2d_Line(gp_Pnt2d(Pos.x,Pos.y),gp_Dir2d(Dir.x,Dir.y)); + this->myCurve = new Geom2d_Line(gp_Pnt2d(Pos.x, Pos.y), gp_Dir2d(Dir.x, Dir.y)); } Geom2dLine::~Geom2dLine() = default; void Geom2dLine::setLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir) { - this->myCurve->SetLocation(gp_Pnt2d(Pos.x,Pos.y)); - this->myCurve->SetDirection(gp_Dir2d(Dir.x,Dir.y)); + this->myCurve->SetLocation(gp_Pnt2d(Pos.x, Pos.y)); + this->myCurve->SetDirection(gp_Dir2d(Dir.x, Dir.y)); } Base::Vector2d Geom2dLine::getPos() const { gp_Pnt2d Pos = this->myCurve->Lin2d().Location(); - return {Pos.X(),Pos.Y()}; + return {Pos.X(), Pos.Y()}; } Base::Vector2d Geom2dLine::getDir() const { gp_Dir2d Dir = this->myCurve->Lin2d().Direction(); - return {Dir.X(),Dir.Y()}; + return {Dir.X(), Dir.Y()}; } -const Handle(Geom2d_Geometry)& Geom2dLine::handle() const +const Handle(Geom2d_Geometry) & Geom2dLine::handle() const { return myCurve; } -Geometry2d *Geom2dLine::clone() const +Geometry2d* Geom2dLine::clone() const { - Geom2dLine *newLine = new Geom2dLine(myCurve); + Geom2dLine* newLine = new Geom2dLine(myCurve); return newLine; } -unsigned int Geom2dLine::getMemSize () const +unsigned int Geom2dLine::getMemSize() const { return sizeof(Geom2d_Line); } -void Geom2dLine::Save(Base::Writer &writer) const +void Geom2dLine::Save(Base::Writer& writer) const { // save the attributes of the father class Geometry2d::Save(writer); @@ -1927,22 +1940,20 @@ void Geom2dLine::Save(Base::Writer &writer) const Base::Vector2d Pos = getPos(); Base::Vector2d Dir = getDir(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; } -void Geom2dLine::Restore(Base::XMLReader &reader) +void Geom2dLine::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geom2dCurve::Restore(reader); - double PosX,PosY,DirX,DirY; + double PosX, PosY, DirX, DirY; // read my Element reader.readElement("Geom2dLine"); // get the value of my Attribute @@ -1955,8 +1966,9 @@ void Geom2dLine::Restore(Base::XMLReader &reader) try { GCE2d_MakeLine mc(pnt, dir); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } this->myCurve = mc.Value(); } @@ -1965,7 +1977,7 @@ void Geom2dLine::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dLine::getPyObject() +PyObject* Geom2dLine::getPyObject() { return new Line2dPy(static_cast(this->clone())); } @@ -1977,30 +1989,31 @@ TYPESYSTEM_SOURCE(Part::Geom2dLineSegment, Part::Geom2dCurve) Geom2dLineSegment::Geom2dLineSegment() { gp_Lin2d line; - line.SetLocation(gp_Pnt2d(0.0,0.0)); - line.SetDirection(gp_Dir2d(0.0,1.0)); + line.SetLocation(gp_Pnt2d(0.0, 0.0)); + line.SetDirection(gp_Dir2d(0.0, 1.0)); Handle(Geom2d_Line) c = new Geom2d_Line(line); - this->myCurve = new Geom2d_TrimmedCurve(c, 0.0,1.0); + this->myCurve = new Geom2d_TrimmedCurve(c, 0.0, 1.0); } Geom2dLineSegment::~Geom2dLineSegment() = default; -void Geom2dLineSegment::setHandle(const Handle(Geom2d_TrimmedCurve)& c) +void Geom2dLineSegment::setHandle(const Handle(Geom2d_TrimmedCurve) & c) { Handle(Geom2d_Line) basis = Handle(Geom2d_Line)::DownCast(c->BasisCurve()); - if (basis.IsNull()) + if (basis.IsNull()) { Standard_Failure::Raise("Basis curve is not a line"); + } this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dLineSegment::handle() const +const Handle(Geom2d_Geometry) & Geom2dLineSegment::handle() const { return myCurve; } -Geometry2d *Geom2dLineSegment::clone()const +Geometry2d* Geom2dLineSegment::clone() const { - Geom2dLineSegment *tempCurve = new Geom2dLineSegment(); + Geom2dLineSegment* tempCurve = new Geom2dLineSegment(); tempCurve->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(myCurve->Copy()); return tempCurve; } @@ -2021,21 +2034,21 @@ Base::Vector2d Geom2dLineSegment::getEndPoint() const void Geom2dLineSegment::setPoints(const Base::Vector2d& Start, const Base::Vector2d& End) { - gp_Pnt2d p1(Start.x,Start.y), p2(End.x,End.y); + gp_Pnt2d p1(Start.x, Start.y), p2(End.x, End.y); Handle(Geom2d_TrimmedCurve) this_curv = Handle(Geom2d_TrimmedCurve)::DownCast(handle()); try { // Create line out of two points - if (p1.Distance(p2) < gp::Resolution()) + if (p1.Distance(p2) < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); + } GCE2d_MakeSegment ms(p1, p2); if (!ms.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(ms.Status())); } // get Geom_Line of line segment - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom2d_TrimmedCurve) that_curv = ms.Value(); Handle(Geom2d_Line) that_line = Handle(Geom2d_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin2d(that_line->Lin2d()); @@ -2046,50 +2059,49 @@ void Geom2dLineSegment::setPoints(const Base::Vector2d& Start, const Base::Vecto } } -unsigned int Geom2dLineSegment::getMemSize () const +unsigned int Geom2dLineSegment::getMemSize() const { return sizeof(Geom2d_TrimmedCurve) + sizeof(Geom2d_Line); } -void Geom2dLineSegment::Save(Base::Writer &writer) const +void Geom2dLineSegment::Save(Base::Writer& writer) const { // save the attributes of the father class Geom2dCurve::Save(writer); - Base::Vector2d End = getEndPoint(); - Base::Vector2d Start = getStartPoint(); + Base::Vector2d End = getEndPoint(); + Base::Vector2d Start = getStartPoint(); - writer.Stream() - << writer.ind() - << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; } -void Geom2dLineSegment::Restore(Base::XMLReader &reader) +void Geom2dLineSegment::Restore(Base::XMLReader& reader) { // read the attributes of the father class Geom2dCurve::Restore(reader); - double StartX,StartY,EndX,EndY; + double StartX, StartY, EndX, EndY; // read my Element reader.readElement("Geom2dLineSegment"); // get the value of my Attribute StartX = reader.getAttribute("StartX"); StartY = reader.getAttribute("StartY"); - EndX = reader.getAttribute("EndX"); - EndY = reader.getAttribute("EndY"); + EndX = reader.getAttribute("EndX"); + EndY = reader.getAttribute("EndY"); gp_Pnt2d p1(StartX, StartY); gp_Pnt2d p2(EndX, EndY); try { GCE2d_MakeSegment mc(p1, p2); - if (!mc.IsDone()) + if (!mc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(mc.Status())); + } this->myCurve = mc.Value(); } @@ -2098,7 +2110,7 @@ void Geom2dLineSegment::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dLineSegment::getPyObject() +PyObject* Geom2dLineSegment::getPyObject() { return new Line2dSegmentPy(static_cast(this->clone())); } @@ -2109,50 +2121,50 @@ TYPESYSTEM_SOURCE(Part::Geom2dOffsetCurve, Part::Geom2dCurve) Geom2dOffsetCurve::Geom2dOffsetCurve() = default; -Geom2dOffsetCurve::Geom2dOffsetCurve(const Handle(Geom2d_Curve)& c, double offset) +Geom2dOffsetCurve::Geom2dOffsetCurve(const Handle(Geom2d_Curve) & c, double offset) { this->myCurve = new Geom2d_OffsetCurve(c, offset); } -Geom2dOffsetCurve::Geom2dOffsetCurve(const Handle(Geom2d_OffsetCurve)& c) +Geom2dOffsetCurve::Geom2dOffsetCurve(const Handle(Geom2d_OffsetCurve) & c) { this->myCurve = Handle(Geom2d_OffsetCurve)::DownCast(c->Copy()); } Geom2dOffsetCurve::~Geom2dOffsetCurve() = default; -Geometry2d *Geom2dOffsetCurve::clone() const +Geometry2d* Geom2dOffsetCurve::clone() const { - Geom2dOffsetCurve *newCurve = new Geom2dOffsetCurve(myCurve); + Geom2dOffsetCurve* newCurve = new Geom2dOffsetCurve(myCurve); return newCurve; } -void Geom2dOffsetCurve::setHandle(const Handle(Geom2d_OffsetCurve)& c) +void Geom2dOffsetCurve::setHandle(const Handle(Geom2d_OffsetCurve) & c) { this->myCurve = Handle(Geom2d_OffsetCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dOffsetCurve::handle() const +const Handle(Geom2d_Geometry) & Geom2dOffsetCurve::handle() const { return this->myCurve; } -unsigned int Geom2dOffsetCurve::getMemSize () const +unsigned int Geom2dOffsetCurve::getMemSize() const { throw Base::NotImplementedError("Geom2dOffsetCurve::getMemSize"); } -void Geom2dOffsetCurve::Save(Base::Writer &/*writer*/) const +void Geom2dOffsetCurve::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("Geom2dOffsetCurve::Save"); } -void Geom2dOffsetCurve::Restore(Base::XMLReader &/*reader*/) +void Geom2dOffsetCurve::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("Geom2dOffsetCurve::Restore"); } -PyObject *Geom2dOffsetCurve::getPyObject() +PyObject* Geom2dOffsetCurve::getPyObject() { return new OffsetCurve2dPy(static_cast(this->clone())); } @@ -2163,80 +2175,81 @@ TYPESYSTEM_SOURCE(Part::Geom2dTrimmedCurve, Part::Geom2dCurve) Geom2dTrimmedCurve::Geom2dTrimmedCurve() = default; -Geom2dTrimmedCurve::Geom2dTrimmedCurve(const Handle(Geom2d_TrimmedCurve)& c) +Geom2dTrimmedCurve::Geom2dTrimmedCurve(const Handle(Geom2d_TrimmedCurve) & c) { this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } Geom2dTrimmedCurve::~Geom2dTrimmedCurve() = default; -void Geom2dTrimmedCurve::setHandle(const Handle(Geom2d_TrimmedCurve)& c) +void Geom2dTrimmedCurve::setHandle(const Handle(Geom2d_TrimmedCurve) & c) { this->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(c->Copy()); } -const Handle(Geom2d_Geometry)& Geom2dTrimmedCurve::handle() const +const Handle(Geom2d_Geometry) & Geom2dTrimmedCurve::handle() const { return myCurve; } -Geometry2d *Geom2dTrimmedCurve::clone() const +Geometry2d* Geom2dTrimmedCurve::clone() const { - Geom2dTrimmedCurve *newCurve = new Geom2dTrimmedCurve(myCurve); + Geom2dTrimmedCurve* newCurve = new Geom2dTrimmedCurve(myCurve); return newCurve; } -unsigned int Geom2dTrimmedCurve::getMemSize () const +unsigned int Geom2dTrimmedCurve::getMemSize() const { throw Base::NotImplementedError("Geom2dTrimmedCurve::getMemSize"); } -void Geom2dTrimmedCurve::Save(Base::Writer &/*writer*/) const +void Geom2dTrimmedCurve::Save(Base::Writer& /*writer*/) const { throw Base::NotImplementedError("Geom2dTrimmedCurve::Save"); } -void Geom2dTrimmedCurve::Restore(Base::XMLReader &/*reader*/) +void Geom2dTrimmedCurve::Restore(Base::XMLReader& /*reader*/) { throw Base::NotImplementedError("Geom2dTrimmedCurve::Restore"); } -PyObject *Geom2dTrimmedCurve::getPyObject() +PyObject* Geom2dTrimmedCurve::getPyObject() { Handle(Geom2d_Curve) basis = this->myCurve->BasisCurve(); - if (basis.IsNull()) + if (basis.IsNull()) { Py_Return; - if (basis->IsKind(STANDARD_TYPE (Geom2d_Parabola))) { + } + if (basis->IsKind(STANDARD_TYPE(Geom2d_Parabola))) { Geom2dArcOfParabola c; c.setHandle(this->myCurve); return c.getPyObject(); } - if (basis->IsKind(STANDARD_TYPE (Geom2d_Hyperbola))) { + if (basis->IsKind(STANDARD_TYPE(Geom2d_Hyperbola))) { Geom2dArcOfHyperbola c; c.setHandle(this->myCurve); return c.getPyObject(); } - if (basis->IsKind(STANDARD_TYPE (Geom2d_Ellipse))) { + if (basis->IsKind(STANDARD_TYPE(Geom2d_Ellipse))) { Geom2dArcOfEllipse c; c.setHandle(this->myCurve); return c.getPyObject(); } - if (basis->IsKind(STANDARD_TYPE (Geom2d_Circle))) { + if (basis->IsKind(STANDARD_TYPE(Geom2d_Circle))) { Geom2dArcOfCircle c; c.setHandle(this->myCurve); return c.getPyObject(); } - if (basis->IsKind(STANDARD_TYPE (Geom2d_Line))) { + if (basis->IsKind(STANDARD_TYPE(Geom2d_Line))) { Geom2dLineSegment c; c.setHandle(this->myCurve); return c.getPyObject(); } - if (basis->IsKind(STANDARD_TYPE (Geom2d_BSplineCurve))) { + if (basis->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve))) { Geom2dBSplineCurve c; c.setHandle(Handle(Geom2d_BSplineCurve)::DownCast(basis)); return c.getPyObject(); } - if (basis->IsKind(STANDARD_TYPE (Geom2d_BezierCurve))) { + if (basis->IsKind(STANDARD_TYPE(Geom2d_BezierCurve))) { Geom2dBezierCurve c; c.setHandle(Handle(Geom2d_BezierCurve)::DownCast(basis)); return c.getPyObject(); @@ -2248,50 +2261,50 @@ PyObject *Geom2dTrimmedCurve::getPyObject() // ------------------------------------------------------------------ -namespace Part { +namespace Part +{ std::unique_ptr makeFromCurve2d(Handle(Geom2d_Curve) curve) { std::unique_ptr geo2d; - if (curve.IsNull()) + if (curve.IsNull()) { return geo2d; - if (curve->IsKind(STANDARD_TYPE (Geom2d_Parabola))) { + } + if (curve->IsKind(STANDARD_TYPE(Geom2d_Parabola))) { geo2d = std::make_unique(Handle(Geom2d_Parabola)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_Hyperbola))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_Hyperbola))) { geo2d = std::make_unique(Handle(Geom2d_Hyperbola)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_Ellipse))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_Ellipse))) { geo2d = std::make_unique(Handle(Geom2d_Ellipse)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_Circle))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_Circle))) { geo2d = std::make_unique(Handle(Geom2d_Circle)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_Line))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_Line))) { geo2d = std::make_unique(Handle(Geom2d_Line)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_BSplineCurve))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_BSplineCurve))) { geo2d = std::make_unique(Handle(Geom2d_BSplineCurve)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_BezierCurve))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_BezierCurve))) { geo2d = std::make_unique(Handle(Geom2d_BezierCurve)::DownCast(curve)); } - else if (curve->IsKind(STANDARD_TYPE (Geom2d_TrimmedCurve))) { + else if (curve->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))) { geo2d = std::make_unique(Handle(Geom2d_TrimmedCurve)::DownCast(curve)); } return geo2d; } -std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& c, double f, double l) +std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve) & c, double f, double l) { if (c->IsKind(STANDARD_TYPE(Geom2d_Circle))) { Handle(Geom2d_Circle) circ = Handle(Geom2d_Circle)::DownCast(c); std::unique_ptr arc(new Geom2dArcOfCircle()); - Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom2d_Circle) this_circ = Handle(Geom2d_Circle)::DownCast - (this_arc->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom2d_Circle) this_circ = Handle(Geom2d_Circle)::DownCast(this_arc->BasisCurve()); this_circ->SetCirc2d(circ->Circ2d()); this_arc->SetTrim(f, l); return arc; @@ -2300,10 +2313,8 @@ std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& Handle(Geom2d_Ellipse) ellp = Handle(Geom2d_Ellipse)::DownCast(c); std::unique_ptr arc(new Geom2dArcOfEllipse()); - Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom2d_Ellipse) this_ellp = Handle(Geom2d_Ellipse)::DownCast - (this_arc->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom2d_Ellipse) this_ellp = Handle(Geom2d_Ellipse)::DownCast(this_arc->BasisCurve()); this_ellp->SetElips2d(ellp->Elips2d()); this_arc->SetTrim(f, l); return arc; @@ -2312,10 +2323,8 @@ std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& Handle(Geom2d_Hyperbola) hypr = Handle(Geom2d_Hyperbola)::DownCast(c); std::unique_ptr arc(new Geom2dArcOfHyperbola()); - Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom2d_Hyperbola) this_hypr = Handle(Geom2d_Hyperbola)::DownCast - (this_arc->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom2d_Hyperbola) this_hypr = Handle(Geom2d_Hyperbola)::DownCast(this_arc->BasisCurve()); this_hypr->SetHypr2d(hypr->Hypr2d()); this_arc->SetTrim(f, l); return arc; @@ -2324,10 +2333,8 @@ std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& Handle(Geom2d_Line) line = Handle(Geom2d_Line)::DownCast(c); std::unique_ptr segm(new Geom2dLineSegment()); - Handle(Geom2d_TrimmedCurve) this_segm = Handle(Geom2d_TrimmedCurve)::DownCast - (segm->handle()); - Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast - (this_segm->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_segm = Handle(Geom2d_TrimmedCurve)::DownCast(segm->handle()); + Handle(Geom2d_Line) this_line = Handle(Geom2d_Line)::DownCast(this_segm->BasisCurve()); this_line->SetLin2d(line->Lin2d()); this_segm->SetTrim(f, l); return segm; @@ -2336,10 +2343,8 @@ std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& Handle(Geom2d_Parabola) para = Handle(Geom2d_Parabola)::DownCast(c); std::unique_ptr arc(new Geom2dArcOfParabola()); - Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast - (arc->handle()); - Handle(Geom2d_Parabola) this_para = Handle(Geom2d_Parabola)::DownCast - (this_arc->BasisCurve()); + Handle(Geom2d_TrimmedCurve) this_arc = Handle(Geom2d_TrimmedCurve)::DownCast(arc->handle()); + Handle(Geom2d_Parabola) this_para = Handle(Geom2d_Parabola)::DownCast(this_arc->BasisCurve()); this_para->SetParab2d(para->Parab2d()); this_arc->SetTrim(f, l); return arc; @@ -2358,7 +2363,9 @@ std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& Handle(Geom2d_OffsetCurve) oc = Handle(Geom2d_OffsetCurve)::DownCast(c); double v = oc->Offset(); std::unique_ptr bc(makeFromTrimmedCurve2d(oc->BasisCurve(), f, l)); - return std::unique_ptr(new Geom2dOffsetCurve(Handle(Geom2d_Curve)::DownCast(bc->handle()), v)); + return std::unique_ptr( + new Geom2dOffsetCurve(Handle(Geom2d_Curve)::DownCast(bc->handle()), v) + ); } else if (c->IsKind(STANDARD_TYPE(Geom2d_TrimmedCurve))) { Handle(Geom2d_TrimmedCurve) trc = Handle(Geom2d_TrimmedCurve)::DownCast(c); @@ -2373,69 +2380,56 @@ std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)& std::unique_ptr makeFromCurveAdaptor2d(const Adaptor2d_Curve2d& adapt) { std::unique_ptr geoCurve; - switch (adapt.GetType()) - { - case GeomAbs_Line: - { + switch (adapt.GetType()) { + case GeomAbs_Line: { geoCurve = std::make_unique(); - Handle(Geom2d_Line) this_curv = Handle(Geom2d_Line)::DownCast - (geoCurve->handle()); + Handle(Geom2d_Line) this_curv = Handle(Geom2d_Line)::DownCast(geoCurve->handle()); this_curv->SetLin2d(adapt.Line()); break; } - case GeomAbs_Circle: - { + case GeomAbs_Circle: { geoCurve = std::make_unique(); - Handle(Geom2d_Circle) this_curv = Handle(Geom2d_Circle)::DownCast - (geoCurve->handle()); + Handle(Geom2d_Circle) this_curv = Handle(Geom2d_Circle)::DownCast(geoCurve->handle()); this_curv->SetCirc2d(adapt.Circle()); break; } - case GeomAbs_Ellipse: - { + case GeomAbs_Ellipse: { geoCurve = std::make_unique(); - Handle(Geom2d_Ellipse) this_curv = Handle(Geom2d_Ellipse)::DownCast - (geoCurve->handle()); + Handle(Geom2d_Ellipse) this_curv = Handle(Geom2d_Ellipse)::DownCast(geoCurve->handle()); this_curv->SetElips2d(adapt.Ellipse()); break; } - case GeomAbs_Hyperbola: - { + case GeomAbs_Hyperbola: { geoCurve = std::make_unique(); - Handle(Geom2d_Hyperbola) this_curv = Handle(Geom2d_Hyperbola)::DownCast - (geoCurve->handle()); + Handle(Geom2d_Hyperbola) this_curv = Handle(Geom2d_Hyperbola)::DownCast(geoCurve->handle()); this_curv->SetHypr2d(adapt.Hyperbola()); break; } - case GeomAbs_Parabola: - { + case GeomAbs_Parabola: { geoCurve = std::make_unique(); - Handle(Geom2d_Parabola) this_curv = Handle(Geom2d_Parabola)::DownCast - (geoCurve->handle()); + Handle(Geom2d_Parabola) this_curv = Handle(Geom2d_Parabola)::DownCast(geoCurve->handle()); this_curv->SetParab2d(adapt.Parabola()); break; } - case GeomAbs_BezierCurve: - { + case GeomAbs_BezierCurve: { geoCurve = std::make_unique(adapt.Bezier()); break; } - case GeomAbs_BSplineCurve: - { + case GeomAbs_BSplineCurve: { geoCurve = std::make_unique(adapt.BSpline()); break; } - case GeomAbs_OtherCurve: - default: - break; + case GeomAbs_OtherCurve: + default: + break; } - if (!geoCurve) + if (!geoCurve) { throw Base::TypeError("Unhandled curve type"); + } // Check if the curve must be trimmed - Handle(Geom2d_Curve) curv2d = Handle(Geom2d_Curve)::DownCast - (geoCurve->handle()); + Handle(Geom2d_Curve) curv2d = Handle(Geom2d_Curve)::DownCast(geoCurve->handle()); double u = curv2d->FirstParameter(); double v = curv2d->LastParameter(); if (u != adapt.FirstParameter() || v != adapt.LastParameter()) { @@ -2444,4 +2438,4 @@ std::unique_ptr makeFromCurveAdaptor2d(const Adaptor2d_Curve2d& ada return geoCurve; } -} +} // namespace Part diff --git a/src/Mod/Part/App/Geometry2d.h b/src/Mod/Part/App/Geometry2d.h index 8ed3e1d159..bdc31ad29d 100644 --- a/src/Mod/Part/App/Geometry2d.h +++ b/src/Mod/Part/App/Geometry2d.h @@ -48,61 +48,65 @@ #include -namespace Part { +namespace Part +{ -class PartExport Geometry2d : public Base::Persistence +class PartExport Geometry2d: public Base::Persistence { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: ~Geometry2d() override; virtual TopoDS_Shape toShape() const = 0; - virtual const Handle(Geom2d_Geometry)& handle() const = 0; + virtual const Handle(Geom2d_Geometry) & handle() const = 0; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; /// returns a cloned object - virtual Geometry2d *clone() const = 0; + virtual Geometry2d* clone() const = 0; protected: Geometry2d(); public: Geometry2d(const Geometry2d&) = delete; - Geometry2d& operator = (const Geometry2d&) = delete; + Geometry2d& operator=(const Geometry2d&) = delete; }; -class PartExport Geom2dPoint : public Geometry2d +class PartExport Geom2dPoint: public Geometry2d { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dPoint(); - Geom2dPoint(const Handle(Geom2d_CartesianPoint)&); + Geom2dPoint(const Handle(Geom2d_CartesianPoint) &); Geom2dPoint(const Base::Vector2d&); ~Geom2dPoint() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; TopoDS_Shape toShape() const override; - // Persistence implementer --------------------- + // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const override; + const Handle(Geom2d_Geometry) & handle() const override; - Base::Vector2d getPoint()const; + Base::Vector2d getPoint() const; void setPoint(const Base::Vector2d&); private: Handle(Geom2d_CartesianPoint) myPoint; }; -class PartExport Geom2dCurve : public Geometry2d +class PartExport Geom2dCurve: public Geometry2d { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dCurve(); ~Geom2dCurve() override; @@ -113,41 +117,43 @@ public: Base::Vector2d firstDerivativeAtParameter(double u) const; Base::Vector2d secondDerivativeAtParameter(double u) const; bool normal(double u, gp_Dir2d& dir) const; - bool closestParameter(const Base::Vector2d& point, double &u) const; - bool closestParameterToBasicCurve(const Base::Vector2d& point, double &u) const; + bool closestParameter(const Base::Vector2d& point, double& u) const; + bool closestParameterToBasicCurve(const Base::Vector2d& point, double& u) const; }; -class PartExport Geom2dBezierCurve : public Geom2dCurve +class PartExport Geom2dBezierCurve: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dBezierCurve(); - Geom2dBezierCurve(const Handle(Geom2d_BezierCurve)&); + Geom2dBezierCurve(const Handle(Geom2d_BezierCurve) &); ~Geom2dBezierCurve() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; // Persistence implementer --------------------- - unsigned int getMemSize () const override; - void Save (Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + unsigned int getMemSize() const override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_BezierCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_BezierCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_BezierCurve) myCurve; }; -class PartExport Geom2dBSplineCurve : public Geom2dCurve +class PartExport Geom2dBSplineCurve: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dBSplineCurve(); - Geom2dBSplineCurve(const Handle(Geom2d_BSplineCurve)&); + Geom2dBSplineCurve(const Handle(Geom2d_BSplineCurve) &); ~Geom2dBSplineCurve() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; /*! * Set the poles and tangents for the cubic Hermite spline @@ -157,78 +163,95 @@ public: * Compute the tangents for a Cardinal spline using the * the cubic Hermite spline. It uses the method for Cardinal splines. */ - void getCardinalSplineTangents(const std::vector&, - const std::vector&, - std::vector&) const; + void getCardinalSplineTangents( + const std::vector&, + const std::vector&, + std::vector& + ) const; /*! * Compute the tangents for a Cardinal spline using the * the cubic Hermite spline. It uses the method for Cardinal splines. * It uses the same parameter for each tangent. */ - void getCardinalSplineTangents(const std::vector&, double, - std::vector&) const; + void getCardinalSplineTangents(const std::vector&, double, std::vector&) const; int countPoles() const; - void setPole(int index, const Base::Vector2d&, double weight=-1); + void setPole(int index, const Base::Vector2d&, double weight = -1); std::vector getPoles() const; - bool join(const Handle(Geom2d_BSplineCurve)&); + bool join(const Handle(Geom2d_BSplineCurve) &); void makeC1Continuous(double); std::list toBiArcs(double tolerance) const; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_BSplineCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_BSplineCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: - void createArcs(double tolerance, std::list& new_spans, - const gp_Pnt2d &p_start, const gp_Vec2d &v_start, - double t_start, double t_end, gp_Pnt2d &p_end, gp_Vec2d &v_end) const; - bool calculateBiArcPoints(const gp_Pnt2d& p0, gp_Vec2d v_start, - const gp_Pnt2d& p4, gp_Vec2d v_end, - gp_Pnt2d& p1, gp_Pnt2d& p2, gp_Pnt2d& p3) const; + void createArcs( + double tolerance, + std::list& new_spans, + const gp_Pnt2d& p_start, + const gp_Vec2d& v_start, + double t_start, + double t_end, + gp_Pnt2d& p_end, + gp_Vec2d& v_end + ) const; + bool calculateBiArcPoints( + const gp_Pnt2d& p0, + gp_Vec2d v_start, + const gp_Pnt2d& p4, + gp_Vec2d v_end, + gp_Pnt2d& p1, + gp_Pnt2d& p2, + gp_Pnt2d& p3 + ) const; + private: Handle(Geom2d_BSplineCurve) myCurve; }; -class PartExport Geom2dConic : public Geom2dCurve +class PartExport Geom2dConic: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + protected: Geom2dConic(); public: ~Geom2dConic() override; - Geometry2d *clone() const override = 0; + Geometry2d* clone() const override = 0; Base::Vector2d getLocation() const; void setLocation(const Base::Vector2d& Center); bool isReversed() const; unsigned int getMemSize() const override = 0; - PyObject *getPyObject() override = 0; + PyObject* getPyObject() override = 0; - const Handle(Geom2d_Geometry)& handle() const override = 0; + const Handle(Geom2d_Geometry) & handle() const override = 0; protected: void SaveAxis(Base::Writer& writer, const gp_Ax22d&) const; void RestoreAxis(Base::XMLReader& reader, gp_Ax22d&); }; -class PartExport Geom2dArcOfConic : public Geom2dCurve +class PartExport Geom2dArcOfConic: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + protected: Geom2dArcOfConic(); public: ~Geom2dArcOfConic() override; - Geometry2d *clone() const override = 0; + Geometry2d* clone() const override = 0; Base::Vector2d getLocation() const; void setLocation(const Base::Vector2d& Center); @@ -241,76 +264,83 @@ public: void setRange(double u, double v); unsigned int getMemSize() const override = 0; - PyObject *getPyObject() override = 0; + PyObject* getPyObject() override = 0; - const Handle(Geom2d_Geometry)& handle() const override = 0; + const Handle(Geom2d_Geometry) & handle() const override = 0; protected: void SaveAxis(Base::Writer& writer, const gp_Ax22d&, double u, double v) const; void RestoreAxis(Base::XMLReader& reader, gp_Ax22d&, double& u, double& v); }; -class PartExport Geom2dCircle : public Geom2dConic +class PartExport Geom2dCircle: public Geom2dConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dCircle(); - Geom2dCircle(const Handle(Geom2d_Circle)&); + Geom2dCircle(const Handle(Geom2d_Circle) &); ~Geom2dCircle() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getRadius() const; void setRadius(double Radius); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const override; + const Handle(Geom2d_Geometry) & handle() const override; - static Base::Vector2d getCircleCenter (const Base::Vector2d &p1, const Base::Vector2d &p2, const Base::Vector2d &p3); + static Base::Vector2d getCircleCenter( + const Base::Vector2d& p1, + const Base::Vector2d& p2, + const Base::Vector2d& p3 + ); private: Handle(Geom2d_Circle) myCurve; }; -class PartExport Geom2dArcOfCircle : public Geom2dArcOfConic +class PartExport Geom2dArcOfCircle: public Geom2dArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dArcOfCircle(); - Geom2dArcOfCircle(const Handle(Geom2d_Circle)&); + Geom2dArcOfCircle(const Handle(Geom2d_Circle) &); ~Geom2dArcOfCircle() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getRadius() const; void setRadius(double Radius); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_TrimmedCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; }; -class PartExport Geom2dEllipse : public Geom2dConic +class PartExport Geom2dEllipse: public Geom2dConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dEllipse(); - Geom2dEllipse(const Handle(Geom2d_Ellipse)&); + Geom2dEllipse(const Handle(Geom2d_Ellipse) &); ~Geom2dEllipse() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getMajorRadius() const; void setMajorRadius(double Radius); @@ -321,26 +351,27 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_Ellipse) &e); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_Ellipse) & e); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_Ellipse) myCurve; }; -class PartExport Geom2dArcOfEllipse : public Geom2dArcOfConic +class PartExport Geom2dArcOfEllipse: public Geom2dArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dArcOfEllipse(); - Geom2dArcOfEllipse(const Handle(Geom2d_Ellipse)&); + Geom2dArcOfEllipse(const Handle(Geom2d_Ellipse) &); ~Geom2dArcOfEllipse() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getMajorRadius() const; void setMajorRadius(double Radius); @@ -351,26 +382,27 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_TrimmedCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; }; -class PartExport Geom2dHyperbola : public Geom2dConic +class PartExport Geom2dHyperbola: public Geom2dConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dHyperbola(); - Geom2dHyperbola(const Handle(Geom2d_Hyperbola)&); + Geom2dHyperbola(const Handle(Geom2d_Hyperbola) &); ~Geom2dHyperbola() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getMajorRadius() const; void setMajorRadius(double Radius); @@ -379,25 +411,26 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const override; + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_Hyperbola) myCurve; }; -class PartExport Geom2dArcOfHyperbola : public Geom2dArcOfConic +class PartExport Geom2dArcOfHyperbola: public Geom2dArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dArcOfHyperbola(); - Geom2dArcOfHyperbola(const Handle(Geom2d_Hyperbola)&); + Geom2dArcOfHyperbola(const Handle(Geom2d_Hyperbola) &); ~Geom2dArcOfHyperbola() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getMajorRadius() const; void setMajorRadius(double Radius); @@ -406,78 +439,81 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_TrimmedCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; }; -class PartExport Geom2dParabola : public Geom2dConic +class PartExport Geom2dParabola: public Geom2dConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dParabola(); - Geom2dParabola(const Handle(Geom2d_Parabola)&); + Geom2dParabola(const Handle(Geom2d_Parabola) &); ~Geom2dParabola() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getFocal() const; void setFocal(double length); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const override; + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_Parabola) myCurve; }; -class PartExport Geom2dArcOfParabola : public Geom2dArcOfConic +class PartExport Geom2dArcOfParabola: public Geom2dArcOfConic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dArcOfParabola(); - Geom2dArcOfParabola(const Handle(Geom2d_Parabola)&); + Geom2dArcOfParabola(const Handle(Geom2d_Parabola) &); ~Geom2dArcOfParabola() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; double getFocal() const; void setFocal(double length); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_TrimmedCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; }; -class PartExport Geom2dLine : public Geom2dCurve +class PartExport Geom2dLine: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dLine(); - Geom2dLine(const Handle(Geom2d_Line)&); + Geom2dLine(const Handle(Geom2d_Line) &); Geom2dLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir); ~Geom2dLine() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; void setLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir); Base::Vector2d getPos() const; @@ -485,96 +521,98 @@ public: // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const override; + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_Line) myCurve; }; -class PartExport Geom2dLineSegment : public Geom2dCurve +class PartExport Geom2dLineSegment: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dLineSegment(); ~Geom2dLineSegment() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; Base::Vector2d getStartPoint() const; Base::Vector2d getEndPoint() const; - void setPoints(const Base::Vector2d& p1, - const Base::Vector2d& p2); + void setPoints(const Base::Vector2d& p1, const Base::Vector2d& p2); // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_TrimmedCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; }; -class PartExport Geom2dOffsetCurve : public Geom2dCurve +class PartExport Geom2dOffsetCurve: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dOffsetCurve(); - Geom2dOffsetCurve(const Handle(Geom2d_Curve)&, double); - Geom2dOffsetCurve(const Handle(Geom2d_OffsetCurve)&); + Geom2dOffsetCurve(const Handle(Geom2d_Curve) &, double); + Geom2dOffsetCurve(const Handle(Geom2d_OffsetCurve) &); ~Geom2dOffsetCurve() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_OffsetCurve)& c); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_OffsetCurve) & c); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_OffsetCurve) myCurve; }; -class PartExport Geom2dTrimmedCurve : public Geom2dCurve +class PartExport Geom2dTrimmedCurve: public Geom2dCurve { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: Geom2dTrimmedCurve(); - explicit Geom2dTrimmedCurve(const Handle(Geom2d_TrimmedCurve)&); + explicit Geom2dTrimmedCurve(const Handle(Geom2d_TrimmedCurve) &); ~Geom2dTrimmedCurve() override; - Geometry2d *clone() const override; + Geometry2d* clone() const override; // Persistence implementer --------------------- unsigned int getMemSize() const override; - void Save(Base::Writer &/*writer*/) const override; - void Restore(Base::XMLReader &/*reader*/) override; + void Save(Base::Writer& /*writer*/) const override; + void Restore(Base::XMLReader& /*reader*/) override; // Base implementer ---------------------------- - PyObject *getPyObject() override; + PyObject* getPyObject() override; - void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const override; + void setHandle(const Handle(Geom2d_TrimmedCurve) &); + const Handle(Geom2d_Geometry) & handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; }; std::unique_ptr makeFromCurve2d(Handle(Geom2d_Curve)); -std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve)&, double f, double l); +std::unique_ptr makeFromTrimmedCurve2d(const Handle(Geom2d_Curve) &, double f, double l); std::unique_ptr makeFromCurveAdaptor2d(const Adaptor2d_Curve2d&); -} +} // namespace Part -#endif // PART_GEOMETRY2D_H +#endif // PART_GEOMETRY2D_H diff --git a/src/Mod/Part/App/GeometryBoolExtension.pyi b/src/Mod/Part/App/GeometryBoolExtension.pyi index 7f3db293b4..1c550c6cf3 100644 --- a/src/Mod/Part/App/GeometryBoolExtension.pyi +++ b/src/Mod/Part/App/GeometryBoolExtension.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from GeometryExtension import GeometryExtension - @export( PythonName="Part.GeometryBoolExtension", Include="Mod/Part/App/GeometryDefaultExtension.h", diff --git a/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp b/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp index 18cd5ca10f..0fde236a66 100644 --- a/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp @@ -34,18 +34,19 @@ std::string GeometryBoolExtensionPy::representation() const { std::stringstream str; bool val = getGeometryBoolExtensionPtr()->getValue(); - str << "getName().empty()) + if (!getGeometryBoolExtensionPtr()->getName().empty()) { str << "\'" << getGeometryBoolExtensionPtr()->getName() << "\', "; + } - str << (val?"True":"False") << ") >"; + str << (val ? "True" : "False") << ") >"; return str.str(); } -PyObject *GeometryBoolExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryBoolExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of the python object and the Twin object return new GeometryBoolExtensionPy(new GeometryBoolExtension); @@ -68,17 +69,20 @@ int GeometryBoolExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - char * pystr; + char* pystr; if (PyArg_ParseTuple(args, "O!s", &PyBool_Type, &val, &pystr)) { this->getGeometryBoolExtensionPtr()->setValue(Base::asBoolean(val)); this->getGeometryBoolExtensionPtr()->setName(pystr); return 0; } - PyErr_SetString(PyExc_TypeError, "GeometryBoolExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- Boolean\n" - "-- Boolean, string\n"); + PyErr_SetString( + PyExc_TypeError, + "GeometryBoolExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- Boolean\n" + "-- Boolean, string\n" + ); return -1; } @@ -92,7 +96,7 @@ void GeometryBoolExtensionPy::setValue(Py::Boolean value) this->getGeometryBoolExtensionPtr()->setValue(value); } -PyObject *GeometryBoolExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryBoolExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeometryCurve.pyi b/src/Mod/Part/App/GeometryCurve.pyi index 993c1014ae..bf68f44611 100644 --- a/src/Mod/Part/App/GeometryCurve.pyi +++ b/src/Mod/Part/App/GeometryCurve.pyi @@ -4,7 +4,6 @@ from Base.Rotation import Rotation as RotationPy from Geometry import Geometry from typing import Final, overload, List, Union, Optional, Tuple - @export( Twin="GeomCurve", TwinPointer="GeomCurve", @@ -43,11 +42,7 @@ class GeometryCurve(Geometry): @overload @constmethod def discretize( - self, - Number: int, - *, - First: Optional[float] = None, - Last: Optional[float] = None + self, Number: int, *, First: Optional[float] = None, Last: Optional[float] = None ) -> List[Vector]: """ Discretizes the curve and returns a list of points. @@ -57,11 +52,7 @@ class GeometryCurve(Geometry): @overload @constmethod def discretize( - self, - QuasiNumber: int, - *, - First: Optional[float] = None, - Last: Optional[float] = None + self, QuasiNumber: int, *, First: Optional[float] = None, Last: Optional[float] = None ) -> List[Vector]: """ Discretizes the curve and returns a list of quasi equidistant points. @@ -71,11 +62,7 @@ class GeometryCurve(Geometry): @overload @constmethod def discretize( - self, - Distance: float, - *, - First: Optional[float] = None, - Last: Optional[float] = None + self, Distance: float, *, First: Optional[float] = None, Last: Optional[float] = None ) -> List[Vector]: """ Discretizes the curve and returns a list of equidistant points with distance 'd'. @@ -85,11 +72,7 @@ class GeometryCurve(Geometry): @overload @constmethod def discretize( - self, - Deflection: float, - *, - First: Optional[float] = None, - Last: Optional[float] = None + self, Deflection: float, *, First: Optional[float] = None, Last: Optional[float] = None ) -> List[Vector]: """ Discretizes the curve and returns a list of points with a maximum deflection 'd' to the curve. @@ -99,11 +82,7 @@ class GeometryCurve(Geometry): @overload @constmethod def discretize( - self, - QuasiDeflection: float, - *, - First: Optional[float] = None, - Last: Optional[float] = None + self, QuasiDeflection: float, *, First: Optional[float] = None, Last: Optional[float] = None ) -> List[Vector]: """ Discretizes the curve and returns a list of points with a maximum deflection 'd' to the curve (faster). @@ -293,9 +272,7 @@ class GeometryCurve(Geometry): @overload @constmethod - def projectPoint( - self, Point: Vector, Method: str = "LowerDistanceParameter" - ) -> float: + def projectPoint(self, Point: Vector, Method: str = "LowerDistanceParameter") -> float: """ projectPoint(Vector, "LowerDistanceParameter") -> float. """ diff --git a/src/Mod/Part/App/GeometryCurvePyImp.cpp b/src/Mod/Part/App/GeometryCurvePyImp.cpp index c05fec255a..b3fa9ed8cf 100644 --- a/src/Mod/Part/App/GeometryCurvePyImp.cpp +++ b/src/Mod/Part/App/GeometryCurvePyImp.cpp @@ -22,37 +22,37 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -70,10 +70,11 @@ #include "TopoShapeEdgePy.h" -namespace Part { -extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); -extern const Py::Object makeTrimmedCurvePy(const Handle(Geom_Curve)& c, double f,double l); -} +namespace Part +{ +extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve) & c); +extern const Py::Object makeTrimmedCurvePy(const Handle(Geom_Curve) & c, double f, double l); +} // namespace Part using namespace Part; @@ -83,11 +84,13 @@ std::string GeometryCurvePy::representation() const return ""; } -PyObject *GeometryCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryCurvePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'GeometryCurve'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'GeometryCurve'." + ); return nullptr; } @@ -97,17 +100,18 @@ int GeometryCurvePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* GeometryCurvePy::toShape(PyObject *args) const +PyObject* GeometryCurvePy::toShape(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u,v; - u=c->FirstParameter(); - v=c->LastParameter(); - if (!PyArg_ParseTuple(args, "|dd", &u,&v)) + double u, v; + u = c->FirstParameter(); + v = c->LastParameter(); + if (!PyArg_ParseTuple(args, "|dd", &u, &v)) { return nullptr; + } BRepBuilderAPI_MakeEdge mkBuilder(c, u, v); TopoDS_Shape sh = mkBuilder.Shape(); return new TopoShapeEdgePy(new TopoShape(sh)); @@ -122,7 +126,7 @@ PyObject* GeometryCurvePy::toShape(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const +PyObject* GeometryCurvePy::discretize(PyObject* args, PyObject* kwds) const { try { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); @@ -158,16 +162,37 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const } else { // use Number kwds - static const std::array kwds_numPoints {"Number", "First", "Last", nullptr}; + static const std::array kwds_numPoints {"Number", "First", "Last", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_numPoints, &numPoints, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_numPoints, + &numPoints, + &first, + &last + )) { uniformAbscissaPoints = true; } else { // use Abscissa kwds - static const std::array kwds_Distance {"Distance", "First", "Last", nullptr}; + static const std::array kwds_Distance { + "Distance", + "First", + "Last", + nullptr + }; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Distance, &distance, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Distance, + &distance, + &first, + &last + )) { uniformAbscissaDistance = true; } } @@ -175,17 +200,19 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const if (uniformAbscissaPoints || uniformAbscissaDistance) { GCPnts_UniformAbscissa discretizer; - if (uniformAbscissaPoints) - discretizer.Initialize (adapt, numPoints, first, last); - else - discretizer.Initialize (adapt, distance, first, last); + if (uniformAbscissaPoints) { + discretizer.Initialize(adapt, numPoints, first, last); + } + else { + discretizer.Initialize(adapt, distance, first, last); + } - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = adapt.Value (discretizer.Parameter (i)); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = adapt.Value(discretizer.Parameter(i)); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -197,17 +224,25 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const } // use Deflection kwds - static const std::array kwds_Deflection {"Deflection", "First", "Last", nullptr}; + static const std::array kwds_Deflection {"Deflection", "First", "Last", nullptr}; PyErr_Clear(); double deflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Deflection, &deflection, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Deflection, + &deflection, + &first, + &last + )) { GCPnts_UniformDeflection discretizer(adapt, deflection, first, last); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -219,21 +254,30 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const } // use TangentialDeflection kwds - static const std::array kwds_TangentialDeflection{"Angular", "Curvature", "First", "Last", - "Minimum", nullptr}; + static const std::array + kwds_TangentialDeflection {"Angular", "Curvature", "First", "Last", "Minimum", nullptr}; PyErr_Clear(); double angular; double curvature; int minimumPoints = 2; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "dd|ddi", kwds_TangentialDeflection, &angular, &curvature, - &first, &last, &minimumPoints)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "dd|ddi", + kwds_TangentialDeflection, + &angular, + &curvature, + &first, + &last, + &minimumPoints + )) { GCPnts_TangentialDeflection discretizer(adapt, first, last, angular, curvature, minimumPoints); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -245,18 +289,30 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiNumber kwds - static const std::array kwds_QuasiNumPoints {"QuasiNumber", "First", "Last", nullptr}; + static const std::array kwds_QuasiNumPoints { + "QuasiNumber", + "First", + "Last", + nullptr + }; PyErr_Clear(); int quasiNumPoints; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_QuasiNumPoints, &quasiNumPoints, &first, - &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_QuasiNumPoints, + &quasiNumPoints, + &first, + &last + )) { GCPnts_QuasiUniformAbscissa discretizer(adapt, quasiNumPoints, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = adapt.Value (discretizer.Parameter (i)); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = adapt.Value(discretizer.Parameter(i)); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -268,18 +324,30 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiDeflection kwds - static const std::array kwds_QuasiDeflection {"QuasiDeflection", "First", "Last", nullptr}; + static const std::array kwds_QuasiDeflection { + "QuasiDeflection", + "First", + "Last", + nullptr + }; PyErr_Clear(); double quasiDeflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_QuasiDeflection, &quasiDeflection, &first, - &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_QuasiDeflection, + &quasiDeflection, + &first, + &last + )) { GCPnts_QuasiUniformDeflection discretizer(adapt, quasiDeflection, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -295,23 +363,24 @@ PyObject* GeometryCurvePy::discretize(PyObject *args, PyObject *kwds) const return nullptr; } - PyErr_SetString(PartExceptionOCCError,"Wrong arguments"); + PyErr_SetString(PartExceptionOCCError, "Wrong arguments"); return nullptr; } -PyObject* GeometryCurvePy::length(PyObject *args) const +PyObject* GeometryCurvePy::length(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u=c->FirstParameter(); - double v=c->LastParameter(); - double t=Precision::Confusion(); - if (!PyArg_ParseTuple(args, "|ddd", &u,&v,&t)) + double u = c->FirstParameter(); + double v = c->LastParameter(); + double t = Precision::Confusion(); + if (!PyArg_ParseTuple(args, "|ddd", &u, &v, &t)) { return nullptr; + } GeomAdaptor_Curve adapt(c); - double len = GCPnts_AbscissaPoint::Length(adapt,u,v,t); + double len = GCPnts_AbscissaPoint::Length(adapt, u, v, t); return PyFloat_FromDouble(len); } } @@ -324,7 +393,7 @@ PyObject* GeometryCurvePy::length(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::parameterAtDistance(PyObject *args) const +PyObject* GeometryCurvePy::parameterAtDistance(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); @@ -332,10 +401,11 @@ PyObject* GeometryCurvePy::parameterAtDistance(PyObject *args) const if (!c.IsNull()) { double abscissa; double u = 0; - if (!PyArg_ParseTuple(args, "d|d", &abscissa,&u)) + if (!PyArg_ParseTuple(args, "d|d", &abscissa, &u)) { return nullptr; + } GeomAdaptor_Curve adapt(c); - GCPnts_AbscissaPoint abscissaPoint(adapt,abscissa,u); + GCPnts_AbscissaPoint abscissaPoint(adapt, abscissa, u); double parm = abscissaPoint.Parameter(); return PyFloat_FromDouble(parm); } @@ -349,18 +419,19 @@ PyObject* GeometryCurvePy::parameterAtDistance(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::getD0(PyObject *args) const +PyObject* GeometryCurvePy::getD0(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Pnt p; c->D0(u, p); - return new Base::VectorPy(Base::Vector3d(p.X(),p.Y(),p.Z())); + return new Base::VectorPy(Base::Vector3d(p.X(), p.Y(), p.Z())); } } catch (Standard_Failure& e) { @@ -372,21 +443,22 @@ PyObject* GeometryCurvePy::getD0(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::getD1(PyObject *args) const +PyObject* GeometryCurvePy::getD1(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Pnt p; gp_Vec v; c->D1(u, p, v); Py::Tuple tuple(2); - tuple.setItem(0, Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); - tuple.setItem(1, Py::Vector(Base::Vector3d(v.X(),v.Y(),v.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(v.X(), v.Y(), v.Z()))); return Py::new_reference_to(tuple); } } @@ -399,22 +471,23 @@ PyObject* GeometryCurvePy::getD1(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::getD2(PyObject *args) const +PyObject* GeometryCurvePy::getD2(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Pnt p1; gp_Vec v1, v2; c->D2(u, p1, v1, v2); Py::Tuple tuple(3); - tuple.setItem(0, Py::Vector(Base::Vector3d(p1.X(),p1.Y(),p1.Z()))); - tuple.setItem(1, Py::Vector(Base::Vector3d(v1.X(),v1.Y(),v1.Z()))); - tuple.setItem(2, Py::Vector(Base::Vector3d(v2.X(),v2.Y(),v2.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(p1.X(), p1.Y(), p1.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(v1.X(), v1.Y(), v1.Z()))); + tuple.setItem(2, Py::Vector(Base::Vector3d(v2.X(), v2.Y(), v2.Z()))); return Py::new_reference_to(tuple); } } @@ -427,23 +500,24 @@ PyObject* GeometryCurvePy::getD2(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::getD3(PyObject *args) const +PyObject* GeometryCurvePy::getD3(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Pnt p1; gp_Vec v1, v2, v3; c->D3(u, p1, v1, v2, v3); Py::Tuple tuple(4); - tuple.setItem(0, Py::Vector(Base::Vector3d(p1.X(),p1.Y(),p1.Z()))); - tuple.setItem(1, Py::Vector(Base::Vector3d(v1.X(),v1.Y(),v1.Z()))); - tuple.setItem(2, Py::Vector(Base::Vector3d(v2.X(),v2.Y(),v2.Z()))); - tuple.setItem(3, Py::Vector(Base::Vector3d(v3.X(),v3.Y(),v3.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(p1.X(), p1.Y(), p1.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(v1.X(), v1.Y(), v1.Z()))); + tuple.setItem(2, Py::Vector(Base::Vector3d(v2.X(), v2.Y(), v2.Z()))); + tuple.setItem(3, Py::Vector(Base::Vector3d(v3.X(), v3.Y(), v3.Z()))); return Py::new_reference_to(tuple); } } @@ -456,7 +530,7 @@ PyObject* GeometryCurvePy::getD3(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::getDN(PyObject *args) const +PyObject* GeometryCurvePy::getDN(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); @@ -464,10 +538,11 @@ PyObject* GeometryCurvePy::getDN(PyObject *args) const if (!c.IsNull()) { int n; double u; - if (!PyArg_ParseTuple(args, "di", &u, &n)) + if (!PyArg_ParseTuple(args, "di", &u, &n)) { return nullptr; + } gp_Vec v = c->DN(u, n); - return new Base::VectorPy(Base::Vector3d(v.X(),v.Y(),v.Z())); + return new Base::VectorPy(Base::Vector3d(v.X(), v.Y(), v.Z())); } } catch (Standard_Failure& e) { @@ -479,17 +554,18 @@ PyObject* GeometryCurvePy::getDN(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::value(PyObject *args) const +PyObject* GeometryCurvePy::value(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Pnt p = c->Value(u); - return new Base::VectorPy(Base::Vector3d(p.X(),p.Y(),p.Z())); + return new Base::VectorPy(Base::Vector3d(p.X(), p.Y(), p.Z())); } } catch (Standard_Failure& e) { @@ -501,21 +577,22 @@ PyObject* GeometryCurvePy::value(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::tangent(PyObject *args) const +PyObject* GeometryCurvePy::tangent(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Dir dir; Py::Tuple tuple(1); - GeomLProp_CLProps prop(c,u,2,Precision::Confusion()); + GeomLProp_CLProps prop(c, u, 2, Precision::Confusion()); if (prop.IsTangentDefined()) { prop.Tangent(dir); - tuple.setItem(0, Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z()))); } return Py::new_reference_to(tuple); @@ -530,19 +607,20 @@ PyObject* GeometryCurvePy::tangent(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::normal(PyObject *args) const +PyObject* GeometryCurvePy::normal(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } gp_Dir dir; - GeomLProp_CLProps prop(c,u,2,Precision::Confusion()); + GeomLProp_CLProps prop(c, u, 2, Precision::Confusion()); prop.Normal(dir); - return new Base::VectorPy(new Base::Vector3d(dir.X(),dir.Y(),dir.Z())); + return new Base::VectorPy(new Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } } catch (Standard_Failure& e) { @@ -554,13 +632,12 @@ PyObject* GeometryCurvePy::normal(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::projectPoint(PyObject *args, PyObject* kwds) const +PyObject* GeometryCurvePy::projectPoint(PyObject* args, PyObject* kwds) const { - PyObject *v; - const char *meth = "NearestPoint"; - static const std::array kwlist{"Point", "Method", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|s", kwlist, - &Base::VectorPy::Type, &v, &meth)) { + PyObject* v; + const char* meth = "NearestPoint"; + static const std::array kwlist {"Point", "Method", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|s", kwlist, &Base::VectorPy::Type, &v, &meth)) { return nullptr; } @@ -589,7 +666,7 @@ PyObject* GeometryCurvePy::projectPoint(PyObject *args, PyObject* kwds) const else if (method == "Distance") { Standard_Integer num = proj.NbPoints(); Py::List list; - for (Standard_Integer i=1; i <= num; i++) { + for (Standard_Integer i = 1; i <= num; i++) { list.append(Py::Float(proj.Distance(i))); } return Py::new_reference_to(list); @@ -597,7 +674,7 @@ PyObject* GeometryCurvePy::projectPoint(PyObject *args, PyObject* kwds) const else if (method == "Parameter") { Standard_Integer num = proj.NbPoints(); Py::List list; - for (Standard_Integer i=1; i <= num; i++) { + for (Standard_Integer i = 1; i <= num; i++) { list.append(Py::Float(proj.Parameter(i))); } return Py::new_reference_to(list); @@ -605,7 +682,7 @@ PyObject* GeometryCurvePy::projectPoint(PyObject *args, PyObject* kwds) const else if (method == "Point") { Standard_Integer num = proj.NbPoints(); Py::List list; - for (Standard_Integer i=1; i <= num; i++) { + for (Standard_Integer i = 1; i <= num; i++) { gp_Pnt pnt = proj.Point(i); Base::Vector3d vec(pnt.X(), pnt.Y(), pnt.Z()); list.append(Py::Vector(vec)); @@ -623,16 +700,17 @@ PyObject* GeometryCurvePy::projectPoint(PyObject *args, PyObject* kwds) const } } -PyObject* GeometryCurvePy::curvature(PyObject *args) const +PyObject* GeometryCurvePy::curvature(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; - GeomLProp_CLProps prop(c,u,2,Precision::Confusion()); + } + GeomLProp_CLProps prop(c, u, 2, Precision::Confusion()); double C = prop.Curvature(); return Py::new_reference_to(Py::Float(C)); } @@ -646,19 +724,20 @@ PyObject* GeometryCurvePy::curvature(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::centerOfCurvature(PyObject *args) const +PyObject* GeometryCurvePy::centerOfCurvature(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { double u; - if (!PyArg_ParseTuple(args, "d", &u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; - GeomLProp_CLProps prop(c,u,2,Precision::Confusion()); - gp_Pnt V ; + } + GeomLProp_CLProps prop(c, u, 2, Precision::Confusion()); + gp_Pnt V; prop.CentreOfCurvature(V); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } } catch (Standard_Failure& e) { @@ -670,18 +749,20 @@ PyObject* GeometryCurvePy::centerOfCurvature(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::parameter(PyObject *args) const +PyObject* GeometryCurvePy::parameter(PyObject* args) const { try { - PyObject *p; - if (!PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &p)) + PyObject* p; + if (!PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &p)) { return nullptr; + } Base::Vector3d v = Py::Vector(p, false).toVector(); double u; - if (static_cast(getGeometryPtr())->closestParameter(v,u)) + if (static_cast(getGeometryPtr())->closestParameter(v, u)) { return Py::new_reference_to(Py::Float(u)); + } } catch (Base::CADKernelError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); @@ -692,35 +773,39 @@ PyObject* GeometryCurvePy::parameter(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::makeRuledSurface(PyObject *args) const +PyObject* GeometryCurvePy::makeRuledSurface(PyObject* args) const { PyObject* curve; - if (!PyArg_ParseTuple(args, "O!", &(Part::GeometryCurvePy::Type), &curve)) + if (!PyArg_ParseTuple(args, "O!", &(Part::GeometryCurvePy::Type), &curve)) { return nullptr; + } try { Handle(Geom_Curve) aCrv1 = Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle()); GeometryCurvePy* c = static_cast(curve); Handle(Geom_Curve) aCrv2 = Handle(Geom_Curve)::DownCast(c->getGeometryPtr()->handle()); - Handle(Geom_Surface) aSurf = GeomFill::Surface (aCrv1, aCrv2); + Handle(Geom_Surface) aSurf = GeomFill::Surface(aCrv1, aCrv2); if (aSurf.IsNull()) { PyErr_SetString(PartExceptionOCCError, "Failed to create ruled surface"); return nullptr; } // check the result surface type if (aSurf->IsKind(STANDARD_TYPE(Geom_RectangularTrimmedSurface))) { - Handle(Geom_RectangularTrimmedSurface) aTSurf = - Handle(Geom_RectangularTrimmedSurface)::DownCast(aSurf); + Handle(Geom_RectangularTrimmedSurface) aTSurf = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(aSurf); return new RectangularTrimmedSurfacePy(new GeomTrimmedSurface(aTSurf)); } else if (aSurf->IsKind(STANDARD_TYPE(Geom_BSplineSurface))) { - Handle(Geom_BSplineSurface) aBSurf = - Handle(Geom_BSplineSurface)::DownCast(aSurf); + Handle(Geom_BSplineSurface) aBSurf = Handle(Geom_BSplineSurface)::DownCast(aSurf); return new BSplineSurfacePy(new GeomBSplineSurface(aBSurf)); } else { - PyErr_Format(PyExc_NotImplementedError, "Ruled surface is of type '%s'", - aSurf->DynamicType()->Name()); + PyErr_Format( + PyExc_NotImplementedError, + "Ruled surface is of type '%s'", + aSurf->DynamicType()->Name() + ); return nullptr; } } @@ -730,26 +815,28 @@ PyObject* GeometryCurvePy::makeRuledSurface(PyObject *args) const } } -PyObject* GeometryCurvePy::intersect2d(PyObject *args) const +PyObject* GeometryCurvePy::intersect2d(PyObject* args) const { - PyObject *c,*p; - if (!PyArg_ParseTuple(args, "O!O!", &(Part::GeometryCurvePy::Type), &c, - &(Part::PlanePy::Type), &p)) + PyObject *c, *p; + if (!PyArg_ParseTuple(args, "O!O!", &(Part::GeometryCurvePy::Type), &c, &(Part::PlanePy::Type), &p)) { return nullptr; + } try { Handle(Geom_Curve) self = Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle()); - Handle(Geom_Curve) curv = Handle(Geom_Curve)::DownCast(static_cast(c)-> - getGeometryPtr()->handle()); - Handle(Geom_Plane) plane = Handle(Geom_Plane)::DownCast(static_cast(p)-> - getGeometryPtr()->handle()); + Handle(Geom_Curve) curv = Handle(Geom_Curve)::DownCast( + static_cast(c)->getGeometryPtr()->handle() + ); + Handle(Geom_Plane) plane = Handle(Geom_Plane)::DownCast( + static_cast(p)->getGeometryPtr()->handle() + ); Handle(Geom2d_Curve) curv1 = GeomAPI::To2d(self, plane->Pln()); Handle(Geom2d_Curve) curv2 = GeomAPI::To2d(curv, plane->Pln()); Geom2dAPI_InterCurveCurve intCC(curv1, curv2); int nbPoints = intCC.NbPoints(); Py::List list; - for (int i=1; i<= nbPoints; i++) { + for (int i = 1; i <= nbPoints; i++) { gp_Pnt2d pt = intCC.Point(i); Py::Tuple tuple(2); tuple.setItem(0, Py::Float(pt.X())); @@ -759,7 +846,7 @@ PyObject* GeometryCurvePy::intersect2d(PyObject *args) const if (intCC.NbSegments() > 0) { // See also Curve2dPy::intersectCC() that uses Geom2dAPI_ExtremaCurveCurve const Geom2dInt_GInter& gInter = intCC.Intersector(); - for (int i=1; i <= gInter.NbSegments(); i++) { + for (int i = 1; i <= gInter.NbSegments(); i++) { const IntRes2d_IntersectionSegment& segm = gInter.Segment(i); if (segm.HasFirstPoint()) { const IntRes2d_IntersectionPoint& fp = segm.FirstPoint(); @@ -779,17 +866,18 @@ PyObject* GeometryCurvePy::intersect2d(PyObject *args) const } } -PyObject* GeometryCurvePy::toBSpline(PyObject * args) const +PyObject* GeometryCurvePy::toBSpline(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u,v; - u=c->FirstParameter(); - v=c->LastParameter(); - if (!PyArg_ParseTuple(args, "|dd", &u,&v)) + double u, v; + u = c->FirstParameter(); + v = c->LastParameter(); + if (!PyArg_ParseTuple(args, "|dd", &u, &v)) { return nullptr; + } GeomBSplineCurve* spline = getGeomCurvePtr()->toBSpline(u, v); return new BSplineCurvePy(spline); } @@ -803,17 +891,18 @@ PyObject* GeometryCurvePy::toBSpline(PyObject * args) const return nullptr; } -PyObject* GeometryCurvePy::toNurbs(PyObject * args) const +PyObject* GeometryCurvePy::toNurbs(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u,v; - u=c->FirstParameter(); - v=c->LastParameter(); - if (!PyArg_ParseTuple(args, "|dd", &u,&v)) + double u, v; + u = c->FirstParameter(); + v = c->LastParameter(); + if (!PyArg_ParseTuple(args, "|dd", &u, &v)) { return nullptr; + } GeomBSplineCurve* spline = getGeomCurvePtr()->toNurbs(u, v); return new BSplineCurvePy(spline); } @@ -827,18 +916,19 @@ PyObject* GeometryCurvePy::toNurbs(PyObject * args) const return nullptr; } -PyObject* GeometryCurvePy::trim(PyObject * args) const +PyObject* GeometryCurvePy::trim(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); try { if (!c.IsNull()) { - double u,v; - u=c->FirstParameter(); - v=c->LastParameter(); - if (!PyArg_ParseTuple(args, "|dd", &u,&v)) + double u, v; + u = c->FirstParameter(); + v = c->LastParameter(); + if (!PyArg_ParseTuple(args, "|dd", &u, &v)) { return nullptr; - return Py::new_reference_to(makeTrimmedCurvePy(c,u,v)); + } + return Py::new_reference_to(makeTrimmedCurvePy(c, u, v)); } } catch (Standard_Failure& e) { @@ -850,32 +940,41 @@ PyObject* GeometryCurvePy::trim(PyObject * args) const return nullptr; } -PyObject* GeometryCurvePy::approximateBSpline(PyObject *args) const +PyObject* GeometryCurvePy::approximateBSpline(PyObject* args) const { double tolerance; int maxSegment, maxDegree; const char* order = "C2"; - if (!PyArg_ParseTuple(args, "dii|s", &tolerance, &maxSegment, &maxDegree, &order)) + if (!PyArg_ParseTuple(args, "dii|s", &tolerance, &maxSegment, &maxDegree, &order)) { return nullptr; + } GeomAbs_Shape absShape; std::string str = order; - if (str == "C0") + if (str == "C0") { absShape = GeomAbs_C0; - else if (str == "G1") + } + else if (str == "G1") { absShape = GeomAbs_G1; - else if (str == "C1") + } + else if (str == "C1") { absShape = GeomAbs_C1; - else if (str == "G2") + } + else if (str == "G2") { absShape = GeomAbs_G2; - else if (str == "C2") + } + else if (str == "C2") { absShape = GeomAbs_C2; - else if (str == "C3") + } + else if (str == "C3") { absShape = GeomAbs_C3; - else if (str == "CN") + } + else if (str == "CN") { absShape = GeomAbs_CN; - else + } + else { absShape = GeomAbs_C2; + } try { Handle(Geom_Curve) self = Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle()); @@ -900,20 +999,29 @@ PyObject* GeometryCurvePy::approximateBSpline(PyObject *args) const } } -PyObject* GeometryCurvePy::continuityWith(PyObject *args) const +PyObject* GeometryCurvePy::continuityWith(PyObject* args) const { double u1 = -1.0, u2 = -1.0; double tl = -1.0, ta = -1.0; PyObject* curve; PyObject* rev1 = Py_False; PyObject* rev2 = Py_False; - if (!PyArg_ParseTuple(args, "O!|ddO!O!dd", - &GeometryCurvePy::Type, &curve, - &u1, &u2, - &PyBool_Type, &rev1, - &PyBool_Type, &rev2, - &tl, &ta)) + if (!PyArg_ParseTuple( + args, + "O!|ddO!O!dd", + &GeometryCurvePy::Type, + &curve, + &u1, + &u2, + &PyBool_Type, + &rev1, + &PyBool_Type, + &rev2, + &tl, + &ta + )) { return nullptr; + } Handle(Geom_Geometry) g1 = getGeometryPtr()->handle(); Handle(Geom_Curve) c1 = Handle(Geom_Curve)::DownCast(g1); @@ -921,12 +1029,14 @@ PyObject* GeometryCurvePy::continuityWith(PyObject *args) const Handle(Geom_Curve) c2 = Handle(Geom_Curve)::DownCast(g2); // if no parameter value is given then by default use the end of the parameter range - if (u1 < 0.0) + if (u1 < 0.0) { u1 = c1->LastParameter(); + } // if no parameter value is given then by default use the start of the parameter range - if (u2 < 0.0) + if (u2 < 0.0) { u2 = c2->FirstParameter(); + } Standard_Boolean r1 = Base::asBoolean(rev1); Standard_Boolean r2 = Base::asBoolean(rev2); @@ -934,37 +1044,39 @@ PyObject* GeometryCurvePy::continuityWith(PyObject *args) const try { if (!c1.IsNull() && !c2.IsNull()) { GeomAbs_Shape c; - if (tl >= 0.0 && ta >= 0.0) + if (tl >= 0.0 && ta >= 0.0) { c = GeomLProp::Continuity(c1, c2, u1, u2, r1, r2, tl, ta); - else + } + else { c = GeomLProp::Continuity(c1, c2, u1, u2, r1, r2); + } std::string str; switch (c) { - case GeomAbs_C0: - str = "C0"; - break; - case GeomAbs_G1: - str = "G1"; - break; - case GeomAbs_C1: - str = "C1"; - break; - case GeomAbs_G2: - str = "G2"; - break; - case GeomAbs_C2: - str = "C2"; - break; - case GeomAbs_C3: - str = "C3"; - break; - case GeomAbs_CN: - str = "CN"; - break; - default: - str = "Unknown"; - break; + case GeomAbs_C0: + str = "C0"; + break; + case GeomAbs_G1: + str = "G1"; + break; + case GeomAbs_C1: + str = "C1"; + break; + case GeomAbs_G2: + str = "G2"; + break; + case GeomAbs_C2: + str = "C2"; + break; + case GeomAbs_C3: + str = "C3"; + break; + case GeomAbs_CN: + str = "CN"; + break; + default: + str = "Unknown"; + break; } return Py_BuildValue("s", str.c_str()); } @@ -980,51 +1092,48 @@ PyObject* GeometryCurvePy::continuityWith(PyObject *args) const Py::String GeometryCurvePy::getContinuity() const { - GeomAbs_Shape c = Handle(Geom_Curve)::DownCast - (getGeometryPtr()->handle())->Continuity(); + GeomAbs_Shape c = Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle())->Continuity(); std::string str; switch (c) { - case GeomAbs_C0: - str = "C0"; - break; - case GeomAbs_G1: - str = "G1"; - break; - case GeomAbs_C1: - str = "C1"; - break; - case GeomAbs_G2: - str = "G2"; - break; - case GeomAbs_C2: - str = "C2"; - break; - case GeomAbs_C3: - str = "C3"; - break; - case GeomAbs_CN: - str = "CN"; - break; - default: - str = "Unknown"; - break; + case GeomAbs_C0: + str = "C0"; + break; + case GeomAbs_G1: + str = "G1"; + break; + case GeomAbs_C1: + str = "C1"; + break; + case GeomAbs_G2: + str = "G2"; + break; + case GeomAbs_C2: + str = "C2"; + break; + case GeomAbs_C3: + str = "C3"; + break; + case GeomAbs_CN: + str = "CN"; + break; + default: + str = "Unknown"; + break; } return Py::String(str); } Py::Float GeometryCurvePy::getFirstParameter() const { - return Py::Float(Handle(Geom_Curve)::DownCast - (getGeometryPtr()->handle())->FirstParameter()); + return Py::Float(Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle())->FirstParameter()); } Py::Float GeometryCurvePy::getLastParameter() const { - return Py::Float(Handle(Geom_Curve)::DownCast - (getGeometryPtr()->handle())->LastParameter()); + return Py::Float(Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle())->LastParameter()); } -PyObject *GeometryCurvePy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryCurvePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -1036,16 +1145,19 @@ int GeometryCurvePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/ // Specialized intersection functions -PyObject* GeometryCurvePy::intersectCS(PyObject *args) const +PyObject* GeometryCurvePy::intersectCS(PyObject* args) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle()); try { if (!curve.IsNull()) { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) + if (!PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) { return nullptr; - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(p)->getGeometryPtr()->handle()); + } + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(p)->getGeometryPtr()->handle() + ); GeomAPI_IntCS intersector(curve, surf); if (!intersector.IsDone()) { PyErr_SetString(PyExc_RuntimeError, "Intersection of curve and surface failed"); @@ -1055,7 +1167,9 @@ PyObject* GeometryCurvePy::intersectCS(PyObject *args) const Py::List points; for (int i = 1; i <= intersector.NbPoints(); i++) { gp_Pnt p = intersector.Point(i); - points.append(Py::asObject(new PointPy(new GeomPoint(Base::Vector3d(p.X(), p.Y(), p.Z()))))); + points.append( + Py::asObject(new PointPy(new GeomPoint(Base::Vector3d(p.X(), p.Y(), p.Z())))) + ); } Py::List segments; for (int i = 1; i <= intersector.NbSegments(); i++) { @@ -1078,25 +1192,26 @@ PyObject* GeometryCurvePy::intersectCS(PyObject *args) const return nullptr; } -PyObject* GeometryCurvePy::intersectCC(PyObject *args) const +PyObject* GeometryCurvePy::intersectCC(PyObject* args) const { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d", &(Part::GeometryCurvePy::Type), &p, &prec)) + if (!PyArg_ParseTuple(args, "O!|d", &(Part::GeometryCurvePy::Type), &p, &prec)) { return nullptr; + } GeomCurve* curve1 = getGeomCurvePtr(); GeomCurve* curve2 = static_cast(p)->getGeomCurvePtr(); try { - std::vector > pairs; + std::vector> pairs; if (!curve1->intersect(curve2, pairs, prec)) { // No intersection return Py::new_reference_to(Py::List()); } Py::List points; - for (const auto & pair : pairs) { + for (const auto& pair : pairs) { points.append(Py::asObject(new PointPy(new GeomPoint(pair.first)))); } @@ -1110,23 +1225,28 @@ PyObject* GeometryCurvePy::intersectCC(PyObject *args) const // General intersection function -PyObject* GeometryCurvePy::intersect(PyObject *args) const +PyObject* GeometryCurvePy::intersect(PyObject* args) const { Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(getGeometryPtr()->handle()); try { if (!curve.IsNull()) { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); try { - if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometryCurvePy::Type), &p, &prec)) + if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometryCurvePy::Type), &p, &prec)) { return intersectCC(args); - } catch(...) {} + } + } + catch (...) { + } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) + if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) { return intersectCS(args); - else + } + else { return nullptr; + } } } catch (Standard_Failure& e) { @@ -1141,18 +1261,20 @@ PyObject* GeometryCurvePy::intersect(PyObject *args) const Py::Object GeometryCurvePy::getRotation() const { Handle(Geom_Conic) s = Handle(Geom_Conic)::DownCast(getGeometryPtr()->handle()); - if(!s) + if (!s) { return Py::Object(); + } gp_Trsf trsf; - trsf.SetTransformation(s->Position(),gp_Ax3()); + trsf.SetTransformation(s->Position(), gp_Ax3()); auto q = trsf.GetRotation(); - return Py::Rotation(Base::Rotation(q.X(),q.Y(),q.Z(),q.W())); + return Py::Rotation(Base::Rotation(q.X(), q.Y(), q.Z(), q.W())); } -PyObject* GeometryCurvePy::reverse(PyObject *args) +PyObject* GeometryCurvePy::reverse(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); @@ -1165,11 +1287,12 @@ PyObject* GeometryCurvePy::reverse(PyObject *args) Py_Return; } -PyObject* GeometryCurvePy::reversedParameter(PyObject *args) const +PyObject* GeometryCurvePy::reversedParameter(PyObject* args) const { double p; - if (!PyArg_ParseTuple(args, "d", &p)) + if (!PyArg_ParseTuple(args, "d", &p)) { return nullptr; + } try { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); @@ -1182,10 +1305,11 @@ PyObject* GeometryCurvePy::reversedParameter(PyObject *args) const } } -PyObject* GeometryCurvePy::isPeriodic(PyObject *args) const +PyObject* GeometryCurvePy::isPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); @@ -1198,10 +1322,11 @@ PyObject* GeometryCurvePy::isPeriodic(PyObject *args) const } } -PyObject* GeometryCurvePy::period(PyObject *args) const +PyObject* GeometryCurvePy::period(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); @@ -1214,10 +1339,11 @@ PyObject* GeometryCurvePy::period(PyObject *args) const } } -PyObject* GeometryCurvePy::isClosed(PyObject *args) const +PyObject* GeometryCurvePy::isClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(g); diff --git a/src/Mod/Part/App/GeometryDefaultExtension.cpp b/src/Mod/Part/App/GeometryDefaultExtension.cpp index 83cac30712..1b4a363620 100644 --- a/src/Mod/Part/App/GeometryDefaultExtension.cpp +++ b/src/Mod/Part/App/GeometryDefaultExtension.cpp @@ -36,37 +36,38 @@ using namespace Part; //---------- Geometry Extension -template -GeometryDefaultExtension::GeometryDefaultExtension(const T& val, std::string name):value(val) +template +GeometryDefaultExtension::GeometryDefaultExtension(const T& val, std::string name) + : value(val) { setName(name); } -template -void GeometryDefaultExtension::copyAttributes(Part::GeometryExtension * cpy) const +template +void GeometryDefaultExtension::copyAttributes(Part::GeometryExtension* cpy) const { Part::GeometryPersistenceExtension::copyAttributes(cpy); - static_cast *>(cpy)->value = this->value; + static_cast*>(cpy)->value = this->value; } -template -void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) +template +void GeometryDefaultExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); value = reader.getAttribute("value"); } -template -void GeometryDefaultExtension::saveAttributes(Base::Writer &writer) const +template +void GeometryDefaultExtension::saveAttributes(Base::Writer& writer) const { Part::GeometryPersistenceExtension::saveAttributes(writer); writer.Stream() << "\" value=\"" << value; } -template +template std::unique_ptr GeometryDefaultExtension::copy() const { std::unique_ptr> cpy = std::make_unique>(); @@ -75,29 +76,35 @@ std::unique_ptr GeometryDefaultExtension::copy() con return cpy; } -template -PyObject * GeometryDefaultExtension::getPyObject() +template +PyObject* GeometryDefaultExtension::getPyObject() { - THROWM(Base::NotImplementedError,"Python object not implemented for default geometry extension template type. Template Specialisation missing."); // use template specialisation to provide the actual object + THROWM( + Base::NotImplementedError, + "Python object not implemented for default geometry extension template type. Template " + "Specialisation missing." + ); // use template specialisation to provide the actual object } -namespace Part { -// ----------------------------- Template specialisations---------------------------------------------------- +namespace Part +{ +// ----------------------------- Template +// specialisations---------------------------------------------------- -//using GeometryIntExtension = Part::GeometryDefaultExtension; -//using GeometryStringExtension = Part::GeometryStringExtension; +// using GeometryIntExtension = Part::GeometryDefaultExtension; +// using GeometryStringExtension = Part::GeometryStringExtension; // ---------- GeometryIntExtension ---------- -TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryIntExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryIntExtension, Part::GeometryPersistenceExtension) -template <> -PyObject * GeometryDefaultExtension::getPyObject() +template<> +PyObject* GeometryDefaultExtension::getPyObject() { return new GeometryIntExtensionPy(new GeometryIntExtension(*this)); } -template <> -void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) +template<> +void GeometryDefaultExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); @@ -105,25 +112,25 @@ void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) } // ---------- GeometryStringExtension ---------- -TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryStringExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryStringExtension, Part::GeometryPersistenceExtension) -template <> -PyObject * GeometryDefaultExtension::getPyObject() +template<> +PyObject* GeometryDefaultExtension::getPyObject() { return new GeometryStringExtensionPy(new GeometryStringExtension(*this)); } // ---------- GeometryBoolExtension ---------- -TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryBoolExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryBoolExtension, Part::GeometryPersistenceExtension) -template <> -PyObject * GeometryDefaultExtension::getPyObject() +template<> +PyObject* GeometryDefaultExtension::getPyObject() { return new GeometryBoolExtensionPy(new GeometryBoolExtension(*this)); } -template <> -void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) +template<> +void GeometryDefaultExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); @@ -131,16 +138,16 @@ void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) } // ---------- GeometryDoubleExtension ---------- -TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryDoubleExtension,Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryDoubleExtension, Part::GeometryPersistenceExtension) -template <> -PyObject * GeometryDefaultExtension::getPyObject() +template<> +PyObject* GeometryDefaultExtension::getPyObject() { return new GeometryDoubleExtensionPy(new GeometryDoubleExtension(*this)); } -template <> -void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) +template<> +void GeometryDefaultExtension::restoreAttributes(Base::XMLReader& reader) { Part::GeometryPersistenceExtension::restoreAttributes(reader); @@ -149,11 +156,11 @@ void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader // instantiate the types so that other translation units (python wrappers) can access template -//constructors other than the default. +// constructors other than the default. template class GeometryDefaultExtension; template class GeometryDefaultExtension; template class GeometryDefaultExtension; template class GeometryDefaultExtension; -} //namespace Part +} // namespace Part diff --git a/src/Mod/Part/App/GeometryDefaultExtension.h b/src/Mod/Part/App/GeometryDefaultExtension.h index 2ba8246e0f..11d4280565 100644 --- a/src/Mod/Part/App/GeometryDefaultExtension.h +++ b/src/Mod/Part/App/GeometryDefaultExtension.h @@ -31,90 +31,114 @@ #include -namespace Part { +namespace Part +{ - template - class PartExport GeometryDefaultExtension: public Part::GeometryPersistenceExtension +template +class PartExport GeometryDefaultExtension: public Part::GeometryPersistenceExtension +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + inline GeometryDefaultExtension(); + explicit GeometryDefaultExtension(const T& val, std::string name = std::string()); + ~GeometryDefaultExtension() override = default; + + inline void setValue(const T& val) { - TYPESYSTEM_HEADER_WITH_OVERRIDE(); - public: - inline GeometryDefaultExtension(); - explicit GeometryDefaultExtension(const T& val, std::string name = std::string()); - ~GeometryDefaultExtension() override = default; - - inline void setValue(const T& val) {value = val;}; - inline const T &getValue() const {return value;}; - - std::unique_ptr copy() const override; - - PyObject *getPyObject() override; - - protected: - void copyAttributes(Part::GeometryExtension * cpy) const override; - void restoreAttributes(Base::XMLReader &reader) override; - void saveAttributes(Base::Writer &writer) const override; - - private: - GeometryDefaultExtension(const GeometryDefaultExtension&) = default; - - private: - T value; + value = val; + }; + inline const T& getValue() const + { + return value; }; - // Description: - // - // This template allows one to define a geometry extension for a given type (uniform interface for one value of type T). - // - // Warnings: - // - The default constructor relies on the default constructor of T for initialisation. Built-in types - // so constructed will be uninitialised. Use the specific constructor from a T to initialise it. Note - // that the default constructor is required by the type system (see TYPESYSTEM_SOURCE_TEMPLATE_T). - // - // Default assumptions: - // - T can be constructed from T - // - T can be assigned to T - // - T is convertible to a std::string - // - T is serialisable as a string - // - // template specialisation: - // - // If the assumptions do not meet for your type, template specialisation allows you to provide specific code, - // look for examples (int/string) in GeometryDefaultExtensions.cpp - // - // Instructions: - // - // 1. Read the assumptions above and provide template initialisation if needed. - // 2. Add an alias to your type under these comments - // 3. Add a TYPESYSTEM_SOURCE_TEMPLATE_T in the cpp file to generate class type information - // 4. Provide a specialisation of getPyObject to generate a py object of the corresponding type (cpp file) - // 5. Provide specialisations if your type does not meet the assumptions above (e.g. for serialisation) (cpp file) - // 6. Register your type and corresponding python type in AppPart.cpp + std::unique_ptr copy() const override; - template - Base::Type GeometryDefaultExtension::classTypeId{Base::Type::BadType}; + PyObject* getPyObject() override; - // Must be explicitly declared here - template<> void * GeometryDefaultExtension::create(); - template<> void * GeometryDefaultExtension::create(); - template<> void * GeometryDefaultExtension::create(); - template<> void * GeometryDefaultExtension::create(); +protected: + void copyAttributes(Part::GeometryExtension* cpy) const override; + void restoreAttributes(Base::XMLReader& reader) override; + void saveAttributes(Base::Writer& writer) const override; - template - inline GeometryDefaultExtension::GeometryDefaultExtension():value{}{} +private: + GeometryDefaultExtension(const GeometryDefaultExtension&) = default; - // Specialised constructors go here so that specialisation is before the template instantiation - // Specialised default constructors are inline, because a full specialisation otherwise shall go in the cpp file, but there it would be after the template instantiation. - template <> - inline GeometryDefaultExtension::GeometryDefaultExtension():value(0){} +private: + T value; +}; - template <> - inline GeometryDefaultExtension::GeometryDefaultExtension():value(0.0f){} +// Description: +// +// This template allows one to define a geometry extension for a given type (uniform interface for +// one value of type T). +// +// Warnings: +// - The default constructor relies on the default constructor of T for initialisation. Built-in +// types +// so constructed will be uninitialised. Use the specific constructor from a T to initialise it. +// Note that the default constructor is required by the type system (see +// TYPESYSTEM_SOURCE_TEMPLATE_T). +// +// Default assumptions: +// - T can be constructed from T +// - T can be assigned to T +// - T is convertible to a std::string +// - T is serialisable as a string +// +// template specialisation: +// +// If the assumptions do not meet for your type, template specialisation allows you to provide +// specific code, look for examples (int/string) in GeometryDefaultExtensions.cpp +// +// Instructions: +// +// 1. Read the assumptions above and provide template initialisation if needed. +// 2. Add an alias to your type under these comments +// 3. Add a TYPESYSTEM_SOURCE_TEMPLATE_T in the cpp file to generate class type information +// 4. Provide a specialisation of getPyObject to generate a py object of the corresponding type (cpp +// file) +// 5. Provide specialisations if your type does not meet the assumptions above (e.g. for +// serialisation) (cpp file) +// 6. Register your type and corresponding python type in AppPart.cpp - // Prefer alias to typedef item 9 - using GeometryIntExtension = GeometryDefaultExtension; - using GeometryStringExtension = GeometryDefaultExtension; - using GeometryBoolExtension = GeometryDefaultExtension; - using GeometryDoubleExtension = GeometryDefaultExtension; -} +template +Base::Type GeometryDefaultExtension::classTypeId {Base::Type::BadType}; -#endif // PART_GEOMETRYDEFAULTEXTENSION_H +// Must be explicitly declared here +template<> +void* GeometryDefaultExtension::create(); +template<> +void* GeometryDefaultExtension::create(); +template<> +void* GeometryDefaultExtension::create(); +template<> +void* GeometryDefaultExtension::create(); + +template +inline GeometryDefaultExtension::GeometryDefaultExtension() + : value {} +{} + +// Specialised constructors go here so that specialisation is before the template instantiation +// Specialised default constructors are inline, because a full specialisation otherwise shall go in +// the cpp file, but there it would be after the template instantiation. +template<> +inline GeometryDefaultExtension::GeometryDefaultExtension() + : value(0) +{} + +template<> +inline GeometryDefaultExtension::GeometryDefaultExtension() + : value(0.0f) +{} + +// Prefer alias to typedef item 9 +using GeometryIntExtension = GeometryDefaultExtension; +using GeometryStringExtension = GeometryDefaultExtension; +using GeometryBoolExtension = GeometryDefaultExtension; +using GeometryDoubleExtension = GeometryDefaultExtension; +} // namespace Part + +#endif // PART_GEOMETRYDEFAULTEXTENSION_H diff --git a/src/Mod/Part/App/GeometryDoubleExtension.pyi b/src/Mod/Part/App/GeometryDoubleExtension.pyi index 64a63673f4..e91ba72224 100644 --- a/src/Mod/Part/App/GeometryDoubleExtension.pyi +++ b/src/Mod/Part/App/GeometryDoubleExtension.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from GeometryExtension import GeometryExtension - @export( PythonName="Part.GeometryDoubleExtension", Include="Mod/Part/App/GeometryDefaultExtension.h", diff --git a/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp b/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp index 29e758669f..e44a044770 100644 --- a/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp @@ -23,7 +23,6 @@ ***************************************************************************/ - #include "GeometryDefaultExtension.h" #include "GeometryDoubleExtensionPy.h" @@ -36,10 +35,11 @@ std::string GeometryDoubleExtensionPy::representation() const { std::stringstream str; double val = getGeometryDoubleExtensionPtr()->getValue(); - str << "getName().empty()) + if (!getGeometryDoubleExtensionPtr()->getName().empty()) { str << "\'" << getGeometryDoubleExtensionPtr()->getName() << "\', "; + } str << val << ") >"; @@ -47,7 +47,7 @@ std::string GeometryDoubleExtensionPy::representation() const return str.str(); } -PyObject *GeometryDoubleExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryDoubleExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of the python object and the Twin object return new GeometryDoubleExtensionPy(new GeometryDoubleExtension); @@ -70,17 +70,20 @@ int GeometryDoubleExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - char * pystr; - if (PyArg_ParseTuple(args, "ds", &val,&pystr)) { + char* pystr; + if (PyArg_ParseTuple(args, "ds", &val, &pystr)) { this->getGeometryDoubleExtensionPtr()->setValue(val); this->getGeometryDoubleExtensionPtr()->setName(pystr); return 0; } - PyErr_SetString(PyExc_TypeError, "GeometryDoubleExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- double\n" - "-- double, string\n"); + PyErr_SetString( + PyExc_TypeError, + "GeometryDoubleExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- double\n" + "-- double, string\n" + ); return -1; } @@ -95,8 +98,7 @@ void GeometryDoubleExtensionPy::setValue(Py::Float value) } - -PyObject *GeometryDoubleExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryDoubleExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeometryExtension.cpp b/src/Mod/Part/App/GeometryExtension.cpp index fe27e1747b..1d36c6c900 100644 --- a/src/Mod/Part/App/GeometryExtension.cpp +++ b/src/Mod/Part/App/GeometryExtension.cpp @@ -32,7 +32,7 @@ using namespace Part; -TYPESYSTEM_SOURCE_ABSTRACT(Part::GeometryExtension,Base::BaseClass) +TYPESYSTEM_SOURCE_ABSTRACT(Part::GeometryExtension, Base::BaseClass) GeometryExtension::GeometryExtension() = default; @@ -40,33 +40,33 @@ PyObject* GeometryExtension::copyPyObject() const { Py::Tuple tuple; Py::Object obj = Py::asObject(const_cast(this)->getPyObject()); - return static_cast(obj.ptr())->copy(tuple.ptr()); + return static_cast(obj.ptr())->copy(tuple.ptr()); } -void GeometryExtension::copyAttributes(Part::GeometryExtension * cpy) const +void GeometryExtension::copyAttributes(Part::GeometryExtension* cpy) const { - cpy->setName(this->getName()); // Base Class + cpy->setName(this->getName()); // Base Class } -TYPESYSTEM_SOURCE_ABSTRACT(Part::GeometryPersistenceExtension,Part::GeometryExtension) +TYPESYSTEM_SOURCE_ABSTRACT(Part::GeometryPersistenceExtension, Part::GeometryExtension) -void GeometryPersistenceExtension::restoreAttributes(Base::XMLReader &reader) +void GeometryPersistenceExtension::restoreAttributes(Base::XMLReader& reader) { - if(reader.hasAttribute("name")) { + if (reader.hasAttribute("name")) { std::string name = reader.getAttribute("name"); setName(name); } } -void GeometryPersistenceExtension::saveAttributes(Base::Writer &writer) const +void GeometryPersistenceExtension::saveAttributes(Base::Writer& writer) const { const std::string name = getName(); - if(!name.empty()) + if (!name.empty()) { writer.Stream() << "\" name=\"" << name; - + } } -void GeometryPersistenceExtension::Save(Base::Writer &writer) const +void GeometryPersistenceExtension::Save(Base::Writer& writer) const { writer.Stream() << writer.ind() << "getTypeId().getName(); @@ -75,18 +75,17 @@ void GeometryPersistenceExtension::Save(Base::Writer &writer) const writer.Stream() << "\"/>" << std::endl; } -void GeometryPersistenceExtension::Restore(Base::XMLReader &reader) +void GeometryPersistenceExtension::Restore(Base::XMLReader& reader) { restoreAttributes(reader); } -bool GeometryPersistenceExtension::isSame(const GeometryPersistenceExtension &other) const +bool GeometryPersistenceExtension::isSame(const GeometryPersistenceExtension& other) const { - static Base::StringWriter writer,writer2; -// writer.clear(); + static Base::StringWriter writer, writer2; + // writer.clear(); Save(writer); -// writer2.clear(); + // writer2.clear(); other.Save(writer2); return writer.getString() == writer2.getString(); } - diff --git a/src/Mod/Part/App/GeometryExtension.h b/src/Mod/Part/App/GeometryExtension.h index aaf92e7f07..066a0caee9 100644 --- a/src/Mod/Part/App/GeometryExtension.h +++ b/src/Mod/Part/App/GeometryExtension.h @@ -32,59 +32,67 @@ #include -namespace Part { +namespace Part +{ class Geometry; class PartExport GeometryExtension: public Base::BaseClass { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: ~GeometryExtension() override = default; virtual std::unique_ptr copy() const = 0; - PyObject *getPyObject() override = 0; + PyObject* getPyObject() override = 0; PyObject* copyPyObject() const; - inline void setName(const std::string& str) {name = str;} - inline const std::string &getName () const {return name;} + inline void setName(const std::string& str) + { + name = str; + } + inline const std::string& getName() const + { + return name; + } // Default method to notify an extension that it has been attached // to a given geometry - virtual void notifyAttachment(Part::Geometry *) {} + virtual void notifyAttachment(Part::Geometry*) + {} protected: GeometryExtension(); - GeometryExtension(const GeometryExtension &obj) = default; - GeometryExtension& operator= (const GeometryExtension &obj) = default; + GeometryExtension(const GeometryExtension& obj) = default; + GeometryExtension& operator=(const GeometryExtension& obj) = default; - virtual void copyAttributes(Part::GeometryExtension * cpy) const; + virtual void copyAttributes(Part::GeometryExtension* cpy) const; private: std::string name; }; - -class PartExport GeometryPersistenceExtension : public Part::GeometryExtension +class PartExport GeometryPersistenceExtension: public Part::GeometryExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: ~GeometryPersistenceExtension() override = default; // Own Persistence implementer - Not Base::Persistence - managed by Part::Geometry - void Save(Base::Writer &/*writer*/) const; - void Restore(Base::XMLReader &/*reader*/); + void Save(Base::Writer& /*writer*/) const; + void Restore(Base::XMLReader& /*reader*/); - bool isSame(const GeometryPersistenceExtension &other) const; + bool isSame(const GeometryPersistenceExtension& other) const; protected: - virtual void restoreAttributes(Base::XMLReader &/*reader*/); - virtual void saveAttributes(Base::Writer &writer) const; - + virtual void restoreAttributes(Base::XMLReader& /*reader*/); + virtual void saveAttributes(Base::Writer& writer) const; }; -} +} // namespace Part -#endif // PART_GEOMETRYEXTENSION_H +#endif // PART_GEOMETRYEXTENSION_H diff --git a/src/Mod/Part/App/GeometryExtension.pyi b/src/Mod/Part/App/GeometryExtension.pyi index 7d582844cb..08c10000ee 100644 --- a/src/Mod/Part/App/GeometryExtension.pyi +++ b/src/Mod/Part/App/GeometryExtension.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from Base.PyObjectBase import PyObjectBase from typing import Final - @export( Include="Mod/Part/App/GeometryExtension.h", Constructor=True, diff --git a/src/Mod/Part/App/GeometryExtensionPyImp.cpp b/src/Mod/Part/App/GeometryExtensionPyImp.cpp index 7427f473f4..04ba85f8a2 100644 --- a/src/Mod/Part/App/GeometryExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryExtensionPyImp.cpp @@ -36,11 +36,13 @@ std::string GeometryExtensionPy::representation() const return ""; } -PyObject *GeometryExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'GeometryExtension'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'GeometryExtension'." + ); return nullptr; } @@ -50,25 +52,27 @@ int GeometryExtensionPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* GeometryExtensionPy::copy(PyObject *args) const +PyObject* GeometryExtensionPy::copy(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Part::GeometryExtension* ext = this->getGeometryExtensionPtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = nullptr; // let the type object decide - if (type->tp_new) + if (type->tp_new) { cpy = type->tp_new(type, const_cast(this), nullptr); + } if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create copy of the geometry extension"); return nullptr; } Part::GeometryExtensionPy* extpy = static_cast(cpy); - // the PyMake function must have created the corresponding instance of the 'GeometryExtension' subclass - // so delete it now to avoid a memory leak + // the PyMake function must have created the corresponding instance of the 'GeometryExtension' + // subclass so delete it now to avoid a memory leak if (extpy->_pcTwinPointer) { Part::GeometryExtension* clone = static_cast(extpy->_pcTwinPointer); delete clone; @@ -91,7 +95,7 @@ void GeometryExtensionPy::setName(Py::String arg) this->getGeometryExtensionPtr()->setName(name); } -PyObject *GeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeometryIntExtension.pyi b/src/Mod/Part/App/GeometryIntExtension.pyi index f8a306e3dc..56c58a7aaa 100644 --- a/src/Mod/Part/App/GeometryIntExtension.pyi +++ b/src/Mod/Part/App/GeometryIntExtension.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from Part.GeometryExtension import GeometryExtension from typing import Final - @export( Father="GeometryExtensionPy", Name="GeometryIntExtensionPy", diff --git a/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp b/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp index 2cdc6776ea..58eb2fd99c 100644 --- a/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp @@ -34,10 +34,11 @@ std::string GeometryIntExtensionPy::representation() const { std::stringstream str; long val = getGeometryIntExtensionPtr()->getValue(); - str << "getName().empty()) + if (!getGeometryIntExtensionPtr()->getName().empty()) { str << "\'" << getGeometryIntExtensionPtr()->getName() << "\', "; + } str << val << ") >"; @@ -45,7 +46,7 @@ std::string GeometryIntExtensionPy::representation() const return str.str(); } -PyObject *GeometryIntExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryIntExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of the python object and the Twin object return new GeometryIntExtensionPy(new GeometryIntExtension); @@ -68,17 +69,20 @@ int GeometryIntExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - char * pystr; - if (PyArg_ParseTuple(args, "ls", &val,&pystr)) { + char* pystr; + if (PyArg_ParseTuple(args, "ls", &val, &pystr)) { this->getGeometryIntExtensionPtr()->setValue(val); this->getGeometryIntExtensionPtr()->setName(pystr); return 0; } - PyErr_SetString(PyExc_TypeError, "GeometryIntExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- long int\n" - "-- long int, string\n"); + PyErr_SetString( + PyExc_TypeError, + "GeometryIntExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- long int\n" + "-- long int, string\n" + ); return -1; } @@ -93,8 +97,7 @@ void GeometryIntExtensionPy::setValue(Py::Long value) } - -PyObject *GeometryIntExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryIntExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeometryMigrationExtension.cpp b/src/Mod/Part/App/GeometryMigrationExtension.cpp index fe30649770..fd57b3b77e 100644 --- a/src/Mod/Part/App/GeometryMigrationExtension.cpp +++ b/src/Mod/Part/App/GeometryMigrationExtension.cpp @@ -33,18 +33,19 @@ using namespace Part; TYPESYSTEM_SOURCE_ABSTRACT(Part::GeometryMigrationPersistenceExtension, Part::GeometryPersistenceExtension) //---------- Geometry Extension -TYPESYSTEM_SOURCE(Part::GeometryMigrationExtension,Part::GeometryExtension) +TYPESYSTEM_SOURCE(Part::GeometryMigrationExtension, Part::GeometryExtension) -void GeometryMigrationExtension::copyAttributes(Part::GeometryExtension *cpy) const { +void GeometryMigrationExtension::copyAttributes(Part::GeometryExtension* cpy) const +{ Part::GeometryExtension::copyAttributes(cpy); - static_cast(cpy)->ConstructionState = this->ConstructionState; - static_cast(cpy)->GeometryMigrationFlags = this->GeometryMigrationFlags; + static_cast(cpy)->ConstructionState = this->ConstructionState; + static_cast(cpy)->GeometryMigrationFlags = this->GeometryMigrationFlags; - static_cast(cpy)->Id = this->Id; - static_cast(cpy)->Flags = this->Flags; - static_cast(cpy)->Ref = this->Ref; - static_cast(cpy)->RefIndex = this->RefIndex; + static_cast(cpy)->Id = this->Id; + static_cast(cpy)->Flags = this->Flags; + static_cast(cpy)->Ref = this->Ref; + static_cast(cpy)->RefIndex = this->RefIndex; } std::unique_ptr GeometryMigrationExtension::copy() const @@ -56,7 +57,7 @@ std::unique_ptr GeometryMigrationExtension::copy() cons return cpy; } -PyObject * GeometryMigrationExtension::getPyObject() +PyObject* GeometryMigrationExtension::getPyObject() { THROWM(Base::NotImplementedError, "GeometryMigrationExtension does not have a Python counterpart"); } diff --git a/src/Mod/Part/App/GeometryMigrationExtension.h b/src/Mod/Part/App/GeometryMigrationExtension.h index 16973c47cd..761347d6ac 100644 --- a/src/Mod/Part/App/GeometryMigrationExtension.h +++ b/src/Mod/Part/App/GeometryMigrationExtension.h @@ -33,28 +33,29 @@ namespace Part { -// This is a light-weight c++ only geometry extension to enable migration of information that was stored within -// the Part WB and should be migrated to another WB +// This is a light-weight c++ only geometry extension to enable migration of information that was +// stored within the Part WB and should be migrated to another WB // // It is designed so that a single extension can migrate different types of data. // // To migrate data: // 1. Add an enum bit to indicate the type of migration type // 2. Add the data members to store the information and accessors -class PartExport GeometryMigrationExtension : public Part::GeometryExtension +class PartExport GeometryMigrationExtension: public Part::GeometryExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: +public: // Indicates the type of migration to be performed, it is stored as a bitset, so several // migrations may take place in a single extension. // It is intended to support also LinkStage3 migration with a single framework (Id, Ref, ...) - enum MigrationType { - None = 0, - Construction = 1, - GeometryId = 2, - ExternalReference = 3, - NumMigrationType // Must be the last + enum MigrationType + { + None = 0, + Construction = 1, + GeometryId = 2, + ExternalReference = 3, + NumMigrationType // Must be the last }; GeometryMigrationExtension() = default; @@ -62,67 +63,94 @@ public: std::unique_ptr copy() const override; - PyObject *getPyObject() override; + PyObject* getPyObject() override; - virtual bool getConstruction() const { return ConstructionState; } + virtual bool getConstruction() const + { + return ConstructionState; + } - virtual void setConstruction(bool construction) { + virtual void setConstruction(bool construction) + { ConstructionState = construction; setMigrationType(Construction); } - long getId() const { return Id; } + long getId() const + { + return Id; + } - void setId(long id) { + void setId(long id) + { Id = id; setMigrationType(GeometryId); } - const std::string &getRef() const { return Ref; } + const std::string& getRef() const + { + return Ref; + } - int getRefIndex() const { return RefIndex; } + int getRefIndex() const + { + return RefIndex; + } - unsigned long getFlags() const { return Flags; } + unsigned long getFlags() const + { + return Flags; + } - void setReference(const char *ref, int index, unsigned long flags) { + void setReference(const char* ref, int index, unsigned long flags) + { Ref = ref ? ref : ""; RefIndex = index; Flags = flags; setMigrationType(ExternalReference); } - virtual bool testMigrationType(int flag) const { return GeometryMigrationFlags.test((size_t)(flag)); }; - virtual void setMigrationType(int flag, bool v=true) { GeometryMigrationFlags.set((size_t)(flag), v); }; + virtual bool testMigrationType(int flag) const + { + return GeometryMigrationFlags.test((size_t)(flag)); + }; + virtual void setMigrationType(int flag, bool v = true) + { + GeometryMigrationFlags.set((size_t)(flag), v); + }; protected: - void copyAttributes(Part::GeometryExtension * cpy) const override; + void copyAttributes(Part::GeometryExtension* cpy) const override; private: GeometryMigrationExtension(const GeometryMigrationExtension&) = default; private: using MigrationTypeFlagType = std::bitset<32>; - MigrationTypeFlagType GeometryMigrationFlags; - bool ConstructionState{false}; - long Id = 0; - int RefIndex = -1; - unsigned long Flags = 0; - std::string Ref; + MigrationTypeFlagType GeometryMigrationFlags; + bool ConstructionState {false}; + long Id = 0; + int RefIndex = -1; + unsigned long Flags = 0; + std::string Ref; }; -class PartExport GeometryMigrationPersistenceExtension : public Part::GeometryPersistenceExtension +class PartExport GeometryMigrationPersistenceExtension: public Part::GeometryPersistenceExtension { TYPESYSTEM_HEADER(); + public: // Called to extend 'Geometry' XML tag with additional attributes (eg Id) - virtual void preSave(Base::Writer &/*writer*/) const {} + virtual void preSave(Base::Writer& /*writer*/) const + {} // Called to add additional tag after 'GeometryExtensions' XML elements (eg Construction flag) - virtual void postSave(Base::Writer &/*writer*/) const {} + virtual void postSave(Base::Writer& /*writer*/) const + {} }; -} //namespace Part +} // namespace Part -#endif // PART_GEOMETRYMIGRATIONEXTENSION_H +#endif // PART_GEOMETRYMIGRATIONEXTENSION_H diff --git a/src/Mod/Part/App/GeometryPyImp.cpp b/src/Mod/Part/App/GeometryPyImp.cpp index 312ffc5194..a5bccdff4f 100644 --- a/src/Mod/Part/App/GeometryPyImp.cpp +++ b/src/Mod/Part/App/GeometryPyImp.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ -# include +#include #include @@ -48,11 +48,13 @@ std::string GeometryPy::representation() const return ""; } -PyObject *GeometryPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'Geometry'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'Geometry'." + ); return nullptr; } @@ -62,10 +64,10 @@ int GeometryPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* GeometryPy::mirror(PyObject *args) +PyObject* GeometryPy::mirror(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type),&o)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &o)) { Base::Vector3d vec = static_cast(o)->value(); getGeometryPtr()->mirror(vec); Py_Return; @@ -73,42 +75,45 @@ PyObject* GeometryPy::mirror(PyObject *args) PyErr_Clear(); PyObject* axis; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type),&o, - &(Base::VectorPy::Type),&axis)) { + if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &o, &(Base::VectorPy::Type), &axis)) { Base::Vector3d pnt = static_cast(o)->value(); Base::Vector3d dir = static_cast(axis)->value(); getGeometryPtr()->mirror(pnt, dir); Py_Return; } - PyErr_SetString(PartExceptionOCCError, "either a point (vector) or axis (vector, vector) must be given"); + PyErr_SetString( + PartExceptionOCCError, + "either a point (vector) or axis (vector, vector) must be given" + ); return nullptr; } -PyObject* GeometryPy::rotate(PyObject *args) +PyObject* GeometryPy::rotate(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type),&o)) + if (!PyArg_ParseTuple(args, "O!", &(Base::PlacementPy::Type), &o)) { return nullptr; + } Base::Placement* plm = static_cast(o)->getPlacementPtr(); getGeometryPtr()->rotate(*plm); Py_Return; } -PyObject* GeometryPy::scale(PyObject *args) +PyObject* GeometryPy::scale(PyObject* args) { PyObject* o; double scale; Base::Vector3d vec; - if (PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type),&o, &scale)) { + if (PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type), &o, &scale)) { vec = static_cast(o)->value(); getGeometryPtr()->scale(vec, scale); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!d", &PyTuple_Type,&o, &scale)) { + if (PyArg_ParseTuple(args, "O!d", &PyTuple_Type, &o, &scale)) { vec = Base::getVectorFromTuple(o); getGeometryPtr()->scale(vec, scale); Py_Return; @@ -118,28 +123,29 @@ PyObject* GeometryPy::scale(PyObject *args) return nullptr; } -PyObject* GeometryPy::transform(PyObject *args) +PyObject* GeometryPy::transform(PyObject* args) { PyObject* o; - if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type),&o)) + if (!PyArg_ParseTuple(args, "O!", &(Base::MatrixPy::Type), &o)) { return nullptr; + } Base::Matrix4D mat = static_cast(o)->value(); getGeometryPtr()->transform(mat); Py_Return; } -PyObject* GeometryPy::translate(PyObject *args) +PyObject* GeometryPy::translate(PyObject* args) { PyObject* o; Base::Vector3d vec; - if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type),&o)) { + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &o)) { vec = static_cast(o)->value(); getGeometryPtr()->translate(vec); Py_Return; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!", &PyTuple_Type,&o)) { + if (PyArg_ParseTuple(args, "O!", &PyTuple_Type, &o)) { vec = Base::getVectorFromTuple(o); getGeometryPtr()->translate(vec); Py_Return; @@ -149,17 +155,19 @@ PyObject* GeometryPy::translate(PyObject *args) return nullptr; } -PyObject* GeometryPy::copy(PyObject *args) const +PyObject* GeometryPy::copy(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Part::Geometry* geom = this->getGeometryPtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = nullptr; // let the type object decide - if (type->tp_new) + if (type->tp_new) { cpy = type->tp_new(type, const_cast(this), nullptr); + } if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create copy of geometry"); return nullptr; @@ -176,17 +184,19 @@ PyObject* GeometryPy::copy(PyObject *args) const return cpy; } -PyObject* GeometryPy::clone(PyObject *args) const +PyObject* GeometryPy::clone(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Part::Geometry* geom = this->getGeometryPtr(); PyTypeObject* type = this->GetType(); PyObject* cpy = nullptr; // let the type object decide - if (type->tp_new) + if (type->tp_new) { cpy = type->tp_new(type, const_cast(this), nullptr); + } if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create clone of geometry"); return nullptr; @@ -203,7 +213,7 @@ PyObject* GeometryPy::clone(PyObject *args) const return cpy; } -PyObject* GeometryPy::isSame(PyObject *args) const +PyObject* GeometryPy::isSame(PyObject* args) const { PyObject* other {}; double tol {}; @@ -217,12 +227,12 @@ PyObject* GeometryPy::isSame(PyObject *args) const return Py::new_reference_to(Py::Boolean(same)); } -PyObject* GeometryPy::setExtension(PyObject *args) +PyObject* GeometryPy::setExtension(PyObject* args) { PyObject* o; - if (PyArg_ParseTuple(args, "O!", &(GeometryExtensionPy::Type),&o)) { - Part::GeometryExtension * ext; - ext = static_cast(o)->getGeometryExtensionPtr(); + if (PyArg_ParseTuple(args, "O!", &(GeometryExtensionPy::Type), &o)) { + Part::GeometryExtension* ext; + ext = static_cast(o)->getGeometryExtensionPtr(); // make copy of Python managed memory and wrap it in smart pointer auto cpy = ext->copy(); @@ -235,154 +245,170 @@ PyObject* GeometryPy::setExtension(PyObject *args) return nullptr; } -PyObject* GeometryPy::getExtensionOfType(PyObject *args) const +PyObject* GeometryPy::getExtensionOfType(PyObject* args) const { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(!type.isBad()) { + if (!type.isBad()) { try { - std::shared_ptr ext(this->getGeometryPtr()->getExtension(type)); + std::shared_ptr ext( + this->getGeometryPtr()->getExtension(type) + ); // we create a copy and transfer this copy's memory management responsibility to Python PyObject* cpy = ext->copyPyObject(); return cpy; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } - catch(const std::bad_weak_ptr&) { + catch (const std::bad_weak_ptr&) { PyErr_SetString(PartExceptionOCCError, "Geometry extension does not exist anymore."); return nullptr; } - catch(Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not implement a Python counterpart."); + catch (Base::NotImplementedError&) { + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart." + ); return nullptr; } } - else - { + else { PyErr_SetString(PartExceptionOCCError, "Exception type does not exist"); return nullptr; } - } - PyErr_SetString(PartExceptionOCCError, "A string with the name of the geometry extension type was expected"); + PyErr_SetString( + PartExceptionOCCError, + "A string with the name of the geometry extension type was expected" + ); return nullptr; } -PyObject* GeometryPy::getExtensionOfName(PyObject *args) const +PyObject* GeometryPy::getExtensionOfName(PyObject* args) const { char* o; if (PyArg_ParseTuple(args, "s", &o)) { try { - std::shared_ptr ext(this->getGeometryPtr()->getExtension(std::string(o))); + std::shared_ptr ext( + this->getGeometryPtr()->getExtension(std::string(o)) + ); // we create a copy and transfer this copy's memory management responsibility to Python PyObject* cpy = ext->copyPyObject(); return cpy; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } - catch(const std::bad_weak_ptr&) { + catch (const std::bad_weak_ptr&) { PyErr_SetString(PartExceptionOCCError, "Geometry extension does not exist anymore."); return nullptr; } - catch(Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not implement a Python counterpart."); + catch (Base::NotImplementedError&) { + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart." + ); return nullptr; } - } - PyErr_SetString(PartExceptionOCCError, "A string with the name of the geometry extension was expected"); + PyErr_SetString( + PartExceptionOCCError, + "A string with the name of the geometry extension was expected" + ); return nullptr; } -PyObject* GeometryPy::hasExtensionOfType(PyObject *args) const +PyObject* GeometryPy::hasExtensionOfType(PyObject* args) const { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(!type.isBad()) { + if (!type.isBad()) { try { return Py::new_reference_to(Py::Boolean(this->getGeometryPtr()->hasExtension(type))); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } } - else - { + else { PyErr_SetString(PartExceptionOCCError, "Exception type does not exist"); return nullptr; } - } - PyErr_SetString(PartExceptionOCCError, "A string with the type of the geometry extension was expected"); + PyErr_SetString( + PartExceptionOCCError, + "A string with the type of the geometry extension was expected" + ); return nullptr; } -PyObject* GeometryPy::hasExtensionOfName(PyObject *args) const +PyObject* GeometryPy::hasExtensionOfName(PyObject* args) const { char* o; if (PyArg_ParseTuple(args, "s", &o)) { try { - return Py::new_reference_to(Py::Boolean(this->getGeometryPtr()->hasExtension(std::string(o)))); + return Py::new_reference_to( + Py::Boolean(this->getGeometryPtr()->hasExtension(std::string(o))) + ); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } - } - PyErr_SetString(PartExceptionOCCError, "A string with the type of the geometry extension was expected"); + PyErr_SetString( + PartExceptionOCCError, + "A string with the type of the geometry extension was expected" + ); return nullptr; } -PyObject* GeometryPy::deleteExtensionOfType(PyObject *args) +PyObject* GeometryPy::deleteExtensionOfType(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { Base::Type type = Base::Type::fromName(o); - if(!type.isBad()) { + if (!type.isBad()) { try { this->getGeometryPtr()->deleteExtension(type); Py_Return; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } } - else - { + else { PyErr_SetString(PartExceptionOCCError, "Type does not exist"); return nullptr; } - } PyErr_SetString(PartExceptionOCCError, "A string with a type object was expected"); return nullptr; } -PyObject* GeometryPy::deleteExtensionOfName(PyObject *args) +PyObject* GeometryPy::deleteExtensionOfName(PyObject* args) { char* o; if (PyArg_ParseTuple(args, "s", &o)) { @@ -391,7 +417,7 @@ PyObject* GeometryPy::deleteExtensionOfName(PyObject *args) this->getGeometryPtr()->deleteExtension(std::string(o)); Py_Return; } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } @@ -401,30 +427,33 @@ PyObject* GeometryPy::deleteExtensionOfName(PyObject *args) return nullptr; } -PyObject* GeometryPy::getExtensions(PyObject *args) const +PyObject* GeometryPy::getExtensions(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")){ + if (!PyArg_ParseTuple(args, "")) { PyErr_SetString(PartExceptionOCCError, "No arguments were expected"); return nullptr; } try { - const std::vector> ext = this->getGeometryPtr()->getExtensions(); + const std::vector> ext + = this->getGeometryPtr()->getExtensions(); Py::List list; - for (const auto & it : ext) { + for (const auto& it : ext) { // const casting only to get the Python object to make a copy - std::shared_ptr p = std::const_pointer_cast(it.lock()); + std::shared_ptr p = std::const_pointer_cast( + it.lock() + ); - if(p) { + if (p) { // we create a python copy and add it to the list try { list.append(Py::asObject(p->copyPyObject())); } - catch(Base::NotImplementedError&) { + catch (Base::NotImplementedError&) { // silently ignoring extensions not having a Python object } } @@ -432,11 +461,10 @@ PyObject* GeometryPy::getExtensions(PyObject *args) const return Py::new_reference_to(list); } - catch(const Base::ValueError& e) { + catch (const Base::ValueError& e) { PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } - } Py::String GeometryPy::getTag() const @@ -445,7 +473,7 @@ Py::String GeometryPy::getTag() const return {tmp}; } -PyObject *GeometryPy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeometryStringExtension.pyi b/src/Mod/Part/App/GeometryStringExtension.pyi index 732f60c2f3..d958dd5a8e 100644 --- a/src/Mod/Part/App/GeometryStringExtension.pyi +++ b/src/Mod/Part/App/GeometryStringExtension.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from GeometryExtension import GeometryExtension - @export( PythonName="Part.GeometryStringExtension", Include="Mod/Part/App/GeometryDefaultExtension.h", diff --git a/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp b/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp index 0a117c02ef..23808a26b4 100644 --- a/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ -# include +#include #include "GeometryStringExtensionPy.h" @@ -36,17 +36,18 @@ using namespace Part; std::string GeometryStringExtensionPy::representation() const { std::stringstream str; - str << "getName().empty()) + if (!getGeometryStringExtensionPtr()->getName().empty()) { str << "\'" << getGeometryStringExtensionPtr()->getName() << "\', "; + } str << getGeometryStringExtensionPtr()->getValue() << ") >"; return str.str(); } -PyObject *GeometryStringExtensionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometryStringExtensionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of the python object and the Twin object return new GeometryStringExtensionPy(new GeometryStringExtension); @@ -62,14 +63,14 @@ int GeometryStringExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - char *pstr; + char* pstr; if (PyArg_ParseTuple(args, "s", &pstr)) { this->getGeometryStringExtensionPtr()->setValue(pstr); return 0; } PyErr_Clear(); - char * pystr; + char* pystr; if (PyArg_ParseTuple(args, "ss", &pstr, &pystr)) { this->getGeometryStringExtensionPtr()->setValue(pstr); this->getGeometryStringExtensionPtr()->setName(pystr); @@ -77,10 +78,13 @@ int GeometryStringExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } - PyErr_SetString(PyExc_TypeError, "GeometryStringExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- string\n" - "-- string, string\n"); + PyErr_SetString( + PyExc_TypeError, + "GeometryStringExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- string\n" + "-- string, string\n" + ); return -1; } @@ -94,7 +98,7 @@ void GeometryStringExtensionPy::setValue(Py::String value) this->getGeometryStringExtensionPtr()->setValue(value.as_std_string()); } -PyObject *GeometryStringExtensionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometryStringExtensionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/GeometrySurface.pyi b/src/Mod/Part/App/GeometrySurface.pyi index a5e0f621f4..96404f7fb8 100644 --- a/src/Mod/Part/App/GeometrySurface.pyi +++ b/src/Mod/Part/App/GeometrySurface.pyi @@ -6,7 +6,6 @@ from GeometryCurve import GeometryCurve from Line import Line from typing import Final, overload, Any, Tuple, List, Literal, Union - @export( Twin="GeomSurface", TwinPointer="GeomSurface", @@ -85,30 +84,20 @@ class GeometrySurface(Geometry): def projectPoint( self, Point: Vector, Method: Literal["NearestPoint"] = "NearestPoint" ) -> Vector: ... - @overload - def projectPoint( - self, Point: Vector, Method: Literal["LowerDistance"] - ) -> float: ... - + def projectPoint(self, Point: Vector, Method: Literal["LowerDistance"]) -> float: ... @overload def projectPoint( self, Point: Vector, Method: Literal["LowerDistanceParameters"] ) -> Tuple[float, float]: ... - @overload - def projectPoint( - self, Point: Vector, Method: Literal["Distance"] - ) -> List[float]: ... - + def projectPoint(self, Point: Vector, Method: Literal["Distance"]) -> List[float]: ... @overload def projectPoint( self, Point: Vector, Method: Literal["Parameters"] ) -> List[Tuple[float, float]]: ... - @overload def projectPoint(self, Point: Vector, Method: Literal["Point"]) -> List[Vector]: ... - @constmethod def projectPoint(self, *, Point: Vector, Method: str = ...) -> Any: """ @@ -243,7 +232,6 @@ class GeometrySurface(Geometry): max_segments: int = 1000, precision_code: int = 0, ) -> Any: ... - @constmethod def toBSpline( self, diff --git a/src/Mod/Part/App/GeometrySurfacePyImp.cpp b/src/Mod/Part/App/GeometrySurfacePyImp.cpp index 84207425d6..bd4bc2bb62 100644 --- a/src/Mod/Part/App/GeometrySurfacePyImp.cpp +++ b/src/Mod/Part/App/GeometrySurfacePyImp.cpp @@ -23,23 +23,23 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -56,8 +56,9 @@ #include "TopoShapeShellPy.h" -namespace Part { -const Py::Object makeTrimmedCurvePy(const Handle(Geom_Curve)& c, double f, double l) +namespace Part +{ +const Py::Object makeTrimmedCurvePy(const Handle(Geom_Curve) & c, double f, double l) { try { std::unique_ptr gc(makeFromTrimmedCurve(c, f, l)); @@ -68,7 +69,7 @@ const Py::Object makeTrimmedCurvePy(const Handle(Geom_Curve)& c, double f, doubl } } -const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c) +const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve) & c) { try { std::unique_ptr gc(makeFromCurve(c)); @@ -79,7 +80,7 @@ const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c) } } -} // Part +} // namespace Part // --------------------------------------- @@ -91,11 +92,13 @@ std::string GeometrySurfacePy::representation() const return ""; } -PyObject *GeometrySurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* GeometrySurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'GeometrySurface'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'GeometrySurface'." + ); return nullptr; } @@ -105,17 +108,18 @@ int GeometrySurfacePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* GeometrySurfacePy::toShape(PyObject *args) const +PyObject* GeometrySurfacePy::toShape(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(g); try { if (!s.IsNull()) { - double u1,u2,v1,v2; - s->Bounds(u1,u2,v1,v2); - if (!PyArg_ParseTuple(args, "|dddd", &u1,&u2,&v1,&v2)) + double u1, u2, v1, v2; + s->Bounds(u1, u2, v1, v2); + if (!PyArg_ParseTuple(args, "|dddd", &u1, &u2, &v1, &v2)) { return nullptr; - BRepBuilderAPI_MakeFace mkBuilder(s, u1, u2, v1, v2, Precision::Confusion() ); + } + BRepBuilderAPI_MakeFace mkBuilder(s, u1, u2, v1, v2, Precision::Confusion()); TopoDS_Shape sh = mkBuilder.Shape(); return new TopoShapeFacePy(new TopoShape(sh)); } @@ -130,13 +134,21 @@ PyObject* GeometrySurfacePy::toShape(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::toShell(PyObject *args, PyObject* kwds) const +PyObject* GeometrySurfacePy::toShell(PyObject* args, PyObject* kwds) const { PyObject* bound = nullptr; PyObject* segm = nullptr; - static const std::array kwlist {"Bounds", "Segment", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|O!O!", kwlist, - &PyTuple_Type, &bound, &PyBool_Type, &segm)) { + static const std::array kwlist {"Bounds", "Segment", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|O!O!", + kwlist, + &PyTuple_Type, + &bound, + &PyBool_Type, + &segm + )) { return nullptr; } @@ -151,8 +163,8 @@ PyObject* GeometrySurfacePy::toShell(PyObject *args, PyObject* kwds) const return new TopoShapeShellPy(new TopoShape(sh)); } else { - double u1,u2,v1,v2; - s->Bounds(u1,u2,v1,v2); + double u1, u2, v1, v2; + s->Bounds(u1, u2, v1, v2); if (bound) { Py::Tuple tuple(bound); @@ -177,18 +189,19 @@ PyObject* GeometrySurfacePy::toShell(PyObject *args, PyObject* kwds) const return nullptr; } -PyObject* GeometrySurfacePy::getD0(PyObject *args) const +PyObject* GeometrySurfacePy::getD0(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(g); try { if (!s.IsNull()) { - double u,v; - if (!PyArg_ParseTuple(args, "dd", &u, &v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } gp_Pnt p; s->D0(u, v, p); - return new Base::VectorPy(Base::Vector3d(p.X(),p.Y(),p.Z())); + return new Base::VectorPy(Base::Vector3d(p.X(), p.Y(), p.Z())); } } catch (Standard_Failure& e) { @@ -200,15 +213,16 @@ PyObject* GeometrySurfacePy::getD0(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::getDN(PyObject *args) const +PyObject* GeometrySurfacePy::getDN(PyObject* args) const { try { int nu, nv; - double u,v; - if (!PyArg_ParseTuple(args, "ddii", &u, &v, &nu, &nv)) + double u, v; + if (!PyArg_ParseTuple(args, "ddii", &u, &v, &nu, &nv)) { return nullptr; + } gp_Vec v1 = getGeomSurfacePtr()->getDN(u, v, nu, nv); - return new Base::VectorPy(Base::Vector3d(v1.X(),v1.Y(),v1.Z())); + return new Base::VectorPy(Base::Vector3d(v1.X(), v1.Y(), v1.Z())); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -216,17 +230,18 @@ PyObject* GeometrySurfacePy::getDN(PyObject *args) const } } -PyObject* GeometrySurfacePy::value(PyObject *args) const +PyObject* GeometrySurfacePy::value(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(g); try { if (!s.IsNull()) { - double u,v; - if (!PyArg_ParseTuple(args, "dd", &u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; - gp_Pnt p = s->Value(u,v); - return new Base::VectorPy(Base::Vector3d(p.X(),p.Y(),p.Z())); + } + gp_Pnt p = s->Value(u, v); + return new Base::VectorPy(Base::Vector3d(p.X(), p.Y(), p.Z())); } } catch (Standard_Failure& e) { @@ -239,25 +254,26 @@ PyObject* GeometrySurfacePy::value(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::tangent(PyObject *args) const +PyObject* GeometrySurfacePy::tangent(PyObject* args) const { Handle(Geom_Geometry) g = getGeometryPtr()->handle(); Handle(Geom_Surface) s = Handle(Geom_Surface)::DownCast(g); try { if (!s.IsNull()) { - double u,v; - if (!PyArg_ParseTuple(args, "dd", &u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } gp_Dir dir; Py::Tuple tuple(2); - GeomLProp_SLProps prop(s,u,v,2,Precision::Confusion()); + GeomLProp_SLProps prop(s, u, v, 2, Precision::Confusion()); if (prop.IsTangentUDefined()) { prop.TangentU(dir); - tuple.setItem(0, Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z()))); } if (prop.IsTangentVDefined()) { prop.TangentV(dir); - tuple.setItem(1, Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z()))); } return Py::new_reference_to(tuple); @@ -273,17 +289,18 @@ PyObject* GeometrySurfacePy::tangent(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::normal(PyObject *args) const +PyObject* GeometrySurfacePy::normal(PyObject* args) const { try { GeomSurface* s = getGeomSurfacePtr(); if (s) { - double u,v; - if (!PyArg_ParseTuple(args, "dd", &u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } gp_Dir d; - if (s->normal(u,v,d)) { - return new Base::VectorPy(Base::Vector3d(d.X(),d.Y(),d.Z())); + if (s->normal(u, v, d)) { + return new Base::VectorPy(Base::Vector3d(d.X(), d.Y(), d.Z())); } else { PyErr_SetString(PyExc_RuntimeError, "normal at this point is not defined"); @@ -300,11 +317,11 @@ PyObject* GeometrySurfacePy::normal(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::projectPoint(PyObject *args, PyObject* kwds) const +PyObject* GeometrySurfacePy::projectPoint(PyObject* args, PyObject* kwds) const { PyObject* v; const char* meth = "NearestPoint"; - static const std::array kwlist {"Point", "Method", nullptr}; + static const std::array kwlist {"Point", "Method", nullptr}; if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|s", kwlist, &Base::VectorPy::Type, &v, &meth)) { return nullptr; } @@ -338,7 +355,7 @@ PyObject* GeometrySurfacePy::projectPoint(PyObject *args, PyObject* kwds) const else if (method == "Distance") { Standard_Integer num = proj.NbPoints(); Py::List list; - for (Standard_Integer i=1; i <= num; i++) { + for (Standard_Integer i = 1; i <= num; i++) { list.append(Py::Float(proj.Distance(i))); } return Py::new_reference_to(list); @@ -346,7 +363,7 @@ PyObject* GeometrySurfacePy::projectPoint(PyObject *args, PyObject* kwds) const else if (method == "Parameters") { Standard_Integer num = proj.NbPoints(); Py::List list; - for (Standard_Integer i=1; i <= num; i++) { + for (Standard_Integer i = 1; i <= num; i++) { Standard_Real u, v; proj.Parameters(i, u, v); Py::Tuple par(2); @@ -359,7 +376,7 @@ PyObject* GeometrySurfacePy::projectPoint(PyObject *args, PyObject* kwds) const else if (method == "Point") { Standard_Integer num = proj.NbPoints(); Py::List list; - for (Standard_Integer i=1; i <= num; i++) { + for (Standard_Integer i = 1; i <= num; i++) { gp_Pnt pnt = proj.Point(i); Base::Vector3d vec(pnt.X(), pnt.Y(), pnt.Z()); list.append(Py::Vector(vec)); @@ -377,16 +394,17 @@ PyObject* GeometrySurfacePy::projectPoint(PyObject *args, PyObject* kwds) const } } -PyObject* GeometrySurfacePy::isUmbillic(PyObject *args) const +PyObject* GeometrySurfacePy::isUmbillic(PyObject* args) const { try { GeomSurface* s = getGeomSurfacePtr(); if (s) { - double u,v; - if (!PyArg_ParseTuple(args, "dd", &u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } - bool val = s->isUmbillic(u,v); + bool val = s->isUmbillic(u, v); return PyBool_FromLong(val ? 1 : 0); } } @@ -400,21 +418,22 @@ PyObject* GeometrySurfacePy::isUmbillic(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::curvatureDirections(PyObject *args) const +PyObject* GeometrySurfacePy::curvatureDirections(PyObject* args) const { try { GeomSurface* s = getGeomSurfacePtr(); if (s) { - double u,v; - if (!PyArg_ParseTuple(args, "dd", &u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } gp_Dir maxd, mind; - s->curvatureDirections(u,v,maxd,mind); + s->curvatureDirections(u, v, maxd, mind); Py::Tuple tuple(2); - tuple.setItem(0, Py::Vector(Base::Vector3d(maxd.X(),maxd.Y(),maxd.Z()))); - tuple.setItem(1, Py::Vector(Base::Vector3d(mind.X(),mind.Y(),mind.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(maxd.X(), maxd.Y(), maxd.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(mind.X(), mind.Y(), mind.Z()))); return Py::new_reference_to(tuple); } } @@ -428,27 +447,28 @@ PyObject* GeometrySurfacePy::curvatureDirections(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::curvature(PyObject *args) const +PyObject* GeometrySurfacePy::curvature(PyObject* args) const { try { GeomSurface* s = getGeomSurfacePtr(); if (s) { - double u,v; + double u, v; char* type; - if (!PyArg_ParseTuple(args, "dds", &u,&v,&type)) + if (!PyArg_ParseTuple(args, "dds", &u, &v, &type)) { return nullptr; + } GeomSurface::Curvature t; - if (strcmp(type,"Max") == 0) { + if (strcmp(type, "Max") == 0) { t = GeomSurface::Maximum; } - else if (strcmp(type,"Min") == 0) { + else if (strcmp(type, "Min") == 0) { t = GeomSurface::Minimum; } - else if (strcmp(type,"Mean") == 0) { + else if (strcmp(type, "Mean") == 0) { t = GeomSurface::Mean; } - else if (strcmp(type,"Gauss") == 0) { + else if (strcmp(type, "Gauss") == 0) { t = GeomSurface::Gaussian; } else { @@ -456,7 +476,7 @@ PyObject* GeometrySurfacePy::curvature(PyObject *args) const return nullptr; } - double c = s->curvature(u,v,t); + double c = s->curvature(u, v, t); return PyFloat_FromDouble(c); } } @@ -470,15 +490,15 @@ PyObject* GeometrySurfacePy::curvature(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::isPlanar(PyObject *args) const +PyObject* GeometrySurfacePy::isPlanar(PyObject* args) const { try { - Handle(Geom_Surface) surf = Handle(Geom_Surface) - ::DownCast(getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); if (!surf.IsNull()) { double tol = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "|d", &tol)) + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; + } GeomLib_IsPlanarSurface check(surf, tol); Standard_Boolean val = check.IsPlanar(); @@ -494,18 +514,18 @@ PyObject* GeometrySurfacePy::isPlanar(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::parameter(PyObject *args) const +PyObject* GeometrySurfacePy::parameter(PyObject* args) const { - Handle(Geom_Surface) surf = Handle(Geom_Surface) - ::DownCast(getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); try { if (!surf.IsNull()) { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d", &(Base::VectorPy::Type), &p, &prec)) + if (!PyArg_ParseTuple(args, "O!|d", &(Base::VectorPy::Type), &p, &prec)) { return nullptr; + } Base::Vector3d v = Py::Vector(p, false).toVector(); - gp_Pnt pnt(v.x,v.y,v.z); + gp_Pnt pnt(v.x, v.y, v.z); ShapeAnalysis_Surface as(surf); gp_Pnt2d uv = as.ValueOfUV(pnt, prec); Py::Tuple tuple(2); @@ -524,32 +544,32 @@ PyObject* GeometrySurfacePy::parameter(PyObject *args) const return nullptr; } -PyObject* GeometrySurfacePy::bounds(PyObject * args) const +PyObject* GeometrySurfacePy::bounds(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_Surface) surf = Handle(Geom_Surface) - ::DownCast(getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Py::Tuple bound(4); - Standard_Real u1,u2,v1,v2; - surf->Bounds(u1,u2,v1,v2); - bound.setItem(0,Py::Float(u1)); - bound.setItem(1,Py::Float(u2)); - bound.setItem(2,Py::Float(v1)); - bound.setItem(3,Py::Float(v2)); + Standard_Real u1, u2, v1, v2; + surf->Bounds(u1, u2, v1, v2); + bound.setItem(0, Py::Float(u1)); + bound.setItem(1, Py::Float(u2)); + bound.setItem(2, Py::Float(v1)); + bound.setItem(3, Py::Float(v2)); return Py::new_reference_to(bound); } -PyObject* GeometrySurfacePy::uIso(PyObject * args) const +PyObject* GeometrySurfacePy::uIso(PyObject* args) const { double v; - if (!PyArg_ParseTuple(args, "d", &v)) + if (!PyArg_ParseTuple(args, "d", &v)) { return nullptr; + } try { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Handle(Geom_Curve) c = surf->UIso(v); if (c.IsNull()) { PyErr_SetString(PyExc_RuntimeError, "failed to create u iso curve"); @@ -559,8 +579,7 @@ PyObject* GeometrySurfacePy::uIso(PyObject * args) const if (c->IsKind(STANDARD_TYPE(Geom_Line))) { Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(c); GeomLine* line = new GeomLine(); - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (line->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(line->handle()); this_curv->SetLin(aLine->Lin()); return new LinePy(line); } @@ -575,15 +594,15 @@ PyObject* GeometrySurfacePy::uIso(PyObject * args) const } } -PyObject* GeometrySurfacePy::vIso(PyObject * args) const +PyObject* GeometrySurfacePy::vIso(PyObject* args) const { double v; - if (!PyArg_ParseTuple(args, "d", &v)) + if (!PyArg_ParseTuple(args, "d", &v)) { return nullptr; + } try { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Handle(Geom_Curve) c = surf->VIso(v); if (c.IsNull()) { PyErr_SetString(PyExc_RuntimeError, "failed to create v iso curve"); @@ -593,8 +612,7 @@ PyObject* GeometrySurfacePy::vIso(PyObject * args) const if (c->IsKind(STANDARD_TYPE(Geom_Line))) { Handle(Geom_Line) aLine = Handle(Geom_Line)::DownCast(c); GeomLine* line = new GeomLine(); - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (line->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(line->handle()); this_curv->SetLin(aLine->Lin()); return new LinePy(line); } @@ -609,58 +627,58 @@ PyObject* GeometrySurfacePy::vIso(PyObject * args) const } } -PyObject* GeometrySurfacePy::isUPeriodic(PyObject * args) const +PyObject* GeometrySurfacePy::isUPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsUPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* GeometrySurfacePy::isVPeriodic(PyObject * args) const +PyObject* GeometrySurfacePy::isVPeriodic(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsVPeriodic(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* GeometrySurfacePy::isUClosed(PyObject * args) const +PyObject* GeometrySurfacePy::isUClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsUClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* GeometrySurfacePy::isVClosed(PyObject * args) const +PyObject* GeometrySurfacePy::isVClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Standard_Boolean val = surf->IsVClosed(); return PyBool_FromLong(val ? 1 : 0); } -PyObject* GeometrySurfacePy::UPeriod(PyObject * args) const +PyObject* GeometrySurfacePy::UPeriod(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Standard_Real val = surf->UPeriod(); return PyFloat_FromDouble(val); } @@ -671,14 +689,14 @@ PyObject* GeometrySurfacePy::UPeriod(PyObject * args) const } } -PyObject* GeometrySurfacePy::VPeriod(PyObject * args) const +PyObject* GeometrySurfacePy::VPeriod(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); Standard_Real val = surf->VPeriod(); return PyFloat_FromDouble(val); } @@ -691,95 +709,127 @@ PyObject* GeometrySurfacePy::VPeriod(PyObject * args) const Py::String GeometrySurfacePy::getContinuity() const { - GeomAbs_Shape c = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle())->Continuity(); + GeomAbs_Shape c = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle())->Continuity(); std::string str; switch (c) { - case GeomAbs_C0: - str = "C0"; - break; - case GeomAbs_G1: - str = "G1"; - break; - case GeomAbs_C1: - str = "C1"; - break; - case GeomAbs_G2: - str = "G2"; - break; - case GeomAbs_C2: - str = "C2"; - break; - case GeomAbs_C3: - str = "C3"; - break; - case GeomAbs_CN: - str = "CN"; - break; - default: - str = "Unknown"; - break; + case GeomAbs_C0: + str = "C0"; + break; + case GeomAbs_G1: + str = "G1"; + break; + case GeomAbs_C1: + str = "C1"; + break; + case GeomAbs_G2: + str = "G2"; + break; + case GeomAbs_C2: + str = "C2"; + break; + case GeomAbs_C3: + str = "C3"; + break; + case GeomAbs_CN: + str = "CN"; + break; + default: + str = "Unknown"; + break; } return Py::String(str); } -PyObject* GeometrySurfacePy::toBSpline(PyObject * args, PyObject * kwds) const +PyObject* GeometrySurfacePy::toBSpline(PyObject* args, PyObject* kwds) const { - double tol3d=Precision::Confusion(); - const char *ucont = "C1"; - const char *vcont = "C1"; - int maxDegU=Geom_BSplineSurface::MaxDegree(); - int maxDegV=Geom_BSplineSurface::MaxDegree(); - int maxSegm=1000, prec=0; + double tol3d = Precision::Confusion(); + const char* ucont = "C1"; + const char* vcont = "C1"; + int maxDegU = Geom_BSplineSurface::MaxDegree(); + int maxDegV = Geom_BSplineSurface::MaxDegree(); + int maxSegm = 1000, prec = 0; - static const std::array kwlist{"Tol3d", "UContinuity", "VContinuity", "MaxDegreeU", "MaxDegreeV", - "MaxSegments", "PrecisCode", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|dssiiii", kwlist, - &tol3d, &ucont, &vcont, - &maxDegU, &maxDegV, &maxSegm, &prec)) { + static const std::array kwlist { + "Tol3d", + "UContinuity", + "VContinuity", + "MaxDegreeU", + "MaxDegreeV", + "MaxSegments", + "PrecisCode", + nullptr + }; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|dssiiii", + kwlist, + &tol3d, + &ucont, + &vcont, + &maxDegU, + &maxDegV, + &maxSegm, + &prec + )) { return nullptr; } GeomAbs_Shape absU, absV; std::string uc = ucont; - if (maxDegU <= 1) + if (maxDegU <= 1) { absU = GeomAbs_C0; - else if (uc == "C0") + } + else if (uc == "C0") { absU = GeomAbs_C0; - else if (uc == "C1") + } + else if (uc == "C1") { absU = GeomAbs_C1; - else if (uc == "C2") + } + else if (uc == "C2") { absU = GeomAbs_C2; - else if (uc == "C3") + } + else if (uc == "C3") { absU = GeomAbs_C3; - else if (uc == "CN") + } + else if (uc == "CN") { absU = GeomAbs_CN; - else if (uc == "G1") + } + else if (uc == "G1") { absU = GeomAbs_G1; - else + } + else { absU = GeomAbs_G2; + } std::string vc = vcont; - if (maxDegV <= 1) + if (maxDegV <= 1) { absV = GeomAbs_C0; - else if (vc == "C0") + } + else if (vc == "C0") { absV = GeomAbs_C0; - else if (vc == "C1") + } + else if (vc == "C1") { absV = GeomAbs_C1; - else if (vc == "C2") + } + else if (vc == "C2") { absV = GeomAbs_C2; - else if (vc == "C3") + } + else if (vc == "C3") { absV = GeomAbs_C3; - else if (vc == "CN") + } + else if (vc == "CN") { absV = GeomAbs_CN; - else if (vc == "G1") + } + else if (vc == "G1") { absV = GeomAbs_G1; - else + } + else { absV = GeomAbs_G2; + } try { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); GeomConvert_ApproxSurface cvt(surf, tol3d, absU, absV, maxDegU, maxDegV, maxSegm, prec); if (cvt.IsDone() && cvt.HasResult()) { return new BSplineSurfacePy(new GeomBSplineSurface(cvt.Surface())); @@ -796,7 +846,7 @@ PyObject* GeometrySurfacePy::toBSpline(PyObject * args, PyObject * kwds) const return nullptr; } -PyObject *GeometrySurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* GeometrySurfacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -808,16 +858,19 @@ int GeometrySurfacePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj // Specialized intersection functions -PyObject* GeometrySurfacePy::intersectSS(PyObject *args) const +PyObject* GeometrySurfacePy::intersectSS(PyObject* args) const { Handle(Geom_Surface) surf1 = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); try { if (!surf1.IsNull()) { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) + if (!PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) { return nullptr; - Handle(Geom_Surface) surf2 = Handle(Geom_Surface)::DownCast(static_cast(p)->getGeometryPtr()->handle()); + } + Handle(Geom_Surface) surf2 = Handle(Geom_Surface)::DownCast( + static_cast(p)->getGeometryPtr()->handle() + ); GeomAPI_IntSS intersector(surf1, surf2, prec); if (!intersector.IsDone()) { PyErr_SetString(PyExc_RuntimeError, "Intersection of surfaces failed"); @@ -845,18 +898,21 @@ PyObject* GeometrySurfacePy::intersectSS(PyObject *args) const // General intersection function -PyObject* GeometrySurfacePy::intersect(PyObject *args) const +PyObject* GeometrySurfacePy::intersect(PyObject* args) const { Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(getGeometryPtr()->handle()); try { if (!surf.IsNull()) { - PyObject *p; + PyObject* p; double prec = Precision::Confusion(); try { - if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) + if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometrySurfacePy::Type), &p, &prec)) { return intersectSS(args); - } catch(...) {}; + } + } + catch (...) { + }; PyErr_Clear(); if (PyArg_ParseTuple(args, "O!|d", &(Part::GeometryCurvePy::Type), &p, &prec)) { @@ -866,7 +922,8 @@ PyObject* GeometrySurfacePy::intersect(PyObject *args) const PyTuple_SetItem(t, 0, const_cast(this)); PyTuple_SetItem(t, 1, PyFloat_FromDouble(prec)); return curve->intersectCS(t); - } else { + } + else { return nullptr; } } @@ -883,12 +940,14 @@ PyObject* GeometrySurfacePy::intersect(PyObject *args) const Py::Object GeometrySurfacePy::getRotation() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeometryPtr()->handle()); - if(!s) + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeometryPtr()->handle() + ); + if (!s) { return Py::Object(); + } gp_Trsf trsf; - trsf.SetTransformation(s->Position().Ax2(),gp_Ax3()); + trsf.SetTransformation(s->Position().Ax2(), gp_Ax3()); auto q = trsf.GetRotation(); - return Py::Rotation(Base::Rotation(q.X(),q.Y(),q.Z(),q.W())); + return Py::Rotation(Base::Rotation(q.X(), q.Y(), q.Z(), q.W())); } diff --git a/src/Mod/Part/App/GizmoHelper.cpp b/src/Mod/Part/App/GizmoHelper.cpp index fc3a068073..1e8dec2e1f 100644 --- a/src/Mod/Part/App/GizmoHelper.cpp +++ b/src/Mod/Part/App/GizmoHelper.cpp @@ -57,7 +57,8 @@ EdgeMidPointProps getEdgeMidPointProps(Part::TopoShape& edge) } Base::Console().error( - "Failed to calculate tangent for the draggers! Please file a bug report for this."); + "Failed to calculate tangent for the draggers! Please file a bug report for this." + ); return {position, Base::Vector3d {0, 0, 0}, middle}; } @@ -68,8 +69,11 @@ Base::Vector3d getCentreOfMassFromFace(TopoDS_Face& face) return Base::convertTo(massProps.CentreOfMass()); } -std::optional> -getFaceNormalFromPointNearEdge(Part::TopoShape& edge, double middle, TopoDS_Face& face) +std::optional> getFaceNormalFromPointNearEdge( + Part::TopoShape& edge, + double middle, + TopoDS_Face& face +) { auto _edge = TopoDS::Edge(edge.getShape()); @@ -77,17 +81,18 @@ getFaceNormalFromPointNearEdge(Part::TopoShape& edge, double middle, TopoDS_Face gp_Dir _normal; Handle(IntTools_Context) context = new IntTools_Context; - if (!BOPTools_AlgoTools3D::GetApproxNormalToFaceOnEdge(_edge, - face, - middle, - _inwardPoint, - _normal, - context)) { + if (!BOPTools_AlgoTools3D::GetApproxNormalToFaceOnEdge( + _edge, + face, + middle, + _inwardPoint, + _normal, + context + )) { return std::nullopt; } - return { - {Base::convertTo(_inwardPoint), Base::convertTo(_normal)}}; + return {{Base::convertTo(_inwardPoint), Base::convertTo(_normal)}}; } Base::Vector3d getFaceNormalFromPoint(Base::Vector3d& point, TopoDS_Face& face) @@ -104,8 +109,8 @@ Base::Vector3d getFaceNormalFromPoint(Base::Vector3d& point, TopoDS_Face& face) } std::pair getAdjacentFacesFromEdge( - Part::TopoShape& edge, - Part::TopoShape& baseShape + Part::TopoShape& edge, + Part::TopoShape& baseShape ) { TopTools_IndexedDataMapOfShapeListOfShape edgeToFaceMap; @@ -113,8 +118,7 @@ std::pair getAdjacentFacesFromEdge( TopExp::MapShapesAndAncestors(baseShape.getShape(), TopAbs_EDGE, TopAbs_FACE, edgeToFaceMap); const TopTools_ListOfShape& faces = edgeToFaceMap.FindFromKey(edge.getShape()); - assert(faces.Extent() >= 2 - && "This is probably a bug so please report it to the issue tracker"); + assert(faces.Extent() >= 2 && "This is probably a bug so please report it to the issue tracker"); TopoDS_Face face1 = TopoDS::Face(faces.First()); TopoDS_Face face2 = TopoDS::Face(*(++faces.begin())); @@ -150,10 +154,7 @@ DraggerPlacementProps getDraggerPlacementFromEdgeAndFace(Part::TopoShape& edge, return {position, dir, tangent}; } -DraggerPlacementProps getDraggerPlacementFromEdgeAndFace( - Part::TopoShape& edge, - Part::TopoShape& face -) +DraggerPlacementProps getDraggerPlacementFromEdgeAndFace(Part::TopoShape& edge, Part::TopoShape& face) { TopoDS_Face _face = TopoDS::Face(face.getShape()); return getDraggerPlacementFromEdgeAndFace(edge, _face); diff --git a/src/Mod/Part/App/GizmoHelper.h b/src/Mod/Part/App/GizmoHelper.h index 1d920f0bc4..9be87e6609 100644 --- a/src/Mod/Part/App/GizmoHelper.h +++ b/src/Mod/Part/App/GizmoHelper.h @@ -39,13 +39,13 @@ EdgeMidPointProps PartExport getEdgeMidPointProps(Part::TopoShape& edge); Base::Vector3d PartExport getCentreOfMassFromFace(TopoDS_Face& face); -std::optional> -PartExport getFaceNormalFromPointNearEdge(Part::TopoShape& edge, double middle, TopoDS_Face& face); +std::optional> PartExport +getFaceNormalFromPointNearEdge(Part::TopoShape& edge, double middle, TopoDS_Face& face); Base::Vector3d PartExport getFaceNormalFromPoint(Base::Vector3d& point, TopoDS_Face& face); -std::pair PartExport getAdjacentFacesFromEdge(Part::TopoShape& edge, - Part::TopoShape& baseShape); +std::pair PartExport +getAdjacentFacesFromEdge(Part::TopoShape& edge, Part::TopoShape& baseShape); struct PartExport DraggerPlacementProps { @@ -53,10 +53,11 @@ struct PartExport DraggerPlacementProps Base::Vector3d dir; Base::Vector3d tangent; }; -DraggerPlacementProps PartExport getDraggerPlacementFromEdgeAndFace(Part::TopoShape& edge, TopoDS_Face& face); +DraggerPlacementProps PartExport +getDraggerPlacementFromEdgeAndFace(Part::TopoShape& edge, TopoDS_Face& face); -DraggerPlacementProps PartExport getDraggerPlacementFromEdgeAndFace(Part::TopoShape& edge, - Part::TopoShape& face); +DraggerPlacementProps PartExport +getDraggerPlacementFromEdgeAndFace(Part::TopoShape& edge, Part::TopoShape& face); std::vector PartExport getAdjacentEdgesFromFace(Part::TopoShape& face); diff --git a/src/Mod/Part/App/HLRBRep/HLRBRep_Algo.pyi b/src/Mod/Part/App/HLRBRep/HLRBRep_Algo.pyi index 99ea10de99..6e057c5471 100644 --- a/src/Mod/Part/App/HLRBRep/HLRBRep_Algo.pyi +++ b/src/Mod/Part/App/HLRBRep/HLRBRep_Algo.pyi @@ -8,7 +8,8 @@ from typing import Final Include="HLRBRep_Algo.hxx", Constructor=True, ) -@class_declarations(""" +@class_declarations( + """ private: Handle(HLRBRep_Algo) hAlgo; @@ -16,7 +17,8 @@ public: Handle(HLRBRep_Algo) handle() { return hAlgo; } -""") +""" +) class HLRBRep_Algo(PyObjectBase): """ Algo() -> HLRBRep_Algo @@ -175,7 +177,7 @@ class HLRBRep_Algo(PyObjectBase): def selectFace(self, i: int) -> None: """ selectFace(i) - + Select only the faces of the shape of index i. """ ... @@ -192,7 +194,7 @@ class HLRBRep_Algo(PyObjectBase): def update(self) -> None: """ update() - + Update the DataStructure. """ ... diff --git a/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp b/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp index de81283f8d..871997ea07 100644 --- a/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp @@ -24,13 +24,13 @@ #include -# include +#include -# include -# include -# include +#include +#include +#include -# include +#include #include #include @@ -44,7 +44,7 @@ using namespace Part; -PyObject *HLRBRep_AlgoPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* HLRBRep_AlgoPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of HLRBRep_AlgoPy return new HLRBRep_AlgoPy(nullptr); @@ -66,198 +66,231 @@ std::string HLRBRep_AlgoPy::representation() const return {""}; } -PyObject* HLRBRep_AlgoPy::add(PyObject *args) +PyObject* HLRBRep_AlgoPy::add(PyObject* args) { PyObject* shape; int nbIso = 0; - if (!PyArg_ParseTuple(args, "O!|i", &Part::TopoShapePy::Type, &shape, &nbIso)) + if (!PyArg_ParseTuple(args, "O!|i", &Part::TopoShapePy::Type, &shape, &nbIso)) { return nullptr; + } TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); getHLRBRep_AlgoPtr()->Add(input, nbIso); Py_Return; } -PyObject* HLRBRep_AlgoPy::remove(PyObject *args) +PyObject* HLRBRep_AlgoPy::remove(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } getHLRBRep_AlgoPtr()->Remove(index); Py_Return; } -PyObject* HLRBRep_AlgoPy::index(PyObject *args) +PyObject* HLRBRep_AlgoPy::index(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); int value = getHLRBRep_AlgoPtr()->Index(input); return Py_BuildValue("i", value); } -PyObject* HLRBRep_AlgoPy::outLinedShapeNullify(PyObject *args) +PyObject* HLRBRep_AlgoPy::outLinedShapeNullify(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_AlgoPtr()->OutLinedShapeNullify(); Py_Return; } -PyObject* HLRBRep_AlgoPy::setProjector(PyObject *args, PyObject *kwds) +PyObject* HLRBRep_AlgoPy::setProjector(PyObject* args, PyObject* kwds) { PyObject* ps = nullptr; PyObject* zd = nullptr; PyObject* xd = nullptr; double focus = std::numeric_limits::quiet_NaN(); - static const std::array kwlist {"Origin", "ZDir", "XDir", "focus", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|O!O!O!d", kwlist, - &Base::VectorPy::Type, &ps, - &Base::VectorPy::Type, &zd, - &Base::VectorPy::Type, &xd, - &focus)) { + static const std::array kwlist {"Origin", "ZDir", "XDir", "focus", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|O!O!O!d", + kwlist, + &Base::VectorPy::Type, + &ps, + &Base::VectorPy::Type, + &zd, + &Base::VectorPy::Type, + &xd, + &focus + )) { gp_Ax2 ax2; if (ps && zd && xd) { - Base::Vector3d p = Py::Vector(ps,false).toVector(); - Base::Vector3d z = Py::Vector(zd,false).toVector(); - Base::Vector3d x = Py::Vector(xd,false).toVector(); + Base::Vector3d p = Py::Vector(ps, false).toVector(); + Base::Vector3d z = Py::Vector(zd, false).toVector(); + Base::Vector3d x = Py::Vector(xd, false).toVector(); ax2.SetLocation(Base::convertTo(p)); ax2.SetDirection(Base::convertTo(z)); ax2.SetXDirection(Base::convertTo(x)); } else if (ps && zd) { - Base::Vector3d p = Py::Vector(ps,false).toVector(); - Base::Vector3d z = Py::Vector(zd,false).toVector(); + Base::Vector3d p = Py::Vector(ps, false).toVector(); + Base::Vector3d z = Py::Vector(zd, false).toVector(); ax2.SetLocation(Base::convertTo(p)); ax2.SetDirection(Base::convertTo(z)); } - if (boost::math::isnan(focus)) + if (boost::math::isnan(focus)) { getHLRBRep_AlgoPtr()->Projector(HLRAlgo_Projector(ax2)); - else + } + else { getHLRBRep_AlgoPtr()->Projector(HLRAlgo_Projector(ax2, focus)); + } Py_Return; } return nullptr; } -PyObject* HLRBRep_AlgoPy::nbShapes(PyObject *args) +PyObject* HLRBRep_AlgoPy::nbShapes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = getHLRBRep_AlgoPtr()->NbShapes(); return Py_BuildValue("i", num); } -PyObject* HLRBRep_AlgoPy::showAll(PyObject *args) +PyObject* HLRBRep_AlgoPy::showAll(PyObject* args) { - int i=-1; - if (!PyArg_ParseTuple(args, "|i", &i)) + int i = -1; + if (!PyArg_ParseTuple(args, "|i", &i)) { return nullptr; + } - if (i < 1) + if (i < 1) { getHLRBRep_AlgoPtr()->ShowAll(); - else + } + else { getHLRBRep_AlgoPtr()->ShowAll(i); + } Py_Return; } -PyObject* HLRBRep_AlgoPy::hide(PyObject *args) +PyObject* HLRBRep_AlgoPy::hide(PyObject* args) { - int i=-1, j=-1; - if (!PyArg_ParseTuple(args, "|ii", &i, &j)) + int i = -1, j = -1; + if (!PyArg_ParseTuple(args, "|ii", &i, &j)) { return nullptr; + } - if (i < 1) + if (i < 1) { getHLRBRep_AlgoPtr()->Hide(); - else if (j < 1) + } + else if (j < 1) { getHLRBRep_AlgoPtr()->Hide(i); - else + } + else { getHLRBRep_AlgoPtr()->Hide(i, j); + } Py_Return; } -PyObject* HLRBRep_AlgoPy::hideAll(PyObject *args) +PyObject* HLRBRep_AlgoPy::hideAll(PyObject* args) { - int i=-1; - if (!PyArg_ParseTuple(args, "|i", &i)) + int i = -1; + if (!PyArg_ParseTuple(args, "|i", &i)) { return nullptr; + } - if (i < 1) + if (i < 1) { getHLRBRep_AlgoPtr()->HideAll(); - else + } + else { getHLRBRep_AlgoPtr()->HideAll(i); + } Py_Return; } -PyObject* HLRBRep_AlgoPy::partialHide(PyObject *args) +PyObject* HLRBRep_AlgoPy::partialHide(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_AlgoPtr()->PartialHide(); Py_Return; } -PyObject* HLRBRep_AlgoPy::select(PyObject *args) +PyObject* HLRBRep_AlgoPy::select(PyObject* args) { - int i=-1; - if (!PyArg_ParseTuple(args, "|i", &i)) + int i = -1; + if (!PyArg_ParseTuple(args, "|i", &i)) { return nullptr; + } - if (i < 1) + if (i < 1) { getHLRBRep_AlgoPtr()->Select(); - else + } + else { getHLRBRep_AlgoPtr()->Select(i); + } Py_Return; } -PyObject* HLRBRep_AlgoPy::selectEdge(PyObject *args) +PyObject* HLRBRep_AlgoPy::selectEdge(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } getHLRBRep_AlgoPtr()->SelectEdge(index); Py_Return; } -PyObject* HLRBRep_AlgoPy::selectFace(PyObject *args) +PyObject* HLRBRep_AlgoPy::selectFace(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } getHLRBRep_AlgoPtr()->SelectFace(index); Py_Return; } -PyObject* HLRBRep_AlgoPy::initEdgeStatus(PyObject *args) +PyObject* HLRBRep_AlgoPy::initEdgeStatus(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_AlgoPtr()->InitEdgeStatus(); Py_Return; } -PyObject* HLRBRep_AlgoPy::update(PyObject *args) +PyObject* HLRBRep_AlgoPy::update(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_AlgoPtr()->Update(); Py_Return; } -PyObject *HLRBRep_AlgoPy::getCustomAttributes(const char* /*attr*/) const +PyObject* HLRBRep_AlgoPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgo.pyi b/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgo.pyi index 0ae16f6935..5d795cbb43 100644 --- a/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgo.pyi +++ b/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgo.pyi @@ -10,7 +10,8 @@ from typing import Final, overload Include="HLRBRep_PolyAlgo.hxx", Constructor=True, ) -@class_declarations(""" +@class_declarations( + """ private: Handle(HLRBRep_PolyAlgo) hAlgo; @@ -18,7 +19,8 @@ public: Handle(HLRBRep_PolyAlgo) handle() { return hAlgo; } -""") +""" +) class HLRBRep_PolyAlgo(PyObjectBase): """ PolyAlgo() -> HLRBRep_PolyAlgo @@ -73,7 +75,7 @@ class HLRBRep_PolyAlgo(PyObjectBase): remove(i) Remove the shape of index i from this framework. - """ + """ ... def nbShapes(self) -> int: @@ -82,7 +84,7 @@ class HLRBRep_PolyAlgo(PyObjectBase): Returns the number of shapes in the collection. It does not modify the object's state and is used to retrieve the count of shapes. - """ + """ ... def shape(self, i: int) -> TopoShape: @@ -90,7 +92,7 @@ class HLRBRep_PolyAlgo(PyObjectBase): shape(i) -> TopoShape Return the shape of index i. - """ + """ ... def index(self, S: TopoShape) -> int: @@ -98,13 +100,17 @@ class HLRBRep_PolyAlgo(PyObjectBase): index(S) -> int Return the index of the Shape S. - """ + """ ... - def setProjector(self, *, Origin: tuple[float, float, float] = (0.0, 0.0, 0.0), - ZDir: tuple[float, float, float] = (0.0, 0.0, 0.0), - XDir: tuple[float, float, float] = (0.0, 0.0, 0.0), - focus: float = float("nan")) -> None: + def setProjector( + self, + *, + Origin: tuple[float, float, float] = (0.0, 0.0, 0.0), + ZDir: tuple[float, float, float] = (0.0, 0.0, 0.0), + XDir: tuple[float, float, float] = (0.0, 0.0, 0.0), + focus: float = float("nan") + ) -> None: """ setProjector(Origin=(0, 0, 0), ZDir=(0,0,0), XDir=(0,0,0), focus=NaN) @@ -120,7 +126,7 @@ class HLRBRep_PolyAlgo(PyObjectBase): Launches calculation of outlines of the shape visualized by this framework. Used after setting the point of view and defining the shape or shapes to be visualized. - """ + """ ... def initHide(self) -> None: @@ -166,7 +172,6 @@ class HLRBRep_PolyAlgo(PyObjectBase): Make a shape with the internal outlines in each face of shape S. """ ... - TolAngular: float = ... TolCoef: float = ... diff --git a/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp b/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp index feaebf02cc..54c6d7789a 100644 --- a/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp @@ -24,14 +24,14 @@ #include -# include +#include -# include -# include -# include -# include +#include +#include +#include +#include -# include +#include #include #include @@ -45,7 +45,7 @@ using namespace Part; -PyObject *HLRBRep_PolyAlgoPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* HLRBRep_PolyAlgoPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of HLRBRep_AlgoPy return new HLRBRep_PolyAlgoPy(nullptr); @@ -55,8 +55,9 @@ PyObject *HLRBRep_PolyAlgoPy::PyMake(struct _typeobject *, PyObject *, PyObject int HLRBRep_PolyAlgoPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return -1; + } // The lifetime of the HLRBRep_PolyAlgo is controlled by the hAlgo handle if (shape) { @@ -80,164 +81,187 @@ std::string HLRBRep_PolyAlgoPy::representation() const return {""}; } -PyObject* HLRBRep_PolyAlgoPy::setProjector(PyObject *args, PyObject *kwds) +PyObject* HLRBRep_PolyAlgoPy::setProjector(PyObject* args, PyObject* kwds) { PyObject* ps = nullptr; PyObject* zd = nullptr; PyObject* xd = nullptr; double focus = std::numeric_limits::quiet_NaN(); - static const std::array kwlist {"Origin", "ZDir", "XDir", "focus", nullptr}; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|O!O!O!d", kwlist, - &Base::VectorPy::Type, &ps, - &Base::VectorPy::Type, &zd, - &Base::VectorPy::Type, &xd, - &focus)) { + static const std::array kwlist {"Origin", "ZDir", "XDir", "focus", nullptr}; + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|O!O!O!d", + kwlist, + &Base::VectorPy::Type, + &ps, + &Base::VectorPy::Type, + &zd, + &Base::VectorPy::Type, + &xd, + &focus + )) { gp_Ax2 ax2; if (ps && zd && xd) { - Base::Vector3d p = Py::Vector(ps,false).toVector(); - Base::Vector3d z = Py::Vector(zd,false).toVector(); - Base::Vector3d x = Py::Vector(xd,false).toVector(); + Base::Vector3d p = Py::Vector(ps, false).toVector(); + Base::Vector3d z = Py::Vector(zd, false).toVector(); + Base::Vector3d x = Py::Vector(xd, false).toVector(); ax2.SetLocation(Base::convertTo(p)); ax2.SetDirection(Base::convertTo(z)); ax2.SetXDirection(Base::convertTo(x)); } else if (ps && zd) { - Base::Vector3d p = Py::Vector(ps,false).toVector(); - Base::Vector3d z = Py::Vector(zd,false).toVector(); + Base::Vector3d p = Py::Vector(ps, false).toVector(); + Base::Vector3d z = Py::Vector(zd, false).toVector(); ax2.SetLocation(Base::convertTo(p)); ax2.SetDirection(Base::convertTo(z)); } - if (boost::math::isnan(focus)) + if (boost::math::isnan(focus)) { getHLRBRep_PolyAlgoPtr()->Projector(HLRAlgo_Projector(ax2)); - else + } + else { getHLRBRep_PolyAlgoPtr()->Projector(HLRAlgo_Projector(ax2, focus)); + } Py_Return; } return nullptr; } -PyObject* HLRBRep_PolyAlgoPy::update(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::update(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyAlgoPtr()->Update(); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::load(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::load(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); getHLRBRep_PolyAlgoPtr()->Load(input); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::remove(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::remove(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } getHLRBRep_PolyAlgoPtr()->Remove(index); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::nbShapes(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::nbShapes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = getHLRBRep_PolyAlgoPtr()->NbShapes(); return Py_BuildValue("i", num); } -PyObject* HLRBRep_PolyAlgoPy::shape(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::shape(PyObject* args) { int index; - if (!PyArg_ParseTuple(args, "i", &index)) + if (!PyArg_ParseTuple(args, "i", &index)) { return nullptr; + } TopoDS_Shape result = getHLRBRep_PolyAlgoPtr()->Shape(index); return new TopoShapePy(new TopoShape(result)); } -PyObject* HLRBRep_PolyAlgoPy::index(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::index(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); int value = getHLRBRep_PolyAlgoPtr()->Index(input); return Py_BuildValue("i", value); } -PyObject* HLRBRep_PolyAlgoPy::initHide(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::initHide(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyAlgoPtr()->InitHide(); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::moreHide(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::moreHide(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean more = getHLRBRep_PolyAlgoPtr()->MoreHide(); return Py_BuildValue("O", (more ? Py_True : Py_False)); } -PyObject* HLRBRep_PolyAlgoPy::nextHide(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::nextHide(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyAlgoPtr()->NextHide(); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::initShow(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::initShow(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyAlgoPtr()->InitShow(); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::moreShow(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::moreShow(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean more = getHLRBRep_PolyAlgoPtr()->MoreShow(); return Py_BuildValue("O", (more ? Py_True : Py_False)); } -PyObject* HLRBRep_PolyAlgoPy::nextShow(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::nextShow(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyAlgoPtr()->NextShow(); Py_Return; } -PyObject* HLRBRep_PolyAlgoPy::outLinedShape(PyObject *args) +PyObject* HLRBRep_PolyAlgoPy::outLinedShape(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); TopoDS_Shape result = getHLRBRep_PolyAlgoPtr()->OutLinedShape(input); @@ -250,7 +274,7 @@ Py::Float HLRBRep_PolyAlgoPy::getTolAngular() const return Py::Float(getHLRBRep_PolyAlgoPtr()->TolAngular()); } -void HLRBRep_PolyAlgoPy::setTolAngular(Py::Float arg) +void HLRBRep_PolyAlgoPy::setTolAngular(Py::Float arg) { getHLRBRep_PolyAlgoPtr()->TolAngular(static_cast(arg)); } @@ -260,12 +284,12 @@ Py::Float HLRBRep_PolyAlgoPy::getTolCoef() const return Py::Float(getHLRBRep_PolyAlgoPtr()->TolCoef()); } -void HLRBRep_PolyAlgoPy::setTolCoef(Py::Float arg) +void HLRBRep_PolyAlgoPy::setTolCoef(Py::Float arg) { getHLRBRep_PolyAlgoPtr()->TolCoef(static_cast(arg)); } -PyObject *HLRBRep_PolyAlgoPy::getCustomAttributes(const char* /*attr*/) const +PyObject* HLRBRep_PolyAlgoPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/HLRBRep/HLRToShape.pyi b/src/Mod/Part/App/HLRBRep/HLRToShape.pyi index b5b1fef975..0367ea61c0 100644 --- a/src/Mod/Part/App/HLRBRep/HLRToShape.pyi +++ b/src/Mod/Part/App/HLRBRep/HLRToShape.pyi @@ -140,7 +140,9 @@ class HLRToShape(PyObjectBase): """ ... - def compoundOfEdges(self, Type: int, Visible: bool, In3D: bool, *, Shape: Optional[TopoShape] = None) -> TopoShape: + def compoundOfEdges( + self, Type: int, Visible: bool, In3D: bool, *, Shape: Optional[TopoShape] = None + ) -> TopoShape: """ compoundOfEdges(Type: int, Visible: bool, In3D: bool, Shape=None) -> TopoShape @@ -148,4 +150,4 @@ class HLRToShape(PyObjectBase): into account the kind of space (2d or 3d). If Shape=None, return it for all added shapes, otherwise return it for shape Shape. """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp b/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp index 3170560e04..62d6481133 100644 --- a/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp @@ -34,7 +34,7 @@ using namespace Part; -PyObject *HLRToShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* HLRToShapePy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of HLRBRep_AlgoPy return new HLRToShapePy(nullptr); @@ -44,8 +44,9 @@ PyObject *HLRToShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) int HLRToShapePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* algo; - if (!PyArg_ParseTuple(args, "O!", &Part::HLRBRep_AlgoPy::Type, &algo)) + if (!PyArg_ParseTuple(args, "O!", &Part::HLRBRep_AlgoPy::Type, &algo)) { return -1; + } HLRBRep_AlgoPy* py = static_cast(algo); setTwinPointer(new HLRBRep_HLRToShape(py->handle())); @@ -59,11 +60,12 @@ std::string HLRToShapePy::representation() const return {""}; } -PyObject* HLRToShapePy::vCompound(PyObject *args) +PyObject* HLRToShapePy::vCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -76,11 +78,12 @@ PyObject* HLRToShapePy::vCompound(PyObject *args) } } -PyObject* HLRToShapePy::Rg1LineVCompound(PyObject *args) +PyObject* HLRToShapePy::Rg1LineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -93,11 +96,12 @@ PyObject* HLRToShapePy::Rg1LineVCompound(PyObject *args) } } -PyObject* HLRToShapePy::RgNLineVCompound(PyObject *args) +PyObject* HLRToShapePy::RgNLineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -110,11 +114,12 @@ PyObject* HLRToShapePy::RgNLineVCompound(PyObject *args) } } -PyObject* HLRToShapePy::outLineVCompound(PyObject *args) +PyObject* HLRToShapePy::outLineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -127,20 +132,22 @@ PyObject* HLRToShapePy::outLineVCompound(PyObject *args) } } -PyObject* HLRToShapePy::outLineVCompound3d(PyObject *args) +PyObject* HLRToShapePy::outLineVCompound3d(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoDS_Shape result = getHLRBRep_HLRToShapePtr()->OutLineVCompound3d(); return new TopoShapePy(new TopoShape(result)); } -PyObject* HLRToShapePy::isoLineVCompound(PyObject *args) +PyObject* HLRToShapePy::isoLineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -153,11 +160,12 @@ PyObject* HLRToShapePy::isoLineVCompound(PyObject *args) } } -PyObject* HLRToShapePy::hCompound(PyObject *args) +PyObject* HLRToShapePy::hCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -170,11 +178,12 @@ PyObject* HLRToShapePy::hCompound(PyObject *args) } } -PyObject* HLRToShapePy::Rg1LineHCompound(PyObject *args) +PyObject* HLRToShapePy::Rg1LineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -187,11 +196,12 @@ PyObject* HLRToShapePy::Rg1LineHCompound(PyObject *args) } } -PyObject* HLRToShapePy::RgNLineHCompound(PyObject *args) +PyObject* HLRToShapePy::RgNLineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -204,11 +214,12 @@ PyObject* HLRToShapePy::RgNLineHCompound(PyObject *args) } } -PyObject* HLRToShapePy::outLineHCompound(PyObject *args) +PyObject* HLRToShapePy::outLineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -221,11 +232,12 @@ PyObject* HLRToShapePy::outLineHCompound(PyObject *args) } } -PyObject* HLRToShapePy::isoLineHCompound(PyObject *args) +PyObject* HLRToShapePy::isoLineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -238,36 +250,51 @@ PyObject* HLRToShapePy::isoLineHCompound(PyObject *args) } } -PyObject* HLRToShapePy::compoundOfEdges(PyObject *args, PyObject *kwds) +PyObject* HLRToShapePy::compoundOfEdges(PyObject* args, PyObject* kwds) { int type; PyObject* visible = nullptr; PyObject* in3d = nullptr; PyObject* shape = nullptr; - static const std::array keywords {"Type", "Visible", "In3D", "Shape", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "iO!O!|O!", keywords, - &type, - &PyBool_Type, &visible, - &PyBool_Type, &in3d, - &Part::TopoShapePy::Type, &shape)) { + static const std::array keywords {"Type", "Visible", "In3D", "Shape", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "iO!O!|O!", + keywords, + &type, + &PyBool_Type, + &visible, + &PyBool_Type, + &in3d, + &Part::TopoShapePy::Type, + &shape + )) { return nullptr; } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); - TopoDS_Shape result = getHLRBRep_HLRToShapePtr()->CompoundOfEdges(input, static_cast(type), - Base::asBoolean(visible), Base::asBoolean(in3d)); + TopoDS_Shape result = getHLRBRep_HLRToShapePtr()->CompoundOfEdges( + input, + static_cast(type), + Base::asBoolean(visible), + Base::asBoolean(in3d) + ); return new TopoShapePy(new TopoShape(result)); } else { - TopoDS_Shape result = getHLRBRep_HLRToShapePtr()->CompoundOfEdges(static_cast(type), - Base::asBoolean(visible), Base::asBoolean(in3d)); + TopoDS_Shape result = getHLRBRep_HLRToShapePtr()->CompoundOfEdges( + static_cast(type), + Base::asBoolean(visible), + Base::asBoolean(in3d) + ); return new TopoShapePy(new TopoShape(result)); } } -PyObject *HLRToShapePy::getCustomAttributes(const char* /*attr*/) const +PyObject* HLRToShapePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/HLRBRep/PolyHLRToShape.pyi b/src/Mod/Part/App/HLRBRep/PolyHLRToShape.pyi index 3a4d946bd9..b69947f70f 100644 --- a/src/Mod/Part/App/HLRBRep/PolyHLRToShape.pyi +++ b/src/Mod/Part/App/HLRBRep/PolyHLRToShape.pyi @@ -38,7 +38,7 @@ class PolyHLRToShape(PyObjectBase): shape. In order to obtain a complete image, you must combine the shapes given by each of the chosen filters. The construction of the shape does not call a new computation of the algorithm, but only reads its internal results. - """ + """ def update(self, algo: HLRBRep_PolyAlgo) -> None: """ @@ -73,7 +73,7 @@ class PolyHLRToShape(PyObjectBase): Sets the extraction filter for visible smooth edges for either shape Shape or for all added shapes (Shape=None). - """ + """ ... def RgNLineVCompound(self, Shape: Optional[TopoShape] = None) -> TopoShape: @@ -82,7 +82,7 @@ class PolyHLRToShape(PyObjectBase): Sets the extraction filter for visible sewn edges for either shape Shape or for all added shapes (Shape=None). - """ + """ ... def outLineVCompound(self, Shape: Optional[TopoShape] = None) -> TopoShape: diff --git a/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp b/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp index e93aa2499a..22ad03da3e 100644 --- a/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp @@ -32,7 +32,7 @@ using namespace Part; -PyObject *PolyHLRToShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* PolyHLRToShapePy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of HLRBRep_AlgoPy return new PolyHLRToShapePy(new HLRBRep_PolyHLRToShape()); @@ -42,8 +42,9 @@ PyObject *PolyHLRToShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) int PolyHLRToShapePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* algo = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::HLRBRep_PolyAlgoPy::Type, &algo)) + if (!PyArg_ParseTuple(args, "|O!", &Part::HLRBRep_PolyAlgoPy::Type, &algo)) { return -1; + } if (algo) { HLRBRep_PolyAlgoPy* py = static_cast(algo); @@ -59,40 +60,44 @@ std::string PolyHLRToShapePy::representation() const return {""}; } -PyObject* PolyHLRToShapePy::update(PyObject *args) +PyObject* PolyHLRToShapePy::update(PyObject* args) { PyObject* algo; - if (!PyArg_ParseTuple(args, "O!", &Part::HLRBRep_PolyAlgoPy::Type, &algo)) + if (!PyArg_ParseTuple(args, "O!", &Part::HLRBRep_PolyAlgoPy::Type, &algo)) { return nullptr; + } HLRBRep_PolyAlgoPy* py = static_cast(algo); getHLRBRep_PolyHLRToShapePtr()->Update(py->handle()); Py_Return; } -PyObject* PolyHLRToShapePy::show(PyObject *args) +PyObject* PolyHLRToShapePy::show(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyHLRToShapePtr()->Show(); Py_Return; } -PyObject* PolyHLRToShapePy::hide(PyObject *args) +PyObject* PolyHLRToShapePy::hide(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getHLRBRep_PolyHLRToShapePtr()->Hide(); Py_Return; } -PyObject* PolyHLRToShapePy::vCompound(PyObject *args) +PyObject* PolyHLRToShapePy::vCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -105,11 +110,12 @@ PyObject* PolyHLRToShapePy::vCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::Rg1LineVCompound(PyObject *args) +PyObject* PolyHLRToShapePy::Rg1LineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -122,11 +128,12 @@ PyObject* PolyHLRToShapePy::Rg1LineVCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::RgNLineVCompound(PyObject *args) +PyObject* PolyHLRToShapePy::RgNLineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -139,11 +146,12 @@ PyObject* PolyHLRToShapePy::RgNLineVCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::outLineVCompound(PyObject *args) +PyObject* PolyHLRToShapePy::outLineVCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -156,11 +164,12 @@ PyObject* PolyHLRToShapePy::outLineVCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::hCompound(PyObject *args) +PyObject* PolyHLRToShapePy::hCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -173,11 +182,12 @@ PyObject* PolyHLRToShapePy::hCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::Rg1LineHCompound(PyObject *args) +PyObject* PolyHLRToShapePy::Rg1LineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -190,11 +200,12 @@ PyObject* PolyHLRToShapePy::Rg1LineHCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::RgNLineHCompound(PyObject *args) +PyObject* PolyHLRToShapePy::RgNLineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -207,11 +218,12 @@ PyObject* PolyHLRToShapePy::RgNLineHCompound(PyObject *args) } } -PyObject* PolyHLRToShapePy::outLineHCompound(PyObject *args) +PyObject* PolyHLRToShapePy::outLineHCompound(PyObject* args) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &Part::TopoShapePy::Type, &shape)) { return nullptr; + } if (shape) { TopoDS_Shape input = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -224,7 +236,7 @@ PyObject* PolyHLRToShapePy::outLineHCompound(PyObject *args) } } -PyObject *PolyHLRToShapePy::getCustomAttributes(const char* /*attr*/) const +PyObject* PolyHLRToShapePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Hyperbola.pyi b/src/Mod/Part/App/Hyperbola.pyi index d3423f3ab2..a0689db88b 100644 --- a/src/Mod/Part/App/Hyperbola.pyi +++ b/src/Mod/Part/App/Hyperbola.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from Conic import Conic from typing import Final, overload - @export( Name="HyperbolaPy", Namespace="Part", @@ -59,14 +58,9 @@ class Hyperbola(Conic): @overload def __init__(self) -> None: ... - @overload def __init__(self, hyperbola: "Hyperbola") -> None: ... - @overload def __init__(self, S1: Vector, S2: Vector, Center: Vector) -> None: ... - @overload - def __init__( - self, Center: Vector, MajorRadius: float, MinorRadius: float - ) -> None: ... + def __init__(self, Center: Vector, MajorRadius: float, MinorRadius: float) -> None: ... diff --git a/src/Mod/Part/App/HyperbolaPyImp.cpp b/src/Mod/Part/App/HyperbolaPyImp.cpp index 28408eb508..86af38978a 100644 --- a/src/Mod/Part/App/HyperbolaPyImp.cpp +++ b/src/Mod/Part/App/HyperbolaPyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -45,7 +45,7 @@ std::string HyperbolaPy::representation() const return ""; } -PyObject *HyperbolaPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* HyperbolaPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of HyperbolaPy and the Twin object return new HyperbolaPy(new GeomHyperbola); @@ -54,123 +54,164 @@ PyObject *HyperbolaPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // // constructor method int HyperbolaPy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); hyperbola->SetMajorRadius(2.0); hyperbola->SetMinorRadius(1.0); return 0; } - static const std::array keywords_e {"Hyperbola", nullptr}; + static const std::array keywords_e {"Hyperbola", nullptr}; PyErr_Clear(); - PyObject *pHypr; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!",keywords_e, &(HyperbolaPy::Type), &pHypr)) { + PyObject* pHypr; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_e, &(HyperbolaPy::Type), &pHypr)) { HyperbolaPy* pHyperbola = static_cast(pHypr); - Handle(Geom_Hyperbola) Hypr1 = Handle(Geom_Hyperbola)::DownCast - (pHyperbola->getGeomHyperbolaPtr()->handle()); - Handle(Geom_Hyperbola) Hypr2 = Handle(Geom_Hyperbola)::DownCast - (this->getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) Hypr1 = Handle(Geom_Hyperbola)::DownCast( + pHyperbola->getGeomHyperbolaPtr()->handle() + ); + Handle(Geom_Hyperbola) Hypr2 = Handle(Geom_Hyperbola)::DownCast( + this->getGeomHyperbolaPtr()->handle() + ); Hypr2->SetHypr(Hypr1->Hypr()); return 0; } - static const std::array keywords_ssc{"S1", "S2", "Center", nullptr}; + static const std::array keywords_ssc {"S1", "S2", "Center", nullptr}; PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ssc, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ssc, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakeHyperbola me(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakeHyperbola me( + gp_Pnt(v1.x, v1.y, v1.z), + gp_Pnt(v2.x, v2.y, v2.z), + gp_Pnt(v3.x, v3.y, v3.z) + ); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; } - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); hyperbola->SetHypr(me.Value()->Hypr()); return 0; } - static const std::array keywords_cmm {"Center","MajorRadius","MinorRadius",nullptr}; + static const std::array keywords_cmm {"Center", "MajorRadius", "MinorRadius", nullptr}; PyErr_Clear(); - PyObject *pV; + PyObject* pV; double major, minor; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!dd", keywords_cmm, - &(Base::VectorPy::Type), &pV, - &major, &minor)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!dd", + keywords_cmm, + &(Base::VectorPy::Type), + &pV, + &major, + &minor + )) { Base::Vector3d c = static_cast(pV)->value(); - GC_MakeHyperbola me(gp_Ax2(gp_Pnt(c.x,c.y,c.z), gp_Dir(0.0,0.0,1.0)), - major, minor); + GC_MakeHyperbola me(gp_Ax2(gp_Pnt(c.x, c.y, c.z), gp_Dir(0.0, 0.0, 1.0)), major, minor); if (!me.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(me.Status())); return -1; } - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); hyperbola->SetHypr(me.Value()->Hypr()); return 0; } - PyErr_SetString(PyExc_TypeError, "Hyperbola constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Hyperbola constructor accepts:\n" "-- empty parameter list\n" "-- Hyperbola\n" "-- Point, double, double\n" - "-- Point, Point, Point"); + "-- Point, Point, Point" + ); return -1; } Py::Float HyperbolaPy::getMajorRadius() const { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); return Py::Float(hyperbola->MajorRadius()); } void HyperbolaPy::setMajorRadius(Py::Float arg) { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); hyperbola->SetMajorRadius((double)arg); } Py::Float HyperbolaPy::getMinorRadius() const { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); return Py::Float(hyperbola->MinorRadius()); } void HyperbolaPy::setMinorRadius(Py::Float arg) { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); hyperbola->SetMinorRadius((double)arg); } Py::Float HyperbolaPy::getFocal() const { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); return Py::Float(hyperbola->Focal()); } Py::Object HyperbolaPy::getFocus1() const { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); gp_Pnt loc = hyperbola->Focus1(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } Py::Object HyperbolaPy::getFocus2() const { - Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); + Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast( + getGeomHyperbolaPtr()->handle() + ); gp_Pnt loc = hyperbola->Focus2(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -PyObject *HyperbolaPy::getCustomAttributes(const char* /*attr*/) const +PyObject* HyperbolaPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/IGES/ImportExportSettings.cpp b/src/Mod/Part/App/IGES/ImportExportSettings.cpp index 8c6b401c95..4875945d9c 100644 --- a/src/Mod/Part/App/IGES/ImportExportSettings.cpp +++ b/src/Mod/Part/App/IGES/ImportExportSettings.cpp @@ -22,19 +22,23 @@ * * ***************************************************************************/ -# include +#include #include "ImportExportSettings.h" #include -namespace Part { -namespace IGES { +namespace Part +{ +namespace IGES +{ ImportExportSettings::ImportExportSettings() { - pGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part/IGES"); + pGroup = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part/IGES" + ); } bool ImportExportSettings::getSkipBlankEntities() const @@ -102,5 +106,5 @@ void ImportExportSettings::setProductName(const char* name) Part::Interface::writeIgesHeaderProduct(name); } -} // namespace IGES -} // namespace Part +} // namespace IGES +} // namespace Part diff --git a/src/Mod/Part/App/IGES/ImportExportSettings.h b/src/Mod/Part/App/IGES/ImportExportSettings.h index 1516e20cee..2bb57f40af 100644 --- a/src/Mod/Part/App/IGES/ImportExportSettings.h +++ b/src/Mod/Part/App/IGES/ImportExportSettings.h @@ -33,7 +33,8 @@ namespace Part { -namespace IGES { +namespace IGES +{ class PartExport ImportExportSettings { @@ -62,7 +63,7 @@ private: ParameterGrp::handle pGroup; }; -} //namespace IGES -} //namespace Part +} // namespace IGES +} // namespace Part #endif diff --git a/src/Mod/Part/App/ImportIges.cpp b/src/Mod/Part/App/ImportIges.cpp index d99bb17c1c..ed0f7a33f4 100644 --- a/src/Mod/Part/App/ImportIges.cpp +++ b/src/Mod/Part/App/ImportIges.cpp @@ -22,22 +22,22 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -51,7 +51,7 @@ FC_LOG_LEVEL_INIT("Part") using namespace Part; -int Part::ImportIgesParts(App::Document *pcDoc, const char* FileName) +int Part::ImportIgesParts(App::Document* pcDoc, const char* FileName) { FC_WARN("Importing IGES via 'Part' is deprecated. Use 'ImportGui' instead."); try { @@ -60,27 +60,28 @@ int Part::ImportIgesParts(App::Document *pcDoc, const char* FileName) IGESControl_Controller::Init(); // load data exchange message files - Message_MsgFile::LoadFromEnv("CSF_XSMessage","IGES"); + Message_MsgFile::LoadFromEnv("CSF_XSMessage", "IGES"); // load shape healing message files - Message_MsgFile::LoadFromEnv("CSF_SHMessageStd","SHAPEStd"); + Message_MsgFile::LoadFromEnv("CSF_SHMessageStd", "SHAPEStd"); IGESControl_Reader aReader; - if (aReader.ReadFile((Standard_CString)FileName) != IFSelect_RetDone) + if (aReader.ReadFile((Standard_CString)FileName) != IFSelect_RetDone) { throw Base::FileException("Error in reading IGES"); + } // Ignore construction elements // http://www.opencascade.org/org/forum/thread_20603/?forum=3 aReader.SetReadVisible(Standard_True); // check file conformity and output stats - aReader.PrintCheckLoad(Standard_True,IFSelect_GeneralInfo); + aReader.PrintCheckLoad(Standard_True, IFSelect_GeneralInfo); std::string aName = fi.fileNamePure(); // make model aReader.ClearShapes(); - //Standard_Integer nbRootsForTransfer = aReader.NbRootsForTransfer(); + // Standard_Integer nbRootsForTransfer = aReader.NbRootsForTransfer(); aReader.TransferRoots(); // put all other free-flying shapes into a single compound @@ -90,14 +91,13 @@ int Part::ImportIgesParts(App::Document *pcDoc, const char* FileName) builder.MakeCompound(comp); Standard_Integer nbShapes = aReader.NbShapes(); - for (Standard_Integer i=1; i<=nbShapes; i++) { + for (Standard_Integer i = 1; i <= nbShapes; i++) { TopoDS_Shape aShape = aReader.Shape(i); if (!aShape.IsNull()) { - if (aShape.ShapeType() == TopAbs_SOLID || - aShape.ShapeType() == TopAbs_COMPOUND || - aShape.ShapeType() == TopAbs_SHELL) { - auto* obj = pcDoc->addObject(aName.c_str()); - obj->Shape.setValue(aShape); + if (aShape.ShapeType() == TopAbs_SOLID || aShape.ShapeType() == TopAbs_COMPOUND + || aShape.ShapeType() == TopAbs_SHELL) { + auto* obj = pcDoc->addObject(aName.c_str()); + obj->Shape.setValue(aShape); } else { builder.Add(comp, aShape); diff --git a/src/Mod/Part/App/ImportIges.h b/src/Mod/Part/App/ImportIges.h index acfcf5f387..7801d0af4a 100644 --- a/src/Mod/Part/App/ImportIges.h +++ b/src/Mod/Part/App/ImportIges.h @@ -28,15 +28,16 @@ #include -namespace App { +namespace App +{ class Document; } namespace Part { -PartExport int ImportIgesParts(App::Document *pcDoc, const char* Name); +PartExport int ImportIgesParts(App::Document* pcDoc, const char* Name); -} //namespace Part +} // namespace Part -#endif // PART_IMPORT_IGES_H +#endif // PART_IMPORT_IGES_H diff --git a/src/Mod/Part/App/ImportStep.cpp b/src/Mod/Part/App/ImportStep.cpp index 139164b30d..78d92b6c21 100644 --- a/src/Mod/Part/App/ImportStep.cpp +++ b/src/Mod/Part/App/ImportStep.cpp @@ -22,22 +22,22 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -53,12 +53,13 @@ FC_LOG_LEVEL_INIT("Part") -namespace Part { -bool ReadColors (const Handle(XSControl_WorkSession) &WS, std::map& hash_col); -bool ReadNames (const Handle(XSControl_WorkSession) &WS); -} +namespace Part +{ +bool ReadColors(const Handle(XSControl_WorkSession) & WS, std::map& hash_col); +bool ReadNames(const Handle(XSControl_WorkSession) & WS); +} // namespace Part -int Part::ImportStepParts(App::Document *pcDoc, const char* Name) +int Part::ImportStepParts(App::Document* pcDoc, const char* Name) { // Use this to force to link against TKSTEPBase, TKSTEPAttr and TKStep209 // in order to make RUNPATH working on Linux @@ -77,17 +78,16 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) throw Base::FileException(str.str().c_str()); } std::string encodednamestr = encodeFilename(std::string(Name)); - const char * encodedname = encodednamestr.c_str(); + const char* encodedname = encodednamestr.c_str(); - if (aReader.ReadFile((Standard_CString)encodedname) != - IFSelect_RetDone) { + if (aReader.ReadFile((Standard_CString)encodedname) != IFSelect_RetDone) { throw Base::FileException("Cannot open STEP file"); } // Root transfers Standard_Integer nbr = aReader.NbRootsForTransfer(); - for (Standard_Integer n = 1; n<= nbr; n++) { - Base::Console().log("STEP: Transferring Root %d\n",n); + for (Standard_Integer n = 1; n <= nbr; n++) { + Base::Console().log("STEP: Transferring Root %d\n", n); aReader.TransferRoot(n); } @@ -100,31 +100,30 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) std::map hash_col; - for (Standard_Integer i=1; i<=nbs; i++) { - Base::Console().log("STEP: Transferring Shape %d\n",i); + for (Standard_Integer i = 1; i <= nbs; i++) { + Base::Console().log("STEP: Transferring Shape %d\n", i); aShape = aReader.Shape(i); // load each solid as an own object TopExp_Explorer ex; - for (ex.Init(aShape, TopAbs_SOLID); ex.More(); ex.Next()) - { + for (ex.Init(aShape, TopAbs_SOLID); ex.More(); ex.Next()) { // get the shape const TopoDS_Solid& aSolid = TopoDS::Solid(ex.Current()); std::string name = fi.fileNamePure(); - //Handle(Standard_Transient) ent = tr->EntityFromShapeResult(aSolid, 3); - //if (!ent.IsNull()) { - // name += ws->Model()->StringLabel(ent)->ToCString(); - //} + // Handle(Standard_Transient) ent = tr->EntityFromShapeResult(aSolid, 3); + // if (!ent.IsNull()) { + // name += ws->Model()->StringLabel(ent)->ToCString(); + // } - Part::Feature *pcFeature; + Part::Feature* pcFeature; pcFeature = pcDoc->addObject(name.c_str()); pcFeature->Shape.setValue(aSolid); // This is a trick to access the GUI via Python and set the color property // of the associated view provider. If no GUI is up an exception is thrown // and cleared immediately - std::map::iterator it = hash_col.find(ShapeMapHasher{}(aSolid)); + std::map::iterator it = hash_col.find(ShapeMapHasher {}(aSolid)); if (it != hash_col.end()) { try { Py::Object obj(pcFeature->getPyObject(), true); @@ -141,14 +140,13 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) } } // load all non-solids now - for (ex.Init(aShape, TopAbs_SHELL, TopAbs_SOLID); ex.More(); ex.Next()) - { + for (ex.Init(aShape, TopAbs_SHELL, TopAbs_SOLID); ex.More(); ex.Next()) { // get the shape const TopoDS_Shell& aShell = TopoDS::Shell(ex.Current()); std::string name = fi.fileNamePure(); - Part::Feature *pcFeature = pcDoc->addObject(name.c_str()); + Part::Feature* pcFeature = pcDoc->addObject(name.c_str()); pcFeature->Shape.setValue(aShell); } @@ -185,8 +183,9 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) if (!emptyComp) { std::string name = fi.fileNamePure(); - Part::Feature *pcFeature = static_cast(pcDoc->addObject - ("Part::Feature", name.c_str())); + Part::Feature* pcFeature = static_cast( + pcDoc->addObject("Part::Feature", name.c_str()) + ); pcFeature->Shape.setValue(comp); } } @@ -196,14 +195,14 @@ int Part::ImportStepParts(App::Document *pcDoc, const char* Name) } -bool Part::ReadColors (const Handle(XSControl_WorkSession) &WS, std::map& hash_col) +bool Part::ReadColors(const Handle(XSControl_WorkSession) & WS, std::map& hash_col) { (void)WS; (void)hash_col; return Standard_False; } -bool Part::ReadNames (const Handle(XSControl_WorkSession) &WS) +bool Part::ReadNames(const Handle(XSControl_WorkSession) & WS) { (void)WS; return Standard_False; diff --git a/src/Mod/Part/App/ImportStep.h b/src/Mod/Part/App/ImportStep.h index cf81758cb0..3e226643b5 100644 --- a/src/Mod/Part/App/ImportStep.h +++ b/src/Mod/Part/App/ImportStep.h @@ -27,7 +27,8 @@ #include -namespace App { +namespace App +{ class Document; } @@ -36,9 +37,10 @@ namespace Part /** The part shape property */ -PartExport int ImportStepParts(App::Document *pcDoc, const char* Name); +PartExport int ImportStepParts(App::Document* pcDoc, const char* Name); -inline std::list supportedSTEPSchemes() { +inline std::list supportedSTEPSchemes() +{ std::list schemes; schemes.emplace_back("AP203"); schemes.emplace_back("AP214CD"); @@ -48,8 +50,7 @@ inline std::list supportedSTEPSchemes() { return schemes; } -} //namespace Part - +} // namespace Part #endif diff --git a/src/Mod/Part/App/Interface.cpp b/src/Mod/Part/App/Interface.cpp index 174339c463..da5f959586 100644 --- a/src/Mod/Part/App/Interface.cpp +++ b/src/Mod/Part/App/Interface.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include "Interface.h" @@ -113,12 +113,12 @@ bool Interface::writeStepUnit(Standard_CString unit) bool Interface::writeStepUnit(Interface::Unit unit) { switch (unit) { - case Interface::Unit::Meter: - return Interface_Static::SetCVal("write.step.unit","M"); - case Interface::Unit::Inch: - return Interface_Static::SetCVal("write.step.unit","INCH"); - default: - return Interface_Static::SetCVal("write.step.unit","MM"); + case Interface::Unit::Meter: + return Interface_Static::SetCVal("write.step.unit", "M"); + case Interface::Unit::Inch: + return Interface_Static::SetCVal("write.step.unit", "INCH"); + default: + return Interface_Static::SetCVal("write.step.unit", "MM"); } } @@ -175,12 +175,12 @@ bool Interface::writeIgesUnit(Standard_CString unit) bool Interface::writeIgesUnit(Interface::Unit unit) { switch (unit) { - case Unit::Meter: - return Interface_Static::SetCVal("write.iges.unit","M"); - case Unit::Inch: - return Interface_Static::SetCVal("write.iges.unit","INCH"); - default: - return Interface_Static::SetCVal("write.iges.unit","MM"); + case Unit::Meter: + return Interface_Static::SetCVal("write.iges.unit", "M"); + case Unit::Inch: + return Interface_Static::SetCVal("write.iges.unit", "INCH"); + default: + return Interface_Static::SetCVal("write.iges.unit", "MM"); } } diff --git a/src/Mod/Part/App/Interface.h b/src/Mod/Part/App/Interface.h index d9a7b3e482..1900243eb7 100644 --- a/src/Mod/Part/App/Interface.h +++ b/src/Mod/Part/App/Interface.h @@ -36,14 +36,16 @@ class PartExport Interface { public: // See https://dev.opencascade.org/doc/overview/html/occt_user_guides__step.html - enum class Assembly { + enum class Assembly + { Off = 0, /**< (Default) writes STEP files without assemblies */ On = 1, /**< writes all shapes in the form of STEP assemblies */ Auto = 2, /**< writes shapes having a structure of (possibly nested) TopoDS_Compounds in the form of STEP assemblies, single shapes are written without assembly structures */ }; - enum class Unit { + enum class Unit + { Millimeter = 0, Meter = 1, Inch = 2, @@ -77,6 +79,6 @@ public: //@} }; -} //namespace Part +} // namespace Part #endif diff --git a/src/Mod/Part/App/Line.pyi b/src/Mod/Part/App/Line.pyi index 1d6351999b..c2ec01a386 100644 --- a/src/Mod/Part/App/Line.pyi +++ b/src/Mod/Part/App/Line.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from GeometryCurve import GeometryCurve from typing import overload, Final - @export( PythonName="Part.Line", Twin="GeomLine", @@ -37,9 +36,7 @@ class Line(GeometryCurve): @overload def __init__(self) -> None: ... - @overload def __init__(self, line: "Line") -> None: ... - @overload def __init__(self, point1: Vector, point2: Vector) -> None: ... diff --git a/src/Mod/Part/App/LinePyImp.cpp b/src/Mod/Part/App/LinePyImp.cpp index fad73e687e..9b3d057e60 100644 --- a/src/Mod/Part/App/LinePyImp.cpp +++ b/src/Mod/Part/App/LinePyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -44,7 +44,7 @@ std::string LinePy::representation() const return ""; } -PyObject *LinePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* LinePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of LinePy and the Twin object return new LinePy(new GeomLine); @@ -60,16 +60,14 @@ int LinePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pLine; + PyObject* pLine; if (PyArg_ParseTuple(args, "O!", &(LinePy::Type), &pLine)) { // Copy line LinePy* pcLine = static_cast(pLine); // get Geom_Line of line - Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast - (pcLine->getGeomLinePtr()->handle()); + Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(pcLine->getGeomLinePtr()->handle()); // get Geom_Line of line - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this->getGeomLinePtr()->handle()); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this->getGeomLinePtr()->handle()); // Assign the lines this_line->SetLin(that_line->Lin()); @@ -78,25 +76,23 @@ int LinePy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject *pV1, *pV2; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2)) { + if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &pV1, &(Base::VectorPy::Type), &pV2)) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); try { // Create line out of two points double distance = Base::Distance(v1, v2); - if (distance < gp::Resolution()) + if (distance < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); - GC_MakeLine ms(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z)); + } + GC_MakeLine ms(gp_Pnt(v1.x, v1.y, v1.z), gp_Pnt(v2.x, v2.y, v2.z)); if (!ms.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(ms.Status())); return -1; } // get Geom_Line of line - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (this->getGeomLinePtr()->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(this->getGeomLinePtr()->handle()); Handle(Geom_Line) that_curv = ms.Value(); this_curv->SetLin(that_curv->Lin()); return 0; @@ -112,17 +108,19 @@ int LinePy::PyInit(PyObject* args, PyObject* /*kwd*/) } } - PyErr_SetString(PyExc_TypeError, "Line constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Line constructor accepts:\n" "-- empty parameter list\n" "-- Line\n" - "-- Point, Point"); + "-- Point, Point" + ); return -1; } Py::Object LinePy::getLocation() const { - Handle(Geom_Line) this_curve = Handle(Geom_Line)::DownCast - (this->getGeomLinePtr()->handle()); + Handle(Geom_Line) this_curve = Handle(Geom_Line)::DownCast(this->getGeomLinePtr()->handle()); gp_Pnt pnt = this_curve->Position().Location(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } @@ -131,11 +129,10 @@ void LinePy::setLocation(Py::Object arg) { gp_Pnt pnt; gp_Dir dir; - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (this->getGeomLinePtr()->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(this->getGeomLinePtr()->handle()); dir = this_curv->Position().Direction(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); pnt.SetX(v.x); @@ -171,8 +168,7 @@ void LinePy::setLocation(Py::Object arg) Py::Object LinePy::getDirection() const { - Handle(Geom_Line) this_curve = Handle(Geom_Line)::DownCast - (this->getGeomLinePtr()->handle()); + Handle(Geom_Line) this_curve = Handle(Geom_Line)::DownCast(this->getGeomLinePtr()->handle()); gp_Dir dir = this_curve->Position().Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } @@ -181,21 +177,20 @@ void LinePy::setDirection(Py::Object arg) { gp_Pnt pnt; gp_Dir dir; - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (this->getGeomLinePtr()->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(this->getGeomLinePtr()->handle()); pnt = this_curv->Position().Location(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); - dir = gp_Dir(v.x,v.y,v.z); + dir = gp_Dir(v.x, v.y, v.z); } else if (PyTuple_Check(p)) { Py::Tuple tuple(arg); double x = (double)Py::Float(tuple.getItem(0)); double y = (double)Py::Float(tuple.getItem(1)); double z = (double)Py::Float(tuple.getItem(2)); - dir = gp_Dir(x,y,z); + dir = gp_Dir(x, y, z); } else { std::string error = std::string("type must be 'Vector' or tuple, not "); @@ -218,7 +213,7 @@ void LinePy::setDirection(Py::Object arg) } } -PyObject *LinePy::getCustomAttributes(const char* /*attr*/) const +PyObject* LinePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/LineSegment.pyi b/src/Mod/Part/App/LineSegment.pyi index 0e4c17faf6..581d7ab8d5 100644 --- a/src/Mod/Part/App/LineSegment.pyi +++ b/src/Mod/Part/App/LineSegment.pyi @@ -4,7 +4,6 @@ from TrimmedCurve import TrimmedCurve from Point import Point from typing import Final, overload - @export( PythonName="Part.LineSegment", Twin="GeomLineSegment", @@ -35,13 +34,10 @@ class LineSegment(TrimmedCurve): @overload def __init__(self) -> None: ... - @overload def __init__(self, line_segment: "LineSegment") -> None: ... - @overload def __init__(self, point1: Point, point2: Point) -> None: ... - def setParameterRange(self) -> None: """ Set the parameter range of the underlying line geometry diff --git a/src/Mod/Part/App/LineSegmentPyImp.cpp b/src/Mod/Part/App/LineSegmentPyImp.cpp index e6c1298a3e..ccbeca9ec6 100644 --- a/src/Mod/Part/App/LineSegmentPyImp.cpp +++ b/src/Mod/Part/App/LineSegmentPyImp.cpp @@ -22,9 +22,9 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include @@ -45,15 +45,14 @@ std::string LineSegmentPy::representation() const { std::stringstream str; Base::Vector3d start = getGeomLineSegmentPtr()->getStartPoint(); - Base::Vector3d end = getGeomLineSegmentPtr()->getEndPoint(); - str << ""; + Base::Vector3d end = getGeomLineSegmentPtr()->getEndPoint(); + str << ""; return str.str(); } -PyObject *LineSegmentPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* LineSegmentPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of LineSegmentPy and the Twin object return new LineSegmentPy(new GeomLineSegment); @@ -67,20 +66,20 @@ int LineSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pLine; + PyObject* pLine; if (PyArg_ParseTuple(args, "O!", &(LineSegmentPy::Type), &pLine)) { // Copy line LineSegmentPy* pcLine = static_cast(pLine); // get Geom_Line of line segment - Handle(Geom_TrimmedCurve) that_curv = Handle(Geom_TrimmedCurve)::DownCast - (pcLine->getGeomLineSegmentPtr()->handle()); - Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast - (that_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) that_curv = Handle(Geom_TrimmedCurve)::DownCast( + pcLine->getGeomLineSegmentPtr()->handle() + ); + Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(that_curv->BasisCurve()); // get Geom_Line of line segment - Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); // Assign the lines this_line->SetLin(that_line->Lin()); @@ -94,15 +93,15 @@ int LineSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) // Copy line LineSegmentPy* pcLine = static_cast(pLine); // get Geom_Line of line segment - Handle(Geom_TrimmedCurve) that_curv = Handle(Geom_TrimmedCurve)::DownCast - (pcLine->getGeomLineSegmentPtr()->handle()); - Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast - (that_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) that_curv = Handle(Geom_TrimmedCurve)::DownCast( + pcLine->getGeomLineSegmentPtr()->handle() + ); + Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(that_curv->BasisCurve()); // get Geom_Line of line segment - Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); // Assign the lines this_line->SetLin(that_line->Lin()); @@ -115,13 +114,12 @@ int LineSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) // Copy line LinePy* pcLine = static_cast(pLine); // get Geom_Line of line segment - Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast - (pcLine->getGeomLinePtr()->handle()); + Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(pcLine->getGeomLinePtr()->handle()); // get Geom_Line of line segment - Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); // Assign the lines this_line->SetLin(that_line->Lin()); @@ -131,27 +129,26 @@ int LineSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject *pV1, *pV2; - if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2)) { + if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &pV1, &(Base::VectorPy::Type), &pV2)) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); try { // Create line out of two points double distance = Base::Distance(v1, v2); - if (distance < gp::Resolution()) + if (distance < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); - GC_MakeSegment ms(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z)); + } + GC_MakeSegment ms(gp_Pnt(v1.x, v1.y, v1.z), gp_Pnt(v2.x, v2.y, v2.z)); if (!ms.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(ms.Status())); return -1; } // get Geom_Line of line segment - Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom_TrimmedCurve) that_curv = ms.Value(); Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin(that_line->Lin()); @@ -170,24 +167,29 @@ int LineSegmentPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } - PyErr_SetString(PyExc_TypeError, "Line constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Line constructor accepts:\n" "-- empty parameter list\n" "-- LineSegment\n" "-- LineSegment,double,double\n" "-- Line,double,double\n" - "-- Point, Point"); + "-- Point, Point" + ); return -1; } -PyObject* LineSegmentPy::setParameterRange(PyObject *args) +PyObject* LineSegmentPy::setParameterRange(PyObject* args) { double first, last; - if (!PyArg_ParseTuple(args, "dd", &first, &last)) + if (!PyArg_ParseTuple(args, "dd", &first, &last)) { return nullptr; + } try { - Handle(Geom_TrimmedCurve) this_curve = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); + Handle(Geom_TrimmedCurve) this_curve = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); this_curve->SetTrim(first, last); } catch (Standard_Failure& e) { @@ -200,8 +202,9 @@ PyObject* LineSegmentPy::setParameterRange(PyObject *args) Py::Object LineSegmentPy::getStartPoint() const { - Handle(Geom_TrimmedCurve) this_curve = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); + Handle(Geom_TrimmedCurve) this_curve = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); gp_Pnt pnt = this_curve->StartPoint(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } @@ -209,11 +212,12 @@ Py::Object LineSegmentPy::getStartPoint() const void LineSegmentPy::setStartPoint(Py::Object arg) { gp_Pnt p1, p2; - Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); + Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); p2 = this_curv->EndPoint(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); p1.SetX(v.x); @@ -234,16 +238,16 @@ void LineSegmentPy::setStartPoint(Py::Object arg) try { // Create line out of two points - if (p1.Distance(p2) < gp::Resolution()) + if (p1.Distance(p2) < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); + } GC_MakeSegment ms(p1, p2); if (!ms.IsDone()) { throw Py::RuntimeError(gce_ErrorStatusText(ms.Status())); } // get Geom_Line of line segment - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom_TrimmedCurve) that_curv = ms.Value(); Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin(that_line->Lin()); @@ -256,8 +260,9 @@ void LineSegmentPy::setStartPoint(Py::Object arg) Py::Object LineSegmentPy::getEndPoint() const { - Handle(Geom_TrimmedCurve) this_curve = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); + Handle(Geom_TrimmedCurve) this_curve = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); gp_Pnt pnt = this_curve->EndPoint(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } @@ -265,11 +270,12 @@ Py::Object LineSegmentPy::getEndPoint() const void LineSegmentPy::setEndPoint(Py::Object arg) { gp_Pnt p1, p2; - Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast - (this->getGeomLineSegmentPtr()->handle()); + Handle(Geom_TrimmedCurve) this_curv = Handle(Geom_TrimmedCurve)::DownCast( + this->getGeomLineSegmentPtr()->handle() + ); p1 = this_curv->StartPoint(); - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); p2.SetX(v.x); @@ -290,16 +296,16 @@ void LineSegmentPy::setEndPoint(Py::Object arg) try { // Create line out of two points - if (p1.Distance(p2) < gp::Resolution()) + if (p1.Distance(p2) < gp::Resolution()) { Standard_Failure::Raise("Both points are equal"); + } GC_MakeSegment ms(p1, p2); if (!ms.IsDone()) { throw Py::RuntimeError(gce_ErrorStatusText(ms.Status())); } // get Geom_Line of line segment - Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast - (this_curv->BasisCurve()); + Handle(Geom_Line) this_line = Handle(Geom_Line)::DownCast(this_curv->BasisCurve()); Handle(Geom_TrimmedCurve) that_curv = ms.Value(); Handle(Geom_Line) that_line = Handle(Geom_Line)::DownCast(that_curv->BasisCurve()); this_line->SetLin(that_line->Lin()); @@ -310,7 +316,7 @@ void LineSegmentPy::setEndPoint(Py::Object arg) } } -PyObject *LineSegmentPy::getCustomAttributes(const char* /*attr*/) const +PyObject* LineSegmentPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/MeasureClient.cpp b/src/Mod/Part/App/MeasureClient.cpp index 55f66e81f1..82c41d81c8 100644 --- a/src/Mod/Part/App/MeasureClient.cpp +++ b/src/Mod/Part/App/MeasureClient.cpp @@ -24,7 +24,6 @@ **************************************************************************/ - #include #include @@ -68,22 +67,26 @@ using namespace Part; using Attacher::AttachEnginePlane; -// From: https://github.com/Celemation/FreeCAD/blob/joel_selection_summary_demo/src/Gui/Selection/SelectionSummary.cpp +// From: +// https://github.com/Celemation/FreeCAD/blob/joel_selection_summary_demo/src/Gui/Selection/SelectionSummary.cpp // Should work with edges and wires -static float getLength(TopoDS_Shape& wire){ +static float getLength(TopoDS_Shape& wire) +{ GProp_GProps gprops; BRepGProp::LinearProperties(wire, gprops); return gprops.Mass(); } -static float getFaceArea(TopoDS_Shape& face){ +static float getFaceArea(TopoDS_Shape& face) +{ GProp_GProps gprops; BRepGProp::SurfaceProperties(face, gprops); return gprops.Mass(); } -static float getRadius(TopoDS_Shape& edge){ +static float getRadius(TopoDS_Shape& edge) +{ // gprops.Mass() would be the circumference (length) of the circle (arc) if (edge.ShapeType() == TopAbs_EDGE) { BRepAdaptor_Curve adapt(TopoDS::Edge(edge)); @@ -106,17 +109,22 @@ TopoDS_Shape getLocatedShape(const App::SubObjectT& subject, Base::Matrix4D* mat Part::TopoShape shape = Part::Feature::getTopoShape( obj, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform, subject.getElementName(), - mat); + mat + ); if (shape.isNull()) { - Base::Console().log("Part::MeasureClient::getLocatedShape: Did not retrieve shape for %s, %s\n", obj->getNameInDocument(), subject.getElementName()); + Base::Console().log( + "Part::MeasureClient::getLocatedShape: Did not retrieve shape for %s, %s\n", + obj->getNameInDocument(), + subject.getElementName() + ); return {}; } - auto placement = App::GeoFeature::getGlobalPlacement(obj, subject.getObject(), subject.getSubName()); + auto placement + = App::GeoFeature::getGlobalPlacement(obj, subject.getObject(), subject.getSubName()); shape.setPlacement(placement); // Don't get the subShape from datum elements @@ -140,15 +148,20 @@ App::MeasureElementType PartMeasureTypeCb(App::DocumentObject* ob, const char* s return curve->NbPoles() == 2; }; - TopoDS_Shape shape = Part::Feature::getShape(ob, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subName); + TopoDS_Shape shape = Part::Feature::getShape( + ob, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subName + ); if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().message("Part::PartMeasureTypeCb did not retrieve shape for %s, %s\n", ob->getNameInDocument(), subName); + Base::Console().message( + "Part::PartMeasureTypeCb did not retrieve shape for %s, %s\n", + ob->getNameInDocument(), + subName + ); return App::MeasureElementType(); } TopAbs_ShapeEnum shapeType = shape.ShapeType(); @@ -171,20 +184,22 @@ App::MeasureElementType PartMeasureTypeCb(App::DocumentObject* ob, const char* s } case GeomAbs_BezierCurve: { return isStraightBezierCurve(curve.Bezier()) - ? App::MeasureElementType::LINESEGMENT - : App::MeasureElementType::CURVE; + ? App::MeasureElementType::LINESEGMENT + : App::MeasureElementType::CURVE; } case GeomAbs_BSplineCurve: { return isStraightBSplineCurve(curve.BSpline()) - ? App::MeasureElementType::LINESEGMENT - : App::MeasureElementType::CURVE; + ? App::MeasureElementType::LINESEGMENT + : App::MeasureElementType::CURVE; } case GeomAbs_Ellipse: case GeomAbs_Hyperbola: case GeomAbs_Parabola: { return App::MeasureElementType::CURVE; } - default: { return App::MeasureElementType::INVALID; } + default: { + return App::MeasureElementType::INVALID; + } } } case TopAbs_FACE: { @@ -220,19 +235,20 @@ App::MeasureElementType PartMeasureTypeCb(App::DocumentObject* ob, const char* s } -bool getShapeFromStrings(TopoDS_Shape &shapeOut, const App::SubObjectT& subject, Base::Matrix4D *mat) +bool getShapeFromStrings(TopoDS_Shape& shapeOut, const App::SubObjectT& subject, Base::Matrix4D* mat) { - App::DocumentObject *obj = subject.getObject(); + App::DocumentObject* obj = subject.getObject(); if (!obj) { return {}; - } - shapeOut = Part::Feature::getShape(obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subject.getElementName(), - mat); - return !shapeOut.IsNull(); + } + shapeOut = Part::Feature::getShape( + obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subject.getElementName(), + mat + ); + return !shapeOut.IsNull(); } @@ -243,46 +259,46 @@ Part::VectorAdapter buildAdapter(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().message("Part::buildAdapter did not retrieve shape for %s, %s\n", - subject.getObjectName(), subject.getElementName()); + Base::Console().message( + "Part::buildAdapter did not retrieve shape for %s, %s\n", + subject.getObjectName(), + subject.getElementName() + ); return Part::VectorAdapter(); } TopAbs_ShapeEnum shapeType = shape.ShapeType(); - if (shapeType == TopAbs_EDGE) - { - TopoDS_Edge edge = TopoDS::Edge(shape); - // make edge orientation so that end of edge closest to pick is head of vector. - TopoDS_Vertex firstVertex = TopExp::FirstVertex(edge, Standard_True); - TopoDS_Vertex lastVertex = TopExp::LastVertex(edge, Standard_True); - if (firstVertex.IsNull() || lastVertex.IsNull()) { - return {}; - } - gp_Vec firstPoint = Part::VectorAdapter::convert(firstVertex); - gp_Vec lastPoint = Part::VectorAdapter::convert(lastVertex); - Base::Vector3d v(0.0, 0.0, 0.0); //v(current.x,current.y,current.z); - v = mat*v; - gp_Vec pickPoint(v.x, v.y, v.z); - double firstDistance = (firstPoint - pickPoint).Magnitude(); - double lastDistance = (lastPoint - pickPoint).Magnitude(); - if (lastDistance > firstDistance) - { - if (edge.Orientation() == TopAbs_FORWARD) { - edge.Orientation(TopAbs_REVERSED); + if (shapeType == TopAbs_EDGE) { + TopoDS_Edge edge = TopoDS::Edge(shape); + // make edge orientation so that end of edge closest to pick is head of vector. + TopoDS_Vertex firstVertex = TopExp::FirstVertex(edge, Standard_True); + TopoDS_Vertex lastVertex = TopExp::LastVertex(edge, Standard_True); + if (firstVertex.IsNull() || lastVertex.IsNull()) { + return {}; } - else { - edge.Orientation(TopAbs_FORWARD); + gp_Vec firstPoint = Part::VectorAdapter::convert(firstVertex); + gp_Vec lastPoint = Part::VectorAdapter::convert(lastVertex); + Base::Vector3d v(0.0, 0.0, 0.0); // v(current.x,current.y,current.z); + v = mat * v; + gp_Vec pickPoint(v.x, v.y, v.z); + double firstDistance = (firstPoint - pickPoint).Magnitude(); + double lastDistance = (lastPoint - pickPoint).Magnitude(); + if (lastDistance > firstDistance) { + if (edge.Orientation() == TopAbs_FORWARD) { + edge.Orientation(TopAbs_REVERSED); + } + else { + edge.Orientation(TopAbs_FORWARD); + } } - } - return {edge, pickPoint}; + return {edge, pickPoint}; } - if (shapeType == TopAbs_FACE) - { - TopoDS_Face face = TopoDS::Face(shape); - Base::Vector3d vTemp(0.0, 0.0, 0.0); //v(current.x, current.y, current.z); - vTemp = mat*vTemp; - gp_Vec pickPoint(vTemp.x, vTemp.y, vTemp.z); - return {face, pickPoint}; + if (shapeType == TopAbs_FACE) { + TopoDS_Face face = TopoDS::Face(shape); + Base::Vector3d vTemp(0.0, 0.0, 0.0); // v(current.x, current.y, current.z); + vTemp = mat * vTemp; + gp_Vec pickPoint(vTemp.x, vTemp.y, vTemp.z); + return {face, pickPoint}; } return {}; @@ -295,8 +311,11 @@ MeasureLengthInfoPtr MeasureLengthHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().message("MeasureLengthHandler did not retrieve shape for %s, %s\n", - subject.getObjectName(), subject.getElementName()); + Base::Console().message( + "MeasureLengthHandler did not retrieve shape for %s, %s\n", + subject.getObjectName(), + subject.getElementName() + ); return std::make_shared(false, 0.0, Base::Matrix4D()); } TopAbs_ShapeEnum sType = shape.ShapeType(); @@ -316,18 +335,18 @@ MeasureLengthInfoPtr MeasureLengthHandler(const App::SubObjectT& subject) MeasureRadiusInfoPtr MeasureRadiusHandler(const App::SubObjectT& subject) { - Base::Placement placement; // curve center + orientation + Base::Placement placement; // curve center + orientation Base::Vector3d pointOnCurve; TopoDS_Shape shape = getLocatedShape(subject); if (shape.IsNull()) { - return std::make_shared( false, 0.0, pointOnCurve, placement); + return std::make_shared(false, 0.0, pointOnCurve, placement); } - TopAbs_ShapeEnum sType = shape.ShapeType(); + TopAbs_ShapeEnum sType = shape.ShapeType(); if (sType != TopAbs_EDGE) { - return std::make_shared( false, 0.0, pointOnCurve, placement); + return std::make_shared(false, 0.0, pointOnCurve, placement); } // Get Center of mass as the attachment point of the label @@ -346,7 +365,7 @@ MeasureRadiusInfoPtr MeasureRadiusHandler(const App::SubObjectT& subject) placement = Base::Placement(Base::Vector3d(origin.X(), origin.Y(), origin.Z()), rot); - return std::make_shared( true, getRadius(shape), pointOnCurve, placement); + return std::make_shared(true, getRadius(shape), pointOnCurve, placement); } @@ -356,8 +375,11 @@ MeasureAreaInfoPtr MeasureAreaHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().message("MeasureAreaHandler did not retrieve shape for %s, %s\n", - subject.getObjectName(), subject.getElementName()); + Base::Console().message( + "MeasureAreaHandler did not retrieve shape for %s, %s\n", + subject.getObjectName(), + subject.getElementName() + ); return std::make_shared(false, 0.0, Base::Matrix4D()); } TopAbs_ShapeEnum sType = shape.ShapeType(); @@ -371,7 +393,8 @@ MeasureAreaInfoPtr MeasureAreaHandler(const App::SubObjectT& subject) BRepGProp::SurfaceProperties(shape, gprops); auto origin = gprops.CentreOfMass(); - // TODO: Center of Mass might not lie on the surface, somehow snap to the closest point on the surface? + // TODO: Center of Mass might not lie on the surface, somehow snap to the closest point on the + // surface? Base::Placement placement(Base::Vector3d(origin.X(), origin.Y(), origin.Z()), Base::Rotation()); return std::make_shared(true, getFaceArea(shape), placement); @@ -383,8 +406,11 @@ MeasurePositionInfoPtr MeasurePositionHandler(const App::SubObjectT& subject) TopoDS_Shape shape = getLocatedShape(subject); if (shape.IsNull()) { - Base::Console().message("MeasurePositionHandler did not retrieve shape for %s, %s\n", - subject.getObjectName(), subject.getElementName()); + Base::Console().message( + "MeasurePositionHandler did not retrieve shape for %s, %s\n", + subject.getObjectName(), + subject.getElementName() + ); return std::make_shared(false, Base::Vector3d()); } TopAbs_ShapeEnum sType = shape.ShapeType(); @@ -395,7 +421,7 @@ MeasurePositionInfoPtr MeasurePositionHandler(const App::SubObjectT& subject) TopoDS_Vertex vertex = TopoDS::Vertex(shape); auto point = BRep_Tool::Pnt(vertex); - return std::make_shared( true, Base::Vector3d(point.X(), point.Y(), point.Z())); + return std::make_shared(true, Base::Vector3d(point.X(), point.Y(), point.Z())); } @@ -405,8 +431,11 @@ MeasureAngleInfoPtr MeasureAngleHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().message("MeasureAngleHandler did not retrieve shape for %s, %s\n", - subject.getObjectName(), subject.getElementName()); + Base::Console().message( + "MeasureAngleHandler did not retrieve shape for %s, %s\n", + subject.getObjectName(), + subject.getElementName() + ); return std::make_shared(); } @@ -422,8 +451,8 @@ MeasureAngleInfoPtr MeasureAngleHandler(const App::SubObjectT& subject) GProp_GProps gprops; BRepGProp::SurfaceProperties(face, gprops); vec = gprops.CentreOfMass(); - - } else if (sType == TopAbs_EDGE) { + } + else if (sType == TopAbs_EDGE) { TopoDS_Edge edge = TopoDS::Edge(shape); GProp_GProps gprops; @@ -444,8 +473,11 @@ MeasureDistanceInfoPtr MeasureDistanceHandler(const App::SubObjectT& subject) if (shape.IsNull()) { // failure here on loading document with existing measurement. - Base::Console().message("MeasureDistanceHandler did not retrieve shape for %s, %s\n", - subject.getObjectName(), subject.getElementName()); + Base::Console().message( + "MeasureDistanceHandler did not retrieve shape for %s, %s\n", + subject.getObjectName(), + subject.getElementName() + ); return std::make_shared(); } @@ -455,9 +487,9 @@ MeasureDistanceInfoPtr MeasureDistanceHandler(const App::SubObjectT& subject) } -void Part::MeasureClient::initialize() { +void Part::MeasureClient::initialize() +{ App::MeasureManager::addMeasureHandler("Part", PartMeasureTypeCb); - } Part::CallbackRegistrationList Part::MeasureClient::reportLengthCB() diff --git a/src/Mod/Part/App/MeasureClient.h b/src/Mod/Part/App/MeasureClient.h index 35110dcb9f..8b3cb2932b 100644 --- a/src/Mod/Part/App/MeasureClient.h +++ b/src/Mod/Part/App/MeasureClient.h @@ -29,7 +29,6 @@ #include "MeasureInfo.h" - namespace Part { @@ -37,7 +36,6 @@ namespace Part class PartExport MeasureClient { public: - static void initialize(); static CallbackRegistrationList reportLengthCB(); @@ -49,6 +47,6 @@ public: }; -} //namespace Part +} // namespace Part #endif diff --git a/src/Mod/Part/App/MeasureInfo.h b/src/Mod/Part/App/MeasureInfo.h index 30482a1b89..c605c327c0 100644 --- a/src/Mod/Part/App/MeasureInfo.h +++ b/src/Mod/Part/App/MeasureInfo.h @@ -39,7 +39,8 @@ #include #include -namespace Part { +namespace Part +{ class MeasureInfo; using MeasureInfoPtr = std::shared_ptr; @@ -57,95 +58,130 @@ class MeasureRadiusInfo; using MeasureRadiusInfoPtr = std::shared_ptr; -class PartExport MeasureInfo { +class PartExport MeasureInfo +{ public: // making the destructor virtual so MeasureInfo is polymorphic MeasureInfo() = default; - MeasureInfo(bool val) : valid(val) {} + MeasureInfo(bool val) + : valid(val) + {} virtual ~MeasureInfo() = default; - bool valid{false}; + bool valid {false}; }; -class PartExport MeasureAngleInfo : public MeasureInfo { +class PartExport MeasureAngleInfo: public MeasureInfo +{ public: MeasureAngleInfo() = default; - MeasureAngleInfo(bool val, Base::Vector3d orient, Base::Vector3d pos) : - MeasureInfo(val), orientation(orient), position(pos) {} + MeasureAngleInfo(bool val, Base::Vector3d orient, Base::Vector3d pos) + : MeasureInfo(val) + , orientation(orient) + , position(pos) + {} ~MeasureAngleInfo() override = default; - Base::Vector3d orientation{0.0, 0.0, 0.0}; - Base::Vector3d position{0.0, 0.0, 0.0}; + Base::Vector3d orientation {0.0, 0.0, 0.0}; + Base::Vector3d position {0.0, 0.0, 0.0}; }; -class PartExport MeasureAreaInfo : public MeasureInfo { +class PartExport MeasureAreaInfo: public MeasureInfo +{ public: MeasureAreaInfo() = default; - MeasureAreaInfo(bool val, double a2, Base::Placement plm) : - MeasureInfo(val), area(a2), placement(plm) {} + MeasureAreaInfo(bool val, double a2, Base::Placement plm) + : MeasureInfo(val) + , area(a2) + , placement(plm) + {} ~MeasureAreaInfo() override = default; - double area{0}; - Base::Placement placement{}; + double area {0}; + Base::Placement placement {}; }; // Translate geometry reference into an OCC type -class PartExport MeasureDistanceInfo : public MeasureInfo { +class PartExport MeasureDistanceInfo: public MeasureInfo +{ public: MeasureDistanceInfo() = default; - explicit MeasureDistanceInfo(bool val, const TopoDS_Shape& shp) : - MeasureInfo(val), shape(shp) {} + explicit MeasureDistanceInfo(bool val, const TopoDS_Shape& shp) + : MeasureInfo(val) + , shape(shp) + {} ~MeasureDistanceInfo() override = default; - const TopoDS_Shape& getShape() { return shape; } + const TopoDS_Shape& getShape() + { + return shape; + } private: TopoDS_Shape shape; }; -class PartExport MeasureLengthInfo : public MeasureInfo { +class PartExport MeasureLengthInfo: public MeasureInfo +{ public: MeasureLengthInfo() = default; - MeasureLengthInfo(bool val, double len, Base::Placement plm) : - MeasureInfo(val), length(len), placement(plm) {} + MeasureLengthInfo(bool val, double len, Base::Placement plm) + : MeasureInfo(val) + , length(len) + , placement(plm) + {} ~MeasureLengthInfo() override = default; - double length{0}; - Base::Placement placement{}; + double length {0}; + Base::Placement placement {}; }; -class PartExport MeasurePositionInfo : public MeasureInfo { +class PartExport MeasurePositionInfo: public MeasureInfo +{ public: MeasurePositionInfo() = default; - MeasurePositionInfo(bool val, Base::Vector3d pos) : - MeasureInfo(val), position(pos) {} + MeasurePositionInfo(bool val, Base::Vector3d pos) + : MeasureInfo(val) + , position(pos) + {} ~MeasurePositionInfo() override = default; - Base::Vector3d position{0.0, 0.0, 0.0}; + Base::Vector3d position {0.0, 0.0, 0.0}; }; -class PartExport MeasureRadiusInfo : public MeasureInfo { +class PartExport MeasureRadiusInfo: public MeasureInfo +{ public: MeasureRadiusInfo() = default; - MeasureRadiusInfo(bool val, double rad, Base::Vector3d point, Base::Placement plm) : - MeasureInfo(val), radius(rad), pointOnCurve(point), placement(plm) {} + MeasureRadiusInfo(bool val, double rad, Base::Vector3d point, Base::Placement plm) + : MeasureInfo(val) + , radius(rad) + , pointOnCurve(point) + , placement(plm) + {} ~MeasureRadiusInfo() override = default; - double radius{}; + double radius {}; Base::Vector3d pointOnCurve; Base::Placement placement; // curve center & circle orientation }; //! callback registrations // TODO: is there more that one place that GeometryHandler is defined? - using GeometryHandler = std::function; +using GeometryHandler = std::function; class PartExport CallbackRegistrationRecord { public: CallbackRegistrationRecord() = default; - CallbackRegistrationRecord(const std::string& module, const std::string& measureType, GeometryHandler callback) : - m_module(module), m_measureType(measureType), m_callback(callback) - { } + CallbackRegistrationRecord( + const std::string& module, + const std::string& measureType, + GeometryHandler callback + ) + : m_module(module) + , m_measureType(measureType) + , m_callback(callback) + {} std::string m_module; std::string m_measureType; @@ -154,6 +190,6 @@ public: using CallbackRegistrationList = std::vector; -} //end namespace Part +} // end namespace Part #endif diff --git a/src/Mod/Part/App/OCAF/ImportExportSettings.cpp b/src/Mod/Part/App/OCAF/ImportExportSettings.cpp index 762df4385c..816d9348b1 100644 --- a/src/Mod/Part/App/OCAF/ImportExportSettings.cpp +++ b/src/Mod/Part/App/OCAF/ImportExportSettings.cpp @@ -31,14 +31,19 @@ #include -namespace Part { -namespace OCAF { +namespace Part +{ +namespace OCAF +{ void ImportExportSettings::initialize() { // set the user-defined settings - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/Part"); initGeneral(hGrp); initSTEP(hGrp); initIGES(hGrp); @@ -50,51 +55,52 @@ void ImportExportSettings::initGeneral(Base::Reference hGrp) Base::Reference hGenGrp = hGrp->GetGroup("General"); // http://www.opencascade.org/org/forum/thread_20801/ // read.surfacecurve.mode: - // A preference for the computation of curves in an entity which has both 2D and 3D representation. - // Each TopoDS_Edge in TopoDS_Face must have a 3D and 2D curve that references the surface. - // If both 2D and 3D representation of the entity are present, the computation of these curves depends on - // the following values of parameter: - // 0: "Default" - no preference, both curves are taken - // 3: "3DUse_Preferred" - 3D curves are used to rebuild 2D ones - // Additional modes for IGES + // A preference for the computation of curves in an entity which has both 2D and 3D + // representation. Each TopoDS_Edge in TopoDS_Face must have a 3D and 2D curve that references + // the surface. If both 2D and 3D representation of the entity are present, the computation of + // these curves depends on the following values of parameter: 0: "Default" - no preference, both + // curves are taken 3: "3DUse_Preferred" - 3D curves are used to rebuild 2D ones Additional + // modes for IGES // 2: "2DUse_Preferred" - the 2D is used to rebuild the 3D in case of their inconsistency - // -2: "2DUse_Forced" - the 2D is always used to rebuild the 3D (even if 2D is present in the file) - // -3: "3DUse_Forced" - the 3D is always used to rebuild the 2D (even if 2D is present in the file) + // -2: "2DUse_Forced" - the 2D is always used to rebuild the 3D (even if 2D is present in the + // file) -3: "3DUse_Forced" - the 3D is always used to rebuild the 2D (even if 2D is present in + // the file) int readsurfacecurve = hGenGrp->GetInt("ReadSurfaceCurveMode", 0); Interface_Static::SetIVal("read.surfacecurve.mode", readsurfacecurve); // write.surfacecurve.mode (STEP-only): - // This parameter indicates whether parametric curves (curves in parametric space of surface) should be - // written into the STEP file. This parameter can be set to Off in order to minimize the size of the resulting - // STEP file. - // Off (0) : writes STEP files without pcurves. This mode decreases the size of the resulting file. - // On (1) : (default) writes pcurves to STEP file + // This parameter indicates whether parametric curves (curves in parametric space of surface) + // should be written into the STEP file. This parameter can be set to Off in order to minimize + // the size of the resulting STEP file. Off (0) : writes STEP files without pcurves. This mode + // decreases the size of the resulting file. On (1) : (default) writes pcurves to STEP file int writesurfacecurve = hGenGrp->GetInt("WriteSurfaceCurveMode", 0); Interface_Static::SetIVal("write.surfacecurve.mode", writesurfacecurve); } void ImportExportSettings::initIGES(Base::Reference hGrp) { - //IGES handling + // IGES handling Base::Reference hIgesGrp = hGrp->GetGroup("IGES"); int value = Interface_Static::IVal("write.iges.brep.mode"); bool brep = hIgesGrp->GetBool("BrepMode", value > 0); - Interface_Static::SetIVal("write.iges.brep.mode",brep ? 1 : 0); + Interface_Static::SetIVal("write.iges.brep.mode", brep ? 1 : 0); Interface_Static::SetCVal("write.iges.header.company", hIgesGrp->GetASCII("Company").c_str()); Interface_Static::SetCVal("write.iges.header.author", hIgesGrp->GetASCII("Author").c_str()); - Interface_Static::SetCVal("write.iges.header.product", hIgesGrp->GetASCII("Product", - Interface_Static::CVal("write.iges.header.product")).c_str()); + Interface_Static::SetCVal( + "write.iges.header.product", + hIgesGrp->GetASCII("Product", Interface_Static::CVal("write.iges.header.product")).c_str() + ); int unitIges = hIgesGrp->GetInt("Unit", 0); switch (unitIges) { case 1: - Interface_Static::SetCVal("write.iges.unit","M"); + Interface_Static::SetCVal("write.iges.unit", "M"); break; case 2: - Interface_Static::SetCVal("write.iges.unit","INCH"); + Interface_Static::SetCVal("write.iges.unit", "INCH"); break; default: - Interface_Static::SetCVal("write.iges.unit","MM"); + Interface_Static::SetCVal("write.iges.unit", "MM"); break; } } @@ -126,30 +132,34 @@ std::list ImportExportSettings::getCodePageList( void ImportExportSettings::initSTEP(Base::Reference hGrp) { - //STEP handling + // STEP handling Base::Reference hStepGrp = hGrp->GetGroup("STEP"); int unitStep = hStepGrp->GetInt("Unit", 0); switch (unitStep) { case 1: - Interface_Static::SetCVal("write.step.unit","M"); + Interface_Static::SetCVal("write.step.unit", "M"); break; case 2: - Interface_Static::SetCVal("write.step.unit","INCH"); + Interface_Static::SetCVal("write.step.unit", "INCH"); break; default: - Interface_Static::SetCVal("write.step.unit","MM"); + Interface_Static::SetCVal("write.step.unit", "MM"); break; } std::string ap = hStepGrp->GetASCII("Scheme", Interface_Static::CVal("write.step.schema")); Interface_Static::SetCVal("write.step.schema", ap.c_str()); - Interface_Static::SetCVal("write.step.product.name", hStepGrp->GetASCII("Product", - Interface_Static::CVal("write.step.product.name")).c_str()); + Interface_Static::SetCVal( + "write.step.product.name", + hStepGrp->GetASCII("Product", Interface_Static::CVal("write.step.product.name")).c_str() + ); } ImportExportSettings::ImportExportSettings() { - pGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Import"); + pGroup = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Import" + ); } STEP::ImportExportSettingsPtr ImportExportSettings::getSTEPSettings() const @@ -282,5 +292,5 @@ ImportExportSettings::ImportMode ImportExportSettings::getImportMode() const return static_cast(pGroup->GetInt("ImportMode", 0)); } -} // namespace OCAF -} // namespace Part +} // namespace OCAF +} // namespace Part diff --git a/src/Mod/Part/App/OCAF/ImportExportSettings.h b/src/Mod/Part/App/OCAF/ImportExportSettings.h index 180a34cf50..494b313d21 100644 --- a/src/Mod/Part/App/OCAF/ImportExportSettings.h +++ b/src/Mod/Part/App/OCAF/ImportExportSettings.h @@ -36,15 +36,17 @@ namespace Part { -namespace STEP { +namespace STEP +{ class ImportExportSettings; using ImportExportSettingsPtr = std::shared_ptr; -} +} // namespace STEP -namespace IGES { +namespace IGES +{ class ImportExportSettings; using ImportExportSettingsPtr = std::shared_ptr; -} +} // namespace IGES namespace OCAF { @@ -52,14 +54,16 @@ namespace OCAF class PartExport ImportExportSettings { public: - enum class ImportMode { + enum class ImportMode + { SingleDocument = 0, GroupPerDocument = 1, GroupPerDirectory = 2, ObjectPerDocument = 3, ObjectPerDirectory = 4, }; - struct CodePage { + struct CodePage + { std::string codePageName; Resource_FormatType codePage; }; @@ -150,7 +154,7 @@ private: // clang-format on }; -} //namespace OCAF -} //namespace Part +} // namespace OCAF +} // namespace Part #endif diff --git a/src/Mod/Part/App/OCCError.h b/src/Mod/Part/App/OCCError.h index 786c9bc1fc..af7839e9e2 100644 --- a/src/Mod/Part/App/OCCError.h +++ b/src/Mod/Part/App/OCCError.h @@ -25,14 +25,15 @@ #ifndef _OCCError_h_ #define _OCCError_h_ -# include -# include +#include +#include #include #include -namespace Part { +namespace Part +{ PartExport extern PyObject* PartExceptionOCCError; PartExport extern PyObject* PartExceptionOCCDomainError; PartExport extern PyObject* PartExceptionOCCRangeError; @@ -40,22 +41,26 @@ PartExport extern PyObject* PartExceptionOCCConstructionError; PartExport extern PyObject* PartExceptionOCCDimensionError; -#define PY_TRY try +#define PY_TRY try /// see docu of PY_TRY -# define _PY_CATCH_OCC(R) \ - catch (Standard_Failure &e) \ - { \ - std::string str; \ - Standard_CString msg = e.GetMessageString(); \ - str += typeid(e).name(); \ - str += " "; \ - if (msg) {str += msg;} \ - else {str += "No OCCT Exception Message";} \ - _Py_Error(R,Part::PartExceptionOCCError,str.c_str()); \ - } \ +#define _PY_CATCH_OCC(R) \ + catch (Standard_Failure & e) \ + { \ + std::string str; \ + Standard_CString msg = e.GetMessageString(); \ + str += typeid(e).name(); \ + str += " "; \ + if (msg) { \ + str += msg; \ + } \ + else { \ + str += "No OCCT Exception Message"; \ + } \ + _Py_Error(R, Part::PartExceptionOCCError, str.c_str()); \ + } \ _PY_CATCH(R) -} //namespace Part +} // namespace Part -#define PY_CATCH_OCC _PY_CATCH_OCC(return(NULL)) +#define PY_CATCH_OCC _PY_CATCH_OCC(return (NULL)) #endif // _OCCError_h_ diff --git a/src/Mod/Part/App/OCCTProgressIndicator.h b/src/Mod/Part/App/OCCTProgressIndicator.h index 203aa54193..ab95e25d7f 100644 --- a/src/Mod/Part/App/OCCTProgressIndicator.h +++ b/src/Mod/Part/App/OCCTProgressIndicator.h @@ -29,22 +29,26 @@ #include -namespace Part { +namespace Part +{ -class PartExport OCCTProgressIndicator : public Message_ProgressIndicator +class PartExport OCCTProgressIndicator: public Message_ProgressIndicator { Base::ProgressIndicator& baseIndicator; public: OCCTProgressIndicator(Base::ProgressIndicator& indicator) - : baseIndicator(indicator) {} + : baseIndicator(indicator) + {} - Standard_Boolean UserBreak() override { + Standard_Boolean UserBreak() override + { return baseIndicator.userBreak(); } - void Show(const Message_ProgressScope& scope, const Standard_Boolean isForce) override { - float pos = -1; // negative means indeterminate + void Show(const Message_ProgressScope& scope, const Standard_Boolean isForce) override + { + float pos = -1; // negative means indeterminate if (!scope.IsInfinite()) { pos = static_cast(GetPosition()); } @@ -52,7 +56,8 @@ public: baseIndicator.show(pos, isForce ? ShowFlags::Force : ShowFlags::None); } - static OCCTProgressIndicator getAppIndicator() { + static OCCTProgressIndicator getAppIndicator() + { return {App::GetApplication().getProgressIndicator()}; } }; @@ -63,11 +68,15 @@ public: class Message_ProgressRange { public: - bool UserBreak() { return false; } - void Show([[maybe_unused]] float position, [[maybe_unused]] bool isForce) {} + bool UserBreak() + { + return false; + } + void Show([[maybe_unused]] float position, [[maybe_unused]] bool isForce) + {} }; #endif -} // namespace Part +} // namespace Part -#endif // PART_OCCTPROGRESSINDICATOR_H +#endif // PART_OCCTPROGRESSINDICATOR_H diff --git a/src/Mod/Part/App/OffsetCurve.pyi b/src/Mod/Part/App/OffsetCurve.pyi index 367e9e7e9a..4c50a5343b 100644 --- a/src/Mod/Part/App/OffsetCurve.pyi +++ b/src/Mod/Part/App/OffsetCurve.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from GeometryCurve import GeometryCurve from typing import Final - @export( PythonName="Part.OffsetCurve", Twin="GeomOffsetCurve", diff --git a/src/Mod/Part/App/OffsetCurvePyImp.cpp b/src/Mod/Part/App/OffsetCurvePyImp.cpp index b734f36ed2..a21097cc34 100644 --- a/src/Mod/Part/App/OffsetCurvePyImp.cpp +++ b/src/Mod/Part/App/OffsetCurvePyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -43,7 +43,7 @@ std::string OffsetCurvePy::representation() const return ""; } -PyObject *OffsetCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* OffsetCurvePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of OffsetCurvePy and the Twin object return new OffsetCurvePy(new GeomOffsetCurve); @@ -55,15 +55,20 @@ int OffsetCurvePy::PyInit(PyObject* args, PyObject* /*kwd*/) PyObject* pGeom; PyObject* pDir; double offset; - if (!PyArg_ParseTuple(args, "O!dO!", - &(GeometryPy::Type), &pGeom, - &offset, - &(Base::VectorPy::Type),&pDir)) + if (!PyArg_ParseTuple( + args, + "O!dO!", + &(GeometryPy::Type), + &pGeom, + &offset, + &(Base::VectorPy::Type), + &pDir + )) { return -1; + } GeometryPy* pcGeo = static_cast(pGeom); - Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a curve"); return -1; @@ -71,7 +76,8 @@ int OffsetCurvePy::PyInit(PyObject* args, PyObject* /*kwd*/) try { Base::Vector3d dir = static_cast(pDir)->value(); - Handle(Geom_OffsetCurve) curve2 = new Geom_OffsetCurve(curve, offset, gp_Dir(dir.x,dir.y,dir.z)); + Handle(Geom_OffsetCurve) curve2 + = new Geom_OffsetCurve(curve, offset, gp_Dir(dir.x, dir.y, dir.z)); getGeomOffsetCurvePtr()->setHandle(curve2); return 0; } @@ -98,7 +104,7 @@ Py::Object OffsetCurvePy::getOffsetDirection() const { Handle(Geom_OffsetCurve) curve = Handle(Geom_OffsetCurve)::DownCast(getGeometryPtr()->handle()); const gp_Dir& dir = curve->Direction(); - return Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z())); + return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } void OffsetCurvePy::setOffsetDirection(Py::Object arg) @@ -107,12 +113,12 @@ void OffsetCurvePy::setOffsetDirection(Py::Object arg) if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d dir = static_cast(p)->value(); Handle(Geom_OffsetCurve) curve = Handle(Geom_OffsetCurve)::DownCast(getGeometryPtr()->handle()); - curve->SetDirection(gp_Dir(dir.x,dir.y,dir.z)); + curve->SetDirection(gp_Dir(dir.x, dir.y, dir.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d dir = Base::getVectorFromTuple(p); Handle(Geom_OffsetCurve) curve = Handle(Geom_OffsetCurve)::DownCast(getGeometryPtr()->handle()); - curve->SetDirection(gp_Dir(dir.x,dir.y,dir.z)); + curve->SetDirection(gp_Dir(dir.x, dir.y, dir.z)); } else { std::string error = std::string("type must be 'Vector', not "); @@ -134,24 +140,24 @@ void OffsetCurvePy::setBasisCurve(Py::Object arg) PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(GeometryPy::Type))) { GeometryPy* pcGeo = static_cast(p); - Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { throw Py::TypeError("geometry is not a curve"); } try { - Handle(Geom_OffsetCurve) curve2 = Handle(Geom_OffsetCurve)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_OffsetCurve) curve2 = Handle(Geom_OffsetCurve)::DownCast( + getGeometryPtr()->handle() + ); curve2->SetBasisCurve(curve); } catch (Standard_Failure& e) { - throw Py::RuntimeError(e.GetMessageString()); + throw Py::RuntimeError(e.GetMessageString()); } } } -PyObject *OffsetCurvePy::getCustomAttributes(const char* /*attr*/) const +PyObject* OffsetCurvePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/OffsetSurface.pyi b/src/Mod/Part/App/OffsetSurface.pyi index 4c25fe54a5..8266243613 100644 --- a/src/Mod/Part/App/OffsetSurface.pyi +++ b/src/Mod/Part/App/OffsetSurface.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from GeometrySurface import GeometrySurface - @export( Twin="GeomOffsetSurface", TwinPointer="GeomOffsetSurface", diff --git a/src/Mod/Part/App/OffsetSurfacePyImp.cpp b/src/Mod/Part/App/OffsetSurfacePyImp.cpp index 970555e504..0c7bb86f62 100644 --- a/src/Mod/Part/App/OffsetSurfacePyImp.cpp +++ b/src/Mod/Part/App/OffsetSurfacePyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include "OCCError.h" @@ -39,7 +39,7 @@ std::string OffsetSurfacePy::representation() const return ""; } -PyObject *OffsetSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* OffsetSurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of OffsetSurfacePy and the Twin object return new OffsetSurfacePy(new GeomOffsetSurface); @@ -50,14 +50,12 @@ int OffsetSurfacePy::PyInit(PyObject* args, PyObject* /*kwd*/) { PyObject* pGeom; double offset; - if (!PyArg_ParseTuple(args, "O!d", - &(GeometryPy::Type), &pGeom, - &offset)) + if (!PyArg_ParseTuple(args, "O!d", &(GeometryPy::Type), &pGeom, &offset)) { return -1; + } GeometryPy* pcGeo = static_cast(pGeom); - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(pcGeo->getGeometryPtr()->handle()); if (surf.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a surface"); return -1; @@ -81,7 +79,7 @@ Py::Float OffsetSurfacePy::getOffsetValue() const return Py::Float(surf->Offset()); } -void OffsetSurfacePy::setOffsetValue(Py::Float arg) +void OffsetSurfacePy::setOffsetValue(Py::Float arg) { Handle(Geom_OffsetSurface) surf = Handle(Geom_OffsetSurface)::DownCast(getGeometryPtr()->handle()); surf->SetOffsetValue((double)arg); @@ -89,8 +87,7 @@ void OffsetSurfacePy::setOffsetValue(Py::Float arg) Py::Object OffsetSurfacePy::getBasisSurface() const { - Handle(Geom_OffsetSurface) surf = Handle(Geom_OffsetSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_OffsetSurface) surf = Handle(Geom_OffsetSurface)::DownCast(getGeometryPtr()->handle()); if (surf.IsNull()) { throw Py::TypeError("geometry is not a surface"); } @@ -99,20 +96,20 @@ Py::Object OffsetSurfacePy::getBasisSurface() const return Py::asObject(geo->getPyObject()); } -void OffsetSurfacePy::setBasisSurface(Py::Object arg) +void OffsetSurfacePy::setBasisSurface(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(GeometryPy::Type))) { GeometryPy* pcGeo = static_cast(p); - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(pcGeo->getGeometryPtr()->handle()); if (surf.IsNull()) { throw Py::TypeError("geometry is not a surface"); } try { - Handle(Geom_OffsetSurface) surf2 = Handle(Geom_OffsetSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_OffsetSurface) surf2 = Handle(Geom_OffsetSurface)::DownCast( + getGeometryPtr()->handle() + ); surf2->SetBasisSurface(surf); } catch (Standard_Failure& e) { @@ -121,7 +118,7 @@ void OffsetSurfacePy::setBasisSurface(Py::Object arg) } } -PyObject *OffsetSurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* OffsetSurfacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/OpenCascadeAll.h b/src/Mod/Part/App/OpenCascadeAll.h index 9279c5b99f..dd6cb34330 100644 --- a/src/Mod/Part/App/OpenCascadeAll.h +++ b/src/Mod/Part/App/OpenCascadeAll.h @@ -31,7 +31,7 @@ #include #include #if OCC_VERSION_HEX < 0x070800 -#include +# include #endif #include #include @@ -47,7 +47,7 @@ #include #include #if OCC_VERSION_HEX < 0x070800 -#include +# include #endif #include #include @@ -117,16 +117,16 @@ #include #include -//#include +// #include #include -//#include +// #include #include -//#include +// #include #include -# include -//#include +#include +// #include #include -//#include +// #include #include #include @@ -411,7 +411,7 @@ #include #if OCC_VERSION_HEX < 0x070700 -#include +# include #endif #include @@ -516,4 +516,4 @@ #include #include -#endif // __OpenCascadeAll__ +#endif // __OpenCascadeAll__ diff --git a/src/Mod/Part/App/Parabola.pyi b/src/Mod/Part/App/Parabola.pyi index fc95a37bc1..096b42c475 100644 --- a/src/Mod/Part/App/Parabola.pyi +++ b/src/Mod/Part/App/Parabola.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from Conic import Conic from typing import Final - @export( Twin="GeomParabola", TwinPointer="GeomParabola", diff --git a/src/Mod/Part/App/ParabolaPyImp.cpp b/src/Mod/Part/App/ParabolaPyImp.cpp index 58b2648455..8f19ecf823 100644 --- a/src/Mod/Part/App/ParabolaPyImp.cpp +++ b/src/Mod/Part/App/ParabolaPyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -45,7 +45,7 @@ std::string ParabolaPy::representation() const return ""; } -PyObject *ParabolaPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ParabolaPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ParabolaPy and the Twin object return new ParabolaPy(new GeomParabola); @@ -54,77 +54,101 @@ PyObject *ParabolaPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // P // constructor method int ParabolaPy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { - Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast(getGeomParabolaPtr()->handle()); + Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast( + getGeomParabolaPtr()->handle() + ); parabola->SetFocal(1.0); return 0; } - static const std::array keywords_e {"Parabola", nullptr}; + static const std::array keywords_e {"Parabola", nullptr}; PyErr_Clear(); - PyObject *pParab; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!",keywords_e, &(ParabolaPy::Type), &pParab)) { + PyObject* pParab; + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_e, &(ParabolaPy::Type), &pParab)) { ParabolaPy* pParabola = static_cast(pParab); - Handle(Geom_Parabola) Parab1 = Handle(Geom_Parabola)::DownCast - (pParabola->getGeomParabolaPtr()->handle()); - Handle(Geom_Parabola) Parab2 = Handle(Geom_Parabola)::DownCast - (this->getGeomParabolaPtr()->handle()); + Handle(Geom_Parabola) Parab1 = Handle(Geom_Parabola)::DownCast( + pParabola->getGeomParabolaPtr()->handle() + ); + Handle(Geom_Parabola) Parab2 = Handle(Geom_Parabola)::DownCast( + this->getGeomParabolaPtr()->handle() + ); Parab2->SetParab(Parab1->Parab()); return 0; } - static const std::array keywords_ssc {"Focus","Center","Normal",nullptr}; + static const std::array keywords_ssc {"Focus", "Center", "Normal", nullptr}; PyErr_Clear(); PyObject *pV1, *pV2, *pV3; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ssc, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ssc, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d focus = static_cast(pV1)->value(); Base::Vector3d center = static_cast(pV2)->value(); Base::Vector3d normal = static_cast(pV3)->value(); - Base::Vector3d xvect = focus-center; + Base::Vector3d xvect = focus - center; // set the geometry - gp_Pnt p1(center.x,center.y,center.z); - gp_Dir norm(normal.x,normal.y,normal.z); - gp_Dir xdiroce(xvect.x,xvect.y,xvect.z); + gp_Pnt p1(center.x, center.y, center.z); + gp_Dir norm(normal.x, normal.y, normal.z); + gp_Dir xdiroce(xvect.x, xvect.y, xvect.z); gp_Ax2 xdir(p1, norm, xdiroce); - gce_MakeParab mc(xdir, (Standard_Real) xvect.Length()); + gce_MakeParab mc(xdir, (Standard_Real)xvect.Length()); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; } - Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast(getGeomParabolaPtr()->handle()); + Handle(Geom_Parabola) parabola = Handle(Geom_Parabola)::DownCast( + getGeomParabolaPtr()->handle() + ); parabola->SetParab(mc.Value()); return 0; } - PyErr_SetString(PyExc_TypeError, "Parabola constructor accepts:\n" - "-- empty parameter list\n" - "-- Parabola\n" - "-- Point, Point, Point"); + PyErr_SetString( + PyExc_TypeError, + "Parabola constructor accepts:\n" + "-- empty parameter list\n" + "-- Parabola\n" + "-- Point, Point, Point" + ); return -1; } -PyObject* ParabolaPy::compute(PyObject *args) +PyObject* ParabolaPy::compute(PyObject* args) { PyObject *p1, *p2, *p3; - if (!PyArg_ParseTuple(args, "O!O!O!", - &Base::VectorPy::Type,&p1, - &Base::VectorPy::Type,&p2, - &Base::VectorPy::Type,&p3)) + if (!PyArg_ParseTuple( + args, + "O!O!O!", + &Base::VectorPy::Type, + &p1, + &Base::VectorPy::Type, + &p2, + &Base::VectorPy::Type, + &p3 + )) { return nullptr; - Base::Vector3d v1 = Py::Vector(p1,false).toVector(); - Base::Vector3d v2 = Py::Vector(p2,false).toVector(); - Base::Vector3d v3 = Py::Vector(p3,false).toVector(); - Base::Vector3d c = (v1-v2) % (v3-v2); + } + Base::Vector3d v1 = Py::Vector(p1, false).toVector(); + Base::Vector3d v2 = Py::Vector(p2, false).toVector(); + Base::Vector3d v3 = Py::Vector(p3, false).toVector(); + Base::Vector3d c = (v1 - v2) % (v3 - v2); double zValue = v1.z; if (fabs(c.Length()) < 0.0001) { PyErr_SetString(PartExceptionOCCError, "Points are collinear"); @@ -149,11 +173,11 @@ PyObject* ParabolaPy::compute(PyObject *args) v = m * v; double a22 = v.x; double a10 = -0.5; - double a20 = v.y/2.0; + double a20 = v.y / 2.0; double a00 = v.z; Handle(Geom_Parabola) curve = Handle(Geom_Parabola)::DownCast(getGeometryPtr()->handle()); - curve->SetFocal(0.5*fabs(a10/a22)); - curve->SetLocation(gp_Pnt((a20*a20-a22*a00)/(2*a22*a10), -a20/a22, zValue)); + curve->SetFocal(0.5 * fabs(a10 / a22)); + curve->SetLocation(gp_Pnt((a20 * a20 - a22 * a00) / (2 * a22 * a10), -a20 / a22, zValue)); Py_Return; } @@ -172,8 +196,7 @@ void ParabolaPy::setFocal(Py::Float arg) Py::Object ParabolaPy::getFocus() const { - Handle(Geom_Parabola) c = Handle(Geom_Parabola)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_Parabola) c = Handle(Geom_Parabola)::DownCast(getGeometryPtr()->handle()); gp_Pnt loc = c->Focus(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } @@ -184,7 +207,7 @@ Py::Float ParabolaPy::getParameter() const return Py::Float(curve->Parameter()); } -PyObject *ParabolaPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ParabolaPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -193,5 +216,3 @@ int ParabolaPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Mod/Part/App/Part2DObject.cpp b/src/Mod/Part/App/Part2DObject.cpp index d82441e695..ad291ced8d 100644 --- a/src/Mod/Part/App/Part2DObject.cpp +++ b/src/Mod/Part/App/Part2DObject.cpp @@ -22,21 +22,21 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -66,17 +66,18 @@ Part2DObject::Part2DObject() } -App::DocumentObjectExecReturn *Part2DObject::execute() +App::DocumentObjectExecReturn* Part2DObject::execute() { return Feature::execute(); } -void Part2DObject::transformPlacement(const Base::Placement &transform) +void Part2DObject::transformPlacement(const Base::Placement& transform) { if (!AttachmentSupport.getValues().empty()) { - //part->transformPlacement(transform); + // part->transformPlacement(transform); positionBySupport(); - } else { + } + else { GeoFeature::transformPlacement(transform); } } @@ -89,40 +90,48 @@ int Part2DObject::getAxisCount() const Base::Axis Part2DObject::getAxis(int axId) const { if (axId == H_Axis) { - return Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(1,0,0)); + return Base::Axis(Base::Vector3d(0, 0, 0), Base::Vector3d(1, 0, 0)); } else if (axId == V_Axis) { - return Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(0,1,0)); + return Base::Axis(Base::Vector3d(0, 0, 0), Base::Vector3d(0, 1, 0)); } else if (axId == N_Axis) { - return Base::Axis(Base::Vector3d(0,0,0), Base::Vector3d(0,0,1)); + return Base::Axis(Base::Vector3d(0, 0, 0), Base::Vector3d(0, 0, 1)); } return {}; } -bool Part2DObject::seekTrimPoints(const std::vector &geomlist, - int geometryIndex, const Base::Vector3d &point, - int &geometryIndex1, Base::Vector3d &intersect1, - int &geometryIndex2, Base::Vector3d &intersect2) +bool Part2DObject::seekTrimPoints( + const std::vector& geomlist, + int geometryIndex, + const Base::Vector3d& point, + int& geometryIndex1, + Base::Vector3d& intersect1, + int& geometryIndex2, + Base::Vector3d& intersect2 +) { - if ( geometryIndex >= int(geomlist.size())) + if (geometryIndex >= int(geomlist.size())) { return false; + } - gp_Pln plane(gp_Pnt(0,0,0),gp_Dir(0,0,1)); + gp_Pln plane(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)); - Standard_Boolean periodic=Standard_False; + Standard_Boolean periodic = Standard_False; double period = 0; Handle(Geom2d_Curve) primaryCurve; Handle(Geom_Geometry) geom = (geomlist[geometryIndex])->handle(); Handle(Geom_Curve) curve3d = Handle(Geom_Curve)::DownCast(geom); - if (curve3d.IsNull()) + if (curve3d.IsNull()) { return false; + } else { primaryCurve = GeomAPI::To2d(curve3d, plane); periodic = primaryCurve->IsPeriodic(); - if (periodic) + if (periodic) { period = primaryCurve->Period(); + } } // create the intersector and projector functions @@ -136,12 +145,12 @@ bool Part2DObject::seekTrimPoints(const std::vector &geomlist, // find intersection points geometryIndex1 = -1; geometryIndex2 = -1; - double param1=-1e10,param2=1e10; - gp_Pnt2d p1,p2; + double param1 = -1e10, param2 = 1e10; + gp_Pnt2d p1, p2; Handle(Geom2d_Curve) secondaryCurve; - for (int id=0; id < int(geomlist.size()); id++) { + for (int id = 0; id < int(geomlist.size()); id++) { // #0000624: Trim tool doesn't work with construction lines - if (id != geometryIndex/* && !geomlist[id]->Construction*/) { + if (id != geometryIndex /* && !geomlist[id]->Construction*/) { geom = (geomlist[id])->handle(); curve3d = Handle(Geom_Curve)::DownCast(geom); if (!curve3d.IsNull()) { @@ -157,20 +166,21 @@ bool Part2DObject::seekTrimPoints(const std::vector &geomlist, // https://tracker.dev.opencascade.org/view.php?id=30217 if (geomlist[id]->isDerivedFrom()) { - Part::GeomBoundedCurve * bcurve = static_cast(geomlist[id]); + Part::GeomBoundedCurve* bcurve = static_cast(geomlist[id]); - points.emplace_back(bcurve->getStartPoint().x,bcurve->getStartPoint().y); - points.emplace_back(bcurve->getEndPoint().x,bcurve->getEndPoint().y); + points.emplace_back(bcurve->getStartPoint().x, bcurve->getStartPoint().y); + points.emplace_back(bcurve->getEndPoint().x, bcurve->getEndPoint().y); } Intersector.Init(primaryCurve, secondaryCurve, 1.0e-12); - for (int i=1; i <= Intersector.NbPoints(); i++) + for (int i = 1; i <= Intersector.NbPoints(); i++) { points.push_back(Intersector.Point(i)); + } if (Intersector.NbSegments() > 0) { const Geom2dInt_GInter& gInter = Intersector.Intersector(); - for (int i=1; i <= gInter.NbSegments(); i++) { + for (int i = 1; i <= gInter.NbSegments(); i++) { const IntRes2d_IntersectionSegment& segm = gInter.Segment(i); if (segm.HasFirstPoint()) { const IntRes2d_IntersectionPoint& fp = segm.FirstPoint(); @@ -187,20 +197,23 @@ bool Part2DObject::seekTrimPoints(const std::vector &geomlist, // get the parameter of the intersection point on the primary curve Projector.Init(p, primaryCurve); - if (Projector.NbPoints()<1 || Projector.LowerDistance() > Precision::Confusion()) + if (Projector.NbPoints() < 1 + || Projector.LowerDistance() > Precision::Confusion()) { continue; + } double param = Projector.LowerDistanceParameter(); if (periodic) { // transfer param into the interval (pickedParam-period pickedParam] - param = param - period * ceil((param-pickedParam) / period); + param = param - period * ceil((param - pickedParam) / period); if (param > param1) { param1 = param; p1 = p; geometryIndex1 = id; } - param -= period; // transfer param into the interval (pickedParam pickedParam+period] + param -= period; // transfer param into the interval (pickedParam + // pickedParam+period] if (param < param2) { param2 = param; p2 = p; @@ -224,21 +237,26 @@ bool Part2DObject::seekTrimPoints(const std::vector &geomlist, if (periodic) { // in case both points coincide, cancel the selection of one of both - if (fabs(param2-param1-period) < 1e-10) { - if (param2 - pickedParam >= pickedParam - param1) + if (fabs(param2 - param1 - period) < 1e-10) { + if (param2 - pickedParam >= pickedParam - param1) { geometryIndex2 = -1; - else + } + else { geometryIndex1 = -1; + } } } - if ( geometryIndex1 < 0 && geometryIndex2 < 0) + if (geometryIndex1 < 0 && geometryIndex2 < 0) { return false; + } - if ( geometryIndex1 >= 0) - intersect1 = Base::Vector3d(p1.X(),p1.Y(),0.f); - if ( geometryIndex2 >= 0) - intersect2 = Base::Vector3d(p2.X(),p2.Y(),0.f); + if (geometryIndex1 >= 0) { + intersect1 = Base::Vector3d(p1.X(), p1.Y(), 0.f); + } + if (geometryIndex2 >= 0) { + intersect2 = Base::Vector3d(p2.X(), p2.Y(), 0.f); + } return true; } @@ -247,28 +265,33 @@ void Part2DObject::acceptGeometry() // implemented in sub-classes } -void Part2DObject::Restore(Base::XMLReader &reader) +void Part2DObject::Restore(Base::XMLReader& reader) { Part::Feature::Restore(reader); } // Python Drawing feature --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR - PROPERTY_SOURCE_TEMPLATE(Part::Part2DObjectPython, Part::Part2DObject) - template<> const char* Part::Part2DObjectPython::getViewProviderName() const { +PROPERTY_SOURCE_TEMPLATE(Part::Part2DObjectPython, Part::Part2DObject) +template<> +const char* Part::Part2DObjectPython::getViewProviderName() const +{ return "PartGui::ViewProvider2DObjectPython"; - } - template<> PyObject* Part::Part2DObjectPython::getPyObject() { - if (PythonObject.is(Py::_None())) { - // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePythonPyT(this),true); - } - return Py::new_reference_to(PythonObject); - } +} +template<> +PyObject* Part::Part2DObjectPython::getPyObject() +{ + if (PythonObject.is(Py::_None())) { + // ref counter is set to 1 + PythonObject = Py::Object(new FeaturePythonPyT(this), true); + } + return Py::new_reference_to(PythonObject); +} /// @endcond // explicit template instantiation - template class PartExport FeaturePythonT; -} +template class PartExport FeaturePythonT; +} // namespace App diff --git a/src/Mod/Part/App/Part2DObject.h b/src/Mod/Part/App/Part2DObject.h index 42c0ecdcf4..2852b70d52 100644 --- a/src/Mod/Part/App/Part2DObject.h +++ b/src/Mod/Part/App/Part2DObject.h @@ -40,26 +40,26 @@ namespace Part class Geometry; /** 2D Shape - * This is a specialized version of the PartShape for use with - * flat (2D) geometry. The Z direction has always to be 0. - * The position and orientation of the Plane this 2D geometry is - * referenced is defined by the Placement property. It also - * has a link to a supporting Face which defines the position - * in space where it is located. If the support is changed the - * static method positionBySupport() is used to calculate a - * new position for the Part2DObject. - * This object can be used stand alone or for constraint - * geometry as its descend Sketcher::SketchObject . - */ + * This is a specialized version of the PartShape for use with + * flat (2D) geometry. The Z direction has always to be 0. + * The position and orientation of the Plane this 2D geometry is + * referenced is defined by the Placement property. It also + * has a link to a supporting Face which defines the position + * in space where it is located. If the support is changed the + * static method positionBySupport() is used to calculate a + * new position for the Part2DObject. + * This object can be used stand alone or for constraint + * geometry as its descend Sketcher::SketchObject . + */ -class PartExport Part2DObject : public Part::Feature, public Part::AttachExtension +class PartExport Part2DObject: public Part::Feature, public Part::AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::Part2DObject); public: Part2DObject(); - void transformPlacement(const Base::Placement &transform) override; + void transformPlacement(const Base::Placement& transform) override; /// returns the number of construction lines (to be used as axes) virtual int getAxisCount() const; @@ -69,18 +69,23 @@ public: virtual void acceptGeometry(); /** calculate the points where a curve with index geometryIndex should be trimmed - * with respect to the rest of the curves contained in the list geomlist - * and a picked point. The outputs intersect1 and intersect2 specify the - * tightest boundaries for trimming around the picked point and the - * indexes geometryIndex1 and geometryIndex2 specify the corresponding curves that intersect - * the curve geometryIndex. - * - * If intersection is found, the associated geometryIndex1 or geometryIndex2 returns -1. - */ - static bool seekTrimPoints(const std::vector &geomlist, - int geometryIndex, const Base::Vector3d &point, - int &geometryIndex1, Base::Vector3d &intersect1, - int &geometryIndex2, Base::Vector3d &intersect2); + * with respect to the rest of the curves contained in the list geomlist + * and a picked point. The outputs intersect1 and intersect2 specify the + * tightest boundaries for trimming around the picked point and the + * indexes geometryIndex1 and geometryIndex2 specify the corresponding curves that intersect + * the curve geometryIndex. + * + * If intersection is found, the associated geometryIndex1 or geometryIndex2 returns -1. + */ + static bool seekTrimPoints( + const std::vector& geomlist, + int geometryIndex, + const Base::Vector3d& point, + int& geometryIndex1, + Base::Vector3d& intersect1, + int& geometryIndex2, + Base::Vector3d& intersect2 + ); static const int H_Axis; static const int V_Axis; @@ -89,20 +94,21 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProvider2DObject"; } //@} - void Restore(Base::XMLReader &reader) override; + void Restore(Base::XMLReader& reader) override; }; using Part2DObjectPython = App::FeaturePythonT; -} //namespace Part +} // namespace Part -#endif // PART_PART2DOBJECT_H +#endif // PART_PART2DOBJECT_H diff --git a/src/Mod/Part/App/Part2DObject.pyi b/src/Mod/Part/App/Part2DObject.pyi index 606e74daf2..189a9c95b5 100644 --- a/src/Mod/Part/App/Part2DObject.pyi +++ b/src/Mod/Part/App/Part2DObject.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from PartFeature import PartFeature - @export( Twin="Part2DObject", TwinPointer="Part2DObject", @@ -15,4 +14,5 @@ class Part2DObject(PartFeature): Author: Juergen Riegel (FreeCAD@juergen-riegel.net) Licence: LGPL """ + ... diff --git a/src/Mod/Part/App/Part2DObjectPyImp.cpp b/src/Mod/Part/App/Part2DObjectPyImp.cpp index 5fece679cb..39640b5246 100644 --- a/src/Mod/Part/App/Part2DObjectPyImp.cpp +++ b/src/Mod/Part/App/Part2DObjectPyImp.cpp @@ -39,7 +39,7 @@ std::string Part2DObjectPy::representation() const return {""}; } -PyObject *Part2DObjectPy::getCustomAttributes(const char* /*attr*/) const +PyObject* Part2DObjectPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -48,5 +48,3 @@ int Part2DObjectPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { return 0; } - - diff --git a/src/Mod/Part/App/PartFeature.cpp b/src/Mod/Part/App/PartFeature.cpp index 232cf568bd..abb1421412 100644 --- a/src/Mod/Part/App/PartFeature.cpp +++ b/src/Mod/Part/App/PartFeature.cpp @@ -23,37 +23,37 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#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 @@ -82,7 +82,7 @@ using namespace Part; namespace sp = std::placeholders; -FC_LOG_LEVEL_INIT("Part",true,true) +FC_LOG_LEVEL_INIT("Part", true, true) PROPERTY_SOURCE(Part::Feature, App::GeoFeature) @@ -101,7 +101,7 @@ short Feature::mustExecute() const return GeoFeature::mustExecute(); } -App::DocumentObjectExecReturn *Feature::recompute() +App::DocumentObjectExecReturn* Feature::recompute() { try { return App::GeoFeature::recompute(); @@ -109,22 +109,24 @@ App::DocumentObjectExecReturn *Feature::recompute() catch (Standard_Failure& e) { App::DocumentObjectExecReturn* ret = new App::DocumentObjectExecReturn(e.GetMessageString()); - if (ret->Why.empty()) ret->Why = "Unknown OCC exception"; + if (ret->Why.empty()) { + ret->Why = "Unknown OCC exception"; + } return ret; } } -App::DocumentObjectExecReturn *Feature::execute() +App::DocumentObjectExecReturn* Feature::execute() { this->Shape.touch(); return GeoFeature::execute(); } -PyObject *Feature::getPyObject() +PyObject* Feature::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new PartFeaturePy(this),true); + PythonObject = Py::Object(new PartFeaturePy(this), true); } return Py::new_reference_to(PythonObject); } @@ -156,8 +158,7 @@ void Feature::copyMaterial(App::DocumentObject* link) * @param type An element type name. * @return a struct with the newName and oldName. New element name may be empty. */ -App::ElementNamePair Feature::getElementName(const char* name, - ElementNameType type) const +App::ElementNamePair Feature::getElementName(const char* name, ElementNameType type) const { if (type != ElementNameType::Export) { return App::GeoFeature::getElementName(name, type); @@ -173,8 +174,7 @@ App::ElementNamePair Feature::getElementName(const char* name, return getExportElementName(prop->getShape(), name); } -App::ElementNamePair Feature::getExportElementName(TopoShape shape, - const char* name) const +App::ElementNamePair Feature::getExportElementName(TopoShape shape, const char* name) const { Data::MappedElement mapped = shape.getElementName(name); auto res = shape.shapeTypeAndIndex(mapped.index); @@ -228,8 +228,7 @@ App::ElementNamePair Feature::getExportElementName(TopoShape shape, if (!name) { continue; } - indices.emplace_back(names.size(), - shape.findAncestors(ss.getShape(), res.first)); + indices.emplace_back(names.size(), shape.findAncestors(ss.getShape(), res.first)); names.push_back(name); if (indices.back().second.size() == 1 && ++count >= MinLowerTopoNames) { break; @@ -237,11 +236,13 @@ App::ElementNamePair Feature::getExportElementName(TopoShape shape, } if (names.size() >= MaxLowerTopoNames) { - std::stable_sort(indices.begin(), - indices.end(), - [](const NameEntry& a, const NameEntry& b) { - return a.second.size() < b.second.size(); - }); + std::stable_sort( + indices.begin(), + indices.end(), + [](const NameEntry& a, const NameEntry& b) { + return a.second.size() < b.second.size(); + } + ); std::vector sorted; auto pos = 0; sorted.reserve(names.size()); @@ -252,8 +253,7 @@ App::ElementNamePair Feature::getExportElementName(TopoShape shape, } else if (size > 1) { for (auto it = ancestors.begin(); it != ancestors.end();) { - if (std::ranges::find(v.second, *it) - == v.second.end()) { + if (std::ranges::find(v.second, *it) == v.second.end()) { it = ancestors.erase(it); if (ancestors.size() == 1) { break; @@ -302,10 +302,12 @@ App::ElementNamePair Feature::getExportElementName(TopoShape shape, // change the element map inside the Shape property without // recording the change in undo stack. // - mapped.name = shape.setElementComboName(mapped.index, - names, - mapped.index.getType(), - op.c_str()); + mapped.name = shape.setElementComboName( + mapped.index, + names, + mapped.index.getType(), + op.c_str() + ); } } } @@ -327,26 +329,32 @@ App::ElementNamePair Feature::getExportElementName(TopoShape shape, } std::pair occindex = shape.shapeTypeAndIndex(dot); if (occindex.second > 0) { - auto idxName = Data::IndexedName::fromConst(shape.shapeName(occindex.first).c_str(), - occindex.second); + auto idxName = Data::IndexedName::fromConst( + shape.shapeName(occindex.first).c_str(), + occindex.second + ); std::string postfix; - auto names = - shape.decodeElementComboName(idxName, mapped.name, idxName.getType(), &postfix); + auto names + = shape.decodeElementComboName(idxName, mapped.name, idxName.getType(), &postfix); std::vector ancestors; - if ( names.empty() ) { + if (names.empty()) { // Naming based heuristic has failed to find the element. Let's see if we can // find it by matching either planes for faces or lines for edges. auto searchShape = this->Shape.getShape(); // If we're still out at a Shell, Solid, CompSolid, or Compound drill in - while (!searchShape.getShape().IsNull() && searchShape.getShape().ShapeType() < TopAbs_FACE ) { + while (!searchShape.getShape().IsNull() + && searchShape.getShape().ShapeType() < TopAbs_FACE) { auto shapes = searchShape.getSubTopoShapes(); - if ( shapes.empty() ) // No more subshapes, so don't continue + if (shapes.empty()) { // No more subshapes, so don't continue break; - searchShape = shapes.front(); // After the break, so we stopped at innermost container + } + searchShape = shapes.front(); // After the break, so we stopped at + // innermost container } auto newMapped = TopoShape::chooseMatchingSubShapeByPlaneOrLine(shape, searchShape); - if ( ! newMapped.name.empty() ) + if (!newMapped.name.empty()) { mapped = newMapped; + } } for (auto& name : names) { auto index = shape.getIndexedName(name); @@ -395,13 +403,17 @@ App::ElementNamePair Feature::getExportElementName(TopoShape shape, return App::GeoFeature::_getElementName(name, mapped); } -App::DocumentObject* Feature::getSubObject(const char* subname, - PyObject** pyObj, - Base::Matrix4D* pmat, - bool transform, - int depth) const +App::DocumentObject* Feature::getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth +) const { - while(subname && *subname=='.') ++subname; // skip leading . + while (subname && *subname == '.') { + ++subname; // skip leading . + } // having '.' inside subname means it is referencing some children object, // instead of any sub-element from ourself @@ -427,13 +439,14 @@ App::DocumentObject* Feature::getSubObject(const char* subname, ts.setShape(ts.getShape().Located(TopLoc_Location()), false); } if (subname && *subname && !ts.isNull()) { - ts = ts.getSubTopoShape(subname,true); + ts = ts.getSubTopoShape(subname, true); } if (doTransform && !ts.isNull()) { static int sCopy = -1; if (sCopy < 0) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Part/General"); + "User parameter:BaseApp/Preferences/Mod/Part/General" + ); sCopy = hGrp->GetBool("CopySubShape", false) ? 1 : 0; } bool copy = sCopy ? true : false; @@ -483,10 +496,12 @@ App::DocumentObject* Feature::getSubObject(const char* subname, } } -static std::vector> getElementSource(App::DocumentObject* owner, - TopoShape shape, - const Data::MappedName& name, - char type) +static std::vector> getElementSource( + App::DocumentObject* owner, + TopoShape shape, + const Data::MappedName& name, + char type +) { std::set> tagSet; std::vector> ret; @@ -521,8 +536,9 @@ static std::vector> getElementSource(App::Docu } } if (owner->isDerivedFrom()) { - auto ownerGeoFeature = - static_cast(owner)->getElementOwner(ret.back().second); + auto ownerGeoFeature = static_cast(owner)->getElementOwner( + ret.back().second + ); if (ownerGeoFeature) { doc = ownerGeoFeature->getDocument(); } @@ -544,13 +560,13 @@ static std::vector> getElementSource(App::Docu doc = nullptr; } else { - shape = - Part::Feature::getTopoShape(obj, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - nullptr, - nullptr, - &owner); + shape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform, + nullptr, + nullptr, + &owner + ); } if (type && shape.elementType(original) != type) { break; @@ -571,10 +587,12 @@ static std::vector> getElementSource(App::Docu return ret; } -std::list Feature::getElementHistory(App::DocumentObject* feature, - const char* name, - bool recursive, - bool sameType) +std::list Feature::getElementHistory( + App::DocumentObject* feature, + const char* name, + bool recursive, + bool sameType +) { std::list ret; TopoShape shape = getTopoShape(feature, ShapeOption::ResolveLink | ShapeOption::Transform); @@ -630,8 +648,7 @@ std::list Feature::getElementHistory(App::DocumentObject* fea } } if (feature->isDerivedFrom()) { - auto ownerGeoFeature = - static_cast(feature)->getElementOwner(element); + auto ownerGeoFeature = static_cast(feature)->getElementOwner(element); if (ownerGeoFeature) { doc = ownerGeoFeature->getDocument(); } @@ -663,11 +680,13 @@ std::list Feature::getElementHistory(App::DocumentObject* fea return ret; } -QVector Feature::getElementFromSource(App::DocumentObject* obj, - const char* subname, - App::DocumentObject* src, - const char* srcSub, - bool single) +QVector Feature::getElementFromSource( + App::DocumentObject* obj, + const char* subname, + App::DocumentObject* src, + const char* srcSub, + bool single +) { QVector res; if (!obj || !src) { @@ -675,12 +694,8 @@ QVector Feature::getElementFromSource(App::DocumentObject* } auto shape = getTopoShape(obj, ShapeOption::ResolveLink, subname, nullptr, nullptr); App::DocumentObject* owner = nullptr; - auto srcShape = getTopoShape(src, - ShapeOption::ResolveLink - | ShapeOption::Transform, - srcSub, - nullptr, - &owner); + auto srcShape + = getTopoShape(src, ShapeOption::ResolveLink | ShapeOption::Transform, srcSub, nullptr, &owner); int tagChanges; Data::MappedElement element; Data::IndexedName checkingSubname; @@ -703,8 +718,12 @@ QVector Feature::getElementFromSource(App::DocumentObject* GeoFeature::resolveElement(obj, sub.c_str(), objElement); sub.resize(len); if (objElement.oldName.size()) { - res.push_back(Data::MappedElement(Data::MappedName(objElement.newName), - Data::IndexedName(objElement.oldName.c_str()))); + res.push_back( + Data::MappedElement( + Data::MappedName(objElement.newName), + Data::IndexedName(objElement.oldName.c_str()) + ) + ); return true; } } @@ -790,18 +809,16 @@ QVector Feature::getElementFromSource(App::DocumentObject* return res; } -QVector Feature::getRelatedElements(App::DocumentObject* obj, - const char* name, - HistoryTraceType sameType, - bool withCache) +QVector Feature::getRelatedElements( + App::DocumentObject* obj, + const char* name, + HistoryTraceType sameType, + bool withCache +) { auto owner = obj; - auto shape = getTopoShape(obj, - ShapeOption::ResolveLink - | ShapeOption::Transform, - nullptr, - nullptr, - &owner); + auto shape + = getTopoShape(obj, ShapeOption::ResolveLink | ShapeOption::Transform, nullptr, nullptr, &owner); QVector ret; Data::MappedElement mapped = shape.getElementName(name); if (!mapped.name) { @@ -817,11 +834,12 @@ QVector Feature::getRelatedElements(App::DocumentObject* ob return ret; } - auto source = - getElementSource(owner, - shape, - mapped.name, - sameType == HistoryTraceType::followTypeChange ? element_type : 0); + auto source = getElementSource( + owner, + shape, + mapped.name, + sameType == HistoryTraceType::followTypeChange ? element_type : 0 + ); for (auto& src : source) { auto srcIndex = shape.getIndexedName(src.second); if (srcIndex) { @@ -842,11 +860,12 @@ QVector Feature::getRelatedElements(App::DocumentObject* ob if (!related.name) { continue; } - auto src = - getElementSource(owner, - shape, - related.name, - sameType == HistoryTraceType::followTypeChange ? element_type : 0); + auto src = getElementSource( + owner, + shape, + related.name, + sameType == HistoryTraceType::followTypeChange ? element_type : 0 + ); int idx = (int)source.size() - 1; for (auto rit = src.rbegin(); idx >= 0 && rit != src.rend(); ++rit, --idx) { // TODO: shall we ignore source tag when comparing? It could cause @@ -868,11 +887,13 @@ QVector Feature::getRelatedElements(App::DocumentObject* ob return ret; } -TopoDS_Shape Feature::getShape( const App::DocumentObject *obj, - ShapeOptions options, - const char *subname, - Base::Matrix4D *pmat, - App::DocumentObject **powner) +TopoDS_Shape Feature::getShape( + const App::DocumentObject* obj, + ShapeOptions options, + const char* subname, + Base::Matrix4D* pmat, + App::DocumentObject** powner +) { return getTopoShape(obj, options | ShapeOption::NoElementMap, subname, pmat, powner).getShape(); } @@ -893,8 +914,9 @@ void Feature::setMaterialAppearance(const App::Material& material) } // Toponaming project March 2024: This method should be going away when we get to the python layer. -void Feature::clearShapeCache() { -// _ShapeCache.cache.clear(); +void Feature::clearShapeCache() +{ + // _ShapeCache.cache.clear(); } /* @@ -908,13 +930,15 @@ void Feature::clearShapeCache() { const std::set hiddens, const App::DocumentObject* lastLink) */ -static TopoShape _getTopoShape(const App::DocumentObject* obj, - ShapeOptions options, - const char* subname, - Base::Matrix4D* pmat, - App::DocumentObject** powner, - const std::set hiddens, - const App::DocumentObject* lastLink) +static TopoShape _getTopoShape( + const App::DocumentObject* obj, + ShapeOptions options, + const char* subname, + Base::Matrix4D* pmat, + App::DocumentObject** powner, + const std::set hiddens, + const App::DocumentObject* lastLink +) { TopoShape shape; @@ -947,7 +971,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (options.testFlag(ShapeOption::NoElementMap)) { shape.resetElementMap(); shape.Tag = 0; - if ( shape.Hasher ) { + if (shape.Hasher) { shape.Hasher = nullptr; } } @@ -999,7 +1023,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (options.testFlag(ShapeOption::NoElementMap)) { shape.resetElementMap(); shape.Tag = 0; - if ( shape.Hasher ) { + if (shape.Hasher) { shape.Hasher = nullptr; } } @@ -1013,7 +1037,9 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (_shape.IsNull()) { auto line = static_cast(linked); Base::Vector3d dir = line->getBaseDirection(); - BRepBuilderAPI_MakeEdge builder(gp_Lin(gp_Pnt(0, 0, 0), Base::convertTo(dir))); + BRepBuilderAPI_MakeEdge builder( + gp_Lin(gp_Pnt(0, 0, 0), Base::convertTo(dir)) + ); _shape = builder.Shape(); _shape.Infinite(Standard_True); } @@ -1024,7 +1050,9 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (_shape.IsNull()) { auto plane = static_cast(linked); Base::Vector3d dir = plane->getBaseDirection(); - BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0, 0, 0), Base::convertTo(dir))); + BRepBuilderAPI_MakeFace builder( + gp_Pln(gp_Pnt(0, 0, 0), Base::convertTo(dir)) + ); _shape = builder.Shape(); _shape.Infinite(Standard_True); } @@ -1046,8 +1074,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, || boost::iequals("z", element) || boost::iequals("z-axis", element)) { static TopoDS_Shape _shape; if (_shape.IsNull()) { - BRepBuilderAPI_MakeEdge builder( - gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))); + BRepBuilderAPI_MakeEdge builder(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))); _shape = builder.Shape(); _shape.Infinite(Standard_True); } @@ -1095,8 +1122,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, shape.reTagElementMap(obj->getID(), obj->getDocument()->getStringHasher()); PropertyShapeCache::setShape(obj, shape, subname); } - else if (scaled - || (linked != owner && linkMat.hasScale() != Base::ScaleType::NoScaling)) { + else if (scaled || (linked != owner && linkMat.hasScale() != Base::ScaleType::NoScaling)) { PropertyShapeCache::setShape(obj, shape, subname); } } @@ -1104,7 +1130,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (options.testFlag(ShapeOption::NoElementMap)) { shape.resetElementMap(); shape.Tag = 0; - if ( shape.Hasher) { + if (shape.Hasher) { shape.Hasher = nullptr; } } @@ -1146,8 +1172,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (linked && linked != owner) { baseShape = Feature::getTopoShape(linked, ShapeOption::NoFlag); if (!link->getShowElementValue()) { - baseShape.reTagElementMap(owner->getID(), - owner->getDocument()->getStringHasher()); + baseShape.reTagElementMap(owner->getID(), owner->getDocument()->getStringHasher()); } } } @@ -1164,8 +1189,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, visible = 1; } else { - subObj = - owner->resolve(sub.c_str(), &parent, &childName, nullptr, nullptr, &mat, false); + subObj = owner->resolve(sub.c_str(), &parent, &childName, nullptr, nullptr, &mat, false); if (!parent || !subObj) { continue; } @@ -1184,10 +1208,10 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, const App::DocumentObject* nextLink = lastLink; // Todo: This might belong. // Toponaming project March 2024: This appears to be a non toponaming feature: -// if (!checkLinkVisibility(nextHiddens, true, nextLink, owner, sub.c_str())) { -// cacheable = false; -// continue; -// } + // if (!checkLinkVisibility(nextHiddens, true, nextLink, owner, sub.c_str())) { + // cacheable = false; + // continue; + // } TopoShape shape; @@ -1199,13 +1223,15 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, } } if (doGetShape) { - shape = _getTopoShape(owner, - ShapeOption::NeedSubElement, - sub.c_str(), - nullptr, - &subObj, - nextHiddens, - nextLink); + shape = _getTopoShape( + owner, + ShapeOption::NeedSubElement, + sub.c_str(), + nullptr, + &subObj, + nextHiddens, + nextLink + ); if (shape.isNull()) { continue; @@ -1216,14 +1242,14 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, } else { if (link && !link->getShowElementValue()) { - shape = - baseShape.makeElementTransform(mat, - (Data::POSTFIX_INDEX + childName).c_str()); + shape = baseShape.makeElementTransform( + mat, + (Data::POSTFIX_INDEX + childName).c_str() + ); } else { shape = baseShape.makeElementTransform(mat); - shape.reTagElementMap(subObj->getID(), - subObj->getDocument()->getStringHasher()); + shape.reTagElementMap(subObj->getID(), subObj->getDocument()->getStringHasher()); } } shapes.push_back(shape); @@ -1254,7 +1280,7 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, if (options.testFlag(ShapeOption::NoElementMap)) { shape.resetElementMap(); shape.Tag = 0; - if ( shape.Hasher ) { + if (shape.Hasher) { shape.Hasher = nullptr; } } @@ -1262,11 +1288,13 @@ static TopoShape _getTopoShape(const App::DocumentObject* obj, } -TopoShape Feature::getTopoShape(const App::DocumentObject* obj, - ShapeOptions options, - const char* subname, - Base::Matrix4D* pmat, - App::DocumentObject** powner) +TopoShape Feature::getTopoShape( + const App::DocumentObject* obj, + ShapeOptions options, + const char* subname, + Base::Matrix4D* pmat, + App::DocumentObject** powner +) { if (!obj || !obj->getNameInDocument()) { return {}; @@ -1276,9 +1304,9 @@ TopoShape Feature::getTopoShape(const App::DocumentObject* obj, std::set hiddens; // Toponaming project March 2024: This appears to be a non toponaming feature: // Todo is this a cause behind #13886 ? -// if (!checkLinkVisibility(hiddens, false, lastLink, obj, subname)) { -// return TopoShape(); -// } + // if (!checkLinkVisibility(hiddens, false, lastLink, obj, subname)) { + // return TopoShape(); + // } // NOTE! _getTopoShape() always return shape without top level // transformation for easy shape caching, i.e. with `transform` set @@ -1314,15 +1342,9 @@ TopoShape Feature::getTopoShape(const App::DocumentObject* obj, } Base::Matrix4D mat; - auto shape = _getTopoShape(obj, - options, - subname, - &mat, - powner, - hiddens, - lastLink); - if (options.testFlag(ShapeOption::NeedSubElement) - && !options.testFlag(ShapeOption::DontSimplifyCompound) + auto shape = _getTopoShape(obj, options, subname, &mat, powner, hiddens, lastLink); + if (options.testFlag(ShapeOption::NeedSubElement) + && !options.testFlag(ShapeOption::DontSimplifyCompound) && shape.shapeType(true) == TopAbs_COMPOUND) { shape = simplifyCompound(shape); } @@ -1346,35 +1368,36 @@ TopoShape Feature::getTopoShape(const App::DocumentObject* obj, } TopoShape Feature::simplifyCompound(TopoShape compoundShape) { - std::initializer_list simplificationOrder = { - TopAbs_SOLID, - TopAbs_COMPSOLID, - TopAbs_FACE, - TopAbs_SHELL, - TopAbs_EDGE, - TopAbs_WIRE, - TopAbs_VERTEX}; + std::initializer_list simplificationOrder = { + TopAbs_SOLID, + TopAbs_COMPSOLID, + TopAbs_FACE, + TopAbs_SHELL, + TopAbs_EDGE, + TopAbs_WIRE, + TopAbs_VERTEX + }; - auto foundSimplification = - std::ranges::find_if(simplificationOrder, - [&](TopAbs_ShapeEnum topType) { - return compoundShape.countSubShapes(topType) == 1; - }); + auto foundSimplification = std::ranges::find_if(simplificationOrder, [&](TopAbs_ShapeEnum topType) { + return compoundShape.countSubShapes(topType) == 1; + }); if (foundSimplification != simplificationOrder.end()) { return compoundShape.getSubTopoShape(*foundSimplification, 1); } return compoundShape; } -App::DocumentObject *Feature::getShapeOwner(const App::DocumentObject *obj, const char *subname) +App::DocumentObject* Feature::getShapeOwner(const App::DocumentObject* obj, const char* subname) { - if(!obj) + if (!obj) { return nullptr; + } auto owner = obj->getSubObject(subname); - if(owner) { + if (owner) { auto linked = owner->getLinkedObject(true); - if(linked) + if (linked) { owner = linked; + } } return owner; } @@ -1475,13 +1498,15 @@ void Feature::onBeforeChange(const App::Property* prop) continue; } } - auto res = - _elementCache.insert(std::make_pair(std::string(element), ElementCache())); + auto res = _elementCache.insert( + std::make_pair(std::string(element), ElementCache()) + ); if (res.second) { res.first->second.searched = false; res.first->second.shape = propShape->getShape().getSubTopoShape( element + (prefix ? prefix->size() : 0), - true); + true + ); } } } @@ -1500,8 +1525,9 @@ void Feature::onChanged(const App::Property* prop) shape.setTransform(newTransform); Base::ObjectStatusLocker guard( App::Property::NoRecompute, - &this->Shape); - if ( oldTransform != newTransform) { + &this->Shape + ); + if (oldTransform != newTransform) { this->Shape.setValue(shape); } } @@ -1527,10 +1553,12 @@ void Feature::onChanged(const App::Property* prop) GeoFeature::onChanged(prop); } -const std::vector& Feature::searchElementCache(const std::string& element, - Data::SearchOptions options, - double tol, - double atol) const +const std::vector& Feature::searchElementCache( + const std::string& element, + Data::SearchOptions options, + double tol, + double atol +) const { static std::vector none; if (element.empty()) { @@ -1551,11 +1579,8 @@ const std::vector& Feature::searchElementCache(const std::string& e } } it->second.searched = true; - propShape->getShape().findSubShapesWithSharedVertex(it->second.shape, - &it->second.names, - options, - tol, - atol); + propShape->getShape() + .findSubShapesWithSharedVertex(it->second.shape, &it->second.names, options, tol, atol); if (prefix) { for (auto& name : it->second.names) { if (auto dot = strrchr(name.c_str(), '.')) { @@ -1579,7 +1604,7 @@ TopLoc_Location Feature::getLocation() const rot.getValue(axis, angle); gp_Trsf trf; trf.SetRotation(gp_Ax1(gp_Pnt(), gp_Dir(axis.x, axis.y, axis.z)), angle); - trf.SetTranslationPart(gp_Vec(pl.getPosition().x,pl.getPosition().y,pl.getPosition().z)); + trf.SetTranslationPart(gp_Vec(pl.getPosition().x, pl.getPosition().y, pl.getPosition().z)); return TopLoc_Location(trf); } @@ -1606,37 +1631,43 @@ void Feature::onDocumentRestored() App::GeoFeature::onDocumentRestored(); } -ShapeHistory Feature::buildHistory(BRepBuilderAPI_MakeShape& mkShape, TopAbs_ShapeEnum type, - const TopoDS_Shape& newS, const TopoDS_Shape& oldS) +ShapeHistory Feature::buildHistory( + BRepBuilderAPI_MakeShape& mkShape, + TopAbs_ShapeEnum type, + const TopoDS_Shape& newS, + const TopoDS_Shape& oldS +) { ShapeHistory history; history.type = type; TopTools_IndexedMapOfShape newM, oldM; - TopExp::MapShapes(newS, type, newM); // map containing all old objects of type "type" - TopExp::MapShapes(oldS, type, oldM); // map containing all new objects of type "type" + TopExp::MapShapes(newS, type, newM); // map containing all old objects of type "type" + TopExp::MapShapes(oldS, type, oldM); // map containing all new objects of type "type" // Look at all objects in the old shape and try to find the modified object in the new shape - for (int i=1; i<=oldM.Extent(); i++) { + for (int i = 1; i <= oldM.Extent(); i++) { bool found = false; TopTools_ListIteratorOfListOfShape it; // Find all new objects that are a modification of the old object (e.g. a face was resized) for (it.Initialize(mkShape.Modified(oldM(i))); it.More(); it.Next()) { found = true; - for (int j=1; j<=newM.Extent(); j++) { // one old object might create several new ones! + for (int j = 1; j <= newM.Extent(); + j++) { // one old object might create several new ones! if (newM(j).IsPartner(it.Value())) { - history.shapeMap[i-1].push_back(j-1); // adjust indices to start at zero + history.shapeMap[i - 1].push_back(j - 1); // adjust indices to start at zero break; } } } - // Find all new objects that were generated from an old object (e.g. a face generated from an edge) + // Find all new objects that were generated from an old object (e.g. a face generated from + // an edge) for (it.Initialize(mkShape.Generated(oldM(i))); it.More(); it.Next()) { found = true; - for (int j=1; j<=newM.Extent(); j++) { + for (int j = 1; j <= newM.Extent(); j++) { if (newM(j).IsPartner(it.Value())) { - history.shapeMap[i-1].push_back(j-1); + history.shapeMap[i - 1].push_back(j - 1); break; } } @@ -1645,13 +1676,13 @@ ShapeHistory Feature::buildHistory(BRepBuilderAPI_MakeShape& mkShape, TopAbs_Sha if (!found) { // Find all old objects that don't exist any more (e.g. a face was completely cut away) if (mkShape.IsDeleted(oldM(i))) { - history.shapeMap[i-1] = std::vector(); + history.shapeMap[i - 1] = std::vector(); } else { // Mop up the rest (will this ever be reached?) - for (int j=1; j<=newM.Extent(); j++) { + for (int j = 1; j <= newM.Extent(); j++) { if (newM(j).IsPartner(oldM(i))) { - history.shapeMap[i-1].push_back(j-1); + history.shapeMap[i - 1].push_back(j - 1); break; } } @@ -1667,10 +1698,11 @@ ShapeHistory Feature::joinHistory(const ShapeHistory& oldH, const ShapeHistory& ShapeHistory join; join.type = oldH.type; - for (const auto & it : oldH.shapeMap) { + for (const auto& it : oldH.shapeMap) { int old_shape_index = it.first; - if (it.second.empty()) + if (it.second.empty()) { join.shapeMap[old_shape_index] = ShapeHistory::List(); + } for (const auto& jt : it.second) { const auto& kt = newH.shapeMap.find(jt); if (kt != newH.shapeMap.end()) { @@ -1683,8 +1715,9 @@ ShapeHistory Feature::joinHistory(const ShapeHistory& oldH, const ShapeHistory& return join; } - /// returns the type name of the ViewProvider -const char* Feature::getViewProviderName() const { +/// returns the type name of the ViewProvider +const char* Feature::getViewProviderName() const +{ return "PartGui::ViewProviderPart"; } @@ -1699,31 +1732,34 @@ bool Feature::isElementMappingDisabled(App::PropertyContainer* container) return false; // TODO: March 2024 consider if any of this RT branch logic makes sense: -// if (!container) { -// return false; -// } -// auto prop = propDisableMapping(container, /*forced*/ false); -// if (prop && prop->getValue()) { -// return true; -// } -// if (auto obj = freecad_cast(container)) { -// if (auto doc = obj->getDocument()) { -// if (auto prop = propDisableMapping(doc, /*forced*/ false)) { -// return prop->getValue(); -// } -// } -// } -// return false; + // if (!container) { + // return false; + // } + // auto prop = propDisableMapping(container, /*forced*/ false); + // if (prop && prop->getValue()) { + // return true; + // } + // if (auto obj = freecad_cast(container)) { + // if (auto doc = obj->getDocument()) { + // if (auto prop = propDisableMapping(doc, /*forced*/ false)) { + // return prop->getValue(); + // } + // } + // } + // return false; } -bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vector3d &directionX, const char* subname) const +bool Feature::getCameraAlignmentDirection( + Base::Vector3d& directionZ, + Base::Vector3d& directionX, + const char* subname +) const { - const auto topoShape = getTopoShape(this, - ShapeOptions( - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform), - subname); + const auto topoShape = getTopoShape( + this, + ShapeOptions(ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform), + subname + ); if (topoShape.isNull()) { return false; @@ -1737,11 +1773,12 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect gp_Vec vector; BRepGProp_Face(face).Normal(0, 0, point, vector); directionZ = Base::Vector3d(vector.X(), vector.Y(), vector.Z()).Normalize(); - + // Try to find a second alignment direction // Use the longest straight edge for horizontal or vertical alignment - std::optional> longestEdge; // Tuple of (shape, length of edge) - for (TopExp_Explorer Ex (face, TopAbs_EDGE); Ex.More(); Ex.Next()) { + std::optional> longestEdge; // Tuple of (shape, + // length of edge) + for (TopExp_Explorer Ex(face, TopAbs_EDGE); Ex.More(); Ex.Next()) { const auto edge = TopoDS::Edge(Ex.Current()); const auto edgeTopoShape = TopoShape(edge); if (!edgeTopoShape.isLinearEdge()) { @@ -1759,13 +1796,17 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect } if (longestEdge.has_value()) { - if (const std::unique_ptr geometry = Geometry::fromShape(get<0>(longestEdge.value()), true)) { - if (const std::unique_ptr geomLine(static_cast(geometry.get())->toLine()); geomLine) { + if (const std::unique_ptr geometry + = Geometry::fromShape(get<0>(longestEdge.value()), true)) { + if (const std::unique_ptr geomLine( + static_cast(geometry.get())->toLine() + ); + geomLine) { directionX = geomLine->getDir().Normalize(); } } } - + return true; } catch (Standard_TypeMismatch&) { @@ -1773,7 +1814,7 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect } } - // Single non-planar face (average normal of a curved surface) + // Single non-planar face (average normal of a curved surface) const TopoDS_Shape shape = topoShape.getShape(); if (shape.ShapeType() == TopAbs_FACE && !topoShape.isPlanar()) { const auto face = TopoDS::Face(shape); @@ -1790,7 +1831,9 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect Standard_Real vTest[4] = {v1, v2, v2, v1}; for (int i = 0; i < 4; ++i) { faceProp.Normal(uTest[i], vTest[i], p, n); - if (n.Magnitude() > Precision::Confusion()) break; + if (n.Magnitude() > Precision::Confusion()) { + break; + } } if (n.Magnitude() <= Precision::Confusion()) { return false; @@ -1803,7 +1846,9 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect for (TopExp_Explorer Ex(face, TopAbs_EDGE); Ex.More(); Ex.Next()) { const auto edge = TopoDS::Edge(Ex.Current()); const auto edgeTopoShape = TopoShape(edge); - if (!edgeTopoShape.isLinearEdge()) continue; + if (!edgeTopoShape.isLinearEdge()) { + continue; + } GProp_GProps props; BRepGProp::LinearProperties(edge, props); const auto length = props.Mass(); @@ -1814,7 +1859,8 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect if (!longestEdge.has_value()) { return true; } - if (const std::unique_ptr geometry = Geometry::fromShape(std::get<0>(longestEdge.value()), true)) { + if (const std::unique_ptr geometry + = Geometry::fromShape(std::get<0>(longestEdge.value()), true)) { if (const auto geomLine = static_cast(geometry.get())->toLine()) { directionX = geomLine->getDir().Normalize(); } @@ -1827,7 +1873,8 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect const size_t edgeCount = topoShape.countSubShapes(TopAbs_EDGE); if (edgeCount == 1) { if (topoShape.isLinearEdge()) { - if (const std::unique_ptr geometry = Geometry::fromShape(topoShape.getSubShape(TopAbs_EDGE, 1), true)) { + if (const std::unique_ptr geometry + = Geometry::fromShape(topoShape.getSubShape(TopAbs_EDGE, 1), true)) { if (const auto geomLine = static_cast(geometry.get())->toLine()) { directionZ = geomLine->getDir().Normalize(); return true; @@ -1837,7 +1884,12 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect else { // Planar curves if (gp_Pln plane; topoShape.findPlane(plane)) { - directionZ = Base::Vector3d(plane.Axis().Direction().X(), plane.Axis().Direction().Y(), plane.Axis().Direction().Z()).Normalize(); + directionZ = Base::Vector3d( + plane.Axis().Direction().X(), + plane.Axis().Direction().Y(), + plane.Axis().Direction().Z() + ) + .Normalize(); return true; } } @@ -1846,8 +1898,9 @@ bool Feature::getCameraAlignmentDirection(Base::Vector3d& directionZ, Base::Vect return GeoFeature::getCameraAlignmentDirection(directionZ, directionX, subname); } -void Feature::guessNewLink(std::string &replacementName, DocumentObject *base, const char *oldLink) { - for (auto &element : Part::Feature::getRelatedElements(base, oldLink)) { +void Feature::guessNewLink(std::string& replacementName, DocumentObject* base, const char* oldLink) +{ + for (auto& element : Part::Feature::getRelatedElements(base, oldLink)) { replacementName.clear(); element.index.appendToStringBuffer(replacementName); FC_WARN("Feature guess element reference " << oldLink << " -> " << replacementName); @@ -1862,17 +1915,17 @@ PROPERTY_SOURCE(Part::FilletBase, Part::Feature) FilletBase::FilletBase() { - ADD_PROPERTY(Base,(nullptr)); - ADD_PROPERTY(Edges,(0,0,0)); - ADD_PROPERTY_TYPE(EdgeLinks,(0), 0, - (App::PropertyType)(App::Prop_ReadOnly|App::Prop_Hidden),0); + ADD_PROPERTY(Base, (nullptr)); + ADD_PROPERTY(Edges, (0, 0, 0)); + ADD_PROPERTY_TYPE(EdgeLinks, (0), 0, (App::PropertyType)(App::Prop_ReadOnly | App::Prop_Hidden), 0); Edges.setSize(0); } short FilletBase::mustExecute() const { - if (Base.isTouched() || Edges.isTouched() || EdgeLinks.isTouched()) + if (Base.isTouched() || Edges.isTouched() || EdgeLinks.isTouched()) { return 1; + } return 0; } @@ -1886,55 +1939,64 @@ App::DocumentObjectExecReturn* FilletBase::execute() return Part::Feature::execute(); } -void FilletBase::onChanged(const App::Property *prop) { - if(getDocument() && !getDocument()->testStatus(App::Document::Restoring)) { - if(prop == &Edges || prop == &Base) { - if(!prop->testStatus(App::Property::User3)) +void FilletBase::onChanged(const App::Property* prop) +{ + if (getDocument() && !getDocument()->testStatus(App::Document::Restoring)) { + if (prop == &Edges || prop == &Base) { + if (!prop->testStatus(App::Property::User3)) { syncEdgeLink(); + } } } Feature::onChanged(prop); } -void FilletBase::onDocumentRestored() { - if(EdgeLinks.getSubValues().empty()) +void FilletBase::onDocumentRestored() +{ + if (EdgeLinks.getSubValues().empty()) { syncEdgeLink(); + } Feature::onDocumentRestored(); } -void FilletBase::syncEdgeLink() { - if(!Base.getValue() || !Edges.getSize()) { +void FilletBase::syncEdgeLink() +{ + if (!Base.getValue() || !Edges.getSize()) { EdgeLinks.setValue(0); return; } std::vector subs; std::string sub("Edge"); - for(auto &info : Edges.getValues()) - subs.emplace_back(sub+std::to_string(info.edgeid)); - EdgeLinks.setValue(Base.getValue(),subs); + for (auto& info : Edges.getValues()) { + subs.emplace_back(sub + std::to_string(info.edgeid)); + } + EdgeLinks.setValue(Base.getValue(), subs); } -void FilletBase::onUpdateElementReference(const App::Property *prop) { - if(prop!=&EdgeLinks || !getNameInDocument()) +void FilletBase::onUpdateElementReference(const App::Property* prop) +{ + if (prop != &EdgeLinks || !getNameInDocument()) { return; + } auto values = Edges.getValues(); - const auto &subs = EdgeLinks.getSubValues(); - for(size_t i=0;i=subs.size()) { + const auto& subs = EdgeLinks.getSubValues(); + for (size_t i = 0; i < values.size(); ++i) { + if (i >= subs.size()) { FC_WARN("fillet edge count mismatch in object " << getFullName()); break; } int idx = 0; - sscanf(subs[i].c_str(),"Edge%d",&idx); - if(idx) + sscanf(subs[i].c_str(), "Edge%d", &idx); + if (idx) { values[i].edgeid = idx; - else - FC_WARN("invalid fillet edge link '" << subs[i] << "' in object " - << getFullName()); + } + else { + FC_WARN("invalid fillet edge link '" << subs[i] << "' in object " << getFullName()); + } } - Edges.setStatus(App::Property::User3,true); + Edges.setStatus(App::Property::User3, true); Edges.setValues(values); - Edges.setStatus(App::Property::User3,false); + Edges.setStatus(App::Property::User3, false); } // --------------------------------------------------------- @@ -1942,17 +2004,21 @@ void FilletBase::onUpdateElementReference(const App::Property *prop) { PROPERTY_SOURCE(Part::FeatureExt, Part::Feature) - -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Part::FeaturePython, Part::Feature) -template<> const char* Part::FeaturePython::getViewProviderName() const { +template<> +const char* Part::FeaturePython::getViewProviderName() const +{ return "PartGui::ViewProviderPython"; } -template<> PyObject* Part::FeaturePython::getPyObject() { +template<> +PyObject* Part::FeaturePython::getPyObject() +{ if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePythonPyT(this),true); + PythonObject = Py::Object(new FeaturePythonPyT(this), true); } return Py::new_reference_to(PythonObject); } @@ -1960,15 +2026,18 @@ template<> PyObject* Part::FeaturePython::getPyObject() { // explicit template instantiation template class PartExport FeaturePythonT; -} +} // namespace App // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. std::vector Part::findAllFacesCutBy( - const TopoDS_Shape& shape, const TopoDS_Shape& face, const gp_Dir& dir) + const TopoDS_Shape& shape, + const TopoDS_Shape& face, + const gp_Dir& dir +) { // Find the centre of gravity of the face GProp_GProps props; - BRepGProp::SurfaceProperties(face,props); + BRepGProp::SurfaceProperties(face, props); gp_Pnt cog = props.CentreOfMass(); // create a line through the centre of gravity @@ -1983,16 +2052,19 @@ std::vector Part::findAllFacesCutBy( gp_Pnt iPnt = mkSection.Pnt(); double dsq = cog.SquareDistance(iPnt); - if (dsq < Precision::Confusion()) - continue; // intersection with original face + if (dsq < Precision::Confusion()) { + continue; // intersection with original face + } // Find out which side of the original face the intersection is on gce_MakeDir mkDir(cog, iPnt); - if (!mkDir.IsDone()) - continue; // some error (appears highly unlikely to happen, though...) + if (!mkDir.IsDone()) { + continue; // some error (appears highly unlikely to happen, though...) + } - if (mkDir.Value().IsOpposite(dir, Precision::Confusion())) - continue; // wrong side of face (opposite to extrusion direction) + if (mkDir.Value().IsOpposite(dir, Precision::Confusion())) { + continue; // wrong side of face (opposite to extrusion direction) + } cutFaces newF; newF.face = mkSection.Face(); @@ -2003,8 +2075,11 @@ std::vector Part::findAllFacesCutBy( return result; } -std::vector -Part::findAllFacesCutBy(const TopoShape& shape, const TopoShape& face, const gp_Dir& dir) +std::vector Part::findAllFacesCutBy( + const TopoShape& shape, + const TopoShape& face, + const gp_Dir& dir +) { // Find the centre of gravity of the face GProp_GProps props; @@ -2048,8 +2123,13 @@ Part::findAllFacesCutBy(const TopoShape& shape, const TopoShape& face, const gp_ return result; } -bool Part::checkIntersection(const TopoDS_Shape& first, const TopoDS_Shape& second, - const bool quick, const bool touch_is_intersection) { +bool Part::checkIntersection( + const TopoDS_Shape& first, + const TopoDS_Shape& second, + const bool quick, + const bool touch_is_intersection +) +{ Bnd_Box first_bb, second_bb; BRepBndLib::Add(first, first_bb); @@ -2061,41 +2141,48 @@ bool Part::checkIntersection(const TopoDS_Shape& first, const TopoDS_Shape& seco // Improving reliability: If it fails sometimes when touching and touching is intersection, // then please check further unless the user asked for a quick potentially unreliable result - if (first_bb.IsOut(second_bb) && !touch_is_intersection) - return false; // no intersection - if (quick && !first_bb.IsOut(second_bb)) - return true; // assumed intersection + if (first_bb.IsOut(second_bb) && !touch_is_intersection) { + return false; // no intersection + } + if (quick && !first_bb.IsOut(second_bb)) { + return true; // assumed intersection + } if (touch_is_intersection) { // If both shapes fuse to a single solid, then they intersect FCBRepAlgoAPI_Fuse mkFuse(first, second); - if (!mkFuse.IsDone()) + if (!mkFuse.IsDone()) { return false; - if (mkFuse.Shape().IsNull()) + } + if (mkFuse.Shape().IsNull()) { return false; + } // Did we get one or two solids? TopExp_Explorer xp; - xp.Init(mkFuse.Shape(),TopAbs_SOLID); + xp.Init(mkFuse.Shape(), TopAbs_SOLID); if (xp.More()) { // At least one solid xp.Next(); return (xp.More() == Standard_False); - } else { + } + else { return false; } - } else { + } + else { // If both shapes have common material, then they intersect FCBRepAlgoAPI_Common mkCommon(first, second); - if (!mkCommon.IsDone()) + if (!mkCommon.IsDone()) { return false; - if (mkCommon.Shape().IsNull()) + } + if (mkCommon.Shape().IsNull()) { return false; + } // Did we get a solid? TopExp_Explorer xp; - xp.Init(mkCommon.Shape(),TopAbs_SOLID); + xp.Init(mkCommon.Shape(), TopAbs_SOLID); return (xp.More() == Standard_True); } - } diff --git a/src/Mod/Part/App/PartFeature.h b/src/Mod/Part/App/PartFeature.h index 4165835378..a36130abe0 100644 --- a/src/Mod/Part/App/PartFeature.h +++ b/src/Mod/Part/App/PartFeature.h @@ -65,7 +65,7 @@ class PartFeaturePy; /** Base class of all shape feature classes in FreeCAD */ -class PartExport Feature : public App::GeoFeature +class PartExport Feature: public App::GeoFeature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Feature); @@ -88,17 +88,21 @@ public: PyObject* getPyObject() override; - App::ElementNamePair getElementName( - const char *name, ElementNameType type=Normal) const override; + App::ElementNamePair getElementName(const char* name, ElementNameType type = Normal) const override; - static std::list getElementHistory(App::DocumentObject *obj, - const char *name, bool recursive=true, bool sameType=false); + static std::list getElementHistory( + App::DocumentObject* obj, + const char* name, + bool recursive = true, + bool sameType = false + ); - static QVector - getRelatedElements(App::DocumentObject* obj, - const char* name, - HistoryTraceType sameType = HistoryTraceType::followTypeChange, - bool withCache = true); + static QVector getRelatedElements( + App::DocumentObject* obj, + const char* name, + HistoryTraceType sameType = HistoryTraceType::followTypeChange, + bool withCache = true + ); /** Obtain the element name from a feature based of the element name of its source feature * @@ -112,17 +116,23 @@ public: * * @return Return a vector of pair of new style and old style element names. */ - static QVector - getElementFromSource(App::DocumentObject *obj, - const char *subname, - App::DocumentObject *src, - const char *srcSub, - bool single = false); + static QVector getElementFromSource( + App::DocumentObject* obj, + const char* subname, + App::DocumentObject* src, + const char* srcSub, + bool single = false + ); TopLoc_Location getLocation() const; - DocumentObject *getSubObject(const char *subname, PyObject **pyObj, - Base::Matrix4D *mat, bool transform, int depth) const override; + DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* mat, + bool transform, + int depth + ) const override; App::Material getMaterialAppearance() const override; void setMaterialAppearance(const App::Material& material) override; @@ -147,42 +157,64 @@ public: * @param transform: if true, apply obj's transformation. Set to false * if pmat already include obj's transformation matrix. */ - static TopoDS_Shape getShape(const App::DocumentObject *obj, ShapeOptions options, - const char *subname=nullptr, Base::Matrix4D *pmat=nullptr, - App::DocumentObject **owner=nullptr); + static TopoDS_Shape getShape( + const App::DocumentObject* obj, + ShapeOptions options, + const char* subname = nullptr, + Base::Matrix4D* pmat = nullptr, + App::DocumentObject** owner = nullptr + ); - static TopoShape getTopoShape(const App::DocumentObject* obj, ShapeOptions options, - const char* subname=nullptr, Base::Matrix4D* pmat=nullptr, - App::DocumentObject**owner=nullptr); + static TopoShape getTopoShape( + const App::DocumentObject* obj, + ShapeOptions options, + const char* subname = nullptr, + Base::Matrix4D* pmat = nullptr, + App::DocumentObject** owner = nullptr + ); static TopoShape simplifyCompound(TopoShape compoundShape); static void clearShapeCache(); - static App::DocumentObject *getShapeOwner(const App::DocumentObject *obj, const char *subname=nullptr); + static App::DocumentObject* getShapeOwner( + const App::DocumentObject* obj, + const char* subname = nullptr + ); - static bool hasShapeOwner(const App::DocumentObject *obj, const char *subname=nullptr) { - auto owner = getShapeOwner(obj,subname); + static bool hasShapeOwner(const App::DocumentObject* obj, const char* subname = nullptr) + { + auto owner = getShapeOwner(obj, subname); return owner && owner->isDerivedFrom(getClassTypeId()); } - static Feature* - create(const TopoShape& shape, const char* name = nullptr, App::Document* document = nullptr); + static Feature* create( + const TopoShape& shape, + const char* name = nullptr, + App::Document* document = nullptr + ); - static bool isElementMappingDisabled(App::PropertyContainer *container); + static bool isElementMappingDisabled(App::PropertyContainer* container); - bool getCameraAlignmentDirection(Base::Vector3d &directionZ, Base::Vector3d &directionX, const char *subname) const override; + bool getCameraAlignmentDirection( + Base::Vector3d& directionZ, + Base::Vector3d& directionX, + const char* subname + ) const override; - static void guessNewLink(std::string &replacementName, DocumentObject *base, const char *oldLink); + static void guessNewLink(std::string& replacementName, DocumentObject* base, const char* oldLink); + + const std::vector& searchElementCache( + const std::string& element, + Data::SearchOptions options = Data::SearchOption::CheckGeometry, + double tol = 1e-7, + double atol = 1e-10 + ) const override; - const std::vector& searchElementCache(const std::string &element, - Data::SearchOptions options = Data::SearchOption::CheckGeometry, - double tol = 1e-7, - double atol = 1e-10) const override; protected: /// recompute only this object - App::DocumentObjectExecReturn *recompute() override; + App::DocumentObjectExecReturn* recompute() override; /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; void onBeforeChange(const App::Property* prop) override; void onChanged(const App::Property* prop) override; void onDocumentRestored() override; @@ -190,7 +222,7 @@ protected: void copyMaterial(Feature* feature); void copyMaterial(App::DocumentObject* link); - void registerElementCache(const std::string &prefix, PropertyPartShape *prop); + void registerElementCache(const std::string& prefix, PropertyPartShape* prop); /** Helper function to obtain mapped and indexed element name from a shape * @params shape: source shape @@ -201,7 +233,7 @@ protected: * Vertex/Edge/Face, this function will auto generate a name from primary * sub-shapes. */ - App::ElementNamePair getExportElementName(TopoShape shape, const char *name) const; + App::ElementNamePair getExportElementName(TopoShape shape, const char* name) const; /** * Build a history of changes @@ -210,25 +242,30 @@ protected: * newS: The new shape that was created by the operation * oldS: The original shape prior to the operation */ - ShapeHistory buildHistory(BRepBuilderAPI_MakeShape&, TopAbs_ShapeEnum type, - const TopoDS_Shape& newS, const TopoDS_Shape& oldS); + ShapeHistory buildHistory( + BRepBuilderAPI_MakeShape&, + TopAbs_ShapeEnum type, + const TopoDS_Shape& newS, + const TopoDS_Shape& oldS + ); ShapeHistory joinHistory(const ShapeHistory&, const ShapeHistory&); + private: struct ElementCache; std::map _elementCache; std::vector> _elementCachePrefixMap; }; -class PartExport FilletBase : public Part::Feature +class PartExport FilletBase: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::FilletBase); public: FilletBase(); - App::PropertyLink Base; + App::PropertyLink Base; PropertyFilletEdges Edges; - App::PropertyLinkSub EdgeLinks; + App::PropertyLinkSub EdgeLinks; short mustExecute() const override; App::DocumentObjectExecReturn* execute() override; @@ -236,7 +273,7 @@ public: protected: void onDocumentRestored() override; - void onChanged(const App::Property *) override; + void onChanged(const App::Property*) override; void syncEdgeLink(); }; @@ -245,12 +282,13 @@ using FeaturePython = App::FeaturePythonT; /** Base class of all shape feature classes in FreeCAD */ -class PartExport FeatureExt : public Feature +class PartExport FeatureExt: public Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::FeatureExt); public: - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPartExt"; } }; @@ -261,45 +299,53 @@ public: * Useful for the "up to face" options to pocket or pad */ // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. -struct cutFaces { +struct cutFaces +{ TopoDS_Face face; double distsq; }; // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. -PartExport -std::vector findAllFacesCutBy(const TopoDS_Shape& shape, - const TopoDS_Shape& face, const gp_Dir& dir); +PartExport std::vector findAllFacesCutBy( + const TopoDS_Shape& shape, + const TopoDS_Shape& face, + const gp_Dir& dir +); struct cutTopoShapeFaces { TopoShape face; double distsq; }; -PartExport std::vector -findAllFacesCutBy(const TopoShape& shape, const TopoShape& face, const gp_Dir& dir); +PartExport std::vector findAllFacesCutBy( + const TopoShape& shape, + const TopoShape& face, + const gp_Dir& dir +); /** - * Check for intersection between the two shapes. Only solids are guaranteed to work properly - * There are two modes: - * 1. Bounding box check only - quick but inaccurate - * 2. Bounding box check plus (if necessary) boolean operation - costly but accurate - * Return true if the shapes intersect, false if they don't - * The flag touch_is_intersection decides whether shapes touching at distance zero are regarded - * as intersecting or not - * 1. If set to true, a true check result means that a boolean fuse operation between the two shapes - * will return a single solid - * 2. If set to false, a true check result means that a boolean common operation will return a - * valid solid - * If there is any error in the boolean operations, the check always returns false - */ -PartExport -bool checkIntersection(const TopoDS_Shape& first, const TopoDS_Shape& second, - const bool quick, const bool touch_is_intersection); + * Check for intersection between the two shapes. Only solids are guaranteed to work properly + * There are two modes: + * 1. Bounding box check only - quick but inaccurate + * 2. Bounding box check plus (if necessary) boolean operation - costly but accurate + * Return true if the shapes intersect, false if they don't + * The flag touch_is_intersection decides whether shapes touching at distance zero are regarded + * as intersecting or not + * 1. If set to true, a true check result means that a boolean fuse operation between the two shapes + * will return a single solid + * 2. If set to false, a true check result means that a boolean common operation will return a + * valid solid + * If there is any error in the boolean operations, the check always returns false + */ +PartExport bool checkIntersection( + const TopoDS_Shape& first, + const TopoDS_Shape& second, + const bool quick, + const bool touch_is_intersection +); -} //namespace Part +} // namespace Part ENABLE_BITMASK_OPERATORS(Part::ShapeOption) -#endif // PART_FEATURE_H - +#endif // PART_FEATURE_H diff --git a/src/Mod/Part/App/PartFeature.pyi b/src/Mod/Part/App/PartFeature.pyi index e1a52920b4..98f3722106 100644 --- a/src/Mod/Part/App/PartFeature.pyi +++ b/src/Mod/Part/App/PartFeature.pyi @@ -3,7 +3,6 @@ from App.GeoFeature import GeoFeature from App.DocumentObject import DocumentObject from typing import List, Tuple, Union - @export( Twin="Feature", TwinPointer="Feature", diff --git a/src/Mod/Part/App/PartFeaturePyImp.cpp b/src/Mod/Part/App/PartFeaturePyImp.cpp index 871ba26318..2a96eae71b 100644 --- a/src/Mod/Part/App/PartFeaturePyImp.cpp +++ b/src/Mod/Part/App/PartFeaturePyImp.cpp @@ -42,36 +42,60 @@ std::string PartFeaturePy::representation() const PyObject* PartFeaturePy::getElementHistory(PyObject* args, PyObject* kwds) const { - const char *name; - PyObject *recursive = Py_True; - PyObject *sameType = Py_False; - PyObject *showName = Py_False; + const char* name; + PyObject* recursive = Py_True; + PyObject* sameType = Py_False; + PyObject* showName = Py_False; - static const std::array kwlist{"elementName", "recursive", "sameType", "showName", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "s|OOO", kwlist, &name, &recursive, &sameType, &showName)) { + static const std::array + kwlist {"elementName", "recursive", "sameType", "showName", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "s|OOO", + kwlist, + &name, + &recursive, + &sameType, + &showName + )) { return {}; } auto feature = getFeaturePtr(); Py::List list; bool showObjName = PyObject_IsTrue(showName); - PY_TRY { + PY_TRY + { std::string tmp; - for (auto &history: Feature::getElementHistory(feature, name, - PyObject_IsTrue(recursive), PyObject_IsTrue(sameType))) { + for (auto& history : Feature::getElementHistory( + feature, + name, + PyObject_IsTrue(recursive), + PyObject_IsTrue(sameType) + )) { Py::Tuple ret(3); if (history.obj) { if (showObjName) { - ret.setItem(0, Py::TupleN(Py::String(history.obj->getFullName()), - Py::String(history.obj->Label.getValue()))); - } else + ret.setItem( + 0, + Py::TupleN( + Py::String(history.obj->getFullName()), + Py::String(history.obj->Label.getValue()) + ) + ); + } + else { ret.setItem(0, Py::Object(history.obj->getPyObject(), true)); - } else + } + } + else { ret.setItem(0, Py::Long(history.tag)); + } tmp.clear(); ret.setItem(1, Py::String(history.element.appendToBuffer(tmp))); Py::List intermedates; - for (auto &h: history.intermediates) { + for (auto& h : history.intermediates) { tmp.clear(); intermedates.append(Py::String(h.appendToBuffer(tmp))); } @@ -79,15 +103,16 @@ PyObject* PartFeaturePy::getElementHistory(PyObject* args, PyObject* kwds) const list.append(ret); } return Py::new_reference_to(list); - } PY_CATCH; + } + PY_CATCH; } -PyObject *PartFeaturePy::getCustomAttributes(const char* ) const +PyObject* PartFeaturePy::getCustomAttributes(const char*) const { return nullptr; } -int PartFeaturePy::setCustomAttributes(const char* , PyObject *) +int PartFeaturePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/PartFeatureReference.cpp b/src/Mod/Part/App/PartFeatureReference.cpp index e5456bac7d..31872cd7b2 100644 --- a/src/Mod/Part/App/PartFeatureReference.cpp +++ b/src/Mod/Part/App/PartFeatureReference.cpp @@ -23,8 +23,8 @@ ***************************************************************************/ -# include -# include +#include +#include #include @@ -49,7 +49,7 @@ short FeatureReference::mustExecute() const return GeoFeature::mustExecute(); } -App::DocumentObjectExecReturn *FeatureReference::execute() +App::DocumentObjectExecReturn* FeatureReference::execute() { return App::DocumentObject::StdReturn; } @@ -63,10 +63,8 @@ TopLoc_Location FeatureReference::getLocation() const rot.getValue(axis, angle); gp_Trsf trf; trf.SetRotation(gp_Ax1(gp_Pnt(), gp_Dir(axis.x, axis.y, axis.z)), angle); - trf.SetTranslationPart(gp_Vec(pl.getPosition().x,pl.getPosition().y,pl.getPosition().z)); + trf.SetTranslationPart(gp_Vec(pl.getPosition().x, pl.getPosition().y, pl.getPosition().z)); return TopLoc_Location(trf); } // --------------------------------------------------------- - - diff --git a/src/Mod/Part/App/PartFeatureReference.h b/src/Mod/Part/App/PartFeatureReference.h index f35bdf5e58..e2a0cc31de 100644 --- a/src/Mod/Part/App/PartFeatureReference.h +++ b/src/Mod/Part/App/PartFeatureReference.h @@ -39,7 +39,7 @@ class PartFeaturePy; /** Base class of all shape feature classes in FreeCAD */ -class PartExport FeatureReference : public App::GeoFeature +class PartExport FeatureReference: public App::GeoFeature { PROPERTY_HEADER_WITH_OVERRIDE(Part::FeatureReference); @@ -48,26 +48,27 @@ public: FeatureReference(); ~FeatureReference() override; - App::PropertyLink Reference; + App::PropertyLink Reference; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPartReference"; } + protected: TopLoc_Location getLocation() const; - }; -} //namespace Part +} // namespace Part -#endif // PART_FeatureReference_H +#endif // PART_FeatureReference_H diff --git a/src/Mod/Part/App/PartFeatures.cpp b/src/Mod/Part/App/PartFeatures.cpp index 88758a8fec..4049b8dd33 100644 --- a/src/Mod/Part/App/PartFeatures.cpp +++ b/src/Mod/Part/App/PartFeatures.cpp @@ -59,11 +59,13 @@ RuledSurface::RuledSurface() { ADD_PROPERTY_TYPE(Curve1, (nullptr), "Ruled Surface", App::Prop_None, "Curve of ruled surface"); ADD_PROPERTY_TYPE(Curve2, (nullptr), "Ruled Surface", App::Prop_None, "Curve of ruled surface"); - ADD_PROPERTY_TYPE(Orientation, - ((long)0), - "Ruled Surface", - App::Prop_None, - "Orientation of ruled surface"); + ADD_PROPERTY_TYPE( + Orientation, + ((long)0), + "Ruled Surface", + App::Prop_None, + "Orientation of ruled surface" + ); Orientation.setEnums(OrientationEnums); } @@ -86,11 +88,14 @@ void RuledSurface::onChanged(const App::Property* prop) Part::Feature::onChanged(prop); } -App::DocumentObjectExecReturn* RuledSurface::getShape(const App::PropertyLinkSub& link, - TopoDS_Shape& shape) const +App::DocumentObjectExecReturn* RuledSurface::getShape( + const App::PropertyLinkSub& link, + TopoDS_Shape& shape +) const { App::DocumentObject* obj = link.getValue(); - const Part::TopoShape part = Part::Feature::getTopoShape(obj, ShapeOption::ResolveLink | ShapeOption::Transform); + const Part::TopoShape part + = Part::Feature::getTopoShape(obj, ShapeOption::ResolveLink | ShapeOption::Transform); if (part.isNull()) { return new App::DocumentObjectExecReturn("No shape linked."); } @@ -127,7 +132,8 @@ App::DocumentObjectExecReturn* RuledSurface::execute() std::array links = {&Curve1, &Curve2}; for (auto link : links) { App::DocumentObject* obj = link->getValue(); - const Part::TopoShape part = Part::Feature::getTopoShape(obj, ShapeOption::ResolveLink | ShapeOption::Transform); + const Part::TopoShape part + = Part::Feature::getTopoShape(obj, ShapeOption::ResolveLink | ShapeOption::Transform); if (part.isNull()) { return new App::DocumentObjectExecReturn("No shape linked."); } @@ -140,11 +146,11 @@ App::DocumentObjectExecReturn* RuledSurface::execute() return new App::DocumentObjectExecReturn("Not exactly one sub-shape linked."); } else { - shapes.push_back(getTopoShape(link->getValue(), - ShapeOption::NeedSubElement - | ShapeOption::ResolveLink - | ShapeOption::Transform, - subs.front().c_str())); + shapes.push_back(getTopoShape( + link->getValue(), + ShapeOption::NeedSubElement | ShapeOption::ResolveLink | ShapeOption::Transform, + subs.front().c_str() + )); } if (shapes.back().isNull()) { return new App::DocumentObjectExecReturn("Invalid link."); @@ -154,7 +160,6 @@ App::DocumentObjectExecReturn* RuledSurface::execute() res.makeElementRuledSurface(shapes, Orientation.getValue()); this->Shape.setValue(res); return Part::Feature::execute(); - } catch (Standard_Failure& e) { @@ -167,9 +172,7 @@ App::DocumentObjectExecReturn* RuledSurface::execute() // ---------------------------------------------------------------------------- -App::PropertyIntegerConstraint::Constraints Loft::Degrees = {2, - Geom_BSplineSurface::MaxDegree(), - 1}; +App::PropertyIntegerConstraint::Constraints Loft::Degrees = {2, Geom_BSplineSurface::MaxDegree(), 1}; PROPERTY_SOURCE(Part::Loft, Part::Feature) @@ -181,8 +184,13 @@ Loft::Loft() ADD_PROPERTY_TYPE(Ruled, (false), "Loft", App::Prop_None, "Ruled surface"); ADD_PROPERTY_TYPE(Closed, (false), "Loft", App::Prop_None, "Close Last to First Profile"); ADD_PROPERTY_TYPE(MaxDegree, (5), "Loft", App::Prop_None, "Maximum Degree"); - ADD_PROPERTY_TYPE(Linearize,(false), "Loft", App::Prop_None, - "Linearize the result shape by simplifying linear edge and planar face into line and plane"); + ADD_PROPERTY_TYPE( + Linearize, + (false), + "Loft", + App::Prop_None, + "Linearize the result shape by simplifying linear edge and planar face into line and plane" + ); MaxDegree.setConstraints(&Degrees); } @@ -232,7 +240,7 @@ App::DocumentObjectExecReturn* Loft::execute() TopoShape result(0, getDocument()->getStringHasher()); result.makeElementLoft(shapes, isSolid, isRuled, isClosed, degMax); if (Linearize.getValue()) { - result.linearize( LinearizeFace::linearizeFaces, LinearizeEdge::noEdges); + result.linearize(LinearizeFace::linearizeFaces, LinearizeEdge::noEdges); } this->Shape.setValue(result); return Part::Feature::execute(); @@ -245,10 +253,7 @@ App::DocumentObjectExecReturn* Loft::execute() // ---------------------------------------------------------------------------- -const char* Part::Sweep::TransitionEnums[] = {"Transformed", - "Right corner", - "Round corner", - nullptr}; +const char* Part::Sweep::TransitionEnums[] = {"Transformed", "Right corner", "Round corner", nullptr}; PROPERTY_SOURCE(Part::Sweep, Part::Feature) @@ -260,8 +265,13 @@ Sweep::Sweep() ADD_PROPERTY_TYPE(Solid, (true), "Sweep", App::Prop_None, "Create solid"); ADD_PROPERTY_TYPE(Frenet, (true), "Sweep", App::Prop_None, "Frenet"); ADD_PROPERTY_TYPE(Transition, (long(1)), "Sweep", App::Prop_None, "Transition mode"); - ADD_PROPERTY_TYPE(Linearize,(false), "Sweep", App::Prop_None, - "Linearize the result shape by simplifying linear edge and planar face into line and plane"); + ADD_PROPERTY_TYPE( + Linearize, + (false), + "Sweep", + App::Prop_None, + "Linearize the result shape by simplifying linear edge and planar face into line and plane" + ); Transition.setEnums(TransitionEnums); } @@ -312,7 +322,11 @@ App::DocumentObjectExecReturn* Sweep::execute() } spineShapes.push_back(shape); } - spine = TopoShape(0).makeElementCompound(spineShapes, 0, TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + spine = TopoShape(0).makeElementCompound( + spineShapes, + 0, + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); } std::vector shapes; shapes.push_back(spine); @@ -388,9 +402,11 @@ short Thickness::mustExecute() const return 0; } -void Thickness::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Thickness::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { if (prop == &Value && strcmp(TypeName, "App::PropertyFloat") == 0) { App::PropertyFloat v; @@ -427,15 +443,10 @@ App::DocumentObjectExecReturn* Thickness::execute() short mode = (short)Mode.getValue(); short join = (short)Join.getValue(); - this->Shape.setValue(TopoShape(0, getDocument()->getStringHasher()) - .makeElementThickSolid(base, - shapes, - thickness, - tol, - inter, - self, - mode, - static_cast(join))); + this->Shape.setValue( + TopoShape(0, getDocument()->getStringHasher()) + .makeElementThickSolid(base, shapes, thickness, tol, inter, self, mode, static_cast(join)) + ); return Part::Feature::execute(); } @@ -477,7 +488,8 @@ Reverse::Reverse() App::DocumentObjectExecReturn* Reverse::execute() { App::DocumentObject* source = Source.getValue(); - Part::TopoShape topoShape = Part::Feature::getTopoShape(source, ShapeOption::ResolveLink | ShapeOption::Transform); + Part::TopoShape topoShape + = Part::Feature::getTopoShape(source, ShapeOption::ResolveLink | ShapeOption::Transform); if (topoShape.isNull()) { return new App::DocumentObjectExecReturn("No part object linked."); } diff --git a/src/Mod/Part/App/PartFeatures.h b/src/Mod/Part/App/PartFeatures.h index 9143d3464f..29ff9e5ddf 100644 --- a/src/Mod/Part/App/PartFeatures.h +++ b/src/Mod/Part/App/PartFeatures.h @@ -36,7 +36,7 @@ namespace Part { -class PartExport RuledSurface : public Part::Feature +class PartExport RuledSurface: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::RuledSurface); @@ -50,15 +50,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderRuledSurface"; } //@} protected: - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; private: App::DocumentObjectExecReturn* getShape(const App::PropertyLinkSub& link, TopoDS_Shape&) const; @@ -67,7 +68,7 @@ private: static const char* OrientationEnums[]; }; -class PartExport Loft : public Part::Feature +class PartExport Loft: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Loft); @@ -84,21 +85,22 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderLoft"; } //@} protected: - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; private: static App::PropertyIntegerConstraint::Constraints Degrees; }; -class PartExport Sweep : public Part::Feature +class PartExport Sweep: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Sweep); @@ -115,21 +117,22 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderSweep"; } //@} protected: - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; private: static const char* TransitionEnums[]; }; -class PartExport Thickness : public Part::Feature +class PartExport Thickness: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Thickness); @@ -146,22 +149,27 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderThickness"; } //@} protected: - void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; private: static const char* ModeEnums[]; static const char* JoinEnums[]; }; -class Refine : public Part::Feature +class Refine: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Refine); @@ -173,14 +181,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; - const char* getViewProviderName() const override { + App::DocumentObjectExecReturn* execute() override; + const char* getViewProviderName() const override + { return "PartGui::ViewProviderRefine"; } //@} }; -class Reverse : public Part::Feature +class Reverse: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(Part::Reverse); @@ -193,13 +202,14 @@ public: //@{ /// recalculate the feature App::DocumentObjectExecReturn* execute() override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderReverse"; } //@} }; -} //namespace Part +} // namespace Part -#endif // PART_FEATURES_H +#endif // PART_FEATURES_H diff --git a/src/Mod/Part/App/PartPyCXX.cpp b/src/Mod/Part/App/PartPyCXX.cpp index 92f143d3af..80a618c9a2 100644 --- a/src/Mod/Part/App/PartPyCXX.cpp +++ b/src/Mod/Part/App/PartPyCXX.cpp @@ -26,28 +26,30 @@ #include "PartPyCXX.h" -namespace Part { -PartExport Py::Object shape2pyshape(const TopoShape &shape) +namespace Part { - PyObject* ret = const_cast(shape).getPyObject(); +PartExport Py::Object shape2pyshape(const TopoShape& shape) +{ + PyObject* ret = const_cast(shape).getPyObject(); return Py::asObject(ret); } -PartExport Py::Object shape2pyshape(const TopoDS_Shape &shape) { +PartExport Py::Object shape2pyshape(const TopoDS_Shape& shape) +{ return shape2pyshape(TopoShape(shape)); } -} //namespace Part +} // namespace Part -namespace Py { - template<> - bool TopoShape::accepts (PyObject *pyob) const - { - return (pyob && PyObject_TypeCheck(pyob, &(Part::TopoShapePy::Type))); - } - - // explicit template instantiation - template class PartExport ExtensionObject; +namespace Py +{ +template<> +bool TopoShape::accepts(PyObject* pyob) const +{ + return (pyob && PyObject_TypeCheck(pyob, &(Part::TopoShapePy::Type))); } +// explicit template instantiation +template class PartExport ExtensionObject; +} // namespace Py diff --git a/src/Mod/Part/App/PartPyCXX.h b/src/Mod/Part/App/PartPyCXX.h index 24dab96de6..4e9f709c0e 100644 --- a/src/Mod/Part/App/PartPyCXX.h +++ b/src/Mod/Part/App/PartPyCXX.h @@ -31,17 +31,19 @@ #include -namespace Py { - using TopoShape = ExtensionObject; - template<> - bool TopoShape::accepts (PyObject *pyob) const; -} +namespace Py +{ +using TopoShape = ExtensionObject; +template<> +bool TopoShape::accepts(PyObject* pyob) const; +} // namespace Py -namespace Part { - PartExport Py::Object shape2pyshape(const TopoShape &shape); - PartExport Py::Object shape2pyshape(const TopoDS_Shape &shape); - PartExport void getPyShapes(PyObject *obj, std::vector &shapes); - PartExport std::vector getPyShapes(PyObject *obj); -} +namespace Part +{ +PartExport Py::Object shape2pyshape(const TopoShape& shape); +PartExport Py::Object shape2pyshape(const TopoDS_Shape& shape); +PartExport void getPyShapes(PyObject* obj, std::vector& shapes); +PartExport std::vector getPyShapes(PyObject* obj); +} // namespace Part -#endif //PART_PYCXX_H +#endif // PART_PYCXX_H diff --git a/src/Mod/Part/App/Plane.pyi b/src/Mod/Part/App/Plane.pyi index 3f808757bc..5b408d3111 100644 --- a/src/Mod/Part/App/Plane.pyi +++ b/src/Mod/Part/App/Plane.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from GeometrySurface import GeometrySurface - @export( PythonName="Part.Plane", Twin="GeomPlane", diff --git a/src/Mod/Part/App/PlanePyImp.cpp b/src/Mod/Part/App/PlanePyImp.cpp index 9abe7cb83a..bc5f51f528 100644 --- a/src/Mod/Part/App/PlanePyImp.cpp +++ b/src/Mod/Part/App/PlanePyImp.cpp @@ -22,13 +22,13 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -50,7 +50,7 @@ std::string PlanePy::representation() const return ""; } -PyObject *PlanePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PlanePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of PlanePy and the Twin object return new PlanePy(new GeomPlane); @@ -60,13 +60,12 @@ PyObject *PlanePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pyth int PlanePy::PyInit(PyObject* args, PyObject* kwds) { // plane and distance for offset - PyObject *pPlane; + PyObject* pPlane; double dist; - static const std::array keywords_pd {"Plane", "Distance", nullptr}; + static const std::array keywords_pd {"Plane", "Distance", nullptr}; if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!d", keywords_pd, &(PlanePy::Type), &pPlane, &dist)) { PlanePy* pcPlane = static_cast(pPlane); - Handle(Geom_Plane) plane = Handle(Geom_Plane)::DownCast - (pcPlane->getGeometryPtr()->handle()); + Handle(Geom_Plane) plane = Handle(Geom_Plane)::DownCast(pcPlane->getGeometryPtr()->handle()); GC_MakePlane mc(plane->Pln(), dist); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); @@ -79,12 +78,11 @@ int PlanePy::PyInit(PyObject* args, PyObject* kwds) } // plane from equation - double a,b,c,d; - static const std::array keywords_abcd{"A", "B", "C", "D", nullptr}; + double a, b, c, d; + static const std::array keywords_abcd {"A", "B", "C", "D", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "dddd", keywords_abcd, - &a,&b,&c,&d)) { - GC_MakePlane mc(a,b,c,d); + if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "dddd", keywords_abcd, &a, &b, &c, &d)) { + GC_MakePlane mc(a, b, c, d); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -96,18 +94,24 @@ int PlanePy::PyInit(PyObject* args, PyObject* kwds) } PyObject *pV1, *pV2, *pV3; - static const std::array keywords_ppp{"Point1", "Point2", "Point3", nullptr}; + static const std::array keywords_ppp {"Point1", "Point2", "Point3", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!O!", keywords_ppp, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2, - &(Base::VectorPy::Type), &pV3)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!O!", + keywords_ppp, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2, + &(Base::VectorPy::Type), + &pV3 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); Base::Vector3d v3 = static_cast(pV3)->value(); - GC_MakePlane mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Pnt(v2.x,v2.y,v2.z), - gp_Pnt(v3.x,v3.y,v3.z)); + GC_MakePlane mc(gp_Pnt(v1.x, v1.y, v1.z), gp_Pnt(v2.x, v2.y, v2.z), gp_Pnt(v3.x, v3.y, v3.z)); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -119,15 +123,21 @@ int PlanePy::PyInit(PyObject* args, PyObject* kwds) } // location and normal - static const std::array keywords_cnr {"Location", "Normal", nullptr}; + static const std::array keywords_cnr {"Location", "Normal", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!O!", keywords_cnr, - &(Base::VectorPy::Type), &pV1, - &(Base::VectorPy::Type), &pV2)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!O!", + keywords_cnr, + &(Base::VectorPy::Type), + &pV1, + &(Base::VectorPy::Type), + &pV2 + )) { Base::Vector3d v1 = static_cast(pV1)->value(); Base::Vector3d v2 = static_cast(pV2)->value(); - GC_MakePlane mc(gp_Pnt(v1.x,v1.y,v1.z), - gp_Dir(v2.x,v2.y,v2.z)); + GC_MakePlane mc(gp_Pnt(v1.x, v1.y, v1.z), gp_Dir(v2.x, v2.y, v2.z)); if (!mc.IsDone()) { PyErr_SetString(PartExceptionOCCError, gce_ErrorStatusText(mc.Status())); return -1; @@ -138,40 +148,40 @@ int PlanePy::PyInit(PyObject* args, PyObject* kwds) return 0; } - static const std::array keywords_p {"Plane", nullptr}; + static const std::array keywords_p {"Plane", nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!", keywords_p, &(PlanePy::Type), &pPlane)) { PlanePy* pcPlane = static_cast(pPlane); - Handle(Geom_Plane) plane1 = Handle(Geom_Plane)::DownCast - (pcPlane->getGeometryPtr()->handle()); - Handle(Geom_Plane) plane2 = Handle(Geom_Plane)::DownCast - (this->getGeometryPtr()->handle()); + Handle(Geom_Plane) plane1 = Handle(Geom_Plane)::DownCast(pcPlane->getGeometryPtr()->handle()); + Handle(Geom_Plane) plane2 = Handle(Geom_Plane)::DownCast(this->getGeometryPtr()->handle()); plane2->SetPln(plane1->Pln()); return 0; } - static const std::array keywords_n {nullptr}; + static const std::array keywords_n {nullptr}; PyErr_Clear(); if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "", keywords_n)) { // do nothing return 0; } - PyErr_SetString(PyExc_TypeError, "Plane constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Plane constructor accepts:\n" "-- empty parameter list\n" "-- Plane\n" "-- Plane, Distance\n" "-- Location, Normal\n" "-- Point1, Point2, Point3\n" "-- A, B, C, D\n" - " (as equation: Ax + By + Cz + D = 0.0)"); + " (as equation: Ax + By + Cz + D = 0.0)" + ); return -1; } Py::Object PlanePy::getPosition() const { - Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast - (this->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast(this->getGeomPlanePtr()->handle()); gp_Pnt pnt = this_surf->Location(); return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } @@ -179,7 +189,7 @@ Py::Object PlanePy::getPosition() const void PlanePy::setPosition(Py::Object arg) { gp_Pnt loc; - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); loc.SetX(v.x); @@ -199,8 +209,7 @@ void PlanePy::setPosition(Py::Object arg) } try { - Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast - (this->getGeomPlanePtr()->handle()); + Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast(this->getGeomPlanePtr()->handle()); this_surf->SetLocation(loc); } catch (Standard_Failure& e) { @@ -210,8 +219,9 @@ void PlanePy::setPosition(Py::Object arg) Py::Object PlanePy::getAxis() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeometryPtr()->handle() + ); gp_Dir dir = s->Axis().Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } @@ -219,7 +229,7 @@ Py::Object PlanePy::getAxis() const void PlanePy::setAxis(Py::Object arg) { Standard_Real dir_x, dir_y, dir_z; - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); dir_x = v.x; @@ -239,8 +249,9 @@ void PlanePy::setAxis(Py::Object arg) } try { - Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast - (this->getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast( + this->getGeometryPtr()->handle() + ); gp_Ax1 axis; axis.SetLocation(this_surf->Location()); axis.SetDirection(gp_Dir(dir_x, dir_y, dir_z)); @@ -251,7 +262,7 @@ void PlanePy::setAxis(Py::Object arg) } } -PyObject *PlanePy::getCustomAttributes(const char* /*attr*/) const +PyObject* PlanePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/PlateSurface.pyi b/src/Mod/Part/App/PlateSurface.pyi index ba3eaeb5e8..fecbd9252e 100644 --- a/src/Mod/Part/App/PlateSurface.pyi +++ b/src/Mod/Part/App/PlateSurface.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from GeometrySurface import GeometrySurface - @export( Twin="GeomPlateSurface", TwinPointer="GeomPlateSurface", diff --git a/src/Mod/Part/App/PlateSurfacePyImp.cpp b/src/Mod/Part/App/PlateSurfacePyImp.cpp index 138a3aaa88..03508f385e 100644 --- a/src/Mod/Part/App/PlateSurfacePyImp.cpp +++ b/src/Mod/Part/App/PlateSurfacePyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -47,7 +47,7 @@ std::string PlateSurfacePy::representation() const return ""; } -PyObject *PlateSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PlateSurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of PlateSurfacePy and the Twin object return new PlateSurfacePy(new GeomPlateSurface); @@ -56,9 +56,20 @@ PyObject *PlateSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // constructor method int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) { - static const std::array kwds_Parameter{"Surface", "Points", "Curves", "Degree", - "NbPtsOnCur", "NbIter", "Tol2d", "Tol3d", "TolAng", - "TolCurv", "Anisotropie", nullptr}; + static const std::array kwds_Parameter { + "Surface", + "Points", + "Curves", + "Degree", + "NbPtsOnCur", + "NbIter", + "Tol2d", + "Tol3d", + "TolAng", + "TolCurv", + "Anisotropie", + nullptr + }; PyObject* surface = nullptr; PyObject* points = nullptr; @@ -70,12 +81,27 @@ int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) double Tol3d = 0.0001; double TolAng = 0.01; double TolCurv = 0.1; - PyObject* Anisotropie = Py_False; // NOLINT + PyObject* Anisotropie = Py_False; // NOLINT - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|O!OOiiiddddO!", kwds_Parameter, - &(GeometryPy::Type), &surface, &points, &curves, - &Degree, &NbPtsOnCur, &NbIter, &Tol2d, &Tol3d, &TolAng, &TolCurv, - &PyBool_Type, &Anisotropie)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|O!OOiiiddddO!", + kwds_Parameter, + &(GeometryPy::Type), + &surface, + &points, + &curves, + &Degree, + &NbPtsOnCur, + &NbIter, + &Tol2d, + &Tol3d, + &TolAng, + &TolCurv, + &PyBool_Type, + &Anisotropie + )) { return -1; } @@ -87,8 +113,7 @@ int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) Handle(Geom_Surface) surf; if (surface) { GeometryPy* pcGeo = static_cast(surface); - surf = Handle(Geom_Surface)::DownCast - (pcGeo->getGeometryPtr()->handle()); + surf = Handle(Geom_Surface)::DownCast(pcGeo->getGeometryPtr()->handle()); if (surf.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a surface"); return -1; @@ -96,18 +121,26 @@ int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) } try { - GeomPlate_BuildPlateSurface buildPlate(Degree, NbPtsOnCur, NbIter, Tol2d, Tol3d, TolAng, TolCurv, - Base::asBoolean(Anisotropie)); + GeomPlate_BuildPlateSurface buildPlate( + Degree, + NbPtsOnCur, + NbIter, + Tol2d, + Tol3d, + TolAng, + TolCurv, + Base::asBoolean(Anisotropie) + ); if (!surf.IsNull()) { buildPlate.LoadInitSurface(surf); if (!points && !curves) { - Standard_Real U1,U2,V1,V2; - surf->Bounds(U1,U2,V1,V2); - buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U1,V1),0)); - buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U1,V2),0)); - buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U2,V1),0)); - buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U2,V2),0)); + Standard_Real U1, U2, V1, V2; + surf->Bounds(U1, U2, V1, V2); + buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U1, V1), 0)); + buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U1, V2), 0)); + buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U2, V1), 0)); + buildPlate.Add(new GeomPlate_PointConstraint(surf->Value(U2, V2), 0)); } } @@ -115,7 +148,8 @@ int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) Py::Sequence list(points); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Base::Vector3d vec = Py::Vector(*it).toVector(); - Handle(GeomPlate_PointConstraint) PCont = new GeomPlate_PointConstraint(gp_Pnt(vec.x,vec.y,vec.z),0); + Handle(GeomPlate_PointConstraint) PCont + = new GeomPlate_PointConstraint(gp_Pnt(vec.x, vec.y, vec.z), 0); buildPlate.Add(PCont); } } @@ -123,7 +157,7 @@ int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) if (curves) { Py::Sequence list(curves); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { - //TODO + // TODO } } @@ -138,44 +172,79 @@ int PlateSurfacePy::PyInit(PyObject* args, PyObject* kwds) } } -PyObject* PlateSurfacePy::makeApprox(PyObject *args, PyObject* kwds) +PyObject* PlateSurfacePy::makeApprox(PyObject* args, PyObject* kwds) { - static const std::array kwds_Parameter{"Tol3d", "MaxSegments", "MaxDegree", "MaxDistance", - "CritOrder", "Continuity", "EnlargeCoeff", nullptr}; + static const std::array kwds_Parameter { + "Tol3d", + "MaxSegments", + "MaxDegree", + "MaxDistance", + "CritOrder", + "Continuity", + "EnlargeCoeff", + nullptr + }; - double tol3d=0.01; - int maxSeg=9; - int maxDegree=3; + double tol3d = 0.01; + int maxSeg = 9; + int maxDegree = 3; double dmax = 0.0001; - int critOrder=0; + int critOrder = 0; const char* cont = "C1"; double enlargeCoeff = 1.1; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|diidisd", kwds_Parameter, - &tol3d, &maxSeg, &maxDegree, &dmax, &critOrder, &cont, &enlargeCoeff)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|diidisd", + kwds_Parameter, + &tol3d, + &maxSeg, + &maxDegree, + &dmax, + &critOrder, + &cont, + &enlargeCoeff + )) { return nullptr; } GeomAbs_Shape continuity; std::string uc = cont; - if (uc == "C0") + if (uc == "C0") { continuity = GeomAbs_C0; - else if (uc == "C1") + } + else if (uc == "C1") { continuity = GeomAbs_C1; - else if (uc == "C2") + } + else if (uc == "C2") { continuity = GeomAbs_C2; - else if (uc == "C3") + } + else if (uc == "C3") { continuity = GeomAbs_C3; - else if (uc == "CN") + } + else if (uc == "CN") { continuity = GeomAbs_CN; - else if (uc == "G1") + } + else if (uc == "G1") { continuity = GeomAbs_G1; - else + } + else { continuity = GeomAbs_C1; + } - PY_TRY { - GeomPlate_MakeApprox approx(Handle(GeomPlate_Surface)::DownCast(getGeomPlateSurfacePtr()->handle()), - tol3d, maxSeg, maxDegree, dmax, critOrder, continuity, enlargeCoeff); + PY_TRY + { + GeomPlate_MakeApprox approx( + Handle(GeomPlate_Surface)::DownCast(getGeomPlateSurfacePtr()->handle()), + tol3d, + maxSeg, + maxDegree, + dmax, + critOrder, + continuity, + enlargeCoeff + ); Handle(Geom_BSplineSurface) hSurf = approx.Surface(); if (!hSurf.IsNull()) { @@ -184,10 +253,11 @@ PyObject* PlateSurfacePy::makeApprox(PyObject *args, PyObject* kwds) PyErr_SetString(PyExc_RuntimeError, "Approximation of B-spline surface failed"); return nullptr; - } PY_CATCH_OCC; + } + PY_CATCH_OCC; } -PyObject *PlateSurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* PlateSurfacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Point.pyi b/src/Mod/Part/App/Point.pyi index 0856e66525..f989df2b49 100644 --- a/src/Mod/Part/App/Point.pyi +++ b/src/Mod/Part/App/Point.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from Geometry import Geometry from typing import overload - @export( PythonName="Part.Point", Twin="GeomPoint", @@ -31,20 +30,16 @@ class Point(Geometry): @overload def __init__(self) -> None: ... - @overload def __init__(self, other: "Point") -> None: ... - @overload def __init__(self, coordinates: Vector) -> None: ... - @constmethod def toShape(self) -> object: """ Create a vertex from this point. """ ... - X: float = ... """X component of this point.""" diff --git a/src/Mod/Part/App/PointPyImp.cpp b/src/Mod/Part/App/PointPyImp.cpp index 12679466d6..e3d1a165d5 100644 --- a/src/Mod/Part/App/PointPyImp.cpp +++ b/src/Mod/Part/App/PointPyImp.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -49,7 +49,7 @@ std::string PointPy::representation() const return str.str(); } -PyObject *PointPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PointPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of PointPy and the Twin object return new PointPy(new GeomPoint); @@ -65,16 +65,18 @@ int PointPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pPoint; + PyObject* pPoint; if (PyArg_ParseTuple(args, "O!", &(PointPy::Type), &pPoint)) { // Copy point PointPy* pcPoint = static_cast(pPoint); // get Geom_CartesianPoint of that point - Handle(Geom_CartesianPoint) that_point = Handle(Geom_CartesianPoint)::DownCast - (pcPoint->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) that_point = Handle(Geom_CartesianPoint)::DownCast( + pcPoint->getGeomPointPtr()->handle() + ); // get Geom_CartesianPoint of this point - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); // Assign the coordinates this_point->SetPnt(that_point->Pnt()); @@ -82,30 +84,36 @@ int PointPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pV; + PyObject* pV; if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &pV)) { Base::Vector3d v = static_cast(pV)->value(); - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); - this_point->SetCoord(v.x,v.y,v.z); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); + this_point->SetCoord(v.x, v.y, v.z); return 0; } - PyErr_SetString(PyExc_TypeError, "Point constructor accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "Point constructor accepts:\n" "-- empty parameter list\n" "-- Point\n" - "-- Coordinates vector"); + "-- Coordinates vector" + ); return -1; } -PyObject* PointPy::toShape(PyObject *args) const +PyObject* PointPy::toShape(PyObject* args) const { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); try { if (!this_point.IsNull()) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } BRepBuilderAPI_MakeVertex mkBuilder(this_point->Pnt()); const TopoDS_Vertex& sh = mkBuilder.Vertex(); @@ -124,15 +132,17 @@ PyObject* PointPy::toShape(PyObject *args) const Py::Float PointPy::getX() const { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); return Py::Float(this_point->X()); } void PointPy::setX(Py::Float X) { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); try { this_point->SetX(double(X)); @@ -144,15 +154,17 @@ void PointPy::setX(Py::Float X) Py::Float PointPy::getY() const { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); return Py::Float(this_point->Y()); } void PointPy::setY(Py::Float Y) { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); try { this_point->SetY(double(Y)); @@ -164,15 +176,17 @@ void PointPy::setY(Py::Float Y) Py::Float PointPy::getZ() const { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); return Py::Float(this_point->Z()); } void PointPy::setZ(Py::Float Z) { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (this->getGeomPointPtr()->handle()); + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + this->getGeomPointPtr()->handle() + ); try { this_point->SetZ(double(Z)); @@ -183,7 +197,7 @@ void PointPy::setZ(Py::Float Z) } -PyObject *PointPy::getCustomAttributes(const char* /*attr*/) const +PyObject* PointPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/PreCompiled.h b/src/Mod/Part/App/PreCompiled.h index 3d0667c84d..41cbd409b5 100644 --- a/src/Mod/Part/App/PreCompiled.h +++ b/src/Mod/Part/App/PreCompiled.h @@ -67,7 +67,7 @@ #include "OpenCascadeAll.h" #if defined(FC_OS_WIN32) -#include +# include #endif #ifndef _Standard_Version_HeaderFile diff --git a/src/Mod/Part/App/PrimitiveFeature.cpp b/src/Mod/Part/App/PrimitiveFeature.cpp index f055391370..3edb27df14 100644 --- a/src/Mod/Part/App/PrimitiveFeature.cpp +++ b/src/Mod/Part/App/PrimitiveFeature.cpp @@ -22,28 +22,28 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -52,13 +52,15 @@ #include "PrimitiveFeature.h" #include "PartFeaturePy.h" -namespace Part { - const App::PropertyQuantityConstraint::Constraints apexRange = {-89.9, 89.9, 0.1}; - const App::PropertyQuantityConstraint::Constraints torusRangeV = {-180.0, 180.0, 1.0}; - const App::PropertyQuantityConstraint::Constraints angleRangeU = {0.0, 360.0, 1.0}; - const App::PropertyQuantityConstraint::Constraints angleRangeV = {-90.0, 90.0, 1.0}; - const App::PropertyQuantityConstraint::Constraints quantityRange = {0.0, std::numeric_limits::max(), 0.1}; -} +namespace Part +{ +const App::PropertyQuantityConstraint::Constraints apexRange = {-89.9, 89.9, 0.1}; +const App::PropertyQuantityConstraint::Constraints torusRangeV = {-180.0, 180.0, 1.0}; +const App::PropertyQuantityConstraint::Constraints angleRangeU = {0.0, 360.0, 1.0}; +const App::PropertyQuantityConstraint::Constraints angleRangeV = {-90.0, 90.0, 1.0}; +const App::PropertyQuantityConstraint::Constraints quantityRange + = {0.0, std::numeric_limits::max(), 0.1}; +} // namespace Part using namespace Part; @@ -78,7 +80,8 @@ short Primitive::mustExecute() const return Feature::mustExecute(); } -App::DocumentObjectExecReturn* Primitive::execute() { +App::DocumentObjectExecReturn* Primitive::execute() +{ return Part::Feature::execute(); } @@ -88,10 +91,11 @@ App::DocumentObjectExecReturn* Primitive::execute() { # pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif -namespace Part { - PYTHON_TYPE_DEF(PrimitivePy, PartFeaturePy) - PYTHON_TYPE_IMP(PrimitivePy, PartFeaturePy) -}//explicit bombs +namespace Part +{ +PYTHON_TYPE_DEF(PrimitivePy, PartFeaturePy) +PYTHON_TYPE_IMP(PrimitivePy, PartFeaturePy) +} // namespace Part #if defined(__clang__) # pragma clang diagnostic pop @@ -99,19 +103,23 @@ namespace Part { PyObject* Primitive::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new PrimitivePy(this),true); + PythonObject = Py::Object(new PrimitivePy(this), true); } return Py::new_reference_to(PythonObject); } -void Primitive::Restore(Base::XMLReader &reader) +void Primitive::Restore(Base::XMLReader& reader) { Part::Feature::Restore(reader); } -void Primitive::handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) +void Primitive::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // For #0001652 the property types of many primitive features have changed // from PropertyFloat or PropertyFloatConstraint to a more meaningful type. @@ -119,8 +127,8 @@ void Primitive::handleChangedPropertyType(Base::XMLReader &reader, const char * // types don't match if both inherit from PropertyFloat because all derived // classes do not re-implement the Save/Restore methods. Base::Type inputType = Base::Type::fromName(TypeName); - if (prop->isDerivedFrom() && - inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) { + if (prop->isDerivedFrom() + && inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) { // Do not directly call the property's Restore method in case the implementation // has changed. So, create a temporary PropertyFloat object and assign the value. App::PropertyFloat floatProp; @@ -140,7 +148,7 @@ void Primitive::onChanged(const App::Property* prop) std::string grp = (prop->getGroup() ? prop->getGroup() : ""); if (grp == "Plane" || grp == "Cylinder" || grp == "Cone") { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -154,23 +162,22 @@ PROPERTY_SOURCE(Part::Vertex, Part::Primitive) Vertex::Vertex() { - ADD_PROPERTY(X,(0.0f)); - ADD_PROPERTY(Y,(0.0f)); - ADD_PROPERTY(Z,(0.0f)); + ADD_PROPERTY(X, (0.0f)); + ADD_PROPERTY(Y, (0.0f)); + ADD_PROPERTY(Z, (0.0f)); } Vertex::~Vertex() = default; short Vertex::mustExecute() const { - if (X.isTouched() || - Y.isTouched() || - Z.isTouched()) + if (X.isTouched() || Y.isTouched() || Z.isTouched()) { return 1; + } return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Vertex::execute() +App::DocumentObjectExecReturn* Vertex::execute() { gp_Pnt point; point.SetX(this->X.getValue()); @@ -188,9 +195,9 @@ App::DocumentObjectExecReturn *Vertex::execute() void Vertex::onChanged(const App::Property* prop) { if (!isRestoring()) { - if (prop == &X || prop == &Y || prop == &Z){ + if (prop == &X || prop == &Y || prop == &Z) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -204,29 +211,26 @@ PROPERTY_SOURCE(Part::Line, Part::Primitive) Line::Line() { - ADD_PROPERTY_TYPE(X1,(0.0),"Vertex 1 - Start",App::Prop_None,"X value of the start vertex"); - ADD_PROPERTY_TYPE(Y1,(0.0),"Vertex 1 - Start",App::Prop_None,"Y value of the start vertex"); - ADD_PROPERTY_TYPE(Z1,(0.0),"Vertex 1 - Start",App::Prop_None,"Z value of the start vertex"); - ADD_PROPERTY_TYPE(X2,(0.0),"Vertex 2 - Finish",App::Prop_None,"X value of the finish vertex"); - ADD_PROPERTY_TYPE(Y2,(0.0),"Vertex 2 - Finish",App::Prop_None,"Y value of the finish vertex"); - ADD_PROPERTY_TYPE(Z2,(1.0),"Vertex 2 - Finish",App::Prop_None,"Z value of the finish vertex"); + ADD_PROPERTY_TYPE(X1, (0.0), "Vertex 1 - Start", App::Prop_None, "X value of the start vertex"); + ADD_PROPERTY_TYPE(Y1, (0.0), "Vertex 1 - Start", App::Prop_None, "Y value of the start vertex"); + ADD_PROPERTY_TYPE(Z1, (0.0), "Vertex 1 - Start", App::Prop_None, "Z value of the start vertex"); + ADD_PROPERTY_TYPE(X2, (0.0), "Vertex 2 - Finish", App::Prop_None, "X value of the finish vertex"); + ADD_PROPERTY_TYPE(Y2, (0.0), "Vertex 2 - Finish", App::Prop_None, "Y value of the finish vertex"); + ADD_PROPERTY_TYPE(Z2, (1.0), "Vertex 2 - Finish", App::Prop_None, "Z value of the finish vertex"); } Line::~Line() = default; short Line::mustExecute() const { - if (X1.isTouched() || - Y1.isTouched() || - Z1.isTouched() || - X2.isTouched() || - Y2.isTouched() || - Z2.isTouched()) + if (X1.isTouched() || Y1.isTouched() || Z1.isTouched() || X2.isTouched() || Y2.isTouched() + || Z2.isTouched()) { return 1; + } return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Line::execute() +App::DocumentObjectExecReturn* Line::execute() { gp_Pnt point1; point1.SetX(this->X1.getValue()); @@ -239,8 +243,9 @@ App::DocumentObjectExecReturn *Line::execute() point2.SetZ(this->Z2.getValue()); BRepBuilderAPI_MakeEdge mkEdge(point1, point2); - if (!mkEdge.IsDone()) + if (!mkEdge.IsDone()) { return new App::DocumentObjectExecReturn("Failed to create edge"); + } const TopoDS_Edge& edge = mkEdge.Edge(); this->Shape.setValue(edge); @@ -250,9 +255,9 @@ App::DocumentObjectExecReturn *Line::execute() void Line::onChanged(const App::Property* prop) { if (!isRestoring()) { - if (prop == &X1 || prop == &Y1 || prop == &Z1 || prop == &X2 || prop == &Y2 || prop == &Z2){ + if (prop == &X1 || prop == &Y1 || prop == &Z1 || prop == &X2 || prop == &Y2 || prop == &Z2) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -266,52 +271,53 @@ PROPERTY_SOURCE(Part::Plane, Part::Primitive) Plane::Plane() { - ADD_PROPERTY_TYPE(Length,(100.0f),"Plane",App::Prop_None,"The length of the plane"); - ADD_PROPERTY_TYPE(Width ,(100.0f),"Plane",App::Prop_None,"The width of the plane"); + ADD_PROPERTY_TYPE(Length, (100.0f), "Plane", App::Prop_None, "The length of the plane"); + ADD_PROPERTY_TYPE(Width, (100.0f), "Plane", App::Prop_None, "The width of the plane"); } short Plane::mustExecute() const { - if (Length.isTouched() || - Width.isTouched() ) + if (Length.isTouched() || Width.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Plane::execute() +App::DocumentObjectExecReturn* Plane::execute() { double L = this->Length.getValue(); double W = this->Width.getValue(); - if (L < Precision::Confusion()) + if (L < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Length of plane too small"); - if (W < Precision::Confusion()) - return new App::DocumentObjectExecReturn("Width of plane too small"); + } + if (W < Precision::Confusion()) { + return new App::DocumentObjectExecReturn("Width of plane too small"); + } - gp_Pnt pnt(0.0,0.0,0.0); - gp_Dir dir(0.0,0.0,1.0); + gp_Pnt pnt(0.0, 0.0, 0.0); + gp_Dir dir(0.0, 0.0, 1.0); Handle(Geom_Plane) aPlane = new Geom_Plane(pnt, dir); BRepBuilderAPI_MakeFace mkFace(aPlane, 0.0, L, 0.0, W, Precision::Confusion()); - const char *error=nullptr; - switch (mkFace.Error()) - { - case BRepBuilderAPI_FaceDone: - break; // ok - case BRepBuilderAPI_NoFace: - error = "no face"; - break; - case BRepBuilderAPI_NotPlanar: - error = "not planar"; - break; - case BRepBuilderAPI_CurveProjectionFailed: - break; - case BRepBuilderAPI_ParametersOutOfRange: - error = "parameters out of range"; - break; - default: - error = "unknown error"; - break; + const char* error = nullptr; + switch (mkFace.Error()) { + case BRepBuilderAPI_FaceDone: + break; // ok + case BRepBuilderAPI_NoFace: + error = "no face"; + break; + case BRepBuilderAPI_NotPlanar: + error = "not planar"; + break; + case BRepBuilderAPI_CurveProjectionFailed: + break; + case BRepBuilderAPI_ParametersOutOfRange: + error = "parameters out of range"; + break; + default: + error = "unknown error"; + break; } // Error ? if (error) { @@ -328,39 +334,46 @@ PROPERTY_SOURCE(Part::Sphere, Part::Primitive) Sphere::Sphere() { - ADD_PROPERTY_TYPE(Radius,(5.0),"Sphere",App::Prop_None,"The radius of the sphere"); + ADD_PROPERTY_TYPE(Radius, (5.0), "Sphere", App::Prop_None, "The radius of the sphere"); Radius.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Angle1,(-90.0f),"Sphere",App::Prop_None,"The angle of the sphere"); + ADD_PROPERTY_TYPE(Angle1, (-90.0f), "Sphere", App::Prop_None, "The angle of the sphere"); Angle1.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle2,(90.0f),"Sphere",App::Prop_None,"The angle of the sphere"); + ADD_PROPERTY_TYPE(Angle2, (90.0f), "Sphere", App::Prop_None, "The angle of the sphere"); Angle2.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle3,(360.0f),"Sphere",App::Prop_None,"The angle of the sphere"); + ADD_PROPERTY_TYPE(Angle3, (360.0f), "Sphere", App::Prop_None, "The angle of the sphere"); Angle3.setConstraints(&angleRangeU); } short Sphere::mustExecute() const { - if (Radius.isTouched()) + if (Radius.isTouched()) { return 1; - if (Angle1.isTouched()) + } + if (Angle1.isTouched()) { return 1; - if (Angle2.isTouched()) + } + if (Angle2.isTouched()) { return 1; - if (Angle3.isTouched()) + } + if (Angle3.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Sphere::execute() +App::DocumentObjectExecReturn* Sphere::execute() { // Build a sphere - if (Radius.getValue() < Precision::Confusion()) + if (Radius.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Radius of sphere too small"); + } try { - BRepPrimAPI_MakeSphere mkSphere(Radius.getValue(), - Base::toRadians(Angle1.getValue()), - Base::toRadians(Angle2.getValue()), - Base::toRadians(Angle3.getValue())); + BRepPrimAPI_MakeSphere mkSphere( + Radius.getValue(), + Base::toRadians(Angle1.getValue()), + Base::toRadians(Angle2.getValue()), + Base::toRadians(Angle3.getValue()) + ); TopoDS_Shape ResultShape = mkSphere.Shape(); this->Shape.setValue(ResultShape); } @@ -376,72 +389,83 @@ PROPERTY_SOURCE(Part::Ellipsoid, Part::Primitive) Ellipsoid::Ellipsoid() { - ADD_PROPERTY_TYPE(Radius1,(2.0),"Ellipsoid",App::Prop_None,"The radius of the ellipsoid"); + ADD_PROPERTY_TYPE(Radius1, (2.0), "Ellipsoid", App::Prop_None, "The radius of the ellipsoid"); Radius1.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius2,(4.0),"Ellipsoid",App::Prop_None,"The radius of the ellipsoid"); + ADD_PROPERTY_TYPE(Radius2, (4.0), "Ellipsoid", App::Prop_None, "The radius of the ellipsoid"); Radius2.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius3,(0.0),"Ellipsoid",App::Prop_None,"The radius of the ellipsoid"); + ADD_PROPERTY_TYPE(Radius3, (0.0), "Ellipsoid", App::Prop_None, "The radius of the ellipsoid"); Radius3.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Angle1,(-90.0f),"Ellipsoid",App::Prop_None,"The angle of the ellipsoid"); + ADD_PROPERTY_TYPE(Angle1, (-90.0f), "Ellipsoid", App::Prop_None, "The angle of the ellipsoid"); Angle1.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle2,(90.0f),"Ellipsoid",App::Prop_None,"The angle of the ellipsoid"); + ADD_PROPERTY_TYPE(Angle2, (90.0f), "Ellipsoid", App::Prop_None, "The angle of the ellipsoid"); Angle2.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle3,(360.0f),"Ellipsoid",App::Prop_None,"The angle of the ellipsoid"); + ADD_PROPERTY_TYPE(Angle3, (360.0f), "Ellipsoid", App::Prop_None, "The angle of the ellipsoid"); Angle3.setConstraints(&angleRangeU); } short Ellipsoid::mustExecute() const { - if (Radius1.isTouched()) + if (Radius1.isTouched()) { return 1; - if (Radius2.isTouched()) + } + if (Radius2.isTouched()) { return 1; - if (Radius3.isTouched()) + } + if (Radius3.isTouched()) { return 1; - if (Angle1.isTouched()) + } + if (Angle1.isTouched()) { return 1; - if (Angle2.isTouched()) + } + if (Angle2.isTouched()) { return 1; - if (Angle3.isTouched()) + } + if (Angle3.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Ellipsoid::execute() +App::DocumentObjectExecReturn* Ellipsoid::execute() { // Build a sphere - if (Radius1.getValue() < Precision::Confusion()) + if (Radius1.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Radius of ellipsoid too small"); - if (Radius2.getValue() < Precision::Confusion()) + } + if (Radius2.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Radius of ellipsoid too small"); + } try { - gp_Pnt pnt(0.0,0.0,0.0); - gp_Dir dir(0.0,0.0,1.0); - gp_Ax2 ax2(pnt,dir); - BRepPrimAPI_MakeSphere mkSphere(ax2, - Radius2.getValue(), - Base::toRadians(Angle1.getValue()), - Base::toRadians(Angle2.getValue()), - Base::toRadians(Angle3.getValue())); + gp_Pnt pnt(0.0, 0.0, 0.0); + gp_Dir dir(0.0, 0.0, 1.0); + gp_Ax2 ax2(pnt, dir); + BRepPrimAPI_MakeSphere mkSphere( + ax2, + Radius2.getValue(), + Base::toRadians(Angle1.getValue()), + Base::toRadians(Angle2.getValue()), + Base::toRadians(Angle3.getValue()) + ); Standard_Real scaleX = 1.0; - Standard_Real scaleZ = Radius1.getValue()/Radius2.getValue(); + Standard_Real scaleZ = Radius1.getValue() / Radius2.getValue(); // issue #1798: A third radius has been introduced. To be backward // compatible if Radius3 is 0.0 (default) it's handled to be the same // as Radius2 Standard_Real scaleY = 1.0; - if (Radius3.getValue() >= Precision::Confusion()) - scaleY = Radius3.getValue()/Radius2.getValue(); + if (Radius3.getValue() >= Precision::Confusion()) { + scaleY = Radius3.getValue() / Radius2.getValue(); + } gp_GTrsf mat; - mat.SetValue(1,1,scaleX); - mat.SetValue(2,1,0.0); - mat.SetValue(3,1,0.0); - mat.SetValue(1,2,0.0); - mat.SetValue(2,2,scaleY); - mat.SetValue(3,2,0.0); - mat.SetValue(1,3,0.0); - mat.SetValue(2,3,0.0); - mat.SetValue(3,3,scaleZ); + mat.SetValue(1, 1, scaleX); + mat.SetValue(2, 1, 0.0); + mat.SetValue(3, 1, 0.0); + mat.SetValue(1, 2, 0.0); + mat.SetValue(2, 2, scaleY); + mat.SetValue(3, 2, 0.0); + mat.SetValue(1, 3, 0.0); + mat.SetValue(2, 3, 0.0); + mat.SetValue(3, 3, scaleZ); BRepBuilderAPI_GTransform mkTrsf(mkSphere.Shape(), mat); TopoDS_Shape ResultShape = mkTrsf.Shape(); this->Shape.setValue(ResultShape); @@ -458,9 +482,9 @@ PROPERTY_SOURCE(Part::Cylinder, Part::Primitive) Cylinder::Cylinder() { - ADD_PROPERTY_TYPE(Radius,(2.0),"Cylinder",App::Prop_None,"The radius of the cylinder"); - ADD_PROPERTY_TYPE(Height,(10.0f),"Cylinder",App::Prop_None,"The height of the cylinder"); - ADD_PROPERTY_TYPE(Angle,(360.0f),"Cylinder",App::Prop_None,"The rotation angle of the cylinder"); + ADD_PROPERTY_TYPE(Radius, (2.0), "Cylinder", App::Prop_None, "The radius of the cylinder"); + ADD_PROPERTY_TYPE(Height, (10.0f), "Cylinder", App::Prop_None, "The height of the cylinder"); + ADD_PROPERTY_TYPE(Angle, (360.0f), "Cylinder", App::Prop_None, "The rotation angle of the cylinder"); Angle.setConstraints(&angleRangeU); PrismExtension::initExtension(this); @@ -468,28 +492,36 @@ Cylinder::Cylinder() short Cylinder::mustExecute() const { - if (Radius.isTouched()) + if (Radius.isTouched()) { return 1; - if (Height.isTouched()) + } + if (Height.isTouched()) { return 1; - if (Angle.isTouched()) + } + if (Angle.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Cylinder::execute() +App::DocumentObjectExecReturn* Cylinder::execute() { // Build a cylinder - if (Radius.getValue() < Precision::Confusion()) + if (Radius.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Radius of cylinder too small"); - if (Height.getValue() < Precision::Confusion()) + } + if (Height.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Height of cylinder too small"); - if (Angle.getValue() < Precision::Confusion()) + } + if (Angle.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Rotation angle of cylinder too small"); + } try { - BRepPrimAPI_MakeCylinder mkCylr(Radius.getValue(), - Height.getValue(), - Base::toRadians(Angle.getValue())); + BRepPrimAPI_MakeCylinder mkCylr( + Radius.getValue(), + Height.getValue(), + Base::toRadians(Angle.getValue()) + ); // the direction vector for the prism is the height for z and the given angle BRepPrim_Cylinder prim = mkCylr.Cylinder(); TopoDS_Shape ResultShape = makePrism(Height.getValue(), prim.BottomFace()); @@ -503,14 +535,26 @@ App::DocumentObjectExecReturn *Cylinder::execute() return Primitive::execute(); } -App::PropertyIntegerConstraint::Constraints Prism::polygonRange = {3,INT_MAX,1}; +App::PropertyIntegerConstraint::Constraints Prism::polygonRange = {3, INT_MAX, 1}; PROPERTY_SOURCE(Part::Prism, Part::Primitive) Prism::Prism() { - ADD_PROPERTY_TYPE(Polygon, (6.0), "Prism", App::Prop_None, "Number of sides in the polygon, of the prism"); - ADD_PROPERTY_TYPE(Circumradius, (2.0), "Prism", App::Prop_None, "Circumradius (centre to vertex) of the polygon, of the prism"); + ADD_PROPERTY_TYPE( + Polygon, + (6.0), + "Prism", + App::Prop_None, + "Number of sides in the polygon, of the prism" + ); + ADD_PROPERTY_TYPE( + Circumradius, + (2.0), + "Prism", + App::Prop_None, + "Circumradius (centre to vertex) of the polygon, of the prism" + ); ADD_PROPERTY_TYPE(Height, (10.0f), "Prism", App::Prop_None, "The height of the prism"); Polygon.setConstraints(&polygonRange); @@ -519,38 +563,48 @@ Prism::Prism() short Prism::mustExecute() const { - if (Polygon.isTouched()) + if (Polygon.isTouched()) { return 1; - if (Circumradius.isTouched()) + } + if (Circumradius.isTouched()) { return 1; - if (Height.isTouched()) + } + if (Height.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Prism::execute() +App::DocumentObjectExecReturn* Prism::execute() { // Build a prism - if (Polygon.getValue() < 3) - return new App::DocumentObjectExecReturn("Polygon of prism is invalid, must have 3 or more sides"); - if (Circumradius.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn("Circumradius of the polygon, of the prism, is too small"); - if (Height.getValue() < Precision::Confusion()) + if (Polygon.getValue() < 3) { + return new App::DocumentObjectExecReturn( + "Polygon of prism is invalid, must have 3 or more sides" + ); + } + if (Circumradius.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + "Circumradius of the polygon, of the prism, is too small" + ); + } + if (Height.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Height of prism is too small"); + } try { long nodes = Polygon.getValue(); Base::Matrix4D mat; - mat.rotZ(Base::toRadians(360.0/nodes)); + mat.rotZ(Base::toRadians(360.0 / nodes)); // create polygon BRepBuilderAPI_MakePolygon mkPoly; - Base::Vector3d v(Circumradius.getValue(),0,0); - for (long i=0; iShape.setValue(makePrism(Height.getValue(), mkFace.Face())); @@ -562,48 +616,64 @@ App::DocumentObjectExecReturn *Prism::execute() return Primitive::execute(); } -App::PropertyIntegerConstraint::Constraints RegularPolygon::polygon = {3,INT_MAX,1}; +App::PropertyIntegerConstraint::Constraints RegularPolygon::polygon = {3, INT_MAX, 1}; PROPERTY_SOURCE(Part::RegularPolygon, Part::Primitive) RegularPolygon::RegularPolygon() { - ADD_PROPERTY_TYPE(Polygon,(6.0),"RegularPolygon",App::Prop_None,"Number of sides in the regular polygon"); - ADD_PROPERTY_TYPE(Circumradius,(2.0),"RegularPolygon",App::Prop_None,"Circumradius (centre to vertex) of the polygon"); + ADD_PROPERTY_TYPE( + Polygon, + (6.0), + "RegularPolygon", + App::Prop_None, + "Number of sides in the regular polygon" + ); + ADD_PROPERTY_TYPE( + Circumradius, + (2.0), + "RegularPolygon", + App::Prop_None, + "Circumradius (centre to vertex) of the polygon" + ); Polygon.setConstraints(&polygon); } short RegularPolygon::mustExecute() const { - if (Polygon.isTouched()) + if (Polygon.isTouched()) { return 1; - if (Circumradius.isTouched()) + } + if (Circumradius.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *RegularPolygon::execute() +App::DocumentObjectExecReturn* RegularPolygon::execute() { // Build a regular polygon - if (Polygon.getValue() < 3) + if (Polygon.getValue() < 3) { return new App::DocumentObjectExecReturn("the polygon is invalid, must have 3 or more sides"); - if (Circumradius.getValue() < Precision::Confusion()) + } + if (Circumradius.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Circumradius of the polygon is too small"); + } try { long nodes = Polygon.getValue(); Base::Matrix4D mat; - mat.rotZ(Base::toRadians(360.0/nodes)); + mat.rotZ(Base::toRadians(360.0 / nodes)); // create polygon BRepBuilderAPI_MakePolygon mkPoly; - Base::Vector3d v(Circumradius.getValue(),0,0); - for (long i=0; iShape.setValue(mkPoly.Shape()); } catch (Standard_Failure& e) { @@ -619,48 +689,60 @@ PROPERTY_SOURCE(Part::Cone, Part::Primitive) Cone::Cone() { - ADD_PROPERTY_TYPE(Radius1,(2.0),"Cone",App::Prop_None,"The radius of the cone"); - ADD_PROPERTY_TYPE(Radius2,(4.0),"Cone",App::Prop_None,"The radius of the cone"); - ADD_PROPERTY_TYPE(Height,(10.0),"Cone",App::Prop_None,"The height of the cone"); - ADD_PROPERTY_TYPE(Angle,(360.0),"Cone",App::Prop_None,"The angle of the cone"); + ADD_PROPERTY_TYPE(Radius1, (2.0), "Cone", App::Prop_None, "The radius of the cone"); + ADD_PROPERTY_TYPE(Radius2, (4.0), "Cone", App::Prop_None, "The radius of the cone"); + ADD_PROPERTY_TYPE(Height, (10.0), "Cone", App::Prop_None, "The height of the cone"); + ADD_PROPERTY_TYPE(Angle, (360.0), "Cone", App::Prop_None, "The angle of the cone"); Angle.setConstraints(&angleRangeU); } short Cone::mustExecute() const { - if (Radius1.isTouched()) + if (Radius1.isTouched()) { return 1; - if (Radius2.isTouched()) + } + if (Radius2.isTouched()) { return 1; - if (Height.isTouched()) + } + if (Height.isTouched()) { return 1; - if (Angle.isTouched()) + } + if (Angle.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Cone::execute() +App::DocumentObjectExecReturn* Cone::execute() { - if (Radius1.getValue() < 0) + if (Radius1.getValue() < 0) { return new App::DocumentObjectExecReturn("Radius of cone too small"); - if (Radius2.getValue() < 0) + } + if (Radius2.getValue() < 0) { return new App::DocumentObjectExecReturn("Radius of cone too small"); - if (Height.getValue() < Precision::Confusion()) + } + if (Height.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Height of cone too small"); + } try { TopoDS_Shape ResultShape; - if (std::abs(Radius1.getValue() - Radius2.getValue()) < Precision::Confusion()){ - //Build a cylinder - BRepPrimAPI_MakeCylinder mkCylr(Radius1.getValue(), - Height.getValue(), - Base::toRadians(Angle.getValue())); + if (std::abs(Radius1.getValue() - Radius2.getValue()) < Precision::Confusion()) { + // Build a cylinder + BRepPrimAPI_MakeCylinder mkCylr( + Radius1.getValue(), + Height.getValue(), + Base::toRadians(Angle.getValue()) + ); ResultShape = mkCylr.Shape(); - } else { + } + else { // Build a cone - BRepPrimAPI_MakeCone mkCone(Radius1.getValue(), - Radius2.getValue(), - Height.getValue(), - Base::toRadians(Angle.getValue())); + BRepPrimAPI_MakeCone mkCone( + Radius1.getValue(), + Radius2.getValue(), + Height.getValue(), + Base::toRadians(Angle.getValue()) + ); ResultShape = mkCone.Shape(); } this->Shape.setValue(ResultShape); @@ -677,46 +759,55 @@ PROPERTY_SOURCE(Part::Torus, Part::Primitive) Torus::Torus() { - ADD_PROPERTY_TYPE(Radius1,(10.0),"Torus",App::Prop_None,"The radius of the torus"); + ADD_PROPERTY_TYPE(Radius1, (10.0), "Torus", App::Prop_None, "The radius of the torus"); Radius1.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius2,(2.0),"Torus",App::Prop_None,"The radius of the torus"); + ADD_PROPERTY_TYPE(Radius2, (2.0), "Torus", App::Prop_None, "The radius of the torus"); Radius2.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Angle1,(-180.0),"Torus",App::Prop_None,"The angle of the torus"); + ADD_PROPERTY_TYPE(Angle1, (-180.0), "Torus", App::Prop_None, "The angle of the torus"); Angle1.setConstraints(&torusRangeV); - ADD_PROPERTY_TYPE(Angle2,(180.0),"Torus",App::Prop_None,"The angle of the torus"); + ADD_PROPERTY_TYPE(Angle2, (180.0), "Torus", App::Prop_None, "The angle of the torus"); Angle2.setConstraints(&torusRangeV); - ADD_PROPERTY_TYPE(Angle3,(360.0),"Torus",App::Prop_None,"The angle of the torus"); + ADD_PROPERTY_TYPE(Angle3, (360.0), "Torus", App::Prop_None, "The angle of the torus"); Angle3.setConstraints(&angleRangeU); } short Torus::mustExecute() const { - if (Radius1.isTouched()) + if (Radius1.isTouched()) { return 1; - if (Radius2.isTouched()) + } + if (Radius2.isTouched()) { return 1; - if (Angle1.isTouched()) + } + if (Angle1.isTouched()) { return 1; - if (Angle2.isTouched()) + } + if (Angle2.isTouched()) { return 1; - if (Angle3.isTouched()) + } + if (Angle3.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Torus::execute() +App::DocumentObjectExecReturn* Torus::execute() { - if (Radius1.getValue() < Precision::Confusion()) + if (Radius1.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Radius of torus too small"); - if (Radius2.getValue() < Precision::Confusion()) + } + if (Radius2.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Radius of torus too small"); + } try { TopoShape shape; - this->Shape.setValue(shape.makeTorus(Radius1.getValue(), - Radius2.getValue(), - Angle1.getValue(), - Angle2.getValue(), - Angle3.getValue())); + this->Shape.setValue(shape.makeTorus( + Radius1.getValue(), + Radius2.getValue(), + Angle1.getValue(), + Angle2.getValue(), + Angle3.getValue() + )); } catch (Standard_Failure& e) { return new App::DocumentObjectExecReturn(e.GetMessageString()); @@ -727,37 +818,60 @@ App::DocumentObjectExecReturn *Torus::execute() PROPERTY_SOURCE(Part::Helix, Part::Primitive) -const char* Part::Helix::LocalCSEnums[]= {"Right-handed","Left-handed",nullptr}; -const char* Part::Helix::StyleEnums []= {"Old style","New style",nullptr}; +const char* Part::Helix::LocalCSEnums[] = {"Right-handed", "Left-handed", nullptr}; +const char* Part::Helix::StyleEnums[] = {"Old style", "New style", nullptr}; Helix::Helix() { - ADD_PROPERTY_TYPE(Pitch, (1.0),"Helix",App::Prop_None,"The pitch of the helix"); + ADD_PROPERTY_TYPE(Pitch, (1.0), "Helix", App::Prop_None, "The pitch of the helix"); Pitch.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Height,(2.0),"Helix",App::Prop_None,"The height of the helix"); + ADD_PROPERTY_TYPE(Height, (2.0), "Helix", App::Prop_None, "The height of the helix"); Height.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius,(1.0),"Helix",App::Prop_None,"The radius of the helix"); + ADD_PROPERTY_TYPE(Radius, (1.0), "Helix", App::Prop_None, "The radius of the helix"); Radius.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(SegmentLength,(0.0),"Helix",App::Prop_None,"The number of turns per helix subdivision"); + ADD_PROPERTY_TYPE( + SegmentLength, + (0.0), + "Helix", + App::Prop_None, + "The number of turns per helix subdivision" + ); SegmentLength.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Angle,(0.0),"Helix",App::Prop_None,"If angle is != 0 a conical otherwise a cylindircal surface is used"); + ADD_PROPERTY_TYPE( + Angle, + (0.0), + "Helix", + App::Prop_None, + "If angle is != 0 a conical otherwise a cylindircal surface is used" + ); Angle.setConstraints(&apexRange); - ADD_PROPERTY_TYPE(LocalCoord,(long(0)),"Coordinate System",App::Prop_None,"Orientation of the local coordinate system of the helix"); + ADD_PROPERTY_TYPE( + LocalCoord, + (long(0)), + "Coordinate System", + App::Prop_None, + "Orientation of the local coordinate system of the helix" + ); LocalCoord.setEnums(LocalCSEnums); - ADD_PROPERTY_TYPE(Style,(long(0)),"Helix style",App::Prop_Hidden,"Old style creates incorrect and new style create correct helices"); + ADD_PROPERTY_TYPE( + Style, + (long(0)), + "Helix style", + App::Prop_Hidden, + "Old style creates incorrect and new style create correct helices" + ); Style.setEnums(StyleEnums); - ADD_PROPERTY_TYPE(Length,(1.0),"Helix",App::Prop_None,"The length of the helix"); + ADD_PROPERTY_TYPE(Length, (1.0), "Helix", App::Prop_None, "The length of the helix"); Length.setReadOnly(true); } void Helix::onChanged(const App::Property* prop) { if (!isRestoring()) { - if (prop == &Pitch || prop == &Height || prop == &Radius || - prop == &Angle || prop == &LocalCoord || prop == &Style || - prop == &SegmentLength) { + if (prop == &Pitch || prop == &Height || prop == &Radius || prop == &Angle + || prop == &LocalCoord || prop == &Style || prop == &SegmentLength) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -769,39 +883,49 @@ void Helix::onChanged(const App::Property* prop) short Helix::mustExecute() const { - if (Pitch.isTouched()) + if (Pitch.isTouched()) { return 1; - if (Height.isTouched()) + } + if (Height.isTouched()) { return 1; - if (Radius.isTouched()) + } + if (Radius.isTouched()) { return 1; - if (Angle.isTouched()) + } + if (Angle.isTouched()) { return 1; - if (LocalCoord.isTouched()) + } + if (LocalCoord.isTouched()) { return 1; - if (Style.isTouched()) + } + if (Style.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Helix::execute() +App::DocumentObjectExecReturn* Helix::execute() { try { - Standard_Real myPitch = Pitch.getValue(); + Standard_Real myPitch = Pitch.getValue(); Standard_Real myHeight = Height.getValue(); Standard_Real myRadius = Radius.getValue(); - Standard_Real myAngle = Angle.getValue(); + Standard_Real myAngle = Angle.getValue(); Standard_Boolean myLocalCS = LocalCoord.getValue() ? Standard_True : Standard_False; Standard_Real mySegLen = SegmentLength.getValue(); - if (myPitch < Precision::Confusion()) + if (myPitch < Precision::Confusion()) { Standard_Failure::Raise("Pitch too small"); + } Standard_Real nbTurns = myHeight / myPitch; - if (nbTurns > 1e4) + if (nbTurns > 1e4) { Standard_Failure::Raise("Number of turns too high (> 1e4)"); + } Standard_Real myRadiusTop = myRadius + myHeight * tan(Base::toRadians(myAngle)); - this->Shape.setValue(TopoShape().makeSpiralHelix(myRadius, myRadiusTop, myHeight, nbTurns, mySegLen, myLocalCS)); - // props.Mass() may seem a strange way to get the Length, but + this->Shape.setValue( + TopoShape().makeSpiralHelix(myRadius, myRadiusTop, myHeight, nbTurns, mySegLen, myLocalCS) + ); + // props.Mass() may seem a strange way to get the Length, but // https://dev.opencascade.org/doc/refman/html/class_b_rep_g_prop.html#ab1d4bacc290bfaa8df13dd99ae7b8e70 // confirms this. GProp_GProps props; @@ -820,25 +944,30 @@ PROPERTY_SOURCE(Part::Spiral, Part::Primitive) Spiral::Spiral() { - ADD_PROPERTY_TYPE(Growth, (1.0),"Spiral",App::Prop_None,"The growth of the spiral per rotation"); + ADD_PROPERTY_TYPE(Growth, (1.0), "Spiral", App::Prop_None, "The growth of the spiral per rotation"); Growth.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius,(1.0),"Spiral",App::Prop_None,"The radius of the spiral"); + ADD_PROPERTY_TYPE(Radius, (1.0), "Spiral", App::Prop_None, "The radius of the spiral"); Radius.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Rotations,(2.0),"Spiral",App::Prop_None,"The number of rotations"); + ADD_PROPERTY_TYPE(Rotations, (2.0), "Spiral", App::Prop_None, "The number of rotations"); Rotations.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(SegmentLength,(1.0),"Spiral",App::Prop_None,"The number of turns per spiral subdivision"); + ADD_PROPERTY_TYPE( + SegmentLength, + (1.0), + "Spiral", + App::Prop_None, + "The number of turns per spiral subdivision" + ); SegmentLength.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Length,(1.0),"Spiral",App::Prop_None,"The length of the spiral"); + ADD_PROPERTY_TYPE(Length, (1.0), "Spiral", App::Prop_None, "The length of the spiral"); Length.setReadOnly(true); } void Spiral::onChanged(const App::Property* prop) { if (!isRestoring()) { - if (prop == &Growth || prop == &Rotations || prop == &Radius || - prop == &SegmentLength) { + if (prop == &Growth || prop == &Rotations || prop == &Radius || prop == &SegmentLength) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -850,16 +979,19 @@ void Spiral::onChanged(const App::Property* prop) short Spiral::mustExecute() const { - if (Growth.isTouched()) + if (Growth.isTouched()) { return 1; - if (Rotations.isTouched()) + } + if (Rotations.isTouched()) { return 1; - if (Radius.isTouched()) + } + if (Radius.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Spiral::execute() +App::DocumentObjectExecReturn* Spiral::execute() { try { Standard_Real myNumRot = Rotations.getValue(); @@ -868,10 +1000,13 @@ App::DocumentObjectExecReturn *Spiral::execute() Standard_Real myRadiusTop = myRadius + myGrowth * myNumRot; Standard_Real mySegLen = SegmentLength.getValue(); - if (myNumRot < Precision::Confusion()) + if (myNumRot < Precision::Confusion()) { Standard_Failure::Raise("Number of rotations too small"); + } - this->Shape.setValue(TopoShape().makeSpiralHelix(myRadius, myRadiusTop, 0, myNumRot, mySegLen, Standard_False)); + this->Shape.setValue( + TopoShape().makeSpiralHelix(myRadius, myRadiusTop, 0, myNumRot, mySegLen, Standard_False) + ); GProp_GProps props; BRepGProp::LinearProperties(Shape.getShape().getShape(), props); Length.setValue(props.Mass()); @@ -886,35 +1021,29 @@ PROPERTY_SOURCE(Part::Wedge, Part::Primitive) Wedge::Wedge() { - ADD_PROPERTY_TYPE(Xmin,(0.0f),"Wedge",App::Prop_None,"Xmin of the wedge"); - ADD_PROPERTY_TYPE(Ymin,(0.0f),"Wedge",App::Prop_None,"Ymin of the wedge"); - ADD_PROPERTY_TYPE(Zmin,(0.0f),"Wedge",App::Prop_None,"Zmin of the wedge"); - ADD_PROPERTY_TYPE(X2min,(2.0f),"Wedge",App::Prop_None,"X2min of the wedge"); - ADD_PROPERTY_TYPE(Z2min,(2.0f),"Wedge",App::Prop_None,"Z2min of the wedge"); - ADD_PROPERTY_TYPE(Xmax,(10.0f),"Wedge",App::Prop_None,"Xmax of the wedge"); - ADD_PROPERTY_TYPE(Ymax,(10.0f),"Wedge",App::Prop_None,"Ymax of the wedge"); - ADD_PROPERTY_TYPE(Zmax,(10.0f),"Wedge",App::Prop_None,"Zmax of the wedge"); - ADD_PROPERTY_TYPE(X2max,(8.0f),"Wedge",App::Prop_None,"X2max of the wedge"); - ADD_PROPERTY_TYPE(Z2max,(8.0f),"Wedge",App::Prop_None,"Z2max of the wedge"); + ADD_PROPERTY_TYPE(Xmin, (0.0f), "Wedge", App::Prop_None, "Xmin of the wedge"); + ADD_PROPERTY_TYPE(Ymin, (0.0f), "Wedge", App::Prop_None, "Ymin of the wedge"); + ADD_PROPERTY_TYPE(Zmin, (0.0f), "Wedge", App::Prop_None, "Zmin of the wedge"); + ADD_PROPERTY_TYPE(X2min, (2.0f), "Wedge", App::Prop_None, "X2min of the wedge"); + ADD_PROPERTY_TYPE(Z2min, (2.0f), "Wedge", App::Prop_None, "Z2min of the wedge"); + ADD_PROPERTY_TYPE(Xmax, (10.0f), "Wedge", App::Prop_None, "Xmax of the wedge"); + ADD_PROPERTY_TYPE(Ymax, (10.0f), "Wedge", App::Prop_None, "Ymax of the wedge"); + ADD_PROPERTY_TYPE(Zmax, (10.0f), "Wedge", App::Prop_None, "Zmax of the wedge"); + ADD_PROPERTY_TYPE(X2max, (8.0f), "Wedge", App::Prop_None, "X2max of the wedge"); + ADD_PROPERTY_TYPE(Z2max, (8.0f), "Wedge", App::Prop_None, "Z2max of the wedge"); } short Wedge::mustExecute() const { - if (Xmin.isTouched() || - Ymin.isTouched() || - Zmin.isTouched() || - X2min.isTouched() || - Z2min.isTouched() || - Xmax.isTouched() || - Ymax.isTouched() || - Zmax.isTouched() || - X2max.isTouched() || - Z2max.isTouched()) + if (Xmin.isTouched() || Ymin.isTouched() || Zmin.isTouched() || X2min.isTouched() + || Z2min.isTouched() || Xmax.isTouched() || Ymax.isTouched() || Zmax.isTouched() + || X2max.isTouched() || Z2max.isTouched()) { return 1; + } return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Wedge::execute() +App::DocumentObjectExecReturn* Wedge::execute() { double xmin = Xmin.getValue(); double ymin = Ymin.getValue(); @@ -928,33 +1057,37 @@ App::DocumentObjectExecReturn *Wedge::execute() double x2max = X2max.getValue(); - double dx = xmax-xmin; - double dy = ymax-ymin; - double dz = zmax-zmin; - double dz2 = z2max-z2min; - double dx2 = x2max-x2min; + double dx = xmax - xmin; + double dy = ymax - ymin; + double dz = zmax - zmin; + double dz2 = z2max - z2min; + double dx2 = x2max - x2min; - if (dx < Precision::Confusion()) + if (dx < Precision::Confusion()) { return new App::DocumentObjectExecReturn("delta x of wedge too small"); + } - if (dy < Precision::Confusion()) + if (dy < Precision::Confusion()) { return new App::DocumentObjectExecReturn("delta y of wedge too small"); + } - if (dz < Precision::Confusion()) + if (dz < Precision::Confusion()) { return new App::DocumentObjectExecReturn("delta z of wedge too small"); + } - if (dz2 < 0) + if (dz2 < 0) { return new App::DocumentObjectExecReturn("delta z2 of wedge is negative"); + } - if (dx2 < 0) + if (dx2 < 0) { return new App::DocumentObjectExecReturn("delta x2 of wedge is negative"); + } try { - gp_Pnt pnt(0.0,0.0,0.0); - gp_Dir dir(0.0,0.0,1.0); - BRepPrim_Wedge mkWedge(gp_Ax2(pnt,dir), - xmin, ymin, zmin, z2min, x2min, - xmax, ymax, zmax, z2max, x2max); + gp_Pnt pnt(0.0, 0.0, 0.0); + gp_Dir dir(0.0, 0.0, 1.0); + BRepPrim_Wedge + mkWedge(gp_Ax2(pnt, dir), xmin, ymin, zmin, z2min, x2min, xmax, ymax, zmax, z2max, x2max); BRepBuilderAPI_MakeSolid mkSolid; mkSolid.Add(mkWedge.Shell()); this->Shape.setValue(mkSolid.Solid()); @@ -968,30 +1101,28 @@ App::DocumentObjectExecReturn *Wedge::execute() void Wedge::onChanged(const App::Property* prop) { - if (prop == &Xmin || prop == &Ymin || prop == &Zmin || - prop == &X2min || prop == &Z2min || - prop == &Xmax || prop == &Ymax || prop == &Zmax || - prop == &X2max || prop == &Z2max) { + if (prop == &Xmin || prop == &Ymin || prop == &Zmin || prop == &X2min || prop == &Z2min + || prop == &Xmax || prop == &Ymax || prop == &Zmax || prop == &X2max || prop == &Z2max) { if (!isRestoring()) { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } } Part::Primitive::onChanged(prop); } -App::PropertyQuantityConstraint::Constraints Ellipse::angleRange = {0.0,360.0,1.0}; +App::PropertyQuantityConstraint::Constraints Ellipse::angleRange = {0.0, 360.0, 1.0}; PROPERTY_SOURCE(Part::Ellipse, Part::Primitive) Ellipse::Ellipse() { - ADD_PROPERTY(MajorRadius,(4.0f)); - ADD_PROPERTY(MinorRadius,(4.0f)); - ADD_PROPERTY(Angle1,(0.0f)); + ADD_PROPERTY(MajorRadius, (4.0f)); + ADD_PROPERTY(MinorRadius, (4.0f)); + ADD_PROPERTY(Angle1, (0.0f)); Angle1.setConstraints(&angleRange); - ADD_PROPERTY(Angle2,(360.0f)); + ADD_PROPERTY(Angle2, (360.0f)); Angle2.setConstraints(&angleRange); } @@ -999,27 +1130,31 @@ Ellipse::~Ellipse() = default; short Ellipse::mustExecute() const { - if (Angle1.isTouched() || - Angle2.isTouched() || - MajorRadius.isTouched() || - MinorRadius.isTouched()) + if (Angle1.isTouched() || Angle2.isTouched() || MajorRadius.isTouched() + || MinorRadius.isTouched()) { return 1; + } return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Ellipse::execute() +App::DocumentObjectExecReturn* Ellipse::execute() { - if (this->MinorRadius.getValue() > this->MajorRadius.getValue()) + if (this->MinorRadius.getValue() > this->MajorRadius.getValue()) { return new App::DocumentObjectExecReturn("Minor radius greater than major radius"); - if (this->MinorRadius.getValue() < Precision::Confusion()) + } + if (this->MinorRadius.getValue() < Precision::Confusion()) { return new App::DocumentObjectExecReturn("Minor radius of ellipse too small"); + } gp_Elips ellipse; ellipse.SetMajorRadius(this->MajorRadius.getValue()); ellipse.SetMinorRadius(this->MinorRadius.getValue()); - BRepBuilderAPI_MakeEdge clMakeEdge(ellipse, Base::toRadians(this->Angle1.getValue()), - Base::toRadians(this->Angle2.getValue())); + BRepBuilderAPI_MakeEdge clMakeEdge( + ellipse, + Base::toRadians(this->Angle1.getValue()), + Base::toRadians(this->Angle2.getValue()) + ); const TopoDS_Edge& edge = clMakeEdge.Edge(); this->Shape.setValue(edge); @@ -1029,9 +1164,9 @@ App::DocumentObjectExecReturn *Ellipse::execute() void Ellipse::onChanged(const App::Property* prop) { if (!isRestoring()) { - if (prop == &MajorRadius || prop == &MinorRadius || prop == &Angle1 || prop == &Angle2){ + if (prop == &MajorRadius || prop == &MinorRadius || prop == &Angle1 || prop == &Angle2) { try { - App::DocumentObjectExecReturn *ret = recompute(); + App::DocumentObjectExecReturn* ret = recompute(); delete ret; } catch (...) { @@ -1041,9 +1176,13 @@ void Ellipse::onChanged(const App::Property* prop) Part::Primitive::onChanged(prop); } -void Ellipse::Restore(Base::XMLReader &reader) +void Ellipse::Restore(Base::XMLReader& reader) { - Base::ObjectStatusLocker lock(App::Property::User1, &Angle2, false); + Base::ObjectStatusLocker lock( + App::Property::User1, + &Angle2, + false + ); Primitive::Restore(reader); if (Angle2.testStatus(App::Property::User1)) { @@ -1053,7 +1192,7 @@ void Ellipse::Restore(Base::XMLReader &reader) } } -void Ellipse::handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) +void Ellipse::handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, const char* PropName) { Base::Type type = Base::Type::fromName(TypeName); if (Angle2.getTypeId() == type && strcmp(PropName, "Angle0") == 0) { diff --git a/src/Mod/Part/App/PrimitiveFeature.h b/src/Mod/Part/App/PrimitiveFeature.h index 107b70d952..4149b59af2 100644 --- a/src/Mod/Part/App/PrimitiveFeature.h +++ b/src/Mod/Part/App/PrimitiveFeature.h @@ -34,7 +34,7 @@ namespace Part { -class PartExport Primitive : public Part::Feature, public Part::AttachExtension +class PartExport Primitive: public Part::Feature, public Part::AttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(Part::Primitive); @@ -45,18 +45,22 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; PyObject* getPyObject() override; //@} protected: - void Restore(Base::XMLReader &reader) override; - void onChanged (const App::Property* prop) override; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void Restore(Base::XMLReader& reader) override; + void onChanged(const App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; }; -class PartExport Vertex : public Part::Primitive +class PartExport Vertex: public Part::Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Vertex); @@ -71,17 +75,18 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPointParametric"; } //@} }; -class PartExport Line : public Part::Primitive +class PartExport Line: public Part::Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Line); @@ -99,17 +104,18 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderLineParametric"; } //@} }; -class PartExport Plane : public Primitive +class PartExport Plane: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Plane); @@ -122,16 +128,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPlaneParametric"; } //@} }; -class PartExport Sphere : public Primitive +class PartExport Sphere: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Sphere); @@ -146,16 +153,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderSphereParametric"; } //@} }; -class PartExport Ellipsoid : public Primitive +class PartExport Ellipsoid: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Ellipsoid); @@ -172,16 +180,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; //@} - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderEllipsoid"; } }; -class PartExport Cylinder : public Primitive, - public PrismExtension +class PartExport Cylinder: public Primitive, public PrismExtension { PROPERTY_HEADER_WITH_OVERRIDE(Part::Cylinder); @@ -195,17 +203,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderCylinderParametric"; } //@} }; -class PartExport Prism : public Primitive, - public PrismExtension +class PartExport Prism: public Primitive, public PrismExtension { PROPERTY_HEADER_WITH_OVERRIDE(Part::Prism); @@ -219,10 +227,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderPrism"; } //@} @@ -230,7 +239,7 @@ private: static App::PropertyIntegerConstraint::Constraints polygonRange; }; -class PartExport RegularPolygon : public Primitive +class PartExport RegularPolygon: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::RegularPolygon); @@ -243,10 +252,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderRegularPolygon"; } //@} @@ -254,7 +264,7 @@ private: static App::PropertyIntegerConstraint::Constraints polygon; }; -class PartExport Cone : public Primitive +class PartExport Cone: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Cone); @@ -269,16 +279,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderConeParametric"; } //@} }; -class PartExport Torus : public Primitive +class PartExport Torus: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Torus); @@ -294,16 +305,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderTorusParametric"; } //@} }; -class PartExport Helix : public Primitive +class PartExport Helix: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Helix); @@ -315,30 +327,31 @@ public: App::PropertyLength Radius; App::PropertyAngle Angle; App::PropertyQuantityConstraint SegmentLength; - App::PropertyEnumeration LocalCoord; - App::PropertyEnumeration Style; + App::PropertyEnumeration LocalCoord; + App::PropertyEnumeration Style; App::PropertyLength Length; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderHelixParametric"; } //@} protected: - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; private: static const char* LocalCSEnums[]; static const char* StyleEnums[]; }; -class PartExport Spiral : public Primitive +class PartExport Spiral: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Spiral); @@ -354,19 +367,20 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderSpiralParametric"; } //@} protected: - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; }; -class PartExport Wedge : public Primitive +class PartExport Wedge: public Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Wedge); @@ -387,10 +401,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderWedge"; } //@} @@ -399,7 +414,7 @@ protected: void onChanged(const App::Property* prop) override; }; -class PartExport Ellipse : public Part::Primitive +class PartExport Ellipse: public Part::Primitive { PROPERTY_HEADER_WITH_OVERRIDE(Part::Ellipse); @@ -415,24 +430,29 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartGui::ViewProviderEllipseParametric"; } //@} protected: - void Restore(Base::XMLReader &reader) override; - void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; + void Restore(Base::XMLReader& reader) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; private: static App::PropertyQuantityConstraint::Constraints angleRange; }; -} //namespace Part +} // namespace Part -#endif // PART_PRIMITIVEFEATURE_H +#endif // PART_PRIMITIVEFEATURE_H diff --git a/src/Mod/Part/App/PrismExtension.cpp b/src/Mod/Part/App/PrismExtension.cpp index 0d1c4b4472..2ebc59b3a1 100644 --- a/src/Mod/Part/App/PrismExtension.cpp +++ b/src/Mod/Part/App/PrismExtension.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -39,7 +39,8 @@ PrismExtension::PrismExtension() EXTENSION_ADD_PROPERTY_TYPE(FirstAngle, (0.0f), "Prism", App::Prop_None, "Angle in first direction"); EXTENSION_ADD_PROPERTY_TYPE(SecondAngle, (0.0f), "Prism", App::Prop_None, "Angle in second direction"); - static const App::PropertyQuantityConstraint::Constraints angleConstraint = { -89.99999, 89.99999, 1.0 }; + static const App::PropertyQuantityConstraint::Constraints angleConstraint + = {-89.99999, 89.99999, 1.0}; FirstAngle.setConstraints(&angleConstraint); SecondAngle.setConstraints(&angleConstraint); @@ -50,14 +51,16 @@ PrismExtension::~PrismExtension() = default; short int PrismExtension::extensionMustExecute() { - if (FirstAngle.isTouched()) + if (FirstAngle.isTouched()) { return 1; - if (SecondAngle.isTouched()) + } + if (SecondAngle.isTouched()) { return 1; + } return DocumentObjectExtension::extensionMustExecute(); } -App::DocumentObjectExecReturn *PrismExtension::extensionExecute() +App::DocumentObjectExecReturn* PrismExtension::extensionExecute() { return App::DocumentObjectExtension::extensionExecute(); } @@ -70,9 +73,13 @@ void PrismExtension::extensionOnChanged(const App::Property* prop) TopoDS_Shape PrismExtension::makePrism(double height, const TopoDS_Face& face) const { // the direction vector for the prism is the height for z and the given angle - BRepPrimAPI_MakePrism mkPrism(face, - gp_Vec(height * tan(Base::toRadians(FirstAngle.getValue())), - height * tan(Base::toRadians(SecondAngle.getValue())), - height)); + BRepPrimAPI_MakePrism mkPrism( + face, + gp_Vec( + height * tan(Base::toRadians(FirstAngle.getValue())), + height * tan(Base::toRadians(SecondAngle.getValue())), + height + ) + ); return mkPrism.Shape(); } diff --git a/src/Mod/Part/App/PrismExtension.h b/src/Mod/Part/App/PrismExtension.h index f273f1d1bd..354223dca0 100644 --- a/src/Mod/Part/App/PrismExtension.h +++ b/src/Mod/Part/App/PrismExtension.h @@ -35,9 +35,10 @@ namespace Part { -class PartExport PrismExtension : public App::DocumentObjectExtension +class PartExport PrismExtension: public App::DocumentObjectExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Part::PrismExtension); + public: PrismExtension(); ~PrismExtension() override; @@ -49,12 +50,12 @@ public: TopoDS_Shape makePrism(double height, const TopoDS_Face& face) const; short int extensionMustExecute() override; - App::DocumentObjectExecReturn *extensionExecute() override; + App::DocumentObjectExecReturn* extensionExecute() override; protected: void extensionOnChanged(const App::Property* /*prop*/) override; }; -} // namespace Part +} // namespace Part -#endif // PART_PRISM_EXTENSION_H +#endif // PART_PRISM_EXTENSION_H diff --git a/src/Mod/Part/App/PropertyGeometryList.cpp b/src/Mod/Part/App/PropertyGeometryList.cpp index e8db0eefc0..e7d172b79f 100644 --- a/src/Mod/Part/App/PropertyGeometryList.cpp +++ b/src/Mod/Part/App/PropertyGeometryList.cpp @@ -54,14 +54,17 @@ PropertyGeometryList::PropertyGeometryList() = default; PropertyGeometryList::~PropertyGeometryList() { for (auto it : _lValueList) { - if (it) delete it; + if (it) { + delete it; + } } } void PropertyGeometryList::setSize(int newSize) { - for (unsigned int i = newSize; i < _lValueList.size(); i++) + for (unsigned int i = newSize; i < _lValueList.size(); i++) { delete _lValueList[i]; + } _lValueList.resize(newSize); } @@ -75,8 +78,9 @@ void PropertyGeometryList::setValue(const Geometry* lValue) if (lValue) { aboutToSetValue(); Geometry* newVal = lValue->clone(); - for (auto it : _lValueList) + for (auto it : _lValueList) { delete it; + } _lValueList.resize(1); _lValueList[0] = newVal; hasSetValue(); @@ -88,22 +92,25 @@ void PropertyGeometryList::setValues(const std::vector& lValue) auto copy = lValue; aboutToSetValue(); std::sort(_lValueList.begin(), _lValueList.end()); - for (auto & geo : copy) { + for (auto& geo : copy) { auto range = std::equal_range(_lValueList.begin(), _lValueList.end(), geo); // clone if the new entry does not exist in the original value list, or // else, simply reuse it (i.e. erase it so that it won't get deleted below). - if (range.first == range.second) + if (range.first == range.second) { geo = geo->clone(); - else + } + else { _lValueList.erase(range.first, range.second); + } } - for (auto v : _lValueList) + for (auto v : _lValueList) { delete v; + } _lValueList = std::move(copy); hasSetValue(); } -void PropertyGeometryList::setValues(std::vector &&lValue) +void PropertyGeometryList::setValues(std::vector&& lValue) { // Unlike above, the moved version of setValues() indicates the caller want // us to manager the memory of the passed in values. So no need clone. @@ -113,21 +120,25 @@ void PropertyGeometryList::setValues(std::vector &&lValue) auto range = std::equal_range(_lValueList.begin(), _lValueList.end(), geo); _lValueList.erase(range.first, range.second); } - for (auto geo : _lValueList) + for (auto geo : _lValueList) { delete geo; + } _lValueList = std::move(lValue); hasSetValue(); } -void PropertyGeometryList::set1Value(int idx, std::unique_ptr &&lValue) +void PropertyGeometryList::set1Value(int idx, std::unique_ptr&& lValue) { - if (!lValue) + if (!lValue) { return; - if(idx>=(int)_lValueList.size()) + } + if (idx >= (int)_lValueList.size()) { throw Base::IndexError("Index out of bound"); + } aboutToSetValue(); - if(idx < 0) + if (idx < 0) { _lValueList.push_back(lValue.release()); + } else { delete _lValueList[idx]; _lValueList[idx] = lValue.release(); @@ -135,7 +146,7 @@ void PropertyGeometryList::set1Value(int idx, std::unique_ptr &&lValue hasSetValue(); } -PyObject *PropertyGeometryList::getPyObject() +PyObject* PropertyGeometryList::getPyObject() { Py::List list; for (int i = 0; i < getSize(); i++) { @@ -144,7 +155,7 @@ PyObject *PropertyGeometryList::getPyObject() return Py::new_reference_to(list); } -void PropertyGeometryList::setPyObject(PyObject *value) +void PropertyGeometryList::setPyObject(PyObject* value) { // check container of this property to notify about changes Part2DObject* part2d = freecad_cast(this->getContainer()); @@ -155,7 +166,7 @@ void PropertyGeometryList::setPyObject(PyObject *value) std::vector values; values.resize(nSize); - for (Py_ssize_t i=0; i < nSize; ++i) { + for (Py_ssize_t i = 0; i < nSize; ++i) { Py::Object item = sequence.getItem(i); if (!PyObject_TypeCheck(item.ptr(), &(GeometryPy::Type))) { std::string error = std::string("types in list must be 'Geometry', not "); @@ -172,7 +183,7 @@ void PropertyGeometryList::setPyObject(PyObject *value) } } else if (PyObject_TypeCheck(value, &(GeometryPy::Type))) { - GeometryPy *pcObject = static_cast(value); + GeometryPy* pcObject = static_cast(value); setValue(pcObject->getGeometryPtr()); if (part2d) { part2d->acceptGeometry(); @@ -185,32 +196,34 @@ void PropertyGeometryList::setPyObject(PyObject *value) } } -void PropertyGeometryList::trySaveGeometry(Geometry * geom, Base::Writer &writer) const +void PropertyGeometryList::trySaveGeometry(Geometry* geom, Base::Writer& writer) const { // Not all geometry classes implement Save() and throw an exception instead try { geom->Save(writer); - for( auto & ext : geom->getExtensions() ) { + for (auto& ext : geom->getExtensions()) { auto extension = ext.lock(); auto gpe = freecad_cast(extension.get()); - if (gpe) + if (gpe) { gpe->postSave(writer); + } } } catch (const Base::NotImplementedError& e) { - Base::Console().warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); + Base::Console() + .warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); } } -void PropertyGeometryList::tryRestoreGeometry(Geometry * geom, Base::XMLReader &reader) +void PropertyGeometryList::tryRestoreGeometry(Geometry* geom, Base::XMLReader& reader) { // Not all geometry classes implement Restore() and throw an exception instead try { if (!reader.getAttribute("migrated", 0) && reader.hasAttribute("id")) { auto ext = std::make_unique(); ext->setId(reader.getAttribute("id")); - if(reader.hasAttribute("ref")) { - const char *ref = reader.getAttribute("ref"); + if (reader.hasAttribute("ref")) { + const char* ref = reader.getAttribute("ref"); int index = reader.getAttribute("refIndex", 1); unsigned long flags = (unsigned long)reader.getAttribute("flags"); ext->setReference(ref, index, flags); @@ -220,18 +233,19 @@ void PropertyGeometryList::tryRestoreGeometry(Geometry * geom, Base::XMLReader & geom->Restore(reader); } catch (const Base::NotImplementedError& e) { - Base::Console().warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); + Base::Console() + .warning(std::string("PropertyGeometryList"), "Not yet implemented: %s\n", e.what()); } } -void PropertyGeometryList::Save(Writer &writer) const +void PropertyGeometryList::Save(Writer& writer) const { - writer.Stream() << writer.ind() << "" << endl; + writer.Stream() << writer.ind() << "" << endl; writer.incInd(); for (int i = 0; i < getSize(); i++) { writer.Stream() << writer.ind() << "getTypeId().getName() << "\""; - for (auto &e : _lValueList[i]->getExtensions() ) { + << _lValueList[i]->getTypeId().getName() << "\""; + for (auto& e : _lValueList[i]->getExtensions()) { auto ext = e.lock(); if (auto gpe = freecad_cast(ext.get())) { gpe->preSave(writer); @@ -245,10 +259,10 @@ void PropertyGeometryList::Save(Writer &writer) const writer.Stream() << writer.ind() << "" << endl; } writer.decInd(); - writer.Stream() << writer.ind() << "" << endl ; + writer.Stream() << writer.ind() << "" << endl; } -void PropertyGeometryList::Restore(Base::XMLReader &reader) +void PropertyGeometryList::Restore(Base::XMLReader& reader) { // read my element reader.clearPartialRestoreObject(); @@ -260,12 +274,15 @@ void PropertyGeometryList::Restore(Base::XMLReader &reader) for (int i = 0; i < count; i++) { reader.readElement("Geometry"); const char* TypeName = reader.getAttribute("type"); - Geometry *newG = static_cast(Base::Type::fromName(TypeName).createInstance()); + Geometry* newG = static_cast(Base::Type::fromName(TypeName).createInstance()); tryRestoreGeometry(newG, reader); - if(reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { - Base::Console().error("Geometry \"%s\" within a PropertyGeometryList was subject to a partial restore.\n",reader.localName()); - if(isOrderRelevant()) { + if (reader.testStatus(Base::XMLReader::ReaderStatus::PartialRestoreInObject)) { + Base::Console().error( + "Geometry \"%s\" within a PropertyGeometryList was subject to a partial restore.\n", + reader.localName() + ); + if (isOrderRelevant()) { // Pushes the best try by the Geometry class values.push_back(newG); } @@ -287,14 +304,14 @@ void PropertyGeometryList::Restore(Base::XMLReader &reader) setValues(std::move(values)); } -App::Property *PropertyGeometryList::Copy() const +App::Property* PropertyGeometryList::Copy() const { - PropertyGeometryList *p = new PropertyGeometryList(); + PropertyGeometryList* p = new PropertyGeometryList(); p->setValues(_lValueList); return p; } -void PropertyGeometryList::Paste(const Property &from) +void PropertyGeometryList::Paste(const Property& from) { const PropertyGeometryList& FromList = dynamic_cast(from); setValues(FromList._lValueList); @@ -303,14 +320,13 @@ void PropertyGeometryList::Paste(const Property &from) unsigned int PropertyGeometryList::getMemSize() const { int size = sizeof(PropertyGeometryList); - for (int i = 0; i < getSize(); i++) + for (int i = 0; i < getSize(); i++) { size += _lValueList[i]->getMemSize(); + } return size; } -void PropertyGeometryList::moveValues(PropertyGeometryList &&other) +void PropertyGeometryList::moveValues(PropertyGeometryList&& other) { setValues(std::move(other._lValueList)); } - - diff --git a/src/Mod/Part/App/PropertyGeometryList.h b/src/Mod/Part/App/PropertyGeometryList.h index 5b7defc4da..43c7865432 100644 --- a/src/Mod/Part/App/PropertyGeometryList.h +++ b/src/Mod/Part/App/PropertyGeometryList.h @@ -34,7 +34,8 @@ #include "Geometry.h" -namespace Base { +namespace Base +{ class Writer; } @@ -68,39 +69,41 @@ public: void setValues(const std::vector&); void setValues(std::vector&&); - void moveValues(PropertyGeometryList &&other); + void moveValues(PropertyGeometryList&& other); /// index operator - Geometry *operator[] (const int idx) const { + Geometry* operator[](const int idx) const + { return _lValueList[idx]; } - const std::vector &getValues() const { + const std::vector& getValues() const + { return _lValueList; } - void set1Value(int idx, std::unique_ptr &&); + void set1Value(int idx, std::unique_ptr&&); - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; - void Save(Base::Writer &writer) const override; - void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; - App::Property *Copy() const override; - void Paste(const App::Property &from) override; + App::Property* Copy() const override; + void Paste(const App::Property& from) override; unsigned int getMemSize() const override; private: - void trySaveGeometry(Geometry * geom, Base::Writer &writer) const; - void tryRestoreGeometry(Geometry * geom, Base::XMLReader &reader); + void trySaveGeometry(Geometry* geom, Base::Writer& writer) const; + void tryRestoreGeometry(Geometry* geom, Base::XMLReader& reader); private: std::vector _lValueList; }; -} // namespace Part +} // namespace Part -#endif // APP_PropertyGeometryList_H +#endif // APP_PropertyGeometryList_H diff --git a/src/Mod/Part/App/PropertyTopoShape.cpp b/src/Mod/Part/App/PropertyTopoShape.cpp index 2163c6ef10..633be80b91 100644 --- a/src/Mod/Part/App/PropertyTopoShape.cpp +++ b/src/Mod/Part/App/PropertyTopoShape.cpp @@ -23,16 +23,16 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -56,7 +56,7 @@ FC_LOG_LEVEL_INIT("App", true, true) namespace sp = std::placeholders; using namespace Part; -TYPESYSTEM_SOURCE(Part::PropertyPartShape , App::PropertyComplexGeoData) +TYPESYSTEM_SOURCE(Part::PropertyPartShape, App::PropertyComplexGeoData) PropertyPartShape::PropertyPartShape() = default; @@ -67,20 +67,22 @@ void PropertyPartShape::setValue(const TopoShape& sh) aboutToSetValue(); _Shape = sh; auto obj = freecad_cast(getContainer()); - if(obj) { - if(_Shape.getElementMap().size() != sh.getElementMap().size()) { + if (obj) { + if (_Shape.getElementMap().size() != sh.getElementMap().size()) { TopoShape res(obj->getID(), sh.Hasher, _Shape.getShape()); res.mapSubElement(_Shape); _Shape = res; } auto tag = obj->getID(); - if(_Shape.Tag && tag!=_Shape.Tag) { - auto hasher = _Shape.Hasher?_Shape.Hasher:obj->getDocument()->getStringHasher(); + if (_Shape.Tag && tag != _Shape.Tag) { + auto hasher = _Shape.Hasher ? _Shape.Hasher : obj->getDocument()->getStringHasher(); - _Shape.reTagElementMap(tag,hasher); - } else + _Shape.reTagElementMap(tag, hasher); + } + else { _Shape.Tag = obj->getID(); + } if (!_Shape.Hasher && _Shape.hasChildElementMap()) { _Shape.Hasher = obj->getDocument()->getStringHasher(); _Shape.hashChildMaps(); @@ -94,9 +96,10 @@ void PropertyPartShape::setValue(const TopoDS_Shape& sh, bool resetElementMap) { aboutToSetValue(); auto obj = dynamic_cast(getContainer()); - if(obj) + if (obj) { _Shape.Tag = obj->getID(); - _Shape.setShape(sh,resetElementMap); + } + _Shape.setShape(sh, resetElementMap); hasSetValue(); _Ver.clear(); } @@ -131,8 +134,9 @@ const Data::ComplexGeoData* PropertyPartShape::getComplexData() const Base::BoundBox3d PropertyPartShape::getBoundingBox() const { Base::BoundBox3d box; - if (_Shape.getShape().IsNull()) + if (_Shape.getShape().IsNull()) { return box; + } try { // If the shape is empty an exception may be thrown Bnd_Box bounds; @@ -154,7 +158,7 @@ Base::BoundBox3d PropertyPartShape::getBoundingBox() const return box; } -void PropertyPartShape::setTransform(const Base::Matrix4D &rclTrf) +void PropertyPartShape::setTransform(const Base::Matrix4D& rclTrf) { _Shape.setTransform(rclTrf); } @@ -164,36 +168,38 @@ Base::Matrix4D PropertyPartShape::getTransform() const return _Shape.getTransform(); } -void PropertyPartShape::transformGeometry(const Base::Matrix4D &rclTrf) +void PropertyPartShape::transformGeometry(const Base::Matrix4D& rclTrf) { aboutToSetValue(); _Shape.transformGeometry(rclTrf); hasSetValue(); } -PyObject *PropertyPartShape::getPyObject() +PyObject* PropertyPartShape::getPyObject() { Base::PyObjectBase* prop = static_cast(_Shape.getPyObject()); - if (prop) + if (prop) { prop->setConst(); + } return prop; } -void PropertyPartShape::setPyObject(PyObject *value) +void PropertyPartShape::setPyObject(PyObject* value) { if (PyObject_TypeCheck(value, &(TopoShapePy::Type))) { auto shape = *static_cast(value)->getTopoShapePtr(); auto owner = dynamic_cast(getContainer()); - if(owner && owner->getDocument()) { - if(shape.Tag || shape.getElementMapSize()) { + if (owner && owner->getDocument()) { + if (shape.Tag || shape.getElementMapSize()) { // We can't trust the meaning of the input shape tag, so we // remap anyway - TopoShape res(owner->getID(),owner->getDocument()->getStringHasher(),shape.getShape()); + TopoShape res(owner->getID(), owner->getDocument()->getStringHasher(), shape.getShape()); res.mapSubElement(shape); shape = res; - }else{ + } + else { shape.Tag = owner->getID(); - if ( shape.Hasher ) { // TODO: This null guard added during TNP transition + if (shape.Hasher) { // TODO: This null guard added during TNP transition shape.Hasher->clear(); } } @@ -207,85 +213,140 @@ void PropertyPartShape::setPyObject(PyObject *value) } } -App::Property *PropertyPartShape::Copy() const +App::Property* PropertyPartShape::Copy() const { - PropertyPartShape *prop = new PropertyPartShape(); + PropertyPartShape* prop = new PropertyPartShape(); // March, 2024 Toponaming project: There was originally a feature to enable making an element // copy ( new geometry and map ) that has not been kept: -// if (PartParams::getShapePropertyCopy()) { -// // makeElementCopy() consume too much memory for complex geometry. -// prop->_Shape = this->_Shape.makeElementCopy(); -// } else -// prop->_Shape = this->_Shape; + // if (PartParams::getShapePropertyCopy()) { + // // makeElementCopy() consume too much memory for complex geometry. + // prop->_Shape = this->_Shape.makeElementCopy(); + // } else + // prop->_Shape = this->_Shape; prop->_Shape = this->_Shape; prop->_Ver = this->_Ver; return prop; } -void PropertyPartShape::Paste(const App::Property &from) +void PropertyPartShape::Paste(const App::Property& from) { auto prop = freecad_cast(&from); - if(prop) { + if (prop) { setValue(prop->_Shape); _Ver = prop->_Ver; } } -unsigned int PropertyPartShape::getMemSize () const +unsigned int PropertyPartShape::getMemSize() const { return _Shape.getMemSize(); } -void PropertyPartShape::getPaths(std::vector &paths) const +void PropertyPartShape::getPaths(std::vector& paths) const { - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ShapeType"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Orientation"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Length"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Area"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Volume"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox"))); - + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ShapeType")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent( + App::ObjectIdentifier::String("Orientation") + ) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Length")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Area")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Volume")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + ); + // BoundBox sub-properties - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("XMax"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("XMin"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("YMax"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("YMin"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ZMax"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ZMin"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("XLength"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("YLength"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ZLength"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("DiagonalLength"))); - paths.push_back(App::ObjectIdentifier(getContainer()) << App::ObjectIdentifier::Component::SimpleComponent(getName()) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) - << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Center"))); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("XMax")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("XMin")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("YMax")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("YMin")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ZMax")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ZMin")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("XLength")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("YLength")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("ZLength")) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent( + App::ObjectIdentifier::String("DiagonalLength") + ) + ); + paths.push_back( + App::ObjectIdentifier(getContainer()) + << App::ObjectIdentifier::Component::SimpleComponent(getName()) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("BoundBox")) + << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Center")) + ); } void PropertyPartShape::beforeSave() const @@ -293,24 +354,23 @@ void PropertyPartShape::beforeSave() const _HasherIndex = 0; _SaveHasher = false; auto owner = freecad_cast(getContainer()); - if(owner && !_Shape.isNull() && _Shape.getElementMapSize()>0) { + if (owner && !_Shape.isNull() && _Shape.getElementMapSize() > 0) { auto ret = owner->getDocument()->addStringHasher(_Shape.Hasher); _HasherIndex = ret.second; _SaveHasher = ret.first; _Shape.beforeSave(); } } -void PropertyPartShape::Save (Base::Writer &writer) const +void PropertyPartShape::Save(Base::Writer& writer) const { - //See SaveDocFile(), RestoreDocFile() + // See SaveDocFile(), RestoreDocFile() writer.Stream() << writer.ind() << "(getContainer()); - if(owner && !_Shape.isNull() - && _Shape.getElementMapSize()>0 - && !_Shape.Hasher.isNull()) { + if (owner && !_Shape.isNull() && _Shape.getElementMapSize() > 0 && !_Shape.Hasher.isNull()) { writer.Stream() << " HasherIndex=\"" << _HasherIndex << '"'; - if(_SaveHasher) + if (_SaveHasher) { writer.Stream() << " SaveHasher=\"1\""; + } } std::string version; // If exporting, do not export mapped element name, but still make a mark @@ -319,58 +379,68 @@ void PropertyPartShape::Save (Base::Writer &writer) const if (!owner->isExporting()) { version = version_valid ? _Ver : owner->getElementMapVersion(this); } - } else { + } + else { version = version_valid ? _Ver : _Shape.getElementMapVersion(); } writer.Stream() << " ElementMap=\"" << version << '"'; bool binary = writer.getMode("BinaryBrep"); bool toXML = writer.isForceXML(); - if(!toXML) { + if (!toXML) { writer.Stream() << " file=\"" - << writer.addFile(getFileName(binary?".bin":".brp").c_str(), this) + << writer.addFile(getFileName(binary ? ".bin" : ".brp").c_str(), this) << "\"/>\n"; - } else if(binary) { + } + else if (binary) { writer.Stream() << " binary=\"1\">\n"; _Shape.exportBinary(writer.beginCharStream(Base::CharStreamFormat::Base64Encoded)); - writer.endCharStream() << writer.ind() << "\n"; - } else { + writer.endCharStream() << writer.ind() << "\n"; + } + else { writer.Stream() << " brep=\"1\">\n"; - _Shape.exportBrep(writer.beginCharStream(Base::CharStreamFormat::Raw)<<'\n'); + _Shape.exportBrep(writer.beginCharStream(Base::CharStreamFormat::Raw) << '\n'); writer.endCharStream() << '\n' << writer.ind() << "\n"; } - if(_SaveHasher) { - if(!toXML) + if (_SaveHasher) { + if (!toXML) { _Shape.Hasher->setPersistenceFileName(getFileName(".Table").c_str()); - else + } + else { _Shape.Hasher->setPersistenceFileName(0); + } _Shape.Hasher->Save(writer); } - if(version.size()) { - if(!toXML) + if (version.size()) { + if (!toXML) { _Shape.setPersistenceFileName(getFileName(".Map").c_str()); - else + } + else { _Shape.setPersistenceFileName(0); + } _Shape.Save(writer); } } -std::string PropertyPartShape::getElementMapVersion(bool restored) const { - if(restored) +std::string PropertyPartShape::getElementMapVersion(bool restored) const +{ + if (restored) { return _Ver; + } return PropertyComplexGeoData::getElementMapVersion(false); } -void PropertyPartShape::Restore(Base::XMLReader &reader) +void PropertyPartShape::Restore(Base::XMLReader& reader) { reader.readElement("Part"); auto owner = freecad_cast(getContainer()); _Ver = "?"; bool has_ver = reader.hasAttribute("ElementMap"); - if (has_ver) + if (has_ver) { _Ver = reader.getAttribute("ElementMap"); + } int hasher_idx = reader.getAttribute("HasherIndex", -1); int save_hasher = reader.getAttribute("SaveHasher", 0); @@ -395,57 +465,64 @@ void PropertyPartShape::Restore(Base::XMLReader &reader) reader.readEndElement("Part"); - if(owner && hasher_idx>=0) { + if (owner && hasher_idx >= 0) { _Shape.Hasher = owner->getDocument()->getStringHasher(hasher_idx); - if(save_hasher) + if (save_hasher) { _Shape.Hasher->Restore(reader); + } } - if(has_ver) { + if (has_ver) { // The file name here is not used for restore, but just a way to get // more useful error message if something wrong when restoring _Shape.setPersistenceFileName(getFileName().c_str()); - if(owner && owner->getDocument()->testStatus(App::Document::PartialDoc)) + if (owner && owner->getDocument()->testStatus(App::Document::PartialDoc)) { _Shape.Restore(reader); - else if(_Ver == "?" || _Ver.empty()) { + } + else if (_Ver == "?" || _Ver.empty()) { // This indicate the shape is saved by legacy version without // element map info. - if(owner) { + if (owner) { // This will ask user for recompute after import owner->getDocument()->addRecomputeObject(owner); } - }else{ + } + else { _Shape.Restore(reader); if (owner ? owner->checkElementMapVersion(this, _Ver.c_str()) : _Shape.checkElementMapVersion(_Ver.c_str())) { - auto ver = owner?owner->getElementMapVersion(this):_Shape.getElementMapVersion(); - if(!owner || !owner->getNameInDocument() || !_Shape.getElementMapSize()) { + auto ver = owner ? owner->getElementMapVersion(this) : _Shape.getElementMapVersion(); + if (!owner || !owner->getNameInDocument() || !_Shape.getElementMapSize()) { _Ver = ver; - } else { + } + else { // version mismatch, signal for regenerating. - static const char *warnedDoc=0; - if(warnedDoc != owner->getDocument()->getName()) { + static const char* warnedDoc = 0; + if (warnedDoc != owner->getDocument()->getName()) { warnedDoc = owner->getDocument()->getName(); - FC_WARN("Recomputation required for document '" << warnedDoc - << "' on geo element version change in " << getFullName() - << ": " << _Ver << " -> " << ver); + FC_WARN( + "Recomputation required for document '" + << warnedDoc << "' on geo element version change in " << getFullName() + << ": " << _Ver << " -> " << ver + ); } owner->getDocument()->addRecomputeObject(owner); } } } - } else if(owner && !owner->getDocument()->testStatus(App::Document::PartialDoc)) { - // Toponaming 09/2024: Original code has an infrastructure for document parameters we aren't bringing in: - // if(App::DocumentParams::getWarnRecomputeOnRestore()) { - // However, this warning appeared on all files without element maps, and is now superseded by a user dialog - // after loading that is triggered by any call to addRecomputeObject() + } + else if (owner && !owner->getDocument()->testStatus(App::Document::PartialDoc)) { + // Toponaming 09/2024: Original code has an infrastructure for document parameters we + // aren't bringing in: if(App::DocumentParams::getWarnRecomputeOnRestore()) { However, this + // warning appeared on all files without element maps, and is now superseded by a user + // dialog after loading that is triggered by any call to addRecomputeObject() // FC_WARN("Pending recompute for generating element map: " << owner->getFullName()); owner->getDocument()->addRecomputeObject(owner); } if (!shape.isNull() || !_Shape.isNull()) { aboutToSetValue(); - _Shape.setShape(shape.getShape(),false); + _Shape.setShape(shape.getShape(), false); hasSetValue(); } } @@ -459,8 +536,9 @@ void PropertyPartShape::afterRestore() _Ver = "?"; } else if (_Shape.getElementMapSize() == 0) { - if (_Shape.Hasher) + if (_Shape.Hasher) { _Shape.Hasher->clear(); + } } PropertyComplexGeoData::afterRestore(); } @@ -469,46 +547,50 @@ void PropertyPartShape::afterRestore() // to disable saving of triangulation // -static Standard_Boolean BRepTools_Write(const TopoDS_Shape& Sh, const Standard_CString File) +static Standard_Boolean BRepTools_Write(const TopoDS_Shape& Sh, const Standard_CString File) { - std::ofstream os; - OSD_OpenStream(os, File, std::ios::out); + std::ofstream os; + OSD_OpenStream(os, File, std::ios::out); - if (!os.rdbuf()->is_open()) - return Standard_False; + if (!os.rdbuf()->is_open()) { + return Standard_False; + } + + Standard_Boolean isGood = (os.good() && !os.eof()); + if (!isGood) { + return isGood; + } + + // See TopTools_FormatVersion of OCCT 7.6 + enum + { + VERSION_1 = 1, + VERSION_2 = 2, + VERSION_3 = 3 + }; + + BRepTools_ShapeSet SS(Standard_False); + SS.SetFormatNb(VERSION_1); + // SS.SetProgress(PR); + SS.Add(Sh); + + os << "DBRep_DrawableShape\n"; // for easy Draw read + SS.Write(os); + isGood = os.good(); + if (isGood) { + SS.Write(Sh, os); + } + os.flush(); + isGood = os.good(); + + errno = 0; + os.close(); + isGood = os.good() && isGood && !errno; - Standard_Boolean isGood = (os.good() && !os.eof()); - if(!isGood) return isGood; - - // See TopTools_FormatVersion of OCCT 7.6 - enum { - VERSION_1 = 1, - VERSION_2 = 2, - VERSION_3 = 3 - }; - - BRepTools_ShapeSet SS(Standard_False); - SS.SetFormatNb(VERSION_1); - // SS.SetProgress(PR); - SS.Add(Sh); - - os << "DBRep_DrawableShape\n"; // for easy Draw read - SS.Write(os); - isGood = os.good(); - if(isGood ) - SS.Write(Sh,os); - os.flush(); - isGood = os.good(); - - errno = 0; - os.close(); - isGood = os.good() && isGood && !errno; - - return isGood; } -void PropertyPartShape::saveToFile(Base::Writer &writer) const +void PropertyPartShape::saveToFile(Base::Writer& writer) const { // create a temporary file and copy the content to the zip stream // once the tmp. filename is known use always the same because otherwise @@ -516,7 +598,7 @@ void PropertyPartShape::saveToFile(Base::Writer &writer) const static Base::FileInfo fi(App::Application::getTempFileName()); TopoDS_Shape myShape = _Shape.getShape(); - if (!BRepTools_Write(myShape,static_cast(fi.filePath().c_str()))) { + if (!BRepTools_Write(myShape, static_cast(fi.filePath().c_str()))) { // Note: Do NOT throw an exception here because if the tmp. file could // not be created we should not abort. // We only print an error message but continue writing the next files to the @@ -524,8 +606,11 @@ void PropertyPartShape::saveToFile(Base::Writer &writer) const App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().error("Shape of '%s' cannot be written to BRep file '%s'\n", - obj->Label.getValue(),fi.filePath().c_str()); + Base::Console().error( + "Shape of '%s' cannot be written to BRep file '%s'\n", + obj->Label.getValue(), + fi.filePath().c_str() + ); } else { Base::Console().error("Cannot save BRep file '%s'\n", fi.filePath().c_str()); @@ -547,7 +632,7 @@ void PropertyPartShape::saveToFile(Base::Writer &writer) const fi.deleteFile(); } -void PropertyPartShape::loadFromFile(Base::Reader &reader) +void PropertyPartShape::loadFromFile(Base::Reader& reader) { BRep_Builder builder; // create a temporary file and copy the content from the zip stream @@ -576,11 +661,17 @@ void PropertyPartShape::loadFromFile(Base::Reader &reader) App::PropertyContainer* father = this->getContainer(); if (father && father->isDerivedFrom()) { App::DocumentObject* obj = static_cast(father); - Base::Console().error("BRep file '%s' with shape of '%s' seems to be empty\n", - fi.filePath().c_str(),obj->Label.getValue()); + Base::Console().error( + "BRep file '%s' with shape of '%s' seems to be empty\n", + fi.filePath().c_str(), + obj->Label.getValue() + ); } else { - Base::Console().warning("Loaded BRep file '%s' seems to be empty\n", fi.filePath().c_str()); + Base::Console().warning( + "Loaded BRep file '%s' seems to be empty\n", + fi.filePath().c_str() + ); } } } @@ -590,7 +681,7 @@ void PropertyPartShape::loadFromFile(Base::Reader &reader) setValue(shape); } -void PropertyPartShape::loadFromStream(Base::Reader &reader) +void PropertyPartShape::loadFromStream(Base::Reader& reader) { try { reader.exceptions(std::istream::failbit | std::istream::badbit); @@ -600,17 +691,19 @@ void PropertyPartShape::loadFromStream(Base::Reader &reader) setValue(shape); } catch (const std::exception&) { - if (!reader.eof()) + if (!reader.eof()) { Base::Console().warning("Failed to load BRep file %s\n", reader.getFileName().c_str()); + } } } -void PropertyPartShape::SaveDocFile (Base::Writer &writer) const +void PropertyPartShape::SaveDocFile(Base::Writer& writer) const { // If the shape is empty we simply store nothing. The file size will be 0 which // can be checked when reading in the data. - if (_Shape.getShape().IsNull()) + if (_Shape.getShape().IsNull()) { return; + } TopoDS_Shape myShape = _Shape.getShape(); if (writer.getMode("BinaryBrep")) { TopoShape shape; @@ -618,8 +711,9 @@ void PropertyPartShape::SaveDocFile (Base::Writer &writer) const shape.exportBinary(writer.Stream()); } else { - bool direct = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Mod/Part/General")->GetBool("DirectAccess", true); + bool direct = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part/General") + ->GetBool("DirectAccess", true); if (!direct) { saveToFile(writer); } @@ -631,7 +725,7 @@ void PropertyPartShape::SaveDocFile (Base::Writer &writer) const } } -void PropertyPartShape::RestoreDocFile(Base::Reader &reader) +void PropertyPartShape::RestoreDocFile(Base::Reader& reader) { // save the element map @@ -654,8 +748,9 @@ void PropertyPartShape::RestoreDocFile(Base::Reader &reader) shape.importBinary(reader); } else { - bool direct = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Mod/Part/General")->GetBool("DirectAccess", true); + bool direct = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part/General") + ->GetBool("DirectAccess", true); if (!direct) { loadFromFile(reader); } @@ -676,43 +771,53 @@ void PropertyPartShape::RestoreDocFile(Base::Reader &reader) // ------------------------------------------------------------------------- -ShapeHistory::ShapeHistory(BRepBuilderAPI_MakeShape& mkShape, TopAbs_ShapeEnum type, - const TopoDS_Shape& newS, const TopoDS_Shape& oldS) +ShapeHistory::ShapeHistory( + BRepBuilderAPI_MakeShape& mkShape, + TopAbs_ShapeEnum type, + const TopoDS_Shape& newS, + const TopoDS_Shape& oldS +) { - reset(mkShape,type,newS,oldS); + reset(mkShape, type, newS, oldS); } -void ShapeHistory::reset(BRepBuilderAPI_MakeShape& mkShape, TopAbs_ShapeEnum type, - const TopoDS_Shape& newS, const TopoDS_Shape& oldS) +void ShapeHistory::reset( + BRepBuilderAPI_MakeShape& mkShape, + TopAbs_ShapeEnum type, + const TopoDS_Shape& newS, + const TopoDS_Shape& oldS +) { shapeMap.clear(); this->type = type; TopTools_IndexedMapOfShape newM, oldM; - TopExp::MapShapes(newS, type, newM); // map containing all old objects of type "type" - TopExp::MapShapes(oldS, type, oldM); // map containing all new objects of type "type" + TopExp::MapShapes(newS, type, newM); // map containing all old objects of type "type" + TopExp::MapShapes(oldS, type, oldM); // map containing all new objects of type "type" // Look at all objects in the old shape and try to find the modified object in the new shape - for (int i=1; i<=oldM.Extent(); i++) { + for (int i = 1; i <= oldM.Extent(); i++) { bool found = false; TopTools_ListIteratorOfListOfShape it; // Find all new objects that are a modification of the old object (e.g. a face was resized) for (it.Initialize(mkShape.Modified(oldM(i))); it.More(); it.Next()) { found = true; - for (int j=1; j<=newM.Extent(); j++) { // one old object might create several new ones! + for (int j = 1; j <= newM.Extent(); + j++) { // one old object might create several new ones! if (newM(j).IsPartner(it.Value())) { - shapeMap[i-1].push_back(j-1); // adjust indices to start at zero + shapeMap[i - 1].push_back(j - 1); // adjust indices to start at zero break; } } } - // Find all new objects that were generated from an old object (e.g. a face generated from an edge) + // Find all new objects that were generated from an old object (e.g. a face generated from + // an edge) for (it.Initialize(mkShape.Generated(oldM(i))); it.More(); it.Next()) { found = true; - for (int j=1; j<=newM.Extent(); j++) { + for (int j = 1; j <= newM.Extent(); j++) { if (newM(j).IsPartner(it.Value())) { - shapeMap[i-1].push_back(j-1); + shapeMap[i - 1].push_back(j - 1); break; } } @@ -721,13 +826,13 @@ void ShapeHistory::reset(BRepBuilderAPI_MakeShape& mkShape, TopAbs_ShapeEnum typ if (!found) { // Find all old objects that don't exist any more (e.g. a face was completely cut away) if (mkShape.IsDeleted(oldM(i))) { - shapeMap[i-1] = std::vector(); + shapeMap[i - 1] = std::vector(); } else { // Mop up the rest (will this ever be reached?) - for (int j=1; j<=newM.Extent(); j++) { + for (int j = 1; j <= newM.Extent(); j++) { if (newM(j).IsPartner(oldM(i))) { - shapeMap[i-1].push_back(j-1); + shapeMap[i - 1].push_back(j - 1); break; } } @@ -742,9 +847,11 @@ void ShapeHistory::join(const ShapeHistory& newH) for (ShapeHistory::MapList::const_iterator it = shapeMap.begin(); it != shapeMap.end(); ++it) { int old_shape_index = it->first; - if (it->second.empty()) + if (it->second.empty()) { join.shapeMap[old_shape_index] = ShapeHistory::List(); - for (ShapeHistory::List::const_iterator jt = it->second.begin(); jt != it->second.end(); ++jt) { + } + for (ShapeHistory::List::const_iterator jt = it->second.begin(); jt != it->second.end(); + ++jt) { ShapeHistory::MapList::const_iterator kt = newH.shapeMap.find(*jt); if (kt != newH.shapeMap.end()) { ShapeHistory::List& ary = join.shapeMap[old_shape_index]; @@ -758,7 +865,7 @@ void ShapeHistory::join(const ShapeHistory& newH) // ------------------------------------------------------------------------- -TYPESYSTEM_SOURCE(Part::PropertyShapeHistory , App::PropertyLists) +TYPESYSTEM_SOURCE(Part::PropertyShapeHistory, App::PropertyLists) PropertyShapeHistory::PropertyShapeHistory() = default; @@ -779,39 +886,34 @@ void PropertyShapeHistory::setValues(const std::vector& values) hasSetValue(); } -PyObject *PropertyShapeHistory::getPyObject() +PyObject* PropertyShapeHistory::getPyObject() { return Py::new_reference_to(Py::None()); } -void PropertyShapeHistory::setPyObject(PyObject *) -{ -} +void PropertyShapeHistory::setPyObject(PyObject*) +{} -void PropertyShapeHistory::Save (Base::Writer &) const -{ -} +void PropertyShapeHistory::Save(Base::Writer&) const +{} -void PropertyShapeHistory::Restore(Base::XMLReader &) -{ -} +void PropertyShapeHistory::Restore(Base::XMLReader&) +{} -void PropertyShapeHistory::SaveDocFile (Base::Writer &) const -{ -} +void PropertyShapeHistory::SaveDocFile(Base::Writer&) const +{} -void PropertyShapeHistory::RestoreDocFile(Base::Reader &) -{ -} +void PropertyShapeHistory::RestoreDocFile(Base::Reader&) +{} -App::Property *PropertyShapeHistory::Copy() const +App::Property* PropertyShapeHistory::Copy() const { - PropertyShapeHistory *p= new PropertyShapeHistory(); + PropertyShapeHistory* p = new PropertyShapeHistory(); p->_lValueList = _lValueList; return p; } -void PropertyShapeHistory::Paste(const Property &from) +void PropertyShapeHistory::Paste(const Property& from) { aboutToSetValue(); _lValueList = dynamic_cast(from)._lValueList; @@ -820,7 +922,7 @@ void PropertyShapeHistory::Paste(const Property &from) // ------------------------------------------------------------------------- -TYPESYSTEM_SOURCE(Part::PropertyFilletEdges , App::PropertyLists) +TYPESYSTEM_SOURCE(Part::PropertyFilletEdges, App::PropertyLists) PropertyFilletEdges::PropertyFilletEdges() = default; @@ -843,7 +945,7 @@ void PropertyFilletEdges::setValues(const std::vector& values) hasSetValue(); } -PyObject *PropertyFilletEdges::getPyObject() +PyObject* PropertyFilletEdges::getPyObject() { Py::List list(getSize()); std::vector::const_iterator it; @@ -859,7 +961,7 @@ PyObject *PropertyFilletEdges::getPyObject() return Py::new_reference_to(list); } -void PropertyFilletEdges::setPyObject(PyObject *value) +void PropertyFilletEdges::setPyObject(PyObject* value) { Py::Sequence list(value); std::vector values; @@ -876,54 +978,55 @@ void PropertyFilletEdges::setPyObject(PyObject *value) setValues(values); } -void PropertyFilletEdges::Save (Base::Writer &writer) const +void PropertyFilletEdges::Save(Base::Writer& writer) const { if (!writer.isForceXML()) { - writer.Stream() << writer.ind() << "" << std::endl; + writer.Stream() << writer.ind() << "" << std::endl; } } -void PropertyFilletEdges::Restore(Base::XMLReader &reader) +void PropertyFilletEdges::Restore(Base::XMLReader& reader) { reader.readElement("FilletEdges"); - std::string file (reader.getAttribute("file") ); + std::string file(reader.getAttribute("file")); if (!file.empty()) { // initiate a file read - reader.addFile(file.c_str(),this); + reader.addFile(file.c_str(), this); } } -void PropertyFilletEdges::SaveDocFile (Base::Writer &writer) const +void PropertyFilletEdges::SaveDocFile(Base::Writer& writer) const { Base::OutputStream str(writer.Stream()); uint32_t uCt = (uint32_t)getSize(); str << uCt; - for (const auto & it : _lValueList) { + for (const auto& it : _lValueList) { str << it.edgeid << it.radius1 << it.radius2; } } -void PropertyFilletEdges::RestoreDocFile(Base::Reader &reader) +void PropertyFilletEdges::RestoreDocFile(Base::Reader& reader) { Base::InputStream str(reader); - uint32_t uCt=0; + uint32_t uCt = 0; str >> uCt; std::vector values(uCt); - for (auto & it : values) { + for (auto& it : values) { str >> it.edgeid >> it.radius1 >> it.radius2; } setValues(values); } -App::Property *PropertyFilletEdges::Copy() const +App::Property* PropertyFilletEdges::Copy() const { - PropertyFilletEdges *p= new PropertyFilletEdges(); + PropertyFilletEdges* p = new PropertyFilletEdges(); p->_lValueList = _lValueList; return p; } -void PropertyFilletEdges::Paste(const Property &from) +void PropertyFilletEdges::Paste(const Property& from) { aboutToSetValue(); _lValueList = dynamic_cast(from)._lValueList; @@ -934,30 +1037,32 @@ void PropertyFilletEdges::Paste(const Property &from) TYPESYSTEM_SOURCE(Part::PropertyShapeCache, App::Property); -App::Property *PropertyShapeCache::Copy(void) const { +App::Property* PropertyShapeCache::Copy(void) const +{ return new PropertyShapeCache(); } -void PropertyShapeCache::Paste(const App::Property &) { +void PropertyShapeCache::Paste(const App::Property&) +{ cache.clear(); } -void PropertyShapeCache::Save (Base::Writer &) const -{ -} +void PropertyShapeCache::Save(Base::Writer&) const +{} -void PropertyShapeCache::Restore(Base::XMLReader &) -{ -} +void PropertyShapeCache::Restore(Base::XMLReader&) +{} /** * Make a new python List with a tuple for each cache entry containing the key and the shape * @return the python list */ -PyObject *PropertyShapeCache::getPyObject() { +PyObject* PropertyShapeCache::getPyObject() +{ Py::List res; - for(auto &v : cache) - res.append(Py::TupleN(Py::String(v.first),shape2pyshape(v.second))); + for (auto& v : cache) { + res.append(Py::TupleN(Py::String(v.first), shape2pyshape(v.second))); + } return Py::new_reference_to(res); } @@ -965,17 +1070,20 @@ PyObject *PropertyShapeCache::getPyObject() { * Remove the cache entries for every element in the list * @param value A python list of entry names */ -void PropertyShapeCache::setPyObject(PyObject *value) { - if(!value) +void PropertyShapeCache::setPyObject(PyObject* value) +{ + if (!value) { return; - if(value == Py_None) { + } + if (value == Py_None) { cache.clear(); return; } App::PropertyStringList prop; prop.setPyObject(value); - for(const auto &sub : prop.getValues()) + for (const auto& sub : prop.getValues()) { cache.erase(sub); + } } #define SHAPE_CACHE_NAME "_Part_ShapeCache" @@ -985,23 +1093,31 @@ void PropertyShapeCache::setPyObject(PyObject *value) { * @param create True if we should create the cache if it doesn't exist * @return The shape cache, or null if we aren't creating and it doesn't exist */ -PropertyShapeCache *PropertyShapeCache::get(const App::DocumentObject *obj, bool create) { - auto prop = freecad_cast( - obj->getDynamicPropertyByName(SHAPE_CACHE_NAME)); - if(prop && prop->getContainer()==obj) +PropertyShapeCache* PropertyShapeCache::get(const App::DocumentObject* obj, bool create) +{ + auto prop = freecad_cast(obj->getDynamicPropertyByName(SHAPE_CACHE_NAME)); + if (prop && prop->getContainer() == obj) { return prop; - if(!create) + } + if (!create) { return 0; + } - prop = static_cast( - const_cast(obj)->addDynamicProperty("Part::PropertyShapeCache", - SHAPE_CACHE_NAME,"Part","Shape cache", - App::Prop_NoPersist|App::Prop_Output|App::Prop_Hidden)); - if(!prop) + prop = static_cast(const_cast(obj)->addDynamicProperty( + "Part::PropertyShapeCache", + SHAPE_CACHE_NAME, + "Part", + "Shape cache", + App::Prop_NoPersist | App::Prop_Output | App::Prop_Hidden + )); + if (!prop) { FC_ERR("Failed to add shape cache for " << obj->getFullName()); - else + } + else { prop->connChanged = const_cast(obj)->signalEarlyChanged.connect( - std::bind(&PropertyShapeCache::slotChanged,prop,sp::_1,sp::_2)); + std::bind(&PropertyShapeCache::slotChanged, prop, sp::_1, sp::_2) + ); + } return prop; } @@ -1012,17 +1128,21 @@ PropertyShapeCache *PropertyShapeCache::get(const App::DocumentObject *obj, bool * @param subname The key to look up * @return True if the name was found */ -bool PropertyShapeCache::getShape(const App::DocumentObject *obj, TopoShape &shape, const char *subname) { -// March, 2024 Toponaming project: There was originally a feature to disable shape cache -// that has not been kept: -// if (PartParams::getDisableShapeCache()) -// return false; - auto prop = get(obj,false); - if(!prop) +bool PropertyShapeCache::getShape(const App::DocumentObject* obj, TopoShape& shape, const char* subname) +{ + // March, 2024 Toponaming project: There was originally a feature to disable shape cache + // that has not been kept: + // if (PartParams::getDisableShapeCache()) + // return false; + auto prop = get(obj, false); + if (!prop) { return false; - if(!subname) subname = ""; + } + if (!subname) { + subname = ""; + } auto it = prop->cache.find(subname); - if(it!=prop->cache.end()) { + if (it != prop->cache.end()) { shape = it->second; return !shape.isNull(); } @@ -1035,29 +1155,31 @@ bool PropertyShapeCache::getShape(const App::DocumentObject *obj, TopoShape &sha * @param shape The shape to cache * @param subname The key to point at that shape */ -void PropertyShapeCache::setShape( - const App::DocumentObject *obj, const TopoShape &shape, const char *subname) +void PropertyShapeCache::setShape(const App::DocumentObject* obj, const TopoShape& shape, const char* subname) { -// March, 2024 Toponaming project: There was originally a feature to disable shape cache -// that has not been kept: -// if (PartParams::getDisableShapeCache()) -// return; - auto prop = get(obj,true); - if(!prop) + // March, 2024 Toponaming project: There was originally a feature to disable shape cache + // that has not been kept: + // if (PartParams::getDisableShapeCache()) + // return; + auto prop = get(obj, true); + if (!prop) { return; - if(!subname) subname = ""; + } + if (!subname) { + subname = ""; + } prop->cache[subname] = shape; } -void PropertyShapeCache::slotChanged(const App::DocumentObject &, const App::Property &prop) { +void PropertyShapeCache::slotChanged(const App::DocumentObject&, const App::Property& prop) +{ auto propName = prop.getName(); - if(!propName) return; - if(strcmp(propName,"Group")==0 || - strcmp(propName,"Shape")==0 || - strstr(propName,"Touched")!=0) - { + if (!propName) { + return; + } + if (strcmp(propName, "Group") == 0 || strcmp(propName, "Shape") == 0 + || strstr(propName, "Touched") != 0) { FC_LOG("clear shape cache on changed " << prop.getFullName()); cache.clear(); } } - diff --git a/src/Mod/Part/App/PropertyTopoShape.h b/src/Mod/Part/App/PropertyTopoShape.h index 421f07c3f4..b84649e489 100644 --- a/src/Mod/Part/App/PropertyTopoShape.h +++ b/src/Mod/Part/App/PropertyTopoShape.h @@ -39,11 +39,11 @@ namespace Part { -class Feature; +class Feature; /** The part shape property class. * @author Werner Mayer */ -class PartExport PropertyPartShape : public App::PropertyComplexGeoData +class PartExport PropertyPartShape: public App::PropertyComplexGeoData { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -56,7 +56,7 @@ public: /// set the part shape void setValue(const TopoShape&); /// set the part shape - void setValue(const TopoDS_Shape&, bool resetElementMap=true); + void setValue(const TopoDS_Shape&, bool resetElementMap = true); /// get the part shape const TopoDS_Shape& getValue() const; const TopoShape& getShape() const; @@ -70,7 +70,7 @@ public: /// Get the placement of the geometry Base::Matrix4D getTransform() const override; /// Transform the real shape data - void transformGeometry(const Base::Matrix4D &rclMat) override; + void transformGeometry(const Base::Matrix4D& rclMat) override; //@} /** @name Getting basic geometric entities */ @@ -82,38 +82,41 @@ public: /** @name Python interface */ //@{ PyObject* getPyObject() override; - void setPyObject(PyObject *value) override; + void setPyObject(PyObject* value) override; //@} /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const override; - void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; virtual void beforeSave() const override; - void SaveDocFile (Base::Writer &writer) const override; - void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile(Base::Writer& writer) const override; + void RestoreDocFile(Base::Reader& reader) override; - App::Property *Copy() const override; - void Paste(const App::Property &from) override; - unsigned int getMemSize () const override; + App::Property* Copy() const override; + void Paste(const App::Property& from) override; + unsigned int getMemSize() const override; //@} /// Get valid paths for this property; used by auto completer - void getPaths(std::vector & paths) const override; + void getPaths(std::vector& paths) const override; std::string getElementMapVersion(bool restored) const override; - void resetElementMapVersion() {_Ver.clear();} + void resetElementMapVersion() + { + _Ver.clear(); + } void afterRestore() override; friend class Feature; private: - void saveToFile(Base::Writer &writer) const; - void loadFromFile(Base::Reader &reader); - void loadFromStream(Base::Reader &reader); + void saveToFile(Base::Writer& writer) const; + void loadFromFile(Base::Reader& reader); + void loadFromStream(Base::Reader& reader); private: TopoShape _Shape; @@ -122,17 +125,19 @@ private: mutable bool _SaveHasher = false; }; -struct PartExport ShapeHistory { +struct PartExport ShapeHistory +{ /** - * @brief MapList: key is index of subshape (of type 'type') in source - * shape. Value is list of indexes of subshapes in result shape. - */ - using MapList = std::map >; + * @brief MapList: key is index of subshape (of type 'type') in source + * shape. Value is list of indexes of subshapes in result shape. + */ + using MapList = std::map>; using List = std::vector; TopAbs_ShapeEnum type {TopAbs_SHAPE}; MapList shapeMap; - ShapeHistory() {} + ShapeHistory() + {} /** * Build a history of changes * MakeShape: The operation that created the changes, e.g. FCBRepAlgoAPI_Common @@ -140,15 +145,22 @@ struct PartExport ShapeHistory { * newS: The new shape that was created by the operation * oldS: The original shape prior to the operation */ - ShapeHistory(BRepBuilderAPI_MakeShape& mkShape, TopAbs_ShapeEnum type, - const TopoDS_Shape& newS, const TopoDS_Shape& oldS); - void reset(BRepBuilderAPI_MakeShape& mkShape, TopAbs_ShapeEnum type, - const TopoDS_Shape& newS, const TopoDS_Shape& oldS); - void join(const ShapeHistory &newH); - + ShapeHistory( + BRepBuilderAPI_MakeShape& mkShape, + TopAbs_ShapeEnum type, + const TopoDS_Shape& newS, + const TopoDS_Shape& oldS + ); + void reset( + BRepBuilderAPI_MakeShape& mkShape, + TopAbs_ShapeEnum type, + const TopoDS_Shape& newS, + const TopoDS_Shape& oldS + ); + void join(const ShapeHistory& newH); }; -class PartExport PropertyShapeHistory : public App::PropertyLists +class PartExport PropertyShapeHistory: public App::PropertyLists { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -156,10 +168,12 @@ public: PropertyShapeHistory(); ~PropertyShapeHistory() override; - void setSize(int newSize) override { + void setSize(int newSize) override + { _lValueList.resize(newSize); } - int getSize() const override { + int getSize() const override + { return _lValueList.size(); } @@ -167,25 +181,27 @@ public: */ void setValue(const ShapeHistory&); - void setValues (const std::vector& values); + void setValues(const std::vector& values); - const std::vector &getValues() const { + const std::vector& getValues() const + { return _lValueList; } - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; - void Save (Base::Writer &writer) const override; - void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; - void SaveDocFile (Base::Writer &writer) const override; - void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile(Base::Writer& writer) const override; + void RestoreDocFile(Base::Reader& reader) override; - Property *Copy() const override; - void Paste(const Property &from) override; + Property* Copy() const override; + void Paste(const Property& from) override; - unsigned int getMemSize () const override { + unsigned int getMemSize() const override + { return _lValueList.size() * sizeof(ShapeHistory); } @@ -196,26 +212,29 @@ private: /** A property class to store hash codes and two radii for the fillet algorithm. * @author Werner Mayer */ -struct PartExport FilletElement { +struct PartExport FilletElement +{ int edgeid; double radius1, radius2; - FilletElement(int id=0,double r1=1.0,double r2=1.0) - :edgeid(id),radius1(r1),radius2(r2) + FilletElement(int id = 0, double r1 = 1.0, double r2 = 1.0) + : edgeid(id) + , radius1(r1) + , radius2(r2) {} - bool operator<(const FilletElement &other) const { + bool operator<(const FilletElement& other) const + { return edgeid < other.edgeid; } - bool operator==(const FilletElement &other) const { - return edgeid == other.edgeid - && radius1 == other.radius1 - && radius2 == other.radius2; + bool operator==(const FilletElement& other) const + { + return edgeid == other.edgeid && radius1 == other.radius1 && radius2 == other.radius2; } }; -class PartExport PropertyFilletEdges : public App::PropertyLists +class PartExport PropertyFilletEdges: public App::PropertyLists { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -223,10 +242,12 @@ public: PropertyFilletEdges(); ~PropertyFilletEdges() override; - void setSize(int newSize) override { + void setSize(int newSize) override + { _lValueList.resize(newSize); } - int getSize() const override { + int getSize() const override + { return _lValueList.size(); } @@ -234,25 +255,27 @@ public: */ void setValue(int id, double r1, double r2); - void setValues (const std::vector& values); + void setValues(const std::vector& values); - const std::vector &getValues() const { + const std::vector& getValues() const + { return _lValueList; } - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; - void Save (Base::Writer &writer) const override; - void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; - void SaveDocFile (Base::Writer &writer) const override; - void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile(Base::Writer& writer) const override; + void RestoreDocFile(Base::Reader& reader) override; - Property *Copy() const override; - void Paste(const Property &from) override; + Property* Copy() const override; + void Paste(const Property& from) override; - unsigned int getMemSize () const override { + unsigned int getMemSize() const override + { return _lValueList.size() * sizeof(FilletElement); } @@ -261,34 +284,36 @@ private: }; -class PartExport PropertyShapeCache: public App::Property { +class PartExport PropertyShapeCache: public App::Property +{ TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - virtual App::Property *Copy(void) const override; + virtual App::Property* Copy(void) const override; - virtual void Paste(const App::Property &) override; + virtual void Paste(const App::Property&) override; - virtual PyObject *getPyObject() override; + virtual PyObject* getPyObject() override; - virtual void setPyObject(PyObject *value) override; + virtual void setPyObject(PyObject* value) override; - virtual void Save (Base::Writer &writer) const override; + virtual void Save(Base::Writer& writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + virtual void Restore(Base::XMLReader& reader) override; - static PropertyShapeCache *get(const App::DocumentObject *obj, bool create); - static bool getShape(const App::DocumentObject *obj, TopoShape &shape, const char *subname=0); - static void setShape(const App::DocumentObject *obj, const TopoShape &shape, const char *subname=0); + static PropertyShapeCache* get(const App::DocumentObject* obj, bool create); + static bool getShape(const App::DocumentObject* obj, TopoShape& shape, const char* subname = 0); + static void setShape(const App::DocumentObject* obj, const TopoShape& shape, const char* subname = 0); private: - void slotChanged(const App::DocumentObject &, const App::Property &prop); + void slotChanged(const App::DocumentObject&, const App::Property& prop); private: std::unordered_map cache; boost::signals2::scoped_connection connChanged; }; -} //namespace Part +} // namespace Part -#endif // PART_PROPERTYTOPOSHAPE_H +#endif // PART_PROPERTYTOPOSHAPE_H diff --git a/src/Mod/Part/App/PropertyTopoShapeList.cpp b/src/Mod/Part/App/PropertyTopoShapeList.cpp index 0950e031f4..1861a92b52 100644 --- a/src/Mod/Part/App/PropertyTopoShapeList.cpp +++ b/src/Mod/Part/App/PropertyTopoShapeList.cpp @@ -73,7 +73,7 @@ void PropertyTopoShapeList::setValue() clear(); } -void PropertyTopoShapeList::setValue(const TopoShape &ts) +void PropertyTopoShapeList::setValue(const TopoShape& ts) { aboutToSetValue(); _lValueList.resize(1); @@ -98,7 +98,6 @@ void PropertyTopoShapeList::clear() _lValueList.clear(); _lValueList.resize(0); hasSetValue(); - } // populate the lists with the TopoShapes that have now finished restoring @@ -115,7 +114,7 @@ void PropertyTopoShapeList::afterRestore() App::PropertyLists::afterRestore(); } -PyObject *PropertyTopoShapeList::getPyObject() +PyObject* PropertyTopoShapeList::getPyObject() { Py::List list; for (int i = 0; i < getSize(); i++) { @@ -124,7 +123,7 @@ PyObject *PropertyTopoShapeList::getPyObject() return Py::new_reference_to(list); } -void PropertyTopoShapeList::setPyObject(PyObject *value) +void PropertyTopoShapeList::setPyObject(PyObject* value) { if (PySequence_Check(value)) { Py::Sequence sequence(value); @@ -132,7 +131,7 @@ void PropertyTopoShapeList::setPyObject(PyObject *value) std::vector values; values.resize(nSize); - for (Py_ssize_t i=0; i < nSize; ++i) { + for (Py_ssize_t i = 0; i < nSize; ++i) { Py::Object item = sequence.getItem(i); if (!PyObject_TypeCheck(item.ptr(), &(TopoShapePy::Type))) { std::string error = std::string("types in list must be 'Shape', not "); @@ -145,7 +144,7 @@ void PropertyTopoShapeList::setPyObject(PyObject *value) setValues(values); } else if (PyObject_TypeCheck(value, &(TopoShapePy::Type))) { - TopoShapePy *pcObject = static_cast(value); + TopoShapePy* pcObject = static_cast(value); setValue(*pcObject->getTopoShapePtr()); } else { @@ -250,9 +249,9 @@ void PropertyTopoShapeList::RestoreDocFile(Base::Reader& reader) } } -App::Property *PropertyTopoShapeList::Copy() const +App::Property* PropertyTopoShapeList::Copy() const { - PropertyTopoShapeList *p = new PropertyTopoShapeList(); + PropertyTopoShapeList* p = new PropertyTopoShapeList(); std::vector copiedShapes; for (auto& shape : _lValueList) { BRepBuilderAPI_Copy copy(shape.getShape()); @@ -262,7 +261,7 @@ App::Property *PropertyTopoShapeList::Copy() const return p; } -void PropertyTopoShapeList::Paste(const Property &from) +void PropertyTopoShapeList::Paste(const Property& from) { const PropertyTopoShapeList& FromList = dynamic_cast(from); setValues(FromList._lValueList); @@ -271,8 +270,8 @@ void PropertyTopoShapeList::Paste(const Property &from) unsigned int PropertyTopoShapeList::getMemSize() const { int size = sizeof(PropertyTopoShapeList); - for (int i = 0; i < getSize(); i++) + for (int i = 0; i < getSize(); i++) { size += _lValueList[i].getMemSize(); + } return size; } - diff --git a/src/Mod/Part/App/PropertyTopoShapeList.h b/src/Mod/Part/App/PropertyTopoShapeList.h index 61d80384fd..77befe768b 100644 --- a/src/Mod/Part/App/PropertyTopoShapeList.h +++ b/src/Mod/Part/App/PropertyTopoShapeList.h @@ -32,13 +32,14 @@ #include -#include "TopoShape.h" +#include "TopoShape.h" -namespace Base { +namespace Base +{ class Writer; class XMLReader; -} +} // namespace Base namespace Part { @@ -72,25 +73,27 @@ public: void clear(); /// index operator - const TopoShape& operator[] (const int idx) const { + const TopoShape& operator[](const int idx) const + { return _lValueList[idx]; } - const std::vector& getValues() const { + const std::vector& getValues() const + { return _lValueList; } - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; - void Save(Base::Writer &writer) const override; - void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer& writer) const override; + void Restore(Base::XMLReader& reader) override; - void SaveDocFile (Base::Writer &writer) const override; - void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile(Base::Writer& writer) const override; + void RestoreDocFile(Base::Reader& reader) override; - App::Property *Copy() const override; - void Paste(const App::Property &from) override; + App::Property* Copy() const override; + void Paste(const App::Property& from) override; unsigned int getMemSize() const override; @@ -106,9 +109,7 @@ private: std::vector m_restorePointers; }; -} // namespace Part - - -#endif // APP_PropertyTopoShapeList_H +} // namespace Part +#endif // APP_PropertyTopoShapeList_H diff --git a/src/Mod/Part/App/RectangularTrimmedSurface.pyi b/src/Mod/Part/App/RectangularTrimmedSurface.pyi index 086111f2df..1cbe0fae18 100644 --- a/src/Mod/Part/App/RectangularTrimmedSurface.pyi +++ b/src/Mod/Part/App/RectangularTrimmedSurface.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export from GeometrySurface import GeometrySurface from typing import Any, Final, Tuple - @export( Twin="GeomTrimmedSurface", TwinPointer="GeomTrimmedSurface", diff --git a/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp b/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp index 9c2711025b..ec79bf8296 100644 --- a/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp +++ b/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include "OCCError.h" @@ -41,7 +41,7 @@ std::string RectangularTrimmedSurfacePy::representation() const return {""}; } -PyObject *RectangularTrimmedSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* RectangularTrimmedSurfacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of RectangularTrimmedSurfacePy and the Twin object return new RectangularTrimmedSurfacePy(new GeomTrimmedSurface); @@ -51,14 +51,30 @@ PyObject *RectangularTrimmedSurfacePy::PyMake(struct _typeobject *, PyObject *, int RectangularTrimmedSurfacePy::PyInit(PyObject* args, PyObject* /*kwd*/) { PyObject* surf; - double u1,u2,v1,v2; - PyObject *usense=Py_True, *vsense=Py_True; - if (PyArg_ParseTuple(args, "O!dddd|O!O!",&(Part::GeometrySurfacePy::Type),&surf, - &u1,&u2,&v1,&v2,&PyBool_Type,&usense,&PyBool_Type,&vsense)) { + double u1, u2, v1, v2; + PyObject *usense = Py_True, *vsense = Py_True; + if (PyArg_ParseTuple( + args, + "O!dddd|O!O!", + &(Part::GeometrySurfacePy::Type), + &surf, + &u1, + &u2, + &v1, + &v2, + &PyBool_Type, + &usense, + &PyBool_Type, + &vsense + )) { getGeomTrimmedSurfacePtr()->setHandle(new Geom_RectangularTrimmedSurface( - Handle(Geom_Surface)::DownCast(static_cast(surf)-> - getGeomSurfacePtr()->handle()), - u1, u2, v1, v2, + Handle(Geom_Surface)::DownCast( + static_cast(surf)->getGeomSurfacePtr()->handle() + ), + u1, + u2, + v1, + v2, Base::asBoolean(usense), Base::asBoolean(vsense) )); @@ -66,16 +82,30 @@ int RectangularTrimmedSurfacePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - double param1,param2; - PyObject *utrim=Py_False, *sense=Py_True; - if (PyArg_ParseTuple(args, "O!ddO!|O!",&(Part::GeometrySurfacePy::Type),&surf, - ¶m1,¶m2,&PyBool_Type,&utrim,&PyBool_Type,&sense)) { + double param1, param2; + PyObject *utrim = Py_False, *sense = Py_True; + if (PyArg_ParseTuple( + args, + "O!ddO!|O!", + &(Part::GeometrySurfacePy::Type), + &surf, + ¶m1, + ¶m2, + &PyBool_Type, + &utrim, + &PyBool_Type, + &sense + )) { Standard_Boolean UTrim = Base::asBoolean(utrim); Standard_Boolean Sense = Base::asBoolean(sense); getGeomTrimmedSurfacePtr()->setHandle(new Geom_RectangularTrimmedSurface( - Handle(Geom_Surface)::DownCast(static_cast(surf)-> - getGeomSurfacePtr()->handle()), - param1, param2, UTrim, Sense + Handle(Geom_Surface)::DownCast( + static_cast(surf)->getGeomSurfacePtr()->handle() + ), + param1, + param2, + UTrim, + Sense )); return 0; } @@ -84,15 +114,17 @@ int RectangularTrimmedSurfacePy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -PyObject* RectangularTrimmedSurfacePy::setTrim(PyObject *args) +PyObject* RectangularTrimmedSurfacePy::setTrim(PyObject* args) { double u1, u2, v1, v2; - if (!PyArg_ParseTuple(args, "dddd", &u1, &u2, &v1, &v2)) + if (!PyArg_ParseTuple(args, "dddd", &u1, &u2, &v1, &v2)) { return nullptr; + } try { - Handle(Geom_RectangularTrimmedSurface) surf = Handle(Geom_RectangularTrimmedSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_RectangularTrimmedSurface) surf = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(getGeometryPtr()->handle()); if (surf.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a surface"); return nullptr; @@ -109,8 +141,9 @@ PyObject* RectangularTrimmedSurfacePy::setTrim(PyObject *args) Py::Object RectangularTrimmedSurfacePy::getBasisSurface() const { - Handle(Geom_RectangularTrimmedSurface) surf = Handle(Geom_RectangularTrimmedSurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_RectangularTrimmedSurface) surf = Handle(Geom_RectangularTrimmedSurface)::DownCast( + getGeometryPtr()->handle() + ); if (surf.IsNull()) { throw Py::TypeError("geometry is not a surface"); } @@ -119,7 +152,7 @@ Py::Object RectangularTrimmedSurfacePy::getBasisSurface() const return Py::asObject(geo->getPyObject()); } -PyObject *RectangularTrimmedSurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* RectangularTrimmedSurfacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/STEP/ImportExportSettings.cpp b/src/Mod/Part/App/STEP/ImportExportSettings.cpp index 409a1b40b2..ba9d48e856 100644 --- a/src/Mod/Part/App/STEP/ImportExportSettings.cpp +++ b/src/Mod/Part/App/STEP/ImportExportSettings.cpp @@ -22,19 +22,23 @@ * * ***************************************************************************/ -# include +#include #include "ImportExportSettings.h" #include -namespace Part { -namespace STEP { +namespace Part +{ +namespace STEP +{ ImportExportSettings::ImportExportSettings() { - pGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part/STEP"); + pGroup = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part/STEP" + ); } void ImportExportSettings::setVisibleExportDialog(bool on) @@ -59,14 +63,18 @@ bool ImportExportSettings::isVisibleImportDialog() const void ImportExportSettings::setWriteSurfaceCurveMode(bool on) { - ParameterGrp::handle grp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part/General"); + ParameterGrp::handle grp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part/General" + ); grp->SetInt("WriteSurfaceCurveMode", on ? 1 : 0); Interface_Static::SetIVal("write.surfacecurve.mode", on ? 1 : 0); } bool ImportExportSettings::getWriteSurfaceCurveMode() const { - ParameterGrp::handle grp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part/General"); + ParameterGrp::handle grp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part/General" + ); int writesurfacecurve = Interface_Static::IVal("write.surfacecurve.mode"); writesurfacecurve = grp->GetInt("WriteSurfaceCurveMode", writesurfacecurve); return (writesurfacecurve == 0 ? false : true); @@ -124,5 +132,5 @@ void ImportExportSettings::setProductName(const char* name) Part::Interface::writeStepHeaderProduct(name); } -} // namespace STEP -} // namespace Part +} // namespace STEP +} // namespace Part diff --git a/src/Mod/Part/App/STEP/ImportExportSettings.h b/src/Mod/Part/App/STEP/ImportExportSettings.h index e612f721c9..993358c50a 100644 --- a/src/Mod/Part/App/STEP/ImportExportSettings.h +++ b/src/Mod/Part/App/STEP/ImportExportSettings.h @@ -68,7 +68,7 @@ private: ParameterGrp::handle pGroup; }; -} //namespace STEP -} //namespace Part +} // namespace STEP +} // namespace Part #endif diff --git a/src/Mod/Part/App/Services.cpp b/src/Mod/Part/App/Services.cpp index ab3826c5ec..8c84cafd77 100644 --- a/src/Mod/Part/App/Services.cpp +++ b/src/Mod/Part/App/Services.cpp @@ -31,8 +31,10 @@ AttacherSubObjectPlacement::AttacherSubObjectPlacement() attacher->setUp({}, Attacher::mmMidpoint); } -Base::Placement AttacherSubObjectPlacement::calculate(App::SubObjectT object, - Base::Placement basePlacement) const +Base::Placement AttacherSubObjectPlacement::calculate( + App::SubObjectT object, + Base::Placement basePlacement +) const { attacher->setReferences({object}); @@ -47,11 +49,11 @@ std::optional PartCenterOfMass::ofDocumentObject(App::DocumentOb const auto shape = feature->Shape.getShape(); if (const auto cog = shape.centerOfGravity()) { - const Base::Placement comPlacement { *cog, Base::Rotation { } }; + const Base::Placement comPlacement {*cog, Base::Rotation {}}; return (feature->Placement.getValue().inverse() * comPlacement).getPosition(); } } return {}; -} \ No newline at end of file +} diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_Edge.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_Edge.pyi index 82ebf40d97..0cc7246f96 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_Edge.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_Edge.pyi @@ -7,7 +7,8 @@ from typing import Final Include="ShapeFix_Edge.hxx", Constructor=True, ) -@class_declarations(""" +@class_declarations( + """ private: Handle(ShapeFix_Edge) hEdge; @@ -16,7 +17,8 @@ public: setTwinPointer(handle.get()); hEdge = handle; } -""") +""" +) class ShapeFix_Edge(PyObjectBase): """ Fixing invalid edge diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnect.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnect.pyi index b1154908c1..0a4f3d2749 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnect.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnect.pyi @@ -20,10 +20,8 @@ class ShapeFix_EdgeConnect(PyObjectBase): @overload def add(self, edge1: TopoShapeEdge, edge2: TopoShapeEdge) -> None: ... - @overload def add(self, shape: TopoShape) -> None: ... - def add(self, *args, **kwargs) -> None: """ add(edge, edge) diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnectPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnectPyImp.cpp index 137fbf2fe4..642dff51ef 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnectPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_EdgeConnectPyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_EdgeConnectPy.h" @@ -40,7 +40,7 @@ std::string ShapeFix_EdgeConnectPy::representation() const return ""; } -PyObject *ShapeFix_EdgeConnectPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_EdgeConnectPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_RootPy return new ShapeFix_EdgeConnectPy(new ShapeFix_EdgeConnect); @@ -49,17 +49,17 @@ PyObject *ShapeFix_EdgeConnectPy::PyMake(struct _typeobject *, PyObject *, PyObj // constructor method int ShapeFix_EdgeConnectPy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_EdgeConnectPy::add(PyObject *args) +PyObject* ShapeFix_EdgeConnectPy::add(PyObject* args) { PyObject* edge1; PyObject* edge2; - if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge1, - &TopoShapeEdgePy::Type, &edge2)) { + if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge1, &TopoShapeEdgePy::Type, &edge2)) { TopoDS_Shape e1 = static_cast(edge1)->getTopoShapePtr()->getShape(); TopoDS_Shape e2 = static_cast(edge2)->getTopoShapePtr()->getShape(); getShapeFix_EdgeConnectPtr()->Add(TopoDS::Edge(e1), TopoDS::Edge(e2)); @@ -73,30 +73,35 @@ PyObject* ShapeFix_EdgeConnectPy::add(PyObject *args) Py_Return; } - PyErr_SetString(PyExc_TypeError, "add(edge, edge) or\n" - "add(shape)"); + PyErr_SetString( + PyExc_TypeError, + "add(edge, edge) or\n" + "add(shape)" + ); return nullptr; } -PyObject* ShapeFix_EdgeConnectPy::build(PyObject *args) +PyObject* ShapeFix_EdgeConnectPy::build(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_EdgeConnectPtr()->Build(); Py_Return; } -PyObject* ShapeFix_EdgeConnectPy::clear(PyObject *args) +PyObject* ShapeFix_EdgeConnectPy::clear(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_EdgeConnectPtr()->Clear(); Py_Return; } -PyObject *ShapeFix_EdgeConnectPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_EdgeConnectPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_EdgePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_EdgePyImp.cpp index 10bee17df9..813734e934 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_EdgePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_EdgePyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include @@ -45,7 +45,7 @@ std::string ShapeFix_EdgePy::representation() const return ""; } -PyObject *ShapeFix_EdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_EdgePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_EdgePy return new ShapeFix_EdgePy(nullptr); @@ -54,19 +54,19 @@ PyObject *ShapeFix_EdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // constructor method int ShapeFix_EdgePy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } setHandle(new ShapeFix_Edge); return 0; } -PyObject* ShapeFix_EdgePy::fixRemovePCurve(PyObject *args) +PyObject* ShapeFix_EdgePy::fixRemovePCurve(PyObject* args) { PyObject* edge; PyObject* face; - if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge, - &TopoShapeFacePy::Type, &face)) { + if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge, &TopoShapeFacePy::Type, &face)) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); @@ -76,11 +76,20 @@ PyObject* ShapeFix_EdgePy::fixRemovePCurve(PyObject *args) PyErr_Clear(); PyObject* plm; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge, - &GeometrySurfacePy::Type, &face, - &Base::PlacementPy::Type, &plm)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge, + &GeometrySurfacePy::Type, + &face, + &Base::PlacementPy::Type, + &plm + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(face)->getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(face)->getGeometryPtr()->handle() + ); Base::Placement* pm = static_cast(plm)->getPlacementPtr(); TopLoc_Location loc = Tools::fromPlacement(*pm); @@ -88,82 +97,107 @@ PyObject* ShapeFix_EdgePy::fixRemovePCurve(PyObject *args) return Py::new_reference_to(Py::Boolean(ok)); } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- fixRemovePCurve(edge, face) or\n" - "-- fixRemovePCurve(edge, surface, placement)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- fixRemovePCurve(edge, face) or\n" + "-- fixRemovePCurve(edge, surface, placement)" + ); return nullptr; } -PyObject* ShapeFix_EdgePy::fixRemoveCurve3d(PyObject *args) +PyObject* ShapeFix_EdgePy::fixRemoveCurve3d(PyObject* args) { PyObject* edge; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeEdgePy::Type, &edge)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeEdgePy::Type, &edge)) { return nullptr; + } TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); bool ok = getShapeFix_EdgePtr()->FixRemoveCurve3d(TopoDS::Edge(e)); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_EdgePy::fixAddPCurve(PyObject *args) +PyObject* ShapeFix_EdgePy::fixAddPCurve(PyObject* args) { PyObject* edge; PyObject* face; PyObject* seam; double prec = 0.0; - if (PyArg_ParseTuple(args, "O!O!O!|d", &TopoShapeEdgePy::Type, &edge, - &TopoShapeFacePy::Type, &face, - &PyBool_Type, &seam, &prec)) { + if (PyArg_ParseTuple( + args, + "O!O!O!|d", + &TopoShapeEdgePy::Type, + &edge, + &TopoShapeFacePy::Type, + &face, + &PyBool_Type, + &seam, + &prec + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); - bool ok = getShapeFix_EdgePtr()->FixAddPCurve(TopoDS::Edge(e), TopoDS::Face(f), - Base::asBoolean(seam), - prec); + bool ok = getShapeFix_EdgePtr() + ->FixAddPCurve(TopoDS::Edge(e), TopoDS::Face(f), Base::asBoolean(seam), prec); return Py::new_reference_to(Py::Boolean(ok)); } PyErr_Clear(); PyObject* plm; - if (PyArg_ParseTuple(args, "O!O!O!O!|d", &TopoShapeEdgePy::Type, &edge, - &GeometrySurfacePy::Type, &face, - &Base::PlacementPy::Type, &plm, - &PyBool_Type, &seam, &prec)) { + if (PyArg_ParseTuple( + args, + "O!O!O!O!|d", + &TopoShapeEdgePy::Type, + &edge, + &GeometrySurfacePy::Type, + &face, + &Base::PlacementPy::Type, + &plm, + &PyBool_Type, + &seam, + &prec + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(face)->getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(face)->getGeometryPtr()->handle() + ); Base::Placement* pm = static_cast(plm)->getPlacementPtr(); TopLoc_Location loc = Tools::fromPlacement(*pm); - bool ok = getShapeFix_EdgePtr()->FixAddPCurve(TopoDS::Edge(e), surf, loc, - Base::asBoolean(seam), - prec); + bool ok = getShapeFix_EdgePtr() + ->FixAddPCurve(TopoDS::Edge(e), surf, loc, Base::asBoolean(seam), prec); return Py::new_reference_to(Py::Boolean(ok)); } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- fixAddPCurve(edge, face, isSeam, prec) or\n" - "-- fixAddPCurve(edge, surface, placement, isSeam, prec)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- fixAddPCurve(edge, face, isSeam, prec) or\n" + "-- fixAddPCurve(edge, surface, placement, isSeam, prec)" + ); return nullptr; } -PyObject* ShapeFix_EdgePy::fixAddCurve3d(PyObject *args) +PyObject* ShapeFix_EdgePy::fixAddCurve3d(PyObject* args) { PyObject* edge; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeEdgePy::Type, &edge)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeEdgePy::Type, &edge)) { return nullptr; + } TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); bool ok = getShapeFix_EdgePtr()->FixAddCurve3d(TopoDS::Edge(e)); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_EdgePy::fixVertexTolerance(PyObject *args) +PyObject* ShapeFix_EdgePy::fixVertexTolerance(PyObject* args) { PyObject* edge; PyObject* face = nullptr; - if (!PyArg_ParseTuple(args, "O!|O!", &TopoShapeEdgePy::Type, &edge, - &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!|O!", &TopoShapeEdgePy::Type, &edge, &TopoShapeFacePy::Type, &face)) { return nullptr; + } TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); @@ -178,12 +212,11 @@ PyObject* ShapeFix_EdgePy::fixVertexTolerance(PyObject *args) } } -PyObject* ShapeFix_EdgePy::fixReversed2d(PyObject *args) +PyObject* ShapeFix_EdgePy::fixReversed2d(PyObject* args) { PyObject* edge; PyObject* face; - if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge, - &TopoShapeFacePy::Type, &face)) { + if (PyArg_ParseTuple(args, "O!O!", &TopoShapeEdgePy::Type, &edge, &TopoShapeFacePy::Type, &face)) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); @@ -193,11 +226,20 @@ PyObject* ShapeFix_EdgePy::fixReversed2d(PyObject *args) PyErr_Clear(); PyObject* plm; - if (PyArg_ParseTuple(args, "O!O!O!", &TopoShapeEdgePy::Type, &edge, - &GeometrySurfacePy::Type, &face, - &Base::PlacementPy::Type, &plm)) { + if (PyArg_ParseTuple( + args, + "O!O!O!", + &TopoShapeEdgePy::Type, + &edge, + &GeometrySurfacePy::Type, + &face, + &Base::PlacementPy::Type, + &plm + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(face)->getGeometryPtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(face)->getGeometryPtr()->handle() + ); Base::Placement* pm = static_cast(plm)->getPlacementPtr(); TopLoc_Location loc = Tools::fromPlacement(*pm); @@ -205,13 +247,16 @@ PyObject* ShapeFix_EdgePy::fixReversed2d(PyObject *args) return Py::new_reference_to(Py::Boolean(ok)); } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- FixReversed2d(edge, face) or\n" - "-- FixReversed2d(edge, surface, placement)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- FixReversed2d(edge, face) or\n" + "-- FixReversed2d(edge, surface, placement)" + ); return nullptr; } -PyObject* ShapeFix_EdgePy::fixSameParameter(PyObject *args) +PyObject* ShapeFix_EdgePy::fixSameParameter(PyObject* args) { PyObject* edge; double tolerance = 0.0; @@ -224,9 +269,15 @@ PyObject* ShapeFix_EdgePy::fixSameParameter(PyObject *args) PyErr_Clear(); PyObject* face; - if (PyArg_ParseTuple(args, "O!O!|d", &TopoShapeEdgePy::Type, &edge, - &TopoShapeFacePy::Type, &face, - &tolerance)) { + if (PyArg_ParseTuple( + args, + "O!O!|d", + &TopoShapeEdgePy::Type, + &edge, + &TopoShapeFacePy::Type, + &face, + &tolerance + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); @@ -234,13 +285,16 @@ PyObject* ShapeFix_EdgePy::fixSameParameter(PyObject *args) return Py::new_reference_to(Py::Boolean(ok)); } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- fixSameParameter(edge, tolerance) or\n" - "-- fixSameParameter(edge, face, tolerance)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- fixSameParameter(edge, tolerance) or\n" + "-- fixSameParameter(edge, face, tolerance)" + ); return nullptr; } -PyObject *ShapeFix_EdgePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_EdgePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnect.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnect.pyi index e36d79abd7..6819755e03 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnect.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnect.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export, constmethod from Base.PyObjectBase import PyObjectBase - @export( PythonName="Part.ShapeFix.FaceConnect", Include="ShapeFix_FaceConnect.hxx", diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnectPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnectPyImp.cpp index 05a9576403..c71875a463 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnectPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FaceConnectPyImp.cpp @@ -24,8 +24,8 @@ #include -# include -# include +#include +#include #include "ShapeFix/ShapeFix_FaceConnectPy.h" @@ -42,7 +42,7 @@ std::string ShapeFix_FaceConnectPy::representation() const return ""; } -PyObject *ShapeFix_FaceConnectPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_FaceConnectPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_FaceConnectPy(new ShapeFix_FaceConnect); } @@ -50,18 +50,19 @@ PyObject *ShapeFix_FaceConnectPy::PyMake(struct _typeobject *, PyObject *, PyObj // constructor method int ShapeFix_FaceConnectPy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_FaceConnectPy::add(PyObject *args) +PyObject* ShapeFix_FaceConnectPy::add(PyObject* args) { PyObject* face1; PyObject* face2; - if (!PyArg_ParseTuple(args, "O!O!", &TopoShapeFacePy::Type, &face1, - &TopoShapeFacePy::Type, &face2)) + if (!PyArg_ParseTuple(args, "O!O!", &TopoShapeFacePy::Type, &face1, &TopoShapeFacePy::Type, &face2)) { return nullptr; + } TopoDS_Shape f1 = static_cast(face1)->getTopoShapePtr()->getShape(); TopoDS_Shape f2 = static_cast(face2)->getTopoShapePtr()->getShape(); @@ -69,29 +70,31 @@ PyObject* ShapeFix_FaceConnectPy::add(PyObject *args) Py_Return; } -PyObject* ShapeFix_FaceConnectPy::build(PyObject *args) +PyObject* ShapeFix_FaceConnectPy::build(PyObject* args) { PyObject* shell; double sewtoler; double fixtoler; - if (!PyArg_ParseTuple(args, "O!dd", &TopoShapeShellPy::Type, &shell, &sewtoler, &fixtoler)) + if (!PyArg_ParseTuple(args, "O!dd", &TopoShapeShellPy::Type, &shell, &sewtoler, &fixtoler)) { return nullptr; + } TopoDS_Shape sh = static_cast(shell)->getTopoShapePtr()->getShape(); TopoShape res = getShapeFix_FaceConnectPtr()->Build(TopoDS::Shell(sh), sewtoler, fixtoler); return res.getPyObject(); } -PyObject* ShapeFix_FaceConnectPy::clear(PyObject *args) +PyObject* ShapeFix_FaceConnectPy::clear(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_FaceConnectPtr()->Clear(); Py_Return; } -PyObject *ShapeFix_FaceConnectPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_FaceConnectPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FacePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_FacePyImp.cpp index 220760901c..c25a4792e0 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FacePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FacePyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_FacePy.h" @@ -43,7 +43,7 @@ std::string ShapeFix_FacePy::representation() const return ""; } -PyObject *ShapeFix_FacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_FacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_FacePy return new ShapeFix_FacePy(nullptr); @@ -56,7 +56,9 @@ int ShapeFix_FacePy::PyInit(PyObject* args, PyObject* /*kwds*/) if (PyArg_ParseTuple(args, "|O!", &TopoShapeFacePy::Type, &face)) { setHandle(new ShapeFix_Face()); if (face) { - getShapeFix_FacePtr()->Init(TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape())); + getShapeFix_FacePtr()->Init( + TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()) + ); } return 0; @@ -68,14 +70,18 @@ int ShapeFix_FacePy::PyInit(PyObject* args, PyObject* /*kwds*/) if (PyArg_ParseTuple(args, "O!d|O!", &GeometrySurfacePy::Type, &face, &prec, &PyBool_Type, &fwd)) { setHandle(new ShapeFix_Face()); if (face) { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(face)->getGeomSurfacePtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(face)->getGeomSurfacePtr()->handle() + ); getShapeFix_FacePtr()->Init(surf, prec, Base::asBoolean(fwd)); } return 0; } - PyErr_SetString(PyExc_TypeError, "Supported arguments are:\n" + PyErr_SetString( + PyExc_TypeError, + "Supported arguments are:\n" "-- Face\n" "-- Surface, Precision, [Forward=True}\n" " Precision is a Float\n" @@ -84,11 +90,13 @@ int ShapeFix_FacePy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -PyObject* ShapeFix_FacePy::init(PyObject *args) +PyObject* ShapeFix_FacePy::init(PyObject* args) { PyObject* face; if (PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { - getShapeFix_FacePtr()->Init(TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape())); + getShapeFix_FacePtr()->Init( + TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()) + ); Py_Return; } @@ -97,26 +105,31 @@ PyObject* ShapeFix_FacePy::init(PyObject *args) PyObject* fwd = Py_True; if (PyArg_ParseTuple(args, "O!d|O!", &GeometrySurfacePy::Type, &face, &prec, &PyBool_Type, &fwd)) { if (face) { - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(face)->getGeomSurfacePtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(face)->getGeomSurfacePtr()->handle() + ); getShapeFix_FacePtr()->Init(surf, prec, Base::asBoolean(fwd)); } Py_Return; } - PyErr_SetString(PyExc_TypeError, "Supported arguments are:\n" + PyErr_SetString( + PyExc_TypeError, + "Supported arguments are:\n" "-- Face\n" "-- Surface, Precision, [Forward=True}\n" " Precision is a Float\n" " If Forward is the orientation will be FORWARD or REVERSED otherwise" - ); + ); return nullptr; } -PyObject* ShapeFix_FacePy::fixWireTool(PyObject *args) +PyObject* ShapeFix_FacePy::fixWireTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Wire) tool = getShapeFix_FacePtr()->FixWireTool(); ShapeFix_WirePy* wire = new ShapeFix_WirePy(nullptr); @@ -124,66 +137,75 @@ PyObject* ShapeFix_FacePy::fixWireTool(PyObject *args) return wire; } -PyObject* ShapeFix_FacePy::clearModes(PyObject *args) +PyObject* ShapeFix_FacePy::clearModes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_FacePtr()->ClearModes(); Py_Return; } -PyObject* ShapeFix_FacePy::add(PyObject *args) +PyObject* ShapeFix_FacePy::add(PyObject* args) { PyObject* wire; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) { return nullptr; + } - getShapeFix_FacePtr()->Add(TopoDS::Wire(static_cast(wire)->getTopoShapePtr()->getShape())); + getShapeFix_FacePtr()->Add( + TopoDS::Wire(static_cast(wire)->getTopoShapePtr()->getShape()) + ); Py_Return; } -PyObject* ShapeFix_FacePy::fixOrientation(PyObject *args) +PyObject* ShapeFix_FacePy::fixOrientation(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixOrientation(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::fixAddNaturalBound(PyObject *args) +PyObject* ShapeFix_FacePy::fixAddNaturalBound(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixAddNaturalBound(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::fixMissingSeam(PyObject *args) +PyObject* ShapeFix_FacePy::fixMissingSeam(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixMissingSeam(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::fixSmallAreaWire(PyObject *args) +PyObject* ShapeFix_FacePy::fixSmallAreaWire(PyObject* args) { PyObject* removeSmall; - if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &removeSmall)) + if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &removeSmall)) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixSmallAreaWire(Base::asBoolean(removeSmall)); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::fixLoopWire(PyObject *args) +PyObject* ShapeFix_FacePy::fixLoopWire(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopTools_SequenceOfShape aResWires; Standard_Boolean ok = getShapeFix_FacePtr()->FixLoopWire(aResWires); @@ -195,55 +217,61 @@ PyObject* ShapeFix_FacePy::fixLoopWire(PyObject *args) return Py::new_reference_to(Py::TupleN(Py::Boolean(ok), list)); } -PyObject* ShapeFix_FacePy::fixIntersectingWires(PyObject *args) +PyObject* ShapeFix_FacePy::fixIntersectingWires(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixIntersectingWires(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::fixWiresTwoCoincidentEdges(PyObject *args) +PyObject* ShapeFix_FacePy::fixWiresTwoCoincidentEdges(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixWiresTwoCoincEdges(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::fixPeriodicDegenerated(PyObject *args) +PyObject* ShapeFix_FacePy::fixPeriodicDegenerated(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->FixPeriodicDegenerated(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::perform(PyObject *args) +PyObject* ShapeFix_FacePy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_FacePtr()->Perform(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FacePy::face(PyObject *args) +PyObject* ShapeFix_FacePy::face(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_FacePtr()->Face(); return shape.getPyObject(); } -PyObject* ShapeFix_FacePy::result(PyObject *args) +PyObject* ShapeFix_FacePy::result(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_FacePtr()->Result(); return shape.getPyObject(); @@ -359,7 +387,7 @@ void ShapeFix_FacePy::setFixPeriodicDegeneratedMode(Py::Boolean arg) getShapeFix_FacePtr()->FixPeriodicDegeneratedMode() = arg; } -PyObject *ShapeFix_FacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_FacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFace.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFace.pyi index a52039e695..8a5b45a32d 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFace.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFace.pyi @@ -7,7 +7,7 @@ from typing import Final, overload PythonName="Part.ShapeFix.FixSmallFace", Include="ShapeFix_FixSmallFace.hxx", FatherInclude="Mod/Part/App/ShapeFix/ShapeFix_RootPy.h", - Constructor=True + Constructor=True, ) class ShapeFix_FixSmallFace(ShapeFix_Root): """ diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFacePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFacePyImp.cpp index b5598fed0f..0e94307ac3 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFacePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallFacePyImp.cpp @@ -24,8 +24,8 @@ #include -# include -# include +#include +#include #include "ShapeFix/ShapeFix_FixSmallFacePy.h" @@ -40,7 +40,7 @@ std::string ShapeFix_FixSmallFacePy::representation() const return ""; } -PyObject *ShapeFix_FixSmallFacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_FixSmallFacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_FacePy return new ShapeFix_FixSmallFacePy(new ShapeFix_FixSmallFace); @@ -49,122 +49,146 @@ PyObject *ShapeFix_FixSmallFacePy::PyMake(struct _typeobject *, PyObject *, PyOb // constructor method int ShapeFix_FixSmallFacePy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_FixSmallFacePy::init(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::init(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } - getShapeFix_FixSmallFacePtr()->Init(static_cast(shape)->getTopoShapePtr()->getShape()); + getShapeFix_FixSmallFacePtr()->Init( + static_cast(shape)->getTopoShapePtr()->getShape() + ); Py_Return; } -PyObject* ShapeFix_FixSmallFacePy::perform(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_FixSmallFacePtr()->Perform(); Py_Return; } -PyObject* ShapeFix_FixSmallFacePy::fixSpotFace(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::fixSpotFace(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape sh = getShapeFix_FixSmallFacePtr()->FixSpotFace(); return sh.getPyObject(); } -PyObject* ShapeFix_FixSmallFacePy::replaceVerticesInCaseOfSpot(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::replaceVerticesInCaseOfSpot(PyObject* args) { PyObject* face; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { return nullptr; + } - TopoDS_Face shape = TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()); + TopoDS_Face shape = TopoDS::Face( + static_cast(face)->getTopoShapePtr()->getShape() + ); getShapeFix_FixSmallFacePtr()->ReplaceVerticesInCaseOfSpot(shape, 0.0); return TopoShape(shape).getPyObject(); } -PyObject* ShapeFix_FixSmallFacePy::removeFacesInCaseOfSpot(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::removeFacesInCaseOfSpot(PyObject* args) { PyObject* face; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { return nullptr; + } - TopoDS_Face shape = TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()); + TopoDS_Face shape = TopoDS::Face( + static_cast(face)->getTopoShapePtr()->getShape() + ); bool ok = getShapeFix_FixSmallFacePtr()->RemoveFacesInCaseOfSpot(shape); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FixSmallFacePy::fixStripFace(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::fixStripFace(PyObject* args) { PyObject* wasdone = Py_False; - if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &wasdone)) + if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &wasdone)) { return nullptr; + } TopoShape sh = getShapeFix_FixSmallFacePtr()->FixStripFace(Base::asBoolean(wasdone)); return sh.getPyObject(); } -PyObject* ShapeFix_FixSmallFacePy::removeFacesInCaseOfStrip(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::removeFacesInCaseOfStrip(PyObject* args) { PyObject* face; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { return nullptr; + } - TopoDS_Face shape = TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()); + TopoDS_Face shape = TopoDS::Face( + static_cast(face)->getTopoShapePtr()->getShape() + ); bool ok = getShapeFix_FixSmallFacePtr()->RemoveFacesInCaseOfStrip(shape); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_FixSmallFacePy::fixSplitFace(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::fixSplitFace(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } - TopoShape sh = getShapeFix_FixSmallFacePtr()->FixSplitFace(static_cast(shape)->getTopoShapePtr()->getShape()); + TopoShape sh = getShapeFix_FixSmallFacePtr()->FixSplitFace( + static_cast(shape)->getTopoShapePtr()->getShape() + ); return sh.getPyObject(); } -PyObject* ShapeFix_FixSmallFacePy::fixFace(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::fixFace(PyObject* args) { PyObject* face; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { return nullptr; + } - TopoDS_Face shape = TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()); + TopoDS_Face shape = TopoDS::Face( + static_cast(face)->getTopoShapePtr()->getShape() + ); TopoShape sh = getShapeFix_FixSmallFacePtr()->FixFace(shape); return sh.getPyObject(); } -PyObject* ShapeFix_FixSmallFacePy::fixShape(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::fixShape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_FixSmallFacePtr()->FixShape(); return shape.getPyObject(); } -PyObject* ShapeFix_FixSmallFacePy::shape(PyObject *args) +PyObject* ShapeFix_FixSmallFacePy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape sh = getShapeFix_FixSmallFacePtr()->Shape(); return sh.getPyObject(); } -PyObject *ShapeFix_FixSmallFacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_FixSmallFacePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallSolidPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallSolidPyImp.cpp index 77792c0de7..bf907e2804 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallSolidPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FixSmallSolidPyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_FixSmallSolidPy.h" @@ -39,7 +39,7 @@ std::string ShapeFix_FixSmallSolidPy::representation() const return ""; } -PyObject *ShapeFix_FixSmallSolidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_FixSmallSolidPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_FixSmallSolidPy(new ShapeFix_FixSmallSolid); } @@ -47,64 +47,76 @@ PyObject *ShapeFix_FixSmallSolidPy::PyMake(struct _typeobject *, PyObject *, PyO // constructor method int ShapeFix_FixSmallSolidPy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_FixSmallSolidPy::setFixMode(PyObject *args) +PyObject* ShapeFix_FixSmallSolidPy::setFixMode(PyObject* args) { int mode; - if (!PyArg_ParseTuple(args, "i", &mode)) + if (!PyArg_ParseTuple(args, "i", &mode)) { return nullptr; + } getShapeFix_FixSmallSolidPtr()->SetFixMode(mode); Py_Return; } -PyObject* ShapeFix_FixSmallSolidPy::setVolumeThreshold(PyObject *args) +PyObject* ShapeFix_FixSmallSolidPy::setVolumeThreshold(PyObject* args) { double value = -1.0; - if (!PyArg_ParseTuple(args, "|d", &value)) + if (!PyArg_ParseTuple(args, "|d", &value)) { return nullptr; + } getShapeFix_FixSmallSolidPtr()->SetVolumeThreshold(value); Py_Return; } -PyObject* ShapeFix_FixSmallSolidPy::setWidthFactorThreshold(PyObject *args) +PyObject* ShapeFix_FixSmallSolidPy::setWidthFactorThreshold(PyObject* args) { double value = -1.0; - if (!PyArg_ParseTuple(args, "|d", &value)) + if (!PyArg_ParseTuple(args, "|d", &value)) { return nullptr; + } getShapeFix_FixSmallSolidPtr()->SetWidthFactorThreshold(value); Py_Return; } -PyObject* ShapeFix_FixSmallSolidPy::remove(PyObject *args) +PyObject* ShapeFix_FixSmallSolidPy::remove(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } Handle(ShapeBuild_ReShape) context = new ShapeBuild_ReShape(); - TopoShape sh = getShapeFix_FixSmallSolidPtr()->Remove(static_cast(shape)->getTopoShapePtr()->getShape(), context); + TopoShape sh = getShapeFix_FixSmallSolidPtr()->Remove( + static_cast(shape)->getTopoShapePtr()->getShape(), + context + ); return sh.getPyObject(); } -PyObject* ShapeFix_FixSmallSolidPy::merge(PyObject *args) +PyObject* ShapeFix_FixSmallSolidPy::merge(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } Handle(ShapeBuild_ReShape) context = new ShapeBuild_ReShape(); - TopoShape sh = getShapeFix_FixSmallSolidPtr()->Merge(static_cast(shape)->getTopoShapePtr()->getShape(), context); + TopoShape sh = getShapeFix_FixSmallSolidPtr()->Merge( + static_cast(shape)->getTopoShapePtr()->getShape(), + context + ); return sh.getPyObject(); } -PyObject *ShapeFix_FixSmallSolidPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_FixSmallSolidPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBounds.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBounds.pyi index dee021db9f..f367b4a28b 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBounds.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBounds.pyi @@ -33,4 +33,4 @@ class ShapeFix_FreeBounds(PyObjectBase): """ Returns modified source shape """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBoundsPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBoundsPyImp.cpp index bb8e04874e..b315ef7d0b 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBoundsPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_FreeBoundsPyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_FreeBoundsPy.h" @@ -40,7 +40,7 @@ std::string ShapeFix_FreeBoundsPy::representation() const return ""; } -PyObject *ShapeFix_FreeBoundsPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_FreeBoundsPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_FreeBoundsPy(nullptr); } @@ -59,59 +59,91 @@ int ShapeFix_FreeBoundsPy::PyInit(PyObject* args, PyObject* /*kwds*/) PyObject* splitopen; double sewtoler; double closetoler; - if (PyArg_ParseTuple(args, "O!ddO!O!", &TopoShapePy::Type, &shape, &sewtoler, &closetoler, - &PyBool_Type, &splitclosed, &PyBool_Type, &splitopen)) { + if (PyArg_ParseTuple( + args, + "O!ddO!O!", + &TopoShapePy::Type, + &shape, + &sewtoler, + &closetoler, + &PyBool_Type, + &splitclosed, + &PyBool_Type, + &splitopen + )) { TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); - setTwinPointer(new ShapeFix_FreeBounds(sh, sewtoler, closetoler, - Base::asBoolean(splitclosed), - Base::asBoolean(splitopen))); + setTwinPointer(new ShapeFix_FreeBounds( + sh, + sewtoler, + closetoler, + Base::asBoolean(splitclosed), + Base::asBoolean(splitopen) + )); return 0; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!dO!O!", &TopoShapePy::Type, &shape, &closetoler, - &PyBool_Type, &splitclosed, &PyBool_Type, &splitopen)) { + if (PyArg_ParseTuple( + args, + "O!dO!O!", + &TopoShapePy::Type, + &shape, + &closetoler, + &PyBool_Type, + &splitclosed, + &PyBool_Type, + &splitopen + )) { TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); - setTwinPointer(new ShapeFix_FreeBounds(sh, closetoler, - Base::asBoolean(splitclosed), - Base::asBoolean(splitopen))); + setTwinPointer(new ShapeFix_FreeBounds( + sh, + closetoler, + Base::asBoolean(splitclosed), + Base::asBoolean(splitopen) + )); return 0; } - PyErr_SetString(PyExc_TypeError, "ShapeFix_FreeBounds()\n" - "ShapeFix_FreeBounds(shape, sewtolerance, closetolerance, splitClosed, splitOpen)\n" - "ShapeFix_FreeBounds(shape, closetolerance, splitClosed, splitOpen)"); + PyErr_SetString( + PyExc_TypeError, + "ShapeFix_FreeBounds()\n" + "ShapeFix_FreeBounds(shape, sewtolerance, closetolerance, splitClosed, splitOpen)\n" + "ShapeFix_FreeBounds(shape, closetolerance, splitClosed, splitOpen)" + ); return -1; } -PyObject* ShapeFix_FreeBoundsPy::closedWires(PyObject *args) +PyObject* ShapeFix_FreeBoundsPy::closedWires(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape comp = getShapeFix_FreeBoundsPtr()->GetClosedWires(); return comp.getPyObject(); } -PyObject* ShapeFix_FreeBoundsPy::openWires(PyObject *args) +PyObject* ShapeFix_FreeBoundsPy::openWires(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape comp = getShapeFix_FreeBoundsPtr()->GetOpenWires(); return comp.getPyObject(); } -PyObject* ShapeFix_FreeBoundsPy::shape(PyObject *args) +PyObject* ShapeFix_FreeBoundsPy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_FreeBoundsPtr()->GetShape(); return shape.getPyObject(); } -PyObject *ShapeFix_FreeBoundsPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_FreeBoundsPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_Root.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_Root.pyi index 2f9fd413c9..e5c67a64ea 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_Root.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_Root.pyi @@ -7,7 +7,8 @@ from typing import Final, overload Include="ShapeFix_Root.hxx", Constructor=True, ) -@class_declarations(""" +@class_declarations( + """ private: Handle(ShapeFix_Root) hRoot; @@ -16,7 +17,8 @@ public: setTwinPointer(handle.get()); hRoot = handle; } -""") +""" +) class ShapeFix_Root(PyObjectBase): """ Root class for fixing operations diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_RootPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_RootPyImp.cpp index 8d16fd4aa8..c8fe04c2ec 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_RootPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_RootPyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_RootPy.h" @@ -39,7 +39,7 @@ std::string ShapeFix_RootPy::representation() const return ""; } -PyObject *ShapeFix_RootPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_RootPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_RootPy return new ShapeFix_RootPy(nullptr); @@ -48,18 +48,20 @@ PyObject *ShapeFix_RootPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // constructor method int ShapeFix_RootPy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } setHandle(new ShapeFix_Root); return 0; } -PyObject* ShapeFix_RootPy::limitTolerance(PyObject *args) const +PyObject* ShapeFix_RootPy::limitTolerance(PyObject* args) const { double tol; - if (!PyArg_ParseTuple(args, "d", &tol)) + if (!PyArg_ParseTuple(args, "d", &tol)) { return nullptr; + } tol = getShapeFix_RootPtr()->LimitTolerance(tol); return Py::new_reference_to(Py::Float(tol)); @@ -95,7 +97,7 @@ void ShapeFix_RootPy::setMaxTolerance(Py::Float arg) getShapeFix_RootPtr()->SetMaxTolerance(arg); } -PyObject *ShapeFix_RootPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_RootPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_Shape.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_Shape.pyi index e66d193891..1940aae036 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_Shape.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_Shape.pyi @@ -3,7 +3,6 @@ from Part.App.ShapeFix.ShapeFix_Root import ShapeFix_Root from Part.TopoShape import TopoShape from typing import Final, overload - @export( PythonName="Part.ShapeFix.Shape", Include="ShapeFix_Shape.hxx", diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_ShapePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_ShapePyImp.cpp index 0ec2bb9add..f920b437b3 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_ShapePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_ShapePyImp.cpp @@ -42,7 +42,7 @@ std::string ShapeFix_ShapePy::representation() const return ""; } -PyObject *ShapeFix_ShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_ShapePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_ShapePy return new ShapeFix_ShapePy(nullptr); @@ -52,8 +52,9 @@ PyObject *ShapeFix_ShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) int ShapeFix_ShapePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &TopoShapePy::Type, &shape)) { return -1; + } setHandle(new ShapeFix_Shape); if (shape) { @@ -63,38 +64,42 @@ int ShapeFix_ShapePy::PyInit(PyObject* args, PyObject* /*kwds*/) return 0; } -PyObject* ShapeFix_ShapePy::init(PyObject *args) +PyObject* ShapeFix_ShapePy::init(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } getShapeFix_ShapePtr()->Init(static_cast(shape)->getTopoShapePtr()->getShape()); Py_Return; } -PyObject* ShapeFix_ShapePy::perform(PyObject *args) +PyObject* ShapeFix_ShapePy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_ShapePtr()->Perform(); return Py::new_reference_to(Py::Boolean(ok ? true : false)); } -PyObject* ShapeFix_ShapePy::shape(PyObject *args) +PyObject* ShapeFix_ShapePy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_ShapePtr()->Shape(); return shape.getPyObject(); } -PyObject* ShapeFix_ShapePy::fixSolidTool(PyObject *args) +PyObject* ShapeFix_ShapePy::fixSolidTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Solid) tool = getShapeFix_ShapePtr()->FixSolidTool(); ShapeFix_SolidPy* solid = new ShapeFix_SolidPy(nullptr); @@ -102,10 +107,11 @@ PyObject* ShapeFix_ShapePy::fixSolidTool(PyObject *args) return solid; } -PyObject* ShapeFix_ShapePy::fixShellTool(PyObject *args) +PyObject* ShapeFix_ShapePy::fixShellTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Shell) tool = getShapeFix_ShapePtr()->FixShellTool(); ShapeFix_ShellPy* shell = new ShapeFix_ShellPy(nullptr); @@ -113,10 +119,11 @@ PyObject* ShapeFix_ShapePy::fixShellTool(PyObject *args) return shell; } -PyObject* ShapeFix_ShapePy::fixFaceTool(PyObject *args) +PyObject* ShapeFix_ShapePy::fixFaceTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Face) tool = getShapeFix_ShapePtr()->FixFaceTool(); ShapeFix_FacePy* face = new ShapeFix_FacePy(nullptr); @@ -124,10 +131,11 @@ PyObject* ShapeFix_ShapePy::fixFaceTool(PyObject *args) return face; } -PyObject* ShapeFix_ShapePy::fixWireTool(PyObject *args) +PyObject* ShapeFix_ShapePy::fixWireTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Wire) tool = getShapeFix_ShapePtr()->FixWireTool(); ShapeFix_WirePy* wire = new ShapeFix_WirePy(nullptr); @@ -135,10 +143,11 @@ PyObject* ShapeFix_ShapePy::fixWireTool(PyObject *args) return wire; } -PyObject* ShapeFix_ShapePy::fixEdgeTool(PyObject *args) +PyObject* ShapeFix_ShapePy::fixEdgeTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Edge) tool = getShapeFix_ShapePtr()->FixEdgeTool(); ShapeFix_EdgePy* edge = new ShapeFix_EdgePy(nullptr); @@ -216,7 +225,7 @@ void ShapeFix_ShapePy::setFixVertexTolMode(Py::Boolean arg) getShapeFix_ShapePtr()->FixVertexTolMode() = arg; } -PyObject *ShapeFix_ShapePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_ShapePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerance.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerance.pyi index 8670b15b27..862aacee9b 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerance.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerance.pyi @@ -19,11 +19,13 @@ class ShapeFix_ShapeTolerance(PyObjectBase): @overload def limitTolerance(self, shape: TopoShape, tmin: float) -> None: ... - @overload - def limitTolerance(self, shape: TopoShape, tmin: float, tmax: float, ShapeEnum: str = None) -> None: ... - - def limitTolerance(self, shape: TopoShape, tmin: float, tmax: float = 0, ShapeEnum: str = None) -> None: + def limitTolerance( + self, shape: TopoShape, tmin: float, tmax: float, ShapeEnum: str = None + ) -> None: ... + def limitTolerance( + self, shape: TopoShape, tmin: float, tmax: float = 0, ShapeEnum: str = None + ) -> None: """ limitTolerance(shape, tmin, [tmax=0, ShapeEnum=SHAPE]) """ @@ -31,10 +33,8 @@ class ShapeFix_ShapeTolerance(PyObjectBase): @overload def setTolerance(self, shape: TopoShape, precision: float) -> None: ... - @overload def setTolerance(self, shape: TopoShape, precision: float, ShapeEnum: str = None) -> None: ... - def setTolerance(self, shape: TopoShape, precision: float, ShapeEnum: str = None) -> None: """ setTolerance(shape, precision, [ShapeEnum=SHAPE]) diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerancePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerancePyImp.cpp index b7bd39bb88..7e5ec4048c 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerancePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_ShapeTolerancePyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_ShapeTolerancePy.h" @@ -40,7 +40,7 @@ std::string ShapeFix_ShapeTolerancePy::representation() const return ""; } -PyObject *ShapeFix_ShapeTolerancePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_ShapeTolerancePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_ShapeTolerancePy(new ShapeFix_ShapeTolerance); } @@ -48,41 +48,42 @@ PyObject *ShapeFix_ShapeTolerancePy::PyMake(struct _typeobject *, PyObject *, Py // constructor method int ShapeFix_ShapeTolerancePy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_ShapeTolerancePy::limitTolerance(PyObject *args) +PyObject* ShapeFix_ShapeTolerancePy::limitTolerance(PyObject* args) { PyObject* shape; double tmin; double tmax = 0.0; TopAbs_ShapeEnum styp = TopAbs_SHAPE; - if (!PyArg_ParseTuple(args, "O!d|di", &TopoShapePy::Type, &shape, - &tmin, &tmax, &styp)) + if (!PyArg_ParseTuple(args, "O!d|di", &TopoShapePy::Type, &shape, &tmin, &tmax, &styp)) { return nullptr; + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); bool ok = getShapeFix_ShapeTolerancePtr()->LimitTolerance(sh, tmin, tmax, styp); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_ShapeTolerancePy::setTolerance(PyObject *args) +PyObject* ShapeFix_ShapeTolerancePy::setTolerance(PyObject* args) { PyObject* shape; double prec; TopAbs_ShapeEnum styp = TopAbs_SHAPE; - if (!PyArg_ParseTuple(args, "O!d|i", &TopoShapePy::Type, &shape, - &prec, &styp)) + if (!PyArg_ParseTuple(args, "O!d|i", &TopoShapePy::Type, &shape, &prec, &styp)) { return nullptr; + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); getShapeFix_ShapeTolerancePtr()->SetTolerance(sh, prec, styp); Py_Return; } -PyObject *ShapeFix_ShapeTolerancePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_ShapeTolerancePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_Shell.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_Shell.pyi index 84d04b2195..04160e2675 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_Shell.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_Shell.pyi @@ -89,4 +89,4 @@ class ShapeFix_Shell(ShapeFix_Root): """ Sets NonManifold flag """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPyImp.cpp index d53bbd8c08..8c9c5025e7 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_ShellPy.h" @@ -41,7 +41,7 @@ std::string ShapeFix_ShellPy::representation() const return ""; } -PyObject *ShapeFix_ShellPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_ShellPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_RootPy return new ShapeFix_ShellPy(nullptr); @@ -51,31 +51,38 @@ PyObject *ShapeFix_ShellPy::PyMake(struct _typeobject *, PyObject *, PyObject *) int ShapeFix_ShellPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* shell = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &TopoShapeShellPy::Type, &shell)) + if (!PyArg_ParseTuple(args, "|O!", &TopoShapeShellPy::Type, &shell)) { return -1; + } setHandle(new ShapeFix_Shell); if (shell) { - getShapeFix_ShellPtr()->Init(TopoDS::Shell(static_cast(shell)->getTopoShapePtr()->getShape())); + getShapeFix_ShellPtr()->Init( + TopoDS::Shell(static_cast(shell)->getTopoShapePtr()->getShape()) + ); } return 0; } -PyObject* ShapeFix_ShellPy::init(PyObject *args) +PyObject* ShapeFix_ShellPy::init(PyObject* args) { PyObject* shell; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeShellPy::Type, &shell)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeShellPy::Type, &shell)) { return nullptr; + } - getShapeFix_ShellPtr()->Init(TopoDS::Shell(static_cast(shell)->getTopoShapePtr()->getShape())); + getShapeFix_ShellPtr()->Init( + TopoDS::Shell(static_cast(shell)->getTopoShapePtr()->getShape()) + ); Py_Return; } -PyObject* ShapeFix_ShellPy::fixFaceTool(PyObject *args) +PyObject* ShapeFix_ShellPy::fixFaceTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Face) tool = getShapeFix_ShellPtr()->FixFaceTool(); ShapeFix_FacePy* face = new ShapeFix_FacePy(nullptr); @@ -83,71 +90,88 @@ PyObject* ShapeFix_ShellPy::fixFaceTool(PyObject *args) return face; } -PyObject* ShapeFix_ShellPy::perform(PyObject *args) +PyObject* ShapeFix_ShellPy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_ShellPtr()->Perform(); return Py::new_reference_to(Py::Boolean(ok ? true : false)); } -PyObject* ShapeFix_ShellPy::shell(PyObject *args) +PyObject* ShapeFix_ShellPy::shell(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_ShellPtr()->Shell(); return shape.getPyObject(); } -PyObject* ShapeFix_ShellPy::numberOfShells(PyObject *args) +PyObject* ShapeFix_ShellPy::numberOfShells(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = getShapeFix_ShellPtr()->NbShells(); return Py::new_reference_to(Py::Long(num)); } -PyObject* ShapeFix_ShellPy::shape(PyObject *args) +PyObject* ShapeFix_ShellPy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_ShellPtr()->Shape(); return shape.getPyObject(); } -PyObject* ShapeFix_ShellPy::errorFaces(PyObject *args) +PyObject* ShapeFix_ShellPy::errorFaces(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_ShellPtr()->ErrorFaces(); return shape.getPyObject(); } -PyObject* ShapeFix_ShellPy::fixFaceOrientation(PyObject *args) +PyObject* ShapeFix_ShellPy::fixFaceOrientation(PyObject* args) { PyObject* shell; PyObject* multiConex = Py_True; PyObject* nonManifold = Py_False; - if (!PyArg_ParseTuple(args, "O!|O!O!", &TopoShapeShellPy::Type, &shell, - &PyBool_Type, &multiConex, - &PyBool_Type, &nonManifold)) + if (!PyArg_ParseTuple( + args, + "O!|O!O!", + &TopoShapeShellPy::Type, + &shell, + &PyBool_Type, + &multiConex, + &PyBool_Type, + &nonManifold + )) { return nullptr; + } - bool ok = getShapeFix_ShellPtr()->FixFaceOrientation(TopoDS::Shell(static_cast(shell)->getTopoShapePtr()->getShape()), - Base::asBoolean(multiConex), Base::asBoolean(nonManifold)); + bool ok = getShapeFix_ShellPtr()->FixFaceOrientation( + TopoDS::Shell(static_cast(shell)->getTopoShapePtr()->getShape()), + Base::asBoolean(multiConex), + Base::asBoolean(nonManifold) + ); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_ShellPy::setNonManifoldFlag(PyObject *args) +PyObject* ShapeFix_ShellPy::setNonManifoldFlag(PyObject* args) { PyObject* nonManifold; - if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &nonManifold)) + if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &nonManifold)) { return nullptr; + } getShapeFix_ShellPtr()->SetNonManifoldFlag(Base::asBoolean(nonManifold)); Py_Return; @@ -173,7 +197,7 @@ void ShapeFix_ShellPy::setFixOrientationMode(Py::Boolean arg) getShapeFix_ShellPtr()->FixOrientationMode() = arg; } -PyObject *ShapeFix_ShellPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_ShellPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_SolidPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_SolidPyImp.cpp index 5b89056c9b..6acfdb9019 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_SolidPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_SolidPyImp.cpp @@ -24,10 +24,10 @@ #include -# include -# include -# include -# include +#include +#include +#include +#include #include "ShapeFix/ShapeFix_SolidPy.h" #include "ShapeFix/ShapeFix_SolidPy.cpp" @@ -44,7 +44,7 @@ std::string ShapeFix_SolidPy::representation() const return ""; } -PyObject *ShapeFix_SolidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_SolidPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ShapeFix_SolidPy return new ShapeFix_SolidPy(nullptr); @@ -54,69 +54,80 @@ PyObject *ShapeFix_SolidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) int ShapeFix_SolidPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* solid = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &TopoShapeSolidPy::Type, &solid)) + if (!PyArg_ParseTuple(args, "|O!", &TopoShapeSolidPy::Type, &solid)) { return -1; + } setHandle(new ShapeFix_Solid); if (solid) { - getShapeFix_SolidPtr()->Init(TopoDS::Solid(static_cast(solid)->getTopoShapePtr()->getShape())); + getShapeFix_SolidPtr()->Init( + TopoDS::Solid(static_cast(solid)->getTopoShapePtr()->getShape()) + ); } return 0; } -PyObject* ShapeFix_SolidPy::init(PyObject *args) +PyObject* ShapeFix_SolidPy::init(PyObject* args) { PyObject* solid; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeSolidPy::Type, &solid)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeSolidPy::Type, &solid)) { return nullptr; + } - getShapeFix_SolidPtr()->Init(TopoDS::Solid(static_cast(solid)->getTopoShapePtr()->getShape())); + getShapeFix_SolidPtr()->Init( + TopoDS::Solid(static_cast(solid)->getTopoShapePtr()->getShape()) + ); Py_Return; } -PyObject* ShapeFix_SolidPy::perform(PyObject *args) +PyObject* ShapeFix_SolidPy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_SolidPtr()->Perform(); return Py::new_reference_to(Py::Boolean(ok ? true : false)); } -PyObject* ShapeFix_SolidPy::solidFromShell(PyObject *args) +PyObject* ShapeFix_SolidPy::solidFromShell(PyObject* args) { PyObject* shell; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeShellPy::Type, &shell)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeShellPy::Type, &shell)) { return nullptr; + } TopoDS_Shape shape = static_cast(shell)->getTopoShapePtr()->getShape(); TopoShape solid = getShapeFix_SolidPtr()->SolidFromShell(TopoDS::Shell(shape)); return solid.getPyObject(); } -PyObject* ShapeFix_SolidPy::solid(PyObject *args) +PyObject* ShapeFix_SolidPy::solid(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_SolidPtr()->Solid(); return shape.getPyObject(); } -PyObject* ShapeFix_SolidPy::shape(PyObject *args) +PyObject* ShapeFix_SolidPy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_SolidPtr()->Shape(); return shape.getPyObject(); } -PyObject* ShapeFix_SolidPy::fixShellTool(PyObject *args) +PyObject* ShapeFix_SolidPy::fixShellTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Shell) tool = getShapeFix_SolidPtr()->FixShellTool(); ShapeFix_ShellPy* shell = new ShapeFix_ShellPy(nullptr); @@ -154,7 +165,7 @@ void ShapeFix_SolidPy::setCreateOpenSolidMode(Py::Boolean arg) getShapeFix_SolidPtr()->CreateOpenSolidMode() = arg; } -PyObject *ShapeFix_SolidPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_SolidPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_SplitCommonVertexPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_SplitCommonVertexPyImp.cpp index 1d4f47b05d..bbd5bb23eb 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_SplitCommonVertexPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_SplitCommonVertexPyImp.cpp @@ -37,7 +37,8 @@ std::string ShapeFix_SplitCommonVertexPy::representation() const return ""; } -PyObject *ShapeFix_SplitCommonVertexPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_SplitCommonVertexPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python + // wrapper { // create a new instance of ShapeFix_ShapePy return new ShapeFix_SplitCommonVertexPy(nullptr); @@ -47,46 +48,54 @@ PyObject *ShapeFix_SplitCommonVertexPy::PyMake(struct _typeobject *, PyObject *, int ShapeFix_SplitCommonVertexPy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &TopoShapePy::Type, &shape)) { return -1; + } setHandle(new ShapeFix_SplitCommonVertex); if (shape) { - getShapeFix_SplitCommonVertexPtr()->Init(static_cast(shape)->getTopoShapePtr()->getShape()); + getShapeFix_SplitCommonVertexPtr()->Init( + static_cast(shape)->getTopoShapePtr()->getShape() + ); } return 0; } -PyObject* ShapeFix_SplitCommonVertexPy::init(PyObject *args) +PyObject* ShapeFix_SplitCommonVertexPy::init(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } - getShapeFix_SplitCommonVertexPtr()->Init(static_cast(shape)->getTopoShapePtr()->getShape()); + getShapeFix_SplitCommonVertexPtr()->Init( + static_cast(shape)->getTopoShapePtr()->getShape() + ); Py_Return; } -PyObject* ShapeFix_SplitCommonVertexPy::perform(PyObject *args) +PyObject* ShapeFix_SplitCommonVertexPy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_SplitCommonVertexPtr()->Perform(); Py_Return; } -PyObject* ShapeFix_SplitCommonVertexPy::shape(PyObject *args) +PyObject* ShapeFix_SplitCommonVertexPy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape shape = getShapeFix_SplitCommonVertexPtr()->Shape(); return shape.getPyObject(); } -PyObject *ShapeFix_SplitCommonVertexPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_SplitCommonVertexPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_SplitTool.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_SplitTool.pyi index bd7c0896df..6f2d9e6ba7 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_SplitTool.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_SplitTool.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from Base.PyObjectBase import PyObjectBase from typing import overload - @export( PythonName="Part.ShapeFix.SplitTool", Include="ShapeFix_SplitTool.hxx", @@ -28,4 +27,4 @@ class ShapeFix_SplitTool(PyObjectBase): """ Cut edge by parameters pend and cut """ - ... \ No newline at end of file + ... diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_SplitToolPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_SplitToolPyImp.cpp index 29ed2fd9f5..7f0079f0ac 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_SplitToolPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_SplitToolPyImp.cpp @@ -24,8 +24,8 @@ #include -# include -# include +#include +#include #include "ShapeFix/ShapeFix_SplitToolPy.h" @@ -43,7 +43,7 @@ std::string ShapeFix_SplitToolPy::representation() const return ""; } -PyObject *ShapeFix_SplitToolPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_SplitToolPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_SplitToolPy(new ShapeFix_SplitTool); } @@ -51,12 +51,13 @@ PyObject *ShapeFix_SplitToolPy::PyMake(struct _typeobject *, PyObject *, PyObjec // constructor method int ShapeFix_SplitToolPy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (PyArg_ParseTuple(args, "")) + if (PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_SplitToolPy::splitEdge(PyObject *args) +PyObject* ShapeFix_SplitToolPy::splitEdge(PyObject* args) { TopoDS_Edge e1, e2; bool ok = false; @@ -69,37 +70,76 @@ PyObject* ShapeFix_SplitToolPy::splitEdge(PyObject *args) double tol3d; double tol2d; - if (PyArg_ParseTuple(args, "O!dO!O!dd", &TopoShapeEdgePy::Type, &edge, ¶m1, - &TopoShapeVertexPy::Type, &vert, - &TopoShapeFacePy::Type, &face, - &tol3d, &tol2d)) { + if (PyArg_ParseTuple( + args, + "O!dO!O!dd", + &TopoShapeEdgePy::Type, + &edge, + ¶m1, + &TopoShapeVertexPy::Type, + &vert, + &TopoShapeFacePy::Type, + &face, + &tol3d, + &tol2d + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape v = static_cast(vert)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); - ok = getShapeFix_SplitToolPtr()->SplitEdge(TopoDS::Edge(e), param1, TopoDS::Vertex(v), TopoDS::Face(f), e1, e2, tol3d, tol2d); + ok = getShapeFix_SplitToolPtr()->SplitEdge( + TopoDS::Edge(e), + param1, + TopoDS::Vertex(v), + TopoDS::Face(f), + e1, + e2, + tol3d, + tol2d + ); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!ddO!O!dd", &TopoShapeEdgePy::Type, &edge, - ¶m1, ¶m2, - &TopoShapeVertexPy::Type, &vert, - &TopoShapeFacePy::Type, &face, - &tol3d, &tol2d)) { + if (PyArg_ParseTuple( + args, + "O!ddO!O!dd", + &TopoShapeEdgePy::Type, + &edge, + ¶m1, + ¶m2, + &TopoShapeVertexPy::Type, + &vert, + &TopoShapeFacePy::Type, + &face, + &tol3d, + &tol2d + )) { TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape v = static_cast(vert)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); - ok = getShapeFix_SplitToolPtr()->SplitEdge(TopoDS::Edge(e), param1, param2, TopoDS::Vertex(v), TopoDS::Face(f), e1, e2, tol3d, tol2d); + ok = getShapeFix_SplitToolPtr()->SplitEdge( + TopoDS::Edge(e), + param1, + param2, + TopoDS::Vertex(v), + TopoDS::Face(f), + e1, + e2, + tol3d, + tol2d + ); break; } - PyErr_SetString(PyExc_TypeError, "splitEdge(edge, param, vertex, face, tol3d, tol2d)\n" - "splitEdge(edge, param1, param2, vertex, face, tol3d, tol2d)"); + PyErr_SetString( + PyExc_TypeError, + "splitEdge(edge, param, vertex, face, tol3d, tol2d)\n" + "splitEdge(edge, param1, param2, vertex, face, tol3d, tol2d)" + ); return nullptr; - } - while(false); + } while (false); Py::Tuple tuple(2); if (ok && !e1.IsNull() && !e2.IsNull()) { @@ -107,27 +147,36 @@ PyObject* ShapeFix_SplitToolPy::splitEdge(PyObject *args) tuple.setItem(1, Py::asObject(TopoShape(e2).getPyObject())); } return Py::new_reference_to(tuple); - } -PyObject* ShapeFix_SplitToolPy::cutEdge(PyObject *args) +PyObject* ShapeFix_SplitToolPy::cutEdge(PyObject* args) { PyObject* edge; PyObject* face; double pend; double cut; - if (!PyArg_ParseTuple(args, "O!ddO!", &TopoShapeEdgePy::Type, &edge, &pend, &cut, - &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple( + args, + "O!ddO!", + &TopoShapeEdgePy::Type, + &edge, + &pend, + &cut, + &TopoShapeFacePy::Type, + &face + )) { return nullptr; + } TopoDS_Shape e = static_cast(edge)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); Standard_Boolean iscutline; - bool ok = getShapeFix_SplitToolPtr()->CutEdge(TopoDS::Edge(e), pend, cut, TopoDS::Face(f), iscutline); + bool ok + = getShapeFix_SplitToolPtr()->CutEdge(TopoDS::Edge(e), pend, cut, TopoDS::Face(f), iscutline); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject *ShapeFix_SplitToolPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_SplitToolPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_Wire.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_Wire.pyi index 75dcf7c8de..90cede9115 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_Wire.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_Wire.pyi @@ -226,7 +226,6 @@ class ShapeFix_Wire(ShapeFix_Root): This method examines the geometry and applies corrective actions to eliminate or reduce the presence of tails. """ pass - ModifyTopologyMode: bool = ... """Mode for modifying topology of the wire""" diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_WirePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_WirePyImp.cpp index 419c0c058e..3ba3ef2de6 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_WirePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_WirePyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include @@ -47,7 +47,7 @@ std::string ShapeFix_WirePy::representation() const return ""; } -PyObject *ShapeFix_WirePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_WirePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_WirePy(nullptr); } @@ -65,8 +65,7 @@ int ShapeFix_WirePy::PyInit(PyObject* args, PyObject* /*kwds*/) PyObject* wire; PyObject* face; double prec; - if (PyArg_ParseTuple(args, "O!O!d", &TopoShapeWirePy::Type, &wire, - &TopoShapeFacePy::Type, &face, &prec)) { + if (PyArg_ParseTuple(args, "O!O!d", &TopoShapeWirePy::Type, &wire, &TopoShapeFacePy::Type, &face, &prec)) { setHandle(new ShapeFix_Wire); TopoDS_Shape w = static_cast(wire)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); @@ -75,21 +74,23 @@ int ShapeFix_WirePy::PyInit(PyObject* args, PyObject* /*kwds*/) return 0; } - PyErr_SetString(PyExc_TypeError, "Supported arguments are:\n" + PyErr_SetString( + PyExc_TypeError, + "Supported arguments are:\n" "-- Empty\n" "-- Wire, Face, Precision" ); return -1; } -PyObject* ShapeFix_WirePy::init(PyObject *args) +PyObject* ShapeFix_WirePy::init(PyObject* args) { PyObject* wire; PyObject* face; double prec; - if (!PyArg_ParseTuple(args, "O!O!d", &TopoShapeWirePy::Type, &wire, - &TopoShapeFacePy::Type, &face, &prec)) + if (!PyArg_ParseTuple(args, "O!O!d", &TopoShapeWirePy::Type, &wire, &TopoShapeFacePy::Type, &face, &prec)) { return nullptr; + } TopoDS_Shape w = static_cast(wire)->getTopoShapePtr()->getShape(); TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); @@ -98,10 +99,11 @@ PyObject* ShapeFix_WirePy::init(PyObject *args) Py_Return; } -PyObject* ShapeFix_WirePy::fixEdgeTool(PyObject *args) +PyObject* ShapeFix_WirePy::fixEdgeTool(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Handle(ShapeFix_Edge) tool = getShapeFix_WirePtr()->FixEdgeTool(); ShapeFix_EdgePy* edge = new ShapeFix_EdgePy(nullptr); @@ -109,55 +111,61 @@ PyObject* ShapeFix_WirePy::fixEdgeTool(PyObject *args) return edge; } -PyObject* ShapeFix_WirePy::clearModes(PyObject *args) +PyObject* ShapeFix_WirePy::clearModes(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_WirePtr()->ClearModes(); Py_Return; } -PyObject* ShapeFix_WirePy::clearStatuses(PyObject *args) +PyObject* ShapeFix_WirePy::clearStatuses(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_WirePtr()->ClearStatuses(); Py_Return; } -PyObject* ShapeFix_WirePy::load(PyObject *args) +PyObject* ShapeFix_WirePy::load(PyObject* args) { PyObject* wire; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) { return nullptr; + } TopoDS_Shape w = static_cast(wire)->getTopoShapePtr()->getShape(); getShapeFix_WirePtr()->Load(TopoDS::Wire(w)); Py_Return; } -PyObject* ShapeFix_WirePy::setFace(PyObject *args) +PyObject* ShapeFix_WirePy::setFace(PyObject* args) { PyObject* face; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { return nullptr; + } TopoDS_Shape f = static_cast(face)->getTopoShapePtr()->getShape(); getShapeFix_WirePtr()->SetFace(TopoDS::Face(f)); Py_Return; } -PyObject* ShapeFix_WirePy::setSurface(PyObject *args) +PyObject* ShapeFix_WirePy::setSurface(PyObject* args) { PyObject* surface; PyObject* plm = nullptr; - if (!PyArg_ParseTuple(args, "O!|O!", &GeometrySurfacePy::Type, &surface, - &Base::PlacementPy::Type, &plm)) + if (!PyArg_ParseTuple(args, "O!|O!", &GeometrySurfacePy::Type, &surface, &Base::PlacementPy::Type, &plm)) { return nullptr; + } - Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast(static_cast(surface)->getGeomSurfacePtr()->handle()); + Handle(Geom_Surface) surf = Handle(Geom_Surface)::DownCast( + static_cast(surface)->getGeomSurfacePtr()->handle() + ); if (plm) { Base::Placement* pm = static_cast(plm)->getPlacementPtr(); TopLoc_Location loc = Tools::fromPlacement(*pm); @@ -169,99 +177,109 @@ PyObject* ShapeFix_WirePy::setSurface(PyObject *args) Py_Return; } -PyObject* ShapeFix_WirePy::setMaxTailAngle(PyObject *args) +PyObject* ShapeFix_WirePy::setMaxTailAngle(PyObject* args) { double angle; - if (!PyArg_ParseTuple(args, "d", &angle)) + if (!PyArg_ParseTuple(args, "d", &angle)) { return nullptr; + } getShapeFix_WirePtr()->SetMaxTailAngle(angle); Py_Return; } -PyObject* ShapeFix_WirePy::setMaxTailWidth(PyObject *args) +PyObject* ShapeFix_WirePy::setMaxTailWidth(PyObject* args) { double width; - if (!PyArg_ParseTuple(args, "d", &width)) + if (!PyArg_ParseTuple(args, "d", &width)) { return nullptr; + } getShapeFix_WirePtr()->SetMaxTailWidth(width); Py_Return; } -PyObject* ShapeFix_WirePy::isLoaded(PyObject *args) +PyObject* ShapeFix_WirePy::isLoaded(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->IsLoaded(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::isReady(PyObject *args) +PyObject* ShapeFix_WirePy::isReady(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->IsReady(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::numberOfEdges(PyObject *args) +PyObject* ShapeFix_WirePy::numberOfEdges(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = getShapeFix_WirePtr()->NbEdges(); return Py::new_reference_to(Py::Long(num)); } -PyObject* ShapeFix_WirePy::wire(PyObject *args) +PyObject* ShapeFix_WirePy::wire(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape wire = getShapeFix_WirePtr()->Wire(); return wire.getPyObject(); } -PyObject* ShapeFix_WirePy::wireAPIMake(PyObject *args) +PyObject* ShapeFix_WirePy::wireAPIMake(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape wire = getShapeFix_WirePtr()->WireAPIMake(); return wire.getPyObject(); } -PyObject* ShapeFix_WirePy::face(PyObject *args) +PyObject* ShapeFix_WirePy::face(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape face = getShapeFix_WirePtr()->Face(); return face.getPyObject(); } -PyObject* ShapeFix_WirePy::perform(PyObject *args) +PyObject* ShapeFix_WirePy::perform(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->Perform(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixReorder(PyObject *args) +PyObject* ShapeFix_WirePy::fixReorder(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixReorder(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixSmall(PyObject *args) +PyObject* ShapeFix_WirePy::fixSmall(PyObject* args) { PyObject* lock; double prec = 0.0; @@ -289,13 +307,16 @@ PyObject* ShapeFix_WirePy::fixSmall(PyObject *args) } } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- fixSmall(bool, [float]) or\n" - "-- fixSmall(int, bool, float)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- fixSmall(bool, [float]) or\n" + "-- fixSmall(int, bool, float)" + ); return nullptr; } -PyObject* ShapeFix_WirePy::fixConnected(PyObject *args) +PyObject* ShapeFix_WirePy::fixConnected(PyObject* args) { double prec = -1.0; if (PyArg_ParseTuple(args, "|d", &prec)) { @@ -322,26 +343,31 @@ PyObject* ShapeFix_WirePy::fixConnected(PyObject *args) } } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- fixConnected([float]) or\n" - "-- fixConnected(int, float)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- fixConnected([float]) or\n" + "-- fixConnected(int, float)" + ); return nullptr; } -PyObject* ShapeFix_WirePy::fixEdgeCurves(PyObject *args) +PyObject* ShapeFix_WirePy::fixEdgeCurves(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixEdgeCurves(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixDegenerated(PyObject *args) +PyObject* ShapeFix_WirePy::fixDegenerated(PyObject* args) { int num = -1; - if (!PyArg_ParseTuple(args, "|i", &num)) + if (!PyArg_ParseTuple(args, "|i", &num)) { return nullptr; + } try { Standard_Boolean ok = num > -1 ? getShapeFix_WirePtr()->FixDegenerated(num) @@ -354,16 +380,17 @@ PyObject* ShapeFix_WirePy::fixDegenerated(PyObject *args) } } -PyObject* ShapeFix_WirePy::fixSelfIntersection(PyObject *args) +PyObject* ShapeFix_WirePy::fixSelfIntersection(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixSelfIntersection(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixLacking(PyObject *args) +PyObject* ShapeFix_WirePy::fixLacking(PyObject* args) { PyObject* force = Py_False; if (PyArg_ParseTuple(args, "|O!", &PyBool_Type, &force)) { @@ -391,46 +418,53 @@ PyObject* ShapeFix_WirePy::fixLacking(PyObject *args) } } - PyErr_SetString(PyExc_TypeError, "Arguments must be:\n" - "-- fixLacking([bool=False]) or\n" - "-- fixLacking(int, bool)"); + PyErr_SetString( + PyExc_TypeError, + "Arguments must be:\n" + "-- fixLacking([bool=False]) or\n" + "-- fixLacking(int, bool)" + ); return nullptr; } -PyObject* ShapeFix_WirePy::fixClosed(PyObject *args) +PyObject* ShapeFix_WirePy::fixClosed(PyObject* args) { double prec = -1.0; - if (!PyArg_ParseTuple(args, "|d", &prec)) + if (!PyArg_ParseTuple(args, "|d", &prec)) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixClosed(prec); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixGaps3d(PyObject *args) +PyObject* ShapeFix_WirePy::fixGaps3d(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixGaps3d(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixGaps2d(PyObject *args) +PyObject* ShapeFix_WirePy::fixGaps2d(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixGaps2d(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixGap3d(PyObject *args) +PyObject* ShapeFix_WirePy::fixGap3d(PyObject* args) { int num; PyObject* convert; - if (!PyArg_ParseTuple(args, "iO!", &num, &PyBool_Type, &convert)) + if (!PyArg_ParseTuple(args, "iO!", &num, &PyBool_Type, &convert)) { return nullptr; + } try { Standard_Boolean ok = getShapeFix_WirePtr()->FixGap3d(num, Base::asBoolean(convert)); @@ -442,12 +476,13 @@ PyObject* ShapeFix_WirePy::fixGap3d(PyObject *args) } } -PyObject* ShapeFix_WirePy::fixGap2d(PyObject *args) +PyObject* ShapeFix_WirePy::fixGap2d(PyObject* args) { int num; PyObject* convert; - if (!PyArg_ParseTuple(args, "iO!", &num, &PyBool_Type, &convert)) + if (!PyArg_ParseTuple(args, "iO!", &num, &PyBool_Type, &convert)) { return nullptr; + } try { Standard_Boolean ok = getShapeFix_WirePtr()->FixGap2d(num, Base::asBoolean(convert)); @@ -459,11 +494,12 @@ PyObject* ShapeFix_WirePy::fixGap2d(PyObject *args) } } -PyObject* ShapeFix_WirePy::fixSeam(PyObject *args) +PyObject* ShapeFix_WirePy::fixSeam(PyObject* args) { int num; - if (!PyArg_ParseTuple(args, "i", &num)) + if (!PyArg_ParseTuple(args, "i", &num)) { return nullptr; + } try { Standard_Boolean ok = getShapeFix_WirePtr()->FixSeam(num); @@ -475,28 +511,31 @@ PyObject* ShapeFix_WirePy::fixSeam(PyObject *args) } } -PyObject* ShapeFix_WirePy::fixShifted(PyObject *args) +PyObject* ShapeFix_WirePy::fixShifted(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixShifted(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixNotchedEdges(PyObject *args) +PyObject* ShapeFix_WirePy::fixNotchedEdges(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixNotchedEdges(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WirePy::fixTails(PyObject *args) +PyObject* ShapeFix_WirePy::fixTails(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } Standard_Boolean ok = getShapeFix_WirePtr()->FixTails(); return Py::new_reference_to(Py::Boolean(ok)); @@ -792,7 +831,7 @@ void ShapeFix_WirePy::setFixTailMode(Py::Boolean arg) getShapeFix_WirePtr()->FixTailMode() = arg; } -PyObject *ShapeFix_WirePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_WirePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_WireVertexPyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_WireVertexPyImp.cpp index 16f3d7261b..e50799420e 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_WireVertexPyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_WireVertexPyImp.cpp @@ -24,7 +24,7 @@ #include -# include +#include #include "ShapeFix/ShapeFix_WireVertexPy.h" @@ -40,7 +40,7 @@ std::string ShapeFix_WireVertexPy::representation() const return ""; } -PyObject *ShapeFix_WireVertexPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_WireVertexPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_WireVertexPy(new ShapeFix_WireVertex); } @@ -48,52 +48,57 @@ PyObject *ShapeFix_WireVertexPy::PyMake(struct _typeobject *, PyObject *, PyObje // constructor method int ShapeFix_WireVertexPy::PyInit(PyObject* args, PyObject* /*kwds*/) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return -1; + } return 0; } -PyObject* ShapeFix_WireVertexPy::init(PyObject *args) +PyObject* ShapeFix_WireVertexPy::init(PyObject* args) { PyObject* shape; double prec; - if (!PyArg_ParseTuple(args, "O!d", &TopoShapeWirePy::Type, &shape, &prec)) + if (!PyArg_ParseTuple(args, "O!d", &TopoShapeWirePy::Type, &shape, &prec)) { return nullptr; + } TopoDS_Shape sh = static_cast(shape)->getTopoShapePtr()->getShape(); getShapeFix_WireVertexPtr()->Init(TopoDS::Wire(sh), prec); Py_Return; } -PyObject* ShapeFix_WireVertexPy::wire(PyObject *args) +PyObject* ShapeFix_WireVertexPy::wire(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape w = getShapeFix_WireVertexPtr()->Wire(); return w.getPyObject(); } -PyObject* ShapeFix_WireVertexPy::fixSame(PyObject *args) +PyObject* ShapeFix_WireVertexPy::fixSame(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = getShapeFix_WireVertexPtr()->FixSame(); return Py::new_reference_to(Py::Long(num)); } -PyObject* ShapeFix_WireVertexPy::fix(PyObject *args) +PyObject* ShapeFix_WireVertexPy::fix(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } int num = getShapeFix_WireVertexPtr()->Fix(); return Py::new_reference_to(Py::Long(num)); } -PyObject *ShapeFix_WireVertexPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_WireVertexPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_Wireframe.pyi b/src/Mod/Part/App/ShapeFix/ShapeFix_Wireframe.pyi index ca9bbbf09c..c6383e7c47 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_Wireframe.pyi +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_Wireframe.pyi @@ -48,5 +48,4 @@ class ShapeFix_Wireframe(ShapeFix_Root): """ ... - def shape(self) -> None: - ... + def shape(self) -> None: ... diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_WireframePyImp.cpp b/src/Mod/Part/App/ShapeFix/ShapeFix_WireframePyImp.cpp index be9649a1fb..e015e3ab65 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_WireframePyImp.cpp +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_WireframePyImp.cpp @@ -36,7 +36,7 @@ std::string ShapeFix_WireframePy::representation() const return ""; } -PyObject *ShapeFix_WireframePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ShapeFix_WireframePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { return new ShapeFix_WireframePy(nullptr); } @@ -45,11 +45,14 @@ PyObject *ShapeFix_WireframePy::PyMake(struct _typeobject *, PyObject *, PyObjec int ShapeFix_WireframePy::PyInit(PyObject* args, PyObject* /*kwds*/) { PyObject* shape = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "|O!", &TopoShapePy::Type, &shape)) { return -1; + } if (shape) { - setHandle(new ShapeFix_Wireframe(static_cast(shape)->getTopoShapePtr()->getShape())); + setHandle( + new ShapeFix_Wireframe(static_cast(shape)->getTopoShapePtr()->getShape()) + ); } else { setHandle(new ShapeFix_Wireframe()); @@ -58,47 +61,52 @@ int ShapeFix_WireframePy::PyInit(PyObject* args, PyObject* /*kwds*/) return 0; } -PyObject* ShapeFix_WireframePy::load(PyObject *args) +PyObject* ShapeFix_WireframePy::load(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } getShapeFix_WireframePtr()->Load(static_cast(shape)->getTopoShapePtr()->getShape()); Py_Return; } -PyObject* ShapeFix_WireframePy::clearStatuses(PyObject *args) +PyObject* ShapeFix_WireframePy::clearStatuses(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } getShapeFix_WireframePtr()->ClearStatuses(); Py_Return; } -PyObject* ShapeFix_WireframePy::fixWireGaps(PyObject *args) +PyObject* ShapeFix_WireframePy::fixWireGaps(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } bool ok = getShapeFix_WireframePtr()->FixWireGaps(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WireframePy::fixSmallEdges(PyObject *args) +PyObject* ShapeFix_WireframePy::fixSmallEdges(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } bool ok = getShapeFix_WireframePtr()->FixSmallEdges(); return Py::new_reference_to(Py::Boolean(ok)); } -PyObject* ShapeFix_WireframePy::shape(PyObject *args) +PyObject* ShapeFix_WireframePy::shape(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoShape sh = getShapeFix_WireframePtr()->Shape(); return sh.getPyObject(); @@ -124,7 +132,7 @@ void ShapeFix_WireframePy::setLimitAngle(Py::Float arg) getShapeFix_WireframePtr()->SetLimitAngle(arg); } -PyObject *ShapeFix_WireframePy::getCustomAttributes(const char* /*attr*/) const +PyObject* ShapeFix_WireframePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/ShapeMapHasher.h b/src/Mod/Part/App/ShapeMapHasher.h index fdd8d07f6f..fbfa4f22ac 100644 --- a/src/Mod/Part/App/ShapeMapHasher.h +++ b/src/Mod/Part/App/ShapeMapHasher.h @@ -29,10 +29,11 @@ #include #include #if OCC_VERSION_HEX >= 0x070800 -#include +# include #endif -namespace Part { +namespace Part +{ class ShapeMapHasher { @@ -42,11 +43,11 @@ public: #if OCC_VERSION_HEX < 0x070800 return theShape.HashCode(std::numeric_limits::max()); #else - return std::hash{}(theShape); + return std::hash {}(theShape); #endif } }; -} +} // namespace Part #endif // PART_SHAPEMAPHASHER_H diff --git a/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp b/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp index 76fe54842c..f349357694 100644 --- a/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp +++ b/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp @@ -24,8 +24,8 @@ #include -# include -# include +#include +#include // Needed for OCCT 7.5.2 #include @@ -40,7 +40,7 @@ using namespace Part; -PyObject *UnifySameDomainPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* UnifySameDomainPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of UnifySameDomainPy return new UnifySameDomainPy(nullptr); @@ -49,26 +49,38 @@ PyObject *UnifySameDomainPy::PyMake(struct _typeobject *, PyObject *, PyObject * // constructor method int UnifySameDomainPy::PyInit(PyObject* args, PyObject* kwds) { - PyObject *shape; - PyObject *unifyEdges = Py_True; // NOLINT - PyObject *unifyFaces = Py_True; // NOLINT - PyObject *concatBSpl = Py_False; // NOLINT + PyObject* shape; + PyObject* unifyEdges = Py_True; // NOLINT + PyObject* unifyFaces = Py_True; // NOLINT + PyObject* concatBSpl = Py_False; // NOLINT - static const std::array keywords{"Shape", "UnifyEdges", "UnifyFaces", "ConcatBSplines", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|O!O!O!", keywords, - &TopoShapePy::Type, &shape, - &PyBool_Type, &unifyEdges, - &PyBool_Type, &unifyFaces, - &PyBool_Type, &concatBSpl)) { + static const std::array + keywords {"Shape", "UnifyEdges", "UnifyFaces", "ConcatBSplines", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|O!O!O!", + keywords, + &TopoShapePy::Type, + &shape, + &PyBool_Type, + &unifyEdges, + &PyBool_Type, + &unifyFaces, + &PyBool_Type, + &concatBSpl + )) { return -1; } try { TopoDS_Shape shp = static_cast(shape)->getTopoShapePtr()->getShape(); - std::unique_ptr ptr(new ShapeUpgrade_UnifySameDomain(shp, - Base::asBoolean(unifyEdges), - Base::asBoolean(unifyFaces), - Base::asBoolean(concatBSpl))); + std::unique_ptr ptr(new ShapeUpgrade_UnifySameDomain( + shp, + Base::asBoolean(unifyEdges), + Base::asBoolean(unifyFaces), + Base::asBoolean(concatBSpl) + )); setTwinPointer(ptr.release()); return 0; @@ -79,28 +91,40 @@ int UnifySameDomainPy::PyInit(PyObject* args, PyObject* kwds) } } -PyObject* UnifySameDomainPy::initialize(PyObject *args, PyObject* kwds) +PyObject* UnifySameDomainPy::initialize(PyObject* args, PyObject* kwds) { - PyObject *shape; - PyObject *unifyEdges = Py_True; - PyObject *unifyFaces = Py_True; - PyObject *concatBSpl = Py_False; + PyObject* shape; + PyObject* unifyEdges = Py_True; + PyObject* unifyFaces = Py_True; + PyObject* concatBSpl = Py_False; - static const std::array keywords{"Shape", "UnifyEdges", "UnifyFaces", "ConcatBSplines", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|O!O!O!", keywords, - &TopoShapePy::Type, &shape, - &PyBool_Type, &unifyEdges, - &PyBool_Type, &unifyFaces, - &PyBool_Type, &concatBSpl)) { + static const std::array + keywords {"Shape", "UnifyEdges", "UnifyFaces", "ConcatBSplines", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|O!O!O!", + keywords, + &TopoShapePy::Type, + &shape, + &PyBool_Type, + &unifyEdges, + &PyBool_Type, + &unifyFaces, + &PyBool_Type, + &concatBSpl + )) { return nullptr; } try { TopoDS_Shape shp = static_cast(shape)->getTopoShapePtr()->getShape(); - getShapeUpgrade_UnifySameDomainPtr()->Initialize(shp, + getShapeUpgrade_UnifySameDomainPtr()->Initialize( + shp, Base::asBoolean(unifyEdges), Base::asBoolean(unifyFaces), - Base::asBoolean(concatBSpl)); + Base::asBoolean(concatBSpl) + ); Py_Return; } @@ -116,11 +140,12 @@ std::string UnifySameDomainPy::representation() const return {""}; } -PyObject* UnifySameDomainPy::allowInternalEdges(PyObject *args) +PyObject* UnifySameDomainPy::allowInternalEdges(PyObject* args) { PyObject* allow; - if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &allow)) + if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &allow)) { return nullptr; + } try { getShapeUpgrade_UnifySameDomainPtr()->AllowInternalEdges(Base::asBoolean(allow)); @@ -132,11 +157,12 @@ PyObject* UnifySameDomainPy::allowInternalEdges(PyObject *args) } } -PyObject* UnifySameDomainPy::keepShape(PyObject *args) +PyObject* UnifySameDomainPy::keepShape(PyObject* args) { PyObject* shape; - if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapePy::Type, &shape)) { return nullptr; + } try { TopoDS_Shape shp = static_cast(shape)->getTopoShapePtr()->getShape(); @@ -149,11 +175,12 @@ PyObject* UnifySameDomainPy::keepShape(PyObject *args) } } -PyObject* UnifySameDomainPy::keepShapes(PyObject *args) +PyObject* UnifySameDomainPy::keepShapes(PyObject* args) { PyObject* obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } try { TopTools_MapOfShape theShapes; @@ -172,11 +199,12 @@ PyObject* UnifySameDomainPy::keepShapes(PyObject *args) } } -PyObject* UnifySameDomainPy::setSafeInputMode(PyObject *args) +PyObject* UnifySameDomainPy::setSafeInputMode(PyObject* args) { PyObject* mode; - if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &mode)) + if (!PyArg_ParseTuple(args, "O!", &PyBool_Type, &mode)) { return nullptr; + } try { getShapeUpgrade_UnifySameDomainPtr()->SetSafeInputMode(Base::asBoolean(mode)); @@ -188,11 +216,12 @@ PyObject* UnifySameDomainPy::setSafeInputMode(PyObject *args) } } -PyObject* UnifySameDomainPy::setLinearTolerance(PyObject *args) +PyObject* UnifySameDomainPy::setLinearTolerance(PyObject* args) { double linTol; - if (!PyArg_ParseTuple(args, "d", &linTol)) + if (!PyArg_ParseTuple(args, "d", &linTol)) { return nullptr; + } try { getShapeUpgrade_UnifySameDomainPtr()->SetLinearTolerance(linTol); @@ -204,11 +233,12 @@ PyObject* UnifySameDomainPy::setLinearTolerance(PyObject *args) } } -PyObject* UnifySameDomainPy::setAngularTolerance(PyObject *args) +PyObject* UnifySameDomainPy::setAngularTolerance(PyObject* args) { double angTol; - if (!PyArg_ParseTuple(args, "d", &angTol)) + if (!PyArg_ParseTuple(args, "d", &angTol)) { return nullptr; + } try { getShapeUpgrade_UnifySameDomainPtr()->SetAngularTolerance(angTol); @@ -220,10 +250,11 @@ PyObject* UnifySameDomainPy::setAngularTolerance(PyObject *args) } } -PyObject* UnifySameDomainPy::build(PyObject *args) +PyObject* UnifySameDomainPy::build(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { getShapeUpgrade_UnifySameDomainPtr()->Build(); @@ -235,10 +266,11 @@ PyObject* UnifySameDomainPy::build(PyObject *args) } } -PyObject* UnifySameDomainPy::shape(PyObject *args) const +PyObject* UnifySameDomainPy::shape(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { TopoDS_Shape shape = getShapeUpgrade_UnifySameDomainPtr()->Shape(); @@ -250,7 +282,7 @@ PyObject* UnifySameDomainPy::shape(PyObject *args) const } } -PyObject *UnifySameDomainPy::getCustomAttributes(const char* /*attr*/) const +PyObject* UnifySameDomainPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Sphere.pyi b/src/Mod/Part/App/Sphere.pyi index 83241c40ed..93df75794f 100644 --- a/src/Mod/Part/App/Sphere.pyi +++ b/src/Mod/Part/App/Sphere.pyi @@ -5,7 +5,6 @@ from Base.Axis import Axis as AxisPy from GeometrySurface import GeometrySurface from typing import Final - @export( Twin="GeomSphere", TwinPointer="GeomSphere", diff --git a/src/Mod/Part/App/SpherePyImp.cpp b/src/Mod/Part/App/SpherePyImp.cpp index 80e7bffc6a..7caddf0895 100644 --- a/src/Mod/Part/App/SpherePyImp.cpp +++ b/src/Mod/Part/App/SpherePyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -39,8 +39,9 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python std::string SpherePy::representation() const { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); gp_Ax1 axis = sphere->Axis(); gp_Dir dir = axis.Direction(); gp_Pnt loc = axis.Location(); @@ -49,14 +50,14 @@ std::string SpherePy::representation() const std::stringstream str; str << "Sphere ("; str << "Radius : " << fRad << ", "; - str << "Center : (" << loc.X() << ", "<< loc.Y() << ", "<< loc.Z() << "), "; - str << "Direction : (" << dir.X() << ", "<< dir.Y() << ", "<< dir.Z() << ")"; + str << "Center : (" << loc.X() << ", " << loc.Y() << ", " << loc.Z() << "), "; + str << "Direction : (" << dir.X() << ", " << dir.Y() << ", " << dir.Z() << ")"; str << ")"; return str.str(); } -PyObject *SpherePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* SpherePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of SpherePy and the Twin object return new SpherePy(new GeomSphere); @@ -66,8 +67,9 @@ PyObject *SpherePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pyt int SpherePy::PyInit(PyObject* args, PyObject* /*kwd*/) { if (PyArg_ParseTuple(args, "")) { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); sphere->SetRadius(1.0); return 0; } @@ -77,36 +79,41 @@ int SpherePy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::Float SpherePy::getRadius() const { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); return Py::Float(sphere->Radius()); } -void SpherePy::setRadius(Py::Float arg) +void SpherePy::setRadius(Py::Float arg) { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); sphere->SetRadius((double)arg); } Py::Float SpherePy::getArea() const { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); return Py::Float(sphere->Area()); } Py::Float SpherePy::getVolume() const { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); return Py::Float(sphere->Volume()); } Py::Object SpherePy::getCenter() const { - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); gp_Pnt loc = sphere->Location(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } @@ -116,14 +123,16 @@ void SpherePy::setCenter(Py::Object arg) PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d loc = static_cast(p)->value(); - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); sphere->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d loc = Base::getVectorFromTuple(p); - Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast - (getGeomSpherePtr()->handle()); + Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast( + getGeomSpherePtr()->handle() + ); sphere->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else { @@ -135,8 +144,9 @@ void SpherePy::setCenter(Py::Object arg) Py::Object SpherePy::getAxis() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeometryPtr()->handle() + ); gp_Dir dir = s->Axis().Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } @@ -144,7 +154,7 @@ Py::Object SpherePy::getAxis() const void SpherePy::setAxis(Py::Object arg) { Standard_Real dir_x, dir_y, dir_z; - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); dir_x = v.x; @@ -164,8 +174,9 @@ void SpherePy::setAxis(Py::Object arg) } try { - Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast - (this->getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast( + this->getGeometryPtr()->handle() + ); gp_Ax1 axis; axis.SetLocation(this_surf->Location()); axis.SetDirection(gp_Dir(dir_x, dir_y, dir_z)); @@ -176,7 +187,7 @@ void SpherePy::setAxis(Py::Object arg) } } -PyObject *SpherePy::getCustomAttributes(const char* /*attr*/) const +PyObject* SpherePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/SurfaceOfExtrusion.pyi b/src/Mod/Part/App/SurfaceOfExtrusion.pyi index 8cdc6e15b6..7409c77dcb 100644 --- a/src/Mod/Part/App/SurfaceOfExtrusion.pyi +++ b/src/Mod/Part/App/SurfaceOfExtrusion.pyi @@ -3,7 +3,6 @@ from GeometrySurface import GeometrySurface from GeometryCurve import GeometryCurve from Base.Vector import Vector - @export( Twin="GeomSurfaceOfExtrusion", TwinPointer="GeomSurfaceOfExtrusion", diff --git a/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp b/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp index ad170ec3d9..9edc52fbee 100644 --- a/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp +++ b/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -43,7 +43,7 @@ std::string SurfaceOfExtrusionPy::representation() const return {""}; } -PyObject *SurfaceOfExtrusionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* SurfaceOfExtrusionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of SurfaceOfExtrusionPy and the Twin object return new SurfaceOfExtrusionPy(new GeomSurfaceOfExtrusion); @@ -54,14 +54,12 @@ int SurfaceOfExtrusionPy::PyInit(PyObject* args, PyObject* /*kwd*/) { PyObject* pGeom; PyObject* pDir; - if (!PyArg_ParseTuple(args, "O!O!", - &(GeometryPy::Type), &pGeom, - &(Base::VectorPy::Type),&pDir)) + if (!PyArg_ParseTuple(args, "O!O!", &(GeometryPy::Type), &pGeom, &(Base::VectorPy::Type), &pDir)) { return -1; + } GeometryPy* pcGeo = static_cast(pGeom); - Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a curve"); return -1; @@ -69,8 +67,8 @@ int SurfaceOfExtrusionPy::PyInit(PyObject* args, PyObject* /*kwd*/) try { Base::Vector3d dir = static_cast(pDir)->value(); - Handle(Geom_SurfaceOfLinearExtrusion) curve2 = new Geom_SurfaceOfLinearExtrusion(curve, - gp_Dir(dir.x,dir.y,dir.z)); + Handle(Geom_SurfaceOfLinearExtrusion) curve2 + = new Geom_SurfaceOfLinearExtrusion(curve, gp_Dir(dir.x, dir.y, dir.z)); getGeomSurfaceOfExtrusionPtr()->setHandle(curve2); return 0; } @@ -83,26 +81,29 @@ int SurfaceOfExtrusionPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::Object SurfaceOfExtrusionPy::getDirection() const { - Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast( + getGeometryPtr()->handle() + ); const gp_Dir& dir = curve->Direction(); - return Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z())); + return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void SurfaceOfExtrusionPy::setDirection(Py::Object arg) +void SurfaceOfExtrusionPy::setDirection(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d dir = static_cast(p)->value(); - Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast - (getGeometryPtr()->handle()); - curve->SetDirection(gp_Dir(dir.x,dir.y,dir.z)); + Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle( + Geom_SurfaceOfLinearExtrusion + )::DownCast(getGeometryPtr()->handle()); + curve->SetDirection(gp_Dir(dir.x, dir.y, dir.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d dir = Base::getVectorFromTuple(p); - Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast - (getGeometryPtr()->handle()); - curve->SetDirection(gp_Dir(dir.x,dir.y,dir.z)); + Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle( + Geom_SurfaceOfLinearExtrusion + )::DownCast(getGeometryPtr()->handle()); + curve->SetDirection(gp_Dir(dir.x, dir.y, dir.z)); } else { std::string error = std::string("type must be 'Vector', not "); @@ -111,32 +112,34 @@ void SurfaceOfExtrusionPy::setDirection(Py::Object arg) } } -namespace Part { - extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); +namespace Part +{ +extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve) & c); } Py::Object SurfaceOfExtrusionPy::getBasisCurve() const { - Handle(Geom_SurfaceOfLinearExtrusion) surf = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfLinearExtrusion) surf = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast( + getGeometryPtr()->handle() + ); Handle(Geom_Curve) curve = surf->BasisCurve(); return makeGeometryCurvePy(curve); } -void SurfaceOfExtrusionPy::setBasisCurve(Py::Object arg) +void SurfaceOfExtrusionPy::setBasisCurve(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(GeometryPy::Type))) { GeometryPy* pcGeo = static_cast(p); - Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { throw Py::TypeError("geometry is not a curve"); } try { - Handle(Geom_SurfaceOfLinearExtrusion) curve2 = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfLinearExtrusion) curve2 = Handle( + Geom_SurfaceOfLinearExtrusion + )::DownCast(getGeometryPtr()->handle()); curve2->SetBasisCurve(curve); } catch (Standard_Failure& e) { @@ -145,7 +148,7 @@ void SurfaceOfExtrusionPy::setBasisCurve(Py::Object arg) } } -PyObject *SurfaceOfExtrusionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* SurfaceOfExtrusionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/SurfaceOfRevolution.pyi b/src/Mod/Part/App/SurfaceOfRevolution.pyi index 9b318a5bfb..52dcf70deb 100644 --- a/src/Mod/Part/App/SurfaceOfRevolution.pyi +++ b/src/Mod/Part/App/SurfaceOfRevolution.pyi @@ -5,7 +5,6 @@ from GeometrySurface import GeometrySurface from GeometryCurve import GeometryCurve from typing import overload - @export( Twin="GeomSurfaceOfRevolution", TwinPointer="GeomSurfaceOfRevolution", diff --git a/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp b/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp index 83ae0a6478..a9de76dfe2 100644 --- a/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp +++ b/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -41,7 +41,7 @@ std::string SurfaceOfRevolutionPy::representation() const return {""}; } -PyObject *SurfaceOfRevolutionPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* SurfaceOfRevolutionPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of SurfaceOfRevolutionPy and the Twin object return new SurfaceOfRevolutionPy(new GeomSurfaceOfRevolution); @@ -53,15 +53,21 @@ int SurfaceOfRevolutionPy::PyInit(PyObject* args, PyObject* /*kwd*/) PyObject* pGeom; PyObject* pPnt; PyObject* pDir; - if (!PyArg_ParseTuple(args, "O!O!O!", - &(GeometryPy::Type), &pGeom, - &(Base::VectorPy::Type),&pPnt, - &(Base::VectorPy::Type),&pDir)) + if (!PyArg_ParseTuple( + args, + "O!O!O!", + &(GeometryPy::Type), + &pGeom, + &(Base::VectorPy::Type), + &pPnt, + &(Base::VectorPy::Type), + &pDir + )) { return -1; + } GeometryPy* pcGeo = static_cast(pGeom); - Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a curve"); return -1; @@ -70,9 +76,10 @@ int SurfaceOfRevolutionPy::PyInit(PyObject* args, PyObject* /*kwd*/) try { Base::Vector3d pnt = static_cast(pPnt)->value(); Base::Vector3d dir = static_cast(pDir)->value(); - Handle(Geom_SurfaceOfRevolution) curve2 = new Geom_SurfaceOfRevolution(curve, - gp_Ax1(gp_Pnt(pnt.x,pnt.y,pnt.z), - gp_Dir(dir.x,dir.y,dir.z))); + Handle(Geom_SurfaceOfRevolution) curve2 = new Geom_SurfaceOfRevolution( + curve, + gp_Ax1(gp_Pnt(pnt.x, pnt.y, pnt.z), gp_Dir(dir.x, dir.y, dir.z)) + ); getGeomSurfaceOfRevolutionPtr()->setHandle(curve2); return 0; } @@ -85,26 +92,29 @@ int SurfaceOfRevolutionPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::Object SurfaceOfRevolutionPy::getLocation() const { - Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); const gp_Pnt& pnt = curve->Location(); - return Py::Vector(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z())); + return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } -void SurfaceOfRevolutionPy::setLocation(Py::Object arg) +void SurfaceOfRevolutionPy::setLocation(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d pnt = static_cast(p)->value(); - Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); - curve->SetLocation(gp_Pnt(pnt.x,pnt.y,pnt.z)); + Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); + curve->SetLocation(gp_Pnt(pnt.x, pnt.y, pnt.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d pnt = Base::getVectorFromTuple(p); - Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); - curve->SetLocation(gp_Pnt(pnt.x,pnt.y,pnt.z)); + Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); + curve->SetLocation(gp_Pnt(pnt.x, pnt.y, pnt.z)); } else { std::string error = std::string("type must be 'Vector', not "); @@ -115,26 +125,29 @@ void SurfaceOfRevolutionPy::setLocation(Py::Object arg) Py::Object SurfaceOfRevolutionPy::getDirection() const { - Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); const gp_Dir& dir = curve->Direction(); - return Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z())); + return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -void SurfaceOfRevolutionPy::setDirection(Py::Object arg) +void SurfaceOfRevolutionPy::setDirection(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d dir = static_cast(p)->value(); - Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); - curve->SetDirection(gp_Dir(dir.x,dir.y,dir.z)); + Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); + curve->SetDirection(gp_Dir(dir.x, dir.y, dir.z)); } else if (PyObject_TypeCheck(p, &PyTuple_Type)) { Base::Vector3d dir = Base::getVectorFromTuple(p); - Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); - curve->SetDirection(gp_Dir(dir.x,dir.y,dir.z)); + Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); + curve->SetDirection(gp_Dir(dir.x, dir.y, dir.z)); } else { std::string error = std::string("type must be 'Vector', not "); @@ -143,32 +156,34 @@ void SurfaceOfRevolutionPy::setDirection(Py::Object arg) } } -namespace Part { - extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); +namespace Part +{ +extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve) & c); } Py::Object SurfaceOfRevolutionPy::getBasisCurve() const { - Handle(Geom_SurfaceOfRevolution) surf = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfRevolution) surf = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); Handle(Geom_Curve) curve = surf->BasisCurve(); return makeGeometryCurvePy(curve); } -void SurfaceOfRevolutionPy::setBasisCurve(Py::Object arg) +void SurfaceOfRevolutionPy::setBasisCurve(Py::Object arg) { PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(GeometryPy::Type))) { GeometryPy* pcGeo = static_cast(p); - Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast - (pcGeo->getGeometryPtr()->handle()); + Handle(Geom_Curve) curve = Handle(Geom_Curve)::DownCast(pcGeo->getGeometryPtr()->handle()); if (curve.IsNull()) { throw Py::TypeError("geometry is not a curve"); } try { - Handle(Geom_SurfaceOfRevolution) curve2 = Handle(Geom_SurfaceOfRevolution)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_SurfaceOfRevolution) curve2 = Handle(Geom_SurfaceOfRevolution)::DownCast( + getGeometryPtr()->handle() + ); curve2->SetBasisCurve(curve); } catch (Standard_Failure& e) { @@ -177,7 +192,7 @@ void SurfaceOfRevolutionPy::setBasisCurve(Py::Object arg) } } -PyObject *SurfaceOfRevolutionPy::getCustomAttributes(const char* /*attr*/) const +PyObject* SurfaceOfRevolutionPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -186,5 +201,3 @@ int SurfaceOfRevolutionPy::setCustomAttributes(const char* /*attr*/, PyObject* / { return 0; } - - diff --git a/src/Mod/Part/App/Tools.cpp b/src/Mod/Part/App/Tools.cpp index 03ee6c9748..365448e50f 100644 --- a/src/Mod/Part/App/Tools.cpp +++ b/src/Mod/Part/App/Tools.cpp @@ -22,49 +22,49 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# if OCC_VERSION_HEX < 0x070600 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if OCC_VERSION_HEX < 0x070600 # include # include -# endif +#endif #include #include @@ -83,23 +83,23 @@ void Part::closestPointsOnLines(const gp_Lin& lin1, const gp_Lin& lin2, gp_Pnt& gp_Vec v2(lin2.Direction()); gp_Vec v3(lin2.Location(), lin1.Location()); - double a = v1*v1; - double b = v1*v2; - double c = v2*v2; - double d = v1*v3; - double e = v2*v3; - double D = a*c - b*b; + double a = v1 * v1; + double b = v1 * v2; + double c = v2 * v2; + double d = v1 * v3; + double e = v2 * v3; + double D = a * c - b * b; double s, t; // D = (v1 x v2) * (v1 x v2) - if (D < Precision::Angular()){ + if (D < Precision::Angular()) { // the lines are considered parallel s = 0.0; - t = (b>c ? d/b : e/c); + t = (b > c ? d / b : e / c); } else { - s = (b*e - c*d) / D; - t = (a*e - b*d) / D; + s = (b * e - c * d) / D; + t = (a * e - b * d) / D; } p1 = lin1.Location().XYZ() + s * v1.XYZ(); @@ -109,8 +109,8 @@ void Part::closestPointsOnLines(const gp_Lin& lin1, const gp_Lin& lin2, gp_Pnt& bool Part::intersect(const gp_Pln& pln1, const gp_Pln& pln2, gp_Lin& lin) { bool found = false; - Handle (Geom_Plane) gp1 = new Geom_Plane(pln1); - Handle (Geom_Plane) gp2 = new Geom_Plane(pln2); + Handle(Geom_Plane) gp1 = new Geom_Plane(pln1); + Handle(Geom_Plane) gp2 = new Geom_Plane(pln2); GeomAPI_IntSS intSS(gp1, gp2, Precision::Confusion()); if (intSS.IsDone()) { @@ -134,111 +134,135 @@ If the \a theBoundaries list is empty then Standard_ConstructionError is thrown. If the algorithm fails it returns a null surface. \see http://opencascade.blogspot.com/2010/03/surface-modeling-part6.html */ -Handle(Geom_Surface) -Part::Tools::makeSurface(const TColStd_ListOfTransient &theBoundaries, - const Standard_Real theTol, - const Standard_Integer theNbPnts, - const Standard_Integer theNbIter, - const Standard_Integer theMaxDeg) +Handle(Geom_Surface) Part::Tools::makeSurface( + const TColStd_ListOfTransient& theBoundaries, + const Standard_Real theTol, + const Standard_Integer theNbPnts, + const Standard_Integer theNbIter, + const Standard_Integer theMaxDeg +) { (void)theTol; - //constants for algorithm - const Standard_Integer aNbIter = theNbIter; //number of algorithm iterations - const Standard_Integer aNbPnts = theNbPnts; //sample points per each constraint - const Standard_Integer aDeg = 3; //requested surface degree ? + // constants for algorithm + const Standard_Integer aNbIter = theNbIter; // number of algorithm iterations + const Standard_Integer aNbPnts = theNbPnts; // sample points per each constraint + const Standard_Integer aDeg = 3; // requested surface degree ? const Standard_Integer aMaxDeg = theMaxDeg; const Standard_Integer aMaxSeg = 10000; const Standard_Real aTol3d = 1.e-04; const Standard_Real aTol2d = 1.e-05; - const Standard_Real anAngTol = 1.e-02; //angular - const Standard_Real aCurvTol = 1.e-01; //curvature + const Standard_Real anAngTol = 1.e-02; // angular + const Standard_Real aCurvTol = 1.e-01; // curvature Handle(Geom_Surface) aRes; - GeomPlate_BuildPlateSurface aPlateBuilder (aDeg, aNbPnts, aNbIter, aTol2d, aTol3d, anAngTol, aCurvTol); + GeomPlate_BuildPlateSurface aPlateBuilder(aDeg, aNbPnts, aNbIter, aTol2d, aTol3d, anAngTol, aCurvTol); - TColStd_ListIteratorOfListOfTransient anIt (theBoundaries); + TColStd_ListIteratorOfListOfTransient anIt(theBoundaries); if (anIt.More()) { int i = 1; for (; anIt.More(); anIt.Next(), i++) { - const Handle(Standard_Transient)& aCur = anIt.Value(); + const Handle(Standard_Transient) & aCur = anIt.Value(); if (aCur.IsNull()) { - assert (0); - Standard_ConstructionError::Raise ("Tools::makeSurface()"); + assert(0); + Standard_ConstructionError::Raise("Tools::makeSurface()"); } #if OCC_VERSION_HEX >= 0x070600 - else if (aCur->IsKind (STANDARD_TYPE (Adaptor3d_CurveOnSurface))) { - //G1 constraint - Handle(Adaptor3d_CurveOnSurface) aHCOS (Handle(Adaptor3d_CurveOnSurface)::DownCast (aCur)); - Handle (GeomPlate_CurveConstraint) aConst = new GeomPlate_CurveConstraint (aHCOS, 1 /*GeomAbs_G1*/,aNbPnts, aTol3d, anAngTol, aCurvTol); - aPlateBuilder.Add (aConst); + else if (aCur->IsKind(STANDARD_TYPE(Adaptor3d_CurveOnSurface))) { + // G1 constraint + Handle(Adaptor3d_CurveOnSurface) + aHCOS(Handle(Adaptor3d_CurveOnSurface)::DownCast(aCur)); + Handle(GeomPlate_CurveConstraint) aConst = new GeomPlate_CurveConstraint( + aHCOS, + 1 /*GeomAbs_G1*/, + aNbPnts, + aTol3d, + anAngTol, + aCurvTol + ); + aPlateBuilder.Add(aConst); } - else if (aCur->IsKind (STANDARD_TYPE (GeomAdaptor_Curve))) { - //G0 constraint - Handle(GeomAdaptor_Curve) aHC (Handle(GeomAdaptor_Curve)::DownCast (aCur)); - Handle (GeomPlate_CurveConstraint) aConst = new GeomPlate_CurveConstraint (aHC, 0 /*GeomAbs_G0*/, aNbPnts, aTol3d); - aPlateBuilder.Add (aConst); + else if (aCur->IsKind(STANDARD_TYPE(GeomAdaptor_Curve))) { + // G0 constraint + Handle(GeomAdaptor_Curve) aHC(Handle(GeomAdaptor_Curve)::DownCast(aCur)); + Handle(GeomPlate_CurveConstraint) aConst + = new GeomPlate_CurveConstraint(aHC, 0 /*GeomAbs_G0*/, aNbPnts, aTol3d); + aPlateBuilder.Add(aConst); } #else - else if (aCur->IsKind (STANDARD_TYPE (Adaptor3d_HCurveOnSurface))) { - //G1 constraint - Handle(Adaptor3d_HCurveOnSurface) aHCOS (Handle(Adaptor3d_HCurveOnSurface)::DownCast (aCur)); - Handle (GeomPlate_CurveConstraint) aConst = new GeomPlate_CurveConstraint (aHCOS, 1 /*GeomAbs_G1*/,aNbPnts, aTol3d, anAngTol, aCurvTol); - aPlateBuilder.Add (aConst); + else if (aCur->IsKind(STANDARD_TYPE(Adaptor3d_HCurveOnSurface))) { + // G1 constraint + Handle(Adaptor3d_HCurveOnSurface) + aHCOS(Handle(Adaptor3d_HCurveOnSurface)::DownCast(aCur)); + Handle(GeomPlate_CurveConstraint) aConst = new GeomPlate_CurveConstraint( + aHCOS, + 1 /*GeomAbs_G1*/, + aNbPnts, + aTol3d, + anAngTol, + aCurvTol + ); + aPlateBuilder.Add(aConst); } - else if (aCur->IsKind (STANDARD_TYPE (GeomAdaptor_HCurve))) { - //G0 constraint - Handle(GeomAdaptor_HCurve) aHC (Handle(GeomAdaptor_HCurve)::DownCast (aCur)); - Handle (GeomPlate_CurveConstraint) aConst = new GeomPlate_CurveConstraint (aHC, 0 /*GeomAbs_G0*/, aNbPnts, aTol3d); - aPlateBuilder.Add (aConst); + else if (aCur->IsKind(STANDARD_TYPE(GeomAdaptor_HCurve))) { + // G0 constraint + Handle(GeomAdaptor_HCurve) aHC(Handle(GeomAdaptor_HCurve)::DownCast(aCur)); + Handle(GeomPlate_CurveConstraint) aConst + = new GeomPlate_CurveConstraint(aHC, 0 /*GeomAbs_G0*/, aNbPnts, aTol3d); + aPlateBuilder.Add(aConst); } #endif - else if (aCur->IsKind (STANDARD_TYPE (Geom_Point))) { - //Point constraint - Handle(Geom_Point) aGP (Handle(Geom_Point)::DownCast (aCur)); - Handle(GeomPlate_PointConstraint) aConst = new GeomPlate_PointConstraint(aGP->Pnt(),0); + else if (aCur->IsKind(STANDARD_TYPE(Geom_Point))) { + // Point constraint + Handle(Geom_Point) aGP(Handle(Geom_Point)::DownCast(aCur)); + Handle(GeomPlate_PointConstraint) aConst = new GeomPlate_PointConstraint(aGP->Pnt(), 0); aPlateBuilder.Add(aConst); } else { - Standard_TypeMismatch::Raise ("Tools::makeSurface()"); + Standard_TypeMismatch::Raise("Tools::makeSurface()"); } } } else { - Standard_ConstructionError::Raise ("Tools::makeSurface()"); + Standard_ConstructionError::Raise("Tools::makeSurface()"); } - //construct + // construct aPlateBuilder.Perform(); if (!aPlateBuilder.IsDone()) { return aRes; } - const Handle(GeomPlate_Surface)& aPlate = aPlateBuilder.Surface(); - //approximation (see BRepFill_Filling - when no initial surface was given) + const Handle(GeomPlate_Surface) & aPlate = aPlateBuilder.Surface(); + // approximation (see BRepFill_Filling - when no initial surface was given) Standard_Real aDMax = aPlateBuilder.G0Error(); TColgp_SequenceOfXY aS2d; TColgp_SequenceOfXYZ aS3d; - aPlateBuilder.Disc2dContour (4, aS2d); - aPlateBuilder.Disc3dContour (4, 0, aS3d); - Standard_Real aMax = Max (aTol3d, 10. * aDMax); - GeomPlate_PlateG0Criterion aCriterion (aS2d, aS3d, aMax); + aPlateBuilder.Disc2dContour(4, aS2d); + aPlateBuilder.Disc3dContour(4, 0, aS3d); + Standard_Real aMax = Max(aTol3d, 10. * aDMax); + GeomPlate_PlateG0Criterion aCriterion(aS2d, aS3d, aMax); { - //data races in AdvApp2Var used by GeomApprox_Surface, use global mutex - //Standard_Mutex::Sentry aSentry (theBSMutex); - GeomPlate_MakeApprox aMakeApprox (aPlate, aCriterion, aTol3d, aMaxSeg, aMaxDeg); + // data races in AdvApp2Var used by GeomApprox_Surface, use global mutex + // Standard_Mutex::Sentry aSentry (theBSMutex); + GeomPlate_MakeApprox aMakeApprox(aPlate, aCriterion, aTol3d, aMaxSeg, aMaxDeg); aRes = aMakeApprox.Surface(); } return aRes; } -bool Part::Tools::getTriangulation(const TopoDS_Face& face, std::vector& points, std::vector& facets) +bool Part::Tools::getTriangulation( + const TopoDS_Face& face, + std::vector& points, + std::vector& facets +) { TopLoc_Location loc; Handle(Poly_Triangulation) hTria = BRep_Tool::Triangulation(face, loc); - if (hTria.IsNull()) + if (hTria.IsNull()) { return false; + } // getting the transformation of the face gp_Trsf transf; @@ -280,13 +304,15 @@ bool Part::Tools::getTriangulation(const TopoDS_Face& face, std::vector& for (int i = 1; i <= nbTriangles; i++) { // Get the triangle - Standard_Integer n1,n2,n3; + Standard_Integer n1, n2, n3; #if OCC_VERSION_HEX < 0x070600 triangles(i).Get(n1, n2, n3); #else hTria->Triangle(i).Get(n1, n2, n3); #endif - --n1; --n2; --n3; + --n1; + --n2; + --n3; // change orientation of the triangles if (orient != TopAbs_FORWARD) { @@ -299,17 +325,23 @@ bool Part::Tools::getTriangulation(const TopoDS_Face& face, std::vector& return true; } -bool Part::Tools::getPolygonOnTriangulation(const TopoDS_Edge& edge, const TopoDS_Face& face, std::vector& points) +bool Part::Tools::getPolygonOnTriangulation( + const TopoDS_Edge& edge, + const TopoDS_Face& face, + std::vector& points +) { TopLoc_Location loc; Handle(Poly_Triangulation) hTria = BRep_Tool::Triangulation(face, loc); - if (hTria.IsNull()) + if (hTria.IsNull()) { return false; + } // this holds the indices of the edge's triangulation to the actual points Handle(Poly_PolygonOnTriangulation) hPoly = BRep_Tool::PolygonOnTriangulation(edge, hTria, loc); - if (hPoly.IsNull()) + if (hPoly.IsNull()) { return false; + } // getting the transformation of the edge gp_Trsf transf; @@ -348,8 +380,9 @@ bool Part::Tools::getPolygon3D(const TopoDS_Edge& edge, std::vector& poi { TopLoc_Location loc; Handle(Poly_Polygon3D) hPoly = BRep_Tool::Polygon3D(edge, loc); - if (hPoly.IsNull()) + if (hPoly.IsNull()) { return false; + } // getting the transformation of the edge gp_Trsf transf; @@ -378,14 +411,18 @@ bool Part::Tools::getPolygon3D(const TopoDS_Edge& edge, std::vector& poi return true; } -void Part::Tools::getPointNormals(const std::vector& points, const std::vector& facets, std::vector& vertexnormals) +void Part::Tools::getPointNormals( + const std::vector& points, + const std::vector& facets, + std::vector& vertexnormals +) { vertexnormals.resize(points.size()); for (const auto& it : facets) { // Get the triangle - Standard_Integer n1,n2,n3; - it.Get(n1,n2,n3); + Standard_Integer n1, n2, n3; + it.Get(n1, n2, n3); // Calculate triangle normal gp_Vec v1(points[n1].XYZ()); @@ -399,18 +436,25 @@ void Part::Tools::getPointNormals(const std::vector& points, const std:: vertexnormals[n3] += n; } - for (auto& it : vertexnormals) + for (auto& it : vertexnormals) { it.Normalize(); + } } -void Part::Tools::getPointNormals(const std::vector& points, const TopoDS_Face& face, std::vector& vertexnormals) +void Part::Tools::getPointNormals( + const std::vector& points, + const TopoDS_Face& face, + std::vector& vertexnormals +) { - if (points.size() != vertexnormals.size()) + if (points.size() != vertexnormals.size()) { return; + } Handle(Geom_Surface) hSurface = BRep_Tool::Surface(face); - if (hSurface.IsNull()) + if (hSurface.IsNull()) { return; + } // normalize all vertex normals for (std::size_t i = 0; i < points.size(); i++) { @@ -423,10 +467,10 @@ void Part::Tools::getPointNormals(const std::vector& points, const TopoD gp_Dir normal = propOfFace.Normal(); gp_Vec temp = normal; - if (temp * vertexnormals[i] < 0.0) + if (temp * vertexnormals[i] < 0.0) { temp = -temp; + } vertexnormals[i] = temp; - } catch (...) { } @@ -435,30 +479,29 @@ void Part::Tools::getPointNormals(const std::vector& points, const TopoD } } -void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triangulation) aPolyTri, TColgp_Array1OfDir& theNormals) +void Part::Tools::getPointNormals( + const TopoDS_Face& theFace, + Handle(Poly_Triangulation) aPolyTri, + TColgp_Array1OfDir& theNormals +) { #if OCC_VERSION_HEX < 0x070600 const TColgp_Array1OfPnt& aNodes = aPolyTri->Nodes(); - if(aPolyTri->HasNormals()) - { + if (aPolyTri->HasNormals()) { // normals pre-computed in triangulation structure const TShort_Array1OfShortReal& aNormals = aPolyTri->Normals(); - const Standard_ShortReal* aNormArr = &(aNormals.Value(aNormals.Lower())); + const Standard_ShortReal* aNormArr = &(aNormals.Value(aNormals.Lower())); - for(Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter) - { + for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter) { const Standard_Integer anId = 3 * (aNodeIter - aNodes.Lower()); - const gp_Dir aNorm(aNormArr[anId + 0], - aNormArr[anId + 1], - aNormArr[anId + 2]); + const gp_Dir aNorm(aNormArr[anId + 0], aNormArr[anId + 1], aNormArr[anId + 2]); theNormals(aNodeIter) = aNorm; } - if(theFace.Orientation() == TopAbs_REVERSED) - { - for(Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter) - { + if (theFace.Orientation() == TopAbs_REVERSED) { + for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); + ++aNodeIter) { theNormals.ChangeValue(aNodeIter).Reverse(); } } @@ -466,34 +509,34 @@ void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triang else { // take in face the surface location Poly_Connect thePolyConnect(aPolyTri); - const TopoDS_Face aZeroFace = TopoDS::Face(theFace.Located(TopLoc_Location())); - Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aZeroFace); - const Standard_Real aTol = Precision::Confusion(); - Handle(TShort_HArray1OfShortReal) aNormals = new TShort_HArray1OfShortReal(1, aPolyTri->NbNodes() * 3); + const TopoDS_Face aZeroFace = TopoDS::Face(theFace.Located(TopLoc_Location())); + Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aZeroFace); + const Standard_Real aTol = Precision::Confusion(); + Handle(TShort_HArray1OfShortReal) aNormals + = new TShort_HArray1OfShortReal(1, aPolyTri->NbNodes() * 3); const Poly_Array1OfTriangle& aTriangles = aPolyTri->Triangles(); - const TColgp_Array1OfPnt2d* aNodesUV = aPolyTri->HasUVNodes() && !aSurf.IsNull() - ? &aPolyTri->UVNodes() - : nullptr; + const TColgp_Array1OfPnt2d* aNodesUV = aPolyTri->HasUVNodes() && !aSurf.IsNull() + ? &aPolyTri->UVNodes() + : nullptr; Standard_Integer aTri[3]; - for(Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter) - { + for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter) { // try to retrieve normal from real surface first, when UV coordinates are available - if (!aNodesUV || GeomLib::NormEstim(aSurf, aNodesUV->Value(aNodeIter), aTol, theNormals(aNodeIter)) > 1) - { + if (!aNodesUV + || GeomLib::NormEstim(aSurf, aNodesUV->Value(aNodeIter), aTol, theNormals(aNodeIter)) + > 1) { // compute flat normals gp_XYZ eqPlan(0.0, 0.0, 0.0); - for(thePolyConnect.Initialize(aNodeIter); thePolyConnect.More(); thePolyConnect.Next()) - { + for (thePolyConnect.Initialize(aNodeIter); thePolyConnect.More(); + thePolyConnect.Next()) { aTriangles(thePolyConnect.Value()).Get(aTri[0], aTri[1], aTri[2]); const gp_XYZ v1(aNodes(aTri[1]).Coord() - aNodes(aTri[0]).Coord()); const gp_XYZ v2(aNodes(aTri[2]).Coord() - aNodes(aTri[1]).Coord()); const gp_XYZ vv = v1 ^ v2; const Standard_Real aMod = vv.Modulus(); - if(aMod >= aTol) - { + if (aMod >= aTol) { eqPlan += vv / aMod; } } @@ -510,10 +553,9 @@ void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triang aPolyTri->SetNormals(aNormals); - if(theFace.Orientation() == TopAbs_REVERSED) - { - for(Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); ++aNodeIter) - { + if (theFace.Orientation() == TopAbs_REVERSED) { + for (Standard_Integer aNodeIter = aNodes.Lower(); aNodeIter <= aNodes.Upper(); + ++aNodeIter) { theNormals.ChangeValue(aNodeIter).Reverse(); } } @@ -521,17 +563,13 @@ void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triang #else Standard_Integer numNodes = aPolyTri->NbNodes(); - if(aPolyTri->HasNormals()) - { - for(Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) - { + if (aPolyTri->HasNormals()) { + for (Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) { theNormals(aNodeIter) = aPolyTri->Normal(aNodeIter); } - if(theFace.Orientation() == TopAbs_REVERSED) - { - for(Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) - { + if (theFace.Orientation() == TopAbs_REVERSED) { + for (Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) { theNormals.ChangeValue(aNodeIter).Reverse(); } } @@ -539,31 +577,30 @@ void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triang else { // take in face the surface location Poly_Connect thePolyConnect(aPolyTri); - const TopoDS_Face aZeroFace = TopoDS::Face(theFace.Located(TopLoc_Location())); - Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aZeroFace); - const Standard_Real aTol = Precision::Confusion(); - Standard_Boolean hasNodesUV = aPolyTri->HasUVNodes() && !aSurf.IsNull(); + const TopoDS_Face aZeroFace = TopoDS::Face(theFace.Located(TopLoc_Location())); + Handle(Geom_Surface) aSurf = BRep_Tool::Surface(aZeroFace); + const Standard_Real aTol = Precision::Confusion(); + Standard_Boolean hasNodesUV = aPolyTri->HasUVNodes() && !aSurf.IsNull(); Standard_Integer aTri[3]; aPolyTri->AddNormals(); - for(Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) - { + for (Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) { // try to retrieve normal from real surface first, when UV coordinates are available - if (!hasNodesUV || GeomLib::NormEstim(aSurf, aPolyTri->UVNode(aNodeIter), aTol, theNormals(aNodeIter)) > 1) - { + if (!hasNodesUV + || GeomLib::NormEstim(aSurf, aPolyTri->UVNode(aNodeIter), aTol, theNormals(aNodeIter)) + > 1) { // compute flat normals gp_XYZ eqPlan(0.0, 0.0, 0.0); - for(thePolyConnect.Initialize(aNodeIter); thePolyConnect.More(); thePolyConnect.Next()) - { + for (thePolyConnect.Initialize(aNodeIter); thePolyConnect.More(); + thePolyConnect.Next()) { aPolyTri->Triangle(thePolyConnect.Value()).Get(aTri[0], aTri[1], aTri[2]); const gp_XYZ v1(aPolyTri->Node(aTri[1]).Coord() - aPolyTri->Node(aTri[0]).Coord()); const gp_XYZ v2(aPolyTri->Node(aTri[2]).Coord() - aPolyTri->Node(aTri[1]).Coord()); const gp_XYZ vv = v1 ^ v2; const Standard_Real aMod = vv.Modulus(); - if(aMod >= aTol) - { + if (aMod >= aTol) { eqPlan += vv / aMod; } } @@ -575,10 +612,8 @@ void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triang aPolyTri->SetNormal(aNodeIter, theNormals(aNodeIter)); } - if(theFace.Orientation() == TopAbs_REVERSED) - { - for(Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) - { + if (theFace.Orientation() == TopAbs_REVERSED) { + for (Standard_Integer aNodeIter = 1; aNodeIter <= numNodes; ++aNodeIter) { theNormals.ChangeValue(aNodeIter).Reverse(); } } @@ -586,9 +621,13 @@ void Part::Tools::getPointNormals(const TopoDS_Face& theFace, Handle(Poly_Triang #endif } -void Part::Tools::getPointNormals(const TopoDS_Face& face, Handle(Poly_Triangulation) aPoly, std::vector& normals) +void Part::Tools::getPointNormals( + const TopoDS_Face& face, + Handle(Poly_Triangulation) aPoly, + std::vector& normals +) { - TColgp_Array1OfDir dirs (1, aPoly->NbNodes()); + TColgp_Array1OfDir dirs(1, aPoly->NbNodes()); getPointNormals(face, aPoly, dirs); normals.reserve(aPoly->NbNodes()); @@ -608,15 +647,16 @@ void Part::Tools::applyTransformationOnNormals(const TopLoc_Location& loc, std:: } } -Handle (Poly_Triangulation) Part::Tools::triangulationOfFace(const TopoDS_Face& face) +Handle(Poly_Triangulation) Part::Tools::triangulationOfFace(const TopoDS_Face& face) { TopLoc_Location loc; - Handle (Poly_Triangulation) mesh = BRep_Tool::Triangulation(face, loc); - if (!mesh.IsNull()) + Handle(Poly_Triangulation) mesh = BRep_Tool::Triangulation(face, loc); + if (!mesh.IsNull()) { return mesh; + } // If no triangulation exists then the shape is probably infinite - double u1{}, u2{}, v1{}, v2{}; + double u1 {}, u2 {}, v1 {}, v2 {}; try { BRepAdaptor_Surface adapt(face); u1 = adapt.FirstUParameter(); @@ -631,7 +671,7 @@ Handle (Poly_Triangulation) Part::Tools::triangulationOfFace(const TopoDS_Face& auto selectRange = [](double& p1, double& p2) { if (Precision::IsInfinite(p1) && Precision::IsInfinite(p2)) { p1 = -50.0; - p2 = 50.0; + p2 = 50.0; } else if (Precision::IsInfinite(p1)) { p1 = p2 - 100.0; @@ -646,10 +686,10 @@ Handle (Poly_Triangulation) Part::Tools::triangulationOfFace(const TopoDS_Face& selectRange(v1, v2); Handle(Geom_Surface) surface = BRep_Tool::Surface(face); - if ( surface.IsNull() ) { + if (surface.IsNull()) { FC_THROWM(Base::CADKernelError, "Cannot create surface from face"); } - BRepBuilderAPI_MakeFace mkBuilder(surface, u1, u2, v1, v2, Precision::Confusion() ); + BRepBuilderAPI_MakeFace mkBuilder(surface, u1, u2, v1, v2, Precision::Confusion()); TopoDS_Shape shape = mkBuilder.Shape(); shape.Location(loc); @@ -663,12 +703,13 @@ Handle(Poly_Polygon3D) Part::Tools::polygonOfEdge(const TopoDS_Edge& edge, TopLo double u = adapt.FirstParameter(); double v = adapt.LastParameter(); Handle(Poly_Polygon3D) aPoly = BRep_Tool::Polygon3D(edge, loc); - if (!aPoly.IsNull() && !Precision::IsInfinite(u) && !Precision::IsInfinite(v)) + if (!aPoly.IsNull() && !Precision::IsInfinite(u) && !Precision::IsInfinite(v)) { return aPoly; + } // recreate an edge with a clear range u = std::max(-50.0, u); - v = std::min( 50.0, v); + v = std::min(50.0, v); double uv; Handle(Geom_Curve) curve = BRep_Tool::Curve(edge, uv, uv); @@ -686,46 +727,65 @@ Handle(Poly_Polygon3D) Part::Tools::polygonOfEdge(const TopoDS_Edge& edge, TopLo // helper function to use in getNormal, here we pass the local properties // of the surface given by the #LProp_SLProps objects -template -void getNormalBySLProp(T& prop, double u, double v, Standard_Real lastU, Standard_Real lastV, - const Standard_Real tol, gp_Dir& dir, Standard_Boolean& done) +template +void getNormalBySLProp( + T& prop, + double u, + double v, + Standard_Real lastU, + Standard_Real lastV, + const Standard_Real tol, + gp_Dir& dir, + Standard_Boolean& done +) { - if (prop.D1U().Magnitude() > tol && - prop.D1V().Magnitude() > tol && - prop.IsNormalDefined()) { + if (prop.D1U().Magnitude() > tol && prop.D1V().Magnitude() > tol && prop.IsNormalDefined()) { dir = prop.Normal(); done = Standard_True; } // use an alternative method in case of a null normal else { CSLib_NormalStatus stat; - CSLib::Normal(prop.D1U(), prop.D1V(), prop.D2U(), prop.D2V(), prop.DUV(), - tol, done, stat, dir); + CSLib::Normal(prop.D1U(), prop.D1V(), prop.D2U(), prop.D2V(), prop.DUV(), tol, done, stat, dir); // at the right boundary, the normal is flipped with respect to the // normal on surrounding points. if (stat == CSLib_D1NuIsNull) { - if (Abs(lastV - v) < tol) + if (Abs(lastV - v) < tol) { dir.Reverse(); + } } else if (stat == CSLib_D1NvIsNull || stat == CSLib_D1NuIsParallelD1Nv) { - if (Abs(lastU - u) < tol) + if (Abs(lastU - u) < tol) { dir.Reverse(); + } } } } -void Part::Tools::getNormal(const Handle(Geom_Surface)& surf, double u, double v, - const Standard_Real tol, gp_Dir& dir, Standard_Boolean& done) +void Part::Tools::getNormal( + const Handle(Geom_Surface) & surf, + double u, + double v, + const Standard_Real tol, + gp_Dir& dir, + Standard_Boolean& done +) { GeomLProp_SLProps prop(surf, u, v, 1, tol); - Standard_Real u1,u2,v1,v2; - surf->Bounds(u1,u2,v1,v2); + Standard_Real u1, u2, v1, v2; + surf->Bounds(u1, u2, v1, v2); getNormalBySLProp(prop, u, v, u2, v2, tol, dir, done); } -void Part::Tools::getNormal(const TopoDS_Face& face, double u, double v, - const Standard_Real tol, gp_Dir& dir, Standard_Boolean& done) +void Part::Tools::getNormal( + const TopoDS_Face& face, + double u, + double v, + const Standard_Real tol, + gp_Dir& dir, + Standard_Boolean& done +) { BRepAdaptor_Surface adapt(face); BRepLProp_SLProps prop(adapt, u, v, 1, tol); @@ -734,8 +794,9 @@ void Part::Tools::getNormal(const TopoDS_Face& face, double u, double v, getNormalBySLProp(prop, u, v, u2, v2, tol, dir, done); - if (face.Orientation() == TopAbs_REVERSED) + if (face.Orientation() == TopAbs_REVERSED) { dir.Reverse(); + } } TopLoc_Location Part::Tools::fromPlacement(const Base::Placement& plm) @@ -750,9 +811,7 @@ TopLoc_Location Part::Tools::fromPlacement(const Base::Placement& plm) return {trf}; } -bool Part::Tools::isConcave(const TopoDS_Face& face, - const gp_Pnt& pointOfVue, - const gp_Dir& direction) +bool Part::Tools::isConcave(const TopoDS_Face& face, const gp_Pnt& pointOfVue, const gp_Dir& direction) { bool result = false; diff --git a/src/Mod/Part/App/Tools.h b/src/Mod/Part/App/Tools.h index c3f1a2ed9e..88bed90f18 100644 --- a/src/Mod/Part/App/Tools.h +++ b/src/Mod/Part/App/Tools.h @@ -53,75 +53,95 @@ class gp_Lin; class gp_Pln; class Bnd_Box; -namespace Base { +namespace Base +{ // Specialization for gp_Pnt -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = gp_Pnt; using float_type = double; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.X(), v.Y(), v.Z()); } + private: const vec_type& v; }; // Specialization for gp_Vec -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = gp_Vec; using float_type = double; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.X(), v.Y(), v.Z()); } + private: const vec_type& v; }; // Specialization for gp_Dir -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = gp_Dir; using float_type = double; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.X(), v.Y(), v.Z()); } + private: const vec_type& v; }; // Specialization for gp_XYZ -template <> -struct vec_traits { +template<> +struct vec_traits +{ using vec_type = gp_XYZ; using float_type = double; - explicit vec_traits(const vec_type& v) : v(v){} - inline std::tuple get() const { + explicit vec_traits(const vec_type& v) + : v(v) + {} + inline std::tuple get() const + { return std::make_tuple(v.X(), v.Y(), v.Z()); } + private: const vec_type& v; }; -} +} // namespace Base namespace Part { -PartExport -void closestPointsOnLines(const gp_Lin& lin1, const gp_Lin& lin2, gp_Pnt &p1, gp_Pnt &p2); -PartExport -bool intersect(const gp_Pln& pln1, const gp_Pln& pln2, gp_Lin& lin); -PartExport -bool tangentialArc(const gp_Pnt& p0, const gp_Vec& v0, const gp_Pnt& p1, gp_Pnt& c, gp_Dir& a); +PartExport void closestPointsOnLines(const gp_Lin& lin1, const gp_Lin& lin2, gp_Pnt& p1, gp_Pnt& p2); +PartExport bool intersect(const gp_Pln& pln1, const gp_Pln& pln2, gp_Lin& lin); +PartExport bool tangentialArc(const gp_Pnt& p0, const gp_Vec& v0, const gp_Pnt& p1, gp_Pnt& c, gp_Dir& a); class PartExport Tools { public: - Handle(Geom_Surface) makeSurface (const TColStd_ListOfTransient& theBoundaries, - const Standard_Real theTol, - const Standard_Integer theNbPnts, - const Standard_Integer theNbIter, - const Standard_Integer theMaxDeg); + Handle(Geom_Surface) makeSurface( + const TColStd_ListOfTransient& theBoundaries, + const Standard_Real theTol, + const Standard_Integer theNbPnts, + const Standard_Integer theNbIter, + const Standard_Integer theMaxDeg + ); /*! * @brief getTriangulation * The indexes of the triangles are adjusted to the points vector. @@ -130,7 +150,11 @@ public: * @param facets * @return true if a triangulation exists or false otherwise */ - static bool getTriangulation(const TopoDS_Face& face, std::vector& points, std::vector& facets); + static bool getTriangulation( + const TopoDS_Face& face, + std::vector& points, + std::vector& facets + ); /*! * \brief getPolygonOnTriangulation * Get the polygon of edge. @@ -140,7 +164,11 @@ public: * \param points * \return true if a triangulation exists or false otherwise */ - static bool getPolygonOnTriangulation(const TopoDS_Edge& edge, const TopoDS_Face& face, std::vector& points); + static bool getPolygonOnTriangulation( + const TopoDS_Edge& edge, + const TopoDS_Face& face, + std::vector& points + ); /*! * \brief getPolygon3D * \param edge @@ -155,32 +183,50 @@ public: * \param facets * \param normals */ - static void getPointNormals(const std::vector& points, const std::vector& facets, std::vector& vertexnormals); + static void getPointNormals( + const std::vector& points, + const std::vector& facets, + std::vector& vertexnormals + ); /*! * \brief getPointNormals - * Computes the more accurate surface normals for the points. If the calculation for a point fails then the precomputed - * point normal of the triangulation is used. + * Computes the more accurate surface normals for the points. If the calculation for a point + * fails then the precomputed point normal of the triangulation is used. * \param points * \param face * \param vertexnormals */ - static void getPointNormals(const std::vector& points, const TopoDS_Face& face, std::vector& vertexnormals); + static void getPointNormals( + const std::vector& points, + const TopoDS_Face& face, + std::vector& vertexnormals + ); /*! * \brief getPointNormals - * Computes the exact surface normals for the points by using the UV coordinates of the mesh vertexes. + * Computes the exact surface normals for the points by using the UV coordinates of the mesh + * vertexes. * \param face * \param aPoly * \param vertexnormals */ - static void getPointNormals(const TopoDS_Face& face, Handle(Poly_Triangulation) aPoly, TColgp_Array1OfDir& normals); + static void getPointNormals( + const TopoDS_Face& face, + Handle(Poly_Triangulation) aPoly, + TColgp_Array1OfDir& normals + ); /*! * \brief getPointNormals - * Computes the exact surface normals for the points by using the UV coordinates of the mesh vertexes. + * Computes the exact surface normals for the points by using the UV coordinates of the mesh + * vertexes. * \param face * \param aPoly * \param vertexnormals */ - static void getPointNormals(const TopoDS_Face& face, Handle(Poly_Triangulation) aPoly, std::vector& normals); + static void getPointNormals( + const TopoDS_Face& face, + Handle(Poly_Triangulation) aPoly, + std::vector& normals + ); /*! * \brief applyTransformationOnNormals * Apply the transformation to the vectors @@ -190,16 +236,16 @@ public: static void applyTransformationOnNormals(const TopLoc_Location& loc, std::vector& normals); /*! * \brief triangulationOfInfinite - * Returns the triangulation of the face of the tessellated shape. In case the face has infinite lengths - * the triangulation of a limited parameter range is computed. + * Returns the triangulation of the face of the tessellated shape. In case the face has infinite + * lengths the triangulation of a limited parameter range is computed. * \param edge * \param loc */ - static Handle (Poly_Triangulation) triangulationOfFace(const TopoDS_Face& face); + static Handle(Poly_Triangulation) triangulationOfFace(const TopoDS_Face& face); /*! * \brief polygonOfEdge - * Returns the polygon of the edge of the tessellated shape. In case the edge has infinite length - * the polygon of a limited parameter range is computed. + * Returns the polygon of the edge of the tessellated shape. In case the edge has infinite + * length the polygon of a limited parameter range is computed. * \param edge * \param loc */ @@ -214,7 +260,14 @@ public: * \param dir * \param done */ - static void getNormal(const Handle(Geom_Surface)& surf, double u, double v, const Standard_Real tol, gp_Dir& dir, Standard_Boolean& done); + static void getNormal( + const Handle(Geom_Surface) & surf, + double u, + double v, + const Standard_Real tol, + gp_Dir& dir, + Standard_Boolean& done + ); /*! \brief getNormal * Returns the normal at the given parameters on the face and the state of the calculation. * The orientation is taken into account @@ -225,7 +278,14 @@ public: * \param dir * \param done */ - static void getNormal(const TopoDS_Face& face, double u, double v, const Standard_Real tol, gp_Dir& dir, Standard_Boolean& done); + static void getNormal( + const TopoDS_Face& face, + double u, + double v, + const Standard_Real tol, + gp_Dir& dir, + Standard_Boolean& done + ); /*! * \brief fromPlacement * Converts a placement into a TopLoc_Location @@ -241,7 +301,7 @@ public: * \return true if the face is concave when shown from pointOfVue and looking into direction * and false otherwise, plane case included. */ - static bool isConcave(const TopoDS_Face &face, const gp_Pnt &pointOfVue, const gp_Dir &direction); + static bool isConcave(const TopoDS_Face& face, const gp_Pnt& pointOfVue, const gp_Dir& direction); /** * \copydoc Part::Tools::isShapeEmpty(const TopoDS_Shape&) @@ -304,7 +364,7 @@ public: static Standard_Real getDeflection(const TopoDS_Shape& shape, double deviation); }; -} //namespace Part +} // namespace Part -#endif // PART_TOOLS_H +#endif // PART_TOOLS_H diff --git a/src/Mod/Part/App/TopoShape.cpp b/src/Mod/Part/App/TopoShape.cpp index b814e5b78c..b706dae74e 100644 --- a/src/Mod/Part/App/TopoShape.cpp +++ b/src/Mod/Part/App/TopoShape.cpp @@ -24,141 +24,141 @@ #include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include +#include +#include -# include +#include #if OCC_VERSION_HEX < 0x070600 # include # include #endif -# include -# include +#include +#include #include #include @@ -191,26 +191,25 @@ #include "TopoShapeWirePy.h" #include "OCCTProgressIndicator.h" -FC_LOG_LEVEL_INIT("TopoShape",true,true) +FC_LOG_LEVEL_INIT("TopoShape", true, true) using namespace Part; const char* BRepBuilderAPI_FaceErrorText(BRepBuilderAPI_FaceError et) { - switch (et) - { - case BRepBuilderAPI_FaceDone: - return "Construction was successful"; - case BRepBuilderAPI_NoFace: - return "No face"; - case BRepBuilderAPI_NotPlanar: - return "Face is not planar"; - case BRepBuilderAPI_CurveProjectionFailed: - return "Curve projection failed"; - case BRepBuilderAPI_ParametersOutOfRange: - return "Parameters out of range"; - default: - return "Unknown creation error"; + switch (et) { + case BRepBuilderAPI_FaceDone: + return "Construction was successful"; + case BRepBuilderAPI_NoFace: + return "No face"; + case BRepBuilderAPI_NotPlanar: + return "Face is not planar"; + case BRepBuilderAPI_CurveProjectionFailed: + return "Curve projection failed"; + case BRepBuilderAPI_ParametersOutOfRange: + return "Parameters out of range"; + default: + return "Unknown creation error"; } } @@ -222,7 +221,8 @@ const char* BRepBuilderAPI_FaceErrorText(BRepBuilderAPI_FaceError et) * If needed for specific use cases, explicit angular deflection parameters can * still be exposed separately. */ -inline double defaultAngularDeflection(double linearTolerance) { +inline double defaultAngularDeflection(double linearTolerance) +{ // Default OCC angular deflection is 0.5 radians, or about 28.6 degrees. // That is a bit coarser than necessary for performance, so we default to at // most 0.1 radians, or 5.7 degrees. We also do not go finer than 0.005, or @@ -234,40 +234,34 @@ inline double defaultAngularDeflection(double linearTolerance) { // ------------------------------------------------ NullShapeException::NullShapeException() - : ValueError() -{ -} + : ValueError() +{} -NullShapeException::NullShapeException(const char * sMessage) - : ValueError(sMessage) -{ -} +NullShapeException::NullShapeException(const char* sMessage) + : ValueError(sMessage) +{} NullShapeException::NullShapeException(const std::string& sMessage) - : ValueError(sMessage) -{ -} + : ValueError(sMessage) +{} // ------------------------------------------------ BooleanException::BooleanException() - : CADKernelError() -{ -} + : CADKernelError() +{} -BooleanException::BooleanException(const char * sMessage) - : CADKernelError(sMessage) -{ -} +BooleanException::BooleanException(const char* sMessage) + : CADKernelError(sMessage) +{} BooleanException::BooleanException(const std::string& sMessage) - : CADKernelError(sMessage) -{ -} + : CADKernelError(sMessage) +{} // ------------------------------------------------ -TYPESYSTEM_SOURCE(Part::ShapeSegment , Data::Segment) +TYPESYSTEM_SOURCE(Part::ShapeSegment, Data::Segment) std::string ShapeSegment::getName() const { @@ -276,19 +270,19 @@ std::string ShapeSegment::getName() const // ------------------------------------------------ -TYPESYSTEM_SOURCE(Part::TopoShape , Data::ComplexGeoData) +TYPESYSTEM_SOURCE(Part::TopoShape, Data::ComplexGeoData) TopoShape::~TopoShape() = default; -TopoShape::TopoShape(long tag,App::StringHasherRef hasher, const TopoDS_Shape &shape) - :_Shape(*this, shape) +TopoShape::TopoShape(long tag, App::StringHasherRef hasher, const TopoDS_Shape& shape) + : _Shape(*this, shape) { Tag = tag; Hasher = hasher; } -TopoShape::TopoShape(const TopoDS_Shape &shape, long tag, App::StringHasherRef hasher) +TopoShape::TopoShape(const TopoDS_Shape& shape, long tag, App::StringHasherRef hasher) : _Shape(*this, shape) { Tag = tag; @@ -318,7 +312,7 @@ std::pair TopoShape::getElementTypeAndIndex(const ch std::vector TopoShape::getElementTypes() const { - static const std::vector temp = {"Face","Edge","Vertex"}; + static const std::vector temp = {"Face", "Edge", "Vertex"}; return temp; } @@ -336,37 +330,43 @@ Data::Segment* TopoShape::getSubElement(const char* Type, unsigned long n) const } // Type can be (should be?) a subshape name, not a type, E.G. Edge3 -TopoDS_Shape TopoShape::getSubShape(const char* Type, bool silent) const { +TopoDS_Shape TopoShape::getSubShape(const char* Type, bool silent) const +{ TopoShape s(*this); s.Tag = 0; - return s.getSubTopoShape(Type,silent).getShape(); + return s.getSubTopoShape(Type, silent).getShape(); } -TopoDS_Shape TopoShape::getSubShape(TopAbs_ShapeEnum type, int idx, bool silent) const { +TopoDS_Shape TopoShape::getSubShape(TopAbs_ShapeEnum type, int idx, bool silent) const +{ TopoShape s(*this); s.Tag = 0; - return s.getSubTopoShape(type,idx,silent).getShape(); + return s.getSubTopoShape(type, idx, silent).getShape(); } unsigned long TopoShape::countSubShapes(const char* Type) const { - if(!Type) + if (!Type) { return 0; - if(strcmp(Type,"SubShape")==0) + } + if (strcmp(Type, "SubShape") == 0) { return countSubShapes(TopAbs_SHAPE); - auto type = shapeType(Type,true); - if(type == TopAbs_SHAPE) + } + auto type = shapeType(Type, true); + if (type == TopAbs_SHAPE) { return 0; + } return countSubShapes(type); } unsigned long TopoShape::countSubShapes(TopAbs_ShapeEnum Type) const { - if(Type == TopAbs_SHAPE) { + if (Type == TopAbs_SHAPE) { int count = 0; - for(TopoDS_Iterator it(_Shape);it.More();it.Next()) + for (TopoDS_Iterator it(_Shape); it.More(); it.Next()) { ++count; + } return count; } TopTools_IndexedMapOfShape anIndices; @@ -374,29 +374,34 @@ unsigned long TopoShape::countSubShapes(TopAbs_ShapeEnum Type) const return anIndices.Extent(); } -bool TopoShape::hasSubShape(TopAbs_ShapeEnum type) const { - if(type == TopAbs_SHAPE) { +bool TopoShape::hasSubShape(TopAbs_ShapeEnum type) const +{ + if (type == TopAbs_SHAPE) { TopoDS_Iterator it(_Shape); return !!it.More(); } - TopExp_Explorer exp(_Shape,type); + TopExp_Explorer exp(_Shape, type); return !!exp.More(); } -bool TopoShape::hasSubShape(const char *Type) const { +bool TopoShape::hasSubShape(const char* Type) const +{ auto idx = shapeTypeAndIndex(Type); - return idx.second>0 && idx.second<=(int)countSubShapes(idx.first); + return idx.second > 0 && idx.second <= (int)countSubShapes(idx.first); } template -static inline std::vector _getSubShapes(const TopoDS_Shape &s, TopAbs_ShapeEnum type) { +static inline std::vector _getSubShapes(const TopoDS_Shape& s, TopAbs_ShapeEnum type) +{ std::vector shapes; - if(s.IsNull()) + if (s.IsNull()) { return shapes; + } - if(type == TopAbs_SHAPE) { - for(TopoDS_Iterator it(s);it.More();it.Next()) + if (type == TopAbs_SHAPE) { + for (TopoDS_Iterator it(s); it.More(); it.Next()) { shapes.emplace_back(it.Value()); + } return shapes; } @@ -404,15 +409,17 @@ static inline std::vector _getSubShapes(const TopoDS_Shape &s, TopAbs_ShapeEn TopExp::MapShapes(s, type, anIndices); int count = anIndices.Extent(); shapes.reserve(count); - for(int i=1;i<=count;++i) + for (int i = 1; i <= count; ++i) { shapes.emplace_back(anIndices.FindKey(i)); + } return shapes; } -static std::array _ShapeNames; +static std::array _ShapeNames; -static void initShapeNameMap() { - if(_ShapeNames[TopAbs_VERTEX].empty()) { +static void initShapeNameMap() +{ + if (_ShapeNames[TopAbs_VERTEX].empty()) { _ShapeNames[TopAbs_VERTEX] = "Vertex"; _ShapeNames[TopAbs_EDGE] = "Edge"; _ShapeNames[TopAbs_FACE] = "Face"; @@ -424,27 +431,30 @@ static void initShapeNameMap() { } } -std::pair TopoShape::shapeTypeAndIndex(const char *name) { +std::pair TopoShape::shapeTypeAndIndex(const char* name) +{ int idx = 0; TopAbs_ShapeEnum type = TopAbs_SHAPE; static const std::string _subshape("SubShape"); - if(boost::starts_with(name,_subshape)) { - std::istringstream iss(name+_subshape.size()); + if (boost::starts_with(name, _subshape)) { + std::istringstream iss(name + _subshape.size()); iss >> idx; - if(!iss.eof()) + if (!iss.eof()) { idx = 0; - } else { - type = shapeType(name,true); - if(type != TopAbs_SHAPE) { - std::istringstream iss(name+shapeName(type).size()); + } + } + else { + type = shapeType(name, true); + if (type != TopAbs_SHAPE) { + std::istringstream iss(name + shapeName(type).size()); iss >> idx; - if(!iss.eof()) { + if (!iss.eof()) { idx = 0; type = TopAbs_SHAPE; } } } - return std::make_pair(type,idx); + return std::make_pair(type, idx); } std::pair TopoShape::shapeTypeAndIndex(const Data::IndexedName& element) @@ -463,66 +473,77 @@ std::pair TopoShape::shapeTypeAndIndex(const Data::Indexe return std::make_pair(shapetype, element.getIndex()); } -TopAbs_ShapeEnum TopoShape::shapeType(const char *type, bool silent) { - if(type) { +TopAbs_ShapeEnum TopoShape::shapeType(const char* type, bool silent) +{ + if (type) { initShapeNameMap(); - for(size_t idx=0;idx<_ShapeNames.size();++idx) { - if(!_ShapeNames[idx].empty() && boost::starts_with(type,_ShapeNames[idx])) + for (size_t idx = 0; idx < _ShapeNames.size(); ++idx) { + if (!_ShapeNames[idx].empty() && boost::starts_with(type, _ShapeNames[idx])) { return static_cast(idx); + } } } - if(!silent) { - if(Data::hasMissingElement(type)) - FC_THROWM(Base::CADKernelError,"missing shape element: " << (type?type:"?")); - FC_THROWM(Base::CADKernelError,"invalid shape type: " << (type?type:"?")); + if (!silent) { + if (Data::hasMissingElement(type)) { + FC_THROWM(Base::CADKernelError, "missing shape element: " << (type ? type : "?")); + } + FC_THROWM(Base::CADKernelError, "invalid shape type: " << (type ? type : "?")); } return TopAbs_SHAPE; } -TopAbs_ShapeEnum TopoShape::shapeType(char type, bool silent) { - switch(type) { - case 'E': - return TopAbs_EDGE; - case 'V': - return TopAbs_VERTEX; - case 'F': - return TopAbs_FACE; - default: - if(!silent) - FC_THROWM(Base::CADKernelError, "invalid shape type '" << type << "'"); - return TopAbs_SHAPE; +TopAbs_ShapeEnum TopoShape::shapeType(char type, bool silent) +{ + switch (type) { + case 'E': + return TopAbs_EDGE; + case 'V': + return TopAbs_VERTEX; + case 'F': + return TopAbs_FACE; + default: + if (!silent) { + FC_THROWM(Base::CADKernelError, "invalid shape type '" << type << "'"); + } + return TopAbs_SHAPE; } } -TopAbs_ShapeEnum TopoShape::shapeType(bool silent) const { - if(isNull()) { - if(!silent) +TopAbs_ShapeEnum TopoShape::shapeType(bool silent) const +{ + if (isNull()) { + if (!silent) { FC_THROWM(NullShapeException, "Input shape is null"); + } return TopAbs_SHAPE; } return getShape().ShapeType(); } -const std::string &TopoShape::shapeName(TopAbs_ShapeEnum type, bool silent) { +const std::string& TopoShape::shapeName(TopAbs_ShapeEnum type, bool silent) +{ initShapeNameMap(); - if(type>=0 && type<_ShapeNames.size() && !_ShapeNames[type].empty()) + if (type >= 0 && type < _ShapeNames.size() && !_ShapeNames[type].empty()) { return _ShapeNames[type]; - if(!silent) + } + if (!silent) { FC_THROWM(Base::CADKernelError, "invalid shape type '" << type << "'"); + } static std::string ret; return ret; } -const std::string &TopoShape::shapeName(bool silent) const { - return shapeName(shapeType(silent),silent); -} - -PyObject * TopoShape::getPySubShape(const char* Type, bool silent) const +const std::string& TopoShape::shapeName(bool silent) const { - return Py::new_reference_to(shape2pyshape(getSubShape(Type,silent))); + return shapeName(shapeType(silent), silent); } -PyObject * TopoShape::getPyObject() +PyObject* TopoShape::getPySubShape(const char* Type, bool silent) const +{ + return Py::new_reference_to(shape2pyshape(getSubShape(Type, silent))); +} + +PyObject* TopoShape::getPyObject() { Base::PyObjectBase* prop = nullptr; if (_Shape.IsNull()) { @@ -530,40 +551,39 @@ PyObject * TopoShape::getPyObject() } else { TopAbs_ShapeEnum type = _Shape.ShapeType(); - switch (type) - { - case TopAbs_COMPOUND: - prop = new TopoShapeCompoundPy(new TopoShape(*this)); - break; - case TopAbs_COMPSOLID: - prop = new TopoShapeCompSolidPy(new TopoShape(*this)); - break; - case TopAbs_SOLID: - prop = new TopoShapeSolidPy(new TopoShape(*this)); - break; - case TopAbs_SHELL: - prop = new TopoShapeShellPy(new TopoShape(*this)); - break; - case TopAbs_FACE: - prop = new TopoShapeFacePy(new TopoShape(*this)); - break; - case TopAbs_WIRE: - prop = new TopoShapeWirePy(new TopoShape(*this)); - break; - case TopAbs_EDGE: - prop = new TopoShapeEdgePy(new TopoShape(*this)); - break; - case TopAbs_VERTEX: - prop = new TopoShapeVertexPy(new TopoShape(*this)); - break; - case TopAbs_SHAPE: - default: - prop = new TopoShapePy(new TopoShape(*this)); - break; + switch (type) { + case TopAbs_COMPOUND: + prop = new TopoShapeCompoundPy(new TopoShape(*this)); + break; + case TopAbs_COMPSOLID: + prop = new TopoShapeCompSolidPy(new TopoShape(*this)); + break; + case TopAbs_SOLID: + prop = new TopoShapeSolidPy(new TopoShape(*this)); + break; + case TopAbs_SHELL: + prop = new TopoShapeShellPy(new TopoShape(*this)); + break; + case TopAbs_FACE: + prop = new TopoShapeFacePy(new TopoShape(*this)); + break; + case TopAbs_WIRE: + prop = new TopoShapeWirePy(new TopoShape(*this)); + break; + case TopAbs_EDGE: + prop = new TopoShapeEdgePy(new TopoShape(*this)); + break; + case TopAbs_VERTEX: + prop = new TopoShapeVertexPy(new TopoShape(*this)); + break; + case TopAbs_SHAPE: + default: + prop = new TopoShapePy(new TopoShape(*this)); + break; } } - prop->setNotTracking(); // TODO: Does this still belong here? + prop->setNotTracking(); // TODO: Does this still belong here? return prop; } @@ -579,19 +599,30 @@ void TopoShape::setPyObject(PyObject* obj) } } -//void TopoShape::operator = (const TopoShape& sh) +// void TopoShape::operator = (const TopoShape& sh) //{ -// if (this != &sh) { -// this->Tag = sh.Tag; -// this->_Shape = sh._Shape; -// } -//} +// if (this != &sh) { +// this->Tag = sh.Tag; +// this->_Shape = sh._Shape; +// } +// } void TopoShape::convertTogpTrsf(const Base::Matrix4D& mtrx, gp_Trsf& trsf) { - trsf.SetValues(mtrx[0][0],mtrx[0][1],mtrx[0][2],mtrx[0][3], - mtrx[1][0],mtrx[1][1],mtrx[1][2],mtrx[1][3], - mtrx[2][0],mtrx[2][1],mtrx[2][2],mtrx[2][3]); + trsf.SetValues( + mtrx[0][0], + mtrx[0][1], + mtrx[0][2], + mtrx[0][3], + mtrx[1][0], + mtrx[1][1], + mtrx[1][2], + mtrx[1][3], + mtrx[2][0], + mtrx[2][1], + mtrx[2][2], + mtrx[2][3] + ); } void TopoShape::convertToMatrix(const gp_Trsf& trsf, Base::Matrix4D& mtrx) @@ -602,17 +633,17 @@ void TopoShape::convertToMatrix(const gp_Trsf& trsf, Base::Matrix4D& mtrx) gp_XYZ p = trsf.TranslationPart(); // set Rotation matrix - mtrx[0][0] = m(1,1); - mtrx[0][1] = m(1,2); - mtrx[0][2] = m(1,3); + mtrx[0][0] = m(1, 1); + mtrx[0][1] = m(1, 2); + mtrx[0][2] = m(1, 3); - mtrx[1][0] = m(2,1); - mtrx[1][1] = m(2,2); - mtrx[1][2] = m(2,3); + mtrx[1][0] = m(2, 1); + mtrx[1][1] = m(2, 2); + mtrx[1][2] = m(2, 3); - mtrx[2][0] = m(3,1); - mtrx[2][1] = m(3,2); - mtrx[2][2] = m(3,3); + mtrx[2][0] = m(3, 1); + mtrx[2][1] = m(3, 2); + mtrx[2][2] = m(3, 3); // set pos vector mtrx[0][3] = p.X(); @@ -620,15 +651,17 @@ void TopoShape::convertToMatrix(const gp_Trsf& trsf, Base::Matrix4D& mtrx) mtrx[2][3] = p.Z(); } -Base::Matrix4D TopoShape::convert(const gp_Trsf& trsf) { +Base::Matrix4D TopoShape::convert(const gp_Trsf& trsf) +{ Base::Matrix4D mat; - convertToMatrix(trsf,mat); + convertToMatrix(trsf, mat); return mat; } -gp_Trsf TopoShape::convert(const Base::Matrix4D& mtrx) { +gp_Trsf TopoShape::convert(const Base::Matrix4D& mtrx) +{ gp_Trsf trsf; - convertTogpTrsf(mtrx,trsf); + convertTogpTrsf(mtrx, trsf); return trsf; } @@ -650,13 +683,14 @@ Base::Matrix4D TopoShape::getTransform() const } -void TopoShape::read(const char *FileName) +void TopoShape::read(const char* FileName) { Base::FileInfo File(FileName); // checking on the file - if (!File.isReadable()) + if (!File.isReadable()) { throw Base::FileException("File to load not existing or not readable", FileName); + } if (File.hasExtension({"igs", "iges"})) { // read iges file @@ -669,7 +703,7 @@ void TopoShape::read(const char *FileName) // read brep-file importBrep(File.filePath().c_str()); } - else{ + else { throw Base::FileException("Unknown extension"); } } @@ -708,7 +742,7 @@ for (ex.Init(this->_Shape, TopAbs_FACE); ex.More(); ex.Next()) } \endcode */ -void TopoShape::importIges(const char *FileName) +void TopoShape::importIges(const char* FileName) { try { // read iges file @@ -717,8 +751,9 @@ void TopoShape::importIges(const char *FileName) // Ignore construction elements // http://www.opencascade.org/org/forum/thread_20603/?forum=3 aReader.SetReadVisible(Standard_True); - if (aReader.ReadFile(encodeFilename(FileName).c_str()) != IFSelect_RetDone) + if (aReader.ReadFile(encodeFilename(FileName).c_str()) != IFSelect_RetDone) { throw Base::FileException("Error in reading IGES"); + } // make brep aReader.ClearShapes(); @@ -731,12 +766,13 @@ void TopoShape::importIges(const char *FileName) } } -void TopoShape::importStep(const char *FileName) +void TopoShape::importStep(const char* FileName) { try { STEPControl_Reader aReader; - if (aReader.ReadFile(encodeFilename(FileName).c_str()) != IFSelect_RetDone) + if (aReader.ReadFile(encodeFilename(FileName).c_str()) != IFSelect_RetDone) { throw Base::FileException("Error in reading STEP"); + } // Root transfers aReader.TransferRoots(); @@ -748,13 +784,13 @@ void TopoShape::importStep(const char *FileName) } } -void TopoShape::importBrep(const char *FileName) +void TopoShape::importBrep(const char* FileName) { try { // read brep-file BRep_Builder aBuilder; TopoDS_Shape aShape; - BRepTools::Read(aShape,static_cast(FileName),aBuilder); + BRepTools::Read(aShape, static_cast(FileName), aBuilder); this->_Shape = aShape; } catch (Standard_Failure& e) { @@ -769,7 +805,7 @@ void TopoShape::importBrep(std::istream& str, int indicator) BRep_Builder aBuilder; TopoDS_Shape aShape; (void)indicator; - BRepTools::Read(aShape,str,aBuilder); + BRepTools::Read(aShape, str, aBuilder); this->_Shape = aShape; } catch (Standard_Failure& e) { @@ -784,10 +820,11 @@ void TopoShape::importBinary(std::istream& str) { BinTools_ShapeSet theShapeSet; theShapeSet.Read(str); - Standard_Integer shapeId=0, locId=0, orient=0; + Standard_Integer shapeId = 0, locId = 0, orient = 0; BinTools::GetInteger(str, shapeId); - if (shapeId <= 0 || shapeId > theShapeSet.NbShapes()) + if (shapeId <= 0 || shapeId > theShapeSet.NbShapes()) { return; + } BinTools::GetInteger(str, locId); BinTools::GetInteger(str, orient); @@ -795,15 +832,15 @@ void TopoShape::importBinary(std::istream& str) try { this->_Shape = theShapeSet.Shape(shapeId); - this->_Shape.Location(theShapeSet.Locations().Location (locId)); - this->_Shape.Orientation (anOrient); + this->_Shape.Location(theShapeSet.Locations().Location(locId)); + this->_Shape.Orientation(anOrient); } catch (Standard_Failure&) { throw Base::RuntimeError("Failed to read shape from binary stream"); } } -void TopoShape::write(const char *FileName) const +void TopoShape::write(const char* FileName) const { Base::FileInfo File(FileName); @@ -822,12 +859,12 @@ void TopoShape::write(const char *FileName) const // read brep-file exportStl(File.filePath().c_str(), 0.01); } - else{ + else { throw Base::FileException("Unknown extension"); } } -void TopoShape::exportIges(const char *filename) const +void TopoShape::exportIges(const char* filename) const { try { // write iges file @@ -840,15 +877,16 @@ void TopoShape::exportIges(const char *filename) const aWriter.Model()->SetGlobalSection(header); aWriter.AddShape(this->_Shape); aWriter.ComputeModel(); - if (aWriter.Write(encodeFilename(filename).c_str()) != IFSelect_RetDone) + if (aWriter.Write(encodeFilename(filename).c_str()) != IFSelect_RetDone) { throw Base::FileException("Writing of IGES failed"); + } } catch (Standard_Failure& e) { throw Base::CADKernelError(e.GetMessageString()); } } -void TopoShape::exportStep(const char *filename) const +void TopoShape::exportStep(const char* filename) const { try { // Fixes issue #6282 @@ -858,43 +896,54 @@ void TopoShape::exportStep(const char *filename) const // write step file STEPControl_Writer aWriter; - const Handle(XSControl_TransferWriter)& hTransferWriter = aWriter.WS()->TransferWriter(); + const Handle(XSControl_TransferWriter) & hTransferWriter = aWriter.WS()->TransferWriter(); Handle(Transfer_FinderProcess) hFinder = hTransferWriter->FinderProcess(); - if (aWriter.Transfer(this->_Shape, STEPControl_AsIs) != IFSelect_RetDone) + if (aWriter.Transfer(this->_Shape, STEPControl_AsIs) != IFSelect_RetDone) { throw Base::FileException("Error in transferring STEP"); + } APIHeaderSection_MakeHeader makeHeader(aWriter.Model()); // Don't set name because STEP doesn't support UTF-8 // https://forum.freecad.org/viewtopic.php?f=8&t=52967 - makeHeader.SetAuthorValue (1, new TCollection_HAsciiString("FreeCAD")); - makeHeader.SetOrganizationValue (1, new TCollection_HAsciiString("FreeCAD")); + makeHeader.SetAuthorValue(1, new TCollection_HAsciiString("FreeCAD")); + makeHeader.SetOrganizationValue(1, new TCollection_HAsciiString("FreeCAD")); makeHeader.SetOriginatingSystem(new TCollection_HAsciiString("FreeCAD")); makeHeader.SetDescriptionValue(1, new TCollection_HAsciiString("FreeCAD Model")); - if (aWriter.Write(encodeFilename(filename).c_str()) != IFSelect_RetDone) + if (aWriter.Write(encodeFilename(filename).c_str()) != IFSelect_RetDone) { throw Base::FileException("Writing of STEP failed"); + } } catch (Standard_Failure& e) { throw Base::CADKernelError(e.GetMessageString()); } } -void TopoShape::exportBrep(const char *filename) const +void TopoShape::exportBrep(const char* filename) const { #if OCC_VERSION_HEX >= 0x070600 - if (!BRepTools::Write(this->_Shape,encodeFilename(filename).c_str(), Standard_False, Standard_False, TopTools_FormatVersion_VERSION_1)) + if (!BRepTools::Write( + this->_Shape, + encodeFilename(filename).c_str(), + Standard_False, + Standard_False, + TopTools_FormatVersion_VERSION_1 + )) { throw Base::FileException("Writing of BREP failed"); + } #else - if (!BRepTools::Write(this->_Shape,encodeFilename(filename).c_str())) + if (!BRepTools::Write(this->_Shape, encodeFilename(filename).c_str())) { throw Base::FileException("Writing of BREP failed"); + } #endif } void TopoShape::exportBrep(std::ostream& out) const { // See TopTools_FormatVersion of OCCT 7.6 - enum { + enum + { VERSION_1 = 1, VERSION_2 = 2, VERSION_3 = 3 @@ -909,7 +958,8 @@ void TopoShape::exportBrep(std::ostream& out) const void TopoShape::exportBinary(std::ostream& out) const { // See BinTools_FormatVersion of OCCT 7.6 - enum { + enum + { VERSION_1 = 1, VERSION_2 = 2, VERSION_3 = 3, @@ -943,20 +993,26 @@ void TopoShape::dump(std::ostream& out) const BRepTools::Dump(this->_Shape, out); } -void TopoShape::exportStl(const char *filename, double deflection) const +void TopoShape::exportStl(const char* filename, double deflection) const { StlAPI_Writer writer; - BRepMesh_IncrementalMesh aMesh(this->_Shape, deflection, - /*isRelative*/ Standard_False, - /*theAngDeflection*/ - defaultAngularDeflection(deflection), - /*isInParallel*/ true); - writer.Write(this->_Shape,encodeFilename(filename).c_str()); + BRepMesh_IncrementalMesh aMesh( + this->_Shape, + deflection, + /*isRelative*/ Standard_False, + /*theAngDeflection*/ + defaultAngularDeflection(deflection), + /*isInParallel*/ true + ); + writer.Write(this->_Shape, encodeFilename(filename).c_str()); } -void TopoShape::exportFaceSet(double dev, double ca, - const std::vector& colors, - std::ostream& str) const +void TopoShape::exportFaceSet( + double dev, + double ca, + const std::vector& colors, + std::ostream& str +) const { Base::InventorBuilder builder(str); builder.beginSeparator(); @@ -968,19 +1024,23 @@ void TopoShape::exportFaceSet(double dev, double ca, bool supportFaceColors = (numFaces == colors.size()); - std::size_t index=0; - BRepMesh_IncrementalMesh MESH(this->_Shape, dev, - /*isRelative*/ Standard_False, - /*theAngDeflection*/ - defaultAngularDeflection(dev), - /*isInParallel*/ true); + std::size_t index = 0; + BRepMesh_IncrementalMesh MESH( + this->_Shape, + dev, + /*isRelative*/ Standard_False, + /*theAngDeflection*/ + defaultAngularDeflection(dev), + /*isInParallel*/ true + ); for (ex.Init(this->_Shape, TopAbs_FACE); ex.More(); ex.Next(), index++) { // get the shape and mesh it const TopoDS_Face& aFace = TopoDS::Face(ex.Current()); std::vector points; std::vector facets; - if (!Tools::getTriangulation(aFace, points, facets)) + if (!Tools::getTriangulation(aFace, points, facets)) { continue; + } std::vector vertices; std::vector indices; @@ -992,28 +1052,28 @@ void TopoShape::exportFaceSet(double dev, double ca, } for (std::size_t i = 0; i < facets.size(); i++) { - Standard_Integer n1,n2,n3; + Standard_Integer n1, n2, n3; facets[i].Get(n1, n2, n3); - indices[4 * i ] = n1; + indices[4 * i] = n1; indices[4 * i + 1] = n2; indices[4 * i + 2] = n3; indices[4 * i + 3] = -1; } builder.beginSeparator(); - Base::ShapeHintsItem shapeHints{static_cast(ca)}; + Base::ShapeHintsItem shapeHints {static_cast(ca)}; builder.addNode(shapeHints); if (supportFaceColors) { Base::Color c = colors[index]; Base::MaterialItem material; - material.setDiffuseColor({Base::ColorRGB{c.r, c.g, c.b}}); + material.setDiffuseColor({Base::ColorRGB {c.r, c.g, c.b}}); material.setTransparency({c.a}); builder.addNode(material); } - Base::Coordinate3Item coords{vertices}; + Base::Coordinate3Item coords {vertices}; builder.addNode(coords); - Base::IndexedFaceSetItem faceSet{indices}; + Base::IndexedFaceSetItem faceSet {indices}; builder.addNode(faceSet); builder.endSeparator(); } @@ -1032,8 +1092,8 @@ void TopoShape::exportLineSet(std::ostream& str) const TopTools_IndexedDataMapOfShapeListOfShape edge2Face; TopExp::MapShapesAndAncestors(this->_Shape, TopAbs_EDGE, TopAbs_FACE, edge2Face); - for (int i=0; i points; if (!Tools::getPolygon3D(aEdge, points)) { @@ -1042,8 +1102,9 @@ void TopoShape::exportLineSet(std::ostream& str) const // Look for one face in our map (it doesn't care which one we take) const TopoDS_Face& aFace = TopoDS::Face(edge2Face.FindFromKey(aEdge).First()); - if (!Tools::getPolygonOnTriangulation(aEdge, aFace, points)) + if (!Tools::getPolygonOnTriangulation(aEdge, aFace, points)) { continue; + } } std::vector vertices; @@ -1054,7 +1115,7 @@ void TopoShape::exportLineSet(std::ostream& str) const Base::DrawStyle drawStyle; drawStyle.lineWidth = 2.0F; - builder.addNode(Base::MultiLineItem{vertices, drawStyle, Base::ColorRGB{0, 0, 0}}); + builder.addNode(Base::MultiLineItem {vertices, drawStyle, Base::ColorRGB {0, 0, 0}}); } builder.endSeparator(); @@ -1108,7 +1169,8 @@ Base::BoundBox3d TopoShape::getBoundBoxOptimal() const return box; } -namespace { +namespace +{ bool getShapeProperties(const TopoDS_Shape& shape, GProp_GProps& prop) { TopExp_Explorer xpSolid(shape, TopAbs_SOLID); @@ -1151,12 +1213,13 @@ bool getShapeProperties(const TopoDS_Shape& shape, GProp_GProps& prop) return false; } -} +} // namespace bool TopoShape::getCenterOfGravity(Base::Vector3d& center) const { - if (_Shape.IsNull()) + if (_Shape.IsNull()) { return false; + } // Computing of CentreOfMass GProp_GProps prop; @@ -1172,22 +1235,22 @@ bool TopoShape::getCenterOfGravity(Base::Vector3d& center) const return false; } -void TopoShape::Save (Base::Writer &writer ) const +void TopoShape::Save(Base::Writer& writer) const { Data::ComplexGeoData::Save(writer); } -void TopoShape::Restore(Base::XMLReader &reader) +void TopoShape::Restore(Base::XMLReader& reader) { Data::ComplexGeoData::Restore(reader); } -void TopoShape::SaveDocFile (Base::Writer &writer) const +void TopoShape::SaveDocFile(Base::Writer& writer) const { Data::ComplexGeoData::SaveDocFile(writer); } -void TopoShape::RestoreDocFile(Base::Reader &reader) +void TopoShape::RestoreDocFile(Base::Reader& reader) { Data::ComplexGeoData::RestoreDocFile(reader); } @@ -1195,40 +1258,40 @@ void TopoShape::RestoreDocFile(Base::Reader &reader) unsigned int TopoShape_RefCountShapes(const TopoDS_Shape& aShape) { - unsigned int size = 1; // this shape + unsigned int size = 1; // this shape TopoDS_Iterator it; // go through all direct children - for (it.Initialize(aShape, false, false);it.More(); it.Next()) { + for (it.Initialize(aShape, false, false); it.More(); it.Next()) { size += TopoShape_RefCountShapes(it.Value()); } return size; } -unsigned int TopoShape::getMemSize () const +unsigned int TopoShape::getMemSize() const { if (!_Shape.IsNull()) { // Count total amount of references of TopoDS_Shape objects - unsigned int memsize = (sizeof(TopoDS_Shape)+sizeof(TopoDS_TShape)) * TopoShape_RefCountShapes(_Shape); + unsigned int memsize = (sizeof(TopoDS_Shape) + sizeof(TopoDS_TShape)) + * TopoShape_RefCountShapes(_Shape); // Now get a map of TopoDS_Shape objects without duplicates TopTools_IndexedMapOfShape M; TopExp::MapShapes(_Shape, M); - for (int i=0; iDynamicType()->Size(); - switch (shape.ShapeType()) - { - case TopAbs_FACE: - { + switch (shape.ShapeType()) { + case TopAbs_FACE: { // first, last, tolerance - memsize += 5*sizeof(Standard_Real); + memsize += 5 * sizeof(Standard_Real); const TopoDS_Face& face = TopoDS::Face(shape); // if no geometry is attached to a face an exception is raised BRepAdaptor_Surface surface; @@ -1239,52 +1302,55 @@ unsigned int TopoShape::getMemSize () const continue; } - switch (surface.GetType()) - { - case GeomAbs_Plane: - memsize += sizeof(Geom_Plane); - break; - case GeomAbs_Cylinder: - memsize += sizeof(Geom_CylindricalSurface); - break; - case GeomAbs_Cone: - memsize += sizeof(Geom_ConicalSurface); - break; - case GeomAbs_Sphere: - memsize += sizeof(Geom_SphericalSurface); - break; - case GeomAbs_Torus: - memsize += sizeof(Geom_ToroidalSurface); - break; - case GeomAbs_BezierSurface: - memsize += sizeof(Geom_BezierSurface); - memsize += (surface.NbUPoles()*surface.NbVPoles()) * sizeof(Standard_Real); - memsize += (surface.NbUPoles()*surface.NbVPoles()) * sizeof(Geom_CartesianPoint); - break; - case GeomAbs_BSplineSurface: - memsize += sizeof(Geom_BSplineSurface); - memsize += (surface.NbUKnots()+surface.NbVKnots()) * sizeof(Standard_Real); - memsize += (surface.NbUPoles()*surface.NbVPoles()) * sizeof(Standard_Real); - memsize += (surface.NbUPoles()*surface.NbVPoles()) * sizeof(Geom_CartesianPoint); - break; - case GeomAbs_SurfaceOfRevolution: - memsize += sizeof(Geom_SurfaceOfRevolution); - break; - case GeomAbs_SurfaceOfExtrusion: - memsize += sizeof(Geom_SurfaceOfLinearExtrusion); - break; - case GeomAbs_OtherSurface: - // What kind of surface should this be? - memsize += sizeof(Geom_Surface); - break; - default: - break; + switch (surface.GetType()) { + case GeomAbs_Plane: + memsize += sizeof(Geom_Plane); + break; + case GeomAbs_Cylinder: + memsize += sizeof(Geom_CylindricalSurface); + break; + case GeomAbs_Cone: + memsize += sizeof(Geom_ConicalSurface); + break; + case GeomAbs_Sphere: + memsize += sizeof(Geom_SphericalSurface); + break; + case GeomAbs_Torus: + memsize += sizeof(Geom_ToroidalSurface); + break; + case GeomAbs_BezierSurface: + memsize += sizeof(Geom_BezierSurface); + memsize += (surface.NbUPoles() * surface.NbVPoles()) + * sizeof(Standard_Real); + memsize += (surface.NbUPoles() * surface.NbVPoles()) + * sizeof(Geom_CartesianPoint); + break; + case GeomAbs_BSplineSurface: + memsize += sizeof(Geom_BSplineSurface); + memsize += (surface.NbUKnots() + surface.NbVKnots()) + * sizeof(Standard_Real); + memsize += (surface.NbUPoles() * surface.NbVPoles()) + * sizeof(Standard_Real); + memsize += (surface.NbUPoles() * surface.NbVPoles()) + * sizeof(Geom_CartesianPoint); + break; + case GeomAbs_SurfaceOfRevolution: + memsize += sizeof(Geom_SurfaceOfRevolution); + break; + case GeomAbs_SurfaceOfExtrusion: + memsize += sizeof(Geom_SurfaceOfLinearExtrusion); + break; + case GeomAbs_OtherSurface: + // What kind of surface should this be? + memsize += sizeof(Geom_Surface); + break; + default: + break; } } break; - case TopAbs_EDGE: - { + case TopAbs_EDGE: { // first, last, tolerance - memsize += 3*sizeof(Standard_Real); + memsize += 3 * sizeof(Standard_Real); const TopoDS_Edge& edge = TopoDS::Edge(shape); // if no geometry is attached to an edge an exception is raised BRepAdaptor_Curve curve; @@ -1295,50 +1361,48 @@ unsigned int TopoShape::getMemSize () const continue; } - switch (curve.GetType()) - { - case GeomAbs_Line: - memsize += sizeof(Geom_Line); - break; - case GeomAbs_Circle: - memsize += sizeof(Geom_Circle); - break; - case GeomAbs_Ellipse: - memsize += sizeof(Geom_Ellipse); - break; - case GeomAbs_Hyperbola: - memsize += sizeof(Geom_Hyperbola); - break; - case GeomAbs_Parabola: - memsize += sizeof(Geom_Parabola); - break; - case GeomAbs_BezierCurve: - memsize += sizeof(Geom_BezierCurve); - memsize += curve.NbPoles() * sizeof(Standard_Real); - memsize += curve.NbPoles() * sizeof(Geom_CartesianPoint); - break; - case GeomAbs_BSplineCurve: - memsize += sizeof(Geom_BSplineCurve); - memsize += curve.NbKnots() * sizeof(Standard_Real); - memsize += curve.NbPoles() * sizeof(Standard_Real); - memsize += curve.NbPoles() * sizeof(Geom_CartesianPoint); - break; - case GeomAbs_OtherCurve: - // What kind of curve should this be? - memsize += sizeof(Geom_Curve); - break; - default: - break; + switch (curve.GetType()) { + case GeomAbs_Line: + memsize += sizeof(Geom_Line); + break; + case GeomAbs_Circle: + memsize += sizeof(Geom_Circle); + break; + case GeomAbs_Ellipse: + memsize += sizeof(Geom_Ellipse); + break; + case GeomAbs_Hyperbola: + memsize += sizeof(Geom_Hyperbola); + break; + case GeomAbs_Parabola: + memsize += sizeof(Geom_Parabola); + break; + case GeomAbs_BezierCurve: + memsize += sizeof(Geom_BezierCurve); + memsize += curve.NbPoles() * sizeof(Standard_Real); + memsize += curve.NbPoles() * sizeof(Geom_CartesianPoint); + break; + case GeomAbs_BSplineCurve: + memsize += sizeof(Geom_BSplineCurve); + memsize += curve.NbKnots() * sizeof(Standard_Real); + memsize += curve.NbPoles() * sizeof(Standard_Real); + memsize += curve.NbPoles() * sizeof(Geom_CartesianPoint); + break; + case GeomAbs_OtherCurve: + // What kind of curve should this be? + memsize += sizeof(Geom_Curve); + break; + default: + break; } } break; - case TopAbs_VERTEX: - { + case TopAbs_VERTEX: { // tolerance memsize += sizeof(Standard_Real); memsize += sizeof(Geom_CartesianPoint); } break; - default: - break; + default: + break; } } @@ -1366,40 +1430,41 @@ bool TopoShape::isEmpty() const return Tools::isShapeEmpty(this->_Shape); } -namespace Part { +namespace Part +{ std::vector buildShapeEnumVector() { - std::vector names; - names.emplace_back("Compound"); //TopAbs_COMPOUND - names.emplace_back("Compound Solid"); //TopAbs_COMPSOLID - names.emplace_back("Solid"); //TopAbs_SOLID - names.emplace_back("Shell"); //TopAbs_SHELL - names.emplace_back("Face"); //TopAbs_FACE - names.emplace_back("Wire"); //TopAbs_WIRE - names.emplace_back("Edge"); //TopAbs_EDGE - names.emplace_back("Vertex"); //TopAbs_VERTEX - names.emplace_back("Shape"); //TopAbs_SHAPE - return names; + std::vector names; + names.emplace_back("Compound"); // TopAbs_COMPOUND + names.emplace_back("Compound Solid"); // TopAbs_COMPSOLID + names.emplace_back("Solid"); // TopAbs_SOLID + names.emplace_back("Shell"); // TopAbs_SHELL + names.emplace_back("Face"); // TopAbs_FACE + names.emplace_back("Wire"); // TopAbs_WIRE + names.emplace_back("Edge"); // TopAbs_EDGE + names.emplace_back("Vertex"); // TopAbs_VERTEX + names.emplace_back("Shape"); // TopAbs_SHAPE + return names; } std::vector buildBOPCheckResultVector() { - std::vector results; - results.emplace_back("BOPAlgo CheckUnknown"); //BOPAlgo_CheckUnknown - results.emplace_back("BOPAlgo BadType"); //BOPAlgo_BadType - results.emplace_back("BOPAlgo SelfIntersect"); //BOPAlgo_SelfIntersect - results.emplace_back("BOPAlgo TooSmallEdge"); //BOPAlgo_TooSmallEdge - results.emplace_back("BOPAlgo NonRecoverableFace"); //BOPAlgo_NonRecoverableFace - results.emplace_back("BOPAlgo IncompatibilityOfVertex"); //BOPAlgo_IncompatibilityOfVertex - results.emplace_back("BOPAlgo IncompatibilityOfEdge"); //BOPAlgo_IncompatibilityOfEdge - results.emplace_back("BOPAlgo IncompatibilityOfFace"); //BOPAlgo_IncompatibilityOfFace - results.emplace_back("BOPAlgo OperationAborted"); //BOPAlgo_OperationAborted - results.emplace_back("BOPAlgo GeomAbs_C0"); //BOPAlgo_GeomAbs_C0 - results.emplace_back("BOPAlgo_InvalidCurveOnSurface"); //BOPAlgo_InvalidCurveOnSurface - results.emplace_back("BOPAlgo NotValid"); //BOPAlgo_NotValid - return results; -} + std::vector results; + results.emplace_back("BOPAlgo CheckUnknown"); // BOPAlgo_CheckUnknown + results.emplace_back("BOPAlgo BadType"); // BOPAlgo_BadType + results.emplace_back("BOPAlgo SelfIntersect"); // BOPAlgo_SelfIntersect + results.emplace_back("BOPAlgo TooSmallEdge"); // BOPAlgo_TooSmallEdge + results.emplace_back("BOPAlgo NonRecoverableFace"); // BOPAlgo_NonRecoverableFace + results.emplace_back("BOPAlgo IncompatibilityOfVertex"); // BOPAlgo_IncompatibilityOfVertex + results.emplace_back("BOPAlgo IncompatibilityOfEdge"); // BOPAlgo_IncompatibilityOfEdge + results.emplace_back("BOPAlgo IncompatibilityOfFace"); // BOPAlgo_IncompatibilityOfFace + results.emplace_back("BOPAlgo OperationAborted"); // BOPAlgo_OperationAborted + results.emplace_back("BOPAlgo GeomAbs_C0"); // BOPAlgo_GeomAbs_C0 + results.emplace_back("BOPAlgo_InvalidCurveOnSurface"); // BOPAlgo_InvalidCurveOnSurface + results.emplace_back("BOPAlgo NotValid"); // BOPAlgo_NotValid + return results; } +} // namespace Part bool TopoShape::analyze(bool runBopCheck, std::ostream& str) const { @@ -1410,161 +1475,169 @@ bool TopoShape::analyze(bool runBopCheck, std::ostream& str) const TopTools_IndexedMapOfShape vertexOfShape; TopExp::MapShapes(this->_Shape, TopAbs_VERTEX, vertexOfShape); - for (int i = 1; i <= vertexOfShape.Extent();++i) + for (int i = 1; i <= vertexOfShape.Extent(); ++i) { shapes.push_back(vertexOfShape(i)); + } TopTools_IndexedMapOfShape edgeOfShape; TopExp::MapShapes(this->_Shape, TopAbs_EDGE, edgeOfShape); - for (int i = 1; i <= edgeOfShape.Extent();++i) + for (int i = 1; i <= edgeOfShape.Extent(); ++i) { shapes.push_back(edgeOfShape(i)); + } TopTools_IndexedMapOfShape wireOfShape; TopExp::MapShapes(this->_Shape, TopAbs_WIRE, wireOfShape); - for (int i = 1; i <= wireOfShape.Extent();++i) + for (int i = 1; i <= wireOfShape.Extent(); ++i) { shapes.push_back(wireOfShape(i)); + } TopTools_IndexedMapOfShape faceOfShape; TopExp::MapShapes(this->_Shape, TopAbs_FACE, faceOfShape); - for (int i = 1; i <= faceOfShape.Extent();++i) + for (int i = 1; i <= faceOfShape.Extent(); ++i) { shapes.push_back(faceOfShape(i)); + } TopTools_IndexedMapOfShape shellOfShape; TopExp::MapShapes(this->_Shape, TopAbs_SHELL, shellOfShape); - for (int i = 1; i <= shellOfShape.Extent();++i) + for (int i = 1; i <= shellOfShape.Extent(); ++i) { shapes.push_back(shellOfShape(i)); + } TopTools_IndexedMapOfShape solidOfShape; TopExp::MapShapes(this->_Shape, TopAbs_SOLID, solidOfShape); - for (int i = 1; i <= solidOfShape.Extent();++i) + for (int i = 1; i <= solidOfShape.Extent(); ++i) { shapes.push_back(solidOfShape(i)); + } TopTools_IndexedMapOfShape compOfShape; TopExp::MapShapes(this->_Shape, TopAbs_COMPOUND, compOfShape); - for (int i = 1; i <= compOfShape.Extent();++i) + for (int i = 1; i <= compOfShape.Extent(); ++i) { shapes.push_back(compOfShape(i)); + } TopTools_IndexedMapOfShape compsOfShape; TopExp::MapShapes(this->_Shape, TopAbs_COMPSOLID, compsOfShape); - for (int i = 1; i <= compsOfShape.Extent();++i) + for (int i = 1; i <= compsOfShape.Extent(); ++i) { shapes.push_back(compsOfShape(i)); + } - for (const auto & shape : shapes) { + for (const auto& shape : shapes) { if (!aChecker.IsValid(shape)) { - const Handle(BRepCheck_Result)& result = aChecker.Result(shape); - if (result.IsNull()) + const Handle(BRepCheck_Result) & result = aChecker.Result(shape); + if (result.IsNull()) { continue; + } const BRepCheck_ListOfStatus& status = result->StatusOnShape(shape); BRepCheck_ListIteratorOfListOfStatus it(status); while (it.More()) { BRepCheck_Status& val = it.Value(); - switch (val) - { - case BRepCheck_NoError: - str << "No error" << std::endl; - break; - case BRepCheck_InvalidPointOnCurve: - str << "Invalid point on curve" << std::endl; - break; - case BRepCheck_InvalidPointOnCurveOnSurface: - str << "Invalid point on curve on surface" << std::endl; - break; - case BRepCheck_InvalidPointOnSurface: - str << "Invalid point on surface" << std::endl; - break; - case BRepCheck_No3DCurve: - str << "No 3D curve" << std::endl; - break; - case BRepCheck_Multiple3DCurve: - str << "Multiple 3D curve" << std::endl; - break; - case BRepCheck_Invalid3DCurve: - str << "Invalid 3D curve" << std::endl; - break; - case BRepCheck_NoCurveOnSurface: - str << "No curve on surface" << std::endl; - break; - case BRepCheck_InvalidCurveOnSurface: - str << "Invalid curve on surface" << std::endl; - break; - case BRepCheck_InvalidCurveOnClosedSurface: - str << "Invalid curve on closed surface" << std::endl; - break; - case BRepCheck_InvalidSameRangeFlag: - str << "Invalid same-range flag" << std::endl; - break; - case BRepCheck_InvalidSameParameterFlag: - str << "Invalid same-parameter flag" << std::endl; - break; - case BRepCheck_InvalidDegeneratedFlag: - str << "Invalid degenerated flag" << std::endl; - break; - case BRepCheck_FreeEdge: - str << "Free edge" << std::endl; - break; - case BRepCheck_InvalidMultiConnexity: - str << "Invalid multi-connexity" << std::endl; - break; - case BRepCheck_InvalidRange: - str << "Invalid range" << std::endl; - break; - case BRepCheck_EmptyWire: - str << "Empty wire" << std::endl; - break; - case BRepCheck_RedundantEdge: - str << "Redundant edge" << std::endl; - break; - case BRepCheck_SelfIntersectingWire: - str << "Self-intersecting wire" << std::endl; - break; - case BRepCheck_NoSurface: - str << "No surface" << std::endl; - break; - case BRepCheck_InvalidWire: - str << "Invalid wires" << std::endl; - break; - case BRepCheck_RedundantWire: - str << "Redundant wires" << std::endl; - break; - case BRepCheck_IntersectingWires: - str << "Intersecting wires" << std::endl; - break; - case BRepCheck_InvalidImbricationOfWires: - str << "Invalid imbrication of wires" << std::endl; - break; - case BRepCheck_EmptyShell: - str << "Empty shell" << std::endl; - break; - case BRepCheck_RedundantFace: - str << "Redundant face" << std::endl; - break; - case BRepCheck_UnorientableShape: - str << "Unorientable shape" << std::endl; - break; - case BRepCheck_NotClosed: - str << "Not closed" << std::endl; - break; - case BRepCheck_NotConnected: - str << "Not connected" << std::endl; - break; - case BRepCheck_SubshapeNotInShape: - str << "Sub-shape not in shape" << std::endl; - break; - case BRepCheck_BadOrientation: - str << "Bad orientation" << std::endl; - break; - case BRepCheck_BadOrientationOfSubshape: - str << "Bad orientation of sub-shape" << std::endl; - break; - case BRepCheck_InvalidToleranceValue: - str << "Invalid tolerance value" << std::endl; - break; - case BRepCheck_CheckFail: - str << "Check failed" << std::endl; - break; - default: - str << "Undetermined error" << std::endl; - break; + switch (val) { + case BRepCheck_NoError: + str << "No error" << std::endl; + break; + case BRepCheck_InvalidPointOnCurve: + str << "Invalid point on curve" << std::endl; + break; + case BRepCheck_InvalidPointOnCurveOnSurface: + str << "Invalid point on curve on surface" << std::endl; + break; + case BRepCheck_InvalidPointOnSurface: + str << "Invalid point on surface" << std::endl; + break; + case BRepCheck_No3DCurve: + str << "No 3D curve" << std::endl; + break; + case BRepCheck_Multiple3DCurve: + str << "Multiple 3D curve" << std::endl; + break; + case BRepCheck_Invalid3DCurve: + str << "Invalid 3D curve" << std::endl; + break; + case BRepCheck_NoCurveOnSurface: + str << "No curve on surface" << std::endl; + break; + case BRepCheck_InvalidCurveOnSurface: + str << "Invalid curve on surface" << std::endl; + break; + case BRepCheck_InvalidCurveOnClosedSurface: + str << "Invalid curve on closed surface" << std::endl; + break; + case BRepCheck_InvalidSameRangeFlag: + str << "Invalid same-range flag" << std::endl; + break; + case BRepCheck_InvalidSameParameterFlag: + str << "Invalid same-parameter flag" << std::endl; + break; + case BRepCheck_InvalidDegeneratedFlag: + str << "Invalid degenerated flag" << std::endl; + break; + case BRepCheck_FreeEdge: + str << "Free edge" << std::endl; + break; + case BRepCheck_InvalidMultiConnexity: + str << "Invalid multi-connexity" << std::endl; + break; + case BRepCheck_InvalidRange: + str << "Invalid range" << std::endl; + break; + case BRepCheck_EmptyWire: + str << "Empty wire" << std::endl; + break; + case BRepCheck_RedundantEdge: + str << "Redundant edge" << std::endl; + break; + case BRepCheck_SelfIntersectingWire: + str << "Self-intersecting wire" << std::endl; + break; + case BRepCheck_NoSurface: + str << "No surface" << std::endl; + break; + case BRepCheck_InvalidWire: + str << "Invalid wires" << std::endl; + break; + case BRepCheck_RedundantWire: + str << "Redundant wires" << std::endl; + break; + case BRepCheck_IntersectingWires: + str << "Intersecting wires" << std::endl; + break; + case BRepCheck_InvalidImbricationOfWires: + str << "Invalid imbrication of wires" << std::endl; + break; + case BRepCheck_EmptyShell: + str << "Empty shell" << std::endl; + break; + case BRepCheck_RedundantFace: + str << "Redundant face" << std::endl; + break; + case BRepCheck_UnorientableShape: + str << "Unorientable shape" << std::endl; + break; + case BRepCheck_NotClosed: + str << "Not closed" << std::endl; + break; + case BRepCheck_NotConnected: + str << "Not connected" << std::endl; + break; + case BRepCheck_SubshapeNotInShape: + str << "Sub-shape not in shape" << std::endl; + break; + case BRepCheck_BadOrientation: + str << "Bad orientation" << std::endl; + break; + case BRepCheck_BadOrientationOfSubshape: + str << "Bad orientation of sub-shape" << std::endl; + break; + case BRepCheck_InvalidToleranceValue: + str << "Invalid tolerance value" << std::endl; + break; + case BRepCheck_CheckFail: + str << "Check failed" << std::endl; + break; + default: + str << "Undetermined error" << std::endl; + break; } it.Next(); @@ -1572,41 +1645,42 @@ bool TopoShape::analyze(bool runBopCheck, std::ostream& str) const } } - return false; // errors detected + return false; // errors detected } else if (runBopCheck) { TopoDS_Shape BOPCopy = BRepBuilderAPI_Copy(this->_Shape).Shape(); BOPAlgo_ArgumentAnalyzer BOPCheck; BOPCheck.SetShape1(BOPCopy); - //all settings are false by default. so only turn on what we want. + // all settings are false by default. so only turn on what we want. BOPCheck.ArgumentTypeMode() = true; BOPCheck.SelfInterMode() = true; BOPCheck.SmallEdgeMode() = true; BOPCheck.RebuildFaceMode() = true; BOPCheck.ContinuityMode() = true; - BOPCheck.SetParallelMode(true); //this doesn't help for speed right now(occt 6.9.1). - BOPCheck.SetRunParallel(true); //performance boost, use all available cores - BOPCheck.TangentMode() = true; //these 4 new tests add about 5% processing time. + BOPCheck.SetParallelMode(true); // this doesn't help for speed right now(occt 6.9.1). + BOPCheck.SetRunParallel(true); // performance boost, use all available cores + BOPCheck.TangentMode() = true; // these 4 new tests add about 5% processing time. BOPCheck.MergeVertexMode() = true; BOPCheck.CurveOnSurfaceMode() = true; BOPCheck.MergeEdgeMode() = true; BOPCheck.Perform(); - if (!BOPCheck.HasFaulty()) + if (!BOPCheck.HasFaulty()) { return true; + } str << "BOP check found the following errors:" << std::endl; static std::vector shapeEnumToString = buildShapeEnumVector(); static std::vector bopEnumToString = buildBOPCheckResultVector(); - const BOPAlgo_ListOfCheckResult &BOPResults = BOPCheck.GetCheckResult(); + const BOPAlgo_ListOfCheckResult& BOPResults = BOPCheck.GetCheckResult(); BOPAlgo_ListIteratorOfListOfCheckResult BOPResultsIt(BOPResults); for (; BOPResultsIt.More(); BOPResultsIt.Next()) { - const BOPAlgo_CheckResult ¤t = BOPResultsIt.Value(); + const BOPAlgo_CheckResult& current = BOPResultsIt.Value(); - const TopTools_ListOfShape &faultyShapes1 = current.GetFaultyShapes1(); + const TopTools_ListOfShape& faultyShapes1 = current.GetFaultyShapes1(); TopTools_ListIteratorOfListOfShape faultyShapes1It(faultyShapes1); - for (;faultyShapes1It.More(); faultyShapes1It.Next()) { - const TopoDS_Shape &faultyShape = faultyShapes1It.Value(); + for (; faultyShapes1It.More(); faultyShapes1It.Next()) { + const TopoDS_Shape& faultyShape = faultyShapes1It.Value(); str << "Error in " << shapeEnumToString[faultyShape.ShapeType()] << ": "; str << bopEnumToString[current.GetCheckStatus()] << std::endl; } @@ -1619,28 +1693,26 @@ bool TopoShape::analyze(bool runBopCheck, std::ostream& str) const bool TopoShape::isClosed() const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return false; + } bool closed = false; switch (this->_Shape.ShapeType()) { - case TopAbs_SHELL: - case TopAbs_WIRE: - case TopAbs_EDGE: - closed = BRep_Tool::IsClosed(this->_Shape) ? true : false; - break; - case TopAbs_COMPSOLID: - case TopAbs_SOLID: - { + case TopAbs_SHELL: + case TopAbs_WIRE: + case TopAbs_EDGE: + closed = BRep_Tool::IsClosed(this->_Shape) ? true : false; + break; + case TopAbs_COMPSOLID: + case TopAbs_SOLID: { closed = true; TopExp_Explorer xp(this->_Shape, TopAbs_SHELL); while (xp.More()) { closed &= BRep_Tool::IsClosed(xp.Current()) ? true : false; xp.Next(); } - } - break; - case TopAbs_COMPOUND: - { + } break; + case TopAbs_COMPOUND: { closed = true; TopExp_Explorer xp; for (xp.Init(this->_Shape, TopAbs_SHELL); xp.More(); xp.Next()) { @@ -1658,38 +1730,41 @@ bool TopoShape::isClosed() const for (xp.Init(this->_Shape, TopAbs_VERTEX, TopAbs_EDGE); xp.More(); xp.Next()) { closed &= BRep_Tool::IsClosed(xp.Current()) ? true : false; } - } - break; - case TopAbs_FACE: - case TopAbs_VERTEX: - case TopAbs_SHAPE: - closed = BRep_Tool::IsClosed(this->_Shape) ? true : false; - break; + } break; + case TopAbs_FACE: + case TopAbs_VERTEX: + case TopAbs_SHAPE: + closed = BRep_Tool::IsClosed(this->_Shape) ? true : false; + break; } return closed; } TopoDS_Shape TopoShape::cut(TopoDS_Shape shape) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return this->_Shape; - if (shape.IsNull()) + } + if (shape.IsNull()) { return this->_Shape; + } FCBRepAlgoAPI_Cut mkCut(this->_Shape, shape); return makeShell(mkCut.Shape()); } TopoDS_Shape TopoShape::cut(const std::vector& shapes, Standard_Real tolerance) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return this->_Shape; + } FCBRepAlgoAPI_Cut mkCut; mkCut.SetRunParallel(true); - TopTools_ListOfShape shapeArguments,shapeTools; + TopTools_ListOfShape shapeArguments, shapeTools; shapeArguments.Append(this->_Shape); - for (const auto & shape : shapes) { - if (shape.IsNull()) + for (const auto& shape : shapes) { + if (shape.IsNull()) { throw Base::ValueError("Tool shape is null"); + } shapeTools.Append(shape); } @@ -1697,7 +1772,8 @@ TopoDS_Shape TopoShape::cut(const std::vector& shapes, Standard_Re mkCut.SetTools(shapeTools); if (tolerance > 0.0) { mkCut.SetFuzzyValue(tolerance); - } else if (tolerance < 0.0) { + } + else if (tolerance < 0.0) { mkCut.setAutoFuzzy(); } #if OCC_VERSION_HEX >= 0x070600 @@ -1705,8 +1781,9 @@ TopoDS_Shape TopoShape::cut(const std::vector& shapes, Standard_Re #else mkCut.Build(); #endif - if (!mkCut.IsDone()) + if (!mkCut.IsDone()) { throw Base::RuntimeError("Multi cut failed"); + } TopoDS_Shape resShape = mkCut.Shape(); return makeShell(resShape); @@ -1714,25 +1791,29 @@ TopoDS_Shape TopoShape::cut(const std::vector& shapes, Standard_Re TopoDS_Shape TopoShape::common(TopoDS_Shape shape) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return this->_Shape; - if (shape.IsNull()) + } + if (shape.IsNull()) { return shape; + } FCBRepAlgoAPI_Common mkCommon(this->_Shape, shape); return makeShell(mkCommon.Shape()); } TopoDS_Shape TopoShape::common(const std::vector& shapes, Standard_Real tolerance) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return this->_Shape; + } FCBRepAlgoAPI_Common mkCommon; mkCommon.SetRunParallel(true); - TopTools_ListOfShape shapeArguments,shapeTools; + TopTools_ListOfShape shapeArguments, shapeTools; shapeArguments.Append(this->_Shape); - for (const auto & shape : shapes) { - if (shape.IsNull()) + for (const auto& shape : shapes) { + if (shape.IsNull()) { throw Base::ValueError("Tool shape is null"); + } shapeTools.Append(shape); } @@ -1740,7 +1821,8 @@ TopoDS_Shape TopoShape::common(const std::vector& shapes, Standard mkCommon.SetTools(shapeTools); if (tolerance > 0.0) { mkCommon.SetFuzzyValue(tolerance); - } else if (tolerance < 0.0) { + } + else if (tolerance < 0.0) { mkCommon.setAutoFuzzy(); } #if OCC_VERSION_HEX >= 0x070600 @@ -1748,8 +1830,9 @@ TopoDS_Shape TopoShape::common(const std::vector& shapes, Standard #else mkCommon.Build(); #endif - if (!mkCommon.IsDone()) + if (!mkCommon.IsDone()) { throw Base::RuntimeError("Multi common failed"); + } TopoDS_Shape resShape = mkCommon.Shape(); return makeShell(resShape); @@ -1757,33 +1840,38 @@ TopoDS_Shape TopoShape::common(const std::vector& shapes, Standard TopoDS_Shape TopoShape::fuse(TopoDS_Shape shape) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return shape; - if (shape.IsNull()) + } + if (shape.IsNull()) { return this->_Shape; + } FCBRepAlgoAPI_Fuse mkFuse(this->_Shape, shape); return makeShell(mkFuse.Shape()); } TopoDS_Shape TopoShape::fuse(const std::vector& shapes, Standard_Real tolerance) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Base shape is null"); + } FCBRepAlgoAPI_Fuse mkFuse; mkFuse.SetRunParallel(true); - TopTools_ListOfShape shapeArguments,shapeTools; + TopTools_ListOfShape shapeArguments, shapeTools; shapeArguments.Append(this->_Shape); - for (const auto & shape : shapes) { - if (shape.IsNull()) + for (const auto& shape : shapes) { + if (shape.IsNull()) { throw NullShapeException("Tool shape is null"); + } shapeTools.Append(shape); } mkFuse.SetArguments(shapeArguments); mkFuse.SetTools(shapeTools); if (tolerance > 0.0) { mkFuse.SetFuzzyValue(tolerance); - } else if (tolerance < 0.0) { + } + else if (tolerance < 0.0) { mkFuse.setAutoFuzzy(); } #if OCC_VERSION_HEX >= 0x070600 @@ -1791,8 +1879,9 @@ TopoDS_Shape TopoShape::fuse(const std::vector& shapes, Standard_R #else mkFuse.Build(); #endif - if (!mkFuse.IsDone()) + if (!mkFuse.IsDone()) { throw Base::RuntimeError("Multi fuse failed"); + } TopoDS_Shape resShape = mkFuse.Shape(); return makeShell(resShape); @@ -1801,10 +1890,12 @@ TopoDS_Shape TopoShape::fuse(const std::vector& shapes, Standard_R TopoDS_Shape TopoShape::section(TopoDS_Shape shape, Standard_Boolean approximate) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Base shape is null"); - if (shape.IsNull()) + } + if (shape.IsNull()) { Standard_Failure::Raise("Tool shape is null"); + } FCBRepAlgoAPI_Section mkSection; mkSection.Init1(this->_Shape); mkSection.Init2(shape); @@ -1814,26 +1905,31 @@ TopoDS_Shape TopoShape::section(TopoDS_Shape shape, Standard_Boolean approximate #else mkSection.Build(); #endif - if (!mkSection.IsDone()) + if (!mkSection.IsDone()) { throw Base::RuntimeError("Section failed"); + } return mkSection.Shape(); } -TopoDS_Shape TopoShape::section(const std::vector& shapes, - Standard_Real tolerance, - Standard_Boolean approximate) const +TopoDS_Shape TopoShape::section( + const std::vector& shapes, + Standard_Real tolerance, + Standard_Boolean approximate +) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Base shape is null"); + } FCBRepAlgoAPI_Section mkSection; mkSection.SetRunParallel(true); mkSection.Approximation(approximate); - TopTools_ListOfShape shapeArguments,shapeTools; + TopTools_ListOfShape shapeArguments, shapeTools; shapeArguments.Append(this->_Shape); - for (const auto & shape : shapes) { - if (shape.IsNull()) + for (const auto& shape : shapes) { + if (shape.IsNull()) { throw Base::ValueError("Tool shape is null"); + } shapeTools.Append(shape); } @@ -1841,7 +1937,8 @@ TopoDS_Shape TopoShape::section(const std::vector& shapes, mkSection.SetTools(shapeTools); if (tolerance > 0.0) { mkSection.SetFuzzyValue(tolerance); - } else if (tolerance < 0.0) { + } + else if (tolerance < 0.0) { mkSection.setAutoFuzzy(); } #if OCC_VERSION_HEX >= 0x070600 @@ -1849,8 +1946,9 @@ TopoDS_Shape TopoShape::section(const std::vector& shapes, #else mkSection.Build(); #endif - if (!mkSection.IsDone()) + if (!mkSection.IsDone()) { throw Base::RuntimeError("Multi section failed"); + } TopoDS_Shape resShape = mkSection.Shape(); return resShape; @@ -1864,39 +1962,44 @@ std::list TopoShape::slice(const Base::Vector3d& dir, double d) con TopoDS_Compound TopoShape::slices(const Base::Vector3d& dir, const std::vector& d) const { - std::vector< std::list > wire_list; + std::vector> wire_list; CrossSection cs(dir.x, dir.y, dir.z, this->_Shape); for (double jt : d) { wire_list.push_back(cs.slice(jt)); } - std::vector< std::list >::const_iterator ft; + std::vector>::const_iterator ft; TopoDS_Compound comp; BRep_Builder builder; builder.MakeCompound(comp); for (ft = wire_list.begin(); ft != wire_list.end(); ++ft) { const std::list& w = *ft; - for (const auto & wt : w) { - if (!wt.IsNull()) + for (const auto& wt : w) { + if (!wt.IsNull()) { builder.Add(comp, wt); + } } } return comp; } -TopoDS_Shape TopoShape::generalFuse(const std::vector &sOthers, Standard_Real tolerance, - std::vector* mapInOut) const +TopoDS_Shape TopoShape::generalFuse( + const std::vector& sOthers, + Standard_Real tolerance, + std::vector* mapInOut +) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Base shape is null"); + } BRepAlgoAPI_BuilderAlgo mkGFA; mkGFA.SetRunParallel(true); TopTools_ListOfShape GFAArguments; GFAArguments.Append(this->_Shape); - for (const TopoDS_Shape &it: sOthers) { + for (const TopoDS_Shape& it : sOthers) { if (it.IsNull()) { throw NullShapeException("Tool shape is null"); } @@ -1916,11 +2019,12 @@ TopoDS_Shape TopoShape::generalFuse(const std::vector &sOthers, St #else mkGFA.Build(); #endif - if (!mkGFA.IsDone()) + if (!mkGFA.IsDone()) { throw BooleanException("MultiFusion failed"); + } TopoDS_Shape resShape = mkGFA.Shape(); - if (mapInOut){ - for(TopTools_ListIteratorOfListOfShape it(GFAArguments); it.More(); it.Next()){ + if (mapInOut) { + for (TopTools_ListIteratorOfListOfShape it(GFAArguments); it.More(); it.Next()) { mapInOut->push_back(mkGFA.Modified(it.Value())); } } @@ -1929,34 +2033,44 @@ TopoDS_Shape TopoShape::generalFuse(const std::vector &sOthers, St TopoDS_Shape TopoShape::makePipe(const TopoDS_Shape& profile) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot sweep along empty spine"); - if (this->_Shape.ShapeType() != TopAbs_WIRE) + } + if (this->_Shape.ShapeType() != TopAbs_WIRE) { Standard_Failure::Raise("Spine shape is not a wire"); - if (profile.IsNull()) + } + if (profile.IsNull()) { Standard_Failure::Raise("Cannot sweep empty profile"); + } BRepOffsetAPI_MakePipe mkPipe(TopoDS::Wire(this->_Shape), profile); return mkPipe.Shape(); } -TopoDS_Shape TopoShape::makePipeShell(const TopTools_ListOfShape& profiles, - const Standard_Boolean make_solid, - const Standard_Boolean isFrenet, - int transition) const +TopoDS_Shape TopoShape::makePipeShell( + const TopTools_ListOfShape& profiles, + const Standard_Boolean make_solid, + const Standard_Boolean isFrenet, + int transition +) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot sweep along empty spine"); - if (this->_Shape.ShapeType() != TopAbs_WIRE) + } + if (this->_Shape.ShapeType() != TopAbs_WIRE) { Standard_Failure::Raise("Spine shape is not a wire"); + } BRepOffsetAPI_MakePipeShell mkPipeShell(TopoDS::Wire(this->_Shape)); BRepBuilderAPI_TransitionMode transMode; switch (transition) { - case 1: transMode = BRepBuilderAPI_RightCorner; + case 1: + transMode = BRepBuilderAPI_RightCorner; break; - case 2: transMode = BRepBuilderAPI_RoundCorner; + case 2: + transMode = BRepBuilderAPI_RoundCorner; break; - default: transMode = BRepBuilderAPI_Transformed; + default: + transMode = BRepBuilderAPI_Transformed; break; } mkPipeShell.SetMode(isFrenet); @@ -1966,25 +2080,31 @@ TopoDS_Shape TopoShape::makePipeShell(const TopTools_ListOfShape& profiles, mkPipeShell.Add(TopoDS_Shape(it.Value())); } - if (!mkPipeShell.IsReady()) + if (!mkPipeShell.IsReady()) { throw Standard_Failure("shape is not ready to build"); + } #if OCC_VERSION_HEX >= 0x070600 mkPipeShell.Build(OCCTProgressIndicator::getAppIndicator().Start()); #else mkPipeShell.Build(); #endif - if (make_solid) + if (make_solid) { mkPipeShell.MakeSolid(); + } return mkPipeShell.Shape(); } -static Handle(Law_Function) CreateBsFunction (const Standard_Real theFirst, const Standard_Real theLast, const Standard_Real theRadius) +static Handle(Law_Function) CreateBsFunction( + const Standard_Real theFirst, + const Standard_Real theLast, + const Standard_Real theRadius +) { (void)theRadius; - //Handle(Law_BSpline) aBs; - //Handle(Law_BSpFunc) aFunc = new Law_BSpFunc (aBs, theFirst, theLast); + // Handle(Law_BSpline) aBs; + // Handle(Law_BSpFunc) aFunc = new Law_BSpFunc (aBs, theFirst, theLast); Handle(Law_Constant) aFunc = new Law_Constant(); aFunc->Set(1, theFirst, theLast); return aFunc; @@ -1995,14 +2115,15 @@ TopoDS_Shape TopoShape::makeTube(double radius, double tol, int cont, int maxdeg // http://opencascade.blogspot.com/2009/11/surface-modeling-part3.html Standard_Real theTol = tol; Standard_Real theRadius = radius; - //Standard_Boolean theIsPolynomial = Standard_True; + // Standard_Boolean theIsPolynomial = Standard_True; Standard_Boolean myIsElem = Standard_True; GeomAbs_Shape theContinuity = GeomAbs_Shape(cont); Standard_Integer theMaxDegree = maxdegree; Standard_Integer theMaxSegment = maxsegm; - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot sweep along empty spine"); + } #if OCC_VERSION_HEX >= 0x070600 @@ -2025,27 +2146,27 @@ TopoDS_Shape TopoShape::makeTube(double radius, double tol, int cont, int maxdeg Standard_Failure::Raise("Spine shape is not an edge"); } - //circular profile - Handle(Geom_Circle) aCirc = new Geom_Circle (gp::XOY(), theRadius); - aCirc->Rotate (gp::OZ(), std::numbers::pi/2.); + // circular profile + Handle(Geom_Circle) aCirc = new Geom_Circle(gp::XOY(), theRadius); + aCirc->Rotate(gp::OZ(), std::numbers::pi / 2.); - //perpendicular section - Handle(Law_Function) myEvol = ::CreateBsFunction (myPath->FirstParameter(), myPath->LastParameter(), theRadius); + // perpendicular section + Handle(Law_Function) myEvol + = ::CreateBsFunction(myPath->FirstParameter(), myPath->LastParameter(), theRadius); Handle(GeomFill_SectionLaw) aSec = new GeomFill_EvolvedSection(aCirc, myEvol); Handle(GeomFill_LocationLaw) aLoc = new GeomFill_CurveAndTrihedron(new GeomFill_CorrectedFrenet); - aLoc->SetCurve (myPath); + aLoc->SetCurve(myPath); - GeomFill_Sweep mkSweep (aLoc, myIsElem); - mkSweep.SetTolerance (theTol); - mkSweep.Build (aSec, GeomFill_Location, theContinuity, theMaxDegree, theMaxSegment); + GeomFill_Sweep mkSweep(aLoc, myIsElem); + mkSweep.SetTolerance(theTol); + mkSweep.Build(aSec, GeomFill_Location, theContinuity, theMaxDegree, theMaxSegment); if (mkSweep.IsDone()) { Handle(Geom_Surface) mySurface = mkSweep.Surface(); - //Standard_Real myError = mkSweep.ErrorOnSurface(); + // Standard_Real myError = mkSweep.ErrorOnSurface(); - Standard_Real u1,u2,v1,v2; - mySurface->Bounds(u1,u2,v1,v2); - BRepBuilderAPI_MakeFace mkBuilder(mySurface, u1, u2, v1, v2 , Precision::Confusion() - ); + Standard_Real u1, u2, v1, v2; + mySurface->Bounds(u1, u2, v1, v2); + BRepBuilderAPI_MakeFace mkBuilder(mySurface, u1, u2, v1, v2, Precision::Confusion()); return mkBuilder.Shape(); } @@ -2056,15 +2177,19 @@ TopoDS_Shape TopoShape::makeTube(double radius, double tol, int cont, int maxdeg TopoDS_Shape TopoShape::makeSweep(const TopoDS_Shape& profile, double tol, int fillMode) const { // http://opencascade.blogspot.com/2009/10/surface-modeling-part2.html - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot sweep along empty spine"); - if (this->_Shape.ShapeType() != TopAbs_EDGE) + } + if (this->_Shape.ShapeType() != TopAbs_EDGE) { Standard_Failure::Raise("Spine shape is not an edge"); + } - if (profile.IsNull()) + if (profile.IsNull()) { Standard_Failure::Raise("Cannot sweep with empty profile"); - if (profile.ShapeType() != TopAbs_EDGE) + } + if (profile.ShapeType() != TopAbs_EDGE) { Standard_Failure::Raise("Profile shape is not an edge"); + } const TopoDS_Edge& path_edge = TopoDS::Edge(this->_Shape); const TopoDS_Edge& prof_edge = TopoDS::Edge(profile); @@ -2078,8 +2203,9 @@ TopoDS_Shape TopoShape::makeSweep(const TopoDS_Shape& profile, double tol, int f TopLoc_Location loc1 = path_edge.Location(); hPath = Handle(Geom_Curve)::DownCast(hPath->Transformed(loc1.Transformation())); - if (hPath.IsNull()) + if (hPath.IsNull()) { Standard_Failure::Raise("invalid curve in path edge"); + } BRepAdaptor_Curve prof_adapt(prof_edge); double vmin = prof_adapt.FirstParameter(); @@ -2090,33 +2216,42 @@ TopoDS_Shape TopoShape::makeSweep(const TopoDS_Shape& profile, double tol, int f TopLoc_Location loc2 = prof_edge.Location(); hProfile = Handle(Geom_Curve)::DownCast(hProfile->Transformed(loc2.Transformation())); - if (hProfile.IsNull()) + if (hProfile.IsNull()) { Standard_Failure::Raise("invalid curve in profile edge"); + } GeomFill_Pipe mkSweep(hPath, hProfile, static_cast(fillMode)); mkSweep.GenerateParticularCase(Standard_True); mkSweep.Perform(tol, Standard_False, GeomAbs_C1, BSplCLib::MaxDegree(), 1000); - const Handle(Geom_Surface)& surf = mkSweep.Surface(); - BRepBuilderAPI_MakeFace mkBuilder(surf, umin, umax, vmin, vmax , Precision::Confusion()); + const Handle(Geom_Surface) & surf = mkSweep.Surface(); + BRepBuilderAPI_MakeFace mkBuilder(surf, umin, umax, vmin, vmax, Precision::Confusion()); return mkBuilder.Face(); } -TopoDS_Shape TopoShape::makeTorus(Standard_Real radius1, Standard_Real radius2, - Standard_Real angle1, Standard_Real angle2, - Standard_Real angle3, Standard_Boolean isSolid) const +TopoDS_Shape TopoShape::makeTorus( + Standard_Real radius1, + Standard_Real radius2, + Standard_Real angle1, + Standard_Real angle2, + Standard_Real angle3, + Standard_Boolean isSolid +) const { // https://forum.freecad.org/viewtopic.php?f=3&t=1445 // https://forum.freecad.org/viewtopic.php?f=3&t=52719 // Build a torus gp_Circ circle; circle.SetRadius(radius2); - gp_Pnt pos(radius1,0,0); - gp_Dir dir(0,1,0); + gp_Pnt pos(radius1, 0, 0); + gp_Dir dir(0, 1, 0); circle.SetAxis(gp_Ax1(pos, dir)); - BRepBuilderAPI_MakeEdge mkEdge(circle, Base::toRadians(angle1), - Base::toRadians(angle2)); + BRepBuilderAPI_MakeEdge mkEdge( + circle, + Base::toRadians(angle1), + Base::toRadians(angle2) + ); BRepBuilderAPI_MakeWire mkWire; mkWire.Add(mkEdge.Edge()); @@ -2129,38 +2264,51 @@ TopoDS_Shape TopoShape::makeTorus(Standard_Real radius1, Standard_Real radius2, } BRepBuilderAPI_MakeFace mkFace(mkWire.Wire()); - BRepPrimAPI_MakeRevol mkRevol(mkFace.Face(), gp_Ax1(gp_Pnt(0,0,0), gp_Dir(0,0,1)), - Base::toRadians(angle3), Standard_True); + BRepPrimAPI_MakeRevol mkRevol( + mkFace.Face(), + gp_Ax1(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1)), + Base::toRadians(angle3), + Standard_True + ); return mkRevol.Shape(); } -TopoDS_Shape TopoShape::makeHelix(Standard_Real pitch, Standard_Real height, - Standard_Real radius, Standard_Real angle, - Standard_Boolean leftHanded, - Standard_Boolean newStyle) const +TopoDS_Shape TopoShape::makeHelix( + Standard_Real pitch, + Standard_Real height, + Standard_Real radius, + Standard_Real angle, + Standard_Boolean leftHanded, + Standard_Boolean newStyle +) const { using std::numbers::pi; - if (fabs(pitch) < Precision::Confusion()) + if (fabs(pitch) < Precision::Confusion()) { Standard_Failure::Raise("Pitch of helix too small"); + } - if (fabs(height) < Precision::Confusion()) + if (fabs(height) < Precision::Confusion()) { Standard_Failure::Raise("Height of helix too small"); + } - if ((height > 0 && pitch < 0) || (height < 0 && pitch > 0)) + if ((height > 0 && pitch < 0) || (height < 0 && pitch > 0)) { Standard_Failure::Raise("Pitch and height of helix not compatible"); + } - gp_Ax2 cylAx2(gp_Pnt(0.0,0.0,0.0) , gp::DZ()); + gp_Ax2 cylAx2(gp_Pnt(0.0, 0.0, 0.0), gp::DZ()); Handle(Geom_Surface) surf; if (angle < Precision::Confusion()) { - if (radius < Precision::Confusion()) + if (radius < Precision::Confusion()) { Standard_Failure::Raise("Radius of helix too small"); + } surf = new Geom_CylindricalSurface(cylAx2, radius); } else { angle = Base::toRadians(angle); - if (angle < Precision::Confusion()) + if (angle < Precision::Confusion()) { Standard_Failure::Raise("Angle of helix too small"); + } surf = new Geom_ConicalSurface(gp_Ax3(cylAx2), angle, radius); } @@ -2175,22 +2323,22 @@ TopoDS_Shape TopoShape::makeHelix(Standard_Real pitch, Standard_Real height, Handle(Geom2d_Line) line = new Geom2d_Line(aAx2d); gp_Pnt2d beg = line->Value(0); - gp_Pnt2d end = line->Value(sqrt(4.0*pi*pi+pitch*pitch)*(height/pitch)); + gp_Pnt2d end = line->Value(sqrt(4.0 * pi * pi + pitch * pitch) * (height / pitch)); if (newStyle) { // See discussion at 0001247: Part Conical Helix Height/Pitch Incorrect if (angle >= Precision::Confusion()) { // calculate end point for conical helix Standard_Real v = height / cos(angle); - Standard_Real u = coneDir * (height/pitch) * 2.0 * pi; + Standard_Real u = coneDir * (height / pitch) * 2.0 * pi; gp_Pnt2d cend(u, v); end = cend; } } - Handle(Geom2d_TrimmedCurve) segm = GCE2d_MakeSegment(beg , end); + Handle(Geom2d_TrimmedCurve) segm = GCE2d_MakeSegment(beg, end); - TopoDS_Edge edgeOnSurf = BRepBuilderAPI_MakeEdge(segm , surf); + TopoDS_Edge edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf); TopoDS_Wire wire = BRepBuilderAPI_MakeWire(edgeOnSurf); BRepLib::BuildCurves3d(wire); return TopoDS_Shape(std::move(wire)); @@ -2200,35 +2348,42 @@ TopoDS_Shape TopoShape::makeHelix(Standard_Real pitch, Standard_Real height, // makeLongHelix is a workaround for an OCC problem found in helices with more than // some magic number of turns. See Mantis #0954. //*********** -TopoDS_Shape TopoShape::makeLongHelix(Standard_Real pitch, Standard_Real height, - Standard_Real radius, Standard_Real angle, - Standard_Boolean leftHanded) const +TopoDS_Shape TopoShape::makeLongHelix( + Standard_Real pitch, + Standard_Real height, + Standard_Real radius, + Standard_Real angle, + Standard_Boolean leftHanded +) const { using std::numbers::pi; - if (pitch < Precision::Confusion()) + if (pitch < Precision::Confusion()) { Standard_Failure::Raise("Pitch of helix too small"); + } - if (height < Precision::Confusion()) + if (height < Precision::Confusion()) { Standard_Failure::Raise("Height of helix too small"); + } - gp_Ax2 cylAx2(gp_Pnt(0.0,0.0,0.0) , gp::DZ()); + gp_Ax2 cylAx2(gp_Pnt(0.0, 0.0, 0.0), gp::DZ()); Handle(Geom_Surface) surf; Standard_Boolean isCylinder; - if (std::fabs(angle) < Precision::Confusion()) { // Cylindrical helix - if (radius < Precision::Confusion()) + if (std::fabs(angle) < Precision::Confusion()) { // Cylindrical helix + if (radius < Precision::Confusion()) { Standard_Failure::Raise("Radius of helix too small"); - surf= new Geom_CylindricalSurface(cylAx2, radius); + } + surf = new Geom_CylindricalSurface(cylAx2, radius); isCylinder = true; } - else { // Conical helix + else { // Conical helix angle = Base::toRadians(angle); surf = new Geom_ConicalSurface(gp_Ax3(cylAx2), angle, radius); isCylinder = false; } - Standard_Real turns = height/pitch; + Standard_Real turns = height / pitch; unsigned long wholeTurns = floor(turns); Standard_Real partTurn = turns - wholeTurns; @@ -2243,37 +2398,37 @@ TopoDS_Shape TopoShape::makeLongHelix(Standard_Real pitch, Standard_Real height, Handle(Geom2d_Line) line = new Geom2d_Line(aAx2d); gp_Pnt2d beg = line->Value(0); gp_Pnt2d end; - Standard_Real u,v; + Standard_Real u, v; BRepBuilderAPI_MakeWire mkWire; Handle(Geom2d_TrimmedCurve) segm; TopoDS_Edge edgeOnSurf; for (unsigned long i = 0; i < wholeTurns; i++) { if (isCylinder) { - end = line->Value(sqrt(4.0*pi*pi+pitch*pitch)*(i+1)); + end = line->Value(sqrt(4.0 * pi * pi + pitch * pitch) * (i + 1)); } else { - u = coneDir * (i+1) * 2.0 * pi; - v = ((i+1) * pitch) / cos(angle); + u = coneDir * (i + 1) * 2.0 * pi; + v = ((i + 1) * pitch) / cos(angle); end = gp_Pnt2d(u, v); } - segm = GCE2d_MakeSegment(beg , end); - edgeOnSurf = BRepBuilderAPI_MakeEdge(segm , surf); + segm = GCE2d_MakeSegment(beg, end); + edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf); mkWire.Add(edgeOnSurf); beg = end; } if (partTurn > Precision::Confusion()) { if (isCylinder) { - end = line->Value(sqrt(4.0*pi*pi+pitch*pitch)*turns); + end = line->Value(sqrt(4.0 * pi * pi + pitch * pitch) * turns); } else { u = coneDir * turns * 2.0 * pi; v = height / cos(angle); end = gp_Pnt2d(u, v); } - segm = GCE2d_MakeSegment(beg , end); - edgeOnSurf = BRepBuilderAPI_MakeEdge(segm , surf); + segm = GCE2d_MakeSegment(beg, end); + edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf); mkWire.Add(edgeOnSurf); } @@ -2282,110 +2437,131 @@ TopoDS_Shape TopoShape::makeLongHelix(Standard_Real pitch, Standard_Real height, return TopoDS_Shape(std::move(wire)); } -TopoDS_Shape TopoShape::makeSpiralHelix(Standard_Real radiusbottom, Standard_Real radiustop, - Standard_Real height, Standard_Real nbturns, - Standard_Real breakperiod, Standard_Boolean leftHanded) const +TopoDS_Shape TopoShape::makeSpiralHelix( + Standard_Real radiusbottom, + Standard_Real radiustop, + Standard_Real height, + Standard_Real nbturns, + Standard_Real breakperiod, + Standard_Boolean leftHanded +) const { // 1000 periods is an OCCT limit. The 3D curve gets truncated // if the 2D curve spans beyond this limit. - if ((breakperiod < 0) || (breakperiod > 1000)) + if ((breakperiod < 0) || (breakperiod > 1000)) { Standard_Failure::Raise("Break period must be in [0, 1000]"); - if (breakperiod == 0) + } + if (breakperiod == 0) { breakperiod = 1000; - if (nbturns <= 0) + } + if (nbturns <= 0) { Standard_Failure::Raise("Number of turns must be greater than 0"); + } - Standard_Real nbPeriods = nbturns/breakperiod; + Standard_Real nbPeriods = nbturns / breakperiod; Standard_Real nbFullPeriods = floor(nbPeriods); Standard_Real partPeriod = nbPeriods - nbFullPeriods; // A Bezier curve is used below, to get a periodic surface also for spirals. - TColgp_Array1OfPnt poles(1,2); + TColgp_Array1OfPnt poles(1, 2); poles(1) = gp_Pnt(radiusbottom, 0, 0); poles(2) = gp_Pnt(radiustop, 0, height); Handle(Geom_BezierCurve) meridian = new Geom_BezierCurve(poles); - gp_Ax1 axis(gp_Pnt(0.0,0.0,0.0) , gp::DZ()); + gp_Ax1 axis(gp_Pnt(0.0, 0.0, 0.0), gp::DZ()); Handle(Geom_Surface) surf = new Geom_SurfaceOfRevolution(meridian, axis); gp_Pnt2d beg(0, 0); gp_Pnt2d end(0, 0); gp_Vec2d dir(breakperiod * 2.0 * std::numbers::pi, 1 / nbPeriods); - if (leftHanded == Standard_True) + if (leftHanded == Standard_True) { dir = gp_Vec2d(-breakperiod * 2.0 * std::numbers::pi, 1 / nbPeriods); + } Handle(Geom2d_TrimmedCurve) segm; TopoDS_Edge edgeOnSurf; BRepBuilderAPI_MakeWire mkWire; for (unsigned long i = 0; i < nbFullPeriods; i++) { end = beg.Translated(dir); - segm = GCE2d_MakeSegment(beg , end); - edgeOnSurf = BRepBuilderAPI_MakeEdge(segm , surf); + segm = GCE2d_MakeSegment(beg, end); + edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf); mkWire.Add(edgeOnSurf); beg = end; } if (partPeriod > Precision::Confusion()) { dir.Scale(partPeriod); end = beg.Translated(dir); - segm = GCE2d_MakeSegment(beg , end); - edgeOnSurf = BRepBuilderAPI_MakeEdge(segm , surf); + segm = GCE2d_MakeSegment(beg, end); + edgeOnSurf = BRepBuilderAPI_MakeEdge(segm, surf); mkWire.Add(edgeOnSurf); } TopoDS_Wire wire = mkWire.Wire(); - BRepLib::BuildCurves3d(wire, Precision::Confusion() * 1e-6 * (radiusbottom+radiustop), GeomAbs_Shape::GeomAbs_C1, 14, 10000); // precision must be reduced for very large parts to avoid #17113 + BRepLib::BuildCurves3d( + wire, + Precision::Confusion() * 1e-6 * (radiusbottom + radiustop), + GeomAbs_Shape::GeomAbs_C1, + 14, + 10000 + ); // precision must be reduced for very large parts to avoid #17113 return TopoDS_Shape(std::move(wire)); } -TopoDS_Shape TopoShape::makeThread(Standard_Real pitch, - Standard_Real depth, - Standard_Real height, - Standard_Real radius) const +TopoDS_Shape TopoShape::makeThread( + Standard_Real pitch, + Standard_Real depth, + Standard_Real height, + Standard_Real radius +) const { using std::numbers::pi; - if (pitch < Precision::Confusion()) + if (pitch < Precision::Confusion()) { Standard_Failure::Raise("Pitch of thread too small"); + } - if (depth < Precision::Confusion()) + if (depth < Precision::Confusion()) { Standard_Failure::Raise("Depth of thread too small"); + } - if (height < Precision::Confusion()) + if (height < Precision::Confusion()) { Standard_Failure::Raise("Height of thread too small"); + } - if (radius < Precision::Confusion()) + if (radius < Precision::Confusion()) { Standard_Failure::Raise("Radius of thread too small"); + } - //Threading : Create Surfaces - gp_Ax2 cylAx2(gp_Pnt(0.0,0.0,0.0) , gp::DZ()); - Handle(Geom_CylindricalSurface) aCyl1 = new Geom_CylindricalSurface(cylAx2 , radius); - Handle(Geom_CylindricalSurface) aCyl2 = new Geom_CylindricalSurface(cylAx2 , radius+depth); + // Threading : Create Surfaces + gp_Ax2 cylAx2(gp_Pnt(0.0, 0.0, 0.0), gp::DZ()); + Handle(Geom_CylindricalSurface) aCyl1 = new Geom_CylindricalSurface(cylAx2, radius); + Handle(Geom_CylindricalSurface) aCyl2 = new Geom_CylindricalSurface(cylAx2, radius + depth); - //Threading : Define 2D Curves - gp_Pnt2d aPnt(2. * pi , height / 2.); - gp_Dir2d aDir(2. * pi , height / 4.); - gp_Ax2d aAx2d(aPnt , aDir); + // Threading : Define 2D Curves + gp_Pnt2d aPnt(2. * pi, height / 2.); + gp_Dir2d aDir(2. * pi, height / 4.); + gp_Ax2d aAx2d(aPnt, aDir); Standard_Real aMajor = 2. * pi; Standard_Real aMinor = pitch; - Handle(Geom2d_Ellipse) anEllipse1 = new Geom2d_Ellipse(aAx2d , aMajor , aMinor); - Handle(Geom2d_Ellipse) anEllipse2 = new Geom2d_Ellipse(aAx2d , aMajor , aMinor / 4); + Handle(Geom2d_Ellipse) anEllipse1 = new Geom2d_Ellipse(aAx2d, aMajor, aMinor); + Handle(Geom2d_Ellipse) anEllipse2 = new Geom2d_Ellipse(aAx2d, aMajor, aMinor / 4); - Handle(Geom2d_TrimmedCurve) aArc1 = new Geom2d_TrimmedCurve(anEllipse1 , 0 , pi); - Handle(Geom2d_TrimmedCurve) aArc2 = new Geom2d_TrimmedCurve(anEllipse2 , 0 , pi); + Handle(Geom2d_TrimmedCurve) aArc1 = new Geom2d_TrimmedCurve(anEllipse1, 0, pi); + Handle(Geom2d_TrimmedCurve) aArc2 = new Geom2d_TrimmedCurve(anEllipse2, 0, pi); gp_Pnt2d anEllipsePnt1 = anEllipse1->Value(0); gp_Pnt2d anEllipsePnt2 = anEllipse1->Value(pi); - Handle(Geom2d_TrimmedCurve) aSegment = GCE2d_MakeSegment(anEllipsePnt1 , anEllipsePnt2); + Handle(Geom2d_TrimmedCurve) aSegment = GCE2d_MakeSegment(anEllipsePnt1, anEllipsePnt2); - //Threading : Build Edges and Wires - TopoDS_Edge aEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(aArc1 , aCyl1); - TopoDS_Edge aEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment , aCyl1); - TopoDS_Edge aEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(aArc2 , aCyl2); - TopoDS_Edge aEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment , aCyl2); + // Threading : Build Edges and Wires + TopoDS_Edge aEdge1OnSurf1 = BRepBuilderAPI_MakeEdge(aArc1, aCyl1); + TopoDS_Edge aEdge2OnSurf1 = BRepBuilderAPI_MakeEdge(aSegment, aCyl1); + TopoDS_Edge aEdge1OnSurf2 = BRepBuilderAPI_MakeEdge(aArc2, aCyl2); + TopoDS_Edge aEdge2OnSurf2 = BRepBuilderAPI_MakeEdge(aSegment, aCyl2); - TopoDS_Wire threadingWire1 = BRepBuilderAPI_MakeWire(aEdge1OnSurf1 , aEdge2OnSurf1); - TopoDS_Wire threadingWire2 = BRepBuilderAPI_MakeWire(aEdge1OnSurf2 , aEdge2OnSurf2); + TopoDS_Wire threadingWire1 = BRepBuilderAPI_MakeWire(aEdge1OnSurf1, aEdge2OnSurf1); + TopoDS_Wire threadingWire2 = BRepBuilderAPI_MakeWire(aEdge1OnSurf2, aEdge2OnSurf2); BRepLib::BuildCurves3d(threadingWire1); BRepLib::BuildCurves3d(threadingWire2); @@ -2399,14 +2575,16 @@ TopoDS_Shape TopoShape::makeThread(Standard_Real pitch, return aTool.Shape(); } -TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, - Standard_Boolean isSolid, - Standard_Boolean isRuled, - Standard_Boolean isClosed, - Standard_Integer maxDegree) const +TopoDS_Shape TopoShape::makeLoft( + const TopTools_ListOfShape& profiles, + Standard_Boolean isSolid, + Standard_Boolean isRuled, + Standard_Boolean isClosed, + Standard_Integer maxDegree +) const { // http://opencascade.blogspot.com/2010/01/surface-modeling-part5.html - BRepOffsetAPI_ThruSections aGenerator (isSolid,isRuled); + BRepOffsetAPI_ThruSections aGenerator(isSolid, isRuled); aGenerator.SetMaxDegree(maxDegree); TopTools_ListIteratorOfListOfShape it; @@ -2414,7 +2592,7 @@ TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, for (it.Initialize(profiles); it.More(); it.Next()) { const TopoDS_Shape& item = it.Value(); if (!item.IsNull() && item.ShapeType() == TopAbs_VERTEX) { - aGenerator.AddVertex(TopoDS::Vertex (item)); + aGenerator.AddVertex(TopoDS::Vertex(item)); countShapes++; } else if (!item.IsNull() && item.ShapeType() == TopAbs_EDGE) { @@ -2423,7 +2601,7 @@ TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, countShapes++; } else if (!item.IsNull() && item.ShapeType() == TopAbs_WIRE) { - aGenerator.AddWire(TopoDS::Wire (item)); + aGenerator.AddWire(TopoDS::Wire(item)); countShapes++; } } @@ -2434,27 +2612,28 @@ TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, else { // close loft by duplicating initial profile as last profile. not perfect. if (isClosed) { - /* can only close loft in certain combinations of Vertex/Wire(Edge): - - V1-W1-W2-W3-V2 ==> V1-W1-W2-W3-V2-V1 invalid closed - - V1-W1-W2-W3 ==> V1-W1-W2-W3-V1 valid closed - - W1-W2-W3-V1 ==> W1-W2-W3-V1-W1 invalid closed - - W1-W2-W3 ==> W1-W2-W3-W1 valid closed*/ + /* can only close loft in certain combinations of Vertex/Wire(Edge): + - V1-W1-W2-W3-V2 ==> V1-W1-W2-W3-V2-V1 invalid closed + - V1-W1-W2-W3 ==> V1-W1-W2-W3-V1 valid closed + - W1-W2-W3-V1 ==> W1-W2-W3-V1-W1 invalid closed + - W1-W2-W3 ==> W1-W2-W3-W1 valid closed*/ if (profiles.Last().ShapeType() == TopAbs_VERTEX) { - Base::Console().message("TopoShape::makeLoft: can't close Loft with Vertex as last profile. 'Closed' ignored.\n"); + Base::Console() + .message("TopoShape::makeLoft: can't close Loft with Vertex as last profile. 'Closed' ignored.\n"); } else { // repeat Add logic above for first profile const TopoDS_Shape& firstProfile = profiles.First(); - if (firstProfile.ShapeType() == TopAbs_VERTEX) { - aGenerator.AddVertex(TopoDS::Vertex (firstProfile)); + if (firstProfile.ShapeType() == TopAbs_VERTEX) { + aGenerator.AddVertex(TopoDS::Vertex(firstProfile)); countShapes++; } - else if (firstProfile.ShapeType() == TopAbs_EDGE) { - aGenerator.AddWire(TopoDS::Wire (firstProfile)); + else if (firstProfile.ShapeType() == TopAbs_EDGE) { + aGenerator.AddWire(TopoDS::Wire(firstProfile)); countShapes++; } - else if (firstProfile.ShapeType() == TopAbs_WIRE) { - aGenerator.AddWire(TopoDS::Wire (firstProfile)); + else if (firstProfile.ShapeType() == TopAbs_WIRE) { + aGenerator.AddWire(TopoDS::Wire(firstProfile)); countShapes++; } } @@ -2462,29 +2641,35 @@ TopoDS_Shape TopoShape::makeLoft(const TopTools_ListOfShape& profiles, } Standard_Boolean anIsCheck = Standard_True; - aGenerator.CheckCompatibility (anIsCheck); // use BRepFill_CompatibleWires on profiles. force #edges, orientation, "origin" to match. + aGenerator.CheckCompatibility(anIsCheck); // use BRepFill_CompatibleWires on profiles. force + // #edges, orientation, "origin" to match. #if OCC_VERSION_HEX >= 0x070600 aGenerator.Build(OCCTProgressIndicator::getAppIndicator().Start()); #else aGenerator.Build(); #endif - if (!aGenerator.IsDone()) + if (!aGenerator.IsDone()) { Standard_Failure::Raise("Failed to create loft face"); + } - //Base::Console().message("DEBUG: TopoShape::makeLoft returns.\n"); + // Base::Console().message("DEBUG: TopoShape::makeLoft returns.\n"); return aGenerator.Shape(); } TopoDS_Shape TopoShape::makePrism(const gp_Vec& vec) const { - if (this->_Shape.IsNull()) Standard_Failure::Raise("cannot sweep empty shape"); + if (this->_Shape.IsNull()) { + Standard_Failure::Raise("cannot sweep empty shape"); + } BRepPrimAPI_MakePrism mkPrism(this->_Shape, vec); return mkPrism.Shape(); } TopoDS_Shape TopoShape::revolve(const gp_Ax1& axis, double d, Standard_Boolean isSolid) const { - if (this->_Shape.IsNull()) Standard_Failure::Raise("cannot revolve empty shape"); + if (this->_Shape.IsNull()) { + Standard_Failure::Raise("cannot revolve empty shape"); + } TopoDS_Face f; TopoDS_Wire w; @@ -2492,37 +2677,49 @@ TopoDS_Shape TopoShape::revolve(const gp_Ax1& axis, double d, Standard_Boolean i Standard_Boolean convertFailed = false; TopoDS_Shape base = this->_Shape; - if ((isSolid) && (BRep_Tool::IsClosed(base)) && - ((base.ShapeType() == TopAbs_EDGE) || (base.ShapeType() == TopAbs_WIRE))) { + if ((isSolid) && (BRep_Tool::IsClosed(base)) + && ((base.ShapeType() == TopAbs_EDGE) || (base.ShapeType() == TopAbs_WIRE))) { if (base.ShapeType() == TopAbs_EDGE) { BRepBuilderAPI_MakeWire mkWire(TopoDS::Edge(base)); if (mkWire.IsDone()) { - w = mkWire.Wire(); } + w = mkWire.Wire(); + } else { - convertFailed = true; } + convertFailed = true; + } } else { - w = TopoDS::Wire(base);} + w = TopoDS::Wire(base); + } if (!convertFailed) { BRepBuilderAPI_MakeFace mkFace(w); if (mkFace.IsDone()) { f = mkFace.Face(); - base = f; } + base = f; + } else { - convertFailed = true; } + convertFailed = true; + } } } if (convertFailed) { - Base::Console().message("TopoShape::revolve could not make Solid from Wire/Edge.\n");} + Base::Console().message("TopoShape::revolve could not make Solid from Wire/Edge.\n"); + } - BRepPrimAPI_MakeRevol mkRevol(base, axis,d); + BRepPrimAPI_MakeRevol mkRevol(base, axis, d); return mkRevol.Shape(); } -TopoDS_Shape TopoShape::makeOffsetShape(double offset, double tol, bool intersection, - bool selfInter, short offsetMode, short join, - bool fill) const +TopoDS_Shape TopoShape::makeOffsetShape( + double offset, + double tol, + bool intersection, + bool selfInter, + short offsetMode, + short join, + bool fill +) const { // If the input shape is a compound with a single solid then the offset // algorithm creates only a shell instead of a solid which causes errors @@ -2538,64 +2735,67 @@ TopoDS_Shape TopoShape::makeOffsetShape(double offset, double tol, bool intersec // If exactly one solid then get it TopoDS_Shape inputSolid = xp.Current(); xp.Next(); - if (xp.More() == Standard_False) + if (xp.More() == Standard_False) { inputShape = inputSolid; + } } } BRepOffsetAPI_MakeOffsetShape mkOffset; - mkOffset.PerformByJoin(inputShape, offset, tol, BRepOffset_Mode(offsetMode), - intersection ? Standard_True : Standard_False, - selfInter ? Standard_True : Standard_False, - GeomAbs_JoinType(join)); + mkOffset.PerformByJoin( + inputShape, + offset, + tol, + BRepOffset_Mode(offsetMode), + intersection ? Standard_True : Standard_False, + selfInter ? Standard_True : Standard_False, + GeomAbs_JoinType(join) + ); - if (!mkOffset.IsDone()) + if (!mkOffset.IsDone()) { Standard_Failure::Raise("BRepOffsetAPI_MakeOffsetShape not done"); + } const TopoDS_Shape& res = mkOffset.Shape(); - if (!fill) + if (!fill) { return res; + } - //get perimeter wire of original shape. - //Wires returned seem to have edges in connection order. + // get perimeter wire of original shape. + // Wires returned seem to have edges in connection order. ShapeAnalysis_FreeBoundsProperties freeCheck(this->_Shape); freeCheck.Perform(); - if (freeCheck.NbClosedFreeBounds() < 1) - { + if (freeCheck.NbClosedFreeBounds() < 1) { Standard_Failure::Raise("no closed bounds"); } BRep_Builder builder; TopoDS_Compound perimeterCompound; builder.MakeCompound(perimeterCompound); - for (int index = 1; index <= freeCheck.NbClosedFreeBounds(); ++index) - { + for (int index = 1; index <= freeCheck.NbClosedFreeBounds(); ++index) { TopoDS_Wire originalWire = freeCheck.ClosedFreeBound(index)->FreeBound(); const BRepAlgo_Image& img = mkOffset.MakeOffset().OffsetEdgesFromShapes(); - //build offset wire. + // build offset wire. TopoDS_Wire offsetWire; builder.MakeWire(offsetWire); TopExp_Explorer xp; - for (xp.Init(originalWire, TopAbs_EDGE); xp.More(); xp.Next()) - { - if (!img.HasImage(xp.Current())) - { + for (xp.Init(originalWire, TopAbs_EDGE); xp.More(); xp.Next()) { + if (!img.HasImage(xp.Current())) { Standard_Failure::Raise("no image for shape"); } const TopTools_ListOfShape& currentImage = img.Image(xp.Current()); TopTools_ListIteratorOfListOfShape listIt; int edgeCount(0); TopoDS_Edge mappedEdge; - for (listIt.Initialize(currentImage); listIt.More(); listIt.Next()) - { - if (listIt.Value().ShapeType() != TopAbs_EDGE) + for (listIt.Initialize(currentImage); listIt.More(); listIt.Next()) { + if (listIt.Value().ShapeType() != TopAbs_EDGE) { continue; + } edgeCount++; mappedEdge = TopoDS::Edge(listIt.Value()); } - if (edgeCount != 1) - { + if (edgeCount != 1) { std::ostringstream stream; stream << "wrong edge count: " << edgeCount << std::endl; Standard_Failure::Raise(stream.str().c_str()); @@ -2603,9 +2803,9 @@ TopoDS_Shape TopoShape::makeOffsetShape(double offset, double tol, bool intersec builder.Add(offsetWire, mappedEdge); } - //It would be nice if we could get thruSections to build planar faces - //in all areas possible, so we could run through refine. I tried setting - //ruled to standard_true, but that didn't have the desired affect. + // It would be nice if we could get thruSections to build planar faces + // in all areas possible, so we could run through refine. I tried setting + // ruled to standard_true, but that didn't have the desired affect. BRepOffsetAPI_ThruSections aGenerator; aGenerator.AddWire(originalWire); aGenerator.AddWire(offsetWire); @@ -2614,49 +2814,55 @@ TopoDS_Shape TopoShape::makeOffsetShape(double offset, double tol, bool intersec #else aGenerator.Build(); #endif - if (!aGenerator.IsDone()) - { + if (!aGenerator.IsDone()) { Standard_Failure::Raise("ThruSections failed"); } builder.Add(perimeterCompound, aGenerator.Shape()); } - //still had to sew. not using the passed in parameter for sew. - //Sew has it's own default tolerance. Opinions? + // still had to sew. not using the passed in parameter for sew. + // Sew has it's own default tolerance. Opinions? BRepBuilderAPI_Sewing sewTool; sewTool.Add(this->_Shape); sewTool.Add(perimeterCompound); sewTool.Add(res); - sewTool.Perform(); //Perform Sewing + sewTool.Perform(); // Perform Sewing TopoDS_Shape outputShape = sewTool.SewedShape(); - if ((outputShape.ShapeType() == TopAbs_SHELL) && (outputShape.Closed())) - { + if ((outputShape.ShapeType() == TopAbs_SHELL) && (outputShape.Closed())) { BRepBuilderAPI_MakeSolid solidMaker(TopoDS::Shell(outputShape)); - if (solidMaker.IsDone()) - { + if (solidMaker.IsDone()) { TopoDS_Solid temp = solidMaker.Solid(); - //contrary to the occ docs the return value OrientCloseSolid doesn't - //indicate whether the shell was open or not. It returns true with an - //open shell and we end up with an invalid solid. - if (BRepLib::OrientClosedSolid(temp)) + // contrary to the occ docs the return value OrientCloseSolid doesn't + // indicate whether the shell was open or not. It returns true with an + // open shell and we end up with an invalid solid. + if (BRepLib::OrientClosedSolid(temp)) { outputShape = temp; + } } } return outputShape; } -TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, bool allowOpenResult, bool intersection) const +TopoDS_Shape TopoShape::makeOffset2D( + double offset, + short joinType, + bool fill, + bool allowOpenResult, + bool intersection +) const { - if (_Shape.IsNull()) + if (_Shape.IsNull()) { throw Base::ValueError("makeOffset2D: input shape is null!"); + } // OUTLINE OF MAKEOFFSET2D // * Prepare shapes to process // ** if _Shape is a compound, recursively call this routine for all subcompounds - // ** if intrsection, dump all non-compound children into shapes to process; otherwise call this routine recursively for all children + // ** if intrsection, dump all non-compound children into shapes to process; otherwise call this + // routine recursively for all children // ** if _shape isn't a compound, dump it straight to shapes to process // * Test for shape types, and convert them all to wires // * find plane @@ -2665,7 +2871,8 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b // ** convert offset result back to faces, if inputs were faces // ** OR do offset filling: // *** for closed wires, simply feed source wires + offset wires to smart facemaker - // *** for open wires, try to connect source anf offset result by creating new edges (incomplete implementation) + // *** for open wires, try to connect source anf offset result by creating new edges (incomplete + // implementation) // ** actual call to FaceMakerBullseye, unified for all facemaking. std::vector shapesToProcess; @@ -2674,20 +2881,26 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b if (this->_Shape.ShapeType() == TopAbs_COMPOUND) { if (!intersection) { - //simply recursively process the children, independently + // simply recursively process the children, independently TopoDS_Iterator it(_Shape); - for( ; it.More() ; it.Next()) { - shapesToReturn.push_back( TopoShape(it.Value()).makeOffset2D(offset, joinType, fill, allowOpenResult, intersection) ); + for (; it.More(); it.Next()) { + shapesToReturn.push_back( + TopoShape(it.Value()).makeOffset2D(offset, joinType, fill, allowOpenResult, intersection) + ); forceOutputCompound = true; } } else { - //collect non-compounds from this compound for collective offset. Process other shapes independently. + // collect non-compounds from this compound for collective offset. Process other shapes + // independently. TopoDS_Iterator it(_Shape); - for( ; it.More() ; it.Next()) { - if(it.Value().ShapeType() == TopAbs_COMPOUND) { - //recursively process subcompounds - shapesToReturn.push_back( TopoShape(it.Value()).makeOffset2D(offset, joinType, fill, allowOpenResult, intersection) ); + for (; it.More(); it.Next()) { + if (it.Value().ShapeType() == TopAbs_COMPOUND) { + // recursively process subcompounds + shapesToReturn.push_back( + TopoShape(it.Value()) + .makeOffset2D(offset, joinType, fill, allowOpenResult, intersection) + ); forceOutputCompound = true; } else { @@ -2700,85 +2913,96 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b shapesToProcess.push_back(this->_Shape); } - if(!shapesToProcess.empty()) { + if (!shapesToProcess.empty()) { - //although 2d offset supports offsetting a face directly, it seems there is - //no way to do a collective offset of multiple faces. So, we are doing it - //by getting all wires from the faces, and applying offsets to them, and - //reassembling the faces later. + // although 2d offset supports offsetting a face directly, it seems there is + // no way to do a collective offset of multiple faces. So, we are doing it + // by getting all wires from the faces, and applying offsets to them, and + // reassembling the faces later. std::vector sourceWires; bool haveWires = false; bool haveFaces = false; - for(TopoDS_Shape &sh : shapesToProcess){ + for (TopoDS_Shape& sh : shapesToProcess) { switch (sh.ShapeType()) { case TopAbs_EDGE: - case TopAbs_WIRE:{ - //convert edge to a wire if necessary... + case TopAbs_WIRE: { + // convert edge to a wire if necessary... TopoDS_Wire sourceWire; - if (sh.ShapeType() == TopAbs_WIRE){ + if (sh.ShapeType() == TopAbs_WIRE) { sourceWire = TopoDS::Wire(sh); - } else { //edge + } + else { // edge sourceWire = BRepBuilderAPI_MakeWire(TopoDS::Edge(sh)).Wire(); } sourceWires.push_back(sourceWire); haveWires = true; - }break; - case TopAbs_FACE:{ - //get all wires of the face + } break; + case TopAbs_FACE: { + // get all wires of the face TopoDS_Iterator it(sh); - for(; it.More(); it.Next()){ + for (; it.More(); it.Next()) { sourceWires.push_back(TopoDS::Wire(it.Value())); } haveFaces = true; - }break; + } break; default: throw Base::TypeError("makeOffset2D: input shape is not an edge, wire or face or compound of those."); - break; + break; } } - if (haveWires && haveFaces) - throw Base::TypeError("makeOffset2D: collective offset of a mix of wires and faces is not supported"); - if (haveFaces) + if (haveWires && haveFaces) { + throw Base::TypeError( + "makeOffset2D: collective offset of a mix of wires and faces is not supported" + ); + } + if (haveFaces) { allowOpenResult = false; + } - //find plane. + // find plane. gp_Pln workingPlane; TopoDS_Compound compoundSourceWires; { BRep_Builder builder; builder.MakeCompound(compoundSourceWires); - for(TopoDS_Wire &w : sourceWires) + for (TopoDS_Wire& w : sourceWires) { builder.Add(compoundSourceWires, w); + } BRepLib_FindSurface planefinder(compoundSourceWires, -1, Standard_True); - if (!planefinder.Found()) + if (!planefinder.Found()) { throw Base::CADKernelError("makeOffset2D: wires are nonplanar or noncoplanar"); - if (haveFaces){ - //extract plane from first face (useful for preserving the plane of face precisely if dealing with only one face) + } + if (haveFaces) { + // extract plane from first face (useful for preserving the plane of face precisely + // if dealing with only one face) workingPlane = BRepAdaptor_Surface(TopoDS::Face(shapesToProcess[0])).Plane(); - } else { + } + else { workingPlane = GeomAdaptor_Surface(planefinder.Surface()).Plane(); } } - //do the offset.. + // do the offset.. TopoDS_Shape offsetShape; BRepOffsetAPI_MakeOffsetFix mkOffset(GeomAbs_JoinType(joinType), allowOpenResult); - for (TopoDS_Wire &w : sourceWires) { + for (TopoDS_Wire& w : sourceWires) { mkOffset.AddWire(w); } if (fabs(offset) > Precision::Confusion()) { try { - #if defined(__GNUC__) && defined (FC_OS_LINUX) +#if defined(__GNUC__) && defined(FC_OS_LINUX) Base::SignalException se; - #endif +#endif mkOffset.Perform(offset); } - catch (Standard_Failure &){ + catch (Standard_Failure&) { throw; } catch (...) { - throw Base::CADKernelError("BRepOffsetAPI_MakeOffset has crashed! (Unknown exception caught)"); + throw Base::CADKernelError( + "BRepOffsetAPI_MakeOffset has crashed! (Unknown exception caught)" + ); } offsetShape = mkOffset.Shape(); @@ -2787,138 +3011,166 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b offsetShape = mkOffset.Replace(GeomAbs_OffsetCurve, offsetShape); } - if (offsetShape.IsNull()) + if (offsetShape.IsNull()) { throw Base::CADKernelError("makeOffset2D: result of offsetting is null!"); + } - //Copying shape to fix strange orientation behavior, OCC7.0.0. See bug #2699 - // https://www.freecad.org/tracker/view.php?id=2699 + // Copying shape to fix strange orientation behavior, OCC7.0.0. See bug #2699 + // https://www.freecad.org/tracker/view.php?id=2699 offsetShape = BRepBuilderAPI_Copy(offsetShape).Shape(); } else { - offsetShape = sourceWires.size()>1 ? TopoDS_Shape(compoundSourceWires) : sourceWires[0]; + offsetShape = sourceWires.size() > 1 ? TopoDS_Shape(compoundSourceWires) : sourceWires[0]; } std::list offsetWires; - //interestingly, if wires are removed, empty compounds are returned by MakeOffset (as of OCC 7.0.0) - //so, we just extract all nesting - Handle(TopTools_HSequenceOfShape) seq = ShapeExtend_Explorer().SeqFromCompound(offsetShape, Standard_True); + // interestingly, if wires are removed, empty compounds are returned by MakeOffset (as of + // OCC 7.0.0) so, we just extract all nesting + Handle(TopTools_HSequenceOfShape) seq + = ShapeExtend_Explorer().SeqFromCompound(offsetShape, Standard_True); TopoDS_Iterator it(offsetShape); - for(int i = 0; i < seq->Length(); ++i){ - offsetWires.push_back(TopoDS::Wire(seq->Value(i+1))); + for (int i = 0; i < seq->Length(); ++i) { + offsetWires.push_back(TopoDS::Wire(seq->Value(i + 1))); } - if (offsetWires.empty()) + if (offsetWires.empty()) { throw Base::CADKernelError("makeOffset2D: offset result has no wires."); + } std::list wiresForMakingFaces; - if (!fill){ - if (haveFaces){ + if (!fill) { + if (haveFaces) { wiresForMakingFaces = offsetWires; } else { - for(TopoDS_Wire &w : offsetWires) + for (TopoDS_Wire& w : offsetWires) { shapesToReturn.push_back(w); + } } } else { - //fill offset - if (fabs(offset) < Precision::Confusion()) + // fill offset + if (fabs(offset) < Precision::Confusion()) { throw Base::ValueError("makeOffset2D: offset distance is zero. Can't fill offset."); + } - //filling offset. There are three major cases to consider: - // 1. source wires and result wires are closed (simplest) -> make face - // from source wire + offset wire + // filling offset. There are three major cases to consider: + // 1. source wires and result wires are closed (simplest) -> make face + // from source wire + offset wire // - // 2. source wire is open, but offset wire is closed (if not - // allowOpenResult). -> throw away source wire and make face right from - // offset result. + // 2. source wire is open, but offset wire is closed (if not + // allowOpenResult). -> throw away source wire and make face right from + // offset result. // - // 3. source and offset wire are both open (note that there may be - // closed islands in offset result) -> need connecting offset result to - // source wire with new edges + // 3. source and offset wire are both open (note that there may be + // closed islands in offset result) -> need connecting offset result to + // source wire with new edges - //first, lets split apart closed and open wires. + // first, lets split apart closed and open wires. std::list closedWires; std::list openWires; - for(TopoDS_Wire &w : sourceWires) - if (BRep_Tool::IsClosed(w)) + for (TopoDS_Wire& w : sourceWires) { + if (BRep_Tool::IsClosed(w)) { closedWires.push_back(w); - else + } + else { openWires.push_back(w); - for(TopoDS_Wire &w : offsetWires) - if (BRep_Tool::IsClosed(w)) + } + } + for (TopoDS_Wire& w : offsetWires) { + if (BRep_Tool::IsClosed(w)) { closedWires.push_back(w); - else + } + else { openWires.push_back(w); + } + } wiresForMakingFaces = closedWires; - if (!allowOpenResult || openWires.empty()){ - //just ignore all open wires + if (!allowOpenResult || openWires.empty()) { + // just ignore all open wires } else { - //We need to connect open wires to form closed wires. + // We need to connect open wires to form closed wires. - //for now, only support offsetting one open wire -> there should be exactly two open wires for connecting - if (openWires.size() != 2) + // for now, only support offsetting one open wire -> there should be exactly two + // open wires for connecting + if (openWires.size() != 2) { throw Base::CADKernelError("makeOffset2D: collective offset with filling of multiple wires is not supported yet."); + } TopoDS_Wire openWire1 = openWires.front(); TopoDS_Wire openWire2 = openWires.back(); - //find open vertices + // find open vertices BRepTools_WireExplorer xp; xp.Init(openWire1); TopoDS_Vertex v1 = xp.CurrentVertex(); - for(;xp.More();xp.Next()){}; + for (; xp.More(); xp.Next()) { + }; TopoDS_Vertex v2 = xp.CurrentVertex(); - //find open vertices + // find open vertices xp.Init(openWire2); TopoDS_Vertex v3 = xp.CurrentVertex(); - for(;xp.More();xp.Next()){}; + for (; xp.More(); xp.Next()) { + }; TopoDS_Vertex v4 = xp.CurrentVertex(); - //check - if (v1.IsNull()) throw NullShapeException("v1 is null"); - if (v2.IsNull()) throw NullShapeException("v2 is null"); - if (v3.IsNull()) throw NullShapeException("v3 is null"); - if (v4.IsNull()) throw NullShapeException("v4 is null"); + // check + if (v1.IsNull()) { + throw NullShapeException("v1 is null"); + } + if (v2.IsNull()) { + throw NullShapeException("v2 is null"); + } + if (v3.IsNull()) { + throw NullShapeException("v3 is null"); + } + if (v4.IsNull()) { + throw NullShapeException("v4 is null"); + } - //assemble new wire + // assemble new wire - //we want the connection order to be - //v1 -> openWire1 -> v2 -> (new edge) -> v4 -> openWire2(rev) -> v3 -> (new edge) -> v1 - //let's check if it's the case. If not, we reverse one wire and swap its endpoints. + // we want the connection order to be + // v1 -> openWire1 -> v2 -> (new edge) -> v4 -> openWire2(rev) -> v3 -> (new edge) + // -> v1 let's check if it's the case. If not, we reverse one wire and swap its + // endpoints. - if (fabs(gp_Vec(BRep_Tool::Pnt(v2), BRep_Tool::Pnt(v3)).Magnitude() - fabs(offset)) <= BRep_Tool::Tolerance(v2) + BRep_Tool::Tolerance(v3)){ + if (fabs(gp_Vec(BRep_Tool::Pnt(v2), BRep_Tool::Pnt(v3)).Magnitude() - fabs(offset)) + <= BRep_Tool::Tolerance(v2) + BRep_Tool::Tolerance(v3)) { openWire2.Reverse(); std::swap(v3, v4); v3.Reverse(); v4.Reverse(); } - else if ((fabs(gp_Vec(BRep_Tool::Pnt(v2), BRep_Tool::Pnt(v4)).Magnitude() - fabs(offset)) <= BRep_Tool::Tolerance(v2) + BRep_Tool::Tolerance(v4))){ - //orientation is as expected, nothing to do + else if ((fabs(gp_Vec(BRep_Tool::Pnt(v2), BRep_Tool::Pnt(v4)).Magnitude() - fabs(offset)) + <= BRep_Tool::Tolerance(v2) + BRep_Tool::Tolerance(v4))) { + // orientation is as expected, nothing to do } else { - throw Base::CADKernelError("makeOffset2D: fill offset: failed to establish open vertex relationship."); + throw Base::CADKernelError( + "makeOffset2D: fill offset: failed to establish open vertex relationship." + ); } - //now directions of open wires are aligned. Finally. make new wire! + // now directions of open wires are aligned. Finally. make new wire! BRepBuilderAPI_MakeWire mkWire; - //add openWire1 + // add openWire1 BRepTools_WireExplorer it; - for(it.Init(openWire1); it.More(); it.Next()){ + for (it.Init(openWire1); it.More(); it.Next()) { mkWire.Add(it.Current()); } - //add first joining edge - mkWire.Add(BRepBuilderAPI_MakeEdge(v2,v4).Edge()); - //add openWire2, in reverse order + // add first joining edge + mkWire.Add(BRepBuilderAPI_MakeEdge(v2, v4).Edge()); + // add openWire2, in reverse order openWire2.Reverse(); - for(it.Init(TopoDS::Wire(openWire2)); it.More(); it.Next()){ + for (it.Init(TopoDS::Wire(openWire2)); it.More(); it.Next()) { mkWire.Add(it.Current()); } - //add final joining edge - mkWire.Add(BRepBuilderAPI_MakeEdge(v3,v1).Edge()); + // add final joining edge + mkWire.Add(BRepBuilderAPI_MakeEdge(v3, v1).Edge()); #if OCC_VERSION_HEX >= 0x070600 mkWire.Build(OCCTProgressIndicator::getAppIndicator().Start()); @@ -2929,11 +3181,11 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b } } - //make faces - if (!wiresForMakingFaces.empty()){ + // make faces + if (!wiresForMakingFaces.empty()) { FaceMakerBullseye mkFace; mkFace.setPlane(workingPlane); - for(TopoDS_Wire &w : wiresForMakingFaces){ + for (TopoDS_Wire& w : wiresForMakingFaces) { mkFace.addWire(w); } #if OCC_VERSION_HEX >= 0x070600 @@ -2941,27 +3193,31 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b #else mkFace.Build(); #endif - if (mkFace.Shape().IsNull()) + if (mkFace.Shape().IsNull()) { throw Base::CADKernelError("makeOffset2D: making face failed (null shape returned)."); + } TopoDS_Shape result = mkFace.Shape(); - if (haveFaces && shapesToProcess.size() == 1) + if (haveFaces && shapesToProcess.size() == 1) { result.Orientation(shapesToProcess[0].Orientation()); + } ShapeExtend_Explorer xp; Handle(TopTools_HSequenceOfShape) result_leaves = xp.SeqFromCompound(result, Standard_True); - for(int i = 0; i < result_leaves->Length(); ++i) - shapesToReturn.push_back(result_leaves->Value(i+1)); + for (int i = 0; i < result_leaves->Length(); ++i) { + shapesToReturn.push_back(result_leaves->Value(i + 1)); + } } } - //assemble output compound - if (shapesToReturn.empty()) - return {}; //failure - if (shapesToReturn.size() > 1 || forceOutputCompound){ + // assemble output compound + if (shapesToReturn.empty()) { + return {}; // failure + } + if (shapesToReturn.size() > 1 || forceOutputCompound) { TopoDS_Compound result; BRep_Builder builder; builder.MakeCompound(result); - for(TopoDS_Shape &sh : shapesToReturn) { + for (TopoDS_Shape& sh : shapesToReturn) { if (!sh.IsNull()) { builder.Add(result, sh); } @@ -2973,23 +3229,36 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b } } -TopoDS_Shape TopoShape::makeThickSolid(const TopTools_ListOfShape& remFace, - double offset, double tol, bool intersection, - bool selfInter, short offsetMode, short join) const +TopoDS_Shape TopoShape::makeThickSolid( + const TopTools_ListOfShape& remFace, + double offset, + double tol, + bool intersection, + bool selfInter, + short offsetMode, + short join +) const { BRepOffsetAPI_MakeThickSolid mkThick; - mkThick.MakeThickSolidByJoin(this->_Shape, remFace, offset, tol, BRepOffset_Mode(offsetMode), + mkThick.MakeThickSolidByJoin( + this->_Shape, + remFace, + offset, + tol, + BRepOffset_Mode(offsetMode), intersection ? Standard_True : Standard_False, selfInter ? Standard_True : Standard_False, - GeomAbs_JoinType(join)); + GeomAbs_JoinType(join) + ); return mkThick.Shape(); } -void TopoShape::transformGeometry(const Base::Matrix4D &rclMat) +void TopoShape::transformGeometry(const Base::Matrix4D& rclMat) { try { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot transform null shape"); + } *this = makeGTransform(rclMat); } @@ -3000,22 +3269,23 @@ void TopoShape::transformGeometry(const Base::Matrix4D &rclMat) TopoDS_Shape TopoShape::transformGShape(const Base::Matrix4D& rclTrf, bool copy) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot transform null shape"); + } gp_GTrsf mat; - mat.SetValue(1,1,rclTrf[0][0]); - mat.SetValue(2,1,rclTrf[1][0]); - mat.SetValue(3,1,rclTrf[2][0]); - mat.SetValue(1,2,rclTrf[0][1]); - mat.SetValue(2,2,rclTrf[1][1]); - mat.SetValue(3,2,rclTrf[2][1]); - mat.SetValue(1,3,rclTrf[0][2]); - mat.SetValue(2,3,rclTrf[1][2]); - mat.SetValue(3,3,rclTrf[2][2]); - mat.SetValue(1,4,rclTrf[0][3]); - mat.SetValue(2,4,rclTrf[1][3]); - mat.SetValue(3,4,rclTrf[2][3]); + mat.SetValue(1, 1, rclTrf[0][0]); + mat.SetValue(2, 1, rclTrf[1][0]); + mat.SetValue(3, 1, rclTrf[2][0]); + mat.SetValue(1, 2, rclTrf[0][1]); + mat.SetValue(2, 2, rclTrf[1][1]); + mat.SetValue(3, 2, rclTrf[2][1]); + mat.SetValue(1, 3, rclTrf[0][2]); + mat.SetValue(2, 3, rclTrf[1][2]); + mat.SetValue(3, 3, rclTrf[2][2]); + mat.SetValue(1, 4, rclTrf[0][3]); + mat.SetValue(2, 4, rclTrf[1][3]); + mat.SetValue(3, 4, rclTrf[2][3]); // this copy step seems to eliminate Part.OCCError: gp_GTrsf::Trsf() - non-orthogonal GTrsf BRepBuilderAPI_Copy copier(this->_Shape); // geometric transformation @@ -3025,10 +3295,11 @@ TopoDS_Shape TopoShape::transformGShape(const Base::Matrix4D& rclTrf, bool copy) bool TopoShape::transformShape(const Base::Matrix4D& rclTrf, bool copy, bool checkScale) { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot transform null shape"); + } - return _makeTransform(TopoShape(*this),rclTrf,nullptr,checkScale,copy); + return _makeTransform(TopoShape(*this), rclTrf, nullptr, checkScale, copy); } TopoDS_Shape TopoShape::mirror(const gp_Ax2& ax2) const @@ -3041,27 +3312,30 @@ TopoDS_Shape TopoShape::mirror(const gp_Ax2& ax2) const TopoDS_Shape TopoShape::toNurbs() const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Cannot convert null shape to NURBS"); + } BRepBuilderAPI_NurbsConvert mkNurbs(this->_Shape); return mkNurbs.Shape(); } -TopoDS_Shape TopoShape::replaceShape(const std::vector< std::pair >& s) const +TopoDS_Shape TopoShape::replaceShape(const std::vector>& s) const { BRepTools_ReShape reshape; - std::vector< std::pair >::const_iterator it; - for (it = s.begin(); it != s.end(); ++it) + std::vector>::const_iterator it; + for (it = s.begin(); it != s.end(); ++it) { reshape.Replace(it->first, it->second); + } return reshape.Apply(this->_Shape, TopAbs_SHAPE); } TopoDS_Shape TopoShape::removeShape(const std::vector& s) const { BRepTools_ReShape reshape; - for (const auto & it : s) + for (const auto& it : s) { reshape.Remove(it); + } return reshape.Apply(this->_Shape, TopAbs_SHAPE); } @@ -3129,8 +3403,9 @@ bool TopoShape::fix() bool TopoShape::fix(double precision, double mintol, double maxtol) { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return false; + } TopAbs_ShapeEnum type = this->_Shape.ShapeType(); @@ -3142,7 +3417,7 @@ bool TopoShape::fix(double precision, double mintol, double maxtol) fix.Perform(); if (type == TopAbs_SOLID) { - //fix.FixEdgeTool(); + // fix.FixEdgeTool(); fix.FixWireTool()->Perform(); fix.FixFaceTool()->Perform(); fix.FixShellTool()->Perform(); @@ -3182,19 +3457,20 @@ bool TopoShape::removeInternalWires(double minArea) TopoDS_Shape TopoShape::removeSplitter() const { - if (_Shape.IsNull()) + if (_Shape.IsNull()) { Standard_Failure::Raise("Cannot remove splitter from empty shape"); + } if (_Shape.ShapeType() == TopAbs_SOLID) { - const TopoDS_Solid &solid = TopoDS::Solid(_Shape); + const TopoDS_Solid& solid = TopoDS::Solid(_Shape); BRepBuilderAPI_MakeSolid mkSolid; TopExp_Explorer it; for (it.Init(solid, TopAbs_SHELL); it.More(); it.Next()) { - const TopoDS_Shell ¤tShell = TopoDS::Shell(it.Current()); + const TopoDS_Shell& currentShell = TopoDS::Shell(it.Current()); ModelRefine::FaceUniter uniter(currentShell); if (uniter.process()) { if (uniter.isModified()) { - const TopoDS_Shell &newShell = uniter.getShell(); + const TopoDS_Shell& newShell = uniter.getShell(); mkSolid.Add(newShell); } else { @@ -3226,15 +3502,15 @@ TopoDS_Shape TopoShape::removeSplitter() const TopExp_Explorer xp; // solids for (xp.Init(_Shape, TopAbs_SOLID); xp.More(); xp.Next()) { - const TopoDS_Solid &solid = TopoDS::Solid(xp.Current()); + const TopoDS_Solid& solid = TopoDS::Solid(xp.Current()); BRepTools_ReShape reshape; TopExp_Explorer it; for (it.Init(solid, TopAbs_SHELL); it.More(); it.Next()) { - const TopoDS_Shell ¤tShell = TopoDS::Shell(it.Current()); + const TopoDS_Shell& currentShell = TopoDS::Shell(it.Current()); ModelRefine::FaceUniter uniter(currentShell); if (uniter.process()) { if (uniter.isModified()) { - const TopoDS_Shell &newShell = uniter.getShell(); + const TopoDS_Shell& newShell = uniter.getShell(); reshape.Replace(currentShell, newShell); } } @@ -3251,20 +3527,24 @@ TopoDS_Shape TopoShape::removeSplitter() const } // the rest for (xp.Init(_Shape, TopAbs_FACE, TopAbs_SHELL); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } for (xp.Init(_Shape, TopAbs_WIRE, TopAbs_FACE); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } for (xp.Init(_Shape, TopAbs_EDGE, TopAbs_WIRE); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } for (xp.Init(_Shape, TopAbs_VERTEX, TopAbs_EDGE); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } return TopoDS_Shape(std::move(comp)); @@ -3299,7 +3579,7 @@ void TopoShape::getDomains(std::vector& domains) const domain.points.reserve(points.size()); for (const auto& it : points) { Standard_Real X, Y, Z; - it.Coord (X, Y, Z); + it.Coord(X, Y, Z); domain.points.emplace_back(X, Y, Z); } @@ -3321,9 +3601,11 @@ void TopoShape::getDomains(std::vector& domains) const } } -void TopoShape::getFacesFromDomains(const std::vector& domains, - std::vector& points, - std::vector& faces) const +void TopoShape::getFacesFromDomains( + const std::vector& domains, + std::vector& points, + std::vector& faces +) const { BRepMesh mesh; mesh.getFacesFromDomains(domains, points, faces); @@ -3333,31 +3615,38 @@ double TopoShape::getAccuracy() const { double deviation = 0.2; Base::BoundBox3d bbox = getBoundBox(); - if (bbox.IsValid()) - return ((bbox.LengthX() + bbox.LengthY() + bbox.LengthZ())/300.0 * deviation); + if (bbox.IsValid()) { + return ((bbox.LengthX() + bbox.LengthY() + bbox.LengthZ()) / 300.0 * deviation); + } return ComplexGeoData::getAccuracy(); } -void TopoShape::getFaces(std::vector &aPoints, - std::vector &aTopo, - double accuracy, uint16_t /*flags*/) const +void TopoShape:: + getFaces(std::vector& aPoints, std::vector& aTopo, double accuracy, uint16_t /*flags*/) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { return; + } // get the meshes of all faces and then merge them - BRepMesh_IncrementalMesh aMesh(this->_Shape, accuracy, - /*isRelative*/ Standard_False, - /*theAngDeflection*/ - defaultAngularDeflection(accuracy), - /*isInParallel*/ true); + BRepMesh_IncrementalMesh aMesh( + this->_Shape, + accuracy, + /*isRelative*/ Standard_False, + /*theAngDeflection*/ + defaultAngularDeflection(accuracy), + /*isInParallel*/ true + ); std::vector domains; getDomains(domains); getFacesFromDomains(domains, aPoints, aTopo); } -void TopoShape::setFaces(const std::vector &Points, - const std::vector &Topo, double tolerance) +void TopoShape::setFaces( + const std::vector& Points, + const std::vector& Topo, + double tolerance +) { gp_XYZ p1, p2, p3; std::vector Vertexes; @@ -3382,16 +3671,19 @@ void TopoShape::setFaces(const std::vector &Points, }; for (const auto& it : Topo) { if (it.I1 < ctPoints) { - if (Vertexes[it.I1].IsNull()) + if (Vertexes[it.I1].IsNull()) { Vertexes[it.I1] = CreateVertex(Points[it.I1]); + } } if (it.I2 < ctPoints) { - if (Vertexes[it.I2].IsNull()) + if (Vertexes[it.I2].IsNull()) { Vertexes[it.I2] = CreateVertex(Points[it.I2]); + } } if (it.I3 < ctPoints) { - if (Vertexes[it.I3].IsNull()) + if (Vertexes[it.I3].IsNull()) { Vertexes[it.I3] = CreateVertex(Points[it.I3]); + } } } @@ -3409,8 +3701,9 @@ void TopoShape::setFaces(const std::vector &Points, } else { BRepBuilderAPI_MakeEdge mkEdge(Vertexes[p1], Vertexes[p2]); - if (mkEdge.IsDone()) + if (mkEdge.IsDone()) { Edges[key2] = mkEdge.Edge(); + } } }; auto GetEdge = [&Edges](uint32_t p1, uint32_t p2) { @@ -3424,30 +3717,40 @@ void TopoShape::setFaces(const std::vector &Points, } for (const auto& it : Topo) { - if (it.I1 >= ctPoints || it.I2 >= ctPoints || it.I3 >= ctPoints) + if (it.I1 >= ctPoints || it.I2 >= ctPoints || it.I3 >= ctPoints) { continue; - x1 = Points[it.I1].x; y1 = Points[it.I1].y; z1 = Points[it.I1].z; - x2 = Points[it.I2].x; y2 = Points[it.I2].y; z2 = Points[it.I2].z; - x3 = Points[it.I3].x; y3 = Points[it.I3].y; z3 = Points[it.I3].z; + } + x1 = Points[it.I1].x; + y1 = Points[it.I1].y; + z1 = Points[it.I1].z; + x2 = Points[it.I2].x; + y2 = Points[it.I2].y; + z2 = Points[it.I2].z; + x3 = Points[it.I3].x; + y3 = Points[it.I3].y; + z3 = Points[it.I3].z; - p1.SetCoord(x1,y1,z1); - p2.SetCoord(x2,y2,z2); - p3.SetCoord(x3,y3,z3); + p1.SetCoord(x1, y1, z1); + p2.SetCoord(x2, y2, z2); + p3.SetCoord(x3, y3, z3); - // Avoid very tiny edges as this may result into broken faces. The tolerance is Approximation - // because Confusion might be too tight. - if ((!(p1.IsEqual(p2, Precision::Approximation()))) && (!(p1.IsEqual(p3, Precision::Approximation())))) { + // Avoid very tiny edges as this may result into broken faces. The tolerance is + // Approximation because Confusion might be too tight. + if ((!(p1.IsEqual(p2, Precision::Approximation()))) + && (!(p1.IsEqual(p3, Precision::Approximation())))) { const TopoDS_Edge& e1 = GetEdge(it.I1, it.I2); const TopoDS_Edge& e2 = GetEdge(it.I2, it.I3); const TopoDS_Edge& e3 = GetEdge(it.I3, it.I1); - if (e1.IsNull() || e2.IsNull() || e3.IsNull()) + if (e1.IsNull() || e2.IsNull() || e3.IsNull()) { continue; + } newWire = BRepBuilderAPI_MakeWire(e1, e2, e3); if (!newWire.IsNull()) { newFace = BRepBuilderAPI_MakeFace(newWire); - if (!newFace.IsNull()) + if (!newFace.IsNull()) { BuildTool.Add(aComp, newFace); + } } } } @@ -3467,16 +3770,20 @@ void TopoShape::setFaces(const std::vector &Points, _Shape = aSewingTool.SewedShape(); - if (_Shape.IsNull()) + if (_Shape.IsNull()) { _Shape = aComp; + } } -void TopoShape::getLinesFromSubShape(const TopoDS_Shape& shape, - std::vector &vertices, - std::vector &lines) const +void TopoShape::getLinesFromSubShape( + const TopoDS_Shape& shape, + std::vector& vertices, + std::vector& lines +) const { - if (shape.IsNull()) + if (shape.IsNull()) { return; + } // build up map edge->face TopTools_IndexedDataMapOfShapeListOfShape edge2Face; @@ -3492,16 +3799,19 @@ void TopoShape::getLinesFromSubShape(const TopoDS_Shape& shape, // Look for one face in our map (it doesn't care which one we take) int index = edge2Face.FindIndex(aEdge); - if (index < 1) + if (index < 1) { continue; + } - const auto &faces = edge2Face.FindFromIndex(index); - if (faces.IsEmpty()) + const auto& faces = edge2Face.FindFromIndex(index); + if (faces.IsEmpty()) { continue; + } const TopoDS_Face& aFace = TopoDS::Face(faces.First()); - if (!Part::Tools::getPolygonOnTriangulation(aEdge, aFace, points)) + if (!Part::Tools::getPolygonOnTriangulation(aEdge, aFace, points)) { continue; + } } auto line_start = vertices.size(); @@ -3510,27 +3820,34 @@ void TopoShape::getLinesFromSubShape(const TopoDS_Shape& shape, vertices.push_back(Base::convertTo(p)); }); - if (line_start+1 < vertices.size()) { + if (line_start + 1 < vertices.size()) { lines.emplace_back(); lines.back().I1 = line_start; - lines.back().I2 = vertices.size()-1; + lines.back().I2 = vertices.size() - 1; } } } -void TopoShape::getLines(std::vector &vertices, - std::vector &lines, - double /*Accuracy*/, uint16_t /*flags*/) const +void TopoShape::getLines( + std::vector& vertices, + std::vector& lines, + double /*Accuracy*/, + uint16_t /*flags*/ +) const { getLinesFromSubShape(_Shape, vertices, lines); } -void TopoShape::getPoints(std::vector &Points, - std::vector &Normals, - double Accuracy, uint16_t /*flags*/) const +void TopoShape::getPoints( + std::vector& Points, + std::vector& Normals, + double Accuracy, + uint16_t /*flags*/ +) const { - if (_Shape.IsNull()) + if (_Shape.IsNull()) { return; + } const int minPointsPerEdge = 30; const double lateralDistance = Accuracy; @@ -3539,19 +3856,20 @@ void TopoShape::getPoints(std::vector &Points, for (TopExp_Explorer xp(_Shape, TopAbs_VERTEX, TopAbs_EDGE); xp.More(); xp.Next()) { gp_Pnt p = BRep_Tool::Pnt(TopoDS::Vertex(xp.Current())); Points.push_back(Base::convertTo(p)); - Normals.emplace_back(0,0,0); + Normals.emplace_back(0, 0, 0); } // sample inner points of all free edges for (TopExp_Explorer xp(_Shape, TopAbs_EDGE, TopAbs_FACE); xp.More(); xp.Next()) { BRepAdaptor_Curve curve(TopoDS::Edge(xp.Current())); - GCPnts_UniformAbscissa discretizer(curve, lateralDistance, curve.FirstParameter(), curve.LastParameter()); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + GCPnts_UniformAbscissa + discretizer(curve, lateralDistance, curve.FirstParameter(), curve.LastParameter()); + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { int nbPoints = discretizer.NbPoints(); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = curve.Value (discretizer.Parameter(i)); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = curve.Value(discretizer.Parameter(i)); Points.push_back(Base::convertTo(p)); - Normals.emplace_back(0,0,0); + Normals.emplace_back(0, 0, 0); } } } @@ -3569,35 +3887,35 @@ void TopoShape::getPoints(std::vector &Points, // parameter ranges Standard_Real uFirst = surface.FirstUParameter(); Standard_Real uLast = surface.LastUParameter(); - Standard_Real uMid = (uFirst+uLast)/2; + Standard_Real uMid = (uFirst + uLast) / 2; Standard_Real vFirst = surface.FirstVParameter(); Standard_Real vLast = surface.LastVParameter(); - Standard_Real vMid = (vFirst+vLast)/2; + Standard_Real vMid = (vFirst + vLast) / 2; // get geometrical length and width of the surface // gp_Pnt p1, p2; Standard_Real fLengthU = 0.0, fLengthV = 0.0; for (int i = 1; i <= pointsPerEdge; i++) { - double u1 = static_cast(i-1)/static_cast(pointsPerEdge); - double s1 = (1.0-u1)*uFirst + u1*uLast; - p1 = surface.Value(s1,vMid); + double u1 = static_cast(i - 1) / static_cast(pointsPerEdge); + double s1 = (1.0 - u1) * uFirst + u1 * uLast; + p1 = surface.Value(s1, vMid); - double u2 = static_cast(i)/static_cast(pointsPerEdge); - double s2 = (1.0-u2)*uFirst + u2*uLast; - p2 = surface.Value(s2,vMid); + double u2 = static_cast(i) / static_cast(pointsPerEdge); + double s2 = (1.0 - u2) * uFirst + u2 * uLast; + p2 = surface.Value(s2, vMid); fLengthU += p1.Distance(p2); } for (int i = 1; i <= pointsPerEdge; i++) { - double v1 = static_cast(i-1)/static_cast(pointsPerEdge); - double t1 = (1.0-v1)*vFirst + v1*vLast; - p1 = surface.Value(uMid,t1); + double v1 = static_cast(i - 1) / static_cast(pointsPerEdge); + double t1 = (1.0 - v1) * vFirst + v1 * vLast; + p1 = surface.Value(uMid, t1); - double v2 = static_cast(i)/static_cast(pointsPerEdge); - double t2 = (1.0-v2)*vFirst + v2*vLast; - p2 = surface.Value(uMid,t2); + double v2 = static_cast(i) / static_cast(pointsPerEdge); + double t2 = (1.0 - v2) * vFirst + v2 * vLast; + p2 = surface.Value(uMid, t2); fLengthV += p1.Distance(p2); } @@ -3608,26 +3926,27 @@ void TopoShape::getPoints(std::vector &Points, vPointsPerEdge = std::max(vPointsPerEdge, 1); for (int i = 0; i <= uPointsPerEdge; i++) { - double u = static_cast(i)/static_cast(uPointsPerEdge); - double s = (1.0-u)*uFirst + u*uLast; + double u = static_cast(i) / static_cast(uPointsPerEdge); + double s = (1.0 - u) * uFirst + u * uLast; for (int j = 0; j <= vPointsPerEdge; j++) { - double v = static_cast(j)/static_cast(vPointsPerEdge); - double t = (1.0-v)*vFirst + v*vLast; + double v = static_cast(j) / static_cast(vPointsPerEdge); + double t = (1.0 - v) * vFirst + v * vLast; - gp_Pnt2d p2d(s,t); - classifier.Perform(face,p2d,1.0e-4); + gp_Pnt2d p2d(s, t); + classifier.Perform(face, p2d, 1.0e-4); if (classifier.State() == TopAbs_IN || classifier.State() == TopAbs_ON) { - gp_Pnt p = surface.Value(s,t); + gp_Pnt p = surface.Value(s, t); Points.push_back(Base::convertTo(p)); gp_Dir normal; if (GeomLib::NormEstim(aSurf, p2d, Precision::Confusion(), normal) <= 1) { - if (face.Orientation() == TopAbs_REVERSED) + if (face.Orientation() == TopAbs_REVERSED) { normal.Reverse(); + } Normals.push_back(Base::convertTo(normal)); } else { - Normals.emplace_back(0,0,0); + Normals.emplace_back(0, 0, 0); } } } @@ -3635,51 +3954,60 @@ void TopoShape::getPoints(std::vector &Points, } // if no faces are found then the normals can be cleared - if (!hasFaces) + if (!hasFaces) { Normals.clear(); + } } -void TopoShape::getLinesFromSubElement(const Data::Segment* element, - std::vector &vertices, - std::vector &lines) const +void TopoShape::getLinesFromSubElement( + const Data::Segment* element, + std::vector& vertices, + std::vector& lines +) const { if (element->is()) { const TopoDS_Shape& shape = static_cast(element)->Shape; - if (shape.IsNull()) + if (shape.IsNull()) { return; + } getLinesFromSubShape(shape, vertices, lines); } } -void TopoShape::getFacesFromSubElement(const Data::Segment* element, - std::vector &points, - std::vector &pointNormals, - std::vector &faces) const +void TopoShape::getFacesFromSubElement( + const Data::Segment* element, + std::vector& points, + std::vector& pointNormals, + std::vector& faces +) const { if (element->is()) { const TopoDS_Shape& shape = static_cast(element)->Shape; - if (shape.IsNull() || shape.ShapeType() != TopAbs_FACE) + if (shape.IsNull() || shape.ShapeType() != TopAbs_FACE) { return; + } // get the meshes of all faces and then merge them std::vector domains; TopoShape(shape).getDomains(domains); getFacesFromDomains(domains, points, faces); - (void)pointNormals; // leave this empty + (void)pointNormals; // leave this empty } } TopoDS_Shape TopoShape::defeaturing(const std::vector& s) const { - if (this->_Shape.IsNull()) + if (this->_Shape.IsNull()) { Standard_Failure::Raise("Base shape is null"); + } BRepAlgoAPI_Defeaturing defeat; defeat.SetRunParallel(true); defeat.SetShape(this->_Shape); - for (const auto & it : s) + for (const auto& it : s) { defeat.AddFaceToRemove(it); + } #if OCC_VERSION_HEX >= 0x070600 defeat.Build(OCCTProgressIndicator::getAppIndicator().Start()); #else @@ -3708,32 +4036,38 @@ TopoDS_Shape TopoShape::makeShell(const TopoDS_Shape& input) const { // For comparison see also: // GEOMImpl_BooleanDriver::makeCompoundShellFromFaces - if (input.IsNull()) + if (input.IsNull()) { return input; - if (input.ShapeType() != TopAbs_COMPOUND) + } + if (input.ShapeType() != TopAbs_COMPOUND) { return input; + } // we need a compound that consists of only faces TopExp_Explorer it; // no shells it.Init(input, TopAbs_SHELL); - if (it.More()) + if (it.More()) { return input; + } // no wires outside a face it.Init(input, TopAbs_WIRE, TopAbs_FACE); - if (it.More()) + if (it.More()) { return input; + } // no edges outside a wire it.Init(input, TopAbs_EDGE, TopAbs_WIRE); - if (it.More()) + if (it.More()) { return input; + } // no vertexes outside an edge it.Init(input, TopAbs_VERTEX, TopAbs_EDGE); - if (it.More()) + if (it.More()) { return input; + } BRep_Builder builder; TopoDS_Shape shape; @@ -3742,8 +4076,9 @@ TopoDS_Shape TopoShape::makeShell(const TopoDS_Shape& input) const try { for (it.Init(input, TopAbs_FACE); it.More(); it.Next()) { - if (!it.Current().IsNull()) + if (!it.Current().IsNull()) { builder.Add(shell, it.Current()); + } } shape = shell; @@ -3753,38 +4088,44 @@ TopoDS_Shape TopoShape::makeShell(const TopoDS_Shape& input) const shape = sewShell.ApplySewing(shell); } - if (shape.IsNull()) + if (shape.IsNull()) { return input; + } - if (shape.ShapeType() != TopAbs_SHELL) + if (shape.ShapeType() != TopAbs_SHELL) { return input; + } - return shape; // success + return shape; // success } catch (Standard_Failure&) { return input; } } -#define _HANDLE_NULL_SHAPE(_msg,_throw) do {\ - if(_throw) {\ - FC_THROWM(NullShapeException,_msg);\ - }\ - FC_WARN(_msg);\ -}while(0) +#define _HANDLE_NULL_SHAPE(_msg, _throw) \ + do { \ + if (_throw) { \ + FC_THROWM(NullShapeException, _msg); \ + } \ + FC_WARN(_msg); \ + } while (0) -#define HANDLE_NULL_SHAPE _HANDLE_NULL_SHAPE("Null shape",true) -#define HANDLE_NULL_INPUT _HANDLE_NULL_SHAPE("Null input shape",true) -#define WARN_NULL_INPUT _HANDLE_NULL_SHAPE("Null input shape",false) +#define HANDLE_NULL_SHAPE _HANDLE_NULL_SHAPE("Null shape", true) +#define HANDLE_NULL_INPUT _HANDLE_NULL_SHAPE("Null input shape", true) +#define WARN_NULL_INPUT _HANDLE_NULL_SHAPE("Null input shape", false) -TopoShape &TopoShape::makeWires(const TopoShape &shape, const char *op, bool fix, double tol) +TopoShape& TopoShape::makeWires(const TopoShape& shape, const char* op, bool fix, double tol) { _Shape.Nullify(); - if(shape.isNull()) + if (shape.isNull()) { HANDLE_NULL_INPUT; + } - if(tolgetShape())); if (mkWire.Error() != BRepBuilderAPI_DisconnectedWire) { // edge added ==> remove it from list @@ -3845,18 +4187,19 @@ TopoShape &TopoShape::makeWires(const TopoShape &shape, const char *op, bool fix // Now retrieve the shape and set it without touching element map wires.back().setShape(aFix.Wire()); } - return makeCompound(wires,nullptr,false); + return makeCompound(wires, nullptr, false); } -TopoShape &TopoShape::makeCompound(const std::vector &shapes, const char *op, bool force) +TopoShape& TopoShape::makeCompound(const std::vector& shapes, const char* op, bool force) { (void)op; _Shape.Nullify(); - if(shapes.empty()) + if (shapes.empty()) { HANDLE_NULL_INPUT; + } - if(!force && shapes.size()==1) { + if (!force && shapes.size() == 1) { *this = shapes[0]; return *this; } @@ -3865,45 +4208,52 @@ TopoShape &TopoShape::makeCompound(const std::vector &shapes, const c TopoDS_Compound comp; builder.MakeCompound(comp); int count = 0; - for(auto &s : shapes) { - if(s.isNull()) { + for (auto& s : shapes) { + if (s.isNull()) { WARN_NULL_INPUT; continue; } - builder.Add(comp,s.getShape()); + builder.Add(comp, s.getShape()); ++count; } - if(!count) + if (!count) { HANDLE_NULL_SHAPE; + } _Shape = comp; return *this; } -TopoShape &TopoShape::makeFace(const TopoShape &shape, const char *op, const char *maker) +TopoShape& TopoShape::makeFace(const TopoShape& shape, const char* op, const char* maker) { std::vector shapes; - if(shape.shapeType() == TopAbs_COMPOUND) { - for(TopoDS_Iterator it(shape.getShape());it.More();it.Next()) + if (shape.shapeType() == TopAbs_COMPOUND) { + for (TopoDS_Iterator it(shape.getShape()); it.More(); it.Next()) { shapes.emplace_back(it.Value()); - } else + } + } + else { shapes.push_back(shape); - return makeFace(shapes,op,maker); + } + return makeFace(shapes, op, maker); } -TopoShape &TopoShape::makeFace(const std::vector &shapes, const char *op, const char *maker) +TopoShape& TopoShape::makeFace(const std::vector& shapes, const char* op, const char* maker) { (void)op; _Shape.Nullify(); - if(!maker || !maker[0]) + if (!maker || !maker[0]) { maker = "Part::FaceMakerBullseye"; + } std::unique_ptr mkFace = FaceMaker::ConstructFromType(maker); - for(auto &s : shapes) { - if (s.getShape().ShapeType() == TopAbs_COMPOUND) + for (auto& s : shapes) { + if (s.getShape().ShapeType() == TopAbs_COMPOUND) { mkFace->useCompound(TopoDS::Compound(s.getShape())); - else if (s.getShape().ShapeType() != TopAbs_VERTEX) + } + else if (s.getShape().ShapeType() != TopAbs_VERTEX) { mkFace->addShape(s.getShape()); + } } #if OCC_VERSION_HEX >= 0x070600 mkFace->Build(OCCTProgressIndicator::getAppIndicator().Start()); @@ -3914,12 +4264,12 @@ TopoShape &TopoShape::makeFace(const std::vector &shapes, const char return *this; } -TopoShape &TopoShape::makeRefine(const TopoShape &shape, const char *op, RefineFail no_fail) +TopoShape& TopoShape::makeRefine(const TopoShape& shape, const char* op, RefineFail no_fail) { (void)op; _Shape.Nullify(); - if(shape.isNull()) { + if (shape.isNull()) { if (no_fail == RefineFail::throwException) { HANDLE_NULL_SHAPE; } @@ -3929,8 +4279,9 @@ TopoShape &TopoShape::makeRefine(const TopoShape &shape, const char *op, RefineF BRepBuilderAPI_RefineModel mkRefine(shape.getShape()); _Shape = mkRefine.Shape(); return *this; - }catch (Standard_Failure &) { - if(no_fail == RefineFail::throwException ) { + } + catch (Standard_Failure&) { + if (no_fail == RefineFail::throwException) { throw; } } @@ -4009,10 +4360,14 @@ bool TopoShape::findPlane(gp_Pln& pln, double tol, double atol) const TopoDS_Compound comp; builder.MakeCompound(comp); for (int i = 0, c = (int)vertexes.size() - 1; i < c; ++i) { - builder.Add(comp, - BRepBuilderAPI_MakeEdge(TopoDS::Vertex(vertexes[i]), - TopoDS::Vertex(vertexes[i + 1])) - .Edge()); + builder.Add( + comp, + BRepBuilderAPI_MakeEdge( + TopoDS::Vertex(vertexes[i]), + TopoDS::Vertex(vertexes[i + 1]) + ) + .Edge() + ); } BRepLib_FindSurface finder(comp, tol, Standard_True); if (!finder.Found()) { @@ -4035,10 +4390,10 @@ bool TopoShape::findPlane(gp_Pln& pln, double tol, double atol) const if (hasSubShape(TopAbs_FACE)) { shape = getSubShape(TopAbs_FACE, 1); BRepAdaptor_Surface adapt(TopoDS::Face(shape)); - double u = - adapt.FirstUParameter() + (adapt.LastUParameter() - adapt.FirstUParameter()) / 2.; - double v = - adapt.FirstVParameter() + (adapt.LastVParameter() - adapt.FirstVParameter()) / 2.; + double u = adapt.FirstUParameter() + + (adapt.LastUParameter() - adapt.FirstUParameter()) / 2.; + double v = adapt.FirstVParameter() + + (adapt.LastVParameter() - adapt.FirstVParameter()) / 2.; BRepLProp_SLProps prop(adapt, u, v, 2, Precision::Confusion()); if (prop.IsNormalDefined()) { gp_Pnt pnt; @@ -4062,8 +4417,9 @@ bool TopoShape::findPlane(gp_Pln& pln, double tol, double atol) const bool TopoShape::isInfinite() const { - if (_Shape.IsNull()) + if (_Shape.IsNull()) { return false; + } try { // If the shape is empty an exception may be thrown @@ -4073,12 +4429,15 @@ bool TopoShape::isInfinite() const Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); - if (Precision::IsInfinite(xMax - xMin)) + if (Precision::IsInfinite(xMax - xMin)) { return true; - if (Precision::IsInfinite(yMax - yMin)) + } + if (Precision::IsInfinite(yMax - yMin)) { return true; - if (Precision::IsInfinite(zMax - zMin)) + } + if (Precision::IsInfinite(zMax - zMin)) { return true; + } return false; } @@ -4108,28 +4467,38 @@ bool TopoShape::isPlanar(double tol) const return check.IsPlanar(); } -bool TopoShape::isCoplanar(const TopoShape &other, double tol) const { - if(isNull() || other.isNull()) +bool TopoShape::isCoplanar(const TopoShape& other, double tol) const +{ + if (isNull() || other.isNull()) { return false; - if(_Shape.IsEqual(other._Shape)) + } + if (_Shape.IsEqual(other._Shape)) { return true; - gp_Pln pln1,pln2; - if(!findPlane(pln1,tol) || !other.findPlane(pln2,tol)) + } + gp_Pln pln1, pln2; + if (!findPlane(pln1, tol) || !other.findPlane(pln2, tol)) { return false; - if(tol<0.0) + } + if (tol < 0.0) { tol = Precision::Confusion(); - return pln1.Position().IsCoplanar(pln2.Position(),tol,tol); + } + return pln1.Position().IsCoplanar(pln2.Position(), tol, tol); } -bool TopoShape::_makeTransform(const TopoShape &shape, - const Base::Matrix4D &rclTrf, const char *op, bool checkScale, bool copy) +bool TopoShape::_makeTransform( + const TopoShape& shape, + const Base::Matrix4D& rclTrf, + const char* op, + bool checkScale, + bool copy +) { - if(checkScale) { + if (checkScale) { try { auto type = rclTrf.hasScale(); if ((type != Base::ScaleType::Uniform && type != Base::ScaleType::NoScaling) || (type == Base::ScaleType::Uniform && rclTrf.determinant3() == 0.0)) { - makeGTransform(shape,rclTrf,op,copy); + makeGTransform(shape, rclTrf, op, copy); return true; } } @@ -4137,20 +4506,21 @@ bool TopoShape::_makeTransform(const TopoShape &shape, Base::Console().warning("TopoShape::makeGTransform failed: %s\n", e.GetMessageString()); } } - makeTransform(shape,convert(rclTrf),op,copy); + makeTransform(shape, convert(rclTrf), op, copy); return false; } -TopoShape &TopoShape::makeTransform(const TopoShape &shape, const gp_Trsf &trsf, const char *op, bool copy) { +TopoShape& TopoShape::makeTransform(const TopoShape& shape, const gp_Trsf& trsf, const char* op, bool copy) +{ // resetElementMap(); - if(!copy) { + if (!copy) { // OCCT checks the ScaleFactor against gp::Resolution() which is DBL_MIN!!! - copy = trsf.ScaleFactor()*trsf.HVectorialPart().Determinant() < 0. || - Abs(Abs(trsf.ScaleFactor()) - 1) > Precision::Confusion(); + copy = trsf.ScaleFactor() * trsf.HVectorialPart().Determinant() < 0. + || Abs(Abs(trsf.ScaleFactor()) - 1) > Precision::Confusion(); } TopoShape tmp(shape); - if(copy) { + if (copy) { BRepBuilderAPI_Transform mkTrf(shape.getShape(), trsf, Standard_True); // TODO: calling Moved() is to make sure the shape has some Location, // which is necessary for STEP export to work. However, if we reach @@ -4159,18 +4529,27 @@ TopoShape &TopoShape::makeTransform(const TopoShape &shape, const gp_Trsf &trsf, // parent relationship anyway. In short, STEP import/export will most // likely break badly if there is any scaling involved tmp._Shape = mkTrf.Shape().Moved(gp_Trsf()); - }else + } + else { tmp._Shape.Move(trsf); - if(op || (shape.Tag && shape.Tag!=Tag)) { + } + if (op || (shape.Tag && shape.Tag != Tag)) { _Shape = tmp._Shape; // tmp.initCache(1); // mapSubElement(tmp,op); - } else + } + else { *this = tmp; + } return *this; } -TopoShape &TopoShape::makeGTransform(const TopoShape &shape, const Base::Matrix4D &rclTrf, const char *op, bool copy) +TopoShape& TopoShape::makeGTransform( + const TopoShape& shape, + const Base::Matrix4D& rclTrf, + const char* op, + bool copy +) { boost::ignore_unused(op); _Shape = shape.transformGShape(rclTrf, copy); diff --git a/src/Mod/Part/App/TopoShape.h b/src/Mod/Part/App/TopoShape.h index 3ae80af4a7..3f716f4640 100644 --- a/src/Mod/Part/App/TopoShape.h +++ b/src/Mod/Part/App/TopoShape.h @@ -116,8 +116,8 @@ enum class HistoryTraceType followTypeChange }; -/// Behavior of refines when a problem arises; either leave the shape untouched or throw an exception. -/// This replaces a boolean parameter in the original Toponaming branch by realthunder.. +/// Behavior of refines when a problem arises; either leave the shape untouched or throw an +/// exception. This replaces a boolean parameter in the original Toponaming branch by realthunder.. enum class RefineFail { shapeUntouched, @@ -266,7 +266,8 @@ enum class OpenResult }; // See BRepFeat_MakeRevol -enum class RevolMode { +enum class RevolMode +{ CutFromBase = 0, FuseWithBase = 1, None = 2 @@ -281,12 +282,16 @@ class PartExport TopoShape: public Data::ComplexGeoData TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - TopoShape(long Tag=0, // NOLINT google-explicit-constructor - App::StringHasherRef hasher=App::StringHasherRef(), - const TopoDS_Shape &shape=TopoDS_Shape()); // Cannot be made explicit - TopoShape(const TopoDS_Shape&, // NOLINT google-explicit-constructor - long Tag=0, - App::StringHasherRef hasher=App::StringHasherRef()); // Cannot be made explicit + TopoShape( + long Tag = 0, // NOLINT google-explicit-constructor + App::StringHasherRef hasher = App::StringHasherRef(), + const TopoDS_Shape& shape = TopoDS_Shape() + ); // Cannot be made explicit + TopoShape( + const TopoDS_Shape&, // NOLINT google-explicit-constructor + long Tag = 0, + App::StringHasherRef hasher = App::StringHasherRef() + ); // Cannot be made explicit TopoShape(const TopoShape&); ~TopoShape() override; @@ -304,11 +309,12 @@ public: void operator=(const TopoShape&); - bool operator == (const TopoShape &other) const { + bool operator==(const TopoShape& other) const + { return _Shape.IsEqual(other._Shape); } - virtual bool isSame (const Data::ComplexGeoData &other) const; + virtual bool isSame(const Data::ComplexGeoData& other) const; /** @name Placement control */ //@{ @@ -331,40 +337,55 @@ public: //@{ private: /** Get lines from sub-shape */ - void getLinesFromSubShape(const TopoDS_Shape& shape, - std::vector& vertices, - std::vector& lines) const; - void getFacesFromDomains(const std::vector& domains, - std::vector& vertices, - std::vector& faces) const; + void getLinesFromSubShape( + const TopoDS_Shape& shape, + std::vector& vertices, + std::vector& lines + ) const; + void getFacesFromDomains( + const std::vector& domains, + std::vector& vertices, + std::vector& faces + ) const; public: /// Get the standard accuracy to be used with getPoints, getLines or getFaces double getAccuracy() const override; /** Get points from object with given accuracy */ - void getPoints(std::vector& Points, - std::vector& Normals, - double Accuracy, - uint16_t flags = 0) const override; + void getPoints( + std::vector& Points, + std::vector& Normals, + double Accuracy, + uint16_t flags = 0 + ) const override; /** Get lines from object with given accuracy */ - void getLines(std::vector& Points, - std::vector& lines, - double Accuracy, - uint16_t flags = 0) const override; - void getFaces(std::vector& Points, - std::vector& faces, - double Accuracy, - uint16_t flags = 0) const override; - void setFaces(const std::vector& Points, - const std::vector& faces, - double tolerance = 1.0e-06); // NOLINT + void getLines( + std::vector& Points, + std::vector& lines, + double Accuracy, + uint16_t flags = 0 + ) const override; + void getFaces( + std::vector& Points, + std::vector& faces, + double Accuracy, + uint16_t flags = 0 + ) const override; + void setFaces( + const std::vector& Points, + const std::vector& faces, + double tolerance = 1.0e-06 + ); // NOLINT void getDomains(std::vector&) const; //@} /** @name Subelement management */ //@{ /// Search to see if a SubShape matches - static Data::MappedElement chooseMatchingSubShapeByPlaneOrLine(const TopoShape& shapeToFind, const TopoShape& shapeToLookIn); + static Data::MappedElement chooseMatchingSubShapeByPlaneOrLine( + const TopoShape& shapeToFind, + const TopoShape& shapeToLookIn + ); /// Unlike \ref getTypeAndIndex() this function only handles the supported /// element types. static std::pair getElementTypeAndIndex(const char* Name); @@ -377,14 +398,18 @@ public: /// get the subelement by type and number Data::Segment* getSubElement(const char* Type, unsigned long index) const override; /** Get lines from segment */ - void getLinesFromSubElement(const Data::Segment* segment, - std::vector& Points, - std::vector& lines) const override; + void getLinesFromSubElement( + const Data::Segment* segment, + std::vector& Points, + std::vector& lines + ) const override; /** Get faces from segment */ - void getFacesFromSubElement(const Data::Segment* segment, - std::vector& Points, - std::vector& PointNormals, - std::vector& faces) const override; + void getFacesFromSubElement( + const Data::Segment* segment, + std::vector& Points, + std::vector& PointNormals, + std::vector& faces + ) const override; //@} /** * Locate the TopoDS_Shape associated with a Topo"sub"Shape of the given name @@ -426,26 +451,32 @@ public: * @param avoid The type to avoid * @return The sub TopoShapes. */ - std::vector getSubTopoShapes(TopAbs_ShapeEnum type=TopAbs_SHAPE, TopAbs_ShapeEnum avoid=TopAbs_SHAPE) const; + std::vector getSubTopoShapes( + TopAbs_ShapeEnum type = TopAbs_SHAPE, + TopAbs_ShapeEnum avoid = TopAbs_SHAPE + ) const; /** * Locate all of the sub TopoDS_Shapes of a given type, while avoiding a given type * @param type The type to find * @param avoid The type to avoid * @return The sub TopoDS_Shapes. */ - std::vector getSubShapes(TopAbs_ShapeEnum type=TopAbs_SHAPE, TopAbs_ShapeEnum avoid=TopAbs_SHAPE) const; + std::vector getSubShapes( + TopAbs_ShapeEnum type = TopAbs_SHAPE, + TopAbs_ShapeEnum avoid = TopAbs_SHAPE + ) const; /** * Locate all the Edges in the Wires of this shape * @param mapElement If True, map the subelements ( Edges ) found * @return Vector of the edges */ - std::vector getOrderedEdges(MapElement mapElement=MapElement::map) const; + std::vector getOrderedEdges(MapElement mapElement = MapElement::map) const; /** * Locate all the Vertexes in the Wires of this shape * @param mapElement If True, map the subelements ( Vertexes ) found * @return Vector of the Vertexes */ - std::vector getOrderedVertexes(MapElement mapElement=MapElement::map) const; + std::vector getOrderedVertexes(MapElement mapElement = MapElement::map) const; unsigned long countSubShapes(const char* Type) const; unsigned long countSubShapes(TopAbs_ShapeEnum type) const; bool hasSubShape(const char* Type) const; @@ -497,11 +528,11 @@ public: /// Returns true if the expansion of the shape is infinite, false otherwise bool isInfinite() const; /// Checks whether the shape is a planar face - bool isPlanar(double tol = 1.0e-7) const; // NOLINT + bool isPlanar(double tol = 1.0e-7) const; // NOLINT /// Check if this shape is a single linear edge, works on BSplineCurve and BezierCurve bool isLinearEdge() const; /// Check if this shape is a single planar face, works on BSplineSurface and BezierSurface - bool isPlanarFace(double tol=1e-7) const; // NOLINT + bool isPlanarFace(double tol = 1e-7) const; // NOLINT //@} /** @name Boolean operation*/ @@ -513,9 +544,11 @@ public: TopoDS_Shape fuse(TopoDS_Shape) const; TopoDS_Shape fuse(const std::vector&, Standard_Real tolerance = -1.0) const; TopoDS_Shape section(TopoDS_Shape, Standard_Boolean approximate = Standard_False) const; - TopoDS_Shape section(const std::vector&, - Standard_Real tolerance = -1.0, - Standard_Boolean approximate = Standard_False) const; + TopoDS_Shape section( + const std::vector&, + Standard_Real tolerance = -1.0, + Standard_Boolean approximate = Standard_False + ) const; std::list slice(const Base::Vector3d&, double) const; TopoDS_Compound slices(const Base::Vector3d&, const std::vector&) const; /** @@ -539,75 +572,97 @@ public: * For example, if input shapes are two intersecting spheres, GFA returns * three solids: two cuts and common. */ - TopoDS_Shape generalFuse(const std::vector& sOthers, - Standard_Real tolerance, - std::vector* mapInOut = nullptr) const; + TopoDS_Shape generalFuse( + const std::vector& sOthers, + Standard_Real tolerance, + std::vector* mapInOut = nullptr + ) const; //@} /** Sweeping */ //@{ TopoDS_Shape makePipe(const TopoDS_Shape& profile) const; - TopoDS_Shape makePipeShell(const TopTools_ListOfShape& profiles, - const Standard_Boolean make_solid, - const Standard_Boolean isFrenet = Standard_False, - int transition = 0) const; + TopoDS_Shape makePipeShell( + const TopTools_ListOfShape& profiles, + const Standard_Boolean make_solid, + const Standard_Boolean isFrenet = Standard_False, + int transition = 0 + ) const; TopoDS_Shape makePrism(const gp_Vec&) const; /// revolve shape. Note: isSolid is deprecated (instead, use some Part::FaceMaker to make a /// face, first). TopoDS_Shape revolve(const gp_Ax1&, double d, Standard_Boolean isSolid = Standard_False) const; TopoDS_Shape makeSweep(const TopoDS_Shape& profile, double, int) const; TopoDS_Shape makeTube(double radius, double tol, int cont, int maxdeg, int maxsegm) const; - TopoDS_Shape makeTorus(Standard_Real radius1, - Standard_Real radius2, - Standard_Real angle1, - Standard_Real angle2, - Standard_Real angle3, - Standard_Boolean isSolid = Standard_True) const; - TopoDS_Shape makeHelix(Standard_Real pitch, - Standard_Real height, - Standard_Real radius, - Standard_Real angle = 0, - Standard_Boolean left = Standard_False, - Standard_Boolean style = Standard_False) const; - TopoDS_Shape makeLongHelix(Standard_Real pitch, - Standard_Real height, - Standard_Real radius, - Standard_Real angle = 0, - Standard_Boolean left = Standard_False) const; - TopoDS_Shape makeSpiralHelix(Standard_Real radiusbottom, - Standard_Real radiustop, - Standard_Real height, - Standard_Real nbturns = 1, - Standard_Real breakperiod = 1, - Standard_Boolean left = Standard_False) const; - TopoDS_Shape makeThread(Standard_Real pitch, - Standard_Real depth, - Standard_Real height, - Standard_Real radius) const; - TopoDS_Shape makeLoft(const TopTools_ListOfShape& profiles, - Standard_Boolean isSolid, - Standard_Boolean isRuled, - Standard_Boolean isClosed = Standard_False, - Standard_Integer maxDegree = 5) const; - TopoDS_Shape makeOffsetShape(double offset, - double tol, - bool intersection = false, - bool selfInter = false, - short offsetMode = 0, - short join = 0, - bool fill = false) const; - TopoDS_Shape makeOffset2D(double offset, - short joinType = 0, - bool fill = false, - bool allowOpenResult = false, - bool intersection = false) const; - TopoDS_Shape makeThickSolid(const TopTools_ListOfShape& remFace, - double offset, - double tol, - bool intersection = false, - bool selfInter = false, - short offsetMode = 0, - short join = 0) const; + TopoDS_Shape makeTorus( + Standard_Real radius1, + Standard_Real radius2, + Standard_Real angle1, + Standard_Real angle2, + Standard_Real angle3, + Standard_Boolean isSolid = Standard_True + ) const; + TopoDS_Shape makeHelix( + Standard_Real pitch, + Standard_Real height, + Standard_Real radius, + Standard_Real angle = 0, + Standard_Boolean left = Standard_False, + Standard_Boolean style = Standard_False + ) const; + TopoDS_Shape makeLongHelix( + Standard_Real pitch, + Standard_Real height, + Standard_Real radius, + Standard_Real angle = 0, + Standard_Boolean left = Standard_False + ) const; + TopoDS_Shape makeSpiralHelix( + Standard_Real radiusbottom, + Standard_Real radiustop, + Standard_Real height, + Standard_Real nbturns = 1, + Standard_Real breakperiod = 1, + Standard_Boolean left = Standard_False + ) const; + TopoDS_Shape makeThread( + Standard_Real pitch, + Standard_Real depth, + Standard_Real height, + Standard_Real radius + ) const; + TopoDS_Shape makeLoft( + const TopTools_ListOfShape& profiles, + Standard_Boolean isSolid, + Standard_Boolean isRuled, + Standard_Boolean isClosed = Standard_False, + Standard_Integer maxDegree = 5 + ) const; + TopoDS_Shape makeOffsetShape( + double offset, + double tol, + bool intersection = false, + bool selfInter = false, + short offsetMode = 0, + short join = 0, + bool fill = false + ) const; + TopoDS_Shape makeOffset2D( + double offset, + short joinType = 0, + bool fill = false, + bool allowOpenResult = false, + bool intersection = false + ) const; + TopoDS_Shape makeThickSolid( + const TopTools_ListOfShape& remFace, + double offset, + double tol, + bool intersection = false, + bool selfInter = false, + short offsetMode = 0, + short join = 0 + ) const; //@} /** @name Manipulation*/ @@ -628,9 +683,10 @@ public: TopoDS_Shape defeaturing(const std::vector& s) const; TopoDS_Shape makeShell(const TopoDS_Shape&) const; //@} - + /// Wire re-orientation when calling splitWires() - enum SplitWireReorient { + enum SplitWireReorient + { /// Keep original reorientation NoReorient, /// Make outer wire forward, and inner wires reversed @@ -647,59 +703,77 @@ public: * * @return Return the outer wire */ - TopoShape splitWires(std::vector *inner = nullptr, - SplitWireReorient reorient = Reorient) const; + TopoShape splitWires( + std::vector* inner = nullptr, + SplitWireReorient reorient = Reorient + ) const; /** @name Element name mapping aware shape maker * * To be complete in next batch of patches */ //@{ - TopoShape& - makeCompound(const std::vector& shapes, const char* op = nullptr, bool force = true); + TopoShape& makeCompound( + const std::vector& shapes, + const char* op = nullptr, + bool force = true + ); - TopoShape& - makeWires(const TopoShape& shape, const char* op = nullptr, bool fix = false, double tol = 0.0); + TopoShape& makeWires( + const TopoShape& shape, + const char* op = nullptr, + bool fix = false, + double tol = 0.0 + ); TopoShape makeWires(const char* op = nullptr, bool fix = false, double tol = 0.0) const { return TopoShape().makeWires(*this, op, fix, tol); } - TopoShape& makeFace(const std::vector& shapes, - const char* op = nullptr, - const char* maker = nullptr); - TopoShape& - makeFace(const TopoShape& shape, const char* op = nullptr, const char* maker = nullptr); + TopoShape& makeFace( + const std::vector& shapes, + const char* op = nullptr, + const char* maker = nullptr + ); + TopoShape& makeFace(const TopoShape& shape, const char* op = nullptr, const char* maker = nullptr); TopoShape makeFace(const char* op = nullptr, const char* maker = nullptr) const { return TopoShape().makeFace(*this, op, maker); } - bool _makeTransform(const TopoShape& shape, - const Base::Matrix4D& mat, - const char* op = nullptr, - bool checkScale = false, - bool copy = false); + bool _makeTransform( + const TopoShape& shape, + const Base::Matrix4D& mat, + const char* op = nullptr, + bool checkScale = false, + bool copy = false + ); - TopoShape& makeTransform(const TopoShape& shape, - const Base::Matrix4D& mat, - const char* op = nullptr, - bool checkScale = false, - bool copy = false) + TopoShape& makeTransform( + const TopoShape& shape, + const Base::Matrix4D& mat, + const char* op = nullptr, + bool checkScale = false, + bool copy = false + ) { _makeTransform(shape, mat, op, checkScale, copy); return *this; } - TopoShape makeTransform(const Base::Matrix4D& mat, - const char* op = nullptr, - bool checkScale = false, - bool copy = false) const + TopoShape makeTransform( + const Base::Matrix4D& mat, + const char* op = nullptr, + bool checkScale = false, + bool copy = false + ) const { return TopoShape().makeTransform(*this, mat, op, checkScale, copy); } - TopoShape& makeTransform(const TopoShape& shape, - const gp_Trsf& trsf, - const char* op = nullptr, - bool copy = false); + TopoShape& makeTransform( + const TopoShape& shape, + const gp_Trsf& trsf, + const char* op = nullptr, + bool copy = false + ); TopoShape makeTransform(const gp_Trsf& trsf, const char* op = nullptr, bool copy = false) const { return TopoShape().makeTransform(*this, trsf, op, copy); @@ -809,16 +883,17 @@ public: static TopoDS_Shape& locate(TopoDS_Shape& tds, const gp_Trsf& transfer); static TopoDS_Shape located(const TopoDS_Shape& tds, const gp_Trsf& transfer); - TopoShape& makeGTransform(const TopoShape& shape, - const Base::Matrix4D& mat, - const char* op = nullptr, - bool copy = false); - TopoShape - makeGTransform(const Base::Matrix4D& mat, const char* op = nullptr, bool copy = false) const + TopoShape& makeGTransform( + const TopoShape& shape, + const Base::Matrix4D& mat, + const char* op = nullptr, + bool copy = false + ); + TopoShape makeGTransform(const Base::Matrix4D& mat, const char* op = nullptr, bool copy = false) const { return TopoShape().makeGTransform(*this, mat, op, copy); } - + /** Refine the input shape by merging faces/edges that share the same geometry * * @param shape: input shape @@ -832,9 +907,11 @@ public: * itself as a self reference so that multiple operations can be * carried out for the same shape in the same line of code. */ - TopoShape& makeElementRefine(const TopoShape& shape, - const char* op = nullptr, - RefineFail no_fail = RefineFail::throwException); + TopoShape& makeElementRefine( + const TopoShape& shape, + const char* op = nullptr, + RefineFail no_fail = RefineFail::throwException + ); /** Refine the input shape by merging faces/edges that share the same geometry * @@ -846,19 +923,22 @@ public: * * @return Return a refined shape. The shape itself is not modified */ - TopoShape makeElementRefine(const char* op = nullptr, - RefineFail no_fail = RefineFail::throwException) const + TopoShape makeElementRefine( + const char* op = nullptr, + RefineFail no_fail = RefineFail::throwException + ) const { return TopoShape(Tag, Hasher).makeElementRefine(*this, op, no_fail); } - TopoShape& makeRefine(const TopoShape& shape, - const char* op = nullptr, - RefineFail no_fail = RefineFail::throwException); + TopoShape& makeRefine( + const TopoShape& shape, + const char* op = nullptr, + RefineFail no_fail = RefineFail::throwException + ); - TopoShape makeRefine(const char* op = nullptr, - RefineFail no_fail = RefineFail::throwException) const + TopoShape makeRefine(const char* op = nullptr, RefineFail no_fail = RefineFail::throwException) const { return TopoShape().makeRefine(*this, op, no_fail); } @@ -882,9 +962,17 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape &makeElementThickSolid(const TopoShape &shape, const std::vector &faces, - double offset, double tol, bool intersection = false, bool selfInter = false, - short offsetMode = 0, JoinType join = JoinType::arc, const char *op=nullptr); + TopoShape& makeElementThickSolid( + const TopoShape& shape, + const std::vector& faces, + double offset, + double tol, + bool intersection = false, + bool selfInter = false, + short offsetMode = 0, + JoinType join = JoinType::arc, + const char* op = nullptr + ); /** Make a hollowed solid by removing some faces from a given solid * @@ -903,11 +991,28 @@ public: * * @return Return the generated new shape. The TopoShape itself is not modified. */ - TopoShape makeElementThickSolid(const std::vector &faces, - double offset, double tol, bool intersection = false, bool selfInter = false, - short offsetMode = 0, JoinType join = JoinType::arc, const char *op=nullptr) const { - return TopoShape(0,Hasher).makeElementThickSolid(*this,faces,offset,tol,intersection,selfInter, - offsetMode,join,op); + TopoShape makeElementThickSolid( + const std::vector& faces, + double offset, + double tol, + bool intersection = false, + bool selfInter = false, + short offsetMode = 0, + JoinType join = JoinType::arc, + const char* op = nullptr + ) const + { + return TopoShape(0, Hasher).makeElementThickSolid( + *this, + faces, + offset, + tol, + intersection, + selfInter, + offsetMode, + join, + op + ); } /** Make a 3D offset of a given shape * @@ -930,15 +1035,17 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementOffset(const TopoShape& source, - double offset, - double tol, - bool intersection = false, - bool selfInter = false, - short offsetMode = 0, - JoinType join = JoinType::arc, - FillType fill = FillType::noFill, - const char* op = nullptr); + TopoShape& makeElementOffset( + const TopoShape& source, + double offset, + double tol, + bool intersection = false, + bool selfInter = false, + short offsetMode = 0, + JoinType join = JoinType::arc, + FillType fill = FillType::noFill, + const char* op = nullptr + ); /** Make a 3D offset of this shape * @@ -957,24 +1064,19 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementOffset(double offset, - double tol, - bool intersection = false, - bool selfInter = false, - short offsetMode = 0, - JoinType join = JoinType::arc, - FillType fill = FillType::noFill, - const char* op = nullptr) const + TopoShape makeElementOffset( + double offset, + double tol, + bool intersection = false, + bool selfInter = false, + short offsetMode = 0, + JoinType join = JoinType::arc, + FillType fill = FillType::noFill, + const char* op = nullptr + ) const { - return TopoShape(0, Hasher).makeElementOffset(*this, - offset, - tol, - intersection, - selfInter, - offsetMode, - join, - fill, - op); + return TopoShape(0, Hasher) + .makeElementOffset(*this, offset, tol, intersection, selfInter, offsetMode, join, fill, op); } /** Make a 2D offset of a given shape @@ -995,13 +1097,15 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementOffset2D(const TopoShape& source, - double offset, - JoinType join = JoinType::arc, - FillType fill = FillType::noFill, - OpenResult allowOpenResult = OpenResult::allowOpenResult, - bool intersection = false, - const char* op = nullptr); + TopoShape& makeElementOffset2D( + const TopoShape& source, + double offset, + JoinType join = JoinType::arc, + FillType fill = FillType::noFill, + OpenResult allowOpenResult = OpenResult::allowOpenResult, + bool intersection = false, + const char* op = nullptr + ); /** Make a 2D offset of a given shape * * @param source: source shape of edge, wire, face, or compound @@ -1017,12 +1121,14 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementOffset2D(double offset, - JoinType join = JoinType::arc, - FillType fill = FillType::noFill, - OpenResult allowOpenResult = OpenResult::allowOpenResult, - bool intersection = false, - const char* op = nullptr) const + TopoShape makeElementOffset2D( + double offset, + JoinType join = JoinType::arc, + FillType fill = FillType::noFill, + OpenResult allowOpenResult = OpenResult::allowOpenResult, + bool intersection = false, + const char* op = nullptr + ) const { return TopoShape(0, Hasher) .makeElementOffset2D(*this, offset, join, fill, allowOpenResult, intersection, op); @@ -1044,12 +1150,14 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementOffsetFace(const TopoShape& source, - double offset, - double innerOffset, - JoinType join = JoinType::arc, - JoinType innerJoin = JoinType::arc, - const char* op = nullptr); + TopoShape& makeElementOffsetFace( + const TopoShape& source, + double offset, + double innerOffset, + JoinType join = JoinType::arc, + JoinType innerJoin = JoinType::arc, + const char* op = nullptr + ); /** Make a 2D offset of face with separate control for outer and inner (hole) wires * @@ -1064,18 +1172,19 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementOffsetFace(double offset, - double innerOffset, - JoinType join = JoinType::arc, - JoinType innerJoin = JoinType::arc, - const char* op = nullptr) const + TopoShape makeElementOffsetFace( + double offset, + double innerOffset, + JoinType join = JoinType::arc, + JoinType innerJoin = JoinType::arc, + const char* op = nullptr + ) const { return TopoShape(0, Hasher) .makeElementOffsetFace(*this, offset, innerOffset, join, innerJoin, op); } - /** Make revolved shell around a basis shape * * @param base: the base shape @@ -1091,8 +1200,13 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape &makeElementRevolve(const TopoShape &base, const gp_Ax1& axis, double d, - const char *face_maker=0, const char *op=nullptr); + TopoShape& makeElementRevolve( + const TopoShape& base, + const gp_Ax1& axis, + double d, + const char* face_maker = 0, + const char* op = nullptr + ); /** Make revolved shell around a basis shape * @@ -1105,9 +1219,14 @@ public: * * @return Return the generated new shape. The TopoShape itself is not modified. */ - TopoShape makeElementRevolve(const gp_Ax1& axis, double d, - const char *face_maker=nullptr, const char *op=nullptr) const { - return TopoShape(0,Hasher).makeElementRevolve(*this,axis,d,face_maker,op); + TopoShape makeElementRevolve( + const gp_Ax1& axis, + double d, + const char* face_maker = nullptr, + const char* op = nullptr + ) const + { + return TopoShape(0, Hasher).makeElementRevolve(*this, axis, d, face_maker, op); } @@ -1127,15 +1246,17 @@ public: * * @return Return the generated new shape. The TopoShape itself is not modified. */ - TopoShape& makeElementRevolution(const TopoShape& _base, - const TopoDS_Shape& profile, - const gp_Ax1& axis, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const char* face_maker = nullptr, - RevolMode Mode = RevolMode::None, - Standard_Boolean Modify = Standard_True, - const char* op = nullptr); + TopoShape& makeElementRevolution( + const TopoShape& _base, + const TopoDS_Shape& profile, + const gp_Ax1& axis, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const char* face_maker = nullptr, + RevolMode Mode = RevolMode::None, + Standard_Boolean Modify = Standard_True, + const char* op = nullptr + ); /** Make revolved shell around a basis shape * @@ -1151,24 +1272,28 @@ public: * * @return Return the generated new shape. The TopoShape itself is not modified. */ - TopoShape& makeElementRevolution(const gp_Ax1& axis, - const TopoDS_Shape& profile, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const char* face_maker = nullptr, - RevolMode Mode = RevolMode::None, - Standard_Boolean Modify = Standard_True, - const char* op = nullptr) const + TopoShape& makeElementRevolution( + const gp_Ax1& axis, + const TopoDS_Shape& profile, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const char* face_maker = nullptr, + RevolMode Mode = RevolMode::None, + Standard_Boolean Modify = Standard_True, + const char* op = nullptr + ) const { - return TopoShape(0, Hasher).makeElementRevolution(*this, - profile, - axis, - supportface, - uptoface, - face_maker, - Mode, - Modify, - op); + return TopoShape(0, Hasher).makeElementRevolution( + *this, + profile, + axis, + supportface, + uptoface, + face_maker, + Mode, + Modify, + op + ); } /** Make a prism that is a linear sweep of a basis shape @@ -1183,7 +1308,7 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape &makeElementPrism(const TopoShape &base, const gp_Vec& vec, const char *op=nullptr); + TopoShape& makeElementPrism(const TopoShape& base, const gp_Vec& vec, const char* op = nullptr); /** Make a prism that is a linear sweep of this shape * @@ -1193,12 +1318,14 @@ public: * * @return Return the generated new shape. The TopoShape itself is not modified. */ - TopoShape makeElementPrism(const gp_Vec& vec, const char *op=nullptr) const { - return TopoShape(0,Hasher).makeElementPrism(*this,vec,op); + TopoShape makeElementPrism(const gp_Vec& vec, const char* op = nullptr) const + { + return TopoShape(0, Hasher).makeElementPrism(*this, vec, op); } /// Operation mode for makeElementPrismUntil() - enum PrismMode { + enum PrismMode + { /// Remove the generated prism shape from the base shape with boolean cut CutFromBase = 0, /// Add generated prism shape to the base shape with fusion @@ -1227,16 +1354,19 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementPrismUntil(const TopoShape& base, - const TopoShape& profile, - const TopoShape& supportFace, - const TopoShape& upToFace, - const gp_Dir& direction, - PrismMode mode, - Standard_Boolean checkLimits = Standard_True, - const char* op = nullptr); + TopoShape& makeElementPrismUntil( + const TopoShape& base, + const TopoShape& profile, + const TopoShape& supportFace, + const TopoShape& upToFace, + const gp_Dir& direction, + PrismMode mode, + Standard_Boolean checkLimits = Standard_True, + const char* op = nullptr + ); - /** Make a prism based on this shape that is either depression or protrusion of a profile shape up to a given face + /** Make a prism based on this shape that is either depression or protrusion of a profile shape + * up to a given face * * @param profile: profile shape used for sweeping to make the prism * @param supportFace: optional face serves to determining the type of @@ -1253,22 +1383,26 @@ public: * * @return Return the generated new shape. The TopoShape itself is not modified. */ - TopoShape makeElementPrismUntil(const TopoShape& profile, - const TopoShape& supportFace, - const TopoShape& upToFace, - const gp_Dir& direction, - PrismMode mode, - Standard_Boolean checkLimits = Standard_True, - const char* op = nullptr) const + TopoShape makeElementPrismUntil( + const TopoShape& profile, + const TopoShape& supportFace, + const TopoShape& upToFace, + const gp_Dir& direction, + PrismMode mode, + Standard_Boolean checkLimits = Standard_True, + const char* op = nullptr + ) const { - return TopoShape(0, Hasher).makeElementPrismUntil(*this, - profile, - supportFace, - upToFace, - direction, - mode, - checkLimits, - op); + return TopoShape(0, Hasher).makeElementPrismUntil( + *this, + profile, + supportFace, + upToFace, + direction, + mode, + checkLimits, + op + ); } @@ -1293,14 +1427,16 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementPipeShell(const std::vector& sources, - const MakeSolid makeSolid, - const Standard_Boolean isFrenet, - TransitionMode transition = TransitionMode::Transformed, - const char* op = nullptr, - double tol3d = 0.0, - double tolBound = 0.0, - double tolAngular = 0.0); + TopoShape& makeElementPipeShell( + const std::vector& sources, + const MakeSolid makeSolid, + const Standard_Boolean isFrenet, + TransitionMode transition = TransitionMode::Transformed, + const char* op = nullptr, + double tol3d = 0.0, + double tolBound = 0.0, + double tolAngular = 0.0 + ); /* Make a shape with some subshapes replaced. * @@ -1312,8 +1448,10 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& replaceElementShape(const TopoShape& source, - const std::vector>& s); + TopoShape& replaceElementShape( + const TopoShape& source, + const std::vector>& s + ); /* Make a new shape using this shape with some subshapes replaced by others * * @param s: replacement mapping the existing sub shape of source to new shapes @@ -1360,10 +1498,12 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementGeneralFuse(const std::vector& sources, - std::vector>& modified, - double tol = -1.0, - const char* op = nullptr); + TopoShape& makeElementGeneralFuse( + const std::vector& sources, + std::vector>& modified, + double tol = -1.0, + const char* op = nullptr + ); /** Make a fusion of input shapes * @@ -1377,9 +1517,11 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementFuse(const std::vector& sources, - const char* op = nullptr, - double tol = -1.0); + TopoShape& makeElementFuse( + const std::vector& sources, + const char* op = nullptr, + double tol = -1.0 + ); /** Make a fusion of this shape and an input shape * * @param source: the source shape @@ -1389,8 +1531,7 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape - makeElementFuse(const TopoShape& source, const char* op = nullptr, double tol = -1.0) const + TopoShape makeElementFuse(const TopoShape& source, const char* op = nullptr, double tol = -1.0) const { return TopoShape(0, Hasher).makeElementFuse({*this, source}, op, tol); } @@ -1407,8 +1548,11 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& - makeElementCut(const std::vector& sources, const char* op = nullptr, double tol = -1.0); + TopoShape& makeElementCut( + const std::vector& sources, + const char* op = nullptr, + double tol = -1.0 + ); /** Make a boolean cut of this shape with an input shape * * @param source: the source shape @@ -1418,8 +1562,7 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape - makeElementCut(const TopoShape& source, const char* op = nullptr, double tol = -1.0) const + TopoShape makeElementCut(const TopoShape& source, const char* op = nullptr, double tol = -1.0) const { return TopoShape(0, Hasher).makeElementCut({*this, source}, op, tol); } @@ -1436,8 +1579,11 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& - makeElementXor(const std::vector& sources, const char* op = nullptr, double tol = -1.0); + TopoShape& makeElementXor( + const std::vector& sources, + const char* op = nullptr, + double tol = -1.0 + ); /** Make a boolean xor of this shape with an input shape * * @param source: the source shape @@ -1447,8 +1593,7 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape - makeElementXor(const TopoShape& source, const char* op = nullptr, double tol = -1.0) const + TopoShape makeElementXor(const TopoShape& source, const char* op = nullptr, double tol = -1.0) const { return TopoShape(0, Hasher).makeElementXor({*this, source}, op, tol); } @@ -1465,24 +1610,30 @@ public: static const std::string& shapeName(TopAbs_ShapeEnum type, bool silent = false); const std::string& shapeName(bool silent = false) const; static std::pair shapeTypeAndIndex(const char* name); - static std::pair shapeTypeAndIndex(const Data::IndexedName &name); + static std::pair shapeTypeAndIndex(const Data::IndexedName& name); - Data::MappedName setElementComboName(const Data::IndexedName & element, - const std::vector &names, - const char *marker=nullptr, - const char *op=nullptr, - const Data::ElementIDRefs *sids=nullptr); + Data::MappedName setElementComboName( + const Data::IndexedName& element, + const std::vector& names, + const char* marker = nullptr, + const char* op = nullptr, + const Data::ElementIDRefs* sids = nullptr + ); - std::vector decodeElementComboName(const Data::IndexedName& element, - const Data::MappedName& name, - const char* marker = nullptr, - std::string* postfix = nullptr) const; + std::vector decodeElementComboName( + const Data::IndexedName& element, + const Data::MappedName& name, + const char* marker = nullptr, + std::string* postfix = nullptr + ) const; - void reTagElementMap(long tag, // NOLINT google-default-arguments - App::StringHasherRef hasher, - const char* postfix = nullptr) override; + void reTagElementMap( + long tag, // NOLINT google-default-arguments + App::StringHasherRef hasher, + const char* postfix = nullptr + ) override; - long isElementGenerated(const Data::MappedName &name, int depth=1) const; + long isElementGenerated(const Data::MappedName& name, int depth = 1) const; /** @name sub shape cached functions * @@ -1498,12 +1649,14 @@ public: int findAncestor(const TopoDS_Shape& subshape, TopAbs_ShapeEnum type) const; TopoDS_Shape findAncestorShape(const TopoDS_Shape& subshape, TopAbs_ShapeEnum type) const; std::vector findAncestors(const TopoDS_Shape& subshape, TopAbs_ShapeEnum type) const; - std::vector findAncestorsShapes(const TopoDS_Shape& subshape, - TopAbs_ShapeEnum type) const; + std::vector findAncestorsShapes( + const TopoDS_Shape& subshape, + TopAbs_ShapeEnum type + ) const; /** Find sub shapes with shared Vertexes. * * Renamed: searchSubShape -> findSubShapesWithSharedVertex - * + * * unlike findShape(), the input shape does not have to be an actual * sub-shape of this shape. The sub-shape is searched by shape geometry * Note that subshape must be a Vertex, Edge, or Face. @@ -1514,24 +1667,31 @@ public: * @param tol: tolerance to check coincident vertices * @param atol: tolerance to check for same angles */ - std::vector findSubShapesWithSharedVertex(const TopoShape &subshape, - std::vector *names=nullptr, - Data::SearchOptions = Data::SearchOption::CheckGeometry, - double tol=1e-7, double atol=1e-12) const; + std::vector findSubShapesWithSharedVertex( + const TopoShape& subshape, + std::vector* names = nullptr, + Data::SearchOptions = Data::SearchOption::CheckGeometry, + double tol = 1e-7, + double atol = 1e-12 + ) const; //@} - void copyElementMap(const TopoShape & topoShape, const char *op=nullptr); - bool canMapElement(const TopoShape &other) const; - void cacheRelatedElements(const Data::MappedName & name, - HistoryTraceType sameType, - const QVector & names) const; + void copyElementMap(const TopoShape& topoShape, const char* op = nullptr); + bool canMapElement(const TopoShape& other) const; + void cacheRelatedElements( + const Data::MappedName& name, + HistoryTraceType sameType, + const QVector& names + ) const; - bool getRelatedElementsCached(const Data::MappedName & name, - HistoryTraceType sameType, - QVector &names) const; + bool getRelatedElementsCached( + const Data::MappedName& name, + HistoryTraceType sameType, + QVector& names + ) const; - void mapSubElement(const TopoShape &other,const char *op=nullptr, bool forceHasher=false); - void mapSubElement(const std::vector &shapes, const char *op=nullptr); + void mapSubElement(const TopoShape& other, const char* op = nullptr, bool forceHasher = false); + void mapSubElement(const std::vector& shapes, const char* op = nullptr); void mapSubElementsTo(std::vector& shapes, const char* op = nullptr) const; bool hasPendingElementMap() const; @@ -1539,11 +1699,12 @@ public: void flushElementMap() const override; - Data::ElementMapPtr resetElementMap( - Data::ElementMapPtr elementMap=Data::ElementMapPtr()) override; + Data::ElementMapPtr resetElementMap(Data::ElementMapPtr elementMap = Data::ElementMapPtr()) override; - std::vector getHigherElements(const char *element, - bool silent = false) const override; + std::vector getHigherElements( + const char* element, + bool silent = false + ) const override; /** Helper class to return the generated and modified shape given an input shape * @@ -1552,16 +1713,20 @@ public: * some glitches in various derived class. So we use this class as an * abstraction, and create various derived classes to deal with the glitches. */ - struct PartExport Mapper { + struct PartExport Mapper + { /// Helper vector for temporary storage of both generated and modified shapes mutable std::vector _res; - virtual ~Mapper() {} + virtual ~Mapper() + {} /// Return a list of shape generated from the given input shape - virtual const std::vector &generated(const TopoDS_Shape &) const { + virtual const std::vector& generated(const TopoDS_Shape&) const + { return _res; } /// Return a list of shape modified from the given input shape - virtual const std::vector &modified(const TopoDS_Shape &) const { + virtual const std::vector& modified(const TopoDS_Shape&) const + { return _res; } }; @@ -1587,14 +1752,16 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementEvolve(const TopoShape& spine, - const TopoShape& profile, - JoinType join = JoinType::arc, - CoordinateSystem = CoordinateSystem::global, - MakeSolid solid = MakeSolid::noSolid, - Spine profOnSpine = Spine::notOn, - double tol = 0.0, - const char* op = nullptr); + TopoShape& makeElementEvolve( + const TopoShape& spine, + const TopoShape& profile, + JoinType join = JoinType::arc, + CoordinateSystem = CoordinateSystem::global, + MakeSolid solid = MakeSolid::noSolid, + Spine profOnSpine = Spine::notOn, + double tol = 0.0, + const char* op = nullptr + ); /** Make an evolved shape using this shape as spine * @@ -1612,13 +1779,15 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementEvolve(const TopoShape& profile, - JoinType join = JoinType::arc, - CoordinateSystem axeProf = CoordinateSystem::global, - MakeSolid solid = MakeSolid::noSolid, - Spine profOnSpine = Spine::notOn, - double tol = 0.0, - const char* op = nullptr) + TopoShape makeElementEvolve( + const TopoShape& profile, + JoinType join = JoinType::arc, + CoordinateSystem axeProf = CoordinateSystem::global, + MakeSolid solid = MakeSolid::noSolid, + Spine profOnSpine = Spine::notOn, + double tol = 0.0, + const char* op = nullptr + ) { return TopoShape(0, Hasher) .makeElementEvolve(*this, profile, join, axeProf, solid, profOnSpine, tol, op); @@ -1645,9 +1814,14 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape &makeElementLoft(const std::vector &sources, - IsSolid isSolid, IsRuled isRuled, IsClosed isClosed=IsClosed::notClosed, - Standard_Integer maxDegree=5, const char *op=nullptr); + TopoShape& makeElementLoft( + const std::vector& sources, + IsSolid isSolid, + IsRuled isRuled, + IsClosed isClosed = IsClosed::notClosed, + Standard_Integer maxDegree = 5, + const char* op = nullptr + ); /** Make a ruled surface * @@ -1662,7 +1836,11 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape &makeElementRuledSurface(const std::vector &source, int orientation=0, const char *op=nullptr); + TopoShape& makeElementRuledSurface( + const std::vector& source, + int orientation = 0, + const char* op = nullptr + ); /** Core function to generate mapped element names from shape history * @@ -1677,15 +1855,18 @@ public: * itself as a self reference so that multiple operations can be * carried out for the same shape in the same line of code. */ - TopoShape &makeShapeWithElementMap(const TopoDS_Shape &shape, - const Mapper &mapper, - const std::vector &sources, - const char *op=nullptr); + TopoShape& makeShapeWithElementMap( + const TopoDS_Shape& shape, + const Mapper& mapper, + const std::vector& sources, + const char* op = nullptr + ); /** * When given a single shape to create a compound, two results are possible: either to simply * return the shape as given, or to force it to be placed in a Compound. */ - enum class SingleShapeCompoundCreationPolicy { + enum class SingleShapeCompoundCreationPolicy + { returnShape, forceCompound }; @@ -1702,10 +1883,11 @@ public: * a reference so that multiple operations can be carried out for * the same shape in the same line of code. */ - TopoShape& makeElementCompound(const std::vector& shapes, - const char* op = nullptr, - SingleShapeCompoundCreationPolicy policy = - SingleShapeCompoundCreationPolicy::forceCompound); + TopoShape& makeElementCompound( + const std::vector& shapes, + const char* op = nullptr, + SingleShapeCompoundCreationPolicy policy = SingleShapeCompoundCreationPolicy::forceCompound + ); enum class ConnectionPolicy @@ -1736,11 +1918,13 @@ public: * a reference so that multiple operations can be carried out for * the same shape in the same line of code. */ - TopoShape& makeElementWires(const std::vector& shapes, - const char* op = nullptr, - double tol = 0.0, - ConnectionPolicy policy = ConnectionPolicy::mergeWithTolerance, - TopoShapeMap* output = nullptr); + TopoShape& makeElementWires( + const std::vector& shapes, + const char* op = nullptr, + double tol = 0.0, + ConnectionPolicy policy = ConnectionPolicy::mergeWithTolerance, + TopoShapeMap* output = nullptr + ); /** Make a compound of wires by connecting input edges @@ -1765,11 +1949,13 @@ public: * a reference so that multiple operations can be carried out for * the same shape in the same line of code. */ - TopoShape& makeElementWires(const TopoShape& shape, - const char* op = nullptr, - double tol = 0.0, - ConnectionPolicy policy = ConnectionPolicy::mergeWithTolerance, - TopoShapeMap* output = nullptr); + TopoShape& makeElementWires( + const TopoShape& shape, + const char* op = nullptr, + double tol = 0.0, + ConnectionPolicy policy = ConnectionPolicy::mergeWithTolerance, + TopoShapeMap* output = nullptr + ); /** Make a compound of wires by connecting input edges in the given order * @@ -1791,10 +1977,12 @@ public: * a reference so that multiple operations can be carried out for * the same shape in the same line of code. */ - TopoShape& makeElementOrderedWires(const std::vector& shapes, - const char* op = nullptr, - double tol = 0.0, - TopoShapeMap* output = nullptr); + TopoShape& makeElementOrderedWires( + const std::vector& shapes, + const char* op = nullptr, + double tol = 0.0, + TopoShapeMap* output = nullptr + ); /** Make a wire or compound of wires with the edges inside the this shape * @@ -1814,10 +2002,12 @@ public: * @return The function returns a new shape of either a single wire or a * compound of wires. The shape itself is not modified. */ - TopoShape makeElementWires(const char* op = nullptr, - double tol = 0.0, - ConnectionPolicy policy = ConnectionPolicy::mergeWithTolerance, - TopoShapeMap* output = nullptr) const + TopoShape makeElementWires( + const char* op = nullptr, + double tol = 0.0, + ConnectionPolicy policy = ConnectionPolicy::mergeWithTolerance, + TopoShapeMap* output = nullptr + ) const { return TopoShape(0, Hasher).makeElementWires(*this, op, tol, policy, output); } @@ -1836,10 +2026,12 @@ public: * TopoShape itself as a self reference so that multiple operations * can be carried out for the same shape in the same line of code. */ - TopoShape& makeElementGTransform(const TopoShape& source, - const Base::Matrix4D& mat, - const char* op = nullptr, - CopyType copy = CopyType::noCopy); + TopoShape& makeElementGTransform( + const TopoShape& source, + const Base::Matrix4D& mat, + const char* op = nullptr, + CopyType copy = CopyType::noCopy + ); /** Make a new shape with transformation that may contain non-uniform scaling * @@ -1853,9 +2045,11 @@ public: * @return Return a new shape with transformation. The shape itself is not * modified */ - TopoShape makeElementGTransform(const Base::Matrix4D& mat, - const char* op = nullptr, - CopyType copy = CopyType::noCopy) const + TopoShape makeElementGTransform( + const Base::Matrix4D& mat, + const char* op = nullptr, + CopyType copy = CopyType::noCopy + ) const { return TopoShape(Tag, Hasher).makeElementGTransform(*this, mat, op, copy); } @@ -1873,10 +2067,12 @@ public: * TopoShape itself as a self reference so that multiple operations * can be carried out for the same shape in the same line of code. */ - TopoShape& makeElementCopy(const TopoShape& source, - const char* op = nullptr, - bool copyGeom = true, - bool copyMesh = false); + TopoShape& makeElementCopy( + const TopoShape& source, + const char* op = nullptr, + bool copyGeom = true, + bool copyMesh = false + ); /** Make a deep copy of the shape * @@ -1888,8 +2084,7 @@ public: * @return Return a deep copy of the shape. The shape itself is not * modified */ - TopoShape - makeElementCopy(const char* op = nullptr, bool copyGeom = true, bool copyMesh = false) const + TopoShape makeElementCopy(const char* op = nullptr, bool copyGeom = true, bool copyMesh = false) const { return TopoShape(Tag, Hasher).makeElementCopy(*this, op, copyGeom, copyMesh); } @@ -1909,10 +2104,12 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape& makeElementBoolean(const char* maker, - const std::vector& sources, - const char* op = nullptr, - double tol = -1.0); + TopoShape& makeElementBoolean( + const char* maker, + const std::vector& sources, + const char* op = nullptr, + double tol = -1.0 + ); /** Generalized shape making with mapped element name from shape history * * @param maker: op code from TopoShapeOpCodes @@ -1927,10 +2124,12 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape& makeElementBoolean(const char* maker, - const TopoShape& source, - const char* op = nullptr, - double tol = -1.0); + TopoShape& makeElementBoolean( + const char* maker, + const TopoShape& source, + const char* op = nullptr, + double tol = -1.0 + ); /** Generalized shape making with mapped element name from shape history * @@ -1943,8 +2142,7 @@ public: * shape history using this shape as the source. The shape itself * is not modified. */ - TopoShape - makeElementBoolean(const char* maker, const char* op = nullptr, double tol = -1.0) const + TopoShape makeElementBoolean(const char* maker, const char* op = nullptr, double tol = -1.0) const { return TopoShape(0, Hasher).makeElementBoolean(maker, *this, op, tol); } @@ -1961,8 +2159,7 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& - makeElementMirror(const TopoShape& source, const gp_Ax2& axis, const char* op = nullptr); + TopoShape& makeElementMirror(const TopoShape& source, const gp_Ax2& axis, const char* op = nullptr); /** Make a mirrored shape * * @param source: the source shape @@ -1990,10 +2187,12 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementSlice(const TopoShape& source, - const Base::Vector3d& dir, - double distance, - const char* op = nullptr); + TopoShape& makeElementSlice( + const TopoShape& source, + const Base::Vector3d& dir, + double distance, + const char* op = nullptr + ); /** Make a cross section slice * * @param source: the source shape @@ -2022,10 +2221,12 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementSlices(const TopoShape& source, - const Base::Vector3d& dir, - const std::vector& distances, - const char* op = nullptr); + TopoShape& makeElementSlices( + const TopoShape& source, + const Base::Vector3d& dir, + const std::vector& distances, + const char* op = nullptr + ); /** Make multiple cross section slices * * @param source: the source shape @@ -2036,9 +2237,11 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementSlices(const Base::Vector3d& dir, - const std::vector& distances, - const char* op = nullptr) const + TopoShape makeElementSlices( + const Base::Vector3d& dir, + const std::vector& distances, + const char* op = nullptr + ) const { return TopoShape(0, Hasher).makeElementSlices(*this, dir, distances, op); } @@ -2057,11 +2260,13 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementFillet(const TopoShape& source, - const std::vector& edges, - double radius1, - double radius2, - const char* op = nullptr); + TopoShape& makeElementFillet( + const TopoShape& source, + const std::vector& edges, + double radius1, + double radius2, + const char* op = nullptr + ); /* Make fillet shape * * @param source: the source shape @@ -2073,10 +2278,12 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementFillet(const std::vector& edges, - double radius1, - double radius2, - const char* op = nullptr) const + TopoShape makeElementFillet( + const std::vector& edges, + double radius1, + double radius2, + const char* op = nullptr + ) const { return TopoShape(0, Hasher).makeElementFillet(*this, edges, radius1, radius2, op); } @@ -2095,13 +2302,15 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementChamfer(const TopoShape& source, - const std::vector& edges, - ChamferType chamferType, - double radius1, - double radius2, - const char* op = nullptr, - Flip flipDirection = Flip::none); + TopoShape& makeElementChamfer( + const TopoShape& source, + const std::vector& edges, + ChamferType chamferType, + double radius1, + double radius2, + const char* op = nullptr, + Flip flipDirection = Flip::none + ); /* Make chamfer shape * * @param source: the source shape @@ -2113,12 +2322,14 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementChamfer(const std::vector& edges, - ChamferType chamferType, - double radius1, - double radius2, - const char* op = nullptr, - Flip flipDirection = Flip::none) const + TopoShape makeElementChamfer( + const std::vector& edges, + ChamferType chamferType, + double radius1, + double radius2, + const char* op = nullptr, + Flip flipDirection = Flip::none + ) const { return TopoShape(0, Hasher) .makeElementChamfer(*this, edges, chamferType, radius1, radius2, op, flipDirection); @@ -2141,11 +2352,13 @@ public: * The original content of this TopoShape is discarded and replaced with * the new transformed shape. */ - bool _makeElementTransform(const TopoShape& source, - const Base::Matrix4D& mat, - const char* op = nullptr, - CheckScale checkScale = CheckScale::noScaleCheck, - CopyType copy = CopyType::noCopy); + bool _makeElementTransform( + const TopoShape& source, + const Base::Matrix4D& mat, + const char* op = nullptr, + CheckScale checkScale = CheckScale::noScaleCheck, + CopyType copy = CopyType::noCopy + ); /** Make a new shape with transformation * @@ -2164,11 +2377,13 @@ public: * TopoShape itself as a self reference so that multiple operations * can be carried out for the same shape in the same line of code. */ - TopoShape& makeElementTransform(const TopoShape& source, - const Base::Matrix4D& mat, - const char* op = nullptr, - CheckScale checkScale = CheckScale::noScaleCheck, - CopyType copy = CopyType::noCopy) + TopoShape& makeElementTransform( + const TopoShape& source, + const Base::Matrix4D& mat, + const char* op = nullptr, + CheckScale checkScale = CheckScale::noScaleCheck, + CopyType copy = CopyType::noCopy + ) { _makeElementTransform(source, mat, op, checkScale, copy); return *this; @@ -2189,10 +2404,12 @@ public: * @return Return a new shape with transformation. The shape itself is not * modified */ - TopoShape makeElementTransform(const Base::Matrix4D& mat, - const char* op = nullptr, - CheckScale checkScale = CheckScale::noScaleCheck, - CopyType copy = CopyType::noCopy) + TopoShape makeElementTransform( + const Base::Matrix4D& mat, + const char* op = nullptr, + CheckScale checkScale = CheckScale::noScaleCheck, + CopyType copy = CopyType::noCopy + ) { return TopoShape(Tag, Hasher).makeElementTransform(*this, mat, op, checkScale, copy); } @@ -2210,10 +2427,12 @@ public: * TopoShape itself as a self reference so that multiple operations * can be carried out for the same shape in the same line of code. */ - TopoShape& makeElementTransform(const TopoShape& shape, - const gp_Trsf& trsf, - const char* op = nullptr, - CopyType copy = CopyType::noCopy); + TopoShape& makeElementTransform( + const TopoShape& shape, + const gp_Trsf& trsf, + const char* op = nullptr, + CopyType copy = CopyType::noCopy + ); /** Make a new shape with transformation * @@ -2226,8 +2445,11 @@ public: * @return Return a new shape with transformation. The shape itself is not * modified */ - TopoShape - makeElementTransform(const gp_Trsf& trsf, const char* op = nullptr, CopyType copy = CopyType::noCopy) + TopoShape makeElementTransform( + const gp_Trsf& trsf, + const char* op = nullptr, + CopyType copy = CopyType::noCopy + ) { return TopoShape(Tag, Hasher).makeElementTransform(*this, trsf, op, copy); } @@ -2248,9 +2470,15 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape &makeElementDraft(const TopoShape &source, const std::vector &faces, - const gp_Dir &pullDirection, double angle, const gp_Pln &neutralPlane, - bool retry=true, const char *op=nullptr); + TopoShape& makeElementDraft( + const TopoShape& source, + const std::vector& faces, + const gp_Dir& pullDirection, + double angle, + const gp_Pln& neutralPlane, + bool retry = true, + const char* op = nullptr + ); /* Make draft shape * * @param source: the source shape @@ -2264,10 +2492,17 @@ public: * * @return Return the new shape. The TopoShape itself is not modified. */ - TopoShape makeElementDraft(const std::vector &faces, - const gp_Dir &pullDirection, double angle, const gp_Pln &neutralPlane, - bool retry=true, const char *op=nullptr) const { - return TopoShape(0,Hasher).makeElementDraft(*this,faces,pullDirection,angle,neutralPlane,retry,op); + TopoShape makeElementDraft( + const std::vector& faces, + const gp_Dir& pullDirection, + double angle, + const gp_Pln& neutralPlane, + bool retry = true, + const char* op = nullptr + ) const + { + return TopoShape(0, Hasher) + .makeElementDraft(*this, faces, pullDirection, angle, neutralPlane, retry, op); } /* Make a shell using this shape @@ -2294,9 +2529,11 @@ public: * a self reference so that multiple operations can be carried out * for the same shape in the same line of code. */ - TopoShape& makeElementShellFromWires(const std::vector& wires, - bool silent = true, - const char* op = nullptr); + TopoShape& makeElementShellFromWires( + const std::vector& wires, + bool silent = true, + const char* op = nullptr + ); /* Make a shell with input wires * * @param wires: input wires @@ -2327,10 +2564,12 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape& makeElementFace(const std::vector& shapes, - const char* op = nullptr, - const char* maker = nullptr, - const gp_Pln* plane = nullptr); + TopoShape& makeElementFace( + const std::vector& shapes, + const char* op = nullptr, + const char* maker = nullptr, + const gp_Pln* plane = nullptr + ); /** Make a planar face with the input wire or edge * * @param shape: input shape. Can be either edge, wire, or compound of @@ -2347,10 +2586,12 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape& makeElementFace(const TopoShape& shape, - const char* op = nullptr, - const char* maker = nullptr, - const gp_Pln* plane = nullptr); + TopoShape& makeElementFace( + const TopoShape& shape, + const char* op = nullptr, + const char* maker = nullptr, + const gp_Pln* plane = nullptr + ); /** Make a planar face using this shape * * @param op: optional string to be encoded into topo naming for indicating @@ -2362,9 +2603,11 @@ public: * @return The function returns a new planar face made using the wire or edge * inside this shape. The shape itself is not modified. */ - TopoShape makeElementFace(const char* op = nullptr, - const char* maker = nullptr, - const gp_Pln* plane = nullptr) const + TopoShape makeElementFace( + const char* op = nullptr, + const char* maker = nullptr, + const gp_Pln* plane = nullptr + ) const { return TopoShape(0, Hasher).makeElementFace(*this, op, maker, plane); } @@ -2385,10 +2628,12 @@ public: * itself as a self reference so that multiple operations can be * carried out for the same shape in the same line of code. */ - TopoShape &makeElementBSplineFace(const std::vector &input, - FillingStyle style = FillingStyle::stretch, - bool keepBezier = false, - const char *op=nullptr); + TopoShape& makeElementBSplineFace( + const std::vector& input, + FillingStyle style = FillingStyle::stretch, + bool keepBezier = false, + const char* op = nullptr + ); /** Make a face with BSpline (or Bezier) surface * * @param shape: input shape of any type, but only edges inside the shape @@ -2405,10 +2650,12 @@ public: * itself as a self reference so that multiple operations can be * carried out for the same shape in the same line of code. */ - TopoShape &makeElementBSplineFace(const TopoShape &input, - FillingStyle style = FillingStyle::stretch, - bool keepBezier = false, - const char *op=nullptr); + TopoShape& makeElementBSplineFace( + const TopoShape& input, + FillingStyle style = FillingStyle::stretch, + bool keepBezier = false, + const char* op = nullptr + ); /** Make a face with BSpline (or Bezier) surface * * @param style: surface filling style. @sa FillingStyle @@ -2420,11 +2667,13 @@ public: * @return The function returns a new face with either BSpline or Bezier * surface. The shape itself is not modified. */ - TopoShape makeElementBSplineFace(FillingStyle style = FillingStyle::stretch, - bool keepBezier = false, - const char *op=nullptr) + TopoShape makeElementBSplineFace( + FillingStyle style = FillingStyle::stretch, + bool keepBezier = false, + const char* op = nullptr + ) { - return TopoShape(0,Hasher).makeElementBSplineFace(*this, style, keepBezier, op); + return TopoShape(0, Hasher).makeElementBSplineFace(*this, style, keepBezier, op); } @@ -2433,21 +2682,22 @@ public: /** Provides information about the continuity of a curve. * Corresponds to OCCT type GeomAbs_Shape */ - enum class Continuity { + enum class Continuity + { /// Only geometric continuity C0, /** for each point on the curve, the tangent vectors 'on the right' and 'on - * the left' are collinear with the same orientation. - */ - G1, + * the left' are collinear with the same orientation. + */ + G1, /** Continuity of the first derivative. The 'C1' curve is also 'G1' but, in - * addition, the tangent vectors 'on the right' and 'on the left' are equal. - */ + * addition, the tangent vectors 'on the right' and 'on the left' are equal. + */ C1, /** For each point on the curve, the normalized normal vectors 'on the - * right' and 'on the left' are equal. - */ + * right' and 'on the left' are equal. + */ G2, /// Continuity of the second derivative. @@ -2457,9 +2707,9 @@ public: C3, /** Continuity of the N-th derivative, whatever is the value given for N - * (infinite order of continuity). Also provides information about the - * continuity of a surface. - */ + * (infinite order of continuity). Also provides information about the + * continuity of a surface. + */ CN, }; @@ -2482,9 +2732,11 @@ public: * * @sa OCCT BRepOffsetAPI_MakeFilling */ - TopoShape &makeElementFilledFace(const std::vector &shapes, - const BRepFillingParams ¶ms, - const char *op=nullptr); + TopoShape& makeElementFilledFace( + const std::vector& shapes, + const BRepFillingParams& params, + const char* op = nullptr + ); /** Make a solid using shells or CompSolid @@ -2500,7 +2752,7 @@ public: * that multiple operations can be carried out for the same shape * in the same line of code. */ - TopoShape &makeElementSolid(const TopoShape &shape, const char *op=nullptr); + TopoShape& makeElementSolid(const TopoShape& shape, const char* op = nullptr); /** Make a solid using this shape * * @param op: optional string to be encoded into topo naming for indicating @@ -2509,8 +2761,9 @@ public: * @return The function returns a new solid using the shell or CompSolid * inside this shape. The shape itself is not modified. */ - TopoShape makeElementSolid(const char *op=nullptr) const { - return TopoShape(0,Hasher).makeElementSolid(*this,op); + TopoShape makeElementSolid(const char* op = nullptr) const + { + return TopoShape(0, Hasher).makeElementSolid(*this, op); } @@ -2527,9 +2780,11 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape& makeElementShape(BRepBuilderAPI_MakeShape& mkShape, - const std::vector& sources, - const char* op = nullptr); + TopoShape& makeElementShape( + BRepBuilderAPI_MakeShape& mkShape, + const std::vector& sources, + const char* op = nullptr + ); /** Generic shape making with mapped element name from shape history * * @param mkShape: OCCT shape maker. @@ -2543,9 +2798,11 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape& makeElementShape(BRepBuilderAPI_MakeShape& mkShape, - const TopoShape& source, - const char* op = nullptr); + TopoShape& makeElementShape( + BRepBuilderAPI_MakeShape& mkShape, + const TopoShape& source, + const char* op = nullptr + ); /** Generic shape making with mapped element name from shape history * * @param mkShape: OCCT shape maker. @@ -2574,8 +2831,12 @@ public: * multiple operations can be carried out for the same shape in the * same line of code. */ - TopoShape &makeElementShape(BRepFeat_MakePrism &mkShape, - const std::vector &sources, const TopoShape &uptoface, const char *op); + TopoShape& makeElementShape( + BRepFeat_MakePrism& mkShape, + const std::vector& sources, + const TopoShape& uptoface, + const char* op + ); /* Toponaming migration, February 2014: * Note that the specialized versions of makeElementShape for operations that do not @@ -2607,12 +2868,13 @@ private: using TopoDS_Shape::TopoDS_Shape; using TopoDS_Shape::operator=; - explicit ShapeProtector(TopoShape & owner) + explicit ShapeProtector(TopoShape& owner) : _owner(&owner) {} - ShapeProtector(TopoShape & owner, const TopoDS_Shape & shape) - : TopoDS_Shape(shape), _owner(&owner) + ShapeProtector(TopoShape& owner, const TopoDS_Shape& shape) + : TopoDS_Shape(shape) + , _owner(&owner) {} void Nullify() @@ -2705,21 +2967,28 @@ private: private: // Helper methods - static std::vector - createChildMap(size_t count, const std::vector& shapes, const char* op); + static std::vector createChildMap( + size_t count, + const std::vector& shapes, + const char* op + ); - void setupChild(Data::ElementMap::MappedChildElements& child, - TopAbs_ShapeEnum elementType, - const TopoShape& topoShape, - size_t shapeCount, - const char* op); + void setupChild( + Data::ElementMap::MappedChildElements& child, + TopAbs_ShapeEnum elementType, + const TopoShape& topoShape, + size_t shapeCount, + const char* op + ); void mapSubElementForShape(const TopoShape& other, const char* op); - void mapSubElementTypeForShape(const TopoShape& other, - TopAbs_ShapeEnum type, - const char* op, - int count, - bool forward, - bool& warned); + void mapSubElementTypeForShape( + const TopoShape& other, + TopAbs_ShapeEnum type, + const char* op, + int count, + bool forward, + bool& warned + ); void mapCompoundSubElements(const std::vector& shapes, const char* op); /** Given a set of edges, return a sorted list of connected edges @@ -2733,8 +3002,11 @@ private: * if two edges are connected * @return Return a list of ordered connected edges. */ - static std::deque - sortEdges(std::list& edges, bool keepOrder = false, double tol = 0.0); + static std::deque sortEdges( + std::list& edges, + bool keepOrder = false, + double tol = 0.0 + ); static TopoShape reverseEdge(const TopoShape& edge); }; diff --git a/src/Mod/Part/App/TopoShape.pyi b/src/Mod/Part/App/TopoShape.pyi index a009c03f50..849018519f 100644 --- a/src/Mod/Part/App/TopoShape.pyi +++ b/src/Mod/Part/App/TopoShape.pyi @@ -84,7 +84,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def writeInventor(self, *, Mode: int, Deviation: float, Angle: float, FaceColors: object) -> str: + def writeInventor( + self, *, Mode: int, Deviation: float, Angle: float, FaceColors: object + ) -> str: """ Write the mesh in OpenInventor format to a string. writeInventor() -> string @@ -290,7 +292,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def section(self, tool: Tuple[TopoShape, ...], tolerance: float = 0.0, approximation: bool = False) -> TopoShape: + def section( + self, tool: Tuple[TopoShape, ...], tolerance: float = 0.0, approximation: bool = False + ) -> TopoShape: """ Section of this with a given (list of) topo shape. section(tool,[approximation=False]) -> Shape @@ -342,7 +346,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def generalFuse(self, shapes: Tuple[TopoShape, ...], fuzzy_value: float = 0.0) -> Tuple[TopoShape, List[List[TopoShape]]]: + def generalFuse( + self, shapes: Tuple[TopoShape, ...], fuzzy_value: float = 0.0 + ) -> Tuple[TopoShape, List[List[TopoShape]]]: """ Run general fuse algorithm (GFA) between this and given shapes. generalFuse(list_of_other_shapes, [fuzzy_value = 0.0]) -> (result, map) @@ -454,7 +460,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def transformed(self, *, matrix: Matrix, copy: bool = False, checkScale: bool = False, op: str = None) -> TopoShape: + def transformed( + self, *, matrix: Matrix, copy: bool = False, checkScale: bool = False, op: str = None + ) -> TopoShape: """ Create a new transformed shape transformed(Matrix,copy=False,checkScale=False,op=None) -> shape @@ -521,11 +529,9 @@ class TopoShape(ComplexGeoData): @overload @constmethod def makeFillet(self, radius: float, edgeList: List) -> TopoShape: ... - @overload @constmethod def makeFillet(self, radius1: float, radius2: float, edgeList: List) -> TopoShape: ... - @constmethod def makeChamfer(self, *args) -> TopoShape: """ @@ -539,11 +545,9 @@ class TopoShape(ComplexGeoData): @overload @constmethod def makeChamfer(self, radius: float, edgeList: List) -> TopoShape: ... - @overload @constmethod def makeChamfer(self, radius1: float, radius2: float, edgeList: List) -> TopoShape: ... - @constmethod def makeThickness(self, faces: List, offset: float, tolerance: float) -> TopoShape: """ @@ -557,7 +561,17 @@ class TopoShape(ComplexGeoData): ... @constmethod - def makeOffsetShape(self, offset: float, tolerance: float, *, inter: bool = False, self_inter: bool = False, offsetMode: int = 0, join: int = 0, fill: bool = False) -> TopoShape: + def makeOffsetShape( + self, + offset: float, + tolerance: float, + *, + inter: bool = False, + self_inter: bool = False, + offsetMode: int = 0, + join: int = 0, + fill: bool = False + ) -> TopoShape: """ Makes an offset shape (3d offsetting). makeOffsetShape(offset, tolerance, [inter=False, self_inter=False, offsetMode=0, join=0, fill=False]) -> Shape @@ -584,7 +598,15 @@ class TopoShape(ComplexGeoData): ... @constmethod - def makeOffset2D(self, offset: float, *, join: int = 0, fill: bool = False, openResult: bool = False, intersection: bool = False) -> TopoShape: + def makeOffset2D( + self, + offset: float, + *, + join: int = 0, + fill: bool = False, + openResult: bool = False, + intersection: bool = False + ) -> TopoShape: """ Makes an offset shape (2d offsetting). makeOffset2D(offset, [join=0, fill=False, openResult=False, intersection=False]) -> Shape @@ -615,8 +637,16 @@ class TopoShape(ComplexGeoData): ... @constmethod - def makeEvolved(self, *, Profile: TopoShape, Join: int, AxeProf: bool, Solid: bool, - ProfOnSpine: bool, Tolerance: float) -> None: + def makeEvolved( + self, + *, + Profile: TopoShape, + Join: int, + AxeProf: bool, + Solid: bool, + ProfOnSpine: bool, + Tolerance: float + ) -> None: """ Profile along the spine """ @@ -751,7 +781,9 @@ class TopoShape(ComplexGeoData): """ ... - def fix(self, working_precision: float, minimum_precision: float, maximum_precision: float) -> bool: + def fix( + self, working_precision: float, minimum_precision: float, maximum_precision: float + ) -> bool: """ Tries to fix a broken shape. fix(working precision, minimum precision, maximum precision) -> bool @@ -803,8 +835,16 @@ class TopoShape(ComplexGeoData): ... @constmethod - def reflectLines(self, ViewDir: Vector, *, ViewPos: Vector = None, UpDir: Vector = None, - EdgeType: str = None, Visible: bool = True, OnShape: bool = False) -> TopoShape: + def reflectLines( + self, + ViewDir: Vector, + *, + ViewPos: Vector = None, + UpDir: Vector = None, + EdgeType: str = None, + Visible: bool = True, + OnShape: bool = False + ) -> TopoShape: """ Build projection or reflect lines of a shape according to a view direction. reflectLines(ViewDir, [ViewPos, UpDir, EdgeType, Visible, OnShape]) -> Shape (Compound of edges) @@ -927,7 +967,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def distToShape(self, shape: TopoShape, tol: float = 1e-7) -> Tuple[float, List[Tuple[Vector, Vector]], List[Tuple]]: + def distToShape( + self, shape: TopoShape, tol: float = 1e-7 + ) -> Tuple[float, List[Tuple[Vector, Vector]], List[Tuple]]: """ Find the minimum distance to another shape. distToShape(shape, tol=1e-7) -> (dist, vectors, infos) @@ -981,7 +1023,12 @@ class TopoShape(ComplexGeoData): """ ... - def mapShapes(self, generated: List[Tuple[TopoShape, TopoShape]], modified: List[Tuple[TopoShape, TopoShape]], op: str = "") -> None: + def mapShapes( + self, + generated: List[Tuple[TopoShape, TopoShape]], + modified: List[Tuple[TopoShape, TopoShape]], + op: str = "", + ) -> None: """ mapShapes(generated, modified, op='') @@ -1039,7 +1086,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def inTolerance(self, valmin: float, valmax: float, ShapeType: str = "Shape") -> List[TopoShape]: + def inTolerance( + self, valmin: float, valmax: float, ShapeType: str = "Shape" + ) -> List[TopoShape]: """ Determines which shapes have a tolerance within a given interval inTolerance(valmin, valmax, [ShapeType=Shape]) -> ShapeList @@ -1095,7 +1144,9 @@ class TopoShape(ComplexGeoData): ... @constmethod - def optimalBoundingBox(self, useTriangulation: bool = True, useShapeTolerance: bool = False) -> BoundBox: + def optimalBoundingBox( + self, useTriangulation: bool = True, useShapeTolerance: bool = False + ) -> BoundBox: """ Get the optimal bounding box optimalBoundingBox([useTriangulation = True, useShapeTolerance = False]) -> bound box @@ -1119,7 +1170,15 @@ class TopoShape(ComplexGeoData): ... @constmethod - def findSubShapesWithSharedVertex(self, shape: TopoShape, *, needName: bool = False, checkGeometry: bool = True, tol: float = 1e-7, atol: float = 1e-12) -> Union[List[Tuple[str, TopoShape]], List[TopoShape]]: + def findSubShapesWithSharedVertex( + self, + shape: TopoShape, + *, + needName: bool = False, + checkGeometry: bool = True, + tol: float = 1e-7, + atol: float = 1e-12 + ) -> Union[List[Tuple[str, TopoShape]], List[TopoShape]]: """ findSubShapesWithSharedVertex(shape, needName=False, checkGeometry=True, tol=1e-7, atol=1e-12) -> Shape diff --git a/src/Mod/Part/App/TopoShapeCache.cpp b/src/Mod/Part/App/TopoShapeCache.cpp index 0def189182..18c7ae66a0 100644 --- a/src/Mod/Part/App/TopoShapeCache.cpp +++ b/src/Mod/Part/App/TopoShapeCache.cpp @@ -116,8 +116,7 @@ std::vector TopoShapeCache::Ancestry::getTopoShapes(const TopoShape& return res; } -TopoDS_Shape TopoShapeCache::Ancestry::stripLocation(const TopoDS_Shape& parent, - const TopoDS_Shape& child) +TopoDS_Shape TopoShapeCache::Ancestry::stripLocation(const TopoDS_Shape& parent, const TopoDS_Shape& child) { if (parent.Location() != owner->location) { owner->location = parent.Location(); @@ -159,8 +158,7 @@ TopoShapeCache::TopoShapeCache(const TopoDS_Shape& tds) : shape(tds.Located(TopLoc_Location())) {} -void TopoShapeCache::insertRelation(const ShapeRelationKey& key, - const QVector& value) +void TopoShapeCache::insertRelation(const ShapeRelationKey& key, const QVector& value) { auto [insertedItr, newKeyInserted] = relations.insert({key, value}); if (newKeyInserted) { @@ -219,10 +217,12 @@ TopoDS_Shape TopoShapeCache::findShape(const TopoDS_Shape& parent, TopAbs_ShapeE return {}; } -TopoDS_Shape TopoShapeCache::findAncestor(const TopoDS_Shape& parent, - const TopoDS_Shape& subShape, - TopAbs_ShapeEnum type, - std::vector* ancestors) +TopoDS_Shape TopoShapeCache::findAncestor( + const TopoDS_Shape& parent, + const TopoDS_Shape& subShape, + TopAbs_ShapeEnum type, + std::vector* ancestors +) { TopoDS_Shape nullShape; if (shape.IsNull() || subShape.IsNull() || type == TopAbs_SHAPE) { diff --git a/src/Mod/Part/App/TopoShapeCache.h b/src/Mod/Part/App/TopoShapeCache.h index df64c576ac..75aff066a2 100644 --- a/src/Mod/Part/App/TopoShapeCache.h +++ b/src/Mod/Part/App/TopoShapeCache.h @@ -128,10 +128,12 @@ public: /// the result. Subsequent calls to this method given unchanged geometry will use the cached /// data rather than re-running MapShapesAndAncestors. /// If ancestors is given, it is cleared and overwritten with the ancestry data. - TopoDS_Shape findAncestor(const TopoDS_Shape& parent, - const TopoDS_Shape& subShape, - TopAbs_ShapeEnum type, - std::vector* ancestors = nullptr); + TopoDS_Shape findAncestor( + const TopoDS_Shape& parent, + const TopoDS_Shape& subShape, + TopAbs_ShapeEnum type, + std::vector* ancestors = nullptr + ); /// Ancestor and children shape caches of all shape types. Note that /// shapeAncestryCache[TopAbs_SHAPE] is also valid and stores the direct children of a diff --git a/src/Mod/Part/App/TopoShapeCompSolid.pyi b/src/Mod/Part/App/TopoShapeCompSolid.pyi index 76f791389e..34a80fee85 100644 --- a/src/Mod/Part/App/TopoShapeCompSolid.pyi +++ b/src/Mod/Part/App/TopoShapeCompSolid.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from TopoShape import TopoShape - @export( Father="TopoShapePy", Name="TopoShapeCompSolidPy", diff --git a/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp b/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp index b8590b6234..da3fc1e6c1 100644 --- a/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp @@ -23,10 +23,10 @@ ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include "OCCError.h" @@ -50,7 +50,7 @@ std::string TopoShapeCompSolidPy::representation() const return str.str(); } -PyObject *TopoShapeCompSolidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* TopoShapeCompSolidPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { return new TopoShapeCompSolidPy(new TopoShape); } @@ -112,7 +112,7 @@ PyObject* TopoShapeCompSolidPy::add(PyObject* args) } } -PyObject *TopoShapeCompSolidPy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeCompSolidPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TopoShapeCompound.pyi b/src/Mod/Part/App/TopoShapeCompound.pyi index 316bcd3058..b78f52c4cb 100644 --- a/src/Mod/Part/App/TopoShapeCompound.pyi +++ b/src/Mod/Part/App/TopoShapeCompound.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export, constmethod from TopoShape import TopoShape - @export( Twin="TopoShape", TwinPointer="TopoShape", @@ -25,7 +24,9 @@ class TopoShapeCompound(TopoShape): ... @constmethod - def connectEdgesToWires(self, Shared: bool = True, Tolerance: float = 1e-7) -> "TopoShapeCompound": + def connectEdgesToWires( + self, Shared: bool = True, Tolerance: float = 1e-7 + ) -> "TopoShapeCompound": """ Build a compound of wires out of the edges of this compound. connectEdgesToWires([Shared = True, Tolerance = 1e-7]) -> Compound diff --git a/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp b/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp index b1bcf996d1..2b51e11de8 100644 --- a/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp @@ -25,14 +25,14 @@ #include "TopoShape.h" -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include "OCCError.h" @@ -53,7 +53,7 @@ std::string TopoShapeCompoundPy::representation() const return str.str(); } -PyObject *TopoShapeCompoundPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* TopoShapeCompoundPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { return new TopoShapeCompoundPy(new TopoShape); } @@ -68,9 +68,10 @@ int TopoShapeCompoundPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O", &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O", &pcObj)) { return -1; + } BRep_Builder builder; TopoDS_Compound Comp; @@ -80,10 +81,11 @@ int TopoShapeCompoundPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast((*it).ptr())-> - getTopoShapePtr()->getShape(); - if (!sh.IsNull()) + const TopoDS_Shape& sh + = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); + if (!sh.IsNull()) { builder.Add(Comp, sh); + } } } } @@ -96,11 +98,12 @@ int TopoShapeCompoundPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } -PyObject* TopoShapeCompoundPy::add(PyObject *args) +PyObject* TopoShapeCompoundPy::add(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &obj)) { return nullptr; + } BRep_Builder builder; TopoDS_Shape comp = getTopoShapePtr()->getShape(); @@ -109,10 +112,10 @@ PyObject* TopoShapeCompoundPy::add(PyObject *args) } try { - const TopoDS_Shape& sh = static_cast(obj)-> - getTopoShapePtr()->getShape(); - if (!sh.IsNull()) + const TopoDS_Shape& sh = static_cast(obj)->getTopoShapePtr()->getShape(); + if (!sh.IsNull()) { builder.Add(comp, sh); + } } catch (Standard_Failure& e) { @@ -125,20 +128,22 @@ PyObject* TopoShapeCompoundPy::add(PyObject *args) Py_Return; } -PyObject* TopoShapeCompoundPy::connectEdgesToWires(PyObject *args) const +PyObject* TopoShapeCompoundPy::connectEdgesToWires(PyObject* args) const { - PyObject *shared=Py_True; + PyObject* shared = Py_True; double tol = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "|O!d",&PyBool_Type,&shared,&tol)) + if (!PyArg_ParseTuple(args, "|O!d", &PyBool_Type, &shared, &tol)) { return nullptr; + } try { const TopoDS_Shape& s = getTopoShapePtr()->getShape(); Handle(TopTools_HSequenceOfShape) hEdges = new TopTools_HSequenceOfShape(); Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); - for (TopExp_Explorer xp(s, TopAbs_EDGE); xp.More(); xp.Next()) + for (TopExp_Explorer xp(s, TopAbs_EDGE); xp.More(); xp.Next()) { hEdges->Append(xp.Current()); + } ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, tol, Base::asBoolean(shared), hWires); @@ -147,7 +152,7 @@ PyObject* TopoShapeCompoundPy::connectEdgesToWires(PyObject *args) const builder.MakeCompound(comp); int len = hWires->Length(); - for(int i=1;i<=len;i++) { + for (int i = 1; i <= len; i++) { builder.Add(comp, hWires->Value(i)); } @@ -161,7 +166,7 @@ PyObject* TopoShapeCompoundPy::connectEdgesToWires(PyObject *args) const } } -PyObject* TopoShapeCompoundPy::setFaces(PyObject *args) +PyObject* TopoShapeCompoundPy::setFaces(PyObject* args) { using Facet = Data::ComplexGeoData::Facet; using Point = Base::Vector3d; @@ -169,7 +174,7 @@ PyObject* TopoShapeCompoundPy::setFaces(PyObject *args) std::vector points; std::vector facets; - PyObject* data{}; + PyObject* data {}; double accuracy = 1.0e-06; // NOLINT if (!PyArg_ParseTuple(args, "O!|d", &PyTuple_Type, &data, &accuracy)) { return nullptr; @@ -221,7 +226,7 @@ PyObject* TopoShapeCompoundPy::setFaces(PyObject *args) Py_Return; } -PyObject *TopoShapeCompoundPy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeCompoundPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TopoShapeEdge.pyi b/src/Mod/Part/App/TopoShapeEdge.pyi index 53d298d101..c9c9cce0f5 100644 --- a/src/Mod/Part/App/TopoShapeEdge.pyi +++ b/src/Mod/Part/App/TopoShapeEdge.pyi @@ -5,7 +5,6 @@ from Vertex import Vertex from TopoShape import TopoShape from typing import Final, Tuple, Dict, List, overload - @export( Twin="TopoShape", TwinPointer="TopoShape", @@ -452,34 +451,27 @@ class TopoShapeEdge(TopoShape): @constmethod @overload - def discretize( - self, Number: int, First: float = ..., Last: float = ... - ) -> List[Vector]: ... - + def discretize(self, Number: int, First: float = ..., Last: float = ...) -> List[Vector]: ... @constmethod @overload def discretize( self, QuasiNumber: int, First: float = ..., Last: float = ... ) -> List[Vector]: ... - @constmethod @overload def discretize( self, Distance: float, First: float = ..., Last: float = ... ) -> List[Vector]: ... - @constmethod @overload def discretize( self, Deflection: float, First: float = ..., Last: float = ... ) -> List[Vector]: ... - @constmethod @overload def discretize( self, QuasiDeflection: float, First: float = ..., Last: float = ... ) -> List[Vector]: ... - @constmethod @overload def discretize( @@ -490,7 +482,6 @@ class TopoShapeEdge(TopoShape): First: float = ..., Last: float = ..., ) -> List[Vector]: ... - @constmethod def discretize(self, **kwargs) -> List[Vector]: """ diff --git a/src/Mod/Part/App/TopoShapeEdgePyImp.cpp b/src/Mod/Part/App/TopoShapeEdgePyImp.cpp index 4407f2bc9d..35772d8435 100644 --- a/src/Mod/Part/App/TopoShapeEdgePyImp.cpp +++ b/src/Mod/Part/App/TopoShapeEdgePyImp.cpp @@ -20,48 +20,48 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -90,14 +90,17 @@ using namespace Part; -namespace { -const TopoDS_Edge& getTopoDSEdge(const TopoShapeEdgePy* theEdge){ +namespace +{ +const TopoDS_Edge& getTopoDSEdge(const TopoShapeEdgePy* theEdge) +{ const TopoDS_Edge& e = TopoDS::Edge(theEdge->getTopoShapePtr()->getShape()); - if (e.IsNull()) + if (e.IsNull()) { throw Py::ValueError("Edge is null"); + } return e; } -} +} // namespace // returns a string which represents the object e.g. when printed in python std::string TopoShapeEdgePy::representation() const @@ -108,7 +111,7 @@ std::string TopoShapeEdgePy::representation() const return str.str(); } -PyObject *TopoShapeEdgePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* TopoShapeEdgePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of TopoShapeEdgePy and the Twin object return new TopoShapeEdgePy(new TopoShape); @@ -135,10 +138,12 @@ int TopoShapeEdgePy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } - if (first == std::numeric_limits::max()) + if (first == std::numeric_limits::max()) { first = curve->FirstParameter(); - if (last == std::numeric_limits::max()) + } + if (last == std::numeric_limits::max()) { last = curve->LastParameter(); + } try { BRepBuilderAPI_MakeEdge mkEdge(curve, first, last); @@ -166,8 +171,14 @@ int TopoShapeEdgePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!O!", &(Part::TopoShapeVertexPy::Type), &pcObj, - &(Part::TopoShapeVertexPy::Type), &pcObj2)) { + if (PyArg_ParseTuple( + args, + "O!O!", + &(Part::TopoShapeVertexPy::Type), + &pcObj, + &(Part::TopoShapeVertexPy::Type), + &pcObj2 + )) { TopoShape* shape1 = static_cast(pcObj)->getTopoShapePtr(); TopoShape* shape2 = static_cast(pcObj2)->getTopoShapePtr(); const TopoDS_Vertex& v1 = TopoDS::Vertex(shape1->getShape()); @@ -191,12 +202,13 @@ int TopoShapeEdgePy::PyInit(PyObject* args, PyObject* /*kwd*/) // ====== Methods ====================================================================== -PyObject* TopoShapeEdgePy::getParameterByLength(PyObject *args) const +PyObject* TopoShapeEdgePy::getParameterByLength(PyObject* args) const { double u; - double t=Precision::Confusion(); - if (!PyArg_ParseTuple(args, "d|d",&u,&t)) + double t = Precision::Confusion(); + if (!PyArg_ParseTuple(args, "d|d", &u, &t)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); @@ -205,15 +217,16 @@ PyObject* TopoShapeEdgePy::getParameterByLength(PyObject *args) const double first = BRepLProp_CurveTool::FirstParameter(adapt); double last = BRepLProp_CurveTool::LastParameter(adapt); if (!Precision::IsInfinite(first) && !Precision::IsInfinite(last)) { - double length = GCPnts_AbscissaPoint::Length(adapt,t); + double length = GCPnts_AbscissaPoint::Length(adapt, t); if (u < -length || u > length) { PyErr_SetString(PyExc_ValueError, "value out of range"); return nullptr; } - if (u < 0) - u = length+u; - GCPnts_AbscissaPoint abscissaPoint(t,adapt,u,first); + if (u < 0) { + u = length + u; + } + GCPnts_AbscissaPoint abscissaPoint(t, adapt, u, first); double parm = abscissaPoint.Parameter(); return PyFloat_FromDouble(parm); } @@ -221,27 +234,29 @@ PyObject* TopoShapeEdgePy::getParameterByLength(PyObject *args) const return PyFloat_FromDouble(u); } -PyObject* TopoShapeEdgePy::valueAt(PyObject *args) const +PyObject* TopoShapeEdgePy::valueAt(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); // Check now the orientation of the edge to make // sure that we get the right wanted point! - BRepLProp_CLProps prop(adapt,u,0,Precision::Confusion()); + BRepLProp_CLProps prop(adapt, u, 0, Precision::Confusion()); const gp_Pnt& V = prop.Value(); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } -PyObject* TopoShapeEdgePy::parameters(PyObject *args) const +PyObject* TopoShapeEdgePy::parameters(PyObject* args) const { PyObject* pyface = nullptr; - if (!PyArg_ParseTuple(args, "|O!", &(TopoShapeFacePy::Type), &pyface)) + if (!PyArg_ParseTuple(args, "|O!", &(TopoShapeFacePy::Type), &pyface)) { return nullptr; + } auto e = getTopoDSEdge(this); TopLoc_Location aLoc; @@ -253,7 +268,7 @@ PyObject* TopoShapeEdgePy::parameters(PyObject *args) const } const TColStd_Array1OfReal& aNodes = aPoly->Parameters(); - for (int i=aNodes.Lower(); i<=aNodes.Upper(); i++) { + for (int i = aNodes.Lower(); i <= aNodes.Upper(); i++) { list.append(Py::Float(aNodes(i))); } @@ -265,9 +280,10 @@ PyObject* TopoShapeEdgePy::parameters(PyObject *args) const TopTools_IndexedDataMapOfShapeListOfShape edge2Face; TopExp::MapShapesAndAncestors(TopoDS::Face(face), TopAbs_EDGE, TopAbs_FACE, edge2Face); if (edge2Face.Contains(e)) { - Handle(Poly_Triangulation) aPolyTria = BRep_Tool::Triangulation(TopoDS::Face(face),aLoc); + Handle(Poly_Triangulation) aPolyTria = BRep_Tool::Triangulation(TopoDS::Face(face), aLoc); if (!aPolyTria.IsNull()) { - Handle(Poly_PolygonOnTriangulation) aPoly = BRep_Tool::PolygonOnTriangulation(e, aPolyTria, aLoc); + Handle(Poly_PolygonOnTriangulation) aPoly + = BRep_Tool::PolygonOnTriangulation(e, aPolyTria, aLoc); if (!aPoly.IsNull()) { if (!aPoly->HasParameters()) { Py::List list; @@ -277,7 +293,7 @@ PyObject* TopoShapeEdgePy::parameters(PyObject *args) const Handle(TColStd_HArray1OfReal) aNodes = aPoly->Parameters(); if (!aNodes.IsNull()) { Py::List list; - for (int i=aNodes->Lower(); i<=aNodes->Upper(); i++) { + for (int i = aNodes->Lower(); i <= aNodes->Upper(); i++) { list.append(Py::Float(aNodes->Value(i))); } @@ -296,13 +312,13 @@ PyObject* TopoShapeEdgePy::parameters(PyObject *args) const return nullptr; } -PyObject* TopoShapeEdgePy::parameterAt(PyObject *args) const +PyObject* TopoShapeEdgePy::parameterAt(PyObject* args) const { PyObject* pnt; - PyObject* face=nullptr; - if (!PyArg_ParseTuple(args, "O!|O!",&TopoShapeVertexPy::Type,&pnt, - &TopoShapeFacePy::Type,&face)) + PyObject* face = nullptr; + if (!PyArg_ParseTuple(args, "O!|O!", &TopoShapeVertexPy::Type, &pnt, &TopoShapeFacePy::Type, &face)) { return nullptr; + } try { const TopoDS_Shape& v = static_cast(pnt)->getTopoShapePtr()->getShape(); @@ -325,20 +341,21 @@ PyObject* TopoShapeEdgePy::parameterAt(PyObject *args) const } } -PyObject* TopoShapeEdgePy::tangentAt(PyObject *args) const +PyObject* TopoShapeEdgePy::tangentAt(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); - BRepLProp_CLProps prop(adapt,u,2,Precision::Confusion()); + BRepLProp_CLProps prop(adapt, u, 2, Precision::Confusion()); if (prop.IsTangentDefined()) { gp_Dir dir; prop.Tangent(dir); - return new Base::VectorPy(new Base::Vector3d(dir.X(),dir.Y(),dir.Z())); + return new Base::VectorPy(new Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } else { PyErr_SetString(PyExc_NotImplementedError, "Tangent not defined at this position!"); @@ -346,20 +363,21 @@ PyObject* TopoShapeEdgePy::tangentAt(PyObject *args) const } } -PyObject* TopoShapeEdgePy::normalAt(PyObject *args) const +PyObject* TopoShapeEdgePy::normalAt(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); try { - BRepLProp_CLProps prop(adapt,u,2,Precision::Confusion()); - gp_Dir V ; + BRepLProp_CLProps prop(adapt, u, 2, Precision::Confusion()); + gp_Dir V; prop.Normal(V); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } catch (Standard_Failure& e) { @@ -368,17 +386,18 @@ PyObject* TopoShapeEdgePy::normalAt(PyObject *args) const } } -PyObject* TopoShapeEdgePy::curvatureAt(PyObject *args) const +PyObject* TopoShapeEdgePy::curvatureAt(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); try { - BRepLProp_CLProps prop(adapt,u,2,Precision::Confusion()); + BRepLProp_CLProps prop(adapt, u, 2, Precision::Confusion()); double C = prop.Curvature(); return Py::new_reference_to(Py::Float(C)); } @@ -389,20 +408,21 @@ PyObject* TopoShapeEdgePy::curvatureAt(PyObject *args) const } } -PyObject* TopoShapeEdgePy::centerOfCurvatureAt(PyObject *args) const +PyObject* TopoShapeEdgePy::centerOfCurvatureAt(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); try { - BRepLProp_CLProps prop(adapt,u,2,Precision::Confusion()); - gp_Pnt V ; + BRepLProp_CLProps prop(adapt, u, 2, Precision::Confusion()); + gp_Pnt V; prop.CentreOfCurvature(V); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } catch (Standard_Failure& e) { @@ -411,19 +431,20 @@ PyObject* TopoShapeEdgePy::centerOfCurvatureAt(PyObject *args) const } } -PyObject* TopoShapeEdgePy::derivative1At(PyObject *args) const +PyObject* TopoShapeEdgePy::derivative1At(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); try { - BRepLProp_CLProps prop(adapt,u,1,Precision::Confusion()); + BRepLProp_CLProps prop(adapt, u, 1, Precision::Confusion()); const gp_Vec& V = prop.D1(); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } catch (Standard_Failure& e) { @@ -432,19 +453,20 @@ PyObject* TopoShapeEdgePy::derivative1At(PyObject *args) const } } -PyObject* TopoShapeEdgePy::derivative2At(PyObject *args) const +PyObject* TopoShapeEdgePy::derivative2At(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); try { - BRepLProp_CLProps prop(adapt,u,2,Precision::Confusion()); + BRepLProp_CLProps prop(adapt, u, 2, Precision::Confusion()); const gp_Vec& V = prop.D2(); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } catch (Standard_Failure& e) { @@ -453,19 +475,20 @@ PyObject* TopoShapeEdgePy::derivative2At(PyObject *args) const } } -PyObject* TopoShapeEdgePy::derivative3At(PyObject *args) const +PyObject* TopoShapeEdgePy::derivative3At(PyObject* args) const { double u; - if (!PyArg_ParseTuple(args, "d",&u)) + if (!PyArg_ParseTuple(args, "d", &u)) { return nullptr; + } auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); try { - BRepLProp_CLProps prop(adapt,u,3,Precision::Confusion()); + BRepLProp_CLProps prop(adapt, u, 3, Precision::Confusion()); const gp_Vec& V = prop.D3(); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } catch (Standard_Failure& e) { @@ -474,7 +497,7 @@ PyObject* TopoShapeEdgePy::derivative3At(PyObject *args) const } } -PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const +PyObject* TopoShapeEdgePy::discretize(PyObject* args, PyObject* kwds) const { try { BRepAdaptor_Curve adapt(TopoDS::Edge(getTopoShapePtr()->getShape())); @@ -503,16 +526,37 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const } else { // use Number kwds - static const std::array kwds_numPoints{"Number", "First", "Last", nullptr}; + static const std::array kwds_numPoints {"Number", "First", "Last", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_numPoints, &numPoints, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_numPoints, + &numPoints, + &first, + &last + )) { uniformAbscissaPoints = true; } else { // use Abscissa kwds - static const std::array kwds_Distance{"Distance", "First", "Last", nullptr}; + static const std::array kwds_Distance { + "Distance", + "First", + "Last", + nullptr + }; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Distance, &distance, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Distance, + &distance, + &first, + &last + )) { uniformAbscissaDistance = true; } } @@ -520,17 +564,19 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const if (uniformAbscissaPoints || uniformAbscissaDistance) { GCPnts_UniformAbscissa discretizer; - if (uniformAbscissaPoints) - discretizer.Initialize (adapt, numPoints, first, last); - else - discretizer.Initialize (adapt, distance, first, last); + if (uniformAbscissaPoints) { + discretizer.Initialize(adapt, numPoints, first, last); + } + else { + discretizer.Initialize(adapt, distance, first, last); + } - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = adapt.Value (discretizer.Parameter (i)); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = adapt.Value(discretizer.Parameter(i)); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -542,17 +588,25 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const } // use Deflection kwds - static const std::array kwds_Deflection{"Deflection", "First", "Last", nullptr}; + static const std::array kwds_Deflection {"Deflection", "First", "Last", nullptr}; PyErr_Clear(); double deflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Deflection, &deflection, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Deflection, + &deflection, + &first, + &last + )) { GCPnts_UniformDeflection discretizer(adapt, deflection, first, last); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -564,21 +618,30 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const } // use TangentialDeflection kwds - static const std::array kwds_TangentialDeflection {"Angular", "Curvature", "First", "Last", - "Minimum", nullptr}; + static const std::array + kwds_TangentialDeflection {"Angular", "Curvature", "First", "Last", "Minimum", nullptr}; PyErr_Clear(); double angular; double curvature; int minimumPoints = 2; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "dd|ddi", kwds_TangentialDeflection, &angular, &curvature, - &first, &last, &minimumPoints)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "dd|ddi", + kwds_TangentialDeflection, + &angular, + &curvature, + &first, + &last, + &minimumPoints + )) { GCPnts_TangentialDeflection discretizer(adapt, first, last, angular, curvature, minimumPoints); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -590,18 +653,30 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiNumber kwds - static const std::array kwds_QuasiNumPoints{"QuasiNumber", "First", "Last", nullptr}; + static const std::array kwds_QuasiNumPoints { + "QuasiNumber", + "First", + "Last", + nullptr + }; PyErr_Clear(); int quasiNumPoints; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_QuasiNumPoints, &quasiNumPoints, &first, - &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_QuasiNumPoints, + &quasiNumPoints, + &first, + &last + )) { GCPnts_QuasiUniformAbscissa discretizer(adapt, quasiNumPoints, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = adapt.Value (discretizer.Parameter (i)); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = adapt.Value(discretizer.Parameter(i)); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -613,18 +688,30 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiDeflection kwds - static const std::array kwds_QuasiDeflection{"QuasiDeflection", "First", "Last", nullptr}; + static const std::array kwds_QuasiDeflection { + "QuasiDeflection", + "First", + "Last", + nullptr + }; PyErr_Clear(); double quasiDeflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_QuasiDeflection, - &quasiDeflection, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_QuasiDeflection, + &quasiDeflection, + &first, + &last + )) { GCPnts_QuasiUniformDeflection discretizer(adapt, quasiDeflection, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -640,19 +727,20 @@ PyObject* TopoShapeEdgePy::discretize(PyObject *args, PyObject *kwds) const return nullptr; } - PyErr_SetString(PartExceptionOCCError,"Wrong arguments"); + PyErr_SetString(PartExceptionOCCError, "Wrong arguments"); return nullptr; } -PyObject* TopoShapeEdgePy::countNodes(PyObject *args) const +PyObject* TopoShapeEdgePy::countNodes(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } const TopoDS_Shape& shape = this->getTopoShapePtr()->getShape(); TopoDS_Edge aEdge = TopoDS::Edge(shape); TopLoc_Location aLoc; - const Handle(Poly_Polygon3D)& aPoly = BRep_Tool::Polygon3D(aEdge, aLoc); + const Handle(Poly_Polygon3D) & aPoly = BRep_Tool::Polygon3D(aEdge, aLoc); int count = 0; if (!aPoly.IsNull()) { count = aPoly->NbNodes(); @@ -661,11 +749,12 @@ PyObject* TopoShapeEdgePy::countNodes(PyObject *args) const return Py::new_reference_to(Py::Long(count)); } -PyObject* TopoShapeEdgePy::split(PyObject *args) const +PyObject* TopoShapeEdgePy::split(PyObject* args) const { PyObject* float_or_list; - if (!PyArg_ParseTuple(args, "O", &float_or_list)) + if (!PyArg_ParseTuple(args, "O", &float_or_list)) { return nullptr; + } try { BRepAdaptor_Curve adapt(TopoDS::Edge(getTopoShapePtr()->getShape())); @@ -717,7 +806,7 @@ PyObject* TopoShapeEdgePy::split(PyObject *args) const std::vector::iterator end = par.end() - 1; for (std::vector::iterator it = par.begin(); it != end; ++it) { BRepBuilderAPI_MakeEdge mke(c, it[0], it[1]); - e = mke.Edge(); + e = mke.Edge(); builder.Transfert(edge, e); builder.Range(e, it[0], it[1], false); mkWire.Add(e); @@ -732,15 +821,18 @@ PyObject* TopoShapeEdgePy::split(PyObject *args) const } } -PyObject* TopoShapeEdgePy::isSeam(PyObject *args) const +PyObject* TopoShapeEdgePy::isSeam(PyObject* args) const { PyObject* face; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeFacePy::Type, &face)) { return nullptr; + } try { const TopoDS_Edge& e = TopoDS::Edge(this->getTopoShapePtr()->getShape()); - const TopoDS_Face& f = TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()); + const TopoDS_Face& f = TopoDS::Face( + static_cast(face)->getTopoShapePtr()->getShape() + ); ShapeAnalysis_Edge sa; Standard_Boolean ok = sa.IsSeam(e, f); @@ -753,21 +845,23 @@ PyObject* TopoShapeEdgePy::isSeam(PyObject *args) const } } -PyObject* TopoShapeEdgePy::firstVertex(PyObject *args) const +PyObject* TopoShapeEdgePy::firstVertex(PyObject* args) const { PyObject* orient = Py_False; - if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &orient)) + if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &orient)) { return nullptr; + } auto e = getTopoDSEdge(this); TopoDS_Vertex v = TopExp::FirstVertex(e, Base::asBoolean(orient)); return new TopoShapeVertexPy(new TopoShape(v)); } -PyObject* TopoShapeEdgePy::lastVertex(PyObject *args) const +PyObject* TopoShapeEdgePy::lastVertex(PyObject* args) const { PyObject* orient = Py_False; - if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &orient)) + if (!PyArg_ParseTuple(args, "|O!", &PyBool_Type, &orient)) { return nullptr; + } auto e = getTopoDSEdge(this); TopoDS_Vertex v = TopExp::LastVertex(e, Base::asBoolean(orient)); return new TopoShapeVertexPy(new TopoShape(v)); @@ -780,27 +874,27 @@ Py::String TopoShapeEdgePy::getContinuity() const BRepAdaptor_Curve adapt(TopoDS::Edge(getTopoShapePtr()->getShape())); std::string cont; switch (adapt.Continuity()) { - case GeomAbs_C0: - cont = "C0"; - break; - case GeomAbs_G1: - cont = "G1"; - break; - case GeomAbs_C1: - cont = "C1"; - break; - case GeomAbs_G2: - cont = "G2"; - break; - case GeomAbs_C2: - cont = "C2"; - break; - case GeomAbs_C3: - cont = "C3"; - break; - case GeomAbs_CN: - cont = "CN"; - break; + case GeomAbs_C0: + cont = "C0"; + break; + case GeomAbs_G1: + cont = "G1"; + break; + case GeomAbs_C1: + cont = "C1"; + break; + case GeomAbs_G2: + cont = "G2"; + break; + case GeomAbs_C2: + cont = "C2"; + break; + case GeomAbs_C3: + cont = "C3"; + break; + case GeomAbs_CN: + cont = "CN"; + break; } return Py::String(cont); @@ -834,69 +928,55 @@ Py::Object TopoShapeEdgePy::getCurve() const auto e = getTopoDSEdge(this); BRepAdaptor_Curve adapt(e); Base::PyObjectBase* curve = nullptr; - switch(adapt.GetType()) - { - case GeomAbs_Line: - { + switch (adapt.GetType()) { + case GeomAbs_Line: { GeomLine* line = new GeomLine(); - Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast - (line->handle()); + Handle(Geom_Line) this_curv = Handle(Geom_Line)::DownCast(line->handle()); this_curv->SetLin(adapt.Line()); curve = new LinePy(line); break; } - case GeomAbs_Circle: - { + case GeomAbs_Circle: { GeomCircle* circle = new GeomCircle(); - Handle(Geom_Circle) this_curv = Handle(Geom_Circle)::DownCast - (circle->handle()); + Handle(Geom_Circle) this_curv = Handle(Geom_Circle)::DownCast(circle->handle()); this_curv->SetCirc(adapt.Circle()); - //Standard_Real dd = adapt.FirstParameter(); - //Standard_Real ee = adapt.LastParameter(); + // Standard_Real dd = adapt.FirstParameter(); + // Standard_Real ee = adapt.LastParameter(); curve = new CirclePy(circle); break; } - case GeomAbs_Ellipse: - { + case GeomAbs_Ellipse: { GeomEllipse* elips = new GeomEllipse(); - Handle(Geom_Ellipse) this_curv = Handle(Geom_Ellipse)::DownCast - (elips->handle()); + Handle(Geom_Ellipse) this_curv = Handle(Geom_Ellipse)::DownCast(elips->handle()); this_curv->SetElips(adapt.Ellipse()); curve = new EllipsePy(elips); break; } - case GeomAbs_Hyperbola: - { + case GeomAbs_Hyperbola: { GeomHyperbola* hypr = new GeomHyperbola(); - Handle(Geom_Hyperbola) this_curv = Handle(Geom_Hyperbola)::DownCast - (hypr->handle()); + Handle(Geom_Hyperbola) this_curv = Handle(Geom_Hyperbola)::DownCast(hypr->handle()); this_curv->SetHypr(adapt.Hyperbola()); curve = new HyperbolaPy(hypr); break; } - case GeomAbs_Parabola: - { + case GeomAbs_Parabola: { GeomParabola* parab = new GeomParabola(); - Handle(Geom_Parabola) this_curv = Handle(Geom_Parabola)::DownCast - (parab->handle()); + Handle(Geom_Parabola) this_curv = Handle(Geom_Parabola)::DownCast(parab->handle()); this_curv->SetParab(adapt.Parabola()); curve = new ParabolaPy(parab); break; } - case GeomAbs_BezierCurve: - { + case GeomAbs_BezierCurve: { GeomBezierCurve* bezier = new GeomBezierCurve(adapt.Bezier()); curve = new BezierCurvePy(bezier); break; } - case GeomAbs_BSplineCurve: - { + case GeomAbs_BSplineCurve: { GeomBSplineCurve* bspline = new GeomBSplineCurve(adapt.BSpline()); curve = new BSplineCurvePy(bspline); break; } - case GeomAbs_OffsetCurve: - { + case GeomAbs_OffsetCurve: { Standard_Real first, last; Handle(Geom_Curve) c = BRep_Tool::Curve(e, first, last); Handle(Geom_OffsetCurve) off = Handle(Geom_OffsetCurve)::DownCast(c); @@ -909,8 +989,8 @@ Py::Object TopoShapeEdgePy::getCurve() const throw Py::RuntimeError("Failed to convert to offset curve"); } } - case GeomAbs_OtherCurve: - break; + case GeomAbs_OtherCurve: + break; } if (curve) { @@ -963,7 +1043,7 @@ Py::Object TopoShapeEdgePy::getCenterOfMass() const GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); gp_Pnt c = props.CentreOfMass(); - return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); + return Py::Vector(Base::Vector3d(c.X(), c.Y(), c.Z())); } Py::Object TopoShapeEdgePy::getMatrixOfInertia() const @@ -972,9 +1052,9 @@ Py::Object TopoShapeEdgePy::getMatrixOfInertia() const BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); gp_Mat m = props.MatrixOfInertia(); Base::Matrix4D mat; - for (int i=0; i<3; i++) { - for (int j=0; j<3; j++) { - mat[i][j] = m(i+1,j+1); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + mat[i][j] = m(i + 1, j + 1); } } return Py::Matrix(mat); @@ -984,8 +1064,8 @@ Py::Object TopoShapeEdgePy::getStaticMoments() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); - Standard_Real lx,ly,lz; - props.StaticMoments(lx,ly,lz); + Standard_Real lx, ly, lz; + props.StaticMoments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); @@ -1002,34 +1082,41 @@ Py::Dict TopoShapeEdgePy::getPrincipalProperties() const Py::Dict dict; dict.setItem("SymmetryAxis", Py::Boolean(pprops.HasSymmetryAxis() ? true : false)); dict.setItem("SymmetryPoint", Py::Boolean(pprops.HasSymmetryPoint() ? true : false)); - Standard_Real lx,ly,lz; - pprops.Moments(lx,ly,lz); + Standard_Real lx, ly, lz; + pprops.Moments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); tuple.setItem(2, Py::Float(lz)); - dict.setItem("Moments",tuple); - dict.setItem("FirstAxisOfInertia",Py::Vector(Base::convertTo - (pprops.FirstAxisOfInertia()))); - dict.setItem("SecondAxisOfInertia",Py::Vector(Base::convertTo - (pprops.SecondAxisOfInertia()))); - dict.setItem("ThirdAxisOfInertia",Py::Vector(Base::convertTo - (pprops.ThirdAxisOfInertia()))); + dict.setItem("Moments", tuple); + dict.setItem( + "FirstAxisOfInertia", + Py::Vector(Base::convertTo(pprops.FirstAxisOfInertia())) + ); + dict.setItem( + "SecondAxisOfInertia", + Py::Vector(Base::convertTo(pprops.SecondAxisOfInertia())) + ); + dict.setItem( + "ThirdAxisOfInertia", + Py::Vector(Base::convertTo(pprops.ThirdAxisOfInertia())) + ); - Standard_Real Rxx,Ryy,Rzz; - pprops.RadiusOfGyration(Rxx,Ryy,Rzz); + Standard_Real Rxx, Ryy, Rzz; + pprops.RadiusOfGyration(Rxx, Ryy, Rzz); Py::Tuple rog(3); rog.setItem(0, Py::Float(Rxx)); rog.setItem(1, Py::Float(Ryy)); rog.setItem(2, Py::Float(Rzz)); - dict.setItem("RadiusOfGyration",rog); + dict.setItem("RadiusOfGyration", rog); return dict; } Py::Boolean TopoShapeEdgePy::getClosed() const { - if (getTopoShapePtr()->getShape().IsNull()) + if (getTopoShapePtr()->getShape().IsNull()) { throw Py::RuntimeError("Cannot determine the 'Closed'' flag of an empty shape"); + } Standard_Boolean ok = BRep_Tool::IsClosed(getTopoShapePtr()->getShape()); return Py::Boolean(ok ? true : false); } @@ -1040,11 +1127,12 @@ Py::Boolean TopoShapeEdgePy::getDegenerated() const return Py::Boolean(ok ? true : false); } -PyObject* TopoShapeEdgePy::curveOnSurface(PyObject *args) const +PyObject* TopoShapeEdgePy::curveOnSurface(PyObject* args) const { int idx; - if (!PyArg_ParseTuple(args, "i", &idx)) + if (!PyArg_ParseTuple(args, "i", &idx)) { return nullptr; + } try { TopoDS_Edge edge = TopoDS::Edge(getTopoShapePtr()->getShape()); @@ -1053,15 +1141,18 @@ PyObject* TopoShapeEdgePy::curveOnSurface(PyObject *args) const TopLoc_Location loc; Standard_Real first, last; - BRep_Tool::CurveOnSurface(edge, curve, surf, loc, first, last, idx+1); - if (curve.IsNull()) + BRep_Tool::CurveOnSurface(edge, curve, surf, loc, first, last, idx + 1); + if (curve.IsNull()) { Py_Return; + } std::unique_ptr geo2d(makeFromCurve2d(curve)); - if (!geo2d) + if (!geo2d) { Py_Return; + } std::unique_ptr geosurf(makeFromSurface(surf)); - if (!geosurf) + if (!geosurf) { Py_Return; + } gp_Trsf trsf = loc.Transformation(); gp_XYZ pos = trsf.TranslationPart(); @@ -1085,7 +1176,7 @@ PyObject* TopoShapeEdgePy::curveOnSurface(PyObject *args) const } } -PyObject *TopoShapeEdgePy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeEdgePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TopoShapeExpansion.cpp b/src/Mod/Part/App/TopoShapeExpansion.cpp index dbcfafc6a4..491ef21418 100644 --- a/src/Mod/Part/App/TopoShapeExpansion.cpp +++ b/src/Mod/Part/App/TopoShapeExpansion.cpp @@ -32,8 +32,8 @@ #include #include #if OCC_VERSION_HEX < 0x070600 -#include -#include +# include +# include #endif #include @@ -174,9 +174,11 @@ void TopoShape::flushElementMap() const TopoShape parent(this->Tag, this->Hasher, this->_parentCache->shape); parent._cache = _parentCache; parent.flushElementMap(); - TopoShape self(this->Tag, - this->Hasher, - this->_Shape.Located(this->_subLocation * this->_cache->subLocation)); + TopoShape self( + this->Tag, + this->Hasher, + this->_Shape.Located(this->_subLocation * this->_cache->subLocation) + ); self._cache = _cache; self.mapSubElement(parent); this->_parentCache.reset(); @@ -318,11 +320,13 @@ TopoDS_Shape TopoShape::findShape(TopAbs_ShapeEnum type, int idx) const return _cache->findShape(_Shape, type, idx); } -std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& subshape, - std::vector* names, - Data::SearchOptions options, - double tol, - double atol) const +std::vector TopoShape::findSubShapesWithSharedVertex( + const TopoShape& subshape, + std::vector* names, + Data::SearchOptions options, + double tol, + double atol +) const { bool checkGeometry = options.testFlag(Data::SearchOption::CheckGeometry); bool singleSearch = options.testFlag(Data::SearchOption::SingleResult); @@ -342,8 +346,7 @@ std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& return; } auto first = subshape.getSubTopoShape(childType, 1); - for (const auto& child : - findSubShapesWithSharedVertex(first, nullptr, options, tol, atol)) { + for (const auto& child : findSubShapesWithSharedVertex(first, nullptr, options, tol, atol)) { for (int idx : findAncestors(child.getShape(), shapeType)) { auto shape = getSubTopoShape(shapeType, idx); if (shape.countSubShapes(childType) != count) { @@ -352,11 +355,13 @@ std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& bool found = true; for (unsigned long i = 2; i < count; ++i) { if (shape - .findSubShapesWithSharedVertex(subshape.getSubTopoShape(childType, i), - nullptr, - options, - tol, - atol) + .findSubShapesWithSharedVertex( + subshape.getSubTopoShape(childType, i), + nullptr, + options, + tol, + atol + ) .empty()) { found = false; break; @@ -392,11 +397,13 @@ std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& // special treatment of single sub-shape compound, that is, search // its extracting the compound if (countSubShapes(TopAbs_SHAPE) == 1) { - return findSubShapesWithSharedVertex(subshape.getSubTopoShape(TopAbs_SHAPE, 1), - names, - options, - tol, - atol); + return findSubShapesWithSharedVertex( + subshape.getSubTopoShape(TopAbs_SHAPE, 1), + names, + options, + tol, + atol + ); } else if (unsigned long count = countSubShapes(TopAbs_SHAPE)) { // For multi-sub-shape compound, only search for compound with the same @@ -476,8 +483,8 @@ std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& return res; } if (shapeType == TopAbs_EDGE) { - isLine = (geom->isDerivedFrom() - || geom->isDerivedFrom()); + isLine + = (geom->isDerivedFrom() || geom->isDerivedFrom()); } else { isPlane = geom->isDerivedFrom(); @@ -493,8 +500,7 @@ std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& // For lines, don't compare geometry, just check the // vertices below instead, because the exact same edge // may have different geometrical representation. - if (!g2->isDerivedFrom() - && !g2->isDerivedFrom()) { + if (!g2->isDerivedFrom() && !g2->isDerivedFrom()) { return false; } } @@ -628,10 +634,8 @@ std::vector TopoShape::findSubShapesWithSharedVertex(const TopoShape& if (isLine2) { if (g1->isDerivedFrom() || g1->isDerivedFrom()) { - auto p1 = - BRep_Tool::Pnt(TopExp::FirstVertex(TopoDS::Edge(e1))); - auto p2 = - BRep_Tool::Pnt(TopExp::LastVertex(TopoDS::Edge(e1))); + auto p1 = BRep_Tool::Pnt(TopExp::FirstVertex(TopoDS::Edge(e1))); + auto p2 = BRep_Tool::Pnt(TopExp::LastVertex(TopoDS::Edge(e1))); if ((p1.SquareDistance(pt1) <= tol2 && p2.SquareDistance(pt2) <= tol2) || (p1.SquareDistance(pt2) <= tol2 @@ -694,8 +698,10 @@ std::vector TopoShape::findAncestors(const TopoDS_Shape& subshape, TopAbs_S return ret; } -std::vector TopoShape::findAncestorsShapes(const TopoDS_Shape& subshape, - TopAbs_ShapeEnum type) const +std::vector TopoShape::findAncestorsShapes( + const TopoDS_Shape& subshape, + TopAbs_ShapeEnum type +) const { initCache(); std::vector shapes; @@ -736,9 +742,11 @@ bool TopoShape::canMapElement(const TopoShape& other) const namespace { -size_t checkSubshapeCount(const TopoShape& topoShape1, - const TopoShape& topoShape2, - TopAbs_ShapeEnum elementType) +size_t checkSubshapeCount( + const TopoShape& topoShape1, + const TopoShape& topoShape2, + TopAbs_ShapeEnum elementType +) { auto count = topoShape1.countSubShapes(elementType); auto other = topoShape2.countSubShapes(elementType); @@ -753,11 +761,13 @@ size_t checkSubshapeCount(const TopoShape& topoShape1, } // namespace -void TopoShape::setupChild(Data::ElementMap::MappedChildElements& child, - TopAbs_ShapeEnum elementType, - const TopoShape& topoShape, - size_t shapeCount, - const char* op) +void TopoShape::setupChild( + Data::ElementMap::MappedChildElements& child, + TopAbs_ShapeEnum elementType, + const TopoShape& topoShape, + size_t shapeCount, + const char* op +) { child.indexedName = Data::IndexedName::fromConst(TopoShape::shapeName(elementType).c_str(), 1); child.offset = 0; @@ -799,12 +809,14 @@ void TopoShape::copyElementMap(const TopoShape& topoShape, const char* op) // TODO: Refactor mapSubElementTypeForShape to reduce complexity -void TopoShape::mapSubElementTypeForShape(const TopoShape& other, - TopAbs_ShapeEnum type, - const char* op, - int count, - bool forward, - bool& warned) +void TopoShape::mapSubElementTypeForShape( + const TopoShape& other, + TopAbs_ShapeEnum type, + const char* op, + int count, + bool forward, + bool& warned +) { auto& shapeMap = _cache->getAncestry(type); auto& otherMap = other._cache->getAncestry(type); @@ -830,8 +842,7 @@ void TopoShape::mapSubElementTypeForShape(const TopoShape& other, } Data::IndexedName element = Data::IndexedName::fromConst(shapeType, index); for (auto& mappedName : - other.getElementMappedNames(Data::IndexedName::fromConst(shapeType, innerCounter), - true)) { + other.getElementMappedNames(Data::IndexedName::fromConst(shapeType, innerCounter), true)) { auto& name = mappedName.first; auto& sids = mappedName.second; if (!sids.empty()) { @@ -990,8 +1001,11 @@ void TopoShape::mapSubElementsTo(std::vector& shapes, const char* op) } } -std::vector -TopoShape::createChildMap(size_t count, const std::vector& shapes, const char* op) +std::vector TopoShape::createChildMap( + size_t count, + const std::vector& shapes, + const char* op +) { std::vector children; children.reserve(count * (size_t)3); @@ -1008,8 +1022,8 @@ TopoShape::createChildMap(size_t count, const std::vector& shapes, co } children.emplace_back(); auto& child = children.back(); - child.indexedName = - Data::IndexedName::fromConst(TopoShape::shapeName(topAbsType).c_str(), 1); + child.indexedName + = Data::IndexedName::fromConst(TopoShape::shapeName(topAbsType).c_str(), 1); child.offset = static_cast(offset); offset += subShapeCount; child.count = static_cast(subShapeCount); @@ -1073,8 +1087,7 @@ void TopoShape::mapSubElement(const std::vector& shapes, const char* } children.emplace_back(); auto& child = children.back(); - child.indexedName = - Data::IndexedName::fromConst(shapeName(types[i]).c_str(), 1); + child.indexedName = Data::IndexedName::fromConst(shapeName(types[i]).c_str(), 1); child.offset = offset; offset += count; child.count = count; @@ -1095,8 +1108,7 @@ void TopoShape::mapSubElement(const std::vector& shapes, const char* } } -std::vector TopoShape::getSubShapes(TopAbs_ShapeEnum type, - TopAbs_ShapeEnum avoid) const +std::vector TopoShape::getSubShapes(TopAbs_ShapeEnum type, TopAbs_ShapeEnum avoid) const { std::vector ret; if (isNull()) { @@ -1118,8 +1130,7 @@ std::vector TopoShape::getSubShapes(TopAbs_ShapeEnum type, return ret; } -std::vector TopoShape::getSubTopoShapes(TopAbs_ShapeEnum type, - TopAbs_ShapeEnum avoid) const +std::vector TopoShape::getSubTopoShapes(TopAbs_ShapeEnum type, TopAbs_ShapeEnum avoid) const { if (isNull()) { return std::vector(); @@ -1332,13 +1343,15 @@ const std::string& lowerPostfix() } // TODO: Refactor checkForParallelOrCoplanar to reduce complexity -void checkForParallelOrCoplanar(const TopoDS_Shape& newShape, - const ShapeInfo& newInfo, - std::vector& newShapes, - const gp_Pln& pln, - int& parallelFace, - int& coplanarFace, - int& checkParallel) +void checkForParallelOrCoplanar( + const TopoDS_Shape& newShape, + const ShapeInfo& newInfo, + std::vector& newShapes, + const gp_Pln& pln, + int& parallelFace, + int& coplanarFace, + int& checkParallel +) { for (TopExp_Explorer xp(newShape, newInfo.type); xp.More(); xp.Next()) { newShapes.push_back(xp.Current()); @@ -1387,10 +1400,12 @@ void checkForParallelOrCoplanar(const TopoDS_Shape& newShape, } // TODO: Refactor makeShapeWithElementMap to reduce complexity -TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, - const Mapper& mapper, - const std::vector& shapes, - const char* op) +TopoShape& TopoShape::makeShapeWithElementMap( + const TopoDS_Shape& shape, + const Mapper& mapper, + const std::vector& shapes, + const char* op +) { setShape(shape); if (shape.IsNull()) { @@ -1462,17 +1477,19 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, Data::ElementIDRefs sids; NameKey key( info.type, - incomingShape.getMappedName(Data::IndexedName::fromConst(info.shapetype, i), - true, - &sids)); + incomingShape + .getMappedName(Data::IndexedName::fromConst(info.shapetype, i), true, &sids) + ); int newShapeCounter = 0; for (auto& newShape : mapper.modified(otherElement)) { ++newShapeCounter; if (newShape.ShapeType() >= TopAbs_SHAPE) { // NOLINTNEXTLINE - FC_ERR("unknown modified shape type " << newShape.ShapeType() << " from " - << info.shapetype << i); + FC_ERR( + "unknown modified shape type " << newShape.ShapeType() << " from " + << info.shapetype << i + ); continue; } auto& newInfo = *infoMap.at(newShape.ShapeType()); @@ -1482,9 +1499,10 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, // level shape type just like generated shape below. // Maybe we shall do the same for name construction. // NOLINTNEXTLINE - FC_WARN("modified shape type " << shapeName(newShape.ShapeType()) - << " mismatch with " << info.shapetype - << i); + FC_WARN( + "modified shape type " << shapeName(newShape.ShapeType()) + << " mismatch with " << info.shapetype << i + ); } continue; } @@ -1495,14 +1513,16 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, // final shape. There may be incomingShape cases there. if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { // NOLINTNEXTLINE - FC_WARN("Cannot find " << op << " modified " << newInfo.shapetype - << " from " << info.shapetype << i); + FC_WARN( + "Cannot find " << op << " modified " << newInfo.shapetype + << " from " << info.shapetype << i + ); } continue; } - Data::IndexedName element = - Data::IndexedName::fromConst(newInfo.shapetype, newShapeIndex); + Data::IndexedName element + = Data::IndexedName::fromConst(newInfo.shapetype, newShapeIndex); if (getMappedName(element)) { continue; } @@ -1523,8 +1543,10 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, for (auto& newShape : mapper.generated(otherElement)) { if (newShape.ShapeType() >= TopAbs_SHAPE) { // NOLINTNEXTLINE - FC_ERR("unknown generated shape type " << newShape.ShapeType() << " from " - << info.shapetype << i); + FC_ERR( + "unknown generated shape type " << newShape.ShapeType() << " from " + << info.shapetype << i + ); continue; } @@ -1561,13 +1583,15 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, checkParallel = 1; } } - checkForParallelOrCoplanar(newShape, - newInfo, - newShapes, - pln, - parallelFace, - coplanarFace, - checkParallel); + checkForParallelOrCoplanar( + newShape, + newInfo, + newShapes, + pln, + parallelFace, + coplanarFace, + checkParallel + ); } key.shapetype += shapeOffset; for (auto& workingShape : newShapes) { @@ -1576,14 +1600,16 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, if (workingShapeIndex == 0) { if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { // NOLINTNEXTLINE - FC_WARN("Cannot find " << op << " generated " << newInfo.shapetype - << " from " << info.shapetype << i); + FC_WARN( + "Cannot find " << op << " generated " << newInfo.shapetype + << " from " << info.shapetype << i + ); } continue; } - Data::IndexedName element = - Data::IndexedName::fromConst(newInfo.shapetype, workingShapeIndex); + Data::IndexedName element + = Data::IndexedName::fromConst(newInfo.shapetype, workingShapeIndex); auto mapped = getMappedName(element); if (mapped) { continue; @@ -1651,8 +1677,8 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, continue; } - int name_type = - first_info.index > 0 ? 1 : 2; // index>0 means modified, or else generated + int name_type = first_info.index > 0 ? 1 + : 2; // index>0 means modified, or else generated Data::MappedName first_name = first_key.name; Data::ElementIDRefs sids(first_info.sids); @@ -1703,13 +1729,15 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, } Data::MappedName other_name = other_key.name; - ensureElementMap()->encodeElementName(*other_info.shapetype, - other_name, - ss2, - &sids, - Tag, - nullptr, - other_key.tag); + ensureElementMap()->encodeElementName( + *other_info.shapetype, + other_name, + ss2, + &sids, + Tag, + nullptr, + other_key.tag + ); ss << other_name; if ((name_type == 1 && other_info.index < 0) || (name_type == 2 && other_info.index > 0)) { @@ -1775,8 +1803,7 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, // multiple higher elements, e.g. same edge in multiple faces. for (size_t infoIndex = infos.size() - 1; infoIndex != 0; --infoIndex) { - std::map> + std::map> names; auto& info = *infos.at(infoIndex); auto& next = *infos.at(infoIndex - 1); @@ -1821,8 +1848,8 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, ss.str(""); int elementIndex = next.find(submap(submapIndex)); assert(elementIndex); - Data::IndexedName indexedName = - Data::IndexedName::fromConst(next.shapetype, elementIndex); + Data::IndexedName indexedName + = Data::IndexedName::fromConst(next.shapetype, elementIndex); if (getMappedName(indexedName)) { continue; } @@ -1848,7 +1875,7 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, ensureElementMap()->encodeElementName(indexedName[0], newName, ss, &sids, Tag, op); elementMap()->setElementName(indexedName, newName, Tag, &sids); - } + } } } @@ -1876,8 +1903,8 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, for (; xp.More(); xp.Next()) { int previousElementIndex = prev.find(xp.Current()); assert(previousElementIndex); - Data::IndexedName prevElement = - Data::IndexedName::fromConst(prev.shapetype, previousElementIndex); + Data::IndexedName prevElement + = Data::IndexedName::fromConst(prev.shapetype, previousElementIndex); if (!delayed && (newNames.count(prevElement) != 0U)) { names.clear(); break; @@ -1900,9 +1927,11 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, // The seam edge will appear twice, which is normal. We // only warn if the mapped element names are different. // NOLINTNEXTLINE - FC_WARN("lower element " << prevElement << " and " << res.first->second - << " has duplicated name " << name << " for " - << info.shapetype << i); + FC_WARN( + "lower element " << prevElement << " and " << res.first->second + << " has duplicated name " << name << " for " + << info.shapetype << i + ); } } if (names.empty()) { @@ -1958,9 +1987,7 @@ TopoShape& TopoShape::makeShapeWithElementMap(const TopoDS_Shape& shape, namespace { -void addShapesToBuilder(const std::vector& shapes, - BRep_Builder& builder, - TopoDS_Compound& comp) +void addShapesToBuilder(const std::vector& shapes, BRep_Builder& builder, TopoDS_Compound& comp) { int count = 0; for (auto& topoShape : shapes) { @@ -2051,8 +2078,7 @@ TopoShape TopoShape::getSubTopoShape(TopAbs_ShapeEnum type, int idx, bool silent auto& shapeMap = _cache->getAncestry(type); if (idx > shapeMap.count()) { if (!silent) { - FC_THROWM(Base::IndexError, - "Shape index " << idx << " out of bound " << shapeMap.count()); + FC_THROWM(Base::IndexError, "Shape index " << idx << " out of bound " << shapeMap.count()); } return TopoShape(); } @@ -2081,14 +2107,16 @@ std::string TopoShape::getElementMapVersion() const return _getElementMapVersion() + Data::ComplexGeoData::getElementMapVersion(); } -TopoShape& TopoShape::makeElementEvolve(const TopoShape& spine, - const TopoShape& profile, - JoinType join, - CoordinateSystem axeProf, - MakeSolid solid, - Spine profOnSpine, - double tol, - const char* op) +TopoShape& TopoShape::makeElementEvolve( + const TopoShape& spine, + const TopoShape& profile, + JoinType join, + CoordinateSystem axeProf, + MakeSolid solid, + Spine profOnSpine, + double tol, + const char* op +) { if (!op) { op = Part::OpCodes::Evolve; @@ -2118,8 +2146,7 @@ TopoShape& TopoShape::makeElementEvolve(const TopoShape& spine, spineShape = spine.getSubShape(TopAbs_WIRE, 1); } else if (spine.countSubShapes(TopAbs_EDGE) > 0) { - spineShape = - BRepBuilderAPI_MakeWire(TopoDS::Edge(spine.getSubShape(TopAbs_EDGE, 1))).Wire(); + spineShape = BRepBuilderAPI_MakeWire(TopoDS::Edge(spine.getSubShape(TopAbs_EDGE, 1))).Wire(); } if (spineShape.IsNull() || !BRepBuilderAPI_FindPlane(spineShape).Found()) { FC_THROWM(Base::CADKernelError, "Expect the spine to be a planar wire or face"); @@ -2130,14 +2157,16 @@ TopoShape& TopoShape::makeElementEvolve(const TopoShape& spine, profileShape = profile.getSubShape(TopAbs_WIRE, 1); } else if (profile.countSubShapes(TopAbs_EDGE) > 0) { - profileShape = - BRepBuilderAPI_MakeWire(TopoDS::Edge(profile.getSubShape(TopAbs_EDGE, 1))).Wire(); + profileShape + = BRepBuilderAPI_MakeWire(TopoDS::Edge(profile.getSubShape(TopAbs_EDGE, 1))).Wire(); } if (profileShape.IsNull() || !BRepBuilderAPI_FindPlane(profileShape).Found()) { if (profileShape.IsNull() || profile.countSubShapes(TopAbs_EDGE) > 1 || !profile.getSubTopoShape(TopAbs_EDGE, 1).isLinearEdge()) { - FC_THROWM(Base::CADKernelError, - "Expect the the profile to be a planar wire or a face or a line"); + FC_THROWM( + Base::CADKernelError, + "Expect the the profile to be a planar wire or a face or a line" + ); } } if (spineShape.ShapeType() == TopAbs_FACE) { @@ -2148,7 +2177,8 @@ TopoShape& TopoShape::makeElementEvolve(const TopoShape& spine, axeProf == CoordinateSystem::global ? Standard_True : Standard_False, solid == MakeSolid::makeSolid ? Standard_True : Standard_False, profOnSpine == Spine::on ? Standard_True : Standard_False, - tol); + tol + ); return makeElementShape(maker, {spine, profile}, op); } else { @@ -2159,14 +2189,17 @@ TopoShape& TopoShape::makeElementEvolve(const TopoShape& spine, axeProf == CoordinateSystem::global ? Standard_True : Standard_False, solid == MakeSolid::makeSolid ? Standard_True : Standard_False, profOnSpine == Spine::on ? Standard_True : Standard_False, - tol); + tol + ); return makeElementShape(maker, {spine, profile}, op); } } -TopoShape& TopoShape::makeElementRuledSurface(const std::vector& shapes, - int orientation, - const char* op) +TopoShape& TopoShape::makeElementRuledSurface( + const std::vector& shapes, + int orientation, + const char* op +) { if (!op) { op = Part::OpCodes::RuledSurface; @@ -2311,9 +2344,11 @@ TopoShape& TopoShape::makeElementRuledSurface(const std::vector& shap return makeShapeWithElementMap(res.getShape(), Mapper(), edges, op); } -TopoShape& TopoShape::makeElementCompound(const std::vector& shapes, - const char* op, - SingleShapeCompoundCreationPolicy policy) +TopoShape& TopoShape::makeElementCompound( + const std::vector& shapes, + const char* op, + SingleShapeCompoundCreationPolicy policy +) { if (policy == SingleShapeCompoundCreationPolicy::returnShape && shapes.size() == 1) { *this = shapes[0]; @@ -2336,8 +2371,7 @@ TopoShape& TopoShape::makeElementCompound(const std::vector& shapes, return *this; } -static std::vector prepareProfiles(const std::vector& shapes, - size_t offset = 0) +static std::vector prepareProfiles(const std::vector& shapes, size_t offset = 0) { std::vector ret; for (size_t i = offset; i < shapes.size(); ++i) { @@ -2361,8 +2395,7 @@ static std::vector prepareProfiles(const std::vector& shap continue; } - FC_THROWM(Base::CADKernelError, - "Profile shape is not a single vertex, edge, wire nor face."); + FC_THROWM(Base::CADKernelError, "Profile shape is not a single vertex, edge, wire nor face."); } if (ret.empty()) { FC_THROWM(Base::CADKernelError, "No profile"); @@ -2370,14 +2403,16 @@ static std::vector prepareProfiles(const std::vector& shap return ret; } -TopoShape& TopoShape::makeElementPipeShell(const std::vector& shapes, - const MakeSolid make_solid, - const Standard_Boolean isFrenet, - TransitionMode transition, - const char* op, - double tol3d, - double tolBound, - double tolAngular) +TopoShape& TopoShape::makeElementPipeShell( + const std::vector& shapes, + const MakeSolid make_solid, + const Standard_Boolean isFrenet, + TransitionMode transition, + const char* op, + double tol3d, + double tolBound, + double tolAngular +) { if (!op) { op = Part::OpCodes::PipeShell; @@ -2445,28 +2480,32 @@ TopoShape& TopoShape::makeElementPipeShell(const std::vector& shapes, return makeElementShape(mkPipeShell, shapes, op); } -TopoShape& TopoShape::makeElementOffset(const TopoShape& shape, - double offset, - double tol, - bool intersection, - bool selfInter, - short offsetMode, - JoinType join, - FillType fill, - const char* op) +TopoShape& TopoShape::makeElementOffset( + const TopoShape& shape, + double offset, + double tol, + bool intersection, + bool selfInter, + short offsetMode, + JoinType join, + FillType fill, + const char* op +) { if (!op) { op = Part::OpCodes::Offset; } BRepOffsetAPI_MakeOffsetShape mkOffset; - mkOffset.PerformByJoin(shape.getShape(), - offset, - tol, - BRepOffset_Mode(offsetMode), - intersection ? Standard_True : Standard_False, - selfInter ? Standard_True : Standard_False, - GeomAbs_JoinType(join)); + mkOffset.PerformByJoin( + shape.getShape(), + offset, + tol, + BRepOffset_Mode(offsetMode), + intersection ? Standard_True : Standard_False, + selfInter ? Standard_True : Standard_False, + GeomAbs_JoinType(join) + ); if (!mkOffset.IsDone()) { FC_THROWM(Base::CADKernelError, "BRepOffsetAPI_MakeOffsetShape not done"); @@ -2498,9 +2537,7 @@ TopoShape& TopoShape::makeElementOffset(const TopoShape& shape, BRep_Builder builder; std::vector shapes; for (int index = 1; index <= freeCheck.NbClosedFreeBounds(); ++index) { - TopoShape originalWire(shape.Tag, - shape.Hasher, - freeCheck.ClosedFreeBound(index)->FreeBound()); + TopoShape originalWire(shape.Tag, shape.Hasher, freeCheck.ClosedFreeBound(index)->FreeBound()); originalWire.mapSubElement(shape); const BRepAlgo_Image& img = mkOffset.MakeOffset().OffsetEdgesFromShapes(); @@ -2587,15 +2624,16 @@ TopoShape& TopoShape::makeElementOffset(const TopoShape& shape, return *this; } -TopoShape& TopoShape::makeElementOffsetFace(const TopoShape& shape, - double offset, - double innerOffset, - JoinType joinType, - JoinType innerJoinType, - const char* op) +TopoShape& TopoShape::makeElementOffsetFace( + const TopoShape& shape, + double offset, + double innerOffset, + JoinType joinType, + JoinType innerJoinType, + const char* op +) { - if (std::abs(innerOffset) < Precision::Confusion() - && std::abs(offset) < Precision::Confusion()) { + if (std::abs(innerOffset) < Precision::Confusion() && std::abs(offset) < Precision::Confusion()) { *this = shape; return *this; } @@ -2612,13 +2650,15 @@ TopoShape& TopoShape::makeElementOffsetFace(const TopoShape& shape, std::vector wires; TopoShape outerWire = face.splitWires(&wires, ReorientForward); if (wires.empty()) { - res.push_back(makeElementOffset2D(face, - offset, - joinType, - FillType::noFill, - OpenResult::noOpenResult, - false, - op)); + res.push_back(makeElementOffset2D( + face, + offset, + joinType, + FillType::noFill, + OpenResult::noOpenResult, + false, + op + )); continue; } if (outerWire.isNull()) { @@ -2626,44 +2666,48 @@ TopoShape& TopoShape::makeElementOffsetFace(const TopoShape& shape, } if (std::abs(offset) > Precision::Confusion()) { - outerWire = outerWire.makeElementOffset2D(offset, - joinType, - FillType::noFill, - OpenResult::noOpenResult, - false, - op); + outerWire = outerWire.makeElementOffset2D( + offset, + joinType, + FillType::noFill, + OpenResult::noOpenResult, + false, + op + ); } if (std::abs(innerOffset) > Precision::Confusion()) { TopoShape innerWires(0, Hasher); - innerWires.makeElementCompound(wires, - "", - SingleShapeCompoundCreationPolicy::returnShape); - innerWires = innerWires.makeElementOffset2D(innerOffset, - innerJoinType, - FillType::noFill, - OpenResult::noOpenResult, - true, - op); + innerWires.makeElementCompound(wires, "", SingleShapeCompoundCreationPolicy::returnShape); + innerWires = innerWires.makeElementOffset2D( + innerOffset, + innerJoinType, + FillType::noFill, + OpenResult::noOpenResult, + true, + op + ); wires = innerWires.getSubTopoShapes(TopAbs_WIRE); } wires.push_back(outerWire); gp_Pln pln; - res.push_back(TopoShape(0, Hasher).makeElementFace(wires, - nullptr, - nullptr, - face.findPlane(pln) ? &pln : nullptr)); + res.push_back( + TopoShape(0, Hasher) + .makeElementFace(wires, nullptr, nullptr, face.findPlane(pln) ? &pln : nullptr) + ); } return makeElementCompound(res, "", SingleShapeCompoundCreationPolicy::returnShape); } -TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, - double offset, - JoinType joinType, - FillType fill, - OpenResult allowOpenResult, - bool intersection, - const char* op) +TopoShape& TopoShape::makeElementOffset2D( + const TopoShape& shape, + double offset, + JoinType joinType, + FillType fill, + OpenResult allowOpenResult, + bool intersection, + const char* op +) { if (!op) { op = Part::OpCodes::Offset2D; @@ -2697,13 +2741,11 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, if (shape.getShape().ShapeType() == TopAbs_COMPOUND) { if (!intersection) { // simply recursively process the children, independently - for(TopoDS_Iterator it(shape.getShape()); it.More() ; it.Next()) { - shapesToReturn.push_back(TopoShape(it.Value()).makeElementOffset2D(offset, - joinType, - fill, - allowOpenResult, - intersection, - op)); + for (TopoDS_Iterator it(shape.getShape()); it.More(); it.Next()) { + shapesToReturn.push_back( + TopoShape(it.Value()) + .makeElementOffset2D(offset, joinType, fill, allowOpenResult, intersection, op) + ); outputPolicy = SingleShapeCompoundCreationPolicy::forceCompound; } } @@ -2713,14 +2755,10 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, for (auto& s : shape.getSubTopoShapes()) { if (s.getShape().ShapeType() == TopAbs_COMPOUND) { // recursively process subcompounds - shapesToReturn.push_back(TopoShape(Tag, Hasher) - .makeElementOffset2D(s, - offset, - joinType, - fill, - allowOpenResult, - intersection, - op)); + shapesToReturn.push_back( + TopoShape(Tag, Hasher) + .makeElementOffset2D(s, offset, joinType, fill, allowOpenResult, intersection, op) + ); outputPolicy = SingleShapeCompoundCreationPolicy::forceCompound; } else { @@ -2755,22 +2793,24 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, haveWires = true; break; case TopAbs_FACE: { - std::ranges::copy(s.getSubTopoShapes(TopAbs_WIRE), - std::back_inserter(sourceWires)); + std::ranges::copy(s.getSubTopoShapes(TopAbs_WIRE), std::back_inserter(sourceWires)); haveFaces = true; } break; default: - FC_THROWM(Base::TypeError, - "makeOffset2D: input shape is not an edge, wire or face or compound " - "of those."); + FC_THROWM( + Base::TypeError, + "makeOffset2D: input shape is not an edge, wire or face or compound " + "of those." + ); break; } } if (haveWires && haveFaces) { FC_THROWM( Base::TypeError, - "makeOffset2D: collective offset of a mix of wires and faces is not supported"); + "makeOffset2D: collective offset of a mix of wires and faces is not supported" + ); } if (haveFaces) { allowOpenResult = OpenResult::noOpenResult; @@ -2779,9 +2819,7 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, // find plane. gp_Pln workingPlane; if (!TopoShape() - .makeElementCompound(sourceWires, - "", - SingleShapeCompoundCreationPolicy::returnShape) + .makeElementCompound(sourceWires, "", SingleShapeCompoundCreationPolicy::returnShape) .findPlane(workingPlane)) { FC_THROWM(Base::CADKernelError, "makeOffset2D: wires are nonplanar or noncoplanar"); } @@ -2789,8 +2827,10 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, // do the offset.. TopoShape offsetShape; if (fabs(offset) > Precision::Confusion()) { - BRepOffsetAPI_MakeOffsetFix mkOffset(GeomAbs_JoinType(joinType), - allowOpenResult == OpenResult::allowOpenResult); + BRepOffsetAPI_MakeOffsetFix mkOffset( + GeomAbs_JoinType(joinType), + allowOpenResult == OpenResult::allowOpenResult + ); for (auto& w : sourceWires) { mkOffset.AddWire(TopoDS::Wire(w.getShape())); } @@ -2804,8 +2844,10 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, throw; } catch (...) { - FC_THROWM(Base::CADKernelError, - "BRepOffsetAPI_MakeOffset has crashed! (Unknown exception caught)"); + FC_THROWM( + Base::CADKernelError, + "BRepOffsetAPI_MakeOffset has crashed! (Unknown exception caught)" + ); } if (mkOffset.Shape().IsNull()) { FC_THROWM(NullShapeException, "makeOffset2D: result of offsetting is null!"); @@ -2817,9 +2859,11 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, } else { offsetShape = TopoShape(Tag, Hasher) - .makeElementCompound(sourceWires, - 0, - SingleShapeCompoundCreationPolicy::returnShape); + .makeElementCompound( + sourceWires, + 0, + SingleShapeCompoundCreationPolicy::returnShape + ); } std::vector offsetWires; @@ -2833,9 +2877,8 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, std::vector wiresForMakingFaces; if (fill == FillType::noFill) { if (haveFaces) { - wiresForMakingFaces.insert(wiresForMakingFaces.end(), - offsetWires.begin(), - offsetWires.end()); + wiresForMakingFaces + .insert(wiresForMakingFaces.end(), offsetWires.begin(), offsetWires.end()); } else { shapesToReturn.insert(shapesToReturn.end(), offsetWires.begin(), offsetWires.end()); @@ -2844,8 +2887,7 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, else { // fill offset if (fabs(offset) < Precision::Confusion()) { - FC_THROWM(Base::ValueError, - "makeOffset2D: offset distance is zero. Can't fill offset."); + FC_THROWM(Base::ValueError, "makeOffset2D: offset distance is zero. Can't fill offset."); } // filling offset. There are three major cases to consider: @@ -2880,9 +2922,8 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, } } - wiresForMakingFaces.insert(wiresForMakingFaces.end(), - closedWires.begin(), - closedWires.end()); + wiresForMakingFaces + .insert(wiresForMakingFaces.end(), closedWires.begin(), closedWires.end()); if (allowOpenResult == OpenResult::noOpenResult || openWires.size() == 0) { // just ignore all open wires } @@ -2892,9 +2933,11 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, // for now, only support offsetting one open wire -> there should be exactly two // open wires for connecting if (openWires.size() != 2) { - FC_THROWM(Base::CADKernelError, - "makeOffset2D: collective offset with filling of multiple wires is " - "not supported yet."); + FC_THROWM( + Base::CADKernelError, + "makeOffset2D: collective offset with filling of multiple wires is " + "not supported yet." + ); } TopoShape openWire1 = openWires.front(); @@ -2904,13 +2947,15 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, BRepTools_WireExplorer xp; xp.Init(TopoDS::Wire(openWire1.getShape())); TopoDS_Vertex v1 = xp.CurrentVertex(); - for (; xp.More(); xp.Next()) {}; + for (; xp.More(); xp.Next()) { + }; TopoDS_Vertex v2 = xp.CurrentVertex(); // find open vertices xp.Init(TopoDS::Wire(openWire2.getShape())); TopoDS_Vertex v3 = xp.CurrentVertex(); - for (; xp.More(); xp.Next()) {}; + for (; xp.More(); xp.Next()) { + }; TopoDS_Vertex v4 = xp.CurrentVertex(); // check @@ -2941,15 +2986,15 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, v3.Reverse(); v4.Reverse(); } - else if ((fabs(gp_Vec(BRep_Tool::Pnt(v2), BRep_Tool::Pnt(v4)).Magnitude() - - fabs(offset)) + else if ((fabs(gp_Vec(BRep_Tool::Pnt(v2), BRep_Tool::Pnt(v4)).Magnitude() - fabs(offset)) <= BRep_Tool::Tolerance(v2) + BRep_Tool::Tolerance(v4))) { // orientation is as expected, nothing to do } else { FC_THROWM( Base::CADKernelError, - "makeOffset2D: fill offset: failed to establish open vertex relationship."); + "makeOffset2D: fill offset: failed to establish open vertex relationship." + ); } // now directions of open wires are aligned. Finally. make new wire! @@ -2975,7 +3020,8 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, #endif wiresForMakingFaces.push_back( - TopoShape(Tag, Hasher).makeElementShape(mkWire, openWires, op)); + TopoShape(Tag, Hasher).makeElementShape(mkWire, openWires, op) + ); } } @@ -2990,15 +3036,17 @@ TopoShape& TopoShape::makeElementOffset2D(const TopoShape& shape, return makeElementCompound(shapesToReturn, op, outputPolicy); } -TopoShape& TopoShape::makeElementThickSolid(const TopoShape& shape, - const std::vector& faces, - double offset, - double tol, - bool intersection, - bool selfInter, - short offsetMode, - JoinType join, - const char* op) +TopoShape& TopoShape::makeElementThickSolid( + const TopoShape& shape, + const std::vector& faces, + double offset, + double tol, + bool intersection, + bool selfInter, + short offsetMode, + JoinType join, + const char* op +) { if (!op) { op = Part::OpCodes::Thicken; @@ -3037,33 +3085,39 @@ TopoShape& TopoShape::makeElementThickSolid(const TopoShape& shape, remFace.Append(face.getShape()); } BRepOffsetAPI_MakeThickSolid mkThick; - mkThick.MakeThickSolidByJoin(shape.getShape(), - remFace, - offset, - tol, - BRepOffset_Mode(offsetMode), - intersection ? Standard_True : Standard_False, - selfInter ? Standard_True : Standard_False, - GeomAbs_JoinType(join)); + mkThick.MakeThickSolidByJoin( + shape.getShape(), + remFace, + offset, + tol, + BRepOffset_Mode(offsetMode), + intersection ? Standard_True : Standard_False, + selfInter ? Standard_True : Standard_False, + GeomAbs_JoinType(join) + ); return makeElementShape(mkThick, shape, op); } -TopoShape& TopoShape::makeElementWires(const TopoShape& shape, - const char* op, - double tol, - ConnectionPolicy policy, - TopoShapeMap* output) +TopoShape& TopoShape::makeElementWires( + const TopoShape& shape, + const char* op, + double tol, + ConnectionPolicy policy, + TopoShapeMap* output +) { - return makeElementWires(std::vector{shape}, op , tol, policy, output); + return makeElementWires(std::vector {shape}, op, tol, policy, output); } -TopoShape& TopoShape::makeElementWires(const std::vector& shapes, - const char* op, - double tol, - ConnectionPolicy policy, - TopoShapeMap* output) +TopoShape& TopoShape::makeElementWires( + const std::vector& shapes, + const char* op, + double tol, + ConnectionPolicy policy, + TopoShapeMap* output +) { if (!op) { op = Part::OpCodes::Wire; @@ -3078,8 +3132,8 @@ TopoShape& TopoShape::makeElementWires(const std::vector& shapes, // resulting edges. Handle(TopTools_HSequenceOfShape) hEdges = new TopTools_HSequenceOfShape(); Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); - for (const auto &shape : shapes) { - for (const auto &edge : shape.getSubShapes(TopAbs_EDGE)) { + for (const auto& shape : shapes) { + for (const auto& edge : shape.getSubShapes(TopAbs_EDGE)) { hEdges->Append(edge); } } @@ -3094,7 +3148,7 @@ TopoShape& TopoShape::makeElementWires(const std::vector& shapes, std::vector wires; for (int i = 1; i <= hWires->Length(); i++) { auto wire = hWires->Value(i); - wires.emplace_back(Tag,Hasher,wire); + wires.emplace_back(Tag, Hasher, wire); wires.back().mapSubElement(shapes, op); } return makeElementCompound(wires, "", SingleShapeCompoundCreationPolicy::returnShape); @@ -3103,8 +3157,8 @@ TopoShape& TopoShape::makeElementWires(const std::vector& shapes, std::vector wires; std::list edgeList; - for (const auto &shape : shapes) { - for(const auto &e : shape.getSubTopoShapes(TopAbs_EDGE)) { + for (const auto& shape : shapes) { + for (const auto& e : shape.getSubTopoShapes(TopAbs_EDGE)) { edgeList.emplace_back(e); } } @@ -3189,13 +3243,13 @@ struct EdgePoints } }; -} +} // namespace TopoShape TopoShape::reverseEdge(const TopoShape& edge) { Standard_Real first = NAN; Standard_Real last = NAN; - const Handle(Geom_Curve)& curve = BRep_Tool::Curve(TopoDS::Edge(edge.getShape()), first, last); + const Handle(Geom_Curve) & curve = BRep_Tool::Curve(TopoDS::Edge(edge.getShape()), first, last); first = curve->ReversedParameter(first); last = curve->ReversedParameter(last); TopoShape res(BRepBuilderAPI_MakeEdge(curve->Reversed(), last, first)); @@ -3264,8 +3318,7 @@ std::deque TopoShape::sortEdges(std::list& edges, bool kee } if (keepOrder && sorted.size() == 1) { - if (pEI->v2.SquareDistance(first) <= tol3d - || pEI->v1.SquareDistance(first) <= tol3d) { + if (pEI->v2.SquareDistance(first) <= tol3d || pEI->v1.SquareDistance(first) <= tol3d) { sorted[0] = reverseEdge(sorted[0]); std::swap(first, last); } @@ -3314,10 +3367,12 @@ std::deque TopoShape::sortEdges(std::list& edges, bool kee return sorted; } -TopoShape& TopoShape::makeElementOrderedWires(const std::vector& shapes, - const char* op, - double tol, - TopoShapeMap* output) +TopoShape& TopoShape::makeElementOrderedWires( + const std::vector& shapes, + const char* op, + double tol, + TopoShapeMap* output +) { if (!op) { op = Part::OpCodes::Wire; @@ -3329,8 +3384,8 @@ TopoShape& TopoShape::makeElementOrderedWires(const std::vector& shap std::vector wires; std::list edgeList; - auto shape = - TopoShape().makeElementCompound(shapes, "", SingleShapeCompoundCreationPolicy::returnShape); + auto shape + = TopoShape().makeElementCompound(shapes, "", SingleShapeCompoundCreationPolicy::returnShape); for (auto& edge : shape.getSubTopoShapes(TopAbs_EDGE)) { edgeList.push_back(edge); } @@ -3355,11 +3410,13 @@ TopoShape& TopoShape::makeElementOrderedWires(const std::vector& shap return makeElementCompound(wires, nullptr, SingleShapeCompoundCreationPolicy::returnShape); } -bool TopoShape::_makeElementTransform(const TopoShape& shape, - const Base::Matrix4D& mat, - const char* op, - CheckScale checkScale, - CopyType copy) +bool TopoShape::_makeElementTransform( + const TopoShape& shape, + const Base::Matrix4D& mat, + const char* op, + CheckScale checkScale, + CopyType copy +) { if (checkScale == CheckScale::checkScale) { auto scaleType = mat.hasScale(); @@ -3372,10 +3429,12 @@ bool TopoShape::_makeElementTransform(const TopoShape& shape, return false; } -TopoShape& TopoShape::makeElementTransform(const TopoShape& shape, - const gp_Trsf& trsf, - const char* op, - CopyType copy) +TopoShape& TopoShape::makeElementTransform( + const TopoShape& shape, + const gp_Trsf& trsf, + const char* op, + CopyType copy +) { if (copy == CopyType::noCopy) { // OCCT checks the ScaleFactor against gp::Resolution() which is DBL_MIN!!! @@ -3417,10 +3476,12 @@ TopoShape& TopoShape::makeElementTransform(const TopoShape& shape, return *this; } -TopoShape& TopoShape::makeElementGTransform(const TopoShape& shape, - const Base::Matrix4D& mat, - const char* op, - CopyType copy) +TopoShape& TopoShape::makeElementGTransform( + const TopoShape& shape, + const Base::Matrix4D& mat, + const char* op, + CopyType copy +) { if (shape.isNull()) { FC_THROWM(NullShapeException, "Null input shape"); @@ -3459,8 +3520,7 @@ TopoShape& TopoShape::makeElementGTransform(const TopoShape& shape, return *this; } -TopoShape& -TopoShape::makeElementCopy(const TopoShape& shape, const char* op, bool copyGeom, bool copyMesh) +TopoShape& TopoShape::makeElementCopy(const TopoShape& shape, const char* op, bool copyGeom, bool copyMesh) { if (shape.isNull()) { return *this; @@ -3574,9 +3634,11 @@ struct MapperPrism: MapperMaker std::unordered_set edgeSet; TopoShape bottom; - bottom.makeElementCompound(shapes, - nullptr, - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + bottom.makeElementCompound( + shapes, + nullptr, + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); TopoShape shape(maker.Shape()); for (auto& vertex : bottom.getSubShapes(TopAbs_VERTEX)) { for (auto& e : shape.findAncestorsShapes(vertex, TopAbs_EDGE)) { @@ -3659,23 +3721,27 @@ struct MapperPrism: MapperMaker } }; -TopoShape& TopoShape::makeElementFilledFace(const std::vector& _shapes, - const BRepFillingParams& params, - const char* op) +TopoShape& TopoShape::makeElementFilledFace( + const std::vector& _shapes, + const BRepFillingParams& params, + const char* op +) { if (!op) { op = Part::OpCodes::FilledFace; } - BRepOffsetAPI_MakeFilling maker(params.degree, - params.ptsoncurve, - params.numiter, - params.anisotropy, - params.tol2d, - params.tol3d, - params.tolG1, - params.tolG2, - params.maxdeg, - params.maxseg); + BRepOffsetAPI_MakeFilling maker( + params.degree, + params.ptsoncurve, + params.numiter, + params.anisotropy, + params.tol2d, + params.tol3d, + params.tolG1, + params.tolG2, + params.maxdeg, + params.maxseg + ); if (!params.surface.isNull() && params.surface.getShape().ShapeType() == TopAbs_FACE) { maker.LoadInitSurface(TopoDS::Face(params.surface.getShape())); @@ -3750,18 +3816,15 @@ TopoShape& TopoShape::makeElementFilledFace(const std::vector& _shape if (params.boundary_end - 1 != params.boundary_begin || shapes[params.boundary_begin].shapeType() != TopAbs_WIRE) { std::vector edges; - edges.insert(edges.end(), - shapes.begin() + params.boundary_begin, - shapes.begin() + params.boundary_end); + edges.insert( + edges.end(), + shapes.begin() + params.boundary_begin, + shapes.begin() + params.boundary_end + ); wires = TopoShape(0, Hasher) - .makeElementWires(edges, - "", - 0.0, - ConnectionPolicy::requireSharedVertex, - &output) + .makeElementWires(edges, "", 0.0, ConnectionPolicy::requireSharedVertex, &output) .getSubTopoShapes(TopAbs_WIRE); - shapes.erase(shapes.begin() + params.boundary_begin, - shapes.begin() + params.boundary_end); + shapes.erase(shapes.begin() + params.boundary_begin, shapes.begin() + params.boundary_end); } } else { @@ -3780,11 +3843,7 @@ TopoShape& TopoShape::makeElementFilledFace(const std::vector& _shape } if (edges.size()) { wires = TopoShape(0, Hasher) - .makeElementWires(edges, - "", - 0.0, - ConnectionPolicy::requireSharedVertex, - &output) + .makeElementWires(edges, "", 0.0, ConnectionPolicy::requireSharedVertex, &output) .getSubTopoShapes(TopAbs_WIRE); } } @@ -3809,10 +3868,12 @@ TopoShape& TopoShape::makeElementFilledFace(const std::vector& _shape bound.fix(Precision::Confusion(), Precision::Confusion(), Precision::Confusion()); for (const auto& e : bound.getOrderedEdges()) { - maker.Add(TopoDS::Edge(e.getShape()), - getSupport(e.getShape()), - getOrder(e.getShape()), - /*IsBound*/ Standard_True); + maker.Add( + TopoDS::Edge(e.getShape()), + getSupport(e.getShape()), + getOrder(e.getShape()), + /*IsBound*/ Standard_True + ); } for (const auto& s : shapes) { @@ -3822,17 +3883,21 @@ TopoShape& TopoShape::makeElementFilledFace(const std::vector& _shape const auto& sh = s.getShape(); if (sh.ShapeType() == TopAbs_WIRE) { for (const auto& e : s.getSubShapes(TopAbs_EDGE)) { - maker.Add(TopoDS::Edge(e), - getSupport(e), - getOrder(e), - /*IsBound*/ Standard_False); + maker.Add( + TopoDS::Edge(e), + getSupport(e), + getOrder(e), + /*IsBound*/ Standard_False + ); } } else if (sh.ShapeType() == TopAbs_EDGE) { - maker.Add(TopoDS::Edge(sh), - getSupport(sh), - getOrder(sh), - /*IsBound*/ Standard_False); + maker.Add( + TopoDS::Edge(sh), + getSupport(sh), + getOrder(sh), + /*IsBound*/ Standard_False + ); } else if (sh.ShapeType() == TopAbs_FACE) { maker.Add(TopoDS::Face(sh), getOrder(sh)); @@ -3905,9 +3970,11 @@ TopoShape& TopoShape::makeElementSolid(const TopoShape& shape, const char* op) makeElementShape(mkSolid, shape, op); } else { // if (count > 1) - FC_THROWM(Base::CADKernelError, - "Only one compsolid can be accepted. " - "Provided shape has more than one compsolid."); + FC_THROWM( + Base::CADKernelError, + "Only one compsolid can be accepted. " + "Provided shape has more than one compsolid." + ); } return *this; } @@ -3930,10 +3997,12 @@ TopoShape& TopoShape::makeElementMirror(const TopoShape& shape, const gp_Ax2& ax return makeElementShape(mkTrf, shape, op); } -TopoShape& TopoShape::makeElementSlice(const TopoShape& shape, - const Base::Vector3d& dir, - double distance, - const char* op) +TopoShape& TopoShape::makeElementSlice( + const TopoShape& shape, + const Base::Vector3d& dir, + double distance, + const char* op +) { if (shape.isNull()) { FC_THROWM(NullShapeException, "Null shape"); @@ -3946,10 +4015,12 @@ TopoShape& TopoShape::makeElementSlice(const TopoShape& shape, return *this; } -TopoShape& TopoShape::makeElementSlices(const TopoShape& shape, - const Base::Vector3d& dir, - const std::vector& distances, - const char* op) +TopoShape& TopoShape::makeElementSlices( + const TopoShape& shape, + const Base::Vector3d& dir, + const std::vector& distances, + const char* op +) { std::vector wires; TopoCrossSection cs(dir.x, dir.y, dir.z, shape, op); @@ -3960,8 +4031,10 @@ TopoShape& TopoShape::makeElementSlices(const TopoShape& shape, return makeElementCompound(wires, op, SingleShapeCompoundCreationPolicy::returnShape); } -TopoShape& TopoShape::replaceElementShape(const TopoShape& shape, - const std::vector>& s) +TopoShape& TopoShape::replaceElementShape( + const TopoShape& shape, + const std::vector>& s +) { if (shape.isNull()) { FC_THROWM(NullShapeException, "Null shape"); @@ -4002,11 +4075,13 @@ TopoShape& TopoShape::removeElementShape(const TopoShape& shape, const std::vect return *this; } -TopoShape& TopoShape::makeElementFillet(const TopoShape& shape, - const std::vector& edges, - double radius1, - double radius2, - const char* op) +TopoShape& TopoShape::makeElementFillet( + const TopoShape& shape, + const std::vector& edges, + double radius1, + double radius2, + const char* op +) { if (!op) { op = Part::OpCodes::Fillet; @@ -4032,13 +4107,15 @@ TopoShape& TopoShape::makeElementFillet(const TopoShape& shape, return makeElementShape(mkFillet, shape, op); } -TopoShape& TopoShape::makeElementChamfer(const TopoShape& shape, - const std::vector& edges, - ChamferType chamferType, - double radius1, - double radius2, - const char* op, - Flip flipDirection) +TopoShape& TopoShape::makeElementChamfer( + const TopoShape& shape, + const std::vector& edges, + ChamferType chamferType, + double radius1, + double radius2, + const char* op, + Flip flipDirection +) { if (!op) { op = Part::OpCodes::Chamfer; @@ -4074,20 +4151,20 @@ TopoShape& TopoShape::makeElementChamfer(const TopoShape& shape, mkChamfer.Add(radius1, radius2, TopoDS::Edge(edge), TopoDS::Face(face)); break; case ChamferType::distanceAngle: // Distance and angle - mkChamfer.AddDA(radius1, - Base::toRadians(radius2), - TopoDS::Edge(edge), - TopoDS::Face(face)); + mkChamfer + .AddDA(radius1, Base::toRadians(radius2), TopoDS::Edge(edge), TopoDS::Face(face)); break; } } return makeElementShape(mkChamfer, shape, op); } -TopoShape& TopoShape::makeElementGeneralFuse(const std::vector& _shapes, - std::vector>& modifies, - double tol, - const char* op) +TopoShape& TopoShape::makeElementGeneralFuse( + const std::vector& _shapes, + std::vector>& modifies, + double tol, + const char* op +) { if (!op) { op = Part::OpCodes::GeneralFuse; @@ -4111,7 +4188,8 @@ TopoShape& TopoShape::makeElementGeneralFuse(const std::vector& _shap mkGFA.SetArguments(GFAArguments); if (tol > 0.0) { mkGFA.SetFuzzyValue(tol); - } else if (tol < 0.0) { + } + else if (tol < 0.0) { FCBRepAlgoAPIHelper::setAutoFuzzy(&mkGFA); } mkGFA.SetNonDestructive(Standard_True); @@ -4139,20 +4217,17 @@ TopoShape& TopoShape::makeElementGeneralFuse(const std::vector& _shap return *this; } -TopoShape& -TopoShape::makeElementFuse(const std::vector& shapes, const char* op, double tol) +TopoShape& TopoShape::makeElementFuse(const std::vector& shapes, const char* op, double tol) { return makeElementBoolean(Part::OpCodes::Fuse, shapes, op, tol); } -TopoShape& -TopoShape::makeElementCut(const std::vector& shapes, const char* op, double tol) +TopoShape& TopoShape::makeElementCut(const std::vector& shapes, const char* op, double tol) { return makeElementBoolean(Part::OpCodes::Cut, shapes, op, tol); } -TopoShape& -TopoShape::makeElementXor(const std::vector& shapes, const char* op, double tol) +TopoShape& TopoShape::makeElementXor(const std::vector& shapes, const char* op, double tol) { if (shapes.empty()) { FC_THROWM(NullShapeException, "Null shape"); @@ -4219,10 +4294,7 @@ TopoShape::makeElementXor(const std::vector& shapes, const char* op, } else { // Final result is Cut(Union, Common). - result.makeElementBoolean(Part::OpCodes::Cut, - {tempUnion, tempCommon}, - currentOp, - tol); + result.makeElementBoolean(Part::OpCodes::Cut, {tempUnion, tempCommon}, currentOp, tol); } } @@ -4230,17 +4302,21 @@ TopoShape::makeElementXor(const std::vector& shapes, const char* op, return *this; } -TopoShape& TopoShape::makeElementShape(BRepBuilderAPI_MakeShape& mkShape, - const TopoShape& source, - const char* op) +TopoShape& TopoShape::makeElementShape( + BRepBuilderAPI_MakeShape& mkShape, + const TopoShape& source, + const char* op +) { std::vector sources(1, source); return makeElementShape(mkShape, sources, op); } -TopoShape& TopoShape::makeElementShape(BRepBuilderAPI_MakeShape& mkShape, - const std::vector& shapes, - const char* op) +TopoShape& TopoShape::makeElementShape( + BRepBuilderAPI_MakeShape& mkShape, + const std::vector& shapes, + const char* op +) { TopoDS_Shape shape; // OCCT 7.3.x requires calling Solid() and not Shape() to function correctly @@ -4253,10 +4329,12 @@ TopoShape& TopoShape::makeElementShape(BRepBuilderAPI_MakeShape& mkShape, return makeShapeWithElementMap(shape, MapperMaker(mkShape), shapes, op); } -TopoShape& TopoShape::makeElementShape(BRepFeat_MakePrism& mkShape, - const std::vector& sources, - const TopoShape& upTo, - const char* op) +TopoShape& TopoShape::makeElementShape( + BRepFeat_MakePrism& mkShape, + const std::vector& sources, + const TopoShape& upTo, + const char* op +) { if (!op) { op = Part::OpCodes::Prism; @@ -4267,12 +4345,14 @@ TopoShape& TopoShape::makeElementShape(BRepFeat_MakePrism& mkShape, } -TopoShape& TopoShape::makeElementLoft(const std::vector& shapes, - IsSolid isSolid, - IsRuled isRuled, - IsClosed isClosed, - Standard_Integer maxDegree, - const char* op) +TopoShape& TopoShape::makeElementLoft( + const std::vector& shapes, + IsSolid isSolid, + IsRuled isRuled, + IsClosed isClosed, + Standard_Integer maxDegree, + const char* op +) { if (!op) { op = Part::OpCodes::Loft; @@ -4284,17 +4364,19 @@ TopoShape& TopoShape::makeElementLoft(const std::vector& shapes, auto profiles = prepareProfiles(shapes); if (shapes.size() < 2) { - FC_THROWM(Base::CADKernelError, - "Need at least two vertices, edges or wires to create loft face"); + FC_THROWM(Base::CADKernelError, "Need at least two vertices, edges or wires to create loft face"); } - int i=0; - Base::Vector3d center1,center2; + int i = 0; + Base::Vector3d center1, center2; for (auto& sh : profiles) { - if (i>0) { - if (sh.getCenterOfGravity(center1) && profiles[i-1].getCenterOfGravity(center2) && center1.IsEqual(center2,Precision::Confusion())) { - FC_THROWM(Base::CADKernelError, - "Segments of a Loft/Pad do not have sufficient separation"); + if (i > 0) { + if (sh.getCenterOfGravity(center1) && profiles[i - 1].getCenterOfGravity(center2) + && center1.IsEqual(center2, Precision::Confusion())) { + FC_THROWM( + Base::CADKernelError, + "Segments of a Loft/Pad do not have sufficient separation" + ); } } const auto& shape = sh.getShape(); @@ -4314,8 +4396,10 @@ TopoShape& TopoShape::makeElementLoft(const std::vector& shapes, - W1-W2-W3-V1 ==> W1-W2-W3-V1-W1 invalid closed - W1-W2-W3 ==> W1-W2-W3-W1 valid closed*/ if (profiles.back().getShape().ShapeType() == TopAbs_VERTEX) { - Base::Console().message("TopoShape::makeLoft: can't close Loft with Vertex as last " - "profile. 'Closed' ignored.\n"); + Base::Console().message( + "TopoShape::makeLoft: can't close Loft with Vertex as last " + "profile. 'Closed' ignored.\n" + ); } else { // repeat Add logic above for first profile @@ -4341,10 +4425,12 @@ TopoShape& TopoShape::makeElementLoft(const std::vector& shapes, #else aGenerator.Build(); #endif - return makeShapeWithElementMap(aGenerator.Shape(), - MapperThruSections(aGenerator, profiles), - shapes, - op); + return makeShapeWithElementMap( + aGenerator.Shape(), + MapperThruSections(aGenerator, profiles), + shapes, + op + ); } TopoShape& TopoShape::makeElementPrism(const TopoShape& base, const gp_Vec& vec, const char* op) @@ -4359,14 +4445,16 @@ TopoShape& TopoShape::makeElementPrism(const TopoShape& base, const gp_Vec& vec, return makeElementShape(mkPrism, base, op); } -TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, - const TopoShape& profile, - const TopoShape& supportFace, - const TopoShape& __uptoface, - const gp_Dir& direction, - PrismMode Mode, - Standard_Boolean checkLimits, - const char* op) +TopoShape& TopoShape::makeElementPrismUntil( + const TopoShape& _base, + const TopoShape& profile, + const TopoShape& supportFace, + const TopoShape& __uptoface, + const gp_Dir& direction, + PrismMode Mode, + Standard_Boolean checkLimits, + const char* op +) { if (!op) { op = Part::OpCodes::Prism; @@ -4375,11 +4463,11 @@ TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, BRepFeat_MakePrism PrismMaker; // don't remove limits of concave face - if (checkLimits && __uptoface.shapeType(true) == TopAbs_FACE){ + if (checkLimits && __uptoface.shapeType(true) == TopAbs_FACE) { Base::Vector3d vCog; profile.getCenterOfGravity(vCog); gp_Pnt pCog(vCog.x, vCog.y, vCog.z); - checkLimits = ! Part::Tools::isConcave(TopoDS::Face(__uptoface.getShape()), pCog , direction); + checkLimits = !Part::Tools::isConcave(TopoDS::Face(__uptoface.getShape()), pCog, direction); } TopoShape _uptoface(__uptoface); @@ -4403,8 +4491,7 @@ TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, // Check whether the face has limits or not. Unlimited faces have no wire // Note: Datum planes are always unlimited - if (checkLimits && uptoface.shapeType(true) == TopAbs_FACE - && uptoface.hasSubShape(TopAbs_WIRE)) { + if (checkLimits && uptoface.shapeType(true) == TopAbs_FACE && uptoface.hasSubShape(TopAbs_WIRE)) { TopoDS_Face face = TopoDS::Face(uptoface.getShape()); bool remove_limits = false; // Remove the limits of the upToFace so that the extrusion works even if profile is larger @@ -4426,9 +4513,7 @@ TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, std::vector wires; uptoface.splitWires(&wires); for (auto& w : wires) { - BRepProj_Projection proj(TopoDS::Wire(w.getShape()), - profile.getShape(), - -direction); + BRepProj_Projection proj(TopoDS::Wire(w.getShape()), profile.getShape(), -direction); if (proj.More()) { remove_limits = true; break; @@ -4487,7 +4572,8 @@ TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, auto mode = PrismMode::None; for (auto& face : profile.getSubTopoShapes( - profile.hasSubShape(TopAbs_FACE) ? TopAbs_FACE : TopAbs_WIRE)) { + profile.hasSubShape(TopAbs_FACE) ? TopAbs_FACE : TopAbs_WIRE + )) { srcShapes.clear(); if (!profile.isNull() && !result.findShape(profile.getShape())) { srcShapes.push_back(profile); @@ -4508,16 +4594,18 @@ TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, srcShapes.push_back(result); - if (result.isInfinite()){ + if (result.isInfinite()) { result = face; } - PrismMaker.Init(result.getShape(), - face.getShape(), - TopoDS::Face(supportFace.getShape()), - direction, - mode, - Standard_False); + PrismMaker.Init( + result.getShape(), + face.getShape(), + TopoDS::Face(supportFace.getShape()), + direction, + mode, + Standard_False + ); mode = PrismMode::FuseWithBase; PrismMaker.Perform(uptoface.getShape()); @@ -4555,11 +4643,13 @@ TopoShape& TopoShape::makeElementPrismUntil(const TopoShape& _base, return *this; } -TopoShape& TopoShape::makeElementRevolve(const TopoShape& _base, - const gp_Ax1& axis, - double d, - const char* face_maker, - const char* op) +TopoShape& TopoShape::makeElementRevolve( + const TopoShape& _base, + const gp_Ax1& axis, + double d, + const char* face_maker, + const char* op +) { if (!op) { op = Part::OpCodes::Revolve; @@ -4579,15 +4669,17 @@ TopoShape& TopoShape::makeElementRevolve(const TopoShape& _base, return makeElementShape(mkRevol, base, op); } -TopoShape& TopoShape::makeElementRevolution(const TopoShape& _base, - const TopoDS_Shape& profile, - const gp_Ax1& axis, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const char* face_maker, - RevolMode Mode, - Standard_Boolean Modify, - const char* op) +TopoShape& TopoShape::makeElementRevolution( + const TopoShape& _base, + const TopoDS_Shape& profile, + const gp_Ax1& axis, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const char* face_maker, + RevolMode Mode, + Standard_Boolean Modify, + const char* op +) { if (!op) { op = Part::OpCodes::Revolve; @@ -4608,12 +4700,7 @@ TopoShape& TopoShape::makeElementRevolution(const TopoShape& _base, BRepFeat_MakeRevol mkRevol; for (TopExp_Explorer xp(profile, TopAbs_FACE); xp.More(); xp.Next()) { - mkRevol.Init(base.getShape(), - xp.Current(), - supportface, - axis, - static_cast(Mode), - Modify); + mkRevol.Init(base.getShape(), xp.Current(), supportface, axis, static_cast(Mode), Modify); mkRevol.Perform(uptoface); if (!mkRevol.IsDone()) { throw Base::RuntimeError("Revolution: Up to face: Could not revolve the sketch!"); @@ -4623,13 +4710,15 @@ TopoShape& TopoShape::makeElementRevolution(const TopoShape& _base, return makeElementShape(mkRevol, base, op); } -TopoShape& TopoShape::makeElementDraft(const TopoShape& shape, - const std::vector& _faces, - const gp_Dir& pullDirection, - double angle, - const gp_Pln& neutralPlane, - bool retry, - const char* op) +TopoShape& TopoShape::makeElementDraft( + const TopoShape& shape, + const std::vector& _faces, + const gp_Dir& pullDirection, + double angle, + const gp_Pln& neutralPlane, + bool retry, + const char* op +) { if (!op) { op = Part::OpCodes::Draft; @@ -4675,10 +4764,12 @@ TopoShape& TopoShape::makeElementDraft(const TopoShape& shape, return makeElementShape(mkDraft, shape, op); } -TopoShape& TopoShape::makeElementFace(const TopoShape& shape, - const char* op, - const char* maker, - const gp_Pln* plane) +TopoShape& TopoShape::makeElementFace( + const TopoShape& shape, + const char* op, + const char* maker, + const gp_Pln* plane +) { std::vector shapes; if (shape.isNull()) { @@ -4693,10 +4784,12 @@ TopoShape& TopoShape::makeElementFace(const TopoShape& shape, return makeElementFace(shapes, op, maker, plane); } -TopoShape& TopoShape::makeElementFace(const std::vector& shapes, - const char* op, - const char* maker, - const gp_Pln* plane) +TopoShape& TopoShape::makeElementFace( + const std::vector& shapes, + const char* op, + const char* maker, + const gp_Pln* plane +) { if (!maker || !maker[0]) { maker = "Part::FaceMakerBullseye"; @@ -4728,10 +4821,7 @@ TopoShape& TopoShape::makeElementFace(const std::vector& shapes, resetElementMap(ret.elementMap()); if (!isValid()) { ShapeFix_ShapeTolerance aSFT; - aSFT.LimitTolerance(getShape(), - Precision::Confusion(), - Precision::Confusion(), - TopAbs_SHAPE); + aSFT.LimitTolerance(getShape(), Precision::Confusion(), Precision::Confusion(), TopAbs_SHAPE); // In some cases, the OCC reports the returned shape having invalid // tolerance. Not sure about the real cause. @@ -4808,36 +4898,41 @@ TopoShape& TopoShape::makeElementRefine(const TopoShape& shape, const char* op, return *this; } - std::vector - TopoShape::getHigherElements(const char *element, bool silent) const - { - TopoShape shape = getSubTopoShape(element, silent); - if(shape.isNull()) - return {}; - - std::vector res; - - for (int type = shape.shapeType() - 1; type >= 0; type--) { - const char* shapetype = shapeName((TopAbs_ShapeEnum)type).c_str(); - for (int idx : findAncestors(shape.getShape(), (TopAbs_ShapeEnum)type)) - res.emplace_back(shapetype, idx); - } - return res; +std::vector TopoShape::getHigherElements(const char* element, bool silent) const +{ + TopoShape shape = getSubTopoShape(element, silent); + if (shape.isNull()) { + return {}; } -TopoShape& TopoShape::makeElementBSplineFace(const TopoShape& shape, - FillingStyle style, - bool keepBezier, - const char* op) + std::vector res; + + for (int type = shape.shapeType() - 1; type >= 0; type--) { + const char* shapetype = shapeName((TopAbs_ShapeEnum)type).c_str(); + for (int idx : findAncestors(shape.getShape(), (TopAbs_ShapeEnum)type)) { + res.emplace_back(shapetype, idx); + } + } + return res; +} + +TopoShape& TopoShape::makeElementBSplineFace( + const TopoShape& shape, + FillingStyle style, + bool keepBezier, + const char* op +) { std::vector input(1, shape); return makeElementBSplineFace(input, style, keepBezier, op); } -TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input, - FillingStyle style, - bool keepBezier, - const char* op) +TopoShape& TopoShape::makeElementBSplineFace( + const std::vector& input, + FillingStyle style, + bool keepBezier, + const char* op +) { std::vector edges; for (auto& s : input) { @@ -4933,8 +5028,7 @@ TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input if (!curve) { break; } - curve->Transform( - heloc.Transformation()); // apply original transformation to control points + curve->Transform(heloc.Transformation()); // apply original transformation to control points curves.push_back(curve); } if (curves.size() == edges.size()) { @@ -4959,10 +5053,10 @@ TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input for (const auto& e : edges) { const TopoDS_Edge& edge = TopoDS::Edge(e.getShape()); TopLoc_Location heloc; // this will be output - Handle(Geom_Curve) c_geom = - BRep_Tool::Curve(edge, heloc, u1, u2); // The geometric curve - Handle(Geom_BSplineCurve) bspline = - Handle(Geom_BSplineCurve)::DownCast(c_geom); // Try to get BSpline curve + Handle(Geom_Curve) c_geom = BRep_Tool::Curve(edge, heloc, u1, u2); // The geometric curve + Handle(Geom_BSplineCurve) bspline = Handle(Geom_BSplineCurve)::DownCast( + c_geom + ); // Try to get BSpline curve if (!bspline.IsNull()) { gp_Trsf transf = heloc.Transformation(); bspline->Transform(transf); // apply original transformation to control points @@ -4975,10 +5069,12 @@ TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input TopoDS_Edge nurbs = TopoDS::Edge(mkNurbs.Shape()); // avoid copying TopLoc_Location heloc2; // this will be output - Handle(Geom_Curve) c_geom2 = - BRep_Tool::Curve(nurbs, heloc2, u1, u2); // The geometric curve - Handle(Geom_BSplineCurve) bspline2 = - Handle(Geom_BSplineCurve)::DownCast(c_geom2); // Try to get BSpline curve + Handle(Geom_Curve) c_geom2 = BRep_Tool::Curve(nurbs, heloc2, u1, u2); // The + // geometric + // curve + Handle(Geom_BSplineCurve) bspline2 = Handle(Geom_BSplineCurve)::DownCast( + c_geom2 + ); // Try to get BSpline curve if (!bspline2.IsNull()) { gp_Trsf transf = heloc2.Transformation(); @@ -4989,11 +5085,12 @@ TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input else { // BRepBuilderAPI_NurbsConvert failed, try ShapeConstruct_Curve now ShapeConstruct_Curve scc; - Handle(Geom_BSplineCurve) spline = - scc.ConvertToBSpline(c_geom, u1, u2, Precision::Confusion()); + Handle(Geom_BSplineCurve) spline + = scc.ConvertToBSpline(c_geom, u1, u2, Precision::Confusion()); if (spline.IsNull()) { Standard_Failure::Raise( - "A curve was not a B-spline and could not be converted into one."); + "A curve was not a B-spline and could not be converted into one." + ); } gp_Trsf transf = heloc2.Transformation(); spline->Transform(transf); // apply original transformation to control points @@ -5050,13 +5147,15 @@ TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input aFace.mapSubElement(newEdges); Data::ElementIDRefs sids; - Data::MappedName edgeName = - aFace.getMappedName(Data::IndexedName::fromConst("Edge", 1), true, &sids); - aFace.setElementComboName(Data::IndexedName::fromConst("Face", 1), - {edgeName}, - Part::OpCodes::BSplineFace, - op, - &sids); + Data::MappedName edgeName + = aFace.getMappedName(Data::IndexedName::fromConst("Edge", 1), true, &sids); + aFace.setElementComboName( + Data::IndexedName::fromConst("Face", 1), + {edgeName}, + Part::OpCodes::BSplineFace, + op, + &sids + ); *this = aFace; return *this; } @@ -5074,11 +5173,13 @@ TopoShape& TopoShape::makeElementBSplineFace(const std::vector& input * * @return The encoded, possibly hashed name. */ -Data::MappedName TopoShape::setElementComboName(const Data::IndexedName& element, - const std::vector& names, - const char* marker, - const char* op, - const Data::ElementIDRefs* _sids) +Data::MappedName TopoShape::setElementComboName( + const Data::IndexedName& element, + const std::vector& names, + const char* marker, + const char* op, + const Data::ElementIDRefs* _sids +) { if (names.empty()) { return Data::MappedName {}; @@ -5129,10 +5230,12 @@ Data::MappedName TopoShape::setElementComboName(const Data::IndexedName& element return elementMap()->setElementName(element, newName, Tag, &sids); } -std::vector TopoShape::decodeElementComboName(const Data::IndexedName& element, - const Data::MappedName& name, - const char* marker, - std::string* postfix) const +std::vector TopoShape::decodeElementComboName( + const Data::IndexedName& element, + const Data::MappedName& name, + const char* marker, + std::string* postfix +) const { std::vector names; if (!element) { @@ -5345,9 +5448,11 @@ bool TopoShape::isPlanarFace(double tol) const return false; } - return GeomSurface::isPlanar(BRepAdaptor_Surface(TopoDS::Face(getShape())).Surface().Surface(), - nullptr, - tol); + return GeomSurface::isPlanar( + BRepAdaptor_Surface(TopoDS::Face(getShape())).Surface().Surface(), + nullptr, + tol + ); } // TODO: Refactor this into two methods. Totally separate concerns here. @@ -5365,14 +5470,17 @@ bool TopoShape::linearize(LinearizeFace do_face, LinearizeEdge do_edge) continue; } std::unique_ptr geo( - Geometry::fromShape(e.Located(TopLoc_Location()).Oriented(TopAbs_FORWARD))); + Geometry::fromShape(e.Located(TopLoc_Location()).Oriented(TopAbs_FORWARD)) + ); std::unique_ptr gline(static_cast(geo.get())->toLine()); if (gline) { touched = true; - builder.UpdateEdge(e, - Handle(Geom_Curve)::DownCast(gline->handle()), - e.Location(), - BRep_Tool::Tolerance(e)); + builder.UpdateEdge( + e, + Handle(Geom_Curve)::DownCast(gline->handle()), + e.Location(), + BRep_Tool::Tolerance(e) + ); } } } @@ -5384,14 +5492,17 @@ bool TopoShape::linearize(LinearizeFace do_face, LinearizeEdge do_edge) continue; } std::unique_ptr geo( - Geometry::fromShape(f.Located(TopLoc_Location()).Oriented(TopAbs_FORWARD))); + Geometry::fromShape(f.Located(TopLoc_Location()).Oriented(TopAbs_FORWARD)) + ); std::unique_ptr gplane(static_cast(geo.get())->toPlane()); if (gplane) { touched = true; - builder.UpdateFace(f, - Handle(Geom_Surface)::DownCast(gplane->handle()), - f.Location(), - BRep_Tool::Tolerance(f)); + builder.UpdateFace( + f, + Handle(Geom_Surface)::DownCast(gplane->handle()), + f.Location(), + BRep_Tool::Tolerance(f) + ); } } } @@ -5586,9 +5697,11 @@ TopoShape& TopoShape::makeElementShell(bool silent, const char* op) if (silent) { return *this; } - FC_THROWM(Base::CADKernelError, - "Failed to make shell: unexpected output shape type " - << shapeType(shape.ShapeType(), true)); + FC_THROWM( + Base::CADKernelError, + "Failed to make shell: unexpected output shape type " + << shapeType(shape.ShapeType(), true) + ); } setShape(shape); @@ -5603,9 +5716,11 @@ TopoShape& TopoShape::makeElementShell(bool silent, const char* op) return *this; } -TopoShape& TopoShape::makeElementShellFromWires(const std::vector& wires, - bool silent, - const char* op) +TopoShape& TopoShape::makeElementShellFromWires( + const std::vector& wires, + bool silent, + const char* op +) { BRepFill_Generator maker; for (auto& w : wires) { @@ -5680,20 +5795,24 @@ bool TopoShape::fixSolidOrientation() return false; } -TopoShape& TopoShape::makeElementBoolean(const char* maker, - const TopoShape& shape, - const char* op, - double tolerance) +TopoShape& TopoShape::makeElementBoolean( + const char* maker, + const TopoShape& shape, + const char* op, + double tolerance +) { return makeElementBoolean(maker, std::vector(1, shape), op, tolerance); } // TODO: Refactor this so that each OpCode type is a separate method to reduce size -TopoShape& TopoShape::makeElementBoolean(const char* maker, - const std::vector& shapes, - const char* op, - double tolerance) +TopoShape& TopoShape::makeElementBoolean( + const char* maker, + const std::vector& shapes, + const char* op, + double tolerance +) { if (!maker) { FC_THROWM(Base::CADKernelError, "no maker"); @@ -5783,8 +5902,8 @@ TopoShape& TopoShape::makeElementBoolean(const char* maker, for (auto it = shapes.begin(); it != shapes.end(); ++it) { auto& s = *it; if (s.isNull()) { - if ( it == shapes.begin() ) { - return *this; // Compatible with pre-TNP allowing .fuse() behavior + if (it == shapes.begin()) { + return *this; // Compatible with pre-TNP allowing .fuse() behavior } FC_THROWM(NullShapeException, "Null input shape"); } @@ -5875,7 +5994,8 @@ TopoShape& TopoShape::makeElementBoolean(const char* maker, mk->SetTools(shapeTools); if (tolerance > 0.0) { mk->SetFuzzyValue(tolerance); - } else if (tolerance < 0.0) { + } + else if (tolerance < 0.0) { FCBRepAlgoAPIHelper::setAutoFuzzy(mk.get()); } #if OCC_VERSION_HEX >= 0x070600 @@ -5936,8 +6056,9 @@ void TopoShape::reTagElementMap(long tag, App::StringHasherRef hasher, const cha return; } - if (_Shape.IsNull()) + if (_Shape.IsNull()) { return; + } TopoShape tmp(*this); initCache(1); @@ -5947,17 +6068,21 @@ void TopoShape::reTagElementMap(long tag, App::StringHasherRef hasher, const cha copyElementMap(tmp, postfix); } -void TopoShape::cacheRelatedElements(const Data::MappedName& name, - HistoryTraceType sameType, - const QVector& names) const +void TopoShape::cacheRelatedElements( + const Data::MappedName& name, + HistoryTraceType sameType, + const QVector& names +) const { initCache(); _cache->insertRelation(ShapeRelationKey(name, sameType), names); } -bool TopoShape::getRelatedElementsCached(const Data::MappedName& name, - HistoryTraceType sameType, - QVector& names) const +bool TopoShape::getRelatedElementsCached( + const Data::MappedName& name, + HistoryTraceType sameType, + QVector& names +) const { if (!_cache) { return false; @@ -5970,32 +6095,40 @@ bool TopoShape::getRelatedElementsCached(const Data::MappedName& name, return true; } -Data::MappedElement TopoShape::chooseMatchingSubShapeByPlaneOrLine(const TopoShape& shapeToFind, const TopoShape& shapeToLookIn) +Data::MappedElement TopoShape::chooseMatchingSubShapeByPlaneOrLine( + const TopoShape& shapeToFind, + const TopoShape& shapeToLookIn +) { Data::MappedElement result; // See if we have a Face. If so, try to match using a plane. auto targetShape = shapeToFind.getSubTopoShape("Face", true); - if ( ! targetShape.isNull() ) { + if (!targetShape.isNull()) { int index = 0; - for ( const auto& searchFace : shapeToLookIn.getSubTopoShapes(TopAbs_FACE)) { - index++; // We have to generate the element index. - if ( targetShape.isCoplanar(searchFace) ) { - if ( ! result.name.empty() ) - return {}; // Found more than one, invalidate our guess. Future: return all matches to the UI? - result = shapeToLookIn.getElementName(("Face"+std::to_string(index)).c_str()); + for (const auto& searchFace : shapeToLookIn.getSubTopoShapes(TopAbs_FACE)) { + index++; // We have to generate the element index. + if (targetShape.isCoplanar(searchFace)) { + if (!result.name.empty()) { + return {}; // Found more than one, invalidate our guess. Future: return all + // matches to the UI? + } + result = shapeToLookIn.getElementName(("Face" + std::to_string(index)).c_str()); } } } - // Alternatively, try to locate an Edge, and try to match. Currently by exact equivalence; later can improve. + // Alternatively, try to locate an Edge, and try to match. Currently by exact equivalence; + // later can improve. targetShape = shapeToFind.getSubTopoShape("Edge", true); - if ( ! targetShape.isNull() ) { // Try to match edges + if (!targetShape.isNull()) { // Try to match edges int index = 0; - for ( const auto& searchEdge : shapeToLookIn.getSubTopoShapes(TopAbs_EDGE)) { + for (const auto& searchEdge : shapeToLookIn.getSubTopoShapes(TopAbs_EDGE)) { index++; - if ( targetShape.isSame(searchEdge) ) { // TODO: Test for edges that are collinear as really what we want - if ( ! result.name.empty() ) - return {}; // Found more than one - result = shapeToLookIn.getElementName(("Edge"+std::to_string(index)).c_str()); + if (targetShape.isSame(searchEdge)) { // TODO: Test for edges that are collinear as + // really what we want + if (!result.name.empty()) { + return {}; // Found more than one + } + result = shapeToLookIn.getElementName(("Edge" + std::to_string(index)).c_str()); } } } diff --git a/src/Mod/Part/App/TopoShapeFace.pyi b/src/Mod/Part/App/TopoShapeFace.pyi index 18444c2800..2794ba48ca 100644 --- a/src/Mod/Part/App/TopoShapeFace.pyi +++ b/src/Mod/Part/App/TopoShapeFace.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from TopoShape import TopoShape from typing import Final, Tuple, Dict, Optional, List - @export( Twin="TopoShape", TwinPointer="TopoShape", @@ -106,8 +105,16 @@ class TopoShapeFace(TopoShape): ... @constmethod - def makeEvolved(self, *, Profile: TopoShape, Join: int, AxeProf: bool, Solid: bool, - ProfOnSpine: bool, Tolerance: float) -> TopoShape: + def makeEvolved( + self, + *, + Profile: TopoShape, + Join: int, + AxeProf: bool, + Solid: bool, + ProfOnSpine: bool, + Tolerance: float + ) -> TopoShape: """ Profile along the spine """ diff --git a/src/Mod/Part/App/TopoShapeFacePyImp.cpp b/src/Mod/Part/App/TopoShapeFacePyImp.cpp index 53e8ec29ca..f3c9475366 100644 --- a/src/Mod/Part/App/TopoShapeFacePyImp.cpp +++ b/src/Mod/Part/App/TopoShapeFacePyImp.cpp @@ -22,46 +22,46 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -94,18 +94,22 @@ using namespace Part; -namespace Part { - extern Py::Object shape2pyshape(const TopoDS_Shape &shape); +namespace Part +{ +extern Py::Object shape2pyshape(const TopoDS_Shape& shape); } -namespace{ -const TopoDS_Face& getTopoDSFace(const TopoShapeFacePy* theFace){ +namespace +{ +const TopoDS_Face& getTopoDSFace(const TopoShapeFacePy* theFace) +{ const TopoDS_Face& f = TopoDS::Face(theFace->getTopoShapePtr()->getShape()); - if (f.IsNull()) + if (f.IsNull()) { throw Py::ValueError("Face is null"); + } return f; } -} +} // namespace // returns a string which represent the object e.g. when printed in python std::string TopoShapeFacePy::representation() const @@ -116,7 +120,7 @@ std::string TopoShapeFacePy::representation() const return str.str(); } -PyObject *TopoShapeFacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* TopoShapeFacePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of TopoShapeFacePy and the Twin object return new TopoShapeFacePy(new TopoShape); @@ -132,7 +136,7 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pW; + PyObject* pW; if (PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pW)) { try { const TopoDS_Shape& sh = static_cast(pW)->getTopoShapePtr()->getShape(); @@ -163,15 +167,23 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); PyObject *face, *wire; - if (PyArg_ParseTuple(args, "O!O!", &(Part::TopoShapeFacePy::Type), &face, - &(Part::TopoShapeWirePy::Type), &wire)) { + if (PyArg_ParseTuple( + args, + "O!O!", + &(Part::TopoShapeFacePy::Type), + &face, + &(Part::TopoShapeWirePy::Type), + &wire + )) { try { - const TopoDS_Shape& f = static_cast(face)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& f + = static_cast(face)->getTopoShapePtr()->getShape(); if (f.IsNull()) { PyErr_SetString(PartExceptionOCCError, "cannot create face out of empty support face"); return -1; } - const TopoDS_Shape& w = static_cast(wire)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& w + = static_cast(wire)->getTopoShapePtr()->getShape(); if (w.IsNull()) { PyErr_SetString(PartExceptionOCCError, "cannot create face out of empty boundary wire"); return -1; @@ -194,17 +206,25 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *surf; - if (PyArg_ParseTuple(args, "O!O!", &(Part::GeometrySurfacePy::Type), &surf, - &(Part::TopoShapeWirePy::Type), &wire)) { + PyObject* surf; + if (PyArg_ParseTuple( + args, + "O!O!", + &(Part::GeometrySurfacePy::Type), + &surf, + &(Part::TopoShapeWirePy::Type), + &wire + )) { try { - Handle(Geom_Surface) S = Handle(Geom_Surface)::DownCast - (static_cast(surf)->getGeometryPtr()->handle()); + Handle(Geom_Surface) S = Handle(Geom_Surface)::DownCast( + static_cast(surf)->getGeometryPtr()->handle() + ); if (S.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a valid surface"); return -1; } - const TopoDS_Shape& w = static_cast(wire)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& w + = static_cast(wire)->getTopoShapePtr()->getShape(); if (w.IsNull()) { PyErr_SetString(PartExceptionOCCError, "cannot create face out of empty boundary wire"); return -1; @@ -226,11 +246,12 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *bound=nullptr; + PyObject* bound = nullptr; if (PyArg_ParseTuple(args, "O!|O!", &(GeometryPy::Type), &surf, &(PyList_Type), &bound)) { try { - Handle(Geom_Surface) S = Handle(Geom_Surface)::DownCast - (static_cast(surf)->getGeometryPtr()->handle()); + Handle(Geom_Surface) S = Handle(Geom_Surface)::DownCast( + static_cast(surf)->getGeometryPtr()->handle() + ); if (S.IsNull()) { PyErr_SetString(PyExc_TypeError, "geometry is not a valid surface"); return -1; @@ -242,9 +263,11 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) for (Py::List::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); - if (sh.ShapeType() == TopAbs_WIRE) + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); + if (sh.ShapeType() == TopAbs_WIRE) { mkFace.Add(TopoDS::Wire(sh)); + } else { PyErr_SetString(PyExc_TypeError, "shape is not a wire"); return -1; @@ -274,39 +297,45 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) for (Py::List::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); - if (sh.ShapeType() == TopAbs_WIRE) + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); + if (sh.ShapeType() == TopAbs_WIRE) { wires.push_back(TopoDS::Wire(sh)); - else + } + else { Standard_Failure::Raise("shape is not a wire"); + } } - else + else { Standard_Failure::Raise("shape is not a wire"); + } } if (!wires.empty()) { BRepBuilderAPI_MakeFace mkFace(wires.front()); if (!mkFace.IsDone()) { switch (mkFace.Error()) { - case BRepBuilderAPI_NoFace: - Standard_Failure::Raise("No face"); - break; - case BRepBuilderAPI_NotPlanar: - Standard_Failure::Raise("Not planar"); - break; - case BRepBuilderAPI_CurveProjectionFailed: - Standard_Failure::Raise("Curve projection failed"); - break; - case BRepBuilderAPI_ParametersOutOfRange: - Standard_Failure::Raise("Parameters out of range"); - break; - default: - Standard_Failure::Raise("Unknown failure"); - break; + case BRepBuilderAPI_NoFace: + Standard_Failure::Raise("No face"); + break; + case BRepBuilderAPI_NotPlanar: + Standard_Failure::Raise("Not planar"); + break; + case BRepBuilderAPI_CurveProjectionFailed: + Standard_Failure::Raise("Curve projection failed"); + break; + case BRepBuilderAPI_ParametersOutOfRange: + Standard_Failure::Raise("Parameters out of range"); + break; + default: + Standard_Failure::Raise("Unknown failure"); + break; } } - for (std::vector::iterator it = wires.begin()+1; it != wires.end(); ++it) + for (std::vector::iterator it = wires.begin() + 1; it != wires.end(); + ++it) { mkFace.Add(*it); + } getTopoShapePtr()->setShape(mkFace.Face()); return 0; } @@ -325,28 +354,31 @@ int TopoShapeFacePy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); if (PyArg_ParseTuple(args, "Os", &pcPyShapeOrList, &className)) { try { - getTopoShapePtr()->makeElementFace(getPyShapes(pcPyShapeOrList),0,className); + getTopoShapePtr()->makeElementFace(getPyShapes(pcPyShapeOrList), 0, className); return 0; - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.setPyException(); return -1; - } catch (Standard_Failure& e){ + } + catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); return -1; } } - PyErr_SetString(PartExceptionOCCError, - "Argument list signature is incorrect.\n\nSupported signatures:\n" - "(face)\n" - "(wire)\n" - "(face, wire)\n" - "(surface, wire)\n" - "(list_of_wires)\n" - "(wire, facemaker_class_name)\n" - "(list_of_wires, facemaker_class_name)\n" - "(surface, list_of_wires)\n" - ); + PyErr_SetString( + PartExceptionOCCError, + "Argument list signature is incorrect.\n\nSupported signatures:\n" + "(face)\n" + "(wire)\n" + "(face, wire)\n" + "(surface, wire)\n" + "(list_of_wires)\n" + "(wire, facemaker_class_name)\n" + "(list_of_wires, facemaker_class_name)\n" + "(surface, list_of_wires)\n" + ); return -1; } @@ -375,11 +407,12 @@ face.Area Part.show(face) * \endcode */ -PyObject* TopoShapeFacePy::addWire(PyObject *args) +PyObject* TopoShapeFacePy::addWire(PyObject* args) { PyObject* wire; - if (!PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) + if (!PyArg_ParseTuple(args, "O!", &TopoShapeWirePy::Type, &wire)) { return nullptr; + } BRep_Builder aBuilder; TopoDS_Face face = TopoDS::Face(getTopoShapePtr()->getShape()); @@ -389,7 +422,7 @@ PyObject* TopoShapeFacePy::addWire(PyObject *args) Py_Return; } -PyObject* TopoShapeFacePy::makeOffset(PyObject *args) const +PyObject* TopoShapeFacePy::makeOffset(PyObject* args) const { Py::Dict dict; return TopoShapePy::makeOffset2D(args, dict.ptr()); @@ -399,33 +432,35 @@ PyObject* TopoShapeFacePy::makeOffset(PyObject *args) const import PartEnums v = App.Vector profile = Part.makePolygon([v(0.,0.,0.), v(-60.,-60.,-100.), v(-60.,-60.,-140.)]) -spine = Part.Face(Part.makePolygon([v(0.,0.,0.), v(100.,0.,0.), v(100.,100.,0.), v(0.,100.,0.), v(0.,0.,0.)])) -evolve = spine.makeEvolved(Profile=profile, Join=PartEnums.JoinType.Arc) +spine = Part.Face(Part.makePolygon([v(0.,0.,0.), v(100.,0.,0.), v(100.,100.,0.), v(0.,100.,0.), +v(0.,0.,0.)])) evolve = spine.makeEvolved(Profile=profile, Join=PartEnums.JoinType.Arc) */ -PyObject* TopoShapeFacePy::makeEvolved(PyObject *args, PyObject *kwds) const +PyObject* TopoShapeFacePy::makeEvolved(PyObject* args, PyObject* kwds) const { return TopoShapePy::makeEvolved(args, kwds); } -PyObject* TopoShapeFacePy::valueAt(PyObject *args) const +PyObject* TopoShapeFacePy::valueAt(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } auto f = getTopoDSFace(this); BRepAdaptor_Surface adapt(f); - BRepLProp_SLProps prop(adapt,u,v,0,Precision::Confusion()); + BRepLProp_SLProps prop(adapt, u, v, 0, Precision::Confusion()); const gp_Pnt& V = prop.Value(); - return new Base::VectorPy(new Base::Vector3d(V.X(),V.Y(),V.Z())); + return new Base::VectorPy(new Base::Vector3d(V.X(), V.Y(), V.Z())); } -PyObject* TopoShapeFacePy::normalAt(PyObject *args) const +PyObject* TopoShapeFacePy::normalAt(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } auto f = getTopoDSFace(this); Standard_Boolean done; @@ -438,17 +473,18 @@ PyObject* TopoShapeFacePy::normalAt(PyObject *args) const return nullptr; } - return new Base::VectorPy(new Base::Vector3d(dir.X(),dir.Y(),dir.Z())); + return new Base::VectorPy(new Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } -PyObject* TopoShapeFacePy::getUVNodes(PyObject *args) const +PyObject* TopoShapeFacePy::getUVNodes(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } auto f = getTopoDSFace(this); TopLoc_Location aLoc; - Handle (Poly_Triangulation) mesh = BRep_Tool::Triangulation(f,aLoc); + Handle(Poly_Triangulation) mesh = BRep_Tool::Triangulation(f, aLoc); if (mesh.IsNull()) { PyErr_SetString(PyExc_RuntimeError, "Face has no triangulation"); return nullptr; @@ -460,7 +496,7 @@ PyObject* TopoShapeFacePy::getUVNodes(PyObject *args) const } #if OCC_VERSION_HEX >= 0x070600 - for (int i=1; i<=mesh->NbNodes(); i++) { + for (int i = 1; i <= mesh->NbNodes(); i++) { gp_Pnt2d pt2d = mesh->UVNode(i); Py::Tuple uv(2); uv.setItem(0, Py::Float(pt2d.X())); @@ -469,7 +505,7 @@ PyObject* TopoShapeFacePy::getUVNodes(PyObject *args) const } #else const TColgp_Array1OfPnt2d& aNodesUV = mesh->UVNodes(); - for (int i=aNodesUV.Lower(); i<=aNodesUV.Upper(); i++) { + for (int i = aNodesUV.Lower(); i <= aNodesUV.Upper(); i++) { gp_Pnt2d pt2d = aNodesUV(i); Py::Tuple uv(2); uv.setItem(0, Py::Float(pt2d.X())); @@ -481,21 +517,22 @@ PyObject* TopoShapeFacePy::getUVNodes(PyObject *args) const return Py::new_reference_to(list); } -PyObject* TopoShapeFacePy::tangentAt(PyObject *args) const +PyObject* TopoShapeFacePy::tangentAt(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } gp_Dir dir; Py::Tuple tuple(2); auto f = getTopoDSFace(this); BRepAdaptor_Surface adapt(f); - BRepLProp_SLProps prop(adapt,u,v,2,Precision::Confusion()); + BRepLProp_SLProps prop(adapt, u, v, 2, Precision::Confusion()); if (prop.IsTangentUDefined()) { prop.TangentU(dir); - tuple.setItem(0, Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z()))); } else { PyErr_SetString(PartExceptionOCCError, "tangent in u not defined"); @@ -503,7 +540,7 @@ PyObject* TopoShapeFacePy::tangentAt(PyObject *args) const } if (prop.IsTangentVDefined()) { prop.TangentV(dir); - tuple.setItem(1, Py::Vector(Base::Vector3d(dir.X(),dir.Y(),dir.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z()))); } else { PyErr_SetString(PartExceptionOCCError, "tangent in v not defined"); @@ -513,17 +550,18 @@ PyObject* TopoShapeFacePy::tangentAt(PyObject *args) const return Py::new_reference_to(tuple); } -PyObject* TopoShapeFacePy::curvatureAt(PyObject *args) const +PyObject* TopoShapeFacePy::curvatureAt(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } Py::Tuple tuple(2); auto f = getTopoDSFace(this); BRepAdaptor_Surface adapt(f); - BRepLProp_SLProps prop(adapt,u,v,2,Precision::Confusion()); + BRepLProp_SLProps prop(adapt, u, v, 2, Precision::Confusion()); if (prop.IsCurvatureDefined()) { tuple.setItem(0, Py::Float(prop.MinCurvature())); tuple.setItem(1, Py::Float(prop.MaxCurvature())); @@ -536,22 +574,23 @@ PyObject* TopoShapeFacePy::curvatureAt(PyObject *args) const return Py::new_reference_to(tuple); } -PyObject* TopoShapeFacePy::derivative1At(PyObject *args) const +PyObject* TopoShapeFacePy::derivative1At(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } Py::Tuple tuple(2); auto f = getTopoDSFace(this); BRepAdaptor_Surface adapt(f); try { - BRepLProp_SLProps prop(adapt,u,v,1,Precision::Confusion()); + BRepLProp_SLProps prop(adapt, u, v, 1, Precision::Confusion()); const gp_Vec& vecU = prop.D1U(); - tuple.setItem(0, Py::Vector(Base::Vector3d(vecU.X(),vecU.Y(),vecU.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(vecU.X(), vecU.Y(), vecU.Z()))); const gp_Vec& vecV = prop.D1V(); - tuple.setItem(1, Py::Vector(Base::Vector3d(vecV.X(),vecV.Y(),vecV.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(vecV.X(), vecV.Y(), vecV.Z()))); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { @@ -560,22 +599,23 @@ PyObject* TopoShapeFacePy::derivative1At(PyObject *args) const } } -PyObject* TopoShapeFacePy::derivative2At(PyObject *args) const +PyObject* TopoShapeFacePy::derivative2At(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } Py::Tuple tuple(2); auto f = getTopoDSFace(this); BRepAdaptor_Surface adapt(f); try { - BRepLProp_SLProps prop(adapt,u,v,2,Precision::Confusion()); + BRepLProp_SLProps prop(adapt, u, v, 2, Precision::Confusion()); const gp_Vec& vecU = prop.D2U(); - tuple.setItem(0, Py::Vector(Base::Vector3d(vecU.X(),vecU.Y(),vecU.Z()))); + tuple.setItem(0, Py::Vector(Base::Vector3d(vecU.X(), vecU.Y(), vecU.Z()))); const gp_Vec& vecV = prop.D2V(); - tuple.setItem(1, Py::Vector(Base::Vector3d(vecV.X(),vecV.Y(),vecV.Z()))); + tuple.setItem(1, Py::Vector(Base::Vector3d(vecV.X(), vecV.Y(), vecV.Z()))); return Py::new_reference_to(tuple); } catch (Standard_Failure& e) { @@ -584,24 +624,25 @@ PyObject* TopoShapeFacePy::derivative2At(PyObject *args) const } } -PyObject* TopoShapeFacePy::isPartOfDomain(PyObject *args) const +PyObject* TopoShapeFacePy::isPartOfDomain(PyObject* args) const { - double u,v; - if (!PyArg_ParseTuple(args, "dd",&u,&v)) + double u, v; + if (!PyArg_ParseTuple(args, "dd", &u, &v)) { return nullptr; + } const TopoDS_Face& face = TopoDS::Face(getTopoShapePtr()->getShape()); double tol; - //double u1, u2, v1, v2, dialen; + // double u1, u2, v1, v2, dialen; tol = Precision::Confusion(); try { - //BRepTools::UVBounds(face, u1, u2, v1, v2); - //dialen = (u2-u1)*(u2-u1) + (v2-v1)*(v2-v1); - //dialen = sqrt(dialen)/400.0; - //tol = std::max(dialen, tol); - BRepTopAdaptor_FClass2d CL(face,tol); - TopAbs_State state = CL.Perform(gp_Pnt2d(u,v)); + // BRepTools::UVBounds(face, u1, u2, v1, v2); + // dialen = (u2-u1)*(u2-u1) + (v2-v1)*(v2-v1); + // dialen = sqrt(dialen)/400.0; + // tol = std::max(dialen, tol); + BRepTopAdaptor_FClass2d CL(face, tol); + TopAbs_State state = CL.Perform(gp_Pnt2d(u, v)); return PyBool_FromLong((state == TopAbs_ON || state == TopAbs_IN) ? 1 : 0); } catch (Standard_Failure& e) { @@ -610,15 +651,19 @@ PyObject* TopoShapeFacePy::isPartOfDomain(PyObject *args) const } } -PyObject* TopoShapeFacePy::makeHalfSpace(PyObject *args) const +PyObject* TopoShapeFacePy::makeHalfSpace(PyObject* args) const { PyObject* pPnt; - if (!PyArg_ParseTuple(args, "O!",&(Base::VectorPy::Type),&pPnt)) + if (!PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &pPnt)) { return nullptr; + } try { - Base::Vector3d pt = Py::Vector(pPnt,false).toVector(); - BRepPrimAPI_MakeHalfSpace mkHS(TopoDS::Face(this->getTopoShapePtr()->getShape()), gp_Pnt(pt.x,pt.y,pt.z)); + Base::Vector3d pt = Py::Vector(pPnt, false).toVector(); + BRepPrimAPI_MakeHalfSpace mkHS( + TopoDS::Face(this->getTopoShapePtr()->getShape()), + gp_Pnt(pt.x, pt.y, pt.z) + ); return new TopoShapeSolidPy(new TopoShape(mkHS.Solid())); } catch (Standard_Failure& e) { @@ -627,10 +672,11 @@ PyObject* TopoShapeFacePy::makeHalfSpace(PyObject *args) const } } -PyObject* TopoShapeFacePy::validate(PyObject *args) +PyObject* TopoShapeFacePy::validate(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { const TopoDS_Face& face = TopoDS::Face(getTopoShapePtr()->getShape()); @@ -640,7 +686,7 @@ PyObject* TopoShapeFacePy::validate(PyObject *args) TopTools_IndexedMapOfShape myMap; myMap.Add(outerwire); - TopExp_Explorer xp(face,TopAbs_WIRE); + TopExp_Explorer xp(face, TopAbs_WIRE); ShapeFix_Wire fix; fix.SetFace(face); fix.Load(outerwire); @@ -678,15 +724,16 @@ PyObject* TopoShapeFacePy::validate(PyObject *args) } } -PyObject* TopoShapeFacePy::countNodes(PyObject *args) const +PyObject* TopoShapeFacePy::countNodes(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } const TopoDS_Shape& shape = this->getTopoShapePtr()->getShape(); TopoDS_Face aFace = TopoDS::Face(shape); TopLoc_Location aLoc; - const Handle(Poly_Triangulation)& aTriangulation = BRep_Tool::Triangulation(aFace, aLoc); + const Handle(Poly_Triangulation) & aTriangulation = BRep_Tool::Triangulation(aFace, aLoc); int count = 0; if (!aTriangulation.IsNull()) { count = aTriangulation->NbNodes(); @@ -695,15 +742,16 @@ PyObject* TopoShapeFacePy::countNodes(PyObject *args) const return Py::new_reference_to(Py::Long(count)); } -PyObject* TopoShapeFacePy::countTriangles(PyObject *args) const +PyObject* TopoShapeFacePy::countTriangles(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } const TopoDS_Shape& shape = this->getTopoShapePtr()->getShape(); TopoDS_Face aFace = TopoDS::Face(shape); TopLoc_Location aLoc; - const Handle(Poly_Triangulation)& aTriangulation = BRep_Tool::Triangulation(aFace, aLoc); + const Handle(Poly_Triangulation) & aTriangulation = BRep_Tool::Triangulation(aFace, aLoc); int count = 0; if (!aTriangulation.IsNull()) { count = aTriangulation->NbTriangles(); @@ -712,11 +760,12 @@ PyObject* TopoShapeFacePy::countTriangles(PyObject *args) const return Py::new_reference_to(Py::Long(count)); } -PyObject* TopoShapeFacePy::curveOnSurface(PyObject *args) const +PyObject* TopoShapeFacePy::curveOnSurface(PyObject* args) const { PyObject* e; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapeEdgePy::Type), &e)) + if (!PyArg_ParseTuple(args, "O!", &(TopoShapeEdgePy::Type), &e)) { return nullptr; + } try { TopoDS_Shape shape = static_cast(e)->getTopoShapePtr()->getShape(); @@ -731,8 +780,9 @@ PyObject* TopoShapeFacePy::curveOnSurface(PyObject *args) const Standard_Real first, last; Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface(edge, face, first, last); std::unique_ptr geo2d = makeFromCurve2d(curve); - if (!geo2d) + if (!geo2d) { Py_Return; + } Py::Tuple tuple(3); tuple.setItem(0, Py::asObject(geo2d->getPyObject())); @@ -746,9 +796,9 @@ PyObject* TopoShapeFacePy::curveOnSurface(PyObject *args) const } } -PyObject* TopoShapeFacePy::cutHoles(PyObject *args) +PyObject* TopoShapeFacePy::cutHoles(PyObject* args) { - PyObject *holes=nullptr; + PyObject* holes = nullptr; if (PyArg_ParseTuple(args, "O!", &(PyList_Type), &holes)) { try { std::vector wires; @@ -756,38 +806,43 @@ PyObject* TopoShapeFacePy::cutHoles(PyObject *args) for (Py::List::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); - if (sh.ShapeType() == TopAbs_WIRE) + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); + if (sh.ShapeType() == TopAbs_WIRE) { wires.push_back(TopoDS::Wire(sh)); - else + } + else { Standard_Failure::Raise("shape is not a wire"); + } } - else + else { Standard_Failure::Raise("argument is not a shape"); + } } if (!wires.empty()) { auto f = getTopoDSFace(this); BRepBuilderAPI_MakeFace mkFace(f); - for (const auto & wire : wires) + for (const auto& wire : wires) { mkFace.Add(wire); + } if (!mkFace.IsDone()) { switch (mkFace.Error()) { - case BRepBuilderAPI_NoFace: - Standard_Failure::Raise("No face"); - break; - case BRepBuilderAPI_NotPlanar: - Standard_Failure::Raise("Not planar"); - break; - case BRepBuilderAPI_CurveProjectionFailed: - Standard_Failure::Raise("Curve projection failed"); - break; - case BRepBuilderAPI_ParametersOutOfRange: - Standard_Failure::Raise("Parameters out of range"); - break; - default: - Standard_Failure::Raise("Unknown failure"); - break; + case BRepBuilderAPI_NoFace: + Standard_Failure::Raise("No face"); + break; + case BRepBuilderAPI_NotPlanar: + Standard_Failure::Raise("Not planar"); + break; + case BRepBuilderAPI_CurveProjectionFailed: + Standard_Failure::Raise("Curve projection failed"); + break; + case BRepBuilderAPI_ParametersOutOfRange: + Standard_Failure::Raise("Parameters out of range"); + break; + default: + Standard_Failure::Raise("Unknown failure"); + break; } } @@ -810,75 +865,72 @@ PyObject* TopoShapeFacePy::cutHoles(PyObject *args) Py::Object TopoShapeFacePy::getSurface() const { const TopoDS_Face& f = TopoDS::Face(getTopoShapePtr()->getShape()); - if (f.IsNull()) + if (f.IsNull()) { return Py::None(); + } BRepAdaptor_Surface adapt(f); Base::PyObjectBase* surface = nullptr; - switch(adapt.GetType()) - { - case GeomAbs_Plane: - { + switch (adapt.GetType()) { + case GeomAbs_Plane: { GeomPlane* plane = new GeomPlane(); - Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast - (plane->handle()); + Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast(plane->handle()); this_surf->SetPln(adapt.Plane()); surface = new PlanePy(plane); break; } - case GeomAbs_Cylinder: - { + case GeomAbs_Cylinder: { GeomCylinder* cylinder = new GeomCylinder(); - Handle(Geom_CylindricalSurface) this_surf = Handle(Geom_CylindricalSurface)::DownCast - (cylinder->handle()); + Handle(Geom_CylindricalSurface) this_surf = Handle(Geom_CylindricalSurface)::DownCast( + cylinder->handle() + ); this_surf->SetCylinder(adapt.Cylinder()); surface = new CylinderPy(cylinder); break; } - case GeomAbs_Cone: - { + case GeomAbs_Cone: { GeomCone* cone = new GeomCone(); - Handle(Geom_ConicalSurface) this_surf = Handle(Geom_ConicalSurface)::DownCast - (cone->handle()); + Handle(Geom_ConicalSurface) this_surf = Handle(Geom_ConicalSurface)::DownCast( + cone->handle() + ); this_surf->SetCone(adapt.Cone()); surface = new ConePy(cone); break; } - case GeomAbs_Sphere: - { + case GeomAbs_Sphere: { GeomSphere* sphere = new GeomSphere(); - Handle(Geom_SphericalSurface) this_surf = Handle(Geom_SphericalSurface)::DownCast - (sphere->handle()); + Handle(Geom_SphericalSurface) this_surf = Handle(Geom_SphericalSurface)::DownCast( + sphere->handle() + ); this_surf->SetSphere(adapt.Sphere()); surface = new SpherePy(sphere); break; } - case GeomAbs_Torus: - { + case GeomAbs_Torus: { GeomToroid* toroid = new GeomToroid(); - Handle(Geom_ToroidalSurface) this_surf = Handle(Geom_ToroidalSurface)::DownCast - (toroid->handle()); + Handle(Geom_ToroidalSurface) this_surf = Handle(Geom_ToroidalSurface)::DownCast( + toroid->handle() + ); this_surf->SetTorus(adapt.Torus()); surface = new ToroidPy(toroid); break; } - case GeomAbs_BezierSurface: - { + case GeomAbs_BezierSurface: { GeomBezierSurface* surf = new GeomBezierSurface(adapt.Bezier()); surface = new BezierSurfacePy(surf); break; } - case GeomAbs_BSplineSurface: - { + case GeomAbs_BSplineSurface: { GeomBSplineSurface* surf = new GeomBSplineSurface(adapt.BSpline()); surface = new BSplineSurfacePy(surf); break; } - case GeomAbs_SurfaceOfRevolution: - { + case GeomAbs_SurfaceOfRevolution: { Handle(Geom_Surface) s = BRep_Tool::Surface(f); Handle(Geom_SurfaceOfRevolution) rev = Handle(Geom_SurfaceOfRevolution)::DownCast(s); if (rev.IsNull()) { - Handle(Geom_RectangularTrimmedSurface) rect = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) rect = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); rev = Handle(Geom_SurfaceOfRevolution)::DownCast(rect->BasisSurface()); } if (!rev.IsNull()) { @@ -890,12 +942,15 @@ Py::Object TopoShapeFacePy::getSurface() const throw Py::RuntimeError("Failed to convert to surface of revolution"); } } - case GeomAbs_SurfaceOfExtrusion: - { + case GeomAbs_SurfaceOfExtrusion: { Handle(Geom_Surface) s = BRep_Tool::Surface(f); - Handle(Geom_SurfaceOfLinearExtrusion) ext = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(s); + Handle(Geom_SurfaceOfLinearExtrusion) ext = Handle( + Geom_SurfaceOfLinearExtrusion + )::DownCast(s); if (ext.IsNull()) { - Handle(Geom_RectangularTrimmedSurface) rect = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) rect = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); ext = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast(rect->BasisSurface()); } if (!ext.IsNull()) { @@ -907,12 +962,13 @@ Py::Object TopoShapeFacePy::getSurface() const throw Py::RuntimeError("Failed to convert to surface of extrusion"); } } - case GeomAbs_OffsetSurface: - { + case GeomAbs_OffsetSurface: { Handle(Geom_Surface) s = BRep_Tool::Surface(f); Handle(Geom_OffsetSurface) off = Handle(Geom_OffsetSurface)::DownCast(s); if (off.IsNull()) { - Handle(Geom_RectangularTrimmedSurface) rect = Handle(Geom_RectangularTrimmedSurface)::DownCast(s); + Handle(Geom_RectangularTrimmedSurface) rect = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(s); off = Handle(Geom_OffsetSurface)::DownCast(rect->BasisSurface()); } if (!off.IsNull()) { @@ -924,8 +980,8 @@ Py::Object TopoShapeFacePy::getSurface() const throw Py::RuntimeError("Failed to convert to offset surface"); } } - case GeomAbs_OtherSurface: - break; + case GeomAbs_OtherSurface: + break; } if (surface) { @@ -984,8 +1040,9 @@ Py::Object TopoShapeFacePy::getWire() const Py::Object TopoShapeFacePy::getOuterWire() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); - if (shape.IsNull()) + if (shape.IsNull()) { throw Py::RuntimeError("Null shape"); + } if (shape.ShapeType() == TopAbs_FACE) { TopoDS_Wire wire = BRepTools::OuterWire(TopoDS::Face(shape)); Base::PyObjectBase* wirepy = new TopoShapeWirePy(new TopoShape(wire)); @@ -1010,7 +1067,7 @@ Py::Object TopoShapeFacePy::getCenterOfMass() const GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); gp_Pnt c = props.CentreOfMass(); - return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); + return Py::Vector(Base::Vector3d(c.X(), c.Y(), c.Z())); } Py::Object TopoShapeFacePy::getMatrixOfInertia() const @@ -1019,9 +1076,9 @@ Py::Object TopoShapeFacePy::getMatrixOfInertia() const BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); gp_Mat m = props.MatrixOfInertia(); Base::Matrix4D mat; - for (int i=0; i<3; i++) { - for (int j=0; j<3; j++) { - mat[i][j] = m(i+1,j+1); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + mat[i][j] = m(i + 1, j + 1); } } return Py::Matrix(mat); @@ -1031,8 +1088,8 @@ Py::Object TopoShapeFacePy::getStaticMoments() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); - Standard_Real lx,ly,lz; - props.StaticMoments(lx,ly,lz); + Standard_Real lx, ly, lz; + props.StaticMoments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); @@ -1049,36 +1106,42 @@ Py::Dict TopoShapeFacePy::getPrincipalProperties() const Py::Dict dict; dict.setItem("SymmetryAxis", Py::Boolean(pprops.HasSymmetryAxis() ? true : false)); dict.setItem("SymmetryPoint", Py::Boolean(pprops.HasSymmetryPoint() ? true : false)); - Standard_Real lx,ly,lz; - pprops.Moments(lx,ly,lz); + Standard_Real lx, ly, lz; + pprops.Moments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); tuple.setItem(2, Py::Float(lz)); - dict.setItem("Moments",tuple); - dict.setItem("FirstAxisOfInertia",Py::Vector(Base::convertTo - (pprops.FirstAxisOfInertia()))); - dict.setItem("SecondAxisOfInertia",Py::Vector(Base::convertTo - (pprops.SecondAxisOfInertia()))); - dict.setItem("ThirdAxisOfInertia",Py::Vector(Base::convertTo - (pprops.ThirdAxisOfInertia()))); + dict.setItem("Moments", tuple); + dict.setItem( + "FirstAxisOfInertia", + Py::Vector(Base::convertTo(pprops.FirstAxisOfInertia())) + ); + dict.setItem( + "SecondAxisOfInertia", + Py::Vector(Base::convertTo(pprops.SecondAxisOfInertia())) + ); + dict.setItem( + "ThirdAxisOfInertia", + Py::Vector(Base::convertTo(pprops.ThirdAxisOfInertia())) + ); - Standard_Real Rxx,Ryy,Rzz; - pprops.RadiusOfGyration(Rxx,Ryy,Rzz); + Standard_Real Rxx, Ryy, Rzz; + pprops.RadiusOfGyration(Rxx, Ryy, Rzz); Py::Tuple rog(3); rog.setItem(0, Py::Float(Rxx)); rog.setItem(1, Py::Float(Ryy)); rog.setItem(2, Py::Float(Rzz)); - dict.setItem("RadiusOfGyration",rog); + dict.setItem("RadiusOfGyration", rog); return dict; } -PyObject *TopoShapeFacePy::getCustomAttributes(const char* ) const +PyObject* TopoShapeFacePy::getCustomAttributes(const char*) const { return nullptr; } -int TopoShapeFacePy::setCustomAttributes(const char* , PyObject *) +int TopoShapeFacePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/TopoShapeMapper.cpp b/src/Mod/Part/App/TopoShapeMapper.cpp index c09aae9848..a073c811e3 100644 --- a/src/Mod/Part/App/TopoShapeMapper.cpp +++ b/src/Mod/Part/App/TopoShapeMapper.cpp @@ -48,18 +48,18 @@ void ShapeMapper::expand(const TopoDS_Shape& d, std::vector& shape } } -void ShapeMapper::populate(MappingStatus status, - const TopTools_ListOfShape& src, - const TopTools_ListOfShape& dst) +void ShapeMapper::populate( + MappingStatus status, + const TopTools_ListOfShape& src, + const TopTools_ListOfShape& dst +) { for (TopTools_ListIteratorOfListOfShape it(src); it.More(); it.Next()) { populate(status, it.Value(), dst); } } -void ShapeMapper::populate(MappingStatus status, - const TopoShape& src, - const TopTools_ListOfShape& dst) +void ShapeMapper::populate(MappingStatus status, const TopoShape& src, const TopTools_ListOfShape& dst) { if (src.isNull()) { return; @@ -98,9 +98,7 @@ void ShapeMapper::insert(MappingStatus status, const TopoDS_Shape& s, const Topo } }; -void ShapeMapper::insert(MappingStatus status, - const TopoDS_Shape& s, - const std::vector& d) +void ShapeMapper::insert(MappingStatus status, const TopoDS_Shape& s, const std::vector& d) { if (s.IsNull() || d.empty()) { return; @@ -158,8 +156,8 @@ void GenericShapeMapper::init(const TopoShape& src, const TopoDS_Shape& dst) TopoDS_Edge e = TopoDS::Edge(it.Current()); if (BRep_Tool::IsClosed(e)) { // closed edge, one face is enough - TopoDS_Shape face = - src.findAncestorShape(src.getSubShape(TopAbs_EDGE, idx), TopAbs_FACE); + TopoDS_Shape face + = src.findAncestorShape(src.getSubShape(TopAbs_EDGE, idx), TopAbs_FACE); if (!face.IsNull()) { this->insert(MappingStatus::Generated, face, dstFace); found = true; diff --git a/src/Mod/Part/App/TopoShapeMapper.h b/src/Mod/Part/App/TopoShapeMapper.h index 8ced574aa2..4cd0467472 100644 --- a/src/Mod/Part/App/TopoShapeMapper.h +++ b/src/Mod/Part/App/TopoShapeMapper.h @@ -97,14 +97,18 @@ struct ShapeHasher #endif return res; } - inline bool operator()(const std::pair& a, - const std::pair& b) const + inline bool operator()( + const std::pair& a, + const std::pair& b + ) const { return a.first.getShape().IsSame(b.first.getShape()) && a.second.getShape().IsSame(b.second.getShape()); } - inline bool operator()(const std::pair& a, - const std::pair& b) const + inline bool operator()( + const std::pair& a, + const std::pair& b + ) const { return a.first.IsSame(b.first) && a.second.IsSame(b.second); } @@ -141,9 +145,7 @@ struct PartExport ShapeMapper: TopoShape::Mapper * The source will be expanded into sub shapes of faces, edges and vertices * before being inserted into the map. */ - void populate(MappingStatus status, - const TopTools_ListOfShape& src, - const TopTools_ListOfShape& dst); + void populate(MappingStatus status, const TopTools_ListOfShape& src, const TopTools_ListOfShape& dst); /** Populate mapping from a source sub shape to a list of shape * @@ -154,9 +156,11 @@ struct PartExport ShapeMapper: TopoShape::Mapper * The source will be expanded into sub shapes of faces, edges and vertices * before being inserted into the map. */ - void populate(MappingStatus status, - const std::vector& src, - const std::vector& dst) + void populate( + MappingStatus status, + const std::vector& src, + const std::vector& dst + ) { for (auto& s : src) { populate(status, s, dst); @@ -241,9 +245,10 @@ struct PartExport ShapeMapper: TopoShape::Mapper /** Generic shape mapper from a given source to an output shape */ -struct PartExport GenericShapeMapper: ShapeMapper { +struct PartExport GenericShapeMapper: ShapeMapper +{ /// Populate the map with a given source shape to an output shape - void init(const TopoShape &src, const TopoDS_Shape &dst); + void init(const TopoShape& src, const TopoDS_Shape& dst); }; /// Parameters for TopoShape::makeElementFilledFace() diff --git a/src/Mod/Part/App/TopoShapeOpCode.h b/src/Mod/Part/App/TopoShapeOpCode.h index b1e4691472..5ba56fde4a 100644 --- a/src/Mod/Part/App/TopoShapeOpCode.h +++ b/src/Mod/Part/App/TopoShapeOpCode.h @@ -34,9 +34,11 @@ * to its predecessors. Some op codes can be passed to the generalized shape- * making API TopoShape::makEBoolean() to make a shape. */ -namespace Part { +namespace Part +{ -class PartExport OpCodes { +class PartExport OpCodes +{ public: /** Element name encoding scheme version number * @@ -49,56 +51,56 @@ public: /** @name Op codes that are also accepted by TopoShape::makEBoolean() */ //@{ - static constexpr const char *Fuse = "FUS"; - static constexpr const char *Cut = "CUT"; - static constexpr const char *Common = "CMN"; + static constexpr const char* Fuse = "FUS"; + static constexpr const char* Cut = "CUT"; + static constexpr const char* Common = "CMN"; static constexpr const char* Section = "SEC"; static constexpr const char* Xor = "XOR"; - static constexpr const char *Compound = "CMP"; - static constexpr const char *Compsolid = "CSD"; - static constexpr const char *Pipe = "PIP"; - static constexpr const char *Shell = "SHL"; - static constexpr const char *Wire = "WIR"; + static constexpr const char* Compound = "CMP"; + static constexpr const char* Compsolid = "CSD"; + static constexpr const char* Pipe = "PIP"; + static constexpr const char* Shell = "SHL"; + static constexpr const char* Wire = "WIR"; //@} - static constexpr const char *Tag = "TAG"; - static constexpr const char *Copy = "CPY"; - static constexpr const char *Transform = "XFM"; - static constexpr const char *Gtransform = "GFM"; - static constexpr const char *Face = "FAC"; - static constexpr const char *FilledFace = "FFC"; - static constexpr const char *Extrude = "XTR"; - static constexpr const char *GeneralFuse = "GFS"; - static constexpr const char *Refine = "RFI"; - static constexpr const char *Boolean = "BOL"; - static constexpr const char *Slice = "SLC"; - static constexpr const char *Maker = "MAK"; - static constexpr const char *Fillet = "FLT"; - static constexpr const char *Chamfer = "CHF"; - static constexpr const char *Thicken = "THK"; - static constexpr const char *Offset = "OFS"; - static constexpr const char *Offset2D = "OFF"; - static constexpr const char *Revolve = "RVL"; - static constexpr const char *Loft = "LFT"; - static constexpr const char *Sweep = "SWP"; - static constexpr const char *PipeShell = "PSH"; - static constexpr const char *ShellFill = "SHF"; - static constexpr const char *Solid = "SLD"; - static constexpr const char *RuledSurface = "RSF"; - static constexpr const char *Mirror = "MIR"; - static constexpr const char *Sketch = "SKT"; - static constexpr const char *SketchExport = "SKE"; - static constexpr const char *Shapebinder = "BND"; - static constexpr const char *ThruSections = "TRU"; - static constexpr const char *Sewing = "SEW"; - static constexpr const char *Prism = "PSM"; - static constexpr const char *Draft = "DFT"; - static constexpr const char *HalfSpace = "HSP"; - static constexpr const char *BSplineFace = "BSF"; - static constexpr const char *Split = "SPT"; - static constexpr const char *Evolve = "EVO"; + static constexpr const char* Tag = "TAG"; + static constexpr const char* Copy = "CPY"; + static constexpr const char* Transform = "XFM"; + static constexpr const char* Gtransform = "GFM"; + static constexpr const char* Face = "FAC"; + static constexpr const char* FilledFace = "FFC"; + static constexpr const char* Extrude = "XTR"; + static constexpr const char* GeneralFuse = "GFS"; + static constexpr const char* Refine = "RFI"; + static constexpr const char* Boolean = "BOL"; + static constexpr const char* Slice = "SLC"; + static constexpr const char* Maker = "MAK"; + static constexpr const char* Fillet = "FLT"; + static constexpr const char* Chamfer = "CHF"; + static constexpr const char* Thicken = "THK"; + static constexpr const char* Offset = "OFS"; + static constexpr const char* Offset2D = "OFF"; + static constexpr const char* Revolve = "RVL"; + static constexpr const char* Loft = "LFT"; + static constexpr const char* Sweep = "SWP"; + static constexpr const char* PipeShell = "PSH"; + static constexpr const char* ShellFill = "SHF"; + static constexpr const char* Solid = "SLD"; + static constexpr const char* RuledSurface = "RSF"; + static constexpr const char* Mirror = "MIR"; + static constexpr const char* Sketch = "SKT"; + static constexpr const char* SketchExport = "SKE"; + static constexpr const char* Shapebinder = "BND"; + static constexpr const char* ThruSections = "TRU"; + static constexpr const char* Sewing = "SEW"; + static constexpr const char* Prism = "PSM"; + static constexpr const char* Draft = "DFT"; + static constexpr const char* HalfSpace = "HSP"; + static constexpr const char* BSplineFace = "BSF"; + static constexpr const char* Split = "SPT"; + static constexpr const char* Evolve = "EVO"; }; -} // namespace Part +} // namespace Part -#endif // PART_TOPOSHAPE_OPCODE_H +#endif // PART_TOPOSHAPE_OPCODE_H diff --git a/src/Mod/Part/App/TopoShapePyImp.cpp b/src/Mod/Part/App/TopoShapePyImp.cpp index ff4b343828..b389f0443e 100644 --- a/src/Mod/Part/App/TopoShapePyImp.cpp +++ b/src/Mod/Part/App/TopoShapePyImp.cpp @@ -22,49 +22,49 @@ * * ***************************************************************************/ -# include -# include -# include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -104,21 +104,26 @@ using namespace Part; static Py_hash_t _TopoShapeHash(PyObject* self) { if (!self) { - PyErr_SetString(PyExc_TypeError, - "descriptor 'hash' of 'Part.TopoShape' object needs an argument"); + PyErr_SetString( + PyExc_TypeError, + "descriptor 'hash' of 'Part.TopoShape' object needs an argument" + ); return 0; } if (!static_cast(self)->isValid()) { - PyErr_SetString(PyExc_ReferenceError, - "This object is already deleted most likely through closing a document. " - "This reference is no longer valid!"); + PyErr_SetString( + PyExc_ReferenceError, + "This object is already deleted most likely through closing a document. " + "This reference is no longer valid!" + ); return 0; } #if OCC_VERSION_HEX >= 0x070800 return std::hash {}(static_cast(self)->getTopoShapePtr()->getShape()); #else return static_cast(self)->getTopoShapePtr()->getShape().HashCode( - std::numeric_limits::max()); + std::numeric_limits::max() + ); #endif } @@ -139,7 +144,7 @@ std::string TopoShapePy::representation() const return str.str(); } -PyObject *TopoShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* TopoShapePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of TopoShapePy and the Twin object return new TopoShapePy(new TopoShape); @@ -147,24 +152,22 @@ PyObject *TopoShapePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // int TopoShapePy::PyInit(PyObject* args, PyObject* keywds) { - static const std::array kwlist{ "shape", - "op", - "tag", - "hasher", - nullptr }; + static const std::array kwlist {"shape", "op", "tag", "hasher", nullptr}; long tag = 0; PyObject* pyHasher = nullptr; const char* op = nullptr; PyObject* pcObj = nullptr; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "|OsiO!", - kwlist, - &pcObj, - &op, - &tag, - &App::StringHasherPy::Type, - &pyHasher)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "|OsiO!", + kwlist, + &pcObj, + &op, + &tag, + &App::StringHasherPy::Type, + &pyHasher + )) { return -1; } auto& self = *getTopoShapePtr(); @@ -200,21 +203,23 @@ int TopoShapePy::PyInit(PyObject* args, PyObject* keywds) return 0; } -PyObject* TopoShapePy::copy(PyObject *args) const +PyObject* TopoShapePy::copy(PyObject* args) const { PyObject* copyGeom = Py_True; PyObject* copyMesh = Py_False; const char* op = nullptr; PyObject* pyHasher = nullptr; - if (!PyArg_ParseTuple(args, - "|sO!O!O!", - &op, - &App::StringHasherPy::Type, - &pyHasher, - &PyBool_Type, - ©Geom, - &PyBool_Type, - ©Mesh)) { + if (!PyArg_ParseTuple( + args, + "|sO!O!O!", + &op, + &App::StringHasherPy::Type, + &pyHasher, + &PyBool_Type, + ©Geom, + &PyBool_Type, + ©Mesh + )) { PyErr_Clear(); if (!PyArg_ParseTuple(args, "|O!O!", &PyBool_Type, ©Geom, &PyBool_Type, ©Mesh)) { return 0; @@ -230,13 +235,15 @@ PyObject* TopoShapePy::copy(PyObject *args) const auto& self = *getTopoShapePtr(); return Py::new_reference_to(shape2pyshape( TopoShape(self.Tag, hasher) - .makeElementCopy(self, op, PyObject_IsTrue(copyGeom), PyObject_IsTrue(copyMesh)))); + .makeElementCopy(self, op, PyObject_IsTrue(copyGeom), PyObject_IsTrue(copyMesh)) + )); } -PyObject* TopoShapePy::cleaned(PyObject *args) const +PyObject* TopoShapePy::cleaned(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } auto& self = *getTopoShapePtr(); TopoShape copy(self.makeElementCopy()); if (!copy.isNull()) { @@ -245,11 +252,12 @@ PyObject* TopoShapePy::cleaned(PyObject *args) const return Py::new_reference_to(shape2pyshape(copy)); } -PyObject* TopoShapePy::replaceShape(PyObject *args) const +PyObject* TopoShapePy::replaceShape(PyObject* args) const { - PyObject *l; - if (!PyArg_ParseTuple(args, "O",&l)) + PyObject* l; + if (!PyArg_ParseTuple(args, "O", &l)) { return nullptr; + } try { Py::Sequence list(l); @@ -258,8 +266,12 @@ PyObject* TopoShapePy::replaceShape(PyObject *args) const Py::Tuple tuple(*it); Py::TopoShape sh1(tuple[0]); Py::TopoShape sh2(tuple[1]); - shapes.push_back(std::make_pair(*sh1.extensionObject()->getTopoShapePtr(), - *sh2.extensionObject()->getTopoShapePtr())); + shapes.push_back( + std::make_pair( + *sh1.extensionObject()->getTopoShapePtr(), + *sh2.extensionObject()->getTopoShapePtr() + ) + ); } return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->replaceElementShape(shapes))); } @@ -272,15 +284,17 @@ PyObject* TopoShapePy::replaceShape(PyObject *args) const } } -PyObject* TopoShapePy::removeShape(PyObject *args) const +PyObject* TopoShapePy::removeShape(PyObject* args) const { - PyObject *l; - if (!PyArg_ParseTuple(args, "O",&l)) + PyObject* l; + if (!PyArg_ParseTuple(args, "O", &l)) { return nullptr; + } try { return Py::new_reference_to( - shape2pyshape(getTopoShapePtr()->removeElementShape(getPyShapes(l)))); + shape2pyshape(getTopoShapePtr()->removeElementShape(getPyShapes(l))) + ); } catch (...) { PyErr_SetString(PartExceptionOCCError, "failed to remove shape"); @@ -288,11 +302,12 @@ PyObject* TopoShapePy::removeShape(PyObject *args) const } } -PyObject* TopoShapePy::read(PyObject *args) +PyObject* TopoShapePy::read(PyObject* args) { char* Name; - if (!PyArg_ParseTuple(args, "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args, "et", "utf-8", &Name)) { return nullptr; + } std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -301,15 +316,14 @@ PyObject* TopoShapePy::read(PyObject *args) Py_Return; } -PyObject* TopoShapePy::writeInventor(PyObject * args, PyObject * keywds) const +PyObject* TopoShapePy::writeInventor(PyObject* args, PyObject* keywds) const { - static const std::array kwlist{"Mode", "Deviation", "Angle", "FaceColors", nullptr}; + static const std::array kwlist {"Mode", "Deviation", "Angle", "FaceColors", nullptr}; double dev = 0.3, angle = 0.4; int mode = 2; - PyObject *pylist = nullptr; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "|iddO", kwlist, - &mode, &dev, &angle, &pylist)) { + PyObject* pylist = nullptr; + if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "|iddO", kwlist, &mode, &dev, &angle, &pylist)) { return nullptr; } @@ -321,7 +335,7 @@ PyObject* TopoShapePy::writeInventor(PyObject * args, PyObject * keywds) const } std::stringstream result; - BRepMesh_IncrementalMesh(getTopoShapePtr()->getShape(),dev); + BRepMesh_IncrementalMesh(getTopoShapePtr()->getShape(), dev); if (mode == 0) { getTopoShapePtr()->exportFaceSet(dev, angle, faceColors, result); } @@ -335,11 +349,12 @@ PyObject* TopoShapePy::writeInventor(PyObject * args, PyObject * keywds) const return Py::new_reference_to(Py::String(result.str())); } -PyObject* TopoShapePy::exportIges(PyObject *args) const +PyObject* TopoShapePy::exportIges(PyObject* args) const { char* Name; - if (!PyArg_ParseTuple(args, "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args, "et", "utf-8", &Name)) { return nullptr; + } std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -349,18 +364,19 @@ PyObject* TopoShapePy::exportIges(PyObject *args) const getTopoShapePtr()->exportIges(EncodedName.c_str()); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } Py_Return; } -PyObject* TopoShapePy::exportStep(PyObject *args) const +PyObject* TopoShapePy::exportStep(PyObject* args) const { char* Name; - if (!PyArg_ParseTuple(args, "et","utf-8",&Name)) + if (!PyArg_ParseTuple(args, "et", "utf-8", &Name)) { return nullptr; + } std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -370,17 +386,17 @@ PyObject* TopoShapePy::exportStep(PyObject *args) const getTopoShapePtr()->exportStep(EncodedName.c_str()); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } Py_Return; } -PyObject* TopoShapePy::exportBrep(PyObject *args) const +PyObject* TopoShapePy::exportBrep(PyObject* args) const { char* Name; - if (PyArg_ParseTuple(args, "et","utf-8",&Name)) { + if (PyArg_ParseTuple(args, "et", "utf-8", &Name)) { std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -389,7 +405,7 @@ PyObject* TopoShapePy::exportBrep(PyObject *args) const getTopoShapePtr()->exportBrep(EncodedName.c_str()); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } @@ -408,7 +424,7 @@ PyObject* TopoShapePy::exportBrep(PyObject *args) const getTopoShapePtr()->exportBrep(str); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } @@ -419,11 +435,12 @@ PyObject* TopoShapePy::exportBrep(PyObject *args) const return nullptr; } -PyObject* TopoShapePy::exportBinary(PyObject *args) const +PyObject* TopoShapePy::exportBinary(PyObject* args) const { char* input; - if (!PyArg_ParseTuple(args, "s", &input)) + if (!PyArg_ParseTuple(args, "s", &input)) { return nullptr; + } try { // read binary brep @@ -433,17 +450,18 @@ PyObject* TopoShapePy::exportBinary(PyObject *args) const str.close(); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } Py_Return; } -PyObject* TopoShapePy::dumpToString(PyObject *args) const +PyObject* TopoShapePy::dumpToString(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { std::stringstream str; @@ -451,11 +469,11 @@ PyObject* TopoShapePy::dumpToString(PyObject *args) const return Py::new_reference_to(Py::String(str.str())); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (const std::exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (Standard_Failure& e) { @@ -465,10 +483,11 @@ PyObject* TopoShapePy::dumpToString(PyObject *args) const } } -PyObject* TopoShapePy::exportBrepToString(PyObject *args) const +PyObject* TopoShapePy::exportBrepToString(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { // write brep file @@ -477,11 +496,11 @@ PyObject* TopoShapePy::exportBrepToString(PyObject *args) const return Py::new_reference_to(Py::String(str.str())); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (const std::exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (Standard_Failure& e) { @@ -490,10 +509,10 @@ PyObject* TopoShapePy::exportBrepToString(PyObject *args) const } } -PyObject* TopoShapePy::importBrep(PyObject *args) +PyObject* TopoShapePy::importBrep(PyObject* args) { char* Name; - if (PyArg_ParseTuple(args, "et","utf-8",&Name)) { + if (PyArg_ParseTuple(args, "et", "utf-8", &Name)) { std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -502,7 +521,7 @@ PyObject* TopoShapePy::importBrep(PyObject *args) getTopoShapePtr()->importBrep(EncodedName.c_str()); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } @@ -520,7 +539,7 @@ PyObject* TopoShapePy::importBrep(PyObject *args) getTopoShapePtr()->importBrep(str); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } @@ -531,11 +550,12 @@ PyObject* TopoShapePy::importBrep(PyObject *args) return nullptr; } -PyObject* TopoShapePy::importBinary(PyObject *args) +PyObject* TopoShapePy::importBinary(PyObject* args) { char* input; - if (!PyArg_ParseTuple(args, "s", &input)) + if (!PyArg_ParseTuple(args, "s", &input)) { return nullptr; + } try { // read binary brep @@ -545,31 +565,32 @@ PyObject* TopoShapePy::importBinary(PyObject *args) str.close(); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } Py_Return; } -PyObject* TopoShapePy::importBrepFromString(PyObject *args) +PyObject* TopoShapePy::importBrepFromString(PyObject* args) { char* input; - int indicator=1; - if (!PyArg_ParseTuple(args, "s|i", &input, &indicator)) + int indicator = 1; + if (!PyArg_ParseTuple(args, "s|i", &input, &indicator)) { return nullptr; + } try { // read brep std::stringstream str(input); - getTopoShapePtr()->importBrep(str,indicator); + getTopoShapePtr()->importBrep(str, indicator); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (const std::exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (Standard_Failure& e) { @@ -586,9 +607,10 @@ PyObject* TopoShapePy::dumps(PyObject* args) const } -PyObject* TopoShapePy::loads(PyObject *args) { - if (! getTopoShapePtr()) { - PyErr_SetString(Base::PyExc_FC_GeneralError,"no c++ object"); +PyObject* TopoShapePy::loads(PyObject* args) +{ + if (!getTopoShapePtr()) { + PyErr_SetString(Base::PyExc_FC_GeneralError, "no c++ object"); return nullptr; } else { @@ -596,12 +618,13 @@ PyObject* TopoShapePy::loads(PyObject *args) { } } -PyObject* TopoShapePy::exportStl(PyObject *args) const +PyObject* TopoShapePy::exportStl(PyObject* args) const { double deflection = 0.01; char* Name; - if (!PyArg_ParseTuple(args, "et|d","utf-8",&Name,&deflection)) + if (!PyArg_ParseTuple(args, "et|d", "utf-8", &Name, &deflection)) { return nullptr; + } std::string EncodedName = std::string(Name); PyMem_Free(Name); @@ -611,7 +634,7 @@ PyObject* TopoShapePy::exportStl(PyObject *args) const getTopoShapePtr()->exportStl(EncodedName.c_str(), deflection); } catch (const Base::Exception& e) { - PyErr_SetString(PartExceptionOCCError,e.what()); + PyErr_SetString(PartExceptionOCCError, e.what()); return nullptr; } catch (Standard_Failure& e) { @@ -622,16 +645,18 @@ PyObject* TopoShapePy::exportStl(PyObject *args) const Py_Return; } -PyObject* TopoShapePy::extrude(PyObject *args) const +PyObject* TopoShapePy::extrude(PyObject* args) const { - PyObject *pVec; - if (!PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &pVec)) + PyObject* pVec; + if (!PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &pVec)) { return nullptr; + } try { Base::Vector3d vec = static_cast(pVec)->value(); return Py::new_reference_to( - shape2pyshape(getTopoShapePtr()->makeElementPrism(gp_Vec(vec.x, vec.y, vec.z)))); + shape2pyshape(getTopoShapePtr()->makeElementPrism(gp_Vec(vec.x, vec.y, vec.z))) + ); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -639,18 +664,30 @@ PyObject* TopoShapePy::extrude(PyObject *args) const } } -PyObject* TopoShapePy::revolve(PyObject *args) const +PyObject* TopoShapePy::revolve(PyObject* args) const { - PyObject *pPos,*pDir; - double angle=360; - if (!PyArg_ParseTuple(args, "O!O!|d", &(Base::VectorPy::Type), &pPos, &(Base::VectorPy::Type), &pDir,&angle)) + PyObject *pPos, *pDir; + double angle = 360; + if (!PyArg_ParseTuple( + args, + "O!O!|d", + &(Base::VectorPy::Type), + &pPos, + &(Base::VectorPy::Type), + &pDir, + &angle + )) { return nullptr; + } Base::Vector3d pos = static_cast(pPos)->value(); Base::Vector3d dir = static_cast(pDir)->value(); try { - return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementRevolve( - gp_Ax1(gp_Pnt(pos.x, pos.y, pos.z), gp_Dir(dir.x, dir.y, dir.z)), - Base::toRadians(angle)))); + return Py::new_reference_to(shape2pyshape( + getTopoShapePtr()->makeElementRevolve( + gp_Ax1(gp_Pnt(pos.x, pos.y, pos.z), gp_Dir(dir.x, dir.y, dir.z)), + Base::toRadians(angle) + ) + )); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -658,11 +695,12 @@ PyObject* TopoShapePy::revolve(PyObject *args) const } } -PyObject* TopoShapePy::check(PyObject *args) const +PyObject* TopoShapePy::check(PyObject* args) const { PyObject* runBopCheck = Py_False; - if (!PyArg_ParseTuple(args, "|O!", &(PyBool_Type), &runBopCheck)) + if (!PyArg_ParseTuple(args, "|O!", &(PyBool_Type), &runBopCheck)) { return nullptr; + } if (!getTopoShapePtr()->getShape().IsNull()) { std::stringstream str; @@ -675,45 +713,50 @@ PyObject* TopoShapePy::check(PyObject *args) const Py_Return; } -static PyObject *makeShape(const char *op,const TopoShape &shape, PyObject *args) { - double tol=0; - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O|d", &pcObj,&tol)) +static PyObject* makeShape(const char* op, const TopoShape& shape, PyObject* args) +{ + double tol = 0; + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O|d", &pcObj, &tol)) { return 0; - PY_TRY { + } + PY_TRY + { std::vector shapes; shapes.push_back(shape); - getPyShapes(pcObj,shapes); - return Py::new_reference_to(shape2pyshape(TopoShape().makeElementBoolean(op,shapes,0,tol))); - } PY_CATCH_OCC + getPyShapes(pcObj, shapes); + return Py::new_reference_to(shape2pyshape(TopoShape().makeElementBoolean(op, shapes, 0, tol))); + } + PY_CATCH_OCC } -PyObject* TopoShapePy::fuse(PyObject *args) const +PyObject* TopoShapePy::fuse(PyObject* args) const { return makeShape(Part::OpCodes::Fuse, *getTopoShapePtr(), args); } -PyObject* TopoShapePy::multiFuse(PyObject *args) const +PyObject* TopoShapePy::multiFuse(PyObject* args) const { return makeShape(Part::OpCodes::Fuse, *getTopoShapePtr(), args); } -PyObject* TopoShapePy::common(PyObject *args) const +PyObject* TopoShapePy::common(PyObject* args) const { return makeShape(Part::OpCodes::Common, *getTopoShapePtr(), args); } -PyObject* TopoShapePy::section(PyObject *args) const +PyObject* TopoShapePy::section(PyObject* args) const { return makeShape(Part::OpCodes::Section, *getTopoShapePtr(), args); } -PyObject* TopoShapePy::slice(PyObject *args) const +PyObject* TopoShapePy::slice(PyObject* args) const { - PyObject *dir; + PyObject* dir; double d; - if (!PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type), &dir, &d)) + if (!PyArg_ParseTuple(args, "O!d", &(Base::VectorPy::Type), &dir, &d)) { return nullptr; + } Base::Vector3d vec = Py::Vector(dir, false).toVector(); @@ -735,19 +778,21 @@ PyObject* TopoShapePy::slice(PyObject *args) const } } -PyObject* TopoShapePy::slices(PyObject *args) const +PyObject* TopoShapePy::slices(PyObject* args) const { PyObject *dir, *dist; - if (!PyArg_ParseTuple(args, "O!O", &(Base::VectorPy::Type), &dir, &dist)) + if (!PyArg_ParseTuple(args, "O!O", &(Base::VectorPy::Type), &dir, &dist)) { return nullptr; + } try { Base::Vector3d vec = Py::Vector(dir, false).toVector(); Py::Sequence list(dist); std::vector d; d.reserve(list.size()); - for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) + for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { d.push_back((double)Py::Float(*it)); + } return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementSlices(vec, d))); } catch (Standard_Failure& e) { @@ -760,17 +805,18 @@ PyObject* TopoShapePy::slices(PyObject *args) const } } -PyObject* TopoShapePy::cut(PyObject *args) const +PyObject* TopoShapePy::cut(PyObject* args) const { return makeShape(Part::OpCodes::Cut, *getTopoShapePtr(), args); } -PyObject* TopoShapePy::generalFuse(PyObject *args) const +PyObject* TopoShapePy::generalFuse(PyObject* args) const { double tolerance = 0.0; - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O|d", &pcObj, &tolerance)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O|d", &pcObj, &tolerance)) { return nullptr; + } std::vector> modifies; std::vector shapes; @@ -795,11 +841,12 @@ PyObject* TopoShapePy::generalFuse(PyObject *args) const PY_CATCH_OCC } -PyObject* TopoShapePy::sewShape(PyObject *args) +PyObject* TopoShapePy::sewShape(PyObject* args) { double tolerance = 1.0e-06; - if (!PyArg_ParseTuple(args, "|d", &tolerance)) + if (!PyArg_ParseTuple(args, "|d", &tolerance)) { return nullptr; + } try { getTopoShapePtr()->sewShape(); @@ -811,12 +858,13 @@ PyObject* TopoShapePy::sewShape(PyObject *args) } } -PyObject* TopoShapePy::childShapes(PyObject *args) const +PyObject* TopoShapePy::childShapes(PyObject* args) const { PyObject* cumOri = Py_True; PyObject* cumLoc = Py_True; - if (!PyArg_ParseTuple(args, "|O!O!", &(PyBool_Type), &cumOri, &(PyBool_Type), &cumLoc)) + if (!PyArg_ParseTuple(args, "|O!O!", &(PyBool_Type), &cumOri, &(PyBool_Type), &cumLoc)) { return nullptr; + } TopoShape shape = *getTopoShapePtr(); if (!PyObject_IsTrue(cumOri)) { @@ -836,7 +884,8 @@ PyObject* TopoShapePy::childShapes(PyObject *args) const PY_CATCH_OCC } -namespace Part { +namespace Part +{ // Containers to associate TopAbs_ShapeEnum values to each TopoShape*Py class static const std::vector> vecTypeShape = { {&TopoShapeCompoundPy::Type, TopAbs_COMPOUND}, @@ -851,31 +900,34 @@ static const std::vector> vecTypeShap }; static const std::map mapTypeShape( - vecTypeShape.begin(), vecTypeShape.end()); + vecTypeShape.begin(), + vecTypeShape.end() +); // Returns shape type of a Python type. Similar to TopAbs::ShapeTypeFromString. // Returns TopAbs_SHAPE if pyType is not a subclass of any of the TopoShape*Py. static TopAbs_ShapeEnum ShapeTypeFromPyType(PyTypeObject* pyType) { - for (const auto & it : vecTypeShape) { - if (PyType_IsSubtype(pyType, it.first)) + for (const auto& it : vecTypeShape) { + if (PyType_IsSubtype(pyType, it.first)) { return it.second; + } } return TopAbs_SHAPE; } -} +} // namespace Part -PyObject* TopoShapePy::ancestorsOfType(PyObject *args) const +PyObject* TopoShapePy::ancestorsOfType(PyObject* args) const { - PyObject *pcObj; - PyObject *type; - if (!PyArg_ParseTuple(args, "O!O!", &(TopoShapePy::Type), &pcObj, &PyType_Type, &type)) + PyObject* pcObj; + PyObject* type; + if (!PyArg_ParseTuple(args, "O!O!", &(TopoShapePy::Type), &pcObj, &PyType_Type, &type)) { return nullptr; + } try { const TopoDS_Shape& model = getTopoShapePtr()->getShape(); - const TopoDS_Shape& shape = static_cast(pcObj)-> - getTopoShapePtr()->getShape(); + const TopoDS_Shape& shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); if (model.IsNull() || shape.IsNull()) { PyErr_SetString(PyExc_ValueError, "Shape is null"); return nullptr; @@ -897,7 +949,7 @@ PyObject* TopoShapePy::ancestorsOfType(PyObject *args) const TopTools_ListIteratorOfListOfShape it(ancestors); for (; it.More(); it.Next()) { // make sure to avoid duplicates - Standard_Integer code = ShapeMapHasher{}(it.Value()); + Standard_Integer code = ShapeMapHasher {}(it.Value()); if (hashes.find(code) == hashes.end()) { list.append(shape2pyshape(it.Value())); hashes.insert(code); @@ -912,11 +964,12 @@ PyObject* TopoShapePy::ancestorsOfType(PyObject *args) const } } -PyObject* TopoShapePy::removeInternalWires(PyObject *args) +PyObject* TopoShapePy::removeInternalWires(PyObject* args) { double minArea; - if (!PyArg_ParseTuple(args, "d",&minArea)) + if (!PyArg_ParseTuple(args, "d", &minArea)) { return nullptr; + } try { bool ok = getTopoShapePtr()->removeInternalWires(minArea); @@ -930,17 +983,18 @@ PyObject* TopoShapePy::removeInternalWires(PyObject *args) } } -PyObject* TopoShapePy::mirror(PyObject *args) const +PyObject* TopoShapePy::mirror(PyObject* args) const { PyObject *v1, *v2; - if (!PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type),&v1, &(Base::VectorPy::Type),&v2)) + if (!PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &v1, &(Base::VectorPy::Type), &v2)) { return nullptr; + } - Base::Vector3d base = Py::Vector(v1,false).toVector(); - Base::Vector3d norm = Py::Vector(v2,false).toVector(); + Base::Vector3d base = Py::Vector(v1, false).toVector(); + Base::Vector3d norm = Py::Vector(v2, false).toVector(); try { - gp_Ax2 ax2(gp_Pnt(base.x,base.y,base.z), gp_Dir(norm.x,norm.y,norm.z)); + gp_Ax2 ax2(gp_Pnt(base.x, base.y, base.z), gp_Dir(norm.x, norm.y, norm.z)); return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementMirror(ax2))); } catch (Standard_Failure& e) { @@ -949,12 +1003,13 @@ PyObject* TopoShapePy::mirror(PyObject *args) const } } -PyObject* TopoShapePy::transformGeometry(PyObject *args) const +PyObject* TopoShapePy::transformGeometry(PyObject* args) const { - PyObject *obj; - PyObject *cpy = Py_False; - if (!PyArg_ParseTuple(args, "O!|O!", &(Base::MatrixPy::Type), &obj, &PyBool_Type, &cpy)) + PyObject* obj; + PyObject* cpy = Py_False; + if (!PyArg_ParseTuple(args, "O!|O!", &(Base::MatrixPy::Type), &obj, &PyBool_Type, &cpy)) { return nullptr; + } try { Base::Matrix4D mat = static_cast(obj)->value(); @@ -967,50 +1022,73 @@ PyObject* TopoShapePy::transformGeometry(PyObject *args) const } } -PyObject* TopoShapePy::transformShape(PyObject *args) +PyObject* TopoShapePy::transformShape(PyObject* args) { - PyObject *obj; - PyObject *copy = Py_False; - PyObject *checkScale = Py_False; - if (!PyArg_ParseTuple(args, "O!|O!O!", &(Base::MatrixPy::Type),&obj,&(PyBool_Type), ©, &(PyBool_Type), &checkScale)) + PyObject* obj; + PyObject* copy = Py_False; + PyObject* checkScale = Py_False; + if (!PyArg_ParseTuple( + args, + "O!|O!O!", + &(Base::MatrixPy::Type), + &obj, + &(PyBool_Type), + ©, + &(PyBool_Type), + &checkScale + )) { return nullptr; + } Base::Matrix4D mat = static_cast(obj)->value(); - PY_TRY { + PY_TRY + { this->getTopoShapePtr()->transformShape(mat, Base::asBoolean(copy), Base::asBoolean(checkScale)); return IncRef(); } PY_CATCH_OCC } -PyObject* TopoShapePy::transformed(PyObject *args, PyObject *keywds) const +PyObject* TopoShapePy::transformed(PyObject* args, PyObject* keywds) const { - static const std::array kwlist{"matrix", "copy", "checkScale", "op", nullptr}; - PyObject *pymat; - PyObject *copy = Py_False; - PyObject *checkScale = Py_False; - const char *op = nullptr; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "O!|O!O!s", kwlist, - &Base::MatrixPy::Type, &pymat, &PyBool_Type, ©, &PyBool_Type, - &checkScale, &op)) { + static const std::array kwlist {"matrix", "copy", "checkScale", "op", nullptr}; + PyObject* pymat; + PyObject* copy = Py_False; + PyObject* checkScale = Py_False; + const char* op = nullptr; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "O!|O!O!s", + kwlist, + &Base::MatrixPy::Type, + &pymat, + &PyBool_Type, + ©, + &PyBool_Type, + &checkScale, + &op + )) { return nullptr; } Base::Matrix4D mat = static_cast(pymat)->value(); (void)op; - PY_TRY { + PY_TRY + { TopoShape s(*getTopoShapePtr()); - s.transformShape(mat,Base::asBoolean(copy), Base::asBoolean(checkScale)); + s.transformShape(mat, Base::asBoolean(copy), Base::asBoolean(checkScale)); return Py::new_reference_to(shape2pyshape(s)); } PY_CATCH_OCC } -PyObject* TopoShapePy::translate(PyObject *args) +PyObject* TopoShapePy::translate(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } Base::Vector3d vec; if (PyObject_TypeCheck(obj, &(Base::VectorPy::Type))) { @@ -1025,7 +1103,7 @@ PyObject* TopoShapePy::translate(PyObject *args) } gp_Trsf mov; - mov.SetTranslation(gp_Vec(vec.x,vec.y,vec.z)); + mov.SetTranslation(gp_Vec(vec.x, vec.y, vec.z)); TopLoc_Location loc(mov); TopoDS_Shape shape = getTopoShapePtr()->getShape(); shape.Move(loc); @@ -1034,23 +1112,23 @@ PyObject* TopoShapePy::translate(PyObject *args) return IncRef(); } -PyObject* TopoShapePy::rotate(PyObject *args) +PyObject* TopoShapePy::rotate(PyObject* args) { PyObject *obj1, *obj2; double angle; - if (!PyArg_ParseTuple(args, "OOd", &obj1, &obj2, &angle)) + if (!PyArg_ParseTuple(args, "OOd", &obj1, &obj2, &angle)) { return nullptr; + } - PY_TRY { + PY_TRY + { // Vector also supports sequence Py::Sequence p1(obj1), p2(obj2); // Convert into OCC representation - gp_Pnt pos = gp_Pnt((double)Py::Float(p1[0]), - (double)Py::Float(p1[1]), - (double)Py::Float(p1[2])); - gp_Dir dir = gp_Dir((double)Py::Float(p2[0]), - (double)Py::Float(p2[1]), - (double)Py::Float(p2[2])); + gp_Pnt pos + = gp_Pnt((double)Py::Float(p1[0]), (double)Py::Float(p1[1]), (double)Py::Float(p1[2])); + gp_Dir dir + = gp_Dir((double)Py::Float(p2[0]), (double)Py::Float(p2[1]), (double)Py::Float(p2[2])); gp_Ax1 axis(pos, dir); gp_Trsf mov; @@ -1065,14 +1143,15 @@ PyObject* TopoShapePy::rotate(PyObject *args) PY_CATCH_OCC } -PyObject* TopoShapePy::scale(PyObject *args) +PyObject* TopoShapePy::scale(PyObject* args) { double factor; - PyObject* p=nullptr; - if (!PyArg_ParseTuple(args, "d|O!", &factor, &(Base::VectorPy::Type), &p)) + PyObject* p = nullptr; + if (!PyArg_ParseTuple(args, "d|O!", &factor, &(Base::VectorPy::Type), &p)) { return nullptr; + } - gp_Pnt pos(0,0,0); + gp_Pnt pos(0, 0, 0); if (p) { Base::Vector3d pnt = static_cast(p)->value(); pos.SetX(pnt.x); @@ -1084,7 +1163,8 @@ PyObject* TopoShapePy::scale(PyObject *args) return nullptr; } - PY_TRY { + PY_TRY + { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); if (!shape.IsNull()) { gp_Trsf scl; @@ -1100,44 +1180,47 @@ PyObject* TopoShapePy::scale(PyObject *args) PY_CATCH_OCC } -PyObject* TopoShapePy::translated(PyObject *args) const +PyObject* TopoShapePy::translated(PyObject* args) const { Py::Object pyobj(shape2pyshape(*getTopoShapePtr())); return static_cast(pyobj.ptr())->translate(args); } -PyObject* TopoShapePy::rotated(PyObject *args) const +PyObject* TopoShapePy::rotated(PyObject* args) const { Py::Object pyobj(shape2pyshape(*getTopoShapePtr())); return static_cast(pyobj.ptr())->rotate(args); } -PyObject* TopoShapePy::scaled(PyObject *args) const +PyObject* TopoShapePy::scaled(PyObject* args) const { Py::Object pyobj(shape2pyshape(*getTopoShapePtr())); return static_cast(pyobj.ptr())->scale(args); } -PyObject* TopoShapePy::makeFillet(PyObject *args) const +PyObject* TopoShapePy::makeFillet(PyObject* args) const { // use two radii for all edges double radius1, radius2; - PyObject *obj; + PyObject* obj; if (!PyArg_ParseTuple(args, "ddO", &radius1, &radius2, &obj)) { PyErr_Clear(); if (!PyArg_ParseTuple(args, "dO", &radius1, &obj)) { - PyErr_SetString(PyExc_TypeError, - "This method accepts:\n" - "-- one radius and a list of edges\n" - "-- two radii and a list of edges"); + PyErr_SetString( + PyExc_TypeError, + "This method accepts:\n" + "-- one radius and a list of edges\n" + "-- two radii and a list of edges" + ); return 0; } radius2 = radius1; } PY_TRY { - return Py::new_reference_to(shape2pyshape( - getTopoShapePtr()->makeElementFillet(getPyShapes(obj), radius1, radius2))); + return Py::new_reference_to( + shape2pyshape(getTopoShapePtr()->makeElementFillet(getPyShapes(obj), radius1, radius2)) + ); } PY_CATCH_OCC PyErr_Clear(); @@ -1150,9 +1233,10 @@ PyObject* TopoShapePy::makeFillet(PyObject *args) const Py::Sequence list(obj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& edge = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); + const TopoDS_Shape& edge + = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); if (edge.ShapeType() == TopAbs_EDGE) { - //Add edge to fillet algorithm + // Add edge to fillet algorithm mkFillet.Add(radius, TopoDS::Edge(edge)); } } @@ -1165,24 +1249,29 @@ PyObject* TopoShapePy::makeFillet(PyObject *args) const } } - PyErr_SetString(PyExc_TypeError, "This method accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "This method accepts:\n" "-- one radius and a list of edges\n" - "-- two radii and a list of edges"); + "-- two radii and a list of edges" + ); return nullptr; } // TODO: Should this python interface support all three chamfer methods and not just two? -PyObject* TopoShapePy::makeChamfer(PyObject *args) const +PyObject* TopoShapePy::makeChamfer(PyObject* args) const { // use two radii for all edges double radius1, radius2; - PyObject *obj; + PyObject* obj; if (!PyArg_ParseTuple(args, "ddO", &radius1, &radius2, &obj)) { if (!PyArg_ParseTuple(args, "dO", &radius1, &obj)) { - PyErr_SetString(PyExc_TypeError, - "This method accepts:\n" - "-- one radius and a list of edges\n" - "-- two radii and a list of edges"); + PyErr_SetString( + PyExc_TypeError, + "This method accepts:\n" + "-- one radius and a list of edges\n" + "-- two radii and a list of edges" + ); return 0; } PyErr_Clear(); @@ -1191,7 +1280,9 @@ PyObject* TopoShapePy::makeChamfer(PyObject *args) const PY_TRY { return Py::new_reference_to(shape2pyshape( - getTopoShapePtr()->makeElementChamfer(getPyShapes(obj), Part::ChamferType::twoDistances, radius1, radius2))); + getTopoShapePtr() + ->makeElementChamfer(getPyShapes(obj), Part::ChamferType::twoDistances, radius1, radius2) + )); } PY_CATCH_OCC PyErr_Clear(); @@ -1209,9 +1300,10 @@ PyObject* TopoShapePy::makeChamfer(PyObject *args) const Py::Sequence list(obj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& edge = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); + const TopoDS_Shape& edge + = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); if (edge.ShapeType() == TopAbs_EDGE) { - //Add edge to fillet algorithm + // Add edge to fillet algorithm const TopoDS_Face& face = TopoDS::Face(mapEdgeFace.FindFromKey(edge).First()); mkChamfer.Add(radius, radius, TopoDS::Edge(edge), face); } @@ -1225,32 +1317,50 @@ PyObject* TopoShapePy::makeChamfer(PyObject *args) const } } - PyErr_SetString(PyExc_TypeError, "This method accepts:\n" + PyErr_SetString( + PyExc_TypeError, + "This method accepts:\n" "-- one radius and a list of edges\n" - "-- two radii and a list of edges"); + "-- two radii and a list of edges" + ); return nullptr; } -PyObject* TopoShapePy::makeThickness(PyObject *args) const +PyObject* TopoShapePy::makeThickness(PyObject* args) const { - PyObject *obj; + PyObject* obj; double offset, tolerance; PyObject* inter = Py_False; PyObject* self_inter = Py_False; short offsetMode = 0, join = 0; - if (!PyArg_ParseTuple(args, "Odd|O!O!hh", &obj, &offset, &tolerance, - &(PyBool_Type), &inter, &(PyBool_Type), &self_inter, &offsetMode, &join)) + if (!PyArg_ParseTuple( + args, + "Odd|O!O!hh", + &obj, + &offset, + &tolerance, + &(PyBool_Type), + &inter, + &(PyBool_Type), + &self_inter, + &offsetMode, + &join + )) { return nullptr; + } try { return Py::new_reference_to(shape2pyshape( - getTopoShapePtr()->makeElementThickSolid(getPyShapes(obj), - offset, - tolerance, - PyObject_IsTrue(inter) ? true : false, - PyObject_IsTrue(self_inter) ? true : false, - offsetMode, - static_cast(join)))); + getTopoShapePtr()->makeElementThickSolid( + getPyShapes(obj), + offset, + tolerance, + PyObject_IsTrue(inter) ? true : false, + PyObject_IsTrue(self_inter) ? true : false, + offsetMode, + static_cast(join) + ) + )); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -1258,30 +1368,46 @@ PyObject* TopoShapePy::makeThickness(PyObject *args) const } } -PyObject* TopoShapePy::makeOffsetShape(PyObject *args, PyObject *keywds) const +PyObject* TopoShapePy::makeOffsetShape(PyObject* args, PyObject* keywds) const { - static const std::array kwlist{"offset", "tolerance", "inter", "self_inter", "offsetMode", "join", - "fill", nullptr}; + static const std::array + kwlist {"offset", "tolerance", "inter", "self_inter", "offsetMode", "join", "fill", nullptr}; double offset, tolerance; - PyObject *inter = Py_False; - PyObject *self_inter = Py_False; - PyObject *fill = Py_False; + PyObject* inter = Py_False; + PyObject* self_inter = Py_False; + PyObject* fill = Py_False; short offsetMode = 0, join = 0; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "dd|O!O!hhO!", kwlist, &offset, &tolerance, - &(PyBool_Type), &inter, &(PyBool_Type), &self_inter, &offsetMode, &join, - &(PyBool_Type), &fill)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "dd|O!O!hhO!", + kwlist, + &offset, + &tolerance, + &(PyBool_Type), + &inter, + &(PyBool_Type), + &self_inter, + &offsetMode, + &join, + &(PyBool_Type), + &fill + )) { return nullptr; } try { - return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementOffset( - offset, - tolerance, - PyObject_IsTrue(inter) ? true : false, - PyObject_IsTrue(self_inter) ? true : false, - offsetMode, - static_cast(join), - PyObject_IsTrue(fill) ? FillType::fill : FillType::noFill))); + return Py::new_reference_to(shape2pyshape( + getTopoShapePtr()->makeElementOffset( + offset, + tolerance, + PyObject_IsTrue(inter) ? true : false, + PyObject_IsTrue(self_inter) ? true : false, + offsetMode, + static_cast(join), + PyObject_IsTrue(fill) ? FillType::fill : FillType::noFill + ) + )); } catch (Standard_Failure& e) { PyErr_SetString(PartExceptionOCCError, e.GetMessageString()); @@ -1289,35 +1415,51 @@ PyObject* TopoShapePy::makeOffsetShape(PyObject *args, PyObject *keywds) const } } -PyObject* TopoShapePy::makeOffset2D(PyObject *args, PyObject *keywds) const +PyObject* TopoShapePy::makeOffset2D(PyObject* args, PyObject* keywds) const { - static const std::array kwlist {"offset", "join", "fill", "openResult", "intersection", nullptr}; + static const std::array + kwlist {"offset", "join", "fill", "openResult", "intersection", nullptr}; double offset; PyObject* fill = Py_False; PyObject* openResult = Py_False; PyObject* inter = Py_False; short join = 0; - if (!Base::Wrapped_ParseTupleAndKeywords(args, keywds, "d|hO!O!O!", kwlist, &offset, &join, - &(PyBool_Type), &fill, &(PyBool_Type), &openResult, &(PyBool_Type), - &inter)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "d|hO!O!O!", + kwlist, + &offset, + &join, + &(PyBool_Type), + &fill, + &(PyBool_Type), + &openResult, + &(PyBool_Type), + &inter + )) { return nullptr; } try { - return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementOffset2D( - offset, - static_cast(join), - PyObject_IsTrue(fill) ? FillType::fill : FillType::noFill, - PyObject_IsTrue(openResult) ? OpenResult::allowOpenResult : OpenResult::noOpenResult, - PyObject_IsTrue(inter) ? true : false))); + return Py::new_reference_to(shape2pyshape( + getTopoShapePtr()->makeElementOffset2D( + offset, + static_cast(join), + PyObject_IsTrue(fill) ? FillType::fill : FillType::noFill, + PyObject_IsTrue(openResult) ? OpenResult::allowOpenResult : OpenResult::noOpenResult, + PyObject_IsTrue(inter) ? true : false + ) + )); } PY_CATCH_OCC; } -PyObject* TopoShapePy::reverse(PyObject *args) +PyObject* TopoShapePy::reverse(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoDS_Shape shape = getTopoShapePtr()->getShape(); shape.Reverse(); @@ -1326,10 +1468,11 @@ PyObject* TopoShapePy::reverse(PyObject *args) Py_Return; } -PyObject* TopoShapePy::reversed(PyObject *args) const +PyObject* TopoShapePy::reversed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoDS_Shape shape = getTopoShapePtr()->getShape(); shape = shape.Reversed(); @@ -1338,8 +1481,9 @@ PyObject* TopoShapePy::reversed(PyObject *args) const PyObject* cpy = nullptr; // let the type object decide - if (type->tp_new) + if (type->tp_new) { cpy = type->tp_new(type, const_cast(this), nullptr); + } if (!cpy) { PyErr_SetString(PyExc_TypeError, "failed to create copy of shape"); return nullptr; @@ -1351,10 +1495,11 @@ PyObject* TopoShapePy::reversed(PyObject *args) const return cpy; } -PyObject* TopoShapePy::complement(PyObject *args) +PyObject* TopoShapePy::complement(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoDS_Shape shape = getTopoShapePtr()->getShape(); shape.Complement(); @@ -1363,10 +1508,11 @@ PyObject* TopoShapePy::complement(PyObject *args) Py_Return; } -PyObject* TopoShapePy::nullify(PyObject *args) +PyObject* TopoShapePy::nullify(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } TopoDS_Shape shape = getTopoShapePtr()->getShape(); shape.Nullify(); @@ -1375,23 +1521,26 @@ PyObject* TopoShapePy::nullify(PyObject *args) Py_Return; } -PyObject* TopoShapePy::isNull(PyObject *args) const +PyObject* TopoShapePy::isNull(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } bool null = getTopoShapePtr()->isNull(); return Py_BuildValue("O", (null ? Py_True : Py_False)); } -PyObject* TopoShapePy::isClosed(PyObject *args) const +PyObject* TopoShapePy::isClosed(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { - if (getTopoShapePtr()->getShape().IsNull()) + if (getTopoShapePtr()->getShape().IsNull()) { Standard_Failure::Raise("Cannot determine the 'Closed'' flag of an empty shape"); + } return Py_BuildValue("O", (getTopoShapePtr()->isClosed() ? Py_True : Py_False)); } catch (...) { @@ -1400,11 +1549,12 @@ PyObject* TopoShapePy::isClosed(PyObject *args) const } } -PyObject* TopoShapePy::isEqual(PyObject *args) const +PyObject* TopoShapePy::isEqual(PyObject* args) const { - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &pcObj)) { return nullptr; + } TopoDS_Shape shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); Standard_Boolean test = (getTopoShapePtr()->getShape().IsEqual(shape)); @@ -1412,11 +1562,12 @@ PyObject* TopoShapePy::isEqual(PyObject *args) const return Py_BuildValue("O", (test ? Py_True : Py_False)); } -PyObject* TopoShapePy::isSame(PyObject *args) const +PyObject* TopoShapePy::isSame(PyObject* args) const { - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &pcObj)) { return nullptr; + } TopoDS_Shape shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); Standard_Boolean test = getTopoShapePtr()->getShape().IsSame(shape); @@ -1424,11 +1575,12 @@ PyObject* TopoShapePy::isSame(PyObject *args) const return Py_BuildValue("O", (test ? Py_True : Py_False)); } -PyObject* TopoShapePy::isPartner(PyObject *args) const +PyObject* TopoShapePy::isPartner(PyObject* args) const { - PyObject *pcObj; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &pcObj)) + PyObject* pcObj; + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &pcObj)) { return nullptr; + } TopoDS_Shape shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); Standard_Boolean test = getTopoShapePtr()->getShape().IsPartner(shape); @@ -1436,62 +1588,75 @@ PyObject* TopoShapePy::isPartner(PyObject *args) const return Py_BuildValue("O", (test ? Py_True : Py_False)); } -PyObject* TopoShapePy::isValid(PyObject *args) const +PyObject* TopoShapePy::isValid(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { return Py_BuildValue("O", (getTopoShapePtr()->isValid() ? Py_True : Py_False)); } PY_CATCH_OCC } -PyObject* TopoShapePy::isCoplanar(PyObject *args) const +PyObject* TopoShapePy::isCoplanar(PyObject* args) const { - PyObject *pyObj; + PyObject* pyObj; double tol = -1; - if (!PyArg_ParseTuple(args, "O!|d", &TopoShapePy::Type, &pyObj, &tol)) + if (!PyArg_ParseTuple(args, "O!|d", &TopoShapePy::Type, &pyObj, &tol)) { return nullptr; + } - PY_TRY { - return Py::new_reference_to(Py::Boolean(getTopoShapePtr()->isCoplanar( - *static_cast(pyObj)->getTopoShapePtr(),tol))); + PY_TRY + { + return Py::new_reference_to( + Py::Boolean( + getTopoShapePtr()->isCoplanar(*static_cast(pyObj)->getTopoShapePtr(), tol) + ) + ); } PY_CATCH_OCC } -PyObject* TopoShapePy::isInfinite(PyObject *args) const +PyObject* TopoShapePy::isInfinite(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } - PY_TRY { + PY_TRY + { return Py::new_reference_to(Py::Boolean(getTopoShapePtr()->isInfinite())); } PY_CATCH_OCC } -PyObject* TopoShapePy::findPlane(PyObject *args) const +PyObject* TopoShapePy::findPlane(PyObject* args) const { double tol = -1; - if (!PyArg_ParseTuple(args, "|d", &tol)) + if (!PyArg_ParseTuple(args, "|d", &tol)) { return nullptr; + } - PY_TRY { + PY_TRY + { gp_Pln pln; - if (getTopoShapePtr()->findPlane(pln, tol)) + if (getTopoShapePtr()->findPlane(pln, tol)) { return new PlanePy(new GeomPlane(new Geom_Plane(pln))); + } Py_Return; } PY_CATCH_OCC } -PyObject* TopoShapePy::fix(PyObject *args) +PyObject* TopoShapePy::fix(PyObject* args) { double prec, mintol, maxtol; - if (!PyArg_ParseTuple(args, "ddd", &prec, &mintol, &maxtol)) + if (!PyArg_ParseTuple(args, "ddd", &prec, &mintol, &maxtol)) { return nullptr; + } try { return Py_BuildValue("O", (getTopoShapePtr()->fix(prec, mintol, maxtol) ? Py_True : Py_False)); @@ -1502,40 +1667,44 @@ PyObject* TopoShapePy::fix(PyObject *args) } } -PyObject* TopoShapePy::hashCode(PyObject *args) const +PyObject* TopoShapePy::hashCode(PyObject* args) const { int upper = IntegerLast(); - if (!PyArg_ParseTuple(args, "|i",&upper)) + if (!PyArg_ParseTuple(args, "|i", &upper)) { return nullptr; + } - int hc = ShapeMapHasher{}(getTopoShapePtr()->getShape()); + int hc = ShapeMapHasher {}(getTopoShapePtr()->getShape()); return Py_BuildValue("i", hc); } -PyObject* TopoShapePy::tessellate(PyObject *args) const +PyObject* TopoShapePy::tessellate(PyObject* args) const { double tolerance; PyObject* ok = Py_False; - if (!PyArg_ParseTuple(args, "d|O!", &tolerance, &PyBool_Type, &ok)) + if (!PyArg_ParseTuple(args, "d|O!", &tolerance, &PyBool_Type, &ok)) { return nullptr; + } try { std::vector Points; std::vector Facets; - if (Base::asBoolean(ok)) + if (Base::asBoolean(ok)) { BRepTools::Clean(getTopoShapePtr()->getShape()); - getTopoShapePtr()->getFaces(Points, Facets,tolerance); + } + getTopoShapePtr()->getFaces(Points, Facets, tolerance); Py::Tuple tuple(2); Py::List vertex; - for (const auto & Point : Points) + for (const auto& Point : Points) { vertex.append(Py::asObject(new Base::VectorPy(Point))); + } tuple.setItem(0, vertex); Py::List facet; for (const auto& it : Facets) { Py::Tuple f(3); - f.setItem(0,Py::Long((long)it.I1)); - f.setItem(1,Py::Long((long)it.I2)); - f.setItem(2,Py::Long((long)it.I3)); + f.setItem(0, Py::Long((long)it.I1)); + f.setItem(1, Py::Long((long)it.I2)); + f.setItem(2, Py::Long((long)it.I3)); facet.append(f); } tuple.setItem(1, facet); @@ -1547,20 +1716,22 @@ PyObject* TopoShapePy::tessellate(PyObject *args) const } } -PyObject* TopoShapePy::project(PyObject *args) const +PyObject* TopoShapePy::project(PyObject* args) const { - PyObject *obj; + PyObject* obj; BRepAlgo_NormalProjection algo; algo.Init(this->getTopoShapePtr()->getShape()); - if (!PyArg_ParseTuple(args, "O", &obj)) + if (!PyArg_ParseTuple(args, "O", &obj)) { return nullptr; + } try { Py::Sequence list(obj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& shape = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); + const TopoDS_Shape& shape + = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); algo.Add(shape); } } @@ -1568,7 +1739,7 @@ PyObject* TopoShapePy::project(PyObject *args) const algo.Compute3d(Standard_True); algo.SetLimit(Standard_True); algo.SetParams(1.e-6, 1.e-6, GeomAbs_C1, 14, 10000); - //algo.SetDefaultParams(); + // algo.SetDefaultParams(); algo.Build(); return new TopoShapePy(new TopoShape(algo.Projection())); } @@ -1578,17 +1749,18 @@ PyObject* TopoShapePy::project(PyObject *args) const } } -PyObject* TopoShapePy::makeParallelProjection(PyObject *args) const +PyObject* TopoShapePy::makeParallelProjection(PyObject* args) const { PyObject *pShape, *pDir; - if (!PyArg_ParseTuple(args, "O!O!", &(Part::TopoShapePy::Type), &pShape, &Base::VectorPy::Type, &pDir)) + if (!PyArg_ParseTuple(args, "O!O!", &(Part::TopoShapePy::Type), &pShape, &Base::VectorPy::Type, &pDir)) { return nullptr; + } try { const TopoDS_Shape& shape = this->getTopoShapePtr()->getShape(); const TopoDS_Shape& wire = static_cast(pShape)->getTopoShapePtr()->getShape(); - Base::Vector3d vec = Py::Vector(pDir,false).toVector(); - BRepProj_Projection proj(wire, shape, gp_Dir(vec.x,vec.y,vec.z)); + Base::Vector3d vec = Py::Vector(pDir, false).toVector(); + BRepProj_Projection proj(wire, shape, gp_Dir(vec.x, vec.y, vec.z)); TopoDS_Shape projected = proj.Shape(); return new TopoShapePy(new TopoShape(projected)); } @@ -1598,17 +1770,18 @@ PyObject* TopoShapePy::makeParallelProjection(PyObject *args) const } } -PyObject* TopoShapePy::makePerspectiveProjection(PyObject *args) const +PyObject* TopoShapePy::makePerspectiveProjection(PyObject* args) const { PyObject *pShape, *pDir; - if (!PyArg_ParseTuple(args, "O!O!", &(Part::TopoShapePy::Type), &pShape, &Base::VectorPy::Type, &pDir)) + if (!PyArg_ParseTuple(args, "O!O!", &(Part::TopoShapePy::Type), &pShape, &Base::VectorPy::Type, &pDir)) { return nullptr; + } try { const TopoDS_Shape& shape = this->getTopoShapePtr()->getShape(); const TopoDS_Shape& wire = static_cast(pShape)->getTopoShapePtr()->getShape(); - Base::Vector3d vec = Py::Vector(pDir,false).toVector(); - BRepProj_Projection proj(wire, shape, gp_Pnt(vec.x,vec.y,vec.z)); + Base::Vector3d vec = Py::Vector(pDir, false).toVector(); + BRepProj_Projection proj(wire, shape, gp_Pnt(vec.x, vec.y, vec.z)); TopoDS_Shape projected = proj.Shape(); return new TopoShapePy(new TopoShape(projected)); } @@ -1631,54 +1804,75 @@ pos=Gui.ActiveDocument.ActiveView.getCameraNode().position.getValue().getValue() pos=App.Vector(*pos) shape=App.ActiveDocument.ActiveObject.Shape -reflect=shape.reflectLines(ViewDir=vdir, ViewPos=pos, UpDir=udir, EdgeType="Sharp", Visible=True, OnShape=False) -Part.show(reflect) +reflect=shape.reflectLines(ViewDir=vdir, ViewPos=pos, UpDir=udir, EdgeType="Sharp", Visible=True, +OnShape=False) Part.show(reflect) */ -PyObject* TopoShapePy::reflectLines(PyObject *args, PyObject *kwds) const +PyObject* TopoShapePy::reflectLines(PyObject* args, PyObject* kwds) const { - static const std::array kwlist{"ViewDir", "ViewPos", "UpDir", "EdgeType", "Visible", "OnShape", - nullptr}; + static const std::array + kwlist {"ViewDir", "ViewPos", "UpDir", "EdgeType", "Visible", "OnShape", nullptr}; - const char* type="OutLine"; + const char* type = "OutLine"; PyObject* vis = Py_True; PyObject* in3d = Py_False; PyObject* pPos = nullptr; PyObject* pUp = nullptr; - PyObject *pView; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|O!O!sO!O!", kwlist, - &Base::VectorPy::Type, &pView, &Base::VectorPy::Type, &pPos, - &Base::VectorPy::Type, - &pUp, &type, &PyBool_Type, &vis, &PyBool_Type, &in3d)) { + PyObject* pView; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|O!O!sO!O!", + kwlist, + &Base::VectorPy::Type, + &pView, + &Base::VectorPy::Type, + &pPos, + &Base::VectorPy::Type, + &pUp, + &type, + &PyBool_Type, + &vis, + &PyBool_Type, + &in3d + )) { return nullptr; } try { HLRBRep_TypeOfResultingEdge t; std::string str = type; - if (str == "IsoLine") + if (str == "IsoLine") { t = HLRBRep_IsoLine; - else if (str == "Rg1Line") + } + else if (str == "Rg1Line") { t = HLRBRep_Rg1Line; - else if (str == "RgNLine") + } + else if (str == "RgNLine") { t = HLRBRep_RgNLine; - else if (str == "Sharp") + } + else if (str == "Sharp") { t = HLRBRep_Sharp; - else + } + else { t = HLRBRep_OutLine; + } Base::Vector3d p(0.0, 0.0, 0.0); - if (pPos) - p = Py::Vector(pPos,false).toVector(); + if (pPos) { + p = Py::Vector(pPos, false).toVector(); + } Base::Vector3d u(0.0, 1.0, 0.0); - if (pUp) - u = Py::Vector(pUp,false).toVector(); + if (pUp) { + u = Py::Vector(pUp, false).toVector(); + } - Base::Vector3d v = Py::Vector(pView,false).toVector(); + Base::Vector3d v = Py::Vector(pView, false).toVector(); const TopoDS_Shape& shape = this->getTopoShapePtr()->getShape(); HLRAppli_ReflectLines reflect(shape); reflect.SetAxes(v.x, v.y, v.z, p.x, p.y, p.z, u.x, u.y, u.z); reflect.Perform(); - TopoDS_Shape lines = reflect.GetCompoundOf3dEdges(t, Base::asBoolean(vis), Base::asBoolean(in3d)); + TopoDS_Shape lines + = reflect.GetCompoundOf3dEdges(t, Base::asBoolean(vis), Base::asBoolean(in3d)); return new TopoShapePy(new TopoShape(lines)); } catch (Standard_Failure& e) { @@ -1687,13 +1881,14 @@ PyObject* TopoShapePy::reflectLines(PyObject *args, PyObject *kwds) const } } -PyObject* TopoShapePy::makeShapeFromMesh(PyObject *args) +PyObject* TopoShapePy::makeShapeFromMesh(PyObject* args) { - PyObject *tup; + PyObject* tup; double tolerance = 1.0e-06; PyObject* sewShape = Py_True; - if (!PyArg_ParseTuple(args, "O!|dO!",&PyTuple_Type, &tup, &tolerance, &PyBool_Type, &sewShape)) + if (!PyArg_ParseTuple(args, "O!|dO!", &PyTuple_Type, &tup, &tolerance, &PyBool_Type, &sewShape)) { return nullptr; + } try { Py::Tuple tuple(tup); @@ -1716,15 +1911,16 @@ PyObject* TopoShapePy::makeShapeFromMesh(PyObject *args) } getTopoShapePtr()->setFaces(Points, Facets, tolerance); - if (Base::asBoolean(sewShape)) + if (Base::asBoolean(sewShape)) { getTopoShapePtr()->sewShape(tolerance); + } Py_Return; } PY_CATCH_OCC } -PyObject* TopoShapePy::makeEvolved(PyObject *args, PyObject *kwds) const +PyObject* TopoShapePy::makeEvolved(PyObject* args, PyObject* kwds) const { PyObject* Profile; PyObject* AxeProf = Py_True; @@ -1733,39 +1929,60 @@ PyObject* TopoShapePy::makeEvolved(PyObject *args, PyObject *kwds) const auto JoinType = JoinType::arc; double Tolerance = 0.0000001; - static const std::array kwds_evolve{"Profile", "Join", "AxeProf", "Solid", "ProfOnSpine", "Tolerance", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|iO!O!O!d", kwds_evolve, - &TopoShapePy::Type, &Profile, &JoinType, - &PyBool_Type, &AxeProf, &PyBool_Type, &Solid, - &PyBool_Type, &ProfOnSpine, &Tolerance)) { + static const std::array + kwds_evolve {"Profile", "Join", "AxeProf", "Solid", "ProfOnSpine", "Tolerance", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|iO!O!O!d", + kwds_evolve, + &TopoShapePy::Type, + &Profile, + &JoinType, + &PyBool_Type, + &AxeProf, + &PyBool_Type, + &Solid, + &PyBool_Type, + &ProfOnSpine, + &Tolerance + )) { return nullptr; } try { - return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementEvolve( - *static_cast(Profile)->getTopoShapePtr(), JoinType, - PyObject_IsTrue(AxeProf) ? CoordinateSystem::global : CoordinateSystem::relativeToSpine, - PyObject_IsTrue(Solid) ? MakeSolid::makeSolid : MakeSolid::noSolid, - PyObject_IsTrue(ProfOnSpine) ? Spine::on : Spine::notOn, - Tolerance))); - } PY_CATCH_OCC + return Py::new_reference_to(shape2pyshape( + getTopoShapePtr()->makeElementEvolve( + *static_cast(Profile)->getTopoShapePtr(), + JoinType, + PyObject_IsTrue(AxeProf) ? CoordinateSystem::global : CoordinateSystem::relativeToSpine, + PyObject_IsTrue(Solid) ? MakeSolid::makeSolid : MakeSolid::noSolid, + PyObject_IsTrue(ProfOnSpine) ? Spine::on : Spine::notOn, + Tolerance + ) + )); + } + PY_CATCH_OCC } PyObject* TopoShapePy::makeWires(PyObject* args) const { - const char *op = nullptr; - if (!PyArg_ParseTuple(args, "s", &op)) + const char* op = nullptr; + if (!PyArg_ParseTuple(args, "s", &op)) { return nullptr; + } - PY_TRY { + PY_TRY + { return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeWires(op))); } PY_CATCH_OCC } -PyObject* TopoShapePy::toNurbs(PyObject *args) const +PyObject* TopoShapePy::toNurbs(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { // Convert into nurbs @@ -1778,14 +1995,15 @@ PyObject* TopoShapePy::toNurbs(PyObject *args) const } } -PyObject* TopoShapePy::isInside(PyObject *args) const +PyObject* TopoShapePy::isInside(PyObject* args) const { - PyObject *point; + PyObject* point; double tolerance; PyObject* checkFace = Py_False; TopAbs_State stateIn = TopAbs_IN; - if (!PyArg_ParseTuple(args, "O!dO!", &(Base::VectorPy::Type), &point, &tolerance, &PyBool_Type, &checkFace)) + if (!PyArg_ParseTuple(args, "O!dO!", &(Base::VectorPy::Type), &point, &tolerance, &PyBool_Type, &checkFace)) { return nullptr; + } try { TopoDS_Shape shape = getTopoShapePtr()->getShape(); @@ -1795,11 +2013,9 @@ PyObject* TopoShapePy::isInside(PyObject *args) const } Base::Vector3d pnt = static_cast(point)->value(); - gp_Pnt vertex = gp_Pnt(pnt.x,pnt.y,pnt.z); - if (shape.ShapeType() == TopAbs_VERTEX || - shape.ShapeType() == TopAbs_EDGE || - shape.ShapeType() == TopAbs_WIRE || - shape.ShapeType() == TopAbs_FACE) { + gp_Pnt vertex = gp_Pnt(pnt.x, pnt.y, pnt.z); + if (shape.ShapeType() == TopAbs_VERTEX || shape.ShapeType() == TopAbs_EDGE + || shape.ShapeType() == TopAbs_WIRE || shape.ShapeType() == TopAbs_FACE) { BRepBuilderAPI_MakeVertex mkVertex(vertex); BRepExtrema_DistShapeShape extss; @@ -1817,8 +2033,9 @@ PyObject* TopoShapePy::isInside(PyObject *args) const solidClassifier.Perform(vertex, tolerance); Standard_Boolean test = (solidClassifier.State() == stateIn); - if (Base::asBoolean(checkFace) && solidClassifier.IsOnAFace()) + if (Base::asBoolean(checkFace) && solidClassifier.IsOnAFace()) { test = Standard_True; + } return Py_BuildValue("O", (test ? Py_True : Py_False)); } } @@ -1832,10 +2049,11 @@ PyObject* TopoShapePy::isInside(PyObject *args) const } } -PyObject* TopoShapePy::removeSplitter(PyObject *args) const +PyObject* TopoShapePy::removeSplitter(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } try { return Py::new_reference_to(shape2pyshape(getTopoShapePtr()->makeElementRefine())); @@ -1846,7 +2064,7 @@ PyObject* TopoShapePy::removeSplitter(PyObject *args) const } } -PyObject* TopoShapePy::getElement(PyObject *args) const +PyObject* TopoShapePy::getElement(PyObject* args) const { char* input; PyObject* silent = Py_False; @@ -1863,32 +2081,35 @@ PyObject* TopoShapePy::getElement(PyObject *args) const PY_CATCH_OCC } -PyObject* TopoShapePy::countElement(PyObject *args) const +PyObject* TopoShapePy::countElement(PyObject* args) const { char* input; - if (!PyArg_ParseTuple(args, "s", &input)) + if (!PyArg_ParseTuple(args, "s", &input)) { return nullptr; + } - PY_TRY { + PY_TRY + { return Py::new_reference_to(Py::Long((long)getTopoShapePtr()->countSubShapes(input))); } PY_CATCH_OCC } -PyObject* TopoShapePy::getTolerance(PyObject *args) const +PyObject* TopoShapePy::getTolerance(PyObject* args) const { int mode; PyObject* type = reinterpret_cast(&TopoShapePy::Type); - if (!PyArg_ParseTuple(args, "i|O!", &mode, &PyType_Type, &type)) + if (!PyArg_ParseTuple(args, "i|O!", &mode, &PyType_Type, &type)) { return nullptr; + } try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); PyTypeObject* pyType = reinterpret_cast(type); TopAbs_ShapeEnum shapetype = ShapeTypeFromPyType(pyType); - if (!PyType_IsSubtype(pyType, &TopoShapePy::Type) || - (shapetype != TopAbs_SHAPE && shapetype != TopAbs_VERTEX && - shapetype != TopAbs_EDGE && shapetype != TopAbs_FACE && shapetype != TopAbs_SHELL)) { + if (!PyType_IsSubtype(pyType, &TopoShapePy::Type) + || (shapetype != TopAbs_SHAPE && shapetype != TopAbs_VERTEX && shapetype != TopAbs_EDGE + && shapetype != TopAbs_FACE && shapetype != TopAbs_SHELL)) { PyErr_SetString(PyExc_TypeError, "shape type must be Shape, Vertex, Edge, Face or Shell"); return nullptr; } @@ -1903,20 +2124,21 @@ PyObject* TopoShapePy::getTolerance(PyObject *args) const } } -PyObject* TopoShapePy::overTolerance(PyObject *args) const +PyObject* TopoShapePy::overTolerance(PyObject* args) const { double value; PyObject* type = reinterpret_cast(&TopoShapePy::Type); - if (!PyArg_ParseTuple(args, "d|O!", &value, &PyType_Type, &type)) + if (!PyArg_ParseTuple(args, "d|O!", &value, &PyType_Type, &type)) { return nullptr; + } try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); PyTypeObject* pyType = reinterpret_cast(type); TopAbs_ShapeEnum shapetype = ShapeTypeFromPyType(pyType); - if (!PyType_IsSubtype(pyType, &TopoShapePy::Type) || - (shapetype != TopAbs_SHAPE && shapetype != TopAbs_VERTEX && - shapetype != TopAbs_EDGE && shapetype != TopAbs_FACE && shapetype != TopAbs_SHELL)) { + if (!PyType_IsSubtype(pyType, &TopoShapePy::Type) + || (shapetype != TopAbs_SHAPE && shapetype != TopAbs_VERTEX && shapetype != TopAbs_EDGE + && shapetype != TopAbs_FACE && shapetype != TopAbs_SHELL)) { PyErr_SetString(PyExc_TypeError, "shape type must be Shape, Vertex, Edge, Face or Shell"); return nullptr; } @@ -1924,8 +2146,8 @@ PyObject* TopoShapePy::overTolerance(PyObject *args) const ShapeAnalysis_ShapeTolerance analysis; Handle(TopTools_HSequenceOfShape) seq = analysis.OverTolerance(shape, value, shapetype); Py::Tuple tuple(seq->Length()); - std::size_t index=0; - for (int i=1; i <= seq->Length(); i++) { + std::size_t index = 0; + for (int i = 1; i <= seq->Length(); i++) { TopoDS_Shape item = seq->Value(i); tuple.setItem(index++, shape2pyshape(item)); } @@ -1937,21 +2159,22 @@ PyObject* TopoShapePy::overTolerance(PyObject *args) const } } -PyObject* TopoShapePy::inTolerance(PyObject *args) const +PyObject* TopoShapePy::inTolerance(PyObject* args) const { double valmin; double valmax; PyObject* type = reinterpret_cast(&TopoShapePy::Type); - if (!PyArg_ParseTuple(args, "dd|O!", &valmin, &valmax, &PyType_Type, &type)) + if (!PyArg_ParseTuple(args, "dd|O!", &valmin, &valmax, &PyType_Type, &type)) { return nullptr; + } try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); PyTypeObject* pyType = reinterpret_cast(type); TopAbs_ShapeEnum shapetype = ShapeTypeFromPyType(pyType); - if (!PyType_IsSubtype(pyType, &TopoShapePy::Type) || - (shapetype != TopAbs_SHAPE && shapetype != TopAbs_VERTEX && - shapetype != TopAbs_EDGE && shapetype != TopAbs_FACE && shapetype != TopAbs_SHELL)) { + if (!PyType_IsSubtype(pyType, &TopoShapePy::Type) + || (shapetype != TopAbs_SHAPE && shapetype != TopAbs_VERTEX && shapetype != TopAbs_EDGE + && shapetype != TopAbs_FACE && shapetype != TopAbs_SHELL)) { PyErr_SetString(PyExc_TypeError, "shape type must be Shape, Vertex, Edge, Face or Shell"); return nullptr; } @@ -1959,8 +2182,8 @@ PyObject* TopoShapePy::inTolerance(PyObject *args) const ShapeAnalysis_ShapeTolerance analysis; Handle(TopTools_HSequenceOfShape) seq = analysis.InTolerance(shape, valmin, valmax, shapetype); Py::Tuple tuple(seq->Length()); - std::size_t index=0; - for (int i=1; i <= seq->Length(); i++) { + std::size_t index = 0; + for (int i = 1; i <= seq->Length(); i++) { TopoDS_Shape item = seq->Value(i); tuple.setItem(index++, shape2pyshape(item)); } @@ -1972,11 +2195,12 @@ PyObject* TopoShapePy::inTolerance(PyObject *args) const } } -PyObject* TopoShapePy::globalTolerance(PyObject *args) const +PyObject* TopoShapePy::globalTolerance(PyObject* args) const { int mode; - if (!PyArg_ParseTuple(args, "i", &mode)) + if (!PyArg_ParseTuple(args, "i", &mode)) { return nullptr; + } try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); @@ -1992,12 +2216,13 @@ PyObject* TopoShapePy::globalTolerance(PyObject *args) const } } -PyObject* TopoShapePy::fixTolerance(PyObject *args) const +PyObject* TopoShapePy::fixTolerance(PyObject* args) const { double value; PyObject* type = reinterpret_cast(&TopoShapePy::Type); - if (!PyArg_ParseTuple(args, "d|O!", &value, &PyType_Type, &type)) + if (!PyArg_ParseTuple(args, "d|O!", &value, &PyType_Type, &type)) { return nullptr; + } try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); @@ -2018,13 +2243,14 @@ PyObject* TopoShapePy::fixTolerance(PyObject *args) const } } -PyObject* TopoShapePy::limitTolerance(PyObject *args) const +PyObject* TopoShapePy::limitTolerance(PyObject* args) const { double tmin; - double tmax=0; + double tmax = 0; PyObject* type = reinterpret_cast(&TopoShapePy::Type); - if (!PyArg_ParseTuple(args, "d|dO!", &tmin, &tmax, &PyType_Type, &type)) + if (!PyArg_ParseTuple(args, "d|dO!", &tmin, &tmax, &PyType_Type, &type)) { return nullptr; + } try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); @@ -2045,32 +2271,34 @@ PyObject* TopoShapePy::limitTolerance(PyObject *args) const } } -PyObject* _getSupportIndex(const char* suppStr, TopoShape* ts, TopoDS_Shape suppShape) { +PyObject* _getSupportIndex(const char* suppStr, TopoShape* ts, TopoDS_Shape suppShape) +{ std::stringstream ss; TopoDS_Shape subShape; unsigned long nSubShapes = ts->countSubShapes(suppStr); long supportIndex = -1; - for (unsigned long j=1; j<=nSubShapes; j++){ + for (unsigned long j = 1; j <= nSubShapes; j++) { ss.str(""); ss << suppStr << j; subShape = ts->getSubShape(ss.str().c_str()); if (subShape.IsEqual(suppShape)) { - supportIndex = j-1; + supportIndex = j - 1; break; } } return PyLong_FromLong(supportIndex); } -PyObject* TopoShapePy::proximity(PyObject *args) const +PyObject* TopoShapePy::proximity(PyObject* args) const { using BRepExtrema_OverlappedSubShapes = BRepExtrema_MapOfIntegerPackedMapOfInteger; PyObject* ps2; Standard_Real tol = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d",&(TopoShapePy::Type), &ps2, &tol)) + if (!PyArg_ParseTuple(args, "O!|d", &(TopoShapePy::Type), &ps2, &tol)) { return nullptr; + } const TopoDS_Shape& s1 = getTopoShapePtr()->getShape(); const TopoDS_Shape& s2 = static_cast(ps2)->getTopoShapePtr()->getShape(); @@ -2084,36 +2312,40 @@ PyObject* TopoShapePy::proximity(PyObject *args) const } BRepExtrema_ShapeProximity proximity; - proximity.LoadShape1 (s1); - proximity.LoadShape2 (s2); + proximity.LoadShape1(s1); + proximity.LoadShape2(s2); if (tol > 0.0) { - proximity.SetTolerance (tol); + proximity.SetTolerance(tol); } proximity.Perform(); if (!proximity.IsDone()) { - PyErr_SetString(PartExceptionOCCError, "BRepExtrema_ShapeProximity failed, make sure the shapes are tessellated"); + PyErr_SetString( + PartExceptionOCCError, + "BRepExtrema_ShapeProximity failed, make sure the shapes are tessellated" + ); return nullptr; } Py::List overlappssindex1; Py::List overlappssindex2; - for (BRepExtrema_OverlappedSubShapes::Iterator anIt1 (proximity.OverlapSubShapes1()); anIt1.More(); anIt1.Next()) { + for (BRepExtrema_OverlappedSubShapes::Iterator anIt1(proximity.OverlapSubShapes1()); anIt1.More(); + anIt1.Next()) { overlappssindex1.append(Py::Long(anIt1.Key() + 1)); } - for (BRepExtrema_OverlappedSubShapes::Iterator anIt2 (proximity.OverlapSubShapes2()); anIt2.More(); anIt2.Next()) { + for (BRepExtrema_OverlappedSubShapes::Iterator anIt2(proximity.OverlapSubShapes2()); anIt2.More(); + anIt2.Next()) { overlappssindex2.append(Py::Long(anIt2.Key() + 1)); } Py::Tuple tuple(2); tuple.setItem(0, overlappssindex1); tuple.setItem(1, overlappssindex2); - return Py::new_reference_to(tuple); //face indexes - + return Py::new_reference_to(tuple); // face indexes } -PyObject* TopoShapePy::distToShape(PyObject *args) const +PyObject* TopoShapePy::distToShape(PyObject* args) const { PyObject* ps2; gp_Pnt P1, P2; @@ -2122,8 +2354,9 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const Standard_Real minDist = -1, t1, t2, u1, v1, u2, v2; Standard_Real tol = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "O!|d",&(TopoShapePy::Type), &ps2, &tol)) + if (!PyArg_ParseTuple(args, "O!|d", &(TopoShapePy::Type), &ps2, &tol)) { return nullptr; + } const TopoDS_Shape& s1 = getTopoShapePtr()->getShape(); TopoShape* ts1 = getTopoShapePtr(); @@ -2157,8 +2390,8 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const int count = extss.NbSolution(); if (count != 0) { minDist = extss.Value(); - //extss.Dump(std::cout); - for (int i=1; i<= count; i++) { + // extss.Dump(std::cout); + for (int i = 1; i <= count; i++) { Py::Object pt1, pt2; Py::String suppType1, suppType2; Py::Long suppIndex1, suppIndex2; @@ -2177,13 +2410,13 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const case BRepExtrema_IsOnEdge: suppType1 = Py::String("Edge"); suppIndex1 = Py::asObject(_getSupportIndex("Edge", ts1, suppS1)); - extss.ParOnEdgeS1(i,t1); + extss.ParOnEdgeS1(i, t1); param1 = Py::Float(t1); break; case BRepExtrema_IsInFace: suppType1 = Py::String("Face"); suppIndex1 = Py::asObject(_getSupportIndex("Face", ts1, suppS1)); - extss.ParOnFaceS1(i,u1,v1); + extss.ParOnFaceS1(i, u1, v1); { Py::Tuple tup(2); tup[0] = Py::Float(u1); @@ -2192,8 +2425,10 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const } break; default: - Base::Console().message("distToShape: supportType1 is unknown: %d \n", - static_cast(supportType1)); + Base::Console().message( + "distToShape: supportType1 is unknown: %d \n", + static_cast(supportType1) + ); suppType1 = Py::String("Unknown"); suppIndex1 = -1; param1 = Py::None(); @@ -2212,13 +2447,13 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const case BRepExtrema_IsOnEdge: suppType2 = Py::String("Edge"); suppIndex2 = Py::asObject(_getSupportIndex("Edge", ts2, suppS2)); - extss.ParOnEdgeS2(i,t2); + extss.ParOnEdgeS2(i, t2); param2 = Py::Float(t2); break; case BRepExtrema_IsInFace: suppType2 = Py::String("Face"); suppIndex2 = Py::asObject(_getSupportIndex("Face", ts2, suppS2)); - extss.ParOnFaceS2(i,u2,v2); + extss.ParOnFaceS2(i, u2, v2); { Py::Tuple tup(2); tup[0] = Py::Float(u2); @@ -2227,8 +2462,10 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const } break; default: - Base::Console().message("distToShape: supportType2 is unknown: %d \n", - static_cast(supportType2)); + Base::Console().message( + "distToShape: supportType2 is unknown: %d \n", + static_cast(supportType2) + ); suppType2 = Py::String("Unknown"); suppIndex2 = -1; param2 = Py::None(); @@ -2260,7 +2497,7 @@ PyObject* TopoShapePy::distToShape(PyObject *args) const return Py::new_reference_to(ret); } -PyObject* TopoShapePy::optimalBoundingBox(PyObject *args) const +PyObject* TopoShapePy::optimalBoundingBox(PyObject* args) const { PyObject* useT = Py_True; PyObject* useS = Py_False; @@ -2271,9 +2508,7 @@ PyObject* TopoShapePy::optimalBoundingBox(PyObject *args) const try { TopoDS_Shape shape = this->getTopoShapePtr()->getShape(); Bnd_Box bounds; - BRepBndLib::AddOptimal(shape, bounds, - Base::asBoolean(useT), - Base::asBoolean(useS)); + BRepBndLib::AddOptimal(shape, bounds, Base::asBoolean(useT), Base::asBoolean(useS)); bounds.SetGap(0.0); Standard_Real xMin, yMin, zMin, xMax, yMax, zMax; bounds.Get(xMin, yMin, zMin, xMax, yMax, zMax); @@ -2303,25 +2538,25 @@ PyObject* TopoShapePy::clearCache(PyObject* args) return IncRef(); } -PyObject* TopoShapePy::defeaturing(PyObject *args) const +PyObject* TopoShapePy::defeaturing(PyObject* args) const { - PyObject *l; - if (!PyArg_ParseTuple(args, "O",&l)) + PyObject* l; + if (!PyArg_ParseTuple(args, "O", &l)) { return nullptr; + } try { Py::Sequence list(l); std::vector shapes; for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { Py::TopoShape sh(*it); - shapes.push_back( - sh.extensionObject()->getTopoShapePtr()->getShape() - ); + shapes.push_back(sh.extensionObject()->getTopoShapePtr()->getShape()); } PyTypeObject* type = this->GetType(); PyObject* inst = type->tp_new(type, const_cast(this), nullptr); - static_cast(inst)->getTopoShapePtr()->setShape - (this->getTopoShapePtr()->defeaturing(shapes)); + static_cast(inst)->getTopoShapePtr()->setShape( + this->getTopoShapePtr()->defeaturing(shapes) + ); return inst; } catch (const Standard_Failure& e) { @@ -2359,24 +2594,27 @@ PyObject* TopoShapePy::findSubShape(PyObject* args) const PyObject* TopoShapePy::findSubShapesWithSharedVertex(PyObject* args, PyObject* keywds) const { - static const std::array kwlist {"shape", "needName", "checkGeometry", "tol", "atol", "singleResult", nullptr}; + static const std::array + kwlist {"shape", "needName", "checkGeometry", "tol", "atol", "singleResult", nullptr}; PyObject* pyobj; PyObject* needName = Py_False; PyObject* checkGeometry = Py_True; PyObject* singleResult = Py_False; double tol = 1e-7; double atol = 1e-12; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - keywds, - "O!|OOddO", - kwlist, - &Type, - &pyobj, - &needName, - &checkGeometry, - &tol, - &atol, - &singleResult)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + keywds, + "O!|OOddO", + kwlist, + &Type, + &pyobj, + &needName, + &checkGeometry, + &tol, + &atol, + &singleResult + )) { return nullptr; } @@ -2385,29 +2623,23 @@ PyObject* TopoShapePy::findSubShapesWithSharedVertex(PyObject* args, PyObject* k Py::List res; const TopoShape& shape = *static_cast(pyobj)->getTopoShapePtr(); Data::SearchOptions options; - if (PyObject_IsTrue(checkGeometry)) + if (PyObject_IsTrue(checkGeometry)) { options.setFlag(Data::SearchOption::CheckGeometry); - if (PyObject_IsTrue(singleResult)) + } + if (PyObject_IsTrue(singleResult)) { options.setFlag(Data::SearchOption::SingleResult); + } if (PyObject_IsTrue(needName)) { std::vector names; - auto shapes = getTopoShapePtr()->findSubShapesWithSharedVertex( - shape, - &names, - options, - tol, - atol); + auto shapes + = getTopoShapePtr()->findSubShapesWithSharedVertex(shape, &names, options, tol, atol); for (std::size_t i = 0; i < shapes.size(); ++i) { res.append(Py::TupleN(Py::String(names[i]), shape2pyshape(shapes[i]))); } } else { - for (auto& s : getTopoShapePtr()->findSubShapesWithSharedVertex( - shape, - nullptr, - options, - tol, - atol)) { + for (auto& s : + getTopoShapePtr()->findSubShapesWithSharedVertex(shape, nullptr, options, tol, atol)) { res.append(shape2pyshape(s)); } } @@ -2421,8 +2653,9 @@ PyObject* TopoShapePy::findSubShapesWithSharedVertex(PyObject* args, PyObject* k Py::String TopoShapePy::getShapeType() const { TopoDS_Shape sh = getTopoShapePtr()->getShape(); - if (sh.IsNull()) + if (sh.IsNull()) { throw Py::Exception(Base::PyExc_FC_GeneralError, "cannot determine type of null shape"); + } TopAbs_ShapeEnum type = sh.ShapeType(); std::string name; @@ -2462,8 +2695,9 @@ Py::String TopoShapePy::getShapeType() const Py::String TopoShapePy::getOrientation() const { TopoDS_Shape sh = getTopoShapePtr()->getShape(); - if (sh.IsNull()) + if (sh.IsNull()) { throw Py::Exception(Base::PyExc_FC_GeneralError, "cannot determine orientation of null shape"); + } TopAbs_Orientation type = sh.Orientation(); std::string name; @@ -2488,8 +2722,9 @@ Py::String TopoShapePy::getOrientation() const void TopoShapePy::setOrientation(Py::String arg) { TopoDS_Shape sh = getTopoShapePtr()->getShape(); - if (sh.IsNull()) + if (sh.IsNull()) { throw Py::Exception(Base::PyExc_FC_GeneralError, "cannot determine orientation of null shape"); + } std::string name = static_cast(arg); TopAbs_Orientation type; @@ -2513,8 +2748,7 @@ void TopoShapePy::setOrientation(Py::String arg) getTopoShapePtr()->setShape(sh); } -static Py::List -getElements(const TopoShape& sh, TopAbs_ShapeEnum type, TopAbs_ShapeEnum avoid = TopAbs_SHAPE) +static Py::List getElements(const TopoShape& sh, TopAbs_ShapeEnum type, TopAbs_ShapeEnum avoid = TopAbs_SHAPE) { Py::List ret; for (auto& shape : sh.getSubTopoShapes(type, avoid)) { @@ -2533,10 +2767,11 @@ PyObject* TopoShapePy::getChildShapes(PyObject* args) const PY_TRY { - return Py::new_reference_to( - getElements(*getTopoShapePtr(), - TopoShape::shapeType(type), - !Base::Tools::isNullOrEmpty(avoid) ? TopoShape::shapeType(avoid) : TopAbs_SHAPE)); + return Py::new_reference_to(getElements( + *getTopoShapePtr(), + TopoShape::shapeType(type), + !Base::Tools::isNullOrEmpty(avoid) ? TopoShape::shapeType(avoid) : TopAbs_SHAPE + )); } PY_CATCH_OCC; } @@ -2589,8 +2824,9 @@ Py::List TopoShapePy::getCompounds() const Py::Float TopoShapePy::getLength() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); - if (shape.IsNull()) + if (shape.IsNull()) { throw Py::RuntimeError("shape is invalid"); + } GProp_GProps props; BRepGProp::LinearProperties(shape, props); return Py::Float(props.Mass()); @@ -2599,8 +2835,9 @@ Py::Float TopoShapePy::getLength() const Py::Float TopoShapePy::getArea() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); - if (shape.IsNull()) + if (shape.IsNull()) { throw Py::RuntimeError("shape is invalid"); + } GProp_GProps props; BRepGProp::SurfaceProperties(shape, props); return Py::Float(props.Mass()); @@ -2609,8 +2846,9 @@ Py::Float TopoShapePy::getArea() const Py::Float TopoShapePy::getVolume() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); - if (shape.IsNull()) + if (shape.IsNull()) { throw Py::RuntimeError("shape is invalid"); + } GProp_GProps props; BRepGProp::VolumeProperties(shape, props); return Py::Float(props.Mass()); @@ -2662,9 +2900,11 @@ struct PyShapeMapper: Part::ShapeMapper return false; } - Part::ShapeMapper::populate(status, - getPyShapes(item[0].ptr()), - getPyShapes(item[1].ptr())); + Part::ShapeMapper::populate( + status, + getPyShapes(item[0].ptr()), + getPyShapes(item[1].ptr()) + ); } } catch (Py::Exception&) { @@ -2676,8 +2916,8 @@ struct PyShapeMapper: Part::ShapeMapper void init(PyObject* g, PyObject* m) { - const char* msg = - "Expect input mapping to be a list of tuple(srcShape|shapeList, dstShape|shapeList)"; + const char* msg + = "Expect input mapping to be a list of tuple(srcShape|shapeList, dstShape|shapeList)"; if (!populate(MappingStatus::Generated, g) || !populate(MappingStatus::Modified, m)) { throw Py::TypeError(msg); } @@ -2736,7 +2976,7 @@ PyObject* TopoShapePy::getCustomAttributes(const char* attr) const return nullptr; } -int TopoShapePy::setCustomAttributes(const char* , PyObject *) +int TopoShapePy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Part/App/TopoShapeShell.pyi b/src/Mod/Part/App/TopoShapeShell.pyi index 1a43ba2fbf..1d86b69f65 100644 --- a/src/Mod/Part/App/TopoShapeShell.pyi +++ b/src/Mod/Part/App/TopoShapeShell.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from TopoShape import TopoShape from typing import Final, Dict - @export( Twin="TopoShape", TwinPointer="TopoShape", diff --git a/src/Mod/Part/App/TopoShapeShellPyImp.cpp b/src/Mod/Part/App/TopoShapeShellPyImp.cpp index 8106c686e1..81e6f41c14 100644 --- a/src/Mod/Part/App/TopoShapeShellPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeShellPyImp.cpp @@ -22,16 +22,16 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -66,7 +66,7 @@ std::string TopoShapeShellPy::representation() const return str.str(); } -PyObject *TopoShapeShellPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* TopoShapeShellPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of TopoShapeSolidPy and the Twin object return new TopoShapeShellPy(new TopoShape); @@ -82,9 +82,10 @@ int TopoShapeShellPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *obj; - if (!PyArg_ParseTuple(args, "O", &obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O", &obj)) { return -1; + } try { getTopoShapePtr()->makeElementBoolean(Part::OpCodes::Shell, getPyShapes(obj)); @@ -93,11 +94,12 @@ int TopoShapeShellPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } -PyObject* TopoShapeShellPy::add(PyObject *args) +PyObject* TopoShapeShellPy::add(PyObject* args) { - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapeFacePy::Type), &obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapeFacePy::Type), &obj)) { return nullptr; + } BRep_Builder builder; TopoDS_Shape shell = getTopoShapePtr()->getShape(); @@ -107,7 +109,7 @@ PyObject* TopoShapeShellPy::add(PyObject *args) try { const TopoShape& shape = *static_cast(obj)->getTopoShapePtr(); - const auto &sh = shape.getShape(); + const auto& sh = shape.getShape(); if (!sh.IsNull()) { builder.Add(shell, sh); BRepCheck_Analyzer check(shell); @@ -131,10 +133,11 @@ PyObject* TopoShapeShellPy::add(PyObject *args) Py_Return; } -PyObject* TopoShapeShellPy::getFreeEdges(PyObject *args) const +PyObject* TopoShapeShellPy::getFreeEdges(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } ShapeAnalysis_Shell as; as.LoadShells(getTopoShapePtr()->getShape()); as.CheckOrientedShells(getTopoShapePtr()->getShape(), Standard_True, Standard_True); @@ -146,10 +149,11 @@ PyObject* TopoShapeShellPy::getFreeEdges(PyObject *args) const return Py::new_reference_to(shape2pyshape(res)); } -PyObject* TopoShapeShellPy::getBadEdges(PyObject *args) const +PyObject* TopoShapeShellPy::getBadEdges(PyObject* args) const { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } ShapeAnalysis_Shell as; as.LoadShells(getTopoShapePtr()->getShape()); as.CheckOrientedShells(getTopoShapePtr()->getShape(), Standard_True, Standard_True); @@ -161,15 +165,19 @@ PyObject* TopoShapeShellPy::getBadEdges(PyObject *args) const return Py::new_reference_to(shape2pyshape(res)); } -PyObject* TopoShapeShellPy::makeHalfSpace(PyObject *args) const +PyObject* TopoShapeShellPy::makeHalfSpace(PyObject* args) const { PyObject* pPnt; - if (!PyArg_ParseTuple(args, "O!",&(Base::VectorPy::Type),&pPnt)) + if (!PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &pPnt)) { return nullptr; + } try { - Base::Vector3d pt = Py::Vector(pPnt,false).toVector(); - BRepPrimAPI_MakeHalfSpace mkHS(TopoDS::Shell(this->getTopoShapePtr()->getShape()), gp_Pnt(pt.x,pt.y,pt.z)); + Base::Vector3d pt = Py::Vector(pPnt, false).toVector(); + BRepPrimAPI_MakeHalfSpace mkHS( + TopoDS::Shell(this->getTopoShapePtr()->getShape()), + gp_Pnt(pt.x, pt.y, pt.z) + ); return new TopoShapeSolidPy(new TopoShape(mkHS.Solid())); } catch (Standard_Failure& e) { @@ -191,7 +199,7 @@ Py::Object TopoShapeShellPy::getCenterOfMass() const GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); gp_Pnt c = props.CentreOfMass(); - return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); + return Py::Vector(Base::Vector3d(c.X(), c.Y(), c.Z())); } Py::Object TopoShapeShellPy::getMatrixOfInertia() const @@ -200,9 +208,9 @@ Py::Object TopoShapeShellPy::getMatrixOfInertia() const BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); gp_Mat m = props.MatrixOfInertia(); Base::Matrix4D mat; - for (int i=0; i<3; i++) { - for (int j=0; j<3; j++) { - mat[i][j] = m(i+1,j+1); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + mat[i][j] = m(i + 1, j + 1); } } return Py::Matrix(mat); @@ -212,8 +220,8 @@ Py::Object TopoShapeShellPy::getStaticMoments() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); - Standard_Real lx,ly,lz; - props.StaticMoments(lx,ly,lz); + Standard_Real lx, ly, lz; + props.StaticMoments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); @@ -230,31 +238,37 @@ Py::Dict TopoShapeShellPy::getPrincipalProperties() const Py::Dict dict; dict.setItem("SymmetryAxis", Py::Boolean(pprops.HasSymmetryAxis() ? true : false)); dict.setItem("SymmetryPoint", Py::Boolean(pprops.HasSymmetryPoint() ? true : false)); - Standard_Real lx,ly,lz; - pprops.Moments(lx,ly,lz); + Standard_Real lx, ly, lz; + pprops.Moments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); tuple.setItem(2, Py::Float(lz)); - dict.setItem("Moments",tuple); - dict.setItem("FirstAxisOfInertia",Py::Vector(Base::convertTo - (pprops.FirstAxisOfInertia()))); - dict.setItem("SecondAxisOfInertia",Py::Vector(Base::convertTo - (pprops.SecondAxisOfInertia()))); - dict.setItem("ThirdAxisOfInertia",Py::Vector(Base::convertTo - (pprops.ThirdAxisOfInertia()))); + dict.setItem("Moments", tuple); + dict.setItem( + "FirstAxisOfInertia", + Py::Vector(Base::convertTo(pprops.FirstAxisOfInertia())) + ); + dict.setItem( + "SecondAxisOfInertia", + Py::Vector(Base::convertTo(pprops.SecondAxisOfInertia())) + ); + dict.setItem( + "ThirdAxisOfInertia", + Py::Vector(Base::convertTo(pprops.ThirdAxisOfInertia())) + ); - Standard_Real Rxx,Ryy,Rzz; - pprops.RadiusOfGyration(Rxx,Ryy,Rzz); + Standard_Real Rxx, Ryy, Rzz; + pprops.RadiusOfGyration(Rxx, Ryy, Rzz); Py::Tuple rog(3); rog.setItem(0, Py::Float(Rxx)); rog.setItem(1, Py::Float(Ryy)); rog.setItem(2, Py::Float(Rzz)); - dict.setItem("RadiusOfGyration",rog); + dict.setItem("RadiusOfGyration", rog); return dict; } -PyObject *TopoShapeShellPy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeShellPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TopoShapeSolid.pyi b/src/Mod/Part/App/TopoShapeSolid.pyi index 4402988cbe..11f971e312 100644 --- a/src/Mod/Part/App/TopoShapeSolid.pyi +++ b/src/Mod/Part/App/TopoShapeSolid.pyi @@ -4,7 +4,6 @@ from Base.Vector import Vector from Base.Matrix import Matrix from typing import Final, Dict, Tuple, overload - @export( Twin="TopoShape", TwinPointer="TopoShape", @@ -95,14 +94,10 @@ class TopoShapeSolid(TopoShape): @overload @constmethod - def offsetFaces( - self, facesTuple: Tuple[TopoShape, ...], offset: float - ) -> TopoShape: ... - + def offsetFaces(self, facesTuple: Tuple[TopoShape, ...], offset: float) -> TopoShape: ... @overload @constmethod def offsetFaces(self, facesDict: Dict[TopoShape, float]) -> TopoShape: ... - @constmethod def offsetFaces(self, *args, **kwargs) -> TopoShape: """ diff --git a/src/Mod/Part/App/TopoShapeSolidPyImp.cpp b/src/Mod/Part/App/TopoShapeSolidPyImp.cpp index 1b8aacc966..2b75f0eccf 100644 --- a/src/Mod/Part/App/TopoShapeSolidPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeSolidPyImp.cpp @@ -23,24 +23,24 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -67,7 +67,7 @@ std::string TopoShapeSolidPy::representation() const return str.str(); } -PyObject *TopoShapeSolidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) +PyObject* TopoShapeSolidPy::PyMake(struct _typeobject*, PyObject*, PyObject*) { // create a new instance of TopoShapeSolidPy and the Twin object return new TopoShapeSolidPy(new TopoShape); @@ -83,9 +83,10 @@ int TopoShapeSolidPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *obj; - if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &obj)) + PyObject* obj; + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &obj)) { return -1; + } try { getTopoShapePtr()->makeElementSolid(*static_cast(obj)->getTopoShapePtr()); @@ -113,7 +114,7 @@ Py::Object TopoShapeSolidPy::getCenterOfMass() const GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); gp_Pnt c = props.CentreOfMass(); - return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); + return Py::Vector(Base::Vector3d(c.X(), c.Y(), c.Z())); } Py::Object TopoShapeSolidPy::getMatrixOfInertia() const @@ -122,9 +123,9 @@ Py::Object TopoShapeSolidPy::getMatrixOfInertia() const BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); gp_Mat m = props.MatrixOfInertia(); Base::Matrix4D mat; - for (int i=0; i<3; i++) { - for (int j=0; j<3; j++) { - mat[i][j] = m(i+1,j+1); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + mat[i][j] = m(i + 1, j + 1); } } return Py::Matrix(mat); @@ -134,8 +135,8 @@ Py::Object TopoShapeSolidPy::getStaticMoments() const { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); - Standard_Real lx,ly,lz; - props.StaticMoments(lx,ly,lz); + Standard_Real lx, ly, lz; + props.StaticMoments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); @@ -152,27 +153,33 @@ Py::Dict TopoShapeSolidPy::getPrincipalProperties() const Py::Dict dict; dict.setItem("SymmetryAxis", Py::Boolean(pprops.HasSymmetryAxis() ? true : false)); dict.setItem("SymmetryPoint", Py::Boolean(pprops.HasSymmetryPoint() ? true : false)); - Standard_Real lx,ly,lz; - pprops.Moments(lx,ly,lz); + Standard_Real lx, ly, lz; + pprops.Moments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); tuple.setItem(2, Py::Float(lz)); - dict.setItem("Moments",tuple); - dict.setItem("FirstAxisOfInertia",Py::Vector(Base::convertTo - (pprops.FirstAxisOfInertia()))); - dict.setItem("SecondAxisOfInertia",Py::Vector(Base::convertTo - (pprops.SecondAxisOfInertia()))); - dict.setItem("ThirdAxisOfInertia",Py::Vector(Base::convertTo - (pprops.ThirdAxisOfInertia()))); + dict.setItem("Moments", tuple); + dict.setItem( + "FirstAxisOfInertia", + Py::Vector(Base::convertTo(pprops.FirstAxisOfInertia())) + ); + dict.setItem( + "SecondAxisOfInertia", + Py::Vector(Base::convertTo(pprops.SecondAxisOfInertia())) + ); + dict.setItem( + "ThirdAxisOfInertia", + Py::Vector(Base::convertTo(pprops.ThirdAxisOfInertia())) + ); - Standard_Real Rxx,Ryy,Rzz; - pprops.RadiusOfGyration(Rxx,Ryy,Rzz); + Standard_Real Rxx, Ryy, Rzz; + pprops.RadiusOfGyration(Rxx, Ryy, Rzz); Py::Tuple rog(3); rog.setItem(0, Py::Float(Rxx)); rog.setItem(1, Py::Float(Ryy)); rog.setItem(2, Py::Float(Rzz)); - dict.setItem("RadiusOfGyration",rog); + dict.setItem("RadiusOfGyration", rog); return dict; } @@ -180,28 +187,30 @@ Py::Object TopoShapeSolidPy::getOuterShell() const { TopoDS_Shell shell; const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); - if (!shape.IsNull() && shape.ShapeType() == TopAbs_SOLID) + if (!shape.IsNull() && shape.ShapeType() == TopAbs_SOLID) { shell = BRepClass3d::OuterShell(TopoDS::Solid(shape)); + } TopoShape res; res.setShape(shell); res.mapSubElement(*getTopoShapePtr()); return shape2pyshape(res); } -PyObject* TopoShapeSolidPy::getMomentOfInertia(PyObject *args) const +PyObject* TopoShapeSolidPy::getMomentOfInertia(PyObject* args) const { - PyObject *p,*d; - if (!PyArg_ParseTuple(args, "O!O!",&Base::VectorPy::Type,&p - ,&Base::VectorPy::Type,&d)) + PyObject *p, *d; + if (!PyArg_ParseTuple(args, "O!O!", &Base::VectorPy::Type, &p, &Base::VectorPy::Type, &d)) { return nullptr; - Base::Vector3d pnt = Py::Vector(p,false).toVector(); - Base::Vector3d dir = Py::Vector(d,false).toVector(); + } + Base::Vector3d pnt = Py::Vector(p, false).toVector(); + Base::Vector3d dir = Py::Vector(d, false).toVector(); try { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); - double r = props.MomentOfInertia(gp_Ax1(Base::convertTo(pnt), - Base::convertTo(dir))); + double r = props.MomentOfInertia( + gp_Ax1(Base::convertTo(pnt), Base::convertTo(dir)) + ); return PyFloat_FromDouble(r); } catch (Standard_Failure& e) { @@ -211,20 +220,21 @@ PyObject* TopoShapeSolidPy::getMomentOfInertia(PyObject *args) const } } -PyObject* TopoShapeSolidPy::getRadiusOfGyration(PyObject *args) const +PyObject* TopoShapeSolidPy::getRadiusOfGyration(PyObject* args) const { - PyObject *p,*d; - if (!PyArg_ParseTuple(args, "O!O!",&Base::VectorPy::Type,&p - ,&Base::VectorPy::Type,&d)) + PyObject *p, *d; + if (!PyArg_ParseTuple(args, "O!O!", &Base::VectorPy::Type, &p, &Base::VectorPy::Type, &d)) { return nullptr; - Base::Vector3d pnt = Py::Vector(p,false).toVector(); - Base::Vector3d dir = Py::Vector(d,false).toVector(); + } + Base::Vector3d pnt = Py::Vector(p, false).toVector(); + Base::Vector3d dir = Py::Vector(d, false).toVector(); try { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); - double r = props.RadiusOfGyration(gp_Ax1(Base::convertTo(pnt), - Base::convertTo(dir))); + double r = props.RadiusOfGyration( + gp_Ax1(Base::convertTo(pnt), Base::convertTo(dir)) + ); return PyFloat_FromDouble(r); } catch (Standard_Failure& e) { @@ -234,16 +244,24 @@ PyObject* TopoShapeSolidPy::getRadiusOfGyration(PyObject *args) const } } -PyObject* TopoShapeSolidPy::offsetFaces(PyObject *args) const +PyObject* TopoShapeSolidPy::offsetFaces(PyObject* args) const { - PyObject *obj; + PyObject* obj; Standard_Real offset; const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); BRepOffset_MakeOffset builder; // Set here an offset value higher than the tolerance - builder.Initialize(shape,1.0,Precision::Confusion(),BRepOffset_Skin,Standard_False,Standard_False,GeomAbs_Intersection); - TopExp_Explorer xp(shape,TopAbs_FACE); + builder.Initialize( + shape, + 1.0, + Precision::Confusion(), + BRepOffset_Skin, + Standard_False, + Standard_False, + GeomAbs_Intersection + ); + TopExp_Explorer xp(shape, TopAbs_FACE); while (xp.More()) { // go through all faces and set offset to zero builder.SetOffsetOnFace(TopoDS::Face(xp.Current()), 0.0); @@ -251,13 +269,14 @@ PyObject* TopoShapeSolidPy::offsetFaces(PyObject *args) const } bool paramOK = false; - if (PyArg_ParseTuple(args, "Od", &obj,&offset)) { + if (PyArg_ParseTuple(args, "Od", &obj, &offset)) { paramOK = true; Py::Sequence list(obj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { // set offset of the requested faces - const TopoDS_Shape& face = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); + const TopoDS_Shape& face + = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); builder.SetOffsetOnFace(TopoDS::Face(face), offset); } } @@ -270,7 +289,8 @@ PyObject* TopoShapeSolidPy::offsetFaces(PyObject *args) const for (Py::Dict::iterator it = dict.begin(); it != dict.end(); ++it) { if (PyObject_TypeCheck((*it).first.ptr(), &(Part::TopoShapePy::Type))) { // set offset of the requested faces - const TopoDS_Shape& face = static_cast((*it).first.ptr())->getTopoShapePtr()->getShape(); + const TopoDS_Shape& face + = static_cast((*it).first.ptr())->getTopoShapePtr()->getShape(); Standard_Real value = (double)Py::Float((*it).second.ptr()); builder.SetOffsetOnFace(TopoDS::Face(face), value); } @@ -296,7 +316,7 @@ PyObject* TopoShapeSolidPy::offsetFaces(PyObject *args) const } } -PyObject *TopoShapeSolidPy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeSolidPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TopoShapeVertex.pyi b/src/Mod/Part/App/TopoShapeVertex.pyi index eda89b1c3a..44685da8c5 100644 --- a/src/Mod/Part/App/TopoShapeVertex.pyi +++ b/src/Mod/Part/App/TopoShapeVertex.pyi @@ -3,7 +3,6 @@ from Base.Vector import Vector from TopoShape import TopoShape from typing import Final - @export( Twin="TopoShape", TwinPointer="TopoShape", diff --git a/src/Mod/Part/App/TopoShapeVertexPyImp.cpp b/src/Mod/Part/App/TopoShapeVertexPyImp.cpp index e99fb1fe4e..5bbd867125 100644 --- a/src/Mod/Part/App/TopoShapeVertexPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeVertexPyImp.cpp @@ -23,14 +23,14 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -52,7 +52,7 @@ std::string TopoShapeVertexPy::representation() const return str.str(); } -PyObject *TopoShapeVertexPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* TopoShapeVertexPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of TopoShapeVertexPy and the Twin object return new TopoShapeVertexPy(new TopoShape); @@ -68,16 +68,16 @@ int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - double x=0.0,y=0.0,z=0.0; - PyObject *object; + double x = 0.0, y = 0.0, z = 0.0; + PyObject* object; bool success = false; - if (PyArg_ParseTuple(args, "|ddd", &x,&y,&z)) { + if (PyArg_ParseTuple(args, "|ddd", &x, &y, &z)) { // do nothing here success = true; } if (!success) { - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!", &(Base::VectorPy::Type), &object)) { Base::Vector3d* ptr = static_cast(object)->getVectorPtr(); x = ptr->x; y = ptr->y; @@ -86,8 +86,8 @@ int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } if (!success) { - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!",&(PyTuple_Type), &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!", &(PyTuple_Type), &object)) { try { Py::Tuple tuple(object); x = Py::Float(tuple.getItem(0)); @@ -101,10 +101,11 @@ int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } if (!success) { - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!",&(PointPy::Type), &object)) { - Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast - (static_cast(object)->getGeomPointPtr()->handle()); + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!", &(PointPy::Type), &object)) { + Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast( + static_cast(object)->getGeomPointPtr()->handle() + ); gp_Pnt pnt = this_point->Pnt(); x = pnt.X(); y = pnt.Y(); @@ -113,8 +114,8 @@ int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } if (!success) { - PyErr_Clear(); // set by PyArg_ParseTuple() - if (PyArg_ParseTuple(args,"O!",&(Part::TopoShapePy::Type), &object)) { + PyErr_Clear(); // set by PyArg_ParseTuple() + if (PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &object)) { TopoShape* ptr = static_cast(object)->getTopoShapePtr(); TopoDS_Shape shape = ptr->getShape(); if (!shape.IsNull() && shape.ShapeType() == TopAbs_VERTEX) { @@ -130,7 +131,7 @@ int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) } TopoShapeVertexPy::PointerType ptr = getTopoShapePtr(); - BRepBuilderAPI_MakeVertex aBuilder(gp_Pnt(x,y,z)); + BRepBuilderAPI_MakeVertex aBuilder(gp_Pnt(x, y, z)); TopoDS_Shape s = aBuilder.Vertex(); ptr->setShape(s); @@ -191,7 +192,7 @@ Py::Object TopoShapeVertexPy::getPoint() const try { const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape()); gp_Pnt p = BRep_Tool::Pnt(v); - Base::PyObjectBase* pnt = new Base::VectorPy(new Base::Vector3d(p.X(),p.Y(),p.Z())); + Base::PyObjectBase* pnt = new Base::VectorPy(new Base::Vector3d(p.X(), p.Y(), p.Z())); pnt->setNotTracking(); return Py::asObject(pnt); } @@ -201,7 +202,7 @@ Py::Object TopoShapeVertexPy::getPoint() const } } -PyObject *TopoShapeVertexPy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeVertexPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TopoShapeWire.pyi b/src/Mod/Part/App/TopoShapeWire.pyi index 15df853c78..b67fe61c91 100644 --- a/src/Mod/Part/App/TopoShapeWire.pyi +++ b/src/Mod/Part/App/TopoShapeWire.pyi @@ -2,7 +2,6 @@ from Base.Metadata import export, constmethod from TopoShape import TopoShape from typing import Dict, List, Final, overload, Optional - @export( Twin="TopoShape", TwinPointer="TopoShape", @@ -93,9 +92,7 @@ class TopoShapeWire(TopoShape): """ ... - def fixWire( - self, face: Optional[object] = None, tolerance: Optional[float] = None - ) -> None: + def fixWire(self, face: Optional[object] = None, tolerance: Optional[float] = None) -> None: """ Fix wire fixWire([face, tolerance]) @@ -137,8 +134,16 @@ class TopoShapeWire(TopoShape): ... @constmethod - def makeEvolved(self, *, Profile: TopoShape, Join: int, AxeProf: bool, Solid: bool, - ProfOnSpine: bool, Tolerance: float) -> TopoShape: + def makeEvolved( + self, + *, + Profile: TopoShape, + Join: int, + AxeProf: bool, + Solid: bool, + ProfOnSpine: bool, + Tolerance: float, + ) -> TopoShape: """ Profile along the spine """ @@ -201,19 +206,14 @@ class TopoShapeWire(TopoShape): @overload @constmethod - def discretize( - self, Angular: float, Curvature: float, Minimum: int = 2 - ) -> List[object]: + def discretize(self, Angular: float, Curvature: float, Minimum: int = 2) -> List[object]: """ discretize(Angular=a,Curvature=c,[Minimum=m]) -> list """ ... @constmethod - def discretize( - self, - **kwargs - ) -> List[object]: + def discretize(self, **kwargs) -> List[object]: """ Discretizes the wire and returns a list of points. discretize(kwargs) -> list diff --git a/src/Mod/Part/App/TopoShapeWirePyImp.cpp b/src/Mod/Part/App/TopoShapeWirePyImp.cpp index cfa4b561e9..c31d2188fe 100644 --- a/src/Mod/Part/App/TopoShapeWirePyImp.cpp +++ b/src/Mod/Part/App/TopoShapeWirePyImp.cpp @@ -22,26 +22,26 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -58,8 +58,9 @@ using namespace Part; -namespace Part { - extern Py::Object shape2pyshape(const TopoDS_Shape &shape); +namespace Part +{ +extern Py::Object shape2pyshape(const TopoDS_Shape& shape); } @@ -72,7 +73,7 @@ std::string TopoShapeWirePy::representation() const return str.str(); } -PyObject *TopoShapeWirePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* TopoShapeWirePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of TopoShapeWirePy and the Twin object return new TopoShapeWirePy(new TopoShape); @@ -88,7 +89,7 @@ int TopoShapeWirePy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - PyObject *pcObj; + PyObject* pcObj; if (PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pcObj)) { BRepBuilderAPI_MakeWire mkWire; const TopoDS_Shape& sh = static_cast(pcObj)->getTopoShapePtr()->getShape(); @@ -96,10 +97,12 @@ int TopoShapeWirePy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_SetString(PyExc_TypeError, "given shape is invalid"); return -1; } - if (sh.ShapeType() == TopAbs_EDGE) + if (sh.ShapeType() == TopAbs_EDGE) { mkWire.Add(TopoDS::Edge(sh)); - else if (sh.ShapeType() == TopAbs_WIRE) + } + else if (sh.ShapeType() == TopAbs_WIRE) { mkWire.Add(TopoDS::Wire(sh)); + } else { PyErr_SetString(PyExc_TypeError, "shape is neither edge nor wire"); return -1; @@ -118,7 +121,7 @@ int TopoShapeWirePy::PyInit(PyObject* args, PyObject* /*kwd*/) PyErr_Clear(); if (PyArg_ParseTuple(args, "O", &pcObj)) { - if(!Py::Object(pcObj).isList() && !Py::Object(pcObj).isTuple()) { + if (!Py::Object(pcObj).isList() && !Py::Object(pcObj).isTuple()) { PyErr_SetString(PyExc_TypeError, "object is neither a list nor a tuple"); return -1; } @@ -128,15 +131,18 @@ int TopoShapeWirePy::PyInit(PyObject* args, PyObject* /*kwd*/) for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& sh = static_cast(item)->getTopoShapePtr()->getShape(); + const TopoDS_Shape& sh + = static_cast(item)->getTopoShapePtr()->getShape(); if (sh.IsNull()) { PyErr_SetString(PyExc_TypeError, "given shape is invalid"); return -1; } - if (sh.ShapeType() == TopAbs_EDGE) + if (sh.ShapeType() == TopAbs_EDGE) { mkWire.Add(TopoDS::Edge(sh)); - else if (sh.ShapeType() == TopAbs_WIRE) + } + else if (sh.ShapeType() == TopAbs_WIRE) { mkWire.Add(TopoDS::Wire(sh)); + } else { PyErr_SetString(PyExc_TypeError, "shape is neither edge nor wire"); return -1; @@ -163,11 +169,12 @@ int TopoShapeWirePy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -PyObject* TopoShapeWirePy::add(PyObject *args) +PyObject* TopoShapeWirePy::add(PyObject* args) { PyObject* edge; - if (!PyArg_ParseTuple(args, "O!",&(TopoShapePy::Type), &edge)) + if (!PyArg_ParseTuple(args, "O!", &(TopoShapePy::Type), &edge)) { return nullptr; + } const TopoDS_Wire& w = TopoDS::Wire(getTopoShapePtr()->getShape()); BRepBuilderAPI_MakeWire mkWire(w); @@ -176,10 +183,12 @@ PyObject* TopoShapeWirePy::add(PyObject *args) PyErr_SetString(PyExc_TypeError, "given shape is invalid"); return nullptr; } - if (sh.ShapeType() == TopAbs_EDGE) + if (sh.ShapeType() == TopAbs_EDGE) { mkWire.Add(TopoDS::Edge(sh)); - else if (sh.ShapeType() == TopAbs_WIRE) + } + else if (sh.ShapeType() == TopAbs_WIRE) { mkWire.Add(TopoDS::Wire(sh)); + } else { PyErr_SetString(PyExc_TypeError, "shape is neither edge nor wire"); return nullptr; @@ -196,19 +205,22 @@ PyObject* TopoShapeWirePy::add(PyObject *args) } } -PyObject* TopoShapeWirePy::fixWire(PyObject *args) +PyObject* TopoShapeWirePy::fixWire(PyObject* args) { - PyObject* face=nullptr; + PyObject* face = nullptr; double tol = Precision::Confusion(); - if (!PyArg_ParseTuple(args, "|O!d",&(TopoShapeFacePy::Type), &face, &tol)) + if (!PyArg_ParseTuple(args, "|O!d", &(TopoShapeFacePy::Type), &face, &tol)) { return nullptr; + } try { ShapeFix_Wire aFix; const TopoDS_Wire& w = TopoDS::Wire(getTopoShapePtr()->getShape()); if (face) { - const TopoDS_Face& f = TopoDS::Face(static_cast(face)->getTopoShapePtr()->getShape()); + const TopoDS_Face& f = TopoDS::Face( + static_cast(face)->getTopoShapePtr()->getShape() + ); aFix.Init(w, f, tol); } else { @@ -230,11 +242,12 @@ PyObject* TopoShapeWirePy::fixWire(PyObject *args) } } -PyObject* TopoShapeWirePy::makeOffset(PyObject *args) const +PyObject* TopoShapeWirePy::makeOffset(PyObject* args) const { double dist; - if (!PyArg_ParseTuple(args, "d",&dist)) + if (!PyArg_ParseTuple(args, "d", &dist)) { return nullptr; + } const TopoDS_Wire& w = TopoDS::Wire(getTopoShapePtr()->getShape()); BRepBuilderAPI_FindPlane findPlane(w); if (!findPlane.Found()) { @@ -248,9 +261,9 @@ PyObject* TopoShapeWirePy::makeOffset(PyObject *args) const return new TopoShapePy(new TopoShape(mkOffset.Shape())); } -PyObject* TopoShapeWirePy::makePipe(PyObject *args) const +PyObject* TopoShapeWirePy::makePipe(PyObject* args) const { - PyObject *pShape; + PyObject* pShape; if (PyArg_ParseTuple(args, "O!", &(Part::TopoShapePy::Type), &pShape)) { try { TopoDS_Shape profile = static_cast(pShape)->getTopoShapePtr()->getShape(); @@ -267,28 +280,30 @@ PyObject* TopoShapeWirePy::makePipe(PyObject *args) const return nullptr; } -PyObject* TopoShapeWirePy::makePipeShell(PyObject *args) const +PyObject* TopoShapeWirePy::makePipeShell(PyObject* args) const { - PyObject *obj; - PyObject *make_solid = Py_False; - PyObject *is_Frenet = Py_False; + PyObject* obj; + PyObject* make_solid = Py_False; + PyObject* is_Frenet = Py_False; int transition = 0; - if (PyArg_ParseTuple(args, "O|O!O!i", &obj, - &PyBool_Type, &make_solid, - &PyBool_Type, &is_Frenet, - &transition)) { + if (PyArg_ParseTuple(args, "O|O!O!i", &obj, &PyBool_Type, &make_solid, &PyBool_Type, &is_Frenet, &transition)) { try { TopTools_ListOfShape sections; Py::Sequence list(obj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Part::TopoShapePy::Type))) { - const TopoDS_Shape& shape = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); + const TopoDS_Shape& shape + = static_cast((*it).ptr())->getTopoShapePtr()->getShape(); sections.Append(shape); } } - TopoDS_Shape shape = this->getTopoShapePtr()->makePipeShell(sections, - Base::asBoolean(make_solid), Base::asBoolean(is_Frenet), transition); + TopoDS_Shape shape = this->getTopoShapePtr()->makePipeShell( + sections, + Base::asBoolean(make_solid), + Base::asBoolean(is_Frenet), + transition + ); return new TopoShapePy(new TopoShape(shape)); } catch (Standard_Failure& e) { @@ -308,7 +323,7 @@ profile = Part.makePolygon([v(0.,0.,0.), v(-60.,-60.,-100.), v(-60.,-60.,-140.)] spine = Part.makePolygon([v(0.,0.,0.), v(100.,0.,0.), v(100.,100.,0.), v(0.,100.,0.), v(0.,0.,0.)]) evolve = spine.makeEvolved(Profile=profile, Join=PartEnums.JoinType.Arc) */ -PyObject* TopoShapeWirePy::makeEvolved(PyObject *args, PyObject *kwds) const +PyObject* TopoShapeWirePy::makeEvolved(PyObject* args, PyObject* kwds) const { PyObject* Profile; PyObject* AxeProf = Py_True; @@ -317,12 +332,24 @@ PyObject* TopoShapeWirePy::makeEvolved(PyObject *args, PyObject *kwds) const int JoinType = int(GeomAbs_Arc); double Tolerance = 0.0000001; - static const std::array kwds_evolve{"Profile", "Join", "AxeProf", "Solid", "ProfOnSpine", - "Tolerance", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "O!|iO!O!O!d", kwds_evolve, - &TopoShapeWirePy::Type, &Profile, &JoinType, - &PyBool_Type, &AxeProf, &PyBool_Type, &Solid, - &PyBool_Type, &ProfOnSpine, &Tolerance)) { + static const std::array + kwds_evolve {"Profile", "Join", "AxeProf", "Solid", "ProfOnSpine", "Tolerance", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "O!|iO!O!O!d", + kwds_evolve, + &TopoShapeWirePy::Type, + &Profile, + &JoinType, + &PyBool_Type, + &AxeProf, + &PyBool_Type, + &Solid, + &PyBool_Type, + &ProfOnSpine, + &Tolerance + )) { return nullptr; } @@ -333,27 +360,33 @@ PyObject* TopoShapeWirePy::makeEvolved(PyObject *args, PyObject *kwds) const return nullptr; } - const TopoDS_Wire& profile = TopoDS::Wire(static_cast(Profile)->getTopoShapePtr()->getShape()); + const TopoDS_Wire& profile = TopoDS::Wire( + static_cast(Profile)->getTopoShapePtr()->getShape() + ); GeomAbs_JoinType joinType; switch (JoinType) { - case GeomAbs_Tangent: - joinType = GeomAbs_Tangent; - break; - case GeomAbs_Intersection: - joinType = GeomAbs_Intersection; - break; - default: - joinType = GeomAbs_Arc; - break; + case GeomAbs_Tangent: + joinType = GeomAbs_Tangent; + break; + case GeomAbs_Intersection: + joinType = GeomAbs_Intersection; + break; + default: + joinType = GeomAbs_Arc; + break; } try { - BRepOffsetAPI_MakeEvolved evolved(spine, profile, joinType, - Base::asBoolean(AxeProf), - Base::asBoolean(Solid), - Base::asBoolean(ProfOnSpine), - Tolerance); + BRepOffsetAPI_MakeEvolved evolved( + spine, + profile, + joinType, + Base::asBoolean(AxeProf), + Base::asBoolean(Solid), + Base::asBoolean(ProfOnSpine), + Tolerance + ); TopoDS_Shape shape = evolved.Shape(); return Py::new_reference_to(shape2pyshape(shape)); } @@ -363,17 +396,20 @@ PyObject* TopoShapeWirePy::makeEvolved(PyObject *args, PyObject *kwds) const } } -PyObject* TopoShapeWirePy::makeHomogenousWires(PyObject *args) const +PyObject* TopoShapeWirePy::makeHomogenousWires(PyObject* args) const { PyObject* wire; - if (!PyArg_ParseTuple(args, "O!",&(Part::TopoShapeWirePy::Type),&wire)) + if (!PyArg_ParseTuple(args, "O!", &(Part::TopoShapeWirePy::Type), &wire)) { return nullptr; + } try { TopoDS_Wire o1, o2; const TopoDS_Wire& w1 = TopoDS::Wire(getTopoShapePtr()->getShape()); - const TopoDS_Wire& w2 = TopoDS::Wire(static_cast(wire)->getTopoShapePtr()->getShape()); + const TopoDS_Wire& w2 = TopoDS::Wire( + static_cast(wire)->getTopoShapePtr()->getShape() + ); ShapeAlgo_AlgoContainer shapeAlgo; - if (shapeAlgo.HomoWires(w1,w2,o1,o2,Standard_True)) { + if (shapeAlgo.HomoWires(w1, w2, o1, o2, Standard_True)) { getTopoShapePtr()->setShape(o1); return new TopoShapeWirePy(new TopoShape(o2)); } @@ -389,21 +425,29 @@ PyObject* TopoShapeWirePy::makeHomogenousWires(PyObject *args) const } } -PyObject* TopoShapeWirePy::approximate(PyObject *args, PyObject *kwds) const +PyObject* TopoShapeWirePy::approximate(PyObject* args, PyObject* kwds) const { double tol2d = gp::Resolution(); double tol3d = 0.0001; - int maxseg=10, maxdeg=3; + int maxseg = 10, maxdeg = 3; - static const std::array kwds_approx{"Tol2d", "Tol3d", "MaxSegments", "MaxDegree", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, kwds, "|ddii", kwds_approx, &tol2d, &tol3d, &maxseg, &maxdeg)) { + static const std::array + kwds_approx {"Tol2d", "Tol3d", "MaxSegments", "MaxDegree", nullptr}; + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "|ddii", + kwds_approx, + &tol2d, + &tol3d, + &maxseg, + &maxdeg + )) { return nullptr; } try { BRepAdaptor_CompCurve adapt(TopoDS::Wire(getTopoShapePtr()->getShape())); - auto hcurve = adapt.Trim(adapt.FirstParameter(), - adapt.LastParameter(), - tol2d); + auto hcurve = adapt.Trim(adapt.FirstParameter(), adapt.LastParameter(), tol2d); Approx_Curve3d approx(hcurve, tol3d, GeomAbs_C0, maxseg, maxdeg); if (approx.IsDone()) { return new BSplineCurvePy(new GeomBSplineCurve(approx.Curve())); @@ -419,7 +463,7 @@ PyObject* TopoShapeWirePy::approximate(PyObject *args, PyObject *kwds) const } } -PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const +PyObject* TopoShapeWirePy::discretize(PyObject* args, PyObject* kwds) const { try { BRepAdaptor_CompCurve adapt(TopoDS::Wire(getTopoShapePtr()->getShape())); @@ -448,16 +492,37 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const } else { // use Number kwds - static const std::array kwds_numPoints{"Number", "First", "Last", nullptr}; + static const std::array kwds_numPoints {"Number", "First", "Last", nullptr}; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_numPoints, &numPoints, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_numPoints, + &numPoints, + &first, + &last + )) { uniformAbscissaPoints = true; } else { // use Abscissa kwds - static const std::array kwds_Distance{"Distance", "First", "Last", nullptr}; + static const std::array kwds_Distance { + "Distance", + "First", + "Last", + nullptr + }; PyErr_Clear(); - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Distance, &distance, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Distance, + &distance, + &first, + &last + )) { uniformAbscissaDistance = true; } } @@ -465,17 +530,19 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const if (uniformAbscissaPoints || uniformAbscissaDistance) { GCPnts_UniformAbscissa discretizer; - if (uniformAbscissaPoints) - discretizer.Initialize (adapt, numPoints, first, last); - else - discretizer.Initialize (adapt, distance, first, last); + if (uniformAbscissaPoints) { + discretizer.Initialize(adapt, numPoints, first, last); + } + else { + discretizer.Initialize(adapt, distance, first, last); + } - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = adapt.Value (discretizer.Parameter (i)); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = adapt.Value(discretizer.Parameter(i)); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -487,17 +554,25 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const } // use Deflection kwds - static const std::array kwds_Deflection{"Deflection", "First", "Last", nullptr}; + static const std::array kwds_Deflection {"Deflection", "First", "Last", nullptr}; PyErr_Clear(); double deflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_Deflection, &deflection, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_Deflection, + &deflection, + &first, + &last + )) { GCPnts_UniformDeflection discretizer(adapt, deflection, first, last); - if (discretizer.IsDone () && discretizer.NbPoints () > 0) { + if (discretizer.IsDone() && discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -509,21 +584,30 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const } // use TangentialDeflection kwds - static const std::array kwds_TangentialDeflection{"Angular", "Curvature", "First", "Last", - "Minimum", nullptr}; + static const std::array + kwds_TangentialDeflection {"Angular", "Curvature", "First", "Last", "Minimum", nullptr}; PyErr_Clear(); double angular; double curvature; int minimumPoints = 2; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "dd|ddi", kwds_TangentialDeflection, - &angular, &curvature, &first, &last, &minimumPoints)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "dd|ddi", + kwds_TangentialDeflection, + &angular, + &curvature, + &first, + &last, + &minimumPoints + )) { GCPnts_TangentialDeflection discretizer(adapt, first, last, angular, curvature, minimumPoints); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -535,18 +619,30 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiNumber kwds - static const std::array kwds_QuasiNumPoints{"QuasiNumber", "First", "Last", nullptr}; + static const std::array kwds_QuasiNumPoints { + "QuasiNumber", + "First", + "Last", + nullptr + }; PyErr_Clear(); int quasiNumPoints; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "i|dd", kwds_QuasiNumPoints, - &quasiNumPoints, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "i|dd", + kwds_QuasiNumPoints, + &quasiNumPoints, + &first, + &last + )) { GCPnts_QuasiUniformAbscissa discretizer(adapt, quasiNumPoints, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = adapt.Value (discretizer.Parameter (i)); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = adapt.Value(discretizer.Parameter(i)); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -558,18 +654,30 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const } // use QuasiDeflection kwds - static const std::array kwds_QuasiDeflection{"QuasiDeflection", "First", "Last", nullptr}; + static const std::array kwds_QuasiDeflection { + "QuasiDeflection", + "First", + "Last", + nullptr + }; PyErr_Clear(); double quasiDeflection; - if (Base::Wrapped_ParseTupleAndKeywords(args, kwds, "d|dd", kwds_QuasiDeflection, - &quasiDeflection, &first, &last)) { + if (Base::Wrapped_ParseTupleAndKeywords( + args, + kwds, + "d|dd", + kwds_QuasiDeflection, + &quasiDeflection, + &first, + &last + )) { GCPnts_QuasiUniformDeflection discretizer(adapt, quasiDeflection, first, last); - if (discretizer.NbPoints () > 0) { + if (discretizer.NbPoints() > 0) { Py::List points; - int nbPoints = discretizer.NbPoints (); - for (int i=1; i<=nbPoints; i++) { - gp_Pnt p = discretizer.Value (i); - points.append(Py::Vector(Base::Vector3d(p.X(),p.Y(),p.Z()))); + int nbPoints = discretizer.NbPoints(); + for (int i = 1; i <= nbPoints; i++) { + gp_Pnt p = discretizer.Value(i); + points.append(Py::Vector(Base::Vector3d(p.X(), p.Y(), p.Z()))); } return Py::new_reference_to(points); @@ -585,7 +693,7 @@ PyObject* TopoShapeWirePy::discretize(PyObject *args, PyObject *kwds) const return nullptr; } - PyErr_SetString(PartExceptionOCCError,"Wrong arguments"); + PyErr_SetString(PartExceptionOCCError, "Wrong arguments"); return nullptr; } @@ -594,27 +702,27 @@ Py::String TopoShapeWirePy::getContinuity() const BRepAdaptor_CompCurve adapt(TopoDS::Wire(getTopoShapePtr()->getShape())); std::string cont; switch (adapt.Continuity()) { - case GeomAbs_C0: - cont = "C0"; - break; - case GeomAbs_G1: - cont = "G1"; - break; - case GeomAbs_C1: - cont = "C1"; - break; - case GeomAbs_G2: - cont = "G2"; - break; - case GeomAbs_C2: - cont = "C2"; - break; - case GeomAbs_C3: - cont = "C3"; - break; - case GeomAbs_CN: - cont = "CN"; - break; + case GeomAbs_C0: + cont = "C0"; + break; + case GeomAbs_G1: + cont = "G1"; + break; + case GeomAbs_C1: + cont = "C1"; + break; + case GeomAbs_G2: + cont = "G2"; + break; + case GeomAbs_C2: + cont = "C2"; + break; + case GeomAbs_C3: + cont = "C3"; + break; + case GeomAbs_CN: + cont = "CN"; + break; } return Py::String(cont); @@ -633,7 +741,7 @@ Py::Object TopoShapeWirePy::getCenterOfMass() const GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); gp_Pnt c = props.CentreOfMass(); - return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); + return Py::Vector(Base::Vector3d(c.X(), c.Y(), c.Z())); } Py::Object TopoShapeWirePy::getMatrixOfInertia() const @@ -642,9 +750,9 @@ Py::Object TopoShapeWirePy::getMatrixOfInertia() const BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); gp_Mat m = props.MatrixOfInertia(); Base::Matrix4D mat; - for (int i=0; i<3; i++) { - for (int j=0; j<3; j++) { - mat[i][j] = m(i+1,j+1); + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + mat[i][j] = m(i + 1, j + 1); } } return Py::Matrix(mat); @@ -654,8 +762,8 @@ Py::Object TopoShapeWirePy::getStaticMoments() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); - Standard_Real lx,ly,lz; - props.StaticMoments(lx,ly,lz); + Standard_Real lx, ly, lz; + props.StaticMoments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); @@ -672,27 +780,33 @@ Py::Dict TopoShapeWirePy::getPrincipalProperties() const Py::Dict dict; dict.setItem("SymmetryAxis", Py::Boolean(pprops.HasSymmetryAxis() ? true : false)); dict.setItem("SymmetryPoint", Py::Boolean(pprops.HasSymmetryPoint() ? true : false)); - Standard_Real lx,ly,lz; - pprops.Moments(lx,ly,lz); + Standard_Real lx, ly, lz; + pprops.Moments(lx, ly, lz); Py::Tuple tuple(3); tuple.setItem(0, Py::Float(lx)); tuple.setItem(1, Py::Float(ly)); tuple.setItem(2, Py::Float(lz)); - dict.setItem("Moments",tuple); - dict.setItem("FirstAxisOfInertia",Py::Vector(Base::convertTo - (pprops.FirstAxisOfInertia()))); - dict.setItem("SecondAxisOfInertia",Py::Vector(Base::convertTo - (pprops.SecondAxisOfInertia()))); - dict.setItem("ThirdAxisOfInertia",Py::Vector(Base::convertTo - (pprops.ThirdAxisOfInertia()))); + dict.setItem("Moments", tuple); + dict.setItem( + "FirstAxisOfInertia", + Py::Vector(Base::convertTo(pprops.FirstAxisOfInertia())) + ); + dict.setItem( + "SecondAxisOfInertia", + Py::Vector(Base::convertTo(pprops.SecondAxisOfInertia())) + ); + dict.setItem( + "ThirdAxisOfInertia", + Py::Vector(Base::convertTo(pprops.ThirdAxisOfInertia())) + ); - Standard_Real Rxx,Ryy,Rzz; - pprops.RadiusOfGyration(Rxx,Ryy,Rzz); + Standard_Real Rxx, Ryy, Rzz; + pprops.RadiusOfGyration(Rxx, Ryy, Rzz); Py::Tuple rog(3); rog.setItem(0, Py::Float(Rxx)); rog.setItem(1, Py::Float(Ryy)); rog.setItem(2, Py::Float(Rzz)); - dict.setItem("RadiusOfGyration",rog); + dict.setItem("RadiusOfGyration", rog); return dict; } @@ -732,7 +846,7 @@ Py::List TopoShapeWirePy::getOrderedVertexes() const return ret; } -PyObject *TopoShapeWirePy::getCustomAttributes(const char* /*attr*/) const +PyObject* TopoShapeWirePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/Toroid.pyi b/src/Mod/Part/App/Toroid.pyi index 698576389f..4353a40f11 100644 --- a/src/Mod/Part/App/Toroid.pyi +++ b/src/Mod/Part/App/Toroid.pyi @@ -3,7 +3,6 @@ from Part.GeometrySurface import GeometrySurface from Base.Vector import Vector from typing import Final - @export( Name="ToroidPy", Namespace="Part", diff --git a/src/Mod/Part/App/ToroidPyImp.cpp b/src/Mod/Part/App/ToroidPyImp.cpp index d7880945c2..589a579a5b 100644 --- a/src/Mod/Part/App/ToroidPyImp.cpp +++ b/src/Mod/Part/App/ToroidPyImp.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include @@ -42,7 +42,7 @@ std::string ToroidPy::representation() const return ""; } -PyObject *ToroidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* ToroidPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of ToroidPy and the Twin object return new ToroidPy(new GeomToroid); @@ -52,8 +52,9 @@ PyObject *ToroidPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Pyt int ToroidPy::PyInit(PyObject* args, PyObject* /*kwd*/) { if (PyArg_ParseTuple(args, "")) { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); torus->SetMajorRadius(5.0); torus->SetMinorRadius(1.0); return 0; @@ -64,16 +65,18 @@ int ToroidPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::Float ToroidPy::getMajorRadius() const { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); return Py::Float(torus->MajorRadius()); } void ToroidPy::setMajorRadius(Py::Float arg) { try { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); torus->SetMajorRadius((double)arg); } catch (Standard_Failure&) { @@ -83,16 +86,18 @@ void ToroidPy::setMajorRadius(Py::Float arg) Py::Float ToroidPy::getMinorRadius() const { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); return Py::Float(torus->MinorRadius()); } void ToroidPy::setMinorRadius(Py::Float arg) { try { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); torus->SetMinorRadius((double)arg); } catch (Standard_Failure&) { @@ -102,8 +107,9 @@ void ToroidPy::setMinorRadius(Py::Float arg) Py::Object ToroidPy::getCenter() const { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); gp_Pnt loc = torus->Location(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } @@ -113,8 +119,9 @@ void ToroidPy::setCenter(Py::Object arg) PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d loc = static_cast(p)->value(); - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); torus->SetLocation(gp_Pnt(loc.x, loc.y, loc.z)); } else { @@ -126,8 +133,9 @@ void ToroidPy::setCenter(Py::Object arg) Py::Object ToroidPy::getAxis() const { - Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast - (getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast( + getGeometryPtr()->handle() + ); gp_Dir dir = s->Axis().Direction(); return Py::Vector(Base::Vector3d(dir.X(), dir.Y(), dir.Z())); } @@ -135,7 +143,7 @@ Py::Object ToroidPy::getAxis() const void ToroidPy::setAxis(Py::Object arg) { Standard_Real dir_x, dir_y, dir_z; - PyObject *p = arg.ptr(); + PyObject* p = arg.ptr(); if (PyObject_TypeCheck(p, &(Base::VectorPy::Type))) { Base::Vector3d v = static_cast(p)->value(); dir_x = v.x; @@ -155,8 +163,9 @@ void ToroidPy::setAxis(Py::Object arg) } try { - Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast - (this->getGeometryPtr()->handle()); + Handle(Geom_ElementarySurface) this_surf = Handle(Geom_ElementarySurface)::DownCast( + this->getGeometryPtr()->handle() + ); gp_Ax1 axis; axis.SetLocation(this_surf->Location()); axis.SetDirection(gp_Dir(dir_x, dir_y, dir_z)); @@ -169,19 +178,21 @@ void ToroidPy::setAxis(Py::Object arg) Py::Float ToroidPy::getArea() const { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); return Py::Float(torus->Area()); } Py::Float ToroidPy::getVolume() const { - Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast - (getGeomToroidPtr()->handle()); + Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast( + getGeomToroidPtr()->handle() + ); return Py::Float(torus->Volume()); } -PyObject *ToroidPy::getCustomAttributes(const char* /*attr*/) const +PyObject* ToroidPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/TrimmedCurve.pyi b/src/Mod/Part/App/TrimmedCurve.pyi index 83e974d30a..ee15e49b64 100644 --- a/src/Mod/Part/App/TrimmedCurve.pyi +++ b/src/Mod/Part/App/TrimmedCurve.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from BoundedCurve import BoundedCurve - @export( Twin="GeomTrimmedCurve", TwinPointer="GeomTrimmedCurve", diff --git a/src/Mod/Part/App/TrimmedCurvePyImp.cpp b/src/Mod/Part/App/TrimmedCurvePyImp.cpp index ac64d32cd8..e0695dc145 100644 --- a/src/Mod/Part/App/TrimmedCurvePyImp.cpp +++ b/src/Mod/Part/App/TrimmedCurvePyImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include "OCCError.h" @@ -38,11 +38,13 @@ std::string TrimmedCurvePy::representation() const return ""; } -PyObject *TrimmedCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* TrimmedCurvePy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // never create such objects with the constructor - PyErr_SetString(PyExc_RuntimeError, - "You cannot create an instance of the abstract class 'TrimmedCurve'."); + PyErr_SetString( + PyExc_RuntimeError, + "You cannot create an instance of the abstract class 'TrimmedCurve'." + ); return nullptr; } @@ -52,18 +54,19 @@ int TrimmedCurvePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject* TrimmedCurvePy::setParameterRange(PyObject * args) +PyObject* TrimmedCurvePy::setParameterRange(PyObject* args) { Handle(Geom_Geometry) g = getGeomTrimmedCurvePtr()->handle(); Handle(Geom_TrimmedCurve) c = Handle(Geom_TrimmedCurve)::DownCast(g); try { if (!c.IsNull()) { - double u,v; - u=c->FirstParameter(); - v=c->LastParameter(); - if (!PyArg_ParseTuple(args, "|dd", &u,&v)) + double u, v; + u = c->FirstParameter(); + v = c->LastParameter(); + if (!PyArg_ParseTuple(args, "|dd", &u, &v)) { return nullptr; - getGeomTrimmedCurvePtr()->setRange(u,v); + } + getGeomTrimmedCurvePtr()->setRange(u, v); Py_Return; } } @@ -76,7 +79,7 @@ PyObject* TrimmedCurvePy::setParameterRange(PyObject * args) return nullptr; } -PyObject *TrimmedCurvePy::getCustomAttributes(const char* /*attr*/) const +PyObject* TrimmedCurvePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Part/App/VectorAdapter.cpp b/src/Mod/Part/App/VectorAdapter.cpp index 6eb0d15b82..7709fe0aa7 100644 --- a/src/Mod/Part/App/VectorAdapter.cpp +++ b/src/Mod/Part/App/VectorAdapter.cpp @@ -23,7 +23,6 @@ ***************************************************************************/ - #include #include #include "VectorAdapter.h" @@ -47,19 +46,19 @@ using Attacher::AttachEnginePlane; -namespace Part { +namespace Part +{ VectorAdapter::VectorAdapter() : status(false) -{ -} +{} -VectorAdapter::VectorAdapter(const TopoDS_Face &faceIn, const gp_Vec &pickedPointIn) +VectorAdapter::VectorAdapter(const TopoDS_Face& faceIn, const gp_Vec& pickedPointIn) : status(false) , origin(pickedPointIn) { - std::vector> funcs = { + std::vector> funcs = { [this](const TopoDS_Face& face, const gp_Vec& vec) { return this->handleElementarySurface(face, vec); }, @@ -74,7 +73,7 @@ VectorAdapter::VectorAdapter(const TopoDS_Face &faceIn, const gp_Vec &pickedPoin } } -VectorAdapter::VectorAdapter(const TopoDS_Edge &edgeIn, const gp_Vec &pickedPointIn) +VectorAdapter::VectorAdapter(const TopoDS_Edge& edgeIn, const gp_Vec& pickedPointIn) : status(false) , origin(pickedPointIn) { @@ -90,13 +89,13 @@ VectorAdapter::VectorAdapter(const TopoDS_Edge &edgeIn, const gp_Vec &pickedPoin projectOriginOntoVector(pickedPointIn); } -VectorAdapter::VectorAdapter(const TopoDS_Vertex &vertex1In, const TopoDS_Vertex &vertex2In) +VectorAdapter::VectorAdapter(const TopoDS_Vertex& vertex1In, const TopoDS_Vertex& vertex2In) : status(false) { vector = convert(vertex2In) - convert(vertex1In); vector.Normalize(); - //build origin half way. + // build origin half way. gp_Vec tempVector = (convert(vertex2In) - convert(vertex1In)); double mag = tempVector.Magnitude(); tempVector.Normalize(); @@ -106,13 +105,13 @@ VectorAdapter::VectorAdapter(const TopoDS_Vertex &vertex1In, const TopoDS_Vertex status = true; } -VectorAdapter::VectorAdapter(const gp_Vec &vector1, const gp_Vec &vector2) +VectorAdapter::VectorAdapter(const gp_Vec& vector1, const gp_Vec& vector2) : status(false) { - vector = vector2- vector1; + vector = vector2 - vector1; vector.Normalize(); - //build origin half way. + // build origin half way. gp_Vec tempVector = vector2 - vector1; double mag = tempVector.Magnitude(); tempVector.Normalize(); @@ -122,7 +121,7 @@ VectorAdapter::VectorAdapter(const gp_Vec &vector1, const gp_Vec &vector2) status = true; } -bool VectorAdapter::handleElementarySurface(const TopoDS_Face &faceIn, const gp_Vec &pickedPointIn) +bool VectorAdapter::handleElementarySurface(const TopoDS_Face& faceIn, const gp_Vec& pickedPointIn) { Handle(Geom_Surface) surface = BRep_Tool::Surface(faceIn); if (surface->IsKind(STANDARD_TYPE(Geom_ElementarySurface))) { @@ -133,9 +132,8 @@ bool VectorAdapter::handleElementarySurface(const TopoDS_Face &faceIn, const gp_ if (faceIn.Orientation() == TopAbs_REVERSED) { vector.Reverse(); } - if (surface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) || - surface->IsKind(STANDARD_TYPE(Geom_SphericalSurface)) - ) { + if (surface->IsKind(STANDARD_TYPE(Geom_CylindricalSurface)) + || surface->IsKind(STANDARD_TYPE(Geom_SphericalSurface))) { origin = eSurface->Axis().Location().XYZ(); projectOriginOntoVector(pickedPointIn); } @@ -149,7 +147,7 @@ bool VectorAdapter::handleElementarySurface(const TopoDS_Face &faceIn, const gp_ return false; } -bool VectorAdapter::handlePlanarSurface(const TopoDS_Face &faceIn, const gp_Vec &pickedPointIn) +bool VectorAdapter::handlePlanarSurface(const TopoDS_Face& faceIn, const gp_Vec& pickedPointIn) { Handle(Geom_Surface) surface = BRep_Tool::Surface(faceIn); GeomLib_IsPlanarSurface check(surface, AttachEnginePlane::planarPrecision()); @@ -175,7 +173,7 @@ bool VectorAdapter::handlePlanarSurface(const TopoDS_Face &faceIn, const gp_Vec return false; } -void VectorAdapter::projectOriginOntoVector(const gp_Vec &pickedPointIn) +void VectorAdapter::projectOriginOntoVector(const gp_Vec& pickedPointIn) { Handle(Geom_Curve) heapLine = new Geom_Line(origin.XYZ(), vector.XYZ()); gp_Pnt tempPoint(pickedPointIn.XYZ()); @@ -194,11 +192,11 @@ VectorAdapter::operator gp_Lin() const /*convert a vertex to vector*/ -gp_Vec VectorAdapter::convert(const TopoDS_Vertex &vertex) +gp_Vec VectorAdapter::convert(const TopoDS_Vertex& vertex) { gp_Pnt point = BRep_Tool::Pnt(vertex); gp_Vec out(point.X(), point.Y(), point.Z()); return out; } -} +} // namespace Part diff --git a/src/Mod/Part/App/VectorAdapter.h b/src/Mod/Part/App/VectorAdapter.h index 758d078f05..2c32b753b3 100644 --- a/src/Mod/Part/App/VectorAdapter.h +++ b/src/Mod/Part/App/VectorAdapter.h @@ -50,44 +50,54 @@ public: /*!Build a vector from a faceIn * @param faceIn vector will be normal to plane and equal to cylindrical axis. * @param pickedPointIn location of pick. straight conversion from sbvec. not accurate.*/ - VectorAdapter(const TopoDS_Face &faceIn, const gp_Vec &pickedPointIn); + VectorAdapter(const TopoDS_Face& faceIn, const gp_Vec& pickedPointIn); /*!Build a vector from an edgeIn * @param edgeIn vector will be lastPoint - firstPoint. * @param pickedPointIn location of pick. straight conversion from sbvec. not accurate.*/ - VectorAdapter(const TopoDS_Edge &edgeIn, const gp_Vec &pickedPointIn); + VectorAdapter(const TopoDS_Edge& edgeIn, const gp_Vec& pickedPointIn); /*!Build a vector From 2 vertices. *vector will be equal to @param vertex2In - @param vertex1In.*/ - VectorAdapter(const TopoDS_Vertex &vertex1In, const TopoDS_Vertex &vertex2In); + VectorAdapter(const TopoDS_Vertex& vertex1In, const TopoDS_Vertex& vertex2In); /*!Build a vector From 2 vectors. *vector will be equal to @param vector2 - @param vector1.*/ - VectorAdapter(const gp_Vec &vector1, const gp_Vec &vector2); + VectorAdapter(const gp_Vec& vector1, const gp_Vec& vector2); /*!make sure no errors in vector construction. * @return true = vector is good. false = vector is NOT good.*/ - bool isValid() const {return status;} + bool isValid() const + { + return status; + } /*!get the calculated vector. * @return the vector. use isValid to ensure correct results.*/ - explicit operator gp_Vec() const {return vector;} + explicit operator gp_Vec() const + { + return vector; + } /*!build occ line used for extrema calculation*/ explicit operator gp_Lin() const; - gp_Vec getPickPoint() const {return origin;} + gp_Vec getPickPoint() const + { + return origin; + } - explicit operator Base::Vector3d() const { + explicit operator Base::Vector3d() const + { return Base::Vector3d(vector.X(), vector.Y(), vector.Z()); } static gp_Vec convert(const TopoDS_Vertex& vertex); private: - void projectOriginOntoVector(const gp_Vec &pickedPointIn); - bool handleElementarySurface(const TopoDS_Face &faceIn, const gp_Vec &pickedPointIn); - bool handlePlanarSurface(const TopoDS_Face &faceIn, const gp_Vec &pickedPointIn); + void projectOriginOntoVector(const gp_Vec& pickedPointIn); + bool handleElementarySurface(const TopoDS_Face& faceIn, const gp_Vec& pickedPointIn); + bool handlePlanarSurface(const TopoDS_Face& faceIn, const gp_Vec& pickedPointIn); bool status; gp_Vec vector; gp_Vec origin; }; -} //namespace Part +} // namespace Part #endif diff --git a/src/Mod/Part/App/WireJoiner.cpp b/src/Mod/Part/App/WireJoiner.cpp index a318bf9827..ff0aa47b03 100644 --- a/src/Mod/Part/App/WireJoiner.cpp +++ b/src/Mod/Part/App/WireJoiner.cpp @@ -28,31 +28,31 @@ #include #include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -83,22 +83,24 @@ namespace bgi = boost::geometry::index; const size_t RParametersNumber = 16UL; using RParameters = bgi::linear; -BOOST_GEOMETRY_REGISTER_POINT_3D_GET_SET( - gp_Pnt,double,bg::cs::cartesian,X,Y,Z,SetX,SetY,SetZ) +BOOST_GEOMETRY_REGISTER_POINT_3D_GET_SET(gp_Pnt, double, bg::cs::cartesian, X, Y, Z, SetX, SetY, SetZ) -FC_LOG_LEVEL_INIT("WireJoiner",true, true) +FC_LOG_LEVEL_INIT("WireJoiner", true, true) using namespace Part; -static inline void getEndPoints(const TopoDS_Edge &eForEndPoints, gp_Pnt &p1, gp_Pnt &p2) { +static inline void getEndPoints(const TopoDS_Edge& eForEndPoints, gp_Pnt& p1, gp_Pnt& p2) +{ p1 = BRep_Tool::Pnt(TopExp::FirstVertex(eForEndPoints)); p2 = BRep_Tool::Pnt(TopExp::LastVertex(eForEndPoints)); } -static inline void getEndPoints(const TopoDS_Wire &wire, gp_Pnt &p1, gp_Pnt &p2) { +static inline void getEndPoints(const TopoDS_Wire& wire, gp_Pnt& p1, gp_Pnt& p2) +{ BRepTools_WireExplorer xp(wire); p1 = BRep_Tool::Pnt(TopoDS::Vertex(xp.CurrentVertex())); - for(;xp.More();xp.Next()) {}; + for (; xp.More(); xp.Next()) { + }; p2 = BRep_Tool::Pnt(TopoDS::Vertex(xp.CurrentVertex())); } @@ -110,12 +112,15 @@ static inline void getEndPoints(const TopoDS_Wire &wire, gp_Pnt &p1, gp_Pnt &p2) * and throws an exception unlike the standard assert which terminates the program. */ #define ENSURE(cond) \ - do { if (!(cond)) {\ - FC_ERR("Condition failed: " #cond);\ - throw Base::RuntimeError("Condition failed: " #cond);\ - } } while (0) + do { \ + if (!(cond)) { \ + FC_ERR("Condition failed: " #cond); \ + throw Base::RuntimeError("Condition failed: " #cond); \ + } \ + } while (0) -class WireJoiner::WireJoinerP { +class WireJoiner::WireJoinerP +{ public: double myTol = Precision::Confusion(); double myTol2 = myTol * myTol; @@ -131,7 +136,7 @@ public: using Box = bg::model::box; - bool checkBBox(const Bnd_Box &box) const + bool checkBBox(const Bnd_Box& box) const { if (box.IsVoid()) { return false; @@ -147,17 +152,23 @@ public: } WireJoinerP() - : catchObject(App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/WireJoiner") - ->GetASCII("ObjectName")) - , catchIteration(static_cast( + : catchObject( App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/WireJoiner") - ->GetInt("Iteration", 0))) + ->GetASCII("ObjectName") + ) + , catchIteration( + static_cast( + App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/WireJoiner") + ->GetInt("Iteration", 0) + ) + ) {} - bool getBBox(const TopoDS_Shape &eForBBox, Bnd_Box &bound) { - BRepBndLib::AddOptimal(eForBBox,bound,Standard_False); + bool getBBox(const TopoDS_Shape& eForBBox, Bnd_Box& bound) + { + BRepBndLib::AddOptimal(eForBBox, bound, Standard_False); if (bound.IsVoid()) { if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { FC_WARN("failed to get bound of edge"); @@ -174,7 +185,8 @@ public: return true; } - bool getBBox(const TopoDS_Shape &eForBBox, Box &box) { + bool getBBox(const TopoDS_Shape& eForBBox, Box& box) + { Bnd_Box bound; if (!getBBox(eForBBox, bound)) { return false; @@ -186,14 +198,15 @@ public: Standard_Real yMax = Standard_Real(); Standard_Real zMax = Standard_Real(); bound.Get(xMin, yMin, zMin, xMax, yMax, zMax); - box = Box(gp_Pnt(xMin,yMin,zMin), gp_Pnt(xMax,yMax,zMax)); + box = Box(gp_Pnt(xMin, yMin, zMin), gp_Pnt(xMax, yMax, zMax)); return true; } struct WireInfo; struct EdgeSet; - struct EdgeInfo { + struct EdgeInfo + { TopoDS_Edge edge; TopoDS_Wire superEdge; mutable TopoDS_Shape edgeReversed; @@ -208,7 +221,8 @@ public: int iteration2 {}; bool queryBBox; std::shared_ptr wireInfo {}; - std::shared_ptr wireInfo2 {}; // an edge can be shared by at most two tight bound wires. + std::shared_ptr wireInfo2 {}; // an edge can be shared by at most two tight bound + // wires. std::unique_ptr geo {}; Standard_Real firstParam {}; Standard_Real lastParam {}; @@ -216,12 +230,14 @@ public: GeomAbs_CurveType type {}; bool isLinear; - EdgeInfo(const TopoDS_Edge& eForInfo, - const gp_Pnt& pt1, - const gp_Pnt& pt2, - const Box& bound, - bool bbox, - bool isLinear) + EdgeInfo( + const TopoDS_Edge& eForInfo, + const gp_Pnt& pt1, + const gp_Pnt& pt2, + const Box& bound, + bool bbox, + bool isLinear + ) : edge(eForInfo) , p1(pt1) , p2(pt2) @@ -234,18 +250,20 @@ public: ENSURE(!curve.IsNull()); const double halving {0.5}; - GeomLProp_CLProps prop(curve,(firstParam+lastParam)*halving,0,Precision::Confusion()); + GeomLProp_CLProps prop(curve, (firstParam + lastParam) * halving, 0, Precision::Confusion()); mid = prop.Value(); reset(); } - Geometry *geometry() { + Geometry* geometry() + { if (!geo) { geo = Geometry::fromShape(edge, /*silent*/ true); } return geo.get(); } - void reset() { + void reset() + { wireInfo.reset(); wireInfo2.reset(); if (iteration >= 0) { @@ -254,7 +272,7 @@ public: iteration2 = 0; iStart[0] = iStart[1] = iEnd[0] = iEnd[1] = -1; } - const TopoDS_Shape &shape(bool forward=true) const + const TopoDS_Shape& shape(bool forward = true) const { if (superEdge.IsNull()) { if (forward) { @@ -284,7 +302,8 @@ public: }; template - struct VectorSet { + struct VectorSet + { void sort() { if (!sorted) { @@ -292,7 +311,7 @@ public: std::sort(data.begin(), data.end()); } } - bool contains(const T &vForContains) + bool contains(const T& vForContains) { if (!sorted) { constexpr static size_t dataSizeMax = 30; @@ -302,15 +321,15 @@ public: sort(); } auto it = std::ranges::lower_bound(data, vForContains); - return it!=data.end() && *it == vForContains; + return it != data.end() && *it == vForContains; } - bool intersects(const VectorSet &other) + bool intersects(const VectorSet& other) { if (other.size() < size()) { return other.intersects(*this); } if (!sorted) { - for (const auto &vector : data) { + for (const auto& vector : data) { if (other.contains(vector)) { return true; } @@ -319,7 +338,7 @@ public: else { other.sort(); auto it = other.data.begin(); - for (const auto &vertex : data) { + for (const auto& vertex : data) { it = std::lower_bound(it, other.data.end(), vertex); if (it == other.data.end()) { return false; @@ -331,7 +350,7 @@ public: } return false; } - void insert(const T &vToInsert) + void insert(const T& vToInsert) { if (sorted) { data.insert(std::ranges::upper_bound(data, vToInsert), vToInsert); @@ -340,7 +359,7 @@ public: data.push_back(vToInsert); } } - bool insertUnique(const T &vToInsertUnique) + bool insertUnique(const T& vToInsertUnique) { if (sorted) { auto it = std::ranges::lower_bound(data, vToInsertUnique); @@ -357,7 +376,7 @@ public: data.push_back(vToInsertUnique); return true; } - void erase(const T &vToErase) + void erase(const T& vToErase) { if (!sorted) { data.erase(std::remove(data.begin(), data.end(), vToErase), data.end()); @@ -388,6 +407,7 @@ public: { return data.empty(); } + private: bool sorted = false; std::vector data {}; @@ -400,20 +420,25 @@ public: std::map edgesTable {}; - struct VertexInfo { + struct VertexInfo + { Edges::iterator it {}; bool start {}; VertexInfo() = default; VertexInfo(Edges::iterator it, bool start) - :it(it),start(start) + : it(it) + , start(start) {} - VertexInfo reversed() const { + VertexInfo reversed() const + { return {it, !start}; } - bool operator==(const VertexInfo &other) const { - return it==other.it && start==other.start; + bool operator==(const VertexInfo& other) const + { + return it == other.it && start == other.start; } - bool operator<(const VertexInfo &other) const { + bool operator<(const VertexInfo& other) const + { auto thisInfo = edgeInfo(); auto otherInfo = other.edgeInfo(); if (thisInfo < otherInfo) { @@ -424,33 +449,42 @@ public: } return static_cast(start) < static_cast(other.start); } - const gp_Pnt &pt() const { - return start?it->p1:it->p2; + const gp_Pnt& pt() const + { + return start ? it->p1 : it->p2; } - gp_Pnt &pt() { - return start?it->p1:it->p2; + gp_Pnt& pt() + { + return start ? it->p1 : it->p2; } - const gp_Pnt &ptOther() const { - return start?it->p2:it->p1; + const gp_Pnt& ptOther() const + { + return start ? it->p2 : it->p1; } - gp_Pnt &ptOther() { - return start?it->p2:it->p1; + gp_Pnt& ptOther() + { + return start ? it->p2 : it->p1; } - TopoDS_Vertex vertex() const { + TopoDS_Vertex vertex() const + { return start ? TopExp::FirstVertex(edge()) : TopExp::LastVertex(edge()); } - TopoDS_Vertex otherVertex() const { + TopoDS_Vertex otherVertex() const + { return start ? TopExp::LastVertex(edge()) : TopExp::FirstVertex(edge()); } - EdgeInfo *edgeInfo() const { + EdgeInfo* edgeInfo() const + { return &(*it); } - const TopoDS_Edge &edge() const { + const TopoDS_Edge& edge() const + { return it->edge; } }; - struct StackInfo { + struct StackInfo + { size_t iStart; size_t iEnd; size_t iCurrent; @@ -466,7 +500,8 @@ public: std::vector tmpVertices {}; std::vector adjacentList {}; - struct WireInfo { + struct WireInfo + { std::vector vertices {}; mutable std::vector sorted {}; TopoDS_Wire wire; @@ -490,7 +525,7 @@ public: return vertices[vA] < vertices[vB]; }); } - int find(const VertexInfo &info) const + int find(const VertexInfo& info) const { const size_t verticesSizeMax = 20; if (vertices.size() < verticesSizeMax) { @@ -501,19 +536,23 @@ public: return (static_cast(it - vertices.begin()) + 1); } sort(); - const auto it = std::lower_bound(sorted.begin(), sorted.end(), info, - [&](const int idx, const VertexInfo &vertex) {return vertices[idx]edgeInfo() == info) { return (static_cast(it - vertices.begin()) + 1); } @@ -521,15 +560,19 @@ public: return 0; } sort(); - const auto it = std::lower_bound(sorted.begin(), sorted.end(), info, - [&](int idx, const EdgeInfo *vertex) {return vertices[idx].edgeInfo() { + struct EdgeSet: VectorSet + { }; EdgeSet edgeSet; - struct WireSet: VectorSet { + struct WireSet: VectorSet + { }; WireSet wireSet; - const Bnd_Box &getWireBound(const WireInfo &wireInfo) const + const Bnd_Box& getWireBound(const WireInfo& wireInfo) const { if (wireInfo.box.IsVoid()) { for (auto& vertex : wireInfo.vertices) { @@ -604,7 +649,7 @@ public: return true; } - bool initWireInfo(WireInfo &wireInfo) + bool initWireInfo(WireInfo& wireInfo) { if (!wireInfo.face.IsNull()) { return true; @@ -629,7 +674,7 @@ public: return true; } - bool isInside(const WireInfo &wireInfo, gp_Pnt &pt) const + bool isInside(const WireInfo& wireInfo, gp_Pnt& pt) const { if (getWireBound(wireInfo).IsOut(pt)) { return false; @@ -638,7 +683,7 @@ public: return fc.State() == TopAbs_IN; } - bool isOutside(const WireInfo &wireInfo, gp_Pnt &pt) const + bool isOutside(const WireInfo& wireInfo, gp_Pnt& pt) const { if (getWireBound(wireInfo).IsOut(pt)) { return false; @@ -650,7 +695,8 @@ public: struct PntGetter { using result_type = const gp_Pnt&; - result_type operator()(const VertexInfo &vInfo) const { + result_type operator()(const VertexInfo& vInfo) const + { return vInfo.pt(); } }; @@ -660,7 +706,8 @@ public: struct BoxGetter { using result_type = const Box&; - result_type operator()(Edges::iterator it) const { + result_type operator()(Edges::iterator it) const + { return it->box; } }; @@ -697,12 +744,12 @@ public: if (it->queryBBox) { boxMap.remove(it); } - vmap.remove(VertexInfo(it,true)); - vmap.remove(VertexInfo(it,false)); + vmap.remove(VertexInfo(it, true)); + vmap.remove(VertexInfo(it, false)); return edges.erase(it); } - void remove(EdgeInfo *info) + void remove(EdgeInfo* info) { if (edgesTable.empty()) { for (auto it = edges.begin(); it != edges.end(); ++it) { @@ -718,21 +765,21 @@ public: void add(Edges::iterator it) { - vmap.insert(VertexInfo(it,true)); - vmap.insert(VertexInfo(it,false)); + vmap.insert(VertexInfo(it, true)); + vmap.insert(VertexInfo(it, false)); if (it->queryBBox) { boxMap.insert(it); } showShape(it->edge, "add"); } - int add(const TopoDS_Edge &eToAdd, bool queryBBox=false) + int add(const TopoDS_Edge& eToAdd, bool queryBBox = false) { auto it = edges.begin(); return add(eToAdd, queryBBox, it); } - int add(const TopoDS_Edge &eToAdd, bool queryBBox, Edges::iterator &it) + int add(const TopoDS_Edge& eToAdd, bool queryBBox, Edges::iterator& it) { Box bbox; if (!getBBox(eToAdd, bbox)) { @@ -744,12 +791,14 @@ public: } // This method was originally part of WireJoinerP::add(), split to reduce cognitive complexity - bool addNoDuplicates(const TopoDS_Edge& eToAdd, - TopoDS_Vertex& v2, - TopoDS_Edge& ev2, - const bool isLinear, - const VertexInfo& vinfo, - std::unique_ptr& geo) + bool addNoDuplicates( + const TopoDS_Edge& eToAdd, + TopoDS_Vertex& v2, + TopoDS_Edge& ev2, + const bool isLinear, + const VertexInfo& vinfo, + std::unique_ptr& geo + ) { if (v2.IsNull()) { ev2 = vinfo.edge(); @@ -774,15 +823,17 @@ public: } // This method was originally part of WireJoinerP::add(), split to reduce cognitive complexity - bool addValidEdges(const TopoDS_Edge& eToAdd, - const gp_Pnt p1, - const double tol, - TopoDS_Vertex& v1, - TopoDS_Edge& ev1, - const gp_Pnt p2, - TopoDS_Vertex& v2, - TopoDS_Edge& ev2, - const bool isLinear) + bool addValidEdges( + const TopoDS_Edge& eToAdd, + const gp_Pnt p1, + const double tol, + TopoDS_Vertex& v1, + TopoDS_Edge& ev1, + const gp_Pnt p2, + TopoDS_Vertex& v2, + TopoDS_Edge& ev2, + const bool isLinear + ) { std::unique_ptr geo; constexpr int max = std::numeric_limits::max(); @@ -805,7 +856,7 @@ public: } double d2 = vinfo.ptOther().SquareDistance(p2); if (d2 < tol) { - if (!addNoDuplicates(eToAdd, v2, ev2, isLinear, vinfo, geo)){ + if (!addNoDuplicates(eToAdd, v2, ev2, isLinear, vinfo, geo)) { return false; } } @@ -813,11 +864,11 @@ public: return true; } - bool add(const TopoDS_Edge &eToAdd, bool queryBBox, const Box &bbox, Edges::iterator &it) + bool add(const TopoDS_Edge& eToAdd, bool queryBBox, const Box& bbox, Edges::iterator& it) { gp_Pnt p1 = gp_Pnt(); gp_Pnt p2 = gp_Pnt(); - getEndPoints(eToAdd,p1,p2); + getEndPoints(eToAdd, p1, p2); TopoDS_Vertex v1 = TopoDS_Vertex(); TopoDS_Vertex v2 = TopoDS_Vertex(); TopoDS_Edge ev1 = TopoDS_Edge(); @@ -827,13 +878,13 @@ public: showShape(eToAdd, "addcheck"); bool isLinear = TopoShape(eToAdd).isLinearEdge(); - if (!addValidEdges(eToAdd, p1, tol, v1, ev1, p2, v2, ev2, isLinear)){ + if (!addValidEdges(eToAdd, p1, tol, v1, ev1, p2, v2, ev2, isLinear)) { return false; } if (v2.IsNull()) { - for (auto vit=vmap.qbegin(bgi::nearest(p2,1));vit!=vmap.qend();++vit) { - auto &vinfo = *vit; + for (auto vit = vmap.qbegin(bgi::nearest(p2, 1)); vit != vmap.qend(); ++vit) { + auto& vinfo = *vit; double d1 = vinfo.pt().SquareDistance(p2); if (d1 < tol) { v2 = vit->vertex(); @@ -856,12 +907,14 @@ public: if (vCurrent.IsSame(vOther)) { return; } - double tol = std::max(BRep_Tool::Pnt(vCurrent).Distance(BRep_Tool::Pnt(vOther)), - BRep_Tool::Tolerance(vOther)); + double tol = std::max( + BRep_Tool::Pnt(vCurrent).Distance(BRep_Tool::Pnt(vOther)), + BRep_Tool::Tolerance(vOther) + ); if (tol >= BRep_Tool::Tolerance(vCurrent)) { ShapeFix_ShapeTolerance fix; const double halving {0.5}; - fix.SetTolerance(vCurrent, std::max(tol*halving, myTol), TopAbs_VERTEX); + fix.SetTolerance(vCurrent, std::max(tol * halving, myTol), TopAbs_VERTEX); } BRepBuilderAPI_MakeWire mkWire(eOther); mkWire.Add(eCurrent); @@ -886,15 +939,15 @@ public: sourceEdges.erase(itSource); sourceEdges.insert(newEdge); } - getEndPoints(edge,p1,p2); + getEndPoints(edge, p1, p2); // Shall we also update bbox? } - it = edges.emplace(it,edge,p1,p2,bbox,queryBBox,isLinear); + it = edges.emplace(it, edge, p1, p2, bbox, queryBBox, isLinear); add(it); return true; } - void add(const TopoDS_Shape &shape, bool queryBBox=false) + void add(const TopoDS_Shape& shape, bool queryBBox = false) { for (TopExp_Explorer xp(shape, TopAbs_EDGE); xp.More(); xp.Next()) { add(TopoDS::Edge(xp.Current()), queryBBox); @@ -902,10 +955,7 @@ public: } // This method was originally part of WireJoinerP::join(), split to reduce cognitive complexity - void joinMakeWire(const int idx, - BRepBuilderAPI_MakeWire& mkWire, - const Edges::iterator it, - bool& done) + void joinMakeWire(const int idx, BRepBuilderAPI_MakeWire& mkWire, const Edges::iterator it, bool& done) { double tol = myTol2; gp_Pnt pstart(it->p1); @@ -959,11 +1009,11 @@ public: } } - //This algorithm tries to join connected edges into wires + // This algorithm tries to join connected edges into wires // - //tol*tol>Precision::SquareConfusion() can be used to join points that are - //close but do not coincide with a line segment. The close points may be - //the results of rounding issue. + // tol*tol>Precision::SquareConfusion() can be used to join points that are + // close but do not coincide with a line segment. The close points may be + // the results of rounding issue. // void join() { @@ -974,15 +1024,16 @@ public: remove(it); bool done = false; - for (int idx=0;!done&&idx<2;++idx) { + for (int idx = 0; !done && idx < 2; ++idx) { joinMakeWire(idx, mkWire, it, done); } - builder.Add(compound,mkWire.Wire()); + builder.Add(compound, mkWire.Wire()); } } - struct IntersectInfo { + struct IntersectInfo + { double param; TopoDS_Shape intersectShape; gp_Pnt point; @@ -991,12 +1042,13 @@ public: , intersectShape(std::move(sToIntersect)) , point(pt) {} - bool operator<(const IntersectInfo &other) const { + bool operator<(const IntersectInfo& other) const + { return param < other.param; } }; - void checkSelfIntersection(const EdgeInfo &info, std::set ¶ms) const + void checkSelfIntersection(const EdgeInfo& info, std::set& params) const { // Early return if checking for self intersection (only for non linear spline curves) if (info.type <= GeomAbs_Parabola || info.isLinear) { @@ -1027,7 +1079,7 @@ public: analysis.CheckSelfIntersectingEdge(1, points2d, points3d); ENSURE(points2d.Length() == points3d.Length()); - for (int i=1; i<=points2d.Length(); ++i) { + for (int i = 1; i <= points2d.Length(); ++i) { params.emplace(points2d(i).ParamOnFirst(), points3d(i), info.edge); params.emplace(points2d(i).ParamOnSecond(), points3d(i), info.edge); } @@ -1035,10 +1087,12 @@ public: // This method was originally part of WireJoinerP::checkIntersection(), split to reduce // cognitive complexity - bool checkIntersectionPlanar(const EdgeInfo& info, - const EdgeInfo& other, - std::set& params1, - std::set& params2) + bool checkIntersectionPlanar( + const EdgeInfo& info, + const EdgeInfo& other, + std::set& params1, + std::set& params2 + ) { gp_Pln pln; bool planar = TopoShape(info.edge).findPlane(pln); @@ -1104,10 +1158,12 @@ public: // This method was originally part of WireJoinerP::checkIntersection(), split to reduce // cognitive complexity - static bool checkIntersectionMakeWire(const EdgeInfo& info, - const EdgeInfo& other, - int& idx, - TopoDS_Wire& wire) + static bool checkIntersectionMakeWire( + const EdgeInfo& info, + const EdgeInfo& other, + int& idx, + TopoDS_Wire& wire + ) { BRepBuilderAPI_MakeWire mkWire(info.edge); mkWire.Add(other.edge); @@ -1159,12 +1215,14 @@ public: return true; } - void checkIntersection(const EdgeInfo &info, - const EdgeInfo &other, - std::set ¶ms1, - std::set ¶ms2) + void checkIntersection( + const EdgeInfo& info, + const EdgeInfo& other, + std::set& params1, + std::set& params2 + ) { - if(!checkIntersectionPlanar(info, other, params1, params2)){ + if (!checkIntersectionPlanar(info, other, params1, params2)) { return; } @@ -1180,7 +1238,7 @@ public: TopoDS_Wire wire; int idx = 0; - if (!checkIntersectionMakeWire(info, other, idx, wire)){ + if (!checkIntersectionMakeWire(info, other, idx, wire)) { return; } @@ -1194,16 +1252,18 @@ public: analysis.CheckIntersectingEdges(1, idx, points2d, points3d, errors); ENSURE(points2d.Length() == points3d.Length()); - for (int i=1; i<=points2d.Length(); ++i) { + for (int i = 1; i <= points2d.Length(); ++i) { pushIntersection(params1, points2d(i).ParamOnFirst(), points3d(i), other.edge); pushIntersection(params2, points2d(i).ParamOnSecond(), points3d(i), info.edge); } } - void pushIntersection(std::set& params, - double param, - const gp_Pnt& pt, - const TopoDS_Shape& shape) + void pushIntersection( + std::set& params, + double param, + const gp_Pnt& pt, + const TopoDS_Shape& shape + ) { IntersectInfo info(param, pt, shape); auto it = params.upper_bound(info); @@ -1222,7 +1282,8 @@ public: params.insert(it, info); } - struct SplitInfo { + struct SplitInfo + { TopoDS_Edge edge; TopoDS_Shape intersectShape; Box bbox; @@ -1230,11 +1291,13 @@ public: // This method was originally part of WireJoinerP::splitEdges(), split to reduce cognitive // complexity - void splitEdgesMakeEdge(const std::set::iterator& itParam, - const EdgeInfo& info, - std::vector& splits, - std::set::iterator& itPrevParam, - const TopoDS_Shape& intersectShape) + void splitEdgesMakeEdge( + const std::set::iterator& itParam, + const EdgeInfo& info, + std::vector& splits, + std::set::iterator& itPrevParam, + const TopoDS_Shape& intersectShape + ) { // Using points cause MakeEdge failure for some reason. Using // parameters is better. @@ -1258,17 +1321,21 @@ public: } } else if (FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) { - FC_WARN("edge split failed " << std::setprecision(16) << FC_XYZ(p1) << FC_XYZ(p2) - << ": " << mkEdge.Error()); + FC_WARN( + "edge split failed " << std::setprecision(16) << FC_XYZ(p1) << FC_XYZ(p2) << ": " + << mkEdge.Error() + ); } } // This method was originally part of WireJoinerP::splitEdges(), split to reduce cognitive // complexity - void splitEdgesMakeEdges(std::set::iterator& itParam, - const std::set& params, - const EdgeInfo& info, - std::vector& splits) + void splitEdgesMakeEdges( + std::set::iterator& itParam, + const std::set& params, + const EdgeInfo& info, + std::vector& splits + ) { for (auto itPrevParam = itParam++; itParam != params.end(); ++itParam) { const auto& intersectShape = itParam->intersectShape.IsNull() @@ -1287,23 +1354,24 @@ public: { std::unordered_map> intersects; - int idx=0; + int idx = 0; for (auto& info : edges) { info.iteration = ++idx; } std::unique_ptr seq( - new Base::SequencerLauncher("Splitting edges", edges.size())); + new Base::SequencerLauncher("Splitting edges", edges.size()) + ); idx = 0; for (auto& info : edges) { seq->next(true); ++idx; - auto ¶ms = intersects[&info]; + auto& params = intersects[&info]; checkSelfIntersection(info, params); - for (auto vit=boxMap.qbegin(bgi::intersects(info.box)); vit!=boxMap.qend(); ++vit) { - const auto &other = *(*vit); + for (auto vit = boxMap.qbegin(bgi::intersects(info.box)); vit != boxMap.qend(); ++vit) { + const auto& other = *(*vit); if (other.iteration <= idx) { // means the edge is before us, and we've already checked intersection continue; @@ -1312,17 +1380,17 @@ public: } } - idx=0; + idx = 0; std::vector splits; - for (auto it=edges.begin(); it!=edges.end(); ) { + for (auto it = edges.begin(); it != edges.end();) { ++idx; auto iter = intersects.find(&(*it)); if (iter == intersects.end()) { ++it; continue; } - auto &info = *it; - auto ¶ms = iter->second; + auto& info = *it; + auto& params = iter->second; if (params.empty()) { ++it; continue; @@ -1362,7 +1430,7 @@ public: if (!add(split.edge, false, split.bbox, it)) { continue; } - auto &newInfo = *it++; + auto& newInfo = *it++; aHistory->AddModified(split.intersectShape, newInfo.edge); // if (v.intersectShape != removedEdge) // aHistory->AddModified(removedEdge, newInfo.edge); @@ -1486,7 +1554,8 @@ public: void findSuperEdges() { std::unique_ptr seq( - new Base::SequencerLauncher("Combining edges", edges.size())); + new Base::SequencerLauncher("Combining edges", edges.size()) + ); std::deque vertices; @@ -1553,8 +1622,7 @@ public: info.iEnd[ic] = info.iStart[ic] = (int)adjacentList.size(); constexpr int max = std::numeric_limits::max(); - for (auto vit = vmap.qbegin(bgi::nearest(pt[ic], max)); vit != vmap.qend(); - ++vit) { + for (auto vit = vmap.qbegin(bgi::nearest(pt[ic], max)); vit != vmap.qend(); ++vit) { auto& vinfo = *vit; if (vinfo.pt().SquareDistance(pt[ic]) > myTol2) { break; @@ -1644,19 +1712,20 @@ public: // This algorithm tries to find a set of closed wires that includes as many // edges (added by calling add() ) as possible. One edge may be included // in more than one closed wires if it connects to more than one edges. - void findClosedWires(bool tightBound=false) + void findClosedWires(bool tightBound = false) { std::unique_ptr seq( - new Base::SequencerLauncher("Finding wires", edges.size())); + new Base::SequencerLauncher("Finding wires", edges.size()) + ); - for (auto &info : edges) { + for (auto& info : edges) { info.wireInfo.reset(); info.wireInfo2.reset(); } - for (auto it=edges.begin(); it!=edges.end(); ++it) { + for (auto it = edges.begin(); it != edges.end(); ++it) { VertexInfo beginVertex(it, true); - auto &beginInfo = *it; + auto& beginInfo = *it; seq->next(true); ++iteration; if (beginInfo.iteration < 0 || beginInfo.wireInfo) { @@ -1664,7 +1733,7 @@ public: } VertexInfo currentVertex(it, true); - EdgeInfo *currentInfo = &beginInfo; + EdgeInfo* currentInfo = &beginInfo; showShape(currentInfo, "begin"); stack.clear(); vertexStack.clear(); @@ -1682,9 +1751,9 @@ public: beginInfo.wireInfo->vertices.emplace_back(it, true); beginInfo.wireInfo->wire = wire; } - for (auto &entry : stack) { - const auto &vertex = vertexStack[entry.iCurrent]; - auto &info = *vertex.it; + for (auto& entry : stack) { + const auto& vertex = vertexStack[entry.iCurrent]; + auto& info = *vertex.it; if (tightBound) { beginInfo.wireInfo->vertices.push_back(vertex); } @@ -1693,7 +1762,7 @@ public: // showShape(&info, "visited"); } } - showShape(wire,"joined"); + showShape(wire, "joined"); if (!tightBound) { builder.Add(compound, wire); } @@ -1705,13 +1774,13 @@ public: // https://github.com/realthunder/FreeCAD/blob/6f15849be2505f98927e75d0e8352185e14e7b72/src/Mod/Part/App/WireJoiner.cpp#L1366 // for reference - void checkWireInfo(const WireInfo &wireInfo) + void checkWireInfo(const WireInfo& wireInfo) { (void)wireInfo; if (FC_LOG_INSTANCE.level() <= FC_LOGLEVEL_TRACE) { return; } - for (auto &info : edges) { + for (auto& info : edges) { if (auto wire = info.wireInfo.get()) { boost::ignore_unused(wire); @@ -1722,9 +1791,11 @@ public: // This method was originally part of WireJoinerP::_findClosedWires(), split to reduce cognitive // complexity - void _findClosedWiresBeginEdge(const std::shared_ptr& wireInfo, - const EdgeInfo& beginInfo, - int& idx) + void _findClosedWiresBeginEdge( + const std::shared_ptr& wireInfo, + const EdgeInfo& beginInfo, + int& idx + ) { auto info = wireInfo->vertices[idx].edgeInfo(); showShape(info, "merge", iteration); @@ -1751,15 +1822,17 @@ public: // This method was originally part of WireJoinerP::_findClosedWires(), split to reduce cognitive // complexity - int _findClosedWiresWithExisting(int* idxVertex, - const std::shared_ptr& wireInfo, - int* const stackPos, - bool& proceed, - const VertexInfo& vinfo, - const int ic, - StackInfo& stackBack, - const EdgeInfo& beginInfo, - EdgeInfo& info) + int _findClosedWiresWithExisting( + int* idxVertex, + const std::shared_ptr& wireInfo, + int* const stackPos, + bool& proceed, + const VertexInfo& vinfo, + const int ic, + StackInfo& stackBack, + const EdgeInfo& beginInfo, + EdgeInfo& info + ) { if (wireInfo) { // We may be called by findTightBound() with an existing wire @@ -1802,13 +1875,15 @@ public: // This method was originally part of WireJoinerP::_findClosedWires(), split to reduce cognitive // complexity - void _findClosedWiresUpdateStack(int* idxVertex, - const std::shared_ptr& wireInfo, - int* stackPos, - const EdgeInfo* currentInfo, - const int currentIdx, - bool& proceed, - const EdgeInfo& beginInfo) + void _findClosedWiresUpdateStack( + int* idxVertex, + const std::shared_ptr& wireInfo, + int* stackPos, + const EdgeInfo* currentInfo, + const int currentIdx, + bool& proceed, + const EdgeInfo& beginInfo + ) { auto& stackBack = stack.back(); @@ -1852,15 +1927,17 @@ public: } info.iteration = iteration; - int exists = _findClosedWiresWithExisting(idxVertex, - wireInfo, - stackPos, - proceed, - vinfo, - i, - stackBack, - beginInfo, - info); + int exists = _findClosedWiresWithExisting( + idxVertex, + wireInfo, + stackPos, + proceed, + vinfo, + i, + stackBack, + beginInfo, + info + ); if (exists == 1) { break; @@ -1877,11 +1954,13 @@ public: // This method was originally part of WireJoinerP::_findClosedWires(), split to reduce cognitive // complexity - bool _findClosedWiresUpdateEdges(VertexInfo& currentVertex, - gp_Pnt& pend, - EdgeInfo* currentInfo, - int& currentIdx, - const size_t stackEnd) + bool _findClosedWiresUpdateEdges( + VertexInfo& currentVertex, + gp_Pnt& pend, + EdgeInfo* currentInfo, + int& currentIdx, + const size_t stackEnd + ) { while (true) { auto& stackBack = stack.back(); @@ -1900,7 +1979,10 @@ public: } break; } - vertexStack.erase(vertexStack.begin() + static_cast(stackBack.iStart), vertexStack.end()); + vertexStack.erase( + vertexStack.begin() + static_cast(stackBack.iStart), + vertexStack.end() + ); stack.pop_back(); if (stack.size() == stackEnd) { @@ -1919,9 +2001,11 @@ public: // This method was originally part of WireJoinerP::_findClosedWires(), split to reduce cognitive // complexity - bool _findClosedWiresIsClosed(const VertexInfo& beginVertex, - const TopoDS_Wire& wire, - const EdgeInfo& beginInfo) + bool _findClosedWiresIsClosed( + const VertexInfo& beginVertex, + const TopoDS_Wire& wire, + const EdgeInfo& beginInfo + ) { if (!BRep_Tool::IsClosed(wire)) { FC_WARN("failed to close some wire in iteration " << iteration); @@ -1939,16 +2023,18 @@ public: return true; } - TopoDS_Wire _findClosedWires(VertexInfo beginVertex, - VertexInfo currentVertex, - int *idxVertex = nullptr, - const std::shared_ptr& wireInfo = std::shared_ptr(), - int* stackPos = nullptr) + TopoDS_Wire _findClosedWires( + VertexInfo beginVertex, + VertexInfo currentVertex, + int* idxVertex = nullptr, + const std::shared_ptr& wireInfo = std::shared_ptr(), + int* stackPos = nullptr + ) { Base::SequencerBase::Instance().checkAbort(); - EdgeInfo &beginInfo = *beginVertex.it; + EdgeInfo& beginInfo = *beginVertex.it; - EdgeInfo *currentInfo = currentVertex.edgeInfo(); + EdgeInfo* currentInfo = currentVertex.edgeInfo(); int currentIdx = currentVertex.start ? 1 : 0; currentInfo->iteration = iteration; @@ -1968,23 +2054,21 @@ public: bool proceed = true; - _findClosedWiresUpdateStack(idxVertex, - wireInfo, - stackPos, - currentInfo, - currentIdx, - proceed, - beginInfo); + _findClosedWiresUpdateStack( + idxVertex, + wireInfo, + stackPos, + currentInfo, + currentIdx, + proceed, + beginInfo + ); // Originally here there was a call to the method checkStack(), which does nothing and // therefore has been removed. if (proceed) { - if (_findClosedWiresUpdateEdges(currentVertex, - pend, - currentInfo, - currentIdx, - stackEnd)) { + if (_findClosedWiresUpdateEdges(currentVertex, pend, currentInfo, currentIdx, stackEnd)) { return {}; } @@ -2005,9 +2089,9 @@ public: wireData->Clear(); wireData->Add(beginInfo.shape(beginVertex.start)); - for (auto &entry : stack) { - const auto &vertex = vertexStack[entry.iCurrent]; - auto &info = *vertex.it; + for (auto& entry : stack) { + const auto& vertex = vertexStack[entry.iCurrent]; + auto& info = *vertex.it; wireData->Add(info.shape(vertex.start)); } TopoDS_Wire wire = makeCleanWire(); @@ -2020,13 +2104,15 @@ public: // This method was originally part of WireJoinerP::findTightBound(), split to reduce cognitive // complexity - void findTightBoundSplitWire(const std::shared_ptr& wireInfo, - const EdgeInfo& beginInfo, - const std::vector& wireVertices, - std::shared_ptr& splitWire, - const int idxV, - int& idxStart, - const int idxEnd) + void findTightBoundSplitWire( + const std::shared_ptr& wireInfo, + const EdgeInfo& beginInfo, + const std::vector& wireVertices, + std::shared_ptr& splitWire, + const int idxV, + int& idxStart, + const int idxEnd + ) { for (int idx = idxV; idx != idxEnd; ++idx) { auto info = wireVertices[idx].edgeInfo(); @@ -2048,13 +2134,15 @@ public: // This method was originally part of WireJoinerP::findTightBound(), split to reduce cognitive // complexity - void findTightBoundWithSplit(const std::vector& wireVertices, - const int idxV, - const std::shared_ptr& splitWire, - const int idxStart, - const int idxEnd, - const int stackPos, - const int stackStart) + void findTightBoundWithSplit( + const std::vector& wireVertices, + const int idxV, + const std::shared_ptr& splitWire, + const int idxStart, + const int idxEnd, + const int stackPos, + const int stackStart + ) { auto& splitEdges = splitWire->vertices; gp_Pnt pstart; @@ -2100,14 +2188,16 @@ public: // This method was originally part of WireJoinerP::findTightBound(), split to reduce cognitive // complexity - void findTightBoundByVertices(EdgeInfo& beginInfo, - const std::vector& wireVertices, - int& idxV, - const int iteration2, - const gp_Pnt& pstart, - const std::shared_ptr& wireInfo, - const VertexInfo& beginVertex, - std::shared_ptr& newWire) + void findTightBoundByVertices( + EdgeInfo& beginInfo, + const std::vector& wireVertices, + int& idxV, + const int iteration2, + const gp_Pnt& pstart, + const std::shared_ptr& wireInfo, + const VertexInfo& beginVertex, + std::shared_ptr& newWire + ) { const int idx = wireVertices[idxV].start ? 1 : 0; @@ -2143,11 +2233,7 @@ public: TopoDS_Wire wire; if (pstart.SquareDistance(currentVertex.ptOther()) > myTol2) { - wire = _findClosedWires(beginVertex, - currentVertex, - &idxEnd, - beginInfo.wireInfo, - &stackPos); + wire = _findClosedWires(beginVertex, currentVertex, &idxEnd, beginInfo.wireInfo, &stackPos); if (wire.IsNull()) { vertexStack.pop_back(); stack.pop_back(); @@ -2190,22 +2276,10 @@ public: ENSURE(idxV <= idxEnd); int idxStart = idxV; - findTightBoundSplitWire(wireInfo, - beginInfo, - wireVertices, - splitWire, - idxV, - idxStart, - idxEnd); + findTightBoundSplitWire(wireInfo, beginInfo, wireVertices, splitWire, idxV, idxStart, idxEnd); if (splitWire) { - findTightBoundWithSplit(wireVertices, - idxV, - splitWire, - idxStart, - idxEnd, - stackPos, - stackStart); + findTightBoundWithSplit(wireVertices, idxV, splitWire, idxStart, idxEnd, stackPos, stackStart); } checkWireInfo(*newWire); @@ -2246,9 +2320,8 @@ public: } if (tmpVertices.size() != otherWireVertices.size()) { otherWireVertices.erase(otherWireVertices.begin(), it); - otherWireVertices.insert(otherWireVertices.end(), - tmpVertices.begin(), - tmpVertices.end()); + otherWireVertices + .insert(otherWireVertices.end(), tmpVertices.begin(), tmpVertices.end()); } } @@ -2272,10 +2345,11 @@ public: // adjacent list built earlier), and split the wire whenever possible. std::unique_ptr seq( - new Base::SequencerLauncher("Finding tight bound", edges.size())); + new Base::SequencerLauncher("Finding tight bound", edges.size()) + ); int iteration2 = iteration; - for (auto &info : edges) { + for (auto& info : edges) { ++iteration; seq->next(true); if (info.iteration < 0 || !info.wireInfo) { @@ -2283,12 +2357,12 @@ public: } ++iteration2; - while(!info.wireInfo->done) { + while (!info.wireInfo->done) { auto wireInfo = info.wireInfo; checkWireInfo(*wireInfo); - const auto &wireVertices = wireInfo->vertices; + const auto& wireVertices = wireInfo->vertices; auto beginVertex = wireVertices.front(); - auto &beginInfo = *beginVertex.it; + auto& beginInfo = *beginVertex.it; initWireInfo(*wireInfo); showShape(wireInfo->wire, "iwire", iteration); for (auto& vertex : wireVertices) { @@ -2304,14 +2378,16 @@ public: int idxV = 0; while (true) { - findTightBoundByVertices(beginInfo, - wireVertices, - idxV, - iteration2, - pstart, - wireInfo, - beginVertex, - newWire); + findTightBoundByVertices( + beginInfo, + wireVertices, + idxV, + iteration2, + pstart, + wireInfo, + beginVertex, + newWire + ); if (newWire) { ++iteration; @@ -2338,15 +2414,17 @@ public: } } - // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce cognitive - // complexity - void exhaustTightBoundUpdateVertex(const int iteration2, - const VertexInfo& beginVertex, - const int idxV, - const gp_Pnt& pstart, - const std::vector& wireVertices, - std::shared_ptr& newWire, - const std::shared_ptr& wireInfo) + // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce + // cognitive complexity + void exhaustTightBoundUpdateVertex( + const int iteration2, + const VertexInfo& beginVertex, + const int idxV, + const gp_Pnt& pstart, + const std::vector& wireVertices, + std::shared_ptr& newWire, + const std::shared_ptr& wireInfo + ) { const int idx = wireVertices[idxV].start ? 1 : 0; auto current = wireVertices[idxV].edgeInfo(); @@ -2415,25 +2493,29 @@ public: } } - // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce cognitive - // complexity - void exhaustTightBoundUpdateEdge(const int iteration2, - const VertexInfo& beginVertex, - const std::vector& wireVertices, - const gp_Pnt& pstart, - std::shared_ptr& wireInfo) + // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce + // cognitive complexity + void exhaustTightBoundUpdateEdge( + const int iteration2, + const VertexInfo& beginVertex, + const std::vector& wireVertices, + const gp_Pnt& pstart, + std::shared_ptr& wireInfo + ) { std::shared_ptr newWire; int idxV = 1; while (true) { - exhaustTightBoundUpdateVertex(iteration2, - beginVertex, - idxV, - pstart, - wireVertices, - newWire, - wireInfo); + exhaustTightBoundUpdateVertex( + iteration2, + beginVertex, + idxV, + pstart, + wireVertices, + newWire, + wireInfo + ); if (newWire) { ++iteration; @@ -2462,12 +2544,14 @@ public: } } - // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce cognitive - // complexity - void exhaustTightBoundWithAdjacent(const EdgeInfo& info, - int& iteration2, - const VertexInfo beginVertex, - const EdgeInfo* check) + // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce + // cognitive complexity + void exhaustTightBoundWithAdjacent( + const EdgeInfo& info, + int& iteration2, + const VertexInfo beginVertex, + const EdgeInfo* check + ) { const gp_Pnt& pstart = beginVertex.pt(); const int vidx = beginVertex.start ? 1 : 0; @@ -2539,11 +2623,7 @@ public: vertex.it->iteration2 = iteration2; } - exhaustTightBoundUpdateEdge(iteration2, - beginVertex, - wireVertices, - pstart, - wireInfo); + exhaustTightBoundUpdateEdge(iteration2, beginVertex, wireVertices, pstart, wireInfo); } if (wireInfo && wireInfo->done) { @@ -2571,8 +2651,8 @@ public: } } - // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce cognitive - // complexity + // This method was originally part of WireJoinerP::exhaustTightBound(), split to reduce + // cognitive complexity void exhaustTightBoundUpdateWire(const EdgeInfo& info, int& iteration2) { @@ -2606,13 +2686,14 @@ public: // bound wires. std::unique_ptr seq( - new Base::SequencerLauncher("Exhaust tight bound", edges.size())); + new Base::SequencerLauncher("Exhaust tight bound", edges.size()) + ); - for (auto &info : edges) { + for (auto& info : edges) { if (info.iteration < 0 || !info.wireInfo || !info.wireInfo->done) { continue; } - for (auto &vertex : info.wireInfo->vertices) { + for (auto& vertex : info.wireInfo->vertices) { auto edgeInfo = vertex.edgeInfo(); if (edgeInfo->wireInfo != info.wireInfo) { edgeInfo->wireInfo2 = info.wireInfo; @@ -2621,13 +2702,10 @@ public: } int iteration2 = iteration; - for (auto &info : edges) { + for (auto& info : edges) { ++iteration; seq->next(true); - if (info.iteration < 0 - || !info.wireInfo - || !info.wireInfo->done) - { + if (info.iteration < 0 || !info.wireInfo || !info.wireInfo->done) { if (info.wireInfo) { showShape(*info.wireInfo, "iskip"); } @@ -2643,15 +2721,16 @@ public: } exhaustTightBoundUpdateWire(info, iteration2); - } wireSet.clear(); } // This method was originally part of WireJoinerP::makeCleanWire(), split to reduce cognitive // complexity - void printHistoryInit(const Handle(BRepTools_History)& newHistory, - const std::vector& inputEdges) + void printHistoryInit( + const Handle(BRepTools_History) & newHistory, + const std::vector& inputEdges + ) { FC_MSG("init:"); for (const auto& shape : sourceEdges) { @@ -2659,8 +2738,10 @@ public: constexpr int max = std::numeric_limits::max(); FC_MSG(shape.getShape().TShape().get() << ", " << shape.getShape().HashCode(max)); #else - FC_MSG(shape.getShape().TShape().get() - << ", " << std::hash {}(shape.getShape())); + FC_MSG( + shape.getShape().TShape().get() + << ", " << std::hash {}(shape.getShape()) + ); #endif } printHistory(aHistory, sourceEdges); @@ -2684,7 +2765,7 @@ public: } } - TopoDS_Wire makeCleanWire(bool fixGap=true) + TopoDS_Wire makeCleanWire(bool fixGap = true) { // Make a clean wire with sorted, oriented, connected, etc edges TopoDS_Wire result; @@ -2736,25 +2817,29 @@ public: // This method was originally part of WireJoinerP::printHistory(), split to reduce cognitive // complexity template - void printHistoryOfShape(const Handle(BRepTools_History)& hist, const T& shape) + void printHistoryOfShape(const Handle(BRepTools_History) & hist, const T& shape) { for (TopTools_ListIteratorOfListOfShape it(hist->Modified(shape.getShape())); it.More(); it.Next()) { #if OCC_VERSION_HEX < 0x070800 - constexpr int max = std::numeric_limits::max(); - FC_MSG(shape.getShape().TShape().get() - << ", " << shape.getShape().HashCode(max) << " -> " - << it.Value().TShape().get() << ", " << it.Value().HashCode(max)); + constexpr int max = std::numeric_limits::max(); + FC_MSG( + shape.getShape().TShape().get() + << ", " << shape.getShape().HashCode(max) << " -> " << it.Value().TShape().get() + << ", " << it.Value().HashCode(max) + ); #else - FC_MSG(shape.getShape().TShape().get() - << ", " << std::hash {}(shape.getShape()) << " -> " - << it.Value().TShape().get() << ", " << std::hash {}(it.Value())); + FC_MSG( + shape.getShape().TShape().get() + << ", " << std::hash {}(shape.getShape()) << " -> " + << it.Value().TShape().get() << ", " << std::hash {}(it.Value()) + ); #endif } } template - void printHistory(Handle(BRepTools_History) hist, const T &input) + void printHistory(Handle(BRepTools_History) hist, const T& input) { FC_MSG("\nHistory:\n"); for (const auto& shape : input) { @@ -2762,7 +2847,7 @@ public: } } - bool canShowShape(int idx=-1, bool forced=false) const + bool canShowShape(int idx = -1, bool forced = false) const { if (idx < 0 || catchIteration == 0 || catchIteration > idx) { if (!forced && FC_LOG_INSTANCE.level() <= FC_LOGLEVEL_TRACE) { @@ -2780,7 +2865,7 @@ public: showShape(info->shape(), name, idx, forced); } - void showShape(WireInfo &wireInfo, const char *name, int idx=-1, bool forced=false) + void showShape(WireInfo& wireInfo, const char* name, int idx = -1, bool forced = false) { if (!canShowShape(idx, forced)) { return; @@ -2791,10 +2876,7 @@ public: showShape(wireInfo.wire, name, idx, forced); } - void showShape(const TopoDS_Shape& sToShow, - const char* name, - int idx = -1, - bool forced = false) const + void showShape(const TopoDS_Shape& sToShow, const char* name, int idx = -1, bool forced = false) const { if (!canShowShape(idx, forced)) { return; @@ -2915,8 +2997,8 @@ public: // those entries. bool hasOpenEdge = false; - for (const auto &info : edges) { - if (info.iteration == -3 || (!info.wireInfo && info.iteration>=0)) { + for (const auto& info : edges) { + if (info.iteration == -3 || (!info.wireInfo && info.iteration >= 0)) { if (!hasOpenEdge) { hasOpenEdge = true; builder.MakeCompound(openWireCompound); @@ -2926,7 +3008,7 @@ public: } } - void addWire(std::shared_ptr &wireInfo) + void addWire(std::shared_ptr& wireInfo) { if (!wireInfo || !wireInfo->done || !wireSet.insertUnique(wireInfo.get())) { return; @@ -2935,7 +3017,8 @@ public: builder.Add(compound, wireInfo->wire); } - bool getOpenWires(TopoShape &shape, const char *op, bool noOriginal) { + bool getOpenWires(TopoShape& shape, const char* op, bool noOriginal) + { if (openWireCompound.IsNull()) { shape.setShape(TopoShape()); return false; @@ -2946,9 +3029,9 @@ public: source.makeElementCompound(sourceEdgeArray); auto wires = TopoShape(openWireCompound, -1).getSubTopoShapes(TopAbs_WIRE); bool touched = false; - for (auto it=wires.begin(); it!=wires.end();) { + for (auto it = wires.begin(); it != wires.end();) { bool purge = true; - for (const auto &edge : it->getSubShapes(TopAbs_EDGE)) { + for (const auto& edge : it->getSubShapes(TopAbs_EDGE)) { if (source.findSubShapesWithSharedVertex(TopoShape(edge, -1)).empty()) { purge = false; break; @@ -2970,14 +3053,17 @@ public: comp = TopoDS::Compound(TopoShape(-1).makeElementCompound(wires).getShape()); } } - shape.makeShapeWithElementMap(comp, - MapperHistory(aHistory), - {sourceEdges.begin(), sourceEdges.end()}, - op); + shape.makeShapeWithElementMap( + comp, + MapperHistory(aHistory), + {sourceEdges.begin(), sourceEdges.end()}, + op + ); return true; } - bool getResultWires(TopoShape &shape, const char *op) { + bool getResultWires(TopoShape& shape, const char* op) + { // As compound is created by various calls to builder.MakeCompound() it looks that the // following condition is always false. // Probably it may be needed to add something like compound.Nullify() as done for @@ -2986,23 +3072,24 @@ public: shape.setShape(TopoShape()); return false; } - shape.makeShapeWithElementMap(compound, - MapperHistory(aHistory), - {sourceEdges.begin(), sourceEdges.end()}, - op); + shape.makeShapeWithElementMap( + compound, + MapperHistory(aHistory), + {sourceEdges.begin(), sourceEdges.end()}, + op + ); return true; } }; WireJoiner::WireJoiner() - :pimpl(new WireJoinerP()) -{ -} + : pimpl(new WireJoinerP()) +{} WireJoiner::~WireJoiner() = default; -void WireJoiner::addShape(const TopoShape &shape) +void WireJoiner::addShape(const TopoShape& shape) { NotDone(); for (auto& edge : shape.getSubTopoShapes(TopAbs_EDGE)) { @@ -3010,20 +3097,20 @@ void WireJoiner::addShape(const TopoShape &shape) } } -void WireJoiner::addShape(const std::vector &shapes) +void WireJoiner::addShape(const std::vector& shapes) { NotDone(); - for (const auto &shape : shapes) { + for (const auto& shape : shapes) { for (auto& edge : shape.getSubTopoShapes(TopAbs_EDGE)) { pimpl->sourceEdgeArray.push_back(edge); } } } -void WireJoiner::addShape(const std::vector &shapes) +void WireJoiner::addShape(const std::vector& shapes) { NotDone(); - for (const auto &shape : shapes) { + for (const auto& shape : shapes) { for (TopExp_Explorer xp(shape, TopAbs_EDGE); xp.More(); xp.Next()) { pimpl->sourceEdgeArray.emplace_back(TopoDS::Edge(xp.Current()), -1); } @@ -3096,31 +3183,31 @@ void WireJoiner::Build(const Message_ProgressRange& theRange) Done(); } -bool WireJoiner::getOpenWires(TopoShape &shape, const char *op, bool noOriginal) +bool WireJoiner::getOpenWires(TopoShape& shape, const char* op, bool noOriginal) { Build(); return pimpl->getOpenWires(shape, op, noOriginal); } -bool WireJoiner::getResultWires(TopoShape &shape, const char *op) +bool WireJoiner::getResultWires(TopoShape& shape, const char* op) { Build(); return pimpl->getResultWires(shape, op); } -const TopTools_ListOfShape& WireJoiner::Generated (const TopoDS_Shape& SThatGenerates) +const TopTools_ListOfShape& WireJoiner::Generated(const TopoDS_Shape& SThatGenerates) { Build(); return pimpl->aHistory->Generated(SThatGenerates); } -const TopTools_ListOfShape& WireJoiner::Modified (const TopoDS_Shape& SThatModifies) +const TopTools_ListOfShape& WireJoiner::Modified(const TopoDS_Shape& SThatModifies) { Build(); return pimpl->aHistory->Modified(SThatModifies); } -Standard_Boolean WireJoiner::IsDeleted (const TopoDS_Shape& SDeleted) +Standard_Boolean WireJoiner::IsDeleted(const TopoDS_Shape& SDeleted) { Build(); return pimpl->aHistory->IsRemoved(SDeleted); diff --git a/src/Mod/Part/App/WireJoiner.h b/src/Mod/Part/App/WireJoiner.h index 60c89e69ac..6d4eb6fc48 100644 --- a/src/Mod/Part/App/WireJoiner.h +++ b/src/Mod/Part/App/WireJoiner.h @@ -32,40 +32,42 @@ #include -namespace Part{ +namespace Part +{ -class PartExport WireJoiner: public BRepBuilderAPI_MakeShape { +class PartExport WireJoiner: public BRepBuilderAPI_MakeShape +{ public: WireJoiner(); ~WireJoiner() override; - void addShape(const TopoShape &shape); - void addShape(const std::vector &shapes); - void addShape(const std::vector &shapes); + void addShape(const TopoShape& shape); + void addShape(const std::vector& shapes); + void addShape(const std::vector& shapes); - void setOutline(bool enable=true); - void setTightBound(bool enable=true); - void setSplitEdges(bool enable=true); - void setMergeEdges(bool enable=true); - void setTolerance(double tolerance, double atol=0.0); + void setOutline(bool enable = true); + void setTightBound(bool enable = true); + void setSplitEdges(bool enable = true); + void setMergeEdges(bool enable = true); + void setTolerance(double tolerance, double atol = 0.0); - bool getOpenWires(TopoShape &shape, const char *op="", bool noOriginal=true); - bool getResultWires(TopoShape &shape, const char *op=""); + bool getOpenWires(TopoShape& shape, const char* op = "", bool noOriginal = true); + bool getResultWires(TopoShape& shape, const char* op = ""); #if OCC_VERSION_HEX < 0x070600 void Build() override; #else void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) override; #endif - const TopTools_ListOfShape& Modified (const TopoDS_Shape& SThatModifies) override; - const TopTools_ListOfShape& Generated (const TopoDS_Shape& SThatGenerates) override; - Standard_Boolean IsDeleted (const TopoDS_Shape& SDeleted) override; + const TopTools_ListOfShape& Modified(const TopoDS_Shape& SThatModifies) override; + const TopTools_ListOfShape& Generated(const TopoDS_Shape& SThatGenerates) override; + Standard_Boolean IsDeleted(const TopoDS_Shape& SDeleted) override; private: class WireJoinerP; std::unique_ptr pimpl; }; -} // namespace Part +} // namespace Part -#endif // PART_WIRE_JOINER_H +#endif // PART_WIRE_JOINER_H diff --git a/src/Mod/Part/App/edgecluster.cpp b/src/Mod/Part/App/edgecluster.cpp index 219a98ce87..076eac326d 100644 --- a/src/Mod/Part/App/edgecluster.cpp +++ b/src/Mod/Part/App/edgecluster.cpp @@ -22,11 +22,11 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include "edgecluster.h" @@ -35,7 +35,7 @@ using namespace Part; Edgecluster::Edgecluster(const std::vector& unsorted_edges) - :m_unsortededges(unsorted_edges) + : m_unsortededges(unsorted_edges) { m_edges.clear(); m_vertices.clear(); @@ -52,50 +52,45 @@ tEdgeClusterVector Edgecluster::GetClusters() void Edgecluster::Perform() { - if ( m_unsortededges.empty() ) + if (m_unsortededges.empty()) { return; + } - //adds all the vertices to a map, and store the associated edges + // adds all the vertices to a map, and store the associated edges std::vector::iterator aVectorIt; - for (aVectorIt = m_unsortededges.begin();aVectorIt != m_unsortededges.end();++aVectorIt) - { - if (IsValidEdge(*aVectorIt)) - { + for (aVectorIt = m_unsortededges.begin(); aVectorIt != m_unsortededges.end(); ++aVectorIt) { + if (IsValidEdge(*aVectorIt)) { Perform(*aVectorIt); } } - //now, iterate through the edges to sort and cluster them + // now, iterate through the edges to sort and cluster them - do - { + do { m_edges.clear(); - //Lets start with a vertice that only has one edge (that means start or end point of the merged edges!) + // Lets start with a vertice that only has one edge (that means start or end point of the + // merged edges!) tMapPntEdge::iterator iter; bool closed = true; - for(iter=m_vertices.begin();iter!=m_vertices.end();++iter) - { - if (iter->second.size()==1) - { + for (iter = m_vertices.begin(); iter != m_vertices.end(); ++iter) { + if (iter->second.size() == 1) { closed = false; break; } } - if(closed) + if (closed) { iter = m_vertices.begin(); + } const gp_Pnt& firstPoint = iter->first; gp_Pnt currentPoint = firstPoint; Standard_Boolean toContinue; - do - { + do { toContinue = PerformEdges(currentPoint); - } - while (toContinue == Standard_True); - //Store the current adjacent edges as a cluster + } while (toContinue == Standard_True); + // Store the current adjacent edges as a cluster m_final_cluster.push_back(m_edges); - //and continue now with the still existing edges in the m_vertices - } - while (!m_vertices.empty()); + // and continue now with the still existing edges in the m_vertices + } while (!m_vertices.empty()); m_done = true; } @@ -103,17 +98,17 @@ void Edgecluster::Perform() bool Edgecluster::PerformEdges(gp_Pnt& point) { tMapPntEdge::iterator iter = m_vertices.find(point); - if ( iter == m_vertices.end() ) + if (iter == m_vertices.end()) { return false; + } tEdgeVector& edges = iter->second; tEdgeVector::iterator edgeIt = edges.begin(); - //no more edges. pb - if ( edgeIt == edges.end() ) - { - //Delete also the current vertex + // no more edges. pb + if (edgeIt == edges.end()) { + // Delete also the current vertex m_vertices.erase(iter); return false; @@ -121,88 +116,85 @@ bool Edgecluster::PerformEdges(gp_Pnt& point) TopoDS_Edge theEdge = *edgeIt; - //we are storing the edge, so remove it from the vertex association + // we are storing the edge, so remove it from the vertex association edges.erase(edgeIt); - //if no more edges, remove the vertex - if ( edges.empty() ) + // if no more edges, remove the vertex + if (edges.empty()) { m_vertices.erase(iter); + } - TopoDS_Vertex V1,V2; - TopExp::Vertices(theEdge,V1,V2); + TopoDS_Vertex V1, V2; + TopExp::Vertices(theEdge, V1, V2); gp_Pnt P1 = BRep_Tool::Pnt(V1); gp_Pnt P2 = BRep_Tool::Pnt(V2); - if ( theEdge.Orientation() == TopAbs_REVERSED ) - { - //switch the points + if (theEdge.Orientation() == TopAbs_REVERSED) { + // switch the points gp_Pnt tmpP = P1; P1 = P2; P2 = tmpP; } gp_Pnt nextPoint; - if ( P2.IsEqual(point,0.2) ) - { - //need to reverse the edge + if (P2.IsEqual(point, 0.2)) { + // need to reverse the edge theEdge.Reverse(); nextPoint = P1; } - else - { + else { nextPoint = P2; } - //need to erase the edge from the second point + // need to erase the edge from the second point iter = m_vertices.find(nextPoint); - if ( iter != m_vertices.end() ) - { + if (iter != m_vertices.end()) { tEdgeVector& nextEdges = iter->second; - for ( edgeIt = nextEdges.begin() ; edgeIt != nextEdges.end(); ++edgeIt ) - { - if ( theEdge.IsSame(*edgeIt) ) - { + for (edgeIt = nextEdges.begin(); edgeIt != nextEdges.end(); ++edgeIt) { + if (theEdge.IsSame(*edgeIt)) { nextEdges.erase(edgeIt); break; } } } - //put the edge at the end of the list + // put the edge at the end of the list m_edges.push_back(theEdge); - //Update the point for the next do-while loop + // Update the point for the next do-while loop point = nextPoint; return true; - } void Edgecluster::Perform(const TopoDS_Edge& edge) { - if ( edge.IsNull() ) + if (edge.IsNull()) { return; - TopoDS_Vertex V1,V2; - TopExp::Vertices(edge,V1,V2); + } + TopoDS_Vertex V1, V2; + TopExp::Vertices(edge, V1, V2); gp_Pnt P1 = BRep_Tool::Pnt(V1); gp_Pnt P2 = BRep_Tool::Pnt(V2); tEdgeVector emptyList; - std::pair iter = m_vertices.insert(tMapPntEdgePair(P1,emptyList)); + std::pair iter = m_vertices.insert(tMapPntEdgePair(P1, emptyList)); iter.first->second.push_back(edge); - iter = m_vertices.insert(tMapPntEdgePair(P2,emptyList)); + iter = m_vertices.insert(tMapPntEdgePair(P2, emptyList)); iter.first->second.push_back(edge); } bool Edgecluster::IsValidEdge(const TopoDS_Edge& edge) { - if ( edge.IsNull() ) + if (edge.IsNull()) { return false; - if ( BRep_Tool::Degenerated(edge) ) + } + if (BRep_Tool::Degenerated(edge)) { return false; + } BRepAdaptor_Curve bac(edge); @@ -212,19 +204,20 @@ bool Edgecluster::IsValidEdge(const TopoDS_Edge& edge) gp_Pnt fpoint = bac.Value(fparam); gp_Pnt lpoint = bac.Value(lparam); - //do not test the distance first last in case of a full circle edge (fpoint == lastpoint) - //if ( fpoint.IsEqual(lpoint,1e-5 ) ) - // return false; + // do not test the distance first last in case of a full circle edge (fpoint == lastpoint) + // if ( fpoint.IsEqual(lpoint,1e-5 ) ) + // return false; - gp_Pnt mpoint = bac.Value((fparam+lparam)*0.5); + gp_Pnt mpoint = bac.Value((fparam + lparam) * 0.5); Standard_Real dist = mpoint.Distance(lpoint); - if ( dist <= 1e-5 ) + if (dist <= 1e-5) { return false; + } dist = mpoint.Distance(fpoint); - if ( dist <= 1e-5 ) + if (dist <= 1e-5) { return false; + } return true; } - diff --git a/src/Mod/Part/App/edgecluster.h b/src/Mod/Part/App/edgecluster.h index cb38c5ded0..559b899872 100644 --- a/src/Mod/Part/App/edgecluster.h +++ b/src/Mod/Part/App/edgecluster.h @@ -34,30 +34,34 @@ #include -namespace Part { +namespace Part +{ struct Edgesort_gp_Pnt_Less { - bool operator()(const gp_Pnt & _Left, const gp_Pnt & _Right) const + bool operator()(const gp_Pnt& _Left, const gp_Pnt& _Right) const { - Standard_Real x1,y1,z1,x2,y2,z2; - _Left.Coord(x1,y1,z1); - _Right.Coord(x2,y2,z2); - if ( fabs(x1- x2) > 0.2 ) + Standard_Real x1, y1, z1, x2, y2, z2; + _Left.Coord(x1, y1, z1); + _Right.Coord(x2, y2, z2); + if (fabs(x1 - x2) > 0.2) { return x1 < x2; - else if ( fabs(y1 -y2) > 0.2 ) + } + else if (fabs(y1 - y2) > 0.2) { return y1 < y2; - else if ( fabs(z1 -z2) > 0.2 ) + } + else if (fabs(z1 - z2) > 0.2) { return z1 < z2; + } return false; } }; using tEdgeVector = std::vector; -using tMapPntEdge = std::map; -using tMapPntEdgePair = std::pair; -using tEdgeClusterVector = std::vector >; +using tMapPntEdge = std::map; +using tMapPntEdgePair = std::pair; +using tEdgeClusterVector = std::vector>; class PartExport Edgecluster @@ -79,12 +83,11 @@ private: tEdgeVector m_edges; tMapPntEdge m_vertices; - bool m_done{false}; + bool m_done {false}; tEdgeVector::const_iterator m_edgeIter; - }; -} +} // namespace Part -#endif // PART_EDGECLUSTER_H +#endif // PART_EDGECLUSTER_H diff --git a/src/Mod/Part/App/encodeFilename.h b/src/Mod/Part/App/encodeFilename.h index ab095c0a4d..3989a95a76 100644 --- a/src/Mod/Part/App/encodeFilename.h +++ b/src/Mod/Part/App/encodeFilename.h @@ -33,6 +33,6 @@ inline std::string encodeFilename(std::string fn) return fn; } -} //namespace Part +} // namespace Part -#endif // PART_ENCODEFILENAME_H +#endif // PART_ENCODEFILENAME_H diff --git a/src/Mod/Part/App/modelRefine.cpp b/src/Mod/Part/App/modelRefine.cpp index a489b06e92..077a5d5228 100644 --- a/src/Mod/Part/App/modelRefine.cpp +++ b/src/Mod/Part/App/modelRefine.cpp @@ -23,49 +23,49 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -75,38 +75,36 @@ using namespace ModelRefine; -void ModelRefine::getFaceEdges(const TopoDS_Face &face, EdgeVectorType &edges) +void ModelRefine::getFaceEdges(const TopoDS_Face& face, EdgeVectorType& edges) { TopExp_Explorer it; - for (it.Init(face, TopAbs_EDGE); it.More(); it.Next()) + for (it.Init(face, TopAbs_EDGE); it.More(); it.Next()) { edges.push_back(TopoDS::Edge(it.Current())); + } } -void ModelRefine::boundaryEdges(const FaceVectorType &faces, EdgeVectorType &edgesOut) +void ModelRefine::boundaryEdges(const FaceVectorType& faces, EdgeVectorType& edgesOut) { - //this finds all the boundary edges. Maybe more than one boundary. + // this finds all the boundary edges. Maybe more than one boundary. std::list edges; FaceVectorType::const_iterator faceIt; - for (faceIt = faces.begin(); faceIt != faces.end(); ++faceIt) - { + for (faceIt = faces.begin(); faceIt != faces.end(); ++faceIt) { EdgeVectorType faceEdges; EdgeVectorType::iterator faceEdgesIt; getFaceEdges(*faceIt, faceEdges); - for (faceEdgesIt = faceEdges.begin(); faceEdgesIt != faceEdges.end(); ++faceEdgesIt) - { + for (faceEdgesIt = faceEdges.begin(); faceEdgesIt != faceEdges.end(); ++faceEdgesIt) { bool foundSignal(false); std::list::iterator edgesIt; - for (edgesIt = edges.begin(); edgesIt != edges.end(); ++edgesIt) - { - if ((*edgesIt).IsSame(*faceEdgesIt)) - { + for (edgesIt = edges.begin(); edgesIt != edges.end(); ++edgesIt) { + if ((*edgesIt).IsSame(*faceEdgesIt)) { edgesIt = edges.erase(edgesIt); foundSignal = true; break; } } - if (!foundSignal) + if (!foundSignal) { edges.push_back(*faceEdgesIt); + } } } @@ -114,44 +112,45 @@ void ModelRefine::boundaryEdges(const FaceVectorType &faces, EdgeVectorType &edg std::copy(edges.begin(), edges.end(), back_inserter(edgesOut)); } -TopoDS_Shell ModelRefine::removeFaces(const TopoDS_Shell &shell, const FaceVectorType &faces) +TopoDS_Shell ModelRefine::removeFaces(const TopoDS_Shell& shell, const FaceVectorType& faces) { ShapeBuild_ReShape rebuilder; FaceVectorType::const_iterator it; - for (it = faces.begin(); it != faces.end(); ++it) + for (it = faces.begin(); it != faces.end(); ++it) { rebuilder.Remove(*it); + } return TopoDS::Shell(rebuilder.Apply(shell)); } namespace ModelRefine { - class WireSort +class WireSort +{ +public: + bool operator()(const TopoDS_Wire& wire1, const TopoDS_Wire& wire2) { - public: - bool operator() (const TopoDS_Wire& wire1, const TopoDS_Wire& wire2) - { - Bnd_Box box1, box2; - BRepBndLib::Add(wire1, box1); - BRepBndLib::Add(wire2, box2); - // Note: This works because we can be sure that the wires do not intersect - return box2.SquareExtent() < box1.SquareExtent(); - } - }; -} + Bnd_Box box1, box2; + BRepBndLib::Add(wire1, box1); + BRepBndLib::Add(wire2, box2); + // Note: This works because we can be sure that the wires do not intersect + return box2.SquareExtent() < box1.SquareExtent(); + } +}; +} // namespace ModelRefine //////////////////////////////////////////////////////////////////////////////////////////// -void FaceTypeSplitter::addShell(const TopoDS_Shell &shellIn) +void FaceTypeSplitter::addShell(const TopoDS_Shell& shellIn) { shell = shellIn; } -void FaceTypeSplitter::registerType(const GeomAbs_SurfaceType &type) +void FaceTypeSplitter::registerType(const GeomAbs_SurfaceType& type) { typeMap.insert(SplitMapType::value_type(type, FaceVectorType())); } -bool FaceTypeSplitter::hasType(const GeomAbs_SurfaceType &type) const +bool FaceTypeSplitter::hasType(const GeomAbs_SurfaceType& type) const { return typeMap.find(type) != typeMap.end(); } @@ -159,92 +158,93 @@ bool FaceTypeSplitter::hasType(const GeomAbs_SurfaceType &type) const void FaceTypeSplitter::split() { TopExp_Explorer shellIt; - for (shellIt.Init(shell, TopAbs_FACE); shellIt.More(); shellIt.Next()) - { + for (shellIt.Init(shell, TopAbs_FACE); shellIt.More(); shellIt.Next()) { TopoDS_Face tempFace(TopoDS::Face(shellIt.Current())); GeomAbs_SurfaceType currentType = FaceTypedBase::getFaceType(tempFace); SplitMapType::iterator mapIt = typeMap.find(currentType); - if (mapIt == typeMap.end()) + if (mapIt == typeMap.end()) { continue; + } (*mapIt).second.push_back(tempFace); } } -const FaceVectorType& FaceTypeSplitter::getTypedFaceVector(const GeomAbs_SurfaceType &type) const +const FaceVectorType& FaceTypeSplitter::getTypedFaceVector(const GeomAbs_SurfaceType& type) const { - if (this->hasType(type)) + if (this->hasType(type)) { return (*(typeMap.find(type))).second; - //error here. + } + // error here. static FaceVectorType error; return error; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// -FaceAdjacencySplitter::FaceAdjacencySplitter(const TopoDS_Shell &shell) +FaceAdjacencySplitter::FaceAdjacencySplitter(const TopoDS_Shell& shell) { TopExp_Explorer shellIt; - for (shellIt.Init(shell, TopAbs_FACE); shellIt.More(); shellIt.Next()) - { + for (shellIt.Init(shell, TopAbs_FACE); shellIt.More(); shellIt.Next()) { TopTools_ListOfShape shapeList; TopExp_Explorer it; - for (it.Init(shellIt.Current(), TopAbs_EDGE); it.More(); it.Next()) + for (it.Init(shellIt.Current(), TopAbs_EDGE); it.More(); it.Next()) { shapeList.Append(it.Current()); + } faceToEdgeMap.Add(shellIt.Current(), shapeList); } TopExp::MapShapesAndAncestors(shell, TopAbs_EDGE, TopAbs_FACE, edgeToFaceMap); } -void FaceAdjacencySplitter::split(const FaceVectorType &facesIn) +void FaceAdjacencySplitter::split(const FaceVectorType& facesIn) { facesInMap.Clear(); processedMap.Clear(); adjacencyArray.clear(); FaceVectorType::const_iterator it; - for (it = facesIn.begin(); it != facesIn.end(); ++it) + for (it = facesIn.begin(); it != facesIn.end(); ++it) { facesInMap.Add(*it); - //the reserve call guarantees the vector will never get "pushed back" in the - //recursiveFind calls, thus invalidating the iterators. We can be sure of this as any one - //matched set can't be bigger than the set passed in. if we have seg faults, we will - //want to turn this tempFaces vector back into a std::list ensuring valid iterators - //at the expense of std::find speed. + } + // the reserve call guarantees the vector will never get "pushed back" in the + // recursiveFind calls, thus invalidating the iterators. We can be sure of this as any one + // matched set can't be bigger than the set passed in. if we have seg faults, we will + // want to turn this tempFaces vector back into a std::list ensuring valid iterators + // at the expense of std::find speed. FaceVectorType tempFaces; tempFaces.reserve(facesIn.size() + 1); - for (it = facesIn.begin(); it != facesIn.end(); ++it) - { - //skip already processed shapes. - if (processedMap.Contains(*it)) + for (it = facesIn.begin(); it != facesIn.end(); ++it) { + // skip already processed shapes. + if (processedMap.Contains(*it)) { continue; + } tempFaces.clear(); processedMap.Add(*it); recursiveFind(*it, tempFaces); - if (tempFaces.size() > 1) - { + if (tempFaces.size() > 1) { adjacencyArray.push_back(tempFaces); } } } -void FaceAdjacencySplitter::recursiveFind(const TopoDS_Face &face, FaceVectorType &outVector) +void FaceAdjacencySplitter::recursiveFind(const TopoDS_Face& face, FaceVectorType& outVector) { outVector.push_back(face); - const TopTools_ListOfShape &edges = faceToEdgeMap.FindFromKey(face); + const TopTools_ListOfShape& edges = faceToEdgeMap.FindFromKey(face); TopTools_ListIteratorOfListOfShape edgeIt; - for (edgeIt.Initialize(edges); edgeIt.More(); edgeIt.Next()) - { - const TopTools_ListOfShape &faces = edgeToFaceMap.FindFromKey(edgeIt.Value()); + for (edgeIt.Initialize(edges); edgeIt.More(); edgeIt.Next()) { + const TopTools_ListOfShape& faces = edgeToFaceMap.FindFromKey(edgeIt.Value()); TopTools_ListIteratorOfListOfShape faceIt; - for (faceIt.Initialize(faces); faceIt.More(); faceIt.Next()) - { - if (!facesInMap.Contains(faceIt.Value())) + for (faceIt.Initialize(faces); faceIt.More(); faceIt.Next()) { + if (!facesInMap.Contains(faceIt.Value())) { continue; - if (processedMap.Contains(faceIt.Value())) + } + if (processedMap.Contains(faceIt.Value())) { continue; + } processedMap.Add(faceIt.Value()); recursiveFind(TopoDS::Face(faceIt.Value()), outVector); } @@ -253,26 +253,22 @@ void FaceAdjacencySplitter::recursiveFind(const TopoDS_Face &face, FaceVectorTyp ////////////////////////////////////////////////////////////////////////////////////////////////////// -void FaceEqualitySplitter::split(const FaceVectorType &faces, FaceTypedBase *object) +void FaceEqualitySplitter::split(const FaceVectorType& faces, FaceTypedBase* object) { std::vector tempVector; tempVector.reserve(faces.size()); FaceVectorType::const_iterator faceIt; - for (faceIt = faces.begin(); faceIt != faces.end(); ++faceIt) - { + for (faceIt = faces.begin(); faceIt != faces.end(); ++faceIt) { bool foundMatch(false); std::vector::iterator tempIt; - for (tempIt = tempVector.begin(); tempIt != tempVector.end(); ++tempIt) - { - if (object->isEqual((*tempIt).front(), *faceIt)) - { + for (tempIt = tempVector.begin(); tempIt != tempVector.end(); ++tempIt) { + if (object->isEqual((*tempIt).front(), *faceIt)) { (*tempIt).push_back(*faceIt); foundMatch = true; break; } } - if (!foundMatch) - { + if (!foundMatch) { FaceVectorType another; another.reserve(faces.size()); another.push_back(*faceIt); @@ -280,57 +276,55 @@ void FaceEqualitySplitter::split(const FaceVectorType &faces, FaceTypedBase *obj } } std::vector::iterator it; - for (it = tempVector.begin(); it != tempVector.end(); ++it) - { - if ((*it).size() < 2) + for (it = tempVector.begin(); it != tempVector.end(); ++it) { + if ((*it).size() < 2) { continue; + } equalityVector.push_back(*it); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// -GeomAbs_SurfaceType FaceTypedBase::getFaceType(const TopoDS_Face &faceIn) +GeomAbs_SurfaceType FaceTypedBase::getFaceType(const TopoDS_Face& faceIn) { Handle(Geom_Surface) surface = BRep_Tool::Surface(faceIn); GeomAdaptor_Surface surfaceTest(surface); return surfaceTest.GetType(); } -void FaceTypedBase::boundarySplit(const FaceVectorType &facesIn, std::vector &boundariesOut) const +void FaceTypedBase::boundarySplit( + const FaceVectorType& facesIn, + std::vector& boundariesOut +) const { EdgeVectorType bEdges; boundaryEdges(facesIn, bEdges); std::list edges; std::copy(bEdges.begin(), bEdges.end(), back_inserter(edges)); - while(!edges.empty()) - { + while (!edges.empty()) { TopoDS_Vertex destination = TopExp::FirstVertex(edges.front(), Standard_True); TopoDS_Vertex lastVertex = TopExp::LastVertex(edges.front(), Standard_True); EdgeVectorType boundary; boundary.push_back(edges.front()); edges.pop_front(); - //single edge closed check. - if (destination.IsSame(lastVertex)) - { + // single edge closed check. + if (destination.IsSame(lastVertex)) { boundariesOut.push_back(boundary); continue; } bool closedSignal(false); std::list::iterator it; - for (it = edges.begin(); it != edges.end();) - { + for (it = edges.begin(); it != edges.end();) { TopoDS_Vertex currentVertex = TopExp::FirstVertex(*it, Standard_True); - if (lastVertex.IsSame(currentVertex)) - { + if (lastVertex.IsSame(currentVertex)) { boundary.push_back(*it); lastVertex = TopExp::LastVertex(*it, Standard_True); edges.erase(it); it = edges.begin(); - if (lastVertex.IsSame(destination)) - { + if (lastVertex.IsSame(destination)) { closedSignal = true; break; } @@ -338,47 +332,55 @@ void FaceTypedBase::boundarySplit(const FaceVectorType &facesIn, std::vectorBasisSurface()); + Handle(Geom_Plane) planeSurfaceOut; + Handle(Geom_Surface) surface = BRep_Tool::Surface(faceIn); + if (!surface.IsNull()) { + planeSurfaceOut = Handle(Geom_Plane)::DownCast(surface); + if (planeSurfaceOut.IsNull()) { + Handle(Geom_RectangularTrimmedSurface) trimmedSurface = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(surface); + if (!trimmedSurface.IsNull()) { + planeSurfaceOut = Handle(Geom_Plane)::DownCast(trimmedSurface->BasisSurface()); + } + } } - } - return planeSurfaceOut; + return planeSurfaceOut; } -bool FaceTypedPlane::isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const +bool FaceTypedPlane::isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const { - Handle(Geom_Plane) planeSurfaceOne = getGeomPlane(faceOne); - Handle(Geom_Plane) planeSurfaceTwo = getGeomPlane(faceTwo); - if (planeSurfaceOne.IsNull() || planeSurfaceTwo.IsNull()) - return false;//error? + Handle(Geom_Plane) planeSurfaceOne = getGeomPlane(faceOne); + Handle(Geom_Plane) planeSurfaceTwo = getGeomPlane(faceTwo); + if (planeSurfaceOne.IsNull() || planeSurfaceTwo.IsNull()) { + return false; // error? + } gp_Pln planeOne(planeSurfaceOne->Pln()); gp_Pln planeTwo(planeSurfaceTwo->Pln()); - return (planeOne.Position().Direction().IsParallel(planeTwo.Position().Direction(), Precision::Confusion()) && - planeOne.Distance(planeTwo.Position().Location()) < Precision::Confusion()); + return ( + planeOne.Position().Direction().IsParallel( + planeTwo.Position().Direction(), + Precision::Confusion() + ) + && planeOne.Distance(planeTwo.Position().Location()) < Precision::Confusion() + ); } GeomAbs_SurfaceType FaceTypedPlane::getType() const @@ -386,21 +388,22 @@ GeomAbs_SurfaceType FaceTypedPlane::getType() const return GeomAbs_Plane; } -TopoDS_Face FaceTypedPlane::buildFace(const FaceVectorType &faces) const +TopoDS_Face FaceTypedPlane::buildFace(const FaceVectorType& faces) const { std::vector wires; std::vector splitEdges; this->boundarySplit(faces, splitEdges); - if (splitEdges.empty()) + if (splitEdges.empty()) { return {}; + } std::vector::iterator splitIt; - for (splitIt = splitEdges.begin(); splitIt != splitEdges.end(); ++splitIt) - { + for (splitIt = splitEdges.begin(); splitIt != splitEdges.end(); ++splitIt) { BRepLib_MakeWire wireMaker; EdgeVectorType::iterator it; - for (it = (*splitIt).begin(); it != (*splitIt).end(); ++it) + for (it = (*splitIt).begin(); it != (*splitIt).end(); ++it) { wireMaker.Add(*it); + } TopoDS_Wire currentWire = wireMaker.Wire(); wires.push_back(currentWire); } @@ -408,22 +411,25 @@ TopoDS_Face FaceTypedPlane::buildFace(const FaceVectorType &faces) const std::sort(wires.begin(), wires.end(), ModelRefine::WireSort()); BRepLib_MakeFace faceMaker(wires.at(0), Standard_True); - if (faceMaker.Error() != BRepLib_FaceDone) + if (faceMaker.Error() != BRepLib_FaceDone) { return {}; + } TopoDS_Face current = faceMaker.Face(); - if (wires.size() > 1) - { + if (wires.size() > 1) { ShapeFix_Face faceFix(current); faceFix.SetContext(new ShapeBuild_ReShape()); - for (size_t index(1); indexBasisSurface()); + Handle(Geom_CylindricalSurface) cylinderSurfaceOut; + Handle(Geom_Surface) surface = BRep_Tool::Surface(faceIn); + if (!surface.IsNull()) { + cylinderSurfaceOut = Handle(Geom_CylindricalSurface)::DownCast(surface); + if (cylinderSurfaceOut.IsNull()) { + Handle(Geom_RectangularTrimmedSurface) trimmedSurface = Handle( + Geom_RectangularTrimmedSurface + )::DownCast(surface); + if (!trimmedSurface.IsNull()) { + cylinderSurfaceOut = Handle(Geom_CylindricalSurface)::DownCast( + trimmedSurface->BasisSurface() + ); + } + } } - } - return cylinderSurfaceOut; + return cylinderSurfaceOut; } -bool FaceTypedCylinder::isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const +bool FaceTypedCylinder::isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const { Handle(Geom_CylindricalSurface) surfaceOne = getGeomCylinder(faceOne); Handle(Geom_CylindricalSurface) surfaceTwo = getGeomCylinder(faceTwo); - if (surfaceOne.IsNull() || surfaceTwo.IsNull()) - return false;//probably need an error + if (surfaceOne.IsNull() || surfaceTwo.IsNull()) { + return false; // probably need an error + } gp_Cylinder cylinderOne = surfaceOne->Cylinder(); gp_Cylinder cylinderTwo = surfaceTwo->Cylinder(); - if (fabs(cylinderOne.Radius() - cylinderTwo.Radius()) > Precision::Confusion()) + if (fabs(cylinderOne.Radius() - cylinderTwo.Radius()) > Precision::Confusion()) { return false; - if (!cylinderOne.Axis().IsCoaxial(cylinderTwo.Axis(), Precision::Angular(), Precision::Confusion()) && - !cylinderOne.Axis().IsCoaxial(cylinderTwo.Axis().Reversed(), Precision::Angular(), Precision::Confusion())) + } + if (!cylinderOne.Axis().IsCoaxial(cylinderTwo.Axis(), Precision::Angular(), Precision::Confusion()) + && !cylinderOne.Axis().IsCoaxial( + cylinderTwo.Axis().Reversed(), + Precision::Angular(), + Precision::Confusion() + )) { return false; + } return true; } @@ -483,33 +499,39 @@ GeomAbs_SurfaceType FaceTypedCylinder::getType() const } // Auxiliary method -const TopoDS_Face fixFace(const TopoDS_Face& f) { +const TopoDS_Face fixFace(const TopoDS_Face& f) +{ static TopoDS_Face dummy; // Fix the face. Orientation doesn't seem to get fixed the first call. ShapeFix_Face faceFixer(f); faceFixer.SetContext(new ShapeBuild_ReShape()); faceFixer.Perform(); - if (faceFixer.Status(ShapeExtend_FAIL)) + if (faceFixer.Status(ShapeExtend_FAIL)) { return dummy; + } faceFixer.FixMissingSeam(); faceFixer.Perform(); - if (faceFixer.Status(ShapeExtend_FAIL)) - return dummy; + if (faceFixer.Status(ShapeExtend_FAIL)) { + return dummy; + } faceFixer.FixOrientation(); faceFixer.Perform(); - if (faceFixer.Status(ShapeExtend_FAIL)) + if (faceFixer.Status(ShapeExtend_FAIL)) { return dummy; + } return faceFixer.Face(); } // Detect whether a wire encircles the cylinder axis or not. This is done by calculating the // wire length, oriented with respect to the cylinder axis -bool wireEncirclesAxis(const TopoDS_Wire& wire, const Handle(Geom_CylindricalSurface)& cylinder) +bool wireEncirclesAxis(const TopoDS_Wire& wire, const Handle(Geom_CylindricalSurface) & cylinder) { double radius = cylinder->Radius(); gp_Ax1 cylAxis = cylinder->Axis(); - gp_Vec cv(cylAxis.Location().X(), cylAxis.Location().Y(), cylAxis.Location().Z()); // center of cylinder - gp_Vec av(cylAxis.Direction().X(), cylAxis.Direction().Y(), cylAxis.Direction().Z()); // axis of cylinder + gp_Vec cv(cylAxis.Location().X(), cylAxis.Location().Y(), cylAxis.Location().Z()); // center of + // cylinder + gp_Vec av(cylAxis.Direction().X(), cylAxis.Direction().Y(), cylAxis.Direction().Z()); // axis + // of cylinder Handle(Geom_Plane) plane = new Geom_Plane(gp_Ax3(cylAxis.Location(), cylAxis.Direction())); double totalArc = 0.0; bool firstSegment = false; @@ -532,29 +554,33 @@ bool wireEncirclesAxis(const TopoDS_Wire& wire, const Handle(Geom_CylindricalSur if (adapt.GetType() == GeomAbs_Line) { // Any line on the cylinder must be parallel to the cylinder axis - length = 0.0; - } else if (adapt.GetType() == GeomAbs_Circle) { + length = 0.0; + } + else if (adapt.GetType() == GeomAbs_Circle) { // Arc segment length = (lp - fp) * radius; // Check orientation in relation to cylinder axis GeomAPI_ProjectPointOnSurf proj(segFirst, plane); gp_Vec bv = gp_Vec(proj.Point(1).X(), proj.Point(1).Y(), proj.Point(1).Z()); - if ((bv - cv).Crossed(segTangent).IsOpposite(av, Precision::Confusion())) + if ((bv - cv).Crossed(segTangent).IsOpposite(av, Precision::Confusion())) { length = -length; - } else { + } + } + else { // Linearize the edge. Idea taken from ShapeAnalysis.cxx ShapeAnalysis::TotCross2D() TColgp_SequenceOfPnt SeqPnt; ShapeAnalysis_Curve::GetSamplePoints(adapt.Curve().Curve(), fp, lp, SeqPnt); // Calculate the oriented length of the edge gp_Pnt begin; - for (Standard_Integer j=1; j <= SeqPnt.Length(); j++) { + for (Standard_Integer j = 1; j <= SeqPnt.Length(); j++) { gp_Pnt end = SeqPnt.Value(j); // Project end point onto the plane GeomAPI_ProjectPointOnSurf proj(end, plane); - if (!proj.IsDone()) - return false; // FIXME: What else can we do? + if (!proj.IsDone()) { + return false; // FIXME: What else can we do? + } gp_Pnt pend = proj.Point(1); if (j > 1) { @@ -565,8 +591,9 @@ bool wireEncirclesAxis(const TopoDS_Wire& wire, const Handle(Geom_CylindricalSur if (dist > 0) { // Check orientation of this piece in relation to cylinder axis - if ((bv - cv).Crossed(dv).IsOpposite(av, Precision::Confusion())) + if ((bv - cv).Crossed(dv).IsOpposite(av, Precision::Confusion())) { dist = -dist; + } length += dist; } @@ -581,29 +608,35 @@ bool wireEncirclesAxis(const TopoDS_Wire& wire, const Handle(Geom_CylindricalSur firstSegment = true; first = segFirst; last = segLast; - } else if (!secondSegment) { + } + else if (!secondSegment) { // Second wire segment. Determine whether the second segment continues from // the first or from the last point of the first segment secondSegment = true; if (last.IsEqual(segFirst, Precision::Confusion())) { - last = segLast; // Third segment must begin here - } else if (last.IsEqual(segLast, Precision::Confusion())) { + last = segLast; // Third segment must begin here + } + else if (last.IsEqual(segLast, Precision::Confusion())) { last = segFirst; length = -length; - } else if (first.IsEqual(segLast, Precision::Confusion())) { + } + else if (first.IsEqual(segLast, Precision::Confusion())) { last = segFirst; totalArc = -totalArc; length = -length; - } else { // first.IsEqual(segFirst) + } + else { // first.IsEqual(segFirst) last = segLast; totalArc = -totalArc; } - } else { + } + else { if (!last.IsEqual(segFirst, Precision::Confusion())) { // The length was calculated in the opposite direction of the wire traversal length = -length; last = segFirst; - } else { + } + else { last = segLast; } } @@ -617,29 +650,32 @@ bool wireEncirclesAxis(const TopoDS_Wire& wire, const Handle(Geom_CylindricalSur return (fabs(totalArc) > std::numbers::pi * radius); } -TopoDS_Face FaceTypedCylinder::buildFace(const FaceVectorType &faces) const +TopoDS_Face FaceTypedCylinder::buildFace(const FaceVectorType& faces) const { static TopoDS_Face dummy; std::vector boundaries; boundarySplit(faces, boundaries); - if (boundaries.empty()) + if (boundaries.empty()) { return dummy; + } - //make wires + // make wires std::vector allWires; std::vector::iterator boundaryIt; - for (boundaryIt = boundaries.begin(); boundaryIt != boundaries.end(); ++boundaryIt) - { + for (boundaryIt = boundaries.begin(); boundaryIt != boundaries.end(); ++boundaryIt) { BRepLib_MakeWire wireMaker; EdgeVectorType::iterator it; - for (it = (*boundaryIt).begin(); it != (*boundaryIt).end(); ++it) + for (it = (*boundaryIt).begin(); it != (*boundaryIt).end(); ++it) { wireMaker.Add(*it); - if (wireMaker.Error() != BRepLib_WireDone) + } + if (wireMaker.Error() != BRepLib_WireDone) { return dummy; + } allWires.push_back(wireMaker.Wire()); } - if (allWires.empty()) + if (allWires.empty()) { return dummy; + } // Sort wires by size, that is, the innermost wire comes last std::sort(allWires.begin(), allWires.end(), ModelRefine::WireSort()); @@ -647,86 +683,100 @@ TopoDS_Face FaceTypedCylinder::buildFace(const FaceVectorType &faces) const // Find outer boundary wires that cut the cylinder into segments. This will be the case f we // have removed the seam edges of a complete (360 degrees) cylindrical face Handle(Geom_CylindricalSurface) surface = getGeomCylinder(faces.at(0)); - if (surface.IsNull()) - return dummy; + if (surface.IsNull()) { + return dummy; + } std::vector innerWires, encirclingWires; std::vector::iterator wireIt; for (wireIt = allWires.begin(); wireIt != allWires.end(); ++wireIt) { - if (wireEncirclesAxis(*wireIt, surface)) + if (wireEncirclesAxis(*wireIt, surface)) { encirclingWires.push_back(*wireIt); - else + } + else { innerWires.push_back(*wireIt); + } } if (encirclingWires.empty()) { // We can use the result of the bounding box sort. First wire is the outer wire wireIt = allWires.begin(); BRepBuilderAPI_MakeFace faceMaker(surface, *wireIt); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } // Add additional boundaries (inner wires). - for (wireIt++; wireIt != allWires.end(); ++wireIt) - { + for (wireIt++; wireIt != allWires.end(); ++wireIt) { faceMaker.Add(*wireIt); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } } return fixFace(faceMaker.Face()); - } else { - if (encirclingWires.size() != 2) + } + else { + if (encirclingWires.size() != 2) { return dummy; + } if (innerWires.empty()) { // We have just two outer boundaries BRepBuilderAPI_MakeFace faceMaker(surface, encirclingWires.front()); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } faceMaker.Add(encirclingWires.back()); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } return fixFace(faceMaker.Face()); - } else { + } + else { // Add the inner wires first, because otherwise those that cut the seam edge will fail wireIt = innerWires.begin(); BRepBuilderAPI_MakeFace faceMaker(surface, *wireIt, false); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } // Add additional boundaries (inner wires). - for (wireIt++; wireIt != innerWires.end(); ++wireIt) - { + for (wireIt++; wireIt != innerWires.end(); ++wireIt) { faceMaker.Add(*wireIt); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } } // Add outer boundaries faceMaker.Add(encirclingWires.front()); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } faceMaker.Add(encirclingWires.back()); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return dummy; + } return fixFace(faceMaker.Face()); } } } -void FaceTypedCylinder::boundarySplit(const FaceVectorType &facesIn, std::vector &boundariesOut) const +void FaceTypedCylinder::boundarySplit( + const FaceVectorType& facesIn, + std::vector& boundariesOut +) const { - //normal edges. + // normal edges. EdgeVectorType normalEdges; ModelRefine::boundaryEdges(facesIn, normalEdges); std::list sortedEdges; std::copy(normalEdges.begin(), normalEdges.end(), back_inserter(sortedEdges)); - while (!sortedEdges.empty()) - { + while (!sortedEdges.empty()) { TopoDS_Vertex destination = TopExp::FirstVertex(sortedEdges.back(), Standard_True); TopoDS_Vertex lastVertex = TopExp::LastVertex(sortedEdges.back(), Standard_True); bool closedSignal(false); @@ -737,25 +787,22 @@ void FaceTypedCylinder::boundarySplit(const FaceVectorType &facesIn, std::vector if (destination.IsSame(lastVertex)) { // Single circular edge closedSignal = true; - } else { + } + else { std::list::iterator sortedIt; - for (sortedIt = sortedEdges.begin(); sortedIt != sortedEdges.end();) - { + for (sortedIt = sortedEdges.begin(); sortedIt != sortedEdges.end();) { TopoDS_Vertex currentVertex = TopExp::FirstVertex(*sortedIt, Standard_True); - //Seam edges lie on top of each other. i.e. same. and we remove every match from the list - //so we don't actually ever compare the same edge. - if ((*sortedIt).IsSame(boundary.back())) - { + // Seam edges lie on top of each other. i.e. same. and we remove every match from + // the list so we don't actually ever compare the same edge. + if ((*sortedIt).IsSame(boundary.back())) { ++sortedIt; continue; } - if (lastVertex.IsSame(currentVertex)) - { + if (lastVertex.IsSame(currentVertex)) { boundary.push_back(*sortedIt); lastVertex = TopExp::LastVertex(*sortedIt, Standard_True); - if (lastVertex.IsSame(destination)) - { + if (lastVertex.IsSame(destination)) { closedSignal = true; sortedEdges.erase(sortedIt); break; @@ -767,8 +814,7 @@ void FaceTypedCylinder::boundarySplit(const FaceVectorType &facesIn, std::vector ++sortedIt; } } - if (closedSignal) - { + if (closedSignal) { EdgeVectorType temp; std::copy(boundary.begin(), boundary.end(), std::back_inserter(temp)); boundariesOut.push_back(temp); @@ -786,173 +832,199 @@ FaceTypedCylinder& ModelRefine::getCylinderObject() // TODO: change this version after occ fix. Freecad Mantis 1450 #if OCC_VERSION_HEX <= 0x7fffff -void collectConicEdges(const TopoDS_Shell &shell, TopTools_IndexedMapOfShape &map) +void collectConicEdges(const TopoDS_Shell& shell, TopTools_IndexedMapOfShape& map) { - TopTools_IndexedMapOfShape edges; - TopExp::MapShapes(shell, TopAbs_EDGE, edges); + TopTools_IndexedMapOfShape edges; + TopExp::MapShapes(shell, TopAbs_EDGE, edges); - for (int index = 1; index <= edges.Extent(); ++index) - { - const TopoDS_Edge ¤tEdge = TopoDS::Edge(edges.FindKey(index)); - if (currentEdge.IsNull()) - continue; - TopLoc_Location location; - Standard_Real first, last; - const Handle(Geom_Curve) &curve = BRep_Tool::Curve(currentEdge, location, first, last); - if (curve.IsNull()) - continue; - if (curve->IsKind(STANDARD_TYPE(Geom_Conic))) - map.Add(currentEdge); - } + for (int index = 1; index <= edges.Extent(); ++index) { + const TopoDS_Edge& currentEdge = TopoDS::Edge(edges.FindKey(index)); + if (currentEdge.IsNull()) { + continue; + } + TopLoc_Location location; + Standard_Real first, last; + const Handle(Geom_Curve) & curve = BRep_Tool::Curve(currentEdge, location, first, last); + if (curve.IsNull()) { + continue; + } + if (curve->IsKind(STANDARD_TYPE(Geom_Conic))) { + map.Add(currentEdge); + } + } } #endif -FaceTypedBSpline::FaceTypedBSpline() : FaceTypedBase(GeomAbs_BSplineSurface) +FaceTypedBSpline::FaceTypedBSpline() + : FaceTypedBase(GeomAbs_BSplineSurface) +{} + +bool FaceTypedBSpline::isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const { -} + try { + Handle(Geom_BSplineSurface) surfaceOne = Handle(Geom_BSplineSurface)::DownCast( + BRep_Tool::Surface(faceOne) + ); + Handle(Geom_BSplineSurface) surfaceTwo = Handle(Geom_BSplineSurface)::DownCast( + BRep_Tool::Surface(faceTwo) + ); -bool FaceTypedBSpline::isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const -{ - try - { - Handle(Geom_BSplineSurface) surfaceOne = Handle(Geom_BSplineSurface)::DownCast(BRep_Tool::Surface(faceOne)); - Handle(Geom_BSplineSurface) surfaceTwo = Handle(Geom_BSplineSurface)::DownCast(BRep_Tool::Surface(faceTwo)); - - if (surfaceOne.IsNull() || surfaceTwo.IsNull()) - return false; - - if (surfaceOne->IsURational() != surfaceTwo->IsURational()) - return false; - if (surfaceOne->IsVRational() != surfaceTwo->IsVRational()) - return false; - if (surfaceOne->IsUPeriodic() != surfaceTwo->IsUPeriodic()) - return false; - if (surfaceOne->IsVPeriodic() != surfaceTwo->IsVPeriodic()) - return false; - if (surfaceOne->IsUClosed() != surfaceTwo->IsUClosed()) - return false; - if (surfaceOne->IsVClosed() != surfaceTwo->IsVClosed()) - return false; - if (surfaceOne->UDegree() != surfaceTwo->UDegree()) - return false; - if (surfaceOne->VDegree() != surfaceTwo->VDegree()) - return false; - - //pole test - int uPoleCountOne(surfaceOne->NbUPoles()); - int vPoleCountOne(surfaceOne->NbVPoles()); - int uPoleCountTwo(surfaceTwo->NbUPoles()); - int vPoleCountTwo(surfaceTwo->NbVPoles()); - - if (uPoleCountOne != uPoleCountTwo || vPoleCountOne != vPoleCountTwo) - return false; - - TColgp_Array2OfPnt polesOne(1, uPoleCountOne, 1, vPoleCountOne); - TColgp_Array2OfPnt polesTwo(1, uPoleCountTwo, 1, vPoleCountTwo); - surfaceOne->Poles(polesOne); - surfaceTwo->Poles(polesTwo); - - for (int indexU = 1; indexU <= uPoleCountOne; ++indexU) - { - for (int indexV = 1; indexV <= vPoleCountOne; ++indexV) - { - if (!(polesOne.Value(indexU, indexV).IsEqual(polesTwo.Value(indexU, indexV), Precision::Confusion()))) - return false; + if (surfaceOne.IsNull() || surfaceTwo.IsNull()) { + return false; } + + if (surfaceOne->IsURational() != surfaceTwo->IsURational()) { + return false; + } + if (surfaceOne->IsVRational() != surfaceTwo->IsVRational()) { + return false; + } + if (surfaceOne->IsUPeriodic() != surfaceTwo->IsUPeriodic()) { + return false; + } + if (surfaceOne->IsVPeriodic() != surfaceTwo->IsVPeriodic()) { + return false; + } + if (surfaceOne->IsUClosed() != surfaceTwo->IsUClosed()) { + return false; + } + if (surfaceOne->IsVClosed() != surfaceTwo->IsVClosed()) { + return false; + } + if (surfaceOne->UDegree() != surfaceTwo->UDegree()) { + return false; + } + if (surfaceOne->VDegree() != surfaceTwo->VDegree()) { + return false; + } + + // pole test + int uPoleCountOne(surfaceOne->NbUPoles()); + int vPoleCountOne(surfaceOne->NbVPoles()); + int uPoleCountTwo(surfaceTwo->NbUPoles()); + int vPoleCountTwo(surfaceTwo->NbVPoles()); + + if (uPoleCountOne != uPoleCountTwo || vPoleCountOne != vPoleCountTwo) { + return false; + } + + TColgp_Array2OfPnt polesOne(1, uPoleCountOne, 1, vPoleCountOne); + TColgp_Array2OfPnt polesTwo(1, uPoleCountTwo, 1, vPoleCountTwo); + surfaceOne->Poles(polesOne); + surfaceTwo->Poles(polesTwo); + + for (int indexU = 1; indexU <= uPoleCountOne; ++indexU) { + for (int indexV = 1; indexV <= vPoleCountOne; ++indexV) { + if (!(polesOne.Value(indexU, indexV) + .IsEqual(polesTwo.Value(indexU, indexV), Precision::Confusion()))) { + return false; + } + } + } + + // knot test + int uKnotCountOne(surfaceOne->NbUKnots()); + int vKnotCountOne(surfaceOne->NbVKnots()); + int uKnotCountTwo(surfaceTwo->NbUKnots()); + int vKnotCountTwo(surfaceTwo->NbVKnots()); + if (uKnotCountOne != uKnotCountTwo || vKnotCountOne != vKnotCountTwo) { + return false; + } + TColStd_Array1OfReal uKnotsOne(1, uKnotCountOne); + TColStd_Array1OfReal vKnotsOne(1, vKnotCountOne); + TColStd_Array1OfReal uKnotsTwo(1, uKnotCountTwo); + TColStd_Array1OfReal vKnotsTwo(1, vKnotCountTwo); + surfaceOne->UKnots(uKnotsOne); + surfaceOne->VKnots(vKnotsOne); + surfaceTwo->UKnots(uKnotsTwo); + surfaceTwo->VKnots(vKnotsTwo); + for (int indexU = 1; indexU <= uKnotCountOne; ++indexU) { + if (uKnotsOne.Value(indexU) != uKnotsTwo.Value(indexU)) { + return false; + } + } + for (int indexV = 1; indexV <= vKnotCountOne; ++indexV) { + if (vKnotsOne.Value(indexV) != vKnotsTwo.Value(indexV)) { + return false; + } + } + + // Formulas: + // Periodic: knots=poles+2*degree-mult(1)+2 + // Non-periodic: knots=poles+degree+1 + auto getUKnotSequenceSize = [](Handle(Geom_BSplineSurface) surface) { + int uPoleCount(surface->NbUPoles()); + int uDegree(surface->UDegree()); + if (surface->IsUPeriodic()) { + int uMult1(surface->UMultiplicity(1)); + int size = uPoleCount + 2 * uDegree - uMult1 + 2; + return size; + } + else { + int size = uPoleCount + uDegree + 1; + return size; + } + }; + auto getVKnotSequenceSize = [](Handle(Geom_BSplineSurface) surface) { + int vPoleCount(surface->NbVPoles()); + int vDegree(surface->VDegree()); + if (surface->IsVPeriodic()) { + int vMult1(surface->VMultiplicity(1)); + int size = vPoleCount + 2 * vDegree - vMult1 + 2; + return size; + } + else { + int size = vPoleCount + vDegree + 1; + return size; + } + }; + + // knot sequence. + int uKnotSequenceOneCount(getUKnotSequenceSize(surfaceOne)); + int vKnotSequenceOneCount(getVKnotSequenceSize(surfaceOne)); + int uKnotSequenceTwoCount(getUKnotSequenceSize(surfaceTwo)); + int vKnotSequenceTwoCount(getVKnotSequenceSize(surfaceTwo)); + if (uKnotSequenceOneCount != uKnotSequenceTwoCount + || vKnotSequenceOneCount != vKnotSequenceTwoCount) { + return false; + } + TColStd_Array1OfReal uKnotSequenceOne(1, uKnotSequenceOneCount); + TColStd_Array1OfReal vKnotSequenceOne(1, vKnotSequenceOneCount); + TColStd_Array1OfReal uKnotSequenceTwo(1, uKnotSequenceTwoCount); + TColStd_Array1OfReal vKnotSequenceTwo(1, vKnotSequenceTwoCount); + surfaceOne->UKnotSequence(uKnotSequenceOne); + surfaceOne->VKnotSequence(vKnotSequenceOne); + surfaceTwo->UKnotSequence(uKnotSequenceTwo); + surfaceTwo->VKnotSequence(vKnotSequenceTwo); + for (int indexU = 1; indexU <= uKnotSequenceOneCount; ++indexU) { + if (uKnotSequenceOne.Value(indexU) != uKnotSequenceTwo.Value(indexU)) { + return false; + } + } + for (int indexV = 1; indexV <= vKnotSequenceOneCount; ++indexV) { + if (vKnotSequenceOne.Value(indexV) != vKnotSequenceTwo.Value(indexV)) { + return false; + } + } + return true; + } + catch (Standard_Failure& e) { + std::ostringstream stream; + if (e.GetMessageString()) { + stream << "FaceTypedBSpline::isEqual: OCC Error: " << e.GetMessageString() << std::endl; + } + else { + stream << "FaceTypedBSpline::isEqual: Unknown OCC Error" << std::endl; + } + Base::Console().message(stream.str().c_str()); + } + catch (...) { + std::ostringstream stream; + stream << "FaceTypedBSpline::isEqual: Unknown Error" << std::endl; + Base::Console().message(stream.str().c_str()); } - //knot test - int uKnotCountOne(surfaceOne->NbUKnots()); - int vKnotCountOne(surfaceOne->NbVKnots()); - int uKnotCountTwo(surfaceTwo->NbUKnots()); - int vKnotCountTwo(surfaceTwo->NbVKnots()); - if (uKnotCountOne != uKnotCountTwo || vKnotCountOne != vKnotCountTwo) - return false; - TColStd_Array1OfReal uKnotsOne(1, uKnotCountOne); - TColStd_Array1OfReal vKnotsOne(1, vKnotCountOne); - TColStd_Array1OfReal uKnotsTwo(1, uKnotCountTwo); - TColStd_Array1OfReal vKnotsTwo(1, vKnotCountTwo); - surfaceOne->UKnots(uKnotsOne); - surfaceOne->VKnots(vKnotsOne); - surfaceTwo->UKnots(uKnotsTwo); - surfaceTwo->VKnots(vKnotsTwo); - for (int indexU = 1; indexU <= uKnotCountOne; ++indexU) - if (uKnotsOne.Value(indexU) != uKnotsTwo.Value(indexU)) - return false; - for (int indexV = 1; indexV <= vKnotCountOne; ++indexV) - if (vKnotsOne.Value(indexV) != vKnotsTwo.Value(indexV)) - return false; - - //Formulas: - //Periodic: knots=poles+2*degree-mult(1)+2 - //Non-periodic: knots=poles+degree+1 - auto getUKnotSequenceSize = [](Handle(Geom_BSplineSurface) surface) { - int uPoleCount(surface->NbUPoles()); - int uDegree(surface->UDegree()); - if (surface->IsUPeriodic()) { - int uMult1(surface->UMultiplicity(1)); - int size = uPoleCount + 2*uDegree - uMult1 + 2; - return size; - } - else { - int size = uPoleCount + uDegree + 1; - return size; - } - }; - auto getVKnotSequenceSize = [](Handle(Geom_BSplineSurface) surface) { - int vPoleCount(surface->NbVPoles()); - int vDegree(surface->VDegree()); - if (surface->IsVPeriodic()) { - int vMult1(surface->VMultiplicity(1)); - int size = vPoleCount + 2*vDegree - vMult1 + 2; - return size; - } - else { - int size = vPoleCount + vDegree + 1; - return size; - } - }; - - //knot sequence. - int uKnotSequenceOneCount(getUKnotSequenceSize(surfaceOne)); - int vKnotSequenceOneCount(getVKnotSequenceSize(surfaceOne)); - int uKnotSequenceTwoCount(getUKnotSequenceSize(surfaceTwo)); - int vKnotSequenceTwoCount(getVKnotSequenceSize(surfaceTwo)); - if (uKnotSequenceOneCount != uKnotSequenceTwoCount || vKnotSequenceOneCount != vKnotSequenceTwoCount) - return false; - TColStd_Array1OfReal uKnotSequenceOne(1, uKnotSequenceOneCount); - TColStd_Array1OfReal vKnotSequenceOne(1, vKnotSequenceOneCount); - TColStd_Array1OfReal uKnotSequenceTwo(1, uKnotSequenceTwoCount); - TColStd_Array1OfReal vKnotSequenceTwo(1, vKnotSequenceTwoCount); - surfaceOne->UKnotSequence(uKnotSequenceOne); - surfaceOne->VKnotSequence(vKnotSequenceOne); - surfaceTwo->UKnotSequence(uKnotSequenceTwo); - surfaceTwo->VKnotSequence(vKnotSequenceTwo); - for (int indexU = 1; indexU <= uKnotSequenceOneCount; ++indexU) - if (uKnotSequenceOne.Value(indexU) != uKnotSequenceTwo.Value(indexU)) - return false; - for (int indexV = 1; indexV <= vKnotSequenceOneCount; ++indexV) - if (vKnotSequenceOne.Value(indexV) != vKnotSequenceTwo.Value(indexV)) - return false; - return true; - } - catch (Standard_Failure& e) - { - std::ostringstream stream; - if (e.GetMessageString()) - stream << "FaceTypedBSpline::isEqual: OCC Error: " << e.GetMessageString() << std::endl; - else - stream << "FaceTypedBSpline::isEqual: Unknown OCC Error" << std::endl; - Base::Console().message(stream.str().c_str()); - } - catch (...) - { - std::ostringstream stream; - stream << "FaceTypedBSpline::isEqual: Unknown Error" << std::endl; - Base::Console().message(stream.str().c_str()); - } - - return false; + return false; } GeomAbs_SurfaceType FaceTypedBSpline::getType() const @@ -960,55 +1032,62 @@ GeomAbs_SurfaceType FaceTypedBSpline::getType() const return GeomAbs_BSplineSurface; } -TopoDS_Face FaceTypedBSpline::buildFace(const FaceVectorType &faces) const +TopoDS_Face FaceTypedBSpline::buildFace(const FaceVectorType& faces) const { std::vector wires; std::vector splitEdges; this->boundarySplit(faces, splitEdges); - if (splitEdges.empty()) + if (splitEdges.empty()) { return {}; + } std::vector::iterator splitIt; - for (splitIt = splitEdges.begin(); splitIt != splitEdges.end(); ++splitIt) - { + for (splitIt = splitEdges.begin(); splitIt != splitEdges.end(); ++splitIt) { BRepLib_MakeWire wireMaker; EdgeVectorType::iterator it; - for (it = (*splitIt).begin(); it != (*splitIt).end(); ++it) + for (it = (*splitIt).begin(); it != (*splitIt).end(); ++it) { wireMaker.Add(*it); + } TopoDS_Wire currentWire = wireMaker.Wire(); wires.push_back(currentWire); } std::sort(wires.begin(), wires.end(), ModelRefine::WireSort()); - //make face from surface and outer wire. - Handle(Geom_BSplineSurface) surface = Handle(Geom_BSplineSurface)::DownCast(BRep_Tool::Surface(faces.at(0))); - if (!surface) + // make face from surface and outer wire. + Handle(Geom_BSplineSurface) surface = Handle(Geom_BSplineSurface)::DownCast( + BRep_Tool::Surface(faces.at(0)) + ); + if (!surface) { return {}; + } std::vector::iterator wireIt; wireIt = wires.begin(); BRepBuilderAPI_MakeFace faceMaker(surface, *wireIt); - if (!faceMaker.IsDone()) + if (!faceMaker.IsDone()) { return {}; - - //add additional boundaries. - for (wireIt++; wireIt != wires.end(); ++wireIt) - { - faceMaker.Add(*wireIt); - if (!faceMaker.IsDone()) - return {}; } - //fix newly constructed face. Orientation doesn't seem to get fixed the first call. + // add additional boundaries. + for (wireIt++; wireIt != wires.end(); ++wireIt) { + faceMaker.Add(*wireIt); + if (!faceMaker.IsDone()) { + return {}; + } + } + + // fix newly constructed face. Orientation doesn't seem to get fixed the first call. ShapeFix_Face faceFixer(faceMaker.Face()); faceFixer.SetContext(new ShapeBuild_ReShape()); faceFixer.Perform(); - if (faceFixer.Status(ShapeExtend_FAIL)) + if (faceFixer.Status(ShapeExtend_FAIL)) { return {}; + } faceFixer.FixOrientation(); faceFixer.Perform(); - if (faceFixer.Status(ShapeExtend_FAIL)) + if (faceFixer.Status(ShapeExtend_FAIL)) { return {}; + } return faceFixer.Face(); } @@ -1021,28 +1100,31 @@ FaceTypedBSpline& ModelRefine::getBSplineObject() ///////////////////////////////////////////////////////////////////////////////////////////////////////// -FaceUniter::FaceUniter(const TopoDS_Shell &shellIn) : modifiedSignal(false) +FaceUniter::FaceUniter(const TopoDS_Shell& shellIn) + : modifiedSignal(false) { workShell = shellIn; } bool FaceUniter::process() { - if (workShell.IsNull()) + if (workShell.IsNull()) { return false; + } modifiedShapes.clear(); deletedShapes.clear(); typeObjects.push_back(&getPlaneObject()); typeObjects.push_back(&getCylinderObject()); typeObjects.push_back(&getBSplineObject()); - //add more face types. + // add more face types. bool checkFinalShell = false; ModelRefine::FaceTypeSplitter splitter; splitter.addShell(workShell); - std::vector::iterator typeIt; - for(typeIt = typeObjects.begin(); typeIt != typeObjects.end(); ++typeIt) + std::vector::iterator typeIt; + for (typeIt = typeObjects.begin(); typeIt != typeObjects.end(); ++typeIt) { splitter.registerType((*typeIt)->getType()); + } splitter.split(); ModelRefine::FaceVectorType facesToRemove; @@ -1050,21 +1132,21 @@ bool FaceUniter::process() ModelRefine::FaceAdjacencySplitter adjacencySplitter(workShell); - for(typeIt = typeObjects.begin(); typeIt != typeObjects.end(); ++typeIt) - { + for (typeIt = typeObjects.begin(); typeIt != typeObjects.end(); ++typeIt) { ModelRefine::FaceVectorType typedFaces = splitter.getTypedFaceVector((*typeIt)->getType()); ModelRefine::FaceEqualitySplitter equalitySplitter; equalitySplitter.split(typedFaces, *typeIt); - for (std::size_t indexEquality(0); indexEquality < equalitySplitter.getGroupCount(); ++indexEquality) - { + for (std::size_t indexEquality(0); indexEquality < equalitySplitter.getGroupCount(); + ++indexEquality) { adjacencySplitter.split(equalitySplitter.getGroup(indexEquality)); -// std::cout << " adjacency group count: " << adjacencySplitter.getGroupCount() << std::endl; - for (std::size_t adjacentIndex(0); adjacentIndex < adjacencySplitter.getGroupCount(); ++adjacentIndex) - { -// std::cout << " face count is: " << adjacencySplitter.getGroup(adjacentIndex).size() << std::endl; + // std::cout << " adjacency group count: " << + // adjacencySplitter.getGroupCount() << std::endl; + for (std::size_t adjacentIndex(0); adjacentIndex < adjacencySplitter.getGroupCount(); + ++adjacentIndex) { + // std::cout << " face count is: " << + // adjacencySplitter.getGroup(adjacentIndex).size() << std::endl; TopoDS_Face newFace = (*typeIt)->buildFace(adjacencySplitter.getGroup(adjacentIndex)); - if (!newFace.IsNull()) - { + if (!newFace.IsNull()) { // the created face should have the same orientation as the input faces const FaceVectorType& faces = adjacencySplitter.getGroup(adjacentIndex); if (!faces.empty() && newFace.Orientation() != faces[0].Orientation()) { @@ -1075,68 +1157,69 @@ bool FaceUniter::process() // This reserve is probably not actually an improvement over letting // emplace_back allocate as needed. Leaving the code here for study if someone // wants to measure it. Coverity issue 356645. - chennes, March 2025 - //if (facesToRemove.capacity() <= facesToRemove.size() + adjacencySplitter.getGroup(adjacentIndex).size()) - // facesToRemove.reserve(facesToRemove.size() + adjacencySplitter.getGroup(adjacentIndex).size()); + // if (facesToRemove.capacity() <= facesToRemove.size() + + // adjacencySplitter.getGroup(adjacentIndex).size()) + // facesToRemove.reserve(facesToRemove.size() + + // adjacencySplitter.getGroup(adjacentIndex).size()); FaceVectorType temp = adjacencySplitter.getGroup(adjacentIndex); facesToRemove.insert(facesToRemove.end(), temp.begin(), temp.end()); - // the first shape will be marked as modified, i.e. replaced by newFace, all others are marked as deleted - // jrheinlaender: IMHO this is not correct because references to the deleted faces will be broken, whereas they should - // be replaced by references to the new face. To achieve this all shapes should be marked as - // modified, producing one single new face. This is the inverse behaviour to faces that are split e.g. - // by a boolean cut, where one old shape is marked as modified, producing multiple new shapes - if (!temp.empty()) - { - for (const auto & f : temp) - modifiedShapes.emplace_back(f, newFace); + // the first shape will be marked as modified, i.e. replaced by newFace, all + // others are marked as deleted jrheinlaender: IMHO this is not correct because + // references to the deleted faces will be broken, whereas they should be + // replaced by references to the new face. To achieve this all shapes should be + // marked as modified, producing one single new face. This is the inverse + // behaviour to faces that are split e.g. by a boolean cut, where one old shape + // is marked as modified, producing multiple new shapes + if (!temp.empty()) { + for (const auto& f : temp) { + modifiedShapes.emplace_back(f, newFace); + } } } } } } - if (!facesToSew.empty()) - { + if (!facesToSew.empty()) { modifiedSignal = true; workShell = ModelRefine::removeFaces(workShell, facesToRemove); TopExp_Explorer xp; bool emptyShell = true; - for (xp.Init(workShell, TopAbs_FACE); xp.More(); xp.Next()) - { + for (xp.Init(workShell, TopAbs_FACE); xp.More(); xp.Next()) { emptyShell = false; break; } - if (!emptyShell || facesToSew.size() > 1) - { + if (!emptyShell || facesToSew.size() > 1) { BRepBuilderAPI_Sewing sew; sew.Add(workShell); FaceVectorType::iterator sewIt; - for(sewIt = facesToSew.begin(); sewIt != facesToSew.end(); ++sewIt) + for (sewIt = facesToSew.begin(); sewIt != facesToSew.end(); ++sewIt) { sew.Add(*sewIt); + } sew.Perform(); try { workShell = TopoDS::Shell(sew.SewedShape()); - } catch (Standard_Failure&) { + } + catch (Standard_Failure&) { return false; } // update the list of modifications - for (auto & it : modifiedShapes) - { - if (sew.IsModified(it.second)) - { + for (auto& it : modifiedShapes) { + if (sew.IsModified(it.second)) { it.second = sew.Modified(it.second); break; } } } - else - { + else { // workShell has no more faces and we add exactly one face BRep_Builder builder; builder.MakeShell(workShell); FaceVectorType::iterator sewIt; - for(sewIt = facesToSew.begin(); sewIt != facesToSew.end(); ++sewIt) + for (sewIt = facesToSew.begin(); sewIt != facesToSew.end(); ++sewIt) { builder.Add(workShell, *sewIt); + } } BRepLib_FuseEdges edgeFuse(workShell); @@ -1149,8 +1232,7 @@ bool FaceUniter::process() TopTools_DataMapOfShapeShape affectedFaces; edgeFuse.Faces(affectedFaces); TopTools_DataMapIteratorOfDataMapOfShapeShape mapIt; - for (mapIt.Initialize(affectedFaces); mapIt.More(); mapIt.Next()) - { + for (mapIt.Initialize(affectedFaces); mapIt.More(); mapIt.Next()) { ShapeFix_Face faceFixer(TopoDS::Face(mapIt.Value())); faceFixer.Perform(); } @@ -1164,47 +1246,45 @@ bool FaceUniter::process() // the shell is a solid, make sure that volume is positive GProp_GProps props; BRepGProp::VolumeProperties(workShell, props); - if (props.Mass() < 0) + if (props.Mass() < 0) { workShell = TopoDS::Shell(workShell.Reversed()); + } } } // update the list of modifications TopTools_DataMapOfShapeShape faceMap; edgeFuse.Faces(faceMap); - for (mapIt.Initialize(faceMap); mapIt.More(); mapIt.Next()) - { + for (mapIt.Initialize(faceMap); mapIt.More(); mapIt.Next()) { bool isModifiedFace = false; - for (auto & it : modifiedShapes) - { + for (auto& it : modifiedShapes) { if (mapIt.Key().IsSame(it.second)) { // Note: IsEqual() for some reason does not work it.second = mapIt.Value(); isModifiedFace = true; } } - if (!isModifiedFace) - { + if (!isModifiedFace) { // Catch faces that were not united but whose boundary was changed (probably because // several adjacent faces were united) // See https://sourceforge.net/apps/mantisbt/free-cad/view.php?id=873 modifiedShapes.emplace_back(mapIt.Key(), mapIt.Value()); } } - // Handle edges that were fused. See https://sourceforge.net/apps/mantisbt/free-cad/view.php?id=873 + // Handle edges that were fused. See + // https://sourceforge.net/apps/mantisbt/free-cad/view.php?id=873 TopTools_DataMapOfIntegerListOfShape oldEdges; TopTools_DataMapOfIntegerShape newEdges; edgeFuse.Edges(oldEdges); edgeFuse.ResultEdges(newEdges); TopTools_DataMapIteratorOfDataMapOfIntegerListOfShape edgeMapIt; - for (edgeMapIt.Initialize(oldEdges); edgeMapIt.More(); edgeMapIt.Next()) - { + for (edgeMapIt.Initialize(oldEdges); edgeMapIt.More(); edgeMapIt.Next()) { const TopTools_ListOfShape& edges = edgeMapIt.Value(); int idx = edgeMapIt.Key(); TopTools_ListIteratorOfListOfShape edgeIt; - for (edgeIt.Initialize(edges); edgeIt.More(); edgeIt.Next()) - { - if (newEdges.IsBound(idx)) + for (edgeIt.Initialize(edges); edgeIt.More(); edgeIt.Next()) { + if (newEdges.IsBound(idx)) { modifiedShapes.emplace_back(edgeIt.Value(), newEdges(idx)); + } } // TODO: Handle vertices that have disappeared in the fusion of the edges } @@ -1214,7 +1294,7 @@ bool FaceUniter::process() ///////////////////////////////////////////////////////////////////////////////////////////////////////// -//BRepBuilderAPI_RefineModel implement a way to log all modifications on the faces +// BRepBuilderAPI_RefineModel implement a way to log all modifications on the faces Part::BRepBuilderAPI_RefineModel::BRepBuilderAPI_RefineModel(const TopoDS_Shape& shape) { @@ -1228,19 +1308,20 @@ void Part::BRepBuilderAPI_RefineModel::Build(const Message_ProgressRange&) void Part::BRepBuilderAPI_RefineModel::Build() #endif { - if (myShape.IsNull()) + if (myShape.IsNull()) { Standard_Failure::Raise("Cannot remove splitter from empty shape"); + } if (myShape.ShapeType() == TopAbs_SOLID) { - const TopoDS_Solid &solid = TopoDS::Solid(myShape); + const TopoDS_Solid& solid = TopoDS::Solid(myShape); BRepBuilderAPI_MakeSolid mkSolid; TopExp_Explorer it; for (it.Init(solid, TopAbs_SHELL); it.More(); it.Next()) { - const TopoDS_Shell ¤tShell = TopoDS::Shell(it.Current()); + const TopoDS_Shell& currentShell = TopoDS::Shell(it.Current()); ModelRefine::FaceUniter uniter(currentShell); if (uniter.process()) { if (uniter.isModified()) { - const TopoDS_Shell &newShell = uniter.getShell(); + const TopoDS_Shell& newShell = uniter.getShell(); mkSolid.Add(newShell); LogModifications(uniter); } @@ -1274,15 +1355,15 @@ void Part::BRepBuilderAPI_RefineModel::Build() TopExp_Explorer xp; // solids for (xp.Init(myShape, TopAbs_SOLID); xp.More(); xp.Next()) { - const TopoDS_Solid &solid = TopoDS::Solid(xp.Current()); + const TopoDS_Solid& solid = TopoDS::Solid(xp.Current()); BRepTools_ReShape reshape; TopExp_Explorer it; for (it.Init(solid, TopAbs_SHELL); it.More(); it.Next()) { - const TopoDS_Shell ¤tShell = TopoDS::Shell(it.Current()); + const TopoDS_Shell& currentShell = TopoDS::Shell(it.Current()); ModelRefine::FaceUniter uniter(currentShell); if (uniter.process()) { if (uniter.isModified()) { - const TopoDS_Shell &newShell = uniter.getShell(); + const TopoDS_Shell& newShell = uniter.getShell(); reshape.Replace(currentShell, newShell); LogModifications(uniter); } @@ -1301,20 +1382,24 @@ void Part::BRepBuilderAPI_RefineModel::Build() } // the rest for (xp.Init(myShape, TopAbs_FACE, TopAbs_SHELL); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } for (xp.Init(myShape, TopAbs_WIRE, TopAbs_FACE); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } for (xp.Init(myShape, TopAbs_EDGE, TopAbs_WIRE); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } for (xp.Init(myShape, TopAbs_VERTEX, TopAbs_EDGE); xp.More(); xp.Next()) { - if (!xp.Current().IsNull()) + if (!xp.Current().IsNull()) { builder.Add(comp, xp.Current()); + } } myShape = comp; @@ -1326,34 +1411,35 @@ void Part::BRepBuilderAPI_RefineModel::Build() void Part::BRepBuilderAPI_RefineModel::LogModifications(const ModelRefine::FaceUniter& uniter) { const std::vector& modShapes = uniter.getModifiedShapes(); - for (const auto & it : modShapes) { + for (const auto& it : modShapes) { TopTools_ListOfShape list; list.Append(it.second); myModified.Bind(it.first, list); } const ShapeVectorType& delShapes = uniter.getDeletedShapes(); - for (const auto & it : delShapes) { + for (const auto& it : delShapes) { myDeleted.Append(it); } } const TopTools_ListOfShape& Part::BRepBuilderAPI_RefineModel::Modified(const TopoDS_Shape& S) { - if (myModified.IsBound(S)) + if (myModified.IsBound(S)) { return myModified.Find(S); - else + } + else { return myEmptyList; + } } Standard_Boolean Part::BRepBuilderAPI_RefineModel::IsDeleted(const TopoDS_Shape& S) { TopTools_ListIteratorOfListOfShape it; - for (it.Initialize(myDeleted); it.More(); it.Next()) - { - if (it.Value().IsSame(S)) + for (it.Initialize(myDeleted); it.More(); it.Next()) { + if (it.Value().IsSame(S)) { return Standard_True; + } } return Standard_False; } - diff --git a/src/Mod/Part/App/modelRefine.h b/src/Mod/Part/App/modelRefine.h index 07045adad5..3a9d404ef0 100644 --- a/src/Mod/Part/App/modelRefine.h +++ b/src/Mod/Part/App/modelRefine.h @@ -46,140 +46,179 @@ namespace ModelRefine { - using FaceVectorType = std::vector; - using EdgeVectorType = std::vector; - using ShapeVectorType = std::vector; - using ShapePairType = std::pair; +using FaceVectorType = std::vector; +using EdgeVectorType = std::vector; +using ShapeVectorType = std::vector; +using ShapePairType = std::pair; - void getFaceEdges(const TopoDS_Face &face, EdgeVectorType &edges); - void boundaryEdges(const FaceVectorType &faces, EdgeVectorType &edgesOut); - TopoDS_Shell removeFaces(const TopoDS_Shell &shell, const FaceVectorType &faces); +void getFaceEdges(const TopoDS_Face& face, EdgeVectorType& edges); +void boundaryEdges(const FaceVectorType& faces, EdgeVectorType& edgesOut); +TopoDS_Shell removeFaces(const TopoDS_Shell& shell, const FaceVectorType& faces); - class FaceTypedBase +class FaceTypedBase +{ +private: + FaceTypedBase() = default; + +protected: + FaceTypedBase(const GeomAbs_SurfaceType& typeIn) { - private: - FaceTypedBase() = default; - protected: - FaceTypedBase(const GeomAbs_SurfaceType &typeIn){surfaceType = typeIn;} - public: - virtual bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const = 0; - virtual GeomAbs_SurfaceType getType() const = 0; - virtual TopoDS_Face buildFace(const FaceVectorType &faces) const = 0; + surfaceType = typeIn; + } - static GeomAbs_SurfaceType getFaceType(const TopoDS_Face &faceIn); +public: + virtual bool isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const = 0; + virtual GeomAbs_SurfaceType getType() const = 0; + virtual TopoDS_Face buildFace(const FaceVectorType& faces) const = 0; - protected: - virtual void boundarySplit(const FaceVectorType &facesIn, std::vector &boundariesOut) const; - GeomAbs_SurfaceType surfaceType; - }; + static GeomAbs_SurfaceType getFaceType(const TopoDS_Face& faceIn); - class FaceTypedPlane : public FaceTypedBase +protected: + virtual void boundarySplit( + const FaceVectorType& facesIn, + std::vector& boundariesOut + ) const; + GeomAbs_SurfaceType surfaceType; +}; + +class FaceTypedPlane: public FaceTypedBase +{ +private: + FaceTypedPlane(); + +public: + bool isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const override; + GeomAbs_SurfaceType getType() const override; + TopoDS_Face buildFace(const FaceVectorType& faces) const override; + friend FaceTypedPlane& getPlaneObject(); +}; +FaceTypedPlane& getPlaneObject(); + +class FaceTypedCylinder: public FaceTypedBase +{ +private: + FaceTypedCylinder(); + +public: + bool isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const override; + GeomAbs_SurfaceType getType() const override; + TopoDS_Face buildFace(const FaceVectorType& faces) const override; + friend FaceTypedCylinder& getCylinderObject(); + +protected: + void boundarySplit( + const FaceVectorType& facesIn, + std::vector& boundariesOut + ) const override; +}; +FaceTypedCylinder& getCylinderObject(); + +class FaceTypedBSpline: public FaceTypedBase +{ +private: + FaceTypedBSpline(); + +public: + bool isEqual(const TopoDS_Face& faceOne, const TopoDS_Face& faceTwo) const override; + GeomAbs_SurfaceType getType() const override; + TopoDS_Face buildFace(const FaceVectorType& faces) const override; + friend FaceTypedBSpline& getBSplineObject(); +}; +FaceTypedBSpline& getBSplineObject(); + +class FaceTypeSplitter +{ + using SplitMapType = std::map; + +public: + FaceTypeSplitter() = default; + void addShell(const TopoDS_Shell& shellIn); + void registerType(const GeomAbs_SurfaceType& type); + bool hasType(const GeomAbs_SurfaceType& type) const; + void split(); + const FaceVectorType& getTypedFaceVector(const GeomAbs_SurfaceType& type) const; + +private: + SplitMapType typeMap; + TopoDS_Shell shell; +}; + +class FaceAdjacencySplitter +{ +public: + FaceAdjacencySplitter(const TopoDS_Shell& shell); + void split(const FaceVectorType& facesIn); + std::size_t getGroupCount() const { - private: - FaceTypedPlane(); - public: - bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const override; - GeomAbs_SurfaceType getType() const override; - TopoDS_Face buildFace(const FaceVectorType &faces) const override; - friend FaceTypedPlane& getPlaneObject(); - }; - FaceTypedPlane& getPlaneObject(); - - class FaceTypedCylinder : public FaceTypedBase + return adjacencyArray.size(); + } + const FaceVectorType& getGroup(const std::size_t& index) const { - private: - FaceTypedCylinder(); - public: - bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const override; - GeomAbs_SurfaceType getType() const override; - TopoDS_Face buildFace(const FaceVectorType &faces) const override; - friend FaceTypedCylinder& getCylinderObject(); + return adjacencyArray[index]; + } - protected: - void boundarySplit(const FaceVectorType &facesIn, std::vector &boundariesOut) const override; - }; - FaceTypedCylinder& getCylinderObject(); +private: + FaceAdjacencySplitter() = default; + void recursiveFind(const TopoDS_Face& face, FaceVectorType& outVector); + std::vector adjacencyArray; + TopTools_MapOfShape processedMap; + TopTools_MapOfShape facesInMap; - class FaceTypedBSpline : public FaceTypedBase + TopTools_IndexedDataMapOfShapeListOfShape faceToEdgeMap; + TopTools_IndexedDataMapOfShapeListOfShape edgeToFaceMap; +}; + +class FaceEqualitySplitter +{ +public: + FaceEqualitySplitter() = default; + void split(const FaceVectorType& faces, FaceTypedBase* object); + std::size_t getGroupCount() const { - private: - FaceTypedBSpline(); - public: - bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const override; - GeomAbs_SurfaceType getType() const override; - TopoDS_Face buildFace(const FaceVectorType &faces) const override; - friend FaceTypedBSpline& getBSplineObject(); - }; - FaceTypedBSpline& getBSplineObject(); - - class FaceTypeSplitter + return equalityVector.size(); + } + const FaceVectorType& getGroup(const std::size_t& index) const { - using SplitMapType = std::map; - public: - FaceTypeSplitter() = default; - void addShell(const TopoDS_Shell &shellIn); - void registerType(const GeomAbs_SurfaceType &type); - bool hasType(const GeomAbs_SurfaceType &type) const; - void split(); - const FaceVectorType& getTypedFaceVector(const GeomAbs_SurfaceType &type) const; - private: - SplitMapType typeMap; - TopoDS_Shell shell; - }; + return equalityVector[index]; + } - class FaceAdjacencySplitter +private: + std::vector equalityVector; +}; + +class FaceUniter +{ +private: + FaceUniter() = default; + +public: + FaceUniter(const TopoDS_Shell& shellIn); + bool process(); + const TopoDS_Shell& getShell() const { - public: - FaceAdjacencySplitter(const TopoDS_Shell &shell); - void split(const FaceVectorType &facesIn); - std::size_t getGroupCount() const {return adjacencyArray.size();} - const FaceVectorType& getGroup(const std::size_t &index) const {return adjacencyArray[index];} - - private: - FaceAdjacencySplitter() = default; - void recursiveFind(const TopoDS_Face &face, FaceVectorType &outVector); - std::vector adjacencyArray; - TopTools_MapOfShape processedMap; - TopTools_MapOfShape facesInMap; - - TopTools_IndexedDataMapOfShapeListOfShape faceToEdgeMap; - TopTools_IndexedDataMapOfShapeListOfShape edgeToFaceMap; - }; - - class FaceEqualitySplitter + return workShell; + } + bool isModified() { - public: - FaceEqualitySplitter() = default; - void split(const FaceVectorType &faces, FaceTypedBase *object); - std::size_t getGroupCount() const {return equalityVector.size();} - const FaceVectorType& getGroup(const std::size_t &index) const {return equalityVector[index];} - - private: - std::vector equalityVector; - }; - - class FaceUniter + return modifiedSignal; + } + const std::vector& getModifiedShapes() const { - private: - FaceUniter() = default; - public: - FaceUniter(const TopoDS_Shell &shellIn); - bool process(); - const TopoDS_Shell& getShell() const {return workShell;} - bool isModified(){return modifiedSignal;} - const std::vector& getModifiedShapes() const - {return modifiedShapes;} - const ShapeVectorType& getDeletedShapes() const - {return deletedShapes;} + return modifiedShapes; + } + const ShapeVectorType& getDeletedShapes() const + { + return deletedShapes; + } - private: - TopoDS_Shell workShell; - std::vector typeObjects; - std::vector modifiedShapes; - ShapeVectorType deletedShapes; - bool modifiedSignal; - }; -} +private: + TopoDS_Shell workShell; + std::vector typeObjects; + std::vector modifiedShapes; + ShapeVectorType deletedShapes; + bool modifiedSignal; +}; +} // namespace ModelRefine /* excerpt from GeomAbs_SurfaceType.hxx enum GeomAbs_SurfaceType { @@ -196,8 +235,9 @@ GeomAbs_OffsetSurface, GeomAbs_OtherSurface }; */ -namespace Part { -class PartExport BRepBuilderAPI_RefineModel : public BRepBuilderAPI_MakeShape +namespace Part +{ +class PartExport BRepBuilderAPI_RefineModel: public BRepBuilderAPI_MakeShape { public: BRepBuilderAPI_RefineModel(const TopoDS_Shape&); @@ -217,6 +257,6 @@ protected: TopTools_ListOfShape myEmptyList; TopTools_ListOfShape myDeleted; }; -} +} // namespace Part -#endif // MODELREFINE_H +#endif // MODELREFINE_H diff --git a/src/Mod/Part/AttachmentEditor/Commands.py b/src/Mod/Part/AttachmentEditor/Commands.py index 206031623e..8faaac4531 100644 --- a/src/Mod/Part/AttachmentEditor/Commands.py +++ b/src/Mod/Part/AttachmentEditor/Commands.py @@ -29,16 +29,20 @@ import FreeCAD as App try: from PySide.QtCore import QT_TRANSLATE_NOOP except ImportError: + def QT_TRANSLATE_NOOP(ctx, msg): return msg -def editAttachment(feature = None, - take_selection = False, - create_transaction = True, - callback_OK = None, - callback_Cancel = None, - callback_Apply = None): - '''Opens attachment editing dialog. + +def editAttachment( + feature=None, + take_selection=False, + create_transaction=True, + callback_OK=None, + callback_Cancel=None, + callback_Apply=None, +): + """Opens attachment editing dialog. editAttachment(feature = None, take_selection = False, create_transaction = True, @@ -55,38 +59,48 @@ def editAttachment(feature = None, callback_OK: function to be called upon OK. Invoked after writing values to feature, committing transaction and closing the dialog. callback_Cancel: called after closing the dialog and aborting transaction. - callback_Apply: invoked after writing values to feature.''' + callback_Apply: invoked after writing values to feature.""" import AttachmentEditor.TaskAttachmentEditor as TaskAttachmentEditor - global taskd # exposing to outside, for ease of debugging + + global taskd # exposing to outside, for ease of debugging if feature is None: feature = Gui.Selection.getSelectionEx()[0].Object try: - taskd = TaskAttachmentEditor.AttachmentEditorTaskPanel(feature, - take_selection= take_selection, - create_transaction= create_transaction, - callback_OK= callback_OK, - callback_Cancel= callback_Cancel, - callback_Apply= callback_Apply) + taskd = TaskAttachmentEditor.AttachmentEditorTaskPanel( + feature, + take_selection=take_selection, + create_transaction=create_transaction, + callback_OK=callback_OK, + callback_Cancel=callback_Cancel, + callback_Apply=callback_Apply, + ) Gui.Control.showDialog(taskd) except TaskAttachmentEditor.CancelError: pass class CommandEditAttachment: - 'Command to edit attachment' + "Command to edit attachment" + def GetResources(self): - return {'Pixmap': 'Part_Attachment', - 'MenuText': QT_TRANSLATE_NOOP("Part_EditAttachment","Attachment"), - 'Accel': "", - 'ToolTip': QT_TRANSLATE_NOOP("Part_EditAttachment","Opens the attachment editor to change the attachment of the selected object")} + return { + "Pixmap": "Part_Attachment", + "MenuText": QT_TRANSLATE_NOOP("Part_EditAttachment", "Attachment"), + "Accel": "", + "ToolTip": QT_TRANSLATE_NOOP( + "Part_EditAttachment", + "Opens the attachment editor to change the attachment of the selected object", + ), + } def Activated(self): try: editAttachment() except Exception as err: from PySide import QtGui + mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) mb.setText(str(err)) @@ -96,12 +110,13 @@ class CommandEditAttachment: def IsActive(self): sel = Gui.Selection.getSelectionEx() if len(sel) == 1: - if hasattr(sel[0].Object,"Placement"): + if hasattr(sel[0].Object, "Placement"): return True return False + if App.GuiUp: import FreeCADGui as Gui - command_instance = CommandEditAttachment() - Gui.addCommand('Part_EditAttachment', command_instance) + command_instance = CommandEditAttachment() + Gui.addCommand("Part_EditAttachment", command_instance) diff --git a/src/Mod/Part/AttachmentEditor/FrozenClass.py b/src/Mod/Part/AttachmentEditor/FrozenClass.py index 0843722910..3d241f9a48 100644 --- a/src/Mod/Part/AttachmentEditor/FrozenClass.py +++ b/src/Mod/Part/AttachmentEditor/FrozenClass.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,13 +22,18 @@ # * * # ***************************************************************************/ + # adapted from http://stackoverflow.com/a/3603824/6285007 class FrozenClass(object): - '''FrozenClass: prevents adding new attributes to class outside of __init__''' + """FrozenClass: prevents adding new attributes to class outside of __init__""" + __isfrozen = False + def __setattr__(self, key, value): if self.__isfrozen and not hasattr(self, key): - raise TypeError( "{cls} has no attribute {attr}".format(cls= self.__class__.__name__, attr= key) ) + raise TypeError( + "{cls} has no attribute {attr}".format(cls=self.__class__.__name__, attr=key) + ) object.__setattr__(self, key, value) def _freeze(self): @@ -36,4 +41,3 @@ class FrozenClass(object): def _unfreeze(self): self.__isfrozen = False - diff --git a/src/Mod/Part/AttachmentEditor/TaskAttachmentEditor.py b/src/Mod/Part/AttachmentEditor/TaskAttachmentEditor.py index 0d4bef4a97..ae00c975f4 100644 --- a/src/Mod/Part/AttachmentEditor/TaskAttachmentEditor.py +++ b/src/Mod/Part/AttachmentEditor/TaskAttachmentEditor.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -26,20 +26,27 @@ from __future__ import absolute_import import FreeCAD as App import Part + mm = App.Units.MilliMetre deg = App.Units.Degree Q = App.Units.Quantity from AttachmentEditor.FrozenClass import FrozenClass + try: from Show import TempoVis from Show.DepGraphTools import getAllDependent except ImportError as err: - def TempoVis(doc,tag): + + def TempoVis(doc, tag): return None + def getAllDependent(feature): return [] - App.Console.PrintWarning("AttachmentEditor: Failed to import some code from Show module. Functionality will be limited.\n") + + App.Console.PrintWarning( + "AttachmentEditor: Failed to import some code from Show module. Functionality will be limited.\n" + ) App.Console.PrintWarning(str(err)) if App.GuiUp: @@ -47,60 +54,78 @@ if App.GuiUp: from PySide import QtCore, QtGui from FreeCADGui import PySideUic as uic -#-------------------------- translation-related code ---------------------------------------- -#Thanks, yorik! (see forum thread "A new Part tool is being born... JoinFeatures!" -#https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 ) +# -------------------------- translation-related code ---------------------------------------- +# Thanks, yorik! (see forum thread "A new Part tool is being born... JoinFeatures!" +# https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 ) try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: + def _fromUtf8(s): return s + + translate = App.Qt.translate -#--------------------------/translation-related code ---------------------------------------- +# --------------------------/translation-related code ---------------------------------------- + def linkSubList_convertToOldStyle(references): - ("input: [(obj1, (sub1, sub2)), (obj2, (sub1, sub2))]\n" - "output: [(obj1, sub1), (obj1, sub2), (obj2, sub1), (obj2, sub2)]") + ( + "input: [(obj1, (sub1, sub2)), (obj2, (sub1, sub2))]\n" + "output: [(obj1, sub1), (obj1, sub2), (obj2, sub1), (obj2, sub2)]" + ) result = [] for tup in references: if type(tup[1]) is tuple or type(tup[1]) is list: for subname in tup[1]: result.append((tup[0], subname)) if len(tup[1]) == 0: - result.append((tup[0], '')) - elif isinstance(tup[1],str): + result.append((tup[0], "")) + elif isinstance(tup[1], str): # old style references, no conversion required result.append(tup) return result def StrFromLink(feature, subname): - return feature.Name+ ((':'+subname) if subname else '') + return feature.Name + ((":" + subname) if subname else "") + def LinkFromStr(strlink, document): if len(strlink) == 0: return None - pieces = strlink.split(':') + pieces = strlink.split(":") feature = document.getObject(pieces[0]) - subname = '' + subname = "" if feature is None: - raise ValueError(translate('AttachmentEditor',"No object named {}",None).format(pieces[0])) + raise ValueError( + translate("AttachmentEditor", "No object named {}", None).format(pieces[0]) + ) if len(pieces) == 2: subname = pieces[1] elif len(pieces) > 2: - raise ValueError(translate('AttachmentEditor',"Failed to parse link (more than one colon encountered)",None)) + raise ValueError( + translate( + "AttachmentEditor", "Failed to parse link (more than one colon encountered)", None + ) + ) + + return ( + feature, + str(subname), + ) # wrap in str to remove unicode, which confuses assignment to PropertyLinkSubList. - return (feature,str(subname)) #wrap in str to remove unicode, which confuses assignment to PropertyLinkSubList. def StrListFromRefs(references): - '''input: PropertyLinkSubList. Output: list of strings for UI.''' + """input: PropertyLinkSubList. Output: list of strings for UI.""" references_oldstyle = linkSubList_convertToOldStyle(references) - return [StrFromLink(feature,subelement) for (feature, subelement) in references_oldstyle] + return [StrFromLink(feature, subelement) for (feature, subelement) in references_oldstyle] + def RefsFromStrList(strings, document): - '''input: strings as from UI. Output: list of tuples that can be assigned to PropertyLinkSubList.''' + """input: strings as from UI. Output: list of tuples that can be assigned to PropertyLinkSubList.""" refs = [] for st in strings: lnk = LinkFromStr(st, document) @@ -108,6 +133,7 @@ def RefsFromStrList(strings, document): refs.append(lnk) return refs + def GetSelectionAsLinkSubList(): sel = Gui.Selection.getSelectionEx() result = [] @@ -115,108 +141,134 @@ def GetSelectionAsLinkSubList(): for subname in selobj.SubElementNames: result.append((selobj.Object, subname)) if len(selobj.SubElementNames) == 0: - result.append((selobj.Object, '')) + result.append((selobj.Object, "")) return result def PlacementsFuzzyCompare(plm1, plm2): - pos_eq = (plm1.Base - plm2.Base).Length < 1e-7 # 1e-7 is OCC's Precision::Confusion + pos_eq = (plm1.Base - plm2.Base).Length < 1e-7 # 1e-7 is OCC's Precision::Confusion q1 = plm1.Rotation.Q q2 = plm2.Rotation.Q # rotations are equal if q1 == q2 or q1 == -q2. # Invert one of Q's if their scalar product is negative, before comparison. - if q1[0]*q2[0] + q1[1]*q2[1] + q1[2]*q2[2] + q1[3]*q2[3] < 0: + if q1[0] * q2[0] + q1[1] * q2[1] + q1[2] * q2[2] + q1[3] * q2[3] < 0: q2 = [-v for v in q2] - rot_eq = ( abs(q1[0]-q2[0]) + - abs(q1[1]-q2[1]) + - abs(q1[2]-q2[2]) + - abs(q1[3]-q2[3]) ) < 1e-12 # 1e-12 is OCC's Precision::Angular (in radians) + rot_eq = ( + abs(q1[0] - q2[0]) + abs(q1[1] - q2[1]) + abs(q1[2] - q2[2]) + abs(q1[3] - q2[3]) + ) < 1e-12 # 1e-12 is OCC's Precision::Angular (in radians) return pos_eq and rot_eq + class CancelError(Exception): def __init__(self): - self.message = 'Canceled by user' + self.message = "Canceled by user" self.isCancelError = True + class AttachmentEditorTaskPanel(FrozenClass): - '''The editmode TaskPanel for attachment editing''' - KEYmode = QtCore.Qt.ItemDataRole.UserRole # Key to use in Item.data(key) to obtain a mode associated with list item - KEYon = QtCore.Qt.ItemDataRole.UserRole + 1 # Key to use in Item.data(key) to obtain if the mode is valid + """The editmode TaskPanel for attachment editing""" + + KEYmode = ( + QtCore.Qt.ItemDataRole.UserRole + ) # Key to use in Item.data(key) to obtain a mode associated with list item + KEYon = ( + QtCore.Qt.ItemDataRole.UserRole + 1 + ) # Key to use in Item.data(key) to obtain if the mode is valid def __define_attributes(self): - self.obj = None #feature being attached - self.attacher = None #AttachEngine that is being actively used by the dialog. Its parameters are constantly and actively kept in sync with the dialog. - self.obj_is_attachable = True # False when editing non-attachable objects (alignment, not attachment) + self.obj = None # feature being attached + self.attacher = None # AttachEngine that is being actively used by the dialog. Its parameters are constantly and actively kept in sync with the dialog. + self.obj_is_attachable = ( + True # False when editing non-attachable objects (alignment, not attachment) + ) - self.last_sugr = None #result of last execution of suggestor + self.last_sugr = None # result of last execution of suggestor - self.form = None #Qt widget of dialog interface - self.block = False #when True, event handlers return without doing anything (instead of doing-undoing blockSignals to everything) - self.refLines = [] #reference lineEdit widgets, packed into a list for convenience - self.refButtons = [] #buttons next to reference lineEdits - self.attachmentOffsetEdits = [] #all edit boxes related to attachmentOffset - self.i_active_ref = -1 #index of reference being selected (-1 means no reaction to selecting) - self.auto_next = False #if true, references being selected are appended ('Selecting' state is automatically advanced to next button) + self.form = None # Qt widget of dialog interface + self.block = False # when True, event handlers return without doing anything (instead of doing-undoing blockSignals to everything) + self.refLines = [] # reference lineEdit widgets, packed into a list for convenience + self.refButtons = [] # buttons next to reference lineEdits + self.attachmentOffsetEdits = [] # all edit boxes related to attachmentOffset + self.i_active_ref = ( + -1 + ) # index of reference being selected (-1 means no reaction to selecting) + self.auto_next = False # if true, references being selected are appended ('Selecting' state is automatically advanced to next button) - self.tv = None #TempoVis class instance + self.tv = None # TempoVis class instance - self.create_transaction = True # if false, dialog doesn't mess with transactions. - self.callback_OK = None - self.callback_Cancel = None - self.callback_Apply = None + self.create_transaction = True # if false, dialog doesn't mess with transactions. + self.callback_OK = None + self.callback_Cancel = None + self.callback_Apply = None self._freeze() - def __init__(self, obj_to_attach, - take_selection = False, - create_transaction = True, - callback_OK = None, - callback_Cancel = None, - callback_Apply = None): + def __init__( + self, + obj_to_attach, + take_selection=False, + create_transaction=True, + callback_OK=None, + callback_Cancel=None, + callback_Apply=None, + ): self.__define_attributes() self.create_transaction = create_transaction - self.callback_OK = callback_OK - self.callback_Cancel = callback_Cancel - self.callback_Apply = callback_Apply + self.callback_OK = callback_OK + self.callback_Cancel = callback_Cancel + self.callback_Apply = callback_Apply self.obj = obj_to_attach try: - if not self.obj.hasExtension('Part::AttachExtension'): - self.obj.addExtension('Part::AttachExtensionPython') + if not self.obj.hasExtension("Part::AttachExtension"): + self.obj.addExtension("Part::AttachExtensionPython") except Exception: pass - if hasattr(obj_to_attach,'Attacher'): + if hasattr(obj_to_attach, "Attacher"): self.attacher = obj_to_attach.Attacher - elif hasattr(obj_to_attach,'AttacherType'): + elif hasattr(obj_to_attach, "AttacherType"): self.attacher = Part.AttachEngine(obj_to_attach.AttacherType) else: movable = True if not hasattr(self.obj, "Placement"): movable = False - if 'Hidden' in self.obj.getEditorMode("Placement") or 'ReadOnly' in self.obj.getEditorMode("Placement"): + if "Hidden" in self.obj.getEditorMode( + "Placement" + ) or "ReadOnly" in self.obj.getEditorMode("Placement"): movable = False if not movable: if self.callback_Cancel: self.callback_Cancel() - raise ValueError(translate('AttachmentEditor',"Object {} is neither movable nor attachable, can't edit attachment",None) - .format(self.obj.Label)) + raise ValueError( + translate( + "AttachmentEditor", + "Object {} is neither movable nor attachable, can't edit attachment", + None, + ).format(self.obj.Label) + ) self.obj_is_attachable = False self.attacher = Part.AttachEngine() mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate('AttachmentEditor', - "{} is not attachable. The attachment editor can still be used to align the object, but the attachment will not be parametric." - ,None) - .format(obj_to_attach.Label)) - mb.setWindowTitle(translate('AttachmentEditor',"Attachment",None)) + mb.setText( + translate( + "AttachmentEditor", + "{} is not attachable. The attachment editor can still be used to align the object, but the attachment will not be parametric.", + None, + ).format(obj_to_attach.Label) + ) + mb.setWindowTitle(translate("AttachmentEditor", "Attachment", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate('AttachmentEditor',"Continue",None),QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("AttachmentEditor", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() if mb.clickedButton() is btnAbort: @@ -225,58 +277,85 @@ class AttachmentEditorTaskPanel(FrozenClass): raise CancelError() import os - self.form=uic.loadUi(os.path.dirname(__file__) + os.path.sep + 'TaskAttachmentEditor.ui') - self.form.setWindowIcon(QtGui.QIcon(':/icons/tools/Part_Attachment.svg')) - self.form.setWindowTitle(translate('AttachmentEditor',"Attachment",None)) + + self.form = uic.loadUi(os.path.dirname(__file__) + os.path.sep + "TaskAttachmentEditor.ui") + self.form.setWindowIcon(QtGui.QIcon(":/icons/tools/Part_Attachment.svg")) + self.form.setWindowTitle(translate("AttachmentEditor", "Attachment", None)) self.form.attachmentOffsetX.setProperty("unit", "mm") self.form.attachmentOffsetY.setProperty("unit", "mm") self.form.attachmentOffsetZ.setProperty("unit", "mm") - Gui.ExpressionBinding(self.form.attachmentOffsetX).bind(self.obj,"AttachmentOffset.Base.x") - Gui.ExpressionBinding(self.form.attachmentOffsetY).bind(self.obj,"AttachmentOffset.Base.y") - Gui.ExpressionBinding(self.form.attachmentOffsetZ).bind(self.obj,"AttachmentOffset.Base.z") + Gui.ExpressionBinding(self.form.attachmentOffsetX).bind(self.obj, "AttachmentOffset.Base.x") + Gui.ExpressionBinding(self.form.attachmentOffsetY).bind(self.obj, "AttachmentOffset.Base.y") + Gui.ExpressionBinding(self.form.attachmentOffsetZ).bind(self.obj, "AttachmentOffset.Base.z") - Gui.ExpressionBinding(self.form.attachmentOffsetYaw).bind(self.obj,"AttachmentOffset.Rotation.Yaw") - Gui.ExpressionBinding(self.form.attachmentOffsetPitch).bind(self.obj,"AttachmentOffset.Rotation.Pitch") - Gui.ExpressionBinding(self.form.attachmentOffsetRoll).bind(self.obj,"AttachmentOffset.Rotation.Roll") + Gui.ExpressionBinding(self.form.attachmentOffsetYaw).bind( + self.obj, "AttachmentOffset.Rotation.Yaw" + ) + Gui.ExpressionBinding(self.form.attachmentOffsetPitch).bind( + self.obj, "AttachmentOffset.Rotation.Pitch" + ) + Gui.ExpressionBinding(self.form.attachmentOffsetRoll).bind( + self.obj, "AttachmentOffset.Rotation.Roll" + ) - self.refLines = [self.form.lineRef1, - self.form.lineRef2, - self.form.lineRef3, - self.form.lineRef4] - self.refButtons = [self.form.buttonRef1, - self.form.buttonRef2, - self.form.buttonRef3, - self.form.buttonRef4] - self.attachmentOffsetEdits = [self.form.attachmentOffsetX, - self.form.attachmentOffsetY, - self.form.attachmentOffsetZ, - self.form.attachmentOffsetYaw, - self.form.attachmentOffsetPitch, - self.form.attachmentOffsetRoll] + self.refLines = [ + self.form.lineRef1, + self.form.lineRef2, + self.form.lineRef3, + self.form.lineRef4, + ] + self.refButtons = [ + self.form.buttonRef1, + self.form.buttonRef2, + self.form.buttonRef3, + self.form.buttonRef4, + ] + self.attachmentOffsetEdits = [ + self.form.attachmentOffsetX, + self.form.attachmentOffsetY, + self.form.attachmentOffsetZ, + self.form.attachmentOffsetYaw, + self.form.attachmentOffsetPitch, + self.form.attachmentOffsetRoll, + ] self.block = False for i in range(len(self.refLines)): - QtCore.QObject.connect(self.refLines[i], QtCore.SIGNAL('textEdited(QString)'), lambda txt, i=i: self.lineRefChanged(i,txt)) + QtCore.QObject.connect( + self.refLines[i], + QtCore.SIGNAL("textEdited(QString)"), + lambda txt, i=i: self.lineRefChanged(i, txt), + ) for i in range(len(self.refLines)): - QtCore.QObject.connect(self.refButtons[i], QtCore.SIGNAL('clicked()'), lambda i=i: self.refButtonClicked(i)) + QtCore.QObject.connect( + self.refButtons[i], QtCore.SIGNAL("clicked()"), lambda i=i: self.refButtonClicked(i) + ) for i in range(len(self.attachmentOffsetEdits)): - QtCore.QObject.connect(self.attachmentOffsetEdits[i], QtCore.SIGNAL('valueChanged(double)'), lambda val, i=i: self.attachmentOffsetChanged(i,val)) + QtCore.QObject.connect( + self.attachmentOffsetEdits[i], + QtCore.SIGNAL("valueChanged(double)"), + lambda val, i=i: self.attachmentOffsetChanged(i, val), + ) - QtCore.QObject.connect(self.form.checkBoxFlip, QtCore.SIGNAL('clicked()'), self.checkBoxFlipClicked) + QtCore.QObject.connect( + self.form.checkBoxFlip, QtCore.SIGNAL("clicked()"), self.checkBoxFlipClicked + ) - QtCore.QObject.connect(self.form.listOfModes, QtCore.SIGNAL('itemSelectionChanged()'), self.modeSelected) + QtCore.QObject.connect( + self.form.listOfModes, QtCore.SIGNAL("itemSelectionChanged()"), self.modeSelected + ) if self.create_transaction: - self.obj.Document.openTransaction(translate('AttachmentEditor',"Edit attachment of {}",None).format(self.obj.Name)) - + self.obj.Document.openTransaction( + translate("AttachmentEditor", "Edit attachment of {}", None).format(self.obj.Name) + ) self.readParameters() - if len(self.attacher.References) == 0 and take_selection: sel = GetSelectionAsLinkSubList() for i in range(len(sel))[::-1]: @@ -298,25 +377,31 @@ class AttachmentEditorTaskPanel(FrozenClass): self.updatePreview() self.updateRefButtons() - self.tv = TempoVis(self.obj.Document, tag= "PartGui.TaskAttachmentEditor") - if self.tv: # tv will still be None if Show module is unavailable + self.tv = TempoVis(self.obj.Document, tag="PartGui.TaskAttachmentEditor") + if self.tv: # tv will still be None if Show module is unavailable self.tv.hide_all_dependent(self.obj) self.tv.show(self.obj) self.tv.setUnpickable(self.obj) self.tv.modifyVPProperty(self.obj, "Transparency", 70) - self.tv.show([obj for (obj,subname) in self.attacher.References]) + self.tv.show([obj for (obj, subname) in self.attacher.References]) # task dialog handling def getStandardButtons(self): - return QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Apply + return ( + QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Apply + ) - def clicked(self,button): + def clicked(self, button): if button == QtGui.QDialogButtonBox.Apply: if self.obj_is_attachable: self.writeParameters() if self.create_transaction: self.obj.Document.commitTransaction() - self.obj.Document.openTransaction(translate('AttachmentEditor',"Edit attachment of {}",None).format(self.obj.Name)) + self.obj.Document.openTransaction( + translate("AttachmentEditor", "Edit attachment of {}", None).format( + self.obj.Name + ) + ) self.updatePreview() if self.callback_Apply: self.callback_Apply() @@ -339,36 +424,45 @@ class AttachmentEditorTaskPanel(FrozenClass): if self.callback_Cancel: self.callback_Cancel() - - #selectionObserver stuff - def addSelection(self,docname,objname,subname,pnt): + # selectionObserver stuff + def addSelection(self, docname, objname, subname, pnt): i = self.i_active_ref if i < 0: - #not selecting any reference + # not selecting any reference return if i > 0 and self.auto_next: - prevref = LinkFromStr( self.refLines[i-1].text(), self.obj.Document ) - if prevref[0].Name == objname and subname == '': + prevref = LinkFromStr(self.refLines[i - 1].text(), self.obj.Document) + if prevref[0].Name == objname and subname == "": # whole object was selected by double-clicking # its subelement was already written to line[i-1], so we decrease i to overwrite the lineRefChanged i -= 1 - if i > len(self.refLines)-1: + if i > len(self.refLines) - 1: # all 4 references have been selected, finish - assert(self.auto_next) + assert self.auto_next self.i_active_ref = -1 self.updateRefButtons() return if i > -1: # assign the selected reference if objname == self.obj.Name: - self.form.message.setText(translate('AttachmentEditor',"Ignored. Can't attach object to itself!",None)) + self.form.message.setText( + translate("AttachmentEditor", "Ignored. Can't attach object to itself!", None) + ) return if App.getDocument(docname).getObject(objname) in getAllDependent(self.obj): - self.form.message.setText(translate('AttachmentEditor',"{} depends on object being attached, can't use it for attachment",None).format(objname)) + self.form.message.setText( + translate( + "AttachmentEditor", + "{} depends on object being attached, can't use it for attachment", + None, + ).format(objname) + ) return - self.refLines[i].setText( StrFromLink(App.getDocument(docname).getObject(objname), subname) ) - self.lineRefChanged(i,'') + self.refLines[i].setText( + StrFromLink(App.getDocument(docname).getObject(objname), subname) + ) + self.lineRefChanged(i, "") if self.auto_next: i += 1 self.i_active_ref = i @@ -381,19 +475,19 @@ class AttachmentEditorTaskPanel(FrozenClass): return plm = self.attacher.AttachmentOffset pos = plm.Base - if index==0: + if index == 0: pos.x = Q(self.form.attachmentOffsetX.text()).getValueAs(mm) - if index==1: + if index == 1: pos.y = Q(self.form.attachmentOffsetY.text()).getValueAs(mm) - if index==2: + if index == 2: pos.z = Q(self.form.attachmentOffsetZ.text()).getValueAs(mm) - if index >= 0 and index <= 2: + if index >= 0 and index <= 2: plm.Base = pos - if index >= 3 and index <= 5: + if index >= 3 and index <= 5: yaw = Q(self.form.attachmentOffsetYaw.text()).getValueAs(deg) pitch = Q(self.form.attachmentOffsetPitch.text()).getValueAs(deg) roll = Q(self.form.attachmentOffsetRoll.text()).getValueAs(deg) - rot = App.Rotation(yaw,pitch,roll) + rot = App.Rotation(yaw, pitch, roll) plm.Rotation = rot self.attacher.AttachmentOffset = plm @@ -416,10 +510,10 @@ class AttachmentEditorTaskPanel(FrozenClass): if self.block: return if self.i_active_ref == index: - #stop selecting + # stop selecting self.i_active_ref = -1 else: - #start selecting + # start selecting self.i_active_ref = index self.auto_next = False self.updateRefButtons() @@ -430,13 +524,13 @@ class AttachmentEditorTaskPanel(FrozenClass): self.attacher.Mode = self.getCurrentMode() self.updatePreview() - #internal methods + # internal methods def writeParameters(self): - 'Transfer from the dialog to the object' + "Transfer from the dialog to the object" self.attacher.writeParametersToFeature(self.obj) def readParameters(self): - 'Transfer from the object to the dialog' + "Transfer from the object to the dialog" if self.obj_is_attachable: self.attacher.readParametersFromFeature(self.obj) @@ -444,12 +538,18 @@ class AttachmentEditorTaskPanel(FrozenClass): try: old_selfblock = self.block self.block = True - self.form.attachmentOffsetX.lineEdit().setText ((plm.Base.x * mm).UserString) - self.form.attachmentOffsetY.lineEdit().setText ((plm.Base.y * mm).UserString) - self.form.attachmentOffsetZ.lineEdit().setText ((plm.Base.z * mm).UserString) - self.form.attachmentOffsetYaw.lineEdit().setText ((plm.Rotation.toEuler()[0] * deg).UserString) - self.form.attachmentOffsetPitch.lineEdit().setText((plm.Rotation.toEuler()[1] * deg).UserString) - self.form.attachmentOffsetRoll.lineEdit().setText ((plm.Rotation.toEuler()[2] * deg).UserString) + self.form.attachmentOffsetX.lineEdit().setText((plm.Base.x * mm).UserString) + self.form.attachmentOffsetY.lineEdit().setText((plm.Base.y * mm).UserString) + self.form.attachmentOffsetZ.lineEdit().setText((plm.Base.z * mm).UserString) + self.form.attachmentOffsetYaw.lineEdit().setText( + (plm.Rotation.toEuler()[0] * deg).UserString + ) + self.form.attachmentOffsetPitch.lineEdit().setText( + (plm.Rotation.toEuler()[1] * deg).UserString + ) + self.form.attachmentOffsetRoll.lineEdit().setText( + (plm.Rotation.toEuler()[2] * deg).UserString + ) self.form.checkBoxFlip.setChecked(self.attacher.Reverse) @@ -463,17 +563,19 @@ class AttachmentEditorTaskPanel(FrozenClass): self.block = True strings = StrListFromRefs(self.attacher.References) if len(strings) < len(self.refLines): - strings.extend(['']*(len(self.refLines) - len(strings))) + strings.extend([""] * (len(self.refLines) - len(strings))) for i in range(len(self.refLines)): self.refLines[i].setText(strings[i]) finally: - self.block = old_block + self.block = old_block def parseAllRefLines(self): - self.attacher.References = RefsFromStrList([le.text() for le in self.refLines], self.obj.Document) + self.attacher.References = RefsFromStrList( + [le.text() for le in self.refLines], self.obj.Document + ) def updateListOfModes(self): - '''needs suggestor to have been called, and assigned to self.last_sugr''' + """needs suggestor to have been called, and assigned to self.last_sugr""" try: old_selfblock = self.block self.block = True @@ -481,40 +583,46 @@ class AttachmentEditorTaskPanel(FrozenClass): list_widget.clear() sugr = self.last_sugr # always have the option to choose Deactivated mode - valid_modes = ['Deactivated'] + sugr['allApplicableModes'] + valid_modes = ["Deactivated"] + sugr["allApplicableModes"] # add valid modes for m in valid_modes: item = QtGui.QListWidgetItem() - txt = self.attacher.getModeInfo(m)['UserFriendlyName'] + txt = self.attacher.getModeInfo(m)["UserFriendlyName"] item.setText(txt) - item.setData(self.KEYmode,m) - item.setData(self.KEYon,True) - if m == sugr['bestFitMode']: + item.setData(self.KEYmode, m) + item.setData(self.KEYon, True) + if m == sugr["bestFitMode"]: f = item.font() f.setBold(True) item.setFont(f) list_widget.addItem(item) item.setSelected(self.attacher.Mode == m) # add potential modes - for m in sugr['reachableModes'].keys(): + for m in sugr["reachableModes"].keys(): item = QtGui.QListWidgetItem() - txt = self.attacher.getModeInfo(m)['UserFriendlyName'] - listlistrefs = sugr['reachableModes'][m] + txt = self.attacher.getModeInfo(m)["UserFriendlyName"] + listlistrefs = sugr["reachableModes"][m] if len(listlistrefs) == 1: - listrefs_userfriendly = [self.attacher.getRefTypeInfo(t)['UserFriendlyName'] for t in listlistrefs[0]] - txt = translate('AttachmentEditor',"{} (add {})",None).format(txt, u"+".join(listrefs_userfriendly)) + listrefs_userfriendly = [ + self.attacher.getRefTypeInfo(t)["UserFriendlyName"] for t in listlistrefs[0] + ] + txt = translate("AttachmentEditor", "{} (add {})", None).format( + txt, "+".join(listrefs_userfriendly) + ) else: - txt = translate('AttachmentEditor',"{} (add more references)",None).format(txt) + txt = translate("AttachmentEditor", "{} (add more references)", None).format( + txt + ) item.setText(txt) - item.setData(self.KEYmode,m) - item.setData(self.KEYon,True) - if m == sugr['bestFitMode']: + item.setData(self.KEYmode, m) + item.setData(self.KEYon, True) + if m == sugr["bestFitMode"]: f = item.font() f.setBold(True) item.setFont(f) - #disable this item + # disable this item f = item.flags() f = f & ~(QtCore.Qt.ItemFlag.ItemIsEnabled | QtCore.Qt.ItemFlag.ItemIsSelectable) item.setFlags(f) @@ -522,27 +630,30 @@ class AttachmentEditorTaskPanel(FrozenClass): list_widget.addItem(item) # re-scan the list to fill in tooltips - for item in list_widget.findItems('', QtCore.Qt.MatchContains): + for item in list_widget.findItems("", QtCore.Qt.MatchContains): m = item.data(self.KEYmode) on = item.data(self.KEYon) mi = self.attacher.getModeInfo(m) cmb = [] - for refstr in mi['ReferenceCombinations']: - refstr_userfriendly = [self.attacher.getRefTypeInfo(t)['UserFriendlyName'] for t in refstr] - cmb.append(u", ".join(refstr_userfriendly)) + for refstr in mi["ReferenceCombinations"]: + refstr_userfriendly = [ + self.attacher.getRefTypeInfo(t)["UserFriendlyName"] for t in refstr + ] + cmb.append(", ".join(refstr_userfriendly)) - tip = mi['BriefDocu'] - if (m != 'Deactivated'): - tip += u"\n\n" - tip += translate('AttachmentEditor', "Reference combinations:", None) + u" \n\n".join(cmb) + tip = mi["BriefDocu"] + if m != "Deactivated": + tip += "\n\n" + tip += translate( + "AttachmentEditor", "Reference combinations:", None + ) + " \n\n".join(cmb) item.setToolTip(tip) finally: self.block = old_selfblock - def updateRefButtons(self): try: old_selfblock = self.block @@ -551,12 +662,16 @@ class AttachmentEditorTaskPanel(FrozenClass): btn = self.refButtons[i] btn.setCheckable(True) btn.setChecked(self.i_active_ref == i) - typ = translate('AttachmentEditor',"Reference{}",None).format(str(i+1)) + typ = translate("AttachmentEditor", "Reference{}", None).format(str(i + 1)) if self.last_sugr is not None: - typestr = self.last_sugr['references_Types'] + typestr = self.last_sugr["references_Types"] if i < len(typestr): - typ = self.attacher.getRefTypeInfo(typestr[i])['UserFriendlyName'] - btn.setText(translate('AttachmentEditor',"Selecting…",None) if self.i_active_ref == i else typ) + typ = self.attacher.getRefTypeInfo(typestr[i])["UserFriendlyName"] + btn.setText( + translate("AttachmentEditor", "Selecting…", None) + if self.i_active_ref == i + else typ + ) finally: self.block = old_selfblock @@ -565,11 +680,13 @@ class AttachmentEditorTaskPanel(FrozenClass): sel = list_widget.selectedItems() if len(sel) == 1: if sel[0].data(self.KEYon): - return str(sel[0].data(self.KEYmode)) # data() returns unicode, which confuses attacher + return str( + sel[0].data(self.KEYmode) + ) # data() returns unicode, which confuses attacher # nothing selected in list. Return suggested if self.last_sugr is not None: - if self.last_sugr['message'] == 'OK': - return self.last_sugr['bestFitMode'] + if self.last_sugr["message"] == "OK": + return self.last_sugr["bestFitMode"] # no suggested mode. Return current, so it doesn't change return self.attacher.Mode @@ -579,8 +696,12 @@ class AttachmentEditorTaskPanel(FrozenClass): try: self.parseAllRefLines() self.last_sugr = self.attacher.suggestModes() - if self.last_sugr['message'] == 'LinkBroken': - raise ValueError(translate('AttachmentEditor',"Failed to resolve links. {}",None).format(self.last_sugr['error'])) + if self.last_sugr["message"] == "LinkBroken": + raise ValueError( + translate("AttachmentEditor", "Failed to resolve links. {}", None).format( + self.last_sugr["error"] + ) + ) self.updateListOfModes() @@ -588,27 +709,35 @@ class AttachmentEditorTaskPanel(FrozenClass): new_plm = self.attacher.calculateAttachedPlacement(self.obj.Placement) if new_plm is None: - self.form.message.setText(translate('AttachmentEditor',"Not attached",None)) + self.form.message.setText(translate("AttachmentEditor", "Not attached", None)) else: - self.form.message.setText(translate('AttachmentEditor',"Attached with mode {}",None) - .format(self.attacher.getModeInfo(self.getCurrentMode())['UserFriendlyName'])) + self.form.message.setText( + translate("AttachmentEditor", "Attached with mode {}", None).format( + self.attacher.getModeInfo(self.getCurrentMode())["UserFriendlyName"] + ) + ) if PlacementsFuzzyCompare(self.obj.Placement, new_plm) == False: # assign only if placement changed. this avoids touching the object # when entering and exiting dialog without changing anything self.obj.Placement = new_plm except Exception as err: - self.form.message.setText(translate('AttachmentEditor',"Error: {}",None).format(str(err))) + self.form.message.setText( + translate("AttachmentEditor", "Error: {}", None).format(str(err)) + ) if new_plm is not None: - self.form.groupBox_AttachmentOffset.setTitle(translate('AttachmentEditor',"Attachment Offset (in local coordinates):",None)) + self.form.groupBox_AttachmentOffset.setTitle( + translate("AttachmentEditor", "Attachment Offset (in local coordinates):", None) + ) self.form.groupBox_AttachmentOffset.setEnabled(True) else: - self.form.groupBox_AttachmentOffset.setTitle(translate('AttachmentEditor',"Attachment Offset (inactive - not attached):",None)) + self.form.groupBox_AttachmentOffset.setTitle( + translate("AttachmentEditor", "Attachment Offset (inactive - not attached):", None) + ) self.form.groupBox_AttachmentOffset.setEnabled(False) def cleanUp(self): - '''stuff that needs to be done when dialog is closed.''' + """stuff that needs to be done when dialog is closed.""" Gui.Selection.removeObserver(self) if self.tv: self.tv.restore() - diff --git a/src/Mod/Part/AttachmentEditor/__init__.py b/src/Mod/Part/AttachmentEditor/__init__.py index 8fbb285884..bd4fba4dfe 100644 --- a/src/Mod/Part/AttachmentEditor/__init__.py +++ b/src/Mod/Part/AttachmentEditor/__init__.py @@ -1 +1 @@ -# SPDX-License-Identifier: LGPL-2.1-or-later \ No newline at end of file +# SPDX-License-Identifier: LGPL-2.1-or-later diff --git a/src/Mod/Part/BOPTools/BOPFeatures.py b/src/Mod/Part/BOPTools/BOPFeatures.py index 03556da911..41193ca74c 100644 --- a/src/Mod/Part/BOPTools/BOPFeatures.py +++ b/src/Mod/Part/BOPTools/BOPFeatures.py @@ -29,6 +29,7 @@ __doc__ = "Helper class to create the features for Boolean operations." import FreeCAD import Part + class BOPFeatures: def __init__(self, doc): self.doc = doc diff --git a/src/Mod/Part/BOPTools/GeneralFuseResult.py b/src/Mod/Part/BOPTools/GeneralFuseResult.py index ec7ba2b25c..e02e6ce7aa 100644 --- a/src/Mod/Part/BOPTools/GeneralFuseResult.py +++ b/src/Mod/Part/BOPTools/GeneralFuseResult.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,7 +22,7 @@ # * * # ***************************************************************************/ -__title__="BOPTools.GeneralFuseResult module" +__title__ = "BOPTools.GeneralFuseResult module" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" __doc__ = "Implementation of GeneralFuseResult class, which parses return of generalFuse." @@ -33,13 +33,13 @@ from .Utils import HashableShape, HashableShape_Deep, FrozenClass class GeneralFuseResult(FrozenClass): """class GeneralFuseResult: helper object for obtaining info from results of - Part.Shape.generalFuse() method. + Part.Shape.generalFuse() method. -Usage: -def myCustomFusionRoutine(list_of_shapes): - generalFuse_return = list_of_shapes[0].generalFuse(list_of_shapes[1:]) - ao = GeneralFuseResult(list_of_shapes, generalFuse_return) - ... (use attributes and methods of ao) ...""" + Usage: + def myCustomFusionRoutine(list_of_shapes): + generalFuse_return = list_of_shapes[0].generalFuse(list_of_shapes[1:]) + ao = GeneralFuseResult(list_of_shapes, generalFuse_return) + ... (use attributes and methods of ao) ...""" def __define_attributes(self): # stores the data returned by generalFuse, supplied to class constructor @@ -55,9 +55,9 @@ def myCustomFusionRoutine(list_of_shapes): # key = decorated shape. Value = index (int) into self.source_shapes self._source_to_index = {} - #list of pieces (indexes) generated from a source shape, by index of source shape. List of lists of ints. + # list of pieces (indexes) generated from a source shape, by index of source shape. List of lists of ints. self._pieces_of_source = [] - #list of source shapes (indexes) the piece came from, by index of piece. List of lists of ints. + # list of source shapes (indexes) the piece came from, by index of piece. List of lists of ints. self._sources_of_piece = [] # dictionary for finding, which source shapes did an element of pieces come from. @@ -79,7 +79,7 @@ def myCustomFusionRoutine(list_of_shapes): It is called automatically by class constructor.""" - #save things to be parsed and wipe out all other data + # save things to be parsed and wipe out all other data gfa_return = self.gfa_return source_shapes = self.source_shapes self.__define_attributes() @@ -105,15 +105,15 @@ def myCustomFusionRoutine(list_of_shapes): else: raise ValueError("GeneralFuseAnalyzer.parse: duplicate source shape detected.") - #test if map has missing entries + # test if map has missing entries map_needs_repairing = False for iSource in range(len(map)): if len(map[iSource]) == 0: map_needs_repairing = True if map_needs_repairing: - aggregate_types = set(["Wire","Shell","CompSolid","Compound"]) - nonaggregate_types = set(["Vertex","Edge","Face","Solid"]) + aggregate_types = set(["Wire", "Shell", "CompSolid", "Compound"]) + nonaggregate_types = set(["Vertex", "Edge", "Face", "Solid"]) types = set() for piece in self.pieces: @@ -123,25 +123,29 @@ def myCustomFusionRoutine(list_of_shapes): def extractor(sh): return ( - (sh.Vertexes if "Vertex" in types_to_extract else []) + - (sh.Edges if "Edge" in types_to_extract else []) + - (sh.Faces if "Face" in types_to_extract else []) + - (sh.Solids if "Solid" in types_to_extract else []) + (sh.Vertexes if "Vertex" in types_to_extract else []) + + (sh.Edges if "Edge" in types_to_extract else []) + + (sh.Faces if "Face" in types_to_extract else []) + + (sh.Solids if "Solid" in types_to_extract else []) ) - aggregate_sources_indexes = [self.indexOfSource(sh) for sh in self.source_shapes if sh.ShapeType in aggregate_types] + aggregate_sources_indexes = [ + self.indexOfSource(sh) + for sh in self.source_shapes + if sh.ShapeType in aggregate_types + ] aggregate_pieces = [sh for sh in self.pieces if sh.ShapeType in aggregate_types] - assert(len(aggregate_sources_indexes) == len(aggregate_pieces)) + assert len(aggregate_sources_indexes) == len(aggregate_pieces) for i_aggregate in range(len(aggregate_sources_indexes)): iSource = aggregate_sources_indexes[i_aggregate] - if len(map[iSource]) == 0:#recover only if info is actually missing + if len(map[iSource]) == 0: # recover only if info is actually missing map[iSource] = [aggregate_pieces[i_aggregate]] - #search if any plain pieces are also in this aggregate piece. If yes, we need to add the piece to map. + # search if any plain pieces are also in this aggregate piece. If yes, we need to add the piece to map. for sh in extractor(aggregate_pieces[i_aggregate]): hash = HashableShape(sh) iPiece = self._piece_to_index.get(hash) if iPiece is not None: - #print "found piece {num} in compound {numc}".format(num= iPiece, numc= i_aggregate) + # print "found piece {num} in compound {numc}".format(num= iPiece, numc= i_aggregate) if not map[iSource][-1].isSame(self.pieces[iPiece]): map[iSource].append(self.pieces[iPiece]) @@ -149,12 +153,17 @@ def myCustomFusionRoutine(list_of_shapes): for iSource in range(len(map)): if len(map[iSource]) == 0: import FreeCAD as App - App.Console.PrintWarning("Map entry {num} is empty. " - "Source-to-piece correspondence information is probably incomplete.".format(num=iSource)) + + App.Console.PrintWarning( + "Map entry {num} is empty. " + "Source-to-piece correspondence information is probably incomplete.".format( + num=iSource + ) + ) self._pieces_of_source = [[] for i in range(len(self.source_shapes))] self._sources_of_piece = [[] for i in range(len(self.pieces))] - assert(len(map) == len(self.source_shapes)) + assert len(map) == len(self.source_shapes) for iSource in range(len(self.source_shapes)): list_pieces = map[iSource] for piece in list_pieces: @@ -166,8 +175,8 @@ def myCustomFusionRoutine(list_of_shapes): """Fills element-to-source map. Potentially slow, so separated from general parse. Needed for splitAggregates; called automatically from splitAggregates.""" - if len(self._element_to_source)>0: - return #already parsed. + if len(self._element_to_source) > 0: + return # already parsed. for iPiece in range(len(self.pieces)): piece = self.pieces[iPiece] @@ -181,6 +190,7 @@ def myCustomFusionRoutine(list_of_shapes): def indexOfPiece(self, piece_shape): "indexOfPiece(piece_shape): returns index of piece_shape in list of pieces" return self._piece_to_index[HashableShape(piece_shape)] + def indexOfSource(self, source_shape): "indexOfSource(source_shape): returns index of source_shape in list of arguments" return self._source_to_index[HashableShape(source_shape)] @@ -212,11 +222,12 @@ def myCustomFusionRoutine(list_of_shapes): returns 3. Note: the return value may be incorrect if some of the pieces are wires/shells/ - compsolids/compounds. Please use explodeCompounds and splitAggregates before using this function.""" + compsolids/compounds. Please use explodeCompounds and splitAggregates before using this function. + """ return max([len(ilist) for ilist in self._sources_of_piece]) - def splitAggregates(self, pieces_to_split = None): + def splitAggregates(self, pieces_to_split=None): """splitAggregates(pieces_to_split = None): splits aggregate shapes (wires, shells, compsolids) in pieces of GF result as cut by intersections. Also splits aggregates inside compounds. After running this, 'self' is replaced with new data, where the @@ -238,20 +249,20 @@ def myCustomFusionRoutine(list_of_shapes): new_data = GeneralFuseReturnBuilder(self.source_shapes) changed = False - #split pieces that are not compounds.... + # split pieces that are not compounds.... for iPiece in range(len(self.pieces)): piece = self.pieces[iPiece] if HashableShape(piece) in pieces_to_split: new_pieces = self.makeSplitPieces(piece) - changed = changed or len(new_pieces)>1 + changed = changed or len(new_pieces) > 1 for new_piece in new_pieces: new_data.addPiece(new_piece, self._sources_of_piece[iPiece]) else: new_data.addPiece(piece, self._sources_of_piece[iPiece]) - #split pieces inside compounds - #prepare index of existing pieces. + # split pieces inside compounds + # prepare index of existing pieces. existing_pieces = new_data._piece_to_index.copy() for i_new_piece in range(len(new_data.pieces)): new_piece = new_data.pieces[i_new_piece] @@ -265,8 +276,8 @@ def myCustomFusionRoutine(list_of_shapes): if len(new_data.pieces) > len(self.pieces) or changed: self.gfa_return = new_data.getGFReturn() self.parse() - #else: - #print "Nothing was split" + # else: + # print "Nothing was split" def _splitInCompound(self, compound, existing_pieces): """Splits aggregates inside compound. Returns None if nothing is split, otherwise @@ -287,10 +298,10 @@ def myCustomFusionRoutine(list_of_shapes): changed = True else: new_pieces = self.makeSplitPieces(piece) - changed = changed or len(new_pieces)>1 + changed = changed or len(new_pieces) > 1 for new_piece in new_pieces: hash = HashableShape_Deep(new_piece) - dummy,ex_piece = existing_pieces.get(hash, (None, None)) + dummy, ex_piece = existing_pieces.get(hash, (None, None)) if ex_piece is not None: new_children.append(ex_piece) changed = True @@ -302,7 +313,6 @@ def myCustomFusionRoutine(list_of_shapes): else: return None - def makeSplitPieces(self, shape): """makeSplitPieces(self, shape): splits a shell, wire or compsolid into pieces where it intersects with other shapes. @@ -320,7 +330,7 @@ def myCustomFusionRoutine(list_of_shapes): bit_extractor = lambda sh: sh.Solids joint_extractor = lambda sh: sh.Faces else: - #can't split the shape + # can't split the shape return [shape] # for each joint, test if all bits it's connected to are from same number of sources. @@ -334,21 +344,23 @@ def myCustomFusionRoutine(list_of_shapes): for bit in bit_extractor(self.gfa_return[0]): for joint_bit in joint_extractor(bit): if joint_bit.isSame(joint): - #bit is connected to joint! + # bit is connected to joint! bit_overlap_count = len(self._element_to_source[HashableShape(bit)]) - assert(bit_overlap_count <= joint_overlap_count) + assert bit_overlap_count <= joint_overlap_count if bit_overlap_count < joint_overlap_count: if len(splits) == 0 or splits[-1] is not joint: splits.append(joint) - if len(splits)==0: - #shape was not split - no split points found + if len(splits) == 0: + # shape was not split - no split points found return [shape] from . import ShapeMerge - new_pieces = ShapeMerge.mergeShapes(bit_extractor(shape), split_connections= splits, bool_compsolid= True).childShapes() + new_pieces = ShapeMerge.mergeShapes( + bit_extractor(shape), split_connections=splits, bool_compsolid=True + ).childShapes() if len(new_pieces) == 1: - #shape was not split (split points found, but the shape remained in one piece). + # shape was not split (split points found, but the shape remained in one piece). return [shape] return new_pieces @@ -367,7 +379,7 @@ def myCustomFusionRoutine(list_of_shapes): from .Utils import compoundLeaves new_data = GeneralFuseReturnBuilder(self.source_shapes) - new_data.hasher_class = HashableShape #deep hashing not needed here. + new_data.hasher_class = HashableShape # deep hashing not needed here. for iPiece in range(len(self.pieces)): piece = self.pieces[iPiece] @@ -383,13 +395,14 @@ def myCustomFusionRoutine(list_of_shapes): class GeneralFuseReturnBuilder(FrozenClass): "GeneralFuseReturnBuilder: utility class used by splitAggregates to build fake return of generalFuse, for re-parsing." + def __define_attributes(self): self.pieces = [] # key = hasher_class(shape). Value = (index_into_self_dot_pieces, shape). # Note that GeneralFuseResult uses this item directly. self._piece_to_index = {} - self._pieces_from_source = [] #list of list of ints + self._pieces_from_source = [] # list of list of ints self.source_shapes = [] self.hasher_class = HashableShape_Deep @@ -408,19 +421,22 @@ class GeneralFuseReturnBuilder(FrozenClass): ret = False i_piece_existing = None hash = None - if piece_shape.ShapeType != "Compound": # do not catch duplicate compounds + if piece_shape.ShapeType != "Compound": # do not catch duplicate compounds hash = self.hasher_class(piece_shape) i_piece_existing, dummy = self._piece_to_index.get(hash, (None, None)) if i_piece_existing is None: - #adding + # adding self.pieces.append(piece_shape) - i_piece_existing = len(self.pieces)-1 + i_piece_existing = len(self.pieces) - 1 if hash is not None: - self._piece_to_index[hash] = (i_piece_existing, piece_shape,) + self._piece_to_index[hash] = ( + i_piece_existing, + piece_shape, + ) ret = True else: - #re-adding + # re-adding ret = False for iSource in source_shape_index_list: if not i_piece_existing in self._pieces_from_source[iSource]: @@ -428,9 +444,12 @@ class GeneralFuseReturnBuilder(FrozenClass): return ret def replacePiece(self, piece_index, new_shape): - assert(self.pieces[piece_index].ShapeType == "Compound") - assert(new_shape.ShapeType == "Compound") + assert self.pieces[piece_index].ShapeType == "Compound" + assert new_shape.ShapeType == "Compound" self.pieces[piece_index] = new_shape def getGFReturn(self): - return (Part.makeCompound(self.pieces), [[self.pieces[iPiece] for iPiece in ilist] for ilist in self._pieces_from_source]) + return ( + Part.makeCompound(self.pieces), + [[self.pieces[iPiece] for iPiece in ilist] for ilist in self._pieces_from_source], + ) diff --git a/src/Mod/Part/BOPTools/JoinAPI.py b/src/Mod/Part/BOPTools/JoinAPI.py index e6a34aa860..73921a101c 100644 --- a/src/Mod/Part/BOPTools/JoinAPI.py +++ b/src/Mod/Part/BOPTools/JoinAPI.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,7 +22,7 @@ # * * # ***************************************************************************/ -__title__="BOPTools.JoinAPI module" +__title__ = "BOPTools.JoinAPI module" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" __doc__ = "JoinFeatures functions that operate on shapes." @@ -32,31 +32,33 @@ from . import ShapeMerge from .GeneralFuseResult import GeneralFuseResult from .Utils import compoundLeaves + def shapeOfMaxSize(list_of_shapes): """shapeOfMaxSize(list_of_shapes): finds the shape that has the largest " "mass in the list and returns it. The shapes in the list must be of same dimension.""" - #first, check if shapes can be compared by size + # first, check if shapes can be compared by size ShapeMerge.dimensionOfShapes(list_of_shapes) rel_precision = 1e-8 - #find it! - max_size = -1e100 # max size encountered so far - count_max = 0 # number of shapes with size equal to max_size - shape_max = None # shape of max_size + # find it! + max_size = -1e100 # max size encountered so far + count_max = 0 # number of shapes with size equal to max_size + shape_max = None # shape of max_size for sh in list_of_shapes: v = abs(Part.cast_to_shape(sh).Mass) - if v > max_size*(1 + rel_precision) : + if v > max_size * (1 + rel_precision): max_size = v shape_max = sh count_max = 1 - elif (1-rel_precision) * max_size <= v and v <= (1+rel_precision) * max_size : + elif (1 - rel_precision) * max_size <= v and v <= (1 + rel_precision) * max_size: count_max = count_max + 1 - if count_max > 1 : + if count_max > 1: raise ValueError("There is more than one largest piece!") return shape_max -def connect(list_of_shapes, tolerance = 0.0): + +def connect(list_of_shapes, tolerance=0.0): """connect(list_of_shapes, tolerance = 0.0): connects solids (walled objects), shells and wires by throwing off small parts that result when splitting them at intersections. @@ -66,10 +68,10 @@ def connect(list_of_shapes, tolerance = 0.0): # explode all compounds before GFA. new_list_of_shapes = [] for sh in list_of_shapes: - new_list_of_shapes.extend( compoundLeaves(sh) ) + new_list_of_shapes.extend(compoundLeaves(sh)) list_of_shapes = new_list_of_shapes - #test if shapes are compatible for connecting + # test if shapes are compatible for connecting dim = ShapeMerge.dimensionOfShapes(list_of_shapes) if dim == 0: raise TypeError("Cannot connect vertices!") @@ -80,22 +82,24 @@ def connect(list_of_shapes, tolerance = 0.0): pieces, map = list_of_shapes[0].generalFuse(list_of_shapes[1:], tolerance) ao = GeneralFuseResult(list_of_shapes, (pieces, map)) ao.splitAggregates() - #print len(ao.pieces)," pieces total" + # print len(ao.pieces)," pieces total" keepers = [] - all_danglers = [] # debug + all_danglers = [] # debug - #add all biggest dangling pieces + # add all biggest dangling pieces for src in ao.source_shapes: - danglers = [piece for piece in ao.piecesFromSource(src) if len(ao.sourcesOfPiece(piece)) == 1] + danglers = [ + piece for piece in ao.piecesFromSource(src) if len(ao.sourcesOfPiece(piece)) == 1 + ] all_danglers.extend(danglers) largest = shapeOfMaxSize(danglers) if largest is not None: keepers.append(largest) touch_test_list = Part.makeCompound(keepers) - #add all intersection pieces that touch danglers, triple intersection pieces that touch duals, and so on - for ii in range(2, ao.largestOverlapCount()+1): + # add all intersection pieces that touch danglers, triple intersection pieces that touch duals, and so on + for ii in range(2, ao.largestOverlapCount() + 1): list_ii_pieces = [piece for piece in ao.pieces if len(ao.sourcesOfPiece(piece)) == ii] keepers_2_add = [] for piece in list_ii_pieces: @@ -106,18 +110,19 @@ def connect(list_of_shapes, tolerance = 0.0): keepers.extend(keepers_2_add) touch_test_list = Part.makeCompound(keepers_2_add) - - #merge, and we are done! - #print len(keepers)," pieces to keep" + # merge, and we are done! + # print len(keepers)," pieces to keep" return ShapeMerge.mergeShapes(keepers) -def connect_legacy(shape1, shape2, tolerance = 0.0): + +def connect_legacy(shape1, shape2, tolerance=0.0): """connect_legacy(shape1, shape2, tolerance = 0.0): alternative implementation of connect, without use of generalFuse. Slow. Provided for backwards compatibility, and for older OCC.""" - if tolerance>0.0: + if tolerance > 0.0: import FreeCAD as App + App.Console.PrintWarning("connect_legacy does not support tolerance (yet).\n") cut1 = shape1.cut(shape2) cut1 = shapeOfMaxSize(cut1.childShapes()) @@ -125,15 +130,18 @@ def connect_legacy(shape1, shape2, tolerance = 0.0): cut2 = shapeOfMaxSize(cut2.childShapes()) return cut1.multiFuse([cut2, shape2.common(shape1)]) -#def embed(shape_base, shape_tool, tolerance = 0.0): + +# def embed(shape_base, shape_tool, tolerance = 0.0): # (TODO) -def embed_legacy(shape_base, shape_tool, tolerance = 0.0): + +def embed_legacy(shape_base, shape_tool, tolerance=0.0): """embed_legacy(shape_base, shape_tool, tolerance = 0.0): alternative implementation of embed, without use of generalFuse. Slow. Provided for backwards compatibility, and for older OCC.""" - if tolerance>0.0: + if tolerance > 0.0: import FreeCAD as App + App.Console.PrintWarning("embed_legacy does not support tolerance (yet).\n") # using legacy implementation, except adding support for shells @@ -148,15 +156,17 @@ def embed_legacy(shape_base, shape_tool, tolerance = 0.0): result = ShapeMerge.mergeShapes(result.Edges) return result -def cutout_legacy(shape_base, shape_tool, tolerance = 0.0): + +def cutout_legacy(shape_base, shape_tool, tolerance=0.0): """cutout_legacy(shape_base, shape_tool, tolerance = 0.0): alternative implementation of cutout, without use of generalFuse. Slow. Provided for backwards compatibility, and for older OCC.""" - if tolerance>0.0: + if tolerance > 0.0: import FreeCAD as App + App.Console.PrintWarning("cutout_legacy does not support tolerance (yet).\n") - #if base is multi-piece, work on per-piece basis + # if base is multi-piece, work on per-piece basis shapes_base = compoundLeaves(shape_base) if len(shapes_base) > 1: result = [] diff --git a/src/Mod/Part/BOPTools/JoinFeatures.py b/src/Mod/Part/BOPTools/JoinFeatures.py index 5023bff0e3..fece129c45 100644 --- a/src/Mod/Part/BOPTools/JoinFeatures.py +++ b/src/Mod/Part/BOPTools/JoinFeatures.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -34,39 +34,48 @@ import Part if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui -# -------------------------- common stuff ------------------------------------- -# -------------------------- translation-related code ------------------------- -# Thanks, yorik! (see forum thread "A new Part tool is being born... JoinFeatures!" -# https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 ) + # -------------------------- common stuff ------------------------------------- + + # -------------------------- translation-related code ------------------------- + # Thanks, yorik! (see forum thread "A new Part tool is being born... JoinFeatures!" + # https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 ) try: _fromUtf8 = QtCore.QString.fromUtf8 except Exception: + def _fromUtf8(s): return s + translate = FreeCAD.Qt.translate # --------------------------/translation-related code ------------------------- def getParamRefine(): - return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool("RefineModel") + return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool( + "RefineModel" + ) def cmdCreateJoinFeature(name, mode): """cmdCreateJoinFeature(name, mode): generalized implementation of GUI commands.""" sel = FreeCADGui.Selection.getSelectionEx() - FreeCAD.ActiveDocument.openTransaction("Create "+mode) + FreeCAD.ActiveDocument.openTransaction("Create " + mode) FreeCADGui.addModule("BOPTools.JoinFeatures") - FreeCADGui.doCommand("j = BOPTools.JoinFeatures.make{mode}(name='{name}')".format(mode=mode, name=name)) + FreeCADGui.doCommand( + "j = BOPTools.JoinFeatures.make{mode}(name='{name}')".format(mode=mode, name=name) + ) if mode == "Embed" or mode == "Cutout": - FreeCADGui.doCommand("j.Base = App.ActiveDocument."+sel[0].Object.Name) - FreeCADGui.doCommand("j.Tool = App.ActiveDocument."+sel[1].Object.Name) + FreeCADGui.doCommand("j.Base = App.ActiveDocument." + sel[0].Object.Name) + FreeCADGui.doCommand("j.Tool = App.ActiveDocument." + sel[1].Object.Name) elif mode == "Connect": - FreeCADGui.doCommand("j.Objects = {sel}".format( - sel= "[" + ", ".join(["App.ActiveDocument."+so.Object.Name for so in sel]) + "]" - )) + FreeCADGui.doCommand( + "j.Objects = {sel}".format( + sel="[" + ", ".join(["App.ActiveDocument." + so.Object.Name for so in sel]) + "]" + ) + ) else: raise ValueError("cmdCreateJoinFeature: Unexpected mode {mode}".format(mode=repr(mode))) @@ -77,12 +86,17 @@ def cmdCreateJoinFeature(name, mode): mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) error_text1 = translate("Part_JoinFeatures", "Computing the result failed with an error:") - error_text2 = translate("Part_JoinFeatures", "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.") + error_text2 = translate( + "Part_JoinFeatures", + "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.", + ) mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2) - mb.setWindowTitle(translate("Part_JoinFeatures","Bad Selection", None)) + mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate("Part_JoinFeatures","Continue",None), - QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("Part_JoinFeatures", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() @@ -90,8 +104,9 @@ def cmdCreateJoinFeature(name, mode): FreeCAD.ActiveDocument.abortTransaction() return - FreeCADGui.doCommand("for obj in j.ViewObject.Proxy.claimChildren():\n" - " obj.ViewObject.hide()") + FreeCADGui.doCommand( + "for obj in j.ViewObject.Proxy.claimChildren():\n" " obj.ViewObject.hide()" + ) FreeCAD.ActiveDocument.commitTransaction() @@ -99,13 +114,15 @@ def cmdCreateJoinFeature(name, mode): def getIconPath(icon_dot_svg): return icon_dot_svg + # -------------------------- /common stuff ------------------------------------ # -------------------------- Connect ------------------------------------------ + def makeConnect(name): - '''makeConnect(name): makes an Connect object.''' - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name) + """makeConnect(name): makes an Connect object.""" + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureConnect(obj) if FreeCAD.GuiUp: ViewProviderConnect(obj.ViewObject) @@ -115,19 +132,31 @@ def makeConnect(name): class FeatureConnect: """The PartJoinFeature object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLinkList","Objects","Connect","Object to be connected.", locked=True) - obj.addProperty("App::PropertyBool","Refine","Connect", - "True = refine resulting shape. False = output as is.", locked=True) + def __init__(self, obj): + obj.addProperty( + "App::PropertyLinkList", "Objects", "Connect", "Object to be connected.", locked=True + ) + obj.addProperty( + "App::PropertyBool", + "Refine", + "Connect", + "True = refine resulting shape. False = output as is.", + locked=True, + ) obj.Refine = getParamRefine() - obj.addProperty("App::PropertyLength","Tolerance","Connect", - "Tolerance when intersecting (fuzzy value). " - "In addition to tolerances of the shapes.", locked=True) + obj.addProperty( + "App::PropertyLength", + "Tolerance", + "Connect", + "Tolerance when intersecting (fuzzy value). " + "In addition to tolerances of the shapes.", + locked=True, + ) obj.Proxy = self self.Type = "FeatureConnect" - def execute(self,selfobj): + def execute(self, selfobj): rst = JoinAPI.connect([obj.Shape for obj in selfobj.Objects], selfobj.Tolerance) if selfobj.Refine: rst = rst.removeSplitter() @@ -137,7 +166,7 @@ class FeatureConnect: class ViewProviderConnect: """A View Provider for the Part Connect feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -150,7 +179,7 @@ class ViewProviderConnect: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -166,16 +195,21 @@ class ViewProviderConnect: def canDragObjects(self): return True + def canDropObjects(self): return True + def canDragObject(self, dragged_object): return True + def canDropObject(self, incoming_object): - return hasattr(incoming_object, 'Shape') + return hasattr(incoming_object, "Shape") + def dragObject(self, selfvp, dragged_object): objs = self.Object.Objects objs.remove(dragged_object) self.Object.Objects = objs + def dropObject(self, selfvp, incoming_object): self.Object.Objects = self.Object.Objects + [incoming_object] @@ -184,11 +218,14 @@ class CommandConnect: """Command to create Connect feature.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_JoinConnect.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_JoinConnect","Connect Shapes"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_JoinConnect", - "Fuses shapes, taking care to preserve voids")} + return { + "Pixmap": getIconPath("Part_JoinConnect.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_JoinConnect", "Connect Shapes"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_JoinConnect", "Fuses shapes, taking care to preserve voids" + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) >= 1: @@ -196,9 +233,14 @@ class CommandConnect: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_JoinFeatures", - "Select at least two objects, or one or more compounds", None)) - mb.setWindowTitle(translate("Part_JoinFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_JoinFeatures", + "Select at least two objects, or one or more compounds", + None, + ) + ) + mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -207,6 +249,7 @@ class CommandConnect: else: return False + # -------------------------- /Connect ----------------------------------------- @@ -214,8 +257,8 @@ class CommandConnect: def makeEmbed(name): - '''makeEmbed(name): makes an Embed object.''' - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name) + """makeEmbed(name): makes an Embed object.""" + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureEmbed(obj) if FreeCAD.GuiUp: ViewProviderEmbed(obj.ViewObject) @@ -225,20 +268,30 @@ def makeEmbed(name): class FeatureEmbed: """The Part Embed object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLink","Base","Embed","Object to embed into.", locked=True) - obj.addProperty("App::PropertyLink","Tool","Embed","Object to be embedded.", locked=True) - obj.addProperty("App::PropertyBool","Refine","Embed", - "True = refine resulting shape. False = output as is.", locked=True) + def __init__(self, obj): + obj.addProperty("App::PropertyLink", "Base", "Embed", "Object to embed into.", locked=True) + obj.addProperty("App::PropertyLink", "Tool", "Embed", "Object to be embedded.", locked=True) + obj.addProperty( + "App::PropertyBool", + "Refine", + "Embed", + "True = refine resulting shape. False = output as is.", + locked=True, + ) obj.Refine = getParamRefine() - obj.addProperty("App::PropertyLength","Tolerance","Embed", - "Tolerance when intersecting (fuzzy value). " - "In addition to tolerances of the shapes.", locked=True) + obj.addProperty( + "App::PropertyLength", + "Tolerance", + "Embed", + "Tolerance when intersecting (fuzzy value). " + "In addition to tolerances of the shapes.", + locked=True, + ) obj.Proxy = self self.Type = "FeatureEmbed" - def execute(self,selfobj): + def execute(self, selfobj): rst = JoinAPI.embed_legacy(selfobj.Base.Shape, selfobj.Tool.Shape, selfobj.Tolerance) if selfobj.Refine: rst = rst.removeSplitter() @@ -248,7 +301,7 @@ class FeatureEmbed: class ViewProviderEmbed: """A View Provider for the Part Embed feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -261,7 +314,7 @@ class ViewProviderEmbed: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -280,21 +333,29 @@ class CommandEmbed: """Command to create Part Embed feature.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_JoinEmbed.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_JoinEmbed","Embed Shapes"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_JoinEmbed", - "Fuses one shape into another, taking care to preserve voids")} + return { + "Pixmap": getIconPath("Part_JoinEmbed.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_JoinEmbed", "Embed Shapes"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_JoinEmbed", "Fuses one shape into another, taking care to preserve voids" + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) == 2: - cmdCreateJoinFeature(name = "Embed", mode = "Embed") + cmdCreateJoinFeature(name="Embed", mode="Embed") else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_JoinFeatures", - "Select base object, then the object to embed, and then invoke this tool.", None)) - mb.setWindowTitle(translate("Part_JoinFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_JoinFeatures", + "Select base object, then the object to embed, and then invoke this tool.", + None, + ) + ) + mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -303,14 +364,16 @@ class CommandEmbed: else: return False + # -------------------------- /Embed ------------------------------------------- # -------------------------- Cutout ------------------------------------------- + def makeCutout(name): - '''makeCutout(name): makes an Cutout object.''' - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name) + """makeCutout(name): makes an Cutout object.""" + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureCutout(obj) if FreeCAD.GuiUp: ViewProviderCutout(obj.ViewObject) @@ -320,19 +383,31 @@ def makeCutout(name): class FeatureCutout: """The Part Cutout object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLink","Base","Cutout","Object to be cut.", locked=True) - obj.addProperty("App::PropertyLink","Tool","Cutout","Object to make cutout for.", locked=True) - obj.addProperty("App::PropertyBool","Refine","Cutout", - "True = refine resulting shape. False = output as is.", locked=True) + def __init__(self, obj): + obj.addProperty("App::PropertyLink", "Base", "Cutout", "Object to be cut.", locked=True) + obj.addProperty( + "App::PropertyLink", "Tool", "Cutout", "Object to make cutout for.", locked=True + ) + obj.addProperty( + "App::PropertyBool", + "Refine", + "Cutout", + "True = refine resulting shape. False = output as is.", + locked=True, + ) obj.Refine = getParamRefine() - obj.addProperty("App::PropertyLength","Tolerance","Cutout", - "Tolerance when intersecting (fuzzy value). In addition to tolerances of the shapes.", locked=True) + obj.addProperty( + "App::PropertyLength", + "Tolerance", + "Cutout", + "Tolerance when intersecting (fuzzy value). In addition to tolerances of the shapes.", + locked=True, + ) obj.Proxy = self self.Type = "FeatureCutout" - def execute(self,selfobj): + def execute(self, selfobj): rst = JoinAPI.cutout_legacy(selfobj.Base.Shape, selfobj.Tool.Shape, selfobj.Tolerance) if selfobj.Refine: rst = rst.removeSplitter() @@ -342,7 +417,7 @@ class FeatureCutout: class ViewProviderCutout: """A View Provider for the Part Cutout feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -355,7 +430,7 @@ class ViewProviderCutout: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -374,11 +449,14 @@ class CommandCutout: """Command to create PartJoinFeature in Cutout mode.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_JoinCutout.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_JoinCutout","Cutout Shape"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_JoinCutout", - "Creates a cutout in the selected shape to fit another shape")} + return { + "Pixmap": getIconPath("Part_JoinCutout.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_JoinCutout", "Cutout Shape"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_JoinCutout", "Creates a cutout in the selected shape to fit another shape" + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) == 2: @@ -386,9 +464,14 @@ class CommandCutout: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_JoinFeatures", - "Select the object to make a cutout in, then the object that should fit into the cutout, and then invoke this tool.", None)) - mb.setWindowTitle(translate("Part_JoinFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_JoinFeatures", + "Select the object to make a cutout in, then the object that should fit into the cutout, and then invoke this tool.", + None, + ) + ) + mb.setWindowTitle(translate("Part_JoinFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -397,9 +480,11 @@ class CommandCutout: else: return False + # -------------------------- /Cutout ------------------------------------------ + def addCommands(): - FreeCADGui.addCommand('Part_JoinCutout', CommandCutout()) - FreeCADGui.addCommand('Part_JoinEmbed', CommandEmbed()) - FreeCADGui.addCommand('Part_JoinConnect', CommandConnect()) + FreeCADGui.addCommand("Part_JoinCutout", CommandCutout()) + FreeCADGui.addCommand("Part_JoinEmbed", CommandEmbed()) + FreeCADGui.addCommand("Part_JoinConnect", CommandConnect()) diff --git a/src/Mod/Part/BOPTools/ShapeMerge.py b/src/Mod/Part/BOPTools/ShapeMerge.py index 52f97254a3..f000b1906a 100644 --- a/src/Mod/Part/BOPTools/ShapeMerge.py +++ b/src/Mod/Part/BOPTools/ShapeMerge.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,7 +22,7 @@ # * * # ***************************************************************************/ -__title__="BOPTools.ShapeMerge module" +__title__ = "BOPTools.ShapeMerge module" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" __doc__ = "Tools for merging shapes with shared elements. Useful for final processing of results of Part.Shape.generalFuse()." @@ -30,15 +30,18 @@ __doc__ = "Tools for merging shapes with shared elements. Useful for final proce import Part from .Utils import HashableShape + def findSharedElements(shape_list, element_extractor): if len(shape_list) < 2: - raise ValueError("findSharedElements: at least two shapes must be provided (have {num})".format(num= len(shape_list))) + raise ValueError( + "findSharedElements: at least two shapes must be provided (have {num})".format( + num=len(shape_list) + ) + ) - all_elements = [] #list of sets of HashableShapes + all_elements = [] # list of sets of HashableShapes for shape in shape_list: - all_elements.append(set( - [HashableShape(sh) for sh in element_extractor(shape)] - )) + all_elements.append(set([HashableShape(sh) for sh in element_extractor(shape)])) shared_elements = None for elements in all_elements: if shared_elements is None: @@ -47,16 +50,20 @@ def findSharedElements(shape_list, element_extractor): shared_elements.intersection_update(elements) return [el.Shape for el in shared_elements] -def isConnected(shape1, shape2, shape_dim = -1): + +def isConnected(shape1, shape2, shape_dim=-1): if shape_dim == -1: shape_dim = dimensionOfShapes([shape1, shape2]) - extractor = {0: None, - 1: (lambda sh: sh.Vertexes), - 2: (lambda sh: sh.Edges), - 3: (lambda sh: sh.Faces) }[shape_dim] - return len(findSharedElements([shape1, shape2], extractor))>0 + extractor = { + 0: None, + 1: (lambda sh: sh.Vertexes), + 2: (lambda sh: sh.Edges), + 3: (lambda sh: sh.Faces), + }[shape_dim] + return len(findSharedElements([shape1, shape2], extractor)) > 0 -def splitIntoGroupsBySharing(list_of_shapes, element_extractor, split_connections = []): + +def splitIntoGroupsBySharing(list_of_shapes, element_extractor, split_connections=[]): """splitIntoGroupsBySharing(list_of_shapes, element_type, split_connections = []): find, which shapes in list_of_shapes are connected into groups by sharing elements. @@ -70,14 +77,16 @@ def splitIntoGroupsBySharing(list_of_shapes, element_extractor, split_connection split_connections = set([HashableShape(element) for element in split_connections]) - groups = [] #list of tuples (shapes,elements). Shapes is a list of plain shapes. Elements is a set of HashableShapes - all elements of shapes in the group, excluding split_connections. + groups = ( + [] + ) # list of tuples (shapes,elements). Shapes is a list of plain shapes. Elements is a set of HashableShapes - all elements of shapes in the group, excluding split_connections. # add shapes to the list of groups, one by one. If not connected to existing groups, # new group is created. If connected, shape is added to groups, and the groups are joined. for shape in list_of_shapes: shape_elements = set([HashableShape(element) for element in element_extractor(shape)]) shape_elements.difference_update(split_connections) - #search if shape is connected to any groups + # search if shape is connected to any groups connected_to = [] not_in_connected_to = [] for iGroup in range(len(groups)): @@ -92,21 +101,21 @@ def splitIntoGroupsBySharing(list_of_shapes, element_extractor, split_connection not_in_connected_to.append(iGroup) # test if we need to join groups - if len(connected_to)>1: - #shape bridges a gap between some groups. Join them into one. - #rebuilding list of groups. First, add the new "supergroup", then add the rest + if len(connected_to) > 1: + # shape bridges a gap between some groups. Join them into one. + # rebuilding list of groups. First, add the new "supergroup", then add the rest groups_new = [] - supergroup = (list(),set()) + supergroup = (list(), set()) for iGroup in connected_to: - supergroup[0].extend( groups[iGroup][0] )# merge lists of shapes - supergroup[1].update( groups[iGroup][1] )# merge lists of elements + supergroup[0].extend(groups[iGroup][0]) # merge lists of shapes + supergroup[1].update(groups[iGroup][1]) # merge lists of elements groups_new.append(supergroup) l_groups = len(groups) - groups_new.extend([groups[i_group] \ - for i_group in not_in_connected_to \ - if i_group < l_groups]) + groups_new.extend( + [groups[i_group] for i_group in not_in_connected_to if i_group < l_groups] + ) groups = groups_new connected_to = [0] @@ -114,15 +123,18 @@ def splitIntoGroupsBySharing(list_of_shapes, element_extractor, split_connection if len(connected_to) > 0: iGroup = connected_to[0] groups[iGroup][0].append(shape) - groups[iGroup][1].update( shape_elements ) + groups[iGroup][1].update(shape_elements) else: newgroup = ([shape], shape_elements) groups.append(newgroup) # done. Discard unnecessary data and return result. - return [shapes for shapes,elements in groups] + return [shapes for shapes, elements in groups] -def mergeSolids(list_of_solids_compsolids, flag_single = False, split_connections = [], bool_compsolid = False): + +def mergeSolids( + list_of_solids_compsolids, flag_single=False, split_connections=[], bool_compsolid=False +): """mergeSolids(list_of_solids, flag_single = False): merges touching solids that share faces. If flag_single is True, it is assumed that all solids touch, and output is a single solid. If flag_single is False, the output is a compound containing all @@ -137,7 +149,7 @@ def mergeSolids(list_of_solids_compsolids, flag_single = False, split_connection cs = Part.CompSolid(solids) return cs if bool_compsolid else Part.makeSolid(cs) else: - if len(solids)==0: + if len(solids) == 0: return Part.Compound([]) groups = splitIntoGroupsBySharing(solids, lambda sh: sh.Faces, split_connections) if bool_compsolid: @@ -146,7 +158,8 @@ def mergeSolids(list_of_solids_compsolids, flag_single = False, split_connection merged_solids = [Part.makeSolid(Part.CompSolid(group)) for group in groups] return Part.makeCompound(merged_solids) -def mergeShells(list_of_faces_shells, flag_single = False, split_connections = []): + +def mergeShells(list_of_faces_shells, flag_single=False, split_connections=[]): faces = [] for sh in list_of_faces_shells: faces.extend(sh.Faces) @@ -156,7 +169,8 @@ def mergeShells(list_of_faces_shells, flag_single = False, split_connections = [ groups = splitIntoGroupsBySharing(faces, lambda sh: sh.Edges, split_connections) return Part.makeCompound([Part.makeShell(group) for group in groups]) -def mergeWires(list_of_edges_wires, flag_single = False, split_connections = []): + +def mergeWires(list_of_edges_wires, flag_single=False, split_connections=[]): edges = [] for sh in list_of_edges_wires: edges.extend(sh.Edges) @@ -166,11 +180,13 @@ def mergeWires(list_of_edges_wires, flag_single = False, split_connections = []) groups = splitIntoGroupsBySharing(edges, lambda sh: sh.Vertexes, split_connections) return Part.makeCompound([Part.Wire(Part.sortEdges(group)[0]) for group in groups]) -def mergeVertices(list_of_vertices, flag_single = False, split_connections = []): + +def mergeVertices(list_of_vertices, flag_single=False, split_connections=[]): # no comprehensive support, just following the footprint of other mergeXXX() return Part.makeCompound(removeDuplicates(list_of_vertices)) -def mergeShapes(list_of_shapes, flag_single = False, split_connections = [], bool_compsolid = False): + +def mergeShapes(list_of_shapes, flag_single=False, split_connections=[], bool_compsolid=False): """mergeShapes(list_of_shapes, flag_single = False, split_connections = [], bool_compsolid = False): merges list of edges/wires into wires, faces/shells into shells, solids/compsolids into solids or compsolids. @@ -189,7 +205,7 @@ def mergeShapes(list_of_shapes, flag_single = False, split_connections = [], boo compsolids are unified into single solids. If not merging solids/compsolids, this argument is ignored.""" - if len(list_of_shapes)==0: + if len(list_of_shapes) == 0: return Part.Compound([]) args = [list_of_shapes, flag_single, split_connections] dim = dimensionOfShapes(list_of_shapes) @@ -203,7 +219,8 @@ def mergeShapes(list_of_shapes, flag_single = False, split_connections = [], boo args.append(bool_compsolid) return mergeSolids(*args) else: - assert(dim >= 0 and dim <= 3) + assert dim >= 0 and dim <= 3 + def removeDuplicates(list_of_shapes): hashes = set() @@ -217,11 +234,12 @@ def removeDuplicates(list_of_shapes): hashes.add(hash) return new_list + def dimensionOfShapes(list_of_shapes): """dimensionOfShapes(list_of_shapes): returns dimension (0D, 1D, 2D, or 3D) of shapes in the list. If dimension of shapes varies, TypeError is raised.""" - dimensions = [["Vertex"], ["Edge","Wire"], ["Face","Shell"], ["Solid","CompSolid"]] + dimensions = [["Vertex"], ["Edge", "Wire"], ["Face", "Shell"], ["Solid", "CompSolid"]] dim = -1 for sh in list_of_shapes: sht = sh.ShapeType @@ -230,5 +248,9 @@ def dimensionOfShapes(list_of_shapes): if dim == -1: dim = iDim if iDim != dim: - raise TypeError("Shapes are of different dimensions ({t1} and {t2}), and cannot be merged or compared.".format(t1= list_of_shapes[0].ShapeType, t2= sht)) + raise TypeError( + "Shapes are of different dimensions ({t1} and {t2}), and cannot be merged or compared.".format( + t1=list_of_shapes[0].ShapeType, t2=sht + ) + ) return dim diff --git a/src/Mod/Part/BOPTools/SplitAPI.py b/src/Mod/Part/BOPTools/SplitAPI.py index a39f2fb8aa..42864deb11 100644 --- a/src/Mod/Part/BOPTools/SplitAPI.py +++ b/src/Mod/Part/BOPTools/SplitAPI.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,7 +22,7 @@ # * * # ***************************************************************************/ -__title__="BOPTools.SplitAPI module" +__title__ = "BOPTools.SplitAPI module" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" __doc__ = "Split functions that operate on list_of_shapes." @@ -33,7 +33,8 @@ from .GeneralFuseResult import GeneralFuseResult from . import Utils import FreeCAD -def booleanFragments(list_of_shapes, mode, tolerance = 0.0): + +def booleanFragments(list_of_shapes, mode, tolerance=0.0): """booleanFragments(list_of_shapes, mode, tolerance = 0.0): functional part of BooleanFragments feature. It's just result of generalFuse plus a bit of post-processing. @@ -52,16 +53,19 @@ def booleanFragments(list_of_shapes, mode, tolerance = 0.0): if len(solids) < 1: raise ValueError("No solids in the result. Can't make CompSolid.") elif len(solids) == 1: - FreeCAD.Console.PrintWarning("Part_BooleanFragments: only one solid in the result, generating trivial compsolid.") - return ShapeMerge.mergeSolids(solids, bool_compsolid= True) + FreeCAD.Console.PrintWarning( + "Part_BooleanFragments: only one solid in the result, generating trivial compsolid." + ) + return ShapeMerge.mergeSolids(solids, bool_compsolid=True) elif mode == "Split": - gr = GeneralFuseResult(list_of_shapes, (pieces,map)) + gr = GeneralFuseResult(list_of_shapes, (pieces, map)) gr.splitAggregates() return Part.makeCompound(gr.pieces) else: - raise ValueError("Unknown mode: {mode}".format(mode= mode)) + raise ValueError("Unknown mode: {mode}".format(mode=mode)) -def slice(base_shape, tool_shapes, mode, tolerance = 0.0): + +def slice(base_shape, tool_shapes, mode, tolerance=0.0): """slice(base_shape, tool_shapes, mode, tolerance = 0.0): functional part of Slice feature. Splits base_shape into pieces based on intersections with tool_shapes. @@ -71,11 +75,13 @@ def slice(base_shape, tool_shapes, mode, tolerance = 0.0): "Split" - wires and shells will be split at intersections, too. "CompSolid" - slice a solid and glue it back together to make a compsolid""" - shapes = [base_shape] + [Part.makeCompound([tool_shape]) for tool_shape in tool_shapes] # hack: putting tools into compounds will prevent contamination of result with pieces of tools + shapes = [base_shape] + [ + Part.makeCompound([tool_shape]) for tool_shape in tool_shapes + ] # hack: putting tools into compounds will prevent contamination of result with pieces of tools if len(shapes) < 2: raise ValueError("No slicing objects supplied!") pieces, map = shapes[0].generalFuse(shapes[1:], tolerance) - gr = GeneralFuseResult(shapes, (pieces,map)) + gr = GeneralFuseResult(shapes, (pieces, map)) result = None if mode == "Standard": result = gr.piecesFromSource(shapes[0]) @@ -84,8 +90,10 @@ def slice(base_shape, tool_shapes, mode, tolerance = 0.0): if len(solids) < 1: raise ValueError("No solids in the result. Can't make compsolid.") elif len(solids) == 1: - FreeCAD.Console.PrintWarning("Part_Slice: only one solid in the result, generating trivial compsolid.") - result = ShapeMerge.mergeSolids(solids, bool_compsolid= True).childShapes() + FreeCAD.Console.PrintWarning( + "Part_Slice: only one solid in the result, generating trivial compsolid." + ) + result = ShapeMerge.mergeSolids(solids, bool_compsolid=True).childShapes() elif mode == "Split": gr.splitAggregates(gr.piecesFromSource(shapes[0])) result = gr.piecesFromSource(shapes[0]) @@ -94,11 +102,12 @@ def slice(base_shape, tool_shapes, mode, tolerance = 0.0): else: return Part.Shape() -def xor(list_of_shapes, tolerance = 0.0): + +def xor(list_of_shapes, tolerance=0.0): """xor(list_of_shapes, tolerance = 0.0): boolean XOR operation.""" list_of_shapes = Utils.upgradeToAggregateIfNeeded(list_of_shapes) pieces, map = list_of_shapes[0].generalFuse(list_of_shapes[1:], tolerance) - gr = GeneralFuseResult(list_of_shapes, (pieces,map)) + gr = GeneralFuseResult(list_of_shapes, (pieces, map)) gr.explodeCompounds() gr.splitAggregates() pieces_to_keep = [] diff --git a/src/Mod/Part/BOPTools/SplitFeatures.py b/src/Mod/Part/BOPTools/SplitFeatures.py index 26f3b6bd21..05c8e08e29 100644 --- a/src/Mod/Part/BOPTools/SplitFeatures.py +++ b/src/Mod/Part/BOPTools/SplitFeatures.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,7 +22,7 @@ # * * # ***************************************************************************/ -__title__="BOPTools.SplitFeatures module" +__title__ = "BOPTools.SplitFeatures module" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" __doc__ = "Shape splitting document objects (features)." @@ -35,27 +35,31 @@ if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui -# -------------------------- translation-related code ------------------------- -# See forum thread "A new Part tool is being born... JoinFeatures!" -# https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 + # -------------------------- translation-related code ------------------------- + # See forum thread "A new Part tool is being born... JoinFeatures!" + # https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 try: _fromUtf8 = QtCore.QString.fromUtf8 except Exception: + def _fromUtf8(s): return s + translate = FreeCAD.Qt.translate -#--------------------------/translation-related code -------------------------- +# --------------------------/translation-related code -------------------------- def getIconPath(icon_dot_svg): return icon_dot_svg + # -------------------------- /common stuff ------------------------------------ # -------------------------- BooleanFragments --------------------------------- + def makeBooleanFragments(name): - '''makeBooleanFragments(name): makes an BooleanFragments object.''' + """makeBooleanFragments(name): makes an BooleanFragments object.""" obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureBooleanFragments(obj) if FreeCAD.GuiUp: @@ -66,33 +70,53 @@ def makeBooleanFragments(name): class FeatureBooleanFragments: """The BooleanFragments feature object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLinkList","Objects","BooleanFragments","Object to compute intersections between.", locked=True) - obj.addProperty("App::PropertyEnumeration","Mode","BooleanFragments", - "- Standard: wires, shells, compsolids remain in one piece.\n" - "- Split: wires, shells, compsolids are split.\n" - "- CompSolid: make compsolid from solid fragments.", locked=True) + def __init__(self, obj): + obj.addProperty( + "App::PropertyLinkList", + "Objects", + "BooleanFragments", + "Object to compute intersections between.", + locked=True, + ) + obj.addProperty( + "App::PropertyEnumeration", + "Mode", + "BooleanFragments", + "- Standard: wires, shells, compsolids remain in one piece.\n" + "- Split: wires, shells, compsolids are split.\n" + "- CompSolid: make compsolid from solid fragments.", + locked=True, + ) obj.Mode = ["Standard", "Split", "CompSolid"] - obj.addProperty("App::PropertyLength","Tolerance","BooleanFragments", - "Tolerance when intersecting (fuzzy value). " - "In addition to tolerances of the shapes.", locked=True) + obj.addProperty( + "App::PropertyLength", + "Tolerance", + "BooleanFragments", + "Tolerance when intersecting (fuzzy value). " + "In addition to tolerances of the shapes.", + locked=True, + ) obj.Proxy = self self.Type = "FeatureBooleanFragments" - def execute(self,selfobj): + def execute(self, selfobj): shapes = [obj.Shape for obj in selfobj.Objects] if len(shapes) == 1 and shapes[0].ShapeType == "Compound": shapes = shapes[0].childShapes() if len(shapes) < 2: - raise ValueError("At least two shapes are needed for computing boolean fragments. Got only {num}.".format(num=len(shapes))) + raise ValueError( + "At least two shapes are needed for computing boolean fragments. Got only {num}.".format( + num=len(shapes) + ) + ) selfobj.Shape = SplitAPI.booleanFragments(shapes, selfobj.Mode, selfobj.Tolerance) class ViewProviderBooleanFragments: """A View Provider for the Part BooleanFragments feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -105,7 +129,7 @@ class ViewProviderBooleanFragments: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -121,16 +145,21 @@ class ViewProviderBooleanFragments: def canDragObjects(self): return True + def canDropObjects(self): return True + def canDragObject(self, dragged_object): return True + def canDropObject(self, incoming_object): - return hasattr(incoming_object, 'Shape') + return hasattr(incoming_object, "Shape") + def dragObject(self, selfvp, dragged_object): objs = self.Object.Objects objs.remove(dragged_object) self.Object.Objects = objs + def dropObject(self, selfvp, incoming_object): self.Object.Objects = self.Object.Objects + [incoming_object] @@ -141,11 +170,15 @@ def cmdCreateBooleanFragmentsFeature(name, mode): sel = FreeCADGui.Selection.getSelectionEx() FreeCAD.ActiveDocument.openTransaction("Create Boolean Fragments") FreeCADGui.addModule("BOPTools.SplitFeatures") - FreeCADGui.doCommand("j = BOPTools.SplitFeatures.makeBooleanFragments(name='{name}')".format(name=name)) - FreeCADGui.doCommand("j.Objects = {sel}".format( - sel= "[" + ", ".join(["App.ActiveDocument."+so.Object.Name for so in sel]) + "]" - )) - FreeCADGui.doCommand("j.Mode = {mode}".format(mode= repr(mode))) + FreeCADGui.doCommand( + "j = BOPTools.SplitFeatures.makeBooleanFragments(name='{name}')".format(name=name) + ) + FreeCADGui.doCommand( + "j.Objects = {sel}".format( + sel="[" + ", ".join(["App.ActiveDocument." + so.Object.Name for so in sel]) + "]" + ) + ) + FreeCADGui.doCommand("j.Mode = {mode}".format(mode=repr(mode))) try: FreeCADGui.doCommand("j.Proxy.execute(j)") @@ -154,12 +187,17 @@ def cmdCreateBooleanFragmentsFeature(name, mode): mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) error_text1 = translate("Part_SplitFeatures", "Computing the result failed with an error:") - error_text2 = translate("Part_SplitFeatures", "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.") + error_text2 = translate( + "Part_SplitFeatures", + "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.", + ) mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate("Part_SplitFeatures","Continue",None), - QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("Part_SplitFeatures", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() @@ -168,8 +206,9 @@ def cmdCreateBooleanFragmentsFeature(name, mode): FreeCAD.ActiveDocument.abortTransaction() return - FreeCADGui.doCommand("for obj in j.ViewObject.Proxy.claimChildren():\n" - " obj.ViewObject.hide()") + FreeCADGui.doCommand( + "for obj in j.ViewObject.Proxy.claimChildren():\n" " obj.ViewObject.hide()" + ) FreeCAD.ActiveDocument.commitTransaction() @@ -178,11 +217,15 @@ class CommandBooleanFragments: """Command to create BooleanFragments feature.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_BooleanFragments.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_BooleanFragments","Boolean Fragments"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_BooleanFragments", - "Creates a boolean union which is sliced at the intersections of the selected shapes")} + return { + "Pixmap": getIconPath("Part_BooleanFragments.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_BooleanFragments", "Boolean Fragments"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_BooleanFragments", + "Creates a boolean union which is sliced at the intersections of the selected shapes", + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) >= 1: @@ -190,11 +233,16 @@ class CommandBooleanFragments: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_SplitFeatures", - "Select at least two objects, or one or more compounds. " - "If only one compound is selected, the compounded shapes will be intersected between each other " - "(otherwise, compounds with self-intersections are invalid).", None)) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_SplitFeatures", + "Select at least two objects, or one or more compounds. " + "If only one compound is selected, the compounded shapes will be intersected between each other " + "(otherwise, compounds with self-intersections are invalid).", + None, + ) + ) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -203,13 +251,15 @@ class CommandBooleanFragments: else: return False + # -------------------------- /BooleanFragments -------------------------------- # -------------------------- Slice -------------------------------------------- + def makeSlice(name): - '''makeSlice(name): makes an Slice object.''' - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name) + """makeSlice(name): makes an Slice object.""" + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureSlice(obj) if FreeCAD.GuiUp: ViewProviderSlice(obj.ViewObject) @@ -219,34 +269,48 @@ def makeSlice(name): class FeatureSlice: """The Slice feature object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLink","Base","Slice","Object to be sliced.", locked=True) - obj.addProperty("App::PropertyLinkList","Tools","Slice","Objects that slice.", locked=True) - obj.addProperty("App::PropertyEnumeration","Mode","Slice", - "- Standard: wires, shells, compsolids remain in one piece.\n" - "- Split: wires, shells, compsolids are split.\n" - "- CompSolid: make compsolid from solid fragments.", locked=True) + def __init__(self, obj): + obj.addProperty("App::PropertyLink", "Base", "Slice", "Object to be sliced.", locked=True) + obj.addProperty( + "App::PropertyLinkList", "Tools", "Slice", "Objects that slice.", locked=True + ) + obj.addProperty( + "App::PropertyEnumeration", + "Mode", + "Slice", + "- Standard: wires, shells, compsolids remain in one piece.\n" + "- Split: wires, shells, compsolids are split.\n" + "- CompSolid: make compsolid from solid fragments.", + locked=True, + ) obj.Mode = ["Standard", "Split", "CompSolid"] - obj.addProperty("App::PropertyLength","Tolerance","Slice", - "Tolerance when intersecting (fuzzy value). " - "In addition to tolerances of the shapes.", locked=True) + obj.addProperty( + "App::PropertyLength", + "Tolerance", + "Slice", + "Tolerance when intersecting (fuzzy value). " + "In addition to tolerances of the shapes.", + locked=True, + ) obj.Proxy = self self.Type = "FeatureSlice" - def execute(self,selfobj): + def execute(self, selfobj): if len(selfobj.Tools) < 1: raise ValueError("No slicing objects supplied!") - selfobj.Shape = SplitAPI.slice(selfobj.Base.Shape, - [obj.Shape for obj in selfobj.Tools], - selfobj.Mode, - selfobj.Tolerance) + selfobj.Shape = SplitAPI.slice( + selfobj.Base.Shape, + [obj.Shape for obj in selfobj.Tools], + selfobj.Mode, + selfobj.Tolerance, + ) class ViewProviderSlice: """A View Provider for the Part Slice feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -259,7 +323,7 @@ class ViewProviderSlice: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -273,18 +337,22 @@ class ViewProviderSlice: FreeCAD.Console.PrintError("Error in onDelete: " + str(err)) return True + def cmdCreateSliceFeature(name, mode, transaction=True): """cmdCreateSliceFeature(name, mode): implementation of GUI command to create Slice feature. Mode can be "Standard", "Split", or "CompSolid".""" sel = FreeCADGui.Selection.getSelectionEx() - if transaction: FreeCAD.ActiveDocument.openTransaction("Create Slice") + if transaction: + FreeCAD.ActiveDocument.openTransaction("Create Slice") FreeCADGui.addModule("BOPTools.SplitFeatures") FreeCADGui.doCommand("f = BOPTools.SplitFeatures.makeSlice(name='{name}')".format(name=name)) - FreeCADGui.doCommand("f.Base = {sel}[0]\n" - "f.Tools = {sel}[1:]".format( - sel= "[" + ", ".join(["App.ActiveDocument."+so.Object.Name for so in sel]) + "]" - )) - FreeCADGui.doCommand("f.Mode = {mode}".format(mode= repr(mode))) + FreeCADGui.doCommand( + "f.Base = {sel}[0]\n" + "f.Tools = {sel}[1:]".format( + sel="[" + ", ".join(["App.ActiveDocument." + so.Object.Name for so in sel]) + "]" + ) + ) + FreeCADGui.doCommand("f.Mode = {mode}".format(mode=repr(mode))) try: FreeCADGui.doCommand("f.Proxy.execute(f)") @@ -293,26 +361,35 @@ def cmdCreateSliceFeature(name, mode, transaction=True): mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) error_text1 = translate("Part_SplitFeatures", "Computing the result failed with an error:") - error_text2 = translate("Part_SplitFeatures", "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.") + error_text2 = translate( + "Part_SplitFeatures", + "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.", + ) mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate("Part_SplitFeatures","Continue",None), - QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("Part_SplitFeatures", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() if mb.clickedButton() is btnAbort: - if transaction: FreeCAD.ActiveDocument.abortTransaction() + if transaction: + FreeCAD.ActiveDocument.abortTransaction() return False - FreeCADGui.doCommand("for obj in f.ViewObject.Proxy.claimChildren():\n" - " obj.ViewObject.hide()") + FreeCADGui.doCommand( + "for obj in f.ViewObject.Proxy.claimChildren():\n" " obj.ViewObject.hide()" + ) - if transaction: FreeCAD.ActiveDocument.commitTransaction() + if transaction: + FreeCAD.ActiveDocument.commitTransaction() return True + def cmdSliceApart(): FreeCAD.ActiveDocument.openTransaction("Slice apart") made = cmdCreateSliceFeature(name="Slice", mode="Split", transaction=False) @@ -331,11 +408,15 @@ class CommandSlice: """Command to create Slice feature.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_Slice.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_Slice","Slice to Compound"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_Slice", - "Slices the selected object by using other objects as cutting tools and storing the results in one compound")} + return { + "Pixmap": getIconPath("Part_Slice.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_Slice", "Slice to Compound"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_Slice", + "Slices the selected object by using other objects as cutting tools and storing the results in one compound", + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) > 1: @@ -343,11 +424,16 @@ class CommandSlice: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_SplitFeatures", - "Select at least two objects. " - "The first one is the object to be sliced; " - "the rest are objects to slice with.", None)) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_SplitFeatures", + "Select at least two objects. " + "The first one is the object to be sliced; " + "the rest are objects to slice with.", + None, + ) + ) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -361,11 +447,15 @@ class CommandSliceApart: """Command to create exploded Slice feature.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_SliceApart.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_SliceApart","Slice Apart"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_SliceApart", - "Slices the selected object by other objects, and splits it apart, creating a compound filter for each slide")} + return { + "Pixmap": getIconPath("Part_SliceApart.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_SliceApart", "Slice Apart"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_SliceApart", + "Slices the selected object by other objects, and splits it apart, creating a compound filter for each slide", + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) > 1: @@ -373,11 +463,16 @@ class CommandSliceApart: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_SplitFeatures", - "Select at least two objects. " - "The first one is the object to be sliced; " - "the rest are objects to slice with.", None)) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_SplitFeatures", + "Select at least two objects. " + "The first one is the object to be sliced; " + "the rest are objects to slice with.", + None, + ) + ) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -386,13 +481,15 @@ class CommandSliceApart: else: return False + # -------------------------- /Slice ------------------------------------------- # -------------------------- XOR ---------------------------------------------- + def makeXOR(name): - '''makeXOR(name): makes an XOR object.''' - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name) + """makeXOR(name): makes an XOR object.""" + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureXOR(obj) if FreeCAD.GuiUp: ViewProviderXOR(obj.ViewObject) @@ -402,28 +499,43 @@ def makeXOR(name): class FeatureXOR: """The XOR feature object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLinkList","Objects","XOR","Object to compute intersections between.", locked=True) - obj.addProperty("App::PropertyLength","Tolerance","XOR", - "Tolerance when intersecting (fuzzy value). " - "In addition to tolerances of the shapes.", locked=True) + def __init__(self, obj): + obj.addProperty( + "App::PropertyLinkList", + "Objects", + "XOR", + "Object to compute intersections between.", + locked=True, + ) + obj.addProperty( + "App::PropertyLength", + "Tolerance", + "XOR", + "Tolerance when intersecting (fuzzy value). " + "In addition to tolerances of the shapes.", + locked=True, + ) obj.Proxy = self self.Type = "FeatureXOR" - def execute(self,selfobj): + def execute(self, selfobj): shapes = [obj.Shape for obj in selfobj.Objects] if len(shapes) == 1 and shapes[0].ShapeType == "Compound": shapes = shapes[0].childShapes() if len(shapes) < 2: - raise ValueError("At least two shapes are needed for computing XOR. Got only {num}.".format(num=len(shapes))) + raise ValueError( + "At least two shapes are needed for computing XOR. Got only {num}.".format( + num=len(shapes) + ) + ) selfobj.Shape = SplitAPI.xor(shapes, selfobj.Tolerance) class ViewProviderXOR: """A View Provider for the Part XOR feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -436,7 +548,7 @@ class ViewProviderXOR: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -452,16 +564,21 @@ class ViewProviderXOR: def canDragObjects(self): return True + def canDropObjects(self): return True + def canDragObject(self, dragged_object): return True + def canDropObject(self, incoming_object): - return hasattr(incoming_object, 'Shape') + return hasattr(incoming_object, "Shape") + def dragObject(self, selfvp, dragged_object): objs = self.Object.Objects objs.remove(dragged_object) self.Object.Objects = objs + def dropObject(self, selfvp, incoming_object): self.Object.Objects = self.Object.Objects + [incoming_object] @@ -473,9 +590,11 @@ def cmdCreateXORFeature(name): FreeCAD.ActiveDocument.openTransaction("Create Boolean XOR") FreeCADGui.addModule("BOPTools.SplitFeatures") FreeCADGui.doCommand("j = BOPTools.SplitFeatures.makeXOR(name='{name}')".format(name=name)) - FreeCADGui.doCommand("j.Objects = {sel}".format( - sel= "[" + ", ".join(["App.ActiveDocument."+so.Object.Name for so in sel]) + "]" - )) + FreeCADGui.doCommand( + "j.Objects = {sel}".format( + sel="[" + ", ".join(["App.ActiveDocument." + so.Object.Name for so in sel]) + "]" + ) + ) try: FreeCADGui.doCommand("j.Proxy.execute(j)") @@ -484,12 +603,17 @@ def cmdCreateXORFeature(name): mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) error_text1 = translate("Part_SplitFeatures", "Computing the result failed with an error:") - error_text2 = translate("Part_SplitFeatures", "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.") + error_text2 = translate( + "Part_SplitFeatures", + "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.", + ) mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate("Part_SplitFeatures","Continue",None), - QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("Part_SplitFeatures", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() @@ -498,8 +622,9 @@ def cmdCreateXORFeature(name): FreeCAD.ActiveDocument.abortTransaction() return - FreeCADGui.doCommand("for obj in j.ViewObject.Proxy.claimChildren():\n" - " obj.ViewObject.hide()") + FreeCADGui.doCommand( + "for obj in j.ViewObject.Proxy.claimChildren():\n" " obj.ViewObject.hide()" + ) FreeCAD.ActiveDocument.commitTransaction() @@ -508,13 +633,17 @@ class CommandXOR: """Command to create XOR feature.""" def GetResources(self): - return {'Pixmap': getIconPath("Part_XOR.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_XOR","Boolean XOR"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_XOR", - "Performs an 'exclusive OR' boolean operation with two or more selected objects,\n" - "or with the shapes inside a compound.\n" - "Overlapping volumes of the shapes will be removed.")} + return { + "Pixmap": getIconPath("Part_XOR.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_XOR", "Boolean XOR"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_XOR", + "Performs an 'exclusive OR' boolean operation with two or more selected objects,\n" + "or with the shapes inside a compound.\n" + "Overlapping volumes of the shapes will be removed.", + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) >= 1: @@ -522,11 +651,16 @@ class CommandXOR: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_SplitFeatures", - "Select at least two objects, or one or more compounds. " - "If only one compound is selected, the compounded shapes will be intersected between each other " - "(otherwise, compounds with self-intersections are invalid).", None)) - mb.setWindowTitle(translate("Part_SplitFeatures","Bad Selection", None)) + mb.setText( + translate( + "Part_SplitFeatures", + "Select at least two objects, or one or more compounds. " + "If only one compound is selected, the compounded shapes will be intersected between each other " + "(otherwise, compounds with self-intersections are invalid).", + None, + ) + ) + mb.setWindowTitle(translate("Part_SplitFeatures", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -535,10 +669,12 @@ class CommandXOR: else: return False + # -------------------------- /XOR --------------------------------------------- + def addCommands(): - FreeCADGui.addCommand('Part_BooleanFragments',CommandBooleanFragments()) - FreeCADGui.addCommand('Part_Slice',CommandSlice()) - FreeCADGui.addCommand('Part_SliceApart',CommandSliceApart()) - FreeCADGui.addCommand('Part_XOR',CommandXOR()) + FreeCADGui.addCommand("Part_BooleanFragments", CommandBooleanFragments()) + FreeCADGui.addCommand("Part_Slice", CommandSlice()) + FreeCADGui.addCommand("Part_SliceApart", CommandSliceApart()) + FreeCADGui.addCommand("Part_XOR", CommandXOR()) diff --git a/src/Mod/Part/BOPTools/ToleranceFeatures.py b/src/Mod/Part/BOPTools/ToleranceFeatures.py index f653533e71..8a3bff3de4 100644 --- a/src/Mod/Part/BOPTools/ToleranceFeatures.py +++ b/src/Mod/Part/BOPTools/ToleranceFeatures.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2024 Eric Price (CorvusCorax) * # * * # * * @@ -32,21 +32,26 @@ import Part if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui -# -------------------------- common stuff ------------------------------------- -# -------------------------- translation-related code ------------------------- + # -------------------------- common stuff ------------------------------------- + + # -------------------------- translation-related code ------------------------- try: _fromUtf8 = QtCore.QString.fromUtf8 except Exception: + def _fromUtf8(s): return s + translate = FreeCAD.Qt.translate # --------------------------/translation-related code ------------------------- def getParamRefine(): - return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool("RefineModel") + return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool( + "RefineModel" + ) def cmdCreateToleranceSetFeature(name, minTolerance=1e-7, maxTolerance=0): @@ -55,12 +60,16 @@ def cmdCreateToleranceSetFeature(name, minTolerance=1e-7, maxTolerance=0): FreeCAD.ActiveDocument.openTransaction("Create ToleranceSet") FreeCADGui.addModule("BOPTools.ToleranceFeatures") - FreeCADGui.doCommand("j = BOPTools.ToleranceFeatures.makeToleranceSet(name='{name}')".format(name=name)) + FreeCADGui.doCommand( + "j = BOPTools.ToleranceFeatures.makeToleranceSet(name='{name}')".format(name=name) + ) FreeCADGui.doCommand("j.minTolerance = {minTolerance}".format(minTolerance=minTolerance)) FreeCADGui.doCommand("j.maxTolerance = {maxTolerance}".format(maxTolerance=maxTolerance)) - FreeCADGui.doCommand("j.Objects = {sel}".format( - sel= "[" + ", ".join(["App.ActiveDocument."+so.Object.Name for so in sel]) + "]" - )) + FreeCADGui.doCommand( + "j.Objects = {sel}".format( + sel="[" + ", ".join(["App.ActiveDocument." + so.Object.Name for so in sel]) + "]" + ) + ) try: FreeCADGui.doCommand("j.Proxy.execute(j)") @@ -68,13 +77,20 @@ def cmdCreateToleranceSetFeature(name, minTolerance=1e-7, maxTolerance=0): except Exception as err: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - error_text1 = translate("Part_ToleranceFeatures", "Computing the result failed with an error:") - error_text2 = translate("Part_ToleranceFeatures", "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.") + error_text1 = translate( + "Part_ToleranceFeatures", "Computing the result failed with an error:" + ) + error_text2 = translate( + "Part_ToleranceFeatures", + "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.", + ) mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2) - mb.setWindowTitle(translate("Part_ToleranceFeatures","Bad Selection", None)) + mb.setWindowTitle(translate("Part_ToleranceFeatures", "Bad Selection", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate("Part_ToleranceFeatures","Continue",None), - QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("Part_ToleranceFeatures", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() @@ -82,8 +98,9 @@ def cmdCreateToleranceSetFeature(name, minTolerance=1e-7, maxTolerance=0): FreeCAD.ActiveDocument.abortTransaction() return - FreeCADGui.doCommand("for obj in j.ViewObject.Proxy.claimChildren():\n" - " obj.ViewObject.hide()") + FreeCADGui.doCommand( + "for obj in j.ViewObject.Proxy.claimChildren():\n" " obj.ViewObject.hide()" + ) FreeCAD.ActiveDocument.commitTransaction() @@ -91,13 +108,15 @@ def cmdCreateToleranceSetFeature(name, minTolerance=1e-7, maxTolerance=0): def getIconPath(icon_dot_svg): return icon_dot_svg + # -------------------------- /common stuff ------------------------------------ # -------------------------- Connect ------------------------------------------ + def makeToleranceSet(name): - '''makeToleranceSet(name): makes an ToleranceSet object.''' - obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython",name) + """makeToleranceSet(name): makes an ToleranceSet object.""" + obj = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", name) FeatureToleranceSet(obj) if FreeCAD.GuiUp: ViewProviderToleranceSet(obj.ViewObject) @@ -107,33 +126,46 @@ def makeToleranceSet(name): class FeatureToleranceSet: """The PartToleranceSetFeature object.""" - def __init__(self,obj): - obj.addProperty("App::PropertyLinkList","Objects","ToleranceSet","Objects to have tolerance adjusted.", locked=True) - obj.addProperty("App::PropertyBool","Refine","ToleranceSet", - "True = refine resulting shape. False = output as is.", locked=True) - obj.addProperty("App::PropertyLength","minTolerance","ToleranceSet", "0.1 nm", locked=True) - obj.addProperty("App::PropertyLength","maxTolerance","ToleranceSet", "0", locked=True) + def __init__(self, obj): + obj.addProperty( + "App::PropertyLinkList", + "Objects", + "ToleranceSet", + "Objects to have tolerance adjusted.", + locked=True, + ) + obj.addProperty( + "App::PropertyBool", + "Refine", + "ToleranceSet", + "True = refine resulting shape. False = output as is.", + locked=True, + ) + obj.addProperty( + "App::PropertyLength", "minTolerance", "ToleranceSet", "0.1 nm", locked=True + ) + obj.addProperty("App::PropertyLength", "maxTolerance", "ToleranceSet", "0", locked=True) obj.Refine = getParamRefine() obj.Proxy = self self.Type = "FeatureToleranceSet" def onDocumentRestored(self, obj): - if not hasattr(obj, 'maxTolerance'): - obj.addProperty("App::PropertyLength","maxTolerance","ToleranceSet", "0", locked=True) + if not hasattr(obj, "maxTolerance"): + obj.addProperty("App::PropertyLength", "maxTolerance", "ToleranceSet", "0", locked=True) - def execute(self,selfobj): + def execute(self, selfobj): shapes = [] for obj in selfobj.Objects: - sh = obj.Shape.copy(True,False) - sh.limitTolerance(selfobj.minTolerance,selfobj.maxTolerance) + sh = obj.Shape.copy(True, False) + sh.limitTolerance(selfobj.minTolerance, selfobj.maxTolerance) if selfobj.Refine: - sh.fix(selfobj.minTolerance,selfobj.minTolerance,selfobj.maxTolerance) + sh.fix(selfobj.minTolerance, selfobj.minTolerance, selfobj.maxTolerance) sh = sh.removeSplitter() - sh.fix(selfobj.minTolerance,selfobj.minTolerance,selfobj.maxTolerance) + sh.fix(selfobj.minTolerance, selfobj.minTolerance, selfobj.maxTolerance) shapes.append(sh) - if len(shapes)>1: + if len(shapes) > 1: rst = Part.makeCompound(shapes) else: rst = shapes[0] @@ -143,7 +175,7 @@ class FeatureToleranceSet: class ViewProviderToleranceSet: """A View Provider for the Part ToleranceSet feature.""" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -156,7 +188,7 @@ class ViewProviderToleranceSet: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None def claimChildren(self): @@ -172,16 +204,21 @@ class ViewProviderToleranceSet: def canDragObjects(self): return True + def canDropObjects(self): return True + def canDragObject(self, dragged_object): return True + def canDropObject(self, incoming_object): - return hasattr(incoming_object, 'Shape') + return hasattr(incoming_object, "Shape") + def dragObject(self, selfvp, dragged_object): objs = self.Object.Objects objs.remove(dragged_object) self.Object.Objects = objs + def dropObject(self, selfvp, incoming_object): self.Object.Objects = self.Object.Objects + [incoming_object] @@ -190,11 +227,15 @@ class CommandToleranceSet: """Command to create ToleranceSet feature.""" def GetResources(self): - return {'Pixmap': getIconPath("preferences-part_design.svg"), - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_ToleranceSet","Set Tolerance"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_ToleranceSet", - "Creates a parametric copy of the selected object with all contained tolerances set to at least a certain minimum value")} + return { + "Pixmap": getIconPath("preferences-part_design.svg"), + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_ToleranceSet", "Set Tolerance"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_ToleranceSet", + "Creates a parametric copy of the selected object with all contained tolerances set to at least a certain minimum value", + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelectionEx()) >= 1: @@ -202,9 +243,10 @@ class CommandToleranceSet: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_ToleranceSet", - "Select at least one object or compounds", None)) - mb.setWindowTitle(translate("Part_ToleranceSet","Bad Selection", None)) + mb.setText( + translate("Part_ToleranceSet", "Select at least one object or compounds", None) + ) + mb.setWindowTitle(translate("Part_ToleranceSet", "Bad Selection", None)) mb.exec_() def IsActive(self): @@ -213,8 +255,9 @@ class CommandToleranceSet: else: return False + # -------------------------- /Connect ----------------------------------------- def addCommands(): - FreeCADGui.addCommand('Part_ToleranceSet', CommandToleranceSet()) + FreeCADGui.addCommand("Part_ToleranceSet", CommandToleranceSet()) diff --git a/src/Mod/Part/BOPTools/Utils.py b/src/Mod/Part/BOPTools/Utils.py index 0ae140d76a..29c1cd4f5d 100644 --- a/src/Mod/Part/BOPTools/Utils.py +++ b/src/Mod/Part/BOPTools/Utils.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -22,13 +22,15 @@ # * * # ***************************************************************************/ -__title__="BOPTools.Utils module" +__title__ = "BOPTools.Utils module" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" __doc__ = "Utility code, used by various modules of BOPTools." + class HashableShape(object): "Decorator for Part.Shape, that can be used as key in dicts. Based on isSame method." + def __init__(self, shape): self.Shape = shape self.hash = shape.hashCode() @@ -39,15 +41,16 @@ class HashableShape(object): def __hash__(self): return self.hash + class HashableShape_Deep(object): """Similar to HashableShape, except that the things the shape is composed of are compared. -Example: - >>> wire2 = Part.Wire(wire1.childShapes()) - >>> wire2.isSame(wire1) - False # <--- the wire2 is a new wire, although made of edges of wire1 - >>> HashableShape_Deep(wire2) == HashableShape_Deep(wire1) - True # <--- made of same set of elements + Example: + >>> wire2 = Part.Wire(wire1.childShapes()) + >>> wire2.isSame(wire1) + False # <--- the wire2 is a new wire, although made of edges of wire1 + >>> HashableShape_Deep(wire2) == HashableShape_Deep(wire1) + True # <--- made of same set of elements """ def __init__(self, shape): @@ -67,6 +70,7 @@ Example: def __hash__(self): return self.hash + def compoundLeaves(shape_or_compound): """compoundLeaves(shape_or_compound): extracts all non-compound shapes from a nested compound. Note: shape_or_compound may be a non-compound; then, it is the only thing in the @@ -75,12 +79,13 @@ def compoundLeaves(shape_or_compound): if shape_or_compound.ShapeType == "Compound": leaves = [] for child in shape_or_compound.childShapes(): - leaves.extend( compoundLeaves(child) ) + leaves.extend(compoundLeaves(child)) return leaves else: return [shape_or_compound] -def upgradeToAggregateIfNeeded(list_of_shapes, types = None): + +def upgradeToAggregateIfNeeded(list_of_shapes, types=None): """upgradeToAggregateIfNeeded(list_of_shapes, types = None): upgrades non-aggregate type shapes to aggregate-type shapes if the list has a mix of aggregate and non-aggregate type shapes. Returns the new list. Recursively traverses into compounds. @@ -97,6 +102,7 @@ def upgradeToAggregateIfNeeded(list_of_shapes, types = None): 'types' argument is needed for recursive traversal. Do not supply.""" import Part + if types is None: types = set() for shape in list_of_shapes: @@ -105,22 +111,42 @@ def upgradeToAggregateIfNeeded(list_of_shapes, types = None): for subshape in subshapes: types.add(subshape.ShapeType) if "Wire" in types: - list_of_shapes = [(Part.Wire([shape]) if shape.ShapeType == "Edge" else shape) for shape in list_of_shapes] + list_of_shapes = [ + (Part.Wire([shape]) if shape.ShapeType == "Edge" else shape) for shape in list_of_shapes + ] if "Shell" in types: - list_of_shapes = [(Part.makeShell([shape]) if shape.ShapeType == "Face" else shape) for shape in list_of_shapes] + list_of_shapes = [ + (Part.makeShell([shape]) if shape.ShapeType == "Face" else shape) + for shape in list_of_shapes + ] if "CompSolid" in types: - list_of_shapes = [(Part.CompSolid([shape]) if shape.ShapeType == "Solid" else shape) for shape in list_of_shapes] + list_of_shapes = [ + (Part.CompSolid([shape]) if shape.ShapeType == "Solid" else shape) + for shape in list_of_shapes + ] if "Compound" in types: - list_of_shapes = [(Part.makeCompound(upgradeToAggregateIfNeeded(shape.childShapes(), types)) if shape.ShapeType == "Compound" else shape) for shape in list_of_shapes] + list_of_shapes = [ + ( + Part.makeCompound(upgradeToAggregateIfNeeded(shape.childShapes(), types)) + if shape.ShapeType == "Compound" + else shape + ) + for shape in list_of_shapes + ] return list_of_shapes + # adapted from http://stackoverflow.com/a/3603824/6285007 class FrozenClass(object): - '''FrozenClass: prevents adding new attributes to class outside of __init__''' + """FrozenClass: prevents adding new attributes to class outside of __init__""" + __isfrozen = False + def __setattr__(self, key, value): if self.__isfrozen and not hasattr(self, key): - raise TypeError( "{cls} has no attribute {attr}".format(cls= self.__class__.__name__, attr= key) ) + raise TypeError( + "{cls} has no attribute {attr}".format(cls=self.__class__.__name__, attr=key) + ) object.__setattr__(self, key, value) def _freeze(self): diff --git a/src/Mod/Part/BOPTools/__init__.py b/src/Mod/Part/BOPTools/__init__.py index 64cf134c78..8eafb89655 100644 --- a/src/Mod/Part/BOPTools/__init__.py +++ b/src/Mod/Part/BOPTools/__init__.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#/*************************************************************************** +# /*************************************************************************** # * Copyright (c) 2016 Victor Titov (DeepSOIC) * # * * # * This file is part of the FreeCAD CAx development system. * @@ -32,16 +32,17 @@ BOP-like operations""" # \ingroup PART __all__ = [ -"BOPFeatures", -"GeneralFuseResult", -"JoinAPI", -"JoinFeatures", -"ShapeMerge", -"Utils", -"SplitAPI", -"SplitFeatures", + "BOPFeatures", + "GeneralFuseResult", + "JoinAPI", + "JoinFeatures", + "ShapeMerge", + "Utils", + "SplitAPI", + "SplitFeatures", ] + def importAll(): "importAll(): imports all modules of BOPTools package" from . import BOPFeatures @@ -54,17 +55,19 @@ def importAll(): from . import SplitFeatures from . import ToleranceFeatures + def reloadAll(): "reloadAll(): reloads all modules of BOPTools package. Useful for debugging." for modstr in __all__: reload(globals()[modstr]) import FreeCAD + if FreeCAD.GuiUp: addCommands() + def addCommands(): "addCommands(): add all GUI commands of BOPTools package to FreeCAD command manager." JoinFeatures.addCommands() SplitFeatures.addCommands() ToleranceFeatures.addCommands() - diff --git a/src/Mod/Part/BasicShapes/CommandShapes.py b/src/Mod/Part/BasicShapes/CommandShapes.py index 6c2fbe1bd6..75a58bbb5a 100644 --- a/src/Mod/Part/BasicShapes/CommandShapes.py +++ b/src/Mod/Part/BasicShapes/CommandShapes.py @@ -39,23 +39,25 @@ import math import sys - class CommandTube: """Command for creating Tube.""" + def GetResources(self): - return {'MenuText': Qt.QT_TRANSLATE_NOOP("Part_Tube","Tube"), - 'Accel': "", - 'CmdType': "AlterDoc:Alter3DView:AlterSelection", - 'Pixmap': "Part_Tube_Parametric", - 'ToolTip': Qt.QT_TRANSLATE_NOOP("Part_Tube","Creates a tube")} + return { + "MenuText": Qt.QT_TRANSLATE_NOOP("Part_Tube", "Tube"), + "Accel": "", + "CmdType": "AlterDoc:Alter3DView:AlterSelection", + "Pixmap": "Part_Tube_Parametric", + "ToolTip": Qt.QT_TRANSLATE_NOOP("Part_Tube", "Creates a tube"), + } def Activated(self): text = FreeCAD.Qt.translate("QObject", "Create tube") FreeCAD.ActiveDocument.openTransaction(text) - tube = FreeCAD.ActiveDocument.addObject("Part::FeaturePython","Tube") + tube = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "Tube") Shapes.TubeFeature(tube) vp = ViewProviderShapes.ViewProviderTube(tube.ViewObject) - activePart = FreeCADGui.activeView().getActiveObject('part') + activePart = FreeCADGui.activeView().getActiveObject("part") if activePart: activePart.addObject(tube) FreeCAD.ActiveDocument.recompute() @@ -65,4 +67,4 @@ class CommandTube: return not FreeCAD.ActiveDocument is None -FreeCADGui.addCommand('Part_Tube', CommandTube()) +FreeCADGui.addCommand("Part_Tube", CommandTube()) diff --git a/src/Mod/Part/BasicShapes/ShapeContent.py b/src/Mod/Part/BasicShapes/ShapeContent.py index 5099c31b09..72d03de455 100644 --- a/src/Mod/Part/BasicShapes/ShapeContent.py +++ b/src/Mod/Part/BasicShapes/ShapeContent.py @@ -28,45 +28,15 @@ def buildShapeContent(objArg, decimals=2, advancedShapeContent=True): typeStr = str(shp.ShapeType) lbl = "" if obj.Name == obj.Label else " (" + obj.Label + ")" result = linkName + obj.Name + lbl + "\n" + result += translate("TaskCheckGeometryResults", "Shape type") + ": " + typeStr + "\n" result += ( - translate("TaskCheckGeometryResults", "Shape type") + ": " + typeStr + "\n" - ) - result += ( - translate("TaskCheckGeometryResults", "Vertices") - + ": " - + str(len(shp.Vertexes)) - + "\n" - ) - result += ( - translate("TaskCheckGeometryResults", "Edges") - + ": " - + str(len(shp.Edges)) - + "\n" - ) - result += ( - translate("TaskCheckGeometryResults", "Wires") - + ": " - + str(len(shp.Wires)) - + "\n" - ) - result += ( - translate("TaskCheckGeometryResults", "Faces") - + ": " - + str(len(shp.Faces)) - + "\n" - ) - result += ( - translate("TaskCheckGeometryResults", "Shells") - + ": " - + str(len(shp.Shells)) - + "\n" - ) - result += ( - translate("TaskCheckGeometryResults", "Solids") - + ": " - + str(len(shp.Solids)) - + "\n" + translate("TaskCheckGeometryResults", "Vertices") + ": " + str(len(shp.Vertexes)) + "\n" ) + result += translate("TaskCheckGeometryResults", "Edges") + ": " + str(len(shp.Edges)) + "\n" + result += translate("TaskCheckGeometryResults", "Wires") + ": " + str(len(shp.Wires)) + "\n" + result += translate("TaskCheckGeometryResults", "Faces") + ": " + str(len(shp.Faces)) + "\n" + result += translate("TaskCheckGeometryResults", "Shells") + ": " + str(len(shp.Shells)) + "\n" + result += translate("TaskCheckGeometryResults", "Solids") + ": " + str(len(shp.Solids)) + "\n" result += ( translate("TaskCheckGeometryResults", "CompSolids") + ": " @@ -74,10 +44,7 @@ def buildShapeContent(objArg, decimals=2, advancedShapeContent=True): + "\n" ) result += ( - translate("TaskCheckGeometryResults", "Compounds") - + ": " - + str(len(shp.Compounds)) - + "\n" + translate("TaskCheckGeometryResults", "Compounds") + ": " + str(len(shp.Compounds)) + "\n" ) result += ( translate("TaskCheckGeometryResults", "Shapes") @@ -168,9 +135,7 @@ def buildShapeContent(objArg, decimals=2, advancedShapeContent=True): if hasattr(shp, "normalAt"): try: result += ( - "normalAt(0): " - + str([round(vv, decimals) for vv in shp.normalAt(0)]) - + "\n" + "normalAt(0): " + str([round(vv, decimals) for vv in shp.normalAt(0)]) + "\n" ) except Exception: try: diff --git a/src/Mod/Part/BasicShapes/Shapes.py b/src/Mod/Part/BasicShapes/Shapes.py index 01ee953c9e..11e6f075c8 100644 --- a/src/Mod/Part/BasicShapes/Shapes.py +++ b/src/Mod/Part/BasicShapes/Shapes.py @@ -44,9 +44,15 @@ def makeTube(outerRadius, innerRadius, height): class TubeFeature: def __init__(self, obj): obj.Proxy = self - obj.addProperty("App::PropertyLength","OuterRadius","Tube","Outer radius", locked=True).OuterRadius = 5.0 - obj.addProperty("App::PropertyLength","InnerRadius","Tube","Inner radius", locked=True).InnerRadius = 2.0 - obj.addProperty("App::PropertyLength","Height","Tube", "Height of the tube", locked=True).Height = 10.0 + obj.addProperty( + "App::PropertyLength", "OuterRadius", "Tube", "Outer radius", locked=True + ).OuterRadius = 5.0 + obj.addProperty( + "App::PropertyLength", "InnerRadius", "Tube", "Inner radius", locked=True + ).InnerRadius = 2.0 + obj.addProperty( + "App::PropertyLength", "Height", "Tube", "Height of the tube", locked=True + ).Height = 10.0 obj.addExtension("Part::AttachExtensionPython") def execute(self, fp): @@ -62,5 +68,6 @@ def addTube(doc, name="Tube"): TubeFeature(obj) if FreeCAD.GuiUp: from . import ViewProviderShapes + ViewProviderShapes.ViewProviderTube(obj.ViewObject) return obj diff --git a/src/Mod/Part/BasicShapes/Utils.py b/src/Mod/Part/BasicShapes/Utils.py index 11260dd9d7..e3d8e67fd4 100644 --- a/src/Mod/Part/BasicShapes/Utils.py +++ b/src/Mod/Part/BasicShapes/Utils.py @@ -30,7 +30,8 @@ __doc__ = "Utilities for shapes" import Part -def makeCompoundFromPoints(geometry, distance = 1.0): + +def makeCompoundFromPoints(geometry, distance=1.0): """Get sampled points from geometry and create a compound.""" try: points = geometry.getPropertyOfGeometry().getPoints(distance)[0] @@ -38,7 +39,8 @@ def makeCompoundFromPoints(geometry, distance = 1.0): except AttributeError: return None -def showCompoundFromPoints(geometry, distance = 1.0): + +def showCompoundFromPoints(geometry, distance=1.0): """Create a compound from geometry and show it.""" try: compound = makeCompoundFromPoints(geometry, distance) diff --git a/src/Mod/Part/BasicShapes/ViewProviderShapes.py b/src/Mod/Part/BasicShapes/ViewProviderShapes.py index 9e334c487e..bee67afbf3 100644 --- a/src/Mod/Part/BasicShapes/ViewProviderShapes.py +++ b/src/Mod/Part/BasicShapes/ViewProviderShapes.py @@ -34,19 +34,22 @@ import FreeCADGui from PySide import QtGui + class ViewProviderTube: def __init__(self, obj): - ''' Set this object to the proxy object of the actual view provider ''' + """Set this object to the proxy object of the actual view provider""" obj.Proxy = self obj.addExtension("PartGui::ViewProviderAttachExtensionPython") obj.setIgnoreOverlayIcon(True, "PartGui::ViewProviderAttachExtensionPython") def attach(self, obj): - ''' Setup the scene sub-graph of the view provider, this method is mandatory ''' + """Setup the scene sub-graph of the view provider, this method is mandatory""" return def setupContextMenu(self, viewObject, menu): - action = menu.addAction(FreeCAD.Qt.translate("QObject", "Edit %1").replace("%1", viewObject.Object.Label)) + action = menu.addAction( + FreeCAD.Qt.translate("QObject", "Edit %1").replace("%1", viewObject.Object.Label) + ) action.triggered.connect(lambda: self.startDefaultEditMode(viewObject)) return False @@ -73,7 +76,7 @@ class ViewProviderTube: def dumps(self): return None - def loads(self,state): + def loads(self, state): return None @@ -95,9 +98,9 @@ class TaskTubeUI: self.form.tubeInnerRadius.valueChanged.connect(lambda x: self.onChangeInnerRadius(x)) self.form.tubeHeight.valueChanged.connect(lambda x: self.onChangeHeight(x)) - FreeCADGui.ExpressionBinding(self.form.tubeOuterRadius).bind(object,"OuterRadius") - FreeCADGui.ExpressionBinding(self.form.tubeInnerRadius).bind(object,"InnerRadius") - FreeCADGui.ExpressionBinding(self.form.tubeHeight).bind(object,"Height") + FreeCADGui.ExpressionBinding(self.form.tubeOuterRadius).bind(object, "OuterRadius") + FreeCADGui.ExpressionBinding(self.form.tubeInnerRadius).bind(object, "InnerRadius") + FreeCADGui.ExpressionBinding(self.form.tubeHeight).bind(object, "Height") def onChangeOuterRadius(self, radius): object = self.viewObject.Object diff --git a/src/Mod/Part/CompoundTools/CompoundFilter.py b/src/Mod/Part/CompoundTools/CompoundFilter.py index ec0ce88e44..adffa9d066 100644 --- a/src/Mod/Part/CompoundTools/CompoundFilter.py +++ b/src/Mod/Part/CompoundTools/CompoundFilter.py @@ -33,11 +33,11 @@ import math import sys -def makeCompoundFilter(name, into_group = None): - '''makeCompoundFilter(name): makes a CompoundFilter object.''' +def makeCompoundFilter(name, into_group=None): + """makeCompoundFilter(name): makes a CompoundFilter object.""" if into_group is None: into_group = FreeCAD.ActiveDocument - if into_group.isDerivedFrom('App::Document'): + if into_group.isDerivedFrom("App::Document"): obj = into_group.addObject("Part::FeaturePython", name) else: obj = into_group.newObject("Part::FeaturePython", name) @@ -51,40 +51,81 @@ class _CompoundFilter: """The CompoundFilter object.""" def __init__(self, obj): - obj.addProperty("App::PropertyLink", "Base", "CompoundFilter", "Compound to be filtered", locked=True) + obj.addProperty( + "App::PropertyLink", "Base", "CompoundFilter", "Compound to be filtered", locked=True + ) - obj.addProperty("App::PropertyEnumeration", - "FilterType", - "CompoundFilter", - "Type of filter method to use; some of these methods " - "require, or are affected by, a 'Stencil' object.", locked=True) - obj.FilterType = ['bypass', 'specific items', 'collision-pass', - 'window-volume', 'window-area', 'window-length', - 'window-distance'] - obj.FilterType = 'bypass' + obj.addProperty( + "App::PropertyEnumeration", + "FilterType", + "CompoundFilter", + "Type of filter method to use; some of these methods " + "require, or are affected by, a 'Stencil' object.", + locked=True, + ) + obj.FilterType = [ + "bypass", + "specific items", + "collision-pass", + "window-volume", + "window-area", + "window-length", + "window-distance", + ] + obj.FilterType = "bypass" # properties controlling "specific items" mode - obj.addProperty("App::PropertyString", "items", "CompoundFilter", - "Indices of the pieces to be returned.\n" - "These are numbers separated by a semicolon, '1;3;5'.\n" - "A range can also be provided using a colon, '1;4;8:10'.", locked=True) + obj.addProperty( + "App::PropertyString", + "items", + "CompoundFilter", + "Indices of the pieces to be returned.\n" + "These are numbers separated by a semicolon, '1;3;5'.\n" + "A range can also be provided using a colon, '1;4;8:10'.", + locked=True, + ) - obj.addProperty("App::PropertyLink", "Stencil", "CompoundFilter", - "Object that defines filtering", locked=True) + obj.addProperty( + "App::PropertyLink", + "Stencil", + "CompoundFilter", + "Object that defines filtering", + locked=True, + ) - obj.addProperty("App::PropertyFloat", "WindowFrom", "CompoundFilter", - "Value of threshold, expressed as a percentage of maximum value.", locked=True) + obj.addProperty( + "App::PropertyFloat", + "WindowFrom", + "CompoundFilter", + "Value of threshold, expressed as a percentage of maximum value.", + locked=True, + ) obj.WindowFrom = 80.0 - obj.addProperty("App::PropertyFloat", "WindowTo", "CompoundFilter", - "Value of threshold, expressed as a percentage of maximum value.", locked=True) + obj.addProperty( + "App::PropertyFloat", + "WindowTo", + "CompoundFilter", + "Value of threshold, expressed as a percentage of maximum value.", + locked=True, + ) obj.WindowTo = 100.0 - obj.addProperty("App::PropertyFloat", "OverrideMaxVal", "CompoundFilter", - "Volume threshold, expressed as percentage of the volume of largest child", locked=True) + obj.addProperty( + "App::PropertyFloat", + "OverrideMaxVal", + "CompoundFilter", + "Volume threshold, expressed as percentage of the volume of largest child", + locked=True, + ) obj.OverrideMaxVal = 0 - obj.addProperty("App::PropertyBool", "Invert", "CompoundFilter", - "Output shapes that are rejected by the filter, instead", locked=True) + obj.addProperty( + "App::PropertyBool", + "Invert", + "CompoundFilter", + "Output shapes that are rejected by the filter, instead", + locked=True, + ) obj.Invert = False self.Type = "CompoundFilter" @@ -94,36 +135,49 @@ class _CompoundFilter: # When operating on the object, it is to be treated as a lattice object. # If False, treat as a regular shape. if hasattr(obj, "isLattice"): - if 'On' in obj.isLattice: - print(obj.Name + " A generic shape is expected, but an array of placements was supplied. " - "It will be treated as a generic shape.\n") + if "On" in obj.isLattice: + print( + obj.Name + + " A generic shape is expected, but an array of placements was supplied. " + "It will be treated as a generic shape.\n" + ) rst = [] # variable to receive the final list of shapes shps = obj.Base.Shape.childShapes() - if obj.FilterType == 'bypass': + if obj.FilterType == "bypass": rst = shps - elif obj.FilterType == 'specific items': + elif obj.FilterType == "specific items": rst = [] flags = [False] * len(shps) if not obj.items: - raise ValueError("The 'items' property must have a number to use this filter: '{}'".format(obj.FilterType)) - ranges = obj.items.split(';') + raise ValueError( + "The 'items' property must have a number to use this filter: '{}'".format( + obj.FilterType + ) + ) + ranges = obj.items.split(";") for r in ranges: - r_v = r.split(':') + r_v = r.split(":") if len(r_v) == 1: try: i = int(r_v[0]) except ValueError: - raise ValueError("Make sure the 'item' does not have spaces; " - "a semicolon (;) can only appear between two numbers; " - "filter: '{}'".format(obj.FilterType)) + raise ValueError( + "Make sure the 'item' does not have spaces; " + "a semicolon (;) can only appear between two numbers; " + "filter: '{}'".format(obj.FilterType) + ) try: rst.append(shps[i]) - len(shps[i].ElementMap) # this calls flushElementMap on the c++ side, + len(shps[i].ElementMap) # this calls flushElementMap on the c++ side, # which allows for the element map to be usable # for later use. except IndexError: - raise ValueError("Item index '{}' is out of range for this filter: '{}'".format(i, obj.FilterType)) + raise ValueError( + "Item index '{}' is out of range for this filter: '{}'".format( + i, obj.FilterType + ) + ) flags[i] = True elif len(r_v) == 2 or len(r_v) == 3: if len(r_v) == 2: @@ -143,37 +197,42 @@ class _CompoundFilter: for i in range(len(shps)): if not flags[i]: rst.append(shps[i]) - elif obj.FilterType == 'collision-pass': + elif obj.FilterType == "collision-pass": if not obj.Stencil: - raise ValueError("A 'Stencil' object must be set to use this filter: '{}'".format(obj.FilterType)) + raise ValueError( + "A 'Stencil' object must be set to use this filter: '{}'".format(obj.FilterType) + ) stencil = obj.Stencil.Shape for s in shps: d = s.distToShape(stencil) if bool(d[0] < Part.Precision.confusion()) ^ bool(obj.Invert): rst.append(s) - elif obj.FilterType in ('window-volume', 'window-area', - 'window-length', 'window-distance'): + elif obj.FilterType in ("window-volume", "window-area", "window-length", "window-distance"): vals = [0.0] * len(shps) for i in range(len(shps)): - if obj.FilterType == 'window-volume': + if obj.FilterType == "window-volume": vals[i] = shps[i].Volume - elif obj.FilterType == 'window-area': + elif obj.FilterType == "window-area": vals[i] = shps[i].Area - elif obj.FilterType == 'window-length': + elif obj.FilterType == "window-length": vals[i] = shps[i].Length - elif obj.FilterType == 'window-distance': + elif obj.FilterType == "window-distance": if not obj.Stencil: - raise ValueError("A 'Stencil' object must be set to use this filter: '{}'".format(obj.FilterType)) + raise ValueError( + "A 'Stencil' object must be set to use this filter: '{}'".format( + obj.FilterType + ) + ) vals[i] = shps[i].distToShape(obj.Stencil.Shape)[0] maxval = max(vals) if obj.Stencil: - if obj.FilterType == 'window-volume': + if obj.FilterType == "window-volume": maxval = obj.Stencil.Shape.Volume - elif obj.FilterType == 'window-area': + elif obj.FilterType == "window-area": maxval = obj.Stencil.Shape.Area - elif obj.FilterType == 'window-length': + elif obj.FilterType == "window-length": maxval = obj.Stencil.Shape.Length if obj.OverrideMaxVal: maxval = obj.OverrideMaxVal @@ -197,7 +256,7 @@ class _CompoundFilter: obj.Shape = getNullShapeShape(scale) # Feeding empty compounds to FreeCAD seems to cause rendering issues, # otherwise it would have been a good idea to output nothing. - raise ValueError('Nothing passes through the filter') + raise ValueError("Nothing passes through the filter") if len(rst) > 1: obj.Shape = Part.makeCompound(rst) @@ -215,11 +274,14 @@ class _ViewProviderCompoundFilter: def __init__(self, vobj): vobj.Proxy = self - vobj.addProperty("App::PropertyBool", - "DontUnhideOnDelete", - "CompoundFilter", - "When this object is deleted, Base and Stencil are unhidden. " - "This flag stops it from happening.", locked=True) + vobj.addProperty( + "App::PropertyBool", + "DontUnhideOnDelete", + "CompoundFilter", + "When this object is deleted, Base and Stencil are unhidden. " + "This flag stops it from happening.", + locked=True, + ) vobj.setEditorMode("DontUnhideOnDelete", 2) # set hidden def getIcon(self): @@ -275,8 +337,8 @@ def getNullShapeShape(scale=1.0): if not _nullShapeShape: _nullShapeShape = Part.Shape() import os - shapePath = os.path.join(os.path.dirname(__file__), - "shapes", "empty-shape.brep") + + shapePath = os.path.join(os.path.dirname(__file__), "shapes", "empty-shape.brep") f = open(shapePath) _nullShapeShape.importBrep(f) f.close() diff --git a/src/Mod/Part/CompoundTools/Explode.py b/src/Mod/Part/CompoundTools/Explode.py index c09350d690..6ea7442bc3 100644 --- a/src/Mod/Part/CompoundTools/Explode.py +++ b/src/Mod/Part/CompoundTools/Explode.py @@ -5,34 +5,39 @@ import Part from .CompoundFilter import makeCompoundFilter -def explodeCompound(compound_obj, b_group = None): + +def explodeCompound(compound_obj, b_group=None): """explodeCompound(compound_obj, b_group = None): creates a bunch of compound filters, to extract every child of a compound into a separate object. group: if True, Group is always made. If False, group is never made. If None, group is made if there is more than one child. returns: (group_object, list_of_child_objects)""" - if (isinstance(compound_obj, FreeCAD.GeoFeature) and - isinstance(compound_obj.getPropertyOfGeometry(), Part.Shape)): + if isinstance(compound_obj, FreeCAD.GeoFeature) and isinstance( + compound_obj.getPropertyOfGeometry(), Part.Shape + ): sh = compound_obj.getPropertyOfGeometry() else: raise TypeError("Object must be App.GeoFeature with Part.Shape property") - n = len(sh.childShapes(False,False)) + n = len(sh.childShapes(False, False)) if b_group is None: b_group = n > 1 if b_group: - group = compound_obj.Document.addObject('App::DocumentObjectGroup','GrExplode_'+compound_obj.Name) - group.Label = 'Exploded {obj.Label}'.format(obj = compound_obj) + group = compound_obj.Document.addObject( + "App::DocumentObjectGroup", "GrExplode_" + compound_obj.Name + ) + group.Label = "Exploded {obj.Label}".format(obj=compound_obj) else: group = compound_obj.Document features_created = [] for i in range(0, n): - cf = makeCompoundFilter('{obj.Name}_child{child_num}'.format(obj = compound_obj, child_num = i), group) - cf.Label = '{obj.Label}.{child_num}'.format(obj = compound_obj, child_num = i) + cf = makeCompoundFilter( + "{obj.Name}_child{child_num}".format(obj=compound_obj, child_num=i), group + ) + cf.Label = "{obj.Label}.{child_num}".format(obj=compound_obj, child_num=i) cf.Base = compound_obj - cf.FilterType = 'specific items' + cf.FilterType = "specific items" cf.items = str(i) if cf.ViewObject is not None: cf.ViewObject.DontUnhideOnDelete = True features_created.append(cf) return (group, features_created) - diff --git a/src/Mod/Part/CompoundTools/_CommandCompoundFilter.py b/src/Mod/Part/CompoundTools/_CommandCompoundFilter.py index 17072f93d3..ce65064a49 100644 --- a/src/Mod/Part/CompoundTools/_CommandCompoundFilter.py +++ b/src/Mod/Part/CompoundTools/_CommandCompoundFilter.py @@ -28,48 +28,63 @@ __doc__ = "Compound Filter: remove some children from a compound (features)." import FreeCAD + if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui from PySide import QtCore - -# translation-related code -#(see forum thread "A new Part tool is being born... JoinFeatures!" -#https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 ) + # translation-related code + # (see forum thread "A new Part tool is being born... JoinFeatures!" + # https://forum.freecad.org/viewtopic.php?f=22&t=11112&start=30#p90239 ) try: _fromUtf8 = QtCore.QString.fromUtf8 except Exception: + def _fromUtf8(s): return s + translate = FreeCAD.Qt.translate # command class class _CommandCompoundFilter: "Command to create CompoundFilter feature" + def GetResources(self): - return {'Pixmap': "Part_CompoundFilter", - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_CompoundFilter", "Compound Filter"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_CompoundFilter", - "Filters out objects from the selected compound " - "by characteristics like volume,\n" - "area, or length, or by choosing specific items.\n" - "If a second object is selected, it will be used " - "as reference, for example,\n" - "for collision or distance filtering.")} + return { + "Pixmap": "Part_CompoundFilter", + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_CompoundFilter", "Compound Filter"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_CompoundFilter", + "Filters out objects from the selected compound " + "by characteristics like volume,\n" + "area, or length, or by choosing specific items.\n" + "If a second object is selected, it will be used " + "as reference, for example,\n" + "for collision or distance filtering.", + ), + } def Activated(self): - if len(FreeCADGui.Selection.getSelection()) == 1 or len(FreeCADGui.Selection.getSelection()) == 2: + if ( + len(FreeCADGui.Selection.getSelection()) == 1 + or len(FreeCADGui.Selection.getSelection()) == 2 + ): cmdCreateCompoundFilter(name="CompoundFilter") else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_CompoundFilter", - "First select a shape that is a compound. " - "If a second object is selected (optional) " - "it will be treated as a stencil.", None)) + mb.setText( + translate( + "Part_CompoundFilter", + "First select a shape that is a compound. " + "If a second object is selected (optional) " + "it will be treated as a stencil.", + None, + ) + ) mb.setWindowTitle(translate("Part_CompoundFilter", "Bad Selection", None)) mb.exec_() @@ -81,7 +96,7 @@ class _CommandCompoundFilter: if FreeCAD.GuiUp: - FreeCADGui.addCommand('Part_CompoundFilter', _CommandCompoundFilter()) + FreeCADGui.addCommand("Part_CompoundFilter", _CommandCompoundFilter()) # helper @@ -89,7 +104,9 @@ def cmdCreateCompoundFilter(name): sel = FreeCADGui.Selection.getSelection() FreeCAD.ActiveDocument.openTransaction("Create CompoundFilter") FreeCADGui.addModule("CompoundTools.CompoundFilter") - FreeCADGui.doCommand("f = CompoundTools.CompoundFilter.makeCompoundFilter(name = '" + name + "')") + FreeCADGui.doCommand( + "f = CompoundTools.CompoundFilter.makeCompoundFilter(name = '" + name + "')" + ) FreeCADGui.doCommand("f.Base = App.ActiveDocument." + sel[0].Name) if len(sel) == 2: FreeCADGui.doCommand("f.Stencil = App.ActiveDocument." + sel[1].Name) @@ -109,11 +126,17 @@ def cmdCreateCompoundFilter(name): mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) error_text1 = translate("Part_CompoundFilter", "Computing the result failed with an error:") - error_text2 = translate("Part_CompoundFilter", "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.") + error_text2 = translate( + "Part_CompoundFilter", + "Click 'Continue' to create the feature anyway, or 'Abort' to cancel.", + ) mb.setText(error_text1 + "\n\n" + str(err) + "\n\n" + error_text2) - mb.setWindowTitle(translate("Part_CompoundFilter","Bad Selection", None)) + mb.setWindowTitle(translate("Part_CompoundFilter", "Bad Selection", None)) btnAbort = mb.addButton(QtGui.QMessageBox.StandardButton.Abort) - btnOK = mb.addButton(translate("Part_SplitFeatures", "Continue", None), QtGui.QMessageBox.ButtonRole.ActionRole) + btnOK = mb.addButton( + translate("Part_SplitFeatures", "Continue", None), + QtGui.QMessageBox.ButtonRole.ActionRole, + ) mb.setDefaultButton(btnOK) mb.exec_() diff --git a/src/Mod/Part/CompoundTools/_CommandExplodeCompound.py b/src/Mod/Part/CompoundTools/_CommandExplodeCompound.py index 5e88d768c1..babc572a2f 100644 --- a/src/Mod/Part/CompoundTools/_CommandExplodeCompound.py +++ b/src/Mod/Part/CompoundTools/_CommandExplodeCompound.py @@ -24,35 +24,44 @@ __title__ = "CompoundTools._CommandExplodeCompound" __author__ = "DeepSOIC" __url__ = "https://www.freecad.org" -__doc__ = "ExplodeCompound: create a bunch of CompoundFilter objects to split a compound into pieces." +__doc__ = ( + "ExplodeCompound: create a bunch of CompoundFilter objects to split a compound into pieces." +) from .Explode import explodeCompound import FreeCAD + if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui from PySide import QtCore - -# translation-related code + # translation-related code try: _fromUtf8 = QtCore.QString.fromUtf8 except Exception: + def _fromUtf8(s): return s + translate = FreeCAD.Qt.translate # command class class _CommandExplodeCompound: "Command to explode a compound" + def GetResources(self): - return {'Pixmap': "Part_ExplodeCompound", - 'MenuText': QtCore.QT_TRANSLATE_NOOP("Part_ExplodeCompound", "Explode Compound"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("Part_ExplodeCompound", - "Splits up a compound of shapes into separate objects, creating a compound filter for each shape")} + return { + "Pixmap": "Part_ExplodeCompound", + "MenuText": QtCore.QT_TRANSLATE_NOOP("Part_ExplodeCompound", "Explode Compound"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "Part_ExplodeCompound", + "Splits up a compound of shapes into separate objects, creating a compound filter for each shape", + ), + } def Activated(self): if len(FreeCADGui.Selection.getSelection()) == 1: @@ -60,7 +69,9 @@ class _CommandExplodeCompound: else: mb = QtGui.QMessageBox() mb.setIcon(mb.Icon.Warning) - mb.setText(translate("Part_ExplodeCompound", "First select a shape that is a compound.", None)) + mb.setText( + translate("Part_ExplodeCompound", "First select a shape that is a compound.", None) + ) mb.setWindowTitle(translate("Part_ExplodeCompound", "Bad Selection", None)) mb.exec_() @@ -72,9 +83,7 @@ class _CommandExplodeCompound: if FreeCAD.GuiUp: - FreeCADGui.addCommand('Part_ExplodeCompound', _CommandExplodeCompound()) - - + FreeCADGui.addCommand("Part_ExplodeCompound", _CommandExplodeCompound()) def cmdExplode(): @@ -82,10 +91,15 @@ def cmdExplode(): try: sel = FreeCADGui.Selection.getSelectionEx() if len(sel) != 1: - raise ValueError("Bad selection","More than one object selected. You have selected {num} objects.".format(num= len(sel))) + raise ValueError( + "Bad selection", + "More than one object selected. You have selected {num} objects.".format( + num=len(sel) + ), + ) obj = sel[0].Object FreeCADGui.addModule("CompoundTools.Explode") - FreeCADGui.doCommand("input_obj = App.ActiveDocument."+obj.Name) + FreeCADGui.doCommand("input_obj = App.ActiveDocument." + obj.Name) FreeCADGui.doCommand("CompoundTools.Explode.explodeCompound(input_obj)") FreeCADGui.doCommand("input_obj.ViewObject.hide()") except Exception as ex: @@ -94,4 +108,3 @@ def cmdExplode(): FreeCAD.ActiveDocument.commitTransaction() FreeCADGui.doCommand("App.ActiveDocument.recompute()") - diff --git a/src/Mod/Part/Gui/AttacherTexts.cpp b/src/Mod/Part/Gui/AttacherTexts.cpp index 371317e4f9..7e48d00399 100644 --- a/src/Mod/Part/Gui/AttacherTexts.cpp +++ b/src/Mod/Part/Gui/AttacherTexts.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -32,7 +32,8 @@ using namespace Attacher; -namespace AttacherGui { +namespace AttacherGui +{ TextSet TwoStrings(QString str1, QString str2) { @@ -45,278 +46,799 @@ TextSet TwoStrings(QString str1, QString str2) TextSet getUIStrings(Base::Type attacherType, eMapMode mmode) { - if (attacherType.isDerivedFrom(AttachEngine3D::getClassTypeId())){ + if (attacherType.isDerivedFrom(AttachEngine3D::getClassTypeId())) { //---- coordinate system attacher ---- - switch (mmode){ - case mmDeactivated: - return TwoStrings(qApp->translate("Attacher3D", "Deactivated","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Attachment is disabled. Object can be moved by editing Placement property.","Attachment3D mode tooltip")); - case mmTranslate: - return TwoStrings(qApp->translate("Attacher3D", "Translate origin","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Origin is aligned to match Vertex. Orientation is controlled by Placement property.","Attachment3D mode tooltip")); - case mmObjectXY: - return TwoStrings(qApp->translate("Attacher3D", "Object's X Y Z","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Placement is made equal to Placement of linked object.","Attachment3D mode tooltip")); - case mmObjectXZ: - return TwoStrings(qApp->translate("Attacher3D", "Object's X Z Y","Attachment3D mode caption"), - qApp->translate("Attacher3D", "X', Y', Z' axes are matched with object's local X, Z, -Y, respectively.","Attachment3D mode tooltip")); - case mmObjectYZ: - return TwoStrings(qApp->translate("Attacher3D", "Object's Y Z X","Attachment3D mode caption"), - qApp->translate("Attacher3D", "X', Y', Z' axes are matched with object's local Y, Z, X, respectively.","Attachment3D mode tooltip")); - case mmParallelPlane: - return TwoStrings(qApp->translate("Attacher3D", "XY parallel to plane","Attachment3D mode caption"), - qApp->translate("Attacher3D", "X' Y' plane is parallel to the plane (object's XY) and passes through the vertex.","Attachment3D mode tooltip")); - case mmFlatFace: - return TwoStrings(qApp->translate("Attacher3D", "XY on plane","Attachment3D mode caption"), - qApp->translate("Attacher3D", "X' Y' plane is aligned to coincide planar face.","Attachment3D mode tooltip")); - case mmTangentPlane: - return TwoStrings(qApp->translate("Attacher3D", "XY tangent to surface","Attachment3D mode caption"), - qApp->translate("Attacher3D", "X' Y' plane is made tangent to surface at vertex.","Attachment3D mode tooltip")); - case mmNormalToPath: - return TwoStrings(qApp->translate("Attacher3D", "Z tangent to edge","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Z' axis is aligned to be tangent to edge. Optional vertex link defines where.","Attachment3D mode tooltip")); - case mmFrenetNB: - return TwoStrings(qApp->translate("Attacher3D", "Frenet NBT","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align to Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","Attachment3D mode tooltip")); - case mmFrenetTN: - return TwoStrings(qApp->translate("Attacher3D", "Frenet TNB","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align to Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","Attachment3D mode tooltip")); - case mmFrenetTB: - return TwoStrings(qApp->translate("Attacher3D", "Frenet TBN","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align to Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","Attachment3D mode tooltip")); - case mmConcentric: - return TwoStrings(qApp->translate("Attacher3D", "Concentric","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align XY-plane to osculating circle of an edge. Optional vertex link defines where.","Attachment3D mode tooltip")); - case mmRevolutionSection: - return TwoStrings(qApp->translate("Attacher3D", "Revolution Section","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align Y' axis to match axis of osculating circle of an edge. Optional vertex link defines where.","Attachment3D mode tooltip")); - case mmThreePointsPlane: - return TwoStrings(qApp->translate("Attacher3D", "XY-plane by 3 points","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align XY-plane to pass through three vertices.","Attachment3D mode tooltip")); - case mmThreePointsNormal: - return TwoStrings(qApp->translate("Attacher3D", "XZ-plane by 3 points","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Align XZ-plane to pass through 3 points; X axis will pass through two first points.","Attachment3D mode tooltip")); - case mmFolding: - return TwoStrings(qApp->translate("Attacher3D", "Folding","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Specialty mode for folding polyhedra. Select 4 edges in order: foldable edge, fold line, other fold line, other foldable edge. XY-plane will be aligned to folding the first edge.","Attachment3D mode tooltip")); - case mmInertialCS: - return TwoStrings(qApp->translate("Attacher3D", "Inertial CS","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Inertial coordinate system, constructed on principal axes of inertia and center of mass.","Attachment3D mode tooltip")); - case mmOZX: - return TwoStrings(qApp->translate("Attacher3D", "Align O-Z-X","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align Z' and X' axes towards vertex/along line.","Attachment3D mode tooltip")); - case mmOZY: - return TwoStrings(qApp->translate("Attacher3D", "Align O-Z-Y","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align Z' and Y' axes towards vertex/along line.","Attachment3D mode tooltip")); - case mmOXY: - return TwoStrings(qApp->translate("Attacher3D", "Align O-X-Y","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align X' and Y' axes towards vertex/along line.","Attachment3D mode tooltip")); - case mmOXZ: - return TwoStrings(qApp->translate("Attacher3D", "Align O-X-Z","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align X' and Z' axes towards vertex/along line.","Attachment3D mode tooltip")); - case mmOYZ: - return TwoStrings(qApp->translate("Attacher3D", "Align O-Y-Z","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align Y' and Z' axes towards vertex/along line.","Attachment3D mode tooltip")); - case mmOYX: - return TwoStrings(qApp->translate("Attacher3D", "Align O-Y-X","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align Y' and X' axes towards vertex/along line.","Attachment3D mode tooltip")); - default: - break; + switch (mmode) { + case mmDeactivated: + return TwoStrings( + qApp->translate("Attacher3D", "Deactivated", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Attachment is disabled. Object can be moved by editing Placement " + "property.", + "Attachment3D mode tooltip" + ) + ); + case mmTranslate: + return TwoStrings( + qApp->translate("Attacher3D", "Translate origin", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Origin is aligned to match Vertex. Orientation is controlled by Placement " + "property.", + "Attachment3D mode tooltip" + ) + ); + case mmObjectXY: + return TwoStrings( + qApp->translate("Attacher3D", "Object's X Y Z", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Placement is made equal to Placement of linked object.", + "Attachment3D mode tooltip" + ) + ); + case mmObjectXZ: + return TwoStrings( + qApp->translate("Attacher3D", "Object's X Z Y", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "X', Y', Z' axes are matched with object's local X, Z, -Y, respectively.", + "Attachment3D mode tooltip" + ) + ); + case mmObjectYZ: + return TwoStrings( + qApp->translate("Attacher3D", "Object's Y Z X", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "X', Y', Z' axes are matched with object's local Y, Z, X, respectively.", + "Attachment3D mode tooltip" + ) + ); + case mmParallelPlane: + return TwoStrings( + qApp->translate("Attacher3D", "XY parallel to plane", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "X' Y' plane is parallel to the plane (object's XY) and passes through the " + "vertex.", + "Attachment3D mode tooltip" + ) + ); + case mmFlatFace: + return TwoStrings( + qApp->translate("Attacher3D", "XY on plane", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "X' Y' plane is aligned to coincide planar face.", + "Attachment3D mode tooltip" + ) + ); + case mmTangentPlane: + return TwoStrings( + qApp->translate("Attacher3D", "XY tangent to surface", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "X' Y' plane is made tangent to surface at vertex.", + "Attachment3D mode tooltip" + ) + ); + case mmNormalToPath: + return TwoStrings( + qApp->translate("Attacher3D", "Z tangent to edge", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Z' axis is aligned to be tangent to edge. Optional vertex link defines " + "where.", + "Attachment3D mode tooltip" + ) + ); + case mmFrenetNB: + return TwoStrings( + qApp->translate("Attacher3D", "Frenet NBT", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align to Frenet-Serret coordinate system of curved edge. Optional vertex " + "link defines where.", + "Attachment3D mode tooltip" + ) + ); + case mmFrenetTN: + return TwoStrings( + qApp->translate("Attacher3D", "Frenet TNB", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align to Frenet-Serret coordinate system of curved edge. Optional vertex " + "link defines where.", + "Attachment3D mode tooltip" + ) + ); + case mmFrenetTB: + return TwoStrings( + qApp->translate("Attacher3D", "Frenet TBN", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align to Frenet-Serret coordinate system of curved edge. Optional vertex " + "link defines where.", + "Attachment3D mode tooltip" + ) + ); + case mmConcentric: + return TwoStrings( + qApp->translate("Attacher3D", "Concentric", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align XY-plane to osculating circle of an edge. Optional vertex link " + "defines where.", + "Attachment3D mode tooltip" + ) + ); + case mmRevolutionSection: + return TwoStrings( + qApp->translate("Attacher3D", "Revolution Section", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align Y' axis to match axis of osculating circle of an edge. Optional " + "vertex link defines where.", + "Attachment3D mode tooltip" + ) + ); + case mmThreePointsPlane: + return TwoStrings( + qApp->translate("Attacher3D", "XY-plane by 3 points", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align XY-plane to pass through three vertices.", + "Attachment3D mode tooltip" + ) + ); + case mmThreePointsNormal: + return TwoStrings( + qApp->translate("Attacher3D", "XZ-plane by 3 points", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Align XZ-plane to pass through 3 points; X axis will pass through two " + "first points.", + "Attachment3D mode tooltip" + ) + ); + case mmFolding: + return TwoStrings( + qApp->translate("Attacher3D", "Folding", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Specialty mode for folding polyhedra. Select 4 edges in order: foldable " + "edge, fold line, other fold line, other foldable edge. XY-plane will be " + "aligned to folding the first edge.", + "Attachment3D mode tooltip" + ) + ); + case mmInertialCS: + return TwoStrings( + qApp->translate("Attacher3D", "Inertial CS", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Inertial coordinate system, constructed on principal axes of inertia and " + "center of mass.", + "Attachment3D mode tooltip" + ) + ); + case mmOZX: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-Z-X", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align Z' and X' axes towards vertex/along " + "line.", + "Attachment3D mode tooltip" + ) + ); + case mmOZY: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-Z-Y", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align Z' and Y' axes towards vertex/along " + "line.", + "Attachment3D mode tooltip" + ) + ); + case mmOXY: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-X-Y", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align X' and Y' axes towards vertex/along " + "line.", + "Attachment3D mode tooltip" + ) + ); + case mmOXZ: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-X-Z", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align X' and Z' axes towards vertex/along " + "line.", + "Attachment3D mode tooltip" + ) + ); + case mmOYZ: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-Y-Z", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align Y' and Z' axes towards vertex/along " + "line.", + "Attachment3D mode tooltip" + ) + ); + case mmOYX: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-Y-X", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align Y' and X' axes towards vertex/along " + "line.", + "Attachment3D mode tooltip" + ) + ); + default: + break; } - } else if (attacherType.isDerivedFrom(AttachEnginePlane::getClassTypeId())){ + } + else if (attacherType.isDerivedFrom(AttachEnginePlane::getClassTypeId())) { //---- Plane/sketch attacher ---- - switch (mmode){ - case mmDeactivated: - return TwoStrings(qApp->translate("Attacher2D", "Deactivated","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Attachment is disabled. Object can be moved by editing Placement property.","AttachmentPlane mode tooltip")); - case mmTranslate: - return TwoStrings(qApp->translate("Attacher2D", "Translate origin","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Origin is aligned to match Vertex. Orientation is controlled by Placement property.","AttachmentPlane mode tooltip")); - case mmObjectXY: - return TwoStrings(qApp->translate("Attacher2D", "Object's XY","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is aligned to XY local plane of linked object.","AttachmentPlane mode tooltip")); - case mmObjectXZ: - return TwoStrings(qApp->translate("Attacher2D", "Object's XZ","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is aligned to XZ local plane of linked object.","AttachmentPlane mode tooltip")); - case mmObjectYZ: - return TwoStrings(qApp->translate("Attacher2D", "Object's YZ","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is aligned to YZ local plane of linked object.","AttachmentPlane mode tooltip")); - case mmParallelPlane: - return TwoStrings(qApp->translate("Attacher2D", "XY parallel to plane","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "X' Y' plane is parallel to the plane (object's XY) and passes through the vertex","AttachmentPlane mode tooltip")); - case mmFlatFace: - return TwoStrings(qApp->translate("Attacher2D", "Plane face","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is aligned to coincide planar face.","AttachmentPlane mode tooltip")); - case mmTangentPlane: - return TwoStrings(qApp->translate("Attacher2D", "Tangent to surface","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is made tangent to surface at vertex.","AttachmentPlane mode tooltip")); - case mmNormalToPath: - return TwoStrings(qApp->translate("Attacher2D", "Normal to edge","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is made tangent to edge. Optional vertex link defines where.","AttachmentPlane mode tooltip")); - case mmFrenetNB: - return TwoStrings(qApp->translate("Attacher2D", "Frenet NB","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Align to Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","AttachmentPlane mode tooltip")); - case mmFrenetTN: - return TwoStrings(qApp->translate("Attacher2D", "Frenet TN","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Align to Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","AttachmentPlane mode tooltip")); - case mmFrenetTB: - return TwoStrings(qApp->translate("Attacher2D", "Frenet TB","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Align to Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","AttachmentPlane mode tooltip")); - case mmConcentric: - return TwoStrings(qApp->translate("Attacher2D", "Concentric","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Align to plane to osculating circle of an edge. Origin is aligned to point of curvature. Optional vertex link defines where.","AttachmentPlane mode tooltip")); - case mmRevolutionSection: - return TwoStrings(qApp->translate("Attacher2D", "Revolution Section","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane is perpendicular to edge, and Y axis is matched with axis of osculating circle. Optional vertex link defines where.","AttachmentPlane mode tooltip")); - case mmThreePointsPlane: - return TwoStrings(qApp->translate("Attacher2D", "Plane by 3 points","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Align plane to pass through three vertices.","AttachmentPlane mode tooltip")); - case mmThreePointsNormal: - return TwoStrings(qApp->translate("Attacher2D", "Normal to 3 points","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane will pass through first two vertices, and perpendicular to plane that passes through three vertices.","AttachmentPlane mode tooltip")); - case mmFolding: - return TwoStrings(qApp->translate("Attacher2D", "Folding","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Specialty mode for folding polyhedra. Select 4 edges in order: foldable edge, fold line, other fold line, other foldable edge. Plane will be aligned to folding the first edge.","AttachmentPlane mode tooltip")); - case mmInertialCS: - return TwoStrings(qApp->translate("Attacher2D", "Inertia 2-3","AttachmentPlane mode caption"), - qApp->translate("Attacher2D", "Plane constructed on second and third principal axes of inertia (passes through center of mass).","AttachmentPlane mode tooltip")); - case mmOZX: - return TwoStrings(qApp->translate("Attacher3D", "Align O-N-X","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align normal and horizontal plane axis towards vertex/along line.","Attachment3D mode tooltip")); - case mmOZY: - return TwoStrings(qApp->translate("Attacher3D", "Align O-N-Y","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align normal and vertical plane axis towards vertex/along line.","Attachment3D mode tooltip")); - case mmOXY: - return TwoStrings(qApp->translate("Attacher3D", "Align O-X-Y","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align horizontal and vertical plane axes towards vertex/along line.","Attachment3D mode tooltip")); - case mmOXZ: - return TwoStrings(qApp->translate("Attacher3D", "Align O-X-N","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align horizontal plane axis and normal towards vertex/along line.","Attachment3D mode tooltip")); - case mmOYZ: - return TwoStrings(qApp->translate("Attacher3D", "Align O-Y-N","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align vertical plane axis and normal towards vertex/along line.","Attachment3D mode tooltip")); - case mmOYX: - return TwoStrings(qApp->translate("Attacher3D", "Align O-Y-X","Attachment3D mode caption"), - qApp->translate("Attacher3D", "Match origin with first Vertex. Align vertical and horizontal plane axes towards vertex/along line.","Attachment3D mode tooltip")); - default: - break; + switch (mmode) { + case mmDeactivated: + return TwoStrings( + qApp->translate("Attacher2D", "Deactivated", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Attachment is disabled. Object can be moved by editing Placement " + "property.", + "AttachmentPlane mode tooltip" + ) + ); + case mmTranslate: + return TwoStrings( + qApp->translate("Attacher2D", "Translate origin", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Origin is aligned to match Vertex. Orientation is controlled by Placement " + "property.", + "AttachmentPlane mode tooltip" + ) + ); + case mmObjectXY: + return TwoStrings( + qApp->translate("Attacher2D", "Object's XY", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is aligned to XY local plane of linked object.", + "AttachmentPlane mode tooltip" + ) + ); + case mmObjectXZ: + return TwoStrings( + qApp->translate("Attacher2D", "Object's XZ", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is aligned to XZ local plane of linked object.", + "AttachmentPlane mode tooltip" + ) + ); + case mmObjectYZ: + return TwoStrings( + qApp->translate("Attacher2D", "Object's YZ", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is aligned to YZ local plane of linked object.", + "AttachmentPlane mode tooltip" + ) + ); + case mmParallelPlane: + return TwoStrings( + qApp->translate("Attacher2D", "XY parallel to plane", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "X' Y' plane is parallel to the plane (object's XY) and passes through the " + "vertex", + "AttachmentPlane mode tooltip" + ) + ); + case mmFlatFace: + return TwoStrings( + qApp->translate("Attacher2D", "Plane face", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is aligned to coincide planar face.", + "AttachmentPlane mode tooltip" + ) + ); + case mmTangentPlane: + return TwoStrings( + qApp->translate("Attacher2D", "Tangent to surface", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is made tangent to surface at vertex.", + "AttachmentPlane mode tooltip" + ) + ); + case mmNormalToPath: + return TwoStrings( + qApp->translate("Attacher2D", "Normal to edge", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is made tangent to edge. Optional vertex link defines where.", + "AttachmentPlane mode tooltip" + ) + ); + case mmFrenetNB: + return TwoStrings( + qApp->translate("Attacher2D", "Frenet NB", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Align to Frenet-Serret coordinate system of curved edge. Optional vertex " + "link defines where.", + "AttachmentPlane mode tooltip" + ) + ); + case mmFrenetTN: + return TwoStrings( + qApp->translate("Attacher2D", "Frenet TN", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Align to Frenet-Serret coordinate system of curved edge. Optional vertex " + "link defines where.", + "AttachmentPlane mode tooltip" + ) + ); + case mmFrenetTB: + return TwoStrings( + qApp->translate("Attacher2D", "Frenet TB", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Align to Frenet-Serret coordinate system of curved edge. Optional vertex " + "link defines where.", + "AttachmentPlane mode tooltip" + ) + ); + case mmConcentric: + return TwoStrings( + qApp->translate("Attacher2D", "Concentric", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Align to plane to osculating circle of an edge. Origin is aligned to " + "point of curvature. Optional vertex link defines where.", + "AttachmentPlane mode tooltip" + ) + ); + case mmRevolutionSection: + return TwoStrings( + qApp->translate("Attacher2D", "Revolution Section", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane is perpendicular to edge, and Y axis is matched with axis of " + "osculating circle. Optional vertex link defines where.", + "AttachmentPlane mode tooltip" + ) + ); + case mmThreePointsPlane: + return TwoStrings( + qApp->translate("Attacher2D", "Plane by 3 points", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Align plane to pass through three vertices.", + "AttachmentPlane mode tooltip" + ) + ); + case mmThreePointsNormal: + return TwoStrings( + qApp->translate("Attacher2D", "Normal to 3 points", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane will pass through first two vertices, and perpendicular to plane " + "that passes through three vertices.", + "AttachmentPlane mode tooltip" + ) + ); + case mmFolding: + return TwoStrings( + qApp->translate("Attacher2D", "Folding", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Specialty mode for folding polyhedra. Select 4 edges in order: foldable " + "edge, fold line, other fold line, other foldable edge. Plane will be " + "aligned to folding the first edge.", + "AttachmentPlane mode tooltip" + ) + ); + case mmInertialCS: + return TwoStrings( + qApp->translate("Attacher2D", "Inertia 2-3", "AttachmentPlane mode caption"), + qApp->translate( + "Attacher2D", + "Plane constructed on second and third principal axes of inertia (passes " + "through center of mass).", + "AttachmentPlane mode tooltip" + ) + ); + case mmOZX: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-N-X", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align normal and horizontal plane axis " + "towards vertex/along line.", + "Attachment3D mode tooltip" + ) + ); + case mmOZY: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-N-Y", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align normal and vertical plane axis " + "towards vertex/along line.", + "Attachment3D mode tooltip" + ) + ); + case mmOXY: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-X-Y", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align horizontal and vertical plane axes " + "towards vertex/along line.", + "Attachment3D mode tooltip" + ) + ); + case mmOXZ: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-X-N", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align horizontal plane axis and normal " + "towards vertex/along line.", + "Attachment3D mode tooltip" + ) + ); + case mmOYZ: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-Y-N", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align vertical plane axis and normal " + "towards vertex/along line.", + "Attachment3D mode tooltip" + ) + ); + case mmOYX: + return TwoStrings( + qApp->translate("Attacher3D", "Align O-Y-X", "Attachment3D mode caption"), + qApp->translate( + "Attacher3D", + "Match origin with first Vertex. Align vertical and horizontal plane axes " + "towards vertex/along line.", + "Attachment3D mode tooltip" + ) + ); + default: + break; } - } else if (attacherType.isDerivedFrom(AttachEngineLine::getClassTypeId())){ + } + else if (attacherType.isDerivedFrom(AttachEngineLine::getClassTypeId())) { //---- Line attacher ---- - switch (mmode){ - case mmDeactivated: - return TwoStrings(qApp->translate("Attacher1D", "Deactivated","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Attachment is disabled. Line can be moved by editing Placement property.","AttachmentLine mode tooltip")); - case mm1AxisX: - return TwoStrings(qApp->translate("Attacher1D", "Object's X","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line is aligned along local X axis of object. Works on objects with placements, and ellipse/parabola/hyperbola edges.","AttachmentLine mode tooltip")); - case mm1AxisY: - return TwoStrings(qApp->translate("Attacher1D", "Object's Y","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line is aligned along local Y axis of object. Works on objects with placements, and ellipse/parabola/hyperbola edges.","AttachmentLine mode tooltip")); - case mm1AxisZ: - return TwoStrings(qApp->translate("Attacher1D", "Object's Z","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line is aligned along local X axis of object. Works on objects with placements, and ellipse/parabola/hyperbola edges.","AttachmentLine mode tooltip")); - case mm1AxisCurv: - return TwoStrings(qApp->translate("Attacher1D", "Axis of curvature","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line that is an axis of osculating circle of curved edge. Optional vertex defines where.","AttachmentLine mode tooltip")); - case mm1Directrix1: - return TwoStrings(qApp->translate("Attacher1D", "Directrix1","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Directrix line for ellipse, parabola, hyperbola.","AttachmentLine mode tooltip")); - case mm1Directrix2: - return TwoStrings(qApp->translate("Attacher1D", "Directrix2","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Second directrix line for ellipse and hyperbola.","AttachmentLine mode tooltip")); - case mm1Asymptote1: - return TwoStrings(qApp->translate("Attacher1D", "Asymptote1","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Asymptote of a hyperbola.","AttachmentLine mode tooltip")); - case mm1Asymptote2: - return TwoStrings(qApp->translate("Attacher1D", "Asymptote2","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Second asymptote of hyperbola.","AttachmentLine mode tooltip")); - case mm1Tangent: - return TwoStrings(qApp->translate("Attacher1D", "Tangent","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line tangent to an edge. Optional vertex link defines where.","AttachmentLine mode tooltip")); - case mm1Normal: - return TwoStrings(qApp->translate("Attacher1D", "Normal to edge","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Align to N vector of Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","AttachmentLine mode tooltip")); - case mm1Binormal: - return TwoStrings(qApp->translate("Attacher1D", "Binormal","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Align to B vector of Frenet-Serret coordinate system of curved edge. Optional vertex link defines where.","AttachmentLine mode tooltip")); - case mm1TangentU: - return TwoStrings(qApp->translate("Attacher1D", "Tangent to surface (U)","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Tangent to surface, along U parameter. Vertex link defines where.","AttachmentLine mode tooltip")); - case mm1TangentV: - return TwoStrings(qApp->translate("Attacher1D", "Tangent to surface (V)","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Tangent to surface, along U parameter. Vertex link defines where.","AttachmentLine mode tooltip")); - case mm1TwoPoints: - return TwoStrings(qApp->translate("Attacher1D", "Through two points","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line that passes through two vertices.","AttachmentLine mode tooltip")); - case mm1Intersection: - return TwoStrings(qApp->translate("Attacher1D", "Intersection","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Intersection of two faces.","AttachmentLine mode tooltip")); - case mm1Proximity: - return TwoStrings(qApp->translate("Attacher1D", "Proximity line","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line that spans the shortest distance between shapes.","AttachmentLine mode tooltip")); - case mm1AxisInertia1: - return TwoStrings(qApp->translate("Attacher1D", "1st principal axis","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line follows first principal axis of inertia.","AttachmentLine mode tooltip")); - case mm1AxisInertia2: - return TwoStrings(qApp->translate("Attacher1D", "2nd principal axis","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line follows second principal axis of inertia.","AttachmentLine mode tooltip")); - case mm1AxisInertia3: - return TwoStrings(qApp->translate("Attacher1D", "3rd principal axis","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line follows third principal axis of inertia.","AttachmentLine mode tooltip")); - case mm1FaceNormal: - return TwoStrings(qApp->translate("Attacher1D", "Normal to surface","AttachmentLine mode caption"), - qApp->translate("Attacher1D", "Line perpendicular to surface at point set by vertex.","AttachmentLine mode tooltip")); - default: - break; + switch (mmode) { + case mmDeactivated: + return TwoStrings( + qApp->translate("Attacher1D", "Deactivated", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Attachment is disabled. Line can be moved by editing Placement property.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisX: + return TwoStrings( + qApp->translate("Attacher1D", "Object's X", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line is aligned along local X axis of object. Works on objects with " + "placements, and ellipse/parabola/hyperbola edges.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisY: + return TwoStrings( + qApp->translate("Attacher1D", "Object's Y", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line is aligned along local Y axis of object. Works on objects with " + "placements, and ellipse/parabola/hyperbola edges.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisZ: + return TwoStrings( + qApp->translate("Attacher1D", "Object's Z", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line is aligned along local X axis of object. Works on objects with " + "placements, and ellipse/parabola/hyperbola edges.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisCurv: + return TwoStrings( + qApp->translate("Attacher1D", "Axis of curvature", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line that is an axis of osculating circle of curved edge. Optional vertex " + "defines where.", + "AttachmentLine mode tooltip" + ) + ); + case mm1Directrix1: + return TwoStrings( + qApp->translate("Attacher1D", "Directrix1", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Directrix line for ellipse, parabola, hyperbola.", + "AttachmentLine mode tooltip" + ) + ); + case mm1Directrix2: + return TwoStrings( + qApp->translate("Attacher1D", "Directrix2", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Second directrix line for ellipse and hyperbola.", + "AttachmentLine mode tooltip" + ) + ); + case mm1Asymptote1: + return TwoStrings( + qApp->translate("Attacher1D", "Asymptote1", "AttachmentLine mode caption"), + qApp->translate("Attacher1D", "Asymptote of a hyperbola.", "AttachmentLine mode tooltip") + ); + case mm1Asymptote2: + return TwoStrings( + qApp->translate("Attacher1D", "Asymptote2", "AttachmentLine mode caption"), + qApp->translate("Attacher1D", "Second asymptote of hyperbola.", "AttachmentLine mode tooltip") + ); + case mm1Tangent: + return TwoStrings( + qApp->translate("Attacher1D", "Tangent", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line tangent to an edge. Optional vertex link defines where.", + "AttachmentLine mode tooltip" + ) + ); + case mm1Normal: + return TwoStrings( + qApp->translate("Attacher1D", "Normal to edge", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Align to N vector of Frenet-Serret coordinate system of curved edge. " + "Optional vertex link defines where.", + "AttachmentLine mode tooltip" + ) + ); + case mm1Binormal: + return TwoStrings( + qApp->translate("Attacher1D", "Binormal", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Align to B vector of Frenet-Serret coordinate system of curved edge. " + "Optional vertex link defines where.", + "AttachmentLine mode tooltip" + ) + ); + case mm1TangentU: + return TwoStrings( + qApp->translate("Attacher1D", "Tangent to surface (U)", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Tangent to surface, along U parameter. Vertex link defines where.", + "AttachmentLine mode tooltip" + ) + ); + case mm1TangentV: + return TwoStrings( + qApp->translate("Attacher1D", "Tangent to surface (V)", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Tangent to surface, along U parameter. Vertex link defines where.", + "AttachmentLine mode tooltip" + ) + ); + case mm1TwoPoints: + return TwoStrings( + qApp->translate("Attacher1D", "Through two points", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line that passes through two vertices.", + "AttachmentLine mode tooltip" + ) + ); + case mm1Intersection: + return TwoStrings( + qApp->translate("Attacher1D", "Intersection", "AttachmentLine mode caption"), + qApp->translate("Attacher1D", "Intersection of two faces.", "AttachmentLine mode tooltip") + ); + case mm1Proximity: + return TwoStrings( + qApp->translate("Attacher1D", "Proximity line", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line that spans the shortest distance between shapes.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisInertia1: + return TwoStrings( + qApp->translate("Attacher1D", "1st principal axis", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line follows first principal axis of inertia.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisInertia2: + return TwoStrings( + qApp->translate("Attacher1D", "2nd principal axis", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line follows second principal axis of inertia.", + "AttachmentLine mode tooltip" + ) + ); + case mm1AxisInertia3: + return TwoStrings( + qApp->translate("Attacher1D", "3rd principal axis", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line follows third principal axis of inertia.", + "AttachmentLine mode tooltip" + ) + ); + case mm1FaceNormal: + return TwoStrings( + qApp->translate("Attacher1D", "Normal to surface", "AttachmentLine mode caption"), + qApp->translate( + "Attacher1D", + "Line perpendicular to surface at point set by vertex.", + "AttachmentLine mode tooltip" + ) + ); + default: + break; } - } else if (attacherType.isDerivedFrom(AttachEnginePoint::getClassTypeId())){ + } + else if (attacherType.isDerivedFrom(AttachEnginePoint::getClassTypeId())) { //---- Point attacher ---- - switch (mmode){ - case mmDeactivated: - return TwoStrings(qApp->translate("Attacher0D", "Deactivated","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Attachment is disabled. Point can be moved by editing Placement property.","AttachmentPoint mode tooltip")); - case mm0Origin: - return TwoStrings(qApp->translate("Attacher0D", "Object's origin","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Point is put at object's placement position. Works on objects with placements, and ellipse/parabola/hyperbola edges.","AttachmentPoint mode tooltip")); - case mm0Focus1: - return TwoStrings(qApp->translate("Attacher0D", "Focus1","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Focus of ellipse, parabola, hyperbola.","AttachmentPoint mode tooltip")); - case mm0Focus2: - return TwoStrings(qApp->translate("Attacher0D", "Focus2","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Second focus of ellipse and hyperbola.","AttachmentPoint mode tooltip")); - case mm0OnEdge: - return TwoStrings(qApp->translate("Attacher0D", "On edge","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Point is put on edge, MapPathParameter controls where. Additionally, vertex can be linked in for making a projection.","AttachmentPoint mode tooltip")); - case mm0CenterOfCurvature: - return TwoStrings(qApp->translate("Attacher0D", "Center of curvature","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Center of osculating circle of an edge. Optional vertex link defines where.","AttachmentPoint mode tooltip")); - case mm0CenterOfMass: - return TwoStrings(qApp->translate("Attacher0D", "Center of mass","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Center of mass of all references (equal densities are assumed).","AttachmentPoint mode tooltip")); - case mm0Intersection: - return TwoStrings(qApp->translate("Attacher0D", "Intersection","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Not implemented","AttachmentPoint mode tooltip")); - case mm0Vertex: - return TwoStrings(qApp->translate("Attacher0D", "Vertex","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Put Datum point coincident with another vertex.","AttachmentPoint mode tooltip")); - case mm0ProximityPoint1: - return TwoStrings(qApp->translate("Attacher0D", "Proximity point 1","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Point on first reference that is closest to second reference.","AttachmentPoint mode tooltip")); - case mm0ProximityPoint2: - return TwoStrings(qApp->translate("Attacher0D", "Proximity point 2","AttachmentPoint mode caption"), - qApp->translate("Attacher0D", "Point on second reference that is closest to first reference.","AttachmentPoint mode tooltip")); - default: - break; + switch (mmode) { + case mmDeactivated: + return TwoStrings( + qApp->translate("Attacher0D", "Deactivated", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Attachment is disabled. Point can be moved by editing Placement property.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0Origin: + return TwoStrings( + qApp->translate("Attacher0D", "Object's origin", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Point is put at object's placement position. Works on objects with " + "placements, and ellipse/parabola/hyperbola edges.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0Focus1: + return TwoStrings( + qApp->translate("Attacher0D", "Focus1", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Focus of ellipse, parabola, hyperbola.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0Focus2: + return TwoStrings( + qApp->translate("Attacher0D", "Focus2", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Second focus of ellipse and hyperbola.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0OnEdge: + return TwoStrings( + qApp->translate("Attacher0D", "On edge", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Point is put on edge, MapPathParameter controls where. Additionally, " + "vertex can be linked in for making a projection.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0CenterOfCurvature: + return TwoStrings( + qApp->translate("Attacher0D", "Center of curvature", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Center of osculating circle of an edge. Optional vertex link defines " + "where.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0CenterOfMass: + return TwoStrings( + qApp->translate("Attacher0D", "Center of mass", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Center of mass of all references (equal densities are assumed).", + "AttachmentPoint mode tooltip" + ) + ); + case mm0Intersection: + return TwoStrings( + qApp->translate("Attacher0D", "Intersection", "AttachmentPoint mode caption"), + qApp->translate("Attacher0D", "Not implemented", "AttachmentPoint mode tooltip") + ); + case mm0Vertex: + return TwoStrings( + qApp->translate("Attacher0D", "Vertex", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Put Datum point coincident with another vertex.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0ProximityPoint1: + return TwoStrings( + qApp->translate("Attacher0D", "Proximity point 1", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Point on first reference that is closest to second reference.", + "AttachmentPoint mode tooltip" + ) + ); + case mm0ProximityPoint2: + return TwoStrings( + qApp->translate("Attacher0D", "Proximity point 2", "AttachmentPoint mode caption"), + qApp->translate( + "Attacher0D", + "Point on second reference that is closest to first reference.", + "AttachmentPoint mode tooltip" + ) + ); + default: + break; } } - Base::Console().warning("No user-friendly string defined for this attachment mode and attacher type: %s %s \n",AttachEngine::getModeName(mmode).c_str(), attacherType.getName()); + Base::Console().warning( + "No user-friendly string defined for this attachment mode and attacher type: %s %s \n", + AttachEngine::getModeName(mmode).c_str(), + attacherType.getName() + ); return TwoStrings(QString::fromStdString(AttachEngine::getModeName(mmode)), QString()); } -//Note: this list must be in sync with eRefType enum -static struct { const char *txt; const char *comment; } eRefTypeStrings[] = { +// Note: this list must be in sync with eRefType enum +static struct +{ + const char* txt; + const char* comment; +} eRefTypeStrings[] = { QT_TRANSLATE_NOOP3("Attacher", "Any", "Attacher reference type"), QT_TRANSLATE_NOOP3("Attacher", "Vertex", "Attacher reference type"), QT_TRANSLATE_NOOP3("Attacher", "Edge", "Attacher reference type"), @@ -348,25 +870,29 @@ static struct { const char *txt; const char *comment; } eRefTypeStrings[] = { QString getShapeTypeText(eRefType type) { - //get rid of flags in type + // get rid of flags in type type = eRefType(type & (rtFlagHasPlacement - 1)); - if (type >= 0 && type < rtDummy_numberOfShapeTypes){ - if (eRefTypeStrings[int(type)].txt){ - return qApp->translate("Attacher", eRefTypeStrings[int(type)].txt, eRefTypeStrings[int(type)].comment); + if (type >= 0 && type < rtDummy_numberOfShapeTypes) { + if (eRefTypeStrings[int(type)].txt) { + return qApp->translate( + "Attacher", + eRefTypeStrings[int(type)].txt, + eRefTypeStrings[int(type)].comment + ); } } throw Base::TypeError("getShTypeText: type value is wrong, or a string is missing in the list"); } -QStringList getRefListForMode(AttachEngine &attacher, eMapMode mmode) +QStringList getRefListForMode(AttachEngine& attacher, eMapMode mmode) { refTypeStringList list = attacher.modeRefTypes[mmode]; QStringList strlist; - for(refTypeString &rts : list){ + for (refTypeString& rts : list) { QStringList buf; - for(eRefType rt : rts){ + for (eRefType rt : rts) { buf.append(getShapeTypeText(rt)); } strlist.append(buf.join(QStringLiteral(", "))); @@ -377,49 +903,55 @@ QStringList getRefListForMode(AttachEngine &attacher, eMapMode mmode) // --------------------Py interface--------------------- -PyObject* AttacherGuiPy::sGetModeStrings(PyObject * /*self*/, PyObject *args) +PyObject* AttacherGuiPy::sGetModeStrings(PyObject* /*self*/, PyObject* args) { int modeIndex = 0; char* attacherType; - if (!PyArg_ParseTuple(args, "si", &attacherType, &modeIndex)) + if (!PyArg_ParseTuple(args, "si", &attacherType, &modeIndex)) { return nullptr; + } try { Base::Type t = Base::Type::fromName(attacherType); - if (! t.isDerivedFrom(AttachEngine::getClassTypeId())){ + if (!t.isDerivedFrom(AttachEngine::getClassTypeId())) { std::stringstream ss; ss << "Object of this type is not derived from AttachEngine: "; ss << attacherType; throw Py::TypeError(ss.str()); } - TextSet strs = getUIStrings(t,eMapMode(modeIndex)); + TextSet strs = getUIStrings(t, eMapMode(modeIndex)); Py::List result; - for(QString &s : strs){ + for (QString& s : strs) { QByteArray ba_utf8 = s.toUtf8(); result.append(Py::String(ba_utf8.data(), "utf-8")); } return Py::new_reference_to(result); - } catch (const Py::Exception&) { + } + catch (const Py::Exception&) { return nullptr; - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { e.setPyException(); return nullptr; } } -PyObject* AttacherGuiPy::sGetRefTypeUserFriendlyName(PyObject * /*self*/, PyObject *args) +PyObject* AttacherGuiPy::sGetRefTypeUserFriendlyName(PyObject* /*self*/, PyObject* args) { int refTypeIndex = 0; - if (!PyArg_ParseTuple(args, "i", &refTypeIndex)) + if (!PyArg_ParseTuple(args, "i", &refTypeIndex)) { return nullptr; + } try { QByteArray ba_utf8 = getShapeTypeText(eRefType(refTypeIndex)).toUtf8(); return Py::new_reference_to(Py::String(ba_utf8.data(), "utf-8")); - } catch (const Py::Exception&) { + } + catch (const Py::Exception&) { return nullptr; - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { e.setPyException(); return nullptr; } @@ -427,12 +959,18 @@ PyObject* AttacherGuiPy::sGetRefTypeUserFriendlyName(PyObject * /*self*/, PyObje PyMethodDef AttacherGuiPy::Methods[] = { - {"getModeStrings", (PyCFunction) AttacherGuiPy::sGetModeStrings, METH_VARARGS, - "getModeStrings(attacher_type, mode_index) - gets mode user-friendly name and brief description."}, - {"getRefTypeUserFriendlyName", (PyCFunction) AttacherGuiPy::sGetRefTypeUserFriendlyName, METH_VARARGS, - "getRefTypeUserFriendlyName(type_index) - gets user-friendly name of AttachEngine's shape type."}, - {nullptr, nullptr, 0, nullptr} /* Sentinel */ + {"getModeStrings", + (PyCFunction)AttacherGuiPy::sGetModeStrings, + METH_VARARGS, + "getModeStrings(attacher_type, mode_index) - gets mode user-friendly name and brief " + "description."}, + {"getRefTypeUserFriendlyName", + (PyCFunction)AttacherGuiPy::sGetRefTypeUserFriendlyName, + METH_VARARGS, + "getRefTypeUserFriendlyName(type_index) - gets user-friendly name of AttachEngine's shape " + "type."}, + {nullptr, nullptr, 0, nullptr} /* Sentinel */ }; -} //namespace AttacherGui +} // namespace AttacherGui diff --git a/src/Mod/Part/Gui/AttacherTexts.h b/src/Mod/Part/Gui/AttacherTexts.h index 9ac0fcb94d..1a254a0ddb 100644 --- a/src/Mod/Part/Gui/AttacherTexts.h +++ b/src/Mod/Part/Gui/AttacherTexts.h @@ -23,9 +23,9 @@ ***************************************************************************/ /** - * AttacherTexts.h, .cpp - files that contain user-friendly translatable names - * of attachment modes, as well as help texts, and the like. - */ + * AttacherTexts.h, .cpp - files that contain user-friendly translatable names + * of attachment modes, as well as help texts, and the like. + */ #ifndef PARTATTACHERTEXTS_H #define PARTATTACHERTEXTS_H @@ -37,7 +37,8 @@ #include -namespace AttacherGui { +namespace AttacherGui +{ using TextSet = std::vector; @@ -54,16 +55,17 @@ TextSet PartGuiExport getUIStrings(Base::Type attacherType, Attacher::eMapMode m QString PartGuiExport getShapeTypeText(Attacher::eRefType type); -QStringList PartGuiExport getRefListForMode(Attacher::AttachEngine &attacher, Attacher::eMapMode mmode); +QStringList PartGuiExport getRefListForMode(Attacher::AttachEngine& attacher, Attacher::eMapMode mmode); // Python interface -class PartGuiExport AttacherGuiPy{ +class PartGuiExport AttacherGuiPy +{ public: - static PyMethodDef Methods[]; - static PyObject* sGetModeStrings(PyObject * /*self*/, PyObject *args); - static PyObject* sGetRefTypeUserFriendlyName(PyObject * /*self*/, PyObject *args); + static PyMethodDef Methods[]; + static PyObject* sGetModeStrings(PyObject* /*self*/, PyObject* args); + static PyObject* sGetRefTypeUserFriendlyName(PyObject* /*self*/, PyObject* args); }; -} +} // namespace AttacherGui #endif diff --git a/src/Mod/Part/Gui/BoxSelection.cpp b/src/Mod/Part/Gui/BoxSelection.cpp index 1450382488..b07c3f86c2 100644 --- a/src/Mod/Part/Gui/BoxSelection.cpp +++ b/src/Mod/Part/Gui/BoxSelection.cpp @@ -23,15 +23,15 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -51,20 +51,20 @@ using namespace PartGui; -class BoxSelection::FaceSelectionGate : public Gui::SelectionFilterGate +class BoxSelection::FaceSelectionGate: public Gui::SelectionFilterGate { public: FaceSelectionGate() : Gui::SelectionFilterGate() - { - } + {} ~FaceSelectionGate() override = default; - bool allow(App::Document*, App::DocumentObject*, const char*sSubName) override + bool allow(App::Document*, App::DocumentObject*, const char* sSubName) override { - if (Base::Tools::isNullOrEmpty(sSubName)) + if (Base::Tools::isNullOrEmpty(sSubName)) { return false; + } std::string element(sSubName); - return element.substr(0,4) == "Face"; + return element.substr(0, 4) == "Face"; } }; @@ -82,9 +82,9 @@ bool BoxSelection::isAutoDelete() const return autodelete; } -void BoxSelection::selectionCallback(void * ud, SoEventCallback * cb) +void BoxSelection::selectionCallback(void* ud, SoEventCallback* cb) { - Gui::View3DInventorViewer* view = static_cast(cb->getUserData()); + Gui::View3DInventorViewer* view = static_cast(cb->getUserData()); view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), selectionCallback, ud); view->setSelectionEnabled(true); @@ -102,8 +102,9 @@ void BoxSelection::selectionCallback(void * ud, SoEventCallback * cb) polygon.Add(Base::Vector2d(pt2[0], pt1[1])); } else { - for (const auto& it : picked) - polygon.Add(Base::Vector2d(it[0],it[1])); + for (const auto& it : picked) { + polygon.Add(Base::Vector2d(it[0], it[1])); + } } BoxSelection* self = static_cast(ud); @@ -114,10 +115,18 @@ void BoxSelection::selectionCallback(void * ud, SoEventCallback * cb) std::vector geom = doc->getObjectsOfType(); for (auto it : geom) { Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(it); - if (!vp->isVisible()) + if (!vp->isVisible()) { continue; + } const TopoDS_Shape& shape = it->Shape.getValue(); - self->addShapeToSelection(doc->getName(), it->getNameInDocument(), proj, polygon, shape, self->shapeEnum); + self->addShapeToSelection( + doc->getName(), + it->getNameInDocument(), + proj, + polygon, + shape, + self->shapeEnum + ); } view->redraw(); } @@ -132,27 +141,31 @@ void BoxSelection::selectionCallback(void * ud, SoEventCallback * cb) const char* BoxSelection::nameFromShapeType(TopAbs_ShapeEnum type) const { switch (type) { - case TopAbs_FACE: - return "Face"; - case TopAbs_EDGE: - return "Edge"; - case TopAbs_VERTEX: - return "Vertex"; - default: - return nullptr; + case TopAbs_FACE: + return "Face"; + case TopAbs_EDGE: + return "Edge"; + case TopAbs_VERTEX: + return "Vertex"; + default: + return nullptr; } } -void BoxSelection::addShapeToSelection(const char* doc, const char* obj, - const Gui::ViewVolumeProjection& proj, - const Base::Polygon2d& polygon, - const TopoDS_Shape& shape, - TopAbs_ShapeEnum subtype) +void BoxSelection::addShapeToSelection( + const char* doc, + const char* obj, + const Gui::ViewVolumeProjection& proj, + const Base::Polygon2d& polygon, + const TopoDS_Shape& shape, + TopAbs_ShapeEnum subtype +) { try { const char* subname = nameFromShapeType(subtype); - if (!subname) + if (!subname) { return; + } TopTools_IndexedMapOfShape M; TopExp_Explorer xp(shape, subtype); @@ -185,14 +198,16 @@ void BoxSelection::addShapeToSelection(const char* doc, const char* obj, void BoxSelection::start(TopAbs_ShapeEnum shape) { - Gui::View3DInventor* view = qobject_cast(Gui::getMainWindow()->activeWindow()); + Gui::View3DInventor* view = qobject_cast( + Gui::getMainWindow()->activeWindow() + ); if (view) { Gui::View3DInventorViewer* viewer = view->getViewer(); if (!viewer->isSelecting()) { viewer->startSelection(Gui::View3DInventorViewer::Rubberband); viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), selectionCallback, this); - // avoid that the selection node handles the event otherwise the callback function won't be - // called immediately + // avoid that the selection node handles the event otherwise the callback function won't + // be called immediately viewer->setSelectionEnabled(false); shapeEnum = shape; } diff --git a/src/Mod/Part/Gui/BoxSelection.h b/src/Mod/Part/Gui/BoxSelection.h index f134fd6362..4c69793750 100644 --- a/src/Mod/Part/Gui/BoxSelection.h +++ b/src/Mod/Part/Gui/BoxSelection.h @@ -31,16 +31,19 @@ class SoEventCallback; class TopoDS_Shape; -namespace Base { +namespace Base +{ class Polygon2d; } -namespace Gui { +namespace Gui +{ class View3DInventorViewer; class ViewVolumeProjection; -} +} // namespace Gui -namespace PartGui { +namespace PartGui +{ class BoxSelection { @@ -54,19 +57,22 @@ public: private: class FaceSelectionGate; - void addShapeToSelection(const char* doc, const char* obj, - const Gui::ViewVolumeProjection& proj, - const Base::Polygon2d& polygon, - const TopoDS_Shape& shape, - TopAbs_ShapeEnum subtype); + void addShapeToSelection( + const char* doc, + const char* obj, + const Gui::ViewVolumeProjection& proj, + const Base::Polygon2d& polygon, + const TopoDS_Shape& shape, + TopAbs_ShapeEnum subtype + ); const char* nameFromShapeType(TopAbs_ShapeEnum) const; - static void selectionCallback(void * ud, SoEventCallback * cb); + static void selectionCallback(void* ud, SoEventCallback* cb); private: - bool autodelete{false}; - TopAbs_ShapeEnum shapeEnum{TopAbs_SHAPE}; + bool autodelete {false}; + TopAbs_ShapeEnum shapeEnum {TopAbs_SHAPE}; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_BOXSELECTION_H +#endif // PARTGUI_BOXSELECTION_H diff --git a/src/Mod/Part/Gui/Command.cpp b/src/Mod/Part/Gui/Command.cpp index 5fd479a672..cd55e75dbb 100644 --- a/src/Mod/Part/Gui/Command.cpp +++ b/src/Mod/Part/Gui/Command.cpp @@ -23,12 +23,12 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -81,15 +81,15 @@ DEF_STD_CMD(CmdPartPickCurveNet) CmdPartPickCurveNet::CmdPartPickCurveNet() - :Command("Part_PickCurveNet") + : Command("Part_PickCurveNet") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Pick Curve Network"); - sToolTipText = QT_TR_NOOP("Picks a curve network"); - sWhatsThis = "Part_PickCurveNet"; - sStatusTip = sToolTipText; - sPixmap = "Test1"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Pick Curve Network"); + sToolTipText = QT_TR_NOOP("Picks a curve network"); + sWhatsThis = "Part_PickCurveNet"; + sStatusTip = sToolTipText; + sPixmap = "Test1"; } void CmdPartPickCurveNet::activated(int iMsg) @@ -103,21 +103,21 @@ void CmdPartPickCurveNet::activated(int iMsg) DEF_STD_CMD(CmdPartNewDoc) CmdPartNewDoc::CmdPartNewDoc() - :Command("Part_NewDoc") + : Command("Part_NewDoc") { - sAppModule = "Part"; - sGroup = "Part"; - sMenuText = "New Document"; - sToolTipText = "Creates an Empty Part Document"; - sWhatsThis = "Part_NewDoc"; - sStatusTip = sToolTipText; - sPixmap = "New"; + sAppModule = "Part"; + sGroup = "Part"; + sMenuText = "New Document"; + sToolTipText = "Creates an Empty Part Document"; + sWhatsThis = "Part_NewDoc"; + sStatusTip = sToolTipText; + sPixmap = "New"; } void CmdPartNewDoc::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Doc,"d = App.New()"); + doCommand(Doc, "d = App.New()"); updateActive(); } @@ -127,39 +127,41 @@ void CmdPartNewDoc::activated(int iMsg) DEF_STD_CMD_A(CmdPartBox2) CmdPartBox2::CmdPartBox2() - :Command("Part_Box2") + : Command("Part_Box2") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Box Fix 1"); - sToolTipText = QT_TR_NOOP("Creates a solid box"); - sWhatsThis = "Part_Box2"; - sStatusTip = sToolTipText; - sPixmap = "Part_Box_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Box Fix 1"); + sToolTipText = QT_TR_NOOP("Creates a solid box"); + sWhatsThis = "Part_Box2"; + sStatusTip = sToolTipText; + sPixmap = "Part_Box_Parametric"; } void CmdPartBox2::activated(int iMsg) { Q_UNUSED(iMsg); openCommand(QT_TRANSLATE_NOOP("Command", "Part Box Create")); - doCommand(Doc,"from FreeCAD import Base"); - doCommand(Doc,"import Part"); - doCommand(Doc,"__fb__ = App.ActiveDocument.addObject(\"Part::Box\",\"PartBox\")"); - doCommand(Doc,"__fb__.Location = Base.Vector(0.0,0.0,0.0)"); - doCommand(Doc,"__fb__.Length = 100.0"); - doCommand(Doc,"__fb__.Width = 100.0"); - doCommand(Doc,"__fb__.Height = 100.0"); - doCommand(Doc,"del __fb__"); + doCommand(Doc, "from FreeCAD import Base"); + doCommand(Doc, "import Part"); + doCommand(Doc, "__fb__ = App.ActiveDocument.addObject(\"Part::Box\",\"PartBox\")"); + doCommand(Doc, "__fb__.Location = Base.Vector(0.0,0.0,0.0)"); + doCommand(Doc, "__fb__.Length = 100.0"); + doCommand(Doc, "__fb__.Width = 100.0"); + doCommand(Doc, "__fb__.Height = 100.0"); + doCommand(Doc, "del __fb__"); commitCommand(); updateActive(); } bool CmdPartBox2::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -168,39 +170,41 @@ bool CmdPartBox2::isActive() DEF_STD_CMD_A(CmdPartBox3) CmdPartBox3::CmdPartBox3() - :Command("Part_Box3") + : Command("Part_Box3") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Box Fix 2"); - sToolTipText = QT_TR_NOOP("Creates a solid box"); - sWhatsThis = "Part_Box3"; - sStatusTip = sToolTipText; - sPixmap = "Part_Box_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Box Fix 2"); + sToolTipText = QT_TR_NOOP("Creates a solid box"); + sWhatsThis = "Part_Box3"; + sStatusTip = sToolTipText; + sPixmap = "Part_Box_Parametric"; } void CmdPartBox3::activated(int iMsg) { Q_UNUSED(iMsg); openCommand(QT_TRANSLATE_NOOP("Command", "Part Box Create")); - doCommand(Doc,"from FreeCAD import Base"); - doCommand(Doc,"import Part"); - doCommand(Doc,"__fb__ = App.ActiveDocument.addObject(\"Part::Box\",\"PartBox\")"); - doCommand(Doc,"__fb__.Location = Base.Vector(50.0,50.0,50.0)"); - doCommand(Doc,"__fb__.Length = 100.0"); - doCommand(Doc,"__fb__.Width = 100.0"); - doCommand(Doc,"__fb__.Height = 100.0"); - doCommand(Doc,"del __fb__"); + doCommand(Doc, "from FreeCAD import Base"); + doCommand(Doc, "import Part"); + doCommand(Doc, "__fb__ = App.ActiveDocument.addObject(\"Part::Box\",\"PartBox\")"); + doCommand(Doc, "__fb__.Location = Base.Vector(50.0,50.0,50.0)"); + doCommand(Doc, "__fb__.Length = 100.0"); + doCommand(Doc, "__fb__.Width = 100.0"); + doCommand(Doc, "__fb__.Height = 100.0"); + doCommand(Doc, "del __fb__"); commitCommand(); updateActive(); } bool CmdPartBox3::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -209,16 +213,16 @@ bool CmdPartBox3::isActive() DEF_STD_CMD_A(CmdPartPrimitives) CmdPartPrimitives::CmdPartPrimitives() - :Command("Part_Primitives") + : Command("Part_Primitives") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Primitive"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Primitive"); - sToolTipText = QT_TR_NOOP("Creates solid geometric primitives parametrically"); - sWhatsThis = "Part_Primitives"; - sStatusTip = sToolTipText; - sPixmap = "Part_Primitives"; + sToolTipText = QT_TR_NOOP("Creates solid geometric primitives parametrically"); + sWhatsThis = "Part_Primitives"; + sStatusTip = sToolTipText; + sPixmap = "Part_Primitives"; } void CmdPartPrimitives::activated(int iMsg) @@ -233,7 +237,8 @@ bool CmdPartPrimitives::isActive() return (hasActiveDocument() && !Gui::Control().activeDialog()); } -namespace PartGui { +namespace PartGui +{ bool checkForSolids(const TopoDS_Shape& shape) { TopExp_Explorer xp; @@ -262,11 +267,16 @@ bool checkForSolids(const TopoDS_Shape& shape) */ std::vector getShapesFromSelection() { - std::vector objs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); - std::vector shapes; + std::vector objs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); + std::vector shapes; for (auto it : objs) { - Part::TopoShape shp = Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); - if (!shp.isNull()){ + Part::TopoShape shp = Part::Feature::getTopoShape( + it, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); + if (!shp.isNull()) { shapes.push_back(shp); } } @@ -279,7 +289,9 @@ std::vector getShapesFromSelection() bool hasShapesInSelection() { bool hasShapes = false; - std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); for (auto it : docobjs) { if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink).isNull()) { hasShapes = true; @@ -288,7 +300,7 @@ bool hasShapesInSelection() } return hasShapes; } -} +} // namespace PartGui //=========================================================================== // Part_Cut @@ -296,39 +308,56 @@ bool hasShapesInSelection() DEF_STD_CMD_A(CmdPartCut) CmdPartCut::CmdPartCut() - :Command("Part_Cut") + : Command("Part_Cut") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Cut"); - sToolTipText = QT_TR_NOOP("Cuts 2 selected shapes"); - sWhatsThis = "Part_Cut"; - sStatusTip = sToolTipText; - sPixmap = "Part_Cut"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Cut"); + sToolTipText = QT_TR_NOOP("Cuts 2 selected shapes"); + sWhatsThis = "Part_Cut"; + sStatusTip = sToolTipText; + sPixmap = "Part_Cut"; } void CmdPartCut::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector Sel = - getSelection().getSelectionEx(nullptr, App::DocumentObject::getClassTypeId(), Gui::ResolveMode::FollowLink); + std::vector Sel = getSelection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::FollowLink + ); if (Sel.size() != 2) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select 2 shapes")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select 2 shapes") + ); return; } bool askUser = false; std::vector names; - for (const auto & it : Sel) { + for (const auto& it : Sel) { const App::DocumentObject* obj = it.getObject(); - const TopoDS_Shape& shape = Part::Feature::getShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + const TopoDS_Shape& shape = Part::Feature::getShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!PartGui::checkForSolids(shape) && !askUser) { - int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), - QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" - "Continue?"), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::No) + int ret = QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Non-solids selected"), + QObject::tr( + "The use of non-solids for boolean operations may lead to unexpected results.\n" + "Continue?" + ), + QMessageBox::Yes, + QMessageBox::No + ); + if (ret == QMessageBox::No) { return; + } askUser = true; } @@ -345,7 +374,8 @@ void CmdPartCut::activated(int iMsg) bool CmdPartCut::isActive() { - return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) == 2; + return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + == 2; } //=========================================================================== @@ -354,40 +384,57 @@ bool CmdPartCut::isActive() DEF_STD_CMD_A(CmdPartCommon) CmdPartCommon::CmdPartCommon() - :Command("Part_Common") + : Command("Part_Common") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Intersection"); - sToolTipText = QT_TR_NOOP("Intersects the selected shapes"); - sWhatsThis = "Part_Common"; - sStatusTip = sToolTipText; - sPixmap = "Part_Common"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Intersection"); + sToolTipText = QT_TR_NOOP("Intersects the selected shapes"); + sWhatsThis = "Part_Common"; + sStatusTip = sToolTipText; + sPixmap = "Part_Common"; } void CmdPartCommon::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector Sel = - getSelection().getSelectionEx(nullptr, App::DocumentObject::getClassTypeId(), Gui::ResolveMode::FollowLink); + std::vector Sel = getSelection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::FollowLink + ); if (Sel.empty()) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select at least 2 shapes. Alternatively, select 1 compound containing 2 or more shapes to compute the intersection between.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select at least 2 shapes. Alternatively, select 1 compound containing 2 or more shapes to compute the intersection between.") + ); return; } bool askUser = false; std::vector names; - for (const auto & it : Sel) { + for (const auto& it : Sel) { const App::DocumentObject* obj = it.getObject(); - const TopoDS_Shape& shape = Part::Feature::getShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + const TopoDS_Shape& shape = Part::Feature::getShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!PartGui::checkForSolids(shape) && !askUser) { - int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), - QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" - "Continue?"), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::No) + int ret = QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Non-solids selected"), + QObject::tr( + "The use of non-solids for boolean operations may lead to unexpected results.\n" + "Continue?" + ), + QMessageBox::Yes, + QMessageBox::No + ); + if (ret == QMessageBox::No) { return; + } askUser = true; } @@ -404,7 +451,8 @@ void CmdPartCommon::activated(int iMsg) bool CmdPartCommon::isActive() { - return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) >= 1; + return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + >= 1; } //=========================================================================== @@ -413,30 +461,36 @@ bool CmdPartCommon::isActive() DEF_STD_CMD_A(CmdPartFuse) CmdPartFuse::CmdPartFuse() - :Command("Part_Fuse") + : Command("Part_Fuse") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Union"); - sToolTipText = QT_TR_NOOP("Unites the selected shapes"); - sWhatsThis = "Part_Fuse"; - sStatusTip = sToolTipText; - sPixmap = "Part_Fuse"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Union"); + sToolTipText = QT_TR_NOOP("Unites the selected shapes"); + sWhatsThis = "Part_Fuse"; + sStatusTip = sToolTipText; + sPixmap = "Part_Fuse"; } void CmdPartFuse::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector Sel = - getSelection().getSelectionEx(nullptr, App::DocumentObject::getClassTypeId(), Gui::ResolveMode::FollowLink); + std::vector Sel = getSelection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::FollowLink + ); - //test if selected object is a compound, and if it is, look how many children it has... + // test if selected object is a compound, and if it is, look how many children it has... std::size_t numShapes = 0; - if (Sel.size() == 1){ - numShapes = 1; //to be updated later in code + if (Sel.size() == 1) { + numShapes = 1; // to be updated later in code Gui::SelectionObject selobj = Sel[0]; - TopoDS_Shape sh = Part::Feature::getShape(selobj.getObject(), Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); - while (numShapes==1 && sh.ShapeType() == TopAbs_COMPOUND) { + TopoDS_Shape sh = Part::Feature::getShape( + selobj.getObject(), + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); + while (numShapes == 1 && sh.ShapeType() == TopAbs_COMPOUND) { numShapes = 0; TopoDS_Iterator it(sh); TopoDS_Shape last; @@ -446,26 +500,41 @@ void CmdPartFuse::activated(int iMsg) } sh = last; } - } else { + } + else { numShapes = Sel.size(); } if (numShapes < 2) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select at least 2 shapes. Alternatively, select 1 compound containing 2 or more shapes to be fused.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select at least 2 shapes. Alternatively, select 1 compound containing 2 or more shapes to be fused.") + ); return; } bool askUser = false; std::vector names; - for (const auto & it : Sel) { + for (const auto& it : Sel) { const App::DocumentObject* obj = it.getObject(); - const TopoDS_Shape& shape = Part::Feature::getShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + const TopoDS_Shape& shape = Part::Feature::getShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!PartGui::checkForSolids(shape) && !askUser) { - int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), - QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" - "Continue?"), QMessageBox::Yes, QMessageBox::No); - if (ret == QMessageBox::No) + int ret = QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Non-solids selected"), + QObject::tr( + "The use of non-solids for boolean operations may lead to unexpected results.\n" + "Continue?" + ), + QMessageBox::Yes, + QMessageBox::No + ); + if (ret == QMessageBox::No) { return; + } askUser = true; } @@ -482,7 +551,8 @@ void CmdPartFuse::activated(int iMsg) bool CmdPartFuse::isActive() { - return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) >= 1; + return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + >= 1; } //=========================================================================== @@ -492,28 +562,32 @@ bool CmdPartFuse::isActive() DEF_STD_CMD_ACL(CmdPartCompJoinFeatures) CmdPartCompJoinFeatures::CmdPartCompJoinFeatures() - : Command("Part_CompJoinFeatures") + : Command("Part_CompJoinFeatures") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Join Shapes"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Join Shapes"); - sToolTipText = QT_TR_NOOP("Joins the selected walled shapes"); - sWhatsThis = "Part_CompJoinFeatures"; - sStatusTip = sToolTipText; + sToolTipText = QT_TR_NOOP("Joins the selected walled shapes"); + sWhatsThis = "Part_CompJoinFeatures"; + sStatusTip = sToolTipText; } void CmdPartCompJoinFeatures::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("Part_JoinConnect"); - else if (iMsg==1) + } + else if (iMsg == 1) { rcCmdMgr.runCommandByName("Part_JoinEmbed"); - else if (iMsg==2) + } + else if (iMsg == 2) { rcCmdMgr.runCommandByName("Part_JoinCutout"); - else + } + else { return; + } // Since the default icon is reset when enabling/disabling the command we have // to explicitly set the icon of the used command. @@ -524,7 +598,7 @@ void CmdPartCompJoinFeatures::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompJoinFeatures::createAction() +Gui::Action* CmdPartCompJoinFeatures::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -551,10 +625,11 @@ void CmdPartCompJoinFeatures::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); @@ -586,10 +661,12 @@ void CmdPartCompJoinFeatures::languageChange() bool CmdPartCompJoinFeatures::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -599,30 +676,35 @@ bool CmdPartCompJoinFeatures::isActive() DEF_STD_CMD_ACL(CmdPartCompSplitFeatures) CmdPartCompSplitFeatures::CmdPartCompSplitFeatures() - : Command("Part_CompSplitFeatures") + : Command("Part_CompSplitFeatures") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Split Shapes"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Split Shapes"); - sToolTipText = QT_TR_NOOP("Shape splitting and compsolid creation tools"); - sWhatsThis = "Part_CompSplitFeatures"; - sStatusTip = sToolTipText; + sToolTipText = QT_TR_NOOP("Shape splitting and compsolid creation tools"); + sWhatsThis = "Part_CompSplitFeatures"; + sStatusTip = sToolTipText; } void CmdPartCompSplitFeatures::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("Part_BooleanFragments"); - else if (iMsg==1) + } + else if (iMsg == 1) { rcCmdMgr.runCommandByName("Part_SliceApart"); - else if (iMsg==2) + } + else if (iMsg == 2) { rcCmdMgr.runCommandByName("Part_Slice"); - else if (iMsg==3) + } + else if (iMsg == 3) { rcCmdMgr.runCommandByName("Part_XOR"); - else + } + else { return; + } // Since the default icon is reset when enabling/disabling the command we have // to explicitly set the icon of the used command. @@ -633,7 +715,7 @@ void CmdPartCompSplitFeatures::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompSplitFeatures::createAction() +Gui::Action* CmdPartCompSplitFeatures::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -662,10 +744,11 @@ void CmdPartCompSplitFeatures::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); @@ -674,16 +757,24 @@ void CmdPartCompSplitFeatures::languageChange() if (splitBoolFragments) { QAction* cmd0 = a[0]; cmd0->setText(QApplication::translate("Part_SplitFeatures", splitBoolFragments->getMenuText())); - cmd0->setToolTip(QApplication::translate("Part_SplitFeatures", splitBoolFragments->getToolTipText())); - cmd0->setStatusTip(QApplication::translate("Part_SplitFeatures", splitBoolFragments->getStatusTip())); + cmd0->setToolTip( + QApplication::translate("Part_SplitFeatures", splitBoolFragments->getToolTipText()) + ); + cmd0->setStatusTip( + QApplication::translate("Part_SplitFeatures", splitBoolFragments->getStatusTip()) + ); } Gui::Command* splitSliceApart = rcCmdMgr.getCommandByName("Part_SliceApart"); if (splitSliceApart) { QAction* cmd1 = a[1]; cmd1->setText(QApplication::translate("Part_SplitFeatures", splitSliceApart->getMenuText())); - cmd1->setToolTip(QApplication::translate("Part_SplitFeatures", splitSliceApart->getToolTipText())); - cmd1->setStatusTip(QApplication::translate("Part_SplitFeatures", splitSliceApart->getStatusTip())); + cmd1->setToolTip( + QApplication::translate("Part_SplitFeatures", splitSliceApart->getToolTipText()) + ); + cmd1->setStatusTip( + QApplication::translate("Part_SplitFeatures", splitSliceApart->getStatusTip()) + ); } Gui::Command* splitSlice = rcCmdMgr.getCommandByName("Part_Slice"); @@ -705,10 +796,12 @@ void CmdPartCompSplitFeatures::languageChange() bool CmdPartCompSplitFeatures::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -718,27 +811,31 @@ bool CmdPartCompSplitFeatures::isActive() DEF_STD_CMD_ACL(CmdPartCompCompoundTools) CmdPartCompCompoundTools::CmdPartCompCompoundTools() - : Command("Part_CompCompoundTools") + : Command("Part_CompCompoundTools") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Compound Tools"); - sToolTipText = QT_TR_NOOP("Compound tools for working with multiple shapes"); - sWhatsThis = "Part_CompCompoundTools"; - sStatusTip = sToolTipText; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Compound Tools"); + sToolTipText = QT_TR_NOOP("Compound tools for working with multiple shapes"); + sWhatsThis = "Part_CompCompoundTools"; + sStatusTip = sToolTipText; } void CmdPartCompCompoundTools::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("Part_Compound"); - else if (iMsg==1) + } + else if (iMsg == 1) { rcCmdMgr.runCommandByName("Part_ExplodeCompound"); - else if (iMsg==2) + } + else if (iMsg == 2) { rcCmdMgr.runCommandByName("Part_CompoundFilter"); - else + } + else { return; + } // Since the default icon is reset when enabling/disabling the command we have // to explicitly set the icon of the used command. @@ -749,7 +846,7 @@ void CmdPartCompCompoundTools::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompCompoundTools::createAction() +Gui::Action* CmdPartCompCompoundTools::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -776,10 +873,11 @@ void CmdPartCompCompoundTools::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); @@ -804,45 +902,56 @@ void CmdPartCompCompoundTools::languageChange() if (cmdCompoundFilter) { QAction* cmd2 = a[2]; cmd2->setText(QApplication::translate("Part_CompoundTools", cmdCompoundFilter->getMenuText())); - cmd2->setToolTip(QApplication::translate("Part_CompoundTools", cmdCompoundFilter->getToolTipText())); - cmd2->setStatusTip(QApplication::translate("Part_CompoundTools", cmdCompoundFilter->getStatusTip())); + cmd2->setToolTip( + QApplication::translate("Part_CompoundTools", cmdCompoundFilter->getToolTipText()) + ); + cmd2->setStatusTip( + QApplication::translate("Part_CompoundTools", cmdCompoundFilter->getStatusTip()) + ); } } bool CmdPartCompCompoundTools::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } - //=========================================================================== // Part_Compound //=========================================================================== DEF_STD_CMD_A(CmdPartCompound) CmdPartCompound::CmdPartCompound() - :Command("Part_Compound") + : Command("Part_Compound") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Compound"); - sToolTipText = QT_TR_NOOP("Compounds the selected shapes"); - sWhatsThis = "Part_Compound"; - sStatusTip = sToolTipText; - sPixmap = "Part_Compound"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Compound"); + sToolTipText = QT_TR_NOOP("Compounds the selected shapes"); + sWhatsThis = "Part_Compound"; + sStatusTip = sToolTipText; + sPixmap = "Part_Compound"; } void CmdPartCompound::activated(int iMsg) { Q_UNUSED(iMsg); - unsigned int n = getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink); + unsigned int n = getSelection().countObjectsOfType( + nullptr, + Gui::ResolveMode::FollowLink + ); if (n < 1) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select at least one shape")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select at least one shape") + ); return; } @@ -854,7 +963,7 @@ void CmdPartCompound::activated(int iMsg) // avoid duplicates without changing the order std::set tempSelNames; str << "App.activeDocument()." << FeatName << ".Links = ["; - for (const auto & it : Sel) { + for (const auto& it : Sel) { auto pos = tempSelNames.insert(it.FeatName); if (pos.second) { str << "App.activeDocument()." << it.FeatName << ","; @@ -863,15 +972,16 @@ void CmdPartCompound::activated(int iMsg) str << "]"; openCommand(QT_TRANSLATE_NOOP("Command", "Compound")); - doCommand(Doc,"App.activeDocument().addObject(\"Part::Compound\",\"%s\")",FeatName.c_str()); - runCommand(Doc,str.str().c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Part::Compound\",\"%s\")", FeatName.c_str()); + runCommand(Doc, str.str().c_str()); updateActive(); commitCommand(); } bool CmdPartCompound::isActive() { - return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) >= 1; + return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + >= 1; } //=========================================================================== @@ -880,46 +990,68 @@ bool CmdPartCompound::isActive() DEF_STD_CMD_A(CmdPartSection) CmdPartSection::CmdPartSection() - :Command("Part_Section") + : Command("Part_Section") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Section"); - sToolTipText = QT_TR_NOOP("Sections 2 selected shapes"); - sWhatsThis = "Part_Section"; - sStatusTip = sToolTipText; - sPixmap = "Part_Section"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Section"); + sToolTipText = QT_TR_NOOP("Sections 2 selected shapes"); + sWhatsThis = "Part_Section"; + sStatusTip = sToolTipText; + sPixmap = "Part_Section"; } void CmdPartSection::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector Sel = - getSelection().getSelectionEx(nullptr, App::DocumentObject::getClassTypeId(), Gui::ResolveMode::FollowLink); + std::vector Sel = getSelection().getSelectionEx( + nullptr, + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::FollowLink + ); if (Sel.size() != 2) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select 2 shapes")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select 2 shapes") + ); return; } std::string FeatName = getUniqueObjectName("Section"); - std::string BaseName = Sel[0].getFeatName(); - std::string ToolName = Sel[1].getFeatName(); + std::string BaseName = Sel[0].getFeatName(); + std::string ToolName = Sel[1].getFeatName(); openCommand(QT_TRANSLATE_NOOP("Command", "Section")); - doCommand(Doc,"App.activeDocument().addObject(\"Part::Section\",\"%s\")",FeatName.c_str()); - doCommand(Doc,"App.activeDocument().%s.Base = App.activeDocument().%s",FeatName.c_str(),BaseName.c_str()); - doCommand(Doc,"App.activeDocument().%s.Tool = App.activeDocument().%s",FeatName.c_str(),ToolName.c_str()); - doCommand(Gui,"Gui.activeDocument().hide('%s')",BaseName.c_str()); - doCommand(Gui,"Gui.activeDocument().hide('%s')",ToolName.c_str()); - doCommand(Gui,"Gui.activeDocument().%s.LineMaterial = Gui.activeDocument().%s.ShapeAppearance[0]",FeatName.c_str(),BaseName.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Part::Section\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.Base = App.activeDocument().%s", + FeatName.c_str(), + BaseName.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.Tool = App.activeDocument().%s", + FeatName.c_str(), + ToolName.c_str() + ); + doCommand(Gui, "Gui.activeDocument().hide('%s')", BaseName.c_str()); + doCommand(Gui, "Gui.activeDocument().hide('%s')", ToolName.c_str()); + doCommand( + Gui, + "Gui.activeDocument().%s.LineMaterial = Gui.activeDocument().%s.ShapeAppearance[0]", + FeatName.c_str(), + BaseName.c_str() + ); updateActive(); commitCommand(); } bool CmdPartSection::isActive() { - return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) == 2; + return getSelection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + == 2; } //=========================================================================== @@ -928,16 +1060,16 @@ bool CmdPartSection::isActive() DEF_STD_CMD_A(CmdPartImport) CmdPartImport::CmdPartImport() - :Command("Part_Import") + : Command("Part_Import") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Import CAD File"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Import CAD File"); - sToolTipText = QT_TR_NOOP("Imports a CAD file"); - sWhatsThis = "Part_Import"; - sStatusTip = sToolTipText; - sPixmap = "Part_Import"; + sToolTipText = QT_TR_NOOP("Imports a CAD file"); + sWhatsThis = "Part_Import"; + sStatusTip = sToolTipText; + sPixmap = "Part_Import"; } void CmdPartImport::activated(int iMsg) @@ -951,17 +1083,23 @@ void CmdPartImport::activated(int iMsg) filter << QStringLiteral("BREP (*.brp *.brep)"); QString select; - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QString(), QString(), filter.join(QLatin1String(";;")), &select); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + filter.join(QLatin1String(";;")), + &select + ); if (!fn.isEmpty()) { Gui::WaitCursor wc; App::Document* pDoc = getDocument(); - if (!pDoc) // no document + if (!pDoc) { // no document return; + } fn = Base::Tools::escapeEncodeFilename(fn); openCommand(QT_TRANSLATE_NOOP("Command", "Import Part")); - if (select == filter[1] || - select == filter[3]) { + if (select == filter[1] || select == filter[3]) { doCommand(Doc, "import ImportGui"); doCommand(Doc, "ImportGui.insert(\"%s\",\"%s\")", (const char*)fn.toUtf8(), pDoc->getName()); } @@ -971,7 +1109,9 @@ void CmdPartImport::activated(int iMsg) } commitCommand(); - std::list views = getActiveGuiDocument()->getMDIViewsOfType(Gui::View3DInventor::getClassTypeId()); + std::list views = getActiveGuiDocument()->getMDIViewsOfType( + Gui::View3DInventor::getClassTypeId() + ); for (auto view : views) { view->viewAll(); } @@ -980,10 +1120,12 @@ void CmdPartImport::activated(int iMsg) bool CmdPartImport::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -992,16 +1134,16 @@ bool CmdPartImport::isActive() DEF_STD_CMD_A(CmdPartExport) CmdPartExport::CmdPartExport() - : Command("Part_Export") + : Command("Part_Export") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Export CAD File"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Export CAD File"); - sToolTipText = QT_TR_NOOP("Exports to a CAD file"); - sWhatsThis = "Part_Export"; - sStatusTip = sToolTipText; - sPixmap = "Part_Export"; + sToolTipText = QT_TR_NOOP("Exports to a CAD file"); + sWhatsThis = "Part_Export"; + sStatusTip = sToolTipText; + sPixmap = "Part_Export"; } void CmdPartExport::activated(int iMsg) @@ -1015,24 +1157,31 @@ void CmdPartExport::activated(int iMsg) filter << QStringLiteral("BREP (*.brp *.brep)"); QString select; - QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), QString(), QString(), filter.join(QLatin1String(";;")), &select); + QString fn = Gui::FileDialog::getSaveFileName( + Gui::getMainWindow(), + QString(), + QString(), + filter.join(QLatin1String(";;")), + &select + ); if (!fn.isEmpty()) { App::Document* pDoc = getDocument(); - if (!pDoc) // no document + if (!pDoc) { // no document return; - if (select == filter[1] || - select == filter[3]) { - Gui::Application::Instance->exportTo((const char*)fn.toUtf8(),pDoc->getName(),"ImportGui"); + } + if (select == filter[1] || select == filter[3]) { + Gui::Application::Instance->exportTo((const char*)fn.toUtf8(), pDoc->getName(), "ImportGui"); } else { - Gui::Application::Instance->exportTo((const char*)fn.toUtf8(),pDoc->getName(),"Part"); + Gui::Application::Instance->exportTo((const char*)fn.toUtf8(), pDoc->getName(), "Part"); } } } bool CmdPartExport::isActive() { - return Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) > 0; + return Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + > 0; } //=========================================================================== @@ -1041,16 +1190,16 @@ bool CmdPartExport::isActive() DEF_STD_CMD_A(CmdPartImportCurveNet) CmdPartImportCurveNet::CmdPartImportCurveNet() - :Command("Part_ImportCurveNet") + : Command("Part_ImportCurveNet") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Import Curve Network"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Import Curve Network"); - sToolTipText= QT_TR_NOOP("Imports a curve network"); - sWhatsThis = "Part_ImportCurveNet"; - sStatusTip = sToolTipText; - sPixmap = "Part_Box_Parametric"; + sToolTipText = QT_TR_NOOP("Imports a curve network"); + sWhatsThis = "Part_ImportCurveNet"; + sStatusTip = sToolTipText; + sPixmap = "Part_Box_Parametric"; } void CmdPartImportCurveNet::activated(int iMsg) @@ -1058,19 +1207,28 @@ void CmdPartImportCurveNet::activated(int iMsg) Q_UNUSED(iMsg); QStringList filter; filter << QStringLiteral("%1 (*.stp *.step *.igs *.iges *.brp *.brep)") - .arg(QObject::tr("All CAD Files")); + .arg(QObject::tr("All CAD Files")); filter << QStringLiteral("STEP (*.stp *.step)"); filter << QStringLiteral("IGES (*.igs *.iges)"); filter << QStringLiteral("BREP (*.brp *.brep)"); - filter << QStringLiteral("%1 (*.*)") - .arg(QObject::tr("All Files")); + filter << QStringLiteral("%1 (*.*)").arg(QObject::tr("All Files")); - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QString(), QString(), filter.join(QLatin1String(";;"))); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + filter.join(QLatin1String(";;")) + ); if (!fn.isEmpty()) { - QFileInfo fi; fi.setFile(fn); + QFileInfo fi; + fi.setFile(fn); openCommand(QT_TRANSLATE_NOOP("Command", "Import Curve Net")); - doCommand(Doc,"f = App.activeDocument().addObject(\"Part::CurveNet\",\"%s\")", (const char*)fi.baseName().toLatin1()); - doCommand(Doc,"f.FileName = \"%s\"",(const char*)fn.toLatin1()); + doCommand( + Doc, + "f = App.activeDocument().addObject(\"Part::CurveNet\",\"%s\")", + (const char*)fi.baseName().toLatin1() + ); + doCommand(Doc, "f.FileName = \"%s\"", (const char*)fn.toLatin1()); commitCommand(); updateActive(); } @@ -1078,10 +1236,12 @@ void CmdPartImportCurveNet::activated(int iMsg) bool CmdPartImportCurveNet::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -1090,68 +1250,82 @@ bool CmdPartImportCurveNet::isActive() DEF_STD_CMD_A(CmdPartMakeSolid) CmdPartMakeSolid::CmdPartMakeSolid() - :Command("Part_MakeSolid") + : Command("Part_MakeSolid") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Convert to Solid"); - sToolTipText = QT_TR_NOOP("Converts the selected shell or compound to a solid"); - sWhatsThis = "Part_MakeSolid"; - sStatusTip = sToolTipText; - sPixmap = "Part_MakeSolid"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Convert to Solid"); + sToolTipText = QT_TR_NOOP("Converts the selected shell or compound to a solid"); + sWhatsThis = "Part_MakeSolid"; + sStatusTip = sToolTipText; + sPixmap = "Part_MakeSolid"; } void CmdPartMakeSolid::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector objs = Gui::Selection().getObjectsOfType - (App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink); + std::vector objs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId(), + nullptr, + Gui::ResolveMode::FollowLink + ); runCommand(Doc, "import Part"); for (auto it : objs) { - const TopoDS_Shape& shape = Part::Feature::getShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + const TopoDS_Shape& shape = Part::Feature::getShape( + it, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!shape.IsNull()) { TopAbs_ShapeEnum type = shape.ShapeType(); QString str; if (type == TopAbs_SOLID) { - Base::Console().message("%s is ignored because it is already a solid.\n", - it->Label.getValue()); + Base::Console().message( + "%s is ignored because it is already a solid.\n", + it->Label.getValue() + ); } else if (type == TopAbs_COMPOUND || type == TopAbs_COMPSOLID) { str = QStringLiteral( - "__s__=App.ActiveDocument.%1.Shape.Faces\n" - "__s__=Part.Solid(Part.Shell(__s__))\n" - "__o__=App.ActiveDocument.addObject(\"Part::Feature\",\"%1_solid\")\n" - "__o__.Label=\"%2 (Solid)\"\n" - "__o__.Shape=__s__\n" - "del __s__, __o__" - ) - .arg(QLatin1String(it->getNameInDocument()), - QLatin1String(it->Label.getValue())); + "__s__=App.ActiveDocument.%1.Shape.Faces\n" + "__s__=Part.Solid(Part.Shell(__s__))\n" + "__o__=App.ActiveDocument.addObject(\"Part::Feature\",\"%1_solid\")\n" + "__o__.Label=\"%2 (Solid)\"\n" + "__o__.Shape=__s__\n" + "del __s__, __o__" + ) + .arg( + QLatin1String(it->getNameInDocument()), + QLatin1String(it->Label.getValue()) + ); } else if (type == TopAbs_SHELL) { str = QStringLiteral( - "__s__=App.ActiveDocument.%1.Shape\n" - "__s__=Part.Solid(__s__)\n" - "__o__=App.ActiveDocument.addObject(\"Part::Feature\",\"%1_solid\")\n" - "__o__.Label=\"%2 (Solid)\"\n" - "__o__.Shape=__s__\n" - "del __s__, __o__" - ) - .arg(QLatin1String(it->getNameInDocument()), - QLatin1String(it->Label.getValue())); + "__s__=App.ActiveDocument.%1.Shape\n" + "__s__=Part.Solid(__s__)\n" + "__o__=App.ActiveDocument.addObject(\"Part::Feature\",\"%1_solid\")\n" + "__o__.Label=\"%2 (Solid)\"\n" + "__o__.Shape=__s__\n" + "del __s__, __o__" + ) + .arg( + QLatin1String(it->getNameInDocument()), + QLatin1String(it->Label.getValue()) + ); } else { - Base::Console().message("%s is ignored because it is neither a shell nor a compound.\n", - it->Label.getValue()); + Base::Console().message( + "%s is ignored because it is neither a shell nor a compound.\n", + it->Label.getValue() + ); } try { - if (!str.isEmpty()) + if (!str.isEmpty()) { runCommand(Doc, str.toLatin1()); + } } catch (const Base::Exception& e) { - Base::Console().error("Cannot convert %s because %s.\n", - it->Label.getValue(), e.what()); + Base::Console().error("Cannot convert %s because %s.\n", it->Label.getValue(), e.what()); } } } @@ -1159,7 +1333,8 @@ void CmdPartMakeSolid::activated(int iMsg) bool CmdPartMakeSolid::isActive() { - return Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) > 0; + return Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + > 0; } //=========================================================================== @@ -1168,49 +1343,54 @@ bool CmdPartMakeSolid::isActive() DEF_STD_CMD_A(CmdPartReverseShape) CmdPartReverseShape::CmdPartReverseShape() - :Command("Part_ReverseShape") + : Command("Part_ReverseShape") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Reverse Shapes"); - sToolTipText = QT_TR_NOOP("Reverses the orientation of the selected shapes"); - sWhatsThis = "Part_ReverseShape"; - sStatusTip = sToolTipText; - sPixmap = "Part_Reverse_Shape"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Reverse Shapes"); + sToolTipText = QT_TR_NOOP("Reverses the orientation of the selected shapes"); + sWhatsThis = "Part_ReverseShape"; + sStatusTip = sToolTipText; + sPixmap = "Part_Reverse_Shape"; } void CmdPartReverseShape::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector objs = Gui::Selection().getObjectsOfType - (App::DocumentObject::getClassTypeId()); + std::vector objs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); openCommand(QT_TRANSLATE_NOOP("Command", "Reverse")); for (auto it : objs) { - const TopoDS_Shape& shape = Part::Feature::getShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + const TopoDS_Shape& shape = Part::Feature::getShape( + it, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!shape.IsNull()) { std::string name = it->getNameInDocument(); name += "_rev"; name = getUniqueObjectName(name.c_str()); QString str = QStringLiteral( - "__o__=App.ActiveDocument.addObject(\"Part::Reverse\",\"%1\")\n" - "__o__.Source=App.ActiveDocument.%2\n" - "__o__.Label=\"%3 (Rev)\"\n" - "del __o__" - ) - .arg(QString::fromLatin1(name.c_str()), - QString::fromLatin1(it->getNameInDocument()), - QString::fromLatin1(it->Label.getValue())); + "__o__=App.ActiveDocument.addObject(\"Part::Reverse\",\"%1\")\n" + "__o__.Source=App.ActiveDocument.%2\n" + "__o__.Label=\"%3 (Rev)\"\n" + "del __o__" + ) + .arg( + QString::fromLatin1(name.c_str()), + QString::fromLatin1(it->getNameInDocument()), + QString::fromLatin1(it->Label.getValue()) + ); try { runCommand(Doc, str.toLatin1()); copyVisual(name.c_str(), "ShapeAppearance", it->getNameInDocument()); - copyVisual(name.c_str(), "LineColor" , it->getNameInDocument()); + copyVisual(name.c_str(), "LineColor", it->getNameInDocument()); copyVisual(name.c_str(), "PointColor", it->getNameInDocument()); } catch (const Base::Exception& e) { - Base::Console().error("Cannot convert %s because %s.\n", - it->Label.getValue(), e.what()); + Base::Console().error("Cannot convert %s because %s.\n", it->Label.getValue(), e.what()); } } } @@ -1230,23 +1410,24 @@ bool CmdPartReverseShape::isActive() DEF_STD_CMD_A(CmdPartBoolean) CmdPartBoolean::CmdPartBoolean() - :Command("Part_Boolean") + : Command("Part_Boolean") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); sMenuText = QT_TR_NOOP("Boolean Operation"); - sToolTipText = QT_TR_NOOP("Applies a boolean operations with the selected shapes"); - sWhatsThis = "Part_Boolean"; - sStatusTip = sToolTipText; - sPixmap = "Part_Booleans"; + sToolTipText = QT_TR_NOOP("Applies a boolean operations with the selected shapes"); + sWhatsThis = "Part_Boolean"; + sStatusTip = sToolTipText; + sPixmap = "Part_Booleans"; } void CmdPartBoolean::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (!dlg) + if (!dlg) { dlg = new PartGui::TaskBooleanOperation(); + } Gui::Control().showDialog(dlg); } @@ -1261,15 +1442,15 @@ bool CmdPartBoolean::isActive() DEF_STD_CMD_A(CmdPartExtrude) CmdPartExtrude::CmdPartExtrude() - :Command("Part_Extrude") + : Command("Part_Extrude") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Extrude"); - sToolTipText = QT_TR_NOOP("Extrudes the selected sketch or profile"); - sWhatsThis = "Part_Extrude"; - sStatusTip = sToolTipText; - sPixmap = "Part_Extrude"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Extrude"); + sToolTipText = QT_TR_NOOP("Extrudes the selected sketch or profile"); + sWhatsThis = "Part_Extrude"; + sStatusTip = sToolTipText; + sPixmap = "Part_Extrude"; } void CmdPartExtrude::activated(int iMsg) @@ -1289,15 +1470,15 @@ bool CmdPartExtrude::isActive() DEF_STD_CMD_A(CmdPartScale) CmdPartScale::CmdPartScale() - :Command("Part_Scale") + : Command("Part_Scale") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Scale"); - sToolTipText = QT_TR_NOOP("Scales the selected shape"); - sWhatsThis = "Part_Scale"; - sStatusTip = sToolTipText; - sPixmap = "Part_Scale"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Scale"); + sToolTipText = QT_TR_NOOP("Scales the selected shape"); + sWhatsThis = "Part_Scale"; + sStatusTip = sToolTipText; + sPixmap = "Part_Scale"; } void CmdPartScale::activated(int iMsg) @@ -1318,37 +1499,41 @@ bool CmdPartScale::isActive() DEF_STD_CMD_A(CmdPartMakeFace) CmdPartMakeFace::CmdPartMakeFace() - : Command("Part_MakeFace") + : Command("Part_MakeFace") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Face From Wires"); - sToolTipText = QT_TR_NOOP("Creates a face from the selected wires (e.g. from a sketch)"); - sWhatsThis = "Part_MakeFace"; - sStatusTip = sToolTipText; - sPixmap = "Part_MakeFace"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Face From Wires"); + sToolTipText = QT_TR_NOOP("Creates a face from the selected wires (e.g. from a sketch)"); + sWhatsThis = "Part_MakeFace"; + sStatusTip = sToolTipText; + sPixmap = "Part_MakeFace"; } void CmdPartMakeFace::activated(int iMsg) { Q_UNUSED(iMsg); - auto sketches = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink); - if(sketches.empty()) + auto sketches = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId(), + nullptr, + Gui::ResolveMode::FollowLink + ); + if (sketches.empty()) { return; + } openCommand(QT_TRANSLATE_NOOP("Command", "Make face")); try { App::DocumentT doc(sketches.front()->getDocument()); std::stringstream str; - str << doc.getDocumentPython() - << R"(.addObject("Part::Face", "Face").Sources = ()"; - for (auto &obj : sketches) { + str << doc.getDocumentPython() << R"(.addObject("Part::Face", "Face").Sources = ()"; + for (auto& obj : sketches) { str << App::DocumentObjectT(obj).getObjectPython() << ", "; } str << ")"; - runCommand(Doc,str.str().c_str()); + runCommand(Doc, str.str().c_str()); commitCommand(); updateActive(); } @@ -1360,8 +1545,11 @@ void CmdPartMakeFace::activated(int iMsg) bool CmdPartMakeFace::isActive() { - return (Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) > 0 && - !Gui::Control().activeDialog()); + return ( + Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + > 0 + && !Gui::Control().activeDialog() + ); } //=========================================================================== @@ -1370,15 +1558,15 @@ bool CmdPartMakeFace::isActive() DEF_STD_CMD_A(CmdPartRevolve) CmdPartRevolve::CmdPartRevolve() - :Command("Part_Revolve") + : Command("Part_Revolve") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Revolve"); - sToolTipText = QT_TR_NOOP("Revolves the selected shape"); - sWhatsThis = "Part_Revolve"; - sStatusTip = sToolTipText; - sPixmap = "Part_Revolve"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Revolve"); + sToolTipText = QT_TR_NOOP("Revolves the selected shape"); + sWhatsThis = "Part_Revolve"; + sStatusTip = sToolTipText; + sPixmap = "Part_Revolve"; } void CmdPartRevolve::activated(int iMsg) @@ -1398,15 +1586,15 @@ bool CmdPartRevolve::isActive() DEF_STD_CMD_A(CmdPartFillet) CmdPartFillet::CmdPartFillet() - :Command("Part_Fillet") + : Command("Part_Fillet") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Fillet"); - sToolTipText = QT_TR_NOOP("Fillets the selected edges of a shape"); - sWhatsThis = "Part_Fillet"; - sStatusTip = sToolTipText; - sPixmap = "Part_Fillet"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Fillet"); + sToolTipText = QT_TR_NOOP("Fillets the selected edges of a shape"); + sWhatsThis = "Part_Fillet"; + sStatusTip = sToolTipText; + sPixmap = "Part_Fillet"; } void CmdPartFillet::activated(int iMsg) @@ -1426,15 +1614,15 @@ bool CmdPartFillet::isActive() DEF_STD_CMD_A(CmdPartChamfer) CmdPartChamfer::CmdPartChamfer() - :Command("Part_Chamfer") + : Command("Part_Chamfer") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Chamfer"); - sToolTipText = QT_TR_NOOP("Chamfers the selected edges of a shape"); - sWhatsThis = "Part_Chamfer"; - sStatusTip = sToolTipText; - sPixmap = "Part_Chamfer"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Chamfer"); + sToolTipText = QT_TR_NOOP("Chamfers the selected edges of a shape"); + sWhatsThis = "Part_Chamfer"; + sStatusTip = sToolTipText; + sPixmap = "Part_Chamfer"; } void CmdPartChamfer::activated(int iMsg) @@ -1454,15 +1642,15 @@ bool CmdPartChamfer::isActive() DEF_STD_CMD_A(CmdPartMirror) CmdPartMirror::CmdPartMirror() - :Command("Part_Mirror") + : Command("Part_Mirror") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Mirror"); - sToolTipText = QT_TR_NOOP("Mirrors the selected shape"); - sWhatsThis = "Part_Mirror"; - sStatusTip = sToolTipText; - sPixmap = "Part_Mirror"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Mirror"); + sToolTipText = QT_TR_NOOP("Mirrors the selected shape"); + sWhatsThis = "Part_Mirror"; + sStatusTip = sToolTipText; + sPixmap = "Part_Mirror"; } void CmdPartMirror::activated(int iMsg) @@ -1482,15 +1670,15 @@ bool CmdPartMirror::isActive() DEF_STD_CMD_A(CmdPartCrossSections) CmdPartCrossSections::CmdPartCrossSections() - :Command("Part_CrossSections") + : Command("Part_CrossSections") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Cross-Sections"); - sToolTipText = QT_TR_NOOP("Creates cross-sections"); - sWhatsThis = "Part_CrossSections"; - sStatusTip = sToolTipText; - sPixmap = "Part_CrossSections"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Cross-Sections"); + sToolTipText = QT_TR_NOOP("Creates cross-sections"); + sWhatsThis = "Part_CrossSections"; + sStatusTip = sToolTipText; + sPixmap = "Part_CrossSections"; } void CmdPartCrossSections::activated(int iMsg) @@ -1500,7 +1688,7 @@ void CmdPartCrossSections::activated(int iMsg) if (!dlg) { std::vector shapes = PartGui::getShapesFromSelection(); Base::BoundBox3d bbox; - for (const auto & it : shapes) { + for (const auto& it : shapes) { bbox.Add(it.getBoundBox()); } dlg = new PartGui::TaskCrossSections(bbox); @@ -1521,16 +1709,16 @@ bool CmdPartCrossSections::isActive() DEF_STD_CMD_A(CmdPartBuilder) CmdPartBuilder::CmdPartBuilder() - :Command("Part_Builder") + : Command("Part_Builder") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Shape Builder"); + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Shape Builder"); - sToolTipText = QT_TR_NOOP("Advanced utility to create shapes"); - sWhatsThis = "Part_Builder"; - sStatusTip = sToolTipText; - sPixmap = "Part_Shapebuilder"; + sToolTipText = QT_TR_NOOP("Advanced utility to create shapes"); + sWhatsThis = "Part_Builder"; + sStatusTip = sToolTipText; + sPixmap = "Part_Shapebuilder"; } void CmdPartBuilder::activated(int iMsg) @@ -1551,15 +1739,15 @@ bool CmdPartBuilder::isActive() DEF_STD_CMD_A(CmdPartLoft) CmdPartLoft::CmdPartLoft() - : Command("Part_Loft") + : Command("Part_Loft") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Loft"); - sToolTipText = QT_TR_NOOP("Lofts the selected profiles"); - sWhatsThis = "Part_Loft"; - sStatusTip = sToolTipText; - sPixmap = "Part_Loft"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Loft"); + sToolTipText = QT_TR_NOOP("Lofts the selected profiles"); + sWhatsThis = "Part_Loft"; + sStatusTip = sToolTipText; + sPixmap = "Part_Loft"; } void CmdPartLoft::activated(int iMsg) @@ -1580,15 +1768,15 @@ bool CmdPartLoft::isActive() DEF_STD_CMD_A(CmdPartSweep) CmdPartSweep::CmdPartSweep() - : Command("Part_Sweep") + : Command("Part_Sweep") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Sweep"); - sToolTipText = QT_TR_NOOP("Sweeps profiles along a wire"); - sWhatsThis = "Part_Sweep"; - sStatusTip = sToolTipText; - sPixmap = "Part_Sweep"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Sweep"); + sToolTipText = QT_TR_NOOP("Sweeps profiles along a wire"); + sWhatsThis = "Part_Sweep"; + sStatusTip = sToolTipText; + sPixmap = "Part_Sweep"; } void CmdPartSweep::activated(int iMsg) @@ -1609,25 +1797,28 @@ bool CmdPartSweep::isActive() DEF_STD_CMD_A(CmdPartOffset) CmdPartOffset::CmdPartOffset() - : Command("Part_Offset") + : Command("Part_Offset") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("3D Offset"); - sToolTipText = QT_TR_NOOP("Offsets shapes in 3D"); - sWhatsThis = "Part_Offset"; - sStatusTip = sToolTipText; - sPixmap = "Part_Offset"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("3D Offset"); + sToolTipText = QT_TR_NOOP("Offsets shapes in 3D"); + sWhatsThis = "Part_Offset"; + sStatusTip = sToolTipText; + sPixmap = "Part_Offset"; } void CmdPartOffset::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); std::vector shapes; for (auto it : docobjs) { - if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform).isNull()) { - shapes.push_back(it); + if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform) + .isNull()) { + shapes.push_back(it); } } if (shapes.size() != 1) { @@ -1637,12 +1828,17 @@ void CmdPartOffset::activated(int iMsg) std::string offset = getUniqueObjectName("Offset"); openCommand(QT_TRANSLATE_NOOP("Command", "Make Offset")); - doCommand(Doc,"App.ActiveDocument.addObject(\"Part::Offset\",\"%s\")",offset.c_str()); - doCommand(Doc,"App.ActiveDocument.%s.Source = App.ActiveDocument.%s" ,offset.c_str(), shape->getNameInDocument()); - doCommand(Doc,"App.ActiveDocument.%s.Value = 1.0",offset.c_str()); + doCommand(Doc, "App.ActiveDocument.addObject(\"Part::Offset\",\"%s\")", offset.c_str()); + doCommand( + Doc, + "App.ActiveDocument.%s.Source = App.ActiveDocument.%s", + offset.c_str(), + shape->getNameInDocument() + ); + doCommand(Doc, "App.ActiveDocument.%s.Value = 1.0", offset.c_str()); updateActive(); - doCommand(Gui,"Gui.ActiveDocument.setEdit('%s')",offset.c_str()); + doCommand(Gui, "Gui.ActiveDocument.setEdit('%s')", offset.c_str()); if (!shape->isDerivedFrom()) { copyVisual(offset.c_str(), "ShapeAppearance", shape->getNameInDocument()); @@ -1653,9 +1849,11 @@ void CmdPartOffset::activated(int iMsg) bool CmdPartOffset::isActive() { - bool hasShapes = PartGui::hasShapesInSelection(); - std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); - return (hasShapes && !Gui::Control().activeDialog() && docobjs.size() == 1); + bool hasShapes = PartGui::hasShapesInSelection(); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); + return (hasShapes && !Gui::Control().activeDialog() && docobjs.size() == 1); } @@ -1666,26 +1864,29 @@ bool CmdPartOffset::isActive() DEF_STD_CMD_A(CmdPartOffset2D) CmdPartOffset2D::CmdPartOffset2D() - : Command("Part_Offset2D") + : Command("Part_Offset2D") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("2D Offset"); - sToolTipText = QT_TR_NOOP("Offsets planar shapes in 2D"); - sWhatsThis = "Part_Offset2D"; - sStatusTip = sToolTipText; - sPixmap = "Part_Offset2D"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("2D Offset"); + sToolTipText = QT_TR_NOOP("Offsets planar shapes in 2D"); + sWhatsThis = "Part_Offset2D"; + sStatusTip = sToolTipText; + sPixmap = "Part_Offset2D"; } void CmdPartOffset2D::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); std::vector shapes; for (auto it : docobjs) { - if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform).isNull()) { - shapes.push_back(it); + if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform) + .isNull()) { + shapes.push_back(it); } } if (shapes.size() != 1) { @@ -1695,11 +1896,16 @@ void CmdPartOffset2D::activated(int iMsg) std::string offset = getUniqueObjectName("Offset2D"); openCommand(QT_TRANSLATE_NOOP("Command", "Make 2D Offset")); - doCommand(Doc,"App.ActiveDocument.addObject(\"Part::Offset2D\",\"%s\")",offset.c_str()); - doCommand(Doc,"App.ActiveDocument.%s.Source = App.ActiveDocument.%s" ,offset.c_str(), shape->getNameInDocument()); - doCommand(Doc,"App.ActiveDocument.%s.Value = 1.0",offset.c_str()); + doCommand(Doc, "App.ActiveDocument.addObject(\"Part::Offset2D\",\"%s\")", offset.c_str()); + doCommand( + Doc, + "App.ActiveDocument.%s.Source = App.ActiveDocument.%s", + offset.c_str(), + shape->getNameInDocument() + ); + doCommand(Doc, "App.ActiveDocument.%s.Value = 1.0", offset.c_str()); updateActive(); - doCommand(Gui,"Gui.ActiveDocument.setEdit('%s')",offset.c_str()); + doCommand(Gui, "Gui.ActiveDocument.setEdit('%s')", offset.c_str()); if (!shape->isDerivedFrom()) { copyVisual(offset.c_str(), "ShapeAppearance", shape->getNameInDocument()); @@ -1711,7 +1917,9 @@ void CmdPartOffset2D::activated(int iMsg) bool CmdPartOffset2D::isActive() { bool hasShapes = PartGui::hasShapesInSelection(); - std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); return (hasShapes && !Gui::Control().activeDialog() && docobjs.size() == 1); } @@ -1722,25 +1930,28 @@ bool CmdPartOffset2D::isActive() DEF_STD_CMD_ACL(CmdPartCompOffset) CmdPartCompOffset::CmdPartCompOffset() - : Command("Part_CompOffset") + : Command("Part_CompOffset") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Offset"); - sToolTipText = QT_TR_NOOP("Tools to offset shapes (construct parallel shapes)"); - sWhatsThis = "Part_CompOffset"; - sStatusTip = sToolTipText; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Offset"); + sToolTipText = QT_TR_NOOP("Tools to offset shapes (construct parallel shapes)"); + sWhatsThis = "Part_CompOffset"; + sStatusTip = sToolTipText; } void CmdPartCompOffset::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("Part_Offset"); - else if (iMsg==1) + } + else if (iMsg == 1) { rcCmdMgr.runCommandByName("Part_Offset2D"); - else + } + else { return; + } // Since the default icon is reset when enabling/disabling the command we have // to explicitly set the icon of the used command. @@ -1751,7 +1962,7 @@ void CmdPartCompOffset::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompOffset::createAction() +Gui::Action* CmdPartCompOffset::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1776,10 +1987,11 @@ void CmdPartCompOffset::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); @@ -1796,15 +2008,21 @@ void CmdPartCompOffset::languageChange() if (cmdOffset2D) { QAction* cmd1 = a[1]; cmd1->setText(QApplication::translate(cmdOffset2D->className(), cmdOffset2D->getMenuText())); - cmd1->setToolTip(QApplication::translate(cmdOffset2D->className(), cmdOffset2D->getToolTipText())); - cmd1->setStatusTip(QApplication::translate(cmdOffset2D->className(), cmdOffset2D->getStatusTip())); + cmd1->setToolTip( + QApplication::translate(cmdOffset2D->className(), cmdOffset2D->getToolTipText()) + ); + cmd1->setStatusTip( + QApplication::translate(cmdOffset2D->className(), cmdOffset2D->getStatusTip()) + ); } } bool CmdPartCompOffset::isActive() { bool hasShapes = PartGui::hasShapesInSelection(); - std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); return (hasShapes && !Gui::Control().activeDialog() && docobjs.size() == 1); } //=========================================================================== @@ -1814,15 +2032,17 @@ bool CmdPartCompOffset::isActive() DEF_STD_CMD_A(CmdPartThickness) CmdPartThickness::CmdPartThickness() - : Command("Part_Thickness") + : Command("Part_Thickness") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Thickness"); - sToolTipText = QT_TR_NOOP("Removes the selected faces and offsets the remaining shape outward to add thickness"); - sWhatsThis = "Part_Thickness"; - sStatusTip = sToolTipText; - sPixmap = "Part_Thickness"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Thickness"); + sToolTipText = QT_TR_NOOP( + "Removes the selected faces and offsets the remaining shape outward to add thickness" + ); + sWhatsThis = "Part_Thickness"; + sStatusTip = sToolTipText; + sPixmap = "Part_Thickness"; } void CmdPartThickness::activated(int iMsg) @@ -1839,61 +2059,76 @@ void CmdPartThickness::activated(int iMsg) selection = selobjs[0].getAsPropertyLinkSubString(); const std::vector& subnames = selobjs[0].getSubNames(); obj = selobjs[0].getObject(); - topoShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + topoShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!topoShape.isNull()) { - for (std::vector::const_iterator it = subnames.begin(); it != subnames.end(); ++it) { + for (std::vector::const_iterator it = subnames.begin(); it != subnames.end(); + ++it) { subShapes.emplace_back(topoShape.getSubShape(subnames[0].c_str())); } - for (const auto & it : subShapes) { + for (const auto& it : subShapes) { TopoDS_Shape dsShape = it.getShape(); - if (dsShape.IsNull() || dsShape.ShapeType() != TopAbs_FACE) { //only face selection allowed + if (dsShape.IsNull() + || dsShape.ShapeType() != TopAbs_FACE) { // only face selection allowed ok = false; } } - } else { //could be not a part::feature or app:link to non-part::feature or app::part without a visible part::feature + } + else { // could be not a part::feature or app:link to non-part::feature or app::part + // without a visible part::feature ok = false; } - - } else { //not just one object selected + } + else { // not just one object selected ok = false; } int countSolids = 0; TopExp_Explorer xp; - if (!topoShape.isNull()){ + if (!topoShape.isNull()) { xp.Init(topoShape.getShape(), TopAbs_SOLID); - for (;xp.More(); xp.Next()) { + for (; xp.More(); xp.Next()) { countSolids++; } } if (countSolids != 1 || !ok) { - QMessageBox::warning(Gui::getMainWindow(), - QApplication::translate("CmdPartThickness", "Wrong selection"), - QApplication::translate("CmdPartThickness", "Selected shape is not a solid")); + QMessageBox::warning( + Gui::getMainWindow(), + QApplication::translate("CmdPartThickness", "Wrong selection"), + QApplication::translate("CmdPartThickness", "Selected shape is not a solid") + ); return; } std::string thick = getUniqueObjectName("Thickness"); openCommand(QT_TRANSLATE_NOOP("Command", "Make Thickness")); - doCommand(Doc,"App.ActiveDocument.addObject(\"Part::Thickness\",\"%s\")",thick.c_str()); - doCommand(Doc,"App.ActiveDocument.%s.Faces = %s" ,thick.c_str(), selection.c_str()); - doCommand(Doc,"App.ActiveDocument.%s.Value = 1.0",thick.c_str()); + doCommand(Doc, "App.ActiveDocument.addObject(\"Part::Thickness\",\"%s\")", thick.c_str()); + doCommand(Doc, "App.ActiveDocument.%s.Faces = %s", thick.c_str(), selection.c_str()); + doCommand(Doc, "App.ActiveDocument.%s.Value = 1.0", thick.c_str()); updateActive(); if (isActiveObjectValid()) { - doCommand(App,"App.getDocument(\"%s\").getObject(\"%s\").ViewObject.Visibility = False", - obj->getDocument()->getName(), obj->getNameInDocument()); + doCommand( + App, + "App.getDocument(\"%s\").getObject(\"%s\").ViewObject.Visibility = False", + obj->getDocument()->getName(), + obj->getNameInDocument() + ); } - doCommand(Gui,"Gui.ActiveDocument.setEdit('%s')",thick.c_str()); + doCommand(Gui, "Gui.ActiveDocument.setEdit('%s')", thick.c_str()); copyVisual(thick.c_str(), "ShapeAppearance", obj->getNameInDocument()); - copyVisual(thick.c_str(), "LineColor" , obj->getNameInDocument()); + copyVisual(thick.c_str(), "LineColor", obj->getNameInDocument()); copyVisual(thick.c_str(), "PointColor", obj->getNameInDocument()); } bool CmdPartThickness::isActive() { - bool objectsSelected = Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) > 0; + bool objectsSelected + = Gui::Selection().countObjectsOfType(nullptr, Gui::ResolveMode::FollowLink) + > 0; return (objectsSelected && !Gui::Control().activeDialog()); } @@ -1904,16 +2139,16 @@ bool CmdPartThickness::isActive() DEF_STD_CMD_A(CmdShapeInfo) CmdShapeInfo::CmdShapeInfo() - :Command("Part_ShapeInfo") + : Command("Part_ShapeInfo") { - sAppModule = "Part"; - sGroup = "Part"; - sMenuText = "Shape Info"; + sAppModule = "Part"; + sGroup = "Part"; + sMenuText = "Shape Info"; - sToolTipText = "Displays information about the selected shape"; - sWhatsThis = "Part_ShapeInfo"; - sStatusTip = sToolTipText; - sPixmap = "Part_ShapeInfo"; + sToolTipText = "Displays information about the selected shape"; + sWhatsThis = "Part_ShapeInfo"; + sStatusTip = sToolTipText; + sPixmap = "Part_ShapeInfo"; } void CmdShapeInfo::activated(int iMsg) @@ -1924,8 +2159,9 @@ void CmdShapeInfo::activated(int iMsg) bool CmdShapeInfo::isActive() { App::Document* doc = App::GetApplication().getActiveDocument(); - if (!doc || doc->countObjectsOfType() == 0) + if (!doc || doc->countObjectsOfType() == 0) { return false; + } Gui::MDIView* view = Gui::getMainWindow()->activeWindow(); if (view && view->isDerivedFrom()) { @@ -1943,15 +2179,15 @@ bool CmdShapeInfo::isActive() DEF_STD_CMD_A(CmdPartRuledSurface) CmdPartRuledSurface::CmdPartRuledSurface() - : Command("Part_RuledSurface") + : Command("Part_RuledSurface") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Ruled Surface"); - sToolTipText = QT_TR_NOOP("Creates a ruled surface between 2 selected wires"); - sWhatsThis = "Part_RuledSurface"; - sStatusTip = sToolTipText; - sPixmap = "Part_RuledSurface"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Ruled Surface"); + sToolTipText = QT_TR_NOOP("Creates a ruled surface between 2 selected wires"); + sWhatsThis = "Part_RuledSurface"; + sStatusTip = sToolTipText; + sPixmap = "Part_RuledSurface"; } void CmdPartRuledSurface::activated(int iMsg) @@ -1970,36 +2206,44 @@ void CmdPartRuledSurface::activated(int iMsg) if (ok && selobjs.size() <= 2) { if (!selobjs.empty()) { - const std::vector& subnames1= selobjs[0].getSubNames(); + const std::vector& subnames1 = selobjs[0].getSubNames(); docobj1 = selobjs[0].getObject(); obj1 = docobj1->getNameInDocument(); - obj2 = obj1; //changed later if 2 objects were selected - const Part::TopoShape& shape1 = Part::Feature::getTopoShape(docobj1, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + obj2 = obj1; // changed later if 2 objects were selected + const Part::TopoShape& shape1 = Part::Feature::getTopoShape( + docobj1, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (shape1.isNull()) { ok = false; } if (ok && subnames1.size() <= 2) { if (!subnames1.empty()) { - curve2 = Part::Feature::getTopoShape(docobj1, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subnames1[0].c_str()).getShape(); + curve2 = Part::Feature::getTopoShape( + docobj1, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subnames1[0].c_str() + ) + .getShape(); link1 = subnames1[0]; } if (subnames1.size() == 2) { - curve2 = Part::Feature::getTopoShape(docobj1, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subnames1[1].c_str()).getShape(); + curve2 = Part::Feature::getTopoShape( + docobj1, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subnames1[1].c_str() + ) + .getShape(); link2 = subnames1[1]; } if (subnames1.empty()) { curve1 = shape1.getShape(); } - } else { + } + else { ok = false; } } @@ -2008,19 +2252,25 @@ void CmdPartRuledSurface::activated(int iMsg) docobj2 = selobjs[1].getObject(); obj2 = docobj2->getNameInDocument(); - const Part::TopoShape& shape2 = Part::Feature::getTopoShape(docobj2, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + const Part::TopoShape& shape2 = Part::Feature::getTopoShape( + docobj2, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (shape2.isNull()) { ok = false; } if (ok && subnames2.size() == 1) { - curve2 = Part::Feature::getTopoShape(docobj2, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subnames2[0].c_str()).getShape(); + curve2 = Part::Feature::getTopoShape( + docobj2, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subnames2[0].c_str() + ) + .getShape(); link2 = subnames2[0]; - } else { + } + else { if (subnames2.empty()) { curve2 = shape2.getShape(); } @@ -2028,24 +2278,35 @@ void CmdPartRuledSurface::activated(int iMsg) } if (!curve1.IsNull() && !curve2.IsNull()) { if ((curve1.ShapeType() == TopAbs_EDGE || curve1.ShapeType() == TopAbs_WIRE) - && (curve2.ShapeType() == TopAbs_EDGE || curve2.ShapeType() == TopAbs_WIRE)) { + && (curve2.ShapeType() == TopAbs_EDGE || curve2.ShapeType() == TopAbs_WIRE)) { ok = true; } } } if (!ok) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select either 2 edges or 2 wires.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select either 2 edges or 2 wires.") + ); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Create ruled surface")); doCommand(Doc, "FreeCAD.ActiveDocument.addObject('Part::RuledSurface', 'Ruled Surface')"); - doCommand(Doc, "FreeCAD.ActiveDocument.ActiveObject.Curve1=(FreeCAD.ActiveDocument.%s,['%s'])" - ,obj1.c_str(), link1.c_str()); - doCommand(Doc, "FreeCAD.ActiveDocument.ActiveObject.Curve2=(FreeCAD.ActiveDocument.%s,['%s'])" - ,obj2.c_str(), link2.c_str()); + doCommand( + Doc, + "FreeCAD.ActiveDocument.ActiveObject.Curve1=(FreeCAD.ActiveDocument.%s,['%s'])", + obj1.c_str(), + link1.c_str() + ); + doCommand( + Doc, + "FreeCAD.ActiveDocument.ActiveObject.Curve2=(FreeCAD.ActiveDocument.%s,['%s'])", + obj2.c_str(), + link2.c_str() + ); commitCommand(); updateActive(); } @@ -2062,23 +2323,24 @@ bool CmdPartRuledSurface::isActive() DEF_STD_CMD_A(CmdCheckGeometry) CmdCheckGeometry::CmdCheckGeometry() - : Command("Part_CheckGeometry") + : Command("Part_CheckGeometry") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Check Geometry"); - sToolTipText = QT_TR_NOOP("Analyzes the selected shapes for errors"); - sWhatsThis = "Part_CheckGeometry"; - sStatusTip = sToolTipText; - sPixmap = "Part_CheckGeometry"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Check Geometry"); + sToolTipText = QT_TR_NOOP("Analyzes the selected shapes for errors"); + sWhatsThis = "Part_CheckGeometry"; + sStatusTip = sToolTipText; + sPixmap = "Part_CheckGeometry"; } void CmdCheckGeometry::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (!dlg) + if (!dlg) { dlg = new PartGui::TaskCheckGeometryDialog(); + } Gui::Control().showDialog(dlg); } @@ -2095,28 +2357,35 @@ bool CmdCheckGeometry::isActive() DEF_STD_CMD_A(CmdColorPerFace) CmdColorPerFace::CmdColorPerFace() - : Command("Part_ColorPerFace") + : Command("Part_ColorPerFace") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Appearance per &Face"); - sToolTipText = QT_TR_NOOP("Sets the appearance of individual faces of the selected object"); - sStatusTip = sToolTipText; - sWhatsThis = "Part_ColorPerFace"; - sPixmap = "Part_ColorFace"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Appearance per &Face"); + sToolTipText = QT_TR_NOOP("Sets the appearance of individual faces of the selected object"); + sStatusTip = sToolTipText; + sWhatsThis = "Part_ColorPerFace"; + sPixmap = "Part_ColorFace"; } void CmdColorPerFace::activated(int iMsg) { Q_UNUSED(iMsg); - if (getActiveGuiDocument()->getInEdit()) + if (getActiveGuiDocument()->getInEdit()) { getActiveGuiDocument()->resetEdit(); - std::vector sel = Gui::Selection().getObjectsOfType(Part::Feature::getClassTypeId()); - if (sel.empty()) + } + std::vector sel = Gui::Selection().getObjectsOfType( + Part::Feature::getClassTypeId() + ); + if (sel.empty()) { return; - PartGui::ViewProviderPartExt* vp = dynamic_cast(Gui::Application::Instance->getViewProvider(sel.front())); - if (vp) + } + PartGui::ViewProviderPartExt* vp = dynamic_cast( + Gui::Application::Instance->getViewProvider(sel.front()) + ); + if (vp) { vp->changeFaceAppearances(); + } } bool CmdColorPerFace::isActive() @@ -2132,15 +2401,15 @@ bool CmdColorPerFace::isActive() DEF_STD_CMD_A(CmdBoxSelection) CmdBoxSelection::CmdBoxSelection() - : Command("Part_BoxSelection") + : Command("Part_BoxSelection") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Box Selection"); - sToolTipText = QT_TR_NOOP("Selects elements in the 3D view using a box selection"); - sWhatsThis = "Part_BoxSelection"; - sStatusTip = QT_TR_NOOP("Box selection"); - sPixmap = "Part_BoxSelection"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Box Selection"); + sToolTipText = QT_TR_NOOP("Selects elements in the 3D view using a box selection"); + sWhatsThis = "Part_BoxSelection"; + sStatusTip = QT_TR_NOOP("Box selection"); + sPixmap = "Part_BoxSelection"; } void CmdBoxSelection::activated(int iMsg) @@ -2162,15 +2431,17 @@ bool CmdBoxSelection::isActive() DEF_STD_CMD_A(CmdPartProjectionOnSurface) CmdPartProjectionOnSurface::CmdPartProjectionOnSurface() - :Command("Part_ProjectionOnSurface") + : Command("Part_ProjectionOnSurface") { sAppModule = "Part"; sGroup = QT_TR_NOOP("Part"); sMenuText = QT_TR_NOOP("Project on Surface"); - sToolTipText = QT_TR_NOOP("Projects edges, wires, or faces of one shape\n" - "onto a face of another shape.\n" - "The camera view determines the direction\n" - "of the projection."); + sToolTipText = QT_TR_NOOP( + "Projects edges, wires, or faces of one shape\n" + "onto a face of another shape.\n" + "The camera view determines the direction\n" + "of the projection." + ); sWhatsThis = "Part_ProjectionOnSurface"; sStatusTip = sToolTipText; sPixmap = "Part_ProjectionOnSurface"; @@ -2200,8 +2471,10 @@ CmdPartSectionCut::CmdPartSectionCut() sAppModule = "Part"; sGroup = "View"; sMenuText = QT_TR_NOOP("Persiste&nt Section Cut"); - sToolTipText = QT_TR_NOOP("Creates a new object as a boolean intersection of all visible " - "shapes and the selected axis planes"); + sToolTipText = QT_TR_NOOP( + "Creates a new object as a boolean intersection of all visible " + "shapes and the selected axis planes" + ); sWhatsThis = "Part_SectionCut"; sStatusTip = sToolTipText; sPixmap = "Part_SectionCut"; @@ -2233,23 +2506,28 @@ bool CmdPartSectionCut::isActive() // Part_CoordinateSystem //=========================================================================== -namespace { - QString getAutoGroupCommandStr() - // Helper function to get the python code to add the newly created object to the active Part/Body object if present - { - App::GeoFeature* activeObj = Gui::Application::Instance->activeView()->getActiveObject(PDBODYKEY); - if (!activeObj) { - activeObj = Gui::Application::Instance->activeView()->getActiveObject(PARTKEY); - } - - if (activeObj) { - QString activeName = QString::fromLatin1(activeObj->getNameInDocument()); - return QStringLiteral("App.ActiveDocument.getObject('%1\').addObject(obj)\n").arg(activeName); - } - - return QStringLiteral("# Object created at document root."); +namespace +{ +QString getAutoGroupCommandStr() +// Helper function to get the python code to add the newly created object to the active Part/Body +// object if present +{ + App::GeoFeature* activeObj + = Gui::Application::Instance->activeView()->getActiveObject(PDBODYKEY); + if (!activeObj) { + activeObj = Gui::Application::Instance->activeView()->getActiveObject( + PARTKEY + ); } + + if (activeObj) { + QString activeName = QString::fromLatin1(activeObj->getNameInDocument()); + return QStringLiteral("App.ActiveDocument.getObject('%1\').addObject(obj)\n").arg(activeName); + } + + return QStringLiteral("# Object created at document root."); } +} // namespace DEF_STD_CMD_A(CmdPartCoordinateSystem) @@ -2271,7 +2549,11 @@ void CmdPartCoordinateSystem::activated(int iMsg) openCommand(QT_TRANSLATE_NOOP("Command", "Add coordinate system")); std::string name = getUniqueObjectName("LCS"); - doCommand(Doc, "obj = App.activeDocument().addObject('Part::LocalCoordinateSystem','%s')", name.c_str()); + doCommand( + Doc, + "obj = App.activeDocument().addObject('Part::LocalCoordinateSystem','%s')", + name.c_str() + ); doCommand(Doc, getAutoGroupCommandStr().toUtf8()); doCommand(Doc, "obj.Visibility = True"); doCommand(Doc, "obj.ViewObject.doubleClicked()"); @@ -2385,7 +2667,7 @@ bool CmdPartDatumPoint::isActive() //=========================================================================== // Part_Datums //=========================================================================== -class CmdPartDatums : public Gui::GroupCommand +class CmdPartDatums: public Gui::GroupCommand { public: CmdPartDatums() @@ -2393,7 +2675,8 @@ public: { sGroup = QT_TR_NOOP("Part"); sMenuText = QT_TR_NOOP("Datums"); - sToolTipText = QT_TR_NOOP("Creates a datum object (coordinate system, plane, line, or point) that can be attached to other objects"); + sToolTipText + = QT_TR_NOOP("Creates a datum object (coordinate system, plane, line, or point) that can be attached to other objects"); sWhatsThis = "Part_Datums"; sStatusTip = sToolTipText; @@ -2419,7 +2702,7 @@ public: void CreatePartCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPartMakeSolid()); rcCmdMgr.addCommand(new CmdPartReverseShape()); @@ -2467,4 +2750,3 @@ void CreatePartCommands() rcCmdMgr.addCommand(new CmdPartDatumPoint()); rcCmdMgr.addCommand(new CmdPartDatums()); } - diff --git a/src/Mod/Part/Gui/CommandFilter.cpp b/src/Mod/Part/Gui/CommandFilter.cpp index e9db6ee446..be134234f1 100644 --- a/src/Mod/Part/Gui/CommandFilter.cpp +++ b/src/Mod/Part/Gui/CommandFilter.cpp @@ -40,30 +40,30 @@ DEF_STD_CMD_ACL(PartCmdSelectFilter) PartCmdSelectFilter::PartCmdSelectFilter() - : Command("Part_SelectFilter") + : Command("Part_SelectFilter") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Selection Filter"); - sToolTipText = QT_TR_NOOP("Changes the selection filter"); - sStatusTip = sToolTipText; - sWhatsThis = "Part_SelectFilter"; - sPixmap = "clear-selection"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Selection Filter"); + sToolTipText = QT_TR_NOOP("Changes the selection filter"); + sStatusTip = sToolTipText; + sWhatsThis = "Part_SelectFilter"; + sPixmap = "clear-selection"; + eType = Alter3DView; } void PartCmdSelectFilter::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("Part_VertexSelection"); } - else if (iMsg==1) { + else if (iMsg == 1) { rcCmdMgr.runCommandByName("Part_EdgeSelection"); } - else if (iMsg==2) { + else if (iMsg == 2) { rcCmdMgr.runCommandByName("Part_FaceSelection"); } - else if (iMsg==3) { + else if (iMsg == 3) { rcCmdMgr.runCommandByName("Part_RemoveSelectionGate"); } else { @@ -79,7 +79,7 @@ void PartCmdSelectFilter::activated(int iMsg) pcAction->setIcon(act[iMsg]->icon()); } -Gui::Action * PartCmdSelectFilter::createAction() +Gui::Action* PartCmdSelectFilter::createAction() { auto pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -116,7 +116,7 @@ void PartCmdSelectFilter::languageChange() return; } - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); auto pcAction = qobject_cast(_pcAction); QList act = pcAction->actions(); @@ -124,33 +124,53 @@ void PartCmdSelectFilter::languageChange() Gui::Command* vertexSelection = rcCmdMgr.getCommandByName("Part_VertexSelection"); if (vertexSelection) { QAction* cmd0 = act[0]; - cmd0->setText(QApplication::translate("PartCmdVertexSelection", vertexSelection->getMenuText())); - cmd0->setToolTip(QApplication::translate("PartCmdVertexSelection", vertexSelection->getToolTipText())); - cmd0->setStatusTip(QApplication::translate("PartCmdVertexSelection", vertexSelection->getStatusTip())); + cmd0->setText( + QApplication::translate("PartCmdVertexSelection", vertexSelection->getMenuText()) + ); + cmd0->setToolTip( + QApplication::translate("PartCmdVertexSelection", vertexSelection->getToolTipText()) + ); + cmd0->setStatusTip( + QApplication::translate("PartCmdVertexSelection", vertexSelection->getStatusTip()) + ); } Gui::Command* edgeSelection = rcCmdMgr.getCommandByName("Part_EdgeSelection"); if (edgeSelection) { QAction* cmd1 = act[1]; cmd1->setText(QApplication::translate("PartCmdEdgeSelection", edgeSelection->getMenuText())); - cmd1->setToolTip(QApplication::translate("PartCmdEdgeSelection", edgeSelection->getToolTipText())); - cmd1->setStatusTip(QApplication::translate("PartCmdEdgeSelection", edgeSelection->getStatusTip())); + cmd1->setToolTip( + QApplication::translate("PartCmdEdgeSelection", edgeSelection->getToolTipText()) + ); + cmd1->setStatusTip( + QApplication::translate("PartCmdEdgeSelection", edgeSelection->getStatusTip()) + ); } Gui::Command* faceSelection = rcCmdMgr.getCommandByName("Part_FaceSelection"); if (faceSelection) { QAction* cmd1 = act[2]; cmd1->setText(QApplication::translate("PartCmdFaceSelection", faceSelection->getMenuText())); - cmd1->setToolTip(QApplication::translate("PartCmdFaceSelection", faceSelection->getToolTipText())); - cmd1->setStatusTip(QApplication::translate("PartCmdFaceSelection", faceSelection->getStatusTip())); + cmd1->setToolTip( + QApplication::translate("PartCmdFaceSelection", faceSelection->getToolTipText()) + ); + cmd1->setStatusTip( + QApplication::translate("PartCmdFaceSelection", faceSelection->getStatusTip()) + ); } Gui::Command* removeSelection = rcCmdMgr.getCommandByName("Part_RemoveSelectionGate"); if (removeSelection) { QAction* cmd2 = act[3]; - cmd2->setText(QApplication::translate("PartCmdRemoveSelectionGate", removeSelection->getMenuText())); - cmd2->setToolTip(QApplication::translate("PartCmdRemoveSelectionGate", removeSelection->getToolTipText())); - cmd2->setStatusTip(QApplication::translate("PartCmdRemoveSelectionGate", removeSelection->getStatusTip())); + cmd2->setText( + QApplication::translate("PartCmdRemoveSelectionGate", removeSelection->getMenuText()) + ); + cmd2->setToolTip( + QApplication::translate("PartCmdRemoveSelectionGate", removeSelection->getToolTipText()) + ); + cmd2->setStatusTip( + QApplication::translate("PartCmdRemoveSelectionGate", removeSelection->getStatusTip()) + ); } } @@ -167,22 +187,22 @@ bool PartCmdSelectFilter::isActive() DEF_3DV_CMD(PartCmdVertexSelection) PartCmdVertexSelection::PartCmdVertexSelection() - : Command("Part_VertexSelection") + : Command("Part_VertexSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Vertex Selection"); - sToolTipText = QT_TR_NOOP("Only allows the selection of vertices"); - sWhatsThis = "Part_VertexSelection"; - sStatusTip = sToolTipText; - sPixmap = "vertex-selection"; - sAccel = "X, S"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Vertex Selection"); + sToolTipText = QT_TR_NOOP("Only allows the selection of vertices"); + sWhatsThis = "Part_VertexSelection"; + sStatusTip = sToolTipText; + sPixmap = "vertex-selection"; + sAccel = "X, S"; + eType = Alter3DView; } void PartCmdVertexSelection::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Vertex SELECT App::Link SUBELEMENT Vertex')"); + doCommand(Command::Gui, "Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Vertex SELECT App::Link SUBELEMENT Vertex')"); } @@ -192,22 +212,22 @@ void PartCmdVertexSelection::activated(int iMsg) DEF_3DV_CMD(PartCmdEdgeSelection) PartCmdEdgeSelection::PartCmdEdgeSelection() - : Command("Part_EdgeSelection") + : Command("Part_EdgeSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Edge Selection"); - sToolTipText = QT_TR_NOOP("Only allows the selection of edges"); - sWhatsThis = "Part_EdgeSelection"; - sStatusTip = sToolTipText; - sPixmap = "edge-selection"; - sAccel = "E, S"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Edge Selection"); + sToolTipText = QT_TR_NOOP("Only allows the selection of edges"); + sWhatsThis = "Part_EdgeSelection"; + sStatusTip = sToolTipText; + sPixmap = "edge-selection"; + sAccel = "E, S"; + eType = Alter3DView; } void PartCmdEdgeSelection::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Edge SELECT App::Link SUBELEMENT Edge')"); + doCommand(Command::Gui, "Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Edge SELECT App::Link SUBELEMENT Edge')"); } @@ -217,22 +237,22 @@ void PartCmdEdgeSelection::activated(int iMsg) DEF_3DV_CMD(PartCmdFaceSelection) PartCmdFaceSelection::PartCmdFaceSelection() - : Command("Part_FaceSelection") + : Command("Part_FaceSelection") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Face Selection"); - sToolTipText = QT_TR_NOOP("Only allows the selection of faces"); - sWhatsThis = "Part_FaceSelection"; - sStatusTip = sToolTipText; - sPixmap = "face-selection"; - sAccel = "F, S"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("Face Selection"); + sToolTipText = QT_TR_NOOP("Only allows the selection of faces"); + sWhatsThis = "Part_FaceSelection"; + sStatusTip = sToolTipText; + sPixmap = "face-selection"; + sAccel = "F, S"; + eType = Alter3DView; } void PartCmdFaceSelection::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Face SELECT App::Link SUBELEMENT Face')"); + doCommand(Command::Gui, "Gui.Selection.addSelectionGate('SELECT Part::Feature SUBELEMENT Face SELECT App::Link SUBELEMENT Face')"); } @@ -242,27 +262,27 @@ void PartCmdFaceSelection::activated(int iMsg) DEF_3DV_CMD(PartCmdRemoveSelectionGate) PartCmdRemoveSelectionGate::PartCmdRemoveSelectionGate() - : Command("Part_RemoveSelectionGate") + : Command("Part_RemoveSelectionGate") { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("No Selection Filters"); - sToolTipText = QT_TR_NOOP("Clears all selection filters"); - sWhatsThis = "Part_RemoveSelectionGate"; - sStatusTip = sToolTipText; - sPixmap = "clear-selection"; - sAccel = "C, S"; - eType = Alter3DView; + sGroup = "Standard-View"; + sMenuText = QT_TR_NOOP("No Selection Filters"); + sToolTipText = QT_TR_NOOP("Clears all selection filters"); + sWhatsThis = "Part_RemoveSelectionGate"; + sStatusTip = sToolTipText; + sPixmap = "clear-selection"; + sAccel = "C, S"; + eType = Alter3DView; } void PartCmdRemoveSelectionGate::activated(int iMsg) { Q_UNUSED(iMsg); - doCommand(Command::Gui,"Gui.Selection.removeSelectionGate()"); + doCommand(Command::Gui, "Gui.Selection.removeSelectionGate()"); } void CreatePartSelectCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); // NOLINTBEGIN rcCmdMgr.addCommand(new PartCmdSelectFilter()); rcCmdMgr.addCommand(new PartCmdVertexSelection()); diff --git a/src/Mod/Part/Gui/CommandParametric.cpp b/src/Mod/Part/Gui/CommandParametric.cpp index cb7012d34f..cd6d152c26 100644 --- a/src/Mod/Part/Gui/CommandParametric.cpp +++ b/src/Mod/Part/Gui/CommandParametric.cpp @@ -23,8 +23,7 @@ ***************************************************************************/ - -# include +#include #include @@ -37,20 +36,26 @@ //=========================================================================== // Utils //=========================================================================== -namespace { -QString getAutoGroupCommandStr() -// Helper function to get the python code to add the newly created object to the active Part object if present +namespace { - App::Part* activePart = Gui::Application::Instance->activeView()->getActiveObject("part"); +QString getAutoGroupCommandStr() +// Helper function to get the python code to add the newly created object to the active Part object +// if present +{ + App::Part* activePart = Gui::Application::Instance->activeView()->getActiveObject( + "part" + ); if (activePart) { QString activePartName = QString::fromLatin1(activePart->getNameInDocument()); - return QStringLiteral("App.ActiveDocument.getObject('%1\')." - "addObject(App.ActiveDocument.ActiveObject)\n") + return QStringLiteral( + "App.ActiveDocument.getObject('%1\')." + "addObject(App.ActiveDocument.ActiveObject)\n" + ) .arg(activePartName); } return QStringLiteral("# Object created at document root."); } -} +} // namespace //=========================================================================== // Part_Cylinder @@ -58,28 +63,28 @@ QString getAutoGroupCommandStr() DEF_STD_CMD_A(CmdPartCylinder) CmdPartCylinder::CmdPartCylinder() - : Command("Part_Cylinder") + : Command("Part_Cylinder") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Cylinder"); - sToolTipText = QT_TR_NOOP("Creates a solid cylinder"); - sWhatsThis = "Part_Cylinder"; - sStatusTip = sToolTipText; - sPixmap = "Part_Cylinder_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Cylinder"); + sToolTipText = QT_TR_NOOP("Creates a solid cylinder"); + sWhatsThis = "Part_Cylinder"; + sStatusTip = sToolTipText; + sPixmap = "Part_Cylinder_Parametric"; } void CmdPartCylinder::activated(int iMsg) { Q_UNUSED(iMsg); QString cmd; - cmd = qApp->translate("CmdPartCylinder","Cylinder"); + cmd = qApp->translate("CmdPartCylinder", "Cylinder"); openCommand((const char*)cmd.toUtf8()); - runCommand(Doc,"App.ActiveDocument.addObject(\"Part::Cylinder\",\"Cylinder\")"); + runCommand(Doc, "App.ActiveDocument.addObject(\"Part::Cylinder\",\"Cylinder\")"); cmd = QStringLiteral("App.ActiveDocument.ActiveObject.Label = \"%1\"") - .arg(qApp->translate("CmdPartCylinder","Cylinder")); - runCommand(Doc,cmd.toUtf8()); + .arg(qApp->translate("CmdPartCylinder", "Cylinder")); + runCommand(Doc, cmd.toUtf8()); runCommand(Doc, getAutoGroupCommandStr().toUtf8()); commitCommand(); updateActive(); @@ -88,10 +93,12 @@ void CmdPartCylinder::activated(int iMsg) bool CmdPartCylinder::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -100,28 +107,28 @@ bool CmdPartCylinder::isActive() DEF_STD_CMD_A(CmdPartBox) CmdPartBox::CmdPartBox() - : Command("Part_Box") + : Command("Part_Box") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Cube"); - sToolTipText = QT_TR_NOOP("Creates a solid cube"); - sWhatsThis = "Part_Box"; - sStatusTip = sToolTipText; - sPixmap = "Part_Box_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Cube"); + sToolTipText = QT_TR_NOOP("Creates a solid cube"); + sWhatsThis = "Part_Box"; + sStatusTip = sToolTipText; + sPixmap = "Part_Box_Parametric"; } void CmdPartBox::activated(int iMsg) { Q_UNUSED(iMsg); QString cmd; - cmd = qApp->translate("CmdPartBox","Cube"); + cmd = qApp->translate("CmdPartBox", "Cube"); openCommand((const char*)cmd.toUtf8()); - runCommand(Doc,"App.ActiveDocument.addObject(\"Part::Box\",\"Box\")"); + runCommand(Doc, "App.ActiveDocument.addObject(\"Part::Box\",\"Box\")"); cmd = QStringLiteral("App.ActiveDocument.ActiveObject.Label = \"%1\"") - .arg(qApp->translate("CmdPartBox","Cube")); - runCommand(Doc,cmd.toUtf8()); + .arg(qApp->translate("CmdPartBox", "Cube")); + runCommand(Doc, cmd.toUtf8()); runCommand(Doc, getAutoGroupCommandStr().toUtf8()); commitCommand(); updateActive(); @@ -130,10 +137,12 @@ void CmdPartBox::activated(int iMsg) bool CmdPartBox::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -142,28 +151,28 @@ bool CmdPartBox::isActive() DEF_STD_CMD_A(CmdPartSphere) CmdPartSphere::CmdPartSphere() - : Command("Part_Sphere") + : Command("Part_Sphere") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Sphere"); - sToolTipText = QT_TR_NOOP("Creates a solid sphere"); - sWhatsThis = "Part_Sphere"; - sStatusTip = sToolTipText; - sPixmap = "Part_Sphere_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Sphere"); + sToolTipText = QT_TR_NOOP("Creates a solid sphere"); + sWhatsThis = "Part_Sphere"; + sStatusTip = sToolTipText; + sPixmap = "Part_Sphere_Parametric"; } void CmdPartSphere::activated(int iMsg) { Q_UNUSED(iMsg); QString cmd; - cmd = qApp->translate("CmdPartSphere","Sphere"); + cmd = qApp->translate("CmdPartSphere", "Sphere"); openCommand((const char*)cmd.toUtf8()); - runCommand(Doc,"App.ActiveDocument.addObject(\"Part::Sphere\",\"Sphere\")"); + runCommand(Doc, "App.ActiveDocument.addObject(\"Part::Sphere\",\"Sphere\")"); cmd = QStringLiteral("App.ActiveDocument.ActiveObject.Label = \"%1\"") - .arg(qApp->translate("CmdPartSphere","Sphere")); - runCommand(Doc,cmd.toUtf8()); + .arg(qApp->translate("CmdPartSphere", "Sphere")); + runCommand(Doc, cmd.toUtf8()); runCommand(Doc, getAutoGroupCommandStr().toUtf8()); commitCommand(); updateActive(); @@ -172,10 +181,12 @@ void CmdPartSphere::activated(int iMsg) bool CmdPartSphere::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -184,28 +195,28 @@ bool CmdPartSphere::isActive() DEF_STD_CMD_A(CmdPartCone) CmdPartCone::CmdPartCone() - : Command("Part_Cone") + : Command("Part_Cone") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Cone"); - sToolTipText = QT_TR_NOOP("Creates a solid cone"); - sWhatsThis = "Part_Cone"; - sStatusTip = sToolTipText; - sPixmap = "Part_Cone_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Cone"); + sToolTipText = QT_TR_NOOP("Creates a solid cone"); + sWhatsThis = "Part_Cone"; + sStatusTip = sToolTipText; + sPixmap = "Part_Cone_Parametric"; } void CmdPartCone::activated(int iMsg) { Q_UNUSED(iMsg); QString cmd; - cmd = qApp->translate("CmdPartCone","Cone"); + cmd = qApp->translate("CmdPartCone", "Cone"); openCommand((const char*)cmd.toUtf8()); - runCommand(Doc,"App.ActiveDocument.addObject(\"Part::Cone\",\"Cone\")"); + runCommand(Doc, "App.ActiveDocument.addObject(\"Part::Cone\",\"Cone\")"); cmd = QStringLiteral("App.ActiveDocument.ActiveObject.Label = \"%1\"") - .arg(qApp->translate("CmdPartCone","Cone")); - runCommand(Doc,cmd.toUtf8()); + .arg(qApp->translate("CmdPartCone", "Cone")); + runCommand(Doc, cmd.toUtf8()); runCommand(Doc, getAutoGroupCommandStr().toUtf8()); commitCommand(); updateActive(); @@ -214,10 +225,12 @@ void CmdPartCone::activated(int iMsg) bool CmdPartCone::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -226,28 +239,28 @@ bool CmdPartCone::isActive() DEF_STD_CMD_A(CmdPartTorus) CmdPartTorus::CmdPartTorus() - : Command("Part_Torus") + : Command("Part_Torus") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Torus"); - sToolTipText = QT_TR_NOOP("Creates a solid torus"); - sWhatsThis = "Part_Torus"; - sStatusTip = sToolTipText; - sPixmap = "Part_Torus_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Torus"); + sToolTipText = QT_TR_NOOP("Creates a solid torus"); + sWhatsThis = "Part_Torus"; + sStatusTip = sToolTipText; + sPixmap = "Part_Torus_Parametric"; } void CmdPartTorus::activated(int iMsg) { Q_UNUSED(iMsg); QString cmd; - cmd = qApp->translate("CmdPartTorus","Torus"); + cmd = qApp->translate("CmdPartTorus", "Torus"); openCommand((const char*)cmd.toUtf8()); - runCommand(Doc,"App.ActiveDocument.addObject(\"Part::Torus\",\"Torus\")"); + runCommand(Doc, "App.ActiveDocument.addObject(\"Part::Torus\",\"Torus\")"); cmd = QStringLiteral("App.ActiveDocument.ActiveObject.Label = \"%1\"") - .arg(qApp->translate("CmdPartTorus","Torus")); - runCommand(Doc,cmd.toUtf8()); + .arg(qApp->translate("CmdPartTorus", "Torus")); + runCommand(Doc, cmd.toUtf8()); runCommand(Doc, getAutoGroupCommandStr().toUtf8()); commitCommand(); updateActive(); @@ -256,10 +269,12 @@ void CmdPartTorus::activated(int iMsg) bool CmdPartTorus::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } @@ -267,7 +282,7 @@ bool CmdPartTorus::isActive() void CreateParamPartCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPartCylinder()); rcCmdMgr.addCommand(new CmdPartBox()); rcCmdMgr.addCommand(new CmdPartSphere()); diff --git a/src/Mod/Part/Gui/CommandSimple.cpp b/src/Mod/Part/Gui/CommandSimple.cpp index 575a246693..854446bc61 100644 --- a/src/Mod/Part/Gui/CommandSimple.cpp +++ b/src/Mod/Part/Gui/CommandSimple.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ -# include +#include #include @@ -49,35 +49,42 @@ DEF_STD_CMD_A(CmdPartSimpleCylinder) CmdPartSimpleCylinder::CmdPartSimpleCylinder() - :Command("Part_SimpleCylinder") + : Command("Part_SimpleCylinder") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Cylinder"); - sToolTipText = QT_TR_NOOP("Creates a solid cylinder"); - sWhatsThis = "Part_SimpleCylinder"; - sStatusTip = sToolTipText; - sPixmap = "Part_Cylinder_Parametric"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Cylinder"); + sToolTipText = QT_TR_NOOP("Creates a solid cylinder"); + sWhatsThis = "Part_SimpleCylinder"; + sStatusTip = sToolTipText; + sPixmap = "Part_Cylinder_Parametric"; } void CmdPartSimpleCylinder::activated(int iMsg) { Q_UNUSED(iMsg); PartGui::DlgPartCylinderImp dlg(Gui::getMainWindow()); - if (dlg.exec()== QDialog::Accepted) { + if (dlg.exec() == QDialog::Accepted) { Base::Vector3d dir = dlg.getDirection(); Base::Vector3d pos = dlg.getPosition(); openCommand(QT_TRANSLATE_NOOP("Command", "Create Cylinder")); - doCommand(Doc,"from FreeCAD import Base"); - doCommand(Doc,"import Part"); - doCommand(Doc,"App.ActiveDocument.addObject(\"Part::Feature\",\"Cylinder\")" - ".Shape=Part.makeCylinder(%f,%f," - "Base.Vector(%f,%f,%f)," - "Base.Vector(%f,%f,%f))" - ,dlg.getRadius() - ,dlg.getLength() - ,pos.x,pos.y,pos.z - ,dir.x,dir.y,dir.z); + doCommand(Doc, "from FreeCAD import Base"); + doCommand(Doc, "import Part"); + doCommand( + Doc, + "App.ActiveDocument.addObject(\"Part::Feature\",\"Cylinder\")" + ".Shape=Part.makeCylinder(%f,%f," + "Base.Vector(%f,%f,%f)," + "Base.Vector(%f,%f,%f))", + dlg.getRadius(), + dlg.getLength(), + pos.x, + pos.y, + pos.z, + dir.x, + dir.y, + dir.z + ); commitCommand(); updateActive(); doCommand(Gui, "Gui.SendMsgToActiveView(\"ViewFit\")"); @@ -86,10 +93,12 @@ void CmdPartSimpleCylinder::activated(int iMsg) bool CmdPartSimpleCylinder::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } @@ -99,15 +108,15 @@ bool CmdPartSimpleCylinder::isActive() DEF_STD_CMD_A(CmdPartShapeFromMesh) CmdPartShapeFromMesh::CmdPartShapeFromMesh() - :Command("Part_ShapeFromMesh") + : Command("Part_ShapeFromMesh") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Shape From Mesh"); - sToolTipText = QT_TR_NOOP("Creates a shape from the selected mesh"); - sWhatsThis = "Part_ShapeFromMesh"; - sStatusTip = sToolTipText; - sPixmap = "Part_Shape_from_Mesh"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Shape From Mesh"); + sToolTipText = QT_TR_NOOP("Creates a shape from the selected mesh"); + sWhatsThis = "Part_ShapeFromMesh"; + sStatusTip = sToolTipText; + sPixmap = "Part_Shape_from_Mesh"; } void CmdPartShapeFromMesh::activated(int iMsg) @@ -127,15 +136,15 @@ bool CmdPartShapeFromMesh::isActive() DEF_STD_CMD_A(CmdPartPointsFromMesh) CmdPartPointsFromMesh::CmdPartPointsFromMesh() - :Command("Part_PointsFromMesh") + : Command("Part_PointsFromMesh") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Points From Shape"); - sToolTipText = QT_TR_NOOP("Creates distributed points from the selected shape"); - sWhatsThis = "Part_PointsFromMesh"; - sStatusTip = sToolTipText; - sPixmap = "Part_PointsFromMesh"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Points From Shape"); + sToolTipText = QT_TR_NOOP("Creates distributed points from the selected shape"); + sWhatsThis = "Part_PointsFromMesh"; + sStatusTip = sToolTipText; + sPixmap = "Part_PointsFromMesh"; } void CmdPartPointsFromMesh::activated(int iMsg) @@ -144,7 +153,7 @@ void CmdPartPointsFromMesh::activated(int iMsg) auto getDefaultDistance = [](Part::Feature* geometry) { auto bbox = geometry->Shape.getBoundingBox(); - int steps{20}; + int steps {20}; return bbox.CalcDiagonalLength() / steps; }; @@ -152,7 +161,7 @@ void CmdPartPointsFromMesh::activated(int iMsg) std::vector geoms; geoms = Gui::Selection().getObjectsOfType(geoid); - double distance{1.0}; + double distance {1.0}; auto found = std::find_if(geoms.begin(), geoms.end(), [](App::DocumentObject* obj) { return freecad_cast(obj); }); @@ -166,11 +175,22 @@ void CmdPartPointsFromMesh::activated(int iMsg) int decimals = Base::UnitsApi::getDecimals(); double tolerance_from_decimals = pow(10., -decimals); - double minimal_tolerance = tolerance_from_decimals < STD_OCC_TOLERANCE ? STD_OCC_TOLERANCE : tolerance_from_decimals; + double minimal_tolerance = tolerance_from_decimals < STD_OCC_TOLERANCE + ? STD_OCC_TOLERANCE + : tolerance_from_decimals; bool ok; - distance = QInputDialog::getDouble(Gui::getMainWindow(), QObject::tr("Distance in parameter space"), - QObject::tr("Enter distance:"), defaultDistance, minimal_tolerance, 10.0 * defaultDistance, decimals, &ok, Qt::MSWindowsFixedSizeDialogHint); + distance = QInputDialog::getDouble( + Gui::getMainWindow(), + QObject::tr("Distance in parameter space"), + QObject::tr("Enter distance:"), + defaultDistance, + minimal_tolerance, + 10.0 * defaultDistance, + decimals, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok) { return; } @@ -213,54 +233,67 @@ bool CmdPartPointsFromMesh::isActive() DEF_STD_CMD_A(CmdPartSimpleCopy) CmdPartSimpleCopy::CmdPartSimpleCopy() - : Command("Part_SimpleCopy") + : Command("Part_SimpleCopy") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Simple Copy"); - sToolTipText = QT_TR_NOOP("Creates a simple non-parametric copy of the selected shapes"); - sWhatsThis = "Part_SimpleCopy"; - sStatusTip = sToolTipText; - sPixmap = "Part_3D_object"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Simple Copy"); + sToolTipText = QT_TR_NOOP("Creates a simple non-parametric copy of the selected shapes"); + sWhatsThis = "Part_SimpleCopy"; + sStatusTip = sToolTipText; + sPixmap = "Part_3D_object"; } -static void _copyShape(const char *cmdName, bool resolve,bool needElement=false, bool refine=false) { +static void _copyShape(const char* cmdName, bool resolve, bool needElement = false, bool refine = false) +{ Gui::WaitCursor wc; Gui::Command::openCommand(cmdName); - for(auto &sel : Gui::Selection().getSelectionEx("*", App::DocumentObject::getClassTypeId(), - resolve ? Gui::ResolveMode::OldStyleElement : Gui::ResolveMode::NoResolve)) { - std::map subMap; + for (auto& sel : Gui::Selection().getSelectionEx( + "*", + App::DocumentObject::getClassTypeId(), + resolve ? Gui::ResolveMode::OldStyleElement : Gui::ResolveMode::NoResolve + )) { + std::map subMap; auto obj = sel.getObject(); - if (!obj) + if (!obj) { continue; + } if (resolve || !sel.hasSubNames()) { - subMap.emplace("",obj); + subMap.emplace("", obj); } else { - for(const auto &sub : sel.getSubNames()) { - const char *element = nullptr; - auto sobj = obj->resolve(sub.c_str(),nullptr,nullptr,&element); - if(!sobj) continue; - if(!needElement && element) - subMap.emplace(sub.substr(0,element-sub.c_str()),sobj); - else - subMap.emplace(sub,sobj); + for (const auto& sub : sel.getSubNames()) { + const char* element = nullptr; + auto sobj = obj->resolve(sub.c_str(), nullptr, nullptr, &element); + if (!sobj) { + continue; + } + if (!needElement && element) { + subMap.emplace(sub.substr(0, element - sub.c_str()), sobj); + } + else { + subMap.emplace(sub, sobj); + } } - if(subMap.empty()) + if (subMap.empty()) { continue; + } } auto parentName = Gui::Command::getObjectCmd(obj); - for(auto &v : subMap) { - Gui::Command::doCommand(Gui::Command::Doc, - "__shape = Part.getShape(%s,'%s',needSubElement=%s,refine=%s)%s\n" - "App.ActiveDocument.addObject('Part::Feature','%s').Shape=__shape\n" - "App.ActiveDocument.ActiveObject.Label=%s.Label\n", - parentName.c_str(), v.first.c_str(), - needElement ? "True" : "False", - refine ? "True" : "False", - needElement ? ".copy()" : "", - v.second->getNameInDocument(), - Gui::Command::getObjectCmd(v.second).c_str()); + for (auto& v : subMap) { + Gui::Command::doCommand( + Gui::Command::Doc, + "__shape = Part.getShape(%s,'%s',needSubElement=%s,refine=%s)%s\n" + "App.ActiveDocument.addObject('Part::Feature','%s').Shape=__shape\n" + "App.ActiveDocument.ActiveObject.Label=%s.Label\n", + parentName.c_str(), + v.first.c_str(), + needElement ? "True" : "False", + refine ? "True" : "False", + needElement ? ".copy()" : "", + v.second->getNameInDocument(), + Gui::Command::getObjectCmd(v.second).c_str() + ); auto newObj = App::GetApplication().getActiveDocument()->getActiveObject(); Gui::Command::copyVisual(newObj, "ShapeAppearance", v.second); Gui::Command::copyVisual(newObj, "LineColor", v.second); @@ -274,7 +307,7 @@ static void _copyShape(const char *cmdName, bool resolve,bool needElement=false, void CmdPartSimpleCopy::activated(int iMsg) { Q_UNUSED(iMsg); - _copyShape("Simple copy",true); + _copyShape("Simple copy", true); } bool CmdPartSimpleCopy::isActive() @@ -288,21 +321,23 @@ bool CmdPartSimpleCopy::isActive() DEF_STD_CMD_A(CmdPartTransformedCopy) CmdPartTransformedCopy::CmdPartTransformedCopy() - : Command("Part_TransformedCopy") + : Command("Part_TransformedCopy") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Transformed Copy"); - sToolTipText = QT_TR_NOOP("Creates a non-parametric copy with transformed placement of the selected shapes"); - sWhatsThis = "Part_TransformCopy"; - sStatusTip = sToolTipText; - sPixmap = "Part_Transformed_Copy.svg"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Transformed Copy"); + sToolTipText = QT_TR_NOOP( + "Creates a non-parametric copy with transformed placement of the selected shapes" + ); + sWhatsThis = "Part_TransformCopy"; + sStatusTip = sToolTipText; + sPixmap = "Part_Transformed_Copy.svg"; } void CmdPartTransformedCopy::activated(int iMsg) { Q_UNUSED(iMsg); - _copyShape("Transformed copy",false); + _copyShape("Transformed copy", false); } bool CmdPartTransformedCopy::isActive() @@ -316,21 +351,21 @@ bool CmdPartTransformedCopy::isActive() DEF_STD_CMD_A(CmdPartElementCopy) CmdPartElementCopy::CmdPartElementCopy() - : Command("Part_ElementCopy") + : Command("Part_ElementCopy") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Shape Element Copy"); - sToolTipText = QT_TR_NOOP("Creates a non-parametric copy of the selected shape element"); - sWhatsThis = "Part_ElementCopy"; - sStatusTip = sToolTipText; - sPixmap = "Part_Element_Copy.svg"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Shape Element Copy"); + sToolTipText = QT_TR_NOOP("Creates a non-parametric copy of the selected shape element"); + sWhatsThis = "Part_ElementCopy"; + sStatusTip = sToolTipText; + sPixmap = "Part_Element_Copy.svg"; } void CmdPartElementCopy::activated(int iMsg) { Q_UNUSED(iMsg); - _copyShape("Element copy",false,true); + _copyShape("Element copy", false, true); } bool CmdPartElementCopy::isActive() @@ -344,21 +379,23 @@ bool CmdPartElementCopy::isActive() DEF_STD_CMD_A(CmdPartRefineShape) CmdPartRefineShape::CmdPartRefineShape() - : Command("Part_RefineShape") + : Command("Part_RefineShape") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Refine Shape"); - sToolTipText = QT_TR_NOOP("Creates a refined copy of the selected shapes"); - sWhatsThis = "Part_RefineShape"; - sStatusTip = sToolTipText; - sPixmap = "Part_Refine_Shape"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Refine Shape"); + sToolTipText = QT_TR_NOOP("Creates a refined copy of the selected shapes"); + sWhatsThis = "Part_RefineShape"; + sStatusTip = sToolTipText; + sPixmap = "Part_Refine_Shape"; } void CmdPartRefineShape::activated(int iMsg) { Q_UNUSED(iMsg); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part" + ); bool parametric = hGrp->GetBool("ParametricRefine", true); if (parametric) { Gui::WaitCursor wc; @@ -368,16 +405,29 @@ void CmdPartRefineShape::activated(int iMsg) std::for_each(objs.begin(), objs.end(), [](App::DocumentObject* obj) { try { App::DocumentObjectT objT(obj); - Gui::cmdAppDocumentArgs(obj->getDocument(), "addObject('Part::Refine','%s')", - obj->getNameInDocument()); - Gui::cmdAppDocumentArgs(obj->getDocument(), "ActiveObject.Source = %s", - objT.getObjectPython()); - Gui::cmdAppDocumentArgs(obj->getDocument(), "ActiveObject.Label = %s.Label", - objT.getObjectPython()); + Gui::cmdAppDocumentArgs( + obj->getDocument(), + "addObject('Part::Refine','%s')", + obj->getNameInDocument() + ); + Gui::cmdAppDocumentArgs( + obj->getDocument(), + "ActiveObject.Source = %s", + objT.getObjectPython() + ); + Gui::cmdAppDocumentArgs( + obj->getDocument(), + "ActiveObject.Label = %s.Label", + objT.getObjectPython() + ); Gui::cmdAppObjectHide(obj); auto newObj = App::GetApplication().getActiveDocument()->getActiveObject(); - Gui::copyVisualT(newObj->getNameInDocument(), "ShapeAppearance", obj->getNameInDocument()); + Gui::copyVisualT( + newObj->getNameInDocument(), + "ShapeAppearance", + obj->getNameInDocument() + ); Gui::copyVisualT(newObj->getNameInDocument(), "LineColor", obj->getNameInDocument()); Gui::copyVisualT(newObj->getNameInDocument(), "PointColor", obj->getNameInDocument()); } @@ -389,7 +439,7 @@ void CmdPartRefineShape::activated(int iMsg) updateActive(); } else { - _copyShape("Refined copy",true,false,true); + _copyShape("Refined copy", true, false, true); } } @@ -404,15 +454,15 @@ bool CmdPartRefineShape::isActive() DEF_STD_CMD_A(CmdPartDefeaturing) CmdPartDefeaturing::CmdPartDefeaturing() - : Command("Part_Defeaturing") + : Command("Part_Defeaturing") { - sAppModule = "Part"; - sGroup = QT_TR_NOOP("Part"); - sMenuText = QT_TR_NOOP("Defeaturing"); - sToolTipText = QT_TR_NOOP("Removes the selected features from a shape"); - sWhatsThis = "Part_Defeaturing"; - sStatusTip = sToolTipText; - sPixmap = "Part_Defeaturing"; + sAppModule = "Part"; + sGroup = QT_TR_NOOP("Part"); + sMenuText = QT_TR_NOOP("Defeaturing"); + sToolTipText = QT_TR_NOOP("Removes the selected features from a shape"); + sWhatsThis = "Part_Defeaturing"; + sStatusTip = sToolTipText; + sPixmap = "Part_Defeaturing"; } void CmdPartDefeaturing::activated(int iMsg) @@ -433,23 +483,27 @@ void CmdPartDefeaturing::activated(int iMsg) std::string faces; std::vector subnames = it->getSubNames(); - for (const auto & subname : subnames) { + for (const auto& subname : subnames) { faces.append("sh."); faces.append(subname); faces.append(","); } - doCommand(Doc,"\nsh = App.getDocument('%s').%s.Shape\n" - "nsh = sh.defeaturing([%s])\n" - "if not sh.isPartner(nsh):\n" - "\t\tdefeat = App.ActiveDocument.addObject('Part::Feature','Defeatured').Shape = nsh\n" - "\t\tGui.ActiveDocument.%s.hide()\n" - "else:\n" - "\t\tFreeCAD.Console.PrintError('Defeaturing failed\\n')", - it->getDocName(), - it->getFeatName(), - faces.c_str(), - it->getFeatName()); + doCommand( + Doc, + "\nsh = App.getDocument('%s').%s.Shape\n" + "nsh = sh.defeaturing([%s])\n" + "if not sh.isPartner(nsh):\n" + "\t\tdefeat = App.ActiveDocument.addObject('Part::Feature','Defeatured').Shape = " + "nsh\n" + "\t\tGui.ActiveDocument.%s.hide()\n" + "else:\n" + "\t\tFreeCAD.Console.PrintError('Defeaturing failed\\n')", + it->getDocName(), + it->getFeatName(), + faces.c_str(), + it->getFeatName() + ); } catch (const Base::Exception& e) { Base::Console().warning("%s: %s\n", it->getFeatName(), e.what()); @@ -463,10 +517,10 @@ bool CmdPartDefeaturing::isActive() { Base::Type partid = Base::Type::fromName("Part::Feature"); std::vector objs = Gui::Selection().getSelectionEx(nullptr, partid); - for (const auto & obj : objs) { + for (const auto& obj : objs) { std::vector subnames = obj.getSubNames(); - for (const auto & subname : subnames) { - if (subname.substr(0,4) == "Face") { + for (const auto& subname : subnames) { + if (subname.substr(0, 4) == "Face") { return true; } } @@ -479,7 +533,7 @@ bool CmdPartDefeaturing::isActive() void CreateSimplePartCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPartSimpleCylinder()); rcCmdMgr.addCommand(new CmdPartShapeFromMesh()); rcCmdMgr.addCommand(new CmdPartPointsFromMesh()); diff --git a/src/Mod/Part/Gui/CrossSections.cpp b/src/Mod/Part/Gui/CrossSections.cpp index 7edc706594..723429484c 100644 --- a/src/Mod/Part/Gui/CrossSections.cpp +++ b/src/Mod/Part/Gui/CrossSections.cpp @@ -22,20 +22,20 @@ * * ***************************************************************************/ -# include +#include -# include -# include +#include +#include -# include -# include -# include +#include +#include +#include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include #include @@ -60,10 +60,11 @@ using namespace PartGui; namespace sp = std::placeholders; -#undef CS_FUTURE // multi-threading causes some problems +#undef CS_FUTURE // multi-threading causes some problems -namespace PartGui { -class ViewProviderCrossSections : public Gui::ViewProvider +namespace PartGui +{ +class ViewProviderCrossSections: public Gui::ViewProvider { public: ViewProviderCrossSections() @@ -87,8 +88,7 @@ public: planes->unref(); } void updateData(const App::Property*) override - { - } + {} const char* getDefaultDisplayMode() const override { return ""; @@ -101,15 +101,15 @@ public: { coords->point.setNum(v.size()); SbVec3f* p = coords->point.startEditing(); - for (unsigned int i=0; ipoint.finishEditing(); - unsigned int count = v.size()/5; + unsigned int count = v.size() / 5; planes->numVertices.setNum(count); int32_t* l = planes->numVertices.startEditing(); - for (unsigned int i=0; inumVertices.finishEditing(); @@ -119,12 +119,12 @@ private: SoCoordinate3* coords; SoLineSet* planes; }; -} +} // namespace PartGui CrossSections::CrossSections(const Base::BoundBox3d& bb, QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) - , ui(new Ui_CrossSections) - , bbox(bb) + : QDialog(parent, fl) + , ui(new Ui_CrossSections) + , bbox(bb) { ui->setupUi(this); setupConnections(); @@ -161,35 +161,45 @@ CrossSections::~CrossSections() void CrossSections::setupConnections() { - connect(ui->xyPlane, &QRadioButton::clicked, - this, &CrossSections::xyPlaneClicked); - connect(ui->xzPlane, &QRadioButton::clicked, - this, &CrossSections::xzPlaneClicked); - connect(ui->yzPlane, &QRadioButton::clicked, - this, &CrossSections::yzPlaneClicked); - connect(ui->position, qOverload(&Gui::QuantitySpinBox::valueChanged), - this, &CrossSections::positionValueChanged); - connect(ui->distance, qOverload(&Gui::QuantitySpinBox::valueChanged), - this, &CrossSections::distanceValueChanged); - connect(ui->countSections, qOverload(&QSpinBox::valueChanged), - this, &CrossSections::countSectionsValueChanged); - connect(ui->checkBothSides, &QCheckBox::toggled, - this, &CrossSections::checkBothSidesToggled); - connect(ui->sectionsBox, &QGroupBox::toggled, - this, &CrossSections::sectionsBoxToggled); + connect(ui->xyPlane, &QRadioButton::clicked, this, &CrossSections::xyPlaneClicked); + connect(ui->xzPlane, &QRadioButton::clicked, this, &CrossSections::xzPlaneClicked); + connect(ui->yzPlane, &QRadioButton::clicked, this, &CrossSections::yzPlaneClicked); + connect( + ui->position, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CrossSections::positionValueChanged + ); + connect( + ui->distance, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &CrossSections::distanceValueChanged + ); + connect( + ui->countSections, + qOverload(&QSpinBox::valueChanged), + this, + &CrossSections::countSectionsValueChanged + ); + connect(ui->checkBothSides, &QCheckBox::toggled, this, &CrossSections::checkBothSidesToggled); + connect(ui->sectionsBox, &QGroupBox::toggled, this, &CrossSections::sectionsBoxToggled); } CrossSections::Plane CrossSections::plane() const { - if (ui->xyPlane->isChecked()) + if (ui->xyPlane->isChecked()) { return CrossSections::XY; - else if (ui->xzPlane->isChecked()) + } + else if (ui->xzPlane->isChecked()) { return CrossSections::XZ; - else + } + else { return CrossSections::YZ; + } } -void CrossSections::changeEvent(QEvent *e) +void CrossSections::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -215,21 +225,25 @@ void CrossSections::accept() bool CrossSections::apply() { - std::vector docobjs = Gui::Selection(). - getObjectsOfType(App::DocumentObject::getClassTypeId()); + std::vector docobjs = Gui::Selection().getObjectsOfType( + App::DocumentObject::getClassTypeId() + ); std::vector obj; for (auto it : docobjs) { - if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform).isNull()) { + if (!Part::Feature::getTopoShape(it, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform) + .isNull()) { obj.push_back(it); } } std::vector d; - if (ui->sectionsBox->isChecked()) + if (ui->sectionsBox->isChecked()) { d = getPlanes(); - else + } + else { d.push_back(ui->position->value().getValue()); - double a=0,b=0,c=0; + } + double a = 0, b = 0, c = 0; switch (plane()) { case CrossSections::XY: c = 1.0; @@ -245,11 +259,11 @@ bool CrossSections::apply() #ifdef CS_FUTURE Standard::SetReentrant(Standard_True); for (std::vector::iterator it = obj.begin(); it != obj.end(); ++it) { - Part::CrossSection cs(a,b,c,static_cast(*it)->Shape.getValue()); - QFuture< std::list > future = QtConcurrent::mapped - (d, std::bind(&Part::CrossSection::section, &cs, sp::_1)); + Part::CrossSection cs(a, b, c, static_cast(*it)->Shape.getValue()); + QFuture> future + = QtConcurrent::mapped(d, std::bind(&Part::CrossSection::section, &cs, sp::_1)); future.waitForFinished(); - QFuture< std::list >::const_iterator ft; + QFuture>::const_iterator ft; TopoDS_Compound comp; BRep_Builder builder; builder.MakeCompound(comp); @@ -257,8 +271,9 @@ bool CrossSections::apply() for (ft = future.begin(); ft != future.end(); ++ft) { const std::list& w = *ft; for (std::list::const_iterator wt = w.begin(); wt != w.end(); ++wt) { - if (!wt->IsNull()) + if (!wt->IsNull()) { builder.Add(comp, *wt); + } } } @@ -278,33 +293,54 @@ bool CrossSections::apply() App::Document* doc = it->getDocument(); std::string s = it->getNameInDocument(); s += "_cs"; - Gui::Command::runCommand(Gui::Command::App, QStringLiteral( - "wires=list()\n" - "shape=FreeCAD.getDocument(\"%1\").%2.Shape\n") - .arg(QLatin1String(doc->getName()), - QLatin1String(it->getNameInDocument())).toLatin1()); + Gui::Command::runCommand( + Gui::Command::App, + QStringLiteral( + "wires=list()\n" + "shape=FreeCAD.getDocument(\"%1\").%2.Shape\n" + ) + .arg(QLatin1String(doc->getName()), QLatin1String(it->getNameInDocument())) + .toLatin1() + ); for (double jt : d) { - Gui::Command::runCommand(Gui::Command::App, QStringLiteral( - "for i in shape.slice(Base.Vector(%1,%2,%3),%4):\n" - " wires.append(i)\n" - ).arg(a).arg(b).arg(c).arg(jt).toLatin1()); + Gui::Command::runCommand( + Gui::Command::App, + QStringLiteral( + "for i in shape.slice(Base.Vector(%1,%2,%3),%4):\n" + " wires.append(i)\n" + ) + .arg(a) + .arg(b) + .arg(c) + .arg(jt) + .toLatin1() + ); seq.next(); } - Gui::Command::runCommand(Gui::Command::App, QStringLiteral( - "comp=Part.makeCompound(wires)\n" - "slice=FreeCAD.getDocument(\"%1\").addObject(\"Part::Feature\",\"%2\")\n" - "slice.Shape=comp\n" - "slice.purgeTouched()\n" - "del slice,comp,wires,shape") - .arg(QLatin1String(doc->getName()), - QLatin1String(s.c_str())).toLatin1()); + Gui::Command::runCommand( + Gui::Command::App, + QStringLiteral( + "comp=Part.makeCompound(wires)\n" + "slice=FreeCAD.getDocument(\"%1\").addObject(\"Part::Feature\",\"%2\")\n" + "slice.Shape=comp\n" + "slice.purgeTouched()\n" + "del slice,comp,wires,shape" + ) + .arg(QLatin1String(doc->getName()), QLatin1String(s.c_str())) + .toLatin1() + ); } seq.next(); - } catch (Base::Exception& e) { + } + catch (Base::Exception& e) { e.reportException(); - QMessageBox::critical(Gui::getMainWindow(), tr("Cannot compute cross-sections"), QString::fromStdString(e.getMessage())); + QMessageBox::critical( + Gui::getMainWindow(), + tr("Cannot compute cross-sections"), + QString::fromStdString(e.getMessage()) + ); return false; } @@ -323,8 +359,9 @@ void CrossSections::xyPlaneClicked() } else { double dist = bbox.LengthZ() / ui->countSections->value(); - if (!ui->checkBothSides->isChecked()) + if (!ui->checkBothSides->isChecked()) { dist *= 0.5f; + } ui->distance->setValue(dist); calcPlanes(CrossSections::XY); } @@ -339,8 +376,9 @@ void CrossSections::xzPlaneClicked() } else { double dist = bbox.LengthY() / ui->countSections->value(); - if (!ui->checkBothSides->isChecked()) + if (!ui->checkBothSides->isChecked()) { dist *= 0.5f; + } ui->distance->setValue(dist); calcPlanes(CrossSections::XZ); } @@ -355,8 +393,9 @@ void CrossSections::yzPlaneClicked() } else { double dist = bbox.LengthX() / ui->countSections->value(); - if (!ui->checkBothSides->isChecked()) + if (!ui->checkBothSides->isChecked()) { dist *= 0.5f; + } ui->distance->setValue(dist); calcPlanes(CrossSections::YZ); } @@ -421,8 +460,9 @@ void CrossSections::countSectionsValueChanged(int v) dist = bbox.LengthX() / v; break; } - if (!ui->checkBothSides->isChecked()) + if (!ui->checkBothSides->isChecked()) { dist *= 0.5f; + } ui->distance->setValue(dist); calcPlanes(type); } @@ -498,14 +538,14 @@ std::vector CrossSections::getPlanes() const std::vector d; if (both) { - double start = pos-0.5f*(count-1)*stp; - for (int i=0; i& d, double Base::Vector3f v[4]; switch (type) { case XY: - v[0].Set(bound[0],bound[2],it); - v[1].Set(bound[1],bound[2],it); - v[2].Set(bound[1],bound[3],it); - v[3].Set(bound[0],bound[3],it); + v[0].Set(bound[0], bound[2], it); + v[1].Set(bound[1], bound[2], it); + v[2].Set(bound[1], bound[3], it); + v[3].Set(bound[0], bound[3], it); break; case XZ: - v[0].Set(bound[0],it,bound[2]); - v[1].Set(bound[1],it,bound[2]); - v[2].Set(bound[1],it,bound[3]); - v[3].Set(bound[0],it,bound[3]); + v[0].Set(bound[0], it, bound[2]); + v[1].Set(bound[1], it, bound[2]); + v[2].Set(bound[1], it, bound[3]); + v[3].Set(bound[0], it, bound[3]); break; case YZ: - v[0].Set(it,bound[0],bound[2]); - v[1].Set(it,bound[1],bound[2]); - v[2].Set(it,bound[1],bound[3]); - v[3].Set(it,bound[0],bound[3]); + v[0].Set(it, bound[0], bound[2]); + v[1].Set(it, bound[1], bound[2]); + v[2].Set(it, bound[1], bound[3]); + v[3].Set(it, bound[0], bound[3]); break; } diff --git a/src/Mod/Part/Gui/CrossSections.h b/src/Mod/Part/Gui/CrossSections.h index e8b494d1a0..ba0dd9bdc9 100644 --- a/src/Mod/Part/Gui/CrossSections.h +++ b/src/Mod/Part/Gui/CrossSections.h @@ -33,28 +33,39 @@ #include -namespace Gui { +namespace Gui +{ class View3DInventor; } -namespace PartGui { +namespace PartGui +{ class ViewProviderCrossSections; class Ui_CrossSections; -class CrossSections : public QDialog +class CrossSections: public QDialog { Q_OBJECT - enum Plane { XY, XZ, YZ }; + enum Plane + { + XY, + XZ, + YZ + }; public: - explicit CrossSections(const Base::BoundBox3d& bb, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + explicit CrossSections( + const Base::BoundBox3d& bb, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~CrossSections() override; void accept() override; bool apply(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void keyPressEvent(QKeyEvent*) override; private: @@ -71,7 +82,7 @@ private: private: std::vector getPlanes() const; void calcPlane(Plane, double); - void calcPlanes(Plane/*, double, bool, int*/); + void calcPlanes(Plane /*, double, bool, int*/); void makePlanes(Plane, const std::vector&, double[4]); Plane plane() const; @@ -82,7 +93,7 @@ private: QPointer view; }; -class TaskCrossSections : public Gui::TaskView::TaskDialog +class TaskCrossSections: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -94,12 +105,14 @@ public: void clicked(int id) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; + } private: CrossSections* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_CROSSSECTIONS_H +#endif // PARTGUI_CROSSSECTIONS_H diff --git a/src/Mod/Part/Gui/DlgBooleanOperation.cpp b/src/Mod/Part/Gui/DlgBooleanOperation.cpp index e71421bec7..c4823ff4f2 100644 --- a/src/Mod/Part/Gui/DlgBooleanOperation.cpp +++ b/src/Mod/Part/Gui/DlgBooleanOperation.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -50,55 +50,67 @@ using namespace PartGui; namespace sp = std::placeholders; -namespace PartGui { - class BooleanOperationItem : public QTreeWidgetItem +namespace PartGui +{ +class BooleanOperationItem: public QTreeWidgetItem +{ +public: + explicit BooleanOperationItem(int type = Type) + : QTreeWidgetItem(type) + {} + void setData(int column, int role, const QVariant& value) override { - public: - explicit BooleanOperationItem(int type = Type) - : QTreeWidgetItem(type) - { - } - void setData (int column, int role, const QVariant & value) override - { - QTreeWidgetItem::setData(column, role, value); - if (role == Qt::CheckStateRole && value.toBool()) { - QTreeWidget* tree = this->treeWidget(); - if (!tree) - return; - int numChild = tree->topLevelItemCount(); - for (int i=0; itopLevelItem(i); - for (int j=0; jchildCount(); j++) { - QTreeWidgetItem* child = item->child(j); - if (child && child->checkState(column) & Qt::Checked) { - if (child != this) - child->setCheckState(column, Qt::Unchecked); + QTreeWidgetItem::setData(column, role, value); + if (role == Qt::CheckStateRole && value.toBool()) { + QTreeWidget* tree = this->treeWidget(); + if (!tree) { + return; + } + int numChild = tree->topLevelItemCount(); + for (int i = 0; i < numChild; i++) { + QTreeWidgetItem* item = tree->topLevelItem(i); + for (int j = 0; j < item->childCount(); j++) { + QTreeWidgetItem* child = item->child(j); + if (child && child->checkState(column) & Qt::Checked) { + if (child != this) { + child->setCheckState(column, Qt::Unchecked); } } } } } - }; -} + } +}; +} // namespace PartGui /* TRANSLATOR PartGui::DlgBooleanOperation */ DlgBooleanOperation::DlgBooleanOperation(QWidget* parent) - : QWidget(parent), ui(new Ui_DlgBooleanOperation) + : QWidget(parent) + , ui(new Ui_DlgBooleanOperation) { ui->setupUi(this); - connect(ui->swapButton, &QPushButton::clicked, - this, &DlgBooleanOperation::onSwapButtonClicked); - connect(ui->firstShape, &QTreeWidget::currentItemChanged, - this, &DlgBooleanOperation::currentItemChanged); - connect(ui->secondShape, &QTreeWidget::currentItemChanged, - this, &DlgBooleanOperation::currentItemChanged); - //NOLINTBEGIN - this->connectNewObject = App::GetApplication().signalNewObject.connect(std::bind - (&DlgBooleanOperation::slotCreatedObject, this, sp::_1)); - this->connectModObject = App::GetApplication().signalChangedObject.connect(std::bind - (&DlgBooleanOperation::slotChangedObject, this, sp::_1, sp::_2)); - //NOLINTEND + connect(ui->swapButton, &QPushButton::clicked, this, &DlgBooleanOperation::onSwapButtonClicked); + connect( + ui->firstShape, + &QTreeWidget::currentItemChanged, + this, + &DlgBooleanOperation::currentItemChanged + ); + connect( + ui->secondShape, + &QTreeWidget::currentItemChanged, + this, + &DlgBooleanOperation::currentItemChanged + ); + // NOLINTBEGIN + this->connectNewObject = App::GetApplication().signalNewObject.connect( + std::bind(&DlgBooleanOperation::slotCreatedObject, this, sp::_1) + ); + this->connectModObject = App::GetApplication().signalChangedObject.connect( + std::bind(&DlgBooleanOperation::slotChangedObject, this, sp::_1, sp::_2) + ); + // NOLINTEND findShapes(); } @@ -112,7 +124,7 @@ DlgBooleanOperation::~DlgBooleanOperation() this->connectModObject.disconnect(); } -void DlgBooleanOperation::changeEvent(QEvent *e) +void DlgBooleanOperation::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -123,16 +135,16 @@ void DlgBooleanOperation::changeEvent(QEvent *e) void DlgBooleanOperation::slotCreatedObject(const App::DocumentObject& obj) { App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } App::Document* doc = obj.getDocument(); if (activeDoc == doc && obj.isDerivedFrom()) { observe.push_back(&obj); } } -void DlgBooleanOperation::slotChangedObject(const App::DocumentObject& obj, - const App::Property& prop) +void DlgBooleanOperation::slotChangedObject(const App::DocumentObject& obj, const App::Property& prop) { if (const auto it = std::ranges::find(observe, &obj); it != observe.end() && prop.is()) { @@ -148,16 +160,18 @@ void DlgBooleanOperation::slotChangedObject(const App::DocumentObject& obj, child->setToolTip(0, label); child->setData(0, Qt::UserRole, name); Gui::ViewProvider* vp = activeGui->getViewProvider(&obj); - if (vp) + if (vp) { child->setIcon(0, vp->getIcon()); + } QTreeWidgetItem* copy = new BooleanOperationItem(); copy->setCheckState(0, Qt::Unchecked); copy->setText(0, label); copy->setToolTip(0, label); copy->setData(0, Qt::UserRole, name); - if (vp) + if (vp) { copy->setIcon(0, vp->getIcon()); + } TopAbs_ShapeEnum type = shape.ShapeType(); if (type == TopAbs_SOLID) { @@ -184,9 +198,11 @@ void DlgBooleanOperation::slotChangedObject(const App::DocumentObject& obj, ui->firstShape->topLevelItem(3)->setExpanded(true); ui->secondShape->topLevelItem(3)->setExpanded(true); } - else { // belongs to none of these groups - delete child; child = nullptr; - delete copy; copy = nullptr; + else { // belongs to none of these groups + delete child; + child = nullptr; + delete copy; + copy = nullptr; } // remove the watched object because now it is added to the tree @@ -199,7 +215,7 @@ bool DlgBooleanOperation::hasSolids(const App::DocumentObject* obj) const { if (obj->isDerivedFrom()) { const TopoDS_Shape& shape = static_cast(obj)->Shape.getValue(); - TopExp_Explorer anExp (shape, TopAbs_SOLID); + TopExp_Explorer anExp(shape, TopAbs_SOLID); if (anExp.More()) { return true; } @@ -211,16 +227,19 @@ bool DlgBooleanOperation::hasSolids(const App::DocumentObject* obj) const void DlgBooleanOperation::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); - if (!activeGui) + if (!activeGui) { return; + } - std::vector objs = activeDoc->getObjectsOfType - (Part::Feature::getClassTypeId()); + std::vector objs = activeDoc->getObjectsOfType( + Part::Feature::getClassTypeId() + ); - QTreeWidgetItem *item_left=nullptr, *item_right=nullptr; + QTreeWidgetItem *item_left = nullptr, *item_right = nullptr; for (auto obj : objs) { const TopoDS_Shape& shape = static_cast(obj)->Shape.getValue(); if (!shape.IsNull()) { @@ -233,16 +252,18 @@ void DlgBooleanOperation::findShapes() child->setToolTip(0, label); child->setData(0, Qt::UserRole, name); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) + if (vp) { child->setIcon(0, vp->getIcon()); + } QTreeWidgetItem* copy = new BooleanOperationItem(); copy->setCheckState(0, Qt::Unchecked); copy->setText(0, label); copy->setToolTip(0, label); copy->setData(0, Qt::UserRole, name); - if (vp) + if (vp) { copy->setIcon(0, vp->getIcon()); + } TopAbs_ShapeEnum type = shape.ShapeType(); if (type == TopAbs_SOLID) { @@ -261,17 +282,21 @@ void DlgBooleanOperation::findShapes() ui->firstShape->topLevelItem(3)->addChild(child); ui->secondShape->topLevelItem(3)->addChild(copy); } - else { // belongs to none of these groups - delete child; child = nullptr; - delete copy; copy = nullptr; + else { // belongs to none of these groups + delete child; + child = nullptr; + delete copy; + copy = nullptr; } if (!item_left || !item_right) { bool selected = Gui::Selection().isSelected(obj); - if (!item_left && selected) + if (!item_left && selected) { item_left = child; - else if (!item_right && selected) + } + else if (!item_right && selected) { item_right = copy; + } } } } @@ -287,14 +312,16 @@ void DlgBooleanOperation::findShapes() for (int i = 0; i < ui->firstShape->topLevelItemCount(); i++) { QTreeWidgetItem* group = ui->firstShape->topLevelItem(i); group->setFlags(Qt::ItemIsEnabled); - if (group->childCount() > 0) + if (group->childCount() > 0) { group->setExpanded(true); + } } for (int i = 0; i < ui->secondShape->topLevelItemCount(); i++) { QTreeWidgetItem* group = ui->secondShape->topLevelItem(i); group->setFlags(Qt::ItemIsEnabled); - if (group->childCount() > 0) + if (group->childCount() > 0) { group->setExpanded(true); + } } } @@ -310,13 +337,13 @@ bool DlgBooleanOperation::indexOfCurrentItem(QTreeWidgetItem* item, int& top_ind return false; } -void DlgBooleanOperation::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem * previous) +void DlgBooleanOperation::currentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { Q_UNUSED(current); Q_UNUSED(previous); -// if (current && current->flags() & Qt::ItemIsUserCheckable) -// current->setCheckState(0, Qt::Checked); - //if (previous && previous->flags() & Qt::ItemIsUserCheckable) + // if (current && current->flags() & Qt::ItemIsUserCheckable) + // current->setCheckState(0, Qt::Checked); + // if (previous && previous->flags() & Qt::ItemIsUserCheckable) // previous->setCheckState(0, Qt::Unchecked); } @@ -351,9 +378,9 @@ void DlgBooleanOperation::accept() QTreeWidgetItem* litem = nullptr; int numLChild = ui->firstShape->topLevelItemCount(); - for (int i=0; ifirstShape->topLevelItem(i); - for (int j=0; jchildCount(); j++) { + for (int j = 0; j < item->childCount(); j++) { QTreeWidgetItem* child = item->child(j); if (child && child->checkState(0) & Qt::Checked) { litem = child; @@ -361,15 +388,16 @@ void DlgBooleanOperation::accept() } } - if (litem) + if (litem) { break; + } } QTreeWidgetItem* ritem = nullptr; int numRChild = ui->secondShape->topLevelItemCount(); - for (int i=0; isecondShape->topLevelItem(i); - for (int j=0; jchildCount(); j++) { + for (int j = 0; j < item->childCount(); j++) { QTreeWidgetItem* child = item->child(j); if (child && child->checkState(0) & Qt::Checked) { ritem = child; @@ -377,23 +405,25 @@ void DlgBooleanOperation::accept() } } - if (ritem) + if (ritem) { break; + } } - if (!litem || !indexOfCurrentItem(litem,ltop,lchild)) { - QMessageBox::critical(this, windowTitle(), - tr("First, select a shape on the left side")); + if (!litem || !indexOfCurrentItem(litem, ltop, lchild)) { + QMessageBox::critical(this, windowTitle(), tr("First, select a shape on the left side")); return; } - if (!ritem || !indexOfCurrentItem(ritem,rtop,rchild)) { - QMessageBox::critical(this, windowTitle(), - tr("First, select a shape on the right side")); + if (!ritem || !indexOfCurrentItem(ritem, rtop, rchild)) { + QMessageBox::critical(this, windowTitle(), tr("First, select a shape on the right side")); return; } if (ltop == rtop && lchild == rchild) { - QMessageBox::critical(this, windowTitle(), - tr("Cannot perform a boolean operation with the same shape")); + QMessageBox::critical( + this, + windowTitle(), + tr("Cannot perform a boolean operation with the same shape") + ); return; } @@ -402,8 +432,7 @@ void DlgBooleanOperation::accept() shapeTwo = (const char*)ritem->data(0, Qt::UserRole).toByteArray(); App::Document* activeDoc = App::GetApplication().getActiveDocument(); if (!activeDoc) { - QMessageBox::critical(this, windowTitle(), - tr("No active document available")); + QMessageBox::critical(this, windowTitle(), tr("No active document available")); return; } @@ -412,31 +441,43 @@ void DlgBooleanOperation::accept() App::DocumentObject* obj2 = activeDoc->getObject(shapeTwo.c_str()); if (!obj1 || !obj2) { // objects don't exists (anymore) - QMessageBox::critical(this, windowTitle(), - tr("One of the selected objects does not exist anymore")); + QMessageBox::critical( + this, + windowTitle(), + tr("One of the selected objects does not exist anymore") + ); return; } if (ui->unionButton->isChecked()) { if (!hasSolids(obj1) || !hasSolids(obj2)) { - QMessageBox::critical(this, windowTitle(), - tr("Performing union on non-solids is not possible")); + QMessageBox::critical( + this, + windowTitle(), + tr("Performing union on non-solids is not possible") + ); return; } method = "make_fuse"; } else if (ui->interButton->isChecked()) { if (!hasSolids(obj1) || !hasSolids(obj2)) { - QMessageBox::critical(this, windowTitle(), - tr("Performing intersection on non-solids is not possible")); + QMessageBox::critical( + this, + windowTitle(), + tr("Performing intersection on non-solids is not possible") + ); return; } method = "make_common"; } else if (ui->diffButton->isChecked()) { if (!hasSolids(obj1) || !hasSolids(obj2)) { - QMessageBox::critical(this, windowTitle(), - tr("Performing difference on non-solids is not possible")); + QMessageBox::critical( + this, + windowTitle(), + tr("Performing difference on non-solids is not possible") + ); return; } method = "make_cut"; @@ -451,12 +492,14 @@ void DlgBooleanOperation::accept() std::vector names; names.push_back(Base::Tools::quoted(shapeOne.c_str())); names.push_back(Base::Tools::quoted(shapeTwo.c_str())); - Gui::Command::doCommand(Gui::Command::Doc, - "from BOPTools import BOPFeatures"); - Gui::Command::doCommand(Gui::Command::Doc, - "bp = BOPFeatures.BOPFeatures(App.activeDocument())"); - Gui::Command::doCommand(Gui::Command::Doc, - "bp.%s([%s])", method.c_str(), Base::Tools::joinList(names).c_str()); + Gui::Command::doCommand(Gui::Command::Doc, "from BOPTools import BOPFeatures"); + Gui::Command::doCommand(Gui::Command::Doc, "bp = BOPFeatures.BOPFeatures(App.activeDocument())"); + Gui::Command::doCommand( + Gui::Command::Doc, + "bp.%s([%s])", + method.c_str(), + Base::Tools::joinList(names).c_str() + ); activeDoc->commitTransaction(); activeDoc->recompute(); } diff --git a/src/Mod/Part/Gui/DlgBooleanOperation.h b/src/Mod/Part/Gui/DlgBooleanOperation.h index 776d8ac671..cbfe830844 100644 --- a/src/Mod/Part/Gui/DlgBooleanOperation.h +++ b/src/Mod/Part/Gui/DlgBooleanOperation.h @@ -31,15 +31,17 @@ class QTreeWidgetItem; -namespace App { +namespace App +{ class DocumentObject; class Property; -} -namespace PartGui { +} // namespace App +namespace PartGui +{ using Connection = boost::signals2::connection; class Ui_DlgBooleanOperation; -class DlgBooleanOperation : public QWidget +class DlgBooleanOperation: public QWidget { Q_OBJECT @@ -56,7 +58,7 @@ private: bool hasSolids(const App::DocumentObject*) const; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void onSwapButtonClicked(); @@ -69,7 +71,7 @@ private: std::list observe; }; -class TaskBooleanOperation : public Gui::TaskView::TaskDialog +class TaskBooleanOperation: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -80,16 +82,22 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Apply | QDialogButtonBox::Close; } + { + return QDialogButtonBox::Apply | QDialogButtonBox::Close; + } bool isAllowedAlterDocument() const override - { return true; } + { + return true; + } bool needsFullSpace() const override - { return true; } + { + return true; + } private: DlgBooleanOperation* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGBOOLEANOPERATION_H +#endif // PARTGUI_DLGBOOLEANOPERATION_H diff --git a/src/Mod/Part/Gui/DlgExportStep.cpp b/src/Mod/Part/Gui/DlgExportStep.cpp index b67cfd8eac..70a2cf78e9 100644 --- a/src/Mod/Part/Gui/DlgExportStep.cpp +++ b/src/Mod/Part/Gui/DlgExportStep.cpp @@ -23,12 +23,12 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -44,8 +44,8 @@ using namespace PartGui; DlgExportStep::DlgExportStep(QWidget* parent) - : PreferencePage(parent) - , ui(new Ui_DlgExportStep) + : PreferencePage(parent) + , ui(new Ui_DlgExportStep) { ui->setupUi(this); @@ -56,9 +56,13 @@ DlgExportStep::DlgExportStep(QWidget* parent) ui->comboBoxSchema->setItemData(4, QByteArray("AP242DIS")); // https://tracker.dev.opencascade.org/view.php?id=25654 - ui->checkBoxPcurves->setToolTip(tr("This parameter indicates whether parametric curves (curves in parametric space of surface)\n" - "should be written into the STEP file. This parameter can be set to off in order to minimize\n" - "the size of the resulting STEP file.")); + ui->checkBoxPcurves->setToolTip( + tr("This parameter indicates whether parametric curves (curves in parametric space of " + "surface)\n" + "should be written into the STEP file. This parameter can be set to off in order to " + "minimize\n" + "the size of the resulting STEP file.") + ); Part::OCAF::ImportExportSettings settings; ui->checkBoxExportHiddenObj->setChecked(settings.getExportHiddenObject()); @@ -104,8 +108,9 @@ void DlgExportStep::loadSettings() // scheme QByteArray ap(settings.getScheme().c_str()); int index = ui->comboBoxSchema->findData(QVariant(ap)); - if (index >= 0) + if (index >= 0) { ui->comboBoxSchema->setCurrentIndex(index); + } // (h)STEP of Import module ui->checkBoxExportHiddenObj->onRestore(); @@ -125,7 +130,7 @@ StepSettings DlgExportStep::getSettings() const /** * Sets the strings of the subwidgets using the current language. */ -void DlgExportStep::changeEvent(QEvent *e) +void DlgExportStep::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -138,8 +143,8 @@ void DlgExportStep::changeEvent(QEvent *e) // ---------------------------------------------------------------------------- DlgExportHeaderStep::DlgExportHeaderStep(QWidget* parent) - : PreferencePage(parent) - , ui(new Ui_DlgExportHeaderStep) + : PreferencePage(parent) + , ui(new Ui_DlgExportHeaderStep) { ui->setupUi(this); @@ -147,7 +152,9 @@ DlgExportHeaderStep::DlgExportHeaderStep(QWidget* parent) QRegularExpression rx; rx.setPattern(QStringLiteral("[\\x00-\\x7F]+")); - QRegularExpressionValidator* companyValidator = new QRegularExpressionValidator(ui->lineEditCompany); + QRegularExpressionValidator* companyValidator = new QRegularExpressionValidator( + ui->lineEditCompany + ); companyValidator->setRegularExpression(rx); ui->lineEditCompany->setValidator(companyValidator); QRegularExpressionValidator* authorValidator = new QRegularExpressionValidator(ui->lineEditAuthor); @@ -179,7 +186,7 @@ void DlgExportHeaderStep::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void DlgExportHeaderStep::changeEvent(QEvent *e) +void DlgExportHeaderStep::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -192,8 +199,8 @@ void DlgExportHeaderStep::changeEvent(QEvent *e) // ---------------------------------------------------------------------------- TaskExportStep::TaskExportStep(QWidget* parent) - : QDialog(parent) - , ui(new DlgExportStep(this)) + : QDialog(parent) + , ui(new DlgExportStep(this)) { QApplication::setOverrideCursor(Qt::ArrowCursor); diff --git a/src/Mod/Part/Gui/DlgExportStep.h b/src/Mod/Part/Gui/DlgExportStep.h index 9923d76697..0e95d7def6 100644 --- a/src/Mod/Part/Gui/DlgExportStep.h +++ b/src/Mod/Part/Gui/DlgExportStep.h @@ -33,7 +33,8 @@ class QButtonGroup; class QCheckBox; -namespace PartGui { +namespace PartGui +{ struct StepSettings { @@ -45,7 +46,7 @@ struct StepSettings // ---------------------------------------------------------------------------- class Ui_DlgExportStep; -class DlgExportStep : public Gui::Dialog::PreferencePage +class DlgExportStep: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -59,7 +60,7 @@ public: StepSettings getSettings() const; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; @@ -68,7 +69,7 @@ private: // ---------------------------------------------------------------------------- class Ui_DlgExportHeaderStep; -class DlgExportHeaderStep : public Gui::Dialog::PreferencePage +class DlgExportHeaderStep: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -80,7 +81,7 @@ public: void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; @@ -88,7 +89,7 @@ private: // ---------------------------------------------------------------------------- -class PartGuiExport TaskExportStep : public QDialog +class PartGuiExport TaskExportStep: public QDialog { Q_OBJECT @@ -105,6 +106,6 @@ private: std::unique_ptr ui; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGEXPORTSTEP_H +#endif // PARTGUI_DLGEXPORTSTEP_H diff --git a/src/Mod/Part/Gui/DlgExtrusion.cpp b/src/Mod/Part/Gui/DlgExtrusion.cpp index 160200cdf1..8068c712ac 100644 --- a/src/Mod/Part/Gui/DlgExtrusion.cpp +++ b/src/Mod/Part/Gui/DlgExtrusion.cpp @@ -22,15 +22,15 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -55,12 +55,11 @@ #include "DlgExtrusion.h" - FC_LOG_LEVEL_INIT("Part", true, true) using namespace PartGui; -class DlgExtrusion::EdgeSelection : public Gui::SelectionFilterGate +class DlgExtrusion::EdgeSelection: public Gui::SelectionFilterGate { public: bool canSelect; @@ -74,21 +73,28 @@ public: { this->canSelect = false; - if (Base::Tools::isNullOrEmpty(sSubName)) + if (Base::Tools::isNullOrEmpty(sSubName)) { return false; + } std::string element(sSubName); - if (element.substr(0,4) != "Edge") + if (element.substr(0, 4) != "Edge") { return false; - Part::TopoShape part = Part::Feature::getTopoShape(pObj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + } + Part::TopoShape part = Part::Feature::getTopoShape( + pObj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (part.isNull()) { return false; } try { - TopoDS_Shape sub = Part::Feature::getTopoShape(pObj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sSubName).getShape(); + TopoDS_Shape sub = Part::Feature::getTopoShape( + pObj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sSubName + ) + .getShape(); if (!sub.IsNull() && sub.ShapeType() == TopAbs_EDGE) { const TopoDS_Edge& edge = TopoDS::Edge(sub); @@ -107,7 +113,9 @@ public: }; DlgExtrusion::DlgExtrusion(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), ui(new Ui_DlgExtrusion), filter(nullptr) + : QDialog(parent, fl) + , ui(new Ui_DlgExtrusion) + , filter(nullptr) { ui->setupUi(this); setupConnections(); @@ -143,7 +151,7 @@ DlgExtrusion::DlgExtrusion(QWidget* parent, Qt::WindowFlags fl) */ DlgExtrusion::~DlgExtrusion() { - if (filter){ + if (filter) { Gui::Selection().rmvSelectionGate(); filter = nullptr; } @@ -175,7 +183,7 @@ void DlgExtrusion::setupConnections() // clang-format on } -void DlgExtrusion::changeEvent(QEvent *e) +void DlgExtrusion::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -192,20 +200,24 @@ void DlgExtrusion::keyPressEvent(QKeyEvent* ke) void DlgExtrusion::onDirModeCustomToggled(bool on) { - if(on) //this check prevents dual fire of dirmode changed - on radio buttons, one will come on, and other will come off, causing two events. + if (on) { // this check prevents dual fire of dirmode changed - on radio buttons, one will come + // on, and other will come off, causing two events. this->onDirModeChanged(); + } } void DlgExtrusion::onDirModeEdgeToggled(bool on) { - if(on) + if (on) { this->onDirModeChanged(); + } } void DlgExtrusion::onDirModeNormalToggled(bool on) { - if(on) + if (on) { this->onDirModeChanged(); + } } void DlgExtrusion::onSelectEdgeClicked() @@ -215,36 +227,40 @@ void DlgExtrusion::onSelectEdgeClicked() Gui::Selection().addSelectionGate(filter); ui->btnSelectEdge->setText(tr("Selecting…")); - //visibility automation - try{ + // visibility automation + try { QString code = QStringLiteral( - "import Show\n" - "tv = Show.TempoVis(App.ActiveDocument, tag= 'PartGui::DlgExtrusion')\n" - "tv.hide([%1])" - ); - std::vectorsources = getShapesToExtrude(); + "import Show\n" + "tv = Show.TempoVis(App.ActiveDocument, tag= 'PartGui::DlgExtrusion')\n" + "tv.hide([%1])" + ); + std::vector sources = getShapesToExtrude(); QString features_to_hide; - for (App::DocumentObject* obj: sources){ - if (!obj) + for (App::DocumentObject* obj : sources) { + if (!obj) { continue; + } features_to_hide.append(QStringLiteral("App.ActiveDocument.")); features_to_hide.append(QString::fromLatin1(obj->getNameInDocument())); features_to_hide.append(QStringLiteral(", \n")); } QByteArray code_2 = code.arg(features_to_hide).toLatin1(); Base::Interpreter().runString(code_2.constData()); - } catch (Base::PyException &e){ + } + catch (Base::PyException& e) { e.reportException(); } - } else { + } + else { Gui::Selection().rmvSelectionGate(); filter = nullptr; ui->btnSelectEdge->setText(tr("Select")); - //visibility automation - try{ + // visibility automation + try { Base::Interpreter().runString("del(tv)"); - } catch (Base::PyException &e){ + } + catch (Base::PyException& e) { e.reportException(); } } @@ -253,8 +269,9 @@ void DlgExtrusion::onSelectEdgeClicked() void DlgExtrusion::onButtnoXClicked() { Base::Vector3d axis(1.0, 0.0, 0.0); - if ((getDir() - axis).Length() < 1e-7) + if ((getDir() - axis).Length() < 1e-7) { axis = axis * (-1); + } setDirMode(Part::Extrusion::dmCustom); setDir(axis); } @@ -262,8 +279,9 @@ void DlgExtrusion::onButtnoXClicked() void DlgExtrusion::onButtonYClicked() { Base::Vector3d axis(0.0, 1.0, 0.0); - if ((getDir() - axis).Length() < 1e-7) + if ((getDir() - axis).Length() < 1e-7) { axis = axis * (-1); + } setDirMode(Part::Extrusion::dmCustom); setDir(axis); } @@ -271,8 +289,9 @@ void DlgExtrusion::onButtonYClicked() void DlgExtrusion::onButtonZClicked() { Base::Vector3d axis(0.0, 0.0, 1.0); - if ((getDir() - axis).Length() < 1e-7) + if ((getDir() - axis).Length() < 1e-7) { axis = axis * (-1); + } setDirMode(Part::Extrusion::dmCustom); setDir(axis); } @@ -310,84 +329,93 @@ void DlgExtrusion::onSelectionChanged(const Gui::SelectionChanges& msg) App::DocumentObject& DlgExtrusion::getShapeToExtrude() const { std::vector objs = this->getShapesToExtrude(); - if (objs.empty()) + if (objs.empty()) { throw Base::ValueError("No shapes selected"); + } return *(objs[0]); } void DlgExtrusion::fetchDir() { - bool lengths_are_at_defaults = - (fabs(ui->spinLenFwd->value().getValue() - 10.0) < 1e-7) - && (fabs(ui->spinLenRev->value().getValue() - 0.0) < 1e-7); - bool lengths_are_zero = - (fabs(ui->spinLenFwd->value().getValue() - 0.0) < 1e-7) - && (fabs(ui->spinLenRev->value().getValue() - 0.0) < 1e-7); + bool lengths_are_at_defaults = (fabs(ui->spinLenFwd->value().getValue() - 10.0) < 1e-7) + && (fabs(ui->spinLenRev->value().getValue() - 0.0) < 1e-7); + bool lengths_are_zero = (fabs(ui->spinLenFwd->value().getValue() - 0.0) < 1e-7) + && (fabs(ui->spinLenRev->value().getValue() - 0.0) < 1e-7); - try{ + try { Base::Vector3d pos, dir; bool fetched = false; bool dir_has_valid_magnitude = false; - if(this->getDirMode() == Part::Extrusion::dmEdge){ - App::PropertyLinkSub lnk; this->getAxisLink(lnk); + if (this->getDirMode() == Part::Extrusion::dmEdge) { + App::PropertyLinkSub lnk; + this->getAxisLink(lnk); fetched = Part::Extrusion::fetchAxisLink(lnk, pos, dir); dir_has_valid_magnitude = fetched; - } else if (this->getDirMode() == Part::Extrusion::dmNormal){ + } + else if (this->getDirMode() == Part::Extrusion::dmNormal) { App::PropertyLink lnk; lnk.setValue(&this->getShapeToExtrude()); dir = Part::Extrusion::calculateShapeNormal(lnk); fetched = true; } - if (dir_has_valid_magnitude && lengths_are_at_defaults){ + if (dir_has_valid_magnitude && lengths_are_at_defaults) { ui->spinLenFwd->setValue(0); - } else if (!dir_has_valid_magnitude && lengths_are_zero){ + } + else if (!dir_has_valid_magnitude && lengths_are_zero) { ui->spinLenFwd->setValue(1.0); } - if (fetched){ + if (fetched) { this->setDir(dir); } - } catch (Base::Exception &){ - - } catch (...){ - + } + catch (Base::Exception&) { + } + catch (...) { } } void DlgExtrusion::autoSolid() { - try{ + try { App::DocumentObject* dobj = &this->getShapeToExtrude(); - Part::TopoShape shape = Part::Feature::getTopoShape(dobj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape shape = Part::Feature::getTopoShape( + dobj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (shape.isNull()) { return; } TopoDS_Shape sh = shape.getShape(); - if (sh.IsNull()) + if (sh.IsNull()) { return; + } ShapeExtend_Explorer xp; - Handle(TopTools_HSequenceOfShape) leaves = xp.SeqFromCompound(sh, /*recursive= */Standard_True); + Handle(TopTools_HSequenceOfShape) leaves + = xp.SeqFromCompound(sh, /*recursive= */ Standard_True); int cntClosedWires = 0; - for(int i = 0; i < leaves->Length(); i++){ - const TopoDS_Shape &leaf = leaves->Value(i+1); - if (leaf.IsNull()) + for (int i = 0; i < leaves->Length(); i++) { + const TopoDS_Shape& leaf = leaves->Value(i + 1); + if (leaf.IsNull()) { return; - if (leaf.ShapeType() == TopAbs_WIRE || leaf.ShapeType() == TopAbs_EDGE){ - if (BRep_Tool::IsClosed(leaf)){ + } + if (leaf.ShapeType() == TopAbs_WIRE || leaf.ShapeType() == TopAbs_EDGE) { + if (BRep_Tool::IsClosed(leaf)) { cntClosedWires++; } } } - ui->chkSolid->setChecked( cntClosedWires == leaves->Length() ); - } catch(...) { - + ui->chkSolid->setChecked(cntClosedWires == leaves->Length()); + } + catch (...) { } } void DlgExtrusion::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); this->document = activeDoc->getName(); this->label = activeDoc->Label.getValue(); @@ -395,39 +423,46 @@ void DlgExtrusion::findShapes() std::vector objs = activeDoc->getObjectsOfType(); for (auto obj : objs) { - Part::TopoShape topoShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { continue; } TopoDS_Shape shape = topoShape.getShape(); - if (shape.IsNull()) continue; + if (shape.IsNull()) { + continue; + } if (canExtrude(shape)) { QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeWidget); item->setText(0, QString::fromUtf8(obj->Label.getValue())); item->setData(0, Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) + if (vp) { item->setIcon(0, vp->getIcon()); + } } } } bool DlgExtrusion::canExtrude(const TopoDS_Shape& shape) const { - if (shape.IsNull()) + if (shape.IsNull()) { return false; + } TopAbs_ShapeEnum type = shape.ShapeType(); - if (type == TopAbs_VERTEX || type == TopAbs_EDGE || - type == TopAbs_WIRE || type == TopAbs_FACE || - type == TopAbs_SHELL) + if (type == TopAbs_VERTEX || type == TopAbs_EDGE || type == TopAbs_WIRE || type == TopAbs_FACE + || type == TopAbs_SHELL) { return true; + } if (type == TopAbs_COMPOUND) { TopExp_Explorer xp; - xp.Init(shape,TopAbs_SOLID); + xp.Init(shape, TopAbs_SOLID); while (xp.More()) { return false; } - xp.Init(shape,TopAbs_COMPSOLID); + xp.Init(shape, TopAbs_COMPSOLID); while (xp.More()) { return false; } @@ -440,43 +475,56 @@ bool DlgExtrusion::canExtrude(const TopoDS_Shape& shape) const void DlgExtrusion::accept() { - try{ + try { apply(); QDialog::accept(); - } catch (Base::AbortException&){ - + } + catch (Base::AbortException&) { }; } void DlgExtrusion::apply() { - try{ - if (!validate()) + try { + if (!validate()) { throw Base::AbortException(); + } - if (filter) //if still selecting edge - stop. This is important for visibility automation. + if (filter) { // if still selecting edge - stop. This is important for visibility automation. this->onSelectEdgeClicked(); + } Gui::WaitCursor wc; App::Document* activeDoc = App::GetApplication().getDocument(this->document.c_str()); if (!activeDoc) { - QMessageBox::critical(this, windowTitle(), - tr("The document '%1' doesn't exist.").arg(QString::fromUtf8(this->label.c_str()))); + QMessageBox::critical( + this, + windowTitle(), + tr("The document '%1' doesn't exist.").arg(QString::fromUtf8(this->label.c_str())) + ); return; } activeDoc->openTransaction("Extrude"); - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/Part"); bool addBaseName = hGrp->GetBool("AddBaseObjectName", false); std::vector objects = this->getShapesToExtrude(); - for (App::DocumentObject* sourceObj: objects) { + for (App::DocumentObject* sourceObj : objects) { assert(sourceObj); - if (Part::Feature::getTopoShape(sourceObj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform).isNull()){ - FC_ERR("Object " << sourceObj->getFullName() - << " is not a Part object because it has no OCC shape. Extrusion is not possible."); + if (Part::Feature::getTopoShape( + sourceObj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ) + .isNull()) { + FC_ERR( + "Object " << sourceObj->getFullName() << " is not a Part object because it has no OCC shape. Extrusion is not possible." + ); continue; } @@ -484,12 +532,12 @@ void DlgExtrusion::apply() std::string name; name = sourceObj->getDocument()->getUniqueObjectName("Extrude").c_str(); if (addBaseName) { - //FIXME: implement - //QString baseName = QStringLiteral("Extrude_%1").arg(sourceObjectName); - //label = QStringLiteral("%1_Extrude").arg((*it)->text(0)); + // FIXME: implement + // QString baseName = QStringLiteral("Extrude_%1").arg(sourceObjectName); + // label = QStringLiteral("%1_Extrude").arg((*it)->text(0)); } - FCMD_OBJ_DOC_CMD(sourceObj,"addObject('Part::Extrusion','" << name << "')"); + FCMD_OBJ_DOC_CMD(sourceObj, "addObject('Part::Extrusion','" << name << "')"); auto newObj = sourceObj->getDocument()->getObject(name.c_str()); this->writeParametersToFeature(*newObj, sourceObj); @@ -506,37 +554,39 @@ void DlgExtrusion::apply() activeDoc->commitTransaction(); Gui::Command::updateActive(); } - catch (Base::AbortException&){ + catch (Base::AbortException&) { throw; } - catch (Base::Exception &err){ - QMessageBox::critical(this, - windowTitle(), - tr("Creating extrusion failed.\n%1") - .arg(QCoreApplication::translate("Exception", err.what()))); + catch (Base::Exception& err) { + QMessageBox::critical( + this, + windowTitle(), + tr("Creating extrusion failed.\n%1").arg(QCoreApplication::translate("Exception", err.what())) + ); return; } - catch(...) { - QMessageBox::critical(this, windowTitle(), - tr("Creating Extrusion failed.\n%1").arg(QStringLiteral("Unknown error"))); + catch (...) { + QMessageBox::critical( + this, + windowTitle(), + tr("Creating Extrusion failed.\n%1").arg(QStringLiteral("Unknown error")) + ); return; } } void DlgExtrusion::reject() { - if (filter) //if still selecting edge - stop. + if (filter) { // if still selecting edge - stop. this->onSelectEdgeClicked(); + } QDialog::reject(); } Base::Vector3d DlgExtrusion::getDir() const { - return Base::Vector3d( - ui->dirX->value(), - ui->dirY->value(), - ui->dirZ->value()); + return Base::Vector3d(ui->dirX->value(), ui->dirY->value(), ui->dirZ->value()); } void DlgExtrusion::setDir(Base::Vector3d newDir) @@ -548,14 +598,17 @@ void DlgExtrusion::setDir(Base::Vector3d newDir) Part::Extrusion::eDirMode DlgExtrusion::getDirMode() const { - if(ui->rbDirModeCustom->isChecked()) + if (ui->rbDirModeCustom->isChecked()) { return Part::Extrusion::dmCustom; - if(ui->rbDirModeEdge->isChecked()) + } + if (ui->rbDirModeEdge->isChecked()) { return Part::Extrusion::dmEdge; - if(ui->rbDirModeNormal->isChecked()) + } + if (ui->rbDirModeNormal->isChecked()) { return Part::Extrusion::dmNormal; + } - //we shouldn't get here... + // we shouldn't get here... return Part::Extrusion::dmCustom; } @@ -581,62 +634,69 @@ void DlgExtrusion::getAxisLink(App::PropertyLinkSub& lnk) const if (text.length() == 0) { lnk.setValue(nullptr); - } else { + } + else { QStringList parts = text.split(QChar::fromLatin1(':')); - App::DocumentObject* obj = App::GetApplication().getActiveDocument()->getObject(parts[0].toLatin1()); - if(!obj){ + App::DocumentObject* obj = App::GetApplication().getActiveDocument()->getObject( + parts[0].toLatin1() + ); + if (!obj) { throw Base::ValueError(tr("Object not found: %1").arg(parts[0]).toUtf8().constData()); } lnk.setValue(obj); if (parts.size() == 1) { return; - } else if (parts.size() == 2) { + } + else if (parts.size() == 2) { std::vector subs; subs.emplace_back(parts[1].toLatin1().constData()); - lnk.setValue(obj,subs); + lnk.setValue(obj, subs); } } - } void DlgExtrusion::setAxisLink(const App::PropertyLinkSub& lnk) { - if (!lnk.getValue()){ + if (!lnk.getValue()) { ui->txtLink->clear(); return; } - if (lnk.getSubValues().size() == 1){ + if (lnk.getSubValues().size() == 1) { this->setAxisLink(lnk.getValue()->getNameInDocument(), lnk.getSubValues()[0].c_str()); - } else { + } + else { this->setAxisLink(lnk.getValue()->getNameInDocument(), ""); } } void DlgExtrusion::setAxisLink(const char* objname, const char* subname) { - if(objname && strlen(objname) > 0){ + if (objname && strlen(objname) > 0) { QString txt = QString::fromLatin1(objname); - if (subname && strlen(subname) > 0){ + if (subname && strlen(subname) > 0) { txt = txt + QStringLiteral(":") + QString::fromLatin1(subname); } ui->txtLink->setText(txt); - } else { + } + else { ui->txtLink->clear(); } } std::vector DlgExtrusion::getShapesToExtrude() const { - QList items = ui->treeWidget->selectedItems(); + QList items = ui->treeWidget->selectedItems(); App::Document* doc = App::GetApplication().getDocument(this->document.c_str()); - if (!doc) + if (!doc) { throw Base::RuntimeError("Document lost"); + } std::vector objects; for (auto item : items) { App::DocumentObject* obj = doc->getObject(item->data(0, Qt::UserRole).toString().toLatin1()); - if (!obj) + if (!obj) { throw Base::RuntimeError("Object not found"); + } objects.push_back(obj); } return objects; @@ -644,77 +704,110 @@ std::vector DlgExtrusion::getShapesToExtrude() const bool DlgExtrusion::validate() { - //check source shapes + // check source shapes if (ui->treeWidget->selectedItems().isEmpty()) { - QMessageBox::critical(this, windowTitle(), - tr("No shapes selected for extrusion.")); + QMessageBox::critical(this, windowTitle(), tr("No shapes selected for extrusion.")); return false; } - //check axis link + // check axis link QString errmsg; bool hasValidAxisLink = false; - try{ + try { App::PropertyLinkSub lnk; this->getAxisLink(lnk); Base::Vector3d dir, base; hasValidAxisLink = Part::Extrusion::fetchAxisLink(lnk, base, dir); - } catch(Base::Exception &err) { + } + catch (Base::Exception& err) { errmsg = QCoreApplication::translate("Exception", err.what()); - } catch(Standard_Failure &err) { + } + catch (Standard_Failure& err) { errmsg = QString::fromLocal8Bit(err.GetMessageString()); - } catch(...) { + } + catch (...) { errmsg = tr("Unknown error"); } - if (this->getDirMode() == Part::Extrusion::dmEdge && !hasValidAxisLink){ - if (errmsg.length() > 0) - QMessageBox::critical(this, windowTitle(), tr("Extrusion direction link is invalid.\n\n%1").arg(errmsg)); - else - QMessageBox::critical(this, windowTitle(), tr("Direction mode is to use an edge, but no edge is linked.")); + if (this->getDirMode() == Part::Extrusion::dmEdge && !hasValidAxisLink) { + if (errmsg.length() > 0) { + QMessageBox::critical( + this, + windowTitle(), + tr("Extrusion direction link is invalid.\n\n%1").arg(errmsg) + ); + } + else { + QMessageBox::critical( + this, + windowTitle(), + tr("Direction mode is to use an edge, but no edge is linked.") + ); + } ui->txtLink->setFocus(); return false; - } else if (this->getDirMode() != Part::Extrusion::dmEdge && !hasValidAxisLink){ - //axis link is invalid, but it is not required by the mode. We shouldn't complain it's invalid then... + } + else if (this->getDirMode() != Part::Extrusion::dmEdge && !hasValidAxisLink) { + // axis link is invalid, but it is not required by the mode. We shouldn't complain it's + // invalid then... ui->txtLink->clear(); } - //check normal - if (this->getDirMode() == Part::Extrusion::dmNormal){ + // check normal + if (this->getDirMode() == Part::Extrusion::dmNormal) { errmsg.clear(); try { App::PropertyLink lnk; - lnk.setValue(&this->getShapeToExtrude()); //simplified - check only for the first shape. + lnk.setValue(&this->getShapeToExtrude()); // simplified - check only for the first shape. Part::Extrusion::calculateShapeNormal(lnk); - } catch(Base::Exception &err) { + } + catch (Base::Exception& err) { errmsg = QCoreApplication::translate("Exception", err.what()); - } catch(Standard_Failure &err) { + } + catch (Standard_Failure& err) { errmsg = QString::fromLocal8Bit(err.GetMessageString()); - } catch(...) { + } + catch (...) { errmsg = QStringLiteral("Unknown error"); } - if (errmsg.length() > 0){ - QMessageBox::critical(this, windowTitle(), tr("Cannot determine normal vector of shape to be extruded. Use other mode. \n\n(%1)").arg(errmsg)); + if (errmsg.length() > 0) { + QMessageBox::critical( + this, + windowTitle(), + tr("Cannot determine normal vector of shape to be extruded. Use other mode. " + "\n\n(%1)") + .arg(errmsg) + ); ui->rbDirModeNormal->setFocus(); return false; } } - //check axis dir - if (this->getDirMode() == Part::Extrusion::dmCustom){ - if(this->getDir().Length() < Precision::Confusion()){ - QMessageBox::critical(this, windowTitle(), - tr("Extrusion direction vector is zero-length. It must be non-zero.")); + // check axis dir + if (this->getDirMode() == Part::Extrusion::dmCustom) { + if (this->getDir().Length() < Precision::Confusion()) { + QMessageBox::critical( + this, + windowTitle(), + tr("Extrusion direction vector is zero-length. It must be non-zero.") + ); ui->dirX->setFocus(); return false; } } - //check lengths + // check lengths if (!ui->chkSymmetric->isChecked() - && fabs(ui->spinLenFwd->value().getValue() + ui->spinLenRev->value().getValue()) < Precision::Confusion() - && ! (fabs(ui->spinLenFwd->value().getValue() - ui->spinLenRev->value().getValue()) < Precision::Confusion())){ - QMessageBox::critical(this, windowTitle(), - tr("Total extrusion length is zero (length1 == -length2). It must be nonzero.")); + && fabs(ui->spinLenFwd->value().getValue() + ui->spinLenRev->value().getValue()) + < Precision::Confusion() + && !( + fabs(ui->spinLenFwd->value().getValue() - ui->spinLenRev->value().getValue()) + < Precision::Confusion() + )) { + QMessageBox::critical( + this, + windowTitle(), + tr("Total extrusion length is zero (length1 == -length2). It must be nonzero.") + ); ui->spinLenFwd->setFocus(); return false; } @@ -722,20 +815,37 @@ bool DlgExtrusion::validate() return true; } -void DlgExtrusion::writeParametersToFeature(App::DocumentObject &feature, App::DocumentObject* base) const +void DlgExtrusion::writeParametersToFeature(App::DocumentObject& feature, App::DocumentObject* base) const { - Gui::Command::doCommand(Gui::Command::Doc,"f = App.getDocument('%s').getObject('%s')", feature.getDocument()->getName(), feature.getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Doc, + "f = App.getDocument('%s').getObject('%s')", + feature.getDocument()->getName(), + feature.getNameInDocument() + ); - if (base) - Gui::Command::doCommand(Gui::Command::Doc,"f.Base = App.getDocument('%s').getObject('%s')", base->getDocument()->getName(), base->getNameInDocument()); + if (base) { + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Base = App.getDocument('%s').getObject('%s')", + base->getDocument()->getName(), + base->getNameInDocument() + ); + } Part::Extrusion::eDirMode dirMode = this->getDirMode(); const char* modestr = Part::Extrusion::eDirModeStrings[dirMode]; - Gui::Command::doCommand(Gui::Command::Doc,"f.DirMode = \"%s\"", modestr); + Gui::Command::doCommand(Gui::Command::Doc, "f.DirMode = \"%s\"", modestr); - if (dirMode == Part::Extrusion::dmCustom){ + if (dirMode == Part::Extrusion::dmCustom) { Base::Vector3d dir = this->getDir(); - Gui::Command::doCommand(Gui::Command::Doc, "f.Dir = App.Vector(%.15f, %.15f, %.15f)", dir.x, dir.y, dir.z); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Dir = App.Vector(%.15f, %.15f, %.15f)", + dir.x, + dir.y, + dir.z + ); } App::PropertyLinkSub lnk; @@ -743,24 +853,46 @@ void DlgExtrusion::writeParametersToFeature(App::DocumentObject &feature, App::D std::stringstream linkstr; if (!lnk.getValue()) { linkstr << "None"; - } else { - linkstr << "(App.getDocument(\"" << lnk.getValue()->getDocument()->getName() <<"\")." << lnk.getValue()->getNameInDocument(); + } + else { + linkstr << "(App.getDocument(\"" << lnk.getValue()->getDocument()->getName() << "\")." + << lnk.getValue()->getNameInDocument(); linkstr << ", ["; - for (const std::string &str: lnk.getSubValues()){ + for (const std::string& str : lnk.getSubValues()) { linkstr << "\"" << str << "\""; } linkstr << "])"; } - Gui::Command::doCommand(Gui::Command::Doc,"f.DirLink = %s", linkstr.str().c_str()); + Gui::Command::doCommand(Gui::Command::Doc, "f.DirLink = %s", linkstr.str().c_str()); - Gui::Command::doCommand(Gui::Command::Doc,"f.LengthFwd = %.15f", ui->spinLenFwd->value().getValue()); - Gui::Command::doCommand(Gui::Command::Doc,"f.LengthRev = %.15f", ui->spinLenRev->value().getValue()); + Gui::Command::doCommand(Gui::Command::Doc, "f.LengthFwd = %.15f", ui->spinLenFwd->value().getValue()); + Gui::Command::doCommand(Gui::Command::Doc, "f.LengthRev = %.15f", ui->spinLenRev->value().getValue()); - Gui::Command::doCommand(Gui::Command::Doc,"f.Solid = %s", ui->chkSolid->isChecked() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc,"f.Reversed = %s", ui->chkReversed->isChecked() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc,"f.Symmetric = %s", ui->chkSymmetric->isChecked() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc,"f.TaperAngle = %.15f", ui->spinTaperAngle->value().getValue()); - Gui::Command::doCommand(Gui::Command::Doc,"f.TaperAngleRev = %.15f", ui->spinTaperAngleRev->value().getValue()); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Solid = %s", + ui->chkSolid->isChecked() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Reversed = %s", + ui->chkReversed->isChecked() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Symmetric = %s", + ui->chkSymmetric->isChecked() ? "True" : "False" + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.TaperAngle = %.15f", + ui->spinTaperAngle->value().getValue() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.TaperAngleRev = %.15f", + ui->spinTaperAngleRev->value().getValue() + ); } @@ -787,13 +919,12 @@ bool TaskExtrusion::reject() void TaskExtrusion::clicked(int id) { if (id == QDialogButtonBox::Apply) { - try{ + try { widget->apply(); - } catch (Base::AbortException&){ - + } + catch (Base::AbortException&) { }; } } #include "moc_DlgExtrusion.cpp" - diff --git a/src/Mod/Part/Gui/DlgExtrusion.h b/src/Mod/Part/Gui/DlgExtrusion.h index b49b72efa5..83de97af4c 100644 --- a/src/Mod/Part/Gui/DlgExtrusion.h +++ b/src/Mod/Part/Gui/DlgExtrusion.h @@ -35,10 +35,11 @@ class TopoDS_Shape; -namespace PartGui { +namespace PartGui +{ class Ui_DlgExtrusion; -class DlgExtrusion : public QDialog, public Gui::SelectionObserver +class DlgExtrusion: public QDialog, public Gui::SelectionObserver { Q_OBJECT @@ -55,8 +56,8 @@ public: Part::Extrusion::eDirMode getDirMode() const; void setDirMode(Part::Extrusion::eDirMode newMode); - void getAxisLink(App::PropertyLinkSub &lnk) const; - void setAxisLink(const App::PropertyLinkSub &lnk); + void getAxisLink(App::PropertyLinkSub& lnk) const; + void setAxisLink(const App::PropertyLinkSub& lnk); void setAxisLink(const char* objname, const char* subname); std::vector getShapesToExtrude() const; @@ -68,7 +69,7 @@ public: protected: void findShapes(); bool canExtrude(const TopoDS_Shape&) const; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void keyPressEvent(QKeyEvent*) override; private: @@ -84,15 +85,16 @@ private: void onTextLinkTextChanged(QString); private: - ///updates enabling of controls + /// updates enabling of controls void onDirModeChanged(); void onSelectionChanged(const Gui::SelectionChanges& msg) override; - ///returns link to any of selected source shapes. Throws if nothing is selected for extrusion. + /// returns link to any of selected source shapes. Throws if nothing is selected for extrusion. App::DocumentObject& getShapeToExtrude() const; - ///if dirMode is not custom, it tries to compute the actual extrusion direction. Also, it does some auto-magic manipulation of length value. + /// if dirMode is not custom, it tries to compute the actual extrusion direction. Also, it does + /// some auto-magic manipulation of length value. void fetchDir(); - ///automatically checks Solid checkbox depending on input shape + /// automatically checks Solid checkbox depending on input shape void autoSolid(); private: @@ -102,7 +104,7 @@ private: EdgeSelection* filter; }; -class TaskExtrusion : public Gui::TaskView::TaskDialog +class TaskExtrusion: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -115,12 +117,14 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Close; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Close; + } private: DlgExtrusion* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGEXTRUSION_H +#endif // PARTGUI_DLGEXTRUSION_H diff --git a/src/Mod/Part/Gui/DlgFilletEdges.cpp b/src/Mod/Part/Gui/DlgFilletEdges.cpp index 6f4841a3a9..e06c63c30b 100644 --- a/src/Mod/Part/Gui/DlgFilletEdges.cpp +++ b/src/Mod/Part/Gui/DlgFilletEdges.cpp @@ -22,28 +22,28 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include +#include +#include #include #include @@ -75,17 +75,21 @@ FC_LOG_LEVEL_INIT("Part", true, true) using namespace PartGui; namespace sp = std::placeholders; -FilletRadiusDelegate::FilletRadiusDelegate(QObject *parent) : QItemDelegate(parent) -{ -} +FilletRadiusDelegate::FilletRadiusDelegate(QObject* parent) + : QItemDelegate(parent) +{} -QWidget *FilletRadiusDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &/* option */, - const QModelIndex & index) const +QWidget* FilletRadiusDelegate::createEditor( + QWidget* parent, + const QStyleOptionViewItem& /* option */, + const QModelIndex& index +) const { - if (index.column() < 1) + if (index.column() < 1) { return nullptr; + } - Gui::QuantitySpinBox *editor = new Gui::QuantitySpinBox(parent); + Gui::QuantitySpinBox* editor = new Gui::QuantitySpinBox(parent); editor->setUnit(Base::Unit::Length); editor->setMinimum(0.0); editor->setMaximum(std::numeric_limits::max()); @@ -94,54 +98,59 @@ QWidget *FilletRadiusDelegate::createEditor(QWidget *parent, const QStyleOptionV return editor; } -void FilletRadiusDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const +void FilletRadiusDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { Base::Quantity value = index.model()->data(index, Qt::EditRole).value(); - Gui::QuantitySpinBox *spinBox = static_cast(editor); + Gui::QuantitySpinBox* spinBox = static_cast(editor); spinBox->setValue(value); } -void FilletRadiusDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const +void FilletRadiusDelegate::setModelData( + QWidget* editor, + QAbstractItemModel* model, + const QModelIndex& index +) const { - Gui::QuantitySpinBox *spinBox = static_cast(editor); + Gui::QuantitySpinBox* spinBox = static_cast(editor); spinBox->interpretText(); - //double value = spinBox->value(); - //QString value = QStringLiteral("%1").arg(spinBox->value(),0,'f',2); - //QString value = QLocale().toString(spinBox->value().getValue(),'f',Base::UnitsApi::getDecimals()); + // double value = spinBox->value(); + // QString value = QStringLiteral("%1").arg(spinBox->value(),0,'f',2); + // QString value = QLocale().toString(spinBox->value().getValue(),'f',Base::UnitsApi::getDecimals()); Base::Quantity value = spinBox->value(); model->setData(index, QVariant::fromValue(value), Qt::EditRole); } -void FilletRadiusDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, - const QModelIndex &/* index */) const +void FilletRadiusDelegate:: + updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& /* index */) const { editor->setGeometry(option.rect); } // -------------------------------------------------------------- -FilletRadiusModel::FilletRadiusModel(QObject * parent) : QStandardItemModel(parent) -{ -} +FilletRadiusModel::FilletRadiusModel(QObject* parent) + : QStandardItemModel(parent) +{} void FilletRadiusModel::updateCheckStates() { - // See http://www.qtcentre.org/threads/18856-Checkboxes-in-Treeview-do-not-get-refreshed?s=b0fea2bfc66da1098413ae9f2a651a68&p=93201#post93201 + // See + // http://www.qtcentre.org/threads/18856-Checkboxes-in-Treeview-do-not-get-refreshed?s=b0fea2bfc66da1098413ae9f2a651a68&p=93201#post93201 Q_EMIT layoutChanged(); } -Qt::ItemFlags FilletRadiusModel::flags (const QModelIndex & index) const +Qt::ItemFlags FilletRadiusModel::flags(const QModelIndex& index) const { Qt::ItemFlags fl = QStandardItemModel::flags(index); - if (index.column() == 0) + if (index.column() == 0) { fl = fl | Qt::ItemIsUserCheckable; + } return fl; } -bool FilletRadiusModel::setData (const QModelIndex & index, const QVariant & value, int role) +bool FilletRadiusModel::setData(const QModelIndex& index, const QVariant& value, int role) { bool ok = QStandardItemModel::setData(index, value, role); if (role == Qt::CheckStateRole) { @@ -163,72 +172,84 @@ QVariant FilletRadiusModel::data(const QModelIndex& index, int role) const // -------------------------------------------------------------- -namespace PartGui { - class EdgeFaceSelection : public Gui::SelectionFilterGate - { - bool allowEdge{true}; - App::DocumentObject*& object; - public: - explicit EdgeFaceSelection(App::DocumentObject*& obj) - : Gui::SelectionFilterGate(nullPointer()) - , object(obj) - { - } - void selectEdges() - { - allowEdge = true; - } - void selectFaces() - { - allowEdge = false; - } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override - { - if (pObj != this->object) - return false; - if (Base::Tools::isNullOrEmpty(sSubName)) - return false; - std::string element(sSubName); - if (allowEdge) - return element.substr(0,4) == "Edge"; - else - return element.substr(0,4) == "Face"; - } - }; - class DlgFilletEdges::Private - { - public: - App::DocumentObject* object; - EdgeFaceSelection* selection; - Part::FilletBase* fillet; - QTimer* highlighttimer; - FilletType filletType; - std::vector edge_ids; - TopTools_IndexedMapOfShape all_edges; - TopTools_IndexedMapOfShape all_faces; - using Connection = boost::signals2::connection; - Connection connectApplicationDeletedObject; - Connection connectApplicationDeletedDocument; +namespace PartGui +{ +class EdgeFaceSelection: public Gui::SelectionFilterGate +{ + bool allowEdge {true}; + App::DocumentObject*& object; - class SelectionObjectCompare +public: + explicit EdgeFaceSelection(App::DocumentObject*& obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) + {} + void selectEdges() + { + allowEdge = true; + } + void selectFaces() + { + allowEdge = false; + } + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override + { + if (pObj != this->object) { + return false; + } + if (Base::Tools::isNullOrEmpty(sSubName)) { + return false; + } + std::string element(sSubName); + if (allowEdge) { + return element.substr(0, 4) == "Edge"; + } + else { + return element.substr(0, 4) == "Face"; + } + } +}; +class DlgFilletEdges::Private +{ +public: + App::DocumentObject* object; + EdgeFaceSelection* selection; + Part::FilletBase* fillet; + QTimer* highlighttimer; + FilletType filletType; + std::vector edge_ids; + TopTools_IndexedMapOfShape all_edges; + TopTools_IndexedMapOfShape all_faces; + using Connection = boost::signals2::connection; + Connection connectApplicationDeletedObject; + Connection connectApplicationDeletedDocument; + + class SelectionObjectCompare + { + public: + App::DocumentObject* obj; + explicit SelectionObjectCompare(App::DocumentObject* obj) + : obj(obj) + {} + bool operator()(const Gui::SelectionObject& sel) const { - public: - App::DocumentObject* obj; - explicit SelectionObjectCompare(App::DocumentObject* obj) : obj(obj) - { - } - bool operator()(const Gui::SelectionObject& sel) const - { - return (sel.getObject() == obj); - } - }; + return (sel.getObject() == obj); + } }; -} +}; +} // namespace PartGui /* TRANSLATOR PartGui::DlgFilletEdges */ -DlgFilletEdges::DlgFilletEdges(FilletType type, Part::FilletBase* fillet, QWidget* parent, Qt::WindowFlags fl) - : QWidget(parent, fl), ui(new Ui_DlgFilletEdges()), d(new Private()) +DlgFilletEdges::DlgFilletEdges( + FilletType type, + Part::FilletBase* fillet, + QWidget* parent, + Qt::WindowFlags fl +) + : QWidget(parent, fl) + , ui(new Ui_DlgFilletEdges()) + , d(new Private()) { ui->setupUi(this); setupConnections(); @@ -246,23 +267,23 @@ DlgFilletEdges::DlgFilletEdges(FilletType type, Part::FilletBase* fillet, QWidge Gui::Selection().addSelectionGate(d->selection); d->fillet = fillet; - //NOLINTBEGIN - d->connectApplicationDeletedObject = App::GetApplication().signalDeletedObject - .connect(std::bind(&DlgFilletEdges::onDeleteObject, this, sp::_1)); - d->connectApplicationDeletedDocument = App::GetApplication().signalDeleteDocument - .connect(std::bind(&DlgFilletEdges::onDeleteDocument, this, sp::_1)); - //NOLINTEND - // set tree view with three columns + // NOLINTBEGIN + d->connectApplicationDeletedObject = App::GetApplication().signalDeletedObject.connect( + std::bind(&DlgFilletEdges::onDeleteObject, this, sp::_1) + ); + d->connectApplicationDeletedDocument = App::GetApplication().signalDeleteDocument.connect( + std::bind(&DlgFilletEdges::onDeleteDocument, this, sp::_1) + ); + // NOLINTEND + // set tree view with three columns FilletRadiusModel* model = new FilletRadiusModel(this); - connect(model, &FilletRadiusModel::toggleCheckState, - this, &DlgFilletEdges::toggleCheckState); - model->insertColumns(0,3); + connect(model, &FilletRadiusModel::toggleCheckState, this, &DlgFilletEdges::toggleCheckState); + model->insertColumns(0, 3); // timer for highlighting d->highlighttimer = new QTimer(this); d->highlighttimer->setSingleShot(true); - connect(d->highlighttimer, &QTimer::timeout, - this, &DlgFilletEdges::onHighlightEdges); + connect(d->highlighttimer, &QTimer::timeout, this, &DlgFilletEdges::onHighlightEdges); d->filletType = type; if (d->filletType == DlgFilletEdges::CHAMFER) { @@ -333,16 +354,17 @@ void DlgFilletEdges::setupConnections() void DlgFilletEdges::onSelectionChanged(const Gui::SelectionChanges& msg) { // no object selected in the combobox or no sub-element was selected - if (!d->object || !msg.pSubName) + if (!d->object || !msg.pSubName) { return; - if (msg.Type == Gui::SelectionChanges::AddSelection || - msg.Type == Gui::SelectionChanges::RmvSelection) { + } + if (msg.Type == Gui::SelectionChanges::AddSelection + || msg.Type == Gui::SelectionChanges::RmvSelection) { // when adding a sub-element to the selection check // whether this is the currently handled object App::Document* doc = d->object->getDocument(); std::string docname = doc->getName(); std::string objname = d->object->getNameInDocument(); - if (docname==msg.pDocName && objname==msg.pObjectName) { + if (docname == msg.pDocName && objname == msg.pObjectName) { QString subelement = QString::fromLatin1(msg.pSubName); if (subelement.startsWith(QLatin1String("Edge"))) { onSelectEdge(subelement, msg.Type); @@ -355,9 +377,10 @@ void DlgFilletEdges::onSelectionChanged(const Gui::SelectionChanges& msg) } } - if (msg.Type != Gui::SelectionChanges::SetPreselect && - msg.Type != Gui::SelectionChanges::RmvPreselect) + if (msg.Type != Gui::SelectionChanges::SetPreselect + && msg.Type != Gui::SelectionChanges::RmvPreselect) { d->highlighttimer->start(20); + } } void DlgFilletEdges::onHighlightEdges() @@ -396,7 +419,9 @@ void DlgFilletEdges::onHighlightEdges() searchAction.apply(view->getRoot()); SoPath* selectionPath = searchAction.getPath(); if (selectionPath) { - ParameterGrp::handle hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup("View"); + ParameterGrp::handle hGrp = Gui::WindowParameter::getDefaultParameter()->GetGroup( + "View" + ); SbColor selectionColor(0.1f, 0.8f, 0.1f); unsigned long selection = (unsigned long)(selectionColor.getPackedValue()); selection = hGrp->GetUnsigned("SelectionColor", selection); @@ -414,15 +439,15 @@ void DlgFilletEdges::onHighlightEdges() QAbstractItemModel* model = ui->treeView->model(); SoLineDetail detail; action.setElement(&detail); - for (int i=0; irowCount(); ++i) { - QVariant value = model->index(i,0).data(Qt::CheckStateRole); + for (int i = 0; i < model->rowCount(); ++i) { + QVariant value = model->index(i, 0).data(Qt::CheckStateRole); Qt::CheckState checkState = static_cast(value.toInt()); // is item checked if (checkState & Qt::Checked) { // the index value of the edge - int id = model->index(i,0).data(Qt::UserRole).toInt(); - detail.setLineIndex(id-1); + int id = model->index(i, 0).data(Qt::UserRole).toInt(); + detail.setLineIndex(id - 1); action.apply(selectionPath); } } @@ -435,20 +460,19 @@ void DlgFilletEdges::onSelectEdge(const QString& subelement, int type) { Gui::SelectionChanges::MsgType msgType = Gui::SelectionChanges::MsgType(type); QAbstractItemModel* model = ui->treeView->model(); - for (int i=0; irowCount(); ++i) { - int id = model->data(model->index(i,0), Qt::UserRole).toInt(); + for (int i = 0; i < model->rowCount(); ++i) { + int id = model->data(model->index(i, 0), Qt::UserRole).toInt(); QString name = QStringLiteral("Edge%1").arg(id); if (name == subelement) { // ok, check the selected sub-element - Qt::CheckState checkState = - (msgType == Gui::SelectionChanges::AddSelection - ? Qt::Checked : Qt::Unchecked); + Qt::CheckState checkState + = (msgType == Gui::SelectionChanges::AddSelection ? Qt::Checked : Qt::Unchecked); QVariant value(static_cast(checkState)); - QModelIndex index = model->index(i,0); + QModelIndex index = model->index(i, 0); model->setData(index, value, Qt::CheckStateRole); // select the item - ui->treeView->selectionModel()->setCurrentIndex(index,QItemSelectionModel::NoUpdate); - QItemSelection selection(index, model->index(i,1)); + ui->treeView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate); + QItemSelection selection(index, model->index(i, 1)); ui->treeView->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect); ui->treeView->update(); break; @@ -466,15 +490,18 @@ void DlgFilletEdges::onSelectEdgesOfFace(const QString& subelement, int type) TopTools_IndexedMapOfShape mapOfEdges; TopExp::MapShapes(face, TopAbs_EDGE, mapOfEdges); - for(int j = 1; j <= mapOfEdges.Extent(); ++j) { + for (int j = 1; j <= mapOfEdges.Extent(); ++j) { TopoDS_Edge edge = TopoDS::Edge(mapOfEdges.FindKey(j)); int id = d->all_edges.FindIndex(edge); QString name = QStringLiteral("Edge%1").arg(id); onSelectEdge(name, type); Gui::SelectionChanges::MsgType msgType = Gui::SelectionChanges::MsgType(type); if (msgType == Gui::SelectionChanges::AddSelection) { - Gui::Selection().addSelection(d->object->getDocument()->getName(), - d->object->getNameInDocument(), (const char*)name.toLatin1()); + Gui::Selection().addSelection( + d->object->getDocument()->getName(), + d->object->getNameInDocument(), + (const char*)name.toLatin1() + ); } } } @@ -503,7 +530,7 @@ void DlgFilletEdges::onDeleteObject(const App::DocumentObject& obj) else { QString shape = QString::fromLatin1(obj.getNameInDocument()); // start from the second item - for (int i=1; ishapeObject->count(); i++) { + for (int i = 1; i < ui->shapeObject->count(); i++) { if (ui->shapeObject->itemData(i).toString() == shape) { ui->shapeObject->removeItem(i); break; @@ -530,8 +557,9 @@ void DlgFilletEdges::onDeleteDocument(const App::Document& doc) void DlgFilletEdges::toggleCheckState(const QModelIndex& index) { - if (!d->object) + if (!d->object) { return; + } QVariant check = index.data(Qt::CheckStateRole); int id = index.data(Qt::UserRole).toInt(); QString name = QStringLiteral("Edge%1").arg(id); @@ -542,15 +570,19 @@ void DlgFilletEdges::toggleCheckState(const QModelIndex& index) // is item checked if (checkState & Qt::Checked) { App::Document* doc = d->object->getDocument(); - Gui::Selection().addSelection(doc->getName(), + Gui::Selection().addSelection( + doc->getName(), d->object->getNameInDocument(), - (const char*)name.toLatin1()); + (const char*)name.toLatin1() + ); } else { App::Document* doc = d->object->getDocument(); - Gui::Selection().rmvSelection(doc->getName(), + Gui::Selection().rmvSelection( + doc->getName(), d->object->getNameInDocument(), - (const char*)name.toLatin1()); + (const char*)name.toLatin1() + ); } this->blockSelection(block); @@ -559,14 +591,17 @@ void DlgFilletEdges::toggleCheckState(const QModelIndex& index) void DlgFilletEdges::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } - std::vector objs = activeDoc->getObjectsOfType - (Part::Feature::getClassTypeId()); + std::vector objs = activeDoc->getObjectsOfType( + Part::Feature::getClassTypeId() + ); int index = 1; int current_index = 0; - for (std::vector::iterator it = objs.begin(); it!=objs.end(); ++it, ++index) { + for (std::vector::iterator it = objs.begin(); it != objs.end(); + ++it, ++index) { ui->shapeObject->addItem(QString::fromUtf8((*it)->Label.getValue())); ui->shapeObject->setItemData(index, QString::fromLatin1((*it)->getNameInDocument())); if (current_index == 0) { @@ -577,8 +612,9 @@ void DlgFilletEdges::findShapes() } // if only one object is in the document then simply use that - if (objs.size() == 1) + if (objs.size() == 1) { current_index = 1; + } if (current_index > 0) { ui->shapeObject->setCurrentIndex(current_index); @@ -595,23 +631,28 @@ void DlgFilletEdges::setupFillet(const std::vector& objs) { App::DocumentObject* base = d->fillet->Base.getValue(); const std::vector& e = d->fillet->Edges.getValues(); - const auto &subs = d->fillet->EdgeLinks.getShadowSubs(); - if(subs.size()!=e.size()) { + const auto& subs = d->fillet->EdgeLinks.getShadowSubs(); + if (subs.size() != e.size()) { FC_ERR("edge link size mismatch"); return; } std::set subSet; - for(auto &sub : subs) - subSet.insert(sub.newName.empty()?sub.oldName:sub.newName); + for (auto& sub : subs) { + subSet.insert(sub.newName.empty() ? sub.oldName : sub.newName); + } if (auto it = std::ranges::find(objs, base); it != objs.end()) { // toggle visibility std::string tmp; Gui::ViewProvider* vp; vp = Gui::Application::Instance->getViewProvider(d->fillet); - if (vp) vp->hide(); + if (vp) { + vp->hide(); + } vp = Gui::Application::Instance->getViewProvider(base); - if (vp) vp->show(); + if (vp) { + vp->show(); + } int current_index = (it - objs.begin()) + 1; ui->shapeObject->setCurrentIndex(current_index); @@ -623,56 +664,73 @@ void DlgFilletEdges::setupFillet(const std::vector& objs) bool twoRadii = false; std::vector subElements; - QStandardItemModel *model = qobject_cast(ui->treeView->model()); - bool block = model->blockSignals(true); // do not call toggleCheckState - auto baseShape = Part::Feature::getTopoShape(base, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + QStandardItemModel* model = qobject_cast(ui->treeView->model()); + bool block = model->blockSignals(true); // do not call toggleCheckState + auto baseShape = Part::Feature::getTopoShape( + base, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); std::set elements; - for(size_t i=0;igetFullName() << "." << ref); - for(auto &mapped : Part::Feature::getRelatedElements(base,ref.c_str())) { + for (auto& mapped : Part::Feature::getRelatedElements(base, ref.c_str())) { tmp.clear(); - if(!subSet.insert(mapped.index.appendToStringBuffer(tmp)).second - || !subSet.insert(mapped.name.toString(0)).second) + if (!subSet.insert(mapped.index.appendToStringBuffer(tmp)).second + || !subSet.insert(mapped.name.toString(0)).second) { continue; + } FC_WARN("guess element reference: " << ref << " -> " << mapped.index); - elements.emplace(mapped.index.getIndex(),e[i].radius1,e[i].radius2); + elements.emplace(mapped.index.getIndex(), e[i].radius1, e[i].radius2); } } - for (const auto & et : e) { + for (const auto& et : e) { auto it2 = std::ranges::find(d->edge_ids, et.edgeid); if (it2 != d->edge_ids.end()) { int index = it2 - d->edge_ids.begin(); model->setData(model->index(index, 0), Qt::Checked, Qt::CheckStateRole); - //model->setData(model->index(index, 1), QVariant(QLocale().toString(et->radius1,'f',Base::UnitsApi::getDecimals()))); - //model->setData(model->index(index, 2), QVariant(QLocale().toString(et->radius2,'f',Base::UnitsApi::getDecimals()))); - model->setData(model->index(index, 1), QVariant::fromValue(Base::Quantity(et.radius1, Base::Unit::Length))); - model->setData(model->index(index, 2), QVariant::fromValue(Base::Quantity(et.radius2, Base::Unit::Length))); + // model->setData(model->index(index, 1), + // QVariant(QLocale().toString(et->radius1,'f',Base::UnitsApi::getDecimals()))); + // model->setData(model->index(index, 2), + // QVariant(QLocale().toString(et->radius2,'f',Base::UnitsApi::getDecimals()))); + model->setData( + model->index(index, 1), + QVariant::fromValue(Base::Quantity(et.radius1, Base::Unit::Length)) + ); + model->setData( + model->index(index, 2), + QVariant::fromValue(Base::Quantity(et.radius2, Base::Unit::Length)) + ); startRadius = et.radius1; endRadius = et.radius2; - if (startRadius != endRadius) + if (startRadius != endRadius) { twoRadii = true; + } int id = model->index(index, 0).data(Qt::UserRole).toInt(); std::stringstream str; @@ -698,36 +756,36 @@ void DlgFilletEdges::setupFillet(const std::vector& objs) App::Document* doc = d->object->getDocument(); // get current selection and their sub-elements - //std::vector selObj = Gui::Selection().getSelectionEx(doc->getName()); - //std::vector::iterator selIt = std::find_if(selObj.begin(), selObj.end(), + // std::vector selObj = + // Gui::Selection().getSelectionEx(doc->getName()); + // std::vector::iterator selIt = std::find_if(selObj.begin(), + // selObj.end(), // Private::SelectionObjectCompare(d->object)); - /* - * Edit: the following check is no longer necessary, as Gui::Selection - * will do the check - * - // If sub-objects are already selected then only add the un-selected parts. - // This is important to avoid recursive calls of rmvSelection() which - // invalidates the internal iterator (#0002200). - if (selIt != selObj.end()) { - std::vector selElements = selIt->getSubNames(); - std::sort(selElements.begin(), selElements.end()); - std::sort(subElements.begin(), subElements.end()); + /* + * Edit: the following check is no longer necessary, as Gui::Selection + * will do the check + * + // If sub-objects are already selected then only add the un-selected parts. + // This is important to avoid recursive calls of rmvSelection() which + // invalidates the internal iterator (#0002200). + if (selIt != selObj.end()) { + std::vector selElements = selIt->getSubNames(); + std::sort(selElements.begin(), selElements.end()); + std::sort(subElements.begin(), subElements.end()); - std::vector complementary; - std::back_insert_iterator > biit(complementary); - std::set_difference(subElements.begin(), subElements.end(), selElements.begin(), selElements.end(), biit); - subElements = complementary; - } - */ + std::vector complementary; + std::back_insert_iterator > biit(complementary); + std::set_difference(subElements.begin(), subElements.end(), selElements.begin(), + selElements.end(), biit); subElements = complementary; + } + */ Gui::Selection().clearSelection(doc->getName()); if (!subElements.empty()) { - Gui::Selection().addSelections(doc->getName(), - d->object->getNameInDocument(), - subElements); + Gui::Selection().addSelections(doc->getName(), d->object->getNameInDocument(), subElements); } } } @@ -735,7 +793,7 @@ void DlgFilletEdges::setupFillet(const std::vector& objs) /** * Sets the strings of the subwidgets using the current language. */ -void DlgFilletEdges::changeEvent(QEvent *e) +void DlgFilletEdges::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { int index = ui->shapeObject->currentIndex(); @@ -743,21 +801,21 @@ void DlgFilletEdges::changeEvent(QEvent *e) int count = ui->shapeObject->count() - 1; QStringList text; QList data; - for (int i=0; ishapeObject->itemText(i+1); - data << ui->shapeObject->itemData(i+1); + for (int i = 0; i < count; i++) { + text << ui->shapeObject->itemText(i + 1); + data << ui->shapeObject->itemData(i + 1); } ui->retranslateUi(this); - for (int i=0; ishapeObject->addItem(text.at(i)); - ui->shapeObject->setItemData(i+1, data.at(i)); + ui->shapeObject->setItemData(i + 1, data.at(i)); } ui->shapeObject->setCurrentIndex(index); - QStandardItemModel *model = qobject_cast(ui->treeView->model()); + QStandardItemModel* model = qobject_cast(ui->treeView->model()); count = model->rowCount(); - for (int i=0; idata(model->index(i, 0), Qt::UserRole).toInt(); model->setData(model->index(i, 0), QVariant(tr("Edge%1").arg(id))); } @@ -770,13 +828,14 @@ void DlgFilletEdges::changeEvent(QEvent *e) void DlgFilletEdges::onShapeObjectActivated(int itemPos) { d->object = nullptr; - QStandardItemModel *model = qobject_cast(ui->treeView->model()); + QStandardItemModel* model = qobject_cast(ui->treeView->model()); model->removeRows(0, model->rowCount()); QByteArray name = ui->shapeObject->itemData(itemPos).toByteArray(); App::Document* doc = App::GetApplication().getActiveDocument(); - if (!doc) + if (!doc) { return; + } App::DocumentObject* part = doc->getObject((const char*)name); if (part && part->isDerivedFrom()) { d->object = part; @@ -796,7 +855,7 @@ void DlgFilletEdges::onShapeObjectActivated(int itemPos) // populate the model d->edge_ids.clear(); - for (int i=1; i<= edge2Face.Extent(); ++i) { + for (int i = 1; i <= edge2Face.Extent(); ++i) { // set the index value as user data to use it in accept() const TopTools_ListOfShape& los = edge2Face.FindFromIndex(i); if (los.Extent() == 2) { @@ -806,9 +865,11 @@ void DlgFilletEdges::onShapeObjectActivated(int itemPos) // faces const TopoDS_Shape& face1 = los.First(); const TopoDS_Shape& face2 = los.Last(); - GeomAbs_Shape cont = BRep_Tool::Continuity(TopoDS::Edge(edge), - TopoDS::Face(face1), - TopoDS::Face(face2)); + GeomAbs_Shape cont = BRep_Tool::Continuity( + TopoDS::Edge(edge), + TopoDS::Face(face1), + TopoDS::Face(face2) + ); if (cont == GeomAbs_C0) { int id = mapOfShape.FindIndex(edge); d->edge_ids.push_back(id); @@ -821,16 +882,26 @@ void DlgFilletEdges::onShapeObjectActivated(int itemPos) for (int id : d->edge_ids) { model->setData(model->index(index, 0), QVariant(tr("Edge%1").arg(id))); model->setData(model->index(index, 0), QVariant(id), Qt::UserRole); - //model->setData(model->index(index, 1), QVariant(QLocale().toString(1.0,'f',Base::UnitsApi::getDecimals()))); - //model->setData(model->index(index, 2), QVariant(QLocale().toString(1.0,'f',Base::UnitsApi::getDecimals()))); - model->setData(model->index(index, 1), QVariant::fromValue(Base::Quantity(1.0,Base::Unit::Length))); - model->setData(model->index(index, 2), QVariant::fromValue(Base::Quantity(1.0,Base::Unit::Length))); + // model->setData(model->index(index, 1), + // QVariant(QLocale().toString(1.0,'f',Base::UnitsApi::getDecimals()))); + // model->setData(model->index(index, 2), + // QVariant(QLocale().toString(1.0,'f',Base::UnitsApi::getDecimals()))); + model->setData( + model->index(index, 1), + QVariant::fromValue(Base::Quantity(1.0, Base::Unit::Length)) + ); + model->setData( + model->index(index, 2), + QVariant::fromValue(Base::Quantity(1.0, Base::Unit::Length)) + ); std::stringstream element; element << "Edge" << id; - if (Gui::Selection().isSelected(part, element.str().c_str())) + if (Gui::Selection().isSelected(part, element.str().c_str())) { model->setData(model->index(index, 0), Qt::Checked, Qt::CheckStateRole); - else + } + else { model->setData(model->index(index, 0), Qt::Unchecked, Qt::CheckStateRole); + } index++; } } @@ -838,21 +909,25 @@ void DlgFilletEdges::onShapeObjectActivated(int itemPos) void DlgFilletEdges::onSelectEdgesToggled(bool on) { - if (on) d->selection->selectEdges(); + if (on) { + d->selection->selectEdges(); + } } void DlgFilletEdges::onSelectFacesToggled(bool on) { - if (on) d->selection->selectFaces(); + if (on) { + d->selection->selectFaces(); + } } void DlgFilletEdges::onSelectAllButtonClicked() { std::vector subElements; FilletRadiusModel* model = static_cast(ui->treeView->model()); - bool block = model->blockSignals(true); // do not call toggleCheckState - for (int i=0; irowCount(); ++i) { - QModelIndex index = model->index(i,0); + bool block = model->blockSignals(true); // do not call toggleCheckState + for (int i = 0; i < model->rowCount(); ++i) { + QModelIndex index = model->index(i, 0); // is not yet checked? QVariant check = index.data(Qt::CheckStateRole); @@ -873,20 +948,18 @@ void DlgFilletEdges::onSelectAllButtonClicked() if (d->object) { App::Document* doc = d->object->getDocument(); - Gui::Selection().addSelections(doc->getName(), - d->object->getNameInDocument(), - subElements); + Gui::Selection().addSelections(doc->getName(), d->object->getNameInDocument(), subElements); } } void DlgFilletEdges::onSelectNoneButtonClicked() { FilletRadiusModel* model = static_cast(ui->treeView->model()); - bool block = model->blockSignals(true); // do not call toggleCheckState - for (int i=0; irowCount(); ++i) { + bool block = model->blockSignals(true); // do not call toggleCheckState + for (int i = 0; i < model->rowCount(); ++i) { Qt::CheckState checkState = Qt::Unchecked; QVariant value(static_cast(checkState)); - model->setData(model->index(i,0), value, Qt::CheckStateRole); + model->setData(model->index(i, 0), value, Qt::CheckStateRole); } model->blockSignals(block); model->updateCheckStates(); @@ -899,20 +972,24 @@ void DlgFilletEdges::onSelectNoneButtonClicked() void DlgFilletEdges::onFilletTypeActivated(int index) { - QStandardItemModel *model = qobject_cast(ui->treeView->model()); + QStandardItemModel* model = qobject_cast(ui->treeView->model()); if (index == 0) { - if (d->filletType == DlgFilletEdges::CHAMFER) + if (d->filletType == DlgFilletEdges::CHAMFER) { model->setHeaderData(1, Qt::Horizontal, tr("Length"), Qt::DisplayRole); - else + } + else { model->setHeaderData(1, Qt::Horizontal, tr("Radius"), Qt::DisplayRole); + } ui->treeView->hideColumn(2); ui->filletEndRadius->hide(); } else { - if (d->filletType == DlgFilletEdges::CHAMFER) + if (d->filletType == DlgFilletEdges::CHAMFER) { model->setHeaderData(1, Qt::Horizontal, tr("Start length"), Qt::DisplayRole); - else + } + else { model->setHeaderData(1, Qt::Horizontal, tr("Start radius"), Qt::DisplayRole); + } ui->treeView->showColumn(2); ui->filletEndRadius->show(); } @@ -925,8 +1002,8 @@ void DlgFilletEdges::onFilletTypeActivated(int index) void DlgFilletEdges::onFilletStartRadiusValueChanged(const Base::Quantity& radius) { QAbstractItemModel* model = ui->treeView->model(); - for (int i=0; irowCount(); ++i) { - QVariant value = model->index(i,0).data(Qt::CheckStateRole); + for (int i = 0; i < model->rowCount(); ++i) { + QVariant value = model->index(i, 0).data(Qt::CheckStateRole); Qt::CheckState checkState = static_cast(value.toInt()); // is item checked @@ -939,8 +1016,8 @@ void DlgFilletEdges::onFilletStartRadiusValueChanged(const Base::Quantity& radiu void DlgFilletEdges::onFilletEndRadiusValueChanged(const Base::Quantity& radius) { QAbstractItemModel* model = ui->treeView->model(); - for (int i=0; irowCount(); ++i) { - QVariant value = model->index(i,0).data(Qt::CheckStateRole); + for (int i = 0; i < model->rowCount(); ++i) { + QVariant value = model->index(i, 0).data(Qt::CheckStateRole); Qt::CheckState checkState = static_cast(value.toInt()); // is item checked @@ -958,9 +1035,12 @@ const char* DlgFilletEdges::getFilletType() const bool DlgFilletEdges::accept() { if (!d->object) { - QMessageBox::warning(this, tr("No shape selected"), + QMessageBox::warning( + this, + tr("No shape selected"), tr("No valid shape is selected.\n" - "Select a valid shape in the drop-down box first.")); + "Select a valid shape in the drop-down box first.") + ); return false; } App::Document* activeDoc = App::GetApplication().getActiveDocument(); @@ -974,61 +1054,70 @@ bool DlgFilletEdges::accept() shape = ui->shapeObject->itemData(index).toString(); type = QStringLiteral("Part::%1").arg(QString::fromLatin1(fillet.c_str())); - if (d->fillet) + if (d->fillet) { name = QString::fromLatin1(d->fillet->getNameInDocument()); - else + } + else { name = QString::fromLatin1(activeDoc->getUniqueObjectName(fillet.c_str()).c_str()); + } activeDoc->openTransaction(fillet.c_str()); QString code; if (!d->fillet) { code = QStringLiteral( - "FreeCAD.ActiveDocument.addObject(\"%1\",\"%2\")\n" - "FreeCAD.ActiveDocument.%2.Base = FreeCAD.ActiveDocument.%3\n") - .arg(type, name, shape); + "FreeCAD.ActiveDocument.addObject(\"%1\",\"%2\")\n" + "FreeCAD.ActiveDocument.%2.Base = FreeCAD.ActiveDocument.%3\n" + ) + .arg(type, name, shape); } code += QStringLiteral("__fillets__ = []\n"); - for (int i=0; irowCount(); ++i) { - QVariant value = model->index(i,0).data(Qt::CheckStateRole); + for (int i = 0; i < model->rowCount(); ++i) { + QVariant value = model->index(i, 0).data(Qt::CheckStateRole); Qt::CheckState checkState = static_cast(value.toInt()); // is item checked if (checkState & Qt::Checked) { // the index value of the edge - int id = model->index(i,0).data(Qt::UserRole).toInt(); - Base::Quantity r1 = model->index(i,1).data(Qt::EditRole).value(); + int id = model->index(i, 0).data(Qt::UserRole).toInt(); + Base::Quantity r1 = model->index(i, 1).data(Qt::EditRole).value(); Base::Quantity r2 = r1; - if (end_radius) - r2 = model->index(i,2).data(Qt::EditRole).value(); - code += QStringLiteral( - "__fillets__.append((%1,%2,%3))\n") - .arg(id) - .arg(r1.getValue(),0,'f',Base::UnitsApi::getDecimals()) - .arg(r2.getValue(),0,'f',Base::UnitsApi::getDecimals()); + if (end_radius) { + r2 = model->index(i, 2).data(Qt::EditRole).value(); + } + code += QStringLiteral("__fillets__.append((%1,%2,%3))\n") + .arg(id) + .arg(r1.getValue(), 0, 'f', Base::UnitsApi::getDecimals()) + .arg(r2.getValue(), 0, 'f', Base::UnitsApi::getDecimals()); todo = true; } } if (!todo) { - QMessageBox::warning(this, tr("No edge selected"), + QMessageBox::warning( + this, + tr("No edge selected"), tr("No edge entity is checked to fillet.\n" - "Check one or more edge entities first.")); + "Check one or more edge entities first.") + ); return false; } Gui::WaitCursor wc; code += QStringLiteral( - "FreeCAD.ActiveDocument.%1.Edges = __fillets__\n" - "del __fillets__\n" - "FreeCADGui.ActiveDocument.%2.Visibility = False\n") - .arg(name, shape); + "FreeCAD.ActiveDocument.%1.Edges = __fillets__\n" + "del __fillets__\n" + "FreeCADGui.ActiveDocument.%2.Visibility = False\n" + ) + .arg(name, shape); Gui::Command::runCommand(Gui::Command::App, code.toLatin1()); activeDoc->commitTransaction(); activeDoc->recompute(); if (d->fillet) { Gui::ViewProvider* vp; vp = Gui::Application::Instance->getViewProvider(d->fillet); - if (vp) vp->show(); + if (vp) { + vp->show(); + } } QByteArray to = name.toLatin1(); @@ -1040,15 +1129,20 @@ bool DlgFilletEdges::accept() // --------------------------------------- -FilletEdgesDialog::FilletEdgesDialog(DlgFilletEdges::FilletType type, Part::FilletBase* fillet, QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) +FilletEdgesDialog::FilletEdgesDialog( + DlgFilletEdges::FilletType type, + Part::FilletBase* fillet, + QWidget* parent, + Qt::WindowFlags fl +) + : QDialog(parent, fl) { widget = new DlgFilletEdges(type, fillet, this); this->setWindowTitle(widget->windowTitle()); QVBoxLayout* hboxLayout = new QVBoxLayout(this); QDialogButtonBox* buttonBox = new QDialogButtonBox(this); - buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); + buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); QObject::connect(buttonBox, &QDialogButtonBox::accepted, this, &FilletEdgesDialog::accept); QObject::connect(buttonBox, &QDialogButtonBox::rejected, this, &FilletEdgesDialog::reject); @@ -1061,8 +1155,9 @@ FilletEdgesDialog::~FilletEdgesDialog() = default; void FilletEdgesDialog::accept() { - if (widget->accept()) + if (widget->accept()) { QDialog::accept(); + } } // --------------------------------------- @@ -1079,24 +1174,23 @@ TaskFilletEdges::~TaskFilletEdges() } void TaskFilletEdges::open() -{ -} +{} void TaskFilletEdges::clicked(int) -{ -} +{} bool TaskFilletEdges::accept() { bool ok = widget->accept(); - if (ok) - Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()"); + if (ok) { + Gui::Command::doCommand(Gui::Command::Gui, "Gui.activeDocument().resetEdit()"); + } return ok; } bool TaskFilletEdges::reject() { - Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()"); + Gui::Command::doCommand(Gui::Command::Gui, "Gui.activeDocument().resetEdit()"); return true; } @@ -1105,7 +1199,7 @@ bool TaskFilletEdges::reject() /* TRANSLATOR PartGui::DlgChamferEdges */ DlgChamferEdges::DlgChamferEdges(Part::FilletBase* chamfer, QWidget* parent, Qt::WindowFlags fl) - : DlgFilletEdges(DlgFilletEdges::CHAMFER, chamfer, parent, fl) + : DlgFilletEdges(DlgFilletEdges::CHAMFER, chamfer, parent, fl) { this->setWindowTitle(tr("Chamfer Edges")); } @@ -1132,24 +1226,23 @@ TaskChamferEdges::~TaskChamferEdges() } void TaskChamferEdges::open() -{ -} +{} void TaskChamferEdges::clicked(int) -{ -} +{} bool TaskChamferEdges::accept() { bool ok = widget->accept(); - if (ok) - Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()"); + if (ok) { + Gui::Command::doCommand(Gui::Command::Gui, "Gui.activeDocument().resetEdit()"); + } return ok; } bool TaskChamferEdges::reject() { - Gui::Command::doCommand(Gui::Command::Gui,"Gui.activeDocument().resetEdit()"); + Gui::Command::doCommand(Gui::Command::Gui, "Gui.activeDocument().resetEdit()"); return true; } diff --git a/src/Mod/Part/Gui/DlgFilletEdges.h b/src/Mod/Part/Gui/DlgFilletEdges.h index 76e06b5fb1..2511775a30 100644 --- a/src/Mod/Part/Gui/DlgFilletEdges.h +++ b/src/Mod/Part/Gui/DlgFilletEdges.h @@ -34,46 +34,53 @@ #include -namespace Base { - class Quantity; -} -namespace Part { - class FilletBase; - class Fillet; - class Chamfer; +namespace Base +{ +class Quantity; } +namespace Part +{ +class FilletBase; +class Fillet; +class Chamfer; +} // namespace Part -namespace PartGui { +namespace PartGui +{ class Ui_DlgFilletEdges; -class FilletRadiusDelegate : public QItemDelegate +class FilletRadiusDelegate: public QItemDelegate { Q_OBJECT public: - explicit FilletRadiusDelegate(QObject *parent = nullptr); + explicit FilletRadiusDelegate(QObject* parent = nullptr); - QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + QWidget* createEditor( + QWidget* parent, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const override; - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; + void setEditorData(QWidget* editor, const QModelIndex& index) const override; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; - void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void updateEditorGeometry( + QWidget* editor, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override; }; -class FilletRadiusModel : public QStandardItemModel +class FilletRadiusModel: public QStandardItemModel { Q_OBJECT public: - explicit FilletRadiusModel(QObject * parent = nullptr); + explicit FilletRadiusModel(QObject* parent = nullptr); - Qt::ItemFlags flags (const QModelIndex & index) const override; - bool setData (const QModelIndex & index, const QVariant & value, - int role = Qt::EditRole) override; + Qt::ItemFlags flags(const QModelIndex& index) const override; + bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override; QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const override; void updateCheckStates(); @@ -81,21 +88,30 @@ Q_SIGNALS: void toggleCheckState(const QModelIndex&); }; -class DlgFilletEdges : public QWidget, public Gui::SelectionObserver +class DlgFilletEdges: public QWidget, public Gui::SelectionObserver { Q_OBJECT public: - enum FilletType { FILLET, CHAMFER }; + enum FilletType + { + FILLET, + CHAMFER + }; - DlgFilletEdges(FilletType type, Part::FilletBase*, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + DlgFilletEdges( + FilletType type, + Part::FilletBase*, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~DlgFilletEdges() override; bool accept(); protected: void findShapes(); void setupFillet(const std::vector&); - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; virtual const char* getFilletType() const; private: @@ -124,12 +140,17 @@ private: std::unique_ptr d; }; -class FilletEdgesDialog : public QDialog +class FilletEdgesDialog: public QDialog { Q_OBJECT public: - FilletEdgesDialog(DlgFilletEdges::FilletType type, Part::FilletBase* fillet, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + FilletEdgesDialog( + DlgFilletEdges::FilletType type, + Part::FilletBase* fillet, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~FilletEdgesDialog() override; void accept() override; @@ -137,19 +158,23 @@ private: DlgFilletEdges* widget; }; -class DlgChamferEdges : public DlgFilletEdges +class DlgChamferEdges: public DlgFilletEdges { Q_OBJECT public: - explicit DlgChamferEdges(Part::FilletBase*, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + explicit DlgChamferEdges( + Part::FilletBase*, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~DlgChamferEdges() override; protected: const char* getFilletType() const override; }; -class TaskFilletEdges : public Gui::TaskView::TaskDialog +class TaskFilletEdges: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -164,15 +189,19 @@ public: bool reject() override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } bool needsFullSpace() const override - { return true; } + { + return true; + } private: DlgFilletEdges* widget; }; -class TaskChamferEdges : public Gui::TaskView::TaskDialog +class TaskChamferEdges: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -187,14 +216,18 @@ public: bool reject() override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } bool needsFullSpace() const override - { return true; } + { + return true; + } private: DlgChamferEdges* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGFILLETEDGES_H +#endif // PARTGUI_DLGFILLETEDGES_H diff --git a/src/Mod/Part/Gui/DlgImportStep.cpp b/src/Mod/Part/Gui/DlgImportStep.cpp index 4d14ccd710..8ae8b94dce 100644 --- a/src/Mod/Part/Gui/DlgImportStep.cpp +++ b/src/Mod/Part/Gui/DlgImportStep.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ -# include +#include #include @@ -36,8 +36,8 @@ using namespace PartGui; DlgImportStep::DlgImportStep(QWidget* parent) - : PreferencePage(parent) - , ui(new Ui_DlgImportStep) + : PreferencePage(parent) + , ui(new Ui_DlgImportStep) { ui->setupUi(this); Part::OCAF::ImportExportSettings settings; @@ -120,7 +120,7 @@ StepImportSettings DlgImportStep::getSettings() const /** * Sets the strings of the subwidgets using the current language. */ -void DlgImportStep::changeEvent(QEvent *e) +void DlgImportStep::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -133,8 +133,8 @@ void DlgImportStep::changeEvent(QEvent *e) // ---------------------------------------------------------------------------- TaskImportStep::TaskImportStep(QWidget* parent) - : QDialog(parent) - , ui(new DlgImportStep(this)) + : QDialog(parent) + , ui(new DlgImportStep(this)) { QApplication::setOverrideCursor(Qt::ArrowCursor); diff --git a/src/Mod/Part/Gui/DlgImportStep.h b/src/Mod/Part/Gui/DlgImportStep.h index 3d2959b2af..b2dd2f486c 100644 --- a/src/Mod/Part/Gui/DlgImportStep.h +++ b/src/Mod/Part/Gui/DlgImportStep.h @@ -33,7 +33,8 @@ class QButtonGroup; class QCheckBox; -namespace PartGui { +namespace PartGui +{ struct StepImportSettings { @@ -49,7 +50,7 @@ struct StepImportSettings }; class Ui_DlgImportStep; -class DlgImportStep : public Gui::Dialog::PreferencePage +class DlgImportStep: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -63,7 +64,7 @@ public: StepImportSettings getSettings() const; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; @@ -71,7 +72,7 @@ private: // ---------------------------------------------------------------------------- -class PartGuiExport TaskImportStep : public QDialog +class PartGuiExport TaskImportStep: public QDialog { Q_OBJECT @@ -88,6 +89,6 @@ private: std::unique_ptr ui; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGIMPORTSTEP_H +#endif // PARTGUI_DLGIMPORTSTEP_H diff --git a/src/Mod/Part/Gui/DlgPartBoxImp.cpp b/src/Mod/Part/Gui/DlgPartBoxImp.cpp index c7fc26a607..f997c8532f 100644 --- a/src/Mod/Part/Gui/DlgPartBoxImp.cpp +++ b/src/Mod/Part/Gui/DlgPartBoxImp.cpp @@ -38,8 +38,7 @@ using namespace PartGui; */ DlgPartBoxImp::DlgPartBoxImp(QWidget* parent, Qt::WindowFlags fl) : Gui::LocationDialogUiImp(new Ui_DlgPartBox, parent, fl) -{ -} +{} /* * Destroys the object and frees any allocated resources diff --git a/src/Mod/Part/Gui/DlgPartBoxImp.h b/src/Mod/Part/Gui/DlgPartBoxImp.h index 023bbe5cb8..87d3441d17 100644 --- a/src/Mod/Part/Gui/DlgPartBoxImp.h +++ b/src/Mod/Part/Gui/DlgPartBoxImp.h @@ -27,11 +27,12 @@ #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgPartBox; using Ui_DlgPartBoxPtr = std::shared_ptr; -class DlgPartBoxImp : public Gui::LocationDialogUiImp +class DlgPartBoxImp: public Gui::LocationDialogUiImp { Q_OBJECT @@ -40,6 +41,6 @@ public: ~DlgPartBoxImp() override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGPARTBOXIMP_H +#endif // PARTGUI_DLGPARTBOXIMP_H diff --git a/src/Mod/Part/Gui/DlgPartCylinderImp.cpp b/src/Mod/Part/Gui/DlgPartCylinderImp.cpp index 9082fb298c..e8766503fa 100644 --- a/src/Mod/Part/Gui/DlgPartCylinderImp.cpp +++ b/src/Mod/Part/Gui/DlgPartCylinderImp.cpp @@ -30,9 +30,8 @@ using namespace PartGui; DlgPartCylinderImp::DlgPartCylinderImp(QWidget* parent, Qt::WindowFlags fl) - : Gui::LocationDialogUiImp(new Ui_DlgPartCylinder, parent, fl) -{ -} + : Gui::LocationDialogUiImp(new Ui_DlgPartCylinder, parent, fl) +{} /* * Destroys the object and frees any allocated resources @@ -41,7 +40,7 @@ DlgPartCylinderImp::~DlgPartCylinderImp() = default; Ui_DlgPartCylinderPtr DlgPartCylinderImp::getUi() const { - return boost::any_cast< Ui_DlgPartCylinderPtr >(ui->get()); + return boost::any_cast(ui->get()); } double DlgPartCylinderImp::getRadius() const diff --git a/src/Mod/Part/Gui/DlgPartCylinderImp.h b/src/Mod/Part/Gui/DlgPartCylinderImp.h index 1fda379837..cea6330d07 100644 --- a/src/Mod/Part/Gui/DlgPartCylinderImp.h +++ b/src/Mod/Part/Gui/DlgPartCylinderImp.h @@ -27,11 +27,12 @@ #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgPartCylinder; using Ui_DlgPartCylinderPtr = std::shared_ptr; -class DlgPartCylinderImp : public Gui::LocationDialogUiImp +class DlgPartCylinderImp: public Gui::LocationDialogUiImp { Q_OBJECT @@ -46,6 +47,6 @@ private: Ui_DlgPartCylinderPtr getUi() const; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGPARTCYLINDERIMP_H +#endif // PARTGUI_DLGPARTCYLINDERIMP_H diff --git a/src/Mod/Part/Gui/DlgPartImportIgesImp.cpp b/src/Mod/Part/Gui/DlgPartImportIgesImp.cpp index 1471a0274a..af7a350dec 100644 --- a/src/Mod/Part/Gui/DlgPartImportIgesImp.cpp +++ b/src/Mod/Part/Gui/DlgPartImportIgesImp.cpp @@ -58,21 +58,22 @@ DlgPartImportIgesImp::~DlgPartImportIgesImp() = default; */ void DlgPartImportIgesImp::OnApply() { - qWarning( "DlgPartImportIgesImp::OnApply() not yet implemented!" ); + qWarning("DlgPartImportIgesImp::OnApply() not yet implemented!"); } void DlgPartImportIgesImp::onChooseFileName() { - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QString(), QString(), - QStringLiteral("%1 (*.igs *.iges);;%2 (*.*)")) - .arg(tr("IGES"), - tr("All Files")); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + QStringLiteral("%1 (*.igs *.iges);;%2 (*.*)") + ) + .arg(tr("IGES"), tr("All Files")); if (!fn.isEmpty()) { ui->FileName->setText(fn); } } - - #include "moc_DlgPartImportIgesImp.cpp" diff --git a/src/Mod/Part/Gui/DlgPartImportIgesImp.h b/src/Mod/Part/Gui/DlgPartImportIgesImp.h index f06bc5c4fb..a0a9341209 100644 --- a/src/Mod/Part/Gui/DlgPartImportIgesImp.h +++ b/src/Mod/Part/Gui/DlgPartImportIgesImp.h @@ -28,24 +28,25 @@ #include #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgPartImportIges; -class DlgPartImportIgesImp : public QDialog +class DlgPartImportIgesImp: public QDialog { Q_OBJECT public: - explicit DlgPartImportIgesImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgPartImportIgesImp() override; + explicit DlgPartImportIgesImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgPartImportIgesImp() override; public Q_SLOTS: - virtual void OnApply(); - virtual void onChooseFileName(); + virtual void OnApply(); + virtual void onChooseFileName(); private: - std::unique_ptr ui; + std::unique_ptr ui; }; -} // namespace PartGui +} // namespace PartGui -#endif // DlgPartImportIgesImp_H +#endif // DlgPartImportIgesImp_H diff --git a/src/Mod/Part/Gui/DlgPartImportStepImp.cpp b/src/Mod/Part/Gui/DlgPartImportStepImp.cpp index a04a40e66e..5f9da9e285 100644 --- a/src/Mod/Part/Gui/DlgPartImportStepImp.cpp +++ b/src/Mod/Part/Gui/DlgPartImportStepImp.cpp @@ -41,8 +41,8 @@ using namespace PartGui; * The dialog will by default be modeless, unless you set 'modal' to * true to construct a modal dialog. */ -DlgPartImportStepImp::DlgPartImportStepImp( QWidget* parent, Qt::WindowFlags fl ) - : QDialog( parent, fl ) +DlgPartImportStepImp::DlgPartImportStepImp(QWidget* parent, Qt::WindowFlags fl) + : QDialog(parent, fl) , ui(new Ui_DlgPartImportStep) { ui->setupUi(this); @@ -58,15 +58,18 @@ DlgPartImportStepImp::~DlgPartImportStepImp() = default; */ void DlgPartImportStepImp::OnApply() { - qWarning( "DlgPartImportStepImp::OnApply() not yet implemented!" ); + qWarning("DlgPartImportStepImp::OnApply() not yet implemented!"); } void DlgPartImportStepImp::onChooseFileName() { - QString fn = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QString(), QString(), - QStringLiteral("%1 (*.stp *.step);;%2 (*.*)")) - .arg(QLatin1String("STEP"), - tr("All Files")); + QString fn = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QString(), + QString(), + QStringLiteral("%1 (*.stp *.step);;%2 (*.*)") + ) + .arg(QLatin1String("STEP"), tr("All Files")); if (!fn.isEmpty()) { ui->FileName->setText(fn); } diff --git a/src/Mod/Part/Gui/DlgPartImportStepImp.h b/src/Mod/Part/Gui/DlgPartImportStepImp.h index 0ea7c8785e..ed71cd6dc7 100644 --- a/src/Mod/Part/Gui/DlgPartImportStepImp.h +++ b/src/Mod/Part/Gui/DlgPartImportStepImp.h @@ -28,25 +28,26 @@ #include #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgPartImportStep; -class DlgPartImportStepImp : public QDialog +class DlgPartImportStepImp: public QDialog { Q_OBJECT public: - explicit DlgPartImportStepImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgPartImportStepImp() override; + explicit DlgPartImportStepImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgPartImportStepImp() override; public Q_SLOTS: - virtual void OnApply(); - virtual void onChooseFileName(); + virtual void OnApply(); + virtual void onChooseFileName(); private: - std::unique_ptr ui; + std::unique_ptr ui; }; -} // namespace PartGui +} // namespace PartGui -#endif // DlgPartImportStepImp_H +#endif // DlgPartImportStepImp_H diff --git a/src/Mod/Part/Gui/DlgPrimitives.cpp b/src/Mod/Part/Gui/DlgPrimitives.cpp index b9dabb8882..5cc05f85d5 100644 --- a/src/Mod/Part/Gui/DlgPrimitives.cpp +++ b/src/Mod/Part/Gui/DlgPrimitives.cpp @@ -61,59 +61,64 @@ using namespace PartGui; -namespace PartGui { +namespace PartGui +{ - QString getAutoGroupCommandStr(QString objectName) - // Helper function to get the python code to add the newly created object to the active Part object if present - { - App::Part* activePart = Gui::Application::Instance->activeView()->getActiveObject("part"); - if (activePart) { - QString activeObjectName = QString::fromLatin1(activePart->getNameInDocument()); - return QStringLiteral("App.ActiveDocument.getObject('%1\')." - "addObject(App.ActiveDocument.getObject('%2\'))\n") - .arg(activeObjectName, objectName); - } - return QStringLiteral("# Object %1 created at document root").arg(objectName); +QString getAutoGroupCommandStr(QString objectName) +// Helper function to get the python code to add the newly created object to the active Part object +// if present +{ + App::Part* activePart = Gui::Application::Instance->activeView()->getActiveObject( + "part" + ); + if (activePart) { + QString activeObjectName = QString::fromLatin1(activePart->getNameInDocument()); + return QStringLiteral( + "App.ActiveDocument.getObject('%1\')." + "addObject(App.ActiveDocument.getObject('%2\'))\n" + ) + .arg(activeObjectName, objectName); } + return QStringLiteral("# Object %1 created at document root").arg(objectName); +} const char* gce_ErrorStatusText(gce_ErrorType et) { - switch (et) - { - case gce_Done: - return "Construction was successful"; - case gce_ConfusedPoints: - return "Two points are coincident"; - case gce_NegativeRadius: - return "Radius value is negative"; - case gce_ColinearPoints: - return "Three points are collinear"; - case gce_IntersectionError: - return "Intersection cannot be computed"; - case gce_NullAxis: - return "Axis is undefined"; - case gce_NullAngle: - return "Angle value is invalid (usually null)"; - case gce_NullRadius: - return "Radius is null"; - case gce_InvertAxis: - return "Axis value is invalid"; - case gce_BadAngle: - return "Angle value is invalid"; - case gce_InvertRadius: - return "Radius value is incorrect (usually with respect to another radius)"; - case gce_NullFocusLength: - return "Focal distance is null"; - case gce_NullVector: - return "Vector is null"; - case gce_BadEquation: - return "Coefficients are incorrect (applies to the equation of a geometric object)"; - default: - return "Creation of geometry failed"; + switch (et) { + case gce_Done: + return "Construction was successful"; + case gce_ConfusedPoints: + return "Two points are coincident"; + case gce_NegativeRadius: + return "Radius value is negative"; + case gce_ColinearPoints: + return "Three points are collinear"; + case gce_IntersectionError: + return "Intersection cannot be computed"; + case gce_NullAxis: + return "Axis is undefined"; + case gce_NullAngle: + return "Angle value is invalid (usually null)"; + case gce_NullRadius: + return "Radius is null"; + case gce_InvertAxis: + return "Axis value is invalid"; + case gce_BadAngle: + return "Angle value is invalid"; + case gce_InvertRadius: + return "Radius value is incorrect (usually with respect to another radius)"; + case gce_NullFocusLength: + return "Focal distance is null"; + case gce_NullVector: + return "Vector is null"; + case gce_BadEquation: + return "Coefficients are incorrect (applies to the equation of a geometric object)"; + default: + return "Creation of geometry failed"; } } -static QString safeQuantityQString(Gui::QuantitySpinBox *qs) +static QString safeQuantityQString(Gui::QuantitySpinBox* qs) { return QString::fromStdString(qs->value().getSafeUserString()); } @@ -139,61 +144,63 @@ void Picker::createPrimitive(QWidget* widget, const QString& descr, Gui::Documen QString Picker::toPlacement(const gp_Ax2& axis) const { gp_Dir dir = axis.Direction(); - gp_Pnt pnt = gp_Pnt(0.0,0.0,0.0); + gp_Pnt pnt = gp_Pnt(0.0, 0.0, 0.0); gp_Ax3 ax3(pnt, dir, axis.XDirection()); gp_Trsf Trf; Trf.SetTransformation(ax3); Trf.Invert(); - gp_XYZ theAxis(0,0,1); + gp_XYZ theAxis(0, 0, 1); Standard_Real theAngle = 0.0; - Trf.GetRotation(theAxis,theAngle); + Trf.GetRotation(theAxis, theAngle); Base::Rotation rot(Base::convertTo(theAxis), theAngle); gp_Pnt loc = axis.Location(); return QStringLiteral("Base.Placement(Base.Vector(%1,%2,%3),Base.Rotation(%4,%5,%6,%7))") - .arg(loc.X(),0,'g',Base::UnitsApi::getDecimals()) - .arg(loc.Y(),0,'g',Base::UnitsApi::getDecimals()) - .arg(loc.Z(),0,'g',Base::UnitsApi::getDecimals()) - .arg(rot[0],0,'g',Base::UnitsApi::getDecimals()) - .arg(rot[1],0,'g',Base::UnitsApi::getDecimals()) - .arg(rot[2],0,'g',Base::UnitsApi::getDecimals()) - .arg(rot[3],0,'g',Base::UnitsApi::getDecimals()); + .arg(loc.X(), 0, 'g', Base::UnitsApi::getDecimals()) + .arg(loc.Y(), 0, 'g', Base::UnitsApi::getDecimals()) + .arg(loc.Z(), 0, 'g', Base::UnitsApi::getDecimals()) + .arg(rot[0], 0, 'g', Base::UnitsApi::getDecimals()) + .arg(rot[1], 0, 'g', Base::UnitsApi::getDecimals()) + .arg(rot[2], 0, 'g', Base::UnitsApi::getDecimals()) + .arg(rot[3], 0, 'g', Base::UnitsApi::getDecimals()); } -class CircleFromThreePoints : public Picker +class CircleFromThreePoints: public Picker { public: - CircleFromThreePoints() : Picker() - { - } - bool pickedPoint(const SoPickedPoint * point) override + CircleFromThreePoints() + : Picker() + {} + bool pickedPoint(const SoPickedPoint* point) override { SbVec3f pnt = point->getPoint(); - points.emplace_back(pnt[0],pnt[1],pnt[2]); + points.emplace_back(pnt[0], pnt[1], pnt[2]); return points.size() == 3; } QString command(App::Document* doc) const override { GC_MakeArcOfCircle arc(points[0], points[1], points[2]); - if (!arc.IsDone()) + if (!arc.IsDone()) { throw Base::CADKernelError(gce_ErrorStatusText(arc.Status())); + } Handle(Geom_TrimmedCurve) trim = arc.Value(); Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(trim->BasisCurve()); QString name = QString::fromLatin1(doc->getUniqueObjectName("Circle").c_str()); return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Circle\",\"%1\")\n" - "App.ActiveDocument.%1.Radius=%2\n" - "App.ActiveDocument.%1.Angle1=%3\n" - "App.ActiveDocument.%1.Angle2=%4\n" - "App.ActiveDocument.%1.Placement=%5\n") + "App.ActiveDocument.addObject(\"Part::Circle\",\"%1\")\n" + "App.ActiveDocument.%1.Radius=%2\n" + "App.ActiveDocument.%1.Angle1=%3\n" + "App.ActiveDocument.%1.Angle2=%4\n" + "App.ActiveDocument.%1.Placement=%5\n" + ) .arg(name) - .arg(circle->Radius(),0,'g',Base::UnitsApi::getDecimals()) - .arg(Base::toDegrees(trim->FirstParameter()),0,'g',Base::UnitsApi::getDecimals()) - .arg(Base::toDegrees(trim->LastParameter ()),0,'g',Base::UnitsApi::getDecimals()) + .arg(circle->Radius(), 0, 'g', Base::UnitsApi::getDecimals()) + .arg(Base::toDegrees(trim->FirstParameter()), 0, 'g', Base::UnitsApi::getDecimals()) + .arg(Base::toDegrees(trim->LastParameter()), 0, 'g', Base::UnitsApi::getDecimals()) .arg(toPlacement(circle->Position())); } @@ -201,14 +208,13 @@ private: std::vector points; }; -} +} // namespace PartGui // ---------------------------------------------------------------------------- AbstractPrimitive::AbstractPrimitive(Part::Primitive* feature) : featurePtr(feature) -{ -} +{} bool AbstractPrimitive::hasValidPrimitive() const { @@ -217,23 +223,28 @@ bool AbstractPrimitive::hasValidPrimitive() const void AbstractPrimitive::connectSignalMapper(QSignalMapper* mapper) { - connect(mapper, &QSignalMapper::mappedObject, this, &AbstractPrimitive::changeValue); + connect(mapper, &QSignalMapper::mappedObject, this, &AbstractPrimitive::changeValue); } -namespace PartGui { +namespace PartGui +{ -void mapSignalMapper(QObject *sender, QSignalMapper* mapper) +void mapSignalMapper(QObject* sender, QSignalMapper* mapper) { mapper->setMapping(sender, sender); } -template -void connectMapSignalMapper(typename QtPrivate::FunctionPointer::Object *sender, Function func, QSignalMapper* mapper) +template +void connectMapSignalMapper( + typename QtPrivate::FunctionPointer::Object* sender, + Function func, + QSignalMapper* mapper +) { QObject::connect(sender, func, mapper, qOverload<>(&QSignalMapper::map)); mapSignalMapper(sender, mapper); } -} +} // namespace PartGui // ---------------------------------------------------------------------------- @@ -252,8 +263,16 @@ PlanePrimitive::PlanePrimitive(std::shared_ptr ui, Part::Plane QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->planeLength, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->planeWidth, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->planeLength, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->planeWidth, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -265,34 +284,41 @@ const char* PlanePrimitive::getDefaultName() const QString PlanePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Plane\",\"%1\")\n" - "App.ActiveDocument.%1.Length='%2'\n" - "App.ActiveDocument.%1.Width='%3'\n" - "App.ActiveDocument.%1.Placement=%4\n" - "App.ActiveDocument.%1.Label='%5'\n") - .arg(objectName, - safeQuantityQString(ui->planeLength), - safeQuantityQString(ui->planeWidth), - placement, - DlgPrimitives::tr("Plane")); + "App.ActiveDocument.addObject(\"Part::Plane\",\"%1\")\n" + "App.ActiveDocument.%1.Length='%2'\n" + "App.ActiveDocument.%1.Width='%3'\n" + "App.ActiveDocument.%1.Placement=%4\n" + "App.ActiveDocument.%1.Label='%5'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->planeLength), + safeQuantityQString(ui->planeWidth), + placement, + DlgPrimitives::tr("Plane") + ); } QString PlanePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Length='%2'\n" - "%1.Width='%3'\n" - "%1.Placement=%4\n") - .arg(objectName, - safeQuantityQString(ui->planeLength), - safeQuantityQString(ui->planeWidth), - placement); + "%1.Length='%2'\n" + "%1.Width='%3'\n" + "%1.Placement=%4\n" + ) + .arg( + objectName, + safeQuantityQString(ui->planeLength), + safeQuantityQString(ui->planeWidth), + placement + ); } void PlanePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Plane* plane = featurePtr.get(); if (widget == ui->planeLength) { plane->Length.setValue(ui->planeLength->value().getValue()); @@ -324,9 +350,21 @@ BoxPrimitive::BoxPrimitive(std::shared_ptr ui, Part::Box* feat QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->boxLength, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->boxWidth, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->boxHeight, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->boxLength, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->boxWidth, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->boxHeight, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -338,38 +376,45 @@ const char* BoxPrimitive::getDefaultName() const QString BoxPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Box\",\"%1\")\n" - "App.ActiveDocument.%1.Length='%2'\n" - "App.ActiveDocument.%1.Width='%3'\n" - "App.ActiveDocument.%1.Height='%4'\n" - "App.ActiveDocument.%1.Placement=%5\n" - "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName, - safeQuantityQString(ui->boxLength), - safeQuantityQString(ui->boxWidth), - safeQuantityQString(ui->boxHeight), - placement, - DlgPrimitives::tr("Box")); + "App.ActiveDocument.addObject(\"Part::Box\",\"%1\")\n" + "App.ActiveDocument.%1.Length='%2'\n" + "App.ActiveDocument.%1.Width='%3'\n" + "App.ActiveDocument.%1.Height='%4'\n" + "App.ActiveDocument.%1.Placement=%5\n" + "App.ActiveDocument.%1.Label='%6'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->boxLength), + safeQuantityQString(ui->boxWidth), + safeQuantityQString(ui->boxHeight), + placement, + DlgPrimitives::tr("Box") + ); } QString BoxPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Length='%2'\n" - "%1.Width='%3'\n" - "%1.Height='%4'\n" - "%1.Placement=%5\n") - .arg(objectName, - safeQuantityQString(ui->boxLength), - safeQuantityQString(ui->boxWidth), - safeQuantityQString(ui->boxHeight), - placement); + "%1.Length='%2'\n" + "%1.Width='%3'\n" + "%1.Height='%4'\n" + "%1.Placement=%5\n" + ) + .arg( + objectName, + safeQuantityQString(ui->boxLength), + safeQuantityQString(ui->boxWidth), + safeQuantityQString(ui->boxHeight), + placement + ); } void BoxPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Box* box = featurePtr.get(); if (widget == ui->boxLength) { box->Length.setValue(ui->boxLength->value().getValue()); @@ -408,11 +453,31 @@ CylinderPrimitive::CylinderPrimitive(std::shared_ptr ui, Part: QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->cylinderRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->cylinderHeight, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->cylinderXSkew, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->cylinderYSkew, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->cylinderAngle, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->cylinderRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->cylinderHeight, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->cylinderXSkew, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->cylinderYSkew, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->cylinderAngle, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -424,46 +489,53 @@ const char* CylinderPrimitive::getDefaultName() const QString CylinderPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Cylinder\",\"%1\")\n" - "App.ActiveDocument.%1.Radius='%2'\n" - "App.ActiveDocument.%1.Height='%3'\n" - "App.ActiveDocument.%1.Angle='%4'\n" - "App.ActiveDocument.%1.FirstAngle='%5'\n" - "App.ActiveDocument.%1.SecondAngle='%6'\n" - "App.ActiveDocument.%1.Placement=%7\n" - "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName, - safeQuantityQString(ui->cylinderRadius), - safeQuantityQString(ui->cylinderHeight), - safeQuantityQString(ui->cylinderAngle), - safeQuantityQString(ui->cylinderXSkew), - safeQuantityQString(ui->cylinderYSkew), - placement, - DlgPrimitives::tr("Cylinder")); + "App.ActiveDocument.addObject(\"Part::Cylinder\",\"%1\")\n" + "App.ActiveDocument.%1.Radius='%2'\n" + "App.ActiveDocument.%1.Height='%3'\n" + "App.ActiveDocument.%1.Angle='%4'\n" + "App.ActiveDocument.%1.FirstAngle='%5'\n" + "App.ActiveDocument.%1.SecondAngle='%6'\n" + "App.ActiveDocument.%1.Placement=%7\n" + "App.ActiveDocument.%1.Label='%8'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->cylinderRadius), + safeQuantityQString(ui->cylinderHeight), + safeQuantityQString(ui->cylinderAngle), + safeQuantityQString(ui->cylinderXSkew), + safeQuantityQString(ui->cylinderYSkew), + placement, + DlgPrimitives::tr("Cylinder") + ); } QString CylinderPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Radius='%2'\n" - "%1.Height='%3'\n" - "%1.Angle='%4'\n" - "%1.FirstAngle='%5'\n" - "%1.SecondAngle='%6'\n" - "%1.Placement=%7\n") - .arg(objectName, - safeQuantityQString(ui->cylinderRadius), - safeQuantityQString(ui->cylinderHeight), - safeQuantityQString(ui->cylinderAngle), - safeQuantityQString(ui->cylinderXSkew), - safeQuantityQString(ui->cylinderYSkew), - placement); + "%1.Radius='%2'\n" + "%1.Height='%3'\n" + "%1.Angle='%4'\n" + "%1.FirstAngle='%5'\n" + "%1.SecondAngle='%6'\n" + "%1.Placement=%7\n" + ) + .arg( + objectName, + safeQuantityQString(ui->cylinderRadius), + safeQuantityQString(ui->cylinderHeight), + safeQuantityQString(ui->cylinderAngle), + safeQuantityQString(ui->cylinderXSkew), + safeQuantityQString(ui->cylinderYSkew), + placement + ); } void CylinderPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Cylinder* cyl = featurePtr.get(); if (widget == ui->cylinderRadius) { cyl->Radius.setValue(ui->cylinderRadius->value().getValue()); @@ -507,10 +579,26 @@ ConePrimitive::ConePrimitive(std::shared_ptr ui, Part::Cone* f QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->coneRadius1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->coneRadius2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->coneHeight, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->coneAngle, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->coneRadius1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->coneRadius2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->coneHeight, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->coneAngle, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -522,42 +610,49 @@ const char* ConePrimitive::getDefaultName() const QString ConePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Cone\",\"%1\")\n" - "App.ActiveDocument.%1.Radius1='%2'\n" - "App.ActiveDocument.%1.Radius2='%3'\n" - "App.ActiveDocument.%1.Height='%4'\n" - "App.ActiveDocument.%1.Angle='%5'\n" - "App.ActiveDocument.%1.Placement=%6\n" - "App.ActiveDocument.%1.Label='%7'\n") - .arg(objectName, - safeQuantityQString(ui->coneRadius1), - safeQuantityQString(ui->coneRadius2), - safeQuantityQString(ui->coneHeight), - safeQuantityQString(ui->coneAngle), - placement, - DlgPrimitives::tr("Cone")); + "App.ActiveDocument.addObject(\"Part::Cone\",\"%1\")\n" + "App.ActiveDocument.%1.Radius1='%2'\n" + "App.ActiveDocument.%1.Radius2='%3'\n" + "App.ActiveDocument.%1.Height='%4'\n" + "App.ActiveDocument.%1.Angle='%5'\n" + "App.ActiveDocument.%1.Placement=%6\n" + "App.ActiveDocument.%1.Label='%7'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->coneRadius1), + safeQuantityQString(ui->coneRadius2), + safeQuantityQString(ui->coneHeight), + safeQuantityQString(ui->coneAngle), + placement, + DlgPrimitives::tr("Cone") + ); } QString ConePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Radius1='%2'\n" - "%1.Radius2='%3'\n" - "%1.Height='%4'\n" - "%1.Angle='%5'\n" - "%1.Placement=%6\n") - .arg(objectName, - safeQuantityQString(ui->coneRadius1), - safeQuantityQString(ui->coneRadius2), - safeQuantityQString(ui->coneHeight), - safeQuantityQString(ui->coneAngle), - placement); + "%1.Radius1='%2'\n" + "%1.Radius2='%3'\n" + "%1.Height='%4'\n" + "%1.Angle='%5'\n" + "%1.Placement=%6\n" + ) + .arg( + objectName, + safeQuantityQString(ui->coneRadius1), + safeQuantityQString(ui->coneRadius2), + safeQuantityQString(ui->coneHeight), + safeQuantityQString(ui->coneAngle), + placement + ); } void ConePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Cone* cone = featurePtr.get(); if (widget == ui->coneRadius1) { cone->Radius1.setValue(ui->coneRadius1->value().getValue()); @@ -598,10 +693,26 @@ SpherePrimitive::SpherePrimitive(std::shared_ptr ui, Part::Sph QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->sphereRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->sphereAngle1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->sphereAngle2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->sphereAngle3, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->sphereRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->sphereAngle1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->sphereAngle2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->sphereAngle3, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -613,42 +724,49 @@ const char* SpherePrimitive::getDefaultName() const QString SpherePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Sphere\",\"%1\")\n" - "App.ActiveDocument.%1.Radius='%2'\n" - "App.ActiveDocument.%1.Angle1='%3'\n" - "App.ActiveDocument.%1.Angle2='%4'\n" - "App.ActiveDocument.%1.Angle3='%5'\n" - "App.ActiveDocument.%1.Placement=%6\n" - "App.ActiveDocument.%1.Label='%7'\n") - .arg(objectName, - safeQuantityQString(ui->sphereRadius), - safeQuantityQString(ui->sphereAngle1), - safeQuantityQString(ui->sphereAngle2), - safeQuantityQString(ui->sphereAngle3), - placement, - DlgPrimitives::tr("Sphere")); + "App.ActiveDocument.addObject(\"Part::Sphere\",\"%1\")\n" + "App.ActiveDocument.%1.Radius='%2'\n" + "App.ActiveDocument.%1.Angle1='%3'\n" + "App.ActiveDocument.%1.Angle2='%4'\n" + "App.ActiveDocument.%1.Angle3='%5'\n" + "App.ActiveDocument.%1.Placement=%6\n" + "App.ActiveDocument.%1.Label='%7'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->sphereRadius), + safeQuantityQString(ui->sphereAngle1), + safeQuantityQString(ui->sphereAngle2), + safeQuantityQString(ui->sphereAngle3), + placement, + DlgPrimitives::tr("Sphere") + ); } QString SpherePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Radius='%2'\n" - "%1.Angle1='%3'\n" - "%1.Angle2='%4'\n" - "%1.Angle3='%5'\n" - "%1.Placement=%6\n") - .arg(objectName, - safeQuantityQString(ui->sphereRadius), - safeQuantityQString(ui->sphereAngle1), - safeQuantityQString(ui->sphereAngle2), - safeQuantityQString(ui->sphereAngle3), - placement); + "%1.Radius='%2'\n" + "%1.Angle1='%3'\n" + "%1.Angle2='%4'\n" + "%1.Angle3='%5'\n" + "%1.Placement=%6\n" + ) + .arg( + objectName, + safeQuantityQString(ui->sphereRadius), + safeQuantityQString(ui->sphereAngle1), + safeQuantityQString(ui->sphereAngle2), + safeQuantityQString(ui->sphereAngle3), + placement + ); } void SpherePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Sphere* sphere = featurePtr.get(); if (widget == ui->sphereRadius) { sphere->Radius.setValue(ui->sphereRadius->value().getValue()); @@ -695,13 +813,36 @@ EllipsoidPrimitive::EllipsoidPrimitive(std::shared_ptr ui, Par QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->ellipsoidRadius1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipsoidRadius2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipsoidRadius3, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipsoidAngle1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipsoidAngle2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipsoidAngle3, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - + connectMapSignalMapper( + ui->ellipsoidRadius1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipsoidRadius2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipsoidRadius3, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipsoidAngle1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipsoidAngle2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipsoidAngle3, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -713,50 +854,57 @@ const char* EllipsoidPrimitive::getDefaultName() const QString EllipsoidPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Ellipsoid\",\"%1\")\n" - "App.ActiveDocument.%1.Radius1='%2'\n" - "App.ActiveDocument.%1.Radius2='%3'\n" - "App.ActiveDocument.%1.Radius3='%4'\n" - "App.ActiveDocument.%1.Angle1='%5'\n" - "App.ActiveDocument.%1.Angle2='%6'\n" - "App.ActiveDocument.%1.Angle3='%7'\n" - "App.ActiveDocument.%1.Placement=%8\n" - "App.ActiveDocument.%1.Label='%9'\n") - .arg(objectName, - safeQuantityQString(ui->ellipsoidRadius1), - safeQuantityQString(ui->ellipsoidRadius2), - safeQuantityQString(ui->ellipsoidRadius3), - safeQuantityQString(ui->ellipsoidAngle1), - safeQuantityQString(ui->ellipsoidAngle2), - safeQuantityQString(ui->ellipsoidAngle3), - placement, - DlgPrimitives::tr("Ellipsoid")); + "App.ActiveDocument.addObject(\"Part::Ellipsoid\",\"%1\")\n" + "App.ActiveDocument.%1.Radius1='%2'\n" + "App.ActiveDocument.%1.Radius2='%3'\n" + "App.ActiveDocument.%1.Radius3='%4'\n" + "App.ActiveDocument.%1.Angle1='%5'\n" + "App.ActiveDocument.%1.Angle2='%6'\n" + "App.ActiveDocument.%1.Angle3='%7'\n" + "App.ActiveDocument.%1.Placement=%8\n" + "App.ActiveDocument.%1.Label='%9'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->ellipsoidRadius1), + safeQuantityQString(ui->ellipsoidRadius2), + safeQuantityQString(ui->ellipsoidRadius3), + safeQuantityQString(ui->ellipsoidAngle1), + safeQuantityQString(ui->ellipsoidAngle2), + safeQuantityQString(ui->ellipsoidAngle3), + placement, + DlgPrimitives::tr("Ellipsoid") + ); } QString EllipsoidPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Radius1='%2'\n" - "%1.Radius2='%3'\n" - "%1.Radius3='%4'\n" - "%1.Angle1='%5'\n" - "%1.Angle2='%6'\n" - "%1.Angle3='%7'\n" - "%1.Placement=%8\n") - .arg(objectName, - safeQuantityQString(ui->ellipsoidRadius1), - safeQuantityQString(ui->ellipsoidRadius2), - safeQuantityQString(ui->ellipsoidRadius3), - safeQuantityQString(ui->ellipsoidAngle1), - safeQuantityQString(ui->ellipsoidAngle2), - safeQuantityQString(ui->ellipsoidAngle3), - placement); + "%1.Radius1='%2'\n" + "%1.Radius2='%3'\n" + "%1.Radius3='%4'\n" + "%1.Angle1='%5'\n" + "%1.Angle2='%6'\n" + "%1.Angle3='%7'\n" + "%1.Placement=%8\n" + ) + .arg( + objectName, + safeQuantityQString(ui->ellipsoidRadius1), + safeQuantityQString(ui->ellipsoidRadius2), + safeQuantityQString(ui->ellipsoidRadius3), + safeQuantityQString(ui->ellipsoidAngle1), + safeQuantityQString(ui->ellipsoidAngle2), + safeQuantityQString(ui->ellipsoidAngle3), + placement + ); } void EllipsoidPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Ellipsoid* ell = featurePtr.get(); if (widget == ui->ellipsoidRadius1) { ell->Radius1.setValue(ui->ellipsoidRadius1->value().getValue()); @@ -806,11 +954,31 @@ TorusPrimitive::TorusPrimitive(std::shared_ptr ui, Part::Torus QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->torusRadius1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->torusRadius2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->torusAngle1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->torusAngle2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->torusAngle3, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->torusRadius1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->torusRadius2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->torusAngle1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->torusAngle2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->torusAngle3, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -822,46 +990,53 @@ const char* TorusPrimitive::getDefaultName() const QString TorusPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Torus\",\"%1\")\n" - "App.ActiveDocument.%1.Radius1='%2'\n" - "App.ActiveDocument.%1.Radius2='%3'\n" - "App.ActiveDocument.%1.Angle1='%4'\n" - "App.ActiveDocument.%1.Angle2='%5'\n" - "App.ActiveDocument.%1.Angle3='%6'\n" - "App.ActiveDocument.%1.Placement=%7\n" - "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName, - safeQuantityQString(ui->torusRadius1), - safeQuantityQString(ui->torusRadius2), - safeQuantityQString(ui->torusAngle1), - safeQuantityQString(ui->torusAngle2), - safeQuantityQString(ui->torusAngle3), - placement, - DlgPrimitives::tr("Torus")); + "App.ActiveDocument.addObject(\"Part::Torus\",\"%1\")\n" + "App.ActiveDocument.%1.Radius1='%2'\n" + "App.ActiveDocument.%1.Radius2='%3'\n" + "App.ActiveDocument.%1.Angle1='%4'\n" + "App.ActiveDocument.%1.Angle2='%5'\n" + "App.ActiveDocument.%1.Angle3='%6'\n" + "App.ActiveDocument.%1.Placement=%7\n" + "App.ActiveDocument.%1.Label='%8'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->torusRadius1), + safeQuantityQString(ui->torusRadius2), + safeQuantityQString(ui->torusAngle1), + safeQuantityQString(ui->torusAngle2), + safeQuantityQString(ui->torusAngle3), + placement, + DlgPrimitives::tr("Torus") + ); } QString TorusPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Radius1='%2'\n" - "%1.Radius2='%3'\n" - "%1.Angle1='%4'\n" - "%1.Angle2='%5'\n" - "%1.Angle3='%6'\n" - "%1.Placement=%7\n") - .arg(objectName, - safeQuantityQString(ui->torusRadius1), - safeQuantityQString(ui->torusRadius2), - safeQuantityQString(ui->torusAngle1), - safeQuantityQString(ui->torusAngle2), - safeQuantityQString(ui->torusAngle3), - placement); + "%1.Radius1='%2'\n" + "%1.Radius2='%3'\n" + "%1.Angle1='%4'\n" + "%1.Angle2='%5'\n" + "%1.Angle3='%6'\n" + "%1.Placement=%7\n" + ) + .arg( + objectName, + safeQuantityQString(ui->torusRadius1), + safeQuantityQString(ui->torusRadius2), + safeQuantityQString(ui->torusAngle1), + safeQuantityQString(ui->torusAngle2), + safeQuantityQString(ui->torusAngle3), + placement + ); } void TorusPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Torus* torus = featurePtr.get(); if (widget == ui->torusRadius1) { torus->Radius1.setValue(ui->torusRadius1->value().getValue()); @@ -905,10 +1080,26 @@ PrismPrimitive::PrismPrimitive(std::shared_ptr ui, Part::Prism QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); connectMapSignalMapper(ui->prismPolygon, qOverload(&QSpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->prismCircumradius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->prismHeight, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->prismXSkew, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->prismYSkew, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->prismCircumradius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->prismHeight, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->prismXSkew, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->prismYSkew, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -920,46 +1111,53 @@ const char* PrismPrimitive::getDefaultName() const QString PrismPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Prism\",\"%1\")\n" - "App.ActiveDocument.%1.Polygon=%2\n" - "App.ActiveDocument.%1.Circumradius='%3'\n" - "App.ActiveDocument.%1.Height='%4'\n" - "App.ActiveDocument.%1.FirstAngle='%5'\n" - "App.ActiveDocument.%1.SecondAngle='%6'\n" - "App.ActiveDocument.%1.Placement=%7\n" - "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName, - QString::number(ui->prismPolygon->value()), - safeQuantityQString(ui->prismCircumradius), - safeQuantityQString(ui->prismHeight), - safeQuantityQString(ui->prismXSkew), - safeQuantityQString(ui->prismYSkew), - placement, - DlgPrimitives::tr("Prism")); + "App.ActiveDocument.addObject(\"Part::Prism\",\"%1\")\n" + "App.ActiveDocument.%1.Polygon=%2\n" + "App.ActiveDocument.%1.Circumradius='%3'\n" + "App.ActiveDocument.%1.Height='%4'\n" + "App.ActiveDocument.%1.FirstAngle='%5'\n" + "App.ActiveDocument.%1.SecondAngle='%6'\n" + "App.ActiveDocument.%1.Placement=%7\n" + "App.ActiveDocument.%1.Label='%8'\n" + ) + .arg( + objectName, + QString::number(ui->prismPolygon->value()), + safeQuantityQString(ui->prismCircumradius), + safeQuantityQString(ui->prismHeight), + safeQuantityQString(ui->prismXSkew), + safeQuantityQString(ui->prismYSkew), + placement, + DlgPrimitives::tr("Prism") + ); } QString PrismPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Polygon=%2\n" - "%1.Circumradius='%3'\n" - "%1.Height='%4'\n" - "%1.FirstAngle='%5'\n" - "%1.SecondAngle='%6'\n" - "%1.Placement=%7\n") - .arg(objectName, - QString::number(ui->prismPolygon->value()), - safeQuantityQString(ui->prismCircumradius), - safeQuantityQString(ui->prismHeight), - safeQuantityQString(ui->prismXSkew), - safeQuantityQString(ui->prismYSkew), - placement); + "%1.Polygon=%2\n" + "%1.Circumradius='%3'\n" + "%1.Height='%4'\n" + "%1.FirstAngle='%5'\n" + "%1.SecondAngle='%6'\n" + "%1.Placement=%7\n" + ) + .arg( + objectName, + QString::number(ui->prismPolygon->value()), + safeQuantityQString(ui->prismCircumradius), + safeQuantityQString(ui->prismHeight), + safeQuantityQString(ui->prismXSkew), + safeQuantityQString(ui->prismYSkew), + placement + ); } void PrismPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Prism* prism = featurePtr.get(); if (widget == ui->prismPolygon) { prism->Polygon.setValue(ui->prismPolygon->value()); @@ -1033,16 +1231,56 @@ WedgePrimitive::WedgePrimitive(std::shared_ptr ui, Part::Wedge QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->wedgeXmin, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeYmin, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeZmin, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeX2min, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeZ2min, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeXmax, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeYmax, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeZmax, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeX2max, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->wedgeZ2max, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->wedgeXmin, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeYmin, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeZmin, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeX2min, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeZ2min, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeXmax, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeYmax, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeZmax, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeX2max, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->wedgeZ2max, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -1054,66 +1292,73 @@ const char* WedgePrimitive::getDefaultName() const QString WedgePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Wedge\",\"%1\")\n" - "App.ActiveDocument.%1.Xmin='%2'\n" - "App.ActiveDocument.%1.Ymin='%3'\n" - "App.ActiveDocument.%1.Zmin='%4'\n" - "App.ActiveDocument.%1.X2min='%5'\n" - "App.ActiveDocument.%1.Z2min='%6'\n" - "App.ActiveDocument.%1.Xmax='%7'\n" - "App.ActiveDocument.%1.Ymax='%8'\n" - "App.ActiveDocument.%1.Zmax='%9'\n" - "App.ActiveDocument.%1.X2max='%10'\n" - "App.ActiveDocument.%1.Z2max='%11'\n" - "App.ActiveDocument.%1.Placement=%12\n" - "App.ActiveDocument.%1.Label='%13'\n") - .arg(objectName, - safeQuantityQString(ui->wedgeXmin), - safeQuantityQString(ui->wedgeYmin), - safeQuantityQString(ui->wedgeZmin), - safeQuantityQString(ui->wedgeX2min), - safeQuantityQString(ui->wedgeZ2min), - safeQuantityQString(ui->wedgeXmax), - safeQuantityQString(ui->wedgeYmax)) - .arg(safeQuantityQString(ui->wedgeZmax), - safeQuantityQString(ui->wedgeX2max), - safeQuantityQString(ui->wedgeZ2max), - placement, - DlgPrimitives::tr("Wedge")); + "App.ActiveDocument.addObject(\"Part::Wedge\",\"%1\")\n" + "App.ActiveDocument.%1.Xmin='%2'\n" + "App.ActiveDocument.%1.Ymin='%3'\n" + "App.ActiveDocument.%1.Zmin='%4'\n" + "App.ActiveDocument.%1.X2min='%5'\n" + "App.ActiveDocument.%1.Z2min='%6'\n" + "App.ActiveDocument.%1.Xmax='%7'\n" + "App.ActiveDocument.%1.Ymax='%8'\n" + "App.ActiveDocument.%1.Zmax='%9'\n" + "App.ActiveDocument.%1.X2max='%10'\n" + "App.ActiveDocument.%1.Z2max='%11'\n" + "App.ActiveDocument.%1.Placement=%12\n" + "App.ActiveDocument.%1.Label='%13'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->wedgeXmin), + safeQuantityQString(ui->wedgeYmin), + safeQuantityQString(ui->wedgeZmin), + safeQuantityQString(ui->wedgeX2min), + safeQuantityQString(ui->wedgeZ2min), + safeQuantityQString(ui->wedgeXmax), + safeQuantityQString(ui->wedgeYmax) + ) + .arg( + safeQuantityQString(ui->wedgeZmax), + safeQuantityQString(ui->wedgeX2max), + safeQuantityQString(ui->wedgeZ2max), + placement, + DlgPrimitives::tr("Wedge") + ); } QString WedgePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Xmin='%2'\n" - "%1.Ymin='%3'\n" - "%1.Zmin='%4'\n" - "%1.X2min='%5'\n" - "%1.Z2min='%6'\n" - "%1.Xmax='%7'\n" - "%1.Ymax='%8'\n" - "%1.Zmax='%9'\n" - "%1.X2max='%10'\n" - "%1.Z2max='%11'\n" - "%1.Placement=%12\n") - .arg(objectName, - safeQuantityQString(ui->wedgeXmin), - safeQuantityQString(ui->wedgeYmin), - safeQuantityQString(ui->wedgeZmin), - safeQuantityQString(ui->wedgeX2min), - safeQuantityQString(ui->wedgeZ2min), - safeQuantityQString(ui->wedgeXmax), - safeQuantityQString(ui->wedgeYmax), - safeQuantityQString(ui->wedgeZmax)) - .arg(safeQuantityQString(ui->wedgeX2max), - safeQuantityQString(ui->wedgeZ2max), - placement); + "%1.Xmin='%2'\n" + "%1.Ymin='%3'\n" + "%1.Zmin='%4'\n" + "%1.X2min='%5'\n" + "%1.Z2min='%6'\n" + "%1.Xmax='%7'\n" + "%1.Ymax='%8'\n" + "%1.Zmax='%9'\n" + "%1.X2max='%10'\n" + "%1.Z2max='%11'\n" + "%1.Placement=%12\n" + ) + .arg( + objectName, + safeQuantityQString(ui->wedgeXmin), + safeQuantityQString(ui->wedgeYmin), + safeQuantityQString(ui->wedgeZmin), + safeQuantityQString(ui->wedgeX2min), + safeQuantityQString(ui->wedgeZ2min), + safeQuantityQString(ui->wedgeXmax), + safeQuantityQString(ui->wedgeYmax), + safeQuantityQString(ui->wedgeZmax) + ) + .arg(safeQuantityQString(ui->wedgeX2max), safeQuantityQString(ui->wedgeZ2max), placement); } void WedgePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Wedge* wedge = featurePtr.get(); if (widget == ui->wedgeXmin) { wedge->Xmin.setValue(ui->wedgeXmin->value().getValue()); @@ -1173,10 +1418,26 @@ HelixPrimitive::HelixPrimitive(std::shared_ptr ui, Part::Helix QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->helixPitch, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->helixHeight, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->helixRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->helixAngle, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->helixPitch, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->helixHeight, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->helixRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->helixAngle, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); connectMapSignalMapper(ui->helixLocalCS, qOverload(&QComboBox::currentIndexChanged), mapper); } } @@ -1189,47 +1450,54 @@ const char* HelixPrimitive::getDefaultName() const QString HelixPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Helix\",\"%1\")\n" - "App.ActiveDocument.%1.Pitch='%2'\n" - "App.ActiveDocument.%1.Height='%3'\n" - "App.ActiveDocument.%1.Radius='%4'\n" - "App.ActiveDocument.%1.Angle='%5'\n" - "App.ActiveDocument.%1.LocalCoord=%6\n" - "App.ActiveDocument.%1.Style=1\n" - "App.ActiveDocument.%1.Placement=%7\n" - "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName, - safeQuantityQString(ui->helixPitch), - safeQuantityQString(ui->helixHeight), - safeQuantityQString(ui->helixRadius), - safeQuantityQString(ui->helixAngle), - QString::number(ui->helixLocalCS->currentIndex()), - placement, - DlgPrimitives::tr("Helix")); + "App.ActiveDocument.addObject(\"Part::Helix\",\"%1\")\n" + "App.ActiveDocument.%1.Pitch='%2'\n" + "App.ActiveDocument.%1.Height='%3'\n" + "App.ActiveDocument.%1.Radius='%4'\n" + "App.ActiveDocument.%1.Angle='%5'\n" + "App.ActiveDocument.%1.LocalCoord=%6\n" + "App.ActiveDocument.%1.Style=1\n" + "App.ActiveDocument.%1.Placement=%7\n" + "App.ActiveDocument.%1.Label='%8'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->helixPitch), + safeQuantityQString(ui->helixHeight), + safeQuantityQString(ui->helixRadius), + safeQuantityQString(ui->helixAngle), + QString::number(ui->helixLocalCS->currentIndex()), + placement, + DlgPrimitives::tr("Helix") + ); } QString HelixPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Pitch='%2'\n" - "%1.Height='%3'\n" - "%1.Radius='%4'\n" - "%1.Angle='%5'\n" - "%1.LocalCoord=%6\n" - "%1.Placement=%7\n") - .arg(objectName, - safeQuantityQString(ui->helixPitch), - safeQuantityQString(ui->helixHeight), - safeQuantityQString(ui->helixRadius), - safeQuantityQString(ui->helixAngle), - QString::number(ui->helixLocalCS->currentIndex()), - placement); + "%1.Pitch='%2'\n" + "%1.Height='%3'\n" + "%1.Radius='%4'\n" + "%1.Angle='%5'\n" + "%1.LocalCoord=%6\n" + "%1.Placement=%7\n" + ) + .arg( + objectName, + safeQuantityQString(ui->helixPitch), + safeQuantityQString(ui->helixHeight), + safeQuantityQString(ui->helixRadius), + safeQuantityQString(ui->helixAngle), + QString::number(ui->helixLocalCS->currentIndex()), + placement + ); } void HelixPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Helix* helix = featurePtr.get(); if (widget == ui->helixPitch) { helix->Pitch.setValue(ui->helixPitch->value().getValue()); @@ -1269,9 +1537,21 @@ SpiralPrimitive::SpiralPrimitive(std::shared_ptr ui, Part::Spi QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->spiralGrowth, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->spiralRotation, qOverload(&QDoubleSpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->spiralRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->spiralGrowth, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->spiralRotation, + qOverload(&QDoubleSpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->spiralRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -1283,38 +1563,45 @@ const char* SpiralPrimitive::getDefaultName() const QString SpiralPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Spiral\",\"%1\")\n" - "App.ActiveDocument.%1.Growth='%2'\n" - "App.ActiveDocument.%1.Rotations=%3\n" - "App.ActiveDocument.%1.Radius='%4'\n" - "App.ActiveDocument.%1.Placement=%5\n" - "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName, - safeQuantityQString(ui->spiralGrowth), - QString::number(ui->spiralRotation->value()), - safeQuantityQString(ui->spiralRadius), - placement, - DlgPrimitives::tr("Spiral")); + "App.ActiveDocument.addObject(\"Part::Spiral\",\"%1\")\n" + "App.ActiveDocument.%1.Growth='%2'\n" + "App.ActiveDocument.%1.Rotations=%3\n" + "App.ActiveDocument.%1.Radius='%4'\n" + "App.ActiveDocument.%1.Placement=%5\n" + "App.ActiveDocument.%1.Label='%6'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->spiralGrowth), + QString::number(ui->spiralRotation->value()), + safeQuantityQString(ui->spiralRadius), + placement, + DlgPrimitives::tr("Spiral") + ); } QString SpiralPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Growth='%2'\n" - "%1.Rotations=%3\n" - "%1.Radius='%4'\n" - "%1.Placement=%5\n") - .arg(objectName, - safeQuantityQString(ui->spiralGrowth), - QString::number(ui->spiralRotation->value()), - safeQuantityQString(ui->spiralRadius), - placement); + "%1.Growth='%2'\n" + "%1.Rotations=%3\n" + "%1.Radius='%4'\n" + "%1.Placement=%5\n" + ) + .arg( + objectName, + safeQuantityQString(ui->spiralGrowth), + QString::number(ui->spiralRotation->value()), + safeQuantityQString(ui->spiralRadius), + placement + ); } void SpiralPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Spiral* spiral = featurePtr.get(); if (widget == ui->spiralGrowth) { spiral->Growth.setValue(ui->spiralGrowth->value().getValue()); @@ -1349,9 +1636,21 @@ CirclePrimitive::CirclePrimitive(std::shared_ptr ui, Part::Cir QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->circleRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->circleAngle1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->circleAngle2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->circleRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->circleAngle1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->circleAngle2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -1363,38 +1662,45 @@ const char* CirclePrimitive::getDefaultName() const QString CirclePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Circle\",\"%1\")\n" - "App.ActiveDocument.%1.Radius='%2'\n" - "App.ActiveDocument.%1.Angle1='%3'\n" - "App.ActiveDocument.%1.Angle2='%4'\n" - "App.ActiveDocument.%1.Placement=%5\n" - "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName, - safeQuantityQString(ui->circleRadius), - safeQuantityQString(ui->circleAngle1), - safeQuantityQString(ui->circleAngle2), - placement, - DlgPrimitives::tr("Circle")); + "App.ActiveDocument.addObject(\"Part::Circle\",\"%1\")\n" + "App.ActiveDocument.%1.Radius='%2'\n" + "App.ActiveDocument.%1.Angle1='%3'\n" + "App.ActiveDocument.%1.Angle2='%4'\n" + "App.ActiveDocument.%1.Placement=%5\n" + "App.ActiveDocument.%1.Label='%6'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->circleRadius), + safeQuantityQString(ui->circleAngle1), + safeQuantityQString(ui->circleAngle2), + placement, + DlgPrimitives::tr("Circle") + ); } QString CirclePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Radius='%2'\n" - "%1.Angle1='%3'\n" - "%1.Angle2='%4'\n" - "%1.Placement=%5\n") - .arg(objectName, - safeQuantityQString(ui->circleRadius), - safeQuantityQString(ui->circleAngle1), - safeQuantityQString(ui->circleAngle2), - placement); + "%1.Radius='%2'\n" + "%1.Angle1='%3'\n" + "%1.Angle2='%4'\n" + "%1.Placement=%5\n" + ) + .arg( + objectName, + safeQuantityQString(ui->circleRadius), + safeQuantityQString(ui->circleAngle1), + safeQuantityQString(ui->circleAngle2), + placement + ); } void CirclePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Circle* circle = featurePtr.get(); if (widget == ui->circleRadius) { circle->Radius.setValue(ui->circleRadius->value().getValue()); @@ -1432,10 +1738,26 @@ EllipsePrimitive::EllipsePrimitive(std::shared_ptr ui, Part::E QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->ellipseMajorRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipseMinorRadius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipseAngle1, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->ellipseAngle2, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->ellipseMajorRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipseMinorRadius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipseAngle1, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->ellipseAngle2, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -1447,42 +1769,49 @@ const char* EllipsePrimitive::getDefaultName() const QString EllipsePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Ellipse\",\"%1\")\n" - "App.ActiveDocument.%1.MajorRadius='%2'\n" - "App.ActiveDocument.%1.MinorRadius='%3'\n" - "App.ActiveDocument.%1.Angle1='%4'\n" - "App.ActiveDocument.%1.Angle2='%5'\n" - "App.ActiveDocument.%1.Placement=%6\n" - "App.ActiveDocument.%1.Label='%7'\n") - .arg(objectName, - safeQuantityQString(ui->ellipseMajorRadius), - safeQuantityQString(ui->ellipseMinorRadius), - safeQuantityQString(ui->ellipseAngle1), - safeQuantityQString(ui->ellipseAngle2), - placement, - DlgPrimitives::tr("Ellipse")); + "App.ActiveDocument.addObject(\"Part::Ellipse\",\"%1\")\n" + "App.ActiveDocument.%1.MajorRadius='%2'\n" + "App.ActiveDocument.%1.MinorRadius='%3'\n" + "App.ActiveDocument.%1.Angle1='%4'\n" + "App.ActiveDocument.%1.Angle2='%5'\n" + "App.ActiveDocument.%1.Placement=%6\n" + "App.ActiveDocument.%1.Label='%7'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->ellipseMajorRadius), + safeQuantityQString(ui->ellipseMinorRadius), + safeQuantityQString(ui->ellipseAngle1), + safeQuantityQString(ui->ellipseAngle2), + placement, + DlgPrimitives::tr("Ellipse") + ); } QString EllipsePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.MajorRadius='%2'\n" - "%1.MinorRadius='%3'\n" - "%1.Angle1='%4'\n" - "%1.Angle2='%5'\n" - "%1.Placement=%6\n") - .arg(objectName, - safeQuantityQString(ui->ellipseMajorRadius), - safeQuantityQString(ui->ellipseMinorRadius), - safeQuantityQString(ui->ellipseAngle1), - safeQuantityQString(ui->ellipseAngle2), - placement); + "%1.MajorRadius='%2'\n" + "%1.MinorRadius='%3'\n" + "%1.Angle1='%4'\n" + "%1.Angle2='%5'\n" + "%1.Placement=%6\n" + ) + .arg( + objectName, + safeQuantityQString(ui->ellipseMajorRadius), + safeQuantityQString(ui->ellipseMinorRadius), + safeQuantityQString(ui->ellipseAngle1), + safeQuantityQString(ui->ellipseAngle2), + placement + ); } void EllipsePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Ellipse* ell = featurePtr.get(); if (widget == ui->ellipseMajorRadius) { ell->MajorRadius.setValue(ui->ellipseMajorRadius->value().getValue()); @@ -1516,7 +1845,11 @@ PolygonPrimitive::PolygonPrimitive(std::shared_ptr ui, Part::R QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); connectMapSignalMapper(ui->regularPolygonPolygon, qOverload(&QSpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->regularPolygonCircumradius, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->regularPolygonCircumradius, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -1528,34 +1861,41 @@ const char* PolygonPrimitive::getDefaultName() const QString PolygonPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::RegularPolygon\",\"%1\")\n" - "App.ActiveDocument.%1.Polygon=%2\n" - "App.ActiveDocument.%1.Circumradius='%3'\n" - "App.ActiveDocument.%1.Placement=%4\n" - "App.ActiveDocument.%1.Label='%5'\n") - .arg(objectName, - QString::number(ui->regularPolygonPolygon->value()), - safeQuantityQString(ui->regularPolygonCircumradius), - placement, - DlgPrimitives::tr("Regular polygon")); + "App.ActiveDocument.addObject(\"Part::RegularPolygon\",\"%1\")\n" + "App.ActiveDocument.%1.Polygon=%2\n" + "App.ActiveDocument.%1.Circumradius='%3'\n" + "App.ActiveDocument.%1.Placement=%4\n" + "App.ActiveDocument.%1.Label='%5'\n" + ) + .arg( + objectName, + QString::number(ui->regularPolygonPolygon->value()), + safeQuantityQString(ui->regularPolygonCircumradius), + placement, + DlgPrimitives::tr("Regular polygon") + ); } QString PolygonPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.Polygon=%2\n" - "%1.Circumradius='%3'\n" - "%1.Placement=%4\n") - .arg(objectName, - QString::number(ui->regularPolygonPolygon->value()), - safeQuantityQString(ui->regularPolygonCircumradius), - placement); + "%1.Polygon=%2\n" + "%1.Circumradius='%3'\n" + "%1.Placement=%4\n" + ) + .arg( + objectName, + QString::number(ui->regularPolygonPolygon->value()), + safeQuantityQString(ui->regularPolygonCircumradius), + placement + ); } void PolygonPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::RegularPolygon* poly = featurePtr.get(); if (widget == ui->regularPolygonPolygon) { poly->Polygon.setValue(ui->regularPolygonPolygon->value()); @@ -1621,50 +1961,57 @@ const char* LinePrimitive::getDefaultName() const QString LinePrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Line\",\"%1\")\n" - "App.ActiveDocument.%1.X1='%2'\n" - "App.ActiveDocument.%1.Y1='%3'\n" - "App.ActiveDocument.%1.Z1='%4'\n" - "App.ActiveDocument.%1.X2='%5'\n" - "App.ActiveDocument.%1.Y2='%6'\n" - "App.ActiveDocument.%1.Z2='%7'\n" - "App.ActiveDocument.%1.Placement=%8\n" - "App.ActiveDocument.%1.Label='%9'\n") - .arg(objectName, - safeQuantityQString(ui->edgeX1), - safeQuantityQString(ui->edgeY1), - safeQuantityQString(ui->edgeZ1), - safeQuantityQString(ui->edgeX2), - safeQuantityQString(ui->edgeY2), - safeQuantityQString(ui->edgeZ2), - placement, - DlgPrimitives::tr("Line")); + "App.ActiveDocument.addObject(\"Part::Line\",\"%1\")\n" + "App.ActiveDocument.%1.X1='%2'\n" + "App.ActiveDocument.%1.Y1='%3'\n" + "App.ActiveDocument.%1.Z1='%4'\n" + "App.ActiveDocument.%1.X2='%5'\n" + "App.ActiveDocument.%1.Y2='%6'\n" + "App.ActiveDocument.%1.Z2='%7'\n" + "App.ActiveDocument.%1.Placement=%8\n" + "App.ActiveDocument.%1.Label='%9'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->edgeX1), + safeQuantityQString(ui->edgeY1), + safeQuantityQString(ui->edgeZ1), + safeQuantityQString(ui->edgeX2), + safeQuantityQString(ui->edgeY2), + safeQuantityQString(ui->edgeZ2), + placement, + DlgPrimitives::tr("Line") + ); } QString LinePrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.X1='%2'\n" - "%1.Y1='%3'\n" - "%1.Z1='%4'\n" - "%1.X2='%5'\n" - "%1.Y2='%6'\n" - "%1.Z2='%7'\n" - "%1.Placement=%8\n") - .arg(objectName, - safeQuantityQString(ui->edgeX1), - safeQuantityQString(ui->edgeY1), - safeQuantityQString(ui->edgeZ1), - safeQuantityQString(ui->edgeX2), - safeQuantityQString(ui->edgeY2), - safeQuantityQString(ui->edgeZ2), - placement); + "%1.X1='%2'\n" + "%1.Y1='%3'\n" + "%1.Z1='%4'\n" + "%1.X2='%5'\n" + "%1.Y2='%6'\n" + "%1.Z2='%7'\n" + "%1.Placement=%8\n" + ) + .arg( + objectName, + safeQuantityQString(ui->edgeX1), + safeQuantityQString(ui->edgeY1), + safeQuantityQString(ui->edgeZ1), + safeQuantityQString(ui->edgeX2), + safeQuantityQString(ui->edgeY2), + safeQuantityQString(ui->edgeZ2), + placement + ); } void LinePrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Line* line = featurePtr.get(); if (widget == ui->edgeX1) { line->X1.setValue(ui->edgeX1->value().getValue()); @@ -1713,9 +2060,21 @@ VertexPrimitive::VertexPrimitive(std::shared_ptr ui, Part::Ver QSignalMapper* mapper = new QSignalMapper(this); connectSignalMapper(mapper); - connectMapSignalMapper(ui->vertexX, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->vertexY, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); - connectMapSignalMapper(ui->vertexZ, qOverload(&Gui::QuantitySpinBox::valueChanged), mapper); + connectMapSignalMapper( + ui->vertexX, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->vertexY, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); + connectMapSignalMapper( + ui->vertexZ, + qOverload(&Gui::QuantitySpinBox::valueChanged), + mapper + ); } } @@ -1727,38 +2086,45 @@ const char* VertexPrimitive::getDefaultName() const QString VertexPrimitive::create(const QString& objectName, const QString& placement) const { return QStringLiteral( - "App.ActiveDocument.addObject(\"Part::Vertex\",\"%1\")\n" - "App.ActiveDocument.%1.X='%2'\n" - "App.ActiveDocument.%1.Y='%3'\n" - "App.ActiveDocument.%1.Z='%4'\n" - "App.ActiveDocument.%1.Placement=%5\n" - "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName, - safeQuantityQString(ui->vertexX), - safeQuantityQString(ui->vertexY), - safeQuantityQString(ui->vertexZ), - placement, - DlgPrimitives::tr("Vertex")); + "App.ActiveDocument.addObject(\"Part::Vertex\",\"%1\")\n" + "App.ActiveDocument.%1.X='%2'\n" + "App.ActiveDocument.%1.Y='%3'\n" + "App.ActiveDocument.%1.Z='%4'\n" + "App.ActiveDocument.%1.Placement=%5\n" + "App.ActiveDocument.%1.Label='%6'\n" + ) + .arg( + objectName, + safeQuantityQString(ui->vertexX), + safeQuantityQString(ui->vertexY), + safeQuantityQString(ui->vertexZ), + placement, + DlgPrimitives::tr("Vertex") + ); } QString VertexPrimitive::change(const QString& objectName, const QString& placement) const { return QStringLiteral( - "%1.X='%2'\n" - "%1.Y='%3'\n" - "%1.Z='%4'\n" - "%1.Placement=%5\n") - .arg(objectName, - safeQuantityQString(ui->vertexX), - safeQuantityQString(ui->vertexY), - safeQuantityQString(ui->vertexZ), - placement); + "%1.X='%2'\n" + "%1.Y='%3'\n" + "%1.Z='%4'\n" + "%1.Placement=%5\n" + ) + .arg( + objectName, + safeQuantityQString(ui->vertexX), + safeQuantityQString(ui->vertexY), + safeQuantityQString(ui->vertexZ), + placement + ); } void VertexPrimitive::changeValue(QObject* widget) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } Part::Vertex* v = featurePtr.get(); if (widget == ui->vertexX) { v->X.setValue(ui->vertexX->value().getValue()); @@ -1778,13 +2144,17 @@ void VertexPrimitive::changeValue(QObject* widget) /* TRANSLATOR PartGui::DlgPrimitives */ DlgPrimitives::DlgPrimitives(QWidget* parent, Part::Primitive* feature) - : QWidget(parent) - , ui(new Ui_DlgPrimitives) - , featurePtr(feature) + : QWidget(parent) + , ui(new Ui_DlgPrimitives) + , featurePtr(feature) { ui->setupUi(this); - connect(ui->buttonCircleFromThreePoints, &QPushButton::clicked, - this, &DlgPrimitives::buttonCircleFromThreePoints); + connect( + ui->buttonCircleFromThreePoints, + &QPushButton::clicked, + this, + &DlgPrimitives::buttonCircleFromThreePoints + ); Gui::Command::doCommand(Gui::Command::Doc, "from FreeCAD import Base"); Gui::Command::doCommand(Gui::Command::Doc, "import Part,PartGui"); @@ -1836,24 +2206,27 @@ std::shared_ptr DlgPrimitives::getPrimitive(int index) const int DlgPrimitives::findIndexOfValidPrimitive() const { - return std::distance(primitive.begin(), std::find_if(primitive.begin(), primitive.end(), - [](std::shared_ptr prim) { - return prim->hasValidPrimitive(); - })); + return std::distance( + primitive.begin(), + std::find_if(primitive.begin(), primitive.end(), [](std::shared_ptr prim) { + return prim->hasValidPrimitive(); + }) + ); } -void DlgPrimitives::pickCallback(void * ud, SoEventCallback * n) +void DlgPrimitives::pickCallback(void* ud, SoEventCallback* n) { - const SoMouseButtonEvent * mbe = static_cast(n->getEvent()); + const SoMouseButtonEvent* mbe = static_cast(n->getEvent()); Picker* pick = static_cast(ud); - if (pick->exitCode >= 0) + if (pick->exitCode >= 0) { pick->loop.exit(pick->exitCode); + } // Mark all incoming mouse button events as handled, especially, to deactivate the selection node n->setHandled(); if (mbe->getButton() == SoMouseButtonEvent::BUTTON1) { if (mbe->getState() == SoButtonEvent::DOWN) { - const SoPickedPoint * point = n->getPickedPoint(); + const SoPickedPoint* point = n->getPickedPoint(); if (point) { if (pick->pickedPoint(point)) { pick->exitCode = 0; @@ -1885,13 +2258,16 @@ void DlgPrimitives::executeCallback(Picker* p) int mode = 0; if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) { mode = static_cast(root)->selectionMode.getValue(); - static_cast(root)->selectionMode.setValue(Gui::SoFCUnifiedSelection::OFF); + static_cast(root)->selectionMode.setValue( + Gui::SoFCUnifiedSelection::OFF + ); } viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), pickCallback, p); this->setDisabled(true); int ret = p->loop.exec(); - if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) + if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) { static_cast(root)->selectionMode.setValue(mode); + } this->setEnabled(true); viewer->setEditing(false); viewer->setRedirectToSceneGraph(false); @@ -1916,8 +2292,11 @@ void DlgPrimitives::tryCreatePrimitive(const QString& placement) QString name; App::Document* doc = App::GetApplication().getActiveDocument(); if (!doc) { - QMessageBox::warning(this, tr("Create %1") - .arg(ui->PrimitiveTypeCB->currentText()), tr("No active document")); + QMessageBox::warning( + this, + tr("Create %1").arg(ui->PrimitiveTypeCB->currentText()), + tr("No active document") + ); return; } @@ -1941,12 +2320,18 @@ void DlgPrimitives::createPrimitive(const QString& placement) tryCreatePrimitive(placement); } catch (const std::exception& e) { - QMessageBox::warning(this, tr("Create %1") - .arg(ui->PrimitiveTypeCB->currentText()), QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + this, + tr("Create %1").arg(ui->PrimitiveTypeCB->currentText()), + QCoreApplication::translate("Exception", e.what()) + ); } catch (const Base::PyException& e) { - QMessageBox::warning(this, tr("Create %1") - .arg(ui->PrimitiveTypeCB->currentText()), QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + this, + tr("Create %1").arg(ui->PrimitiveTypeCB->currentText()), + QCoreApplication::translate("Exception", e.what()) + ); } } @@ -1954,8 +2339,10 @@ void DlgPrimitives::acceptChanges(const QString& placement) { App::Document* doc = featurePtr->getDocument(); QString objectName = QStringLiteral("App.getDocument(\"%1\").%2") - .arg(QString::fromLatin1(doc->getName()), - QString::fromLatin1(featurePtr->getNameInDocument())); + .arg( + QString::fromLatin1(doc->getName()), + QString::fromLatin1(featurePtr->getNameInDocument()) + ); // read values from the properties std::shared_ptr primitive = getPrimitive(ui->PrimitiveTypeCB->currentIndex()); @@ -1967,8 +2354,9 @@ void DlgPrimitives::acceptChanges(const QString& placement) void DlgPrimitives::accept(const QString& placement) { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } App::Document* doc = featurePtr->getDocument(); acceptChanges(placement); doc->recompute(); @@ -1978,8 +2366,9 @@ void DlgPrimitives::accept(const QString& placement) void DlgPrimitives::reject() { - if (featurePtr.expired()) + if (featurePtr.expired()) { return; + } App::Document* doc = featurePtr->getDocument(); doc->abortTransaction(); } @@ -1995,8 +2384,7 @@ Location::Location(QWidget* parent, Part::Feature* feature) { mode = 0; ui->setupUi(this); - connect(ui->viewPositionButton, &QPushButton::clicked, - this, &Location::onViewPositionButton); + connect(ui->viewPositionButton, &QPushButton::clicked, this, &Location::onViewPositionButton); ui->XPositionQSB->setUnit(Base::Unit::Length); ui->YPositionQSB->setUnit(Base::Unit::Length); @@ -2015,14 +2403,15 @@ Location::~Location() { // no need to delete child widgets, Qt does it all for us if (!this->activeView.isNull()) { - Gui::View3DInventorViewer* viewer = static_cast - (this->activeView.data())->getViewer(); + Gui::View3DInventorViewer* viewer + = static_cast(this->activeView.data())->getViewer(); viewer->setEditing(false); viewer->setRedirectToSceneGraph(false); - viewer->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), pickCallback,this); + viewer->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), pickCallback, this); SoNode* root = viewer->getSceneGraph(); - if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) + if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) { static_cast(root)->selectionMode.setValue(this->mode); + } } } @@ -2052,28 +2441,70 @@ void Location::bindExpressions(Part::Feature* feature) ui->XPositionQSB->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Base.x"))); ui->YPositionQSB->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Base.y"))); ui->ZPositionQSB->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Base.z"))); - ui->XDirectionEdit->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Axis.x"))); - ui->YDirectionEdit->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Axis.y"))); - ui->ZDirectionEdit->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Axis.z"))); + ui->XDirectionEdit->bind( + App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Axis.x")) + ); + ui->YDirectionEdit->bind( + App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Axis.y")) + ); + ui->ZDirectionEdit->bind( + App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Axis.z")) + ); ui->AngleQSB->bind(App::ObjectIdentifier::parse(feature, std::string("Placement.Rotation.Angle"))); } void Location::connectSignals() { - connect(ui->XPositionQSB, qOverload(&Gui::QuantitySpinBox::valueChanged), this, &Location::onPlacementChanged); - connect(ui->YPositionQSB, qOverload(&Gui::QuantitySpinBox::valueChanged), this, &Location::onPlacementChanged); - connect(ui->ZPositionQSB, qOverload(&Gui::QuantitySpinBox::valueChanged), this, &Location::onPlacementChanged); - connect(ui->AngleQSB, qOverload(&Gui::QuantitySpinBox::valueChanged), this, &Location::onPlacementChanged); - connect(ui->XDirectionEdit, qOverload(&Gui::DoubleSpinBox::valueChanged), this, &Location::onPlacementChanged); - connect(ui->YDirectionEdit, qOverload(&Gui::DoubleSpinBox::valueChanged), this, &Location::onPlacementChanged); - connect(ui->ZDirectionEdit, qOverload(&Gui::DoubleSpinBox::valueChanged), this, &Location::onPlacementChanged); + connect( + ui->XPositionQSB, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); + connect( + ui->YPositionQSB, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); + connect( + ui->ZPositionQSB, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); + connect( + ui->AngleQSB, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); + connect( + ui->XDirectionEdit, + qOverload(&Gui::DoubleSpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); + connect( + ui->YDirectionEdit, + qOverload(&Gui::DoubleSpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); + connect( + ui->ZDirectionEdit, + qOverload(&Gui::DoubleSpinBox::valueChanged), + this, + &Location::onPlacementChanged + ); } void Location::onPlacementChanged() { App::GeoFeature* geom = featurePtr.get(); - if (!geom) + if (!geom) { return; + } // read dialog values Base::Vector3d loc; @@ -2117,22 +2548,24 @@ void Location::onViewPositionButton() SoNode* root = viewer->getSceneGraph(); if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) { this->mode = static_cast(root)->selectionMode.getValue(); - static_cast(root)->selectionMode.setValue(Gui::SoFCUnifiedSelection::OFF); + static_cast(root)->selectionMode.setValue( + Gui::SoFCUnifiedSelection::OFF + ); } } - } + } } -void Location::pickCallback(void * ud, SoEventCallback * n) +void Location::pickCallback(void* ud, SoEventCallback* n) { - const SoMouseButtonEvent * mbe = static_cast(n->getEvent()); - Gui::View3DInventorViewer* view = static_cast(n->getUserData()); + const SoMouseButtonEvent* mbe = static_cast(n->getEvent()); + Gui::View3DInventorViewer* view = static_cast(n->getUserData()); // Mark all incoming mouse button events as handled, especially, to deactivate the selection node n->getAction()->setHandled(); if (mbe->getButton() == SoMouseButtonEvent::BUTTON1) { if (mbe->getState() == SoButtonEvent::DOWN) { - const SoPickedPoint * point = n->getPickedPoint(); + const SoPickedPoint* point = n->getPickedPoint(); if (point) { SbVec3f pnt = point->getPoint(); SbVec3f nor = point->getNormal(); @@ -2154,10 +2587,13 @@ void Location::pickCallback(void * ud, SoEventCallback * n) view->setRedirectToSceneGraph(false); Location* dlg = static_cast(ud); dlg->activeView = nullptr; - view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), pickCallback,ud); + view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), pickCallback, ud); SoNode* root = view->getSceneGraph(); - if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) - static_cast(root)->selectionMode.setValue(static_cast(ud)->mode); + if (root && root->getTypeId().isDerivedFrom(Gui::SoFCUnifiedSelection::getClassTypeId())) { + static_cast(root)->selectionMode.setValue( + static_cast(ud)->mode + ); + } } } } @@ -2203,8 +2639,7 @@ TaskPrimitives::TaskPrimitives() QDialogButtonBox::StandardButtons TaskPrimitives::getStandardButtons() const { - return QDialogButtonBox::Close| - QDialogButtonBox::Ok; + return QDialogButtonBox::Close | QDialogButtonBox::Ok; } void TaskPrimitives::modifyStandardButtons(QDialogButtonBox* box) @@ -2241,14 +2676,13 @@ TaskPrimitivesEdit::TaskPrimitivesEdit(Part::Primitive* feature) QDialogButtonBox::StandardButtons TaskPrimitivesEdit::getStandardButtons() const { - return QDialogButtonBox::Cancel | - QDialogButtonBox::Ok; + return QDialogButtonBox::Cancel | QDialogButtonBox::Ok; } bool TaskPrimitivesEdit::accept() { widget->accept(location->toPlacement()); - std::string document = getDocumentName(); // needed because resetEdit() deletes this instance + std::string document = getDocumentName(); // needed because resetEdit() deletes this instance Gui::Command::doCommand(Gui::Command::Gui, "Gui.getDocument('%s').resetEdit()", document.c_str()); return true; } @@ -2256,7 +2690,7 @@ bool TaskPrimitivesEdit::accept() bool TaskPrimitivesEdit::reject() { widget->reject(); - std::string document = getDocumentName(); // needed because resetEdit() deletes this instance + std::string document = getDocumentName(); // needed because resetEdit() deletes this instance Gui::Command::doCommand(Gui::Command::Gui, "Gui.getDocument('%s').resetEdit()", document.c_str()); return true; } diff --git a/src/Mod/Part/Gui/DlgPrimitives.h b/src/Mod/Part/Gui/DlgPrimitives.h index 67ceea66af..95302f992e 100644 --- a/src/Mod/Part/Gui/DlgPrimitives.h +++ b/src/Mod/Part/Gui/DlgPrimitives.h @@ -36,9 +36,16 @@ class SoPickedPoint; class SoEventCallback; class QSignalMapper; -namespace App { class Document; } -namespace Gui { class Document; } -namespace Part { +namespace App +{ +class Document; +} +namespace Gui +{ +class Document; +} +namespace Part +{ class Feature; class Primitive; class Plane; @@ -57,26 +64,27 @@ class Ellipse; class Vertex; class Line; class RegularPolygon; -} -namespace PartGui { +} // namespace Part +namespace PartGui +{ class Picker { public: virtual ~Picker() = default; - virtual bool pickedPoint(const SoPickedPoint * point) = 0; + virtual bool pickedPoint(const SoPickedPoint* point) = 0; virtual QString command(App::Document*) const = 0; void createPrimitive(QWidget* widget, const QString&, Gui::Document*); QString toPlacement(const gp_Ax2&) const; - int exitCode{-1}; + int exitCode {-1}; QEventLoop loop; }; class Ui_DlgPrimitives; -class AbstractPrimitive : public QObject +class AbstractPrimitive: public QObject { Q_OBJECT @@ -99,7 +107,7 @@ protected: // ---------------------------------------------------------------------------- -class PlanePrimitive : public AbstractPrimitive +class PlanePrimitive: public AbstractPrimitive { Q_OBJECT @@ -117,7 +125,7 @@ private: // ---------------------------------------------------------------------------- -class BoxPrimitive : public AbstractPrimitive +class BoxPrimitive: public AbstractPrimitive { Q_OBJECT @@ -135,7 +143,7 @@ private: // ---------------------------------------------------------------------------- -class CylinderPrimitive : public AbstractPrimitive +class CylinderPrimitive: public AbstractPrimitive { Q_OBJECT @@ -153,7 +161,7 @@ private: // ---------------------------------------------------------------------------- -class ConePrimitive : public AbstractPrimitive +class ConePrimitive: public AbstractPrimitive { Q_OBJECT @@ -171,7 +179,7 @@ private: // ---------------------------------------------------------------------------- -class SpherePrimitive : public AbstractPrimitive +class SpherePrimitive: public AbstractPrimitive { Q_OBJECT @@ -189,7 +197,7 @@ private: // ---------------------------------------------------------------------------- -class EllipsoidPrimitive : public AbstractPrimitive +class EllipsoidPrimitive: public AbstractPrimitive { Q_OBJECT @@ -207,7 +215,7 @@ private: // ---------------------------------------------------------------------------- -class TorusPrimitive : public AbstractPrimitive +class TorusPrimitive: public AbstractPrimitive { Q_OBJECT @@ -225,7 +233,7 @@ private: // ---------------------------------------------------------------------------- -class PrismPrimitive : public AbstractPrimitive +class PrismPrimitive: public AbstractPrimitive { Q_OBJECT @@ -243,7 +251,7 @@ private: // ---------------------------------------------------------------------------- -class WedgePrimitive : public AbstractPrimitive +class WedgePrimitive: public AbstractPrimitive { Q_OBJECT @@ -261,7 +269,7 @@ private: // ---------------------------------------------------------------------------- -class HelixPrimitive : public AbstractPrimitive +class HelixPrimitive: public AbstractPrimitive { Q_OBJECT @@ -279,7 +287,7 @@ private: // ---------------------------------------------------------------------------- -class SpiralPrimitive : public AbstractPrimitive +class SpiralPrimitive: public AbstractPrimitive { Q_OBJECT @@ -297,7 +305,7 @@ private: // ---------------------------------------------------------------------------- -class CirclePrimitive : public AbstractPrimitive +class CirclePrimitive: public AbstractPrimitive { Q_OBJECT @@ -315,7 +323,7 @@ private: // ---------------------------------------------------------------------------- -class EllipsePrimitive : public AbstractPrimitive +class EllipsePrimitive: public AbstractPrimitive { Q_OBJECT @@ -333,7 +341,7 @@ private: // ---------------------------------------------------------------------------- -class PolygonPrimitive : public AbstractPrimitive +class PolygonPrimitive: public AbstractPrimitive { Q_OBJECT @@ -351,7 +359,7 @@ private: // ---------------------------------------------------------------------------- -class LinePrimitive : public AbstractPrimitive +class LinePrimitive: public AbstractPrimitive { Q_OBJECT @@ -369,7 +377,7 @@ private: // ---------------------------------------------------------------------------- -class VertexPrimitive : public AbstractPrimitive +class VertexPrimitive: public AbstractPrimitive { Q_OBJECT @@ -387,7 +395,7 @@ private: // ---------------------------------------------------------------------------- -class DlgPrimitives : public QWidget +class DlgPrimitives: public QWidget { Q_OBJECT @@ -402,7 +410,7 @@ private: void buttonCircleFromThreePoints(); private: - static void pickCallback(void * ud, SoEventCallback * n); + static void pickCallback(void* ud, SoEventCallback* n); void executeCallback(Picker*); void acceptChanges(const QString&); void tryCreatePrimitive(const QString&); @@ -420,7 +428,7 @@ private: }; class Ui_Location; -class Location : public QWidget +class Location: public QWidget { Q_OBJECT @@ -437,7 +445,7 @@ private: void setPlacement(Part::Feature* feature); void bindExpressions(Part::Feature* feature); void connectSignals(); - static void pickCallback(void * ud, SoEventCallback * n); + static void pickCallback(void* ud, SoEventCallback* n); int mode; QPointer activeView; @@ -445,7 +453,7 @@ private: App::DocumentObjectWeakPtrT featurePtr; }; -class TaskPrimitives : public Gui::TaskView::TaskDialog +class TaskPrimitives: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -463,7 +471,7 @@ private: Location* location; }; -class TaskPrimitivesEdit : public Gui::TaskView::TaskDialog +class TaskPrimitivesEdit: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -480,6 +488,6 @@ private: Location* location; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGPRIMITIVES_H +#endif // PARTGUI_DLGPRIMITIVES_H diff --git a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp index 9f18035db5..2ce7958a86 100644 --- a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp +++ b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp @@ -62,7 +62,8 @@ using namespace PartGui; -namespace { +namespace +{ ////////////////////////////////////////////////////////////////////////// class EdgeSelection: public Gui::SelectionFilterGate { @@ -129,7 +130,7 @@ public: } }; ////////////////////////////////////////////////////////////////////////// -} +} // namespace DlgProjectionOnSurface::DlgProjectionOnSurface(QWidget* parent) : QWidget(parent) @@ -184,11 +185,14 @@ DlgProjectionOnSurface::~DlgProjectionOnSurface() higlight_object(it.partFeature, it.partName, false, 0); } catch (Standard_NoSuchObject& e) { - Base::Console().warning("DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", - e.GetMessageString()); + Base::Console().warning( + "DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", + e.GetMessageString() + ); } auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(it.partFeature)); + Gui::Application::Instance->getViewProvider(it.partFeature) + ); if (vp) { vp->Selectable.setValue(it.is_selectable); vp->Transparency.setValue(it.transparency); @@ -199,8 +203,10 @@ DlgProjectionOnSurface::~DlgProjectionOnSurface() higlight_object(it.partFeature, it.partName, false, 0); } catch (Standard_NoSuchObject& e) { - Base::Console().warning("DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", - e.GetMessageString()); + Base::Console().warning( + "DlgProjectionOnSurface::~DlgProjectionOnSurface: %s", + e.GetMessageString() + ); } } Gui::Selection().rmvSelectionGate(); @@ -367,8 +373,8 @@ void PartGui::DlgProjectionOnSurface::onSelectionChanged(const Gui::SelectionCha store_current_selected_parts(m_projectionSurfaceVec, 0xffff0000); if (!m_projectionSurfaceVec.empty()) { auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider( - m_projectionSurfaceVec.back().partFeature)); + Gui::Application::Instance->getViewProvider(m_projectionSurfaceVec.back().partFeature) + ); if (vp) { vp->Selectable.setValue(false); vp->Transparency.setValue(90); @@ -406,7 +412,8 @@ void PartGui::DlgProjectionOnSurface::get_camera_direction() void PartGui::DlgProjectionOnSurface::store_current_selected_parts( std::vector& iStoreVec, - unsigned int iColor) + unsigned int iColor +) { if (!m_partDocument) { return; @@ -426,7 +433,8 @@ void PartGui::DlgProjectionOnSurface::store_current_selected_parts( currentShapeStore.partName = aPart->getNameInDocument(); auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(aPart)); + Gui::Application::Instance->getViewProvider(aPart) + ); if (vp) { currentShapeStore.is_selectable = vp->Selectable.getValue(); currentShapeStore.transparency = vp->Transparency.getValue(); @@ -446,8 +454,10 @@ void PartGui::DlgProjectionOnSurface::store_current_selected_parts( } } else { - transform_shape_to_global_position(currentShapeStore.inputShape, - currentShapeStore.partFeature); + transform_shape_to_global_position( + currentShapeStore.inputShape, + currentShapeStore.partFeature + ); auto store = store_part_in_vector(currentShapeStore, iStoreVec); higlight_object(aPart, aPart->Shape.getName(), store, iColor); } @@ -458,8 +468,10 @@ void PartGui::DlgProjectionOnSurface::store_current_selected_parts( } } -bool PartGui::DlgProjectionOnSurface::store_part_in_vector(SShapeStore& iCurrentShape, - std::vector& iStoreVec) +bool PartGui::DlgProjectionOnSurface::store_part_in_vector( + SShapeStore& iCurrentShape, + std::vector& iStoreVec +) { if (iCurrentShape.inputShape.IsNull()) { return false; @@ -499,8 +511,7 @@ bool PartGui::DlgProjectionOnSurface::store_part_in_vector(SShapeStore& iCurrent return true; } -void PartGui::DlgProjectionOnSurface::create_projection_wire( - std::vector& iCurrentShape) +void PartGui::DlgProjectionOnSurface::create_projection_wire(std::vector& iCurrentShape) { try { if (iCurrentShape.empty()) { @@ -523,9 +534,11 @@ void PartGui::DlgProjectionOnSurface::create_projection_wire( if (!itCurrentShape.aFace.IsNull()) { get_all_wire_from_face(itCurrentShape); for (const auto& itWire : itCurrentShape.aWireVec) { - BRepProj_Projection aProjection(itWire, - itCurrentShape.surfaceToProject, - itCurrentShape.aProjectionDir); + BRepProj_Projection aProjection( + itWire, + itCurrentShape.surfaceToProject, + itCurrentShape.aProjectionDir + ); double minDistance = std::numeric_limits::max(); TopoDS_Wire wireToTake; for (; aProjection.More(); aProjection.Next()) { @@ -544,9 +557,11 @@ void PartGui::DlgProjectionOnSurface::create_projection_wire( } } else if (!itCurrentShape.aEdge.IsNull()) { - BRepProj_Projection aProjection(itCurrentShape.aEdge, - itCurrentShape.surfaceToProject, - itCurrentShape.aProjectionDir); + BRepProj_Projection aProjection( + itCurrentShape.aEdge, + itCurrentShape.surfaceToProject, + itCurrentShape.aProjectionDir + ); double minDistance = std::numeric_limits::max(); TopoDS_Wire wireToTake; for (; aProjection.More(); aProjection.Next()) { @@ -574,8 +589,7 @@ void PartGui::DlgProjectionOnSurface::create_projection_wire( } } -TopoDS_Shape -PartGui::DlgProjectionOnSurface::create_compound(const std::vector& iShapeVec) +TopoDS_Shape PartGui::DlgProjectionOnSurface::create_compound(const std::vector& iShapeVec) { if (iShapeVec.empty()) { return {}; @@ -635,7 +649,8 @@ PartGui::DlgProjectionOnSurface::create_compound(const std::vector& } void PartGui::DlgProjectionOnSurface::show_projected_shapes( - const std::vector& iShapeStoreVec) + const std::vector& iShapeStoreVec +) { if (!m_projectionObject) { return; @@ -654,7 +669,8 @@ void PartGui::DlgProjectionOnSurface::show_projected_shapes( // set color auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(m_projectionObject)); + Gui::Application::Instance->getViewProvider(m_projectionObject) + ); if (vp) { const unsigned int color = 0x8ae23400; vp->LineColor.setValue(color); @@ -664,8 +680,10 @@ void PartGui::DlgProjectionOnSurface::show_projected_shapes( } } -void PartGui::DlgProjectionOnSurface::disable_ui_elements(const std::vector& iObjectVec, - QWidget* iExceptThis) +void PartGui::DlgProjectionOnSurface::disable_ui_elements( + const std::vector& iObjectVec, + QWidget* iExceptThis +) { for (auto it : iObjectVec) { if (!it) { @@ -678,8 +696,10 @@ void PartGui::DlgProjectionOnSurface::disable_ui_elements(const std::vector& iObjectVec, - QWidget* iExceptThis) +void PartGui::DlgProjectionOnSurface::enable_ui_elements( + const std::vector& iObjectVec, + QWidget* iExceptThis +) { for (auto it : iObjectVec) { if (!it) { @@ -692,10 +712,12 @@ void PartGui::DlgProjectionOnSurface::enable_ui_elements(const std::vector( - Gui::Application::Instance->getViewProvider(iCurrentObject)); + Gui::Application::Instance->getViewProvider(iCurrentObject) + ); if (vp) { std::vector colors; Base::Color defaultColor; @@ -770,7 +793,8 @@ void PartGui::DlgProjectionOnSurface::get_all_wire_from_face(SShapeStore& ioCurr } void PartGui::DlgProjectionOnSurface::create_projection_face_from_wire( - std::vector& iCurrentShape) + std::vector& iCurrentShape +) { try { if (iCurrentShape.empty()) { @@ -808,19 +832,21 @@ void PartGui::DlgProjectionOnSurface::create_projection_face_from_wire( for (auto itEdge : edgeVec) { Standard_Real first {}; Standard_Real last {}; - auto currentCurve = BRep_Tool::CurveOnSurface(TopoDS::Edge(itEdge), - itCurrentShape.surfaceToProject, - first, - last); + auto currentCurve = BRep_Tool::CurveOnSurface( + TopoDS::Edge(itEdge), + itCurrentShape.surfaceToProject, + first, + last + ); if (!currentCurve) { continue; } - auto edgeInParametricSpace = - BRepBuilderAPI_MakeEdge(currentCurve, surface, first, last).Edge(); + auto edgeInParametricSpace + = BRepBuilderAPI_MakeEdge(currentCurve, surface, first, last).Edge(); edgeInParametricSpaceVec.push_back(edgeInParametricSpace); } - auto aWire = - sort_and_heal_wire(edgeInParametricSpaceVec, itCurrentShape.surfaceToProject); + auto aWire + = sort_and_heal_wire(edgeInParametricSpaceVec, itCurrentShape.surfaceToProject); itCurrentShape.aProjectedWireInParametricSpaceVec.push_back(aWire); } @@ -843,8 +869,8 @@ void PartGui::DlgProjectionOnSurface::create_projection_face_from_wire( auto aFace = fix.Face(); BRepCheck_Analyzer aChecker(aFace); if (!aChecker.IsValid()) { - faceMaker = - BRepBuilderAPI_MakeFace(surface, TopoDS::Wire(currentWire.Reversed())); + faceMaker + = BRepBuilderAPI_MakeFace(surface, TopoDS::Wire(currentWire.Reversed())); } } else { @@ -874,8 +900,10 @@ void PartGui::DlgProjectionOnSurface::create_projection_face_from_wire( } } -TopoDS_Wire PartGui::DlgProjectionOnSurface::sort_and_heal_wire(const TopoDS_Shape& iShape, - const TopoDS_Face& iFaceToProject) +TopoDS_Wire PartGui::DlgProjectionOnSurface::sort_and_heal_wire( + const TopoDS_Shape& iShape, + const TopoDS_Face& iFaceToProject +) { std::vector aEdgeVec; for (TopExp_Explorer aExplorer(iShape, TopAbs_EDGE); aExplorer.More(); aExplorer.Next()) { @@ -885,9 +913,10 @@ TopoDS_Wire PartGui::DlgProjectionOnSurface::sort_and_heal_wire(const TopoDS_Sha return sort_and_heal_wire(aEdgeVec, iFaceToProject); } -TopoDS_Wire -PartGui::DlgProjectionOnSurface::sort_and_heal_wire(const std::vector& iEdgeVec, - const TopoDS_Face& iFaceToProject) +TopoDS_Wire PartGui::DlgProjectionOnSurface::sort_and_heal_wire( + const std::vector& iEdgeVec, + const TopoDS_Face& iFaceToProject +) { // try to sort and heal all wires // if the wires are not clean making a face will fail! @@ -958,10 +987,12 @@ void PartGui::DlgProjectionOnSurface::create_face_extrude(std::vector& iStoreVec, - unsigned int iColor) +void PartGui::DlgProjectionOnSurface::store_wire_in_vector( + const SShapeStore& iCurrentShape, + const TopoDS_Shape& iParentShape, + std::vector& iStoreVec, + unsigned int iColor +) { if (m_currentSelection != "add_wire") { return; @@ -1043,8 +1074,10 @@ void PartGui::DlgProjectionOnSurface::set_xyz_dir_spinbox(QDoubleSpinBox* icurre icurrentSpinBox->setValue(newVal); } -void PartGui::DlgProjectionOnSurface::transform_shape_to_global_position(TopoDS_Shape& ioShape, - Part::Feature* iPart) +void PartGui::DlgProjectionOnSurface::transform_shape_to_global_position( + TopoDS_Shape& ioShape, + Part::Feature* iPart +) { auto currentPos = iPart->Placement.getValue().getPosition(); auto currentRotation = iPart->Placement.getValue().getRotation(); @@ -1060,16 +1093,22 @@ void PartGui::DlgProjectionOnSurface::transform_shape_to_global_position(TopoDS_ Base::Vector3d rotationAxes; double rotationAngle {}; newRotation.getRawValue(rotationAxes, rotationAngle); - aAngleTransform.SetRotation(gp_Ax1(gp_Pnt(currentPos.x, currentPos.y, currentPos.z), - gp_Dir(rotationAxes.x, rotationAxes.y, rotationAxes.z)), - rotationAngle); + aAngleTransform.SetRotation( + gp_Ax1( + gp_Pnt(currentPos.x, currentPos.y, currentPos.z), + gp_Dir(rotationAxes.x, rotationAxes.y, rotationAxes.z) + ), + rotationAngle + ); ioShape = BRepBuilderAPI_Transform(ioShape, aAngleTransform, true).Shape(); } if (currentPos != globalPosition) { gp_Trsf aPosTransform; - aPosTransform.SetTranslation(gp_Pnt(currentPos.x, currentPos.y, currentPos.z), - gp_Pnt(globalPosition.x, globalPosition.y, globalPosition.z)); + aPosTransform.SetTranslation( + gp_Pnt(currentPos.x, currentPos.y, currentPos.z), + gp_Pnt(globalPosition.x, globalPosition.y, globalPosition.z) + ); ioShape = BRepBuilderAPI_Transform(ioShape, aPosTransform, true).Shape(); } } @@ -1157,10 +1196,12 @@ void PartGui::DlgProjectionOnSurface::onDoubleSpinBoxSolidDepthValueChanged(doub TaskProjectionOnSurface::TaskProjectionOnSurface() : widget(new DlgProjectionOnSurface()) - , taskbox(new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("Part_ProjectionOnSurface"), - widget->windowTitle(), - true, - nullptr)) + , taskbox(new Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("Part_ProjectionOnSurface"), + widget->windowTitle(), + true, + nullptr + )) { taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); @@ -1437,7 +1478,10 @@ void DlgProjectOnSurface::addWire(const Gui::SelectionChanges& msg) return; } - Part::TopoShape part = Part::Feature::getTopoShape(selObj.getObject(), Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape part = Part::Feature::getTopoShape( + selObj.getObject(), + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (part.isNull()) { return; } @@ -1452,7 +1496,7 @@ void DlgProjectOnSurface::addWire(const Gui::SelectionChanges& msg) const TopoDS_Shape& shape = part.getShape(); for (TopExp_Explorer xp(shape, TopAbs_WIRE); xp.More(); xp.Next()) { if (isEdgePartOf(xp.Current(), edge)) { - std::string name{"Wire"}; + std::string name {"Wire"}; name += std::to_string(index); addSelection(msg, name); break; @@ -1461,8 +1505,7 @@ void DlgProjectOnSurface::addWire(const Gui::SelectionChanges& msg) } } -void DlgProjectOnSurface::addSelection(const Gui::SelectionChanges& msg, - const std::string& subName) +void DlgProjectOnSurface::addSelection(const Gui::SelectionChanges& msg, const std::string& subName) { if (!feature.expired()) { Gui::SelectionObject selObj(msg); @@ -1560,18 +1603,24 @@ TaskProjectOnSurface::TaskProjectOnSurface(App::Document* doc) doc->openTransaction(QT_TRANSLATE_NOOP("Command", "Project on surface")); auto feature = doc->addObject("Projection"); widget = new DlgProjectOnSurface(feature); - taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("Part_ProjectionOnSurface"), - widget->windowTitle(), true, nullptr); + taskbox = new Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("Part_ProjectionOnSurface"), + widget->windowTitle(), + true, + nullptr + ); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); } TaskProjectOnSurface::TaskProjectOnSurface(Part::ProjectOnSurface* feature) : widget(new DlgProjectOnSurface(feature)) - , taskbox(new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("Part_ProjectionOnSurface"), - widget->windowTitle(), - true, - nullptr)) + , taskbox(new Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("Part_ProjectionOnSurface"), + widget->windowTitle(), + true, + nullptr + )) { taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); diff --git a/src/Mod/Part/Gui/DlgProjectionOnSurface.h b/src/Mod/Part/Gui/DlgProjectionOnSurface.h index 1fe48eb177..e7011ed4e5 100644 --- a/src/Mod/Part/Gui/DlgProjectionOnSurface.h +++ b/src/Mod/Part/Gui/DlgProjectionOnSurface.h @@ -48,9 +48,7 @@ namespace Ui class DlgProjectionOnSurface; } -class DlgProjectionOnSurface: public QWidget, - public Gui::SelectionObserver, - public App::DocumentObserver +class DlgProjectionOnSurface: public QWidget, public Gui::SelectionObserver, public App::DocumentObserver { Q_OBJECT @@ -103,28 +101,33 @@ private: void get_camera_direction(); - void store_current_selected_parts(std::vector& iStoreVec, - unsigned int iColor); + void store_current_selected_parts(std::vector& iStoreVec, unsigned int iColor); bool store_part_in_vector(SShapeStore& iCurrentShape, std::vector& iStoreVec); void create_projection_wire(std::vector& iCurrentShape); TopoDS_Shape create_compound(const std::vector& iShapeVec); void show_projected_shapes(const std::vector& iShapeStoreVec); void disable_ui_elements(const std::vector& iObjectVec, QWidget* iExceptThis); void enable_ui_elements(const std::vector& iObjectVec, QWidget* iExceptThis); - void higlight_object(Part::Feature* iCurrentObject, - const std::string& iShapeName, - bool iHighlight, - unsigned int iColor); + void higlight_object( + Part::Feature* iCurrentObject, + const std::string& iShapeName, + bool iHighlight, + unsigned int iColor + ); void get_all_wire_from_face(SShapeStore& ioCurrentSahpe); void create_projection_face_from_wire(std::vector& iCurrentShape); TopoDS_Wire sort_and_heal_wire(const TopoDS_Shape& iShape, const TopoDS_Face& iFaceToProject); - TopoDS_Wire sort_and_heal_wire(const std::vector& iEdgeVec, - const TopoDS_Face& iFaceToProject); + TopoDS_Wire sort_and_heal_wire( + const std::vector& iEdgeVec, + const TopoDS_Face& iFaceToProject + ); void create_face_extrude(std::vector& iCurrentShape); - void store_wire_in_vector(const SShapeStore& iCurrentShape, - const TopoDS_Shape& iParentShape, - std::vector& iStoreVec, - unsigned int iColor); + void store_wire_in_vector( + const SShapeStore& iCurrentShape, + const TopoDS_Shape& iParentShape, + std::vector& iStoreVec, + unsigned int iColor + ); void set_xyz_dir_spinbox(QDoubleSpinBox* icurrentSpinBox); void transform_shape_to_global_position(TopoDS_Shape& ioShape, Part::Feature* iPart); @@ -177,8 +180,7 @@ private: // ------------------------------------------------------------------------------------------------ -class DlgProjectOnSurface : public QWidget, - public Gui::SelectionObserver +class DlgProjectOnSurface: public QWidget, public Gui::SelectionObserver { Q_OBJECT @@ -193,7 +195,8 @@ public: void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: - enum SelectionMode { + enum SelectionMode + { None, SupportFace, AddFace, diff --git a/src/Mod/Part/Gui/DlgRevolution.cpp b/src/Mod/Part/Gui/DlgRevolution.cpp index 4a3df63c65..81edf8904a 100644 --- a/src/Mod/Part/Gui/DlgRevolution.cpp +++ b/src/Mod/Part/Gui/DlgRevolution.cpp @@ -57,7 +57,7 @@ using namespace PartGui; -class DlgRevolution::EdgeSelection : public Gui::SelectionFilterGate +class DlgRevolution::EdgeSelection: public Gui::SelectionFilterGate { public: bool canSelect; @@ -67,16 +67,21 @@ public: { canSelect = false; } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override { this->canSelect = false; - if (Base::Tools::isNullOrEmpty(sSubName)) + if (Base::Tools::isNullOrEmpty(sSubName)) { return false; + } std::string element(sSubName); - if (element.substr(0,4) != "Edge") + if (element.substr(0, 4) != "Edge") { return false; - Part::TopoShape part = Part::Feature::getTopoShape(pObj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + } + Part::TopoShape part = Part::Feature::getTopoShape( + pObj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (part.isNull()) { return false; } @@ -99,9 +104,9 @@ public: }; DlgRevolution::DlgRevolution(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl) - , ui(new Ui_DlgRevolution) - , filter(nullptr) + : QDialog(parent, fl) + , ui(new Ui_DlgRevolution) + , filter(nullptr) { ui->setupUi(this); setupConnections(); @@ -164,41 +169,46 @@ void DlgRevolution::setupConnections() Base::Vector3d DlgRevolution::getDirection() const { return Base::Vector3d( - ui->xDir->value().getValue(), - ui->yDir->value().getValue(), - ui->zDir->value().getValue()); + ui->xDir->value().getValue(), + ui->yDir->value().getValue(), + ui->zDir->value().getValue() + ); } Base::Vector3d DlgRevolution::getPosition() const { return Base::Vector3d( - ui->xPos->value().getValueAs(Base::Quantity::MilliMetre), - ui->yPos->value().getValueAs(Base::Quantity::MilliMetre), - ui->zPos->value().getValueAs(Base::Quantity::MilliMetre)); + ui->xPos->value().getValueAs(Base::Quantity::MilliMetre), + ui->yPos->value().getValueAs(Base::Quantity::MilliMetre), + ui->zPos->value().getValueAs(Base::Quantity::MilliMetre) + ); } -void DlgRevolution::getAxisLink(App::PropertyLinkSub &lnk) const +void DlgRevolution::getAxisLink(App::PropertyLinkSub& lnk) const { QString text = ui->txtAxisLink->text(); if (text.length() == 0) { lnk.setValue(nullptr); - } else { + } + else { QStringList parts = text.split(QChar::fromLatin1(':')); - App::DocumentObject* obj = App::GetApplication().getActiveDocument()->getObject(parts[0].toLatin1()); - if(!obj){ + App::DocumentObject* obj = App::GetApplication().getActiveDocument()->getObject( + parts[0].toLatin1() + ); + if (!obj) { throw Base::ValueError(tr("Object not found: %1").arg(parts[0]).toUtf8().constData()); } lnk.setValue(obj); if (parts.size() == 1) { return; - } else if (parts.size() == 2) { + } + else if (parts.size() == 2) { std::vector subs; subs.emplace_back(parts[1].toLatin1().constData()); - lnk.setValue(obj,subs); + lnk.setValue(obj, subs); } } - } double DlgRevolution::getAngle() const @@ -222,42 +232,46 @@ void DlgRevolution::setPosition(Base::Vector3d pos) void DlgRevolution::setAxisLink(const App::PropertyLinkSub& lnk) { - if (!lnk.getValue()){ + if (!lnk.getValue()) { ui->txtAxisLink->clear(); return; } - if (lnk.getSubValues().size() == 1){ + if (lnk.getSubValues().size() == 1) { this->setAxisLink(lnk.getValue()->getNameInDocument(), lnk.getSubValues()[0].c_str()); - } else { + } + else { this->setAxisLink(lnk.getValue()->getNameInDocument(), ""); } } void DlgRevolution::setAxisLink(const char* objname, const char* subname) { - if(objname && strlen(objname) > 0){ + if (objname && strlen(objname) > 0) { QString txt = QString::fromLatin1(objname); - if (subname && strlen(subname) > 0){ + if (subname && strlen(subname) > 0) { txt = txt + QStringLiteral(":") + QString::fromLatin1(subname); } ui->txtAxisLink->setText(txt); - } else { + } + else { ui->txtAxisLink->clear(); } } std::vector DlgRevolution::getShapesToRevolve() const { - QList items = ui->treeWidget->selectedItems(); + QList items = ui->treeWidget->selectedItems(); App::Document* doc = App::GetApplication().getActiveDocument(); - if (!doc) + if (!doc) { throw Base::RuntimeError("Document lost"); + } std::vector objects; for (auto item : items) { App::DocumentObject* obj = doc->getObject(item->data(0, Qt::UserRole).toString().toLatin1()); - if (!obj) + if (!obj) { throw Base::RuntimeError("Object not found"); + } objects.push_back(obj); } return objects; @@ -265,55 +279,74 @@ std::vector DlgRevolution::getShapesToRevolve() const bool DlgRevolution::validate() { - //check source shapes + // check source shapes if (ui->treeWidget->selectedItems().isEmpty()) { - QMessageBox::critical(this, windowTitle(), - tr("Select a shape for revolution.")); + QMessageBox::critical(this, windowTitle(), tr("Select a shape for revolution.")); return false; } - //check axis link + // check axis link bool axisLinkIsValid = false; bool axisLinkHasAngle = false; - try{ + try { App::PropertyLinkSub lnk; this->getAxisLink(lnk); double angle_edge = 1e100; Base::Vector3d axis, center; axisLinkIsValid = Part::Revolution::fetchAxisLink(lnk, center, axis, angle_edge); axisLinkHasAngle = angle_edge != 1e100; - } catch(Base::Exception &err) { - QMessageBox::critical(this, windowTitle(), - tr("Revolution axis link is invalid.\n\n%1").arg(QCoreApplication::translate("Exception", err.what()))); + } + catch (Base::Exception& err) { + QMessageBox::critical( + this, + windowTitle(), + tr("Revolution axis link is invalid.\n\n%1") + .arg(QCoreApplication::translate("Exception", err.what())) + ); ui->txtAxisLink->setFocus(); return false; - } catch(Standard_Failure &err) { - QMessageBox::critical(this, windowTitle(), - tr("Revolution axis link is invalid.\n\n%1").arg(QString::fromLocal8Bit(err.GetMessageString()))); + } + catch (Standard_Failure& err) { + QMessageBox::critical( + this, + windowTitle(), + tr("Revolution axis link is invalid.\n\n%1") + .arg(QString::fromLocal8Bit(err.GetMessageString())) + ); ui->txtAxisLink->setFocus(); return false; - } catch(...) { - QMessageBox::critical(this, windowTitle(), - tr("Revolution axis link is invalid.\n\n%1").arg(tr("Unknown error"))); + } + catch (...) { + QMessageBox::critical( + this, + windowTitle(), + tr("Revolution axis link is invalid.\n\n%1").arg(tr("Unknown error")) + ); ui->txtAxisLink->setFocus(); return false; } - //check axis dir - if (!axisLinkIsValid){ - if(this->getDirection().Length() < Precision::Confusion()){ - QMessageBox::critical(this, windowTitle(), - tr("Revolution axis direction is zero-length. It must be non-zero.")); + // check axis dir + if (!axisLinkIsValid) { + if (this->getDirection().Length() < Precision::Confusion()) { + QMessageBox::critical( + this, + windowTitle(), + tr("Revolution axis direction is zero-length. It must be non-zero.") + ); ui->xDir->setFocus(); return false; } } - //check angle - if (!axisLinkHasAngle){ + // check angle + if (!axisLinkHasAngle) { if (fabs(Base::toRadians(this->getAngle())) < Precision::Angular()) { - QMessageBox::critical(this, windowTitle(), - tr("Revolution angle span is zero. It must be non-zero.")); + QMessageBox::critical( + this, + windowTitle(), + tr("Revolution angle span is zero. It must be non-zero.") + ); ui->angle->setFocus(); return false; } @@ -322,7 +355,7 @@ bool DlgRevolution::validate() return true; } -void DlgRevolution::changeEvent(QEvent *e) +void DlgRevolution::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -342,68 +375,90 @@ void DlgRevolution::keyPressEvent(QKeyEvent* ke) void DlgRevolution::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); std::vector objs = activeDoc->getObjectsOfType(); for (auto obj : objs) { - Part::TopoShape topoShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { continue; } TopoDS_Shape shape = topoShape.getShape(); - if (shape.IsNull()) continue; + if (shape.IsNull()) { + continue; + } TopExp_Explorer xp; - xp.Init(shape,TopAbs_SOLID); - if (xp.More()) continue; // solids not allowed - xp.Init(shape,TopAbs_COMPSOLID); - if (xp.More()) continue; // compound solids not allowed + xp.Init(shape, TopAbs_SOLID); + if (xp.More()) { + continue; // solids not allowed + } + xp.Init(shape, TopAbs_COMPSOLID); + if (xp.More()) { + continue; // compound solids not allowed + } // So allowed are: vertex, edge, wire, face, shell and compound QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeWidget); item->setText(0, QString::fromUtf8(obj->Label.getValue())); item->setData(0, Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) item->setIcon(0, vp->getIcon()); + if (vp) { + item->setIcon(0, vp->getIcon()); + } } } void DlgRevolution::accept() { - if (!this->validate()) + if (!this->validate()) { return; + } Gui::WaitCursor wc; App::Document* activeDoc = App::GetApplication().getActiveDocument(); activeDoc->openTransaction("Revolve"); - try{ + try { QString shape, type, name, solid; - QList items = ui->treeWidget->selectedItems(); + QList items = ui->treeWidget->selectedItems(); if (ui->checkSolid->isChecked()) { - solid = QStringLiteral("True");} + solid = QStringLiteral("True"); + } else { - solid = QStringLiteral("False");} + solid = QStringLiteral("False"); + } App::PropertyLinkSub axisLink; this->getAxisLink(axisLink); QString strAxisLink; - if (axisLink.getValue()){ + if (axisLink.getValue()) { strAxisLink = QStringLiteral("(App.ActiveDocument.%1, %2)") - .arg(QString::fromLatin1(axisLink.getValue()->getNameInDocument()), - axisLink.getSubValues().size() == 1 ? - QStringLiteral("\"%1\"").arg(QString::fromLatin1(axisLink.getSubValues()[0].c_str())) - : QString() ); - } else { + .arg( + QString::fromLatin1(axisLink.getValue()->getNameInDocument()), + axisLink.getSubValues().size() == 1 + ? QStringLiteral("\"%1\"").arg( + QString::fromLatin1(axisLink.getSubValues()[0].c_str()) + ) + : QString() + ); + } + else { strAxisLink = QStringLiteral("None"); } QString symmetric; if (ui->checkSymmetric->isChecked()) { - symmetric = QStringLiteral("True");} + symmetric = QStringLiteral("True"); + } else { - symmetric = QStringLiteral("False");} + symmetric = QStringLiteral("False"); + } for (auto item : items) { shape = item->data(0, Qt::UserRole).toString(); @@ -414,26 +469,29 @@ void DlgRevolution::accept() QString code = QStringLiteral( - "FreeCAD.ActiveDocument.addObject(\"%1\",\"%2\")\n" - "FreeCAD.ActiveDocument.%2.Source = FreeCAD.ActiveDocument.%3\n" - "FreeCAD.ActiveDocument.%2.Axis = (%4,%5,%6)\n" - "FreeCAD.ActiveDocument.%2.Base = (%7,%8,%9)\n" - "FreeCAD.ActiveDocument.%2.Angle = %10\n" - "FreeCAD.ActiveDocument.%2.Solid = %11\n" - "FreeCAD.ActiveDocument.%2.AxisLink = %12\n" - "FreeCAD.ActiveDocument.%2.Symmetric = %13\n" - "FreeCADGui.ActiveDocument.%3.Visibility = False\n") - .arg(type, name, shape) //%1, 2, 3 - .arg(axis.x,0,'f',15) //%4 - .arg(axis.y,0,'f',15) //%5 - .arg(axis.z,0,'f',15) //%6 - .arg(pos.x, 0,'f',15) //%7 - .arg(pos.y, 0,'f',15) //%8 - .arg(pos.z, 0,'f',15) //%9 - .arg(getAngle(),0,'f',15) //%10 - .arg(solid, //%11 - strAxisLink, //%12 - symmetric) //%13 + "FreeCAD.ActiveDocument.addObject(\"%1\",\"%2\")\n" + "FreeCAD.ActiveDocument.%2.Source = FreeCAD.ActiveDocument.%3\n" + "FreeCAD.ActiveDocument.%2.Axis = (%4,%5,%6)\n" + "FreeCAD.ActiveDocument.%2.Base = (%7,%8,%9)\n" + "FreeCAD.ActiveDocument.%2.Angle = %10\n" + "FreeCAD.ActiveDocument.%2.Solid = %11\n" + "FreeCAD.ActiveDocument.%2.AxisLink = %12\n" + "FreeCAD.ActiveDocument.%2.Symmetric = %13\n" + "FreeCADGui.ActiveDocument.%3.Visibility = False\n" + ) + .arg(type, name, shape) //%1, 2, 3 + .arg(axis.x, 0, 'f', 15) //%4 + .arg(axis.y, 0, 'f', 15) //%5 + .arg(axis.z, 0, 'f', 15) //%6 + .arg(pos.x, 0, 'f', 15) //%7 + .arg(pos.y, 0, 'f', 15) //%8 + .arg(pos.z, 0, 'f', 15) //%9 + .arg(getAngle(), 0, 'f', 15) //%10 + .arg( + solid, //%11 + strAxisLink, //%12 + symmetric + ) //%13 ; Gui::Command::runCommand(Gui::Command::App, code.toLatin1()); @@ -449,13 +507,21 @@ void DlgRevolution::accept() activeDoc->commitTransaction(); activeDoc->recompute(); - } catch (Base::Exception &err) { - QMessageBox::critical(this, windowTitle(), - tr("Creating Revolve failed.\n\n%1").arg(QCoreApplication::translate("Exception", err.what()))); + } + catch (Base::Exception& err) { + QMessageBox::critical( + this, + windowTitle(), + tr("Creating Revolve failed.\n\n%1").arg(QCoreApplication::translate("Exception", err.what())) + ); return; - } catch (...){ - QMessageBox::critical(this, windowTitle(), - tr("Creating Revolve failed.\n\n%1").arg(QStringLiteral("Unknown error"))); + } + catch (...) { + QMessageBox::critical( + this, + windowTitle(), + tr("Creating Revolve failed.\n\n%1").arg(QStringLiteral("Unknown error")) + ); return; } @@ -468,7 +534,8 @@ void DlgRevolution::onSelectLineClicked() filter = new EdgeSelection(); Gui::Selection().addSelectionGate(filter); ui->selectLine->setText(tr("Selecting… (line or arc)")); - } else { + } + else { Gui::Selection().rmvSelectionGate(); filter = nullptr; ui->selectLine->setText(tr("Select reference")); @@ -477,47 +544,52 @@ void DlgRevolution::onSelectLineClicked() void DlgRevolution::onButtonXClicked() { - setDirection(Base::Vector3d(1,0,0)); - if (!ui->xDir->isEnabled()) + setDirection(Base::Vector3d(1, 0, 0)); + if (!ui->xDir->isEnabled()) { ui->txtAxisLink->clear(); + } } void DlgRevolution::onButtonYClicked() { - setDirection(Base::Vector3d(0,1,0)); - if (!ui->xDir->isEnabled()) + setDirection(Base::Vector3d(0, 1, 0)); + if (!ui->xDir->isEnabled()) { ui->txtAxisLink->clear(); + } } void DlgRevolution::onButtonZClicked() { - setDirection(Base::Vector3d(0,0,1)); - if (!ui->xDir->isEnabled()) + setDirection(Base::Vector3d(0, 0, 1)); + if (!ui->xDir->isEnabled()) { ui->txtAxisLink->clear(); + } } void DlgRevolution::onAxisLinkTextChanged(QString) { bool en = true; - try{ + try { Base::Vector3d pos, dir; double angle_edge = 1e100; - App::PropertyLinkSub lnk; this->getAxisLink(lnk); + App::PropertyLinkSub lnk; + this->getAxisLink(lnk); bool fetched = Part::Revolution::fetchAxisLink(lnk, pos, dir, angle_edge); - if (fetched){ + if (fetched) { this->setDirection(dir); this->setPosition(pos); - if (angle_edge != 1e100){ + if (angle_edge != 1e100) { ui->angle->setValue(0.0); - } else if (fabs(ui->angle->value().getValue()) < 1e-12) { + } + else if (fabs(ui->angle->value().getValue()) < 1e-12) { ui->angle->setValue(360.0); } en = false; } - } catch (Base::Exception &){ - - } catch (...){ - + } + catch (Base::Exception&) { + } + catch (...) { } ui->xDir->setEnabled(en); ui->yDir->setEnabled(en); @@ -536,44 +608,51 @@ void DlgRevolution::onSelectionChanged(const Gui::SelectionChanges& msg) } } -App::DocumentObject&DlgRevolution::getShapeToRevolve() const +App::DocumentObject& DlgRevolution::getShapeToRevolve() const { std::vector objs = this->getShapesToRevolve(); - if (objs.empty()) + if (objs.empty()) { throw Base::ValueError("No shapes selected"); + } return *(objs[0]); } void DlgRevolution::autoSolid() { - try{ - App::DocumentObject &dobj = this->getShapeToRevolve(); - Part::TopoShape topoShape = Part::Feature::getTopoShape(&dobj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + try { + App::DocumentObject& dobj = this->getShapeToRevolve(); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + &dobj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { return; - } else { + } + else { TopoDS_Shape sh = topoShape.getShape(); - if (sh.IsNull()) + if (sh.IsNull()) { return; + } ShapeExtend_Explorer xp; - Handle(TopTools_HSequenceOfShape) leaves = xp.SeqFromCompound(sh, /*recursive= */Standard_True); + Handle(TopTools_HSequenceOfShape) leaves + = xp.SeqFromCompound(sh, /*recursive= */ Standard_True); int cntClosedWires = 0; for (int i = 0; i < leaves->Length(); i++) { - const TopoDS_Shape &leaf = leaves->Value(i+1); - if (leaf.IsNull()) + const TopoDS_Shape& leaf = leaves->Value(i + 1); + if (leaf.IsNull()) { return; - if (leaf.ShapeType() == TopAbs_WIRE || leaf.ShapeType() == TopAbs_EDGE){ - if (BRep_Tool::IsClosed(leaf)){ + } + if (leaf.ShapeType() == TopAbs_WIRE || leaf.ShapeType() == TopAbs_EDGE) { + if (BRep_Tool::IsClosed(leaf)) { cntClosedWires++; } } } - ui->checkSolid->setChecked( cntClosedWires == leaves->Length() ); + ui->checkSolid->setChecked(cntClosedWires == leaves->Length()); } - } catch(...){ - } - + catch (...) { + } } // --------------------------------------- @@ -591,4 +670,3 @@ bool TaskRevolution::accept() } #include "moc_DlgRevolution.cpp" - diff --git a/src/Mod/Part/Gui/DlgRevolution.h b/src/Mod/Part/Gui/DlgRevolution.h index 062db3717b..1e3a7ece44 100644 --- a/src/Mod/Part/Gui/DlgRevolution.h +++ b/src/Mod/Part/Gui/DlgRevolution.h @@ -31,10 +31,11 @@ #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgRevolution; -class DlgRevolution : public QDialog, public Gui::SelectionObserver +class DlgRevolution: public QDialog, public Gui::SelectionObserver { Q_OBJECT @@ -45,12 +46,12 @@ public: Base::Vector3d getDirection() const; Base::Vector3d getPosition() const; - void getAxisLink(App::PropertyLinkSub &lnk) const; + void getAxisLink(App::PropertyLinkSub& lnk) const; double getAngle() const; void setDirection(Base::Vector3d dir); void setPosition(Base::Vector3d dir); - void setAxisLink(const App::PropertyLinkSub &lnk); + void setAxisLink(const App::PropertyLinkSub& lnk); void setAxisLink(const char* objname, const char* subname); std::vector getShapesToRevolve() const; @@ -58,7 +59,7 @@ public: bool validate(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void keyPressEvent(QKeyEvent*) override; private: @@ -73,10 +74,10 @@ private: void findShapes(); void onSelectionChanged(const Gui::SelectionChanges& msg) override; - ///returns link to any of selected source shapes. Throws if nothing is selected for extrusion. + /// returns link to any of selected source shapes. Throws if nothing is selected for extrusion. App::DocumentObject& getShapeToRevolve() const; - ///automatically checks Solid checkbox depending on input shape + /// automatically checks Solid checkbox depending on input shape void autoSolid(); private: @@ -85,7 +86,7 @@ private: EdgeSelection* filter; }; -class TaskRevolution : public Gui::TaskView::TaskDialog +class TaskRevolution: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -96,12 +97,14 @@ public: bool accept() override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } private: DlgRevolution* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGREVOLUTION_H +#endif // PARTGUI_DLGREVOLUTION_H diff --git a/src/Mod/Part/Gui/DlgScale.cpp b/src/Mod/Part/Gui/DlgScale.cpp index 8327af7ac3..b695177d69 100644 --- a/src/Mod/Part/Gui/DlgScale.cpp +++ b/src/Mod/Part/Gui/DlgScale.cpp @@ -22,15 +22,15 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -53,12 +53,13 @@ #include "DlgScale.h" -FC_LOG_LEVEL_INIT("Part",true,true) +FC_LOG_LEVEL_INIT("Part", true, true) using namespace PartGui; DlgScale::DlgScale(QWidget* parent, Qt::WindowFlags fl) - : QDialog(parent, fl), ui(new Ui_DlgScale) + : QDialog(parent, fl) + , ui(new Ui_DlgScale) { ui->setupUi(this); setupConnections(); @@ -78,11 +79,10 @@ DlgScale::DlgScale(QWidget* parent, Qt::WindowFlags fl) void DlgScale::setupConnections() { - connect(ui->rbUniform, &QRadioButton::toggled, - this, &DlgScale::onUniformScaleToggled); + connect(ui->rbUniform, &QRadioButton::toggled, this, &DlgScale::onUniformScaleToggled); } -void DlgScale::changeEvent(QEvent *e) +void DlgScale::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -92,14 +92,15 @@ void DlgScale::changeEvent(QEvent *e) void DlgScale::onUniformScaleToggled(bool state) { -// Base::Console().message("DS::onUniformScaleToggled()\n"); + // Base::Console().message("DS::onUniformScaleToggled()\n"); if (state) { // this is uniform scaling, so hide the non-uniform input fields ui->dsbUniformScale->setEnabled(true); ui->dsbXScale->setEnabled(false); ui->dsbYScale->setEnabled(false); ui->dsbZScale->setEnabled(false); - } else { + } + else { // this is non-uniform scaling, so hide the uniform input fields ui->dsbUniformScale->setEnabled(false); ui->dsbXScale->setEnabled(true); @@ -112,10 +113,11 @@ void DlgScale::onUniformScaleToggled(bool state) //! list widget void DlgScale::findShapes() { -// Base::Console().message("DS::findShapes()\n"); + // Base::Console().message("DS::findShapes()\n"); App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); m_document = activeDoc->getName(); m_label = activeDoc->Label.getValue(); @@ -123,19 +125,25 @@ void DlgScale::findShapes() std::vector objs = activeDoc->getObjectsOfType(); for (auto obj : objs) { - Part::TopoShape topoShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { continue; } TopoDS_Shape shape = topoShape.getShape(); - if (shape.IsNull()) continue; + if (shape.IsNull()) { + continue; + } if (canScale(shape)) { QTreeWidgetItem* item = new QTreeWidgetItem(ui->treeWidget); item->setText(0, QString::fromUtf8(obj->Label.getValue())); item->setData(0, Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) + if (vp) { item->setIcon(0, vp->getIcon()); + } } } } @@ -153,11 +161,10 @@ bool DlgScale::canScale(const TopoDS_Shape& shape) const return false; } - if (type == TopAbs_COMPOUND || - type == TopAbs_COMPSOLID) { + if (type == TopAbs_COMPOUND || type == TopAbs_COMPSOLID) { TopExp_Explorer xp; xp.Init(shape, TopAbs_EDGE); - for ( ; xp.More() ; xp.Next()) { + for (; xp.More(); xp.Next()) { // there is at least 1 edge inside the compound, so as long as it isn't null, // we can scale this shape. We can stop looking as soon as we find a non-null // edge. @@ -168,7 +175,8 @@ bool DlgScale::canScale(const TopoDS_Shape& shape) const } // did not find a non-null shape return false; - } else { + } + else { // not a Vertex, Compound or CompSolid, must be one of Edge, Wire, Face, Shell or // Solid, all of which we can scale. return true; @@ -179,11 +187,12 @@ bool DlgScale::canScale(const TopoDS_Shape& shape) const void DlgScale::accept() { -// Base::Console().message("DS::accept()\n"); - try{ + // Base::Console().message("DS::accept()\n"); + try { apply(); QDialog::accept(); - } catch (Base::AbortException&){ + } + catch (Base::AbortException&) { Base::Console().message("DS::accept - apply failed!\n"); }; } @@ -191,46 +200,57 @@ void DlgScale::accept() // create a FeatureScale for each scalable object void DlgScale::apply() { -// Base::Console().message("DS::apply()\n"); - try{ + // Base::Console().message("DS::apply()\n"); + try { if (!validate()) { - QMessageBox::critical(this, windowTitle(), - tr("No scalable shapes selected")); + QMessageBox::critical(this, windowTitle(), tr("No scalable shapes selected")); return; } Gui::WaitCursor wc; App::Document* activeDoc = App::GetApplication().getDocument(m_document.c_str()); if (!activeDoc) { - QMessageBox::critical(this, windowTitle(), - tr("The document '%1' doesn't exist.").arg(QString::fromUtf8(m_label.c_str()))); + QMessageBox::critical( + this, + windowTitle(), + tr("The document '%1' doesn't exist.").arg(QString::fromUtf8(m_label.c_str())) + ); return; } activeDoc->openTransaction("Scale"); - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/Part"); bool addBaseName = hGrp->GetBool("AddBaseObjectName", false); std::vector objects = this->getShapesToScale(); - for (App::DocumentObject* sourceObj: objects) { + for (App::DocumentObject* sourceObj : objects) { assert(sourceObj); - if (Part::Feature::getTopoShape(sourceObj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform).isNull()){ - FC_ERR("Object " << sourceObj->getFullName() - << " is not a shape object. Scaling is not possible."); + if (Part::Feature::getTopoShape( + sourceObj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ) + .isNull()) { + FC_ERR( + "Object " << sourceObj->getFullName() + << " is not a shape object. Scaling is not possible." + ); continue; } std::string name; name = sourceObj->getDocument()->getUniqueObjectName("Scale").c_str(); if (addBaseName) { - //FIXME: implement - //QString baseName = QStringLiteral("Scale_%1").arg(sourceObjectName); - //label = QStringLiteral("%1_Scale").arg((*it)->text(0)); + // FIXME: implement + // QString baseName = QStringLiteral("Scale_%1").arg(sourceObjectName); + // label = QStringLiteral("%1_Scale").arg((*it)->text(0)); } - FCMD_OBJ_DOC_CMD(sourceObj,"addObject('Part::Scale','" << name << "')"); + FCMD_OBJ_DOC_CMD(sourceObj, "addObject('Part::Scale','" << name << "')"); auto newObj = sourceObj->getDocument()->getObject(name.c_str()); this->writeParametersToFeature(*newObj, sourceObj); @@ -245,19 +265,23 @@ void DlgScale::apply() activeDoc->commitTransaction(); Gui::Command::updateActive(); } - catch (Base::AbortException&){ + catch (Base::AbortException&) { throw; } - catch (Base::Exception &err){ - QMessageBox::critical(this, - windowTitle(), - tr("Creating scale failed.\n%1") - .arg(QCoreApplication::translate("Exception", err.what()))); + catch (Base::Exception& err) { + QMessageBox::critical( + this, + windowTitle(), + tr("Creating scale failed.\n%1").arg(QCoreApplication::translate("Exception", err.what())) + ); return; } - catch(...) { - QMessageBox::critical(this, windowTitle(), - tr("Creating scale failed.\n%1").arg(QStringLiteral("Unknown error"))); + catch (...) { + QMessageBox::critical( + this, + windowTitle(), + tr("Creating scale failed.\n%1").arg(QStringLiteral("Unknown error")) + ); return; } } @@ -271,17 +295,19 @@ void DlgScale::reject() //! widget std::vector DlgScale::getShapesToScale() const { -// Base::Console().message("DS::getShapesToScale()\n"); - QList items = ui->treeWidget->selectedItems(); + // Base::Console().message("DS::getShapesToScale()\n"); + QList items = ui->treeWidget->selectedItems(); App::Document* doc = App::GetApplication().getDocument(m_document.c_str()); - if (!doc) + if (!doc) { throw Base::RuntimeError("Document lost"); + } std::vector objects; for (auto item : items) { App::DocumentObject* obj = doc->getObject(item->data(0, Qt::UserRole).toString().toLatin1()); - if (!obj) + if (!obj) { throw Base::RuntimeError("Object not found"); + } objects.push_back(obj); } return objects; @@ -291,38 +317,54 @@ std::vector DlgScale::getShapesToScale() const //! available document object in the document bool DlgScale::validate() { - QList items = ui->treeWidget->selectedItems(); + QList items = ui->treeWidget->selectedItems(); App::Document* doc = App::GetApplication().getDocument(m_document.c_str()); - if (!doc) + if (!doc) { throw Base::RuntimeError("Document lost"); + } std::vector objects; for (auto item : items) { App::DocumentObject* obj = doc->getObject(item->data(0, Qt::UserRole).toString().toLatin1()); - if (!obj) + if (!obj) { throw Base::RuntimeError("Object not found"); + } objects.push_back(obj); } return !objects.empty(); } //! update a FeatureScale with the parameters from the UI -void DlgScale::writeParametersToFeature(App::DocumentObject &feature, App::DocumentObject* base) const +void DlgScale::writeParametersToFeature(App::DocumentObject& feature, App::DocumentObject* base) const { -// Base::Console().message("DS::writeParametersToFeature()\n"); - Gui::Command::doCommand(Gui::Command::Doc,"f = App.getDocument('%s').getObject('%s')", feature.getDocument()->getName(), feature.getNameInDocument()); + // Base::Console().message("DS::writeParametersToFeature()\n"); + Gui::Command::doCommand( + Gui::Command::Doc, + "f = App.getDocument('%s').getObject('%s')", + feature.getDocument()->getName(), + feature.getNameInDocument() + ); if (!base) { return; } - Gui::Command::doCommand(Gui::Command::Doc,"f.Base = App.getDocument('%s').getObject('%s')", base->getDocument()->getName(), base->getNameInDocument()); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Base = App.getDocument('%s').getObject('%s')", + base->getDocument()->getName(), + base->getNameInDocument() + ); - Gui::Command::doCommand(Gui::Command::Doc,"f.Uniform = %s", ui->rbUniform->isChecked() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc,"f.UniformScale = %.7f", ui->dsbUniformScale->value()); - Gui::Command::doCommand(Gui::Command::Doc,"f.XScale = %.7f", ui->dsbXScale->value()); - Gui::Command::doCommand(Gui::Command::Doc,"f.YScale = %.7f", ui->dsbYScale->value()); - Gui::Command::doCommand(Gui::Command::Doc,"f.ZScale = %.7f", ui->dsbZScale->value()); + Gui::Command::doCommand( + Gui::Command::Doc, + "f.Uniform = %s", + ui->rbUniform->isChecked() ? "True" : "False" + ); + Gui::Command::doCommand(Gui::Command::Doc, "f.UniformScale = %.7f", ui->dsbUniformScale->value()); + Gui::Command::doCommand(Gui::Command::Doc, "f.XScale = %.7f", ui->dsbXScale->value()); + Gui::Command::doCommand(Gui::Command::Doc, "f.YScale = %.7f", ui->dsbYScale->value()); + Gui::Command::doCommand(Gui::Command::Doc, "f.ZScale = %.7f", ui->dsbZScale->value()); } // --------------------------------------- @@ -348,10 +390,10 @@ bool TaskScale::reject() void TaskScale::clicked(int id) { if (id == QDialogButtonBox::Apply) { - try{ + try { widget->apply(); - } catch (Base::AbortException&){ - + } + catch (Base::AbortException&) { }; } } diff --git a/src/Mod/Part/Gui/DlgScale.h b/src/Mod/Part/Gui/DlgScale.h index 6db3b36196..b66370d952 100644 --- a/src/Mod/Part/Gui/DlgScale.h +++ b/src/Mod/Part/Gui/DlgScale.h @@ -34,10 +34,11 @@ class TopoDS_Shape; -namespace PartGui { +namespace PartGui +{ class Ui_DlgScale; -class DlgScale : public QDialog +class DlgScale: public QDialog { Q_OBJECT @@ -57,21 +58,21 @@ public: protected: void findShapes(); bool canScale(const TopoDS_Shape&) const; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void setupConnections(); void onUniformScaleToggled(bool on); private: - ///returns link to any of selected source shapes. Throws if nothing is selected for scaling. + /// returns link to any of selected source shapes. Throws if nothing is selected for scaling. App::DocumentObject& getShapeToScale() const; std::unique_ptr ui; std::string m_document, m_label; }; -class TaskScale : public Gui::TaskView::TaskDialog +class TaskScale: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -84,12 +85,14 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Close; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Close; + } private: DlgScale* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DLGSCALE_H +#endif // PARTGUI_DLGSCALE_H diff --git a/src/Mod/Part/Gui/DlgSettings3DViewPartImp.cpp b/src/Mod/Part/Gui/DlgSettings3DViewPartImp.cpp index 45294c4704..bb432f1b9d 100644 --- a/src/Mod/Part/Gui/DlgSettings3DViewPartImp.cpp +++ b/src/Mod/Part/Gui/DlgSettings3DViewPartImp.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -47,21 +47,26 @@ DlgSettings3DViewPart::DlgSettings3DViewPart(QWidget* parent) , checkValue(false) { ui->setupUi(this); - connect(ui->maxDeviation, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &DlgSettings3DViewPart::onMaxDeviationValueChanged); - connect(ui->maxAngularDeflection, - qOverload(&QDoubleSpinBox::valueChanged), - this, - &DlgSettings3DViewPart::onMaxAngularDeflectionValueChanged); + connect( + ui->maxDeviation, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &DlgSettings3DViewPart::onMaxDeviationValueChanged + ); + connect( + ui->maxAngularDeflection, + qOverload(&QDoubleSpinBox::valueChanged), + this, + &DlgSettings3DViewPart::onMaxAngularDeflectionValueChanged + ); ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Part"); - const double minDeviationlowerLimit = hPart->GetFloat( - "MinimumDeviation", ui->maxDeviation->minimum()); + "User parameter:BaseApp/Preferences/Mod/Part" + ); + const double minDeviationlowerLimit + = hPart->GetFloat("MinimumDeviation", ui->maxDeviation->minimum()); ui->maxDeviation->setMinimum(minDeviationlowerLimit); - const double minAngleDeflectionlowerLimit = hPart->GetFloat( - "MinimumDeviation", ui->maxAngularDeflection->minimum()); + const double minAngleDeflectionlowerLimit + = hPart->GetFloat("MinimumDeviation", ui->maxAngularDeflection->minimum()); ui->maxAngularDeflection->setMinimum(minAngleDeflectionlowerLimit); } @@ -82,7 +87,8 @@ void DlgSettings3DViewPart::onMaxDeviationValueChanged(double vMaxDev) this, tr("Deviation"), tr("Setting a too small deviation causes the tessellation to take longer" - " and thus freezes or slows down the GUI.")); + " and thus freezes or slows down the GUI.") + ); } } @@ -103,7 +109,8 @@ void DlgSettings3DViewPart::onMaxAngularDeflectionValueChanged(double vMaxAngle) this, tr("Angle deflection"), tr("Setting a too small angle deviation causes the tessellation to take longer" - " and thus freezes or slows down the GUI.")); + " and thus freezes or slows down the GUI.") + ); } } @@ -116,8 +123,9 @@ void DlgSettings3DViewPart::saveSettings() std::vector docs = App::GetApplication().getDocuments(); for (auto it : docs) { Gui::Document* doc = Gui::Application::Instance->getDocument(it); - std::vector views = - doc->getViewProvidersOfType(ViewProviderPart::getClassTypeId()); + std::vector views = doc->getViewProvidersOfType( + ViewProviderPart::getClassTypeId() + ); for (auto view : views) { static_cast(view)->reload(); } @@ -132,7 +140,7 @@ void DlgSettings3DViewPart::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void DlgSettings3DViewPart::changeEvent(QEvent *e) +void DlgSettings3DViewPart::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); diff --git a/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h b/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h index 846bc99f53..0719b2009b 100644 --- a/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h +++ b/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h @@ -29,14 +29,15 @@ #include #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgSettings3DViewPart; /** * The DlgSettings3DViewPartImp class implements a preference page to change settings * for the Inventor viewer. * \author Jürgen Riegel */ -class DlgSettings3DViewPart : public Gui::Dialog::PreferencePage +class DlgSettings3DViewPart: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -47,7 +48,7 @@ public: protected: void saveSettings() override; void loadSettings() override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void onMaxDeviationValueChanged(double); @@ -58,6 +59,6 @@ private: bool checkValue; }; -} // namespace Gui +} // namespace PartGui -#endif // PARTGUI_DLGSETTINGS3DVIEWIMP_H +#endif // PARTGUI_DLGSETTINGS3DVIEWIMP_H diff --git a/src/Mod/Part/Gui/DlgSettingsGeneral.cpp b/src/Mod/Part/Gui/DlgSettingsGeneral.cpp index 87632afa8b..38f5f5aecd 100644 --- a/src/Mod/Part/Gui/DlgSettingsGeneral.cpp +++ b/src/Mod/Part/Gui/DlgSettingsGeneral.cpp @@ -22,11 +22,11 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -45,7 +45,8 @@ using namespace PartGui; DlgSettingsGeneral::DlgSettingsGeneral(QWidget* parent) - : PreferencePage(parent), ui(new Ui_DlgSettingsGeneral) + : PreferencePage(parent) + , ui(new Ui_DlgSettingsGeneral) { ui->setupUi(this); } @@ -90,7 +91,7 @@ void DlgSettingsGeneral::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void DlgSettingsGeneral::changeEvent(QEvent *e) +void DlgSettingsGeneral::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -103,7 +104,8 @@ void DlgSettingsGeneral::changeEvent(QEvent *e) // ---------------------------------------------------------------------------- DlgImportExportIges::DlgImportExportIges(QWidget* parent) - : PreferencePage(parent), ui(new Ui_DlgImportExportIges) + : PreferencePage(parent) + , ui(new Ui_DlgImportExportIges) { ui->setupUi(this); ui->lineEditProduct->setReadOnly(true); @@ -114,7 +116,9 @@ DlgImportExportIges::DlgImportExportIges(QWidget* parent) QRegularExpression rx; rx.setPattern(QStringLiteral("[\\x00-\\x7F]+")); - QRegularExpressionValidator* companyValidator = new QRegularExpressionValidator(ui->lineEditCompany); + QRegularExpressionValidator* companyValidator = new QRegularExpressionValidator( + ui->lineEditCompany + ); companyValidator->setRegularExpression(rx); ui->lineEditCompany->setValidator(companyValidator); QRegularExpressionValidator* authorValidator = new QRegularExpressionValidator(ui->lineEditAuthor); @@ -150,10 +154,12 @@ void DlgImportExportIges::loadSettings() ui->comboBoxUnits->setCurrentIndex(static_cast(settings.getUnit())); bool brep = settings.getBRepMode(); - if (brep) + if (brep) { ui->radioButtonBRepOn->setChecked(true); - else + } + else { ui->radioButtonBRepOff->setChecked(true); + } // Import ui->checkSkipBlank->setChecked(settings.getSkipBlankEntities()); @@ -167,7 +173,7 @@ void DlgImportExportIges::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void DlgImportExportIges::changeEvent(QEvent *e) +void DlgImportExportIges::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -180,10 +186,10 @@ void DlgImportExportIges::changeEvent(QEvent *e) // ---------------------------------------------------------------------------- DlgImportExportStep::DlgImportExportStep(QWidget* parent) - : PreferencePage(parent) - , exportStep(new DlgExportStep(this)) - , importStep(new DlgImportStep(this)) - , headerStep(new DlgExportHeaderStep(this)) + : PreferencePage(parent) + , exportStep(new DlgExportStep(this)) + , importStep(new DlgImportStep(this)) + , headerStep(new DlgExportHeaderStep(this)) { setWindowTitle(QLatin1String("STEP")); QVBoxLayout* layout = new QVBoxLayout(this); @@ -218,7 +224,7 @@ void DlgImportExportStep::loadSettings() headerStep->loadSettings(); } -void DlgImportExportStep::changeEvent(QEvent *) +void DlgImportExportStep::changeEvent(QEvent*) { // do nothing } diff --git a/src/Mod/Part/Gui/DlgSettingsGeneral.h b/src/Mod/Part/Gui/DlgSettingsGeneral.h index a1a09edd28..8216b9fe07 100644 --- a/src/Mod/Part/Gui/DlgSettingsGeneral.h +++ b/src/Mod/Part/Gui/DlgSettingsGeneral.h @@ -30,10 +30,11 @@ class QButtonGroup; -namespace PartGui { +namespace PartGui +{ class Ui_DlgSettingsGeneral; -class DlgSettingsGeneral : public Gui::Dialog::PreferencePage +class DlgSettingsGeneral: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -44,14 +45,14 @@ public: protected: void saveSettings() override; void loadSettings() override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; }; class Ui_DlgImportExportIges; -class DlgImportExportIges : public Gui::Dialog::PreferencePage +class DlgImportExportIges: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -62,7 +63,7 @@ public: protected: void saveSettings() override; void loadSettings() override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: std::unique_ptr ui; @@ -72,7 +73,7 @@ private: class DlgExportStep; class DlgImportStep; class DlgExportHeaderStep; -class DlgImportExportStep : public Gui::Dialog::PreferencePage +class DlgImportExportStep: public Gui::Dialog::PreferencePage { Q_OBJECT @@ -83,7 +84,7 @@ public: protected: void saveSettings() override; void loadSettings() override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: DlgExportStep* exportStep; @@ -91,6 +92,6 @@ private: DlgExportHeaderStep* headerStep; }; -} // namespace Gui +} // namespace PartGui -#endif // PARTGUI_DLGSETTINGSGENERAL_H +#endif // PARTGUI_DLGSETTINGSGENERAL_H diff --git a/src/Mod/Part/Gui/DlgSettingsObjectColor.cpp b/src/Mod/Part/Gui/DlgSettingsObjectColor.cpp index e8f4e295b6..a8d4a9f99a 100644 --- a/src/Mod/Part/Gui/DlgSettingsObjectColor.cpp +++ b/src/Mod/Part/Gui/DlgSettingsObjectColor.cpp @@ -93,7 +93,7 @@ void DlgSettingsObjectColor::loadSettings() /** * Sets the strings of the subwidgets using the current language. */ -void DlgSettingsObjectColor::changeEvent(QEvent *e) +void DlgSettingsObjectColor::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -104,4 +104,3 @@ void DlgSettingsObjectColor::changeEvent(QEvent *e) } #include "moc_DlgSettingsObjectColor.cpp" - diff --git a/src/Mod/Part/Gui/DlgSettingsObjectColor.h b/src/Mod/Part/Gui/DlgSettingsObjectColor.h index e08badf5bd..ad03b09985 100644 --- a/src/Mod/Part/Gui/DlgSettingsObjectColor.h +++ b/src/Mod/Part/Gui/DlgSettingsObjectColor.h @@ -29,7 +29,8 @@ #include #include -namespace PartGui { +namespace PartGui +{ class Ui_DlgSettingsObjectColor; /** @@ -37,24 +38,24 @@ class Ui_DlgSettingsObjectColor; * for data objects. * @author Werner Mayer */ -class DlgSettingsObjectColor : public Gui::Dialog::PreferencePage +class DlgSettingsObjectColor: public Gui::Dialog::PreferencePage { - Q_OBJECT + Q_OBJECT public: - explicit DlgSettingsObjectColor(QWidget* parent = nullptr); - ~DlgSettingsObjectColor() override; + explicit DlgSettingsObjectColor(QWidget* parent = nullptr); + ~DlgSettingsObjectColor() override; - void saveSettings() override; - void loadSettings() override; + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: - std::unique_ptr ui; + std::unique_ptr ui; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_DIALOG_DLGSETTINGSOBJECTCOLOR_H +#endif // PARTGUI_DIALOG_DLGSETTINGSOBJECTCOLOR_H diff --git a/src/Mod/Part/Gui/Mirroring.cpp b/src/Mod/Part/Gui/Mirroring.cpp index d9c10ff8c5..25f0759431 100644 --- a/src/Mod/Part/Gui/Mirroring.cpp +++ b/src/Mod/Part/Gui/Mirroring.cpp @@ -23,24 +23,24 @@ ***************************************************************************/ -# include -# include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include -# include -# include +#include +#include +#include +#include #include #include @@ -69,14 +69,14 @@ using namespace PartGui; -namespace PartGui { -class MirrorPlaneSelection : public Gui::SelectionFilterGate +namespace PartGui +{ +class MirrorPlaneSelection: public Gui::SelectionFilterGate { public: explicit MirrorPlaneSelection() : Gui::SelectionFilterGate() - { - } + {} /** * We can't simply check if the selection is a face or an edge because only certain faces * and edges can work. Bspline faces won't work, and only circle edges are supported. But we @@ -90,78 +90,97 @@ public: std::string subString(sSubName); if (pObj->isDerivedFrom() || pObj->isDerivedFrom() - || (strstr(pObj->getNameInDocument(), "Plane") && pObj->isDerivedFrom())) { + || (strstr(pObj->getNameInDocument(), "Plane") && pObj->isDerivedFrom())) { return true; // reference is an app::link or a part::feature or some subobject - } else if (pObj->isDerivedFrom() || pObj->isDerivedFrom()) { - bool isFace = false; //will be true if user selected face subobject or if object only has 1 face - bool isEdge = false; //will be true if user selected edge subobject or if object only has 1 edge + } + else if (pObj->isDerivedFrom() || pObj->isDerivedFrom()) { + bool isFace = false; // will be true if user selected face subobject or if object only + // has 1 face + bool isEdge = false; // will be true if user selected edge subobject or if object only + // has 1 edge TopoDS_Shape shape; - if (subString.length() > 0){ - shape = Part::Feature::getTopoShape(pObj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sSubName).getShape(); + if (subString.length() > 0) { + shape = Part::Feature::getTopoShape( + pObj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sSubName + ) + .getShape(); - if (strstr(subString.c_str(), "Face")){ - isFace = true; //was face subobject, e.g. Face3 - } else { - if (strstr(subString.c_str(), "Edge")){ - isEdge = true; //was edge subobject, e.g. Edge7 + if (strstr(subString.c_str(), "Face")) { + isFace = true; // was face subobject, e.g. Face3 + } + else { + if (strstr(subString.c_str(), "Edge")) { + isEdge = true; // was edge subobject, e.g. Edge7 } } - } else { - //no subobjects were selected, so this is entire shape of feature - shape = Part::Feature::getShape(pObj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + } + else { + // no subobjects were selected, so this is entire shape of feature + shape = Part::Feature::getShape( + pObj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); } - // if there is only 1 face or 1 edge, then we don't need to force the user to select that face or edge - // instead we can infer what was intended + // if there is only 1 face or 1 edge, then we don't need to force the user to select + // that face or edge instead we can infer what was intended int faceCount = Part::TopoShape(shape).countSubShapes(TopAbs_FACE); int edgeCount = Part::TopoShape(shape).countSubShapes(TopAbs_EDGE); TopoDS_Face face; TopoDS_Edge edge; - if (isFace) { //user selected a face, so use shape to get the TopoDS::Face + if (isFace) { // user selected a face, so use shape to get the TopoDS::Face face = TopoDS::Face(shape); - } else { - if (faceCount == 1) { //entire feature selected, but it only has 1 face, so get that face - TopoDS_Shape tdface = Part::TopoShape(shape).getSubShape(std::string("Face1").c_str()); + } + else { + if (faceCount == 1) { // entire feature selected, but it only has 1 face, so get + // that face + TopoDS_Shape tdface = Part::TopoShape(shape).getSubShape( + std::string("Face1").c_str() + ); face = TopoDS::Face(tdface); isFace = true; } } - if (!isFace && isEdge){ //don't bother with edge if we already have a face to work with - edge = TopoDS::Edge(shape); //isEdge means an edge was selected - } else { - if (edgeCount == 1){ //we don't have a face yet and there were no edges in the subobject selection - //but since this object only has 1 edge, we use it - TopoDS_Shape tdedge = Part::TopoShape(shape).getSubShape(std::string("Edge1").c_str()); + if (!isFace && isEdge) { // don't bother with edge if we already have a face to work with + edge = TopoDS::Edge(shape); // isEdge means an edge was selected + } + else { + if (edgeCount == 1) { // we don't have a face yet and there were no edges in the + // subobject selection + // but since this object only has 1 edge, we use it + TopoDS_Shape tdedge = Part::TopoShape(shape).getSubShape( + std::string("Edge1").c_str() + ); edge = TopoDS::Edge(tdedge); isEdge = true; } } - if (isFace && face.IsNull()) { //ensure we have a good face to work with + if (isFace && face.IsNull()) { // ensure we have a good face to work with return false; } - if (isEdge && edge.IsNull()){ //ensure we have a good edge to work with + if (isEdge && edge.IsNull()) { // ensure we have a good edge to work with return false; } - if (!isFace && !isEdge){ + if (!isFace && !isEdge) { return false; } if (isFace) { BRepAdaptor_Surface adapt(face); - if (adapt.GetType() != GeomAbs_Plane){ + if (adapt.GetType() != GeomAbs_Plane) { return false; } return true; - } else { - if (isEdge){ + } + else { + if (isEdge) { BRepAdaptor_Curve curve(edge); if (!(curve.GetType() == GeomAbs_Circle)) { return false; @@ -169,18 +188,19 @@ public: return true; } } - } //end of if(derived from part::feature) + } // end of if(derived from part::feature) return true; - }//end of allow() + } // end of allow() -}; //end of class -}; //end of namespace block +}; // end of class +}; // namespace PartGui /* TRANSLATOR PartGui::Mirroring */ Mirroring::Mirroring(QWidget* parent) - : QWidget(parent), ui(new Ui_Mirroring) + : QWidget(parent) + , ui(new Ui_Mirroring) { ui->setupUi(this); constexpr double max = std::numeric_limits::max(); @@ -208,18 +228,20 @@ Mirroring::Mirroring(QWidget* parent) */ Mirroring::~Mirroring() = default; -void Mirroring::onSelectButtonClicked(){ - if (!ui->selectButton->isChecked()){ +void Mirroring::onSelectButtonClicked() +{ + if (!ui->selectButton->isChecked()) { Gui::Selection().rmvSelectionGate(); ui->selectButton->setText(tr("Select reference")); - } else { + } + else { MirrorPlaneSelection* gate = new MirrorPlaneSelection(); Gui::Selection().addSelectionGate(gate); ui->selectButton->setText(tr("Selecting")); } } -void Mirroring::changeEvent(QEvent *e) +void Mirroring::changeEvent(QEvent* e) { if (e->type() == QEvent::LanguageChange) { ui->retranslateUi(this); @@ -227,7 +249,7 @@ void Mirroring::changeEvent(QEvent *e) QWidget::changeEvent(e); } -void Mirroring::onSelectionChanged(const Gui::SelectionChanges &msg) +void Mirroring::onSelectionChanged(const Gui::SelectionChanges& msg) { if (ui->selectButton->isChecked()) { if (msg.Type == Gui::SelectionChanges::AddSelection) { @@ -244,17 +266,22 @@ void Mirroring::onSelectionChanged(const Gui::SelectionChanges &msg) void Mirroring::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); - if (!activeDoc) + if (!activeDoc) { return; + } Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); - if (!activeGui) + if (!activeGui) { return; + } this->document = QString::fromLatin1(activeDoc->getName()); std::vector objs = activeDoc->getObjectsOfType(); for (auto obj : objs) { - Part::TopoShape shape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape shape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!shape.isNull()) { QString label = QString::fromUtf8(obj->Label.getValue()); QString name = QString::fromLatin1(obj->getNameInDocument()); @@ -264,7 +291,9 @@ void Mirroring::findShapes() child->setToolTip(0, label); child->setData(0, Qt::UserRole, name); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) child->setIcon(0, vp->getIcon()); + if (vp) { + child->setIcon(0, vp->getIcon()); + } ui->shapes->addTopLevelItem(child); } } @@ -279,15 +308,15 @@ bool Mirroring::reject() bool Mirroring::accept() { if (ui->shapes->selectedItems().isEmpty()) { - QMessageBox::critical(this, windowTitle(), - tr("Select a shape for mirroring.")); + QMessageBox::critical(this, windowTitle(), tr("Select a shape for mirroring.")); return false; } - App::Document* activeDoc = App::GetApplication().getDocument((const char*)this->document.toLatin1()); + App::Document* activeDoc = App::GetApplication().getDocument( + (const char*)this->document.toLatin1() + ); if (!activeDoc) { - QMessageBox::critical(this, windowTitle(), - tr("No such document '%1'.").arg(this->document)); + QMessageBox::critical(this, windowTitle(), tr("No such document '%1'.").arg(this->document)); return false; } @@ -297,19 +326,22 @@ bool Mirroring::accept() QString shape, label, selectionString; QRegularExpression rx(QString::fromLatin1(R"( \(Mirror #\d+\)$)")); - QList items = ui->shapes->selectedItems(); - float normx=0, normy=0, normz=0; + QList items = ui->shapes->selectedItems(); + float normx = 0, normy = 0, normz = 0; int index = ui->comboBox->currentIndex(); - std::string selection(""); //set MirrorPlane property to empty string unless - //user has selected Use selected reference in combobox + std::string selection(""); // set MirrorPlane property to empty string unless + // user has selected Use selected reference in combobox - if (index == 0){ + if (index == 0) { normz = 1.0f; - } else if (index == 1){ + } + else if (index == 1) { normy = 1.0f; - } else if (index == 2){ + } + else if (index == 2) { normx = 1.0f; - } else if (index == 3){ //use selected reference + } + else if (index == 3) { // use selected reference std::vector selobjs = Gui::Selection().getSelectionEx(); if (selobjs.size() == 1) { selection = selobjs[0].getAsPropertyLinkSubString(); @@ -326,23 +358,29 @@ bool Mirroring::accept() // if we already have the suffix " (Mirror #)" remove it int pos = label.indexOf(rx); - if (pos > -1) + if (pos > -1) { label = label.left(pos); + } label.append(QStringLiteral(" (Mirror #%1)").arg(++count)); QString code = QStringLiteral( - "__doc__=FreeCAD.getDocument(\"%1\")\n" - "__doc__.addObject(\"Part::Mirroring\")\n" - "__doc__.ActiveObject.Source=__doc__.getObject(\"%2\")\n" - "__doc__.ActiveObject.Label=u\"%3\"\n" - "__doc__.ActiveObject.Normal=(%4,%5,%6)\n" - "__doc__.ActiveObject.Base=(%7,%8,%9)\n" - "__doc__.ActiveObject.MirrorPlane=(%10)\n" - "del __doc__") - .arg(this->document, shape, label) - .arg(normx).arg(normy).arg(normz) - .arg(basex).arg(basey).arg(basez) - .arg(selectionString); + "__doc__=FreeCAD.getDocument(\"%1\")\n" + "__doc__.addObject(\"Part::Mirroring\")\n" + "__doc__.ActiveObject.Source=__doc__.getObject(\"%2\")\n" + "__doc__.ActiveObject.Label=u\"%3\"\n" + "__doc__.ActiveObject.Normal=(%4,%5,%6)\n" + "__doc__.ActiveObject.Base=(%7,%8,%9)\n" + "__doc__.ActiveObject.MirrorPlane=(%10)\n" + "del __doc__" + ) + .arg(this->document, shape, label) + .arg(normx) + .arg(normy) + .arg(normz) + .arg(basex) + .arg(basey) + .arg(basez) + .arg(selectionString); Gui::Command::runCommand(Gui::Command::App, code.toLatin1()); QByteArray from = shape.toLatin1(); Gui::Command::copyVisual("ActiveObject", "ShapeAppearance", from); diff --git a/src/Mod/Part/Gui/Mirroring.h b/src/Mod/Part/Gui/Mirroring.h index 2d5f105e7b..fac59c54df 100644 --- a/src/Mod/Part/Gui/Mirroring.h +++ b/src/Mod/Part/Gui/Mirroring.h @@ -30,14 +30,16 @@ class QTreeWidgetItem; -namespace App { +namespace App +{ class DocumentObject; class Property; -} -namespace PartGui { +} // namespace App +namespace PartGui +{ class Ui_Mirroring; -class Mirroring : public QWidget, public Gui::SelectionObserver +class Mirroring: public QWidget, public Gui::SelectionObserver { Q_OBJECT @@ -48,7 +50,7 @@ public: bool reject(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void findShapes(); @@ -60,7 +62,7 @@ private: std::unique_ptr ui; }; -class TaskMirroring : public Gui::TaskView::TaskDialog +class TaskMirroring: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -72,16 +74,22 @@ public: bool reject() override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } bool isAllowedAlterDocument() const override - { return false; } + { + return false; + } bool needsFullSpace() const override - { return false; } + { + return false; + } private: Mirroring* widget; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_MIRRORING_H +#endif // PARTGUI_MIRRORING_H diff --git a/src/Mod/Part/Gui/PatternParametersWidget.cpp b/src/Mod/Part/Gui/PatternParametersWidget.cpp index be6eaf29e5..27ba50584a 100644 --- a/src/Mod/Part/Gui/PatternParametersWidget.cpp +++ b/src/Mod/Part/Gui/PatternParametersWidget.cpp @@ -44,10 +44,10 @@ using namespace PartGui; -PatternParametersWidget::PatternParametersWidget(PatternType type, QWidget* parent) : - QWidget(parent), - type(type), - ui(new Ui_PatternParametersWidget) +PatternParametersWidget::PatternParametersWidget(PatternType type, QWidget* parent) + : QWidget(parent) + , type(type) + , ui(new Ui_PatternParametersWidget) { ui->setupUi(this); setupUiElements(); @@ -73,7 +73,8 @@ void PatternParametersWidget::setupUiElements() dirLinks.setCombo(ui->comboDirection); ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Part"); + "User parameter:BaseApp/Preferences/Mod/Part" + ); ui->addSpacingButton->setVisible(hPart->GetBool("ExperimentalFeatures", false)); ui->enableCheckbox->setVisible(false); @@ -81,40 +82,67 @@ void PatternParametersWidget::setupUiElements() void PatternParametersWidget::connectSignals() { - connect(ui->comboDirection, qOverload(&QComboBox::activated), - this, &PatternParametersWidget::onDirectionChanged); - connect(ui->PushButtonReverse, &QToolButton::pressed, - this, &PatternParametersWidget::onReversePressed); - connect(ui->comboMode, qOverload(&QComboBox::activated), - this, &PatternParametersWidget::onModeChanged); + connect( + ui->comboDirection, + qOverload(&QComboBox::activated), + this, + &PatternParametersWidget::onDirectionChanged + ); + connect(ui->PushButtonReverse, &QToolButton::pressed, this, &PatternParametersWidget::onReversePressed); + connect( + ui->comboMode, + qOverload(&QComboBox::activated), + this, + &PatternParametersWidget::onModeChanged + ); - connect(ui->spinExtent, qOverload(&Gui::QuantitySpinBox::valueChanged), - this, &PatternParametersWidget::onLengthChanged); - connect(ui->spinSpacing, qOverload(&Gui::QuantitySpinBox::valueChanged), - this, &PatternParametersWidget::onOffsetChanged); - connect(ui->spinOccurrences, &Gui::UIntSpinBox::unsignedChanged, - this, &PatternParametersWidget::onOccurrencesChanged); + connect( + ui->spinExtent, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PatternParametersWidget::onLengthChanged + ); + connect( + ui->spinSpacing, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PatternParametersWidget::onOffsetChanged + ); + connect( + ui->spinOccurrences, + &Gui::UIntSpinBox::unsignedChanged, + this, + &PatternParametersWidget::onOccurrencesChanged + ); // Dynamic spacing buttons - connect(ui->addSpacingButton, &QToolButton::clicked, - this, &PatternParametersWidget::onAddSpacingButtonClicked); + connect( + ui->addSpacingButton, + &QToolButton::clicked, + this, + &PatternParametersWidget::onAddSpacingButtonClicked + ); connect(ui->groupBox, &QGroupBox::toggled, this, &PatternParametersWidget::onGroupBoxToggled); - connect(ui->enableCheckbox, - &QCheckBox::toggled, - this, - &PatternParametersWidget::onEnableCheckBoxToggled); + connect( + ui->enableCheckbox, + &QCheckBox::toggled, + this, + &PatternParametersWidget::onEnableCheckBoxToggled + ); // Note: Connections for dynamic rows are done in addSpacingRow() } -void PatternParametersWidget::bindProperties(App::PropertyLinkSub* directionProp, +void PatternParametersWidget::bindProperties( + App::PropertyLinkSub* directionProp, App::PropertyBool* reversedProp, App::PropertyEnumeration* modeProp, App::PropertyQuantity* lengthProp, App::PropertyQuantity* offsetProp, App::PropertyFloatList* spacingPatternProp, App::PropertyIntegerConstraint* occurrencesProp, - App::DocumentObject* feature) + App::DocumentObject* feature +) { // Store pointers to the properties m_directionProp = directionProp; @@ -124,7 +152,7 @@ void PatternParametersWidget::bindProperties(App::PropertyLinkSub* directionProp m_spacingProp = offsetProp; m_spacingPatternProp = spacingPatternProp; m_occurrencesProp = occurrencesProp; - m_feature = feature; // Store feature for context (units, etc.) + m_feature = feature; // Store feature for context (units, etc.) ui->spinExtent->bind(*m_extentProp); Base::Unit unit = type == PatternType::Linear ? Base::Unit::Length : Base::Unit::Angle; @@ -152,7 +180,12 @@ void PatternParametersWidget::bindProperties(App::PropertyLinkSub* directionProp updateUI(); } -void PatternParametersWidget::addDirection(App::DocumentObject* linkObj, const std::string& linkSubname, const QString& itemText, int userData) +void PatternParametersWidget::addDirection( + App::DocumentObject* linkObj, + const std::string& linkSubname, + const QString& itemText, + int userData +) { // Insert custom directions before "Select reference..." dirLinks.addLink(linkObj, linkSubname, itemText, userData); @@ -160,7 +193,7 @@ void PatternParametersWidget::addDirection(App::DocumentObject* linkObj, const s void PatternParametersWidget::updateUI() { - if (blockUpdate || !m_feature) { // Need properties to be bound + if (blockUpdate || !m_feature) { // Need properties to be bound return; } Base::StateLocker locker(blockUpdate, true); @@ -169,9 +202,10 @@ void PatternParametersWidget::updateUI() if (dirLinks.setCurrentLink(*m_directionProp) == -1) { // failed to set current, because the link isn't in the list yet if (m_directionProp->getValue()) { - QString refStr = - QStringLiteral("%1:%2").arg(QString::fromLatin1(m_directionProp->getValue()->getNameInDocument()), - QString::fromLatin1(m_directionProp->getSubValues().front().c_str())); + QString refStr = QStringLiteral("%1:%2").arg( + QString::fromLatin1(m_directionProp->getValue()->getNameInDocument()), + QString::fromLatin1(m_directionProp->getSubValues().front().c_str()) + ); dirLinks.addLink(*m_directionProp, refStr); dirLinks.setCurrentLink(*m_directionProp); } @@ -267,21 +301,25 @@ void PatternParametersWidget::setChecked(bool on) void PatternParametersWidget::onDirectionChanged(int /*index*/) { - if (blockUpdate || !m_directionProp) return; + if (blockUpdate || !m_directionProp) { + return; + } if (isSelectReferenceMode()) { // Emit signal for the task panel to handle reference selection requestReferenceSelection(); } else { - m_directionProp->Paste(dirLinks.getCurrentLink()); // Update the property - parametersChanged(); // Notify change + m_directionProp->Paste(dirLinks.getCurrentLink()); // Update the property + parametersChanged(); // Notify change } } void PatternParametersWidget::onReversePressed() { - if (blockUpdate || !m_reversedProp) return; + if (blockUpdate || !m_reversedProp) { + return; + } m_reversedProp->setValue(!m_reversedProp->getValue()); parametersChanged(); @@ -289,46 +327,55 @@ void PatternParametersWidget::onReversePressed() void PatternParametersWidget::onModeChanged(int index) { - if (blockUpdate || !m_modeProp) return; - m_modeProp->setValue(index); // Assuming enum values match index - adaptVisibilityToMode(); // Update visibility based on new mode + if (blockUpdate || !m_modeProp) { + return; + } + m_modeProp->setValue(index); // Assuming enum values match index + adaptVisibilityToMode(); // Update visibility based on new mode parametersChanged(); } void PatternParametersWidget::onLengthChanged(double value) { // Usually handled by bind(). If manual update needed: - if (blockUpdate || !m_extentProp) return; + if (blockUpdate || !m_extentProp) { + return; + } m_extentProp->setValue(value); - parametersChanged(); // Still emit signal even if bound + parametersChanged(); // Still emit signal even if bound } void PatternParametersWidget::onOffsetChanged(double value) { - if (blockUpdate || !m_spacingProp || !m_spacingPatternProp) return; + if (blockUpdate || !m_spacingProp || !m_spacingPatternProp) { + return; + } m_spacingProp->setValue(value); // Crucially, also update the *first* element of the SpacingPattern list std::vector currentSpacings = m_spacingPatternProp->getValues(); if (currentSpacings.empty()) { - currentSpacings.push_back(ui->spinSpacing->value().getValue()); // Use UI value which includes units + currentSpacings.push_back(ui->spinSpacing->value().getValue()); // Use UI value which + // includes units } else { currentSpacings[0] = ui->spinSpacing->value().getValue(); } - m_spacingPatternProp->setValues(currentSpacings); // Update the property list - parametersChanged(); // Emit signal + m_spacingPatternProp->setValues(currentSpacings); // Update the property list + parametersChanged(); // Emit signal } void PatternParametersWidget::onOccurrencesChanged(unsigned int value) { // Usually handled by bind(). If manual update needed: - if (blockUpdate || !m_occurrencesProp) return; + if (blockUpdate || !m_occurrencesProp) { + return; + } m_occurrencesProp->setValue(value); - parametersChanged(); // Still emit signal even if bound + parametersChanged(); // Still emit signal even if bound } @@ -385,10 +432,12 @@ void PatternParametersWidget::addSpacingRow(double value) dynamicSpacingSpinBoxes.append(spinBox); // Connect signals for the new row - connect(spinBox, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &PatternParametersWidget::onDynamicSpacingChanged); + connect( + spinBox, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &PatternParametersWidget::onDynamicSpacingChanged + ); connect(removeButton, &QToolButton::clicked, this, [this, fieldWidget]() { this->onRemoveSpacingButtonClicked(fieldWidget); }); @@ -412,20 +461,24 @@ void PatternParametersWidget::rebuildDynamicSpacingUI() void PatternParametersWidget::onAddSpacingButtonClicked() { - if (blockUpdate || !m_spacingProp) return; + if (blockUpdate || !m_spacingProp) { + return; + } // Add a new row to the UI with a default value (same as main offset) addSpacingRow(ui->spinSpacing->value().getValue()); // Update the underlying property list - updateSpacingPatternProperty(); // This will emit parametersChanged + updateSpacingPatternProperty(); // This will emit parametersChanged } void PatternParametersWidget::onDynamicSpacingChanged() { - if (blockUpdate) return; + if (blockUpdate) { + return; + } // Update the entire property list based on the current UI state. - updateSpacingPatternProperty(); // This will emit parametersChanged + updateSpacingPatternProperty(); // This will emit parametersChanged } void PatternParametersWidget::onRemoveSpacingButtonClicked(QWidget* fieldWidget) @@ -447,8 +500,7 @@ void PatternParametersWidget::onRemoveSpacingButtonClicked(QWidget* fieldWidget) // Update labels of subsequent rows for (int i = indexToRemove; i < dynamicSpacingRows.size(); ++i) { - if (auto* label = - qobject_cast(ui->formLayout->labelForField(dynamicSpacingRows[i]))) { + if (auto* label = qobject_cast(ui->formLayout->labelForField(dynamicSpacingRows[i]))) { label->setText(tr("Spacing %1").arg(i + 2)); } } @@ -473,14 +525,13 @@ void PatternParametersWidget::updateSpacingPatternProperty() newSpacings.push_back(spinBox->value().getValue()); } - m_spacingPatternProp->setValues(newSpacings); // Set the property list - parametersChanged(); // Emit signal after property is set + m_spacingPatternProp->setValues(newSpacings); // Set the property list + parametersChanged(); // Emit signal after property is set } // --- Getters --- -void PatternParametersWidget::getAxis(App::DocumentObject*& obj, - std::vector& sub) const +void PatternParametersWidget::getAxis(App::DocumentObject*& obj, std::vector& sub) const { const App::PropertyLinkSub& lnk = dirLinks.getCurrentLink(); obj = lnk.getValue(); @@ -532,5 +583,4 @@ void PatternParametersWidget::applyQuantitySpinboxes() const ui->spinOccurrences->apply(); } -//#include "moc_PatternParametersWidget.cpp" - +// #include "moc_PatternParametersWidget.cpp" diff --git a/src/Mod/Part/Gui/PatternParametersWidget.h b/src/Mod/Part/Gui/PatternParametersWidget.h index e22ce4edca..537a8c55a9 100644 --- a/src/Mod/Part/Gui/PatternParametersWidget.h +++ b/src/Mod/Part/Gui/PatternParametersWidget.h @@ -26,192 +26,204 @@ #define PARTGUI_PATTERNPARAMETERSWIDGET_H #include -#include // For Property types -#include // For PropertyLinkSub +#include // For Property types +#include // For PropertyLinkSub #include #include class Ui_PatternParametersWidget; -namespace App { - class PropertyLinkSub; - class PropertyBool; - class PropertyEnumeration; - class PropertyQuantity; - class PropertyFloatList; - class PropertyIntegerConstraint; - class DocumentObject; -} -namespace Gui { - class QuantitySpinBox; +namespace App +{ +class PropertyLinkSub; +class PropertyBool; +class PropertyEnumeration; +class PropertyQuantity; +class PropertyFloatList; +class PropertyIntegerConstraint; +class DocumentObject; +} // namespace App +namespace Gui +{ +class QuantitySpinBox; } class QToolButton; -namespace PartGui { +namespace PartGui +{ - enum class PatternType { - Linear, - Polar - }; +enum class PatternType +{ + Linear, + Polar +}; - enum class PatternMode { - Extent, - Spacing - }; +enum class PatternMode +{ + Extent, + Spacing +}; + +/** + * @brief A widget to configure the parameters for a single direction of a linear pattern. + * + * This widget encapsulates the UI and logic for Direction, Reverse, Mode, + * Length/Spacing (including dynamic spacing), and Occurrences. It binds directly + * to the corresponding properties of a Feature. + */ +class PartGuiExport PatternParametersWidget: public QWidget +{ + Q_OBJECT + +public: + explicit PatternParametersWidget(PatternType type, QWidget* parent = nullptr); + ~PatternParametersWidget() override; /** - * @brief A widget to configure the parameters for a single direction of a linear pattern. + * @brief Binds the widget's UI elements to the properties of a DocumentObject. * - * This widget encapsulates the UI and logic for Direction, Reverse, Mode, - * Length/Spacing (including dynamic spacing), and Occurrences. It binds directly - * to the corresponding properties of a Feature. + * This must be called after creating the widget to link its controls + * to the underlying feature's data. + * + * @param directionProp Reference to the Direction property (PropertyLinkSub). + * @param reversedProp Reference to the Reversed property (PropertyBool). + * @param modeProp Reference to the Mode property (PropertyEnumeration). + * @param lengthProp Reference to the Length property (PropertyQuantity). + * @param offsetProp Reference to the Offset property (PropertyQuantity). + * @param spacingPatternProp Reference to the SpacingPattern property (PropertyFloatList). + * @param occurrencesProp Reference to the Occurrences property (PropertyIntegerConstraint). + * @param feature The feature object itself, needed for context (e.g., units). */ - class PartGuiExport PatternParametersWidget : public QWidget - { - Q_OBJECT - - public: - explicit PatternParametersWidget(PatternType type, QWidget* parent = nullptr); - ~PatternParametersWidget() override; - - /** - * @brief Binds the widget's UI elements to the properties of a DocumentObject. - * - * This must be called after creating the widget to link its controls - * to the underlying feature's data. - * - * @param directionProp Reference to the Direction property (PropertyLinkSub). - * @param reversedProp Reference to the Reversed property (PropertyBool). - * @param modeProp Reference to the Mode property (PropertyEnumeration). - * @param lengthProp Reference to the Length property (PropertyQuantity). - * @param offsetProp Reference to the Offset property (PropertyQuantity). - * @param spacingPatternProp Reference to the SpacingPattern property (PropertyFloatList). - * @param occurrencesProp Reference to the Occurrences property (PropertyIntegerConstraint). - * @param feature The feature object itself, needed for context (e.g., units). - */ - void bindProperties(App::PropertyLinkSub* directionProp, - App::PropertyBool* reversedProp, - App::PropertyEnumeration* modeProp, - App::PropertyQuantity* lengthProp, - App::PropertyQuantity* offsetProp, - App::PropertyFloatList* spacingPatternProp, - App::PropertyIntegerConstraint* occurrencesProp, - App::DocumentObject* feature); // Pass feature for context + void bindProperties( + App::PropertyLinkSub* directionProp, + App::PropertyBool* reversedProp, + App::PropertyEnumeration* modeProp, + App::PropertyQuantity* lengthProp, + App::PropertyQuantity* offsetProp, + App::PropertyFloatList* spacingPatternProp, + App::PropertyIntegerConstraint* occurrencesProp, + App::DocumentObject* feature + ); // Pass feature for context - /** - * @brief Adds a custom direction option to the Direction combo box. - * - * Used by consuming tools (like PartDesign tasks) to add context-specific - * directions (e.g., Sketch axes). - * - * @param link The PropertyLinkSub representing the custom direction. - * @param text The user-visible text for the combo box item. - */ - void addDirection(App::DocumentObject* linkObj, const std::string& linkSubname, const QString& itemText, int userData = -1); + /** + * @brief Adds a custom direction option to the Direction combo box. + * + * Used by consuming tools (like PartDesign tasks) to add context-specific + * directions (e.g., Sketch axes). + * + * @param link The PropertyLinkSub representing the custom direction. + * @param text The user-visible text for the combo box item. + */ + void addDirection( + App::DocumentObject* linkObj, + const std::string& linkSubname, + const QString& itemText, + int userData = -1 + ); - /** - * @brief Updates the UI elements to reflect the current values of the bound properties. - */ - void updateUI(); + /** + * @brief Updates the UI elements to reflect the current values of the bound properties. + */ + void updateUI(); - /** - * @brief Returns the currently selected direction link from the combo box. - * Returns an empty link if "Select reference..." is chosen. - */ - const App::PropertyLinkSub& getCurrentDirectionLink() const; + /** + * @brief Returns the currently selected direction link from the combo box. + * Returns an empty link if "Select reference..." is chosen. + */ + const App::PropertyLinkSub& getCurrentDirectionLink() const; - /** - * @brief Checks if the "Select reference..." item is currently selected. - */ - bool isSelectReferenceMode() const; + /** + * @brief Checks if the "Select reference..." item is currently selected. + */ + bool isSelectReferenceMode() const; - void getAxis(App::DocumentObject*& obj, std::vector& sub) const; - bool getReverse() const; - int getMode() const; - double getExtent() const; - double getSpacing() const; - unsigned getOccurrences() const; - std::string getSpacingPatternsAsString() const; + void getAxis(App::DocumentObject*& obj, std::vector& sub) const; + bool getReverse() const; + int getMode() const; + double getExtent() const; + double getSpacing() const; + unsigned getOccurrences() const; + std::string getSpacingPatternsAsString() const; - void setTitle(const QString& title); - void setCheckable(bool on); - void setChecked(bool on); + void setTitle(const QString& title); + void setCheckable(bool on); + void setChecked(bool on); - void applyQuantitySpinboxes() const; + void applyQuantitySpinboxes() const; - Gui::ComboLinks dirLinks; + Gui::ComboLinks dirLinks; - Q_SIGNALS: - /** - * @brief Emitted when the user selects the "Select reference..." option - * in the direction combo box, indicating the need to enter selection mode. - */ - void requestReferenceSelection(); +Q_SIGNALS: + /** + * @brief Emitted when the user selects the "Select reference..." option + * in the direction combo box, indicating the need to enter selection mode. + */ + void requestReferenceSelection(); - /** - * @brief Emitted when any parameter value controlled by this widget changes - * that requires a recompute of the feature. - */ - void parametersChanged(); + /** + * @brief Emitted when any parameter value controlled by this widget changes + * that requires a recompute of the feature. + */ + void parametersChanged(); - private Q_SLOTS: - // Slots connected to UI elements - void onDirectionChanged(int index); - void onReversePressed(); - void onModeChanged(int index); - // Note: Spinbox value changes are often handled by direct binding, - // but we might need slots if extra logic (like updating SpacingPattern[0]) is needed. - void onLengthChanged(double value); - void onOffsetChanged(double value); - void onOccurrencesChanged(unsigned int value); +private Q_SLOTS: + // Slots connected to UI elements + void onDirectionChanged(int index); + void onReversePressed(); + void onModeChanged(int index); + // Note: Spinbox value changes are often handled by direct binding, + // but we might need slots if extra logic (like updating SpacingPattern[0]) is needed. + void onLengthChanged(double value); + void onOffsetChanged(double value); + void onOccurrencesChanged(unsigned int value); - void onGroupBoxToggled(bool checked); - void onEnableCheckBoxToggled(bool checked); + void onGroupBoxToggled(bool checked); + void onEnableCheckBoxToggled(bool checked); - // Slots for dynamic spacing - void onAddSpacingButtonClicked(); - void onDynamicSpacingChanged(); // Simplified slot - void onRemoveSpacingButtonClicked(QWidget* rowWidget); + // Slots for dynamic spacing + void onAddSpacingButtonClicked(); + void onDynamicSpacingChanged(); // Simplified slot + void onRemoveSpacingButtonClicked(QWidget* rowWidget); - private: - // Initialization and setup - void setupUiElements(); - void connectSignals(); +private: + // Initialization and setup + void setupUiElements(); + void connectSignals(); - // UI Update and state management - void adaptVisibilityToMode(); + // UI Update and state management + void adaptVisibilityToMode(); - // Dynamic spacing helpers - void addSpacingRow(double value); - void clearDynamicSpacingRows(); - void rebuildDynamicSpacingUI(); - void updateSpacingPatternProperty(); // Updates the property from the UI + // Dynamic spacing helpers + void addSpacingRow(double value); + void clearDynamicSpacingRows(); + void rebuildDynamicSpacingUI(); + void updateSpacingPatternProperty(); // Updates the property from the UI - std::unique_ptr ui; + std::unique_ptr ui; - // Pointers to bound properties (raw pointers, lifetime managed externally) - App::PropertyLinkSub* m_directionProp = nullptr; - App::PropertyBool* m_reversedProp = nullptr; - App::PropertyEnumeration* m_modeProp = nullptr; - App::PropertyQuantity* m_extentProp = nullptr; - App::PropertyQuantity* m_spacingProp = nullptr; - App::PropertyFloatList* m_spacingPatternProp = nullptr; - App::PropertyIntegerConstraint* m_occurrencesProp = nullptr; - App::DocumentObject* m_feature = nullptr; // Store feature for context + // Pointers to bound properties (raw pointers, lifetime managed externally) + App::PropertyLinkSub* m_directionProp = nullptr; + App::PropertyBool* m_reversedProp = nullptr; + App::PropertyEnumeration* m_modeProp = nullptr; + App::PropertyQuantity* m_extentProp = nullptr; + App::PropertyQuantity* m_spacingProp = nullptr; + App::PropertyFloatList* m_spacingPatternProp = nullptr; + App::PropertyIntegerConstraint* m_occurrencesProp = nullptr; + App::DocumentObject* m_feature = nullptr; // Store feature for context - bool blockUpdate = false; // Prevents signal loops + bool blockUpdate = false; // Prevents signal loops - // Store pointers to dynamically created widgets for removal and access - QList dynamicSpacingRows; - QList dynamicSpacingSpinBoxes; + // Store pointers to dynamically created widgets for removal and access + QList dynamicSpacingRows; + QList dynamicSpacingSpinBoxes; - PatternType type; - }; + PatternType type; +}; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_PATTERNPARAMETERSWIDGET_H +#endif // PARTGUI_PATTERNPARAMETERSWIDGET_H diff --git a/src/Mod/Part/Gui/PatternParametersWidget.ui b/src/Mod/Part/Gui/PatternParametersWidget.ui index 654f69b89d..2c81c6c2c8 100644 --- a/src/Mod/Part/Gui/PatternParametersWidget.ui +++ b/src/Mod/Part/Gui/PatternParametersWidget.ui @@ -198,4 +198,3 @@ - diff --git a/src/Mod/Part/Gui/PreCompiled.h b/src/Mod/Part/Gui/PreCompiled.h index 4bba3bc540..62b9e99977 100644 --- a/src/Mod/Part/Gui/PreCompiled.h +++ b/src/Mod/Part/Gui/PreCompiled.h @@ -68,16 +68,16 @@ # endif # include # include -# endif //FC_OS_MACOSX -#endif //FC_OS_WIN32 +# endif // FC_OS_MACOSX +#endif // FC_OS_WIN32 // Should come after glext.h to avoid warnings #include // Qt Toolkit -# include +#include // Inventor includes OpenGL -# include +#include -#endif // PARTGUI_PRECOMPILED_H +#endif // PARTGUI_PRECOMPILED_H diff --git a/src/Mod/Part/Gui/PropertyEnumAttacherItem.cpp b/src/Mod/Part/Gui/PropertyEnumAttacherItem.cpp index d84e2c6d2a..33839a893b 100644 --- a/src/Mod/Part/Gui/PropertyEnumAttacherItem.cpp +++ b/src/Mod/Part/Gui/PropertyEnumAttacherItem.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include #include @@ -36,24 +36,28 @@ PROPERTYITEM_SOURCE(PartGui::PropertyEnumAttacherItem) PropertyEnumAttacherItem::PropertyEnumAttacherItem() = default; -QWidget* PropertyEnumAttacherItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption /*frameOption*/) const +QWidget* PropertyEnumAttacherItem:: + createEditor(QWidget* parent, const std::function& method, FrameOption /*frameOption*/) const { Gui::LabelButton* modeEditor = new Gui::LabelButton(parent); QObject::connect(modeEditor, &Gui::LabelButton::valueChanged, method); - QObject::connect(modeEditor, &Gui::LabelButton::buttonClicked, this, &PropertyEnumAttacherItem::openTask); + QObject::connect( + modeEditor, + &Gui::LabelButton::buttonClicked, + this, + &PropertyEnumAttacherItem::openTask + ); modeEditor->setDisabled(isReadOnly()); return modeEditor; } -void PropertyEnumAttacherItem::setEditorData(QWidget *editor, const QVariant& data) const +void PropertyEnumAttacherItem::setEditorData(QWidget* editor, const QVariant& data) const { Gui::LabelButton* modeEditor = qobject_cast(editor); modeEditor->setValue(data); } -QVariant PropertyEnumAttacherItem::editorData(QWidget *editor) const +QVariant PropertyEnumAttacherItem::editorData(QWidget* editor) const { Gui::LabelButton* modeEditor = qobject_cast(editor); return modeEditor->value(); diff --git a/src/Mod/Part/Gui/PropertyEnumAttacherItem.h b/src/Mod/Part/Gui/PropertyEnumAttacherItem.h index d7d8c47220..d5580df912 100644 --- a/src/Mod/Part/Gui/PropertyEnumAttacherItem.h +++ b/src/Mod/Part/Gui/PropertyEnumAttacherItem.h @@ -38,8 +38,8 @@ namespace PartGui using FrameOption = Gui::PropertyEditor::FrameOption; /** -* Custom editor item for PropertyEnumeration to open Attacher task -*/ + * Custom editor item for PropertyEnumeration to open Attacher task + */ class PartGuiExport PropertyEnumAttacherItem: public Gui::PropertyEditor::PropertyEnumItem { Q_OBJECT @@ -47,9 +47,11 @@ class PartGuiExport PropertyEnumAttacherItem: public Gui::PropertyEditor::Proper public: PROPERTYITEM_HEADER - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; @@ -60,6 +62,6 @@ protected: PropertyEnumAttacherItem(); }; -} // namespace PartGui +} // namespace PartGui -#endif // PART_PropertyEnumAttacherItem_H +#endif // PART_PropertyEnumAttacherItem_H diff --git a/src/Mod/Part/Gui/ReferenceHighlighter.cpp b/src/Mod/Part/Gui/ReferenceHighlighter.cpp index 5ed219ed88..114b283994 100644 --- a/src/Mod/Part/Gui/ReferenceHighlighter.cpp +++ b/src/Mod/Part/Gui/ReferenceHighlighter.cpp @@ -22,10 +22,10 @@ * * ***************************************************************************/ -# include -# include +#include +#include -# include +#include #include "ReferenceHighlighter.h" @@ -34,8 +34,8 @@ using namespace PartGui; ReferenceHighlighter::ReferenceHighlighter(const TopoDS_Shape& shape, const Base::Color& color) : defaultColor(color) - , elementColor(1.0f,0.0f,1.0f) // magenta - , objectColor(0.6f,0.0f,1.0f) // purple + , elementColor(1.0f, 0.0f, 1.0f) // magenta + , objectColor(0.6f, 0.0f, 1.0f) // purple { TopExp::MapShapes(shape, TopAbs_VERTEX, vMap); TopExp::MapShapes(shape, TopAbs_EDGE, eMap); @@ -46,16 +46,20 @@ ReferenceHighlighter::ReferenceHighlighter(const TopoDS_Shape& shape, const Base void ReferenceHighlighter::getVertexColor(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(6)) - 1; - assert ( idx >= 0 ); + assert(idx >= 0); std::size_t pos = std::size_t(idx); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } -void ReferenceHighlighter::getVertexColorsOfEdge(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColorsOfEdge( + const std::string& element, + std::vector& colors +) const { int idx = std::stoi(element.substr(4)); - assert ( idx > 0 ); + assert(idx > 0); // get the vertexes of the edge TopoDS_Shape edge = eMap.FindKey(idx); for (TopExp_Explorer xp(edge, TopAbs_VERTEX); xp.More(); xp.Next()) { @@ -64,16 +68,20 @@ void ReferenceHighlighter::getVertexColorsOfEdge(const std::string& element, std // Vertex found? if (vertexIndex > 0) { std::size_t pos = std::size_t(vertexIndex - 1); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } } } -void ReferenceHighlighter::getVertexColorsOfWire(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColorsOfWire( + const std::string& element, + std::vector& colors +) const { int idx = std::stoi(element.substr(4)); - assert ( idx > 0 ); + assert(idx > 0); // get the vertexes of the wire TopoDS_Shape wire = wMap.FindKey(idx); for (TopExp_Explorer xp(wire, TopAbs_VERTEX); xp.More(); xp.Next()) { @@ -82,16 +90,20 @@ void ReferenceHighlighter::getVertexColorsOfWire(const std::string& element, std // Vertex found? if (vertexIndex > 0) { std::size_t pos = std::size_t(vertexIndex - 1); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } } } -void ReferenceHighlighter::getVertexColorsOfFace(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getVertexColorsOfFace( + const std::string& element, + std::vector& colors +) const { int idx = std::stoi(element.substr(4)); - assert ( idx > 0 ); + assert(idx > 0); // get the vertexes of the face TopoDS_Shape face = fMap.FindKey(idx); for (TopExp_Explorer xp(face, TopAbs_VERTEX); xp.More(); xp.Next()) { @@ -100,14 +112,17 @@ void ReferenceHighlighter::getVertexColorsOfFace(const std::string& element, std // Vertex found? if (vertexIndex > 0) { std::size_t pos = std::size_t(vertexIndex - 1); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } } } -void ReferenceHighlighter::getVertexColors(const std::vector& elements, - std::vector& colors) const +void ReferenceHighlighter::getVertexColors( + const std::vector& elements, + std::vector& colors +) const { colors.resize(vMap.Extent(), defaultColor); @@ -135,16 +150,20 @@ void ReferenceHighlighter::getVertexColors(const std::vector& eleme void ReferenceHighlighter::getEdgeColor(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)) - 1; - assert ( idx >= 0 ); + assert(idx >= 0); std::size_t pos = std::size_t(idx); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } -void ReferenceHighlighter::getEdgeColorsOfWire(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getEdgeColorsOfWire( + const std::string& element, + std::vector& colors +) const { int idx = std::stoi(element.substr(4)); - assert ( idx > 0 ); + assert(idx > 0); // get the edges of the wire TopoDS_Shape wire = wMap.FindKey(idx); for (TopExp_Explorer xp(wire, TopAbs_EDGE); xp.More(); xp.Next()) { @@ -153,16 +172,20 @@ void ReferenceHighlighter::getEdgeColorsOfWire(const std::string& element, std:: // Edge found? if (edgeIndex > 0) { std::size_t pos = std::size_t(edgeIndex - 1); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } } } -void ReferenceHighlighter::getEdgeColorsOfFace(const std::string& element, std::vector& colors) const +void ReferenceHighlighter::getEdgeColorsOfFace( + const std::string& element, + std::vector& colors +) const { int idx = std::stoi(element.substr(4)); - assert ( idx > 0 ); + assert(idx > 0); // get the edges of the faces TopoDS_Shape face = fMap.FindKey(idx); for (TopExp_Explorer xp(face, TopAbs_EDGE); xp.More(); xp.Next()) { @@ -171,14 +194,17 @@ void ReferenceHighlighter::getEdgeColorsOfFace(const std::string& element, std:: // Edge found? if (edgeIndex > 0) { std::size_t pos = std::size_t(edgeIndex - 1); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } } } -void ReferenceHighlighter::getEdgeColors(const std::vector& elements, - std::vector& colors) const +void ReferenceHighlighter::getEdgeColors( + const std::vector& elements, + std::vector& colors +) const { colors.resize(eMap.Extent(), defaultColor); @@ -203,14 +229,17 @@ void ReferenceHighlighter::getEdgeColors(const std::vector& element void ReferenceHighlighter::getFaceColor(const std::string& element, std::vector& colors) const { int idx = std::stoi(element.substr(4)) - 1; - assert ( idx >= 0 ); + assert(idx >= 0); std::size_t pos = std::size_t(idx); - if (pos < colors.size()) + if (pos < colors.size()) { colors[pos] = elementColor; + } } -void ReferenceHighlighter::getFaceColor(const std::string& element, - std::vector& materials) const +void ReferenceHighlighter::getFaceColor( + const std::string& element, + std::vector& materials +) const { int idx = std::stoi(element.substr(4)) - 1; assert(idx >= 0); @@ -220,8 +249,10 @@ void ReferenceHighlighter::getFaceColor(const std::string& element, } } -void ReferenceHighlighter::getFaceColors(const std::vector& elements, - std::vector& colors) const +void ReferenceHighlighter::getFaceColors( + const std::vector& elements, + std::vector& colors +) const { colors.resize(fMap.Extent(), defaultColor); @@ -237,8 +268,10 @@ void ReferenceHighlighter::getFaceColors(const std::vector& element } } -void ReferenceHighlighter::getFaceMaterials(const std::vector& elements, - std::vector& materials) const +void ReferenceHighlighter::getFaceMaterials( + const std::vector& elements, + std::vector& materials +) const { App::Material defaultMaterial; materials.resize(fMap.Extent(), defaultMaterial); diff --git a/src/Mod/Part/Gui/ReferenceHighlighter.h b/src/Mod/Part/Gui/ReferenceHighlighter.h index a866c2ece7..4ae790ec67 100644 --- a/src/Mod/Part/Gui/ReferenceHighlighter.h +++ b/src/Mod/Part/Gui/ReferenceHighlighter.h @@ -34,7 +34,8 @@ #include -namespace PartGui { +namespace PartGui +{ /*! * \brief The ReferenceHighlighter class @@ -50,45 +51,50 @@ public: */ ReferenceHighlighter(const TopoDS_Shape& shape, const Base::Color& color); - void setDefaultColor(const Base::Color& c) { + void setDefaultColor(const Base::Color& c) + { defaultColor = c; } - void setElementColor(const Base::Color& c) { + void setElementColor(const Base::Color& c) + { elementColor = c; } - void setObjectColor(const Base::Color& c) { + void setObjectColor(const Base::Color& c) + { objectColor = c; } /*! * \brief getVertexColors - * \param elements The sub-element names. If this list is empty \a colors will be filled with the default color. + * \param elements The sub-element names. If this list is empty \a colors will be filled with + * the default color. * \param colors The size of the \a colors array is equal to the number of vertexes of the shape */ - void getVertexColors(const std::vector& elements, - std::vector& colors) const; + void getVertexColors(const std::vector& elements, std::vector& colors) const; /*! * \brief getEdgeColors - * \param elements The sub-element names. If this list is empty \a colors will be filled with the default color. + * \param elements The sub-element names. If this list is empty \a colors will be filled with + * the default color. * \param colors The size of the \a colors array is equal to the number of edges of the shape */ - void getEdgeColors(const std::vector& elements, - std::vector& colors) const; + void getEdgeColors(const std::vector& elements, std::vector& colors) const; /*! * \brief getFaceColors - * \param elements The sub-element names. If this list is empty \a colors will be filled with the default color. + * \param elements The sub-element names. If this list is empty \a colors will be filled with + * the default color. * \param colors The size of the \a colors array is equal to the number of faces of the shape */ - void getFaceColors(const std::vector& elements, - std::vector& colors) const; + void getFaceColors(const std::vector& elements, std::vector& colors) const; /*! * \brief getFaceMaterials * \param elements The sub-element names. If this list is empty \a materials will be filled with * the default color. \param materials The size of the \a materials array is equal to the number * of faces of the shape */ - void getFaceMaterials(const std::vector& elements, - std::vector& materials) const; + void getFaceMaterials( + const std::vector& elements, + std::vector& materials + ) const; private: void getVertexColor(const std::string& element, std::vector& colors) const; @@ -112,7 +118,7 @@ private: }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_REFERENCEHIGHLIGHTER_H +#endif // PARTGUI_REFERENCEHIGHLIGHTER_H diff --git a/src/Mod/Part/Gui/SectionCutting.cpp b/src/Mod/Part/Gui/SectionCutting.cpp index 84b5d7226e..74e5359de3 100644 --- a/src/Mod/Part/Gui/SectionCutting.cpp +++ b/src/Mod/Part/Gui/SectionCutting.cpp @@ -81,7 +81,7 @@ struct Refresh static const bool YRange = true; static const bool ZRange = true; }; -} +} // namespace // NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers) SectionCut::SectionCut(QWidget* parent) @@ -142,16 +142,16 @@ void SectionCut::initControls(const Base::BoundBox3d& BoundCompound) // lambda function to set color and transparency auto setColorTransparency = [&](Part::Box* pcBox) { Base::Color cutColor; - long cutTransparency{}; + long cutTransparency {}; auto vpBox = dynamic_cast( - Gui::Application::Instance->getViewProvider(pcBox)); + Gui::Application::Instance->getViewProvider(pcBox) + ); if (vpBox) { cutColor = vpBox->ShapeAppearance.getDiffuseColor(); cutTransparency = vpBox->Transparency.getValue(); ui->CutColor->setColor(cutColor.asValue()); ui->CutTransparencyHS->setValue(int(cutTransparency)); - ui->CutTransparencyHS->setToolTip(QString::number(cutTransparency) - + QStringLiteral(" %")); + ui->CutTransparencyHS->setToolTip(QString::number(cutTransparency) + QStringLiteral(" %")); } }; @@ -160,8 +160,10 @@ void SectionCut::initControls(const Base::BoundBox3d& BoundCompound) initXControls(BoundCompound, setColorTransparency); } -void SectionCut::initXControls(const Base::BoundBox3d& BoundCompound, - const std::function& setTransparency) +void SectionCut::initXControls( + const Base::BoundBox3d& BoundCompound, + const std::function& setTransparency +) { Base::BoundBox3d BoundCutBox; if (auto pcBox = findCutBox(BoxXName)) { @@ -173,16 +175,17 @@ void SectionCut::initXControls(const Base::BoundBox3d& BoundCompound, ui->flipX->setChecked(true); } else { - ui->cutX->setValue(pcBox->Length.getValue() - + pcBox->Placement.getValue().getPosition().x); + ui->cutX->setValue(pcBox->Length.getValue() + pcBox->Placement.getValue().getPosition().x); ui->flipX->setChecked(false); } setTransparency(pcBox); } } -void SectionCut::initYControls(const Base::BoundBox3d& BoundCompound, - const std::function& setTransparency) +void SectionCut::initYControls( + const Base::BoundBox3d& BoundCompound, + const std::function& setTransparency +) { Base::BoundBox3d BoundCutBox; if (auto pcBox = findCutBox(BoxYName)) { @@ -194,16 +197,17 @@ void SectionCut::initYControls(const Base::BoundBox3d& BoundCompound, ui->flipY->setChecked(true); } else { - ui->cutY->setValue(pcBox->Width.getValue() - + pcBox->Placement.getValue().getPosition().y); + ui->cutY->setValue(pcBox->Width.getValue() + pcBox->Placement.getValue().getPosition().y); ui->flipY->setChecked(false); } setTransparency(pcBox); } } -void SectionCut::initZControls(const Base::BoundBox3d& BoundCompound, - const std::function& setTransparency) +void SectionCut::initZControls( + const Base::BoundBox3d& BoundCompound, + const std::function& setTransparency +) { Base::BoundBox3d BoundCutBox; if (auto pcBox = findCutBox(BoxZName)) { @@ -217,8 +221,7 @@ void SectionCut::initZControls(const Base::BoundBox3d& BoundCompound, ui->flipZ->setChecked(true); } else { - ui->cutZ->setValue(pcBox->Height.getValue() - + pcBox->Placement.getValue().getPosition().z); + ui->cutZ->setValue(pcBox->Height.getValue() + pcBox->Placement.getValue().getPosition().z); ui->flipZ->setChecked(false); } // set color and transparency @@ -234,12 +237,26 @@ void SectionCut::initCutRanges() // if there is a cut box, perform the cut if (hasBoxX || hasBoxY || hasBoxZ) { // refresh only the range since we set the values above already - refreshCutRanges(box, Refresh::notXValue, Refresh::notYValue, Refresh::notZValue, - Refresh::XRange, Refresh::YRange, Refresh::ZRange); + refreshCutRanges( + box, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::XRange, + Refresh::YRange, + Refresh::ZRange + ); } else { - refreshCutRanges(box, Refresh::XValue, Refresh::YValue, Refresh::ZValue, - Refresh::XRange, Refresh::YRange, Refresh::ZRange); + refreshCutRanges( + box, + Refresh::XValue, + Refresh::YValue, + Refresh::ZValue, + Refresh::XRange, + Refresh::YRange, + Refresh::ZRange + ); } } } @@ -297,8 +314,9 @@ void SectionCut::initBooleanFragmentControls(Gui::ViewProviderGeometryObject* co ui->BFragColor->setColor(compoundColor.asValue()); long compoundTransparency = compoundBF->Transparency.getValue(); ui->BFragTransparencyHS->setValue(int(compoundTransparency)); - ui->BFragTransparencyHS->setToolTip(QString::number(compoundTransparency) - + QStringLiteral(" %")); + ui->BFragTransparencyHS->setToolTip( + QString::number(compoundTransparency) + QStringLiteral(" %") + ); // Part::Cut ignores the cutbox transparency when it is set // to zero and the BooleanFragments transparency is not zero // therefore limit the cutbox transparency to 1 in this case @@ -462,15 +480,13 @@ void SectionCut::setAutoTransparency(int value) if (ui->autoCutfaceColorCB->isChecked()) { ui->CutTransparencyHS->blockSignals(true); ui->CutTransparencyHS->setValue(value); - ui->CutTransparencyHS->setToolTip(QString::number(value) - + QStringLiteral(" %")); + ui->CutTransparencyHS->setToolTip(QString::number(value) + QStringLiteral(" %")); ui->CutTransparencyHS->blockSignals(false); } if (ui->autoBFColorCB->isChecked()) { ui->BFragTransparencyHS->blockSignals(true); ui->BFragTransparencyHS->setValue(value); - ui->BFragTransparencyHS->setToolTip(QString::number(value) - + QStringLiteral(" %")); + ui->BFragTransparencyHS->setToolTip(QString::number(value) + QStringLiteral(" %")); ui->BFragTransparencyHS->blockSignals(false); } } @@ -484,9 +500,10 @@ void SectionCut::deleteObejcts() anObject = doc->getObject(objectName); // the deleted object might have been visible before, thus check and delete it from the list auto found = std::find_if( - ObjectsListVisible.begin(), ObjectsListVisible.end(), - [anObject](const App::DocumentObjectT &obj) { return (obj.getObject() == anObject); - }); + ObjectsListVisible.begin(), + ObjectsListVisible.end(), + [anObject](const App::DocumentObjectT& obj) { return (obj.getObject() == anObject); } + ); if (found != ObjectsListVisible.end()) { ObjectsListVisible.erase(found); } @@ -497,7 +514,8 @@ void SectionCut::deleteObejcts() // lambda to store the compoundTransparency auto storeTransparency = [&](App::DocumentObject* cutObject) { auto CompoundVP = dynamic_cast( - Gui::Application::Instance->getViewProvider(cutObject)); + Gui::Application::Instance->getViewProvider(cutObject) + ); if (CompoundVP && compoundTransparency == -1) { compoundTransparency = int(CompoundVP->Transparency.getValue()); } @@ -542,13 +560,14 @@ void SectionCut::deleteCompound() // check if this is a BooleanFragments or a Part::Compound auto pcCompoundDelPart = dynamic_cast(compoundObject); - Gui::ViewProvider* pcCompoundDelBF{}; + Gui::ViewProvider* pcCompoundDelBF {}; if (!pcCompoundDelPart) { // check for BooleanFragments pcCompoundDelBF = Gui::Application::Instance->getViewProvider(compoundObject); if (!pcCompoundDelBF) { Base::Console().error( - "Section cut error: compound is incorrectly named, cannot proceed\n"); + "Section cut error: compound is incorrectly named, cannot proceed\n" + ); return; } compoundChilds = pcCompoundDelBF->claimChildren(); @@ -559,9 +578,10 @@ void SectionCut::deleteCompound() // first delete the compound auto foundObj = std::find_if( - ObjectsListVisible.begin(), ObjectsListVisible.end(), - [anObject](const App::DocumentObjectT &obj) { return (obj.getObject() == anObject); - }); + ObjectsListVisible.begin(), + ObjectsListVisible.end(), + [anObject](const App::DocumentObjectT& obj) { return (obj.getObject() == anObject); } + ); if (foundObj != ObjectsListVisible.end()) { ObjectsListVisible.erase(foundObj); } @@ -569,10 +589,13 @@ void SectionCut::deleteCompound() // now delete the objects that have been part of the compound for (auto aChild : compoundChilds) { anObject = doc->getObject(aChild->getNameInDocument()); - auto foundObjInner = std::find_if(ObjectsListVisible.begin(), ObjectsListVisible.end(), - [anObject](const App::DocumentObjectT &objInner) { - return (objInner.getObject() == anObject); - }); + auto foundObjInner = std::find_if( + ObjectsListVisible.begin(), + ObjectsListVisible.end(), + [anObject](const App::DocumentObjectT& objInner) { + return (objInner.getObject() == anObject); + } + ); if (foundObjInner != ObjectsListVisible.end()) { ObjectsListVisible.erase((foundObjInner)); } @@ -604,8 +627,10 @@ Part::Box* SectionCut::createBox(const char* name, const Base::Vector3f& size) // create a box auto pcBox = doc->addObject(name); if (!pcBox) { - throw Base::RuntimeError(std::string("Section cut error: ") - + std::string(name) + std::string(" could not be added\n")); + throw Base::RuntimeError( + std::string("Section cut error: ") + std::string(name) + + std::string(" could not be added\n") + ); } // it appears that because of internal rounding errors, the bounding box is sometimes @@ -628,24 +653,30 @@ Part::Box* SectionCut::tryCreateXBox(const Base::Vector3f& pos, const Base::Vect } } -std::tuple SectionCut::tryCreateXBoxAndCut(const Base::Vector3f& pos, - const Base::Vector3f& size) +std::tuple SectionCut::tryCreateXBoxAndCut( + const Base::Vector3f& pos, + const Base::Vector3f& size +) { auto pcBox = tryCreateXBox(pos, size); auto pcCut = tryCreateCut(CutXName); return {pcBox, pcCut}; } -std::tuple SectionCut::tryCreateYBoxAndCut(const Base::Vector3f& pos, - const Base::Vector3f& size) +std::tuple SectionCut::tryCreateYBoxAndCut( + const Base::Vector3f& pos, + const Base::Vector3f& size +) { auto pcBox = tryCreateYBox(pos, size); auto pcCut = tryCreateCut(CutYName); return {pcBox, pcCut}; } -std::tuple SectionCut::tryCreateZBoxAndCut(const Base::Vector3f& pos, - const Base::Vector3f& size) +std::tuple SectionCut::tryCreateZBoxAndCut( + const Base::Vector3f& pos, + const Base::Vector3f& size +) { auto pcBox = tryCreateZBox(pos, size); auto pcCut = tryCreateCut(CutZName); @@ -661,10 +692,10 @@ Part::Box* SectionCut::createXBox(const Base::Vector3f& pos, const Base::Vector3 // the previous value might now be outside the current possible range, then reset it double CutPosX = ui->cutX->value(); if (CutPosX >= ui->cutX->maximum()) { - CutPosX = ui->cutX->maximum() - 0.1; // short below the maximum + CutPosX = ui->cutX->maximum() - 0.1; // short below the maximum } else if (CutPosX <= ui->cutX->minimum()) { - CutPosX = ui->cutX->minimum() + 0.1; // short above the minimum + CutPosX = ui->cutX->minimum() + 0.1; // short above the minimum } // set the cut value ui->cutX->setValue(CutPosX); @@ -708,10 +739,10 @@ Part::Box* SectionCut::createYBox(const Base::Vector3f& pos, const Base::Vector3 // reset previous cut value double CutPosY = ui->cutY->value(); if (CutPosY >= ui->cutY->maximum()) { - CutPosY = ui->cutY->maximum() - 0.1; // short below the maximum + CutPosY = ui->cutY->maximum() - 0.1; // short below the maximum } else if (CutPosY <= ui->cutY->minimum()) { - CutPosY = ui->cutY->minimum() + 0.1; // short above the minimum + CutPosY = ui->cutY->minimum() + 0.1; // short above the minimum } // set the cut value @@ -752,10 +783,10 @@ Part::Box* SectionCut::createZBox(const Base::Vector3f& pos, const Base::Vector3 // reset previous cut value double CutPosZ = ui->cutZ->value(); if (CutPosZ >= ui->cutZ->maximum()) { - CutPosZ = ui->cutZ->maximum() - 0.1; // short below the maximum + CutPosZ = ui->cutZ->maximum() - 0.1; // short below the maximum } else if (CutPosZ <= ui->cutZ->minimum()) { - CutPosZ = ui->cutZ->minimum() + 0.1; // short above the minimum + CutPosZ = ui->cutZ->minimum() + 0.1; // short above the minimum } // set the cut value @@ -783,8 +814,10 @@ Part::Cut* SectionCut::createCut(const char* name) { auto pcCut = doc->addObject(name); if (!pcCut) { - throw Base::RuntimeError(std::string("Section cut error: ") - + std::string(name) + std::string(" could not be added\n")); + throw Base::RuntimeError( + std::string("Section cut error: ") + std::string(name) + + std::string(" could not be added\n") + ); } return pcCut; @@ -852,12 +885,10 @@ bool SectionCut::findObjects(std::vector& objects) } } // get all shapes that are also Part::Features - if (object->getPropertyByName("Shape") != nullptr - && object->isDerivedFrom()) { + if (object->getPropertyByName("Shape") != nullptr && object->isDerivedFrom()) { // sort out 2D objects, datums, App:Parts, compounds and objects that are // part of a PartDesign body - if (!object->isDerivedFrom() - && !object->isDerivedFrom() + if (!object->isDerivedFrom() && !object->isDerivedFrom() && !object->isDerivedFrom(Base::Type::fromName("PartDesign::Feature")) && !object->isDerivedFrom() && object->getTypeId() != Base::Type::fromName("App::Part")) { @@ -867,8 +898,7 @@ bool SectionCut::findObjects(std::vector& objects) // get Links that are derived from Part objects if (auto pcLink = dynamic_cast(object)) { auto linkedObject = doc->getObject(pcLink->LinkedObject.getObjectName()); - if (linkedObject != nullptr - && linkedObject->isDerivedFrom()) { + if (linkedObject != nullptr && linkedObject->isDerivedFrom()) { objects.push_back(object); } } @@ -882,23 +912,20 @@ void SectionCut::filterObjects(std::vector& objects) // sort out objects that are part of Part::Boolean, Part::MultiCommon, Part::MultiFuse, // Part::Thickness and Part::FilletBase // check list of visible objects and not cut list because we want to remove from the cut list - for (auto &aVisObject : ObjectsListVisible) { + for (auto& aVisObject : ObjectsListVisible) { App::DocumentObject* object = aVisObject.getObject(); if (!object) { continue; } - if (object->isDerivedFrom() - || object->isDerivedFrom() - || object->isDerivedFrom() - || object->isDerivedFrom() + if (object->isDerivedFrom() || object->isDerivedFrom() + || object->isDerivedFrom() || object->isDerivedFrom() || object->isDerivedFrom()) { // get possible links auto subObjectList = object->getOutList(); // if there are links, delete them if (!subObjectList.empty()) { for (auto aSubObj : subObjectList) { - for (auto itCutObj = objects.begin(); itCutObj != objects.end(); - ++itCutObj) { + for (auto itCutObj = objects.begin(); itCutObj != objects.end(); ++itCutObj) { if (aSubObj == *itCutObj) { objects.erase(itCutObj); break; @@ -927,12 +954,14 @@ bool SectionCut::isCuttingEnabled() const return ui->groupBoxX->isChecked() || ui->groupBoxY->isChecked() || ui->groupBoxZ->isChecked(); } -namespace { +namespace +{ Base::Color getFirstColor(const std::vector& objects) { Base::Color cutColor; auto vpFirstObject = dynamic_cast( - Gui::Application::Instance->getViewProvider(objects.front())); + Gui::Application::Instance->getViewProvider(objects.front()) + ); if (vpFirstObject) { cutColor = vpFirstObject->ShapeAppearance.getDiffuseColor(); } @@ -943,7 +972,8 @@ long getFirstTransparency(const std::vector& objects) { long cutTransparency {0}; auto vpFirstObject = dynamic_cast( - Gui::Application::Instance->getViewProvider(objects.front())); + Gui::Application::Instance->getViewProvider(objects.front()) + ); if (vpFirstObject) { cutTransparency = vpFirstObject->Transparency.getValue(); } @@ -955,7 +985,8 @@ bool isAutoColor(const Base::Color& color, const std::vector( - Gui::Application::Instance->getViewProvider(itCuts)); + Gui::Application::Instance->getViewProvider(itCuts) + ); if (vpObject) { if (color != vpObject->ShapeAppearance.getDiffuseColor()) { autoColor = false; @@ -972,7 +1003,8 @@ bool isAutoTransparency(long transparency, const std::vector( - Gui::Application::Instance->getViewProvider(itCuts)); + Gui::Application::Instance->getViewProvider(itCuts) + ); if (vpObject) { if (transparency != vpObject->Transparency.getValue()) { autoTransparency = false; @@ -984,7 +1016,10 @@ bool isAutoTransparency(long transparency, const std::vector createLinks(App::Document* doc, const std::vector& objects) +std::vector createLinks( + App::Document* doc, + const std::vector& objects +) { std::vector links; for (auto itCuts : objects) { @@ -1018,7 +1053,8 @@ std::vector createLinks(App::Document* doc, const std::vec if (auto parents = itCuts->getInList(); !parents.empty()) { for (auto parent : parents) { if (auto pcPartParent = dynamic_cast(parent)) { - if (auto placement = pcPartParent->getPropertyByName("Placement")) { + if (auto placement + = pcPartParent->getPropertyByName("Placement")) { pcLink->Placement.setValue(placement->getValue()); } } @@ -1050,11 +1086,11 @@ void setMinOrMax(double value, QPushButton* button, QDoubleSpinBox* spinBox) } } -} +} // namespace void SectionCut::setObjectsVisible(bool value) { - for (auto &aVisObject : ObjectsListVisible) { + for (auto& aVisObject : ObjectsListVisible) { App::DocumentObject* object = aVisObject.getObject(); if (object) { object->Visibility.setValue(value); @@ -1084,7 +1120,8 @@ void SectionCut::startObjectCutting(bool isInitial) bool isLinkAssembly = findObjects(ObjectsListCut); if (isLinkAssembly) { - // we disable the sliders because for assemblies it will takes ages to do several dozen recomputes + // we disable the sliders because for assemblies it will takes ages to do several dozen + // recomputes setSlidersEnabled(false); setSlidersToolTip(tr("Sliders are disabled for assemblies")); } @@ -1128,9 +1165,15 @@ std::tuple SectionCut::adjustRanges() } // refresh all cut limits according to the new bounding box - refreshCutRanges(CompoundBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::notZValue, Refresh::XRange, Refresh::YRange, - Refresh::ZRange); + refreshCutRanges( + CompoundBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::XRange, + Refresh::YRange, + Refresh::ZRange + ); // prepare the cut box size according to the bounding box size Base::Vector3f BoundingBoxSize; @@ -1146,17 +1189,29 @@ void SectionCut::adjustYRange() { auto CutBoundingBox = getViewBoundingBox(); // refresh the Y cut limits according to the new bounding box - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::notZValue, Refresh::notXRange, Refresh::YRange, - Refresh::notZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::notZRange + ); } void SectionCut::adjustZRange() { auto CutBoundingBox = getViewBoundingBox(); - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::notZValue, Refresh::notXRange, Refresh::notYRange, - Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::notYRange, + Refresh::ZRange + ); } void SectionCut::resetHasBoxes() @@ -1167,9 +1222,11 @@ void SectionCut::resetHasBoxes() hasBoxCustom = false; } -App::DocumentObject* SectionCut::getCutXBase(size_t num, - App::DocumentObject* comp, - App::DocumentObject* frag) const +App::DocumentObject* SectionCut::getCutXBase( + size_t num, + App::DocumentObject* comp, + App::DocumentObject* frag +) const { if (num == 1 || !(ui->groupBoxIntersecting->isChecked())) { return comp; @@ -1178,9 +1235,11 @@ App::DocumentObject* SectionCut::getCutXBase(size_t num, return frag; } -App::DocumentObject* SectionCut::getCutYBase(size_t num, - App::DocumentObject* comp, - App::DocumentObject* frag) const +App::DocumentObject* SectionCut::getCutYBase( + size_t num, + App::DocumentObject* comp, + App::DocumentObject* frag +) const { // if there is already a cut, we must take it as feature to be cut if (hasBoxX) { @@ -1194,9 +1253,11 @@ App::DocumentObject* SectionCut::getCutYBase(size_t num, return frag; } -App::DocumentObject* SectionCut::getCutZBase(size_t num, - App::DocumentObject* comp, - App::DocumentObject* frag) const +App::DocumentObject* SectionCut::getCutZBase( + size_t num, + App::DocumentObject* comp, + App::DocumentObject* frag +) const { if (hasBoxY) { return doc->getObject(CutYName); @@ -1299,7 +1360,7 @@ void SectionCut::createAllObjects(const std::vector& Objec if (ui->groupBoxIntersecting->isChecked() && ObjectsListCut.size() > 1) { CutCompoundBF = createBooleanFragments(ObjectsListLinks, compoundTransparency); } - else { // create Part::Compound and fill it + else { // create Part::Compound and fill it // if there is only one object to be cut, we cannot create a BooleanFragments object CutCompoundPart = createCompound(ObjectsListLinks, compoundTransparency); } @@ -1328,7 +1389,8 @@ void SectionCut::createAllObjects(const std::vector& Objec // lambda function to set shape color and transparency auto setColorTransparency = [&](Part::Box* pcBox) { auto vpBox = dynamic_cast( - Gui::Application::Instance->getViewProvider(pcBox)); + Gui::Application::Instance->getViewProvider(pcBox) + ); if (vpBox) { vpBox->ShapeAppearance.setDiffuseColor(boxColor); vpBox->Transparency.setValue(boxTransparency); @@ -1338,20 +1400,23 @@ void SectionCut::createAllObjects(const std::vector& Objec // lambda function to set transparency auto setTransparency = [&](Part::Cut* pcCut) { auto vpCut = dynamic_cast( - Gui::Application::Instance->getViewProvider(pcCut)); + Gui::Application::Instance->getViewProvider(pcCut) + ); if (vpCut) { vpCut->Transparency.setValue(compoundTransparency); } }; if (ui->groupBoxX->isChecked()) { - processXBoxAndCut({BoundingBoxOrigin, - BoundingBoxSize, - ObjectsListCut.size(), - CutCompoundPart, - CutCompoundBF, - setColorTransparency, - setTransparency}); + processXBoxAndCut( + {BoundingBoxOrigin, + BoundingBoxSize, + ObjectsListCut.size(), + CutCompoundPart, + CutCompoundBF, + setColorTransparency, + setTransparency} + ); } if (ui->groupBoxY->isChecked()) { // if there is a X cut, its size defines the possible range for the Y cut @@ -1360,26 +1425,30 @@ void SectionCut::createAllObjects(const std::vector& Objec adjustYRange(); } - processYBoxAndCut({BoundingBoxOrigin, - BoundingBoxSize, - ObjectsListCut.size(), - CutCompoundPart, - CutCompoundBF, - setColorTransparency, - setTransparency}); + processYBoxAndCut( + {BoundingBoxOrigin, + BoundingBoxSize, + ObjectsListCut.size(), + CutCompoundPart, + CutCompoundBF, + setColorTransparency, + setTransparency} + ); } if (ui->groupBoxZ->isChecked()) { if (hasBoxX || hasBoxY) { adjustZRange(); } - processZBoxAndCut({BoundingBoxOrigin, - BoundingBoxSize, - ObjectsListCut.size(), - CutCompoundPart, - CutCompoundBF, - setColorTransparency, - setTransparency}); + processZBoxAndCut( + {BoundingBoxOrigin, + BoundingBoxSize, + ObjectsListCut.size(), + CutCompoundPart, + CutCompoundBF, + setColorTransparency, + setTransparency} + ); } } @@ -1389,10 +1458,9 @@ SectionCut* SectionCut::makeDockWidget(QWidget* parent) auto sectionCut = new SectionCut(parent); Gui::DockWindowManager* pDockMgr = Gui::DockWindowManager::instance(); // the dialog is designed that you can see the tree, thus put it to the right side - QDockWidget *dw = - pDockMgr->addDockWindow("Section cutting", sectionCut, Qt::RightDockWidgetArea); + QDockWidget* dw = pDockMgr->addDockWindow("Section cutting", sectionCut, Qt::RightDockWidgetArea); dw->setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); - //dw->setFloating(true); + // dw->setFloating(true); dw->show(); return sectionCut; @@ -1456,15 +1524,15 @@ void SectionCut::CutValueHelper(double value, QDoubleSpinBox* SpinBox, QSlider* if (Slider->isEnabled()) { Slider->blockSignals(true); Slider->setValue( - int((value - SpinBox->minimum()) - / (SpinBox->maximum() - SpinBox->minimum()) * 100.0)); + int((value - SpinBox->minimum()) / (SpinBox->maximum() - SpinBox->minimum()) * 100.0) + ); Slider->setToolTip(QString::number(value, 'g', Base::UnitsApi::getDecimals())); Slider->blockSignals(false); } // we cannot cut to the edge because then the result is an empty shape - // we chose purposely not to simply set the range for cutX previously - // because everything is allowed just not the min/max + // we chose purposely not to simply set the range for cutX previously + // because everything is allowed just not the min/max if (SpinBox->value() == SpinBox->maximum()) { SpinBox->setValue(SpinBox->maximum() - 0.1); return; @@ -1482,7 +1550,7 @@ double SectionCut::getPosX(Part::Box* box) const value = ui->cutX->value() - box->Length.getValue(); } else { - //flipped + // flipped value = ui->cutX->value(); } @@ -1496,7 +1564,7 @@ double SectionCut::getPosY(Part::Box* box) const value = ui->cutY->value() - box->Width.getValue(); } else { - //flipped + // flipped value = ui->cutY->value(); } @@ -1510,7 +1578,7 @@ double SectionCut::getPosZ(Part::Box* box) const value = ui->cutZ->value() - box->Height.getValue(); } else { - //flipped + // flipped value = ui->cutZ->value(); } @@ -1520,34 +1588,61 @@ double SectionCut::getPosZ(Part::Box* box) const void SectionCut::adjustYZRanges(SbBox3f CutBoundingBox) { if (hasBoxY) { - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::notZValue, Refresh::notXRange, Refresh::YRange, - Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); // the value of Y or Z can now be outside or at the limit, in this case reset the value too - if ((ui->cutY->value() >= ui->cutY->maximum()) - || (ui->cutY->value() <= ui->cutY->minimum())) { - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::YValue, - Refresh::notZValue, Refresh::notXRange, Refresh::YRange, - Refresh::ZRange); + if ((ui->cutY->value() >= ui->cutY->maximum()) || (ui->cutY->value() <= ui->cutY->minimum())) { + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::YValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); } - if ((ui->cutZ->value() >= ui->cutZ->maximum()) - || (ui->cutZ->value() <= ui->cutZ->minimum())) { - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::ZValue, Refresh::notXRange, Refresh::YRange, - Refresh::ZRange); + if ((ui->cutZ->value() >= ui->cutZ->maximum()) || (ui->cutZ->value() <= ui->cutZ->minimum())) { + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); } } else { // there is no Y cut yet so we can set the Y value too - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::YValue, - Refresh::notZValue, Refresh::notXRange, Refresh::YRange, - Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::YValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); // the value of Z can now be outside or at the limit, in this case reset the value too - if ((ui->cutZ->value() >= ui->cutZ->maximum()) - || (ui->cutZ->value() <= ui->cutZ->minimum())) { - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::YValue, - Refresh::ZValue, Refresh::notXRange, Refresh::YRange, - Refresh::ZRange); + if ((ui->cutZ->value() >= ui->cutZ->maximum()) || (ui->cutZ->value() <= ui->cutZ->minimum())) { + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::YValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); } } } @@ -1566,7 +1661,8 @@ void SectionCut::onCutXvalueChanged(double val) auto pcBox = dynamic_cast(CutBox); if (!pcBox) { Base::Console().error((std::string("Section cut error: ") + std::string(BoxXName) - + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Box object. Cannot proceed.\n")) + .c_str()); return; } // get its placement and size @@ -1586,7 +1682,7 @@ void SectionCut::onCutXvalueChanged(double val) // if there is another cut, we must recalculate it too // we might have cut so that the range for Y and Z is now smaller // the hierarchy is always Z->Y->X - if (hasBoxY && !hasBoxZ) { // only Y + if (hasBoxY && !hasBoxZ) { // only Y auto CutFeatureY = findOrCreateObject(CutYName); if (!CutFeatureY) { return; @@ -1599,13 +1695,26 @@ void SectionCut::onCutXvalueChanged(double val) // get new bounding box auto CutBoundingBox = getViewBoundingBox(); // refresh Y limits and Z limits + Z value - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, Refresh::ZValue, - Refresh::notXRange, Refresh::YRange, Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); // the value of Y can now be outside or at the limit, in this case reset the value too - if ((ui->cutY->value() >= ui->cutY->maximum()) - || (ui->cutY->value() <= ui->cutY->minimum())) { - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::YValue, Refresh::ZValue, - Refresh::notXRange, Refresh::YRange, Refresh::ZRange); + if ((ui->cutY->value() >= ui->cutY->maximum()) || (ui->cutY->value() <= ui->cutY->minimum())) { + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::YValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); } // make the SectionCutY visible again CutFeatureY->Visibility.setValue(true); @@ -1614,7 +1723,7 @@ void SectionCut::onCutXvalueChanged(double val) // recompute the cut CutFeatureY->recomputeFeature(true); } - else if (hasBoxZ) { // at least Z + else if (hasBoxZ) { // at least Z // the main cut is Z, no matter if there is a cut in Y auto CutFeatureZ = findOrCreateObject(CutZName); if (!CutFeatureZ) { @@ -1634,16 +1743,24 @@ void SectionCut::onCutXvalueChanged(double val) // recompute the cut CutFeatureZ->recomputeFeature(true); } - else { // just X + else { // just X // refresh Y and Z limits + values auto CutBoundingBox = getViewBoundingBox(); - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::YValue, Refresh::ZValue, - Refresh::notXRange, Refresh::YRange, Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::YValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::ZRange + ); // recompute the cut auto pcCut = dynamic_cast(CutObject); if (!pcCut) { Base::Console().error((std::string("Section cut error: ") + std::string(CutZName) - + std::string(" is no Part::Cut object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Cut object. Cannot proceed.\n")) + .c_str()); return; } pcCut->recomputeFeature(true); @@ -1687,7 +1804,8 @@ void SectionCut::onCutYvalueChanged(double val) auto pcBox = dynamic_cast(CutBox); if (!pcBox) { Base::Console().error((std::string("Section cut error: ") + std::string(BoxYName) - + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Box object. Cannot proceed.\n")) + .c_str()); return; } Base::Placement placement = pcBox->Placement.getValue(); @@ -1709,7 +1827,8 @@ void SectionCut::onCutYvalueChanged(double val) auto CutFeatureZ = findObject(CutZName); if (!CutFeatureZ) { Base::Console().error((std::string("Section cut error: there is no ") - + std::string(CutZName) + std::string("\n")).c_str()); + + std::string(CutZName) + std::string("\n")) + .c_str()); return; } // refresh the Z cut limits according to the new bounding box of the cut result @@ -1720,14 +1839,26 @@ void SectionCut::onCutYvalueChanged(double val) // get new bounding box auto CutBoundingBox = getViewBoundingBox(); // refresh Z limits - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, Refresh::notZValue, - Refresh::notXRange, Refresh::notYRange, Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::notYRange, + Refresh::ZRange + ); // the value of Z can now be outside or at the limit, in this case reset the value too - if ((ui->cutZ->value() >= ui->cutZ->maximum()) - || (ui->cutZ->value() <= ui->cutZ->minimum())) { - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::ZValue, Refresh::notXRange, Refresh::notYRange, - Refresh::ZRange); + if ((ui->cutZ->value() >= ui->cutZ->maximum()) || (ui->cutZ->value() <= ui->cutZ->minimum())) { + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::notYRange, + Refresh::ZRange + ); } // make the SectionCutZ visible again CutFeatureZ->Visibility.setValue(true); @@ -1736,16 +1867,24 @@ void SectionCut::onCutYvalueChanged(double val) // recompute the cut CutFeatureZ->recomputeFeature(true); } - else { // just Y + else { // just Y // refresh Z limits + values auto CutBoundingBox = getViewBoundingBox(); - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, Refresh::ZValue, - Refresh::notXRange, Refresh::notYRange, Refresh::ZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::ZValue, + Refresh::notXRange, + Refresh::notYRange, + Refresh::ZRange + ); // recompute the cut auto pcCut = dynamic_cast(CutObject); if (!pcCut) { Base::Console().error((std::string("Section cut error: ") + std::string(CutZName) - + std::string(" is no Part::Cut object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Cut object. Cannot proceed.\n")) + .c_str()); return; } pcCut->recomputeFeature(true); @@ -1765,9 +1904,15 @@ void SectionCut::onCutYvalueChanged(double val) CutBoxX->Visibility.setValue(true); // set new XRange auto CutBoundingBox = getViewBoundingBox(); - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, - Refresh::notZValue, Refresh::XRange, Refresh::notYRange, - Refresh::notZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::XRange, + Refresh::notYRange, + Refresh::notZRange + ); // hide cutting box and compare resultwith stored value CutBoxX->Visibility.setValue(false); setMinOrMax(storedX, ui->flipX, ui->cutX); @@ -1809,7 +1954,8 @@ void SectionCut::onCutZvalueChanged(double val) auto pcBox = dynamic_cast(CutBox); if (!pcBox) { Base::Console().error((std::string("Section cut error: ") + std::string(BoxZName) - + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Box object. Cannot proceed.\n")) + .c_str()); return; } Base::Placement placement = pcBox->Placement.getValue(); @@ -1826,7 +1972,8 @@ void SectionCut::onCutZvalueChanged(double val) auto pcCut = dynamic_cast(CutObject); if (!pcCut) { Base::Console().error((std::string("Section cut error: ") + std::string(CutZName) - + std::string(" is no Part::Cut object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Cut object. Cannot proceed.\n")) + .c_str()); return; } pcCut->recomputeFeature(true); @@ -1848,8 +1995,15 @@ void SectionCut::onCutZvalueChanged(double val) CutBoxX->Visibility.setValue(true); // set new XRange CutBoundingBox = getViewBoundingBox(); - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, Refresh::notZValue, - Refresh::XRange, Refresh::notYRange, Refresh::notZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::XRange, + Refresh::notYRange, + Refresh::notZRange + ); // hide cutting box and compare resultwith stored value CutBoxX->Visibility.setValue(false); @@ -1863,8 +2017,15 @@ void SectionCut::onCutZvalueChanged(double val) double storedY = getMinOrMax(ui->flipY, ui->cutY); CutBoxY->Visibility.setValue(true); CutBoundingBox = getViewBoundingBox(); - refreshCutRanges(CutBoundingBox, Refresh::notXValue, Refresh::notYValue, Refresh::notZValue, - Refresh::notXRange, Refresh::YRange, Refresh::notZRange); + refreshCutRanges( + CutBoundingBox, + Refresh::notXValue, + Refresh::notYValue, + Refresh::notZValue, + Refresh::notXRange, + Refresh::YRange, + Refresh::notZRange + ); CutBoxY->Visibility.setValue(false); setMinOrMax(storedY, ui->flipY, ui->cutY); } @@ -1915,39 +2076,39 @@ void SectionCut::FlipClickedHelper(const char* BoxName) auto pcBox = dynamic_cast(CutBox); if (!pcBox) { Base::Console().error((std::string("Section cut error: ") + std::string(BoxName) - + std::string(" is no Part::Box object. Cannot proceed.\n")).c_str()); + + std::string(" is no Part::Box object. Cannot proceed.\n")) + .c_str()); return; } // get its placement and size Base::Placement placement = pcBox->Placement.getValue(); Base::Vector3d BoxPosition = placement.getPosition(); // flip the box - switch (std::string(BoxName).back()) - { - case 'X': - if (ui->flipX->isChecked()) { - BoxPosition.x = BoxPosition.x + pcBox->Length.getValue(); - } - else { - BoxPosition.x = BoxPosition.x - pcBox->Length.getValue(); - } - break; - case 'Y': - if (ui->flipY->isChecked()) { - BoxPosition.y = BoxPosition.y + pcBox->Width.getValue(); - } - else { - BoxPosition.y = BoxPosition.y - pcBox->Width.getValue(); - } - break; - case 'Z': - if (ui->flipZ->isChecked()) { - BoxPosition.z = BoxPosition.z + pcBox->Height.getValue(); - } - else { - BoxPosition.z = BoxPosition.z - pcBox->Height.getValue(); - } - break; + switch (std::string(BoxName).back()) { + case 'X': + if (ui->flipX->isChecked()) { + BoxPosition.x = BoxPosition.x + pcBox->Length.getValue(); + } + else { + BoxPosition.x = BoxPosition.x - pcBox->Length.getValue(); + } + break; + case 'Y': + if (ui->flipY->isChecked()) { + BoxPosition.y = BoxPosition.y + pcBox->Width.getValue(); + } + else { + BoxPosition.y = BoxPosition.y - pcBox->Width.getValue(); + } + break; + case 'Z': + if (ui->flipZ->isChecked()) { + BoxPosition.z = BoxPosition.z + pcBox->Height.getValue(); + } + else { + BoxPosition.z = BoxPosition.z - pcBox->Height.getValue(); + } + break; } placement.setPosition(BoxPosition); pcBox->Placement.setValue(placement); @@ -2024,7 +2185,8 @@ App::DocumentObject* SectionCut::findOrCreateObject(const char* objName) auto object = findObject(objName); if (!object) { Base::Console().warning((std::string("Section cut warning: there is no ") - + std::string(objName) + std::string(", trying to recreate it\n")).c_str()); + + std::string(objName) + std::string(", trying to recreate it\n")) + .c_str()); startCutting(); return nullptr; } @@ -2136,7 +2298,7 @@ void SectionCut::onBFragColorclicked() // sets BooleanFragments color void SectionCut::setBooleanFragmentsColor() { - App::DocumentObject* compoundObject{}; + App::DocumentObject* compoundObject {}; if (doc->getObject(CompoundName)) { // get the object with the right name compoundObject = doc->getObject(CompoundName); @@ -2172,8 +2334,7 @@ void SectionCut::onBFragTransparencyHSMoved(int val) auto setTransparency = [&](App::DocumentObject* cutObject) { Gui::ViewProvider* CutVP = Gui::Application::Instance->getViewProvider(cutObject); if (!CutVP) { - Base::Console().error( - "Section cut error: cannot access ViewProvider of cut object\n"); + Base::Console().error("Section cut error: cannot access ViewProvider of cut object\n"); return; } auto CutVPGeom = dynamic_cast(CutVP); @@ -2280,17 +2441,17 @@ SbBox3f SectionCut::getViewBoundingBox() auto docGui = Gui::Application::Instance->activeDocument(); if (!docGui) { Base::Console().error("Section cut error: there is no active document\n"); - return Box; // return an empty box + return Box; // return an empty box } auto view = dynamic_cast(docGui->getActiveView()); if (!view) { Base::Console().error("Section cut error: could not get the active view\n"); - return Box; // return an empty box + return Box; // return an empty box } Gui::View3DInventorViewer* viewer = view->getViewer(); SoCamera* camera = viewer->getSoRenderManager()->getCamera(); if (!camera) { - return Box; // return an empty box + return Box; // return an empty box } // get scene bounding box SoGetBoundingBoxAction action(viewer->getSoRenderManager()->getViewportRegion()); @@ -2298,22 +2459,28 @@ SbBox3f SectionCut::getViewBoundingBox() return action.getBoundingBox(); } -void SectionCut::refreshCutRanges(SbBox3f BoundingBox, - bool forXValue, bool forYValue, bool forZValue, - bool forXRange, bool forYRange, bool forZRange) +void SectionCut::refreshCutRanges( + SbBox3f BoundingBox, + bool forXValue, + bool forYValue, + bool forZValue, + bool forXRange, + bool forYRange, + bool forZRange +) { if (!BoundingBox.isEmpty()) { // NOLINT SbVec3f center = BoundingBox.getCenter(); int minDecimals = Base::UnitsApi::getDecimals(); - float lenx{}; - float leny{}; - float lenz{}; + float lenx {}; + float leny {}; + float lenz {}; BoundingBox.getSize(lenx, leny, lenz); const int steps = 100; // set the ranges - float rangeMin{}; - float rangeMax{}; + float rangeMin {}; + float rangeMax {}; if (forXRange) { rangeMin = center[0] - (lenx / 2); rangeMax = center[0] + (lenx / 2); @@ -2368,14 +2535,17 @@ App::DocumentObject* SectionCut::CreateBooleanFragments(App::Document* doc) // create the object Gui::Command::doCommand(Gui::Command::Doc, "import FreeCAD"); Gui::Command::doCommand(Gui::Command::Doc, "from BOPTools import SplitFeatures"); - Gui::Command::doCommand(Gui::Command::Doc, - "SplitFeatures.makeBooleanFragments(name=\"%s\")", - CompoundName); + Gui::Command::doCommand( + Gui::Command::Doc, + "SplitFeatures.makeBooleanFragments(name=\"%s\")", + CompoundName + ); // check for success App::DocumentObject* object = doc->getObject(CompoundName); if (!object) { Base::Console().error((std::string("Section cut error: ") + std::string(CompoundName) - + std::string(" could not be added\n")).c_str()); + + std::string(" could not be added\n")) + .c_str()); return nullptr; } return object; @@ -2383,17 +2553,20 @@ App::DocumentObject* SectionCut::CreateBooleanFragments(App::Document* doc) } App::DocumentObject* SectionCut::createBooleanFragments( - const std::vector& links, - int transparency) + const std::vector& links, + int transparency +) { App::DocumentObject* CutCompoundBF = CreateBooleanFragments(doc); // the BooleanFragment implementation requires to first add at least 2 objects // before any other setting to the BooleanFragment object can be made auto CutLinkList = dynamic_cast( - CutCompoundBF ? CutCompoundBF->getPropertyByName("Objects") : nullptr); + CutCompoundBF ? CutCompoundBF->getPropertyByName("Objects") : nullptr + ); if (!CutLinkList) { throw Base::RuntimeError((std::string("Section cut error: ") + std::string(CompoundName) - + std::string(" could not be added\n")).c_str()); + + std::string(" could not be added\n")) + .c_str()); } CutLinkList->setValue(links); // make all objects in the BooleanFragments object invisible to later only show the cut @@ -2402,7 +2575,8 @@ App::DocumentObject* SectionCut::createBooleanFragments( } // set the transparency auto vpCompound = dynamic_cast( - Gui::Application::Instance->getViewProvider(CutCompoundBF)); + Gui::Application::Instance->getViewProvider(CutCompoundBF) + ); vpCompound->Transparency.setValue(transparency); // set the color // setBooleanFragmentsColor also does a non-recursive recompute @@ -2411,20 +2585,21 @@ App::DocumentObject* SectionCut::createBooleanFragments( return CutCompoundBF; } -Part::Compound* SectionCut::createCompound(const std::vector& links, - int transparency) +Part::Compound* SectionCut::createCompound(const std::vector& links, int transparency) { auto CutCompoundPart = doc->addObject(CompoundName); if (!CutCompoundPart) { throw Base::RuntimeError((std::string("Section cut error: ") + std::string(CompoundName) - + std::string(" could not be added\n")).c_str()); + + std::string(" could not be added\n")) + .c_str()); } // add the link to the compound CutCompoundPart->Links.setValue(links); // set the transparency auto vpCompound = dynamic_cast( - Gui::Application::Instance->getViewProvider(CutCompoundPart)); + Gui::Application::Instance->getViewProvider(CutCompoundPart) + ); vpCompound->Transparency.setValue(transparency); CutCompoundPart->recomputeFeature(); diff --git a/src/Mod/Part/Gui/SectionCutting.h b/src/Mod/Part/Gui/SectionCutting.h index b3245871fb..e5723f31f5 100644 --- a/src/Mod/Part/Gui/SectionCutting.h +++ b/src/Mod/Part/Gui/SectionCutting.h @@ -39,17 +39,19 @@ namespace Gui class ViewProviderGeometryObject; } -namespace Part { +namespace Part +{ class Box; class Cut; class Compound; -} +} // namespace Part -namespace PartGui { +namespace PartGui +{ class Ui_SectionCut; -class SectionCut : public QDialog +class SectionCut: public QDialog { Q_OBJECT @@ -129,15 +131,25 @@ private: void setObjectsVisible(bool value); int getCompoundTransparency() const; static SbBox3f getViewBoundingBox(); - void refreshCutRanges(SbBox3f, bool forXValue, bool forYValue, bool forZValue, - bool forXRange, bool forYRange, bool forZRange); + void refreshCutRanges( + SbBox3f, + bool forXValue, + bool forYValue, + bool forZValue, + bool forXRange, + bool forYRange, + bool forZRange + ); void adjustYZRanges(SbBox3f); void CutValueHelper(double val, QDoubleSpinBox* SpinBox, QSlider* Slider); void FlipClickedHelper(const char* BoxName); void changeCutBoxColors(); void createAllObjects(const std::vector& ObjectsListCut); App::DocumentObject* CreateBooleanFragments(App::Document* doc); - App::DocumentObject* createBooleanFragments(const std::vector& links, int transparency); + App::DocumentObject* createBooleanFragments( + const std::vector& links, + int transparency + ); Part::Compound* createCompound(const std::vector& links, int transparency); void setBooleanFragmentsColor(); Part::Box* findCutBox(const char* name) const; @@ -157,16 +169,22 @@ private: Part::Cut* createCut(const char* name); Part::Cut* tryCreateCut(const char* name); Part::Box* createBox(const char* name, const Base::Vector3f& size); - std::tuple tryCreateXBoxAndCut(const Base::Vector3f& pos, - const Base::Vector3f& size); + std::tuple tryCreateXBoxAndCut( + const Base::Vector3f& pos, + const Base::Vector3f& size + ); Part::Box* tryCreateXBox(const Base::Vector3f& pos, const Base::Vector3f& size); Part::Box* createXBox(const Base::Vector3f& pos, const Base::Vector3f& size); - std::tuple tryCreateYBoxAndCut(const Base::Vector3f& pos, - const Base::Vector3f& size); + std::tuple tryCreateYBoxAndCut( + const Base::Vector3f& pos, + const Base::Vector3f& size + ); Part::Box* tryCreateYBox(const Base::Vector3f& pos, const Base::Vector3f& size); Part::Box* createYBox(const Base::Vector3f& pos, const Base::Vector3f& size); - std::tuple tryCreateZBoxAndCut(const Base::Vector3f& pos, - const Base::Vector3f& size); + std::tuple tryCreateZBoxAndCut( + const Base::Vector3f& pos, + const Base::Vector3f& size + ); Part::Box* tryCreateZBox(const Base::Vector3f& pos, const Base::Vector3f& size); Part::Box* createZBox(const Base::Vector3f& pos, const Base::Vector3f& size); @@ -177,7 +195,7 @@ private: private: std::unique_ptr ui; std::vector ObjectsListVisible; - App::Document* doc = nullptr; // pointer to active document + App::Document* doc = nullptr; // pointer to active document bool hasBoxX = false; bool hasBoxY = false; bool hasBoxZ = false; @@ -191,6 +209,6 @@ private: const char* CutZName = "SectionCutZ"; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_SECTIONCUTTING_H +#endif // PARTGUI_SECTIONCUTTING_H diff --git a/src/Mod/Part/Gui/ShapeFromMesh.cpp b/src/Mod/Part/Gui/ShapeFromMesh.cpp index 95ed00fc1e..79df2e6aab 100644 --- a/src/Mod/Part/Gui/ShapeFromMesh.cpp +++ b/src/Mod/Part/Gui/ShapeFromMesh.cpp @@ -22,7 +22,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -49,7 +49,8 @@ ShapeFromMesh::ShapeFromMesh(QWidget* parent, Qt::WindowFlags fl) int decimals = Base::UnitsApi::getDecimals(); double tolerance_from_decimals = pow(10., -decimals); - double minimal_tolerance = tolerance_from_decimals < STD_OCC_TOLERANCE ? STD_OCC_TOLERANCE : tolerance_from_decimals; + double minimal_tolerance = tolerance_from_decimals < STD_OCC_TOLERANCE ? STD_OCC_TOLERANCE + : tolerance_from_decimals; ui->doubleSpinBox->setRange(minimal_tolerance, 10.0); ui->doubleSpinBox->setValue(0.1); ui->doubleSpinBox->setSingleStep(0.1); @@ -77,12 +78,18 @@ void ShapeFromMesh::perform() std::string mesh = it->getNameInDocument(); std::string name = doc->getUniqueObjectName(mesh.c_str()); - Gui::cmdAppDocumentArgs(doc, "addObject('%s', '%s')", "Part::Feature", name); + Gui::cmdAppDocumentArgs(doc, "addObject('%s', '%s')", "Part::Feature", name); std::string partObj = App::DocumentObjectT(doc, name).getObjectPython(); std::string meshObj = App::DocumentObjectT(doc, mesh).getObjectPython(); Gui::doCommandT(Gui::Command::Doc, "__shape__ = Part.Shape()"); - Gui::doCommandT(Gui::Command::Doc, "__shape__.makeShapeFromMesh(%s.Mesh.Topology, %f, %s)", meshObj, tolerance, (sewShape ? "True" : "False")); + Gui::doCommandT( + Gui::Command::Doc, + "__shape__.makeShapeFromMesh(%s.Mesh.Topology, %f, %s)", + meshObj, + tolerance, + (sewShape ? "True" : "False") + ); Gui::doCommandT(Gui::Command::Doc, partObj + ".Shape = __shape__"); Gui::doCommandT(Gui::Command::Doc, partObj + ".purgeTouched()"); Gui::doCommandT(Gui::Command::Doc, "del __shape__"); diff --git a/src/Mod/Part/Gui/ShapeFromMesh.h b/src/Mod/Part/Gui/ShapeFromMesh.h index 68258957d5..bf7bb9d7c4 100644 --- a/src/Mod/Part/Gui/ShapeFromMesh.h +++ b/src/Mod/Part/Gui/ShapeFromMesh.h @@ -28,10 +28,11 @@ #include #include -namespace PartGui { +namespace PartGui +{ class Ui_ShapeFromMesh; -class ShapeFromMesh : public QDialog +class ShapeFromMesh: public QDialog { Q_OBJECT @@ -46,6 +47,6 @@ private: std::unique_ptr ui; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_SHAPEFROMMESH_H +#endif // PARTGUI_SHAPEFROMMESH_H diff --git a/src/Mod/Part/Gui/SoBrepEdgeSet.cpp b/src/Mod/Part/Gui/SoBrepEdgeSet.cpp index 24ea999b80..7ed1d5f145 100644 --- a/src/Mod/Part/Gui/SoBrepEdgeSet.cpp +++ b/src/Mod/Part/Gui/SoBrepEdgeSet.cpp @@ -24,29 +24,29 @@ #include -# ifdef FC_OS_WIN32 -# include -# endif -# ifdef FC_OS_MACOSX -# include -# else -# include -# endif -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#ifdef FC_OS_WIN32 +# include +#endif +#ifdef FC_OS_MACOSX +# include +#else +# include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -62,7 +62,8 @@ using namespace PartGui; SO_NODE_SOURCE(SoBrepEdgeSet) -struct SoBrepEdgeSet::SelContext: Gui::SoFCSelectionContext { +struct SoBrepEdgeSet::SelContext: Gui::SoFCSelectionContext +{ std::vector hl, sl; }; @@ -78,15 +79,16 @@ SoBrepEdgeSet::SoBrepEdgeSet() SO_NODE_CONSTRUCTOR(SoBrepEdgeSet); } -void SoBrepEdgeSet::GLRender(SoGLRenderAction *action) +void SoBrepEdgeSet::GLRender(SoGLRenderAction* action) { auto state = action->getState(); selCounter.checkRenderCache(state); SelContextPtr ctx2; - SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this,selContext,ctx2); - if(ctx2 && ctx2->selectionIndex.empty()) + SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this, selContext, ctx2); + if (ctx2 && ctx2->selectionIndex.empty()) { return; + } bool hasContextHighlight = ctx && !ctx->hl.empty(); @@ -94,72 +96,90 @@ void SoBrepEdgeSet::GLRender(SoGLRenderAction *action) bool hasAnyHighlight = hasContextHighlight || hasFaceHighlight; if (Gui::Selection().isClarifySelectionActive() - && !Gui::SoDelayedAnnotationsElement::isProcessingDelayedPaths - && hasAnyHighlight) { + && !Gui::SoDelayedAnnotationsElement::isProcessingDelayedPaths && hasAnyHighlight) { // if we are using clarifyselection - add this to delayed paths with priority // as we want to get this rendered on top of everything if (viewProvider) { viewProvider->setFaceHighlightActive(true); } - Gui::SoDelayedAnnotationsElement::addDelayedPath(action->getState(), - action->getCurPath()->copy(), - 200); + Gui::SoDelayedAnnotationsElement::addDelayedPath( + action->getState(), + action->getCurPath()->copy(), + 200 + ); return; } - if(selContext2->checkGlobal(ctx)) { - if(selContext2->isSelectAll()) { + if (selContext2->checkGlobal(ctx)) { + if (selContext2->isSelectAll()) { selContext2->sl.clear(); selContext2->sl.push_back(-1); - }else if(ctx) + } + else if (ctx) { selContext2->sl = ctx->sl; - if(selContext2->highlightIndex == std::numeric_limits::max()) { + } + if (selContext2->highlightIndex == std::numeric_limits::max()) { selContext2->hl.clear(); selContext2->hl.push_back(-1); - }else if(ctx) + } + else if (ctx) { selContext2->hl = ctx->hl; + } ctx = selContext2; } - if(ctx && ctx->highlightIndex == std::numeric_limits::max()) { - if(ctx->selectionIndex.empty() || ctx->isSelectAll()) { - if(ctx2) { + if (ctx && ctx->highlightIndex == std::numeric_limits::max()) { + if (ctx->selectionIndex.empty() || ctx->isSelectAll()) { + if (ctx2) { ctx2->selectionColor = ctx->highlightColor; - renderSelection(action,ctx2); - } else - renderHighlight(action,ctx); - }else{ - if(!action->isRenderingDelayedPaths()) - renderSelection(action,ctx); - if(ctx2) { + renderSelection(action, ctx2); + } + else { + renderHighlight(action, ctx); + } + } + else { + if (!action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } + if (ctx2) { ctx2->selectionColor = ctx->highlightColor; - renderSelection(action,ctx2); - } else - renderHighlight(action,ctx); - if(action->isRenderingDelayedPaths()) - renderSelection(action,ctx); + renderSelection(action, ctx2); + } + else { + renderHighlight(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } } return; } - if(!action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); - if(ctx && !ctx->selectionIndex.empty()) { - if(ctx->isSelectAll()) { - if(ctx2) { + if (!action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + if (ctx && !ctx->selectionIndex.empty()) { + if (ctx->isSelectAll()) { + if (ctx2) { ctx2->selectionColor = ctx->selectionColor; - renderSelection(action,ctx2); - }else if(ctx->isSelectAll()) - renderSelection(action,ctx); - if(action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); + renderSelection(action, ctx2); + } + else if (ctx->isSelectAll()) { + renderSelection(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } return; } - if(!action->isRenderingDelayedPaths()) - renderSelection(action,ctx); + if (!action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } + } + if (ctx2 && !ctx2->selectionIndex.empty()) { + renderSelection(action, ctx2, false); } - if(ctx2 && !ctx2->selectionIndex.empty()) - renderSelection(action,ctx2,false); else if (Gui::Selection().isClarifySelectionActive() && !Gui::SoDelayedAnnotationsElement::isProcessingDelayedPaths && hasAnyHighlight) { state->push(); @@ -173,48 +193,54 @@ void SoBrepEdgeSet::GLRender(SoGLRenderAction *action) state->pop(); } else { - inherited::GLRender(action); + inherited::GLRender(action); } // Workaround for #0000433 -//#if !defined(FC_OS_WIN32) - if(!action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); - if(ctx && !ctx->selectionIndex.empty()) - renderSelection(action,ctx); - if(action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); -//#endif + // #if !defined(FC_OS_WIN32) + if (!action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + if (ctx && !ctx->selectionIndex.empty()) { + renderSelection(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + // #endif } -void SoBrepEdgeSet::GLRenderBelowPath(SoGLRenderAction * action) +void SoBrepEdgeSet::GLRenderBelowPath(SoGLRenderAction* action) { inherited::GLRenderBelowPath(action); } -void SoBrepEdgeSet::getBoundingBox(SoGetBoundingBoxAction * action) { +void SoBrepEdgeSet::getBoundingBox(SoGetBoundingBoxAction* action) +{ - SelContextPtr ctx2 = Gui::SoFCSelectionRoot::getSecondaryActionContext(action,this); - if(!ctx2 || (ctx2->sl.size()==1 && ctx2->sl[0]<0)) { + SelContextPtr ctx2 = Gui::SoFCSelectionRoot::getSecondaryActionContext(action, this); + if (!ctx2 || (ctx2->sl.size() == 1 && ctx2->sl[0] < 0)) { inherited::getBoundingBox(action); return; } - if(ctx2->sl.empty()) + if (ctx2->sl.empty()) { return; + } auto state = action->getState(); auto coords = SoCoordinateElement::getInstance(state); - const SbVec3f *coords3d = coords->getArrayPtr3(); + const SbVec3f* coords3d = coords->getArrayPtr3(); - if(!validIndexes(coords,ctx2->sl)) + if (!validIndexes(coords, ctx2->sl)) { return; + } SbBox3f bbox; int32_t i; - const int32_t *cindices = &ctx2->sl[0]; - const int32_t *end = cindices + ctx2->sl.size(); + const int32_t* cindices = &ctx2->sl[0]; + const int32_t* end = cindices + ctx2->sl.size(); while (cindices < end) { bbox.extendBy(coords3d[*cindices++]); i = (cindices < end) ? *cindices++ : -1; @@ -223,26 +249,30 @@ void SoBrepEdgeSet::getBoundingBox(SoGetBoundingBoxAction * action) { i = cindices < end ? *cindices++ : -1; } } - if(!bbox.isEmpty()) + if (!bbox.isEmpty()) { action->extendBy(bbox); + } } -void SoBrepEdgeSet::renderShape(const SoGLCoordinateElement * const coords, - const int32_t *cindices, int numindices) +void SoBrepEdgeSet::renderShape( + const SoGLCoordinateElement* const coords, + const int32_t* cindices, + int numindices +) { - const SbVec3f * coords3d = coords->getArrayPtr3(); + const SbVec3f* coords3d = coords->getArrayPtr3(); int32_t i; int previ; - const int32_t *end = cindices + numindices; + const int32_t* end = cindices + numindices; while (cindices < end) { glBegin(GL_LINE_STRIP); previ = *cindices++; i = (cindices < end) ? *cindices++ : -1; while (i >= 0) { - glVertex3fv((const GLfloat*) (coords3d + previ)); - glVertex3fv((const GLfloat*) (coords3d + i)); + glVertex3fv((const GLfloat*)(coords3d + previ)); + glVertex3fv((const GLfloat*)(coords3d + i)); previ = i; i = cindices < end ? *cindices++ : -1; } @@ -250,33 +280,44 @@ void SoBrepEdgeSet::renderShape(const SoGLCoordinateElement * const coords, } } -void SoBrepEdgeSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) +void SoBrepEdgeSet::renderHighlight(SoGLRenderAction* action, SelContextPtr ctx) { - if(!ctx || ctx->highlightIndex<0) + if (!ctx || ctx->highlightIndex < 0) { return; + } - SoState * state = action->getState(); + SoState* state = action->getState(); state->push(); - //SoLineWidthElement::set(state, this, 4.0f); + // SoLineWidthElement::set(state, this, 4.0f); SoLazyElement::setEmissive(state, &ctx->highlightColor); packedColor = ctx->highlightColor.getPackedValue(0.0); - SoLazyElement::setPacked(state, this,1, &packedColor,false); + SoLazyElement::setPacked(state, this, 1, &packedColor, false); - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numcindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; SbBool normalCacheUsed; - this->getVertexData(state, coords, normals, cindices, nindices, - tindices, mindices, numcindices, false, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numcindices, + false, + normalCacheUsed + ); SoMaterialBundle mb(action); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material int num = (int)ctx->hl.size(); if (num > 0) { @@ -286,7 +327,10 @@ void SoBrepEdgeSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) else { const int32_t* id = &(ctx->hl[0]); if (!validIndexes(coords, ctx->hl)) { - SoDebugError::postWarning("SoBrepEdgeSet::renderHighlight", "highlightIndex out of range"); + SoDebugError::postWarning( + "SoBrepEdgeSet::renderHighlight", + "highlightIndex out of range" + ); } else { renderShape(static_cast(coords), id, num); @@ -296,32 +340,42 @@ void SoBrepEdgeSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) state->pop(); } -void SoBrepEdgeSet::renderSelection(SoGLRenderAction *action, SelContextPtr ctx, bool push) +void SoBrepEdgeSet::renderSelection(SoGLRenderAction* action, SelContextPtr ctx, bool push) { - SoState * state = action->getState(); - if(push){ + SoState* state = action->getState(); + if (push) { state->push(); - //SoLineWidthElement::set(state, this, 4.0f); + // SoLineWidthElement::set(state, this, 4.0f); SoLazyElement::setEmissive(state, &ctx->selectionColor); packedColor = ctx->selectionColor.getPackedValue(0.0); - SoLazyElement::setPacked(state, this,1, &packedColor,false); + SoLazyElement::setPacked(state, this, 1, &packedColor, false); } - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numcindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; SbBool normalCacheUsed; - this->getVertexData(state, coords, normals, cindices, nindices, - tindices, mindices, numcindices, false, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numcindices, + false, + normalCacheUsed + ); SoMaterialBundle mb(action); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material int num = (int)ctx->sl.size(); if (num > 0) { @@ -332,14 +386,19 @@ void SoBrepEdgeSet::renderSelection(SoGLRenderAction *action, SelContextPtr ctx, cindices = &(ctx->sl[0]); numcindices = (int)ctx->sl.size(); if (!validIndexes(coords, ctx->sl)) { - SoDebugError::postWarning("SoBrepEdgeSet::renderSelection", "selectionIndex out of range"); + SoDebugError::postWarning( + "SoBrepEdgeSet::renderSelection", + "selectionIndex out of range" + ); } else { renderShape(static_cast(coords), cindices, numcindices); } } } - if(push) state->pop(); + if (push) { + state->pop(); + } } bool SoBrepEdgeSet::validIndexes(const SoCoordinateElement* coords, const std::vector& pts) const @@ -358,8 +417,9 @@ void SoBrepEdgeSet::doAction(SoAction* action) Gui::SoHighlightElementAction* hlaction = static_cast(action); selCounter.checkAction(hlaction); if (!hlaction->isHighlighted()) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { ctx->highlightIndex = -1; ctx->hl.clear(); touch(); @@ -368,7 +428,7 @@ void SoBrepEdgeSet::doAction(SoAction* action) } const SoDetail* detail = hlaction->getElement(); if (!detail) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); ctx->highlightColor = hlaction->getColor(); ctx->highlightIndex = std::numeric_limits::max(); ctx->hl.clear(); @@ -378,8 +438,9 @@ void SoBrepEdgeSet::doAction(SoAction* action) } if (!detail->isOfType(SoLineDetail::getClassTypeId())) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { ctx->highlightIndex = -1; ctx->hl.clear(); touch(); @@ -387,106 +448,123 @@ void SoBrepEdgeSet::doAction(SoAction* action) return; } - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); ctx->highlightColor = hlaction->getColor(); int index = static_cast(detail)->getLineIndex(); const int32_t* cindices = this->coordIndex.getValues(0); int numcindices = this->coordIndex.getNum(); ctx->hl.clear(); - for(int section=0,i=0;i index) + for (int section = 0, i = 0; i < numcindices; i++) { + if (cindices[i] < 0) { + if (++section > index) { break; - }else if(section == index) + } + } + else if (section == index) { ctx->hl.push_back(cindices[i]); + } } - if(!ctx->hl.empty()) + if (!ctx->hl.empty()) { ctx->highlightIndex = index; - else + } + else { ctx->highlightIndex = -1; + } touch(); return; } else if (action->getTypeId() == Gui::SoSelectionElementAction::getClassTypeId()) { Gui::SoSelectionElementAction* selaction = static_cast(action); - switch(selaction->getType()) { - case Gui::SoSelectionElementAction::None: { - if(selaction->isSecondary()) { - if(Gui::SoFCSelectionRoot::removeActionContext(action,this)) - touch(); - }else { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { - ctx->selectionIndex.clear(); - ctx->sl.clear(); - touch(); + switch (selaction->getType()) { + case Gui::SoSelectionElementAction::None: { + if (selaction->isSecondary()) { + if (Gui::SoFCSelectionRoot::removeActionContext(action, this)) { + touch(); + } } - } - return; - } case Gui::SoSelectionElementAction::All: { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - ctx->selectionColor = selaction->getColor(); - ctx->selectionIndex.clear(); - ctx->selectionIndex.insert(-1); // all - ctx->sl.clear(); - ctx->sl.push_back(-1); - touch(); - return; - } case Gui::SoSelectionElementAction::Append: - case Gui::SoSelectionElementAction::Remove: { - const SoDetail* detail = selaction->getElement(); - if (!detail || !detail->isOfType(SoLineDetail::getClassTypeId())) { - if(selaction->isSecondary()) { - // For secondary context, a detail of different type means - // the user may want to partial render only other type of - // geometry. So we call below to obtain a action context. - // If no secondary context exist, it will create an empty - // one, and an empty secondary context inhibites drawing - // here. - auto ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - touch(); + else { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { + ctx->selectionIndex.clear(); + ctx->sl.clear(); + touch(); + } } return; } - int index = static_cast(detail)->getLineIndex(); - SelContextPtr ctx; - if(selaction->getType() == Gui::SoSelectionElementAction::Append) { - ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); + case Gui::SoSelectionElementAction::All: { + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); ctx->selectionColor = selaction->getColor(); - if(ctx->isSelectAll()) - ctx->selectionIndex.clear(); - if(!ctx->selectionIndex.insert(index).second) - return; - }else{ - ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(!ctx || !ctx->removeIndex(index)) - return; + ctx->selectionIndex.clear(); + ctx->selectionIndex.insert(-1); // all + ctx->sl.clear(); + ctx->sl.push_back(-1); + touch(); + return; } - ctx->sl.clear(); - if(!ctx->selectionIndex.empty()) { - const int32_t* cindices = this->coordIndex.getValues(0); - int numcindices = this->coordIndex.getNum(); - auto it = ctx->selectionIndex.begin(); - for(int section=0,i=0;isl.push_back(cindices[i]); - if(cindices[i] < 0) { - if(++section > *it) { - if(++it == ctx->selectionIndex.end()) - break; + case Gui::SoSelectionElementAction::Append: + case Gui::SoSelectionElementAction::Remove: { + const SoDetail* detail = selaction->getElement(); + if (!detail || !detail->isOfType(SoLineDetail::getClassTypeId())) { + if (selaction->isSecondary()) { + // For secondary context, a detail of different type means + // the user may want to partial render only other type of + // geometry. So we call below to obtain a action context. + // If no secondary context exist, it will create an empty + // one, and an empty secondary context inhibites drawing + // here. + auto ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + touch(); + } + return; + } + int index = static_cast(detail)->getLineIndex(); + SelContextPtr ctx; + if (selaction->getType() == Gui::SoSelectionElementAction::Append) { + ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + ctx->selectionColor = selaction->getColor(); + if (ctx->isSelectAll()) { + ctx->selectionIndex.clear(); + } + if (!ctx->selectionIndex.insert(index).second) { + return; + } + } + else { + ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (!ctx || !ctx->removeIndex(index)) { + return; + } + } + ctx->sl.clear(); + if (!ctx->selectionIndex.empty()) { + const int32_t* cindices = this->coordIndex.getValues(0); + int numcindices = this->coordIndex.getNum(); + auto it = ctx->selectionIndex.begin(); + for (int section = 0, i = 0; i < numcindices; i++) { + if (section == *it) { + ctx->sl.push_back(cindices[i]); + } + if (cindices[i] < 0) { + if (++section > *it) { + if (++it == ctx->selectionIndex.end()) { + break; + } + } } } } + touch(); + break; } - touch(); - break; - } default : - break; + default: + break; } return; } @@ -494,10 +572,12 @@ void SoBrepEdgeSet::doAction(SoAction* action) inherited::doAction(action); } -SoDetail * SoBrepEdgeSet::createLineSegmentDetail(SoRayPickAction * action, - const SoPrimitiveVertex * v1, - const SoPrimitiveVertex * v2, - SoPickedPoint * pp) +SoDetail* SoBrepEdgeSet::createLineSegmentDetail( + SoRayPickAction* action, + const SoPrimitiveVertex* v1, + const SoPrimitiveVertex* v2, + SoPickedPoint* pp +) { SoDetail* detail = inherited::createLineSegmentDetail(action, v1, v2, pp); SoLineDetail* line_detail = static_cast(detail); @@ -505,4 +585,3 @@ SoDetail * SoBrepEdgeSet::createLineSegmentDetail(SoRayPickAction * action, line_detail->setPartIndex(index); return detail; } - diff --git a/src/Mod/Part/Gui/SoBrepEdgeSet.h b/src/Mod/Part/Gui/SoBrepEdgeSet.h index bbd3cb21af..1e4f5fabf2 100644 --- a/src/Mod/Part/Gui/SoBrepEdgeSet.h +++ b/src/Mod/Part/Gui/SoBrepEdgeSet.h @@ -36,11 +36,13 @@ class SoCoordinateElement; class SoGLCoordinateElement; class SoTextureCoordinateBundle; -namespace PartGui { +namespace PartGui +{ class ViewProviderPartExt; -class PartGuiExport SoBrepEdgeSet : public SoIndexedLineSet { +class PartGuiExport SoBrepEdgeSet: public SoIndexedLineSet +{ using inherited = SoIndexedLineSet; SO_NODE_HEADER(SoBrepEdgeSet); @@ -48,30 +50,37 @@ class PartGuiExport SoBrepEdgeSet : public SoIndexedLineSet { public: static void initClass(); SoBrepEdgeSet(); - - void setViewProvider(ViewProviderPartExt* vp) { viewProvider = vp; } + + void setViewProvider(ViewProviderPartExt* vp) + { + viewProvider = vp; + } protected: ~SoBrepEdgeSet() override = default; - void GLRender(SoGLRenderAction *action) override; - void GLRenderBelowPath(SoGLRenderAction * action) override; + void GLRender(SoGLRenderAction* action) override; + void GLRenderBelowPath(SoGLRenderAction* action) override; void doAction(SoAction* action) override; - SoDetail * createLineSegmentDetail( - SoRayPickAction *action, - const SoPrimitiveVertex *v1, - const SoPrimitiveVertex *v2, - SoPickedPoint *pp) override; + SoDetail* createLineSegmentDetail( + SoRayPickAction* action, + const SoPrimitiveVertex* v1, + const SoPrimitiveVertex* v2, + SoPickedPoint* pp + ) override; - void getBoundingBox(SoGetBoundingBoxAction * action) override; + void getBoundingBox(SoGetBoundingBoxAction* action) override; private: struct SelContext; using SelContextPtr = std::shared_ptr; - void renderShape(const SoGLCoordinateElement * const vertexlist, - const int32_t *vertexindices, int num_vertexindices); - void renderHighlight(SoGLRenderAction *action, SelContextPtr); - void renderSelection(SoGLRenderAction *action, SelContextPtr, bool push=true); + void renderShape( + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int num_vertexindices + ); + void renderHighlight(SoGLRenderAction* action, SelContextPtr); + void renderSelection(SoGLRenderAction* action, SelContextPtr, bool push = true); bool validIndexes(const SoCoordinateElement*, const std::vector&) const; @@ -79,14 +88,13 @@ private: SelContextPtr selContext; SelContextPtr selContext2; Gui::SoFCSelectionCounter selCounter; - uint32_t packedColor{0}; - + uint32_t packedColor {0}; + // backreference to viewprovider that owns this node ViewProviderPartExt* viewProvider = nullptr; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_SOBREPEDGESET_H - +#endif // PARTGUI_SOBREPEDGESET_H diff --git a/src/Mod/Part/Gui/SoBrepFaceSet.cpp b/src/Mod/Part/Gui/SoBrepFaceSet.cpp index 54c3d31be6..f5b4d0daa5 100644 --- a/src/Mod/Part/Gui/SoBrepFaceSet.cpp +++ b/src/Mod/Part/Gui/SoBrepFaceSet.cpp @@ -26,47 +26,47 @@ #ifndef FC_OS_WIN32 # ifndef GL_GLEXT_PROTOTYPES -# define GL_GLEXT_PROTOTYPES 1 +# define GL_GLEXT_PROTOTYPES 1 # endif #endif -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# ifdef FC_OS_WIN32 -# include +#ifdef FC_OS_WIN32 +# include +# include +# include +#else +# ifdef FC_OS_MACOSX +# include +# include +# else # include # include -# else -# ifdef FC_OS_MACOSX -# include -# include -# else -# include -# include -# endif //FC_OS_MACOSX -# endif //FC_OS_WIN32 +# endif // FC_OS_MACOSX +#endif // FC_OS_WIN32 // Should come after glext.h to avoid warnings -# include +#include #include @@ -80,16 +80,17 @@ #include "SoBrepEdgeSet.h" - using namespace PartGui; SO_NODE_SOURCE(SoBrepFaceSet) #define PRIVATE(p) ((p)->pimpl) -class SoBrepFaceSet::VBO { +class SoBrepFaceSet::VBO +{ public: - struct Buffer { + struct Buffer + { uint32_t myvbo[2]; std::size_t vertex_array_size; std::size_t index_array_size; @@ -113,49 +114,52 @@ public: // schedule delete for all allocated GL resources std::map::iterator it; for (it = vbomap.begin(); it != vbomap.end(); ++it) { - void * ptr0 = (void*) ((uintptr_t) it->second.myvbo[0]); + void* ptr0 = (void*)((uintptr_t)it->second.myvbo[0]); SoGLCacheContextElement::scheduleDeleteCallback(it->first, VBO::vbo_delete, ptr0); - void * ptr1 = (void*) ((uintptr_t) it->second.myvbo[1]); + void* ptr1 = (void*)((uintptr_t)it->second.myvbo[1]); SoGLCacheContextElement::scheduleDeleteCallback(it->first, VBO::vbo_delete, ptr1); } } - void render(SoGLRenderAction * action, - const SoGLCoordinateElement * const vertexlist, - const int32_t *vertexindices, - int num_vertexindices, - const int32_t *partindices, - int num_partindices, - const SbVec3f *normals, - const int32_t *normindices, - SoMaterialBundle *const materials, - const int32_t *matindices, - SoTextureCoordinateBundle * const texcoords, - const int32_t *texindices, - const int nbind, - const int mbind, - SbBool texture); + void render( + SoGLRenderAction* action, + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int num_vertexindices, + const int32_t* partindices, + int num_partindices, + const SbVec3f* normals, + const int32_t* normindices, + SoMaterialBundle* const materials, + const int32_t* matindices, + SoTextureCoordinateBundle* const texcoords, + const int32_t* texindices, + const int nbind, + const int mbind, + SbBool texture + ); - static void context_destruction_cb(uint32_t context, void * userdata) + static void context_destruction_cb(uint32_t context, void* userdata) { - VBO * self = static_cast(userdata); + VBO* self = static_cast(userdata); std::map::iterator it = self->vbomap.find(context); if (it != self->vbomap.end()) { #ifdef FC_OS_WIN32 - const cc_glglue * glue = cc_glglue_instance((int) context); - PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)cc_glglue_getprocaddress(glue, "glDeleteBuffersARB"); + const cc_glglue* glue = cc_glglue_instance((int)context); + PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB + = (PFNGLDELETEBUFFERSARBPROC)cc_glglue_getprocaddress(glue, "glDeleteBuffersARB"); #endif - auto &buffer = it->second; + auto& buffer = it->second; glDeleteBuffersARB(2, buffer.myvbo); self->vbomap.erase(it); } } - static void vbo_delete(void * closure, uint32_t contextid) + static void vbo_delete(void* closure, uint32_t contextid) { - const cc_glglue * glue = cc_glglue_instance((int) contextid); - GLuint id = (GLuint) ((uintptr_t) closure); + const cc_glglue* glue = cc_glglue_instance((int)contextid); + GLuint id = (GLuint)((uintptr_t)closure); cc_glglue_glDeleteBuffers(glue, 1, &id); } }; @@ -187,8 +191,9 @@ void SoBrepFaceSet::doAction(SoAction* action) Gui::SoHighlightElementAction* hlaction = static_cast(action); selCounter.checkAction(hlaction); if (!hlaction->isHighlighted()) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { ctx->highlightIndex = -1; touch(); } @@ -200,23 +205,26 @@ void SoBrepFaceSet::doAction(SoAction* action) const SoDetail* detail = hlaction->getElement(); if (!detail) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); ctx->highlightIndex = std::numeric_limits::max(); ctx->highlightColor = hlaction->getColor(); touch(); - }else { + } + else { if (!detail->isOfType(SoFaceDetail::getClassTypeId())) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { ctx->highlightIndex = -1; touch(); } if (viewProvider) { viewProvider->setFaceHighlightActive(false); } - }else { + } + else { int index = static_cast(detail)->getPartIndex(); - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); ctx->highlightIndex = index; ctx->highlightColor = hlaction->getColor(); touch(); @@ -226,93 +234,107 @@ void SoBrepFaceSet::doAction(SoAction* action) } else if (action->getTypeId() == Gui::SoSelectionElementAction::getClassTypeId()) { Gui::SoSelectionElementAction* selaction = static_cast(action); - switch(selaction->getType()) { - case Gui::SoSelectionElementAction::All: { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - ctx->selectionColor = selaction->getColor(); - ctx->selectionIndex.clear(); - ctx->selectionIndex.insert(-1); - touch(); - return; - } case Gui::SoSelectionElementAction::None: - if(selaction->isSecondary()) { - if(Gui::SoFCSelectionRoot::removeActionContext(action,this)) - touch(); - }else { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { - ctx->selectionIndex.clear(); - ctx->colors.clear(); - touch(); - } + switch (selaction->getType()) { + case Gui::SoSelectionElementAction::All: { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + ctx->selectionColor = selaction->getColor(); + ctx->selectionIndex.clear(); + ctx->selectionIndex.insert(-1); + touch(); + return; } - return; - case Gui::SoSelectionElementAction::Color: - if(selaction->isSecondary()) { - const auto &colors = selaction->getColors(); - auto ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(colors.empty()) { - if(ctx) { + case Gui::SoSelectionElementAction::None: + if (selaction->isSecondary()) { + if (Gui::SoFCSelectionRoot::removeActionContext(action, this)) { + touch(); + } + } + else { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { + ctx->selectionIndex.clear(); ctx->colors.clear(); - if(ctx->isSelectAll()) - Gui::SoFCSelectionRoot::removeActionContext(action,this); + touch(); + } + } + return; + case Gui::SoSelectionElementAction::Color: + if (selaction->isSecondary()) { + const auto& colors = selaction->getColors(); + auto ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (colors.empty()) { + if (ctx) { + ctx->colors.clear(); + if (ctx->isSelectAll()) { + Gui::SoFCSelectionRoot::removeActionContext(action, this); + } + touch(); + } + return; + } + static std::string element("Face"); + if (colors.begin()->first.empty() || colors.lower_bound(element) != colors.end()) { + if (!ctx) { + ctx = Gui::SoFCSelectionRoot::getActionContext(action, this); + selCounter.checkAction(selaction, ctx); + ctx->selectAll(); + } + if (ctx->setColors(selaction->getColors(), element)) { + touch(); + } + } + } + return; + case Gui::SoSelectionElementAction::Remove: + case Gui::SoSelectionElementAction::Append: { + const SoDetail* detail = selaction->getElement(); + if (!detail || !detail->isOfType(SoFaceDetail::getClassTypeId())) { + if (selaction->isSecondary()) { + // For secondary context, a detail of different type means + // the user may want to partial render only other type of + // geometry. So we call below to obtain a action context. + // If no secondary context exist, it will create an empty + // one, and an empty secondary context inhibites drawing + // here. + auto ctx = Gui::SoFCSelectionRoot::getActionContext(action, this); + selCounter.checkAction(selaction, ctx); touch(); } return; } - static std::string element("Face"); - if(colors.begin()->first.empty() || colors.lower_bound(element)!=colors.end()) { - if(!ctx) { - ctx = Gui::SoFCSelectionRoot::getActionContext(action,this); - selCounter.checkAction(selaction,ctx); - ctx->selectAll(); + int index = static_cast(detail)->getPartIndex(); + if (selaction->getType() == Gui::SoSelectionElementAction::Append) { + auto ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + ctx->selectionColor = selaction->getColor(); + if (ctx->isSelectAll()) { + ctx->selectionIndex.clear(); } - if(ctx->setColors(selaction->getColors(),element)) + if (ctx->selectionIndex.insert(index).second) { touch(); + } } - } - return; - case Gui::SoSelectionElementAction::Remove: - case Gui::SoSelectionElementAction::Append: { - const SoDetail* detail = selaction->getElement(); - if (!detail || !detail->isOfType(SoFaceDetail::getClassTypeId())) { - if(selaction->isSecondary()) { - // For secondary context, a detail of different type means - // the user may want to partial render only other type of - // geometry. So we call below to obtain a action context. - // If no secondary context exist, it will create an empty - // one, and an empty secondary context inhibites drawing - // here. - auto ctx = Gui::SoFCSelectionRoot::getActionContext(action,this); - selCounter.checkAction(selaction,ctx); - touch(); + else { + auto ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx && ctx->removeIndex(index)) { + touch(); + } } - return; + break; } - int index = static_cast(detail)->getPartIndex(); - if (selaction->getType() == Gui::SoSelectionElementAction::Append) { - auto ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - ctx->selectionColor = selaction->getColor(); - if(ctx->isSelectAll()) - ctx->selectionIndex.clear(); - if(ctx->selectionIndex.insert(index).second) - touch(); - }else{ - auto ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx && ctx->removeIndex(index)) - touch(); - } - break; - } default: - break; + default: + break; } return; } else if (action->getTypeId() == Gui::SoVRMLAction::getClassTypeId()) { // update the materialIndex field to match with the number of triangles if needed - SoState * state = action->getState(); + SoState* state = action->getState(); Binding mbind = this->findMaterialBinding(state); if (mbind == PER_PART) { const SoLazyElement* mat = SoLazyElement::getInstance(state); @@ -322,15 +344,15 @@ void SoBrepFaceSet::doAction(SoAction* action) numColor = mat->getNumDiffuse(); if (numColor == numParts) { int count = 0; - const int32_t * indices = this->partIndex.getValues(0); - for (int i=0; ipartIndex.getValues(0); + for (int i = 0; i < numParts; i++) { count += indices[i]; } this->materialIndex.setNum(count); - int32_t * matind = this->materialIndex.startEditing(); + int32_t* matind = this->materialIndex.startEditing(); int32_t k = 0; - for (int i=0; igetTypeId() == Gui::SoUpdateVBOAction::getClassTypeId()) { - for(auto &v : PRIVATE(this)->vbomap) { + for (auto& v : PRIVATE(this)->vbomap) { v.second.updateVbo = true; v.second.vboLoaded = false; } @@ -353,9 +375,9 @@ void SoBrepFaceSet::doAction(SoAction* action) } #ifdef RENDER_GLARRAYS -void SoBrepFaceSet::GLRender(SoGLRenderAction *action) +void SoBrepFaceSet::GLRender(SoGLRenderAction* action) { - SoState * state = action->getState(); + SoState* state = action->getState(); // Disable caching for this node SoGLCacheContextElement::shouldAutoCache(state, SoGLCacheContextElement::DONT_AUTO_CACHE); @@ -365,43 +387,49 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) SoTextureCoordinateBundle tb(action, true, false); SbBool doTextures = tb.needCoordinates(); - if (ctx->coordIndex.getNum() < 3) + if (ctx->coordIndex.getNum() < 3) { return; + } SelContextPtr ctx2; - SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this,selContext,ctx2); - if(ctx2 && ctx2->selectionIndex.empty()) + SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this, selContext, ctx2); + if (ctx2 && ctx2->selectionIndex.empty()) { return; + } - int32_t hl_idx = ctx?ctx->highlightIndex:-1; - int32_t num_selected = ctx?ctx->selectionIndex.size():0; + int32_t hl_idx = ctx ? ctx->highlightIndex : -1; + int32_t num_selected = ctx ? ctx->selectionIndex.size() : 0; - renderHighlight(action,ctx); - if(ctx && ctx->selectionIndex.size()) { - if(ctx->isSelectAll()) { - if(ctx2 && ctx2->selectionIndex.size()) { + renderHighlight(action, ctx); + if (ctx && ctx->selectionIndex.size()) { + if (ctx->isSelectAll()) { + if (ctx2 && ctx2->selectionIndex.size()) { ctx2->selectionColor = ctx->selectionColor; - renderSelection(action,ctx2); - } else - renderSelection(action,ctx); + renderSelection(action, ctx2); + } + else { + renderSelection(action, ctx); + } return; } - renderSelection(action,ctx); + renderSelection(action, ctx); } - if(ctx2 && ctx2->selectionIndex.size()) { - renderSelection(action,ctx2,false); - }else{ + if (ctx2 && ctx2->selectionIndex.size()) { + renderSelection(action, ctx2, false); + } + else { // When setting transparency shouldGLRender() handles the rendering and returns false. // Therefore generatePrimitives() needs to be re-implemented to handle the materials // correctly. - if (!this->shouldGLRender(action)) + if (!this->shouldGLRender(action)) { return; + } -#ifdef RENDER_GLARRAYS +# ifdef RENDER_GLARRAYS if (!doTextures && index_array.size() && hl_idx < 0 && num_selected <= 0) { if (mbind == 0) { - mb.sendFirst(); // only one material -> apply it! + mb.sendFirst(); // only one material -> apply it! renderSimpleArray(); return; } @@ -410,43 +438,73 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) return; } } -#endif +# endif Binding nbind = this->findNormalBinding(state); - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; - const int32_t * pindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; + const int32_t* pindices; int numparts; SbBool normalCacheUsed; SbBool sendNormals = !mb.isColorOnly() || tb.isFunction(); - this->getVertexData(state, coords, normals, cindices, - nindices, tindices, mindices, numindices, - sendNormals, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material // just in case someone forgot - if (!mindices) mindices = cindices; - if (!nindices) nindices = cindices; + if (!mindices) { + mindices = cindices; + } + if (!nindices) { + nindices = cindices; + } pindices = this->partIndex.getValues(0); numparts = this->partIndex.getNum(); - renderShape(state, vboAvailable, static_cast(coords), cindices, numindices, - pindices, numparts, normals, nindices, &mb, mindices, &tb, tindices, nbind, mbind, doTextures?1:0); + renderShape( + state, + vboAvailable, + static_cast(coords), + cindices, + numindices, + pindices, + numparts, + normals, + nindices, + &mb, + mindices, + &tb, + tindices, + nbind, + mbind, + doTextures ? 1 : 0 + ); - if(normalCacheUsed) + if (normalCacheUsed) { this->readUnlockNormalCache(); + } } - renderHighlight(action,ctx); - renderSelection(action,ctx); + renderHighlight(action, ctx); + renderSelection(action, ctx); } //**************************************************************************** @@ -457,8 +515,9 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) void SoBrepFaceSet::renderSimpleArray() { int cnt = index_array.size(); - if (cnt == 0) + if (cnt == 0) { return; + } glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); @@ -475,12 +534,13 @@ void SoBrepFaceSet::renderSimpleArray() // no texture, highlight or selection but color / material array. // needs to iterate over parts (i.e. geometry faces) // -void SoBrepFaceSet::renderColoredArray(SoMaterialBundle *const materials) +void SoBrepFaceSet::renderColoredArray(SoMaterialBundle* const materials) { int num_parts = partIndex.getNum(); int cnt = index_array.size(); - if (cnt == 0) + if (cnt == 0) { return; + } glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); @@ -503,65 +563,68 @@ void SoBrepFaceSet::renderColoredArray(SoMaterialBundle *const materials) } #else -void SoBrepFaceSet::GLRender(SoGLRenderAction *action) +void SoBrepFaceSet::GLRender(SoGLRenderAction* action) { ZoneScoped; - //SoBase::staticDataLock(); + // SoBase::staticDataLock(); static bool init = false; if (!init) { std::string ext = (const char*)(glGetString(GL_EXTENSIONS)); PRIVATE(this)->vboAvailable = (ext.find("GL_ARB_vertex_buffer_object") != std::string::npos); init = true; } - //SoBase::staticDataUnlock(); + // SoBase::staticDataUnlock(); - if (this->coordIndex.getNum() < 3) + if (this->coordIndex.getNum() < 3) { return; + } SelContextPtr ctx2; std::vector ctxs; - SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this,selContext,ctx2); - if(ctx2 && ctx2->selectionIndex.empty()) + SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this, selContext, ctx2); + if (ctx2 && ctx2->selectionIndex.empty()) { return; - if(selContext2->checkGlobal(ctx)) + } + if (selContext2->checkGlobal(ctx)) { ctx = selContext2; - if(ctx && (ctx->selectionIndex.empty() && ctx->highlightIndex<0)) + } + if (ctx && (ctx->selectionIndex.empty() && ctx->highlightIndex < 0)) { ctx.reset(); + } auto state = action->getState(); selCounter.checkRenderCache(state); - + bool hasContextHighlight = ctx && ctx->isHighlighted() && !ctx->isHighlightAll() && ctx->highlightIndex >= 0 && ctx->highlightIndex < partIndex.getNum(); // for the tool add this node to delayed paths as we want to render it on top of the scene if (Gui::Selection().isClarifySelectionActive() && hasContextHighlight) { - + if (!Gui::SoDelayedAnnotationsElement::isProcessingDelayedPaths) { if (viewProvider) { viewProvider->setFaceHighlightActive(true); } - + const SoPath* currentPath = action->getCurPath(); - Gui::SoDelayedAnnotationsElement::addDelayedPath(action->getState(), - currentPath->copy(), - 100); + Gui::SoDelayedAnnotationsElement::addDelayedPath(action->getState(), currentPath->copy(), 100); return; - } else { + } + else { // during priority delayed paths processing: // render base faces normally first, then render highlight on top - + inherited::GLRender(action); - + state->push(); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(false); glDisable(GL_DEPTH_TEST); - + renderHighlight(action, ctx); - + state->pop(); return; } @@ -569,8 +632,8 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) // override material binding to PER_PART_INDEX to achieve // preselection/selection with transparency - bool pushed = overrideMaterialBinding(action,ctx,ctx2); - if(!pushed){ + bool pushed = overrideMaterialBinding(action, ctx, ctx2); + if (!pushed) { // for non transparent cases, we still use the old selection rendering // code, because it can override emission color, which gives a more // distinguishable selection highlight. The above material binding @@ -594,48 +657,60 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) // Transparency complicates stuff even more, but not here. It will be handled inside // overrideMaterialBinding() // - if(ctx && ctx->highlightIndex == std::numeric_limits::max()) { - if(ctx->selectionIndex.empty() || ctx->isSelectAll()) { - if(ctx2) { + if (ctx && ctx->highlightIndex == std::numeric_limits::max()) { + if (ctx->selectionIndex.empty() || ctx->isSelectAll()) { + if (ctx2) { ctx2->selectionColor = ctx->highlightColor; - renderSelection(action,ctx2); - } else - renderHighlight(action,ctx); - }else{ - if(!action->isRenderingDelayedPaths()) - renderSelection(action,ctx); - if(ctx2) { + renderSelection(action, ctx2); + } + else { + renderHighlight(action, ctx); + } + } + else { + if (!action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } + if (ctx2) { ctx2->selectionColor = ctx->highlightColor; - renderSelection(action,ctx2); - } else - renderHighlight(action,ctx); - if(action->isRenderingDelayedPaths()) - renderSelection(action,ctx); + renderSelection(action, ctx2); + } + else { + renderHighlight(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } } return; } - if(!action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); - if(ctx && !ctx->selectionIndex.empty()) { - if(ctx->isSelectAll()) { - if(ctx2) { + if (!action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + if (ctx && !ctx->selectionIndex.empty()) { + if (ctx->isSelectAll()) { + if (ctx2) { ctx2->selectionColor = ctx->selectionColor; - renderSelection(action,ctx2); - } else - renderSelection(action,ctx); - if(action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); + renderSelection(action, ctx2); + } + else { + renderSelection(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } return; } - if(!action->isRenderingDelayedPaths()) - renderSelection(action,ctx); + if (!action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } } - if(ctx2) { - renderSelection(action,ctx2,false); - if(action->isRenderingDelayedPaths()) { - renderSelection(action,ctx); - renderHighlight(action,ctx); + if (ctx2) { + renderSelection(action, ctx2, false); + if (action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + renderHighlight(action, ctx); } return; } @@ -649,18 +724,18 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) // When setting transparency shouldGLRender() handles the rendering and returns false. // Therefore generatePrimitives() needs to be re-implemented to handle the materials // correctly. - if(this->shouldGLRender(action)) { + if (this->shouldGLRender(action)) { Binding mbind = this->findMaterialBinding(state); Binding nbind = this->findNormalBinding(state); - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; - const int32_t * pindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; + const int32_t* pindices; int numparts; SbBool doTextures; SbBool normalCacheUsed; @@ -669,13 +744,26 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) doTextures = tb.needCoordinates(); SbBool sendNormals = !mb.isColorOnly() || tb.isFunction(); - this->getVertexData(state, coords, normals, cindices, - nindices, tindices, mindices, numindices, - sendNormals, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); // just in case someone forgot - if (!mindices) mindices = cindices; - if (!nindices) nindices = cindices; + if (!mindices) { + mindices = cindices; + } + if (!nindices) { + nindices = cindices; + } pindices = this->partIndex.getValues(0); numparts = this->partIndex.getNum(); @@ -684,43 +772,65 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) // get the VBO status of the viewer Gui::SoGLVBOActivatedElement::get(state, hasVBO); } - renderShape(action, hasVBO, static_cast(coords), cindices, numindices, - pindices, numparts, normals, nindices, &mb, mindices, &tb, tindices, nbind, mbind, doTextures?1:0); + renderShape( + action, + hasVBO, + static_cast(coords), + cindices, + numindices, + pindices, + numparts, + normals, + nindices, + &mb, + mindices, + &tb, + tindices, + nbind, + mbind, + doTextures ? 1 : 0 + ); - if (normalCacheUsed) + if (normalCacheUsed) { this->readUnlockNormalCache(); + } } - if(pushed) { + if (pushed) { state->pop(); - }else if(action->isRenderingDelayedPaths()) { - renderSelection(action,ctx); - renderHighlight(action,ctx); + } + else if (action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + renderHighlight(action, ctx); } } #endif -bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction *action, SelContextPtr ctx, SelContextPtr ctx2) { - if(!ctx && !ctx2) +bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction* action, SelContextPtr ctx, SelContextPtr ctx2) +{ + if (!ctx && !ctx2) { return false; + } auto state = action->getState(); auto mb = SoMaterialBindingElement::get(state); auto element = SoLazyElement::getInstance(state); - const SbColor *diffuse = element->getDiffusePointer(); - if(!diffuse) + const SbColor* diffuse = element->getDiffusePointer(); + if (!diffuse) { return false; + } int diffuse_size = element->getNumDiffuse(); - const float *trans = element->getTransparencyPointer(); + const float* trans = element->getTransparencyPointer(); int trans_size = element->getNumTransparencies(); - if(!trans || !trans_size) + if (!trans || !trans_size) { return false; - float trans0=0.0; + } + float trans0 = 0.0; bool hasTransparency = false; - for(int i=0;i=partIndex.getNum())) - && - ((ctx && Gui::Selection().needPickedList()) || - trans0!=0.0 || - (ctx2 && !ctx2->colors.empty()))) - { + if ((mb == SoMaterialBindingElement::OVERALL + || (mb == SoMaterialBindingElement::PER_PART && diffuse_size >= partIndex.getNum())) + && ((ctx && Gui::Selection().needPickedList()) || trans0 != 0.0 + || (ctx2 && !ctx2->colors.empty()))) { state->push(); packedColors.clear(); - if(ctx && Gui::Selection().needPickedList()) { + if (ctx && Gui::Selection().needPickedList()) { hasTransparency = true; trans_size = 1; - if(ctx2) { + if (ctx2) { ctx2->trans0 = trans0; } } - else if(ctx2) { + else if (ctx2) { ctx2->trans0 = 0.0; } uint32_t diffuseColor = diffuse[0].getPackedValue(trans0); int singleColor = 0; - if(ctx && ctx->isHighlightAll()) { + if (ctx && ctx->isHighlightAll()) { singleColor = 1; diffuseColor = ctx->highlightColor.getPackedValue(trans0); - }else if(ctx && ctx->isSelectAll()) { + } + else if (ctx && ctx->isSelectAll()) { diffuseColor = ctx->selectionColor.getPackedValue(trans0); - singleColor = ctx->isHighlighted()?-1:1; - } else if(ctx2 && ctx2->isSingleColor(diffuseColor,hasTransparency)) { - singleColor = ctx?-1:1; + singleColor = ctx->isHighlighted() ? -1 : 1; + } + else if (ctx2 && ctx2->isSingleColor(diffuseColor, hasTransparency)) { + singleColor = ctx ? -1 : 1; } bool partialRender = (ctx2 && !ctx2->isSelectAll()); - if(singleColor>0 && !partialRender) { - //optimization for single color non-partial rendering - SoMaterialBindingElement::set(state,SoMaterialBindingElement::OVERALL); + if (singleColor > 0 && !partialRender) { + // optimization for single color non-partial rendering + SoMaterialBindingElement::set(state, SoMaterialBindingElement::OVERALL); SoOverrideElement::setMaterialBindingOverride(state, this, true); packedColors.push_back(diffuseColor); - SoLazyElement::setPacked(state, this,1, packedColors.data(), hasTransparency); - SoTextureEnabledElement::set(state,this,false); + SoLazyElement::setPacked(state, this, 1, packedColors.data(), hasTransparency); + SoTextureEnabledElement::set(state, this, false); - if(hasTransparency && action->isRenderingDelayedPaths()) { + if (hasTransparency && action->isRenderingDelayedPaths()) { // rendering delayed paths means we are doing annotation (e.g. // always on top rendering). To render transparency correctly in // this case, we shall use openGL transparency blend. Override @@ -801,86 +910,95 @@ bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction *action, SelContext matIndex.clear(); matIndex.reserve(partIndex.getNum()); - if(ctx && (ctx->isSelectAll() || ctx->isHighlightAll())) { - matIndex.resize(partIndex.getNum(),0); - if(!partialRender) + if (ctx && (ctx->isSelectAll() || ctx->isHighlightAll())) { + matIndex.resize(partIndex.getNum(), 0); + if (!partialRender) { packedColors.push_back(diffuseColor); + } else { // default to full transparent - packedColors.push_back(SbColor(1.0,1.0,1.0).getPackedValue(1.0)); + packedColors.push_back(SbColor(1.0, 1.0, 1.0).getPackedValue(1.0)); packedColors.push_back(diffuseColor); - for(auto idx : ctx2->selectionIndex) { - if(idx>=0 && idxselectionIndex) { + if (idx >= 0 && idx < partIndex.getNum()) { + matIndex[idx] = packedColors.size() - 1; // show only the selected + } } } - if(ctx->highlightIndex>=0 && ctx->highlightIndexhighlightIndex >= 0 && ctx->highlightIndex < partIndex.getNum()) { packedColors.push_back(ctx->highlightColor.getPackedValue(trans0)); - matIndex[ctx->highlightIndex] = packedColors.size()-1; + matIndex[ctx->highlightIndex] = packedColors.size() - 1; } } - else{ - if(partialRender) { - packedColors.push_back(SbColor(1.0,1.0,1.0).getPackedValue(1.0)); - matIndex.resize(partIndex.getNum(),0); + else { + if (partialRender) { + packedColors.push_back(SbColor(1.0, 1.0, 1.0).getPackedValue(1.0)); + matIndex.resize(partIndex.getNum(), 0); - if(mb == SoMaterialBindingElement::OVERALL || singleColor) { + if (mb == SoMaterialBindingElement::OVERALL || singleColor) { packedColors.push_back(diffuseColor); - auto cidx = packedColors.size()-1; - for(auto idx : ctx2->selectionIndex) { - if(idx>=0 && idxapplyColor(idx,packedColors,hasTransparency)) - matIndex[idx] = packedColors.size()-1; - else + auto cidx = packedColors.size() - 1; + for (auto idx : ctx2->selectionIndex) { + if (idx >= 0 && idx < partIndex.getNum()) { + if (!singleColor && ctx2->applyColor(idx, packedColors, hasTransparency)) { + matIndex[idx] = packedColors.size() - 1; + } + else { matIndex[idx] = cidx; + } } } - }else{ + } + else { assert(diffuse_size >= partIndex.getNum()); - for(auto idx : ctx2->selectionIndex) { - if(idx>=0 && idxapplyColor(idx,packedColors,hasTransparency)) { - auto t = idxselectionIndex) { + if (idx >= 0 && idx < partIndex.getNum()) { + if (!ctx2->applyColor(idx, packedColors, hasTransparency)) { + auto t = idx < trans_size ? trans[idx] : trans0; packedColors.push_back(diffuse[idx].getPackedValue(t)); } - matIndex[idx] = packedColors.size()-1; + matIndex[idx] = packedColors.size() - 1; } } } - }else if(mb==SoMaterialBindingElement::OVERALL || singleColor) { + } + else if (mb == SoMaterialBindingElement::OVERALL || singleColor) { packedColors.push_back(diffuseColor); - matIndex.resize(partIndex.getNum(),0); + matIndex.resize(partIndex.getNum(), 0); - if(ctx2 && !singleColor) { - for(auto &v : ctx2->colors) { + if (ctx2 && !singleColor) { + for (auto& v : ctx2->colors) { int idx = v.first; - if(idx>=0 && idxpackColor(v.second,hasTransparency)); - matIndex[idx] = packedColors.size()-1; + if (idx >= 0 && idx < partIndex.getNum()) { + packedColors.push_back(ctx2->packColor(v.second, hasTransparency)); + matIndex[idx] = packedColors.size() - 1; } } } - }else{ + } + else { assert(diffuse_size >= partIndex.getNum()); - packedColors.reserve(diffuse_size+3); - for(int i=0;iapplyColor(i,packedColors,hasTransparency)) + if (!ctx2 || !ctx2->applyColor(i, packedColors, hasTransparency)) { packedColors.push_back(diffuse[i].getPackedValue(t)); + } } } - if(ctx && !ctx->selectionIndex.empty()) { + if (ctx && !ctx->selectionIndex.empty()) { packedColors.push_back(ctx->selectionColor.getPackedValue(trans0)); - for(auto idx : ctx->selectionIndex) { - if(idx>=0 && idxselectionIndex) { + if (idx >= 0 && idx < partIndex.getNum()) { + matIndex[idx] = packedColors.size() - 1; + } } } - if(ctx && ctx->highlightIndex>=0 && ctx->highlightIndexhighlightIndex >= 0 && ctx->highlightIndex < partIndex.getNum()) { packedColors.push_back(ctx->highlightColor.getPackedValue(trans0)); - matIndex[ctx->highlightIndex] = packedColors.size()-1; + matIndex[ctx->highlightIndex] = packedColors.size() - 1; } } @@ -888,12 +1006,14 @@ bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction *action, SelContext if (num != matIndex.size() || materialIndex.getValues(0) != matIndex.data()) { SbBool notify = enableNotify(FALSE); materialIndex.setValuesPointer(matIndex.size(), matIndex.data()); - if (notify) enableNotify(notify); + if (notify) { + enableNotify(notify); + } } SoMaterialBindingElement::set(state, this, SoMaterialBindingElement::PER_PART_INDEXED); SoLazyElement::setPacked(state, this, packedColors.size(), packedColors.data(), hasTransparency); - SoTextureEnabledElement::set(state,this,false); + SoTextureEnabledElement::set(state, this, false); if (hasTransparency && action->isRenderingDelayedPaths()) { // rendering delayed paths means we are doing annotation (e.g. @@ -909,42 +1029,47 @@ bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction *action, SelContext return false; } -void SoBrepFaceSet::GLRenderBelowPath(SoGLRenderAction * action) +void SoBrepFaceSet::GLRenderBelowPath(SoGLRenderAction* action) { inherited::GLRenderBelowPath(action); } -void SoBrepFaceSet::getBoundingBox(SoGetBoundingBoxAction * action) { +void SoBrepFaceSet::getBoundingBox(SoGetBoundingBoxAction* action) +{ - if (this->coordIndex.getNum() < 3) + if (this->coordIndex.getNum() < 3) { return; + } - SelContextPtr ctx2 = Gui::SoFCSelectionRoot::getSecondaryActionContext(action,this); - if(!ctx2 || ctx2->isSelectAll()) { + SelContextPtr ctx2 = Gui::SoFCSelectionRoot::getSecondaryActionContext(action, this); + if (!ctx2 || ctx2->isSelectAll()) { inherited::getBoundingBox(action); return; } - if(ctx2->selectionIndex.empty()) + if (ctx2->selectionIndex.empty()) { return; + } auto state = action->getState(); auto coords = SoCoordinateElement::getInstance(state); - const SbVec3f *coords3d = static_cast(coords)->getArrayPtr3(); - const int32_t *cindices = this->coordIndex.getValues(0); - const int32_t *pindices = this->partIndex.getValues(0); + const SbVec3f* coords3d = static_cast(coords)->getArrayPtr3(); + const int32_t* cindices = this->coordIndex.getValues(0); + const int32_t* pindices = this->partIndex.getValues(0); int numparts = this->partIndex.getNum(); SbBox3f bbox; - for(auto id : ctx2->selectionIndex) { - if (id<0 || id >= numparts) + for (auto id : ctx2->selectionIndex) { + if (id < 0 || id >= numparts) { break; + } // coords - int length=0; - int start=0; - length = (int)pindices[id]*4; - for (int j=0;jextendBy(bbox); + } } - // this macro actually makes the code below more readable :-) +// this macro actually makes the code below more readable :-) #define DO_VERTEX(idx) \ - if (mbind == PER_VERTEX) { \ - pointDetail.setMaterialIndex(matnr); \ - vertex.setMaterialIndex(matnr++); \ - } \ - else if (mbind == PER_VERTEX_INDEXED) { \ - pointDetail.setMaterialIndex(*mindices); \ - vertex.setMaterialIndex(*mindices++); \ - } \ - if (nbind == PER_VERTEX) { \ - pointDetail.setNormalIndex(normnr); \ - currnormal = &normals[normnr++]; \ - vertex.setNormal(*currnormal); \ - } \ - else if (nbind == PER_VERTEX_INDEXED) { \ - pointDetail.setNormalIndex(*nindices); \ - currnormal = &normals[*nindices++]; \ - vertex.setNormal(*currnormal); \ - } \ - if (tb.isFunction()) { \ - vertex.setTextureCoords(tb.get(coords->get3(idx), *currnormal)); \ - if (tb.needIndices()) pointDetail.setTextureCoordIndex(tindices ? *tindices++ : texidx++); \ - } \ - else if (tbind != NONE) { \ - pointDetail.setTextureCoordIndex(tindices ? *tindices : texidx); \ - vertex.setTextureCoords(tb.get(tindices ? *tindices++ : texidx++)); \ - } \ - vertex.setPoint(coords->get3(idx)); \ - pointDetail.setCoordinateIndex(idx); \ - this->shapeVertex(&vertex); + if (mbind == PER_VERTEX) { \ + pointDetail.setMaterialIndex(matnr); \ + vertex.setMaterialIndex(matnr++); \ + } \ + else if (mbind == PER_VERTEX_INDEXED) { \ + pointDetail.setMaterialIndex(*mindices); \ + vertex.setMaterialIndex(*mindices++); \ + } \ + if (nbind == PER_VERTEX) { \ + pointDetail.setNormalIndex(normnr); \ + currnormal = &normals[normnr++]; \ + vertex.setNormal(*currnormal); \ + } \ + else if (nbind == PER_VERTEX_INDEXED) { \ + pointDetail.setNormalIndex(*nindices); \ + currnormal = &normals[*nindices++]; \ + vertex.setNormal(*currnormal); \ + } \ + if (tb.isFunction()) { \ + vertex.setTextureCoords(tb.get(coords->get3(idx), *currnormal)); \ + if (tb.needIndices()) \ + pointDetail.setTextureCoordIndex(tindices ? *tindices++ : texidx++); \ + } \ + else if (tbind != NONE) { \ + pointDetail.setTextureCoordIndex(tindices ? *tindices : texidx); \ + vertex.setTextureCoords(tb.get(tindices ? *tindices++ : texidx++)); \ + } \ + vertex.setPoint(coords->get3(idx)); \ + pointDetail.setCoordinateIndex(idx); \ + this->shapeVertex(&vertex); -void SoBrepFaceSet::generatePrimitives(SoAction * action) +void SoBrepFaceSet::generatePrimitives(SoAction* action) { - //This is highly experimental!!! + // This is highly experimental!!! - if (this->coordIndex.getNum() < 3) + if (this->coordIndex.getNum() < 3) { return; - SoState * state = action->getState(); + } + SoState* state = action->getState(); if (this->vertexProperty.getValue()) { state->push(); @@ -1009,27 +1137,38 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) Binding mbind = this->findMaterialBinding(state); Binding nbind = this->findNormalBinding(state); - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; SbBool doTextures; SbBool sendNormals; SbBool normalCacheUsed; - sendNormals = true; // always generate normals + sendNormals = true; // always generate normals - this->getVertexData(state, coords, normals, cindices, - nindices, tindices, mindices, numindices, - sendNormals, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); SoTextureCoordinateBundle tb(action, false, false); doTextures = tb.needCoordinates(); - if (!sendNormals) nbind = OVERALL; + if (!sendNormals) { + nbind = OVERALL; + } else if (normalCacheUsed && nbind == PER_VERTEX) { nbind = PER_VERTEX_INDEXED; } @@ -1058,15 +1197,16 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) } // FIXME: just call inherited::areTexCoordsIndexed() instead of // the if-check? 20020110 mortene. - else if (SoTextureCoordinateBindingElement::get(state) == - SoTextureCoordinateBindingElement::PER_VERTEX) { + else if (SoTextureCoordinateBindingElement::get(state) + == SoTextureCoordinateBindingElement::PER_VERTEX) { tbind = PER_VERTEX; tindices = nullptr; } else { tbind = PER_VERTEX_INDEXED; - if (!tindices) + if (!tindices) { tindices = cindices; + } } } @@ -1080,12 +1220,12 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) int texidx = 0; TriangleShape mode = POLYGON; TriangleShape newmode; - const int32_t *viptr = cindices; - const int32_t *viendptr = viptr + numindices; - const int32_t *piptr = this->partIndex.getValues(0); + const int32_t* viptr = cindices; + const int32_t* viendptr = viptr + numindices; + const int32_t* piptr = this->partIndex.getValues(0); int num_partindices = this->partIndex.getNum(); - const int32_t *piendptr = piptr + num_partindices; - int32_t v1, v2, v3, v4, v5 = 0, pi; // v5 init unnecessary, but kills a compiler warning. + const int32_t* piendptr = piptr + num_partindices; + int32_t v1, v2, v3, v4, v5 = 0, pi; // v5 init unnecessary, but kills a compiler warning. SoPrimitiveVertex vertex; SoPointDetail pointDetail; @@ -1093,9 +1233,11 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) vertex.setDetail(&pointDetail); - SbVec3f dummynormal(0,0,1); - const SbVec3f *currnormal = &dummynormal; - if (normals) currnormal = normals; + SbVec3f dummynormal(0, 0, 1); + const SbVec3f* currnormal = &dummynormal; + if (normals) { + currnormal = normals; + } vertex.setNormal(*currnormal); int matnr = 0; @@ -1105,10 +1247,12 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) while (pi == 0) { // It may happen that a part has no triangles pi = piptr < piendptr ? *piptr++ : -1; - if (mbind == PER_PART) + if (mbind == PER_PART) { matnr++; - else if (mbind == PER_PART_INDEXED) + } + else if (mbind == PER_PART_INDEXED) { mindices++; + } } while (viptr + 2 < viendptr) { @@ -1119,18 +1263,28 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) break; } v4 = viptr < viendptr ? *viptr++ : -1; - if (v4 < 0) newmode = TRIANGLES; + if (v4 < 0) { + newmode = TRIANGLES; + } else { v5 = viptr < viendptr ? *viptr++ : -1; - if (v5 < 0) newmode = QUADS; - else newmode = POLYGON; + if (v5 < 0) { + newmode = QUADS; + } + else { + newmode = POLYGON; + } } if (newmode != mode) { - if (mode != POLYGON) this->endShape(); + if (mode != POLYGON) { + this->endShape(); + } mode = newmode; this->beginShape(action, mode, &faceDetail); } - else if (mode == POLYGON) this->beginShape(action, POLYGON, &faceDetail); + else if (mode == POLYGON) { + this->beginShape(action, POLYGON, &faceDetail); + } // vertex 1 can't use DO_VERTEX if (mbind == PER_PART) { @@ -1166,7 +1320,9 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) if (tb.isFunction()) { vertex.setTextureCoords(tb.get(coords->get3(v1), *currnormal)); - if (tb.needIndices()) pointDetail.setTextureCoordIndex(tindices ? *tindices++ : texidx++); + if (tb.needIndices()) { + pointDetail.setTextureCoordIndex(tindices ? *tindices++ : texidx++); + } } else if (tbind != NONE) { pointDetail.setTextureCoordIndex(tindices ? *tindices : texidx); @@ -1198,7 +1354,9 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) if (nbind == PER_VERTEX_INDEXED) { nindices++; } - if (tindices) tindices++; + if (tindices) { + tindices++; + } trinr++; if (pi == trinr) { @@ -1206,15 +1364,19 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) while (pi == 0) { // It may happen that a part has no triangles pi = piptr < piendptr ? *piptr++ : -1; - if (mbind == PER_PART) + if (mbind == PER_PART) { matnr++; - else if (mbind == PER_PART_INDEXED) + } + else if (mbind == PER_PART_INDEXED) { mindices++; + } } trinr = 0; } } - if (mode != POLYGON) this->endShape(); + if (mode != POLYGON) { + this->endShape(); + } if (normalCacheUsed) { this->readUnlockNormalCache(); @@ -1227,33 +1389,34 @@ void SoBrepFaceSet::generatePrimitives(SoAction * action) #undef DO_VERTEX -void SoBrepFaceSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) +void SoBrepFaceSet::renderHighlight(SoGLRenderAction* action, SelContextPtr ctx) { - if(!ctx || ctx->highlightIndex < 0) + if (!ctx || ctx->highlightIndex < 0) { return; + } - SoState * state = action->getState(); + SoState* state = action->getState(); state->push(); SoLazyElement::setEmissive(state, &ctx->highlightColor); // if shading is disabled then set also the diffuse color if (SoLazyElement::getLightModel(state) == SoLazyElement::BASE_COLOR) { packedColor = ctx->highlightColor.getPackedValue(0.0); - SoLazyElement::setPacked(state, this,1, &packedColor,false); + SoLazyElement::setPacked(state, this, 1, &packedColor, false); } - SoTextureEnabledElement::set(state,this,false); + SoTextureEnabledElement::set(state, this, false); Binding mbind = this->findMaterialBinding(state); Binding nbind = this->findNormalBinding(state); - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; - const int32_t * pindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; + const int32_t* pindices; SbBool doTextures; SbBool normalCacheUsed; @@ -1262,11 +1425,20 @@ void SoBrepFaceSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) doTextures = tb.needCoordinates(); SbBool sendNormals = !mb.isColorOnly() || tb.isFunction(); - this->getVertexData(state, coords, normals, cindices, - nindices, tindices, mindices, numindices, - sendNormals, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material int id = ctx->highlightIndex; if (id != std::numeric_limits::max() && id >= this->partIndex.getNum()) { @@ -1274,74 +1446,101 @@ void SoBrepFaceSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) } else { // just in case someone forgot - if (!mindices) mindices = cindices; - if (!nindices) nindices = cindices; + if (!mindices) { + mindices = cindices; + } + if (!nindices) { + nindices = cindices; + } pindices = this->partIndex.getValues(0); // coords - int start=0; + int start = 0; int length; - if(id == std::numeric_limits::max()) { + if (id == std::numeric_limits::max()) { length = numindices; id = 0; - } else { - length = (int)pindices[id]*4; - for (int i=0;i(coords), &(cindices[start]), length, - &(pindices[id]), 1, normals, nindices, &mb, mindices, &tb, tindices, nbind, mbind, doTextures); + renderShape( + action, + false, + static_cast(coords), + &(cindices[start]), + length, + &(pindices[id]), + 1, + normals, + nindices, + &mb, + mindices, + &tb, + tindices, + nbind, + mbind, + doTextures + ); } state->pop(); - if (normalCacheUsed) + if (normalCacheUsed) { this->readUnlockNormalCache(); + } } -void SoBrepFaceSet::renderSelection(SoGLRenderAction *action, SelContextPtr ctx, bool push) +void SoBrepFaceSet::renderSelection(SoGLRenderAction* action, SelContextPtr ctx, bool push) { - if(!ctx || ctx->selectionIndex.empty()) + if (!ctx || ctx->selectionIndex.empty()) { return; + } - SoState * state = action->getState(); + SoState* state = action->getState(); - if(push) { + if (push) { state->push(); SoLazyElement::setEmissive(state, &ctx->selectionColor); // if shading is disabled then set also the diffuse color if (SoLazyElement::getLightModel(state) == SoLazyElement::BASE_COLOR) { packedColor = ctx->selectionColor.getPackedValue(0.0); - SoLazyElement::setPacked(state, this,1, &packedColor,false); + SoLazyElement::setPacked(state, this, 1, &packedColor, false); } - SoTextureEnabledElement::set(state,this,false); + SoTextureEnabledElement::set(state, this, false); } Binding mbind = this->findMaterialBinding(state); Binding nbind = this->findNormalBinding(state); - const SoCoordinateElement * coords; - const SbVec3f * normals; - const int32_t * cindices; + const SoCoordinateElement* coords; + const SbVec3f* normals; + const int32_t* cindices; int numindices; - const int32_t * nindices; - const int32_t * tindices; - const int32_t * mindices; - const int32_t * pindices; + const int32_t* nindices; + const int32_t* tindices; + const int32_t* mindices; + const int32_t* pindices; SbBool doTextures; SbBool normalCacheUsed; @@ -1350,118 +1549,161 @@ void SoBrepFaceSet::renderSelection(SoGLRenderAction *action, SelContextPtr ctx, doTextures = tb.needCoordinates(); SbBool sendNormals = !mb.isColorOnly() || tb.isFunction(); - this->getVertexData(state, coords, normals, cindices, - nindices, tindices, mindices, numindices, - sendNormals, normalCacheUsed); + this->getVertexData( + state, + coords, + normals, + cindices, + nindices, + tindices, + mindices, + numindices, + sendNormals, + normalCacheUsed + ); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material // just in case someone forgot - if (!mindices) mindices = cindices; - if (!nindices) nindices = cindices; + if (!mindices) { + mindices = cindices; + } + if (!nindices) { + nindices = cindices; + } pindices = this->partIndex.getValues(0); - if(push) { + if (push) { // materials mbind = OVERALL; doTextures = false; } - for(auto id : ctx->selectionIndex) { + for (auto id : ctx->selectionIndex) { if (id >= this->partIndex.getNum()) { SoDebugError::postWarning("SoBrepFaceSet::renderSelection", "selectionIndex out of range"); break; } - if (id>=0 && id==ctx->highlightIndex) + if (id >= 0 && id == ctx->highlightIndex) { continue; + } // coords - int length=0; - int start=0; - int numparts=1; + int length = 0; + int start = 0; + int numparts = 1; // if < 0 then select everything if (id < 0) { length = numindices; id = 0; - } else { - length = (int)pindices[id]*4; - for (int j=0;j(coords), &(cindices[start]), length, - &(pindices[id]), numparts, normals_s, nindices_s, &mb, mindices, &tb, tindices, nbind, mbind, doTextures?1:0); + renderShape( + action, + false, + static_cast(coords), + &(cindices[start]), + length, + &(pindices[id]), + numparts, + normals_s, + nindices_s, + &mb, + mindices, + &tb, + tindices, + nbind, + mbind, + doTextures ? 1 : 0 + ); } if (push) { state->pop(); } - if (normalCacheUsed) + if (normalCacheUsed) { this->readUnlockNormalCache(); + } } -void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, - const SoGLCoordinateElement * const vertexlist, - const int32_t *vertexindices, - int num_indices, - const int32_t *partindices, - int num_partindices, - const SbVec3f *normals, - const int32_t *normalindices, - SoMaterialBundle *const materials, - const int32_t *matindices, - SoTextureCoordinateBundle * const texcoords, - const int32_t *texindices, - const int nbind, - const int mbind, - SbBool texture) +void SoBrepFaceSet::VBO::render( + SoGLRenderAction* action, + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int num_indices, + const int32_t* partindices, + int num_partindices, + const SbVec3f* normals, + const int32_t* normalindices, + SoMaterialBundle* const materials, + const int32_t* matindices, + SoTextureCoordinateBundle* const texcoords, + const int32_t* texindices, + const int nbind, + const int mbind, + SbBool texture +) { - (void)texcoords; (void)texindices; (void)texture; - const SbVec3f * coords3d = vertexlist->getArrayPtr3(); - SbVec3f * cur_coords3d = const_cast(coords3d); + (void)texcoords; + (void)texindices; + (void)texture; + const SbVec3f* coords3d = vertexlist->getArrayPtr3(); + SbVec3f* cur_coords3d = const_cast(coords3d); - const int32_t *viptr = vertexindices; - const int32_t *viendptr = viptr + num_indices; - const int32_t *piptr = partindices; - const int32_t *piendptr = piptr + num_partindices; + const int32_t* viptr = vertexindices; + const int32_t* viendptr = viptr + num_indices; + const int32_t* piptr = partindices; + const int32_t* piendptr = piptr + num_partindices; int32_t v1, v2, v3, v4, pi; - SbVec3f dummynormal(0,0,1); + SbVec3f dummynormal(0, 0, 1); int numverts = vertexlist->getNum(); - const SbVec3f *currnormal = &dummynormal; - if (normals) currnormal = normals; + const SbVec3f* currnormal = &dummynormal; + if (normals) { + currnormal = normals; + } int matnr = 0; int trinr = 0; - float * vertex_array = nullptr; - GLuint * index_array = nullptr; - SbColor mycolor1,mycolor2,mycolor3; - SbVec3f *mynormal1 = const_cast(currnormal); - SbVec3f *mynormal2 = const_cast(currnormal); - SbVec3f *mynormal3 = const_cast(currnormal); - int indice=0; - uint32_t RGBA,R,G,B,A; - float Rf,Gf,Bf,Af; + float* vertex_array = nullptr; + GLuint* index_array = nullptr; + SbColor mycolor1, mycolor2, mycolor3; + SbVec3f* mynormal1 = const_cast(currnormal); + SbVec3f* mynormal2 = const_cast(currnormal); + SbVec3f* mynormal3 = const_cast(currnormal); + int indice = 0; + uint32_t RGBA, R, G, B, A; + float Rf, Gf, Bf, Af; uint32_t contextId = action->getCacheContext(); - auto res = this->vbomap.insert(std::make_pair(contextId,VBO::Buffer())); - VBO::Buffer &buf = res.first->second; + auto res = this->vbomap.insert(std::make_pair(contextId, VBO::Buffer())); + VBO::Buffer& buf = res.first->second; if (res.second) { #ifdef FC_OS_WIN32 - const cc_glglue * glue = cc_glglue_instance(action->getCacheContext()); - PFNGLGENBUFFERSPROC glGenBuffersARB = (PFNGLGENBUFFERSPROC)cc_glglue_getprocaddress(glue, "glGenBuffersARB"); + const cc_glglue* glue = cc_glglue_instance(action->getCacheContext()); + PFNGLGENBUFFERSPROC glGenBuffersARB + = (PFNGLGENBUFFERSPROC)cc_glglue_getprocaddress(glue, "glGenBuffersARB"); #endif glGenBuffersARB(2, buf.myvbo); buf.vertex_array_size = 0; @@ -1469,10 +1711,11 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, buf.vboLoaded = false; } - if ((buf.vertex_array_size != (sizeof(float) * num_indices * 10)) || - (buf.index_array_size != (sizeof(GLuint) * num_indices))) { - if ((buf.vertex_array_size != 0 ) && ( buf.index_array_size != 0)) + if ((buf.vertex_array_size != (sizeof(float) * num_indices * 10)) + || (buf.index_array_size != (sizeof(GLuint) * num_indices))) { + if ((buf.vertex_array_size != 0) && (buf.index_array_size != 0)) { buf.updateVbo = true; + } } // vbo loaded is defining if we must pre-load data into the VBO. When the variable is set to 0 @@ -1483,39 +1726,46 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, if (!buf.vboLoaded || buf.updateVbo) { #ifdef FC_OS_WIN32 - const cc_glglue * glue = cc_glglue_instance(action->getCacheContext()); + const cc_glglue* glue = cc_glglue_instance(action->getCacheContext()); - PFNGLBINDBUFFERARBPROC glBindBufferARB = (PFNGLBINDBUFFERARBPROC) cc_glglue_getprocaddress(glue, "glBindBufferARB"); - //PFNGLMAPBUFFERARBPROC glMapBufferARB = (PFNGLMAPBUFFERARBPROC) cc_glglue_getprocaddress(glue, "glMapBufferARB"); - PFNGLGENBUFFERSPROC glGenBuffersARB = (PFNGLGENBUFFERSPROC)cc_glglue_getprocaddress(glue, "glGenBuffersARB"); - PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)cc_glglue_getprocaddress(glue, "glDeleteBuffersARB"); - PFNGLBUFFERDATAARBPROC glBufferDataARB = (PFNGLBUFFERDATAARBPROC)cc_glglue_getprocaddress(glue, "glBufferDataARB"); + PFNGLBINDBUFFERARBPROC glBindBufferARB + = (PFNGLBINDBUFFERARBPROC)cc_glglue_getprocaddress(glue, "glBindBufferARB"); + // PFNGLMAPBUFFERARBPROC glMapBufferARB = (PFNGLMAPBUFFERARBPROC) + // cc_glglue_getprocaddress(glue, "glMapBufferARB"); + PFNGLGENBUFFERSPROC glGenBuffersARB + = (PFNGLGENBUFFERSPROC)cc_glglue_getprocaddress(glue, "glGenBuffersARB"); + PFNGLDELETEBUFFERSARBPROC glDeleteBuffersARB + = (PFNGLDELETEBUFFERSARBPROC)cc_glglue_getprocaddress(glue, "glDeleteBuffersARB"); + PFNGLBUFFERDATAARBPROC glBufferDataARB + = (PFNGLBUFFERDATAARBPROC)cc_glglue_getprocaddress(glue, "glBufferDataARB"); #endif // We must manage buffer size increase let's clear everything and re-init to test the // clearing process glDeleteBuffersARB(2, buf.myvbo); glGenBuffersARB(2, buf.myvbo); - vertex_array = ( float * ) malloc ( sizeof(float) * num_indices * 10 ); - index_array = ( GLuint *) malloc ( sizeof(GLuint) * num_indices ); + vertex_array = (float*)malloc(sizeof(float) * num_indices * 10); + index_array = (GLuint*)malloc(sizeof(GLuint) * num_indices); buf.vertex_array_size = sizeof(float) * num_indices * 10; buf.index_array_size = sizeof(GLuint) * num_indices; this->vbomap[contextId] = buf; this->indice_array = 0; // Get the initial colors - SoState * state = action->getState(); - mycolor1=SoLazyElement::getDiffuse(state,0); - mycolor2=SoLazyElement::getDiffuse(state,0); - mycolor3=SoLazyElement::getDiffuse(state,0); + SoState* state = action->getState(); + mycolor1 = SoLazyElement::getDiffuse(state, 0); + mycolor2 = SoLazyElement::getDiffuse(state, 0); + mycolor3 = SoLazyElement::getDiffuse(state, 0); pi = piptr < piendptr ? *piptr++ : -1; while (pi == 0) { - // It may happen that a part has no triangles - pi = piptr < piendptr ? *piptr++ : -1; - if (mbind == PER_PART) - matnr++; - else if (mbind == PER_PART_INDEXED) - matindices++; + // It may happen that a part has no triangles + pi = piptr < piendptr ? *piptr++ : -1; + if (mbind == PER_PART) { + matnr++; + } + else if (mbind == PER_PART_INDEXED) { + matindices++; + } } while (viptr + 2 < viendptr) { @@ -1523,8 +1773,7 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, v2 = *viptr++; v3 = *viptr++; // This test is for robustness upon buggy data sets - if (v1 < 0 || v2 < 0 || v3 < 0 || - v1 >= numverts || v2 >= numverts || v3 >= numverts) { + if (v1 < 0 || v2 < 0 || v3 < 0 || v1 >= numverts || v2 >= numverts || v3 >= numverts) { break; } v4 = viptr < viendptr ? *viptr++ : -1; @@ -1533,14 +1782,15 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, if (mbind == PER_PART) { if (trinr == 0) { materials->send(matnr++, true); - mycolor1=SoLazyElement::getDiffuse(state,matnr-1); - mycolor2=mycolor1; - mycolor3=mycolor1; + mycolor1 = SoLazyElement::getDiffuse(state, matnr - 1); + mycolor2 = mycolor1; + mycolor3 = mycolor1; } } else if (mbind == PER_PART_INDEXED) { - if (trinr == 0) + if (trinr == 0) { materials->send(*matindices++, true); + } } else if (mbind == PER_VERTEX || mbind == PER_FACE) { materials->send(matnr++, true); @@ -1552,129 +1802,128 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, if (normals) { if (nbind == PER_VERTEX || nbind == PER_FACE) { currnormal = normals++; - mynormal1 = const_cast(currnormal); + mynormal1 = const_cast(currnormal); } else if (nbind == PER_VERTEX_INDEXED || nbind == PER_FACE_INDEXED) { currnormal = &normals[*normalindices++]; - mynormal1 = const_cast(currnormal); + mynormal1 = const_cast(currnormal); } } - if (mbind == PER_VERTEX) + if (mbind == PER_VERTEX) { materials->send(matnr++, true); - else if (mbind == PER_VERTEX_INDEXED) + } + else if (mbind == PER_VERTEX_INDEXED) { materials->send(*matindices++, true); + } if (normals) { if (nbind == PER_VERTEX) { currnormal = normals++; - mynormal2 = const_cast(currnormal); - } - else if (nbind == PER_VERTEX_INDEXED) { - currnormal = &normals[*normalindices++]; - mynormal2 = const_cast(currnormal); - } - } - - if (mbind == PER_VERTEX) - materials->send(matnr++, true); - else if (mbind == PER_VERTEX_INDEXED) - materials->send(*matindices++, true); - if (normals) { - if (nbind == PER_VERTEX) { - currnormal = normals++; - mynormal3 =const_cast(currnormal); + mynormal2 = const_cast(currnormal); } else if (nbind == PER_VERTEX_INDEXED) { currnormal = &normals[*normalindices++]; - mynormal3 = const_cast(currnormal); + mynormal2 = const_cast(currnormal); } } - if (nbind == PER_VERTEX_INDEXED) + + if (mbind == PER_VERTEX) { + materials->send(matnr++, true); + } + else if (mbind == PER_VERTEX_INDEXED) { + materials->send(*matindices++, true); + } + if (normals) { + if (nbind == PER_VERTEX) { + currnormal = normals++; + mynormal3 = const_cast(currnormal); + } + else if (nbind == PER_VERTEX_INDEXED) { + currnormal = &normals[*normalindices++]; + mynormal3 = const_cast(currnormal); + } + } + if (nbind == PER_VERTEX_INDEXED) { normalindices++; + } /* We building the Vertex dataset there and push it to a VBO */ /* The Vertex array shall contain per element vertex_coordinates[3], normal_coordinates[3], color_value[3] (RGBA format) */ - index_array[this->indice_array] = this->indice_array; - index_array[this->indice_array+1] = this->indice_array + 1; - index_array[this->indice_array+2] = this->indice_array + 2; + index_array[this->indice_array] = this->indice_array; + index_array[this->indice_array + 1] = this->indice_array + 1; + index_array[this->indice_array + 2] = this->indice_array + 2; this->indice_array += 3; - ((SbVec3f *)(cur_coords3d+v1 ))->getValue(vertex_array[indice+0], - vertex_array[indice+1], - vertex_array[indice+2]); + ((SbVec3f*)(cur_coords3d + v1)) + ->getValue(vertex_array[indice + 0], vertex_array[indice + 1], vertex_array[indice + 2]); - ((SbVec3f *)(mynormal1))->getValue(vertex_array[indice+3], - vertex_array[indice+4], - vertex_array[indice+5]); + ((SbVec3f*)(mynormal1)) + ->getValue(vertex_array[indice + 3], vertex_array[indice + 4], vertex_array[indice + 5]); /* We decode the Vertex1 color */ RGBA = mycolor1.getPackedValue(); - R = ( RGBA & 0xFF000000 ) >> 24 ; - G = ( RGBA & 0xFF0000 ) >> 16; - B = ( RGBA & 0xFF00 ) >> 8; - A = ( RGBA & 0xFF ); + R = (RGBA & 0xFF000000) >> 24; + G = (RGBA & 0xFF0000) >> 16; + B = (RGBA & 0xFF00) >> 8; + A = (RGBA & 0xFF); - Rf = (((float )R) / 255.0); - Gf = (((float )G) / 255.0); - Bf = (((float )B) / 255.0); - Af = (((float )A) / 255.0); + Rf = (((float)R) / 255.0); + Gf = (((float)G) / 255.0); + Bf = (((float)B) / 255.0); + Af = (((float)A) / 255.0); - vertex_array[indice+6] = Rf; - vertex_array[indice+7] = Gf; - vertex_array[indice+8] = Bf; - vertex_array[indice+9] = Af; - indice+=10; + vertex_array[indice + 6] = Rf; + vertex_array[indice + 7] = Gf; + vertex_array[indice + 8] = Bf; + vertex_array[indice + 9] = Af; + indice += 10; - ((SbVec3f *)(cur_coords3d+v2))->getValue(vertex_array[indice+0], - vertex_array[indice+1], - vertex_array[indice+2]); - ((SbVec3f *)(mynormal2))->getValue(vertex_array[indice+3], - vertex_array[indice+4], - vertex_array[indice+5]); + ((SbVec3f*)(cur_coords3d + v2)) + ->getValue(vertex_array[indice + 0], vertex_array[indice + 1], vertex_array[indice + 2]); + ((SbVec3f*)(mynormal2)) + ->getValue(vertex_array[indice + 3], vertex_array[indice + 4], vertex_array[indice + 5]); RGBA = mycolor2.getPackedValue(); - R = ( RGBA & 0xFF000000 ) >> 24 ; - G = ( RGBA & 0xFF0000 ) >> 16; - B = ( RGBA & 0xFF00 ) >> 8; - A = ( RGBA & 0xFF ); + R = (RGBA & 0xFF000000) >> 24; + G = (RGBA & 0xFF0000) >> 16; + B = (RGBA & 0xFF00) >> 8; + A = (RGBA & 0xFF); - Rf = (((float )R) / 255.0); - Gf = (((float )G) / 255.0); - Bf = (((float )B) / 255.0); - Af = (((float )A) / 255.0); + Rf = (((float)R) / 255.0); + Gf = (((float)G) / 255.0); + Bf = (((float)B) / 255.0); + Af = (((float)A) / 255.0); - vertex_array[indice+6] = Rf; - vertex_array[indice+7] = Gf; - vertex_array[indice+8] = Bf; - vertex_array[indice+9] = Af; - indice+=10; + vertex_array[indice + 6] = Rf; + vertex_array[indice + 7] = Gf; + vertex_array[indice + 8] = Bf; + vertex_array[indice + 9] = Af; + indice += 10; - ((SbVec3f *)(cur_coords3d+v3))->getValue(vertex_array[indice+0], - vertex_array[indice+1], - vertex_array[indice+2]); - ((SbVec3f *)(mynormal3))->getValue(vertex_array[indice+3], - vertex_array[indice+4], - vertex_array[indice+5]); + ((SbVec3f*)(cur_coords3d + v3)) + ->getValue(vertex_array[indice + 0], vertex_array[indice + 1], vertex_array[indice + 2]); + ((SbVec3f*)(mynormal3)) + ->getValue(vertex_array[indice + 3], vertex_array[indice + 4], vertex_array[indice + 5]); RGBA = mycolor3.getPackedValue(); - R = ( RGBA & 0xFF000000 ) >> 24 ; - G = ( RGBA & 0xFF0000 ) >> 16; - B = ( RGBA & 0xFF00 ) >> 8; - A = ( RGBA & 0xFF ); + R = (RGBA & 0xFF000000) >> 24; + G = (RGBA & 0xFF0000) >> 16; + B = (RGBA & 0xFF00) >> 8; + A = (RGBA & 0xFF); - Rf = (((float )R) / 255.0); - Gf = (((float )G) / 255.0); - Bf = (((float )B) / 255.0); - Af = (((float )A) / 255.0); + Rf = (((float)R) / 255.0); + Gf = (((float)G) / 255.0); + Bf = (((float)B) / 255.0); + Af = (((float)A) / 255.0); - vertex_array[indice+6] = Rf; - vertex_array[indice+7] = Gf; - vertex_array[indice+8] = Bf; - vertex_array[indice+9] = Af; - indice+=10; + vertex_array[indice + 6] = Rf; + vertex_array[indice + 7] = Gf; + vertex_array[indice + 8] = Bf; + vertex_array[indice + 9] = Af; + indice += 10; /* ============================================================ */ trinr++; @@ -1683,20 +1932,27 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, while (pi == 0) { // It may happen that a part has no triangles pi = piptr < piendptr ? *piptr++ : -1; - if (mbind == PER_PART) + if (mbind == PER_PART) { matnr++; - else if (mbind == PER_PART_INDEXED) - matindices++; + } + else if (mbind == PER_PART_INDEXED) { + matindices++; + } } trinr = 0; } } glBindBufferARB(GL_ARRAY_BUFFER_ARB, buf.myvbo[0]); - glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(float) * indice , vertex_array, GL_DYNAMIC_DRAW_ARB); + glBufferDataARB(GL_ARRAY_BUFFER_ARB, sizeof(float) * indice, vertex_array, GL_DYNAMIC_DRAW_ARB); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, buf.myvbo[1]); - glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, sizeof(GLuint) * this->indice_array , &index_array[0], GL_DYNAMIC_DRAW_ARB); + glBufferDataARB( + GL_ELEMENT_ARRAY_BUFFER_ARB, + sizeof(GLuint) * this->indice_array, + &index_array[0], + GL_DYNAMIC_DRAW_ARB + ); glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); @@ -1709,8 +1965,9 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, // This is the VBO rendering code #ifdef FC_OS_WIN32 - const cc_glglue * glue = cc_glglue_instance(action->getCacheContext()); - PFNGLBINDBUFFERARBPROC glBindBufferARB = (PFNGLBINDBUFFERARBPROC)cc_glglue_getprocaddress(glue, "glBindBufferARB"); + const cc_glglue* glue = cc_glglue_instance(action->getCacheContext()); + PFNGLBINDBUFFERARBPROC glBindBufferARB + = (PFNGLBINDBUFFERARBPROC)cc_glglue_getprocaddress(glue, "glBindBufferARB"); #endif if (!buf.updateVbo) { @@ -1722,11 +1979,11 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, glEnableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_COLOR_ARRAY); - glVertexPointer(3,GL_FLOAT,10*sizeof(GLfloat),nullptr); - glNormalPointer(GL_FLOAT,10*sizeof(GLfloat),(GLvoid *)(3*sizeof(GLfloat))); - glColorPointer(4,GL_FLOAT,10*sizeof(GLfloat),(GLvoid *)(6*sizeof(GLfloat))); + glVertexPointer(3, GL_FLOAT, 10 * sizeof(GLfloat), nullptr); + glNormalPointer(GL_FLOAT, 10 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); + glColorPointer(4, GL_FLOAT, 10 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); - glDrawElements(GL_TRIANGLES, this->indice_array, GL_UNSIGNED_INT, (void *)nullptr); + glDrawElements(GL_TRIANGLES, this->indice_array, GL_UNSIGNED_INT, (void*)nullptr); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); @@ -1737,22 +1994,24 @@ void SoBrepFaceSet::VBO::render(SoGLRenderAction * action, // The data is within the VBO we can clear it at application level } -void SoBrepFaceSet::renderShape(SoGLRenderAction * action, - SbBool hasVBO, - const SoGLCoordinateElement * const vertexlist, - const int32_t *vertexindices, - int num_indices, - const int32_t *partindices, - int num_partindices, - const SbVec3f *normals, - const int32_t *normalindices, - SoMaterialBundle *const materials, - const int32_t *matindices, - SoTextureCoordinateBundle * const texcoords, - const int32_t *texindices, - const int nbind, - const int mbind, - SbBool texture) +void SoBrepFaceSet::renderShape( + SoGLRenderAction* action, + SbBool hasVBO, + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int num_indices, + const int32_t* partindices, + int num_partindices, + const SbVec3f* normals, + const int32_t* normalindices, + SoMaterialBundle* const materials, + const int32_t* matindices, + SoTextureCoordinateBundle* const texcoords, + const int32_t* texindices, + const int nbind, + const int mbind, + SbBool texture +) { // Can we use vertex buffer objects? if (hasVBO) { @@ -1762,26 +2021,43 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, // if no shading is set then the normals are all equal nbinding = static_cast(OVERALL); } - PRIVATE(this)->render(action, vertexlist, vertexindices, num_indices, partindices, num_partindices, normals, - normalindices, materials, matindices, texcoords, texindices, nbinding, mbind, texture); + PRIVATE(this)->render( + action, + vertexlist, + vertexindices, + num_indices, + partindices, + num_partindices, + normals, + normalindices, + materials, + matindices, + texcoords, + texindices, + nbinding, + mbind, + texture + ); return; } int texidx = 0; - const SbVec3f * coords3d = nullptr; + const SbVec3f* coords3d = nullptr; coords3d = vertexlist->getArrayPtr3(); - const int32_t *viptr = vertexindices; - const int32_t *viendptr = viptr + num_indices; - const int32_t *piptr = partindices; - const int32_t *piendptr = piptr + num_partindices; + const int32_t* viptr = vertexindices; + const int32_t* viendptr = viptr + num_indices; + const int32_t* piptr = partindices; + const int32_t* piendptr = piptr + num_partindices; int32_t v1, v2, v3, v4, pi; - SbVec3f dummynormal(0,0,1); + SbVec3f dummynormal(0, 0, 1); int numverts = vertexlist->getNum(); - const SbVec3f *currnormal = &dummynormal; - if (normals) currnormal = normals; + const SbVec3f* currnormal = &dummynormal; + if (normals) { + currnormal = normals; + } int matnr = 0; int trinr = 0; @@ -1791,31 +2067,34 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, while (pi == 0) { // It may happen that a part has no triangles pi = piptr < piendptr ? *piptr++ : -1; - if (mbind == PER_PART) + if (mbind == PER_PART) { matnr++; - else if (mbind == PER_PART_INDEXED) + } + else if (mbind == PER_PART_INDEXED) { matindices++; + } } glBegin(GL_TRIANGLES); while (viptr + 2 < viendptr) { - v1 = *viptr++; - v2 = *viptr++; - v3 = *viptr++; - if (v1 < 0 || v2 < 0 || v3 < 0 || - v1 >= numverts || v2 >= numverts || v3 >= numverts) { + v1 = *viptr++; + v2 = *viptr++; + v3 = *viptr++; + if (v1 < 0 || v2 < 0 || v3 < 0 || v1 >= numverts || v2 >= numverts || v3 >= numverts) { break; } v4 = viptr < viendptr ? *viptr++ : -1; (void)v4; /* vertex 1 *********************************************************/ if (mbind == PER_PART) { - if (trinr == 0) + if (trinr == 0) { materials->send(matnr++, true); + } } else if (mbind == PER_PART_INDEXED) { - if (trinr == 0) + if (trinr == 0) { materials->send(*matindices++, true); + } } else if (mbind == PER_VERTEX || mbind == PER_FACE) { materials->send(matnr++, true); @@ -1836,17 +2115,17 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, } if (texture) { - texcoords->send(texindices ? *texindices++ : texidx++, - vertexlist->get3(v1), - *currnormal); + texcoords->send(texindices ? *texindices++ : texidx++, vertexlist->get3(v1), *currnormal); } - glVertex3fv((const GLfloat*) (coords3d + v1)); + glVertex3fv((const GLfloat*)(coords3d + v1)); /* vertex 2 *********************************************************/ - if (mbind == PER_VERTEX) + if (mbind == PER_VERTEX) { materials->send(matnr++, true); - else if (mbind == PER_VERTEX_INDEXED) + } + else if (mbind == PER_VERTEX_INDEXED) { materials->send(*matindices++, true); + } if (normals) { if (nbind == PER_VERTEX) { @@ -1860,18 +2139,18 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, } if (texture) { - texcoords->send(texindices ? *texindices++ : texidx++, - vertexlist->get3(v2), - *currnormal); + texcoords->send(texindices ? *texindices++ : texidx++, vertexlist->get3(v2), *currnormal); } - glVertex3fv((const GLfloat*) (coords3d + v2)); + glVertex3fv((const GLfloat*)(coords3d + v2)); /* vertex 3 *********************************************************/ - if (mbind == PER_VERTEX) + if (mbind == PER_VERTEX) { materials->send(matnr++, true); - else if (mbind == PER_VERTEX_INDEXED) + } + else if (mbind == PER_VERTEX_INDEXED) { materials->send(*matindices++, true); + } if (normals) { if (nbind == PER_VERTEX) { @@ -1885,18 +2164,18 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, } if (texture) { - texcoords->send(texindices ? *texindices++ : texidx++, - vertexlist->get3(v3), - *currnormal); + texcoords->send(texindices ? *texindices++ : texidx++, vertexlist->get3(v3), *currnormal); } - glVertex3fv((const GLfloat*) (coords3d + v3)); + glVertex3fv((const GLfloat*)(coords3d + v3)); - if (mbind == PER_VERTEX_INDEXED) + if (mbind == PER_VERTEX_INDEXED) { matindices++; + } - if (nbind == PER_VERTEX_INDEXED) + if (nbind == PER_VERTEX_INDEXED) { normalindices++; + } if (texture && texindices) { texindices++; @@ -1908,10 +2187,12 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, while (pi == 0) { // It may happen that a part has no triangles pi = piptr < piendptr ? *piptr++ : -1; - if (mbind == PER_PART) + if (mbind == PER_PART) { matnr++; - else if (mbind == PER_PART_INDEXED) + } + else if (mbind == PER_PART_INDEXED) { matindices++; + } } trinr = 0; } @@ -1919,20 +2200,22 @@ void SoBrepFaceSet::renderShape(SoGLRenderAction * action, glEnd(); } -SoDetail * SoBrepFaceSet::createTriangleDetail(SoRayPickAction * action, - const SoPrimitiveVertex * v1, - const SoPrimitiveVertex * v2, - const SoPrimitiveVertex * v3, - SoPickedPoint * pp) +SoDetail* SoBrepFaceSet::createTriangleDetail( + SoRayPickAction* action, + const SoPrimitiveVertex* v1, + const SoPrimitiveVertex* v2, + const SoPrimitiveVertex* v3, + SoPickedPoint* pp +) { SoDetail* detail = inherited::createTriangleDetail(action, v1, v2, v3, pp); - const int32_t * indices = this->partIndex.getValues(0); + const int32_t* indices = this->partIndex.getValues(0); int num = this->partIndex.getNum(); if (indices) { SoFaceDetail* face_detail = static_cast(detail); int index = face_detail->getFaceIndex(); int count = 0; - for (int i=0; isetPartIndex(i); @@ -1943,72 +2226,69 @@ SoDetail * SoBrepFaceSet::createTriangleDetail(SoRayPickAction * action, return detail; } -SoBrepFaceSet::Binding -SoBrepFaceSet::findMaterialBinding(SoState * const state) const +SoBrepFaceSet::Binding SoBrepFaceSet::findMaterialBinding(SoState* const state) const { Binding binding = OVERALL; - SoMaterialBindingElement::Binding matbind = - SoMaterialBindingElement::get(state); + SoMaterialBindingElement::Binding matbind = SoMaterialBindingElement::get(state); switch (matbind) { - case SoMaterialBindingElement::OVERALL: - binding = OVERALL; - break; - case SoMaterialBindingElement::PER_VERTEX: - binding = PER_VERTEX; - break; - case SoMaterialBindingElement::PER_VERTEX_INDEXED: - binding = PER_VERTEX_INDEXED; - break; - case SoMaterialBindingElement::PER_PART: - binding = PER_PART; - break; - case SoMaterialBindingElement::PER_FACE: - binding = PER_FACE; - break; - case SoMaterialBindingElement::PER_PART_INDEXED: - binding = PER_PART_INDEXED; - break; - case SoMaterialBindingElement::PER_FACE_INDEXED: - binding = PER_FACE_INDEXED; - break; - default: - break; + case SoMaterialBindingElement::OVERALL: + binding = OVERALL; + break; + case SoMaterialBindingElement::PER_VERTEX: + binding = PER_VERTEX; + break; + case SoMaterialBindingElement::PER_VERTEX_INDEXED: + binding = PER_VERTEX_INDEXED; + break; + case SoMaterialBindingElement::PER_PART: + binding = PER_PART; + break; + case SoMaterialBindingElement::PER_FACE: + binding = PER_FACE; + break; + case SoMaterialBindingElement::PER_PART_INDEXED: + binding = PER_PART_INDEXED; + break; + case SoMaterialBindingElement::PER_FACE_INDEXED: + binding = PER_FACE_INDEXED; + break; + default: + break; } return binding; } -SoBrepFaceSet::Binding -SoBrepFaceSet::findNormalBinding(SoState * const state) const +SoBrepFaceSet::Binding SoBrepFaceSet::findNormalBinding(SoState* const state) const { Binding binding = PER_VERTEX_INDEXED; - SoNormalBindingElement::Binding normbind = - (SoNormalBindingElement::Binding) SoNormalBindingElement::get(state); + SoNormalBindingElement::Binding normbind + = (SoNormalBindingElement::Binding)SoNormalBindingElement::get(state); switch (normbind) { - case SoNormalBindingElement::OVERALL: - binding = OVERALL; - break; - case SoNormalBindingElement::PER_VERTEX: - binding = PER_VERTEX; - break; - case SoNormalBindingElement::PER_VERTEX_INDEXED: - binding = PER_VERTEX_INDEXED; - break; - case SoNormalBindingElement::PER_PART: - binding = PER_PART; - break; - case SoNormalBindingElement::PER_FACE: - binding = PER_FACE; - break; - case SoNormalBindingElement::PER_PART_INDEXED: - binding = PER_PART_INDEXED; - break; - case SoNormalBindingElement::PER_FACE_INDEXED: - binding = PER_FACE_INDEXED; - break; - default: - break; + case SoNormalBindingElement::OVERALL: + binding = OVERALL; + break; + case SoNormalBindingElement::PER_VERTEX: + binding = PER_VERTEX; + break; + case SoNormalBindingElement::PER_VERTEX_INDEXED: + binding = PER_VERTEX_INDEXED; + break; + case SoNormalBindingElement::PER_PART: + binding = PER_PART; + break; + case SoNormalBindingElement::PER_FACE: + binding = PER_FACE; + break; + case SoNormalBindingElement::PER_PART_INDEXED: + binding = PER_PART_INDEXED; + break; + case SoNormalBindingElement::PER_FACE_INDEXED: + binding = PER_FACE_INDEXED; + break; + default: + break; } return binding; } diff --git a/src/Mod/Part/Gui/SoBrepFaceSet.h b/src/Mod/Part/Gui/SoBrepFaceSet.h index cbba9b1c90..3e307786d9 100644 --- a/src/Mod/Part/Gui/SoBrepFaceSet.h +++ b/src/Mod/Part/Gui/SoBrepFaceSet.h @@ -38,44 +38,51 @@ class SoGLCoordinateElement; class SoTextureCoordinateBundle; -namespace PartGui { +namespace PartGui +{ class ViewProviderPartExt; /** * First some words to the history and the reason why we have this class: - * In older FreeCAD versions we had an own Inventor node for each sub-element of a shape with its own highlight node. - * For more complex objects the number of nodes increased dramatically with the result that interactions with such - * objects was almost impossible because every little rotation or hovering caused a very time consuming redraw. The - * most time consuming part was not the OpenGL calls to render the elements but the traversal of these many nodes. + * In older FreeCAD versions we had an own Inventor node for each sub-element of a shape with its + * own highlight node. For more complex objects the number of nodes increased dramatically with the + * result that interactions with such objects was almost impossible because every little rotation or + * hovering caused a very time consuming redraw. The most time consuming part was not the OpenGL + * calls to render the elements but the traversal of these many nodes. * - * So, the idea was to have one node that handles all faces of a shape, one node that handles all edges and another node - * that handles the vertexes. And each of these nodes manages the highlighting and selection itself. + * So, the idea was to have one node that handles all faces of a shape, one node that handles all + * edges and another node that handles the vertexes. And each of these nodes manages the + * highlighting and selection itself. * * Now to SoBrepFaceSet in detail: - * The most complex nodes of them is SoBrepFaceSet because it adds some extra logic for the handling of faces. As you can - * see this class also has the attribute partIndex which is an array of integers. This basically expresses the logical - * grouping of the faces in the coordIndex field -- the parts. This means that a part in SoBrepFaceSet corresponds to a face - * in a shape object. Each part value gives you the number of triangles a certain face consists of. That's also the reason why - * SoBrepFaceSet only renders triangles. If you want a quad to be rendered than create two triangles and set the corresponding - * part number to 2. + * The most complex nodes of them is SoBrepFaceSet because it adds some extra logic for the handling + * of faces. As you can see this class also has the attribute partIndex which is an array of + * integers. This basically expresses the logical grouping of the faces in the coordIndex field -- + * the parts. This means that a part in SoBrepFaceSet corresponds to a face in a shape object. Each + * part value gives you the number of triangles a certain face consists of. That's also the reason + * why SoBrepFaceSet only renders triangles. If you want a quad to be rendered than create two + * triangles and set the corresponding part number to 2. * * Example: - * Let's say you have a shape with two faces. When meshing face 1 it creates 10 triangles and face 2 creates 5 triangles. Then - * the partIndex attribute would be the array [10,5]. + * Let's say you have a shape with two faces. When meshing face 1 it creates 10 triangles and face 2 + * creates 5 triangles. Then the partIndex attribute would be the array [10,5]. * * Highlighting/selection: - * The highlightIndex now defines which part of the shape must be highlighted. So, in the above example it can have the values - * 0, 1, or -1 (i.e. no highlighting). The highlightIndex is a SoSFInt32 field because only one part can be highlighted at a - * moment while selectionIndex is a SoMFInt32 field because several parts can be selected at a time. All the logic how to do the + * The highlightIndex now defines which part of the shape must be highlighted. So, in the above + * example it can have the values 0, 1, or -1 (i.e. no highlighting). The highlightIndex is a + * SoSFInt32 field because only one part can be highlighted at a moment while selectionIndex is a + * SoMFInt32 field because several parts can be selected at a time. All the logic how to do the * rendering is done inside renderHighlight()/renderSelection(). * - * Actually you can access the highlightIndex directly or you can apply a SoHighlightElementAction on it. And don't forget: if you - * do some mouse picking and you got a SoFaceDetail then use getPartIndex() to get the correct part. + * Actually you can access the highlightIndex directly or you can apply a SoHighlightElementAction + * on it. And don't forget: if you do some mouse picking and you got a SoFaceDetail then use + * getPartIndex() to get the correct part. * * As an example how to use the class correctly see ViewProviderPartExt::updateVisual(). */ -class PartGuiExport SoBrepFaceSet : public SoIndexedFaceSet { +class PartGuiExport SoBrepFaceSet: public SoIndexedFaceSet +{ using inherited = SoIndexedFaceSet; SO_NODE_HEADER(SoBrepFaceSet); @@ -83,27 +90,32 @@ class PartGuiExport SoBrepFaceSet : public SoIndexedFaceSet { public: static void initClass(); SoBrepFaceSet(); - - void setViewProvider(ViewProviderPartExt* vp) { viewProvider = vp; } + + void setViewProvider(ViewProviderPartExt* vp) + { + viewProvider = vp; + } SoMFInt32 partIndex; protected: ~SoBrepFaceSet() override; - void GLRender(SoGLRenderAction *action) override; - void GLRenderBelowPath(SoGLRenderAction * action) override; + void GLRender(SoGLRenderAction* action) override; + void GLRenderBelowPath(SoGLRenderAction* action) override; void doAction(SoAction* action) override; - SoDetail * createTriangleDetail( - SoRayPickAction * action, - const SoPrimitiveVertex * v1, - const SoPrimitiveVertex * v2, - const SoPrimitiveVertex * v3, - SoPickedPoint * pp) override; - void generatePrimitives(SoAction * action) override; - void getBoundingBox(SoGetBoundingBoxAction * action) override; + SoDetail* createTriangleDetail( + SoRayPickAction* action, + const SoPrimitiveVertex* v1, + const SoPrimitiveVertex* v2, + const SoPrimitiveVertex* v3, + SoPickedPoint* pp + ) override; + void generatePrimitives(SoAction* action) override; + void getBoundingBox(SoGetBoundingBoxAction* action) override; private: - enum Binding { + enum Binding + { OVERALL = 0, PER_PART, PER_PART_INDEXED, @@ -113,36 +125,38 @@ private: PER_VERTEX_INDEXED, NONE = OVERALL }; - Binding findMaterialBinding(SoState * const state) const; - Binding findNormalBinding(SoState * const state) const; - void renderShape(SoGLRenderAction * action, - SbBool hasVBO, - const SoGLCoordinateElement * const vertexlist, - const int32_t *vertexindices, - int num_vertexindices, - const int32_t *partindices, - int num_partindices, - const SbVec3f *normals, - const int32_t *normindices, - SoMaterialBundle *const materials, - const int32_t *matindices, - SoTextureCoordinateBundle * const texcoords, - const int32_t *texindices, - const int nbind, - const int mbind, - SbBool texture); + Binding findMaterialBinding(SoState* const state) const; + Binding findNormalBinding(SoState* const state) const; + void renderShape( + SoGLRenderAction* action, + SbBool hasVBO, + const SoGLCoordinateElement* const vertexlist, + const int32_t* vertexindices, + int num_vertexindices, + const int32_t* partindices, + int num_partindices, + const SbVec3f* normals, + const int32_t* normindices, + SoMaterialBundle* const materials, + const int32_t* matindices, + SoTextureCoordinateBundle* const texcoords, + const int32_t* texindices, + const int nbind, + const int mbind, + SbBool texture + ); using SelContext = Gui::SoFCSelectionContextEx; using SelContextPtr = Gui::SoFCSelectionContextExPtr; - void renderHighlight(SoGLRenderAction *action, SelContextPtr); - void renderSelection(SoGLRenderAction *action, SelContextPtr, bool push=true); + void renderHighlight(SoGLRenderAction* action, SelContextPtr); + void renderSelection(SoGLRenderAction* action, SelContextPtr, bool push = true); - bool overrideMaterialBinding(SoGLRenderAction *action, SelContextPtr ctx, SelContextPtr ctx2); + bool overrideMaterialBinding(SoGLRenderAction* action, SelContextPtr ctx, SelContextPtr ctx2); #ifdef RENDER_GLARRAYS void renderSimpleArray(); - void renderColoredArray(SoMaterialBundle *const materials); + void renderColoredArray(SoMaterialBundle* const materials); #endif private: @@ -160,12 +174,11 @@ private: // Define some VBO pointer for the current mesh class VBO; std::unique_ptr pimpl; - + // backreference to viewprovider that owns this node ViewProviderPartExt* viewProvider = nullptr; }; -} // namespace PartGui - -#endif // PARTGUI_SOBREPFACESET_H +} // namespace PartGui +#endif // PARTGUI_SOBREPFACESET_H diff --git a/src/Mod/Part/Gui/SoBrepPointSet.cpp b/src/Mod/Part/Gui/SoBrepPointSet.cpp index 36e73e04f2..57340ff9d0 100644 --- a/src/Mod/Part/Gui/SoBrepPointSet.cpp +++ b/src/Mod/Part/Gui/SoBrepPointSet.cpp @@ -24,24 +24,24 @@ #include -# ifdef FC_OS_WIN32 -# include -# endif -# ifdef FC_OS_MACOSX -# include -# else -# include -# endif -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#ifdef FC_OS_WIN32 +# include +#endif +#ifdef FC_OS_MACOSX +# include +#else +# include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -66,7 +66,7 @@ SoBrepPointSet::SoBrepPointSet() SO_NODE_CONSTRUCTOR(SoBrepPointSet); } -void SoBrepPointSet::GLRender(SoGLRenderAction *action) +void SoBrepPointSet::GLRender(SoGLRenderAction* action) { auto state = action->getState(); selCounter.checkRenderCache(state); @@ -78,15 +78,17 @@ void SoBrepPointSet::GLRender(SoGLRenderAction *action) return; } SelContextPtr ctx2; - SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this,selContext,ctx2); - if(ctx2 && ctx2->selectionIndex.empty()) + SelContextPtr ctx = Gui::SoFCSelectionRoot::getRenderContext(this, selContext, ctx2); + if (ctx2 && ctx2->selectionIndex.empty()) { return; - if(selContext2->checkGlobal(ctx)) + } + if (selContext2->checkGlobal(ctx)) { ctx = selContext2; - + } - bool hasContextHighlight = - ctx && ctx->isHighlighted() && !ctx->isHighlightAll() && ctx->highlightIndex >= 0; + + bool hasContextHighlight = ctx && ctx->isHighlighted() && !ctx->isHighlightAll() + && ctx->highlightIndex >= 0; // for clarifyselection, add this node to delayed path if it is highlighted and render it on // top of everything else (highest priority) if (Gui::Selection().isClarifySelectionActive() && hasContextHighlight @@ -94,51 +96,66 @@ void SoBrepPointSet::GLRender(SoGLRenderAction *action) if (viewProvider) { viewProvider->setFaceHighlightActive(true); } - Gui::SoDelayedAnnotationsElement::addDelayedPath(action->getState(), - action->getCurPath()->copy(), - 300); + Gui::SoDelayedAnnotationsElement::addDelayedPath( + action->getState(), + action->getCurPath()->copy(), + 300 + ); return; } - if(ctx && ctx->highlightIndex == std::numeric_limits::max()) { - if(ctx->selectionIndex.empty() || ctx->isSelectAll()) { - if(ctx2) { + if (ctx && ctx->highlightIndex == std::numeric_limits::max()) { + if (ctx->selectionIndex.empty() || ctx->isSelectAll()) { + if (ctx2) { ctx2->selectionColor = ctx->highlightColor; - renderSelection(action,ctx2); - } else - renderHighlight(action,ctx); - }else{ - if(!action->isRenderingDelayedPaths()) - renderSelection(action,ctx); - if(ctx2) { + renderSelection(action, ctx2); + } + else { + renderHighlight(action, ctx); + } + } + else { + if (!action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } + if (ctx2) { ctx2->selectionColor = ctx->highlightColor; - renderSelection(action,ctx2); - } else - renderHighlight(action,ctx); - if(action->isRenderingDelayedPaths()) - renderSelection(action,ctx); + renderSelection(action, ctx2); + } + else { + renderHighlight(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } } return; } - if(!action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); - if(ctx && !ctx->selectionIndex.empty()) { - if(ctx->isSelectAll()) { - if(ctx2 && !ctx2->selectionIndex.empty()) { + if (!action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + if (ctx && !ctx->selectionIndex.empty()) { + if (ctx->isSelectAll()) { + if (ctx2 && !ctx2->selectionIndex.empty()) { ctx2->selectionColor = ctx->selectionColor; - renderSelection(action,ctx2); - }else - renderSelection(action,ctx); - if(action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); + renderSelection(action, ctx2); + } + else { + renderSelection(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } return; } - if(!action->isRenderingDelayedPaths()) - renderSelection(action,ctx); + if (!action->isRenderingDelayedPaths()) { + renderSelection(action, ctx); + } + } + if (ctx2 && !ctx2->selectionIndex.empty()) { + renderSelection(action, ctx2, false); } - if(ctx2 && !ctx2->selectionIndex.empty()) - renderSelection(action,ctx2,false); else if (Gui::SoDelayedAnnotationsElement::isProcessingDelayedPaths) { glPushAttrib(GL_DEPTH_BUFFER_BIT); glDepthFunc(GL_ALWAYS); @@ -150,132 +167,153 @@ void SoBrepPointSet::GLRender(SoGLRenderAction *action) } // Workaround for #0000433 -//#if !defined(FC_OS_WIN32) - if(!action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); - if(ctx && !ctx->selectionIndex.empty()) - renderSelection(action,ctx); - if(action->isRenderingDelayedPaths()) - renderHighlight(action,ctx); -//#endif + // #if !defined(FC_OS_WIN32) + if (!action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + if (ctx && !ctx->selectionIndex.empty()) { + renderSelection(action, ctx); + } + if (action->isRenderingDelayedPaths()) { + renderHighlight(action, ctx); + } + // #endif } -void SoBrepPointSet::GLRenderBelowPath(SoGLRenderAction * action) +void SoBrepPointSet::GLRenderBelowPath(SoGLRenderAction* action) { inherited::GLRenderBelowPath(action); } -void SoBrepPointSet::getBoundingBox(SoGetBoundingBoxAction * action) { +void SoBrepPointSet::getBoundingBox(SoGetBoundingBoxAction* action) +{ - SelContextPtr ctx2 = Gui::SoFCSelectionRoot::getSecondaryActionContext(action,this); - if(!ctx2 || ctx2->isSelectAll()) { + SelContextPtr ctx2 = Gui::SoFCSelectionRoot::getSecondaryActionContext(action, this); + if (!ctx2 || ctx2->isSelectAll()) { inherited::getBoundingBox(action); return; } - if(ctx2->selectionIndex.empty()) + if (ctx2->selectionIndex.empty()) { return; + } auto state = action->getState(); auto coords = SoCoordinateElement::getInstance(state); - const SbVec3f *coords3d = coords->getArrayPtr3(); + const SbVec3f* coords3d = coords->getArrayPtr3(); int numverts = coords->getNum(); int startIndex = this->startIndex.getValue(); SbBox3f bbox; - for(auto idx : ctx2->selectionIndex) { - if(idx >= startIndex && idx < numverts) + for (auto idx : ctx2->selectionIndex) { + if (idx >= startIndex && idx < numverts) { bbox.extendBy(coords3d[idx]); + } } - if(!bbox.isEmpty()) + if (!bbox.isEmpty()) { action->extendBy(bbox); + } } -void SoBrepPointSet::renderHighlight(SoGLRenderAction *action, SelContextPtr ctx) +void SoBrepPointSet::renderHighlight(SoGLRenderAction* action, SelContextPtr ctx) { - if(!ctx || ctx->highlightIndex<0) + if (!ctx || ctx->highlightIndex < 0) { return; + } - SoState * state = action->getState(); + SoState* state = action->getState(); state->push(); float ps = SoPointSizeElement::get(state); - if (ps < 4.0f) SoPointSizeElement::set(state, this, 4.0f); + if (ps < 4.0f) { + SoPointSizeElement::set(state, this, 4.0f); + } SoLazyElement::setEmissive(state, &ctx->highlightColor); packedColor = ctx->highlightColor.getPackedValue(0.0); - SoLazyElement::setPacked(state, this,1, &packedColor,false); + SoLazyElement::setPacked(state, this, 1, &packedColor, false); - const SoCoordinateElement * coords; - const SbVec3f * normals; + const SoCoordinateElement* coords; + const SbVec3f* normals; this->getVertexData(state, coords, normals, false); SoMaterialBundle mb(action); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material int id = ctx->highlightIndex; - const SbVec3f * coords3d = coords->getArrayPtr3(); - if(coords3d) { - if(id == std::numeric_limits::max()) { + const SbVec3f* coords3d = coords->getArrayPtr3(); + if (coords3d) { + if (id == std::numeric_limits::max()) { glBegin(GL_POINTS); - for(int idx=startIndex.getValue();idxgetNum();++idx) - glVertex3fv((const GLfloat*) (coords3d + idx)); + for (int idx = startIndex.getValue(); idx < coords->getNum(); ++idx) { + glVertex3fv((const GLfloat*)(coords3d + idx)); + } glEnd(); - }else if (id < this->startIndex.getValue() || id >= coords->getNum()) { + } + else if (id < this->startIndex.getValue() || id >= coords->getNum()) { SoDebugError::postWarning("SoBrepPointSet::renderHighlight", "highlightIndex out of range"); } else { glBegin(GL_POINTS); - glVertex3fv((const GLfloat*) (coords3d + id)); + glVertex3fv((const GLfloat*)(coords3d + id)); glEnd(); } } state->pop(); } -void SoBrepPointSet::renderSelection(SoGLRenderAction *action, SelContextPtr ctx, bool push) +void SoBrepPointSet::renderSelection(SoGLRenderAction* action, SelContextPtr ctx, bool push) { - SoState * state = action->getState(); - if(push) { + SoState* state = action->getState(); + if (push) { state->push(); float ps = SoPointSizeElement::get(state); - if (ps < 4.0f) SoPointSizeElement::set(state, this, 4.0f); + if (ps < 4.0f) { + SoPointSizeElement::set(state, this, 4.0f); + } SoLazyElement::setEmissive(state, &ctx->selectionColor); packedColor = ctx->selectionColor.getPackedValue(0.0); - SoLazyElement::setPacked(state, this,1, &packedColor,false); + SoLazyElement::setPacked(state, this, 1, &packedColor, false); } - const SoCoordinateElement * coords; - const SbVec3f * normals; + const SoCoordinateElement* coords; + const SbVec3f* normals; this->getVertexData(state, coords, normals, false); SoMaterialBundle mb(action); - mb.sendFirst(); // make sure we have the correct material + mb.sendFirst(); // make sure we have the correct material bool warn = false; int startIndex = this->startIndex.getValue(); - const SbVec3f * coords3d = coords->getArrayPtr3(); - if(coords3d) { + const SbVec3f* coords3d = coords->getArrayPtr3(); + if (coords3d) { glBegin(GL_POINTS); - if(ctx->isSelectAll()) { - for(int idx=startIndex;idxgetNum();++idx) - glVertex3fv((const GLfloat*) (coords3d + idx)); - }else{ - for(auto idx : ctx->selectionIndex) { - if(idx >= startIndex && idx < coords->getNum()) - glVertex3fv((const GLfloat*) (coords3d + idx)); - else + if (ctx->isSelectAll()) { + for (int idx = startIndex; idx < coords->getNum(); ++idx) { + glVertex3fv((const GLfloat*)(coords3d + idx)); + } + } + else { + for (auto idx : ctx->selectionIndex) { + if (idx >= startIndex && idx < coords->getNum()) { + glVertex3fv((const GLfloat*)(coords3d + idx)); + } + else { warn = true; + } } } glEnd(); } - if(warn) + if (warn) { SoDebugError::postWarning("SoBrepPointSet::renderSelection", "selectionIndex out of range"); - if(push) state->pop(); + } + if (push) { + state->pop(); + } } void SoBrepPointSet::doAction(SoAction* action) @@ -284,28 +322,30 @@ void SoBrepPointSet::doAction(SoAction* action) Gui::SoHighlightElementAction* hlaction = static_cast(action); selCounter.checkAction(hlaction); if (!hlaction->isHighlighted()) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { ctx->highlightIndex = -1; touch(); } return; } - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); const SoDetail* detail = hlaction->getElement(); if (!detail) { ctx->highlightIndex = std::numeric_limits::max(); ctx->highlightColor = hlaction->getColor(); touch(); return; - }else if (!detail->isOfType(SoPointDetail::getClassTypeId())) { + } + else if (!detail->isOfType(SoPointDetail::getClassTypeId())) { ctx->highlightIndex = -1; touch(); return; } int index = static_cast(detail)->getCoordinateIndex(); - if(index!=ctx->highlightIndex) { + if (index != ctx->highlightIndex) { ctx->highlightIndex = index; ctx->highlightColor = hlaction->getColor(); touch(); @@ -314,65 +354,75 @@ void SoBrepPointSet::doAction(SoAction* action) } else if (action->getTypeId() == Gui::SoSelectionElementAction::getClassTypeId()) { Gui::SoSelectionElementAction* selaction = static_cast(action); - switch(selaction->getType()) { - case Gui::SoSelectionElementAction::All: { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - ctx->selectionColor = selaction->getColor(); - ctx->selectionIndex.clear(); - ctx->selectionIndex.insert(-1); - touch(); - return; - } case Gui::SoSelectionElementAction::None: - if(selaction->isSecondary()) { - if(Gui::SoFCSelectionRoot::removeActionContext(action,this)) - touch(); - } else { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx) { - ctx->selectionIndex.clear(); - touch(); - } - } - return; - case Gui::SoSelectionElementAction::Remove: - case Gui::SoSelectionElementAction::Append: { - const SoDetail* detail = selaction->getElement(); - if (!detail || !detail->isOfType(SoPointDetail::getClassTypeId())) { - if(selaction->isSecondary()) { - // For secondary context, a detail of different type means - // the user may want to partial render only other type of - // geometry. So we call below to obtain a action context. - // If no secondary context exist, it will create an empty - // one, and an empty secondary context inhibites drawing - // here. - auto ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - touch(); - } + switch (selaction->getType()) { + case Gui::SoSelectionElementAction::All: { + SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + ctx->selectionColor = selaction->getColor(); + ctx->selectionIndex.clear(); + ctx->selectionIndex.insert(-1); + touch(); return; } - int index = static_cast(detail)->getCoordinateIndex(); - if(selaction->getType() == Gui::SoSelectionElementAction::Append) { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext); - selCounter.checkAction(selaction,ctx); - ctx->selectionColor = selaction->getColor(); - if(ctx->isSelectAll()) - ctx->selectionIndex.clear(); - if(ctx->selectionIndex.insert(index).second) - touch(); - } else { - SelContextPtr ctx = Gui::SoFCSelectionRoot::getActionContext(action,this,selContext,false); - if(ctx && ctx->removeIndex(index)) - touch(); + case Gui::SoSelectionElementAction::None: + if (selaction->isSecondary()) { + if (Gui::SoFCSelectionRoot::removeActionContext(action, this)) { + touch(); + } + } + else { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx) { + ctx->selectionIndex.clear(); + touch(); + } + } + return; + case Gui::SoSelectionElementAction::Remove: + case Gui::SoSelectionElementAction::Append: { + const SoDetail* detail = selaction->getElement(); + if (!detail || !detail->isOfType(SoPointDetail::getClassTypeId())) { + if (selaction->isSecondary()) { + // For secondary context, a detail of different type means + // the user may want to partial render only other type of + // geometry. So we call below to obtain a action context. + // If no secondary context exist, it will create an empty + // one, and an empty secondary context inhibites drawing + // here. + auto ctx = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + touch(); + } + return; + } + int index = static_cast(detail)->getCoordinateIndex(); + if (selaction->getType() == Gui::SoSelectionElementAction::Append) { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext); + selCounter.checkAction(selaction, ctx); + ctx->selectionColor = selaction->getColor(); + if (ctx->isSelectAll()) { + ctx->selectionIndex.clear(); + } + if (ctx->selectionIndex.insert(index).second) { + touch(); + } + } + else { + SelContextPtr ctx + = Gui::SoFCSelectionRoot::getActionContext(action, this, selContext, false); + if (ctx && ctx->removeIndex(index)) { + touch(); + } + } + break; } - break; - } default: - break; + default: + break; } return; } inherited::doAction(action); } - diff --git a/src/Mod/Part/Gui/SoBrepPointSet.h b/src/Mod/Part/Gui/SoBrepPointSet.h index 8a0361a3f4..f0eee1712a 100644 --- a/src/Mod/Part/Gui/SoBrepPointSet.h +++ b/src/Mod/Part/Gui/SoBrepPointSet.h @@ -36,11 +36,13 @@ class SoCoordinateElement; class SoGLCoordinateElement; class SoTextureCoordinateBundle; -namespace PartGui { +namespace PartGui +{ class ViewProviderPartExt; -class PartGuiExport SoBrepPointSet : public SoPointSet { +class PartGuiExport SoBrepPointSet: public SoPointSet +{ using inherited = SoPointSet; SO_NODE_HEADER(SoBrepPointSet); @@ -48,35 +50,37 @@ class PartGuiExport SoBrepPointSet : public SoPointSet { public: static void initClass(); SoBrepPointSet(); - - void setViewProvider(ViewProviderPartExt* vp) { viewProvider = vp; } + + void setViewProvider(ViewProviderPartExt* vp) + { + viewProvider = vp; + } protected: ~SoBrepPointSet() override = default; - void GLRender(SoGLRenderAction *action) override; - void GLRenderBelowPath(SoGLRenderAction * action) override; + void GLRender(SoGLRenderAction* action) override; + void GLRenderBelowPath(SoGLRenderAction* action) override; void doAction(SoAction* action) override; - void getBoundingBox(SoGetBoundingBoxAction * action) override; + void getBoundingBox(SoGetBoundingBoxAction* action) override; private: using SelContext = Gui::SoFCSelectionContext; using SelContextPtr = Gui::SoFCSelectionContextPtr; - void renderHighlight(SoGLRenderAction *action, SelContextPtr); - void renderSelection(SoGLRenderAction *action, SelContextPtr, bool push=true); + void renderHighlight(SoGLRenderAction* action, SelContextPtr); + void renderSelection(SoGLRenderAction* action, SelContextPtr, bool push = true); private: SelContextPtr selContext; SelContextPtr selContext2; Gui::SoFCSelectionCounter selCounter; - uint32_t packedColor{0}; - + uint32_t packedColor {0}; + // backreference to viewprovider that owns this node ViewProviderPartExt* viewProvider = nullptr; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_SOBREPPOINTSET_H - +#endif // PARTGUI_SOBREPPOINTSET_H diff --git a/src/Mod/Part/Gui/SoFCShapeObject.cpp b/src/Mod/Part/Gui/SoFCShapeObject.cpp index 2d8e4c53bb..9c2bc449c8 100644 --- a/src/Mod/Part/Gui/SoFCShapeObject.cpp +++ b/src/Mod/Part/Gui/SoFCShapeObject.cpp @@ -24,23 +24,23 @@ #include -# ifdef FC_OS_WIN32 -# include -# endif -# ifdef FC_OS_MACOSX -# include -# else -# include -# endif -# include -# include -# include -# include -# include -# include -# include -# include -# include +#ifdef FC_OS_WIN32 +# include +#endif +#ifdef FC_OS_MACOSX +# include +#else +# include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "SoFCShapeObject.h" @@ -86,17 +86,18 @@ SoFCControlPoints::SoFCControlPoints() /** * Renders the control points. */ -void SoFCControlPoints::GLRender(SoGLRenderAction *action) +void SoFCControlPoints::GLRender(SoGLRenderAction* action) { - if (shouldGLRender(action)) - { - SoState* state = action->getState(); - const SoCoordinateElement * coords = SoCoordinateElement::getInstance(state); - if (!coords) + if (shouldGLRender(action)) { + SoState* state = action->getState(); + const SoCoordinateElement* coords = SoCoordinateElement::getInstance(state); + if (!coords) { return; - const SbVec3f * points = coords->getArrayPtr3(); - if (!points) + } + const SbVec3f* points = coords->getArrayPtr3(); + if (!points) { return; + } SoMaterialBundle mb(action); SoTextureCoordinateBundle tb(action, true, false); @@ -111,92 +112,94 @@ void SoFCControlPoints::GLRender(SoGLRenderAction *action) /** * Renders the control points and knots. */ -void SoFCControlPoints::drawControlPoints(const SbVec3f * points,int32_t len) const +void SoFCControlPoints::drawControlPoints(const SbVec3f* points, int32_t len) const { glLineWidth(1.0f); glColor3fv(lineColor.getValue().getValue()); - uint32_t nCtU=numPolesU.getValue(); - uint32_t nCtV=numPolesV.getValue(); + uint32_t nCtU = numPolesU.getValue(); + uint32_t nCtV = numPolesV.getValue(); uint32_t poles = nCtU * nCtV; - if (poles > (uint32_t)len) - return; // wrong setup, too few points + if (poles > (uint32_t)len) { + return; // wrong setup, too few points + } // draw control mesh glBegin(GL_LINES); - for (uint32_t u = 0; u < nCtU-1; ++u) { - for (uint32_t v = 0; v < nCtV -1; ++v) { - glVertex3fv(points[u*nCtV+v].getValue()); - glVertex3fv(points[u*nCtV+v+1].getValue()); - glVertex3fv(points[u*nCtV+v].getValue()); - glVertex3fv(points[(u+1)*nCtV+v].getValue()); + for (uint32_t u = 0; u < nCtU - 1; ++u) { + for (uint32_t v = 0; v < nCtV - 1; ++v) { + glVertex3fv(points[u * nCtV + v].getValue()); + glVertex3fv(points[u * nCtV + v + 1].getValue()); + glVertex3fv(points[u * nCtV + v].getValue()); + glVertex3fv(points[(u + 1) * nCtV + v].getValue()); } - glVertex3fv(points[(u+1)*nCtV-1].getValue()); - glVertex3fv(points[(u+2)*nCtV-1].getValue()); + glVertex3fv(points[(u + 1) * nCtV - 1].getValue()); + glVertex3fv(points[(u + 2) * nCtV - 1].getValue()); } - for (uint32_t v = 0; v < nCtV -1; ++v) { - glVertex3fv(points[(nCtU-1)*nCtV+v].getValue()); - glVertex3fv(points[(nCtU-1)*nCtV+v+1].getValue()); + for (uint32_t v = 0; v < nCtV - 1; ++v) { + glVertex3fv(points[(nCtU - 1) * nCtV + v].getValue()); + glVertex3fv(points[(nCtU - 1) * nCtV + v + 1].getValue()); } glEnd(); // draw poles glPointSize(5.0f); glBegin(GL_POINTS); - for (uint32_t p=0; p (uint32_t)len) - return; // wrong setup, too few points + if (index > (uint32_t)len) { + return; // wrong setup, too few points + } glColor3f(1.0f, 1.0f, 0.0f); glPointSize(6.0f); glBegin(GL_POINTS); - for (uint32_t p=poles; pgetState(); - const SoCoordinateElement * coords = SoCoordinateElement::getInstance(state); - if (!coords) + SoState* state = action->getState(); + const SoCoordinateElement* coords = SoCoordinateElement::getInstance(state); + if (!coords) { return; - const SbVec3f * points = coords->getArrayPtr3(); - if (!points) + } + const SbVec3f* points = coords->getArrayPtr3(); + if (!points) { return; + } constexpr float floatMax = std::numeric_limits::max(); - float maxX=-floatMax, minX=floatMax, - maxY=-floatMax, minY=floatMax, - maxZ=-floatMax, minZ=floatMax; + float maxX = -floatMax, minX = floatMax, maxY = -floatMax, minY = floatMax, maxZ = -floatMax, + minZ = floatMax; int32_t len = coords->getNum(); if (len > 0) { - for (int32_t i=0; i(maxX,points[i][0]); - minX = std::min(minX,points[i][0]); - maxY = std::max(maxY,points[i][1]); - minY = std::min(minY,points[i][1]); - maxZ = std::max(maxZ,points[i][2]); - minZ = std::min(minZ,points[i][2]); + for (int32_t i = 0; i < len; i++) { + maxX = std::max(maxX, points[i][0]); + minX = std::min(minX, points[i][0]); + maxY = std::max(maxY, points[i][1]); + minY = std::min(minY, points[i][1]); + maxZ = std::max(maxZ, points[i][2]); + minZ = std::min(minZ, points[i][2]); } - box.setBounds(minX,minY,minZ,maxX,maxY,maxZ); - center.setValue(0.5f*(minX+maxX),0.5f*(minY+maxY),0.5f*(minZ+maxZ)); + box.setBounds(minX, minY, minZ, maxX, maxY, maxZ); + center.setValue(0.5f * (minX + maxX), 0.5f * (minY + maxY), 0.5f * (minZ + maxZ)); } else { - box.setBounds(SbVec3f(0,0,0), SbVec3f(0,0,0)); - center.setValue(0.0f,0.0f,0.0f); + box.setBounds(SbVec3f(0, 0, 0), SbVec3f(0, 0, 0)); + center.setValue(0.0f, 0.0f, 0.0f); } } diff --git a/src/Mod/Part/Gui/SoFCShapeObject.h b/src/Mod/Part/Gui/SoFCShapeObject.h index aed1d10217..ff4cd90333 100644 --- a/src/Mod/Part/Gui/SoFCShapeObject.h +++ b/src/Mod/Part/Gui/SoFCShapeObject.h @@ -38,9 +38,11 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport SoFCShape : public SoSeparator { +class PartGuiExport SoFCShape: public SoSeparator +{ using inherited = SoSeparator; SO_NODE_HEADER(SoFCShape); @@ -55,7 +57,8 @@ public: SoBrepPointSet* nodeset; }; -class PartGuiExport SoFCControlPoints : public SoShape { +class PartGuiExport SoFCControlPoints: public SoShape +{ using inherited = SoShape; SO_NODE_HEADER(SoFCControlPoints); @@ -68,20 +71,20 @@ public: SoSFUInt32 numPolesV; SoSFUInt32 numKnotsU; SoSFUInt32 numKnotsV; - SoSFColor lineColor; + SoSFColor lineColor; protected: - ~SoFCControlPoints() override = default;; - void GLRender(SoGLRenderAction *action) override; - void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er) override; - void generatePrimitives(SoAction *action) override; + ~SoFCControlPoints() override = default; + ; + void GLRender(SoGLRenderAction* action) override; + void computeBBox(SoAction* action, SbBox3f& box, SbVec3f& center) override; + void generatePrimitives(SoAction* action) override; private: - void drawControlPoints(const SbVec3f *,int32_t) const; + void drawControlPoints(const SbVec3f*, int32_t) const; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_SOFCSHAPEOBJECT_H - +#endif // PARTGUI_SOFCSHAPEOBJECT_H diff --git a/src/Mod/Part/Gui/TaskAttacher.cpp b/src/Mod/Part/Gui/TaskAttacher.cpp index 0b4b9bda33..ddd520630e 100644 --- a/src/Mod/Part/Gui/TaskAttacher.cpp +++ b/src/Mod/Part/Gui/TaskAttacher.cpp @@ -24,11 +24,11 @@ ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -87,8 +87,10 @@ const QString makeRefString(const App::DocumentObject* obj, const std::string& s + QString::fromLatin1(el.oldName.c_str()); } -void TaskAttacher::makeRefStrings(std::vector& refstrings, std::vector& refnames) { - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); +void TaskAttacher::makeRefStrings(std::vector& refstrings, std::vector& refnames) +{ + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); std::vector refs = pcAttach->AttachmentSupport.getValues(); refnames = pcAttach->AttachmentSupport.getSubValues(); @@ -96,8 +98,9 @@ void TaskAttacher::makeRefStrings(std::vector& refstrings, std::vector< if ((r < refs.size()) && (refs[r])) { refstrings.push_back(makeRefString(refs[r], refnames[r])); // for Origin or Datum features refnames is empty but we need a non-empty return value - if (refnames[r].empty()) + if (refnames[r].empty()) { refnames[r] = refs[r]->getNameInDocument(); + } } else { refstrings.push_back(QObject::tr("No reference selected")); @@ -106,8 +109,13 @@ void TaskAttacher::makeRefStrings(std::vector& refstrings, std::vector< } } -TaskAttacher::TaskAttacher(Gui::ViewProviderDocumentObject* ViewProvider, QWidget* parent, - QString picture, QString text, TaskAttacher::VisibilityFunction visFunc) +TaskAttacher::TaskAttacher( + Gui::ViewProviderDocumentObject* ViewProvider, + QWidget* parent, + QString picture, + QString text, + TaskAttacher::VisibilityFunction visFunc +) : TaskBox(Gui::BitmapFactory().pixmap(picture.toLatin1()), text, true, parent) , SelectionObserver(ViewProvider, true, Gui::ResolveMode::NoResolve) , ViewProvider(ViewProvider) @@ -115,9 +123,10 @@ TaskAttacher::TaskAttacher(Gui::ViewProviderDocumentObject* ViewProvider, QWidge , visibilityFunc(visFunc) , completed(false) { - //check if we are attachable - if (!ViewProvider->getObject()->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) + // check if we are attachable + if (!ViewProvider->getObject()->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) { throw Base::RuntimeError("Object has no Part::AttachExtension"); + } // we need a separate container widget to add all controls to proxy = new QWidget(this); @@ -174,7 +183,8 @@ TaskAttacher::TaskAttacher(Gui::ViewProviderDocumentObject* ViewProvider, QWidge ui->listOfModes->blockSignals(true); // Get the feature data - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); std::vector refnames = pcAttach->AttachmentSupport.getSubValues(); ui->checkBoxFlip->setChecked(pcAttach->MapReversed.getValue()); @@ -202,10 +212,12 @@ TaskAttacher::TaskAttacher(Gui::ViewProviderDocumentObject* ViewProvider, QWidge ui->listOfModes->blockSignals(false); // only activate the ref when there is no existing first attachment - if (refnames[0].empty()) + if (refnames[0].empty()) { this->iActiveRef = 0; - else + } + else { this->iActiveRef = -1; + } if (pcAttach->AttachmentSupport.getSize() == 0) { autoNext = true; } @@ -213,18 +225,41 @@ TaskAttacher::TaskAttacher(Gui::ViewProviderDocumentObject* ViewProvider, QWidge autoNext = false; } - ui->attachmentOffsetX->bind(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Base.x"))); - ui->attachmentOffsetY->bind(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Base.y"))); - ui->attachmentOffsetZ->bind(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Base.z"))); + ui->attachmentOffsetX->bind( + App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Base.x")) + ); + ui->attachmentOffsetY->bind( + App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Base.y")) + ); + ui->attachmentOffsetZ->bind( + App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Base.z")) + ); - ui->attachmentOffsetYaw->bind(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Yaw"))); - ui->attachmentOffsetPitch->bind(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Pitch"))); - ui->attachmentOffsetRoll->bind(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Roll"))); + ui->attachmentOffsetYaw->bind( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Yaw") + ) + ); + ui->attachmentOffsetPitch->bind( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Pitch") + ) + ); + ui->attachmentOffsetRoll->bind( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Roll") + ) + ); auto document = ViewProvider->getObject()->getDocument(); for (auto planeDocumentObject : document->getObjectsOfType(App::Plane::getClassTypeId())) { - auto planeViewProvider = Application::Instance->getViewProvider(planeDocumentObject); + auto planeViewProvider = Application::Instance->getViewProvider( + planeDocumentObject + ); if (!planeViewProvider) { continue; @@ -244,12 +279,14 @@ TaskAttacher::TaskAttacher(Gui::ViewProviderDocumentObject* ViewProvider, QWidge updatePreview(); showPlacementUtilities(); - //NOLINTBEGIN - // connect object deletion with slot + // NOLINTBEGIN + // connect object deletion with slot auto bnd1 = std::bind(&TaskAttacher::objectDeleted, this, sp::_1); auto bnd2 = std::bind(&TaskAttacher::documentDeleted, this, sp::_1); - //NOLINTEND - Gui::Document* guiDocument = Gui::Application::Instance->getDocument(ViewProvider->getObject()->getDocument()); + // NOLINTEND + Gui::Document* guiDocument = Gui::Application::Instance->getDocument( + ViewProvider->getObject()->getDocument() + ); connectDelObject = guiDocument->signalDeletedObject.connect(bnd1); connectDelDocument = guiDocument->signalDeleteDocument.connect(bnd2); @@ -312,10 +349,12 @@ const QString makeHintText(std::set hint) void TaskAttacher::updateReferencesUI() { - if (!ViewProvider) + if (!ViewProvider) { return; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); std::vector refs = pcAttach->AttachmentSupport.getValues(); completed = false; @@ -330,7 +369,7 @@ void TaskAttacher::updateReferencesUI() if (this->lastSuggestResult.message != SuggestResult::srOK) { if (!this->lastSuggestResult.nextRefTypeHint.empty()) { - //message = "Need more references"; + // message = "Need more references"; } } else { @@ -345,10 +384,12 @@ void TaskAttacher::updateReferencesUI() bool TaskAttacher::updatePreview() { - if (!ViewProvider) + if (!ViewProvider) { return false; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); QString errMessage; bool attached = false; try { @@ -373,12 +414,16 @@ bool TaskAttacher::updatePreview() ui->message->setStyleSheet(QString()); } else { - std::vector strs = AttacherGui::getUIStrings(pcAttach->attacher().getTypeId(), eMapMode(pcAttach->MapMode.getValue())); + std::vector strs = AttacherGui::getUIStrings( + pcAttach->attacher().getTypeId(), + eMapMode(pcAttach->MapMode.getValue()) + ); ui->message->setText(tr("Attached with mode %1").arg(strs[0])); ui->message->setStyleSheet(QStringLiteral("QLabel{color: green;}")); } } - QString splmLabelText = attached ? tr("Attachment offset (in its local coordinate system):") : tr("Attachment offset (inactive - not attached):"); + QString splmLabelText = attached ? tr("Attachment offset (in its local coordinate system):") + : tr("Attachment offset (inactive - not attached):"); ui->groupBox_AttachmentOffset->setTitle(splmLabelText); ui->groupBox_AttachmentOffset->setEnabled(attached); @@ -388,11 +433,16 @@ bool TaskAttacher::updatePreview() QLineEdit* TaskAttacher::getLine(unsigned idx) { switch (idx) { - case 0: return ui->lineRef1; - case 1: return ui->lineRef2; - case 2: return ui->lineRef3; - case 3: return ui->lineRef4; - default: return nullptr; + case 0: + return ui->lineRef1; + case 1: + return ui->lineRef2; + case 2: + return ui->lineRef3; + case 3: + return ui->lineRef4; + default: + return nullptr; } } @@ -402,7 +452,8 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO // - Part // - - Cube // - Sketch - // if sketch is attached to Cube.Face1 then it must store Part:Cube.Face3 as Sketch is outside of Part. + // if sketch is attached to Cube.Face1 then it must store Part:Cube.Face3 as Sketch is outside + // of Part. // - Part // - - Cube // - - Sketch @@ -418,9 +469,9 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO // - - - Cube // - - Part3 // - - - Sketch - // In this example it's not possible because Sketch has Part3 placement. So it should be rejected - // So we need to take the selection object and subname, and process them to get the correct obj/sub based - // on attached and attaching objects positions. + // In this example it's not possible because Sketch has Part3 placement. So it should be + // rejected So we need to take the selection object and subname, and process them to get the + // correct obj/sub based on attached and attaching objects positions. std::vector names = Base::Tools::splitSubName(sub); if (!rootObj || names.size() < 2) { @@ -429,14 +480,14 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO names.insert(names.begin(), rootObj->getNameInDocument()); App::Document* doc = rootObj->getDocument(); - App::DocumentObject* attachingObj = ViewProvider->getObject(); // Attaching object - App::DocumentObject* subObj = rootObj->getSubObject(sub.c_str()); // Object being attached. + App::DocumentObject* attachingObj = ViewProvider->getObject(); // Attaching object + App::DocumentObject* subObj = rootObj->getSubObject(sub.c_str()); // Object being attached. if (!subObj || subObj == rootObj) { // Case of root object. We don't need to modify it. return; } if (subObj == attachingObj) { - //prevent self-referencing + // prevent self-referencing rootObj = nullptr; return; } @@ -456,9 +507,14 @@ void TaskAttacher::findCorrectObjAndSubInThisContext(App::DocumentObject*& rootO for (size_t i = 0; i < names.size(); ++i) { App::DocumentObject* obj = doc->getObject(names[i].c_str()); if (!obj) { - Base::Console().translatedUserError("TaskAttacher", - "Unsuitable selection: '%s' cannot be attached to '%s' from within it's group '%s'.\n", - attachingObj->getFullLabel(), subObj->getFullLabel(), group->getFullLabel()); + Base::Console().translatedUserError( + "TaskAttacher", + "Unsuitable selection: '%s' cannot be attached to '%s' from within it's group " + "'%s'.\n", + attachingObj->getFullLabel(), + subObj->getFullLabel(), + group->getFullLabel() + ); rootObj = nullptr; return; } @@ -513,13 +569,16 @@ void TaskAttacher::handleInitialSelection() } std::vector subAndObjNamePairs; - auto sel = Gui::Selection().getSelectionEx("", - App::DocumentObject::getClassTypeId(), Gui::ResolveMode::NoResolve); + auto sel = Gui::Selection().getSelectionEx( + "", + App::DocumentObject::getClassTypeId(), + Gui::ResolveMode::NoResolve + ); for (auto& selObj : sel) { std::vector subs = selObj.getSubNames(); std::string objName = selObj.getFeatName(); for (auto& sub : subs) { - SubAndObjName objSubName = { objName, sub }; + SubAndObjName objSubName = {objName, sub}; subAndObjNamePairs.push_back(objSubName); } } @@ -533,7 +592,7 @@ void TaskAttacher::onSelectionChanged(const Gui::SelectionChanges& msg) } if (msg.Type == Gui::SelectionChanges::AddSelection) { - SubAndObjName pair = { msg.pObjectName, msg.pSubName }; + SubAndObjName pair = {msg.pObjectName, msg.pSubName}; addToReference(pair); } } @@ -572,11 +631,11 @@ void TaskAttacher::addToReference(const std::vector& pairs) } if (autoNext && iActiveRef > 0 && iActiveRef == static_cast(refnames.size())) { - if (refs[iActiveRef - 1] == selObj - && refnames[iActiveRef - 1].length() != 0 && subname.length() == 0) { - //A whole object was selected by clicking it twice. Fill it - //into previous reference, where a sub-named reference filled by - //the first click is already stored. + if (refs[iActiveRef - 1] == selObj && refnames[iActiveRef - 1].length() != 0 + && subname.length() == 0) { + // A whole object was selected by clicking it twice. Fill it + // into previous reference, where a sub-named reference filled by + // the first click is already stored. iActiveRef--; } @@ -602,7 +661,7 @@ void TaskAttacher::addToReference(const std::vector& pairs) if (autoNext) { if (iActiveRef == -1) { - //nothing to do + // nothing to do } else if (iActiveRef == 4 || this->lastSuggestResult.nextRefTypeHint.empty()) { iActiveRef = -1; @@ -615,9 +674,10 @@ void TaskAttacher::addToReference(const std::vector& pairs) try { updateListOfModes(); - eMapMode mmode = getActiveMapMode(); //will be mmDeactivated, if selected or if no modes are available + eMapMode mmode = getActiveMapMode(); // will be mmDeactivated, if selected or if no modes + // are available if (mmode == mmDeactivated) { - //error = true; + // error = true; this->completed = false; } else { @@ -637,15 +697,17 @@ void TaskAttacher::addToReference(const std::vector& pairs) void TaskAttacher::addToReference(SubAndObjName pair) { - addToReference({{{ pair }}}); + addToReference({{{pair}}}); } void TaskAttacher::onAttachmentOffsetChanged(double /*val*/, int idx) { - if (!ViewProvider) + if (!ViewProvider) { return; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); Base::Placement pl = pcAttach->AttachmentOffset.getValue(); Base::Vector3d pos = pl.getPosition(); @@ -708,10 +770,12 @@ void TaskAttacher::onAttachmentOffsetRollChanged(double val) void TaskAttacher::onCheckFlip(bool on) { - if (!ViewProvider) + if (!ViewProvider) { return; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); pcAttach->MapReversed.setValue(on); ViewProvider->getObject()->recomputeFeature(); } @@ -732,45 +796,54 @@ void TaskAttacher::onButtonRef(const bool checked, unsigned idx) updateRefButton(3); } -void TaskAttacher::onButtonRef1(const bool checked) { +void TaskAttacher::onButtonRef1(const bool checked) +{ onButtonRef(checked, 0); } -void TaskAttacher::onButtonRef2(const bool checked) { +void TaskAttacher::onButtonRef2(const bool checked) +{ onButtonRef(checked, 1); } -void TaskAttacher::onButtonRef3(const bool checked) { +void TaskAttacher::onButtonRef3(const bool checked) +{ onButtonRef(checked, 2); } -void TaskAttacher::onButtonRef4(const bool checked) { +void TaskAttacher::onButtonRef4(const bool checked) +{ onButtonRef(checked, 3); } void TaskAttacher::onModeSelect() { - if (!ViewProvider) + if (!ViewProvider) { return; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); pcAttach->MapMode.setValue(getActiveMapMode()); updatePreview(); } void TaskAttacher::onRefName(const QString& text, unsigned idx) { - if (!ViewProvider) + if (!ViewProvider) { return; + } QLineEdit* line = getLine(idx); - if (!line) + if (!line) { return; + } if (text.length() == 0) { // Reference was removed // Update the reference list - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); std::vector refs = pcAttach->AttachmentSupport.getValues(); std::vector refnames = pcAttach->AttachmentSupport.getSubValues(); std::vector newrefs; @@ -804,31 +877,37 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) } QStringList parts = text.split(QChar::fromLatin1(':')); - if (parts.length() < 2) + if (parts.length() < 2) { parts.push_back(QStringLiteral("")); + } // Check whether this is the name of an App::Plane or Part::Datum feature App::DocumentObject* obj = ViewProvider->getObject()->getDocument()->getObject(parts[0].toLatin1()); - if (!obj) + if (!obj) { return; + } std::string subElement; if (obj->isDerivedFrom()) { - // everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at the base of the feature tree) + // everything is OK (we assume a Part can only have exactly 3 App::Plane objects located at + // the base of the feature tree) subElement.clear(); } else if (obj->isDerivedFrom()) { - // everything is OK (we assume a Part can only have exactly 3 App::Line objects located at the base of the feature tree) + // everything is OK (we assume a Part can only have exactly 3 App::Line objects located at + // the base of the feature tree) subElement.clear(); } else if (obj->isDerivedFrom()) { subElement.clear(); } else { - // TODO: check validity of the text that was entered: Does subElement actually reference to an element on the obj? + // TODO: check validity of the text that was entered: Does subElement actually reference to + // an element on the obj? auto getSubshapeName = [](const QString& part) -> std::string { - // We must expect that "text" is the translation of "Face", "Edge" or "Vertex" followed by an ID. + // We must expect that "text" is the translation of "Face", "Edge" or "Vertex" followed + // by an ID. QRegularExpression rx; QRegularExpressionMatch match; std::stringstream ss; @@ -854,8 +933,8 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) return ss.str(); } - //none of Edge/Vertex/Face. May be empty string. - //Feed in whatever user supplied, even if invalid. + // none of Edge/Vertex/Face. May be empty string. + // Feed in whatever user supplied, even if invalid. ss << part.toLatin1().constData(); return ss.str(); }; @@ -866,7 +945,8 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) subElement = name; } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); std::vector refs = pcAttach->AttachmentSupport.getValues(); std::vector refnames = pcAttach->AttachmentSupport.getSubValues(); if (idx < refs.size()) { @@ -887,27 +967,40 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) void TaskAttacher::updateRefButton(int idx) { - if (!ViewProvider) + if (!ViewProvider) { return; + } QAbstractButton* b; switch (idx) { - case 0: b = ui->buttonRef1; break; - case 1: b = ui->buttonRef2; break; - case 2: b = ui->buttonRef3; break; - case 3: b = ui->buttonRef4; break; - default: throw Base::IndexError("button index out of range"); + case 0: + b = ui->buttonRef1; + break; + case 1: + b = ui->buttonRef2; + break; + case 2: + b = ui->buttonRef3; + break; + case 3: + b = ui->buttonRef4; + break; + default: + throw Base::IndexError("button index out of range"); } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); std::vector refs = pcAttach->AttachmentSupport.getValues(); int numrefs = refs.size(); bool enable = true; - if (idx > numrefs) + if (idx > numrefs) { enable = false; - if (idx == numrefs && this->lastSuggestResult.nextRefTypeHint.empty()) + } + if (idx == numrefs && this->lastSuggestResult.nextRefTypeHint.empty()) { enable = false; + } b->setEnabled(enable); b->setChecked(iActiveRef == idx); @@ -925,10 +1018,12 @@ void TaskAttacher::updateRefButton(int idx) void TaskAttacher::updateAttachmentOffsetUI() { - if (!ViewProvider) + if (!ViewProvider) { return; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); Base::Placement pl = pcAttach->AttachmentOffset.getValue(); Base::Vector3d pos = pl.getPosition(); Base::Rotation rot = pl.getRotation(); @@ -952,21 +1047,43 @@ void TaskAttacher::updateAttachmentOffsetUI() auto expressions = ViewProvider->getObject()->ExpressionEngine.getExpressions(); bool bRotationBound = false; - bRotationBound = bRotationBound || - expressions.find(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Angle"))) != expressions.end(); - bRotationBound = bRotationBound || - expressions.find(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Axis.x"))) != expressions.end(); - bRotationBound = bRotationBound || - expressions.find(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Axis.y"))) != expressions.end(); - bRotationBound = bRotationBound || - expressions.find(App::ObjectIdentifier::parse(ViewProvider->getObject(), std::string("AttachmentOffset.Rotation.Axis.z"))) != expressions.end(); + bRotationBound = bRotationBound + || expressions.find( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Angle") + ) + ) != expressions.end(); + bRotationBound = bRotationBound + || expressions.find( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Axis.x") + ) + ) != expressions.end(); + bRotationBound = bRotationBound + || expressions.find( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Axis.y") + ) + ) != expressions.end(); + bRotationBound = bRotationBound + || expressions.find( + App::ObjectIdentifier::parse( + ViewProvider->getObject(), + std::string("AttachmentOffset.Rotation.Axis.z") + ) + ) != expressions.end(); ui->attachmentOffsetYaw->setEnabled(!bRotationBound); ui->attachmentOffsetPitch->setEnabled(!bRotationBound); ui->attachmentOffsetRoll->setEnabled(!bRotationBound); if (bRotationBound) { - QString tooltip = tr("Not editable because rotation of AttachmentOffset is bound by expressions."); + QString tooltip = tr( + "Not editable because rotation of AttachmentOffset is bound by expressions." + ); ui->attachmentOffsetYaw->setToolTip(tooltip); ui->attachmentOffsetPitch->setToolTip(tooltip); ui->attachmentOffsetRoll->setToolTip(tooltip); @@ -983,66 +1100,79 @@ void TaskAttacher::updateAttachmentOffsetUI() void TaskAttacher::updateListOfModes() { - if (!ViewProvider) + if (!ViewProvider) { return; + } - //first up, remember currently selected mode. + // first up, remember currently selected mode. eMapMode curMode = mmDeactivated; auto sel = ui->listOfModes->selectedItems(); - if (!sel.isEmpty()) + if (!sel.isEmpty()) { curMode = modesInList[ui->listOfModes->row(sel[0])]; + } - //obtain list of available modes: - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + // obtain list of available modes: + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); this->lastSuggestResult.bestFitMode = mmDeactivated; size_t lastValidModeItemIndex = mmDummy_NumberOfModes; if (pcAttach->AttachmentSupport.getSize() > 0) { pcAttach->attacher().suggestMapModes(this->lastSuggestResult); modesInList = this->lastSuggestResult.allApplicableModes; - modesInList.insert(modesInList.begin(), mmDeactivated); // always have the option to choose Deactivated mode + modesInList.insert(modesInList.begin(), mmDeactivated); // always have the option to choose + // Deactivated mode - //add reachable modes to the list, too, but gray them out (using lastValidModeItemIndex, later) + // add reachable modes to the list, too, but gray them out (using lastValidModeItemIndex, later) lastValidModeItemIndex = modesInList.size() - 1; - for (std::pair& rm : this->lastSuggestResult.reachableModes) { + for (std::pair& rm : + this->lastSuggestResult.reachableModes) { modesInList.push_back(rm.first); } } else { - //no references - display all modes + // no references - display all modes modesInList.clear(); modesInList.push_back(mmDeactivated); for (int mmode = 0; mmode < mmDummy_NumberOfModes; mmode++) { - if (pcAttach->attacher().modeEnabled[mmode]) + if (pcAttach->attacher().modeEnabled[mmode]) { modesInList.push_back(eMapMode(mmode)); + } } } - //populate list + // populate list ui->listOfModes->blockSignals(true); ui->listOfModes->clear(); QListWidgetItem* iSelect = nullptr; if (!modesInList.empty()) { for (size_t i = 0; i < modesInList.size(); ++i) { eMapMode mmode = modesInList[i]; - std::vector mstr = AttacherGui::getUIStrings(pcAttach->attacher().getTypeId(), mmode); + std::vector mstr + = AttacherGui::getUIStrings(pcAttach->attacher().getTypeId(), mmode); ui->listOfModes->addItem(mstr[0]); QListWidgetItem* item = ui->listOfModes->item(i); QString tooltip = mstr[1]; if (mmode != mmDeactivated) { tooltip += QStringLiteral("\n\n%1\n%2") - .arg(tr("Reference combinations:"), - AttacherGui::getRefListForMode(pcAttach->attacher(), mmode).join(QStringLiteral("\n"))); + .arg( + tr("Reference combinations:"), + AttacherGui::getRefListForMode(pcAttach->attacher(), mmode) + .join(QStringLiteral("\n")) + ); } item->setToolTip(tooltip); - if (mmode == curMode && curMode != mmDeactivated) + if (mmode == curMode && curMode != mmDeactivated) { iSelect = ui->listOfModes->item(i); + } if (i > lastValidModeItemIndex) { - //potential mode - can be reached by selecting more stuff - item->setFlags(item->flags() & ~(Qt::ItemFlag::ItemIsEnabled | Qt::ItemFlag::ItemIsSelectable)); + // potential mode - can be reached by selecting more stuff + item->setFlags( + item->flags() & ~(Qt::ItemFlag::ItemIsEnabled | Qt::ItemFlag::ItemIsSelectable) + ); refTypeStringList& extraRefs = this->lastSuggestResult.reachableModes[mmode]; if (extraRefs.size() == 1) { @@ -1050,33 +1180,31 @@ void TaskAttacher::updateListOfModes() for (eRefType rt : extraRefs[0]) { buf.append(AttacherGui::getShapeTypeText(rt)); } - item->setText(tr("%1 (add %2)").arg( - item->text(), - buf.join(QStringLiteral("+")) - )); + item->setText(tr("%1 (add %2)").arg(item->text(), buf.join(QStringLiteral("+")))); } else { item->setText(tr("%1 (add more references)").arg(item->text())); } } else if (mmode == this->lastSuggestResult.bestFitMode) { - //suggested mode - make bold + // suggested mode - make bold QFont fnt = item->font(); fnt.setBold(true); item->setFont(fnt); } - } } - //restore selection - if (iSelect) + // restore selection + if (iSelect) { iSelect->setSelected(true); + } ui->listOfModes->blockSignals(false); } -void TaskAttacher::selectMapMode(eMapMode mmode) { +void TaskAttacher::selectMapMode(eMapMode mmode) +{ ui->listOfModes->blockSignals(true); for (size_t i = 0; i < modesInList.size(); ++i) { @@ -1102,13 +1230,16 @@ void TaskAttacher::showPlacementUtilities() Attacher::eMapMode TaskAttacher::getActiveMapMode() { auto sel = ui->listOfModes->selectedItems(); - if (!sel.isEmpty()) + if (!sel.isEmpty()) { return modesInList[ui->listOfModes->row(sel[0])]; + } else { - if (this->lastSuggestResult.message == SuggestResult::srOK) + if (this->lastSuggestResult.message == SuggestResult::srOK) { return this->lastSuggestResult.bestFitMode; - else + } + else { return mmDeactivated; + } }; } @@ -1176,40 +1307,46 @@ void TaskAttacher::changeEvent(QEvent* e) void TaskAttacher::visibilityAutomation(bool opening_not_closing) { auto defvisfunc = [](bool opening_not_closing, - const std::string& postfix, - Gui::ViewProviderDocumentObject* vp, - App::DocumentObject* editObj, - const std::string& editSubName) { + const std::string& postfix, + Gui::ViewProviderDocumentObject* vp, + App::DocumentObject* editObj, + const std::string& editSubName) { if (opening_not_closing) { - QString code = QStringLiteral( - "import Show\n" - "from Show.Containers import isAContainer\n" - "_tv_%4 = Show.TempoVis(App.ActiveDocument, tag= 'PartGui::TaskAttacher')\n" - "tvObj = %1\n" - "dep_features = _tv_%4.get_all_dependent(%2, '%3')\n" - "dep_features = [o for o in dep_features if not isAContainer(o)]\n" - "if tvObj.isDerivedFrom('PartDesign::CoordinateSystem'):\n" - "\tvisible_features = [feat for feat in tvObj.InList if feat.isDerivedFrom('PartDesign::FeaturePrimitive')]\n" - "\tdep_features = [feat for feat in dep_features if feat not in visible_features]\n" - "\tdel(visible_features)\n" - "_tv_%4.hide(dep_features)\n" - "del(dep_features)\n" - "if not tvObj.isDerivedFrom('PartDesign::CoordinateSystem'):\n" - "\t\tif len(tvObj.AttachmentSupport) > 0:\n" - "\t\t\t_tv_%4.show([lnk[0] for lnk in tvObj.AttachmentSupport])\n" - "del(tvObj)" - ).arg( - QString::fromLatin1(Gui::Command::getObjectCmd(vp->getObject()).c_str()), - QString::fromLatin1(Gui::Command::getObjectCmd(editObj).c_str()), - QString::fromLatin1(editSubName.c_str()), - QString::fromLatin1(postfix.c_str())); + QString code + = QStringLiteral( + "import Show\n" + "from Show.Containers import isAContainer\n" + "_tv_%4 = Show.TempoVis(App.ActiveDocument, tag= 'PartGui::TaskAttacher')\n" + "tvObj = %1\n" + "dep_features = _tv_%4.get_all_dependent(%2, '%3')\n" + "dep_features = [o for o in dep_features if not isAContainer(o)]\n" + "if tvObj.isDerivedFrom('PartDesign::CoordinateSystem'):\n" + "\tvisible_features = [feat for feat in tvObj.InList if " + "feat.isDerivedFrom('PartDesign::FeaturePrimitive')]\n" + "\tdep_features = [feat for feat in dep_features if feat not in " + "visible_features]\n" + "\tdel(visible_features)\n" + "_tv_%4.hide(dep_features)\n" + "del(dep_features)\n" + "if not tvObj.isDerivedFrom('PartDesign::CoordinateSystem'):\n" + "\t\tif len(tvObj.AttachmentSupport) > 0:\n" + "\t\t\t_tv_%4.show([lnk[0] for lnk in tvObj.AttachmentSupport])\n" + "del(tvObj)" + ) + .arg( + QString::fromLatin1(Gui::Command::getObjectCmd(vp->getObject()).c_str()), + QString::fromLatin1(Gui::Command::getObjectCmd(editObj).c_str()), + QString::fromLatin1(editSubName.c_str()), + QString::fromLatin1(postfix.c_str()) + ); Gui::Command::runCommand(Gui::Command::Gui, code.toLatin1().constData()); } else if (!postfix.empty()) { QString code = QStringLiteral( - "_tv_%1.restore()\n" - "del(_tv_%1)" - ).arg(QString::fromLatin1(postfix.c_str())); + "_tv_%1.restore()\n" + "del(_tv_%1)" + ) + .arg(QString::fromLatin1(postfix.c_str())); Gui::Command::runCommand(Gui::Command::Gui, code.toLatin1().constData()); } }; @@ -1217,21 +1354,23 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) auto visAutoFunc = visibilityFunc ? visibilityFunc : defvisfunc; if (opening_not_closing) { - //crash guards - if (!ViewProvider) + // crash guards + if (!ViewProvider) { return; - if (!ViewProvider->getObject()) + } + if (!ViewProvider->getObject()) { return; - if (!ViewProvider->getObject()->isAttachedToDocument()) + } + if (!ViewProvider->getObject()->isAttachedToDocument()) { return; + } auto editDoc = Gui::Application::Instance->editDocument(); App::DocumentObject* editObj = ViewProvider->getObject(); std::string editSubName; auto sels = Gui::Selection().getSelection(nullptr, Gui::ResolveMode::NoResolve, true); if (!sels.empty() && sels[0].pResolvedObject - && sels[0].pResolvedObject->getLinkedObject() == editObj) - { + && sels[0].pResolvedObject->getLinkedObject() == editObj) { editObj = sels[0].pObject; editSubName = sels[0].SubName; } @@ -1239,8 +1378,9 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) ViewProviderDocumentObject* editVp = nullptr; if (editDoc) { editDoc->getInEdit(&editVp, &editSubName); - if (editVp) + if (editVp) { editObj = editVp->getObject(); + } } } ObjectName = ViewProvider->getObject()->getNameInDocument(); @@ -1272,9 +1412,18 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgAttacher::TaskDlgAttacher(Gui::ViewProviderDocumentObject* ViewProvider, bool createBox, - std::function onAccept, std::function onReject) - : TaskDialog(), ViewProvider(ViewProvider), parameter(nullptr), onAccept(onAccept), onReject(onReject), accepted(false) +TaskDlgAttacher::TaskDlgAttacher( + Gui::ViewProviderDocumentObject* ViewProvider, + bool createBox, + std::function onAccept, + std::function onReject +) + : TaskDialog() + , ViewProvider(ViewProvider) + , parameter(nullptr) + , onAccept(onAccept) + , onReject(onReject) + , accepted(false) { assert(ViewProvider); setDocumentName(ViewProvider->getDocument()->getDocument()->getName()); @@ -1303,37 +1452,58 @@ void TaskDlgAttacher::open() } void TaskDlgAttacher::clicked(int) -{ - -} +{} bool TaskDlgAttacher::accept() { try { Gui::DocumentT doc(getDocumentName()); Gui::Document* document = doc.getDocument(); - if (!document || !ViewProvider) + if (!document || !ViewProvider) { return true; + } - Part::AttachExtension* pcAttach = ViewProvider->getObject()->getExtensionByType(); + Part::AttachExtension* pcAttach + = ViewProvider->getObject()->getExtensionByType(); auto obj = ViewProvider->getObject(); - //DeepSOIC: changed this to heavily rely on dialog constantly updating feature properties - //if (pcAttach->AttachmentOffset.isTouched()){ + // DeepSOIC: changed this to heavily rely on dialog constantly updating feature properties + // if (pcAttach->AttachmentOffset.isTouched()){ Base::Placement plm = pcAttach->AttachmentOffset.getValue(); double yaw, pitch, roll; plm.getRotation().getYawPitchRoll(yaw, pitch, roll); - Gui::cmdAppObjectArgs(obj, "AttachmentOffset = App.Placement(App.Vector(%.10f, %.10f, %.10f), App.Rotation(%.10f, %.10f, %.10f))", - plm.getPosition().x, plm.getPosition().y, plm.getPosition().z, yaw, pitch, roll); + Gui::cmdAppObjectArgs( + obj, + "AttachmentOffset = App.Placement(App.Vector(%.10f, %.10f, %.10f), " + "App.Rotation(%.10f, %.10f, %.10f))", + plm.getPosition().x, + plm.getPosition().y, + plm.getPosition().z, + yaw, + pitch, + roll + ); //} - Gui::cmdAppObjectArgs(obj, "MapReversed = %s", pcAttach->MapReversed.getValue() ? "True" : "False"); + Gui::cmdAppObjectArgs( + obj, + "MapReversed = %s", + pcAttach->MapReversed.getValue() ? "True" : "False" + ); - Gui::cmdAppObjectArgs(obj, "AttachmentSupport = %s", pcAttach->AttachmentSupport.getPyReprString().c_str()); + Gui::cmdAppObjectArgs( + obj, + "AttachmentSupport = %s", + pcAttach->AttachmentSupport.getPyReprString().c_str() + ); Gui::cmdAppObjectArgs(obj, "MapPathParameter = %f", pcAttach->MapPathParameter.getValue()); - Gui::cmdAppObjectArgs(obj, "MapMode = '%s'", AttachEngine::getModeName(eMapMode(pcAttach->MapMode.getValue())).c_str()); + Gui::cmdAppObjectArgs( + obj, + "MapMode = '%s'", + AttachEngine::getModeName(eMapMode(pcAttach->MapMode.getValue())).c_str() + ); Gui::cmdAppObject(obj, "recompute()"); Gui::cmdGuiDocument(obj, "resetEdit()"); @@ -1341,7 +1511,11 @@ bool TaskDlgAttacher::accept() Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - QMessageBox::warning(parameter, tr("Datum dialog: input error"), QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + parameter, + tr("Datum dialog: input error"), + QCoreApplication::translate("Exception", e.what()) + ); return false; } @@ -1355,14 +1529,14 @@ bool TaskDlgAttacher::reject() if (onReject) { onReject(); } - + Gui::DocumentT doc(getDocumentName()); Gui::Document* document = doc.getDocument(); if (document) { // roll back the done things Gui::Command::abortCommand(); - Gui::Command::doCommand(Gui::Command::Gui,"%s.resetEdit()", doc.getGuiDocumentPython().c_str()); - Gui::Command::doCommand(Gui::Command::Doc,"%s.recompute()", doc.getAppDocumentPython().c_str()); + Gui::Command::doCommand(Gui::Command::Gui, "%s.resetEdit()", doc.getGuiDocumentPython().c_str()); + Gui::Command::doCommand(Gui::Command::Doc, "%s.recompute()", doc.getAppDocumentPython().c_str()); } accepted = false; diff --git a/src/Mod/Part/Gui/TaskAttacher.h b/src/Mod/Part/Gui/TaskAttacher.h index 76a1a3e94f..849d454581 100644 --- a/src/Mod/Part/Gui/TaskAttacher.h +++ b/src/Mod/Part/Gui/TaskAttacher.h @@ -42,34 +42,41 @@ class Ui_TaskAttacher; class QLineEdit; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProviderPlane; class ViewProvider; -} +} // namespace Gui -namespace PartGui { +namespace PartGui +{ class Ui_TaskAttacher; -class PartGuiExport TaskAttacher : public Gui::TaskView::TaskBox, public Gui::SelectionObserver +class PartGuiExport TaskAttacher: public Gui::TaskView::TaskBox, public Gui::SelectionObserver { Q_OBJECT public: - using VisibilityFunction = std::function; + using VisibilityFunction = std::function< + void(bool, const std::string&, Gui::ViewProviderDocumentObject*, App::DocumentObject*, const std::string&)>; - explicit TaskAttacher(Gui::ViewProviderDocumentObject *ViewProvider, QWidget *parent, - QString picture, - QString text, VisibilityFunction func = 0); + explicit TaskAttacher( + Gui::ViewProviderDocumentObject* ViewProvider, + QWidget* parent, + QString picture, + QString text, + VisibilityFunction func = 0 + ); ~TaskAttacher() override; - bool getFlip() const; + bool getFlip() const; /** * @brief getActiveMapMode returns either the default mode for selected @@ -78,7 +85,10 @@ public: */ Attacher::eMapMode getActiveMapMode(); - bool isCompleted() const { return completed; } + bool isCompleted() const + { + return completed; + } private Q_SLOTS: void onAttachmentOffsetChanged(double, int idx); @@ -101,7 +111,7 @@ private Q_SLOTS: void visibilityAutomation(bool opening_not_closing); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void objectDeleted(const Gui::ViewProviderDocumentObject&); @@ -124,12 +134,13 @@ private: void findCorrectObjAndSubInThisContext(App::DocumentObject*& obj, std::string& sub); void handleInitialSelection(); - struct SubAndObjName { + struct SubAndObjName + { std::string objName; std::string subName; }; - void addToReference(SubAndObjName pair); - void addToReference(const std::vector& pairs); + void addToReference(SubAndObjName pair); + void addToReference(const std::vector& pairs); /** * @brief updateListOfModes Fills the mode list with modes that apply to @@ -145,7 +156,7 @@ private: void showPlacementUtilities(); protected: - Gui::ViewProviderDocumentObject *ViewProvider; + Gui::ViewProviderDocumentObject* ViewProvider; std::string ObjectName; private: @@ -154,9 +165,12 @@ private: VisibilityFunction visibilityFunc; // TODO fix documentation here (2015-11-10, Fat-Zer) - int iActiveRef; //what reference is being picked in 3d view now? -1 means no one, 0-3 means a reference is being picked. - bool autoNext;//if we should automatically switch to next reference (true after dialog launch, false afterwards) - std::vector modesInList; //this list is synchronous to what is populated into listOfModes widget. + int iActiveRef; // what reference is being picked in 3d view now? -1 means no one, 0-3 means a + // reference is being picked. + bool autoNext; // if we should automatically switch to next reference (true after dialog + // launch, false afterwards) + std::vector modesInList; // this list is synchronous to what is populated + // into listOfModes widget. Attacher::SuggestResult lastSuggestResult; bool completed; @@ -170,16 +184,23 @@ private: }; /// simulation dialog for the TaskView -class PartGuiExport TaskDlgAttacher : public Gui::TaskView::TaskDialog +class PartGuiExport TaskDlgAttacher: public Gui::TaskView::TaskDialog { Q_OBJECT public: - explicit TaskDlgAttacher(Gui::ViewProviderDocumentObject *ViewProvider, bool createBox = true, std::function onAccept = {}, std::function onReject = {}); + explicit TaskDlgAttacher( + Gui::ViewProviderDocumentObject* ViewProvider, + bool createBox = true, + std::function onAccept = {}, + std::function onReject = {} + ); ~TaskDlgAttacher() override; Gui::ViewProviderDocumentObject* getViewProvider() const - { return ViewProvider; } + { + return ViewProvider; + } public: @@ -193,22 +214,26 @@ public: bool reject() override; /// is called by the framework if the user presses the help button bool isAllowedAlterDocument() const override - { return false; } + { + return false; + } /// returns for Close and Help button QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } protected: - Gui::ViewProviderDocumentObject *ViewProvider; + Gui::ViewProviderDocumentObject* ViewProvider; - TaskAttacher *parameter; + TaskAttacher* parameter; std::function onAccept; std::function onReject; bool accepted; }; -} //namespace PartDesignGui +} // namespace PartGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/Part/Gui/TaskCheckGeometry.cpp b/src/Mod/Part/Gui/TaskCheckGeometry.cpp index 3435ec5b17..52a77c5c33 100644 --- a/src/Mod/Part/Gui/TaskCheckGeometry.cpp +++ b/src/Mod/Part/Gui/TaskCheckGeometry.cpp @@ -22,38 +22,38 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#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 @@ -73,77 +73,80 @@ using namespace PartGui; QVector buildShapeEnumVector() { - QVectornames; - names.push_back(QObject::tr("Compound")); //TopAbs_COMPOUND - names.push_back(QObject::tr("Compound solid")); //TopAbs_COMPSOLID - names.push_back(QObject::tr("Solid")); //TopAbs_SOLID - names.push_back(QObject::tr("Shell")); //TopAbs_SHELL - names.push_back(QObject::tr("Face")); //TopAbs_FACE - names.push_back(QObject::tr("Wire")); //TopAbs_WIRE - names.push_back(QObject::tr("Edge")); //TopAbs_EDGE - names.push_back(QObject::tr("Vertex")); //TopAbs_VERTEX - names.push_back(QObject::tr("Shape")); //TopAbs_SHAPE - return names; + QVector names; + names.push_back(QObject::tr("Compound")); // TopAbs_COMPOUND + names.push_back(QObject::tr("Compound solid")); // TopAbs_COMPSOLID + names.push_back(QObject::tr("Solid")); // TopAbs_SOLID + names.push_back(QObject::tr("Shell")); // TopAbs_SHELL + names.push_back(QObject::tr("Face")); // TopAbs_FACE + names.push_back(QObject::tr("Wire")); // TopAbs_WIRE + names.push_back(QObject::tr("Edge")); // TopAbs_EDGE + names.push_back(QObject::tr("Vertex")); // TopAbs_VERTEX + names.push_back(QObject::tr("Shape")); // TopAbs_SHAPE + return names; } -QString shapeEnumToString(const int &index) +QString shapeEnumToString(const int& index) { static QVector names = buildShapeEnumVector(); - if (index < 0 || index > TopAbs_SHAPE) + if (index < 0 || index > TopAbs_SHAPE) { return names.at(8); + } return names.at(index); } QVector buildCheckStatusStringVector() { - QVectornames; - names.push_back(QObject::tr("No error")); // BRepCheck_NoError - names.push_back(QObject::tr("Invalid point on curve")); // BRepCheck_InvalidPointOnCurve - names.push_back(QObject::tr("Invalid point on curve on surface")); // BRepCheck_InvalidPointOnCurveOnSurface - names.push_back(QObject::tr("Invalid point on surface")); // BRepCheck_InvalidPointOnSurface - names.push_back(QObject::tr("No 3D curve")); // BRepCheck_No3DCurve - names.push_back(QObject::tr("Multiple 3D curves")); // BRepCheck_Multiple3DCurve - names.push_back(QObject::tr("Invalid 3D curve")); // BRepCheck_Invalid3DCurve - names.push_back(QObject::tr("No curve on surface")); // BRepCheck_NoCurveOnSurface - names.push_back(QObject::tr("Invalid curve on surface")); // BRepCheck_InvalidCurveOnSurface - names.push_back(QObject::tr("Invalid curve on closed surface")); // BRepCheck_InvalidCurveOnClosedSurface - names.push_back(QObject::tr("Invalid same range flag")); // BRepCheck_InvalidSameRangeFlag - names.push_back(QObject::tr("Invalid same parameter flag")); // BRepCheck_InvalidSameParameterFlag - names.push_back(QObject::tr("Invalid degenerated flag")); // BRepCheck_InvalidDegeneratedFlag - names.push_back(QObject::tr("Free edge")); // BRepCheck_FreeEdge - names.push_back(QObject::tr("Invalid multi-connexity")); // BRepCheck_InvalidMultiConnexity - names.push_back(QObject::tr("Invalid range")); // BRepCheck_InvalidRange - names.push_back(QObject::tr("Empty wire")); // BRepCheck_EmptyWire - names.push_back(QObject::tr("Redundant edge")); // BRepCheck_RedundantEdge - names.push_back(QObject::tr("Self-intersecting wire")); // BRepCheck_SelfIntersectingWire - names.push_back(QObject::tr("No surface")); // BRepCheck_NoSurface - names.push_back(QObject::tr("Invalid wire")); // BRepCheck_InvalidWire - names.push_back(QObject::tr("Redundant wire")); // BRepCheck_RedundantWire - names.push_back(QObject::tr("Intersecting wires")); // BRepCheck_IntersectingWires - names.push_back(QObject::tr("Invalid imbrication of wires")); // BRepCheck_InvalidImbricationOfWires - names.push_back(QObject::tr("Empty shell")); // BRepCheck_EmptyShell - names.push_back(QObject::tr("Redundant face")); // BRepCheck_RedundantFace - names.push_back(QObject::tr("Unorientable shape")); // BRepCheck_UnorientableShape - names.push_back(QObject::tr("Not closed")); // BRepCheck_NotClosed - names.push_back(QObject::tr("Not connected")); // BRepCheck_NotConnected - names.push_back(QObject::tr("Sub-shape not in shape")); // BRepCheck_SubshapeNotInShape - names.push_back(QObject::tr("Bad orientation")); // BRepCheck_BadOrientation - names.push_back(QObject::tr("Bad orientation of sub-shape")); // BRepCheck_BadOrientationOfSubshape - names.push_back(QObject::tr("Invalid tolerance value")); // BRepCheck_InvalidToleranceValue - names.push_back(QObject::tr("Check failed")); // BRepCheck_CheckFail + QVector names; + names.push_back(QObject::tr("No error")); // BRepCheck_NoError + names.push_back(QObject::tr("Invalid point on curve")); // BRepCheck_InvalidPointOnCurve + names.push_back( + QObject::tr("Invalid point on curve on surface") + ); // BRepCheck_InvalidPointOnCurveOnSurface + names.push_back(QObject::tr("Invalid point on surface")); // BRepCheck_InvalidPointOnSurface + names.push_back(QObject::tr("No 3D curve")); // BRepCheck_No3DCurve + names.push_back(QObject::tr("Multiple 3D curves")); // BRepCheck_Multiple3DCurve + names.push_back(QObject::tr("Invalid 3D curve")); // BRepCheck_Invalid3DCurve + names.push_back(QObject::tr("No curve on surface")); // BRepCheck_NoCurveOnSurface + names.push_back(QObject::tr("Invalid curve on surface")); // BRepCheck_InvalidCurveOnSurface + names.push_back( + QObject::tr("Invalid curve on closed surface") + ); // BRepCheck_InvalidCurveOnClosedSurface + names.push_back(QObject::tr("Invalid same range flag")); // BRepCheck_InvalidSameRangeFlag + names.push_back(QObject::tr("Invalid same parameter flag")); // BRepCheck_InvalidSameParameterFlag + names.push_back(QObject::tr("Invalid degenerated flag")); // BRepCheck_InvalidDegeneratedFlag + names.push_back(QObject::tr("Free edge")); // BRepCheck_FreeEdge + names.push_back(QObject::tr("Invalid multi-connexity")); // BRepCheck_InvalidMultiConnexity + names.push_back(QObject::tr("Invalid range")); // BRepCheck_InvalidRange + names.push_back(QObject::tr("Empty wire")); // BRepCheck_EmptyWire + names.push_back(QObject::tr("Redundant edge")); // BRepCheck_RedundantEdge + names.push_back(QObject::tr("Self-intersecting wire")); // BRepCheck_SelfIntersectingWire + names.push_back(QObject::tr("No surface")); // BRepCheck_NoSurface + names.push_back(QObject::tr("Invalid wire")); // BRepCheck_InvalidWire + names.push_back(QObject::tr("Redundant wire")); // BRepCheck_RedundantWire + names.push_back(QObject::tr("Intersecting wires")); // BRepCheck_IntersectingWires + names.push_back(QObject::tr("Invalid imbrication of wires")); // BRepCheck_InvalidImbricationOfWires + names.push_back(QObject::tr("Empty shell")); // BRepCheck_EmptyShell + names.push_back(QObject::tr("Redundant face")); // BRepCheck_RedundantFace + names.push_back(QObject::tr("Unorientable shape")); // BRepCheck_UnorientableShape + names.push_back(QObject::tr("Not closed")); // BRepCheck_NotClosed + names.push_back(QObject::tr("Not connected")); // BRepCheck_NotConnected + names.push_back(QObject::tr("Sub-shape not in shape")); // BRepCheck_SubshapeNotInShape + names.push_back(QObject::tr("Bad orientation")); // BRepCheck_BadOrientation + names.push_back(QObject::tr("Bad orientation of sub-shape")); // BRepCheck_BadOrientationOfSubshape + names.push_back(QObject::tr("Invalid tolerance value")); // BRepCheck_InvalidToleranceValue + names.push_back(QObject::tr("Check failed")); // BRepCheck_CheckFail return names; } -QString checkStatusToString(const int &index) +QString checkStatusToString(const int& index) { static QVector names = buildCheckStatusStringVector(); - if (index == -1) - { + if (index == -1) { return QString(QObject::tr("No result")); } - if (index > 33 || index < 0) - { + if (index > 33 || index < 0) { QString message(QObject::tr("Out of enum range:") + QStringLiteral(" ")); QString number; number.setNum(index); @@ -155,30 +158,39 @@ QString checkStatusToString(const int &index) QVector buildBOPCheckResultVector() { - QVector results; - results.push_back(QObject::tr("Boolean operation: unknown check")); //BOPAlgo_CheckUnknown - results.push_back(QObject::tr("Boolean operation: bad type")); //BOPAlgo_BadType - results.push_back(QObject::tr("Boolean operation: self-intersection found")); //BOPAlgo_SelfIntersect - results.push_back(QObject::tr("Boolean operation: edge too small")); //BOPAlgo_TooSmallEdge - results.push_back(QObject::tr("Boolean operation: non-recoverable face")); //BOPAlgo_NonRecoverableFace - results.push_back(QObject::tr("Boolean operation: incompatibility of vertex")); //BOPAlgo_IncompatibilityOfVertex - results.push_back(QObject::tr("Boolean operation: incompatibility of edge")); //BOPAlgo_IncompatibilityOfEdge - results.push_back(QObject::tr("Boolean operation: incompatibility of face")); //BOPAlgo_IncompatibilityOfFace - results.push_back(QObject::tr("Boolean operation: aborted")); //BOPAlgo_OperationAborted - results.push_back(QObject::tr("Boolean operation: GeomAbs_C0")); //BOPAlgo_GeomAbs_C0 - results.push_back(QObject::tr("Boolean operation: invalid curve on surface")); //BOPAlgo_InvalidCurveOnSurface - results.push_back(QObject::tr("Boolean operation: not valid")); //BOPAlgo_NotValid + QVector results; + results.push_back(QObject::tr("Boolean operation: unknown check")); // BOPAlgo_CheckUnknown + results.push_back(QObject::tr("Boolean operation: bad type")); // BOPAlgo_BadType + results.push_back(QObject::tr("Boolean operation: self-intersection found")); // BOPAlgo_SelfIntersect + results.push_back(QObject::tr("Boolean operation: edge too small")); // BOPAlgo_TooSmallEdge + results.push_back(QObject::tr("Boolean operation: non-recoverable face")); // BOPAlgo_NonRecoverableFace + results.push_back( + QObject::tr("Boolean operation: incompatibility of vertex") + ); // BOPAlgo_IncompatibilityOfVertex + results.push_back( + QObject::tr("Boolean operation: incompatibility of edge") + ); // BOPAlgo_IncompatibilityOfEdge + results.push_back( + QObject::tr("Boolean operation: incompatibility of face") + ); // BOPAlgo_IncompatibilityOfFace + results.push_back(QObject::tr("Boolean operation: aborted")); // BOPAlgo_OperationAborted + results.push_back(QObject::tr("Boolean operation: GeomAbs_C0")); // BOPAlgo_GeomAbs_C0 + results.push_back( + QObject::tr("Boolean operation: invalid curve on surface") + ); // BOPAlgo_InvalidCurveOnSurface + results.push_back(QObject::tr("Boolean operation: not valid")); // BOPAlgo_NotValid - return results; + return results; } -QString getBOPCheckString(const BOPAlgo_CheckStatus &status) +QString getBOPCheckString(const BOPAlgo_CheckStatus& status) { - static QVector strings = buildBOPCheckResultVector(); - int index = static_cast(status); - if (index < 0 || index > strings.size()) - index = 0; - return strings.at(index); + static QVector strings = buildBOPCheckResultVector(); + int index = static_cast(status); + if (index < 0 || index > strings.size()) { + index = 0; + } + return strings.at(index); } ResultEntry::ResultEntry() @@ -193,10 +205,12 @@ ResultEntry::ResultEntry() ResultEntry::~ResultEntry() { - if (boxSep && viewProviderRoot) + if (boxSep && viewProviderRoot) { viewProviderRoot->removeChild(boxSep); - if (viewProviderRoot) + } + if (viewProviderRoot) { viewProviderRoot->unref(); + } qDeleteAll(children); } @@ -205,172 +219,185 @@ void ResultEntry::buildEntryName() ResultEntry* parentEntry = this; while (parentEntry->parent) { ResultEntry* temp = parentEntry->parent; - if (!temp->parent) + if (!temp->parent) { break; + } parentEntry = parentEntry->parent; } - QString stringOut; - QTextStream stream(&stringOut); - TopTools_IndexedMapOfShape shapeMap; - int index(-1); + QString stringOut; + QTextStream stream(&stringOut); + TopTools_IndexedMapOfShape shapeMap; + int index(-1); - switch (this->shape.ShapeType()) - { - case TopAbs_COMPOUND: - TopExp::MapShapes(parentEntry->shape, TopAbs_COMPOUND, shapeMap); - stream << "Compound"; - break; - case TopAbs_COMPSOLID: - TopExp::MapShapes(parentEntry->shape, TopAbs_COMPSOLID, shapeMap); - stream << "CompSolid"; - break; - case TopAbs_SOLID: - TopExp::MapShapes(parentEntry->shape, TopAbs_SOLID, shapeMap); - stream << "Solid"; - break; - case TopAbs_SHELL: - TopExp::MapShapes(parentEntry->shape, TopAbs_SHELL, shapeMap); - stream << "Shell"; - break; - case TopAbs_WIRE: - TopExp::MapShapes(parentEntry->shape, TopAbs_WIRE, shapeMap); - stream << "Wire"; - break; - case TopAbs_FACE: - TopExp::MapShapes(parentEntry->shape, TopAbs_FACE, shapeMap); - stream << "Face"; - break; - case TopAbs_EDGE: - TopExp::MapShapes(parentEntry->shape, TopAbs_EDGE, shapeMap); - stream << "Edge"; - break; - case TopAbs_VERTEX: - TopExp::MapShapes(parentEntry->shape, TopAbs_VERTEX, shapeMap); - stream << "Vertex"; - break; - default: - stream << "Unexpected shape type"; - break; - } + switch (this->shape.ShapeType()) { + case TopAbs_COMPOUND: + TopExp::MapShapes(parentEntry->shape, TopAbs_COMPOUND, shapeMap); + stream << "Compound"; + break; + case TopAbs_COMPSOLID: + TopExp::MapShapes(parentEntry->shape, TopAbs_COMPSOLID, shapeMap); + stream << "CompSolid"; + break; + case TopAbs_SOLID: + TopExp::MapShapes(parentEntry->shape, TopAbs_SOLID, shapeMap); + stream << "Solid"; + break; + case TopAbs_SHELL: + TopExp::MapShapes(parentEntry->shape, TopAbs_SHELL, shapeMap); + stream << "Shell"; + break; + case TopAbs_WIRE: + TopExp::MapShapes(parentEntry->shape, TopAbs_WIRE, shapeMap); + stream << "Wire"; + break; + case TopAbs_FACE: + TopExp::MapShapes(parentEntry->shape, TopAbs_FACE, shapeMap); + stream << "Face"; + break; + case TopAbs_EDGE: + TopExp::MapShapes(parentEntry->shape, TopAbs_EDGE, shapeMap); + stream << "Edge"; + break; + case TopAbs_VERTEX: + TopExp::MapShapes(parentEntry->shape, TopAbs_VERTEX, shapeMap); + stream << "Vertex"; + break; + default: + stream << "Unexpected shape type"; + break; + } - index = shapeMap.FindIndex(this->shape); - stream << index; - this->name = stringOut; + index = shapeMap.FindIndex(this->shape); + stream << index; + this->name = stringOut; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -ResultModel::ResultModel(QObject *parent) : QAbstractItemModel(parent) +ResultModel::ResultModel(QObject* parent) + : QAbstractItemModel(parent) { root = nullptr; } ResultModel::~ResultModel() { - if (root) + if (root) { delete root; + } } -QModelIndex ResultModel::index(int row, int column, const QModelIndex &parent) const +QModelIndex ResultModel::index(int row, int column, const QModelIndex& parent) const { - if (!root) + if (!root) { return {}; - ResultEntry *parentNode = nodeFromIndex(parent); - if (!parentNode) + } + ResultEntry* parentNode = nodeFromIndex(parent); + if (!parentNode) { return {}; + } return createIndex(row, column, parentNode->children.at(row)); } -QModelIndex ResultModel::parent(const QModelIndex &child) const +QModelIndex ResultModel::parent(const QModelIndex& child) const { - ResultEntry *childNode = nodeFromIndex(child); - if (!childNode) + ResultEntry* childNode = nodeFromIndex(child); + if (!childNode) { return {}; - ResultEntry *parentNode = childNode->parent; - if (!parentNode) + } + ResultEntry* parentNode = childNode->parent; + if (!parentNode) { return {}; - ResultEntry *grandParentNode = parentNode->parent; - if (!grandParentNode) + } + ResultEntry* grandParentNode = parentNode->parent; + if (!grandParentNode) { return {}; + } int row = grandParentNode->children.indexOf(parentNode); return createIndex(row, 0, parentNode); } -int ResultModel::rowCount(const QModelIndex &parent) const +int ResultModel::rowCount(const QModelIndex& parent) const { - ResultEntry *parentNode = nodeFromIndex(parent); - if (!parentNode) + ResultEntry* parentNode = nodeFromIndex(parent); + if (!parentNode) { return 0; + } return parentNode->children.size(); } -int ResultModel::columnCount(const QModelIndex &parent) const +int ResultModel::columnCount(const QModelIndex& parent) const { Q_UNUSED(parent); return 3; } -QVariant ResultModel::data(const QModelIndex &index, int role) const +QVariant ResultModel::data(const QModelIndex& index, int role) const { - if (role != Qt::DisplayRole) + if (role != Qt::DisplayRole) { return {}; - ResultEntry *node = nodeFromIndex(index); - if (!node) + } + ResultEntry* node = nodeFromIndex(index); + if (!node) { return {}; - switch (index.column()) - { - case 0: - return QVariant(node->name); - case 1: - return QVariant(node->type); - case 2: - return QVariant(node->error); + } + switch (index.column()) { + case 0: + return QVariant(node->name); + case 1: + return QVariant(node->type); + case 2: + return QVariant(node->error); } return {}; } QVariant ResultModel::headerData(int section, Qt::Orientation orientation, int role) const { - if (orientation != Qt::Horizontal || role != Qt::DisplayRole) + if (orientation != Qt::Horizontal || role != Qt::DisplayRole) { return {}; - switch (section) - { - case 0: - return QVariant(QString(tr("Name"))); - case 1: - return QVariant(QString(tr("Type"))); - case 2: - return QVariant(QString(tr("Error"))); + } + switch (section) { + case 0: + return QVariant(QString(tr("Name"))); + case 1: + return QVariant(QString(tr("Type"))); + case 2: + return QVariant(QString(tr("Error"))); } return {}; } -void ResultModel::setResults(ResultEntry *resultsIn) +void ResultModel::setResults(ResultEntry* resultsIn) { this->beginResetModel(); - if (root) + if (root) { delete root; + } root = resultsIn; this->endResetModel(); } -ResultEntry* ResultModel::getEntry(const QModelIndex &index) +ResultEntry* ResultModel::getEntry(const QModelIndex& index) { return nodeFromIndex(index); } -ResultEntry* ResultModel::nodeFromIndex(const QModelIndex &index) const +ResultEntry* ResultModel::nodeFromIndex(const QModelIndex& index) const { - if (index.isValid()) - return static_cast(index.internalPointer()); - else + if (index.isValid()) { + return static_cast(index.internalPointer()); + } + else { return root; + } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// -TaskCheckGeometryResults::TaskCheckGeometryResults(QWidget *parent) : QWidget(parent) +TaskCheckGeometryResults::TaskCheckGeometryResults(QWidget* parent) + : QWidget(parent) { this->setWindowTitle(tr("Check Geometry Results")); setupInterface(); @@ -383,7 +410,7 @@ TaskCheckGeometryResults::~TaskCheckGeometryResults() Gui::Selection().clearSelection(); } catch (const Py::Exception&) { - Base::PyException e; // extract the Python error text + Base::PyException e; // extract the Python error text e.reportException(); } } @@ -401,10 +428,14 @@ void TaskCheckGeometryResults::setupInterface() treeView->setModel(model); treeView->setSelectionMode(QAbstractItemView::SingleSelection); treeView->setSelectionBehavior(QAbstractItemView::SelectRows); - connect(treeView->selectionModel(), &QItemSelectionModel::currentRowChanged, - this, &TaskCheckGeometryResults::currentRowChanged); + connect( + treeView->selectionModel(), + &QItemSelectionModel::currentRowChanged, + this, + &TaskCheckGeometryResults::currentRowChanged + ); - QVBoxLayout *layout = new QVBoxLayout(); + QVBoxLayout* layout = new QVBoxLayout(); layout->addWidget(message); layout->addWidget(treeView); this->setLayout(layout); @@ -416,21 +447,23 @@ void TaskCheckGeometryResults::goCheck() auto selection = Gui::Selection().getSelection(); int selectedCount(0), checkedCount(0), invalidShapes(0); - ResultEntry *theRoot = new ResultEntry(); + ResultEntry* theRoot = new ResultEntry(); reportViewStrings.clear(); reportViewStrings << QLatin1String("\n"); std::string scopeName {tr("Boolean operation check…").toStdString()}; - Handle(Message_ProgressIndicator) theProgress = new BOPProgressIndicator(tr("Check geometry"), - Gui::getMainWindow()); + Handle(Message_ProgressIndicator) theProgress + = new BOPProgressIndicator(tr("Check geometry"), Gui::getMainWindow()); Message_ProgressRange theRange(theProgress->Start()); - Message_ProgressScope theScope(theRange, - TCollection_AsciiString(scopeName.c_str()), - selection.size()); + Message_ProgressScope theScope( + theRange, + TCollection_AsciiString(scopeName.c_str()), + selection.size() + ); theScope.Show(); - for(const auto &sel : selection) { + for (const auto& sel : selection) { selectedCount++; int localInvalidShapeCount(0); QString baseName; @@ -444,30 +477,32 @@ void TaskCheckGeometryResults::goCheck() TopoDS_Shape shape = Part::Feature::getShape( sel.pObject, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sel.SubName); + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sel.SubName + ); if (shape.IsNull()) { - ResultEntry *entry = new ResultEntry(); + ResultEntry* entry = new ResultEntry(); entry->parent = theRoot; entry->name = baseName; entry->type = tr("Null shape"); entry->error = tr("Skipped"); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + entry->error + ); theRoot->children.push_back(entry); continue; } if (shape.Infinite()) { - ResultEntry *entry = new ResultEntry(); + ResultEntry* entry = new ResultEntry(); entry->parent = theRoot; entry->name = baseName; entry->type = tr("Infinite shape"); entry->error = tr("Skipped"); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + entry->error + ); theRoot->children.push_back(entry); continue; } @@ -482,58 +517,68 @@ void TaskCheckGeometryResults::goCheck() buildShapeContent(sel.pObject, baseName, shape); BRepCheck_Analyzer shapeCheck(shape); - if (!shapeCheck.IsValid()) - { + if (!shapeCheck.IsValid()) { invalidShapes++; localInvalidShapeCount++; - ResultEntry *entry = new ResultEntry(); + ResultEntry* entry = new ResultEntry(); entry->parent = theRoot; entry->shape = shape; entry->name = baseName; entry->type = shapeEnumToString(shape.ShapeType()); entry->error = tr("Invalid"); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + entry->error + ); entry->viewProviderRoot = currentSeparator; entry->viewProviderRoot->ref(); goSetupResultBoundingBox(entry); theRoot->children.push_back(entry); recursiveCheck(shapeCheck, shape, entry); - continue; //don't run BOPAlgo_ArgumentAnalyzer if BRepCheck_Analyzer finds something. + continue; // don't run BOPAlgo_ArgumentAnalyzer if BRepCheck_Analyzer finds something. } - else - { - //BOPAlgo_ArgumentAnalyzer can be really slow! - //so only run it when the shape seems valid to BRepCheck_Analyzer And - //when the option is set. + else { + // BOPAlgo_ArgumentAnalyzer can be really slow! + // so only run it when the shape seems valid to BRepCheck_Analyzer And + // when the option is set. - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); - bool runSignal = group->GetBool("RunBOPCheck", false); - group->SetBool("RunBOPCheck", runSignal); - if (runSignal) { - std::string label = tr("Checking").toStdString() + " "; - label += sel.pObject->Label.getStrValue(); - label += "…"; + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); + bool runSignal = group->GetBool("RunBOPCheck", false); + group->SetBool("RunBOPCheck", runSignal); + if (runSignal) { + std::string label = tr("Checking").toStdString() + " "; + label += sel.pObject->Label.getStrValue(); + label += "…"; - Message_ProgressScope theInnerScope(theScope.Next(), TCollection_AsciiString(label.c_str()), 1); - theInnerScope.Show(); - localInvalidShapeCount += goBOPSingleCheck(shape, theRoot, baseName, theInnerScope); - invalidShapes += localInvalidShapeCount; - theInnerScope.Close(); - if (theScope.UserBreak()) - break; - } + Message_ProgressScope theInnerScope( + theScope.Next(), + TCollection_AsciiString(label.c_str()), + 1 + ); + theInnerScope.Show(); + localInvalidShapeCount += goBOPSingleCheck(shape, theRoot, baseName, theInnerScope); + invalidShapes += localInvalidShapeCount; + theInnerScope.Close(); + if (theScope.UserBreak()) { + break; + } + } } // create an entry for shapes without errors if (localInvalidShapeCount == 0) { - ResultEntry *entry = new ResultEntry(); + ResultEntry* entry = new ResultEntry(); entry->parent = theRoot; entry->name = baseName; entry->type = shapeEnumToString(shape.ShapeType()); entry->error = tr("No errors"); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + entry->error + ); entry->viewProviderRoot = currentSeparator; entry->viewProviderRoot->ref(); theRoot->children.push_back(entry); @@ -544,7 +589,8 @@ void TaskCheckGeometryResults::goCheck() treeView->header()->resizeSections(QHeaderView::ResizeToContents); QString aMessage {tr("%1 processed out of %2 selected").arg(checkedCount).arg(selectedCount)}; aMessage += QLatin1String("
      ") + tr("%n invalid shapes.", "", invalidShapes); - aMessage += QLatin1String(" ") + tr("to report view.") + QLatin1String(""); + aMessage += QLatin1String(" ") + tr("to report view.") + + QLatin1String(""); message->setText(aMessage); } @@ -555,24 +601,26 @@ void TaskCheckGeometryResults::generateReport() } -void TaskCheckGeometryResults::recursiveCheck(const BRepCheck_Analyzer &shapeCheck, const TopoDS_Shape &shape, - ResultEntry *parent) +void TaskCheckGeometryResults::recursiveCheck( + const BRepCheck_Analyzer& shapeCheck, + const TopoDS_Shape& shape, + ResultEntry* parent +) { - ResultEntry *branchNode = parent; + ResultEntry* branchNode = parent; BRepCheck_ListIteratorOfListOfStatus listIt; - if (!shapeCheck.Result(shape).IsNull() && !checkedMap.Contains(shape)) - { + if (!shapeCheck.Result(shape).IsNull() && !checkedMap.Contains(shape)) { listIt.Initialize(shapeCheck.Result(shape)->Status()); - if (listIt.Value() != BRepCheck_NoError) - { - ResultEntry *entry = new ResultEntry(); + if (listIt.Value() != BRepCheck_NoError) { + ResultEntry* entry = new ResultEntry(); entry->parent = parent; entry->shape = shape; entry->buildEntryName(); entry->type = shapeEnumToString(shape.ShapeType()); entry->error = checkStatusToString(listIt.Value()); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + entry->error + ); entry->viewProviderRoot = currentSeparator; entry->viewProviderRoot->ref(); dispatchError(entry, listIt.Value()); @@ -582,67 +630,87 @@ void TaskCheckGeometryResults::recursiveCheck(const BRepCheck_Analyzer &shapeChe } checkedMap.Add(shape); - if (shape.ShapeType() == TopAbs_SOLID) + if (shape.ShapeType() == TopAbs_SOLID) { checkSub(shapeCheck, shape, TopAbs_SHELL, branchNode); - if (shape.ShapeType() == TopAbs_EDGE) + } + if (shape.ShapeType() == TopAbs_EDGE) { checkSub(shapeCheck, shape, TopAbs_VERTEX, branchNode); - if (shape.ShapeType() == TopAbs_FACE) - { + } + if (shape.ShapeType() == TopAbs_FACE) { checkSub(shapeCheck, shape, TopAbs_WIRE, branchNode); checkSub(shapeCheck, shape, TopAbs_EDGE, branchNode); checkSub(shapeCheck, shape, TopAbs_VERTEX, branchNode); } - for (TopoDS_Iterator it(shape); it.More(); it.Next()) + for (TopoDS_Iterator it(shape); it.More(); it.Next()) { recursiveCheck(shapeCheck, it.Value(), branchNode); + } } -void TaskCheckGeometryResults::checkSub(const BRepCheck_Analyzer &shapeCheck, const TopoDS_Shape &shape, - const TopAbs_ShapeEnum subType, ResultEntry *parent) +void TaskCheckGeometryResults::checkSub( + const BRepCheck_Analyzer& shapeCheck, + const TopoDS_Shape& shape, + const TopAbs_ShapeEnum subType, + ResultEntry* parent +) { BRepCheck_ListIteratorOfListOfStatus itl; TopExp_Explorer exp; - for (exp.Init(shape,subType); exp.More(); exp.Next()) - { - const Handle(BRepCheck_Result)& res = shapeCheck.Result(exp.Current()); + for (exp.Init(shape, subType); exp.More(); exp.Next()) { + const Handle(BRepCheck_Result) & res = shapeCheck.Result(exp.Current()); const TopoDS_Shape& sub = exp.Current(); - for (res->InitContextIterator(); res->MoreShapeInContext(); res->NextShapeInContext()) - { - if (res->ContextualShape().IsSame(shape)) - { - for (itl.Initialize(res->StatusOnShape()); itl.More(); itl.Next()) - { - if (itl.Value() == BRepCheck_NoError) - break; - checkedMap.Add(sub); - ResultEntry *entry = new ResultEntry(); - entry->parent = parent; - entry->shape = sub; - entry->buildEntryName(); - entry->type = shapeEnumToString(sub.ShapeType()); - entry->error = checkStatusToString(itl.Value()); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); - entry->viewProviderRoot = currentSeparator; - entry->viewProviderRoot->ref(); - dispatchError(entry, itl.Value()); - parent->children.push_back(entry); + for (res->InitContextIterator(); res->MoreShapeInContext(); res->NextShapeInContext()) { + if (res->ContextualShape().IsSame(shape)) { + for (itl.Initialize(res->StatusOnShape()); itl.More(); itl.Next()) { + if (itl.Value() == BRepCheck_NoError) { + break; + } + checkedMap.Add(sub); + ResultEntry* entry = new ResultEntry(); + entry->parent = parent; + entry->shape = sub; + entry->buildEntryName(); + entry->type = shapeEnumToString(sub.ShapeType()); + entry->error = checkStatusToString(itl.Value()); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + + entry->error + ); + entry->viewProviderRoot = currentSeparator; + entry->viewProviderRoot->ref(); + dispatchError(entry, itl.Value()); + parent->children.push_back(entry); } } } } } -void TaskCheckGeometryResults::buildShapeContent(App::DocumentObject *pObject, const QString &baseName, const TopoDS_Shape &shape) +void TaskCheckGeometryResults::buildShapeContent( + App::DocumentObject* pObject, + const QString& baseName, + const TopoDS_Shape& shape +) { - bool advancedShapeContent = App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences")-> - GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry")->GetBool("AdvancedShapeContent", true); - int decimals = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Units")->GetInt("Decimals", 2); + bool advancedShapeContent = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry") + ->GetBool("AdvancedShapeContent", true); + int decimals = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Units") + ->GetInt("Decimals", 2); std::ostringstream stream; - if (!shapeContentString.empty()) + if (!shapeContentString.empty()) { stream << std::endl << std::endl; + } stream << tr("Checked object").toStdString() << ": "; Base::PyGILStateLocker lock; try { @@ -664,21 +732,29 @@ void TaskCheckGeometryResults::buildShapeContent(App::DocumentObject *pObject, c Py::Tuple args(1); { args.setItem(0, Py::Long(-1)); - Py::Float result(Py::asObject(Part::TopoShape(shape).getPyObject()).callMemberFunction("globalTolerance",args)); + Py::Float result( + Py::asObject(Part::TopoShape(shape).getPyObject()) + .callMemberFunction("globalTolerance", args) + ); stream << " " << tr("Global minimum").toStdString() << ": " << result << std::endl; } { args.setItem(0, Py::Long(0)); - Py::Float result(Py::asObject(Part::TopoShape(shape).getPyObject()).callMemberFunction("globalTolerance",args)); + Py::Float result( + Py::asObject(Part::TopoShape(shape).getPyObject()) + .callMemberFunction("globalTolerance", args) + ); stream << " " << tr("Global average").toStdString() << ": " << result << std::endl; } { args.setItem(0, Py::Long(1)); - Py::Float result(Py::asObject(Part::TopoShape(shape).getPyObject()).callMemberFunction("globalTolerance",args)); + Py::Float result( + Py::asObject(Part::TopoShape(shape).getPyObject()) + .callMemberFunction("globalTolerance", args) + ); stream << " " << tr("Global maximum").toStdString() << ": " << result; } } - } catch (Py::Exception&) { Base::PyException e; @@ -693,14 +769,23 @@ void TaskCheckGeometryResults::buildShapeContent(App::DocumentObject *pObject, c QString TaskCheckGeometryResults::getShapeContentString() { - return QString::fromStdString(shapeContentString); + return QString::fromStdString(shapeContentString); } -int TaskCheckGeometryResults::goBOPSingleCheck(const TopoDS_Shape& shapeIn, ResultEntry *theRoot, const QString &baseName, - const Message_ProgressScope& theScope) +int TaskCheckGeometryResults::goBOPSingleCheck( + const TopoDS_Shape& shapeIn, + ResultEntry* theRoot, + const QString& baseName, + const Message_ProgressScope& theScope +) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); bool runSingleThreaded = group->GetBool("RunBOPCheckSingleThreaded", false); bool logErrors = group->GetBool("LogErrors", true); bool argumentTypeMode = group->GetBool("ArgumentTypeMode", true); @@ -713,142 +798,141 @@ int TaskCheckGeometryResults::goBOPSingleCheck(const TopoDS_Shape& shapeIn, Resu bool mergeEdgeMode = group->GetBool("MergeEdgeMode", true); bool curveOnSurfaceMode = group->GetBool("CurveOnSurfaceMode", true); - //Reference use: src/BOPTest/BOPTest_CheckCommands.cxx + // Reference use: src/BOPTest/BOPTest_CheckCommands.cxx - //I don't why we need to make a copy, but it doesn't work without it. - //BRepAlgoAPI_Check also makes a copy of the shape. + // I don't why we need to make a copy, but it doesn't work without it. + // BRepAlgoAPI_Check also makes a copy of the shape. - //didn't use BRepAlgoAPI_Check because it calls BRepCheck_Analyzer itself and - //doesn't give us access to it. so I didn't want to run BRepCheck_Analyzer twice to get invalid results. + // didn't use BRepAlgoAPI_Check because it calls BRepCheck_Analyzer itself and + // doesn't give us access to it. so I didn't want to run BRepCheck_Analyzer twice to get invalid + // results. - //BOPAlgo_ArgumentAnalyzer can check 2 objects with respect to a boolean op. - //this is left for another time. - TopoDS_Shape BOPCopy = BRepBuilderAPI_Copy(shapeIn).Shape(); - BOPAlgo_ArgumentAnalyzer BOPCheck; + // BOPAlgo_ArgumentAnalyzer can check 2 objects with respect to a boolean op. + // this is left for another time. + TopoDS_Shape BOPCopy = BRepBuilderAPI_Copy(shapeIn).Shape(); + BOPAlgo_ArgumentAnalyzer BOPCheck; #if OCC_VERSION_HEX < 0x070600 - BOPCheck.SetProgressIndicator(theScope); + BOPCheck.SetProgressIndicator(theScope); #else - Q_UNUSED(theScope) -#endif // 0x070600 + Q_UNUSED(theScope) +#endif // 0x070600 - BOPCheck.SetShape1(BOPCopy); - //all settings are false by default. so only turn on what we want. - BOPCheck.ArgumentTypeMode() = argumentTypeMode; - BOPCheck.SelfInterMode() = selfInterMode; - BOPCheck.SmallEdgeMode() = smallEdgeMode; - BOPCheck.RebuildFaceMode() = rebuildFaceMode; - BOPCheck.ContinuityMode() = continuityMode; + BOPCheck.SetShape1(BOPCopy); + // all settings are false by default. so only turn on what we want. + BOPCheck.ArgumentTypeMode() = argumentTypeMode; + BOPCheck.SelfInterMode() = selfInterMode; + BOPCheck.SmallEdgeMode() = smallEdgeMode; + BOPCheck.RebuildFaceMode() = rebuildFaceMode; + BOPCheck.ContinuityMode() = continuityMode; - BOPCheck.SetParallelMode(!runSingleThreaded); //this doesn't help for speed right now(occt 6.9.1). - BOPCheck.SetRunParallel(!runSingleThreaded); //performance boost, use all available cores - BOPCheck.TangentMode() = tangentMode; //these 4 new tests add about 5% processing time. - BOPCheck.MergeVertexMode() = mergeVertexMode; - BOPCheck.MergeEdgeMode() = mergeEdgeMode; - BOPCheck.CurveOnSurfaceMode() = curveOnSurfaceMode; + BOPCheck.SetParallelMode(!runSingleThreaded); // this doesn't help for speed right now(occt 6.9.1). + BOPCheck.SetRunParallel(!runSingleThreaded); // performance boost, use all available cores + BOPCheck.TangentMode() = tangentMode; // these 4 new tests add about 5% processing time. + BOPCheck.MergeVertexMode() = mergeVertexMode; + BOPCheck.MergeEdgeMode() = mergeEdgeMode; + BOPCheck.CurveOnSurfaceMode() = curveOnSurfaceMode; #ifdef FC_DEBUG - Base::TimeElapsed start_time; + Base::TimeElapsed start_time; #endif - BOPCheck.Perform(); + BOPCheck.Perform(); #ifdef FC_DEBUG - float bopAlgoTime = Base::TimeElapsed::diffTimeF(start_time, Base::TimeElapsed()); - std::cout << std::endl << "BopAlgo check time is: " << bopAlgoTime << std::endl << std::endl; + float bopAlgoTime = Base::TimeElapsed::diffTimeF(start_time, Base::TimeElapsed()); + std::cout << std::endl << "BopAlgo check time is: " << bopAlgoTime << std::endl << std::endl; #endif - if (!BOPCheck.HasFaulty()) - return 0; - - ResultEntry *entry = new ResultEntry(); - entry->parent = theRoot; - entry->shape = BOPCopy; //this will cause a problem, with existing entry. i.e. entry is true. - entry->name = baseName; - entry->type = shapeEnumToString(shapeIn.ShapeType()); - entry->error = QObject::tr("Invalid"); - reportViewStrings.append(entry->name + QLatin1String(" | ") - + entry->type + QLatin1String(" | ") + entry->error); - entry->viewProviderRoot = currentSeparator; - entry->viewProviderRoot->ref(); - goSetupResultBoundingBox(entry); - theRoot->children.push_back(entry); - - const BOPAlgo_ListOfCheckResult &BOPResults = BOPCheck.GetCheckResult(); - BOPAlgo_ListIteratorOfListOfCheckResult BOPResultsIt(BOPResults); - for (; BOPResultsIt.More(); BOPResultsIt.Next()) - { - const BOPAlgo_CheckResult ¤t = BOPResultsIt.Value(); - const TopTools_ListOfShape &faultyShapes1 = current.GetFaultyShapes1(); - TopTools_ListIteratorOfListOfShape faultyShapes1It(faultyShapes1); - - for (;faultyShapes1It.More(); faultyShapes1It.Next()) - { - const TopoDS_Shape &faultyShape = faultyShapes1It.Value(); - ResultEntry *faultyEntry = new ResultEntry(); - faultyEntry->parent = entry; - faultyEntry->shape = faultyShape; - faultyEntry->buildEntryName(); - faultyEntry->type = shapeEnumToString(faultyShape.ShapeType()); - faultyEntry->error = getBOPCheckString(current.GetCheckStatus()); - reportViewStrings.append(QLatin1String(" ") + faultyEntry->name - + QLatin1String(" | ") + faultyEntry->error); - faultyEntry->viewProviderRoot = currentSeparator; - entry->viewProviderRoot->ref(); - goSetupResultBoundingBox(faultyEntry); - - if (faultyShape.ShapeType() == TopAbs_FACE) - { - goSetupResultTypedSelection(faultyEntry, faultyShape, TopAbs_FACE); - } - else if (faultyShape.ShapeType() == TopAbs_EDGE) - { - goSetupResultTypedSelection(faultyEntry, faultyShape, TopAbs_EDGE); - } - else if (faultyShape.ShapeType() == TopAbs_VERTEX) - { - goSetupResultTypedSelection(faultyEntry, faultyShape, TopAbs_VERTEX); - } - entry->children.push_back(faultyEntry); - - /*log BOPCheck errors to report view*/ - if (logErrors){ - std::clog << faultyEntry->parent->name.toStdString().c_str() << " : " - << faultyEntry->name.toStdString().c_str() << " : " - << faultyEntry->type.toStdString().c_str() << " : " - << faultyEntry->error.toStdString().c_str() - << std::endl; - } + if (!BOPCheck.HasFaulty()) { + return 0; } - } - return 1; + + ResultEntry* entry = new ResultEntry(); + entry->parent = theRoot; + entry->shape = BOPCopy; // this will cause a problem, with existing entry. i.e. entry is true. + entry->name = baseName; + entry->type = shapeEnumToString(shapeIn.ShapeType()); + entry->error = QObject::tr("Invalid"); + reportViewStrings.append( + entry->name + QLatin1String(" | ") + entry->type + QLatin1String(" | ") + entry->error + ); + entry->viewProviderRoot = currentSeparator; + entry->viewProviderRoot->ref(); + goSetupResultBoundingBox(entry); + theRoot->children.push_back(entry); + + const BOPAlgo_ListOfCheckResult& BOPResults = BOPCheck.GetCheckResult(); + BOPAlgo_ListIteratorOfListOfCheckResult BOPResultsIt(BOPResults); + for (; BOPResultsIt.More(); BOPResultsIt.Next()) { + const BOPAlgo_CheckResult& current = BOPResultsIt.Value(); + const TopTools_ListOfShape& faultyShapes1 = current.GetFaultyShapes1(); + TopTools_ListIteratorOfListOfShape faultyShapes1It(faultyShapes1); + + for (; faultyShapes1It.More(); faultyShapes1It.Next()) { + const TopoDS_Shape& faultyShape = faultyShapes1It.Value(); + ResultEntry* faultyEntry = new ResultEntry(); + faultyEntry->parent = entry; + faultyEntry->shape = faultyShape; + faultyEntry->buildEntryName(); + faultyEntry->type = shapeEnumToString(faultyShape.ShapeType()); + faultyEntry->error = getBOPCheckString(current.GetCheckStatus()); + reportViewStrings.append( + QLatin1String(" ") + faultyEntry->name + QLatin1String(" | ") + faultyEntry->error + ); + faultyEntry->viewProviderRoot = currentSeparator; + entry->viewProviderRoot->ref(); + goSetupResultBoundingBox(faultyEntry); + + if (faultyShape.ShapeType() == TopAbs_FACE) { + goSetupResultTypedSelection(faultyEntry, faultyShape, TopAbs_FACE); + } + else if (faultyShape.ShapeType() == TopAbs_EDGE) { + goSetupResultTypedSelection(faultyEntry, faultyShape, TopAbs_EDGE); + } + else if (faultyShape.ShapeType() == TopAbs_VERTEX) { + goSetupResultTypedSelection(faultyEntry, faultyShape, TopAbs_VERTEX); + } + entry->children.push_back(faultyEntry); + + /*log BOPCheck errors to report view*/ + if (logErrors) { + std::clog << faultyEntry->parent->name.toStdString().c_str() << " : " + << faultyEntry->name.toStdString().c_str() << " : " + << faultyEntry->type.toStdString().c_str() << " : " + << faultyEntry->error.toStdString().c_str() << std::endl; + } + } + } + return 1; } -void TaskCheckGeometryResults::dispatchError(ResultEntry *entry, const BRepCheck_Status &stat) +void TaskCheckGeometryResults::dispatchError(ResultEntry* entry, const BRepCheck_Status& stat) { std::vector::iterator mapIt; - for (mapIt = functionMap.begin(); mapIt != functionMap.end(); ++mapIt) - { - if (std::get<0>(*mapIt) == entry->shape.ShapeType() && std::get<1>(*mapIt) == stat) - { + for (mapIt = functionMap.begin(); mapIt != functionMap.end(); ++mapIt) { + if (std::get<0>(*mapIt) == entry->shape.ShapeType() && std::get<1>(*mapIt) == stat) { (std::get<2>(*mapIt))(entry); return; } } goSetupResultBoundingBox(entry); - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); - bool logErrors = group->GetBool("LogErrors", true); //log errors to report view + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); + bool logErrors = group->GetBool("LogErrors", true); // log errors to report view /*log BRepCheck errors to report view*/ - if (logErrors){ + if (logErrors) { std::clog << entry->parent->name.toStdString().c_str() << " : " - << entry->name.toStdString().c_str() << " : " - << entry->type.toStdString().c_str() << " : " - << entry->error.toStdString().c_str() << " (BRepCheck)" - << std::endl; + << entry->name.toStdString().c_str() << " : " << entry->type.toStdString().c_str() + << " : " << entry->error.toStdString().c_str() << " (BRepCheck)" << std::endl; } } @@ -858,37 +942,45 @@ void TaskCheckGeometryResults::setupFunctionMap() functionMap.emplace_back(TopAbs_WIRE, BRepCheck_NotClosed, goSetupResultWireNotClosed); functionMap.emplace_back(TopAbs_VERTEX, BRepCheck_InvalidPointOnCurve, goSetupResultInvalidPointCurve); functionMap.emplace_back(TopAbs_FACE, BRepCheck_IntersectingWires, goSetupResultIntersectingWires); - functionMap.emplace_back(TopAbs_EDGE, BRepCheck_InvalidCurveOnSurface, goSetupResultInvalidCurveSurface); - functionMap.emplace_back(TopAbs_EDGE, BRepCheck_InvalidSameParameterFlag, goSetupResultInvalidSameParameterFlag); + functionMap.emplace_back( + TopAbs_EDGE, + BRepCheck_InvalidCurveOnSurface, + goSetupResultInvalidCurveSurface + ); + functionMap.emplace_back( + TopAbs_EDGE, + BRepCheck_InvalidSameParameterFlag, + goSetupResultInvalidSameParameterFlag + ); functionMap.emplace_back(TopAbs_FACE, BRepCheck_UnorientableShape, goSetupResultUnorientableShapeFace); } -void TaskCheckGeometryResults::currentRowChanged (const QModelIndex ¤t, const QModelIndex &previous) +void TaskCheckGeometryResults::currentRowChanged(const QModelIndex& current, const QModelIndex& previous) { Gui::Selection().clearSelection(); - if (previous.isValid()) - { - ResultEntry *entry = model->getEntry(previous); - if (entry) - { - if (entry->boxSwitch) + if (previous.isValid()) { + ResultEntry* entry = model->getEntry(previous); + if (entry) { + if (entry->boxSwitch) { entry->boxSwitch->whichChild.setValue(SO_SWITCH_NONE); + } } } - if (current.isValid()) - { - ResultEntry *entry = model->getEntry(current); - if (entry) - { - if (entry->boxSwitch) + if (current.isValid()) { + ResultEntry* entry = model->getEntry(current); + if (entry) { + if (entry->boxSwitch) { entry->boxSwitch->whichChild.setValue(0); + } QStringList::Iterator stringIt; - for (stringIt = entry->selectionStrings.begin(); stringIt != entry->selectionStrings.end(); ++stringIt) - { - //need unique delimiter. + for (stringIt = entry->selectionStrings.begin(); + stringIt != entry->selectionStrings.end(); + ++stringIt) { + // need unique delimiter. QString doc, object, sub; - if (!this->split((*stringIt), doc, object, sub)) + if (!this->split((*stringIt), doc, object, sub)) { continue; + } // object might be "name (label)", so trim if necessary int idx = object.indexOf(QLatin1String(" (")); QString trimmed = (idx != -1) ? object.left(idx) : object; @@ -898,11 +990,12 @@ void TaskCheckGeometryResults::currentRowChanged (const QModelIndex ¤t, co } } -bool TaskCheckGeometryResults::split(QString &input, QString &doc, QString &object, QString &sub) +bool TaskCheckGeometryResults::split(QString& input, QString& doc, QString& object, QString& sub) { QStringList strings = input.split(QStringLiteral(".")); - if (strings.size() != 3) + if (strings.size() != 3) { return false; + } doc = strings.at(0); object = strings.at(1); sub = strings.at(2); @@ -911,14 +1004,14 @@ bool TaskCheckGeometryResults::split(QString &input, QString &doc, QString &obje //////////////////////////////////////////////////////////////////////////////////////////////// -QString PartGui::buildSelectionName(const ResultEntry *entry, const TopoDS_Shape &shape) +QString PartGui::buildSelectionName(const ResultEntry* entry, const TopoDS_Shape& shape) { - const ResultEntry *parentEntry = entry; - while(parentEntry->parent) - { - ResultEntry *temp = parentEntry->parent; - if (!temp->parent) - break; + const ResultEntry* parentEntry = entry; + while (parentEntry->parent) { + ResultEntry* temp = parentEntry->parent; + if (!temp->parent) { + break; + } parentEntry = parentEntry->parent; } @@ -929,23 +1022,22 @@ QString PartGui::buildSelectionName(const ResultEntry *entry, const TopoDS_Shape TopTools_IndexedMapOfShape shapeMap; int index(-1); - switch (shape.ShapeType()) - { - case TopAbs_FACE: - TopExp::MapShapes(parentEntry->shape, TopAbs_FACE, shapeMap); - stream << "Face"; - break; - case TopAbs_EDGE: - TopExp::MapShapes(parentEntry->shape, TopAbs_EDGE, shapeMap); - stream << "Edge"; - break; - case TopAbs_VERTEX: - TopExp::MapShapes(parentEntry->shape, TopAbs_VERTEX, shapeMap); - stream << "Vertex"; - break; - default: - stream << "Unexpected shape type"; - break; + switch (shape.ShapeType()) { + case TopAbs_FACE: + TopExp::MapShapes(parentEntry->shape, TopAbs_FACE, shapeMap); + stream << "Face"; + break; + case TopAbs_EDGE: + TopExp::MapShapes(parentEntry->shape, TopAbs_EDGE, shapeMap); + stream << "Edge"; + break; + case TopAbs_VERTEX: + TopExp::MapShapes(parentEntry->shape, TopAbs_VERTEX, shapeMap); + stream << "Vertex"; + break; + default: + stream << "Unexpected shape type"; + break; } index = shapeMap.FindIndex(shape); @@ -953,61 +1045,65 @@ QString PartGui::buildSelectionName(const ResultEntry *entry, const TopoDS_Shape return stringOut; } -void PartGui::goSetupResultTypedSelection(ResultEntry* entry, const TopoDS_Shape& shape, TopAbs_ShapeEnum type) +void PartGui::goSetupResultTypedSelection( + ResultEntry* entry, + const TopoDS_Shape& shape, + TopAbs_ShapeEnum type +) { TopExp_Explorer it; - for (it.Init(shape, type); it.More(); it.Next()) - { + for (it.Init(shape, type); it.More(); it.Next()) { QString name = buildSelectionName(entry, (it.Current())); - if (!name.isEmpty()) + if (!name.isEmpty()) { entry->selectionStrings.append(name); + } } } -void PartGui::goSetupResultBoundingBox(ResultEntry *entry) +void PartGui::goSetupResultBoundingBox(ResultEntry* entry) { - //empty compound throws bounding box error. Mantis #0001426 - try - { - Bnd_Box boundingBox; - BRepBndLib::Add(entry->shape, boundingBox); - Standard_Real xmin, ymin, zmin, xmax, ymax, zmax; - boundingBox.Get(xmin, ymin, zmin, xmax, ymax, zmax); - SbVec3f boundCenter((xmax - xmin)/2 + xmin, (ymax - ymin)/2 + ymin, (zmax - zmin)/2 + zmin); + // empty compound throws bounding box error. Mantis #0001426 + try { + Bnd_Box boundingBox; + BRepBndLib::Add(entry->shape, boundingBox); + Standard_Real xmin, ymin, zmin, xmax, ymax, zmax; + boundingBox.Get(xmin, ymin, zmin, xmax, ymax, zmax); + SbVec3f boundCenter((xmax - xmin) / 2 + xmin, (ymax - ymin) / 2 + ymin, (zmax - zmin) / 2 + zmin); - entry->boxSep = new SoSeparator(); - entry->viewProviderRoot->addChild(entry->boxSep); - entry->boxSwitch = new SoSwitch(); - entry->boxSep->addChild(entry->boxSwitch); - SoGroup *group = new SoGroup(); - entry->boxSwitch->addChild(group); - entry->boxSwitch->whichChild.setValue(SO_SWITCH_NONE); - SoDrawStyle *dStyle = new SoDrawStyle(); - dStyle->style.setValue(SoDrawStyle::LINES); - dStyle->linePattern.setValue(0xc0c0); - group->addChild(dStyle); - SoMaterial *material = new SoMaterial(); - material->diffuseColor.setValue(255.0, 255.0, 255.0); - material->ambientColor.setValue(255.0, 255.0, 255.0); - group->addChild(material); + entry->boxSep = new SoSeparator(); + entry->viewProviderRoot->addChild(entry->boxSep); + entry->boxSwitch = new SoSwitch(); + entry->boxSep->addChild(entry->boxSwitch); + SoGroup* group = new SoGroup(); + entry->boxSwitch->addChild(group); + entry->boxSwitch->whichChild.setValue(SO_SWITCH_NONE); + SoDrawStyle* dStyle = new SoDrawStyle(); + dStyle->style.setValue(SoDrawStyle::LINES); + dStyle->linePattern.setValue(0xc0c0); + group->addChild(dStyle); + SoMaterial* material = new SoMaterial(); + material->diffuseColor.setValue(255.0, 255.0, 255.0); + material->ambientColor.setValue(255.0, 255.0, 255.0); + group->addChild(material); - SoResetTransform *reset = new SoResetTransform(); - group->addChild(reset); + SoResetTransform* reset = new SoResetTransform(); + group->addChild(reset); - SoTransform *position = new SoTransform(); - position->translation.setValue(boundCenter); - group->addChild(position); + SoTransform* position = new SoTransform(); + position->translation.setValue(boundCenter); + group->addChild(position); - SoCube *cube = new SoCube(); - cube->width.setValue(xmax - xmin); - cube->height.setValue(ymax - ymin); - cube->depth.setValue(zmax - zmin); - group->addChild(cube); + SoCube* cube = new SoCube(); + cube->width.setValue(xmax - xmin); + cube->height.setValue(ymax - ymin); + cube->depth.setValue(zmax - zmin); + group->addChild(cube); + } + catch (const Standard_Failure&) { } - catch (const Standard_Failure &){} } -void PartGui::goSetupResultShellNotClosed(ResultEntry *entry) +void PartGui::goSetupResultShellNotClosed(ResultEntry* entry) { ShapeAnalysis_FreeBounds shellCheck(entry->shape); TopoDS_Compound closedWires = shellCheck.GetClosedWires(); @@ -1019,37 +1115,37 @@ void PartGui::goSetupResultShellNotClosed(ResultEntry *entry) goSetupResultBoundingBox(entry); } -void PartGui::goSetupResultWireNotClosed(ResultEntry *entry) +void PartGui::goSetupResultWireNotClosed(ResultEntry* entry) { goSetupResultTypedSelection(entry, entry->shape, TopAbs_EDGE); goSetupResultBoundingBox(entry); } -void PartGui::goSetupResultInvalidPointCurve(ResultEntry *entry) +void PartGui::goSetupResultInvalidPointCurve(ResultEntry* entry) { goSetupResultTypedSelection(entry, entry->shape, TopAbs_VERTEX); goSetupResultBoundingBox(entry); } -void PartGui::goSetupResultIntersectingWires(ResultEntry *entry) +void PartGui::goSetupResultIntersectingWires(ResultEntry* entry) { goSetupResultTypedSelection(entry, entry->shape, TopAbs_FACE); goSetupResultBoundingBox(entry); } -void PartGui::goSetupResultInvalidCurveSurface(ResultEntry *entry) +void PartGui::goSetupResultInvalidCurveSurface(ResultEntry* entry) { goSetupResultTypedSelection(entry, entry->shape, TopAbs_EDGE); goSetupResultBoundingBox(entry); } -void PartGui::goSetupResultInvalidSameParameterFlag(ResultEntry *entry) +void PartGui::goSetupResultInvalidSameParameterFlag(ResultEntry* entry) { goSetupResultTypedSelection(entry, entry->shape, TopAbs_EDGE); goSetupResultBoundingBox(entry); } -void PartGui::goSetupResultUnorientableShapeFace(ResultEntry *entry) +void PartGui::goSetupResultUnorientableShapeFace(ResultEntry* entry) { goSetupResultTypedSelection(entry, entry->shape, TopAbs_FACE); goSetupResultBoundingBox(entry); @@ -1058,10 +1154,19 @@ void PartGui::goSetupResultUnorientableShapeFace(ResultEntry *entry) //////////////////////////////////////////////////////////////////////////////////////////////// TaskCheckGeometryDialog::TaskCheckGeometryDialog() - : widget(nullptr), contentLabel(nullptr), okBtn(nullptr), settingsBtn(nullptr), resultsBtn(nullptr) + : widget(nullptr) + , contentLabel(nullptr) + , okBtn(nullptr) + , settingsBtn(nullptr) + , resultsBtn(nullptr) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); bool expandShapeContent = group->GetBool("ExpandShapeContent", false); this->setButtonPosition(TaskDialog::South); @@ -1069,82 +1174,111 @@ TaskCheckGeometryDialog::TaskCheckGeometryDialog() taskbox = new Gui::TaskView::TaskBox( Gui::BitmapFactory().pixmap("Part_CheckGeometry"), - widget->windowTitle(), true, nullptr); + widget->windowTitle(), + true, + nullptr + ); taskbox->groupLayout()->addWidget(widget); Content.push_back(taskbox); contentLabel = new QTextEdit(); contentLabel->setText(widget->getShapeContentString()); - shapeContentBox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("Part_CheckGeometry"), - tr("Shape Content"), true, nullptr); + shapeContentBox = new Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("Part_CheckGeometry"), + tr("Shape Content"), + true, + nullptr + ); shapeContentBox->groupLayout()->addWidget(contentLabel); - if (!expandShapeContent){ + if (!expandShapeContent) { shapeContentBox->hideGroupBox(); } Content.push_back(shapeContentBox); - settingsBox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("Part_CheckGeometry"), - tr("Settings"), true, nullptr); + settingsBox = new Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("Part_CheckGeometry"), + tr("Settings"), + true, + nullptr + ); Content.push_back(settingsBox); autoRunCheckBox = new QCheckBox(); autoRunCheckBox->setText(tr("Skip this settings page")); autoRunCheckBox->setToolTip( tr("Skip this settings page and run the geometry check automatically") - + QStringLiteral("\n") - + tr("Default: false")); + + QStringLiteral("\n") + tr("Default: false") + ); autoRunCheckBox->setChecked(group->GetBool("AutoRun", false)); - connect(autoRunCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onAutoRunCheckBoxToggled); + connect(autoRunCheckBox, &QCheckBox::toggled, this, &TaskCheckGeometryDialog::onAutoRunCheckBoxToggled); settingsBox->groupLayout()->addWidget(autoRunCheckBox); runBOPCheckBox = new QCheckBox(); runBOPCheckBox->setText(tr("Run boolean operation check")); - runBOPCheckBox->setToolTip(tr( - "Extra boolean operations check that can sometimes find errors that\n" - "the standard BRep geometry check misses. These errors do not always\n" - "mean the checked object is unusable. Default: false")); + runBOPCheckBox->setToolTip( + tr("Extra boolean operations check that can sometimes find errors that\n" + "the standard BRep geometry check misses. These errors do not always\n" + "mean the checked object is unusable. Default: false") + ); runBOPCheckBox->setChecked(group->GetBool("RunBOPCheck", false)); - connect(runBOPCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onRunBOPCheckBoxToggled); + connect(runBOPCheckBox, &QCheckBox::toggled, this, &TaskCheckGeometryDialog::onRunBOPCheckBoxToggled); settingsBox->groupLayout()->addWidget(runBOPCheckBox); runSingleThreadedCheckBox = new QCheckBox(); runSingleThreadedCheckBox->setText(tr("Single-threaded")); - runSingleThreadedCheckBox->setToolTip(tr( - "Run the geometry check in a single thread. This is slower,\n" - "but more stable. Default: false")); + runSingleThreadedCheckBox->setToolTip( + tr("Run the geometry check in a single thread. This is slower,\n" + "but more stable. Default: false") + ); runSingleThreadedCheckBox->setChecked(group->GetBool("RunSingleThreaded", false)); - connect(runSingleThreadedCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onRunSingleThreadedCheckBoxToggled); + connect( + runSingleThreadedCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onRunSingleThreadedCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(runSingleThreadedCheckBox); logErrorsCheckBox = new QCheckBox(); logErrorsCheckBox->setText(tr("Log errors")); logErrorsCheckBox->setToolTip(tr("Log errors to report view. Default: true")); logErrorsCheckBox->setChecked(group->GetBool("LogErrors", true)); - connect(logErrorsCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onLogErrorsCheckBoxToggled); + connect( + logErrorsCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onLogErrorsCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(logErrorsCheckBox); expandShapeContentCheckBox = new QCheckBox(); expandShapeContentCheckBox->setText(tr("Expand shape content")); - expandShapeContentCheckBox->setToolTip(tr( - "Expand shape content. Changes will take effect next time you use \n" - "the check geometry tool. Default: false")); + expandShapeContentCheckBox->setToolTip( + tr("Expand shape content. Changes will take effect next time you use \n" + "the check geometry tool. Default: false") + ); expandShapeContentCheckBox->setChecked(group->GetBool("ExpandShapeContent", false)); - connect(expandShapeContentCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onExpandShapeContentCheckBoxToggled); + connect( + expandShapeContentCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onExpandShapeContentCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(expandShapeContentCheckBox); advancedShapeContentCheckBox = new QCheckBox(); advancedShapeContentCheckBox->setText(tr("Advanced shape content")); - advancedShapeContentCheckBox->setToolTip(tr( - "Show advanced shape content. Changes will take effect next time you use \n" - "the check geometry tool. Default: false")); + advancedShapeContentCheckBox->setToolTip( + tr("Show advanced shape content. Changes will take effect next time you use \n" + "the check geometry tool. Default: false") + ); advancedShapeContentCheckBox->setChecked(group->GetBool("AdvancedShapeContent", true)); - connect(advancedShapeContentCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onAdvancedShapeContentCheckBoxToggled); + connect( + advancedShapeContentCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onAdvancedShapeContentCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(advancedShapeContentCheckBox); settingsBox->groupLayout()->addWidget(new QLabel(tr("\nIndividual boolean operation checks:"))); @@ -1153,78 +1287,115 @@ TaskCheckGeometryDialog::TaskCheckGeometryDialog() argumentTypeModeCheckBox->setText(QStringLiteral(" ") + tr("Bad type")); argumentTypeModeCheckBox->setToolTip(tr("Check for bad argument types. Default: true")); argumentTypeModeCheckBox->setChecked(group->GetBool("ArgumentTypeMode", true)); - connect(argumentTypeModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onArgumentTypeModeCheckBoxToggled); + connect( + argumentTypeModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onArgumentTypeModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(argumentTypeModeCheckBox); selfInterModeCheckBox = new QCheckBox(); selfInterModeCheckBox->setText(QStringLiteral(" ") + tr("Self-intersect")); selfInterModeCheckBox->setToolTip(tr("Check for self-intersections. Default: true")); selfInterModeCheckBox->setChecked(group->GetBool("SelfInterMode", true)); - connect(selfInterModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onSelfInterModeCheckBoxToggled); + connect( + selfInterModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onSelfInterModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(selfInterModeCheckBox); smallEdgeModeCheckBox = new QCheckBox(); smallEdgeModeCheckBox->setText(QStringLiteral(" ") + tr("Too small edge")); smallEdgeModeCheckBox->setToolTip(tr("Check for edges that are too small. Default: true")); smallEdgeModeCheckBox->setChecked(group->GetBool("SmallEdgeMode", true)); - connect(smallEdgeModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onSmallEdgeModeCheckBoxToggled); + connect( + smallEdgeModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onSmallEdgeModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(smallEdgeModeCheckBox); rebuildFaceModeCheckBox = new QCheckBox(); rebuildFaceModeCheckBox->setText(QStringLiteral(" ") + tr("Nonrecoverable face")); rebuildFaceModeCheckBox->setToolTip(tr("Check for nonrecoverable faces. Default: true")); rebuildFaceModeCheckBox->setChecked(group->GetBool("RebuildFaceMode", true)); - connect(rebuildFaceModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onRebuildFaceModeCheckBoxToggled); + connect( + rebuildFaceModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onRebuildFaceModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(rebuildFaceModeCheckBox); continuityModeCheckBox = new QCheckBox(); continuityModeCheckBox->setText(QStringLiteral(" ") + tr("Continuity")); continuityModeCheckBox->setToolTip(tr("Check for continuity. Default: true")); continuityModeCheckBox->setChecked(group->GetBool("ContinuityMode", true)); - connect(continuityModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onContinuityModeCheckBoxToggled); + connect( + continuityModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onContinuityModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(continuityModeCheckBox); tangentModeCheckBox = new QCheckBox(); tangentModeCheckBox->setText(QStringLiteral(" ") + tr("Incompatibility of face")); tangentModeCheckBox->setToolTip(tr("Check for incompatible faces. Default: true")); tangentModeCheckBox->setChecked(group->GetBool("TangentMode", true)); - connect(tangentModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onTangentModeCheckBoxToggled); + connect( + tangentModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onTangentModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(tangentModeCheckBox); mergeVertexModeCheckBox = new QCheckBox(); mergeVertexModeCheckBox->setText(QStringLiteral(" ") + tr("Incompatibility of vertex")); mergeVertexModeCheckBox->setToolTip(tr("Check for incompatible vertices. Default: true")); mergeVertexModeCheckBox->setChecked(group->GetBool("MergeVertexMode", true)); - connect(mergeVertexModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onMergeVertexModeCheckBoxToggled); + connect( + mergeVertexModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onMergeVertexModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(mergeVertexModeCheckBox); mergeEdgeModeCheckBox = new QCheckBox(); mergeEdgeModeCheckBox->setText(QStringLiteral(" ") + tr("Incompatibility of edge")); mergeEdgeModeCheckBox->setToolTip(tr("Check for incompatible edges. Default: true")); mergeEdgeModeCheckBox->setChecked(group->GetBool("MergeEdgeMode", true)); - connect(mergeEdgeModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onMergeEdgeModeCheckBoxToggled); + connect( + mergeEdgeModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onMergeEdgeModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(mergeEdgeModeCheckBox); curveOnSurfaceModeCheckBox = new QCheckBox(); curveOnSurfaceModeCheckBox->setText(QStringLiteral(" ") + tr("Invalid curve on surface")); curveOnSurfaceModeCheckBox->setToolTip(tr("Check for invalid curves on surfaces. Default: true")); curveOnSurfaceModeCheckBox->setChecked(group->GetBool("CurveOnSurfaceMode", true)); - connect(curveOnSurfaceModeCheckBox, &QCheckBox::toggled, - this, &TaskCheckGeometryDialog::onCurveOnSurfaceModeCheckBoxToggled); + connect( + curveOnSurfaceModeCheckBox, + &QCheckBox::toggled, + this, + &TaskCheckGeometryDialog::onCurveOnSurfaceModeCheckBoxToggled + ); settingsBox->groupLayout()->addWidget(curveOnSurfaceModeCheckBox); - if (group->GetBool("AutoRun",false)){ + if (group->GetBool("AutoRun", false)) { settingsBox->hide(); widget->goCheck(); contentLabel->setText(widget->getShapeContentString()); - } else { + } + else { taskbox->hide(); shapeContentBox->hide(); } @@ -1237,11 +1408,11 @@ bool TaskCheckGeometryDialog::accept() shapeContentBox->show(); taskbox->show(); widget->goCheck(); - QScrollBar *v = contentLabel->verticalScrollBar(); - v->setValue(v->maximum()); //scroll to bottom - int curval = v->value(); //save position + QScrollBar* v = contentLabel->verticalScrollBar(); + v->setValue(v->maximum()); // scroll to bottom + int curval = v->value(); // save position contentLabel->setText(widget->getShapeContentString()); - v->setValue(curval+(v->maximum()-curval)/5); + v->setValue(curval + (v->maximum() - curval) / 5); return false; } @@ -1250,7 +1421,7 @@ bool TaskCheckGeometryDialog::reject() return true; } -void TaskCheckGeometryDialog::onClicked(QAbstractButton *btn) +void TaskCheckGeometryDialog::onClicked(QAbstractButton* btn) { /** when ok (run check) is clicked or when close is clicked * the appropriate accept() or reject() is called already @@ -1258,15 +1429,17 @@ void TaskCheckGeometryDialog::onClicked(QAbstractButton *btn) * ui elements */ - if(btn == okBtn){ + if (btn == okBtn) { settingsBtn->setEnabled(true); - } else if (btn == settingsBtn){ + } + else if (btn == settingsBtn) { settingsBtn->setEnabled(false); taskbox->hide(); shapeContentBox->hide(); settingsBox->show(); resultsBtn->setEnabled(true); - } else if (btn == resultsBtn){ + } + else if (btn == resultsBtn) { settingsBtn->setEnabled(true); taskbox->show(); shapeContentBox->show(); @@ -1279,138 +1452,217 @@ void TaskCheckGeometryDialog::modifyStandardButtons(QDialogButtonBox* box) { okBtn = box->button(QDialogButtonBox::Ok); okBtn->setText(tr("Run check")); - settingsBtn = box->addButton(tr("Settings"),QDialogButtonBox::ActionRole); - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); - if(!group->GetBool("AutoRun",false)) + settingsBtn = box->addButton(tr("Settings"), QDialogButtonBox::ActionRole); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); + if (!group->GetBool("AutoRun", false)) { settingsBtn->setEnabled(false); - resultsBtn = box->addButton(tr("Results"),QDialogButtonBox::ActionRole); + } + resultsBtn = box->addButton(tr("Results"), QDialogButtonBox::ActionRole); resultsBtn->setEnabled(false); connect(box, &QDialogButtonBox::clicked, this, &TaskCheckGeometryDialog::onClicked); } void TaskCheckGeometryDialog::onAutoRunCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("AutoRun", isOn); } void TaskCheckGeometryDialog::onRunBOPCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("RunBOPCheck", isOn); } void TaskCheckGeometryDialog::onRunSingleThreadedCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("RunSingleThreaded", isOn); } void TaskCheckGeometryDialog::onLogErrorsCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("LogErrors", isOn); } void TaskCheckGeometryDialog::onArgumentTypeModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("ArgumentTypeMode", isOn); } void TaskCheckGeometryDialog::onExpandShapeContentCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("ExpandShapeContent", isOn); } void TaskCheckGeometryDialog::onAdvancedShapeContentCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("AdvancedShapeContent", isOn); } void TaskCheckGeometryDialog::onSelfInterModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("SelfInterMode", isOn); } void TaskCheckGeometryDialog::onSmallEdgeModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("SmallEdgeMode", isOn); } void TaskCheckGeometryDialog::onRebuildFaceModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("RebuildFaceMode", isOn); } void TaskCheckGeometryDialog::onContinuityModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("ContinuityMode", isOn); } void TaskCheckGeometryDialog::onTangentModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("TangentMode", isOn); } void TaskCheckGeometryDialog::onMergeVertexModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("MergeVertexMode", isOn); } void TaskCheckGeometryDialog::onMergeEdgeModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("MergeEdgeMode", isOn); } void TaskCheckGeometryDialog::onCurveOnSurfaceModeCheckBoxToggled(bool isOn) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod")->GetGroup("Part")->GetGroup("CheckGeometry"); + ParameterGrp::handle group = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod") + ->GetGroup("Part") + ->GetGroup("CheckGeometry"); group->SetBool("CurveOnSurfaceMode", isOn); } TaskCheckGeometryDialog::~TaskCheckGeometryDialog() { - if (widget) - { - delete widget; - widget = nullptr; - } - if (contentLabel) - { - delete contentLabel; - contentLabel = nullptr; - } + if (widget) { + delete widget; + widget = nullptr; + } + if (contentLabel) { + delete contentLabel; + contentLabel = nullptr; + } } //////////////////////////////////////////////////////////////////////////////////////////////// -BOPProgressIndicator::BOPProgressIndicator (const QString& title, QWidget* parent) +BOPProgressIndicator::BOPProgressIndicator(const QString& title, QWidget* parent) { steps = 0; canceled = false; @@ -1420,16 +1672,15 @@ BOPProgressIndicator::BOPProgressIndicator (const QString& title, QWidget* paren myProgress->setAttribute(Qt::WA_DeleteOnClose); } -BOPProgressIndicator::~BOPProgressIndicator () +BOPProgressIndicator::~BOPProgressIndicator() { myProgress->close(); } -void BOPProgressIndicator::Show (const Message_ProgressScope& theScope, - const Standard_Boolean isForce) +void BOPProgressIndicator::Show(const Message_ProgressScope& theScope, const Standard_Boolean isForce) { - Standard_CString aName = theScope.Name(); //current step - myProgress->setLabelText (QString::fromUtf8(aName)); + Standard_CString aName = theScope.Name(); // current step + myProgress->setLabelText(QString::fromUtf8(aName)); if (isForce) { myProgress->show(); @@ -1451,15 +1702,16 @@ void BOPProgressIndicator::Reset() Standard_Boolean BOPProgressIndicator::UserBreak() { - QThread *currentThread = QThread::currentThread(); + QThread* currentThread = QThread::currentThread(); if (currentThread == myProgress->thread()) { // this is needed to check the status outside BOPAlgo_ArgumentAnalyzer // // Hint: We must make sure to do this only when calling from the GUI // thread because when calling it from a worker thread the thrown // exception isn't handled anywhere and thus std::terminate is called - if (canceled) + if (canceled) { return Standard_True; + } // it suffices to update only every second // to avoid to unnecessarily process events diff --git a/src/Mod/Part/Gui/TaskCheckGeometry.h b/src/Mod/Part/Gui/TaskCheckGeometry.h index 55307fa67b..01fec0a8a9 100644 --- a/src/Mod/Part/Gui/TaskCheckGeometry.h +++ b/src/Mod/Part/Gui/TaskCheckGeometry.h @@ -45,7 +45,8 @@ class QCheckBox; class QTextEdit; class QTreeView; -namespace PartGui { +namespace PartGui +{ class ResultEntry { @@ -54,93 +55,108 @@ public: ~ResultEntry(); void buildEntryName(); - TopoDS_Shape shape;//invisible + TopoDS_Shape shape; // invisible QString name; QString type; QString error; - SoSeparator *viewProviderRoot; - SoSeparator *boxSep; - SoSwitch *boxSwitch; - ResultEntry *parent; - QList children; + SoSeparator* viewProviderRoot; + SoSeparator* boxSep; + SoSwitch* boxSwitch; + ResultEntry* parent; + QList children; QStringList selectionStrings; }; -QString buildSelectionName(const ResultEntry *entry, const TopoDS_Shape &shape); -void goSetupResultTypedSelection(ResultEntry *entry, const TopoDS_Shape &shape, TopAbs_ShapeEnum type); -void goSetupResultBoundingBox(ResultEntry *entry); -void goSetupResultShellNotClosed(ResultEntry *entry); -void goSetupResultWireNotClosed(ResultEntry *entry); -void goSetupResultInvalidPointCurve(ResultEntry *entry); -void goSetupResultIntersectingWires(ResultEntry *entry); -void goSetupResultInvalidCurveSurface(ResultEntry *entry); -void goSetupResultInvalidSameParameterFlag(ResultEntry *entry); -void goSetupResultUnorientableShapeFace(ResultEntry *entry); +QString buildSelectionName(const ResultEntry* entry, const TopoDS_Shape& shape); +void goSetupResultTypedSelection(ResultEntry* entry, const TopoDS_Shape& shape, TopAbs_ShapeEnum type); +void goSetupResultBoundingBox(ResultEntry* entry); +void goSetupResultShellNotClosed(ResultEntry* entry); +void goSetupResultWireNotClosed(ResultEntry* entry); +void goSetupResultInvalidPointCurve(ResultEntry* entry); +void goSetupResultIntersectingWires(ResultEntry* entry); +void goSetupResultInvalidCurveSurface(ResultEntry* entry); +void goSetupResultInvalidSameParameterFlag(ResultEntry* entry); +void goSetupResultUnorientableShapeFace(ResultEntry* entry); -using ResultFunction = std::function; +using ResultFunction = std::function; using FunctionMapType = std::tuple; -class ResultModel : public QAbstractItemModel +class ResultModel: public QAbstractItemModel { Q_OBJECT public: - explicit ResultModel(QObject *parent = nullptr); + explicit ResultModel(QObject* parent = nullptr); ~ResultModel() override; - QModelIndex index(int row, int column, const QModelIndex &parent) const override; - QModelIndex parent(const QModelIndex &child) const override; - int rowCount(const QModelIndex &parent) const override; - int columnCount(const QModelIndex &parent) const override; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QModelIndex index(int row, int column, const QModelIndex& parent) const override; + QModelIndex parent(const QModelIndex& child) const override; + int rowCount(const QModelIndex& parent) const override; + int columnCount(const QModelIndex& parent) const override; + QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; -// virtual Qt::ItemFlags flags (const QModelIndex &index) const; + // virtual Qt::ItemFlags flags (const QModelIndex &index) const; + + void setResults(ResultEntry* resultsIn); + ResultEntry* getEntry(const QModelIndex& index); - void setResults(ResultEntry *resultsIn); - ResultEntry* getEntry(const QModelIndex &index); private: - ResultEntry* nodeFromIndex(const QModelIndex &index) const; - ResultEntry *root; + ResultEntry* nodeFromIndex(const QModelIndex& index) const; + ResultEntry* root; }; -class TaskCheckGeometryResults : public QWidget +class TaskCheckGeometryResults: public QWidget { Q_OBJECT public: - explicit TaskCheckGeometryResults(QWidget *parent = nullptr); + explicit TaskCheckGeometryResults(QWidget* parent = nullptr); ~TaskCheckGeometryResults() override; QString getShapeContentString(); void goCheck(); private Q_SLOTS: - void currentRowChanged (const QModelIndex ¤t, const QModelIndex &previous); + void currentRowChanged(const QModelIndex& current, const QModelIndex& previous); private: void setupInterface(); QStringList reportViewStrings; void generateReport(); - void recursiveCheck(const BRepCheck_Analyzer &shapeCheck, const TopoDS_Shape &shape, - ResultEntry *parent); - void checkSub(const BRepCheck_Analyzer &shapeCheck, const TopoDS_Shape &shape, - const TopAbs_ShapeEnum subType, ResultEntry *parent); - void dispatchError(ResultEntry *entry, const BRepCheck_Status &stat); - bool split(QString &input, QString &doc, QString &object, QString &sub); + void recursiveCheck( + const BRepCheck_Analyzer& shapeCheck, + const TopoDS_Shape& shape, + ResultEntry* parent + ); + void checkSub( + const BRepCheck_Analyzer& shapeCheck, + const TopoDS_Shape& shape, + const TopAbs_ShapeEnum subType, + ResultEntry* parent + ); + void dispatchError(ResultEntry* entry, const BRepCheck_Status& stat); + bool split(QString& input, QString& doc, QString& object, QString& sub); void setupFunctionMap(); - int goBOPSingleCheck(const TopoDS_Shape &shapeIn, ResultEntry *theRoot, const QString &baseName, - const Message_ProgressScope& theScope); + int goBOPSingleCheck( + const TopoDS_Shape& shapeIn, + ResultEntry* theRoot, + const QString& baseName, + const Message_ProgressScope& theScope + ); - void buildShapeContent(App::DocumentObject *pObject, const QString &baseName, const TopoDS_Shape &shape); - ResultModel *model; - QTreeView *treeView; - QLabel *message; + void buildShapeContent( + App::DocumentObject* pObject, + const QString& baseName, + const TopoDS_Shape& shape + ); + ResultModel* model; + QTreeView* treeView; + QLabel* message; TopTools_MapOfShape checkedMap; - SoSeparator *currentSeparator; + SoSeparator* currentSeparator; std::vector functionMap; std::string shapeContentString; - }; -class TaskCheckGeometryDialog : public Gui::TaskView::TaskDialog +class TaskCheckGeometryDialog: public Gui::TaskView::TaskDialog { Q_OBJECT public: @@ -148,10 +164,17 @@ public: ~TaskCheckGeometryDialog() override; QDialogButtonBox::StandardButtons getStandardButtons() const override - {return QDialogButtonBox::Ok | QDialogButtonBox::Close;} + { + return QDialogButtonBox::Ok | QDialogButtonBox::Close; + } bool isAllowedAlterDocument() const override - {return false;} - bool needsFullSpace() const override {return true;} + { + return false; + } + bool needsFullSpace() const override + { + return true; + } private: void onRunBOPCheckBoxToggled(bool isOn); @@ -176,38 +199,37 @@ private: Gui::TaskView::TaskBox* taskbox; Gui::TaskView::TaskBox* shapeContentBox; Gui::TaskView::TaskBox* settingsBox; - QTextEdit *contentLabel; - QCheckBox *autoRunCheckBox; - QCheckBox *runBOPCheckBox; - QCheckBox *runSingleThreadedCheckBox; - QCheckBox *logErrorsCheckBox; - QCheckBox *expandShapeContentCheckBox; - QCheckBox *advancedShapeContentCheckBox; - QCheckBox *argumentTypeModeCheckBox; - QCheckBox *selfInterModeCheckBox; - QCheckBox *smallEdgeModeCheckBox; - QCheckBox *rebuildFaceModeCheckBox; - QCheckBox *continuityModeCheckBox; - QCheckBox *tangentModeCheckBox; - QCheckBox *mergeVertexModeCheckBox; - QCheckBox *mergeEdgeModeCheckBox; - QCheckBox *curveOnSurfaceModeCheckBox; + QTextEdit* contentLabel; + QCheckBox* autoRunCheckBox; + QCheckBox* runBOPCheckBox; + QCheckBox* runSingleThreadedCheckBox; + QCheckBox* logErrorsCheckBox; + QCheckBox* expandShapeContentCheckBox; + QCheckBox* advancedShapeContentCheckBox; + QCheckBox* argumentTypeModeCheckBox; + QCheckBox* selfInterModeCheckBox; + QCheckBox* smallEdgeModeCheckBox; + QCheckBox* rebuildFaceModeCheckBox; + QCheckBox* continuityModeCheckBox; + QCheckBox* tangentModeCheckBox; + QCheckBox* mergeVertexModeCheckBox; + QCheckBox* mergeEdgeModeCheckBox; + QCheckBox* curveOnSurfaceModeCheckBox; bool accept() override; bool reject() override; void modifyStandardButtons(QDialogButtonBox*) override; - QPushButton *okBtn; - QPushButton *settingsBtn; - QPushButton *resultsBtn; + QPushButton* okBtn; + QPushButton* settingsBtn; + QPushButton* resultsBtn; }; -class BOPProgressIndicator : public Message_ProgressIndicator +class BOPProgressIndicator: public Message_ProgressIndicator { public: - BOPProgressIndicator (const QString &title, QWidget* parent); - ~BOPProgressIndicator () override; + BOPProgressIndicator(const QString& title, QWidget* parent); + ~BOPProgressIndicator() override; - void Show (const Message_ProgressScope& theScope, - const Standard_Boolean isForce) override; + void Show(const Message_ProgressScope& theScope, const Standard_Boolean isForce) override; void Reset() override; Standard_Boolean UserBreak() override; @@ -218,6 +240,6 @@ private: QElapsedTimer time; QProgressDialog* myProgress; }; -} +} // namespace PartGui -#endif // TASKCHECKGEOMETRY_H +#endif // TASKCHECKGEOMETRY_H diff --git a/src/Mod/Part/Gui/TaskFaceAppearances.cpp b/src/Mod/Part/Gui/TaskFaceAppearances.cpp index 5b77f3d918..1fb6e33f75 100644 --- a/src/Mod/Part/Gui/TaskFaceAppearances.cpp +++ b/src/Mod/Part/Gui/TaskFaceAppearances.cpp @@ -23,24 +23,24 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -67,26 +67,30 @@ using namespace PartGui; namespace sp = std::placeholders; -namespace PartGui { - class FaceSelection : public Gui::SelectionFilterGate +namespace PartGui +{ +class FaceSelection: public Gui::SelectionFilterGate +{ + const App::DocumentObject* object; + +public: + explicit FaceSelection(const App::DocumentObject* obj) + : Gui::SelectionFilterGate() + , object(obj) + {} + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override { - const App::DocumentObject* object; - public: - explicit FaceSelection(const App::DocumentObject* obj) - : Gui::SelectionFilterGate(), object(obj) - { + if (pObj != this->object) { + return false; } - bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override - { - if (pObj != this->object) - return false; - if (Base::Tools::isNullOrEmpty(sSubName)) - return false; - std::string element(sSubName); - return element.substr(0, 4) == "Face"; + if (Base::Tools::isNullOrEmpty(sSubName)) { + return false; } - }; -} + std::string element(sSubName); + return element.substr(0, 4) == "Face"; + } +}; +} // namespace PartGui class FaceAppearances::Private { @@ -104,7 +108,10 @@ public: Connection connectDelObj; Connection connectUndoDoc; - explicit Private(ViewProviderPartExt* vp) : ui(new Ui_TaskFaceAppearances()), view(nullptr), vp(vp) + explicit Private(ViewProviderPartExt* vp) + : ui(new Ui_TaskFaceAppearances()) + , view(nullptr) + , vp(vp) { obj = vp->getObject(); doc = Gui::Application::Instance->getDocument(obj->getDocument()); @@ -150,22 +157,26 @@ public: const SoDetail* detail = pick->getDetail(); if (detail && detail->isOfType(SoFaceDetail::getClassTypeId())) { int index = static_cast(detail)->getPartIndex(); - if (faceIndex != index) + if (faceIndex != index) { return false; + } SbVec3f dir = viewer->getViewDirection(); const SbVec3f& nor = pick->getNormal(); - if (dir.dot(nor) > 0) - return false; // bottom side points to user + if (dir.dot(nor) > 0) { + return false; // bottom side points to user + } return true; } } return false; } - void addFacesToSelection(Gui::View3DInventorViewer* /*viewer*/, - const Gui::ViewVolumeProjection& proj, - const Base::Polygon2d& polygon, - const TopoDS_Shape& shape) + void addFacesToSelection( + Gui::View3DInventorViewer* /*viewer*/, + const Gui::ViewVolumeProjection& proj, + const Base::Polygon2d& polygon, + const TopoDS_Shape& shape + ) { try { TopTools_IndexedMapOfShape M; @@ -188,7 +199,11 @@ public: if (polygon.Contains(Base::Vector2d(pt2d.x, pt2d.y))) { std::stringstream str; str << "Face" << k; - Gui::Selection().addSelection(appdoc->getName(), obj->getNameInDocument(), str.str().c_str()); + Gui::Selection().addSelection( + appdoc->getName(), + obj->getNameInDocument(), + str.str().c_str() + ); break; } xp_vertex.Next(); @@ -218,8 +233,9 @@ public: polygon.Add(Base::Vector2d(pt2[0], pt1[1])); } else { - for (const auto& it : picked) + for (const auto& it : picked) { polygon.Add(Base::Vector2d(it[0], it[1])); + } } FaceAppearances* self = static_cast(ud); @@ -252,22 +268,28 @@ FaceAppearances::FaceAppearances(ViewProviderPartExt* vp, QWidget* parent) FaceSelection* gate = new FaceSelection(d->vp->getObject()); Gui::Selection().addSelectionGate(gate); - //NOLINTBEGIN - d->connectDelDoc = Gui::Application::Instance->signalDeleteDocument.connect(std::bind - (&FaceAppearances::slotDeleteDocument, this, sp::_1)); - d->connectDelObj = Gui::Application::Instance->signalDeletedObject.connect(std::bind - (&FaceAppearances::slotDeleteObject, this, sp::_1)); - d->connectUndoDoc = d->doc->signalUndoDocument.connect(std::bind - (&FaceAppearances::slotUndoDocument, this, sp::_1)); - //NOLINTEND + // NOLINTBEGIN + d->connectDelDoc = Gui::Application::Instance->signalDeleteDocument.connect( + std::bind(&FaceAppearances::slotDeleteDocument, this, sp::_1) + ); + d->connectDelObj = Gui::Application::Instance->signalDeletedObject.connect( + std::bind(&FaceAppearances::slotDeleteObject, this, sp::_1) + ); + d->connectUndoDoc = d->doc->signalUndoDocument.connect( + std::bind(&FaceAppearances::slotUndoDocument, this, sp::_1) + ); + // NOLINTEND } FaceAppearances::~FaceAppearances() { if (d->view) { d->view->stopSelection(); - d->view->removeEventCallback(SoMouseButtonEvent::getClassTypeId(), - Private::selectionCallback, this); + d->view->removeEventCallback( + SoMouseButtonEvent::getClassTypeId(), + Private::selectionCallback, + this + ); d->view->setSelectionEnabled(true); } Gui::Selection().rmvSelectionGate(); @@ -301,34 +323,43 @@ void FaceAppearances::slotUndoDocument(const Gui::Document& Doc) void FaceAppearances::slotDeleteDocument(const Gui::Document& Doc) { - if (d->doc == &Doc) + if (d->doc == &Doc) { Gui::Control().closeDialog(); + } } void FaceAppearances::slotDeleteObject(const Gui::ViewProvider& obj) { - if (d->vp == &obj) + if (d->vp == &obj) { Gui::Control().closeDialog(); + } } void FaceAppearances::onBoxSelectionToggled(bool checked) { - Gui::View3DInventor* view = qobject_cast(Gui::getMainWindow()->activeWindow()); + Gui::View3DInventor* view = qobject_cast( + Gui::getMainWindow()->activeWindow() + ); // toggle the button state and feature d->boxSelection = checked; if (!checked) { // end box selection mode - if (view) + if (view) { view->getViewer()->stopSelection(); + } } if (view && checked) { Gui::View3DInventorViewer* viewer = view->getViewer(); if (!viewer->isSelecting()) { viewer->startSelection(Gui::View3DInventorViewer::Rubberband); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), Private::selectionCallback, this); - // avoid that the selection node handles the event otherwise the callback function won't be - // called immediately + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + Private::selectionCallback, + this + ); + // avoid that the selection node handles the event otherwise the callback function won't + // be called immediately viewer->setSelectionEnabled(false); d->view = viewer; } @@ -357,8 +388,9 @@ void FaceAppearances::onMaterialSelected(const std::shared_ptrindex.size(); for (int it : d->index) { faces += QString::number(it + 1); - if (--size > 0) + if (--size > 0) { faces += QStringLiteral(","); + } } faces += QStringLiteral("]"); @@ -427,7 +460,8 @@ int FaceAppearances::getFirstIndex() const } /** - * Opens a dialog that allows one to modify the 'ShapeMaterial' property of all selected view providers. + * Opens a dialog that allows one to modify the 'ShapeMaterial' property of all selected view + * providers. */ void FaceAppearances::onButtonCustomAppearanceClicked() { @@ -496,8 +530,7 @@ void TaskFaceAppearances::open() } void TaskFaceAppearances::clicked(int) -{ -} +{} bool TaskFaceAppearances::accept() { diff --git a/src/Mod/Part/Gui/TaskFaceAppearances.h b/src/Mod/Part/Gui/TaskFaceAppearances.h index aa131327d9..cf1733d695 100644 --- a/src/Mod/Part/Gui/TaskFaceAppearances.h +++ b/src/Mod/Part/Gui/TaskFaceAppearances.h @@ -28,20 +28,23 @@ #include #include -namespace Gui { - class Document; - class ViewProvider; +namespace Gui +{ +class Document; +class ViewProvider; +} // namespace Gui + +namespace Materials +{ +class Material; } -namespace Materials { - class Material; -} - -namespace PartGui { +namespace PartGui +{ class ViewProviderPartExt; -class FaceAppearances : public QWidget, public Gui::SelectionObserver +class FaceAppearances: public QWidget, public Gui::SelectionObserver { Q_OBJECT @@ -62,7 +65,7 @@ private: protected: void onSelectionChanged(const Gui::SelectionChanges& msg) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void slotUndoDocument(const Gui::Document& Doc); void slotDeleteDocument(const Gui::Document&); void slotDeleteObject(const Gui::ViewProvider&); @@ -74,7 +77,7 @@ private: Private* d; }; -class TaskFaceAppearances : public Gui::TaskView::TaskDialog +class TaskFaceAppearances: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -89,12 +92,14 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } private: FaceAppearances* widget; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_TASKSETCOLORS_H +#endif // PARTGUI_TASKSETCOLORS_H diff --git a/src/Mod/Part/Gui/TaskLoft.cpp b/src/Mod/Part/Gui/TaskLoft.cpp index cc8331c3db..cb24c68a2e 100644 --- a/src/Mod/Part/Gui/TaskLoft.cpp +++ b/src/Mod/Part/Gui/TaskLoft.cpp @@ -23,14 +23,14 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -63,7 +63,7 @@ public: /* TRANSLATOR PartGui::LoftWidget */ LoftWidget::LoftWidget(QWidget* parent) - : d(new Private()) + : d(new Private()) { Q_UNUSED(parent); Gui::Command::runCommand(Gui::Command::App, "from FreeCAD import Base"); @@ -92,19 +92,25 @@ void LoftWidget::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); - if (!activeGui) + if (!activeGui) { return; + } d->document = activeDoc->getName(); std::vector objs = activeDoc->getObjectsOfType(); for (auto obj : objs) { - Part::TopoShape topoShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { continue; } TopoDS_Shape shape = topoShape.getShape(); - if (shape.IsNull()) continue; + if (shape.IsNull()) { + continue; + } // also allow compounds with a single face, wire or vertex or // if there are only edges building one wire @@ -113,7 +119,7 @@ void LoftWidget::findShapes() Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); TopoDS_Iterator it(shape); - int numChilds=0; + int numChilds = 0; TopoDS_Shape child; for (; it.More(); it.Next(), numChilds++) { if (!it.Value().IsNull()) { @@ -130,18 +136,21 @@ void LoftWidget::findShapes() } // or all children are edges else if (hEdges->Length() == numChilds) { - ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, - Precision::Confusion(), Standard_False, hWires); - if (hWires->Length() == 1) + ShapeAnalysis_FreeBounds::ConnectEdgesToWires( + hEdges, + Precision::Confusion(), + Standard_False, + hWires + ); + if (hWires->Length() == 1) { shape = hWires->Value(1); + } } } - if (!shape.Infinite() && - (shape.ShapeType() == TopAbs_FACE || - shape.ShapeType() == TopAbs_WIRE || - shape.ShapeType() == TopAbs_EDGE || - shape.ShapeType() == TopAbs_VERTEX)) { + if (!shape.Infinite() + && (shape.ShapeType() == TopAbs_FACE || shape.ShapeType() == TopAbs_WIRE + || shape.ShapeType() == TopAbs_EDGE || shape.ShapeType() == TopAbs_VERTEX)) { QString label = QString::fromUtf8(obj->Label.getValue()); QString name = QString::fromLatin1(obj->getNameInDocument()); QTreeWidgetItem* child = new QTreeWidgetItem(); @@ -149,7 +158,9 @@ void LoftWidget::findShapes() child->setToolTip(0, label); child->setData(0, Qt::UserRole, name); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) child->setIcon(0, vp->getIcon()); + if (vp) { + child->setIcon(0, vp->getIcon()); + } d->ui.selector->availableTreeWidget()->addTopLevelItem(child); } } @@ -158,29 +169,39 @@ void LoftWidget::findShapes() bool LoftWidget::accept() { QString list, solid, ruled, closed; - if (d->ui.checkSolid->isChecked()) + if (d->ui.checkSolid->isChecked()) { solid = QStringLiteral("True"); - else + } + else { solid = QStringLiteral("False"); + } - if (d->ui.checkRuledSurface->isChecked()) + if (d->ui.checkRuledSurface->isChecked()) { ruled = QStringLiteral("True"); - else + } + else { ruled = QStringLiteral("False"); + } - if (d->ui.checkClosed->isChecked()) + if (d->ui.checkClosed->isChecked()) { closed = QStringLiteral("True"); - else + } + else { closed = QStringLiteral("False"); + } QTextStream str(&list); int count = d->ui.selector->selectedTreeWidget()->topLevelItemCount(); if (count < 2) { - QMessageBox::critical(this, tr("Too few elements"), tr("At least 2 vertices, edges, wires, or faces are required.")); + QMessageBox::critical( + this, + tr("Too few elements"), + tr("At least 2 vertices, edges, wires, or faces are required.") + ); return false; } - for (int i=0; iui.selector->selectedTreeWidget()->topLevelItem(i); QString name = child->data(0, Qt::UserRole).toString(); str << "App.getDocument('" << d->document.c_str() << "')." << name << ", "; @@ -189,16 +210,18 @@ bool LoftWidget::accept() try { QString cmd; cmd = QStringLiteral( - "App.getDocument('%5').addObject('Part::Loft','Loft')\n" - "App.getDocument('%5').ActiveObject.Sections=[%1]\n" - "App.getDocument('%5').ActiveObject.Solid=%2\n" - "App.getDocument('%5').ActiveObject.Ruled=%3\n" - "App.getDocument('%5').ActiveObject.Closed=%4\n" - ).arg(list, solid, ruled, closed, QString::fromLatin1(d->document.c_str())); + "App.getDocument('%5').addObject('Part::Loft','Loft')\n" + "App.getDocument('%5').ActiveObject.Sections=[%1]\n" + "App.getDocument('%5').ActiveObject.Solid=%2\n" + "App.getDocument('%5').ActiveObject.Ruled=%3\n" + "App.getDocument('%5').ActiveObject.Closed=%4\n" + ) + .arg(list, solid, ruled, closed, QString::fromLatin1(d->document.c_str())); Gui::Document* doc = Gui::Application::Instance->getDocument(d->document.c_str()); - if (!doc) + if (!doc) { throw Base::RuntimeError("Document doesn't exist anymore"); + } doc->openCommand(QT_TRANSLATE_NOOP("Command", "Loft")); Gui::Command::runCommand(Gui::Command::App, cmd.toLatin1()); doc->getDocument()->recompute(); @@ -211,7 +234,11 @@ bool LoftWidget::accept() doc->commitCommand(); } catch (const Base::Exception& e) { - QMessageBox::warning(this, tr("Input error"), QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + this, + tr("Input error"), + QCoreApplication::translate("Exception", e.what()) + ); return false; } @@ -226,16 +253,20 @@ bool LoftWidget::reject() void LoftWidget::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { if (previous) { - Gui::Selection().rmvSelection(d->document.c_str(), - (const char*)previous->data(0,Qt::UserRole).toByteArray()); + Gui::Selection().rmvSelection( + d->document.c_str(), + (const char*)previous->data(0, Qt::UserRole).toByteArray() + ); } if (current) { - Gui::Selection().addSelection(d->document.c_str(), - (const char*)current->data(0,Qt::UserRole).toByteArray()); + Gui::Selection().addSelection( + d->document.c_str(), + (const char*)current->data(0, Qt::UserRole).toByteArray() + ); } } -void LoftWidget::changeEvent(QEvent *e) +void LoftWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -257,12 +288,10 @@ TaskLoft::TaskLoft() TaskLoft::~TaskLoft() = default; void TaskLoft::open() -{ -} +{} void TaskLoft::clicked(int) -{ -} +{} bool TaskLoft::accept() { diff --git a/src/Mod/Part/Gui/TaskLoft.h b/src/Mod/Part/Gui/TaskLoft.h index 84edfb8a04..1c8924f1cc 100644 --- a/src/Mod/Part/Gui/TaskLoft.h +++ b/src/Mod/Part/Gui/TaskLoft.h @@ -31,9 +31,10 @@ class QTreeWidgetItem; -namespace PartGui { +namespace PartGui +{ -class LoftWidget : public QWidget +class LoftWidget: public QWidget { Q_OBJECT @@ -48,7 +49,7 @@ private Q_SLOTS: void onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*); private: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void findShapes(); private: @@ -56,7 +57,7 @@ private: Private* d; }; -class TaskLoft : public Gui::TaskView::TaskDialog +class TaskLoft: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -71,12 +72,14 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } private: LoftWidget* widget; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_TASKLOFT_H +#endif // PARTGUI_TASKLOFT_H diff --git a/src/Mod/Part/Gui/TaskOffset.cpp b/src/Mod/Part/Gui/TaskOffset.cpp index 6fd2846c36..39d4ba96ea 100644 --- a/src/Mod/Part/Gui/TaskOffset.cpp +++ b/src/Mod/Part/Gui/TaskOffset.cpp @@ -45,14 +45,14 @@ using namespace PartGui; class OffsetWidget::Private { public: - Ui_TaskOffset ui{}; - Part::Offset* offset{nullptr}; + Ui_TaskOffset ui {}; + Part::Offset* offset {nullptr}; }; /* TRANSLATOR PartGui::OffsetWidget */ OffsetWidget::OffsetWidget(Part::Offset* offset, QWidget* parent) - : d(new Private()) + : d(new Private()) { Q_UNUSED(parent); Gui::Command::runCommand(Gui::Command::App, "from FreeCAD import Base"); @@ -63,17 +63,17 @@ OffsetWidget::OffsetWidget(Part::Offset* offset, QWidget* parent) setupConnections(); d->ui.spinOffset->setUnit(Base::Unit::Length); - d->ui.spinOffset->setRange(-std::numeric_limits::max(), - std::numeric_limits::max()); + d->ui.spinOffset->setRange(-std::numeric_limits::max(), std::numeric_limits::max()); d->ui.spinOffset->setSingleStep(0.1); d->ui.facesButton->hide(); bool is_2d = d->offset->isDerivedFrom(); d->ui.selfIntersection->setVisible(!is_2d); - if(is_2d) - d->ui.modeType->removeItem(2);//remove Recto-Verso mode, not supported by 2d offset + if (is_2d) { + d->ui.modeType->removeItem(2); // remove Recto-Verso mode, not supported by 2d offset + } - //block signals to fill values read out from feature... + // block signals to fill values read out from feature... bool block = true; d->ui.fillOffset->blockSignals(block); d->ui.intersection->blockSignals(block); @@ -82,19 +82,21 @@ OffsetWidget::OffsetWidget(Part::Offset* offset, QWidget* parent) d->ui.joinType->blockSignals(block); d->ui.spinOffset->blockSignals(block); - //read values from feature + // read values from feature d->ui.spinOffset->setValue(d->offset->Value.getValue()); d->ui.fillOffset->setChecked(offset->Fill.getValue()); d->ui.intersection->setChecked(offset->Intersection.getValue()); d->ui.selfIntersection->setChecked(offset->SelfIntersection.getValue()); long mode = offset->Mode.getValue(); - if (mode >= 0 && mode < d->ui.modeType->count()) + if (mode >= 0 && mode < d->ui.modeType->count()) { d->ui.modeType->setCurrentIndex(mode); + } long join = offset->Join.getValue(); - if (join >= 0 && join < d->ui.joinType->count()) + if (join >= 0 && join < d->ui.joinType->count()) { d->ui.joinType->setCurrentIndex(join); + } - //unblock signals + // unblock signals block = false; d->ui.fillOffset->blockSignals(block); d->ui.intersection->blockSignals(block); @@ -139,43 +141,49 @@ Part::Offset* OffsetWidget::getObject() const void OffsetWidget::onSpinOffsetValueChanged(double val) { d->offset->Value.setValue(val); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->offset->getDocument()->recomputeFeature(d->offset); + } } void OffsetWidget::onModeTypeActivated(int val) { d->offset->Mode.setValue(val); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->offset->getDocument()->recomputeFeature(d->offset); + } } void OffsetWidget::onJoinTypeActivated(int val) { d->offset->Join.setValue((long)val); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->offset->getDocument()->recomputeFeature(d->offset); + } } void OffsetWidget::onIntersectionToggled(bool on) { d->offset->Intersection.setValue(on); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->offset->getDocument()->recomputeFeature(d->offset); + } } void OffsetWidget::onSelfIntersectionToggled(bool on) { d->offset->SelfIntersection.setValue(on); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->offset->getDocument()->recomputeFeature(d->offset); + } } void OffsetWidget::onFillOffsetToggled(bool on) { d->offset->Fill.setValue(on); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->offset->getDocument()->recomputeFeature(d->offset); + } } void OffsetWidget::onUpdateViewToggled(bool on) @@ -193,18 +201,31 @@ bool OffsetWidget::accept() d->ui.spinOffset->apply(); Gui::cmdAppObjectArgs(d->offset, "Mode = %d", d->ui.modeType->currentIndex()); Gui::cmdAppObjectArgs(d->offset, "Join = %d", d->ui.joinType->currentIndex()); - Gui::cmdAppObjectArgs(d->offset, "Intersection = %s", d->ui.intersection->isChecked() ? "True" : "False"); - Gui::cmdAppObjectArgs(d->offset, "SelfIntersection = %s", d->ui.selfIntersection->isChecked() ? "True" : "False"); + Gui::cmdAppObjectArgs( + d->offset, + "Intersection = %s", + d->ui.intersection->isChecked() ? "True" : "False" + ); + Gui::cmdAppObjectArgs( + d->offset, + "SelfIntersection = %s", + d->ui.selfIntersection->isChecked() ? "True" : "False" + ); Gui::cmdAppObjectArgs(d->offset, "Fill = %s", d->ui.fillOffset->isChecked() ? "True" : "False"); - Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()"); - if (!d->offset->isValid()) + Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); + if (!d->offset->isValid()) { throw Base::CADKernelError(d->offset->getStatusString()); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); + } + Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { - QMessageBox::warning(this, tr("Input error"), QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + this, + tr("Input error"), + QCoreApplication::translate("Exception", e.what()) + ); return false; } @@ -215,19 +236,19 @@ bool OffsetWidget::reject() { // get the support and Sketch App::DocumentObject* source = d->offset->Source.getValue(); - if (source){ + if (source) { Gui::Application::Instance->getViewProvider(source)->show(); } // roll back the done things Gui::Command::abortCommand(); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); + Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); Gui::Command::updateActive(); return true; } -void OffsetWidget::changeEvent(QEvent *e) +void OffsetWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -252,12 +273,10 @@ Part::Offset* TaskOffset::getObject() const } void TaskOffset::open() -{ -} +{} void TaskOffset::clicked(int) -{ -} +{} bool TaskOffset::accept() { diff --git a/src/Mod/Part/Gui/TaskOffset.h b/src/Mod/Part/Gui/TaskOffset.h index 3defbd7900..d3739b1b2b 100644 --- a/src/Mod/Part/Gui/TaskOffset.h +++ b/src/Mod/Part/Gui/TaskOffset.h @@ -29,10 +29,14 @@ #include #include -namespace Part { class Offset; } -namespace PartGui { +namespace Part +{ +class Offset; +} +namespace PartGui +{ -class OffsetWidget : public QWidget +class OffsetWidget: public QWidget { Q_OBJECT @@ -55,14 +59,14 @@ private: void onUpdateViewToggled(bool); private: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: class Private; Private* d; }; -class TaskOffset : public Gui::TaskView::TaskDialog +class TaskOffset: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -78,12 +82,14 @@ public: Part::Offset* getObject() const; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } private: OffsetWidget* widget; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_TASKOFFSET_H +#endif // PARTGUI_TASKOFFSET_H diff --git a/src/Mod/Part/Gui/TaskShapeBuilder.cpp b/src/Mod/Part/Gui/TaskShapeBuilder.cpp index 7238287f94..3284c50bd8 100644 --- a/src/Mod/Part/Gui/TaskShapeBuilder.cpp +++ b/src/Mod/Part/Gui/TaskShapeBuilder.cpp @@ -23,12 +23,12 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -52,40 +52,48 @@ using namespace PartGui; -namespace PartGui { - class ShapeSelection : public Gui::SelectionFilterGate +namespace PartGui +{ +class ShapeSelection: public Gui::SelectionFilterGate +{ +public: + enum Type { - public: - enum Type {VERTEX, EDGE, FACE, ALL}; - Type mode{ALL}; - ShapeSelection() - : Gui::SelectionFilterGate(nullPointer()) - { + VERTEX, + EDGE, + FACE, + ALL + }; + Type mode {ALL}; + ShapeSelection() + : Gui::SelectionFilterGate(nullPointer()) + {} + void setMode(Type mode) + { + this->mode = mode; + } + bool allow(App::Document*, App::DocumentObject* obj, const char* sSubName) override + { + if (!obj || !obj->isDerivedFrom()) { + return false; } - void setMode(Type mode) - { - this->mode = mode; + if (Base::Tools::isNullOrEmpty(sSubName)) { + return (mode == ALL); } - bool allow(App::Document*, App::DocumentObject* obj, const char*sSubName) override - { - if (!obj || !obj->isDerivedFrom()) - return false; - if (Base::Tools::isNullOrEmpty(sSubName)) - return (mode == ALL); - std::string element(sSubName); - switch (mode) { + std::string element(sSubName); + switch (mode) { case VERTEX: - return element.substr(0,6) == "Vertex"; + return element.substr(0, 6) == "Vertex"; case EDGE: - return element.substr(0,4) == "Edge"; + return element.substr(0, 4) == "Edge"; case FACE: - return element.substr(0,4) == "Face"; + return element.substr(0, 4) == "Face"; default: return true; - } } - }; -} + } +}; +} // namespace PartGui class ShapeBuilderWidget::Private { @@ -105,7 +113,7 @@ public: /* TRANSLATOR PartGui::ShapeBuilderWidget */ ShapeBuilderWidget::ShapeBuilderWidget(QWidget* parent) - : d(new Private()) + : d(new Private()) { Q_UNUSED(parent); d->ui.setupUi(this); @@ -118,12 +126,9 @@ ShapeBuilderWidget::ShapeBuilderWidget(QWidget* parent) d->bg.addButton(d->ui.radioButtonSolidFromShell, 5); d->bg.setExclusive(true); - connect(d->ui.selectButton, &QPushButton::clicked, - this, &ShapeBuilderWidget::onSelectButtonClicked); - connect(d->ui.createButton, &QPushButton::clicked, - this, &ShapeBuilderWidget::onCreateButtonClicked); - connect(&d->bg, &QButtonGroup::idClicked, - this, &ShapeBuilderWidget::switchMode); + connect(d->ui.selectButton, &QPushButton::clicked, this, &ShapeBuilderWidget::onSelectButtonClicked); + connect(d->ui.createButton, &QPushButton::clicked, this, &ShapeBuilderWidget::onCreateButtonClicked); + connect(&d->bg, &QButtonGroup::idClicked, this, &ShapeBuilderWidget::switchMode); d->gate = new ShapeSelection(); Gui::Selection().addSelectionGate(d->gate); @@ -152,12 +157,13 @@ void ShapeBuilderWidget::onSelectionChanged(const Gui::SelectionChanges& msg) TopoDS_Shape myShape = static_cast(obj)->Shape.getValue(); TopTools_IndexedMapOfShape all_faces; TopExp::MapShapes(myShape, TopAbs_FACE, all_faces); - for (int i=1; i<= all_faces.Extent(); i++) { + for (int i = 1; i <= all_faces.Extent(); i++) { TopoDS_Shape face = all_faces(i); if (!face.IsNull()) { std::stringstream str; str << "Face" << i; - Gui::Selection().addSelection(msg.pDocName, msg.pObjectName, str.str().c_str()); + Gui::Selection() + .addSelection(msg.pDocName, msg.pObjectName, str.str().c_str()); } } } @@ -172,8 +178,9 @@ void ShapeBuilderWidget::onCreateButtonClicked() { int mode = d->bg.checkedId(); Gui::Document* doc = Gui::Application::Instance->activeDocument(); - if (!doc) + if (!doc) { return; + } try { if (mode == 0) { @@ -221,7 +228,7 @@ void ShapeBuilderWidget::onSelectButtonClicked() void ShapeBuilderWidget::createEdgeFromVertex() { - Gui::SelectionFilter vertexFilter ("SELECT Part::Feature SUBELEMENT Vertex COUNT 2"); + Gui::SelectionFilter vertexFilter("SELECT Part::Feature SUBELEMENT Vertex COUNT 2"); bool matchVertex = vertexFilter.match(); if (!matchVertex) { QMessageBox::critical(this, tr("Wrong selection"), tr("Select two vertices")); @@ -232,8 +239,8 @@ void ShapeBuilderWidget::createEdgeFromVertex() std::vector elements; std::vector::iterator it; std::vector::const_iterator jt; - for (it=sel.begin();it!=sel.end();++it) { - for (jt=it->getSubNames().begin();jt!=it->getSubNames().end();++jt) { + for (it = sel.begin(); it != sel.end(); ++it) { + for (jt = it->getSubNames().begin(); jt != it->getSubNames().end(); ++jt) { QString line; QTextStream str(&line); str << "App.ActiveDocument." << it->getFeatName() << ".Shape." << jt->c_str() << ".Point"; @@ -249,11 +256,12 @@ void ShapeBuilderWidget::createEdgeFromVertex() QString cmd; cmd = QStringLiteral( - "_=Part.makeLine(%1, %2)\n" - "if _.isNull(): raise RuntimeError('Failed to create edge')\n" - "App.ActiveDocument.addObject('Part::Feature','Edge').Shape=_\n" - "del _\n" - ).arg(elements[0], elements[1]); + "_=Part.makeLine(%1, %2)\n" + "if _.isNull(): raise RuntimeError('Failed to create edge')\n" + "App.ActiveDocument.addObject('Part::Feature','Edge').Shape=_\n" + "del _\n" + ) + .arg(elements[0], elements[1]); try { Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Edge")); @@ -268,7 +276,7 @@ void ShapeBuilderWidget::createEdgeFromVertex() void ShapeBuilderWidget::createWireFromEdge() { - Gui::SelectionFilter edgeFilter ("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); + Gui::SelectionFilter edgeFilter("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); bool matchEdge = edgeFilter.match(); if (!matchEdge) { QMessageBox::critical(this, tr("Wrong selection"), tr("Select at least 1 edge")); @@ -282,8 +290,8 @@ void ShapeBuilderWidget::createWireFromEdge() QString list; QTextStream str(&list); str << "["; - for (it=sel.begin();it!=sel.end();++it) { - for (jt=it->getSubNames().begin();jt!=it->getSubNames().end();++jt) { + for (it = sel.begin(); it != sel.end(); ++it) { + for (jt = it->getSubNames().begin(); jt != it->getSubNames().end(); ++jt) { str << "App.ActiveDocument." << it->getFeatName() << ".Shape." << jt->c_str() << ", "; } } @@ -291,11 +299,12 @@ void ShapeBuilderWidget::createWireFromEdge() QString cmd; cmd = QStringLiteral( - "_=Part.Wire(Part.__sortEdges__(%1))\n" - "if _.isNull(): raise RuntimeError('Failed to create a wire')\n" - "App.ActiveDocument.addObject('Part::Feature','Wire').Shape=_\n" - "del _\n" - ).arg(list); + "_=Part.Wire(Part.__sortEdges__(%1))\n" + "if _.isNull(): raise RuntimeError('Failed to create a wire')\n" + "App.ActiveDocument.addObject('Part::Feature','Wire').Shape=_\n" + "del _\n" + ) + .arg(list); try { Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Wire")); Gui::Command::runCommand(Gui::Command::App, cmd.toLatin1()); @@ -309,7 +318,7 @@ void ShapeBuilderWidget::createWireFromEdge() void ShapeBuilderWidget::createFaceFromVertex() { - Gui::SelectionFilter vertexFilter ("SELECT Part::Feature SUBELEMENT Vertex COUNT 3.."); + Gui::SelectionFilter vertexFilter("SELECT Part::Feature SUBELEMENT Vertex COUNT 3.."); bool matchVertex = vertexFilter.match(); if (!matchVertex) { QMessageBox::critical(this, tr("Wrong selection"), tr("Select three or more vertices")); @@ -323,9 +332,10 @@ void ShapeBuilderWidget::createFaceFromVertex() QString list; QTextStream str(&list); str << "["; - for (it=sel.begin();it!=sel.end();++it) { - for (jt=it->getSubNames().begin();jt!=it->getSubNames().end();++jt) { - str << "App.ActiveDocument." << it->getFeatName() << ".Shape." << jt->c_str() << ".Point, "; + for (it = sel.begin(); it != sel.end(); ++it) { + for (jt = it->getSubNames().begin(); jt != it->getSubNames().end(); ++jt) { + str << "App.ActiveDocument." << it->getFeatName() << ".Shape." << jt->c_str() + << ".Point, "; } } str << "]"; @@ -333,19 +343,21 @@ void ShapeBuilderWidget::createFaceFromVertex() QString cmd; if (d->ui.checkPlanar->isChecked()) { cmd = QStringLiteral( - "_=Part.Face(Part.makePolygon(%1, True))\n" - "if _.isNull(): raise RuntimeError('Failed to create face')\n" - "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" - "del _\n" - ).arg(list); + "_=Part.Face(Part.makePolygon(%1, True))\n" + "if _.isNull(): raise RuntimeError('Failed to create face')\n" + "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" + "del _\n" + ) + .arg(list); } else { cmd = QStringLiteral( - "_=Part.makeFilledFace(Part.makePolygon(%1, True).Edges)\n" - "if _.isNull(): raise RuntimeError('Failed to create face')\n" - "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" - "del _\n" - ).arg(list); + "_=Part.makeFilledFace(Part.makePolygon(%1, True).Edges)\n" + "if _.isNull(): raise RuntimeError('Failed to create face')\n" + "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" + "del _\n" + ) + .arg(list); } try { @@ -361,7 +373,7 @@ void ShapeBuilderWidget::createFaceFromVertex() void ShapeBuilderWidget::createFaceFromEdge() { - Gui::SelectionFilter edgeFilter ("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); + Gui::SelectionFilter edgeFilter("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); bool matchEdge = edgeFilter.match(); if (!matchEdge) { QMessageBox::critical(this, tr("Wrong selection"), tr("Select at least 1 edge")); @@ -375,8 +387,8 @@ void ShapeBuilderWidget::createFaceFromEdge() QString list; QTextStream str(&list); str << "["; - for (it=sel.begin();it!=sel.end();++it) { - for (jt=it->getSubNames().begin();jt!=it->getSubNames().end();++jt) { + for (it = sel.begin(); it != sel.end(); ++it) { + for (jt = it->getSubNames().begin(); jt != it->getSubNames().end(); ++jt) { str << "App.ActiveDocument." << it->getFeatName() << ".Shape." << jt->c_str() << ", "; } } @@ -385,19 +397,21 @@ void ShapeBuilderWidget::createFaceFromEdge() QString cmd; if (d->ui.checkPlanar->isChecked()) { cmd = QStringLiteral( - "_=Part.Face(Part.Wire(Part.__sortEdges__(%1)))\n" - "if _.isNull(): raise RuntimeError('Failed to create face')\n" - "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" - "del _\n" - ).arg(list); + "_=Part.Face(Part.Wire(Part.__sortEdges__(%1)))\n" + "if _.isNull(): raise RuntimeError('Failed to create face')\n" + "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" + "del _\n" + ) + .arg(list); } else { cmd = QStringLiteral( - "_=Part.makeFilledFace(Part.__sortEdges__(%1))\n" - "if _.isNull(): raise RuntimeError('Failed to create face')\n" - "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" - "del _\n" - ).arg(list); + "_=Part.makeFilledFace(Part.__sortEdges__(%1))\n" + "if _.isNull(): raise RuntimeError('Failed to create face')\n" + "App.ActiveDocument.addObject('Part::Feature','Face').Shape=_\n" + "del _\n" + ) + .arg(list); } try { @@ -413,7 +427,7 @@ void ShapeBuilderWidget::createFaceFromEdge() void ShapeBuilderWidget::createShellFromFace() { - Gui::SelectionFilter faceFilter ("SELECT Part::Feature SUBELEMENT Face COUNT 2.."); + Gui::SelectionFilter faceFilter("SELECT Part::Feature SUBELEMENT Face COUNT 2.."); bool matchFace = faceFilter.match(); if (!matchFace) { QMessageBox::critical(this, tr("Wrong selection"), tr("Select at least 2 faces")); @@ -426,8 +440,9 @@ void ShapeBuilderWidget::createShellFromFace() QTextStream str(&list); if (d->ui.checkFaces->isChecked()) { std::set obj; - for (const auto& it : sel) + for (const auto& it : sel) { obj.insert(it.getObject()); + } str << "[]"; for (auto it : obj) { str << "+ App.ActiveDocument." << it->getNameInDocument() << ".Shape.Faces"; @@ -446,23 +461,27 @@ void ShapeBuilderWidget::createShellFromFace() QString cmd; if (d->ui.checkRefine->isEnabled() && d->ui.checkRefine->isChecked()) { cmd = QStringLiteral( - "_=Part.Shell(%1)\n" - "if _.isNull(): raise RuntimeError('Failed to create shell')\n" - "App.ActiveDocument.addObject('Part::Feature','Shell').Shape=_.removeSplitter()\n" - "del _\n" - ).arg(list); + "_=Part.Shell(%1)\n" + "if _.isNull(): raise RuntimeError('Failed to create shell')\n" + "App.ActiveDocument.addObject('Part::Feature','Shell').Shape=_.removeSplitter()\n" + "del _\n" + ) + .arg(list); } else { cmd = QStringLiteral( - "_=Part.Shell(%1)\n" - "if _.isNull(): raise RuntimeError('Failed to create shell')\n" - "App.ActiveDocument.addObject('Part::Feature','Shell').Shape=_\n" - "del _\n" - ).arg(list); + "_=Part.Shell(%1)\n" + "if _.isNull(): raise RuntimeError('Failed to create shell')\n" + "App.ActiveDocument.addObject('Part::Feature','Shell').Shape=_\n" + "del _\n" + ) + .arg(list); } try { - Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Shell")); + Gui::Application::Instance->activeDocument()->openCommand( + QT_TRANSLATE_NOOP("Command", "Shell") + ); Gui::Command::runCommand(Gui::Command::App, cmd.toLatin1()); Gui::Application::Instance->activeDocument()->commitCommand(); } @@ -474,7 +493,7 @@ void ShapeBuilderWidget::createShellFromFace() void ShapeBuilderWidget::createSolidFromShell() { - Gui::SelectionFilter partFilter ("SELECT Part::Feature COUNT 1"); + Gui::SelectionFilter partFilter("SELECT Part::Feature COUNT 1"); bool matchPart = partFilter.match(); if (!matchPart) { QMessageBox::critical(this, tr("Wrong selection"), tr("Select only 1 shape object")); @@ -486,7 +505,7 @@ void ShapeBuilderWidget::createSolidFromShell() std::vector sel = partFilter.Result[0]; std::vector::iterator it; - for (it=sel.begin();it!=sel.end();++it) { + for (it = sel.begin(); it != sel.end(); ++it) { str << "App.ActiveDocument." << it->getFeatName() << ".Shape"; break; } @@ -494,27 +513,33 @@ void ShapeBuilderWidget::createSolidFromShell() QString cmd; if (d->ui.checkRefine->isEnabled() && d->ui.checkRefine->isChecked()) { cmd = QStringLiteral( - "shell=%1\n" - "if shell.ShapeType != 'Shell': raise RuntimeError('Part object is not a shell')\n" - "_=Part.Solid(shell)\n" - "if _.isNull(): raise RuntimeError('Failed to create solid')\n" - "App.ActiveDocument.addObject('Part::Feature','Solid').Shape=_.removeSplitter()\n" - "del _\n" - ).arg(line); + "shell=%1\n" + "if shell.ShapeType != 'Shell': raise RuntimeError('Part object is not a " + "shell')\n" + "_=Part.Solid(shell)\n" + "if _.isNull(): raise RuntimeError('Failed to create solid')\n" + "App.ActiveDocument.addObject('Part::Feature','Solid').Shape=_.removeSplitter()\n" + "del _\n" + ) + .arg(line); } else { cmd = QStringLiteral( - "shell=%1\n" - "if shell.ShapeType != 'Shell': raise RuntimeError('Part object is not a shell')\n" - "_=Part.Solid(shell)\n" - "if _.isNull(): raise RuntimeError('Failed to create solid')\n" - "App.ActiveDocument.addObject('Part::Feature','Solid').Shape=_\n" - "del _\n" - ).arg(line); + "shell=%1\n" + "if shell.ShapeType != 'Shell': raise RuntimeError('Part object is not a " + "shell')\n" + "_=Part.Solid(shell)\n" + "if _.isNull(): raise RuntimeError('Failed to create solid')\n" + "App.ActiveDocument.addObject('Part::Feature','Solid').Shape=_\n" + "del _\n" + ) + .arg(line); } try { - Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Solid")); + Gui::Application::Instance->activeDocument()->openCommand( + QT_TRANSLATE_NOOP("Command", "Solid") + ); Gui::Command::runCommand(Gui::Command::App, cmd.toLatin1()); Gui::Application::Instance->activeDocument()->commitCommand(); } @@ -581,7 +606,7 @@ bool ShapeBuilderWidget::reject() return true; } -void ShapeBuilderWidget::changeEvent(QEvent *e) +void ShapeBuilderWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -601,12 +626,10 @@ TaskShapeBuilder::TaskShapeBuilder() TaskShapeBuilder::~TaskShapeBuilder() = default; void TaskShapeBuilder::open() -{ -} +{} void TaskShapeBuilder::clicked(int) -{ -} +{} bool TaskShapeBuilder::accept() { diff --git a/src/Mod/Part/Gui/TaskShapeBuilder.h b/src/Mod/Part/Gui/TaskShapeBuilder.h index 4c4b3d30c1..34ed7689af 100644 --- a/src/Mod/Part/Gui/TaskShapeBuilder.h +++ b/src/Mod/Part/Gui/TaskShapeBuilder.h @@ -30,10 +30,10 @@ #include -namespace PartGui { +namespace PartGui +{ -class ShapeBuilderWidget : public QWidget, - public Gui::SelectionObserver +class ShapeBuilderWidget: public QWidget, public Gui::SelectionObserver { Q_OBJECT @@ -59,14 +59,14 @@ private: void createFaceFromEdge(); void createShellFromFace(); void createSolidFromShell(); - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: class Private; Private* d; }; -class TaskShapeBuilder : public Gui::TaskView::TaskDialog +class TaskShapeBuilder: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -81,12 +81,14 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Close; } + { + return QDialogButtonBox::Close; + } private: ShapeBuilderWidget* widget; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_TASKSHAPEBUILDER_H +#endif // PARTGUI_TASKSHAPEBUILDER_H diff --git a/src/Mod/Part/Gui/TaskSweep.cpp b/src/Mod/Part/Gui/TaskSweep.cpp index 273be744dc..ecec3e94f0 100644 --- a/src/Mod/Part/Gui/TaskSweep.cpp +++ b/src/Mod/Part/Gui/TaskSweep.cpp @@ -23,18 +23,18 @@ ***************************************************************************/ -# 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 @@ -68,19 +68,21 @@ public: Private() = default; ~Private() = default; - class EdgeSelection : public Gui::SelectionFilterGate + class EdgeSelection: public Gui::SelectionFilterGate { public: EdgeSelection() : Gui::SelectionFilterGate(nullPointer()) - { - } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override + {} + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override { if (Base::Tools::isNullOrEmpty(sSubName)) { // If selecting again the same edge the passed sub-element is empty. If the whole // shape is an edge or wire we can use it completely. - Part::TopoShape topoShape = Part::Feature::getTopoShape(pObj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + pObj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { return false; } @@ -98,11 +100,13 @@ public: if (shape.ShapeType() == TopAbs_COMPOUND) { TopoDS_Iterator it(shape); for (; it.More(); it.Next()) { - if (it.Value().IsNull()) + if (it.Value().IsNull()) { return false; - if ((it.Value().ShapeType() != TopAbs_EDGE) && - (it.Value().ShapeType() != TopAbs_WIRE)) + } + if ((it.Value().ShapeType() != TopAbs_EDGE) + && (it.Value().ShapeType() != TopAbs_WIRE)) { return false; + } } return true; @@ -111,7 +115,7 @@ public: } else { std::string element(sSubName); - return element.substr(0,4) == "Edge"; + return element.substr(0, 4) == "Edge"; } return false; @@ -122,7 +126,7 @@ public: /* TRANSLATOR PartGui::SweepWidget */ SweepWidget::SweepWidget(QWidget* parent) - : d(new Private()) + : d(new Private()) { Q_UNUSED(parent); Gui::Command::runCommand(Gui::Command::App, "from FreeCAD import Base"); @@ -155,19 +159,25 @@ void SweepWidget::findShapes() { App::Document* activeDoc = App::GetApplication().getActiveDocument(); Gui::Document* activeGui = Gui::Application::Instance->getDocument(activeDoc); - if (!activeGui) + if (!activeGui) { return; + } d->document = activeDoc->getName(); std::vector objs = activeDoc->getObjectsOfType(); for (auto obj : objs) { - Part::TopoShape topoShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + Part::TopoShape topoShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (topoShape.isNull()) { continue; } TopoDS_Shape shape = topoShape.getShape(); - if (shape.IsNull()) continue; + if (shape.IsNull()) { + continue; + } // also allow compounds with a single face, wire or vertex or // if there are only edges building one wire @@ -176,7 +186,7 @@ void SweepWidget::findShapes() Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); TopoDS_Iterator it(shape); - int numChilds=0; + int numChilds = 0; TopoDS_Shape child; for (; it.More(); it.Next(), numChilds++) { if (!it.Value().IsNull()) { @@ -193,18 +203,21 @@ void SweepWidget::findShapes() } // or all children are edges else if (hEdges->Length() == numChilds) { - ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, - Precision::Confusion(), Standard_False, hWires); - if (hWires->Length() == 1) + ShapeAnalysis_FreeBounds::ConnectEdgesToWires( + hEdges, + Precision::Confusion(), + Standard_False, + hWires + ); + if (hWires->Length() == 1) { shape = hWires->Value(1); + } } } - if (!shape.Infinite() && - (shape.ShapeType() == TopAbs_FACE || - shape.ShapeType() == TopAbs_WIRE || - shape.ShapeType() == TopAbs_EDGE || - shape.ShapeType() == TopAbs_VERTEX)) { + if (!shape.Infinite() + && (shape.ShapeType() == TopAbs_FACE || shape.ShapeType() == TopAbs_WIRE + || shape.ShapeType() == TopAbs_EDGE || shape.ShapeType() == TopAbs_VERTEX)) { QString label = QString::fromUtf8(obj->Label.getValue()); QString name = QString::fromLatin1(obj->getNameInDocument()); @@ -213,7 +226,9 @@ void SweepWidget::findShapes() child->setToolTip(0, label); child->setData(0, Qt::UserRole, name); Gui::ViewProvider* vp = activeGui->getViewProvider(obj); - if (vp) child->setIcon(0, vp->getIcon()); + if (vp) { + child->setIcon(0, vp->getIcon()); + } d->ui.selector->availableTreeWidget()->addTopLevelItem(child); } } @@ -225,14 +240,17 @@ bool SweepWidget::isPathValid(const Gui::SelectionObject& sel) const const std::vector& sub = sel.getSubNames(); TopoDS_Shape pathShape; - const Part::TopoShape& shape = Part::Feature::getTopoShape(path, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); - if (shape.isNull()){ + const Part::TopoShape& shape = Part::Feature::getTopoShape( + path, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); + if (shape.isNull()) { return false; } if (!sub.empty()) { try { BRepBuilderAPI_MakeWire mkWire; - for (const auto & it : sub) { + for (const auto& it : sub) { TopoDS_Shape subshape = shape.getSubShape(it.c_str()); mkWire.Add(TopoDS::Edge(subshape)); } @@ -253,20 +271,27 @@ bool SweepWidget::isPathValid(const Gui::SelectionObject& sel) const try { TopoDS_Iterator it(shape.getShape()); for (; it.More(); it.Next()) { - if ((it.Value().ShapeType() != TopAbs_EDGE) && - (it.Value().ShapeType() != TopAbs_WIRE)) { + if ((it.Value().ShapeType() != TopAbs_EDGE) + && (it.Value().ShapeType() != TopAbs_WIRE)) { return false; } } Handle(TopTools_HSequenceOfShape) hEdges = new TopTools_HSequenceOfShape(); Handle(TopTools_HSequenceOfShape) hWires = new TopTools_HSequenceOfShape(); - for (TopExp_Explorer xp(shape.getShape(), TopAbs_EDGE); xp.More(); xp.Next()) + for (TopExp_Explorer xp(shape.getShape(), TopAbs_EDGE); xp.More(); xp.Next()) { hEdges->Append(xp.Current()); + } - ShapeAnalysis_FreeBounds::ConnectEdgesToWires(hEdges, Precision::Confusion(), Standard_True, hWires); + ShapeAnalysis_FreeBounds::ConnectEdgesToWires( + hEdges, + Precision::Confusion(), + Standard_True, + hWires + ); int len = hWires->Length(); - if (len != 1) + if (len != 1) { return false; + } pathShape = hWires->Value(1); } catch (...) { @@ -279,8 +304,9 @@ bool SweepWidget::isPathValid(const Gui::SelectionObject& sel) const bool SweepWidget::accept() { - if (d->ui.buttonPath->isChecked()) + if (d->ui.buttonPath->isChecked()) { return false; + } const App::DocumentObject* docobj = nullptr; std::string selection; const std::vector selobjs = Gui::Selection().getSelectionEx(); @@ -295,39 +321,53 @@ bool SweepWidget::accept() docobj = selobjs[0].getObject(); spineObject = selobjs[0].getFeatName(); spineLabel = docobj->Label.getValue(); - topoShape = Part::Feature::getTopoShape(docobj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + topoShape = Part::Feature::getTopoShape( + docobj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (!topoShape.isNull()) { - for (std::vector::const_iterator it = subnames.begin(); it != subnames.end(); ++it) { - subShapes.push_back(Part::Feature::getTopoShape(docobj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subnames[0].c_str())); + for (std::vector::const_iterator it = subnames.begin(); it != subnames.end(); + ++it) { + subShapes.push_back( + Part::Feature::getTopoShape( + docobj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subnames[0].c_str() + ) + ); } - for (const auto & it : subShapes) { + for (const auto& it : subShapes) { TopoDS_Shape dsShape = it.getShape(); - if (dsShape.IsNull() || dsShape.ShapeType() != TopAbs_EDGE) { //only edge selection allowed + if (dsShape.IsNull() + || dsShape.ShapeType() != TopAbs_EDGE) { // only edge selection allowed ok = false; } } - } else { //could be not a part::feature or app:link to non-part::feature or app::part without a visible part::feature + } + else { // could be not a part::feature or app:link to non-part::feature or app::part + // without a visible part::feature ok = false; } - - } else { //not just one object selected + } + else { // not just one object selected ok = false; } QString list, solid, frenet; - if (d->ui.checkSolid->isChecked()) + if (d->ui.checkSolid->isChecked()) { solid = QStringLiteral("True"); - else + } + else { solid = QStringLiteral("False"); + } - if (d->ui.checkFrenet->isChecked()) + if (d->ui.checkFrenet->isChecked()) { frenet = QStringLiteral("True"); - else + } + else { frenet = QStringLiteral("False"); + } QTextStream str(&list); @@ -337,15 +377,22 @@ bool SweepWidget::accept() return false; } if (!ok) { - QMessageBox::critical(this, tr("Invalid selection"), tr("Select at least 1 edge from a single object.")); + QMessageBox::critical( + this, + tr("Invalid selection"), + tr("Select at least 1 edge from a single object.") + ); return false; } - for (int i=0; iui.selector->selectedTreeWidget()->topLevelItem(i); QString name = child->data(0, Qt::UserRole).toString(); if (name == QLatin1String(spineObject.c_str())) { - QMessageBox::critical(this, tr("Wrong selection"), tr("'%1' cannot be used as profile and path.") - .arg(QString::fromUtf8(spineLabel.c_str()))); + QMessageBox::critical( + this, + tr("Wrong selection"), + tr("'%1' cannot be used as profile and path.").arg(QString::fromUtf8(spineLabel.c_str())) + ); return false; } str << "App.getDocument('" << d->document.c_str() << "')." << name << ", "; @@ -355,21 +402,24 @@ bool SweepWidget::accept() Gui::WaitCursor wc; QString cmd; cmd = QStringLiteral( - "App.getDocument('%5').addObject('Part::Sweep','Sweep')\n" - "App.getDocument('%5').ActiveObject.Sections=[%1]\n" - "App.getDocument('%5').ActiveObject.Spine=%2\n" - "App.getDocument('%5').ActiveObject.Solid=%3\n" - "App.getDocument('%5').ActiveObject.Frenet=%4\n" - ) - .arg(list, - QLatin1String(selection.c_str()), - solid, - frenet, - QString::fromLatin1(d->document.c_str())); + "App.getDocument('%5').addObject('Part::Sweep','Sweep')\n" + "App.getDocument('%5').ActiveObject.Sections=[%1]\n" + "App.getDocument('%5').ActiveObject.Spine=%2\n" + "App.getDocument('%5').ActiveObject.Solid=%3\n" + "App.getDocument('%5').ActiveObject.Frenet=%4\n" + ) + .arg( + list, + QLatin1String(selection.c_str()), + solid, + frenet, + QString::fromLatin1(d->document.c_str()) + ); Gui::Document* doc = Gui::Application::Instance->getDocument(d->document.c_str()); - if (!doc) + if (!doc) { throw Base::RuntimeError("Document doesn't exist anymore"); + } doc->openCommand(QT_TRANSLATE_NOOP("Command", "Sweep")); Gui::Command::runCommand(Gui::Command::App, cmd.toLatin1()); doc->getDocument()->recompute(); @@ -382,7 +432,11 @@ bool SweepWidget::accept() doc->commitCommand(); } catch (const Base::Exception& e) { - QMessageBox::warning(this, tr("Input error"), QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + this, + tr("Input error"), + QCoreApplication::translate("Exception", e.what()) + ); return false; } @@ -391,20 +445,25 @@ bool SweepWidget::accept() bool SweepWidget::reject() { - if (d->ui.buttonPath->isChecked()) + if (d->ui.buttonPath->isChecked()) { return false; + } return true; } void SweepWidget::onCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous) { if (previous) { - Gui::Selection().rmvSelection(d->document.c_str(), - (const char*)previous->data(0,Qt::UserRole).toByteArray()); + Gui::Selection().rmvSelection( + d->document.c_str(), + (const char*)previous->data(0, Qt::UserRole).toByteArray() + ); } if (current) { - Gui::Selection().addSelection(d->document.c_str(), - (const char*)current->data(0,Qt::UserRole).toByteArray()); + Gui::Selection().addSelection( + d->document.c_str(), + (const char*)current->data(0, Qt::UserRole).toByteArray() + ); } } @@ -412,12 +471,15 @@ void SweepWidget::onButtonPathToggled(bool on) { if (on) { QList c = this->findChildren(); - for (auto it : c) + for (auto it : c) { it->setEnabled(false); + } d->buttonText = d->ui.buttonPath->text(); d->ui.buttonPath->setText(tr("Done")); d->ui.buttonPath->setEnabled(true); - d->ui.labelPath->setText(tr("Select one or more connected edges in the 3D view and press 'Done'")); + d->ui.labelPath->setText( + tr("Select one or more connected edges in the 3D view and press 'Done'") + ); d->ui.labelPath->setEnabled(true); Gui::Selection().clearSelection(); @@ -425,14 +487,15 @@ void SweepWidget::onButtonPathToggled(bool on) } else { QList c = this->findChildren(); - for (auto it : c) + for (auto it : c) { it->setEnabled(true); + } d->ui.buttonPath->setText(d->buttonText); d->ui.labelPath->clear(); Gui::Selection().rmvSelectionGate(); - Gui::SelectionFilter edgeFilter ("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); - Gui::SelectionFilter partFilter ("SELECT Part::Feature COUNT 1"); + Gui::SelectionFilter edgeFilter("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); + Gui::SelectionFilter partFilter("SELECT Part::Feature COUNT 1"); bool matchEdge = edgeFilter.match(); bool matchPart = partFilter.match(); if (matchEdge) { @@ -454,7 +517,7 @@ void SweepWidget::onButtonPathToggled(bool on) } } -void SweepWidget::changeEvent(QEvent *e) +void SweepWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -467,7 +530,8 @@ void SweepWidget::changeEvent(QEvent *e) /* TRANSLATOR PartGui::TaskSweep */ -TaskSweep::TaskSweep() : label(nullptr) +TaskSweep::TaskSweep() + : label(nullptr) { widget = new SweepWidget(); addTaskBox(Gui::BitmapFactory().pixmap("Part_Sweep"), widget); @@ -479,15 +543,16 @@ TaskSweep::~TaskSweep() } void TaskSweep::open() -{ -} +{} void TaskSweep::clicked(int id) { if (id == QDialogButtonBox::Help) { - QString help = QApplication::translate("PartGui::TaskSweep", + QString help = QApplication::translate( + "PartGui::TaskSweep", "Select at least 1 profile and an edge or wire\n" - "in the 3D view for the sweep path."); + "in the 3D view for the sweep path." + ); if (!label) { label = new Gui::StatusWidget(widget); label->setStatusText(help); diff --git a/src/Mod/Part/Gui/TaskSweep.h b/src/Mod/Part/Gui/TaskSweep.h index 998d357b7c..3eb7c7a2e0 100644 --- a/src/Mod/Part/Gui/TaskSweep.h +++ b/src/Mod/Part/Gui/TaskSweep.h @@ -31,13 +31,15 @@ class QTreeWidgetItem; -namespace Gui { +namespace Gui +{ class SelectionObject; class StatusWidget; -} -namespace PartGui { +} // namespace Gui +namespace PartGui +{ -class SweepWidget : public QWidget +class SweepWidget: public QWidget { Q_OBJECT @@ -53,7 +55,7 @@ private: void onButtonPathToggled(bool); private: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void findShapes(); bool isPathValid(const Gui::SelectionObject& sel) const; @@ -62,7 +64,7 @@ private: Private* d; }; -class TaskSweep : public Gui::TaskView::TaskDialog +class TaskSweep: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -77,13 +79,15 @@ public: void clicked(int) override; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Help; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Help; + } private: SweepWidget* widget; Gui::StatusWidget* label; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_TASKSWEEP_H +#endif // PARTGUI_TASKSWEEP_H diff --git a/src/Mod/Part/Gui/TaskThickness.cpp b/src/Mod/Part/Gui/TaskThickness.cpp index b13cd76510..a6eaf24831 100644 --- a/src/Mod/Part/Gui/TaskThickness.cpp +++ b/src/Mod/Part/Gui/TaskThickness.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include #include @@ -52,27 +52,30 @@ using namespace PartGui; class ThicknessWidget::Private { public: - Ui_TaskOffset ui{}; + Ui_TaskOffset ui {}; QString text; std::string selection; - Part::Thickness* thickness{nullptr}; + Part::Thickness* thickness {nullptr}; - class FaceSelection : public Gui::SelectionFilterGate + class FaceSelection: public Gui::SelectionFilterGate { const App::DocumentObject* object; + public: explicit FaceSelection(const App::DocumentObject* obj) - : Gui::SelectionFilterGate(nullPointer()), object(obj) + : Gui::SelectionFilterGate(nullPointer()) + , object(obj) + {} + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override { - } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override - { - if (pObj != this->object) + if (pObj != this->object) { return false; - if (Base::Tools::isNullOrEmpty(sSubName)) + } + if (Base::Tools::isNullOrEmpty(sSubName)) { return false; + } std::string element(sSubName); - return element.substr(0,4) == "Face"; + return element.substr(0, 4) == "Face"; } }; }; @@ -80,7 +83,7 @@ public: /* TRANSLATOR PartGui::ThicknessWidget */ ThicknessWidget::ThicknessWidget(Part::Thickness* thickness, QWidget* parent) - : d(new Private()) + : d(new Private()) { Q_UNUSED(parent); Gui::Command::runCommand(Gui::Command::App, "from FreeCAD import Base"); @@ -94,8 +97,7 @@ ThicknessWidget::ThicknessWidget(Part::Thickness* thickness, QWidget* parent) d->ui.fillOffset->hide(); QSignalBlocker blockOffset(d->ui.spinOffset); - d->ui.spinOffset->setRange(-std::numeric_limits::max(), - std::numeric_limits::max()); + d->ui.spinOffset->setRange(-std::numeric_limits::max(), std::numeric_limits::max()); d->ui.spinOffset->setSingleStep(0.1); d->ui.spinOffset->setValue(d->thickness->Value.getValue()); @@ -155,44 +157,50 @@ Part::Thickness* ThicknessWidget::getObject() const void ThicknessWidget::onSpinOffsetValueChanged(double val) { d->thickness->Value.setValue(val); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->thickness->getDocument()->recomputeFeature(d->thickness); + } } void ThicknessWidget::onModeTypeActivated(int val) { d->thickness->Mode.setValue(val); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->thickness->getDocument()->recomputeFeature(d->thickness); + } } void ThicknessWidget::onJoinTypeActivated(int val) { d->thickness->Join.setValue((long)val); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->thickness->getDocument()->recomputeFeature(d->thickness); + } } void ThicknessWidget::onIntersectionToggled(bool on) { d->thickness->Intersection.setValue(on); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->thickness->getDocument()->recomputeFeature(d->thickness); + } } void ThicknessWidget::onSelfIntersectionToggled(bool on) { d->thickness->SelfIntersection.setValue(on); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->thickness->getDocument()->recomputeFeature(d->thickness); + } } void ThicknessWidget::onFacesButtonToggled(bool on) { if (on) { QList c = this->findChildren(); - for (auto it : c) + for (auto it : c) { it->setEnabled(false); + } d->ui.facesButton->setEnabled(true); d->ui.labelFaces->setText(tr("Select faces of the source object and press 'Done'")); d->ui.labelFaces->setEnabled(true); @@ -210,15 +218,18 @@ void ThicknessWidget::onFacesButtonToggled(bool on) } else { QList c = this->findChildren(); - for (auto it : c) + for (auto it : c) { it->setEnabled(true); + } d->ui.facesButton->setText(d->text); d->ui.labelFaces->clear(); - d->selection = Gui::Command::getPythonTuple - (d->thickness->Faces.getValue()->getNameInDocument(), d->thickness->Faces.getSubValues()); + d->selection = Gui::Command::getPythonTuple( + d->thickness->Faces.getValue()->getNameInDocument(), + d->thickness->Faces.getSubValues() + ); std::vector sel = Gui::Selection().getSelectionEx(); - for (auto & it : sel) { + for (auto& it : sel) { if (it.getObject() == d->thickness->Faces.getValue()) { d->thickness->Faces.setValue(it.getObject(), it.getSubNames()); d->selection = it.getAsPropertyLinkSubString(); @@ -229,8 +240,9 @@ void ThicknessWidget::onFacesButtonToggled(bool on) Gui::Selection().rmvSelectionGate(); Gui::Application::Instance->showViewProvider(d->thickness); Gui::Application::Instance->hideViewProvider(d->thickness->Faces.getValue()); - if (d->ui.updateView->isChecked()) + if (d->ui.updateView->isChecked()) { d->thickness->getDocument()->recomputeFeature(d->thickness); + } if (gizmoContainer) { gizmoContainer->visible = true; @@ -248,8 +260,9 @@ void ThicknessWidget::onUpdateViewToggled(bool on) bool ThicknessWidget::accept() { - if (d->ui.facesButton->isChecked()) + if (d->ui.facesButton->isChecked()) { return false; + } try { if (!d->selection.empty()) { @@ -258,20 +271,30 @@ bool ThicknessWidget::accept() Gui::cmdAppObjectArgs(d->thickness, "Value = %f", d->ui.spinOffset->value().getValue()); Gui::cmdAppObjectArgs(d->thickness, "Mode = %d", d->ui.modeType->currentIndex()); Gui::cmdAppObjectArgs(d->thickness, "Join = %d", d->ui.joinType->currentIndex()); - Gui::cmdAppObjectArgs(d->thickness, "Intersection = %s", - d->ui.intersection->isChecked() ? "True" : "False"); - Gui::cmdAppObjectArgs(d->thickness, "SelfIntersection = %s", - d->ui.selfIntersection->isChecked() ? "True" : "False"); + Gui::cmdAppObjectArgs( + d->thickness, + "Intersection = %s", + d->ui.intersection->isChecked() ? "True" : "False" + ); + Gui::cmdAppObjectArgs( + d->thickness, + "SelfIntersection = %s", + d->ui.selfIntersection->isChecked() ? "True" : "False" + ); - Gui::Command::doCommand(Gui::Command::Doc,"App.ActiveDocument.recompute()"); - if (!d->thickness->isValid()) + Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); + if (!d->thickness->isValid()) { throw Base::CADKernelError(d->thickness->getStatusString()); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); + } + Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); Gui::Command::commitCommand(); } catch (const Base::Exception& e) { QMessageBox::warning( - this, tr("Input error"), QCoreApplication::translate("Exception", e.what())); + this, + tr("Input error"), + QCoreApplication::translate("Exception", e.what()) + ); return false; } @@ -280,8 +303,9 @@ bool ThicknessWidget::accept() bool ThicknessWidget::reject() { - if (d->ui.facesButton->isChecked()) + if (d->ui.facesButton->isChecked()) { return false; + } // save this and check if the object is still there after the // transaction is aborted @@ -290,7 +314,7 @@ bool ThicknessWidget::reject() // roll back the done things Gui::Command::abortCommand(); - Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); + Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); Gui::Command::updateActive(); // Thickness object was deleted @@ -301,7 +325,7 @@ bool ThicknessWidget::reject() return true; } -void ThicknessWidget::changeEvent(QEvent *e) +void ThicknessWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); if (e->type() == QEvent::LanguageChange) { @@ -337,7 +361,10 @@ void ThicknessWidget::setGizmoPositions() } Part::Thickness* thickness = getObject(); - auto base = thickness->getTopoShape(thickness->Faces.getValue(), Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + auto base = thickness->getTopoShape( + thickness->Faces.getValue(), + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); auto faces = thickness->Faces.getSubValues(true); if (faces.size() == 0) { @@ -376,12 +403,10 @@ Part::Thickness* TaskThickness::getObject() const } void TaskThickness::open() -{ -} +{} void TaskThickness::clicked(int) -{ -} +{} bool TaskThickness::accept() { diff --git a/src/Mod/Part/Gui/TaskThickness.h b/src/Mod/Part/Gui/TaskThickness.h index 9c5d0fd85a..e2ceb3bc93 100644 --- a/src/Mod/Part/Gui/TaskThickness.h +++ b/src/Mod/Part/Gui/TaskThickness.h @@ -29,15 +29,20 @@ #include #include -namespace Gui { +namespace Gui +{ class LinearGizmo; class GizmoContainer; +} // namespace Gui + +namespace Part +{ +class Thickness; } +namespace PartGui +{ -namespace Part { class Thickness; } -namespace PartGui { - -class ThicknessWidget : public QWidget +class ThicknessWidget: public QWidget { Q_OBJECT @@ -60,7 +65,7 @@ private: void onUpdateViewToggled(bool); private: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; std::unique_ptr gizmoContainer; Gui::LinearGizmo* linearGizmo = nullptr; @@ -72,7 +77,7 @@ private: Private* d; }; -class TaskThickness : public Gui::TaskView::TaskDialog +class TaskThickness: public Gui::TaskView::TaskDialog { Q_OBJECT @@ -87,12 +92,14 @@ public: Part::Thickness* getObject() const; QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } private: ThicknessWidget* widget; }; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_TASKTHICKNESS_H +#endif // PARTGUI_TASKTHICKNESS_H diff --git a/src/Mod/Part/Gui/ViewProvider.cpp b/src/Mod/Part/Gui/ViewProvider.cpp index 553946146a..b04745eba0 100644 --- a/src/Mod/Part/Gui/ViewProvider.cpp +++ b/src/Mod/Part/Gui/ViewProvider.cpp @@ -61,9 +61,11 @@ bool ViewProviderPart::doubleClicked() } } -void ViewProviderPart::applyColor(const Part::ShapeHistory& hist, - const std::vector& colBase, - std::vector& colBool) +void ViewProviderPart::applyColor( + const Part::ShapeHistory& hist, + const std::vector& colBase, + std::vector& colBool +) { // apply color from modified faces for (const auto& jt : hist.shapeMap) { @@ -73,9 +75,11 @@ void ViewProviderPart::applyColor(const Part::ShapeHistory& hist, } } -void ViewProviderPart::applyMaterial(const Part::ShapeHistory& hist, - const std::vector& colBase, - std::vector& colBool) +void ViewProviderPart::applyMaterial( + const Part::ShapeHistory& hist, + const std::vector& colBase, + std::vector& colBool +) { // apply color from modified faces for (const auto& jt : hist.shapeMap) { diff --git a/src/Mod/Part/Gui/ViewProvider.h b/src/Mod/Part/Gui/ViewProvider.h index 338ec5f44d..9024984a3e 100644 --- a/src/Mod/Part/Gui/ViewProvider.h +++ b/src/Mod/Part/Gui/ViewProvider.h @@ -39,11 +39,15 @@ namespace Gui class GizmoContainer; } -namespace Part { struct ShapeHistory; } +namespace Part +{ +struct ShapeHistory; +} -namespace PartGui { +namespace PartGui +{ -class ViewProviderShapeBuilder : public Gui::ViewProviderBuilder +class ViewProviderShapeBuilder: public Gui::ViewProviderBuilder { public: ViewProviderShapeBuilder() = default; @@ -52,7 +56,7 @@ public: void createShape(const App::Property*, SoSeparator*) const; }; -class PartGuiExport ViewProviderPart : public ViewProviderPartExt +class PartGuiExport ViewProviderPart: public ViewProviderPartExt { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPart); @@ -64,18 +68,21 @@ public: bool doubleClicked() override; protected: - void applyColor(const Part::ShapeHistory& hist, - const std::vector& colBase, - std::vector& colBool); - void applyMaterial(const Part::ShapeHistory& hist, - const std::vector& colBase, - std::vector& colBool); + void applyColor( + const Part::ShapeHistory& hist, + const std::vector& colBase, + std::vector& colBool + ); + void applyMaterial( + const Part::ShapeHistory& hist, + const std::vector& colBase, + std::vector& colBool + ); void applyTransparency(float transparency, std::vector& colors); void applyTransparency(float transparency, std::vector& colors); }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPART_H - +#endif // PARTGUI_VIEWPROVIDERPART_H diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.cpp b/src/Mod/Part/Gui/ViewProvider2DObject.cpp index c34dfd797d..299ca8c4bf 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.cpp +++ b/src/Mod/Part/Gui/ViewProvider2DObject.cpp @@ -22,17 +22,17 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -53,22 +53,58 @@ using namespace std; //************************************************************************** // Construction/Destruction -const char* ViewProvider2DObjectGrid::GridStyleEnums[]= {"Dashed","Light",nullptr}; -App::PropertyQuantityConstraint::Constraints ViewProvider2DObjectGrid::GridSizeRange = { - 0.001, std::numeric_limits::max(), 1.0}; +const char* ViewProvider2DObjectGrid::GridStyleEnums[] = {"Dashed", "Light", nullptr}; +App::PropertyQuantityConstraint::Constraints ViewProvider2DObjectGrid::GridSizeRange + = {0.001, std::numeric_limits::max(), 1.0}; PROPERTY_SOURCE(PartGui::ViewProvider2DObjectGrid, PartGui::ViewProvider2DObject) ViewProvider2DObjectGrid::ViewProvider2DObjectGrid() { - ADD_PROPERTY_TYPE(ShowGrid,(false),"Grid",(App::PropertyType)(App::Prop_None),"Toggle grid visibility"); - ADD_PROPERTY_TYPE(ShowOnlyInEditMode,(true),"Grid",(App::PropertyType)(App::Prop_None),"Show only while in edit mode"); - ADD_PROPERTY_TYPE(GridSize,(10.0),"Grid",(App::PropertyType)(App::Prop_None),"Gap size of the grid"); - ADD_PROPERTY_TYPE(GridStyle,(0L),"Grid",(App::PropertyType)(App::Prop_None),"Appearance style of the grid"); - ADD_PROPERTY_TYPE(TightGrid,(true),"Grid",(App::PropertyType)(App::Prop_None),"Toggle tight grid mode"); - ADD_PROPERTY_TYPE(GridSnap,(false),"Grid",(App::PropertyType)(App::Prop_None),"Toggle grid snapping"); - ADD_PROPERTY_TYPE(GridAutoSize,(true),"Grid",(App::PropertyType)(App::Prop_Hidden),"Auto-size grid based on shape boundary box"); - ADD_PROPERTY_TYPE(maxNumberOfLines,(10000),"Grid",(App::PropertyType)(App::Prop_None),"Maximum number of lines in grid"); + ADD_PROPERTY_TYPE( + ShowGrid, + (false), + "Grid", + (App::PropertyType)(App::Prop_None), + "Toggle grid visibility" + ); + ADD_PROPERTY_TYPE( + ShowOnlyInEditMode, + (true), + "Grid", + (App::PropertyType)(App::Prop_None), + "Show only while in edit mode" + ); + ADD_PROPERTY_TYPE(GridSize, (10.0), "Grid", (App::PropertyType)(App::Prop_None), "Gap size of the grid"); + ADD_PROPERTY_TYPE( + GridStyle, + (0L), + "Grid", + (App::PropertyType)(App::Prop_None), + "Appearance style of the grid" + ); + ADD_PROPERTY_TYPE( + TightGrid, + (true), + "Grid", + (App::PropertyType)(App::Prop_None), + "Toggle tight grid mode" + ); + ADD_PROPERTY_TYPE(GridSnap, (false), "Grid", (App::PropertyType)(App::Prop_None), "Toggle grid snapping"); + ADD_PROPERTY_TYPE( + GridAutoSize, + (true), + "Grid", + (App::PropertyType)(App::Prop_Hidden), + "Auto-size grid based on shape boundary box" + ); + ADD_PROPERTY_TYPE( + maxNumberOfLines, + (10000), + "Grid", + (App::PropertyType)(App::Prop_None), + "Maximum number of lines in grid" + ); GridRoot = new SoAnnotation(); GridRoot->ref(); @@ -85,7 +121,7 @@ ViewProvider2DObjectGrid::ViewProvider2DObjectGrid() ViewProvider2DObjectGrid::~ViewProvider2DObjectGrid() { - GridRoot->unref(); + GridRoot->unref(); } @@ -93,13 +129,13 @@ ViewProvider2DObjectGrid::~ViewProvider2DObjectGrid() SoSeparator* ViewProvider2DObjectGrid::createGrid() { - float Step = GridSize.getValue(); //pow(10,floor(log10(Size/5.0))); + float Step = GridSize.getValue(); // pow(10,floor(log10(Size/5.0))); float MiX, MaX, MiY, MaY; if (TightGrid.getValue()) { - MiX = MinX - (MaxX-MinX)*0.2f; - MaX = MaxX + (MaxX-MinX)*0.2f; - MiY = MinY - (MaxY-MinY)*0.2f; - MaY = MaxY + (MaxY-MinY)*0.2f; + MiX = MinX - (MaxX - MinX) * 0.2f; + MaX = MaxX + (MaxX - MinX) * 0.2f; + MiY = MinY - (MaxY - MinY) * 0.2f; + MaY = MaxY + (MaxY - MinY) * 0.2f; } else { // make sure that nine of the numbers are exactly zero because log(0) @@ -110,36 +146,38 @@ SoSeparator* ViewProvider2DObjectGrid::createGrid() float yMin = std::abs(MinY) < floatEpsilon ? 0.01f : MinY; float yMax = std::abs(MaxY) < floatEpsilon ? 0.01f : MaxY; MiX = -exp(ceil(log(std::abs(xMin)))); - MiX = std::min(MiX,(float)-exp(ceil(log(std::abs(0.1f*xMax))))); + MiX = std::min(MiX, (float)-exp(ceil(log(std::abs(0.1f * xMax))))); MaX = exp(ceil(log(std::abs(xMax)))); - MaX = std::max(MaX,(float)exp(ceil(log(std::abs(0.1f*xMin))))); + MaX = std::max(MaX, (float)exp(ceil(log(std::abs(0.1f * xMin))))); MiY = -exp(ceil(log(std::abs(yMin)))); - MiY = std::min(MiY,(float)-exp(ceil(log(std::abs(0.1f*yMax))))); + MiY = std::min(MiY, (float)-exp(ceil(log(std::abs(0.1f * yMax))))); MaY = exp(ceil(log(std::abs(yMax)))); - MaY = std::max(MaY,(float)exp(ceil(log(std::abs(0.1f*yMin))))); + MaY = std::max(MaY, (float)exp(ceil(log(std::abs(0.1f * yMin))))); } - //Round the values otherwise grid is not aligned with center - MiX = (floor(MiX / Step)-0.5) * Step; - MaX = (ceil(MaX / Step)+0.5) * Step; - MiY = (floor(MiY / Step)-0.5) * Step; - MaY = (ceil(MaY / Step)+0.5) * Step; + // Round the values otherwise grid is not aligned with center + MiX = (floor(MiX / Step) - 0.5) * Step; + MaX = (ceil(MaX / Step) + 0.5) * Step; + MiY = (floor(MiY / Step) - 0.5) * Step; + MaY = (ceil(MaY / Step) + 0.5) * Step; - double zGrid = 0.0; // carpet-grid separation + double zGrid = 0.0; // carpet-grid separation - SoGroup *parent = new Gui::SoSkipBoundingGroup(); + SoGroup* parent = new Gui::SoSkipBoundingGroup(); Gui::coinRemoveAllChildren(GridRoot); GridRoot->addChild(parent); - SoBaseColor *mycolor; - SoVertexProperty *vts; + SoBaseColor* mycolor; + SoVertexProperty* vts; // gridlines mycolor = new SoBaseColor; - mycolor->rgb.setValue(0.7f, 0.7f ,0.7f); + mycolor->rgb.setValue(0.7f, 0.7f, 0.7f); parent->addChild(mycolor); if (GridStyle.getValue() == 0) { - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part" + ); int pattern = hGrp->GetInt("GridLinePattern", 0x0f0f); SoDrawStyle* DefaultStyle = new SoDrawStyle; DefaultStyle->lineWidth = 1; @@ -156,7 +194,7 @@ SoSeparator* ViewProvider2DObjectGrid::createGrid() PickStyle->style = SoPickStyle::UNPICKABLE; parent->addChild(PickStyle); - SoLineSet *grid = new SoLineSet; + SoLineSet* grid = new SoLineSet; vts = new SoVertexProperty; grid->vertexProperty = vts; @@ -169,8 +207,14 @@ SoSeparator* ViewProvider2DObjectGrid::createGrid() int lines = vlines + hlines; if (lines > maxNumberOfLines.getValue()) { - Base::Console().warning("Grid disabled: requested number of lines %d is larger than the maximum configured of %d\n." - "Either increase the 'GridSize' property to a more reasonable value (recommended) or increase the 'maxNumberOfLines' property.\n", lines, maxNumberOfLines.getValue()); + Base::Console().warning( + "Grid disabled: requested number of lines %d is larger than the maximum configured of " + "%d\n." + "Either increase the 'GridSize' property to a more reasonable value (recommended) or " + "increase the 'maxNumberOfLines' property.\n", + lines, + maxNumberOfLines.getValue() + ); parent->addChild(vts); parent->addChild(grid); return GridRoot; @@ -179,26 +223,27 @@ SoSeparator* ViewProvider2DObjectGrid::createGrid() // set the grid indices grid->numVertices.setNum(lines); int32_t* vertices = grid->numVertices.startEditing(); - for (int i=0; inumVertices.finishEditing(); // set the grid coordinates - vts->vertex.setNum(2*lines); + vts->vertex.setNum(2 * lines); SbVec3f* vertex_coords = vts->vertex.startEditing(); // vertical lines int i_offset_x = static_cast(MiX / Step); - for (int i=0; i(MiY / Step); - for (int i=vlines; ivertex.finishEditing(); @@ -215,10 +260,12 @@ void ViewProvider2DObjectGrid::updateData(const App::Property* prop) if (prop->is()) { if (GridAutoSize.getValue()) { Base::BoundBox3d bbox = static_cast(prop)->getBoundingBox(); - if (!bbox.IsValid()) + if (!bbox.IsValid()) { return; + } Gui::coinRemoveAllChildren(GridRoot); - Base::Placement place = static_cast(prop)->getComplexData()->getPlacement(); + Base::Placement place + = static_cast(prop)->getComplexData()->getPlacement(); place.invert(); Base::ViewOrthoProjMatrix proj(place.toMatrix()); Base::BoundBox2d bbox2d = bbox.ProjectBox(&proj); @@ -227,7 +274,7 @@ void ViewProvider2DObjectGrid::updateData(const App::Property* prop) this->MinY = bbox2d.MinY; this->MaxY = bbox2d.MaxY; } - if (ShowGrid.getValue() && !(ShowOnlyInEditMode.getValue() && !this->isEditing()) ) { + if (ShowGrid.getValue() && !(ShowOnlyInEditMode.getValue() && !this->isEditing())) { createGrid(); } else { @@ -242,10 +289,13 @@ void ViewProvider2DObjectGrid::onChanged(const App::Property* prop) ViewProviderPart::onChanged(prop); if (prop == &ShowGrid || prop == &ShowOnlyInEditMode || prop == &Visibility) { - if (ShowGrid.getValue() && ((Visibility.getValue() && !ShowOnlyInEditMode.getValue()) || this->isEditing())) + if (ShowGrid.getValue() + && ((Visibility.getValue() && !ShowOnlyInEditMode.getValue()) || this->isEditing())) { createGrid(); - else + } + else { Gui::coinRemoveAllChildren(GridRoot); + } } if ((prop == &GridSize) || (prop == &GridStyle) || (prop == &TightGrid)) { @@ -255,18 +305,20 @@ void ViewProvider2DObjectGrid::onChanged(const App::Property* prop) } } -void ViewProvider2DObjectGrid::Restore(Base::XMLReader &reader) +void ViewProvider2DObjectGrid::Restore(Base::XMLReader& reader) { ViewProviderPart::Restore(reader); } -void ViewProvider2DObjectGrid::handleChangedPropertyType(Base::XMLReader &reader, - const char * TypeName, - App::Property * prop) +void ViewProvider2DObjectGrid::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { Base::Type inputType = Base::Type::fromName(TypeName); - if (prop->isDerivedFrom() && - inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) { + if (prop->isDerivedFrom() + && inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) { // Do not directly call the property's Restore method in case the implementation // has changed. So, create a temporary PropertyFloat object and assign the value. App::PropertyFloat floatProp; @@ -278,42 +330,47 @@ void ViewProvider2DObjectGrid::handleChangedPropertyType(Base::XMLReader &reader } } -void ViewProvider2DObjectGrid::attach(App::DocumentObject *pcFeat) +void ViewProvider2DObjectGrid::attach(App::DocumentObject* pcFeat) { ViewProvider2DObject::attach(pcFeat); - if (ShowGrid.getValue() && !(ShowOnlyInEditMode.getValue() && !this->isEditing())) + if (ShowGrid.getValue() && !(ShowOnlyInEditMode.getValue() && !this->isEditing())) { createGrid(); + } } bool ViewProvider2DObjectGrid::setEdit(int) { - if (ShowGrid.getValue()) + if (ShowGrid.getValue()) { createGrid(); + } return false; } void ViewProvider2DObjectGrid::unsetEdit(int) { - if (ShowGrid.getValue() && ShowOnlyInEditMode.getValue()) + if (ShowGrid.getValue() && ShowOnlyInEditMode.getValue()) { Gui::coinRemoveAllChildren(GridRoot); + } } void ViewProvider2DObjectGrid::updateGridExtent(float minx, float maxx, float miny, float maxy) { bool redraw = false; - if (minx < MinX || maxx > MaxX || miny < MinY || maxy > MaxY) + if (minx < MinX || maxx > MaxX || miny < MinY || maxy > MaxY) { redraw = true; + } MinX = minx; MaxX = maxx; MinY = miny; MaxY = maxy; - if (redraw && ShowGrid.getValue() && !(ShowOnlyInEditMode.getValue() && !this->isEditing())) + if (redraw && ShowGrid.getValue() && !(ShowOnlyInEditMode.getValue() && !this->isEditing())) { createGrid(); + } } // ----------------------------------------------------------------------- @@ -323,11 +380,13 @@ PROPERTY_SOURCE(PartGui::ViewProvider2DObject, PartGui::ViewProviderPart) ViewProvider2DObject::ViewProvider2DObject() : plane(new SoSwitch) { - ADD_PROPERTY_TYPE(ShowPlane, - (false), - "Display Options", - (App::PropertyType)(App::Prop_None), - "If true, plane related with object is additionally rendered"); + ADD_PROPERTY_TYPE( + ShowPlane, + (false), + "Display Options", + (App::PropertyType)(App::Prop_None), + "If true, plane related with object is additionally rendered" + ); } ViewProvider2DObject::~ViewProvider2DObject() = default; @@ -366,7 +425,7 @@ std::vector ViewProvider2DObject::getDisplayModes() const // add your own modes StrList.emplace_back("Flat Lines"); - //StrList.push_back("Shaded"); + // StrList.push_back("Shaded"); StrList.emplace_back("Wireframe"); StrList.emplace_back("Points"); @@ -408,7 +467,7 @@ void ViewProvider2DObject::updatePlane() SbVec3f(bb.MaxX + horizontalPlanePadding, bb.MinY - verticalPlanePadding, 0), }; - static const int32_t lines[6] = { 0, 1, 2, 3, 0, -1 }; + static const int32_t lines[6] = {0, 1, 2, 3, 0, -1}; auto pCoords = new SoCoordinate3(); pCoords->point.setNum(4); @@ -461,11 +520,12 @@ void ViewProvider2DObject::updatePlane() plane->addChild(ps); } -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProvider2DObjectPython, PartGui::ViewProvider2DObject) /// @endcond // explicit template instantiation template class PartGuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.h b/src/Mod/Part/Gui/ViewProvider2DObject.h index f9adf13f1e..1ec135cab5 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.h +++ b/src/Mod/Part/Gui/ViewProvider2DObject.h @@ -38,10 +38,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProvider2DObject : public PartGui::ViewProviderPart +class PartGuiExport ViewProvider2DObject: public PartGui::ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProvider2DObject); @@ -57,8 +58,8 @@ public: App::PropertyBool ShowPlane; void attach(App::DocumentObject*) override; - void updateData(const App::Property *) override; - void onChanged(const App::Property *) override; + void updateData(const App::Property*) override; + void onChanged(const App::Property*) override; std::vector getDisplayModes() const override; const char* getDefaultDisplayMode() const override; @@ -69,7 +70,7 @@ protected: Gui::CoinPtr plane; }; -class PartGuiExport ViewProvider2DObjectGrid : public ViewProvider2DObject +class PartGuiExport ViewProvider2DObjectGrid: public ViewProvider2DObject { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProvider2DObjectGrid); @@ -89,7 +90,7 @@ public: App::PropertyBool GridAutoSize; App::PropertyInteger maxNumberOfLines; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void updateData(const App::Property*) override; /// creates the grid @@ -100,10 +101,14 @@ protected: void unsetEdit(int ModNum) override; /// get called by the container whenever a property has been changed void onChanged(const App::Property* prop) override; - void Restore(Base::XMLReader &reader) override; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void Restore(Base::XMLReader& reader) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; - SoSeparator *GridRoot; + SoSeparator* GridRoot; void updateGridExtent(float minx, float maxx, float miny, float maxy); @@ -119,8 +124,7 @@ private: using ViewProvider2DObjectPython = Gui::ViewProviderFeaturePythonT; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDER2DOBJECT_H - +#endif // PARTGUI_VIEWPROVIDER2DOBJECT_H diff --git a/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp b/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp index 58e4dd7a42..11765fbea7 100644 --- a/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp +++ b/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include #include @@ -44,24 +44,27 @@ ViewProviderAttachExtension::ViewProviderAttachExtension() initExtensionType(ViewProviderAttachExtension::getExtensionClassTypeId()); } -QIcon ViewProviderAttachExtension::extensionMergeColorfullOverlayIcons (const QIcon & orig) const +QIcon ViewProviderAttachExtension::extensionMergeColorfullOverlayIcons(const QIcon& orig) const { QIcon mergedicon = orig; - if (getExtendedViewProvider()->getObject()->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) { + if (getExtendedViewProvider()->getObject()->hasExtension( + Part::AttachExtension::getExtensionClassTypeId() + )) { - auto* attach = getExtendedViewProvider()->getObject()->getExtensionByType(); + auto* attach + = getExtendedViewProvider()->getObject()->getExtensionByType(); if (attach) { - if(!attach->isAttacherActive()) { - static QPixmap px( - Gui::BitmapFactory().pixmapFromSvg("Part_Detached", QSize(10, 10))); + if (!attach->isAttacherActive()) { + static QPixmap px(Gui::BitmapFactory().pixmapFromSvg("Part_Detached", QSize(10, 10))); - mergedicon = - Gui::BitmapFactoryInst::mergePixmap(mergedicon, - px, - Gui::BitmapFactoryInst::BottomLeft); + mergedicon = Gui::BitmapFactoryInst::mergePixmap( + mergedicon, + px, + Gui::BitmapFactoryInst::BottomLeft + ); } } } @@ -75,37 +78,37 @@ void ViewProviderAttachExtension::extensionUpdateData(const App::Property* prop) if (obj && obj->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) { auto* attach = obj->getExtensionByType(); - if(attach) { - if( prop == &(attach->AttachmentSupport) || - prop == &(attach->MapMode) || - prop == &(attach->MapPathParameter) || - prop == &(attach->MapReversed) || - prop == &(attach->AttachmentOffset) || - prop == &(attach->AttacherType) ) { + if (attach) { + if (prop == &(attach->AttachmentSupport) || prop == &(attach->MapMode) + || prop == &(attach->MapPathParameter) || prop == &(attach->MapReversed) + || prop == &(attach->AttachmentOffset) || prop == &(attach->AttacherType)) { - getExtendedViewProvider()->signalChangeIcon(); // signal icon change + getExtendedViewProvider()->signalChangeIcon(); // signal icon change } } } - } void ViewProviderAttachExtension::extensionSetupContextMenu(QMenu* menu, QObject*, const char*) { - bool attach = getExtendedViewProvider()->getObject()->hasExtension(Part::AttachExtension::getExtensionClassTypeId()); + bool attach = getExtendedViewProvider()->getObject()->hasExtension( + Part::AttachExtension::getExtensionClassTypeId() + ); if (attach) { // toggle command to display components Gui::ActionFunction* func = new Gui::ActionFunction(menu); QAction* act = menu->addAction(QObject::tr("Attachment Editor")); - if (Gui::Control().activeDialog()) + if (Gui::Control().activeDialog()) { act->setDisabled(true); - func->trigger(act, [this](){ - this->showAttachmentEditor(); - }); + } + func->trigger(act, [this]() { this->showAttachmentEditor(); }); } } -void ViewProviderAttachExtension::showAttachmentEditor(std::function onAccept, std::function onReject) +void ViewProviderAttachExtension::showAttachmentEditor( + std::function onAccept, + std::function onReject +) { if (Gui::Control().activeDialog()) { Gui::Control().closeDialog(); @@ -115,9 +118,13 @@ void ViewProviderAttachExtension::showAttachmentEditor(std::function onA Gui::Control().showDialog(task); } -namespace Gui { - EXTENSION_PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProviderAttachExtensionPython, PartGui::ViewProviderAttachExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + PartGui::ViewProviderAttachExtensionPython, + PartGui::ViewProviderAttachExtension +) // explicit template instantiation - template class PartGuiExport ViewProviderExtensionPythonT; -} +template class PartGuiExport ViewProviderExtensionPythonT; +} // namespace Gui diff --git a/src/Mod/Part/Gui/ViewProviderAttachExtension.h b/src/Mod/Part/Gui/ViewProviderAttachExtension.h index 39718634a8..dbe2c16446 100644 --- a/src/Mod/Part/Gui/ViewProviderAttachExtension.h +++ b/src/Mod/Part/Gui/ViewProviderAttachExtension.h @@ -32,7 +32,7 @@ namespace PartGui { -class PartGuiExport ViewProviderAttachExtension : public Gui::ViewProviderExtension +class PartGuiExport ViewProviderAttachExtension: public Gui::ViewProviderExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderAttachExtension); @@ -41,7 +41,7 @@ public: ViewProviderAttachExtension(); ~ViewProviderAttachExtension() override = default; - QIcon extensionMergeColorfullOverlayIcons (const QIcon & orig) const override; + QIcon extensionMergeColorfullOverlayIcons(const QIcon& orig) const override; void extensionUpdateData(const App::Property*) override; void extensionSetupContextMenu(QMenu*, QObject*, const char*) override; @@ -49,8 +49,9 @@ public: void showAttachmentEditor(std::function onAccept = {}, std::function onReject = {}); }; -using ViewProviderAttachExtensionPython = Gui::ViewProviderExtensionPythonT; +using ViewProviderAttachExtensionPython + = Gui::ViewProviderExtensionPythonT; -} //namespace Part::Gui +} // namespace PartGui -#endif // GUI_VIEWPROVIDERATTACHMENTEXTENSION_H +#endif // GUI_VIEWPROVIDERATTACHMENTEXTENSION_H diff --git a/src/Mod/Part/Gui/ViewProviderBoolean.cpp b/src/Mod/Part/Gui/ViewProviderBoolean.cpp index 74ad431161..d7327ff218 100644 --- a/src/Mod/Part/Gui/ViewProviderBoolean.cpp +++ b/src/Mod/Part/Gui/ViewProviderBoolean.cpp @@ -23,9 +23,9 @@ ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include #include #include @@ -38,72 +38,75 @@ using namespace PartGui; -namespace { - // helper function for Boolean operation deletion with user confirmation - bool handleBooleanDeletion(const std::vector& subNames, - const QString& operationName, - const QString& objectLabel, - const std::vector& inputObjects, - const QString& inputDescription) - { - if (inputObjects.empty()) { - return true; - } - - // if we are in group deletion context it means user is deleting group that contains - // this boolean and they have accepted to delete all of the group objects recursively - // so delete everything automatically - bool inGroupDeletion = !subNames.empty() && subNames[0] == "group_recursive_deletion"; - if (inGroupDeletion) { - for (auto obj : inputObjects) { - if (obj && obj->isAttachedToDocument() && !obj->isRemoving()) { - obj->getDocument()->removeObject(obj->getNameInDocument()); - } - } - return true; - } - - QMessageBox::StandardButton choice = QMessageBox::question( - Gui::getMainWindow(), - QObject::tr("Delete %1 content?").arg(operationName), - QObject::tr("The %1 '%2' has %3. Do you want to delete them as well?") - .arg(operationName.toLower()) - .arg(objectLabel) - .arg(inputDescription), - QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, - QMessageBox::No - ); - - if (choice == QMessageBox::Cancel) { - return false; - } - - if (choice == QMessageBox::Yes) { - for (auto obj : inputObjects) { - if (obj && obj->isAttachedToDocument() && !obj->isRemoving()) { - obj->getDocument()->removeObject(obj->getNameInDocument()); - } - } - return true; - } - - for (auto obj : inputObjects) { - if (obj) { - Gui::Application::Instance->showViewProvider(obj); - } - } - +namespace +{ +// helper function for Boolean operation deletion with user confirmation +bool handleBooleanDeletion( + const std::vector& subNames, + const QString& operationName, + const QString& objectLabel, + const std::vector& inputObjects, + const QString& inputDescription +) +{ + if (inputObjects.empty()) { return true; } -} -PROPERTY_SOURCE(PartGui::ViewProviderBoolean,PartGui::ViewProviderPart) + // if we are in group deletion context it means user is deleting group that contains + // this boolean and they have accepted to delete all of the group objects recursively + // so delete everything automatically + bool inGroupDeletion = !subNames.empty() && subNames[0] == "group_recursive_deletion"; + if (inGroupDeletion) { + for (auto obj : inputObjects) { + if (obj && obj->isAttachedToDocument() && !obj->isRemoving()) { + obj->getDocument()->removeObject(obj->getNameInDocument()); + } + } + return true; + } + + QMessageBox::StandardButton choice = QMessageBox::question( + Gui::getMainWindow(), + QObject::tr("Delete %1 content?").arg(operationName), + QObject::tr("The %1 '%2' has %3. Do you want to delete them as well?") + .arg(operationName.toLower()) + .arg(objectLabel) + .arg(inputDescription), + QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, + QMessageBox::No + ); + + if (choice == QMessageBox::Cancel) { + return false; + } + + if (choice == QMessageBox::Yes) { + for (auto obj : inputObjects) { + if (obj && obj->isAttachedToDocument() && !obj->isRemoving()) { + obj->getDocument()->removeObject(obj->getNameInDocument()); + } + } + return true; + } + + for (auto obj : inputObjects) { + if (obj) { + Gui::Application::Instance->showViewProvider(obj); + } + } + + return true; +} +} // namespace + +PROPERTY_SOURCE(PartGui::ViewProviderBoolean, PartGui::ViewProviderPart) ViewProviderBoolean::ViewProviderBoolean() = default; ViewProviderBoolean::~ViewProviderBoolean() = default; -std::vector ViewProviderBoolean::claimChildren()const +std::vector ViewProviderBoolean::claimChildren() const { std::vector temp; temp.push_back(getObject()->Base.getValue()); @@ -117,14 +120,18 @@ QIcon ViewProviderBoolean::getIcon() const App::DocumentObject* obj = getObject(); if (obj) { Base::Type type = obj->getTypeId(); - if (type == Base::Type::fromName("Part::Common")) + if (type == Base::Type::fromName("Part::Common")) { return Gui::BitmapFactory().iconFromTheme("Part_Common"); - else if (type == Base::Type::fromName("Part::Fuse")) + } + else if (type == Base::Type::fromName("Part::Fuse")) { return Gui::BitmapFactory().iconFromTheme("Part_Fuse"); - else if (type == Base::Type::fromName("Part::Cut")) + } + else if (type == Base::Type::fromName("Part::Cut")) { return Gui::BitmapFactory().iconFromTheme("Part_Cut"); - else if (type == Base::Type::fromName("Part::Section")) + } + else if (type == Base::Type::fromName("Part::Section")) { return Gui::BitmapFactory().iconFromTheme("Part_Section"); + } } return ViewProviderPart::getIcon(); @@ -134,17 +141,21 @@ void ViewProviderBoolean::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - const std::vector& hist = static_cast - (prop)->getValues(); - if (hist.size() != 2) + const std::vector& hist + = static_cast(prop)->getValues(); + if (hist.size() != 2) { return; + } Part::Boolean* objBool = getObject(); - if (!objBool) + if (!objBool) { return; + } Part::Feature* objBase = dynamic_cast( - Part::Feature::getShapeOwner(objBool->Base.getValue())); + Part::Feature::getShapeOwner(objBool->Base.getValue()) + ); Part::Feature* objTool = dynamic_cast( - Part::Feature::getShapeOwner(objBool->Tool.getValue())); + Part::Feature::getShapeOwner(objBool->Tool.getValue()) + ); if (objBase && objTool) { const TopoDS_Shape& baseShape = objBase->Shape.getValue(); const TopoDS_Shape& toolShape = objTool->Shape.getValue(); @@ -156,16 +167,18 @@ void ViewProviderBoolean::updateData(const App::Property* prop) TopExp::MapShapes(boolShape, TopAbs_FACE, boolMap); auto vpBase = dynamic_cast( - Gui::Application::Instance->getViewProvider(objBase)); + Gui::Application::Instance->getViewProvider(objBase) + ); auto vpTool = dynamic_cast( - Gui::Application::Instance->getViewProvider(objTool)); + Gui::Application::Instance->getViewProvider(objTool) + ); if (vpBase && vpTool) { std::vector colBase = vpBase->ShapeAppearance.getValues(); std::vector colTool = vpTool->ShapeAppearance.getValues(); std::vector colBool; colBool.resize(boolMap.Extent(), this->ShapeAppearance[0]); - applyTransparency(vpBase->Transparency.getValue(),colBase); - applyTransparency(vpTool->Transparency.getValue(),colTool); + applyTransparency(vpBase->Transparency.getValue(), colBase); + applyTransparency(vpTool->Transparency.getValue(), colTool); if (static_cast(colBase.size()) == baseMap.Extent()) { applyMaterial(hist[0], colBase, colBool); @@ -194,18 +207,19 @@ void ViewProviderBoolean::updateData(const App::Property* prop) } } else if (prop->isDerivedFrom()) { - App::DocumentObject *pBase = static_cast(prop)->getValue(); - if (pBase) + App::DocumentObject* pBase = static_cast(prop)->getValue(); + if (pBase) { Gui::Application::Instance->hideViewProvider(pBase); + } } } -bool ViewProviderBoolean::onDelete(const std::vector &subNames) +bool ViewProviderBoolean::onDelete(const std::vector& subNames) { // get the input shapes Part::Boolean* pBool = getObject(); - App::DocumentObject *pBase = pBool->Base.getValue(); - App::DocumentObject *pTool = pBool->Tool.getValue(); + App::DocumentObject* pBase = pBool->Base.getValue(); + App::DocumentObject* pTool = pBool->Tool.getValue(); // Prepare input objects list and description std::vector inputObjects; @@ -216,30 +230,34 @@ bool ViewProviderBoolean::onDelete(const std::vector &subNames) if (pTool) { inputObjects.push_back(pTool); } - + QString inputDescription; if (pBase && pTool) { inputDescription = QObject::tr("base and tool objects"); - } else if (pBase) { + } + else if (pBase) { inputDescription = QObject::tr("base object"); - } else if (pTool) { + } + else if (pTool) { inputDescription = QObject::tr("tool object"); } - - return handleBooleanDeletion(subNames, - QObject::tr("Boolean operation"), - QString::fromUtf8(pBool->Label.getValue()), - inputObjects, - inputDescription); + + return handleBooleanDeletion( + subNames, + QObject::tr("Boolean operation"), + QString::fromUtf8(pBool->Label.getValue()), + inputObjects, + inputDescription + ); } -PROPERTY_SOURCE(PartGui::ViewProviderMultiFuse,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderMultiFuse, PartGui::ViewProviderPart) ViewProviderMultiFuse::ViewProviderMultiFuse() = default; ViewProviderMultiFuse::~ViewProviderMultiFuse() = default; -std::vector ViewProviderMultiFuse::claimChildren()const +std::vector ViewProviderMultiFuse::claimChildren() const { return getObject()->Shapes.getValues(); } @@ -253,12 +271,13 @@ void ViewProviderMultiFuse::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - const std::vector& hist = static_cast - (prop)->getValues(); + const std::vector& hist + = static_cast(prop)->getValues(); Part::MultiFuse* objBool = getObject(); std::vector sources = objBool->Shapes.getValues(); - if (hist.size() != sources.size()) + if (hist.size() != sources.size()) { return; + } const TopoDS_Shape& boolShape = objBool->Shape.getValue(); TopTools_IndexedMapOfShape boolMap; @@ -267,20 +286,24 @@ void ViewProviderMultiFuse::updateData(const App::Property* prop) std::vector colBool; colBool.resize(boolMap.Extent(), this->ShapeAppearance[0]); - int index=0; - for (std::vector::iterator it = sources.begin(); it != sources.end(); ++it, ++index) { + int index = 0; + for (std::vector::iterator it = sources.begin(); it != sources.end(); + ++it, ++index) { Part::Feature* objBase = dynamic_cast(Part::Feature::getShapeOwner(*it)); - if (!objBase) + if (!objBase) { continue; + } const TopoDS_Shape& baseShape = objBase->Shape.getValue(); TopTools_IndexedMapOfShape baseMap; TopExp::MapShapes(baseShape, TopAbs_FACE, baseMap); - auto vpBase = dynamic_cast(Gui::Application::Instance->getViewProvider(objBase)); + auto vpBase = dynamic_cast( + Gui::Application::Instance->getViewProvider(objBase) + ); if (vpBase) { std::vector colBase = vpBase->ShapeAppearance.getValues(); - applyTransparency(vpBase->Transparency.getValue(),colBase); + applyTransparency(vpBase->Transparency.getValue(), colBase); if (static_cast(colBase.size()) == baseMap.Extent()) { applyMaterial(hist[index], colBase, colBool); } @@ -300,7 +323,8 @@ void ViewProviderMultiFuse::updateData(const App::Property* prop) this->ShapeAppearance.setValues(colBool); } else if (prop->isDerivedFrom()) { - std::vector pShapes = static_cast(prop)->getValues(); + std::vector pShapes + = static_cast(prop)->getValues(); for (auto it : pShapes) { if (it) { Gui::Application::Instance->hideViewProvider(it); @@ -309,19 +333,21 @@ void ViewProviderMultiFuse::updateData(const App::Property* prop) } } -bool ViewProviderMultiFuse::onDelete(const std::vector &subNames) +bool ViewProviderMultiFuse::onDelete(const std::vector& subNames) { // get the input shapes Part::MultiFuse* pBool = getObject(); std::vector pShapes = pBool->Shapes.getValues(); - + QString inputDescription = QObject::tr("%1 input objects").arg(pShapes.size()); - - return handleBooleanDeletion(subNames, - QObject::tr("Fusion"), - QString::fromUtf8(pBool->Label.getValue()), - pShapes, - inputDescription); + + return handleBooleanDeletion( + subNames, + QObject::tr("Fusion"), + QString::fromUtf8(pBool->Label.getValue()), + pShapes, + inputDescription + ); } bool ViewProviderMultiFuse::canDragObjects() const @@ -369,13 +395,13 @@ void ViewProviderMultiFuse::dropObject(App::DocumentObject* obj) pBool->Shapes.setValues(pShapes); } -PROPERTY_SOURCE(PartGui::ViewProviderMultiCommon,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderMultiCommon, PartGui::ViewProviderPart) ViewProviderMultiCommon::ViewProviderMultiCommon() = default; ViewProviderMultiCommon::~ViewProviderMultiCommon() = default; -std::vector ViewProviderMultiCommon::claimChildren()const +std::vector ViewProviderMultiCommon::claimChildren() const { return getObject()->Shapes.getValues(); } @@ -389,12 +415,13 @@ void ViewProviderMultiCommon::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - const std::vector& hist = static_cast - (prop)->getValues(); + const std::vector& hist + = static_cast(prop)->getValues(); Part::MultiCommon* objBool = getObject(); std::vector sources = objBool->Shapes.getValues(); - if (hist.size() != sources.size()) + if (hist.size() != sources.size()) { return; + } const TopoDS_Shape& boolShape = objBool->Shape.getValue(); TopTools_IndexedMapOfShape boolMap; @@ -403,20 +430,24 @@ void ViewProviderMultiCommon::updateData(const App::Property* prop) std::vector colBool; colBool.resize(boolMap.Extent(), this->ShapeAppearance[0]); - int index=0; - for (std::vector::iterator it = sources.begin(); it != sources.end(); ++it, ++index) { + int index = 0; + for (std::vector::iterator it = sources.begin(); it != sources.end(); + ++it, ++index) { Part::Feature* objBase = dynamic_cast(Part::Feature::getShapeOwner(*it)); - if (!objBase) + if (!objBase) { continue; + } const TopoDS_Shape& baseShape = objBase->Shape.getValue(); TopTools_IndexedMapOfShape baseMap; TopExp::MapShapes(baseShape, TopAbs_FACE, baseMap); - auto vpBase = dynamic_cast(Gui::Application::Instance->getViewProvider(objBase)); + auto vpBase = dynamic_cast( + Gui::Application::Instance->getViewProvider(objBase) + ); if (vpBase) { std::vector colBase = vpBase->ShapeAppearance.getValues(); - applyTransparency(vpBase->Transparency.getValue(),colBase); + applyTransparency(vpBase->Transparency.getValue(), colBase); if (static_cast(colBase.size()) == baseMap.Extent()) { applyMaterial(hist[index], colBase, colBool); } @@ -436,7 +467,8 @@ void ViewProviderMultiCommon::updateData(const App::Property* prop) this->ShapeAppearance.setValues(colBool); } else if (prop->isDerivedFrom()) { - std::vector pShapes = static_cast(prop)->getValues(); + std::vector pShapes + = static_cast(prop)->getValues(); for (auto it : pShapes) { if (it) { Gui::Application::Instance->hideViewProvider(it); @@ -445,19 +477,21 @@ void ViewProviderMultiCommon::updateData(const App::Property* prop) } } -bool ViewProviderMultiCommon::onDelete(const std::vector &subNames) +bool ViewProviderMultiCommon::onDelete(const std::vector& subNames) { // get the input shapes Part::MultiCommon* pBool = getObject(); std::vector pShapes = pBool->Shapes.getValues(); - + QString inputDescription = QObject::tr("%1 input objects").arg(pShapes.size()); - - return handleBooleanDeletion(subNames, - QObject::tr("Intersection"), - QString::fromUtf8(pBool->Label.getValue()), - pShapes, - inputDescription); + + return handleBooleanDeletion( + subNames, + QObject::tr("Intersection"), + QString::fromUtf8(pBool->Label.getValue()), + pShapes, + inputDescription + ); } bool ViewProviderMultiCommon::canDragObjects() const @@ -504,4 +538,3 @@ void ViewProviderMultiCommon::dropObject(App::DocumentObject* obj) pShapes.push_back(obj); pBool->Shapes.setValues(pShapes); } - diff --git a/src/Mod/Part/Gui/ViewProviderBoolean.h b/src/Mod/Part/Gui/ViewProviderBoolean.h index 9eef04f875..cbe8e75609 100644 --- a/src/Mod/Part/Gui/ViewProviderBoolean.h +++ b/src/Mod/Part/Gui/ViewProviderBoolean.h @@ -31,9 +31,10 @@ #include "ViewProvider.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderBoolean : public ViewProviderPart +class PartGuiExport ViewProviderBoolean: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderBoolean); @@ -47,11 +48,11 @@ public: std::vector claimChildren() const override; QIcon getIcon() const override; void updateData(const App::Property*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; }; /// ViewProvider for the MultiFuse feature -class PartGuiExport ViewProviderMultiFuse : public ViewProviderPart +class PartGuiExport ViewProviderMultiFuse: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderMultiFuse); @@ -65,7 +66,7 @@ public: std::vector claimChildren() const override; QIcon getIcon() const override; void updateData(const App::Property*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; /// drag and drop bool canDragObjects() const override; @@ -77,7 +78,7 @@ public: }; /// ViewProvider for the MultiFuse feature -class PartGuiExport ViewProviderMultiCommon : public ViewProviderPart +class PartGuiExport ViewProviderMultiCommon: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderMultiCommon); @@ -91,7 +92,7 @@ public: std::vector claimChildren() const override; QIcon getIcon() const override; void updateData(const App::Property*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; /// drag and drop bool canDragObjects() const override; @@ -103,7 +104,7 @@ public: }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_ViewProviderBoolean_H +#endif // PARTGUI_ViewProviderBoolean_H diff --git a/src/Mod/Part/Gui/ViewProviderBox.cpp b/src/Mod/Part/Gui/ViewProviderBox.cpp index 77994e9c10..04e1e4d730 100644 --- a/src/Mod/Part/Gui/ViewProviderBox.cpp +++ b/src/Mod/Part/Gui/ViewProviderBox.cpp @@ -37,25 +37,24 @@ PROPERTY_SOURCE(PartGui::ViewProviderBox, PartGui::ViewProviderPrimitive) ViewProviderBox::ViewProviderBox() { - sPixmap = "Part_Box_Parametric"; + sPixmap = "Part_Box_Parametric"; } ViewProviderBox::~ViewProviderBox() = default; - // ********************************************************************************** std::vector ViewProviderBox::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderBox.h b/src/Mod/Part/Gui/ViewProviderBox.h index 6895bb8e0b..4fa22b82f0 100644 --- a/src/Mod/Part/Gui/ViewProviderBox.h +++ b/src/Mod/Part/Gui/ViewProviderBox.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderBox : public ViewProviderPrimitive +class PartGuiExport ViewProviderBox: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderBox); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERBOX_H - +#endif // PARTGUI_VIEWPROVIDERBOX_H diff --git a/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp b/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp index 090dc73da7..62078f333e 100644 --- a/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp @@ -37,23 +37,22 @@ PROPERTY_SOURCE(PartGui::ViewProviderCircleParametric, PartGui::ViewProviderPrim ViewProviderCircleParametric::ViewProviderCircleParametric() { - sPixmap = "Part_Circle_Parametric"; + sPixmap = "Part_Circle_Parametric"; } ViewProviderCircleParametric::~ViewProviderCircleParametric() = default; - // ********************************************************************************** std::vector ViewProviderCircleParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderCircleParametric.h b/src/Mod/Part/Gui/ViewProviderCircleParametric.h index d58c8bc4e5..b024d8ddbb 100644 --- a/src/Mod/Part/Gui/ViewProviderCircleParametric.h +++ b/src/Mod/Part/Gui/ViewProviderCircleParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderCircleParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderCircleParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCircleParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERCIRCLEPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERCIRCLEPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderCompound.cpp b/src/Mod/Part/Gui/ViewProviderCompound.cpp index 632396bb9e..3277fa6218 100644 --- a/src/Mod/Part/Gui/ViewProviderCompound.cpp +++ b/src/Mod/Part/Gui/ViewProviderCompound.cpp @@ -23,9 +23,9 @@ ***************************************************************************/ -# include -# include -# include +#include +#include +#include #include #include @@ -37,7 +37,7 @@ using namespace PartGui; -PROPERTY_SOURCE(PartGui::ViewProviderCompound,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderCompound, PartGui::ViewProviderPart) ViewProviderCompound::ViewProviderCompound() { @@ -51,17 +51,17 @@ std::vector ViewProviderCompound::claimChildren() const return getObject()->Links.getValues(); } -bool ViewProviderCompound::onDelete(const std::vector &subNames) +bool ViewProviderCompound::onDelete(const std::vector& subNames) { // get the input shapes Part::Compound* pComp = getObject(); std::vector pLinks = pComp->Links.getValues(); - + if (!pLinks.empty()) { // check group deletion marker -> it means group called this VP to delete it's content // so delete everything recursively bool inGroupDeletion = !subNames.empty() && subNames[0] == "group_recursive_deletion"; - + if (inGroupDeletion) { for (auto pLink : pLinks) { if (pLink && pLink->isAttachedToDocument() && !pLink->isRemoving()) { @@ -71,19 +71,19 @@ bool ViewProviderCompound::onDelete(const std::vector &subNames) return true; } QMessageBox::StandardButton choice = QMessageBox::question( - Gui::getMainWindow(), + Gui::getMainWindow(), QObject::tr("Delete compound content?"), QObject::tr("The compound '%1' has %2 child objects. Do you want to delete them as well?") .arg(QString::fromUtf8(pComp->Label.getValue())) .arg(pLinks.size()), - QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, + QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::No ); - + if (choice == QMessageBox::Cancel) { return false; } - + if (choice == QMessageBox::Yes) { for (auto pLink : pLinks) { if (pLink && pLink->isAttachedToDocument() && !pLink->isRemoving()) { @@ -94,8 +94,9 @@ bool ViewProviderCompound::onDelete(const std::vector &subNames) } for (auto pLink : pLinks) { - if (pLink) + if (pLink) { Gui::Application::Instance->showViewProvider(pLink); + } } } @@ -106,8 +107,8 @@ void ViewProviderCompound::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - const std::vector& hist = static_cast - (prop)->getValues(); + const std::vector& hist + = static_cast(prop)->getValues(); Part::Compound* objComp = getObject(); std::vector sources = objComp->Links.getValues(); @@ -128,8 +129,9 @@ void ViewProviderCompound::updateData(const App::Property* prop) sources = filter; } - if (hist.size() != sources.size()) + if (hist.size() != sources.size()) { return; + } const TopoDS_Shape& compShape = objComp->Shape.getValue(); TopTools_IndexedMapOfShape compMap; @@ -138,18 +140,22 @@ void ViewProviderCompound::updateData(const App::Property* prop) std::vector compCol; compCol.resize(compMap.Extent(), this->ShapeAppearance[0]); - int index=0; - for (std::vector::iterator it = sources.begin(); it != sources.end(); ++it, ++index) { + int index = 0; + for (std::vector::iterator it = sources.begin(); it != sources.end(); + ++it, ++index) { Part::Feature* objBase = dynamic_cast(Part::Feature::getShapeOwner(*it)); - if (!objBase) + if (!objBase) { continue; + } const TopoDS_Shape& baseShape = objBase->Shape.getValue(); TopTools_IndexedMapOfShape baseMap; TopExp::MapShapes(baseShape, TopAbs_FACE, baseMap); - auto vpBase = dynamic_cast(Gui::Application::Instance->getViewProvider(objBase)); + auto vpBase = dynamic_cast( + Gui::Application::Instance->getViewProvider(objBase) + ); if (vpBase) { std::vector baseCol = vpBase->ShapeAppearance.getValues(); applyTransparency(vpBase->Transparency.getValue(), baseCol); @@ -172,9 +178,12 @@ void ViewProviderCompound::updateData(const App::Property* prop) this->ShapeAppearance.setValues(compCol); } else if (prop->isDerivedFrom()) { - const std::vector& pBases = static_cast(prop)->getValues(); + const std::vector& pBases + = static_cast(prop)->getValues(); for (auto pBase : pBases) { - if (pBase) Gui::Application::Instance->hideViewProvider(pBase); + if (pBase) { + Gui::Application::Instance->hideViewProvider(pBase); + } } } } @@ -219,4 +228,3 @@ void ViewProviderCompound::dropObject(App::DocumentObject* obj) pShapes.push_back(obj); pComp->Links.setValues(pShapes); } - diff --git a/src/Mod/Part/Gui/ViewProviderCompound.h b/src/Mod/Part/Gui/ViewProviderCompound.h index ecbef4d110..a209ffc996 100644 --- a/src/Mod/Part/Gui/ViewProviderCompound.h +++ b/src/Mod/Part/Gui/ViewProviderCompound.h @@ -31,9 +31,10 @@ #include "ViewProvider.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderCompound : public ViewProviderPart +class PartGuiExport ViewProviderCompound: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCompound); @@ -43,7 +44,7 @@ public: /// destructor ~ViewProviderCompound() override; std::vector claimChildren() const override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; /// drag and drop bool canDragObjects() const override; @@ -57,7 +58,7 @@ protected: void updateData(const App::Property*) override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERCOMPOUND_H +#endif // PARTGUI_VIEWPROVIDERCOMPOUND_H diff --git a/src/Mod/Part/Gui/ViewProviderConeParametric.cpp b/src/Mod/Part/Gui/ViewProviderConeParametric.cpp index c8597ab9ab..0d93368b20 100644 --- a/src/Mod/Part/Gui/ViewProviderConeParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderConeParametric.cpp @@ -37,25 +37,24 @@ PROPERTY_SOURCE(PartGui::ViewProviderConeParametric, PartGui::ViewProviderPrimit ViewProviderConeParametric::ViewProviderConeParametric() { - sPixmap = "Part_Cone_Parametric"; + sPixmap = "Part_Cone_Parametric"; } ViewProviderConeParametric::~ViewProviderConeParametric() = default; - // ********************************************************************************** std::vector ViewProviderConeParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderConeParametric.h b/src/Mod/Part/Gui/ViewProviderConeParametric.h index 1712e8309e..700fb711e1 100644 --- a/src/Mod/Part/Gui/ViewProviderConeParametric.h +++ b/src/Mod/Part/Gui/ViewProviderConeParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderConeParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderConeParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderConeParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERCONEPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERCONEPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderCurveNet.cpp b/src/Mod/Part/Gui/ViewProviderCurveNet.cpp index ef89b8a72b..6da3a184fa 100644 --- a/src/Mod/Part/Gui/ViewProviderCurveNet.cpp +++ b/src/Mod/Part/Gui/ViewProviderCurveNet.cpp @@ -23,21 +23,21 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -54,7 +54,7 @@ using namespace PartGui; //************************************************************************** // Construction/Destruction -PROPERTY_SOURCE(PartGui::ViewProviderCurveNet,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderCurveNet, PartGui::ViewProviderPart) ViewProviderCurveNet::ViewProviderCurveNet() @@ -62,7 +62,8 @@ ViewProviderCurveNet::ViewProviderCurveNet() LineWidth.setValue(4.0f); PointSize.setValue(0.05f); /* - hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part"); + hGrp = App::GetApplication().GetParameterGroupByPath("User + parameter:BaseApp/Preferences/Mod/Part"); fMeshDeviation = hGrp->GetFloat("MeshDeviation",0.2); bNoPerVertexNormals = hGrp->GetBool("NoPerVertexNormals",false); @@ -73,10 +74,10 @@ ViewProviderCurveNet::ViewProviderCurveNet() ViewProviderCurveNet::~ViewProviderCurveNet() = default; -void ViewProviderCurveNet::attach(App::DocumentObject *pcFeat) +void ViewProviderCurveNet::attach(App::DocumentObject* pcFeat) { // call parent attach method - ViewProviderGeometryObject::attach(pcFeat); // clazy:exclude=skipped-base-method + ViewProviderGeometryObject::attach(pcFeat); // clazy:exclude=skipped-base-method // setup the root and material for the edges SoSeparator* ModeRoot = new SoSeparator(); @@ -89,7 +90,7 @@ void ViewProviderCurveNet::attach(App::DocumentObject *pcFeat) VertexRoot = new SoSeparator(); ModeRoot->addChild(VertexRoot); VertexRoot->addChild(pcPointMaterial); - SoComplexity *copl = new SoComplexity(); + SoComplexity* copl = new SoComplexity(); copl->value = (float)0.2; VertexRoot->addChild(copl); @@ -98,29 +99,32 @@ void ViewProviderCurveNet::attach(App::DocumentObject *pcFeat) void ViewProviderCurveNet::updateData(const App::Property* prop) { - Gui::ViewProviderGeometryObject::updateData(prop); // clazy:exclude=skipped-base-method + Gui::ViewProviderGeometryObject::updateData(prop); // clazy:exclude=skipped-base-method if (prop->is()) { TopoDS_Shape cShape = static_cast(prop)->getValue(); - if (cShape.IsNull()) + if (cShape.IsNull()) { return; + } Gui::coinRemoveAllChildren(EdgeRoot); Gui::coinRemoveAllChildren(VertexRoot); - try{ - computeEdges (EdgeRoot,cShape); - computeVertices(VertexRoot,cShape); + try { + computeEdges(EdgeRoot, cShape); + computeVertices(VertexRoot, cShape); } - catch (...){ - Base::Console().error("ViewProviderPart::create() Cannot compute Inventor representation for the actual shape"); + catch (...) { + Base::Console() + .error("ViewProviderPart::create() Cannot compute Inventor representation for the actual shape"); } } } void ViewProviderCurveNet::setDisplayMode(const char* ModeName) { - if ( strcmp("Edge",ModeName)==0 ) + if (strcmp("Edge", ModeName) == 0) { setDisplayMaskMode("Edge"); + } ViewProviderGeometryObject::setDisplayMode(ModeName); } @@ -142,7 +146,7 @@ bool ViewProviderCurveNet::setEdit(int) { bInEdit = true; return true; - //getWidget()->setCursor( QCursor( 13 /*ArrowCursor*/) ) + // getWidget()->setCursor( QCursor( 13 /*ArrowCursor*/) ) } void ViewProviderCurveNet::unsetEdit(int) @@ -150,7 +154,7 @@ void ViewProviderCurveNet::unsetEdit(int) bInEdit = false; } -bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInventorViewer &Viewer) +bool ViewProviderCurveNet::handleEvent(const SoEvent* const ev, Gui::View3DInventorViewer& Viewer) { SbVec3f point, norm; @@ -159,7 +163,7 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve // Keyboard events if (ev->getTypeId().isDerivedFrom(SoKeyboardEvent::getClassTypeId())) { - const SoKeyboardEvent * ke = static_cast(ev); + const SoKeyboardEvent* ke = static_cast(ev); switch (ke->getKey()) { case SoKeyboardEvent::LEFT_ALT: case SoKeyboardEvent::RIGHT_ALT: @@ -175,7 +179,7 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve // switching the mouse buttons if (ev->getTypeId().isDerivedFrom(SoMouseButtonEvent::getClassTypeId())) { - const SoMouseButtonEvent * const event = static_cast(ev); + const SoMouseButtonEvent* const event = static_cast(ev); const int button = event->getButton(); const SbBool press = event->getState() == SoButtonEvent::DOWN ? true : false; @@ -185,36 +189,32 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve if (press) { Base::Console().log("ViewProviderCurveNet::handleEvent() press left\n"); - bool bIsNode = false; - for (const auto & It : NodeList) - { - if (It.pcHighlight->isHighlighted()) - { + bool bIsNode = false; + for (const auto& It : NodeList) { + if (It.pcHighlight->isHighlighted()) { bIsNode = true; PointToMove = It; break; } } - if (bIsNode) - { + if (bIsNode) { // set the provider in point move mode and remember the point bMovePointMode = true; // PointToMove = *It; ### Error 'It' is out of scope->move inside the loop return true; } - else if(Viewer.pickPoint(pos,point,norm)) - { + else if (Viewer.pickPoint(pos, point, norm)) { Node n; - Base::Console().log("Picked(%f,%f,%f)\n",point[0],point[1],point[2]); + Base::Console().log("Picked(%f,%f,%f)\n", point[0], point[1], point[2]); - SoSeparator *TransRoot = new SoSeparator(); - n.pcTransform = new SoTransform(); + SoSeparator* TransRoot = new SoSeparator(); + n.pcTransform = new SoTransform(); TransRoot->addChild(n.pcTransform); n.pcTransform->translation.setValue(point); - n.pcHighlight = new Gui::SoFCSelection(); - SoSphere * sphere = new SoSphere; + n.pcHighlight = new Gui::SoFCSelection(); + SoSphere* sphere = new SoSphere; sphere->radius = (float)pcLineStyle->pointSize.getValue(); n.pcHighlight->addChild(sphere); TransRoot->addChild(n.pcHighlight); @@ -225,15 +225,14 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve return true; } } - else // if(pressd).. + else // if(pressd).. { - if (bMovePointMode) - { + if (bMovePointMode) { bMovePointMode = false; return true; } } - break; + break; } } @@ -241,7 +240,7 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve if (ev->getTypeId().isDerivedFrom(SoLocation2Event::getClassTypeId())) { // const SoLocation2Event * const event = (const SoLocation2Event *) ev; - if (bMovePointMode && Viewer.pickPoint(pos,point,norm) ){ + if (bMovePointMode && Viewer.pickPoint(pos, point, norm)) { PointToMove.pcTransform->translation.setValue(point); return true; } @@ -251,44 +250,42 @@ bool ViewProviderCurveNet::handleEvent(const SoEvent * const ev, Gui::View3DInve return false; } -Standard_Boolean ViewProviderCurveNet::computeEdges(SoSeparator* root, const TopoDS_Shape &myShape) +Standard_Boolean ViewProviderCurveNet::computeEdges(SoSeparator* root, const TopoDS_Shape& myShape) { unsigned long ulNbOfPoints = 50; TopExp_Explorer ex; - SoSeparator *EdgeRoot = new SoSeparator(); + SoSeparator* EdgeRoot = new SoSeparator(); root->addChild(EdgeRoot); EdgeRoot->addChild(pcLineStyle); EdgeRoot->addChild(pcLineMaterial); - for (ex.Init(myShape, TopAbs_EDGE); ex.More(); ex.Next()) - { + for (ex.Init(myShape, TopAbs_EDGE); ex.More(); ex.Next()) { // get the shape and mesh it const TopoDS_Edge& aEdge = TopoDS::Edge(ex.Current()); Standard_Real fBegin, fEnd; SbVec3f* vertices = new SbVec3f[ulNbOfPoints]; - Handle(Geom_Curve) hCurve = BRep_Tool::Curve(aEdge,fBegin,fEnd); - float fLen = float(fEnd - fBegin); + Handle(Geom_Curve) hCurve = BRep_Tool::Curve(aEdge, fBegin, fEnd); + float fLen = float(fEnd - fBegin); - for (unsigned long i = 0; i < ulNbOfPoints; i++) - { - gp_Pnt gpPt = hCurve->Value(fBegin + (fLen * float(i)) / float(ulNbOfPoints-1)); - vertices[i].setValue((float)(gpPt.X()),(float)(gpPt.Y()),(float)(gpPt.Z())); + for (unsigned long i = 0; i < ulNbOfPoints; i++) { + gp_Pnt gpPt = hCurve->Value(fBegin + (fLen * float(i)) / float(ulNbOfPoints - 1)); + vertices[i].setValue((float)(gpPt.X()), (float)(gpPt.Y()), (float)(gpPt.Z())); } // define vertices - SoCoordinate3 * coords = new SoCoordinate3; - coords->point.setValues(0,ulNbOfPoints, vertices); + SoCoordinate3* coords = new SoCoordinate3; + coords->point.setValues(0, ulNbOfPoints, vertices); EdgeRoot->addChild(coords); // define the indexed face set SoLocateHighlight* h = new SoLocateHighlight(); - h->color.setValue((float)0.2,(float)0.5,(float)0.2); + h->color.setValue((float)0.2, (float)0.5, (float)0.2); - SoLineSet * lineset = new SoLineSet; + SoLineSet* lineset = new SoLineSet; h->addChild(lineset); EdgeRoot->addChild(h); } @@ -296,33 +293,32 @@ Standard_Boolean ViewProviderCurveNet::computeEdges(SoSeparator* root, const Top return true; } -Standard_Boolean ViewProviderCurveNet::computeVertices(SoSeparator* root, const TopoDS_Shape &myShape) +Standard_Boolean ViewProviderCurveNet::computeVertices(SoSeparator* root, const TopoDS_Shape& myShape) { TopExp_Explorer ex; - SoSeparator *VertexRoot = new SoSeparator(); + SoSeparator* VertexRoot = new SoSeparator(); root->addChild(VertexRoot); VertexRoot->addChild(pcPointMaterial); - SoComplexity *copl = new SoComplexity(); + SoComplexity* copl = new SoComplexity(); copl->value = (float)0.2; VertexRoot->addChild(copl); - for (ex.Init(myShape, TopAbs_VERTEX); ex.More(); ex.Next()) - { + for (ex.Init(myShape, TopAbs_VERTEX); ex.More(); ex.Next()) { // get the shape const TopoDS_Vertex& aVertex = TopoDS::Vertex(ex.Current()); - gp_Pnt gpPt = BRep_Tool::Pnt (aVertex); + gp_Pnt gpPt = BRep_Tool::Pnt(aVertex); - SoSeparator *TransRoot = new SoSeparator(); - SoTransform *Trans = new SoTransform(); + SoSeparator* TransRoot = new SoSeparator(); + SoTransform* Trans = new SoTransform(); TransRoot->addChild(Trans); - Trans->translation.setValue((float)(gpPt.X()),(float)(gpPt.Y()),(float)(gpPt.Z())); + Trans->translation.setValue((float)(gpPt.X()), (float)(gpPt.Y()), (float)(gpPt.Z())); SoLocateHighlight* h = new SoLocateHighlight(); - h->color.setValue((float)0.2,(float)0.5,(float)0.2); + h->color.setValue((float)0.2, (float)0.5, (float)0.2); - SoSphere * sphere = new SoSphere; + SoSphere* sphere = new SoSphere; sphere->radius = (float)pcPointStyle->pointSize.getValue(); h->addChild(sphere); diff --git a/src/Mod/Part/Gui/ViewProviderCurveNet.h b/src/Mod/Part/Gui/ViewProviderCurveNet.h index db0a53bc80..cfc9c2c64b 100644 --- a/src/Mod/Part/Gui/ViewProviderCurveNet.h +++ b/src/Mod/Part/Gui/ViewProviderCurveNet.h @@ -37,15 +37,17 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace Gui { - class View3DInventorViewer; - class SoFCSelection; -} +namespace Gui +{ +class View3DInventorViewer; +class SoFCSelection; +} // namespace Gui -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderCurveNet:public ViewProviderPart +class PartGuiExport ViewProviderCurveNet: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPart); @@ -55,7 +57,7 @@ public: /// destructor ~ViewProviderCurveNet() override; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes std::vector getDisplayModes() const override; @@ -63,16 +65,18 @@ public: /// Update the Part representation void updateData(const App::Property*) override; - virtual bool handleEvent(const SoEvent * const ev,Gui::View3DInventorViewer &Viewer); + virtual bool handleEvent(const SoEvent* const ev, Gui::View3DInventorViewer& Viewer); protected: bool setEdit(int ModNum) override; void unsetEdit(int ModNum) override; - struct Node { - Gui::SoFCSelection *pcHighlight; - SoTransform *pcTransform; - Node() { + struct Node + { + Gui::SoFCSelection* pcHighlight; + SoTransform* pcTransform; + Node() + { pcHighlight = nullptr; pcTransform = nullptr; } @@ -80,18 +84,17 @@ protected: std::list NodeList; - bool bInEdit{false}; - bool bMovePointMode{false}; + bool bInEdit {false}; + bool bMovePointMode {false}; Node PointToMove; /// root of the edge and vertex points - SoSeparator *EdgeRoot{nullptr}, *VertexRoot{nullptr}; + SoSeparator *EdgeRoot {nullptr}, *VertexRoot {nullptr}; - Standard_Boolean computeEdges (SoSeparator* root, const TopoDS_Shape &myShape); - Standard_Boolean computeVertices(SoSeparator* root, const TopoDS_Shape &myShape); + Standard_Boolean computeEdges(SoSeparator* root, const TopoDS_Shape& myShape); + Standard_Boolean computeVertices(SoSeparator* root, const TopoDS_Shape& myShape); }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERCURVENET_H - +#endif // PARTGUI_VIEWPROVIDERCURVENET_H diff --git a/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp b/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp index 12d9682364..31dd4513c5 100644 --- a/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp @@ -37,25 +37,24 @@ PROPERTY_SOURCE(PartGui::ViewProviderCylinderParametric, PartGui::ViewProviderPr ViewProviderCylinderParametric::ViewProviderCylinderParametric() { - sPixmap = "Part_Cylinder_Parametric"; + sPixmap = "Part_Cylinder_Parametric"; } ViewProviderCylinderParametric::~ViewProviderCylinderParametric() = default; - // ********************************************************************************** std::vector ViewProviderCylinderParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderCylinderParametric.h b/src/Mod/Part/Gui/ViewProviderCylinderParametric.h index 23a6543c80..f5ac5f226c 100644 --- a/src/Mod/Part/Gui/ViewProviderCylinderParametric.h +++ b/src/Mod/Part/Gui/ViewProviderCylinderParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderCylinderParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderCylinderParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCylinderParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERCYLINDERPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERCYLINDERPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderDatum.h b/src/Mod/Part/Gui/ViewProviderDatum.h index 15166a0725..6e640fc8ba 100644 --- a/src/Mod/Part/Gui/ViewProviderDatum.h +++ b/src/Mod/Part/Gui/ViewProviderDatum.h @@ -36,9 +36,11 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderLine : public Gui::ViewProviderLine, PartGui::ViewProviderAttachExtension +class PartGuiExport ViewProviderLine: public Gui::ViewProviderLine, + PartGui::ViewProviderAttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(PartGui::ViewProviderLine); @@ -49,7 +51,8 @@ public: bool doubleClicked() override; }; -class PartGuiExport ViewProviderPlane : public Gui::ViewProviderPlane, PartGui::ViewProviderAttachExtension +class PartGuiExport ViewProviderPlane: public Gui::ViewProviderPlane, + PartGui::ViewProviderAttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(PartGui::ViewProviderPlane); @@ -60,7 +63,8 @@ public: bool doubleClicked() override; }; -class PartGuiExport ViewProviderPoint : public Gui::ViewProviderPoint, PartGui::ViewProviderAttachExtension +class PartGuiExport ViewProviderPoint: public Gui::ViewProviderPoint, + PartGui::ViewProviderAttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(PartGui::ViewProviderPoint); @@ -71,7 +75,8 @@ public: bool doubleClicked() override; }; -class PartGuiExport ViewProviderLCS : public Gui::ViewProviderCoordinateSystem, PartGui::ViewProviderAttachExtension +class PartGuiExport ViewProviderLCS: public Gui::ViewProviderCoordinateSystem, + PartGui::ViewProviderAttachExtension { PROPERTY_HEADER_WITH_EXTENSIONS(PartGui::ViewProviderLCS); @@ -82,7 +87,7 @@ public: bool doubleClicked() override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_ViewProviderDatum_H +#endif // PARTGUI_ViewProviderDatum_H diff --git a/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp b/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp index 2a3b6784cd..edab3e3c66 100644 --- a/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp @@ -37,23 +37,22 @@ PROPERTY_SOURCE(PartGui::ViewProviderEllipseParametric, PartGui::ViewProviderPri ViewProviderEllipseParametric::ViewProviderEllipseParametric() { - sPixmap = "Part_Ellipse_Parametric"; + sPixmap = "Part_Ellipse_Parametric"; } ViewProviderEllipseParametric::~ViewProviderEllipseParametric() = default; - // ********************************************************************************** std::vector ViewProviderEllipseParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderEllipseParametric.h b/src/Mod/Part/Gui/ViewProviderEllipseParametric.h index 8f238d2e18..bbaea3316a 100644 --- a/src/Mod/Part/Gui/ViewProviderEllipseParametric.h +++ b/src/Mod/Part/Gui/ViewProviderEllipseParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderEllipseParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderEllipseParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderEllipseParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERELLIPSEPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERELLIPSEPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderExt.cpp b/src/Mod/Part/Gui/ViewProviderExt.cpp index 9839bfb630..9bdddf99c5 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.cpp +++ b/src/Mod/Part/Gui/ViewProviderExt.cpp @@ -22,51 +22,51 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include -# include +#include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include +#include #include #include @@ -103,11 +103,12 @@ PROPERTY_SOURCE(PartGui::ViewProviderPartExt, Gui::ViewProviderGeometryObject) //************************************************************************** // Construction/Destruction -App::PropertyFloatConstraint::Constraints ViewProviderPartExt::sizeRange = {1.0,64.0,1.0}; -App::PropertyFloatConstraint::Constraints ViewProviderPartExt::tessRange = {0.01,100.0,0.01}; -App::PropertyQuantityConstraint::Constraints ViewProviderPartExt::angDeflectionRange = {1.0,180.0,0.05}; -const char* ViewProviderPartExt::LightingEnums[]= {"One side","Two side",nullptr}; -const char* ViewProviderPartExt::DrawStyleEnums[]= {"Solid","Dashed","Dotted","Dashdot",nullptr}; +App::PropertyFloatConstraint::Constraints ViewProviderPartExt::sizeRange = {1.0, 64.0, 1.0}; +App::PropertyFloatConstraint::Constraints ViewProviderPartExt::tessRange = {0.01, 100.0, 0.01}; +App::PropertyQuantityConstraint::Constraints ViewProviderPartExt::angDeflectionRange + = {1.0, 180.0, 0.05}; +const char* ViewProviderPartExt::LightingEnums[] = {"One side", "Two side", nullptr}; +const char* ViewProviderPartExt::DrawStyleEnums[] = {"Solid", "Dashed", "Dotted", "Dashdot", nullptr}; ViewProviderPartExt::ViewProviderPartExt() { @@ -118,20 +119,25 @@ ViewProviderPartExt::ViewProviderPartExt() NormalsFromUV = true; // get default line color - unsigned long lcol = Gui::ViewParams::instance()->getDefaultShapeLineColor(); // dark grey (25,25,25) - float lr,lg,lb; - lr = ((lcol >> 24) & 0xff) / 255.0; lg = ((lcol >> 16) & 0xff) / 255.0; lb = ((lcol >> 8) & 0xff) / 255.0; + unsigned long lcol = Gui::ViewParams::instance()->getDefaultShapeLineColor(); // dark grey + // (25,25,25) + float lr, lg, lb; + lr = ((lcol >> 24) & 0xff) / 255.0; + lg = ((lcol >> 16) & 0xff) / 255.0; + lb = ((lcol >> 8) & 0xff) / 255.0; // get default vertex color unsigned long vcol = Gui::ViewParams::instance()->getDefaultShapeVertexColor(); - float vr,vg,vb; - vr = ((vcol >> 24) & 0xff) / 255.0; vg = ((vcol >> 16) & 0xff) / 255.0; vb = ((vcol >> 8) & 0xff) / 255.0; + float vr, vg, vb; + vr = ((vcol >> 24) & 0xff) / 255.0; + vg = ((vcol >> 16) & 0xff) / 255.0; + vb = ((vcol >> 8) & 0xff) / 255.0; int lwidth = Gui::ViewParams::instance()->getDefaultShapeLineWidth(); int psize = Gui::ViewParams::instance()->getDefaultShapePointSize(); - - ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Mod/Part"); + ParameterGrp::handle hPart = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part" + ); NormalsFromUV = hPart->GetBool("NormalsFromUVNodes", NormalsFromUV); long twoside = hPart->GetBool("TwoSideRendering", true) ? 1 : 0; @@ -142,49 +148,83 @@ ViewProviderPartExt::ViewProviderPartExt() lowerLimit = std::max(lowerLimit, Precision::Confusion()); tessRange.LowerBound = lowerLimit; - static const char *osgroup = "Object Style"; + static const char* osgroup = "Object Style"; App::Material lmat; - lmat.ambientColor.set(0.2f,0.2f,0.2f); - lmat.diffuseColor.set(lr,lg,lb); - lmat.specularColor.set(0.0f,0.0f,0.0f); - lmat.emissiveColor.set(0.0f,0.0f,0.0f); + lmat.ambientColor.set(0.2f, 0.2f, 0.2f); + lmat.diffuseColor.set(lr, lg, lb); + lmat.specularColor.set(0.0f, 0.0f, 0.0f); + lmat.emissiveColor.set(0.0f, 0.0f, 0.0f); lmat.shininess = 1.0f; lmat.transparency = 0.0f; App::Material vmat; - vmat.ambientColor.set(0.2f,0.2f,0.2f); - vmat.diffuseColor.set(vr,vg,vb); - vmat.specularColor.set(0.0f,0.0f,0.0f); - vmat.emissiveColor.set(0.0f,0.0f,0.0f); + vmat.ambientColor.set(0.2f, 0.2f, 0.2f); + vmat.diffuseColor.set(vr, vg, vb); + vmat.specularColor.set(0.0f, 0.0f, 0.0f); + vmat.emissiveColor.set(0.0f, 0.0f, 0.0f); vmat.shininess = 1.0f; vmat.transparency = 0.0f; - ADD_PROPERTY_TYPE(LineMaterial,(lmat), osgroup, App::Prop_None, "Object line material."); - ADD_PROPERTY_TYPE(PointMaterial,(vmat), osgroup, App::Prop_None, "Object point material."); + ADD_PROPERTY_TYPE(LineMaterial, (lmat), osgroup, App::Prop_None, "Object line material."); + ADD_PROPERTY_TYPE(PointMaterial, (vmat), osgroup, App::Prop_None, "Object point material."); ADD_PROPERTY_TYPE(LineColor, (lmat.diffuseColor), osgroup, App::Prop_None, "Set object line color."); ADD_PROPERTY_TYPE(PointColor, (vmat.diffuseColor), osgroup, App::Prop_None, "Set object point color"); - ADD_PROPERTY_TYPE(PointColorArray, (PointColor.getValue()), osgroup, App::Prop_None, "Object point color array."); - ADD_PROPERTY_TYPE(LineColorArray,(LineColor.getValue()), osgroup, App::Prop_None, "Object line color array."); - ADD_PROPERTY_TYPE(LineWidth,(lwidth), osgroup, App::Prop_None, "Set object line width."); + ADD_PROPERTY_TYPE( + PointColorArray, + (PointColor.getValue()), + osgroup, + App::Prop_None, + "Object point color array." + ); + ADD_PROPERTY_TYPE( + LineColorArray, + (LineColor.getValue()), + osgroup, + App::Prop_None, + "Object line color array." + ); + ADD_PROPERTY_TYPE(LineWidth, (lwidth), osgroup, App::Prop_None, "Set object line width."); LineWidth.setConstraints(&sizeRange); PointSize.setConstraints(&sizeRange); - ADD_PROPERTY_TYPE(PointSize,(psize), osgroup, App::Prop_None, "Set object point size."); - ADD_PROPERTY_TYPE(Deviation,(0.5f), osgroup, App::Prop_None, - "Sets the accuracy of the polygonal representation of the model\n" - "in the 3D view (tessellation). Lower values indicate better quality.\n" - "The value is in percent of object's size."); + ADD_PROPERTY_TYPE(PointSize, (psize), osgroup, App::Prop_None, "Set object point size."); + ADD_PROPERTY_TYPE( + Deviation, + (0.5f), + osgroup, + App::Prop_None, + "Sets the accuracy of the polygonal representation of the model\n" + "in the 3D view (tessellation). Lower values indicate better quality.\n" + "The value is in percent of object's size." + ); Deviation.setConstraints(&tessRange); - ADD_PROPERTY_TYPE(AngularDeflection,(28.5), osgroup, App::Prop_None, - "Specify how finely to generate the mesh for rendering on screen or when exporting.\n" - "The default value is 28.5 degrees, or 0.5 radians. The smaller the value\n" - "the smoother the appearance in the 3D view, and the finer the mesh that will be exported."); + ADD_PROPERTY_TYPE( + AngularDeflection, + (28.5), + osgroup, + App::Prop_None, + "Specify how finely to generate the mesh for rendering on screen or when exporting.\n" + "The default value is 28.5 degrees, or 0.5 radians. The smaller the value\n" + "the smoother the appearance in the 3D view, and the finer the mesh that will be exported." + ); AngularDeflection.setConstraints(&angDeflectionRange); - ADD_PROPERTY_TYPE(Lighting,(twoside), osgroup, App::Prop_None, "Set object lighting."); + ADD_PROPERTY_TYPE(Lighting, (twoside), osgroup, App::Prop_None, "Set object lighting."); Lighting.setEnums(LightingEnums); - ADD_PROPERTY_TYPE(DrawStyle,((long int)0), osgroup, App::Prop_None, "Defines the style of the edges in the 3D view."); + ADD_PROPERTY_TYPE( + DrawStyle, + ((long int)0), + osgroup, + App::Prop_None, + "Defines the style of the edges in the 3D view." + ); DrawStyle.setEnums(DrawStyleEnums); - ADD_PROPERTY_TYPE(ShowPlacement,(false), "Display Options", App::Prop_None, "If true, placement of object is additionally rendered."); + ADD_PROPERTY_TYPE( + ShowPlacement, + (false), + "Display Options", + App::Prop_None, + "If true, placement of object is additionally rendered." + ); coords = new SoCoordinate3(); coords->ref(); @@ -278,16 +318,20 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) // to freeze the GUI // https://forum.freecad.org/viewtopic.php?f=3&t=24912&p=195613 if (prop == &Deviation) { - if(isUpdateForced()||Visibility.getValue()) + if (isUpdateForced() || Visibility.getValue()) { updateVisual(); - else + } + else { VisualTouched = true; + } } if (prop == &AngularDeflection) { - if(isUpdateForced()||Visibility.getValue()) + if (isUpdateForced() || Visibility.getValue()) { updateVisual(); - else + } + else { VisualTouched = true; + } } if (prop == &LineWidth) { pcLineStyle->lineWidth = LineWidth.getValue(); @@ -297,37 +341,49 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) } else if (prop == &LineColor) { const Base::Color& c = LineColor.getValue(); - pcLineMaterial->diffuseColor.setValue(c.r,c.g,c.b); - if (c != LineMaterial.getValue().diffuseColor) + pcLineMaterial->diffuseColor.setValue(c.r, c.g, c.b); + if (c != LineMaterial.getValue().diffuseColor) { LineMaterial.setDiffuseColor(c); + } LineColorArray.setValue(LineColor.getValue()); } else if (prop == &PointColor) { const Base::Color& c = PointColor.getValue(); - pcPointMaterial->diffuseColor.setValue(c.r,c.g,c.b); - if (c != PointMaterial.getValue().diffuseColor) + pcPointMaterial->diffuseColor.setValue(c.r, c.g, c.b); + if (c != PointMaterial.getValue().diffuseColor) { PointMaterial.setDiffuseColor(c); + } PointColorArray.setValue(PointColor.getValue()); } else if (prop == &LineMaterial) { const App::Material& Mat = LineMaterial.getValue(); - if (LineColor.getValue() != Mat.diffuseColor) + if (LineColor.getValue() != Mat.diffuseColor) { LineColor.setValue(Mat.diffuseColor); - pcLineMaterial->ambientColor.setValue(Mat.ambientColor.r,Mat.ambientColor.g,Mat.ambientColor.b); - pcLineMaterial->diffuseColor.setValue(Mat.diffuseColor.r,Mat.diffuseColor.g,Mat.diffuseColor.b); - pcLineMaterial->specularColor.setValue(Mat.specularColor.r,Mat.specularColor.g,Mat.specularColor.b); - pcLineMaterial->emissiveColor.setValue(Mat.emissiveColor.r,Mat.emissiveColor.g,Mat.emissiveColor.b); + } + pcLineMaterial->ambientColor + .setValue(Mat.ambientColor.r, Mat.ambientColor.g, Mat.ambientColor.b); + pcLineMaterial->diffuseColor + .setValue(Mat.diffuseColor.r, Mat.diffuseColor.g, Mat.diffuseColor.b); + pcLineMaterial->specularColor + .setValue(Mat.specularColor.r, Mat.specularColor.g, Mat.specularColor.b); + pcLineMaterial->emissiveColor + .setValue(Mat.emissiveColor.r, Mat.emissiveColor.g, Mat.emissiveColor.b); pcLineMaterial->shininess.setValue(Mat.shininess); pcLineMaterial->transparency.setValue(Mat.transparency); } else if (prop == &PointMaterial) { const App::Material& Mat = PointMaterial.getValue(); - if (PointColor.getValue() != Mat.diffuseColor) + if (PointColor.getValue() != Mat.diffuseColor) { PointColor.setValue(Mat.diffuseColor); - pcPointMaterial->ambientColor.setValue(Mat.ambientColor.r,Mat.ambientColor.g,Mat.ambientColor.b); - pcPointMaterial->diffuseColor.setValue(Mat.diffuseColor.r,Mat.diffuseColor.g,Mat.diffuseColor.b); - pcPointMaterial->specularColor.setValue(Mat.specularColor.r,Mat.specularColor.g,Mat.specularColor.b); - pcPointMaterial->emissiveColor.setValue(Mat.emissiveColor.r,Mat.emissiveColor.g,Mat.emissiveColor.b); + } + pcPointMaterial->ambientColor + .setValue(Mat.ambientColor.r, Mat.ambientColor.g, Mat.ambientColor.b); + pcPointMaterial->diffuseColor + .setValue(Mat.diffuseColor.r, Mat.diffuseColor.g, Mat.diffuseColor.b); + pcPointMaterial->specularColor + .setValue(Mat.specularColor.r, Mat.specularColor.g, Mat.specularColor.b); + pcPointMaterial->emissiveColor + .setValue(Mat.emissiveColor.r, Mat.emissiveColor.g, Mat.emissiveColor.b); pcPointMaterial->shininess.setValue(Mat.shininess); pcPointMaterial->transparency.setValue(Mat.transparency); } @@ -362,23 +418,31 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) } } else if (prop == &Lighting) { - if (Lighting.getValue() == 0) + if (Lighting.getValue() == 0) { pShapeHints->vertexOrdering = SoShapeHints::UNKNOWN_ORDERING; - else + } + else { pShapeHints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE; + } } else if (prop == &DrawStyle) { - if (DrawStyle.getValue() == 0) + if (DrawStyle.getValue() == 0) { pcLineStyle->linePattern = 0xffff; - else if (DrawStyle.getValue() == 1) + } + else if (DrawStyle.getValue() == 1) { pcLineStyle->linePattern = 0xf00f; - else if (DrawStyle.getValue() == 2) + } + else if (DrawStyle.getValue() == 2) { pcLineStyle->linePattern = 0x0f0f; - else + } + else { pcLineStyle->linePattern = 0xff88; + } } else if (prop == &ShowPlacement) { - pcPlacement->whichChild = (ShowPlacement.getValue() && Visibility.getValue()) ? SO_SWITCH_ALL : SO_SWITCH_NONE; + pcPlacement->whichChild = (ShowPlacement.getValue() && Visibility.getValue()) + ? SO_SWITCH_ALL + : SO_SWITCH_NONE; } else { // if the object was invisible and has been changed, recreate the visual @@ -388,8 +452,10 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) // triggered by an external object through forceUpdate()). And // since ShapeAppearance is not changed here either, do not falsely set // the document modified status - Base::ObjectStatusLocker guard( - App::Property::NoModify, &ShapeAppearance); + Base::ObjectStatusLocker guard( + App::Property::NoModify, + &ShapeAppearance + ); // The material has to be checked again (#0001736) onChanged(&ShapeAppearance); onChanged(&ShowPlacement); @@ -399,13 +465,14 @@ void ViewProviderPartExt::onChanged(const App::Property* prop) ViewProviderGeometryObject::onChanged(prop); } -bool ViewProviderPartExt::allowOverride(const App::DocumentObject &) const { +bool ViewProviderPartExt::allowOverride(const App::DocumentObject&) const +{ // Many derived view providers still uses static_cast to get object // pointer, so check for exact type here. return is(); } -void ViewProviderPartExt::attach(App::DocumentObject *pcFeat) +void ViewProviderPartExt::attach(App::DocumentObject* pcFeat) { // call parent attach method ViewProviderGeometryObject::attach(pcFeat); @@ -423,17 +490,11 @@ void ViewProviderPartExt::attach(App::DocumentObject *pcFeat) // Must turn off all intermediate render caching, and let pcRoot to handle // cache without interference. - pcNormalRoot->renderCaching = - pcFlatRoot->renderCaching = - pcWireframeRoot->renderCaching = - pcPointsRoot->renderCaching = - wireframe->renderCaching = SoSeparator::OFF; + pcNormalRoot->renderCaching = pcFlatRoot->renderCaching = pcWireframeRoot->renderCaching + = pcPointsRoot->renderCaching = wireframe->renderCaching = SoSeparator::OFF; - pcNormalRoot->boundingBoxCaching = - pcFlatRoot->boundingBoxCaching = - pcWireframeRoot->boundingBoxCaching = - pcPointsRoot->boundingBoxCaching = - wireframe->boundingBoxCaching = SoSeparator::OFF; + pcNormalRoot->boundingBoxCaching = pcFlatRoot->boundingBoxCaching = pcWireframeRoot->boundingBoxCaching + = pcPointsRoot->boundingBoxCaching = wireframe->boundingBoxCaching = SoSeparator::OFF; // Avoid any Z-buffer artifacts, so that the lines always appear on top of the faces // The correct order is Edges, Polygon offset, Faces. @@ -476,7 +537,7 @@ void ViewProviderPartExt::attach(App::DocumentObject *pcFeat) pcPointsRoot->addChild(nodeset); // Move 'coords' before the switch - pcRoot->insertChild(coords,pcRoot->findChild(pcModeSwitch)); + pcRoot->insertChild(coords, pcRoot->findChild(pcModeSwitch)); // putting all together with the switch addDisplayMaskMode(pcNormalRoot, "Flat Lines"); @@ -487,16 +548,20 @@ void ViewProviderPartExt::attach(App::DocumentObject *pcFeat) void ViewProviderPartExt::setDisplayMode(const char* ModeName) { - if ( strcmp("Flat Lines",ModeName)==0 ) + if (strcmp("Flat Lines", ModeName) == 0) { setDisplayMaskMode("Flat Lines"); - else if ( strcmp("Shaded",ModeName)==0 ) + } + else if (strcmp("Shaded", ModeName) == 0) { setDisplayMaskMode("Shaded"); - else if ( strcmp("Wireframe",ModeName)==0 ) + } + else if (strcmp("Wireframe", ModeName) == 0) { setDisplayMaskMode("Wireframe"); - else if ( strcmp("Points",ModeName)==0 ) + } + else if (strcmp("Points", ModeName) == 0) { setDisplayMaskMode("Point"); + } - ViewProviderGeometryObject::setDisplayMode( ModeName ); + ViewProviderGeometryObject::setDisplayMode(ModeName); } std::vector ViewProviderPartExt::getDisplayModes() const @@ -555,7 +620,9 @@ SoDetail* ViewProviderPartExt::getDetail(const char* subelement) const } else if (element == "Vertex") { SoPointDetail* detail = new SoPointDetail(); - static_cast(detail)->setCoordinateIndex(index + nodeset->startIndex.getValue() - 1); + static_cast(detail)->setCoordinateIndex( + index + nodeset->startIndex.getValue() - 1 + ); return detail; } @@ -567,7 +634,7 @@ std::vector ViewProviderPartExt::getModelPoints(const SoPickedPo try { std::vector pts; std::string element = this->getElement(pp->getDetail()); - const auto &shape = getRenderedShape(); + const auto& shape = getRenderedShape(); TopoDS_Shape subShape = shape.getSubShape(element.c_str()); @@ -575,26 +642,26 @@ std::vector ViewProviderPartExt::getModelPoints(const SoPickedPo if (subShape.ShapeType() == TopAbs_VERTEX) { const TopoDS_Vertex& v = TopoDS::Vertex(subShape); gp_Pnt p = BRep_Tool::Pnt(v); - pts.emplace_back(p.X(),p.Y(),p.Z()); + pts.emplace_back(p.X(), p.Y(), p.Z()); } // get the nearest point on the edge else if (subShape.ShapeType() == TopAbs_EDGE) { const SbVec3f& vec = pp->getPoint(); - BRepBuilderAPI_MakeVertex mkVert(gp_Pnt(vec[0],vec[1],vec[2])); + BRepBuilderAPI_MakeVertex mkVert(gp_Pnt(vec[0], vec[1], vec[2])); BRepExtrema_DistShapeShape distSS(subShape, mkVert.Vertex(), 0.1); if (distSS.NbSolution() > 0) { gp_Pnt p = distSS.PointOnShape1(1); - pts.emplace_back(p.X(),p.Y(),p.Z()); + pts.emplace_back(p.X(), p.Y(), p.Z()); } } // get the nearest point on the face else if (subShape.ShapeType() == TopAbs_FACE) { const SbVec3f& vec = pp->getPoint(); - BRepBuilderAPI_MakeVertex mkVert(gp_Pnt(vec[0],vec[1],vec[2])); + BRepBuilderAPI_MakeVertex mkVert(gp_Pnt(vec[0], vec[1], vec[2])); BRepExtrema_DistShapeShape distSS(subShape, mkVert.Vertex(), 0.1); if (distSS.NbSolution() > 0) { gp_Pnt p = distSS.PointOnShape1(1); - pts.emplace_back(p.X(),p.Y(),p.Z()); + pts.emplace_back(p.X(), p.Y(), p.Z()); } } @@ -614,8 +681,9 @@ std::vector ViewProviderPartExt::getSelectionShape(const char* / void ViewProviderPartExt::setHighlightedFaces(const std::vector& materials) { - if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) + if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) { getObject()->touch(true); + } Gui::SoUpdateVBOAction action; action.apply(this->faceset); @@ -640,10 +708,26 @@ void ViewProviderPartExt::setHighlightedFaces(const std::vector& float* tr = pcShapeMaterial->transparency.startEditing(); for (int i = 0; i < size; i++) { - dc[i].setValue(materials[i].diffuseColor.r, materials[i].diffuseColor.g, materials[i].diffuseColor.b); - ac[i].setValue(materials[i].ambientColor.r, materials[i].ambientColor.g, materials[i].ambientColor.b); - sc[i].setValue(materials[i].specularColor.r, materials[i].specularColor.g, materials[i].specularColor.b); - ec[i].setValue(materials[i].emissiveColor.r, materials[i].emissiveColor.g, materials[i].emissiveColor.b); + dc[i].setValue( + materials[i].diffuseColor.r, + materials[i].diffuseColor.g, + materials[i].diffuseColor.b + ); + ac[i].setValue( + materials[i].ambientColor.r, + materials[i].ambientColor.g, + materials[i].ambientColor.b + ); + sc[i].setValue( + materials[i].specularColor.r, + materials[i].specularColor.g, + materials[i].specularColor.b + ); + ec[i].setValue( + materials[i].emissiveColor.r, + materials[i].emissiveColor.g, + materials[i].emissiveColor.b + ); sh[i] = materials[i].shininess; tr[i] = materials[i].transparency; } @@ -666,10 +750,11 @@ void ViewProviderPartExt::setHighlightedFaces(const App::PropertyMaterialList& a setHighlightedFaces(appearance.getValues()); } -std::map ViewProviderPartExt::getElementColors(const char *element) const { - std::map ret; +std::map ViewProviderPartExt::getElementColors(const char* element) const +{ + std::map ret; - if(!element || !element[0]) { + if (!element || !element[0]) { auto color = ShapeAppearance.getDiffuseColor(); color.setTransparency(Base::fromPercent(Transparency.getValue())); ret["Face"] = color; @@ -678,9 +763,9 @@ std::map ViewProviderPartExt::getElementColors(const ch return ret; } - if(boost::starts_with(element,"Face")) { + if (boost::starts_with(element, "Face")) { auto size = ShapeAppearance.getSize(); - if(element[4]=='*') { + if (element[4] == '*') { auto color = ShapeAppearance.getDiffuseColor(); color.setTransparency(Base::fromPercent(Transparency.getValue())); bool singleColor = true; @@ -700,58 +785,72 @@ std::map ViewProviderPartExt::getElementColors(const ch ret.clear(); } ret["Face"] = color; - }else{ - int idx = atoi(element+4); - if(idx>0 && idx<=size) - ret[element] = ShapeAppearance.getDiffuseColor(idx - 1); - else - ret[element] = ShapeAppearance.getDiffuseColor(); - if(size==1) - ret[element].setTransparency(Base::fromPercent(Transparency.getValue())); } - } else if (boost::starts_with(element,"Edge")) { + else { + int idx = atoi(element + 4); + if (idx > 0 && idx <= size) { + ret[element] = ShapeAppearance.getDiffuseColor(idx - 1); + } + else { + ret[element] = ShapeAppearance.getDiffuseColor(); + } + if (size == 1) { + ret[element].setTransparency(Base::fromPercent(Transparency.getValue())); + } + } + } + else if (boost::starts_with(element, "Edge")) { auto size = LineColorArray.getSize(); - if(element[4]=='*') { + if (element[4] == '*') { auto color = LineColor.getValue(); bool singleColor = true; - for(int i=0;i0 && idx<=size) - ret[element] = LineColorArray[idx-1]; - else - ret[element] = LineColor.getValue(); } - } else if (boost::starts_with(element,"Vertex")) { + else { + int idx = atoi(element + 4); + if (idx > 0 && idx <= size) { + ret[element] = LineColorArray[idx - 1]; + } + else { + ret[element] = LineColor.getValue(); + } + } + } + else if (boost::starts_with(element, "Vertex")) { auto size = PointColorArray.getSize(); - if(element[5]=='*') { + if (element[5] == '*') { auto color = PointColor.getValue(); bool singleColor = true; - for(int i=0;i0 && idx<=size) - ret[element] = PointColorArray[idx-1]; - else + } + else { + int idx = atoi(element + 5); + if (idx > 0 && idx <= size) { + ret[element] = PointColorArray[idx - 1]; + } + else { ret[element] = PointColor.getValue(); + } } } return ret; @@ -765,8 +864,9 @@ void ViewProviderPartExt::unsetHighlightedFaces() void ViewProviderPartExt::setHighlightedEdges(const std::vector& colors) { - if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) + if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) { getObject()->touch(true); + } int size = static_cast(colors.size()); if (size > 1) { // Although indexed lineset is used the material binding must be PER_FACE! @@ -781,8 +881,9 @@ void ViewProviderPartExt::setHighlightedEdges(const std::vector& co if (cindices[i] < 0) { ca[linecount].setValue(colors[linecount].r, colors[linecount].g, colors[linecount].b); linecount++; - if (linecount >= size) + if (linecount >= size) { break; + } } } @@ -802,15 +903,17 @@ void ViewProviderPartExt::unsetHighlightedEdges() void ViewProviderPartExt::setHighlightedPoints(const std::vector& colors) { - if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) + if (getObject() && getObject()->testStatus(App::ObjectStatus::TouchOnColorChange)) { getObject()->touch(true); + } int size = static_cast(colors.size()); if (size > 1) { pcPointBind->value = SoMaterialBinding::PER_VERTEX; pcPointMaterial->diffuseColor.setNum(size); SbColor* ca = pcPointMaterial->diffuseColor.startEditing(); - for (int i = 0; i < size; ++i) + for (int i = 0; i < size; ++i) { ca[i].setValue(colors[i].r, colors[i].g, colors[i].b); + } pcPointMaterial->diffuseColor.finishEditing(); } else if (size == 1) { @@ -827,17 +930,18 @@ void ViewProviderPartExt::unsetHighlightedPoints() bool ViewProviderPartExt::loadParameter() { bool changed = false; - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Mod/Part"); - float deviation = hGrp->GetFloat("MeshDeviation",0.2); - float angularDeflection = hGrp->GetFloat("MeshAngularDeflection",28.65); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Part" + ); + float deviation = hGrp->GetFloat("MeshDeviation", 0.2); + float angularDeflection = hGrp->GetFloat("MeshAngularDeflection", 28.65); NormalsFromUV = hGrp->GetBool("NormalsFromUVNodes", NormalsFromUV); if (Deviation.getValue() != deviation) { Deviation.setValue(deviation); changed = true; } - if (AngularDeflection.getValue() != angularDeflection ) { + if (AngularDeflection.getValue() != angularDeflection) { AngularDeflection.setValue(angularDeflection); } @@ -846,23 +950,25 @@ bool ViewProviderPartExt::loadParameter() void ViewProviderPartExt::reload() { - if (loadParameter()) + if (loadParameter()) { updateVisual(); + } } void ViewProviderPartExt::updateData(const App::Property* prop) { - const char *propName = prop->getName(); + const char* propName = prop->getName(); if (propName && (strcmp(propName, "Shape") == 0 || strstr(propName, "Touched"))) { // calculate the visual only if visible - if (isUpdateForced() || Visibility.getValue()) + if (isUpdateForced() || Visibility.getValue()) { updateVisual(); - else + } + else { VisualTouched = true; + } if (!VisualTouched) { - if (this->faceset->partIndex.getNum() > - this->pcShapeMaterial->diffuseColor.getNum()) { + if (this->faceset->partIndex.getNum() > this->pcShapeMaterial->diffuseColor.getNum()) { this->pcFaceBind->value = SoMaterialBinding::OVERALL; } } @@ -897,7 +1003,7 @@ void ViewProviderPartExt::setupContextMenu(QMenu* menu, QObject* receiver, const bool ViewProviderPartExt::changeFaceAppearances() { - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (dlg) { Gui::Control().showDialog(dlg); return false; @@ -931,15 +1037,17 @@ void ViewProviderPartExt::unsetEdit(int ModNum) } } -void ViewProviderPartExt::setupCoinGeometry(TopoDS_Shape shape, - SoCoordinate3* coords, - SoBrepFaceSet* faceset, - SoNormal* norm, - SoBrepEdgeSet* lineset, - SoBrepPointSet* nodeset, - double deviation, - double angularDeflection, - bool normalsFromUV) +void ViewProviderPartExt::setupCoinGeometry( + TopoDS_Shape shape, + SoCoordinate3* coords, + SoBrepFaceSet* faceset, + SoNormal* norm, + SoBrepEdgeSet* lineset, + SoBrepPointSet* nodeset, + double deviation, + double angularDeflection, + bool normalsFromUV +) { if (Part::Tools::isShapeEmpty(shape)) { coords->point.setNum(0); @@ -955,7 +1063,9 @@ void ViewProviderPartExt::setupCoinGeometry(TopoDS_Shape shape, Base::TimeElapsed startTime; [[maybe_unused]] - int numTriangles = 0, numNodes = 0, numNorms = 0, numFaces = 0, numEdges = 0, numLines = 0; + int numTriangles + = 0, + numNodes = 0, numNorms = 0, numFaces = 0, numEdges = 0, numLines = 0; std::set faceEdges; @@ -1176,7 +1286,7 @@ void ViewProviderPartExt::setupCoinGeometry(TopoDS_Shape shape, verts[faceNodeOffset + N3 - 1] = Base::convertTo(V3); // set the index vector with the 3 point indexes and the end delimiter - index[faceTriaOffset * 4 + 4 * (g - 1)] = faceNodeOffset + N1 - 1; + index[faceTriaOffset * 4 + 4 * (g - 1)] = faceNodeOffset + N1 - 1; index[faceTriaOffset * 4 + 4 * (g - 1) + 1] = faceNodeOffset + N2 - 1; index[faceTriaOffset * 4 + 4 * (g - 1) + 2] = faceNodeOffset + N3 - 1; index[faceTriaOffset * 4 + 4 * (g - 1) + 3] = SO_END_FACE_INDEX; @@ -1195,8 +1305,8 @@ void ViewProviderPartExt::setupCoinGeometry(TopoDS_Shape shape, if (edgeIdxSet.find(edgeIndex) != edgeIdxSet.end()) { // this holds the indices of the edge's triangulation to the current polygon - Handle(Poly_PolygonOnTriangulation) aPoly = - BRep_Tool::PolygonOnTriangulation(curEdge, mesh, aLoc); + Handle(Poly_PolygonOnTriangulation) aPoly + = BRep_Tool::PolygonOnTriangulation(curEdge, mesh, aLoc); if (aPoly.IsNull()) { continue; // polygon does not exist } @@ -1308,27 +1418,41 @@ void ViewProviderPartExt::setupCoinGeometry(TopoDS_Shape shape, faceset->partIndex.finishEditing(); lineset->coordIndex.finishEditing(); -# ifdef FC_DEBUG - Base::Console().log("ViewProvider update time: %f s\n",Base::TimeElapsed::diffTimeF(startTime,Base::TimeElapsed())); - Base::Console().log("Shape mesh info: Faces:%d Edges:%d Nodes:%d Triangles:%d IdxVec:%d\n",numFaces,numEdges,numNodes,numTriangles,numLines); -# endif +#ifdef FC_DEBUG + Base::Console().log( + "ViewProvider update time: %f s\n", + Base::TimeElapsed::diffTimeF(startTime, Base::TimeElapsed()) + ); + Base::Console().log( + "Shape mesh info: Faces:%d Edges:%d Nodes:%d Triangles:%d IdxVec:%d\n", + numFaces, + numEdges, + numNodes, + numTriangles, + numLines + ); +#endif } -void ViewProviderPartExt::setupCoinGeometry(TopoDS_Shape shape, - SoFCShape* node, - double deviation, - double angularDeflection, - bool normalsFromUV) +void ViewProviderPartExt::setupCoinGeometry( + TopoDS_Shape shape, + SoFCShape* node, + double deviation, + double angularDeflection, + bool normalsFromUV +) { - setupCoinGeometry(shape, - node->coords, - node->faceset, - node->norm, - node->lineset, - node->nodeset, - deviation, - angularDeflection, - normalsFromUV); + setupCoinGeometry( + shape, + node->coords, + node->faceset, + node->norm, + node->lineset, + node->nodeset, + deviation, + angularDeflection, + normalsFromUV + ); } void ViewProviderPartExt::updateVisual() @@ -1351,25 +1475,28 @@ void ViewProviderPartExt::updateVisual() try { TopoDS_Shape cShape = getRenderedShape().getShape(); - setupCoinGeometry(cShape, - coords, - faceset, - norm, - lineset, - nodeset, - Deviation.getValue(), - AngularDeflection.getValue(), - NormalsFromUV); + setupCoinGeometry( + cShape, + coords, + faceset, + norm, + lineset, + nodeset, + Deviation.getValue(), + AngularDeflection.getValue(), + NormalsFromUV + ); VisualTouched = false; } catch (const Standard_Failure& e) { - FC_ERR("Cannot compute Inventor representation for the shape of " - << pcObject->getFullName() << ": " << e.GetMessageString()); + FC_ERR( + "Cannot compute Inventor representation for the shape of " + << pcObject->getFullName() << ": " << e.GetMessageString() + ); } catch (...) { - FC_ERR("Cannot compute Inventor representation for the shape of " - << pcObject->getFullName()); + FC_ERR("Cannot compute Inventor representation for the shape of " << pcObject->getFullName()); } // The material has to be checked again @@ -1378,20 +1505,26 @@ void ViewProviderPartExt::updateVisual() setHighlightedPoints(PointColorArray.getValue()); } -void ViewProviderPartExt::forceUpdate(bool enable) { - if(enable) { - if(++forceUpdateCount == 1) { - if(!isShow() && VisualTouched) +void ViewProviderPartExt::forceUpdate(bool enable) +{ + if (enable) { + if (++forceUpdateCount == 1) { + if (!isShow() && VisualTouched) { updateVisual(); + } } - }else if(forceUpdateCount) + } + else if (forceUpdateCount) { --forceUpdateCount; + } } -void ViewProviderPartExt::handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) +void ViewProviderPartExt::handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName +) { if (strcmp(PropName, "DiffuseColor") == 0 && strcmp(TypeName, App::PropertyColorList::getClassTypeId().getName()) == 0) { @@ -1403,6 +1536,3 @@ void ViewProviderPartExt::handleChangedPropertyName(Base::XMLReader& reader, Gui::ViewProviderGeometryObject::handleChangedPropertyName(reader, TypeName, PropName); } } - - - diff --git a/src/Mod/Part/Gui/ViewProviderExt.h b/src/Mod/Part/Gui/ViewProviderExt.h index 0a91a19eba..f1516afd9f 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.h +++ b/src/Mod/Part/Gui/ViewProviderExt.h @@ -59,13 +59,14 @@ class SoNormalBinding; class SoMaterialBinding; class SoIndexedLineSet; -namespace PartGui { +namespace PartGui +{ class SoBrepFaceSet; class SoBrepEdgeSet; class SoBrepPointSet; -class PartGuiExport ViewProviderPartExt : public Gui::ViewProviderGeometryObject +class PartGuiExport ViewProviderPartExt: public Gui::ViewProviderGeometryObject { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPartExt); @@ -95,7 +96,7 @@ public: App::PropertyMaterial LineMaterial; App::PropertyColorList LineColorArray; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes std::vector getDisplayModes() const override; @@ -119,22 +120,29 @@ public: */ //@{ /// indicates if the ViewProvider use the new Selection model - bool useNewSelectionModel() const override {return true;} + bool useNewSelectionModel() const override + { + return true; + } /// return a hit element to the selection path or 0 std::string getElement(const SoDetail*) const override; SoDetail* getDetail(const char*) const override; - std::vector getModelPoints(const SoPickedPoint *) const override; + std::vector getModelPoints(const SoPickedPoint*) const override; /// return the highlight lines for a given element or the whole shape std::vector getSelectionShape(const char* Element) const override; //@} - virtual Part::TopoShape getRenderedShape() const { - return Part::Feature::getTopoShape(getObject(), Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + virtual Part::TopoShape getRenderedShape() const + { + return Part::Feature::getTopoShape( + getObject(), + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); } /** @name Highlight handling - * This group of methods do the highlighting of elements. - */ + * This group of methods do the highlighting of elements. + */ //@{ void setHighlightedFaces(const std::vector& materials); void setHighlightedFaces(const App::PropertyMaterialList& appearance); @@ -148,18 +156,25 @@ public: /** @name Color management methods */ //@{ - std::map getElementColors(const char *element=nullptr) const override; + std::map getElementColors(const char* element = nullptr) const override; //@} - bool isUpdateForced() const override { - return forceUpdateCount>0; + bool isUpdateForced() const override + { + return forceUpdateCount > 0; } void forceUpdate(bool enable = true) override; - bool allowOverride(const App::DocumentObject &) const override; + bool allowOverride(const App::DocumentObject&) const override; - void setFaceHighlightActive(bool active) { faceHighlightActive = active; } - bool isFaceHighlightActive() const { return faceHighlightActive; } + void setFaceHighlightActive(bool active) + { + faceHighlightActive = active; + } + bool isFaceHighlightActive() const + { + return faceHighlightActive; + } /** @name Edit methods */ //@{ @@ -169,21 +184,25 @@ public: PyObject* getPyObject() override; /// configures Coin nodes so they render given toposhape - static void setupCoinGeometry(TopoDS_Shape shape, - SoCoordinate3* coords, - SoBrepFaceSet* faceset, - SoNormal* norm, - SoBrepEdgeSet* lineset, - SoBrepPointSet* nodeset, - double deviation, - double angularDeflection, - bool normalsFromUV = false); + static void setupCoinGeometry( + TopoDS_Shape shape, + SoCoordinate3* coords, + SoBrepFaceSet* faceset, + SoNormal* norm, + SoBrepEdgeSet* lineset, + SoBrepPointSet* nodeset, + double deviation, + double angularDeflection, + bool normalsFromUV = false + ); - static void setupCoinGeometry(TopoDS_Shape shape, - SoFCShape* node, - double deviation, - double angularDeflection, - bool normalsFromUV = false); + static void setupCoinGeometry( + TopoDS_Shape shape, + SoFCShape* node, + double deviation, + double angularDeflection, + bool normalsFromUV = false + ); protected: bool setEdit(int ModNum) override; @@ -195,26 +214,28 @@ protected: void onChanged(const App::Property* prop) override; bool loadParameter(); void updateVisual(); - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; // nodes for the data representation - SoMaterialBinding * pcFaceBind; - SoMaterialBinding * pcLineBind; - SoMaterialBinding * pcPointBind; - SoMaterial * pcLineMaterial; - SoMaterial * pcPointMaterial; - SoDrawStyle * pcLineStyle; - SoDrawStyle * pcPointStyle; - SoShapeHints * pShapeHints; + SoMaterialBinding* pcFaceBind; + SoMaterialBinding* pcLineBind; + SoMaterialBinding* pcPointBind; + SoMaterial* pcLineMaterial; + SoMaterial* pcPointMaterial; + SoDrawStyle* pcLineStyle; + SoDrawStyle* pcPointStyle; + SoShapeHints* pShapeHints; - SoCoordinate3 * coords; - SoBrepFaceSet * faceset; - SoNormal * norm; - SoNormalBinding * normb; - SoBrepEdgeSet * lineset; - SoBrepPointSet * nodeset; + SoCoordinate3* coords; + SoBrepFaceSet* faceset; + SoNormal* norm; + SoNormalBinding* normb; + SoBrepEdgeSet* lineset; + SoBrepPointSet* nodeset; bool VisualTouched; bool NormalsFromUV; @@ -235,6 +256,6 @@ private: App::PropertyColorList _diffuseColor; }; -} +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPARTEXT_H +#endif // PARTGUI_VIEWPROVIDERPARTEXT_H diff --git a/src/Mod/Part/Gui/ViewProviderExtrusion.cpp b/src/Mod/Part/Gui/ViewProviderExtrusion.cpp index 973f2f54b4..9efd40120e 100644 --- a/src/Mod/Part/Gui/ViewProviderExtrusion.cpp +++ b/src/Mod/Part/Gui/ViewProviderExtrusion.cpp @@ -23,14 +23,13 @@ ***************************************************************************/ - #include "ViewProviderExtrusion.h" #include using namespace PartGui; -PROPERTY_SOURCE(PartGui::ViewProviderExtrusion,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderExtrusion, PartGui::ViewProviderPart) ViewProviderExtrusion::ViewProviderExtrusion() { @@ -39,7 +38,7 @@ ViewProviderExtrusion::ViewProviderExtrusion() ViewProviderExtrusion::~ViewProviderExtrusion() = default; -std::vector ViewProviderExtrusion::claimChildren()const +std::vector ViewProviderExtrusion::claimChildren() const { std::vector temp; temp.push_back(getObject()->Base.getValue()); diff --git a/src/Mod/Part/Gui/ViewProviderExtrusion.h b/src/Mod/Part/Gui/ViewProviderExtrusion.h index 49c42e8035..c7a146c109 100644 --- a/src/Mod/Part/Gui/ViewProviderExtrusion.h +++ b/src/Mod/Part/Gui/ViewProviderExtrusion.h @@ -31,9 +31,10 @@ #include "ViewProvider.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderExtrusion : public ViewProviderPart +class PartGuiExport ViewProviderExtrusion: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderExtrusion); @@ -47,7 +48,7 @@ public: std::vector claimChildren() const override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDEREXTRUSION_H +#endif // PARTGUI_VIEWPROVIDEREXTRUSION_H diff --git a/src/Mod/Part/Gui/ViewProviderGridExtension.cpp b/src/Mod/Part/Gui/ViewProviderGridExtension.cpp index df9c4bdcd9..0f2f874949 100644 --- a/src/Mod/Part/Gui/ViewProviderGridExtension.cpp +++ b/src/Mod/Part/Gui/ViewProviderGridExtension.cpp @@ -22,19 +22,19 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include +#include #include #include @@ -58,14 +58,16 @@ using namespace std; EXTENSION_PROPERTY_SOURCE(PartGui::ViewProviderGridExtension, Gui::ViewProviderExtension) -App::PropertyQuantityConstraint::Constraints ViewProviderGridExtension::GridSizeRange = { - 0.001, std::numeric_limits::max(), 1.0 }; +App::PropertyQuantityConstraint::Constraints ViewProviderGridExtension::GridSizeRange + = {0.001, std::numeric_limits::max(), 1.0}; -namespace PartGui { +namespace PartGui +{ -class GridExtensionP { +class GridExtensionP +{ public: - explicit GridExtensionP(ViewProviderGridExtension *); + explicit GridExtensionP(ViewProviderGridExtension*); ~GridExtensionP(); void drawGrid(bool cameraUpdate = false); @@ -73,9 +75,9 @@ public: void setEnabled(bool enable); bool getEnabled(); - SoSeparator * getGridRoot(); + SoSeparator* getGridRoot(); - void getClosestGridPoint(double &x, double &y) const; + void getClosestGridPoint(double& x, double& y) const; double getGridSize() const; void setGridOrientation(Base::Vector3d origin, Base::Rotation rotation); @@ -93,7 +95,14 @@ public: private: void computeGridSize(const Gui::View3DInventorViewer* viewer); void createGrid(bool cameraUpdate = false); - void createGridPart(int numberSubdiv, bool divLines, bool subDivLines, int pattern, SoBaseColor* color, int lineWidth = 1); + void createGridPart( + int numberSubdiv, + bool divLines, + bool subDivLines, + int pattern, + SoBaseColor* color, + int lineWidth = 1 + ); bool checkCameraZoomChange(const Gui::View3DInventorViewer* viewer); bool checkCameraTranslationChange(const Gui::View3DInventorViewer* viewer); @@ -109,7 +118,7 @@ private: Base::Rotation gridRotation; private: - ViewProviderGridExtension * vp; + ViewProviderGridExtension* vp; bool enabled = false; double computedGridValue = 10; @@ -117,17 +126,17 @@ private: bool isTooManySegmentsNotified = false; // scenograph - SoSeparator * GridRoot; + SoSeparator* GridRoot; }; -} // namespace PartGui +} // namespace PartGui -GridExtensionP::GridExtensionP(ViewProviderGridExtension * vp): - camCenterPointOnFocalPlane(SbVec3f(0., 0., 0.)), - camMaxDimension(200.), - vp(vp), - GridRoot(nullptr) +GridExtensionP::GridExtensionP(ViewProviderGridExtension* vp) + : camCenterPointOnFocalPlane(SbVec3f(0., 0., 0.)) + , camMaxDimension(200.) + , vp(vp) + , GridRoot(nullptr) { SbColor lineCol(0.7f, 0.7f, 0.7f); GridLineColor = lineCol.getPackedValue(); @@ -153,9 +162,9 @@ double GridExtensionP::getGridSize() const return computedGridValue; } -void GridExtensionP::getClosestGridPoint(double &x, double &y) const +void GridExtensionP::getClosestGridPoint(double& x, double& y) const { - auto closestdim = [](double &dim, double gridValue) { + auto closestdim = [](double& dim, double gridValue) { dim = dim / gridValue; dim = dim < 0.0 ? ceil(dim - 0.5) : floor(dim + 0.5); dim *= gridValue; @@ -164,13 +173,13 @@ void GridExtensionP::getClosestGridPoint(double &x, double &y) const closestdim(x, computedGridValue); closestdim(y, computedGridValue); - //Base::Console().log("gridvalue=%f, (x,y)=(%f,%f)", computedGridValue, x, y); + // Base::Console().log("gridvalue=%f, (x,y)=(%f,%f)", computedGridValue, x, y); } bool GridExtensionP::checkCameraZoomChange(const Gui::View3DInventorViewer* viewer) { float newCamMaxDimension = viewer->getMaxDimension(); - if (fabs(newCamMaxDimension - camMaxDimension) > 0) { //ie if user zoomed. + if (fabs(newCamMaxDimension - camMaxDimension) > 0) { // ie if user zoomed. camMaxDimension = newCamMaxDimension; return true; } @@ -180,10 +189,12 @@ bool GridExtensionP::checkCameraZoomChange(const Gui::View3DInventorViewer* view bool GridExtensionP::checkCameraTranslationChange(const Gui::View3DInventorViewer* viewer) { - //Then we check if user moved by more than 10% of camera dimension (must be after updating camera dimension). + // Then we check if user moved by more than 10% of camera dimension (must be after updating + // camera dimension). SbVec3f newCamCenterPointOnFocalPlane = viewer->getCenterPointOnFocalPlane(); - if ((camCenterPointOnFocalPlane - newCamCenterPointOnFocalPlane).length() > 0.1 * camMaxDimension) { + if ((camCenterPointOnFocalPlane - newCamCenterPointOnFocalPlane).length() + > 0.1 * camMaxDimension) { camCenterPointOnFocalPlane = newCamCenterPointOnFocalPlane; return true; } @@ -194,7 +205,7 @@ bool GridExtensionP::checkCameraTranslationChange(const Gui::View3DInventorViewe void GridExtensionP::computeGridSize(const Gui::View3DInventorViewer* viewer) { - auto capGridSize = [](auto & value){ + auto capGridSize = [](auto& value) { value = std::max(static_cast(value), std::numeric_limits::min()); value = std::min(static_cast(value), std::numeric_limits::max()); }; @@ -219,18 +230,27 @@ void GridExtensionP::computeGridSize(const Gui::View3DInventorViewer* viewer) // In such case, we apply a default factor of 10 auto safeGridNumberSubdivision = GridNumberSubdivision <= 1 ? 10 : GridNumberSubdivision; - computedGridValue = vp->GridSize.getValue() * pow(safeGridNumberSubdivision, 1 + floor(log(camMaxDimension / numberOfLines / vp->GridSize.getValue()) / log(safeGridNumberSubdivision))); + computedGridValue = vp->GridSize.getValue() + * pow(safeGridNumberSubdivision, + 1 + + floor( + log(camMaxDimension / numberOfLines / vp->GridSize.getValue()) + / log(safeGridNumberSubdivision) + )); - //cap the grid size + // cap the grid size capGridSize(computedGridValue); } void GridExtensionP::createGrid(bool cameraUpdate) { - auto view = dynamic_cast(Gui::Application::Instance->editDocument()->getActiveView()); + auto view = dynamic_cast( + Gui::Application::Instance->editDocument()->getActiveView() + ); - if(!view) + if (!view) { return; + } Gui::View3DInventorViewer* viewer = view->getViewer(); @@ -240,8 +260,9 @@ void GridExtensionP::createGrid(bool cameraUpdate) bool gridNeedUpdating = cameraDimensionsChanged || cameraCenterMoved; - if (!gridNeedUpdating && cameraUpdate) + if (!gridNeedUpdating && cameraUpdate) { return; + } Gui::coinRemoveAllChildren(GridRoot); @@ -256,19 +277,37 @@ void GridExtensionP::createGrid(bool cameraUpdate) return lineColor; }; - //First we create the subdivision lines - createGridPart(GridNumberSubdivision, true, - (GridNumberSubdivision == 1), GridLinePattern, - getColor(GridLineColor), GridLineWidth); + // First we create the subdivision lines + createGridPart( + GridNumberSubdivision, + true, + (GridNumberSubdivision == 1), + GridLinePattern, + getColor(GridLineColor), + GridLineWidth + ); - //Second we create the wider lines marking every nth lines + // Second we create the wider lines marking every nth lines if (GridNumberSubdivision > 1) { - createGridPart(GridNumberSubdivision, false, true, - GridDivLinePattern, getColor(GridDivLineColor), GridDivLineWidth); + createGridPart( + GridNumberSubdivision, + false, + true, + GridDivLinePattern, + getColor(GridDivLineColor), + GridDivLineWidth + ); } } -void GridExtensionP::createGridPart(int numberSubdiv, bool subDivLines, bool divLines, int pattern, SoBaseColor* color, int lineWidth) +void GridExtensionP::createGridPart( + int numberSubdiv, + bool subDivLines, + bool divLines, + int pattern, + SoBaseColor* color, + int lineWidth +) { auto* parent = new Gui::SoSkipBoundingGroup(); parent->mode = Gui::SoSkipBoundingGroup::EXCLUDE_BBOX; @@ -292,12 +331,15 @@ void GridExtensionP::createGridPart(int numberSubdiv, bool subDivLines, bool div grid->vertexProperty = vts; float gridDimension = 1.5 * camMaxDimension; - int vlines = static_cast(gridDimension / computedGridValue); // total number of vertical lines - int nlines = 2 * vlines; // total number of lines + int vlines = static_cast(gridDimension / computedGridValue); // total number of vertical lines + int nlines = 2 * vlines; // total number of lines if (nlines > 2000) { - if(!isTooManySegmentsNotified) { - Base::Console().warning("The grid is too dense, so it is being disabled. Consider zooming in or changing the grid configuration\n"); + if (!isTooManySegmentsNotified) { + Base::Console().warning( + "The grid is too dense, so it is being disabled. Consider zooming in or changing " + "the grid configuration\n" + ); isTooManySegmentsNotified = true; } @@ -310,9 +352,10 @@ void GridExtensionP::createGridPart(int numberSubdiv, bool subDivLines, bool div // set the grid indices grid->numVertices.setNum(nlines); - auto * vertices = grid->numVertices.startEditing(); - for (int i = 0; i < nlines; i++) + auto* vertices = grid->numVertices.startEditing(); + for (int i = 0; i < nlines; i++) { vertices[i] = 2; + } grid->numVertices.finishEditing(); // set the grid coordinates @@ -333,14 +376,15 @@ void GridExtensionP::createGridPart(int numberSubdiv, bool subDivLines, bool div int i_offset_x = static_cast(minX / computedGridValue); for (int i = 0; i < vlines; i++) { int iStep = (i + i_offset_x); - if (((iStep % numberSubdiv == 0) && divLines) || ((iStep % numberSubdiv != 0) && subDivLines)) { + if (((iStep % numberSubdiv == 0) && divLines) + || ((iStep % numberSubdiv != 0) && subDivLines)) { vertex_coords[2 * i].setValue(iStep * computedGridValue, minY, 0); vertex_coords[2 * i + 1].setValue(iStep * computedGridValue, maxY, 0); } else { - /*the number of vertices is defined before. To know the number of vertices ahead it would require - to run the loop once before, which would double computation time. - If vertices are not filled then there're visual bugs so there are here filled with dummy values.*/ + /*the number of vertices is defined before. To know the number of vertices ahead it would + require to run the loop once before, which would double computation time. If vertices are + not filled then there're visual bugs so there are here filled with dummy values.*/ vertex_coords[2 * i].setValue(0, 0, 0); vertex_coords[2 * i + 1].setValue(0, 0, 0); } @@ -350,7 +394,8 @@ void GridExtensionP::createGridPart(int numberSubdiv, bool subDivLines, bool div int i_offset_y = static_cast(minY / computedGridValue) - vlines; for (int i = vlines; i < nlines; i++) { int iStep = (i + i_offset_y); - if (((iStep % numberSubdiv == 0) && divLines) || ((iStep % numberSubdiv != 0) && subDivLines)) { + if (((iStep % numberSubdiv == 0) && divLines) + || ((iStep % numberSubdiv != 0) && subDivLines)) { vertex_coords[2 * i].setValue(minX, iStep * computedGridValue, 0); vertex_coords[2 * i + 1].setValue(maxX, iStep * computedGridValue, 0); } @@ -369,13 +414,13 @@ Base::Vector3d GridExtensionP::getCamCenterInSketchCoordinates() const { Base::Vector3d xaxis(1, 0, 0), yaxis(0, 1, 0); - gridRotation.multVec(xaxis,xaxis); - gridRotation.multVec(yaxis,yaxis); + gridRotation.multVec(xaxis, xaxis); + gridRotation.multVec(yaxis, yaxis); - float x,y,z; + float x, y, z; camCenterPointOnFocalPlane.getValue(x, y, z); - Base::Vector3d center (x,y,z); + Base::Vector3d center(x, y, z); center.TransformToCoordinateSystem(gridOrigin, xaxis, yaxis); @@ -384,10 +429,9 @@ Base::Vector3d GridExtensionP::getCamCenterInSketchCoordinates() const void GridExtensionP::setEnabled(bool enable) { - enabled=enable; + enabled = enable; drawGrid(); - } bool GridExtensionP::getEnabled() @@ -401,15 +445,15 @@ void GridExtensionP::createEditModeInventorNodes() GridRoot = new SoSeparator(); GridRoot->ref(); GridRoot->setName("GridRoot"); - } -SoSeparator * GridExtensionP::getGridRoot() +SoSeparator* GridExtensionP::getGridRoot() { return GridRoot; } -void GridExtensionP::drawGrid(bool cameraUpdate) { +void GridExtensionP::drawGrid(bool cameraUpdate) +{ if (vp->ShowGrid.getValue() && enabled) { createGrid(cameraUpdate); } @@ -421,17 +465,33 @@ void GridExtensionP::drawGrid(bool cameraUpdate) { ViewProviderGridExtension::ViewProviderGridExtension() { - EXTENSION_ADD_PROPERTY_TYPE(ShowGrid, (false), "Grid", (App::PropertyType)(App::Prop_None), "Toggle grid visibility"); - EXTENSION_ADD_PROPERTY_TYPE(GridSize, (10.0), "Grid", (App::PropertyType)(App::Prop_None), "Gap size of the grid"); - EXTENSION_ADD_PROPERTY_TYPE(GridAuto, (true), "Grid", (App::PropertyType)(App::Prop_None), "Change size of grid based on view area."); + EXTENSION_ADD_PROPERTY_TYPE( + ShowGrid, + (false), + "Grid", + (App::PropertyType)(App::Prop_None), + "Toggle grid visibility" + ); + EXTENSION_ADD_PROPERTY_TYPE( + GridSize, + (10.0), + "Grid", + (App::PropertyType)(App::Prop_None), + "Gap size of the grid" + ); + EXTENSION_ADD_PROPERTY_TYPE( + GridAuto, + (true), + "Grid", + (App::PropertyType)(App::Prop_None), + "Change size of grid based on view area." + ); initExtensionType(ViewProviderGridExtension::getExtensionClassTypeId()); GridSize.setConstraints(&GridSizeRange); pImpl = std::make_unique(this); - - } ViewProviderGridExtension::~ViewProviderGridExtension() = default; @@ -461,14 +521,14 @@ double ViewProviderGridExtension::getGridSize() const return pImpl->getGridSize(); } -void ViewProviderGridExtension::getClosestGridPoint(double &x, double &y) const +void ViewProviderGridExtension::getClosestGridPoint(double& x, double& y) const { return pImpl->getClosestGridPoint(x, y); } void ViewProviderGridExtension::extensionUpdateData(const App::Property* prop) { - if(pImpl->getEnabled()) { + if (pImpl->getEnabled()) { if (prop->is()) { pImpl->drawGrid(); } @@ -477,11 +537,9 @@ void ViewProviderGridExtension::extensionUpdateData(const App::Property* prop) void ViewProviderGridExtension::extensionOnChanged(const App::Property* prop) { - if(pImpl->getEnabled()) { - if (prop == &ShowGrid || - prop == &GridAuto || - prop == &GridSize ) { - pImpl->drawGrid(); + if (pImpl->getEnabled()) { + if (prop == &ShowGrid || prop == &GridAuto || prop == &GridSize) { + pImpl->drawGrid(); } } } @@ -522,26 +580,28 @@ void ViewProviderGridExtension::setGridDivLineWidth(int width) drawGrid(false); } -void ViewProviderGridExtension::setGridLineColor(const Base::Color & color) +void ViewProviderGridExtension::setGridLineColor(const Base::Color& color) { pImpl->GridLineColor = color.getPackedValue(); drawGrid(false); } -void ViewProviderGridExtension::setGridDivLineColor(const Base::Color & color) +void ViewProviderGridExtension::setGridDivLineColor(const Base::Color& color) { pImpl->GridDivLineColor = color.getPackedValue(); drawGrid(false); } -bool ViewProviderGridExtension::extensionHandleChangedPropertyType(Base::XMLReader& reader, +bool ViewProviderGridExtension::extensionHandleChangedPropertyType( + Base::XMLReader& reader, const char* TypeName, - App::Property* prop) + App::Property* prop +) { Base::Type inputType = Base::Type::fromName(TypeName); - if (prop->isDerivedFrom() && - inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) { + if (prop->isDerivedFrom() + && inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) { // Do not directly call the property's Restore method in case the implementation // has changed. So, create a temporary PropertyFloat object and assign the value. App::PropertyFloat floatProp; @@ -553,9 +613,13 @@ bool ViewProviderGridExtension::extensionHandleChangedPropertyType(Base::XMLRead return Gui::ViewProviderExtension::extensionHandleChangedPropertyType(reader, TypeName, prop); } -namespace Gui { - EXTENSION_PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProviderGridExtensionPython, PartGui::ViewProviderGridExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + PartGui::ViewProviderGridExtensionPython, + PartGui::ViewProviderGridExtension +) // explicit template instantiation - template class PartGuiExport ViewProviderExtensionPythonT; -} +template class PartGuiExport ViewProviderExtensionPythonT; +} // namespace Gui diff --git a/src/Mod/Part/Gui/ViewProviderGridExtension.h b/src/Mod/Part/Gui/ViewProviderGridExtension.h index 3b5b63c5db..660c817e21 100644 --- a/src/Mod/Part/Gui/ViewProviderGridExtension.h +++ b/src/Mod/Part/Gui/ViewProviderGridExtension.h @@ -35,11 +35,12 @@ #include -namespace PartGui { +namespace PartGui +{ class GridExtensionP; -class PartGuiExport ViewProviderGridExtension : public Gui::ViewProviderExtension +class PartGuiExport ViewProviderGridExtension: public Gui::ViewProviderExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderGridExtension); @@ -63,9 +64,9 @@ public: void setGridOrientation(Base::Vector3d origin, Base::Rotation rotation); /** Return the distance to the closest point in the grid. - * The point closer to the grid is returned by reference - */ - void getClosestGridPoint(double &x, double &y) const; + * The point closer to the grid is returned by reference + */ + void getClosestGridPoint(double& x, double& y) const; double getGridSize() const; protected: @@ -78,10 +79,14 @@ protected: void setGridDivLinePattern(int pattern); void setGridLineWidth(int width); void setGridDivLineWidth(int width); - void setGridLineColor(const Base::Color & color); - void setGridDivLineColor(const Base::Color & color); + void setGridLineColor(const Base::Color& color); + void setGridDivLineColor(const Base::Color& color); - bool extensionHandleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + bool extensionHandleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; private: @@ -89,15 +94,13 @@ private: static App::PropertyQuantityConstraint::Constraints GridSizeRange; std::unique_ptr pImpl; - - }; -using ViewProviderGridExtensionPython = Gui::ViewProviderExtensionPythonT; +using ViewProviderGridExtensionPython + = Gui::ViewProviderExtensionPythonT; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERGRIDEXTENSION_H - +#endif // PARTGUI_VIEWPROVIDERGRIDEXTENSION_H diff --git a/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp b/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp index 815e0fed28..3e6bf4e495 100644 --- a/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp @@ -23,8 +23,7 @@ ***************************************************************************/ - -# include +#include #include "ViewProviderHelixParametric.h" diff --git a/src/Mod/Part/Gui/ViewProviderHelixParametric.h b/src/Mod/Part/Gui/ViewProviderHelixParametric.h index 257ef59882..06efaf82ef 100644 --- a/src/Mod/Part/Gui/ViewProviderHelixParametric.h +++ b/src/Mod/Part/Gui/ViewProviderHelixParametric.h @@ -31,10 +31,11 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderHelixParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderHelixParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderHelixParametric); @@ -50,7 +51,7 @@ private: ViewProviderSplineExtension extension; }; -class PartGuiExport ViewProviderSpiralParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderSpiralParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSpiralParametric); @@ -66,8 +67,7 @@ private: ViewProviderSplineExtension extension; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERHELIXPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERHELIXPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderImport.cpp b/src/Mod/Part/Gui/ViewProviderImport.cpp index 80e080cd14..eb63894bb0 100644 --- a/src/Mod/Part/Gui/ViewProviderImport.cpp +++ b/src/Mod/Part/Gui/ViewProviderImport.cpp @@ -31,7 +31,7 @@ using namespace PartGui; //************************************************************************** // Construction/Destruction -PROPERTY_SOURCE(PartGui::ViewProviderImport,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderImport, PartGui::ViewProviderPart) ViewProviderImport::ViewProviderImport() { diff --git a/src/Mod/Part/Gui/ViewProviderImport.h b/src/Mod/Part/Gui/ViewProviderImport.h index 6ab22ea7cc..a561a99680 100644 --- a/src/Mod/Part/Gui/ViewProviderImport.h +++ b/src/Mod/Part/Gui/ViewProviderImport.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderImport : public ViewProviderPart +class PartGuiExport ViewProviderImport: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderImport); @@ -55,8 +56,7 @@ protected: void unsetEdit(int ModNum) override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEVPROVIDERIMPORT_H - +#endif // PARTGUI_VIEVPROVIDERIMPORT_H diff --git a/src/Mod/Part/Gui/ViewProviderLineParametric.cpp b/src/Mod/Part/Gui/ViewProviderLineParametric.cpp index 8cf47de6dc..4d3b8ebe67 100644 --- a/src/Mod/Part/Gui/ViewProviderLineParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderLineParametric.cpp @@ -37,23 +37,22 @@ PROPERTY_SOURCE(PartGui::ViewProviderLineParametric, PartGui::ViewProviderPrimit ViewProviderLineParametric::ViewProviderLineParametric() { - sPixmap = "Part_Line_Parametric"; + sPixmap = "Part_Line_Parametric"; } ViewProviderLineParametric::~ViewProviderLineParametric() = default; - // ********************************************************************************** std::vector ViewProviderLineParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderLineParametric.h b/src/Mod/Part/Gui/ViewProviderLineParametric.h index 0a46069271..ea5407b2e5 100644 --- a/src/Mod/Part/Gui/ViewProviderLineParametric.h +++ b/src/Mod/Part/Gui/ViewProviderLineParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderLineParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderLineParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderLineParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERLINEPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERLINEPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderMirror.cpp b/src/Mod/Part/Gui/ViewProviderMirror.cpp index df21fbab9f..65ef640143 100644 --- a/src/Mod/Part/Gui/ViewProviderMirror.cpp +++ b/src/Mod/Part/Gui/ViewProviderMirror.cpp @@ -22,20 +22,20 @@ * * ***************************************************************************/ -# 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 @@ -71,11 +71,12 @@ ViewProviderMirror::~ViewProviderMirror() void ViewProviderMirror::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { - // don't add plane editor to context menu if MirrorPlane is set because it would override any changes, anyway + // don't add plane editor to context menu if MirrorPlane is set because it would override any + // changes, anyway Part::Mirroring* mf = getObject(); Part::Feature* ref = static_cast(mf->MirrorPlane.getValue()); bool enabled = true; - if (ref){ + if (ref) { enabled = false; } QAction* act; @@ -92,7 +93,7 @@ bool ViewProviderMirror::setEdit(int ModNum) // get the properties from the mirror feature Part::Mirroring* mf = getObject(); Part::Feature* ref = static_cast(mf->MirrorPlane.getValue()); - if (ref) { //skip this editor if MirrorPlane property is set + if (ref) { // skip this editor if MirrorPlane property is set return false; } Base::BoundBox3d bbox = mf->Shape.getBoundingBox(); @@ -104,20 +105,20 @@ bool ViewProviderMirror::setEdit(int ModNum) // setup the graph for editing the mirror plane SoTransform* trans = new SoTransform; - SbRotation rot(SbVec3f(0,0,1), SbVec3f(norm.x,norm.y,norm.z)); + SbRotation rot(SbVec3f(0, 0, 1), SbVec3f(norm.x, norm.y, norm.z)); trans->rotation.setValue(rot); - trans->translation.setValue(base.x,base.y,base.z); - trans->center.setValue(0.0f,0.0f,0.0f); + trans->translation.setValue(base.x, base.y, base.z); + trans->center.setValue(0.0f, 0.0f, 0.0f); SoMaterial* color = new SoMaterial(); - color->diffuseColor.setValue(0,0,1); + color->diffuseColor.setValue(0, 0, 1); color->transparency.setValue(0.5); SoCoordinate3* points = new SoCoordinate3(); points->point.setNum(4); - points->point.set1Value(0, -len/2,-len/2,0); - points->point.set1Value(1, len/2,-len/2,0); - points->point.set1Value(2, len/2, len/2,0); - points->point.set1Value(3, -len/2, len/2,0); + points->point.set1Value(0, -len / 2, -len / 2, 0); + points->point.set1Value(1, len / 2, -len / 2, 0); + points->point.set1Value(2, len / 2, len / 2, 0); + points->point.set1Value(3, -len / 2, len / 2, 0); SoFaceSet* face = new SoFaceSet(); pcEditNode->addChild(trans); pcEditNode->addChild(color); @@ -133,9 +134,9 @@ bool ViewProviderMirror::setEdit(int ModNum) sa.setSearchingAll(false); sa.setNode(trans); sa.apply(pcEditNode); - SoPath * path = sa.getPath(); + SoPath* path = sa.getPath(); if (path) { - SoCenterballManip * manip = new SoCenterballManip; + SoCenterballManip* manip = new SoCenterballManip; manip->replaceNode(path); SoDragger* dragger = manip->getDragger(); @@ -155,7 +156,7 @@ bool ViewProviderMirror::setEdit(int ModNum) void ViewProviderMirror::unsetEdit(int ModNum) { if (ModNum == ViewProvider::Default) { - SoCenterballManip* manip = static_cast(pcEditNode->getChild(0)); + SoCenterballManip* manip = static_cast(pcEditNode->getChild(0)); SbVec3f move = manip->translation.getValue(); SbVec3f center = manip->center.getValue(); @@ -163,17 +164,17 @@ void ViewProviderMirror::unsetEdit(int ModNum) // get the whole translation move += center; - rot.multVec(center,center); + rot.multVec(center, center); move -= center; // the new axis of the plane - SbVec3f norm(0,0,1); - rot.multVec(norm,norm); + SbVec3f norm(0, 0, 1); + rot.multVec(norm, norm); // apply the new values Part::Mirroring* mf = getObject(); - mf->Base.setValue(move[0],move[1],move[2]); - mf->Normal.setValue(norm[0],norm[1],norm[2]); + mf->Base.setValue(move[0], move[1], move[2]); + mf->Normal.setValue(norm[0], norm[1], norm[2]); pcRoot->removeChild(pcEditNode); Gui::coinRemoveAllChildren(pcEditNode); @@ -191,40 +192,43 @@ std::vector ViewProviderMirror::claimChildren() const return temp; } -bool ViewProviderMirror::onDelete(const std::vector &) +bool ViewProviderMirror::onDelete(const std::vector&) { // get the input shape Part::Mirroring* pMirroring = getObject(); - App::DocumentObject *pSource = pMirroring->Source.getValue(); - if (pSource) + App::DocumentObject* pSource = pMirroring->Source.getValue(); + if (pSource) { Gui::Application::Instance->showViewProvider(pSource); + } return true; } -void ViewProviderMirror::dragStartCallback(void *, SoDragger *) +void ViewProviderMirror::dragStartCallback(void*, SoDragger*) { // This is called when a manipulator is about to manipulating - Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Edit mirror")); + Gui::Application::Instance->activeDocument()->openCommand( + QT_TRANSLATE_NOOP("Command", "Edit mirror") + ); } -void ViewProviderMirror::dragFinishCallback(void *, SoDragger *) +void ViewProviderMirror::dragFinishCallback(void*, SoDragger*) { // This is called when a manipulator has done manipulating Gui::Application::Instance->activeDocument()->commitCommand(); } -void ViewProviderMirror::dragMotionCallback(void *data, SoDragger *drag) +void ViewProviderMirror::dragMotionCallback(void* data, SoDragger* drag) { ViewProviderMirror* that = static_cast(data); const SbMatrix& mat = drag->getMotionMatrix(); // the new axis of the plane SbRotation rot(mat); - SbVec3f norm(0,0,1); - rot.multVec(norm,norm); + SbVec3f norm(0, 0, 1); + rot.multVec(norm, norm); Part::Mirroring* mf = that->getObject(); - mf->Base.setValue(mat[3][0],mat[3][1],mat[3][2]); - mf->Normal.setValue(norm[0],norm[1],norm[2]); + mf->Base.setValue(mat[3][0], mat[3][1], mat[3][2]); + mf->Normal.setValue(norm[0], norm[1], norm[2]); } // ---------------------------------------------------------------------------- @@ -242,15 +246,18 @@ void ViewProviderFillet::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - const std::vector& hist = static_cast - (prop)->getValues(); - if (hist.size() != 1) + const std::vector& hist + = static_cast(prop)->getValues(); + if (hist.size() != 1) { return; + } Part::Fillet* objFill = getObject(); - if (!objFill) + if (!objFill) { return; + } Part::Feature* objBase = dynamic_cast( - Part::Feature::getShapeOwner(objFill->Base.getValue())); + Part::Feature::getShapeOwner(objFill->Base.getValue()) + ); if (objBase) { const TopoDS_Shape& baseShape = objBase->Shape.getValue(); const TopoDS_Shape& fillShape = objFill->Shape.getValue(); @@ -259,12 +266,18 @@ void ViewProviderFillet::updateData(const App::Property* prop) TopExp::MapShapes(baseShape, TopAbs_FACE, baseMap); TopExp::MapShapes(fillShape, TopAbs_FACE, fillMap); - auto vpBase = dynamic_cast(Gui::Application::Instance->getViewProvider(objBase)); + auto vpBase = dynamic_cast( + Gui::Application::Instance->getViewProvider(objBase) + ); if (vpBase) { - auto colBase = static_cast(vpBase)->ShapeAppearance.getValues(); + auto colBase + = static_cast(vpBase)->ShapeAppearance.getValues(); std::vector colFill; colFill.resize(fillMap.Extent(), colBase[0]); - applyTransparency(static_cast(vpBase)->Transparency.getValue(), colBase); + applyTransparency( + static_cast(vpBase)->Transparency.getValue(), + colBase + ); if (static_cast(colBase.size()) == baseMap.Extent()) { applyMaterial(hist[0], colBase, colFill); @@ -296,9 +309,10 @@ void ViewProviderFillet::setupContextMenu(QMenu* menu, QObject* receiver, const bool ViewProviderFillet::setEdit(int ModNum) { - if (ModNum == ViewProvider::Default ) { - if (Gui::Control().activeDialog()) + if (ModNum == ViewProvider::Default) { + if (Gui::Control().activeDialog()) { return false; + } Part::Fillet* fillet = getObject(); Gui::Control().showDialog(new PartGui::TaskFilletEdges(fillet)); return true; @@ -326,13 +340,14 @@ std::vector ViewProviderFillet::claimChildren() const return temp; } -bool ViewProviderFillet::onDelete(const std::vector &) +bool ViewProviderFillet::onDelete(const std::vector&) { // get the input shape Part::Fillet* pFillet = getObject(); - App::DocumentObject *pBase = pFillet->Base.getValue(); - if (pBase) + App::DocumentObject* pBase = pFillet->Base.getValue(); + if (pBase) { Gui::Application::Instance->showViewProvider(pBase); + } return true; } @@ -352,15 +367,18 @@ void ViewProviderChamfer::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - const std::vector& hist = static_cast - (prop)->getValues(); - if (hist.size() != 1) + const std::vector& hist + = static_cast(prop)->getValues(); + if (hist.size() != 1) { return; + } Part::Chamfer* objCham = getObject(); - if (!objCham) + if (!objCham) { return; + } Part::Feature* objBase = dynamic_cast( - Part::Feature::getShapeOwner(objCham->Base.getValue())); + Part::Feature::getShapeOwner(objCham->Base.getValue()) + ); if (objBase) { const TopoDS_Shape& baseShape = objBase->Shape.getValue(); const TopoDS_Shape& chamShape = objCham->Shape.getValue(); @@ -369,12 +387,18 @@ void ViewProviderChamfer::updateData(const App::Property* prop) TopExp::MapShapes(baseShape, TopAbs_FACE, baseMap); TopExp::MapShapes(chamShape, TopAbs_FACE, chamMap); - auto vpBase = dynamic_cast(Gui::Application::Instance->getViewProvider(objBase)); + auto vpBase = dynamic_cast( + Gui::Application::Instance->getViewProvider(objBase) + ); if (vpBase) { - auto colBase = static_cast(vpBase)->ShapeAppearance.getValues(); + auto colBase + = static_cast(vpBase)->ShapeAppearance.getValues(); std::vector colCham; colCham.resize(chamMap.Extent(), colBase[0]); - applyTransparency(static_cast(vpBase)->Transparency.getValue(), colBase); + applyTransparency( + static_cast(vpBase)->Transparency.getValue(), + colBase + ); if (static_cast(colBase.size()) == baseMap.Extent()) { applyMaterial(hist[0], colBase, colCham); @@ -406,9 +430,10 @@ void ViewProviderChamfer::setupContextMenu(QMenu* menu, QObject* receiver, const bool ViewProviderChamfer::setEdit(int ModNum) { - if (ModNum == ViewProvider::Default ) { - if (Gui::Control().activeDialog()) + if (ModNum == ViewProvider::Default) { + if (Gui::Control().activeDialog()) { return false; + } Part::Chamfer* chamfer = getObject(); Gui::Control().showDialog(new PartGui::TaskChamferEdges(chamfer)); return true; @@ -436,13 +461,14 @@ std::vector ViewProviderChamfer::claimChildren() const return temp; } -bool ViewProviderChamfer::onDelete(const std::vector &) +bool ViewProviderChamfer::onDelete(const std::vector&) { // get the input shape Part::Chamfer* pChamfer = getObject(); - App::DocumentObject *pBase = pChamfer->Base.getValue(); - if (pBase) + App::DocumentObject* pBase = pChamfer->Base.getValue(); + if (pBase) { Gui::Application::Instance->showViewProvider(pBase); + } return true; } @@ -465,13 +491,14 @@ std::vector ViewProviderRevolution::claimChildren() const return temp; } -bool ViewProviderRevolution::onDelete(const std::vector &) +bool ViewProviderRevolution::onDelete(const std::vector&) { // get the input shape Part::Revolution* pRevolve = getObject(); - App::DocumentObject *pBase = pRevolve->Source.getValue(); - if (pBase) + App::DocumentObject* pBase = pRevolve->Source.getValue(); + if (pBase) { Gui::Application::Instance->showViewProvider(pBase); + } return true; } @@ -492,7 +519,7 @@ std::vector ViewProviderLoft::claimChildren() const return getObject()->Sections.getValues(); } -bool ViewProviderLoft::onDelete(const std::vector &) +bool ViewProviderLoft::onDelete(const std::vector&) { return true; } @@ -512,12 +539,13 @@ std::vector ViewProviderSweep::claimChildren() const { auto obj = getObject(); auto children = obj->Sections.getValues(); - if(obj->Spine.getValue()) + if (obj->Spine.getValue()) { children.push_back(obj->Spine.getValue()); + } return children; } -bool ViewProviderSweep::onDelete(const std::vector &) +bool ViewProviderSweep::onDelete(const std::vector&) { return true; } @@ -541,26 +569,31 @@ void ViewProviderOffset::setupContextMenu(QMenu* menu, QObject* receiver, const bool ViewProviderOffset::setEdit(int ModNum) { - if (ModNum == ViewProvider::Default ) { - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); + if (ModNum == ViewProvider::Default) { + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); TaskOffset* offsetDlg = qobject_cast(dlg); - if (offsetDlg && offsetDlg->getObject() != this->getObject()) - offsetDlg = nullptr; // another pad left open its task panel + if (offsetDlg && offsetDlg->getObject() != this->getObject()) { + offsetDlg = nullptr; // another pad left open its task panel + } if (dlg && !offsetDlg) { - if (dlg->canClose()) + if (dlg->canClose()) { Gui::Control().closeDialog(); - else + } + else { return false; + } } // clear the selection (convenience) Gui::Selection().clearSelection(); // start the edit dialog - if (offsetDlg) + if (offsetDlg) { Gui::Control().showDialog(offsetDlg); - else + } + else { Gui::Control().showDialog(new TaskOffset(getObject())); + } return true; } @@ -587,12 +620,12 @@ std::vector ViewProviderOffset::claimChildren() const return child; } -bool ViewProviderOffset::onDelete(const std::vector &) +bool ViewProviderOffset::onDelete(const std::vector&) { // get the support and Sketch Part::Offset* offset = getObject(); App::DocumentObject* source = offset->Source.getValue(); - if (source){ + if (source) { Gui::Application::Instance->getViewProvider(source)->show(); } @@ -623,26 +656,31 @@ void ViewProviderThickness::setupContextMenu(QMenu* menu, QObject* receiver, con bool ViewProviderThickness::setEdit(int ModNum) { - if (ModNum == ViewProvider::Default ) { - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); + if (ModNum == ViewProvider::Default) { + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); TaskThickness* thicknessDlg = qobject_cast(dlg); - if (thicknessDlg && thicknessDlg->getObject() != this->getObject()) - thicknessDlg = nullptr; // another pad left open its task panel + if (thicknessDlg && thicknessDlg->getObject() != this->getObject()) { + thicknessDlg = nullptr; // another pad left open its task panel + } if (dlg && !thicknessDlg) { - if (dlg->canClose()) + if (dlg->canClose()) { Gui::Control().closeDialog(); - else + } + else { return false; + } } // clear the selection (convenience) Gui::Selection().clearSelection(); // start the edit dialog - if (thicknessDlg) + if (thicknessDlg) { Gui::Control().showDialog(thicknessDlg); - else + } + else { Gui::Control().showDialog(new TaskThickness(getObject())); + } return true; } @@ -669,12 +707,12 @@ std::vector ViewProviderThickness::claimChildren() const return child; } -bool ViewProviderThickness::onDelete(const std::vector &) +bool ViewProviderThickness::onDelete(const std::vector&) { // get the support and Sketch Part::Thickness* thickness = getObject(); App::DocumentObject* source = thickness->Faces.getValue(); - if (source){ + if (source) { Gui::Application::Instance->getViewProvider(source)->show(); } @@ -698,8 +736,8 @@ PROPERTY_SOURCE(PartGui::ViewProviderReverse, PartGui::ViewProviderPart) ViewProviderReverse::ViewProviderReverse() { - //TODO: Need a specific icon here! - //sPixmap = "Part_Reverse_Shape"; + // TODO: Need a specific icon here! + // sPixmap = "Part_Reverse_Shape"; } ViewProviderReverse::~ViewProviderReverse() = default; diff --git a/src/Mod/Part/Gui/ViewProviderMirror.h b/src/Mod/Part/Gui/ViewProviderMirror.h index 9ab8510e92..1de8c6a1f2 100644 --- a/src/Mod/Part/Gui/ViewProviderMirror.h +++ b/src/Mod/Part/Gui/ViewProviderMirror.h @@ -30,10 +30,11 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderMirror : public ViewProviderPart +class PartGuiExport ViewProviderMirror: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderMirror); @@ -44,7 +45,7 @@ public: //@{ void setupContextMenu(QMenu*, QObject*, const char*) override; std::vector claimChildren() const override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: bool setEdit(int ModNum) override; @@ -52,15 +53,15 @@ protected: //@} private: - static void dragStartCallback(void * data, SoDragger * d); - static void dragFinishCallback(void * data, SoDragger * d); - static void dragMotionCallback(void * data, SoDragger * d); + static void dragStartCallback(void* data, SoDragger* d); + static void dragFinishCallback(void* data, SoDragger* d); + static void dragMotionCallback(void* data, SoDragger* d); private: SoSeparator* pcEditNode; }; -class PartGuiExport ViewProviderFillet : public ViewProviderPart +class PartGuiExport ViewProviderFillet: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderFillet); @@ -71,7 +72,7 @@ public: //@{ void setupContextMenu(QMenu*, QObject*, const char*) override; std::vector claimChildren() const override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: void updateData(const App::Property*) override; @@ -80,7 +81,7 @@ protected: //@} }; -class ViewProviderChamfer : public ViewProviderPart +class ViewProviderChamfer: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderChamfer); @@ -93,7 +94,7 @@ public: //@{ void setupContextMenu(QMenu*, QObject*, const char*) override; std::vector claimChildren() const override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: void updateData(const App::Property*) override; @@ -102,7 +103,7 @@ protected: //@} }; -class ViewProviderRevolution : public ViewProviderPart +class ViewProviderRevolution: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRevolution); @@ -113,11 +114,11 @@ public: ~ViewProviderRevolution() override; /// grouping handling - std::vector claimChildren()const override; - bool onDelete(const std::vector &) override; + std::vector claimChildren() const override; + bool onDelete(const std::vector&) override; }; -class ViewProviderLoft : public ViewProviderPart +class ViewProviderLoft: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderLoft); @@ -128,11 +129,11 @@ public: ~ViewProviderLoft() override; /// grouping handling - std::vector claimChildren()const override; - bool onDelete(const std::vector &) override; + std::vector claimChildren() const override; + bool onDelete(const std::vector&) override; }; -class ViewProviderSweep : public ViewProviderPart +class ViewProviderSweep: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSweep); @@ -143,11 +144,11 @@ public: ~ViewProviderSweep() override; /// grouping handling - std::vector claimChildren()const override; - bool onDelete(const std::vector &) override; + std::vector claimChildren() const override; + bool onDelete(const std::vector&) override; }; -class ViewProviderOffset : public ViewProviderPart +class ViewProviderOffset: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderOffset); @@ -158,26 +159,27 @@ public: ~ViewProviderOffset() override; /// grouping handling - std::vector claimChildren()const override; + std::vector claimChildren() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: bool setEdit(int ModNum) override; void unsetEdit(int ModNum) override; }; -class ViewProviderOffset2D : public ViewProviderOffset +class ViewProviderOffset2D: public ViewProviderOffset { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderOffset2D); public: - ViewProviderOffset2D(){ + ViewProviderOffset2D() + { sPixmap = "Part_Offset2D"; } }; -class ViewProviderThickness : public ViewProviderPart +class ViewProviderThickness: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderThickness); @@ -188,16 +190,16 @@ public: ~ViewProviderThickness() override; /// grouping handling - std::vector claimChildren()const override; + std::vector claimChildren() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: bool setEdit(int ModNum) override; void unsetEdit(int ModNum) override; }; -class ViewProviderRefine : public ViewProviderPart +class ViewProviderRefine: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRefine); @@ -208,7 +210,7 @@ public: ~ViewProviderRefine() override; }; -class ViewProviderReverse : public ViewProviderPart +class ViewProviderReverse: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderReverse); @@ -219,7 +221,7 @@ public: ~ViewProviderReverse() override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERMIRROR_H +#endif // PARTGUI_VIEWPROVIDERMIRROR_H diff --git a/src/Mod/Part/Gui/ViewProviderPartExt.pyi b/src/Mod/Part/Gui/ViewProviderPartExt.pyi index a085ce40e0..dc9b6adea9 100644 --- a/src/Mod/Part/Gui/ViewProviderPartExt.pyi +++ b/src/Mod/Part/Gui/ViewProviderPartExt.pyi @@ -1,7 +1,6 @@ from Base.Metadata import export from Gui.ViewProviderGeometryObject import ViewProviderGeometryObject - @export( Include="Mod/Part/Gui/ViewProviderExt.h", Namespace="PartGui", @@ -13,4 +12,5 @@ class ViewProviderPartExt(ViewProviderGeometryObject): Author: David Carter (dcarter@davidcarter.ca) Licence: LGPL """ + ... diff --git a/src/Mod/Part/Gui/ViewProviderPlaneParametric.h b/src/Mod/Part/Gui/ViewProviderPlaneParametric.h index e741c601e4..58bed59c34 100644 --- a/src/Mod/Part/Gui/ViewProviderPlaneParametric.h +++ b/src/Mod/Part/Gui/ViewProviderPlaneParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderPlaneParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderPlaneParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPlaneParametric); @@ -53,10 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -class PartGuiExport ViewProviderFace : public ViewProviderPlaneParametric +class PartGuiExport ViewProviderFace: public ViewProviderPlaneParametric { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderFace); @@ -73,8 +73,7 @@ public: void dropObject(App::DocumentObject*) override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPLANEPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERPLANEPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderPointParametric.cpp b/src/Mod/Part/Gui/ViewProviderPointParametric.cpp index fac07c8588..ac27705cc0 100644 --- a/src/Mod/Part/Gui/ViewProviderPointParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderPointParametric.cpp @@ -37,25 +37,24 @@ PROPERTY_SOURCE(PartGui::ViewProviderPointParametric, PartGui::ViewProviderPrimi ViewProviderPointParametric::ViewProviderPointParametric() { - sPixmap = "Part_Point_Parametric"; + sPixmap = "Part_Point_Parametric"; } ViewProviderPointParametric::~ViewProviderPointParametric() = default; - // ********************************************************************************** std::vector ViewProviderPointParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderPointParametric.h b/src/Mod/Part/Gui/ViewProviderPointParametric.h index d407cda0c8..070b643ad9 100644 --- a/src/Mod/Part/Gui/ViewProviderPointParametric.h +++ b/src/Mod/Part/Gui/ViewProviderPointParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderPointParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderPointParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPointParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPOINTPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERPOINTPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderPreviewExtension.cpp b/src/Mod/Part/Gui/ViewProviderPreviewExtension.cpp index b00c2068f0..69db159200 100644 --- a/src/Mod/Part/Gui/ViewProviderPreviewExtension.cpp +++ b/src/Mod/Part/Gui/ViewProviderPreviewExtension.cpp @@ -21,12 +21,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include "ViewProviderPreviewExtension.h" #include "ViewProviderExt.h" @@ -132,7 +132,8 @@ ViewProviderPreviewExtension::ViewProviderPreviewExtension() (magenta), "Preview", static_cast(App::Prop_Transient | App::Prop_Hidden), - "Color used for 3D Preview"); + "Color used for 3D Preview" + ); initExtensionType(ViewProviderPreviewExtension::getExtensionClassTypeId()); } @@ -180,7 +181,8 @@ void ViewProviderPreviewExtension::showPreview(bool enable) if (annotationRoot->findChild(pcPreviewRoot) < 0) { annotationRoot->addChild(pcPreviewRoot); } - } else { + } + else { annotationRoot->removeChild(pcPreviewRoot); } } @@ -204,8 +206,7 @@ void ViewProviderPreviewExtension::updatePreview() updatePreviewShape(getPreviewShape(), pcPreviewShape); } -void ViewProviderPreviewExtension::updatePreviewShape(Part::TopoShape shape, - SoPreviewShape* preview) +void ViewProviderPreviewExtension::updatePreviewShape(Part::TopoShape shape, SoPreviewShape* preview) { if (shape.isNull() || preview == nullptr) { return; @@ -218,20 +219,24 @@ void ViewProviderPreviewExtension::updatePreviewShape(Part::TopoShape shape, } const auto updatePreviewShape = [vp](SoPreviewShape* preview, Part::TopoShape shape) { - ViewProviderPartExt::setupCoinGeometry(shape.getShape(), - preview, - vp->Deviation.getValue(), - vp->AngularDeflection.getValue()); + ViewProviderPartExt::setupCoinGeometry( + shape.getShape(), + preview, + vp->Deviation.getValue(), + vp->AngularDeflection.getValue() + ); }; try { updatePreviewShape(preview, shape); preview->transform.setValue(Base::convertTo(shape.getTransform())); - } catch (Standard_Failure& e) { + } + catch (Standard_Failure& e) { Base::Console().userTranslatedNotification( tr("Failure while rendering preview: %1. That usually indicates an error with model.") .arg(QString::fromUtf8(e.GetMessageString())) - .toUtf8()); + .toUtf8() + ); updatePreviewShape(preview, {}); } @@ -255,9 +260,13 @@ void ViewProviderPreviewExtension::updatePreviewShape(Part::TopoShape shape, } } -namespace Gui { -EXTENSION_PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProviderPreviewExtensionPython, PartGui::ViewProviderPreviewExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + PartGui::ViewProviderPreviewExtensionPython, + PartGui::ViewProviderPreviewExtension +) // explicit template instantiation template class PartGuiExport ViewProviderExtensionPythonT; -} +} // namespace Gui diff --git a/src/Mod/Part/Gui/ViewProviderPreviewExtension.h b/src/Mod/Part/Gui/ViewProviderPreviewExtension.h index df26779b9a..368dfb44bb 100644 --- a/src/Mod/Part/Gui/ViewProviderPreviewExtension.h +++ b/src/Mod/Part/Gui/ViewProviderPreviewExtension.h @@ -45,9 +45,11 @@ #include #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport SoPreviewShape : public SoFCShape { +class PartGuiExport SoPreviewShape: public SoFCShape +{ using inherited = SoFCShape; SO_NODE_HEADER(SoPreviewShape); @@ -68,7 +70,8 @@ private: SoMatrixTransform* pcTransform; }; -class PartGuiExport ViewProviderPreviewExtension : public Gui::ViewProviderExtension { +class PartGuiExport ViewProviderPreviewExtension: public Gui::ViewProviderExtension +{ Q_DECLARE_TR_FUNCTIONS(PartGui::ViewProviderPreviewExtension) EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderPreviewExtension); @@ -78,13 +81,19 @@ public: ViewProviderPreviewExtension(); /// Returns shape that should be used as the preview - virtual Part::TopoShape getPreviewShape() const { return Part::TopoShape(); }; + virtual Part::TopoShape getPreviewShape() const + { + return Part::TopoShape(); + }; void extensionAttach(App::DocumentObject*) override; void extensionBeforeDelete() override; /// Returns whatever preview is enabled or not - bool isPreviewEnabled() const { return _isPreviewEnabled; } + bool isPreviewEnabled() const + { + return _isPreviewEnabled; + } /// Switches preview on or off virtual void showPreview(bool enable); @@ -105,9 +114,10 @@ private: bool _isPreviewEnabled {false}; }; -using ViewProviderPreviewExtensionPython = Gui::ViewProviderExtensionPythonT; +using ViewProviderPreviewExtensionPython + = Gui::ViewProviderExtensionPythonT; -} +} // namespace PartGui #endif // PARTGUI_VIEWPROVIDERPREVIEWEXTENSION_H diff --git a/src/Mod/Part/Gui/ViewProviderPrimitive.cpp b/src/Mod/Part/Gui/ViewProviderPrimitive.cpp index 49ed1b3db2..e2e7ec26a2 100644 --- a/src/Mod/Part/Gui/ViewProviderPrimitive.cpp +++ b/src/Mod/Part/Gui/ViewProviderPrimitive.cpp @@ -23,8 +23,8 @@ ***************************************************************************/ -# include -# include +#include +#include #include @@ -50,11 +50,11 @@ ViewProviderPrimitive::~ViewProviderPrimitive() = default; void ViewProviderPrimitive::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { Gui::ActionFunction* func = new Gui::ActionFunction(menu); - QAction* act = menu->addAction(QObject::tr("Edit %1").arg(QString::fromUtf8(getObject()->Label.getValue()))); + QAction* act = menu->addAction( + QObject::tr("Edit %1").arg(QString::fromUtf8(getObject()->Label.getValue())) + ); act->setData(QVariant((int)ViewProvider::Default)); - func->trigger(act, [this](){ - this->startDefaultEditMode(); - }); + func->trigger(act, [this]() { this->startDefaultEditMode(); }); ViewProviderPart::setupContextMenu(menu, receiver, member); } @@ -62,10 +62,12 @@ void ViewProviderPrimitive::setupContextMenu(QMenu* menu, QObject* receiver, con bool ViewProviderPrimitive::setEdit(int ModNum) { if (ModNum == ViewProvider::Default) { - if (Gui::Control().activeDialog()) + if (Gui::Control().activeDialog()) { return false; - PartGui::TaskPrimitivesEdit* dlg - = new PartGui::TaskPrimitivesEdit(getObject()); + } + PartGui::TaskPrimitivesEdit* dlg = new PartGui::TaskPrimitivesEdit( + getObject() + ); Gui::Control().showDialog(dlg); return true; } diff --git a/src/Mod/Part/Gui/ViewProviderPrimitive.h b/src/Mod/Part/Gui/ViewProviderPrimitive.h index 47cc4fd2bc..3f5ddff566 100644 --- a/src/Mod/Part/Gui/ViewProviderPrimitive.h +++ b/src/Mod/Part/Gui/ViewProviderPrimitive.h @@ -31,9 +31,10 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderPrimitive : public ViewProviderPart +class PartGuiExport ViewProviderPrimitive: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPrimitive); @@ -53,8 +54,7 @@ private: ViewProviderAttachExtension extension; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPRIMITIVE_H - +#endif // PARTGUI_VIEWPROVIDERPRIMITIVE_H diff --git a/src/Mod/Part/Gui/ViewProviderPrism.h b/src/Mod/Part/Gui/ViewProviderPrism.h index 890b914256..0bd1849c35 100644 --- a/src/Mod/Part/Gui/ViewProviderPrism.h +++ b/src/Mod/Part/Gui/ViewProviderPrism.h @@ -31,10 +31,11 @@ #include "ViewProviderPrimitive.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderPrism : public ViewProviderPrimitive +class PartGuiExport ViewProviderPrism: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPrism); @@ -47,10 +48,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -class PartGuiExport ViewProviderWedge : public ViewProviderPrimitive +class PartGuiExport ViewProviderWedge: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderWedge); @@ -63,11 +63,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPRISM_H - +#endif // PARTGUI_VIEWPROVIDERPRISM_H diff --git a/src/Mod/Part/Gui/ViewProviderProjectOnSurface.h b/src/Mod/Part/Gui/ViewProviderProjectOnSurface.h index 93d79d99f4..aba24543cf 100644 --- a/src/Mod/Part/Gui/ViewProviderProjectOnSurface.h +++ b/src/Mod/Part/Gui/ViewProviderProjectOnSurface.h @@ -31,10 +31,11 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderProjectOnSurface : public ViewProviderPart +class PartGuiExport ViewProviderProjectOnSurface: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderProjectOnSurface); @@ -49,8 +50,7 @@ public: void unsetEdit(int ModNum) override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPROJECTONSURFACE_H - +#endif // PARTGUI_VIEWPROVIDERPROJECTONSURFACE_H diff --git a/src/Mod/Part/Gui/ViewProviderPython.cpp b/src/Mod/Part/Gui/ViewProviderPython.cpp index 6f71e9b2ab..c6801dbc70 100644 --- a/src/Mod/Part/Gui/ViewProviderPython.cpp +++ b/src/Mod/Part/Gui/ViewProviderPython.cpp @@ -23,7 +23,7 @@ ***************************************************************************/ -# include +#include #include @@ -63,7 +63,9 @@ void ViewProviderCustom::updateData(const App::Property* prop) if (view) { if (view->isDerivedFrom()) { 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); @@ -78,7 +80,8 @@ void ViewProviderCustom::updateData(const App::Property* prop) // ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProviderPython, PartGui::ViewProviderPart) /// @endcond @@ -92,5 +95,4 @@ PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProviderCustomPython, PartGui::ViewProvide // explicit template instantiation template class PartGuiExport ViewProviderFeaturePythonT; -} - +} // namespace Gui diff --git a/src/Mod/Part/Gui/ViewProviderPython.h b/src/Mod/Part/Gui/ViewProviderPython.h index 6f0497b5ea..2d77e7d393 100644 --- a/src/Mod/Part/Gui/ViewProviderPython.h +++ b/src/Mod/Part/Gui/ViewProviderPython.h @@ -31,9 +31,10 @@ #include -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderCustom : public ViewProviderPart +class PartGuiExport ViewProviderCustom: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCustom); @@ -52,8 +53,7 @@ protected: using ViewProviderPython = Gui::ViewProviderFeaturePythonT; using ViewProviderCustomPython = Gui::ViewProviderFeaturePythonT; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPYTHON_H - +#endif // PARTGUI_VIEWPROVIDERPYTHON_H diff --git a/src/Mod/Part/Gui/ViewProviderReference.cpp b/src/Mod/Part/Gui/ViewProviderReference.cpp index d9cd963f1b..ad1e080ef4 100644 --- a/src/Mod/Part/Gui/ViewProviderReference.cpp +++ b/src/Mod/Part/Gui/ViewProviderReference.cpp @@ -22,11 +22,11 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include +#include +#include +#include #include #include @@ -45,136 +45,136 @@ PROPERTY_SOURCE(PartGui::ViewProviderPartReference, Gui::ViewProviderGeometryObj ViewProviderPartReference::ViewProviderPartReference() { App::Material mat; - mat.ambientColor.set(0.2f,0.2f,0.2f); - mat.diffuseColor.set(0.1f,0.1f,0.1f); - mat.specularColor.set(0.0f,0.0f,0.0f); - mat.emissiveColor.set(0.0f,0.0f,0.0f); + mat.ambientColor.set(0.2f, 0.2f, 0.2f); + mat.diffuseColor.set(0.1f, 0.1f, 0.1f); + mat.specularColor.set(0.0f, 0.0f, 0.0f); + mat.emissiveColor.set(0.0f, 0.0f, 0.0f); mat.shininess = 0.0f; mat.transparency = 0.0f; - //ADD_PROPERTY(LineMaterial,(mat)); - //ADD_PROPERTY(PointMaterial,(mat)); - //ADD_PROPERTY(LineColor,(mat.diffuseColor)); - //ADD_PROPERTY(PointColor,(mat.diffuseColor)); - //ADD_PROPERTY(LineWidth,(2.0f)); - //LineWidth.setConstraints(&floatRange); - //PointSize.setConstraints(&floatRange); - //ADD_PROPERTY(PointSize,(2.0f)); - //ADD_PROPERTY(ControlPoints,(false)); - //ADD_PROPERTY(Lighting,(1)); - //Lighting.setEnums(LightingEnums); + // ADD_PROPERTY(LineMaterial,(mat)); + // ADD_PROPERTY(PointMaterial,(mat)); + // ADD_PROPERTY(LineColor,(mat.diffuseColor)); + // ADD_PROPERTY(PointColor,(mat.diffuseColor)); + // ADD_PROPERTY(LineWidth,(2.0f)); + // LineWidth.setConstraints(&floatRange); + // PointSize.setConstraints(&floatRange); + // ADD_PROPERTY(PointSize,(2.0f)); + // ADD_PROPERTY(ControlPoints,(false)); + // ADD_PROPERTY(Lighting,(1)); + // Lighting.setEnums(LightingEnums); - //EdgeRoot = new SoSeparator(); - //EdgeRoot->ref(); - //FaceRoot = new SoSeparator(); - //FaceRoot->ref(); - //VertexRoot = new SoSeparator(); - //VertexRoot->ref(); - //pcLineMaterial = new SoMaterial; - //pcLineMaterial->ref(); - //LineMaterial.touch(); + // EdgeRoot = new SoSeparator(); + // EdgeRoot->ref(); + // FaceRoot = new SoSeparator(); + // FaceRoot->ref(); + // VertexRoot = new SoSeparator(); + // VertexRoot->ref(); + // pcLineMaterial = new SoMaterial; + // pcLineMaterial->ref(); + // LineMaterial.touch(); - //pcPointMaterial = new SoMaterial; - //pcPointMaterial->ref(); - //PointMaterial.touch(); + // pcPointMaterial = new SoMaterial; + // pcPointMaterial->ref(); + // PointMaterial.touch(); - //pcLineStyle = new SoDrawStyle(); - //pcLineStyle->ref(); - //pcLineStyle->style = SoDrawStyle::LINES; - //pcLineStyle->lineWidth = LineWidth.getValue(); + // pcLineStyle = new SoDrawStyle(); + // pcLineStyle->ref(); + // pcLineStyle->style = SoDrawStyle::LINES; + // pcLineStyle->lineWidth = LineWidth.getValue(); - //pcPointStyle = new SoDrawStyle(); - //pcPointStyle->ref(); - //pcPointStyle->style = SoDrawStyle::POINTS; - //pcPointStyle->pointSize = PointSize.getValue(); + // pcPointStyle = new SoDrawStyle(); + // pcPointStyle->ref(); + // pcPointStyle->style = SoDrawStyle::POINTS; + // pcPointStyle->pointSize = PointSize.getValue(); - //pShapeHints = new SoShapeHints; - //pShapeHints->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE; - //pShapeHints->ref(); - //Lighting.touch(); + // pShapeHints = new SoShapeHints; + // pShapeHints->shapeType = SoShapeHints::UNKNOWN_SHAPE_TYPE; + // pShapeHints->ref(); + // Lighting.touch(); sPixmap = "Part_3D_object"; - //loadParameter(); + // loadParameter(); } ViewProviderPartReference::~ViewProviderPartReference() { - //EdgeRoot->unref(); - //FaceRoot->unref(); - //VertexRoot->unref(); - //pcLineMaterial->unref(); - //pcPointMaterial->unref(); - //pcLineStyle->unref(); - //pcPointStyle->unref(); - //pShapeHints->unref(); + // EdgeRoot->unref(); + // FaceRoot->unref(); + // VertexRoot->unref(); + // pcLineMaterial->unref(); + // pcPointMaterial->unref(); + // pcLineStyle->unref(); + // pcPointStyle->unref(); + // pShapeHints->unref(); } void ViewProviderPartReference::onChanged(const App::Property* /*prop*/) { - //if (prop == &LineWidth) { - // pcLineStyle->lineWidth = LineWidth.getValue(); - //} - //else if (prop == &PointSize) { - // pcPointStyle->pointSize = PointSize.getValue(); - //} - //else if (prop == &LineColor) { - // const Base::Color& c = LineColor.getValue(); - // pcLineMaterial->diffuseColor.setValue(c.r,c.g,c.b); - // if (c != LineMaterial.getValue().diffuseColor) - // LineMaterial.setDiffuseColor(c); - //} - //else if (prop == &PointColor) { - // const Base::Color& c = PointColor.getValue(); - // pcPointMaterial->diffuseColor.setValue(c.r,c.g,c.b); - // if (c != PointMaterial.getValue().diffuseColor) - // PointMaterial.setDiffuseColor(c); - //} - //else if (prop == &LineMaterial) { - // const App::Material& Mat = LineMaterial.getValue(); - // if (LineColor.getValue() != Mat.diffuseColor) - // LineColor.setValue(Mat.diffuseColor); - // pcLineMaterial->ambientColor.setValue(Mat.ambientColor.r,Mat.ambientColor.g,Mat.ambientColor.b); - // pcLineMaterial->diffuseColor.setValue(Mat.diffuseColor.r,Mat.diffuseColor.g,Mat.diffuseColor.b); - // pcLineMaterial->specularColor.setValue(Mat.specularColor.r,Mat.specularColor.g,Mat.specularColor.b); - // pcLineMaterial->emissiveColor.setValue(Mat.emissiveColor.r,Mat.emissiveColor.g,Mat.emissiveColor.b); - // pcLineMaterial->shininess.setValue(Mat.shininess); - // pcLineMaterial->transparency.setValue(Mat.transparency); - //} - //else if (prop == &PointMaterial) { - // const App::Material& Mat = PointMaterial.getValue(); - // if (PointColor.getValue() != Mat.diffuseColor) - // PointColor.setValue(Mat.diffuseColor); - // pcPointMaterial->ambientColor.setValue(Mat.ambientColor.r,Mat.ambientColor.g,Mat.ambientColor.b); - // pcPointMaterial->diffuseColor.setValue(Mat.diffuseColor.r,Mat.diffuseColor.g,Mat.diffuseColor.b); - // pcPointMaterial->specularColor.setValue(Mat.specularColor.r,Mat.specularColor.g,Mat.specularColor.b); - // pcPointMaterial->emissiveColor.setValue(Mat.emissiveColor.r,Mat.emissiveColor.g,Mat.emissiveColor.b); - // pcPointMaterial->shininess.setValue(Mat.shininess); - // pcPointMaterial->transparency.setValue(Mat.transparency); - //} - //else if (prop == &ControlPoints) { - // App::DocumentObject* obj = this->pcObject; - // App::Property* shape = obj->getPropertyByName("Shape"); - // showControlPoints(ControlPoints.getValue(), shape); - //} - //else if (prop == &Lighting) { - // if (Lighting.getValue() == 0) - // pShapeHints->vertexOrdering = SoShapeHints::UNKNOWN_ORDERING; - // else - // pShapeHints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE; - //} - //else { - // ViewProviderGeometryObject::onChanged(prop); - //} + // if (prop == &LineWidth) { + // pcLineStyle->lineWidth = LineWidth.getValue(); + // } + // else if (prop == &PointSize) { + // pcPointStyle->pointSize = PointSize.getValue(); + // } + // else if (prop == &LineColor) { + // const Base::Color& c = LineColor.getValue(); + // pcLineMaterial->diffuseColor.setValue(c.r,c.g,c.b); + // if (c != LineMaterial.getValue().diffuseColor) + // LineMaterial.setDiffuseColor(c); + // } + // else if (prop == &PointColor) { + // const Base::Color& c = PointColor.getValue(); + // pcPointMaterial->diffuseColor.setValue(c.r,c.g,c.b); + // if (c != PointMaterial.getValue().diffuseColor) + // PointMaterial.setDiffuseColor(c); + // } + // else if (prop == &LineMaterial) { + // const App::Material& Mat = LineMaterial.getValue(); + // if (LineColor.getValue() != Mat.diffuseColor) + // LineColor.setValue(Mat.diffuseColor); + // pcLineMaterial->ambientColor.setValue(Mat.ambientColor.r,Mat.ambientColor.g,Mat.ambientColor.b); + // pcLineMaterial->diffuseColor.setValue(Mat.diffuseColor.r,Mat.diffuseColor.g,Mat.diffuseColor.b); + // pcLineMaterial->specularColor.setValue(Mat.specularColor.r,Mat.specularColor.g,Mat.specularColor.b); + // pcLineMaterial->emissiveColor.setValue(Mat.emissiveColor.r,Mat.emissiveColor.g,Mat.emissiveColor.b); + // pcLineMaterial->shininess.setValue(Mat.shininess); + // pcLineMaterial->transparency.setValue(Mat.transparency); + // } + // else if (prop == &PointMaterial) { + // const App::Material& Mat = PointMaterial.getValue(); + // if (PointColor.getValue() != Mat.diffuseColor) + // PointColor.setValue(Mat.diffuseColor); + // pcPointMaterial->ambientColor.setValue(Mat.ambientColor.r,Mat.ambientColor.g,Mat.ambientColor.b); + // pcPointMaterial->diffuseColor.setValue(Mat.diffuseColor.r,Mat.diffuseColor.g,Mat.diffuseColor.b); + // pcPointMaterial->specularColor.setValue(Mat.specularColor.r,Mat.specularColor.g,Mat.specularColor.b); + // pcPointMaterial->emissiveColor.setValue(Mat.emissiveColor.r,Mat.emissiveColor.g,Mat.emissiveColor.b); + // pcPointMaterial->shininess.setValue(Mat.shininess); + // pcPointMaterial->transparency.setValue(Mat.transparency); + // } + // else if (prop == &ControlPoints) { + // App::DocumentObject* obj = this->pcObject; + // App::Property* shape = obj->getPropertyByName("Shape"); + // showControlPoints(ControlPoints.getValue(), shape); + // } + // else if (prop == &Lighting) { + // if (Lighting.getValue() == 0) + // pShapeHints->vertexOrdering = SoShapeHints::UNKNOWN_ORDERING; + // else + // pShapeHints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE; + // } + // else { + // ViewProviderGeometryObject::onChanged(prop); + // } } -void ViewProviderPartReference::attach(App::DocumentObject *pcFeat) +void ViewProviderPartReference::attach(App::DocumentObject* pcFeat) { // call parent attach method ViewProviderGeometryObject::attach(pcFeat); SoGroup* pcNormalRoot = new SoGroup(); - //SoGroup* pcFlatRoot = new SoGroup(); - //SoGroup* pcWireframeRoot = new SoGroup(); - //SoGroup* pcPointsRoot = new SoGroup(); + // SoGroup* pcFlatRoot = new SoGroup(); + // SoGroup* pcWireframeRoot = new SoGroup(); + // SoGroup* pcPointsRoot = new SoGroup(); // enable two-side rendering pShapeHints->vertexOrdering = SoShapeHints::COUNTERCLOCKWISE; @@ -187,15 +187,15 @@ void ViewProviderPartReference::attach(App::DocumentObject *pcFeat) pcNormalRoot->addChild(VertexRoot); // just faces with no edges or points - //pcFlatRoot->addChild(pShapeHints); - //pcFlatRoot->addChild(FaceRoot); + // pcFlatRoot->addChild(pShapeHints); + // pcFlatRoot->addChild(FaceRoot); // only edges - //pcWireframeRoot->addChild(EdgeRoot); - //pcWireframeRoot->addChild(VertexRoot); + // pcWireframeRoot->addChild(EdgeRoot); + // pcWireframeRoot->addChild(VertexRoot); // normal viewing with edges and points - //pcPointsRoot->addChild(VertexRoot); + // pcPointsRoot->addChild(VertexRoot); // putting all together with the switch addDisplayMaskMode(pcNormalRoot, "Reference"); @@ -203,10 +203,11 @@ void ViewProviderPartReference::attach(App::DocumentObject *pcFeat) void ViewProviderPartReference::setDisplayMode(const char* ModeName) { - if ( strcmp("Reference",ModeName)==0 ) + if (strcmp("Reference", ModeName) == 0) { setDisplayMaskMode("Reference"); + } - ViewProviderGeometryObject::setDisplayMode( ModeName ); + ViewProviderGeometryObject::setDisplayMode(ModeName); } std::vector ViewProviderPartReference::getDisplayModes() const @@ -224,6 +225,5 @@ std::vector ViewProviderPartReference::getDisplayModes() const } -void ViewProviderPartReference::updateData(const App::Property* ) -{ -} +void ViewProviderPartReference::updateData(const App::Property*) +{} diff --git a/src/Mod/Part/Gui/ViewProviderReference.h b/src/Mod/Part/Gui/ViewProviderReference.h index 9555614ce4..18e9b96955 100644 --- a/src/Mod/Part/Gui/ViewProviderReference.h +++ b/src/Mod/Part/Gui/ViewProviderReference.h @@ -48,10 +48,11 @@ class SbVec3f; class SoSphere; class SoScale; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderPartReference : public Gui::ViewProviderGeometryObject +class PartGuiExport ViewProviderPartReference: public Gui::ViewProviderGeometryObject { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPartReference); @@ -62,17 +63,17 @@ public: ~ViewProviderPartReference() override; // Display properties - //App::PropertyFloatConstraint LineWidth; - //App::PropertyFloatConstraint PointSize; - //App::PropertyColor LineColor; - //App::PropertyColor PointColor; - //App::PropertyMaterial LineMaterial; - //App::PropertyMaterial PointMaterial; - //App::PropertyBool ControlPoints; - //App::PropertyEnumeration Lighting; + // App::PropertyFloatConstraint LineWidth; + // App::PropertyFloatConstraint PointSize; + // App::PropertyColor LineColor; + // App::PropertyColor PointColor; + // App::PropertyMaterial LineMaterial; + // App::PropertyMaterial PointMaterial; + // App::PropertyBool ControlPoints; + // App::PropertyEnumeration Lighting; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes std::vector getDisplayModes() const override; @@ -84,32 +85,30 @@ public: protected: /// get called by the container whenever a property has been changed void onChanged(const App::Property* prop) override; - //bool loadParameter(); + // bool loadParameter(); // nodes for the data representation - SoGroup *EdgeRoot{nullptr}; - SoGroup *FaceRoot{nullptr}; - SoGroup *VertexRoot{nullptr}; - SoMaterial *pcLineMaterial{nullptr}; - SoMaterial *pcPointMaterial{nullptr}; - SoDrawStyle *pcLineStyle{nullptr}; - SoDrawStyle *pcPointStyle{nullptr}; - SoSwitch *pcControlPoints{nullptr}; - SoShapeHints *pShapeHints{nullptr}; + SoGroup* EdgeRoot {nullptr}; + SoGroup* FaceRoot {nullptr}; + SoGroup* VertexRoot {nullptr}; + SoMaterial* pcLineMaterial {nullptr}; + SoMaterial* pcPointMaterial {nullptr}; + SoDrawStyle* pcLineStyle {nullptr}; + SoDrawStyle* pcPointStyle {nullptr}; + SoSwitch* pcControlPoints {nullptr}; + SoShapeHints* pShapeHints {nullptr}; private: // settings stuff - float meshDeviation{0.01F}; - bool noPerVertexNormals{true}; - bool qualityNormals{false}; + float meshDeviation {0.01F}; + bool noPerVertexNormals {true}; + bool qualityNormals {false}; static App::PropertyFloatConstraint::Constraints floatRange; static const char* LightingEnums[]; }; - -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_ViewProviderPartReference_H - +#endif // PARTGUI_ViewProviderPartReference_H diff --git a/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp b/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp index 9a9ad61449..00c9ceb25b 100644 --- a/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp +++ b/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp @@ -37,7 +37,7 @@ PROPERTY_SOURCE(PartGui::ViewProviderRegularPolygon, PartGui::ViewProviderPrimit ViewProviderRegularPolygon::ViewProviderRegularPolygon() { - sPixmap = "Part_Polygon_Parametric"; + sPixmap = "Part_Polygon_Parametric"; } ViewProviderRegularPolygon::~ViewProviderRegularPolygon() = default; diff --git a/src/Mod/Part/Gui/ViewProviderRegularPolygon.h b/src/Mod/Part/Gui/ViewProviderRegularPolygon.h index 0a04f7b607..2c20516005 100644 --- a/src/Mod/Part/Gui/ViewProviderRegularPolygon.h +++ b/src/Mod/Part/Gui/ViewProviderRegularPolygon.h @@ -31,10 +31,11 @@ #include "ViewProviderPrimitive.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderRegularPolygon : public ViewProviderPrimitive +class PartGuiExport ViewProviderRegularPolygon: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRegularPolygon); @@ -47,11 +48,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERREGULARPOLYGON_H - +#endif // PARTGUI_VIEWPROVIDERREGULARPOLYGON_H diff --git a/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp b/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp index a0be2798ed..02746fcf35 100644 --- a/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp +++ b/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp @@ -40,7 +40,7 @@ PROPERTY_SOURCE(PartGui::ViewProviderRuledSurface, PartGui::ViewProviderPart) ViewProviderRuledSurface::ViewProviderRuledSurface() { - sPixmap = "Part_RuledSurface.svg"; + sPixmap = "Part_RuledSurface.svg"; } ViewProviderRuledSurface::~ViewProviderRuledSurface() = default; @@ -61,11 +61,14 @@ void ViewProviderRuledSurface::updateData(const App::Property* prop) { PartGui::ViewProviderPart::updateData(prop); if (prop->is()) { - //const std::vector& hist = static_cast - // (prop)->getValues(); + // const std::vector& hist = static_cast + // (prop)->getValues(); } - /* //The following hides the Children shapes. If the edges from which the Ruled Surface was created - * were selected from the subshapes of another shape, it is likely that one would not want to hide the shape + /* //The following hides the Children shapes. If the edges from which the Ruled Surface was + created + * were selected from the subshapes of another shape, it is likely that one would not want to + hide the shape * hence this section is commented out Part::RuledSurface* pRuledSurface = getObject(); App::DocumentObject *pCurve1 = pRuledSurface->Curve1.getValue(); @@ -74,19 +77,20 @@ void ViewProviderRuledSurface::updateData(const App::Property* prop) Gui::Application::Instance->hideViewProvider(pCurve1); if (pCurve2) Gui::Application::Instance->hideViewProvider(pCurve2);*/ +} - } - -bool ViewProviderRuledSurface::onDelete(const std::vector &) +bool ViewProviderRuledSurface::onDelete(const std::vector&) { // get the input shape Part::RuledSurface* pRuledSurface = getObject(); - App::DocumentObject *pCurve1 = pRuledSurface->Curve1.getValue(); - App::DocumentObject *pCurve2 = pRuledSurface->Curve2.getValue(); - if (pCurve1) + App::DocumentObject* pCurve1 = pRuledSurface->Curve1.getValue(); + App::DocumentObject* pCurve2 = pRuledSurface->Curve2.getValue(); + if (pCurve1) { Gui::Application::Instance->showViewProvider(pCurve1); - if (pCurve2) + } + if (pCurve2) { Gui::Application::Instance->showViewProvider(pCurve2); + } return true; } @@ -96,14 +100,14 @@ bool ViewProviderRuledSurface::onDelete(const std::vector &) std::vector ViewProviderRuledSurface::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderRuledSurface.h b/src/Mod/Part/Gui/ViewProviderRuledSurface.h index 66c8589312..995bd654a2 100644 --- a/src/Mod/Part/Gui/ViewProviderRuledSurface.h +++ b/src/Mod/Part/Gui/ViewProviderRuledSurface.h @@ -30,10 +30,11 @@ #include "ViewProvider.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderRuledSurface:public ViewProviderPart +class PartGuiExport ViewProviderRuledSurface: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRuledSurface); @@ -46,13 +47,12 @@ public: std::vector getDisplayModes() const override; std::vector claimChildren() const override; void updateData(const App::Property*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERRULEDSURFACE_H +#endif // PARTGUI_VIEWPROVIDERRULEDSURFACE_H diff --git a/src/Mod/Part/Gui/ViewProviderScale.cpp b/src/Mod/Part/Gui/ViewProviderScale.cpp index fba451c410..a5e1a6595e 100644 --- a/src/Mod/Part/Gui/ViewProviderScale.cpp +++ b/src/Mod/Part/Gui/ViewProviderScale.cpp @@ -23,14 +23,13 @@ ***************************************************************************/ - #include "ViewProviderScale.h" #include using namespace PartGui; -PROPERTY_SOURCE(PartGui::ViewProviderScale,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartGui::ViewProviderScale, PartGui::ViewProviderPart) ViewProviderScale::ViewProviderScale() { @@ -39,7 +38,7 @@ ViewProviderScale::ViewProviderScale() ViewProviderScale::~ViewProviderScale() = default; -std::vector ViewProviderScale::claimChildren()const +std::vector ViewProviderScale::claimChildren() const { std::vector temp; temp.push_back(getObject()->Base.getValue()); diff --git a/src/Mod/Part/Gui/ViewProviderScale.h b/src/Mod/Part/Gui/ViewProviderScale.h index 041d6af210..ade862a6f4 100644 --- a/src/Mod/Part/Gui/ViewProviderScale.h +++ b/src/Mod/Part/Gui/ViewProviderScale.h @@ -31,9 +31,10 @@ #include "ViewProvider.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderScale : public ViewProviderPart +class PartGuiExport ViewProviderScale: public ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderScale); @@ -47,7 +48,7 @@ public: std::vector claimChildren() const override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERSCALE_H +#endif // PARTGUI_VIEWPROVIDERSCALE_H diff --git a/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp b/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp index 3b2ab065a0..661e49dc16 100644 --- a/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp @@ -35,22 +35,22 @@ PROPERTY_SOURCE(PartGui::ViewProviderSphereParametric, PartGui::ViewProviderPrim ViewProviderSphereParametric::ViewProviderSphereParametric() { - sPixmap = "Part_Sphere_Parametric"; + sPixmap = "Part_Sphere_Parametric"; } ViewProviderSphereParametric::~ViewProviderSphereParametric() = default; std::vector ViewProviderSphereParametric::getDisplayModes() const { - std::vector StrList; + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } // ---------------------------------------------------------------------------- @@ -66,13 +66,13 @@ ViewProviderEllipsoid::~ViewProviderEllipsoid() = default; std::vector ViewProviderEllipsoid::getDisplayModes() const { - std::vector StrList; + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderSphereParametric.h b/src/Mod/Part/Gui/ViewProviderSphereParametric.h index 0171ef449b..63139ea812 100644 --- a/src/Mod/Part/Gui/ViewProviderSphereParametric.h +++ b/src/Mod/Part/Gui/ViewProviderSphereParametric.h @@ -30,9 +30,10 @@ #include "ViewProviderPrimitive.h" -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderSphereParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderSphereParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSphereParametric); @@ -45,10 +46,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -class PartGuiExport ViewProviderEllipsoid : public ViewProviderPrimitive +class PartGuiExport ViewProviderEllipsoid: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderEllipsoid); @@ -60,8 +60,7 @@ public: std::vector getDisplayModes() const override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERSPHEREPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERSPHEREPARAMETRIC_H diff --git a/src/Mod/Part/Gui/ViewProviderSpline.cpp b/src/Mod/Part/Gui/ViewProviderSpline.cpp index 5e160da5c2..e7d7de007d 100644 --- a/src/Mod/Part/Gui/ViewProviderSpline.cpp +++ b/src/Mod/Part/Gui/ViewProviderSpline.cpp @@ -22,27 +22,27 @@ * * ***************************************************************************/ -# include -# include +#include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include -# include +#include +#include +#include #include #include @@ -78,7 +78,7 @@ EXTENSION_PROPERTY_SOURCE(PartGui::ViewProviderSplineExtension, Gui::ViewProvide ViewProviderSplineExtension::ViewProviderSplineExtension() { initExtensionType(ViewProviderSplineExtension::getExtensionClassTypeId()); - EXTENSION_ADD_PROPERTY(ControlPoints,(false)); + EXTENSION_ADD_PROPERTY(ControlPoints, (false)); } void ViewProviderSplineExtension::toggleControlPoints(bool on) @@ -93,9 +93,7 @@ void ViewProviderSplineExtension::extensionSetupContextMenu(QMenu* menu, QObject QAction* act = menu->addAction(QObject::tr("Show Control Points")); act->setCheckable(true); act->setChecked(ControlPoints.getValue()); - func->toggle(act, [this](bool on) { - this->toggleControlPoints(on); - }); + func->toggle(act, [this](bool on) { this->toggleControlPoints(on); }); } void ViewProviderSplineExtension::extensionUpdateData(const App::Property* prop) @@ -134,14 +132,16 @@ void ViewProviderSplineExtension::showControlPoints(bool show, const App::Proper pcControlPoints->whichChild = (show ? SO_SWITCH_ALL : SO_SWITCH_NONE); } - if (!show || !pcControlPoints || pcControlPoints->getNumChildren() > 0) + if (!show || !pcControlPoints || pcControlPoints->getNumChildren() > 0) { return; + } // ask for the property we are interested in if (prop && prop->is()) { const TopoDS_Shape& shape = static_cast(prop)->getValue(); - if (shape.IsNull()) - return; // empty shape + if (shape.IsNull()) { + return; // empty shape + } for (TopExp_Explorer xp(shape, TopAbs_SHELL); xp.More(); xp.Next()) { const TopoDS_Shell& shell = TopoDS::Shell(xp.Current()); @@ -171,55 +171,58 @@ void ViewProviderSplineExtension::showControlPoints(bool show, const App::Proper void ViewProviderSplineExtension::showControlPointsOfEdge(const TopoDS_Edge& edge) { std::list poles, knots; - Standard_Integer nCt=0; + Standard_Integer nCt = 0; TopoDS_Edge edge_loc(edge); TopLoc_Location aLoc; edge_loc.Location(aLoc); BRepAdaptor_Curve curve(edge_loc); - switch (curve.GetType()) - { - case GeomAbs_BezierCurve: - { + switch (curve.GetType()) { + case GeomAbs_BezierCurve: { Handle(Geom_BezierCurve) hBezier = curve.Bezier(); nCt = hBezier->NbPoles(); - for (Standard_Integer i = 1; i <= nCt; i++) + for (Standard_Integer i = 1; i <= nCt; i++) { poles.push_back(hBezier->Pole(i)); + } if (hBezier->IsClosed()) { nCt++; poles.push_back(hBezier->Pole(1)); } - } break; - case GeomAbs_BSplineCurve: - { + } break; + case GeomAbs_BSplineCurve: { Handle(Geom_BSplineCurve) hBSpline = curve.BSpline(); nCt = hBSpline->NbPoles(); - for (Standard_Integer i = 1; i <= nCt; i++) + for (Standard_Integer i = 1; i <= nCt; i++) { poles.push_back(hBSpline->Pole(i)); + } if (hBSpline->IsClosed()) { nCt++; poles.push_back(hBSpline->Pole(1)); } - for (Standard_Integer i = hBSpline->FirstUKnotIndex()+1; i <= hBSpline->LastUKnotIndex()-1; i++) + for (Standard_Integer i = hBSpline->FirstUKnotIndex() + 1; + i <= hBSpline->LastUKnotIndex() - 1; + i++) { knots.push_back(hBSpline->Value(hBSpline->Knot(i))); - } break; - default: - break; + } + } break; + default: + break; } - if (poles.empty()) - return; // nothing to do + if (poles.empty()) { + return; // nothing to do + } - SoCoordinate3 * controlcoords = new SoCoordinate3; + SoCoordinate3* controlcoords = new SoCoordinate3; controlcoords->point.setNum(nCt + knots.size()); - int index=0; + int index = 0; SbVec3f* verts = controlcoords->point.startEditing(); - for (const auto & pole : poles) { + for (const auto& pole : poles) { verts[index++].setValue((float)pole.X(), (float)pole.Y(), (float)pole.Z()); } - for (const auto & knot : knots) { + for (const auto& knot : knots) { verts[index++].setValue((float)knot.X(), (float)knot.Y(), (float)knot.Z()); } controlcoords->point.finishEditing(); @@ -239,66 +242,68 @@ void ViewProviderSplineExtension::showControlPointsOfEdge(const TopoDS_Edge& edg void ViewProviderSplineExtension::showControlPointsOfFace(const TopoDS_Face& face) { std::list knots; - std::vector > poles; - Standard_Integer nCtU=0, nCtV=0; + std::vector> poles; + Standard_Integer nCtU = 0, nCtV = 0; TopoDS_Face face_loc(face); TopLoc_Location aLoc; face_loc.Location(aLoc); BRepAdaptor_Surface surface(face_loc); - switch (surface.GetType()) - { - case GeomAbs_BezierSurface: - { + switch (surface.GetType()) { + case GeomAbs_BezierSurface: { Handle(Geom_BezierSurface) hBezier = surface.Bezier(); nCtU = hBezier->NbUPoles(); nCtV = hBezier->NbVPoles(); poles.resize(nCtU); for (Standard_Integer u = 1; u <= nCtU; u++) { - poles[u-1].resize(nCtV); - for (Standard_Integer v = 1; v <= nCtV; v++) - poles[u-1][v-1] = hBezier->Pole(u, v); + poles[u - 1].resize(nCtV); + for (Standard_Integer v = 1; v <= nCtV; v++) { + poles[u - 1][v - 1] = hBezier->Pole(u, v); + } } - } break; - case GeomAbs_BSplineSurface: - { + } break; + case GeomAbs_BSplineSurface: { Handle(Geom_BSplineSurface) hBSpline = surface.BSpline(); nCtU = hBSpline->NbUPoles(); nCtV = hBSpline->NbVPoles(); poles.resize(nCtU); for (Standard_Integer u = 1; u <= nCtU; u++) { - poles[u-1].resize(nCtV); - for (Standard_Integer v = 1; v <= nCtV; v++) - poles[u-1][v-1] = hBSpline->Pole(u, v); + poles[u - 1].resize(nCtV); + for (Standard_Integer v = 1; v <= nCtV; v++) { + poles[u - 1][v - 1] = hBSpline->Pole(u, v); + } } - //Standard_Integer nKnU = hBSpline->NbUKnots(); - //Standard_Integer nKnV = hBSpline->NbVKnots(); + // Standard_Integer nKnU = hBSpline->NbUKnots(); + // Standard_Integer nKnV = hBSpline->NbVKnots(); for (Standard_Integer u = 1; u <= hBSpline->NbUKnots(); u++) { - for (Standard_Integer v = 1; v <= hBSpline->NbVKnots(); v++) + for (Standard_Integer v = 1; v <= hBSpline->NbVKnots(); v++) { knots.push_back(hBSpline->Value(hBSpline->UKnot(u), hBSpline->VKnot(v))); + } } - } break; - default: - break; + } break; + default: + break; } - if (poles.empty()) - return; // nothing to do + if (poles.empty()) { + return; // nothing to do + } - SoCoordinate3 * coords = new SoCoordinate3; - coords->point.setNum((static_cast(nCtU) * static_cast(nCtV)) + - static_cast(knots.size())); + SoCoordinate3* coords = new SoCoordinate3; + coords->point.setNum( + (static_cast(nCtU) * static_cast(nCtV)) + static_cast(knots.size()) + ); - int index=0; + int index = 0; SbVec3f* verts = coords->point.startEditing(); - for (const auto & pole : poles) { + for (const auto& pole : poles) { for (const auto& v : pole) { verts[index++].setValue((float)v.X(), (float)v.Y(), (float)v.Z()); } } - for (const auto & knot : knots) { + for (const auto& knot : knots) { verts[index++].setValue((float)knot.X(), (float)knot.Y(), (float)knot.Z()); } coords->point.finishEditing(); @@ -308,10 +313,10 @@ void ViewProviderSplineExtension::showControlPointsOfFace(const TopoDS_Face& fac control->numPolesU = nCtU; control->numPolesV = nCtV; - //if (knots.size() > 0) { - // control->numKnotsU = nKnU; - // control->numKnotsV = nKnV; - //} + // if (knots.size() > 0) { + // control->numKnotsU = nKnU; + // control->numKnotsV = nKnV; + // } SoSeparator* nodes = new SoSeparator(); nodes->addChild(coords); @@ -320,9 +325,13 @@ void ViewProviderSplineExtension::showControlPointsOfFace(const TopoDS_Face& fac pcControlPoints->addChild(nodes); } -namespace Gui { - EXTENSION_PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProviderSplineExtensionPython, PartGui::ViewProviderSplineExtension) +namespace Gui +{ +EXTENSION_PROPERTY_SOURCE_TEMPLATE( + PartGui::ViewProviderSplineExtensionPython, + PartGui::ViewProviderSplineExtension +) // explicit template instantiation - template class PartGuiExport ViewProviderExtensionPythonT; -} +template class PartGuiExport ViewProviderExtensionPythonT; +} // namespace Gui diff --git a/src/Mod/Part/Gui/ViewProviderSpline.h b/src/Mod/Part/Gui/ViewProviderSpline.h index 2fe2cc1bef..9965afac0d 100644 --- a/src/Mod/Part/Gui/ViewProviderSpline.h +++ b/src/Mod/Part/Gui/ViewProviderSpline.h @@ -33,7 +33,7 @@ namespace PartGui { -class PartGuiExport ViewProviderSplineExtension : public Gui::ViewProviderExtension +class PartGuiExport ViewProviderSplineExtension: public Gui::ViewProviderExtension { EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSplineExtension); @@ -54,10 +54,10 @@ protected: void showControlPointsOfEdge(const TopoDS_Edge&); void showControlPointsOfFace(const TopoDS_Face&); - SoSwitch *pcControlPoints{nullptr}; + SoSwitch* pcControlPoints {nullptr}; }; -class PartGuiExport ViewProviderSpline : public ViewProviderPartExt +class PartGuiExport ViewProviderSpline: public ViewProviderPartExt { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSpline); @@ -73,10 +73,10 @@ private: ViewProviderSplineExtension extension; }; -using ViewProviderSplineExtensionPython = Gui::ViewProviderExtensionPythonT; +using ViewProviderSplineExtensionPython + = Gui::ViewProviderExtensionPythonT; -} //namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERPARTSPLINE_H - +#endif // PARTGUI_VIEWPROVIDERPARTSPLINE_H diff --git a/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp b/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp index 6fa913d854..d399d65278 100644 --- a/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp @@ -37,7 +37,7 @@ PROPERTY_SOURCE(PartGui::ViewProviderTorusParametric, PartGui::ViewProviderPrimi ViewProviderTorusParametric::ViewProviderTorusParametric() { - sPixmap = "Part_Torus_Parametric"; + sPixmap = "Part_Torus_Parametric"; } ViewProviderTorusParametric::~ViewProviderTorusParametric() = default; @@ -46,14 +46,14 @@ ViewProviderTorusParametric::~ViewProviderTorusParametric() = default; std::vector ViewProviderTorusParametric::getDisplayModes() const { - // get the modes of the father - std::vector StrList; + // get the modes of the father + std::vector StrList; - // add your own modes - StrList.emplace_back("Flat Lines"); - StrList.emplace_back("Shaded"); - StrList.emplace_back("Wireframe"); - StrList.emplace_back("Points"); + // add your own modes + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); - return StrList; + return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderTorusParametric.h b/src/Mod/Part/Gui/ViewProviderTorusParametric.h index e4994e40af..3403fae6d1 100644 --- a/src/Mod/Part/Gui/ViewProviderTorusParametric.h +++ b/src/Mod/Part/Gui/ViewProviderTorusParametric.h @@ -37,10 +37,11 @@ class SoSeparator; class SbVec3f; class SoTransform; -namespace PartGui { +namespace PartGui +{ -class PartGuiExport ViewProviderTorusParametric : public ViewProviderPrimitive +class PartGuiExport ViewProviderTorusParametric: public ViewProviderPrimitive { PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderTorusParametric); @@ -53,11 +54,9 @@ public: std::vector getDisplayModes() const override; protected: - }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_VIEWPROVIDERTORUSPARAMETRIC_H - +#endif // PARTGUI_VIEWPROVIDERTORUSPARAMETRIC_H diff --git a/src/Mod/Part/Gui/Workbench.cpp b/src/Mod/Part/Gui/Workbench.cpp index 5905f34816..d03870c226 100644 --- a/src/Mod/Part/Gui/Workbench.cpp +++ b/src/Mod/Part/Gui/Workbench.cpp @@ -23,7 +23,6 @@ ***************************************************************************/ - #include "Workbench.h" #include #include @@ -31,7 +30,7 @@ using namespace PartGui; -#if 0 // needed for Qt's lupdate utility +#if 0 // needed for Qt's lupdate utility qApp->translate("Workbench", "&Part"); qApp->translate("Workbench", "&Simple"); qApp->translate("Workbench", "&Parametric"); @@ -48,7 +47,8 @@ using namespace PartGui; /// @namespace PartGui @class Workbench TYPESYSTEM_SOURCE(PartGui::Workbench, Gui::StdWorkbench) -Workbench::Workbench() { +Workbench::Workbench() +{ /** If we are to have Sketcher_NewSketch as command in toolbar and menu, then we must assure SketcherGui has already been loaded. By putting this in a try/except block we avoid creating a dependency @@ -56,16 +56,14 @@ Workbench::Workbench() { Note that BUILD_SKETCHER is a cmake-gui option. **/ - const char* code = - "try:\n" - " import SketcherGui\n" - " success = 'True'\n" - "except ImportError:\n" - " success = 'False'"; + const char* code = "try:\n" + " import SketcherGui\n" + " success = 'True'\n" + "except ImportError:\n" + " success = 'False'"; const std::string result = Base::Interpreter().runStringWithKey(code, "success", "False"); hasSketcher = (result == "True"); - } Workbench::~Workbench() = default; @@ -123,20 +121,16 @@ Gui::MenuItem* Workbench::setupMenuBar() const part->setCommand("&Part"); *part << "Part_BoxSelection" << "Separator"; - *part << prim - << "Part_Primitives" + *part << prim << "Part_Primitives" << "Part_Builder" << "Separator" << "Part_ShapeFromMesh" << "Part_PointsFromMesh" << "Part_MakeSolid" - << "Part_ReverseShape" - << copy - << "Separator" - << bop << join << split << compound + << "Part_ReverseShape" << copy << "Separator" << bop << join << split << compound << "Separator"; if (hasSketcher) { - *part << "Sketcher_NewSketch"; + *part << "Sketcher_NewSketch"; } *part << "Part_Extrude" << "Part_Revolve" diff --git a/src/Mod/Part/Gui/Workbench.h b/src/Mod/Part/Gui/Workbench.h index ef2b5a4c82..3bfe449076 100644 --- a/src/Mod/Part/Gui/Workbench.h +++ b/src/Mod/Part/Gui/Workbench.h @@ -29,29 +29,30 @@ #include #include -namespace PartGui { +namespace PartGui +{ /** * @author Werner Mayer */ -class PartGuiExport Workbench : public Gui::StdWorkbench +class PartGuiExport Workbench: public Gui::StdWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - Workbench(); - ~Workbench() override; + Workbench(); + ~Workbench() override; private: - bool hasSketcher = false; + bool hasSketcher = false; protected: - Gui::MenuItem* setupMenuBar() const override; - Gui::ToolBarItem* setupToolBars() const override; - Gui::ToolBarItem* setupCommandBars() const override; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; -} // namespace PartGui +} // namespace PartGui -#endif // PART_WORKBENCH_H +#endif // PART_WORKBENCH_H diff --git a/src/Mod/Part/Gui/WorkbenchManipulator.cpp b/src/Mod/Part/Gui/WorkbenchManipulator.cpp index eef71b69f7..93fbafd1aa 100644 --- a/src/Mod/Part/Gui/WorkbenchManipulator.cpp +++ b/src/Mod/Part/Gui/WorkbenchManipulator.cpp @@ -29,8 +29,7 @@ using namespace PartGui; void WorkbenchManipulator::modifyMenuBar([[maybe_unused]] Gui::MenuItem* menuBar) -{ -} +{} void WorkbenchManipulator::modifyToolBars(Gui::ToolBarItem* toolBar) { @@ -39,13 +38,12 @@ void WorkbenchManipulator::modifyToolBars(Gui::ToolBarItem* toolBar) } void WorkbenchManipulator::modifyDockWindows([[maybe_unused]] Gui::DockWindowItems* dockWindow) -{ -} +{} void WorkbenchManipulator::addSelectionFilter(Gui::ToolBarItem* toolBar) { if (auto view = toolBar->findItem("View")) { - auto add = new Gui::ToolBarItem(); // NOLINT + auto add = new Gui::ToolBarItem(); // NOLINT add->setCommand("Part_SelectFilter"); auto item = view->findItem("Std_TreeViewActions"); if (item) { @@ -60,7 +58,7 @@ void WorkbenchManipulator::addSelectionFilter(Gui::ToolBarItem* toolBar) void WorkbenchManipulator::addDatums(Gui::ToolBarItem* toolBar) { if (auto view = toolBar->findItem("Structure")) { - auto add = new Gui::ToolBarItem(); // NOLINT + auto add = new Gui::ToolBarItem(); // NOLINT add->setCommand("Part_Datums"); auto item = view->findItem("Std_Group"); if (item) { diff --git a/src/Mod/Part/Gui/WorkbenchManipulator.h b/src/Mod/Part/Gui/WorkbenchManipulator.h index 1f5dfbd5a0..4b9a22bbc3 100644 --- a/src/Mod/Part/Gui/WorkbenchManipulator.h +++ b/src/Mod/Part/Gui/WorkbenchManipulator.h @@ -27,7 +27,8 @@ #include -namespace PartGui { +namespace PartGui +{ class WorkbenchManipulator: public Gui::WorkbenchManipulator { @@ -56,7 +57,7 @@ private: static void addDatums(Gui::ToolBarItem* toolBar); }; -} // namespace PartGui +} // namespace PartGui -#endif // PARTGUI_WORKBENCHMANIPULATOR_H +#endif // PARTGUI_WORKBENCHMANIPULATOR_H diff --git a/src/Mod/Part/Init.py b/src/Mod/Part/Init.py index bf001f04eb..99f8f65490 100644 --- a/src/Mod/Part/Init.py +++ b/src/Mod/Part/Init.py @@ -1,37 +1,37 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#*************************************************************************** -#* Copyright (c) 2001, 2002 Juergen Riegel * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD 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 Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#***************************************************************************/ +# *************************************************************************** +# * Copyright (c) 2001, 2002 Juergen Riegel * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD 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 Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# ***************************************************************************/ # FreeCAD init script of the part module -#FreeCAD.addImportType("CAD formats (*.igs *.iges *.step *.stp *.brep *.brp)","Part") -#FreeCAD.addExportType("CAD formats (*.igs *.iges *.step *.stp *.brep *.brp)","Part") -FreeCAD.addImportType("BREP format (*.brep *.BREP *.brp *.BRP)","Part") -FreeCAD.addExportType("BREP format (*.brep *.brp)","Part") -FreeCAD.addImportType("IGES format (*.iges *.IGES *.igs *.IGS)","Part") -FreeCAD.addExportType("IGES format (*.iges *.igs)","Part") -FreeCAD.addImportType("STEP with colors (*.step *.STEP *.stp *.STP)","Import") -FreeCAD.addExportType("STEP with colors (*.step *.stp)","Import") +# FreeCAD.addImportType("CAD formats (*.igs *.iges *.step *.stp *.brep *.brp)","Part") +# FreeCAD.addExportType("CAD formats (*.igs *.iges *.step *.stp *.brep *.brp)","Part") +FreeCAD.addImportType("BREP format (*.brep *.BREP *.brp *.BRP)", "Part") +FreeCAD.addExportType("BREP format (*.brep *.brp)", "Part") +FreeCAD.addImportType("IGES format (*.iges *.IGES *.igs *.IGS)", "Part") +FreeCAD.addExportType("IGES format (*.iges *.igs)", "Part") +FreeCAD.addImportType("STEP with colors (*.step *.STEP *.stp *.STP)", "Import") +FreeCAD.addExportType("STEP with colors (*.step *.stp)", "Import") -FreeCAD.__unit_test__ += [ "TestPartApp" ] +FreeCAD.__unit_test__ += ["TestPartApp"] diff --git a/src/Mod/Part/InitGui.py b/src/Mod/Part/InitGui.py index a935565c41..c174ad5c07 100644 --- a/src/Mod/Part/InitGui.py +++ b/src/Mod/Part/InitGui.py @@ -33,10 +33,9 @@ class PartWorkbench(Gui.Workbench): """Part workbench object.""" def __init__(self): - self.__class__.Icon = os.path.join(App.getResourceDir(), - "Mod", "Part", - "Resources", "icons", - "PartWorkbench.svg") + self.__class__.Icon = os.path.join( + App.getResourceDir(), "Mod", "Part", "Resources", "icons", "PartWorkbench.svg" + ) self.__class__.MenuText = "Part" self.__class__.ToolTip = "Part workbench" @@ -47,15 +46,17 @@ class PartWorkbench(Gui.Workbench): try: import BasicShapes.CommandShapes except ImportError as err: - App.Console.PrintError("'BasicShapes' package cannot be loaded. " - "{err}\n".format(err=str(err))) + App.Console.PrintError( + "'BasicShapes' package cannot be loaded. " "{err}\n".format(err=str(err)) + ) try: import CompoundTools._CommandCompoundFilter import CompoundTools._CommandExplodeCompound except ImportError as err: - App.Console.PrintError("'CompoundTools' package cannot be loaded. " - "{err}\n".format(err=str(err))) + App.Console.PrintError( + "'CompoundTools' package cannot be loaded. " "{err}\n".format(err=str(err)) + ) try: bop = __import__("BOPTools") @@ -63,8 +64,9 @@ class PartWorkbench(Gui.Workbench): bop.addCommands() PartGui.BOPTools = bop except Exception as err: - App.Console.PrintError("'BOPTools' package cannot be loaded. " - "{err}\n".format(err=str(err))) + App.Console.PrintError( + "'BOPTools' package cannot be loaded. " "{err}\n".format(err=str(err)) + ) def GetClassName(self): return "PartGui::Workbench" diff --git a/src/Mod/Part/JoinFeatures.py b/src/Mod/Part/JoinFeatures.py index bc249c794c..4dafc92955 100644 --- a/src/Mod/Part/JoinFeatures.py +++ b/src/Mod/Part/JoinFeatures.py @@ -32,9 +32,9 @@ FreeCAD v0.16. Do not use. Use BOPTools.JoinFeatures instead." def getParamRefine(): - return FreeCAD.ParamGet( - "User parameter:BaseApp/Preferences/Mod/Part/Boolean" - ).GetBool("RefineModel") + return FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Part/Boolean").GetBool( + "RefineModel" + ) def shapeOfMaxVol(compound): @@ -57,7 +57,6 @@ def shapeOfMaxVol(compound): return compound - class _PartJoinFeature: "The PartJoinFeature object" @@ -67,7 +66,8 @@ class _PartJoinFeature: "App::PropertyEnumeration", "Mode", "Join", - "The mode of operation. bypass = make compound (fast)", locked=True, + "The mode of operation. bypass = make compound (fast)", + locked=True, ) obj.Mode = ["bypass", "Connect", "Embed", "Cutout"] obj.addProperty("App::PropertyLink", "Base", "Join", "First object", locked=True) @@ -76,7 +76,8 @@ class _PartJoinFeature: "App::PropertyBool", "Refine", "Join", - "True = refine resulting shape. False = output as is.", locked=True, + "True = refine resulting shape. False = output as is.", + locked=True, ) obj.Proxy = self @@ -113,11 +114,11 @@ class _ViewProviderPartJoinFeature: return ":/icons/booleans/Part_JoinConnect.svg" else: return { - "bypass": ":/icons/booleans/Part_JoinBypass.svg", - "Connect": ":/icons/booleans/Part_JoinConnect.svg", - "Embed": ":/icons/booleans/Part_JoinEmbed.svg", - "Cutout": ":/icons/booleans/Part_JoinCutout.svg", - }[self.Object.Mode] + "bypass": ":/icons/booleans/Part_JoinBypass.svg", + "Connect": ":/icons/booleans/Part_JoinConnect.svg", + "Embed": ":/icons/booleans/Part_JoinEmbed.svg", + "Cutout": ":/icons/booleans/Part_JoinCutout.svg", + }[self.Object.Mode] def attach(self, vobj): self.ViewObject = vobj diff --git a/src/Mod/Part/MakeBottle.py b/src/Mod/Part/MakeBottle.py index c9e9ea8c0e..3bcc182cae 100644 --- a/src/Mod/Part/MakeBottle.py +++ b/src/Mod/Part/MakeBottle.py @@ -5,131 +5,136 @@ import Part, math import FreeCAD, FreeCADGui -App=FreeCAD -Gui=FreeCADGui + +App = FreeCAD +Gui = FreeCADGui from FreeCAD import Base + def makeBottle(myWidth=50.0, myHeight=70.0, myThickness=30.0): - aPnt1=Base.Vector(-myWidth/2.,0,0) - aPnt2=Base.Vector(-myWidth/2.,-myThickness/4.,0) - aPnt3=Base.Vector(0,-myThickness/2.,0) - aPnt4=Base.Vector(myWidth/2.,-myThickness/4.,0) - aPnt5=Base.Vector(myWidth/2.,0,0) + aPnt1 = Base.Vector(-myWidth / 2.0, 0, 0) + aPnt2 = Base.Vector(-myWidth / 2.0, -myThickness / 4.0, 0) + aPnt3 = Base.Vector(0, -myThickness / 2.0, 0) + aPnt4 = Base.Vector(myWidth / 2.0, -myThickness / 4.0, 0) + aPnt5 = Base.Vector(myWidth / 2.0, 0, 0) - aArcOfCircle = Part.Arc(aPnt2,aPnt3,aPnt4) - aSegment1=Part.LineSegment(aPnt1,aPnt2) - aSegment2=Part.LineSegment(aPnt4,aPnt5) + aArcOfCircle = Part.Arc(aPnt2, aPnt3, aPnt4) + aSegment1 = Part.LineSegment(aPnt1, aPnt2) + aSegment2 = Part.LineSegment(aPnt4, aPnt5) - aEdge1=aSegment1.toShape() - aEdge2=aArcOfCircle.toShape() - aEdge3=aSegment2.toShape() - aWire=Part.Wire([aEdge1,aEdge2,aEdge3]) + aEdge1 = aSegment1.toShape() + aEdge2 = aArcOfCircle.toShape() + aEdge3 = aSegment2.toShape() + aWire = Part.Wire([aEdge1, aEdge2, aEdge3]) - aTrsf=Base.Matrix() - aTrsf.rotateZ(math.pi) # rotate around the z-axis + aTrsf = Base.Matrix() + aTrsf.rotateZ(math.pi) # rotate around the z-axis - aMirroredWire=aWire.copy() - aMirroredWire.transformShape(aTrsf) - myWireProfile=Part.Wire([aWire,aMirroredWire]) + aMirroredWire = aWire.copy() + aMirroredWire.transformShape(aTrsf) + myWireProfile = Part.Wire([aWire, aMirroredWire]) - myFaceProfile=Part.Face(myWireProfile) - aPrismVec=Base.Vector(0,0,myHeight) - myBody=myFaceProfile.extrude(aPrismVec) + myFaceProfile = Part.Face(myWireProfile) + aPrismVec = Base.Vector(0, 0, myHeight) + myBody = myFaceProfile.extrude(aPrismVec) - myBody=myBody.makeFillet(myThickness/12.0,myBody.Edges) + myBody = myBody.makeFillet(myThickness / 12.0, myBody.Edges) - neckLocation=Base.Vector(0,0,myHeight) - neckNormal=Base.Vector(0,0,1) + neckLocation = Base.Vector(0, 0, myHeight) + neckNormal = Base.Vector(0, 0, 1) - myNeckRadius = myThickness / 4. - myNeckHeight = myHeight / 10 - myNeck = Part.makeCylinder(myNeckRadius,myNeckHeight,neckLocation,neckNormal) - myBody = myBody.fuse(myNeck) + myNeckRadius = myThickness / 4.0 + myNeckHeight = myHeight / 10 + myNeck = Part.makeCylinder(myNeckRadius, myNeckHeight, neckLocation, neckNormal) + myBody = myBody.fuse(myNeck) - faceToRemove = 0 - zMax = -1.0 + faceToRemove = 0 + zMax = -1.0 - for xp in myBody.Faces: - surf = xp.Surface - if type(surf) == Part.Plane: - z = surf.Position.z - if z > zMax: - zMax = z - faceToRemove = xp + for xp in myBody.Faces: + surf = xp.Surface + if type(surf) == Part.Plane: + z = surf.Position.z + if z > zMax: + zMax = z + faceToRemove = xp - # This doesn't work for any reason - myBody = myBody.makeThickness([faceToRemove],-myThickness/50 , 1.e-3) - myThreading = Part.makeThread(myNeckHeight/10, myNeckRadius*0.06, myHeight/10, myNeckRadius*0.99) - myThreading.translate(Base.Vector(0,0,myHeight)) - myCompound = Part.makeCompound([myBody, myThreading]) + # This doesn't work for any reason + myBody = myBody.makeThickness([faceToRemove], -myThickness / 50, 1.0e-3) + myThreading = Part.makeThread( + myNeckHeight / 10, myNeckRadius * 0.06, myHeight / 10, myNeckRadius * 0.99 + ) + myThreading.translate(Base.Vector(0, 0, myHeight)) + myCompound = Part.makeCompound([myBody, myThreading]) + + return myCompound - return myCompound def makeBoreHole(): - # create a document if needed - if App.ActiveDocument is None: - App.newDocument("Solid") + # create a document if needed + if App.ActiveDocument is None: + App.newDocument("Solid") - Group = App.ActiveDocument.addObject("App::DocumentObjectGroup","Group") - Group.Label="Bore hole" + Group = App.ActiveDocument.addObject("App::DocumentObjectGroup", "Group") + Group.Label = "Bore hole" - V1 = Base.Vector(0,10,0) - V2 = Base.Vector(30,10,0) - V3 = Base.Vector(30,-10,0) - V4 = Base.Vector(0,-10,0) - VC1 = Base.Vector(-10,0,0) - C1 = Part.Arc(V1,VC1,V4) - # and the second one - VC2 = Base.Vector(40,0,0) - C2 = Part.Arc(V2,VC2,V3) - L1 = Part.LineSegment(V1,V2) - # and the second one - L2 = Part.LineSegment(V4,V3) - S1 = Part.Shape([C1,C2,L1,L2]) + V1 = Base.Vector(0, 10, 0) + V2 = Base.Vector(30, 10, 0) + V3 = Base.Vector(30, -10, 0) + V4 = Base.Vector(0, -10, 0) + VC1 = Base.Vector(-10, 0, 0) + C1 = Part.Arc(V1, VC1, V4) + # and the second one + VC2 = Base.Vector(40, 0, 0) + C2 = Part.Arc(V2, VC2, V3) + L1 = Part.LineSegment(V1, V2) + # and the second one + L2 = Part.LineSegment(V4, V3) + S1 = Part.Shape([C1, C2, L1, L2]) - W=Part.Wire(S1.Edges) - F=Part.makeFace(W) - P=F.extrude(Base.Vector(0,0,5)) + W = Part.Wire(S1.Edges) + F = Part.makeFace(W) + P = F.extrude(Base.Vector(0, 0, 5)) - # add objects with the shape - Wire=Group.newObject("Part::Feature","Wire") - Wire.Shape=W - Face=Group.newObject("Part::Feature","Face") - Face.Shape=F - Prism=Group.newObject("Part::Feature","Extrude") - Prism.Shape=P + # add objects with the shape + Wire = Group.newObject("Part::Feature", "Wire") + Wire.Shape = W + Face = Group.newObject("Part::Feature", "Face") + Face.Shape = F + Prism = Group.newObject("Part::Feature", "Extrude") + Prism.Shape = P - c=Part.Circle(Base.Vector(0,0,-1),Base.Vector(0,0,1),2.0) - w=Part.Wire(c.toShape()) - f=Part.makeFace(w) - p=f.extrude(Base.Vector(0,0,7)) - P=P.cut(p) + c = Part.Circle(Base.Vector(0, 0, -1), Base.Vector(0, 0, 1), 2.0) + w = Part.Wire(c.toShape()) + f = Part.makeFace(w) + p = f.extrude(Base.Vector(0, 0, 7)) + P = P.cut(p) - # add first borer - Bore1=Group.newObject("Part::Feature","Borer_1") - Bore1.Shape=p - Hole1=Group.newObject("Part::Feature","Borer_Hole1") - Hole1.Shape=P + # add first borer + Bore1 = Group.newObject("Part::Feature", "Borer_1") + Bore1.Shape = p + Hole1 = Group.newObject("Part::Feature", "Borer_Hole1") + Hole1.Shape = P - c=Part.Circle(Base.Vector(0,-11,2.5),Base.Vector(0,1,0),1.0) - w=Part.Wire(c.toShape()) - f=Part.makeFace(w) - p=f.extrude(Base.Vector(0,22,0)) - P=P.cut(p) + c = Part.Circle(Base.Vector(0, -11, 2.5), Base.Vector(0, 1, 0), 1.0) + w = Part.Wire(c.toShape()) + f = Part.makeFace(w) + p = f.extrude(Base.Vector(0, 22, 0)) + P = P.cut(p) - # add second borer - Bore2=Group.newObject("Part::Feature","Borer_2") - Bore2.Shape=p - Hole2=Group.newObject("Part::Feature","Borer_Hole2") - Hole2.Shape=P + # add second borer + Bore2 = Group.newObject("Part::Feature", "Borer_2") + Bore2.Shape = p + Hole2 = Group.newObject("Part::Feature", "Borer_Hole2") + Hole2.Shape = P - App.ActiveDocument.recompute() + App.ActiveDocument.recompute() - # hide all objects except of the final one - Gui.ActiveDocument.getObject(Wire.Name).hide() - Gui.ActiveDocument.getObject(Face.Name).hide() - Gui.ActiveDocument.getObject(Prism.Name).hide() - Gui.ActiveDocument.getObject(Bore1.Name).hide() - Gui.ActiveDocument.getObject(Hole1.Name).hide() - Gui.ActiveDocument.getObject(Bore2.Name).hide() - Gui.ActiveDocument.ActiveView.fitAll() + # hide all objects except of the final one + Gui.ActiveDocument.getObject(Wire.Name).hide() + Gui.ActiveDocument.getObject(Face.Name).hide() + Gui.ActiveDocument.getObject(Prism.Name).hide() + Gui.ActiveDocument.getObject(Bore1.Name).hide() + Gui.ActiveDocument.getObject(Hole1.Name).hide() + Gui.ActiveDocument.getObject(Bore2.Name).hide() + Gui.ActiveDocument.ActiveView.fitAll() diff --git a/src/Mod/Part/PartEnums.py b/src/Mod/Part/PartEnums.py index 94574ce80c..ee1224040c 100644 --- a/src/Mod/Part/PartEnums.py +++ b/src/Mod/Part/PartEnums.py @@ -29,11 +29,13 @@ __doc__ = "Enum types" from enum import IntEnum + class JoinType(IntEnum): Arc = 0 Tangent = 1 Intersection = 2 + class Shape(IntEnum): C0 = 0 G1 = 1 @@ -43,28 +45,32 @@ class Shape(IntEnum): C3 = 5 CN = 6 + class FillingStyle(IntEnum): StretchStyle = 0 CoonsStyle = 1 CurvedStyle = 2 + class Orientation(IntEnum): FORWARD = 0 REVERSED = 1 INTERNAL = 2 EXTERNAL = 3 + class ShapeEnum(IntEnum): COMPOUND = 0 COMPSOLID = 1 SOLID = 2 - SHELL= 3 + SHELL = 3 FACE = 4 WIRE = 5 EDGE = 6 VERTEX = 7 SHAPE = 8 + class HLRBRep_TypeOfResultingEdge(IntEnum): Undefined = 0 IsoLine = 1 @@ -73,7 +79,7 @@ class HLRBRep_TypeOfResultingEdge(IntEnum): RgNLine = 4 Sharp = 5 + class SingleShapeCompoundCreationPolicy(IntEnum): ReturnShape = 0 ForceCompound = 1 - diff --git a/src/Mod/Part/PartGlobal.h b/src/Mod/Part/PartGlobal.h index f74e0c0b8a..2c9a09bed2 100644 --- a/src/Mod/Part/PartGlobal.h +++ b/src/Mod/Part/PartGlobal.h @@ -25,28 +25,28 @@ #include #ifndef PART_GLOBAL_H -#define PART_GLOBAL_H +# define PART_GLOBAL_H // Part -#ifndef PartExport -#ifdef Part_EXPORTS -# define PartExport FREECAD_DECL_EXPORT -#else -# define PartExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PartExport +# ifdef Part_EXPORTS +# define PartExport FREECAD_DECL_EXPORT +# else +# define PartExport FREECAD_DECL_IMPORT +# endif +# endif -#ifndef AttacherExport -# define AttacherExport PartExport -#endif +# ifndef AttacherExport +# define AttacherExport PartExport +# endif // PartGui -#ifndef PartGuiExport -#ifdef PartGui_EXPORTS -# define PartGuiExport FREECAD_DECL_EXPORT -#else -# define PartGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PartGuiExport +# ifdef PartGui_EXPORTS +# define PartGuiExport FREECAD_DECL_EXPORT +# else +# define PartGuiExport FREECAD_DECL_IMPORT +# endif +# endif -#endif //PART_GLOBAL_H +#endif // PART_GLOBAL_H diff --git a/src/Mod/Part/TestPartApp.py b/src/Mod/Part/TestPartApp.py index f0dffa9571..58fe87a578 100644 --- a/src/Mod/Part/TestPartApp.py +++ b/src/Mod/Part/TestPartApp.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#************************************************************************** +# ************************************************************************** # Copyright (c) 2011 Juergen Riegel * # * # This file is part of the FreeCAD CAx development system. * @@ -20,13 +20,14 @@ # License along with FreeCAD; if not, write to the Free Software * # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # USA * -#************************************************************************** +# ************************************************************************** import FreeCAD, unittest, Part import copy import math from FreeCAD import Units from FreeCAD import Base + App = FreeCAD from parttests.BRep_tests import BRepTests @@ -35,9 +36,10 @@ from parttests.regression_tests import RegressionTests from parttests.TopoShapeListTest import TopoShapeListTest from parttests.TopoShapeTest import TopoShapeTest -#--------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- # define the test cases to test the FreeCAD Part module -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- def getCoincidentVertexes(vtx1, vtx2): pairs = [] tol = Part.Precision.confusion() @@ -54,28 +56,29 @@ class PartTestCases(unittest.TestCase): self.Doc = FreeCAD.newDocument("PartTest") def testBoxCase(self): - self.Box = self.Doc.addObject("Part::Box","Box") + self.Box = self.Doc.addObject("Part::Box", "Box") self.Doc.recompute() self.assertEqual(len(self.Box.Shape.Faces), 6) def testIssue2985(self): - v1 = App.Vector(0.0,0.0,0.0) - v2 = App.Vector(10.0,0.0,0.0) - v3 = App.Vector(10.0,0.0,10.0) - v4 = App.Vector(0.0,0.0,10.0) + v1 = App.Vector(0.0, 0.0, 0.0) + v2 = App.Vector(10.0, 0.0, 0.0) + v3 = App.Vector(10.0, 0.0, 10.0) + v4 = App.Vector(0.0, 0.0, 10.0) edge1 = Part.makeLine(v1, v2) edge2 = Part.makeLine(v2, v3) edge3 = Part.makeLine(v3, v4) edge4 = Part.makeLine(v4, v1) # Travis build confirms the crash under macOS - #result = Part.makeFilledFace([edge1,edge2,edge3,edge4]) - #self.Doc.addObject("Part::Feature","Face").Shape = result - #self.assertTrue(isinstance(result.Surface, Part.BSplineSurface)) + # result = Part.makeFilledFace([edge1,edge2,edge3,edge4]) + # self.Doc.addObject("Part::Feature","Face").Shape = result + # self.assertTrue(isinstance(result.Surface, Part.BSplineSurface)) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartTest") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") + class PartTestBSplineCurve(unittest.TestCase): def setUp(self): @@ -87,10 +90,10 @@ class PartTestBSplineCurve(unittest.TestCase): poles = [[0, 0, 0], [1, 1, 0], [2, 0, 0], [1, -1, 0]] self.nurbs = Part.BSplineCurve() - self.nurbs.buildFromPolesMultsKnots(poles, (3, 1, 3),(0, 0.5, 1), False, 2) + self.nurbs.buildFromPolesMultsKnots(poles, (3, 1, 3), (0, 0.5, 1), False, 2) def testProperties(self): - self.assertEqual(self.spline.Continuity, 'CN') + self.assertEqual(self.spline.Continuity, "CN") self.assertEqual(self.spline.Degree, 2) self.assertEqual(self.spline.EndPoint, App.Vector(2, 0, 0)) self.assertEqual(self.spline.FirstParameter, 0.0) @@ -104,7 +107,7 @@ class PartTestBSplineCurve(unittest.TestCase): self.assertEqual(self.spline.StartPoint, App.Vector(0.0, 0.0, 0.0)) def testGetters(self): - '''only check if the function doesn't crash''' + """only check if the function doesn't crash""" self.spline.getKnot(1) self.spline.getKnots() self.spline.getMultiplicities() @@ -123,30 +126,30 @@ class PartTestBSplineCurve(unittest.TestCase): spline.setNotPeriodic() # spline.setKnots() # spline.setOrigin(2) # not working? - self.spline.setPole(1, App.Vector([1, 0, 0])) # first parameter 0 gives occ error + self.spline.setPole(1, App.Vector([1, 0, 0])) # first parameter 0 gives occ error def testIssue2671(self): if "BUILD_SPREADSHEET" in FreeCAD.__cmake__: self.Doc = App.newDocument("Issue2671") - Box = self.Doc.addObject("Part::Box","Box") - Mirroring = self.Doc.addObject("Part::Mirroring", 'Mirroring') - Spreadsheet = self.Doc.addObject('Spreadsheet::Sheet', 'Spreadsheet') + Box = self.Doc.addObject("Part::Box", "Box") + Mirroring = self.Doc.addObject("Part::Mirroring", "Mirroring") + Spreadsheet = self.Doc.addObject("Spreadsheet::Sheet", "Spreadsheet") Mirroring.Source = Box Mirroring.Base = (8, 5, 25) Mirroring.Normal = (0.5, 0.2, 0.9) - Spreadsheet.set('A1', '=Mirroring.Base.x') - Spreadsheet.set('B1', '=Mirroring.Base.y') - Spreadsheet.set('C1', '=Mirroring.Base.z') - Spreadsheet.set('A2', '=Mirroring.Normal.x') - Spreadsheet.set('B2', '=Mirroring.Normal.y') - Spreadsheet.set('C2', '=Mirroring.Normal.z') + Spreadsheet.set("A1", "=Mirroring.Base.x") + Spreadsheet.set("B1", "=Mirroring.Base.y") + Spreadsheet.set("C1", "=Mirroring.Base.z") + Spreadsheet.set("A2", "=Mirroring.Normal.x") + Spreadsheet.set("B2", "=Mirroring.Normal.y") + Spreadsheet.set("C2", "=Mirroring.Normal.z") self.Doc.recompute() - self.assertEqual(Spreadsheet.A1, Units.Quantity('8 mm')) - self.assertEqual(Spreadsheet.B1, Units.Quantity('5 mm')) - self.assertEqual(Spreadsheet.C1, Units.Quantity('25 mm')) - self.assertEqual(Spreadsheet.A2, Units.Quantity('0.5 mm')) - self.assertEqual(Spreadsheet.B2, Units.Quantity('0.2 mm')) - self.assertEqual(Spreadsheet.C2, Units.Quantity('0.9 mm')) + self.assertEqual(Spreadsheet.A1, Units.Quantity("8 mm")) + self.assertEqual(Spreadsheet.B1, Units.Quantity("5 mm")) + self.assertEqual(Spreadsheet.C1, Units.Quantity("25 mm")) + self.assertEqual(Spreadsheet.A2, Units.Quantity("0.5 mm")) + self.assertEqual(Spreadsheet.B2, Units.Quantity("0.2 mm")) + self.assertEqual(Spreadsheet.C2, Units.Quantity("0.9 mm")) App.closeDocument("Issue2671") def testIssue2876(self): @@ -157,17 +160,17 @@ class PartTestBSplineCurve(unittest.TestCase): Pipe = self.Doc.addObject("Part::Thickness", "Pipe") Pipe.Faces = (Cylinder, ["Face2", "Face3"]) Pipe.Mode = 1 - Pipe.Value = -1 # negative wall thickness - Spreadsheet = self.Doc.addObject('Spreadsheet::Sheet', 'Spreadsheet') - Spreadsheet.set('A1', 'Pipe OD') - Spreadsheet.set('B1', 'Pipe WT') - Spreadsheet.set('C1', 'Pipe ID') - Spreadsheet.set('A2', '=2*Cylinder.Radius') - Spreadsheet.set('B2', '=-Pipe.Value') - Spreadsheet.set('C2', '=2*(Cylinder.Radius + Pipe.Value)') + Pipe.Value = -1 # negative wall thickness + Spreadsheet = self.Doc.addObject("Spreadsheet::Sheet", "Spreadsheet") + Spreadsheet.set("A1", "Pipe OD") + Spreadsheet.set("B1", "Pipe WT") + Spreadsheet.set("C1", "Pipe ID") + Spreadsheet.set("A2", "=2*Cylinder.Radius") + Spreadsheet.set("B2", "=-Pipe.Value") + Spreadsheet.set("C2", "=2*(Cylinder.Radius + Pipe.Value)") self.Doc.recompute() - self.assertEqual(Spreadsheet.B2, Units.Quantity('1 mm')) - self.assertEqual(Spreadsheet.C2, Units.Quantity('8 mm')) + self.assertEqual(Spreadsheet.B2, Units.Quantity("1 mm")) + self.assertEqual(Spreadsheet.C2, Units.Quantity("8 mm")) App.closeDocument("Issue2876") def testSubElements(self): @@ -182,9 +185,10 @@ class PartTestBSplineCurve(unittest.TestCase): box.getElement("Face7") def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartTest") + class PartTestCurveToNurbs(unittest.TestCase): def testCircleToNurbs(self): mat = Base.Matrix() @@ -227,6 +231,7 @@ class PartTestCurveToNurbs(unittest.TestCase): spline = ellipse.toBSpline() self.assertAlmostEqual(ellipse.value(0).distanceToPoint(spline.value(0)), 0) + class PartTestBSplineSurface(unittest.TestCase): def testTorusToSpline(self): to = Part.Toroid() @@ -245,6 +250,7 @@ class PartTestBSplineSurface(unittest.TestCase): self.assertAlmostEqual(bs.bounds()[1], 1.0) self.assertAlmostEqual(bs.bounds()[3], 1.0) + class PartTestNormals(unittest.TestCase): def setUp(self): self.face = Part.makePlane(1, 1) @@ -261,7 +267,7 @@ class PartTestNormals(unittest.TestCase): def testPlacement(self): self.face.reverse() self.face.Placement.Rotation.Angle = 1 - self.face.Placement.Rotation.Axis = (1,1,1) + self.face.Placement.Rotation.Axis = (1, 1, 1) vec = Base.Vector(-0.63905, 0.33259, -0.69353) self.assertGreater(self.face.normalAt(0, 0).dot(vec), 0.9999) self.assertLess(self.face.Surface.normal(0, 0).dot(vec), -0.9999) @@ -269,6 +275,7 @@ class PartTestNormals(unittest.TestCase): def tearDown(self): pass + class PartTestShapeRotate(unittest.TestCase): def testPlacement(self): tol = 1e-12 @@ -294,6 +301,7 @@ class PartTestShapeRotate(unittest.TestCase): self.assertTrue(p4.isSame(p2 * p1, tol)) self.assertTrue(box.Placement.isSame(p4, tol)) + class PartTestCircle2D(unittest.TestCase): def testValidCircle(self): p1 = App.Base.Vector2d(0.01, 0.01) @@ -308,6 +316,7 @@ class PartTestCircle2D(unittest.TestCase): with self.assertRaises(ValueError): Part.Geom2d.Circle2d.getCircleCenter(p1, p2, p3) + class PartTestCone(unittest.TestCase): def testderivatives(self): def get_dn(surface, u, v): @@ -324,7 +333,7 @@ class PartTestCone(unittest.TestCase): u, v = (5.0, 5.0) vp, v1, v2, v3 = get_dn(cone, u, v) - shape = cone.toShape(0, 2*math.pi, 0, 10) + shape = cone.toShape(0, 2 * math.pi, 0, 10) shape = shape.toNurbs() spline = shape.Face1.Surface @@ -336,11 +345,12 @@ class PartTestCone(unittest.TestCase): self.assertAlmostEqual(v2.getAngle(w2), 0) self.assertAlmostEqual(v3.getAngle(w3), 0) + class PartTestChFi2dAlgos(unittest.TestCase): def testChFi2d_FilletAlgo(self): v = FreeCAD.Vector - edge1 = Part.makeLine(v(0,0,0), v(0,10,0)) - edge2 = Part.makeLine(v(0,10,0), v(10,10,0)) + edge1 = Part.makeLine(v(0, 0, 0), v(0, 10, 0)) + edge2 = Part.makeLine(v(0, 10, 0), v(10, 10, 0)) wire = Part.Wire([edge1, edge2]) pln = Part.Plane() @@ -351,7 +361,7 @@ class PartTestChFi2dAlgos(unittest.TestCase): with self.assertRaises(TypeError): alg.init() - print (alg) + print(alg) # Test without shape with self.assertRaises(Base.CADKernelError): alg.perform(1) @@ -372,8 +382,8 @@ class PartTestChFi2dAlgos(unittest.TestCase): with self.assertRaises(TypeError): alg.result(1) - self.assertEqual(alg.numberOfResults(Base.Vector(0,10,0)), 1) - result = alg.result(Base.Vector(0,10,0)) + self.assertEqual(alg.numberOfResults(Base.Vector(0, 10, 0)), 1) + result = alg.result(Base.Vector(0, 10, 0)) curve = result[0].Curve self.assertEqual(type(curve), Part.Circle) self.assertEqual(curve.Axis, pln.Axis) @@ -381,8 +391,8 @@ class PartTestChFi2dAlgos(unittest.TestCase): def testChFi2d_AnaFilletAlgo(self): v = FreeCAD.Vector - edge1 = Part.makeLine(v(0,0,0), v(0,10,0)) - edge2 = Part.makeLine(v(0,10,0), v(10,10,0)) + edge1 = Part.makeLine(v(0, 0, 0), v(0, 10, 0)) + edge2 = Part.makeLine(v(0, 10, 0), v(10, 10, 0)) wire = Part.Wire([edge1, edge2]) pln = Part.Plane() @@ -393,7 +403,7 @@ class PartTestChFi2dAlgos(unittest.TestCase): with self.assertRaises(TypeError): alg.init() - print (alg) + print(alg) # Test without shape self.assertFalse(alg.perform(1)) @@ -417,8 +427,8 @@ class PartTestChFi2dAlgos(unittest.TestCase): def testChFi2d_ChamferAPI(self): v = FreeCAD.Vector - edge1 = Part.makeLine(v(0,0,0), v(0,10,0)) - edge2 = Part.makeLine(v(0,10,0), v(10,10,0)) + edge1 = Part.makeLine(v(0, 0, 0), v(0, 10, 0)) + edge2 = Part.makeLine(v(0, 10, 0), v(10, 10, 0)) wire = Part.Wire([edge1, edge2]) with self.assertRaises(TypeError): @@ -428,7 +438,7 @@ class PartTestChFi2dAlgos(unittest.TestCase): with self.assertRaises(TypeError): alg.init() - print (alg) + print(alg) with self.assertRaises(TypeError): alg.perform(1) @@ -447,13 +457,14 @@ class PartTestChFi2dAlgos(unittest.TestCase): curve = result[0].Curve self.assertEqual(type(curve), Part.Line) + class PartTestRuledSurface(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument() def testRuledSurfaceFromTwoObjects(self): - line1 = Part.makeLine(FreeCAD.Vector(-70,-30,0), FreeCAD.Vector(-50,40,0)) - line2 = Part.makeLine(FreeCAD.Vector(-40,-30,0), FreeCAD.Vector(-40,10,0)) + line1 = Part.makeLine(FreeCAD.Vector(-70, -30, 0), FreeCAD.Vector(-50, 40, 0)) + line2 = Part.makeLine(FreeCAD.Vector(-40, -30, 0), FreeCAD.Vector(-40, 10, 0)) plm1 = FreeCAD.Placement() plm1.Rotation = FreeCAD.Rotation(0.7071067811865476, 0.0, 0.0, 0.7071067811865475) line1.Placement = plm1 @@ -532,16 +543,29 @@ class PartTestRuledSurface(unittest.TestCase): def testRuledSurfaceFromOneObject(self): if "BUILD_SKETCHER" in FreeCAD.__cmake__: - sketch = self.Doc.addObject('Sketcher::SketchObject', 'Sketch') - sketch.Placement = FreeCAD.Placement(FreeCAD.Vector(0.000000, 0.000000, 0.000000), App.Rotation(0.707107, 0.000000, 0.000000, 0.707107)) + sketch = self.Doc.addObject("Sketcher::SketchObject", "Sketch") + sketch.Placement = FreeCAD.Placement( + FreeCAD.Vector(0.000000, 0.000000, 0.000000), + App.Rotation(0.707107, 0.000000, 0.000000, 0.707107), + ) sketch.MapMode = "Deactivated" - sketch.addGeometry(Part.LineSegment(App.Vector(-43.475811,34.364464,0),App.Vector(-65.860519,-20.078733,0)),False) - sketch.addGeometry(Part.LineSegment(App.Vector(14.004498,27.390331,0),App.Vector(33.577049,-27.952749,0)),False) + sketch.addGeometry( + Part.LineSegment( + App.Vector(-43.475811, 34.364464, 0), App.Vector(-65.860519, -20.078733, 0) + ), + False, + ) + sketch.addGeometry( + Part.LineSegment( + App.Vector(14.004498, 27.390331, 0), App.Vector(33.577049, -27.952749, 0) + ), + False, + ) - ruled = self.Doc.addObject('Part::RuledSurface', 'Ruled Surface') - ruled.Curve1 = (sketch,['Edge1']) - ruled.Curve2 = (sketch,['Edge2']) + ruled = self.Doc.addObject("Part::RuledSurface", "Ruled Surface") + ruled.Curve1 = (sketch, ["Edge1"]) + ruled.Curve2 = (sketch, ["Edge2"]) self.Doc.recompute() same = getCoincidentVertexes(sketch.Shape.Vertexes, ruled.Shape.Vertexes) @@ -550,13 +574,14 @@ class PartTestRuledSurface(unittest.TestCase): def tearDown(self): FreeCAD.closeDocument(self.Doc.Name) + class PartTestShapeFix(unittest.TestCase): def testShapeFix_Root(self): with self.assertRaises(TypeError): Part.ShapeFix.Root([]) fix = Part.ShapeFix.Root() - print (fix) + print(fix) fix.Precision = 0.0 self.assertEqual(fix.Precision, 0.0) @@ -578,7 +603,7 @@ class PartTestShapeFix(unittest.TestCase): fix = Part.ShapeFix.Shape(face) fix.init(face) - print (fix) + print(fix) fix.shape() fix.fixSolidTool() fix.fixShellTool() @@ -618,7 +643,7 @@ class PartTestShapeFix(unittest.TestCase): wirefix = Part.ShapeFix.Wire(face.OuterWire, face, 1e-7) fix = wirefix.fixEdgeTool() - print (fix) + print(fix) fix.fixRemovePCurve(face.Edge1, face) fix.fixRemovePCurve(face.Edge1, face.Surface, face.Placement) @@ -656,7 +681,7 @@ class PartTestShapeFix(unittest.TestCase): Part.ShapeFix.Face([]) fix = Part.ShapeFix.Face(face) - print (fix) + print(fix) fix.fixOrientation() fix.fixAddNaturalBound() @@ -719,7 +744,7 @@ class PartTestShapeFix(unittest.TestCase): fix = Part.ShapeFix.Shell(shell) fix.init(shell) - print (fix) + print(fix) fix.perform() fix.shell() fix.shape() @@ -745,7 +770,7 @@ class PartTestShapeFix(unittest.TestCase): fix = Part.ShapeFix.Solid() fix.init(box) - print (fix) + print(fix) fix.perform() fix.solid() @@ -783,7 +808,7 @@ class PartTestShapeFix(unittest.TestCase): self.assertEqual(fix.isReady(), True) self.assertEqual(fix.numberOfEdges(), 4) - print (fix) + print(fix) fix.clearModes() fix.clearStatuses() @@ -900,6 +925,7 @@ class PartTestShapeFix(unittest.TestCase): fix.fixGap2d(1, False) fix.fixTails() + class PartBOPTestContainer(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument() @@ -911,6 +937,7 @@ class PartBOPTestContainer(unittest.TestCase): part.addObject(box) part.addObject(cyl) from BOPTools import BOPFeatures + bp = BOPFeatures.BOPFeatures(self.Doc) fuse = bp.make_multi_fuse([cyl.Name, box.Name]) self.assertEqual(part, fuse.getParent()) @@ -922,6 +949,7 @@ class PartBOPTestContainer(unittest.TestCase): part.addObject(box) part.addObject(cyl) from BOPTools import BOPFeatures + bp = BOPFeatures.BOPFeatures(self.Doc) fuse = bp.make_cut([cyl.Name, box.Name]) self.assertEqual(part, fuse.getParent()) @@ -933,6 +961,7 @@ class PartBOPTestContainer(unittest.TestCase): part.addObject(box) part.addObject(cyl) from BOPTools import BOPFeatures + bp = BOPFeatures.BOPFeatures(self.Doc) fuse = bp.make_multi_common([cyl.Name, box.Name]) self.assertEqual(part, fuse.getParent()) @@ -940,6 +969,7 @@ class PartBOPTestContainer(unittest.TestCase): def tearDown(self): FreeCAD.closeDocument(self.Doc.Name) + class BSplineCurve2d(unittest.TestCase): def setUp(self): vec2 = FreeCAD.Base.Vector2d @@ -952,11 +982,13 @@ class BSplineCurve2d(unittest.TestCase): def testApproximate(self): self.bs.approximate(Points=self.pts) + class GeometryCurve(unittest.TestCase): def testProject(self): line = Part.Line() line.projectPoint(FreeCAD.Vector()) + class EmptyEdge(unittest.TestCase): def testParameterByLength(self): with self.assertRaises(ValueError): @@ -1060,6 +1092,7 @@ class EmptyEdge(unittest.TestCase): edge = Part.Edge() edge.LastParameter + class EmptyFace(unittest.TestCase): def testMakeOffset(self): with self.assertRaises(ValueError): diff --git a/src/Mod/Part/TestPartGui.py b/src/Mod/Part/TestPartGui.py index 3be1ffe14c..59a7a7f103 100644 --- a/src/Mod/Part/TestPartGui.py +++ b/src/Mod/Part/TestPartGui.py @@ -1,6 +1,6 @@ # SPDX-License-Identifier: LGPL-2.1-or-later -#************************************************************************** +# ************************************************************************** # Copyright (c) 2011 Juergen Riegel * # * # This file is part of the FreeCAD CAx development system. * @@ -20,7 +20,7 @@ # License along with FreeCAD; if not, write to the Free Software * # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # USA * -#************************************************************************** +# ************************************************************************** import os import sys @@ -31,8 +31,9 @@ import Part import PartGui from PySide import QtWidgets + def findDockWidget(name): - """ Get a dock widget by name """ + """Get a dock widget by name""" mw = FreeCADGui.getMainWindow() dws = mw.findChildren(QtWidgets.QDockWidget) for dw in dws: @@ -40,6 +41,7 @@ def findDockWidget(name): return dw return None + """ #--------------------------------------------------------------------------- # define the test cases to test the FreeCAD Part module @@ -49,7 +51,7 @@ from parttests.ColorPerFaceTest import ColorPerFaceTest from parttests.ColorTransparencyTest import ColorTransparencyTest -#class PartGuiTestCases(unittest.TestCase): +# class PartGuiTestCases(unittest.TestCase): # def setUp(self): # self.Doc = FreeCAD.newDocument("PartGuiTest") # @@ -79,9 +81,10 @@ class PartGuiViewProviderTestCases(unittest.TestCase): box.ViewObject.dropObject(box, 0) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartGuiTest") + class SectionCutTestCases(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("SectionCut") @@ -101,7 +104,7 @@ class SectionCutTestCases(unittest.TestCase): button = box.button(QtWidgets.QDialogButtonBox.Close) button.click() else: - print ("No section cutting panel found") + print("No section cutting panel found") def tearDown(self): FreeCAD.closeDocument("SectionCut") diff --git a/src/Mod/Part/part.dox b/src/Mod/Part/part.dox index cafa3ef8b9..5b7cf2f095 100644 --- a/src/Mod/Part/part.dox +++ b/src/Mod/Part/part.dox @@ -5,4 +5,3 @@ See \ref src/Mod/Draft/draft.dox as an example of how to populate this page */ - diff --git a/src/Mod/Part/parttests/BRep_tests.py b/src/Mod/Part/parttests/BRep_tests.py index 99f74dd622..6b39ed9265 100644 --- a/src/Mod/Part/parttests/BRep_tests.py +++ b/src/Mod/Part/parttests/BRep_tests.py @@ -5,6 +5,7 @@ import Part import unittest + class BRepTests(unittest.TestCase): def testProject(self): diff --git a/src/Mod/Part/parttests/ColorPerFaceTest.py b/src/Mod/Part/parttests/ColorPerFaceTest.py index a87c42b059..8560ee3f66 100644 --- a/src/Mod/Part/parttests/ColorPerFaceTest.py +++ b/src/Mod/Part/parttests/ColorPerFaceTest.py @@ -11,6 +11,7 @@ import unittest from BOPTools import BOPFeatures from pivy import coin + class ColorPerFaceTest(unittest.TestCase): def setUp(self): TempPath = tempfile.gettempdir() @@ -21,15 +22,17 @@ class ColorPerFaceTest(unittest.TestCase): App.closeDocument(self.doc.Name) def testBox(self): - box = self.doc.addObject("Part::Box","Box") + box = self.doc.addObject("Part::Box", "Box") self.doc.recompute() - box.ViewObject.DiffuseColor = [(1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,1.,0.,1.), - (1.,1.,0.,1.)] + box.ViewObject.DiffuseColor = [ + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 1.0, 0.0, 1.0), + (1.0, 1.0, 0.0, 1.0), + ] box.Visibility = False self.doc.recompute() @@ -53,17 +56,19 @@ class ColorPerFaceTest(unittest.TestCase): self.assertEqual(mat.diffuseColor.getNum(), 6) def testBoxAndLink(self): - box = self.doc.addObject("Part::Box","Box") + box = self.doc.addObject("Part::Box", "Box") self.doc.recompute() - box.ViewObject.DiffuseColor = [(1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,1.,0.,1.), - (1.,1.,0.,1.)] + box.ViewObject.DiffuseColor = [ + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 1.0, 0.0, 1.0), + (1.0, 1.0, 0.0, 1.0), + ] - link = self.doc.addObject('App::Link','Link') + link = self.doc.addObject("App::Link", "Link") link.setLink(box) box.Visibility = False self.doc.recompute() @@ -90,15 +95,17 @@ class ColorPerFaceTest(unittest.TestCase): """ If color per face is set then changing the transparency must not revert it """ - box = self.doc.addObject("Part::Box","Box") + box = self.doc.addObject("Part::Box", "Box") self.doc.recompute() - box.ViewObject.DiffuseColor = [(1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,0.,0.,1.), - (1.,1.,0.,1.), - (1.,1.,0.,1.)] + box.ViewObject.DiffuseColor = [ + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 0.0, 0.0, 1.0), + (1.0, 1.0, 0.0, 1.0), + (1.0, 1.0, 0.0, 1.0), + ] box.ViewObject.Transparency = 35 self.assertEqual(box.ViewObject.Transparency, 35) @@ -127,10 +134,10 @@ class ColorPerFaceTest(unittest.TestCase): """ Both input objects are red. So, it's expected that the output object is red, too. """ - box = self.doc.addObject("Part::Box","Box") - cyl = self.doc.addObject("Part::Cylinder","Cylinder") - box.ViewObject.ShapeColor = (1.,0.,0.,1.) - cyl.ViewObject.ShapeColor = (1.,0.,0.,1.) + box = self.doc.addObject("Part::Box", "Box") + cyl = self.doc.addObject("Part::Cylinder", "Cylinder") + box.ViewObject.ShapeColor = (1.0, 0.0, 0.0, 1.0) + cyl.ViewObject.ShapeColor = (1.0, 0.0, 0.0, 1.0) self.doc.recompute() bp = BOPFeatures.BOPFeatures(self.doc) @@ -161,13 +168,13 @@ class ColorPerFaceTest(unittest.TestCase): self.assertEqual(len(fuse.Shape.Faces), 11) self.assertEqual(len(fuse.ViewObject.DiffuseColor), 11) - self.assertEqual(fuse.ViewObject.DiffuseColor[0], (1.,0.,0.,1.)) + self.assertEqual(fuse.ViewObject.DiffuseColor[0], (1.0, 0.0, 0.0, 1.0)) def testMultiFuseSaveRestore(self): - box = self.doc.addObject("Part::Box","Box") - cyl = self.doc.addObject("Part::Cylinder","Cylinder") - box.ViewObject.ShapeColor = (1.,0.,0.,1.) - cyl.ViewObject.ShapeColor = (1.,0.,0.,1.) + box = self.doc.addObject("Part::Box", "Box") + cyl = self.doc.addObject("Part::Cylinder", "Cylinder") + box.ViewObject.ShapeColor = (1.0, 0.0, 0.0, 1.0) + cyl.ViewObject.ShapeColor = (1.0, 0.0, 0.0, 1.0) self.doc.recompute() bp = BOPFeatures.BOPFeatures(self.doc) @@ -176,7 +183,7 @@ class ColorPerFaceTest(unittest.TestCase): fuse.Refine = False self.doc.recompute() - fuse.ViewObject.DiffuseColor = [(1.,0.,0.,1.)] * 11 + fuse.ViewObject.DiffuseColor = [(1.0, 0.0, 0.0, 1.0)] * 11 self.doc.saveAs(self.fileName) App.closeDocument(self.doc.Name) @@ -186,7 +193,7 @@ class ColorPerFaceTest(unittest.TestCase): fuse = self.doc.ActiveObject self.assertEqual(len(fuse.Shape.Faces), 11) self.assertEqual(len(fuse.ViewObject.DiffuseColor), 11) - self.assertEqual(fuse.ViewObject.DiffuseColor[0], (1.,0.,0.,1.)) + self.assertEqual(fuse.ViewObject.DiffuseColor[0], (1.0, 0.0, 0.0, 1.0)) sa = coin.SoSearchAction() sa.setType(coin.SoMaterialBinding.getClassTypeId()) diff --git a/src/Mod/Part/parttests/ColorTransparencyTest.py b/src/Mod/Part/parttests/ColorTransparencyTest.py index 3720ae95f9..2eab821e2e 100644 --- a/src/Mod/Part/parttests/ColorTransparencyTest.py +++ b/src/Mod/Part/parttests/ColorTransparencyTest.py @@ -9,16 +9,14 @@ class ColorTransparencyTest(unittest.TestCase): def setUp(self): self._doc = App.newDocument() - self._pg = App.ParamGet('User parameter:BaseApp/Preferences/View') - self._backup_default_transparency = self._pg.GetInt('DefaultShapeTransparency') - self._backup_default_shapecolor = self._pg.GetUnsigned('DefaultShapeColor') - + self._pg = App.ParamGet("User parameter:BaseApp/Preferences/View") + self._backup_default_transparency = self._pg.GetInt("DefaultShapeTransparency") + self._backup_default_shapecolor = self._pg.GetUnsigned("DefaultShapeColor") def tearDown(self): App.closeDocument(self._doc.Name) - self._pg.SetInt('DefaultShapeTransparency', self._backup_default_transparency) - self._pg.SetUnsigned('DefaultShapeColor', self._backup_default_shapecolor) - + self._pg.SetInt("DefaultShapeTransparency", self._backup_default_transparency) + self._pg.SetUnsigned("DefaultShapeColor", self._backup_default_shapecolor) def test_default_shape_transparency(self): """ @@ -26,15 +24,18 @@ class ColorTransparencyTest(unittest.TestCase): related: https://github.com/FreeCAD/FreeCAD/pull/11586 """ transparency = 70 - self._pg.SetInt('DefaultShapeTransparency', transparency) - obj = self._doc.addObject('Part::Box') + self._pg.SetInt("DefaultShapeTransparency", transparency) + obj = self._doc.addObject("Part::Box") assert obj.ViewObject.Transparency == transparency obj.ViewObject.ShapeAppearance[0].DiffuseColor = (0.5, 0.0, 0.0) - self.assertEqual(obj.ViewObject.Transparency, transparency, - 'transparency was unexpectedly changed to {} when changing the color.'.format( - obj.ViewObject.Transparency)) - + self.assertEqual( + obj.ViewObject.Transparency, + transparency, + "transparency was unexpectedly changed to {} when changing the color.".format( + obj.ViewObject.Transparency + ), + ) def test_default_shape_color(self): """ @@ -49,23 +50,26 @@ class ColorTransparencyTest(unittest.TestCase): the transparency when loading to 1.0 """ - self._pg.SetUnsigned('DefaultShapeColor', 0xff000000) # red - obj = self._doc.addObject('Part::Box') - - self.assertEqual(obj.ViewObject.ShapeAppearance[0].DiffuseColor, (1.0, 0.0, 0.0, 1.0), - 'default shape color was not set correctly') - self.assertEqual(obj.ViewObject.ShapeMaterial.DiffuseColor, (1.0, 0.0, 0.0, 1.0), - 'default material color was not set correctly') + self._pg.SetUnsigned("DefaultShapeColor", 0xFF000000) # red + obj = self._doc.addObject("Part::Box") + self.assertEqual( + obj.ViewObject.ShapeAppearance[0].DiffuseColor, + (1.0, 0.0, 0.0, 1.0), + "default shape color was not set correctly", + ) + self.assertEqual( + obj.ViewObject.ShapeMaterial.DiffuseColor, + (1.0, 0.0, 0.0, 1.0), + "default material color was not set correctly", + ) def test_app_plane_transparency(self): """ related: https://github.com/FreeCAD/FreeCAD/pull/12064 """ - self._pg.SetInt('DefaultShapeTransparency', 70) - obj = self._doc.addObject('App::Origin') - t = self._doc.findObjects('App::Plane')[0].ViewObject.Transparency - - self.assertEqual(t, 0, - 'transparency of App::Plane object is {} instead of 0'.format(t)) + self._pg.SetInt("DefaultShapeTransparency", 70) + obj = self._doc.addObject("App::Origin") + t = self._doc.findObjects("App::Plane")[0].ViewObject.Transparency + self.assertEqual(t, 0, "transparency of App::Plane object is {} instead of 0".format(t)) diff --git a/src/Mod/Part/parttests/Geom2d_tests.py b/src/Mod/Part/parttests/Geom2d_tests.py index 60d61b5e05..e44ac68085 100644 --- a/src/Mod/Part/parttests/Geom2d_tests.py +++ b/src/Mod/Part/parttests/Geom2d_tests.py @@ -1,11 +1,13 @@ # SPDX-License-Identifier: LGPL-2.1-or-later import FreeCAD + vec2 = FreeCAD.Base.Vector2d import Part import unittest + class Geom2dTests(unittest.TestCase): def test_toShape(self): diff --git a/src/Mod/Part/parttests/TopoShapeListTest.py b/src/Mod/Part/parttests/TopoShapeListTest.py index fd07a51847..ea1f7f1ab7 100644 --- a/src/Mod/Part/parttests/TopoShapeListTest.py +++ b/src/Mod/Part/parttests/TopoShapeListTest.py @@ -9,6 +9,7 @@ import os import tempfile import unittest + class TopoShapeListTest(unittest.TestCase): def setUp(self): """Creates a document and a FeaturePython that has a PropertyTopoShapeList property""" @@ -21,9 +22,9 @@ class TopoShapeListTest(unittest.TestCase): doc = App.newDocument() obj = doc.addObject("App::FeaturePython", self.objName) obj.addProperty("Part::PropertyTopoShapeList", "Shapes") - box = Part.makeBox(1,1,1) - box2 = Part.makeBox(1,1,2) - box3 = Part.makeBox(1,1,3) + box = Part.makeBox(1, 1, 1) + box2 = Part.makeBox(1, 1, 2) + box3 = Part.makeBox(1, 1, 3) obj.Shapes = [box, box2, box3] doc.saveAs(self.fileName) App.closeDocument(doc.Name) @@ -44,20 +45,33 @@ class TopoShapeListTest(unittest.TestCase): maxError = 0.0000001 error = abs(1.0 - boxes[0].Volume) - self.assertLessEqual(error, maxError, "TopoShapeList entry 0 has wrong volume: {0}".format(boxes[0].Volume)) + self.assertLessEqual( + error, maxError, "TopoShapeList entry 0 has wrong volume: {0}".format(boxes[0].Volume) + ) error = abs(2.0 - boxes[1].Volume) - self.assertLessEqual(error, maxError, "TopoShapeList entry 1 has wrong volume: {0}".format(boxes[1].Volume)) + self.assertLessEqual( + error, maxError, "TopoShapeList entry 1 has wrong volume: {0}".format(boxes[1].Volume) + ) error = abs(3.0 - boxes[2].Volume) - self.assertLessEqual(error, maxError, "TopoShapeList entry 2 has wrong volume: {0}".format(boxes[2].Volume)) + self.assertLessEqual( + error, maxError, "TopoShapeList entry 2 has wrong volume: {0}".format(boxes[2].Volume) + ) twoboxes = [boxes[1], boxes[2]] doc.openTransaction("Change shapes") obj.Shapes = twoboxes doc.commitTransaction() - self.assertEqual(len(obj.Shapes), 2, "TopoShapeList has wrong entry count (1): {0}".format(len(obj.Shapes))) + self.assertEqual( + len(obj.Shapes), + 2, + "TopoShapeList has wrong entry count (1): {0}".format(len(obj.Shapes)), + ) doc.undo() - self.assertEqual(len(obj.Shapes), 3, "TopoShapeList has wrong entry count (2): {0}".format(len(obj.Shapes))) + self.assertEqual( + len(obj.Shapes), + 3, + "TopoShapeList has wrong entry count (2): {0}".format(len(obj.Shapes)), + ) App.closeDocument(doc.Name) - diff --git a/src/Mod/Part/parttests/TopoShapeTest.py b/src/Mod/Part/parttests/TopoShapeTest.py index 8d758ccde7..0cc78f25e7 100644 --- a/src/Mod/Part/parttests/TopoShapeTest.py +++ b/src/Mod/Part/parttests/TopoShapeTest.py @@ -10,20 +10,16 @@ class TopoShapeAssertions: def assertAttrEqual(self, toposhape, attr_value_list, msg=None): for attr, value in attr_value_list: - result = toposhape.__getattribute__( - attr - ) # Look up each attribute by string name + result = toposhape.__getattribute__(attr) # Look up each attribute by string name if result.__str__() != value.__str__(): if msg == None: - msg = f"TopoShape {attr} is incorrect: {result} should be {value}", + msg = (f"TopoShape {attr} is incorrect: {result} should be {value}",) raise AssertionError(msg) def assertAttrAlmostEqual(self, toposhape, attr_value_list, places=5, msg=None): - range = 1 / 10 ** places + range = 1 / 10**places for attr, value in attr_value_list: - result = toposhape.__getattribute__( - attr - ) # Look up each attribute by string name + result = toposhape.__getattribute__(attr) # Look up each attribute by string name if abs(result - value) > range: if msg == None: msg = f"TopoShape {attr} is incorrect: {result} should be {value}" @@ -31,9 +27,7 @@ class TopoShapeAssertions: def assertAttrCount(self, toposhape, attr_value_list, msg=None): for attr, value in attr_value_list: - result = toposhape.__getattribute__( - attr - ) # Look up each attribute by string name + result = toposhape.__getattribute__(attr) # Look up each attribute by string name if len(result) != value: if msg == None: msg = f"TopoShape {attr} is incorrect: {result} should have {value} elements" @@ -80,7 +74,7 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): self.doc.Cylinder1.Height = 2 self.doc.Cylinder1.Angle = 360 self.doc.addObject("Part::Compound", "Compound1") - self.doc.Compound1.Links = [ self.doc.Box1, self.doc.Box2 ] + self.doc.Compound1.Links = [self.doc.Box1, self.doc.Box2] self.doc.recompute() self.box = self.doc.Box1.Shape @@ -99,15 +93,16 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): ["CenterOfMass", App.Vector(1, 0.5, 1)], ["CompSolids", []], ["Compounds", []], - ["Content", "\n"], # Our element map is empty, or there would be more here. + [ + "Content", + "\n", + ], # Our element map is empty, or there would be more here. ["ElementMap", {}], ["ElementReverseMap", {}], - ['Hasher', None], + ["Hasher", None], [ "MatrixOfInertia", - App.Matrix( - 1.66667, 0, 0, 0, 0, 2.66667, 0, 0, 0, 0, 1.66667, 0, 0, 0, 0, 1 - ), + App.Matrix(1.66667, 0, 0, 0, 0, 2.66667, 0, 0, 0, 0, 1.66667, 0, 0, 0, 0, 1), ], ["Module", "Part"], ["Orientation", "Forward"], @@ -174,9 +169,7 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): """Tests TopoShape elementMap""" # Arrange # Act No elementMaps exist in base shapes until we perform an operation. - compound1 = Part.Compound( - [self.doc.Objects[-1].Shape, self.doc.Objects[-2].Shape] - ) + compound1 = Part.Compound([self.doc.Objects[-1].Shape, self.doc.Objects[-2].Shape]) self.doc.addObject("Part::Compound", "Compound") self.doc.Compound.Links = [ App.activeDocument().Box1, @@ -209,36 +202,37 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): common1 = self.doc.Common.Shape # Assert elementMap if common1.ElementMapVersion != "": # Should be '4' as of Mar 2023. - self.assertKeysInMap(common1.ElementReverseMap, - [ - "Edge1", - "Edge2", - "Edge3", - "Edge4", - "Edge5", - "Edge6", - "Edge7", - "Edge8", - "Edge9", - "Edge10", - "Edge11", - "Edge12", - "Face1", - "Face2", - "Face3", - "Face4", - "Face5", - "Face6", - "Vertex1", - "Vertex2", - "Vertex3", - "Vertex4", - "Vertex5", - "Vertex6", - "Vertex7", - "Vertex8", - ], - ) + self.assertKeysInMap( + common1.ElementReverseMap, + [ + "Edge1", + "Edge2", + "Edge3", + "Edge4", + "Edge5", + "Edge6", + "Edge7", + "Edge8", + "Edge9", + "Edge10", + "Edge11", + "Edge12", + "Face1", + "Face2", + "Face3", + "Face4", + "Face5", + "Face6", + "Vertex1", + "Vertex2", + "Vertex3", + "Vertex4", + "Vertex5", + "Vertex6", + "Vertex7", + "Vertex8", + ], + ) # Assert Shape self.assertBounds(common1, App.BoundBox(0, 0, 0, 1, 1, 2)) @@ -252,36 +246,37 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): cut1 = self.doc.Cut.Shape # Assert elementMap if cut1.ElementMapVersion != "": # Should be '4' as of Mar 2023. - self.assertKeysInMap(cut1.ElementReverseMap, - [ - "Edge1", - "Edge2", - "Edge3", - "Edge4", - "Edge5", - "Edge6", - "Edge7", - "Edge8", - "Edge9", - "Edge10", - "Edge11", - "Edge12", - "Face1", - "Face2", - "Face3", - "Face4", - "Face5", - "Face6", - "Vertex1", - "Vertex2", - "Vertex3", - "Vertex4", - "Vertex5", - "Vertex6", - "Vertex7", - "Vertex8", - ], - ) + self.assertKeysInMap( + cut1.ElementReverseMap, + [ + "Edge1", + "Edge2", + "Edge3", + "Edge4", + "Edge5", + "Edge6", + "Edge7", + "Edge8", + "Edge9", + "Edge10", + "Edge11", + "Edge12", + "Face1", + "Face2", + "Face3", + "Face4", + "Face5", + "Face6", + "Vertex1", + "Vertex2", + "Vertex3", + "Vertex4", + "Vertex5", + "Vertex6", + "Vertex7", + "Vertex8", + ], + ) # Assert Shape self.assertBounds(cut1, App.BoundBox(0, 1, 0, 1, 2, 2)) @@ -485,8 +480,9 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): self.doc.recompute() compound = self.doc.Compound.Shape # Act - compound_replaced = compound.replaceShape([(App.activeDocument().Box2.Shape, - App.activeDocument().Box1.Shape)]) + compound_replaced = compound.replaceShape( + [(App.activeDocument().Box2.Shape, App.activeDocument().Box1.Shape)] + ) # Assert elementMap if compound.ElementMapVersion != "": # Should be '4' as of Mar 2023. self.assertEqual(compound.ElementMapSize, 52) @@ -684,7 +680,9 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): offset = box_toposhape.Faces[0].makeOffset(2.0) # Assert elementMap if box_toposhape.Faces[0].ElementMapVersion != "": # Should be '4' as of Mar 2023. - self.assertEqual(box_toposhape.Faces[0].ElementMapSize, 9) # 1 Face, 4 Edges, 4 Vertexes + self.assertEqual( + box_toposhape.Faces[0].ElementMapSize, 9 + ) # 1 Face, 4 Edges, 4 Vertexes self.assertEqual(offset.ElementMapSize, 17) # 1 Face, 8 Edges, 8 Vertexes # Todo: makeEvolved doesn't work right, probably due to missing c++ code. @@ -720,17 +718,17 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): def testTopoShapeMapSubElement(self): # Arrange - box = Part.makeBox(1,2,3) + box = Part.makeBox(1, 2, 3) # face = box.Faces[0] # Do not do this. Need the subelement call each usage. # Assert everything empty - self.assertEqual(box.ElementMapSize,0) - self.assertEqual(box.Faces[0].ElementMapSize,0) + self.assertEqual(box.ElementMapSize, 0) + self.assertEqual(box.Faces[0].ElementMapSize, 0) # Act box.mapSubElement(box.Faces[0]) # Assert elementMaps created if box.ElementMapVersion != "": # Should be '4' as of Mar 2023. - self.assertEqual(box.ElementMapSize,9) # 1 Face, 4 Edges, 4 Vertexes - self.assertEqual(box.Faces[0].ElementMapSize,9) + self.assertEqual(box.ElementMapSize, 9) # 1 Face, 4 Edges, 4 Vertexes + self.assertEqual(box.Faces[0].ElementMapSize, 9) def testTopoShapeGetElementHistory(self): self.doc.addObject("Part::Fuse", "Fuse") @@ -742,7 +740,7 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): if fuse1.ElementMapVersion != "": # Should be '4' as of Mar 2023. history1 = fuse1.getElementHistory(fuse1.ElementReverseMap["Vertex1"]) # Assert - self.assertEqual(len(history1),3) # Just the Fuse operation + self.assertEqual(len(history1), 3) # Just the Fuse operation # Todo: Still broken, still can't find parms that consistently work to test this. # However, the results with an empty elementMap are consistent with making the @@ -777,15 +775,32 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): cut1 = self.doc.Cut.Shape # Assert elementMap refkeys = [ - 'Vertex6', 'Vertex5', 'Edge7', 'Edge8', 'Edge9', 'Edge5', 'Edge6', 'Face4', 'Face2', - 'Edge1', 'Vertex4', 'Edge4', 'Vertex3', 'Edge2', 'Edge3', 'Face1', 'Face5', 'Face3', - 'Vertex1', 'Vertex2' + "Vertex6", + "Vertex5", + "Edge7", + "Edge8", + "Edge9", + "Edge5", + "Edge6", + "Face4", + "Face2", + "Edge1", + "Vertex4", + "Edge4", + "Vertex3", + "Edge2", + "Edge3", + "Face1", + "Face5", + "Face3", + "Vertex1", + "Vertex2", ] if cut1.ElementMapVersion != "": # Should be '4' as of Mar 2023. - self.assertKeysInMap(cut1.ElementReverseMap, refkeys ) - self.assertEqual(len(cut1.ElementReverseMap.keys()),len(refkeys)) + self.assertKeysInMap(cut1.ElementReverseMap, refkeys) + self.assertEqual(len(cut1.ElementReverseMap.keys()), len(refkeys)) # Assert Volume - self.assertAlmostEqual(cut1.Volume, self.doc.Cylinder1.Shape.Volume * (3/4)) + self.assertAlmostEqual(cut1.Volume, self.doc.Cylinder1.Shape.Volume * (3 / 4)) def testPartCompoundCut2(self): # Arrange @@ -798,13 +813,54 @@ class TopoShapeTest(unittest.TestCase, TopoShapeAssertions): cut1 = self.doc.Cut.Shape # Assert elementMap refkeys = [ - 'Vertex3', 'Vertex4', 'Vertex8', 'Vertex10', 'Vertex7', 'Vertex9', 'Vertex13', - 'Vertex14', 'Vertex18', 'Vertex20', 'Vertex17', 'Vertex19', 'Edge3', 'Edge15', 'Edge9', - 'Edge12', 'Edge13', 'Edge11', 'Edge8', 'Edge17', 'Edge18', 'Edge19', 'Edge30', 'Edge24', - 'Edge27', 'Edge28', 'Edge29', 'Edge25', 'Edge26', 'Edge23', 'Face7', 'Face4', 'Face8', - 'Face14', 'Face13', 'Face11', 'Face12', 'Face10', 'Edge22', 'Vertex12', 'Edge20', - 'Vertex11', 'Edge21', 'Edge16', 'Face9', 'Vertex15', 'Vertex16' + "Vertex3", + "Vertex4", + "Vertex8", + "Vertex10", + "Vertex7", + "Vertex9", + "Vertex13", + "Vertex14", + "Vertex18", + "Vertex20", + "Vertex17", + "Vertex19", + "Edge3", + "Edge15", + "Edge9", + "Edge12", + "Edge13", + "Edge11", + "Edge8", + "Edge17", + "Edge18", + "Edge19", + "Edge30", + "Edge24", + "Edge27", + "Edge28", + "Edge29", + "Edge25", + "Edge26", + "Edge23", + "Face7", + "Face4", + "Face8", + "Face14", + "Face13", + "Face11", + "Face12", + "Face10", + "Edge22", + "Vertex12", + "Edge20", + "Vertex11", + "Edge21", + "Edge16", + "Face9", + "Vertex15", + "Vertex16", ] if cut1.ElementMapVersion != "": # Should be '4' as of Mar 2023. - self.assertKeysInMap(cut1.ElementReverseMap, refkeys ) - self.assertEqual(len(cut1.ElementReverseMap.keys()),len(refkeys)) + self.assertKeysInMap(cut1.ElementReverseMap, refkeys) + self.assertEqual(len(cut1.ElementReverseMap.keys()), len(refkeys)) diff --git a/src/Mod/Part/parttests/__init__.py b/src/Mod/Part/parttests/__init__.py index 8fbb285884..bd4fba4dfe 100644 --- a/src/Mod/Part/parttests/__init__.py +++ b/src/Mod/Part/parttests/__init__.py @@ -1 +1 @@ -# SPDX-License-Identifier: LGPL-2.1-or-later \ No newline at end of file +# SPDX-License-Identifier: LGPL-2.1-or-later diff --git a/src/Mod/Part/parttests/part_test_objects.py b/src/Mod/Part/parttests/part_test_objects.py index 3c92ede1c3..a3de0c1644 100644 --- a/src/Mod/Part/parttests/part_test_objects.py +++ b/src/Mod/Part/parttests/part_test_objects.py @@ -67,12 +67,14 @@ def _create_frame(): version = App.Version() now = datetime.datetime.now().strftime("%Y/%m/%dT%H:%M:%S") - _text = ["Part test file", - "Created: {}".format(now), - "\n", - "Version: " + ".".join(version[0:3]), - "Release: " + " ".join(version[3:5]), - "Branch: " + " ".join(version[5:])] + _text = [ + "Part test file", + "Created: {}".format(now), + "\n", + "Version: " + ".".join(version[0:3]), + "Release: " + " ".join(version[3:5]), + "Branch: " + " ".join(version[5:]), + ] record = App.ActiveDocument.addObject("App::Annotation", "Description") record.LabelText = _text record.Position = Vector(0, -1000, 0) @@ -92,9 +94,7 @@ def _create_frame(): frame.Shape = poly -def create_test_file(file_name="part_test_objects", - file_path=os.environ["HOME"], - save=False): +def create_test_file(file_name="part_test_objects", file_path=os.environ["HOME"], save=False): """Create a complete test file of Part objects. It draws a frame with information on the software used to create @@ -265,8 +265,7 @@ def create_test_file(file_name="part_test_objects", _msg(16 * "-") _msg("Regular polygon") displacement += Vector(2500, 0, 0) - polygon = App.ActiveDocument.addObject("Part::RegularPolygon", - "RegularPolygon") + polygon = App.ActiveDocument.addObject("Part::RegularPolygon", "RegularPolygon") polygon.Circumradius = 750 polygon.Placement.Base = displacement @@ -288,6 +287,7 @@ def create_test_file(file_name="part_test_objects", return doc + ## @} diff --git a/src/Mod/Part/parttests/regression_tests.py b/src/Mod/Part/parttests/regression_tests.py index d0589abb97..5ebd05b7e3 100644 --- a/src/Mod/Part/parttests/regression_tests.py +++ b/src/Mod/Part/parttests/regression_tests.py @@ -12,6 +12,7 @@ if "BUILD_SKETCHER" in FreeCAD.__cmake__: import unittest + class RegressionTests(unittest.TestCase): # pylint: disable=attribute-defined-outside-init @@ -111,21 +112,21 @@ class RegressionTests(unittest.TestCase): def test_CircularReference(self): - cube = self.Doc.addObject("Part::Box","Cube") - cube.setExpression('Length', 'Width + 10mm') + cube = self.Doc.addObject("Part::Box", "Cube") + cube.setExpression("Length", "Width + 10mm") with self.assertRaises(RuntimeError) as context: - cube.setExpression('Width', 'Length + 10mm') + cube.setExpression("Width", "Length + 10mm") assert "Width reference creates a cyclic dependency." in str(context.exception) - cube.setExpression('.Placement.Base.x', '.Placement.Base.y + 10mm') + cube.setExpression(".Placement.Base.x", ".Placement.Base.y + 10mm") with self.assertRaises(RuntimeError) as context: - cube.setExpression('.Placement.Base.y', '.Placement.Base.x + 10mm') + cube.setExpression(".Placement.Base.y", ".Placement.Base.x + 10mm") assert ".Placement.Base.y reference creates a cyclic dependency." in str(context.exception) cube.recompute() v1 = cube.Placement.Base cube.recompute() - assert cube.Placement.Base.isEqual(v1,1e-6) + assert cube.Placement.Base.isEqual(v1, 1e-6) def test_TangentMode3_Issue24254(self): """In FreeCAD 1.1 we changed the behavior of the mmTangentPlane, but added code to handle old files @@ -133,7 +134,7 @@ class RegressionTests(unittest.TestCase): tangent plane setup.""" location = os.path.dirname(os.path.realpath(__file__)) - FreeCAD.openDocument(os.path.join(location,"TestTangentMode3-0.21.FCStd"), True) + FreeCAD.openDocument(os.path.join(location, "TestTangentMode3-0.21.FCStd"), True) def check_plane(name, expected_pos, expected_normal, expected_xaxis): obj = FreeCAD.ActiveDocument.getObject(name) @@ -143,8 +144,8 @@ class RegressionTests(unittest.TestCase): pos = obj.Placement.Base rot = obj.Placement.Rotation - normal = rot.multVec(FreeCAD.Vector(0,0,1)) - xaxis = rot.multVec(FreeCAD.Vector(1,0,0)) + normal = rot.multVec(FreeCAD.Vector(0, 0, 1)) + xaxis = rot.multVec(FreeCAD.Vector(1, 0, 0)) # position self.assertAlmostEqual((pos - expected_pos).Length, 0) @@ -161,26 +162,24 @@ class RegressionTests(unittest.TestCase): sin30 = math.sin(rad30) expected_planes = [ - ("Sketch001", - FreeCAD.Vector(-1 * r, 0, 0), # position - FreeCAD.Vector(1, 0, 0), # normal - FreeCAD.Vector(0, -1, 0)), # tangent x-axis - ("Sketch002", - FreeCAD.Vector(sin30 * r, - cos30 * cos30 * (-r), - cos30 * sin30 * r), - FreeCAD.Vector(sin30, - cos30 * cos30 * (-1), - cos30 * sin30), - FreeCAD.Vector(0, sin30, cos30)), - ("Sketch003", - FreeCAD.Vector(cos30 * cos30 * r, - sin30 * r, - cos30 * sin30 * r), - FreeCAD.Vector(cos30 * cos30, - sin30, - cos30 * sin30), - FreeCAD.Vector(sin30, 0, -cos30)), + ( + "Sketch001", + FreeCAD.Vector(-1 * r, 0, 0), # position + FreeCAD.Vector(1, 0, 0), # normal + FreeCAD.Vector(0, -1, 0), + ), # tangent x-axis + ( + "Sketch002", + FreeCAD.Vector(sin30 * r, cos30 * cos30 * (-r), cos30 * sin30 * r), + FreeCAD.Vector(sin30, cos30 * cos30 * (-1), cos30 * sin30), + FreeCAD.Vector(0, sin30, cos30), + ), + ( + "Sketch003", + FreeCAD.Vector(cos30 * cos30 * r, sin30 * r, cos30 * sin30 * r), + FreeCAD.Vector(cos30 * cos30, sin30, cos30 * sin30), + FreeCAD.Vector(sin30, 0, -cos30), + ), ] for name, pos, normal, xaxis in expected_planes: diff --git a/src/Mod/PartDesign/App/AppPartDesignPy.cpp b/src/Mod/PartDesign/App/AppPartDesignPy.cpp index 52b4e51d48..f268dba391 100644 --- a/src/Mod/PartDesign/App/AppPartDesignPy.cpp +++ b/src/Mod/PartDesign/App/AppPartDesignPy.cpp @@ -27,47 +27,58 @@ #include -namespace PartDesign { -class Module : public Py::ExtensionModule +namespace PartDesign +{ +class Module: public Py::ExtensionModule { public: - Module() : Py::ExtensionModule("_PartDesign") + Module() + : Py::ExtensionModule("_PartDesign") { - add_varargs_method("makeFilletArc",&Module::makeFilletArc, - "makeFilletArc(...) -- Fillet arc." - ); - initialize("This module is the PartDesign module."); // register with Python + add_varargs_method("makeFilletArc", &Module::makeFilletArc, "makeFilletArc(...) -- Fillet arc."); + initialize("This module is the PartDesign module."); // register with Python } private: Py::Object makeFilletArc(const Py::Tuple& args) { - PyObject *pM1; - PyObject *pP; - PyObject *pQ; - PyObject *pN; + PyObject* pM1; + PyObject* pP; + PyObject* pQ; + PyObject* pN; double r2; int ccw; - if (!PyArg_ParseTuple(args.ptr(), "O!O!O!O!di", - &(Base::VectorPy::Type), &pM1, - &(Base::VectorPy::Type), &pP, - &(Base::VectorPy::Type), &pQ, - &(Base::VectorPy::Type), &pN, - &r2, &ccw)) + if (!PyArg_ParseTuple( + args.ptr(), + "O!O!O!O!di", + &(Base::VectorPy::Type), + &pM1, + &(Base::VectorPy::Type), + &pP, + &(Base::VectorPy::Type), + &pQ, + &(Base::VectorPy::Type), + &pN, + &r2, + &ccw + )) { throw Py::Exception(); + } Base::Vector3d M1 = Py::Vector(pM1, false).toVector(); - Base::Vector3d P = Py::Vector(pP, false).toVector(); - Base::Vector3d Q = Py::Vector(pQ, false).toVector(); - Base::Vector3d N = Py::Vector(pN, false).toVector(); + Base::Vector3d P = Py::Vector(pP, false).toVector(); + Base::Vector3d Q = Py::Vector(pQ, false).toVector(); + Base::Vector3d N = Py::Vector(pN, false).toVector(); Base::Vector3d u = Q - P; Base::Vector3d v = P - M1; Base::Vector3d b; - if (ccw) + if (ccw) { b = u % N; - else + } + else { b = N % u; + } b.Normalize(); double uu = u * u; @@ -87,14 +98,16 @@ private: double t1 = (-uv + sqrt(d)) / uu; double t2 = (-uv - sqrt(d)) / uu; - if (fabs(t1) < fabs(t2)) + if (fabs(t1) < fabs(t2)) { t = t1; - else + } + else { t = t2; + } - Base::Vector3d M2 = P + (u*t) + (b*r2); - Base::Vector3d S1 = (r2 * M1 + r1 * M2)/(r1+r2); - Base::Vector3d S2 = M2 - (b*r2); + Base::Vector3d M2 = P + (u * t) + (b * r2); + Base::Vector3d S1 = (r2 * M1 + r1 * M2) / (r1 + r2); + Base::Vector3d S2 = M2 - (b * r2); Py::Tuple tuple(3); tuple.setItem(0, Py::Vector(S1)); @@ -110,4 +123,4 @@ PyObject* initModule() return Base::Interpreter().addModule(new Module); } -} // namespace PartDesign +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/Body.cpp b/src/Mod/PartDesign/App/Body.cpp index 25cc873a71..8c0ca5369b 100644 --- a/src/Mod/PartDesign/App/Body.cpp +++ b/src/Mod/PartDesign/App/Body.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -42,35 +41,34 @@ PROPERTY_SOURCE(PartDesign::Body, Part::BodyBase) Body::Body() { - ADD_PROPERTY_TYPE(AllowCompound, (true), "Experimental", App::Prop_None, "Allow multiple solids in Body (experimental)"); + ADD_PROPERTY_TYPE( + AllowCompound, + (true), + "Experimental", + App::Prop_None, + "Allow multiple solids in Body (experimental)" + ); _GroupTouched.setStatus(App::Property::Output, true); } /* -// Note: The following code will catch Python Document::removeObject() modifications. If the object removed is -// a member of the Body::Group, then it will be automatically removed from the Group property which triggers the +// Note: The following code will catch Python Document::removeObject() modifications. If the object +removed is +// a member of the Body::Group, then it will be automatically removed from the Group property which +triggers the // following two methods -// But since we require the Python user to call both Document::addObject() and Body::addObject(), we should -// also require calling both Document::removeObject and Body::removeFeature() in order to be consistent -void Body::onBeforeChange(const App::Property *prop) +// But since we require the Python user to call both Document::addObject() and Body::addObject(), we +should +// also require calling both Document::removeObject and Body::removeFeature() in order to be +consistent void Body::onBeforeChange(const App::Property *prop) { - // Remember the feature before the current Tip. If the Tip is already at the first feature, remember the next feature - if (prop == &Group) { - std::vector features = Group.getValues(); - if (features.empty()) { - rememberTip = NULL; - } else { - std::vector::iterator it = std::find(features.begin(), features.end(), Tip.getValue()); - if (it == features.begin()) { - it++; - if (it == features.end()) - rememberTip = NULL; - else - rememberTip = *it; - } else { - it--; - rememberTip = *it; + // Remember the feature before the current Tip. If the Tip is already at the first feature, +remember the next feature if (prop == &Group) { std::vector features = +Group.getValues(); if (features.empty()) { rememberTip = NULL; } else { + std::vector::iterator it = std::find(features.begin(), +features.end(), Tip.getValue()); if (it == features.begin()) { it++; if (it == features.end()) +rememberTip = NULL; else rememberTip = *it; } else { it--; rememberTip = *it; } } } @@ -85,8 +83,8 @@ void Body::onChanged(const App::Property *prop) if (features.empty()) { Tip.setValue(NULL); } else { - std::vector::iterator it = std::find(features.begin(), features.end(), Tip.getValue()); - if (it == features.end()) { + std::vector::iterator it = std::find(features.begin(), +features.end(), Tip.getValue()); if (it == features.end()) { // Tip feature was deleted Tip.setValue(rememberTip); } @@ -99,83 +97,87 @@ void Body::onChanged(const App::Property *prop) short Body::mustExecute() const { - if ( Tip.isTouched() ) { + if (Tip.isTouched()) { return 1; } return Part::BodyBase::mustExecute(); } -App::DocumentObject* Body::getPrevSolidFeature(App::DocumentObject *start) +App::DocumentObject* Body::getPrevSolidFeature(App::DocumentObject* start) { - if (!start) { // default to tip + if (!start) { // default to tip start = Tip.getValue(); } - if (!start) { // No Tip + if (!start) { // No Tip return nullptr; } - if (!hasObject(start)) - return nullptr; - - const std::vector & features = Group.getValues(); - - auto startIt = std::find (features.rbegin(), features.rend(), start); - if (startIt == features.rend()) { // object not found + if (!hasObject(start)) { return nullptr; } - auto rvIt = std::find_if (startIt + 1, features.rend(), isSolidFeature); - if (rvIt != features.rend()) { // the solid found in model list + const std::vector& features = Group.getValues(); + + auto startIt = std::find(features.rbegin(), features.rend(), start); + if (startIt == features.rend()) { // object not found + return nullptr; + } + + auto rvIt = std::find_if(startIt + 1, features.rend(), isSolidFeature); + if (rvIt != features.rend()) { // the solid found in model list return *rvIt; } return nullptr; } -App::DocumentObject* Body::getNextSolidFeature(App::DocumentObject *start) +App::DocumentObject* Body::getNextSolidFeature(App::DocumentObject* start) { - if (!start) { // default to tip + if (!start) { // default to tip start = Tip.getValue(); } - if (!start || !hasObject(start)) { // no or faulty tip + if (!start || !hasObject(start)) { // no or faulty tip return nullptr; } - const std::vector & features = Group.getValues(); + const std::vector& features = Group.getValues(); std::vector::const_iterator startIt; - startIt = std::find (features.begin(), features.end(), start); - if (startIt == features.end()) { // object not found + startIt = std::find(features.begin(), features.end(), start); + if (startIt == features.end()) { // object not found return nullptr; } startIt++; - if (startIt == features.end()) { // features list has only one element + if (startIt == features.end()) { // features list has only one element return nullptr; } - auto rvIt = std::find_if (startIt, features.end(), isSolidFeature); - if (rvIt != features.end()) { // the solid found in model list + auto rvIt = std::find_if(startIt, features.end(), isSolidFeature); + if (rvIt != features.end()) { // the solid found in model list return *rvIt; } return nullptr; } -bool Body::isAfterInsertPoint(App::DocumentObject* feature) { - App::DocumentObject *nextSolid = getNextSolidFeature (); - assert (feature); +bool Body::isAfterInsertPoint(App::DocumentObject* feature) +{ + App::DocumentObject* nextSolid = getNextSolidFeature(); + assert(feature); if (feature == nextSolid) { return true; - } else if (!nextSolid) { // the tip is last solid, we can't be placed after it + } + else if (!nextSolid) { // the tip is last solid, we can't be placed after it return false; - } else { - return isAfter ( feature, nextSolid ); + } + else { + return isAfter(feature, nextSolid); } } -bool Body::isSolidFeature(const App::DocumentObject *obj) +bool Body::isSolidFeature(const App::DocumentObject* obj) { if (!obj) { return false; @@ -192,68 +194,70 @@ bool Body::isSolidFeature(const App::DocumentObject *obj) } return true; } - return false;//DeepSOIC: work-in-progress? + return false; // DeepSOIC: work-in-progress? } -bool Body::isAllowed(const App::DocumentObject *obj) +bool Body::isAllowed(const App::DocumentObject* obj) { - if (!obj) + if (!obj) { return false; + } - // TODO: Should we introduce a PartDesign::FeaturePython class? This should then also return true for isSolidFeature() - return (obj->isDerivedFrom() || - obj->isDerivedFrom() || - // TODO Shouldn't we replace it with Sketcher::SketchObject? (2015-08-13, Fat-Zer) - obj->isDerivedFrom() || - obj->isDerivedFrom() || - obj->isDerivedFrom() || - // TODO Why this lines was here? why should we allow anything of those? (2015-08-13, Fat-Zer) - //obj->isDerivedFrom() // trouble with this line on Windows!? Linker fails to find getClassTypeId() of the Part::FeaturePython... - //obj->isDerivedFrom() - // allow VarSets for parameterization - obj->isDerivedFrom() || - obj->isDerivedFrom() || - obj->isDerivedFrom() - ); + // TODO: Should we introduce a PartDesign::FeaturePython class? This should then also return + // true for isSolidFeature() + return ( + obj->isDerivedFrom() || obj->isDerivedFrom() || + // TODO Shouldn't we replace it with Sketcher::SketchObject? (2015-08-13, Fat-Zer) + obj->isDerivedFrom() || obj->isDerivedFrom() + || obj->isDerivedFrom() || + // TODO Why this lines was here? why should we allow anything of those? (2015-08-13, + // Fat-Zer) obj->isDerivedFrom() // trouble with this line on Windows!? + // Linker fails to find getClassTypeId() of the Part::FeaturePython... + // obj->isDerivedFrom() + // allow VarSets for parameterization + obj->isDerivedFrom() || obj->isDerivedFrom() + || obj->isDerivedFrom() + ); } Body* Body::findBodyOf(const App::DocumentObject* feature) { - if(!feature) + if (!feature) { return nullptr; + } return static_cast(BodyBase::findBodyOf(feature)); } -std::vector Body::addObject(App::DocumentObject *feature) +std::vector Body::addObject(App::DocumentObject* feature) { - if(!isAllowed(feature)) + if (!isAllowed(feature)) { throw Base::ValueError("Body: object is not allowed"); - - //TODO: features should not add all links - - //only one group per object. If it is in a body the single feature will be removed - auto *group = App::GroupExtension::getGroupOfObject(feature); - if(group && group != getExtendedObject()) - group->getExtensionByType()->removeObject(feature); - - - insertObject (feature, getNextSolidFeature (), /*after = */ false); - // Move the Tip if we added a solid - if (isSolidFeature(feature)) { - Tip.setValue (feature); } - if(feature->Visibility.getValue() - && feature->isDerivedFrom()) - { - for(auto obj : Group.getValues()) { - if(obj->Visibility.getValue() - && obj!=feature - && obj->isDerivedFrom()) + // TODO: features should not add all links + + // only one group per object. If it is in a body the single feature will be removed + auto* group = App::GroupExtension::getGroupOfObject(feature); + if (group && group != getExtendedObject()) { + group->getExtensionByType()->removeObject(feature); + } + + + insertObject(feature, getNextSolidFeature(), /*after = */ false); + // Move the Tip if we added a solid + if (isSolidFeature(feature)) { + Tip.setValue(feature); + } + + if (feature->Visibility.getValue() && feature->isDerivedFrom()) { + for (auto obj : Group.getValues()) { + if (obj->Visibility.getValue() && obj != feature + && obj->isDerivedFrom()) { obj->Visibility.setValue(false); + } } } @@ -261,23 +265,26 @@ std::vector Body::addObject(App::DocumentObject *feature) return result; } -std::vector< App::DocumentObject* > Body::addObjects(std::vector< App::DocumentObject* > objs) { +std::vector Body::addObjects(std::vector objs) +{ - for(auto obj : objs) + for (auto obj : objs) { addObject(obj); + } return objs; } - void Body::insertObject(App::DocumentObject* feature, App::DocumentObject* target, bool after) { - if (target && !hasObject (target)) { - throw Base::ValueError("Body: the feature we should insert relative to is not part of that body"); + if (target && !hasObject(target)) { + throw Base::ValueError( + "Body: the feature we should insert relative to is not part of that body" + ); } - //ensure that all origin links are ok + // ensure that all origin links are ok relinkToOrigin(feature); std::vector model = Group.getValues(); @@ -287,26 +294,31 @@ void Body::insertObject(App::DocumentObject* feature, App::DocumentObject* targe if (!target) { if (after) { insertInto = model.begin(); - } else { + } + else { insertInto = model.end(); } - } else { - std::vector::iterator targetIt = std::find (model.begin(), model.end(), target); - assert (targetIt != model.end()); + } + else { + std::vector::iterator targetIt + = std::find(model.begin(), model.end(), target); + assert(targetIt != model.end()); if (after) { insertInto = targetIt + 1; - } else { + } + else { insertInto = targetIt; } } // Insert the new feature after the given - model.insert (insertInto, feature); + model.insert(insertInto, feature); - Group.setValues (model); + Group.setValues(model); - if(feature->isDerivedFrom()) + if (feature->isDerivedFrom()) { static_cast(feature)->_Body.setValue(this); + } // Set the BaseFeature property setBaseProperty(feature); @@ -323,7 +335,7 @@ void Body::setBaseProperty(App::DocumentObject* feature) // Reroute the next solid feature's BaseFeature property to this feature App::DocumentObject* nextSolidFeature = getNextSolidFeature(feature); if (nextSolidFeature) { - assert ( nextSolidFeature->isDerivedFrom ( PartDesign::Feature::getClassTypeId () ) ); + assert(nextSolidFeature->isDerivedFrom(PartDesign::Feature::getClassTypeId())); static_cast(nextSolidFeature)->BaseFeature.setValue(feature); } } @@ -338,8 +350,9 @@ std::vector Body::removeObject(App::DocumentObject* featur // This is a solid feature // If the next feature is solid, reroute its BaseFeature property to the previous solid feature if (nextSolidFeature) { - assert ( nextSolidFeature->isDerivedFrom ( PartDesign::Feature::getClassTypeId () ) ); - // Note: It's ok to remove the first solid feature, that just mean the next feature become the base one + assert(nextSolidFeature->isDerivedFrom(PartDesign::Feature::getClassTypeId())); + // Note: It's ok to remove the first solid feature, that just mean the next feature + // become the base one static_cast(nextSolidFeature)->BaseFeature.setValue(prevSolidFeature); } } @@ -348,10 +361,11 @@ std::vector Body::removeObject(App::DocumentObject* featur const auto it = std::ranges::find(model, feature); // Adjust Tip feature if it is pointing to the deleted object - if (Tip.getValue()== feature) { + if (Tip.getValue() == feature) { if (prevSolidFeature) { Tip.setValue(prevSolidFeature); - } else { + } + else { Tip.setValue(nextSolidFeature); } } @@ -366,7 +380,7 @@ std::vector Body::removeObject(App::DocumentObject* featur } -App::DocumentObjectExecReturn *Body::execute() +App::DocumentObjectExecReturn* Body::execute() { Part::BodyBase::execute(); /* @@ -375,13 +389,11 @@ App::DocumentObjectExecReturn *Body::execute() Base::Console().error(" Tip: %s\n", (tip == NULL) ? "None" : tip->getNameInDocument()); std::vector model = Group.getValues(); Base::Console().error(" Group:\n"); - for (std::vector::const_iterator m = model.begin(); m != model.end(); m++) { - if (*m == NULL) continue; - Base::Console().error(" %s", (*m)->getNameInDocument()); - if (Body::isSolidFeature(*m)) { - App::DocumentObject* baseFeature = static_cast(*m)->BaseFeature.getValue(); - Base::Console().error(", Base: %s\n", baseFeature == NULL ? "None" : baseFeature->getNameInDocument()); - } else { + for (std::vector::const_iterator m = model.begin(); m != model.end(); m++) + { if (*m == NULL) continue; Base::Console().error(" %s", (*m)->getNameInDocument()); if + (Body::isSolidFeature(*m)) { App::DocumentObject* baseFeature = + static_cast(*m)->BaseFeature.getValue(); Base::Console().error(", Base: + %s\n", baseFeature == NULL ? "None" : baseFeature->getNameInDocument()); } else { Base::Console().error("\n"); } } @@ -390,55 +402,61 @@ App::DocumentObjectExecReturn *Body::execute() App::DocumentObject* tip = Tip.getValue(); Part::TopoShape tipShape; - if ( tip ) { - if ( !tip->isDerivedFrom() ) { - return new App::DocumentObjectExecReturn (QT_TRANSLATE_NOOP("Exception", "Linked object is not a PartDesign feature" )); + if (tip) { + if (!tip->isDerivedFrom()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Linked object is not a PartDesign feature") + ); } // get the shape of the tip - tipShape = static_cast(tip)->Shape.getShape(); + tipShape = static_cast(tip)->Shape.getShape(); - if ( tipShape.getShape().IsNull () ) { - return new App::DocumentObjectExecReturn (QT_TRANSLATE_NOOP("Exception", "Tip shape is empty" )); + if (tipShape.getShape().IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Tip shape is empty") + ); } // We should hide here the transformation of the baseFeature - tipShape.transformShape (tipShape.getTransform(), true ); - - } else { + tipShape.transformShape(tipShape.getTransform(), true); + } + else { tipShape = Part::TopoShape(); } - Shape.setValue ( tipShape ); + Shape.setValue(tipShape); return App::DocumentObject::StdReturn; - } -void Body::onSettingDocument() { +void Body::onSettingDocument() +{ - if(connection.connected()) + if (connection.connected()) { connection.disconnect(); + } Part::BodyBase::onSettingDocument(); } -void Body::onChanged(const App::Property* prop) { +void Body::onChanged(const App::Property* prop) +{ // we neither load a project nor perform undo/redo - if (!this->isRestoring() - && this->getDocument() - && !this->getDocument()->isPerformingTransaction()) { + if (!this->isRestoring() && this->getDocument() + && !this->getDocument()->isPerformingTransaction()) { if (prop == &BaseFeature) { FeatureBase* bf = nullptr; auto first = Group.getValues().empty() ? nullptr : Group.getValues().front(); if (BaseFeature.getValue()) { - //setup the FeatureBase if needed + // setup the FeatureBase if needed if (!first || !first->isDerivedFrom()) { bf = getDocument()->addObject("BaseFeature"); insertObject(bf, first, false); - if (!Tip.getValue()) + if (!Tip.getValue()) { Tip.setValue(bf); + } } else { bf = static_cast(first); @@ -450,10 +468,11 @@ void Body::onChanged(const App::Property* prop) { } } else if (prop == &Group) { - //if the FeatureBase was deleted we set the BaseFeature link to nullptr - if (BaseFeature.getValue() && - (Group.getValues().empty() || !Group.getValues().front()->isDerivedFrom())) { - BaseFeature.setValue(nullptr); + // if the FeatureBase was deleted we set the BaseFeature link to nullptr + if (BaseFeature.getValue() + && (Group.getValues().empty() + || !Group.getValues().front()->isDerivedFrom())) { + BaseFeature.setValue(nullptr); } } else if (prop == &AllowCompound) { @@ -463,7 +482,6 @@ void Body::onChanged(const App::Property* prop) { for (auto feature : getFullModel()) { feature->enforceRecompute(); } - } else if (prop == &ShapeMaterial) { std::vector features = Group.getValues(); @@ -484,31 +502,40 @@ void Body::onChanged(const App::Property* prop) { Part::BodyBase::onChanged(prop); } -void Body::setupObject () { - Part::BodyBase::setupObject (); -} - -void Body::unsetupObject () { - Part::BodyBase::unsetupObject (); -} - -PyObject *Body::getPyObject() +void Body::setupObject() { - if (PythonObject.is(Py::_None())){ + Part::BodyBase::setupObject(); +} + +void Body::unsetupObject() +{ + Part::BodyBase::unsetupObject(); +} + +PyObject* Body::getPyObject() +{ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new BodyPy(this),true); + PythonObject = Py::Object(new BodyPy(this), true); } return Py::new_reference_to(PythonObject); } -std::vector Body::getSubObjects(int reason) const { - if(reason==GS_SELECT && !showTip) +std::vector Body::getSubObjects(int reason) const +{ + if (reason == GS_SELECT && !showTip) { return Part::BodyBase::getSubObjects(reason); + } return {}; } -App::DocumentObject *Body::getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const +App::DocumentObject* Body::getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth +) const { while (subname && *subname == '.') { ++subname; // skip leading . @@ -529,18 +556,20 @@ App::DocumentObject *Body::getSubObject(const char *subname, if (secondObj) { // we support only one level of sibling grouping, so no // recursive call to our own getSubObject() - return Part::BodyBase::getSubObject(firstDot + 1, - pyObj, - pmat, - transform, - depth + 1); + return Part::BodyBase::getSubObject( + firstDot + 1, + pyObj, + pmat, + transform, + depth + 1 + ); } } } } } #if 1 - return Part::BodyBase::getSubObject(subname,pyObj,pmat,transform,depth); + return Part::BodyBase::getSubObject(subname, pyObj, pmat, transform, depth); #else // The following code returns Body shape only if there is at least one // child visible in the body (when show through, not show tip). The @@ -549,35 +578,37 @@ App::DocumentObject *Body::getSubObject(const char *subname, // interfere with direct modeling using body shape. Therefore it is // disabled here. - if(!pyObj || showTip || - (subname && !Data::ComplexGeoData::isMappedElement(subname) && strchr(subname,'.'))) - return Part::BodyBase::getSubObject(subname,pyObj,pmat,transform,depth); + if (!pyObj || showTip + || (subname && !Data::ComplexGeoData::isMappedElement(subname) && strchr(subname, '.'))) { + return Part::BodyBase::getSubObject(subname, pyObj, pmat, transform, depth); + } // We return the shape only if there are feature visible inside - for(auto obj : Group.getValues()) { - if(obj->Visibility.getValue() && - obj->isDerivedFrom()) - { - return Part::BodyBase::getSubObject(subname,pyObj,pmat,transform,depth); + for (auto obj : Group.getValues()) { + if (obj->Visibility.getValue() && obj->isDerivedFrom()) { + return Part::BodyBase::getSubObject(subname, pyObj, pmat, transform, depth); } } - if(pmat && transform) + if (pmat && transform) { *pmat *= Placement.getValue().toMatrix(); + } return const_cast(this); #endif } void Body::onDocumentRestored() { - for(auto obj : Group.getValues()) { - if(obj->isDerivedFrom()) + for (auto obj : Group.getValues()) { + if (obj->isDerivedFrom()) { static_cast(obj)->_Body.setValue(this); + } } - _GroupTouched.setStatus(App::Property::Output,true); + _GroupTouched.setStatus(App::Property::Output, true); // trigger ViewProviderBody::copyColorsfromTip - if (Tip.getValue()) + if (Tip.getValue()) { Tip.touch(); + } DocumentObject::onDocumentRestored(); } @@ -585,10 +616,11 @@ void Body::onDocumentRestored() // a body is solid if it has features that are solid bool Body::isSolid() { - std::vector features = getFullModel(); - for (auto feature : features){ - if (isSolidFeature(feature)) + std::vector features = getFullModel(); + for (auto feature : features) { + if (isSolidFeature(feature)) { return true; + } } return false; } diff --git a/src/Mod/PartDesign/App/Body.h b/src/Mod/PartDesign/App/Body.h index b905fd2997..0540bf4f89 100644 --- a/src/Mod/PartDesign/App/Body.h +++ b/src/Mod/PartDesign/App/Body.h @@ -27,8 +27,9 @@ #include #include -namespace App { - class Origin; +namespace App +{ +class Origin; } namespace PartDesign @@ -36,7 +37,7 @@ namespace PartDesign class Feature; -class PartDesignExport Body : public Part::BodyBase +class PartDesignExport Body: public Part::BodyBase { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Body); @@ -44,18 +45,19 @@ public: App::PropertyBool AllowCompound; /// True if this body feature is active or was active when the document was last closed - //App::PropertyBool IsActive; + // App::PropertyBool IsActive; Body(); /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderBody"; } //@} @@ -65,7 +67,7 @@ public: * The insertion point is the before next solid after the Tip feature */ std::vector addObject(App::DocumentObject*) override; - std::vector< DocumentObject* > addObjects(std::vector< DocumentObject* > obj) override; + std::vector addObjects(std::vector obj) override; /** * Insert the feature into the body after the given feature. @@ -78,7 +80,7 @@ public: * * @note the method doesn't modify the Tip unlike addObject() */ - void insertObject(App::DocumentObject* feature, App::DocumentObject* target, bool after=false); + void insertObject(App::DocumentObject* feature, App::DocumentObject* target, bool after = false); void setBaseProperty(App::DocumentObject* feature); @@ -92,48 +94,55 @@ public: bool isAfterInsertPoint(App::DocumentObject* feature); /** - * Return true if the given feature is a solid feature allowed in a Body. Currently this is only valid - * for features derived from PartDesign::Feature - * Return false if the given feature is a Sketch or a Part::Datum feature - */ - static bool isSolidFeature(const App::DocumentObject *obj); + * Return true if the given feature is a solid feature allowed in a Body. Currently this is only + * valid for features derived from PartDesign::Feature Return false if the given feature is a + * Sketch or a Part::Datum feature + */ + static bool isSolidFeature(const App::DocumentObject* obj); /** - * Return true if the given feature is allowed in a Body. Currently allowed are - * all features derived from PartDesign::Feature and Part::Datum and sketches - */ - static bool isAllowed(const App::DocumentObject *obj); - bool allowObject(DocumentObject *obj) override { - return isAllowed(obj); + * Return true if the given feature is allowed in a Body. Currently allowed are + * all features derived from PartDesign::Feature and Part::Datum and sketches + */ + static bool isAllowed(const App::DocumentObject* obj); + bool allowObject(DocumentObject* obj) override + { + return isAllowed(obj); } /** * Return the body which this feature belongs too, or NULL * The only difference to BodyBase::findBodyOf() is that this one casts value to Body* */ - static Body *findBodyOf(const App::DocumentObject* feature); + static Body* findBodyOf(const App::DocumentObject* feature); - PyObject *getPyObject() override; + PyObject* getPyObject() override; - std::vector getSubObjects(int reason=0) const override; - App::DocumentObject *getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const override; + std::vector getSubObjects(int reason = 0) const override; + App::DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth + ) const override; - void setShowTip(bool enable) { + void setShowTip(bool enable) + { showTip = enable; } /** - * Return the solid feature before the given feature, or before the Tip feature - * That is, sketches and datum features are skipped - */ - App::DocumentObject *getPrevSolidFeature(App::DocumentObject *start = nullptr); + * Return the solid feature before the given feature, or before the Tip feature + * That is, sketches and datum features are skipped + */ + App::DocumentObject* getPrevSolidFeature(App::DocumentObject* start = nullptr); /** - * Return the next solid feature after the given feature, or after the Tip feature - * That is, sketches and datum features are skipped - */ - App::DocumentObject *getNextSolidFeature(App::DocumentObject* start = nullptr); + * Return the next solid feature after the given feature, or after the Tip feature + * That is, sketches and datum features are skipped + */ + App::DocumentObject* getNextSolidFeature(App::DocumentObject* start = nullptr); // a body is solid if it has features that are solid according to member isSolidFeature. bool isSolid(); @@ -142,12 +151,12 @@ protected: void onSettingDocument() override; /// Adjusts the first solid's feature's base on BaseFeature getting set - void onChanged (const App::Property* prop) override; + void onChanged(const App::Property* prop) override; /// Creates the corresponding Origin object - void setupObject () override; + void setupObject() override; /// Removes all planes and axis if they are still linked to the document - void unsetupObject () override; + void unsetupObject() override; void onDocumentRestored() override; @@ -156,7 +165,7 @@ private: bool showTip = false; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Body_H +#endif // PART_Body_H diff --git a/src/Mod/PartDesign/App/BodyPyImp.cpp b/src/Mod/PartDesign/App/BodyPyImp.cpp index e30ad10f54..d0a66714bd 100644 --- a/src/Mod/PartDesign/App/BodyPyImp.cpp +++ b/src/Mod/PartDesign/App/BodyPyImp.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include "Mod/PartDesign/App/Body.h" #include "Mod/PartDesign/App/Feature.h" @@ -38,8 +37,7 @@ std::string BodyPy::representation() const } - -PyObject *BodyPy::getCustomAttributes(const char* /*attr*/) const +PyObject* BodyPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } @@ -49,24 +47,35 @@ int BodyPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -PyObject* BodyPy::insertObject(PyObject *args) +PyObject* BodyPy::insertObject(PyObject* args) { PyObject* featurePy; PyObject* targetPy; PyObject* afterPy = Py_False; - if (!PyArg_ParseTuple(args, "O!O|O!", &(App::DocumentObjectPy::Type), &featurePy, - &targetPy, &PyBool_Type, &afterPy)) { + if (!PyArg_ParseTuple( + args, + "O!O|O!", + &(App::DocumentObjectPy::Type), + &featurePy, + &targetPy, + &PyBool_Type, + &afterPy + )) { return nullptr; } - App::DocumentObject* feature = static_cast(featurePy)->getDocumentObjectPtr(); + App::DocumentObject* feature + = static_cast(featurePy)->getDocumentObjectPtr(); App::DocumentObject* target = nullptr; if (PyObject_TypeCheck(targetPy, &(App::DocumentObjectPy::Type))) { target = static_cast(targetPy)->getDocumentObjectPtr(); } if (!Body::isAllowed(feature)) { - PyErr_SetString(PyExc_SystemError, "Only PartDesign features, datum features and sketches can be inserted into a Body"); + PyErr_SetString( + PyExc_SystemError, + "Only PartDesign features, datum features and sketches can be inserted into a Body" + ); return nullptr; } @@ -84,11 +93,12 @@ PyObject* BodyPy::insertObject(PyObject *args) Py_Return; } -Py::Object BodyPy::getVisibleFeature() const { - for(auto obj : getBodyPtr()->Group.getValues()) { - if(obj->Visibility.getValue() && obj->isDerivedFrom()) - return Py::Object(obj->getPyObject(),true); +Py::Object BodyPy::getVisibleFeature() const +{ + for (auto obj : getBodyPtr()->Group.getValues()) { + if (obj->Visibility.getValue() && obj->isDerivedFrom()) { + return Py::Object(obj->getPyObject(), true); + } } return Py::Object(); } - diff --git a/src/Mod/PartDesign/App/CMakeLists.txt b/src/Mod/PartDesign/App/CMakeLists.txt index a24f4a7f82..a96f64ceda 100644 --- a/src/Mod/PartDesign/App/CMakeLists.txt +++ b/src/Mod/PartDesign/App/CMakeLists.txt @@ -162,4 +162,3 @@ SET_BIN_DIR(PartDesign _PartDesign /Mod/PartDesign) SET_PYTHON_PREFIX_SUFFIX(PartDesign) INSTALL(TARGETS PartDesign DESTINATION ${CMAKE_INSTALL_LIBDIR}) - diff --git a/src/Mod/PartDesign/App/DatumCS.cpp b/src/Mod/PartDesign/App/DatumCS.cpp index 198a7236a5..b84d718dbe 100644 --- a/src/Mod/PartDesign/App/DatumCS.cpp +++ b/src/Mod/PartDesign/App/DatumCS.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -42,11 +41,12 @@ PROPERTY_SOURCE(PartDesign::CoordinateSystem, Part::Datum) CoordinateSystem::CoordinateSystem() { this->setAttacher(new AttachEngine3D); - // Create a shape, which will be used by the Sketcher. Them main function is to avoid a dependency of - // Sketcher on the PartDesign module - BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0,0,0), gp_Dir(0,0,1))); - if (!builder.IsDone()) + // Create a shape, which will be used by the Sketcher. Them main function is to avoid a + // dependency of Sketcher on the PartDesign module + BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))); + if (!builder.IsDone()) { return; + } Shape.setValue(builder.Shape()); } @@ -56,7 +56,7 @@ Base::Vector3d CoordinateSystem::getXAxis() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; - rot.multVec(Base::Vector3d(1,0,0), normal); + rot.multVec(Base::Vector3d(1, 0, 0), normal); return normal; } @@ -64,7 +64,7 @@ Base::Vector3d CoordinateSystem::getYAxis() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; - rot.multVec(Base::Vector3d(0,1,0), normal); + rot.multVec(Base::Vector3d(0, 1, 0), normal); return normal; } @@ -72,35 +72,46 @@ Base::Vector3d CoordinateSystem::getZAxis() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; - rot.multVec(Base::Vector3d(0,0,1), normal); + rot.multVec(Base::Vector3d(0, 0, 1), normal); return normal; } -App::DocumentObject *CoordinateSystem::getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int) const +App::DocumentObject* CoordinateSystem::getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int +) const { - if(pmat && transform) + if (pmat && transform) { *pmat *= Placement.getValue().toMatrix(); + } - if(!pyObj) + if (!pyObj) { return const_cast(this); + } - gp_Dir dir(0,0,1); - if(subname) { - if(strcmp(subname,"X")==0) - dir = gp_Dir(1,0,0); - else if(strcmp(subname,"Y")==0) - dir = gp_Dir(0,1,0); + gp_Dir dir(0, 0, 1); + if (subname) { + if (strcmp(subname, "X") == 0) { + dir = gp_Dir(1, 0, 0); + } + else if (strcmp(subname, "Y") == 0) { + dir = gp_Dir(0, 1, 0); + } } Base::PyGILStateLocker lock; - PY_TRY { - BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0,0,0), dir)); + PY_TRY + { + BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0, 0, 0), dir)); Part::TopoShape ts(builder.Shape()); - if(pmat) - ts.transformShape(*pmat,false,true); - *pyObj = Py::new_reference_to(Part::shape2pyshape(ts)); + if (pmat) { + ts.transformShape(*pmat, false, true); + } + *pyObj = Py::new_reference_to(Part::shape2pyshape(ts)); return const_cast(this); - } PY_CATCH_OCC + } + PY_CATCH_OCC } - diff --git a/src/Mod/PartDesign/App/DatumCS.h b/src/Mod/PartDesign/App/DatumCS.h index f21bb43837..2373db606b 100644 --- a/src/Mod/PartDesign/App/DatumCS.h +++ b/src/Mod/PartDesign/App/DatumCS.h @@ -30,7 +30,7 @@ namespace PartDesign { -class PartDesignExport CoordinateSystem : public Part::Datum +class PartDesignExport CoordinateSystem: public Part::Datum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::CoordinateSystem); @@ -38,7 +38,8 @@ public: CoordinateSystem(); ~CoordinateSystem() override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderDatumCoordinateSystem"; } @@ -46,11 +47,16 @@ public: Base::Vector3d getYAxis(); Base::Vector3d getZAxis(); - App::DocumentObject *getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const override; + App::DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth + ) const override; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_DATUMCS_H +#endif // PARTDESIGN_DATUMCS_H diff --git a/src/Mod/PartDesign/App/DatumLine.cpp b/src/Mod/PartDesign/App/DatumLine.cpp index e14818f904..b91adb8b9b 100644 --- a/src/Mod/PartDesign/App/DatumLine.cpp +++ b/src/Mod/PartDesign/App/DatumLine.cpp @@ -22,10 +22,9 @@ ***************************************************************************/ - -# include -# include -# include +#include +#include +#include #include "DatumLine.h" @@ -35,7 +34,7 @@ using namespace Attacher; // ============================================================================ -const char* Line::ResizeModeEnums[]= {"Automatic","Manual",nullptr}; +const char* Line::ResizeModeEnums[] = {"Automatic", "Manual", nullptr}; PROPERTY_SOURCE(PartDesign::Line, Part::Datum) @@ -45,17 +44,24 @@ Line::Line() // Since they are getting changed from within its view provider // their type is set to "Output" to avoid that they are marked as // touched all the time. - ADD_PROPERTY_TYPE(ResizeMode,(static_cast(0)), "Size", App::Prop_Output, "Automatic or manual resizing"); + ADD_PROPERTY_TYPE( + ResizeMode, + (static_cast(0)), + "Size", + App::Prop_Output, + "Automatic or manual resizing" + ); ResizeMode.setEnums(ResizeModeEnums); - ADD_PROPERTY_TYPE(Length,(20), "Size", App::Prop_Output, "Length of the line"); + ADD_PROPERTY_TYPE(Length, (20), "Size", App::Prop_Output, "Length of the line"); Length.setReadOnly(true); this->setAttacher(new AttachEngineLine); - // Create a shape, which will be used by the Sketcher. Them main function is to avoid a dependency of - // Sketcher on the PartDesign module - BRepBuilderAPI_MakeEdge builder(gp_Lin(gp_Pnt(0,0,0), gp_Dir(0,0,1))); - if (!builder.IsDone()) + // Create a shape, which will be used by the Sketcher. Them main function is to avoid a + // dependency of Sketcher on the PartDesign module + BRepBuilderAPI_MakeEdge builder(gp_Lin(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))); + if (!builder.IsDone()) { return; + } TopoDS_Shape myShape = builder.Shape(); myShape.Infinite(Standard_True); Shape.setValue(myShape); @@ -69,11 +75,11 @@ Base::Vector3d Line::getDirection() const { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d dir; - rot.multVec(Base::Vector3d(0,0,1), dir); + rot.multVec(Base::Vector3d(0, 0, 1), dir); return dir; } -void Line::onChanged(const App::Property *prop) +void Line::onChanged(const App::Property* prop) { if (prop == &ResizeMode) { if (ResizeMode.getValue() == 0) { diff --git a/src/Mod/PartDesign/App/DatumLine.h b/src/Mod/PartDesign/App/DatumLine.h index 7e5af1b0c5..609180a5f3 100644 --- a/src/Mod/PartDesign/App/DatumLine.h +++ b/src/Mod/PartDesign/App/DatumLine.h @@ -32,7 +32,7 @@ namespace PartDesign { -class PartDesignExport Line : public Part::Datum +class PartDesignExport Line: public Part::Datum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Line); @@ -42,9 +42,10 @@ public: App::PropertyEnumeration ResizeMode; App::PropertyLength Length; - void onChanged(const App::Property *prop) override; + void onChanged(const App::Property* prop) override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderDatumLine"; } @@ -54,7 +55,7 @@ private: static const char* ResizeModeEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_DATUMLINE_H +#endif // PARTDESIGN_DATUMLINE_H diff --git a/src/Mod/PartDesign/App/DatumPlane.cpp b/src/Mod/PartDesign/App/DatumPlane.cpp index 183a41024a..5b284fea3c 100644 --- a/src/Mod/PartDesign/App/DatumPlane.cpp +++ b/src/Mod/PartDesign/App/DatumPlane.cpp @@ -22,10 +22,9 @@ ***************************************************************************/ - -# include -# include -# include +#include +#include +#include #include "DatumPlane.h" @@ -35,7 +34,7 @@ using namespace Attacher; // ============================================================================ -const char* Plane::ResizeModeEnums[]= {"Automatic","Manual",nullptr}; +const char* Plane::ResizeModeEnums[] = {"Automatic", "Manual", nullptr}; PROPERTY_SOURCE(PartDesign::Plane, Part::Datum) @@ -45,20 +44,27 @@ Plane::Plane() // Since they are getting changed from within its view provider // their type is set to "Output" to avoid that they are marked as // touched all the time. - ADD_PROPERTY_TYPE(ResizeMode,(static_cast(0)), "Size", App::Prop_Output, "Automatic or manual resizing"); + ADD_PROPERTY_TYPE( + ResizeMode, + (static_cast(0)), + "Size", + App::Prop_Output, + "Automatic or manual resizing" + ); ResizeMode.setEnums(ResizeModeEnums); - ADD_PROPERTY_TYPE(Length,(20), "Size", App::Prop_Output, "Length of the plane"); - ADD_PROPERTY_TYPE(Width,(20), "Size", App::Prop_Output, "Width of the plane"); + ADD_PROPERTY_TYPE(Length, (20), "Size", App::Prop_Output, "Length of the plane"); + ADD_PROPERTY_TYPE(Width, (20), "Size", App::Prop_Output, "Width of the plane"); Length.setReadOnly(true); Width.setReadOnly(true); this->setAttacher(new AttachEnginePlane); - // Create a shape, which will be used by the Sketcher. Them main function is to avoid a dependency of - // Sketcher on the PartDesign module - BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0,0,0), gp_Dir(0,0,1))); - if (!builder.IsDone()) + // Create a shape, which will be used by the Sketcher. Them main function is to avoid a + // dependency of Sketcher on the PartDesign module + BRepBuilderAPI_MakeFace builder(gp_Pln(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1))); + if (!builder.IsDone()) { return; + } TopoDS_Shape myShape = builder.Shape(); myShape.Infinite(Standard_True); Shape.setValue(myShape); @@ -70,7 +76,7 @@ Base::Vector3d Plane::getNormal() { Base::Rotation rot = Placement.getValue().getRotation(); Base::Vector3d normal; - rot.multVec(Base::Vector3d(0,0,1), normal); + rot.multVec(Base::Vector3d(0, 0, 1), normal); return normal; } @@ -83,7 +89,7 @@ void Plane::Restore(Base::XMLReader& reader) Datum::Restore(reader); } -void Plane::onChanged(const App::Property *prop) +void Plane::onChanged(const App::Property* prop) { if (prop == &ResizeMode) { if (ResizeMode.getValue() == 0) { diff --git a/src/Mod/PartDesign/App/DatumPlane.h b/src/Mod/PartDesign/App/DatumPlane.h index 0b6e83f35f..7f0eef6195 100644 --- a/src/Mod/PartDesign/App/DatumPlane.h +++ b/src/Mod/PartDesign/App/DatumPlane.h @@ -32,7 +32,7 @@ namespace PartDesign { -class PartDesignExport Plane : public Part::Datum +class PartDesignExport Plane: public Part::Datum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Plane); @@ -44,8 +44,9 @@ public: App::PropertyLength Length; App::PropertyLength Width; - void onChanged(const App::Property *prop) override; - const char* getViewProviderName() const override { + void onChanged(const App::Property* prop) override; + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderDatumPlane"; } @@ -58,7 +59,7 @@ private: static const char* ResizeModeEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_DATUMPLANE_H +#endif // PARTDESIGN_DATUMPLANE_H diff --git a/src/Mod/PartDesign/App/DatumPoint.cpp b/src/Mod/PartDesign/App/DatumPoint.cpp index 68dbdbc3f6..6fa9dce112 100644 --- a/src/Mod/PartDesign/App/DatumPoint.cpp +++ b/src/Mod/PartDesign/App/DatumPoint.cpp @@ -22,8 +22,8 @@ ***************************************************************************/ -# include -# include +#include +#include #include "DatumPoint.h" @@ -45,10 +45,10 @@ Point::~Point() = default; void Point::onChanged(const App::Property* prop) { - if(prop == &(this->Shape)){ - //fix for #0002758 Datum point moves to (0,0,0) when reopening the file. - //bypass Part::Feature's onChanged, which may alter Placement property to match shape's placement. - //This is to prevent loss of correct Placement when restoring Shape from file. + if (prop == &(this->Shape)) { + // fix for #0002758 Datum point moves to (0,0,0) when reopening the file. + // bypass Part::Feature's onChanged, which may alter Placement property to match shape's + // placement. This is to prevent loss of correct Placement when restoring Shape from file. App::GeoFeature::onChanged(prop); return; } @@ -57,19 +57,20 @@ void Point::onChanged(const App::Property* prop) void Point::onDocumentRestored() { - //fix for #0002758 Datum point moves to (0,0,0) when reopening the file. - //recreate shape, as the restored one has old Placement burned into it. + // fix for #0002758 Datum point moves to (0,0,0) when reopening the file. + // recreate shape, as the restored one has old Placement burned into it. this->makeShape(); Superclass::onDocumentRestored(); } void Point::makeShape() { - // Create a shape, which will be used by Sketcher, attachables, and whatever. Them main function is to avoid a dependency of - // Sketcher on the PartDesign module - BRepBuilderAPI_MakeVertex builder(gp_Pnt(0,0,0)); - if (!builder.IsDone()) + // Create a shape, which will be used by Sketcher, attachables, and whatever. Them main function + // is to avoid a dependency of Sketcher on the PartDesign module + BRepBuilderAPI_MakeVertex builder(gp_Pnt(0, 0, 0)); + if (!builder.IsDone()) { return; + } Part::TopoShape tshape(builder.Shape()); tshape.setPlacement(this->Placement.getValue()); Shape.setValue(tshape); diff --git a/src/Mod/PartDesign/App/DatumPoint.h b/src/Mod/PartDesign/App/DatumPoint.h index 311b56fa44..33dcad1907 100644 --- a/src/Mod/PartDesign/App/DatumPoint.h +++ b/src/Mod/PartDesign/App/DatumPoint.h @@ -31,7 +31,7 @@ namespace PartDesign { -class PartDesignExport Point : public Part::Datum +class PartDesignExport Point: public Part::Datum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Point); @@ -39,7 +39,8 @@ public: Point(); ~Point() override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderDatumPoint"; } @@ -53,10 +54,9 @@ protected: private: void makeShape(); - }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_DATUMPOINT_H +#endif // PARTDESIGN_DATUMPOINT_H diff --git a/src/Mod/PartDesign/App/Feature.cpp b/src/Mod/PartDesign/App/Feature.cpp index 322ea7a568..c90b1e1a47 100644 --- a/src/Mod/PartDesign/App/Feature.cpp +++ b/src/Mod/PartDesign/App/Feature.cpp @@ -21,13 +21,13 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include "App/Datums.h" @@ -47,25 +47,35 @@ FC_LOG_LEVEL_INIT("PartDesign", true, true) -namespace PartDesign { +namespace PartDesign +{ bool getPDRefineModelParameter() { - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/PartDesign"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/PartDesign"); return hGrp->GetBool("RefineModel", true); } // ------------------------------------------------------------------------------------------------ -PROPERTY_SOURCE(PartDesign::Feature,Part::Feature) +PROPERTY_SOURCE(PartDesign::Feature, Part::Feature) Feature::Feature() { - ADD_PROPERTY(BaseFeature,(nullptr)); - ADD_PROPERTY_TYPE(_Body,(nullptr),"Base",(App::PropertyType)( - App::Prop_ReadOnly|App::Prop_Hidden|App::Prop_Output|App::Prop_Transient),0); - ADD_PROPERTY(SuppressedShape,(TopoShape())); + ADD_PROPERTY(BaseFeature, (nullptr)); + ADD_PROPERTY_TYPE( + _Body, + (nullptr), + "Base", + (App::PropertyType)(App::Prop_ReadOnly | App::Prop_Hidden | App::Prop_Output + | App::Prop_Transient), + 0 + ); + ADD_PROPERTY(SuppressedShape, (TopoShape())); Placement.setStatus(App::Property::Hidden, true); BaseFeature.setStatus(App::Property::Hidden, true); @@ -133,16 +143,16 @@ void Feature::updateSuppressedShape() TopoShape shape = Shape.getShape(); shape.setPlacement(Base::Placement()); std::vector generated; - if(!shape.isNull()) { + if (!shape.isNull()) { unsigned count = shape.countSubShapes(TopAbs_FACE); - for(unsigned i=1; i<=count; ++i) { - Data::MappedName mapped = shape.getMappedName( - Data::IndexedName::fromConst("Face", i)); - if(mapped && shape.isElementGenerated(mapped)) + for (unsigned i = 1; i <= count; ++i) { + Data::MappedName mapped = shape.getMappedName(Data::IndexedName::fromConst("Face", i)); + if (mapped && shape.isElementGenerated(mapped)) { generated.push_back(shape.getSubTopoShape(TopAbs_FACE, i)); + } } } - if(!generated.empty()) { + if (!generated.empty()) { res.makeElementCompound(generated); res.setPlacement(Placement.getValue()); } @@ -151,8 +161,9 @@ void Feature::updateSuppressedShape() short Feature::mustExecute() const { - if (BaseFeature.isTouched()) + if (BaseFeature.isTouched()) { return 1; + } return Part::Feature::mustExecute(); } @@ -177,12 +188,10 @@ TopoShape Feature::getSolid(const TopoShape& shape) const return shape; } -void Feature::onChanged(const App::Property *prop) +void Feature::onChanged(const App::Property* prop) { - if (!this->isRestoring() - && this->getDocument() - && !this->getDocument()->isPerformingTransaction() - ) { + if (!this->isRestoring() && this->getDocument() + && !this->getDocument()->isPerformingTransaction()) { if (prop == &Visibility || prop == &BaseFeature) { auto body = Body::findBodyOf(this); if (body) { @@ -191,22 +200,25 @@ void Feature::onChanged(const App::Property *prop) body->Group.find(this->getNameInDocument(), &idx); int baseidx = -1; body->Group.find(BaseFeature.getValue()->getNameInDocument(), &idx); - if (idx >= 0 && baseidx >= 0 && baseidx+1 != idx) + if (idx >= 0 && baseidx >= 0 && baseidx + 1 != idx) { body->insertObject(BaseFeature.getValue(), this); + } } } - } else if (prop == &ShapeMaterial) { + } + else if (prop == &ShapeMaterial) { auto body = Body::findBodyOf(this); if (body) { - if (body->ShapeMaterial.getValue().getUUID() - != ShapeMaterial.getValue().getUUID()) { + if (body->ShapeMaterial.getValue().getUUID() != ShapeMaterial.getValue().getUUID()) { body->ShapeMaterial.setValue(ShapeMaterial.getValue()); } } - } else if (prop == &Suppressed){ + } + else if (prop == &Suppressed) { if (Suppressed.getValue()) { SuppressedPlacement = Placement.getValue(); - } else { + } + else { Placement.setValue(SuppressedPlacement); SuppressedPlacement = Base::Placement(); } @@ -218,10 +230,11 @@ void Feature::onChanged(const App::Property *prop) int Feature::countSolids(const TopoDS_Shape& shape, TopAbs_ShapeEnum type) { int result = 0; - if (shape.IsNull()) + if (shape.IsNull()) { return result; + } TopExp_Explorer xp; - xp.Init(shape,type); + xp.Init(shape, type); for (; xp.More(); xp.Next()) { result++; } @@ -259,8 +272,9 @@ const gp_Pnt Feature::getPointFromFace(const TopoDS_Face& f) if (!f.Infinite()) { TopExp_Explorer exp; exp.Init(f, TopAbs_VERTEX); - if (exp.More()) + if (exp.More()) { return BRep_Tool::Pnt(TopoDS::Vertex(exp.Current())); + } // Else try the other method } @@ -269,19 +283,21 @@ const gp_Pnt Feature::getPointFromFace(const TopoDS_Face& f) throw Base::NotImplementedError("getPointFromFace(): Not implemented yet for this case"); } -Part::Feature* Feature::getBaseObject(bool silent) const { +Part::Feature* Feature::getBaseObject(bool silent) const +{ App::DocumentObject* BaseLink = BaseFeature.getValue(); Part::Feature* BaseObject = nullptr; - const char *err = nullptr; + const char* err = nullptr; if (BaseLink) { if (BaseLink->isDerivedFrom()) { BaseObject = static_cast(BaseLink); } if (!BaseObject) { - err = "No base feature linked"; + err = "No base feature linked"; } - } else { + } + else { err = "Base property not set"; } @@ -293,24 +309,27 @@ Part::Feature* Feature::getBaseObject(bool silent) const { return BaseObject; } -const TopoDS_Shape& Feature::getBaseShape() const { +const TopoDS_Shape& Feature::getBaseShape() const +{ const Part::Feature* BaseObject = getBaseObject(); - if (!BaseObject) + if (!BaseObject) { throw Base::ValueError("Base feature's shape is not defined"); + } - if (BaseObject->isDerivedFrom()|| - BaseObject->isDerivedFrom()) - { + if (BaseObject->isDerivedFrom() + || BaseObject->isDerivedFrom()) { throw Base::ValueError("Base shape of shape binder cannot be used"); } const TopoDS_Shape& result = BaseObject->Shape.getValue(); - if (result.IsNull()) + if (result.IsNull()) { throw Base::ValueError("Base feature's shape is invalid"); - TopExp_Explorer xp (result, TopAbs_SOLID); - if (!xp.More()) + } + TopExp_Explorer xp(result, TopAbs_SOLID); + if (!xp.More()) { throw Base::ValueError("Base feature's shape is not a solid"); + } return result; } @@ -356,17 +375,17 @@ Part::TopoShape Feature::getBaseTopoShape(bool silent) const return result; } -void Feature::getGeneratedShapes(std::vector& faces, - std::vector& edges, - std::vector& vertices) const +void Feature::getGeneratedShapes( + std::vector& faces, + std::vector& edges, + std::vector& vertices +) const { - static const auto addAllSubShapesToSet = []( - const Part::TopoShape& shape, - const Part::TopoShape& face, - TopAbs_ShapeEnum type, - std::set& set - ) { - for (auto &subShape : face.getSubShapes(type)) { + static const auto addAllSubShapesToSet = [](const Part::TopoShape& shape, + const Part::TopoShape& face, + TopAbs_ShapeEnum type, + std::set& set) { + for (auto& subShape : face.getSubShapes(type)) { if (int subShapeId = shape.findShape(subShape); subShapeId > 0) { set.insert(subShapeId); } @@ -403,38 +422,39 @@ void Feature::updatePreviewShape() PyObject* Feature::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePy(this),true); + PythonObject = Py::Object(new FeaturePy(this), true); } return Py::new_reference_to(PythonObject); } bool Feature::isDatum(const App::DocumentObject* feature) { - return feature->isDerivedFrom() || - feature->isDerivedFrom(); + return feature->isDerivedFrom() || feature->isDerivedFrom(); } gp_Pln Feature::makePlnFromPlane(const App::DocumentObject* obj) { const App::GeoFeature* plane = static_cast(obj); - if (!plane) + if (!plane) { throw Base::ValueError("Feature: Null object"); + } Base::Vector3d pos = plane->Placement.getValue().getPosition(); Base::Rotation rot = plane->Placement.getValue().getRotation(); - Base::Vector3d normal(0,0,1); + Base::Vector3d normal(0, 0, 1); rot.multVec(normal, normal); - return gp_Pln(gp_Pnt(pos.x,pos.y,pos.z), gp_Dir(normal.x,normal.y,normal.z)); + return gp_Pln(gp_Pnt(pos.x, pos.y, pos.z), gp_Dir(normal.x, normal.y, normal.z)); } // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. TopoDS_Shape Feature::makeShapeFromPlane(const App::DocumentObject* obj) { BRepBuilderAPI_MakeFace builder(makePlnFromPlane(obj)); - if (!builder.IsDone()) + if (!builder.IsDone()) { throw Base::CADKernelError("Feature: Could not create shape from base plane"); + } return builder.Shape(); } @@ -449,29 +469,36 @@ TopoShape Feature::makeTopoShapeFromPlane(const App::DocumentObject* obj) return TopoShape(obj->getID(), nullptr, builder.Shape()); } -Body* Feature::getFeatureBody() const { +Body* Feature::getFeatureBody() const +{ auto body = freecad_cast(_Body.getValue()); - if(body) + if (body) { return body; + } auto list = getInList(); for (auto in : list) { - if(in->isDerivedFrom() && //is Body? - static_cast(in)->hasObject(this)) { //is part of this Body? + if (in->isDerivedFrom() && // is Body? + static_cast(in)->hasObject(this)) { // is part of this Body? - return static_cast(in); + return static_cast(in); } } return nullptr; } -App::DocumentObject *Feature::getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const +App::DocumentObject* Feature::getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth +) const { if (subname && subname != Data::findElementName(subname)) { - const char * dot = strchr(subname,'.'); + const char* dot = strchr(subname, '.'); if (dot) { auto body = PartDesign::Body::findBodyOf(this); if (body) { @@ -491,12 +518,14 @@ App::DocumentObject *Feature::getSubObject(const char *subname, // transform' is requested, we need to actively apply // an inverse transform. _mat = Placement.getValue().inverse().toMatrix(); - if (pmat) + if (pmat) { *pmat *= _mat; - else + } + else { pmat = &_mat; + } } - return feat->getSubObject(dot+1, pyObj, pmat, true, depth+1); + return feat->getSubObject(dot + 1, pyObj, pmat, true, depth + 1); } } } @@ -505,18 +534,23 @@ App::DocumentObject *Feature::getSubObject(const char *subname, } -}//namespace PartDesign +} // namespace PartDesign -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(PartDesign::FeaturePython, PartDesign::Feature) -template<> const char* PartDesign::FeaturePython::getViewProviderName() const { +template<> +const char* PartDesign::FeaturePython::getViewProviderName() const +{ return "PartDesignGui::ViewProviderPython"; } -template<> PyObject* PartDesign::FeaturePython::getPyObject() { +template<> +PyObject* PartDesign::FeaturePython::getPyObject() +{ if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePythonPyT(this),true); + PythonObject = Py::Object(new FeaturePythonPyT(this), true); } return Py::new_reference_to(PythonObject); } @@ -524,5 +558,4 @@ template<> PyObject* PartDesign::FeaturePython::getPyObject() { // explicit template instantiation template class PartDesignExport FeaturePythonT; -} - +} // namespace App diff --git a/src/Mod/PartDesign/App/Feature.h b/src/Mod/PartDesign/App/Feature.h index 995ed4a3ff..bcb5441036 100644 --- a/src/Mod/PartDesign/App/Feature.h +++ b/src/Mod/PartDesign/App/Feature.h @@ -42,21 +42,27 @@ using TopoShape = Part::TopoShape; class Body; - /** PartDesign feature +/** PartDesign feature * Base class of all PartDesign features. * This kind of features only produce solids or fail. */ -class PartDesignExport Feature : public Part::Feature, public App::SuppressibleExtension, public Part::PreviewExtension +class PartDesignExport Feature: public Part::Feature, + public App::SuppressibleExtension, + public Part::PreviewExtension { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Feature); public: Feature(); - enum SingleSolidRuleMode { Disabled = 0, Enforced = 1 }; + enum SingleSolidRuleMode + { + Disabled = 0, + Enforced = 1 + }; /// Base feature which this feature will be fused into or cut out of - App::PropertyLink BaseFeature; + App::PropertyLink BaseFeature; App::PropertyLinkHidden _Body; /// Keep a copy of suppressed shapes so that we can restore them (and maybe display them) @@ -81,33 +87,40 @@ public: * silently return a nullptr, otherwise throw Base::Exception. * Default is false. */ - virtual Part::Feature* getBaseObject(bool silent=false) const; + virtual Part::Feature* getBaseObject(bool silent = false) const; /// Returns the BaseFeature property's shape (if any) virtual const TopoDS_Shape& getBaseShape() const; /// Returns the BaseFeature property's TopoShape (if any) - Part::TopoShape getBaseTopoShape(bool silent=false) const; + Part::TopoShape getBaseTopoShape(bool silent = false) const; // Fills up information about which sub-shapes were generated by the feature - virtual void getGeneratedShapes(std::vector& faces, - std::vector& edges, - std::vector& vertices) const; + virtual void getGeneratedShapes( + std::vector& faces, + std::vector& edges, + std::vector& vertices + ) const; virtual void updatePreviewShape(); PyObject* getPyObject() override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProvider"; } void onChanged(const App::Property* prop) override; - App::DocumentObject *getSubObject(const char *subname, - PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const override; + App::DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* pmat, + bool transform, + int depth + ) const override; protected: - /** * Get a solid of the given shape. If no solid is found an exception is raised. */ @@ -138,7 +151,7 @@ protected: using FeaturePython = App::FeaturePythonT; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_Feature_H +#endif // PARTDESIGN_Feature_H diff --git a/src/Mod/PartDesign/App/FeatureAddSub.cpp b/src/Mod/PartDesign/App/FeatureAddSub.cpp index aedc29c490..385165d120 100644 --- a/src/Mod/PartDesign/App/FeatureAddSub.cpp +++ b/src/Mod/PartDesign/App/FeatureAddSub.cpp @@ -21,7 +21,7 @@ ***************************************************************************/ -# include +#include #include @@ -36,7 +36,8 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ extern bool getPDRefineModelParameter(); @@ -59,8 +60,9 @@ FeatureAddSub::Type FeatureAddSub::getAddSubType() short FeatureAddSub::mustExecute() const { - if (Refine.isTouched()) + if (Refine.isTouched()) { return 1; + } return PartDesign::Feature::mustExecute(); } @@ -79,9 +81,8 @@ void FeatureAddSub::updatePreviewShape() const auto notifyWarning = [](const QString& message) { Base::Console().translatedUserWarning( "Preview", - tr("Failure while computing removed volume preview: %1") - .arg(message) - .toUtf8()); + tr("Failure while computing removed volume preview: %1").arg(message).toUtf8() + ); }; // for subtractive shapes we want to also showcase removed volume, not only the tool @@ -90,15 +91,20 @@ void FeatureAddSub::updatePreviewShape() if (const TopoShape& addSubShape = AddSubShape.getShape(); !addSubShape.isEmpty()) { try { - base.makeElementBoolean(Part::OpCodes::Common, { base, addSubShape }); - } catch (Standard_Failure& e) { + base.makeElementBoolean(Part::OpCodes::Common, {base, addSubShape}); + } + catch (Standard_Failure& e) { notifyWarning(QString::fromUtf8(e.GetMessageString())); - } catch (Base::Exception& e) { + } + catch (Base::Exception& e) { notifyWarning(QString::fromStdString(e.getMessage())); } if (base.isEmpty()) { - notifyWarning(tr("Resulting shape is empty. That may indicate that no material will be removed or a problem with the model.")); + notifyWarning( + tr("Resulting shape is empty. That may indicate that no material will be " + "removed or a problem with the model.") + ); } PreviewShape.setValue(base); @@ -111,16 +117,21 @@ void FeatureAddSub::updatePreviewShape() } // namespace PartDesign -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(PartDesign::FeatureAddSubPython, PartDesign::FeatureAddSub) -template<> const char* PartDesign::FeatureAddSubPython::getViewProviderName() const { +template<> +const char* PartDesign::FeatureAddSubPython::getViewProviderName() const +{ return "PartDesignGui::ViewProviderPython"; } -template<> PyObject* PartDesign::FeatureAddSubPython::getPyObject() { +template<> +PyObject* PartDesign::FeatureAddSubPython::getPyObject() +{ if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePythonPyT(this),true); + PythonObject = Py::Object(new FeaturePythonPyT(this), true); } return Py::new_reference_to(PythonObject); } @@ -128,10 +139,11 @@ template<> PyObject* PartDesign::FeatureAddSubPython::getPyObject() { // explicit template instantiation template class PartDesignExport FeaturePythonT; -} +} // namespace App -namespace PartDesign { +namespace PartDesign +{ PROPERTY_SOURCE(PartDesign::FeatureAdditivePython, PartDesign::FeatureAddSubPython) @@ -152,4 +164,4 @@ FeatureSubtractivePython::FeatureSubtractivePython() FeatureSubtractivePython::~FeatureSubtractivePython() = default; -} +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureAddSub.h b/src/Mod/PartDesign/App/FeatureAddSub.h index b912dd07c3..d1be0f67d0 100644 --- a/src/Mod/PartDesign/App/FeatureAddSub.h +++ b/src/Mod/PartDesign/App/FeatureAddSub.h @@ -32,38 +32,39 @@ namespace PartDesign { -class PartDesignExport FeatureAddSub : public PartDesign::FeatureRefine +class PartDesignExport FeatureAddSub: public PartDesign::FeatureRefine { Q_DECLARE_TR_FUNCTIONS(PartDesign::FeatureAddSub) PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureAddSub); public: - enum Type { + enum Type + { Additive = 0, Subtractive }; FeatureAddSub(); - void onChanged(const App::Property *) override; + void onChanged(const App::Property*) override; Type getAddSubType(); short mustExecute() const override; - virtual void getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShape); + virtual void getAddSubShape(Part::TopoShape& addShape, Part::TopoShape& subShape); void updatePreviewShape() override; - Part::PropertyPartShape AddSubShape; + Part::PropertyPartShape AddSubShape; protected: - Type addSubType{Additive}; + Type addSubType {Additive}; }; using FeatureAddSubPython = App::FeaturePythonT; -class FeatureAdditivePython : public FeatureAddSubPython +class FeatureAdditivePython: public FeatureAddSubPython { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureAdditivePython); @@ -72,7 +73,7 @@ public: ~FeatureAdditivePython() override; }; -class FeatureSubtractivePython : public FeatureAddSubPython +class FeatureSubtractivePython: public FeatureAddSubPython { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureSubtractivePython); @@ -81,7 +82,7 @@ public: ~FeatureSubtractivePython() override; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeatureAdditive_H +#endif // PARTDESIGN_FeatureAdditive_H diff --git a/src/Mod/PartDesign/App/FeatureBase.cpp b/src/Mod/PartDesign/App/FeatureBase.cpp index e6c063a6ff..1098b6ed8e 100644 --- a/src/Mod/PartDesign/App/FeatureBase.cpp +++ b/src/Mod/PartDesign/App/FeatureBase.cpp @@ -21,7 +21,7 @@ ***************************************************************************/ -# include +#include #include @@ -29,10 +29,11 @@ #include "FeatureBase.h" #include "FeaturePy.h" -namespace PartDesign { +namespace PartDesign +{ -PROPERTY_SOURCE(PartDesign::FeatureBase,PartDesign::Feature) +PROPERTY_SOURCE(PartDesign::FeatureBase, PartDesign::Feature) FeatureBase::FeatureBase() { @@ -40,15 +41,18 @@ FeatureBase::FeatureBase() BaseFeature.setStatus(App::Property::Hidden, false); } -Part::Feature* FeatureBase::getBaseObject(bool) const { +Part::Feature* FeatureBase::getBaseObject(bool) const +{ return nullptr; } -short int FeatureBase::mustExecute() const { +short int FeatureBase::mustExecute() const +{ - if(BaseFeature.isTouched()) + if (BaseFeature.isTouched()) { return 1; + } return PartDesign::Feature::mustExecute(); } @@ -59,18 +63,24 @@ App::DocumentObjectExecReturn* FeatureBase::execute() if (!BaseFeature.getValue()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "BaseFeature link is not set")); + QT_TRANSLATE_NOOP("Exception", "BaseFeature link is not set") + ); } if (!BaseFeature.getValue()->isDerivedFrom()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "BaseFeature must be a Part::Feature")); + QT_TRANSLATE_NOOP("Exception", "BaseFeature must be a Part::Feature") + ); } - auto shape = Part::Feature::getTopoShape(BaseFeature.getValue(), Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + auto shape = Part::Feature::getTopoShape( + BaseFeature.getValue(), + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); if (shape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "BaseFeature has an empty shape")); + QT_TRANSLATE_NOOP("Exception", "BaseFeature has an empty shape") + ); } Shape.setValue(shape); @@ -81,15 +91,15 @@ App::DocumentObjectExecReturn* FeatureBase::execute() void FeatureBase::trySetBaseFeatureOfBody() { if (auto body = getFeatureBody()) { - if (BaseFeature.getValue() - && body->BaseFeature.getValue() - && body->BaseFeature.getValue() != BaseFeature.getValue()) { + if (BaseFeature.getValue() && body->BaseFeature.getValue() + && body->BaseFeature.getValue() != BaseFeature.getValue()) { body->BaseFeature.setValue(BaseFeature.getValue()); } } } -void FeatureBase::onChanged(const App::Property* prop) { +void FeatureBase::onChanged(const App::Property* prop) +{ // the BaseFeature property should track the Body BaseFeature and vice-versa if (prop == &BaseFeature) { @@ -103,10 +113,10 @@ void FeatureBase::onDocumentRestored() { // if the base is not part of a body then show its placement property again auto body = getFeatureBody(); - if (!body) + if (!body) { Placement.setStatus(App::Property::Hidden, false); + } PartDesign::Feature::onDocumentRestored(); } -}//namespace PartDesign - +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureBase.h b/src/Mod/PartDesign/App/FeatureBase.h index 4be140d44d..9d456a6ec8 100644 --- a/src/Mod/PartDesign/App/FeatureBase.h +++ b/src/Mod/PartDesign/App/FeatureBase.h @@ -30,7 +30,7 @@ namespace PartDesign { -class PartDesignExport FeatureBase : public PartDesign::Feature +class PartDesignExport FeatureBase: public PartDesign::Feature { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureBase); @@ -39,9 +39,10 @@ public: short int mustExecute() const override; - Part::Feature* getBaseObject(bool silent=false) const override; + Part::Feature* getBaseObject(bool silent = false) const override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderBase"; } @@ -53,7 +54,7 @@ private: void trySetBaseFeatureOfBody(); }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeatureBase_H +#endif // PARTDESIGN_FeatureBase_H diff --git a/src/Mod/PartDesign/App/FeatureBoolean.cpp b/src/Mod/PartDesign/App/FeatureBoolean.cpp index cfcbd483d4..85708c5d12 100644 --- a/src/Mod/PartDesign/App/FeatureBoolean.cpp +++ b/src/Mod/PartDesign/App/FeatureBoolean.cpp @@ -21,10 +21,10 @@ ******************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -38,20 +38,27 @@ FC_LOG_LEVEL_INIT("PartDesign", true, true); using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ extern bool getPDRefineModelParameter(); PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesign::Boolean, PartDesign::Feature) -const char* Boolean::TypeEnums[]= {"Fuse","Cut","Common",nullptr}; +const char* Boolean::TypeEnums[] = {"Fuse", "Cut", "Common", nullptr}; Boolean::Boolean() { - ADD_PROPERTY(Type,((long)0)); + ADD_PROPERTY(Type, ((long)0)); Type.setEnums(TypeEnums); - ADD_PROPERTY_TYPE(UsePlacement,(0),"Part Design",(App::PropertyType)(App::Prop_None),"Apply the placement of the second ( tool ) object"); + ADD_PROPERTY_TYPE( + UsePlacement, + (0), + "Part Design", + (App::PropertyType)(App::Prop_None), + "Apply the placement of the second ( tool ) object" + ); this->UsePlacement.setValue(false); App::GeoFeatureGroupExtension::initExtension(this); @@ -59,12 +66,13 @@ Boolean::Boolean() short Boolean::mustExecute() const { - if (Group.isTouched()) + if (Group.isTouched()) { return 1; + } return PartDesign::Feature::mustExecute(); } -App::DocumentObjectExecReturn *Boolean::execute() +App::DocumentObjectExecReturn* Boolean::execute() { // Get the operation type std::string type = Type.getValueAsString(); @@ -73,92 +81,131 @@ App::DocumentObjectExecReturn *Boolean::execute() const Part::Feature* baseFeature = this->getBaseObject(/* silent = */ true); if (!baseFeature && type == "Cut") { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Cannot do boolean cut without BaseFeature")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Cannot do boolean cut without BaseFeature") + ); } std::vector tools = Group.getValues(); - if (tools.empty()) + if (tools.empty()) { return App::DocumentObject::StdReturn; + } // Get the base shape to operate on Part::TopoShape baseTopShape; - if(baseFeature) + if (baseFeature) { baseTopShape = baseFeature->Shape.getShape(); + } else { auto feature = tools.back(); - if(!feature->isDerivedFrom()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Cannot do boolean with anything but Part::Feature and its derivatives")); + if (!feature->isDerivedFrom()) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Cannot do boolean with anything but Part::Feature and its derivatives" + )); + } baseTopShape = static_cast(feature)->Shape.getShape(); tools.pop_back(); } - if (baseTopShape.getShape().IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Cannot do boolean operation with invalid base shape")); + if (baseTopShape.getShape().IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Cannot do boolean operation with invalid base shape") + ); + } - //get the body this boolean feature belongs to + // get the body this boolean feature belongs to Part::BodyBase* baseBody = Part::BodyBase::findBodyOf(this); - if(!baseBody) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Cannot do boolean on feature which is not in a body")); + if (!baseBody) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Cannot do boolean on feature which is not in a body") + ); + } std::vector shapes; shapes.push_back(baseTopShape); - for(auto it=tools.begin(); itglobalPlacement().inverse(); - for (auto tool : tools) - { - if(!tool->isDerivedFrom()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Cannot do boolean with anything but Part::Feature and its derivatives")); + Base::Placement bodyPlacement = baseBody->globalPlacement().inverse(); + for (auto tool : tools) { + if (!tool->isDerivedFrom()) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Cannot do boolean with anything but Part::Feature and its derivatives" + )); + } Part::TopoShape toolShape = static_cast(tool)->Shape.getShape(); - if ( UsePlacement.getValue() ) + if (UsePlacement.getValue()) { toolShape.setPlacement(bodyPlacement * toolShape.getPlacement()); + } TopoDS_Shape shape = toolShape.getShape(); TopoDS_Shape boolOp; // Must not pass null shapes to the boolean operations - if (result.isNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Base shape is null")); + if (result.isNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Base shape is null") + ); + } - if (shape.IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Tool shape is null")); + if (shape.IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Tool shape is null") + ); + } - const char *op = nullptr; - if (type == "Fuse") + const char* op = nullptr; + if (type == "Fuse") { op = Part::OpCodes::Fuse; - else if(type == "Cut") + } + else if (type == "Cut") { op = Part::OpCodes::Cut; - else if(type == "Common") + } + else if (type == "Common") { op = Part::OpCodes::Common; + } // LinkStage3 defines these other types of Boolean operations. Removed for now pending // decision to bring them in or not. - // else if(type == "Compound") + // else if(type == "Compound") // op = Part::OpCodes::Compound; // else if(type == "Section") // op = Part::OpCodes::Section; - else - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Unsupported boolean operation")); + else { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Unsupported boolean operation") + ); + } try { result.makeElementBoolean(op, shapes); - } catch (Standard_Failure &e) { + } + catch (Standard_Failure& e) { FC_ERR("Boolean operation failed: " << e.GetMessageString()); - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Boolean operation failed")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Boolean operation failed") + ); } } result = refineShapeIfActive(result); if (!isSingleSolidRuleSatisfied(result.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } this->Shape.setValue(getSolid(result)); @@ -186,7 +233,8 @@ void Boolean::updatePreviewShape() std::vector shapes; for (auto& obj : Group.getValues()) { - auto shape = getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + auto shape + = getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); shape.setPlacement(shape.getPlacement().inverse() * globalPlacement()); shapes.push_back(shape); } @@ -201,7 +249,8 @@ void Boolean::updatePreviewShape() PreviewShape.setValue(Shape.getShape()); } -void Boolean::onChanged(const App::Property* prop) { +void Boolean::onChanged(const App::Property* prop) +{ if (strcmp(prop->getName(), "Group") == 0) { touch(); @@ -214,7 +263,7 @@ void Boolean::onChanged(const App::Property* prop) { Feature::onChanged(prop); } -void Boolean::handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) +void Boolean::handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, const char* PropName) { // The App::PropertyLinkList property was Bodies in the past Base::Type type = Base::Type::fromName(TypeName); @@ -224,6 +273,4 @@ void Boolean::handleChangedPropertyName(Base::XMLReader &reader, const char * Ty } } -} - - +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureBoolean.h b/src/Mod/PartDesign/App/FeatureBoolean.h index 686e312f5f..2da2fdf934 100644 --- a/src/Mod/PartDesign/App/FeatureBoolean.h +++ b/src/Mod/PartDesign/App/FeatureBoolean.h @@ -36,7 +36,7 @@ namespace PartDesign * Abstract superclass of all features that are created by transformation of another feature * Transformations are translation, rotation and mirroring */ -class PartDesignExport Boolean : public PartDesign::FeatureRefine, public App::GeoFeatureGroupExtension +class PartDesignExport Boolean: public PartDesign::FeatureRefine, public App::GeoFeatureGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(PartDesign::Boolean); @@ -44,33 +44,37 @@ public: Boolean(); /// The type of the boolean operation - App::PropertyEnumeration Type; + App::PropertyEnumeration Type; App::PropertyBool UsePlacement; - /** @name methods override feature */ + /** @name methods override feature */ //@{ /// Recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; void updatePreviewShape() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderBoolean"; } void onChanged(const App::Property* prop) override; //@} protected: - void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; private: static const char* TypeEnums[]; - }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeatureBoolean_H +#endif // PARTDESIGN_FeatureBoolean_H diff --git a/src/Mod/PartDesign/App/FeatureChamfer.cpp b/src/Mod/PartDesign/App/FeatureChamfer.cpp index c084c96678..47e6b5351e 100644 --- a/src/Mod/PartDesign/App/FeatureChamfer.cpp +++ b/src/Mod/PartDesign/App/FeatureChamfer.cpp @@ -20,18 +20,18 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -48,10 +48,16 @@ using namespace PartDesign; PROPERTY_SOURCE(PartDesign::Chamfer, PartDesign::DressUp) const char* ChamferTypeEnums[] = {"Equal distance", "Two distances", "Distance and Angle", nullptr}; -const App::PropertyQuantityConstraint::Constraints Chamfer::floatSize = {0.0, std::numeric_limits::max(), 0.1}; +const App::PropertyQuantityConstraint::Constraints Chamfer::floatSize + = {0.0, std::numeric_limits::max(), 0.1}; const App::PropertyAngle::Constraints Chamfer::floatAngle = {0.0, 180.0, 1.0}; -static App::DocumentObjectExecReturn *validateParameters(int chamferType, double size, double size2, double angle); +static App::DocumentObjectExecReturn* validateParameters( + int chamferType, + double size, + double size2, + double angle +); Chamfer::Chamfer() { @@ -71,9 +77,15 @@ Chamfer::Chamfer() Angle.setConstraints(&floatAngle); ADD_PROPERTY_TYPE(FlipDirection, (false), "Chamfer", App::Prop_None, "Flip direction"); - ADD_PROPERTY_TYPE(UseAllEdges, (false), "Chamfer", App::Prop_None, - "Chamfer all edges if true, else use only those edges in Base property.\n" - "If true, then this overrides any edge changes made to the Base property or in the dialog.\n"); + ADD_PROPERTY_TYPE( + UseAllEdges, + (false), + "Chamfer", + App::Prop_None, + "Chamfer all edges if true, else use only those edges in Base property.\n" + "If true, then this overrides any edge changes made to the Base property or in the " + "dialog.\n" + ); updateProperties(); } @@ -85,25 +97,28 @@ short Chamfer::mustExecute() const auto chamferType = ChamferType.getValue(); switch (chamferType) { - case 0: // "Equal distance" + case 0: // "Equal distance" touched = Size.isTouched() || ChamferType.isTouched(); break; - case 1: // "Two distances" + case 1: // "Two distances" touched = Size.isTouched() || ChamferType.isTouched() || Size2.isTouched(); break; - case 2: // "Distance and Angle" + case 2: // "Distance and Angle" touched = Size.isTouched() || ChamferType.isTouched() || Angle.isTouched(); break; } - if (Placement.isTouched() || touched) + if (Placement.isTouched() || touched) { return 1; + } return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Chamfer::execute() +App::DocumentObjectExecReturn* Chamfer::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } // NOTE: Normally the Base property and the BaseFeature property should point to the same object. // The only difference is that the Base property also stores the edges that are to be chamfered @@ -121,8 +136,7 @@ App::DocumentObjectExecReturn *Chamfer::execute() : getContinuousEdges(TopShape); if (edges.empty()) { - return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "No edges specified")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "No edges specified")); } const int chamferType = ChamferType.getValue(); const double size = Size.getValue(); @@ -137,38 +151,46 @@ App::DocumentObjectExecReturn *Chamfer::execute() this->positionByBaseFeature(); - if ( static_cast(chamferType) == Part::ChamferType::distanceAngle ) { + if (static_cast(chamferType) == Part::ChamferType::distanceAngle) { size2 = angle; } try { TopoShape shape(0); - shape.makeElementChamfer(TopShape, - edges, - static_cast(chamferType), - size, - size2, - nullptr, - flipDirection ? Part::Flip::flip : Part::Flip::none); + shape.makeElementChamfer( + TopShape, + edges, + static_cast(chamferType), + size, + size2, + nullptr, + flipDirection ? Part::Flip::flip : Part::Flip::none + ); if (shape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Failed to create chamfer")); + QT_TRANSLATE_NOOP("Exception", "Failed to create chamfer") + ); } TopTools_ListOfShape aLarg; aLarg.Append(TopShape.getShape()); if (!BRepAlgo::IsValid(aLarg, shape.getShape(), Standard_False, Standard_False)) { ShapeFix_ShapeTolerance aSFT; - aSFT.LimitTolerance(shape.getShape(), - Precision::Confusion(), - Precision::Confusion(), - TopAbs_SHAPE); + aSFT.LimitTolerance( + shape.getShape(), + Precision::Confusion(), + Precision::Confusion(), + TopAbs_SHAPE + ); } // store shape before refinement this->rawShape = shape; shape = refineShapeIfActive(shape); if (!isSingleSolidRuleSatisfied(shape.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } shape = getSolid(shape); @@ -180,15 +202,15 @@ App::DocumentObjectExecReturn *Chamfer::execute() } } -void Chamfer::Restore(Base::XMLReader &reader) +void Chamfer::Restore(Base::XMLReader& reader) { DressUp::Restore(reader); } -void Chamfer::handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) +void Chamfer::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { - if (prop && strcmp(TypeName,"App::PropertyFloatConstraint") == 0 && - strcmp(prop->getTypeId().getName(), "App::PropertyQuantityConstraint") == 0) { + if (prop && strcmp(TypeName, "App::PropertyFloatConstraint") == 0 + && strcmp(prop->getTypeId().getName(), "App::PropertyQuantityConstraint") == 0) { App::PropertyFloatConstraint p; p.Restore(reader); static_cast(prop)->setValue(p.getValue()); @@ -211,50 +233,59 @@ void Chamfer::updateProperties() { auto chamferType = ChamferType.getValue(); - auto disableproperty = [](App::Property * prop, bool on) { + auto disableproperty = [](App::Property* prop, bool on) { prop->setStatus(App::Property::ReadOnly, on); }; switch (chamferType) { - case 0: // "Equal distance" - disableproperty(&this->Angle, true); - disableproperty(&this->Size2, true); - break; - case 1: // "Two distances" - disableproperty(&this->Angle, true); - disableproperty(&this->Size2, false); - break; - case 2: // "Distance and Angle" - disableproperty(&this->Angle, false); - disableproperty(&this->Size2, true); - break; + case 0: // "Equal distance" + disableproperty(&this->Angle, true); + disableproperty(&this->Size2, true); + break; + case 1: // "Two distances" + disableproperty(&this->Angle, true); + disableproperty(&this->Size2, false); + break; + case 2: // "Distance and Angle" + disableproperty(&this->Angle, false); + disableproperty(&this->Size2, true); + break; } } -static App::DocumentObjectExecReturn *validateParameters(int chamferType, double size, double size2, double angle) +static App::DocumentObjectExecReturn* validateParameters( + int chamferType, + double size, + double size2, + double angle +) { // Size is common to all chamfer types. if (size <= 0) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Size must be greater than zero")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Size must be greater than zero") + ); } switch (chamferType) { - case 0: // Equal distance + case 0: // Equal distance // Nothing to do. break; - case 1: // Two distances + case 1: // Two distances if (size2 <= 0) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Size2 must be greater than zero")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Size2 must be greater than zero") + ); } break; - case 2: // Distance and angle + case 2: // Distance and angle if (angle <= 0 || angle >= 180.0) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Angle must be greater than 0 and less than 180")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Angle must be greater than 0 and less than 180") + ); } break; } return App::DocumentObject::StdReturn; } - - diff --git a/src/Mod/PartDesign/App/FeatureChamfer.h b/src/Mod/PartDesign/App/FeatureChamfer.h index 2a6aada3ed..ccaca0f10f 100644 --- a/src/Mod/PartDesign/App/FeatureChamfer.h +++ b/src/Mod/PartDesign/App/FeatureChamfer.h @@ -31,7 +31,7 @@ namespace PartDesign { -class PartDesignExport Chamfer : public DressUp +class PartDesignExport Chamfer: public DressUp { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Chamfer); @@ -48,10 +48,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderChamfer"; } //@} @@ -61,13 +62,17 @@ public: void updateProperties(); protected: - void Restore(Base::XMLReader &reader) override; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void Restore(Base::XMLReader& reader) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; static const App::PropertyQuantityConstraint::Constraints floatSize; static const App::PropertyAngle::Constraints floatAngle; }; -} //namespace Part +} // namespace PartDesign -#endif // PARTDESIGN_FEATURECHAMFER_H +#endif // PARTDESIGN_FEATURECHAMFER_H diff --git a/src/Mod/PartDesign/App/FeatureDraft.cpp b/src/Mod/PartDesign/App/FeatureDraft.cpp index 24ce5544f9..14a004b05b 100644 --- a/src/Mod/PartDesign/App/FeatureDraft.cpp +++ b/src/Mod/PartDesign/App/FeatureDraft.cpp @@ -22,22 +22,22 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -58,20 +58,25 @@ using namespace PartDesign; PROPERTY_SOURCE(PartDesign::Draft, PartDesign::DressUp) -const App::PropertyAngle::Constraints Draft::floatAngle = { -90.0, 90.0 - Base::toDegrees(Precision::Angular()), 0.1 }; +const App::PropertyAngle::Constraints Draft::floatAngle + = {-90.0, 90.0 - Base::toDegrees(Precision::Angular()), 0.1}; Draft::Draft() { - ADD_PROPERTY(Angle,(1.5)); + ADD_PROPERTY(Angle, (1.5)); Angle.setConstraints(&floatAngle); - ADD_PROPERTY_TYPE(NeutralPlane,(nullptr),"Draft",(App::PropertyType)(App::Prop_None),"NeutralPlane"); - ADD_PROPERTY_TYPE(PullDirection,(nullptr),"Draft",(App::PropertyType)(App::Prop_None),"PullDirection"); - ADD_PROPERTY(Reversed,(0)); + ADD_PROPERTY_TYPE(NeutralPlane, (nullptr), "Draft", (App::PropertyType)(App::Prop_None), "NeutralPlane"); + ADD_PROPERTY_TYPE( + PullDirection, + (nullptr), + "Draft", + (App::PropertyType)(App::Prop_None), + "PullDirection" + ); + ADD_PROPERTY(Reversed, (0)); } -void Draft::handleChangedPropertyType(Base::XMLReader &reader, - const char * TypeName, - App::Property * prop) +void Draft::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { Base::Type inputType = Base::Type::fromName(TypeName); if (prop == &Angle && inputType == App::PropertyFloatConstraint::getClassTypeId()) { @@ -86,16 +91,14 @@ void Draft::handleChangedPropertyType(Base::XMLReader &reader, short Draft::mustExecute() const { - if (Placement.isTouched() || - Angle.isTouched() || - NeutralPlane.isTouched() || - PullDirection.isTouched() || - Reversed.isTouched()) + if (Placement.isTouched() || Angle.isTouched() || NeutralPlane.isTouched() + || PullDirection.isTouched() || Reversed.isTouched()) { return 1; + } return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Draft::execute() +App::DocumentObjectExecReturn* Draft::execute() { // Get parameters // Base shape @@ -108,10 +111,11 @@ App::DocumentObjectExecReturn *Draft::execute() } // Faces where draft should be applied - // Note: Cannot be const reference currently because of BRepOffsetAPI_DraftAngle::Remove() bug, see below + // Note: Cannot be const reference currently because of BRepOffsetAPI_DraftAngle::Remove() bug, + // see below std::vector SubVals = Base.getSubValuesStartsWith("Face"); - //If no element is selected, then we use a copy of previous feature. + // If no element is selected, then we use a copy of previous feature. if (SubVals.empty()) { this->positionByBaseFeature(); this->Shape.setValue(TopShape); @@ -129,14 +133,17 @@ App::DocumentObjectExecReturn *Draft::execute() PartDesign::Line* line = static_cast(refDirection); Base::Vector3d d = line->getDirection(); pullDirection = gp_Dir(d.x, d.y, d.z); - } else if (refDirection->isDerivedFrom()) { + } + else if (refDirection->isDerivedFrom()) { App::Line* line = static_cast(refDirection); Base::Vector3d d = line->getDirection(); pullDirection = gp_Dir(d.x, d.y, d.z); - } else if (refDirection->isDerivedFrom()) { + } + else if (refDirection->isDerivedFrom()) { std::vector subStrings = PullDirection.getSubValues(); - if (subStrings.empty() || subStrings[0].empty()) + if (subStrings.empty() || subStrings[0].empty()) { throw Base::ValueError("No pull direction reference specified"); + } Part::Feature* refFeature = static_cast(refDirection); Part::TopoShape refShape = refFeature->Shape.getShape(); @@ -144,18 +151,24 @@ App::DocumentObjectExecReturn *Draft::execute() if (ref.ShapeType() == TopAbs_EDGE) { TopoDS_Edge refEdge = TopoDS::Edge(ref); - if (refEdge.IsNull()) + if (refEdge.IsNull()) { throw Base::ValueError("Failed to extract pull direction reference edge"); + } BRepAdaptor_Curve adapt(refEdge); - if (adapt.GetType() != GeomAbs_Line) + if (adapt.GetType() != GeomAbs_Line) { throw Base::TypeError("Pull direction reference edge must be linear"); + } pullDirection = adapt.Line().Direction(); - } else { + } + else { throw Base::TypeError("Pull direction reference must be an edge or a datum line"); } - } else { - throw Base::TypeError("Pull direction reference must be an edge of a feature or a datum line"); + } + else { + throw Base::TypeError( + "Pull direction reference must be an edge of a feature or a datum line" + ); } TopLoc_Location invObjLoc = this->getLocation().Inverted(); @@ -187,20 +200,24 @@ App::DocumentObjectExecReturn *Draft::execute() found = true; break; } - } else { + } + else { // Edge is linear // Find midpoint of edge and create auxiliary plane through midpoint normal to edge gp_Pnt pm = c.Value((c.FirstParameter() + c.LastParameter()) / 2.0); - Handle(Geom_Plane) aux = new Geom_Plane(pm, gp_Dir(p2.X() - p1.X(), p2.Y() - p1.Y(), p2.Z() - p1.Z())); + Handle(Geom_Plane) aux + = new Geom_Plane(pm, gp_Dir(p2.X() - p1.X(), p2.Y() - p1.Y(), p2.Z() - p1.Z())); // Intersect plane with face. Is there no easier way? BRepAdaptor_Surface adapt(TopoDS::Face(face), Standard_False); Handle(Geom_Surface) sf = adapt.Surface().Surface(); GeomAPI_IntSS intersector(aux, sf, Precision::Confusion()); - if (!intersector.IsDone() || intersector.NbLines() < 1) + if (!intersector.IsDone() || intersector.NbLines() < 1) { continue; + } Handle(Geom_Curve) icurve = intersector.Line(1); - if (!icurve->IsKind(STANDARD_TYPE(Geom_Line))) + if (!icurve->IsKind(STANDARD_TYPE(Geom_Line))) { continue; + } // TODO: How to extract the line from icurve without creating an edge first? TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(icurve); BRepAdaptor_Curve c(edge); @@ -210,20 +227,26 @@ App::DocumentObjectExecReturn *Draft::execute() } } - if (!found) + if (!found) { throw Base::RuntimeError("No neutral plane specified and none can be guessed"); - } else { + } + } + else { if (refPlane->isDerivedFrom()) { PartDesign::Plane* plane = static_cast(refPlane); Base::Vector3d b = plane->getBasePoint(); Base::Vector3d n = plane->getNormal(); neutralPlane = gp_Pln(gp_Pnt(b.x, b.y, b.z), gp_Dir(n.x, n.y, n.z)); - } else if (refPlane->isDerivedFrom() || refPlane->isDerivedFrom()) { + } + else if (refPlane->isDerivedFrom() + || refPlane->isDerivedFrom()) { neutralPlane = Feature::makePlnFromPlane(refPlane); - } else if (refPlane->isDerivedFrom()) { + } + else if (refPlane->isDerivedFrom()) { std::vector subStrings = NeutralPlane.getSubValues(); - if (subStrings.empty() || subStrings[0].empty()) + if (subStrings.empty() || subStrings[0].empty()) { throw Base::ValueError("No neutral plane reference specified"); + } Part::Feature* refFeature = static_cast(refPlane); Part::TopoShape refShape = refFeature->Shape.getShape(); @@ -231,33 +254,46 @@ App::DocumentObjectExecReturn *Draft::execute() if (ref.ShapeType() == TopAbs_FACE) { TopoDS_Face refFace = TopoDS::Face(ref); - if (refFace.IsNull()) + if (refFace.IsNull()) { throw Base::ValueError("Failed to extract neutral plane reference face"); + } BRepAdaptor_Surface adapt(refFace); - if (adapt.GetType() != GeomAbs_Plane) + if (adapt.GetType() != GeomAbs_Plane) { throw Base::TypeError("Neutral plane reference face must be planar"); + } neutralPlane = adapt.Plane(); - } else if (ref.ShapeType() == TopAbs_EDGE) { + } + else if (ref.ShapeType() == TopAbs_EDGE) { if (refDirection) { // Create neutral plane through edge normal to pull direction TopoDS_Edge refEdge = TopoDS::Edge(ref); - if (refEdge.IsNull()) + if (refEdge.IsNull()) { throw Base::ValueError("Failed to extract neutral plane reference edge"); + } BRepAdaptor_Curve c(refEdge); - if (c.GetType() != GeomAbs_Line) + if (c.GetType() != GeomAbs_Line) { throw Base::TypeError("Neutral plane reference edge must be linear"); + } double a = c.Line().Angle(gp_Lin(c.Value(c.FirstParameter()), pullDirection)); - if (std::fabs(a - std::numbers::pi/2) > Precision::Confusion()) - throw Base::ValueError("Neutral plane reference edge must be normal to pull direction"); + if (std::fabs(a - std::numbers::pi / 2) > Precision::Confusion()) { + throw Base::ValueError( + "Neutral plane reference edge must be normal to pull direction" + ); + } neutralPlane = gp_Pln(c.Value(c.FirstParameter()), pullDirection); - } else { - throw Base::TypeError("Neutral plane reference can only be an edge if pull direction is defined"); } - } else { + else { + throw Base::TypeError( + "Neutral plane reference can only be an edge if pull direction is defined" + ); + } + } + else { throw Base::TypeError("Neutral plane reference must be a face"); } - } else { + } + else { throw Base::TypeError("Neutral plane reference must be face of a feature or a datum plane"); } @@ -272,8 +308,9 @@ App::DocumentObjectExecReturn *Draft::execute() // Reversed pull direction bool reversed = Reversed.getValue(); - if (reversed) + if (reversed) { angle *= -1.0; + } this->positionByBaseFeature(); // create an untransformed copy of the base shape @@ -286,11 +323,16 @@ App::DocumentObjectExecReturn *Draft::execute() shape.makeElementDraft(baseShape, faces, pullDirection, angle, neutralPlane, reversed); if (shape.isNull()) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Resulting shape is null")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Resulting shape is null") + ); } if (!isSingleSolidRuleSatisfied(shape.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } this->Shape.setValue(getSolid(shape)); @@ -301,5 +343,3 @@ App::DocumentObjectExecReturn *Draft::execute() return new App::DocumentObjectExecReturn(e.GetMessageString()); } } - - diff --git a/src/Mod/PartDesign/App/FeatureDraft.h b/src/Mod/PartDesign/App/FeatureDraft.h index d55a420e91..52ed8bafcc 100644 --- a/src/Mod/PartDesign/App/FeatureDraft.h +++ b/src/Mod/PartDesign/App/FeatureDraft.h @@ -33,7 +33,7 @@ namespace PartDesign { -class PartDesignExport Draft : public DressUp +class PartDesignExport Draft: public DressUp { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Draft); @@ -48,20 +48,25 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderDraft"; } //@} private: - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; static const App::PropertyAngle::Constraints floatAngle; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FEATUREDRAFT_H +#endif // PARTDESIGN_FEATUREDRAFT_H diff --git a/src/Mod/PartDesign/App/FeatureDressUp.cpp b/src/Mod/PartDesign/App/FeatureDressUp.cpp index 78710f81aa..33ef61edf5 100644 --- a/src/Mod/PartDesign/App/FeatureDressUp.cpp +++ b/src/Mod/PartDesign/App/FeatureDressUp.cpp @@ -30,7 +30,6 @@ #include - #include #include "FeatureDressUp.h" @@ -39,44 +38,52 @@ #include #include "Mod/Part/App/TopoShapeMapper.h" -FC_LOG_LEVEL_INIT("PartDesign",true,true) +FC_LOG_LEVEL_INIT("PartDesign", true, true) using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ PROPERTY_SOURCE(PartDesign::DressUp, PartDesign::FeatureAddSub) DressUp::DressUp() { - ADD_PROPERTY(Base,(nullptr)); + ADD_PROPERTY(Base, (nullptr)); Placement.setStatus(App::Property::ReadOnly, true); - ADD_PROPERTY_TYPE(SupportTransform,(false),"Base", App::Prop_None, - "Include the base additive/subtractive shape when used in pattern features.\n" - "If disabled, only the dressed part of the shape is used for patterning."); + ADD_PROPERTY_TYPE( + SupportTransform, + (false), + "Base", + App::Prop_None, + "Include the base additive/subtractive shape when used in pattern features.\n" + "If disabled, only the dressed part of the shape is used for patterning." + ); AddSubShape.setStatus(App::Property::Output, true); } short DressUp::mustExecute() const { - if (Base.getValue() && Base.getValue()->isTouched()) + if (Base.getValue() && Base.getValue()->isTouched()) { return 1; + } return PartDesign::FeatureAddSub::mustExecute(); } void DressUp::positionByBaseFeature() { - Part::Feature *base = static_cast(BaseFeature.getValue()); - if (base && base->isDerivedFrom()) + Part::Feature* base = static_cast(BaseFeature.getValue()); + if (base && base->isDerivedFrom()) { this->Placement.setValue(base->Placement.getValue()); + } } -Part::Feature *DressUp::getBaseObject(bool silent) const +Part::Feature* DressUp::getBaseObject(bool silent) const { - Part::Feature *rv = Feature::getBaseObject(/* silent = */ true); + Part::Feature* rv = Feature::getBaseObject(/* silent = */ true); if (rv) { return rv; } @@ -84,12 +91,14 @@ Part::Feature *DressUp::getBaseObject(bool silent) const const char* err = nullptr; App::DocumentObject* base = Base.getValue(); if (base) { - if(base->isDerivedFrom()) { + if (base->isDerivedFrom()) { rv = static_cast(base); - } else { + } + else { err = "Linked object is not a Part object"; } - } else { + } + else { err = "No Base object linked"; } @@ -100,14 +109,20 @@ Part::Feature *DressUp::getBaseObject(bool silent) const return rv; } -void DressUp::getContinuousEdges(Part::TopoShape TopShape, std::vector< std::string >& SubNames) { +void DressUp::getContinuousEdges(Part::TopoShape TopShape, std::vector& SubNames) +{ - std::vector< std::string > FaceNames; + std::vector FaceNames; getContinuousEdges(TopShape, SubNames, FaceNames); } -void DressUp::getContinuousEdges(Part::TopoShape TopShape, std::vector< std::string >& SubNames, std::vector< std::string >& FaceNames) { +void DressUp::getContinuousEdges( + Part::TopoShape TopShape, + std::vector& SubNames, + std::vector& FaceNames +) +{ TopTools_IndexedMapOfShape mapOfEdges; TopTools_IndexedDataMapOfShapeListOfShape mapEdgeFace; @@ -115,39 +130,36 @@ void DressUp::getContinuousEdges(Part::TopoShape TopShape, std::vector< std::str TopExp::MapShapes(TopShape.getShape(), TopAbs_EDGE, mapOfEdges); unsigned int i = 0; - while(i < SubNames.size()) - { + while (i < SubNames.size()) { std::string aSubName = static_cast(SubNames.at(i)); if (aSubName.compare(0, 4, "Edge") == 0) { TopoDS_Edge edge = TopoDS::Edge(TopShape.getSubShape(aSubName.c_str())); const TopTools_ListOfShape& los = mapEdgeFace.FindFromKey(edge); - if(los.Extent() != 2) - { - SubNames.erase(SubNames.begin()+i); + if (los.Extent() != 2) { + SubNames.erase(SubNames.begin() + i); continue; } const TopoDS_Shape& face1 = los.First(); const TopoDS_Shape& face2 = los.Last(); - GeomAbs_Shape cont = BRep_Tool::Continuity(TopoDS::Edge(edge), - TopoDS::Face(face1), - TopoDS::Face(face2)); + GeomAbs_Shape cont + = BRep_Tool::Continuity(TopoDS::Edge(edge), TopoDS::Face(face1), TopoDS::Face(face2)); if (cont != GeomAbs_C0) { - SubNames.erase(SubNames.begin()+i); + SubNames.erase(SubNames.begin() + i); continue; } i++; } - else if(aSubName.compare(0, 4, "Face") == 0) { + else if (aSubName.compare(0, 4, "Face") == 0) { TopoDS_Face face = TopoDS::Face(TopShape.getSubShape(aSubName.c_str())); TopTools_IndexedMapOfShape mapOfFaces; TopExp::MapShapes(face, TopAbs_EDGE, mapOfFaces); - for(int j = 1; j <= mapOfFaces.Extent(); ++j) { + for (int j = 1; j <= mapOfFaces.Extent(); ++j) { TopoDS_Edge edge = TopoDS::Edge(mapOfFaces.FindKey(j)); int id = mapOfEdges.FindIndex(edge); @@ -156,19 +168,17 @@ void DressUp::getContinuousEdges(Part::TopoShape TopShape, std::vector< std::str buf << "Edge"; buf << id; - if (std::ranges::find(SubNames, buf.str()) == SubNames.end()) - { + if (std::ranges::find(SubNames, buf.str()) == SubNames.end()) { SubNames.push_back(buf.str()); } - } FaceNames.emplace_back(aSubName.c_str()); - SubNames.erase(SubNames.begin()+i); + SubNames.erase(SubNames.begin() + i); } // empty name or any other sub-element else { - SubNames.erase(SubNames.begin()+i); + SubNames.erase(SubNames.begin() + i); } } } @@ -190,8 +200,8 @@ std::vector DressUp::getContinuousEdges(const TopoShape& shape) } const TopoDS_Shape& face1 = faces.front(); const TopoDS_Shape& face2 = faces.back(); - GeomAbs_Shape cont = - BRep_Tool::Continuity(TopoDS::Edge(subshape), TopoDS::Face(face1), TopoDS::Face(face2)); + GeomAbs_Shape cont + = BRep_Tool::Continuity(TopoDS::Edge(subshape), TopoDS::Face(face1), TopoDS::Face(face2)); if (cont != GeomAbs_C0) { FC_WARN(getFullName() << ": skip edge " << ref << " that is not C0 continuous"); return; @@ -216,8 +226,10 @@ std::vector DressUp::getContinuousEdges(const TopoShape& shape) } } else { - FC_WARN(getFullName() << ": skip invalid shape '" << ref << "' with type " - << TopoShape::shapeName(subshape.ShapeType())); + FC_WARN( + getFullName() << ": skip invalid shape '" << ref << "' with type " + << TopoShape::shapeName(subshape.ShapeType()) + ); } } return ret; @@ -248,8 +260,10 @@ std::vector DressUp::getFaces(const TopoShape& shape) } if (subshape.shapeType() != TopAbs_FACE) { - FC_WARN(getFullName() << ": skip invalid shape '" << ref << "' with type " - << subshape.shapeName()); + FC_WARN( + getFullName() << ": skip invalid shape '" << ref << "' with type " + << subshape.shapeName() + ); continue; } ret.push_back(subshape); @@ -262,23 +276,22 @@ void DressUp::onChanged(const App::Property* prop) // the BaseFeature property should track the Base and vice-versa as long as // the feature is inside a body (aka BaseFeature is nonzero) if (prop == &BaseFeature) { - if (BaseFeature.getValue() - && Base.getValue() - && Base.getValue() != BaseFeature.getValue()) { + if (BaseFeature.getValue() && Base.getValue() && Base.getValue() != BaseFeature.getValue()) { auto subs = Base.getSubValues(false); auto shadows = Base.getShadowSubs(); - Base.setValue (BaseFeature.getValue(),std::move(subs),std::move(shadows)); + Base.setValue(BaseFeature.getValue(), std::move(subs), std::move(shadows)); } - } else if (prop == &Base) { + } + else if (prop == &Base) { // track the vice-versa changes if (BaseFeature.getValue() && Base.getValue() != BaseFeature.getValue()) { - BaseFeature.setValue (Base.getValue()); + BaseFeature.setValue(Base.getValue()); } - } else if (prop == &Shape || prop == &SupportTransform) { - if (!getDocument()->testStatus(App::Document::Restoring) && - !getDocument()->isPerformingTransaction()) - { + } + else if (prop == &Shape || prop == &SupportTransform) { + if (!getDocument()->testStatus(App::Document::Restoring) + && !getDocument()->isPerformingTransaction()) { // AddSubShape in DressUp acts as a shape cache. And here we shall // invalidate the cache upon changes in Shape. Other features // (currently only feature Transformed) shall call getAddSubShape() @@ -310,9 +323,10 @@ void DressUp::getAddSubShape(Part::TopoShape& addShape, Part::TopoShape& subShap for (Feature* current = this;; current = static_cast(base)) { base = freecad_cast(current->getBaseObject(true)); if (!base) { - FC_THROWM(Base::CADKernelError, - "Cannot find additive or subtractive support for " - << getFullName()); + FC_THROWM( + Base::CADKernelError, + "Cannot find additive or subtractive support for " << getFullName() + ); } if (!base->isDerivedFrom()) { break; @@ -359,8 +373,10 @@ void DressUp::getAddSubShape(Part::TopoShape& addShape, Part::TopoShape& subShap AddSubShape.setValue(Part::TopoShape().makeElementCompound(shapes)); } catch (Standard_Failure& e) { - FC_THROWM(Base::CADKernelError, - "Failed to calculate AddSub shape: " << e.GetMessageString()); + FC_THROWM( + Base::CADKernelError, + "Failed to calculate AddSub shape: " << e.GetMessageString() + ); } res = AddSubShape.getShape(); } diff --git a/src/Mod/PartDesign/App/FeatureDressUp.h b/src/Mod/PartDesign/App/FeatureDressUp.h index 7be5e81641..723b931e75 100644 --- a/src/Mod/PartDesign/App/FeatureDressUp.h +++ b/src/Mod/PartDesign/App/FeatureDressUp.h @@ -29,7 +29,7 @@ namespace PartDesign { -class PartDesignExport DressUp : public PartDesign::FeatureAddSub +class PartDesignExport DressUp: public PartDesign::FeatureAddSub { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::DressUp); @@ -54,24 +54,24 @@ public: * silently return a nullptr, otherwise throw Base::Exception. * Default is false. */ - Part::Feature* getBaseObject(bool silent=false) const override; + Part::Feature* getBaseObject(bool silent = false) const override; /// extracts all edges from the subshapes (including face edges) and furthermore adds /// all C0 continuous edges to the vector - void getContinuousEdges(Part::TopoShape, std::vector< std::string >&); + void getContinuousEdges(Part::TopoShape, std::vector&); // add argument to return the selected face that edges were derived from - void getContinuousEdges(Part::TopoShape, std::vector< std::string >&, std::vector< std::string >&); + void getContinuousEdges(Part::TopoShape, std::vector&, std::vector&); // Todo: Post-TNP the above two versions should be able to be factored out. - std::vector getContinuousEdges(const TopoShape &shape); + std::vector getContinuousEdges(const TopoShape& shape); - std::vector getFaces(const TopoShape &shape); - void getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShape) override; + std::vector getFaces(const TopoShape& shape); + void getAddSubShape(Part::TopoShape& addShape, Part::TopoShape& subShape) override; void updatePreviewShape() override; protected: void onChanged(const App::Property* prop) override; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_DressUp_H +#endif // PARTDESIGN_DressUp_H diff --git a/src/Mod/PartDesign/App/FeatureExtrude.cpp b/src/Mod/PartDesign/App/FeatureExtrude.cpp index 8abab453f9..f54295dcec 100644 --- a/src/Mod/PartDesign/App/FeatureExtrude.cpp +++ b/src/Mod/PartDesign/App/FeatureExtrude.cpp @@ -21,18 +21,18 @@ * * ***************************************************************************/ -# 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 @@ -50,40 +50,29 @@ const char* FeatureExtrude::SideTypesEnums[] = {"One side", "Two sides", "Symmet PROPERTY_SOURCE(PartDesign::FeatureExtrude, PartDesign::ProfileBased) -App::PropertyQuantityConstraint::Constraints FeatureExtrude::signedLengthConstraint = { - -std::numeric_limits::max(), std::numeric_limits::max(), 1.0 }; +App::PropertyQuantityConstraint::Constraints FeatureExtrude::signedLengthConstraint + = {-std::numeric_limits::max(), std::numeric_limits::max(), 1.0}; double FeatureExtrude::maxAngle = 90 - Base::toDegrees(Precision::Angular()); -App::PropertyAngle::Constraints FeatureExtrude::floatAngle = { -maxAngle, maxAngle, 1.0 }; +App::PropertyAngle::Constraints FeatureExtrude::floatAngle = {-maxAngle, maxAngle, 1.0}; FeatureExtrude::FeatureExtrude() = default; short FeatureExtrude::mustExecute() const { - if (Placement.isTouched() || - SideType.isTouched() || - Type.isTouched() || - Type2.isTouched() || - Length.isTouched() || - Length2.isTouched() || - TaperAngle.isTouched() || - TaperAngle2.isTouched() || - UseCustomVector.isTouched() || - Direction.isTouched() || - ReferenceAxis.isTouched() || - AlongSketchNormal.isTouched() || - Offset.isTouched() || - Offset2.isTouched() || - UpToFace.isTouched() || - UpToFace2.isTouched() || - UpToShape.isTouched() || - UpToShape2.isTouched()) + if (Placement.isTouched() || SideType.isTouched() || Type.isTouched() || Type2.isTouched() + || Length.isTouched() || Length2.isTouched() || TaperAngle.isTouched() + || TaperAngle2.isTouched() || UseCustomVector.isTouched() || Direction.isTouched() + || ReferenceAxis.isTouched() || AlongSketchNormal.isTouched() || Offset.isTouched() + || Offset2.isTouched() || UpToFace.isTouched() || UpToFace2.isTouched() + || UpToShape.isTouched() || UpToShape2.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } Base::Vector3d FeatureExtrude::computeDirection(const Base::Vector3d& sketchVector, bool inverse) { - (void) inverse; + (void)inverse; Base::Vector3d extrudeDirection; if (!UseCustomVector.getValue()) { @@ -124,8 +113,9 @@ Base::Vector3d FeatureExtrude::computeDirection(const Base::Vector3d& sketchVect Direction.setReadOnly(!UseCustomVector.getValue()); ReferenceAxis.setReadOnly(UseCustomVector.getValue()); // UseCustomVector allows AlongSketchNormal but !UseCustomVector does not forbid it - if (UseCustomVector.getValue()) + if (UseCustomVector.getValue()) { AlongSketchNormal.setReadOnly(false); + } // explicitly set the Direction so that the dialog shows also the used direction // if the sketch's normal vector was used @@ -135,15 +125,15 @@ Base::Vector3d FeatureExtrude::computeDirection(const Base::Vector3d& sketchVect bool FeatureExtrude::hasTaperedAngle() const { - return fabs(TaperAngle.getValue()) > Base::toRadians(Precision::Angular()) || - fabs(TaperAngle2.getValue()) > Base::toRadians(Precision::Angular()); + return fabs(TaperAngle.getValue()) > Base::toRadians(Precision::Angular()) + || fabs(TaperAngle2.getValue()) > Base::toRadians(Precision::Angular()); } -TopoShape FeatureExtrude::makeShellFromUpToShape(TopoShape shape, TopoShape sketchshape, gp_Dir dir){ +TopoShape FeatureExtrude::makeShellFromUpToShape(TopoShape shape, TopoShape sketchshape, gp_Dir dir) +{ // Find nearest/furthest face - std::vector cfaces = - Part::findAllFacesCutBy(shape, sketchshape, dir); + std::vector cfaces = Part::findAllFacesCutBy(shape, sketchshape, dir); if (cfaces.empty()) { dir = -dir; cfaces = Part::findAllFacesCutBy(shape, sketchshape, dir); @@ -153,10 +143,10 @@ TopoShape FeatureExtrude::makeShellFromUpToShape(TopoShape shape, TopoShape sket return shape; } - struct Part::cutTopoShapeFaces *nearFace {}; - struct Part::cutTopoShapeFaces *farFace {}; + struct Part::cutTopoShapeFaces* nearFace {}; + struct Part::cutTopoShapeFaces* farFace {}; nearFace = farFace = &cfaces.front(); - for (auto &face : cfaces) { + for (auto& face : cfaces) { if (face.distsq > farFace->distsq) { farFace = &face; } @@ -167,8 +157,8 @@ TopoShape FeatureExtrude::makeShellFromUpToShape(TopoShape shape, TopoShape sket if (nearFace != farFace) { std::vector faceList; - for (auto &face : shape.getSubTopoShapes(TopAbs_FACE)) { - if (! (face == farFace->face)){ + for (auto& face : shape.getSubTopoShapes(TopAbs_FACE)) { + if (!(face == farFace->face)) { // don't use the last face so the shell is open // and OCC works better faceList.push_back(face); @@ -230,47 +220,55 @@ void FeatureExtrude::updateProperties() if (sideTypeVal == "One side") { bool side1ASN = false; - configureSideProperties(methodSide1, - isLength1Enabled, - isTaper1Visible, - isUpToFace1Enabled, - isUpToShape1Enabled, - side1ASN, - isOffset1Enabled); + configureSideProperties( + methodSide1, + isLength1Enabled, + isTaper1Visible, + isUpToFace1Enabled, + isUpToShape1Enabled, + side1ASN, + isOffset1Enabled + ); currentAlongSketchNormalEnabled = side1ASN; } else if (sideTypeVal == "Two sides") { isType2Enabled = true; bool side1ASN = false; - configureSideProperties(methodSide1, - isLength1Enabled, - isTaper1Visible, - isUpToFace1Enabled, - isUpToShape1Enabled, - side1ASN, - isOffset1Enabled); + configureSideProperties( + methodSide1, + isLength1Enabled, + isTaper1Visible, + isUpToFace1Enabled, + isUpToShape1Enabled, + side1ASN, + isOffset1Enabled + ); bool side2ASN = false; - configureSideProperties(methodSide2, - isLength2Enabled, - isTaper2Visible, - isUpToFace2Enabled, - isUpToShape2Enabled, - side2ASN, - isOffset2Enabled); + configureSideProperties( + methodSide2, + isLength2Enabled, + isTaper2Visible, + isUpToFace2Enabled, + isUpToShape2Enabled, + side2ASN, + isOffset2Enabled + ); currentAlongSketchNormalEnabled = side1ASN || side2ASN; // Enable if either side needs it } else if (sideTypeVal == "Symmetric") { bool symASN = false; - configureSideProperties(methodSide1, - isLength1Enabled, - isTaper1Visible, - isUpToFace1Enabled, - isUpToShape1Enabled, - symASN, - isOffset1Enabled); + configureSideProperties( + methodSide1, + isLength1Enabled, + isTaper1Visible, + isUpToFace1Enabled, + isUpToShape1Enabled, + symASN, + isOffset1Enabled + ); currentAlongSketchNormalEnabled = symASN; } @@ -297,7 +295,9 @@ void FeatureExtrude::setupObject() App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions options) { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } bool makeface = options.testFlag(ExtrudeOption::MakeFace); @@ -323,13 +323,13 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt if (std::abs(L + L2) < Precision::Confusion()) { if (addSubType == Type::Additive) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", - "Cannot create a pad with a total length of zero.")); + QT_TRANSLATE_NOOP("Exception", "Cannot create a pad with a total length of zero.") + ); } else { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", - "Cannot create a pocket with a total length of zero.")); + QT_TRANSLATE_NOOP("Exception", "Cannot create a pocket with a total length of zero.") + ); } } } @@ -353,15 +353,18 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt if (sub.empty() && subs.size() > 1) { continue; } - TopoShape shape = Part::Feature::getTopoShape(obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sub.c_str()); + TopoShape shape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sub.c_str() + ); if (shape.isNull()) { - FC_ERR(getFullName() - << ": failed to get profile shape " << obj->getFullName() << "." << sub); + FC_ERR( + getFullName() + << ": failed to get profile shape " << obj->getFullName() << "." << sub + ); failed = true; } hasEdges = hasEdges || shape.hasSubShape(TopAbs_EDGE); @@ -369,7 +372,8 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt } if (failed) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Failed to obtain profile shape")); + QT_TRANSLATE_NOOP("Exception", "Failed to obtain profile shape") + ); } if (hasEdges) { sketchshape.makeElementWires(shapes); @@ -378,7 +382,8 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt sketchshape.makeElementCompound( shapes, nullptr, - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); } } } @@ -423,7 +428,8 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt if (factor < Precision::Confusion()) { return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( "Exception", - "Creation failed because direction is orthogonal to sketch's normal vector")); + "Creation failed because direction is orthogonal to sketch's normal vector" + )); } // perform the length correction if not along custom vector @@ -443,7 +449,8 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt if (sketchshape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Creating a face from sketch failed")); + QT_TRANSLATE_NOOP("Exception", "Creating a face from sketch failed") + ); } sketchshape.move(invObjLoc); @@ -452,9 +459,18 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt double offset1 = Offset.getValue(); if (Sidemethod == "One side") { - TopoShape prism1 = generateSingleExtrusionSide(sketchshape, - method, L, taper1, UpToFace, UpToShape, - dir, offset1, makeface, base); + TopoShape prism1 = generateSingleExtrusionSide( + sketchshape, + method, + L, + taper1, + UpToFace, + UpToShape, + dir, + offset1, + makeface, + base + ); prisms.push_back(prism1); } else if (Sidemethod == "Symmetric") { @@ -466,32 +482,36 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt // to ensure the taper originates correctly from the sketch plane in both // directions. L /= 2.0; - TopoShape prism1 = generateSingleExtrusionSide(sketchshape.makeElementCopy(), - method, - L, - taper1, - UpToFace, - UpToShape, - dir, - offset1, - makeface, - base); + TopoShape prism1 = generateSingleExtrusionSide( + sketchshape.makeElementCopy(), + method, + L, + taper1, + UpToFace, + UpToShape, + dir, + offset1, + makeface, + base + ); if (!prism1.isNull() && !prism1.getShape().IsNull()) { prisms.push_back(prism1); } gp_Dir dir2 = dir; dir2.Reverse(); - TopoShape prism2 = generateSingleExtrusionSide(sketchshape.makeElementCopy(), - method, - L, - taper1, - UpToFace, - UpToShape, - dir2, - offset1, - makeface, - base); + TopoShape prism2 = generateSingleExtrusionSide( + sketchshape.makeElementCopy(), + method, + L, + taper1, + UpToFace, + UpToShape, + dir2, + offset1, + makeface, + base + ); if (!prism2.isNull() && !prism2.getShape().IsNull()) { prisms.push_back(prism2); } @@ -506,16 +526,18 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt TopoShape moved_sketch = sketchshape.makeElementCopy(); moved_sketch.move(start_transform); - TopoShape prism1 = generateSingleExtrusionSide(moved_sketch, - method, - L, - taper1, - UpToFace, - UpToShape, - dir, - offset1, - makeface, - base); + TopoShape prism1 = generateSingleExtrusionSide( + moved_sketch, + method, + L, + taper1, + UpToFace, + UpToShape, + dir, + offset1, + makeface, + base + ); if (!prism1.isNull() && !prism1.getShape().IsNull()) { prisms.push_back(prism1); } @@ -523,9 +545,18 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt } else { // For "UpToFace", "UpToShape", etc., mirror the result. - TopoShape prism1 = generateSingleExtrusionSide(sketchshape, - method, L, taper1, UpToFace, UpToShape, - dir, offset1, makeface, base); + TopoShape prism1 = generateSingleExtrusionSide( + sketchshape, + method, + L, + taper1, + UpToFace, + UpToShape, + dir, + offset1, + makeface, + base + ); prisms.push_back(prism1); // Prism 2: Mirror prism1 across the sketch plane. @@ -534,8 +565,10 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt sketchNormalDir.Transform(invTrsf); // Transform to global CS, like 'dir' was. Base::Vector3d sketchCenter = sketchshape.getBoundBox().GetCenter(); - gp_Ax2 mirrorPlane(gp_Pnt(sketchCenter.x, sketchCenter.y, sketchCenter.z), - sketchNormalDir); + gp_Ax2 mirrorPlane( + gp_Pnt(sketchCenter.x, sketchCenter.y, sketchCenter.z), + sketchNormalDir + ); TopoShape prism2 = prism1.makeElementMirror(mirrorPlane); prisms.push_back(prism2); } @@ -556,16 +589,18 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt TopoShape moved_sketch = sketchshape.makeElementCopy(); moved_sketch.move(start_transform); - TopoShape prism = generateSingleExtrusionSide(moved_sketch, - method2, - L + L2, - 0.0, - UpToFace2, - UpToShape2, - dir2, - offset2, - makeface, - base); + TopoShape prism = generateSingleExtrusionSide( + moved_sketch, + method2, + L + L2, + 0.0, + UpToFace2, + UpToShape2, + dir2, + offset2, + makeface, + base + ); if (!prism.isNull() && !prism.getShape().IsNull()) { prisms.push_back(prism); } @@ -576,46 +611,52 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt TopoShape moved_sketch = sketchshape.makeElementCopy(); moved_sketch.move(start_transform); - TopoShape prism = generateSingleExtrusionSide(moved_sketch, - method, - L + L2, - 0.0, - UpToFace, - UpToShape, - dir, - offset1, - makeface, - base); + TopoShape prism = generateSingleExtrusionSide( + moved_sketch, + method, + L + L2, + 0.0, + UpToFace, + UpToShape, + dir, + offset1, + makeface, + base + ); if (!prism.isNull() && !prism.getShape().IsNull()) { prisms.push_back(prism); } } else { - TopoShape prism1 = generateSingleExtrusionSide(sketchshape.makeElementCopy(), - method, - L, - taper1, - UpToFace, - UpToShape, - dir, - offset1, - makeface, - base); + TopoShape prism1 = generateSingleExtrusionSide( + sketchshape.makeElementCopy(), + method, + L, + taper1, + UpToFace, + UpToShape, + dir, + offset1, + makeface, + base + ); if (!prism1.isNull() && !prism1.getShape().IsNull()) { prisms.push_back(prism1); } // Side 2 - TopoShape prism2 = generateSingleExtrusionSide(sketchshape.makeElementCopy(), - method2, - L2, - taper2, - UpToFace2, - UpToShape2, - dir2, - offset2, - makeface, - base); + TopoShape prism2 = generateSingleExtrusionSide( + sketchshape.makeElementCopy(), + method2, + L2, + taper2, + UpToFace2, + UpToShape2, + dir2, + offset2, + makeface, + base + ); if (!prism2.isNull() && !prism2.getShape().IsNull()) { prisms.push_back(prism2); } @@ -625,7 +666,9 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt // --- Combine generated prisms (all in global CS) --- TopoShape prism(0, getDocument()->getStringHasher()); if (prisms.empty()) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "No extrusion geometry was generated.")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "No extrusion geometry was generated.") + ); } else if (prisms.size() == 1) { prism = prisms[0]; @@ -636,16 +679,20 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt } catch (const Standard_Failure& e) { return new App::DocumentObjectExecReturn( - std::string("Failed to xor extrusion sides (OCC): ") + e.GetMessageString()); + std::string("Failed to xor extrusion sides (OCC): ") + e.GetMessageString() + ); } catch (const Base::Exception& e) { return new App::DocumentObjectExecReturn( - std::string("Failed to xor extrusion sides: ") + e.what()); + std::string("Failed to xor extrusion sides: ") + e.what() + ); } } if (prism.isNull()) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Resulting fused extrusion is null.")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Resulting fused extrusion is null.") + ); } // store shape before refinement @@ -672,14 +719,16 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt } catch (Standard_Failure&) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Fusion with base feature failed")); + QT_TRANSLATE_NOOP("Exception", "Fusion with base feature failed") + ); } // we have to get the solids (fuse sometimes creates compounds) auto solRes = this->getSolid(result); // lets check if the result is a solid if (solRes.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid")); + QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid") + ); } // store shape before refinement @@ -687,7 +736,10 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt solRes = refineShapeIfActive(result); if (!isSingleSolidRuleSatisfied(solRes.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } this->Shape.setValue(getSolid(solRes)); } @@ -700,7 +752,10 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt this->rawShape = prism; prism = refineShapeIfActive(prism); if (!isSingleSolidRuleSatisfied(prism.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } prism = getSolid(prism); this->Shape.setValue(prism); @@ -710,7 +765,10 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt this->rawShape = prism; prism = refineShapeIfActive(prism); if (!isSingleSolidRuleSatisfied(prism.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } this->Shape.setValue(prism); } @@ -725,7 +783,8 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( "Exception", "Could not create face from sketch.\n" - "Intersecting sketch entities or multiple faces in a sketch are not allowed.")); + "Intersecting sketch entities or multiple faces in a sketch are not allowed." + )); } else { return new App::DocumentObjectExecReturn(e.GetMessageString()); @@ -736,20 +795,23 @@ App::DocumentObjectExecReturn* FeatureExtrude::buildExtrusion(ExtrudeOptions opt } } -TopoShape FeatureExtrude::generateSingleExtrusionSide(const TopoShape& sketchshape, - const std::string& method, - double length, - double taperAngleDeg, - App::PropertyLinkSub& upToFacePropHandle, - App::PropertyLinkSubList& upToShapePropHandle, - gp_Dir dir, - double offsetVal, - bool makeFace, - const TopoShape& base) +TopoShape FeatureExtrude::generateSingleExtrusionSide( + const TopoShape& sketchshape, + const std::string& method, + double length, + double taperAngleDeg, + App::PropertyLinkSub& upToFacePropHandle, + App::PropertyLinkSubList& upToShapePropHandle, + gp_Dir dir, + double offsetVal, + bool makeFace, + const TopoShape& base +) { TopoShape prism(0, getDocument()->getStringHasher()); - if (method == "UpToFirst" || method == "UpToLast" || method == "UpToFace" || method == "UpToShape") { + if (method == "UpToFirst" || method == "UpToLast" || method == "UpToFace" + || method == "UpToShape") { // Note: This will return an unlimited planar face if support is a datum plane TopoShape supportface = getTopoShapeSupportFace(); auto invObjLoc = getLocation().Inverted(); @@ -792,17 +854,21 @@ TopoShape FeatureExtrude::generateSingleExtrusionSide(const TopoShape& sketchsha if (addSubType != FeatureAddSub::Subtractive) { _base = base; // avoid issue #16690 } - prism.makeElementPrismUntil(_base, - sketchshape, - supportface, - upToShape, - dir, - TopoShape::PrismMode::None, - true /*CheckUpToFaceLimits.getValue()*/); + prism.makeElementPrismUntil( + _base, + sketchshape, + supportface, + upToShape, + dir, + TopoShape::PrismMode::None, + true /*CheckUpToFaceLimits.getValue()*/ + ); } catch (Base::Exception&) { if (method == "UpToShape" && faceCount > 1) { - throw Base::RuntimeError("Extrude: Unable to reach the selected shape, please select faces"); + throw Base::RuntimeError( + "Extrude: Unable to reach the selected shape, please select faces" + ); } } } @@ -812,8 +878,10 @@ TopoShape FeatureExtrude::generateSingleExtrusionSide(const TopoShape& sketchsha Part::ExtrusionParameters params; params.taperAngleFwd = Base::toRadians(taperAngleDeg); - if (std::fabs(params.taperAngleFwd) >= Precision::Angular() || std::fabs(params.taperAngleRev) >= Precision::Angular()) { - if (fabs(params.taperAngleFwd) > pi * 0.5 - Precision::Angular() || fabs(params.taperAngleRev) > pi * 0.5 - Precision::Angular()) { + if (std::fabs(params.taperAngleFwd) >= Precision::Angular() + || std::fabs(params.taperAngleRev) >= Precision::Angular()) { + if (fabs(params.taperAngleFwd) > pi * 0.5 - Precision::Angular() + || fabs(params.taperAngleRev) > pi * 0.5 - Precision::Angular()) { return prism; } params.dir = dir; @@ -821,16 +889,20 @@ TopoShape FeatureExtrude::generateSingleExtrusionSide(const TopoShape& sketchsha params.lengthFwd = length; std::vector drafts; - Part::ExtrusionHelper::makeElementDraft(params, - sketchshape, - drafts, - getDocument()->getStringHasher()); + Part::ExtrusionHelper::makeElementDraft( + params, + sketchshape, + drafts, + getDocument()->getStringHasher() + ); if (drafts.empty()) { return prism; } - prism.makeElementCompound(drafts, - nullptr, - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + prism.makeElementCompound( + drafts, + nullptr, + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); } else { // Without taper angle we create a prism because its shells are in every case no diff --git a/src/Mod/PartDesign/App/FeatureExtrude.h b/src/Mod/PartDesign/App/FeatureExtrude.h index 67b06e2b7e..6c098d05cc 100644 --- a/src/Mod/PartDesign/App/FeatureExtrude.h +++ b/src/Mod/PartDesign/App/FeatureExtrude.h @@ -35,7 +35,7 @@ class TopoDS_Shape; namespace PartDesign { -class PartDesignExport FeatureExtrude : public ProfileBased +class PartDesignExport FeatureExtrude: public ProfileBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureExtrude); @@ -45,16 +45,16 @@ public: App::PropertyEnumeration SideType; App::PropertyEnumeration Type; App::PropertyEnumeration Type2; - App::PropertyLength Length; - App::PropertyLength Length2; - App::PropertyAngle TaperAngle; - App::PropertyAngle TaperAngle2; - App::PropertyBool UseCustomVector; - App::PropertyVector Direction; - App::PropertyBool AlongSketchNormal; - App::PropertyLength Offset; - App::PropertyLength Offset2; - App::PropertyLinkSub ReferenceAxis; + App::PropertyLength Length; + App::PropertyLength Length2; + App::PropertyAngle TaperAngle; + App::PropertyAngle TaperAngle2; + App::PropertyBool UseCustomVector; + App::PropertyVector Direction; + App::PropertyBool AlongSketchNormal; + App::PropertyLength Offset; + App::PropertyLength Offset2; + App::PropertyLinkSub ReferenceAxis; static App::PropertyQuantityConstraint::Constraints signedLengthConstraint; static double maxAngle; @@ -65,7 +65,8 @@ public: short mustExecute() const override; void setupObject() override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderExtrude"; } //@} @@ -99,8 +100,8 @@ protected: TopoShape makeShellFromUpToShape(TopoShape shape, TopoShape sketchshape, gp_Dir dir); /** - * Disables settings that are not valid for the current method - */ + * Disables settings that are not valid for the current method + */ void updateProperties(); TopoShape generateSingleExtrusionSide( @@ -108,17 +109,17 @@ protected: const std::string& method, double length, double taperAngleDeg, - App::PropertyLinkSub& upToFacePropHandle, // e.g., &UpToFace or &UpToFace2 + App::PropertyLinkSub& upToFacePropHandle, // e.g., &UpToFace or &UpToFace2 App::PropertyLinkSubList& upToShapePropHandle, // e.g., &UpToShape or &UpToShape2 gp_Dir dir, double offsetVal, bool makeFace, - const TopoShape& base // The base shape for context (global CS) + const TopoShape& base // The base shape for context (global CS) ); }; -} //namespace PartDesign +} // namespace PartDesign ENABLE_BITMASK_OPERATORS(PartDesign::FeatureExtrude::ExtrudeOption) -#endif // PARTDESIGN_FEATURE_EXTRUDE_H +#endif // PARTDESIGN_FEATURE_EXTRUDE_H diff --git a/src/Mod/PartDesign/App/FeatureFillet.cpp b/src/Mod/PartDesign/App/FeatureFillet.cpp index e3755c3c73..3b2ab043ef 100644 --- a/src/Mod/PartDesign/App/FeatureFillet.cpp +++ b/src/Mod/PartDesign/App/FeatureFillet.cpp @@ -20,15 +20,15 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -42,28 +42,38 @@ using namespace PartDesign; PROPERTY_SOURCE(PartDesign::Fillet, PartDesign::DressUp) -const App::PropertyQuantityConstraint::Constraints floatRadius = {0.0, std::numeric_limits::max(), 0.1}; +const App::PropertyQuantityConstraint::Constraints floatRadius + = {0.0, std::numeric_limits::max(), 0.1}; Fillet::Fillet() { ADD_PROPERTY_TYPE(Radius, (1.0), "Fillet", App::Prop_None, "Fillet radius."); Radius.setUnit(Base::Unit::Length); Radius.setConstraints(&floatRadius); - ADD_PROPERTY_TYPE(UseAllEdges, (false), "Fillet", App::Prop_None, - "Fillet all edges if true, else use only those edges in Base property.\n" - "If true, then this overrides any edge changes made to the Base property or in the dialog.\n"); + ADD_PROPERTY_TYPE( + UseAllEdges, + (false), + "Fillet", + App::Prop_None, + "Fillet all edges if true, else use only those edges in Base property.\n" + "If true, then this overrides any edge changes made to the Base property or in the " + "dialog.\n" + ); } short Fillet::mustExecute() const { - if (Placement.isTouched() || Radius.isTouched()) + if (Placement.isTouched() || Radius.isTouched()) { return 1; + } return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Fillet::execute() +App::DocumentObjectExecReturn* Fillet::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } Part::TopoShape baseShape; @@ -79,14 +89,16 @@ App::DocumentObjectExecReturn *Fillet::execute() : getContinuousEdges(baseShape); if (edges.empty()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Fillet not possible on selected shapes")); + QT_TRANSLATE_NOOP("Exception", "Fillet not possible on selected shapes") + ); } double radius = Radius.getValue(); if (radius <= 0) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Fillet radius must be greater than zero")); + QT_TRANSLATE_NOOP("Exception", "Fillet radius must be greater than zero") + ); } this->positionByBaseFeature(); @@ -96,24 +108,30 @@ App::DocumentObjectExecReturn *Fillet::execute() shape.makeElementFillet(baseShape, edges, Radius.getValue(), Radius.getValue()); if (shape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Resulting shape is null")); + QT_TRANSLATE_NOOP("Exception", "Resulting shape is null") + ); } TopTools_ListOfShape aLarg; aLarg.Append(baseShape.getShape()); if (!BRepAlgo::IsValid(aLarg, shape.getShape(), Standard_False, Standard_False)) { ShapeFix_ShapeTolerance aSFT; - aSFT.LimitTolerance(shape.getShape(), - Precision::Confusion(), - Precision::Confusion(), - TopAbs_SHAPE); + aSFT.LimitTolerance( + shape.getShape(), + Precision::Confusion(), + Precision::Confusion(), + TopAbs_SHAPE + ); } // store shape before refinement this->rawShape = shape; shape = refineShapeIfActive(shape); if (!isSingleSolidRuleSatisfied(shape.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } shape = getSolid(shape); @@ -125,15 +143,15 @@ App::DocumentObjectExecReturn *Fillet::execute() } } -void Fillet::Restore(Base::XMLReader &reader) +void Fillet::Restore(Base::XMLReader& reader) { DressUp::Restore(reader); } -void Fillet::handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) +void Fillet::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) { - if (prop && strcmp(TypeName,"App::PropertyFloatConstraint") == 0 && - strcmp(prop->getTypeId().getName(), "App::PropertyQuantityConstraint") == 0) { + if (prop && strcmp(TypeName, "App::PropertyFloatConstraint") == 0 + && strcmp(prop->getTypeId().getName(), "App::PropertyQuantityConstraint") == 0) { App::PropertyFloatConstraint p; p.Restore(reader); static_cast(prop)->setValue(p.getValue()); @@ -142,5 +160,3 @@ void Fillet::handleChangedPropertyType(Base::XMLReader &reader, const char * Typ DressUp::handleChangedPropertyType(reader, TypeName, prop); } } - - diff --git a/src/Mod/PartDesign/App/FeatureFillet.h b/src/Mod/PartDesign/App/FeatureFillet.h index 0bc2f54157..1fc101a363 100644 --- a/src/Mod/PartDesign/App/FeatureFillet.h +++ b/src/Mod/PartDesign/App/FeatureFillet.h @@ -31,7 +31,7 @@ namespace PartDesign { -class PartDesignExport Fillet : public DressUp +class PartDesignExport Fillet: public DressUp { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Fillet); @@ -44,20 +44,25 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderFillet"; } //@} protected: - void Restore(Base::XMLReader &reader) override; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void Restore(Base::XMLReader& reader) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; }; -} //namespace Part +} // namespace PartDesign -#endif // PARTDESIGN_FEATUREFILLET_H +#endif // PARTDESIGN_FEATUREFILLET_H diff --git a/src/Mod/PartDesign/App/FeatureGroove.cpp b/src/Mod/PartDesign/App/FeatureGroove.cpp index fd042cdcd5..18e6d6d935 100644 --- a/src/Mod/PartDesign/App/FeatureGroove.cpp +++ b/src/Mod/PartDesign/App/FeatureGroove.cpp @@ -21,13 +21,13 @@ ******************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -37,15 +37,17 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ /* TRANSLATOR PartDesign::Groove */ -const char* Groove::TypeEnums[]= {"Angle", "ThroughAll", "UpToFirst", "UpToFace", "TwoAngles", nullptr}; +const char* Groove::TypeEnums[] + = {"Angle", "ThroughAll", "UpToFirst", "UpToFace", "TwoAngles", nullptr}; PROPERTY_SOURCE(PartDesign::Groove, PartDesign::ProfileBased) -const App::PropertyAngle::Constraints Groove::floatAngle = { 0.0, 360.0, 1.0 }; +const App::PropertyAngle::Constraints Groove::floatAngle = {0.0, 360.0, 1.0}; Groove::Groove() { @@ -53,9 +55,21 @@ Groove::Groove() ADD_PROPERTY_TYPE(Type, (0L), "Groove", App::Prop_None, "Groove type"); Type.setEnums(TypeEnums); - ADD_PROPERTY_TYPE(Base, (Base::Vector3d(0.0f,0.0f,0.0f)), "Groove", App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), "Base"); - ADD_PROPERTY_TYPE(Axis, (Base::Vector3d(0.0f,1.0f,0.0f)), "Groove", App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), "Axis"); - ADD_PROPERTY_TYPE(Angle, (360.0),"Groove", App::Prop_None, "Angle"); + ADD_PROPERTY_TYPE( + Base, + (Base::Vector3d(0.0f, 0.0f, 0.0f)), + "Groove", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), + "Base" + ); + ADD_PROPERTY_TYPE( + Axis, + (Base::Vector3d(0.0f, 1.0f, 0.0f)), + "Groove", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), + "Axis" + ); + ADD_PROPERTY_TYPE(Angle, (360.0), "Groove", App::Prop_None, "Angle"); ADD_PROPERTY_TYPE(Angle2, (0.0), "Groove", App::Prop_None, "Groove length in 2nd direction"); ADD_PROPERTY_TYPE(UpToFace, (nullptr), "Groove", App::Prop_None, "Face where groove will end"); Angle.setConstraints(&floatAngle); @@ -64,20 +78,18 @@ Groove::Groove() short Groove::mustExecute() const { - if (Placement.isTouched() || - ReferenceAxis.isTouched() || - Axis.isTouched() || - Base.isTouched() || - UpToFace.isTouched() || - Angle.isTouched() || - Angle2.isTouched()) + if (Placement.isTouched() || ReferenceAxis.isTouched() || Axis.isTouched() || Base.isTouched() + || UpToFace.isTouched() || Angle.isTouched() || Angle2.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn *Groove::execute() +App::DocumentObjectExecReturn* Groove::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } constexpr double maxDegree = 360.0; auto method = methodFromString(Type.getValueAsString()); @@ -86,19 +98,22 @@ App::DocumentObjectExecReturn *Groove::execute() double angleDeg = Angle.getValue(); if (angleDeg > maxDegree) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Angle of groove too large")); + QT_TRANSLATE_NOOP("Exception", "Angle of groove too large") + ); } double angle = Base::toRadians(angleDeg); if (angle < Precision::Angular() && method == RevolMethod::Angle) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Angle of groove too small")); + QT_TRANSLATE_NOOP("Exception", "Angle of groove too small") + ); } double angle2 = Base::toRadians(Angle2.getValue()); if (std::fabs(angle + angle2) < Precision::Angular() && method == RevolMethod::TwoAngles) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Angles of groove nullify each other")); + QT_TRANSLATE_NOOP("Exception", "Angles of groove nullify each other") + ); } TopoShape sketchshape = getTopoShapeVerifiedFace(); @@ -128,14 +143,16 @@ App::DocumentObjectExecReturn *Groove::execute() if (v.IsNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Reference axis is invalid")); + QT_TRANSLATE_NOOP("Exception", "Reference axis is invalid") + ); } gp_Dir dir(v.x, v.y, v.z); if (sketchshape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Creating a face from sketch failed")); + QT_TRANSLATE_NOOP("Exception", "Creating a face from sketch failed") + ); } this->positionByPrevious(); @@ -151,7 +168,8 @@ App::DocumentObjectExecReturn *Groove::execute() for (; xp.More(); xp.Next()) { if (checkLineCrossesFace(gp_Lin(pnt, dir), TopoDS::Face(xp.Current()))) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Revolve axis intersects the sketch")); + QT_TRANSLATE_NOOP("Exception", "Revolve axis intersects the sketch") + ); } } @@ -161,7 +179,7 @@ App::DocumentObjectExecReturn *Groove::execute() try { supportface = getSupportFace(); } - catch(...) { + catch (...) { // do nothing, null shape is handled below } @@ -175,7 +193,8 @@ App::DocumentObjectExecReturn *Groove::execute() } else { throw Base::RuntimeError( - "ProfileBased: Revolution up to first/last is not yet supported"); + "ProfileBased: Revolution up to first/last is not yet supported" + ); } if (Reversed.getValue()) { @@ -188,14 +207,16 @@ App::DocumentObjectExecReturn *Groove::execute() } try { - result = base.makeElementRevolution(base, - TopoDS::Face(sketchshape.getShape()), - gp_Ax1(pnt, dir), - TopoDS::Face(supportface.getShape()), - TopoDS::Face(upToFace.getShape()), - nullptr, - Part::RevolMode::CutFromBase, - Standard_True); + result = base.makeElementRevolution( + base, + TopoDS::Face(sketchshape.getShape()), + gp_Ax1(pnt, dir), + TopoDS::Face(supportface.getShape()), + TopoDS::Face(upToFace.getShape()), + nullptr, + Part::RevolMode::CutFromBase, + Standard_True + ); } catch (Standard_Failure&) { return new App::DocumentObjectExecReturn("Could not revolve the sketch!"); @@ -204,14 +225,16 @@ App::DocumentObjectExecReturn *Groove::execute() else { bool midplane = Midplane.getValue(); bool reversed = Reversed.getValue(); - generateRevolution(result, - sketchshape.getShape(), - gp_Ax1(pnt, dir), - angle, - angle2, - midplane, - reversed, - method); + generateRevolution( + result, + sketchshape.getShape(), + gp_Ax1(pnt, dir), + angle, + angle2, + midplane, + reversed, + method + ); } if (!result.isNull()) { @@ -228,14 +251,18 @@ App::DocumentObjectExecReturn *Groove::execute() result = refineShapeIfActive(result); } if (!isSingleSolidRuleSatisfied(result.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } result = getSolid(result); this->Shape.setValue(result); } else { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Could not revolve the sketch!")); + QT_TRANSLATE_NOOP("Exception", "Could not revolve the sketch!") + ); } // eventually disable some settings that are not valid for the current method @@ -246,10 +273,11 @@ App::DocumentObjectExecReturn *Groove::execute() catch (Standard_Failure& e) { if (std::string(e.GetMessageString()) == "TopoDS::Face") { - return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", - "Could not create face from sketch.\n" - "Intersecting sketch entities in a sketch are not allowed.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Could not create face from sketch.\n" + "Intersecting sketch entities in a sketch are not allowed." + )); } else { return new App::DocumentObjectExecReturn(e.GetMessageString()); @@ -264,7 +292,8 @@ bool Groove::suggestReversed() { try { updateAxis(); - } catch (const Base::Exception&) { + } + catch (const Base::Exception&) { return false; } @@ -273,44 +302,53 @@ bool Groove::suggestReversed() void Groove::updateAxis() { - App::DocumentObject *pcReferenceAxis = ReferenceAxis.getValue(); - const std::vector &subReferenceAxis = ReferenceAxis.getSubValues(); + App::DocumentObject* pcReferenceAxis = ReferenceAxis.getValue(); + const std::vector& subReferenceAxis = ReferenceAxis.getSubValues(); Base::Vector3d base; Base::Vector3d dir; getAxis(pcReferenceAxis, subReferenceAxis, base, dir, ForbiddenAxis::NotParallelWithNormal); - Base.setValue(base.x,base.y,base.z); - Axis.setValue(dir.x,dir.y,dir.z); + Base.setValue(base.x, base.y, base.z); + Axis.setValue(dir.x, dir.y, dir.z); } Groove::RevolMethod Groove::methodFromString(const std::string& methodStr) { - if (methodStr == "Angle") + if (methodStr == "Angle") { return RevolMethod::Angle; - if (methodStr == "UpToLast") + } + if (methodStr == "UpToLast") { return RevolMethod::ToLast; - if (methodStr == "ThroughAll") + } + if (methodStr == "ThroughAll") { return RevolMethod::ThroughAll; - if (methodStr == "UpToFirst") + } + if (methodStr == "UpToFirst") { return RevolMethod::ToFirst; - if (methodStr == "UpToFace") + } + if (methodStr == "UpToFace") { return RevolMethod::ToFace; - if (methodStr == "TwoAngles") + } + if (methodStr == "TwoAngles") { return RevolMethod::TwoAngles; + } throw Base::ValueError("Groove:: No such method"); } -void Groove::generateRevolution(TopoShape& revol, - const TopoShape& sketchshape, - const gp_Ax1& axis, - const double angle, - const double angle2, - const bool midplane, - const bool reversed, - RevolMethod method) +void Groove::generateRevolution( + TopoShape& revol, + const TopoShape& sketchshape, + const gp_Ax1& axis, + const double angle, + const double angle2, + const bool midplane, + const bool reversed, + RevolMethod method +) { - if (method == RevolMethod::Angle || method == RevolMethod::TwoAngles || method == RevolMethod::ThroughAll) { + if (method == RevolMethod::Angle || method == RevolMethod::TwoAngles + || method == RevolMethod::ThroughAll) { double angleTotal = angle; double angleOffset = 0.; @@ -327,8 +365,9 @@ void Groove::generateRevolution(TopoShape& revol, angleOffset = -angle / 2; } - if (fabs(angleTotal) < Precision::Angular()) + if (fabs(angleTotal) < Precision::Angular()) { throw Base::ValueError("Cannot create a revolution with zero angle."); + } gp_Ax1 revolAx(axis); if (reversed) { @@ -347,28 +386,41 @@ void Groove::generateRevolution(TopoShape& revol, // BRepPrimAPI is the only option that allows use of this shape for patterns. // See https://forum.freecadweb.org/viewtopic.php?f=8&t=70185&p=611673#p611673. revol = from; - revol = revol.makeElementRevolve(revolAx,angleTotal); + revol = revol.makeElementRevolve(revolAx, angleTotal); revol.Tag = -getID(); - } else { + } + else { std::stringstream str; str << "ProfileBased: Internal error: Unknown method for generateRevolution()"; throw Base::RuntimeError(str.str()); } } -void Groove::generateRevolution(TopoShape& revol, - const TopoShape& baseshape, - const TopoDS_Shape& profileshape, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const gp_Ax1& axis, - RevolMethod method, - RevolMode Mode, - Standard_Boolean Modify) +void Groove::generateRevolution( + TopoShape& revol, + const TopoShape& baseshape, + const TopoDS_Shape& profileshape, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const gp_Ax1& axis, + RevolMethod method, + RevolMode Mode, + Standard_Boolean Modify +) { - if (method == RevolMethod::ToFirst || method == RevolMethod::ToFace || method == RevolMethod::ToLast) { - revol = revol.makeElementRevolution(baseshape, profileshape, axis, supportface, uptoface, nullptr, - static_cast(Mode), Modify, nullptr); + if (method == RevolMethod::ToFirst || method == RevolMethod::ToFace + || method == RevolMethod::ToLast) { + revol = revol.makeElementRevolution( + baseshape, + profileshape, + axis, + supportface, + uptoface, + nullptr, + static_cast(Mode), + Modify, + nullptr + ); } else { std::stringstream str; @@ -418,5 +470,4 @@ void Groove::updateProperties(RevolMethod method) UpToFace.setReadOnly(!isUpToFaceEnabled); } -} - +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureGroove.h b/src/Mod/PartDesign/App/FeatureGroove.h index 9856fc1e12..5edbcbd04f 100644 --- a/src/Mod/PartDesign/App/FeatureGroove.h +++ b/src/Mod/PartDesign/App/FeatureGroove.h @@ -30,7 +30,7 @@ namespace PartDesign { -class PartDesignExport Groove : public ProfileBased +class PartDesignExport Groove: public ProfileBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Groove); @@ -40,27 +40,28 @@ public: App::PropertyEnumeration Type; App::PropertyVector Base; App::PropertyVector Axis; - App::PropertyAngle Angle; - App::PropertyAngle Angle2; + App::PropertyAngle Angle; + App::PropertyAngle Angle2; /** if this property is set to a valid link, both Axis and Base properties * are calculated according to the linked line - */ + */ App::PropertyLinkSub ReferenceAxis; /** @name methods override feature */ //@{ /** Recalculate the feature - * Revolves the Sketch around the given Axis (with basepoint Base) - * The angle of the revolution is given by Angle. - * If Midplane is true, then the revolution will extend for half of Angle on both sides of the sketch plane. - * If Reversed is true then the direction of revolution will be reversed. - * The created material will be cut out of the sketch support - */ - App::DocumentObjectExecReturn *execute() override; + * Revolves the Sketch around the given Axis (with basepoint Base) + * The angle of the revolution is given by Angle. + * If Midplane is true, then the revolution will extend for half of Angle on both sides of the + * sketch plane. If Reversed is true then the direction of revolution will be reversed. The + * created material will be cut out of the sketch support + */ + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderGroove"; } //@} @@ -68,7 +69,8 @@ public: /// suggests a value for Reversed flag so that material is always removed from the support bool suggestReversed(); - enum class RevolMethod { + enum class RevolMethod + { Angle, ThroughAll, ToLast = ThroughAll, @@ -84,7 +86,8 @@ protected: static const App::PropertyAngle::Constraints floatAngle; // See BRepFeat_MakeRevol - enum RevolMode { + enum RevolMode + { CutFromBase = 0, FuseWithBase = 1, None = 2 @@ -95,28 +98,32 @@ protected: /** * Generates a [groove] of the input sketchshape and stores it in the given \a revol. */ - void generateRevolution(TopoShape& revol, - const TopoShape& sketchshape, - const gp_Ax1& ax1, - const double angle, - const double angle2, - const bool midplane, - const bool reversed, - RevolMethod method); + void generateRevolution( + TopoShape& revol, + const TopoShape& sketchshape, + const gp_Ax1& ax1, + const double angle, + const double angle2, + const bool midplane, + const bool reversed, + RevolMethod method + ); /** * Generates a [groove] of the input \a profileshape. * It will be a stand-alone solid created with BRepFeat_MakeRevol. */ - void generateRevolution(TopoShape& revol, - const TopoShape& baseshape, - const TopoDS_Shape& profileshape, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const gp_Ax1& ax1, - RevolMethod method, - RevolMode Mode, - Standard_Boolean Modify); + void generateRevolution( + TopoShape& revol, + const TopoShape& baseshape, + const TopoDS_Shape& profileshape, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const gp_Ax1& ax1, + RevolMethod method, + RevolMode Mode, + Standard_Boolean Modify + ); /** * Disables settings that are not valid for the current method @@ -127,7 +134,7 @@ private: static const char* TypeEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Groove_H +#endif // PART_Groove_H diff --git a/src/Mod/PartDesign/App/FeatureHelix.cpp b/src/Mod/PartDesign/App/FeatureHelix.cpp index 8b3d807b84..df1cecb4ab 100644 --- a/src/Mod/PartDesign/App/FeatureHelix.cpp +++ b/src/Mod/PartDesign/App/FeatureHelix.cpp @@ -20,48 +20,51 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include -# include -# include +#include +#include -# include "FeatureHelix.h" +#include "FeatureHelix.h" using namespace PartDesign; -const char* Helix::ModeEnums[] = { "pitch-height-angle", "pitch-turns-angle", "height-turns-angle", "height-turns-growth", nullptr }; +const char* Helix::ModeEnums[] + = {"pitch-height-angle", "pitch-turns-angle", "height-turns-angle", "height-turns-growth", nullptr}; PROPERTY_SOURCE(PartDesign::Helix, PartDesign::ProfileBased) // we purposely use not FLT_MAX because this would not be computable -const App::PropertyFloatConstraint::Constraints Helix::floatTurns = { Precision::Confusion(), std::numeric_limits::max(), 1.0 }; -const App::PropertyFloatConstraint::Constraints Helix::floatTolerance = { 0.1, std::numeric_limits::max(), 1.0 }; -const App::PropertyAngle::Constraints Helix::floatAngle = { -89.0, 89.0, 1.0 }; +const App::PropertyFloatConstraint::Constraints Helix::floatTurns + = {Precision::Confusion(), std::numeric_limits::max(), 1.0}; +const App::PropertyFloatConstraint::Constraints Helix::floatTolerance + = {0.1, std::numeric_limits::max(), 1.0}; +const App::PropertyAngle::Constraints Helix::floatAngle = {-89.0, 89.0, 1.0}; Helix::Helix() { @@ -69,43 +72,141 @@ Helix::Helix() auto initialMode = HelixMode::pitch_height_angle; const char* group = "Helix"; - ADD_PROPERTY_TYPE(Base, (Base::Vector3d(0.0, 0.0, 0.0)), group, App::Prop_ReadOnly, - QT_TRANSLATE_NOOP("App::Property", "The center point of the helix' start; derived from the reference axis.")); - ADD_PROPERTY_TYPE(Axis, (Base::Vector3d(0.0, 1.0, 0.0)), group, App::Prop_ReadOnly, - QT_TRANSLATE_NOOP("App::Property", "The helix' direction; derived from the reference axis.")); - ADD_PROPERTY_TYPE(ReferenceAxis, (nullptr), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The reference axis of the helix.")); - ADD_PROPERTY_TYPE(Mode, (long(initialMode)), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The helix input mode specifies which properties are set by the user.\n" - "Dependent properties are then calculated.")); + ADD_PROPERTY_TYPE( + Base, + (Base::Vector3d(0.0, 0.0, 0.0)), + group, + App::Prop_ReadOnly, + QT_TRANSLATE_NOOP( + "App::Property", + "The center point of the helix' start; derived from the reference axis." + ) + ); + ADD_PROPERTY_TYPE( + Axis, + (Base::Vector3d(0.0, 1.0, 0.0)), + group, + App::Prop_ReadOnly, + QT_TRANSLATE_NOOP("App::Property", "The helix' direction; derived from the reference axis.") + ); + ADD_PROPERTY_TYPE( + ReferenceAxis, + (nullptr), + group, + App::Prop_None, + QT_TRANSLATE_NOOP("App::Property", "The reference axis of the helix.") + ); + ADD_PROPERTY_TYPE( + Mode, + (long(initialMode)), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "The helix input mode specifies which properties are set by the user.\n" + "Dependent properties are then calculated." + ) + ); Mode.setEnums(ModeEnums); - ADD_PROPERTY_TYPE(Pitch, (10.0), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The axial distance between two turns.")); - ADD_PROPERTY_TYPE(Height, (30.0), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The height of the helix' path, not accounting for the extent of the profile.")); - ADD_PROPERTY_TYPE(Turns, (3.0), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The number of turns in the helix.")); + ADD_PROPERTY_TYPE( + Pitch, + (10.0), + group, + App::Prop_None, + QT_TRANSLATE_NOOP("App::Property", "The axial distance between two turns.") + ); + ADD_PROPERTY_TYPE( + Height, + (30.0), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "The height of the helix' path, not accounting for the extent of the profile." + ) + ); + ADD_PROPERTY_TYPE( + Turns, + (3.0), + group, + App::Prop_None, + QT_TRANSLATE_NOOP("App::Property", "The number of turns in the helix.") + ); Turns.setConstraints(&floatTurns); - ADD_PROPERTY_TYPE(Angle, (0.0), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The angle of the cone that forms a hull around the helix.\n" + ADD_PROPERTY_TYPE( + Angle, + (0.0), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "The angle of the cone that forms a hull around the helix.\n" "Non-zero values turn the helix into a conical spiral.\n" - "Positive values make the radius grow, negative shrinks.")); + "Positive values make the radius grow, negative shrinks." + ) + ); Angle.setConstraints(&floatAngle); - ADD_PROPERTY_TYPE(Growth, (0.0), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "The growth of the helix' radius per turn.\n" - "Non-zero values turn the helix into a conical spiral.")); - ADD_PROPERTY_TYPE(LeftHanded, (false), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "Sets the turning direction to left handed,\n" - "i.e. counter-clockwise when moving along its axis.")); - ADD_PROPERTY_TYPE(Reversed, (false), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "Determines whether the helix points in the opposite direction of the axis.")); - ADD_PROPERTY_TYPE(Outside, (false), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "If set, the result will be the intersection of the profile and the preexisting body.")); - ADD_PROPERTY_TYPE(HasBeenEdited, (false), group, App::Prop_Hidden, - QT_TRANSLATE_NOOP("App::Property", "If false, the tool will propose an initial value for the pitch based on the profile bounding box,\n" - "so that self intersection is avoided.")); - ADD_PROPERTY_TYPE(Tolerance, (0.1), group, App::Prop_None, - QT_TRANSLATE_NOOP("App::Property", "Fusion Tolerance for the Helix, increase if helical shape does not merge nicely with part.")); + ADD_PROPERTY_TYPE( + Growth, + (0.0), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "The growth of the helix' radius per turn.\n" + "Non-zero values turn the helix into a conical spiral." + ) + ); + ADD_PROPERTY_TYPE( + LeftHanded, + (false), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "Sets the turning direction to left handed,\n" + "i.e. counter-clockwise when moving along its axis." + ) + ); + ADD_PROPERTY_TYPE( + Reversed, + (false), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "Determines whether the helix points in the opposite direction of the axis." + ) + ); + ADD_PROPERTY_TYPE( + Outside, + (false), + group, + App::Prop_None, + QT_TRANSLATE_NOOP( + "App::Property", + "If set, the result will be the intersection of the profile and the preexisting body." + ) + ); + ADD_PROPERTY_TYPE( + HasBeenEdited, + (false), + group, + App::Prop_Hidden, + QT_TRANSLATE_NOOP( + "App::Property", + "If false, the tool will propose an initial value for the pitch based on the profile " + "bounding box,\n" + "so that self intersection is avoided." + ) + ); + ADD_PROPERTY_TYPE( + Tolerance, + (0.1), + group, + App::Prop_None, + QT_TRANSLATE_NOOP("App::Property", "Fusion Tolerance for the Helix, increase if helical shape does not merge nicely with part.") + ); Tolerance.setConstraints(&floatTolerance); setReadWriteStatusForMode(initialMode); @@ -113,56 +214,80 @@ Helix::Helix() short Helix::mustExecute() const { - if (Placement.isTouched() || - ReferenceAxis.isTouched() || - Axis.isTouched() || - Base.isTouched() || - Angle.isTouched()) + if (Placement.isTouched() || ReferenceAxis.isTouched() || Axis.isTouched() || Base.isTouched() + || Angle.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } App::DocumentObjectExecReturn* Helix::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } // Validate and normalize parameters HelixMode mode = static_cast(Mode.getValue()); if (mode == HelixMode::pitch_height_angle) { - if (Pitch.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Pitch too small!")); - if (Height.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: height too small!")); + if (Pitch.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Pitch too small!") + ); + } + if (Height.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: height too small!") + ); + } Turns.setValue(Height.getValue() / Pitch.getValue()); Growth.setValue(Pitch.getValue() * tan(Base::toRadians(Angle.getValue()))); } else if (mode == HelixMode::pitch_turns_angle) { - if (Pitch.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: pitch too small!")); - if (Turns.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: turns too small!")); + if (Pitch.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: pitch too small!") + ); + } + if (Turns.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: turns too small!") + ); + } Height.setValue(Turns.getValue() * Pitch.getValue()); Growth.setValue(Pitch.getValue() * tan(Base::toRadians(Angle.getValue()))); } else if (mode == HelixMode::height_turns_angle) { - if (Height.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: height too small!")); - if (Turns.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: turns too small!")); + if (Height.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: height too small!") + ); + } + if (Turns.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: turns too small!") + ); + } Pitch.setValue(Height.getValue() / Turns.getValue()); Growth.setValue(Pitch.getValue() * tan(Base::toRadians(Angle.getValue()))); } else if (mode == HelixMode::height_turns_growth) { - if (Turns.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: turns too small!")); + if (Turns.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: turns too small!") + ); + } if ((Height.getValue() < Precision::Confusion()) - && (abs(Growth.getValue()) < Precision::Confusion()) - && Turns.getValue() > 1.0) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: either height or growth must not be zero!")); + && (abs(Growth.getValue()) < Precision::Confusion()) && Turns.getValue() > 1.0) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: either height or growth must not be zero!") + ); + } Pitch.setValue(Height.getValue() / Turns.getValue()); if (Height.getValue() > 0) { - Angle.setValue(Base::toDegrees(atan( - Turns.getValue() * Growth.getValue() / Height.getValue()))); + Angle.setValue( + Base::toDegrees(atan(Turns.getValue() * Growth.getValue() / Height.getValue())) + ); } else { // On purpose, we're doing nothing here; the else-branch is just for this comment. @@ -172,10 +297,12 @@ App::DocumentObjectExecReturn* Helix::execute() } } else { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: unsupported mode")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: unsupported mode") + ); } - TopoDS_Shape sketchshape; // Fixme: Should this be TopoShape here and below? + TopoDS_Shape sketchshape; // Fixme: Should this be TopoShape here and below? try { sketchshape = getVerifiedFace(); } @@ -183,17 +310,24 @@ App::DocumentObjectExecReturn* Helix::execute() return new App::DocumentObjectExecReturn(e.what()); } - if (sketchshape.IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: No valid sketch or face")); + if (sketchshape.IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: No valid sketch or face") + ); + } else { - //TODO: currently we only allow planar faces. the reason for this is that with other faces in front, we could - //not use the current simulate approach and build the start and end face from the wires. As the shell - //begins always at the spine and not the profile, the sketchshape cannot be used directly as front face. - //We would need a method to translate the front shape to match the shell starting position somehow... + // TODO: currently we only allow planar faces. the reason for this is that with other faces + // in front, we could not use the current simulate approach and build the start and end face + // from the wires. As the shell begins always at the spine and not the profile, the + // sketchshape cannot be used directly as front face. We would need a method to translate + // the front shape to match the shell starting position somehow... TopoDS_Face face = TopoDS::Face(sketchshape); BRepAdaptor_Surface adapt(face); - if (adapt.GetType() != GeomAbs_Plane) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Face must be planar")); + if (adapt.GetType() != GeomAbs_Plane) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Face must be planar") + ); + } } // if the Base property has a valid shape, fuse the AddShape into it @@ -224,10 +358,11 @@ App::DocumentObjectExecReturn* Helix::execute() // generate the helix path TopoDS_Shape path; - if (Angle.getValue()==0.){ + if (Angle.getValue() == 0.) { // breaking the path at each turn prevents an OCC issue path = generateHelixPath(); - } else { + } + else { // don't break the path or the generated solid is invalid path = generateHelixPath(1000.); } @@ -237,15 +372,17 @@ App::DocumentObjectExecReturn* Helix::execute() Bnd_Box bounds; BRepBndLib::Add(path, bounds); - double size=sqrt(bounds.SquareExtent()); + double size = sqrt(bounds.SquareExtent()); ShapeFix_ShapeTolerance fix; - fix.LimitTolerance(path, Precision::Confusion() * 1e-6 * size ); // needed to produce valid Pipe for very big parts + fix.LimitTolerance(path, Precision::Confusion() * 1e-6 * size); // needed to produce valid + // Pipe for very big parts // We introduce final part tolerance with the second call to LimitTolerance below, however - // OCCT has a bug where the side-walls of the Pipe disappear with very large (km range) pieces - // increasing a tiny bit of extra tolerance to the path fixes this. This will in any case - // be less than the tolerance lower limit below, but sufficient to avoid the bug + // OCCT has a bug where the side-walls of the Pipe disappear with very large (km range) + // pieces increasing a tiny bit of extra tolerance to the path fixes this. This will in any + // case be less than the tolerance lower limit below, but sufficient to avoid the bug - BRepOffsetAPI_MakePipe mkPS(TopoDS::Wire(path), face, GeomFill_Trihedron::GeomFill_IsFrenet, Standard_False); + BRepOffsetAPI_MakePipe + mkPS(TopoDS::Wire(path), face, GeomFill_Trihedron::GeomFill_IsFrenet, Standard_False); result = mkPS.Shape(); BRepClass3d_SolidClassifier SC(result); @@ -254,7 +391,11 @@ App::DocumentObjectExecReturn* Helix::execute() result.Reverse(); } - fix.LimitTolerance(result, Precision::Confusion() * size * Tolerance.getValue() ); // significant precision reduction due to helical approximation - needed to allow fusion to succeed + fix.LimitTolerance( + result, + Precision::Confusion() * size * Tolerance.getValue() + ); // significant precision reduction due to helical approximation - needed to allow fusion + // to succeed // try to auto-fix possible invalid result ShapeFix_Solid fixer; @@ -267,15 +408,19 @@ App::DocumentObjectExecReturn* Helix::execute() if (base.isNull()) { - if (getAddSubType() == FeatureAddSub::Subtractive){ - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: There is nothing to subtract")); + if (getAddSubType() == FeatureAddSub::Subtractive) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: There is nothing to subtract") + ); } if (!isSingleSolidRuleSatisfied(result)) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Result has multiple solids")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Result has multiple solids") + ); } - // store shape before refinement + // store shape before refinement this->rawShape = result; Shape.setValue(getSolid(result)); return App::DocumentObject::StdReturn; @@ -284,19 +429,25 @@ App::DocumentObjectExecReturn* Helix::execute() if (getAddSubType() == FeatureAddSub::Additive) { FCBRepAlgoAPI_Fuse mkFuse(base.getShape(), result); - if (!mkFuse.IsDone()){ - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Adding the helix failed")); + if (!mkFuse.IsDone()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Adding the helix failed") + ); } // we have to get the solids (fuse sometimes creates compounds) TopoShape boolOp = this->getSolid(mkFuse.Shape()); // lets check if the result is a solid - if (boolOp.isNull()){ - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Result is not a solid")); + if (boolOp.isNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Result is not a solid") + ); } if (!isSingleSolidRuleSatisfied(boolOp.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Result has multiple solids")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Result has multiple solids") + ); } // store shape before refinement @@ -310,24 +461,34 @@ App::DocumentObjectExecReturn* Helix::execute() if (Outside.getValue()) { // are we subtracting the inside or the outside of the profile. FCBRepAlgoAPI_Common mkCom(result, base.getShape()); - if (!mkCom.IsDone()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Intersecting the helix failed")); + if (!mkCom.IsDone()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Intersecting the helix failed") + ); + } boolOp = this->getSolid(mkCom.Shape()); - } else { FCBRepAlgoAPI_Cut mkCut(base.getShape(), result); - if (!mkCut.IsDone()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Subtracting the helix failed")); + if (!mkCut.IsDone()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Subtracting the helix failed") + ); + } boolOp = this->getSolid(mkCut.Shape()); } // lets check if the result is a solid - if (boolOp.isNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Result is not a solid")); + if (boolOp.isNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Result is not a solid") + ); + } if (!isSingleSolidRuleSatisfied(boolOp.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Result has multiple solids")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Result has multiple solids") + ); } // store shape before refinement @@ -340,10 +501,14 @@ App::DocumentObjectExecReturn* Helix::execute() } catch (Standard_Failure& e) { - if (std::string(e.GetMessageString()) == "TopoDS::Face") - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Could not create face from sketch")); - else + if (std::string(e.GetMessageString()) == "TopoDS::Face") { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Could not create face from sketch") + ); + } + else { return new App::DocumentObjectExecReturn(e.GetMessageString()); + } } catch (Base::Exception& e) { return new App::DocumentObjectExecReturn(e.what()); @@ -371,8 +536,9 @@ TopoDS_Shape Helix::generateHelixPath(double breakAtTurn) double angle = Angle.getValue(); double growth = Growth.getValue(); - if (fabs(angle) < Precision::Confusion()) + if (fabs(angle) < Precision::Confusion()) { angle = 0.0; + } // get revolve axis Base::Vector3d baseVector = Base.getValue(); @@ -383,9 +549,9 @@ TopoDS_Shape Helix::generateHelixPath(double breakAtTurn) Base::Vector3d normal = getProfileNormal(); Base::Vector3d start = axisVector.Cross(normal); // pointing towards the desired helix start point. - // if our axis is (nearly) aligned with the profile's normal, we're only interested in the "twist" - // of the helix. The actual starting point, and thus the radius, isn't important as long as it's - // somewhere in the profile's plane: an arbitrary vector perpendicular to the normal. + // if our axis is (nearly) aligned with the profile's normal, we're only interested in the + // "twist" of the helix. The actual starting point, and thus the radius, isn't important as long + // as it's somewhere in the profile's plane: an arbitrary vector perpendicular to the normal. if (start.IsNull()) { auto hopefullyNotParallel = Base::Vector3d(1.0, 2.0, 3.0); start = normal.Cross(hopefullyNotParallel); @@ -401,36 +567,42 @@ TopoDS_Shape Helix::generateHelixPath(double breakAtTurn) // Find out in what quadrant relative to the axis the profile is located, and the exact position. Base::Vector3d profileCenter = getProfileCenterPoint(); - // The factor of 100 below ensures that profile size is small compared to the curvature of the helix. - // This improves the issue reported in https://forum.freecad.org/viewtopic.php?f=10&t=65048 + // The factor of 100 below ensures that profile size is small compared to the curvature of the + // helix. This improves the issue reported in + // https://forum.freecad.org/viewtopic.php?f=10&t=65048 double axisOffset = 100.0 * (profileCenter * start - baseVector * start); double radius = std::fabs(axisOffset); bool turned = axisOffset < 0; - // since the factor does not only change the radius but also the path position, we must shift its offset back - // using the square of the factor - double startOffset = 10000.0 * std::fabs((angle <= 0. ? 1. : 0.) * (profileCenter * axisVector) - baseVector * axisVector); + // since the factor does not only change the radius but also the path position, we must shift + // its offset back using the square of the factor + double startOffset = 10000.0 + * std::fabs((angle <= 0. ? 1. : 0.) * (profileCenter * axisVector) - baseVector * axisVector); if (radius < Precision::Confusion()) { // in this case ensure that axis is not in the sketch plane - if (fabs(axisVector * normal) < Precision::Confusion()) + if (fabs(axisVector * normal) < Precision::Confusion()) { throw Base::ValueError("Error: Result is self intersecting"); - radius = 1000.0; //fallback to radius 1000 + } + radius = 1000.0; // fallback to radius 1000 } bool growthMode = std::string(Mode.getValueAsString()).find("growth") != std::string::npos; double radiusTop; - if (growthMode) + if (growthMode) { radiusTop = radius + turns * growth; - else + } + else { radiusTop = radius + height * tan(Base::toRadians(angle)); + } - //build the helix path - TopoDS_Shape path = TopoShape().makeSpiralHelix(radius, radiusTop, height, turns, breakAtTurn, leftHanded); + // build the helix path + TopoDS_Shape path + = TopoShape().makeSpiralHelix(radius, radiusTop, height, turns, breakAtTurn, leftHanded); /* - * The helix wire is created with the axis coinciding with z-axis and the start point at (radius, 0, 0) - * We want to move it so that the axis becomes aligned with "dir" and "pnt", we also want (radius,0,0) to - * map to the sketch plane. + * The helix wire is created with the axis coinciding with z-axis and the start point at + * (radius, 0, 0) We want to move it so that the axis becomes aligned with "dir" and "pnt", we + * also want (radius,0,0) to map to the sketch plane. */ gp_Pnt origo(0.0, 0.0, 0.0); @@ -438,7 +610,8 @@ TopoDS_Shape Helix::generateHelixPath(double breakAtTurn) gp_Dir dir_axis2(1.0, 0.0, 0.0); // pointing towards the helix start point, as created. gp_Trsf mov; - if (abs(startOffset) > 0) { // translate the helix so that the starting point aligns with the profile + if (abs(startOffset) > 0) { // translate the helix so that the starting point aligns with the + // profile mov.SetTranslation(startOffset * gp_Vec(dir_axis1)); TopLoc_Location loc(mov); path.Move(loc); @@ -475,7 +648,8 @@ TopoDS_Shape Helix::generateHelixPath(double breakAtTurn) double Helix::safePitch() { Base::Vector3d axisVec = Axis.getValue(); - Base::Vector3d startVec = axisVec.Cross(getProfileNormal()); // pointing towards the helix start point + Base::Vector3d startVec = axisVec.Cross(getProfileNormal()); // pointing towards the helix + // start point HelixMode mode = static_cast(Mode.getValue()); double growthValue = Growth.getValue(); double turnsValue = Turns.getValue(); @@ -495,8 +669,9 @@ double Helix::safePitch() // Nevertheless, the result is a valid body so it should be valuable for users // to get this correct warning anyway. else { - if (abs(turnsValue) >= 1.0 && abs(growthValue) > 0.0) + if (abs(turnsValue) >= 1.0 && abs(growthValue) > 0.0) { return Precision::Infinite(); + } } } @@ -532,20 +707,24 @@ double Helix::safePitch() // Note: at the moment helices with a growth end with a plane // whose normal is the final direction of the helix path. // In case this might be changed in future, also 1.0 turn would be safe. - if (turnsValue < 1.0) + if (turnsValue < 1.0) { return 0.0; - else + } + else { return pitch0; + } } } else { // if the angle is so large that the distance perpendicular to axisVec // between two turns is larger than the bounding box size in this direction // the pitch can be smaller than pitch0 - if (tan(abs(angle)) * pitch0 > abs(boundingBoxVec * directionStart)) + if (tan(abs(angle)) * pitch0 > abs(boundingBoxVec * directionStart)) { return abs(boundingBoxVec * directionStart) / tan(abs(angle)); - else + } + else { return pitch0; + } } } @@ -611,66 +790,67 @@ void Helix::onChanged(const App::Property* prop) void Helix::setReadWriteStatusForMode(HelixMode inputMode) { - switch (inputMode) - { - case HelixMode::pitch_height_angle: - // primary input: - Pitch.setStatus(App::Property::ReadOnly, false); - Height.setStatus(App::Property::ReadOnly, false); - Angle.setStatus(App::Property::ReadOnly, false); - // derived props: - Turns.setStatus(App::Property::ReadOnly, true); - Growth.setStatus(App::Property::ReadOnly, true); - break; + switch (inputMode) { + case HelixMode::pitch_height_angle: + // primary input: + Pitch.setStatus(App::Property::ReadOnly, false); + Height.setStatus(App::Property::ReadOnly, false); + Angle.setStatus(App::Property::ReadOnly, false); + // derived props: + Turns.setStatus(App::Property::ReadOnly, true); + Growth.setStatus(App::Property::ReadOnly, true); + break; - case HelixMode::pitch_turns_angle: - // primary input: - Pitch.setStatus(App::Property::ReadOnly, false); - Turns.setStatus(App::Property::ReadOnly, false); - Angle.setStatus(App::Property::ReadOnly, false); - // derived props: - Height.setStatus(App::Property::ReadOnly, true); - Growth.setStatus(App::Property::ReadOnly, true); - break; + case HelixMode::pitch_turns_angle: + // primary input: + Pitch.setStatus(App::Property::ReadOnly, false); + Turns.setStatus(App::Property::ReadOnly, false); + Angle.setStatus(App::Property::ReadOnly, false); + // derived props: + Height.setStatus(App::Property::ReadOnly, true); + Growth.setStatus(App::Property::ReadOnly, true); + break; - case HelixMode::height_turns_angle: - // primary input: - Height.setStatus(App::Property::ReadOnly, false); - Turns.setStatus(App::Property::ReadOnly, false); - Angle.setStatus(App::Property::ReadOnly, false); - // derived props: - Pitch.setStatus(App::Property::ReadOnly, true); - Growth.setStatus(App::Property::ReadOnly, true); - break; + case HelixMode::height_turns_angle: + // primary input: + Height.setStatus(App::Property::ReadOnly, false); + Turns.setStatus(App::Property::ReadOnly, false); + Angle.setStatus(App::Property::ReadOnly, false); + // derived props: + Pitch.setStatus(App::Property::ReadOnly, true); + Growth.setStatus(App::Property::ReadOnly, true); + break; - case HelixMode::height_turns_growth: - // primary input: - Height.setStatus(App::Property::ReadOnly, false); - Turns.setStatus(App::Property::ReadOnly, false); - Growth.setStatus(App::Property::ReadOnly, false); - // derived props: - Pitch.setStatus(App::Property::ReadOnly, true); - Angle.setStatus(App::Property::ReadOnly, true); - break; + case HelixMode::height_turns_growth: + // primary input: + Height.setStatus(App::Property::ReadOnly, false); + Turns.setStatus(App::Property::ReadOnly, false); + Growth.setStatus(App::Property::ReadOnly, false); + // derived props: + Pitch.setStatus(App::Property::ReadOnly, true); + Angle.setStatus(App::Property::ReadOnly, true); + break; - default: - Pitch.setStatus(App::Property::ReadOnly, false); - Height.setStatus(App::Property::ReadOnly, false); - Turns.setStatus(App::Property::ReadOnly, false); - Angle.setStatus(App::Property::ReadOnly, false); - Growth.setStatus(App::Property::ReadOnly, false); - break; + default: + Pitch.setStatus(App::Property::ReadOnly, false); + Height.setStatus(App::Property::ReadOnly, false); + Turns.setStatus(App::Property::ReadOnly, false); + Angle.setStatus(App::Property::ReadOnly, false); + Growth.setStatus(App::Property::ReadOnly, false); + break; } } PROPERTY_SOURCE(PartDesign::AdditiveHelix, PartDesign::Helix) -AdditiveHelix::AdditiveHelix() { +AdditiveHelix::AdditiveHelix() +{ addSubType = Additive; Outside.setStatus(App::Property::Hidden, true); } PROPERTY_SOURCE(PartDesign::SubtractiveHelix, PartDesign::Helix) -SubtractiveHelix::SubtractiveHelix() { +SubtractiveHelix::SubtractiveHelix() +{ addSubType = Subtractive; Outside.setStatus(App::Property::Hidden, false); } diff --git a/src/Mod/PartDesign/App/FeatureHelix.h b/src/Mod/PartDesign/App/FeatureHelix.h index 32e41c41fa..9e36d6ba9e 100644 --- a/src/Mod/PartDesign/App/FeatureHelix.h +++ b/src/Mod/PartDesign/App/FeatureHelix.h @@ -31,36 +31,37 @@ namespace PartDesign { -enum class HelixMode { +enum class HelixMode +{ pitch_height_angle, pitch_turns_angle, height_turns_angle, height_turns_growth }; -class PartDesignExport Helix : public ProfileBased +class PartDesignExport Helix: public ProfileBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Helix); public: Helix(); - App::PropertyVector Base; - App::PropertyVector Axis; - App::PropertyLength Pitch; - App::PropertyLength Height; - App::PropertyFloatConstraint Turns; - App::PropertyBool LeftHanded; - App::PropertyAngle Angle; - App::PropertyDistance Growth; + App::PropertyVector Base; + App::PropertyVector Axis; + App::PropertyLength Pitch; + App::PropertyLength Height; + App::PropertyFloatConstraint Turns; + App::PropertyBool LeftHanded; + App::PropertyAngle Angle; + App::PropertyDistance Growth; App::PropertyEnumeration Mode; - App::PropertyBool Outside; - App::PropertyBool HasBeenEdited; - App::PropertyFloatConstraint Tolerance; + App::PropertyBool Outside; + App::PropertyBool HasBeenEdited; + App::PropertyFloatConstraint Tolerance; /** if this property is set to a valid link, both Axis and Base properties * are calculated according to the linked line - */ + */ App::PropertyLinkSub ReferenceAxis; /** @name methods override feature */ @@ -68,7 +69,8 @@ public: App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderHelix"; } //@} @@ -90,7 +92,11 @@ protected: Base::Vector3d getProfileCenterPoint(); // handle changed property types for backward compatibility - void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; @@ -106,22 +112,26 @@ private: }; -class PartDesignExport AdditiveHelix : public Helix { +class PartDesignExport AdditiveHelix: public Helix +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveHelix); + public: AdditiveHelix(); }; -class PartDesignExport SubtractiveHelix : public Helix { +class PartDesignExport SubtractiveHelix: public Helix +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveHelix); + public: SubtractiveHelix(); }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Helix_H +#endif // PART_Helix_H diff --git a/src/Mod/PartDesign/App/FeatureHole.cpp b/src/Mod/PartDesign/App/FeatureHole.cpp index 9c886a64c2..08975ec1a7 100644 --- a/src/Mod/PartDesign/App/FeatureHole.cpp +++ b/src/Mod/PartDesign/App/FeatureHole.cpp @@ -21,32 +21,32 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -66,24 +66,39 @@ FC_LOG_LEVEL_INIT("PartDesign", true, true); -namespace PartDesign { +namespace PartDesign +{ /* TRANSLATOR PartDesign::Hole */ -const char* Hole::DepthTypeEnums[] = { "Dimension", "ThroughAll", /*, "UpToFirst", */ nullptr }; -const char* Hole::ThreadDepthTypeEnums[] = { "Hole Depth", "Dimension", "Tapped (DIN76)", nullptr }; -const char* Hole::ThreadTypeEnums[] = { "None", "ISOMetricProfile", "ISOMetricFineProfile", "UNC", "UNF", "UNEF", "NPT", "BSP", "BSW", "BSF", "ISOTyre", nullptr}; +const char* Hole::DepthTypeEnums[] = {"Dimension", "ThroughAll", /*, "UpToFirst", */ nullptr}; +const char* Hole::ThreadDepthTypeEnums[] = {"Hole Depth", "Dimension", "Tapped (DIN76)", nullptr}; +const char* Hole::ThreadTypeEnums[] = { + "None", + "ISOMetricProfile", + "ISOMetricFineProfile", + "UNC", + "UNF", + "UNEF", + "NPT", + "BSP", + "BSW", + "BSF", + "ISOTyre", + nullptr +}; -const char* Hole::ClearanceNoneEnums[] = { "-", "-", "-", nullptr}; -const char* Hole::ClearanceMetricEnums[] = { "Medium", "Fine", "Coarse", nullptr}; -const char* Hole::ClearanceUTSEnums[] = { "Normal", "Close", "Loose", nullptr }; -const char* Hole::ClearanceOtherEnums[] = { "Normal", "Close", "Wide", nullptr }; -const char* Hole::DrillPointEnums[] = { "Flat", "Angled", nullptr}; +const char* Hole::ClearanceNoneEnums[] = {"-", "-", "-", nullptr}; +const char* Hole::ClearanceMetricEnums[] = {"Medium", "Fine", "Coarse", nullptr}; +const char* Hole::ClearanceUTSEnums[] = {"Normal", "Close", "Loose", nullptr}; +const char* Hole::ClearanceOtherEnums[] = {"Normal", "Close", "Wide", nullptr}; +const char* Hole::DrillPointEnums[] = {"Flat", "Angled", nullptr}; /* "None" profile */ -const char* Hole::HoleCutType_None_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr }; -const char* Hole::ThreadClass_None_Enums[] = { "None", nullptr }; +const char* Hole::HoleCutType_None_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::ThreadClass_None_Enums[] = {"None", nullptr}; /* Sources: http://www.engineeringtoolbox.com/metric-threads-d_777.html @@ -91,564 +106,354 @@ const char* Hole::ThreadClass_None_Enums[] = { "None", nullptr }; */ -const std::vector Hole::threadDescription[] = -{ +const std::vector Hole::threadDescription[] = { /* None */ { - { "---", 6.0, 0.0, 0.0 }, + {"---", 6.0, 0.0, 0.0}, }, /* ISO metric regular */ /* ISO metric threaded Tap-Drill diameters according to ISO 2306 */ // {name, thread diameter, thread pitch, Tap-Drill diameter} { - { "M1x0.25", 1.0, 0.25, 0.75 }, - { "M1.1x0.25", 1.1, 0.25, 0.85 }, - { "M1.2x0.25", 1.2, 0.25, 0.95 }, - { "M1.4x0.3", 1.4, 0.30, 1.10 }, - { "M1.6x0.35", 1.6, 0.35, 1.25 }, - { "M1.8x0.35", 1.8, 0.35, 1.45 }, - { "M2x0.4", 2.0, 0.40, 1.60 }, - { "M2.2x0.45", 2.2, 0.45, 1.75 }, - { "M2.5x0.45", 2.5, 0.45, 2.05 }, - { "M3x0.5", 3.0, 0.50, 2.50 }, - { "M3.5x0.6", 3.5, 0.60, 2.90 }, - { "M4x0.7", 4.0, 0.70, 3.30 }, - { "M4.5x0.75", 4.5, 0.75, 3.70 }, - { "M5x0.8", 5.0, 0.80, 4.20 }, - { "M6x1.0", 6.0, 1.00, 5.00 }, - { "M7x1.0", 7.0, 1.00, 6.00 }, - { "M8x1.25", 8.0, 1.25, 6.80 }, - { "M9x1.25", 9.0, 1.25, 7.80 }, - { "M10x1.5", 10.0, 1.50, 8.50 }, - { "M11x1.5", 11.0, 1.50, 9.50 }, - { "M12x1.75", 12.0, 1.75, 10.20 }, - { "M14x2.0", 14.0, 2.00, 12.00 }, - { "M16x2.0", 16.0, 2.00, 14.00 }, - { "M18x2.5", 18.0, 2.50, 15.50 }, - { "M20x2.5", 20.0, 2.50, 17.50 }, - { "M22x2.5", 22.0, 2.50, 19.50 }, - { "M24x3.0", 24.0, 3.00, 21.00 }, - { "M27x3.0", 27.0, 3.00, 24.00 }, - { "M30x3.5", 30.0, 3.50, 26.50 }, - { "M33x3.5", 33.0, 3.50, 29.50 }, - { "M36x4.0", 36.0, 4.00, 32.00 }, - { "M39x4.0", 39.0, 4.00, 35.00 }, - { "M42x4.5", 42.0, 4.50, 37.50 }, - { "M45x4.5", 45.0, 4.50, 40.50 }, - { "M48x5.0", 48.0, 5.00, 43.00 }, - { "M52x5.0", 52.0, 5.00, 47.00 }, - { "M56x5.5", 56.0, 5.50, 50.50 }, - { "M60x5.5", 60.0, 5.50, 54.50 }, - { "M64x6.0", 64.0, 6.00, 58.00 }, - { "M68x6.0", 68.0, 6.00, 62.00 }, - }, + {"M1x0.25", 1.0, 0.25, 0.75}, {"M1.1x0.25", 1.1, 0.25, 0.85}, + {"M1.2x0.25", 1.2, 0.25, 0.95}, {"M1.4x0.3", 1.4, 0.30, 1.10}, + {"M1.6x0.35", 1.6, 0.35, 1.25}, {"M1.8x0.35", 1.8, 0.35, 1.45}, + {"M2x0.4", 2.0, 0.40, 1.60}, {"M2.2x0.45", 2.2, 0.45, 1.75}, + {"M2.5x0.45", 2.5, 0.45, 2.05}, {"M3x0.5", 3.0, 0.50, 2.50}, + {"M3.5x0.6", 3.5, 0.60, 2.90}, {"M4x0.7", 4.0, 0.70, 3.30}, + {"M4.5x0.75", 4.5, 0.75, 3.70}, {"M5x0.8", 5.0, 0.80, 4.20}, + {"M6x1.0", 6.0, 1.00, 5.00}, {"M7x1.0", 7.0, 1.00, 6.00}, + {"M8x1.25", 8.0, 1.25, 6.80}, {"M9x1.25", 9.0, 1.25, 7.80}, + {"M10x1.5", 10.0, 1.50, 8.50}, {"M11x1.5", 11.0, 1.50, 9.50}, + {"M12x1.75", 12.0, 1.75, 10.20}, {"M14x2.0", 14.0, 2.00, 12.00}, + {"M16x2.0", 16.0, 2.00, 14.00}, {"M18x2.5", 18.0, 2.50, 15.50}, + {"M20x2.5", 20.0, 2.50, 17.50}, {"M22x2.5", 22.0, 2.50, 19.50}, + {"M24x3.0", 24.0, 3.00, 21.00}, {"M27x3.0", 27.0, 3.00, 24.00}, + {"M30x3.5", 30.0, 3.50, 26.50}, {"M33x3.5", 33.0, 3.50, 29.50}, + {"M36x4.0", 36.0, 4.00, 32.00}, {"M39x4.0", 39.0, 4.00, 35.00}, + {"M42x4.5", 42.0, 4.50, 37.50}, {"M45x4.5", 45.0, 4.50, 40.50}, + {"M48x5.0", 48.0, 5.00, 43.00}, {"M52x5.0", 52.0, 5.00, 47.00}, + {"M56x5.5", 56.0, 5.50, 50.50}, {"M60x5.5", 60.0, 5.50, 54.50}, + {"M64x6.0", 64.0, 6.00, 58.00}, {"M68x6.0", 68.0, 6.00, 62.00}, + }, /* ISO metric fine (drill = diameter - pitch) */ - { - { "M1x0.2", 1.0, 0.20, 0.80 }, - { "M1.1x0.2", 1.1, 0.20, 0.90 }, - { "M1.2x0.2", 1.2, 0.20, 1.00 }, - { "M1.4x0.2", 1.4, 0.20, 1.20 }, - { "M1.6x0.2", 1.6, 0.20, 1.40 }, - { "M1.8x0.2", 1.8, 0.20, 1.60 }, - { "M2x0.25", 2.0, 0.25, 1.75 }, - { "M2.2x0.25", 2.2, 0.25, 1.95 }, - { "M2.5x0.35", 2.5, 0.35, 2.15 }, - { "M3x0.35", 3.0, 0.35, 2.65 }, - { "M3.5x0.35", 3.5, 0.35, 3.15 }, - { "M4x0.5", 4.0, 0.50, 3.50 }, - { "M4.5x0.5", 4.5, 0.50, 4.00 }, - { "M5x0.5", 5.0, 0.50, 4.50 }, - { "M5.5x0.5", 5.5, 0.50, 5.00 }, - { "M6x0.75", 6.0, 0.75, 5.25 }, - { "M7x0.75", 7.0, 0.75, 6.25 }, - { "M8x0.75", 8.0, 0.75, 7.25 }, - { "M8x1.0", 8.0, 1.00, 7.00 }, - { "M9x0.75", 9.0, 0.75, 8.25 }, - { "M9x1.0", 9.0, 1.00, 8.00 }, - { "M10x0.75", 10.0, 0.75, 9.25 }, - { "M10x1.0", 10.0, 1.00, 9.00 }, - { "M10x1.25", 10.0, 1.25, 8.75 }, - { "M11x0.75", 11.0, 0.75, 10.25 }, - { "M11x1.0", 11.0, 1.00, 10.00 }, - { "M12x1.0", 12.0, 1.00, 11.00 }, - { "M12x1.25", 12.0, 1.25, 10.75 }, - { "M12x1.5", 12.0, 1.50, 10.50 }, - { "M14x1.0", 14.0, 1.00, 13.00 }, - { "M14x1.25", 14.0, 1.25, 12.75 }, - { "M14x1.5", 14.0, 1.50, 12.50 }, - { "M15x1.0", 15.0, 1.00, 14.00 }, - { "M15x1.5", 15.0, 1.50, 13.50 }, - { "M16x1.0", 16.0, 1.00, 15.00 }, - { "M16x1.5", 16.0, 1.50, 14.50 }, - { "M17x1.0", 17.0, 1.00, 16.00 }, - { "M17x1.5", 17.0, 1.50, 15.50 }, - { "M18x1.0", 18.0, 1.00, 17.00 }, - { "M18x1.5", 18.0, 1.50, 16.50 }, - { "M18x2.0", 18.0, 2.00, 16.00 }, - { "M20x1.0", 20.0, 1.00, 19.00 }, - { "M20x1.5", 20.0, 1.50, 18.50 }, - { "M20x2.0", 20.0, 2.00, 18.00 }, - { "M22x1.0", 22.0, 1.00, 21.00 }, - { "M22x1.5", 22.0, 1.50, 20.50 }, - { "M22x2.0", 22.0, 2.00, 20.00 }, - { "M24x1.0", 24.0, 1.00, 23.00 }, - { "M24x1.5", 24.0, 1.50, 22.50 }, - { "M24x2.0", 24.0, 2.00, 22.00 }, - { "M25x1.0", 25.0, 1.00, 24.00 }, - { "M25x1.5", 25.0, 1.50, 23.50 }, - { "M25x2.0", 25.0, 2.00, 23.00 }, - { "M27x1.0", 27.0, 1.00, 26.00 }, - { "M27x1.5", 27.0, 1.50, 25.50 }, - { "M27x2.0", 27.0, 2.00, 25.00 }, - { "M28x1.0", 28.0, 1.00, 27.00 }, - { "M28x1.5", 28.0, 1.50, 26.50 }, - { "M28x2.0", 28.0, 2.00, 26.00 }, - { "M30x1.0", 30.0, 1.00, 29.00 }, - { "M30x1.5", 30.0, 1.50, 28.50 }, - { "M30x2.0", 30.0, 2.00, 28.00 }, - { "M30x3.0", 30.0, 3.00, 27.00 }, - { "M32x1.5", 32.0, 1.50, 30.50 }, - { "M32x2.0", 32.0, 2.00, 30.00 }, - { "M33x1.5", 33.0, 1.50, 31.50 }, - { "M33x2.0", 33.0, 2.00, 31.00 }, - { "M33x3.0", 33.0, 3.00, 30.00 }, - { "M35x1.5", 35.0, 1.50, 33.50 }, - { "M35x2.0", 35.0, 2.00, 33.00 }, - { "M36x1.5", 36.0, 1.50, 34.50 }, - { "M36x2.0", 36.0, 2.00, 34.00 }, - { "M36x3.0", 36.0, 3.00, 33.00 }, - { "M39x1.5", 39.0, 1.50, 37.50 }, - { "M39x2.0", 39.0, 2.00, 37.00 }, - { "M39x3.0", 39.0, 3.00, 36.00 }, - { "M40x1.5", 40.0, 1.50, 38.50 }, - { "M40x2.0", 40.0, 2.00, 38.00 }, - { "M40x3.0", 40.0, 3.00, 37.00 }, - { "M42x1.5", 42.0, 1.50, 40.50 }, - { "M42x2.0", 42.0, 2.00, 40.00 }, - { "M42x3.0", 42.0, 3.00, 39.00 }, - { "M42x4.0", 42.0, 4.00, 38.00 }, - { "M45x1.5", 45.0, 1.50, 43.50 }, - { "M45x2.0", 45.0, 2.00, 43.00 }, - { "M45x3.0", 45.0, 3.00, 42.00 }, - { "M45x4.0", 45.0, 4.00, 41.00 }, - { "M48x1.5", 48.0, 1.50, 46.50 }, - { "M48x2.0", 48.0, 2.00, 46.00 }, - { "M48x3.0", 48.0, 3.00, 45.00 }, - { "M48x4.0", 48.0, 4.00, 44.00 }, - { "M50x1.5", 50.0, 1.50, 48.50 }, - { "M50x2.0", 50.0, 2.00, 48.00 }, - { "M50x3.0", 50.0, 3.00, 47.00 }, - { "M52x1.5", 52.0, 1.50, 50.50 }, - { "M52x2.0", 52.0, 2.00, 50.00 }, - { "M52x3.0", 52.0, 3.00, 49.00 }, - { "M52x4.0", 52.0, 4.00, 48.00 }, - { "M55x1.5", 55.0, 1.50, 53.50 }, - { "M55x2.0", 55.0, 2.00, 53.00 }, - { "M55x3.0", 55.0, 3.00, 52.00 }, - { "M55x4.0", 55.0, 4.00, 51.00 }, - { "M56x1.5", 56.0, 1.50, 54.50 }, - { "M56x2.0", 56.0, 2.00, 54.00 }, - { "M56x3.0", 56.0, 3.00, 53.00 }, - { "M56x4.0", 56.0, 4.00, 52.00 }, - { "M58x1.5", 58.0, 1.50, 56.50 }, - { "M58x2.0", 58.0, 2.00, 56.00 }, - { "M58x3.0", 58.0, 3.00, 55.00 }, - { "M58x4.0", 58.0, 4.00, 54.00 }, - { "M60x1.5", 60.0, 1.50, 58.50 }, - { "M60x2.0", 60.0, 2.00, 58.00 }, - { "M60x3.0", 60.0, 3.00, 57.00 }, - { "M60x4.0", 60.0, 4.00, 56.00 }, - { "M62x1.5", 62.0, 1.50, 60.50 }, - { "M62x2.0", 62.0, 2.00, 60.00 }, - { "M62x3.0", 62.0, 3.00, 59.00 }, - { "M62x4.0", 62.0, 4.00, 58.00 }, - { "M64x1.5", 64.0, 1.50, 62.50 }, - { "M64x2.0", 64.0, 2.00, 62.00 }, - { "M64x3.0", 64.0, 3.00, 61.00 }, - { "M64x4.0", 64.0, 4.00, 60.00 }, - { "M65x1.5", 65.0, 1.50, 63.50 }, - { "M65x2.0", 65.0, 2.00, 63.00 }, - { "M65x3.0", 65.0, 3.00, 62.00 }, - { "M65x4.0", 65.0, 4.00, 61.00 }, - { "M68x1.5", 68.0, 1.50, 66.50 }, - { "M68x2.0", 68.0, 2.00, 66.00 }, - { "M68x3.0", 68.0, 3.00, 65.00 }, - { "M68x4.0", 68.0, 4.00, 64.00 }, - { "M70x1.5", 70.0, 1.50, 68.50 }, - { "M70x2.0", 70.0, 2.00, 68.00 }, - { "M70x3.0", 70.0, 3.00, 67.00 }, - { "M70x4.0", 70.0, 4.00, 66.00 }, - { "M70x6.0", 70.0, 6.00, 64.00 }, - { "M72x1.5", 72.0, 1.50, 70.50 }, - { "M72x2.0", 72.0, 2.00, 70.00 }, - { "M72x3.0", 72.0, 3.00, 69.00 }, - { "M72x4.0", 72.0, 4.00, 68.00 }, - { "M72x6.0", 72.0, 6.00, 66.00 }, - { "M75x1.5", 75.0, 1.50, 73.50 }, - { "M75x2.0", 75.0, 2.00, 73.00 }, - { "M75x3.0", 75.0, 3.00, 72.00 }, - { "M75x4.0", 75.0, 4.00, 71.00 }, - { "M75x6.0", 75.0, 6.00, 69.00 }, - { "M76x1.5", 76.0, 1.50, 74.50 }, - { "M76x2.0", 76.0, 2.00, 74.00 }, - { "M76x3.0", 76.0, 3.00, 73.00 }, - { "M76x4.0", 76.0, 4.00, 72.00 }, - { "M76x6.0", 76.0, 6.00, 70.00 }, - { "M80x1.5", 80.0, 1.50, 78.50 }, - { "M80x2.0", 80.0, 2.00, 78.00 }, - { "M80x3.0", 80.0, 3.00, 77.00 }, - { "M80x4.0", 80.0, 4.00, 76.00 }, - { "M80x6.0", 80.0, 6.00, 74.00 }, - { "M85x2.0", 85.0, 2.00, 83.00 }, - { "M85x3.0", 85.0, 3.00, 82.00 }, - { "M85x4.0", 85.0, 4.00, 81.00 }, - { "M85x6.0", 85.0, 6.00, 79.00 }, - { "M90x2.0", 90.0, 2.00, 88.00 }, - { "M90x3.0", 90.0, 3.00, 87.00 }, - { "M90x4.0", 90.0, 4.00, 86.00 }, - { "M90x6.0", 90.0, 6.00, 84.00 }, - { "M95x2.0", 95.0, 2.00, 93.00 }, - { "M95x3.0", 95.0, 3.00, 92.00 }, - { "M95x4.0", 95.0, 4.00, 91.00 }, - { "M95x6.0", 95.0, 6.00, 89.00 }, - { "M100x2.0", 100.0, 2.00, 98.00 }, - { "M100x3.0", 100.0, 3.00, 97.00 }, - { "M100x4.0", 100.0, 4.00, 96.00 }, - { "M100x6.0", 100.0, 6.00, 94.00 } - }, + {{"M1x0.2", 1.0, 0.20, 0.80}, {"M1.1x0.2", 1.1, 0.20, 0.90}, + {"M1.2x0.2", 1.2, 0.20, 1.00}, {"M1.4x0.2", 1.4, 0.20, 1.20}, + {"M1.6x0.2", 1.6, 0.20, 1.40}, {"M1.8x0.2", 1.8, 0.20, 1.60}, + {"M2x0.25", 2.0, 0.25, 1.75}, {"M2.2x0.25", 2.2, 0.25, 1.95}, + {"M2.5x0.35", 2.5, 0.35, 2.15}, {"M3x0.35", 3.0, 0.35, 2.65}, + {"M3.5x0.35", 3.5, 0.35, 3.15}, {"M4x0.5", 4.0, 0.50, 3.50}, + {"M4.5x0.5", 4.5, 0.50, 4.00}, {"M5x0.5", 5.0, 0.50, 4.50}, + {"M5.5x0.5", 5.5, 0.50, 5.00}, {"M6x0.75", 6.0, 0.75, 5.25}, + {"M7x0.75", 7.0, 0.75, 6.25}, {"M8x0.75", 8.0, 0.75, 7.25}, + {"M8x1.0", 8.0, 1.00, 7.00}, {"M9x0.75", 9.0, 0.75, 8.25}, + {"M9x1.0", 9.0, 1.00, 8.00}, {"M10x0.75", 10.0, 0.75, 9.25}, + {"M10x1.0", 10.0, 1.00, 9.00}, {"M10x1.25", 10.0, 1.25, 8.75}, + {"M11x0.75", 11.0, 0.75, 10.25}, {"M11x1.0", 11.0, 1.00, 10.00}, + {"M12x1.0", 12.0, 1.00, 11.00}, {"M12x1.25", 12.0, 1.25, 10.75}, + {"M12x1.5", 12.0, 1.50, 10.50}, {"M14x1.0", 14.0, 1.00, 13.00}, + {"M14x1.25", 14.0, 1.25, 12.75}, {"M14x1.5", 14.0, 1.50, 12.50}, + {"M15x1.0", 15.0, 1.00, 14.00}, {"M15x1.5", 15.0, 1.50, 13.50}, + {"M16x1.0", 16.0, 1.00, 15.00}, {"M16x1.5", 16.0, 1.50, 14.50}, + {"M17x1.0", 17.0, 1.00, 16.00}, {"M17x1.5", 17.0, 1.50, 15.50}, + {"M18x1.0", 18.0, 1.00, 17.00}, {"M18x1.5", 18.0, 1.50, 16.50}, + {"M18x2.0", 18.0, 2.00, 16.00}, {"M20x1.0", 20.0, 1.00, 19.00}, + {"M20x1.5", 20.0, 1.50, 18.50}, {"M20x2.0", 20.0, 2.00, 18.00}, + {"M22x1.0", 22.0, 1.00, 21.00}, {"M22x1.5", 22.0, 1.50, 20.50}, + {"M22x2.0", 22.0, 2.00, 20.00}, {"M24x1.0", 24.0, 1.00, 23.00}, + {"M24x1.5", 24.0, 1.50, 22.50}, {"M24x2.0", 24.0, 2.00, 22.00}, + {"M25x1.0", 25.0, 1.00, 24.00}, {"M25x1.5", 25.0, 1.50, 23.50}, + {"M25x2.0", 25.0, 2.00, 23.00}, {"M27x1.0", 27.0, 1.00, 26.00}, + {"M27x1.5", 27.0, 1.50, 25.50}, {"M27x2.0", 27.0, 2.00, 25.00}, + {"M28x1.0", 28.0, 1.00, 27.00}, {"M28x1.5", 28.0, 1.50, 26.50}, + {"M28x2.0", 28.0, 2.00, 26.00}, {"M30x1.0", 30.0, 1.00, 29.00}, + {"M30x1.5", 30.0, 1.50, 28.50}, {"M30x2.0", 30.0, 2.00, 28.00}, + {"M30x3.0", 30.0, 3.00, 27.00}, {"M32x1.5", 32.0, 1.50, 30.50}, + {"M32x2.0", 32.0, 2.00, 30.00}, {"M33x1.5", 33.0, 1.50, 31.50}, + {"M33x2.0", 33.0, 2.00, 31.00}, {"M33x3.0", 33.0, 3.00, 30.00}, + {"M35x1.5", 35.0, 1.50, 33.50}, {"M35x2.0", 35.0, 2.00, 33.00}, + {"M36x1.5", 36.0, 1.50, 34.50}, {"M36x2.0", 36.0, 2.00, 34.00}, + {"M36x3.0", 36.0, 3.00, 33.00}, {"M39x1.5", 39.0, 1.50, 37.50}, + {"M39x2.0", 39.0, 2.00, 37.00}, {"M39x3.0", 39.0, 3.00, 36.00}, + {"M40x1.5", 40.0, 1.50, 38.50}, {"M40x2.0", 40.0, 2.00, 38.00}, + {"M40x3.0", 40.0, 3.00, 37.00}, {"M42x1.5", 42.0, 1.50, 40.50}, + {"M42x2.0", 42.0, 2.00, 40.00}, {"M42x3.0", 42.0, 3.00, 39.00}, + {"M42x4.0", 42.0, 4.00, 38.00}, {"M45x1.5", 45.0, 1.50, 43.50}, + {"M45x2.0", 45.0, 2.00, 43.00}, {"M45x3.0", 45.0, 3.00, 42.00}, + {"M45x4.0", 45.0, 4.00, 41.00}, {"M48x1.5", 48.0, 1.50, 46.50}, + {"M48x2.0", 48.0, 2.00, 46.00}, {"M48x3.0", 48.0, 3.00, 45.00}, + {"M48x4.0", 48.0, 4.00, 44.00}, {"M50x1.5", 50.0, 1.50, 48.50}, + {"M50x2.0", 50.0, 2.00, 48.00}, {"M50x3.0", 50.0, 3.00, 47.00}, + {"M52x1.5", 52.0, 1.50, 50.50}, {"M52x2.0", 52.0, 2.00, 50.00}, + {"M52x3.0", 52.0, 3.00, 49.00}, {"M52x4.0", 52.0, 4.00, 48.00}, + {"M55x1.5", 55.0, 1.50, 53.50}, {"M55x2.0", 55.0, 2.00, 53.00}, + {"M55x3.0", 55.0, 3.00, 52.00}, {"M55x4.0", 55.0, 4.00, 51.00}, + {"M56x1.5", 56.0, 1.50, 54.50}, {"M56x2.0", 56.0, 2.00, 54.00}, + {"M56x3.0", 56.0, 3.00, 53.00}, {"M56x4.0", 56.0, 4.00, 52.00}, + {"M58x1.5", 58.0, 1.50, 56.50}, {"M58x2.0", 58.0, 2.00, 56.00}, + {"M58x3.0", 58.0, 3.00, 55.00}, {"M58x4.0", 58.0, 4.00, 54.00}, + {"M60x1.5", 60.0, 1.50, 58.50}, {"M60x2.0", 60.0, 2.00, 58.00}, + {"M60x3.0", 60.0, 3.00, 57.00}, {"M60x4.0", 60.0, 4.00, 56.00}, + {"M62x1.5", 62.0, 1.50, 60.50}, {"M62x2.0", 62.0, 2.00, 60.00}, + {"M62x3.0", 62.0, 3.00, 59.00}, {"M62x4.0", 62.0, 4.00, 58.00}, + {"M64x1.5", 64.0, 1.50, 62.50}, {"M64x2.0", 64.0, 2.00, 62.00}, + {"M64x3.0", 64.0, 3.00, 61.00}, {"M64x4.0", 64.0, 4.00, 60.00}, + {"M65x1.5", 65.0, 1.50, 63.50}, {"M65x2.0", 65.0, 2.00, 63.00}, + {"M65x3.0", 65.0, 3.00, 62.00}, {"M65x4.0", 65.0, 4.00, 61.00}, + {"M68x1.5", 68.0, 1.50, 66.50}, {"M68x2.0", 68.0, 2.00, 66.00}, + {"M68x3.0", 68.0, 3.00, 65.00}, {"M68x4.0", 68.0, 4.00, 64.00}, + {"M70x1.5", 70.0, 1.50, 68.50}, {"M70x2.0", 70.0, 2.00, 68.00}, + {"M70x3.0", 70.0, 3.00, 67.00}, {"M70x4.0", 70.0, 4.00, 66.00}, + {"M70x6.0", 70.0, 6.00, 64.00}, {"M72x1.5", 72.0, 1.50, 70.50}, + {"M72x2.0", 72.0, 2.00, 70.00}, {"M72x3.0", 72.0, 3.00, 69.00}, + {"M72x4.0", 72.0, 4.00, 68.00}, {"M72x6.0", 72.0, 6.00, 66.00}, + {"M75x1.5", 75.0, 1.50, 73.50}, {"M75x2.0", 75.0, 2.00, 73.00}, + {"M75x3.0", 75.0, 3.00, 72.00}, {"M75x4.0", 75.0, 4.00, 71.00}, + {"M75x6.0", 75.0, 6.00, 69.00}, {"M76x1.5", 76.0, 1.50, 74.50}, + {"M76x2.0", 76.0, 2.00, 74.00}, {"M76x3.0", 76.0, 3.00, 73.00}, + {"M76x4.0", 76.0, 4.00, 72.00}, {"M76x6.0", 76.0, 6.00, 70.00}, + {"M80x1.5", 80.0, 1.50, 78.50}, {"M80x2.0", 80.0, 2.00, 78.00}, + {"M80x3.0", 80.0, 3.00, 77.00}, {"M80x4.0", 80.0, 4.00, 76.00}, + {"M80x6.0", 80.0, 6.00, 74.00}, {"M85x2.0", 85.0, 2.00, 83.00}, + {"M85x3.0", 85.0, 3.00, 82.00}, {"M85x4.0", 85.0, 4.00, 81.00}, + {"M85x6.0", 85.0, 6.00, 79.00}, {"M90x2.0", 90.0, 2.00, 88.00}, + {"M90x3.0", 90.0, 3.00, 87.00}, {"M90x4.0", 90.0, 4.00, 86.00}, + {"M90x6.0", 90.0, 6.00, 84.00}, {"M95x2.0", 95.0, 2.00, 93.00}, + {"M95x3.0", 95.0, 3.00, 92.00}, {"M95x4.0", 95.0, 4.00, 91.00}, + {"M95x6.0", 95.0, 6.00, 89.00}, {"M100x2.0", 100.0, 2.00, 98.00}, + {"M100x3.0", 100.0, 3.00, 97.00}, {"M100x4.0", 100.0, 4.00, 96.00}, + {"M100x6.0", 100.0, 6.00, 94.00}}, /* UNC */ { - { "#1", 1.854, 0.397, 1.50 }, - { "#2", 2.184, 0.454, 1.85 }, - { "#3", 2.515, 0.529, 2.10 }, - { "#4", 2.845, 0.635, 2.35 }, - { "#5", 3.175, 0.635, 2.65 }, - { "#6", 3.505, 0.794, 2.85 }, - { "#8", 4.166, 0.794, 3.50 }, - { "#10", 4.826, 1.058, 3.90 }, - { "#12", 5.486, 1.058, 4.50 }, - { "1/4", 6.350, 1.270, 5.10 }, - { "5/16", 7.938, 1.411, 6.60 }, - { "3/8", 9.525, 1.588, 8.00 }, - { "7/16", 11.113, 1.814, 9.40 }, - { "1/2", 12.700, 1.954, 10.80 }, - { "9/16", 14.288, 2.117, 12.20 }, - { "5/8", 15.875, 2.309, 13.50 }, - { "3/4", 19.050, 2.540, 16.50 }, - { "7/8", 22.225, 2.822, 19.50 }, - { "1", 25.400, 3.175, 22.25 }, - { "1 1/8", 28.575, 3.628, 25.00 }, - { "1 1/4", 31.750, 3.628, 28.00 }, - { "1 3/8", 34.925, 4.233, 30.75 }, - { "1 1/2", 38.100, 4.233, 34.00 }, - { "1 3/4", 44.450, 5.080, 39.50 }, - { "2", 50.800, 5.644, 45.00 }, - { "2 1/4", 57.150, 5.644, 51.50 }, - { "2 1/2", 63.500, 6.350, 57.00 }, - { "2 3/4", 69.850, 6.350, 63.50 }, - { "3", 76.200, 6.350, 70.00 }, - { "3 1/4", 82.550, 6.350, 76.50 }, - { "3 1/2", 88.900, 6.350, 83.00 }, - { "3 3/4", 95.250, 6.350, 89.00 }, - { "4", 101.600, 6.350, 95.50 }, + {"#1", 1.854, 0.397, 1.50}, {"#2", 2.184, 0.454, 1.85}, + {"#3", 2.515, 0.529, 2.10}, {"#4", 2.845, 0.635, 2.35}, + {"#5", 3.175, 0.635, 2.65}, {"#6", 3.505, 0.794, 2.85}, + {"#8", 4.166, 0.794, 3.50}, {"#10", 4.826, 1.058, 3.90}, + {"#12", 5.486, 1.058, 4.50}, {"1/4", 6.350, 1.270, 5.10}, + {"5/16", 7.938, 1.411, 6.60}, {"3/8", 9.525, 1.588, 8.00}, + {"7/16", 11.113, 1.814, 9.40}, {"1/2", 12.700, 1.954, 10.80}, + {"9/16", 14.288, 2.117, 12.20}, {"5/8", 15.875, 2.309, 13.50}, + {"3/4", 19.050, 2.540, 16.50}, {"7/8", 22.225, 2.822, 19.50}, + {"1", 25.400, 3.175, 22.25}, {"1 1/8", 28.575, 3.628, 25.00}, + {"1 1/4", 31.750, 3.628, 28.00}, {"1 3/8", 34.925, 4.233, 30.75}, + {"1 1/2", 38.100, 4.233, 34.00}, {"1 3/4", 44.450, 5.080, 39.50}, + {"2", 50.800, 5.644, 45.00}, {"2 1/4", 57.150, 5.644, 51.50}, + {"2 1/2", 63.500, 6.350, 57.00}, {"2 3/4", 69.850, 6.350, 63.50}, + {"3", 76.200, 6.350, 70.00}, {"3 1/4", 82.550, 6.350, 76.50}, + {"3 1/2", 88.900, 6.350, 83.00}, {"3 3/4", 95.250, 6.350, 89.00}, + {"4", 101.600, 6.350, 95.50}, }, /* UNF */ { - { "#0", 1.524, 0.317, 1.20 }, - { "#1", 1.854, 0.353, 1.55 }, - { "#2", 2.184, 0.397, 1.85 }, - { "#3", 2.515, 0.454, 2.10 }, - { "#4", 2.845, 0.529, 2.40 }, - { "#5", 3.175, 0.577, 2.70 }, - { "#6", 3.505, 0.635, 2.95 }, - { "#8", 4.166, 0.706, 3.50 }, - { "#10", 4.826, 0.794, 4.10 }, - { "#12", 5.486, 0.907, 4.70 }, - { "1/4", 6.350, 0.907, 5.50 }, - { "5/16", 7.938, 1.058, 6.90 }, - { "3/8", 9.525, 1.058, 8.50 }, - { "7/16", 11.113, 1.270, 9.90 }, - { "1/2", 12.700, 1.270, 11.50 }, - { "9/16", 14.288, 1.411, 12.90 }, - { "5/8", 15.875, 1.411, 14.50 }, - { "3/4", 19.050, 1.588, 17.50 }, - { "7/8", 22.225, 1.814, 20.40 }, - { "1", 25.400, 2.117, 23.25 }, - { "1 1/8", 28.575, 2.117, 26.50 }, - { "1 3/16", 30.163, 1.588, 28.58 }, - { "1 1/4", 31.750, 2.117, 29.50 }, - { "1 3/8", 34.925, 2.117, 32.75 }, - { "1 1/2", 38.100, 2.117, 36.00 }, - } , + {"#0", 1.524, 0.317, 1.20}, {"#1", 1.854, 0.353, 1.55}, + {"#2", 2.184, 0.397, 1.85}, {"#3", 2.515, 0.454, 2.10}, + {"#4", 2.845, 0.529, 2.40}, {"#5", 3.175, 0.577, 2.70}, + {"#6", 3.505, 0.635, 2.95}, {"#8", 4.166, 0.706, 3.50}, + {"#10", 4.826, 0.794, 4.10}, {"#12", 5.486, 0.907, 4.70}, + {"1/4", 6.350, 0.907, 5.50}, {"5/16", 7.938, 1.058, 6.90}, + {"3/8", 9.525, 1.058, 8.50}, {"7/16", 11.113, 1.270, 9.90}, + {"1/2", 12.700, 1.270, 11.50}, {"9/16", 14.288, 1.411, 12.90}, + {"5/8", 15.875, 1.411, 14.50}, {"3/4", 19.050, 1.588, 17.50}, + {"7/8", 22.225, 1.814, 20.40}, {"1", 25.400, 2.117, 23.25}, + {"1 1/8", 28.575, 2.117, 26.50}, {"1 3/16", 30.163, 1.588, 28.58}, + {"1 1/4", 31.750, 2.117, 29.50}, {"1 3/8", 34.925, 2.117, 32.75}, + {"1 1/2", 38.100, 2.117, 36.00}, + }, /* UNEF */ { - { "#12", 5.486, 0.794, 4.80 }, - { "1/4", 6.350, 0.794, 5.70 }, - { "5/16", 7.938, 0.794, 7.25 }, - { "3/8", 9.525, 0.794, 8.85 }, - { "7/16", 11.113, 0.907, 10.35 }, - { "1/2", 12.700, 0.907, 11.80 }, - { "9/16", 14.288, 1.058, 13.40 }, - { "5/8", 15.875, 1.058, 15.00 }, - { "11/16", 17.462, 1.058, 16.60 }, - { "3/4", 19.050, 1.270, 18.00 }, - { "13/16", 20.638, 1.270, 19.60 }, - { "7/8", 22.225, 1.270, 21.15 }, - { "15/16", 23.812, 1.270, 22.70 }, - { "1", 25.400, 1.270, 24.30 }, - { "1 1/16", 26.988, 1.411, 25.80 }, - { "1 1/8", 28.575, 1.411, 27.35 }, - { "1 1/4", 31.750, 1.411, 30.55 }, - { "1 5/16", 33.338, 1.411, 32.10 }, - { "1 3/8", 34.925, 1.411, 33.70 }, - { "1 7/16", 36.512, 1.411, 35.30 }, - { "1 1/2", 38.100, 1.411, 36.90 }, - { "1 9/16", 39.688, 1.411, 38.55 }, - { "1 5/8", 41.275, 1.411, 40.10 }, - { "1 11/16", 42.862, 1.411, 41.60 }, + {"#12", 5.486, 0.794, 4.80}, {"1/4", 6.350, 0.794, 5.70}, + {"5/16", 7.938, 0.794, 7.25}, {"3/8", 9.525, 0.794, 8.85}, + {"7/16", 11.113, 0.907, 10.35}, {"1/2", 12.700, 0.907, 11.80}, + {"9/16", 14.288, 1.058, 13.40}, {"5/8", 15.875, 1.058, 15.00}, + {"11/16", 17.462, 1.058, 16.60}, {"3/4", 19.050, 1.270, 18.00}, + {"13/16", 20.638, 1.270, 19.60}, {"7/8", 22.225, 1.270, 21.15}, + {"15/16", 23.812, 1.270, 22.70}, {"1", 25.400, 1.270, 24.30}, + {"1 1/16", 26.988, 1.411, 25.80}, {"1 1/8", 28.575, 1.411, 27.35}, + {"1 1/4", 31.750, 1.411, 30.55}, {"1 5/16", 33.338, 1.411, 32.10}, + {"1 3/8", 34.925, 1.411, 33.70}, {"1 7/16", 36.512, 1.411, 35.30}, + {"1 1/2", 38.100, 1.411, 36.90}, {"1 9/16", 39.688, 1.411, 38.55}, + {"1 5/8", 41.275, 1.411, 40.10}, {"1 11/16", 42.862, 1.411, 41.60}, }, /* NPT National pipe threads */ // Asme B1.20.1 { - { "1/16", 7.938, 0.941, 0.0 }, - { "1/8", 10.287, 0.941, 0.0 }, - { "1/4", 13.716, 1.411, 0.0 }, - { "3/8", 17.145, 1.411, 0.0 }, - { "1/2", 21.336, 1.814, 0.0 }, - { "3/4", 26.670, 1.814, 0.0 }, - { "1", 33.401, 2.209, 0.0 }, - { "1 1/4", 42.164, 2.209, 0.0 }, - { "1 1/2", 48.260, 2.209, 0.0 }, - { "2", 60.325, 2.209, 0.0 }, - { "2 1/2", 73.025, 3.175, 0.0 }, - { "3", 88.900, 3.175, 0.0 }, - { "3 1/2", 101.600, 3.175, 0.0 }, - { "4", 114.300, 3.175, 0.0 }, - { "5", 141.300, 3.175, 0.0 }, - { "6", 168.275, 3.175, 0.0 }, - { "8", 219.075, 3.175, 0.0 }, - { "10", 273.050, 3.175, 0.0 }, - { "12", 323.850, 3.175, 0.0 }, + {"1/16", 7.938, 0.941, 0.0}, {"1/8", 10.287, 0.941, 0.0}, + {"1/4", 13.716, 1.411, 0.0}, {"3/8", 17.145, 1.411, 0.0}, + {"1/2", 21.336, 1.814, 0.0}, {"3/4", 26.670, 1.814, 0.0}, + {"1", 33.401, 2.209, 0.0}, {"1 1/4", 42.164, 2.209, 0.0}, + {"1 1/2", 48.260, 2.209, 0.0}, {"2", 60.325, 2.209, 0.0}, + {"2 1/2", 73.025, 3.175, 0.0}, {"3", 88.900, 3.175, 0.0}, + {"3 1/2", 101.600, 3.175, 0.0}, {"4", 114.300, 3.175, 0.0}, + {"5", 141.300, 3.175, 0.0}, {"6", 168.275, 3.175, 0.0}, + {"8", 219.075, 3.175, 0.0}, {"10", 273.050, 3.175, 0.0}, + {"12", 323.850, 3.175, 0.0}, }, /* BSP */ // Parallel - ISO 228-1 // Tapered - ISO 7-1 { - { "1/16", 7.723, 0.907, 6.6 }, - { "1/8", 9.728, 0.907, 8.8 }, - { "1/4", 13.157, 1.337, 11.8 }, - { "3/8", 16.662, 1.337, 15.25 }, - { "1/2", 20.955, 1.814, 19.00 }, - { "5/8", 22.911, 1.814, 21.00 }, - { "3/4", 26.441, 1.814, 24.50 }, - { "7/8", 30.201, 1.814, 28.25 }, - { "1", 33.249, 2.309, 30.75 }, - { "1 1/8", 37.897, 2.309, 0.0 }, - { "1 1/4", 41.910, 2.309, 39.50 }, - { "1 1/2", 47.803, 2.309, 45.50 }, - { "1 3/4", 53.743, 2.309, 51.00 }, - { "2", 59.614, 2.309, 57.00 }, - { "2 1/4", 65.710, 2.309, 0.0 }, - { "2 1/2", 75.184, 2.309, 0.0 }, - { "2 3/4", 81.534, 2.309, 0.0 }, - { "3", 87.884, 2.309, 0.0 }, - { "3 1/2", 100.330, 2.309, 0.0 }, - { "4", 113.030, 2.309, 0.0 }, - { "4 1/2", 125.730, 2.309, 0.0 }, - { "5", 138.430, 2.309, 0.0 }, - { "5 1/2", 151.130, 2.309, 0.0 }, - { "6", 163.830, 2.309, 0.0 }, + {"1/16", 7.723, 0.907, 6.6}, {"1/8", 9.728, 0.907, 8.8}, + {"1/4", 13.157, 1.337, 11.8}, {"3/8", 16.662, 1.337, 15.25}, + {"1/2", 20.955, 1.814, 19.00}, {"5/8", 22.911, 1.814, 21.00}, + {"3/4", 26.441, 1.814, 24.50}, {"7/8", 30.201, 1.814, 28.25}, + {"1", 33.249, 2.309, 30.75}, {"1 1/8", 37.897, 2.309, 0.0}, + {"1 1/4", 41.910, 2.309, 39.50}, {"1 1/2", 47.803, 2.309, 45.50}, + {"1 3/4", 53.743, 2.309, 51.00}, {"2", 59.614, 2.309, 57.00}, + {"2 1/4", 65.710, 2.309, 0.0}, {"2 1/2", 75.184, 2.309, 0.0}, + {"2 3/4", 81.534, 2.309, 0.0}, {"3", 87.884, 2.309, 0.0}, + {"3 1/2", 100.330, 2.309, 0.0}, {"4", 113.030, 2.309, 0.0}, + {"4 1/2", 125.730, 2.309, 0.0}, {"5", 138.430, 2.309, 0.0}, + {"5 1/2", 151.130, 2.309, 0.0}, {"6", 163.830, 2.309, 0.0}, }, /* BSW */ // BS 84 Basic sizes { - { "1/8", 3.175, 0.635, 2.55 }, - { "3/16", 4.762, 1.058, 3.70 }, - { "1/4", 6.350, 1.270, 5.10 }, - { "5/16", 7.938, 1.411, 6.50 }, - { "3/8", 9.525, 1.588, 7.90 }, - { "7/16", 11.113, 1.814, 9.30 }, - { "1/2", 12.700, 2.117, 10.50 }, - { "9/16", 14.290, 2.117, 12.10 }, - { "5/8", 15.876, 2.309, 13.50 }, - { "11/16", 17.463, 2.309, 15.00 }, - { "3/4", 19.051, 2.540, 16.25 }, - { "7/8", 22.226, 2.822, 19.25 }, - { "1", 25.400, 3.175, 22.00 }, - { "1 1/8", 28.576, 3.629, 24.75 }, - { "1 1/4", 31.751, 3.629, 28.00 }, - { "1 1/2", 38.100, 4.233, 33.50 }, - { "1 3/4", 44.452, 5.080, 39.00 }, - { "2", 50.802, 5.644, 44.50 }, - { "2 1/4", 57.152, 6.350, 0.0 }, - { "2 1/2", 63.502, 6.350, 0.0 }, - { "2 3/4", 69.853, 7.257, 0.0 }, - { "3", 76.203, 7.257, 0.0 }, - { "3 1/4", 82.553, 7.815, 0.0 }, - { "3 1/2", 88.903, 7.815, 0.0 }, - { "3 3/4", 95.254, 8.467, 0.0 }, - { "4", 101.604, 8.467, 0.0 }, - { "4 1/2", 114.304, 8.835, 0.0 }, - { "5", 127.005, 9.236, 0.0 }, - { "5 1/2", 139.705, 9.676, 0.0 }, - { "6", 152.406, 10.16, 0.0 }, + {"1/8", 3.175, 0.635, 2.55}, {"3/16", 4.762, 1.058, 3.70}, + {"1/4", 6.350, 1.270, 5.10}, {"5/16", 7.938, 1.411, 6.50}, + {"3/8", 9.525, 1.588, 7.90}, {"7/16", 11.113, 1.814, 9.30}, + {"1/2", 12.700, 2.117, 10.50}, {"9/16", 14.290, 2.117, 12.10}, + {"5/8", 15.876, 2.309, 13.50}, {"11/16", 17.463, 2.309, 15.00}, + {"3/4", 19.051, 2.540, 16.25}, {"7/8", 22.226, 2.822, 19.25}, + {"1", 25.400, 3.175, 22.00}, {"1 1/8", 28.576, 3.629, 24.75}, + {"1 1/4", 31.751, 3.629, 28.00}, {"1 1/2", 38.100, 4.233, 33.50}, + {"1 3/4", 44.452, 5.080, 39.00}, {"2", 50.802, 5.644, 44.50}, + {"2 1/4", 57.152, 6.350, 0.0}, {"2 1/2", 63.502, 6.350, 0.0}, + {"2 3/4", 69.853, 7.257, 0.0}, {"3", 76.203, 7.257, 0.0}, + {"3 1/4", 82.553, 7.815, 0.0}, {"3 1/2", 88.903, 7.815, 0.0}, + {"3 3/4", 95.254, 8.467, 0.0}, {"4", 101.604, 8.467, 0.0}, + {"4 1/2", 114.304, 8.835, 0.0}, {"5", 127.005, 9.236, 0.0}, + {"5 1/2", 139.705, 9.676, 0.0}, {"6", 152.406, 10.16, 0.0}, }, /* BSF */ // BS 84 Basic sizes // BS 1157 for drill sizes { - { "3/16", 4.763, 0.794, 4.00 }, - { "7/32", 5.558, 0.907, 4.60 }, - { "1/4", 6.350, 0.977, 5.30 }, - { "9/32", 7.142, 0.977, 6.10 }, - { "5/16", 7.938, 1.154, 6.80 }, - { "3/8", 9.525, 1.270, 8.30 }, - { "7/16", 11.113, 1.411, 9.70 }, - { "1/2", 12.700, 1.588, 11.10 }, - { "9/16", 14.288, 1.588, 12.70 }, - { "5/8", 15.875, 1.814, 14.00 }, - { "11/16", 17.463, 1.814, 15.50 }, - { "3/4", 19.050, 2.116, 16.75 }, - { "7/8", 22.225, 2.309, 19.75 }, - { "1", 25.400, 2.540, 22.75 }, - { "1 1/8", 28.575, 2.822, 25.50 }, - { "1 1/4", 31.750, 2.822, 28.50 }, - { "1 3/8", 34.925, 3.175, 31.50 }, - { "1 1/2", 38.100, 3.175, 34.50 }, - { "1 5/8", 41.275, 3.175, 0.0 }, - { "1 3/4", 44.450, 3.629, 0.0 }, - { "2", 50.800, 3.629, 0.0 }, - { "2 1/4", 57.150, 4.233, 0.0 }, - { "2 1/2", 63.500, 4.233, 0.0 }, - { "2 3/4", 69.850, 4.233, 0.0 }, - { "3", 76.200, 5.080, 0.0 }, - { "3 1/4", 82.550, 5.080, 0.0 }, - { "3 1/2", 88.900, 5.644, 0.0 }, - { "3 3/4", 95.250, 5.644, 0.0 }, - { "4", 101.600, 5.644, 0.0 }, - { "4 1/4", 107.950, 6.350, 0.0 }, + {"3/16", 4.763, 0.794, 4.00}, {"7/32", 5.558, 0.907, 4.60}, + {"1/4", 6.350, 0.977, 5.30}, {"9/32", 7.142, 0.977, 6.10}, + {"5/16", 7.938, 1.154, 6.80}, {"3/8", 9.525, 1.270, 8.30}, + {"7/16", 11.113, 1.411, 9.70}, {"1/2", 12.700, 1.588, 11.10}, + {"9/16", 14.288, 1.588, 12.70}, {"5/8", 15.875, 1.814, 14.00}, + {"11/16", 17.463, 1.814, 15.50}, {"3/4", 19.050, 2.116, 16.75}, + {"7/8", 22.225, 2.309, 19.75}, {"1", 25.400, 2.540, 22.75}, + {"1 1/8", 28.575, 2.822, 25.50}, {"1 1/4", 31.750, 2.822, 28.50}, + {"1 3/8", 34.925, 3.175, 31.50}, {"1 1/2", 38.100, 3.175, 34.50}, + {"1 5/8", 41.275, 3.175, 0.0}, {"1 3/4", 44.450, 3.629, 0.0}, + {"2", 50.800, 3.629, 0.0}, {"2 1/4", 57.150, 4.233, 0.0}, + {"2 1/2", 63.500, 4.233, 0.0}, {"2 3/4", 69.850, 4.233, 0.0}, + {"3", 76.200, 5.080, 0.0}, {"3 1/4", 82.550, 5.080, 0.0}, + {"3 1/2", 88.900, 5.644, 0.0}, {"3 3/4", 95.250, 5.644, 0.0}, + {"4", 101.600, 5.644, 0.0}, {"4 1/4", 107.950, 6.350, 0.0}, }, /* ISO Tyre valve threads */ // ISO 4570:2002 // Ordered as the standard { - { "5v1", 5.334, 0.705, 0 }, // Schrader internal - { "5v2", 5.370, 1.058, 0 }, // Presta cap - { "6v1", 6.160, 0.800, 0 }, // Presta body - { "8v1", 7.798, 0.794, 0 }, // Schrader external - { "9v1", 9.525, 0.794, 0 }, - { "10v2", 10.414, 0.907, 0 }, - { "12v1", 12.319, 0.977, 0 }, - { "13v1", 12.700, 1.270, 0 }, - { "8v2", 7.938, 1.058, 0 }, - { "10v1", 9.800, 1.000, 0 }, - { "11v1", 11.113, 1.270, 0 }, - { "13v2", 12.700, 0.794, 0 }, - { "15v1", 15.137, 1.000, 0 }, - { "16v1", 15.875, 0.941, 0 }, - { "17v1", 17.137, 1.000, 0 }, - { "17v2", 17.463, 1.058, 0 }, - { "17v3", 17.463, 1.588, 0 }, - { "19v1", 19.050, 1.588, 0 }, - { "20v1", 20.642, 1.000, 0 }, + {"5v1", 5.334, 0.705, 0}, // Schrader internal + {"5v2", 5.370, 1.058, 0}, // Presta cap + {"6v1", 6.160, 0.800, 0}, // Presta body + {"8v1", 7.798, 0.794, 0}, // Schrader external + {"9v1", 9.525, 0.794, 0}, {"10v2", 10.414, 0.907, 0}, {"12v1", 12.319, 0.977, 0}, + {"13v1", 12.700, 1.270, 0}, {"8v2", 7.938, 1.058, 0}, {"10v1", 9.800, 1.000, 0}, + {"11v1", 11.113, 1.270, 0}, {"13v2", 12.700, 0.794, 0}, {"15v1", 15.137, 1.000, 0}, + {"16v1", 15.875, 0.941, 0}, {"17v1", 17.137, 1.000, 0}, {"17v2", 17.463, 1.058, 0}, + {"17v3", 17.463, 1.588, 0}, {"19v1", 19.050, 1.588, 0}, {"20v1", 20.642, 1.000, 0}, } }; -const double Hole::metricHoleDiameters[51][4] = -{ +const double Hole::metricHoleDiameters[51][4] = { /* ISO metric clearance hole diameters according to ISO 273 */ // {screw diameter, fine, medium, coarse} - { 1.0, 1.1, 1.2, 1.3}, - { 1.2, 1.3, 1.4, 1.5}, - { 1.4, 1.5, 1.6, 1.8}, - { 1.6, 1.7, 1.8, 2.0}, - { 1.8, 2.0, 2.1, 2.2}, - { 2.0, 2.2, 2.4, 2.6}, - { 2.5, 2.7, 2.9, 3.1}, - { 3.0, 3.2, 3.4, 3.6}, - { 3.5, 3.7, 3.9, 4.2}, - { 4.0, 4.3, 4.5, 4.8}, - { 4.5, 4.8, 5.0, 5.3}, - { 5.0, 5.3, 5.5, 5.8}, - { 6.0, 6.4, 6.6, 7.0}, - { 7.0, 7.4, 7.6, 8.0}, - { 8.0, 8.4, 9.0, 10.0}, - // 9.0 undefined - { 10.0, 10.5, 11.0, 12.0}, - // 11.0 undefined - { 12.0, 13.0, 13.5, 14.5}, - { 14.0, 15.0, 15.5, 16.5}, - { 16.0, 17.0, 17.5, 18.5}, - { 18.0, 19.0, 20.0, 21.0}, - { 20.0, 21.0, 22.0, 24.0}, - { 22.0, 23.0, 24.0, 26.0}, - { 24.0, 25.0, 26.0, 28.0}, - { 27.0, 28.0, 30.0, 32.0}, - { 30.0, 31.0, 33.0, 35.0}, - { 33.0, 34.0, 36.0, 38.0}, - { 36.0, 37.0, 39.0, 42.0}, - { 39.0, 40.0, 42.0, 45.0}, - { 42.0, 43.0, 45.0, 48.0}, - { 45.0, 46.0, 48.0, 52.0}, - { 48.0, 50.0, 52.0, 56.0}, - { 52.0, 54.0, 56.0, 62.0}, - { 56.0, 58.0, 62.0, 66.0}, - { 60.0, 62.0, 66.0, 70.0}, - { 64.0, 66.0, 70.0, 74.0}, - { 68.0, 70.0, 74.0, 78.0}, - { 72.0, 74.0, 78.0, 82.0}, - { 76.0, 78.0, 82.0, 86.0}, - { 80.0, 82.0, 86.0, 91.0}, - { 85.0, 87.0, 91.0, 96.0}, - { 90.0, 93.0, 96.0, 101.0}, - { 95.0, 98.0, 101.0, 107.0}, - { 100.0, 104.0, 107.0, 112.0}, - { 105.0, 109.0, 112.0, 117.0}, - { 110.0, 114.0, 117.0, 122.0}, - { 115.0, 119.0, 122.0, 127.0}, - { 120.0, 124.0, 127.0, 132.0}, - { 125.0, 129.0, 132.0, 137.0}, - { 130.0, 134.0, 137.0, 144.0}, - { 140.0, 144.0, 147.0, 155.0}, - { 150.0, 155.0, 158.0, 165.0} + {1.0, 1.1, 1.2, 1.3}, + {1.2, 1.3, 1.4, 1.5}, + {1.4, 1.5, 1.6, 1.8}, + {1.6, 1.7, 1.8, 2.0}, + {1.8, 2.0, 2.1, 2.2}, + {2.0, 2.2, 2.4, 2.6}, + {2.5, 2.7, 2.9, 3.1}, + {3.0, 3.2, 3.4, 3.6}, + {3.5, 3.7, 3.9, 4.2}, + {4.0, 4.3, 4.5, 4.8}, + {4.5, 4.8, 5.0, 5.3}, + {5.0, 5.3, 5.5, 5.8}, + {6.0, 6.4, 6.6, 7.0}, + {7.0, 7.4, 7.6, 8.0}, + {8.0, 8.4, 9.0, 10.0}, + // 9.0 undefined + {10.0, 10.5, 11.0, 12.0}, + // 11.0 undefined + {12.0, 13.0, 13.5, 14.5}, + {14.0, 15.0, 15.5, 16.5}, + {16.0, 17.0, 17.5, 18.5}, + {18.0, 19.0, 20.0, 21.0}, + {20.0, 21.0, 22.0, 24.0}, + {22.0, 23.0, 24.0, 26.0}, + {24.0, 25.0, 26.0, 28.0}, + {27.0, 28.0, 30.0, 32.0}, + {30.0, 31.0, 33.0, 35.0}, + {33.0, 34.0, 36.0, 38.0}, + {36.0, 37.0, 39.0, 42.0}, + {39.0, 40.0, 42.0, 45.0}, + {42.0, 43.0, 45.0, 48.0}, + {45.0, 46.0, 48.0, 52.0}, + {48.0, 50.0, 52.0, 56.0}, + {52.0, 54.0, 56.0, 62.0}, + {56.0, 58.0, 62.0, 66.0}, + {60.0, 62.0, 66.0, 70.0}, + {64.0, 66.0, 70.0, 74.0}, + {68.0, 70.0, 74.0, 78.0}, + {72.0, 74.0, 78.0, 82.0}, + {76.0, 78.0, 82.0, 86.0}, + {80.0, 82.0, 86.0, 91.0}, + {85.0, 87.0, 91.0, 96.0}, + {90.0, 93.0, 96.0, 101.0}, + {95.0, 98.0, 101.0, 107.0}, + {100.0, 104.0, 107.0, 112.0}, + {105.0, 109.0, 112.0, 117.0}, + {110.0, 114.0, 117.0, 122.0}, + {115.0, 119.0, 122.0, 127.0}, + {120.0, 124.0, 127.0, 132.0}, + {125.0, 129.0, 132.0, 137.0}, + {130.0, 134.0, 137.0, 144.0}, + {140.0, 144.0, 147.0, 155.0}, + {150.0, 155.0, 158.0, 165.0} }; -const Hole::UTSClearanceDefinition Hole::UTSHoleDiameters[23] = -{ +const Hole::UTSClearanceDefinition Hole::UTSHoleDiameters[23] = { /* UTS clearance hole diameters according to ASME B18.2.8 */ - // for information: the norm defines a drill bit number (that is in turn standardized in another ASME norm). - // as result the norm defines a minimal clearance which is the diameter of that drill bit. - // we use here this minimal clearance as the theoretical exact hole diameter as this is also done in the ISO norm. - // {screw class, close, normal, loose} - { "#0", 1.7, 1.9, 2.4 }, - { "#1", 2.1, 2.3, 2.6 }, - { "#2", 2.4, 2.6, 2.9 }, - { "#3", 2.7, 2.9, 3.3 }, - { "#4", 3.0, 3.3, 3.7 }, - { "#5", 3.6, 4.0, 4.4 }, - { "#6", 3.9, 4.3, 4.7 }, - { "#8", 4.6, 5.0, 5.4 }, - { "#10", 5.2, 5.6, 6.0 }, - // "#12" not defined - { "1/4", 6.8, 7.1, 7.5 }, - { "5/16", 8.3, 8.7, 9.1 }, - { "3/8", 9.9, 10.3, 10.7 }, - { "7/16", 11.5, 11.9, 12.3 }, - { "1/2", 13.5, 14.3, 15.5 }, - // "9/16" not defined - { "5/8", 16.7, 17.5, 18.6 }, - { "3/4", 19.8, 20.6, 23.0 }, - { "7/8", 23.0, 23.8, 26.2 }, - { "1", 26.2, 27.8, 29.4 }, - { "1 1/8", 29.4, 31.0, 33.3 }, - { "1 3/16", 31.0, 32.5, 34.9 }, - { "1 1/4", 32.5, 34.1, 36.5 }, - { "1 3/8", 36.5, 38.1, 40.9 }, - { "1 1/2", 39.7, 41.3, 44.0 } + // for information: the norm defines a drill bit number (that is in turn standardized in another + // ASME norm). as result the norm defines a minimal clearance which is the diameter of that + // drill bit. we use here this minimal clearance as the theoretical exact hole diameter as this + // is also done in the ISO norm. {screw class, close, normal, loose} + {"#0", 1.7, 1.9, 2.4}, + {"#1", 2.1, 2.3, 2.6}, + {"#2", 2.4, 2.6, 2.9}, + {"#3", 2.7, 2.9, 3.3}, + {"#4", 3.0, 3.3, 3.7}, + {"#5", 3.6, 4.0, 4.4}, + {"#6", 3.9, 4.3, 4.7}, + {"#8", 4.6, 5.0, 5.4}, + {"#10", 5.2, 5.6, 6.0}, + // "#12" not defined + {"1/4", 6.8, 7.1, 7.5}, + {"5/16", 8.3, 8.7, 9.1}, + {"3/8", 9.9, 10.3, 10.7}, + {"7/16", 11.5, 11.9, 12.3}, + {"1/2", 13.5, 14.3, 15.5}, + // "9/16" not defined + {"5/8", 16.7, 17.5, 18.6}, + {"3/4", 19.8, 20.6, 23.0}, + {"7/8", 23.0, 23.8, 26.2}, + {"1", 26.2, 27.8, 29.4}, + {"1 1/8", 29.4, 31.0, 33.3}, + {"1 3/16", 31.0, 32.5, 34.9}, + {"1 1/4", 32.5, 34.1, 36.5}, + {"1 3/8", 36.5, 38.1, 40.9}, + {"1 1/2", 39.7, 41.3, 44.0} }; -std::vector getThreadDesignations(const int threadType) { +std::vector getThreadDesignations(const int threadType) +{ std::vector designations; for (const auto& thread : Hole::threadDescription[threadType]) { designations.push_back(thread.designation); @@ -657,116 +462,85 @@ std::vector getThreadDesignations(const int threadType) { } /* ISO coarse metric enums */ -std::vector Hole::HoleCutType_ISOmetric_Enums = { - "None", - "Counterbore", - "Countersink", - "Counterdrill"}; -const char* Hole::ThreadClass_ISOmetric_Enums[] = { "4G", "4H", "5G", "5H", "6G", "6H", "7G", "7H","8G", "8H", nullptr }; +std::vector Hole::HoleCutType_ISOmetric_Enums + = {"None", "Counterbore", "Countersink", "Counterdrill"}; +const char* Hole::ThreadClass_ISOmetric_Enums[] + = {"4G", "4H", "5G", "5H", "6G", "6H", "7G", "7H", "8G", "8H", nullptr}; -std::vector Hole::HoleCutType_ISOmetricfine_Enums = { - "None", - "Counterbore", - "Countersink", - "Counterdrill"}; -const char* Hole::ThreadClass_ISOmetricfine_Enums[] = { "4G", "4H", "5G", "5H", "6G", "6H", "7G", "7H","8G", "8H", nullptr }; +std::vector Hole::HoleCutType_ISOmetricfine_Enums + = {"None", "Counterbore", "Countersink", "Counterdrill"}; +const char* Hole::ThreadClass_ISOmetricfine_Enums[] + = {"4G", "4H", "5G", "5H", "6G", "6H", "7G", "7H", "8G", "8H", nullptr}; // ISO 965-1:2013 ISO general purpose metric screw threads - Tolerances - Part 1 // Table 1 - Fundamentral deviations for internal threads ... // reproduced in: https://www.accu.co.uk/en/p/134-iso-metric-thread-tolerances [retrieved: 2021-01-11] const double Hole::ThreadClass_ISOmetric_data[ThreadClass_ISOmetric_data_size][2] = { -// Pitch G - {0.2, 0.017}, - {0.25, 0.018}, - {0.3, 0.018}, - {0.35, 0.019}, - {0.4, 0.019}, - {0.45, 0.020}, - {0.5, 0.020}, - {0.6, 0.021}, - {0.7, 0.022}, - {0.75, 0.022}, - {0.8, 0.024}, - {1.0, 0.026}, - {1.25, 0.028}, - {1.5, 0.032}, - {1.75, 0.034}, - {2.0, 0.038}, - {2.5, 0.042}, - {3.0, 0.048}, - {3.5, 0.053}, - {4.0, 0.060}, - {4.5, 0.063}, - {5.0, 0.071}, - {5.5, 0.075}, - {6.0, 0.080}, - {8.0, 0.100} + // Pitch G + {0.2, 0.017}, {0.25, 0.018}, {0.3, 0.018}, {0.35, 0.019}, {0.4, 0.019}, + {0.45, 0.020}, {0.5, 0.020}, {0.6, 0.021}, {0.7, 0.022}, {0.75, 0.022}, + {0.8, 0.024}, {1.0, 0.026}, {1.25, 0.028}, {1.5, 0.032}, {1.75, 0.034}, + {2.0, 0.038}, {2.5, 0.042}, {3.0, 0.048}, {3.5, 0.053}, {4.0, 0.060}, + {4.5, 0.063}, {5.0, 0.071}, {5.5, 0.075}, {6.0, 0.080}, {8.0, 0.100} }; -/* According to DIN 76-1 (Thread run-outs and thread undercuts - Part 1: For ISO metric threads in accordance with DIN 13-1) */ +/* According to DIN 76-1 (Thread run-outs and thread undercuts - Part 1: For ISO metric threads in + * accordance with DIN 13-1) */ const double Hole::ThreadRunout[ThreadRunout_size][2] = { -// Pitch e1 - {0.2, 1.3}, - {0.25, 1.5}, - {0.3, 1.8}, - {0.35, 2.1}, - {0.4, 2.3}, - {0.45, 2.6}, - {0.5, 2.8}, - {0.6, 3.4}, - {0.7, 3.8}, - {0.75, 4.0}, - {0.8, 4.2}, - {1.0, 5.1}, - {1.25, 6.2}, - {1.5, 7.3}, - {1.75, 8.3}, - {2.0, 9.3}, - {2.5, 11.2}, - {3.0, 13.1}, - {3.5, 15.2}, - {4.0, 16.8}, - {4.5, 18.4}, - {5.0, 20.8}, - {5.5, 22.4}, - {6.0, 24.0} + // Pitch e1 + {0.2, 1.3}, {0.25, 1.5}, {0.3, 1.8}, {0.35, 2.1}, {0.4, 2.3}, {0.45, 2.6}, + {0.5, 2.8}, {0.6, 3.4}, {0.7, 3.8}, {0.75, 4.0}, {0.8, 4.2}, {1.0, 5.1}, + {1.25, 6.2}, {1.5, 7.3}, {1.75, 8.3}, {2.0, 9.3}, {2.5, 11.2}, {3.0, 13.1}, + {3.5, 15.2}, {4.0, 16.8}, {4.5, 18.4}, {5.0, 20.8}, {5.5, 22.4}, {6.0, 24.0} }; /* Details from https://en.wikipedia.org/wiki/Unified_Thread_Standard */ /* UTS coarse */ -const char* Hole::HoleCutType_UNC_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; -const char* Hole::ThreadClass_UNC_Enums[] = { "1B", "2B", "3B", nullptr }; +const char* Hole::HoleCutType_UNC_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::ThreadClass_UNC_Enums[] = {"1B", "2B", "3B", nullptr}; /* UTS fine */ -const char* Hole::HoleCutType_UNF_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; -const char* Hole::ThreadClass_UNF_Enums[] = { "1B", "2B", "3B", nullptr }; +const char* Hole::HoleCutType_UNF_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::ThreadClass_UNF_Enums[] = {"1B", "2B", "3B", nullptr}; /* UTS extrafine */ -const char* Hole::HoleCutType_UNEF_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; -const char* Hole::ThreadClass_UNEF_Enums[] = { "1B", "2B", "3B", nullptr }; +const char* Hole::HoleCutType_UNEF_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::ThreadClass_UNEF_Enums[] = {"1B", "2B", "3B", nullptr}; /* NPT */ -const char* Hole::HoleCutType_NPT_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::HoleCutType_NPT_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; /* BSP */ -const char* Hole::HoleCutType_BSP_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::HoleCutType_BSP_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; /* BSW */ -const char* Hole::HoleCutType_BSW_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; -const char* Hole::ThreadClass_BSW_Enums[] = { "Medium", "Normal", nullptr }; +const char* Hole::HoleCutType_BSW_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::ThreadClass_BSW_Enums[] = {"Medium", "Normal", nullptr}; /* BSF */ -const char* Hole::HoleCutType_BSF_Enums[] = { "None", "Counterbore", "Countersink", "Counterdrill", nullptr}; -const char* Hole::ThreadClass_BSF_Enums[] = { "Medium", "Normal", nullptr }; +const char* Hole::HoleCutType_BSF_Enums[] + = {"None", "Counterbore", "Countersink", "Counterdrill", nullptr}; +const char* Hole::ThreadClass_BSF_Enums[] = {"Medium", "Normal", nullptr}; -const char* Hole::ThreadDirectionEnums[] = { "Right", "Left", nullptr}; +const char* Hole::ThreadDirectionEnums[] = {"Right", "Left", nullptr}; PROPERTY_SOURCE(PartDesign::Hole, PartDesign::ProfileBased) -const App::PropertyAngle::Constraints Hole::floatAngle = { Base::toDegrees(Precision::Angular()), 180.0 - Base::toDegrees(Precision::Angular()), 1.0 }; +const App::PropertyAngle::Constraints Hole::floatAngle = { + Base::toDegrees(Precision::Angular()), + 180.0 - Base::toDegrees(Precision::Angular()), + 1.0 +}; // OCC can only create holes with a min diameter of 10 times the Precision::Confusion() -const App::PropertyQuantityConstraint::Constraints diameterRange = { 10 * Precision::Confusion(), std::numeric_limits::max(), 1.0 }; +const App::PropertyQuantityConstraint::Constraints diameterRange + = {10 * Precision::Confusion(), std::numeric_limits::max(), 1.0}; Hole::Hole() { @@ -826,8 +600,13 @@ Hole::Hole() ADD_PROPERTY_TYPE(DrillPointAngle, (118.0), "Hole", App::Prop_None, "Drill point angle"); DrillPointAngle.setConstraints(&floatAngle); - ADD_PROPERTY_TYPE(DrillForDepth, ((long)0), "Hole", App::Prop_None, - "The size of the drill point will be taken into\n account for the depth of blind holes"); + ADD_PROPERTY_TYPE( + DrillForDepth, + ((long)0), + "Hole", + App::Prop_None, + "The size of the drill point will be taken into\n account for the depth of blind holes" + ); ADD_PROPERTY_TYPE(Tapered, (false), "Hole", App::Prop_None, "Tapered"); @@ -837,15 +616,34 @@ Hole::Hole() ADD_PROPERTY_TYPE(ThreadDepthType, (0L), "Hole", App::Prop_None, "Thread depth type"); ThreadDepthType.setEnums(ThreadDepthTypeEnums); - ADD_PROPERTY_TYPE(ThreadDepth, (23.5), "Hole", App::Prop_None, "Thread Length"); // default is assuming an M1 + ADD_PROPERTY_TYPE(ThreadDepth, (23.5), "Hole", App::Prop_None, "Thread Length"); // default is + // assuming an M1 - ADD_PROPERTY_TYPE(UseCustomThreadClearance, (false), "Hole", App::Prop_None, "Use custom thread clearance"); + ADD_PROPERTY_TYPE( + UseCustomThreadClearance, + (false), + "Hole", + App::Prop_None, + "Use custom thread clearance" + ); - ADD_PROPERTY_TYPE(CustomThreadClearance, (0.0), "Hole", App::Prop_None, "Custom thread clearance (overrides ThreadClass)"); + ADD_PROPERTY_TYPE( + CustomThreadClearance, + (0.0), + "Hole", + App::Prop_None, + "Custom thread clearance (overrides ThreadClass)" + ); // Defaults to circles & arcs so that older files are kept intact // while new file get points, circles and arcs set in setupObject() - ADD_PROPERTY_TYPE(BaseProfileType, (BaseProfileTypeOptions::OnCirclesArcs), "Hole", App::Prop_None, "Which profile feature to base the holes on"); + ADD_PROPERTY_TYPE( + BaseProfileType, + (BaseProfileTypeOptions::OnCirclesArcs), + "Hole", + App::Prop_None, + "Which profile feature to base the holes on" + ); } void Hole::updateHoleCutParams() @@ -853,8 +651,9 @@ void Hole::updateHoleCutParams() std::string holeCutTypeStr = HoleCutType.getValueAsString(); // there is no cut, thus return - if (holeCutTypeStr == "None") + if (holeCutTypeStr == "None") { return; + } if (ThreadType.getValue() < 0) { throw Base::IndexError("Thread type out of range"); @@ -893,13 +692,14 @@ void Hole::updateHoleCutParams() calculateAndSetCounterbore(); } } - if (HoleCutDepth.getValue() == 0.0) + if (HoleCutDepth.getValue() == 0.0) { HoleCutDepth.setValue(dimen.depth); + } HoleCutDiameter.setReadOnly(false); HoleCutDepth.setReadOnly(false); HoleCutCountersinkAngle.setReadOnly(true); } - else if (holeCutTypeStr == "Countersink" || holeCutTypeStr == "Counterdrill") { + else if (holeCutTypeStr == "Countersink" || holeCutTypeStr == "Counterdrill") { // read ISO 10642 values const CutDimensionSet& counter = find_cutDimensionSet(threadTypeStr, "ISO 10642"); if (HoleCutDiameter.getValue() == 0.0 || HoleCutDiameter.getValue() <= diameterVal) { @@ -918,7 +718,8 @@ void Hole::updateHoleCutParams() if (HoleCutDepth.getValue() == 0.0) { if (holeCutTypeStr == "Counterdrill") { HoleCutDepth.setValue(1.0); - } else { + } + else { ProfileBased::onChanged(&HoleCutDiameter); } } @@ -960,7 +761,7 @@ void Hole::updateHoleCutParams() } // cut definition - CutDimensionKey key{ threadTypeStr, holeCutTypeStr }; + CutDimensionKey key {threadTypeStr, holeCutTypeStr}; if (HoleCutTypeMap.count(key)) { const CutDimensionSet& counter = find_cutDimensionSet(key); if (counter.cut_type == CutDimensionSet::Counterbore) { @@ -972,7 +773,8 @@ void Hole::updateHoleCutParams() calculateAndSetCounterbore(); // we force custom values since there are no normed ones HoleCutCustomValues.setReadOnly(true); - // important to set only if not already true, to avoid loop call of updateHoleCutParams() + // important to set only if not already true, to avoid loop call of + // updateHoleCutParams() if (!HoleCutCustomValues.getValue()) { HoleCutCustomValues.setValue(true); HoleCutDiameter.setReadOnly(false); @@ -981,15 +783,17 @@ void Hole::updateHoleCutParams() } else { // set normed values if not overwritten or if previously there - // were no normed values available and thus HoleCutCustomValues is checked and read-only + // were no normed values available and thus HoleCutCustomValues is checked and + // read-only if (!HoleCutCustomValues.getValue() || (HoleCutCustomValues.getValue() && HoleCutCustomValues.isReadOnly())) { HoleCutDiameter.setValue(dimen.diameter); HoleCutDepth.setValue(dimen.depth); HoleCutDiameter.setReadOnly(true); HoleCutDepth.setReadOnly(true); - if (HoleCutCustomValues.getValue() && HoleCutCustomValues.isReadOnly()) + if (HoleCutCustomValues.getValue() && HoleCutCustomValues.isReadOnly()) { HoleCutCustomValues.setValue(false); + } } else { HoleCutDiameter.setReadOnly(false); @@ -1008,7 +812,8 @@ void Hole::updateHoleCutParams() calculateAndSetCountersink(); // we force custom values since there are no normed ones HoleCutCustomValues.setReadOnly(true); - // important to set only if not already true, to avoid loop call of updateHoleCutParams() + // important to set only if not already true, to avoid loop call of + // updateHoleCutParams() if (!HoleCutCustomValues.getValue()) { HoleCutCustomValues.setValue(true); HoleCutDiameter.setReadOnly(false); @@ -1018,7 +823,8 @@ void Hole::updateHoleCutParams() } else { // set normed values if not overwritten or if previously there - // were no normed values available and thus HoleCutCustomValues is checked and read-only + // were no normed values available and thus HoleCutCustomValues is checked and + // read-only if (!HoleCutCustomValues.getValue() || (HoleCutCustomValues.getValue() && HoleCutCustomValues.isReadOnly())) { HoleCutDiameter.setValue(dimen.diameter); @@ -1026,8 +832,9 @@ void Hole::updateHoleCutParams() HoleCutDepth.setReadOnly(true); HoleCutCountersinkAngle.setValue(counter.angle); HoleCutCountersinkAngle.setReadOnly(true); - if (HoleCutCustomValues.getValue() && HoleCutCustomValues.isReadOnly()) + if (HoleCutCustomValues.getValue() && HoleCutCustomValues.isReadOnly()) { HoleCutCustomValues.setValue(false); + } } else { HoleCutDiameter.setReadOnly(false); @@ -1038,7 +845,6 @@ void Hole::updateHoleCutParams() } } } - } else { // we don't update for these settings but we need to set a value for new holes @@ -1050,8 +856,9 @@ void Hole::updateHoleCutParams() HoleCutDiameter.setValue(diameterVal * 1.6); HoleCutDepth.setValue(diameterVal * 0.9); } - if (HoleCutDepth.getValue() == 0.0) + if (HoleCutDepth.getValue() == 0.0) { HoleCutDepth.setValue(diameterVal * 0.9); + } HoleCutDiameter.setReadOnly(false); HoleCutDepth.setReadOnly(false); } @@ -1066,7 +873,8 @@ void Hole::updateHoleCutParams() if (HoleCutDepth.getValue() == 0.0) { if (holeCutTypeStr == "Counterdrill") { HoleCutDepth.setValue(1.0); - } else { + } + else { ProfileBased::onChanged(&HoleCutDiameter); } } @@ -1080,17 +888,12 @@ void Hole::updateHoleCutParams() double Hole::getCountersinkAngle() const { std::string threadTypeStr = ThreadType.getValueAsString(); - if ( - threadTypeStr == "BSW" - || threadTypeStr == "BSF" - ) + if (threadTypeStr == "BSW" || threadTypeStr == "BSF") { return 100.0; - if ( - threadTypeStr == "UNC" - || threadTypeStr == "UNF" - || threadTypeStr == "UNEF" - ) + } + if (threadTypeStr == "UNC" || threadTypeStr == "UNF" || threadTypeStr == "UNEF") { return 82.0; + } return 90.0; } @@ -1122,17 +925,17 @@ double Hole::getThreadRunout(int mode) const double sf = 1.0; // scale factor switch (mode) { - case 1: - sf = 1.0; - break; - case 2: - sf = 0.625; - break; - case 3: - sf = 1.6; - break; - default: - throw Base::ValueError("Unsupported argument"); + case 1: + sf = 1.0; + break; + case 2: + sf = 0.625; + break; + case 3: + sf = 1.6; + break; + default: + throw Base::ValueError("Unsupported argument"); } for (auto it : ThreadRunout) { double p = it[0]; @@ -1168,10 +971,12 @@ void Hole::updateThreadDepthParam() } else if (ThreadMethod == "Dimension") { // the thread cannot be longer than the hole depth - if (ThreadDepth.getValue() > Depth.getValue()) + if (ThreadDepth.getValue() > Depth.getValue()) { ThreadDepth.setValue(Depth.getValue()); - else + } + else { ThreadDepth.setValue(ThreadDepth.getValue()); + } } else if (ThreadMethod == "Tapped (DIN76)") { ThreadDepth.setValue(Depth.getValue() - getThreadRunout()); @@ -1186,10 +991,12 @@ void Hole::updateThreadDepthParam() } else { // the thread cannot be longer than the hole depth - if (ThreadDepth.getValue() > getThroughAllLength()) + if (ThreadDepth.getValue() > getThroughAllLength()) { ThreadDepth.setValue(getThroughAllLength()); - else + } + else { ThreadDepth.setValue(ThreadDepth.getValue()); + } } } else { @@ -1206,20 +1013,23 @@ std::optional Hole::determineDiameter() const if (threadType < 0) { // When restoring the feature it might be in an inconsistent state. // So, just silently ignore it instead of throwing an exception. - if (isRestoring()) + if (isRestoring()) { return std::nullopt; + } throw Base::IndexError("Thread type out of range"); } if (threadSize < 0) { // When restoring the feature it might be in an inconsistent state. // So, just silently ignore it instead of throwing an exception. - if (isRestoring()) + if (isRestoring()) { return std::nullopt; + } throw Base::IndexError("Thread size out of range"); } - if (threadType == 0) + if (threadType == 0) { return std::nullopt; + } double diameter = threadDescription[threadType][threadSize].diameter; double pitch = threadDescription[threadType][threadSize].pitch; @@ -1228,22 +1038,20 @@ std::optional Hole::determineDiameter() const if (Threaded.getValue()) { if (ModelThread.getValue()) { - if (UseCustomThreadClearance.getValue()) + if (UseCustomThreadClearance.getValue()) { clearance = CustomThreadClearance.getValue(); - else + } + else { clearance = getThreadClassClearance(); + } } // use normed diameters if possible std::string threadTypeStr = ThreadType.getValueAsString(); if (threadDescription[threadType][threadSize].TapDrill > 0) { diameter = threadDescription[threadType][threadSize].TapDrill + clearance; - } // if nothing is available, we must calculate - else if ( - threadTypeStr == "BSP" - || threadTypeStr == "BSW" - || threadTypeStr == "BSF" - ) { + } // if nothing is available, we must calculate + else if (threadTypeStr == "BSP" || threadTypeStr == "BSW" || threadTypeStr == "BSF") { double thread = 2 * (0.640327 * pitch); // truncation is allowed by ISO-228 and BS 84 diameter = diameter - thread * 0.75 + clearance; @@ -1257,148 +1065,148 @@ std::optional Hole::determineDiameter() const diameter = diameter - pitch + clearance; } } - else { // we have a clearance hole + else { // we have a clearance hole bool found = false; std::string threadTypeStr = ThreadType.getValueAsString(); // UTS and metric have a different clearance hole set if (threadTypeStr == "ISOMetricProfile" || threadTypeStr == "ISOMetricFineProfile") { int MatrixRowSizeMetric = sizeof(metricHoleDiameters) / sizeof(metricHoleDiameters[0]); switch (ThreadFit.getValue()) { - case 0: /* standard fit */ - // read diameter out of matrix - for (int i = 0; i < MatrixRowSizeMetric; i++) { - if (metricHoleDiameters[i][0] == diameter) { - diameter = metricHoleDiameters[i][2]; - found = true; - break; + case 0: /* standard fit */ + // read diameter out of matrix + for (int i = 0; i < MatrixRowSizeMetric; i++) { + if (metricHoleDiameters[i][0] == diameter) { + diameter = metricHoleDiameters[i][2]; + found = true; + break; + } } - } - // if nothing is defined (e.g. for M2.2, M9 and M11), we must calculate - // we use the factors defined for M5 in the metricHoleDiameters list - if (!found) { - diameter = diameter * 1.10; - } - break; - case 1: /* close fit */ - // read diameter out of matrix - for (int i = 0; i < MatrixRowSizeMetric; i++) { - if (metricHoleDiameters[i][0] == diameter) { - diameter = metricHoleDiameters[i][1]; - found = true; - break; + // if nothing is defined (e.g. for M2.2, M9 and M11), we must calculate + // we use the factors defined for M5 in the metricHoleDiameters list + if (!found) { + diameter = diameter * 1.10; } - } - // if nothing was found, we must calculate - if (!found) { - diameter = diameter * 1.06; - } - break; - case 2: /* wide fit */ - // read diameter out of matrix - for (int i = 0; i < MatrixRowSizeMetric; i++) { - if (metricHoleDiameters[i][0] == diameter) { - diameter = metricHoleDiameters[i][3]; - found = true; - break; + break; + case 1: /* close fit */ + // read diameter out of matrix + for (int i = 0; i < MatrixRowSizeMetric; i++) { + if (metricHoleDiameters[i][0] == diameter) { + diameter = metricHoleDiameters[i][1]; + found = true; + break; + } } - } - // if nothing was found, we must calculate - if (!found) { - diameter = diameter * 1.16; - } - break; - default: - throw Base::IndexError("Thread fit out of range"); + // if nothing was found, we must calculate + if (!found) { + diameter = diameter * 1.06; + } + break; + case 2: /* wide fit */ + // read diameter out of matrix + for (int i = 0; i < MatrixRowSizeMetric; i++) { + if (metricHoleDiameters[i][0] == diameter) { + diameter = metricHoleDiameters[i][3]; + found = true; + break; + } + } + // if nothing was found, we must calculate + if (!found) { + diameter = diameter * 1.16; + } + break; + default: + throw Base::IndexError("Thread fit out of range"); } } else if (threadTypeStr == "UNC" || threadTypeStr == "UNF" || threadTypeStr == "UNEF") { std::string ThreadSizeString = ThreadSize.getValueAsString(); int MatrixRowSizeUTS = sizeof(UTSHoleDiameters) / sizeof(UTSHoleDiameters[0]); switch (ThreadFit.getValue()) { - case 0: /* normal fit */ - // read diameter out of matrix - for (int i = 0; i < MatrixRowSizeUTS; i++) { - if (UTSHoleDiameters[i].designation == ThreadSizeString) { - diameter = UTSHoleDiameters[i].normal; - found = true; - break; + case 0: /* normal fit */ + // read diameter out of matrix + for (int i = 0; i < MatrixRowSizeUTS; i++) { + if (UTSHoleDiameters[i].designation == ThreadSizeString) { + diameter = UTSHoleDiameters[i].normal; + found = true; + break; + } } - } - // if nothing was found (if "#12" or "9/16"), we must calculate - // // we use the factors defined for "3/8" in the UTSHoleDiameters list - if (!found) { - diameter = diameter * 1.08; - } - break; - case 1: /* close fit */ - // read diameter out of matrix - for (int i = 0; i < MatrixRowSizeUTS; i++) { - if (UTSHoleDiameters[i].designation == ThreadSizeString) { - diameter = UTSHoleDiameters[i].close; - found = true; - break; + // if nothing was found (if "#12" or "9/16"), we must calculate + // // we use the factors defined for "3/8" in the UTSHoleDiameters list + if (!found) { + diameter = diameter * 1.08; } - } - // if nothing was found, we must calculate - if (!found) { - diameter = diameter * 1.04; - } - break; - case 2: /* loose fit */ - // read diameter out of matrix - for (int i = 0; i < MatrixRowSizeUTS; i++) { - if (UTSHoleDiameters[i].designation == ThreadSizeString) { - diameter = UTSHoleDiameters[i].loose; - found = true; - break; + break; + case 1: /* close fit */ + // read diameter out of matrix + for (int i = 0; i < MatrixRowSizeUTS; i++) { + if (UTSHoleDiameters[i].designation == ThreadSizeString) { + diameter = UTSHoleDiameters[i].close; + found = true; + break; + } } - } - // if nothing was found, we must calculate - if (!found) { - diameter = diameter * 1.12; - } - break; - default: - throw Base::IndexError("Thread fit out of range"); + // if nothing was found, we must calculate + if (!found) { + diameter = diameter * 1.04; + } + break; + case 2: /* loose fit */ + // read diameter out of matrix + for (int i = 0; i < MatrixRowSizeUTS; i++) { + if (UTSHoleDiameters[i].designation == ThreadSizeString) { + diameter = UTSHoleDiameters[i].loose; + found = true; + break; + } + } + // if nothing was found, we must calculate + if (!found) { + diameter = diameter * 1.12; + } + break; + default: + throw Base::IndexError("Thread fit out of range"); } } else { switch (ThreadFit.getValue()) { - case 0: /* normal fit */ - // we must calculate - if (!found) { - diameter = diameter * 1.1; - } - break; - case 1: /* close fit */ - if (!found) { - diameter = diameter * 1.05; - } - break; - case 2: /* loose fit */ - if (!found) { - diameter = diameter * 1.15; - } - break; - default: - throw Base::IndexError("Thread fit out of range"); + case 0: /* normal fit */ + // we must calculate + if (!found) { + diameter = diameter * 1.1; + } + break; + case 1: /* close fit */ + if (!found) { + diameter = diameter * 1.05; + } + break; + case 2: /* loose fit */ + if (!found) { + diameter = diameter * 1.15; + } + break; + default: + throw Base::IndexError("Thread fit out of range"); } } } - return std::optional{diameter}; + return std::optional {diameter}; } void Hole::updateDiameterParam() { int threadType = ThreadType.getValue(); int threadSize = ThreadSize.getValue(); - if (threadType > 0 && threadSize > 0) - ThreadDiameter.setValue( - threadDescription[threadType][threadSize].diameter - ); - if (auto opt = determineDiameter()) + if (threadType > 0 && threadSize > 0) { + ThreadDiameter.setValue(threadDescription[threadType][threadSize].diameter); + } + if (auto opt = determineDiameter()) { Diameter.setValue(opt.value()); + } } double Hole::getThreadProfileAngle() @@ -1422,7 +1230,7 @@ void Hole::findClosestDesignation() } int oldSizeIndex = ThreadSize.getValue(); - const auto &options = threadDescription[threadType]; + const auto& options = threadDescription[threadType]; double targetPitch = 0.0; if (oldSizeIndex >= 0 && oldSizeIndex < static_cast(options.size())) { targetPitch = options[oldSizeIndex].pitch; @@ -1438,7 +1246,8 @@ void Hole::findClosestDesignation() bestIndex = i; } } - } else { + } + else { // Scan all entries to find the minimal (Δdiameter, Δpitch) Euclidean distance double bestMetric = std::numeric_limits::infinity(); for (size_t i = 0; i < options.size(); ++i) { @@ -1539,8 +1348,7 @@ void Hole::onChanged(const App::Property* prop) ModelThread.setReadOnly(!isNone && isThreaded); UseCustomThreadClearance.setReadOnly(isNone || !isThreaded || !ModelThread.getValue()); CustomThreadClearance.setReadOnly( - !UseCustomThreadClearance.getValue() - || UseCustomThreadClearance.isReadOnly() + !UseCustomThreadClearance.getValue() || UseCustomThreadClearance.isReadOnly() ); std::string holeCutTypeStr; @@ -1565,7 +1373,7 @@ void Hole::onChanged(const App::Property* prop) HoleCutDepth.setReadOnly(false); HoleCutCountersinkAngle.setReadOnly(false); } - else { // screw definition + else { // screw definition HoleCutCustomValues.setReadOnly(false); if (HoleCutCustomValues.getValue()) { HoleCutDiameter.setReadOnly(false); @@ -1588,8 +1396,9 @@ void Hole::onChanged(const App::Property* prop) ProfileBased::onChanged(&Threaded); // Diameter parameter depends on this - if (type != "None") + if (type != "None") { updateDiameterParam(); + } } else if (prop == &Threaded) { std::string type(ThreadType.getValueAsString()); @@ -1605,16 +1414,19 @@ void Hole::onChanged(const App::Property* prop) CustomThreadClearance.setReadOnly(!UseCustomThreadClearance.getValue()); ThreadDepthType.setReadOnly(false); ThreadDepth.setReadOnly(std::string(ThreadDepthType.getValueAsString()) != "Dimension"); - if (Tapered.getValue() && TaperedAngle.getValue() == 90) + if (Tapered.getValue() && TaperedAngle.getValue() == 90) { TaperedAngle.setValue(getThreadProfileAngle()); + } } else { ThreadClass.setReadOnly(true); ThreadDirection.setReadOnly(true); - if (type == "None") + if (type == "None") { ThreadFit.setReadOnly(true); - else + } + else { ThreadFit.setReadOnly(false); + } ModelThread.setReadOnly(true); UseCustomThreadClearance.setReadOnly(true); CustomThreadClearance.setReadOnly(true); @@ -1643,8 +1455,9 @@ void Hole::onChanged(const App::Property* prop) else if (prop == &Tapered) { if (Tapered.getValue()) { TaperedAngle.setReadOnly(false); - if (Threaded.getValue() && TaperedAngle.getValue() == 90) + if (Threaded.getValue() && TaperedAngle.getValue() == 90) { TaperedAngle.setValue(getThreadProfileAngle()); + } } else { TaperedAngle.setValue(90); @@ -1653,8 +1466,9 @@ void Hole::onChanged(const App::Property* prop) } else if (prop == &ThreadSize) { updateDiameterParam(); - if (!isRestoring()) + if (!isRestoring()) { updateThreadDepthParam(); + } // updateHoleCutParams() will later automatically be called because } else if (prop == &ThreadFit) { @@ -1688,7 +1502,7 @@ void Hole::onChanged(const App::Property* prop) const std::string holeCutTypeString = HoleCutType.getValueAsString(); const std::string threadTypeString = ThreadType.getValueAsString(); if (!(holeCutTypeString == "Countersink" - || isDynamicCountersink(threadTypeString, holeCutTypeString))) { + || isDynamicCountersink(threadTypeString, holeCutTypeString))) { return; } auto angle = Base::toRadians(HoleCutCountersinkAngle.getValue()); @@ -1696,12 +1510,14 @@ void Hole::onChanged(const App::Property* prop) constexpr double EPSILON = 1e-6; if (angle <= 0.0 || angle >= std::numbers::pi) { HoleCutDepth.setValue(fallback); - } else { + } + else { double tanHalfAngle = std::tan(angle / 2.0); if (std::abs(tanHalfAngle) < EPSILON) { // Avoid near-zero division HoleCutDepth.setValue(fallback); - } else { + } + else { double diameter = HoleCutDiameter.getValue(); HoleCutDepth.setValue((diameter / 2.0) / tanHalfAngle); } @@ -1728,26 +1544,32 @@ void Hole::onChanged(const App::Property* prop) else if (prop == &Depth) { if (!isRestoring()) { // the depth cannot be greater than the through-all length - if (Depth.getValue() > getThroughAllLength()) + if (Depth.getValue() > getThroughAllLength()) { Depth.setValue(getThroughAllLength()); + } } - if (std::string(ThreadDepthType.getValueAsString()) != "Dimension") + if (std::string(ThreadDepthType.getValueAsString()) != "Dimension") { updateDiameterParam(); // make sure diameter and pitch are updated. + } - if (!isRestoring()) + if (!isRestoring()) { updateThreadDepthParam(); + } } else if (prop == &ThreadDepthType) { - if (!isRestoring()) + if (!isRestoring()) { updateThreadDepthParam(); - ThreadDepth.setReadOnly(Threaded.getValue() - && std::string(ThreadDepthType.getValueAsString()) != "Dimension"); + } + ThreadDepth.setReadOnly( + Threaded.getValue() && std::string(ThreadDepthType.getValueAsString()) != "Dimension" + ); } else if (prop == &ThreadDepth) { // the thread depth cannot be greater than the hole depth - if (ThreadDepth.getValue() > Depth.getValue()) + if (ThreadDepth.getValue() > Depth.getValue()) { ThreadDepth.setValue(Depth.getValue()); + } } else if (prop == &UseCustomThreadClearance) { updateDiameterParam(); @@ -1765,8 +1587,11 @@ void Hole::setupObject() // here so that new objects use points, but older files // keep the default value of "Circles and Arcs" - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/PartDesign"); + Base::Reference hGrp = App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/PartDesign"); BaseProfileType.setValue(baseProfileOption_idxToBitmask(hGrp->GetInt("defaultBaseTypeHole", 1))); @@ -1774,13 +1599,13 @@ void Hole::setupObject() } /** - * Computes 2D intersection between the lines (pa1, pa2) and (pb1, pb2). - * The lines are assumed to be crossing, and it is an error - * to specify parallel lines. - * Only the x and y coordinates of the points are used to compute the 2D intersection. - * - * The result are the x and y coordinate of the intersection point. - */ + * Computes 2D intersection between the lines (pa1, pa2) and (pb1, pb2). + * The lines are assumed to be crossing, and it is an error + * to specify parallel lines. + * Only the x and y coordinates of the points are used to compute the 2D intersection. + * + * The result are the x and y coordinate of the intersection point. + */ static void computeIntersection(gp_Pnt pa1, gp_Pnt pa2, gp_Pnt pb1, gp_Pnt pb2, double& x, double& y) { double vx1 = pa1.X() - pa2.X(); @@ -1827,31 +1652,16 @@ static void computeIntersection(gp_Pnt pa1, gp_Pnt pa2, gp_Pnt pb1, gp_Pnt pb2, short Hole::mustExecute() const { - if (ThreadType.isTouched() || - Threaded.isTouched() || - ThreadSize.isTouched() || - ThreadClass.isTouched() || - ThreadFit.isTouched() || - Diameter.isTouched() || - ThreadDirection.isTouched() || - HoleCutType.isTouched() || - HoleCutDiameter.isTouched() || - HoleCutDepth.isTouched() || - HoleCutCountersinkAngle.isTouched() || - DepthType.isTouched() || - Depth.isTouched() || - DrillPoint.isTouched() || - DrillPointAngle.isTouched() || - Tapered.isTouched() || - TaperedAngle.isTouched() || - ModelThread.isTouched() || - UseCustomThreadClearance.isTouched() || - CustomThreadClearance.isTouched() || - ThreadDepthType.isTouched() || - ThreadDepth.isTouched() || - BaseProfileType.isTouched() - ) + if (ThreadType.isTouched() || Threaded.isTouched() || ThreadSize.isTouched() + || ThreadClass.isTouched() || ThreadFit.isTouched() || Diameter.isTouched() + || ThreadDirection.isTouched() || HoleCutType.isTouched() || HoleCutDiameter.isTouched() + || HoleCutDepth.isTouched() || HoleCutCountersinkAngle.isTouched() || DepthType.isTouched() + || Depth.isTouched() || DrillPoint.isTouched() || DrillPointAngle.isTouched() + || Tapered.isTouched() || TaperedAngle.isTouched() || ModelThread.isTouched() + || UseCustomThreadClearance.isTouched() || CustomThreadClearance.isTouched() + || ThreadDepthType.isTouched() || ThreadDepth.isTouched() || BaseProfileType.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } @@ -1895,11 +1705,10 @@ static gp_Pnt toPnt(gp_Vec dir) App::DocumentObjectExecReturn* Hole::execute() { - TopoShape profileshape = - getProfileShape( Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform - | Part::ShapeOption::DontSimplifyCompound); + TopoShape profileshape = getProfileShape( + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform | Part::ShapeOption::DontSimplifyCompound + ); // Find the base shape TopoShape base; @@ -1907,10 +1716,13 @@ App::DocumentObjectExecReturn* Hole::execute() base = getBaseTopoShape(); } catch (const Base::Exception&) { - std::string text(QT_TRANSLATE_NOOP("Exception", "The requested feature cannot be created. The reason may be that:\n" + std::string text(QT_TRANSLATE_NOOP( + "Exception", + "The requested feature cannot be created. The reason may be that:\n" " - the active Body does not contain a base shape, so there is no\n" " material to be removed;\n" - " - the selected sketch does not belong to the active Body.")); + " - the selected sketch does not belong to the active Body." + )); return new App::DocumentObjectExecReturn(text); } @@ -1929,40 +1741,47 @@ App::DocumentObjectExecReturn* Hole::execute() // Get vector normal to profile Base::Vector3d SketchVector = guessNormalDirection(profileshape); - if (Reversed.getValue()) + if (Reversed.getValue()) { SketchVector *= -1.0; + } // Define this as zDir gp_Vec zDir(SketchVector.x, SketchVector.y, SketchVector.z); zDir.Transform(invObjLoc.Transformation()); gp_Vec xDir = computePerpendicular(zDir); - if (method == "Dimension") + if (method == "Dimension") { length = Depth.getValue(); + } else if (method == "UpToFirst") { /* TODO */ } else if (method == "ThroughAll") { length = getThroughAllLength(); } - else + else { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Hole error: Unsupported length specification")); + QT_TRANSLATE_NOOP("Exception", "Hole error: Unsupported length specification") + ); + } - if (length <= 0.0) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid hole depth")); + if (length <= 0.0) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid hole depth") + ); + } BRepBuilderAPI_MakeWire mkWire; const std::string holeCutType = HoleCutType.getValueAsString(); const std::string threadType = ThreadType.getValueAsString(); - bool isCountersink = (holeCutType == "Countersink" || - isDynamicCountersink(threadType, holeCutType)); - bool isCounterbore = (holeCutType == "Counterbore" || - isDynamicCounterbore(threadType, holeCutType)); + bool isCountersink + = (holeCutType == "Countersink" || isDynamicCountersink(threadType, holeCutType)); + bool isCounterbore + = (holeCutType == "Counterbore" || isDynamicCounterbore(threadType, holeCutType)); bool isCounterdrill = (holeCutType == "Counterdrill"); - double TaperedAngleVal = - Tapered.getValue() ? Base::toRadians(TaperedAngle.getValue()) : Base::toRadians(90.0); + double TaperedAngleVal = Tapered.getValue() ? Base::toRadians(TaperedAngle.getValue()) + : Base::toRadians(90.0); double radiusBottom = Diameter.getValue() / 2.0 - length / tan(TaperedAngleVal); double radius = Diameter.getValue() / 2.0; @@ -1972,8 +1791,11 @@ App::DocumentObjectExecReturn* Hole::execute() double xPosCounter = 0.0; double zPosCounter = 0.0; - if (TaperedAngleVal <= 0.0 || TaperedAngleVal > Base::toRadians(180.0)) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid taper angle")); + if (TaperedAngleVal <= 0.0 || TaperedAngleVal > Base::toRadians(180.0)) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid taper angle") + ); + } if (isCountersink || isCounterbore || isCounterdrill) { double holeCutRadius = HoleCutDiameter.getValue() / 2.0; @@ -1993,16 +1815,25 @@ App::DocumentObjectExecReturn* Hole::execute() // HoleCutDiameter was calculated. } - if (holeCutRadius < radius) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Hole cut diameter too small")); - - if (holeCutDepth > length) + if (holeCutRadius < radius) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Hole error: Hole cut depth must be less than hole depth")); + QT_TRANSLATE_NOOP("Exception", "Hole error: Hole cut diameter too small") + ); + } - if (holeCutDepth < 0.0) - return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Hole error: Hole cut depth must be greater or equal to zero")); + if (holeCutDepth > length) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Hole error: Hole cut depth must be less than hole depth" + )); + } + + if (holeCutDepth < 0.0) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Hole error: Hole cut depth must be greater or equal to zero" + )); + } // Top point gp_Pnt newPoint = toPnt(holeCutRadius * xDir); @@ -2017,14 +1848,20 @@ App::DocumentObjectExecReturn* Hole::execute() } // Compute intersection of tapered edge and line at bottom of counterbore hole - computeIntersection(gp_Pnt(holeCutRadius, -holeCutDepth, 0 ), - gp_Pnt(holeCutRadius - sin(countersinkAngle), - -cos(countersinkAngle) - holeCutDepth, 0), - gp_Pnt(radius, 0, 0), - gp_Pnt(radiusBottom, -length, 0), xPosCounter, zPosCounter); + computeIntersection( + gp_Pnt(holeCutRadius, -holeCutDepth, 0), + gp_Pnt(holeCutRadius - sin(countersinkAngle), -cos(countersinkAngle) - holeCutDepth, 0), + gp_Pnt(radius, 0, 0), + gp_Pnt(radiusBottom, -length, 0), + xPosCounter, + zPosCounter + ); - if (-length > zPosCounter) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid countersink")); + if (-length > zPosCounter) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid countersink") + ); + } lengthCounter = zPosCounter; newPoint = toPnt(xPosCounter * xDir + zPosCounter * zDir); @@ -2056,18 +1893,28 @@ App::DocumentObjectExecReturn* Hole::execute() bool isDrillForDepth = DrillForDepth.getValue(); // the angle is in any case > 0 and < 90 but nevertheless this safeguard: - if (drillPointAngle <= 0.0 || drillPointAngle >= Base::toRadians(180.0)) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid drill point angle")); + if (drillPointAngle <= 0.0 || drillPointAngle >= Base::toRadians(180.0)) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid drill point angle") + ); + } // if option to take drill point size into account // the next wire point is the intersection of the drill edge and the hole edge if (isDrillForDepth) { - computeIntersection(gp_Pnt(0, -length, 0), + computeIntersection( + gp_Pnt(0, -length, 0), gp_Pnt(radius, radius * tan(drillPointAngle) - length, 0), gp_Pnt(radius, 0, 0), - gp_Pnt(radiusBottom, -length, 0), xPosDrill, zPosDrill); - if (zPosDrill > 0 || zPosDrill >= lengthCounter) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid drill point")); + gp_Pnt(radiusBottom, -length, 0), + xPosDrill, + zPosDrill + ); + if (zPosDrill > 0 || zPosDrill >= lengthCounter) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Invalid drill point") + ); + } newPoint = toPnt(xPosDrill * xDir + zPosDrill * zDir); mkWire.Add(BRepBuilderAPI_MakeEdge(lastPoint, newPoint)); @@ -2100,12 +1947,18 @@ App::DocumentObjectExecReturn* Hole::execute() double angle = Base::toRadians(360.0); BRepPrimAPI_MakeRevol RevolMaker(face, gp_Ax1(firstPoint, zDir), angle); - if (!RevolMaker.IsDone()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Could not revolve sketch")); + if (!RevolMaker.IsDone()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Could not revolve sketch") + ); + } TopoDS_Shape protoHole = RevolMaker.Shape(); - if (protoHole.IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Resulting shape is empty")); + if (protoHole.IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Resulting shape is empty") + ); + } // Make thread @@ -2114,8 +1967,11 @@ App::DocumentObjectExecReturn* Hole::execute() // fuse the thread to the hole FCBRepAlgoAPI_Fuse mkFuse(protoHole, protoThread); - if (!mkFuse.IsDone()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Error: Adding the thread failed")); + if (!mkFuse.IsDone()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Error: Adding the thread failed") + ); + } // we reuse the name protoHole (only now it is threaded) protoHole = mkFuse.Shape(); @@ -2123,7 +1979,9 @@ App::DocumentObjectExecReturn* Hole::execute() std::vector holes; auto compound = findHoles(holes, profileshape, protoHole); if (holes.empty()) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Hole error: Finding axis failed")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Hole error: Finding axis failed") + ); } TopoShape result(0); @@ -2139,7 +1997,7 @@ App::DocumentObjectExecReturn* Hole::execute() // First try cutting with compound which will be faster as it is done in // parallel bool retry = true; - const char *maker; + const char* maker; switch (getAddSubType()) { case Additive: maker = Part::OpCodes::Fuse; @@ -2148,39 +2006,55 @@ App::DocumentObjectExecReturn* Hole::execute() maker = Part::OpCodes::Cut; } try { - if (base.isNull()) + if (base.isNull()) { result = compound; - else - result.makeElementBoolean(maker, {base,compound}); + } + else { + result.makeElementBoolean(maker, {base, compound}); + } result = getSolid(result); retry = false; - } catch (Standard_Failure & e) { - FC_WARN(getFullName() << ": boolean operation with compound failed (" - << e.GetMessageString() << "), retry…"); - } catch (Base::Exception & e) { - FC_WARN(getFullName() << ": boolean operation with compound failed (" << e.what() - << "), retry…"); + } + catch (Standard_Failure& e) { + FC_WARN( + getFullName() << ": boolean operation with compound failed (" + << e.GetMessageString() << "), retry…" + ); + } + catch (Base::Exception& e) { + FC_WARN( + getFullName() << ": boolean operation with compound failed (" << e.what() << "), retry…" + ); } if (retry) { int i = 0; - for (auto & hole : holes) { + for (auto& hole : holes) { ++i; try { - result.makeElementBoolean(maker, {base,hole}); - } catch (Standard_Failure &) { - std::string msg(QT_TRANSLATE_NOOP("Exception", "Boolean operation failed on profile Edge")); + result.makeElementBoolean(maker, {base, hole}); + } + catch (Standard_Failure&) { + std::string msg( + QT_TRANSLATE_NOOP("Exception", "Boolean operation failed on profile Edge") + ); msg += std::to_string(i); return new App::DocumentObjectExecReturn(msg.c_str()); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); - std::string msg(QT_TRANSLATE_NOOP("Exception", "Boolean operation failed on profile Edge")); + std::string msg( + QT_TRANSLATE_NOOP("Exception", "Boolean operation failed on profile Edge") + ); msg += std::to_string(i); return new App::DocumentObjectExecReturn(msg.c_str()); } base = getSolid(result); if (base.isNull()) { - std::string msg(QT_TRANSLATE_NOOP("Exception", "Boolean operation produced non-solid on profile Edge")); + std::string msg(QT_TRANSLATE_NOOP( + "Exception", + "Boolean operation produced non-solid on profile Edge" + )); msg += std::to_string(i); return new App::DocumentObjectExecReturn(msg.c_str()); } @@ -2190,8 +2064,10 @@ App::DocumentObjectExecReturn* Hole::execute() result = refineShapeIfActive(result); if (!isSingleSolidRuleSatisfied(result.getShape())) { - return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } this->Shape.setValue(result); @@ -2200,36 +2076,43 @@ App::DocumentObjectExecReturn* Hole::execute() catch (Standard_Failure& e) { if (std::string(e.GetMessageString()) == "TopoDS::Face" && (std::string(DepthType.getValueAsString()) == "UpToFirst" - || std::string(DepthType.getValueAsString()) == "UpToFace")) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", + || std::string(DepthType.getValueAsString()) == "UpToFace")) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", "Could not create face from sketch.\n" "Intersecting sketch entities or multiple faces in a sketch are not allowed " - "for making a pocket up to a face.")); - else + "for making a pocket up to a face." + )); + } + else { return new App::DocumentObjectExecReturn(e.GetMessageString()); + } } catch (Base::Exception& e) { return new App::DocumentObjectExecReturn(e.what()); } } -void Hole::rotateToNormal(const gp_Dir& helixAxis, const gp_Dir& normalAxis, - TopoDS_Shape& helixShape) const +void Hole::rotateToNormal(const gp_Dir& helixAxis, const gp_Dir& normalAxis, TopoDS_Shape& helixShape) const { auto getRotationAxis = [](const gp_Dir& dir1, const gp_Dir& dir2, gp_Dir& dir3, double& angle) { - if (dir1.IsEqual(dir2, Precision::Angular())) + if (dir1.IsEqual(dir2, Precision::Angular())) { return false; + } angle = acos(dir1 * dir2); if (dir1.IsOpposite(dir2, Precision::Angular())) { // Create a vector that is not parallel to dir1 gp_XYZ xyz(dir1.XYZ()); - if (fabs(xyz.X()) <= fabs(xyz.Y()) && fabs(xyz.X()) <= fabs(xyz.Z())) + if (fabs(xyz.X()) <= fabs(xyz.Y()) && fabs(xyz.X()) <= fabs(xyz.Z())) { xyz.SetX(1.0); - else if (fabs(xyz.Y()) <= fabs(xyz.X()) && fabs(xyz.Y()) <= fabs(xyz.Z())) + } + else if (fabs(xyz.Y()) <= fabs(xyz.X()) && fabs(xyz.Y()) <= fabs(xyz.Z())) { xyz.SetY(1.0); - else + } + else { xyz.SetZ(1.0); + } dir3 = dir1.Crossed(gp_Dir(xyz)); } else { @@ -2255,12 +2138,15 @@ gp_Vec Hole::computePerpendicular(const gp_Vec& zDir) const gp_Vec xDir; /* Compute xDir normal to zDir */ - if (std::abs(zDir.Z() - zDir.X()) > Precision::Confusion()) + if (std::abs(zDir.Z() - zDir.X()) > Precision::Confusion()) { xDir = gp_Vec(zDir.Z(), 0, -zDir.X()); - else if (std::abs(zDir.Z() - zDir.Y()) > Precision::Confusion()) + } + else if (std::abs(zDir.Z() - zDir.Y()) > Precision::Confusion()) { xDir = gp_Vec(zDir.Y(), -zDir.X(), 0); - else + } + else { xDir = gp_Vec(0, -zDir.Z(), zDir.Y()); + } // Normalize xDir; this is needed as the computation above does not necessarily give // a unit-length vector. @@ -2283,19 +2169,24 @@ Base::Vector3d Hole::guessNormalDirection(const TopoShape& profileshape) const return getProfileNormal(); } -TopoShape Hole::findHoles(std::vector &holes, - const TopoShape& profileshape, - const TopoDS_Shape& protoHole) const +TopoShape Hole::findHoles( + std::vector& holes, + const TopoShape& profileshape, + const TopoDS_Shape& protoHole +) const { TopoShape result(0); auto addHole = [&](Part::TopoShape const& baseshape, gp_Pnt loc) { gp_Trsf localSketchTransformation; - localSketchTransformation.SetTranslation( gp_Pnt( 0, 0, 0 ), - gp_Pnt(loc.X(), loc.Y(), loc.Z()) ); + localSketchTransformation.SetTranslation(gp_Pnt(0, 0, 0), gp_Pnt(loc.X(), loc.Y(), loc.Z())); Part::ShapeMapper mapper; - mapper.populate(Part::MappingStatus::Modified, baseshape, TopoShape(protoHole).getSubTopoShapes(TopAbs_FACE)); + mapper.populate( + Part::MappingStatus::Modified, + baseshape, + TopoShape(protoHole).getSubTopoShapes(TopAbs_FACE) + ); TopoShape hole(-getID()); hole.makeShapeWithElementMap(protoHole, mapper, {baseshape}); @@ -2308,9 +2199,9 @@ TopoShape Hole::findHoles(std::vector &holes, int baseProfileType = BaseProfileType.getValue(); // Iterate over edges and filter out non-circle/non-arc types - if (baseProfileType & BaseProfileTypeOptions::OnCircles || - baseProfileType & BaseProfileTypeOptions::OnArcs) { - for (const auto &profileEdge : profileshape.getSubTopoShapes(TopAbs_EDGE)) { + if (baseProfileType & BaseProfileTypeOptions::OnCircles + || baseProfileType & BaseProfileTypeOptions::OnArcs) { + for (const auto& profileEdge : profileshape.getSubTopoShapes(TopAbs_EDGE)) { TopoDS_Edge edge = TopoDS::Edge(profileEdge.getShape()); BRepAdaptor_Curve adaptor(edge); @@ -2337,7 +2228,7 @@ TopoShape Hole::findHoles(std::vector &holes, // holes on points if (baseProfileType & BaseProfileTypeOptions::OnPoints) { // Iterate over vertices while avoiding edges so that curve handles are ignored - for (const auto &profileVertex : profileshape.getSubTopoShapes(TopAbs_VERTEX, TopAbs_EDGE)) { + for (const auto& profileVertex : profileshape.getSubTopoShapes(TopAbs_VERTEX, TopAbs_EDGE)) { TopoDS_Vertex vertex = TopoDS::Vertex(profileVertex.getShape()); addHole(profileVertex, BRep_Tool::Pnt(vertex)); @@ -2366,11 +2257,13 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len double Rmaj = threadDescription[threadType][threadSize].diameter / 2; double Pitch = getThreadPitch(); - double clearance; // clearance to be added on the diameter - if (UseCustomThreadClearance.getValue()) + double clearance; // clearance to be added on the diameter + if (UseCustomThreadClearance.getValue()) { clearance = CustomThreadClearance.getValue() / 2; - else + } + else { clearance = getThreadClassClearance() / 2; + } double RmajC = Rmaj + clearance; double marginZ = 0.001; @@ -2378,8 +2271,8 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len double H; std::string threadTypeStr = ThreadType.getValueAsString(); if (threadTypeStr == "BSP" || threadTypeStr == "BSW" || threadTypeStr == "BSF") { - H = 0.960491 * Pitch; // Height of Sharp V - double radius = 0.137329 * Pitch; // radius of the crest + H = 0.960491 * Pitch; // Height of Sharp V + double radius = 0.137329 * Pitch; // radius of the crest // construct the cross section going counter-clockwise // -------------- // P | p4 @@ -2393,30 +2286,25 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len // the little adjustment of p1 and p4 is here to prevent coincidencies double marginX = std::tan(Base::toRadians(62.5)) * marginZ; - gp_Pnt p1 = toPnt( - (RmajC - 5 * H / 6 + marginX) * xDir - + marginZ * zDir - ); - gp_Pnt p4 = toPnt( - (RmajC - 5 * H / 6 + marginX) * xDir - + (Pitch - marginZ) * zDir - ); + gp_Pnt p1 = toPnt((RmajC - 5 * H / 6 + marginX) * xDir + marginZ * zDir); + gp_Pnt p4 = toPnt((RmajC - 5 * H / 6 + marginX) * xDir + (Pitch - marginZ) * zDir); // Calculate positions for p2 and p3 double p23x = RmajC - radius * 0.58284013094; gp_Pnt p2 = toPnt(p23x * xDir + 3 * Pitch / 8 * zDir); gp_Pnt p3 = toPnt(p23x * xDir + 5 * Pitch / 8 * zDir); - gp_Pnt crest = toPnt((RmajC) * xDir + Pitch / 2 * zDir); + gp_Pnt crest = toPnt((RmajC)*xDir + Pitch / 2 * zDir); mkThreadWire.Add(BRepBuilderAPI_MakeEdge(p1, p2).Edge()); Handle(Geom_TrimmedCurve) arc1 = GC_MakeArcOfCircle(p2, crest, p3).Value(); mkThreadWire.Add(BRepBuilderAPI_MakeEdge(arc1).Edge()); mkThreadWire.Add(BRepBuilderAPI_MakeEdge(p3, p4).Edge()); mkThreadWire.Add(BRepBuilderAPI_MakeEdge(p4, p1).Edge()); - } else { - H = sqrt(3) / 2 * Pitch; // height of fundamental triangle - double h = 7 * H / 8; // distance from Rmaj to the base + } + else { + H = sqrt(3) / 2 * Pitch; // height of fundamental triangle + double h = 7 * H / 8; // distance from Rmaj to the base // construct the cross section going counter-clockwise // pitch // -------------- @@ -2429,23 +2317,18 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len // the little adjustment of p1 and p4 is here to prevent coincidencies double marginX = std::tan(Base::toRadians(60.0)) * marginZ; - gp_Pnt p1 = toPnt( - (RmajC - h + marginX) * xDir - + marginZ * zDir - ); - gp_Pnt p2 = toPnt((RmajC) * xDir + 7 * Pitch / 16 * zDir); - gp_Pnt p3 = toPnt((RmajC) * xDir + 9 * Pitch / 16 * zDir); - gp_Pnt p4 = toPnt( - (RmajC - h + marginX) * xDir - + (Pitch - marginZ) * zDir - ); + gp_Pnt p1 = toPnt((RmajC - h + marginX) * xDir + marginZ * zDir); + gp_Pnt p2 = toPnt((RmajC)*xDir + 7 * Pitch / 16 * zDir); + gp_Pnt p3 = toPnt((RmajC)*xDir + 9 * Pitch / 16 * zDir); + gp_Pnt p4 = toPnt((RmajC - h + marginX) * xDir + (Pitch - marginZ) * zDir); mkThreadWire.Add(BRepBuilderAPI_MakeEdge(p1, p2).Edge()); if (threadTypeStr == "ISOTyre") { gp_Pnt crest = toPnt((RmajC + (Pitch / 32)) * xDir + Pitch / 2 * zDir); Handle(Geom_TrimmedCurve) arc1 = GC_MakeArcOfCircle(p2, crest, p3).Value(); mkThreadWire.Add(BRepBuilderAPI_MakeEdge(arc1).Edge()); - } else { + } + else { mkThreadWire.Add(BRepBuilderAPI_MakeEdge(p2, p3).Edge()); } mkThreadWire.Add(BRepBuilderAPI_MakeEdge(p3, p4).Edge()); @@ -2455,7 +2338,7 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len mkThreadWire.Build(); TopoDS_Wire threadWire = mkThreadWire.Wire(); - //create the helix path + // create the helix path double threadDepth = ThreadDepth.getValue(); double helixLength = threadDepth + Pitch / 2; double holeDepth = Depth.getValue(); @@ -2472,7 +2355,7 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len ThreadDepth.setValue(threadDepth); helixLength = threadDepth + Pitch / 2; } - else { // Hole depth + else { // Hole depth threadDepth = holeDepth; ThreadDepth.setValue(threadDepth); helixLength = threadDepth + Pitch / 8; @@ -2482,12 +2365,12 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len if (depthMethod == "Dimension") { // the thread must not be deeper than the hole // thus the max helixLength is holeDepth + P / 8; - if (threadDepth > (holeDepth - Pitch / 2)) + if (threadDepth > (holeDepth - Pitch / 2)) { helixLength = holeDepth + Pitch / 8; + } } } - double helixAngle = - Tapered.getValue() ? TaperedAngle.getValue() - 90 : 0.0; + double helixAngle = Tapered.getValue() ? TaperedAngle.getValue() - 90 : 0.0; TopoDS_Shape helix = TopoShape().makeLongHelix(Pitch, helixLength, Rmaj, helixAngle, leftHanded); gp_Pnt origo(0.0, 0.0, 0.0); @@ -2507,10 +2390,11 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len BRepOffsetAPI_MakePipeShell mkPS(TopoDS::Wire(helix)); mkPS.SetTolerance(Precision::Confusion()); mkPS.SetTransitionMode(BRepBuilderAPI_Transformed); - mkPS.SetMode(true); //This is for frenet + mkPS.SetMode(true); // This is for frenet mkPS.Add(threadWire); - if (!mkPS.IsReady()) + if (!mkPS.IsReady()) { throw Base::CADKernelError(QT_TRANSLATE_NOOP("Exception", "Error: Thread could not be built")); + } TopoDS_Shape shell = mkPS.Shape(); // create faces at the ends of the pipe shell @@ -2534,15 +2418,17 @@ TopoDS_Shape Hole::makeThread(const gp_Vec& xDir, const gp_Vec& zDir, double len // make the closed off shell into a solid BRepBuilderAPI_MakeSolid mkSolid; mkSolid.Add(TopoDS::Shell(sewer.SewedShape())); - if (!mkSolid.IsDone()) + if (!mkSolid.IsDone()) { throw Base::CADKernelError(QT_TRANSLATE_NOOP("Exception", "Error: Result is not a solid")); + } TopoDS_Shape result = mkSolid.Shape(); // check if the algorithm has confused the inside and outside of the solid BRepClass3d_SolidClassifier SC(result); SC.PerformInfinitePoint(Precision::Confusion()); - if (SC.State() == TopAbs_IN) + if (SC.State() == TopAbs_IN) { result.Reverse(); + } // we are done return result; @@ -2555,46 +2441,44 @@ void Hole::addCutType(const CutDimensionSet& dimensions) std::vector* list; switch (thread) { - case CutDimensionSet::Metric: - HoleCutTypeMap.emplace(CutDimensionKey("ISOMetricProfile", name), dimensions); - list = &HoleCutType_ISOmetric_Enums; - break; - case CutDimensionSet::MetricFine: - HoleCutTypeMap.emplace(CutDimensionKey("ISOMetricFineProfile", name), dimensions); - list = &HoleCutType_ISOmetricfine_Enums; - break; - default: - return; + case CutDimensionSet::Metric: + HoleCutTypeMap.emplace(CutDimensionKey("ISOMetricProfile", name), dimensions); + list = &HoleCutType_ISOmetric_Enums; + break; + case CutDimensionSet::MetricFine: + HoleCutTypeMap.emplace(CutDimensionKey("ISOMetricFineProfile", name), dimensions); + list = &HoleCutType_ISOmetricfine_Enums; + break; + default: + return; } // add the collected lists of JSON definitions to the lists // if a name doesn't already exist in the list - if (std::all_of(list->begin(), list->end(), - [name](const std::string& x) { return x != name; })) + if (std::all_of(list->begin(), list->end(), [name](const std::string& x) { return x != name; })) { list->push_back(name); + } } -bool Hole::isDynamicCounterbore(const std::string& thread, - const std::string& holeCutType) +bool Hole::isDynamicCounterbore(const std::string& thread, const std::string& holeCutType) { - CutDimensionKey key{ thread, holeCutType }; - return HoleCutTypeMap.count(key) && - HoleCutTypeMap.find(key)->second.cut_type == CutDimensionSet::Counterbore; + CutDimensionKey key {thread, holeCutType}; + return HoleCutTypeMap.count(key) + && HoleCutTypeMap.find(key)->second.cut_type == CutDimensionSet::Counterbore; } -bool Hole::isDynamicCountersink(const std::string& thread, - const std::string& holeCutType) +bool Hole::isDynamicCountersink(const std::string& thread, const std::string& holeCutType) { - CutDimensionKey key{ thread, holeCutType }; - return HoleCutTypeMap.count(key) && - HoleCutTypeMap.find(key)->second.cut_type == CutDimensionSet::Countersink; + CutDimensionKey key {thread, holeCutType}; + return HoleCutTypeMap.count(key) + && HoleCutTypeMap.find(key)->second.cut_type == CutDimensionSet::Countersink; } /* * Counter Dimensions */ -const Hole::CounterBoreDimension Hole::CounterBoreDimension::nothing{ "None", 0.0, 0.0 }; -const Hole::CounterSinkDimension Hole::CounterSinkDimension::nothing{ "None", 0.0 }; +const Hole::CounterBoreDimension Hole::CounterBoreDimension::nothing {"None", 0.0, 0.0}; +const Hole::CounterSinkDimension Hole::CounterSinkDimension::nothing {"None", 0.0}; void Hole::calculateAndSetCounterbore() { @@ -2618,19 +2502,18 @@ void Hole::calculateAndSetCountersink() } -Hole::CutDimensionKey::CutDimensionKey(const std::string& t, const std::string& c) : - thread_type{ t }, cut_name{ c } -{ -} +Hole::CutDimensionKey::CutDimensionKey(const std::string& t, const std::string& c) + : thread_type {t} + , cut_name {c} +{} bool Hole::CutDimensionKey::operator<(const CutDimensionKey& b) const { - return thread_type < b.thread_type || - (thread_type == b.thread_type && cut_name < b.cut_name); + return thread_type < b.thread_type || (thread_type == b.thread_type && cut_name < b.cut_name); } -const Hole::CutDimensionSet& Hole::find_cutDimensionSet(const std::string& t, - const std::string& c) { +const Hole::CutDimensionSet& Hole::find_cutDimensionSet(const std::string& t, const std::string& c) +{ return HoleCutTypeMap.find(CutDimensionKey(t, c))->second; } @@ -2639,36 +2522,58 @@ const Hole::CutDimensionSet& Hole::find_cutDimensionSet(const CutDimensionKey& k return HoleCutTypeMap.find(k)->second; } -Hole::CutDimensionSet::CutDimensionSet(const std::string& nme, - std::vector&& d, CutType cut, ThreadType thread, double a) : - bore_data{ std::move(d) }, cut_type{ cut }, thread_type{ thread }, name{ nme }, angle{ a } -{ -} +Hole::CutDimensionSet::CutDimensionSet( + const std::string& nme, + std::vector&& d, + CutType cut, + ThreadType thread, + double a +) + : bore_data {std::move(d)} + , cut_type {cut} + , thread_type {thread} + , name {nme} + , angle {a} +{} -Hole::CutDimensionSet::CutDimensionSet(const std::string& nme, - std::vector&& d, CutType cut, ThreadType thread, double a) : - sink_data{ std::move(d) }, cut_type{ cut }, thread_type{ thread }, name{ nme }, angle{ a } -{ -} +Hole::CutDimensionSet::CutDimensionSet( + const std::string& nme, + std::vector&& d, + CutType cut, + ThreadType thread, + double a +) + : sink_data {std::move(d)} + , cut_type {cut} + , thread_type {thread} + , name {nme} + , angle {a} +{} const Hole::CounterBoreDimension& Hole::CutDimensionSet::get_bore(const std::string& t) const { - auto i = std::find_if(bore_data.begin(), bore_data.end(), - [t](const Hole::CounterBoreDimension& x) { return x.thread == t; }); - if (i == bore_data.end()) + auto i = std::find_if(bore_data.begin(), bore_data.end(), [t](const Hole::CounterBoreDimension& x) { + return x.thread == t; + }); + if (i == bore_data.end()) { return CounterBoreDimension::nothing; - else + } + else { return *i; + } } const Hole::CounterSinkDimension& Hole::CutDimensionSet::get_sink(const std::string& t) const { - auto i = std::find_if(sink_data.begin(), sink_data.end(), - [t](const Hole::CounterSinkDimension& x) { return x.thread == t; }); - if (i == sink_data.end()) + auto i = std::find_if(sink_data.begin(), sink_data.end(), [t](const Hole::CounterSinkDimension& x) { + return x.thread == t; + }); + if (i == sink_data.end()) { return CounterSinkDimension::nothing; - else + } + else { return *i; + } } void from_json(const nlohmann::json& j, Hole::CounterBoreDimension& t) @@ -2688,44 +2593,49 @@ void from_json(const nlohmann::json& j, Hole::CutDimensionSet& t) { t.name = j["name"].get(); - std::string thread_type_string = j["thread_type"].get(); - if (thread_type_string == "metric") + std::string thread_type_string = j["thread_type"].get(); + if (thread_type_string == "metric") { t.thread_type = Hole::CutDimensionSet::Metric; - else if (thread_type_string == "metricfine") + } + else if (thread_type_string == "metricfine") { t.thread_type = Hole::CutDimensionSet::MetricFine; - else + } + else { throw Base::IndexError(std::string("Thread type '") + thread_type_string + "' unsupported"); + } - std::string cut_type_string = j["cut_type"].get(); + std::string cut_type_string = j["cut_type"].get(); if (cut_type_string == "counterbore") { t.cut_type = Hole::CutDimensionSet::Counterbore; - t.bore_data = j["data"].get >(); + t.bore_data = j["data"].get>(); t.angle = 0.0; } else if (cut_type_string == "countersink") { t.cut_type = Hole::CutDimensionSet::Countersink; - t.sink_data = j["data"].get >(); + t.sink_data = j["data"].get>(); t.angle = j["angle"].get(); } - else + else { throw Base::IndexError(std::string("Cut type '") + cut_type_string + "' unsupported"); + } t.name = j["name"].get(); } void Hole::readCutDefinitions() { - std::vector dirs{ + std::vector dirs { ::App::Application::getResourceDir() + "Mod/PartDesign/Resources/Hole", ::App::Application::getUserAppDataDir() + "PartDesign/Hole" }; std::clog << "Looking for thread definitions in: "; - for (auto& i : dirs) + for (auto& i : dirs) { std::clog << i << " "; + } std::clog << "\n"; for (auto& dir : dirs) { - std::vector<::Base::FileInfo> files{ ::Base::FileInfo(dir).getDirectoryContent() }; + std::vector<::Base::FileInfo> files {::Base::FileInfo(dir).getDirectoryContent()}; for (const auto& f : files) { if (f.extension() == "json") { try { @@ -2753,7 +2663,7 @@ int Hole::baseProfileOption_idxToBitmask(int index) if (index == 1) { return PartDesign::Hole::BaseProfileTypeOptions::OnPointsCirclesArcs; } - if (index == 2) { + if (index == 2) { return PartDesign::Hole::BaseProfileTypeOptions::OnPoints; } Base::Console().error("Unexpected hole base profile combobox index: %i", index); @@ -2776,6 +2686,4 @@ int Hole::baseProfileOption_bitmaskToIdx(int bitmask) } -} // namespace PartDesign - - +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureHole.h b/src/Mod/PartDesign/App/FeatureHole.h index 579023a992..971a7ec632 100644 --- a/src/Mod/PartDesign/App/FeatureHole.h +++ b/src/Mod/PartDesign/App/FeatureHole.h @@ -31,7 +31,8 @@ class Property; -namespace Base { +namespace Base +{ class XMLReader; } @@ -41,45 +42,46 @@ namespace PartDesign static constexpr size_t ThreadClass_ISOmetric_data_size = 25; static constexpr size_t ThreadRunout_size = 24; -class PartDesignExport Hole : public ProfileBased +class PartDesignExport Hole: public ProfileBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Hole); public: Hole(); - App::PropertyBool Threaded; - App::PropertyBool ModelThread; - App::PropertyLength ThreadPitch; - App::PropertyEnumeration ThreadType; - App::PropertyEnumeration ThreadSize; - App::PropertyEnumeration ThreadClass; - App::PropertyEnumeration ThreadFit; - App::PropertyLength Diameter; - App::PropertyLength ThreadDiameter; - App::PropertyEnumeration ThreadDirection; - App::PropertyEnumeration HoleCutType; - App::PropertyBool HoleCutCustomValues; - App::PropertyLength HoleCutDiameter; - App::PropertyLength HoleCutDepth; - App::PropertyAngle HoleCutCountersinkAngle; - App::PropertyEnumeration DepthType; - App::PropertyLength Depth; - App::PropertyEnumeration ThreadDepthType; - App::PropertyLength ThreadDepth; - App::PropertyEnumeration DrillPoint; - App::PropertyAngle DrillPointAngle; - App::PropertyBool DrillForDepth; - App::PropertyBool Tapered; - App::PropertyAngle TaperedAngle; - App::PropertyBool UseCustomThreadClearance; - App::PropertyLength CustomThreadClearance; - App::PropertyInteger BaseProfileType; + App::PropertyBool Threaded; + App::PropertyBool ModelThread; + App::PropertyLength ThreadPitch; + App::PropertyEnumeration ThreadType; + App::PropertyEnumeration ThreadSize; + App::PropertyEnumeration ThreadClass; + App::PropertyEnumeration ThreadFit; + App::PropertyLength Diameter; + App::PropertyLength ThreadDiameter; + App::PropertyEnumeration ThreadDirection; + App::PropertyEnumeration HoleCutType; + App::PropertyBool HoleCutCustomValues; + App::PropertyLength HoleCutDiameter; + App::PropertyLength HoleCutDepth; + App::PropertyAngle HoleCutCountersinkAngle; + App::PropertyEnumeration DepthType; + App::PropertyLength Depth; + App::PropertyEnumeration ThreadDepthType; + App::PropertyLength ThreadDepth; + App::PropertyEnumeration DrillPoint; + App::PropertyAngle DrillPointAngle; + App::PropertyBool DrillForDepth; + App::PropertyBool Tapered; + App::PropertyAngle TaperedAngle; + App::PropertyBool UseCustomThreadClearance; + App::PropertyLength CustomThreadClearance; + App::PropertyInteger BaseProfileType; - enum BaseProfileTypeOptions { - OnPoints = 1 << 0, - OnCircles = 1 << 1, - OnArcs = 1 << 2, + enum BaseProfileTypeOptions + { + OnPoints = 1 << 0, + OnCircles = 1 << 1, + OnArcs = 1 << 2, // Common combos OnPointsCirclesArcs = OnPoints | OnCircles | OnArcs, @@ -91,17 +93,19 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderHole"; } //@} short mustExecute() const override; - using ThreadDescription = struct { - const char * designation; + using ThreadDescription = struct + { + const char* designation; double diameter; double pitch; double TapDrill; @@ -110,7 +114,8 @@ public: static const double metricHoleDiameters[51][4]; - using UTSClearanceDefinition = struct { + using UTSClearanceDefinition = struct + { std::string designation; double close; double normal; @@ -118,14 +123,18 @@ public: }; static const UTSClearanceDefinition UTSHoleDiameters[23]; - void Restore(Base::XMLReader & reader) override; + void Restore(Base::XMLReader& reader) override; virtual void updateProps(); - bool isDynamicCounterbore(const std::string &thread, const std::string &holeCutType); - bool isDynamicCountersink(const std::string &thread, const std::string &holeCutType); + bool isDynamicCounterbore(const std::string& thread, const std::string& holeCutType); + bool isDynamicCountersink(const std::string& thread, const std::string& holeCutType); Base::Vector3d guessNormalDirection(const TopoShape& profileshape) const; - TopoShape findHoles(std::vector &holes, const TopoShape& profileshape, const TopoDS_Shape& protohole) const; + TopoShape findHoles( + std::vector& holes, + const TopoShape& profileshape, + const TopoDS_Shape& protohole + ) const; protected: void onChanged(const App::Property* prop) override; @@ -186,35 +195,60 @@ private: static const double ThreadRunout[ThreadRunout_size][2]; /* Counter-xxx */ -//public: - // Dimension for counterbore - struct CounterBoreDimension { + // public: + // Dimension for counterbore + struct CounterBoreDimension + { std::string thread; double diameter; double depth; static const CounterBoreDimension nothing; }; // Dimension for countersink - struct CounterSinkDimension { + struct CounterSinkDimension + { std::string thread; double diameter; static const CounterSinkDimension nothing; }; // cut dimensions for a screwtype - class CutDimensionSet { + class CutDimensionSet + { public: - enum CutType { Counterbore, Countersink }; - enum ThreadType { Metric, MetricFine }; + enum CutType + { + Counterbore, + Countersink + }; + enum ThreadType + { + Metric, + MetricFine + }; - CutDimensionSet():cut_type(Counterbore),thread_type(Metric),angle(0.0) {} - CutDimensionSet(const std::string &nme, - std::vector &&d, CutType cut, ThreadType thread, double angle = 0.0); - CutDimensionSet(const std::string &nme, - std::vector &&d, CutType cut, ThreadType thread, double angle = 0.0); + CutDimensionSet() + : cut_type(Counterbore) + , thread_type(Metric) + , angle(0.0) + {} + CutDimensionSet( + const std::string& nme, + std::vector&& d, + CutType cut, + ThreadType thread, + double angle = 0.0 + ); + CutDimensionSet( + const std::string& nme, + std::vector&& d, + CutType cut, + ThreadType thread, + double angle = 0.0 + ); - const CounterBoreDimension &get_bore(const std::string &t) const; - const CounterSinkDimension &get_sink(const std::string &t) const; + const CounterBoreDimension& get_bore(const std::string& t) const; + const CounterSinkDimension& get_sink(const std::string& t) const; std::vector bore_data; std::vector sink_data; @@ -224,21 +258,22 @@ private: double angle; }; - class CutDimensionKey { + class CutDimensionKey + { std::string thread_type; std::string cut_name; + public: CutDimensionKey() = default; - CutDimensionKey(const std::string &t, const std::string &c); - bool operator<(const CutDimensionKey &b) const; + CutDimensionKey(const std::string& t, const std::string& c); + bool operator<(const CutDimensionKey& b) const; }; std::map HoleCutTypeMap; - const CutDimensionSet& find_cutDimensionSet(const std::string &t, - const std::string &c); + const CutDimensionSet& find_cutDimensionSet(const std::string& t, const std::string& c); - const CutDimensionSet& find_cutDimensionSet(const CutDimensionKey &k); + const CutDimensionSet& find_cutDimensionSet(const CutDimensionKey& k); void addCutType(const CutDimensionSet& dimensions); void updateHoleCutParams(); @@ -260,12 +295,12 @@ private: TopoDS_Shape makeThread(const gp_Vec&, const gp_Vec&, double); // helpers for nlohmann json - friend void from_json(const nlohmann::json &j, CounterBoreDimension &t); - friend void from_json(const nlohmann::json &j, CounterSinkDimension &t); - friend void from_json(const nlohmann::json &j, CutDimensionSet &t); + friend void from_json(const nlohmann::json& j, CounterBoreDimension& t); + friend void from_json(const nlohmann::json& j, CounterSinkDimension& t); + friend void from_json(const nlohmann::json& j, CutDimensionSet& t); }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Hole_H +#endif // PART_Hole_H diff --git a/src/Mod/PartDesign/App/FeatureLinearPattern.cpp b/src/Mod/PartDesign/App/FeatureLinearPattern.cpp index 67112f1531..0146916e68 100644 --- a/src/Mod/PartDesign/App/FeatureLinearPattern.cpp +++ b/src/Mod/PartDesign/App/FeatureLinearPattern.cpp @@ -20,15 +20,15 @@ * * ******************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -43,57 +43,69 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ PROPERTY_SOURCE(PartDesign::LinearPattern, PartDesign::Transformed) -const App::PropertyIntegerConstraint::Constraints LinearPattern::intOccurrences = { - 1, std::numeric_limits::max(), 1 }; +const App::PropertyIntegerConstraint::Constraints LinearPattern::intOccurrences + = {1, std::numeric_limits::max(), 1}; -const char* LinearPattern::ModeEnums[] = { "Extent", "Spacing", nullptr }; +const char* LinearPattern::ModeEnums[] = {"Extent", "Spacing", nullptr}; LinearPattern::LinearPattern() { auto initialMode = LinearPatternMode::Extent; - ADD_PROPERTY_TYPE(Direction, - (nullptr), - "Direction 1", - App::Prop_None, - "The first direction of the pattern. This can be a straight edge, a datum " - "line, a sketch axis, or the normal of a planar face."); - ADD_PROPERTY_TYPE(Reversed, - (0), - "Direction 1", - App::Prop_None, - "Reverse the first direction of the pattern"); + ADD_PROPERTY_TYPE( + Direction, + (nullptr), + "Direction 1", + App::Prop_None, + "The first direction of the pattern. This can be a straight edge, a datum " + "line, a sketch axis, or the normal of a planar face." + ); + ADD_PROPERTY_TYPE( + Reversed, + (0), + "Direction 1", + App::Prop_None, + "Reverse the first direction of the pattern" + ); ADD_PROPERTY_TYPE( Mode, (long(initialMode)), "Direction 1", App::Prop_None, "Selects how the pattern is dimensioned.\n'Extent': Uses the total length from the first " - "to the last instance.\n'Spacing': Uses the distance between consecutive instances."); - ADD_PROPERTY_TYPE(Length, - (100.0), - "Direction 1", - App::Prop_None, - "The total length of the pattern, measured from the first to the last " - "instance. This is only used when the Mode is set to 'Extent'."); - ADD_PROPERTY_TYPE(Offset, - (10.0), - "Direction 1", - App::Prop_None, - "The distance between each instance of the pattern. This is only used when " - "the Mode is set to 'Spacing'."); - ADD_PROPERTY_TYPE(Spacings, - ({-1.0}), - "Direction 1", - App::Prop_None, - "A list of custom spacings between instances. If a value is -1, the global " - "'Offset' is used for that spacing. The list should have one less item than " - "the number of occurrences."); + "to the last instance.\n'Spacing': Uses the distance between consecutive instances." + ); + ADD_PROPERTY_TYPE( + Length, + (100.0), + "Direction 1", + App::Prop_None, + "The total length of the pattern, measured from the first to the last " + "instance. This is only used when the Mode is set to 'Extent'." + ); + ADD_PROPERTY_TYPE( + Offset, + (10.0), + "Direction 1", + App::Prop_None, + "The distance between each instance of the pattern. This is only used when " + "the Mode is set to 'Spacing'." + ); + ADD_PROPERTY_TYPE( + Spacings, + ({-1.0}), + "Direction 1", + App::Prop_None, + "A list of custom spacings between instances. If a value is -1, the global " + "'Offset' is used for that spacing. The list should have one less item than " + "the number of occurrences." + ); ADD_PROPERTY_TYPE( SpacingPattern, ({}), @@ -102,54 +114,66 @@ LinearPattern::LinearPattern() "(Experimental and subject to change. To enable " "this in the UI you can add a boolean parameter 'ExperiementalFeature' in " "Preferences/Mod/Part)\nDefines a repeating pattern of spacings for the second direction. " - "For example, a list of [10, 20] will create alternating spacings of 10mm and 20mm."); + "For example, a list of [10, 20] will create alternating spacings of 10mm and 20mm." + ); ADD_PROPERTY_TYPE( Occurrences, (2), "Direction 1", App::Prop_None, - "The total number of instances in the first direction, including the original feature."); + "The total number of instances in the first direction, including the original feature." + ); Occurrences.setConstraints(&intOccurrences); Mode.setEnums(ModeEnums); setReadWriteStatusForMode(LinearPatternDirection::First); - ADD_PROPERTY_TYPE(Direction2, - (nullptr), - "Direction 2", - App::Prop_None, - "The second direction of the pattern. This can be a straight edge, a datum " - "line, a sketch axis, or the normal of a planar face."); - ADD_PROPERTY_TYPE(Reversed2, - (0), - "Direction 2", - App::Prop_None, - "Reverse the second direction of the pattern"); - ADD_PROPERTY_TYPE(Mode2, - (long(initialMode)), - "Direction 2", - App::Prop_None, - "Selects how the pattern is dimensioned in the second direction.\n'Extent': " - "Uses the total length.\n'Spacing': Uses the distance between instances."); + ADD_PROPERTY_TYPE( + Direction2, + (nullptr), + "Direction 2", + App::Prop_None, + "The second direction of the pattern. This can be a straight edge, a datum " + "line, a sketch axis, or the normal of a planar face." + ); + ADD_PROPERTY_TYPE( + Reversed2, + (0), + "Direction 2", + App::Prop_None, + "Reverse the second direction of the pattern" + ); + ADD_PROPERTY_TYPE( + Mode2, + (long(initialMode)), + "Direction 2", + App::Prop_None, + "Selects how the pattern is dimensioned in the second direction.\n'Extent': " + "Uses the total length.\n'Spacing': Uses the distance between instances." + ); ADD_PROPERTY_TYPE( Length2, (100.0), "Direction 2", App::Prop_None, "The total length of the pattern in the second direction, measured from the first to the " - "last instance. This is only used when the Mode is set to 'Extent'."); - ADD_PROPERTY_TYPE(Offset2, - (10.0), - "Direction 2", - App::Prop_None, - "The distance between each instance of the pattern in the second direction. " - "This is only used when the Mode is set to 'Spacing'."); + "last instance. This is only used when the Mode is set to 'Extent'." + ); + ADD_PROPERTY_TYPE( + Offset2, + (10.0), + "Direction 2", + App::Prop_None, + "The distance between each instance of the pattern in the second direction. " + "This is only used when the Mode is set to 'Spacing'." + ); ADD_PROPERTY_TYPE( Spacings2, ({}), "Direction 2", App::Prop_None, "A list of custom spacings for the second direction. If a value is -1, the global 'Offset' " - "is used. The list should have one less item than the number of occurrences."); + "is used. The list should have one less item than the number of occurrences." + ); ADD_PROPERTY_TYPE( SpacingPattern2, ({}), @@ -158,13 +182,15 @@ LinearPattern::LinearPattern() "(Experimental and subject to change. To enable " "this in the UI you can add a boolean parameter 'ExperiementalFeature' in " "Preferences/Mod/Part)\nDefines a repeating pattern of spacings for the second direction. " - "For example, a list of [10, 20] will create alternating spacings of 10mm and 20mm."); + "For example, a list of [10, 20] will create alternating spacings of 10mm and 20mm." + ); ADD_PROPERTY_TYPE( Occurrences2, (1), "Direction 2", App::Prop_None, - "The total number of instances in the second direction, including the original feature."); + "The total number of instances in the second direction, including the original feature." + ); Occurrences2.setConstraints(&intOccurrences); Mode2.setEnums(ModeEnums); setReadWriteStatusForMode(LinearPatternDirection::Second); @@ -172,24 +198,14 @@ LinearPattern::LinearPattern() short LinearPattern::mustExecute() const { - if (Direction.isTouched() || - Reversed.isTouched() || - Mode.isTouched() || + if (Direction.isTouched() || Reversed.isTouched() || Mode.isTouched() || // Length and Offset are mutually exclusive, only one could be updated at once - Length.isTouched() || - Offset.isTouched() || - Spacings.isTouched() || - SpacingPattern.isTouched() || - Occurrences.isTouched() || - Direction2.isTouched() || - Reversed2.isTouched() || - Mode2.isTouched() || - Length2.isTouched() || - Offset2.isTouched() || - Spacings2.isTouched() || - SpacingPattern2.isTouched() || - Occurrences2.isTouched()) + Length.isTouched() || Offset.isTouched() || Spacings.isTouched() + || SpacingPattern.isTouched() || Occurrences.isTouched() || Direction2.isTouched() + || Reversed2.isTouched() || Mode2.isTouched() || Length2.isTouched() || Offset2.isTouched() + || Spacings2.isTouched() || SpacingPattern2.isTouched() || Occurrences2.isTouched()) { return 1; + } return Transformed::mustExecute(); } @@ -279,16 +295,17 @@ gp_Vec LinearPattern::calculateOffsetVector(LinearPatternDirection dir) const return offset; } -std::vector LinearPattern::calculateSteps(LinearPatternDirection dir, - const gp_Vec& offsetVector) const +std::vector LinearPattern::calculateSteps( + LinearPatternDirection dir, + const gp_Vec& offsetVector +) const { - const auto& occurrencesProp = - (dir == LinearPatternDirection::First) ? Occurrences : Occurrences2; + const auto& occurrencesProp = (dir == LinearPatternDirection::First) ? Occurrences : Occurrences2; const auto& modeProp = (dir == LinearPatternDirection::First) ? Mode : Mode2; const auto& offsetValueProp = (dir == LinearPatternDirection::First) ? Offset : Offset2; const auto& spacingsProp = (dir == LinearPatternDirection::First) ? Spacings : Spacings2; - const auto& spacingPatternProp = - (dir == LinearPatternDirection::First) ? SpacingPattern : SpacingPattern2; + const auto& spacingPatternProp = (dir == LinearPatternDirection::First) ? SpacingPattern + : SpacingPattern2; int occurrences = occurrencesProp.getValue(); std::vector steps {gp_Vec()}; // First step is always zero @@ -369,11 +386,13 @@ gp_Dir LinearPattern::getDirectionFromProperty(const App::PropertyLinkSub& dirPr Part::TopoShape refShape = refSketch->Shape.getShape(); TopoDS_Shape ref = refShape.getSubShape(subStrings[0].c_str()); TopoDS_Edge refEdge = TopoDS::Edge(ref); - if (refEdge.IsNull()) + if (refEdge.IsNull()) { throw Base::ValueError("Failed to extract direction edge"); + } BRepAdaptor_Curve adapt(refEdge); - if (adapt.GetType() != GeomAbs_Line) + if (adapt.GetType() != GeomAbs_Line) { throw Base::TypeError("Direction edge must be a straight line"); + } gp_Pnt p = adapt.Line().Location(); gp_Dir d = adapt.Line().Direction(); @@ -410,21 +429,25 @@ gp_Dir LinearPattern::getDirectionFromProperty(const App::PropertyLinkSub& dirPr if (ref.ShapeType() == TopAbs_FACE) { TopoDS_Face refFace = TopoDS::Face(ref); - if (refFace.IsNull()) + if (refFace.IsNull()) { throw Base::ValueError("Failed to extract direction plane"); + } BRepAdaptor_Surface adapt(refFace); - if (adapt.GetType() != GeomAbs_Plane) + if (adapt.GetType() != GeomAbs_Plane) { throw Base::TypeError("Direction face must be planar"); + } dir = adapt.Plane().Axis().Direction(); } else if (ref.ShapeType() == TopAbs_EDGE) { TopoDS_Edge refEdge = TopoDS::Edge(ref); - if (refEdge.IsNull()) + if (refEdge.IsNull()) { throw Base::ValueError("Failed to extract direction edge"); + } BRepAdaptor_Curve adapt(refEdge); - if (adapt.GetType() != GeomAbs_Line) + if (adapt.GetType() != GeomAbs_Line) { throw Base::ValueError("Direction edge must be a straight line"); + } dir = adapt.Line().Direction(); } @@ -433,7 +456,9 @@ gp_Dir LinearPattern::getDirectionFromProperty(const App::PropertyLinkSub& dirPr } } else { - throw Base::ValueError("Direction reference must be edge/face of a feature or a datum line/plane"); + throw Base::ValueError( + "Direction reference must be edge/face of a feature or a datum line/plane" + ); } TopLoc_Location invObjLoc = this->getLocation().Inverted(); @@ -457,7 +482,8 @@ void LinearPattern::updateSpacings(LinearPatternDirection dir) const App::PropertyIntegerConstraint& occurrencesProp = isSecondDir ? Occurrences2 : Occurrences; std::vector spacings = spacingsProp.getValues(); - size_t targetCount = occurrencesProp.getValue() - 1; // 1 less spacing than there are occurrences. + size_t targetCount = occurrencesProp.getValue() + - 1; // 1 less spacing than there are occurrences. for (auto& spacing : spacings) { if (spacing == offsetProp.getValue()) { @@ -481,10 +507,15 @@ void LinearPattern::updateSpacings(LinearPatternDirection dir) spacingsProp.setValues(spacings); } -void LinearPattern::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) +void LinearPattern::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) // transforms properties that had been changed { - // property Occurrences had the App::PropertyInteger and was changed to App::PropertyIntegerConstraint + // property Occurrences had the App::PropertyInteger and was changed to + // App::PropertyIntegerConstraint if (prop == &Occurrences && strcmp(TypeName, "App::PropertyInteger") == 0) { App::PropertyInteger OccurrencesProperty; // restore the PropertyInteger to be able to set its value @@ -554,6 +585,4 @@ void LinearPattern::syncLengthAndOffset(LinearPatternDirection dir) } } -} - - +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureLinearPattern.h b/src/Mod/PartDesign/App/FeatureLinearPattern.h index 41faecf336..c1c6b7a7a0 100644 --- a/src/Mod/PartDesign/App/FeatureLinearPattern.h +++ b/src/Mod/PartDesign/App/FeatureLinearPattern.h @@ -31,7 +31,8 @@ class gp_Vec; namespace PartDesign { -enum class LinearPatternMode { +enum class LinearPatternMode +{ Extent, Spacing }; @@ -42,62 +43,68 @@ enum class LinearPatternDirection : std::uint8_t Second }; -class PartDesignExport LinearPattern : public PartDesign::Transformed +class PartDesignExport LinearPattern: public PartDesign::Transformed { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::LinearPattern); public: LinearPattern(); - App::PropertyLinkSub Direction; - App::PropertyBool Reversed; + App::PropertyLinkSub Direction; + App::PropertyBool Reversed; App::PropertyEnumeration Mode; - App::PropertyLength Length; - App::PropertyLength Offset; + App::PropertyLength Length; + App::PropertyLength Offset; App::PropertyIntegerConstraint Occurrences; - App::PropertyFloatList Spacings; - App::PropertyFloatList SpacingPattern; + App::PropertyFloatList Spacings; + App::PropertyFloatList SpacingPattern; - App::PropertyLinkSub Direction2; - App::PropertyBool Reversed2; + App::PropertyLinkSub Direction2; + App::PropertyBool Reversed2; App::PropertyEnumeration Mode2; - App::PropertyLength Length2; - App::PropertyLength Offset2; + App::PropertyLength Length2; + App::PropertyLength Offset2; App::PropertyIntegerConstraint Occurrences2; - App::PropertyFloatList Spacings2; - App::PropertyFloatList SpacingPattern2; + App::PropertyFloatList Spacings2; + App::PropertyFloatList SpacingPattern2; - /** @name methods override feature */ + /** @name methods override feature */ //@{ short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderLinearPattern"; } //@} /** Create transformations - * Returns a list of (Occurrences - 1) transformations since the first, untransformed instance - * is not counted. - * - * Depending on Mode selection list will be constructed differently: - * 1. For "Overall Length" each transformation will move the shape it is applied to by the distance - * (Length / (Occurrences - 1)) so that the transformations will cover the total Length. - * 2. For "Spacing" each transformation will move the shape by the distance explicitly given in - * the Offset parameter. - * - * If Direction contains a feature and a face name, then the transformation direction will be - * the normal of the given face, which must be planar. If it contains an edge name, then the - * transformation direction will be parallel to the given edge, which must be linear - * - * If Reversed is true, the direction of transformation will be opposite - */ - const std::list getTransformations(const std::vector ) override; + * Returns a list of (Occurrences - 1) transformations since the first, untransformed instance + * is not counted. + * + * Depending on Mode selection list will be constructed differently: + * 1. For "Overall Length" each transformation will move the shape it is applied to by the + * distance (Length / (Occurrences - 1)) so that the transformations will cover the total + * Length. + * 2. For "Spacing" each transformation will move the shape by the distance explicitly given in + * the Offset parameter. + * + * If Direction contains a feature and a face name, then the transformation direction will be + * the normal of the given face, which must be planar. If it contains an edge name, then the + * transformation direction will be parallel to the given edge, which must be linear + * + * If Reversed is true, the direction of transformation will be opposite + */ + const std::list getTransformations(const std::vector) override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; static const App::PropertyIntegerConstraint::Constraints intOccurrences; @@ -117,7 +124,7 @@ private: std::vector calculateSteps(LinearPatternDirection dir, const gp_Vec& offsetVector) const; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeatureLinearPattern_H +#endif // PARTDESIGN_FeatureLinearPattern_H diff --git a/src/Mod/PartDesign/App/FeatureLoft.cpp b/src/Mod/PartDesign/App/FeatureLoft.cpp index c59945d831..fff73c1a32 100644 --- a/src/Mod/PartDesign/App/FeatureLoft.cpp +++ b/src/Mod/PartDesign/App/FeatureLoft.cpp @@ -20,10 +20,10 @@ * * ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -42,28 +42,33 @@ PROPERTY_SOURCE(PartDesign::Loft, PartDesign::ProfileBased) Loft::Loft() { - ADD_PROPERTY_TYPE(Sections,(nullptr),"Loft",App::Prop_None,"List of sections"); + ADD_PROPERTY_TYPE(Sections, (nullptr), "Loft", App::Prop_None, "List of sections"); Sections.setValue(nullptr); - ADD_PROPERTY_TYPE(Ruled,(false),"Loft",App::Prop_None,"Create ruled surface"); - ADD_PROPERTY_TYPE(Closed,(false),"Loft",App::Prop_None,"Close Last to First Profile"); + ADD_PROPERTY_TYPE(Ruled, (false), "Loft", App::Prop_None, "Create ruled surface"); + ADD_PROPERTY_TYPE(Closed, (false), "Loft", App::Prop_None, "Close Last to First Profile"); } short Loft::mustExecute() const { - if (Sections.isTouched()) + if (Sections.isTouched()) { return 1; - if (Ruled.isTouched()) + } + if (Ruled.isTouched()) { return 1; - if (Closed.isTouched()) + } + if (Closed.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } -std::vector Loft::getSectionShape(const char* name, - App::DocumentObject* obj, - const std::vector& subs, - size_t expected_size) +std::vector Loft::getSectionShape( + const char* name, + App::DocumentObject* obj, + const std::vector& subs, + size_t expected_size +) { auto useSketch = [](App::DocumentObject* obj, const std::vector& subs) { // Be smart. If part of a sketch is selected, use the entire sketch unless it is a single @@ -79,9 +84,9 @@ std::vector Loft::getSectionShape(const char* name, std::vector shapes; auto useEntireSketch = useSketch(obj, subs); if (subs.empty() || std::ranges::find(subs, std::string()) != subs.end() || useEntireSketch) { - shapes.push_back(Part::Feature::getTopoShape(obj, - Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform)); + shapes.push_back( + Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform) + ); if (shapes.back().isNull()) { std::stringstream str; str << "Failed to get shape of " << name; @@ -94,11 +99,14 @@ std::vector Loft::getSectionShape(const char* name, } else { for (const auto& sub : subs) { - shapes.push_back(Part::Feature::getTopoShape(obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sub.c_str())); + shapes.push_back( + Part::Feature::getTopoShape( + obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sub.c_str() + ) + ); if (shapes.back().isNull()) { std::stringstream str; str << "Failed to get shape of " << name; @@ -111,35 +119,50 @@ std::vector Loft::getSectionShape(const char* name, } } } - auto compound = TopoShape(0).makeElementCompound(shapes, "", TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + auto compound = TopoShape(0).makeElementCompound( + shapes, + "", + TopoShape::SingleShapeCompoundCreationPolicy::returnShape + ); auto wires = compound.getSubTopoShapes(TopAbs_WIRE); - auto edges = compound.getSubTopoShapes(TopAbs_EDGE, TopAbs_WIRE); // get free edges and make wires from it - if ( ! edges.empty()) { + auto edges = compound.getSubTopoShapes(TopAbs_EDGE, TopAbs_WIRE); // get free edges and make + // wires from it + if (!edges.empty()) { auto extra = TopoShape(0).makeElementWires(edges).getSubTopoShapes(TopAbs_WIRE); wires.insert(wires.end(), extra.begin(), extra.end()); } - const char *msg = "Sections need to have the same amount of wires or vertices as the base section"; + const char* msg + = "Sections need to have the same amount of wires or vertices as the base section"; if (!wires.empty()) { - if (expected_size && expected_size != wires.size()) + if (expected_size && expected_size != wires.size()) { FC_THROWM(Base::CADKernelError, msg); + } return wires; } auto vertices = compound.getSubTopoShapes(TopAbs_VERTEX); - if (vertices.empty()) - FC_THROWM(Base::CADKernelError, "Invalid " << name << " shape, expecting either wires or vertices"); - if (expected_size && expected_size != vertices.size()) + if (vertices.empty()) { + FC_THROWM( + Base::CADKernelError, + "Invalid " << name << " shape, expecting either wires or vertices" + ); + } + if (expected_size && expected_size != vertices.size()) { FC_THROWM(Base::CADKernelError, msg); + } return vertices; } -App::DocumentObjectExecReturn *Loft::execute() +App::DocumentObjectExecReturn* Loft::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } std::vector wires; try { wires = getSectionShape("Profile", Profile.getValue(), Profile.getSubValues()); - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { return new App::DocumentObjectExecReturn(e.what()); } @@ -147,7 +170,8 @@ App::DocumentObjectExecReturn *Loft::execute() TopoShape base; try { base = getBaseTopoShape(); - } catch (const Base::Exception&) { + } + catch (const Base::Exception&) { } auto hasher = getDocument()->getStringHasher(); @@ -156,23 +180,30 @@ App::DocumentObjectExecReturn *Loft::execute() // setup the location this->positionByPrevious(); auto invObjLoc = this->getLocation().Inverted(); - if(!base.isNull()) + if (!base.isNull()) { base.move(invObjLoc); + } // build up multisections auto multisections = Sections.getSubListValues(); - if(multisections.empty()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Loft: At least one section is needed")); + if (multisections.empty()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Loft: At least one section is needed") + ); + } std::vector> wiresections; wiresections.reserve(wires.size()); - for(auto& wire : wires) + for (auto& wire : wires) { wiresections.emplace_back(1, wire); + } - for (const auto &subSet : multisections) { - int i=0; - for (const auto &s : getSectionShape("Section", subSet.first, subSet.second, wiresections.size())) + for (const auto& subSet : multisections) { + int i = 0; + for (const auto& s : + getSectionShape("Section", subSet.first, subSet.second, wiresections.size())) { wiresections[i++].push_back(s); + } } bool closed = Closed.getValue(); @@ -181,34 +212,42 @@ App::DocumentObjectExecReturn *Loft::execute() closed = false; } - TopoShape result(0,hasher); + TopoShape result(0, hasher); std::vector shapes; // build all shells std::vector shells; - for (auto §ionWires : wiresections) { - for(auto& wire : sectionWires) + for (auto& sectionWires : wiresections) { + for (auto& wire : sectionWires) { wire.move(invObjLoc); + } shells.push_back(TopoShape(0, hasher).makeElementLoft( - sectionWires, Part::IsSolid::notSolid, Ruled.getValue()? Part::IsRuled::ruled : Part::IsRuled::notRuled, closed ? Part::IsClosed::closed : Part::IsClosed::notClosed)); + sectionWires, + Part::IsSolid::notSolid, + Ruled.getValue() ? Part::IsRuled::ruled : Part::IsRuled::notRuled, + closed ? Part::IsClosed::closed : Part::IsClosed::notClosed + )); } // build the top and bottom face, sew the shell and build the final solid TopoShape front; if (wiresections[0].front().shapeType() != TopAbs_VERTEX) { front = getTopoShapeVerifiedFace(); - if (front.isNull()) + if (front.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Loft: Creating a face from sketch failed")); + QT_TRANSLATE_NOOP("Exception", "Loft: Creating a face from sketch failed") + ); + } front.move(invObjLoc); } TopoShape back; if (wiresections[0].back().shapeType() != TopAbs_VERTEX) { std::vector backwires; - for(auto& sectionWires : wiresections) + for (auto& sectionWires : wiresections) { backwires.push_back(sectionWires.back()); - const char *faceMaker[] = { + } + const char* faceMaker[] = { "Part::FaceMakerBullseye", "Part::FaceMakerCheese", "Part::FaceMakerSimple", @@ -219,10 +258,10 @@ App::DocumentObjectExecReturn *Loft::execute() break; } catch (...) { - if (i == std::size(faceMaker) - 1) { - throw; - } - continue; + if (i == std::size(faceMaker) - 1) { + throw; + } + continue; } } } @@ -230,56 +269,79 @@ App::DocumentObjectExecReturn *Loft::execute() if (!front.isNull() || !back.isNull()) { BRepBuilderAPI_Sewing sewer; sewer.SetTolerance(Precision::Confusion()); - if (!front.isNull()) + if (!front.isNull()) { sewer.Add(front.getShape()); - if (!back.isNull()) + } + if (!back.isNull()) { sewer.Add(back.getShape()); - for(auto& s : shells) + } + for (auto& s : shells) { sewer.Add(s.getShape()); + } sewer.Perform(); - if (!front.isNull()) + if (!front.isNull()) { shells.push_back(front); - if (!back.isNull()) + } + if (!back.isNull()) { shells.push_back(back); + } // equivalent of the removed: result = result.makeElementShape(sewer,shells); - result = result.makeShapeWithElementMap(sewer.SewedShape(), Part::MapperSewing(sewer), shells, Part::OpCodes::Sewing); + result = result.makeShapeWithElementMap( + sewer.SewedShape(), + Part::MapperSewing(sewer), + shells, + Part::OpCodes::Sewing + ); } - if(!result.countSubShapes(TopAbs_SHELL)) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Loft: Failed to create shell")); + if (!result.countSubShapes(TopAbs_SHELL)) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Loft: Failed to create shell") + ); + } shapes = result.getSubTopoShapes(TopAbs_SHELL); - for (auto &s : shapes) { + for (auto& s : shapes) { // build the solid s = s.makeElementSolid(); BRepClass3d_SolidClassifier SC(s.getShape()); SC.PerformInfinitePoint(Precision::Confusion()); - if ( SC.State() == TopAbs_IN) - s.setShape(s.getShape().Reversed(),false); + if (SC.State() == TopAbs_IN) { + s.setShape(s.getShape().Reversed(), false); + } } - AddSubShape.setValue(result.makeElementCompound(shapes, nullptr, Part::TopoShape::SingleShapeCompoundCreationPolicy::returnShape)); + AddSubShape.setValue(result.makeElementCompound( + shapes, + nullptr, + Part::TopoShape::SingleShapeCompoundCreationPolicy::returnShape + )); - if (shapes.size() > 1) + if (shapes.size() > 1) { result.makeElementFuse(shapes); - else + } + else { result = shapes.front(); + } - if(base.isNull()) { + if (base.isNull()) { if (!isSingleSolidRuleSatisfied(result.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } Shape.setValue(getSolid(result)); return App::DocumentObject::StdReturn; } result.Tag = -getID(); - TopoShape boolOp(0,getDocument()->getStringHasher()); + TopoShape boolOp(0, getDocument()->getStringHasher()); - const char *maker; - switch(getAddSubType()) { + const char* maker; + switch (getAddSubType()) { case Additive: maker = Part::OpCodes::Fuse; break; @@ -287,24 +349,33 @@ App::DocumentObjectExecReturn *Loft::execute() maker = Part::OpCodes::Cut; break; default: - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Unknown operation type")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Unknown operation type") + ); } try { - boolOp.makeElementBoolean(maker, {base,result}); + boolOp.makeElementBoolean(maker, {base, result}); } - catch(Standard_Failure&) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Failed to perform boolean operation")); + catch (Standard_Failure&) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Failed to perform boolean operation") + ); } TopoShape solid = getSolid(boolOp); // lets check if the result is a solid if (solid.isNull()) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid") + ); } // store shape before refinement this->rawShape = boolOp; boolOp = refineShapeIfActive(boolOp); if (!isSingleSolidRuleSatisfied(boolOp.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } boolOp = getSolid(boolOp); Shape.setValue(boolOp); @@ -317,17 +388,21 @@ App::DocumentObjectExecReturn *Loft::execute() return new App::DocumentObjectExecReturn(e.what()); } catch (...) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Loft: A fatal error occurred when making the loft")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Loft: A fatal error occurred when making the loft") + ); } } PROPERTY_SOURCE(PartDesign::AdditiveLoft, PartDesign::Loft) -AdditiveLoft::AdditiveLoft() { +AdditiveLoft::AdditiveLoft() +{ addSubType = Additive; } PROPERTY_SOURCE(PartDesign::SubtractiveLoft, PartDesign::Loft) -SubtractiveLoft::SubtractiveLoft() { +SubtractiveLoft::SubtractiveLoft() +{ addSubType = Subtractive; } @@ -341,5 +416,3 @@ void Loft::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeNa ProfileBased::handleChangedPropertyType(reader, TypeName, prop); } } - - diff --git a/src/Mod/PartDesign/App/FeatureLoft.h b/src/Mod/PartDesign/App/FeatureLoft.h index 497a4ee2db..49fd0f6e31 100644 --- a/src/Mod/PartDesign/App/FeatureLoft.h +++ b/src/Mod/PartDesign/App/FeatureLoft.h @@ -29,7 +29,7 @@ namespace PartDesign { -class PartDesignExport Loft : public ProfileBased +class PartDesignExport Loft: public ProfileBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Loft); @@ -42,43 +42,54 @@ public: /** @name methods override feature */ //@{ - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderLoft"; } //@} - static std::vector getSectionShape(const char *name, - App::DocumentObject *obj, - const std::vector &subname, - size_t expected_size = 0); + static std::vector getSectionShape( + const char* name, + App::DocumentObject* obj, + const std::vector& subname, + size_t expected_size = 0 + ); protected: // handle changed property - void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; private: - //static const char* TypeEnums[]; - //static const char* SideEnums[]; + // static const char* TypeEnums[]; + // static const char* SideEnums[]; }; -class PartDesignExport AdditiveLoft : public Loft { +class PartDesignExport AdditiveLoft: public Loft +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveLoft); + public: AdditiveLoft(); }; -class PartDesignExport SubtractiveLoft : public Loft { +class PartDesignExport SubtractiveLoft: public Loft +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveLoft); + public: SubtractiveLoft(); }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Loft_H +#endif // PART_Loft_H diff --git a/src/Mod/PartDesign/App/FeatureMirrored.cpp b/src/Mod/PartDesign/App/FeatureMirrored.cpp index c5a82f1521..55e14417ae 100644 --- a/src/Mod/PartDesign/App/FeatureMirrored.cpp +++ b/src/Mod/PartDesign/App/FeatureMirrored.cpp @@ -21,11 +21,11 @@ ******************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -38,14 +38,21 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ PROPERTY_SOURCE(PartDesign::Mirrored, PartDesign::Transformed) Mirrored::Mirrored() { - ADD_PROPERTY_TYPE(MirrorPlane,(nullptr),"Mirrored",(App::PropertyType)(App::Prop_None),"Mirror plane"); + ADD_PROPERTY_TYPE( + MirrorPlane, + (nullptr), + "Mirrored", + (App::PropertyType)(App::Prop_None), + "Mirror plane" + ); } short Mirrored::mustExecute() const @@ -77,11 +84,17 @@ const std::list Mirrored::getTransformations(const std::vectorgetAxis(Part::Part2DObject::H_Axis); } else if (subStrings[0].compare(0, 4, "Axis") == 0) { - int AxId = std::atoi(subStrings[0].substr(4,4000).c_str()); + int AxId = std::atoi(subStrings[0].substr(4, 4000).c_str()); if (AxId >= 0 && AxId < refSketch->getAxisCount()) { axis = refSketch->getAxis(AxId); axis.setBase(axis.getBase() + 0.5 * axis.getDirection()); - axis.setDirection(Base::Vector3d(-axis.getDirection().y, axis.getDirection().x, axis.getDirection().z)); + axis.setDirection( + Base::Vector3d( + -axis.getDirection().y, + axis.getDirection().x, + axis.getDirection().z + ) + ); } else { throw Base::ValueError("No valid axis specified"); @@ -179,7 +192,9 @@ const std::list Mirrored::getTransformations(const std::vector Mirrored::createTransformations(gp_Pnt& axbase, gp_Dir& axdir) const @@ -192,10 +207,10 @@ std::list Mirrored::createTransformations(gp_Pnt& axbase, gp_Dir& axdir std::list transformations; gp_Trsf trans; - transformations.push_back(trans); // identity transformation + transformations.push_back(trans); // identity transformation trans.SetMirror(mirrorAxis); - transformations.push_back(trans); // mirrored transformation + transformations.push_back(trans); // mirrored transformation return transformations; } -} +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureMirrored.h b/src/Mod/PartDesign/App/FeatureMirrored.h index fce4565085..b973c27c2b 100644 --- a/src/Mod/PartDesign/App/FeatureMirrored.h +++ b/src/Mod/PartDesign/App/FeatureMirrored.h @@ -30,7 +30,7 @@ namespace PartDesign { -class PartDesignExport Mirrored : public PartDesign::Transformed +class PartDesignExport Mirrored: public PartDesign::Transformed { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Mirrored); @@ -39,29 +39,30 @@ public: App::PropertyLinkSub MirrorPlane; - /** @name methods override feature */ + /** @name methods override feature */ //@{ short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderMirrored"; } //@} /** Create transformations - * Returns a list containing one transformation since the first, untransformed instance - * is not counted. The transformation will mirror the shape it is applied to on a plane - * If MirrorPlane contains a feature and a face name, then the mirror plane will be - * the given face, which must be planar - */ + * Returns a list containing one transformation since the first, untransformed instance + * is not counted. The transformation will mirror the shape it is applied to on a plane + * If MirrorPlane contains a feature and a face name, then the mirror plane will be + * the given face, which must be planar + */ const std::list getTransformations(const std::vector) override; private: std::list createTransformations(gp_Pnt& axbase, gp_Dir& axdir) const; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeatureMirrored_H +#endif // PARTDESIGN_FeatureMirrored_H diff --git a/src/Mod/PartDesign/App/FeatureMultiTransform.cpp b/src/Mod/PartDesign/App/FeatureMultiTransform.cpp index a6dade0d6e..27ac00dcb6 100644 --- a/src/Mod/PartDesign/App/FeatureMultiTransform.cpp +++ b/src/Mod/PartDesign/App/FeatureMultiTransform.cpp @@ -73,8 +73,9 @@ short MultiTransform::mustExecute() const return Transformed::mustExecute(); } -const std::list -MultiTransform::getTransformations(const std::vector originals) +const std::list MultiTransform::getTransformations( + const std::vector originals +) { std::vector transFeatures = Transformations.getValues(); @@ -82,8 +83,7 @@ MultiTransform::getTransformations(const std::vector origi if (!originals.empty()) { // Find centre of gravity of first original // FIXME: This method will NOT give the expected result for more than one original! - if (auto addFeature = - freecad_cast(originals.front())) { + if (auto addFeature = freecad_cast(originals.front())) { TopoDS_Shape original = addFeature->AddSubShape.getShape().getShape(); GProp_GProps props; @@ -128,12 +128,16 @@ MultiTransform::getTransformations(const std::vector origi // oldTransformations vector if (newTransformations.empty()) { - throw Base::ValueError("Number of occurrences must be a divisor of previous " - "number of occurrences"); + throw Base::ValueError( + "Number of occurrences must be a divisor of previous " + "number of occurrences" + ); } if (oldTransformations.size() % newTransformations.size() != 0) { - throw Base::ValueError("Number of occurrences must be a divisor of previous " - "number of occurrences"); + throw Base::ValueError( + "Number of occurrences must be a divisor of previous " + "number of occurrences" + ); } unsigned sliceLength = oldTransformations.size() / newTransformations.size(); diff --git a/src/Mod/PartDesign/App/FeatureMultiTransform.h b/src/Mod/PartDesign/App/FeatureMultiTransform.h index 5408fab22d..56984a1d70 100644 --- a/src/Mod/PartDesign/App/FeatureMultiTransform.h +++ b/src/Mod/PartDesign/App/FeatureMultiTransform.h @@ -55,8 +55,9 @@ public: * by the Transformations property. Subfeatures can be Mirrored, LinearPattern, PolarPattern and * Scaled. */ - const std::list - getTransformations(const std::vector originals) override; + const std::list getTransformations( + const std::vector originals + ) override; protected: void positionBySupport() override; diff --git a/src/Mod/PartDesign/App/FeaturePad.cpp b/src/Mod/PartDesign/App/FeaturePad.cpp index 5fcb6d2c20..fa43af8015 100644 --- a/src/Mod/PartDesign/App/FeaturePad.cpp +++ b/src/Mod/PartDesign/App/FeaturePad.cpp @@ -21,11 +21,11 @@ ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -37,10 +37,11 @@ using namespace PartDesign; // Note, TwoLengths has been deprecated by #21794. We do not remove it from the ui -// because the files store the enum index. So it is not possible to migrate files if the +// because the files store the enum index. So it is not possible to migrate files if the // enum entry is removed (see #23612). In the distant future, when all files are reasonably // migrated we can drop this. -const char* Pad::TypeEnums[]= {"Length", "UpToLast", "UpToFirst", "UpToFace", "?TwoLengths", "UpToShape", nullptr}; +const char* Pad::TypeEnums[] + = {"Length", "UpToLast", "UpToFirst", "UpToFace", "?TwoLengths", "UpToShape", nullptr}; PROPERTY_SOURCE(PartDesign::Pad, PartDesign::FeatureExtrude) @@ -57,15 +58,39 @@ Pad::Pad() ADD_PROPERTY_TYPE(Length, (10.0), "Side1", App::Prop_None, "Pad length"); ADD_PROPERTY_TYPE(Length2, (10.0), "Side2", App::Prop_None, "Pad length in 2nd direction"); ADD_PROPERTY_TYPE(UseCustomVector, (false), "Pad", App::Prop_None, "Use custom vector for pad direction"); - ADD_PROPERTY_TYPE(Direction, (Base::Vector3d(1.0, 1.0, 1.0)), "Pad", App::Prop_None, "Pad direction vector"); + ADD_PROPERTY_TYPE( + Direction, + (Base::Vector3d(1.0, 1.0, 1.0)), + "Pad", + App::Prop_None, + "Pad direction vector" + ); ADD_PROPERTY_TYPE(ReferenceAxis, (nullptr), "Pad", App::Prop_None, "Reference axis of direction"); - ADD_PROPERTY_TYPE(AlongSketchNormal, (true), "Pad", App::Prop_None, "Measure pad length along the sketch normal direction"); + ADD_PROPERTY_TYPE( + AlongSketchNormal, + (true), + "Pad", + App::Prop_None, + "Measure pad length along the sketch normal direction" + ); ADD_PROPERTY_TYPE(UpToFace, (nullptr), "Side1", App::Prop_None, "Face where pad will end"); ADD_PROPERTY_TYPE(UpToShape, (nullptr), "Side1", App::Prop_None, "Faces or shape(s) where pad will end"); ADD_PROPERTY_TYPE(UpToFace2, (nullptr), "Side2", App::Prop_None, "Face where pad will end on side2"); - ADD_PROPERTY_TYPE(UpToShape2, (nullptr), "Side2", App::Prop_None, "Faces or shape(s) where pad will end on side2"); + ADD_PROPERTY_TYPE( + UpToShape2, + (nullptr), + "Side2", + App::Prop_None, + "Faces or shape(s) where pad will end on side2" + ); ADD_PROPERTY_TYPE(Offset, (0.0), "Side1", App::Prop_None, "Offset from face in which pad will end"); - ADD_PROPERTY_TYPE(Offset2, (0.0), "Side2", App::Prop_None, "Offset from face in which pad will end on side 2"); + ADD_PROPERTY_TYPE( + Offset2, + (0.0), + "Side2", + App::Prop_None, + "Offset from face in which pad will end on side 2" + ); Offset.setConstraints(&signedLengthConstraint); Offset2.setConstraints(&signedLengthConstraint); ADD_PROPERTY_TYPE(TaperAngle, (0.0), "Side1", App::Prop_None, "Taper angle"); @@ -84,4 +109,3 @@ App::DocumentObjectExecReturn* Pad::execute() { return buildExtrusion(ExtrudeOption::MakeFace | ExtrudeOption::MakeFuse); } - diff --git a/src/Mod/PartDesign/App/FeaturePad.h b/src/Mod/PartDesign/App/FeaturePad.h index 64456c6bcc..348ad968fc 100644 --- a/src/Mod/PartDesign/App/FeaturePad.h +++ b/src/Mod/PartDesign/App/FeaturePad.h @@ -29,7 +29,7 @@ namespace PartDesign { -class PartDesignExport Pad : public FeatureExtrude +class PartDesignExport Pad: public FeatureExtrude { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Pad); @@ -39,19 +39,20 @@ public: /** @name methods override feature */ //@{ /** Recalculate the feature - * Extrudes the Sketch in the direction of the sketch face normal - * If Type is "Length" then Length gives the extrusion length, the direction will be away from the support - * If Type is "UpToLast" then the extrusion will stop at the last face of the support - * that is cut by a line through the centre of gravite of the sketch - * If Type is "UpToFirst" then extrusion will stop at the first face of the support - * If Type is "UpToFace" then the extrusion will stop at FaceName in the support - * If Midplane is true, then the extrusion will extend for half of the length on both sides of the sketch plane - * If Reversed is true then the direction of revolution will be reversed. - * The created material will be fused with the sketch support (if there is one) - */ - App::DocumentObjectExecReturn *execute() override; + * Extrudes the Sketch in the direction of the sketch face normal + * If Type is "Length" then Length gives the extrusion length, the direction will be away from + * the support If Type is "UpToLast" then the extrusion will stop at the last face of the + * support that is cut by a line through the centre of gravite of the sketch If Type is + * "UpToFirst" then extrusion will stop at the first face of the support If Type is "UpToFace" + * then the extrusion will stop at FaceName in the support If Midplane is true, then the + * extrusion will extend for half of the length on both sides of the sketch plane If Reversed is + * true then the direction of revolution will be reversed. The created material will be fused + * with the sketch support (if there is one) + */ + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderPad"; } //@} @@ -60,7 +61,7 @@ private: static const char* TypeEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Pad_H +#endif // PART_Pad_H diff --git a/src/Mod/PartDesign/App/FeaturePipe.cpp b/src/Mod/PartDesign/App/FeaturePipe.cpp index 12bcdf6815..e835674d12 100644 --- a/src/Mod/PartDesign/App/FeaturePipe.cpp +++ b/src/Mod/PartDesign/App/FeaturePipe.cpp @@ -21,23 +21,23 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -51,15 +51,15 @@ #include "Mod/Part/App/TopoShapeMapper.h" #include "FeatureLoft.h" -FC_LOG_LEVEL_INIT("PartDesign",true,true); +FC_LOG_LEVEL_INIT("PartDesign", true, true); using namespace PartDesign; const char* Pipe::TypeEnums[] = {"FullPath", "UpToFace", nullptr}; const char* Pipe::TransitionEnums[] = {"Transformed", "Right corner", "Round corner", nullptr}; const char* Pipe::ModeEnums[] = {"Standard", "Fixed", "Frenet", "Auxiliary", "Binormal", nullptr}; -const char* Pipe::TransformEnums[] = { - "Constant", "Multisection", "Linear", "S-shape", "Interpolation", nullptr}; +const char* Pipe::TransformEnums[] + = {"Constant", "Multisection", "Linear", "S-shape", "Interpolation", nullptr}; PROPERTY_SOURCE(PartDesign::Pipe, PartDesign::ProfileBased) @@ -69,20 +69,32 @@ Pipe::Pipe() ADD_PROPERTY_TYPE(Sections, (nullptr), "Sweep", App::Prop_None, "List of sections"); Sections.setValue(nullptr); ADD_PROPERTY_TYPE(Spine, (nullptr), "Sweep", App::Prop_None, "Path to sweep along"); - ADD_PROPERTY_TYPE(SpineTangent, (false), "Sweep", App::Prop_None, - "Include tangent edges into path"); - ADD_PROPERTY_TYPE(AuxiliarySpine, (nullptr), "Sweep", App::Prop_None, - "Secondary path to orient sweep"); - ADD_PROPERTY_TYPE(AuxiliarySpineTangent, (false), "Sweep", App::Prop_None, - "Include tangent edges into secondary path"); - ADD_PROPERTY_TYPE(AuxiliaryCurvilinear, (true), "Sweep", App::Prop_None, - "Calculate normal between equidistant points on both spines"); + ADD_PROPERTY_TYPE(SpineTangent, (false), "Sweep", App::Prop_None, "Include tangent edges into path"); + ADD_PROPERTY_TYPE(AuxiliarySpine, (nullptr), "Sweep", App::Prop_None, "Secondary path to orient sweep"); + ADD_PROPERTY_TYPE( + AuxiliarySpineTangent, + (false), + "Sweep", + App::Prop_None, + "Include tangent edges into secondary path" + ); + ADD_PROPERTY_TYPE( + AuxiliaryCurvilinear, + (true), + "Sweep", + App::Prop_None, + "Calculate normal between equidistant points on both spines" + ); ADD_PROPERTY_TYPE(Mode, (long(0)), "Sweep", App::Prop_None, "Profile mode"); - ADD_PROPERTY_TYPE(Binormal, (Base::Vector3d()), "Sweep", App::Prop_None, - "Binormal vector for corresponding orientation mode"); + ADD_PROPERTY_TYPE( + Binormal, + (Base::Vector3d()), + "Sweep", + App::Prop_None, + "Binormal vector for corresponding orientation mode" + ); ADD_PROPERTY_TYPE(Transition, (long(0)), "Sweep", App::Prop_None, "Transition mode"); - ADD_PROPERTY_TYPE(Transformation, (long(0)), "Sweep", App::Prop_None, - "Section transformation mode"); + ADD_PROPERTY_TYPE(Transformation, (long(0)), "Sweep", App::Prop_None, "Section transformation mode"); Mode.setEnums(ModeEnums); Transition.setEnums(TransitionEnums); Transformation.setEnums(TransformEnums); @@ -90,38 +102,45 @@ Pipe::Pipe() short Pipe::mustExecute() const { - if (Sections.isTouched()) + if (Sections.isTouched()) { return 1; - if (Spine.isTouched()) + } + if (Spine.isTouched()) { return 1; - if (Mode.isTouched()) + } + if (Mode.isTouched()) { return 1; - if (Transition.isTouched()) + } + if (Transition.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn *Pipe::execute() +App::DocumentObjectExecReturn* Pipe::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } auto getSectionShape = [](App::DocumentObject* feature, const std::vector& subs) -> TopoDS_Shape { - if (!feature || !feature->isDerivedFrom()) + if (!feature || !feature->isDerivedFrom()) { throw Base::TypeError("Pipe: Invalid profile/section"); + } auto subName = subs.empty() ? "" : subs.front(); // only take the entire shape when we have a sketch selected, but // not a point of the sketch - if (feature->isDerivedFrom() - && subName.compare(0, 6, "Vertex") != 0) + if (feature->isDerivedFrom() && subName.compare(0, 6, "Vertex") != 0) { return static_cast(feature)->Shape.getValue(); + } else { - if (subName.empty()) + if (subName.empty()) { throw Base::ValueError("Pipe: No valid subelement linked in Part::Feature"); - return static_cast(feature)->Shape.getShape().getSubShape( - subName.c_str()); + } + return static_cast(feature)->Shape.getShape().getSubShape(subName.c_str()); } }; @@ -133,15 +152,19 @@ App::DocumentObjectExecReturn *Pipe::execute() for (ex.Init(section, TopAbs_WIRE); ex.More(); ex.Next(), ++i) { // if profile was just a point then this is where we can first set our list if (i >= wiresections.size()) { - if (initialWireSectionsEmpty) + if (initialWireSectionsEmpty) { wiresections.emplace_back(1, ex.Current()); - else + } + else { throw Base::ValueError( "Pipe: Sections need to have the same amount of inner wires (except " - "profile and last section, which can be points)"); + "profile and last section, which can be points)" + ); + } } - else + else { wiresections[i].push_back(TopoDS::Wire(ex.Current())); + } } return i; }; @@ -158,7 +181,8 @@ App::DocumentObjectExecReturn *Pipe::execute() TopoShape base; try { base = getBaseTopoShape(); - } catch (const Base::Exception&) { + } + catch (const Base::Exception&) { base = TopoShape(); } @@ -168,19 +192,23 @@ App::DocumentObjectExecReturn *Pipe::execute() // setup the location this->positionByPrevious(); TopLoc_Location invObjLoc = this->getLocation().Inverted(); - if (!base.isNull()) + if (!base.isNull()) { base.move(invObjLoc); + } // setup the profile section - TopoDS_Shape profileShape = getSectionShape(Profile.getValue(), - Profile.getSubValues()); - if (profileShape.IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Pipe: Could not obtain profile shape")); + TopoDS_Shape profileShape = getSectionShape(Profile.getValue(), Profile.getSubValues()); + if (profileShape.IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Pipe: Could not obtain profile shape") + ); + } // build the paths App::DocumentObject* spine = Spine.getValue(); - if (!(spine && spine->isDerivedFrom())) + if (!(spine && spine->isDerivedFrom())) { return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "No spine linked")); + } std::vector subedge = Spine.getSubValues(); TopoDS_Shape path; @@ -192,12 +220,14 @@ App::DocumentObjectExecReturn *Pipe::execute() TopoDS_Shape auxpath; if (Mode.getValue() == 3) { App::DocumentObject* auxspine = AuxiliarySpine.getValue(); - if (!(auxspine && auxspine->isDerivedFrom())) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "No auxiliary spine linked.")); + if (!(auxspine && auxspine->isDerivedFrom())) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "No auxiliary spine linked.") + ); + } std::vector auxsubedge = AuxiliarySpine.getSubValues(); - const Part::TopoShape& auxshape = - static_cast(auxspine)->Shape.getValue(); + const Part::TopoShape& auxshape = static_cast(auxspine)->Shape.getValue(); buildPipePath(auxshape, auxsubedge, auxpath); auxpath.Move(invObjLoc); } @@ -211,17 +241,24 @@ App::DocumentObjectExecReturn *Pipe::execute() // profileShape had no wires so only other valid option is single point section TopExp_Explorer ex; size_t i = 0; - for (ex.Init(profileShape, TopAbs_VERTEX); ex.More(); ex.Next(), ++i) + for (ex.Init(profileShape, TopAbs_VERTEX); ex.More(); ex.Next(), ++i) { profilePoint = ex.Current(); - if (i > 1) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Pipe: Only one isolated point is needed if using a sketch with isolated " - "points for section")); + } + if (i > 1) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Pipe: Only one isolated point is needed if using a sketch with isolated " + "points for section" + )); + } } - if (!profilePoint.IsNull() && (Transformation.getValue() != 1 || multisections.empty())) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Pipe: At least one section is needed when using a single point for profile")); + if (!profilePoint.IsNull() && (Transformation.getValue() != 1 || multisections.empty())) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Pipe: At least one section is needed when using a single point for profile" + )); + } // maybe we need a scaling law Handle(Law_Function) scalinglaw; @@ -233,40 +270,52 @@ App::DocumentObjectExecReturn *Pipe::execute() // TODO: we need to order the sections to prevent occ from crashing, // as makepipeshell connects the sections in the order of adding for (auto& subSet : multisections) { - if (!subSet.first->isDerivedFrom()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Pipe: All sections need to be Part features")); + if (!subSet.first->isDerivedFrom()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Pipe: All sections need to be Part features") + ); + } // if the section is an object's face then take just the face TopoDS_Shape shape = getSectionShape(subSet.first, subSet.second); - if (shape.IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Pipe: Could not obtain section shape")); + if (shape.IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Pipe: Could not obtain section shape") + ); + } size_t nWiresAdded = addWiresToWireSections(shape, wiresections); if (nWiresAdded == 0) { TopExp_Explorer ex; size_t i = 0; for (ex.Init(shape, TopAbs_VERTEX); ex.More(); ex.Next(), ++i) { - if (isLastSectionVertex) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Pipe: Only the profile and last section can be vertices")); + if (isLastSectionVertex) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Pipe: Only the profile and last section can be vertices" + )); + } isLastSectionVertex = true; - for (auto& wires : wiresections) + for (auto& wires : wiresections) { wires.push_back(ex.Current()); + } } } - if (!isLastSectionVertex && nWiresAdded < wiresections.size()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Multisections need to have the same amount of inner wires as the base " - "section")); + if (!isLastSectionVertex && nWiresAdded < wiresections.size()) { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Multisections need to have the same amount of inner wires as the base " + "section" + )); + } } } /*//build the law functions instead else if (Transformation.getValue() == 2) { if (ScalingData.getValues().size()<1) - return new App::DocumentObjectExecReturn("No valid data given for linear scaling mode"); + return new App::DocumentObjectExecReturn("No valid data given for linear scaling + mode"); Handle(Law_Linear) lin = new Law_Linear(); lin->Set(0, 1, 1, ScalingData[0].x); @@ -275,7 +324,8 @@ App::DocumentObjectExecReturn *Pipe::execute() } else if (Transformation.getValue() == 3) { if (ScalingData.getValues().size()<1) - return new App::DocumentObjectExecReturn("No valid data given for S-shape scaling mode"); + return new App::DocumentObjectExecReturn("No valid data given for S-shape scaling + mode"); Handle(Law_S) s = new Law_S(); s->Set(0, 1, ScalingData[0].y, 1, ScalingData[0].x, ScalingData[0].z); @@ -284,16 +334,19 @@ App::DocumentObjectExecReturn *Pipe::execute() }*/ // Verify that path is not a null shape - if (path.IsNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( - "Exception", "Path must not be a null shape")); + if (path.IsNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Path must not be a null shape") + ); + } // build all shells std::vector shells; TopoDS_Shape copyProfilePoint(profilePoint); - if (!profilePoint.IsNull()) + if (!profilePoint.IsNull()) { copyProfilePoint.Move(invObjLoc); + } std::vector frontwires, backwires; for (auto& wires : wiresections) { @@ -301,8 +354,9 @@ App::DocumentObjectExecReturn *Pipe::execute() setupAlgorithm(mkPS, auxpath); if (!scalinglaw) { - if (!profilePoint.IsNull()) + if (!profilePoint.IsNull()) { mkPS.Add(copyProfilePoint); + } for (auto& wire : wires) { wire.Move(invObjLoc); @@ -310,17 +364,21 @@ App::DocumentObjectExecReturn *Pipe::execute() } } else { - if (!profilePoint.IsNull()) + if (!profilePoint.IsNull()) { mkPS.SetLaw(copyProfilePoint, scalinglaw); + } - for (auto& wire : wires) { + for (auto& wire : wires) { wire.Move(invObjLoc); mkPS.SetLaw(wire, scalinglaw); } } - if (!mkPS.IsReady()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Pipe could not be built")); + if (!mkPS.IsReady()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Pipe could not be built") + ); + } shells.emplace_back(mkPS.Shape()); @@ -350,54 +408,79 @@ App::DocumentObjectExecReturn *Pipe::execute() shells.emplace_back(front); } if (!backwires.empty()) { - TopoDS_Shape back = Part::FaceMakerCheese::makeFace(backwires); + TopoDS_Shape back = Part::FaceMakerCheese::makeFace(backwires); sewer.Add(back); shells.emplace_back(back); } - for (TopoShape& s : shells) + for (TopoShape& s : shells) { sewer.Add(s.getShape()); + } sewer.Perform(); - result = result.makeShapeWithElementMap(sewer.SewedShape(), Part::MapperSewing(sewer), shells, Part::OpCodes::Sewing); - } else { + result = result.makeShapeWithElementMap( + sewer.SewedShape(), + Part::MapperSewing(sewer), + shells, + Part::OpCodes::Sewing + ); + } + else { // shells are already closed - add them directly BRepBuilderAPI_MakeSolid mkSolid; for (TopoShape& s : shells) { mkSolid.Add(TopoDS::Shell(s.getShape())); } - if (!mkSolid.IsDone()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result is not a solid")); + if (!mkSolid.IsDone()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Result is not a solid") + ); + } result.setShape(mkSolid.Shape()); } - if(!result.countSubShapes(TopAbs_SHELL)) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Loft: Failed to create shell")); + if (!result.countSubShapes(TopAbs_SHELL)) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Loft: Failed to create shell") + ); + } auto shapes = result.getSubTopoShapes(TopAbs_SHELL); - for (auto &s : shapes) { + for (auto& s : shapes) { // build the solid s = s.makeElementSolid(); BRepClass3d_SolidClassifier SC(s.getShape()); SC.PerformInfinitePoint(Precision::Confusion()); - if ( SC.State() == TopAbs_IN) - s.setShape(s.getShape().Reversed(),false); + if (SC.State() == TopAbs_IN) { + s.setShape(s.getShape().Reversed(), false); + } } - AddSubShape.setValue(result.makeElementCompound(shapes, nullptr, Part::TopoShape::SingleShapeCompoundCreationPolicy::returnShape)); + AddSubShape.setValue(result.makeElementCompound( + shapes, + nullptr, + Part::TopoShape::SingleShapeCompoundCreationPolicy::returnShape + )); - if (shapes.size() > 1) + if (shapes.size() > 1) { result.makeElementFuse(shapes); - else + } + else { result = shapes.front(); + } - if(base.isNull()) { - if (getAddSubType() == FeatureAddSub::Subtractive) + if (base.isNull()) { + if (getAddSubType() == FeatureAddSub::Subtractive) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Pipe: There is nothing to subtract from")); + QT_TRANSLATE_NOOP("Exception", "Pipe: There is nothing to subtract from") + ); + } if (!isSingleSolidRuleSatisfied(result.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } // store shape before refinement @@ -409,7 +492,7 @@ App::DocumentObjectExecReturn *Pipe::execute() } TopoShape boolOp(0, getDocument()->getStringHasher()); - const char *maker; + const char* maker; switch (getAddSubType()) { case Additive: maker = Part::OpCodes::Fuse; @@ -418,26 +501,35 @@ App::DocumentObjectExecReturn *Pipe::execute() maker = Part::OpCodes::Cut; break; default: - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Unknown operation type")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Unknown operation type") + ); } try { - boolOp.makeElementBoolean(maker, {base,result}); + boolOp.makeElementBoolean(maker, {base, result}); } - catch(Standard_Failure&) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Failed to perform boolean operation")); + catch (Standard_Failure&) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Failed to perform boolean operation") + ); } TopoShape solid = getSolid(boolOp); // lets check if the result is a solid - if (solid.isNull()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid")); + if (solid.isNull()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid") + ); + } // store shape before refinement this->rawShape = boolOp; boolOp = refineShapeIfActive(boolOp); if (!isSingleSolidRuleSatisfied(boolOp.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", - "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } boolOp = getSolid(boolOp); Shape.setValue(boolOp); @@ -447,15 +539,18 @@ App::DocumentObjectExecReturn *Pipe::execute() return new App::DocumentObjectExecReturn(e.GetMessageString()); } catch (...) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "A fatal error occurred when making the pipe")); + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "A fatal error occurred when making the pipe") + ); } } -void Pipe::setupAlgorithm(BRepOffsetAPI_MakePipeShell& mkPipeShell, const TopoDS_Shape& auxshape) { +void Pipe::setupAlgorithm(BRepOffsetAPI_MakePipeShell& mkPipeShell, const TopoDS_Shape& auxshape) +{ mkPipeShell.SetTolerance(Precision::Confusion()); - switch(Transition.getValue()) { + switch (Transition.getValue()) { case 0: mkPipeShell.SetTransitionMode(BRepBuilderAPI_Transformed); break; @@ -469,7 +564,7 @@ void Pipe::setupAlgorithm(BRepOffsetAPI_MakePipeShell& mkPipeShell, const TopoDS bool auxiliary = false; const Base::Vector3d& bVec = Binormal.getValue(); - switch(Mode.getValue()) { + switch (Mode.getValue()) { case 1: mkPipeShell.SetMode(gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 0, 1), gp_Dir(1, 0, 0))); break; @@ -543,17 +638,20 @@ void Pipe::getContinuousEdges(Part::TopoShape /*TopShape*/, std::vector& subedge, - TopoDS_Shape& path) +void Pipe::buildPipePath( + const Part::TopoShape& shape, + const std::vector& subedge, + TopoDS_Shape& path +) { if (!shape.getShape().IsNull()) { try { if (!subedge.empty()) { - //if (SpineTangent.getValue()) - //getContinuousEdges(shape, subedge); + // if (SpineTangent.getValue()) + // getContinuousEdges(shape, subedge); BRepBuilderAPI_MakeWire mkWire; - for (const auto & it : subedge) { + for (const auto& it : subedge) { TopoDS_Shape subshape = shape.getSubShape(it.c_str()); mkWire.Add(TopoDS::Edge(subshape)); } @@ -569,28 +667,42 @@ void Pipe::buildPipePath(const Part::TopoShape& shape, const std::vectorAppend(xp.Current()); + } ShapeAnalysis_FreeBounds::ConnectEdgesToWires( - hEdges, Precision::Confusion(), Standard_True, hWires); + hEdges, + Precision::Confusion(), + Standard_True, + hWires + ); int len = hWires->Length(); - if (len != 1) + if (len != 1) { throw Base::ValueError(QT_TRANSLATE_NOOP("Exception", "Spine is not connected.")); + } path = hWires->Value(1); } else { - throw Base::TypeError(QT_TRANSLATE_NOOP("Exception", "Spine is neither an edge nor a wire.")); + throw Base::TypeError( + QT_TRANSLATE_NOOP("Exception", "Spine is neither an edge nor a wire.") + ); } } catch (Standard_Failure&) { @@ -599,17 +711,18 @@ void Pipe::buildPipePath(const Part::TopoShape& shape, const std::vector &multisections = {}, - bool moveProfile = false, - bool rotateProfile = false); + App::DocumentObjectExecReturn* _execute( + ProfileBased* feat, + const TopoShape& path, + const TopLoc_Location& invObjLoc = TopLoc_Location(), + int transition = 0, + const TopoShape& auxpath = TopoShape(), + bool auxCurviLinear = true, + int mode = 2, + const Base::Vector3d& binormalVector = Base::Vector3d(), + int transformation = 0, + const std::vector& multisections = {}, + bool moveProfile = false, + bool rotateProfile = false + ); protected: /// get the given edges and all their tangent ones - void getContinuousEdges(Part::TopoShape TopShape, std::vector< std::string >& SubNames); - void buildPipePath(const Part::TopoShape& input, const std::vector& edges, TopoDS_Shape& result); + void getContinuousEdges(Part::TopoShape TopShape, std::vector& SubNames); + void buildPipePath( + const Part::TopoShape& input, + const std::vector& edges, + TopoDS_Shape& result + ); void setupAlgorithm(BRepOffsetAPI_MakePipeShell& mkPipeShell, const TopoDS_Shape& auxshape); /// handle changed property - void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; - void handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, - const char* PropName) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; private: static const char* TypeEnums[]; @@ -84,21 +98,25 @@ private: static const char* TransformEnums[]; }; -class PartDesignExport AdditivePipe : public Pipe { +class PartDesignExport AdditivePipe: public Pipe +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditivePipe); + public: AdditivePipe(); }; -class PartDesignExport SubtractivePipe : public Pipe { +class PartDesignExport SubtractivePipe: public Pipe +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractivePipe); + public: SubtractivePipe(); }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_Pipe_H +#endif // PARTDESIGN_Pipe_H diff --git a/src/Mod/PartDesign/App/FeaturePocket.cpp b/src/Mod/PartDesign/App/FeaturePocket.cpp index d4bb07b9fd..dc59e47cd7 100644 --- a/src/Mod/PartDesign/App/FeaturePocket.cpp +++ b/src/Mod/PartDesign/App/FeaturePocket.cpp @@ -21,11 +21,11 @@ ***************************************************************************/ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -41,7 +41,8 @@ using namespace PartDesign; // because the files store the enum index. So it is not possible to migrate files if the // enum entry is removed (see #23612). In the distant future, when all files are reasonably // migrated we can drop this. -const char* Pocket::TypeEnums[]= {"Length", "ThroughAll", "UpToFirst", "UpToFace", "?TwoLengths", "UpToShape", nullptr}; +const char* Pocket::TypeEnums[] + = {"Length", "ThroughAll", "UpToFirst", "UpToFace", "?TwoLengths", "UpToShape", nullptr}; PROPERTY_SOURCE(PartDesign::Pocket, PartDesign::FeatureExtrude) @@ -57,16 +58,52 @@ Pocket::Pocket() Type2.setEnums(TypeEnums); ADD_PROPERTY_TYPE(Length, (5.0), "Side1", App::Prop_None, "Pocket length"); ADD_PROPERTY_TYPE(Length2, (5.0), "Side2", App::Prop_None, "Pocket length in 2nd direction"); - ADD_PROPERTY_TYPE(UseCustomVector, (false), "Pocket", App::Prop_None, "Use custom vector for pocket direction"); - ADD_PROPERTY_TYPE(Direction, (Base::Vector3d(1.0, 1.0, 1.0)), "Pocket", App::Prop_None, "Pocket direction vector"); + ADD_PROPERTY_TYPE( + UseCustomVector, + (false), + "Pocket", + App::Prop_None, + "Use custom vector for pocket direction" + ); + ADD_PROPERTY_TYPE( + Direction, + (Base::Vector3d(1.0, 1.0, 1.0)), + "Pocket", + App::Prop_None, + "Pocket direction vector" + ); ADD_PROPERTY_TYPE(ReferenceAxis, (nullptr), "Pocket", App::Prop_None, "Reference axis of direction"); - ADD_PROPERTY_TYPE(AlongSketchNormal, (true), "Pocket", App::Prop_None, "Measure pocket length along the sketch normal direction"); + ADD_PROPERTY_TYPE( + AlongSketchNormal, + (true), + "Pocket", + App::Prop_None, + "Measure pocket length along the sketch normal direction" + ); ADD_PROPERTY_TYPE(UpToFace, (nullptr), "Side1", App::Prop_None, "Face where pocket will end"); - ADD_PROPERTY_TYPE(UpToShape, (nullptr), "Side1", App::Prop_None, "Face(s) or shape(s) where pocket will end"); + ADD_PROPERTY_TYPE( + UpToShape, + (nullptr), + "Side1", + App::Prop_None, + "Face(s) or shape(s) where pocket will end" + ); ADD_PROPERTY_TYPE(UpToFace2, (nullptr), "Side2", App::Prop_None, "Face where pocket will end"); - ADD_PROPERTY_TYPE(UpToShape2, (nullptr), "Side2", App::Prop_None, "Face(s) or shape(s) where pocket will end"); + ADD_PROPERTY_TYPE( + UpToShape2, + (nullptr), + "Side2", + App::Prop_None, + "Face(s) or shape(s) where pocket will end" + ); ADD_PROPERTY_TYPE(Offset, (0.0), "Side1", App::Prop_None, "Offset from face in which pocket will end"); - ADD_PROPERTY_TYPE(Offset2, (0.0), "Side2", App::Prop_None, "Offset from face in which pocket will end on side 2"); + ADD_PROPERTY_TYPE( + Offset2, + (0.0), + "Side2", + App::Prop_None, + "Offset from face in which pocket will end on side 2" + ); Offset.setConstraints(&signedLengthConstraint); Offset2.setConstraints(&signedLengthConstraint); ADD_PROPERTY_TYPE(TaperAngle, (0.0), "Side1", App::Prop_None, "Taper angle"); @@ -80,13 +117,14 @@ Pocket::Pocket() Length2.setConstraints(nullptr); } -App::DocumentObjectExecReturn *Pocket::execute() +App::DocumentObjectExecReturn* Pocket::execute() { // MakeFace|MakeFuse: because we want a solid. // InverseDirection: to inverse the auto detected extrusion direction for // backward compatibility to upstream - ExtrudeOptions options(ExtrudeOption::MakeFace | ExtrudeOption::MakeFuse - | ExtrudeOption::InverseDirection); + ExtrudeOptions options( + ExtrudeOption::MakeFace | ExtrudeOption::MakeFuse | ExtrudeOption::InverseDirection + ); return buildExtrusion(options); } @@ -96,4 +134,3 @@ Base::Vector3d Pocket::getProfileNormal() const // turn around for pockets return res * -1; } - diff --git a/src/Mod/PartDesign/App/FeaturePocket.h b/src/Mod/PartDesign/App/FeaturePocket.h index c1bf5f3a22..81e442e778 100644 --- a/src/Mod/PartDesign/App/FeaturePocket.h +++ b/src/Mod/PartDesign/App/FeaturePocket.h @@ -29,7 +29,7 @@ namespace PartDesign { -class PartDesignExport Pocket : public FeatureExtrude +class PartDesignExport Pocket: public FeatureExtrude { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Pocket); @@ -39,18 +39,19 @@ public: /** @name methods override feature */ //@{ /** Recalculate the feature - * Extrudes the Sketch in the direction of the sketch face normal - * If Type is "Length" then Length gives the extrusion length, the direction will be into the support - * If Type is "ThroughAll" then the extrusion length will be infinite - * If Type is "UpToFirst" then extrusion will stop at the first face of the support that is cut - * by a line through the centre of gravite of the sketch - * If Type is "UpToFace" then the extrusion will stop at FaceName in the support - * If Midplane is true, then the extrusion will extend for half of the length on both sides of the sketch plane - * The created material will be cut out of the sketch support - */ - App::DocumentObjectExecReturn *execute() override; + * Extrudes the Sketch in the direction of the sketch face normal + * If Type is "Length" then Length gives the extrusion length, the direction will be into the + * support If Type is "ThroughAll" then the extrusion length will be infinite If Type is + * "UpToFirst" then extrusion will stop at the first face of the support that is cut by a line + * through the centre of gravite of the sketch If Type is "UpToFace" then the extrusion will + * stop at FaceName in the support If Midplane is true, then the extrusion will extend for half + * of the length on both sides of the sketch plane The created material will be cut out of the + * sketch support + */ + App::DocumentObjectExecReturn* execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderPocket"; } @@ -60,7 +61,7 @@ private: static const char* TypeEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Pocket_H +#endif // PART_Pocket_H diff --git a/src/Mod/PartDesign/App/FeaturePolarPattern.cpp b/src/Mod/PartDesign/App/FeaturePolarPattern.cpp index 6198eadb3e..89902bc991 100644 --- a/src/Mod/PartDesign/App/FeaturePolarPattern.cpp +++ b/src/Mod/PartDesign/App/FeaturePolarPattern.cpp @@ -20,14 +20,14 @@ * * ******************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include "DatumLine.h" #include @@ -41,62 +41,74 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ PROPERTY_SOURCE(PartDesign::PolarPattern, PartDesign::Transformed) -const App::PropertyIntegerConstraint::Constraints PolarPattern::intOccurrences = { - 1, std::numeric_limits::max(), 1 }; -const App::PropertyAngle::Constraints PolarPattern::floatAngle = { Base::toDegrees(Precision::Angular()), 360.0, 1.0 }; +const App::PropertyIntegerConstraint::Constraints PolarPattern::intOccurrences + = {1, std::numeric_limits::max(), 1}; +const App::PropertyAngle::Constraints PolarPattern::floatAngle + = {Base::toDegrees(Precision::Angular()), 360.0, 1.0}; -const char* PolarPattern::ModeEnums[] = { "Extent", "Spacing", nullptr}; +const char* PolarPattern::ModeEnums[] = {"Extent", "Spacing", nullptr}; PolarPattern::PolarPattern() { auto initialMode = PolarPatternMode::Extent; - ADD_PROPERTY_TYPE(Axis, - (nullptr), - "PolarPattern", - App::Prop_None, - "The axis of rotation for the pattern. This can be a datum axis, a sketch " - "axis, a circular edge, or the normal of a planar face."); + ADD_PROPERTY_TYPE( + Axis, + (nullptr), + "PolarPattern", + App::Prop_None, + "The axis of rotation for the pattern. This can be a datum axis, a sketch " + "axis, a circular edge, or the normal of a planar face." + ); ADD_PROPERTY_TYPE( Reversed, (0), "PolarPattern", App::Prop_None, - "Reverses the pattern direction from counter-clockwise (default) to clockwise."); + "Reverses the pattern direction from counter-clockwise (default) to clockwise." + ); ADD_PROPERTY_TYPE( Mode, (long(initialMode)), "PolarPattern", App::Prop_None, "Selects how the pattern is dimensioned.\n'Extent': Uses the total angle to contain all " - "instances.\n'Spacing': Uses the angle between consecutive instances."); + "instances.\n'Spacing': Uses the angle between consecutive instances." + ); Mode.setEnums(PolarPattern::ModeEnums); - ADD_PROPERTY_TYPE(Angle, - (360.0), - "PolarPattern", - App::Prop_None, - "The total angle of the pattern, measured from the first to the last " - "instance. This is only used when the Mode is set to 'Extent'."); + ADD_PROPERTY_TYPE( + Angle, + (360.0), + "PolarPattern", + App::Prop_None, + "The total angle of the pattern, measured from the first to the last " + "instance. This is only used when the Mode is set to 'Extent'." + ); Angle.setConstraints(&floatAngle); - ADD_PROPERTY_TYPE(Offset, - (120.0), - "PolarPattern", - App::Prop_None, - "The angular distance between each instance of the pattern. This is only " - "used when the Mode is set to 'Spacing'."); + ADD_PROPERTY_TYPE( + Offset, + (120.0), + "PolarPattern", + App::Prop_None, + "The angular distance between each instance of the pattern. This is only " + "used when the Mode is set to 'Spacing'." + ); Offset.setConstraints(&floatAngle); - ADD_PROPERTY_TYPE(Spacings, - ({-1.0, -1.0, -1.0}), - "PolarPattern", - App::Prop_None, - "A list of custom angular spacings between instances. If a value is -1, the " - "global 'Offset' is used for that spacing. The list should have one less " - "item than the number of occurrences."); + ADD_PROPERTY_TYPE( + Spacings, + ({-1.0, -1.0, -1.0}), + "PolarPattern", + App::Prop_None, + "A list of custom angular spacings between instances. If a value is -1, the " + "global 'Offset' is used for that spacing. The list should have one less " + "item than the number of occurrences." + ); ADD_PROPERTY_TYPE( SpacingPattern, ({}), @@ -105,13 +117,15 @@ PolarPattern::PolarPattern() "(Experimental and subject to change. To enable " "this in the UI you can add a boolean parameter 'ExperiementalFeature' in " "Preferences/Mod/Part)\nDefines a repeating pattern of spacings for the second direction. " - "For example, a list of [10, 20] will create alternating spacings of 10mm and 20mm."); + "For example, a list of [10, 20] will create alternating spacings of 10mm and 20mm." + ); ADD_PROPERTY_TYPE( Occurrences, (3), "PolarPattern", App::Prop_None, - "The total number of instances in the pattern, including the original feature."); + "The total number of instances in the pattern, including the original feature." + ); Occurrences.setConstraints(&intOccurrences); setReadWriteStatusForMode(initialMode); @@ -119,93 +133,106 @@ PolarPattern::PolarPattern() short PolarPattern::mustExecute() const { - if (Axis.isTouched() || - Reversed.isTouched() || - Mode.isTouched() || + if (Axis.isTouched() || Reversed.isTouched() || Mode.isTouched() || // Angle and Offset are mutually exclusive, only one could be updated at once - Angle.isTouched() || - Offset.isTouched() || - Spacings.isTouched() || - SpacingPattern.isTouched() || - Occurrences.isTouched()) + Angle.isTouched() || Offset.isTouched() || Spacings.isTouched() + || SpacingPattern.isTouched() || Occurrences.isTouched()) { return 1; + } return Transformed::mustExecute(); } const std::list PolarPattern::getTransformations(const std::vector) { int occurrences = Occurrences.getValue(); - if (occurrences < 1) + if (occurrences < 1) { throw Base::ValueError("At least one occurrence required"); + } - if (occurrences == 1) + if (occurrences == 1) { return {gp_Trsf()}; + } bool reversed = Reversed.getValue(); App::DocumentObject* refObject = Axis.getValue(); - if (!refObject) + if (!refObject) { throw Base::ValueError("No axis reference specified"); + } std::vector subStrings = Axis.getSubValues(); - if (subStrings.empty()) + if (subStrings.empty()) { throw Base::ValueError("No axis reference specified"); + } gp_Pnt axbase; gp_Dir axdir; if (refObject->isDerivedFrom()) { Part::Part2DObject* refSketch = static_cast(refObject); Base::Axis axis; - if (subStrings[0] == "H_Axis") + if (subStrings[0] == "H_Axis") { axis = refSketch->getAxis(Part::Part2DObject::H_Axis); - else if (subStrings[0] == "V_Axis") + } + else if (subStrings[0] == "V_Axis") { axis = refSketch->getAxis(Part::Part2DObject::V_Axis); - else if (subStrings[0] == "N_Axis") + } + else if (subStrings[0] == "N_Axis") { axis = refSketch->getAxis(Part::Part2DObject::N_Axis); + } else if (subStrings[0].compare(0, 4, "Axis") == 0) { - int AxId = std::atoi(subStrings[0].substr(4,4000).c_str()); - if (AxId >= 0 && AxId < refSketch->getAxisCount()) + int AxId = std::atoi(subStrings[0].substr(4, 4000).c_str()); + if (AxId >= 0 && AxId < refSketch->getAxisCount()) { axis = refSketch->getAxis(AxId); + } } axis *= refSketch->Placement.getValue(); axbase = gp_Pnt(axis.getBase().x, axis.getBase().y, axis.getBase().z); axdir = gp_Dir(axis.getDirection().x, axis.getDirection().y, axis.getDirection().z); - } else if (refObject->isDerivedFrom()) { + } + else if (refObject->isDerivedFrom()) { PartDesign::Line* line = static_cast(refObject); Base::Vector3d base = line->getBasePoint(); axbase = gp_Pnt(base.x, base.y, base.z); Base::Vector3d dir = line->getDirection(); axdir = gp_Dir(dir.x, dir.y, dir.z); - } else if (refObject->isDerivedFrom()) { + } + else if (refObject->isDerivedFrom()) { App::Line* line = static_cast(refObject); Base::Vector3d base = line->getBasePoint(); axbase = gp_Pnt(base.x, base.y, base.z); Base::Vector3d d = line->getDirection(); axdir = gp_Dir(d.x, d.y, d.z); - } else if (refObject->isDerivedFrom()) { - if (subStrings[0].empty()) + } + else if (refObject->isDerivedFrom()) { + if (subStrings[0].empty()) { throw Base::ValueError("No axis reference specified"); + } Part::Feature* refFeature = static_cast(refObject); Part::TopoShape refShape = refFeature->Shape.getShape(); TopoDS_Shape ref = refShape.getSubShape(subStrings[0].c_str()); if (ref.ShapeType() == TopAbs_EDGE) { TopoDS_Edge refEdge = TopoDS::Edge(ref); - if (refEdge.IsNull()) + if (refEdge.IsNull()) { throw Base::ValueError("Failed to extract axis edge"); + } BRepAdaptor_Curve adapt(refEdge); if (adapt.GetType() == GeomAbs_Line) { axbase = adapt.Line().Location(); axdir = adapt.Line().Direction(); - } else if (adapt.GetType() == GeomAbs_Circle) { + } + else if (adapt.GetType() == GeomAbs_Circle) { axbase = adapt.Circle().Location(); axdir = adapt.Circle().Axis().Direction(); - } else { + } + else { throw Base::TypeError("Rotation edge must be a straight line, circle or arc of circle"); } - } else { + } + else { throw Base::TypeError("Axis reference must be an edge"); } - } else { + } + else { throw Base::TypeError("Axis reference must be edge of a feature or datum line"); } TopLoc_Location invObjLoc = this->getLocation().Inverted(); @@ -214,21 +241,25 @@ const std::list PolarPattern::getTransformations(const std::vector PolarPattern::getTransformations(const std::vector getTransformations(const std::vector) override; protected: - void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onChanged(const App::Property* prop) override; static const App::PropertyIntegerConstraint::Constraints intOccurrences; @@ -99,7 +107,7 @@ private: void updateSpacings(); }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeaturePolarPattern_H +#endif // PARTDESIGN_FeaturePolarPattern_H diff --git a/src/Mod/PartDesign/App/FeaturePrimitive.cpp b/src/Mod/PartDesign/App/FeaturePrimitive.cpp index cf7f9e96df..99d2ce261f 100644 --- a/src/Mod/PartDesign/App/FeaturePrimitive.cpp +++ b/src/Mod/PartDesign/App/FeaturePrimitive.cpp @@ -20,21 +20,21 @@ * * ***************************************************************************/ -# include +#include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -47,15 +47,18 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ -const App::PropertyQuantityConstraint::Constraints torusRangeV = { -180.0, 180.0, 1.0 }; -const App::PropertyQuantityConstraint::Constraints angleRangeU = { 0.0, 360.0, 1.0 }; -const App::PropertyQuantityConstraint::Constraints angleRangeV = { -90.0, 90.0, 1.0 }; +const App::PropertyQuantityConstraint::Constraints torusRangeV = {-180.0, 180.0, 1.0}; +const App::PropertyQuantityConstraint::Constraints angleRangeU = {0.0, 360.0, 1.0}; +const App::PropertyQuantityConstraint::Constraints angleRangeV = {-90.0, 90.0, 1.0}; // it turned out that OCC cannot e.g. create a box with a width of Precision::Confusion() // with two times Precision::Confusion() all geometric primitives can be created -const App::PropertyQuantityConstraint::Constraints quantityRange = { 2 * Precision::Confusion(), std::numeric_limits::max(), 0.1 }; -const App::PropertyQuantityConstraint::Constraints quantityRangeZero = { 0.0, std::numeric_limits::max(), 0.1 }; +const App::PropertyQuantityConstraint::Constraints quantityRange + = {2 * Precision::Confusion(), std::numeric_limits::max(), 0.1}; +const App::PropertyQuantityConstraint::Constraints quantityRangeZero + = {0.0, std::numeric_limits::max(), 0.1}; PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesign::FeaturePrimitive, PartDesign::FeatureAddSub) @@ -66,13 +69,15 @@ FeaturePrimitive::FeaturePrimitive() App::DocumentObjectExecReturn* FeaturePrimitive::execute(const TopoDS_Shape& primitive) { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } try { - //transform the primitive in the correct coordinance + // transform the primitive in the correct coordinance FeatureAddSub::execute(); - //if we have no base we just add the standard primitive shape + // if we have no base we just add the standard primitive shape TopoShape primitiveShape; primitiveShape.setShape(primitive); @@ -86,15 +91,20 @@ App::DocumentObjectExecReturn* FeaturePrimitive::execute(const TopoDS_Shape& pri catch (const Base::Exception&) { - //as we use this for preview we can add it even if useless for subtractive - AddSubShape.setValue(primitiveShape); + // as we use this for preview we can add it even if useless for subtractive + AddSubShape.setValue(primitiveShape); - if(getAddSubType() == FeatureAddSub::Additive) - Shape.setValue(getSolid(primitiveShape)); - else - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Cannot subtract primitive feature without base feature")); + if (getAddSubType() == FeatureAddSub::Additive) { + Shape.setValue(getSolid(primitiveShape)); + } + else { + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Cannot subtract primitive feature without base feature" + )); + } - return App::DocumentObject::StdReturn; + return App::DocumentObject::StdReturn; } AddSubShape.setValue(primitiveShape); @@ -110,27 +120,30 @@ App::DocumentObjectExecReturn* FeaturePrimitive::execute(const TopoDS_Shape& pri break; default: return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Unknown operation type")); + QT_TRANSLATE_NOOP("Exception", "Unknown operation type") + ); } try { boolOp.makeElementBoolean(maker, {base, primitiveShape}); } catch (Standard_Failure&) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Failed to perform boolean operation")); + QT_TRANSLATE_NOOP("Exception", "Failed to perform boolean operation") + ); } TopoShape solidBoolOp = getSolid(boolOp); // lets check if the result is a solid if (solidBoolOp.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid")); + QT_TRANSLATE_NOOP("Exception", "Resulting shape is not a solid") + ); } // store shape before refinement this->rawShape = boolOp; - - if (solidBoolOp == base){ - //solidBoolOp is misplaced but boolOp is ok + + if (solidBoolOp == base) { + // solidBoolOp is misplaced but boolOp is ok Shape.setValue(boolOp); return App::DocumentObject::StdReturn; } @@ -161,7 +174,7 @@ void FeaturePrimitive::onChanged(const App::Property* prop) # pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif -PYTHON_TYPE_DEF(PrimitivePy, PartDesign::FeaturePy)//explicit bombs +PYTHON_TYPE_DEF(PrimitivePy, PartDesign::FeaturePy) // explicit bombs PYTHON_TYPE_IMP(PrimitivePy, PartDesign::FeaturePy) #if defined(__clang__) @@ -170,9 +183,9 @@ PYTHON_TYPE_IMP(PrimitivePy, PartDesign::FeaturePy) PyObject* FeaturePrimitive::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new PrimitivePy(this),true); + PythonObject = Py::Object(new PrimitivePy(this), true); } return Py::new_reference_to(PythonObject); } @@ -181,9 +194,9 @@ PROPERTY_SOURCE(PartDesign::Box, PartDesign::FeaturePrimitive) Box::Box() { - ADD_PROPERTY_TYPE(Length,(10.0f),"Box",App::Prop_None,"The length of the box"); - ADD_PROPERTY_TYPE(Width ,(10.0f),"Box",App::Prop_None,"The width of the box"); - ADD_PROPERTY_TYPE(Height,(10.0f),"Box",App::Prop_None,"The height of the box"); + ADD_PROPERTY_TYPE(Length, (10.0f), "Box", App::Prop_None, "The length of the box"); + ADD_PROPERTY_TYPE(Width, (10.0f), "Box", App::Prop_None, "The width of the box"); + ADD_PROPERTY_TYPE(Height, (10.0f), "Box", App::Prop_None, "The height of the box"); Length.setConstraints(&quantityRange); Width.setConstraints(&quantityRange); Height.setConstraints(&quantityRange); @@ -197,12 +210,21 @@ App::DocumentObjectExecReturn* Box::execute() double W = Width.getValue(); double H = Height.getValue(); - if (L < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Length of box too small")); - if (W < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Width of box too small")); - if (H < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Height of box too small")); + if (L < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Length of box too small") + ); + } + if (W < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Width of box too small") + ); + } + if (H < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Height of box too small") + ); + } try { // Build a box using the dimension attributes @@ -216,10 +238,9 @@ App::DocumentObjectExecReturn* Box::execute() short int Box::mustExecute() const { - if ( Length.isTouched() || - Height.isTouched() || - Width.isTouched() ) + if (Length.isTouched() || Height.isTouched() || Width.isTouched()) { return 1; + } return FeaturePrimitive::mustExecute(); } @@ -232,9 +253,9 @@ PROPERTY_SOURCE(PartDesign::Cylinder, PartDesign::FeaturePrimitive) Cylinder::Cylinder() { - ADD_PROPERTY_TYPE(Radius,(10.0f),"Cylinder",App::Prop_None,"The radius of the cylinder"); - ADD_PROPERTY_TYPE(Angle,(360.0f),"Cylinder",App::Prop_None,"The closing angle of the cylinder "); - ADD_PROPERTY_TYPE(Height,(10.0f),"Cylinder",App::Prop_None,"The height of the cylinder"); + ADD_PROPERTY_TYPE(Radius, (10.0f), "Cylinder", App::Prop_None, "The radius of the cylinder"); + ADD_PROPERTY_TYPE(Angle, (360.0f), "Cylinder", App::Prop_None, "The closing angle of the cylinder "); + ADD_PROPERTY_TYPE(Height, (10.0f), "Cylinder", App::Prop_None, "The height of the cylinder"); Angle.setConstraints(&angleRangeU); Radius.setConstraints(&quantityRange); Height.setConstraints(&quantityRange); @@ -247,16 +268,27 @@ Cylinder::Cylinder() App::DocumentObjectExecReturn* Cylinder::execute() { // Build a cylinder - if (Radius.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of cylinder too small")); - if (Height.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Height of cylinder too small")); - if (Angle.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Rotation angle of cylinder too small")); + if (Radius.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of cylinder too small") + ); + } + if (Height.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Height of cylinder too small") + ); + } + if (Angle.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Rotation angle of cylinder too small") + ); + } try { - BRepPrimAPI_MakeCylinder mkCylr(Radius.getValue(), - Height.getValue(), - Base::toRadians(Angle.getValue())); + BRepPrimAPI_MakeCylinder mkCylr( + Radius.getValue(), + Height.getValue(), + Base::toRadians(Angle.getValue()) + ); // the direction vector for the prism is the height for z and the given angle BRepPrim_Cylinder prim = mkCylr.Cylinder(); @@ -273,10 +305,9 @@ App::DocumentObjectExecReturn* Cylinder::execute() short int Cylinder::mustExecute() const { - if ( Radius.isTouched() || - Height.isTouched() || - Angle.isTouched() ) + if (Radius.isTouched() || Height.isTouched() || Angle.isTouched()) { return 1; + } return FeaturePrimitive::mustExecute(); } @@ -289,13 +320,13 @@ PROPERTY_SOURCE(PartDesign::Sphere, PartDesign::FeaturePrimitive) Sphere::Sphere() { - ADD_PROPERTY_TYPE(Radius,(5.0),"Sphere",App::Prop_None,"The radius of the sphere"); + ADD_PROPERTY_TYPE(Radius, (5.0), "Sphere", App::Prop_None, "The radius of the sphere"); Radius.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Angle1,(-90.0f),"Sphere",App::Prop_None,"The angle of the sphere"); + ADD_PROPERTY_TYPE(Angle1, (-90.0f), "Sphere", App::Prop_None, "The angle of the sphere"); Angle1.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle2,(90.0f),"Sphere",App::Prop_None,"The angle of the sphere"); + ADD_PROPERTY_TYPE(Angle2, (90.0f), "Sphere", App::Prop_None, "The angle of the sphere"); Angle2.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle3,(360.0f),"Sphere",App::Prop_None,"The angle of the sphere"); + ADD_PROPERTY_TYPE(Angle3, (360.0f), "Sphere", App::Prop_None, "The angle of the sphere"); Angle3.setConstraints(&angleRangeU); primitiveType = FeaturePrimitive::Sphere; @@ -303,14 +334,19 @@ Sphere::Sphere() App::DocumentObjectExecReturn* Sphere::execute() { - // Build a sphere - if (Radius.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of sphere too small")); + // Build a sphere + if (Radius.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of sphere too small") + ); + } try { - BRepPrimAPI_MakeSphere mkSphere(Radius.getValue(), - Base::toRadians(Angle1.getValue()), - Base::toRadians(Angle2.getValue()), - Base::toRadians(Angle3.getValue())); + BRepPrimAPI_MakeSphere mkSphere( + Radius.getValue(), + Base::toRadians(Angle1.getValue()), + Base::toRadians(Angle2.getValue()), + Base::toRadians(Angle3.getValue()) + ); return FeaturePrimitive::execute(mkSphere.Shape()); } catch (Standard_Failure& e) { @@ -322,11 +358,9 @@ App::DocumentObjectExecReturn* Sphere::execute() short int Sphere::mustExecute() const { - if ( Radius.isTouched() || - Angle1.isTouched() || - Angle2.isTouched() || - Angle3.isTouched()) + if (Radius.isTouched() || Angle1.isTouched() || Angle2.isTouched() || Angle3.isTouched()) { return 1; + } return FeaturePrimitive::mustExecute(); } @@ -339,10 +373,10 @@ PROPERTY_SOURCE(PartDesign::Cone, PartDesign::FeaturePrimitive) Cone::Cone() { - ADD_PROPERTY_TYPE(Radius1,(2.0),"Cone",App::Prop_None,"The radius of the cone"); - ADD_PROPERTY_TYPE(Radius2,(4.0),"Cone",App::Prop_None,"The radius of the cone"); - ADD_PROPERTY_TYPE(Height,(10.0),"Cone",App::Prop_None,"The height of the cone"); - ADD_PROPERTY_TYPE(Angle,(360.0),"Cone",App::Prop_None,"The angle of the cone"); + ADD_PROPERTY_TYPE(Radius1, (2.0), "Cone", App::Prop_None, "The radius of the cone"); + ADD_PROPERTY_TYPE(Radius2, (4.0), "Cone", App::Prop_None, "The radius of the cone"); + ADD_PROPERTY_TYPE(Height, (10.0), "Cone", App::Prop_None, "The height of the cone"); + ADD_PROPERTY_TYPE(Angle, (360.0), "Cone", App::Prop_None, "The angle of the cone"); Angle.setConstraints(&angleRangeU); Radius1.setConstraints(&quantityRangeZero); Radius2.setConstraints(&quantityRangeZero); @@ -353,25 +387,38 @@ Cone::Cone() App::DocumentObjectExecReturn* Cone::execute() { - if (Radius1.getValue() < 0.0) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of cone cannot be negative")); - if (Radius2.getValue() < 0.0) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of cone cannot be negative")); - if (Height.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Height of cone too small")); + if (Radius1.getValue() < 0.0) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of cone cannot be negative") + ); + } + if (Radius2.getValue() < 0.0) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of cone cannot be negative") + ); + } + if (Height.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Height of cone too small") + ); + } try { - if (std::abs(Radius1.getValue() - Radius2.getValue()) < Precision::Confusion()){ - //Build a cylinder - BRepPrimAPI_MakeCylinder mkCylr(Radius1.getValue(), - Height.getValue(), - Base::toRadians(Angle.getValue())); + if (std::abs(Radius1.getValue() - Radius2.getValue()) < Precision::Confusion()) { + // Build a cylinder + BRepPrimAPI_MakeCylinder mkCylr( + Radius1.getValue(), + Height.getValue(), + Base::toRadians(Angle.getValue()) + ); return FeaturePrimitive::execute(mkCylr.Shape()); } // Build a cone - BRepPrimAPI_MakeCone mkCone(Radius1.getValue(), - Radius2.getValue(), - Height.getValue(), - Base::toRadians(Angle.getValue())); + BRepPrimAPI_MakeCone mkCone( + Radius1.getValue(), + Radius2.getValue(), + Height.getValue(), + Base::toRadians(Angle.getValue()) + ); return FeaturePrimitive::execute(mkCone.Shape()); } catch (Standard_Failure& e) { @@ -383,14 +430,18 @@ App::DocumentObjectExecReturn* Cone::execute() short int Cone::mustExecute() const { - if (Radius1.isTouched()) + if (Radius1.isTouched()) { return 1; - if (Radius2.isTouched()) + } + if (Radius2.isTouched()) { return 1; - if (Height.isTouched()) + } + if (Height.isTouched()) { return 1; - if (Angle.isTouched()) + } + if (Angle.isTouched()) { return 1; + } return FeaturePrimitive::mustExecute(); } @@ -401,17 +452,23 @@ PROPERTY_SOURCE(PartDesign::Ellipsoid, PartDesign::FeaturePrimitive) Ellipsoid::Ellipsoid() { - ADD_PROPERTY_TYPE(Radius1,(2.0),"Ellipsoid",App::Prop_None,"Radius in local Z-direction"); + ADD_PROPERTY_TYPE(Radius1, (2.0), "Ellipsoid", App::Prop_None, "Radius in local Z-direction"); Radius1.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius2,(4.0),"Ellipsoid",App::Prop_None,"Radius in local X-direction"); + ADD_PROPERTY_TYPE(Radius2, (4.0), "Ellipsoid", App::Prop_None, "Radius in local X-direction"); Radius2.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius3,(0.0),"Ellipsoid",App::Prop_None,"Radius in local Y-direction\nIf zero, it is equal to Radius2"); + ADD_PROPERTY_TYPE( + Radius3, + (0.0), + "Ellipsoid", + App::Prop_None, + "Radius in local Y-direction\nIf zero, it is equal to Radius2" + ); Radius3.setConstraints(&quantityRangeZero); - ADD_PROPERTY_TYPE(Angle1,(-90.0f),"Ellipsoid",App::Prop_None,"The angle of the ellipsoid"); + ADD_PROPERTY_TYPE(Angle1, (-90.0f), "Ellipsoid", App::Prop_None, "The angle of the ellipsoid"); Angle1.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle2,(90.0f),"Ellipsoid",App::Prop_None,"The angle of the ellipsoid"); + ADD_PROPERTY_TYPE(Angle2, (90.0f), "Ellipsoid", App::Prop_None, "The angle of the ellipsoid"); Angle2.setConstraints(&angleRangeV); - ADD_PROPERTY_TYPE(Angle3,(360.0f),"Ellipsoid",App::Prop_None,"The angle of the ellipsoid"); + ADD_PROPERTY_TYPE(Angle3, (360.0f), "Ellipsoid", App::Prop_None, "The angle of the ellipsoid"); Angle3.setConstraints(&angleRangeU); primitiveType = FeaturePrimitive::Ellipsoid; @@ -420,38 +477,47 @@ Ellipsoid::Ellipsoid() App::DocumentObjectExecReturn* Ellipsoid::execute() { // Build a sphere - if (Radius1.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of ellipsoid too small")); - if (Radius2.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of ellipsoid too small")); + if (Radius1.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of ellipsoid too small") + ); + } + if (Radius2.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of ellipsoid too small") + ); + } try { - gp_Pnt pnt(0.0,0.0,0.0); - gp_Dir dir(0.0,0.0,1.0); - gp_Ax2 ax2(pnt,dir); - BRepPrimAPI_MakeSphere mkSphere(ax2, - Radius2.getValue(), - Base::toRadians(Angle1.getValue()), - Base::toRadians(Angle2.getValue()), - Base::toRadians(Angle3.getValue())); + gp_Pnt pnt(0.0, 0.0, 0.0); + gp_Dir dir(0.0, 0.0, 1.0); + gp_Ax2 ax2(pnt, dir); + BRepPrimAPI_MakeSphere mkSphere( + ax2, + Radius2.getValue(), + Base::toRadians(Angle1.getValue()), + Base::toRadians(Angle2.getValue()), + Base::toRadians(Angle3.getValue()) + ); Standard_Real scaleX = 1.0; - Standard_Real scaleZ = Radius1.getValue()/Radius2.getValue(); + Standard_Real scaleZ = Radius1.getValue() / Radius2.getValue(); // issue #1798: A third radius has been introduced. To be backward // compatible if Radius3 is 0.0 (default) it's handled to be the same // as Radius2 Standard_Real scaleY = 1.0; - if (Radius3.getValue() >= Precision::Confusion()) - scaleY = Radius3.getValue()/Radius2.getValue(); + if (Radius3.getValue() >= Precision::Confusion()) { + scaleY = Radius3.getValue() / Radius2.getValue(); + } gp_GTrsf mat; - mat.SetValue(1,1,scaleX); - mat.SetValue(2,1,0.0); - mat.SetValue(3,1,0.0); - mat.SetValue(1,2,0.0); - mat.SetValue(2,2,scaleY); - mat.SetValue(3,2,0.0); - mat.SetValue(1,3,0.0); - mat.SetValue(2,3,0.0); - mat.SetValue(3,3,scaleZ); + mat.SetValue(1, 1, scaleX); + mat.SetValue(2, 1, 0.0); + mat.SetValue(3, 1, 0.0); + mat.SetValue(1, 2, 0.0); + mat.SetValue(2, 2, scaleY); + mat.SetValue(3, 2, 0.0); + mat.SetValue(1, 3, 0.0); + mat.SetValue(2, 3, 0.0); + mat.SetValue(3, 3, scaleZ); BRepBuilderAPI_GTransform mkTrsf(mkSphere.Shape(), mat); return FeaturePrimitive::execute(mkTrsf.Shape()); } @@ -464,18 +530,24 @@ App::DocumentObjectExecReturn* Ellipsoid::execute() short int Ellipsoid::mustExecute() const { - if (Radius1.isTouched()) + if (Radius1.isTouched()) { return 1; - if (Radius2.isTouched()) + } + if (Radius2.isTouched()) { return 1; - if (Radius3.isTouched()) + } + if (Radius3.isTouched()) { return 1; - if (Angle1.isTouched()) + } + if (Angle1.isTouched()) { return 1; - if (Angle2.isTouched()) + } + if (Angle2.isTouched()) { return 1; - if (Angle3.isTouched()) + } + if (Angle3.isTouched()) { return 1; + } return FeaturePrimitive::mustExecute(); } @@ -488,15 +560,15 @@ PROPERTY_SOURCE(PartDesign::Torus, PartDesign::FeaturePrimitive) Torus::Torus() { - ADD_PROPERTY_TYPE(Radius1,(10.0),"Torus",App::Prop_None,"Radius in local XY-plane"); + ADD_PROPERTY_TYPE(Radius1, (10.0), "Torus", App::Prop_None, "Radius in local XY-plane"); Radius1.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Radius2,(2.0),"Torus",App::Prop_None,"Radius in local XZ-plane"); + ADD_PROPERTY_TYPE(Radius2, (2.0), "Torus", App::Prop_None, "Radius in local XZ-plane"); Radius2.setConstraints(&quantityRange); - ADD_PROPERTY_TYPE(Angle1,(-180.0),"Torus",App::Prop_None,"The angle of the torus"); + ADD_PROPERTY_TYPE(Angle1, (-180.0), "Torus", App::Prop_None, "The angle of the torus"); Angle1.setConstraints(&torusRangeV); - ADD_PROPERTY_TYPE(Angle2,(180.0),"Torus",App::Prop_None,"The angle of the torus"); + ADD_PROPERTY_TYPE(Angle2, (180.0), "Torus", App::Prop_None, "The angle of the torus"); Angle2.setConstraints(&torusRangeV); - ADD_PROPERTY_TYPE(Angle3,(360.0),"Torus",App::Prop_None,"The angle of the torus"); + ADD_PROPERTY_TYPE(Angle3, (360.0), "Torus", App::Prop_None, "The angle of the torus"); Angle3.setConstraints(&angleRangeU); primitiveType = FeaturePrimitive::Torus; @@ -504,10 +576,16 @@ Torus::Torus() App::DocumentObjectExecReturn* Torus::execute() { - if (Radius1.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of torus too small")); - if (Radius2.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Radius of torus too small")); + if (Radius1.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of torus too small") + ); + } + if (Radius2.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Radius of torus too small") + ); + } try { // https://forum.freecad.org/viewtopic.php?f=3&t=52719 #if 0 @@ -519,11 +597,13 @@ App::DocumentObjectExecReturn* Torus::execute() return FeaturePrimitive::execute(mkTorus.Solid()); #else Part::TopoShape shape; - return FeaturePrimitive::execute(shape.makeTorus(Radius1.getValue(), - Radius2.getValue(), - Angle1.getValue(), - Angle2.getValue(), - Angle3.getValue())); + return FeaturePrimitive::execute(shape.makeTorus( + Radius1.getValue(), + Radius2.getValue(), + Angle1.getValue(), + Angle2.getValue(), + Angle3.getValue() + )); #endif } catch (Standard_Failure& e) { @@ -535,16 +615,21 @@ App::DocumentObjectExecReturn* Torus::execute() short int Torus::mustExecute() const { - if (Radius1.isTouched()) + if (Radius1.isTouched()) { return 1; - if (Radius2.isTouched()) + } + if (Radius2.isTouched()) { return 1; - if (Angle1.isTouched()) + } + if (Angle1.isTouched()) { return 1; - if (Angle2.isTouched()) + } + if (Angle2.isTouched()) { return 1; - if (Angle3.isTouched()) + } + if (Angle3.isTouched()) { return 1; + } return FeaturePrimitive::mustExecute(); } @@ -557,8 +642,20 @@ PROPERTY_SOURCE(PartDesign::Prism, PartDesign::FeaturePrimitive) Prism::Prism() { - ADD_PROPERTY_TYPE(Polygon, (6.0), "Prism", App::Prop_None, "Number of sides in the polygon, of the prism"); - ADD_PROPERTY_TYPE(Circumradius, (2.0), "Prism", App::Prop_None, "Circumradius (centre to vertex) of the polygon, of the prism"); + ADD_PROPERTY_TYPE( + Polygon, + (6.0), + "Prism", + App::Prop_None, + "Number of sides in the polygon, of the prism" + ); + ADD_PROPERTY_TYPE( + Circumradius, + (2.0), + "Prism", + App::Prop_None, + "Circumradius (centre to vertex) of the polygon, of the prism" + ); ADD_PROPERTY_TYPE(Height, (10.0f), "Prism", App::Prop_None, "The height of the prism"); Part::PrismExtension::initExtension(this); @@ -569,26 +666,35 @@ Prism::Prism() App::DocumentObjectExecReturn* Prism::execute() { // Build a prism - if (Polygon.getValue() < 3) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Polygon of prism is invalid, must have 3 or more sides")); - if (Circumradius.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Circumradius of the polygon, of the prism, is too small")); - if (Height.getValue() < Precision::Confusion()) - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Height of prism is too small")); + if (Polygon.getValue() < 3) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Polygon of prism is invalid, must have 3 or more sides") + ); + } + if (Circumradius.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Circumradius of the polygon, of the prism, is too small") + ); + } + if (Height.getValue() < Precision::Confusion()) { + return new App::DocumentObjectExecReturn( + QT_TRANSLATE_NOOP("Exception", "Height of prism is too small") + ); + } try { long nodes = Polygon.getValue(); Base::Matrix4D mat; - mat.rotZ(Base::toRadians(360.0/nodes)); + mat.rotZ(Base::toRadians(360.0 / nodes)); // create polygon BRepBuilderAPI_MakePolygon mkPoly; - Base::Vector3d v(Circumradius.getValue(),0,0); - for (long i=0; igetBaseObject(); - if (base) + if (base) { return base->getPyObject(); - else + } + else { return Py::new_reference_to(Py::None()); + } } diff --git a/src/Mod/PartDesign/App/FeatureRefine.cpp b/src/Mod/PartDesign/App/FeatureRefine.cpp index 3c25ec7568..61582216d0 100644 --- a/src/Mod/PartDesign/App/FeatureRefine.cpp +++ b/src/Mod/PartDesign/App/FeatureRefine.cpp @@ -40,11 +40,13 @@ PROPERTY_SOURCE(PartDesign::FeatureRefine, PartDesign::Feature) FeatureRefine::FeatureRefine() { - ADD_PROPERTY_TYPE(Refine, - (0), - "Part Design", - (App::PropertyType)(App::Prop_None), - "Refine shape (clean up redundant edges) after operations"); + ADD_PROPERTY_TYPE( + Refine, + (0), + "Part Design", + (App::PropertyType)(App::Prop_None), + "Refine shape (clean up redundant edges) after operations" + ); // init Refine property Base::Reference hGrp = App::GetApplication() .GetUserParameter() @@ -75,8 +77,10 @@ bool FeatureRefine::onlyHaveRefined() Shape.setValue(result); return true; } -TopoShape FeatureRefine::refineShapeIfActive(const TopoShape& oldShape, - const RefineErrorPolicy onError) const +TopoShape FeatureRefine::refineShapeIfActive( + const TopoShape& oldShape, + const RefineErrorPolicy onError +) const { if (!this->Refine.getValue()) { return oldShape; @@ -87,8 +91,7 @@ TopoShape FeatureRefine::refineShapeIfActive(const TopoShape& oldShape, } catch (Standard_Failure& err) { if (onError == RefineErrorPolicy::Warn) { - Base::Console().warning( - fmt::format("Refine failed: {}", err.GetMessageString()).c_str()); + Base::Console().warning(fmt::format("Refine failed: {}", err.GetMessageString()).c_str()); } else { throw; diff --git a/src/Mod/PartDesign/App/FeatureRefine.h b/src/Mod/PartDesign/App/FeatureRefine.h index 673afd78bb..4349986736 100644 --- a/src/Mod/PartDesign/App/FeatureRefine.h +++ b/src/Mod/PartDesign/App/FeatureRefine.h @@ -31,13 +31,13 @@ namespace PartDesign { -class PartDesignExport FeatureRefine : public PartDesign::Feature +class PartDesignExport FeatureRefine: public PartDesign::Feature { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureRefine); public: - - enum class RefineErrorPolicy { + enum class RefineErrorPolicy + { Raise = 0, Warn }; @@ -47,7 +47,7 @@ public: App::PropertyBool Refine; protected: - //store the shape before refinement + // store the shape before refinement TopoShape rawShape; @@ -61,12 +61,15 @@ protected: * computation is necessary. */ bool onlyHaveRefined(); - TopoShape refineShapeIfActive(const TopoShape& oldShape, const RefineErrorPolicy onError = RefineErrorPolicy::Warn) const; + TopoShape refineShapeIfActive( + const TopoShape& oldShape, + const RefineErrorPolicy onError = RefineErrorPolicy::Warn + ) const; }; using FeatureRefinePython = App::FeaturePythonT; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FeatureRefine_H +#endif // PARTDESIGN_FeatureRefine_H diff --git a/src/Mod/PartDesign/App/FeatureRevolution.cpp b/src/Mod/PartDesign/App/FeatureRevolution.cpp index 9133bdda23..2df41a8d47 100644 --- a/src/Mod/PartDesign/App/FeatureRevolution.cpp +++ b/src/Mod/PartDesign/App/FeatureRevolution.cpp @@ -21,13 +21,13 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include @@ -38,15 +38,17 @@ using namespace PartDesign; -namespace PartDesign { +namespace PartDesign +{ /* TRANSLATOR PartDesign::Revolution */ -const char* Revolution::TypeEnums[]= {"Angle", "UpToLast", "UpToFirst", "UpToFace", "TwoAngles", nullptr}; +const char* Revolution::TypeEnums[] + = {"Angle", "UpToLast", "UpToFirst", "UpToFace", "TwoAngles", nullptr}; PROPERTY_SOURCE(PartDesign::Revolution, PartDesign::ProfileBased) -const App::PropertyAngle::Constraints Revolution::floatAngle = { 0.0, 360.0, 1.0 }; +const App::PropertyAngle::Constraints Revolution::floatAngle = {0.0, 360.0, 1.0}; Revolution::Revolution() { @@ -54,32 +56,48 @@ Revolution::Revolution() ADD_PROPERTY_TYPE(Type, (0L), "Revolution", App::Prop_None, "Revolution type"); Type.setEnums(TypeEnums); - ADD_PROPERTY_TYPE(Base, (Base::Vector3d(0.0,0.0,0.0)), "Revolution", App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), "Base"); - ADD_PROPERTY_TYPE(Axis, (Base::Vector3d(0.0,1.0,0.0)), "Revolution", App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), "Axis"); + ADD_PROPERTY_TYPE( + Base, + (Base::Vector3d(0.0, 0.0, 0.0)), + "Revolution", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), + "Base" + ); + ADD_PROPERTY_TYPE( + Axis, + (Base::Vector3d(0.0, 1.0, 0.0)), + "Revolution", + App::PropertyType(App::Prop_ReadOnly | App::Prop_Hidden), + "Axis" + ); ADD_PROPERTY_TYPE(Angle, (360.0), "Revolution", App::Prop_None, "Angle"); ADD_PROPERTY_TYPE(Angle2, (0.0), "Revolution", App::Prop_None, "Revolution length in 2nd direction"); ADD_PROPERTY_TYPE(UpToFace, (nullptr), "Revolution", App::Prop_None, "Face where revolution will end"); Angle.setConstraints(&floatAngle); Angle2.setConstraints(&floatAngle); - ADD_PROPERTY_TYPE(ReferenceAxis, (nullptr), "Revolution", (App::Prop_None), "Reference axis of revolution"); + ADD_PROPERTY_TYPE( + ReferenceAxis, + (nullptr), + "Revolution", + (App::Prop_None), + "Reference axis of revolution" + ); } short Revolution::mustExecute() const { - if (Placement.isTouched() || - ReferenceAxis.isTouched() || - Axis.isTouched() || - Base.isTouched() || - UpToFace.isTouched() || - Angle.isTouched() || - Angle2.isTouched()) + if (Placement.isTouched() || ReferenceAxis.isTouched() || Axis.isTouched() || Base.isTouched() + || UpToFace.isTouched() || Angle.isTouched() || Angle2.isTouched()) { return 1; + } return ProfileBased::mustExecute(); } App::DocumentObjectExecReturn* Revolution::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } constexpr double maxDegree = 360.0; @@ -89,19 +107,22 @@ App::DocumentObjectExecReturn* Revolution::execute() double angleDeg = Angle.getValue(); if (angleDeg > maxDegree) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Angle of revolution too large")); + QT_TRANSLATE_NOOP("Exception", "Angle of revolution too large") + ); } double angle = Base::toRadians(angleDeg); if (angle < Precision::Angular() && method == RevolMethod::Angle) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Angle of revolution too small")); + QT_TRANSLATE_NOOP("Exception", "Angle of revolution too small") + ); } double angle2 = Base::toRadians(Angle2.getValue()); if (std::fabs(angle + angle2) < Precision::Angular() && method == RevolMethod::TwoAngles) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Angles of revolution nullify each other")); + QT_TRANSLATE_NOOP("Exception", "Angles of revolution nullify each other") + ); } TopoShape sketchshape = getTopoShapeVerifiedFace(); @@ -131,14 +152,16 @@ App::DocumentObjectExecReturn* Revolution::execute() if (v.IsNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Reference axis is invalid")); + QT_TRANSLATE_NOOP("Exception", "Reference axis is invalid") + ); } gp_Dir dir(v.x, v.y, v.z); if (sketchshape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Creating a face from sketch failed")); + QT_TRANSLATE_NOOP("Exception", "Creating a face from sketch failed") + ); } this->positionByPrevious(); @@ -154,7 +177,8 @@ App::DocumentObjectExecReturn* Revolution::execute() for (; xp.More(); xp.Next()) { if (checkLineCrossesFace(gp_Lin(pnt, dir), TopoDS::Face(xp.Current()))) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Revolve axis intersects the sketch")); + QT_TRANSLATE_NOOP("Exception", "Revolve axis intersects the sketch") + ); } } @@ -164,8 +188,8 @@ App::DocumentObjectExecReturn* Revolution::execute() try { supportface = getSupportFace(); } - catch(...) { - //do nothing, null shape is handle below + catch (...) { + // do nothing, null shape is handle below } supportface.move(invObjLoc); @@ -178,7 +202,8 @@ App::DocumentObjectExecReturn* Revolution::execute() } else { throw Base::RuntimeError( - "ProfileBased: Revolution up to first/last is not yet supported"); + "ProfileBased: Revolution up to first/last is not yet supported" + ); } if (Reversed.getValue()) { @@ -191,14 +216,16 @@ App::DocumentObjectExecReturn* Revolution::execute() } try { - result = base.makeElementRevolution(base, - TopoDS::Face(sketchshape.getShape()), - gp_Ax1(pnt, dir), - TopoDS::Face(supportface.getShape()), - TopoDS::Face(upToFace.getShape()), - nullptr, - Part::RevolMode::FuseWithBase, - Standard_True); + result = base.makeElementRevolution( + base, + TopoDS::Face(sketchshape.getShape()), + gp_Ax1(pnt, dir), + TopoDS::Face(supportface.getShape()), + TopoDS::Face(upToFace.getShape()), + nullptr, + Part::RevolMode::FuseWithBase, + Standard_True + ); } catch (Standard_Failure&) { return new App::DocumentObjectExecReturn("Could not revolve the sketch!"); @@ -207,14 +234,16 @@ App::DocumentObjectExecReturn* Revolution::execute() else { bool midplane = Midplane.getValue(); bool reversed = Reversed.getValue(); - generateRevolution(result, - sketchshape, - gp_Ax1(pnt, dir), - angle, - angle2, - midplane, - reversed, - method); + generateRevolution( + result, + sketchshape, + gp_Ax1(pnt, dir), + angle, + angle2, + midplane, + reversed, + method + ); } if (!result.isNull()) { @@ -231,14 +260,18 @@ App::DocumentObjectExecReturn* Revolution::execute() result = refineShapeIfActive(result); } if (!isSingleSolidRuleSatisfied(result.getShape())) { - return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP("Exception", "Result has multiple solids: enable 'Allow Compound' in the active body.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Result has multiple solids: enable 'Allow Compound' in the active body." + )); } result = getSolid(result); this->Shape.setValue(result); } else { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Could not revolve the sketch!")); + QT_TRANSLATE_NOOP("Exception", "Could not revolve the sketch!") + ); } // eventually disable some settings that are not valid for the current method @@ -249,10 +282,11 @@ App::DocumentObjectExecReturn* Revolution::execute() catch (Standard_Failure& e) { if (std::string(e.GetMessageString()) == "TopoDS::Face") { - return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", - "Could not create face from sketch.\n" - "Intersecting sketch entities in a sketch are not allowed.")); + return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( + "Exception", + "Could not create face from sketch.\n" + "Intersecting sketch entities in a sketch are not allowed." + )); } else { return new App::DocumentObjectExecReturn(e.GetMessageString()); @@ -267,7 +301,8 @@ bool Revolution::suggestReversed() { try { updateAxis(); - } catch (const Base::Exception&) { + } + catch (const Base::Exception&) { return false; } @@ -276,44 +311,53 @@ bool Revolution::suggestReversed() void Revolution::updateAxis() { - App::DocumentObject *pcReferenceAxis = ReferenceAxis.getValue(); - const std::vector &subReferenceAxis = ReferenceAxis.getSubValues(); + App::DocumentObject* pcReferenceAxis = ReferenceAxis.getValue(); + const std::vector& subReferenceAxis = ReferenceAxis.getSubValues(); Base::Vector3d base; Base::Vector3d dir; getAxis(pcReferenceAxis, subReferenceAxis, base, dir, ForbiddenAxis::NotParallelWithNormal); - Base.setValue(base.x,base.y,base.z); - Axis.setValue(dir.x,dir.y,dir.z); + Base.setValue(base.x, base.y, base.z); + Axis.setValue(dir.x, dir.y, dir.z); } Revolution::RevolMethod Revolution::methodFromString(const std::string& methodStr) { - if (methodStr == "Angle") + if (methodStr == "Angle") { return RevolMethod::Angle; - if (methodStr == "UpToLast") + } + if (methodStr == "UpToLast") { return RevolMethod::ToLast; - if (methodStr == "ThroughAll") + } + if (methodStr == "ThroughAll") { return RevolMethod::ThroughAll; - if (methodStr == "UpToFirst") + } + if (methodStr == "UpToFirst") { return RevolMethod::ToFirst; - if (methodStr == "UpToFace") + } + if (methodStr == "UpToFace") { return RevolMethod::ToFace; - if (methodStr == "TwoAngles") + } + if (methodStr == "TwoAngles") { return RevolMethod::TwoAngles; + } throw Base::ValueError("Revolution:: No such method"); } -void Revolution::generateRevolution(TopoShape& revol, - const TopoShape& sketchshape, - const gp_Ax1& axis, - const double angle, - const double angle2, - const bool midplane, - const bool reversed, - RevolMethod method) +void Revolution::generateRevolution( + TopoShape& revol, + const TopoShape& sketchshape, + const gp_Ax1& axis, + const double angle, + const double angle2, + const bool midplane, + const bool reversed, + RevolMethod method +) { - if (method == RevolMethod::Angle || method == RevolMethod::TwoAngles || method == RevolMethod::ThroughAll) { + if (method == RevolMethod::Angle || method == RevolMethod::TwoAngles + || method == RevolMethod::ThroughAll) { double angleTotal = angle; double angleOffset = 0.; @@ -330,8 +374,9 @@ void Revolution::generateRevolution(TopoShape& revol, angleOffset = -angle / 2; } - if (fabs(angleTotal) < Precision::Angular()) + if (fabs(angleTotal) < Precision::Angular()) { throw Base::ValueError("Cannot create a revolution with zero angle."); + } gp_Ax1 revolAx(axis); if (reversed) { @@ -350,28 +395,41 @@ void Revolution::generateRevolution(TopoShape& revol, // BRepPrimAPI is the only option that allows use of this shape for patterns. // See https://forum.freecadweb.org/viewtopic.php?f=8&t=70185&p=611673#p611673. revol = from; - revol = revol.makeElementRevolve(revolAx,angleTotal); + revol = revol.makeElementRevolve(revolAx, angleTotal); revol.Tag = -getID(); - } else { + } + else { std::stringstream str; str << "ProfileBased: Internal error: Unknown method for generateRevolution()"; throw Base::RuntimeError(str.str()); } } -void Revolution::generateRevolution(TopoShape& revol, - const TopoShape& baseshape, - const TopoDS_Shape& profileshape, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const gp_Ax1& axis, - RevolMethod method, - RevolMode Mode, - Standard_Boolean Modify) +void Revolution::generateRevolution( + TopoShape& revol, + const TopoShape& baseshape, + const TopoDS_Shape& profileshape, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const gp_Ax1& axis, + RevolMethod method, + RevolMode Mode, + Standard_Boolean Modify +) { - if (method == RevolMethod::ToFirst || method == RevolMethod::ToFace || method == RevolMethod::ToLast) { - revol = revol.makeElementRevolution(baseshape, profileshape, axis, supportface, uptoface, nullptr, - static_cast(Mode), Modify, nullptr); + if (method == RevolMethod::ToFirst || method == RevolMethod::ToFace + || method == RevolMethod::ToLast) { + revol = revol.makeElementRevolution( + baseshape, + profileshape, + axis, + supportface, + uptoface, + nullptr, + static_cast(Mode), + Modify, + nullptr + ); } else { std::stringstream str; @@ -421,6 +479,4 @@ void Revolution::updateProperties(RevolMethod method) UpToFace.setReadOnly(!isUpToFaceEnabled); } -} - - +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureRevolution.h b/src/Mod/PartDesign/App/FeatureRevolution.h index 95c3d64edd..a1bbf7ce99 100644 --- a/src/Mod/PartDesign/App/FeatureRevolution.h +++ b/src/Mod/PartDesign/App/FeatureRevolution.h @@ -30,7 +30,7 @@ namespace PartDesign { -class PartDesignExport Revolution : public ProfileBased +class PartDesignExport Revolution: public ProfileBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Revolution); @@ -40,27 +40,28 @@ public: App::PropertyEnumeration Type; App::PropertyVector Base; App::PropertyVector Axis; - App::PropertyAngle Angle; - App::PropertyAngle Angle2; + App::PropertyAngle Angle; + App::PropertyAngle Angle2; /** if this property is set to a valid link, both Axis and Base properties * are calculated according to the linked line - */ + */ App::PropertyLinkSub ReferenceAxis; /** @name methods override feature */ //@{ /** Recalculate the feature - * Revolves the Sketch around the given Axis (with basepoint Base) - * The angle of the revolution is given by Angle. - * If Midplane is true, then the revolution will extend for half of Angle on both sides of the sketch plane. - * If Reversed is true then the direction of revolution will be reversed. - * The created material will be fused with the sketch support (if there is one) - */ - App::DocumentObjectExecReturn *execute() override; + * Revolves the Sketch around the given Axis (with basepoint Base) + * The angle of the revolution is given by Angle. + * If Midplane is true, then the revolution will extend for half of Angle on both sides of the + * sketch plane. If Reversed is true then the direction of revolution will be reversed. The + * created material will be fused with the sketch support (if there is one) + */ + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderRevolution"; } //@} @@ -68,7 +69,8 @@ public: /// suggests a value for Reversed flag so that material is always added to the support bool suggestReversed(); - enum class RevolMethod { + enum class RevolMethod + { Angle, ThroughAll, ToLast = ThroughAll, @@ -84,7 +86,8 @@ protected: static const App::PropertyAngle::Constraints floatAngle; // See BRepFeat_MakeRevol - enum RevolMode { + enum RevolMode + { CutFromBase = 0, FuseWithBase = 1, None = 2 @@ -95,28 +98,32 @@ protected: /** * Generates a revolution of the input sketchshape and stores it in the given \a revol. */ - void generateRevolution(TopoShape& revol, - const TopoShape& sketchshape, - const gp_Ax1& ax1, - const double angle, - const double angle2, - const bool midplane, - const bool reversed, - RevolMethod method); + void generateRevolution( + TopoShape& revol, + const TopoShape& sketchshape, + const gp_Ax1& ax1, + const double angle, + const double angle2, + const bool midplane, + const bool reversed, + RevolMethod method + ); /** * Generates a revolution of the input \a profileshape. * It will be a stand-alone solid created with BRepFeat_MakeRevol. */ - void generateRevolution(TopoShape& revol, - const TopoShape& baseshape, - const TopoDS_Shape& profileshape, - const TopoDS_Face& supportface, - const TopoDS_Face& uptoface, - const gp_Ax1& ax1, - RevolMethod method, - RevolMode Mode, - Standard_Boolean Modify); + void generateRevolution( + TopoShape& revol, + const TopoShape& baseshape, + const TopoDS_Shape& profileshape, + const TopoDS_Face& supportface, + const TopoDS_Face& uptoface, + const gp_Ax1& ax1, + RevolMethod method, + RevolMode Mode, + Standard_Boolean Modify + ); /** * Disables settings that are not valid for the current method @@ -127,7 +134,7 @@ private: static const char* TypeEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PART_Revolution_H +#endif // PART_Revolution_H diff --git a/src/Mod/PartDesign/App/FeatureScaled.cpp b/src/Mod/PartDesign/App/FeatureScaled.cpp index eb2ecf02e0..2dd9b18945 100644 --- a/src/Mod/PartDesign/App/FeatureScaled.cpp +++ b/src/Mod/PartDesign/App/FeatureScaled.cpp @@ -52,8 +52,7 @@ short Scaled::mustExecute() const return Transformed::mustExecute(); } -const std::list -Scaled::getTransformations(const std::vector originals) +const std::list Scaled::getTransformations(const std::vector originals) { double const factor = Factor.getValue(); if (factor < Precision::Confusion()) { diff --git a/src/Mod/PartDesign/App/FeatureScaled.h b/src/Mod/PartDesign/App/FeatureScaled.h index f0393e7d73..5d6d942aa8 100644 --- a/src/Mod/PartDesign/App/FeatureScaled.h +++ b/src/Mod/PartDesign/App/FeatureScaled.h @@ -61,8 +61,9 @@ public: */ // Note: We can't just use the Originals property because this will fail if the Scaled feature // is being used inside a MultiTransform feature - const std::list - getTransformations(const std::vector originals) override; + const std::list getTransformations( + const std::vector originals + ) override; }; } // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureSketchBased.cpp b/src/Mod/PartDesign/App/FeatureSketchBased.cpp index 438a548781..e67936a917 100644 --- a/src/Mod/PartDesign/App/FeatureSketchBased.cpp +++ b/src/Mod/PartDesign/App/FeatureSketchBased.cpp @@ -20,34 +20,34 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -61,7 +61,7 @@ #include "Mod/Part/App/Geometry.h" -FC_LOG_LEVEL_INIT("PartDesign",true,true); +FC_LOG_LEVEL_INIT("PartDesign", true, true); using namespace PartDesign; @@ -72,23 +72,49 @@ ProfileBased::ProfileBased() ADD_PROPERTY_TYPE(Profile, (nullptr), "SketchBased", App::Prop_None, "Reference to sketch"); ADD_PROPERTY_TYPE(Midplane, (0), "SketchBased", App::Prop_None, "Extrude symmetric to sketch face"); ADD_PROPERTY_TYPE(Reversed, (0), "SketchBased", App::Prop_None, "Reverse extrusion direction"); - ADD_PROPERTY_TYPE(UpToFace, (nullptr), "Side1", (App::PropertyType)(App::Prop_None), "Face where feature will end"); - ADD_PROPERTY_TYPE(UpToShape, (nullptr), "Side1", (App::PropertyType)(App::Prop_None), "Shape where feature will end"); - ADD_PROPERTY_TYPE(UpToFace2, (nullptr), "Side2", (App::PropertyType)(App::Prop_None), "Face where feature will end"); - ADD_PROPERTY_TYPE(UpToShape2, (nullptr), "Side2", (App::PropertyType)(App::Prop_None), "Shape where feature will end"); - ADD_PROPERTY_TYPE(AllowMultiFace, (false), "SketchBased", App::Prop_None, "Allow multiple faces in profile"); + ADD_PROPERTY_TYPE( + UpToFace, + (nullptr), + "Side1", + (App::PropertyType)(App::Prop_None), + "Face where feature will end" + ); + ADD_PROPERTY_TYPE( + UpToShape, + (nullptr), + "Side1", + (App::PropertyType)(App::Prop_None), + "Shape where feature will end" + ); + ADD_PROPERTY_TYPE( + UpToFace2, + (nullptr), + "Side2", + (App::PropertyType)(App::Prop_None), + "Face where feature will end" + ); + ADD_PROPERTY_TYPE( + UpToShape2, + (nullptr), + "Side2", + (App::PropertyType)(App::Prop_None), + "Shape where feature will end" + ); + ADD_PROPERTY_TYPE( + AllowMultiFace, + (false), + "SketchBased", + App::Prop_None, + "Allow multiple faces in profile" + ); } short ProfileBased::mustExecute() const { - if (Profile.isTouched() || - Midplane.isTouched() || - Reversed.isTouched() || - UpToFace.isTouched() || - UpToFace2.isTouched() || - UpToShape.isTouched() || - UpToShape2.isTouched()) + if (Profile.isTouched() || Midplane.isTouched() || Reversed.isTouched() || UpToFace.isTouched() + || UpToFace2.isTouched() || UpToShape.isTouched() || UpToShape2.isTouched()) { return 1; + } return PartDesign::FeatureAddSub::mustExecute(); } @@ -104,7 +130,7 @@ void ProfileBased::positionByPrevious() this->Placement.setValue(feat->Placement.getValue()); } else { - //no base. Use either Sketch support's placement, or sketch's placement itself. + // no base. Use either Sketch support's placement, or sketch's placement itself. Part::Part2DObject* sketch = getVerifiedSketch(); App::DocumentObject* support = sketch->AttachmentSupport.getValue(); if (support && support->isDerivedFrom()) { @@ -129,7 +155,8 @@ void ProfileBased::transformPlacement(const Base::Placement& transform) positionByPrevious(); } -Part::Part2DObject* ProfileBased::getVerifiedSketch(bool silent) const { +Part::Part2DObject* ProfileBased::getVerifiedSketch(bool silent) const +{ App::DocumentObject* result = Profile.getValue(); const char* err = nullptr; @@ -150,7 +177,8 @@ Part::Part2DObject* ProfileBased::getVerifiedSketch(bool silent) const { return static_cast(result); } -Part::Feature* ProfileBased::getVerifiedObject(bool silent) const { +Part::Feature* ProfileBased::getVerifiedObject(bool silent) const +{ App::DocumentObject* result = Profile.getValue(); const char* err = nullptr; @@ -159,8 +187,9 @@ Part::Feature* ProfileBased::getVerifiedObject(bool silent) const { err = "No object linked"; } else { - if (!result->isDerivedFrom()) + if (!result->isDerivedFrom()) { err = "Linked object is not a Sketch, Part2DObject or Feature"; + } } if (!silent && err) { @@ -169,11 +198,13 @@ Part::Feature* ProfileBased::getVerifiedObject(bool silent) const { return static_cast(result); } -TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, - [[maybe_unused]]bool doFit, // TODO: Remove parameter - bool allowOpen, - const App::DocumentObject* profile, - const std::vector& _subs) const +TopoShape ProfileBased::getTopoShapeVerifiedFace( + bool silent, + [[maybe_unused]] bool doFit, // TODO: Remove parameter + bool allowOpen, + const App::DocumentObject* profile, + const std::vector& _subs +) const { auto obj = profile ? profile : Profile.getValue(); if (!obj || !obj->getNameInDocument()) { @@ -187,21 +218,27 @@ TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, TopoShape shape; if (AllowMultiFace.getValue()) { if (subs.empty()) { - shape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + shape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); } else { std::vector shapes; for (auto& sub : subs) { - auto subshape = Part::Feature::getTopoShape(obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sub.c_str()); + auto subshape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sub.c_str() + ); if (subshape.isNull()) { - FC_THROWM(Base::CADKernelError, - "Sub shape not found: " << obj->getFullName() << "." << sub); + FC_THROWM( + Base::CADKernelError, + "Sub shape not found: " << obj->getFullName() << "." << sub + ); } shapes.push_back(subshape); } @@ -215,11 +252,12 @@ TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, sub = subs[0]; } } - shape = Part::Feature::getTopoShape(obj, - (sub.empty() ? Part::ShapeOption::NoFlag : Part::ShapeOption::NeedSubElement) - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sub.c_str()); + shape = Part::Feature::getTopoShape( + obj, + (sub.empty() ? Part::ShapeOption::NoFlag : Part::ShapeOption::NeedSubElement) + | Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform, + sub.c_str() + ); } if (shape.isNull()) { if (silent) { @@ -250,7 +288,8 @@ TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, openshape.makeElementCompound( openwires, nullptr, - TopoShape ::SingleShapeCompoundCreationPolicy::returnShape); + TopoShape ::SingleShapeCompoundCreationPolicy::returnShape + ); if (wires.empty()) { shape = TopoShape(); } @@ -258,7 +297,8 @@ TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, shape.makeElementCompound( wires, nullptr, - TopoShape ::SingleShapeCompoundCreationPolicy::returnShape); + TopoShape ::SingleShapeCompoundCreationPolicy::returnShape + ); } } } @@ -302,8 +342,7 @@ TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, } } if (count > 1) { - if (AllowMultiFace.getValue() - || obj->isDerivedFrom()) { + if (AllowMultiFace.getValue() || obj->isDerivedFrom()) { return shape; } FC_WARN("Found more than one face from profile"); @@ -325,7 +364,8 @@ TopoShape ProfileBased::getTopoShapeVerifiedFace(bool silent, } // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. -TopoDS_Shape ProfileBased::getVerifiedFace(bool silent) const { +TopoDS_Shape ProfileBased::getVerifiedFace(bool silent) const +{ App::DocumentObject* result = Profile.getValue(); const char* err = nullptr; @@ -337,25 +377,32 @@ TopoDS_Shape ProfileBased::getVerifiedFace(bool silent) const { else if (AllowMultiFace.getValue()) { try { auto shape = getProfileShape(); - if (shape.isNull()) + if (shape.isNull()) { err = "Linked shape object is empty"; + } else { auto faces = shape.getSubTopoShapes(TopAbs_FACE); if (faces.empty()) { - if (!shape.hasSubShape(TopAbs_WIRE)) + if (!shape.hasSubShape(TopAbs_WIRE)) { shape = shape.makeWires(); - if (shape.hasSubShape(TopAbs_WIRE)) + } + if (shape.hasSubShape(TopAbs_WIRE)) { shape = shape.makeFace(nullptr, "Part::FaceMakerBullseye"); - else + } + else { err = "Cannot make face from profile"; + } } - else if (faces.size() == 1) + else if (faces.size() == 1) { shape = faces.front(); - else + } + else { shape = TopoShape().makeCompound(faces); + } } - if (!err) + if (!err) { return shape.getShape(); + } } catch (Standard_Failure& e) { _err = e.GetMessageString(); @@ -369,31 +416,36 @@ TopoDS_Shape ProfileBased::getVerifiedFace(bool silent) const { return Part::FaceMakerCheese::makeFace(wires); } else if (result->isDerivedFrom()) { - if (Profile.getSubValues().empty()) + if (Profile.getSubValues().empty()) { err = "Linked object has no subshape specified"; + } else { const Part::TopoShape& shape = Profile.getValue()->Shape.getShape(); TopoDS_Shape sub = shape.getSubShape(Profile.getSubValues()[0].c_str()); - if (sub.ShapeType() == TopAbs_FACE) + if (sub.ShapeType() == TopAbs_FACE) { return TopoDS::Face(sub); + } else if (sub.ShapeType() == TopAbs_WIRE) { auto wire = TopoDS::Wire(sub); - if (!wire.Closed()) + if (!wire.Closed()) { err = "Linked wire is not closed"; + } else { BRepBuilderAPI_MakeFace mk(wire); mk.Build(); return TopoDS::Face(mk.Shape()); } } - else + else { err = "Linked Subshape cannot be used"; + } } } - else + else { err = "Linked object is neither Sketch, Part2DObject or Part::Feature"; + } } if (!silent && err) { @@ -409,14 +461,15 @@ TopoShape ProfileBased::getProfileShape(Part::ShapeOptions subShapeOptions) cons const auto& subs = Profile.getSubValues(); auto profile = Profile.getValue(); if (subs.empty()) { - shape = Part::Feature::getTopoShape(profile, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + shape = Part::Feature::getTopoShape( + profile, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); } else { std::vector shapes; for (auto& sub : subs) { - shapes.push_back(Part::Feature::getTopoShape(profile, - subShapeOptions, - sub.c_str())); + shapes.push_back(Part::Feature::getTopoShape(profile, subShapeOptions, sub.c_str())); } shape = TopoShape(shape.Tag).makeElementCompound(shapes); } @@ -428,24 +481,31 @@ TopoShape ProfileBased::getProfileShape(Part::ShapeOptions subShapeOptions) cons // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. -std::vector ProfileBased::getProfileWires() const { +std::vector ProfileBased::getProfileWires() const +{ std::vector result; - if (!Profile.getValue() || !Profile.getValue()->isDerivedFrom()) + if (!Profile.getValue() || !Profile.getValue()->isDerivedFrom()) { throw Base::TypeError("No valid profile linked"); - - TopoDS_Shape shape; - if (Profile.getValue()->isDerivedFrom()) - shape = Profile.getValue()->Shape.getValue(); - else { - if (Profile.getSubValues().empty()) - throw Base::ValueError("No valid subelement linked in Part::Feature"); - - shape = Profile.getValue()->Shape.getShape().getSubShape(Profile.getSubValues().front().c_str()); } - if (shape.IsNull()) + TopoDS_Shape shape; + if (Profile.getValue()->isDerivedFrom()) { + shape = Profile.getValue()->Shape.getValue(); + } + else { + if (Profile.getSubValues().empty()) { + throw Base::ValueError("No valid subelement linked in Part::Feature"); + } + + shape = Profile.getValue()->Shape.getShape().getSubShape( + Profile.getSubValues().front().c_str() + ); + } + + if (shape.IsNull()) { throw Base::ValueError("Linked shape object is empty"); + } // this is a workaround for an obscure OCC bug which leads to empty tessellations // for some faces. Making an explicit copy of the linked shape seems to fix it. @@ -453,15 +513,17 @@ std::vector ProfileBased::getProfileWires() const { // first time BRepBuilderAPI_Copy copy(shape); shape = copy.Shape(); - if (shape.IsNull()) + if (shape.IsNull()) { throw Base::ValueError("Linked shape object is empty"); + } TopExp_Explorer ex; for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next()) { result.push_back(TopoDS::Wire(ex.Current())); } - if (result.empty()) // there can be several wires + if (result.empty()) { // there can be several wires throw Base::ValueError("Linked shape object is not a wire"); + } return result; } @@ -567,11 +629,11 @@ TopoShape ProfileBased::getTopoShapeSupportFace() const const auto& Support = sketch->AttachmentSupport; App::DocumentObject* ref = Support.getValue(); shape = Part::Feature::getTopoShape( - ref, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - Support.getSubValues().empty() ? "" : Support.getSubValues()[0].c_str()); + ref, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + Support.getSubValues().empty() ? "" : Support.getSubValues()[0].c_str() + ); } if (!shape.isNull()) { if (shape.shapeType(true) != TopAbs_FACE) { @@ -596,8 +658,9 @@ TopoShape ProfileBased::getTopoShapeSupportFace() const int ProfileBased::getSketchAxisCount() const { Part::Part2DObject* sketch = static_cast(Profile.getValue()); - if (!sketch) - return -1; // the link to the sketch is lost + if (!sketch) { + return -1; // the link to the sketch is lost + } return sketch->getAxisCount(); } @@ -612,13 +675,15 @@ Part::Feature* ProfileBased::getBaseObject(bool silent) const // getVerifiedObject() may throw it's own exception if fail Part::Feature* obj = getVerifiedObject(silent); - if (!obj) + if (!obj) { return nullptr; + } - if (!obj->isDerivedFrom()) + if (!obj->isDerivedFrom()) { return obj; + } - //due to former test we know we have a 2d object + // due to former test we know we have a 2d object Part::Part2DObject* sketch = getVerifiedSketch(silent); const char* err = nullptr; App::DocumentObject* spt = sketch->AttachmentSupport.getValue(); @@ -667,53 +732,59 @@ void ProfileBased::getUpToFaceFromLinkSub(TopoShape& upToFace, const App::Proper const auto& subs = refFace.getSubValues(); upToFace = Part::Feature::getTopoShape( ref, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subs.empty() ? nullptr : subs[0].c_str()); + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subs.empty() ? nullptr : subs[0].c_str() + ); if (!upToFace.hasSubShape(TopAbs_FACE)) { throw Base::ValueError("SketchBased: Up to face: Failed to extract face"); } } -int ProfileBased::getUpToShapeFromLinkSubList(TopoShape& upToShape, const App::PropertyLinkSubList& refShape) +int ProfileBased::getUpToShapeFromLinkSubList( + TopoShape& upToShape, + const App::PropertyLinkSubList& refShape +) { int ret = 0; auto subSets = refShape.getSubListValues(); std::vector faceList; - for (auto &subSet : subSets){ + for (auto& subSet : subSets) { auto ref = subSet.first; if (ref->isDerivedFrom()) { faceList.push_back(makeTopoShapeFromPlane(ref)); - ret ++; - } else { - if (!ref->isDerivedFrom()) + ret++; + } + else { + if (!ref->isDerivedFrom()) { throw Base::TypeError("SketchBased: Must be face of a feature"); + } auto subStrings = subSet.second; if (subStrings.empty() || subStrings[0].empty()) { - TopoShape baseShape = Part::Feature::getTopoShape(ref, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform); + TopoShape baseShape = Part::Feature::getTopoShape( + ref, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform + ); - for (auto face : baseShape.getSubTopoShapes(TopAbs_FACE)){ + for (auto face : baseShape.getSubTopoShapes(TopAbs_FACE)) { faceList.push_back(face); - ret ++; + ret++; } } else { - for (auto &subString : subStrings){ + for (auto& subString : subStrings) { auto shape = Part::Feature::getShape( - ref, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - subString.c_str()); + ref, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + subString.c_str() + ); TopoShape face = shape; face = face.makeElementFace(); @@ -721,15 +792,15 @@ int ProfileBased::getUpToShapeFromLinkSubList(TopoShape& upToShape, const App::P throw Base::ValueError("SketchBased: Failed to extract face"); } faceList.push_back(face); - ret ++; + ret++; } } } } - if (ret == 0){ + if (ret == 0) { return 0; } - if (ret == 1){ + if (ret == 1) { upToShape = faceList[0]; return 1; } @@ -744,8 +815,9 @@ void ProfileBased::getFaceFromLinkSub(TopoDS_Face& upToFace, const App::Property App::DocumentObject* ref = refFace.getValue(); std::vector subStrings = refFace.getSubValues(); - if (!ref) + if (!ref) { throw Base::ValueError("SketchBased: No face selected"); + } if (ref->isDerivedFrom()) { upToFace = TopoDS::Face(makeShapeFromPlane(ref)); @@ -757,30 +829,35 @@ void ProfileBased::getFaceFromLinkSub(TopoDS_Face& upToFace, const App::Property return; } - if (!ref->isDerivedFrom()) + if (!ref->isDerivedFrom()) { throw Base::TypeError("SketchBased: Must be face of a feature"); + } Part::TopoShape baseShape = static_cast(ref)->Shape.getShape(); // Allow an empty sub here - example is a sketch reference (no sub) that creates a face. - if (subStrings.empty() ) + if (subStrings.empty()) { throw Base::ValueError("SketchBased: No face selected"); + } // TODO: Check for multiple UpToFaces? upToFace = TopoDS::Face(baseShape.getSubShape(subStrings[0].c_str())); - if (upToFace.IsNull()) + if (upToFace.IsNull()) { throw Base::ValueError("SketchBased: Failed to extract face"); + } } -void ProfileBased::getUpToFace(TopoShape& upToFace, - const TopoShape& support, - const TopoShape& sketchshape, - const std::string& method, - gp_Dir& dir) +void ProfileBased::getUpToFace( + TopoShape& upToFace, + const TopoShape& support, + const TopoShape& sketchshape, + const std::string& method, + gp_Dir& dir +) { if ((method == "UpToLast") || (method == "UpToFirst")) { - std::vector cfaces = - Part::findAllFacesCutBy(support, sketchshape, dir); + std::vector cfaces + = Part::findAllFacesCutBy(support, sketchshape, dir); if (cfaces.empty()) { throw Base::ValueError("SketchBased: No faces found in this direction"); } @@ -818,7 +895,8 @@ void ProfileBased::getUpToFace(TopoShape& upToFace, if (adapt.GetType() == GeomAbs_Plane) { if (dir.IsNormal(adapt.Plane().Axis().Direction(), Precision::Confusion())) { throw Base::ValueError( - "SketchBased: Up to face: Must not be parallel to extrusion direction!"); + "SketchBased: Up to face: Must not be parallel to extrusion direction!" + ); } } @@ -860,13 +938,13 @@ double ProfileBased::getThroughAllLength() const return 2.02 * sqrt(box.SquareExtent()); } -bool ProfileBased::checkWireInsideFace(const TopoDS_Wire& wire, const TopoDS_Face& face, - const gp_Dir& dir) { +bool ProfileBased::checkWireInsideFace(const TopoDS_Wire& wire, const TopoDS_Face& face, const gp_Dir& dir) +{ // Project wire onto the face (face, not surface! So limits of face apply) - // FIXME: The results of BRepProj_Projection do not seem to be very stable. Sometimes they return no result - // even in the simplest projection case. - // FIXME: Checking for Closed() is wrong because this has nothing to do with the wire itself being closed - // But ShapeAnalysis_Wire::CheckClosed() doesn't give correct results either. + // FIXME: The results of BRepProj_Projection do not seem to be very stable. Sometimes they + // return no result even in the simplest projection case. + // FIXME: Checking for Closed() is wrong because this has nothing to do with the wire itself + // being closed But ShapeAnalysis_Wire::CheckClosed() doesn't give correct results either. BRepProj_Projection proj(wire, face, dir); return (proj.More() && proj.Current().Closed()); } @@ -877,15 +955,17 @@ bool ProfileBased::checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& f TopoDS_Wire wire = ShapeAnalysis::OuterWire(face); BRepExtrema_DistShapeShape distss(wire, mkEdge.Shape(), Precision::Confusion()); if (distss.IsDone()) { - if (distss.Value() > Precision::Confusion()) + if (distss.Value() > Precision::Confusion()) { return false; + } // build up map vertex->edge TopTools_IndexedDataMapOfShapeListOfShape vertex2Edge; TopExp::MapShapesAndAncestors(wire, TopAbs_VERTEX, TopAbs_EDGE, vertex2Edge); for (Standard_Integer i = 1; i <= distss.NbSolution(); i++) { - if (distss.PointOnShape1(i).Distance(distss.PointOnShape2(i)) > Precision::Confusion()) + if (distss.PointOnShape1(i).Distance(distss.PointOnShape2(i)) > Precision::Confusion()) { continue; + } BRepExtrema_SupportType type = distss.SupportTypeShape1(i); if (type == BRepExtrema_IsOnEdge) { TopoDS_Edge edge = TopoDS::Edge(distss.SupportOnShape1(i)); @@ -898,17 +978,22 @@ bool ProfileBased::checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& f Standard_Real t; distss.ParOnEdgeS1(i, t); - gp_Pnt p_eps1 = adapt.Value(std::max(adapt.FirstParameter(), t - 10 * Precision::Confusion())); - gp_Pnt p_eps2 = adapt.Value(std::min(adapt.LastParameter(), t + 10 * Precision::Confusion())); + gp_Pnt p_eps1 = adapt.Value( + std::max(adapt.FirstParameter(), t - 10 * Precision::Confusion()) + ); + gp_Pnt p_eps2 = adapt.Value( + std::min(adapt.LastParameter(), t + 10 * Precision::Confusion()) + ); // now check if we get a change in the sign of the distances Standard_Real dist_p_eps1_pnt = gp_Vec(p_eps1, pnt).Dot(gp_Vec(dir)); Standard_Real dist_p_eps2_pnt = gp_Vec(p_eps2, pnt).Dot(gp_Vec(dir)); // distance to the plane must be noticeable - if (fabs(dist_p_eps1_pnt) > 5 * Precision::Confusion() && - fabs(dist_p_eps2_pnt) > 5 * Precision::Confusion()) { - if (dist_p_eps1_pnt * dist_p_eps2_pnt < 0) + if (fabs(dist_p_eps1_pnt) > 5 * Precision::Confusion() + && fabs(dist_p_eps2_pnt) > 5 * Precision::Confusion()) { + if (dist_p_eps1_pnt * dist_p_eps2_pnt < 0) { return true; + } } } else if (type == BRepExtrema_IsVertex) { @@ -916,8 +1001,8 @@ bool ProfileBased::checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& f TopoDS_Vertex vertex = TopoDS::Vertex(distss.SupportOnShape1(i)); const TopTools_ListOfShape& edges = vertex2Edge.FindFromKey(vertex); if (edges.Extent() == 2) { - // create a plane (pnt,dir) that goes through the intersection point and is built of - // the vectors of the sketch normal and the rotation axis + // create a plane (pnt,dir) that goes through the intersection point and is + // built of the vectors of the sketch normal and the rotation axis BRepAdaptor_Surface adapt(face); gp_Dir normal = adapt.Plane().Axis().Direction(); gp_Dir dir = line.Direction().Crossed(normal); @@ -929,10 +1014,12 @@ bool ProfileBased::checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& f Standard_Real dist1 = adapt1.Value(adapt1.FirstParameter()).SquareDistance(pnt); Standard_Real dist2 = adapt1.Value(adapt1.LastParameter()).SquareDistance(pnt); gp_Pnt p_eps1; - if (dist1 < dist2) + if (dist1 < dist2) { p_eps1 = adapt1.Value(adapt1.FirstParameter() + 2 * Precision::Confusion()); - else + } + else { p_eps1 = adapt1.Value(adapt1.LastParameter() - 2 * Precision::Confusion()); + } // from the second edge get a point next to the intersection point const TopoDS_Edge& edge2 = TopoDS::Edge(edges.Last()); @@ -940,19 +1027,22 @@ bool ProfileBased::checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& f Standard_Real dist3 = adapt2.Value(adapt2.FirstParameter()).SquareDistance(pnt); Standard_Real dist4 = adapt2.Value(adapt2.LastParameter()).SquareDistance(pnt); gp_Pnt p_eps2; - if (dist3 < dist4) + if (dist3 < dist4) { p_eps2 = adapt2.Value(adapt2.FirstParameter() + 2 * Precision::Confusion()); - else + } + else { p_eps2 = adapt2.Value(adapt2.LastParameter() - 2 * Precision::Confusion()); + } // now check if we get a change in the sign of the distances Standard_Real dist_p_eps1_pnt = gp_Vec(p_eps1, pnt).Dot(gp_Vec(dir)); Standard_Real dist_p_eps2_pnt = gp_Vec(p_eps2, pnt).Dot(gp_Vec(dir)); // distance to the plane must be noticeable - if (fabs(dist_p_eps1_pnt) > Precision::Confusion() && - fabs(dist_p_eps2_pnt) > Precision::Confusion()) { - if (dist_p_eps1_pnt * dist_p_eps2_pnt < 0) + if (fabs(dist_p_eps1_pnt) > Precision::Confusion() + && fabs(dist_p_eps2_pnt) > Precision::Confusion()) { + if (dist_p_eps1_pnt * dist_p_eps2_pnt < 0) { return true; + } } } } @@ -962,7 +1052,7 @@ bool ProfileBased::checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& f return false; } -void ProfileBased::remapSupportShape(const TopoDS_Shape & newShape) +void ProfileBased::remapSupportShape(const TopoDS_Shape& newShape) { (void)newShape; // Realthunder: with the new topological naming, I don't think this function @@ -971,32 +1061,37 @@ void ProfileBased::remapSupportShape(const TopoDS_Shape & newShape) // as dress up editors, can perform element guessing when activated. } -namespace PartDesign { - struct gp_Pnt_Less - { - bool operator()(const gp_Pnt& p1, - const gp_Pnt& p2) const - { - if (fabs(p1.X() - p2.X()) > Precision::Confusion()) - return p1.X() < p2.X(); - if (fabs(p1.Y() - p2.Y()) > Precision::Confusion()) - return p1.Y() < p2.Y(); - if (fabs(p1.Z() - p2.Z()) > Precision::Confusion()) - return p1.Z() < p2.Z(); - return false; // points are considered to be equal - } - }; -} - -bool ProfileBased::isQuasiEqual(const TopoDS_Shape & s1, const TopoDS_Shape & s2) const +namespace PartDesign { - if (s1.ShapeType() != s2.ShapeType()) +struct gp_Pnt_Less +{ + bool operator()(const gp_Pnt& p1, const gp_Pnt& p2) const + { + if (fabs(p1.X() - p2.X()) > Precision::Confusion()) { + return p1.X() < p2.X(); + } + if (fabs(p1.Y() - p2.Y()) > Precision::Confusion()) { + return p1.Y() < p2.Y(); + } + if (fabs(p1.Z() - p2.Z()) > Precision::Confusion()) { + return p1.Z() < p2.Z(); + } + return false; // points are considered to be equal + } +}; +} // namespace PartDesign + +bool ProfileBased::isQuasiEqual(const TopoDS_Shape& s1, const TopoDS_Shape& s2) const +{ + if (s1.ShapeType() != s2.ShapeType()) { return false; + } TopTools_IndexedMapOfShape map1, map2; TopExp::MapShapes(s1, TopAbs_VERTEX, map1); TopExp::MapShapes(s2, TopAbs_VERTEX, map2); - if (map1.Extent() != map2.Extent()) + if (map1.Extent() != map2.Extent()) { return false; + } std::vector p1; for (int i = 1; i <= map1.Extent(); i++) { @@ -1012,19 +1107,21 @@ bool ProfileBased::isQuasiEqual(const TopoDS_Shape & s1, const TopoDS_Shape & s2 std::sort(p1.begin(), p1.end(), gp_Pnt_Less()); std::sort(p2.begin(), p2.end(), gp_Pnt_Less()); - if (p1.size() != p2.size()) + if (p1.size() != p2.size()) { return false; + } std::vector::iterator it = p1.begin(), jt = p2.begin(); for (; it != p1.end(); ++it, ++jt) { - if (!(*it).IsEqual(*jt, Precision::Confusion())) + if (!(*it).IsEqual(*jt, Precision::Confusion())) { return false; + } } return true; } -bool ProfileBased::isEqualGeometry(const TopoDS_Shape & s1, const TopoDS_Shape & s2) const +bool ProfileBased::isEqualGeometry(const TopoDS_Shape& s1, const TopoDS_Shape& s2) const { if (s1.ShapeType() == TopAbs_FACE && s2.ShapeType() == TopAbs_FACE) { BRepAdaptor_Surface a1(TopoDS::Face(s1)); @@ -1035,8 +1132,9 @@ bool ProfileBased::isEqualGeometry(const TopoDS_Shape & s1, const TopoDS_Shape & if (p1.Distance(p2.Location()) < Precision::Confusion()) { const gp_Dir& d1 = p1.Axis().Direction(); const gp_Dir& d2 = p2.Axis().Direction(); - if (d1.IsParallel(d2, Precision::Confusion())) + if (d1.IsParallel(d2, Precision::Confusion())) { return true; + } } } } @@ -1052,7 +1150,7 @@ bool ProfileBased::isEqualGeometry(const TopoDS_Shape & s1, const TopoDS_Shape & return false; } -bool ProfileBased::isParallelPlane(const TopoDS_Shape & s1, const TopoDS_Shape & s2) const +bool ProfileBased::isParallelPlane(const TopoDS_Shape& s1, const TopoDS_Shape& s2) const { if (s1.ShapeType() == TopAbs_FACE && s2.ShapeType() == TopAbs_FACE) { BRepAdaptor_Surface a1(TopoDS::Face(s1)); @@ -1062,15 +1160,16 @@ bool ProfileBased::isParallelPlane(const TopoDS_Shape & s1, const TopoDS_Shape & gp_Pln p2 = a2.Plane(); const gp_Dir& d1 = p1.Axis().Direction(); const gp_Dir& d2 = p2.Axis().Direction(); - if (d1.IsParallel(d2, Precision::Confusion())) + if (d1.IsParallel(d2, Precision::Confusion())) { return true; + } } } return false; } -double ProfileBased::getReversedAngle(const Base::Vector3d & b, const Base::Vector3d & v) const +double ProfileBased::getReversedAngle(const Base::Vector3d& b, const Base::Vector3d& v) const { try { Part::Feature* obj = getVerifiedObject(); @@ -1098,29 +1197,38 @@ double ProfileBased::getReversedAngle(const Base::Vector3d & b, const Base::Vect } } -void ProfileBased::getAxis(const App::DocumentObject * pcReferenceAxis, const std::vector &subReferenceAxis, - Base::Vector3d& base, Base::Vector3d& dir, ProfileBased::ForbiddenAxis checkAxis) const +void ProfileBased::getAxis( + const App::DocumentObject* pcReferenceAxis, + const std::vector& subReferenceAxis, + Base::Vector3d& base, + Base::Vector3d& dir, + ProfileBased::ForbiddenAxis checkAxis +) const { - auto verifyAxisFunc = [](ProfileBased::ForbiddenAxis checkAxis, const gp_Pln& sketchplane, const gp_Dir& dir) { - switch (checkAxis) { - case ForbiddenAxis::NotPerpendicularWithNormal: - // If perpendicular to the normal then it's parallel to the plane - if (sketchplane.Axis().Direction().IsNormal(dir, Precision::Angular())) - throw Base::ValueError("Axis must not be parallel to the sketch plane"); - break; - case ForbiddenAxis::NotParallelWithNormal: - // If parallel with the normal then it's perpendicular to the plane - if (sketchplane.Axis().Direction().IsParallel(dir, Precision::Angular())) - throw Base::ValueError("Axis must not be perpendicular to the sketch plane"); - break; - default: - break; - } - }; + auto verifyAxisFunc = + [](ProfileBased::ForbiddenAxis checkAxis, const gp_Pln& sketchplane, const gp_Dir& dir) { + switch (checkAxis) { + case ForbiddenAxis::NotPerpendicularWithNormal: + // If perpendicular to the normal then it's parallel to the plane + if (sketchplane.Axis().Direction().IsNormal(dir, Precision::Angular())) { + throw Base::ValueError("Axis must not be parallel to the sketch plane"); + } + break; + case ForbiddenAxis::NotParallelWithNormal: + // If parallel with the normal then it's perpendicular to the plane + if (sketchplane.Axis().Direction().IsParallel(dir, Precision::Angular())) { + throw Base::ValueError("Axis must not be perpendicular to the sketch plane"); + } + break; + default: + break; + } + }; auto getAxisFromEdge = [](const TopoDS_Edge& refEdge, Base::Vector3d& base, Base::Vector3d& dir) { - if (refEdge.IsNull()) + if (refEdge.IsNull()) { throw Base::ValueError("Failed to extract rotation edge"); + } BRepAdaptor_Curve adapt(refEdge); gp_Pnt b; gp_Dir d; @@ -1140,7 +1248,7 @@ void ProfileBased::getAxis(const App::DocumentObject * pcReferenceAxis, const st dir = Base::Vector3d(d.X(), d.Y(), d.Z()); }; - dir = Base::Vector3d(0, 0, 0); // If unchanged signals that no valid axis was found + dir = Base::Vector3d(0, 0, 0); // If unchanged signals that no valid axis was found if (!pcReferenceAxis || subReferenceAxis.empty()) { return; } @@ -1155,7 +1263,10 @@ void ProfileBased::getAxis(const App::DocumentObject * pcReferenceAxis, const st Base::Rotation SketchOrientation = SketchPlm.getRotation(); SketchOrientation.multVec(SketchVector, SketchVector); Base::Vector3d SketchPos = SketchPlm.getPosition(); - sketchplane = gp_Pln(gp_Pnt(SketchPos.x, SketchPos.y, SketchPos.z), gp_Dir(SketchVector.x, SketchVector.y, SketchVector.z)); + sketchplane = gp_Pln( + gp_Pnt(SketchPos.x, SketchPos.y, SketchPos.z), + gp_Dir(SketchVector.x, SketchVector.y, SketchVector.z) + ); if (pcReferenceAxis == profile) { bool hasValidAxis = false; @@ -1184,15 +1295,17 @@ void ProfileBased::getAxis(const App::DocumentObject * pcReferenceAxis, const st base = axis.getBase(); dir = axis.getDirection(); return; - } //else - an edge of the sketch was selected as an axis + } // else - an edge of the sketch was selected as an axis } - } else if (profile->isDerivedFrom()) { Base::Placement SketchPlm = getVerifiedObject()->Placement.getValue(); Base::Vector3d SketchVector = getProfileNormal(); Base::Vector3d SketchPos = SketchPlm.getPosition(); - sketchplane = gp_Pln(gp_Pnt(SketchPos.x, SketchPos.y, SketchPos.z), gp_Dir(SketchVector.x, SketchVector.y, SketchVector.z)); + sketchplane = gp_Pln( + gp_Pnt(SketchPos.x, SketchPos.y, SketchPos.z), + gp_Dir(SketchVector.x, SketchVector.y, SketchVector.z) + ); } // get reference axis @@ -1215,8 +1328,9 @@ void ProfileBased::getAxis(const App::DocumentObject * pcReferenceAxis, const st } if (pcReferenceAxis->isDerivedFrom()) { - if (subReferenceAxis.empty()) + if (subReferenceAxis.empty()) { throw Base::ValueError("No rotation axis reference specified"); + } const Part::Feature* refFeature = static_cast(pcReferenceAxis); Part::TopoShape refShape = refFeature->Shape.getShape(); TopoDS_Shape ref; @@ -1238,7 +1352,8 @@ void ProfileBased::getAxis(const App::DocumentObject * pcReferenceAxis, const st throw Base::TypeError("Unsupported geometry type to get reference axis"); } -Base::Vector3d ProfileBased::getProfileNormal() const { +Base::Vector3d ProfileBased::getProfileNormal() const +{ Base::Vector3d SketchVector(0, 0, 1); auto obj = getVerifiedObject(true); @@ -1256,7 +1371,8 @@ Base::Vector3d ProfileBased::getProfileNormal() const { // For newer version, do not do fitting, as it may flip the face normal for // some reason. - TopoShape shape = getTopoShapeVerifiedFace(true, true, true); //, _ProfileBasedVersion.getValue() <= 0); + TopoShape shape = getTopoShapeVerifiedFace(true, true, true); //, _ProfileBasedVersion.getValue() + //<= 0); gp_Pln pln; if (shape.findPlane(pln)) { @@ -1266,7 +1382,10 @@ Base::Vector3d ProfileBased::getProfileNormal() const { if (shape.hasSubShape(TopAbs_EDGE)) { // Find the first planar face that contains the edge, and return the plane normal - TopoShape objShape = Part::Feature::getTopoShape(obj, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + TopoShape objShape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); for (int idx : objShape.findAncestors(shape.getSubShape(TopAbs_EDGE, 1), TopAbs_FACE)) { if (objShape.getSubTopoShape(TopAbs_FACE, idx).findPlane(pln)) { gp_Dir dir = pln.Axis().Direction(); @@ -1279,10 +1398,8 @@ Base::Vector3d ProfileBased::getProfileNormal() const { if (shape.hasSubShape(TopAbs_FACE)) { TopoDS_Face face = TopoDS::Face(shape.getSubShape(TopAbs_FACE, 1)); BRepAdaptor_Surface adapt(face); - double u = - adapt.FirstUParameter() + (adapt.LastUParameter() - adapt.FirstUParameter()) / 2.; - double v = - adapt.FirstVParameter() + (adapt.LastVParameter() - adapt.FirstVParameter()) / 2.; + double u = adapt.FirstUParameter() + (adapt.LastUParameter() - adapt.FirstUParameter()) / 2.; + double v = adapt.FirstVParameter() + (adapt.LastVParameter() - adapt.FirstVParameter()) / 2.; BRepLProp_SLProps prop(adapt, u, v, 2, Precision::Confusion()); if (prop.IsNormalDefined()) { gp_Pnt pnt; @@ -1331,14 +1448,18 @@ Base::Vector3d ProfileBased::getProfileNormal() const { return SketchVector; } -void ProfileBased::Restore(Base::XMLReader & reader) +void ProfileBased::Restore(Base::XMLReader& reader) { PartDesign::FeatureAddSub::Restore(reader); } -void ProfileBased::handleChangedPropertyName(Base::XMLReader & reader, const char* TypeName, const char* PropName) +void ProfileBased::handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName +) { - //check if we load the old sketch property + // check if we load the old sketch property if ((strcmp("Sketch", PropName) == 0) && (strcmp("App::PropertyLink", TypeName) == 0)) { std::vector vec; diff --git a/src/Mod/PartDesign/App/FeatureSketchBased.h b/src/Mod/PartDesign/App/FeatureSketchBased.h index 12537472fe..a571f2e76b 100644 --- a/src/Mod/PartDesign/App/FeatureSketchBased.h +++ b/src/Mod/PartDesign/App/FeatureSketchBased.h @@ -36,12 +36,13 @@ class TopoDS_Wire; namespace PartDesign { -class PartDesignExport ProfileBased : public PartDesign::FeatureAddSub +class PartDesignExport ProfileBased: public PartDesign::FeatureAddSub { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::ProfileBased); public: - enum class ForbiddenAxis { + enum class ForbiddenAxis + { NoCheck = 0, NotPerpendicularWithNormal = 1, NotParallelWithNormal = 2 @@ -52,9 +53,9 @@ public: /// Profile used to create this feature App::PropertyLinkSub Profile; /// Reverse extrusion direction - App::PropertyBool Reversed; + App::PropertyBool Reversed; /// Make extrusion symmetric to sketch plane - App::PropertyBool Midplane; + App::PropertyBool Midplane; /// Face to extrude up to App::PropertyLinkSub UpToFace; App::PropertyLinkSub UpToFace2; @@ -76,8 +77,8 @@ public: /** applies a transform on the Placement of the Sketch or its * support if it has one - */ - void transformPlacement(const Base::Placement &transform) override; + */ + void transformPlacement(const Base::Placement& transform) override; /** * Verifies the linked Profile and returns it if it is a valid 2D object @@ -85,7 +86,7 @@ public: * silently returns nullptr, otherwise throw a Base::Exception. * Default is false. */ - Part::Part2DObject* getVerifiedSketch(bool silent=false) const; + Part::Part2DObject* getVerifiedSketch(bool silent = false) const; /** * Verifies the linked Profile and returns it if it is a valid object @@ -93,7 +94,7 @@ public: * silently returns nullptr, otherwise throw a Base::Exception. * Default is false. */ - Part::Feature* getVerifiedObject(bool silent=false) const; + Part::Feature* getVerifiedObject(bool silent = false) const; /** * Verifies the linked Object and returns the shape used as profile @@ -114,11 +115,13 @@ public: * @param profile: optional profile object, if not given then use 'Profile' property * @param subs: optional profile sub-object names, if not given then use 'Profile' property */ - TopoShape getTopoShapeVerifiedFace(bool silent = false, - bool doFit = true, - bool allowOpen = false, - const App::DocumentObject* profile = nullptr, - const std::vector& subs = {}) const; + TopoShape getTopoShapeVerifiedFace( + bool silent = false, + bool doFit = true, + bool allowOpen = false, + const App::DocumentObject* profile = nullptr, + const std::vector& subs = {} + ) const; /// Returns the wires the sketch is composed of // TODO: Toponaming April 2024 Deprecated in favor of TopoShape method. Remove when possible. @@ -134,19 +137,23 @@ public: virtual Base::Vector3d getProfileNormal() const; // Use Part::ShapeOptions enum to pass flags - TopoShape getProfileShape(Part::ShapeOptions subShapeOptions = - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform) const; + TopoShape getProfileShape( + Part::ShapeOptions subShapeOptions = Part::ShapeOption::NeedSubElement + | Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ) const; /// retrieves the number of axes in the linked sketch (defined as construction lines) int getSketchAxisCount() const; - Part::Feature* getBaseObject(bool silent=false) const override; + Part::Feature* getBaseObject(bool silent = false) const override; - //backwards compatibility: profile property was renamed and has different type now + // backwards compatibility: profile property was renamed and has different type now void Restore(Base::XMLReader& reader) override; - void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; // calculate the through all length double getThroughAllLength() const; @@ -165,43 +172,51 @@ protected: /// Create a shape with shapes and faces from a given LinkSubList /// return 0 if almost one full shape is selected else the face count - static int getUpToShapeFromLinkSubList(TopoShape& upToShape, const App::PropertyLinkSubList& refShape); + static int getUpToShapeFromLinkSubList( + TopoShape& upToShape, + const App::PropertyLinkSubList& refShape + ); /// Find a valid face to extrude up to - static void getUpToFace(TopoShape& upToFace, - const TopoShape& support, - const TopoShape& sketchshape, - const std::string& method, - gp_Dir& dir); + static void getUpToFace( + TopoShape& upToFace, + const TopoShape& support, + const TopoShape& sketchshape, + const std::string& method, + gp_Dir& dir + ); /// Add an offset to the face - static void addOffsetToFace(TopoShape& upToFace, - const gp_Dir& dir, - double offset); + static void addOffsetToFace(TopoShape& upToFace, const gp_Dir& dir, double offset); /// Check whether the wire after projection on the face is inside the face - static bool checkWireInsideFace(const TopoDS_Wire& wire, - const TopoDS_Face& face, - const gp_Dir& dir); + static bool checkWireInsideFace(const TopoDS_Wire& wire, const TopoDS_Face& face, const gp_Dir& dir); /// Check whether the line crosses the face (line and face must be on the same plane) static bool checkLineCrossesFace(const gp_Lin& line, const TopoDS_Face& face); - /// Used to suggest a value for Reversed flag so that material is always removed (Groove) or added (Revolution) from the support + /// Used to suggest a value for Reversed flag so that material is always removed (Groove) or + /// added (Revolution) from the support double getReversedAngle(const Base::Vector3d& b, const Base::Vector3d& v) const; /// get Axis from ReferenceAxis - void getAxis(const App::DocumentObject* pcReferenceAxis, const std::vector& subReferenceAxis, - Base::Vector3d& base, Base::Vector3d& dir, ForbiddenAxis checkAxis) const; + void getAxis( + const App::DocumentObject* pcReferenceAxis, + const std::vector& subReferenceAxis, + Base::Vector3d& base, + Base::Vector3d& dir, + ForbiddenAxis checkAxis + ) const; void onChanged(const App::Property* prop) override; + private: bool isParallelPlane(const TopoDS_Shape&, const TopoDS_Shape&) const; bool isEqualGeometry(const TopoDS_Shape&, const TopoDS_Shape&) const; bool isQuasiEqual(const TopoDS_Shape&, const TopoDS_Shape&) const; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_SketchBased_H +#endif // PARTDESIGN_SketchBased_H diff --git a/src/Mod/PartDesign/App/FeatureSolid.cpp b/src/Mod/PartDesign/App/FeatureSolid.cpp index af9f2cc8a4..30fae90c0b 100644 --- a/src/Mod/PartDesign/App/FeatureSolid.cpp +++ b/src/Mod/PartDesign/App/FeatureSolid.cpp @@ -21,17 +21,16 @@ ***************************************************************************/ - #include "FeatureSolid.h" -namespace PartDesign { +namespace PartDesign +{ -PROPERTY_SOURCE(PartDesign::Solid,PartDesign::Feature) +PROPERTY_SOURCE(PartDesign::Solid, PartDesign::Feature) Solid::Solid() = default; - -} +} // namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureSolid.h b/src/Mod/PartDesign/App/FeatureSolid.h index 41ceacd520..dd1ec17fba 100644 --- a/src/Mod/PartDesign/App/FeatureSolid.h +++ b/src/Mod/PartDesign/App/FeatureSolid.h @@ -31,11 +31,11 @@ namespace PartDesign { - /** PartDesign feature +/** PartDesign feature * Base class of all PartDesign features. * This kind of features only produce solids or fail. */ -class PartDesignExport Solid : public Feature +class PartDesignExport Solid: public Feature { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Solid); @@ -43,10 +43,9 @@ public: Solid(); protected: - }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_Feature_H +#endif // PARTDESIGN_Feature_H diff --git a/src/Mod/PartDesign/App/FeatureThickness.cpp b/src/Mod/PartDesign/App/FeatureThickness.cpp index 287b7e78e8..ee9b1cbe44 100644 --- a/src/Mod/PartDesign/App/FeatureThickness.cpp +++ b/src/Mod/PartDesign/App/FeatureThickness.cpp @@ -24,8 +24,8 @@ #include #include -# include -# include +#include +#include #include @@ -35,35 +35,41 @@ FC_LOG_LEVEL_INIT("PartDesign", true, true) using namespace PartDesign; -const char *PartDesign::Thickness::ModeEnums[] = {"Skin", "Pipe", "RectoVerso", nullptr}; -const char *PartDesign::Thickness::JoinEnums[] = {"Arc", "Intersection", nullptr}; +const char* PartDesign::Thickness::ModeEnums[] = {"Skin", "Pipe", "RectoVerso", nullptr}; +const char* PartDesign::Thickness::JoinEnums[] = {"Arc", "Intersection", nullptr}; PROPERTY_SOURCE(PartDesign::Thickness, PartDesign::DressUp) -Thickness::Thickness() { +Thickness::Thickness() +{ ADD_PROPERTY_TYPE(Value, (1.0), "Thickness", App::Prop_None, "Thickness value"); ADD_PROPERTY_TYPE(Mode, (0L), "Thickness", App::Prop_None, "Mode"); Mode.setEnums(ModeEnums); ADD_PROPERTY_TYPE(Join, (0L), "Thickness", App::Prop_None, "Join type"); Join.setEnums(JoinEnums); - ADD_PROPERTY_TYPE(Reversed, (true), "Thickness", App::Prop_None, - "Apply the thickness towards the solids interior"); - ADD_PROPERTY_TYPE(Intersection, (false), "Thickness", App::Prop_None, - "Enable intersection-handling"); + ADD_PROPERTY_TYPE( + Reversed, + (true), + "Thickness", + App::Prop_None, + "Apply the thickness towards the solids interior" + ); + ADD_PROPERTY_TYPE(Intersection, (false), "Thickness", App::Prop_None, "Enable intersection-handling"); } -int16_t Thickness::mustExecute() const { - if (Placement.isTouched() || - Value.isTouched() || - Mode.isTouched() || - Join.isTouched()) { +int16_t Thickness::mustExecute() const +{ + if (Placement.isTouched() || Value.isTouched() || Mode.isTouched() || Join.isTouched()) { return 1; } return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Thickness::execute() { - if (onlyHaveRefined()) { return App::DocumentObject::StdReturn; } +App::DocumentObjectExecReturn* Thickness::execute() +{ + if (onlyHaveRefined()) { + return App::DocumentObject::StdReturn; + } // Base shape Part::TopoShape TopShape; @@ -89,16 +95,18 @@ App::DocumentObjectExecReturn *Thickness::execute() { this->Placement.setValue(Base::Placement()); std::map> closeFaces; - for ( const auto& it : subStrings ) { + for (const auto& it : subStrings) { TopoDS_Shape face; try { face = TopShape.getSubShape(it.c_str()); } catch (...) { } - if (face.IsNull()) + if (face.IsNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Invalid face reference")); + QT_TRANSLATE_NOOP("Exception", "Invalid face reference") + ); + } // We found the sub element (face) so let's get its history index in our shape int index = TopShape.findAncestor(face, TopAbs_SOLID); if (!index) { @@ -117,11 +125,13 @@ App::DocumentObjectExecReturn *Thickness::execute() { std::vector shapes; auto count = static_cast(TopShape.countSubShapes(TopAbs_SOLID)); - if (!count) + if (!count) { return new App::DocumentObjectExecReturn("No solid"); + } // we do not offer tangent join type - if (join == 1) + if (join == 1) { join = 2; + } if (fabs(thickness) > 2 * tol) { auto mapIterator = closeFaces.begin(); @@ -137,13 +147,15 @@ App::DocumentObjectExecReturn *Thickness::execute() { } TopoShape res(0); try { - res = solid.makeElementThickSolid(*faces, - thickness, - tol, - intersection, - false, - mode, - static_cast(join)); + res = solid.makeElementThickSolid( + *faces, + thickness, + tol, + intersection, + false, + mode, + static_cast(join) + ); shapes.push_back(res); } catch (Standard_Failure& e) { @@ -159,9 +171,11 @@ App::DocumentObjectExecReturn *Thickness::execute() { TopoShape result(0); if (shapes.size() > 1) { result.makeElementFuse(shapes); - } else if (shapes.empty()) { + } + else if (shapes.empty()) { result = TopShape; - } else { + } + else { result = shapes.front(); } // store shape before refinement diff --git a/src/Mod/PartDesign/App/FeatureThickness.h b/src/Mod/PartDesign/App/FeatureThickness.h index 0098cdd487..ed851fca3e 100644 --- a/src/Mod/PartDesign/App/FeatureThickness.h +++ b/src/Mod/PartDesign/App/FeatureThickness.h @@ -31,26 +31,27 @@ namespace PartDesign { -class PartDesignExport Thickness : public DressUp +class PartDesignExport Thickness: public DressUp { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Thickness); public: Thickness(); - App::PropertyLength Value; - App::PropertyBool Reversed; - App::PropertyBool Intersection; - App::PropertyEnumeration Mode; - App::PropertyEnumeration Join; + App::PropertyLength Value; + App::PropertyBool Reversed; + App::PropertyBool Intersection; + App::PropertyEnumeration Mode; + App::PropertyEnumeration Join; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderThickness"; } //@} @@ -59,7 +60,7 @@ private: static const char* JoinEnums[]; }; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_FEATURETHICKNESS_H +#endif // PARTDESIGN_FEATURETHICKNESS_H diff --git a/src/Mod/PartDesign/App/FeatureTransformed.cpp b/src/Mod/PartDesign/App/FeatureTransformed.cpp index 93c827bfa1..904cd79796 100644 --- a/src/Mod/PartDesign/App/FeatureTransformed.cpp +++ b/src/Mod/PartDesign/App/FeatureTransformed.cpp @@ -60,9 +60,7 @@ extern bool getPDRefineModelParameter(); PROPERTY_SOURCE(PartDesign::Transformed, PartDesign::FeatureRefine) -std::array transformModeEnums = {"Features", - "Whole shape", - nullptr}; +std::array transformModeEnums = {"Features", "Whole shape", nullptr}; Transformed::Transformed() { @@ -98,8 +96,10 @@ Part::Feature* Transformed::getBaseObject(bool silent) const if (firstOriginal) { rv = freecad_cast(firstOriginal); if (!rv) { - err = QT_TRANSLATE_NOOP("Exception", - "Transformation feature Linked object is not a Part object"); + err = QT_TRANSLATE_NOOP( + "Exception", + "Transformation feature Linked object is not a Part object" + ); } } else { @@ -184,8 +184,8 @@ bool Transformed::isMultiTransformChild() const } */ - // instead check for default property values because these are invalid for a standalone transform feature. - // This will mislabel standalone features during the initialization phase. + // instead check for default property values because these are invalid for a standalone + // transform feature. This will mislabel standalone features during the initialization phase. if (TransformMode.getValue() == 0 && Originals.getValue().empty()) { return true; } @@ -193,9 +193,11 @@ bool Transformed::isMultiTransformChild() const return false; } -void Transformed::handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) +void Transformed::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // The property 'Angle' of PolarPattern has changed from PropertyFloat // to PropertyAngle and the property 'Length' has changed to PropertyLength. @@ -321,7 +323,8 @@ App::DocumentObjectExecReturn* Transformed::execute() const Part::TopoShape& supportTopShape = supportFeature->Shape.getShape(); if (supportTopShape.getShape().IsNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", "Cannot transform invalid support shape")); + QT_TRANSLATE_NOOP("Exception", "Cannot transform invalid support shape") + ); } // create an untransformed copy of the support shape @@ -333,11 +336,11 @@ App::DocumentObjectExecReturn* Transformed::execute() auto getTransformedCompShape = [&](const auto& supportShape, const auto& origShape) { std::vector shapes = {supportShape}; - TopoShape shape (origShape); - int idx=1; + TopoShape shape(origShape); + int idx = 1; auto transformIter = transformations.cbegin(); transformIter++; - for ( ; transformIter != transformations.end(); transformIter++) { + for (; transformIter != transformations.end(); transformIter++) { if (OCCTProgressIndicator::getAppIndicator().UserBreak()) { return std::vector(); } @@ -364,14 +367,15 @@ App::DocumentObjectExecReturn* Transformed::execute() if (!feature) { return new App::DocumentObjectExecReturn(QT_TRANSLATE_NOOP( "Exception", - "Only additive and subtractive features can be transformed")); + "Only additive and subtractive features can be transformed" + )); } feature->getAddSubShape(fuseShape, cutShape); if (fuseShape.isNull() && cutShape.isNull()) { return new App::DocumentObjectExecReturn( - QT_TRANSLATE_NOOP("Exception", - "Shape of additive/subtractive feature is empty")); + QT_TRANSLATE_NOOP("Exception", "Shape of additive/subtractive feature is empty") + ); } gp_Trsf trsf = feature->getLocation().Transformation().Multiplied(trsfInv); if (!fuseShape.isNull()) { @@ -435,5 +439,3 @@ TopoDS_Shape Transformed::getRemainingSolids(const TopoDS_Shape& shape) } } // namespace PartDesign - - diff --git a/src/Mod/PartDesign/App/FeatureTransformed.h b/src/Mod/PartDesign/App/FeatureTransformed.h index ce830c0e26..3e052612ce 100644 --- a/src/Mod/PartDesign/App/FeatureTransformed.h +++ b/src/Mod/PartDesign/App/FeatureTransformed.h @@ -75,8 +75,7 @@ public: /// Get the list of transformations describing the members of the pattern // Note: Only the Scaled feature requires the originals - virtual const std::list - getTransformations(const std::vector /*originals*/) + virtual const std::list getTransformations(const std::vector /*originals*/) { return std::list(); // Default method } @@ -105,9 +104,11 @@ public: protected: void Restore(Base::XMLReader& reader) override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; virtual void positionBySupport(); static TopoDS_Shape getRemainingSolids(const TopoDS_Shape&); diff --git a/src/Mod/PartDesign/App/Measure.cpp b/src/Mod/PartDesign/App/Measure.cpp index fcbab6fe19..60f14f5e08 100644 --- a/src/Mod/PartDesign/App/Measure.cpp +++ b/src/Mod/PartDesign/App/Measure.cpp @@ -20,16 +20,15 @@ **************************************************************************/ - #include #include #include "Base/Console.h" #include "Measure.h" -void PartDesign::Measure::initialize() { +void PartDesign::Measure::initialize() +{ const App::MeasureHandler& handler = App::MeasureManager::getMeasureHandler("Part"); App::MeasureManager::addMeasureHandler("PartDesign", handler.typeCb); } - diff --git a/src/Mod/PartDesign/App/Measure.h b/src/Mod/PartDesign/App/Measure.h index 23837cafcc..1a4cd29797 100644 --- a/src/Mod/PartDesign/App/Measure.h +++ b/src/Mod/PartDesign/App/Measure.h @@ -25,7 +25,6 @@ #include - namespace PartDesign { @@ -33,12 +32,10 @@ namespace PartDesign class PartDesignExport Measure { public: - static void initialize(); - }; -} //namespace PartDesign +} // namespace PartDesign #endif diff --git a/src/Mod/PartDesign/App/PreCompiled.h b/src/Mod/PartDesign/App/PreCompiled.h index f29dcb061e..6eac88a5e1 100644 --- a/src/Mod/PartDesign/App/PreCompiled.h +++ b/src/Mod/PartDesign/App/PreCompiled.h @@ -32,4 +32,3 @@ #include #endif - diff --git a/src/Mod/PartDesign/App/ShapeBinder.cpp b/src/Mod/PartDesign/App/ShapeBinder.cpp index 2812a33bc6..774f828525 100644 --- a/src/Mod/PartDesign/App/ShapeBinder.cpp +++ b/src/Mod/PartDesign/App/ShapeBinder.cpp @@ -21,12 +21,12 @@ ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -45,7 +45,7 @@ #include "Mod/Part/App/TopoShapeOpCode.h" #include "Base/Tools.h" -FC_LOG_LEVEL_INIT("PartDesign",true,true) +FC_LOG_LEVEL_INIT("PartDesign", true, true) using namespace PartDesign; namespace sp = std::placeholders; @@ -61,7 +61,13 @@ PROPERTY_SOURCE(PartDesign::ShapeBinder, Part::Feature) ShapeBinder::ShapeBinder() { - ADD_PROPERTY_TYPE(Support, (nullptr, nullptr), "", (App::PropertyType)(App::Prop_None), "Support of the geometry"); + ADD_PROPERTY_TYPE( + Support, + (nullptr, nullptr), + "", + (App::PropertyType)(App::Prop_None), + "Support of the geometry" + ); Placement.setStatus(App::Property::Hidden, true); ADD_PROPERTY_TYPE(TraceSupport, (false), "", App::Prop_None, "Trace support shape"); } @@ -76,7 +82,8 @@ void ShapeBinder::onChanged(const App::Property* prop) Feature::onChanged(prop); } -short int ShapeBinder::mustExecute() const { +short int ShapeBinder::mustExecute() const +{ if (Support.isTouched()) { return 1; @@ -96,16 +103,16 @@ Part::TopoShape ShapeBinder::updatedShape() const ShapeBinder::getFilteredReferences(&Support, obj, subs); - //if we have a link we rebuild the shape, but we change nothing if we are a simple copy + // if we have a link we rebuild the shape, but we change nothing if we are a simple copy if (obj) { shape = ShapeBinder::buildShapeFromReferences(obj, subs); - //now, shape is in object's CS, and includes local Placement of obj but nothing else. + // now, shape is in object's CS, and includes local Placement of obj but nothing else. if (TraceSupport.getValue()) { - //compute the transform, and apply it to the shape. - Base::Placement sourceCS = //full placement of container of obj + // compute the transform, and apply it to the shape. + Base::Placement sourceCS = // full placement of container of obj obj->globalPlacement() * obj->Placement.getValue().inverse(); - Base::Placement targetCS = //full placement of container of this shapebinder + Base::Placement targetCS = // full placement of container of this shapebinder this->globalPlacement() * this->Placement.getValue().inverse(); Base::Placement transform = targetCS.inverse() * sourceCS; shape.setPlacement(transform * shape.getPlacement()); @@ -135,9 +142,11 @@ App::DocumentObjectExecReturn* ShapeBinder::execute() return Part::Feature::execute(); } -void ShapeBinder::getFilteredReferences(const App::PropertyLinkSubList* prop, - App::GeoFeature*& obj, - std::vector< std::string >& subobjects) +void ShapeBinder::getFilteredReferences( + const App::PropertyLinkSubList* prop, + App::GeoFeature*& obj, + std::vector& subobjects +) { obj = nullptr; subobjects.clear(); @@ -149,7 +158,7 @@ void ShapeBinder::getFilteredReferences(const App::PropertyLinkSubList* prop, return; } - //we only allow one part feature, so get the first one we find + // we only allow one part feature, so get the first one we find size_t index = 0; for (auto* it : objs) { if (auto part = dynamic_cast(it)) { @@ -159,22 +168,22 @@ void ShapeBinder::getFilteredReferences(const App::PropertyLinkSubList* prop, index++; } - //do we have any part feature? + // do we have any part feature? if (obj) { - //if we have no subshpape we use the whole shape + // if we have no subshpape we use the whole shape if (subs[index].empty()) { return; } - //collect all subshapes for the object + // collect all subshapes for the object for (index = 0; index < objs.size(); index++) { - //we only allow subshapes from a single Part::Feature + // we only allow subshapes from a single Part::Feature if (objs[index] != obj) { continue; } - //in this mode the full shape is not allowed, as we already started the subshape - //processing + // in this mode the full shape is not allowed, as we already started the subshape + // processing if (subs[index].empty()) { continue; } @@ -201,7 +210,8 @@ void ShapeBinder::getFilteredReferences(const App::PropertyLinkSubList* prop, } } -Part::TopoShape ShapeBinder::buildShapeFromReferences(App::GeoFeature* obj, std::vector< std::string > subs) { +Part::TopoShape ShapeBinder::buildShapeFromReferences(App::GeoFeature* obj, std::vector subs) +{ if (!obj) { return TopoDS_Shape(); @@ -220,11 +230,11 @@ Part::TopoShape ShapeBinder::buildShapeFromReferences(App::GeoFeature* obj, std: } if (shapes.size() == 1) { - //single subshape. Return directly. + // single subshape. Return directly. return shapes[0]; } - //multiple subshapes. Make a compound. + // multiple subshapes. Make a compound. BRep_Builder builder; TopoDS_Compound cmp; builder.MakeCompound(cmp); @@ -258,7 +268,11 @@ Part::TopoShape ShapeBinder::buildShapeFromReferences(App::GeoFeature* obj, std: return TopoDS_Shape(); } -void ShapeBinder::handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) +void ShapeBinder::handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop +) { // The type of Support was App::PropertyLinkSubList in the past if (prop == &Support && strcmp(TypeName, "App::PropertyLinkSubList") == 0) { @@ -273,10 +287,11 @@ void ShapeBinder::onSettingDocument() { App::Document* document = getDocument(); if (document) { - //NOLINTBEGIN - this->connectDocumentChangedObject = document->signalChangedObject.connect(std::bind - (&ShapeBinder::slotChangedObject, this, sp::_1, sp::_2)); - //NOLINTEND + // NOLINTBEGIN + this->connectDocumentChangedObject = document->signalChangedObject.connect( + std::bind(&ShapeBinder::slotChangedObject, this, sp::_1, sp::_2) + ); + // NOLINTEND } } @@ -334,55 +349,115 @@ SubShapeBinder::SubShapeBinder() Support.setStatus(App::Property::ReadOnly, true); ADD_PROPERTY_TYPE(Fuse, (false), "Base", App::Prop_None, "Fuse solids from bound shapes"); ADD_PROPERTY_TYPE(MakeFace, (true), "Base", App::Prop_None, "Create face using wires from bound shapes"); - ADD_PROPERTY_TYPE(Offset, (0.0), "Offsetting", App::Prop_None, "2D offset face or wires, 0.0 = no offset"); + ADD_PROPERTY_TYPE( + Offset, + (0.0), + "Offsetting", + App::Prop_None, + "2D offset face or wires, 0.0 = no offset" + ); ADD_PROPERTY_TYPE(OffsetJoinType, ((long)0), "Offsetting", App::Prop_None, "Arcs, Tangent, Intersection"); - static const char* JoinTypeEnum[] = { "Arcs", "Tangent", "Intersection", nullptr }; + static const char* JoinTypeEnum[] = {"Arcs", "Tangent", "Intersection", nullptr}; OffsetJoinType.setEnums(JoinTypeEnum); - ADD_PROPERTY_TYPE(OffsetFill, (false), "Offsetting", App::Prop_None, "True = make face between original wire and offset."); - ADD_PROPERTY_TYPE(OffsetOpenResult, (false), "Offsetting", App::Prop_None, "False = make closed offset from open wire."); - ADD_PROPERTY_TYPE(OffsetIntersection, (false), "Offsetting", App::Prop_None, "False = offset child wires independently."); + ADD_PROPERTY_TYPE( + OffsetFill, + (false), + "Offsetting", + App::Prop_None, + "True = make face between original wire and offset." + ); + ADD_PROPERTY_TYPE( + OffsetOpenResult, + (false), + "Offsetting", + App::Prop_None, + "False = make closed offset from open wire." + ); + ADD_PROPERTY_TYPE( + OffsetIntersection, + (false), + "Offsetting", + App::Prop_None, + "False = offset child wires independently." + ); ADD_PROPERTY_TYPE(ClaimChildren, (false), "Base", App::Prop_Output, "Claim linked object as children"); ADD_PROPERTY_TYPE(Relative, (true), "Base", App::Prop_None, "Enable relative sub-object binding"); - ADD_PROPERTY_TYPE(BindMode, ((long)0), "Base", App::Prop_None, + ADD_PROPERTY_TYPE( + BindMode, + ((long)0), + "Base", + App::Prop_None, "Synchronized: auto update binder shape on changed of bound object.\n" "Frozen: disable auto update, but can be updated manually using context menu.\n" - "Detached: copy the shape of bound object and then remove the binding immediately."); - ADD_PROPERTY_TYPE(PartialLoad, (false), "Base", App::Prop_None, + "Detached: copy the shape of bound object and then remove the binding immediately." + ); + ADD_PROPERTY_TYPE( + PartialLoad, + (false), + "Base", + App::Prop_None, "Enable partial loading, which disables auto loading of external document for" - "external bound object."); + "external bound object." + ); PartialLoad.setStatus(App::Property::PartialTrigger, true); - static const char* BindModeEnum[] = { "Synchronized", "Frozen", "Detached", nullptr }; + static const char* BindModeEnum[] = {"Synchronized", "Frozen", "Detached", nullptr}; BindMode.setEnums(BindModeEnum); - ADD_PROPERTY_TYPE(Context, (nullptr), "Base", App::Prop_Hidden, + ADD_PROPERTY_TYPE( + Context, + (nullptr), + "Base", + App::Prop_Hidden, "Stores the context of this binder. It is used for monitoring and auto updating\n" - "the relative placement of the bound shape"); + "the relative placement of the bound shape" + ); - static const char* BindCopyOnChangeEnum[] = { "Disabled", "Enabled", "Mutated", nullptr }; + static const char* BindCopyOnChangeEnum[] = {"Disabled", "Enabled", "Mutated", nullptr}; BindCopyOnChange.setEnums(BindCopyOnChangeEnum); - ADD_PROPERTY_TYPE(BindCopyOnChange, ((long)0), "Base", App::Prop_None, + ADD_PROPERTY_TYPE( + BindCopyOnChange, + ((long)0), + "Base", + App::Prop_None, "Disabled: disable copy on change.\n" "Enabled: duplicate properties from binding object that are marked with 'CopyOnChange'.\n" " Make internal copy of the object with any changed properties to obtain the\n" " shape of an alternative configuration\n" "Mutated: indicate the binder has already mutated by changing any properties marked with\n" " 'CopyOnChange'. Those properties will not longer be kept in sync between the\n" - " binder and the binding object"); + " binder and the binding object" + ); - ADD_PROPERTY_TYPE(Refine, (true), "Base", (App::PropertyType)(App::Prop_None), - "Refine shape (clean up redundant edges) after adding/subtracting"); + ADD_PROPERTY_TYPE( + Refine, + (true), + "Base", + (App::PropertyType)(App::Prop_None), + "Refine shape (clean up redundant edges) after adding/subtracting" + ); Context.setScope(App::LinkScope::Hidden); - ADD_PROPERTY_TYPE(_Version, (0), "Base", (App::PropertyType)( - App::Prop_Hidden | App::Prop_ReadOnly), ""); + ADD_PROPERTY_TYPE( + _Version, + (0), + "Base", + (App::PropertyType)(App::Prop_Hidden | App::Prop_ReadOnly), + "" + ); _CopiedLink.setScope(App::LinkScope::Hidden); - ADD_PROPERTY_TYPE(_CopiedLink, (nullptr), "Base", (App::PropertyType)( - App::Prop_Hidden | App::Prop_ReadOnly | App::Prop_NoPersist), ""); + ADD_PROPERTY_TYPE( + _CopiedLink, + (nullptr), + "Base", + (App::PropertyType)(App::Prop_Hidden | App::Prop_ReadOnly | App::Prop_NoPersist), + "" + ); } -SubShapeBinder::~SubShapeBinder() { +SubShapeBinder::~SubShapeBinder() +{ try { clearCopiedObjects(); } @@ -391,51 +466,66 @@ SubShapeBinder::~SubShapeBinder() { } } -void SubShapeBinder::setupObject() { +void SubShapeBinder::setupObject() +{ _Version.setValue(2); checkPropertyStatus(); } -App::DocumentObject* SubShapeBinder::getSubObject(const char* subname, PyObject** pyObj, - Base::Matrix4D* mat, bool transform, int depth) const +App::DocumentObject* SubShapeBinder::getSubObject( + const char* subname, + PyObject** pyObj, + Base::Matrix4D* mat, + bool transform, + int depth +) const { auto sobj = Part::Feature::getSubObject(subname, pyObj, mat, transform, depth); - if (sobj) + if (sobj) { return sobj; - if (Data::findElementName(subname) == subname) + } + if (Data::findElementName(subname) == subname) { return nullptr; + } const char* dot = strchr(subname, '.'); - if (!dot) + if (!dot) { return nullptr; + } App::GetApplication().checkLinkDepth(depth); std::string name(subname, dot - subname); for (auto& l : Support.getSubListValues()) { auto obj = l.getValue(); - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { continue; + } for (auto& sub : l.getSubValues()) { auto sobj = obj->getSubObject(sub.c_str()); - if (!sobj || !sobj->isAttachedToDocument()) + if (!sobj || !sobj->isAttachedToDocument()) { continue; - if (subname[0] == '$') { - if (sobj->Label.getStrValue() != name.c_str() + 1) - continue; } - else if (!boost::equals(sobj->getNameInDocument(), name)) + if (subname[0] == '$') { + if (sobj->Label.getStrValue() != name.c_str() + 1) { + continue; + } + } + else if (!boost::equals(sobj->getNameInDocument(), name)) { continue; + } name = Data::noElementName(sub.c_str()); name += dot + 1; - if (mat && transform) + if (mat && transform) { *mat *= Placement.getValue().toMatrix(); + } return obj->getSubObject(name.c_str(), pyObj, mat, true, depth + 1); } } return nullptr; } -void SubShapeBinder::setupCopyOnChange() { +void SubShapeBinder::setupCopyOnChange() +{ copyOnChangeConns.clear(); const auto& support = Support.getSubListValues(); @@ -461,40 +551,48 @@ void SubShapeBinder::setupCopyOnChange() { } auto linked = support.front().getValue(); - hasCopyOnChange = App::LinkBaseExtension::setupCopyOnChange(this, linked, - BindCopyOnChange.getValue() == 1 ? ©OnChangeConns : nullptr, hasCopyOnChange); + hasCopyOnChange = App::LinkBaseExtension::setupCopyOnChange( + this, + linked, + BindCopyOnChange.getValue() == 1 ? ©OnChangeConns : nullptr, + hasCopyOnChange + ); if (hasCopyOnChange) { copyOnChangeConns.emplace_back(linked->signalChanged.connect( [this](const App::DocumentObject&, const App::Property& prop) { - if (!prop.testStatus(App::Property::Output) - && !prop.testStatus(App::Property::PropOutput)) - { - if (!this->_CopiedObjs.empty()) { - FC_LOG("Clear binder " << getFullName() << " cache on change of " - << prop.getFullName()); - this->clearCopiedObjects(); + if (!prop.testStatus(App::Property::Output) + && !prop.testStatus(App::Property::PropOutput)) { + if (!this->_CopiedObjs.empty()) { + FC_LOG( + "Clear binder " << getFullName() << " cache on change of " + << prop.getFullName() + ); + this->clearCopiedObjects(); + } } } - } )); } } -void SubShapeBinder::clearCopiedObjects() { +void SubShapeBinder::clearCopiedObjects() +{ std::vector objs; objs.swap(_CopiedObjs); for (auto& o : objs) { auto obj = o.getObject(); - if (obj) + if (obj) { obj->getDocument()->removeObject(obj->getNameInDocument()); + } } _CopiedLink.setValue(nullptr); } -void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { +void SubShapeBinder::update(SubShapeBinder::UpdateOption options) +{ Part::TopoShape result; std::vector shapes; - std::vector > shapeOwners; + std::vector> shapeOwners; std::vector shapeMats; bool forced = (Shape.getValue().IsNull() || (options & UpdateForced)) ? true : false; @@ -503,8 +601,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { std::string errMsg; auto parent = Context.getValue(); std::string parentSub = Context.getSubName(false); - if (!Relative.getValue()) + if (!Relative.getValue()) { parent = nullptr; + } else { if (parent && parent->getSubObject(parentSub.c_str()) == this) { auto parents = parent->getParents(); @@ -513,8 +612,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { parentSub = parents.begin()->second + parentSub; } } - else + else { parent = nullptr; + } if (!parent && parentSub.empty()) { auto parents = getParents(); if (!parents.empty()) { @@ -522,8 +622,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { parentSub = parents.begin()->second; } } - if (parent && (parent != Context.getValue() || parentSub != Context.getSubName(false))) + if (parent && (parent != Context.getValue() || parentSub != Context.getSubName(false))) { Context.setValue(parent, parentSub.c_str()); + } } bool first = false; @@ -532,8 +633,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { for (auto& l : Support.getSubListValues()) { ++idx; auto obj = l.getValue(); - if (!obj || !obj->isAttachedToDocument()) + if (!obj || !obj->isAttachedToDocument()) { continue; + } auto res = mats.emplace(obj, Base::Matrix4D()); if (parent && res.second) { std::string resolvedSub = parentSub; @@ -542,17 +644,20 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { auto resolved = parent->resolveRelativeLink(resolvedSub, link, linkSub); if (!resolved) { if (!link) { - FC_WARN(getFullName() << " cannot resolve relative link of " - << parent->getFullName() << '.' << parentSub - << " -> " << obj->getFullName()); + FC_WARN( + getFullName() << " cannot resolve relative link of " << parent->getFullName() + << '.' << parentSub << " -> " << obj->getFullName() + ); } } else { Base::Matrix4D mat; auto sobj = resolved->getSubObject(resolvedSub.c_str(), nullptr, &mat); if (sobj != this) { - FC_LOG(getFullName() << " skip invalid parent " << resolved->getFullName() - << '.' << resolvedSub); + FC_LOG( + getFullName() + << " skip invalid parent " << resolved->getFullName() << '.' << resolvedSub + ); } else if (_Version.getValue() == 0) { // For existing legacy SubShapeBinder, we use its Placement @@ -577,14 +682,16 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { } } } - if (init) + if (init) { continue; + } App::DocumentObject* copied = nullptr; if (BindCopyOnChange.getValue() == 2 && Support.getSubListValues().size() == 1) { - if (!_CopiedObjs.empty()) + if (!_CopiedObjs.empty()) { copied = _CopiedObjs.front().getObject(); + } bool recomputeCopy = false; int copyerror = 0; @@ -592,22 +699,21 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { recomputeCopy = true; clearCopiedObjects(); - App::DocumentInitFlags initFlags { - .createView = false, - .temporary = true - }; + App::DocumentInitFlags initFlags {.createView = false, .temporary = true}; auto tmpDoc = App::GetApplication().newDocument("_tmp_binder", nullptr, initFlags); tmpDoc->setUndoMode(0); - auto objs = tmpDoc->copyObject({ obj }, true, true); + auto objs = tmpDoc->copyObject({obj}, true, true); if (!objs.empty()) { - for (auto it = objs.rbegin(); it != objs.rend(); ++it) + for (auto it = objs.rbegin(); it != objs.rend(); ++it) { _CopiedObjs.emplace_back(*it); + } copied = objs.back(); // IMPORTANT! must make a recomputation first before any // further change so that we can generate the correct // geometry element map. - if (!copied->recomputeFeature(true)) + if (!copied->recomputeFeature(true)) { copyerror = 1; + } } } @@ -616,63 +722,76 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { std::vector props; getPropertyList(props); // lambda for copying values of copy-on-change properties - const auto copyPropertyValues = [this, &recomputeCopy, &props, copied](const bool to_support) { - for (auto prop : props) { - if (!App::LinkBaseExtension::isCopyOnChangeProperty(this, *prop)) - continue; - // we only copy read-only and output properties from support to binder - if (!to_support && !(prop->testStatus(App::Property::Output) && prop->testStatus(App::Property::ReadOnly))) - continue; - auto p = copied->getPropertyByName(prop->getName()); - if (p && p->getContainer() == copied - && p->getTypeId() == prop->getTypeId() - && !p->isSame(*prop)) - { - recomputeCopy = true; - auto* const from = to_support ? prop : p; - auto* const to = to_support ? p : prop; + const auto copyPropertyValues = + [this, &recomputeCopy, &props, copied](const bool to_support) { + for (auto prop : props) { + if (!App::LinkBaseExtension::isCopyOnChangeProperty(this, *prop)) { + continue; + } + // we only copy read-only and output properties from support to binder + if (!to_support + && !( + prop->testStatus(App::Property::Output) + && prop->testStatus(App::Property::ReadOnly) + )) { + continue; + } + auto p = copied->getPropertyByName(prop->getName()); + if (p && p->getContainer() == copied + && p->getTypeId() == prop->getTypeId() && !p->isSame(*prop)) { + recomputeCopy = true; + auto* const from = to_support ? prop : p; + auto* const to = to_support ? p : prop; - std::unique_ptr pcopy(from->Copy()); - to->Paste(*pcopy); + std::unique_ptr pcopy(from->Copy()); + to->Paste(*pcopy); + } } - } - }; + }; copyPropertyValues(true); - if (recomputeCopy && !copied->recomputeFeature(true)) + if (recomputeCopy && !copied->recomputeFeature(true)) { copyerror = 2; - if (!copyerror) + } + if (!copyerror) { copyPropertyValues(false); + } } obj = copied; _CopiedLink.setValue(copied, l.getSubValues(false)); if (copyerror) { - FC_THROWM(Base::RuntimeError, - (copyerror == 1 ? "Initial copy failed." : "Copy on change failed.") - << " Please check report view for more details.\n" - "You can show temporary document to reveal the failed objects using\n" - "tree view context menu."); + FC_THROWM( + Base::RuntimeError, + ( + copyerror == 1 ? "Initial copy failed." : "Copy on change failed." + ) << " Please check report view for more details.\n" + "You can show temporary document to reveal the failed objects using\n" + "tree view context menu." + ); } } } const auto& subvals = copied ? _CopiedLink.getSubValues() : l.getSubValues(); std::set subs(subvals.begin(), subvals.end()); - int sidx = copied?-1:idx; + int sidx = copied ? -1 : idx; int subidx = -1; static std::string none; - if (subs.empty()) + if (subs.empty()) { subs.insert(none); - else if (subs.size() > 1) + } + else if (subs.size() > 1) { subs.erase(none); + } for (const auto& sub : subs) { ++subidx; try { - auto shape = Part::Feature::getTopoShape(obj, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - sub.c_str()); + auto shape = Part::Feature::getTopoShape( + obj, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + sub.c_str() + ); if (!shape.isNull()) { shapes.push_back(shape); shapeOwners.emplace_back(sidx, subidx); @@ -681,13 +800,13 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { } catch (Base::Exception& e) { e.reportException(); - FC_ERR(getFullName() << " failed to obtain shape from " - << obj->getFullName() << '.' << sub); + FC_ERR( + getFullName() << " failed to obtain shape from " << obj->getFullName() << '.' << sub + ); if (errMsg.empty()) { std::ostringstream ss; - ss << "Failed to obtain shape " << - obj->getFullName() << '.' - << Data::oldElementName(sub.c_str()); + ss << "Failed to obtain shape " << obj->getFullName() << '.' + << Data::oldElementName(sub.c_str()); errMsg = ss.str(); } } @@ -709,10 +828,12 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { if (!init) { if (!errMsg.empty()) { - if (!(options & UpdateInit)) + if (!(options & UpdateInit)) { FC_THROWM(Base::RuntimeError, errMsg); - if (!Shape.getValue().IsNull()) + } + if (!Shape.getValue().IsNull()) { return; + } } // If not forced, only rebuild when there is any change in @@ -721,37 +842,37 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { bool hit = true; for (auto& v : mats) { auto prop = freecad_cast( - getDynamicPropertyByName(cacheName(v.first))); + getDynamicPropertyByName(cacheName(v.first)) + ); if (!prop || prop->getValue() != v.second) { hit = false; break; } } - if (hit) + if (hit) { return; + } } std::ostringstream ss; int idx = -1; - for(auto &shape : shapes) { + for (auto& shape : shapes) { ++idx; - if(shape.Hasher - && shape.getElementMapSize() - && shape.Hasher != getDocument()->getStringHasher()) - { + if (shape.Hasher && shape.getElementMapSize() + && shape.Hasher != getDocument()->getStringHasher()) { ss.str(""); - ss << Data::POSTFIX_EXTERNAL_TAG - << Data::ComplexGeoData::elementMapPrefix() - << Part::OpCodes::Shapebinder << ':' << shapeOwners[idx].first - << ':' << shapeOwners[idx].second; - shape.reTagElementMap(-getID(), - getDocument()->getStringHasher(),ss.str().c_str()); + ss << Data::POSTFIX_EXTERNAL_TAG << Data::ComplexGeoData::elementMapPrefix() + << Part::OpCodes::Shapebinder << ':' << shapeOwners[idx].first << ':' + << shapeOwners[idx].second; + shape.reTagElementMap(-getID(), getDocument()->getStringHasher(), ss.str().c_str()); } - if (!shape.hasSubShape(TopAbs_FACE) && shape.hasSubShape(TopAbs_EDGE)) + if (!shape.hasSubShape(TopAbs_FACE) && shape.hasSubShape(TopAbs_EDGE)) { shape = shape.makeElementCopy(); + } } - if (shapes.size() == 1 && !Relative.getValue()) + if (shapes.size() == 1 && !Relative.getValue()) { shapes.back().setPlacement(Base::Placement()); + } else { for (size_t i = 0; i < shapes.size(); ++i) { auto& shape = shapes[i]; @@ -778,10 +899,12 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { std::vector solids; Part::TopoShape solid; for (auto& s : result.getSubTopoShapes(TopAbs_SOLID)) { - if (solid.isNull()) + if (solid.isNull()) { solid = s; - else + } + else { solids.push_back(s.getShape()); + } } if (!solids.empty()) { result = solid.fuse(solids); @@ -789,32 +912,33 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { } else if (!solid.isNull()) { // wrap the single solid in compound to keep its placement - result.makeElementCompound({ solid }); + result.makeElementCompound({solid}); fused = true; } } if (!fused && (MakeFace.getValue() || Offset.getValue() != 0.0) - && !result.hasSubShape(TopAbs_FACE) - && result.hasSubShape(TopAbs_EDGE)) - { + && !result.hasSubShape(TopAbs_FACE) && result.hasSubShape(TopAbs_EDGE)) { result = result.makeElementWires(); if (MakeFace.getValue()) { try { result = result.makeElementFace(nullptr); } - catch (...) {} + catch (...) { + } } } - if (!fused && result.hasSubShape(TopAbs_WIRE) - && Offset.getValue() != 0.0) { + if (!fused && result.hasSubShape(TopAbs_WIRE) && Offset.getValue() != 0.0) { try { - result = result.makeElementOffset2D(Offset.getValue(), - (Part::JoinType) OffsetJoinType.getValue() , - OffsetFill.getValue() ? Part::FillType::fill : Part::FillType::noFill, - OffsetOpenResult.getValue() ? Part::OpenResult::allowOpenResult : Part::OpenResult::noOpenResult, - OffsetIntersection.getValue()); + result = result.makeElementOffset2D( + Offset.getValue(), + (Part::JoinType)OffsetJoinType.getValue(), + OffsetFill.getValue() ? Part::FillType::fill : Part::FillType::noFill, + OffsetOpenResult.getValue() ? Part::OpenResult::allowOpenResult + : Part::OpenResult::noOpenResult, + OffsetIntersection.getValue() + ); } catch (...) { std::ostringstream msg; @@ -823,8 +947,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { } } - if (Refine.getValue()) + if (Refine.getValue()) { result = result.makeElementRefine(); + } result.setPlacement(Placement.getValue()); Shape.setValue(result); } @@ -832,8 +957,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { // collect transformation matrix cache entries std::unordered_set caches; for (const auto& name : getDynamicPropertyNames()) { - if (boost::starts_with(name, "Cache_")) + if (boost::starts_with(name, "Cache_")) { caches.emplace(name); + } } // update transformation matrix cache @@ -841,8 +967,9 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { const char* name = cacheName(v.first); auto prop = getDynamicPropertyByName(name); if (!prop || !prop->isDerivedFrom()) { - if (prop) + if (prop) { removeDynamicProperty(name); + } prop = addDynamicProperty("App::PropertyMatrix", name, "Cache", nullptr, 0, false, true); } caches.erase(name); @@ -854,14 +981,14 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { try { removeDynamicProperty(name.c_str()); } - catch (...) {} + catch (...) { + } } } -void SubShapeBinder::slotRecomputedObject(const App::DocumentObject& Obj) { - if (Context.getValue() == &Obj - && !this->testStatus(App::ObjectStatus::Recompute2)) - { +void SubShapeBinder::slotRecomputedObject(const App::DocumentObject& Obj) +{ + if (Context.getValue() == &Obj && !this->testStatus(App::ObjectStatus::Recompute2)) { try { update(); } @@ -871,19 +998,23 @@ void SubShapeBinder::slotRecomputedObject(const App::DocumentObject& Obj) { } } -App::DocumentObjectExecReturn* SubShapeBinder::execute() { +App::DocumentObjectExecReturn* SubShapeBinder::execute() +{ setupCopyOnChange(); - if (BindMode.getValue() == 0) + if (BindMode.getValue() == 0) { update(UpdateForced); + } return inherited::execute(); } -void SubShapeBinder::onDocumentRestored() { - if (_Version.getValue() < 2) +void SubShapeBinder::onDocumentRestored() +{ + if (_Version.getValue() < 2) { update(UpdateInit); + } inherited::onDocumentRestored(); } @@ -895,26 +1026,28 @@ void SubShapeBinder::collapseGeoChildren() // referencing the child. The purpose of this function is to remove any // intermediate Non group features in the object path to avoid unnecessary // dependencies. - if (Support.testStatus(App::Property::User3)) + if (Support.testStatus(App::Property::User3)) { return; + } - Base::ObjectStatusLocker - guard(App::Property::User3, &Support); + Base::ObjectStatusLocker guard(App::Property::User3, &Support); App::PropertyXLinkSubList::atomic_change guard2(Support, false); std::vector removes; - std::map > newVals; + std::map> newVals; std::ostringstream ss; - for(auto &l : Support.getSubListValues()) { + for (auto& l : Support.getSubListValues()) { auto obj = l.getValue(); - if(!obj || !obj->getNameInDocument()) + if (!obj || !obj->getNameInDocument()) { continue; + } auto subvals = l.getSubValues(); - if (subvals.empty()) + if (subvals.empty()) { continue; + } bool touched = false; - for (auto itSub=subvals.begin(); itSub!=subvals.end();) { - auto &sub = *itSub; + for (auto itSub = subvals.begin(); itSub != subvals.end();) { + auto& sub = *itSub; App::SubObjectT sobjT(obj, sub.c_str()); if (sobjT.normalize(App::SubObjectT::NormalizeOption::KeepSubName)) { touched = true; @@ -928,40 +1061,48 @@ void SubShapeBinder::collapseGeoChildren() } ++itSub; } - if (touched) + if (touched) { removes.push_back(obj); + } if (!subvals.empty() && touched) { - auto &newSubs = newVals[obj]; - if (newSubs.empty()) + auto& newSubs = newVals[obj]; + if (newSubs.empty()) { newSubs = std::move(subvals); - else - newSubs.insert(newSubs.end(), - std::make_move_iterator(subvals.begin()), - std::make_move_iterator(subvals.end())); + } + else { + newSubs.insert( + newSubs.end(), + std::make_move_iterator(subvals.begin()), + std::make_move_iterator(subvals.end()) + ); + } } } - if (removes.size() || newVals.size()) + if (removes.size() || newVals.size()) { guard2.aboutToChange(); - for (auto obj : removes) + } + for (auto obj : removes) { Support.removeValue(obj); - if (newVals.size()) + } + if (newVals.size()) { setLinks(std::move(newVals)); + } } -void SubShapeBinder::onChanged(const App::Property* prop) { +void SubShapeBinder::onChanged(const App::Property* prop) +{ if (prop == &Context || prop == &Relative) { if (!Context.getValue() || !Relative.getValue()) { connRecomputedObj.disconnect(); } - else if (contextDoc != Context.getValue()->getDocument() - || !connRecomputedObj.connected()) - { - //NOLINTBEGIN + else if (contextDoc != Context.getValue()->getDocument() || !connRecomputedObj.connected()) { + // NOLINTBEGIN contextDoc = Context.getValue()->getDocument(); connRecomputedObj = contextDoc->signalRecomputedObject.connect( - std::bind(&SubShapeBinder::slotRecomputedObject, this, sp::_1)); - //NOLINTEND + std::bind(&SubShapeBinder::slotRecomputedObject, this, sp::_1) + ); + // NOLINTEND } } else if (!isRestoring()) { @@ -971,45 +1112,53 @@ void SubShapeBinder::onChanged(const App::Property* prop) { setupCopyOnChange(); if (!Support.getSubListValues().empty()) { update(); - if (BindMode.getValue() == 2) + if (BindMode.getValue() == 2) { Support.setValue(nullptr); + } } } else if (prop == &BindCopyOnChange) { setupCopyOnChange(); } else if (prop == &BindMode) { - if (BindMode.getValue() == 2) + if (BindMode.getValue() == 2) { Support.setValue(nullptr); - else if (BindMode.getValue() == 0) + } + else if (BindMode.getValue() == 0) { update(); + } checkPropertyStatus(); } else if (prop == &PartialLoad) { checkPropertyStatus(); } - else if (prop && !prop->testStatus(App::Property::User3)) + else if (prop && !prop->testStatus(App::Property::User3)) { checkCopyOnChange(*prop); + } } inherited::onChanged(prop); } -void SubShapeBinder::checkCopyOnChange(const App::Property& prop) { - if (BindCopyOnChange.getValue() != 1 - || getDocument()->isPerformingTransaction() +void SubShapeBinder::checkCopyOnChange(const App::Property& prop) +{ + if (BindCopyOnChange.getValue() != 1 || getDocument()->isPerformingTransaction() || !App::LinkBaseExtension::isCopyOnChangeProperty(this, prop) - || Support.getSubListValues().size() != 1) + || Support.getSubListValues().size() != 1) { return; + } auto linked = Support.getSubListValues().front().getValue(); - if (!linked) + if (!linked) { return; + } auto linkedProp = linked->getPropertyByName(prop.getName()); - if (linkedProp && linkedProp->getTypeId() == prop.getTypeId() && !linkedProp->isSame(prop)) + if (linkedProp && linkedProp->getTypeId() == prop.getTypeId() && !linkedProp->isSame(prop)) { BindCopyOnChange.setValue(2); + } } -void SubShapeBinder::checkPropertyStatus() { +void SubShapeBinder::checkPropertyStatus() +{ Support.setAllowPartial(PartialLoad.getValue()); // Make Shape transient can reduce some file size, and maybe reduce file @@ -1019,7 +1168,10 @@ void SubShapeBinder::checkPropertyStatus() { // Shape.setStatus(App::Property::Transient, !PartialLoad.getValue() && BindMode.getValue()==0); } -void SubShapeBinder::setLinks(std::map >&& values, bool reset) +void SubShapeBinder::setLinks( + std::map>&& values, + bool reset +) { if (values.empty()) { if (reset) { @@ -1032,10 +1184,12 @@ void SubShapeBinder::setLinks(std::mapisAttachedToDocument()) + if (!v.first || !v.first->isAttachedToDocument()) { FC_THROWM(Base::ValueError, "Invalid document object"); - if (inSet.find(v.first) != inSet.end()) + } + if (inSet.find(v.first) != inSet.end()) { FC_THROWM(Base::ValueError, "Cyclic reference to " << v.first->getFullName()); + } if (v.second.empty()) { v.second.emplace_back(""); @@ -1050,14 +1204,16 @@ void SubShapeBinder::setLinks(std::mapempty() - || (it->back() == '.' && boost::starts_with(sub, *it))) - { + else if (it->empty() || (it->back() == '.' && boost::starts_with(sub, *it))) { FC_LOG("Remove whole subname " << *it << " because of " << sub); it = subs.erase(it); } - else + else { ++it; + } } } subs.insert(subs.end(), s.begin(), s.end()); @@ -1105,7 +1262,10 @@ void SubShapeBinder::setLinks(std::map const char* PartDesign::SubShapeBinderPython::getViewProviderName() const { - return "PartDesignGui::ViewProviderSubShapeBinderPython"; - } - template class PartDesignExport FeaturePythonT; +namespace App +{ +PROPERTY_SOURCE_TEMPLATE(PartDesign::SubShapeBinderPython, PartDesign::SubShapeBinder) +template<> +const char* PartDesign::SubShapeBinderPython::getViewProviderName() const +{ + return "PartDesignGui::ViewProviderSubShapeBinderPython"; } - +template class PartDesignExport FeaturePythonT; +} // namespace App diff --git a/src/Mod/PartDesign/App/ShapeBinder.h b/src/Mod/PartDesign/App/ShapeBinder.h index 73c697e1af..9bfa21a439 100644 --- a/src/Mod/PartDesign/App/ShapeBinder.h +++ b/src/Mod/PartDesign/App/ShapeBinder.h @@ -42,7 +42,7 @@ namespace PartDesign */ // TODO Add better documentation (2015-09-11, Fat-Zer) -class PartDesignExport ShapeBinder : public Part::Feature +class PartDesignExport ShapeBinder: public Part::Feature { PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::ShapeBinder); @@ -50,20 +50,29 @@ public: ShapeBinder(); ~ShapeBinder() override; - App::PropertyLinkSubListGlobal Support; + App::PropertyLinkSubListGlobal Support; App::PropertyBool TraceSupport; - static void getFilteredReferences(const App::PropertyLinkSubList* prop, App::GeoFeature*& object, std::vector< std::string >& subobjects); - static Part::TopoShape buildShapeFromReferences(App::GeoFeature* obj, std::vector< std::string > subs); + static void getFilteredReferences( + const App::PropertyLinkSubList* prop, + App::GeoFeature*& object, + std::vector& subobjects + ); + static Part::TopoShape buildShapeFromReferences(App::GeoFeature* obj, std::vector subs); - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderShapeBinder"; } protected: Part::TopoShape updatedShape() const; bool hasPlacementChanged() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; short int mustExecute() const override; App::DocumentObjectExecReturn* execute() override; void onChanged(const App::Property* prop) override; @@ -76,19 +85,22 @@ private: Connection connectDocumentChangedObject; }; -class PartDesignExport SubShapeBinder : public Part::Feature { +class PartDesignExport SubShapeBinder: public Part::Feature +{ PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubShapeBinder); + public: using inherited = Part::Feature; SubShapeBinder(); ~SubShapeBinder() override; - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "PartDesignGui::ViewProviderSubShapeBinder"; } - void setLinks(std::map > &&values, bool reset=false); + void setLinks(std::map>&& values, bool reset = false); App::PropertyXLinkSubList Support; App::PropertyBool ClaimChildren; @@ -107,34 +119,47 @@ public: App::PropertyBool OffsetOpenResult; App::PropertyBool OffsetIntersection; - enum UpdateOption { + enum UpdateOption + { UpdateNone = 0, UpdateInit = 1, UpdateForced = 2, }; void update(UpdateOption options = UpdateNone); - int canLoadPartial() const override { - return PartialLoad.getValue()?1:0; + int canLoadPartial() const override + { + return PartialLoad.getValue() ? 1 : 0; } - bool canLinkProperties() const override {return false;} + bool canLinkProperties() const override + { + return false; + } - App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj=nullptr, - Base::Matrix4D *mat=nullptr, bool transform=true, int depth=0) const override; + App::DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj = nullptr, + Base::Matrix4D* mat = nullptr, + bool transform = true, + int depth = 0 + ) const override; protected: App::DocumentObjectExecReturn* execute() override; - void onChanged(const App::Property *prop) override; + void onChanged(const App::Property* prop) override; void handleChangedPropertyType( - Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; void onDocumentRestored() override; void setupObject() override; void setupCopyOnChange(); - void checkCopyOnChange(const App::Property &prop); + void checkCopyOnChange(const App::Property& prop); void clearCopiedObjects(); void checkPropertyStatus(); @@ -145,7 +170,7 @@ protected: using Connection = boost::signals2::scoped_connection; Connection connRecomputedObj; - App::Document *contextDoc = nullptr; + App::Document* contextDoc = nullptr; std::vector copyOnChangeConns; bool hasCopyOnChange = true; @@ -156,7 +181,7 @@ protected: using SubShapeBinderPython = App::FeaturePythonT; -} //namespace PartDesign +} // namespace PartDesign -#endif // PARTDESIGN_DATUMSHAPE_H +#endif // PARTDESIGN_DATUMSHAPE_H diff --git a/src/Mod/PartDesign/Gui/Command.cpp b/src/Mod/PartDesign/Gui/Command.cpp index 15e770bdf9..2fa11384df 100644 --- a/src/Mod/PartDesign/Gui/Command.cpp +++ b/src/Mod/PartDesign/Gui/Command.cpp @@ -21,15 +21,14 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -69,7 +68,7 @@ // TODO Remove this header after fixing code so it won;t be needed here (2015-10-20, Fat-Zer) #include "ui_DlgReference.h" -FC_LOG_LEVEL_INIT("PartDesign",true,true) +FC_LOG_LEVEL_INIT("PartDesign", true, true) using namespace std; using namespace Attacher; @@ -86,67 +85,96 @@ using namespace Attacher; * @param name (input). Is used to generate new name for an object, and to fill undo messages. * */ -void UnifiedDatumCommand(Gui::Command &cmd, Base::Type type, std::string name) +void UnifiedDatumCommand(Gui::Command& cmd, Base::Type type, std::string name) { - try{ - std::string fullTypeName (type.getName()); + try { + std::string fullTypeName(type.getName()); App::PropertyLinkSubList support; cmd.getSelection().getAsPropertyLinkSubList(support); bool bEditSelected = false; - if (support.getSize() == 1 && support.getValue() ) { - if (support.getValue()->isDerivedFrom(type)) + if (support.getSize() == 1 && support.getValue()) { + if (support.getValue()->isDerivedFrom(type)) { bEditSelected = true; + } } - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */ true); if (bEditSelected) { - std::string tmp = std::string("Edit ")+name; + std::string tmp = std::string("Edit ") + name; cmd.openCommand(tmp.c_str()); - PartDesignGui::setEdit(support.getValue(),pcActiveBody); - } else if (pcActiveBody) { + PartDesignGui::setEdit(support.getValue(), pcActiveBody); + } + else if (pcActiveBody) { // TODO Check how this will work outside of a body (2015-10-20, Fat-Zer) std::string FeatName = cmd.getUniqueObjectName(name.c_str(), pcActiveBody); - std::string tmp = std::string("Create ")+name; + std::string tmp = std::string("Create ") + name; cmd.openCommand(tmp.c_str()); - FCMD_OBJ_CMD(pcActiveBody,"newObject('" << fullTypeName << "','" << FeatName << "')"); + FCMD_OBJ_CMD(pcActiveBody, "newObject('" << fullTypeName << "','" << FeatName << "')"); // remove the body from links in case it's selected as // otherwise a cyclic dependency will be created support.removeValue(pcActiveBody); auto Feat = pcActiveBody->getDocument()->getObject(FeatName.c_str()); - if (!Feat) + if (!Feat) { return; + } - //test if current selection fits a mode. + // test if current selection fits a mode. if (support.getSize() > 0) { Part::AttachExtension* pcDatum = Feat->getExtensionByType(); pcDatum->attacher().setReferences(support); SuggestResult sugr; pcDatum->attacher().suggestMapModes(sugr); if (sugr.message == Attacher::SuggestResult::srOK) { - //fits some mode. Populate AttachmentSupport property. - FCMD_OBJ_CMD(Feat,"AttachmentSupport = " << support.getPyReprString()); - FCMD_OBJ_CMD(Feat,"MapMode = '" << AttachEngine::getModeName(sugr.bestFitMode) << "'"); - } else { - QMessageBox::information(Gui::getMainWindow(),QObject::tr("Invalid selection"), QObject::tr("There are no attachment modes that fit selected objects. Select something else.")); + // fits some mode. Populate AttachmentSupport property. + FCMD_OBJ_CMD(Feat, "AttachmentSupport = " << support.getPyReprString()); + FCMD_OBJ_CMD( + Feat, + "MapMode = '" << AttachEngine::getModeName(sugr.bestFitMode) << "'" + ); + } + else { + QMessageBox::information( + Gui::getMainWindow(), + QObject::tr("Invalid selection"), + QObject::tr("There are no attachment modes that fit selected objects. Select something else.") + ); } } - cmd.doCommand(Gui::Command::Doc,"App.activeDocument().recompute()"); // recompute the feature based on its references - PartDesignGui::setEdit(Feat,pcActiveBody); - } else { - QMessageBox::warning(Gui::getMainWindow(),QObject::tr("Error"), QObject::tr("There is no active body. Please activate a body before inserting a datum entity.")); + cmd.doCommand( + Gui::Command::Doc, + "App.activeDocument().recompute()" + ); // recompute the feature based on its references + PartDesignGui::setEdit(Feat, pcActiveBody); } - } catch (Base::Exception &e) { - QMessageBox::warning(Gui::getMainWindow(),QObject::tr("Error"),QApplication::translate("Exception", e.what())); - } catch (Standard_Failure &e) { - QMessageBox::warning(Gui::getMainWindow(),QObject::tr("Error"),QString::fromLatin1(e.GetMessageString())); + else { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Error"), + QObject::tr("There is no active body. Please activate a body before inserting a datum entity.") + ); + } + } + catch (Base::Exception& e) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Error"), + QApplication::translate("Exception", e.what()) + ); + } + catch (Standard_Failure& e) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Error"), + QString::fromLatin1(e.GetMessageString()) + ); } } @@ -155,113 +183,121 @@ void UnifiedDatumCommand(Gui::Command &cmd, Base::Type type, std::string name) DEF_STD_CMD_A(CmdPartDesignPlane) CmdPartDesignPlane::CmdPartDesignPlane() - :Command("PartDesign_Plane") + : Command("PartDesign_Plane") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Datum Plane"); - sToolTipText = QT_TR_NOOP("Creates a new datum plane"); - sWhatsThis = "PartDesign_Plane"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Plane"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Datum Plane"); + sToolTipText = QT_TR_NOOP("Creates a new datum plane"); + sWhatsThis = "PartDesign_Plane"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Plane"; } void CmdPartDesignPlane::activated(int iMsg) { Q_UNUSED(iMsg); - UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Plane"),"DatumPlane"); + UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Plane"), "DatumPlane"); } bool CmdPartDesignPlane::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } DEF_STD_CMD_A(CmdPartDesignLine) CmdPartDesignLine::CmdPartDesignLine() - :Command("PartDesign_Line") + : Command("PartDesign_Line") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Datum Line"); - sToolTipText = QT_TR_NOOP("Creates a new datum line"); - sWhatsThis = "PartDesign_Line"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Line"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Datum Line"); + sToolTipText = QT_TR_NOOP("Creates a new datum line"); + sWhatsThis = "PartDesign_Line"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Line"; } void CmdPartDesignLine::activated(int iMsg) { Q_UNUSED(iMsg); - UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Line"),"DatumLine"); + UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Line"), "DatumLine"); } bool CmdPartDesignLine::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } DEF_STD_CMD_A(CmdPartDesignPoint) CmdPartDesignPoint::CmdPartDesignPoint() - :Command("PartDesign_Point") + : Command("PartDesign_Point") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Datum Point"); - sToolTipText = QT_TR_NOOP("Creates a new datum point"); - sWhatsThis = "PartDesign_Point"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Point"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Datum Point"); + sToolTipText = QT_TR_NOOP("Creates a new datum point"); + sWhatsThis = "PartDesign_Point"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Point"; } void CmdPartDesignPoint::activated(int iMsg) { Q_UNUSED(iMsg); - UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Point"),"DatumPoint"); + UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Point"), "DatumPoint"); } bool CmdPartDesignPoint::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } DEF_STD_CMD_A(CmdPartDesignCS) CmdPartDesignCS::CmdPartDesignCS() - :Command("PartDesign_CoordinateSystem") + : Command("PartDesign_CoordinateSystem") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Local Coordinate System"); - sToolTipText = QT_TR_NOOP("Creates a new local coordinate system"); - sWhatsThis = "PartDesign_CoordinateSystem"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_CoordinateSystem"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Local Coordinate System"); + sToolTipText = QT_TR_NOOP("Creates a new local coordinate system"); + sWhatsThis = "PartDesign_CoordinateSystem"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_CoordinateSystem"; } void CmdPartDesignCS::activated(int iMsg) { Q_UNUSED(iMsg); - UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::CoordinateSystem"),"Local_CS"); + UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::CoordinateSystem"), "Local_CS"); } bool CmdPartDesignCS::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== @@ -271,15 +307,15 @@ bool CmdPartDesignCS::isActive() DEF_STD_CMD_A(CmdPartDesignShapeBinder) CmdPartDesignShapeBinder::CmdPartDesignShapeBinder() - :Command("PartDesign_ShapeBinder") + : Command("PartDesign_ShapeBinder") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Shape Binder"); - sToolTipText = QT_TR_NOOP("Creates a new shape binder"); - sWhatsThis = "PartDesign_ShapeBinder"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_ShapeBinder"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Shape Binder"); + sToolTipText = QT_TR_NOOP("Creates a new shape binder"); + sWhatsThis = "PartDesign_ShapeBinder"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_ShapeBinder"; } void CmdPartDesignShapeBinder::activated(int iMsg) @@ -289,45 +325,49 @@ void CmdPartDesignShapeBinder::activated(int iMsg) getSelection().getAsPropertyLinkSubList(support); bool bEditSelected = false; - if (support.getSize() == 1 && support.getValue() ){ - if (support.getValue()->isDerivedFrom()) + if (support.getSize() == 1 && support.getValue()) { + if (support.getValue()->isDerivedFrom()) { bEditSelected = true; + } } if (bEditSelected) { openCommand(QT_TRANSLATE_NOOP("Command", "Edit Shape Binder")); PartDesignGui::setEdit(support.getValue()); - } else { - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */true); - if (!pcActiveBody) + } + else { + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */ true); + if (!pcActiveBody) { return; + } - std::string FeatName = getUniqueObjectName("ShapeBinder",pcActiveBody); + std::string FeatName = getUniqueObjectName("ShapeBinder", pcActiveBody); openCommand(QT_TRANSLATE_NOOP("Command", "Create Shape Binder")); - FCMD_OBJ_CMD(pcActiveBody,"newObject('PartDesign::ShapeBinder','" << FeatName << "')"); + FCMD_OBJ_CMD(pcActiveBody, "newObject('PartDesign::ShapeBinder','" << FeatName << "')"); // remove the body from links in case it's selected as // otherwise a cyclic dependency will be created support.removeValue(pcActiveBody); auto Feat = pcActiveBody->getObject(FeatName.c_str()); - if (!Feat) + if (!Feat) { return; + } - //test if current selection fits a mode. + // test if current selection fits a mode. if (support.getSize() > 0) { - FCMD_OBJ_CMD(Feat,"Support = " << support.getPyReprString()); + FCMD_OBJ_CMD(Feat, "Support = " << support.getPyReprString()); } updateActive(); - PartDesignGui::setEdit(Feat,pcActiveBody); + PartDesignGui::setEdit(Feat, pcActiveBody); } // TODO do a proper error processing (2015-09-11, Fat-Zer) } bool CmdPartDesignShapeBinder::isActive() { - return hasActiveDocument (); + return hasActiveDocument(); } //=========================================================================== @@ -337,80 +377,102 @@ bool CmdPartDesignShapeBinder::isActive() DEF_STD_CMD_A(CmdPartDesignSubShapeBinder) CmdPartDesignSubShapeBinder::CmdPartDesignSubShapeBinder() - :Command("PartDesign_SubShapeBinder") + : Command("PartDesign_SubShapeBinder") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Sub-Shape Binder"); - sToolTipText = QT_TR_NOOP("Creates a reference to geometry from one or more objects, allowing it to be used inside or outside a body. It tracks relative placements, supports multiple geometry types (solids, faces, edges, vertices), and can work with objects in the same or external documents."); - sWhatsThis = "PartDesign_SubShapeBinder"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_SubShapeBinder"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Sub-Shape Binder"); + sToolTipText = QT_TR_NOOP( + "Creates a reference to geometry from one or more objects, allowing it to be used inside " + "or outside a body. It tracks relative placements, supports multiple geometry types " + "(solids, faces, edges, vertices), and can work with objects in the same or external " + "documents." + ); + sWhatsThis = "PartDesign_SubShapeBinder"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_SubShapeBinder"; } void CmdPartDesignSubShapeBinder::activated(int iMsg) { Q_UNUSED(iMsg); - App::DocumentObject *parent = nullptr; + App::DocumentObject* parent = nullptr; std::string parentSub; - std::map > values; - for (auto &sel : Gui::Selection().getCompleteSelection(Gui::ResolveMode::NoResolve)) { - if (!sel.pObject) continue; - auto &subs = values[sel.pObject]; - if (sel.SubName && sel.SubName[0]) + std::map> values; + for (auto& sel : Gui::Selection().getCompleteSelection(Gui::ResolveMode::NoResolve)) { + if (!sel.pObject) { + continue; + } + auto& subs = values[sel.pObject]; + if (sel.SubName && sel.SubName[0]) { subs.emplace_back(sel.SubName); + } } std::string FeatName; - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(false,true,true,&parent,&parentSub); - FeatName = getUniqueObjectName("Binder",pcActiveBody); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(false, true, true, &parent, &parentSub); + FeatName = getUniqueObjectName("Binder", pcActiveBody); if (parent) { decltype(values) links; - for (auto &v : values) { - App::DocumentObject *obj = v.first; + for (auto& v : values) { + App::DocumentObject* obj = v.first; if (obj != parent) { - auto &subs = links[obj]; - subs.insert(subs.end(),v.second.begin(),v.second.end()); + auto& subs = links[obj]; + subs.insert(subs.end(), v.second.begin(), v.second.end()); continue; } - for (auto &sub : v.second) { + for (auto& sub : v.second) { auto link = obj; auto linkSub = parentSub; - parent->resolveRelativeLink(linkSub,link,sub); - if (link && link != pcActiveBody) + parent->resolveRelativeLink(linkSub, link, sub); + if (link && link != pcActiveBody) { links[link].push_back(sub); + } } } values = std::move(links); } - PartDesign::SubShapeBinder *binder = nullptr; + PartDesign::SubShapeBinder* binder = nullptr; try { openCommand(QT_TRANSLATE_NOOP("Command", "Create Sub-Shape Binder")); if (pcActiveBody) { - FCMD_OBJ_CMD(pcActiveBody,"newObject('PartDesign::SubShapeBinder','" << FeatName << "')"); - binder = dynamic_cast(pcActiveBody->getObject(FeatName.c_str())); - } else { - doCommand(Command::Doc, - "App.ActiveDocument.addObject('PartDesign::SubShapeBinder','%s')",FeatName.c_str()); + FCMD_OBJ_CMD(pcActiveBody, "newObject('PartDesign::SubShapeBinder','" << FeatName << "')"); binder = dynamic_cast( - App::GetApplication().getActiveDocument()->getObject(FeatName.c_str())); + pcActiveBody->getObject(FeatName.c_str()) + ); } - if (!binder) + else { + doCommand( + Command::Doc, + "App.ActiveDocument.addObject('PartDesign::SubShapeBinder','%s')", + FeatName.c_str() + ); + binder = dynamic_cast( + App::GetApplication().getActiveDocument()->getObject(FeatName.c_str()) + ); + } + if (!binder) { return; + } binder->setLinks(std::move(values)); updateActive(); commitCommand(); - } catch (Base::Exception &e) { + } + catch (Base::Exception& e) { e.reportException(); - QMessageBox::critical(Gui::getMainWindow(), - QObject::tr("Sub-shape binder"), QApplication::translate("Exception", e.what())); + QMessageBox::critical( + Gui::getMainWindow(), + QObject::tr("Sub-shape binder"), + QApplication::translate("Exception", e.what()) + ); abortCommand(); } } -bool CmdPartDesignSubShapeBinder::isActive() { +bool CmdPartDesignSubShapeBinder::isActive() +{ return hasActiveDocument(); } @@ -421,22 +483,23 @@ bool CmdPartDesignSubShapeBinder::isActive() { DEF_STD_CMD_A(CmdPartDesignClone) CmdPartDesignClone::CmdPartDesignClone() - :Command("PartDesign_Clone") + : Command("PartDesign_Clone") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Clone"); - sToolTipText = QT_TR_NOOP("Copies a solid object parametrically as the base feature of a new body"); - sWhatsThis = "PartDesign_Clone"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Clone"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Clone"); + sToolTipText = QT_TR_NOOP("Copies a solid object parametrically as the base feature of a new body"); + sWhatsThis = "PartDesign_Clone"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Clone"; } void CmdPartDesignClone::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector objs = getSelection().getObjectsOfType - (Part::Feature::getClassTypeId()); + std::vector objs = getSelection().getObjectsOfType( + Part::Feature::getClassTypeId() + ); if (objs.size() == 1) { // As suggested in https://forum.freecad.org/viewtopic.php?f=3&t=25265&p=198547#p207336 // put the clone into its own new body. @@ -450,35 +513,36 @@ void CmdPartDesignClone::activated(int iMsg) std::string bodyName = getUniqueObjectName("Body", obj); // Create body and clone - Gui::cmdAppDocument(obj, std::stringstream() - << "addObject('PartDesign::Body','" << bodyName << "')"); - Gui::cmdAppDocument(obj, std::stringstream() - << "addObject('PartDesign::FeatureBase','" << cloneName << "')"); + Gui::cmdAppDocument( + obj, + std::stringstream() << "addObject('PartDesign::Body','" << bodyName << "')" + ); + Gui::cmdAppDocument( + obj, + std::stringstream() << "addObject('PartDesign::FeatureBase','" << cloneName << "')" + ); auto bodyObj = obj->getDocument()->getObject(bodyName.c_str()); auto cloneObj = obj->getDocument()->getObject(cloneName.c_str()); - Base::Reference hGrp = App::GetApplication() - .GetUserParameter() - .GetGroup("BaseApp/Preferences/Mod/PartDesign"); + Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup( + "BaseApp/Preferences/Mod/PartDesign" + ); bool allowCompound = hGrp->GetBool("AllowCompoundDefault", true); // In the first step set the group link and tip of the body - Gui::cmdAppObject(bodyObj, std::stringstream() - << "Group = [" << getObjectCmd(cloneObj) << "]"); - Gui::cmdAppObject(bodyObj, std::stringstream() - << "Tip = " << getObjectCmd(cloneObj)); - Gui::cmdAppObject(bodyObj, std::stringstream() - << "AllowCompound = " << (allowCompound ? "True" : "False")); + Gui::cmdAppObject(bodyObj, std::stringstream() << "Group = [" << getObjectCmd(cloneObj) << "]"); + Gui::cmdAppObject(bodyObj, std::stringstream() << "Tip = " << getObjectCmd(cloneObj)); + Gui::cmdAppObject( + bodyObj, + std::stringstream() << "AllowCompound = " << (allowCompound ? "True" : "False") + ); // In the second step set the link of the base feature - Gui::cmdAppObject(cloneObj, std::stringstream() - << "BaseFeature = " << objCmd); - Gui::cmdAppObject(cloneObj, std::stringstream() - << "Placement = " << objCmd << ".Placement"); - Gui::cmdAppObject(cloneObj, std::stringstream() - << "setEditorMode('Placement', 0)"); + Gui::cmdAppObject(cloneObj, std::stringstream() << "BaseFeature = " << objCmd); + Gui::cmdAppObject(cloneObj, std::stringstream() << "Placement = " << objCmd << ".Placement"); + Gui::cmdAppObject(cloneObj, std::stringstream() << "setEditorMode('Placement', 0)"); updateActive(); copyVisual(cloneObj, "ShapeAppearance", obj); @@ -503,15 +567,15 @@ bool CmdPartDesignClone::isActive() DEF_STD_CMD_A(CmdPartDesignNewSketch) CmdPartDesignNewSketch::CmdPartDesignNewSketch() - :Command("PartDesign_NewSketch") + : Command("PartDesign_NewSketch") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("New Sketch"); - sToolTipText = QT_TR_NOOP("Creates a new sketch"); - sWhatsThis = "PartDesign_NewSketch"; - sStatusTip = sToolTipText; - sPixmap = "Sketcher_NewSketch"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("New Sketch"); + sToolTipText = QT_TR_NOOP("Creates a new sketch"); + sWhatsThis = "PartDesign_NewSketch"; + sStatusTip = sToolTipText; + sPixmap = "Sketcher_NewSketch"; } @@ -524,42 +588,52 @@ void CmdPartDesignNewSketch::activated(int iMsg) bool CmdPartDesignNewSketch::isActive() { - if (getActiveGuiDocument()) + if (getActiveGuiDocument()) { return true; - else + } + else { return false; + } } //=========================================================================== // Common utility functions for all features creating solids //=========================================================================== -static void finishFeature(const Gui::Command* cmd, App::DocumentObject *feature, - App::DocumentObject* prevSolidFeature = nullptr, - const bool hidePrevSolid = true, - const bool updateDocument = true) +static void finishFeature( + const Gui::Command* cmd, + App::DocumentObject* feature, + App::DocumentObject* prevSolidFeature = nullptr, + const bool hidePrevSolid = true, + const bool updateDocument = true +) { - PartDesign::Body *activeBody; + PartDesign::Body* activeBody; if (prevSolidFeature) { // insert into the same body as the given previous one - activeBody = PartDesignGui::getBodyFor(prevSolidFeature, /*messageIfNot = */false); - } else { - activeBody = PartDesignGui::getBody(/*messageIfNot = */false); + activeBody = PartDesignGui::getBodyFor(prevSolidFeature, /*messageIfNot = */ false); + } + else { + activeBody = PartDesignGui::getBody(/*messageIfNot = */ false); } - if (hidePrevSolid && prevSolidFeature) + if (hidePrevSolid && prevSolidFeature) { FCMD_OBJ_HIDE(prevSolidFeature); + } - if (updateDocument) + if (updateDocument) { cmd->updateActive(); + } auto base = dynamic_cast(feature); - if (base) + if (base) { base = dynamic_cast(base->getBaseObject(true)); - App::DocumentObject *obj = base; - if (!obj) + } + App::DocumentObject* obj = base; + if (!obj) { obj = activeBody; + } // Do this before calling setEdit to avoid to override the 'Shape preview' mode (#0003621) if (obj) { @@ -571,7 +645,7 @@ static void finishFeature(const Gui::Command* cmd, App::DocumentObject *feature, } PartDesignGui::setEdit(feature, activeBody); - cmd->doCommand(cmd->Gui,"Gui.Selection.clearSelection()"); + cmd->doCommand(cmd->Gui, "Gui.Selection.clearSelection()"); } //=========================================================================== @@ -581,16 +655,18 @@ static void finishFeature(const Gui::Command* cmd, App::DocumentObject *feature, // Take a list of Part2DObjects and classify them for creating a // ProfileBased feature. FirstFreeSketch is the first free sketch in the same body // or sketches.end() if non available. The returned number is the amount of free sketches -unsigned validateSketches(std::vector& sketches, - std::vector& status, - std::vector::iterator& firstFreeSketch) +unsigned validateSketches( + std::vector& sketches, + std::vector& status, + std::vector::iterator& firstFreeSketch +) { // TODO Review the function for non-part bodies (2015-09-04, Fat-Zer) PartDesign::Body* pcActiveBody = PartDesignGui::getBody(false); App::Part* pcActivePart = PartDesignGui::getPartFor(pcActiveBody, false); - // TODO: If the user previously opted to allow multiple use of sketches or use of sketches from other bodies, - // then count these as valid sketches! + // TODO: If the user previously opted to allow multiple use of sketches or use of sketches from + // other bodies, then count these as valid sketches! unsigned freeSketches = 0; firstFreeSketch = sketches.end(); @@ -598,43 +674,50 @@ unsigned validateSketches(std::vector& sketches, if (!pcActiveBody) { // We work in the old style outside any body - if (PartDesign::Body::findBodyOf (*s)) { + if (PartDesign::Body::findBodyOf(*s)) { status.push_back(PartDesignGui::TaskFeaturePick::otherPart); continue; } - } else if (!pcActiveBody->hasObject(*s)) { + } + else if (!pcActiveBody->hasObject(*s)) { // Check whether this plane belongs to a body of the same part PartDesign::Body* b = PartDesign::Body::findBodyOf(*s); - if (!b) + if (!b) { status.push_back(PartDesignGui::TaskFeaturePick::notInBody); - else if (pcActivePart && pcActivePart->hasObject(b, true)) + } + else if (pcActivePart && pcActivePart->hasObject(b, true)) { status.push_back(PartDesignGui::TaskFeaturePick::otherBody); - else + } + else { status.push_back(PartDesignGui::TaskFeaturePick::otherPart); + } continue; } - //Base::Console().error("Checking sketch %s\n", (*s)->getNameInDocument()); - // Check whether this sketch is already being used by another feature - // Body features don't count... + // Base::Console().error("Checking sketch %s\n", (*s)->getNameInDocument()); + // Check whether this sketch is already being used by another feature + // Body features don't count... std::vector inList = (*s)->getInList(); std::vector::iterator o = inList.begin(); while (o != inList.end()) { - //Base::Console().error("Inlist: %s\n", (*o)->getNameInDocument()); - if ((*o)->isDerivedFrom()) - o = inList.erase(o); //ignore bodies - else if (!( (*o)->isDerivedFrom() )) - o = inList.erase(o); //ignore non-partDesign - else + // Base::Console().error("Inlist: %s\n", (*o)->getNameInDocument()); + if ((*o)->isDerivedFrom()) { + o = inList.erase(o); // ignore bodies + } + else if (!((*o)->isDerivedFrom())) { + o = inList.erase(o); // ignore non-partDesign + } + else { ++o; + } } if (!inList.empty()) { status.push_back(PartDesignGui::TaskFeaturePick::isUsed); continue; } - if (pcActiveBody && pcActiveBody->isAfterInsertPoint(*s)){ + if (pcActiveBody && pcActiveBody->isAfterInsertPoint(*s)) { status.push_back(PartDesignGui::TaskFeaturePick::afterTip); continue; } @@ -648,7 +731,7 @@ unsigned validateSketches(std::vector& sketches, } // count free wires - int ctWires=0; + int ctWires = 0; TopExp_Explorer ex; for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next()) { ctWires++; @@ -659,8 +742,9 @@ unsigned validateSketches(std::vector& sketches, } // All checks passed - found a valid sketch - if (firstFreeSketch == sketches.end()) + if (firstFreeSketch == sketches.end()) { firstFreeSketch = s; + } freeSketches++; status.push_back(PartDesignGui::TaskFeaturePick::validFeature); } @@ -689,8 +773,7 @@ bool importExternalElements(App::PropertyLinkSub& prop, std::vectorgetNameInDocument()); + FC_THROWM(Base::RuntimeError, "No body for editing object: " << editObj->getNameInDocument()); } std::map> links; std::vector sobjs; @@ -702,12 +785,13 @@ bool importExternalElements(App::PropertyLinkSub& prop, std::vector func) +void prepareProfileBased( + PartDesign::Body* pcActiveBody, + Gui::Command* cmd, + const std::string& which, + std::function func +) { - auto base_worker = [=](App::DocumentObject *feature, const std::vector &subs) { - - if (!feature || !feature->isDerivedFrom()) + auto base_worker = [=](App::DocumentObject* feature, const std::vector& subs) { + if (!feature || !feature->isDerivedFrom()) { return; + } // Related to #0002760: when an operation can't be performed due to a broken // profile then make sure that it is recomputed when cancelling the operation // otherwise it might be impossible to see that it's broken. - if (feature->isTouched()) + if (feature->isTouched()) { feature->recomputeFeature(); + } std::string FeatName = cmd->getUniqueObjectName(which.c_str(), pcActiveBody); Gui::Command::openCommand((std::string("Make ") + which).c_str()); - FCMD_OBJ_CMD(pcActiveBody,"newObject('PartDesign::" << which << "','" << FeatName << "')"); + FCMD_OBJ_CMD(pcActiveBody, "newObject('PartDesign::" << which << "','" << FeatName << "')"); auto Feat = pcActiveBody->getDocument()->getObject(FeatName.c_str()); auto objCmd = Gui::Command::getObjectCmd(feature); @@ -798,23 +887,21 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons cmdSubs = ProfileFeature->Profile.getSubValues(); } // run the command in console to set the profile (without selected subelements) - auto runProfileCmd = - [=]() { - FCMD_OBJ_CMD(Feat,"Profile = " << objCmd); - }; + auto runProfileCmd = [=]() { + FCMD_OBJ_CMD(Feat, "Profile = " << objCmd); + }; // run the command in console to set the profile with selected subelements // useful to set, say, a face of a solid as the "profile" - auto runProfileCmdWithSubs = - [=]() { - std::ostringstream ss; - for (auto &s : cmdSubs) - ss << "'" << s << "',"; - FCMD_OBJ_CMD(Feat,"Profile = (" << objCmd << ", [" << ss.str() << "])"); - }; + auto runProfileCmdWithSubs = [=]() { + std::ostringstream ss; + for (auto& s : cmdSubs) { + ss << "'" << s << "',"; + } + FCMD_OBJ_CMD(Feat, "Profile = (" << objCmd << ", [" << ss.str() << "])"); + }; - if (which.compare("AdditiveLoft") == 0 || - which.compare("SubtractiveLoft") == 0) { + if (which.compare("AdditiveLoft") == 0 || which.compare("SubtractiveLoft") == 0) { // for additive and subtractive lofts set subvalues even for sketches // when a vertex is first selected auto subName = subs.empty() ? "" : subs.front(); @@ -822,23 +909,26 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons // `ProfileBased::getProfileShape()` and other methods will return // just the sub-shapes if they are set. So when whole sketches are // desired, do not set sub-values. - if (feature->isDerivedFrom() && - subName.compare(0, 6, "Vertex") != 0) + if (feature->isDerivedFrom() && subName.compare(0, 6, "Vertex") != 0) { runProfileCmd(); - else + } + else { runProfileCmdWithSubs(); + } // for additive and subtractive lofts allow the user to preselect the sections std::vector selection = cmd->getSelection().getSelectionEx(); - if (selection.size() > 1) { //treat additional selected objects as sections - for (std::vector::size_type ii = 1; ii < selection.size(); ii++) { + if (selection.size() > 1) { // treat additional selected objects as sections + for (std::vector::size_type ii = 1; ii < selection.size(); + ii++) { // Add subvalues even for sketches in case we just want points auto objCmdSection = Gui::Command::getObjectCmd(selection[ii].getObject()); const auto& subnames = selection[ii].getSubNames(); std::ostringstream ss; if (!subnames.empty()) { - for (auto &s : subnames) + for (auto& s : subnames) { ss << "'" << s << "',"; + } } else { // an empty string indicates the whole object @@ -848,8 +938,7 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons } } } - else if (which.compare("AdditivePipe") == 0 || - which.compare("SubtractivePipe") == 0) { + else if (which.compare("AdditivePipe") == 0 || which.compare("SubtractivePipe") == 0) { // for additive and subtractive pipes set subvalues even for sketches // to support point sections auto subName = subs.empty() ? "" : subs.front(); @@ -857,27 +946,30 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons // `ProfileBased::getProfileShape()` and other methods will return // just the sub-shapes if they are set. So when whole sketches are // desired, don't set sub-values. - if (feature->isDerivedFrom() && - subName.compare(0, 6, "Vertex") != 0) + if (feature->isDerivedFrom() && subName.compare(0, 6, "Vertex") != 0) { runProfileCmd(); - else + } + else { runProfileCmdWithSubs(); + } // for additive and subtractive pipes allow the user to preselect the spines std::vector selection = cmd->getSelection().getSelectionEx(); - if (selection.size() == 2) { //treat additional selected object as spine - std::vector subnames = selection[1].getSubNames(); + if (selection.size() == 2) { // treat additional selected object as spine + std::vector subnames = selection[1].getSubNames(); auto objCmdSpine = Gui::Command::getObjectCmd(selection[1].getObject()); - if (selection[1].getObject()->isDerivedFrom() && subnames.empty()) { - FCMD_OBJ_CMD(Feat,"Spine = " << objCmdSpine); + if (selection[1].getObject()->isDerivedFrom() + && subnames.empty()) { + FCMD_OBJ_CMD(Feat, "Spine = " << objCmdSpine); } else { std::ostringstream ss; - for(auto &s : subnames) { - if (s.find("Edge") != std::string::npos) + for (auto& s : subnames) { + if (s.find("Edge") != std::string::npos) { ss << "'" << s << "',"; + } } - FCMD_OBJ_CMD(Feat,"Spine = (" << objCmdSpine << ", [" << ss.str() << "])"); + FCMD_OBJ_CMD(Feat, "Spine = (" << objCmdSpine << ", [" << ss.str() << "])"); } } } @@ -891,14 +983,17 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons // in case of subtractive types, check that there is something to subtract from - if ((which.find("Subtractive") != std::string::npos) || - (which.compare("Groove") == 0) || - (which.compare("Pocket") == 0)) { + if ((which.find("Subtractive") != std::string::npos) || (which.compare("Groove") == 0) + || (which.compare("Pocket") == 0)) { if (!pcActiveBody->isSolid()) { QMessageBox msgBox(Gui::getMainWindow()); - msgBox.setText(QObject::tr("Cannot use this command as there is no solid to subtract from.")); - msgBox.setInformativeText(QObject::tr("Ensure that the body contains a feature before attempting a subtractive command.")); + msgBox.setText( + QObject::tr("Cannot use this command as there is no solid to subtract from.") + ); + msgBox.setInformativeText( + QObject::tr("Ensure that the body contains a feature before attempting a subtractive command.") + ); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); @@ -907,43 +1002,55 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons } - //if a profile is selected we can make our life easy and fast + // if a profile is selected we can make our life easy and fast std::vector selection = cmd->getSelection().getSelectionEx(); if (!selection.empty()) { bool onlyAllowed = true; - for (const auto & it : selection) { - if (PartDesign::Body::findBodyOf(it.getObject()) != pcActiveBody) { // the selected objects must belong to the body + for (const auto& it : selection) { + if (PartDesign::Body::findBodyOf(it.getObject()) + != pcActiveBody) { // the selected objects must belong to the body onlyAllowed = false; break; } } if (!onlyAllowed) { QMessageBox msgBox(Gui::getMainWindow()); - msgBox.setText(QObject::tr("Cannot use selected object. Selected object must belong to the active body")); - msgBox.setInformativeText(QObject::tr("Consider using a shape binder or a base feature to reference external geometry in a body")); + msgBox.setText( + QObject::tr("Cannot use selected object. Selected object must belong to the active body") + ); + msgBox.setInformativeText( + QObject::tr("Consider using a shape binder or a base feature to reference external geometry in a body") + ); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); - } else { + } + else { base_worker(selection.front().getObject(), selection.front().getSubNames()); } return; } - //no face profile was selected, do the extended sketch logic + // no face profile was selected, do the extended sketch logic bool bNoSketchWasSelected = false; // Get a valid sketch from the user // First check selections - std::vector sketches = cmd->getSelection().getObjectsOfType(Part::Part2DObject::getClassTypeId()); - if (sketches.empty()) {//no sketches were selected. Let user pick an object from valid ones available in document + std::vector sketches = cmd->getSelection().getObjectsOfType( + Part::Part2DObject::getClassTypeId() + ); + if (sketches.empty()) { // no sketches were selected. Let user pick an object from valid ones + // available in document sketches = cmd->getDocument()->getObjectsOfType(Part::Part2DObject::getClassTypeId()); bNoSketchWasSelected = true; } if (sketches.empty()) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No sketch to work on"), - QObject::tr("No sketch is available in the document")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No sketch to work on"), + QObject::tr("No sketch is available in the document") + ); return; } @@ -952,9 +1059,9 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons int freeSketches = validateSketches(sketches, status, firstFreeSketch); auto accepter = [=](const std::vector& features) -> bool { - - if (features.empty()) + if (features.empty()) { return false; + } return true; }; @@ -963,15 +1070,18 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons base_worker(features.front(), {}); }; - //if there is a sketch selected which is from another body or part we need to bring up the - //pick task dialog to decide how those are handled - bool extReference = std::find_if( status.begin(), status.end(), - [] (const PartDesignGui::TaskFeaturePick::featureStatus& s) { - return s == PartDesignGui::TaskFeaturePick::otherBody || - s == PartDesignGui::TaskFeaturePick::otherPart || - s == PartDesignGui::TaskFeaturePick::notInBody; - } - ) != status.end(); + // if there is a sketch selected which is from another body or part we need to bring up the + // pick task dialog to decide how those are handled + bool extReference = std::find_if( + status.begin(), + status.end(), + [](const PartDesignGui::TaskFeaturePick::featureStatus& s) { + return s == PartDesignGui::TaskFeaturePick::otherBody + || s == PartDesignGui::TaskFeaturePick::otherPart + || s == PartDesignGui::TaskFeaturePick::notInBody; + } + ) + != status.end(); // TODO Clean this up (2015-10-20, Fat-Zer) if (pcActiveBody && !bNoSketchWasSelected && extReference) { @@ -992,29 +1102,37 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons dlg.setupUi(&dia); dia.setModal(true); int result = dia.exec(); - if (result == QDialog::DialogCode::Rejected) + if (result == QDialog::DialogCode::Rejected) { return; + } if (!dlg.radioXRef->isChecked()) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Make Copy")); - auto copy = PartDesignGui::TaskFeaturePick::makeCopy(sketches[0], "", dlg.radioIndependent->isChecked()); + auto copy = PartDesignGui::TaskFeaturePick::makeCopy( + sketches[0], + "", + dlg.radioIndependent->isChecked() + ); auto oBody = PartDesignGui::getBodyFor(sketches[0], false); - if (oBody) + if (oBody) { pcActiveBody->addObject(copy); - else if (pcActivePart) + } + else if (pcActivePart) { pcActivePart->addObject(copy); + } sketches[0] = copy; firstFreeSketch = sketches.begin(); } } - // Show sketch choose dialog and let user pick sketch if no sketch was selected and no free one available or - // multiple free ones are available - if (bNoSketchWasSelected && (freeSketches != 1) ) { + // Show sketch choose dialog and let user pick sketch if no sketch was selected and no free one + // available or multiple free ones are available + if (bNoSketchWasSelected && (freeSketches != 1)) { - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - PartDesignGui::TaskDlgFeaturePick *pickDlg = qobject_cast(dlg); + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); + PartDesignGui::TaskDlgFeaturePick* pickDlg + = qobject_cast(dlg); if (dlg && !pickDlg) { QMessageBox msgBox(Gui::getMainWindow()); msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -1022,52 +1140,59 @@ void prepareProfileBased(PartDesign::Body *pcActiveBody, Gui::Command* cmd, cons msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); - if (ret == QMessageBox::Yes) + if (ret == QMessageBox::Yes) { Gui::Control().closeDialog(); - else + } + else { return; + } } - if (dlg) + if (dlg) { Gui::Control().closeDialog(); + } Gui::Selection().clearSelection(); pickDlg = new PartDesignGui::TaskDlgFeaturePick(sketches, status, accepter, sketch_worker, true); // Logically dead code because 'bNoSketchWasSelected' must be true - //if (!bNoSketchWasSelected && extReference) + // if (!bNoSketchWasSelected && extReference) // pickDlg->showExternal(true); Gui::Control().showDialog(pickDlg); } else { std::vector theSketch; - if (!bNoSketchWasSelected) + if (!bNoSketchWasSelected) { theSketch.push_back(sketches[0]); - else + } + else { theSketch.push_back(*firstFreeSketch); + } sketch_worker(theSketch); } } -void finishProfileBased(const Gui::Command* cmd, const Part::Feature* sketch, App::DocumentObject *Feat) +void finishProfileBased(const Gui::Command* cmd, const Part::Feature* sketch, App::DocumentObject* Feat) { - if (sketch && sketch->isDerivedFrom()) + if (sketch && sketch->isDerivedFrom()) { FCMD_OBJ_HIDE(sketch); + } finishFeature(cmd, Feat); } void prepareProfileBased(Gui::Command* cmd, const std::string& which, double length) { - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } - auto worker = [cmd, length](Part::Feature* profile, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd, length](Part::Feature* profile, App::DocumentObject* Feat) { + if (!Feat) { return; + } // specific parameters for Pad/Pocket FCMD_OBJ_CMD(Feat, "Length = " << length); @@ -1077,7 +1202,10 @@ void prepareProfileBased(Gui::Command* cmd, const std::string& which, double len if (sketch) { std::ostringstream str; - Gui::cmdAppObject(Feat, str << "ReferenceAxis = (" << Gui::Command::getObjectCmd(sketch) << ",['N_Axis'])"); + Gui::cmdAppObject( + Feat, + str << "ReferenceAxis = (" << Gui::Command::getObjectCmd(sketch) << ",['N_Axis'])" + ); } finishProfileBased(cmd, sketch, Feat); @@ -1092,15 +1220,15 @@ void prepareProfileBased(Gui::Command* cmd, const std::string& which, double len DEF_STD_CMD_A(CmdPartDesignPad) CmdPartDesignPad::CmdPartDesignPad() - : Command("PartDesign_Pad") + : Command("PartDesign_Pad") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Pad"); - sToolTipText = QT_TR_NOOP("Extrudes the selected sketch or profile and adds it to the body"); - sWhatsThis = "PartDesign_Pad"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Pad"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Pad"); + sToolTipText = QT_TR_NOOP("Extrudes the selected sketch or profile and adds it to the body"); + sWhatsThis = "PartDesign_Pad"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Pad"; } void CmdPartDesignPad::activated(int iMsg) @@ -1121,15 +1249,15 @@ bool CmdPartDesignPad::isActive() DEF_STD_CMD_A(CmdPartDesignPocket) CmdPartDesignPocket::CmdPartDesignPocket() - : Command("PartDesign_Pocket") + : Command("PartDesign_Pocket") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Pocket"); - sToolTipText = QT_TR_NOOP("Extrudes the selected sketch or profile and removes it from the body"); - sWhatsThis = "PartDesign_Pocket"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Pocket"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Pocket"); + sToolTipText = QT_TR_NOOP("Extrudes the selected sketch or profile and removes it from the body"); + sWhatsThis = "PartDesign_Pocket"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Pocket"; } void CmdPartDesignPocket::activated(int iMsg) @@ -1150,31 +1278,33 @@ bool CmdPartDesignPocket::isActive() DEF_STD_CMD_A(CmdPartDesignHole) CmdPartDesignHole::CmdPartDesignHole() - : Command("PartDesign_Hole") + : Command("PartDesign_Hole") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Hole"); - sToolTipText = QT_TR_NOOP("Creates holes in the active body at the center points of circles or arcs of the selected sketch or profile"); - sWhatsThis = "PartDesign_Hole"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Hole"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Hole"); + sToolTipText + = QT_TR_NOOP("Creates holes in the active body at the center points of circles or arcs of the selected sketch or profile"); + sWhatsThis = "PartDesign_Hole"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Hole"; } void CmdPartDesignHole::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } finishProfileBased(cmd, sketch, Feat); }; @@ -1193,43 +1323,50 @@ bool CmdPartDesignHole::isActive() DEF_STD_CMD_A(CmdPartDesignRevolution) CmdPartDesignRevolution::CmdPartDesignRevolution() - : Command("PartDesign_Revolution") + : Command("PartDesign_Revolution") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Revolve"); - sToolTipText = QT_TR_NOOP("Revolves the selected sketch or profile around a line or axis and adds it to the body"); - sWhatsThis = "PartDesign_Revolution"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Revolution"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Revolve"); + sToolTipText = QT_TR_NOOP( + "Revolves the selected sketch or profile around a line or axis and adds it to the body" + ); + sWhatsThis = "PartDesign_Revolution"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Revolution"; } void CmdPartDesignRevolution::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } if (sketch->isDerivedFrom()) { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = (" << getObjectCmd(sketch) << ",['V_Axis'])"); + FCMD_OBJ_CMD(Feat, "ReferenceAxis = (" << getObjectCmd(sketch) << ",['V_Axis'])"); } else { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])"); + FCMD_OBJ_CMD( + Feat, + "ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])" + ); } - FCMD_OBJ_CMD(Feat,"Angle = 360.0"); + FCMD_OBJ_CMD(Feat, "Angle = 360.0"); PartDesign::Revolution* pcRevolution = dynamic_cast(Feat); - if (pcRevolution && pcRevolution->suggestReversed()) - FCMD_OBJ_CMD(Feat,"Reversed = 1"); + if (pcRevolution && pcRevolution->suggestReversed()) { + FCMD_OBJ_CMD(Feat, "Reversed = 1"); + } finishProfileBased(cmd, sketch, Feat); }; @@ -1248,47 +1385,54 @@ bool CmdPartDesignRevolution::isActive() DEF_STD_CMD_A(CmdPartDesignGroove) CmdPartDesignGroove::CmdPartDesignGroove() - : Command("PartDesign_Groove") + : Command("PartDesign_Groove") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Groove"); - sToolTipText = QT_TR_NOOP("Revolves the sketch or profile around a line or axis and removes it from the body"); - sWhatsThis = "PartDesign_Groove"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Groove"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Groove"); + sToolTipText = QT_TR_NOOP( + "Revolves the sketch or profile around a line or axis and removes it from the body" + ); + sWhatsThis = "PartDesign_Groove"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Groove"; } void CmdPartDesignGroove::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } if (sketch->isDerivedFrom()) { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = ("<getOrigin()->getY())<<",[''])"); + FCMD_OBJ_CMD( + Feat, + "ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])" + ); } - FCMD_OBJ_CMD(Feat,"Angle = 360.0"); + FCMD_OBJ_CMD(Feat, "Angle = 360.0"); try { // This raises as exception if line is perpendicular to sketch/support face. // Here we should continue to give the user a chance to change the default values. PartDesign::Groove* pcGroove = dynamic_cast(Feat); - if (pcGroove && pcGroove->suggestReversed()) - FCMD_OBJ_CMD(Feat,"Reversed = 1"); + if (pcGroove && pcGroove->suggestReversed()) { + FCMD_OBJ_CMD(Feat, "Reversed = 1"); + } } catch (const Base::Exception& e) { e.reportException(); @@ -1311,31 +1455,34 @@ bool CmdPartDesignGroove::isActive() DEF_STD_CMD_A(CmdPartDesignAdditivePipe) CmdPartDesignAdditivePipe::CmdPartDesignAdditivePipe() - : Command("PartDesign_AdditivePipe") + : Command("PartDesign_AdditivePipe") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Additive Pipe"); - sToolTipText = QT_TR_NOOP("Sweeps the selected sketch or profile along a path and adds it to the body"); - sWhatsThis = "PartDesign_AdditivePipe"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_AdditivePipe"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Additive Pipe"); + sToolTipText = QT_TR_NOOP( + "Sweeps the selected sketch or profile along a path and adds it to the body" + ); + sWhatsThis = "PartDesign_AdditivePipe"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_AdditivePipe"; } void CmdPartDesignAdditivePipe::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } // specific parameters for pipe Gui::Command::updateActive(); @@ -1358,31 +1505,34 @@ bool CmdPartDesignAdditivePipe::isActive() DEF_STD_CMD_A(CmdPartDesignSubtractivePipe) CmdPartDesignSubtractivePipe::CmdPartDesignSubtractivePipe() - : Command("PartDesign_SubtractivePipe") + : Command("PartDesign_SubtractivePipe") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Subtractive Pipe"); - sToolTipText = QT_TR_NOOP("Sweeps the selected sketch or profile along a path and removes it from the body"); - sWhatsThis = "PartDesign_SubtractivePipe"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_SubtractivePipe"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Subtractive Pipe"); + sToolTipText = QT_TR_NOOP( + "Sweeps the selected sketch or profile along a path and removes it from the body" + ); + sWhatsThis = "PartDesign_SubtractivePipe"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_SubtractivePipe"; } void CmdPartDesignSubtractivePipe::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } // specific parameters for pipe Gui::Command::updateActive(); @@ -1405,31 +1555,34 @@ bool CmdPartDesignSubtractivePipe::isActive() DEF_STD_CMD_A(CmdPartDesignAdditiveLoft) CmdPartDesignAdditiveLoft::CmdPartDesignAdditiveLoft() - : Command("PartDesign_AdditiveLoft") + : Command("PartDesign_AdditiveLoft") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Additive Loft"); - sToolTipText = QT_TR_NOOP("Lofts the selected sketch or profile along a path and adds it to the body"); - sWhatsThis = "PartDesign_AdditiveLoft"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_AdditiveLoft"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Additive Loft"); + sToolTipText = QT_TR_NOOP( + "Lofts the selected sketch or profile along a path and adds it to the body" + ); + sWhatsThis = "PartDesign_AdditiveLoft"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_AdditiveLoft"; } void CmdPartDesignAdditiveLoft::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } // specific parameters for pipe Gui::Command::updateActive(); @@ -1452,31 +1605,34 @@ bool CmdPartDesignAdditiveLoft::isActive() DEF_STD_CMD_A(CmdPartDesignSubtractiveLoft) CmdPartDesignSubtractiveLoft::CmdPartDesignSubtractiveLoft() - : Command("PartDesign_SubtractiveLoft") + : Command("PartDesign_SubtractiveLoft") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Subtractive Loft"); - sToolTipText = QT_TR_NOOP("Lofts the selected sketch or profile along a path and removes it from the body"); - sWhatsThis = "PartDesign_SubtractiveLoft"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_SubtractiveLoft"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Subtractive Loft"); + sToolTipText = QT_TR_NOOP( + "Lofts the selected sketch or profile along a path and removes it from the body" + ); + sWhatsThis = "PartDesign_SubtractiveLoft"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_SubtractiveLoft"; } void CmdPartDesignSubtractiveLoft::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } // specific parameters for pipe Gui::Command::updateActive(); @@ -1498,59 +1654,71 @@ bool CmdPartDesignSubtractiveLoft::isActive() DEF_STD_CMD_A(CmdPartDesignAdditiveHelix) CmdPartDesignAdditiveHelix::CmdPartDesignAdditiveHelix() - : Command("PartDesign_AdditiveHelix") + : Command("PartDesign_AdditiveHelix") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Additive Helix"); - sToolTipText = QT_TR_NOOP("Sweeps the selected sketch or profile along a helix and adds it to the body"); - sWhatsThis = "PartDesign_AdditiveHelix"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_AdditiveHelix"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Additive Helix"); + sToolTipText = QT_TR_NOOP( + "Sweeps the selected sketch or profile along a helix and adds it to the body" + ); + sWhatsThis = "PartDesign_AdditiveHelix"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_AdditiveHelix"; } void CmdPartDesignAdditiveHelix::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } // Creating a helix with default values isn't always valid but fixes // itself when more values are set. So, this guard is used to suppress // errors before the user is able to change the parameters. Base::ObjectStatusLocker guard( - App::Document::IgnoreErrorOnRecompute, Feat->getDocument(), true); + App::Document::IgnoreErrorOnRecompute, + Feat->getDocument(), + true + ); // specific parameters for helix Gui::Command::updateActive(); if (sketch->isDerivedFrom()) { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = (" << getObjectCmd(sketch) << ",['V_Axis'])"); + FCMD_OBJ_CMD(Feat, "ReferenceAxis = (" << getObjectCmd(sketch) << ",['V_Axis'])"); } else { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])"); + FCMD_OBJ_CMD( + Feat, + "ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])" + ); } finishProfileBased(cmd, sketch, Feat); - // If the initial helix creation fails then it leaves the base object invisible which makes things - // more difficult for the user. - // To avoid this the base object will be made tmp. visible again. + // If the initial helix creation fails then it leaves the base object invisible which makes + // things more difficult for the user. To avoid this the base object will be made tmp. + // visible again. if (Feat->isError()) { App::DocumentObject* base = static_cast(Feat)->BaseFeature.getValue(); if (base) { - PartDesignGui::ViewProvider* view = dynamic_cast(Gui::Application::Instance->getViewProvider(base)); - if (view) + PartDesignGui::ViewProvider* view = dynamic_cast( + Gui::Application::Instance->getViewProvider(base) + ); + if (view) { view->makeTemporaryVisible(true); + } } } }; @@ -1570,40 +1738,46 @@ bool CmdPartDesignAdditiveHelix::isActive() DEF_STD_CMD_A(CmdPartDesignSubtractiveHelix) CmdPartDesignSubtractiveHelix::CmdPartDesignSubtractiveHelix() - : Command("PartDesign_SubtractiveHelix") + : Command("PartDesign_SubtractiveHelix") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Subtractive Helix"); - sToolTipText = QT_TR_NOOP("Sweeps the selected sketch or profile along a helix and removes it from the body"); - sWhatsThis = "PartDesign_SubtractiveHelix"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_SubtractiveHelix"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Subtractive Helix"); + sToolTipText = QT_TR_NOOP( + "Sweeps the selected sketch or profile along a helix and removes it from the body" + ); + sWhatsThis = "PartDesign_SubtractiveHelix"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_SubtractiveHelix"; } void CmdPartDesignSubtractiveHelix::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject *Feat) { - - if (!Feat) + auto worker = [cmd, &pcActiveBody](Part::Feature* sketch, App::DocumentObject* Feat) { + if (!Feat) { return; + } // specific parameters for helix Gui::Command::updateActive(); if (sketch->isDerivedFrom()) { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = (" << getObjectCmd(sketch) << ",['V_Axis'])"); + FCMD_OBJ_CMD(Feat, "ReferenceAxis = (" << getObjectCmd(sketch) << ",['V_Axis'])"); } else { - FCMD_OBJ_CMD(Feat,"ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])"); + FCMD_OBJ_CMD( + Feat, + "ReferenceAxis = (" << getObjectCmd(pcActiveBody->getOrigin()->getY()) << ",[''])" + ); } finishProfileBased(cmd, sketch, Feat); @@ -1621,13 +1795,19 @@ bool CmdPartDesignSubtractiveHelix::isActive() // Common utility functions for Dressup features //=========================================================================== -bool dressupGetSelected(Gui::Command* cmd, const std::string& which, - Gui::SelectionObject &selected, bool &useAllEdges, bool& noSelection) +bool dressupGetSelected( + Gui::Command* cmd, + const std::string& which, + Gui::SelectionObject& selected, + bool& useAllEdges, + bool& noSelection +) { - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return false; + } std::vector selection = cmd->getSelection().getSelectionEx(); @@ -1636,13 +1816,19 @@ bool dressupGetSelected(Gui::Command* cmd, const std::string& which, return true; } else if (selection.size() != 1) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Select an edge, face, or body from a single body.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select an edge, face, or body from a single body.") + ); return false; } else if (pcActiveBody != PartDesignGui::getBodyFor(selection[0].getObject(), false)) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Selection is not in the active body"), - QObject::tr("Select an edge, face, or body from an active body.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Selection is not in the active body"), + QObject::tr("Select an edge, face, or body from an active body.") + ); return false; } @@ -1652,48 +1838,60 @@ bool dressupGetSelected(Gui::Command* cmd, const std::string& which, selected = selection[0]; if (!selected.isObjectTypeOf(Part::Feature::getClassTypeId())) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong object type"), - QObject::tr("%1 works only on parts.").arg(QString::fromStdString(which))); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong object type"), + QObject::tr("%1 works only on parts.").arg(QString::fromStdString(which)) + ); return false; } - Part::Feature *base = static_cast(selected.getObject()); + Part::Feature* base = static_cast(selected.getObject()); const Part::TopoShape& TopShape = base->Shape.getShape(); - if (TopShape.getShape().IsNull()){ - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), - QObject::tr("Shape of the selected part is empty")); + if (TopShape.getShape().IsNull()) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Shape of the selected part is empty") + ); return false; } // if 1 Part::Feature object selected, but no subobjects, select all edges for the user // but only for fillet and chamfer (not for draft or thickness) - if (selection[0].getSubNames().empty() && (which.compare("Fillet") == 0 || which.compare("Chamfer") == 0)){ + if (selection[0].getSubNames().empty() + && (which.compare("Fillet") == 0 || which.compare("Chamfer") == 0)) { useAllEdges = true; - std::string edgeTypeName = Part::TopoShape::shapeName(TopAbs_EDGE); //"Edge" + std::string edgeTypeName = Part::TopoShape::shapeName(TopAbs_EDGE); //"Edge" int count = TopShape.countSubElements(edgeTypeName.c_str()); std::string docName = App::GetApplication().getDocumentName(base->getDocument()); std::string objName = base->getNameInDocument(); - for (int ii = 0; ii < count; ii++){ + for (int ii = 0; ii < count; ii++) { std::ostringstream edgeName; - edgeName << edgeTypeName << ii+1; + edgeName << edgeTypeName << ii + 1; Gui::Selection().addSelection(docName.c_str(), objName.c_str(), edgeName.str().c_str()); } selection = cmd->getSelection().getSelectionEx(); - if (selection.size() == 1){ + if (selection.size() == 1) { selected = selection[0]; } } return true; } -void finishDressupFeature(const Gui::Command* cmd, const std::string& which, - Part::Feature *base, const std::vector & SubNames, const bool useAllEdges) +void finishDressupFeature( + const Gui::Command* cmd, + const std::string& which, + Part::Feature* base, + const std::vector& SubNames, + const bool useAllEdges +) { std::ostringstream str; str << '(' << Gui::Command::getObjectCmd(base) << ",["; - for (const auto & SubName : SubNames){ + for (const auto& SubName : SubNames) { str << "'" << SubName << "',"; } str << "])"; @@ -1701,25 +1899,29 @@ void finishDressupFeature(const Gui::Command* cmd, const std::string& which, std::string FeatName = cmd->getUniqueObjectName(which.c_str(), base); auto body = PartDesignGui::getBodyFor(base, false); - if (!body) + if (!body) { return; + } cmd->openCommand((std::string("Make ") + which).c_str()); - FCMD_OBJ_CMD(body,"newObject('PartDesign::"<getDocument()->getObject(FeatName.c_str()); - FCMD_OBJ_CMD(Feat,"Base = " << str.str()); - if (useAllEdges && (which.compare("Fillet") == 0 || which.compare("Chamfer") == 0)){ - FCMD_OBJ_CMD(Feat,"UseAllEdges = True"); + FCMD_OBJ_CMD(Feat, "Base = " << str.str()); + if (useAllEdges && (which.compare("Fillet") == 0 || which.compare("Chamfer") == 0)) { + FCMD_OBJ_CMD(Feat, "UseAllEdges = True"); } cmd->doCommand(cmd->Gui, "Gui.Selection.clearSelection()"); finishFeature(cmd, Feat, base); App::DocumentObject* baseFeature = static_cast(Feat)->Base.getValue(); if (baseFeature) { - PartDesignGui::ViewProvider* view = dynamic_cast(Gui::Application::Instance->getViewProvider(baseFeature)); + PartDesignGui::ViewProvider* view = dynamic_cast( + Gui::Application::Instance->getViewProvider(baseFeature) + ); // in case there is an error, for example when a fillet is larger than the available space // display the base feature to avoid that the user sees nothing - if (view && Feat->isError()) + if (view && Feat->isError()) { view->Visibility.setValue(true); + } } } @@ -1728,10 +1930,11 @@ void makeChamferOrFillet(Gui::Command* cmd, const std::string& which) bool useAllEdges = false; bool noSelection = false; Gui::SelectionObject selected; - if (!dressupGetSelected ( cmd, which, selected, useAllEdges, noSelection)) + if (!dressupGetSelected(cmd, which, selected, useAllEdges, noSelection)) { return; + } - Part::Feature *base; + Part::Feature* base; std::vector SubNames; if (noSelection) { base = static_cast(PartDesignGui::getBody(true)->Tip.getValue()); @@ -1741,7 +1944,7 @@ void makeChamferOrFillet(Gui::Command* cmd, const std::string& which) SubNames = std::vector(selected.getSubNames()); } - finishDressupFeature (cmd, which, base, SubNames, useAllEdges); + finishDressupFeature(cmd, which, base, SubNames, useAllEdges); } //=========================================================================== @@ -1750,15 +1953,15 @@ void makeChamferOrFillet(Gui::Command* cmd, const std::string& which) DEF_STD_CMD_A(CmdPartDesignFillet) CmdPartDesignFillet::CmdPartDesignFillet() - :Command("PartDesign_Fillet") + : Command("PartDesign_Fillet") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Fillet"); - sToolTipText = QT_TR_NOOP("Applies a fillet to the selected edges or faces"); - sWhatsThis = "PartDesign_Fillet"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Fillet"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Fillet"); + sToolTipText = QT_TR_NOOP("Applies a fillet to the selected edges or faces"); + sWhatsThis = "PartDesign_Fillet"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Fillet"; } void CmdPartDesignFillet::activated(int iMsg) @@ -1778,22 +1981,22 @@ bool CmdPartDesignFillet::isActive() DEF_STD_CMD_A(CmdPartDesignChamfer) CmdPartDesignChamfer::CmdPartDesignChamfer() - :Command("PartDesign_Chamfer") + : Command("PartDesign_Chamfer") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Chamfer"); - sToolTipText = QT_TR_NOOP("Applies a chamfer to the selected edges or faces"); - sWhatsThis = "PartDesign_Chamfer"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Chamfer"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Chamfer"); + sToolTipText = QT_TR_NOOP("Applies a chamfer to the selected edges or faces"); + sWhatsThis = "PartDesign_Chamfer"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Chamfer"; } void CmdPartDesignChamfer::activated(int iMsg) { Q_UNUSED(iMsg); makeChamferOrFillet(this, "Chamfer"); - doCommand(Gui,"Gui.Selection.clearSelection()"); + doCommand(Gui, "Gui.Selection.clearSelection()"); } bool CmdPartDesignChamfer::isActive() @@ -1807,15 +2010,15 @@ bool CmdPartDesignChamfer::isActive() DEF_STD_CMD_A(CmdPartDesignDraft) CmdPartDesignDraft::CmdPartDesignDraft() - :Command("PartDesign_Draft") + : Command("PartDesign_Draft") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Draft"); - sToolTipText = QT_TR_NOOP("Applies a draft to the selected faces"); - sWhatsThis = "PartDesign_Draft"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Draft"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Draft"); + sToolTipText = QT_TR_NOOP("Applies a draft to the selected faces"); + sWhatsThis = "PartDesign_Draft"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Draft"; } void CmdPartDesignDraft::activated(int iMsg) @@ -1824,8 +2027,9 @@ void CmdPartDesignDraft::activated(int iMsg) Gui::SelectionObject selected; bool useAllEdges = false; bool noSelection = false; - if (!dressupGetSelected ( this, "Draft", selected, useAllEdges, noSelection)) + if (!dressupGetSelected(this, "Draft", selected, useAllEdges, noSelection)) { return; + } Part::Feature* base; std::vector SubNames; @@ -1840,16 +2044,17 @@ void CmdPartDesignDraft::activated(int iMsg) // filter out the edges size_t i = 0; - while (i < SubNames.size()) - { + while (i < SubNames.size()) { std::string aSubName = SubNames.at(i); if (aSubName.compare(0, 4, "Face") == 0) { // Check for valid face types TopoDS_Face face = TopoDS::Face(TopShape.getSubShape(aSubName.c_str())); BRepAdaptor_Surface sf(face); - if ((sf.GetType() != GeomAbs_Plane) && (sf.GetType() != GeomAbs_Cylinder) && (sf.GetType() != GeomAbs_Cone)) + if ((sf.GetType() != GeomAbs_Plane) && (sf.GetType() != GeomAbs_Cylinder) + && (sf.GetType() != GeomAbs_Cone)) { SubNames.erase(SubNames.begin() + i); + } } else { // empty name or any other sub-element @@ -1860,7 +2065,7 @@ void CmdPartDesignDraft::activated(int iMsg) } } - finishDressupFeature (this, "Draft", base, SubNames, useAllEdges); + finishDressupFeature(this, "Draft", base, SubNames, useAllEdges); } bool CmdPartDesignDraft::isActive() @@ -1875,15 +2080,15 @@ bool CmdPartDesignDraft::isActive() DEF_STD_CMD_A(CmdPartDesignThickness) CmdPartDesignThickness::CmdPartDesignThickness() - :Command("PartDesign_Thickness") + : Command("PartDesign_Thickness") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Thickness"); - sToolTipText = QT_TR_NOOP("Applies thickness and removes the selected faces"); - sWhatsThis = "PartDesign_Thickness"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Thickness"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Thickness"); + sToolTipText = QT_TR_NOOP("Applies thickness and removes the selected faces"); + sWhatsThis = "PartDesign_Thickness"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Thickness"; } void CmdPartDesignThickness::activated(int iMsg) @@ -1892,8 +2097,9 @@ void CmdPartDesignThickness::activated(int iMsg) Gui::SelectionObject selected; bool useAllEdges = false; bool noSelection = false; - if (!dressupGetSelected ( this, "Thickness", selected, useAllEdges, noSelection)) + if (!dressupGetSelected(this, "Thickness", selected, useAllEdges, noSelection)) { return; + } Part::Feature* base; @@ -1907,8 +2113,7 @@ void CmdPartDesignThickness::activated(int iMsg) // filter out the edges size_t i = 0; - while (i < SubNames.size()) - { + while (i < SubNames.size()) { std::string aSubName = SubNames.at(i); if (aSubName.compare(0, 4, "Face") != 0) { @@ -1919,7 +2124,7 @@ void CmdPartDesignThickness::activated(int iMsg) } } - finishDressupFeature (this, "Thickness", base, SubNames, useAllEdges); + finishDressupFeature(this, "Thickness", base, SubNames, useAllEdges); } bool CmdPartDesignThickness::isActive() @@ -1931,8 +2136,12 @@ bool CmdPartDesignThickness::isActive() // Common functions for all Transformed features //=========================================================================== -void prepareTransformed(PartDesign::Body *pcActiveBody, Gui::Command* cmd, const std::string& which, - std::function)> func) +void prepareTransformed( + PartDesign::Body* pcActiveBody, + Gui::Command* cmd, + const std::string& which, + std::function)> func +) { std::string FeatName = cmd->getUniqueObjectName(which.c_str(), pcActiveBody); @@ -1943,13 +2152,15 @@ void prepareTransformed(PartDesign::Body *pcActiveBody, Gui::Command* cmd, const FCMD_OBJ_CMD(pcActiveBody, "newObject('PartDesign::" << which << "','" << FeatName << "')"); // FIXME: There seems to be kind of a race condition here, leading to sporadic errors like // Exception (Thu Sep 6 11:52:01 2012): 'App.Document' object has no attribute 'Mirrored' - Gui::Command::updateActive(); // Helps to ensure that the object already exists when the next command comes up + Gui::Command::updateActive(); // Helps to ensure that the object already exists when the + // next command comes up auto Feat = pcActiveBody->getDocument()->getObject(FeatName.c_str()); if (features.empty()) { FCMD_OBJ_CMD(Feat, "TransformMode = \"Whole shape\""); - } else { + } + else { std::stringstream str; str << "Originals = ["; for (auto feature : features) { @@ -1968,20 +2179,25 @@ void prepareTransformed(PartDesign::Body *pcActiveBody, Gui::Command* cmd, const }; // Get a valid original from the user - std::vector features = cmd->getSelection().getObjectsOfType(PartDesign::Feature::getClassTypeId()); + std::vector features = cmd->getSelection().getObjectsOfType( + PartDesign::Feature::getClassTypeId() + ); PartDesign::Body* activeBody = PartDesignGui::getBody(true); for (auto feature : features) { if (activeBody != PartDesignGui::getBodyFor(feature, false)) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Selection is not in the active body"), - QObject::tr("Please select only one feature in an active body.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Selection is not in the active body"), + QObject::tr("Please select only one feature in an active body.") + ); return; } } worker(features); } -void finishTransformed(Gui::Command* cmd, App::DocumentObject *Feat) +void finishTransformed(Gui::Command* cmd, App::DocumentObject* Feat) { finishFeature(cmd, Feat); } @@ -1992,38 +2208,44 @@ void finishTransformed(Gui::Command* cmd, App::DocumentObject *Feat) DEF_STD_CMD_A(CmdPartDesignMirrored) CmdPartDesignMirrored::CmdPartDesignMirrored() - : Command("PartDesign_Mirrored") + : Command("PartDesign_Mirrored") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Mirror"); - sToolTipText = QT_TR_NOOP("Mirrors the selected features or active body"); - sWhatsThis = "PartDesign_Mirrored"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Mirrored"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Mirror"); + sToolTipText = QT_TR_NOOP("Mirrors the selected features or active body"); + sWhatsThis = "PartDesign_Mirrored"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Mirrored"; } void CmdPartDesignMirrored::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, pcActiveBody](App::DocumentObject *Feat, std::vector features) { + auto worker = [cmd, + pcActiveBody](App::DocumentObject* Feat, std::vector features) { bool direction = false; if (!features.empty() && features.front()->isDerivedFrom()) { - Part::Part2DObject* sketch = (static_cast(features.front()))->getVerifiedSketch(/* silent =*/ true); + Part::Part2DObject* sketch = (static_cast(features.front())) + ->getVerifiedSketch(/* silent =*/true); if (sketch) { - FCMD_OBJ_CMD(Feat,"MirrorPlane = ("<getOrigin()->getXY())<<", [''])"); + FCMD_OBJ_CMD( + Feat, + "MirrorPlane = (" << getObjectCmd(pcActiveBody->getOrigin()->getXY()) << ", [''])" + ); } finishTransformed(cmd, Feat); @@ -2043,45 +2265,60 @@ bool CmdPartDesignMirrored::isActive() DEF_STD_CMD_A(CmdPartDesignLinearPattern) CmdPartDesignLinearPattern::CmdPartDesignLinearPattern() - : Command("PartDesign_LinearPattern") + : Command("PartDesign_LinearPattern") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Linear Pattern"); - sToolTipText = QT_TR_NOOP("Duplicates the selected features or the active body in a linear pattern"); - sWhatsThis = "PartDesign_LinearPattern"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_LinearPattern"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Linear Pattern"); + sToolTipText = QT_TR_NOOP( + "Duplicates the selected features or the active body in a linear pattern" + ); + sWhatsThis = "PartDesign_LinearPattern"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_LinearPattern"; } void CmdPartDesignLinearPattern::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, pcActiveBody](App::DocumentObject *Feat, std::vector features) { - bool direction = false; - if (!features.empty() && features.front()->isDerivedFrom()) { - Part::Part2DObject *sketch = (static_cast(features.front()))->getVerifiedSketch(/* silent =*/ true); - if (sketch) { - FCMD_OBJ_CMD(Feat,"Direction = ("< features) { + bool direction = false; + if (!features.empty() && features.front()->isDerivedFrom()) { + Part::Part2DObject* sketch = (static_cast(features.front())) + ->getVerifiedSketch(/* silent =*/true); + if (sketch) { + FCMD_OBJ_CMD( + Feat, + "Direction = (" << Gui::Command::getObjectCmd(sketch) << ", ['H_Axis'])" + ); + FCMD_OBJ_CMD( + Feat, + "Direction2 = (" << Gui::Command::getObjectCmd(sketch) << ", ['V_Axis'])" + ); + direction = true; + } } - } - if (!direction) { - FCMD_OBJ_CMD(Feat,"Direction = ("<getOrigin()->getX())<<",[''])"); - } - FCMD_OBJ_CMD(Feat,"Length = 100"); - FCMD_OBJ_CMD(Feat,"Occurrences = 2"); + if (!direction) { + FCMD_OBJ_CMD( + Feat, + "Direction = (" << Gui::Command::getObjectCmd(pcActiveBody->getOrigin()->getX()) + << ",[''])" + ); + } + FCMD_OBJ_CMD(Feat, "Length = 100"); + FCMD_OBJ_CMD(Feat, "Occurrences = 2"); - finishTransformed(cmd, Feat); - }; + finishTransformed(cmd, Feat); + }; prepareTransformed(pcActiveBody, this, "LinearPattern", worker); } @@ -2097,43 +2334,50 @@ bool CmdPartDesignLinearPattern::isActive() DEF_STD_CMD_A(CmdPartDesignPolarPattern) CmdPartDesignPolarPattern::CmdPartDesignPolarPattern() - : Command("PartDesign_PolarPattern") + : Command("PartDesign_PolarPattern") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Polar Pattern"); - sToolTipText = QT_TR_NOOP("Duplicates the selected features or the active body in a circular pattern"); - sWhatsThis = "PartDesign_PolarPattern"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_PolarPattern"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Polar Pattern"); + sToolTipText = QT_TR_NOOP( + "Duplicates the selected features or the active body in a circular pattern" + ); + sWhatsThis = "PartDesign_PolarPattern"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_PolarPattern"; } void CmdPartDesignPolarPattern::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd, pcActiveBody](App::DocumentObject *Feat, std::vector features) { - + auto worker = [cmd, + pcActiveBody](App::DocumentObject* Feat, std::vector features) { bool direction = false; if (!features.empty() && features.front()->isDerivedFrom()) { - Part::Part2DObject *sketch = (static_cast(features.front()))->getVerifiedSketch(/* silent =*/ true); + Part::Part2DObject* sketch = (static_cast(features.front())) + ->getVerifiedSketch(/* silent =*/true); if (sketch) { - FCMD_OBJ_CMD(Feat,"Axis = ("<getOrigin()->getZ())<<",[''])"); + FCMD_OBJ_CMD( + Feat, + "Axis = (" << Gui::Command::getObjectCmd(pcActiveBody->getOrigin()->getZ()) << ",[''])" + ); } - FCMD_OBJ_CMD(Feat,"Angle = 360"); - FCMD_OBJ_CMD(Feat,"Occurrences = 2"); + FCMD_OBJ_CMD(Feat, "Angle = 360"); + FCMD_OBJ_CMD(Feat, "Occurrences = 2"); finishTransformed(cmd, Feat); }; @@ -2152,30 +2396,31 @@ bool CmdPartDesignPolarPattern::isActive() DEF_STD_CMD_A(CmdPartDesignScaled) CmdPartDesignScaled::CmdPartDesignScaled() - : Command("PartDesign_Scaled") + : Command("PartDesign_Scaled") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Scale"); - sToolTipText = QT_TR_NOOP("Scales the selected features or the active body"); - sWhatsThis = "PartDesign_Scaled"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Scaled"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Scale"); + sToolTipText = QT_TR_NOOP("Scales the selected features or the active body"); + sWhatsThis = "PartDesign_Scaled"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Scaled"; } void CmdPartDesignScaled::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::Command* cmd = this; - auto worker = [cmd](App::DocumentObject *Feat, std::vector /*features*/) { - FCMD_OBJ_CMD(Feat,"Factor = 2"); - FCMD_OBJ_CMD(Feat,"Occurrences = 2"); + auto worker = [cmd](App::DocumentObject* Feat, std::vector /*features*/) { + FCMD_OBJ_CMD(Feat, "Factor = 2"); + FCMD_OBJ_CMD(Feat, "Occurrences = 2"); finishTransformed(cmd, Feat); }; @@ -2194,24 +2439,27 @@ bool CmdPartDesignScaled::isActive() DEF_STD_CMD_A(CmdPartDesignMultiTransform) CmdPartDesignMultiTransform::CmdPartDesignMultiTransform() - : Command("PartDesign_MultiTransform") + : Command("PartDesign_MultiTransform") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Multi-Transform"); - sToolTipText = QT_TR_NOOP("Applies multiple transformations to the selected features or active body"); - sWhatsThis = "PartDesign_MultiTransform"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_MultiTransform"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Multi-Transform"); + sToolTipText = QT_TR_NOOP( + "Applies multiple transformations to the selected features or active body" + ); + sWhatsThis = "PartDesign_MultiTransform"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_MultiTransform"; } void CmdPartDesignMultiTransform::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } std::vector features; @@ -2219,32 +2467,39 @@ void CmdPartDesignMultiTransform::activated(int iMsg) features = getSelection().getObjectsOfType(PartDesign::Transformed::getClassTypeId()); if (!features.empty()) { // Throw out MultiTransform features, we don't want to nest them - for (std::vector::iterator f = features.begin(); f != features.end(); ) { - if ((*f)->isDerivedFrom()) + for (std::vector::iterator f = features.begin(); f != features.end();) { + if ((*f)->isDerivedFrom()) { f = features.erase(f); - else + } + else { f++; + } } - if (features.empty()) + if (features.empty()) { return; + } // Note: If multiple Transformed features were selected, only the first one is used PartDesign::Transformed* trFeat = static_cast(features.front()); // Move the insert point back one feature App::DocumentObject* oldTip = nullptr; App::DocumentObject* prevFeature = nullptr; - if (pcActiveBody){ + if (pcActiveBody) { oldTip = pcActiveBody->Tip.getValue(); prevFeature = pcActiveBody->getPrevSolidFeature(trFeat); } Gui::Selection().clearSelection(); - if (prevFeature) - Gui::Selection().addSelection(prevFeature->getDocument()->getName(), prevFeature->getNameInDocument()); + if (prevFeature) { + Gui::Selection().addSelection( + prevFeature->getDocument()->getName(), + prevFeature->getNameInDocument() + ); + } openCommand(QT_TRANSLATE_NOOP("Command", "Convert to Multi-Transform feature")); - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.runCommandByName("PartDesign_MoveTip"); // We cannot remove the Transform feature from the body as otherwise @@ -2260,16 +2515,16 @@ void CmdPartDesignMultiTransform::activated(int iMsg) #endif // Create a MultiTransform feature and move the Transformed feature inside it - std::string FeatName = getUniqueObjectName("MultiTransform",pcActiveBody); - FCMD_OBJ_CMD(pcActiveBody,"newObject('PartDesign::MultiTransform','"<getDocument()->getObject(FeatName.c_str()); auto objCmd = getObjectCmd(trFeat); - FCMD_OBJ_CMD(Feat,"Originals = "<getDocument()->getName(), oldTip->getNameInDocument()); rcCmdMgr.runCommandByName("PartDesign_MoveTip"); Gui::Selection().clearSelection(); - } // otherwise the insert point remains at the new MultiTransform, which is fine - } else { + } // otherwise the insert point remains at the new MultiTransform, which is fine + } + else { Gui::Command* cmd = this; - auto worker = [cmd, pcActiveBody](App::DocumentObject *Feat, std::vector /*features*/) { - // Make sure the user isn't presented with an empty screen because no transformations are defined yet... - App::DocumentObject* prevSolid = pcActiveBody->Tip.getValue(); - if (prevSolid) { - Part::Feature* feat = static_cast(prevSolid); - FCMD_OBJ_CMD(Feat,"Shape = "< /*features*/) { + // Make sure the user isn't presented with an empty screen because no + // transformations are defined yet... + App::DocumentObject* prevSolid = pcActiveBody->Tip.getValue(); + if (prevSolid) { + Part::Feature* feat = static_cast(prevSolid); + FCMD_OBJ_CMD(Feat, "Shape = " << getObjectCmd(feat) << ".Shape"); + } + finishFeature(cmd, Feat); + }; prepareTransformed(pcActiveBody, this, "MultiTransform", worker); } @@ -2311,30 +2570,33 @@ bool CmdPartDesignMultiTransform::isActive() DEF_STD_CMD_A(CmdPartDesignBoolean) CmdPartDesignBoolean::CmdPartDesignBoolean() - :Command("PartDesign_Boolean") + : Command("PartDesign_Boolean") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Boolean Operation"); - sToolTipText = QT_TR_NOOP("Applies boolean operations with the selected objects and the active body"); - sWhatsThis = "PartDesign_Boolean"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Boolean"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Boolean Operation"); + sToolTipText = QT_TR_NOOP( + "Applies boolean operations with the selected objects and the active body" + ); + sWhatsThis = "PartDesign_Boolean"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Boolean"; } void CmdPartDesignBoolean::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */true); - if (!pcActiveBody) + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */ true); + if (!pcActiveBody) { return; + } Gui::SelectionFilter BodyFilter("SELECT Part::Feature COUNT 1.."); openCommand(QT_TRANSLATE_NOOP("Command", "Create Boolean")); - std::string FeatName = getUniqueObjectName("Boolean",pcActiveBody); - FCMD_OBJ_CMD(pcActiveBody,"newObject('PartDesign::Boolean','"<getDocument()->getObject(FeatName.c_str()); static_cast(Feat)->UsePlacement.setValue(true); @@ -2344,15 +2606,16 @@ void CmdPartDesignBoolean::activated(int iMsg) if (BodyFilter.match() && !BodyFilter.Result.empty()) { std::vector bodies; for (auto& results : BodyFilter.Result) { - for (auto & result : results) { - if (result.getObject() != pcActiveBody) + for (auto& result : results) { + if (result.getObject() != pcActiveBody) { bodies.push_back(result.getObject()); + } } } if (!bodies.empty()) { updateDocument = true; std::string bodyString = PartDesignGui::buildLinkListPythonStr(bodies); - FCMD_OBJ_CMD(Feat,"addObjects("<commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPartDesignShapeBinder()); rcCmdMgr.addCommand(new CmdPartDesignSubShapeBinder()); @@ -2475,7 +2740,7 @@ void CreatePartDesignCommands() rcCmdMgr.addCommand(new CmdPartDesignMirrored()); rcCmdMgr.addCommand(new CmdPartDesignLinearPattern()); rcCmdMgr.addCommand(new CmdPartDesignPolarPattern()); - //rcCmdMgr.addCommand(new CmdPartDesignScaled()); + // rcCmdMgr.addCommand(new CmdPartDesignScaled()); rcCmdMgr.addCommand(new CmdPartDesignMultiTransform()); rcCmdMgr.addCommand(new CmdPartDesignBoolean()); diff --git a/src/Mod/PartDesign/Gui/CommandBody.cpp b/src/Mod/PartDesign/Gui/CommandBody.cpp index a922740640..a22dcbcfde 100644 --- a/src/Mod/PartDesign/Gui/CommandBody.cpp +++ b/src/Mod/PartDesign/Gui/CommandBody.cpp @@ -21,10 +21,10 @@ ***************************************************************************/ -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -53,88 +53,103 @@ // Shared functions //=========================================================================== -namespace PartDesignGui { +namespace PartDesignGui +{ /// Returns active part, if there is no such, creates a new part, if it fails, shows a message -App::Part* assertActivePart () { - App::Part* rv= Gui::Application::Instance->activeView()->getActiveObject ( PARTKEY ); +App::Part* assertActivePart() +{ + App::Part* rv = Gui::Application::Instance->activeView()->getActiveObject(PARTKEY); - if ( !rv ) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + if (!rv) { + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.runCommandByName("Std_Part"); - rv = Gui::Application::Instance->activeView()->getActiveObject ( PARTKEY ); - if ( !rv ) { - QMessageBox::critical ( nullptr, QObject::tr( "Part creation failed" ), - QObject::tr( "Failed to create a part object." ) ); + rv = Gui::Application::Instance->activeView()->getActiveObject(PARTKEY); + if (!rv) { + QMessageBox::critical( + nullptr, + QObject::tr("Part creation failed"), + QObject::tr("Failed to create a part object.") + ); } } return rv; } -} /* PartDesignGui */ +} // namespace PartDesignGui // PartDesign_Body //=========================================================================== DEF_STD_CMD_A(CmdPartDesignBody) CmdPartDesignBody::CmdPartDesignBody() - : Command("PartDesign_Body") + : Command("PartDesign_Body") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("New Body"); - sToolTipText = QT_TR_NOOP("Creates a new body and activates it"); - sWhatsThis = "PartDesign_Body"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Body"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("New Body"); + sToolTipText = QT_TR_NOOP("Creates a new body and activates it"); + sWhatsThis = "PartDesign_Body"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Body"; } void CmdPartDesignBody::activated(int iMsg) { Q_UNUSED(iMsg); - App::Part *actPart = PartDesignGui::getActivePart (); + App::Part* actPart = PartDesignGui::getActivePart(); App::Part* partOfBaseFeature = nullptr; - std::vector features = - getSelection().getObjectsOfType(Part::Feature::getClassTypeId()); + std::vector features = getSelection().getObjectsOfType( + Part::Feature::getClassTypeId() + ); App::DocumentObject* baseFeature = nullptr; bool addtogroup = false; - Base::Reference hGrp = App::GetApplication() - .GetUserParameter() - .GetGroup("BaseApp/Preferences/Mod/PartDesign"); + Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup( + "BaseApp/Preferences/Mod/PartDesign" + ); bool allowCompound = hGrp->GetBool("AllowCompoundDefault", true); if (!features.empty()) { if (features.size() == 1) { baseFeature = features[0]; - if ( baseFeature->isDerivedFrom ( PartDesign::Feature::getClassTypeId() ) && - PartDesign::Body::findBodyOf ( baseFeature ) ) { + if (baseFeature->isDerivedFrom(PartDesign::Feature::getClassTypeId()) + && PartDesign::Body::findBodyOf(baseFeature)) { // Prevent creating bodies based on features already belonging to other bodies - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"), - QObject::tr("A body cannot be based on a Part Design feature.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Bad base feature"), + QObject::tr("A body cannot be based on a Part Design feature.") + ); baseFeature = nullptr; } - else if (PartDesign::Body::findBodyOf ( baseFeature )){ - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"), - QObject::tr("%1 already belongs to a body and cannot be used as a base feature for another body.") - .arg(QString::fromUtf8(baseFeature->Label.getValue()))); + else if (PartDesign::Body::findBodyOf(baseFeature)) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Bad base feature"), + QObject::tr("%1 already belongs to a body and cannot be used as a base feature for another body.") + .arg(QString::fromUtf8(baseFeature->Label.getValue())) + ); baseFeature = nullptr; } - else if ( baseFeature->isDerivedFrom ( Part::BodyBase::getClassTypeId() ) ) { + else if (baseFeature->isDerivedFrom(Part::BodyBase::getClassTypeId())) { // Prevent creating bodies based on bodies (but don't pop-up a dialog) baseFeature = nullptr; } else { partOfBaseFeature = App::Part::getPartOfObject(baseFeature); - if (partOfBaseFeature && partOfBaseFeature != actPart){ - //prevent cross-part mess - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"), - QObject::tr("Base feature (%1) belongs to other part.") - .arg(QString::fromUtf8(baseFeature->Label.getValue()))); + if (partOfBaseFeature && partOfBaseFeature != actPart) { + // prevent cross-part mess + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Bad base feature"), + QObject::tr("Base feature (%1) belongs to other part.") + .arg(QString::fromUtf8(baseFeature->Label.getValue())) + ); baseFeature = nullptr; } else if (baseFeature->isDerivedFrom()) { @@ -144,45 +159,62 @@ void CmdPartDesignBody::activated(int iMsg) // if a standard Part feature (not a PartDesign feature) is selected then check // the number of solids/shells else if (!baseFeature->isDerivedFrom()) { - const TopoDS_Shape& shape = static_cast(baseFeature)->Shape.getValue(); + const TopoDS_Shape& shape + = static_cast(baseFeature)->Shape.getValue(); if (!shape.IsNull()) { int numSolids = 0; int numShells = 0; for (TopExp_Explorer xp(shape, TopAbs_SOLID); xp.More(); xp.Next()) { numSolids++; } - for (TopExp_Explorer xp(shape, TopAbs_SHELL, TopAbs_SOLID); xp.More(); xp.Next()) { + for (TopExp_Explorer xp(shape, TopAbs_SHELL, TopAbs_SOLID); xp.More(); + xp.Next()) { numShells++; } QString warning; if (numSolids > 1 && numShells == 0) { - warning = QObject::tr("The selected shape consists of multiple solids.\n" - "This may lead to unexpected results."); + warning = QObject::tr( + "The selected shape consists of multiple solids.\n" + "This may lead to unexpected results." + ); } else if (numShells > 1 && numSolids == 0) { - warning = QObject::tr("The selected shape consists of multiple shells.\n" - "This may lead to unexpected results."); + warning = QObject::tr( + "The selected shape consists of multiple shells.\n" + "This may lead to unexpected results." + ); } else if (numShells == 1 && numSolids == 0) { - warning = QObject::tr("The selected shape consists of only a shell.\n" - "This may lead to unexpected results."); + warning = QObject::tr( + "The selected shape consists of only a shell.\n" + "This may lead to unexpected results." + ); } else if (numSolids + numShells > 1) { - warning = QObject::tr("The selected shape consists of multiple solids or shells.\n" - "This may lead to unexpected results."); + warning = QObject::tr( + "The selected shape consists of multiple solids or shells.\n" + "This may lead to unexpected results." + ); } if (!warning.isEmpty()) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Base feature"), warning); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Base feature"), + warning + ); } } } } - - } else { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"), - QObject::tr("Body may be based on no more than one feature.")); + } + else { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Bad base feature"), + QObject::tr("Body may be based on no more than one feature.") + ); return; } } @@ -194,46 +226,72 @@ void CmdPartDesignBody::activated(int iMsg) const char* bodyString = bodyName.c_str(); // add the Body feature itself, and make it active - doCommand(Doc,"App.activeDocument().addObject('PartDesign::Body','%s')", bodyString); + doCommand(Doc, "App.activeDocument().addObject('PartDesign::Body','%s')", bodyString); // set Label for i18n/L10N std::string labelString = QObject::tr("Body").toUtf8().toStdString(); labelString = Base::Tools::escapeEncodeString(labelString); - doCommand(Doc,"App.ActiveDocument.getObject('%s').Label = '%s'", bodyString, labelString.c_str()); - doCommand(Doc,"App.ActiveDocument.getObject('%s').AllowCompound = %s", bodyString, allowCompound ? "True" : "False"); + doCommand(Doc, "App.ActiveDocument.getObject('%s').Label = '%s'", bodyString, labelString.c_str()); + doCommand( + Doc, + "App.ActiveDocument.getObject('%s').AllowCompound = %s", + bodyString, + allowCompound ? "True" : "False" + ); if (baseFeature) { - if (partOfBaseFeature){ - //withdraw base feature from Part, otherwise visibility madness results - doCommand(Doc,"App.activeDocument().%s.removeObject(App.activeDocument().%s)", - partOfBaseFeature->getNameInDocument(), baseFeature->getNameInDocument()); + if (partOfBaseFeature) { + // withdraw base feature from Part, otherwise visibility madness results + doCommand( + Doc, + "App.activeDocument().%s.removeObject(App.activeDocument().%s)", + partOfBaseFeature->getNameInDocument(), + baseFeature->getNameInDocument() + ); } if (addtogroup) { - doCommand(Doc,"App.activeDocument().%s.Group = [App.activeDocument().%s]", - bodyString, baseFeature->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().%s.Group = [App.activeDocument().%s]", + bodyString, + baseFeature->getNameInDocument() + ); } else { - doCommand(Doc,"App.activeDocument().%s.BaseFeature = App.activeDocument().%s", - bodyString, baseFeature->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().%s.BaseFeature = App.activeDocument().%s", + bodyString, + baseFeature->getNameInDocument() + ); } } - addModule(Gui,"PartDesignGui"); // import the Gui module only once a session + addModule(Gui, "PartDesignGui"); // import the Gui module only once a session if (actPart) { - doCommand(Doc,"App.activeDocument().%s.addObject(App.ActiveDocument.%s)", - actPart->getNameInDocument(), bodyString); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.ActiveDocument.%s)", + actPart->getNameInDocument(), + bodyString + ); } - doCommand(Gui::Command::Gui, "Gui.activateView('Gui::View3DInventor', True)\n" - "Gui.activeView().setActiveObject('%s', App.activeDocument().%s)", - PDBODYKEY, bodyString); + doCommand( + Gui::Command::Gui, + "Gui.activateView('Gui::View3DInventor', True)\n" + "Gui.activeView().setActiveObject('%s', App.activeDocument().%s)", + PDBODYKEY, + bodyString + ); // Make the "Create sketch" prompt appear in the task panel - doCommand(Gui,"Gui.Selection.clearSelection()"); - doCommand(Gui,"Gui.Selection.addSelection(App.ActiveDocument.%s)", bodyString); + doCommand(Gui, "Gui.Selection.clearSelection()"); + doCommand(Gui, "Gui.Selection.addSelection(App.ActiveDocument.%s)", bodyString); // check if a proxy object has been created for the base feature inside the body if (baseFeature) { - PartDesign::Body* body = dynamic_cast - (baseFeature->getDocument()->getObject(bodyString)); + PartDesign::Body* body = dynamic_cast( + baseFeature->getDocument()->getObject(bodyString) + ); if (body) { std::vector links = body->Group.getValues(); for (auto it : links) { @@ -252,8 +310,8 @@ void CmdPartDesignBody::activated(int iMsg) std::vector planes; std::vector status; unsigned validPlaneCount = 0; - for (auto plane: body->getOrigin ()->planes()) { - planes.push_back (plane); + for (auto plane : body->getOrigin()->planes()) { + planes.push_back(plane); status.push_back(PartDesignGui::TaskFeaturePick::basePlane); validPlaneCount++; } @@ -268,29 +326,39 @@ void CmdPartDesignBody::activated(int iMsg) auto worker = [baseFeature](const std::vector& features) { // may happen when the user switched to an empty document while the // dialog is open - if (features.empty()) + if (features.empty()) { return; + } App::Plane* plane = static_cast(features.front()); - std::string supportString = Gui::Command::getObjectCmd(plane,"(",", [''])"); + std::string supportString = Gui::Command::getObjectCmd(plane, "(", ", [''])"); - FCMD_OBJ_CMD(baseFeature,"AttachmentSupport = " << supportString); - FCMD_OBJ_CMD(baseFeature,"MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) << "'"); + FCMD_OBJ_CMD(baseFeature, "AttachmentSupport = " << supportString); + FCMD_OBJ_CMD( + baseFeature, + "MapMode = '" + << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) << "'" + ); Gui::Command::updateActive(); }; // Called by dialog for "Cancel", or "OK" if accepter returns false std::string docname = getDocument()->getName(); auto quitter = [docname]() { - Gui::Document* document = Gui::Application::Instance->getDocument(docname.c_str()); - if (document) + Gui::Document* document = Gui::Application::Instance->getDocument( + docname.c_str() + ); + if (document) { document->abortCommand(); + } }; // Show dialog and let user pick plane - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); if (!dlg) { Gui::Selection().clearSelection(); - Gui::Control().showDialog(new PartDesignGui::TaskDlgFeaturePick(planes, status, accepter, worker, true, quitter)); + Gui::Control().showDialog( + new PartDesignGui::TaskDlgFeaturePick(planes, status, accepter, worker, true, quitter) + ); } } } @@ -312,212 +380,263 @@ bool CmdPartDesignBody::isActive() DEF_STD_CMD_A(CmdPartDesignMigrate) CmdPartDesignMigrate::CmdPartDesignMigrate() - : Command("PartDesign_Migrate") + : Command("PartDesign_Migrate") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Migrate"); - sToolTipText = QT_TR_NOOP("Migrates the document to the modern Part Design workflow"); - sWhatsThis = "PartDesign_Migrate"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_Migrate"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Migrate"); + sToolTipText = QT_TR_NOOP("Migrates the document to the modern Part Design workflow"); + sWhatsThis = "PartDesign_Migrate"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_Migrate"; } void CmdPartDesignMigrate::activated(int iMsg) { Q_UNUSED(iMsg); - App::Document *doc = getDocument(); + App::Document* doc = getDocument(); std::set migrateFeatures; // Retrieve all PartDesign Features objects and filter out features already belonging to some body - for ( const auto & feat: doc->getObjects( ) ) { - if( feat->isDerivedFrom( PartDesign::Feature::getClassTypeId() ) && - !PartDesign::Body::findBodyOf( feat ) && PartDesign::Body::isSolidFeature ( feat ) ) { - migrateFeatures.insert ( static_cast ( feat ) ); - } + for (const auto& feat : doc->getObjects()) { + if (feat->isDerivedFrom(PartDesign::Feature::getClassTypeId()) + && !PartDesign::Body::findBodyOf(feat) && PartDesign::Body::isSolidFeature(feat)) { + migrateFeatures.insert(static_cast(feat)); + } } - if ( migrateFeatures.empty() ) { - if ( !PartDesignGui::isModernWorkflow ( doc ) ) { + if (migrateFeatures.empty()) { + if (!PartDesignGui::isModernWorkflow(doc)) { // If there is nothing to migrate and workflow is still old just set it to modern - PartDesignGui::WorkflowManager::instance()->forceWorkflow ( - doc, PartDesignGui::Workflow::Modern ); - } else { + PartDesignGui::WorkflowManager::instance()->forceWorkflow( + doc, + PartDesignGui::Workflow::Modern + ); + } + else { // Huh? nothing to migrate? - QMessageBox::warning ( nullptr, QObject::tr ( "Nothing to migrate" ), - QObject::tr ( "No Part Design features without body found" - " Nothing to migrate." ) ); + QMessageBox::warning( + nullptr, + QObject::tr("Nothing to migrate"), + QObject::tr( + "No Part Design features without body found" + " Nothing to migrate." + ) + ); } return; } // Note: this action is undoable, should it be? - PartDesignGui::WorkflowManager::instance()->forceWorkflow ( doc, PartDesignGui::Workflow::Modern ); + PartDesignGui::WorkflowManager::instance()->forceWorkflow(doc, PartDesignGui::Workflow::Modern); // Put features into chains. Each chain should become a separate body. - std::list< std::list > featureChains; - std::list chain; //< the current chain we are working on + std::list> featureChains; + std::list chain; //< the current chain we are working on - for (auto featIt = migrateFeatures.begin(); !migrateFeatures.empty(); ) { - Part::Feature *base = (*featIt)->getBaseObject( /*silent =*/ true ); + for (auto featIt = migrateFeatures.begin(); !migrateFeatures.empty();) { + Part::Feature* base = (*featIt)->getBaseObject(/*silent =*/true); - chain.push_front ( *featIt ); + chain.push_front(*featIt); - if ( !base || !base->isDerivedFrom (PartDesign::Feature::getClassTypeId () ) || - PartDesignGui::isAnyNonPartDesignLinksTo ( static_cast (base), - /*respectGroups=*/ true ) ) { + if (!base || !base->isDerivedFrom(PartDesign::Feature::getClassTypeId()) + || PartDesignGui::isAnyNonPartDesignLinksTo( + static_cast(base), + /*respectGroups=*/true + )) { // a feature based on nothing as well as on non-partdesign solid starts a new chain - auto newChainIt = featureChains.emplace (featureChains.end()); - newChainIt->splice (newChainIt->end(), chain); - } else { + auto newChainIt = featureChains.emplace(featureChains.end()); + newChainIt->splice(newChainIt->end(), chain); + } + else { // we are basing on some partdesign feature which supposed to belong to some body - PartDesign::Feature *baseFeat = static_cast ( base ); + PartDesign::Feature* baseFeat = static_cast(base); auto baseFeatSetIt = migrateFeatures.find(baseFeat); - if ( baseFeatSetIt != migrateFeatures.end() ) { + if (baseFeatSetIt != migrateFeatures.end()) { // base feature is pending for migration, switch to it and continue over migrateFeatures.erase(featIt); featIt = baseFeatSetIt; continue; - } else { + } + else { // The base feature seems already assigned to some chain. Find which - std::list::iterator baseFeatIt; - auto isChain = [baseFeat, &baseFeatIt]( - std::list& fchain) mutable -> bool { + std::list::iterator baseFeatIt; + auto isChain = + [baseFeat, &baseFeatIt](std::list& fchain) mutable -> bool { baseFeatIt = std::ranges::find(fchain, baseFeat); return baseFeatIt != fchain.end(); }; if (auto chainIt = std::ranges::find_if(featureChains, isChain); - chainIt != featureChains.end() ) { - assert (baseFeatIt != chainIt->end()); - if ( std::next ( baseFeatIt ) == chainIt->end() ) { + chainIt != featureChains.end()) { + assert(baseFeatIt != chainIt->end()); + if (std::next(baseFeatIt) == chainIt->end()) { // just append our chain to already found - chainIt->splice ( chainIt->end(), chain ); + chainIt->splice(chainIt->end(), chain); // TODO: If we will hit a third part everything will be messed up again. - // Probably it will require a yet another smart-ass find_if. (2015-08-10, Fat-Zer) - } else { + // Probably it will require a yet another smart-ass find_if. + // (2015-08-10, Fat-Zer) + } + else { // We have a fork of a partDesign feature here // add a chain for current body - auto newChainIt = featureChains.emplace (featureChains.end()); - newChainIt->splice (newChainIt->end(), chain); + auto newChainIt = featureChains.emplace(featureChains.end()); + newChainIt->splice(newChainIt->end(), chain); // add a chain for forked one - newChainIt = featureChains.emplace (featureChains.end()); - newChainIt->splice (newChainIt->end(), *chainIt, - std::next ( baseFeatIt ), chainIt->end()); + newChainIt = featureChains.emplace(featureChains.end()); + newChainIt->splice( + newChainIt->end(), + *chainIt, + std::next(baseFeatIt), + chainIt->end() + ); } - } else { + } + else { // The feature is not present in list pending for migration, // This generally shouldn't happen but may be if we run into some broken file // Try to find out the body we should insert into // TODO: Some error/warning is needed here (2015-08-10, Fat-Zer) - auto newChainIt = featureChains.emplace (featureChains.end()); - newChainIt->splice (newChainIt->end(), chain); + auto newChainIt = featureChains.emplace(featureChains.end()); + newChainIt->splice(newChainIt->end(), chain); } } } - migrateFeatures.erase ( featIt ); - featIt = migrateFeatures.begin (); + migrateFeatures.erase(featIt); + featIt = migrateFeatures.begin(); // TODO: Align visibility (2015-08-17, Fat-Zer) } /* for */ // TODO: make it work without parts (2015-09-04, Fat-Zer) // add a part if there is no active yet - App::Part *actPart = PartDesignGui::assertActivePart (); + App::Part* actPart = PartDesignGui::assertActivePart(); if (!actPart) { return; } // do the actual migration - Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Migrate legacy Part Design features to bodies")); + Gui::Command::openCommand( + QT_TRANSLATE_NOOP("Command", "Migrate legacy Part Design features to bodies") + ); - for ( auto chainIt = featureChains.begin(); !featureChains.empty(); - featureChains.erase (chainIt), chainIt = featureChains.begin () ) { + for (auto chainIt = featureChains.begin(); !featureChains.empty(); + featureChains.erase(chainIt), chainIt = featureChains.begin()) { #ifndef FC_DEBUG - if ( chainIt->empty () ) { // prevent crash in release in case of errors + if (chainIt->empty()) { // prevent crash in release in case of errors continue; } #else - assert ( !chainIt->empty () ); + assert(!chainIt->empty()); #endif - Part::Feature *base = chainIt->front()->getBaseObject ( /*silent =*/ true ); + Part::Feature* base = chainIt->front()->getBaseObject(/*silent =*/true); // Find a suitable chain to work with - for( ; chainIt != featureChains.end(); chainIt ++) { - base = chainIt->front()->getBaseObject ( /*silent =*/ true ); - if (!base || !base->isDerivedFrom ( PartDesign::Feature::getClassTypeId () ) ) { - break; // no base is ok - } else { + for (; chainIt != featureChains.end(); chainIt++) { + base = chainIt->front()->getBaseObject(/*silent =*/true); + if (!base || !base->isDerivedFrom(PartDesign::Feature::getClassTypeId())) { + break; // no base is ok + } + else { // The base feature is a PartDesign, it's a fork, try to reassign it to a body... - base = PartDesign::Body::findBodyOf ( base ); - if ( base ) { + base = PartDesign::Body::findBodyOf(base); + if (base) { break; } } } - if ( chainIt == featureChains.end() ) { + if (chainIt == featureChains.end()) { // Shouldn't happen, may be only in case of some circular dependency? // TODO Some error message (2015-08-11, Fat-Zer) chainIt = featureChains.begin(); - base = chainIt->front()->getBaseObject ( /*silent =*/ true ); + base = chainIt->front()->getBaseObject(/*silent =*/true); } // Construct a Pretty Body name based on the Tip - std::string bodyName = getUniqueObjectName ( - std::string ( chainIt->back()->getNameInDocument() ).append ( "Body" ).c_str () ) ; + std::string bodyName = getUniqueObjectName( + std::string(chainIt->back()->getNameInDocument()).append("Body").c_str() + ); - Base::Reference hGrp = App::GetApplication() - .GetUserParameter() - .GetGroup("BaseApp/Preferences/Mod/PartDesign"); + Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup( + "BaseApp/Preferences/Mod/PartDesign" + ); bool allowCompound = hGrp->GetBool("AllowCompoundDefault", true); // Create a body for the chain - doCommand ( Doc,"App.activeDocument().addObject('PartDesign::Body','%s')", bodyName.c_str () ); - doCommand ( Doc,"App.ActiveDocument.getObject('%s').AllowCompound = %s", bodyName.c_str(), allowCompound ? "True" : "False"); - doCommand ( Doc,"App.activeDocument().%s.addObject(App.ActiveDocument.%s)", - actPart->getNameInDocument (), bodyName.c_str () ); + doCommand(Doc, "App.activeDocument().addObject('PartDesign::Body','%s')", bodyName.c_str()); + doCommand( + Doc, + "App.ActiveDocument.getObject('%s').AllowCompound = %s", + bodyName.c_str(), + allowCompound ? "True" : "False" + ); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.ActiveDocument.%s)", + actPart->getNameInDocument(), + bodyName.c_str() + ); if (base) { - doCommand ( Doc,"App.activeDocument().%s.BaseFeature = App.activeDocument().%s", - bodyName.c_str (), base->getNameInDocument () ); + doCommand( + Doc, + "App.activeDocument().%s.BaseFeature = App.activeDocument().%s", + bodyName.c_str(), + base->getNameInDocument() + ); } // Fill the body with features - for ( auto feature: *chainIt ) { - if ( feature->isDerivedFrom ( PartDesign::ProfileBased::getClassTypeId() ) ) { + for (auto feature : *chainIt) { + if (feature->isDerivedFrom(PartDesign::ProfileBased::getClassTypeId())) { // add the sketch and also reroute it if needed - PartDesign::ProfileBased *sketchBased = static_cast ( feature ); - Part::Part2DObject *sketch = sketchBased->getVerifiedSketch( /*silent =*/ true); - if ( sketch ) { - doCommand ( Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)", - bodyName.c_str (), sketch->getNameInDocument() ); + PartDesign::ProfileBased* sketchBased = static_cast(feature); + Part::Part2DObject* sketch = sketchBased->getVerifiedSketch(/*silent =*/true); + if (sketch) { + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + bodyName.c_str(), + sketch->getNameInDocument() + ); - if ( sketch->isDerivedFrom ( Sketcher::SketchObject::getClassTypeId() ) ) { + if (sketch->isDerivedFrom(Sketcher::SketchObject::getClassTypeId())) { try { - PartDesignGui::fixSketchSupport ( static_cast ( sketch ) ); - } catch (Base::Exception &) { - QMessageBox::critical(Gui::getMainWindow(), - QObject::tr("Sketch plane cannot be migrated"), - QObject::tr("Please edit '%1' and redefine it to use a Base or " - "Datum plane as the sketch plane."). - arg(QString::fromUtf8(sketch->Label.getValue()) ) ); + PartDesignGui::fixSketchSupport( + static_cast(sketch) + ); } - } else { + catch (Base::Exception&) { + QMessageBox::critical( + Gui::getMainWindow(), + QObject::tr("Sketch plane cannot be migrated"), + QObject::tr( + "Please edit '%1' and redefine it to use a Base or " + "Datum plane as the sketch plane." + ) + .arg(QString::fromUtf8(sketch->Label.getValue())) + ); + } + } + else { // TODO: Message that sketchbased is based not on a sketch (2015-08-11, Fat-Zer) } } } - doCommand ( Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)", - bodyName.c_str (), feature->getNameInDocument() ); + doCommand( + Doc, + "App.activeDocument().%s.addObject(App.activeDocument().%s)", + bodyName.c_str(), + feature->getNameInDocument() + ); - PartDesignGui::relinkToBody ( feature ); + PartDesignGui::relinkToBody(feature); } - } updateActive(); @@ -534,70 +653,88 @@ bool CmdPartDesignMigrate::isActive() DEF_STD_CMD_A(CmdPartDesignMoveTip) CmdPartDesignMoveTip::CmdPartDesignMoveTip() - : Command("PartDesign_MoveTip") + : Command("PartDesign_MoveTip") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Set Tip"); - sToolTipText = QT_TR_NOOP("Moves the tip of the body to the selected feature"); - sWhatsThis = "PartDesign_MoveTip"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_MoveTip"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Set Tip"); + sToolTipText = QT_TR_NOOP("Moves the tip of the body to the selected feature"); + sWhatsThis = "PartDesign_MoveTip"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_MoveTip"; } void CmdPartDesignMoveTip::activated(int iMsg) { Q_UNUSED(iMsg); std::vector features = getSelection().getObjectsOfType( - Part::Feature::getClassTypeId() ); + Part::Feature::getClassTypeId() + ); App::DocumentObject* selFeature; - PartDesign::Body* body= nullptr; + PartDesign::Body* body = nullptr; - if ( features.size() == 1 ) { + if (features.size() == 1) { selFeature = features.front(); - if ( selFeature->isDerivedFrom() ) { - body = static_cast ( selFeature ); - } else { - body = PartDesignGui::getBodyFor ( selFeature, /* messageIfNot =*/ false ); + if (selFeature->isDerivedFrom()) { + body = static_cast(selFeature); } - } else { + else { + body = PartDesignGui::getBodyFor(selFeature, /* messageIfNot =*/false); + } + } + else { selFeature = nullptr; } if (!selFeature) { - QMessageBox::warning (nullptr, QObject::tr( "Selection error" ), - QObject::tr( "Select exactly one Part Design feature or a body." ) ); + QMessageBox::warning( + nullptr, + QObject::tr("Selection error"), + QObject::tr("Select exactly one Part Design feature or a body.") + ); return; - } else if (!body) { - QMessageBox::warning (nullptr, QObject::tr( "Selection error" ), - QObject::tr( "Could not determine a body for the selected feature '%s'.", selFeature->Label.getValue() ) ); + } + else if (!body) { + QMessageBox::warning( + nullptr, + QObject::tr("Selection error"), + QObject::tr( + "Could not determine a body for the selected feature '%s'.", + selFeature->Label.getValue() + ) + ); return; - } else if ( !selFeature->isDerivedFrom(PartDesign::Feature::getClassTypeId () ) && - selFeature != body && body->BaseFeature.getValue() != selFeature ) { - QMessageBox::warning (nullptr, QObject::tr( "Selection error" ), - QObject::tr( "Only a solid feature can be the tip of a body." ) ); + } + else if (!selFeature->isDerivedFrom(PartDesign::Feature::getClassTypeId()) && selFeature != body + && body->BaseFeature.getValue() != selFeature) { + QMessageBox::warning( + nullptr, + QObject::tr("Selection error"), + QObject::tr("Only a solid feature can be the tip of a body.") + ); return; } App::DocumentObject* oldTip = body->Tip.getValue(); - if (oldTip == selFeature) { // it's not generally an error, so print only a console message - Base::Console().message ("%s is already the tip of the body\n", selFeature->getNameInDocument () ); + if (oldTip == selFeature) { // it's not generally an error, so print only a console message + Base::Console().message("%s is already the tip of the body\n", selFeature->getNameInDocument()); return; } openCommand(QT_TRANSLATE_NOOP("Command", "Move tip to selected feature")); if (selFeature == body) { - FCMD_OBJ_CMD(body,"Tip = None"); - } else { - FCMD_OBJ_CMD(body,"Tip = " << getObjectCmd(selFeature)); + FCMD_OBJ_CMD(body, "Tip = None"); + } + else { + FCMD_OBJ_CMD(body, "Tip = " << getObjectCmd(selFeature)); // Adjust visibility to show only the Tip feature FCMD_OBJ_SHOW(selFeature); } - // TODO: Hide all datum features after the Tip feature? But the user might have already hidden some and wants to see - // others, so we would have to remember their state somehow + // TODO: Hide all datum features after the Tip feature? But the user might have already hidden + // some and wants to see others, so we would have to remember their state somehow updateActive(); } @@ -613,25 +750,25 @@ bool CmdPartDesignMoveTip::isActive() DEF_STD_CMD_A(CmdPartDesignDuplicateSelection) CmdPartDesignDuplicateSelection::CmdPartDesignDuplicateSelection() - :Command("PartDesign_DuplicateSelection") + : Command("PartDesign_DuplicateSelection") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Duplicate &Object"); - sToolTipText = QT_TR_NOOP("Duplicates the selected object and adds it to the active body"); - sWhatsThis = "PartDesign_DuplicateSelection"; - sStatusTip = sToolTipText; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Duplicate &Object"); + sToolTipText = QT_TR_NOOP("Duplicates the selected object and adds it to the active body"); + sWhatsThis = "PartDesign_DuplicateSelection"; + sStatusTip = sToolTipText; } void CmdPartDesignDuplicateSelection::activated(int iMsg) { Q_UNUSED(iMsg); - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */false); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */ false); std::vector beforeFeatures = getDocument()->getObjects(); openCommand(QT_TRANSLATE_NOOP("Command", "Duplicate a Part Design object")); - doCommand(Doc,"FreeCADGui.runCommand('Std_DuplicateSelection')"); + doCommand(Doc, "FreeCADGui.runCommand('Std_DuplicateSelection')"); if (pcActiveBody) { // Find the features that were added @@ -639,23 +776,29 @@ void CmdPartDesignDuplicateSelection::activated(int iMsg) std::vector newFeatures; std::sort(beforeFeatures.begin(), beforeFeatures.end()); std::sort(afterFeatures.begin(), afterFeatures.end()); - std::set_difference(afterFeatures.begin(), afterFeatures.end(), beforeFeatures.begin(), beforeFeatures.end(), - std::back_inserter(newFeatures)); + std::set_difference( + afterFeatures.begin(), + afterFeatures.end(), + beforeFeatures.begin(), + beforeFeatures.end(), + std::back_inserter(newFeatures) + ); for (auto feature : newFeatures) { if (PartDesign::Body::isAllowed(feature)) { // if feature already is in a body, then we don't put it into the active body issue #6278 auto body = App::GeoFeatureGroupExtension::getGroupOfObject(feature); if (!body) { - FCMD_OBJ_CMD(pcActiveBody,"addObject(" << getObjectCmd(feature) << ")"); + FCMD_OBJ_CMD(pcActiveBody, "addObject(" << getObjectCmd(feature) << ")"); FCMD_OBJ_HIDE(feature); } } } // Adjust visibility of features - if (!newFeatures.empty()) + if (!newFeatures.empty()) { FCMD_OBJ_SHOW(newFeatures.back()); + } } updateActive(); @@ -673,42 +816,52 @@ bool CmdPartDesignDuplicateSelection::isActive() DEF_STD_CMD_A(CmdPartDesignMoveFeature) CmdPartDesignMoveFeature::CmdPartDesignMoveFeature() - :Command("PartDesign_MoveFeature") + : Command("PartDesign_MoveFeature") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Move Object To…"); - sToolTipText = QT_TR_NOOP("Moves the selected object to another body"); - sWhatsThis = "PartDesign_MoveFeature"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_MoveFeature"; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Move Object To…"); + sToolTipText = QT_TR_NOOP("Moves the selected object to another body"); + sWhatsThis = "PartDesign_MoveFeature"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_MoveFeature"; } void CmdPartDesignMoveFeature::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector features = getSelection().getObjectsOfType(Part::Feature::getClassTypeId()); - if (features.empty()) + std::vector features = getSelection().getObjectsOfType( + Part::Feature::getClassTypeId() + ); + if (features.empty()) { return; + } // Check if all features are valid to move - if (std::any_of(std::begin(features), std::end(features), [](App::DocumentObject* obj){ - return !PartDesignGui::isFeatureMovable(obj); - })) - { - //show messagebox and cancel - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Features cannot be moved"), - QObject::tr("Some of the selected features have dependencies in the source body")); + if (std::any_of(std::begin(features), std::end(features), [](App::DocumentObject* obj) { + return !PartDesignGui::isFeatureMovable(obj); + })) { + // show messagebox and cancel + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Features cannot be moved"), + QObject::tr("Some of the selected features have dependencies in the source body") + ); return; } // Collect dependencies of the selected features - std::vector dependencies = PartDesignGui::collectMovableDependencies(features); - if (!dependencies.empty()) + std::vector dependencies = PartDesignGui::collectMovableDependencies( + features + ); + if (!dependencies.empty()) { features.insert(std::end(features), std::begin(dependencies), std::end(dependencies)); + } // Create a list of all bodies in this part - std::vector bodies = getDocument()->getObjectsOfType(Part::BodyBase::getClassTypeId()); + std::vector bodies = getDocument()->getObjectsOfType( + Part::BodyBase::getClassTypeId() + ); std::set source_bodies; for (auto feat : features) { @@ -718,9 +871,12 @@ void CmdPartDesignMoveFeature::activated(int iMsg) } if (source_bodies.size() != 1) { - //show messagebox and cancel - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Features cannot be moved"), - QObject::tr("Only features of a single source body can be moved")); + // show messagebox and cancel + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Features cannot be moved"), + QObject::tr("Only features of a single source body can be moved") + ); return; } @@ -728,14 +884,17 @@ void CmdPartDesignMoveFeature::activated(int iMsg) std::vector target_bodies; for (auto body : bodies) { - if (!source_bodies.count(body)) + if (!source_bodies.count(body)) { target_bodies.push_back(body); + } } - if (target_bodies.empty()) - { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Features cannot be moved"), - QObject::tr("There are no other bodies to move to")); + if (target_bodies.empty()) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Features cannot be moved"), + QObject::tr("There are no other bodies to move to") + ); return; } @@ -745,15 +904,23 @@ void CmdPartDesignMoveFeature::activated(int iMsg) for (auto body : target_bodies) { items.push_back(QString::fromUtf8(body->Label.getValue())); } - QString text = QInputDialog::getItem(Gui::getMainWindow(), + QString text = QInputDialog::getItem( + Gui::getMainWindow(), qApp->translate("PartDesign_MoveFeature", "Select Body"), qApp->translate("PartDesign_MoveFeature", "Select a body from the list"), - items, 0, false, &ok, Qt::MSWindowsFixedSizeDialogHint); - if (!ok) + items, + 0, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); + if (!ok) { return; + } int index = items.indexOf(text); - if (index < 0) + if (index < 0) { return; + } PartDesign::Body* target = static_cast(target_bodies[index]); @@ -763,13 +930,14 @@ void CmdPartDesignMoveFeature::activated(int iMsg) stream << "features_ = [" << getObjectCmd(features.back()); features.pop_back(); - for (auto feat: features) + for (auto feat : features) { stream << ", " << getObjectCmd(feat); + } stream << "]"; runCommand(Doc, stream.str().c_str()); - FCMD_OBJ_CMD(source_body,"removeObjects(features_)"); - FCMD_OBJ_CMD(target,"addObjects(features_)"); + FCMD_OBJ_CMD(source_body, "removeObjects(features_)"); + FCMD_OBJ_CMD(target, "addObjects(features_)"); /* // Find body of this feature @@ -799,17 +967,20 @@ void CmdPartDesignMoveFeature::activated(int iMsg) if ( featureWasTip ) { App::DocumentObject * sourceNewTip = source->Tip.getValue(); if (sourceNewTip) - doCommand(Gui,"Gui.activeDocument().show(\"%s\")", sourceNewTip->getNameInDocument()); + doCommand(Gui,"Gui.activeDocument().show(\"%s\")", + sourceNewTip->getNameInDocument()); } // Hide old tip and show new tip (the moved feature) of the target body App::DocumentObject* targetNewTip = target->Tip.getValue(); if ( targetOldTip != targetNewTip ) { if ( targetOldTip ) { - doCommand(Gui,"Gui.activeDocument().hide(\"%s\")", targetOldTip->getNameInDocument()); + doCommand(Gui,"Gui.activeDocument().hide(\"%s\")", + targetOldTip->getNameInDocument()); } if (targetNewTip) { - doCommand(Gui,"Gui.activeDocument().show(\"%s\")", targetNewTip->getNameInDocument()); + doCommand(Gui,"Gui.activeDocument().show(\"%s\")", + targetNewTip->getNameInDocument()); } } @@ -819,9 +990,9 @@ void CmdPartDesignMoveFeature::activated(int iMsg) try { PartDesignGui::fixSketchSupport(sketch); } catch (Base::Exception &) { - QMessageBox::warning( Gui::getMainWindow(), QObject::tr("Sketch plane cannot be migrated"), - QObject::tr("Please edit '%1' and redefine it to use a Base or Datum plane as the sketch plane."). - arg( QString::fromLatin1( sketch->Label.getValue () ) ) ); + QMessageBox::warning( Gui::getMainWindow(), QObject::tr("Sketch plane cannot be + migrated"), QObject::tr("Please edit '%1' and redefine it to use a Base or Datum plane as the + sketch plane."). arg( QString::fromLatin1( sketch->Label.getValue () ) ) ); } } @@ -840,62 +1011,72 @@ bool CmdPartDesignMoveFeature::isActive() DEF_STD_CMD_A(CmdPartDesignMoveFeatureInTree) CmdPartDesignMoveFeatureInTree::CmdPartDesignMoveFeatureInTree() - :Command("PartDesign_MoveFeatureInTree") + : Command("PartDesign_MoveFeatureInTree") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); sMenuText = QT_TR_NOOP("Move Feature After…"); - sToolTipText = QT_TR_NOOP("Moves the selected feature after another feature in the same body"); - sWhatsThis = "PartDesign_MoveFeatureInTree"; - sStatusTip = sToolTipText; - sPixmap = "PartDesign_MoveFeatureInTree"; + sToolTipText = QT_TR_NOOP("Moves the selected feature after another feature in the same body"); + sWhatsThis = "PartDesign_MoveFeatureInTree"; + sStatusTip = sToolTipText; + sPixmap = "PartDesign_MoveFeatureInTree"; } void CmdPartDesignMoveFeatureInTree::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector features = getSelection().getObjectsOfType(Part::Feature::getClassTypeId()); - if (features.empty()) + std::vector features = getSelection().getObjectsOfType( + Part::Feature::getClassTypeId() + ); + if (features.empty()) { return; + } - PartDesign::Body *body = PartDesignGui::getBodyFor ( features.front(), false ); - App::DocumentObject * bodyBase = nullptr; + PartDesign::Body* body = PartDesignGui::getBodyFor(features.front(), false); + App::DocumentObject* bodyBase = nullptr; // sanity check bool allFeaturesFromSameBody = true; - if ( body ) { + if (body) { bodyBase = body->BaseFeature.getValue(); - for ( auto feat: features ) { - if ( !body->hasObject ( feat ) ) { + for (auto feat : features) { + if (!body->hasObject(feat)) { allFeaturesFromSameBody = false; break; } - if ( bodyBase == feat) { - QMessageBox::warning (nullptr, QObject::tr( "Selection error" ), - QObject::tr( "Impossible to move the base feature of a body." ) ); + if (bodyBase == feat) { + QMessageBox::warning( + nullptr, + QObject::tr("Selection error"), + QObject::tr("Impossible to move the base feature of a body.") + ); return; } } } - if (!body || ! allFeaturesFromSameBody) { - QMessageBox::warning (nullptr, QObject::tr( "Selection error" ), - QObject::tr( "Select one or more features from the same body." ) ); + if (!body || !allFeaturesFromSameBody) { + QMessageBox::warning( + nullptr, + QObject::tr("Selection error"), + QObject::tr("Select one or more features from the same body.") + ); return; } // Create a list of all features in this body - const std::vector & model = body->Group.getValues(); + const std::vector& model = body->Group.getValues(); // Ask user to select the target feature bool ok; QStringList items; - if ( bodyBase ) { - items.push_back( QString::fromUtf8 ( bodyBase->Label.getValue () ) ); - } else { - items.push_back( QObject::tr( "Beginning of the body" ) ); + if (bodyBase) { + items.push_back(QString::fromUtf8(bodyBase->Label.getValue())); } - for ( auto feat: model ) { - items.push_back( QString::fromUtf8 ( feat->Label.getValue() ) ); + else { + items.push_back(QObject::tr("Beginning of the body")); + } + for (auto feat : model) { + items.push_back(QString::fromUtf8(feat->Label.getValue())); } QString text = QInputDialog::getItem( @@ -906,24 +1087,32 @@ void CmdPartDesignMoveFeatureInTree::activated(int iMsg) 0, false, &ok, - Qt::MSWindowsFixedSizeDialogHint); - if (!ok) + Qt::MSWindowsFixedSizeDialogHint + ); + if (!ok) { return; + } int index = items.indexOf(text); // first object is the beginning of the body - App::DocumentObject* target = index != 0 ? model[index-1] : nullptr; + App::DocumentObject* target = index != 0 ? model[index - 1] : nullptr; openCommand(QT_TRANSLATE_NOOP("Command", "Move a feature inside body")); App::DocumentObject* lastObject = target; - for ( auto feat: features ) { - if ( feat == target ) continue; + for (auto feat : features) { + if (feat == target) { + continue; + } // Remove and re-insert the feature to/from the Body, preserving their order. // TODO: if tip was moved the new position of tip is quite undetermined (2015-08-07, Fat-Zer) - // TODO: warn the user if we are moving an object to some place before the object's link (2015-08-07, Fat-Zer) - FCMD_OBJ_CMD(body,"removeObject(" << getObjectCmd(feat) << ")"); - FCMD_OBJ_CMD(body,"insertObject(" << getObjectCmd(feat) << ","<< getObjectCmd(lastObject) << ", True)"); + // TODO: warn the user if we are moving an object to some place before the object's link + // (2015-08-07, Fat-Zer) + FCMD_OBJ_CMD(body, "removeObject(" << getObjectCmd(feat) << ")"); + FCMD_OBJ_CMD( + body, + "insertObject(" << getObjectCmd(feat) << "," << getObjectCmd(lastObject) << ", True)" + ); lastObject = feat; } @@ -932,38 +1121,43 @@ void CmdPartDesignMoveFeatureInTree::activated(int iMsg) // We must make sure the resulting objects of PartDesign::Feature do not // depend on later objects std::vector bodyFeatures; - std::map orders; - for(auto obj : body->Group.getValues()) { - if(obj->isDerivedFrom()) { - orders.emplace(obj,bodyFeatures.size()); + std::map orders; + for (auto obj : body->Group.getValues()) { + if (obj->isDerivedFrom()) { + orders.emplace(obj, bodyFeatures.size()); bodyFeatures.push_back(obj); } } bool failed = false; std::ostringstream ss; - for(size_t i=0;igetOutList()) { - if(obj->isDerivedFrom()) + for (auto obj : feat->getOutList()) { + if (obj->isDerivedFrom()) { continue; - for(auto dep : App::Document::getDependencyList({obj})) { + } + for (auto dep : App::Document::getDependencyList({obj})) { auto it = orders.find(dep); - if(it != orders.end() && it->second > i) { - ss << feat->Label.getValue() << ", " << - obj->Label.getValue() << " -> " << - it->first->Label.getValue(); - if(!failed) + if (it != orders.end() && it->second > i) { + ss << feat->Label.getValue() << ", " << obj->Label.getValue() << " -> " + << it->first->Label.getValue(); + if (!failed) { failed = true; - else + } + else { ss << std::endl; + } } } } } - if(failed) { - QMessageBox::critical (nullptr, QObject::tr( "Dependency violation" ), - QObject::tr( "Early feature must not depend on later feature.\n\n") - + QString::fromUtf8(ss.str().c_str())); + if (failed) { + QMessageBox::critical( + nullptr, + QObject::tr("Dependency violation"), + QObject::tr("Early feature must not depend on later feature.\n\n") + + QString::fromUtf8(ss.str().c_str()) + ); abortCommand(); return; } @@ -971,18 +1165,24 @@ void CmdPartDesignMoveFeatureInTree::activated(int iMsg) // If the selected objects have been moved after the current tip then ask the // user if they want the last object to be the new tip. // Only do this for features that can hold a tip (not for e.g. datums) - if ( lastObject != target && body->Tip.getValue() == target - && lastObject->isDerivedFrom() ) { + if (lastObject != target && body->Tip.getValue() == target + && lastObject->isDerivedFrom()) { QMessageBox msgBox(Gui::getMainWindow()); msgBox.setIcon(QMessageBox::Question); msgBox.setWindowTitle(qApp->translate("PartDesign_MoveFeatureInTree", "Move Tip")); - msgBox.setText(qApp->translate("PartDesign_MoveFeatureInTree", "The moved feature appears after the currently set tip.")); - msgBox.setInformativeText(qApp->translate("PartDesign_MoveFeatureInTree", "Set tip to last feature?")); + msgBox.setText(qApp->translate( + "PartDesign_MoveFeatureInTree", + "The moved feature appears after the currently set tip." + )); + msgBox.setInformativeText( + qApp->translate("PartDesign_MoveFeatureInTree", "Set tip to last feature?") + ); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::No); int ret = msgBox.exec(); - if (ret == QMessageBox::Yes) + if (ret == QMessageBox::Yes) { FCMD_OBJ_CMD(body, "Tip = " << getObjectCmd(lastObject)); + } } updateActive(); @@ -1000,7 +1200,7 @@ bool CmdPartDesignMoveFeatureInTree::isActive() void CreatePartDesignBodyCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPartDesignBody()); rcCmdMgr.addCommand(new CmdPartDesignMigrate()); diff --git a/src/Mod/PartDesign/Gui/CommandPrimitive.cpp b/src/Mod/PartDesign/Gui/CommandPrimitive.cpp index ea3877003e..f9fd2d4801 100644 --- a/src/Mod/PartDesign/Gui/CommandPrimitive.cpp +++ b/src/Mod/PartDesign/Gui/CommandPrimitive.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -44,61 +43,73 @@ using namespace std; DEF_STD_CMD_ACL(CmdPrimtiveCompAdditive) -static const char * primitiveIntToName(int id) +static const char* primitiveIntToName(int id) { - switch(id) { - case 0: return "Box"; - case 1: return "Cylinder"; - case 2: return "Sphere"; - case 3: return "Cone"; - case 4: return "Ellipsoid"; - case 5: return "Torus"; - case 6: return "Prism"; - case 7: return "Wedge"; - default: return nullptr; + switch (id) { + case 0: + return "Box"; + case 1: + return "Cylinder"; + case 2: + return "Sphere"; + case 3: + return "Cone"; + case 4: + return "Ellipsoid"; + case 5: + return "Torus"; + case 6: + return "Prism"; + case 7: + return "Wedge"; + default: + return nullptr; }; } CmdPrimtiveCompAdditive::CmdPrimtiveCompAdditive() - : Command("PartDesign_CompPrimitiveAdditive") + : Command("PartDesign_CompPrimitiveAdditive") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Additive Primitive"); - sToolTipText = QT_TR_NOOP("Creates an additive primitive"); - sWhatsThis = "PartDesign_CompPrimitiveAdditive"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Additive Primitive"); + sToolTipText = QT_TR_NOOP("Creates an additive primitive"); + sWhatsThis = "PartDesign_CompPrimitiveAdditive"; + sStatusTip = sToolTipText; + eType = ForEdit; } void CmdPrimtiveCompAdditive::activated(int iMsg) { - App::Document *doc = getDocument(); + App::Document* doc = getDocument(); // We need either an active Body, or for there to be no Body objects // (in which case, just make one) to make a new additive shape. - PartDesign::Body *pcActiveBody = PartDesignGui::getBody( /* messageIfNot = */ false ); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(/* messageIfNot = */ false); - auto shouldMakeBody( false ); + auto shouldMakeBody(false); if (!pcActiveBody) { - if ( doc->getObjectsOfType(PartDesign::Body::getClassTypeId()).empty() ) { + if (doc->getObjectsOfType(PartDesign::Body::getClassTypeId()).empty()) { shouldMakeBody = true; - } else { + } + else { PartDesignGui::DlgActiveBody dia(Gui::getMainWindow(), doc); - if (dia.exec() == QDialog::DialogCode::Accepted) + if (dia.exec() == QDialog::DialogCode::Accepted) { pcActiveBody = dia.getActiveBody(); - if (!pcActiveBody) + } + if (!pcActiveBody) { return; + } } } Gui::ActionGroup* pcAction = qobject_cast(_pcAction); pcAction->setIcon(pcAction->actions().at(iMsg)->icon()); - auto shapeType( primitiveIntToName(iMsg) ); + auto shapeType(primitiveIntToName(iMsg)); - Gui::Command::openCommand( (std::string("Make additive ") + shapeType).c_str() ); + Gui::Command::openCommand((std::string("Make additive ") + shapeType).c_str()); if (shouldMakeBody) { pcActiveBody = PartDesignGui::makeBody(doc); } @@ -107,33 +118,39 @@ void CmdPrimtiveCompAdditive::activated(int iMsg) return; } - auto FeatName( getUniqueObjectName(shapeType, pcActiveBody) ); + auto FeatName(getUniqueObjectName(shapeType, pcActiveBody)); - FCMD_OBJ_DOC_CMD(pcActiveBody,"addObject('PartDesign::Additive"<( - pcActiveBody->getDocument()->getObject(FeatName.c_str())); + pcActiveBody->getDocument()->getObject(FeatName.c_str()) + ); - if(!prm) + if (!prm) { return; - FCMD_OBJ_CMD(pcActiveBody,"addObject("<BaseFeature.getValue(); FCMD_OBJ_HIDE(base); - if(!base) + if (!base) { base = pcActiveBody; + } copyVisual(prm, "ShapeAppearance", base); copyVisual(prm, "LineColor", base); copyVisual(prm, "PointColor", base); copyVisual(prm, "Transparency", base); copyVisual(prm, "DisplayMode", base); - PartDesignGui::setEdit(prm,pcActiveBody); + PartDesignGui::setEdit(prm, pcActiveBody); } -Gui::Action * CmdPrimtiveCompAdditive::createAction() +Gui::Action* CmdPrimtiveCompAdditive::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -186,42 +203,68 @@ void CmdPrimtiveCompAdditive::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); QAction* arc1 = a[0]; - arc1->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Box")); - arc1->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive box by its width, height, and length")); + arc1->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Box")); + arc1->setToolTip( + QApplication::translate( + "PartDesign_CompPrimitiveAdditive", + "Creates an additive box by its width, height, and length" + ) + ); arc1->setStatusTip(arc1->toolTip()); QAction* arc2 = a[1]; - arc2->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Cylinder")); - arc2->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive cylinder by its radius, height, and angle")); + arc2->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Cylinder")); + arc2->setToolTip( + QApplication::translate( + "PartDesign_CompPrimitiveAdditive", + "Creates an additive cylinder by its radius, height, and angle" + ) + ); arc2->setStatusTip(arc2->toolTip()); QAction* arc3 = a[2]; - arc3->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Sphere")); - arc3->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive sphere by its radius and various angles")); + arc3->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Sphere")); + arc3->setToolTip( + QApplication::translate( + "PartDesign_CompPrimitiveAdditive", + "Creates an additive sphere by its radius and various angles" + ) + ); arc3->setStatusTip(arc3->toolTip()); QAction* arc4 = a[3]; - arc4->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Cone")); - arc4->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive cone")); + arc4->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Cone")); + arc4->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveAdditive", "Creates an additive cone") + ); arc4->setStatusTip(arc4->toolTip()); QAction* arc5 = a[4]; - arc5->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Ellipsoid")); - arc5->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive ellipsoid")); + arc5->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Ellipsoid")); + arc5->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveAdditive", "Creates an additive ellipsoid") + ); arc5->setStatusTip(arc5->toolTip()); QAction* arc6 = a[5]; - arc6->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Torus")); - arc6->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive torus")); + arc6->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Torus")); + arc6->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveAdditive", "Creates an additive torus") + ); arc6->setStatusTip(arc6->toolTip()); QAction* arc7 = a[6]; - arc7->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Prism")); - arc7->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive prism")); + arc7->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Prism")); + arc7->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveAdditive", "Creates an additive prism") + ); arc7->setStatusTip(arc7->toolTip()); QAction* arc8 = a[7]; - arc8->setText(QApplication::translate("CmdPrimtiveCompAdditive","Additive Wedge")); - arc8->setToolTip(QApplication::translate("PartDesign_CompPrimitiveAdditive","Creates an additive wedge")); + arc8->setText(QApplication::translate("CmdPrimtiveCompAdditive", "Additive Wedge")); + arc8->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveAdditive", "Creates an additive wedge") + ); arc8->setStatusTip(arc8->toolTip()); } @@ -233,41 +276,48 @@ bool CmdPrimtiveCompAdditive::isActive() DEF_STD_CMD_ACL(CmdPrimtiveCompSubtractive) CmdPrimtiveCompSubtractive::CmdPrimtiveCompSubtractive() - : Command("PartDesign_CompPrimitiveSubtractive") + : Command("PartDesign_CompPrimitiveSubtractive") { - sAppModule = "PartDesign"; - sGroup = QT_TR_NOOP("PartDesign"); - sMenuText = QT_TR_NOOP("Subtractive Primitive"); - sToolTipText = QT_TR_NOOP("Creates a subtractive primitive"); - sWhatsThis = "PartDesign_CompPrimitiveSubtractive"; - sStatusTip = sToolTipText; - eType = ForEdit; + sAppModule = "PartDesign"; + sGroup = QT_TR_NOOP("PartDesign"); + sMenuText = QT_TR_NOOP("Subtractive Primitive"); + sToolTipText = QT_TR_NOOP("Creates a subtractive primitive"); + sWhatsThis = "PartDesign_CompPrimitiveSubtractive"; + sStatusTip = sToolTipText; + eType = ForEdit; } void CmdPrimtiveCompSubtractive::activated(int iMsg) { - PartDesign::Body *pcActiveBody = PartDesignGui::getBody(true); + PartDesign::Body* pcActiveBody = PartDesignGui::getBody(true); - if (!pcActiveBody) + if (!pcActiveBody) { return; + } Gui::ActionGroup* pcAction = qobject_cast(_pcAction); pcAction->setIcon(pcAction->actions().at(iMsg)->icon()); - //check if we already have a feature as subtractive ones work only if we have - //something to subtract from. - App::DocumentObject *prevSolid = pcActiveBody->Tip.getValue(); - if(!prevSolid) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No previous feature found"), - QObject::tr("It is not possible to create a subtractive feature without a base feature available")); - return; + // check if we already have a feature as subtractive ones work only if we have + // something to subtract from. + App::DocumentObject* prevSolid = pcActiveBody->Tip.getValue(); + if (!prevSolid) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No previous feature found"), + QObject::tr("It is not possible to create a subtractive feature without a base feature available") + ); + return; } - auto shapeType( primitiveIntToName(iMsg) ); - auto FeatName( getUniqueObjectName(shapeType, pcActiveBody) ); + auto shapeType(primitiveIntToName(iMsg)); + auto FeatName(getUniqueObjectName(shapeType, pcActiveBody)); - Gui::Command::openCommand( (std::string("Make subtractive ") + shapeType).c_str() ); - FCMD_OBJ_CMD(pcActiveBody,"newObject('PartDesign::Subtractive"<getDocument()->getObject(FeatName.c_str()); @@ -277,15 +327,15 @@ void CmdPrimtiveCompSubtractive::activated(int iMsg) copyVisual(Feat, "Transparency", prevSolid); copyVisual(Feat, "DisplayMode", prevSolid); - if ( isActiveObjectValid() ) { + if (isActiveObjectValid()) { // TODO (2015-08-05, Fat-Zer) FCMD_OBJ_HIDE(prevSolid); } - PartDesignGui::setEdit(Feat,pcActiveBody); + PartDesignGui::setEdit(Feat, pcActiveBody); } -Gui::Action * CmdPrimtiveCompSubtractive::createAction() +Gui::Action* CmdPrimtiveCompSubtractive::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -338,42 +388,68 @@ void CmdPrimtiveCompSubtractive::languageChange() { Command::languageChange(); - if (!_pcAction) + if (!_pcAction) { return; + } Gui::ActionGroup* pcAction = qobject_cast(_pcAction); QList a = pcAction->actions(); QAction* arc1 = a[0]; - arc1->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Box")); - arc1->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive box by its width, height and length")); + arc1->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Box")); + arc1->setToolTip( + QApplication::translate( + "PartDesign_CompPrimitiveSubtractive", + "Creates a subtractive box by its width, height and length" + ) + ); arc1->setStatusTip(arc1->toolTip()); QAction* arc2 = a[1]; - arc2->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Cylinder")); - arc2->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive cylinder by its radius, height and angle")); + arc2->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Cylinder")); + arc2->setToolTip( + QApplication::translate( + "PartDesign_CompPrimitiveSubtractive", + "Creates a subtractive cylinder by its radius, height and angle" + ) + ); arc2->setStatusTip(arc2->toolTip()); QAction* arc3 = a[2]; - arc3->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Sphere")); - arc3->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive sphere by its radius and various angles")); + arc3->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Sphere")); + arc3->setToolTip( + QApplication::translate( + "PartDesign_CompPrimitiveSubtractive", + "Creates a subtractive sphere by its radius and various angles" + ) + ); arc3->setStatusTip(arc3->toolTip()); QAction* arc4 = a[3]; - arc4->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Cone")); - arc4->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive cone")); + arc4->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Cone")); + arc4->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveSubtractive", "Creates a subtractive cone") + ); arc4->setStatusTip(arc4->toolTip()); QAction* arc5 = a[4]; - arc5->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Ellipsoid")); - arc5->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive ellipsoid")); + arc5->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Ellipsoid")); + arc5->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveSubtractive", "Creates a subtractive ellipsoid") + ); arc5->setStatusTip(arc5->toolTip()); QAction* arc6 = a[5]; - arc6->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Torus")); - arc6->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive torus")); + arc6->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Torus")); + arc6->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveSubtractive", "Creates a subtractive torus") + ); arc6->setStatusTip(arc6->toolTip()); QAction* arc7 = a[6]; - arc7->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Prism")); - arc7->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive prism")); + arc7->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Prism")); + arc7->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveSubtractive", "Creates a subtractive prism") + ); arc7->setStatusTip(arc7->toolTip()); QAction* arc8 = a[7]; - arc8->setText(QApplication::translate("CmdPrimtiveCompSubtractive","Subtractive Wedge")); - arc8->setToolTip(QApplication::translate("PartDesign_CompPrimitiveSubtractive","Creates a subtractive wedge")); + arc8->setText(QApplication::translate("CmdPrimtiveCompSubtractive", "Subtractive Wedge")); + arc8->setToolTip( + QApplication::translate("PartDesign_CompPrimitiveSubtractive", "Creates a subtractive wedge") + ); arc8->setStatusTip(arc8->toolTip()); } @@ -388,7 +464,7 @@ bool CmdPrimtiveCompSubtractive::isActive() void CreatePartDesignPrimitiveCommands() { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPrimtiveCompAdditive); rcCmdMgr.addCommand(new CmdPrimtiveCompSubtractive); diff --git a/src/Mod/PartDesign/Gui/DlgActiveBody.cpp b/src/Mod/PartDesign/Gui/DlgActiveBody.cpp index 028ecc580b..da6cc38674 100644 --- a/src/Mod/PartDesign/Gui/DlgActiveBody.cpp +++ b/src/Mod/PartDesign/Gui/DlgActiveBody.cpp @@ -1,4 +1,4 @@ - /************************************************************************** +/************************************************************************** * Copyright (c) 2021 FreeCAD Developers * * Author: Ajinkya Dahale * * Based on src/Gui/DlgAddProperty.cpp * @@ -23,7 +23,7 @@ ***************************************************************************/ -# include +#include #include @@ -38,7 +38,7 @@ Q_DECLARE_METATYPE(App::DocumentObject*) using namespace PartDesignGui; -DlgActiveBody::DlgActiveBody(QWidget *parent, App::Document*& doc, const QString& infoText) +DlgActiveBody::DlgActiveBody(QWidget* parent, App::Document*& doc, const QString& infoText) : QDialog(parent) , ui(new Ui_DlgActiveBody) , _doc(doc) @@ -46,8 +46,7 @@ DlgActiveBody::DlgActiveBody(QWidget *parent, App::Document*& doc, const QString { ui->setupUi(this); - connect(ui->bodySelect, &QListWidget::itemDoubleClicked, - this, &DlgActiveBody::accept); + connect(ui->bodySelect, &QListWidget::itemDoubleClicked, this, &DlgActiveBody::accept); if (!infoText.isEmpty()) { ui->label->setText(infoText + QStringLiteral("\n\n") + tr("Please select")); @@ -56,12 +55,12 @@ DlgActiveBody::DlgActiveBody(QWidget *parent, App::Document*& doc, const QString auto bodies = _doc->getObjectsOfType(PartDesign::Body::getClassTypeId()); PartDesign::Body* bodyOfActiveObject = nullptr; - for (const auto &obj : Gui::Selection().getSelection()) { + for (const auto& obj : Gui::Selection().getSelection()) { bodyOfActiveObject = PartDesign::Body::findBodyOf(obj.pObject); - break; // Just get the body for first selected object + break; // Just get the body for first selected object } - for (const auto &body : bodies) { + for (const auto& body : bodies) { auto item = new QListWidgetItem(QString::fromUtf8(body->Label.getValue())); item->setData(Qt::UserRole, QVariant::fromValue(body)); ui->bodySelect->addItem(item); @@ -77,8 +76,9 @@ DlgActiveBody::DlgActiveBody(QWidget *parent, App::Document*& doc, const QString // by default select the first item so that the user // can continue by clicking Ok without further action QListWidgetItem* first = ui->bodySelect->item(0); - if (first) + if (first) { first->setSelected(true); + } } } @@ -87,11 +87,12 @@ DlgActiveBody::~DlgActiveBody() = default; void DlgActiveBody::accept() { auto selectedItems = ui->bodySelect->selectedItems(); - if (selectedItems.empty()) + if (selectedItems.empty()) { return; + } - App::DocumentObject* selectedBody = - selectedItems[0]->data(Qt::UserRole).value(); + App::DocumentObject* selectedBody + = selectedItems[0]->data(Qt::UserRole).value(); if (selectedBody) { activeBody = makeBodyActive(selectedBody, _doc); } diff --git a/src/Mod/PartDesign/Gui/DlgActiveBody.h b/src/Mod/PartDesign/Gui/DlgActiveBody.h index 111aa29c3e..e5865ae072 100644 --- a/src/Mod/PartDesign/Gui/DlgActiveBody.h +++ b/src/Mod/PartDesign/Gui/DlgActiveBody.h @@ -1,4 +1,4 @@ - /************************************************************************** +/************************************************************************** * Copyright (c) 2021 FreeCAD Developers * * Author: Ajinkya Dahale * * Based on src/Gui/DlgAddProperty.h * @@ -33,23 +33,26 @@ #include -namespace PartDesignGui { +namespace PartDesignGui +{ class Ui_DlgActiveBody; /** Dialog box to ask user to pick a Part Design body to make active * or make a new one */ -class PartDesignGuiExport DlgActiveBody : public QDialog +class PartDesignGuiExport DlgActiveBody: public QDialog { Q_OBJECT public: - DlgActiveBody(QWidget* parent, App::Document*& doc, - const QString& infoText=QString()); + DlgActiveBody(QWidget* parent, App::Document*& doc, const QString& infoText = QString()); ~DlgActiveBody() override; void accept() override; - PartDesign::Body* getActiveBody() const { return activeBody; } + PartDesign::Body* getActiveBody() const + { + return activeBody; + } private: std::unique_ptr ui; @@ -57,6 +60,6 @@ private: PartDesign::Body* activeBody; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTDESIGNGUI_DLGACTIVEBODY_H +#endif // PARTDESIGNGUI_DLGACTIVEBODY_H diff --git a/src/Mod/PartDesign/Gui/EnumFlags.h b/src/Mod/PartDesign/Gui/EnumFlags.h index 1370b15316..46b444888f 100644 --- a/src/Mod/PartDesign/Gui/EnumFlags.h +++ b/src/Mod/PartDesign/Gui/EnumFlags.h @@ -24,26 +24,28 @@ #ifndef PARTDESIGNGUI_ENUMFLAGS_H #define PARTDESIGNGUI_ENUMFLAGS_H -namespace PartDesignGui { +namespace PartDesignGui +{ // https://wiggling-bits.net/using-enum-classes-as-type-safe-bitmasks/ // https://www.boost.org/doc/libs/1_66_0/boost/detail/bitmask.hpp // https://stackoverflow.com/questions/1448396/how-to-use-enums-as-flags-in-c -enum class AllowSelection { - NONE = 0, /**< This is used to indicate to stop the selection */ - EDGE = 1 << 0, /**< Allow picking edges */ - FACE = 1 << 1, /**< Allow picking faces */ - PLANAR = 1 << 2, /**< Allow only linear edges and planar faces */ - CIRCLE = 1 << 3, /**< Allow picking circular edges (incl arcs) */ - POINT = 1 << 4, /**< Allow picking datum points */ - OTHERBODY = 1 << 5, /**< Allow picking objects from another body in the same part */ - WHOLE = 1 << 6 /**< Allow whole object selection */ +enum class AllowSelection +{ + NONE = 0, /**< This is used to indicate to stop the selection */ + EDGE = 1 << 0, /**< Allow picking edges */ + FACE = 1 << 1, /**< Allow picking faces */ + PLANAR = 1 << 2, /**< Allow only linear edges and planar faces */ + CIRCLE = 1 << 3, /**< Allow picking circular edges (incl arcs) */ + POINT = 1 << 4, /**< Allow picking datum points */ + OTHERBODY = 1 << 5, /**< Allow picking objects from another body in the same part */ + WHOLE = 1 << 6 /**< Allow whole object selection */ }; Q_DECLARE_FLAGS(AllowSelectionFlags, AllowSelection) -} //namespace PartDesignGui +} // namespace PartDesignGui Q_DECLARE_OPERATORS_FOR_FLAGS(PartDesignGui::AllowSelectionFlags) -#endif // PARTDESIGNGUI_ENUMFLAGS_H +#endif // PARTDESIGNGUI_ENUMFLAGS_H diff --git a/src/Mod/PartDesign/Gui/PreCompiled.h b/src/Mod/PartDesign/Gui/PreCompiled.h index 12375929e0..f76d122b40 100644 --- a/src/Mod/PartDesign/Gui/PreCompiled.h +++ b/src/Mod/PartDesign/Gui/PreCompiled.h @@ -26,7 +26,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // Boost @@ -50,9 +50,9 @@ #include // Qt -# include +#include // Inventor -# include +#include -#endif // PART_DESIGN_PRECOMPILED_H +#endif // PART_DESIGN_PRECOMPILED_H diff --git a/src/Mod/PartDesign/Gui/ReferenceSelection.cpp b/src/Mod/PartDesign/Gui/ReferenceSelection.cpp index 011cf93dd7..ba2abaf0b7 100644 --- a/src/Mod/PartDesign/Gui/ReferenceSelection.cpp +++ b/src/Mod/PartDesign/Gui/ReferenceSelection.cpp @@ -21,12 +21,12 @@ ******************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -62,7 +62,7 @@ bool ReferenceSelection::allow(App::Document* pDoc, App::DocumentObject* pObj, c if (!pObj) { return false; } - PartDesign::Body *body = getBody(); + PartDesign::Body* body = getBody(); App::OriginGroupExtension* originGroup = getOriginGroupExtension(body); // Don't allow selection in other document @@ -79,7 +79,8 @@ bool ReferenceSelection::allow(App::Document* pDoc, App::DocumentObject* pObj, c return allowDatum(body, pObj); } - // The flag was used to be set. So, this block will never be treated and really doesn't make sense anyway + // The flag was used to be set. So, this block will never be treated and really doesn't make + // sense anyway #if 0 if (!type.testFlag(AllowSelection::OTHERBODY)) { if (support == NULL) @@ -111,33 +112,37 @@ bool ReferenceSelection::allow(App::Document* pDoc, App::DocumentObject* pObj, c PartDesign::Body* ReferenceSelection::getBody() const { - auto* body = support ? PartDesign::Body::findBodyOf(support) - : PartDesignGui::getBody(false); + auto* body = support ? PartDesign::Body::findBodyOf(support) : PartDesignGui::getBody(false); return body; } -App::OriginGroupExtension* ReferenceSelection::getOriginGroupExtension(PartDesign::Body *body) const +App::OriginGroupExtension* ReferenceSelection::getOriginGroupExtension(PartDesign::Body* body) const { App::DocumentObject* originGroupObject = nullptr; - if (body) { // Search for Part of the body + if (body) { // Search for Part of the body originGroupObject = App::OriginGroupExtension::getGroupOfObject(body); } - else if (support) { // if no body search part for support + else if (support) { // if no body search part for support originGroupObject = App::OriginGroupExtension::getGroupOfObject(support); } - else { // fallback to active part + else { // fallback to active part originGroupObject = PartDesignGui::getActivePart(); } App::OriginGroupExtension* originGroup = nullptr; - if (originGroupObject) + if (originGroupObject) { originGroup = originGroupObject->getExtensionByType(); + } return originGroup; } -bool ReferenceSelection::allowOrigin(PartDesign::Body *body, App::OriginGroupExtension* originGroup, App::DocumentObject* pObj) const +bool ReferenceSelection::allowOrigin( + PartDesign::Body* body, + App::OriginGroupExtension* originGroup, + App::DocumentObject* pObj +) const { bool fits = false; if (type.testFlag(AllowSelection::FACE) && pObj->isDerivedFrom()) { @@ -147,14 +152,14 @@ bool ReferenceSelection::allowOrigin(PartDesign::Body *body, App::OriginGroupExt fits = true; } - if (fits) { // check that it actually belongs to the chosen body or part - try { // here are some throwers + if (fits) { // check that it actually belongs to the chosen body or part + try { // here are some throwers if (body) { - if (body->hasObject(pObj, true) ) { + if (body->hasObject(pObj, true)) { return true; } } - else if (originGroup ) { + else if (originGroup) { if (originGroup->hasObject(pObj, true)) { return true; } @@ -163,24 +168,27 @@ bool ReferenceSelection::allowOrigin(PartDesign::Body *body, App::OriginGroupExt catch (const Base::Exception&) { } } - return false; // The Plane/Axis doesn't fits our needs + return false; // The Plane/Axis doesn't fits our needs } -bool ReferenceSelection::allowDatum(PartDesign::Body *body, App::DocumentObject* pObj) const +bool ReferenceSelection::allowDatum(PartDesign::Body* body, App::DocumentObject* pObj) const { - if (!body) { // Allow selecting Part::Datum features from the active Body + if (!body) { // Allow selecting Part::Datum features from the active Body return false; } else if (!type.testFlag(AllowSelection::OTHERBODY) && !body->hasObject(pObj)) { return false; } - if (type.testFlag(AllowSelection::FACE) && (pObj->isDerivedFrom())) + if (type.testFlag(AllowSelection::FACE) && (pObj->isDerivedFrom())) { return true; - if (type.testFlag(AllowSelection::EDGE) && (pObj->isDerivedFrom())) + } + if (type.testFlag(AllowSelection::EDGE) && (pObj->isDerivedFrom())) { return true; - if (type.testFlag(AllowSelection::POINT) && (pObj->isDerivedFrom())) + } + if (type.testFlag(AllowSelection::POINT) && (pObj->isDerivedFrom())) { return true; + } return false; } @@ -193,18 +201,21 @@ bool ReferenceSelection::allowPartFeature(App::DocumentObject* pObj, const char* } if (type.testFlag(AllowSelection::EDGE) && subName.compare(0, 4, "Edge") == 0) { - if (isEdge(pObj, sSubName)) + if (isEdge(pObj, sSubName)) { return true; + } } if (type.testFlag(AllowSelection::CIRCLE) && subName.compare(0, 4, "Edge") == 0) { - if (isCircle(pObj, sSubName)) + if (isCircle(pObj, sSubName)) { return true; + } } if (type.testFlag(AllowSelection::FACE) && subName.compare(0, 4, "Face") == 0) { - if (isFace(pObj, sSubName)) + if (isFace(pObj, sSubName)) { return true; + } } return false; @@ -212,14 +223,15 @@ bool ReferenceSelection::allowPartFeature(App::DocumentObject* pObj, const char* bool ReferenceSelection::isEdge(App::DocumentObject* pObj, const char* sSubName) const { - const Part::TopoShape &shape = static_cast(pObj)->Shape.getValue(); + const Part::TopoShape& shape = static_cast(pObj)->Shape.getValue(); TopoDS_Shape sh = shape.getSubShape(sSubName); const TopoDS_Edge& edgeShape = TopoDS::Edge(sh); if (!edgeShape.IsNull()) { if (type.testFlag(AllowSelection::PLANAR)) { BRepAdaptor_Curve adapt(edgeShape); - if (adapt.GetType() == GeomAbs_Line) + if (adapt.GetType() == GeomAbs_Line) { return true; + } } else { return true; @@ -231,14 +243,15 @@ bool ReferenceSelection::isEdge(App::DocumentObject* pObj, const char* sSubName) bool ReferenceSelection::isFace(App::DocumentObject* pObj, const char* sSubName) const { - const Part::TopoShape &shape = static_cast(pObj)->Shape.getValue(); + const Part::TopoShape& shape = static_cast(pObj)->Shape.getValue(); TopoDS_Shape sh = shape.getSubShape(sSubName); const TopoDS_Face& face = TopoDS::Face(sh); if (!face.IsNull()) { if (type.testFlag(AllowSelection::PLANAR)) { BRepAdaptor_Surface adapt(face); - if (adapt.GetType() == GeomAbs_Plane) + if (adapt.GetType() == GeomAbs_Plane) { return true; + } } else { return true; @@ -250,7 +263,7 @@ bool ReferenceSelection::isFace(App::DocumentObject* pObj, const char* sSubName) bool ReferenceSelection::isCircle(App::DocumentObject* pObj, const char* sSubName) const { - const Part::TopoShape &shape = static_cast(pObj)->Shape.getValue(); + const Part::TopoShape& shape = static_cast(pObj)->Shape.getValue(); TopoDS_Shape sh = shape.getSubShape(sSubName); const TopoDS_Edge& edgeShape = TopoDS::Edge(sh); BRepAdaptor_Curve adapt(edgeShape); @@ -283,25 +296,32 @@ bool CombineSelectionFilterGates::allow(App::Document* pDoc, App::DocumentObject namespace PartDesignGui { -bool getReferencedSelection(const App::DocumentObject* thisObj, const Gui::SelectionChanges& msg, - App::DocumentObject*& selObj, std::vector& selSub) +bool getReferencedSelection( + const App::DocumentObject* thisObj, + const Gui::SelectionChanges& msg, + App::DocumentObject*& selObj, + std::vector& selSub +) { selObj = nullptr; - if (!thisObj) + if (!thisObj) { return false; + } - if (strcmp(thisObj->getDocument()->getName(), msg.pDocName) != 0) + if (strcmp(thisObj->getDocument()->getName(), msg.pDocName) != 0) { return false; + } selObj = thisObj->getDocument()->getObject(msg.pObjectName); - if (selObj == thisObj) + if (selObj == thisObj) { return false; + } std::string subname = msg.pSubName; - //check if the selection is an external reference and ask the user what to do - //of course only if thisObj is in a body, as otherwise the old workflow would not - //be supported + // check if the selection is an external reference and ask the user what to do + // of course only if thisObj is in a body, as otherwise the old workflow would not + // be supported PartDesign::Body* body = PartDesignGui::getBodyFor(thisObj, false); bool originfeature = selObj->isDerivedFrom(); if (!originfeature && body) { @@ -320,7 +340,11 @@ bool getReferencedSelection(const App::DocumentObject* thisObj, const Gui::Selec if (!dlg.radioXRef->isChecked()) { App::Document* document = thisObj->getDocument(); document->openTransaction("Make copy"); - auto copy = PartDesignGui::TaskFeaturePick::makeCopy(selObj, subname, dlg.radioIndependent->isChecked()); + auto copy = PartDesignGui::TaskFeaturePick::makeCopy( + selObj, + subname, + dlg.radioIndependent->isChecked() + ); body->addObject(copy); selObj = copy; @@ -335,7 +359,7 @@ bool getReferencedSelection(const App::DocumentObject* thisObj, const Gui::Selec subname = ""; } - selSub = std::vector(1,subname); + selSub = std::vector(1, subname); return true; } @@ -350,8 +374,8 @@ QString getRefStr(const App::DocumentObject* obj, const std::vector return QString::fromLatin1(obj->getNameInDocument()); } else if (!sub.empty()) { - return QString::fromLatin1(obj->getNameInDocument()) + QStringLiteral(":") + - QString::fromLatin1(sub.front().c_str()); + return QString::fromLatin1(obj->getNameInDocument()) + QStringLiteral(":") + + QString::fromLatin1(sub.front().c_str()); } return {}; @@ -359,58 +383,68 @@ QString getRefStr(const App::DocumentObject* obj, const std::vector std::string buildLinkSubPythonStr(const App::DocumentObject* obj, const std::vector& subs) { - if (!obj) + if (!obj) { return "None"; + } std::string result("["); - for (const auto & sub : subs) + for (const auto& sub : subs) { result += "\"" + sub + "\","; + } result += "]"; return result; } -std::string buildLinkSingleSubPythonStr(const App::DocumentObject* obj, - const std::vector& subs) +std::string buildLinkSingleSubPythonStr( + const App::DocumentObject* obj, + const std::vector& subs +) { - if (!obj) + if (!obj) { return "None"; + } - if (PartDesign::Feature::isDatum(obj)) - return Gui::Command::getObjectCmd(obj,"(",", [''])"); - else - return Gui::Command::getObjectCmd(obj,"(",", ['") + subs.front() + "'])"; + if (PartDesign::Feature::isDatum(obj)) { + return Gui::Command::getObjectCmd(obj, "(", ", [''])"); + } + else { + return Gui::Command::getObjectCmd(obj, "(", ", ['") + subs.front() + "'])"; + } } -std::string buildLinkListPythonStr(const std::vector & objs) +std::string buildLinkListPythonStr(const std::vector& objs) { - if ( objs.empty() ) { + if (objs.empty()) { return "None"; } std::string result("["); - for (auto obj : objs) - result += Gui::Command::getObjectCmd(obj,nullptr,","); + for (auto obj : objs) { + result += Gui::Command::getObjectCmd(obj, nullptr, ","); + } result += "]"; return result; } -std::string buildLinkSubListPythonStr(const std::vector & objs, - const std::vector& subs) +std::string buildLinkSubListPythonStr( + const std::vector& objs, + const std::vector& subs +) { - if ( objs.empty() ) { + if (objs.empty()) { return "None"; } std::string result("["); - assert (objs.size () == subs.size () ); + assert(objs.size() == subs.size()); - for (size_t i=0, objs_sz=objs.size(); i < objs_sz; i++) { - if (objs[i] ) { + for (size_t i = 0, objs_sz = objs.size(); i < objs_sz; i++) { + if (objs[i]) { result += '('; result += Gui::Command::getObjectCmd(objs[i]); result += ",\""; @@ -423,4 +457,4 @@ std::string buildLinkSubListPythonStr(const std::vector & return result; } -} +} // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/ReferenceSelection.h b/src/Mod/PartDesign/Gui/ReferenceSelection.h index 6a27bc774d..893e53bd07 100644 --- a/src/Mod/PartDesign/Gui/ReferenceSelection.h +++ b/src/Mod/PartDesign/Gui/ReferenceSelection.h @@ -27,56 +27,61 @@ #include #include -namespace App { +namespace App +{ class OriginGroupExtension; } -namespace PartDesign { +namespace PartDesign +{ class Body; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class ReferenceSelection : public Gui::SelectionFilterGate +class ReferenceSelection: public Gui::SelectionFilterGate { const App::DocumentObject* support; AllowSelectionFlags type; public: - ReferenceSelection(const App::DocumentObject* support_, - AllowSelectionFlags type) + ReferenceSelection(const App::DocumentObject* support_, AllowSelectionFlags type) : Gui::SelectionFilterGate(nullPointer()) , support(support_) , type(type) - { - } + {} /** - * Allow the user to pick only edges or faces (or both) from the defined support - * Optionally restrict the selection to planar edges/faces - */ + * Allow the user to pick only edges or faces (or both) from the defined support + * Optionally restrict the selection to planar edges/faces + */ bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) override; private: PartDesign::Body* getBody() const; - App::OriginGroupExtension* getOriginGroupExtension(PartDesign::Body *body) const; - bool allowOrigin(PartDesign::Body *body, App::OriginGroupExtension* originGroup, App::DocumentObject* pObj) const; - bool allowDatum(PartDesign::Body *body, App::DocumentObject* pObj) const; + App::OriginGroupExtension* getOriginGroupExtension(PartDesign::Body* body) const; + bool allowOrigin( + PartDesign::Body* body, + App::OriginGroupExtension* originGroup, + App::DocumentObject* pObj + ) const; + bool allowDatum(PartDesign::Body* body, App::DocumentObject* pObj) const; bool allowPartFeature(App::DocumentObject* pObj, const char* sSubName) const; bool isEdge(App::DocumentObject* pObj, const char* sSubName) const; bool isFace(App::DocumentObject* pObj, const char* sSubName) const; bool isCircle(App::DocumentObject* pObj, const char* sSubName) const; }; -class NoDependentsSelection : public Gui::SelectionFilterGate +class NoDependentsSelection: public Gui::SelectionFilterGate { const App::DocumentObject* support; public: NoDependentsSelection(const App::DocumentObject* support_) - : Gui::SelectionFilterGate(nullPointer()), support(support_) - { - } + : Gui::SelectionFilterGate(nullPointer()) + , support(support_) + {} /** - * Allow the user to pick only objects which are not in objs getDependencyList - */ + * Allow the user to pick only objects which are not in objs getDependencyList + */ bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) override; }; @@ -86,27 +91,40 @@ class CombineSelectionFilterGates: public Gui::SelectionFilterGate std::unique_ptr filter2; public: - CombineSelectionFilterGates(std::unique_ptr &filter1_, std::unique_ptr &filter2_) - : Gui::SelectionFilterGate(nullPointer()), filter1(std::move(filter1_)), filter2(std::move(filter2_)) - { - } + CombineSelectionFilterGates( + std::unique_ptr& filter1_, + std::unique_ptr& filter2_ + ) + : Gui::SelectionFilterGate(nullPointer()) + , filter1(std::move(filter1_)) + , filter2(std::move(filter2_)) + {} bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) override; }; // Convenience methods /// Extract reference from Selection -bool getReferencedSelection(const App::DocumentObject* thisObj, const Gui::SelectionChanges& msg, - App::DocumentObject*& selObj, std::vector& selSub); +bool getReferencedSelection( + const App::DocumentObject* thisObj, + const Gui::SelectionChanges& msg, + App::DocumentObject*& selObj, + std::vector& selSub +); /// Return reference as string for UI elements (format : QString getRefStr(const App::DocumentObject* obj, const std::vector& sub); /// Return reference as string for python in the format ( ["sub1", "sub2", ...]) std::string buildLinkSubPythonStr(const App::DocumentObject* obj, const std::vector& subs); /// Return reference as string for python in the format ( ["sub"?]) -std::string buildLinkSingleSubPythonStr(const App::DocumentObject* obj, const std::vector& subs); +std::string buildLinkSingleSubPythonStr( + const App::DocumentObject* obj, + const std::vector& subs +); /// Return reference as string for python in the format [obj1, obj2, ...,] -std::string buildLinkListPythonStr(const std::vector & objs); +std::string buildLinkListPythonStr(const std::vector& objs); /// Returns sub reference list as a python string in the format [(obj1,"sub1"),(obj2,"sub2"),...] -std::string buildLinkSubListPythonStr(const std::vector & objs, - const std::vector& subs); -} //namespace PartDesignGui +std::string buildLinkSubListPythonStr( + const std::vector& objs, + const std::vector& subs +); +} // namespace PartDesignGui -#endif // GUI_ReferenceSelection_H +#endif // GUI_ReferenceSelection_H diff --git a/src/Mod/PartDesign/Gui/SketchWorkflow.cpp b/src/Mod/PartDesign/Gui/SketchWorkflow.cpp index 074ffea2f8..b79aa5ec52 100644 --- a/src/Mod/PartDesign/Gui/SketchWorkflow.cpp +++ b/src/Mod/PartDesign/Gui/SketchWorkflow.cpp @@ -1,32 +1,32 @@ /************************************************************************** -* Copyright (c) 2022 Werner Mayer * -* * -* 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) 2022 Werner Mayer * + * * + * 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 -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include #include "SketchWorkflow.h" @@ -59,30 +59,26 @@ using namespace PartDesignGui; -namespace { +namespace +{ struct RejectException { - }; struct WrongSelectionException { - }; struct WrongSupportException { - }; struct SupportNotPlanarException { - }; struct MissingPlanesException { - }; class SupportFaceValidator @@ -90,8 +86,7 @@ class SupportFaceValidator public: explicit SupportFaceValidator(Gui::SelectionObject faceSelection) : faceSelection(faceSelection) - { - } + {} void handleSelectedBody(PartDesign::Body* activeBody) { @@ -112,7 +107,7 @@ public: msg.pSubName = elements[0].c_str(); msg.pTypeName = tip->getTypeId().getName(); - faceSelection = Gui::SelectionObject{msg}; + faceSelection = Gui::SelectionObject {msg}; // automatically switch to 'Through' mode setThroughModeOfBody(activeBody); @@ -135,7 +130,7 @@ public: } // get the selected sub shape (a Face) - const Part::TopoShape &shape = partobject->Shape.getValue(); + const Part::TopoShape& shape = partobject->Shape.getValue(); Part::TopoShape subshape(shape.getSubShape(elements[0].c_str())); if (subshape.isNull()) { throw WrongSupportException(); @@ -160,8 +155,9 @@ private: void setThroughModeOfBody(PartDesign::Body* activeBody) { // automatically switch to 'Through' mode - PartDesignGui::ViewProviderBody* vpBody = dynamic_cast - (Gui::Application::Instance->getViewProvider(activeBody)); + PartDesignGui::ViewProviderBody* vpBody = dynamic_cast( + Gui::Application::Instance->getViewProvider(activeBody) + ); if (vpBody) { vpBody->DisplayModeBody.setValue("Through"); } @@ -176,8 +172,7 @@ class SupportPlaneValidator public: explicit SupportPlaneValidator(Gui::SelectionObject faceSelection) : faceSelection(faceSelection) - { - } + {} std::string getSupport() const { @@ -196,15 +191,17 @@ private: class SketchPreselection { public: - SketchPreselection(Gui::Document* guidocument, PartDesign::Body* activeBody, - std::tuple filter) + SketchPreselection( + Gui::Document* guidocument, + PartDesign::Body* activeBody, + std::tuple filter + ) : guidocument(guidocument) , activeBody(activeBody) , faceFilter(std::get<0>(filter)) , planeFilter(std::get<1>(filter)) , sketchFilter(std::get<2>(filter)) - { - } + {} bool matches() { @@ -221,11 +218,11 @@ public: createBodyOrThrow(); // get the selected object - App::DocumentObject* selectedObject{}; + App::DocumentObject* selectedObject {}; if (faceFilter.match()) { Gui::SelectionObject faceSelObject = faceFilter.Result[0][0]; - SupportFaceValidator validator{faceSelObject}; + SupportFaceValidator validator {faceSelObject}; validator.handleSelectedBody(activeBody); validator.throwIfInvalid(); @@ -258,14 +255,16 @@ public: auto Feat = activeBody->getDocument()->getObject(FeatName.c_str()); FCMD_OBJ_CMD(Feat, "AttachmentSupport = " << supportString); if (sketchFilter.match()) { - FCMD_OBJ_CMD(Feat, - "MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmObjectXY) - << "'"); + FCMD_OBJ_CMD( + Feat, + "MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmObjectXY) << "'" + ); } else { // For Face or Plane - FCMD_OBJ_CMD(Feat, - "MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) - << "'"); + FCMD_OBJ_CMD( + Feat, + "MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) << "'" + ); } Gui::Command::updateActive(); PartDesignGui::setEdit(Feat, activeBody); @@ -275,7 +274,7 @@ private: void createBodyOrThrow() { if (!activeBody) { - activeBody = PartDesignGui::getBody( /* messageIfNot = */ true ); + activeBody = PartDesignGui::getBody(/* messageIfNot = */ true); if (activeBody) { tryAddNewBodyToActivePart(); } @@ -287,7 +286,7 @@ private: void tryAddNewBodyToActivePart() { - App::Part *activePart = PartDesignGui::getActivePart(); + App::Part* activePart = PartDesignGui::getActivePart(); if (activePart) { activePart->addObject(activeBody); } @@ -296,12 +295,12 @@ private: void handleIfSupportOutOfBody(App::DocumentObject* selectedObject) { if (!activeBody->hasObject(selectedObject)) { - if ( !selectedObject->isDerivedFrom ( App::Plane::getClassTypeId() ) ) { + if (!selectedObject->isDerivedFrom(App::Plane::getClassTypeId())) { // TODO check here if the plane associated with right part/body (2015-09-01, Fat-Zer) - //check the prerequisites for the selected objects - //the user has to decide which option we should take if external references are used - // TODO share this with UnifiedDatumCommand() (2015-10-20, Fat-Zer) + // check the prerequisites for the selected objects + // the user has to decide which option we should take if external references are used + // TODO share this with UnifiedDatumCommand() (2015-10-20, Fat-Zer) QDialog dia(Gui::getMainWindow()); PartDesignGui::Ui_DlgReference dlg; dlg.setupUi(&dia); @@ -324,8 +323,9 @@ private: App::DocumentObject* makeCopy(App::DocumentObject* selectedObject, bool independent) { std::string sub; - if (faceFilter.match()) + if (faceFilter.match()) { sub = faceFilter.Result[0][0].getSubNames()[0]; + } auto copy = PartDesignGui::TaskFeaturePick::makeCopy(selectedObject, sub, independent); addToBodyOrPart(copy); @@ -337,11 +337,12 @@ private: { std::string supportString; if (planeFilter.match()) { - supportString = Gui::Command::getObjectCmd(copy,"(",",'')"); + supportString = Gui::Command::getObjectCmd(copy, "(", ",'')"); } else { - //it is ensured that only a single face is selected, hence it must always be Face1 of the shapebinder - supportString = Gui::Command::getObjectCmd(copy,"(",",'Face1')"); + // it is ensured that only a single face is selected, hence it must always be Face1 of + // the shapebinder + supportString = Gui::Command::getObjectCmd(copy, "(", ",'Face1')"); } return supportString; } @@ -372,9 +373,7 @@ public: PlaneFinder(App::Document* appdocument, PartDesign::Body* activeBody) : appdocument(appdocument) , activeBody(activeBody) - { - - } + {} std::vector getPlanes() const { @@ -396,46 +395,52 @@ public: try { tryFindBasePlanes(); } - catch (const Base::Exception &ex) { - Base::Console().error ("%s\n", ex.what() ); + catch (const Base::Exception& ex) { + Base::Console().error("%s\n", ex.what()); } } void findDatumPlanes() { - App::GeoFeatureGroupExtension *geoGroup = getGroupExtensionOfBody(); - const std::vector types = { PartDesign::Plane::getClassTypeId(), App::Plane::getClassTypeId() }; + App::GeoFeatureGroupExtension* geoGroup = getGroupExtensionOfBody(); + const std::vector types + = {PartDesign::Plane::getClassTypeId(), App::Plane::getClassTypeId()}; auto datumPlanes = appdocument->getObjectsOfType(types); for (auto plane : datumPlanes) { if (std::find(planes.begin(), planes.end(), plane) != planes.end()) { - continue; // Skip if already in planes (for base planes) + continue; // Skip if already in planes (for base planes) } - planes.push_back ( plane ); + planes.push_back(plane); // Check whether this plane belongs to the active body - if ( activeBody->hasObject(plane, true) ) { - if ( !activeBody->isAfterInsertPoint ( plane ) ) { + if (activeBody->hasObject(plane, true)) { + if (!activeBody->isAfterInsertPoint(plane)) { validPlaneCount++; status.push_back(PartDesignGui::TaskFeaturePick::validFeature); - } else { + } + else { status.push_back(PartDesignGui::TaskFeaturePick::afterTip); } - } else { - PartDesign::Body *planeBody = PartDesign::Body::findBodyOf (plane); - if ( planeBody ) { - if ( ( geoGroup && geoGroup->hasObject ( planeBody, true ) ) || - !App::GeoFeatureGroupExtension::getGroupOfObject (planeBody) ) { - status.push_back ( PartDesignGui::TaskFeaturePick::otherBody ); - } else { - status.push_back ( PartDesignGui::TaskFeaturePick::otherPart ); + } + else { + PartDesign::Body* planeBody = PartDesign::Body::findBodyOf(plane); + if (planeBody) { + if ((geoGroup && geoGroup->hasObject(planeBody, true)) + || !App::GeoFeatureGroupExtension::getGroupOfObject(planeBody)) { + status.push_back(PartDesignGui::TaskFeaturePick::otherBody); } - } else { - if ( ( geoGroup && geoGroup->hasObject ( plane, true ) ) || - !App::GeoFeatureGroupExtension::getGroupOfObject ( plane ) ) { - status.push_back ( PartDesignGui::TaskFeaturePick::otherPart ); - } else { - status.push_back ( PartDesignGui::TaskFeaturePick::notInBody ); + else { + status.push_back(PartDesignGui::TaskFeaturePick::otherPart); + } + } + else { + if ((geoGroup && geoGroup->hasObject(plane, true)) + || !App::GeoFeatureGroupExtension::getGroupOfObject(plane)) { + status.push_back(PartDesignGui::TaskFeaturePick::otherPart); + } + else { + status.push_back(PartDesignGui::TaskFeaturePick::notInBody); } } } @@ -446,15 +451,15 @@ public: { // Collect also shape binders consisting of a single planar face - auto shapeBinders( appdocument->getObjectsOfType(PartDesign::ShapeBinder::getClassTypeId()) ); - auto binders( appdocument->getObjectsOfType(PartDesign::SubShapeBinder::getClassTypeId()) ); - shapeBinders.insert(shapeBinders.end(),binders.begin(),binders.end()); + auto shapeBinders(appdocument->getObjectsOfType(PartDesign::ShapeBinder::getClassTypeId())); + auto binders(appdocument->getObjectsOfType(PartDesign::SubShapeBinder::getClassTypeId())); + shapeBinders.insert(shapeBinders.end(), binders.begin(), binders.end()); for (auto binder : shapeBinders) { // Check whether this plane belongs to the active body if (activeBody->hasObject(binder)) { Part::TopoShape shape = static_cast(binder)->Shape.getShape(); if (shape.isPlanar()) { - if (!activeBody->isAfterInsertPoint (binder)) { + if (!activeBody->isAfterInsertPoint(binder)) { validPlaneCount++; planes.push_back(binder); status.push_back(PartDesignGui::TaskFeaturePick::validFeature); @@ -469,7 +474,7 @@ private: { auto* origin = activeBody->getOrigin(); for (auto plane : origin->planes()) { - planes.push_back (plane); + planes.push_back(plane); status.push_back(PartDesignGui::TaskFeaturePick::basePlane); validPlaneCount++; } @@ -477,9 +482,9 @@ private: App::GeoFeatureGroupExtension* getGroupExtensionOfBody() const { - App::GeoFeatureGroupExtension *geoGroup{nullptr}; + App::GeoFeatureGroupExtension* geoGroup {nullptr}; if (activeBody) { - auto group( App::GeoFeatureGroupExtension::getGroupOfObject(activeBody) ); + auto group(App::GeoFeatureGroupExtension::getGroupOfObject(activeBody)); if (group) { geoGroup = group->getExtensionByType(); } @@ -502,8 +507,7 @@ public: SketchRequestSelection(Gui::Document* guidocument, PartDesign::Body* activeBody) : guidocument(guidocument) , activeBody(activeBody) - { - } + {} void findSupport() { @@ -528,8 +532,10 @@ private: createBodyOrThrow(); bool useAttachment = App::GetApplication() - .GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/PartDesign") - ->GetBool("NewSketchUseAttachmentDialog", false); + .GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/PartDesign" + ) + ->GetBool("NewSketchUseAttachmentDialog", false); if (useAttachment) { createSketchAndShowAttachment(); } @@ -554,7 +560,7 @@ private: void tryAddNewBodyToActivePart() { - App::Part *activePart = PartDesignGui::getActivePart(); + App::Part* activePart = PartDesignGui::getActivePart(); if (activePart) { activePart->addObject(activeBody); } @@ -564,7 +570,8 @@ private: { auto* origin = activeBody->getOrigin(); auto* vpo = dynamic_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); if (vpo) { vpo->setTemporaryVisibility(Gui::DatumElement::Planes | Gui::DatumElement::Axes); vpo->setPlaneLabelVisibility(true); @@ -596,7 +603,9 @@ private: Gui::Selection().clearSelection(); // Open attachment dialog - auto* vps = dynamic_cast(Gui::Application::Instance->getViewProvider(sketch)); + auto* vps = dynamic_cast( + Gui::Application::Instance->getViewProvider(sketch) + ); vps->showAttachmentEditor(onAccept, onReject); } @@ -604,7 +613,8 @@ private: { auto* origin = partDesignBody->getOrigin(); auto* vpo = dynamic_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); if (vpo) { vpo->resetTemporaryVisibility(); vpo->resetTemporarySize(); @@ -626,7 +636,8 @@ private: unsigned validPlaneCount = planeFinder.countValidPlanes(); for (auto& plane : planes) { - auto* planeViewProvider = Gui::Application::Instance->getViewProvider(plane); + auto* planeViewProvider + = Gui::Application::Instance->getViewProvider(plane); // skip updating planes from coordinate systems if (!planeViewProvider || !planeViewProvider->getRole().empty()) { @@ -634,7 +645,9 @@ private: } planeViewProvider->setLabelVisibility(true); - planeViewProvider->setTemporaryScale(Gui::ViewParams::instance()->getDatumTemporaryScaleFactor()); + planeViewProvider->setTemporaryScale( + Gui::ViewParams::instance()->getDatumTemporaryScaleFactor() + ); } // @@ -645,7 +658,8 @@ private: auto restorePlaneVisibility = [planes]() { for (auto& plane : planes) { - auto* planeViewProvider = Gui::Application::Instance->getViewProvider(plane); + auto* planeViewProvider + = Gui::Application::Instance->getViewProvider(plane); if (!planeViewProvider) { continue; } @@ -656,13 +670,15 @@ private: }; // Determines if user made a valid selection in dialog - auto acceptFunction = [restorePlaneVisibility](const std::vector& features) -> bool { + auto acceptFunction = + [restorePlaneVisibility](const std::vector& features) -> bool { restorePlaneVisibility(); return !features.empty(); }; // Called by dialog when user hits "OK" and accepter returns true - auto processFunction = [documentOfBody, partDesignBody](const std::vector& features) { + auto processFunction = [documentOfBody, + partDesignBody](const std::vector& features) { SketchRequestSelection::createSketch(documentOfBody, partDesignBody, features); }; @@ -671,8 +687,9 @@ private: auto rejectFunction = [docname, restorePlaneVisibility]() { restorePlaneVisibility(); Gui::Document* document = Gui::Application::Instance->getDocument(docname.c_str()); - if (document) + if (document) { document->abortCommand(); + } }; // @@ -690,15 +707,22 @@ private: Gui::Selection().clearSelection(); // Show dialog and let user pick plane - Gui::Control().showDialog(new PartDesignGui::TaskDlgFeaturePick(planes, status, acceptFunction, - processFunction, true, rejectFunction)); + Gui::Control().showDialog(new PartDesignGui::TaskDlgFeaturePick( + planes, + status, + acceptFunction, + processFunction, + true, + rejectFunction + )); } } void checkForShownDialog() { - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - PartDesignGui::TaskDlgFeaturePick *pickDlg = qobject_cast(dlg); + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); + PartDesignGui::TaskDlgFeaturePick* pickDlg + = qobject_cast(dlg); if (dlg && !pickDlg) { QMessageBox msgBox(Gui::getMainWindow()); msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -719,8 +743,11 @@ private: } } - static void createSketch(App::Document* documentOfBody, PartDesign::Body* partDesignBody, - const std::vector& features) + static void createSketch( + App::Document* documentOfBody, + PartDesign::Body* partDesignBody, + const std::vector& features + ) { // may happen when the user switched to an empty document while the // dialog is open @@ -733,7 +760,8 @@ private: std::string supportString; if (lcs) { - supportString = Gui::Command::getObjectCmd(lcs, "(") + ",['" + plane->getNameInDocument() + "'])"; + supportString = Gui::Command::getObjectCmd(lcs, "(") + ",['" + + plane->getNameInDocument() + "'])"; } else { supportString = Gui::Command::getObjectCmd(plane, "(", ",[''])"); @@ -744,11 +772,14 @@ private: doc->openTransaction(QT_TRANSLATE_NOOP("Command", "New Sketch")); } - FCMD_OBJ_CMD(partDesignBody,"newObject('Sketcher::SketchObject','" << FeatName << "')"); + FCMD_OBJ_CMD(partDesignBody, "newObject('Sketcher::SketchObject','" << FeatName << "')"); auto Feat = doc->getObject(FeatName.c_str()); - FCMD_OBJ_CMD(Feat,"AttachmentSupport = " << supportString); - FCMD_OBJ_CMD(Feat,"MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace)<<"'"); - Gui::Command::updateActive(); // Make sure the AttachmentSupport's Placement property is updated + FCMD_OBJ_CMD(Feat, "AttachmentSupport = " << supportString); + FCMD_OBJ_CMD( + Feat, + "MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) << "'" + ); + Gui::Command::updateActive(); // Make sure the AttachmentSupport's Placement property is updated PartDesignGui::setEdit(Feat, partDesignBody); } @@ -757,7 +788,7 @@ private: PartDesign::Body* activeBody; }; -} +} // namespace SketchWorkflow::SketchWorkflow(Gui::Document* document) : guidocument(document) @@ -771,23 +802,34 @@ void SketchWorkflow::createSketch() tryCreateSketch(); } catch (const RejectException&) { - } catch (const WrongSelectionException&) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Several sub-elements selected"), - QObject::tr("Select a single face as support for a sketch!")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Several sub-elements selected"), + QObject::tr("Select a single face as support for a sketch!") + ); } catch (const WrongSupportException&) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No support face selected"), - QObject::tr("Select a face as support for a sketch!")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No support face selected"), + QObject::tr("Select a face as support for a sketch!") + ); } catch (const SupportNotPlanarException&) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No planar support"), - QObject::tr("Need a planar face as support for a sketch!")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No planar support"), + QObject::tr("Need a planar face as support for a sketch!") + ); } catch (const MissingPlanesException&) { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No valid planes in this document"), - QObject::tr("Create a plane first or select a face to sketch on")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No valid planes in this document"), + QObject::tr("Create a plane first or select a face to sketch on") + ); } } @@ -809,22 +851,23 @@ void SketchWorkflow::tryCreateSketch() sketchOnFace.createSketchOnSupport(sketchOnFace.getSupport()); } else { - SketchRequestSelection requestSelection{ guidocument, activeBody }; + SketchRequestSelection requestSelection {guidocument, activeBody}; requestSelection.findSupport(); } } std::tuple SketchWorkflow::shouldCreateBody() { - auto shouldMakeBody{false}; + auto shouldMakeBody {false}; // We need either an active Body, or for there to be no Body // objects (in which case, just make one) to make a new sketch. // If we are inside a link, we need to use its placement. - App::DocumentObject *topParent; - PartDesign::Body *pdBody = PartDesignGui::getBody(/* messageIfNot = */ false, true, true, &topParent); + App::DocumentObject* topParent; + PartDesign::Body* pdBody + = PartDesignGui::getBody(/* messageIfNot = */ false, true, true, &topParent); if (pdBody && topParent->isLink()) { - auto *xLink = dynamic_cast(topParent); + auto* xLink = dynamic_cast(topParent); pdBody->Placement.setValue(xLink->Placement.getValue()); } if (!pdBody) { @@ -855,8 +898,8 @@ std::tuple Ske // a new sketch. // See https://forum.freecad.org/viewtopic.php?f=3&t=44070 - Gui::SelectionFilter FaceFilter ("SELECT Part::Feature SUBELEMENT Face COUNT 1"); - Gui::SelectionFilter PlaneFilter ("SELECT App::Plane COUNT 1", activeBody); + Gui::SelectionFilter FaceFilter("SELECT Part::Feature SUBELEMENT Face COUNT 1"); + Gui::SelectionFilter PlaneFilter("SELECT App::Plane COUNT 1", activeBody); Gui::SelectionFilter PlaneFilter2("SELECT PartDesign::Plane COUNT 1", activeBody); Gui::SelectionFilter SketchFilter("SELECT Part::Part2DObject COUNT 1", activeBody); diff --git a/src/Mod/PartDesign/Gui/SketchWorkflow.h b/src/Mod/PartDesign/Gui/SketchWorkflow.h index a57f9fc85d..b0f2f9913e 100644 --- a/src/Mod/PartDesign/Gui/SketchWorkflow.h +++ b/src/Mod/PartDesign/Gui/SketchWorkflow.h @@ -1,24 +1,24 @@ /************************************************************************** -* Copyright (c) 2022 Werner Mayer * -* * -* 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) 2022 Werner Mayer * + * * + * 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 PARTDESIGNGUI_SKETCHWORKFLOW_H #define PARTDESIGNGUI_SKETCHWORKFLOW_H @@ -27,18 +27,22 @@ #include #include -namespace App { +namespace App +{ class Document; class DocumentObject; class GeoFeatureGroupExtension; -} -namespace Gui { +} // namespace App +namespace Gui +{ class Document; } -namespace PartDesign { +namespace PartDesign +{ class Body; } -namespace PartDesignGui { +namespace PartDesignGui +{ class SketchWorkflow { @@ -55,9 +59,9 @@ private: private: Gui::Document* guidocument; App::Document* appdocument; - PartDesign::Body* activeBody{nullptr}; + PartDesign::Body* activeBody {nullptr}; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTDESIGNGUI_SKETCHWORKFLOW_H +#endif // PARTDESIGNGUI_SKETCHWORKFLOW_H diff --git a/src/Mod/PartDesign/Gui/StyleParameters.h b/src/Mod/PartDesign/Gui/StyleParameters.h index 34661146d1..9da7d399e2 100644 --- a/src/Mod/PartDesign/Gui/StyleParameters.h +++ b/src/Mod/PartDesign/Gui/StyleParameters.h @@ -26,22 +26,23 @@ #include -namespace PartDesignGui::StyleParameters { - DEFINE_STYLE_PARAMETER(PreviewAdditiveColor, Base::Color(0.0F, 1.0F, 0.6F)); - DEFINE_STYLE_PARAMETER(PreviewSubtractiveColor, Base::Color(1.0F, 0.0F, 0.0F)); - DEFINE_STYLE_PARAMETER(PreviewCommonColor, Base::Color(1.0F, 1.0F, 0.0F)); - DEFINE_STYLE_PARAMETER(PreviewDressUpColor, Base::Color(1.0F, 0.0F, 1.0F)); +namespace PartDesignGui::StyleParameters +{ +DEFINE_STYLE_PARAMETER(PreviewAdditiveColor, Base::Color(0.0F, 1.0F, 0.6F)); +DEFINE_STYLE_PARAMETER(PreviewSubtractiveColor, Base::Color(1.0F, 0.0F, 0.0F)); +DEFINE_STYLE_PARAMETER(PreviewCommonColor, Base::Color(1.0F, 1.0F, 0.0F)); +DEFINE_STYLE_PARAMETER(PreviewDressUpColor, Base::Color(1.0F, 0.0F, 1.0F)); - DEFINE_STYLE_PARAMETER(PreviewProfileLineWidth, Gui::StyleParameters::Numeric(4)); - DEFINE_STYLE_PARAMETER(PreviewProfileOpacity, Gui::StyleParameters::Numeric(0.0)); +DEFINE_STYLE_PARAMETER(PreviewProfileLineWidth, Gui::StyleParameters::Numeric(4)); +DEFINE_STYLE_PARAMETER(PreviewProfileOpacity, Gui::StyleParameters::Numeric(0.0)); - DEFINE_STYLE_PARAMETER(PreviewErrorColor, Base::Color(1.0F, 0.0F, 0.0F)); - DEFINE_STYLE_PARAMETER(PreviewErrorOpacity, Gui::StyleParameters::Numeric(0.05)); +DEFINE_STYLE_PARAMETER(PreviewErrorColor, Base::Color(1.0F, 0.0F, 0.0F)); +DEFINE_STYLE_PARAMETER(PreviewErrorOpacity, Gui::StyleParameters::Numeric(0.05)); - DEFINE_STYLE_PARAMETER(PreviewToolOpacity, Gui::StyleParameters::Numeric(0.05)); - DEFINE_STYLE_PARAMETER(PreviewShapeOpacity, Gui::StyleParameters::Numeric(0.2)); +DEFINE_STYLE_PARAMETER(PreviewToolOpacity, Gui::StyleParameters::Numeric(0.05)); +DEFINE_STYLE_PARAMETER(PreviewShapeOpacity, Gui::StyleParameters::Numeric(0.2)); - DEFINE_STYLE_PARAMETER(PreviewLineWidth, Gui::StyleParameters::Numeric(2)); -} +DEFINE_STYLE_PARAMETER(PreviewLineWidth, Gui::StyleParameters::Numeric(2)); +} // namespace PartDesignGui::StyleParameters -#endif //STYLEPARAMETERS_H +#endif // STYLEPARAMETERS_H diff --git a/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp b/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp index 937cfd02b5..99cea8b25c 100644 --- a/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp @@ -22,7 +22,6 @@ ***************************************************************************/ - #include #include @@ -48,10 +47,7 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskBooleanParameters */ TaskBooleanParameters::TaskBooleanParameters(ViewProviderBoolean* BooleanView, QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap("PartDesign_Boolean"), - tr("Boolean Parameters"), - true, - parent) + : TaskBox(Gui::BitmapFactory().pixmap("PartDesign_Boolean"), tr("Boolean Parameters"), true, parent) , ui(new Ui_TaskBooleanParameters) , BooleanView(BooleanView) { @@ -108,8 +104,7 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) } // get the selected object - PartDesign::Boolean* pcBoolean = - BooleanView->getObject(); + PartDesign::Boolean* pcBoolean = BooleanView->getObject(); std::string body(msg.pObjectName); if (body.empty()) { return; @@ -147,15 +142,15 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) // Hide the bodies if (bodies.size() == 1) { // Hide base body and added body - Gui::ViewProviderDocumentObject* vp = - dynamic_cast( - Gui::Application::Instance->getViewProvider( - pcBoolean->BaseFeature.getValue())); + Gui::ViewProviderDocumentObject* vp = dynamic_cast( + Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue()) + ); if (vp) { vp->hide(); } vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(bodies.front())); + Gui::Application::Instance->getViewProvider(bodies.front()) + ); if (vp) { vp->hide(); } @@ -163,9 +158,10 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) } else { // Hide newly added body - Gui::ViewProviderDocumentObject* vp = - dynamic_cast( - Gui::Application::Instance->getViewProvider(bodies.back())); + Gui::ViewProviderDocumentObject* vp + = dynamic_cast( + Gui::Application::Instance->getViewProvider(bodies.back()) + ); if (vp) { vp->hide(); } @@ -193,17 +189,16 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) exitSelectionMode(); // Make bodies visible again - Gui::ViewProviderDocumentObject* vp = - dynamic_cast( - Gui::Application::Instance->getViewProvider(pcBody)); + Gui::ViewProviderDocumentObject* vp = dynamic_cast( + Gui::Application::Instance->getViewProvider(pcBody) + ); if (vp) { vp->show(); } if (bodies.empty()) { - Gui::ViewProviderDocumentObject* vp = - dynamic_cast( - Gui::Application::Instance->getViewProvider( - pcBoolean->BaseFeature.getValue())); + Gui::ViewProviderDocumentObject* vp = dynamic_cast( + Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue()) + ); if (vp) { vp->show(); } @@ -217,8 +212,7 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) void TaskBooleanParameters::onButtonBodyAdd(bool checked) { if (checked) { - PartDesign::Boolean* pcBoolean = - BooleanView->getObject(); + PartDesign::Boolean* pcBoolean = BooleanView->getObject(); Gui::Document* doc = BooleanView->getDocument(); BooleanView->hide(); if (pcBoolean->Group.getValues().empty() && pcBoolean->BaseFeature.getValue()) { @@ -272,8 +266,7 @@ const std::vector TaskBooleanParameters::getBodies() const { std::vector result; for (int i = 0; i < ui->listWidgetBodies->count(); i++) { - result.push_back( - ui->listWidgetBodies->item(i)->data(Qt::UserRole).toString().toStdString()); + result.push_back(ui->listWidgetBodies->item(i)->data(Qt::UserRole).toString().toStdString()); } return result; } @@ -308,13 +301,15 @@ void TaskBooleanParameters::onBodyDeleted() // Make bodies visible again Gui::ViewProviderDocumentObject* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(body)); + Gui::Application::Instance->getViewProvider(body) + ); if (vp) { vp->show(); } if (bodies.empty()) { Gui::ViewProviderDocumentObject* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue())); + Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue()) + ); if (vp) { vp->show(); } @@ -382,9 +377,7 @@ bool TaskDlgBooleanParameters::accept() try { std::vector bodies = parameter->getBodies(); if (bodies.empty()) { - QMessageBox::warning(parameter, - tr("Empty body list"), - tr("The body list cannot be empty")); + QMessageBox::warning(parameter, tr("Empty body list"), tr("The body list cannot be empty")); return false; } std::stringstream str; @@ -397,9 +390,11 @@ bool TaskDlgBooleanParameters::accept() Gui::Command::runCommand(Gui::Command::Doc, str.str().c_str()); } catch (const Base::Exception& e) { - QMessageBox::warning(parameter, - tr("Boolean: Accept: Input error"), - QCoreApplication::translate("Exception", e.what())); + QMessageBox::warning( + parameter, + tr("Boolean: Accept: Input error"), + QCoreApplication::translate("Exception", e.what()) + ); return false; } diff --git a/src/Mod/PartDesign/Gui/TaskBooleanParameters.h b/src/Mod/PartDesign/Gui/TaskBooleanParameters.h index 526837447a..e52274e736 100644 --- a/src/Mod/PartDesign/Gui/TaskBooleanParameters.h +++ b/src/Mod/PartDesign/Gui/TaskBooleanParameters.h @@ -35,23 +35,26 @@ class Ui_TaskBooleanParameters; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskBooleanParameters : public Gui::TaskView::TaskBox, public Gui::SelectionObserver +class TaskBooleanParameters: public Gui::TaskView::TaskBox, public Gui::SelectionObserver { Q_OBJECT public: - explicit TaskBooleanParameters(ViewProviderBoolean *BooleanView, QWidget *parent=nullptr); + explicit TaskBooleanParameters(ViewProviderBoolean* BooleanView, QWidget* parent = nullptr); ~TaskBooleanParameters() override; const std::vector getBodies() const; @@ -67,30 +70,36 @@ protected: void exitSelectionMode(); protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: QWidget* proxy; std::unique_ptr ui; - ViewProviderBoolean *BooleanView; + ViewProviderBoolean* BooleanView; - enum selectionModes { none, bodyAdd, bodyRemove }; + enum selectionModes + { + none, + bodyAdd, + bodyRemove + }; selectionModes selectionMode; - }; /// simulation dialog for the TaskView -class TaskDlgBooleanParameters : public TaskDlgFeatureParameters +class TaskDlgBooleanParameters: public TaskDlgFeatureParameters { Q_OBJECT public: - explicit TaskDlgBooleanParameters(ViewProviderBoolean *BooleanView); + explicit TaskDlgBooleanParameters(ViewProviderBoolean* BooleanView); ~TaskDlgBooleanParameters() override; ViewProviderBoolean* getBooleanView() const - { return BooleanView; } + { + return BooleanView; + } public: @@ -104,18 +113,22 @@ public: bool reject() override; /// is called by the framework if the user presses the help button bool isAllowedAlterDocument() const override - { return false; } + { + return false; + } /// returns for Close and Help button QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } protected: - ViewProviderBoolean *BooleanView; + ViewProviderBoolean* BooleanView; - TaskBooleanParameters *parameter; + TaskBooleanParameters* parameter; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp b/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp index 4bce984c71..fe6da1cc15 100644 --- a/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp @@ -171,7 +171,8 @@ void TaskChamferParameters::onSelectionChanged(const Gui::SelectionChanges& msg) if (selectionMode == refSel) { referenceSelected(msg, ui->listWidgetReferences); } - } else if (msg.Type == Gui::SelectionChanges::ClrSelection) { + } + else if (msg.Type == Gui::SelectionChanges::ClrSelection) { // TODO: the gizmo position should be only recalculated when the feature associated // with the gizmo is removed from the list setGizmoPositions(); @@ -354,7 +355,7 @@ void TaskChamferParameters::setupGizmos(ViewProviderDressUp* vp) secondDistanceGizmo = new Gui::LinearGizmo(ui->chamferSize); angleGizmo = new Gui::RotationGizmo(ui->chamferAngle); - connect(ui->chamferType, qOverload(&QComboBox::currentIndexChanged), [this] (int index) { + connect(ui->chamferType, qOverload(&QComboBox::currentIndexChanged), [this](int index) { auto type = static_cast(index); switch (type) { @@ -375,13 +376,10 @@ void TaskChamferParameters::setupGizmos(ViewProviderDressUp* vp) case Part::ChamferType::distanceAngle: secondDistanceGizmo->setVisibility(false); angleGizmo->setVisibility(true); - } }); - gizmoContainer = GizmoContainer::create({ - distanceGizmo, secondDistanceGizmo, angleGizmo - }, vp); + gizmoContainer = GizmoContainer::create({distanceGizmo, secondDistanceGizmo, angleGizmo}, vp); setGizmoPositions(); @@ -422,7 +420,9 @@ void TaskChamferParameters::setGizmoPositions() secondDistanceGizmo->Gizmo::setDraggerPlacement(props2.position, props2.dir); angleGizmo->placeBelowLinearGizmo(distanceGizmo); - angleGizmo->getDraggerContainer()->setArcNormalDirection(Base::convertTo(-props.dir.Cross(props2.dir))); + angleGizmo->getDraggerContainer()->setArcNormalDirection( + Base::convertTo(-props.dir.Cross(props2.dir)) + ); // Only show the gizmo if the chamfer type is set to distance and angle angleGizmo->setVisibility(getType() == 2); } diff --git a/src/Mod/PartDesign/Gui/TaskChamferParameters.h b/src/Mod/PartDesign/Gui/TaskChamferParameters.h index c3d1878f3a..fa9c4dda84 100644 --- a/src/Mod/PartDesign/Gui/TaskChamferParameters.h +++ b/src/Mod/PartDesign/Gui/TaskChamferParameters.h @@ -30,24 +30,27 @@ #include "ViewProviderChamfer.h" class Ui_TaskChamferParameters; -namespace PartDesign { +namespace PartDesign +{ class Chamfer; } -namespace Gui { +namespace Gui +{ class LinearGizmo; class RotationalGizmo; class GizmoContainer; -} +} // namespace Gui -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskChamferParameters : public TaskDressUpParameters +class TaskChamferParameters: public TaskDressUpParameters { Q_OBJECT public: - explicit TaskChamferParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + explicit TaskChamferParameters(ViewProviderDressUp* DressUpView, QWidget* parent = nullptr); ~TaskChamferParameters() override; void apply() override; @@ -64,7 +67,7 @@ private Q_SLOTS: protected: void setButtons(const selectionModes mode) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void onSelectionChanged(const Gui::SelectionChanges& msg) override; int getType() const; @@ -87,12 +90,12 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgChamferParameters : public TaskDlgDressUpParameters +class TaskDlgChamferParameters: public TaskDlgDressUpParameters { Q_OBJECT public: - explicit TaskDlgChamferParameters(ViewProviderChamfer *DressUpView); + explicit TaskDlgChamferParameters(ViewProviderChamfer* DressUpView); ~TaskDlgChamferParameters() override; public: @@ -100,6 +103,6 @@ public: bool accept() override; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskChamferParameters_H +#endif // GUI_TASKVIEW_TaskChamferParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp b/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp index 5499041fbd..6da01638df 100644 --- a/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp @@ -22,9 +22,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -49,9 +48,13 @@ using namespace Attacher; /* TRANSLATOR PartDesignGui::TaskDatumParameters */ -TaskDatumParameters::TaskDatumParameters(ViewProviderDatum *ViewProvider,QWidget *parent) - : PartGui::TaskAttacher(ViewProvider, parent, QStringLiteral("PartDesign_") + ViewProvider->datumType, - ViewProvider->datumMenuText) +TaskDatumParameters::TaskDatumParameters(ViewProviderDatum* ViewProvider, QWidget* parent) + : PartGui::TaskAttacher( + ViewProvider, + parent, + QStringLiteral("PartDesign_") + ViewProvider->datumType, + ViewProvider->datumMenuText + ) { Gui::Selection().addSelectionGate(new NoDependentsSelection(ViewProvider->getObject())); ViewProvider->setPickable(false); @@ -59,8 +62,9 @@ TaskDatumParameters::TaskDatumParameters(ViewProviderDatum *ViewProvider,QWidget TaskDatumParameters::~TaskDatumParameters() { - if(this->ViewProvider && this->ViewProvider->isDerivedFrom()) + if (this->ViewProvider && this->ViewProvider->isDerivedFrom()) { static_cast(this->ViewProvider)->setPickable(true); + } Gui::Selection().rmvSelectionGate(); } @@ -70,72 +74,85 @@ TaskDatumParameters::~TaskDatumParameters() // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgDatumParameters::TaskDlgDatumParameters(ViewProviderDatum *ViewProvider) +TaskDlgDatumParameters::TaskDlgDatumParameters(ViewProviderDatum* ViewProvider) : TaskDlgAttacher(ViewProvider, false) { assert(ViewProvider); - parameter = new TaskDatumParameters(ViewProvider); + parameter = new TaskDatumParameters(ViewProvider); Content.push_back(parameter); } TaskDlgDatumParameters::~TaskDlgDatumParameters() = default; -bool TaskDlgDatumParameters::reject() { +bool TaskDlgDatumParameters::reject() +{ return PartGui::TaskDlgAttacher::reject(); } -bool TaskDlgDatumParameters::accept() { +bool TaskDlgDatumParameters::accept() +{ Part::Datum* pcDatum = ViewProvider->getObject(); auto pcActiveBody = PartDesignGui::getBodyFor(pcDatum, false); auto pcActivePart = PartDesignGui::getPartFor(pcActiveBody, false); std::vector copies; - //see if we are able to assign a mode + // see if we are able to assign a mode if (parameter->getActiveMapMode() == mmDeactivated) { QMessageBox msg(Gui::getMainWindow()); msg.setWindowTitle(tr("Incompatible Reference Set")); - msg.setText(tr("There is no attachment mode that fits the current set" - " of references. If you choose to continue, the feature will remain where" - " it is now, and will not be moved as the references change." - " Continue?")); + msg.setText( + tr("There is no attachment mode that fits the current set" + " of references. If you choose to continue, the feature will remain where" + " it is now, and will not be moved as the references change." + " Continue?") + ); msg.addButton(QMessageBox::Yes); - auto btNo = msg.addButton(QMessageBox::No); + auto btNo = msg.addButton(QMessageBox::No); msg.setDefaultButton(btNo); msg.setIcon(QMessageBox::Warning); msg.exec(); - if (msg.buttonRole(msg.clickedButton()) == QMessageBox::NoRole) + if (msg.buttonRole(msg.clickedButton()) == QMessageBox::NoRole) { return false; + } } - //see what to do with external references - //check the prerequisites for the selected objects - //the user has to decide which option we should take if external references are used + // see what to do with external references + // check the prerequisites for the selected objects + // the user has to decide which option we should take if external references are used bool extReference = false; for (App::DocumentObject* obj : pcDatum->AttachmentSupport.getValues()) { - if (pcActiveBody && !pcActiveBody->hasObject(obj) && !pcActiveBody->getOrigin()->hasObject(obj)) + if (pcActiveBody && !pcActiveBody->hasObject(obj) + && !pcActiveBody->getOrigin()->hasObject(obj)) { extReference = true; + } } - if(extReference) { + if (extReference) { // TODO: rewrite this to be shared with CmdPartDesignNewSketch::activated() (2015-10-20, Fat-Zer) QDialog dia(Gui::getMainWindow()); PartDesignGui::Ui_DlgReference dlg; dlg.setupUi(&dia); dia.setModal(true); int result = dia.exec(); - if (result == QDialog::DialogCode::Rejected) + if (result == QDialog::DialogCode::Rejected) { return false; + } else if (!dlg.radioXRef->isChecked()) { std::vector copyObjects; std::vector copySubValues; std::vector subs = pcDatum->AttachmentSupport.getSubValues(); int index = 0; for (App::DocumentObject* obj : pcDatum->AttachmentSupport.getValues()) { - if (pcActiveBody && !pcActiveBody->hasObject(obj) && !pcActiveBody->getOrigin()->hasObject(obj)) { - auto* copy = PartDesignGui::TaskFeaturePick::makeCopy(obj, subs[index], dlg.radioIndependent->isChecked()); + if (pcActiveBody && !pcActiveBody->hasObject(obj) + && !pcActiveBody->getOrigin()->hasObject(obj)) { + auto* copy = PartDesignGui::TaskFeaturePick::makeCopy( + obj, + subs[index], + dlg.radioIndependent->isChecked() + ); if (copy) { copyObjects.push_back(copy); copies.push_back(copyObjects.back()); @@ -154,15 +171,19 @@ bool TaskDlgDatumParameters::accept() { } } - if (!PartGui::TaskDlgAttacher::accept()) + if (!PartGui::TaskDlgAttacher::accept()) { return false; + } - //we need to add the copied features to the body after the command action, as otherwise FreeCAD crashes unexplainably - for(auto obj : copies) { - if (pcActiveBody) + // we need to add the copied features to the body after the command action, as otherwise FreeCAD + // crashes unexplainably + for (auto obj : copies) { + if (pcActiveBody) { pcActiveBody->addObject(obj); - else if (pcActivePart) + } + else if (pcActivePart) { pcActivePart->addObject(obj); + } } return true; diff --git a/src/Mod/PartDesign/Gui/TaskDatumParameters.h b/src/Mod/PartDesign/Gui/TaskDatumParameters.h index 3cf9510896..9cecf6c494 100644 --- a/src/Mod/PartDesign/Gui/TaskDatumParameters.h +++ b/src/Mod/PartDesign/Gui/TaskDatumParameters.h @@ -33,40 +33,42 @@ class Ui_TaskDatumParameters; class QLineEdit; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; } -namespace PartDesignGui { +namespace PartDesignGui +{ - -class TaskDatumParameters : public PartGui::TaskAttacher +class TaskDatumParameters: public PartGui::TaskAttacher { Q_OBJECT public: - explicit TaskDatumParameters(ViewProviderDatum *DatumView,QWidget *parent = nullptr); + explicit TaskDatumParameters(ViewProviderDatum* DatumView, QWidget* parent = nullptr); ~TaskDatumParameters() override; }; /// simulation dialog for the TaskView -class TaskDlgDatumParameters : public PartGui::TaskDlgAttacher +class TaskDlgDatumParameters: public PartGui::TaskDlgAttacher { Q_OBJECT public: - explicit TaskDlgDatumParameters(ViewProviderDatum *DatumView); + explicit TaskDlgDatumParameters(ViewProviderDatum* DatumView); ~TaskDlgDatumParameters() override; bool accept() override; bool reject() override; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp b/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp index 74c396cd0c..d29338ecce 100644 --- a/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDraftParameters.cpp @@ -22,7 +22,6 @@ ***************************************************************************/ - #include #include #include @@ -185,7 +184,8 @@ void TaskDraftParameters::onButtonPlane(bool checked) Gui::Selection().clearSelection(); Gui::Selection().addSelectionGate(new ReferenceSelection( this->getBase(), - AllowSelection::EDGE | AllowSelection::FACE | AllowSelection::PLANAR)); + AllowSelection::EDGE | AllowSelection::FACE | AllowSelection::PLANAR + )); } } @@ -197,7 +197,8 @@ void TaskDraftParameters::onButtonLine(bool checked) selectionMode = line; Gui::Selection().clearSelection(); Gui::Selection().addSelectionGate( - new ReferenceSelection(this->getBase(), AllowSelection::EDGE | AllowSelection::PLANAR)); + new ReferenceSelection(this->getBase(), AllowSelection::EDGE | AllowSelection::PLANAR) + ); } } diff --git a/src/Mod/PartDesign/Gui/TaskDraftParameters.h b/src/Mod/PartDesign/Gui/TaskDraftParameters.h index b827493c44..9b31b8d872 100644 --- a/src/Mod/PartDesign/Gui/TaskDraftParameters.h +++ b/src/Mod/PartDesign/Gui/TaskDraftParameters.h @@ -30,14 +30,15 @@ class Ui_TaskDraftParameters; -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskDraftParameters : public TaskDressUpParameters +class TaskDraftParameters: public TaskDressUpParameters { Q_OBJECT public: - explicit TaskDraftParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + explicit TaskDraftParameters(ViewProviderDressUp* DressUpView, QWidget* parent = nullptr); ~TaskDraftParameters() override; void apply() override; @@ -57,7 +58,7 @@ private Q_SLOTS: protected: void setButtons(const selectionModes mode) override; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: @@ -65,12 +66,12 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgDraftParameters : public TaskDlgDressUpParameters +class TaskDlgDraftParameters: public TaskDlgDressUpParameters { Q_OBJECT public: - explicit TaskDlgDraftParameters(ViewProviderDraft *DraftView); + explicit TaskDlgDraftParameters(ViewProviderDraft* DraftView); ~TaskDlgDraftParameters() override; public: @@ -78,6 +79,6 @@ public: bool accept() override; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp b/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp index 533114735d..13b7887e39 100644 --- a/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp @@ -22,12 +22,11 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -44,7 +43,7 @@ #include "TaskDressUpParameters.h" -FC_LOG_LEVEL_INIT("PartDesign",true,true) +FC_LOG_LEVEL_INIT("PartDesign", true, true) using namespace PartDesignGui; using namespace Gui; @@ -52,7 +51,12 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskDressUpParameters */ -TaskDressUpParameters::TaskDressUpParameters(ViewProviderDressUp *DressUpView, bool selectEdges, bool selectFaces, QWidget *parent) +TaskDressUpParameters::TaskDressUpParameters( + ViewProviderDressUp* DressUpView, + bool selectEdges, + bool selectFaces, + QWidget* parent +) : TaskFeatureParameters(DressUpView, parent, DressUpView->featureIcon(), DressUpView->menuName) , proxy(nullptr) , deleteAction(nullptr) @@ -75,13 +79,15 @@ TaskDressUpParameters::~TaskDressUpParameters() void TaskDressUpParameters::setupTransaction() { - if (DressUpView.expired()) + if (DressUpView.expired()) { return; + } int tid = 0; App::GetApplication().getActiveTransaction(&tid); - if (tid && tid == transactionID) + if (tid && tid == transactionID) { return; + } // open a transaction if none is active std::string n("Edit "); @@ -91,8 +97,9 @@ void TaskDressUpParameters::setupTransaction() void TaskDressUpParameters::referenceSelected(const Gui::SelectionChanges& msg, QListWidget* widget) { - if (strcmp(msg.pDocName, DressUpView->getObject()->getDocument()->getName()) != 0) + if (strcmp(msg.pDocName, DressUpView->getObject()->getDocument()->getName()) != 0) { return; + } Gui::Selection().clearSelection(); @@ -133,14 +140,16 @@ void TaskDressUpParameters::addAllEdges(QListWidget* widget) if (!base) { return; } - int count = Part::Feature::getTopoShape(base, Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform).countSubShapes(TopAbs_EDGE); + int count = Part::Feature::getTopoShape( + base, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ) + .countSubShapes(TopAbs_EDGE); auto subValues = pcDressUp->Base.getSubValues(false); std::size_t len = subValues.size(); for (int i = 0; i < count; ++i) { - std::string name = "Edge" + std::to_string(i+1); - if (std::find(subValues.begin(), subValues.begin() + len, name) - == subValues.begin() + len) { + std::string name = "Edge" + std::to_string(i + 1); + if (std::find(subValues.begin(), subValues.begin() + len, name) == subValues.begin() + len) { subValues.push_back(name); } } @@ -180,18 +189,24 @@ void TaskDressUpParameters::deleteRef(QListWidget* widget) updateFeature(pcDressUp, refs); } -void TaskDressUpParameters::updateFeature(PartDesign::DressUp* pcDressUp, const std::vector& refs) +void TaskDressUpParameters::updateFeature( + PartDesign::DressUp* pcDressUp, + const std::vector& refs +) { - if (selectionMode == refSel) + if (selectionMode == refSel) { DressUpView->highlightReferences(false); + } setupTransaction(); pcDressUp->Base.setValue(pcDressUp->Base.getValue(), refs); pcDressUp->recomputeFeature(); - if (selectionMode == refSel) + if (selectionMode == refSel) { DressUpView->highlightReferences(true); - else + } + else { hideOnError(); + } } void TaskDressUpParameters::onButtonRefSel(bool checked) @@ -199,7 +214,8 @@ void TaskDressUpParameters::onButtonRefSel(bool checked) setSelectionMode(checked ? refSel : none); } -void TaskDressUpParameters::doubleClicked(QListWidgetItem* item) { +void TaskDressUpParameters::doubleClicked(QListWidgetItem* item) +{ // executed when the user double-clicks on any item in the list // shows the fillets as they are -> useful to switch out of selection mode @@ -210,21 +226,30 @@ void TaskDressUpParameters::doubleClicked(QListWidgetItem* item) { setSelectionMode(none); // enable next possible single-click event after double-click time passed - QTimer::singleShot(QApplication::doubleClickInterval(), this, &TaskDressUpParameters::itemClickedTimeout); + QTimer::singleShot( + QApplication::doubleClickInterval(), + this, + &TaskDressUpParameters::itemClickedTimeout + ); } -void TaskDressUpParameters::setSelection(QListWidgetItem* current) { +void TaskDressUpParameters::setSelection(QListWidgetItem* current) +{ // executed when the user selected an item in the list (but double-clicked it) // highlights the currently selected item - if (current == nullptr){ + if (current == nullptr) { setSelectionMode(none); return; } if (!wasDoubleClicked) { // we treat it as single-click event once the QApplication double-click time is passed - QTimer::singleShot(QApplication::doubleClickInterval(), this, &TaskDressUpParameters::itemClickedTimeout); + QTimer::singleShot( + QApplication::doubleClickInterval(), + this, + &TaskDressUpParameters::itemClickedTimeout + ); // name of the item std::string subName = current->text().toStdString(); @@ -236,10 +261,12 @@ void TaskDressUpParameters::setSelection(QListWidgetItem* current) { std::string objName = body->getNameInDocument(); // Enter selection mode - if (selectionMode == none) + if (selectionMode == none) { setSelectionMode(refSel); - else + } + else { Gui::Selection().clearSelection(); + } // highlight the selected item bool block = this->blockSelection(true); @@ -249,9 +276,11 @@ void TaskDressUpParameters::setSelection(QListWidgetItem* current) { } } -void TaskDressUpParameters::tryAddSelection(const std::string& doc, - const std::string& obj, - const std::string& sub) +void TaskDressUpParameters::tryAddSelection( + const std::string& doc, + const std::string& obj, + const std::string& sub +) { try { Gui::Selection().addSelection(doc.c_str(), obj.c_str(), sub.c_str(), 0, 0, 0); @@ -274,7 +303,8 @@ QString TaskDressUpParameters::stopSelectionLabel() return tr("Confirm Selection"); } -void TaskDressUpParameters::itemClickedTimeout() { +void TaskDressUpParameters::itemClickedTimeout() +{ // executed after double-click time passed wasDoubleClicked = false; } @@ -288,7 +318,9 @@ void TaskDressUpParameters::createAddAllEdgesAction(QListWidget* parentList) // display shortcut behind the context menu entry addAllEdgesAction->setShortcutVisibleInContextMenu(true); parentList->addAction(addAllEdgesAction); - addAllEdgesAction->setStatusTip(tr("Adds all edges to the list box (only when in add selection mode)")); + addAllEdgesAction->setStatusTip( + tr("Adds all edges to the list box (only when in add selection mode)") + ); parentList->setContextMenuPolicy(Qt::ActionsContextMenu); } @@ -308,7 +340,7 @@ void TaskDressUpParameters::createDeleteAction(QListWidget* parentList) bool TaskDressUpParameters::event(QEvent* event) { if (event->type() == QEvent::ShortcutOverride) { - QKeyEvent * kevent = static_cast(event); // NOLINT + QKeyEvent* kevent = static_cast(event); // NOLINT if (deleteAction && Gui::QtTools::matches(kevent, deleteAction->shortcut())) { kevent->accept(); return true; @@ -324,13 +356,13 @@ bool TaskDressUpParameters::event(QEvent* event) void TaskDressUpParameters::keyPressEvent(QKeyEvent* ke) { - if (deleteAction && deleteAction->isEnabled() && - Gui::QtTools::matches(ke, deleteAction->shortcut())) { + if (deleteAction && deleteAction->isEnabled() + && Gui::QtTools::matches(ke, deleteAction->shortcut())) { deleteAction->trigger(); return; } - if (addAllEdgesAction && addAllEdgesAction->isEnabled() && - Gui::QtTools::matches(ke, addAllEdgesAction->shortcut())) { + if (addAllEdgesAction && addAllEdgesAction->isEnabled() + && Gui::QtTools::matches(ke, addAllEdgesAction->shortcut())) { addAllEdgesAction->trigger(); return; } @@ -425,7 +457,7 @@ void TaskDressUpParameters::setSelectionMode(selectionModes mode) // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgDressUpParameters::TaskDlgDressUpParameters(ViewProviderDressUp *DressUpView) +TaskDlgDressUpParameters::TaskDlgDressUpParameters(ViewProviderDressUp* DressUpView) : TaskDlgFeatureParameters(DressUpView) , parameter(nullptr) { @@ -435,17 +467,18 @@ TaskDlgDressUpParameters::TaskDlgDressUpParameters(ViewProviderDressUp *DressUpV std::vector newSubList; bool changed = false; auto& shadowSubs = pcDressUp->Base.getShadowSubs(); - for ( auto &shadowSub : shadowSubs ) { + for (auto& shadowSub : shadowSubs) { auto displayName = shadowSub.oldName; // If there is a missing tag on the shadow sub, take a guess at a new name. - if ( boost::starts_with(shadowSub.oldName,Data::MISSING_PREFIX)) { + if (boost::starts_with(shadowSub.oldName, Data::MISSING_PREFIX)) { Part::Feature::guessNewLink(displayName, base, shadowSub.newName.c_str()); newSubList.emplace_back(displayName); changed = true; } } - if ( changed ) + if (changed) { pcDressUp->Base.setValue(base, newSubList); + } } TaskDlgDressUpParameters::~TaskDlgDressUpParameters() = default; @@ -459,10 +492,11 @@ bool TaskDlgDressUpParameters::accept() std::stringstream str; str << Gui::Command::getObjectCmd(getObject()) << ".Base = (" << Gui::Command::getObjectCmd(parameter->getBase()) << ",["; - for (const auto & ref : refs) + for (const auto& ref : refs) { str << "\"" << ref << "\","; + } str << "])"; - Gui::Command::runCommand(Gui::Command::Doc,str.str().c_str()); + Gui::Command::runCommand(Gui::Command::Doc, str.str().c_str()); return TaskDlgFeatureParameters::accept(); } diff --git a/src/Mod/PartDesign/Gui/TaskDressUpParameters.h b/src/Mod/PartDesign/Gui/TaskDressUpParameters.h index 07e67c72c7..0bd1a5198a 100644 --- a/src/Mod/PartDesign/Gui/TaskDressUpParameters.h +++ b/src/Mod/PartDesign/Gui/TaskDressUpParameters.h @@ -36,26 +36,34 @@ class QAction; class QListWidget; class QListWidgetItem; -namespace Part { - class Feature; +namespace Part +{ +class Feature; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskDressUpParameters : public TaskFeatureParameters, public Gui::SelectionObserver +class TaskDressUpParameters: public TaskFeatureParameters, public Gui::SelectionObserver { Q_OBJECT public: - TaskDressUpParameters(ViewProviderDressUp *DressUpView, bool selectEdges, bool selectFaces, QWidget* parent = nullptr); + TaskDressUpParameters( + ViewProviderDressUp* DressUpView, + bool selectEdges, + bool selectFaces, + QWidget* parent = nullptr + ); ~TaskDressUpParameters() override; const std::vector getReferences() const; - Part::Feature *getBase() const; + Part::Feature* getBase() const; void setupTransaction(); - int getTransactionID() const { + int getTransactionID() const + { return transactionID; } @@ -80,7 +88,13 @@ protected: void updateFeature(PartDesign::DressUp* pcDressUp, const std::vector& refs); protected: - enum selectionModes { none, refSel, plane, line }; + enum selectionModes + { + none, + refSel, + plane, + line + }; void setSelectionMode(selectionModes mode); virtual void setButtons(const selectionModes mode) = 0; static void removeItemFromListWidget(QListWidget* widget, const char* itemstr); @@ -106,16 +120,16 @@ protected: private: Gui::WeakPtrT DressUpView; - Gui::ViewProvider* previouslyShownViewProvider { nullptr }; + Gui::ViewProvider* previouslyShownViewProvider {nullptr}; }; /// simulation dialog for the TaskView -class TaskDlgDressUpParameters : public TaskDlgFeatureParameters +class TaskDlgDressUpParameters: public TaskDlgFeatureParameters { Q_OBJECT public: - explicit TaskDlgDressUpParameters(ViewProviderDressUp *DressUpView); + explicit TaskDlgDressUpParameters(ViewProviderDressUp* DressUpView); ~TaskDlgDressUpParameters() override; public: @@ -124,9 +138,9 @@ public: bool reject() override; protected: - TaskDressUpParameters *parameter; + TaskDressUpParameters* parameter; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskDressUpParameters_H +#endif // GUI_TASKVIEW_TaskDressUpParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp index 3460be95c9..1c47eb72b3 100644 --- a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp @@ -46,10 +46,12 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskExtrudeParameters */ -TaskExtrudeParameters::TaskExtrudeParameters(ViewProviderExtrude* SketchBasedView, - QWidget* parent, - const std::string& pixmapname, - const QString& parname) +TaskExtrudeParameters::TaskExtrudeParameters( + ViewProviderExtrude* SketchBasedView, + QWidget* parent, + const std::string& pixmapname, + const QString& parname +) : TaskSketchBasedParameters(SketchBasedView, parent, pixmapname, parname) , propReferenceAxis(nullptr) , ui(new Ui_TaskPadPocketParameters) @@ -127,7 +129,7 @@ void TaskExtrudeParameters::setupSideDialog(SideController& side) // Because enums do not store text just an index. So this create // a inconsistence between the UI and the property. if (typeIndex > static_cast(Mode::ToShape)) { - typeIndex --; + typeIndex--; } // --- Set up UI widgets with initial values --- @@ -160,10 +162,11 @@ void TaskExtrudeParameters::setupSideDialog(SideController& side) side.lineFaceName->setProperty("FeatureName", QByteArray(faceObj->getNameInDocument())); } else if (faceObj && faceId >= 0) { - side.lineFaceName->setText( - QStringLiteral("%1:%2%3").arg(QString::fromUtf8(faceObj->Label.getValue()), - tr("Face"), - QString::number(faceId))); + side.lineFaceName->setText(QStringLiteral("%1:%2%3").arg( + QString::fromUtf8(faceObj->Label.getValue()), + tr("Face"), + QString::number(faceId) + )); side.lineFaceName->setProperty("FeatureName", QByteArray(faceObj->getNameInDocument())); } else { @@ -262,37 +265,31 @@ void TaskExtrudeParameters::connectSlots() QMetaObject::connectSlotsByName(this); auto connectSideSlots = [this](auto& side, Side sideEnum, auto modeChangedSlot) { - connect(side.lengthEdit, - qOverload(&Gui::PrefQuantitySpinBox::valueChanged), - this, - [this, sideEnum](double val) { - onLengthChanged(val, sideEnum); - }); - connect(side.offsetEdit, - qOverload(&Gui::PrefQuantitySpinBox::valueChanged), - this, - [this, sideEnum](double val) { - onOffsetChanged(val, sideEnum); - }); - connect(side.taperEdit, - qOverload(&Gui::PrefQuantitySpinBox::valueChanged), - this, - [this, sideEnum](double val) { - onTaperChanged(val, sideEnum); - }); - connect(side.changeMode, - qOverload(&QComboBox::currentIndexChanged), - this, - modeChangedSlot); + connect( + side.lengthEdit, + qOverload(&Gui::PrefQuantitySpinBox::valueChanged), + this, + [this, sideEnum](double val) { onLengthChanged(val, sideEnum); } + ); + connect( + side.offsetEdit, + qOverload(&Gui::PrefQuantitySpinBox::valueChanged), + this, + [this, sideEnum](double val) { onOffsetChanged(val, sideEnum); } + ); + connect( + side.taperEdit, + qOverload(&Gui::PrefQuantitySpinBox::valueChanged), + this, + [this, sideEnum](double val) { onTaperChanged(val, sideEnum); } + ); + connect(side.changeMode, qOverload(&QComboBox::currentIndexChanged), this, modeChangedSlot); connect(side.buttonFace, &QToolButton::toggled, this, [this, sideEnum](bool checked) { onSelectFaceToggle(checked, sideEnum); }); - connect(side.lineFaceName, - &QLineEdit::textEdited, - this, - [this, sideEnum](const QString& text) { - onFaceName(text, sideEnum); - }); + connect(side.lineFaceName, &QLineEdit::textEdited, this, [this, sideEnum](const QString& text) { + onFaceName(text, sideEnum); + }); connect(side.checkBoxAllFaces, &QCheckBox::toggled, this, [this, sideEnum](bool checked) { onAllFacesToggled(checked, sideEnum); }); @@ -385,10 +382,12 @@ void TaskExtrudeParameters::setSelectionMode(SelectionMode mode, Side side) return; } - const auto updateCheckedForSide = [mode, side](Side relatedSide, - QAbstractButton* buttonFace, - QAbstractButton* buttonShape, - QAbstractButton* buttonShapeFace) { + const auto updateCheckedForSide = [mode, side]( + Side relatedSide, + QAbstractButton* buttonFace, + QAbstractButton* buttonShape, + QAbstractButton* buttonShapeFace + ) { buttonFace->setChecked(mode == SelectFace && side == relatedSide); buttonShape->setChecked(mode == SelectShape && side == relatedSide); buttonShapeFace->setChecked(mode == SelectShapeFaces && side == relatedSide); @@ -402,8 +401,7 @@ void TaskExtrudeParameters::setSelectionMode(SelectionMode mode, Side side) switch (mode) { case SelectShape: onSelectReference(AllowSelection::WHOLE); - Gui::Selection().addSelectionGate( - new SelectionFilterGate("SELECT Part::Feature COUNT 1")); + Gui::Selection().addSelectionGate(new SelectionFilterGate("SELECT Part::Feature COUNT 1")); break; case SelectFace: onSelectReference(AllowSelection::FACE); @@ -412,12 +410,12 @@ void TaskExtrudeParameters::setSelectionMode(SelectionMode mode, Side side) onSelectReference(AllowSelection::FACE); auto& sideCtrl = getSideController(activeSelectionSide); getViewObject()->highlightShapeFaces( - getShapeFaces(*sideCtrl.UpToShape)); + getShapeFaces(*sideCtrl.UpToShape) + ); break; } case SelectReferenceAxis: - onSelectReference(AllowSelection::EDGE | AllowSelection::PLANAR - | AllowSelection::CIRCLE); + onSelectReference(AllowSelection::EDGE | AllowSelection::PLANAR | AllowSelection::CIRCLE); break; default: getViewObject()->highlightShapeFaces({}); @@ -487,8 +485,7 @@ void TaskExtrudeParameters::selectedReferenceAxis(const Gui::SelectionChanges& m } } -void TaskExtrudeParameters::selectedShapeFace(const Gui::SelectionChanges& msg, - SideController& side) +void TaskExtrudeParameters::selectedShapeFace(const Gui::SelectionChanges& msg, SideController& side) { auto extrude = getObject(); auto document = extrude->getDocument(); @@ -514,8 +511,7 @@ void TaskExtrudeParameters::selectedShapeFace(const Gui::SelectionChanges& msg, } // Add or remove the face from the list - if (const auto positionInList = std::ranges::find(faces, subName); - positionInList != faces.end()) { + if (const auto positionInList = std::ranges::find(faces, subName); positionInList != faces.end()) { faces.erase(positionInList); // Remove it if it exists } else { @@ -529,8 +525,10 @@ void TaskExtrudeParameters::selectedShapeFace(const Gui::SelectionChanges& msg, tryRecomputeFeature(); } -void PartDesignGui::TaskExtrudeParameters::selectedFace(const Gui::SelectionChanges& msg, - SideController& side) +void PartDesignGui::TaskExtrudeParameters::selectedFace( + const Gui::SelectionChanges& msg, + SideController& side +) { QString refText = onAddSelection(msg, *side.UpToFace); @@ -551,8 +549,10 @@ void PartDesignGui::TaskExtrudeParameters::selectedFace(const Gui::SelectionChan setSelectionMode(None); } -void PartDesignGui::TaskExtrudeParameters::selectedShape(const Gui::SelectionChanges& msg, - SideController& side) +void PartDesignGui::TaskExtrudeParameters::selectedShape( + const Gui::SelectionChanges& msg, + SideController& side +) { auto document = getObject()->getDocument(); @@ -613,18 +613,17 @@ void TaskExtrudeParameters::updateShapeFaces(QListWidget* list, App::PropertyLin } } -std::vector PartDesignGui::TaskExtrudeParameters::getShapeFaces(App::PropertyLinkSubList& prop) +std::vector PartDesignGui::TaskExtrudeParameters::getShapeFaces( + App::PropertyLinkSubList& prop +) { std::vector faces; auto allRefs = prop.getSubValues(); - std::copy_if(allRefs.begin(), - allRefs.end(), - std::back_inserter(faces), - [](const std::string& ref) { - return boost::starts_with(ref, "Face"); - }); + std::copy_if(allRefs.begin(), allRefs.end(), std::back_inserter(faces), [](const std::string& ref) { + return boost::starts_with(ref, "Face"); + }); return faces; } @@ -672,8 +671,7 @@ void TaskExtrudeParameters::fillDirectionCombo() // we can have sketches or faces // for sketches just get the sketch normal auto pcFeat = getObject(); - Part::Part2DObject* pcSketch = - dynamic_cast(pcFeat->Profile.getValue()); + Part::Part2DObject* pcSketch = dynamic_cast(pcFeat->Profile.getValue()); // for faces we test if it is verified and if we can get its normal if (!pcSketch) { hasFace = hasProfileFace(pcFeat); @@ -694,10 +692,7 @@ void TaskExtrudeParameters::fillDirectionCombo() addAxisToCombo(pcSketch, "N_Axis", tr("Custom direction")); } else if (hasFace) { - addAxisToCombo(pcFeat->Profile.getValue(), - std::string(), - tr("Custom direction"), - false); + addAxisToCombo(pcFeat->Profile.getValue(), std::string(), tr("Custom direction"), false); } } @@ -741,13 +736,14 @@ void TaskExtrudeParameters::fillDirectionCombo() ui->directionCB->setCurrentIndex(DirectionModes::Custom); setDirectionMode(ui->directionCB->currentIndex()); } - } -void TaskExtrudeParameters::addAxisToCombo(App::DocumentObject* linkObj, - std::string linkSubname, - QString itemText, - bool hasSketch) +void TaskExtrudeParameters::addAxisToCombo( + App::DocumentObject* linkObj, + std::string linkSubname, + QString itemText, + bool hasSketch +) { this->ui->directionCB->addItem(itemText); this->axesInList.emplace_back(new App::PropertyLinkSub); @@ -782,11 +778,13 @@ void TaskExtrudeParameters::updateWholeUI(Type type, Side side) ui->checkBoxReversed->setEnabled(sidesMode != SidesMode::Symmetric || mode1 != Mode::Dimension); } -void TaskExtrudeParameters::updateSideUI(const SideController& s, - Type featureType, - Mode sideMode, - bool isParentVisible, - bool setFocus) +void TaskExtrudeParameters::updateSideUI( + const SideController& s, + Type featureType, + Mode sideMode, + bool isParentVisible, + bool setFocus +) { // Default states for all controls for this side bool isLengthVisible = false; @@ -880,7 +878,8 @@ void TaskExtrudeParameters::onDirectionCBChanged(int num) // to distinguish that this is the direction selection setSelectionMode(SelectReferenceAxis); setDirectionMode(num); - } else if (auto extrude = getObject()) { + } + else if (auto extrude = getObject()) { if (lnk.getValue()) { if (!extrude->getDocument()->isIn(lnk.getValue())) { Base::Console().error("Object was deleted\n"); @@ -929,9 +928,8 @@ void TaskExtrudeParameters::onAllFacesToggled(bool on, Side side) void TaskExtrudeParameters::onXDirectionEditChanged(double len) { if (auto extrude = getObject()) { - extrude->Direction.setValue(len, - extrude->Direction.getValue().y, - extrude->Direction.getValue().z); + extrude->Direction + .setValue(len, extrude->Direction.getValue().y, extrude->Direction.getValue().z); tryRecomputeFeature(); // checking for case of a null vector is done in FeatureExtrude.cpp // if there was a null vector, the normal vector of the sketch is used. @@ -944,9 +942,8 @@ void TaskExtrudeParameters::onXDirectionEditChanged(double len) void TaskExtrudeParameters::onYDirectionEditChanged(double len) { if (auto extrude = getObject()) { - extrude->Direction.setValue(extrude->Direction.getValue().x, - len, - extrude->Direction.getValue().z); + extrude->Direction + .setValue(extrude->Direction.getValue().x, len, extrude->Direction.getValue().z); tryRecomputeFeature(); updateDirectionEdits(); setGizmoPositions(); @@ -956,9 +953,8 @@ void TaskExtrudeParameters::onYDirectionEditChanged(double len) void TaskExtrudeParameters::onZDirectionEditChanged(double len) { if (auto extrude = getObject()) { - extrude->Direction.setValue(extrude->Direction.getValue().x, - extrude->Direction.getValue().y, - len); + extrude->Direction + .setValue(extrude->Direction.getValue().x, extrude->Direction.getValue().y, len); tryRecomputeFeature(); updateDirectionEdits(); setGizmoPositions(); @@ -999,8 +995,8 @@ void TaskExtrudeParameters::setDirectionMode(int index) break; - // Covered by the default option - // case DirectionModes::Select: + // Covered by the default option + // case DirectionModes::Select: case DirectionModes::Custom: ui->groupBoxDirection->show(); @@ -1042,8 +1038,7 @@ void TaskExtrudeParameters::onReversedChanged(bool on) } } -void TaskExtrudeParameters::getReferenceAxis(App::DocumentObject*& obj, - std::vector& sub) const +void TaskExtrudeParameters::getReferenceAxis(App::DocumentObject*& obj, std::vector& sub) const { if (axesInList.empty()) { throw Base::RuntimeError("Not initialized!"); @@ -1139,8 +1134,7 @@ void TaskExtrudeParameters::translateFaceName(QLineEdit* lineEdit) } if (ok) { - lineEdit->setText( - QStringLiteral("%1:%2%3").arg(parts[0], tr("Face")).arg(faceId)); + lineEdit->setText(QStringLiteral("%1:%2%3").arg(parts[0], tr("Face")).arg(faceId)); } else { lineEdit->setText(parts[0]); @@ -1308,9 +1302,10 @@ void TaskExtrudeParameters::applyParameters() ui->taperEdit->apply(); ui->taperEdit2->apply(); FCMD_OBJ_CMD(obj, "UseCustomVector = " << (getCustom() ? 1 : 0)); - FCMD_OBJ_CMD(obj, - "Direction = (" << getXDirection() << ", " << getYDirection() << ", " - << getZDirection() << ")"); + FCMD_OBJ_CMD( + obj, + "Direction = (" << getXDirection() << ", " << getYDirection() << ", " << getZDirection() << ")" + ); FCMD_OBJ_CMD(obj, "ReferenceAxis = " << getReferenceAxis()); FCMD_OBJ_CMD(obj, "AlongSketchNormal = " << (getAlongSketchNormal() ? 1 : 0)); FCMD_OBJ_CMD(obj, "SideType = " << getSidesMode()); @@ -1384,14 +1379,14 @@ void TaskExtrudeParameters::setupGizmos() taperAngleGizmo1 = new Gui::RotationGizmo(ui->taperEdit); taperAngleGizmo2 = new Gui::RotationGizmo(ui->taperEdit2); - connect(ui->sidesMode, qOverload(&QComboBox::currentIndexChanged), [this] (int) { + connect(ui->sidesMode, qOverload(&QComboBox::currentIndexChanged), [this](int) { setGizmoPositions(); }); - gizmoContainer = GizmoContainer::create({ - lengthGizmo1, lengthGizmo2, - taperAngleGizmo1, taperAngleGizmo2 - }, vp); + gizmoContainer = GizmoContainer::create( + {lengthGizmo1, lengthGizmo2, taperAngleGizmo1, taperAngleGizmo2}, + vp + ); setGizmoPositions(); } @@ -1414,34 +1409,31 @@ void TaskExtrudeParameters::setGizmoPositions() std::string sideType = std::string(extrude->SideType.getValueAsString()); std::string extrudeType = std::string(extrude->Type.getValueAsString()); std::string extrudeType2 = std::string(extrude->Type2.getValueAsString()); - double dir = extrude->Reversed.getValue()? -1 : 1; + double dir = extrude->Reversed.getValue() ? -1 : 1; lengthGizmo1->Gizmo::setDraggerPlacement(center, extrude->Direction.getValue() * dir); lengthGizmo1->setVisibility(extrudeType == "Length"); taperAngleGizmo1->placeOverLinearGizmo(lengthGizmo1); taperAngleGizmo1->setVisibility(extrudeType == "Length"); lengthGizmo2->Gizmo::setDraggerPlacement(center, -extrude->Direction.getValue() * dir); - lengthGizmo2->setVisibility( - sideType == "Two sides" && extrudeType2 == "Length" - ); + lengthGizmo2->setVisibility(sideType == "Two sides" && extrudeType2 == "Length"); taperAngleGizmo2->placeOverLinearGizmo(lengthGizmo2); - taperAngleGizmo2->setVisibility( - sideType == "Two sides" && extrudeType2 == "Length" - ); + taperAngleGizmo2->setVisibility(sideType == "Two sides" && extrudeType2 == "Length"); Base::Vector3d padDir = extrude->Direction.getValue().Normalized(); Base::Vector3d sketchDir = extrude->getProfileNormal().Normalized(); double lengthFactor = padDir.Dot(sketchDir); - double multFactor = (sideType == "Symmetric")? 0.5 : 1.0; + double multFactor = (sideType == "Symmetric") ? 0.5 : 1.0; // Important note: This code assumes that nothing other than alongSketchNormal // and symmetric option influence the multFactor. If some custom gizmos changes // it then that also should be handled properly here if (extrude->AlongSketchNormal.getValue()) { - lengthGizmo1->setMultFactor(multFactor/lengthFactor); - lengthGizmo2->setMultFactor(multFactor/lengthFactor); - } else { + lengthGizmo1->setMultFactor(multFactor / lengthFactor); + lengthGizmo2->setMultFactor(multFactor / lengthFactor); + } + else { lengthGizmo1->setMultFactor(multFactor); lengthGizmo2->setMultFactor(multFactor); } @@ -1468,8 +1460,3 @@ bool TaskDlgExtrudeParameters::reject() } #include "moc_TaskExtrudeParameters.cpp" - - - - - diff --git a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h index 44c486e546..48ad303704 100644 --- a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h +++ b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h @@ -36,32 +36,38 @@ class QToolButton; class Ui_TaskPadPocketParameters; -namespace App { +namespace App +{ class Property; class PropertyLinkSubList; -} -namespace Gui { +} // namespace App +namespace Gui +{ class PrefQuantitySpinBox; } -namespace Gui { +namespace Gui +{ class LinearGizmo; class RotationalGizmo; class GizmoContainer; -} +} // namespace Gui -namespace PartDesign { +namespace PartDesign +{ class ProfileBased; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskExtrudeParameters : public TaskSketchBasedParameters +class TaskExtrudeParameters: public TaskSketchBasedParameters { Q_OBJECT - enum DirectionModes { + enum DirectionModes + { Normal, Select, Custom, @@ -69,23 +75,27 @@ class TaskExtrudeParameters : public TaskSketchBasedParameters }; public: - enum class Type { + enum class Type + { Pad, Pocket }; - enum class SidesMode { + enum class SidesMode + { OneSide, TwoSides, Symmetric, }; - enum class Side { + enum class Side + { First, Second, }; - enum class Mode { + enum class Mode + { Dimension, ThroughAll, ToLast = ThroughAll, @@ -94,7 +104,8 @@ public: ToShape, }; - enum SelectionMode { + enum SelectionMode + { None, SelectFace, SelectShape, @@ -102,19 +113,27 @@ public: SelectReferenceAxis }; - TaskExtrudeParameters(ViewProviderExtrude *ExtrudeView, QWidget *parent, - const std::string& pixmapname, const QString& parname); + TaskExtrudeParameters( + ViewProviderExtrude* ExtrudeView, + QWidget* parent, + const std::string& pixmapname, + const QString& parname + ); ~TaskExtrudeParameters() override = default; void saveHistory() override; void fillDirectionCombo(); - void addAxisToCombo(App::DocumentObject* linkObj, std::string linkSubname, QString itemText, - bool hasSketch = true); + void addAxisToCombo( + App::DocumentObject* linkObj, + std::string linkSubname, + QString itemText, + bool hasSketch = true + ); void applyParameters(); void setSelectionMode(SelectionMode mode, Side side = Side::First); - + protected: // This struct holds all pointers for one side's UI and properties struct SideController @@ -183,29 +202,31 @@ private: protected: void updateWholeUI(Type type, Side side); - void updateSideUI(const SideController& s, - Type featureType, - Mode sideMode, - bool isParentVisible, - bool setFocus); + void updateSideUI( + const SideController& s, + Type featureType, + Mode sideMode, + bool isParentVisible, + bool setFocus + ); void setupDialog(); void readValuesFromHistory(); - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; App::PropertyLinkSub* propReferenceAxis; void getReferenceAxis(App::DocumentObject*& obj, std::vector& sub) const; double getOffset() const; double getOffset2() const; - bool getAlongSketchNormal() const; - bool getCustom() const; + bool getAlongSketchNormal() const; + bool getCustom() const; std::string getReferenceAxis() const; double getXDirection() const; double getYDirection() const; double getZDirection() const; - bool getReversed() const; - int getMode() const; - int getMode2() const; - int getSidesMode() const; + bool getReversed() const; + int getMode() const; + int getMode2() const; + int getSidesMode() const; QString getFaceName(QLineEdit*) const; void onSelectionChanged(const Gui::SelectionChanges& msg) override; void translateSidesList(int index); @@ -259,12 +280,12 @@ protected: Side activeSelectionSide = Side::First; }; -class TaskDlgExtrudeParameters : public TaskDlgSketchBasedParameters +class TaskDlgExtrudeParameters: public TaskDlgSketchBasedParameters { Q_OBJECT public: - explicit TaskDlgExtrudeParameters(PartDesignGui::ViewProviderExtrude *vp); + explicit TaskDlgExtrudeParameters(PartDesignGui::ViewProviderExtrude* vp); ~TaskDlgExtrudeParameters() override = default; bool accept() override; @@ -274,6 +295,6 @@ protected: virtual TaskExtrudeParameters* getTaskParameters() = 0; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskExtrudeParameters_H +#endif // GUI_TASKVIEW_TaskExtrudeParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskFeatureParameters.cpp b/src/Mod/PartDesign/Gui/TaskFeatureParameters.cpp index 92c681e373..566c9e45d7 100644 --- a/src/Mod/PartDesign/Gui/TaskFeatureParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskFeatureParameters.cpp @@ -59,23 +59,31 @@ TaskPreviewParameters::TaskPreviewParameters(ViewProvider* vp, QWidget* parent) ui->showTransparentPreviewCheckBox->setChecked(vp->isPreviewEnabled()); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - connect(ui->showTransparentPreviewCheckBox, - &QCheckBox::checkStateChanged, - this, - &TaskPreviewParameters::onShowPreviewChanged); - connect(ui->showFinalCheckBox, - &QCheckBox::checkStateChanged, - this, - &TaskPreviewParameters::onShowFinalChanged); + connect( + ui->showTransparentPreviewCheckBox, + &QCheckBox::checkStateChanged, + this, + &TaskPreviewParameters::onShowPreviewChanged + ); + connect( + ui->showFinalCheckBox, + &QCheckBox::checkStateChanged, + this, + &TaskPreviewParameters::onShowFinalChanged + ); #else - connect(ui->showTransparentPreviewCheckBox, - &QCheckBox::stateChanged, - this, - &TaskPreviewParameters::onShowPreviewChanged); - connect(ui->showFinalCheckBox, - &QCheckBox::stateChanged, - this, - &TaskPreviewParameters::onShowFinalChanged); + connect( + ui->showTransparentPreviewCheckBox, + &QCheckBox::stateChanged, + this, + &TaskPreviewParameters::onShowPreviewChanged + ); + connect( + ui->showFinalCheckBox, + &QCheckBox::stateChanged, + this, + &TaskPreviewParameters::onShowFinalChanged + ); #endif groupLayout()->addWidget(proxy); @@ -93,8 +101,12 @@ void TaskPreviewParameters::onShowPreviewChanged(bool show) vp->showPreview(show); } -TaskFeatureParameters::TaskFeatureParameters(PartDesignGui::ViewProvider *vp, QWidget *parent, - const std::string& pixmapname, const QString& parname) +TaskFeatureParameters::TaskFeatureParameters( + PartDesignGui::ViewProvider* vp, + QWidget* parent, + const std::string& pixmapname, + const QString& parname +) : TaskBox(Gui::BitmapFactory().pixmap(pixmapname.c_str()), parname, true, parent) , vp(vp) , blockUpdate(false) @@ -120,7 +132,7 @@ void TaskFeatureParameters::recomputeFeature() { if (!blockUpdate) { App::DocumentObject* obj = getObject(); - assert (obj); + assert(obj); obj->recomputeFeature(); } } @@ -128,7 +140,7 @@ void TaskFeatureParameters::recomputeFeature() /********************************************************************* * Task Dialog * *********************************************************************/ -TaskDlgFeatureParameters::TaskDlgFeatureParameters(PartDesignGui::ViewProvider *vp) +TaskDlgFeatureParameters::TaskDlgFeatureParameters(PartDesignGui::ViewProvider* vp) : preview(new TaskPreviewParameters(vp)) , vp(vp) { @@ -143,33 +155,35 @@ bool TaskDlgFeatureParameters::accept() bool isUpdateBlocked = false; try { // Iterate over parameter dialogs and apply all parameters from them - for ( QWidget *wgt : Content ) { - TaskFeatureParameters *param = qobject_cast (wgt); - if(!param) + for (QWidget* wgt : Content) { + TaskFeatureParameters* param = qobject_cast(wgt); + if (!param) { continue; + } - param->saveHistory (); - param->apply (); + param->saveHistory(); + param->apply(); isUpdateBlocked |= param->isUpdateBlocked(); } // Make sure the feature is what we are expecting // Should be fine but you never know... - if ( !feature->isDerivedFrom() ) { + if (!feature->isDerivedFrom()) { throw Base::TypeError("Bad object processed in the feature dialog."); } - if(isUpdateBlocked){ + if (isUpdateBlocked) { Gui::cmdAppDocument(feature, "recompute()"); - } else { + } + else { // object was already computed, nothing more to do with it... Gui::cmdAppDocument(feature, "purgeTouched()"); if (!feature->isValid()) { - throw Base::RuntimeError(getObject()->getStatusString()); + throw Base::RuntimeError(getObject()->getStatusString()); } // ...but touch parents to signal the change... - for (auto obj : feature->getInList()){ + for (auto obj : feature->getInList()) { obj->touch(); } // ...and recompute them @@ -180,7 +194,9 @@ bool TaskDlgFeatureParameters::accept() throw Base::RuntimeError(getObject()->getStatusString()); } - App::DocumentObject* previous = static_cast(feature)->getBaseObject(/* silent = */ true ); + App::DocumentObject* previous = static_cast(feature)->getBaseObject( + /* silent = */ true + ); Gui::cmdAppObjectHide(previous); // detach the task panel from the selection to avoid to invoke @@ -188,29 +204,34 @@ bool TaskDlgFeatureParameters::accept() std::vector subwidgets = getDialogContent(); for (auto it : subwidgets) { TaskSketchBasedParameters* param = qobject_cast(it); - if (param) + if (param) { param->detachSelection(); + } } Gui::cmdGuiDocument(feature, "resetEdit()"); Gui::Command::commitCommand(); - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { - QString errorText = QString::fromUtf8(e.what()); - QString statusText = QString::fromUtf8(getObject()->getStatusString()); + QString errorText = QString::fromUtf8(e.what()); + QString statusText = QString::fromUtf8(getObject()->getStatusString()); - // generic, fallback error message - if (errorText == QStringLiteral("Error") || errorText.isEmpty()) { - if (!statusText.isEmpty() && statusText != QStringLiteral("Error")) { - errorText = statusText; - } else { - errorText = tr("The feature could not be created with the given parameters.\n" - "The geometry may be invalid or the parameters may be incompatible.\n" - "Please adjust the parameters and try again."); + // generic, fallback error message + if (errorText == QStringLiteral("Error") || errorText.isEmpty()) { + if (!statusText.isEmpty() && statusText != QStringLiteral("Error")) { + errorText = statusText; + } + else { + errorText = tr( + "The feature could not be created with the given parameters.\n" + "The geometry may be invalid or the parameters may be incompatible.\n" + "Please adjust the parameters and try again." + ); + } } - } - QMessageBox::warning(Gui::getMainWindow(), tr("Input error"), errorText); - return false; + QMessageBox::warning(Gui::getMainWindow(), tr("Input error"), errorText); + return false; } return true; } @@ -225,15 +246,16 @@ bool TaskDlgFeatureParameters::reject() // Find out previous feature we won't be able to do it after abort // (at least in the body case) - App::DocumentObject* previous = feature->getBaseObject(/* silent = */ true ); + App::DocumentObject* previous = feature->getBaseObject(/* silent = */ true); // detach the task panel from the selection to avoid to invoke // eventually onAddSelection when the selection changes std::vector subwidgets = getDialogContent(); for (auto it : subwidgets) { TaskSketchBasedParameters* param = qobject_cast(it); - if (param) + if (param) { param->detachSelection(); + } } // roll back the done things which may delete the feature diff --git a/src/Mod/PartDesign/Gui/TaskFeatureParameters.h b/src/Mod/PartDesign/Gui/TaskFeatureParameters.h index 99b31be128..8fcaf81145 100644 --- a/src/Mod/PartDesign/Gui/TaskFeatureParameters.h +++ b/src/Mod/PartDesign/Gui/TaskFeatureParameters.h @@ -31,11 +31,12 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ class Ui_TaskPreviewParameters; -class TaskPreviewParameters : public Gui::TaskView::TaskBox +class TaskPreviewParameters: public Gui::TaskView::TaskBox { Q_OBJECT @@ -52,24 +53,30 @@ private: std::unique_ptr ui; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/PartDesign/Preview"); + "User parameter:BaseApp/Preferences/Mod/PartDesign/Preview" + ); }; /// Convenience class to collect common methods for all SketchBased features -class TaskFeatureParameters : public Gui::TaskView::TaskBox, - public Gui::DocumentObserver +class TaskFeatureParameters: public Gui::TaskView::TaskBox, public Gui::DocumentObserver { Q_OBJECT public: - TaskFeatureParameters(PartDesignGui::ViewProvider* vp, QWidget *parent, - const std::string& pixmapname, const QString& parname); + TaskFeatureParameters( + PartDesignGui::ViewProvider* vp, + QWidget* parent, + const std::string& pixmapname, + const QString& parname + ); ~TaskFeatureParameters() override = default; /// save field history - virtual void saveHistory() {} + virtual void saveHistory() + {} /// apply changes made in the parameters input to the model via commands - virtual void apply() {} + virtual void apply() + {} void recomputeFeature(); @@ -87,14 +94,15 @@ private: void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; protected: - template T* getViewObject() const + template + T* getViewObject() const { - static_assert(std::is_base_of::value, - "Wrong template argument"); + static_assert(std::is_base_of::value, "Wrong template argument"); return freecad_cast(vp); } - template T* getObject() const + template + T* getObject() const { static_assert(std::is_base_of::value, "Wrong template argument"); @@ -127,19 +135,19 @@ protected: } protected: - PartDesignGui::ViewProvider *vp; + PartDesignGui::ViewProvider* vp; private: bool blockUpdate; }; /// A common base for sketch based, dressup and other solid parameters dialogs -class TaskDlgFeatureParameters : public Gui::TaskView::TaskDialog +class TaskDlgFeatureParameters: public Gui::TaskView::TaskDialog { Q_OBJECT public: - explicit TaskDlgFeatureParameters(PartDesignGui::ViewProvider *vp); + explicit TaskDlgFeatureParameters(PartDesignGui::ViewProvider* vp); ~TaskDlgFeatureParameters() override; public: @@ -148,14 +156,15 @@ public: /// is called by the framework if the dialog is rejected (Cancel) bool reject() override; - template T* getViewObject() const + template + T* getViewObject() const { - static_assert(std::is_base_of::value, - "Wrong template argument"); + static_assert(std::is_base_of::value, "Wrong template argument"); return freecad_cast(vp); } - template T* getObject() const + template + T* getObject() const { static_assert(std::is_base_of::value, "Wrong template argument"); if (vp) { @@ -172,7 +181,7 @@ private: PartDesignGui::ViewProvider* vp; }; -} //namespace PartDesignGui +} // namespace PartDesignGui #endif /* end of include guard: TASKFEATUREPARAMETERS_H_NAHKE2YZ */ diff --git a/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp b/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp index 806c6f36fa..7bdb667498 100644 --- a/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp +++ b/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp @@ -86,10 +86,12 @@ const QString TaskFeaturePick::getFeatureStatusString(const featureStatus st) return QString(); } -TaskFeaturePick::TaskFeaturePick(std::vector& objects, - const std::vector& status, - bool singleFeatureSelect, - QWidget* parent) +TaskFeaturePick::TaskFeaturePick( + std::vector& objects, + const std::vector& status, + bool singleFeatureSelect, + QWidget* parent +) : TaskBox(Gui::BitmapFactory().pixmap("edit-select-all"), tr("Select attachment"), true, parent) , ui(new Ui_TaskFeaturePick) , doSelection(false) @@ -123,9 +125,10 @@ TaskFeaturePick::TaskFeaturePick(std::vector& objects, bool attached = false; for (; statusIt != status.end(); ++statusIt, ++objIt) { - QListWidgetItem* item = new QListWidgetItem( - QStringLiteral("%1 (%2)").arg(QString::fromUtf8((*objIt)->Label.getValue()), - getFeatureStatusString(*statusIt))); + QListWidgetItem* item = new QListWidgetItem(QStringLiteral("%1 (%2)").arg( + QString::fromUtf8((*objIt)->Label.getValue()), + getFeatureStatusString(*statusIt) + )); item->setData(Qt::UserRole, QString::fromLatin1((*objIt)->getNameInDocument())); ui->listWidget->addItem(item); @@ -156,7 +159,8 @@ TaskFeaturePick::TaskFeaturePick(std::vector& objects, const auto& origin = originPair.first; auto* vpo = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); if (vpo) { vpo->setTemporaryVisibility(originVisStatus[origin]); vpo->setTemporaryScale(Gui::ViewParams::instance()->getDatumTemporaryScaleFactor()); @@ -254,9 +258,9 @@ std::vector TaskFeaturePick::getFeatures() std::vector result; for (const auto& feature : features) { - result.push_back(App::GetApplication() - .getDocument(documentName.c_str()) - ->getObject(feature.toLatin1().data())); + result.push_back( + App::GetApplication().getDocument(documentName.c_str())->getObject(feature.toLatin1().data()) + ); } return result; @@ -305,8 +309,8 @@ std::vector TaskFeaturePick::buildFeatures() // doesn't supposed to get here anything but sketch but to be on the // safe side better to check if (copy->isDerivedFrom()) { - Sketcher::SketchObject* sketch = - static_cast(copy); + Sketcher::SketchObject* sketch + = static_cast(copy); PartDesignGui::fixSketchSupport(sketch); } } @@ -340,8 +344,7 @@ std::vector TaskFeaturePick::buildFeatures() return result; } -App::DocumentObject* -TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool independent) +App::DocumentObject* TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool independent) { App::DocumentObject* copy = nullptr; @@ -436,14 +439,14 @@ TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool indepe } else if (!entity.empty()) { datumCopy->Shape.setValue( - static_cast(obj)->Shape.getShape().getSubShape(entity.c_str())); + static_cast(obj)->Shape.getShape().getSubShape(entity.c_str()) + ); } else { datumCopy->Shape.setValue(static_cast(obj)->Shape.getValue()); } } - else if (obj->is() - || obj->isDerivedFrom()) { + else if (obj->is() || obj->isDerivedFrom()) { auto* doc = App::GetApplication().getActiveDocument(); auto* shapeBinderObj = doc->addObject(name.c_str()); @@ -455,8 +458,7 @@ TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool indepe } copy = shapeBinderObj; } - else if (obj->isDerivedFrom() - || obj->isDerivedFrom()) { + else if (obj->isDerivedFrom() || obj->isDerivedFrom()) { auto* doc = App::GetApplication().getActiveDocument(); auto* shapeBinderObj = doc->addObject(name.c_str()); @@ -466,8 +468,8 @@ TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool indepe else { std::vector subvalues; subvalues.push_back(entity); - Part::TopoShape shape = - PartDesign::ShapeBinder::buildShapeFromReferences(shapeBinderObj, subvalues); + Part::TopoShape shape + = PartDesign::ShapeBinder::buildShapeFromReferences(shapeBinderObj, subvalues); shapeBinderObj->Shape.setValue(shape); } copy = shapeBinderObj; @@ -475,8 +477,10 @@ TaskFeaturePick::makeCopy(App::DocumentObject* obj, std::string sub, bool indepe if (independent && shapeProp) { auto* featureObj = static_cast(obj); - shapeProp->setValue(entity.empty() ? featureObj->Shape.getValue() - : featureObj->Shape.getShape().getSubShape(entity.c_str())); + shapeProp->setValue( + entity.empty() ? featureObj->Shape.getValue() + : featureObj->Shape.getShape().getSubShape(entity.c_str()) + ); } } @@ -512,7 +516,8 @@ void TaskFeaturePick::onSelectionChanged(const Gui::SelectionChanges& msg) QMetaObject::invokeMethod( qobject_cast(&Gui::Control()), "accept", - Qt::QueuedConnection); + Qt::QueuedConnection + ); } } } @@ -550,9 +555,11 @@ void TaskFeaturePick::onDoubleClick(QListWidgetItem* item) Gui::Selection().addSelection(documentName.c_str(), t.toLatin1()); doSelection = false; - QMetaObject::invokeMethod(qobject_cast(&Gui::Control()), - "accept", - Qt::QueuedConnection); + QMetaObject::invokeMethod( + qobject_cast(&Gui::Control()), + "accept", + Qt::QueuedConnection + ); } void TaskFeaturePick::slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) @@ -588,12 +595,14 @@ void TaskFeaturePick::showExternal(bool val) // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgFeaturePick::TaskDlgFeaturePick(std::vector& objects, - const std::vector& status, - std::function)> afunc, - std::function)> wfunc, - bool singleFeatureSelect, - std::function abortfunc /* = NULL */) +TaskDlgFeaturePick::TaskDlgFeaturePick( + std::vector& objects, + const std::vector& status, + std::function)> afunc, + std::function)> wfunc, + bool singleFeatureSelect, + std::function abortfunc /* = NULL */ +) : TaskDialog() , accepted(false) { diff --git a/src/Mod/PartDesign/Gui/TaskFeaturePick.h b/src/Mod/PartDesign/Gui/TaskFeaturePick.h index 84139fb96d..b63fb6a14f 100644 --- a/src/Mod/PartDesign/Gui/TaskFeaturePick.h +++ b/src/Mod/PartDesign/Gui/TaskFeaturePick.h @@ -33,18 +33,20 @@ #include -namespace PartDesignGui { +namespace PartDesignGui +{ class SoSwitch; class Ui_TaskFeaturePick; -class TaskFeaturePick : public Gui::TaskView::TaskBox - , public Gui::SelectionObserver - , public Gui::DocumentObserver +class TaskFeaturePick: public Gui::TaskView::TaskBox, + public Gui::SelectionObserver, + public Gui::DocumentObserver { Q_OBJECT public: - enum featureStatus { + enum featureStatus + { validFeature = 0, invalidShape, noWire, @@ -56,10 +58,12 @@ public: afterTip }; - TaskFeaturePick(std::vector &objects, - const std::vector &status, - bool singleFeatureSelect, - QWidget *parent = nullptr); + TaskFeaturePick( + std::vector& objects, + const std::vector& status, + bool singleFeatureSelect, + QWidget* parent = nullptr + ); ~TaskFeaturePick() override; @@ -74,7 +78,7 @@ protected Q_SLOTS: void onUpdate(bool); void onSelectionChanged(const Gui::SelectionChanges& msg) override; void onItemSelectionChanged(); - void onDoubleClick(QListWidgetItem *item); + void onDoubleClick(QListWidgetItem* item); protected: /** Notifies when the object is about to be removed. */ @@ -100,17 +104,19 @@ private: /// simulation dialog for the TaskView -class TaskDlgFeaturePick : public Gui::TaskView::TaskDialog +class TaskDlgFeaturePick: public Gui::TaskView::TaskDialog { Q_OBJECT public: - TaskDlgFeaturePick( std::vector &objects, - const std::vector &status, - std::function)> acceptfunc, - std::function)> workfunc, - bool singleFeatureSelect, - std::function abortfunc = 0); + TaskDlgFeaturePick( + std::vector& objects, + const std::vector& status, + std::function)> acceptfunc, + std::function)> workfunc, + bool singleFeatureSelect, + std::function abortfunc = 0 + ); ~TaskDlgFeaturePick() override; public: @@ -124,23 +130,27 @@ public: bool reject() override; /// is called by the framework if the user presses the help button bool isAllowedAlterDocument() const override - { return false; } + { + return false; + } void showExternal(bool val); /// returns for Close and Help button QDialogButtonBox::StandardButtons getStandardButtons() const override - { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } + { + return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + } protected: - TaskFeaturePick *pick; + TaskFeaturePick* pick; bool accepted; - std::function)> acceptFunction; - std::function)> workFunction; - std::function abortFunction; + std::function)> acceptFunction; + std::function)> workFunction; + std::function abortFunction; }; -} +} // namespace PartDesignGui -#endif // PARTDESIGNGUI_FeaturePickDialog_H +#endif // PARTDESIGNGUI_FeaturePickDialog_H diff --git a/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp b/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp index a3d56aedb9..102b3c141a 100644 --- a/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -119,7 +118,8 @@ void TaskFilletParameters::onSelectionChanged(const Gui::SelectionChanges& msg) if (selectionMode == refSel) { referenceSelected(msg, ui->listWidgetReferences); } - } else if (msg.Type == Gui::SelectionChanges::ClrSelection) { + } + else if (msg.Type == Gui::SelectionChanges::ClrSelection) { // TODO: the gizmo position should be only recalculated when the feature associated // with the gizmo is removed from the list setGizmoPositions(); @@ -252,7 +252,7 @@ void TaskFilletParameters::setGizmoPositions() // The dragger length won't be equal to the radius if the two faces // are not orthogonal so this correction is needed double angle = props1.dir.GetAngle(props2.dir); - double correction = 1/std::tan(angle/2); + double correction = 1 / std::tan(angle / 2); radiusGizmo->setMultFactor(correction); radiusGizmo2->setMultFactor(correction); diff --git a/src/Mod/PartDesign/Gui/TaskFilletParameters.h b/src/Mod/PartDesign/Gui/TaskFilletParameters.h index 922bdb3004..833e1c6abe 100644 --- a/src/Mod/PartDesign/Gui/TaskFilletParameters.h +++ b/src/Mod/PartDesign/Gui/TaskFilletParameters.h @@ -31,19 +31,21 @@ class Ui_TaskFilletParameters; -namespace Gui { +namespace Gui +{ class LinearGizmo; class GizmoContainer; -} +} // namespace Gui -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskFilletParameters : public TaskDressUpParameters +class TaskFilletParameters: public TaskDressUpParameters { Q_OBJECT public: - explicit TaskFilletParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + explicit TaskFilletParameters(ViewProviderDressUp* DressUpView, QWidget* parent = nullptr); ~TaskFilletParameters() override; void apply() override; @@ -71,12 +73,12 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgFilletParameters : public TaskDlgDressUpParameters +class TaskDlgFilletParameters: public TaskDlgDressUpParameters { Q_OBJECT public: - explicit TaskDlgFilletParameters(ViewProviderFillet *DressUpView); + explicit TaskDlgFilletParameters(ViewProviderFillet* DressUpView); ~TaskDlgFilletParameters() override; public: @@ -84,6 +86,6 @@ public: bool accept() override; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskFilletParameters_H +#endif // GUI_TASKVIEW_TaskFilletParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp b/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp index e3e8c2aa47..e64bcd8935 100644 --- a/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp @@ -51,12 +51,8 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskHelixParameters */ -TaskHelixParameters::TaskHelixParameters(PartDesignGui::ViewProviderHelix* HelixView, - QWidget* parent) - : TaskSketchBasedParameters(HelixView, - parent, - "PartDesign_AdditiveHelix", - tr("Helix Parameters")) +TaskHelixParameters::TaskHelixParameters(PartDesignGui::ViewProviderHelix* HelixView, QWidget* parent) + : TaskSketchBasedParameters(HelixView, parent, "PartDesign_AdditiveHelix", tr("Helix Parameters")) , ui(new Ui_TaskHelixParameters) { // we need a separate container widget to add all controls to @@ -178,7 +174,8 @@ void TaskHelixParameters::showCoordinateAxes() App::Origin* origin = body->getOrigin(); ViewProviderCoordinateSystem* vpOrigin; vpOrigin = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); vpOrigin->setTemporaryVisibility(Gui::DatumElement::Axes); } catch (const Base::Exception& ex) { @@ -274,9 +271,11 @@ int TaskHelixParameters::addCurrentLink() return indexOfCurrent; } -void TaskHelixParameters::addAxisToCombo(App::DocumentObject* linkObj, - std::string linkSubname, - QString itemText) +void TaskHelixParameters::addAxisToCombo( + App::DocumentObject* linkObj, + std::string linkSubname, + QString itemText +) { this->ui->axis->addItem(itemText); this->axesInList.emplace_back(new App::PropertyLinkSub); @@ -369,8 +368,7 @@ void TaskHelixParameters::adaptVisibilityToMode() void TaskHelixParameters::assignToolTipsFromPropertyDocs() { auto helix = getObject(); - const char* propCategory = - "App::Property"; // cf. https://tracker.freecad.org/view.php?id=0002524 + const char* propCategory = "App::Property"; // cf. https://tracker.freecad.org/view.php?id=0002524 QString toolTip; // Beware that "Axis" in the GUI actually represents the property "ReferenceAxis"! @@ -495,8 +493,9 @@ void TaskHelixParameters::onAxisChanged(int num) if (auto sketch = dynamic_cast(helix->Profile.getValue())) { Gui::cmdAppObjectShow(sketch); } - TaskSketchBasedParameters::onSelectReference(AllowSelection::EDGE | AllowSelection::PLANAR - | AllowSelection::CIRCLE); + TaskSketchBasedParameters::onSelectReference( + AllowSelection::EDGE | AllowSelection::PLANAR | AllowSelection::CIRCLE + ); return; } else { @@ -593,7 +592,8 @@ TaskHelixParameters::~TaskHelixParameters() App::Origin* origin = body->getOrigin(); ViewProviderCoordinateSystem* vpOrigin {}; vpOrigin = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); vpOrigin->resetTemporaryVisibility(); } } @@ -623,8 +623,7 @@ void TaskHelixParameters::changeEvent(QEvent* e) } } -void TaskHelixParameters::getReferenceAxis(App::DocumentObject*& obj, - std::vector& sub) const +void TaskHelixParameters::getReferenceAxis(App::DocumentObject*& obj, std::vector& sub) const { if (axesInList.empty()) { throw Base::RuntimeError("Not initialized!"); @@ -633,8 +632,7 @@ void TaskHelixParameters::getReferenceAxis(App::DocumentObject*& obj, int num = ui->axis->currentIndex(); const App::PropertyLinkSub& lnk = *(axesInList.at(num)); if (!lnk.getValue()) { - throw Base::RuntimeError( - "Still in reference selection mode; reference was not selected yet"); + throw Base::RuntimeError("Still in reference selection mode; reference was not selected yet"); } else { auto revolution = getObject(); @@ -650,7 +648,8 @@ void TaskHelixParameters::getReferenceAxis(App::DocumentObject*& obj, bool TaskHelixParameters::showPreview(PartDesign::Helix* helix) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/PartDesign"); + "User parameter:BaseApp/Preferences/Mod/PartDesign" + ); if ((hGrp->GetBool("SubractiveHelixPreview", true) && helix->getAddSubType() == PartDesign::FeatureAddSub::Subtractive) || (hGrp->GetBool("AdditiveHelixPreview", false) @@ -661,8 +660,7 @@ bool TaskHelixParameters::showPreview(PartDesign::Helix* helix) return false; } -void TaskHelixParameters::startReferenceSelection(App::DocumentObject* profile, - App::DocumentObject* base) +void TaskHelixParameters::startReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base) { if (auto helix = getObject()) { if (helix && showPreview(helix)) { @@ -677,8 +675,7 @@ void TaskHelixParameters::startReferenceSelection(App::DocumentObject* profile, } } -void TaskHelixParameters::finishReferenceSelection(App::DocumentObject* profile, - App::DocumentObject* base) +void TaskHelixParameters::finishReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base) { if (auto helix = getObject()) { if (helix && showPreview(helix)) { @@ -720,7 +717,7 @@ void TaskHelixParameters::setupGizmos(ViewProviderHelix* vp) heightGizmo = new Gui::LinearGizmo(ui->height); - connect(ui->inputMode, qOverload(&QComboBox::currentIndexChanged), [this] (int index) { + connect(ui->inputMode, qOverload(&QComboBox::currentIndexChanged), [this](int index) { bool isPitchTurnsAngle = index == static_cast(HelixMode::pitch_turns_angle); heightGizmo->setVisibility(!isPitchTurnsAngle); }); @@ -745,7 +742,7 @@ void TaskHelixParameters::setGizmoPositions() } gizmoContainer->visible = true; Part::TopoShape profileShape = helix->getProfileShape(); - double reversed = propReversed->getValue()? -1.0 : 1.0; + double reversed = propReversed->getValue() ? -1.0 : 1.0; auto profileCentre = getMidPointFromProfile(profileShape); Base::Vector3d axisDir = helix->Axis.getValue() * reversed; Base::Vector3d basePos = helix->Base.getValue(); diff --git a/src/Mod/PartDesign/Gui/TaskHelixParameters.h b/src/Mod/PartDesign/Gui/TaskHelixParameters.h index b88231a7ee..25375cb5d9 100644 --- a/src/Mod/PartDesign/Gui/TaskHelixParameters.h +++ b/src/Mod/PartDesign/Gui/TaskHelixParameters.h @@ -29,22 +29,24 @@ #include "ViewProviderHelix.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class LinearGizmo; class GizmoContainer; class ViewProvider; -} +} // namespace Gui -namespace PartDesignGui { +namespace PartDesignGui +{ class Ui_TaskHelixParameters; - -class TaskHelixParameters : public TaskSketchBasedParameters +class TaskHelixParameters: public TaskSketchBasedParameters { Q_OBJECT @@ -93,17 +95,17 @@ protected: void startReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base) override; void finishReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base) override; - //mirrors of helixes's properties - App::PropertyLength* propPitch; - App::PropertyLength* propHeight; - App::PropertyFloatConstraint* propTurns; - App::PropertyBool* propLeftHanded; - App::PropertyBool* propReversed; - App::PropertyLinkSub* propReferenceAxis; - App::PropertyAngle* propAngle; - App::PropertyDistance* propGrowth; + // mirrors of helixes's properties + App::PropertyLength* propPitch; + App::PropertyLength* propHeight; + App::PropertyFloatConstraint* propTurns; + App::PropertyBool* propLeftHanded; + App::PropertyBool* propReversed; + App::PropertyLinkSub* propReferenceAxis; + App::PropertyAngle* propAngle; + App::PropertyDistance* propGrowth; App::PropertyEnumeration* propMode; - App::PropertyBool* propOutside; + App::PropertyBool* propOutside; private: @@ -137,7 +139,7 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgHelixParameters : public TaskDlgSketchBasedParameters +class TaskDlgHelixParameters: public TaskDlgSketchBasedParameters { Q_OBJECT @@ -145,6 +147,6 @@ public: explicit TaskDlgHelixParameters(ViewProviderHelix* HelixView); }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskHelixParameters_H +#endif // GUI_TASKVIEW_TaskHelixParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp b/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp index dd71ab3cee..6470b42e1f 100644 --- a/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp @@ -159,7 +159,7 @@ TaskHoleParameters::TaskHoleParameters(ViewProviderHole* HoleView, QWidget* pare bool isFlatDrill = pcHole->DrillPoint.getValue() == 0L; bool depthIsDimension = std::string(pcHole->DepthType.getValueAsString()) == "Dimension"; ui->DrillPointAngled->setChecked(!isFlatDrill && depthIsDimension); - ui->DrillPointAngle->setEnabled(!isFlatDrill && depthIsDimension); + ui->DrillPointAngle->setEnabled(!isFlatDrill && depthIsDimension); ui->DrillForDepth->setEnabled(!isFlatDrill && depthIsDimension); ui->Tapered->setChecked(pcHole->Tapered.getValue()); @@ -189,7 +189,9 @@ TaskHoleParameters::TaskHoleParameters(ViewProviderHole* HoleView, QWidget* pare std::string(pcHole->ThreadDepthType.getValueAsString()) == "Dimension" ); - ui->BaseProfileType->setCurrentIndex(PartDesign::Hole::baseProfileOption_bitmaskToIdx(pcHole->BaseProfileType.getValue())); + ui->BaseProfileType->setCurrentIndex( + PartDesign::Hole::baseProfileOption_bitmaskToIdx(pcHole->BaseProfileType.getValue()) + ); setCutDiagram(); @@ -262,7 +264,8 @@ TaskHoleParameters::TaskHoleParameters(ViewProviderHole* HoleView, QWidget* pare // NOLINTBEGIN connectPropChanged = App::GetApplication().signalChangePropertyEditor.connect( - std::bind(&TaskHoleParameters::changedObject, this, sp::_1, sp::_2)); + std::bind(&TaskHoleParameters::changedObject, this, sp::_1, sp::_2) + ); // NOLINTEND this->groupLayout()->addWidget(proxy); @@ -417,18 +420,15 @@ void TaskHoleParameters::setCutDiagram() auto hole = getObject(); const std::string holeCutTypeString = hole->HoleCutType.getValueAsString(); const std::string threadTypeString = hole->ThreadType.getValueAsString(); - bool isAngled = ( - std::string(hole->DepthType.getValueAsString()) == "Dimension" - && ui->DrillPointAngled->isChecked() - ); - bool isCountersink = ( - holeCutTypeString == "Countersink" - || hole->isDynamicCountersink(threadTypeString, holeCutTypeString) - ); - bool isCounterbore = ( - holeCutTypeString == "Counterbore" - || hole->isDynamicCounterbore(threadTypeString, holeCutTypeString) - ); + bool isAngled + = (std::string(hole->DepthType.getValueAsString()) == "Dimension" + && ui->DrillPointAngled->isChecked()); + bool isCountersink + = (holeCutTypeString == "Countersink" + || hole->isDynamicCountersink(threadTypeString, holeCutTypeString)); + bool isCounterbore + = (holeCutTypeString == "Counterbore" + || hole->isDynamicCounterbore(threadTypeString, holeCutTypeString)); bool isCounterdrill = (holeCutTypeString == "Counterdrill"); bool includeAngle = hole->DrillForDepth.getValue(); bool isNotCut = holeCutTypeString == "None"; @@ -462,7 +462,8 @@ void TaskHoleParameters::setCutDiagram() if (isAngled) { baseFileName += includeAngle ? "_angled_included" : "_angled"; - } else { + } + else { baseFileName += "_flat"; } @@ -547,9 +548,7 @@ void TaskHoleParameters::depthChanged(int index) hole->DepthType.setValue(index); recomputeFeature(); // enabling must be handled after recompute - bool DepthisDimension = ( - std::string(hole->DepthType.getValueAsString()) == "Dimension" - ); + bool DepthisDimension = (std::string(hole->DepthType.getValueAsString()) == "Dimension"); ui->DrillPointAngled->setEnabled(DepthisDimension); ui->DrillPointAngle->setEnabled(DepthisDimension); ui->DrillForDepth->setEnabled(DepthisDimension); @@ -671,14 +670,32 @@ void TaskHoleParameters::threadTypeChanged(int index) ui->ThreadFit->setItemText(2, noneText); } else if (TypeClass == QByteArray("ISO")) { - ui->ThreadFit->setItemText(0, tr("Medium", "Distance between thread crest and hole wall, use ISO-273 nomenclature or equivalent if possible")); - ui->ThreadFit->setItemText(1, tr("Fine", "Distance between thread crest and hole wall, use ISO-273 nomenclature or equivalent if possible")); - ui->ThreadFit->setItemText(2, tr("Coarse", "Distance between thread crest and hole wall, use ISO-273 nomenclature or equivalent if possible")); + ui->ThreadFit->setItemText( + 0, + tr("Medium", "Distance between thread crest and hole wall, use ISO-273 nomenclature or equivalent if possible") + ); + ui->ThreadFit->setItemText( + 1, + tr("Fine", "Distance between thread crest and hole wall, use ISO-273 nomenclature or equivalent if possible") + ); + ui->ThreadFit->setItemText( + 2, + tr("Coarse", "Distance between thread crest and hole wall, use ISO-273 nomenclature or equivalent if possible") + ); } else if (TypeClass == QByteArray("UTS")) { - ui->ThreadFit->setItemText(0, tr("Normal", "Distance between thread crest and hole wall, use ASME B18.2.8 nomenclature or equivalent if possible")); - ui->ThreadFit->setItemText(1, tr("Close", "Distance between thread crest and hole wall, use ASME B18.2.8 nomenclature or equivalent if possible")); - ui->ThreadFit->setItemText(2, tr("Loose", "Distance between thread crest and hole wall, use ASME B18.2.8 nomenclature or equivalent if possible")); + ui->ThreadFit->setItemText( + 0, + tr("Normal", "Distance between thread crest and hole wall, use ASME B18.2.8 nomenclature or equivalent if possible") + ); + ui->ThreadFit->setItemText( + 1, + tr("Close", "Distance between thread crest and hole wall, use ASME B18.2.8 nomenclature or equivalent if possible") + ); + ui->ThreadFit->setItemText( + 2, + tr("Loose", "Distance between thread crest and hole wall, use ASME B18.2.8 nomenclature or equivalent if possible") + ); } else { ui->ThreadFit->setItemText(0, tr("Normal", "Distance between thread crest and hole wall")); @@ -776,7 +793,7 @@ void TaskHoleParameters::changedObject(const App::Document&, const App::Property { auto hole = getObject(); if (!hole) { - return; // happens when aborting the command + return; // happens when aborting the command } bool ro = Prop.isReadOnly(); @@ -823,9 +840,21 @@ void TaskHoleParameters::changedObject(const App::Document&, const App::Property widget->setCurrentIndex(selected); }; - updateComboBoxItems(ui->ThreadSize, hole->ThreadSize.getEnumVector(), hole->ThreadSize.getValue()); - updateComboBoxItems(ui->HoleCutType, hole->HoleCutType.getEnumVector(), hole->HoleCutType.getValue()); - updateComboBoxItems(ui->ThreadClass, hole->ThreadClass.getEnumVector(), hole->ThreadClass.getValue()); + updateComboBoxItems( + ui->ThreadSize, + hole->ThreadSize.getEnumVector(), + hole->ThreadSize.getValue() + ); + updateComboBoxItems( + ui->HoleCutType, + hole->HoleCutType.getEnumVector(), + hole->HoleCutType.getValue() + ); + updateComboBoxItems( + ui->ThreadClass, + hole->ThreadClass.getEnumVector(), + hole->ThreadClass.getValue() + ); } else if (&Prop == &hole->ThreadSize) { ui->ThreadSize->setEnabled(true); @@ -878,7 +907,10 @@ void TaskHoleParameters::changedObject(const App::Document&, const App::Property } else if (&Prop == &hole->DrillPoint) { ui->DrillPointAngled->setEnabled(true); - updateCheckable(ui->DrillPointAngled, hole->DrillPoint.getValueAsString() == std::string("Angled")); + updateCheckable( + ui->DrillPointAngled, + hole->DrillPoint.getValueAsString() == std::string("Angled") + ); } else if (&Prop == &hole->DrillPointAngle) { ui->DrillPointAngle->setEnabled(true); @@ -911,9 +943,13 @@ void TaskHoleParameters::changedObject(const App::Document&, const App::Property else if (&Prop == &hole->ThreadDepth) { ui->ThreadDepth->setEnabled(true); updateSpinBox(ui->ThreadDepth, hole->ThreadDepth.getValue()); - } else if (&Prop == &hole->BaseProfileType) { + } + else if (&Prop == &hole->BaseProfileType) { ui->BaseProfileType->setEnabled(true); - updateComboBox(ui->BaseProfileType, PartDesign::Hole::baseProfileOption_bitmaskToIdx(hole->BaseProfileType.getValue())); + updateComboBox( + ui->BaseProfileType, + PartDesign::Hole::baseProfileOption_bitmaskToIdx(hole->BaseProfileType.getValue()) + ); } } @@ -927,10 +963,12 @@ void TaskHoleParameters::updateHoleTypeCombo() if (hole->Threaded.getValue()) { if (hole->ModelThread.getValue()) { ui->HoleType->setCurrentIndex(ModeledThread); - } else { + } + else { ui->HoleType->setCurrentIndex(TapDrill); } - } else { + } + else { ui->HoleType->setCurrentIndex(Clearance); } } @@ -1110,8 +1148,7 @@ void TaskHoleParameters::apply() FCMD_OBJ_CMD(hole, "ThreadDepth = " << getThreadDepth()); } if (!hole->UseCustomThreadClearance.isReadOnly()) { - FCMD_OBJ_CMD(hole, - "UseCustomThreadClearance = " << (getUseCustomThreadClearance() ? 1 : 0)); + FCMD_OBJ_CMD(hole, "UseCustomThreadClearance = " << (getUseCustomThreadClearance() ? 1 : 0)); } if (!hole->CustomThreadClearance.isReadOnly()) { FCMD_OBJ_CMD(hole, "CustomThreadClearance = " << getCustomThreadClearance()); @@ -1174,16 +1211,19 @@ void TaskHoleParameters::setupGizmos(ViewProviderHole* vp) setGizmoPositions(); } -std::vector getHolePositionFromShape(const Part::TopoShape& profileshape, const long baseProfileType) +std::vector getHolePositionFromShape( + const Part::TopoShape& profileshape, + const long baseProfileType +) { - using BaseProfileTypeOptions=PartDesign::Hole::BaseProfileTypeOptions; + using BaseProfileTypeOptions = PartDesign::Hole::BaseProfileTypeOptions; std::vector positions; // Iterate over edges and filter out non-circle/non-arc types - if (baseProfileType & BaseProfileTypeOptions::OnCircles || - baseProfileType & BaseProfileTypeOptions::OnArcs) { - for (const auto &profileEdge : profileshape.getSubTopoShapes(TopAbs_EDGE)) { + if (baseProfileType & BaseProfileTypeOptions::OnCircles + || baseProfileType & BaseProfileTypeOptions::OnArcs) { + for (const auto& profileEdge : profileshape.getSubTopoShapes(TopAbs_EDGE)) { TopoDS_Edge edge = TopoDS::Edge(profileEdge.getShape()); BRepAdaptor_Curve adaptor(edge); @@ -1202,9 +1242,7 @@ std::vector getHolePositionFromShape(const Part::TopoShape& prof } gp_Circ circle = adaptor.Circle(); - positions.push_back( - Base::convertTo(circle.Axis().Location()) - ); + positions.push_back(Base::convertTo(circle.Axis().Location())); } } @@ -1212,11 +1250,9 @@ std::vector getHolePositionFromShape(const Part::TopoShape& prof // holes on points if (baseProfileType & BaseProfileTypeOptions::OnPoints) { // Iterate over vertices while avoiding edges so that curve handles are ignored - for (const auto &profileVertex : profileshape.getSubTopoShapes(TopAbs_VERTEX, TopAbs_EDGE)) { + for (const auto& profileVertex : profileshape.getSubTopoShapes(TopAbs_VERTEX, TopAbs_EDGE)) { TopoDS_Vertex vertex = TopoDS::Vertex(profileVertex.getShape()); - positions.push_back( - Base::convertTo(BRep_Tool::Pnt(vertex)) - ); + positions.push_back(Base::convertTo(BRep_Tool::Pnt(vertex))); } } @@ -1235,14 +1271,13 @@ void TaskHoleParameters::setGizmoPositions() return; } Part::TopoShape profileShape = hole->getProfileShape( - Part::ShapeOption::NeedSubElement | - Part::ShapeOption::ResolveLink | - Part::ShapeOption::Transform | - Part::ShapeOption::DontSimplifyCompound + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform | Part::ShapeOption::DontSimplifyCompound ); Base::Vector3d dir = hole->guessNormalDirection(profileShape); - dir *= hole->Reversed.getValue()? -1 : 1; - std::vector holePositions = getHolePositionFromShape(profileShape, hole->BaseProfileType.getValue()); + dir *= hole->Reversed.getValue() ? -1 : 1; + std::vector holePositions + = getHolePositionFromShape(profileShape, hole->BaseProfileType.getValue()); if (holePositions.size() == 0) { gizmoContainer->visible = false; @@ -1250,10 +1285,11 @@ void TaskHoleParameters::setGizmoPositions() } gizmoContainer->visible = true; - holeDepthGizmo->Gizmo::setDraggerPlacement(holePositions[0] - ui->HoleCutDepth->value().getValue() * dir, -dir); - holeDepthGizmo->setVisibility( - std::string(hole->DepthType.getValueAsString()) == "Dimension" + holeDepthGizmo->Gizmo::setDraggerPlacement( + holePositions[0] - ui->HoleCutDepth->value().getValue() * dir, + -dir ); + holeDepthGizmo->setVisibility(std::string(hole->DepthType.getValueAsString()) == "Dimension"); holeDepthGizmo->setDragLength(ui->Depth->rawValue()); } @@ -1284,8 +1320,10 @@ TaskHoleParameters::Observer::Observer(TaskHoleParameters* _owner, PartDesign::H , hole(_hole) {} -void TaskHoleParameters::Observer::slotChangedObject(const App::DocumentObject& Obj, - const App::Property& Prop) +void TaskHoleParameters::Observer::slotChangedObject( + const App::DocumentObject& Obj, + const App::Property& Prop +) { if (&Obj == hole) { Base::Console().log("Parameter %s was updated with a new value\n", Prop.getName()); diff --git a/src/Mod/PartDesign/Gui/TaskHoleParameters.h b/src/Mod/PartDesign/Gui/TaskHoleParameters.h index 2e54089110..cf1b4183cc 100644 --- a/src/Mod/PartDesign/Gui/TaskHoleParameters.h +++ b/src/Mod/PartDesign/Gui/TaskHoleParameters.h @@ -29,52 +29,55 @@ class Ui_TaskHoleParameters; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class LinearGizmo; class GizmoContainer; class ViewProvider; -} +} // namespace Gui -namespace PartDesign { +namespace PartDesign +{ class Hole; } -namespace PartDesignGui { +namespace PartDesignGui +{ - -class TaskHoleParameters : public TaskSketchBasedParameters +class TaskHoleParameters: public TaskSketchBasedParameters { Q_OBJECT public: - explicit TaskHoleParameters(ViewProviderHole *HoleView, QWidget *parent = nullptr); + explicit TaskHoleParameters(ViewProviderHole* HoleView, QWidget* parent = nullptr); ~TaskHoleParameters() override; void apply() override; - bool getThreaded() const; - long getThreadType() const; - long getThreadSize() const; - long getThreadClass() const; - long getThreadFit() const; + bool getThreaded() const; + long getThreadType() const; + long getThreadSize() const; + long getThreadClass() const; + long getThreadFit() const; Base::Quantity getDiameter() const; - long getThreadDirection() const; - long getHoleCutType() const; - bool getHoleCutCustomValues() const; + long getThreadDirection() const; + long getHoleCutType() const; + bool getHoleCutCustomValues() const; Base::Quantity getHoleCutDiameter() const; Base::Quantity getHoleCutDepth() const; Base::Quantity getHoleCutCountersinkAngle() const; - long getDepthType() const; + long getDepthType() const; Base::Quantity getDepth() const; - long getDrillPoint() const; + long getDrillPoint() const; Base::Quantity getDrillPointAngle() const; - bool getDrillForDepth() const; - bool getTapered() const; + bool getDrillForDepth() const; + bool getTapered() const; Base::Quantity getTaperedAngle() const; bool getUseCustomThreadClearance() const; double getCustomThreadClearance() const; @@ -114,31 +117,33 @@ private Q_SLOTS: void setCutDiagram(); private: - class Observer : public App::DocumentObserver { + class Observer: public App::DocumentObserver + { public: - Observer(TaskHoleParameters * _owner, PartDesign::Hole * _hole); + Observer(TaskHoleParameters* _owner, PartDesign::Hole* _hole); + private: void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) override; - TaskHoleParameters * owner; - PartDesign::Hole * hole; + TaskHoleParameters* owner; + PartDesign::Hole* hole; }; - enum HoleTypeIndex : int { + enum HoleTypeIndex : int + { Clearance = 0, TapDrill = 1, ModeledThread = 2 }; protected: - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; void changedObject(const App::Document&, const App::Property& Prop); private: - void onSelectionChanged(const Gui::SelectionChanges &msg) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void updateHoleCutLimits(PartDesign::Hole* hole); void updateHoleTypeCombo(); private: - using Connection = boost::signals2::scoped_connection; Connection connectPropChanged; @@ -153,18 +158,18 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgHoleParameters : public TaskDlgSketchBasedParameters +class TaskDlgHoleParameters: public TaskDlgSketchBasedParameters { Q_OBJECT public: - explicit TaskDlgHoleParameters(ViewProviderHole *HoleView); + explicit TaskDlgHoleParameters(ViewProviderHole* HoleView); ~TaskDlgHoleParameters() override; protected: - TaskHoleParameters *parameter; + TaskHoleParameters* parameter; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp b/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp index 2a15021ab7..7e95f0069c 100644 --- a/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include @@ -79,10 +78,12 @@ TaskLoftParameters::TaskLoftParameters(ViewProviderLoft* LoftView, bool /*newObj ui->listWidgetReferences->setContextMenuPolicy(Qt::ActionsContextMenu); connect(remove, &QAction::triggered, this, &TaskLoftParameters::onDeleteSection); - connect(ui->listWidgetReferences->model(), - &QAbstractListModel::rowsMoved, - this, - &TaskLoftParameters::indexesMoved); + connect( + ui->listWidgetReferences->model(), + &QAbstractListModel::rowsMoved, + this, + &TaskLoftParameters::indexesMoved + ); this->groupLayout()->addWidget(proxy); @@ -161,7 +162,9 @@ void TaskLoftParameters::onSelectionChanged(const Gui::SelectionChanges& msg) item->setData( Qt::UserRole, QVariant::fromValue( - std::make_pair(object, std::vector(1, msg.pSubName)))); + std::make_pair(object, std::vector(1, msg.pSubName)) + ) + ); ui->listWidgetReferences->addItem(item); } else if (selectionMode == refRemove) { @@ -254,9 +257,9 @@ void TaskLoftParameters::onDeleteSection() int row = ui->listWidgetReferences->currentRow(); QListWidgetItem* item = ui->listWidgetReferences->takeItem(row); if (item) { - QByteArray data(item->data(Qt::UserRole) - .value() - .first->getNameInDocument()); + QByteArray data( + item->data(Qt::UserRole).value().first->getNameInDocument() + ); delete item; // search inside the list of sections diff --git a/src/Mod/PartDesign/Gui/TaskLoftParameters.h b/src/Mod/PartDesign/Gui/TaskLoftParameters.h index a14bcf2e9f..8df669b2ba 100644 --- a/src/Mod/PartDesign/Gui/TaskLoftParameters.h +++ b/src/Mod/PartDesign/Gui/TaskLoftParameters.h @@ -30,23 +30,30 @@ class Ui_TaskLoftParameters; class QListWidget; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskLoftParameters : public TaskSketchBasedParameters +class TaskLoftParameters: public TaskSketchBasedParameters { Q_OBJECT public: - explicit TaskLoftParameters(ViewProviderLoft *LoftView, bool newObj=false, QWidget *parent = nullptr); + explicit TaskLoftParameters( + ViewProviderLoft* LoftView, + bool newObj = false, + QWidget* parent = nullptr + ); ~TaskLoftParameters() override; private Q_SLOTS: @@ -59,16 +66,22 @@ private Q_SLOTS: void indexesMoved(); protected: - enum selectionModes { none, refAdd, refRemove, refProfile }; + enum selectionModes + { + none, + refAdd, + refRemove, + refProfile + }; - void changeEvent(QEvent *e) override; + void changeEvent(QEvent* e) override; private: void onSelectionChanged(const Gui::SelectionChanges& msg) override; void updateUI(); bool referenceSelected(const Gui::SelectionChanges& msg) const; - void removeFromListWidget(QListWidget*w, QString name); - void clearButtons(const selectionModes notThis=none); + void removeFromListWidget(QListWidget* w, QString name); + void clearButtons(const selectionModes notThis = none); void exitSelectionMode(); void setSelectionMode(selectionModes mode, bool checked); @@ -80,21 +93,21 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgLoftParameters : public TaskDlgSketchBasedParameters +class TaskDlgLoftParameters: public TaskDlgSketchBasedParameters { Q_OBJECT public: - explicit TaskDlgLoftParameters(ViewProviderLoft *LoftView,bool newObj=false); + explicit TaskDlgLoftParameters(ViewProviderLoft* LoftView, bool newObj = false); ~TaskDlgLoftParameters() override; /// is called by the framework if the dialog is accepted (Ok) bool accept() override; protected: - TaskLoftParameters *parameter; + TaskLoftParameters* parameter; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp b/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp index 9ec9740d86..5e9eea75e1 100644 --- a/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp @@ -21,7 +21,6 @@ ******************************************************************************/ - #include @@ -46,16 +45,17 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskMirroredParameters */ -TaskMirroredParameters::TaskMirroredParameters(ViewProviderTransformed* TransformedView, - QWidget* parent) +TaskMirroredParameters::TaskMirroredParameters(ViewProviderTransformed* TransformedView, QWidget* parent) : TaskTransformedParameters(TransformedView, parent) , ui(new Ui_TaskMirroredParameters) { setupUI(); } -TaskMirroredParameters::TaskMirroredParameters(TaskMultiTransformParameters* parentTask, - QWidget* parameterWidget) +TaskMirroredParameters::TaskMirroredParameters( + TaskMultiTransformParameters* parentTask, + QWidget* parameterWidget +) : TaskTransformedParameters(parentTask) , ui(new Ui_TaskMirroredParameters) { @@ -67,10 +67,12 @@ void TaskMirroredParameters::setupParameterUI(QWidget* widget) ui->setupUi(widget); QMetaObject::connectSlotsByName(this); - connect(ui->comboPlane, - qOverload(&QComboBox::activated), - this, - &TaskMirroredParameters::onPlaneChanged); + connect( + ui->comboPlane, + qOverload(&QComboBox::activated), + this, + &TaskMirroredParameters::onPlaneChanged + ); this->planeLinks.setCombo(ui->comboPlane); ui->comboPlane->setEnabled(true); @@ -89,7 +91,8 @@ void TaskMirroredParameters::setupParameterUI(QWidget* widget) try { App::Origin* origin = body->getOrigin(); auto vpOrigin = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); vpOrigin->setTemporaryVisibility(Gui::DatumElement::Planes); } catch (const Base::Exception& ex) { @@ -118,7 +121,8 @@ void TaskMirroredParameters::updateUI() // failed to set current, because the link isn't in the list yet planeLinks.addLink( pcMirrored->MirrorPlane, - getRefStr(pcMirrored->MirrorPlane.getValue(), pcMirrored->MirrorPlane.getSubValues())); + getRefStr(pcMirrored->MirrorPlane.getValue(), pcMirrored->MirrorPlane.getSubValues()) + ); planeLinks.setCurrentLink(pcMirrored->MirrorPlane); } @@ -200,8 +204,7 @@ void TaskMirroredParameters::onUpdateView(bool on) } } -void TaskMirroredParameters::getMirrorPlane(App::DocumentObject*& obj, - std::vector& sub) const +void TaskMirroredParameters::getMirrorPlane(App::DocumentObject*& obj, std::vector& sub) const { const App::PropertyLinkSub& lnk = planeLinks.getCurrentLink(); obj = lnk.getValue(); @@ -226,7 +229,8 @@ TaskMirroredParameters::~TaskMirroredParameters() if (body) { App::Origin* origin = body->getOrigin(); auto vpOrigin = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); vpOrigin->resetTemporaryVisibility(); } } diff --git a/src/Mod/PartDesign/Gui/TaskMirroredParameters.h b/src/Mod/PartDesign/Gui/TaskMirroredParameters.h index 78f2dade02..b832d8ad37 100644 --- a/src/Mod/PartDesign/Gui/TaskMirroredParameters.h +++ b/src/Mod/PartDesign/Gui/TaskMirroredParameters.h @@ -50,8 +50,7 @@ class TaskMirroredParameters: public TaskTransformedParameters public: /// Constructor for task with ViewProvider - explicit TaskMirroredParameters(ViewProviderTransformed* TransformedView, - QWidget* parent = nullptr); + explicit TaskMirroredParameters(ViewProviderTransformed* TransformedView, QWidget* parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskMirroredParameters(TaskMultiTransformParameters* parentTask, QWidget* parameterWidget); diff --git a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp index 22d1048e66..dbbeeba79c 100644 --- a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp @@ -21,7 +21,6 @@ ******************************************************************************/ - #include @@ -51,8 +50,10 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskMultiTransformParameters */ -TaskMultiTransformParameters::TaskMultiTransformParameters(ViewProviderTransformed* TransformedView, - QWidget* parent) +TaskMultiTransformParameters::TaskMultiTransformParameters( + ViewProviderTransformed* TransformedView, + QWidget* parent +) : TaskTransformedParameters(TransformedView, parent) , ui(new Ui_TaskMultiTransformParameters) { @@ -66,40 +67,37 @@ void TaskMultiTransformParameters::setupParameterUI(QWidget* widget) // Create a context menu for the listview of transformation features auto action = new QAction(tr("Edit"), ui->listTransformFeatures); - action->connect(action, - &QAction::triggered, - this, - &TaskMultiTransformParameters::onTransformEdit); + action->connect(action, &QAction::triggered, this, &TaskMultiTransformParameters::onTransformEdit); ui->listTransformFeatures->addAction(action); action = new QAction(tr("Delete"), ui->listTransformFeatures); - action->connect(action, - &QAction::triggered, - this, - &TaskMultiTransformParameters::onTransformDelete); + action->connect(action, &QAction::triggered, this, &TaskMultiTransformParameters::onTransformDelete); ui->listTransformFeatures->addAction(action); action = new QAction(tr("Add Mirror Transformation"), ui->listTransformFeatures); - action->connect(action, - &QAction::triggered, - this, - &TaskMultiTransformParameters::onTransformAddMirrored); + action->connect( + action, + &QAction::triggered, + this, + &TaskMultiTransformParameters::onTransformAddMirrored + ); ui->listTransformFeatures->addAction(action); action = new QAction(tr("Add Linear Pattern"), ui->listTransformFeatures); - action->connect(action, - &QAction::triggered, - this, - &TaskMultiTransformParameters::onTransformAddLinearPattern); + action->connect( + action, + &QAction::triggered, + this, + &TaskMultiTransformParameters::onTransformAddLinearPattern + ); ui->listTransformFeatures->addAction(action); action = new QAction(tr("Add Polar Pattern"), ui->listTransformFeatures); - action->connect(action, - &QAction::triggered, - this, - &TaskMultiTransformParameters::onTransformAddPolarPattern); + action->connect( + action, + &QAction::triggered, + this, + &TaskMultiTransformParameters::onTransformAddPolarPattern + ); ui->listTransformFeatures->addAction(action); action = new QAction(tr("Add Scale Transformation"), ui->listTransformFeatures); - action->connect(action, - &QAction::triggered, - this, - &TaskMultiTransformParameters::onTransformAddScaled); + action->connect(action, &QAction::triggered, this, &TaskMultiTransformParameters::onTransformAddScaled); ui->listTransformFeatures->addAction(action); action = new QAction(tr("Move Up"), ui->listTransformFeatures); action->connect(action, &QAction::triggered, this, &TaskMultiTransformParameters::onMoveUp); @@ -109,21 +107,19 @@ void TaskMultiTransformParameters::setupParameterUI(QWidget* widget) ui->listTransformFeatures->addAction(action); ui->listTransformFeatures->setContextMenuPolicy(Qt::ActionsContextMenu); - connect(ui->listTransformFeatures, - &QListWidget::activated, - this, - &TaskMultiTransformParameters::onTransformActivated); + connect( + ui->listTransformFeatures, + &QListWidget::activated, + this, + &TaskMultiTransformParameters::onTransformActivated + ); - connect(ui->buttonOK, - &QToolButton::pressed, - this, - &TaskMultiTransformParameters::onSubTaskButtonOK); + connect(ui->buttonOK, &QToolButton::pressed, this, &TaskMultiTransformParameters::onSubTaskButtonOK); ui->buttonOK->hide(); // Get the transformFeatures data auto pcMultiTransform = TransformedView->getObject(); - std::vector transformFeatures = - pcMultiTransform->Transformations.getValues(); + std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); // Fill data into dialog elements ui->listTransformFeatures->setEnabled(true); @@ -173,10 +169,8 @@ void TaskMultiTransformParameters::closeSubTask() // Remove all parameter ui widgets and layout ui->subFeatureWidget->setUpdatesEnabled(false); - qDeleteAll( - ui->subFeatureWidget->findChildren(QString(), Qt::FindDirectChildrenOnly)); - qDeleteAll( - ui->subFeatureWidget->findChildren(QString(), Qt::FindDirectChildrenOnly)); + qDeleteAll(ui->subFeatureWidget->findChildren(QString(), Qt::FindDirectChildrenOnly)); + qDeleteAll(ui->subFeatureWidget->findChildren(QString(), Qt::FindDirectChildrenOnly)); ui->subFeatureWidget->setUpdatesEnabled(true); } } @@ -188,8 +182,7 @@ void TaskMultiTransformParameters::onTransformDelete() } int row = ui->listTransformFeatures->currentIndex().row(); auto pcMultiTransform = TransformedView->getObject(); - std::vector transformFeatures = - pcMultiTransform->Transformations.getValues(); + std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); App::DocumentObject* feature = transformFeatures[row]; if (feature == this->subFeature) { @@ -220,15 +213,14 @@ void TaskMultiTransformParameters::onTransformEdit() ui->listTransformFeatures->currentItem()->setSelected(true); int row = ui->listTransformFeatures->currentIndex().row(); auto pcMultiTransform = TransformedView->getObject(); - std::vector transformFeatures = - pcMultiTransform->Transformations.getValues(); + std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); subFeature = static_cast(transformFeatures[row]); if (subFeature->is()) { subTask = new TaskMirroredParameters(this, ui->subFeatureWidget); } else if (subFeature->is() - || subFeature->is()) { + || subFeature->is()) { subTask = new TaskPatternParameters(this, ui->subFeatureWidget); } else if (subFeature->is()) { @@ -252,8 +244,12 @@ void TaskMultiTransformParameters::onTransformActivated(const QModelIndex& index void TaskMultiTransformParameters::onTransformAddMirrored() { closeSubTask(); - std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName("Mirror"); - auto pcBody = dynamic_cast(Part::BodyBase::findBodyOf(getTopTransformedObject())); + std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName( + "Mirror" + ); + auto pcBody = dynamic_cast( + Part::BodyBase::findBodyOf(getTopTransformedObject()) + ); if (!pcBody) { return; } @@ -262,7 +258,7 @@ void TaskMultiTransformParameters::onTransformAddMirrored() Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Mirror")); } - FCMD_OBJ_CMD(pcBody, "newObject('PartDesign::Mirrored','"<getDocument()->getObject(newFeatName.c_str()); if (!Feat) { return; @@ -270,12 +266,11 @@ void TaskMultiTransformParameters::onTransformAddMirrored() // Gui::Command::updateActive(); App::DocumentObject* sketch = getSketchObject(); if (sketch) { - FCMD_OBJ_CMD(Feat, - "MirrorPlane = (" << Gui::Command::getObjectCmd(sketch) << ",['V_Axis'])"); + FCMD_OBJ_CMD(Feat, "MirrorPlane = (" << Gui::Command::getObjectCmd(sketch) << ",['V_Axis'])"); } else { App::Origin* orig = pcBody->getOrigin(); - FCMD_OBJ_CMD(Feat, "MirrorPlane = ("<getXY())<<",[''])"); + FCMD_OBJ_CMD(Feat, "MirrorPlane = (" << Gui::Command::getObjectCmd(orig->getXY()) << ",[''])"); } finishAdd(newFeatName); // show the new view when no error @@ -289,8 +284,12 @@ void TaskMultiTransformParameters::onTransformAddLinearPattern() // See CmdPartDesignLinearPattern // closeSubTask(); - std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName("Linear Pattern"); - auto pcBody = dynamic_cast(Part::BodyBase::findBodyOf(getTopTransformedObject())); + std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName( + "Linear Pattern" + ); + auto pcBody = dynamic_cast( + Part::BodyBase::findBodyOf(getTopTransformedObject()) + ); if (!pcBody) { return; } @@ -299,7 +298,7 @@ void TaskMultiTransformParameters::onTransformAddLinearPattern() Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Linear Pattern")); } - FCMD_OBJ_CMD(pcBody, "newObject('PartDesign::LinearPattern','"<getDocument()->getObject(newFeatName.c_str()); if (!Feat) { return; @@ -314,9 +313,10 @@ void TaskMultiTransformParameters::onTransformAddLinearPattern() // inside updateUI() auto body = dynamic_cast(Part::BodyBase::findBodyOf(getObject())); if (body) { - FCMD_OBJ_CMD(Feat, - "Direction = (" << Gui::Command::getObjectCmd(body->getOrigin()->getX()) - << ",[''])"); + FCMD_OBJ_CMD( + Feat, + "Direction = (" << Gui::Command::getObjectCmd(body->getOrigin()->getX()) << ",[''])" + ); } } @@ -333,8 +333,12 @@ void TaskMultiTransformParameters::onTransformAddLinearPattern() void TaskMultiTransformParameters::onTransformAddPolarPattern() { closeSubTask(); - std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName("Polar Pattern"); - auto pcBody = dynamic_cast(Part::BodyBase::findBodyOf(getTopTransformedObject())); + std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName( + "Polar Pattern" + ); + auto pcBody = dynamic_cast( + Part::BodyBase::findBodyOf(getTopTransformedObject()) + ); if (!pcBody) { return; } @@ -343,7 +347,7 @@ void TaskMultiTransformParameters::onTransformAddPolarPattern() Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Polar Pattern")); } - FCMD_OBJ_CMD(pcBody, "newObject('PartDesign::PolarPattern','"<getDocument()->getObject(newFeatName.c_str()); if (!Feat) { return; @@ -355,7 +359,7 @@ void TaskMultiTransformParameters::onTransformAddPolarPattern() } else { App::Origin* orig = pcBody->getOrigin(); - FCMD_OBJ_CMD(Feat, "Axis = ("<getX())<<",[''])"); + FCMD_OBJ_CMD(Feat, "Axis = (" << Gui::Command::getObjectCmd(orig->getX()) << ",[''])"); } FCMD_OBJ_CMD(Feat, "Angle = 360"); FCMD_OBJ_CMD(Feat, "Occurrences = 2"); @@ -371,7 +375,9 @@ void TaskMultiTransformParameters::onTransformAddScaled() { closeSubTask(); std::string newFeatName = TransformedView->getObject()->getDocument()->getUniqueObjectName("Scale"); - auto pcBody = dynamic_cast(Part::BodyBase::findBodyOf(getTopTransformedObject())); + auto pcBody = dynamic_cast( + Part::BodyBase::findBodyOf(getTopTransformedObject()) + ); if (!pcBody) { return; } @@ -380,7 +386,7 @@ void TaskMultiTransformParameters::onTransformAddScaled() Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Scale")); } - FCMD_OBJ_CMD(pcBody, "newObject('PartDesign::Scaled','"<getDocument()->getObject(newFeatName.c_str()); if (!Feat) { return; @@ -421,10 +427,8 @@ void TaskMultiTransformParameters::finishAdd(std::string& newFeatName) // Insert new transformation after the selected row // This means that in order to insert at the beginning, the user has to use "Move Up" in the // menu - App::DocumentObject* newFeature = - pcMultiTransform->getDocument()->getObject(newFeatName.c_str()); - std::vector transformFeatures = - pcMultiTransform->Transformations.getValues(); + App::DocumentObject* newFeature = pcMultiTransform->getDocument()->getObject(newFeatName.c_str()); + std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); if (row == ui->listTransformFeatures->model()->rowCount() - 1) { // Note: Inserts always happen before the specified iterator so in order to append at the // end we need to use push_back() and append() @@ -435,8 +439,10 @@ void TaskMultiTransformParameters::finishAdd(std::string& newFeatName) else { // Note: The feature tree always seems to append to the end, no matter what we say here transformFeatures.insert(transformFeatures.begin() + row + 1, newFeature); - ui->listTransformFeatures->insertItem(row + 1, - QString::fromLatin1(newFeature->Label.getValue())); + ui->listTransformFeatures->insertItem( + row + 1, + QString::fromLatin1(newFeature->Label.getValue()) + ); ui->listTransformFeatures->setCurrentRow(row + 1, QItemSelectionModel::ClearAndSelect); } pcMultiTransform->Transformations.setValues(transformFeatures); @@ -455,8 +461,7 @@ void TaskMultiTransformParameters::moveTransformFeature(const int increment) setupTransaction(); int row = ui->listTransformFeatures->currentIndex().row(); auto pcMultiTransform = TransformedView->getObject(); - std::vector transformFeatures = - pcMultiTransform->Transformations.getValues(); + std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); if (transformFeatures.empty()) { return; @@ -517,8 +522,7 @@ void TaskMultiTransformParameters::onUpdateView(bool on) void TaskMultiTransformParameters::apply() { auto pcMultiTransform = getObject(); - std::vector transformFeatures = - pcMultiTransform->Transformations.getValues(); + std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); std::stringstream str; str << Gui::Command::getObjectCmd(TransformedView->getObject()) << ".Transformations = ["; for (auto it : transformFeatures) { @@ -547,7 +551,8 @@ TaskMultiTransformParameters::~TaskMultiTransformParameters() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskDlgMultiTransformParameters::TaskDlgMultiTransformParameters( - ViewProviderMultiTransform* MultiTransformView) + ViewProviderMultiTransform* MultiTransformView +) : TaskDlgTransformedParameters(MultiTransformView) { parameter = new TaskMultiTransformParameters(MultiTransformView); diff --git a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h index 794d731a0f..b088b2e781 100644 --- a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h +++ b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h @@ -54,8 +54,10 @@ class TaskMultiTransformParameters: public TaskTransformedParameters Q_OBJECT public: - explicit TaskMultiTransformParameters(ViewProviderTransformed* TransformedView, - QWidget* parent = nullptr); + explicit TaskMultiTransformParameters( + ViewProviderTransformed* TransformedView, + QWidget* parent = nullptr + ); ~TaskMultiTransformParameters() override; void apply() override; diff --git a/src/Mod/PartDesign/Gui/TaskPadParameters.cpp b/src/Mod/PartDesign/Gui/TaskPadParameters.cpp index 14c8f56ea3..b2811b6e06 100644 --- a/src/Mod/PartDesign/Gui/TaskPadParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPadParameters.cpp @@ -20,7 +20,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -34,7 +34,7 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskPadParameters */ -TaskPadParameters::TaskPadParameters(ViewProviderPad *PadView, QWidget *parent, bool newObj) +TaskPadParameters::TaskPadParameters(ViewProviderPad* PadView, QWidget* parent, bool newObj) : TaskExtrudeParameters(PadView, parent, "PartDesign_Pad", tr("Pad Parameters")) { ui->offsetEdit->setToolTip(tr("Offset the pad from the face at which the pad will end on side 1")); @@ -136,8 +136,9 @@ void TaskPadParameters::apply() // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgPadParameters::TaskDlgPadParameters(ViewProviderPad *PadView, bool /*newObj*/) - : TaskDlgExtrudeParameters(PadView), parameters(new TaskPadParameters(PadView)) +TaskDlgPadParameters::TaskDlgPadParameters(ViewProviderPad* PadView, bool /*newObj*/) + : TaskDlgExtrudeParameters(PadView) + , parameters(new TaskPadParameters(PadView)) { Content.push_back(parameters); Content.push_back(preview); diff --git a/src/Mod/PartDesign/Gui/TaskPadParameters.h b/src/Mod/PartDesign/Gui/TaskPadParameters.h index 4f19ba628f..63c2300eb5 100644 --- a/src/Mod/PartDesign/Gui/TaskPadParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPadParameters.h @@ -28,23 +28,26 @@ class QComboBox; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskPadParameters : public TaskExtrudeParameters +class TaskPadParameters: public TaskExtrudeParameters { Q_OBJECT public: - explicit TaskPadParameters(ViewProviderPad *PadView, QWidget *parent = nullptr, bool newObj=false); + explicit TaskPadParameters(ViewProviderPad* PadView, QWidget* parent = nullptr, bool newObj = false); ~TaskPadParameters() override; void apply() override; @@ -56,12 +59,12 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgPadParameters : public TaskDlgExtrudeParameters +class TaskDlgPadParameters: public TaskDlgExtrudeParameters { Q_OBJECT public: - explicit TaskDlgPadParameters(ViewProviderPad *PadView, bool newObj=false); + explicit TaskDlgPadParameters(ViewProviderPad* PadView, bool newObj = false); protected: TaskExtrudeParameters* getTaskParameters() override @@ -73,6 +76,6 @@ private: TaskPadParameters* parameters; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskPatternParameters.cpp b/src/Mod/PartDesign/Gui/TaskPatternParameters.cpp index 7e24ab8cfa..3c656480db 100644 --- a/src/Mod/PartDesign/Gui/TaskPatternParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPatternParameters.cpp @@ -52,16 +52,17 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskPatternParameters */ -TaskPatternParameters::TaskPatternParameters(ViewProviderTransformed* TransformedView, - QWidget* parent) +TaskPatternParameters::TaskPatternParameters(ViewProviderTransformed* TransformedView, QWidget* parent) : TaskTransformedParameters(TransformedView, parent) , ui(new Ui_TaskPatternParameters) { setupUI(); } -TaskPatternParameters::TaskPatternParameters(TaskMultiTransformParameters* parentTask, - QWidget* parameterWidget) +TaskPatternParameters::TaskPatternParameters( + TaskMultiTransformParameters* parentTask, + QWidget* parameterWidget +) : TaskTransformedParameters(parentTask) , ui(new Ui::TaskPatternParameters) { @@ -70,7 +71,7 @@ TaskPatternParameters::TaskPatternParameters(TaskMultiTransformParameters* paren void TaskPatternParameters::setupParameterUI(QWidget* widget) { - ui->setupUi(widget); // Setup the Task's own minimal UI (placeholder) + ui->setupUi(widget); // Setup the Task's own minimal UI (placeholder) QMetaObject::connectSlotsByName(this); // --- Create and Embed the Parameter Widget --- @@ -78,8 +79,9 @@ void TaskPatternParameters::setupParameterUI(QWidget* widget) if (!pattern) { return; } - PartGui::PatternType type = pattern->isDerivedFrom() ? - PartGui::PatternType::Linear : PartGui::PatternType::Polar; + PartGui::PatternType type = pattern->isDerivedFrom() + ? PartGui::PatternType::Linear + : PartGui::PatternType::Polar; // Set first direction widget parametersWidget = new PartGui::PatternParametersWidget(type, widget); @@ -91,10 +93,18 @@ void TaskPatternParameters::setupParameterUI(QWidget* widget) auto* sketch = dynamic_cast(getSketchObject()); this->fillAxisCombo(parametersWidget->dirLinks, sketch); - connect(parametersWidget, &PartGui::PatternParametersWidget::requestReferenceSelection, - this, &TaskPatternParameters::onParameterWidgetRequestReferenceSelection); - connect(parametersWidget, &PartGui::PatternParametersWidget::parametersChanged, - this, &TaskPatternParameters::onParameterWidgetParametersChanged); + connect( + parametersWidget, + &PartGui::PatternParametersWidget::requestReferenceSelection, + this, + &TaskPatternParameters::onParameterWidgetRequestReferenceSelection + ); + connect( + parametersWidget, + &PartGui::PatternParametersWidget::parametersChanged, + this, + &TaskPatternParameters::onParameterWidgetParametersChanged + ); // Add second direction widget if necessary if (type == PartGui::PatternType::Linear) { @@ -105,10 +115,18 @@ void TaskPatternParameters::setupParameterUI(QWidget* widget) ui->parametersWidgetPlaceholder2->setLayout(placeholderLayout2); this->fillAxisCombo(parametersWidget2->dirLinks, sketch); - connect(parametersWidget2, &PartGui::PatternParametersWidget::requestReferenceSelection, - this, &TaskPatternParameters::onParameterWidgetRequestReferenceSelection2); - connect(parametersWidget2, &PartGui::PatternParametersWidget::parametersChanged, - this, &TaskPatternParameters::onParameterWidgetParametersChanged); + connect( + parametersWidget2, + &PartGui::PatternParametersWidget::requestReferenceSelection, + this, + &TaskPatternParameters::onParameterWidgetRequestReferenceSelection2 + ); + connect( + parametersWidget2, + &PartGui::PatternParametersWidget::parametersChanged, + this, + &TaskPatternParameters::onParameterWidgetParametersChanged + ); parametersWidget2->setTitle(tr("Direction 2")); parametersWidget2->setCheckable(true); } @@ -116,7 +134,7 @@ void TaskPatternParameters::setupParameterUI(QWidget* widget) bindProperties(); // --- Task Specific Setup --- - showOriginAxes(true); // Show origin helper axes + showOriginAxes(true); // Show origin helper axes updateViewTimer = new QTimer(this); updateViewTimer->setSingleShot(true); @@ -133,36 +151,44 @@ void TaskPatternParameters::bindProperties() if (pattern->isDerivedFrom()) { auto* linear = static_cast(pattern); - parametersWidget->bindProperties(&linear->Direction, + parametersWidget->bindProperties( + &linear->Direction, &linear->Reversed, &linear->Mode, &linear->Length, &linear->Offset, &linear->SpacingPattern, &linear->Occurrences, - linear); - parametersWidget2->bindProperties(&linear->Direction2, + linear + ); + parametersWidget2->bindProperties( + &linear->Direction2, &linear->Reversed2, &linear->Mode2, &linear->Length2, &linear->Offset2, &linear->SpacingPattern2, &linear->Occurrences2, - linear); + linear + ); } else if (pattern->isDerivedFrom()) { auto* polar = static_cast(pattern); - parametersWidget->bindProperties(&polar->Axis, + parametersWidget->bindProperties( + &polar->Axis, &polar->Reversed, &polar->Mode, &polar->Angle, &polar->Offset, &polar->SpacingPattern, &polar->Occurrences, - polar); + polar + ); } - else{ - Base::Console().warning("PatternParametersWidget property binding failed. Something is wrong please report.\n"); + else { + Base::Console().warning( + "PatternParametersWidget property binding failed. Something is wrong please report.\n" + ); } } @@ -190,7 +216,8 @@ void TaskPatternParameters::showOriginAxes(bool show) try { App::Origin* origin = body->getOrigin(); auto vpOrigin = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); if (show) { vpOrigin->setTemporaryVisibility(Gui::DatumElement::Axes); } @@ -206,14 +233,18 @@ void TaskPatternParameters::showOriginAxes(bool show) void TaskPatternParameters::enterReferenceSelectionMode() { - if (selectionMode == SelectionMode::Reference) return; + if (selectionMode == SelectionMode::Reference) { + return; + } - hideObject(); // Hide the pattern feature itself - showBase(); // Show the base features/body + hideObject(); // Hide the pattern feature itself + showBase(); // Show the base features/body Gui::Selection().clearSelection(); // Add selection gate (allow edges, faces, potentially datums) addReferenceSelectionGate(AllowSelection::EDGE | AllowSelection::FACE | AllowSelection::PLANAR); - Gui::getMainWindow()->showMessage(tr("Select a direction reference (edge, face, datum line)")); // User feedback + Gui::getMainWindow()->showMessage( + tr("Select a direction reference (edge, face, datum line)") + ); // User feedback } void TaskPatternParameters::exitReferenceSelectionMode() @@ -231,7 +262,7 @@ void TaskPatternParameters::exitReferenceSelectionMode() void TaskPatternParameters::onUpdateViewTimer() { // Recompute is triggered when parameters change and this timer fires - setupTransaction(); // Group potential property changes + setupTransaction(); // Group potential property changes recomputeFeature(); updateUI(); @@ -256,8 +287,10 @@ void TaskPatternParameters::onParameterWidgetRequestReferenceSelection2() void TaskPatternParameters::onParameterWidgetParametersChanged() { // A parameter in the embedded widget changed, trigger a recompute - if (blockUpdate) return; // Avoid loops if change originated from Task update - kickUpdateViewTimer(); // Debounce recompute + if (blockUpdate) { + return; // Avoid loops if change originated from Task update + } + kickUpdateViewTimer(); // Debounce recompute } void TaskPatternParameters::onUpdateView(bool on) @@ -287,19 +320,22 @@ void TaskPatternParameters::onSelectionChanged(const Gui::SelectionChanges& msg) } auto patternObj = getObject(); - if (!patternObj) return; + if (!patternObj) { + return; + } std::vector directions; App::DocumentObject* selObj = nullptr; getReferencedSelection(patternObj, msg, selObj, directions); if (!selObj) { - Base::Console().warning(tr("Invalid selection. Select an edge, planar face, or datum line.").toStdString().c_str()); + Base::Console().warning( + tr("Invalid selection. Select an edge, planar face, or datum line.").toStdString().c_str() + ); return; } // Note: ReferenceSelection has already checked the selection for validity - if (selectionMode == SelectionMode::Reference - || selObj->isDerivedFrom()) { + if (selectionMode == SelectionMode::Reference || selObj->isDerivedFrom()) { setupTransaction(); if (patternObj->isDerivedFrom()) { @@ -311,7 +347,7 @@ void TaskPatternParameters::onSelectionChanged(const Gui::SelectionChanges& msg) linearPattern->Direction2.setValue(selObj, directions); } } - else if(patternObj->isDerivedFrom()) { + else if (patternObj->isDerivedFrom()) { auto* polarPattern = static_cast(patternObj); polarPattern->Axis.setValue(selObj, directions); } @@ -323,8 +359,8 @@ void TaskPatternParameters::onSelectionChanged(const Gui::SelectionChanges& msg) TaskPatternParameters::~TaskPatternParameters() { - showOriginAxes(false); // Clean up temporary visibility - exitReferenceSelectionMode(); // Ensure gates are removed etc. + showOriginAxes(false); // Clean up temporary visibility + exitReferenceSelectionMode(); // Ensure gates are removed etc. // ui unique_ptr handles deletion // parametersWidget is deleted by Qt parent mechanism if added to layout correctly } @@ -360,8 +396,7 @@ void TaskPatternParameters::apply() FCMD_OBJ_CMD(pattern, "Mode2 = " << parametersWidget2->getMode()); parametersWidget2->applyQuantitySpinboxes(); - FCMD_OBJ_CMD(pattern, - "SpacingPattern2 = " << parametersWidget2->getSpacingPatternsAsString()); + FCMD_OBJ_CMD(pattern, "SpacingPattern2 = " << parametersWidget2->getSpacingPatternsAsString()); } // The user may have changed a value and immediately hit 'OK' or Enter. @@ -379,8 +414,9 @@ void TaskPatternParameters::apply() //************************************************************************** TaskDlgLinearPatternParameters::TaskDlgLinearPatternParameters( - ViewProviderTransformed* LinearPatternView) - : TaskDlgTransformedParameters(LinearPatternView) // Use base class constructor + ViewProviderTransformed* LinearPatternView +) + : TaskDlgTransformedParameters(LinearPatternView) // Use base class constructor { // Create the specific parameter task panel parameter = new TaskPatternParameters(LinearPatternView); @@ -390,6 +426,3 @@ TaskDlgLinearPatternParameters::TaskDlgLinearPatternParameters( } #include "moc_TaskPatternParameters.cpp" - - - diff --git a/src/Mod/PartDesign/Gui/TaskPatternParameters.h b/src/Mod/PartDesign/Gui/TaskPatternParameters.h index 1c3424d851..edded92075 100644 --- a/src/Mod/PartDesign/Gui/TaskPatternParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPatternParameters.h @@ -1,4 +1,4 @@ - /****************************************************************************** +/****************************************************************************** * Copyright (c) 2012 Jan Rheinländer * * * * This file is part of the FreeCAD CAx development system. * @@ -30,8 +30,9 @@ class QTimer; class Ui_TaskPatternParameters; -namespace PartGui { - class PatternParametersWidget; +namespace PartGui +{ +class PatternParametersWidget; } namespace PartDesignGui @@ -39,14 +40,13 @@ namespace PartDesignGui class TaskMultiTransformParameters; -class TaskPatternParameters : public TaskTransformedParameters +class TaskPatternParameters: public TaskTransformedParameters { Q_OBJECT public: /// Constructor for task with ViewProvider - explicit TaskPatternParameters(ViewProviderTransformed* TransformedView, - QWidget* parent = nullptr); + explicit TaskPatternParameters(ViewProviderTransformed* TransformedView, QWidget* parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskPatternParameters(TaskMultiTransformParameters* parentTask, QWidget* parameterWidget); ~TaskPatternParameters() override; @@ -79,7 +79,7 @@ private: // Task-specific logic remains void showOriginAxes(bool show); void enterReferenceSelectionMode(); - void exitReferenceSelectionMode(); // Ensure this clears gates etc. + void exitReferenceSelectionMode(); // Ensure this clears gates etc. PartGui::PatternParametersWidget* parametersWidget = nullptr; PartGui::PatternParametersWidget* parametersWidget2 = nullptr; @@ -92,7 +92,7 @@ private: /// simulation dialog for the TaskView -class TaskDlgLinearPatternParameters : public TaskDlgTransformedParameters +class TaskDlgLinearPatternParameters: public TaskDlgTransformedParameters { Q_OBJECT @@ -102,5 +102,4 @@ public: } // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskPatternParameters_H - +#endif // GUI_TASKVIEW_TaskPatternParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp b/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp index e1d124549f..61cb734bcf 100644 --- a/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp @@ -74,14 +74,13 @@ TaskPipeParameters::TaskPipeParameters(ViewProviderPipe* PipeView, bool /*newObj QMetaObject::connectSlotsByName(this); // some buttons are handled in a buttongroup - connect(ui->buttonProfileBase, - &QToolButton::toggled, - this, - &TaskPipeParameters::onProfileButton); - connect(ui->comboBoxTransition, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPipeParameters::onTransitionChanged); + connect(ui->buttonProfileBase, &QToolButton::toggled, this, &TaskPipeParameters::onProfileButton); + connect( + ui->comboBoxTransition, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPipeParameters::onTransitionChanged + ); // Create context menu QAction* remove = new QAction(tr("Remove"), this); @@ -89,7 +88,7 @@ TaskPipeParameters::TaskPipeParameters(ViewProviderPipe* PipeView, bool /*newObj remove->setShortcutContext(Qt::WidgetShortcut); // display shortcut behind the context menu entry - remove->setShortcutVisibleInContextMenu(true); + remove->setShortcutVisibleInContextMenu(true); ui->listWidgetReferences->addAction(remove); @@ -116,7 +115,8 @@ TaskPipeParameters::TaskPipeParameters(ViewProviderPipe* PipeView, bool /*newObj profileShow = profileVP->isShow(); profileVP->setVisible(true); ui->profileBaseEdit->setText( - make2DLabel(pipe->Profile.getValue(), pipe->Profile.getSubValues())); + make2DLabel(pipe->Profile.getValue(), pipe->Profile.getSubValues()) + ); } // the auxiliary spine if (pipe->AuxiliarySpine.getValue()) { @@ -152,8 +152,7 @@ TaskPipeParameters::~TaskPipeParameters() // invoking sweep Gui::cmdGuiObject(pipe, "Visibility = True"); getViewObject()->highlightReferences(ViewProviderPipe::Spine, false); - getViewObject()->highlightReferences(ViewProviderPipe::Profile, - false); + getViewObject()->highlightReferences(ViewProviderPipe::Profile, false); } } catch (const Standard_OutOfRange&) { @@ -179,11 +178,10 @@ void TaskPipeParameters::onSelectionChanged(const Gui::SelectionChanges& msg) if (msg.Type == Gui::SelectionChanges::AddSelection) { if (referenceSelected(msg)) { - if (stateHandler->getSelectionMode() - == StateHandlerTaskPipe::SelectionModes::refProfile) { + if (stateHandler->getSelectionMode() == StateHandlerTaskPipe::SelectionModes::refProfile) { App::Document* document = App::GetApplication().getDocument(msg.pDocName); - App::DocumentObject* object = - document ? document->getObject(msg.pObjectName) : nullptr; + App::DocumentObject* object = document ? document->getObject(msg.pObjectName) + : nullptr; if (object) { QString label = make2DLabel(object, {msg.pSubName}); ui->profileBaseEdit->setText(label); @@ -200,8 +198,8 @@ void TaskPipeParameters::onSelectionChanged(const Gui::SelectionChanges& msg) } App::Document* document = App::GetApplication().getDocument(msg.pDocName); - App::DocumentObject* object = - document ? document->getObject(msg.pObjectName) : nullptr; + App::DocumentObject* object = document ? document->getObject(msg.pObjectName) + : nullptr; if (object) { QString label = QString::fromUtf8(object->Label.getValue()); ui->spineBaseEdit->setText(label); @@ -222,8 +220,8 @@ void TaskPipeParameters::onSelectionChanged(const Gui::SelectionChanges& msg) ui->listWidgetReferences->clear(); App::Document* document = App::GetApplication().getDocument(msg.pDocName); - App::DocumentObject* object = - document ? document->getObject(msg.pObjectName) : nullptr; + App::DocumentObject* object = document ? document->getObject(msg.pObjectName) + : nullptr; if (object) { QString label = QString::fromUtf8(object->Label.getValue()); ui->spineBaseEdit->setText(label); @@ -325,8 +323,7 @@ bool TaskPipeParameters::referenceSelected(const SelectionChanges& msg) const auto pipe = getObject(); Gui::Document* doc = getGuiDocument(); - getViewObject()->highlightReferences(ViewProviderPipe::Profile, - false); + getViewObject()->highlightReferences(ViewProviderPipe::Profile, false); bool success = true; App::DocumentObject* profile = pipe->getDocument()->getObject(msg.pObjectName); @@ -359,8 +356,10 @@ bool TaskPipeParameters::referenceSelected(const SelectionChanges& msg) const const auto f = std::ranges::find(refs, subName); if (selectionMode == StateHandlerTaskPipe::SelectionModes::refSpine) { - getViewObject()->highlightReferences(ViewProviderPipe::Spine, - false); + getViewObject()->highlightReferences( + ViewProviderPipe::Spine, + false + ); refs.clear(); } else if (selectionMode == StateHandlerTaskPipe::SelectionModes::refSpineEdgeAdd) { @@ -371,8 +370,7 @@ bool TaskPipeParameters::referenceSelected(const SelectionChanges& msg) const return false; // duplicate selection } } - else if (selectionMode - == StateHandlerTaskPipe::SelectionModes::refSpineEdgeRemove) { + else if (selectionMode == StateHandlerTaskPipe::SelectionModes::refSpineEdgeRemove) { if (f != refs.end()) { refs.erase(f); } @@ -457,10 +455,11 @@ bool TaskPipeParameters::accept() QString label = ui->spineBaseEdit->text(); if (!spine && !label.isEmpty()) { QByteArray ba = label.toUtf8(); - std::vector objs = - pipe->getDocument()->findObjects(App::DocumentObject::getClassTypeId(), - nullptr, - ba.constData()); + std::vector objs = pipe->getDocument()->findObjects( + App::DocumentObject::getClassTypeId(), + nullptr, + ba.constData() + ); if (!objs.empty()) { pipe->Spine.setValue(objs.front()); spine = objs.front(); @@ -496,19 +495,21 @@ bool TaskPipeParameters::accept() if (!dlg.radioXRef->isChecked()) { if (!pcActiveBody->hasObject(spine) && !pcActiveBody->getOrigin()->hasObject(spine)) { pipe->Spine.setValue( - PartDesignGui::TaskFeaturePick::makeCopy(spine, - "", - dlg.radioIndependent->isChecked()), - pipe->Spine.getSubValues()); + PartDesignGui::TaskFeaturePick::makeCopy(spine, "", dlg.radioIndependent->isChecked()), + pipe->Spine.getSubValues() + ); copies.push_back(pipe->Spine.getValue()); } else if (!pcActiveBody->hasObject(auxSpine) && !pcActiveBody->getOrigin()->hasObject(auxSpine)) { pipe->AuxiliarySpine.setValue( - PartDesignGui::TaskFeaturePick::makeCopy(auxSpine, - "", - dlg.radioIndependent->isChecked()), - pipe->AuxiliarySpine.getSubValues()); + PartDesignGui::TaskFeaturePick::makeCopy( + auxSpine, + "", + dlg.radioIndependent->isChecked() + ), + pipe->AuxiliarySpine.getSubValues() + ); copies.push_back(pipe->AuxiliarySpine.getValue()); } @@ -517,10 +518,13 @@ bool TaskPipeParameters::accept() if (!pcActiveBody->hasObject(subSet.first) && !pcActiveBody->getOrigin()->hasObject(subSet.first)) { subSets.emplace_back( - PartDesignGui::TaskFeaturePick::makeCopy(subSet.first, - "", - dlg.radioIndependent->isChecked()), - subSet.second); + PartDesignGui::TaskFeaturePick::makeCopy( + subSet.first, + "", + dlg.radioIndependent->isChecked() + ), + subSet.second + ); copies.push_back(subSets.back().first); } else { @@ -554,9 +558,7 @@ bool TaskPipeParameters::accept() } } catch (const Base::Exception& e) { - QMessageBox::warning(this, - tr("Input error"), - QApplication::translate("Exception", e.what())); + QMessageBox::warning(this, tr("Input error"), QApplication::translate("Exception", e.what())); return false; } @@ -569,13 +571,8 @@ bool TaskPipeParameters::accept() // Task Orientation //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskPipeOrientation::TaskPipeOrientation(ViewProviderPipe* PipeView, - bool /*newObj*/, - QWidget* parent) - : TaskSketchBasedParameters(PipeView, - parent, - "PartDesign_AdditivePipe", - tr("Section Orientation")) +TaskPipeOrientation::TaskPipeOrientation(ViewProviderPipe* PipeView, bool /*newObj*/, QWidget* parent) + : TaskSketchBasedParameters(PipeView, parent, "PartDesign_AdditivePipe", tr("Section Orientation")) , ui(new Ui_TaskPipeOrientation) , stateHandler(nullptr) { @@ -621,7 +618,8 @@ TaskPipeOrientation::TaskPipeOrientation(ViewProviderPipe* PipeView, // add initial values if (pipe->AuxiliarySpine.getValue()) { ui->profileBaseEdit->setText( - QString::fromUtf8(pipe->AuxiliarySpine.getValue()->Label.getValue())); + QString::fromUtf8(pipe->AuxiliarySpine.getValue()->Label.getValue()) + ); } std::vector strings = pipe->AuxiliarySpine.getSubValues(); @@ -637,10 +635,7 @@ TaskPipeOrientation::TaskPipeOrientation(ViewProviderPipe* PipeView, ui->curvilinear->setChecked(pipe->AuxiliaryCurvilinear.getValue()); // should be called after panel has become visible - QMetaObject::invokeMethod(this, - "updateUI", - Qt::QueuedConnection, - Q_ARG(int, pipe->Mode.getValue())); + QMetaObject::invokeMethod(this, "updateUI", Qt::QueuedConnection, Q_ARG(int, pipe->Mode.getValue())); this->blockSelection(false); } @@ -696,9 +691,11 @@ void TaskPipeOrientation::onCurvilinearChanged(bool checked) void TaskPipeOrientation::onBinormalChanged(double) { if (auto pipe = getObject()) { - Base::Vector3d vec(ui->doubleSpinBoxX->value(), - ui->doubleSpinBoxY->value(), - ui->doubleSpinBoxZ->value()); + Base::Vector3d vec( + ui->doubleSpinBoxX->value(), + ui->doubleSpinBoxY->value(), + ui->doubleSpinBoxZ->value() + ); pipe->Binormal.setValue(vec); recomputeFeature(); @@ -724,8 +721,8 @@ void TaskPipeOrientation::onSelectionChanged(const SelectionChanges& msg) } App::Document* document = App::GetApplication().getDocument(msg.pDocName); - App::DocumentObject* object = - document ? document->getObject(msg.pObjectName) : nullptr; + App::DocumentObject* object = document ? document->getObject(msg.pObjectName) + : nullptr; if (object) { QString label = QString::fromUtf8(object->Label.getValue()); ui->profileBaseEdit->setText(label); @@ -746,8 +743,8 @@ void TaskPipeOrientation::onSelectionChanged(const SelectionChanges& msg) ui->listWidgetReferences->clear(); App::Document* document = App::GetApplication().getDocument(msg.pDocName); - App::DocumentObject* object = - document ? document->getObject(msg.pObjectName) : nullptr; + App::DocumentObject* object = document ? document->getObject(msg.pObjectName) + : nullptr; if (object) { QString label = QString::fromUtf8(object->Label.getValue()); ui->profileBaseEdit->setText(label); @@ -860,8 +857,7 @@ void TaskPipeOrientation::updateUI(int idx) } if (idx < ui->stackedWidget->count()) { - ui->stackedWidget->widget(idx)->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding); + ui->stackedWidget->widget(idx)->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } } @@ -871,10 +867,7 @@ void TaskPipeOrientation::updateUI(int idx) // Task Scaling //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskPipeScaling::TaskPipeScaling(ViewProviderPipe* PipeView, bool /*newObj*/, QWidget* parent) - : TaskSketchBasedParameters(PipeView, - parent, - "PartDesign_AdditivePipe", - tr("Section Transformation")) + : TaskSketchBasedParameters(PipeView, parent, "PartDesign_AdditivePipe", tr("Section Transformation")) , ui(new Ui_TaskPipeScaling) , stateHandler(nullptr) { @@ -884,10 +877,12 @@ TaskPipeScaling::TaskPipeScaling(ViewProviderPipe* PipeView, bool /*newObj*/, QW QMetaObject::connectSlotsByName(this); // some buttons are handled in a buttongroup - connect(ui->comboBoxScaling, - qOverload(&QComboBox::currentIndexChanged), - this, - &TaskPipeScaling::onScalingChanged); + connect( + ui->comboBoxScaling, + qOverload(&QComboBox::currentIndexChanged), + this, + &TaskPipeScaling::onScalingChanged + ); connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, &TaskPipeScaling::updateUI); // Create context menu @@ -902,10 +897,12 @@ TaskPipeScaling::TaskPipeScaling(ViewProviderPipe* PipeView, bool /*newObj*/, QW ui->listWidgetReferences->setContextMenuPolicy(Qt::ActionsContextMenu); connect(remove, &QAction::triggered, this, &TaskPipeScaling::onDeleteSection); - connect(ui->listWidgetReferences->model(), - &QAbstractListModel::rowsMoved, - this, - &TaskPipeScaling::indexesMoved); + connect( + ui->listWidgetReferences->model(), + &QAbstractListModel::rowsMoved, + this, + &TaskPipeScaling::indexesMoved + ); this->groupLayout()->addWidget(proxy); @@ -922,10 +919,12 @@ TaskPipeScaling::TaskPipeScaling(ViewProviderPipe* PipeView, bool /*newObj*/, QW ui->comboBoxScaling->setCurrentIndex(pipe->Transformation.getValue()); // should be called after panel has become visible - QMetaObject::invokeMethod(this, - "updateUI", - Qt::QueuedConnection, - Q_ARG(int, pipe->Transformation.getValue())); + QMetaObject::invokeMethod( + this, + "updateUI", + Qt::QueuedConnection, + Q_ARG(int, pipe->Transformation.getValue()) + ); this->blockSelection(false); } @@ -999,7 +998,9 @@ void TaskPipeScaling::onSelectionChanged(const SelectionChanges& msg) item->setData( Qt::UserRole, QVariant::fromValue( - std::make_pair(object, std::vector(1, msg.pSubName)))); + std::make_pair(object, std::vector(1, msg.pSubName)) + ) + ); ui->listWidgetReferences->addItem(item); } else if (stateHandler->getSelectionMode() @@ -1080,9 +1081,9 @@ void TaskPipeScaling::onDeleteSection() int row = ui->listWidgetReferences->currentRow(); QListWidgetItem* item = ui->listWidgetReferences->takeItem(row); if (item) { - QByteArray data(item->data(Qt::UserRole) - .value() - .first->getNameInDocument()); + QByteArray data( + item->data(Qt::UserRole).value().first->getNameInDocument() + ); delete item; if (const auto pipe = getObject()) { @@ -1106,8 +1107,7 @@ void TaskPipeScaling::updateUI(int idx) } if (idx < ui->stackedWidget->count()) { - ui->stackedWidget->widget(idx)->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding); + ui->stackedWidget->widget(idx)->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } } @@ -1142,21 +1142,21 @@ TaskDlgPipeParameters::TaskDlgPipeParameters(ViewProviderPipe* PipeView, bool ne buttonGroup->addButton(parameter->ui->buttonProfileBase, StateHandlerTaskPipe::refProfile); buttonGroup->addButton(parameter->ui->buttonSpineBase, StateHandlerTaskPipe::refSpine); buttonGroup->addButton(parameter->ui->buttonRefAdd, StateHandlerTaskPipe::refSpineEdgeAdd); - buttonGroup->addButton(parameter->ui->buttonRefRemove, - StateHandlerTaskPipe::refSpineEdgeRemove); + buttonGroup->addButton(parameter->ui->buttonRefRemove, StateHandlerTaskPipe::refSpineEdgeRemove); buttonGroup->addButton(orientation->ui->buttonProfileBase, StateHandlerTaskPipe::refAuxSpine); buttonGroup->addButton(orientation->ui->buttonRefAdd, StateHandlerTaskPipe::refAuxSpineEdgeAdd); - buttonGroup->addButton(orientation->ui->buttonRefRemove, - StateHandlerTaskPipe::refAuxSpineEdgeRemove); + buttonGroup->addButton(orientation->ui->buttonRefRemove, StateHandlerTaskPipe::refAuxSpineEdgeRemove); buttonGroup->addButton(scaling->ui->buttonRefAdd, StateHandlerTaskPipe::refSectionAdd); buttonGroup->addButton(scaling->ui->buttonRefRemove, StateHandlerTaskPipe::refSectionRemove); - connect(buttonGroup, - qOverload(&QButtonGroup::buttonToggled), - this, - &TaskDlgPipeParameters::onButtonToggled); + connect( + buttonGroup, + qOverload(&QButtonGroup::buttonToggled), + this, + &TaskDlgPipeParameters::onButtonToggled + ); } TaskDlgPipeParameters::~TaskDlgPipeParameters() @@ -1182,25 +1182,24 @@ void TaskDlgPipeParameters::onButtonToggled(QAbstractButton* button, bool checke switch (id) { case StateHandlerTaskPipe::SelectionModes::refProfile: - getViewObject()->highlightReferences(ViewProviderPipe::Profile, - checked); + getViewObject()->highlightReferences(ViewProviderPipe::Profile, checked); break; case StateHandlerTaskPipe::SelectionModes::refSpine: case StateHandlerTaskPipe::SelectionModes::refSpineEdgeAdd: case StateHandlerTaskPipe::SelectionModes::refSpineEdgeRemove: - getViewObject()->highlightReferences(ViewProviderPipe::Spine, - checked); + getViewObject()->highlightReferences(ViewProviderPipe::Spine, checked); break; case StateHandlerTaskPipe::SelectionModes::refAuxSpine: case StateHandlerTaskPipe::SelectionModes::refAuxSpineEdgeAdd: case StateHandlerTaskPipe::SelectionModes::refAuxSpineEdgeRemove: - getViewObject()->highlightReferences(ViewProviderPipe::AuxiliarySpine, - checked); + getViewObject()->highlightReferences( + ViewProviderPipe::AuxiliarySpine, + checked + ); break; case StateHandlerTaskPipe::SelectionModes::refSectionAdd: case StateHandlerTaskPipe::SelectionModes::refSectionRemove: - getViewObject()->highlightReferences(ViewProviderPipe::Section, - checked); + getViewObject()->highlightReferences(ViewProviderPipe::Section, checked); break; default: break; diff --git a/src/Mod/PartDesign/Gui/TaskPipeParameters.h b/src/Mod/PartDesign/Gui/TaskPipeParameters.h index 6cbb0b2f51..1507760bee 100644 --- a/src/Mod/PartDesign/Gui/TaskPipeParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPipeParameters.h @@ -28,16 +28,19 @@ #include "TaskDressUpParameters.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ButtonGroup; class ViewProvider; -} +} // namespace Gui -namespace PartDesignGui { +namespace PartDesignGui +{ class Ui_TaskPipeParameters; class Ui_TaskPipeOrientation; @@ -47,7 +50,8 @@ class Ui_TaskPipeScaling; class StateHandlerTaskPipe { public: - enum SelectionModes { + enum SelectionModes + { none = 0, refProfile, refSpine, @@ -61,12 +65,18 @@ public: }; public: - StateHandlerTaskPipe() {selectionMode = SelectionModes::none;} + StateHandlerTaskPipe() + { + selectionMode = SelectionModes::none; + } ~StateHandlerTaskPipe() = default; // only keeping getter because task boxes shouldn't need to change this // and task dialog is already friend - enum SelectionModes getSelectionMode() {return selectionMode;} + enum SelectionModes getSelectionMode() + { + return selectionMode; + } private: enum SelectionModes selectionMode; @@ -74,12 +84,16 @@ private: }; -class TaskPipeParameters : public TaskSketchBasedParameters +class TaskPipeParameters: public TaskSketchBasedParameters { Q_OBJECT public: - explicit TaskPipeParameters(ViewProviderPipe *PipeView, bool newObj=false, QWidget *parent = nullptr); + explicit TaskPipeParameters( + ViewProviderPipe* PipeView, + bool newObj = false, + QWidget* parent = nullptr + ); ~TaskPipeParameters() override; bool accept(); @@ -91,7 +105,7 @@ private Q_SLOTS: void onDeleteEdge(); protected: - void removeFromListWidget(QListWidget*w, QString name); + void removeFromListWidget(QListWidget* w, QString name); bool referenceSelected(const Gui::SelectionChanges& msg) const; private: @@ -108,16 +122,20 @@ private: private: QWidget* proxy; std::unique_ptr ui; - StateHandlerTaskPipe *stateHandler; + StateHandlerTaskPipe* stateHandler; friend class TaskDlgPipeParameters; }; -class TaskPipeOrientation : public TaskSketchBasedParameters +class TaskPipeOrientation: public TaskSketchBasedParameters { Q_OBJECT public: - explicit TaskPipeOrientation(ViewProviderPipe *PipeView, bool newObj=false, QWidget *parent = nullptr); + explicit TaskPipeOrientation( + ViewProviderPipe* PipeView, + bool newObj = false, + QWidget* parent = nullptr + ); ~TaskPipeOrientation() override; @@ -130,7 +148,7 @@ private Q_SLOTS: void onDeleteItem(); protected: - void removeFromListWidget(QListWidget*w, QString name); + void removeFromListWidget(QListWidget* w, QString name); bool referenceSelected(const Gui::SelectionChanges& msg) const; private: @@ -141,17 +159,17 @@ private: private: QWidget* proxy; std::unique_ptr ui; - StateHandlerTaskPipe *stateHandler; + StateHandlerTaskPipe* stateHandler; friend class TaskDlgPipeParameters; }; -class TaskPipeScaling : public TaskSketchBasedParameters +class TaskPipeScaling: public TaskSketchBasedParameters { Q_OBJECT public: - explicit TaskPipeScaling(ViewProviderPipe *PipeView,bool newObj=false,QWidget *parent = nullptr); + explicit TaskPipeScaling(ViewProviderPipe* PipeView, bool newObj = false, QWidget* parent = nullptr); ~TaskPipeScaling() override; private Q_SLOTS: @@ -161,7 +179,7 @@ private Q_SLOTS: void indexesMoved(); protected: - void removeFromListWidget(QListWidget*w, QString name); + void removeFromListWidget(QListWidget* w, QString name); bool referenceSelected(const Gui::SelectionChanges& msg) const; private: @@ -172,17 +190,17 @@ private: private: QWidget* proxy; std::unique_ptr ui; - StateHandlerTaskPipe *stateHandler; + StateHandlerTaskPipe* stateHandler; friend class TaskDlgPipeParameters; }; /// simulation dialog for the TaskView -class TaskDlgPipeParameters : public TaskDlgSketchBasedParameters +class TaskDlgPipeParameters: public TaskDlgSketchBasedParameters { Q_OBJECT public: - explicit TaskDlgPipeParameters(ViewProviderPipe *PipeView,bool newObj=false); + explicit TaskDlgPipeParameters(ViewProviderPipe* PipeView, bool newObj = false); ~TaskDlgPipeParameters() override; public: @@ -191,17 +209,17 @@ public: /// is called by the framework if the dialog is rejected (Cancel) protected Q_SLOTS: - void onButtonToggled(QAbstractButton *button, bool checked); + void onButtonToggled(QAbstractButton* button, bool checked); protected: - TaskPipeParameters *parameter; - TaskPipeOrientation *orientation; - TaskPipeScaling *scaling; + TaskPipeParameters* parameter; + TaskPipeOrientation* orientation; + TaskPipeScaling* scaling; - Gui::ButtonGroup *buttonGroup; - StateHandlerTaskPipe *stateHandler; + Gui::ButtonGroup* buttonGroup; + StateHandlerTaskPipe* stateHandler; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp b/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp index 2ccdf9f31d..73d2a18a51 100644 --- a/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp @@ -20,7 +20,7 @@ * * ***************************************************************************/ -# include +#include #include @@ -34,11 +34,15 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskPocketParameters */ -TaskPocketParameters::TaskPocketParameters(ViewProviderPocket *PocketView,QWidget *parent, bool newObj) +TaskPocketParameters::TaskPocketParameters(ViewProviderPocket* PocketView, QWidget* parent, bool newObj) : TaskExtrudeParameters(PocketView, parent, "PartDesign_Pocket", tr("Pocket Parameters")) { - ui->offsetEdit->setToolTip(tr("Offset from the selected face at which the pocket will end on side 1")); - ui->offsetEdit2->setToolTip(tr("Offset from the selected face at which the pocket will end on side 2")); + ui->offsetEdit->setToolTip( + tr("Offset from the selected face at which the pocket will end on side 1") + ); + ui->offsetEdit2->setToolTip( + tr("Offset from the selected face at which the pocket will end on side 2") + ); ui->checkBoxReversed->setToolTip(tr("Reverses pocket direction")); // set the history path @@ -140,8 +144,9 @@ void TaskPocketParameters::apply() // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgPocketParameters::TaskDlgPocketParameters(ViewProviderPocket *PocketView) - : TaskDlgExtrudeParameters(PocketView), parameters(new TaskPocketParameters(PocketView)) +TaskDlgPocketParameters::TaskDlgPocketParameters(ViewProviderPocket* PocketView) + : TaskDlgExtrudeParameters(PocketView) + , parameters(new TaskPocketParameters(PocketView)) { Content.push_back(parameters); Content.push_back(preview); diff --git a/src/Mod/PartDesign/Gui/TaskPocketParameters.h b/src/Mod/PartDesign/Gui/TaskPocketParameters.h index 5faf69e6f5..fcda2cdd98 100644 --- a/src/Mod/PartDesign/Gui/TaskPocketParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPocketParameters.h @@ -28,23 +28,30 @@ class QComboBox; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class TaskPocketParameters : public TaskExtrudeParameters +class TaskPocketParameters: public TaskExtrudeParameters { Q_OBJECT public: - explicit TaskPocketParameters(ViewProviderPocket *PocketView, QWidget *parent = nullptr, bool newObj=false); + explicit TaskPocketParameters( + ViewProviderPocket* PocketView, + QWidget* parent = nullptr, + bool newObj = false + ); ~TaskPocketParameters() override; void apply() override; @@ -56,12 +63,12 @@ private: }; /// simulation dialog for the TaskView -class TaskDlgPocketParameters : public TaskDlgExtrudeParameters +class TaskDlgPocketParameters: public TaskDlgExtrudeParameters { Q_OBJECT public: - explicit TaskDlgPocketParameters(ViewProviderPocket *PocketView); + explicit TaskDlgPocketParameters(ViewProviderPocket* PocketView); protected: TaskExtrudeParameters* getTaskParameters() override @@ -73,6 +80,6 @@ private: TaskPocketParameters* parameters; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp index 2a95c704cd..387ad51914 100644 --- a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp @@ -382,7 +382,8 @@ TaskBoxPrimitives::~TaskBoxPrimitives() App::Origin* origin = body->getOrigin(); Gui::ViewProviderCoordinateSystem* vpOrigin; vpOrigin = static_cast( - Gui::Application::Instance->getViewProvider(origin)); + Gui::Application::Instance->getViewProvider(origin) + ); vpOrigin->resetTemporaryVisibility(); } } @@ -821,135 +822,157 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject* obj) Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); switch (ui->widgetStack->currentIndex()) { case 1: // box - cmd = fmt::format("{0}.Length='{1}'\n" - "{0}.Width='{2}'\n" - "{0}.Height='{3}'\n", - name, - ui->boxLength->value().getSafeUserString(), - ui->boxWidth->value().getSafeUserString(), - ui->boxHeight->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Length='{1}'\n" + "{0}.Width='{2}'\n" + "{0}.Height='{3}'\n", + name, + ui->boxLength->value().getSafeUserString(), + ui->boxWidth->value().getSafeUserString(), + ui->boxHeight->value().getSafeUserString() + ); break; case 2: // cylinder - cmd = fmt::format("{0}.Radius='{1}'\n" - "{0}.Height='{2}'\n" - "{0}.Angle='{3}'\n" - "{0}.FirstAngle='{4}'\n" - "{0}.SecondAngle='{5}'\n", - name, - ui->cylinderRadius->value().getSafeUserString(), - ui->cylinderHeight->value().getSafeUserString(), - ui->cylinderAngle->value().getSafeUserString(), - ui->cylinderXSkew->value().getSafeUserString(), - ui->cylinderYSkew->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Radius='{1}'\n" + "{0}.Height='{2}'\n" + "{0}.Angle='{3}'\n" + "{0}.FirstAngle='{4}'\n" + "{0}.SecondAngle='{5}'\n", + name, + ui->cylinderRadius->value().getSafeUserString(), + ui->cylinderHeight->value().getSafeUserString(), + ui->cylinderAngle->value().getSafeUserString(), + ui->cylinderXSkew->value().getSafeUserString(), + ui->cylinderYSkew->value().getSafeUserString() + ); break; case 3: // cone - cmd = fmt::format("{0}.Radius1='{1}'\n" - "{0}.Radius2='{2}'\n" - "{0}.Height='{3}'\n" - "{0}.Angle='{4}'\n", - name, - ui->coneRadius1->value().getSafeUserString(), - ui->coneRadius2->value().getSafeUserString(), - ui->coneHeight->value().getSafeUserString(), - ui->coneAngle->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Radius1='{1}'\n" + "{0}.Radius2='{2}'\n" + "{0}.Height='{3}'\n" + "{0}.Angle='{4}'\n", + name, + ui->coneRadius1->value().getSafeUserString(), + ui->coneRadius2->value().getSafeUserString(), + ui->coneHeight->value().getSafeUserString(), + ui->coneAngle->value().getSafeUserString() + ); break; case 4: // sphere - cmd = fmt::format("{0}.Radius='{1}'\n" - "{0}.Angle1='{2}'\n" - "{0}.Angle2='{3}'\n" - "{0}.Angle3='{4}'\n", - name, - ui->sphereRadius->value().getSafeUserString(), - ui->sphereAngle1->value().getSafeUserString(), - ui->sphereAngle2->value().getSafeUserString(), - ui->sphereAngle3->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Radius='{1}'\n" + "{0}.Angle1='{2}'\n" + "{0}.Angle2='{3}'\n" + "{0}.Angle3='{4}'\n", + name, + ui->sphereRadius->value().getSafeUserString(), + ui->sphereAngle1->value().getSafeUserString(), + ui->sphereAngle2->value().getSafeUserString(), + ui->sphereAngle3->value().getSafeUserString() + ); break; case 5: // ellipsoid - cmd = fmt::format("{0}.Radius1='{1}'\n" - "{0}.Radius2='{2}'\n" - "{0}.Radius3='{3}'\n" - "{0}.Angle1='{4}'\n" - "{0}.Angle2='{5}'\n" - "{0}.Angle3='{6}'\n", - name, - ui->ellipsoidRadius1->value().getSafeUserString(), - ui->ellipsoidRadius2->value().getSafeUserString(), - ui->ellipsoidRadius3->value().getSafeUserString(), - ui->ellipsoidAngle1->value().getSafeUserString(), - ui->ellipsoidAngle2->value().getSafeUserString(), - ui->ellipsoidAngle3->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Radius1='{1}'\n" + "{0}.Radius2='{2}'\n" + "{0}.Radius3='{3}'\n" + "{0}.Angle1='{4}'\n" + "{0}.Angle2='{5}'\n" + "{0}.Angle3='{6}'\n", + name, + ui->ellipsoidRadius1->value().getSafeUserString(), + ui->ellipsoidRadius2->value().getSafeUserString(), + ui->ellipsoidRadius3->value().getSafeUserString(), + ui->ellipsoidAngle1->value().getSafeUserString(), + ui->ellipsoidAngle2->value().getSafeUserString(), + ui->ellipsoidAngle3->value().getSafeUserString() + ); break; case 6: // torus - cmd = fmt::format("{0}.Radius1='{1}'\n" - "{0}.Radius2='{2}'\n" - "{0}.Angle1='{3}'\n" - "{0}.Angle2='{4}'\n" - "{0}.Angle3='{5}'\n", - name, - ui->torusRadius1->value().getSafeUserString(), - ui->torusRadius2->value().getSafeUserString(), - ui->torusAngle1->value().getSafeUserString(), - ui->torusAngle2->value().getSafeUserString(), - ui->torusAngle3->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Radius1='{1}'\n" + "{0}.Radius2='{2}'\n" + "{0}.Angle1='{3}'\n" + "{0}.Angle2='{4}'\n" + "{0}.Angle3='{5}'\n", + name, + ui->torusRadius1->value().getSafeUserString(), + ui->torusRadius2->value().getSafeUserString(), + ui->torusAngle1->value().getSafeUserString(), + ui->torusAngle2->value().getSafeUserString(), + ui->torusAngle3->value().getSafeUserString() + ); break; case 7: // prism - cmd = fmt::format("{0}.Polygon={1}\n" - "{0}.Circumradius='{2}'\n" - "{0}.Height='{3}'\n" - "{0}.FirstAngle='{4}'\n" - "{0}.SecondAngle='{5}'\n", - name, - ui->prismPolygon->value(), - ui->prismCircumradius->value().getSafeUserString(), - ui->prismHeight->value().getSafeUserString(), - ui->prismXSkew->value().getSafeUserString(), - ui->prismYSkew->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Polygon={1}\n" + "{0}.Circumradius='{2}'\n" + "{0}.Height='{3}'\n" + "{0}.FirstAngle='{4}'\n" + "{0}.SecondAngle='{5}'\n", + name, + ui->prismPolygon->value(), + ui->prismCircumradius->value().getSafeUserString(), + ui->prismHeight->value().getSafeUserString(), + ui->prismXSkew->value().getSafeUserString(), + ui->prismYSkew->value().getSafeUserString() + ); break; case 8: // wedge // Xmin/max, Ymin/max and Zmin/max must each not be equal if (ui->wedgeXmin->value().getValue() == ui->wedgeXmax->value().getValue()) { - QMessageBox::warning(Gui::getMainWindow(), - tr("Invalid wedge parameters"), - tr("X min must not be equal to X max!")); + QMessageBox::warning( + Gui::getMainWindow(), + tr("Invalid wedge parameters"), + tr("X min must not be equal to X max!") + ); return false; } else if (ui->wedgeYmin->value().getValue() == ui->wedgeYmax->value().getValue()) { - QMessageBox::warning(Gui::getMainWindow(), - tr("Invalid wedge parameters"), - tr("Y min must not be equal to Y max!")); + QMessageBox::warning( + Gui::getMainWindow(), + tr("Invalid wedge parameters"), + tr("Y min must not be equal to Y max!") + ); return false; } else if (ui->wedgeZmin->value().getValue() == ui->wedgeZmax->value().getValue()) { - QMessageBox::warning(Gui::getMainWindow(), - tr("Invalid wedge parameters"), - tr("Z min must not be equal to Z max!")); + QMessageBox::warning( + Gui::getMainWindow(), + tr("Invalid wedge parameters"), + tr("Z min must not be equal to Z max!") + ); return false; } - cmd = fmt::format("{0}.Xmin='{1}'\n" - "{0}.Ymin='{2}'\n" - "{0}.Zmin='{3}'\n" - "{0}.X2min='{4}'\n" - "{0}.Z2min='{5}'\n" - "{0}.Xmax='{6}'\n" - "{0}.Ymax='{7}'\n" - "{0}.Zmax='{8}'\n" - "{0}.X2max='{9}'\n" - "{0}.Z2max='{10}'\n", - name, - ui->wedgeXmin->value().getSafeUserString(), - ui->wedgeYmin->value().getSafeUserString(), - ui->wedgeZmin->value().getSafeUserString(), - ui->wedgeX2min->value().getSafeUserString(), - ui->wedgeZ2min->value().getSafeUserString(), - ui->wedgeXmax->value().getSafeUserString(), - ui->wedgeYmax->value().getSafeUserString(), - ui->wedgeZmax->value().getSafeUserString(), - ui->wedgeX2max->value().getSafeUserString(), - ui->wedgeZ2max->value().getSafeUserString()); + cmd = fmt::format( + "{0}.Xmin='{1}'\n" + "{0}.Ymin='{2}'\n" + "{0}.Zmin='{3}'\n" + "{0}.X2min='{4}'\n" + "{0}.Z2min='{5}'\n" + "{0}.Xmax='{6}'\n" + "{0}.Ymax='{7}'\n" + "{0}.Zmax='{8}'\n" + "{0}.X2max='{9}'\n" + "{0}.Z2max='{10}'\n", + name, + ui->wedgeXmin->value().getSafeUserString(), + ui->wedgeYmin->value().getSafeUserString(), + ui->wedgeZmin->value().getSafeUserString(), + ui->wedgeX2min->value().getSafeUserString(), + ui->wedgeZ2min->value().getSafeUserString(), + ui->wedgeXmax->value().getSafeUserString(), + ui->wedgeYmax->value().getSafeUserString(), + ui->wedgeZmax->value().getSafeUserString(), + ui->wedgeX2max->value().getSafeUserString(), + ui->wedgeZ2max->value().getSafeUserString() + ); break; default: @@ -963,9 +986,11 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject* obj) Gui::Command::runCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } catch (const Base::PyException& e) { - QMessageBox::warning(this, - tr("Create primitive"), - QApplication::translate("Exception", e.what())); + QMessageBox::warning( + this, + tr("Create primitive"), + QApplication::translate("Exception", e.what()) + ); return false; } return true; diff --git a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h index a0da4a3f1f..8a3be046a8 100644 --- a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h @@ -33,18 +33,20 @@ #include "TaskDatumParameters.h" #include "TaskFeatureParameters.h" -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ViewProvider; } -namespace PartDesignGui { +namespace PartDesignGui +{ class Ui_DlgPrimitives; -class TaskBoxPrimitives : public Gui::TaskView::TaskBox, - public Gui::DocumentObserver +class TaskBoxPrimitives: public Gui::TaskView::TaskBox, public Gui::DocumentObserver { Q_OBJECT @@ -52,7 +54,7 @@ public: explicit TaskBoxPrimitives(ViewProviderPrimitive* vp, QWidget* parent = nullptr); ~TaskBoxPrimitives() override; - bool setPrimitive(App::DocumentObject *); + bool setPrimitive(App::DocumentObject*); public Q_SLOTS: void onBoxLengthChanged(double); @@ -102,7 +104,8 @@ private: /** Notifies when the object is about to be removed. */ void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; - template T* getObject() const + template + T* getObject() const { static_assert(std::is_base_of::value, "Wrong template argument"); if (vp) { @@ -118,12 +121,12 @@ private: ViewProviderPrimitive* vp; }; -class TaskDlgPrimitiveParameters : public TaskDlgFeatureParameters +class TaskDlgPrimitiveParameters: public TaskDlgFeatureParameters { Q_OBJECT public: - explicit TaskDlgPrimitiveParameters(ViewProviderPrimitive *PrimitiveView); + explicit TaskDlgPrimitiveParameters(ViewProviderPrimitive* PrimitiveView); ~TaskDlgPrimitiveParameters() override; protected: @@ -133,11 +136,11 @@ protected: bool reject() override; private: - TaskBoxPrimitives* primitive; + TaskBoxPrimitives* primitive; PartGui::TaskAttacher* parameter; ViewProviderPrimitive* vp_prm; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp index 1eabe7811c..620cd037d9 100644 --- a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp @@ -49,10 +49,12 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskRevolutionParameters */ -TaskRevolutionParameters::TaskRevolutionParameters(PartDesignGui::ViewProvider* RevolutionView, - const char* pixname, - const QString& title, - QWidget *parent) +TaskRevolutionParameters::TaskRevolutionParameters( + PartDesignGui::ViewProvider* RevolutionView, + const char* pixname, + const QString& title, + QWidget* parent +) : TaskSketchBasedParameters(RevolutionView, parent, pixname, title) , ui(new Ui_TaskRevolutionParameters) , proxy(new QWidget(this)) @@ -104,7 +106,7 @@ TaskRevolutionParameters::TaskRevolutionParameters(PartDesignGui::ViewProvider* vpOrigin->setTemporaryVisibility(Gui::DatumElement::Axes); } } - catch (const Base::Exception &ex) { + catch (const Base::Exception& ex) { ex.reportException(); } @@ -114,12 +116,13 @@ TaskRevolutionParameters::TaskRevolutionParameters(PartDesignGui::ViewProvider* Gui::ViewProviderCoordinateSystem* TaskRevolutionParameters::getOriginView() const { // show the parts coordinate system axis for selection - PartDesign::Body * body = PartDesign::Body::findBodyOf(getObject()); + PartDesign::Body* body = PartDesign::Body::findBodyOf(getObject()); if (body) { - App::Origin *origin = body->getOrigin(); + App::Origin* origin = body->getOrigin(); return freecad_cast( - Gui::Application::Instance->getViewProvider(origin)); - } + Gui::Application::Instance->getViewProvider(origin) + ); + } return nullptr; } @@ -150,10 +153,11 @@ void TaskRevolutionParameters::setupDialog() ui->lineFaceName->setProperty("FeatureName", QByteArray(obj->getNameInDocument())); } else if (obj && faceId >= 0) { - ui->lineFaceName->setText(QStringLiteral("%1:%2%3") - .arg(QString::fromUtf8(obj->Label.getValue()), - tr("Face"), - QString::number(faceId))); + ui->lineFaceName->setText(QStringLiteral("%1:%2%3").arg( + QString::fromUtf8(obj->Label.getValue()), + tr("Face"), + QString::number(faceId) + )); ui->lineFaceName->setProperty("FeatureName", QByteArray(obj->getNameInDocument())); } else { @@ -214,50 +218,51 @@ void TaskRevolutionParameters::fillAxisCombo(bool forceRefill) ui->axis->clear(); axesInList.clear(); - auto *pcFeat = getObject(); + auto* pcFeat = getObject(); if (!pcFeat) { throw Base::TypeError("The object is not profile-based."); } - //add sketch axes - if (auto *pcSketch = dynamic_cast(pcFeat->Profile.getValue())) { + // add sketch axes + if (auto* pcSketch = dynamic_cast(pcFeat->Profile.getValue())) { addAxisToCombo(pcSketch, "V_Axis", QObject::tr("Vertical sketch axis")); addAxisToCombo(pcSketch, "H_Axis", QObject::tr("Horizontal sketch axis")); - for (int i=0; i < pcSketch->getAxisCount(); i++) { - QString itemText = QObject::tr("Construction line %1").arg(i+1); + for (int i = 0; i < pcSketch->getAxisCount(); i++) { + QString itemText = QObject::tr("Construction line %1").arg(i + 1); std::stringstream sub; sub << "Axis" << i; - addAxisToCombo(pcSketch,sub.str(),itemText); + addAxisToCombo(pcSketch, sub.str(), itemText); } } - //add origin axes - if (PartDesign::Body * body = PartDesign::Body::findBodyOf(pcFeat)) { + // add origin axes + if (PartDesign::Body* body = PartDesign::Body::findBodyOf(pcFeat)) { try { App::Origin* orig = body->getOrigin(); addAxisToCombo(orig->getX(), std::string(), tr("Base X-axis")); addAxisToCombo(orig->getY(), std::string(), tr("Base Y-axis")); addAxisToCombo(orig->getZ(), std::string(), tr("Base Z-axis")); - } catch (const Base::Exception &ex) { + } + catch (const Base::Exception& ex) { ex.reportException(); } } - //add "Select reference" + // add "Select reference" addAxisToCombo(nullptr, std::string(), tr("Select reference…")); - }//endif forceRefill + } // endif forceRefill - //add current link, if not in list - //first, figure out the item number for current axis + // add current link, if not in list + // first, figure out the item number for current axis int indexOfCurrent = -1; App::DocumentObject* ax = propReferenceAxis->getValue(); - const std::vector &subList = propReferenceAxis->getSubValues(); + const std::vector& subList = propReferenceAxis->getSubValues(); for (size_t i = 0; i < axesInList.size(); i++) { if (ax == axesInList[i]->getValue() && subList == axesInList[i]->getSubValues()) { indexOfCurrent = int(i); } } - if (indexOfCurrent == -1 && ax) { + if (indexOfCurrent == -1 && ax) { assert(subList.size() <= 1); std::string sub; if (!subList.empty()) { @@ -267,19 +272,21 @@ void TaskRevolutionParameters::fillAxisCombo(bool forceRefill) indexOfCurrent = int(axesInList.size()) - 1; } - //highlight current. + // highlight current. if (indexOfCurrent != -1) { ui->axis->setCurrentIndex(indexOfCurrent); } } -void TaskRevolutionParameters::addAxisToCombo(App::DocumentObject* linkObj, - const std::string& linkSubname, - const QString& itemText) +void TaskRevolutionParameters::addAxisToCombo( + App::DocumentObject* linkObj, + const std::string& linkSubname, + const QString& itemText +) { this->ui->axis->addItem(itemText); this->axesInList.emplace_back(new App::PropertyLinkSub()); - App::PropertyLinkSub &lnk = *(axesInList[axesInList.size()-1]); + App::PropertyLinkSub& lnk = *(axesInList[axesInList.size() - 1]); lnk.setValue(linkObj, std::vector(1, linkSubname)); } @@ -465,13 +472,11 @@ void TaskRevolutionParameters::translateFaceName() int faceId = -1; bool ok = false; if (upToFace.indexOf("Face") == 0) { - faceId = upToFace.remove(0,4).toInt(&ok); + faceId = upToFace.remove(0, 4).toInt(&ok); } if (ok) { - ui->lineFaceName->setText(QStringLiteral("%1:%2%3") - .arg(parts[0], tr("Face")) - .arg(faceId)); + ui->lineFaceName->setText(QStringLiteral("%1:%2%3").arg(parts[0], tr("Face")).arg(faceId)); } else { ui->lineFaceName->setText(parts[0]); @@ -529,24 +534,25 @@ void TaskRevolutionParameters::onAxisChanged(int num) return; } - App::DocumentObject *oldRefAxis = propReferenceAxis->getValue(); + App::DocumentObject* oldRefAxis = propReferenceAxis->getValue(); std::vector oldSubRefAxis = propReferenceAxis->getSubValues(); std::string oldRefName; if (!oldSubRefAxis.empty()) { oldRefName = oldSubRefAxis.front(); } - App::PropertyLinkSub &lnk = *(axesInList[num]); + App::PropertyLinkSub& lnk = *(axesInList[num]); if (!lnk.getValue()) { // enter reference selection mode if (auto sketch = dynamic_cast(pcRevolution->Profile.getValue())) { Gui::cmdAppObjectShow(sketch); } - TaskSketchBasedParameters::onSelectReference(AllowSelection::EDGE | - AllowSelection::PLANAR | - AllowSelection::CIRCLE); - } else { - if (!pcRevolution->getDocument()->isIn(lnk.getValue())){ + TaskSketchBasedParameters::onSelectReference( + AllowSelection::EDGE | AllowSelection::PLANAR | AllowSelection::CIRCLE + ); + } + else { + if (!pcRevolution->getDocument()->isIn(lnk.getValue())) { Base::Console().error("Object was deleted\n"); return; } @@ -555,16 +561,15 @@ void TaskRevolutionParameters::onAxisChanged(int num) } try { - App::DocumentObject *newRefAxis = propReferenceAxis->getValue(); - const std::vector &newSubRefAxis = propReferenceAxis->getSubValues(); + App::DocumentObject* newRefAxis = propReferenceAxis->getValue(); + const std::vector& newSubRefAxis = propReferenceAxis->getSubValues(); std::string newRefName; if (!newSubRefAxis.empty()) { newRefName = newSubRefAxis.front(); } - if (oldRefAxis != newRefAxis || - oldSubRefAxis.size() != newSubRefAxis.size() || - oldRefName != newRefName) { + if (oldRefAxis != newRefAxis || oldSubRefAxis.size() != newSubRefAxis.size() + || oldRefName != newRefName) { bool reversed = propReversed->getValue(); if (pcRevolution->isDerivedFrom()) { reversed = static_cast(pcRevolution)->suggestReversed(); @@ -599,9 +604,7 @@ void TaskRevolutionParameters::onMidplane(bool on) recomputeFeature(); if (gizmoContainer) { - rotationGizmo->setMultFactor( - rotationGizmo->getMultFactor() * (on? 0.5: 2) - ); + rotationGizmo->setMultFactor(rotationGizmo->getMultFactor() * (on ? 0.5 : 2)); } } } @@ -624,21 +627,21 @@ void TaskRevolutionParameters::onModeChanged(int index) : &(getObject()->Type); switch (static_cast(index)) { - case PartDesign::Revolution::RevolMethod::Angle: - propEnum->setValue("Angle"); - break; - case PartDesign::Revolution::RevolMethod::ToLast: - propEnum->setValue(isGroove ? "ThroughAll" : "UpToLast"); - break; - case PartDesign::Revolution::RevolMethod::ToFirst: - propEnum->setValue("UpToFirst"); - break; - case PartDesign::Revolution::RevolMethod::ToFace: - propEnum->setValue("UpToFace"); - break; - case PartDesign::Revolution::RevolMethod::TwoAngles: - propEnum->setValue("TwoAngles"); - break; + case PartDesign::Revolution::RevolMethod::Angle: + propEnum->setValue("Angle"); + break; + case PartDesign::Revolution::RevolMethod::ToLast: + propEnum->setValue(isGroove ? "ThroughAll" : "UpToLast"); + break; + case PartDesign::Revolution::RevolMethod::ToFirst: + propEnum->setValue("UpToFirst"); + break; + case PartDesign::Revolution::RevolMethod::ToFace: + propEnum->setValue("UpToFace"); + break; + case PartDesign::Revolution::RevolMethod::TwoAngles: + propEnum->setValue("TwoAngles"); + break; } updateUI(index); @@ -649,20 +652,23 @@ void TaskRevolutionParameters::onModeChanged(int index) } } -void TaskRevolutionParameters::getReferenceAxis(App::DocumentObject*& obj, std::vector& sub) const +void TaskRevolutionParameters::getReferenceAxis( + App::DocumentObject*& obj, + std::vector& sub +) const { if (axesInList.empty()) { throw Base::RuntimeError("Not initialized!"); } int num = ui->axis->currentIndex(); - const App::PropertyLinkSub &lnk = *(axesInList[num]); + const App::PropertyLinkSub& lnk = *(axesInList[num]); if (!lnk.getValue()) { throw Base::RuntimeError("Still in reference selection mode; reference wasn't selected yet"); } auto revolution = getObject(); - if (!revolution->getDocument()->isIn(lnk.getValue())){ + if (!revolution->getDocument()->isIn(lnk.getValue())) { throw Base::RuntimeError("Object was deleted"); } @@ -682,20 +688,20 @@ bool TaskRevolutionParameters::getReversed() const TaskRevolutionParameters::~TaskRevolutionParameters() { - //hide the parts coordinate system axis for selection + // hide the parts coordinate system axis for selection try { if (auto vpOrigin = getOriginView()) { vpOrigin->resetTemporaryVisibility(); } } - catch (const Base::Exception &ex) { + catch (const Base::Exception& ex) { ex.reportException(); } axesInList.clear(); } -void TaskRevolutionParameters::changeEvent(QEvent *event) +void TaskRevolutionParameters::changeEvent(QEvent* event) { TaskBox::changeEvent(event); if (event->type() == QEvent::LanguageChange) { @@ -708,7 +714,7 @@ void TaskRevolutionParameters::changeEvent(QEvent *event) void TaskRevolutionParameters::apply() { - //Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Revolution changed")); + // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Revolution changed")); ui->revolveAngle->apply(); ui->revolveAngle2->apply(); std::vector sub; @@ -722,7 +728,8 @@ void TaskRevolutionParameters::apply() int mode = ui->changeMode->currentIndex(); FCMD_OBJ_CMD(tobj, "Type = " << mode); QString facename = QStringLiteral("None"); - if (static_cast(mode) == PartDesign::Revolution::RevolMethod::ToFace) { + if (static_cast(mode) + == PartDesign::Revolution::RevolMethod::ToFace) { facename = getFaceName(); } FCMD_OBJ_CMD(tobj, "UpToFace = " << facename.toLatin1().data()); @@ -769,7 +776,8 @@ void TaskRevolutionParameters::setGizmoPositions() profile.getCenterOfGravity(profileCog); basePos = groove->Base.getValue(); axisDir = groove->Axis.getValue(); - } else { + } + else { auto revolution = getObject(); if (!revolution || revolution->isError()) { gizmoContainer->visible = false; @@ -828,19 +836,23 @@ void TaskRevolutionParameters::setGizmoVisibility() //************************************************************************** // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgRevolutionParameters::TaskDlgRevolutionParameters(ViewProviderRevolution *RevolutionView) +TaskDlgRevolutionParameters::TaskDlgRevolutionParameters(ViewProviderRevolution* RevolutionView) : TaskDlgSketchBasedParameters(RevolutionView) { assert(RevolutionView); - Content.push_back(new TaskRevolutionParameters(RevolutionView, "PartDesign_Revolution", tr("Revolution Parameters"))); + Content.push_back( + new TaskRevolutionParameters(RevolutionView, "PartDesign_Revolution", tr("Revolution Parameters")) + ); Content.push_back(preview); } -TaskDlgGrooveParameters::TaskDlgGrooveParameters(ViewProviderGroove *GrooveView) +TaskDlgGrooveParameters::TaskDlgGrooveParameters(ViewProviderGroove* GrooveView) : TaskDlgSketchBasedParameters(GrooveView) { assert(GrooveView); - Content.push_back(new TaskRevolutionParameters(GrooveView, "PartDesign_Groove", tr("Groove Parameters"))); + Content.push_back( + new TaskRevolutionParameters(GrooveView, "PartDesign_Groove", tr("Groove Parameters")) + ); Content.push_back(preview); } diff --git a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h index 2930a86f51..cfb07730ba 100644 --- a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h +++ b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h @@ -30,30 +30,35 @@ class Ui_TaskRevolutionParameters; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class RadialGizmo; class Gizmo; class ViewProvider; class ViewProviderCoordinateSystem; -} +} // namespace Gui -namespace PartDesignGui { +namespace PartDesignGui +{ class ViewProviderRevolution; class ViewProviderGroove; -class TaskRevolutionParameters : public TaskSketchBasedParameters +class TaskRevolutionParameters: public TaskSketchBasedParameters { Q_OBJECT public: - TaskRevolutionParameters(ViewProvider* RevolutionView, - const char *pixname, - const QString& title, - QWidget* parent = nullptr); + TaskRevolutionParameters( + ViewProvider* RevolutionView, + const char* pixname, + const QString& title, + QWidget* parent = nullptr + ); ~TaskRevolutionParameters() override; void apply() override; @@ -66,9 +71,11 @@ public: * list (if necessary), and selected. If the list is empty, it will be refilled anyway. */ void fillAxisCombo(bool forceRefill = false); - void addAxisToCombo(App::DocumentObject *linkObj, - const std::string& linkSubname, - const QString& itemText); + void addAxisToCombo( + App::DocumentObject* linkObj, + const std::string& linkSubname, + const QString& itemText + ); private Q_SLOTS: void onAngleChanged(double); @@ -82,8 +89,8 @@ private Q_SLOTS: protected: void onSelectionChanged(const Gui::SelectionChanges& msg) override; - void changeEvent(QEvent *event) override; - void getReferenceAxis(App::DocumentObject *&obj, std::vector &sub) const; + void changeEvent(QEvent* event) override; + void getReferenceAxis(App::DocumentObject*& obj, std::vector& sub) const; bool getMidplane() const; bool getReversed() const; QString getFaceName() const; @@ -91,8 +98,8 @@ protected: void setCheckboxes(PartDesign::Revolution::RevolMethod mode); private: - //mirrors of revolution's or groove's properties - //should have been done by inheriting revolution and groove from common class... + // mirrors of revolution's or groove's properties + // should have been done by inheriting revolution and groove from common class... App::PropertyAngle* propAngle; App::PropertyAngle* propAngle2; App::PropertyBool* propReversed; @@ -111,7 +118,7 @@ private: private: std::unique_ptr ui; - QWidget *proxy; + QWidget* proxy; bool selectionFace; bool isGroove; @@ -134,22 +141,22 @@ private: void setGizmoVisibility(); }; -class TaskDlgRevolutionParameters : public TaskDlgSketchBasedParameters +class TaskDlgRevolutionParameters: public TaskDlgSketchBasedParameters { Q_OBJECT public: - explicit TaskDlgRevolutionParameters(PartDesignGui::ViewProviderRevolution *RevolutionView); + explicit TaskDlgRevolutionParameters(PartDesignGui::ViewProviderRevolution* RevolutionView); }; -class TaskDlgGrooveParameters : public TaskDlgSketchBasedParameters +class TaskDlgGrooveParameters: public TaskDlgSketchBasedParameters { Q_OBJECT public: - explicit TaskDlgGrooveParameters(PartDesignGui::ViewProviderGroove *GrooveView); + explicit TaskDlgGrooveParameters(PartDesignGui::ViewProviderGroove* GrooveView); }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp b/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp index f6996fb076..fb67eb1d4e 100644 --- a/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp @@ -40,16 +40,17 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskScaledParameters */ -TaskScaledParameters::TaskScaledParameters(ViewProviderTransformed* TransformedView, - QWidget* parent) +TaskScaledParameters::TaskScaledParameters(ViewProviderTransformed* TransformedView, QWidget* parent) : TaskTransformedParameters(TransformedView, parent) , ui(new Ui_TaskScaledParameters) { setupUI(); } -TaskScaledParameters::TaskScaledParameters(TaskMultiTransformParameters* parentTask, - QWidget* parameterWidget) +TaskScaledParameters::TaskScaledParameters( + TaskMultiTransformParameters* parentTask, + QWidget* parameterWidget +) : TaskTransformedParameters(parentTask) , ui(new Ui_TaskScaledParameters) { @@ -61,14 +62,18 @@ void TaskScaledParameters::setupParameterUI(QWidget* widget) ui->setupUi(widget); QMetaObject::connectSlotsByName(this); - connect(ui->spinFactor, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &TaskScaledParameters::onFactor); - connect(ui->spinOccurrences, - &Gui::UIntSpinBox::unsignedChanged, - this, - &TaskScaledParameters::onOccurrences); + connect( + ui->spinFactor, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &TaskScaledParameters::onFactor + ); + connect( + ui->spinOccurrences, + &Gui::UIntSpinBox::unsignedChanged, + this, + &TaskScaledParameters::onOccurrences + ); // Get the feature data auto pcScaled = getObject(); diff --git a/src/Mod/PartDesign/Gui/TaskScaledParameters.h b/src/Mod/PartDesign/Gui/TaskScaledParameters.h index 5e64b497c2..1bf47d92e0 100644 --- a/src/Mod/PartDesign/Gui/TaskScaledParameters.h +++ b/src/Mod/PartDesign/Gui/TaskScaledParameters.h @@ -50,8 +50,7 @@ class TaskScaledParameters: public TaskTransformedParameters public: /// Constructor for task with ViewProvider - explicit TaskScaledParameters(ViewProviderTransformed* TransformedView, - QWidget* parent = nullptr); + explicit TaskScaledParameters(ViewProviderTransformed* TransformedView, QWidget* parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskScaledParameters(TaskMultiTransformParameters* parentTask, QWidget* parameterWidget); diff --git a/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp b/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp index 85fc59ff44..eb348243ac 100644 --- a/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp +++ b/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp @@ -21,10 +21,9 @@ ***************************************************************************/ - -# include -# include -# include +#include +#include +#include #include @@ -55,8 +54,12 @@ using namespace Gui; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ TaskShapeBinder::TaskShapeBinder(ViewProviderShapeBinder* view, bool newObj, QWidget* parent) - : Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("PartDesign_ShapeBinder"), - tr("Shape Binder Parameters"), true, parent) + : Gui::TaskView::TaskBox( + Gui::BitmapFactory().pixmap("PartDesign_ShapeBinder"), + tr("Shape Binder Parameters"), + true, + parent + ) , SelectionObserver(view) , ui(new Ui_TaskShapeBinder) , vp(view) @@ -81,11 +84,15 @@ void TaskShapeBinder::updateUI() { Gui::Document* doc = vp->getDocument(); - //add initial values + // add initial values App::GeoFeature* obj = nullptr; std::vector subs; - PartDesign::ShapeBinder::getFilteredReferences(&vp->getObject()->Support, obj, subs); + PartDesign::ShapeBinder::getFilteredReferences( + &vp->getObject()->Support, + obj, + subs + ); if (obj) { ui->baseEdit->setText(QString::fromStdString(obj->Label.getStrValue())); @@ -93,11 +100,11 @@ void TaskShapeBinder::updateUI() // Allow one to clear the Support ui->baseEdit->setClearButtonEnabled(true); - connect(ui->baseEdit, &QLineEdit::textChanged, - this, &TaskShapeBinder::supportChanged); + connect(ui->baseEdit, &QLineEdit::textChanged, this, &TaskShapeBinder::supportChanged); - for (const auto& sub : subs) + for (const auto& sub : subs) { ui->listWidgetReferences->addItem(QString::fromStdString(sub)); + } if (obj) { auto* svp = doc->getViewProvider(obj); @@ -113,14 +120,15 @@ void TaskShapeBinder::setupButtonGroup() buttonGroup = new ButtonGroup(this); buttonGroup->setExclusive(true); - buttonGroup->addButton(ui->buttonRefAdd, - TaskShapeBinder::refAdd); - buttonGroup->addButton(ui->buttonRefRemove, - TaskShapeBinder::refRemove); - buttonGroup->addButton(ui->buttonBase, - TaskShapeBinder::refObjAdd); - connect(buttonGroup, qOverload(&QButtonGroup::buttonToggled), - this, &TaskShapeBinder::onButtonToggled); + buttonGroup->addButton(ui->buttonRefAdd, TaskShapeBinder::refAdd); + buttonGroup->addButton(ui->buttonRefRemove, TaskShapeBinder::refRemove); + buttonGroup->addButton(ui->buttonBase, TaskShapeBinder::refObjAdd); + connect( + buttonGroup, + qOverload(&QButtonGroup::buttonToggled), + this, + &TaskShapeBinder::onButtonToggled + ); } void TaskShapeBinder::setupContextMenu() @@ -147,7 +155,7 @@ void TaskShapeBinder::supportChanged(const QString& text) } } -void TaskShapeBinder::onButtonToggled(QAbstractButton *button, bool checked) +void TaskShapeBinder::onButtonToggled(QAbstractButton* button, bool checked) { int id = buttonGroup->id(button); @@ -157,31 +165,33 @@ void TaskShapeBinder::onButtonToggled(QAbstractButton *button, bool checked) } else { Gui::Selection().clearSelection(); - if (selectionMode == static_cast(id)) + if (selectionMode == static_cast(id)) { selectionMode = TaskShapeBinder::none; + } } switch (id) { - case TaskShapeBinder::refAdd: - case TaskShapeBinder::refRemove: - if (!vp.expired()) - vp->highlightReferences(true); - break; - case TaskShapeBinder::refObjAdd: - break; - default: - break; + case TaskShapeBinder::refAdd: + case TaskShapeBinder::refRemove: + if (!vp.expired()) { + vp->highlightReferences(true); + } + break; + case TaskShapeBinder::refObjAdd: + break; + default: + break; } } void TaskShapeBinder::changeEvent(QEvent*) -{ -} +{} void TaskShapeBinder::deleteItem() { - if (vp.expired()) + if (vp.expired()) { return; + } // Delete the selected spine int row = ui->listWidgetReferences->currentRow(); @@ -232,22 +242,25 @@ void TaskShapeBinder::onSelectionChanged(const Gui::SelectionChanges& msg) } }; - if (selectionMode == none) + if (selectionMode == none) { return; + } if (msg.Type == Gui::SelectionChanges::AddSelection) { if (referenceSelected(msg)) { if (selectionMode == refAdd) { QString sub = QString::fromUtf8(msg.pSubName); - if (!sub.isEmpty()) + if (!sub.isEmpty()) { ui->listWidgetReferences->addItem(sub); + } setObjectLabel(msg); } else if (selectionMode == refRemove) { QString sub = QString::fromUtf8(msg.pSubName); - if (!sub.isEmpty()) + if (!sub.isEmpty()) { removeFromListWidget(ui->listWidgetReferences, sub); + } } else if (selectionMode == refObjAdd) { ui->listWidgetReferences->clear(); @@ -269,28 +282,36 @@ void TaskShapeBinder::onSelectionChanged(const Gui::SelectionChanges& msg) bool TaskShapeBinder::referenceSelected(const SelectionChanges& msg) const { - if (vp.expired()) + if (vp.expired()) { return false; + } - if ((msg.Type == Gui::SelectionChanges::AddSelection) && ( - (selectionMode == refAdd) || (selectionMode == refRemove) || (selectionMode == refObjAdd))) { + if ((msg.Type == Gui::SelectionChanges::AddSelection) + && ((selectionMode == refAdd) || (selectionMode == refRemove) + || (selectionMode == refObjAdd))) { - if (strcmp(msg.pDocName, vp->getObject()->getDocument()->getName()) != 0) + if (strcmp(msg.pDocName, vp->getObject()->getDocument()->getName()) != 0) { return false; + } // not allowed to reference ourself const char* fname = vp->getObject()->getNameInDocument(); - if (strcmp(msg.pObjectName, fname) == 0) + if (strcmp(msg.pObjectName, fname) == 0) { return false; + } - //change the references + // change the references std::string subName(msg.pSubName); Part::Feature* selectedObj = nullptr; App::GeoFeature* obj = nullptr; std::vector refs; - PartDesign::ShapeBinder::getFilteredReferences(&vp->getObject()->Support, obj, refs); + PartDesign::ShapeBinder::getFilteredReferences( + &vp->getObject()->Support, + obj, + refs + ); // get selected object auto docObj = vp->getObject()->getDocument()->getObject(msg.pObjectName); @@ -316,16 +337,20 @@ bool TaskShapeBinder::referenceSelected(const SelectionChanges& msg) const const auto f = std::ranges::find(refs, subName); if (selectionMode == refAdd) { - if (f == refs.end()) + if (f == refs.end()) { refs.push_back(subName); - else - return false; // duplicate selection + } + else { + return false; // duplicate selection + } } else { - if (f != refs.end()) + if (f != refs.end()) { refs.erase(f); - else + } + else { return false; + } } } else { @@ -342,14 +367,16 @@ bool TaskShapeBinder::referenceSelected(const SelectionChanges& msg) const return false; } -void TaskShapeBinder::clearButtons() { +void TaskShapeBinder::clearButtons() +{ ui->buttonRefAdd->setChecked(false); ui->buttonRefRemove->setChecked(false); ui->buttonBase->setChecked(false); } -void TaskShapeBinder::exitSelectionMode() { +void TaskShapeBinder::exitSelectionMode() +{ selectionMode = none; Gui::Selection().clearSelection(); @@ -357,15 +384,20 @@ void TaskShapeBinder::exitSelectionMode() { void TaskShapeBinder::accept() { - if (vp.expired()) + if (vp.expired()) { return; + } std::string label = ui->baseEdit->text().toStdString(); PartDesign::ShapeBinder* binder = vp->getObject(); if (!binder->Support.getValue() && !label.empty()) { auto mode = selectionMode; selectionMode = refObjAdd; - SelectionChanges msg(SelectionChanges::AddSelection, binder->getDocument()->getName(), label.c_str()); + SelectionChanges msg( + SelectionChanges::AddSelection, + binder->getDocument()->getName(), + label.c_str() + ); referenceSelected(msg); selectionMode = mode; } @@ -395,14 +427,19 @@ bool TaskDlgShapeBinder::accept() parameter->accept(); Gui::cmdAppDocument(vp->getObject(), "recompute()"); - if (!vp->getObject()->isValid()) + if (!vp->getObject()->isValid()) { throw Base::RuntimeError(vp->getObject()->getStatusString()); + } Gui::cmdGuiDocument(vp->getObject(), "resetEdit()"); Gui::Command::commitCommand(); } } catch (const Base::Exception& e) { - QMessageBox::warning(parameter, tr("Input error"), QApplication::translate("Exception", e.what())); + QMessageBox::warning( + parameter, + tr("Input error"), + QApplication::translate("Exception", e.what()) + ); return false; } diff --git a/src/Mod/PartDesign/Gui/TaskShapeBinder.h b/src/Mod/PartDesign/Gui/TaskShapeBinder.h index 9675bb66c0..51b6409a6f 100644 --- a/src/Mod/PartDesign/Gui/TaskShapeBinder.h +++ b/src/Mod/PartDesign/Gui/TaskShapeBinder.h @@ -33,42 +33,54 @@ class Ui_TaskShapeBinder; class QListWidget; -namespace App { +namespace App +{ class Property; } -namespace Gui { +namespace Gui +{ class ButtonGroup; class ViewProvider; -} +} // namespace Gui -namespace PartDesignGui { +namespace PartDesignGui +{ - -class TaskShapeBinder : public Gui::TaskView::TaskBox, Gui::SelectionObserver +class TaskShapeBinder: public Gui::TaskView::TaskBox, Gui::SelectionObserver { Q_OBJECT public: - explicit TaskShapeBinder(ViewProviderShapeBinder *view,bool newObj=false,QWidget *parent = nullptr); + explicit TaskShapeBinder( + ViewProviderShapeBinder* view, + bool newObj = false, + QWidget* parent = nullptr + ); ~TaskShapeBinder() override; void accept(); protected: - enum selectionModes { none, refAdd, refRemove, refObjAdd }; - void changeEvent(QEvent *e) override; + enum selectionModes + { + none, + refAdd, + refRemove, + refObjAdd + }; + void changeEvent(QEvent* e) override; selectionModes selectionMode = none; - void removeFromListWidget(QListWidget *w, QString name); + void removeFromListWidget(QListWidget* w, QString name); bool referenceSelected(const Gui::SelectionChanges& msg) const; private: void setupButtonGroup(); void setupContextMenu(); void onSelectionChanged(const Gui::SelectionChanges& msg) override; - void onButtonToggled(QAbstractButton *button, bool checked); + void onButtonToggled(QAbstractButton* button, bool checked); void updateUI(); void supportChanged(const QString&); void clearButtons(); @@ -80,18 +92,18 @@ private: private: QWidget* proxy; std::unique_ptr ui; - Gui::ButtonGroup *buttonGroup; + Gui::ButtonGroup* buttonGroup; Gui::WeakPtrT vp; }; /// simulation dialog for the TaskView -class TaskDlgShapeBinder : public Gui::TaskView::TaskDialog +class TaskDlgShapeBinder: public Gui::TaskView::TaskDialog { Q_OBJECT public: - explicit TaskDlgShapeBinder(ViewProviderShapeBinder *view,bool newObj=false); + explicit TaskDlgShapeBinder(ViewProviderShapeBinder* view, bool newObj = false); ~TaskDlgShapeBinder() override; public: @@ -101,10 +113,10 @@ public: bool reject() override; protected: - TaskShapeBinder *parameter; + TaskShapeBinder* parameter; Gui::WeakPtrT vp; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TASKAPPERANCE_H +#endif // GUI_TASKVIEW_TASKAPPERANCE_H diff --git a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp index c29c70b1b5..5a32d5cb46 100644 --- a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp @@ -22,10 +22,9 @@ ***************************************************************************/ - -# include -# include -# include +#include +#include +#include #include @@ -48,15 +47,22 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskSketchBasedParameters */ -TaskSketchBasedParameters::TaskSketchBasedParameters(PartDesignGui::ViewProvider *vp, QWidget *parent, - const std::string& pixmapname, const QString& parname) +TaskSketchBasedParameters::TaskSketchBasedParameters( + PartDesignGui::ViewProvider* vp, + QWidget* parent, + const std::string& pixmapname, + const QString& parname +) : TaskFeatureParameters(vp, parent, pixmapname, parname) { // disable selection this->blockSelection(true); } -const QString TaskSketchBasedParameters::onAddSelection(const Gui::SelectionChanges& msg, App::PropertyLinkSub& prop) +const QString TaskSketchBasedParameters::onAddSelection( + const Gui::SelectionChanges& msg, + App::PropertyLinkSub& prop +) { // Note: The validity checking has already been done in ReferenceSelection.cpp auto sketchBased = getObject(); @@ -75,18 +81,18 @@ const QString TaskSketchBasedParameters::onAddSelection(const Gui::SelectionChan } else if (subname.size() > 4) { int faceId = std::atoi(&subname[4]); - refStr = QString::fromLatin1(selObj->getNameInDocument()) + QStringLiteral(":") + QObject::tr("Face") + QString::number(faceId); + refStr = QString::fromLatin1(selObj->getNameInDocument()) + QStringLiteral(":") + + QObject::tr("Face") + QString::number(faceId); } - std::vector upToFaces(1,subname); + std::vector upToFaces(1, subname); prop.setValue(selObj, upToFaces); recomputeFeature(); return refStr; } -void TaskSketchBasedParameters::startReferenceSelection(App::DocumentObject*, - App::DocumentObject* base) +void TaskSketchBasedParameters::startReferenceSelection(App::DocumentObject*, App::DocumentObject* base) { const auto* bodyViewProvider = getViewObject()->getBodyViewProvider(); @@ -105,8 +111,7 @@ void TaskSketchBasedParameters::startReferenceSelection(App::DocumentObject*, } } -void TaskSketchBasedParameters::finishReferenceSelection(App::DocumentObject*, - App::DocumentObject* base) +void TaskSketchBasedParameters::finishReferenceSelection(App::DocumentObject*, App::DocumentObject* base) { if (!previouslyVisibleViewProvider) { return; @@ -127,7 +132,7 @@ void TaskSketchBasedParameters::onSelectReference(AllowSelectionFlags allow) // Note: Even if there is no solid, App::Plane and Part::Datum can still be selected if (auto sketchBased = getObject()) { // The solid this feature will be fused to - App::DocumentObject* prevSolid = sketchBased->getBaseObject( /* silent =*/ true ); + App::DocumentObject* prevSolid = sketchBased->getBaseObject(/* silent =*/true); if (AllowSelectionFlags::Int(allow) != int(AllowSelection::NONE)) { startReferenceSelection(sketchBased, prevSolid); @@ -151,8 +156,9 @@ void TaskSketchBasedParameters::exitSelectionMode() QVariant TaskSketchBasedParameters::setUpToFace(const QString& text) { - if (text.isEmpty()) + if (text.isEmpty()) { return {}; + } QStringList parts = text.split(QChar::fromLatin1(':')); if (parts.length() < 2) { @@ -203,8 +209,7 @@ QVariant TaskSketchBasedParameters::setUpToFace(const QString& text) return QByteArray(ss.str().c_str()); } -QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label, - const QVariant& suggest) const +QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label, const QVariant& suggest) const { // search for an object with the given label App::Document* doc = getAppDocument(); @@ -229,7 +234,7 @@ QVariant TaskSketchBasedParameters::objectNameByLabel(const QString& label, } } - return {}; // no such feature found + return {}; // no such feature found } QString TaskSketchBasedParameters::getFaceReference(const QString& obj, const QString& sub) const @@ -245,11 +250,13 @@ QString TaskSketchBasedParameters::getFaceReference(const QString& obj, const QS } return QString::fromLatin1(R"((App.getDocument("%1").%2, ["%3"]))") - .arg(QString::fromLatin1(doc->getName()), o, sub); + .arg(QString::fromLatin1(doc->getName()), o, sub); } -QString TaskSketchBasedParameters::make2DLabel(const App::DocumentObject* section, - const std::vector& subValues) +QString TaskSketchBasedParameters::make2DLabel( + const App::DocumentObject* section, + const std::vector& subValues +) { if (section->isDerivedFrom()) { return QString::fromUtf8(section->Label.getValue()); @@ -274,10 +281,9 @@ TaskSketchBasedParameters::~TaskSketchBasedParameters() // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgSketchBasedParameters::TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp) +TaskDlgSketchBasedParameters::TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider* vp) : TaskDlgFeatureParameters(vp) -{ -} +{} TaskDlgSketchBasedParameters::~TaskDlgSketchBasedParameters() = default; diff --git a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h index 0e476e3597..88afab51ef 100644 --- a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h +++ b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h @@ -31,27 +31,33 @@ #include "TaskFeatureParameters.h" #include "EnumFlags.h" -namespace App { +namespace App +{ class Property; class PropertyLinkSubList; -} +} // namespace App -namespace PartDesignGui { +namespace PartDesignGui +{ /// Convenience class to collect common methods for all SketchBased features -class TaskSketchBasedParameters : public PartDesignGui::TaskFeatureParameters, - public Gui::SelectionObserver +class TaskSketchBasedParameters: public PartDesignGui::TaskFeatureParameters, + public Gui::SelectionObserver { Q_OBJECT public: - TaskSketchBasedParameters(PartDesignGui::ViewProvider* vp, QWidget *parent, - const std::string& pixmapname, const QString& parname); + TaskSketchBasedParameters( + PartDesignGui::ViewProvider* vp, + QWidget* parent, + const std::string& pixmapname, + const QString& parname + ); ~TaskSketchBasedParameters() override; protected: - void onSelectionChanged(const Gui::SelectionChanges& msg) override =0; + void onSelectionChanged(const Gui::SelectionChanges& msg) override = 0; const QString onAddSelection(const Gui::SelectionChanges& msg, App::PropertyLinkSub& prop); virtual void startReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base); virtual void finishReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base); @@ -71,19 +77,18 @@ protected: QString getFaceReference(const QString& obj, const QString& sub) const; /// Create a label for the 2D feature: the objects name if it's already 2D, /// or the subelement's name if the object is a solid. - QString make2DLabel(const App::DocumentObject* section, - const std::vector& subValues); + QString make2DLabel(const App::DocumentObject* section, const std::vector& subValues); private: Gui::ViewProvider* previouslyVisibleViewProvider {nullptr}; }; -class TaskDlgSketchBasedParameters : public PartDesignGui::TaskDlgFeatureParameters +class TaskDlgSketchBasedParameters: public PartDesignGui::TaskDlgFeatureParameters { Q_OBJECT public: - explicit TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp); + explicit TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider* vp); ~TaskDlgSketchBasedParameters() override; public: @@ -93,6 +98,6 @@ public: bool reject() override; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskSketchBasedParameters_H +#endif // GUI_TASKVIEW_TaskSketchBasedParameters_H diff --git a/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp b/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp index 9ab7dec603..a9ab9d2264 100644 --- a/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskThicknessParameters.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -139,7 +138,8 @@ void TaskThicknessParameters::onSelectionChanged(const Gui::SelectionChanges& ms if (selectionMode == refSel) { referenceSelected(msg, ui->listWidgetReferences); } - } else if (msg.Type == Gui::SelectionChanges::ClrSelection) { + } + else if (msg.Type == Gui::SelectionChanges::ClrSelection) { // TODO: the gizmo position should be only recalculated when the feature associated // with the gizmo is removed from the list setGizmoPositions(); @@ -304,7 +304,7 @@ void TaskThicknessParameters::setGizmoPositions() Part::TopoShape edge = shapes[0]; DraggerPlacementProps props = getDraggerPlacementFromEdgeAndFace(edge, faces[0]); - props.dir *= thickness->Reversed.getValue()? 1 : -1; + props.dir *= thickness->Reversed.getValue() ? 1 : -1; linearGizmo->Gizmo::setDraggerPlacement(props.position, props.dir); } diff --git a/src/Mod/PartDesign/Gui/TaskThicknessParameters.h b/src/Mod/PartDesign/Gui/TaskThicknessParameters.h index cc14ce5055..73c1f5db99 100644 --- a/src/Mod/PartDesign/Gui/TaskThicknessParameters.h +++ b/src/Mod/PartDesign/Gui/TaskThicknessParameters.h @@ -31,10 +31,11 @@ class Ui_TaskThicknessParameters; -namespace Gui { +namespace Gui +{ class LinearGizmo; class GizmoContainer; -} +} // namespace Gui namespace PartDesign { diff --git a/src/Mod/PartDesign/Gui/TaskTransformedMessages.cpp b/src/Mod/PartDesign/Gui/TaskTransformedMessages.cpp index 2e94586687..a53adc247a 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedMessages.cpp +++ b/src/Mod/PartDesign/Gui/TaskTransformedMessages.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include "ui_TaskTransformedMessages.h" @@ -32,8 +31,13 @@ using namespace PartDesignGui; using namespace Gui::TaskView; namespace sp = std::placeholders; -TaskTransformedMessages::TaskTransformedMessages(ViewProviderTransformed *transformedView_) - : TaskBox(Gui::BitmapFactory().pixmap("Part_Transformed_Copy"), tr("Transformed Feature Messages"), true, nullptr) +TaskTransformedMessages::TaskTransformedMessages(ViewProviderTransformed* transformedView_) + : TaskBox( + Gui::BitmapFactory().pixmap("Part_Transformed_Copy"), + tr("Transformed Feature Messages"), + true, + nullptr + ) , transformedView(transformedView_) , ui(new Ui_TaskTransformedMessages) { @@ -48,11 +52,11 @@ TaskTransformedMessages::TaskTransformedMessages(ViewProviderTransformed *transf this->groupLayout()->addWidget(proxy); ui->labelTransformationStatus->setText(transformedView->getMessage()); - //NOLINTBEGIN + // NOLINTBEGIN connectionDiagnosis = transformedView->signalDiagnosis.connect( std::bind(&PartDesignGui::TaskTransformedMessages::slotDiagnosis, this, sp::_1) ); - //NOLINTEND + // NOLINTEND } TaskTransformedMessages::~TaskTransformedMessages() diff --git a/src/Mod/PartDesign/Gui/TaskTransformedMessages.h b/src/Mod/PartDesign/Gui/TaskTransformedMessages.h index 4f4f4697c7..4319be79c5 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedMessages.h +++ b/src/Mod/PartDesign/Gui/TaskTransformedMessages.h @@ -29,20 +29,22 @@ class Ui_TaskTransformedMessages; using Connection = boost::signals2::connection; -namespace App { +namespace App +{ class Property; } -namespace PartDesignGui { +namespace PartDesignGui +{ class ViewProviderTransformed; -class TaskTransformedMessages : public Gui::TaskView::TaskBox +class TaskTransformedMessages: public Gui::TaskView::TaskBox { Q_OBJECT public: - explicit TaskTransformedMessages(ViewProviderTransformed *transformedView); + explicit TaskTransformedMessages(ViewProviderTransformed* transformedView); ~TaskTransformedMessages() override; void slotDiagnosis(QString msg); @@ -50,7 +52,7 @@ public: private Q_SLOTS: protected: - ViewProviderTransformed *transformedView; + ViewProviderTransformed* transformedView; Connection connectionDiagnosis; private: @@ -58,6 +60,6 @@ private: std::unique_ptr ui; }; -} //namespace PartDesignGui +} // namespace PartDesignGui -#endif // GUI_TASKVIEW_TaskTransformedMessages_H +#endif // GUI_TASKVIEW_TaskTransformedMessages_H diff --git a/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp b/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp index 152deb1afc..c6e208a8ac 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp @@ -53,12 +53,16 @@ using namespace Gui; /* TRANSLATOR PartDesignGui::TaskTransformedParameters */ -TaskTransformedParameters::TaskTransformedParameters(ViewProviderTransformed* TransformedView, - QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap(TransformedView->featureIcon().c_str()), - TransformedView->menuName, - true, - parent) +TaskTransformedParameters::TaskTransformedParameters( + ViewProviderTransformed* TransformedView, + QWidget* parent +) + : TaskBox( + Gui::BitmapFactory().pixmap(TransformedView->featureIcon().c_str()), + TransformedView->menuName, + true, + parent + ) , TransformedView(TransformedView) , ui(new Ui_TaskTransformedParameters) { @@ -90,14 +94,18 @@ void TaskTransformedParameters::setupUI() ui->setupUi(proxy); QMetaObject::connectSlotsByName(this); - connect(ui->buttonAddFeature, - &QToolButton::toggled, - this, - &TaskTransformedParameters::onButtonAddFeature); - connect(ui->buttonRemoveFeature, - &QToolButton::toggled, - this, - &TaskTransformedParameters::onButtonRemoveFeature); + connect( + ui->buttonAddFeature, + &QToolButton::toggled, + this, + &TaskTransformedParameters::onButtonAddFeature + ); + connect( + ui->buttonRemoveFeature, + &QToolButton::toggled, + this, + &TaskTransformedParameters::onButtonRemoveFeature + ); // Create context menu auto action = new QAction(tr("Remove"), this); @@ -108,15 +116,14 @@ void TaskTransformedParameters::setupUI() ui->listWidgetFeatures->addAction(action); connect(action, &QAction::triggered, this, &TaskTransformedParameters::onFeatureDeleted); ui->listWidgetFeatures->setContextMenuPolicy(Qt::ActionsContextMenu); - connect(ui->listWidgetFeatures->model(), - &QAbstractListModel::rowsMoved, - this, - &TaskTransformedParameters::indexesMoved); + connect( + ui->listWidgetFeatures->model(), + &QAbstractListModel::rowsMoved, + this, + &TaskTransformedParameters::indexesMoved + ); - connect(ui->checkBoxUpdateView, - &QCheckBox::toggled, - this, - &TaskTransformedParameters::onUpdateView); + connect(ui->checkBoxUpdateView, &QCheckBox::toggled, this, &TaskTransformedParameters::onUpdateView); // Get the feature data auto pcTransformed = getObject(); @@ -126,10 +133,7 @@ void TaskTransformedParameters::setupUI() ui->buttonGroupMode->setId(ui->radioTransformBody, static_cast(Mode::WholeShape)); ui->buttonGroupMode->setId(ui->radioTransformToolShapes, static_cast(Mode::Features)); - connect(ui->buttonGroupMode, - &QButtonGroup::idClicked, - this, - &TaskTransformedParameters::onModeChanged); + connect(ui->buttonGroupMode, &QButtonGroup::idClicked, this, &TaskTransformedParameters::onModeChanged); auto const mode = static_cast(pcTransformed->TransformMode.getValue()); ui->groupFeatureList->setEnabled(mode == Mode::Features); @@ -224,8 +228,7 @@ bool TaskTransformedParameters::originalSelected(const Gui::SelectionChanges& ms } PartDesign::Transformed* pcTransformed = getObject(); - App::DocumentObject* selectedObject = - pcTransformed->getDocument()->getObject(msg.pObjectName); + App::DocumentObject* selectedObject = pcTransformed->getDocument()->getObject(msg.pObjectName); if (selectedObject->isDerivedFrom()) { // Do the same like in TaskDlgTransformedParameters::accept() but without doCommand @@ -380,8 +383,7 @@ void TaskTransformedParameters::onFeatureDeleted() recomputeFeature(); } -void TaskTransformedParameters::removeItemFromListWidget(QListWidget* widget, - const QString& itemstr) +void TaskTransformedParameters::removeItemFromListWidget(QListWidget* widget, const QString& itemstr) { QList items = widget->findItems(itemstr, Qt::MatchExactly); if (!items.empty()) { @@ -428,8 +430,7 @@ void TaskTransformedParameters::fillAxisCombo(Gui::ComboLinks& combolinks, Part: combolinks.addLink(nullptr, std::string(), tr("Select reference…")); } -void TaskTransformedParameters::fillPlanesCombo(Gui::ComboLinks& combolinks, - Part::Part2DObject* sketch) +void TaskTransformedParameters::fillPlanesCombo(Gui::ComboLinks& combolinks, Part::Part2DObject* sketch) { combolinks.clear(); @@ -577,9 +578,11 @@ void TaskTransformedParameters::exitSelectionMode() void TaskTransformedParameters::addReferenceSelectionGate(AllowSelectionFlags allow) { std::unique_ptr gateRefPtr( - new ReferenceSelection(getBaseObject(), allow)); + new ReferenceSelection(getBaseObject(), allow) + ); std::unique_ptr gateDepPtr( - new NoDependentsSelection(getTopTransformedObject())); + new NoDependentsSelection(getTopTransformedObject()) + ); Gui::Selection().addSelectionGate(new CombineSelectionFilterGates(gateRefPtr, gateDepPtr)); } @@ -613,8 +616,7 @@ void TaskTransformedParameters::indexesMoved() TaskDlgTransformedParameters::TaskDlgTransformedParameters(ViewProviderTransformed* viewProvider) : TaskDlgFeatureParameters(viewProvider) -{ -} +{} //==== calls from the TaskView =============================================================== diff --git a/src/Mod/PartDesign/Gui/TaskTransformedParameters.h b/src/Mod/PartDesign/Gui/TaskTransformedParameters.h index 2aab1f5a5a..79c5538760 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedParameters.h +++ b/src/Mod/PartDesign/Gui/TaskTransformedParameters.h @@ -70,8 +70,10 @@ class TaskTransformedParameters: public Gui::TaskView::TaskBox, public: /// Constructor for task with ViewProvider - explicit TaskTransformedParameters(ViewProviderTransformed* TransformedView, - QWidget* parent = nullptr); + explicit TaskTransformedParameters( + ViewProviderTransformed* TransformedView, + QWidget* parent = nullptr + ); /// Constructor for task with parent task (MultiTransform mode) explicit TaskTransformedParameters(TaskMultiTransformParameters* parentTask); ~TaskTransformedParameters() override; @@ -105,8 +107,11 @@ protected: */ PartDesign::Transformed* getObject() const; - template - T* getObject() const { return freecad_cast(getObject()); } + template + T* getObject() const + { + return freecad_cast(getObject()); + } /// Get the sketch object of the first original either of the object associated with this /// feature or with the parent feature (MultiTransform mode) diff --git a/src/Mod/PartDesign/Gui/Utils.cpp b/src/Mod/PartDesign/Gui/Utils.cpp index ac217d45e6..4a3e7ed1d8 100644 --- a/src/Mod/PartDesign/Gui/Utils.cpp +++ b/src/Mod/PartDesign/Gui/Utils.cpp @@ -22,8 +22,8 @@ #include -# include -# include +#include +#include #include @@ -44,14 +44,15 @@ #include "WorkflowManager.h" -FC_LOG_LEVEL_INIT("PartDesignGui",true,true) +FC_LOG_LEVEL_INIT("PartDesignGui", true, true) //=========================================================================== // Helper for Body //=========================================================================== using namespace Attacher; -namespace PartDesignGui { +namespace PartDesignGui +{ // TODO: Refactor DocumentObjectItem::getSubName() that has similar logic App::DocumentObject* getParent(App::DocumentObject* obj, std::string& subname) @@ -70,7 +71,8 @@ App::DocumentObject* getParent(App::DocumentObject* obj, std::string& subname) return obj; } -bool setEdit(App::DocumentObject *obj, PartDesign::Body *body) { +bool setEdit(App::DocumentObject* obj, PartDesign::Body* body) +{ if (!obj || !obj->isAttachedToDocument()) { FC_ERR("invalid object"); return false; @@ -82,10 +84,11 @@ bool setEdit(App::DocumentObject *obj, PartDesign::Body *body) { return false; } } - auto *activeView = Gui::Application::Instance->activeView(); - if (!activeView) + auto* activeView = Gui::Application::Instance->activeView(); + if (!activeView) { return false; - App::DocumentObject *parent = nullptr; + } + App::DocumentObject* parent = nullptr; std::string subname; auto activeBody = activeView->getActiveObject(PDBODYKEY, &parent, &subname); if (activeBody != body) { @@ -97,9 +100,11 @@ bool setEdit(App::DocumentObject *obj, PartDesign::Body *body) { subname += '.'; } - Gui::cmdGuiDocument(parent, std::ostringstream() << "setEdit(" - << Gui::Command::getObjectCmd(parent) - << ", 0, '" << subname << "')"); + Gui::cmdGuiDocument( + parent, + std::ostringstream() << "setEdit(" << Gui::Command::getObjectCmd(parent) << ", 0, '" + << subname << "')" + ); return true; } @@ -111,22 +116,27 @@ bool setEdit(App::DocumentObject *obj, PartDesign::Body *body) { * \param autoActivate * \return Body */ -PartDesign::Body *getBody(bool messageIfNot, bool autoActivate, bool assertModern, - App::DocumentObject **topParent, std::string *subname) +PartDesign::Body* getBody( + bool messageIfNot, + bool autoActivate, + bool assertModern, + App::DocumentObject** topParent, + std::string* subname +) { - PartDesign::Body * activeBody = nullptr; - Gui::MDIView *activeView = Gui::Application::Instance->activeView(); + PartDesign::Body* activeBody = nullptr; + Gui::MDIView* activeView = Gui::Application::Instance->activeView(); if (activeView) { auto doc = activeView->getAppDocument(); bool singleBodyDocument = doc->countObjectsOfType() == 1; if (assertModern) { - activeBody = activeView->getActiveObject(PDBODYKEY,topParent,subname); + activeBody = activeView->getActiveObject(PDBODYKEY, topParent, subname); if (!activeBody && singleBodyDocument && autoActivate) { auto bodies = doc->getObjectsOfType(PartDesign::Body::getClassTypeId()); - App::DocumentObject *body = nullptr; - if(bodies.size()==1) { + App::DocumentObject* body = nullptr; + if (bodies.size() == 1) { body = bodies[0]; activeBody = makeBodyActive(body, doc, topParent, subname); } @@ -135,12 +145,16 @@ PartDesign::Body *getBody(bool messageIfNot, bool autoActivate, bool assertModer DlgActiveBody dia( Gui::getMainWindow(), doc, - QObject::tr("To use Part Design, an active body is required in the document. " - "Activate a body (double-click) or create a new one." - "\n\nFor legacy documents with Part Design objects lacking a body, " - "use the migrate function in Part Design to place them into a body.")); - if (dia.exec() == QDialog::DialogCode::Accepted) + QObject::tr( + "To use Part Design, an active body is required in the document. " + "Activate a body (double-click) or create a new one." + "\n\nFor legacy documents with Part Design objects lacking a body, " + "use the migrate function in Part Design to place them into a body." + ) + ); + if (dia.exec() == QDialog::DialogCode::Accepted) { activeBody = dia.getActiveBody(); + } } } } @@ -148,17 +162,21 @@ PartDesign::Body *getBody(bool messageIfNot, bool autoActivate, bool assertModer return activeBody; } -PartDesign::Body * makeBodyActive(App::DocumentObject *body, App::Document *doc, - App::DocumentObject **topParent, - std::string *subname) +PartDesign::Body* makeBodyActive( + App::DocumentObject* body, + App::Document* doc, + App::DocumentObject** topParent, + std::string* subname +) { - App::DocumentObject *parent = nullptr; + App::DocumentObject* parent = nullptr; std::string sub; - for(auto &v : body->getParents()) { - if(v.first->getDocument()!=doc) + for (auto& v : body->getParents()) { + if (v.first->getDocument() != doc) { continue; - if(parent) { + } + if (parent) { body = nullptr; break; } @@ -166,14 +184,16 @@ PartDesign::Body * makeBodyActive(App::DocumentObject *body, App::Document *doc, sub = v.second; } - if(body) { - auto _doc = parent?parent->getDocument():body->getDocument(); - Gui::cmdGuiDocument(_doc, std::stringstream() - << "ActiveView.setActiveObject('" << PDBODYKEY - << "'," << Gui::Command::getObjectCmd(parent?parent:body) - << ",'" << sub << "')"); - return Gui::Application::Instance->activeView()-> - getActiveObject(PDBODYKEY,topParent,subname); + if (body) { + auto _doc = parent ? parent->getDocument() : body->getDocument(); + Gui::cmdGuiDocument( + _doc, + std::stringstream() << "ActiveView.setActiveObject('" << PDBODYKEY << "'," + << Gui::Command::getObjectCmd(parent ? parent : body) << ",'" << sub + << "')" + ); + return Gui::Application::Instance->activeView() + ->getActiveObject(PDBODYKEY, topParent, subname); } return dynamic_cast(body); @@ -181,280 +201,342 @@ PartDesign::Body * makeBodyActive(App::DocumentObject *body, App::Document *doc, void needActiveBodyError() { - QMessageBox::warning( Gui::getMainWindow(), + QMessageBox::warning( + Gui::getMainWindow(), QObject::tr("Active Body Required"), - QObject::tr("To create a new Part Design object, an active body is required in the document. " - "Activate an existing body (double-click) or create a new one.")); + QObject::tr( + "To create a new Part Design object, an active body is required in the document. " + "Activate an existing body (double-click) or create a new one." + ) + ); } -PartDesign::Body * makeBody(App::Document *doc) +PartDesign::Body* makeBody(App::Document* doc) { - Base::Reference hGrp = App::GetApplication() - .GetUserParameter() - .GetGroup("BaseApp/Preferences/Mod/PartDesign"); + Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup( + "BaseApp/Preferences/Mod/PartDesign" + ); bool allowCompound = hGrp->GetBool("AllowCompoundDefault", true); // This is intended as a convenience when starting a new document. - auto bodyName( doc->getUniqueObjectName("Body") ); - Gui::Command::doCommand( Gui::Command::Doc, - "App.getDocument('%s').addObject('PartDesign::Body','%s')", - doc->getName(), bodyName.c_str() ); - Gui::Command::doCommand( Gui::Command::Doc, - "App.getDocument('%s').getObject('%s').AllowCompound = %s", - doc->getName(), bodyName.c_str(), allowCompound ? "True" : "False" ); + auto bodyName(doc->getUniqueObjectName("Body")); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').addObject('PartDesign::Body','%s')", + doc->getName(), + bodyName.c_str() + ); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.getDocument('%s').getObject('%s').AllowCompound = %s", + doc->getName(), + bodyName.c_str(), + allowCompound ? "True" : "False" + ); auto body = dynamic_cast(doc->getObject(bodyName.c_str())); - if(body) + if (body) { makeBodyActive(body, doc); + } return body; } -PartDesign::Body *getBodyFor(const App::DocumentObject* obj, bool messageIfNot, - bool autoActivate, bool assertModern, - App::DocumentObject **topParent, std::string *subname) +PartDesign::Body* getBodyFor( + const App::DocumentObject* obj, + bool messageIfNot, + bool autoActivate, + bool assertModern, + App::DocumentObject** topParent, + std::string* subname +) { - if(!obj) + if (!obj) { return nullptr; + } - PartDesign::Body * rv = getBody(/*messageIfNot =*/false, autoActivate, assertModern, topParent, subname); - if (rv && rv->hasObject(obj)) + PartDesign::Body* rv + = getBody(/*messageIfNot =*/false, autoActivate, assertModern, topParent, subname); + if (rv && rv->hasObject(obj)) { return rv; + } rv = PartDesign::Body::findBodyOf(obj); if (rv) { return rv; } - if (messageIfNot){ - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Feature is not in a body"), - QObject::tr("In order to use this feature it needs to belong to a body object in the document.")); + if (messageIfNot) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Feature is not in a body"), + QObject::tr( + "In order to use this feature it needs to belong to a body object in the document." + ) + ); } return nullptr; } -App::Part* getActivePart() { - Gui::MDIView *activeView = Gui::Application::Instance->activeView(); - if ( activeView ) { - return activeView->getActiveObject (PARTKEY); - } else { +App::Part* getActivePart() +{ + Gui::MDIView* activeView = Gui::Application::Instance->activeView(); + if (activeView) { + return activeView->getActiveObject(PARTKEY); + } + else { return nullptr; } } -App::Part* getPartFor(const App::DocumentObject* obj, bool messageIfNot) { +App::Part* getPartFor(const App::DocumentObject* obj, bool messageIfNot) +{ - if(!obj) + if (!obj) { return nullptr; + } PartDesign::Body* body = getBodyFor(obj, false); - if(body) + if (body) { obj = body; + } - //get the part - for(App::Part* p : obj->getDocument()->getObjectsOfType()) { - if(p->hasObject(obj)) { + // get the part + for (App::Part* p : obj->getDocument()->getObjectsOfType()) { + if (p->hasObject(obj)) { return p; } } - if (messageIfNot){ - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Feature is not in a part"), - QObject::tr("In order to use this feature it needs to belong to a part object in the document.")); + if (messageIfNot) { + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Feature is not in a part"), + QObject::tr( + "In order to use this feature it needs to belong to a part object in the document." + ) + ); } return nullptr; } -//static void buildDefaultPartAndBody(const App::Document* doc) +// static void buildDefaultPartAndBody(const App::Document* doc) //{ -// // This adds both the base planes and the body -// std::string PartName = doc->getUniqueObjectName("Part"); -// //// create a PartDesign Part for now, can be later any kind of Part or an empty one -// Gui::Command::addModule(Gui::Command::Doc, "PartDesignGui"); -// Gui::Command::doCommand(Gui::Command::Doc, "App.activeDocument().Tip = App.activeDocument().addObject('App::Part','%s')", PartName.c_str()); -// Gui::Command::doCommand(Gui::Command::Doc, "PartDesignGui.setUpPart(App.activeDocument().%s)", PartName.c_str()); -// Gui::Command::doCommand(Gui::Command::Gui, "Gui.activeView().setActiveObject('Part',App.activeDocument().%s)", PartName.c_str()); -//} +// // This adds both the base planes and the body +// std::string PartName = doc->getUniqueObjectName("Part"); +// //// create a PartDesign Part for now, can be later any kind of Part or an empty one +// Gui::Command::addModule(Gui::Command::Doc, "PartDesignGui"); +// Gui::Command::doCommand(Gui::Command::Doc, "App.activeDocument().Tip = +// App.activeDocument().addObject('App::Part','%s')", PartName.c_str()); +// Gui::Command::doCommand(Gui::Command::Doc, "PartDesignGui.setUpPart(App.activeDocument().%s)", +// PartName.c_str()); Gui::Command::doCommand(Gui::Command::Gui, +// "Gui.activeView().setActiveObject('Part',App.activeDocument().%s)", PartName.c_str()); +// } -void fixSketchSupport (Sketcher::SketchObject* sketch) +void fixSketchSupport(Sketcher::SketchObject* sketch) { App::DocumentObject* support = sketch->AttachmentSupport.getValue(); - if (support) - return; // Sketch is on a face of a solid, do nothing + if (support) { + return; // Sketch is on a face of a solid, do nothing + } const App::Document* doc = sketch->getDocument(); - PartDesign::Body *body = getBodyFor(sketch, /*messageIfNot*/ false); + PartDesign::Body* body = getBodyFor(sketch, /*messageIfNot*/ false); if (!body) { - throw Base::RuntimeError ("Could not find a body for the sketch"); + throw Base::RuntimeError("Could not find a body for the sketch"); } // Get the Origin for the body - App::Origin *origin = body->getOrigin (); // May throw by itself + App::Origin* origin = body->getOrigin(); // May throw by itself Base::Placement plm = sketch->Placement.getValue(); Base::Vector3d pnt = plm.getPosition(); // Currently we only handle positions that are parallel to the base planes Base::Rotation rot = plm.getRotation(); - Base::Vector3d sketchVector(0,0,1); + Base::Vector3d sketchVector(0, 0, 1); rot.multVec(sketchVector, sketchVector); - bool reverseSketch = (sketchVector.x + sketchVector.y + sketchVector.z) < 0.0 ; - if (reverseSketch) sketchVector *= -1.0; + bool reverseSketch = (sketchVector.x + sketchVector.y + sketchVector.z) < 0.0; + if (reverseSketch) { + sketchVector *= -1.0; + } - App::Plane *plane =nullptr; + App::Plane* plane = nullptr; - if (sketchVector == Base::Vector3d(0,0,1)) - plane = origin->getXY (); - else if (sketchVector == Base::Vector3d(0,1,0)) - plane = origin->getXZ (); - else if (sketchVector == Base::Vector3d(1,0,0)) - plane = origin->getYZ (); + if (sketchVector == Base::Vector3d(0, 0, 1)) { + plane = origin->getXY(); + } + else if (sketchVector == Base::Vector3d(0, 1, 0)) { + plane = origin->getXZ(); + } + else if (sketchVector == Base::Vector3d(1, 0, 0)) { + plane = origin->getYZ(); + } else { throw Base::ValueError("Sketch plane cannot be migrated"); } - assert (plane); + assert(plane); // Find the normal distance from origin to the sketch plane - gp_Pln pln(gp_Pnt (pnt.x, pnt.y, pnt.z), gp_Dir(sketchVector.x, sketchVector.y, sketchVector.z)); - double offset = pln.Distance(gp_Pnt(0,0,0)); + gp_Pln pln(gp_Pnt(pnt.x, pnt.y, pnt.z), gp_Dir(sketchVector.x, sketchVector.y, sketchVector.z)); + double offset = pln.Distance(gp_Pnt(0, 0, 0)); // TODO Issue a message if sketch have coordinates offset inside the plain (2016-08-15, Fat-Zer) if (fabs(offset) < Precision::Confusion()) { // One of the base planes - FCMD_OBJ_CMD(sketch,"AttachmentSupport = (" << Gui::Command::getObjectCmd(plane) << ",[''])"); - FCMD_OBJ_CMD(sketch,"MapReversed = " << (reverseSketch ? "True" : "False")); - FCMD_OBJ_CMD(sketch,"MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) << "'"); - - } else { + FCMD_OBJ_CMD(sketch, "AttachmentSupport = (" << Gui::Command::getObjectCmd(plane) << ",[''])"); + FCMD_OBJ_CMD(sketch, "MapReversed = " << (reverseSketch ? "True" : "False")); + FCMD_OBJ_CMD( + sketch, + "MapMode = '" << Attacher::AttachEngine::getModeName(Attacher::mmFlatFace) << "'" + ); + } + else { // Offset to base plane // Find out which direction we need to offset double a = sketchVector.GetAngle(pnt); - if ((a < -std::numbers::pi/2) || (a > std::numbers::pi/2)) + if ((a < -std::numbers::pi / 2) || (a > std::numbers::pi / 2)) { offset *= -1.0; + } std::string Datum = doc->getUniqueObjectName("DatumPlane"); - FCMD_DOC_CMD(doc,"addObject('PartDesign::Plane','"<getObject(Datum.c_str()); - FCMD_OBJ_CMD(obj,"AttachmentSupport = [(" << Gui::Command::getObjectCmd(plane) << ",'')]"); - FCMD_OBJ_CMD(obj,"MapMode = '" << AttachEngine::getModeName(Attacher::mmFlatFace) << "'"); - FCMD_OBJ_CMD(obj,"AttachmentOffset.Base.z = " << offset); - FCMD_OBJ_CMD(body,"insertObject("<isDerivedFrom( PartDesign::Feature::getClassTypeId () ) || - PartDesign::Body::isAllowed ( obj ) || - obj->isDerivedFrom ( PartDesign::Body::getClassTypeId () ) || - ( respectGroups && ( - obj->hasExtension (App::GeoFeatureGroupExtension::getExtensionClassTypeId () ) || - obj->hasExtension (App::GroupExtension::getExtensionClassTypeId () ) - ) ) ); +bool isPartDesignAwareObjecta(App::DocumentObject* obj, bool respectGroups = false) +{ + return ( + obj->isDerivedFrom(PartDesign::Feature::getClassTypeId()) + || PartDesign::Body::isAllowed(obj) || obj->isDerivedFrom(PartDesign::Body::getClassTypeId()) + || (respectGroups + && (obj->hasExtension(App::GeoFeatureGroupExtension::getExtensionClassTypeId()) + || obj->hasExtension(App::GroupExtension::getExtensionClassTypeId()))) + ); } -bool isAnyNonPartDesignLinksTo ( PartDesign::Feature *feature, bool respectGroups ) { - App::Document *doc = feature->getDocument(); +bool isAnyNonPartDesignLinksTo(PartDesign::Feature* feature, bool respectGroups) +{ + App::Document* doc = feature->getDocument(); - for ( const auto & obj: doc->getObjects () ) { - if ( !isPartDesignAwareObjecta ( obj, respectGroups ) ) { - std::vector properties; - obj->getPropertyList ( properties ); - for (auto prop: properties ) { - if ( prop->isDerivedFrom ( App::PropertyLink::getClassTypeId() ) ) { - if ( static_cast ( prop )->getValue () == feature ) { - return true; - } - } else if ( prop->isDerivedFrom ( App::PropertyLinkSub::getClassTypeId() ) ) { - if ( static_cast ( prop )->getValue () == feature ) { - return true; - } - } else if ( prop->isDerivedFrom ( App::PropertyLinkList::getClassTypeId() ) ) { - auto values = static_cast ( prop )->getValues (); - if ( std::find ( values.begin (), values.end (), feature ) != values.end() ) { - return true; - } - } else if ( prop->isDerivedFrom ( App::PropertyLinkSubList::getClassTypeId() ) ) { - auto values = static_cast ( prop )->getValues (); - if ( std::find ( values.begin (), values.end (), feature ) != values.end() ) { + for (const auto& obj : doc->getObjects()) { + if (!isPartDesignAwareObjecta(obj, respectGroups)) { + std::vector properties; + obj->getPropertyList(properties); + for (auto prop : properties) { + if (prop->isDerivedFrom(App::PropertyLink::getClassTypeId())) { + if (static_cast(prop)->getValue() == feature) { return true; } } - } - } + else if (prop->isDerivedFrom(App::PropertyLinkSub::getClassTypeId())) { + if (static_cast(prop)->getValue() == feature) { + return true; + } + } + else if (prop->isDerivedFrom(App::PropertyLinkList::getClassTypeId())) { + auto values = static_cast(prop)->getValues(); + if (std::find(values.begin(), values.end(), feature) != values.end()) { + return true; + } + } + else if (prop->isDerivedFrom(App::PropertyLinkSubList::getClassTypeId())) { + auto values = static_cast(prop)->getValues(); + if (std::find(values.begin(), values.end(), feature) != values.end()) { + return true; + } + } + } + } } return false; } -void relinkToBody (PartDesign::Feature *feature) { - App::Document *doc = feature->getDocument(); - PartDesign::Body *body = PartDesign::Body::findBodyOf ( feature ); +void relinkToBody(PartDesign::Feature* feature) +{ + App::Document* doc = feature->getDocument(); + PartDesign::Body* body = PartDesign::Body::findBodyOf(feature); if (!body) { - throw Base::RuntimeError ("Could not find a body for the feature"); + throw Base::RuntimeError("Could not find a body for the feature"); } - for ( const auto & obj: doc->getObjects () ) { - if ( !isPartDesignAwareObjecta ( obj ) ) { - std::vector properties; - obj->getPropertyList ( properties ); - for (auto prop: properties ) { + for (const auto& obj : doc->getObjects()) { + if (!isPartDesignAwareObjecta(obj)) { + std::vector properties; + obj->getPropertyList(properties); + for (auto prop : properties) { std::string valueStr; - if ( prop->isDerivedFrom ( App::PropertyLink::getClassTypeId() ) ) { - App::PropertyLink *propLink = static_cast ( prop ); - if ( propLink->getValue() != feature ) { + if (prop->isDerivedFrom(App::PropertyLink::getClassTypeId())) { + App::PropertyLink* propLink = static_cast(prop); + if (propLink->getValue() != feature) { continue; } valueStr = Gui::Command::getObjectCmd(body); - } else if ( prop->isDerivedFrom ( App::PropertyLinkSub::getClassTypeId() ) ) { - App::PropertyLinkSub *propLink = static_cast ( prop ); - if ( propLink->getValue() != feature ) { + } + else if (prop->isDerivedFrom(App::PropertyLinkSub::getClassTypeId())) { + App::PropertyLinkSub* propLink = static_cast(prop); + if (propLink->getValue() != feature) { continue; } - valueStr = buildLinkSubPythonStr ( body, propLink->getSubValues() ); - } else if ( prop->isDerivedFrom ( App::PropertyLinkList::getClassTypeId() ) ) { - App::PropertyLinkList *propLink = static_cast ( prop ); - std::vector linkList = propLink->getValues (); - bool valueChanged=false; - for (auto & link : linkList ) { - if ( link == feature ) { + valueStr = buildLinkSubPythonStr(body, propLink->getSubValues()); + } + else if (prop->isDerivedFrom(App::PropertyLinkList::getClassTypeId())) { + App::PropertyLinkList* propLink = static_cast(prop); + std::vector linkList = propLink->getValues(); + bool valueChanged = false; + for (auto& link : linkList) { + if (link == feature) { link = body; valueChanged = true; } } - if ( valueChanged ) { - valueStr = buildLinkListPythonStr ( linkList ); + if (valueChanged) { + valueStr = buildLinkListPythonStr(linkList); // TODO Issue some message here due to it likely will break something // (2015-08-13, Fat-Zer) } - } else if ( prop->isDerivedFrom ( App::PropertyLinkSub::getClassTypeId() ) ) { - App::PropertyLinkSubList *propLink = static_cast ( prop ); - std::vector linkList = propLink->getValues (); - bool valueChanged=false; - for (auto & link : linkList ) { - if ( link == feature ) { + } + else if (prop->isDerivedFrom(App::PropertyLinkSub::getClassTypeId())) { + App::PropertyLinkSubList* propLink = static_cast(prop); + std::vector linkList = propLink->getValues(); + bool valueChanged = false; + for (auto& link : linkList) { + if (link == feature) { link = body; valueChanged = true; } } - if ( valueChanged ) { - valueStr = buildLinkSubListPythonStr ( linkList, propLink->getSubValues() ); + if (valueChanged) { + valueStr = buildLinkSubListPythonStr(linkList, propLink->getSubValues()); // TODO Issue some message here due to it likely will break something // (2015-08-13, Fat-Zer) } } - if ( !valueStr.empty () && prop->hasName()) { - FCMD_OBJ_CMD(obj,prop->getName() << '=' << valueStr); + if (!valueStr.empty() && prop->hasName()) { + FCMD_OBJ_CMD(obj, prop->getName() << '=' << valueStr); } } } @@ -482,17 +564,21 @@ bool isFeatureMovable(App::DocumentObject* const feat) } if (auto prop = dynamic_cast(prim->getPropertyByName("Sections"))) { - if (std::any_of(prop->getValues().begin(), prop->getValues().end(), [](App::DocumentObject* obj) { - return !isFeatureMovable(obj); - })) { + if (std::any_of( + prop->getValues().begin(), + prop->getValues().end(), + [](App::DocumentObject* obj) { return !isFeatureMovable(obj); } + )) { return false; } } if (auto prop = dynamic_cast(prim->getPropertyByName("Sections"))) { - if (std::any_of(prop->getValues().begin(), prop->getValues().end(), [](App::DocumentObject* obj) { - return !isFeatureMovable(obj); - })) { + if (std::any_of( + prop->getValues().begin(), + prop->getValues().end(), + [](App::DocumentObject* obj) { return !isFeatureMovable(obj); } + )) { return false; } } @@ -517,7 +603,6 @@ bool isFeatureMovable(App::DocumentObject* const feat) return false; } } - } if (feat->hasExtension(Part::AttachExtension::getExtensionClassTypeId())) { @@ -535,7 +620,7 @@ std::vector collectMovableDependencies(std::vector unique_objs; - for (auto const &feat : features) { + for (auto const& feat : features) { // Get sketches and datums from profile based features if (auto prim = dynamic_cast(feat)) { Part::Part2DObject* sk = prim->getVerifiedSketch(true); @@ -547,26 +632,29 @@ std::vector collectMovableDependencies(std::vector(prim->getPropertyByName("Sections"))) { + if (auto prop + = dynamic_cast(prim->getPropertyByName("Sections"))) { for (App::DocumentObject* obj : prop->getValues()) { unique_objs.insert(obj); } } - if (auto prop = dynamic_cast(prim->getPropertyByName("ReferenceAxis"))) { + if (auto prop + = dynamic_cast(prim->getPropertyByName("ReferenceAxis"))) { App::DocumentObject* axis = prop->getValue(); - if (axis && !axis->isDerivedFrom()){ + if (axis && !axis->isDerivedFrom()) { unique_objs.insert(axis); } } if (auto prop = dynamic_cast(prim->getPropertyByName("Spine"))) { App::DocumentObject* axis = prop->getValue(); - if (axis && !axis->isDerivedFrom()){ + if (axis && !axis->isDerivedFrom()) { unique_objs.insert(axis); } } - if (auto prop = dynamic_cast(prim->getPropertyByName("AuxiliarySpine"))) { + if (auto prop + = dynamic_cast(prim->getPropertyByName("AuxiliarySpine"))) { App::DocumentObject* axis = prop->getValue(); - if (axis && !axis->isDerivedFrom()){ + if (axis && !axis->isDerivedFrom()) { unique_objs.insert(axis); } } @@ -587,9 +675,14 @@ void relinkToOrigin(App::DocumentObject* feat, PartDesign::Body* targetbody) App::DocumentObject* support = attachable->AttachmentSupport.getValue(); if (support && support->isDerivedFrom()) { auto originfeat = static_cast(support); - App::DatumElement* targetOriginFeature = targetbody->getOrigin()->getDatumElement(originfeat->Role.getValue()); + App::DatumElement* targetOriginFeature = targetbody->getOrigin()->getDatumElement( + originfeat->Role.getValue() + ); if (targetOriginFeature) { - attachable->AttachmentSupport.setValue(static_cast(targetOriginFeature), ""); + attachable->AttachmentSupport.setValue( + static_cast(targetOriginFeature), + "" + ); } } } @@ -597,15 +690,20 @@ void relinkToOrigin(App::DocumentObject* feat, PartDesign::Body* targetbody) auto prim = static_cast(feat); if (auto prop = static_cast(prim->getPropertyByName("ReferenceAxis"))) { App::DocumentObject* axis = prop->getValue(); - if (axis && axis->isDerivedFrom()){ + if (axis && axis->isDerivedFrom()) { auto originfeat = static_cast(axis); - App::DatumElement* targetOriginFeature = targetbody->getOrigin()->getDatumElement(originfeat->Role.getValue()); + App::DatumElement* targetOriginFeature = targetbody->getOrigin()->getDatumElement( + originfeat->Role.getValue() + ); if (targetOriginFeature) { - prop->setValue(static_cast(targetOriginFeature), std::vector(0)); + prop->setValue( + static_cast(targetOriginFeature), + std::vector(0) + ); } } } } } -} /* PartDesignGui */ +} // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/Utils.h b/src/Mod/PartDesign/Gui/Utils.h index 3de0003515..19e1e95ad7 100644 --- a/src/Mod/PartDesign/Gui/Utils.h +++ b/src/Mod/PartDesign/Gui/Utils.h @@ -26,33 +26,41 @@ /** \file PartDesign/Gui/Utils.h * This file contains some utility function used over PartDesignGui module */ -namespace PartDesign { - class Body; - class Feature; +namespace PartDesign +{ +class Body; +class Feature; +} // namespace PartDesign + +namespace App +{ +class Document; +class DocumentObject; +class Part; +} // namespace App + +namespace Sketcher +{ +class SketchObject; } -namespace App { - class Document; - class DocumentObject; - class Part; -} - -namespace Sketcher { - class SketchObject; -} - -namespace PartDesignGui { +namespace PartDesignGui +{ /// Activate edit mode of the given object -bool setEdit(App::DocumentObject *obj, PartDesign::Body *body = nullptr); +bool setEdit(App::DocumentObject* obj, PartDesign::Body* body = nullptr); /// Return active body or show a warning message -PartDesign::Body *getBody(bool messageIfNot, bool autoActivate=true, bool assertModern=true, - App::DocumentObject **topParent=nullptr, std::string *subname=nullptr); +PartDesign::Body* getBody( + bool messageIfNot, + bool autoActivate = true, + bool assertModern = true, + App::DocumentObject** topParent = nullptr, + std::string* subname = nullptr +); /// Display a dialog to select or create a Body object when none is active -PartDesign::Body * needActiveBodyMessage(App::Document *doc, - const QString& infoText=QString()); +PartDesign::Body* needActiveBodyMessage(App::Document* doc, const QString& infoText = QString()); /** * Set given body active, and return pointer to it. @@ -62,46 +70,57 @@ PartDesign::Body * needActiveBodyMessage(App::Document *doc, * \param subname to be passed under certain circumstances * (currently only subshapebinder) */ -PartDesign::Body * makeBodyActive(App::DocumentObject *body, App::Document *doc, - App::DocumentObject **topParent=nullptr, - std::string *subname=nullptr); +PartDesign::Body* makeBodyActive( + App::DocumentObject* body, + App::Document* doc, + App::DocumentObject** topParent = nullptr, + std::string* subname = nullptr +); /// Display error when there are existing Body objects, but none are active void needActiveBodyError(); /// Create a Body object in doc, set it active, and return pointer to it -PartDesign::Body * makeBody(App::Document *doc); +PartDesign::Body* makeBody(App::Document* doc); /** * Finds a body for the given feature. And shows a message if not found * Also unlike Body::findBodyFor it checks if the active body has the feature first. */ -PartDesign::Body *getBodyFor(const App::DocumentObject*, bool messageIfNot, - bool autoActivate=true, bool assertModern=true, - App::DocumentObject **topParent=nullptr, std::string *subname=nullptr); +PartDesign::Body* getBodyFor( + const App::DocumentObject*, + bool messageIfNot, + bool autoActivate = true, + bool assertModern = true, + App::DocumentObject** topParent = nullptr, + std::string* subname = nullptr +); -App::Part *getPartFor(const App::DocumentObject*, bool messageIfNot); -App::Part *getActivePart(); +App::Part* getPartFor(const App::DocumentObject*, bool messageIfNot); +App::Part* getActivePart(); /// Fix sketch support after moving a free sketch into a body void fixSketchSupport(Sketcher::SketchObject* sketch); /** * Returns true if document has any non-PartDesign objects that links to the given object. - * If respectGroups is true don't count links from App::GeoFeatureGroup-derived objects (default is false) + * If respectGroups is true don't count links from App::GeoFeatureGroup-derived objects (default is + * false) */ -bool isAnyNonPartDesignLinksTo ( PartDesign::Feature *feature, bool respectGroups=false ); +bool isAnyNonPartDesignLinksTo(PartDesign::Feature* feature, bool respectGroups = false); /// Relink all nonPartDesign features to the body instead of the given partDesign Feature -void relinkToBody ( PartDesign::Feature *feature ); +void relinkToBody(PartDesign::Feature* feature); /// Check if feature is dependent on anything except movable sketches and datums bool isFeatureMovable(App::DocumentObject* feature); /// Collect dependencies of the features during the move. Dependencies should only be dependent on origin -std::vector collectMovableDependencies(std::vector& features); +std::vector collectMovableDependencies( + std::vector& features +); /// Relink sketches and datums to target body's origin void relinkToOrigin(App::DocumentObject* feature, PartDesign::Body* body); -} /* PartDesignGui */ +} // namespace PartDesignGui #endif /* end of include guard: UTILS_H_CS5LK2ZQ */ diff --git a/src/Mod/PartDesign/Gui/ViewProvider.cpp b/src/Mod/PartDesign/Gui/ViewProvider.cpp index 1322469c0b..ede66664a7 100644 --- a/src/Mod/PartDesign/Gui/ViewProvider.cpp +++ b/src/Mod/PartDesign/Gui/ViewProvider.cpp @@ -20,12 +20,12 @@ * * ***************************************************************************/ -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include #include @@ -81,7 +81,8 @@ void ViewProvider::attach(App::DocumentObject* pcObject) PreviewColor.setValue( isAdditive ? styleParameterManager->resolve(StyleParameters::PreviewAdditiveColor) - : styleParameterManager->resolve(StyleParameters::PreviewSubtractiveColor)); + : styleParameterManager->resolve(StyleParameters::PreviewSubtractiveColor) + ); } } @@ -123,11 +124,11 @@ bool ViewProvider::setEdit(int ModNum) // When double-clicking on the item for this feature the // object unsets and sets its edit mode without closing // the task panel - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - TaskDlgFeatureParameters *featureDlg = qobject_cast(dlg); + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); + TaskDlgFeatureParameters* featureDlg = qobject_cast(dlg); // NOTE: if the dialog is not partDesigan dialog the featureDlg will be NULL if (featureDlg && featureDlg->getViewObject() != this) { - featureDlg = nullptr; // another feature left open its task panel + featureDlg = nullptr; // another feature left open its task panel } if (dlg && !featureDlg) { QMessageBox msgBox(Gui::getMainWindow()); @@ -138,7 +139,8 @@ bool ViewProvider::setEdit(int ModNum) if (msgBox.exec() == QMessageBox::Yes) { Gui::Control().reject(); - } else { + } + else { return false; } } @@ -163,20 +165,22 @@ bool ViewProvider::setEdit(int ModNum) // start the edit dialog if if (!featureDlg) { featureDlg = this->getEditDialog(); - if (!featureDlg) { // Shouldn't generally happen - throw Base::RuntimeError ("Failed to create new edit dialog."); + if (!featureDlg) { // Shouldn't generally happen + throw Base::RuntimeError("Failed to create new edit dialog."); } } Gui::Control().showDialog(featureDlg); return true; - } else { + } + else { return PartGui::ViewProviderPart::setEdit(ModNum); } } -TaskDlgFeatureParameters *ViewProvider::getEditDialog() { +TaskDlgFeatureParameters* ViewProvider::getEditDialog() +{ throw Base::NotImplementedError("getEditDialog() not implemented"); } @@ -208,7 +212,8 @@ void ViewProvider::updateData(const App::Property* prop) { if (strcmp(prop->getName(), "PreviewShape") == 0) { updatePreview(); - } else if (auto* previewExtension = getObject()->getExtensionByType(true)) { + } + else if (auto* previewExtension = getObject()->getExtensionByType(true)) { if (!previewExtension->isPreviewFresh() && isEditing()) { previewExtension->updatePreview(); } @@ -248,7 +253,8 @@ void ViewProvider::updatePreview() Part::TopoShape toolShape = addSubFeature->AddSubShape.getShape(); updatePreviewShape(toolShape, pcToolPreview); - } else { + } + else { updatePreviewShape({}, pcToolPreview); } } @@ -262,22 +268,25 @@ void ViewProvider::makeChildrenVisible() } } -void ViewProvider::onChanged(const App::Property* prop) { +void ViewProvider::onChanged(const App::Property* prop) +{ - //if the object is inside of a body we make sure it is the only visible one on activation - if(prop == &Visibility && Visibility.getValue()) { + // if the object is inside of a body we make sure it is the only visible one on activation + if (prop == &Visibility && Visibility.getValue()) { Part::BodyBase* body = Part::BodyBase::findBodyOf(getObject()); - if(body) { + if (body) { - //hide all features in the body other than this object - for(App::DocumentObject* obj : body->Group.getValues()) { + // hide all features in the body other than this object + for (App::DocumentObject* obj : body->Group.getValues()) { - if(obj->isDerivedFrom() && obj != getObject()) { - auto vpd = freecad_cast( - Gui::Application::Instance->getViewProvider(obj)); - if(vpd && vpd->Visibility.getValue()) - vpd->Visibility.setValue(false); + if (obj->isDerivedFrom() && obj != getObject()) { + auto vpd = freecad_cast( + Gui::Application::Instance->getViewProvider(obj) + ); + if (vpd && vpd->Visibility.getValue()) { + vpd->Visibility.setValue(false); + } } } } @@ -302,7 +311,8 @@ Gui::ViewProvider* ViewProvider::startEditing(int ModNum) return ViewProviderPart::startEditing(ModNum); } -void ViewProvider::setTipIcon(bool onoff) { +void ViewProvider::setTipIcon(bool onoff) +{ isSetTipIcon = onoff; signalChangeIcon(); @@ -314,10 +324,11 @@ QIcon ViewProvider::mergeColorfulOverlayIcons(const QIcon& orig) const if (isSetTipIcon) { static QPixmap px(Gui::BitmapFactory().pixmapFromSvg("PartDesign_Overlay_Tip", QSize(10, 10))); - mergedicon = Gui::BitmapFactoryInst::mergePixmap(mergedicon, px, Gui::BitmapFactoryInst::BottomRight); + mergedicon + = Gui::BitmapFactoryInst::mergePixmap(mergedicon, px, Gui::BitmapFactoryInst::BottomRight); } - return Gui::ViewProvider::mergeColorfulOverlayIcons (mergedicon); + return Gui::ViewProvider::mergeColorfulOverlayIcons(mergedicon); } bool ViewProvider::onDelete(const std::vector&) @@ -337,16 +348,17 @@ bool ViewProvider::onDelete(const std::vector&) Part::BodyBase* body = PartDesign::Body::findBodyOf(getObject()); if (body) { - // Deletion from the tree of a feature is handled by Document.removeObject, which has no clue - // about what a body is. Therefore, Bodies, although an "activable" container, know nothing - // about what happens at Document level with the features they contain. + // Deletion from the tree of a feature is handled by Document.removeObject, which has no + // clue about what a body is. Therefore, Bodies, although an "activable" container, know + // nothing about what happens at Document level with the features they contain. // - // The Deletion command StdCmdDelete::activated, however does notify the viewprovider corresponding - // to the feature (not body) of the imminent deletion (before actually doing it). + // The Deletion command StdCmdDelete::activated, however does notify the viewprovider + // corresponding to the feature (not body) of the imminent deletion (before actually doing + // it). // - // Consequently, the only way of notifying a body of the imminent deletion of one of its features - // so as to do the clean up required (moving basefeature references, tip management) is from the - // viewprovider, so we call it here. + // Consequently, the only way of notifying a body of the imminent deletion of one of its + // features so as to do the clean up required (moving basefeature references, tip + // management) is from the viewprovider, so we call it here. // // fixes (#3084) @@ -372,9 +384,9 @@ Part::TopoShape ViewProvider::getPreviewShape() const void ViewProvider::showPreviousFeature(bool enable) { PartDesign::Feature* feature {getObject()}; - PartDesign::Feature* baseFeature { nullptr }; + PartDesign::Feature* baseFeature {nullptr}; - ViewProvider* baseFeatureViewProvider { nullptr }; + ViewProvider* baseFeatureViewProvider {nullptr}; if (!feature) { return; @@ -382,7 +394,9 @@ void ViewProvider::showPreviousFeature(bool enable) baseFeature = dynamic_cast(feature->BaseFeature.getValue()); if (baseFeature) { - baseFeatureViewProvider = freecad_cast(Gui::Application::Instance->getViewProvider(baseFeature)); + baseFeatureViewProvider = freecad_cast( + Gui::Application::Instance->getViewProvider(baseFeature) + ); } if (!baseFeatureViewProvider) { @@ -392,31 +406,35 @@ void ViewProvider::showPreviousFeature(bool enable) if (enable) { baseFeatureViewProvider->show(); hide(); - } else { + } + else { baseFeatureViewProvider->hide(); show(); } } -void ViewProvider::setBodyMode(bool bodymode) { +void ViewProvider::setBodyMode(bool bodymode) +{ std::vector props; getPropertyList(props); auto vp = getBodyViewProvider(); - if(!vp) + if (!vp) { return; + } - for(App::Property* prop : props) { + for (App::Property* prop : props) { - //we keep visibility and selectibility per object - if(prop == &Visibility || - prop == &Selectable) + // we keep visibility and selectibility per object + if (prop == &Visibility || prop == &Selectable) { continue; + } - //we hide only properties which are available in the body, not special ones - if(!vp->getPropertyByName(prop->getName())) + // we hide only properties which are available in the body, not special ones + if (!vp->getPropertyByName(prop->getName())) { continue; + } prop->setStatus(App::Property::Hidden, bodymode); } @@ -424,21 +442,23 @@ void ViewProvider::setBodyMode(bool bodymode) { void ViewProvider::makeTemporaryVisible(bool onoff) { - //make sure to not use the overridden versions, as they change properties + // make sure to not use the overridden versions, as they change properties if (onoff) { if (VisualTouched) { updateVisual(); } Gui::ViewProvider::show(); } - else + else { Gui::ViewProvider::hide(); + } } PyObject* ViewProvider::getPyObject() { - if (!pyViewObject) + if (!pyViewObject) { pyViewObject = new ViewProviderPy(this); + } pyViewObject->IncRef(); return pyViewObject; } @@ -448,20 +468,22 @@ ViewProviderBody* ViewProvider::getBodyViewProvider() auto body = PartDesign::Body::findBodyOf(getObject()); auto doc = getDocument(); - if(body && doc) { + if (body && doc) { auto vp = doc->getViewProvider(body); - if(vp && vp->isDerivedFrom()) - return static_cast(vp); + if (vp && vp->isDerivedFrom()) { + return static_cast(vp); + } } return nullptr; } -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(PartDesignGui::ViewProviderPython, PartDesignGui::ViewProvider) /// @endcond // explicit template instantiation template class PartDesignGuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Mod/PartDesign/Gui/ViewProvider.h b/src/Mod/PartDesign/Gui/ViewProvider.h index 9b5f361940..1cd6b9dd4e 100644 --- a/src/Mod/PartDesign/Gui/ViewProvider.h +++ b/src/Mod/PartDesign/Gui/ViewProvider.h @@ -35,17 +35,18 @@ #include "ViewProviderBody.h" -namespace PartDesignGui { +namespace PartDesignGui +{ class TaskDlgFeatureParameters; /** * A common base class for all part design features view providers */ -class PartDesignGuiExport ViewProvider : public PartGui::ViewProviderPart, - Gui::ViewProviderSuppressibleExtension, - PartGui::ViewProviderAttachExtension, - public PartGui::ViewProviderPreviewExtension +class PartDesignGuiExport ViewProvider: public PartGui::ViewProviderPart, + Gui::ViewProviderSuppressibleExtension, + PartGui::ViewProviderAttachExtension, + public PartGui::ViewProviderPreviewExtension { using inherited = PartGui::ViewProviderPart; PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProvider); @@ -66,18 +67,18 @@ public: void setTipIcon(bool onoff); - //body mode means that the object is part of a body and that the body is used to set the - //visual properties, not the features. Hence setting body mode to true will hide most - //viewprovider properties. + // body mode means that the object is part of a body and that the body is used to set the + // visual properties, not the features. Hence setting body mode to true will hide most + // viewprovider properties. void setBodyMode(bool bodymode); - //makes this viewprovider visible in the scene graph without changing any properties, - //not the visibility one and also not the display mode. This can be used to show the - //shape of this viewprovider from other viewproviders without doing anything to the - //document and properties. + // makes this viewprovider visible in the scene graph without changing any properties, + // not the visibility one and also not the display mode. This can be used to show the + // shape of this viewprovider from other viewproviders without doing anything to the + // document and properties. void makeTemporaryVisible(bool); - //Returns the ViewProvider of the body the feature belongs to, or NULL, if not in a body + // Returns the ViewProvider of the body the feature belongs to, or NULL, if not in a body ViewProviderBody* getBodyViewProvider(); /// Provides preview shape @@ -87,7 +88,7 @@ public: PyObject* getPyObject() override; - QIcon mergeColorfulOverlayIcons (const QIcon & orig) const override; + QIcon mergeColorfulOverlayIcons(const QIcon& orig) const override; protected: void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; @@ -99,18 +100,18 @@ protected: void updatePreview() override; virtual void makeChildrenVisible(); - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; /** * Returns a newly create dialog for the part to be placed in the task view * Must be reimplemented in subclasses. */ - virtual TaskDlgFeatureParameters *getEditDialog(); + virtual TaskDlgFeatureParameters* getEditDialog(); std::string oldWb; - ViewProvider* previouslyShownViewProvider { nullptr }; + ViewProvider* previouslyShownViewProvider {nullptr}; - bool isSetTipIcon { false }; + bool isSetTipIcon {false}; private: Gui::CoinPtr pcToolPreview; @@ -118,7 +119,7 @@ private: using ViewProviderPython = Gui::ViewProviderFeaturePythonT; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderHole_H +#endif // PARTGUI_ViewProviderHole_H diff --git a/src/Mod/PartDesign/Gui/ViewProvider.pyi b/src/Mod/PartDesign/Gui/ViewProvider.pyi index 0946ad4bb7..2bee076209 100644 --- a/src/Mod/PartDesign/Gui/ViewProvider.pyi +++ b/src/Mod/PartDesign/Gui/ViewProvider.pyi @@ -6,7 +6,7 @@ from typing import Final, overload Include="Mod/PartDesign/Gui/ViewProvider.h", Namespace="PartDesignGui", FatherInclude="Mod/Part/Gui/ViewProviderPartExtPy.h", - FatherNamespace="PartGui" + FatherNamespace="PartGui", ) class ViewProvider(ViewProviderPartExt): """ diff --git a/src/Mod/PartDesign/Gui/ViewProviderBase.cpp b/src/Mod/PartDesign/Gui/ViewProviderBase.cpp index cb34c2e79c..d2f0798b6f 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBase.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBase.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -31,7 +30,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderBase,PartDesignGui::ViewProvider) +PROPERTY_SOURCE(PartDesignGui::ViewProviderBase, PartDesignGui::ViewProvider) ViewProviderBase::ViewProviderBase() { @@ -45,9 +44,9 @@ bool ViewProviderBase::doubleClicked() // If the Placement is mutable then open the transform panel. // If the Placement can't be modified then just do nothing on double-click. PartDesign::FeatureBase* base = getObject(); - if (!base->Placement.testStatus(App::Property::Immutable) && - !base->Placement.testStatus(App::Property::ReadOnly) && - !base->Placement.testStatus(App::Property::Hidden)) { + if (!base->Placement.testStatus(App::Property::Immutable) + && !base->Placement.testStatus(App::Property::ReadOnly) + && !base->Placement.testStatus(App::Property::Hidden)) { try { std::string Msg("Edit "); @@ -68,9 +67,9 @@ void ViewProviderBase::setupContextMenu(QMenu* menu, QObject* receiver, const ch { // If the Placement is mutable then show the context-menu of the base class. PartDesign::FeatureBase* base = getObject(); - if (!base->Placement.testStatus(App::Property::Immutable) && - !base->Placement.testStatus(App::Property::ReadOnly) && - !base->Placement.testStatus(App::Property::Hidden)) { + if (!base->Placement.testStatus(App::Property::Immutable) + && !base->Placement.testStatus(App::Property::ReadOnly) + && !base->Placement.testStatus(App::Property::Hidden)) { // Handling of the edge case where some base features are outside the body // that should not happen, but it was possible to do in older FreeCAD versions. @@ -94,9 +93,9 @@ Gui::ViewProvider* ViewProviderBase::startEditing(int ModNum) bool ViewProviderBase::setEdit(int ModNum) { PartDesign::FeatureBase* base = getObject(); - if (!base->Placement.testStatus(App::Property::Immutable) && - !base->Placement.testStatus(App::Property::ReadOnly) && - !base->Placement.testStatus(App::Property::Hidden)) { + if (!base->Placement.testStatus(App::Property::Immutable) + && !base->Placement.testStatus(App::Property::ReadOnly) + && !base->Placement.testStatus(App::Property::Hidden)) { // same as in setupContextMenu if (!getBodyViewProvider()) { diff --git a/src/Mod/PartDesign/Gui/ViewProviderBase.h b/src/Mod/PartDesign/Gui/ViewProviderBase.h index 592ca2b76a..a4b230050b 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBase.h +++ b/src/Mod/PartDesign/Gui/ViewProviderBase.h @@ -26,9 +26,10 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderBase : public ViewProvider +class PartDesignGuiExport ViewProviderBase: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderBase); @@ -47,7 +48,7 @@ protected: bool setEdit(int ModNum) override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderBase_H +#endif // PARTGUI_ViewProviderBase_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderBody.cpp b/src/Mod/PartDesign/Gui/ViewProviderBody.cpp index 66b6c0b5f0..7b2fcdce2b 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBody.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBody.cpp @@ -21,11 +21,10 @@ ***************************************************************************/ - -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -56,13 +55,13 @@ using namespace PartDesignGui; namespace sp = std::placeholders; -const char* PartDesignGui::ViewProviderBody::BodyModeEnum[] = {"Through","Tip",nullptr}; +const char* PartDesignGui::ViewProviderBody::BodyModeEnum[] = {"Through", "Tip", nullptr}; -PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProviderBody,PartGui::ViewProviderPart) +PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProviderBody, PartGui::ViewProviderPart) ViewProviderBody::ViewProviderBody() { - ADD_PROPERTY(DisplayModeBody,((long)0)); + ADD_PROPERTY(DisplayModeBody, ((long)0)); DisplayModeBody.setEnums(BodyModeEnum); sPixmap = "PartDesign_Body.svg"; @@ -71,15 +70,14 @@ ViewProviderBody::ViewProviderBody() } ViewProviderBody::~ViewProviderBody() -{ -} +{} -void ViewProviderBody::attach(App::DocumentObject *pcFeat) +void ViewProviderBody::attach(App::DocumentObject* pcFeat) { // call parent attach method ViewProviderPart::attach(pcFeat); - //set default display mode + // set default display mode onChanged(&DisplayModeBody); } @@ -88,26 +86,31 @@ void ViewProviderBody::attach(App::DocumentObject *pcFeat) // TODO drag&drop (2015-09-05, Fat-Zer) // TODO Add activate () call (2015-09-08, Fat-Zer) -void ViewProviderBody::setDisplayMode(const char* ModeName) { +void ViewProviderBody::setDisplayMode(const char* ModeName) +{ - //if we show "Through" we must avoid to set the display mask modes, as this would result - //in going into "tip" mode. When through is chosen the child features are displayed, and all - //we need to ensure is that the display mode change is propagated to them from within the - //onChanged() method. - if(DisplayModeBody.getValue() == 1) + // if we show "Through" we must avoid to set the display mask modes, as this would result + // in going into "tip" mode. When through is chosen the child features are displayed, and all + // we need to ensure is that the display mode change is propagated to them from within the + // onChanged() method. + if (DisplayModeBody.getValue() == 1) { PartGui::ViewProviderPartExt::setDisplayMode(ModeName); + } } -void ViewProviderBody::setOverrideMode(const std::string& mode) { +void ViewProviderBody::setOverrideMode(const std::string& mode) +{ - //if we are in through mode, we need to ensure that the override mode is not set for the body + // if we are in through mode, we need to ensure that the override mode is not set for the body //(as this would result in "tip" mode), it is enough when the children are set to the correct - //override mode. + // override mode. - if(DisplayModeBody.getValue() != 0) + if (DisplayModeBody.getValue() != 0) { Gui::ViewProvider::setOverrideMode(mode); - else + } + else { overrideMode = mode; + } } void ViewProviderBody::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) @@ -119,25 +122,26 @@ void ViewProviderBody::setupContextMenu(QMenu* menu, QObject* receiver, const ch QAction* act = menu->addAction(tr("Active Body")); act->setCheckable(true); act->setChecked(isActiveBody()); - func->trigger(act, [this]() { - this->toggleActiveBody(); - }); + func->trigger(act, [this]() { this->toggleActiveBody(); }); - Gui::ViewProviderGeometryObject::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method + Gui::ViewProviderGeometryObject::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method } bool ViewProviderBody::isActiveBody() { auto activeDoc = Gui::Application::Instance->activeDocument(); - if(!activeDoc) + if (!activeDoc) { activeDoc = getDocument(); + } auto activeView = activeDoc->setActiveView(this); - if(!activeView) + if (!activeView) { return false; + } - if (activeView->isActiveObject(getObject(),PDBODYKEY)){ + if (activeView->isActiveObject(getObject(), PDBODYKEY)) { return true; - } else { + } + else { return false; } } @@ -145,26 +149,42 @@ bool ViewProviderBody::isActiveBody() void ViewProviderBody::toggleActiveBody() { if (isActiveBody()) { - //active body double-clicked. Deactivate. - Gui::Command::doCommand(Gui::Command::Gui, - "Gui.ActiveDocument.ActiveView.setActiveObject('%s', None)", PDBODYKEY); - } else { + // active body double-clicked. Deactivate. + Gui::Command::doCommand( + Gui::Command::Gui, + "Gui.ActiveDocument.ActiveView.setActiveObject('%s', None)", + PDBODYKEY + ); + } + else { // assure the PartDesign workbench - if(App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/PartDesign")->GetBool("SwitchToWB", true)) + if (App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/PartDesign") + ->GetBool("SwitchToWB", true)) { Gui::Command::assureWorkbench("PartDesignWorkbench"); - - // and set correct active objects - auto* part = App::Part::getPartOfObject ( getObject() ); - if ( part && !isActiveBody() ) { - Gui::Command::doCommand(Gui::Command::Gui, - "Gui.ActiveDocument.ActiveView.setActiveObject('%s',%s)", - PARTKEY, Gui::Command::getObjectCmd(part).c_str()); } - Gui::Command::doCommand(Gui::Command::Gui, + // and set correct active objects + auto* part = App::Part::getPartOfObject(getObject()); + if (part && !isActiveBody()) { + Gui::Command::doCommand( + Gui::Command::Gui, "Gui.ActiveDocument.ActiveView.setActiveObject('%s',%s)", - PDBODYKEY, Gui::Command::getObjectCmd(getObject()).c_str()); + PARTKEY, + Gui::Command::getObjectCmd(part).c_str() + ); + } + + Gui::Command::doCommand( + Gui::Command::Gui, + "Gui.ActiveDocument.ActiveView.setActiveObject('%s',%s)", + PDBODYKEY, + Gui::Command::getObjectCmd(getObject()).c_str() + ); } } @@ -176,7 +196,7 @@ bool ViewProviderBody::doubleClicked() // TODO To be deleted (2015-09-08, Fat-Zer) -//void ViewProviderBody::updateTree() +// void ViewProviderBody::updateTree() //{ // if (ActiveGuiDoc == NULL) return; // @@ -189,9 +209,11 @@ bool ViewProviderBody::doubleClicked() // std::vector features = body->Group.getValues(); // bool highlight = true; // App::DocumentObject* tip = body->Tip.getValue(); -// for (std::vector::const_iterator f = features.begin(); f != features.end(); f++) { -// //Base::Console().error("Highlighting %s: %s\n", (*f)->getNameInDocument(), highlight ? "true" : "false"); -// Gui::ViewProviderDocumentObject* vp = dynamic_cast(Gui::Application::Instance->getViewProvider(*f)); +// for (std::vector::const_iterator f = features.begin(); f != +// features.end(); f++) { +// //Base::Console().error("Highlighting %s: %s\n", (*f)->getNameInDocument(), highlight ? +// "true" : "false"); Gui::ViewProviderDocumentObject* vp = +// dynamic_cast(Gui::Application::Instance->getViewProvider(*f)); // if (vp != NULL) // ActiveGuiDoc->signalHighlightObject(*vp, Gui::LightBlue, active ? highlight : false); // if (highlight && (tip == *f)) @@ -199,9 +221,10 @@ bool ViewProviderBody::doubleClicked() // } //} -bool ViewProviderBody::onDelete ( const std::vector &) { +bool ViewProviderBody::onDelete(const std::vector&) +{ // TODO May be do it conditionally? (2015-09-05, Fat-Zer) - FCMD_OBJ_CMD(getObject(),"removeObjectsFromDocument()"); + FCMD_OBJ_CMD(getObject(), "removeObjectsFromDocument()"); return true; } @@ -210,7 +233,7 @@ void ViewProviderBody::updateData(const App::Property* prop) PartDesign::Body* body = getObject(); if (prop == &body->Group || prop == &body->BaseFeature) { - //ensure all model features are in visual body mode + // ensure all model features are in visual body mode setVisualBodyMode(true); } @@ -232,28 +255,32 @@ void ViewProviderBody::updateData(const App::Property* prop) PartGui::ViewProviderPart::updateData(prop); } -void ViewProviderBody::onChanged(const App::Property* prop) { +void ViewProviderBody::onChanged(const App::Property* prop) +{ - if(prop == &DisplayModeBody) { + if (prop == &DisplayModeBody) { auto body = getObject(); - if ( DisplayModeBody.getValue() == 0 ) { - //if we are in an override mode we need to make sure to come out, because - //otherwise the maskmode is blocked and won't go into "through" - if(getOverrideMode() != "As Is") { + if (DisplayModeBody.getValue() == 0) { + // if we are in an override mode we need to make sure to come out, because + // otherwise the maskmode is blocked and won't go into "through" + if (getOverrideMode() != "As Is") { auto mode = getOverrideMode(); ViewProvider::setOverrideMode("As Is"); overrideMode = mode; } setDisplayMaskMode("Group"); - if(body) + if (body) { body->setShowTip(false); + } } else { - if(body) + if (body) { body->setShowTip(true); - if(getOverrideMode() == "As Is") + } + if (getOverrideMode() == "As Is") { setDisplayMaskMode(DisplayMode.getValueAsString()); + } else { Base::Console().message("Set override mode: %s\n", getOverrideMode().c_str()); setDisplayMaskMode(getOverrideMode().c_str()); @@ -283,18 +310,15 @@ void ViewProviderBody::onChanged(const App::Property* prop) { } -void ViewProviderBody::unifyVisualProperty(const App::Property* prop) { +void ViewProviderBody::unifyVisualProperty(const App::Property* prop) +{ if (!pcObject || isRestoring()) { return; } - if (prop == &Visibility || - prop == &Selectable || - prop == &DisplayModeBody || - prop == &PointColorArray || - prop == &ShowPlacement || - prop == &LineColorArray) { + if (prop == &Visibility || prop == &Selectable || prop == &DisplayModeBody + || prop == &PointColorArray || prop == &ShowPlacement || prop == &LineColorArray) { return; } @@ -306,9 +330,9 @@ void ViewProviderBody::unifyVisualProperty(const App::Property* prop) { } } - Gui::Document *gdoc = Gui::Application::Instance->getDocument ( pcObject->getDocument() ) ; + Gui::Document* gdoc = Gui::Application::Instance->getDocument(pcObject->getDocument()); - PartDesign::Body *body = static_cast ( getObject() ); + PartDesign::Body* body = static_cast(getObject()); auto features = body->Group.getValues(); for (auto feature : features) { @@ -316,7 +340,7 @@ void ViewProviderBody::unifyVisualProperty(const App::Property* prop) { continue; } - //copy over the properties data + // copy over the properties data if (Gui::ViewProvider* vp = gdoc->getViewProvider(feature)) { if (auto fprop = vp->getPropertyByName(prop->getName())) { fprop->Paste(*prop); @@ -325,19 +349,23 @@ void ViewProviderBody::unifyVisualProperty(const App::Property* prop) { } } -void ViewProviderBody::setVisualBodyMode(bool bodymode) { +void ViewProviderBody::setVisualBodyMode(bool bodymode) +{ - Gui::Document *gdoc = Gui::Application::Instance->getDocument ( pcObject->getDocument() ) ; + Gui::Document* gdoc = Gui::Application::Instance->getDocument(pcObject->getDocument()); - PartDesign::Body *body = static_cast ( getObject() ); + PartDesign::Body* body = static_cast(getObject()); auto features = body->Group.getValues(); - for(auto feature : features) { + for (auto feature : features) { - if(!feature->isDerivedFrom()) + if (!feature->isDerivedFrom()) { continue; + } auto* vp = static_cast(gdoc->getViewProvider(feature)); - if (vp) vp->setBodyMode(bodymode); + if (vp) { + vp->setBodyMode(bodymode); + } } } @@ -412,14 +440,15 @@ bool ViewProviderBody::canDropObject(App::DocumentObject* obj) const else if (PartDesign::Body::findBodyOf(obj)) { return false; } - else if (obj->isDerivedFrom (Part::BodyBase::getClassTypeId())) { + else if (obj->isDerivedFrom(Part::BodyBase::getClassTypeId())) { return false; } - App::Part *actPart = PartDesignGui::getActivePart(); + App::Part* actPart = PartDesignGui::getActivePart(); App::Part* partOfBaseFeature = App::Part::getPartOfObject(obj); - if (partOfBaseFeature && partOfBaseFeature != actPart) + if (partOfBaseFeature && partOfBaseFeature != actPart) { return false; + } return true; } @@ -427,8 +456,7 @@ bool ViewProviderBody::canDropObject(App::DocumentObject* obj) const void ViewProviderBody::dropObject(App::DocumentObject* obj) { auto* body = getObject(); - if (obj->isDerivedFrom() - || obj->isDerivedFrom() + if (obj->isDerivedFrom() || obj->isDerivedFrom() || obj->isDerivedFrom()) { body->addObject(obj); } @@ -439,8 +467,9 @@ void ViewProviderBody::dropObject(App::DocumentObject* obj) move.insert(std::end(move), std::begin(deps), std::end(deps)); PartDesign::Body* source = PartDesign::Body::findBodyOf(obj); - if (source) + if (source) { source->removeObjects(move); + } try { body->addObjects(move); } @@ -452,7 +481,7 @@ void ViewProviderBody::dropObject(App::DocumentObject* obj) body->BaseFeature.setValue(obj); } - App::Document* doc = body->getDocument(); + App::Document* doc = body->getDocument(); doc->recompute(); // check if a proxy object has been created for the base feature @@ -467,8 +496,7 @@ void ViewProviderBody::dropObject(App::DocumentObject* obj) } } } -bool ViewProviderBody::canDragObjectToTarget(App::DocumentObject* obj, - App::DocumentObject* target) const +bool ViewProviderBody::canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const { if (obj->isDerivedFrom()) { return target && target->is(); @@ -476,5 +504,3 @@ bool ViewProviderBody::canDragObjectToTarget(App::DocumentObject* obj, return ViewProviderPart::canDragObjectToTarget(obj, target); } - - diff --git a/src/Mod/PartDesign/Gui/ViewProviderBody.h b/src/Mod/PartDesign/Gui/ViewProviderBody.h index 93f8fd1f55..0c516b9032 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBody.h +++ b/src/Mod/PartDesign/Gui/ViewProviderBody.h @@ -34,7 +34,8 @@ class SoGroup; class SoSeparator; class SbBox3f; class SoGetBoundingBoxAction; -namespace PartDesignGui { +namespace PartDesignGui +{ /** ViewProvider of the Body feature * This class manages the visual appearance of the features in the @@ -42,7 +43,8 @@ namespace PartDesignGui { * If the Body is not active it shows only the result shape (tip). * \author jriegel */ -class PartDesignGuiExport ViewProviderBody : public PartGui::ViewProviderPart, public Gui::ViewProviderOriginGroupExtension +class PartDesignGuiExport ViewProviderBody: public PartGui::ViewProviderPart, + public Gui::ViewProviderOriginGroupExtension { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderBody) PROPERTY_HEADER_WITH_EXTENSIONS(PartDesignGui::ViewProviderBody); @@ -55,29 +57,29 @@ public: App::PropertyEnumeration DisplayModeBody; - void attach(App::DocumentObject *) override; + void attach(App::DocumentObject*) override; bool doubleClicked() override; void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; bool isActiveBody(); void toggleActiveBody(); - std::vector< std::string > getDisplayModes() const override; + std::vector getDisplayModes() const override; void setDisplayMode(const char* ModeName) override; void setOverrideMode(const std::string& mode) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; /// Update the children's highlighting when triggered void updateData(const App::Property* prop) override; - ///unify children visuals + /// unify children visuals void onChanged(const App::Property* prop) override; /** * Return the bounding box of visible features * @note datums are counted as their base point only */ - SbBox3f getBoundBox (); + SbBox3f getBoundBox(); PartDesign::Feature* getShownFeature() const; ViewProvider* getShownViewProvider() const; @@ -90,7 +92,10 @@ public: void dropObject(App::DocumentObject*) override; bool canDragObjectToTarget(App::DocumentObject* obj, App::DocumentObject* target) const override; /* Check whether the object accept reordering of its children during drop.*/ - bool acceptReorderingObjects() const override { return true; }; + bool acceptReorderingObjects() const override + { + return true; + }; protected: /// Copy over all visual properties to the child features @@ -103,9 +108,7 @@ private: }; - -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderHole_H - +#endif // PARTGUI_ViewProviderHole_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp b/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp index 07f7eb5a79..d994fc0043 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp @@ -22,8 +22,8 @@ * * ***************************************************************************/ -# include -# include +#include +#include #include "ViewProviderBoolean.h" @@ -43,7 +43,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProviderBoolean,PartDesignGui::ViewProvider) +PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProviderBoolean, PartDesignGui::ViewProvider) const char* PartDesignGui::ViewProviderBoolean::DisplayEnum[] = {"Result", "Tools", nullptr}; @@ -56,7 +56,7 @@ ViewProviderBoolean::ViewProviderBoolean() ViewProviderGeoFeatureGroupExtension::initExtension(this); - ADD_PROPERTY(Display,((long)0)); + ADD_PROPERTY(Display, ((long)0)); Display.setEnums(DisplayEnum); } @@ -69,7 +69,7 @@ void ViewProviderBoolean::setupContextMenu(QMenu* menu, QObject* receiver, const ViewProvider::setupContextMenu(menu, receiver, member); } -bool ViewProviderBoolean::onDelete(const std::vector &s) +bool ViewProviderBoolean::onDelete(const std::vector& s) { auto* feature = getObject(); @@ -88,7 +88,8 @@ const char* ViewProviderBoolean::getDefaultDisplayMode() const return "Flat Lines"; } -void ViewProviderBoolean::onChanged(const App::Property* prop) { +void ViewProviderBoolean::onChanged(const App::Property* prop) +{ ViewProvider::onChanged(prop); @@ -118,7 +119,8 @@ void ViewProviderBoolean::updateData(const App::Property* prop) auto feature = getObject(); if (prop == &feature->Type) { - const auto* styleParameterManager = Base::provideService(); + const auto* styleParameterManager + = Base::provideService(); const auto type = feature->Type.getValueAsString(); const std::map> lookup { @@ -184,7 +186,9 @@ void ViewProviderBoolean::updatePreview() return; } - auto baseFeatureViewProvider = freecad_cast(Gui::Application::Instance->getViewProvider(baseFeature)); + auto baseFeatureViewProvider = freecad_cast( + Gui::Application::Instance->getViewProvider(baseFeature) + ); if (!baseFeatureViewProvider) { return; } @@ -193,7 +197,9 @@ void ViewProviderBoolean::updatePreview() updatePreviewShape(baseFeature->Shape.getShape(), pcBaseShapePreview); pcBaseShapePreview->transparency.setValue(static_cast(toolTransparency)); - pcBaseShapePreview->color.setValue(baseFeatureViewProvider->ShapeAppearance.getDiffuseColor().asValue()); + pcBaseShapePreview->color.setValue( + baseFeatureViewProvider->ShapeAppearance.getDiffuseColor().asValue() + ); pcBaseShapePreview->lineWidth.connectFrom(&pcPreviewShape->lineWidth); pcBasePreviewToggle->addChild(pcBaseShapePreview); @@ -211,7 +217,8 @@ void ViewProviderBoolean::updatePreview() addBaseShapePreview(); std::ranges::for_each(tools, addToolPreview); - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { e.reportException(); } @@ -228,5 +235,6 @@ void ViewProviderBoolean::updateBasePreviewVisibility() auto feature = getObject(); // enable base preview for Common operation only and when the final result is shown - pcBasePreviewToggle->on = strcmp(feature->Type.getValueAsString(), "Common") == 0 && Visibility.getValue(); + pcBasePreviewToggle->on = strcmp(feature->Type.getValueAsString(), "Common") == 0 + && Visibility.getValue(); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderBoolean.h b/src/Mod/PartDesign/Gui/ViewProviderBoolean.h index d7532e5fbe..d0dc585356 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBoolean.h +++ b/src/Mod/PartDesign/Gui/ViewProviderBoolean.h @@ -31,10 +31,11 @@ #include -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderBoolean : public ViewProvider, - public Gui::ViewProviderGeoFeatureGroupExtension +class PartDesignGuiExport ViewProviderBoolean: public ViewProvider, + public Gui::ViewProviderGeoFeatureGroupExtension { PROPERTY_HEADER_WITH_EXTENSIONS(PartDesignGui::ViewProviderBoolean); @@ -49,7 +50,7 @@ public: /// grouping handling void setupContextMenu(QMenu*, QObject*, const char*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; const char* getDefaultDisplayMode() const override; void onChanged(const App::Property* prop) override; @@ -70,7 +71,7 @@ private: Gui::CoinPtr pcBasePreviewToggle; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderBoolean_H +#endif // PARTGUI_ViewProviderBoolean_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderChamfer.cpp b/src/Mod/PartDesign/Gui/ViewProviderChamfer.cpp index 9a854f866d..bec342dae1 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderChamfer.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderChamfer.cpp @@ -21,16 +21,16 @@ ***************************************************************************/ - #include "TaskChamferParameters.h" #include "ViewProviderChamfer.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderChamfer,PartDesignGui::ViewProviderDressUp) +PROPERTY_SOURCE(PartDesignGui::ViewProviderChamfer, PartDesignGui::ViewProviderDressUp) -const std::string & ViewProviderChamfer::featureName() const { +const std::string& ViewProviderChamfer::featureName() const +{ static const std::string name = "Chamfer"; return name; } @@ -41,6 +41,7 @@ void ViewProviderChamfer::setupContextMenu(QMenu* menu, QObject* receiver, const PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderChamfer::getEditDialog() { - return new TaskDlgChamferParameters (this); +TaskDlgFeatureParameters* ViewProviderChamfer::getEditDialog() +{ + return new TaskDlgChamferParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderChamfer.h b/src/Mod/PartDesign/Gui/ViewProviderChamfer.h index 4b2ee5d7f1..64b8222493 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderChamfer.h +++ b/src/Mod/PartDesign/Gui/ViewProviderChamfer.h @@ -27,9 +27,10 @@ #include "ViewProviderDressUp.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderChamfer : public ViewProviderDressUp +class PartDesignGuiExport ViewProviderChamfer: public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderChamfer) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderChamfer); @@ -37,21 +38,22 @@ class PartDesignGuiExport ViewProviderChamfer : public ViewProviderDressUp public: /// constructor ViewProviderChamfer() - { sPixmap = "PartDesign_Chamfer.svg"; - menuName = tr("Chamfer Parameters");} + { + sPixmap = "PartDesign_Chamfer.svg"; + menuName = tr("Chamfer Parameters"); + } /// return "Chamfer" - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; - -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderChamfer_H +#endif // PARTGUI_ViewProviderChamfer_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp index 49ae11e8ff..567c648569 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp @@ -21,21 +21,20 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include @@ -61,10 +60,10 @@ using namespace PartDesignGui; -PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProviderDatum,Gui::ViewProviderGeometryObject) +PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProviderDatum, Gui::ViewProviderGeometryObject) // static data -const double ViewProviderDatum::defaultSize = Gui::ViewProviderCoordinateSystem::defaultSize (); +const double ViewProviderDatum::defaultSize = Gui::ViewProviderCoordinateSystem::defaultSize(); ViewProviderDatum::ViewProviderDatum() { @@ -78,14 +77,15 @@ ViewProviderDatum::ViewProviderDatum() DisplayMode.setStatus(App::Property::Hidden, true); // set default color for datums (golden yellow with 60% transparency) - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath ( - "User parameter:BaseApp/Preferences/Mod/PartDesign"); - unsigned long shcol = hGrp->GetUnsigned ( "DefaultDatumColor", 0xFFD70099 ); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/PartDesign" + ); + unsigned long shcol = hGrp->GetUnsigned("DefaultDatumColor", 0xFFD70099); - Base::Color col ( (uint32_t) shcol ); + Base::Color col((uint32_t)shcol); ShapeAppearance.setDiffuseColor(col); - Transparency.setValue (col.a * 100); + Transparency.setValue(col.a * 100); oldWb = ""; oldTip = nullptr; @@ -97,13 +97,13 @@ ViewProviderDatum::~ViewProviderDatum() pPickStyle->unref(); } -void ViewProviderDatum::attach(App::DocumentObject *obj) +void ViewProviderDatum::attach(App::DocumentObject* obj) { if (auto geo = dynamic_cast(obj)) { geo->setMaterialAppearance(ShapeAppearance[0]); } - ViewProviderGeometryObject::attach ( obj ); + ViewProviderGeometryObject::attach(obj); // TODO remove this field (2015-09-08, Fat-Zer) App::DocumentObject* o = getObject(); @@ -150,9 +150,10 @@ void ViewProviderDatum::attach(App::DocumentObject *obj) addDisplayMaskMode(sep, "Base"); } -bool ViewProviderDatum::onDelete(const std::vector &) +bool ViewProviderDatum::onDelete(const std::vector&) { - // TODO: Ask user what to do about dependent objects, e.g. Sketches that have this feature as their support + // TODO: Ask user what to do about dependent objects, e.g. Sketches that have this feature as + // their support // 1. Delete // 2. Suppress // 3. Re-route @@ -162,13 +163,14 @@ bool ViewProviderDatum::onDelete(const std::vector &) std::vector ViewProviderDatum::getDisplayModes() const { - return { "Base" }; + return {"Base"}; } void ViewProviderDatum::setDisplayMode(const char* ModeName) { - if (strcmp(ModeName, "Base") == 0) + if (strcmp(ModeName, "Base") == 0) { setDisplayMaskMode("Base"); + } ViewProviderGeometryObject::setDisplayMode(ModeName); } @@ -180,16 +182,19 @@ std::string ViewProviderDatum::getElement(const SoDetail* detail) const if (detail->getTypeId() == SoLineDetail::getClassTypeId()) { const SoLineDetail* line_detail = static_cast(detail); element = line_detail->getLineIndex(); - } else if (detail->getTypeId() == SoFaceDetail::getClassTypeId()) { + } + else if (detail->getTypeId() == SoFaceDetail::getClassTypeId()) { const SoFaceDetail* face_detail = static_cast(detail); element = face_detail->getFaceIndex(); - } else if (detail->getTypeId() == SoPointDetail::getClassTypeId()) { + } + else if (detail->getTypeId() == SoPointDetail::getClassTypeId()) { const SoPointDetail* point_detail = static_cast(detail); element = point_detail->getCoordinateIndex(); } - if (element == 0) + if (element == 0) { return datumType.toStdString(); + } } return {}; @@ -200,18 +205,20 @@ SoDetail* ViewProviderDatum::getDetail(const char* subelement) const QString subelem = QString::fromLatin1(subelement); if (subelem == QObject::tr("Line")) { - SoLineDetail* detail = new SoLineDetail(); - detail->setPartIndex(0); - return detail; - } else if (subelem == QObject::tr("Plane")) { + SoLineDetail* detail = new SoLineDetail(); + detail->setPartIndex(0); + return detail; + } + else if (subelem == QObject::tr("Plane")) { SoFaceDetail* detail = new SoFaceDetail(); detail->setPartIndex(0); return detail; - } else if (subelem == QObject::tr("Point")) { + } + else if (subelem == QObject::tr("Point")) { SoPointDetail* detail = new SoPointDetail(); detail->setCoordinateIndex(0); return detail; - } + } return nullptr; } @@ -232,17 +239,19 @@ void ViewProviderDatum::setupContextMenu(QMenu* menu, QObject* receiver, const c bool ViewProviderDatum::setEdit(int ModNum) { - if (!ViewProvider::setEdit(ModNum)) + if (!ViewProvider::setEdit(ModNum)) { return false; + } // TODO Share this code with Features view providers somehow (2015-09-08, Fat-Zer) - if (ModNum == ViewProvider::Default ) { + if (ModNum == ViewProvider::Default) { // When double-clicking on the item for this datum feature the // object unsets and sets its edit mode without closing // the task panel - Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - TaskDlgDatumParameters *datumDlg = qobject_cast(dlg); - if (datumDlg && datumDlg->getViewProvider() != this) - datumDlg = nullptr; // another datum feature left open its task panel + Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); + TaskDlgDatumParameters* datumDlg = qobject_cast(dlg); + if (datumDlg && datumDlg->getViewProvider() != this) { + datumDlg = nullptr; // another datum feature left open its task panel + } if (dlg && !datumDlg) { QMessageBox msgBox(Gui::getMainWindow()); msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -250,10 +259,12 @@ bool ViewProviderDatum::setEdit(int ModNum) msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); - if (ret == QMessageBox::Yes) + if (ret == QMessageBox::Yes) { Gui::Control().closeDialog(); - else + } + else { return false; + } } // clear the selection (convenience) @@ -262,10 +273,12 @@ bool ViewProviderDatum::setEdit(int ModNum) oldWb = Gui::Command::assureWorkbench("PartDesignWorkbench"); // start the edit dialog - if (datumDlg) + if (datumDlg) { Gui::Control().showDialog(datumDlg); - else + } + else { Gui::Control().showDialog(new TaskDlgDatumParameters(this)); + } return true; } @@ -277,11 +290,13 @@ bool ViewProviderDatum::setEdit(int ModNum) bool ViewProviderDatum::doubleClicked() { auto activeDoc = Gui::Application::Instance->activeDocument(); - if(!activeDoc) + if (!activeDoc) { activeDoc = getDocument(); + } auto activeView = activeDoc->getActiveView(); - if(!activeView) + if (!activeView) { return false; + } std::string Msg("Edit "); Msg += this->pcObject->Label.getValue(); @@ -293,13 +308,16 @@ bool ViewProviderDatum::doubleClicked() if (datumBody) { if (datumBody != activeBody) { - Gui::Command::doCommand(Gui::Command::Gui, - "Gui.ActiveDocument.ActiveView.setActiveObject('%s',%s)", - PDBODYKEY, Gui::Command::getObjectCmd(datumBody).c_str()); + Gui::Command::doCommand( + Gui::Command::Gui, + "Gui.ActiveDocument.ActiveView.setActiveObject('%s',%s)", + PDBODYKEY, + Gui::Command::getObjectCmd(datumBody).c_str() + ); activeBody = datumBody; } } - return PartDesignGui::setEdit(pcObject,activeBody); + return PartDesignGui::setEdit(pcObject, activeBody); } void ViewProviderDatum::unsetEdit(int ModNum) @@ -316,75 +334,97 @@ void ViewProviderDatum::unsetEdit(int ModNum) } } -void ViewProviderDatum::updateExtents () { - setExtents ( getRelevantBoundBox () ); +void ViewProviderDatum::updateExtents() +{ + setExtents(getRelevantBoundBox()); } -void ViewProviderDatum::setExtents (const SbBox3f &bbox) { - const SbVec3f & min = bbox.getMin (); - const SbVec3f & max = bbox.getMax (); - setExtents ( Base::BoundBox3d ( min.getValue()[0], min.getValue()[1], min.getValue()[2], - max.getValue()[0], max.getValue()[1], max.getValue()[2] ) ); +void ViewProviderDatum::setExtents(const SbBox3f& bbox) +{ + const SbVec3f& min = bbox.getMin(); + const SbVec3f& max = bbox.getMax(); + setExtents( + Base::BoundBox3d( + min.getValue()[0], + min.getValue()[1], + min.getValue()[2], + max.getValue()[0], + max.getValue()[1], + max.getValue()[2] + ) + ); } -SbBox3f ViewProviderDatum::getRelevantBoundBox () const { - std::vector objs; +SbBox3f ViewProviderDatum::getRelevantBoundBox() const +{ + std::vector objs; // Probe body first - PartDesign::Body* body = PartDesign::Body::findBodyOf ( this->getObject() ); + PartDesign::Body* body = PartDesign::Body::findBodyOf(this->getObject()); if (body) { - objs = body->getFullModel (); - } else { + objs = body->getFullModel(); + } + else { // Probe if we belongs to some group - App::DocumentObject* group = App::DocumentObjectGroup::getGroupOfObject ( this->getObject () ); + App::DocumentObject* group = App::DocumentObjectGroup::getGroupOfObject(this->getObject()); - if(group) { + if (group) { auto* ext = group->getExtensionByType(); - if(ext) - objs = ext->getObjects (); - } else { + if (ext) { + objs = ext->getObjects(); + } + } + else { // Fallback to whole document - objs = this->getObject ()->getDocument ()->getObjects (); + objs = this->getObject()->getDocument()->getObjects(); } } Gui::View3DInventor* view = dynamic_cast(this->getActiveView()); - if(view){ - Gui::View3DInventorViewer* viewer = view->getViewer(); - SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion()); - SbBox3f bbox = getRelevantBoundBox (bboxAction, objs); + if (view) { + Gui::View3DInventorViewer* viewer = view->getViewer(); + SoGetBoundingBoxAction bboxAction(viewer->getSoRenderManager()->getViewportRegion()); + SbBox3f bbox = getRelevantBoundBox(bboxAction, objs); - if ( bbox.getVolume () < Precision::Confusion() ) { - bbox.extendBy ( defaultBoundBox () ); - } - return bbox; - } else { - return defaultBoundBox(); + if (bbox.getVolume() < Precision::Confusion()) { + bbox.extendBy(defaultBoundBox()); + } + return bbox; + } + else { + return defaultBoundBox(); } } -SbBox3f ViewProviderDatum::getRelevantBoundBox ( - SoGetBoundingBoxAction &bboxAction, const std::vector &objs ) +SbBox3f ViewProviderDatum::getRelevantBoundBox( + SoGetBoundingBoxAction& bboxAction, + const std::vector& objs +) { SbBox3f bbox = defaultBoundBox(); // Adds the bbox of given feature to the output - for (auto obj :objs) { - ViewProvider *vp = Gui::Application::Instance->getViewProvider(obj); - if (!vp) { continue; } - if (!vp->isVisible ()) { continue; } + for (auto obj : objs) { + ViewProvider* vp = Gui::Application::Instance->getViewProvider(obj); + if (!vp) { + continue; + } + if (!vp->isVisible()) { + continue; + } - if (obj->isDerivedFrom (Part::Datum::getClassTypeId() ) ) { + if (obj->isDerivedFrom(Part::Datum::getClassTypeId())) { // Treat datums only as their basepoint // I hope it's ok to take FreeCAD's point here - Base::Vector3d basePoint = static_cast ( obj )->getBasePoint (); - bbox.extendBy (SbVec3f(basePoint.x, basePoint.y, basePoint.z )); - } else { - bboxAction.apply ( vp->getRoot () ); - SbBox3f obj_bbox = bboxAction.getBoundingBox (); + Base::Vector3d basePoint = static_cast(obj)->getBasePoint(); + bbox.extendBy(SbVec3f(basePoint.x, basePoint.y, basePoint.z)); + } + else { + bboxAction.apply(vp->getRoot()); + SbBox3f obj_bbox = bboxAction.getBoundingBox(); - if ( obj_bbox.getVolume () < Precision::Infinite () ) { - bbox.extendBy ( obj_bbox ); + if (obj_bbox.getVolume() < Precision::Infinite()) { + bbox.extendBy(obj_bbox); } } } @@ -393,20 +433,24 @@ SbBox3f ViewProviderDatum::getRelevantBoundBox ( return bbox; } -SbBox3f ViewProviderDatum::defaultBoundBox () { - return SbBox3f ( -defaultSize, -defaultSize, -defaultSize, - defaultSize, defaultSize, defaultSize ); +SbBox3f ViewProviderDatum::defaultBoundBox() +{ + return SbBox3f(-defaultSize, -defaultSize, -defaultSize, defaultSize, defaultSize, defaultSize); } -bool ViewProviderDatum::isPickable() { +bool ViewProviderDatum::isPickable() +{ return bool(pPickStyle->style.getValue() == SoPickStyle::SHAPE); } -void ViewProviderDatum::setPickable(bool val) { +void ViewProviderDatum::setPickable(bool val) +{ - if(val) + if (val) { pPickStyle->style = SoPickStyle::SHAPE; - else + } + else { pPickStyle->style = SoPickStyle::UNPICKABLE; + } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatum.h b/src/Mod/PartDesign/Gui/ViewProviderDatum.h index 07f5a86765..d325933bff 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatum.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatum.h @@ -35,9 +35,11 @@ class SoPickStyle; class SbBox3f; class SoGetBoundingBoxAction; -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderDatum : public Gui::ViewProviderGeometryObject, PartGui::ViewProviderAttachExtension +class PartDesignGuiExport ViewProviderDatum: public Gui::ViewProviderGeometryObject, + PartGui::ViewProviderAttachExtension { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderDatum) PROPERTY_HEADER_WITH_EXTENSIONS(PartDesignGui::ViewProviderDatum); @@ -51,18 +53,21 @@ public: /// grouping handling void setupContextMenu(QMenu*, QObject*, const char*) override; - void attach(App::DocumentObject *) override; - bool onDelete(const std::vector &) override; + void attach(App::DocumentObject*) override; + bool onDelete(const std::vector&) override; bool doubleClicked() override; std::vector getDisplayModes() const override; void setDisplayMode(const char* ModeName) override; /// indicates if the ViewProvider use the new Selection model - bool useNewSelectionModel() const override { return true; } + bool useNewSelectionModel() const override + { + return true; + } /// indicates if the ViewProvider can be selected bool isSelectable() const override; /// return a hit element to the selection path or 0 - std::string getElement(const SoDetail *) const override; + std::string getElement(const SoDetail*) const override; SoDetail* getDetail(const char*) const override; /** @@ -78,14 +83,14 @@ public: * @note should be reimplemented in the offspings * @note use FreeCAD-specific bbox here to simplify the math in derived classes */ - virtual void setExtents (Base::BoundBox3d /*bbox*/) - { } + virtual void setExtents(Base::BoundBox3d /*bbox*/) + {} /// Update the visual sizes. This overloaded version of the previous function to allow pass coin type - void setExtents (const SbBox3f &bbox); + void setExtents(const SbBox3f& bbox); /// update size to match the guessed bounding box - void updateExtents (); + void updateExtents(); /// The datum type (Plane, Line or Point) // TODO remove this attribute (2015-09-08, Fat-Zer) @@ -96,21 +101,25 @@ public: /** * Computes appropriate bounding box for the given list of objects to be passed to setExtents () * @param bboxAction a coin action for traverse the given objects views. - * @param objs the list of objects to traverse, due to we traverse the scene graph, the geo children - * will likely be traversed too. + * @param objs the list of objects to traverse, due to we traverse the scene graph, the + * geo children will likely be traversed too. */ - static SbBox3f getRelevantBoundBox ( - SoGetBoundingBoxAction &bboxAction, - const std::vector &objs); + static SbBox3f getRelevantBoundBox( + SoGetBoundingBoxAction& bboxAction, + const std::vector& objs + ); /// Default size used to produce the default bbox static const double defaultSize; // Returned default bounding box if relevant is can't be used for some reason - static SbBox3f defaultBoundBox (); + static SbBox3f defaultBoundBox(); // Returns a default margin factor (part of size ) - static double marginFactor () { return 0.1; }; + static double marginFactor() + { + return 0.1; + }; protected: bool setEdit(int ModNum) override; @@ -128,17 +137,19 @@ protected: SbBox3f getRelevantBoundBox() const; // Get the separator to fill with datum content - SoSeparator *getShapeRoot () { return pShapeSep; } + SoSeparator* getShapeRoot() + { + return pShapeSep; + } private: SoSeparator* pShapeSep; SoPickStyle* pPickStyle; std::string oldWb; App::DocumentObject* oldTip; - }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDatum_H +#endif // PARTGUI_ViewProviderDatum_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumCS.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatumCS.cpp index a0869a6c5d..2b7b9c7a76 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumCS.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumCS.cpp @@ -22,15 +22,15 @@ #include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -40,12 +40,12 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumCoordinateSystem,PartDesignGui::ViewProviderDatum) +PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumCoordinateSystem, PartDesignGui::ViewProviderDatum) -const App::PropertyFloatConstraint::Constraints ZoomConstraint = { - 0.0, std::numeric_limits::max(), 0.2}; -const App::PropertyIntegerConstraint::Constraints FontConstraint = { - 1,std::numeric_limits::max(), 1}; +const App::PropertyFloatConstraint::Constraints ZoomConstraint + = {0.0, std::numeric_limits::max(), 0.2}; +const App::PropertyIntegerConstraint::Constraints FontConstraint + = {1, std::numeric_limits::max(), 1}; ViewProviderDatumCoordinateSystem::ViewProviderDatumCoordinateSystem() { @@ -53,17 +53,19 @@ ViewProviderDatumCoordinateSystem::ViewProviderDatumCoordinateSystem() FontSize.setConstraints(&FontConstraint); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/PartDesign"); - auto fontSize = hGrp->GetInt("CoordinateSystemFontSize",10); - auto zoom = hGrp->GetFloat("CoordinateSystemZoom",1.0); - auto showLabel = hGrp->GetBool("CoordinateSystemShowLabel",false); + "User parameter:BaseApp/Preferences/Mod/PartDesign" + ); + auto fontSize = hGrp->GetInt("CoordinateSystemFontSize", 10); + auto zoom = hGrp->GetFloat("CoordinateSystemZoom", 1.0); + auto showLabel = hGrp->GetBool("CoordinateSystemShowLabel", false); ADD_PROPERTY_TYPE(FontSize, (fontSize), "Datum", App::Prop_None, ""); ADD_PROPERTY_TYPE(Zoom, (zoom), "Datum", App::Prop_None, ""); ADD_PROPERTY_TYPE(ShowLabel, (showLabel), "Datum", App::Prop_None, ""); - if(hGrp->GetBool("CoordinateSystemSelectOnTop",true)) + if (hGrp->GetBool("CoordinateSystemSelectOnTop", true)) { OnTopWhenSelected.setValue(1); + } sPixmap = "PartDesign_CoordinateSystem.svg"; @@ -92,13 +94,15 @@ ViewProviderDatumCoordinateSystem::~ViewProviderDatumCoordinateSystem() axisLabelXTrans->unref(); axisLabelXToYTrans->unref(); axisLabelYToZTrans->unref(); - if(labelSwitch) + if (labelSwitch) { labelSwitch->unref(); + } autoZoom->unref(); } -void ViewProviderDatumCoordinateSystem::attach ( App::DocumentObject *obj ) { - ViewProviderDatum::attach ( obj ); +void ViewProviderDatumCoordinateSystem::attach(App::DocumentObject* obj) +{ + ViewProviderDatum::attach(obj); SoMaterial* material = new SoMaterial(); material->diffuseColor.setNum(4); @@ -110,19 +114,19 @@ void ViewProviderDatumCoordinateSystem::attach ( App::DocumentObject *obj ) { binding->value = SoMaterialBinding::PER_FACE_INDEXED; autoZoom->scaleFactor.setValue(Zoom.getValue()); - getShapeRoot ()->addChild(autoZoom); - getShapeRoot ()->addChild(binding); - getShapeRoot ()->addChild(material); + getShapeRoot()->addChild(autoZoom); + getShapeRoot()->addChild(binding); + getShapeRoot()->addChild(material); coord->point.setNum(7); - ViewProviderDatum::setExtents ( defaultBoundBox () ); + ViewProviderDatum::setExtents(defaultBoundBox()); - getShapeRoot ()->addChild(coord); + getShapeRoot()->addChild(coord); - SoDrawStyle* style = new SoDrawStyle (); + SoDrawStyle* style = new SoDrawStyle(); style->lineWidth = 2.0f; - getShapeRoot ()->addChild(style); + getShapeRoot()->addChild(style); PartGui::SoBrepEdgeSet* lineSet = new PartGui::SoBrepEdgeSet(); lineSet->coordIndex.setNum(9); @@ -140,21 +144,24 @@ void ViewProviderDatumCoordinateSystem::attach ( App::DocumentObject *obj ) { lineSet->coordIndex.set1Value(8, SO_END_LINE_INDEX); lineSet->materialIndex.setNum(3); - lineSet->materialIndex.set1Value(0,1); - lineSet->materialIndex.set1Value(1,2); - lineSet->materialIndex.set1Value(2,3); - getShapeRoot ()->addChild(lineSet); + lineSet->materialIndex.set1Value(0, 1); + lineSet->materialIndex.set1Value(1, 2); + lineSet->materialIndex.set1Value(2, 3); + getShapeRoot()->addChild(lineSet); setupLabels(); } -void ViewProviderDatumCoordinateSystem::setupLabels() { +void ViewProviderDatumCoordinateSystem::setupLabels() +{ - if(!ShowLabel.getValue()) { - if(labelSwitch) + if (!ShowLabel.getValue()) { + if (labelSwitch) { labelSwitch->whichChild = -1; + } return; - }else if(labelSwitch) { + } + else if (labelSwitch) { labelSwitch->whichChild = 0; return; } @@ -162,9 +169,9 @@ void ViewProviderDatumCoordinateSystem::setupLabels() { labelSwitch = new SoSwitch; labelSwitch->ref(); - getShapeRoot ()->addChild(labelSwitch); + getShapeRoot()->addChild(labelSwitch); - SoGroup *labelGroup = new SoGroup; + SoGroup* labelGroup = new SoGroup; labelSwitch->addChild(labelGroup); labelSwitch->whichChild = 0; @@ -189,68 +196,77 @@ void ViewProviderDatumCoordinateSystem::setupLabels() { void ViewProviderDatumCoordinateSystem::updateData(const App::Property* prop) { - if (strcmp(prop->getName(),"Placement") == 0) - updateExtents (); + if (strcmp(prop->getName(), "Placement") == 0) { + updateExtents(); + } ViewProviderDatum::updateData(prop); } -void ViewProviderDatumCoordinateSystem::onChanged(const App::Property *prop) { - if(getObject()) { - if(prop == &ShowLabel) +void ViewProviderDatumCoordinateSystem::onChanged(const App::Property* prop) +{ + if (getObject()) { + if (prop == &ShowLabel) { setupLabels(); - else if(prop == &Zoom) { + } + else if (prop == &Zoom) { autoZoom->scaleFactor.setValue(Zoom.getValue()); - updateExtents (); - } else if(prop == &FontSize) + updateExtents(); + } + else if (prop == &FontSize) { font->size = FontSize.getValue(); + } } ViewProviderDatum::onChanged(prop); } -void ViewProviderDatumCoordinateSystem::setExtents (Base::BoundBox3d bbox) { +void ViewProviderDatumCoordinateSystem::setExtents(Base::BoundBox3d bbox) +{ // Axis length of the CS is 1/3 of maximum bbox dimension, any smarter sizing will make it only worse double axisLength; // Empty gap at the origin of the coordinate system, this is a nice experimental value double centerGap; - if(Zoom.getValue()) { + if (Zoom.getValue()) { axisLength = 6 * Zoom.getValue(); - }else{ - axisLength = std::max ( { bbox.LengthX (), bbox.LengthY(), bbox.LengthZ() } ); - axisLength *= (1 + marginFactor ()) / 3; + } + else { + axisLength = std::max({bbox.LengthX(), bbox.LengthY(), bbox.LengthZ()}); + axisLength *= (1 + marginFactor()) / 3; } centerGap = axisLength / 8.; - - coord->point.set1Value ( 0, 0, 0, 0 ); - coord->point.set1Value ( 1, centerGap, 0, 0 ); - coord->point.set1Value ( 2, axisLength, 0, 0 ); - coord->point.set1Value ( 3, 0, centerGap, 0 ); - coord->point.set1Value ( 4, 0, axisLength, 0 ); - coord->point.set1Value ( 5, 0, 0, centerGap ); - coord->point.set1Value ( 6, 0, 0, axisLength ); + + coord->point.set1Value(0, 0, 0, 0); + coord->point.set1Value(1, centerGap, 0, 0); + coord->point.set1Value(2, axisLength, 0, 0); + coord->point.set1Value(3, 0, centerGap, 0); + coord->point.set1Value(4, 0, axisLength, 0); + coord->point.set1Value(5, 0, 0, centerGap); + coord->point.set1Value(6, 0, 0, axisLength); double labelPos = axisLength; double labelOffset = 0; // offset 1 pixel - axisLabelXTrans->translation.setValue ( SbVec3f( labelPos, labelOffset, 0) ); - axisLabelXToYTrans->translation.setValue ( SbVec3f( -labelPos + labelOffset, labelPos - labelOffset, 0) ); - axisLabelYToZTrans->translation.setValue ( SbVec3f( -labelOffset, -labelPos + labelOffset, labelPos) ); + axisLabelXTrans->translation.setValue(SbVec3f(labelPos, labelOffset, 0)); + axisLabelXToYTrans->translation.setValue( + SbVec3f(-labelPos + labelOffset, labelPos - labelOffset, 0) + ); + axisLabelYToZTrans->translation.setValue(SbVec3f(-labelOffset, -labelPos + labelOffset, labelPos)); } std::string ViewProviderDatumCoordinateSystem::getElement(const SoDetail* detail) const { if (detail && detail->getTypeId() == SoLineDetail::getClassTypeId()) { const SoLineDetail* line_detail = static_cast(detail); - switch(line_detail->getLineIndex()) { - case 0: - return "X"; - case 1: - return "Y"; - case 2: - return "Z"; + switch (line_detail->getLineIndex()) { + case 0: + return "X"; + case 1: + return "Y"; + case 2: + return "Z"; } } @@ -259,19 +275,20 @@ std::string ViewProviderDatumCoordinateSystem::getElement(const SoDetail* detail SoDetail* ViewProviderDatumCoordinateSystem::getDetail(const char* subelement) const { - if (strcmp(subelement,"X")==0) { - SoLineDetail* detail = new SoLineDetail(); - detail->setLineIndex(0); - return detail; - } else if (strcmp(subelement,"Y")==0) { - SoLineDetail* detail = new SoLineDetail(); - detail->setLineIndex(1); - return detail; - } else if (strcmp(subelement,"Z")==0) { - SoLineDetail* detail = new SoLineDetail(); - detail->setLineIndex(2); - return detail; + if (strcmp(subelement, "X") == 0) { + SoLineDetail* detail = new SoLineDetail(); + detail->setLineIndex(0); + return detail; + } + else if (strcmp(subelement, "Y") == 0) { + SoLineDetail* detail = new SoLineDetail(); + detail->setLineIndex(1); + return detail; + } + else if (strcmp(subelement, "Z") == 0) { + SoLineDetail* detail = new SoLineDetail(); + detail->setLineIndex(2); + return detail; } return nullptr; } - diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h b/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h index 0441a9db9a..34264e9a44 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h @@ -30,13 +30,15 @@ class SoCoordinate3; class SoFont; class SoTranslation; -namespace Gui { +namespace Gui +{ class SoAutoZoomTranslation; } -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderDatumCoordinateSystem : public PartDesignGui::ViewProviderDatum +class PartDesignGuiExport ViewProviderDatumCoordinateSystem: public PartDesignGui::ViewProviderDatum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumCoordinateSystem); @@ -49,11 +51,11 @@ public: ViewProviderDatumCoordinateSystem(); ~ViewProviderDatumCoordinateSystem() override; - void attach ( App::DocumentObject *obj ) override; + void attach(App::DocumentObject* obj) override; void updateData(const App::Property*) override; void onChanged(const App::Property*) override; - void setExtents (Base::BoundBox3d bbox) override; + void setExtents(Base::BoundBox3d bbox) override; SoDetail* getDetail(const char* subelement) const override; std::string getElement(const SoDetail* detail) const override; @@ -62,16 +64,16 @@ private: void setupLabels(); private: - SoCoordinate3 *coord; - SoTranslation *axisLabelXTrans; - SoTranslation *axisLabelXToYTrans; - SoTranslation *axisLabelYToZTrans; + SoCoordinate3* coord; + SoTranslation* axisLabelXTrans; + SoTranslation* axisLabelXToYTrans; + SoTranslation* axisLabelYToZTrans; SoFont* font; - SoSwitch *labelSwitch; - Gui::SoAutoZoomTranslation *autoZoom; + SoSwitch* labelSwitch; + Gui::SoAutoZoomTranslation* autoZoom; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDatumCoordinateSystem_H +#endif // PARTGUI_ViewProviderDatumCoordinateSystem_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumLine.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatumLine.cpp index 7bf6ad4a4d..3769fa7796 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumLine.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumLine.cpp @@ -22,8 +22,8 @@ ***************************************************************************/ -# include -# include +#include +#include #include @@ -33,26 +33,29 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumLine,PartDesignGui::ViewProviderDatum) +PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumLine, PartDesignGui::ViewProviderDatum) -ViewProviderDatumLine::ViewProviderDatumLine() { +ViewProviderDatumLine::ViewProviderDatumLine() +{ sPixmap = "PartDesign_Line.svg"; pCoords = new SoCoordinate3(); - pCoords->ref (); + pCoords->ref(); } -ViewProviderDatumLine::~ViewProviderDatumLine() { - pCoords->unref (); +ViewProviderDatumLine::~ViewProviderDatumLine() +{ + pCoords->unref(); } -void ViewProviderDatumLine::attach ( App::DocumentObject *obj ) { - ViewProviderDatum::attach ( obj ); +void ViewProviderDatumLine::attach(App::DocumentObject* obj) +{ + ViewProviderDatum::attach(obj); PartGui::SoBrepEdgeSet* lineSet; - ViewProviderDatum::setExtents ( defaultBoundBox () ); - getShapeRoot ()->addChild(pCoords); + ViewProviderDatum::setExtents(defaultBoundBox()); + getShapeRoot()->addChild(pCoords); lineSet = new PartGui::SoBrepEdgeSet(); lineSet->coordIndex.setNum(3); @@ -60,51 +63,53 @@ void ViewProviderDatumLine::attach ( App::DocumentObject *obj ) { lineSet->coordIndex.set1Value(1, 1); lineSet->coordIndex.set1Value(2, SO_END_LINE_INDEX); - getShapeRoot ()->addChild(lineSet); + getShapeRoot()->addChild(lineSet); } void ViewProviderDatumLine::updateData(const App::Property* prop) { // Gets called whenever a property of the attached object changes - if (strcmp(prop->getName(),"Placement") == 0) { - updateExtents (); + if (strcmp(prop->getName(), "Placement") == 0) { + updateExtents(); } - else if (strcmp(prop->getName(),"Length") == 0) { + else if (strcmp(prop->getName(), "Length") == 0) { PartDesign::Line* pcDatum = this->getObject(); - if (pcDatum->ResizeMode.getValue() != 0) + if (pcDatum->ResizeMode.getValue() != 0) { setExtents(pcDatum->Length.getValue()); + } } ViewProviderDatum::updateData(prop); } -void ViewProviderDatumLine::setExtents (Base::BoundBox3d bbox) { +void ViewProviderDatumLine::setExtents(Base::BoundBox3d bbox) +{ PartDesign::Line* pcDatum = this->getObject(); // set manual size if (pcDatum->ResizeMode.getValue() != 0) { setExtents(pcDatum->Length.getValue()); return; } - Base::Placement plm = pcDatum->Placement.getValue ().inverse (); + Base::Placement plm = pcDatum->Placement.getValue().inverse(); // Transform the box to the line's coordinates, the result line will be larger than the bbox - bbox = bbox.Transformed ( plm.toMatrix() ); + bbox = bbox.Transformed(plm.toMatrix()); // Add origin of the line to the box if it's not - bbox.Add ( Base::Vector3d (0, 0, 0) ); + bbox.Add(Base::Vector3d(0, 0, 0)); - double margin = bbox.LengthZ () * marginFactor (); + double margin = bbox.LengthZ() * marginFactor(); // Display the line - pCoords->point.setNum (2); - pCoords->point.set1Value(0, 0, 0, bbox.MaxZ + margin ); - pCoords->point.set1Value(1, 0, 0, bbox.MinZ - margin ); + pCoords->point.setNum(2); + pCoords->point.set1Value(0, 0, 0, bbox.MaxZ + margin); + pCoords->point.set1Value(1, 0, 0, bbox.MinZ - margin); } void ViewProviderDatumLine::setExtents(double l) { // Change the coordinates of the line - pCoords->point.setNum (2); - pCoords->point.set1Value(0, 0, 0, l/2 ); - pCoords->point.set1Value(1, 0, 0, -l/2 ); + pCoords->point.setNum(2); + pCoords->point.set1Value(0, 0, 0, l / 2); + pCoords->point.set1Value(1, 0, 0, -l / 2); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h b/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h index c43a428dbb..2283da77c0 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h @@ -29,9 +29,10 @@ class SoCoordinate3; -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderDatumLine : public PartDesignGui::ViewProviderDatum +class PartDesignGuiExport ViewProviderDatumLine: public PartDesignGui::ViewProviderDatum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumLine); @@ -40,17 +41,17 @@ public: ViewProviderDatumLine(); ~ViewProviderDatumLine() override; - void attach ( App::DocumentObject *obj ) override; + void attach(App::DocumentObject* obj) override; void updateData(const App::Property*) override; - void setExtents (Base::BoundBox3d bbox) override; + void setExtents(Base::BoundBox3d bbox) override; void setExtents(double l); private: - SoCoordinate3 *pCoords; + SoCoordinate3* pCoords; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDatumLine_H +#endif // PARTGUI_ViewProviderDatumLine_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.cpp index 791f78ce54..2c03e0d7e4 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.cpp @@ -22,9 +22,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -35,27 +34,28 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumPlane,PartDesignGui::ViewProviderDatum) +PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumPlane, PartDesignGui::ViewProviderDatum) ViewProviderDatumPlane::ViewProviderDatumPlane() { sPixmap = "PartDesign_Plane.svg"; pCoords = new SoCoordinate3(); - pCoords->ref (); + pCoords->ref(); } ViewProviderDatumPlane::~ViewProviderDatumPlane() { - pCoords->unref (); + pCoords->unref(); } -void ViewProviderDatumPlane::attach ( App::DocumentObject *obj ) { +void ViewProviderDatumPlane::attach(App::DocumentObject* obj) +{ - ViewProviderDatum::attach ( obj ); + ViewProviderDatum::attach(obj); - ViewProviderDatum::setExtents ( defaultBoundBox () ); - getShapeRoot ()->addChild(pCoords); + ViewProviderDatum::setExtents(defaultBoundBox()); + getShapeRoot()->addChild(pCoords); PartGui::SoBrepEdgeSet* lineSet = new PartGui::SoBrepEdgeSet(); lineSet->coordIndex.setNum(6); @@ -65,11 +65,11 @@ void ViewProviderDatumPlane::attach ( App::DocumentObject *obj ) { lineSet->coordIndex.set1Value(3, 3); lineSet->coordIndex.set1Value(4, 0); lineSet->coordIndex.set1Value(5, SO_END_LINE_INDEX); - getShapeRoot ()->addChild(lineSet); + getShapeRoot()->addChild(lineSet); - PartGui::SoBrepFaceSet *faceSet = new PartGui::SoBrepFaceSet(); + PartGui::SoBrepFaceSet* faceSet = new PartGui::SoBrepFaceSet(); // SoBrepFaceSet supports only triangles (otherwise we receive incorrect highlighting) - faceSet->partIndex.set1Value(0, 2); // One face, two triangles + faceSet->partIndex.set1Value(0, 2); // One face, two triangles faceSet->coordIndex.setNum(8); // first triangle faceSet->coordIndex.set1Value(0, 0); @@ -82,59 +82,60 @@ void ViewProviderDatumPlane::attach ( App::DocumentObject *obj ) { faceSet->coordIndex.set1Value(6, 0); faceSet->coordIndex.set1Value(7, SO_END_FACE_INDEX); - getShapeRoot ()->addChild(faceSet); + getShapeRoot()->addChild(faceSet); } void ViewProviderDatumPlane::updateData(const App::Property* prop) { // Gets called whenever a property of the attached object changes - if (strcmp(prop->getName(),"Placement") == 0) { - updateExtents (); + if (strcmp(prop->getName(), "Placement") == 0) { + updateExtents(); } - else if (strcmp(prop->getName(),"Length") == 0 || - strcmp(prop->getName(),"Width") == 0) { + else if (strcmp(prop->getName(), "Length") == 0 || strcmp(prop->getName(), "Width") == 0) { PartDesign::Plane* pcDatum = this->getObject(); - if (pcDatum->ResizeMode.getValue() != 0) + if (pcDatum->ResizeMode.getValue() != 0) { setExtents(pcDatum->Length.getValue(), pcDatum->Width.getValue()); + } } ViewProviderDatum::updateData(prop); } -void ViewProviderDatumPlane::setExtents (Base::BoundBox3d bbox) { +void ViewProviderDatumPlane::setExtents(Base::BoundBox3d bbox) +{ PartDesign::Plane* pcDatum = this->getObject(); if (pcDatum->ResizeMode.getValue() != 0) { setExtents(pcDatum->Length.getValue(), pcDatum->Width.getValue()); return; } - Base::Placement plm = pcDatum->Placement.getValue ().inverse (); + Base::Placement plm = pcDatum->Placement.getValue().inverse(); // Transform the box to the line's coordinates, the result line will be larger than the bbox - bbox = bbox.Transformed ( plm.toMatrix() ); + bbox = bbox.Transformed(plm.toMatrix()); // Add origin of the plane to the box if it's not - bbox.Add ( Base::Vector3d (0, 0, 0) ); + bbox.Add(Base::Vector3d(0, 0, 0)); - double margin = sqrt(bbox.LengthX ()*bbox.LengthY ()) * marginFactor (); + double margin = sqrt(bbox.LengthX() * bbox.LengthY()) * marginFactor(); - pcDatum->Length.setValue(bbox.LengthX() + 2*margin); - pcDatum->Width.setValue(bbox.LengthY() + 2*margin); + pcDatum->Length.setValue(bbox.LengthX() + 2 * margin); + pcDatum->Width.setValue(bbox.LengthY() + 2 * margin); // Change the coordinates of the line - pCoords->point.setNum (4); - pCoords->point.set1Value(0, bbox.MaxX + margin, bbox.MaxY + margin, 0 ); - pCoords->point.set1Value(1, bbox.MinX - margin, bbox.MaxY + margin, 0 ); - pCoords->point.set1Value(2, bbox.MinX - margin, bbox.MinY - margin, 0 ); - pCoords->point.set1Value(3, bbox.MaxX + margin, bbox.MinY - margin, 0 ); + pCoords->point.setNum(4); + pCoords->point.set1Value(0, bbox.MaxX + margin, bbox.MaxY + margin, 0); + pCoords->point.set1Value(1, bbox.MinX - margin, bbox.MaxY + margin, 0); + pCoords->point.set1Value(2, bbox.MinX - margin, bbox.MinY - margin, 0); + pCoords->point.set1Value(3, bbox.MaxX + margin, bbox.MinY - margin, 0); } void ViewProviderDatumPlane::setExtents(double l, double w) { // Change the coordinates of the line - pCoords->point.setNum (4); - pCoords->point.set1Value(0, l/2, w/2, 0); - pCoords->point.set1Value(1, -l/2, w/2, 0); - pCoords->point.set1Value(2, -l/2, -w/2, 0); - pCoords->point.set1Value(3, l/2, -w/2, 0); + pCoords->point.setNum(4); + pCoords->point.set1Value(0, l / 2, w / 2, 0); + pCoords->point.set1Value(1, -l / 2, w / 2, 0); + pCoords->point.set1Value(2, -l / 2, -w / 2, 0); + pCoords->point.set1Value(3, l / 2, -w / 2, 0); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h b/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h index 2540ff8645..e3030290d6 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h @@ -27,9 +27,10 @@ #include "ViewProviderDatum.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderDatumPlane : public PartDesignGui::ViewProviderDatum +class PartDesignGuiExport ViewProviderDatumPlane: public PartDesignGui::ViewProviderDatum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumPlane); @@ -38,17 +39,17 @@ public: ViewProviderDatumPlane(); ~ViewProviderDatumPlane() override; - void attach ( App::DocumentObject *obj ) override; + void attach(App::DocumentObject* obj) override; void updateData(const App::Property*) override; - void setExtents (Base::BoundBox3d bbox) override; + void setExtents(Base::BoundBox3d bbox) override; void setExtents(double l, double w); private: - SoCoordinate3 *pCoords; + SoCoordinate3* pCoords; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDatumPlane_H +#endif // PARTGUI_ViewProviderDatumPlane_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.cpp index 3735160391..1b271c3838 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.cpp @@ -22,11 +22,10 @@ ***************************************************************************/ - -# include -# include -# include -# include +#include +#include +#include +#include #include @@ -39,43 +38,45 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumPoint,PartDesignGui::ViewProviderDatum) +PROPERTY_SOURCE(PartDesignGui::ViewProviderDatumPoint, PartDesignGui::ViewProviderDatum) ViewProviderDatumPoint::ViewProviderDatumPoint() { sPixmap = "PartDesign_Point.svg"; // SoMarkerSet won't be drawn if transparency is nonzero, so disabble it - Transparency.setValue (0); - Transparency.setStatus(App::Property::Hidden, true); //< make transparency hidden + Transparency.setValue(0); + Transparency.setStatus(App::Property::Hidden, true); //< make transparency hidden } ViewProviderDatumPoint::~ViewProviderDatumPoint() = default; -void ViewProviderDatumPoint::attach ( App::DocumentObject *obj ) { - ViewProviderDatum::attach ( obj ); +void ViewProviderDatumPoint::attach(App::DocumentObject* obj) +{ + ViewProviderDatum::attach(obj); - const int markerSize = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View")->GetInt("MarkerSize", 9); + const int markerSize = App::GetApplication() + .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") + ->GetInt("MarkerSize", 9); // Using a marker gives a larger point. - auto *marker = new SoMarkerSet(); + auto* marker = new SoMarkerSet(); marker->numPoints = 1; - marker->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("DIAMOND_FILLED", - markerSize); + marker->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex("DIAMOND_FILLED", markerSize); - auto *pcHighlight = Gui::ViewProviderBuilder::createSelection(); + auto* pcHighlight = Gui::ViewProviderBuilder::createSelection(); pcHighlight->style = Gui::SoFCSelection::EMISSIVE_DIFFUSE; pcHighlight->addChild(new SoCoordinate3()); pcHighlight->addChild(marker); - getShapeRoot ()->addChild(pcHighlight); + getShapeRoot()->addChild(pcHighlight); } -void ViewProviderDatumPoint::onChanged (const App::Property* prop) { +void ViewProviderDatumPoint::onChanged(const App::Property* prop) +{ // Forbid to set trancparency if (prop == &Transparency && Transparency.getValue() != 0) { - Transparency.setValue (0); + Transparency.setValue(0); } - ViewProviderDatum::onChanged (prop); + ViewProviderDatum::onChanged(prop); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h b/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h index 910dc64b56..5697aa8ec8 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h @@ -27,9 +27,10 @@ #include "ViewProviderDatum.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderDatumPoint : public PartDesignGui::ViewProviderDatum +class PartDesignGuiExport ViewProviderDatumPoint: public PartDesignGui::ViewProviderDatum { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumPoint); @@ -38,7 +39,7 @@ public: ViewProviderDatumPoint(); ~ViewProviderDatumPoint() override; - void attach ( App::DocumentObject *obj ) override; + void attach(App::DocumentObject* obj) override; // Note: don't overload setExtents () here because point doesn't really depends on it @@ -46,7 +47,7 @@ protected: void onChanged(const App::Property* prop) override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDatumPoint_H +#endif // PARTGUI_ViewProviderDatumPoint_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDraft.cpp b/src/Mod/PartDesign/Gui/ViewProviderDraft.cpp index 75449aaaa3..b5fe47824d 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDraft.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDraft.cpp @@ -22,16 +22,16 @@ ***************************************************************************/ - #include "TaskDraftParameters.h" #include "ViewProviderDraft.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderDraft,PartDesignGui::ViewProviderDressUp) +PROPERTY_SOURCE(PartDesignGui::ViewProviderDraft, PartDesignGui::ViewProviderDressUp) -const std::string & ViewProviderDraft::featureName() const { +const std::string& ViewProviderDraft::featureName() const +{ static const std::string name = "Draft"; return name; } @@ -42,6 +42,7 @@ void ViewProviderDraft::setupContextMenu(QMenu* menu, QObject* receiver, const c PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderDraft::getEditDialog() { - return new TaskDlgDraftParameters (this); +TaskDlgFeatureParameters* ViewProviderDraft::getEditDialog() +{ + return new TaskDlgDraftParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderDraft.h b/src/Mod/PartDesign/Gui/ViewProviderDraft.h index 90aeae4c92..752486774a 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDraft.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDraft.h @@ -28,9 +28,10 @@ #include "ViewProviderDressUp.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderDraft : public ViewProviderDressUp +class PartDesignGuiExport ViewProviderDraft: public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderDraft) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDraft); @@ -38,19 +39,21 @@ class PartDesignGuiExport ViewProviderDraft : public ViewProviderDressUp public: /// constructor ViewProviderDraft() - { sPixmap = "PartDesign_Draft.svg"; - menuName = tr("Draft Parameters"); } + { + sPixmap = "PartDesign_Draft.svg"; + menuName = tr("Draft Parameters"); + } /// return "Draft" - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDraft_H +#endif // PARTGUI_ViewProviderDraft_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp b/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp index fd34e0ed5e..c3c36a081b 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp @@ -22,12 +22,11 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -64,7 +63,8 @@ void ViewProviderDressUp::setupContextMenu(QMenu* menu, QObject* receiver, const PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -const std::string & ViewProviderDressUp::featureName() const { +const std::string& ViewProviderDressUp::featureName() const +{ static const std::string name = "Undefined"; return name; } @@ -75,24 +75,30 @@ std::string ViewProviderDressUp::featureIcon() const } -bool ViewProviderDressUp::setEdit(int ModNum) { +bool ViewProviderDressUp::setEdit(int ModNum) +{ if (ModNum == ViewProvider::Default) { // Here we should prevent edit of a Feature with missing base // Otherwise it could call unhandled exception. PartDesign::DressUp* dressUp = getObject(); - assert (dressUp); - if (dressUp->getBaseObject (/*silent =*/ true)) { + assert(dressUp); + if (dressUp->getBaseObject(/*silent =*/true)) { return ViewProvider::setEdit(ModNum); - } else { - QMessageBox::warning ( nullptr, QObject::tr("Feature error"), - QObject::tr("%1 misses a base feature.\n" - "This feature is broken and cannot be edited.") - .arg( QString::fromLatin1(dressUp->getNameInDocument()) ) - ); + } + else { + QMessageBox::warning( + nullptr, + QObject::tr("Feature error"), + QObject::tr( + "%1 misses a base feature.\n" + "This feature is broken and cannot be edited." + ) + .arg(QString::fromLatin1(dressUp->getNameInDocument())) + ); return false; } - - } else { + } + else { return ViewProvider::setEdit(ModNum); } } @@ -100,13 +106,16 @@ bool ViewProviderDressUp::setEdit(int ModNum) { void ViewProviderDressUp::highlightReferences(const bool on) { PartDesign::DressUp* pcDressUp = getObject(); - Part::Feature* base = pcDressUp->getBaseObject (/*silent =*/ true); - if (!base) + Part::Feature* base = pcDressUp->getBaseObject(/*silent =*/true); + if (!base) { return; + } PartGui::ViewProviderPart* vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); - if (!vp) + Gui::Application::Instance->getViewProvider(base) + ); + if (!vp) { return; + } std::vector faces = pcDressUp->Base.getSubValuesStartsWith("Face"); std::vector edges = pcDressUp->Base.getSubValuesStartsWith("Edge"); @@ -115,7 +124,10 @@ void ViewProviderDressUp::highlightReferences(const bool on) if (!faces.empty()) { std::vector materials = vp->ShapeAppearance.getValues(); - PartGui::ReferenceHighlighter highlighter(base->Shape.getValue(), ShapeAppearance.getDiffuseColor()); + PartGui::ReferenceHighlighter highlighter( + base->Shape.getValue(), + ShapeAppearance.getDiffuseColor() + ); highlighter.getFaceMaterials(faces, materials); vp->setHighlightedFaces(materials); @@ -128,7 +140,8 @@ void ViewProviderDressUp::highlightReferences(const bool on) vp->setHighlightedEdges(colors); } - } else { + } + else { vp->unsetHighlightedFaces(); vp->unsetHighlightedEdges(); } @@ -138,11 +151,11 @@ void ViewProviderDressUp::setErrorState(bool error) { auto* styleParameterManager = Base::provideService(); - const float opacity = - static_cast(styleParameterManager - ->resolve(error ? StyleParameters::PreviewErrorOpacity - : StyleParameters::PreviewShapeOpacity) - .value); + const float opacity = static_cast( + styleParameterManager + ->resolve(error ? StyleParameters::PreviewErrorOpacity : StyleParameters::PreviewShapeOpacity) + .value + ); pcPreviewShape->transparency = 1.0F - opacity; pcPreviewShape->color = error diff --git a/src/Mod/PartDesign/Gui/ViewProviderDressUp.h b/src/Mod/PartDesign/Gui/ViewProviderDressUp.h index c38ec1cc9a..9f50f22e63 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDressUp.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDressUp.h @@ -28,17 +28,18 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ class TaskDlgDressUpParameters; -class PartDesignGuiExport ViewProviderDressUp : public ViewProvider +class PartDesignGuiExport ViewProviderDressUp: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDressUp); public: /// constructor - ViewProviderDressUp() = default; + ViewProviderDressUp() = default; /// destructor ~ViewProviderDressUp() override = default; @@ -57,7 +58,7 @@ public: * Returns the feature Name associated with the view provider. * Should be reimplemented in the successor. */ - virtual const std::string & featureName() const; + virtual const std::string& featureName() const; std::string featureIcon() const; QString menuName; @@ -66,8 +67,7 @@ protected: }; - -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderDressUp_H +#endif // PARTGUI_ViewProviderDressUp_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderExtrude.cpp b/src/Mod/PartDesign/Gui/ViewProviderExtrude.cpp index 373c05d2f7..24ff55a3b8 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderExtrude.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderExtrude.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -43,8 +42,9 @@ void PartDesignGui::ViewProviderExtrude::highlightShapeFaces(const std::vector(); auto base = static_cast(extrude->UpToShape.getValue()); - auto baseViewProvider = - dynamic_cast(Gui::Application::Instance->getViewProvider(base)); + auto baseViewProvider = dynamic_cast( + Gui::Application::Instance->getViewProvider(base) + ); if (!baseViewProvider) { return; diff --git a/src/Mod/PartDesign/Gui/ViewProviderExtrude.h b/src/Mod/PartDesign/Gui/ViewProviderExtrude.h index 02f080811d..772cc3712f 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderExtrude.h +++ b/src/Mod/PartDesign/Gui/ViewProviderExtrude.h @@ -27,9 +27,10 @@ #include "ViewProviderSketchBased.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderExtrude : public ViewProviderSketchBased +class PartDesignGuiExport ViewProviderExtrude: public ViewProviderSketchBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderExtrude); @@ -41,8 +42,7 @@ public: }; - -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderExtrude_H +#endif // PARTGUI_ViewProviderExtrude_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderFillet.cpp b/src/Mod/PartDesign/Gui/ViewProviderFillet.cpp index 3a8a1ab715..3883734c55 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderFillet.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderFillet.cpp @@ -21,16 +21,16 @@ ***************************************************************************/ - #include "TaskFilletParameters.h" #include "ViewProviderFillet.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderFillet,PartDesignGui::ViewProviderDressUp) +PROPERTY_SOURCE(PartDesignGui::ViewProviderFillet, PartDesignGui::ViewProviderDressUp) -const std::string & ViewProviderFillet::featureName() const { +const std::string& ViewProviderFillet::featureName() const +{ static const std::string name = "Fillet"; return name; } @@ -41,6 +41,7 @@ void ViewProviderFillet::setupContextMenu(QMenu* menu, QObject* receiver, const PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderFillet::getEditDialog() { - return new TaskDlgFilletParameters (this); +TaskDlgFeatureParameters* ViewProviderFillet::getEditDialog() +{ + return new TaskDlgFilletParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderFillet.h b/src/Mod/PartDesign/Gui/ViewProviderFillet.h index 2ff681e3ad..be59537de2 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderFillet.h +++ b/src/Mod/PartDesign/Gui/ViewProviderFillet.h @@ -27,9 +27,10 @@ #include "ViewProviderDressUp.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderFillet : public ViewProviderDressUp +class PartDesignGuiExport ViewProviderFillet: public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderFillet) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderFillet); @@ -37,19 +38,21 @@ class PartDesignGuiExport ViewProviderFillet : public ViewProviderDressUp public: /// constructor ViewProviderFillet() - { sPixmap = "PartDesign_Fillet.svg"; - menuName = tr("Fillet Parameters"); } + { + sPixmap = "PartDesign_Fillet.svg"; + menuName = tr("Fillet Parameters"); + } /// return "Fillet" - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderFillet_H +#endif // PARTGUI_ViewProviderFillet_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderGroove.cpp b/src/Mod/PartDesign/Gui/ViewProviderGroove.cpp index 61fa6667d6..4913598032 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderGroove.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderGroove.cpp @@ -21,8 +21,7 @@ ******************************************************************************/ - -# include +#include #include "TaskRevolutionParameters.h" @@ -30,7 +29,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderGroove,PartDesignGui::ViewProviderSketchBased) +PROPERTY_SOURCE(PartDesignGui::ViewProviderGroove, PartDesignGui::ViewProviderSketchBased) ViewProviderGroove::ViewProviderGroove() { @@ -45,7 +44,7 @@ void ViewProviderGroove::setupContextMenu(QMenu* menu, QObject* receiver, const PartDesignGui::ViewProviderSketchBased::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderGroove::getEditDialog() +TaskDlgFeatureParameters* ViewProviderGroove::getEditDialog() { - return new TaskDlgGrooveParameters( this ); + return new TaskDlgGrooveParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderGroove.h b/src/Mod/PartDesign/Gui/ViewProviderGroove.h index 3412b232f8..fced332b19 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderGroove.h +++ b/src/Mod/PartDesign/Gui/ViewProviderGroove.h @@ -27,9 +27,10 @@ #include "ViewProviderSketchBased.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderGroove : public ViewProviderSketchBased +class PartDesignGuiExport ViewProviderGroove: public ViewProviderSketchBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderGroove); @@ -46,12 +47,11 @@ protected: * Returns a newly created TaskDlgRevolutionParameters * NOTE: as for now groove and revolution share the dialog implementation */ - TaskDlgFeatureParameters *getEditDialog() override; - + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderGroove_H +#endif // PARTGUI_ViewProviderGroove_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp b/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp index ede4ca0183..3f5a0e1f57 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -37,7 +36,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderHelix,PartDesignGui::ViewProvider) +PROPERTY_SOURCE(PartDesignGui::ViewProviderHelix, PartDesignGui::ViewProvider) ViewProviderHelix::ViewProviderHelix() = default; @@ -50,29 +49,35 @@ void ViewProviderHelix::setupContextMenu(QMenu* menu, QObject* receiver, const c ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderHelix::getEditDialog() +TaskDlgFeatureParameters* ViewProviderHelix::getEditDialog() { return new TaskDlgHelixParameters(this); } -QIcon ViewProviderHelix::getIcon() const { +QIcon ViewProviderHelix::getIcon() const +{ QString str = QStringLiteral("PartDesign_"); auto* prim = getObject(); - if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) + if (prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) { str += QStringLiteral("Additive"); - else + } + else { str += QStringLiteral("Subtractive"); + } str += QStringLiteral("Helix.svg"); - return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(str.toStdString().c_str())); + return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons( + Gui::BitmapFactory().pixmap(str.toStdString().c_str()) + ); } -std::vector ViewProviderHelix::claimChildren() const { +std::vector ViewProviderHelix::claimChildren() const +{ std::vector temp; App::DocumentObject* sketch = getObject()->Profile.getValue(); - if (sketch && sketch->isDerivedFrom()) + if (sketch && sketch->isDerivedFrom()) { temp.push_back(sketch); + } return temp; } - diff --git a/src/Mod/PartDesign/Gui/ViewProviderHelix.h b/src/Mod/PartDesign/Gui/ViewProviderHelix.h index 921c6aac6a..f49a8f71dc 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHelix.h +++ b/src/Mod/PartDesign/Gui/ViewProviderHelix.h @@ -27,9 +27,10 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderHelix : public ViewProvider +class PartDesignGuiExport ViewProviderHelix: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderHelix); @@ -48,11 +49,11 @@ protected: QIcon getIcon() const override; /// Returns a newly created TaskDlgHelixParameters - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderHelix_H +#endif // PARTGUI_ViewProviderHelix_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderHole.cpp b/src/Mod/PartDesign/Gui/ViewProviderHole.cpp index 79346cb241..5c1463382f 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHole.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderHole.cpp @@ -21,9 +21,8 @@ ***************************************************************************/ - -# include -# include +#include +#include #include @@ -38,7 +37,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderHole,PartDesignGui::ViewProvider) +PROPERTY_SOURCE(PartDesignGui::ViewProviderHole, PartDesignGui::ViewProvider) ViewProviderHole::ViewProviderHole() { diff --git a/src/Mod/PartDesign/Gui/ViewProviderHole.h b/src/Mod/PartDesign/Gui/ViewProviderHole.h index 917711feef..723858b6fb 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHole.h +++ b/src/Mod/PartDesign/Gui/ViewProviderHole.h @@ -27,9 +27,10 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderHole : public ViewProvider +class PartDesignGuiExport ViewProviderHole: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderHole); @@ -40,16 +41,15 @@ public: ~ViewProviderHole() override; /// grouping handling - std::vector claimChildren()const override; - void setupContextMenu(QMenu *menu, QObject *receiver, const char *member) override; + std::vector claimChildren() const override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; protected: TaskDlgFeatureParameters* getEditDialog() override; }; - -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderHole_H +#endif // PARTGUI_ViewProviderHole_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.cpp b/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.cpp index fe92ec7827..148e5e756d 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.cpp @@ -21,16 +21,16 @@ ******************************************************************************/ - #include "ViewProviderLinearPattern.h" #include "TaskPatternParameters.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderLinearPattern,PartDesignGui::ViewProviderTransformed) +PROPERTY_SOURCE(PartDesignGui::ViewProviderLinearPattern, PartDesignGui::ViewProviderTransformed) -TaskDlgFeatureParameters *ViewProviderLinearPattern::getEditDialog() { - return new TaskDlgLinearPatternParameters (this); +TaskDlgFeatureParameters* ViewProviderLinearPattern::getEditDialog() +{ + return new TaskDlgLinearPatternParameters(this); } void ViewProviderLinearPattern::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) @@ -39,7 +39,7 @@ void ViewProviderLinearPattern::setupContextMenu(QMenu* menu, QObject* receiver, PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -const std::string & ViewProviderLinearPattern::featureName() const +const std::string& ViewProviderLinearPattern::featureName() const { static const std::string name = "LinearPattern"; return name; diff --git a/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h b/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h index eedbfb5e37..c5533b7a7a 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h +++ b/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h @@ -26,28 +26,31 @@ #include "ViewProviderTransformed.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderLinearPattern : public ViewProviderTransformed +class PartDesignGuiExport ViewProviderLinearPattern: public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderLinearPattern) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderLinearPattern); + public: ViewProviderLinearPattern() - { menuName = tr("Linear Pattern Parameters"); - sPixmap = "PartDesign_LinearPattern.svg"; } + { + menuName = tr("Linear Pattern Parameters"); + sPixmap = "PartDesign_LinearPattern.svg"; + } - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; - + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderLinearPattern_H +#endif // PARTGUI_ViewProviderLinearPattern_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp b/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp index 5c622a84af..2c14580cef 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -41,19 +40,21 @@ ViewProviderLoft::ViewProviderLoft() = default; ViewProviderLoft::~ViewProviderLoft() = default; -std::vector ViewProviderLoft::claimChildren()const +std::vector ViewProviderLoft::claimChildren() const { std::vector temp; PartDesign::Loft* pcLoft = getObject(); App::DocumentObject* sketch = pcLoft->getVerifiedSketch(true); - if (sketch) + if (sketch) { temp.push_back(sketch); + } - for(App::DocumentObject* obj : pcLoft->Sections.getValues()) { - if (obj && obj->isDerivedFrom()) + for (App::DocumentObject* obj : pcLoft->Sections.getValues()) { + if (obj && obj->isDerivedFrom()) { temp.push_back(obj); + } } return temp; @@ -65,15 +66,19 @@ void ViewProviderLoft::setupContextMenu(QMenu* menu, QObject* receiver, const ch ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters* ViewProviderLoft::getEditDialog() { +TaskDlgFeatureParameters* ViewProviderLoft::getEditDialog() +{ return new TaskDlgLoftParameters(this); } void ViewProviderLoft::highlightProfile(bool on) { PartDesign::Loft* pcLoft = getObject(); - highlightReferences(dynamic_cast(pcLoft->Profile.getValue()), - pcLoft->Profile.getSubValues(), on); + highlightReferences( + dynamic_cast(pcLoft->Profile.getValue()), + pcLoft->Profile.getSubValues(), + on + ); } void ViewProviderLoft::highlightSection(bool on) @@ -94,30 +99,37 @@ void ViewProviderLoft::highlightSection(bool on) void ViewProviderLoft::highlightReferences(ViewProviderLoft::Reference mode, bool on) { switch (mode) { - case Profile: - highlightProfile(on); - break; - case Section: - highlightSection(on); - break; - case Both: - highlightProfile(on); - highlightSection(on); - break; - default: - break; + case Profile: + highlightProfile(on); + break; + case Section: + highlightSection(on); + break; + case Both: + highlightProfile(on); + highlightSection(on); + break; + default: + break; } } -void ViewProviderLoft::highlightReferences(Part::Feature* base, const std::vector& elements, bool on) +void ViewProviderLoft::highlightReferences( + Part::Feature* base, + const std::vector& elements, + bool on +) { - if (!base) + if (!base) { return; + } PartGui::ViewProviderPart* svp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); - if (!svp) + Gui::Application::Instance->getViewProvider(base) + ); + if (!svp) { return; + } std::vector& edgeColors = originalLineColors[base->getID()]; @@ -135,15 +147,19 @@ void ViewProviderLoft::highlightReferences(Part::Feature* base, const std::vecto } } -QIcon ViewProviderLoft::getIcon() const { +QIcon ViewProviderLoft::getIcon() const +{ QString str = QStringLiteral("PartDesign_"); auto* prim = getObject(); - if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) + if (prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) { str += QStringLiteral("Additive"); - else + } + else { str += QStringLiteral("Subtractive"); + } str += QStringLiteral("Loft.svg"); - return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(str.toStdString().c_str())); + return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons( + Gui::BitmapFactory().pixmap(str.toStdString().c_str()) + ); } - diff --git a/src/Mod/PartDesign/Gui/ViewProviderLoft.h b/src/Mod/PartDesign/Gui/ViewProviderLoft.h index ea0224daeb..a9986cc2f8 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLoft.h +++ b/src/Mod/PartDesign/Gui/ViewProviderLoft.h @@ -26,14 +26,16 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderLoft : public ViewProvider +class PartDesignGuiExport ViewProviderLoft: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderLoft); public: - enum Reference { + enum Reference + { Profile, Section, Both @@ -64,7 +66,7 @@ private: }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderLoft_H +#endif // PARTGUI_ViewProviderLoft_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderMainPart.cpp b/src/Mod/PartDesign/Gui/ViewProviderMainPart.cpp index 448c1e6319..78e2b38ada 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMainPart.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderMainPart.cpp @@ -21,28 +21,23 @@ ***************************************************************************/ - #include "ViewProviderMainPart.h" #include using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderMainPart,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartDesignGui::ViewProviderMainPart, PartGui::ViewProviderPart) ViewProviderMainPart::ViewProviderMainPart() -{ -} +{} ViewProviderMainPart::~ViewProviderMainPart() -{ -} +{} -std::vector ViewProviderMainPart::claimChildren(void)const +std::vector ViewProviderMainPart::claimChildren(void) const { std::vector temp; temp.push_back(getObject()->Sketch.getValue()); return temp; } - - diff --git a/src/Mod/PartDesign/Gui/ViewProviderMainPart.h b/src/Mod/PartDesign/Gui/ViewProviderMainPart.h index 1d701a68c6..190992106e 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMainPart.h +++ b/src/Mod/PartDesign/Gui/ViewProviderMainPart.h @@ -27,9 +27,10 @@ #include -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderMainPart : public PartGui::ViewProviderPart +class PartDesignGuiExport ViewProviderMainPart: public PartGui::ViewProviderPart { PROPERTY_HEADER(PartDesignGui::ViewProviderMainPart); @@ -40,11 +41,11 @@ public: virtual ~ViewProviderMainPart(); /// grouping handling - std::vector claimChildren(void)const; + std::vector claimChildren(void) const; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderMainPart_H +#endif // PARTGUI_ViewProviderMainPart_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderMirrored.cpp b/src/Mod/PartDesign/Gui/ViewProviderMirrored.cpp index a5c410fd40..97ef4ec207 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMirrored.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderMirrored.cpp @@ -21,16 +21,16 @@ ******************************************************************************/ - #include "ViewProviderMirrored.h" #include "TaskMirroredParameters.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderMirrored,PartDesignGui::ViewProviderTransformed) +PROPERTY_SOURCE(PartDesignGui::ViewProviderMirrored, PartDesignGui::ViewProviderTransformed) -TaskDlgFeatureParameters *ViewProviderMirrored::getEditDialog() { - return new TaskDlgMirroredParameters (this); +TaskDlgFeatureParameters* ViewProviderMirrored::getEditDialog() +{ + return new TaskDlgMirroredParameters(this); } void ViewProviderMirrored::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) @@ -39,7 +39,7 @@ void ViewProviderMirrored::setupContextMenu(QMenu* menu, QObject* receiver, cons PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -const std::string & ViewProviderMirrored::featureName() const +const std::string& ViewProviderMirrored::featureName() const { static const std::string name = "Mirrored"; return name; diff --git a/src/Mod/PartDesign/Gui/ViewProviderMirrored.h b/src/Mod/PartDesign/Gui/ViewProviderMirrored.h index a384d21c00..6a440581b9 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMirrored.h +++ b/src/Mod/PartDesign/Gui/ViewProviderMirrored.h @@ -26,14 +26,17 @@ #include "ViewProviderTransformed.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderMirrored : public ViewProviderTransformed +class PartDesignGuiExport ViewProviderMirrored: public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGuii::ViewProviderMirrored) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderMirrored); + public: - ViewProviderMirrored() { + ViewProviderMirrored() + { menuName = tr("Mirror Parameters"); sPixmap = "PartDesign_Mirrored.svg"; } @@ -43,11 +46,11 @@ public: protected: /// Returns a newly created dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderMirrored_H +#endif // PARTGUI_ViewProviderMirrored_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp index f5aed61699..6b3bdcdead 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp @@ -21,7 +21,6 @@ ******************************************************************************/ - #include "ViewProviderMultiTransform.h" #include "TaskMultiTransformParameters.h" #include @@ -30,13 +29,14 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderMultiTransform,PartDesignGui::ViewProviderTransformed) +PROPERTY_SOURCE(PartDesignGui::ViewProviderMultiTransform, PartDesignGui::ViewProviderTransformed) -TaskDlgFeatureParameters *ViewProviderMultiTransform::getEditDialog() { - return new TaskDlgMultiTransformParameters (this); +TaskDlgFeatureParameters* ViewProviderMultiTransform::getEditDialog() +{ + return new TaskDlgMultiTransformParameters(this); } -const std::string & ViewProviderMultiTransform::featureName() const +const std::string& ViewProviderMultiTransform::featureName() const { static const std::string name = "MultiTransform"; return name; @@ -45,20 +45,22 @@ const std::string & ViewProviderMultiTransform::featureName() const void ViewProviderMultiTransform::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { addDefaultAction(menu, QObject::tr("Edit Multi-Transform")); - PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method + PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method } std::vector ViewProviderMultiTransform::claimChildren() const { PartDesign::MultiTransform* pcMultiTransform = getObject(); - if (!pcMultiTransform) - return {}; // TODO: Show error? + if (!pcMultiTransform) { + return {}; // TODO: Show error? + } std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); return transformFeatures; } -bool ViewProviderMultiTransform::onDelete(const std::vector &svec) { +bool ViewProviderMultiTransform::onDelete(const std::vector& svec) +{ // Delete the transformation features PartDesign::MultiTransform* pcMultiTransform = getObject(); std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); @@ -67,8 +69,11 @@ bool ViewProviderMultiTransform::onDelete(const std::vector &svec) for (auto it : transformFeatures) { if (it) { Gui::Command::doCommand( - Gui::Command::Doc,"App.getDocument('%s').removeObject(\"%s\")", \ - it->getDocument()->getName(), it->getNameInDocument()); + Gui::Command::Doc, + "App.getDocument('%s').removeObject(\"%s\")", + it->getDocument()->getName(), + it->getNameInDocument() + ); } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h index 1c1ce5c6a0..afec251d88 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h +++ b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h @@ -26,31 +26,34 @@ #include "ViewProviderTransformed.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderMultiTransform : public ViewProviderTransformed +class PartDesignGuiExport ViewProviderMultiTransform: public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderMultiTransform) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderMultiTransform); + public: - ViewProviderMultiTransform() { + ViewProviderMultiTransform() + { menuName = tr("Multi-Transform Parameters"); sPixmap = "PartDesign_MultiTransform.svg"; } - const std::string & featureName() const override; + const std::string& featureName() const override; std::vector claimChildren() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; - bool onDelete(const std::vector &) override; + bool onDelete(const std::vector&) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderMultiTransform_H +#endif // PARTGUI_ViewProviderMultiTransform_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderPad.cpp b/src/Mod/PartDesign/Gui/ViewProviderPad.cpp index 0c950a9ab8..141e4212c6 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPad.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPad.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include "TaskPadParameters.h" @@ -45,9 +44,9 @@ void ViewProviderPad::setupContextMenu(QMenu* menu, QObject* receiver, const cha PartDesignGui::ViewProviderSketchBased::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderPad::getEditDialog() +TaskDlgFeatureParameters* ViewProviderPad::getEditDialog() { // TODO fix setting values from the history: now it doesn't work neither in // the master and in the migrated branch (2015-07-26, Fat-Zer) - return new TaskDlgPadParameters( this ); + return new TaskDlgPadParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderPad.h b/src/Mod/PartDesign/Gui/ViewProviderPad.h index 4d14e3156c..54504c5186 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPad.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPad.h @@ -26,9 +26,10 @@ #include "ViewProviderExtrude.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderPad : public ViewProviderExtrude +class PartDesignGuiExport ViewProviderPad: public ViewProviderExtrude { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPad); @@ -42,12 +43,11 @@ public: protected: /// Returns a newly created TaskDlgPadParameters - TaskDlgFeatureParameters *getEditDialog() override; - + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderPad_H +#endif // PARTGUI_ViewProviderPad_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp b/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp index 3357d18da7..5e16ddcfd7 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include @@ -35,34 +34,38 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderPipe,PartDesignGui::ViewProvider) +PROPERTY_SOURCE(PartDesignGui::ViewProviderPipe, PartDesignGui::ViewProvider) ViewProviderPipe::ViewProviderPipe() = default; ViewProviderPipe::~ViewProviderPipe() = default; -std::vector ViewProviderPipe::claimChildren()const +std::vector ViewProviderPipe::claimChildren() const { std::vector temp; PartDesign::Pipe* pcPipe = getObject(); App::DocumentObject* sketch = pcPipe->getVerifiedSketch(true); - if (sketch) + if (sketch) { temp.push_back(sketch); + } - for(App::DocumentObject* obj : pcPipe->Sections.getValues()) { - if (obj && obj->isDerivedFrom()) + for (App::DocumentObject* obj : pcPipe->Sections.getValues()) { + if (obj && obj->isDerivedFrom()) { temp.push_back(obj); + } } App::DocumentObject* spine = pcPipe->Spine.getValue(); - if (spine && spine->isDerivedFrom()) + if (spine && spine->isDerivedFrom()) { temp.push_back(spine); + } App::DocumentObject* auxspine = pcPipe->AuxiliarySpine.getValue(); - if (auxspine && auxspine->isDerivedFrom()) + if (auxspine && auxspine->isDerivedFrom()) { temp.push_back(auxspine); + } return temp; } @@ -73,7 +76,8 @@ void ViewProviderPipe::setupContextMenu(QMenu* menu, QObject* receiver, const ch PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters* ViewProviderPipe::getEditDialog() { +TaskDlgFeatureParameters* ViewProviderPipe::getEditDialog() +{ return new TaskDlgPipeParameters(this, false); } @@ -82,41 +86,54 @@ void ViewProviderPipe::highlightReferences(ViewProviderPipe::Reference mode, boo PartDesign::Pipe* pcPipe = getObject(); switch (mode) { - case Spine: - highlightReferences(dynamic_cast(pcPipe->Spine.getValue()), - pcPipe->Spine.getSubValuesStartsWith("Edge"), on); - break; - case AuxiliarySpine: - highlightReferences(dynamic_cast(pcPipe->AuxiliarySpine.getValue()), - pcPipe->AuxiliarySpine.getSubValuesStartsWith("Edge"), on); - break; - case Profile: - highlightReferences(dynamic_cast(pcPipe->Profile.getValue()), - pcPipe->Profile.getSubValuesStartsWith("Edge"), on); - break; - case Section: - { + case Spine: + highlightReferences( + dynamic_cast(pcPipe->Spine.getValue()), + pcPipe->Spine.getSubValuesStartsWith("Edge"), + on + ); + break; + case AuxiliarySpine: + highlightReferences( + dynamic_cast(pcPipe->AuxiliarySpine.getValue()), + pcPipe->AuxiliarySpine.getSubValuesStartsWith("Edge"), + on + ); + break; + case Profile: + highlightReferences( + dynamic_cast(pcPipe->Profile.getValue()), + pcPipe->Profile.getSubValuesStartsWith("Edge"), + on + ); + break; + case Section: { std::vector sections = pcPipe->Sections.getValues(); for (auto it : sections) { - highlightReferences(dynamic_cast(it), - std::vector(), on); + highlightReferences(dynamic_cast(it), std::vector(), on); } - } - break; - default: - break; + } break; + default: + break; } } -void ViewProviderPipe::highlightReferences(Part::Feature* base, const std::vector& edges, bool on) +void ViewProviderPipe::highlightReferences( + Part::Feature* base, + const std::vector& edges, + bool on +) { - if (!base) + if (!base) { return; + } PartGui::ViewProviderPart* svp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); - if (!svp) + Gui::Application::Instance->getViewProvider(base) + ); + if (!svp) { return; + } std::vector& edgeColors = originalLineColors[base->getID()]; @@ -129,7 +146,8 @@ void ViewProviderPipe::highlightReferences(Part::Feature* base, const std::vecto highlighter.getEdgeColors(edges, colors); svp->LineColorArray.setValues(colors); } - } else { + } + else { if (!edgeColors.empty()) { svp->LineColorArray.setValues(edgeColors); edgeColors.clear(); @@ -137,15 +155,19 @@ void ViewProviderPipe::highlightReferences(Part::Feature* base, const std::vecto } } -QIcon ViewProviderPipe::getIcon() const { +QIcon ViewProviderPipe::getIcon() const +{ QString str = QStringLiteral("PartDesign_"); auto* prim = getObject(); - if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) + if (prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) { str += QStringLiteral("Additive"); - else + } + else { str += QStringLiteral("Subtractive"); + } str += QStringLiteral("Pipe.svg"); - return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(str.toStdString().c_str())); + return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons( + Gui::BitmapFactory().pixmap(str.toStdString().c_str()) + ); } - diff --git a/src/Mod/PartDesign/Gui/ViewProviderPipe.h b/src/Mod/PartDesign/Gui/ViewProviderPipe.h index 6a262d1c48..938b069212 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPipe.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPipe.h @@ -26,14 +26,16 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderPipe : public ViewProvider +class PartDesignGuiExport ViewProviderPipe: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPipe); public: - enum Reference { + enum Reference + { Spine, AuxiliarySpine, Profile, @@ -46,7 +48,7 @@ public: ~ViewProviderPipe() override; /// grouping handling - std::vector claimChildren()const override; + std::vector claimChildren() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; void highlightReferences(Reference mode, bool on); @@ -55,7 +57,7 @@ protected: QIcon getIcon() const override; /// Returns a newly created TaskDlgPipeParameters - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; private: void highlightReferences(Part::Feature*, const std::vector&, bool); @@ -65,7 +67,7 @@ private: }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderPipe_H +#endif // PARTGUI_ViewProviderPipe_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderPocket.cpp b/src/Mod/PartDesign/Gui/ViewProviderPocket.cpp index e683999559..464067ccd0 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPocket.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPocket.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include "TaskPocketParameters.h" @@ -48,7 +47,7 @@ void ViewProviderPocket::setupContextMenu(QMenu* menu, QObject* receiver, const } -TaskDlgFeatureParameters *ViewProviderPocket::getEditDialog() +TaskDlgFeatureParameters* ViewProviderPocket::getEditDialog() { - return new TaskDlgPocketParameters( this ); + return new TaskDlgPocketParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderPocket.h b/src/Mod/PartDesign/Gui/ViewProviderPocket.h index 5f4b528f08..a73a6e3996 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPocket.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPocket.h @@ -27,9 +27,10 @@ #include "ViewProviderExtrude.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderPocket : public ViewProviderExtrude +class PartDesignGuiExport ViewProviderPocket: public ViewProviderExtrude { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPocket); @@ -43,13 +44,11 @@ public: protected: /// Returns a newly created TaskDlgPocketParameters - TaskDlgFeatureParameters *getEditDialog() override; - + TaskDlgFeatureParameters* getEditDialog() override; }; - -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderPocket_H +#endif // PARTGUI_ViewProviderPocket_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.cpp b/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.cpp index 25989e59bc..801a9d8786 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.cpp @@ -26,9 +26,10 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderPolarPattern,PartDesignGui::ViewProviderTransformed) +PROPERTY_SOURCE(PartDesignGui::ViewProviderPolarPattern, PartDesignGui::ViewProviderTransformed) -TaskDlgFeatureParameters *ViewProviderPolarPattern::getEditDialog() { +TaskDlgFeatureParameters* ViewProviderPolarPattern::getEditDialog() +{ return new TaskDlgLinearPatternParameters(this); } @@ -38,7 +39,7 @@ void ViewProviderPolarPattern::setupContextMenu(QMenu* menu, QObject* receiver, PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -const std::string & ViewProviderPolarPattern::featureName() const +const std::string& ViewProviderPolarPattern::featureName() const { static const std::string name = "PolarPattern"; return name; diff --git a/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h b/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h index 947eab2e13..98fccdf6ee 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h @@ -26,29 +26,31 @@ #include "ViewProviderTransformed.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderPolarPattern : public ViewProviderTransformed +class PartDesignGuiExport ViewProviderPolarPattern: public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderPolarPattern) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPolarPattern); + public: - ViewProviderPolarPattern() { + ViewProviderPolarPattern() + { menuName = tr("Polar Pattern Parameters"); sPixmap = "PartDesign_PolarPattern.svg"; } - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; - + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderPolarPattern_H +#endif // PARTGUI_ViewProviderPolarPattern_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp index 3b3994d056..3d983ec3d9 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp @@ -21,8 +21,8 @@ ***************************************************************************/ -# include -# include +#include +#include #include @@ -38,7 +38,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderPrimitive,PartDesignGui::ViewProvider) +PROPERTY_SOURCE(PartDesignGui::ViewProviderPrimitive, PartDesignGui::ViewProvider) ViewProviderPrimitive::ViewProviderPrimitive() = default; @@ -55,42 +55,47 @@ TaskDlgFeatureParameters* ViewProviderPrimitive::getEditDialog() return new TaskDlgPrimitiveParameters(this); } -QIcon ViewProviderPrimitive::getIcon() const { +QIcon ViewProviderPrimitive::getIcon() const +{ QString str = QStringLiteral("PartDesign_"); auto* prim = getObject(); - if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) + if (prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) { str += QStringLiteral("Additive"); - else + } + else { str += QStringLiteral("Subtractive"); + } - switch(prim->getPrimitiveType()) { - case PartDesign::FeaturePrimitive::Box: - str += QStringLiteral("Box"); - break; - case PartDesign::FeaturePrimitive::Cylinder: - str += QStringLiteral("Cylinder"); - break; - case PartDesign::FeaturePrimitive::Sphere: - str += QStringLiteral("Sphere"); - break; - case PartDesign::FeaturePrimitive::Cone: - str += QStringLiteral("Cone"); - break; - case PartDesign::FeaturePrimitive::Ellipsoid: - str += QStringLiteral("Ellipsoid"); - break; - case PartDesign::FeaturePrimitive::Torus: - str += QStringLiteral("Torus"); - break; - case PartDesign::FeaturePrimitive::Prism: - str += QStringLiteral("Prism"); - break; - case PartDesign::FeaturePrimitive::Wedge: - str += QStringLiteral("Wedge"); - break; + switch (prim->getPrimitiveType()) { + case PartDesign::FeaturePrimitive::Box: + str += QStringLiteral("Box"); + break; + case PartDesign::FeaturePrimitive::Cylinder: + str += QStringLiteral("Cylinder"); + break; + case PartDesign::FeaturePrimitive::Sphere: + str += QStringLiteral("Sphere"); + break; + case PartDesign::FeaturePrimitive::Cone: + str += QStringLiteral("Cone"); + break; + case PartDesign::FeaturePrimitive::Ellipsoid: + str += QStringLiteral("Ellipsoid"); + break; + case PartDesign::FeaturePrimitive::Torus: + str += QStringLiteral("Torus"); + break; + case PartDesign::FeaturePrimitive::Prism: + str += QStringLiteral("Prism"); + break; + case PartDesign::FeaturePrimitive::Wedge: + str += QStringLiteral("Wedge"); + break; } str += QStringLiteral(".svg"); - return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons(Gui::BitmapFactory().pixmap(str.toStdString().c_str())); + return PartDesignGui::ViewProvider::mergeGreyableOverlayIcons( + Gui::BitmapFactory().pixmap(str.toStdString().c_str()) + ); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h index 906bf74cbc..58a0d365ab 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h @@ -26,9 +26,10 @@ #include "ViewProvider.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderPrimitive : public ViewProvider +class PartDesignGuiExport ViewProviderPrimitive: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPrimitive); @@ -42,12 +43,12 @@ protected: QIcon getIcon() const override; void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; - std::string displayMode; + std::string displayMode; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderBoolean_H +#endif // PARTGUI_ViewProviderBoolean_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp b/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp index 073a3980c2..e6d327bef3 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include "ViewProvider.h" // inclusion of the generated files (generated out of ViewProviderPy.xml) @@ -36,12 +35,12 @@ std::string ViewProviderPy::representation() const return {""}; } -PyObject *ViewProviderPy::getCustomAttributes(const char* ) const +PyObject* ViewProviderPy::getCustomAttributes(const char*) const { return nullptr; } -int ViewProviderPy::setCustomAttributes(const char* , PyObject *) +int ViewProviderPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/PartDesign/Gui/ViewProviderRevolution.cpp b/src/Mod/PartDesign/Gui/ViewProviderRevolution.cpp index a2f5df93bd..d20e397d4d 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderRevolution.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderRevolution.cpp @@ -21,8 +21,7 @@ ***************************************************************************/ - -# include +#include #include "TaskRevolutionParameters.h" @@ -30,7 +29,7 @@ using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderRevolution,PartDesignGui::ViewProviderSketchBased) +PROPERTY_SOURCE(PartDesignGui::ViewProviderRevolution, PartDesignGui::ViewProviderSketchBased) ViewProviderRevolution::ViewProviderRevolution() { @@ -45,7 +44,7 @@ void ViewProviderRevolution::setupContextMenu(QMenu* menu, QObject* receiver, co PartDesignGui::ViewProviderSketchBased::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderRevolution::getEditDialog() +TaskDlgFeatureParameters* ViewProviderRevolution::getEditDialog() { - return new TaskDlgRevolutionParameters( this ); + return new TaskDlgRevolutionParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderRevolution.h b/src/Mod/PartDesign/Gui/ViewProviderRevolution.h index 23e2c2f548..4aa44d1de4 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderRevolution.h +++ b/src/Mod/PartDesign/Gui/ViewProviderRevolution.h @@ -27,9 +27,10 @@ #include "ViewProviderSketchBased.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderRevolution : public ViewProviderSketchBased +class PartDesignGuiExport ViewProviderRevolution: public ViewProviderSketchBased { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderRevolution); @@ -43,13 +44,11 @@ public: protected: /// Returns a newly created TaskDlgRevolutionParameters - TaskDlgFeatureParameters *getEditDialog() override; - - + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderRevolution_H +#endif // PARTGUI_ViewProviderRevolution_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderScaled.cpp b/src/Mod/PartDesign/Gui/ViewProviderScaled.cpp index 51528c55e9..d88f74e817 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderScaled.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderScaled.cpp @@ -21,16 +21,16 @@ ******************************************************************************/ - #include "ViewProviderScaled.h" #include "TaskScaledParameters.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderScaled,PartDesignGui::ViewProviderTransformed) +PROPERTY_SOURCE(PartDesignGui::ViewProviderScaled, PartDesignGui::ViewProviderTransformed) -TaskDlgFeatureParameters *ViewProviderScaled::getEditDialog() { - return new TaskDlgScaledParameters (this); +TaskDlgFeatureParameters* ViewProviderScaled::getEditDialog() +{ + return new TaskDlgScaledParameters(this); } void ViewProviderScaled::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) @@ -39,7 +39,7 @@ void ViewProviderScaled::setupContextMenu(QMenu* menu, QObject* receiver, const PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -const std::string & ViewProviderScaled::featureName() const +const std::string& ViewProviderScaled::featureName() const { static const std::string name = "Scaled"; return name; diff --git a/src/Mod/PartDesign/Gui/ViewProviderScaled.h b/src/Mod/PartDesign/Gui/ViewProviderScaled.h index 080a2cc4d3..34395ac966 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderScaled.h +++ b/src/Mod/PartDesign/Gui/ViewProviderScaled.h @@ -26,29 +26,31 @@ #include "ViewProviderTransformed.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderScaled : public ViewProviderTransformed +class PartDesignGuiExport ViewProviderScaled: public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderScaled) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderScaled); + public: - ViewProviderScaled() { + ViewProviderScaled() + { menuName = tr("Scale Parameters"); sPixmap = "PartDesign_Scaled.svg"; } - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; - + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderScaled_H +#endif // PARTGUI_ViewProviderScaled_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp index 48f9bec307..66147a652d 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp @@ -21,12 +21,11 @@ ***************************************************************************/ - -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #include @@ -43,17 +42,17 @@ #include "ViewProviderShapeBinder.h" #include "TaskShapeBinder.h" -FC_LOG_LEVEL_INIT("ShapeBinder",true,true) +FC_LOG_LEVEL_INIT("ShapeBinder", true, true) using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderShapeBinder,PartGui::ViewProviderPart) +PROPERTY_SOURCE(PartDesignGui::ViewProviderShapeBinder, PartGui::ViewProviderPart) ViewProviderShapeBinder::ViewProviderShapeBinder() { sPixmap = "PartDesign_ShapeBinder.svg"; - //make the viewprovider more datum like + // make the viewprovider more datum like AngularDeflection.setStatus(App::Property::Hidden, true); Deviation.setStatus(App::Property::Hidden, true); DrawStyle.setStatus(App::Property::Hidden, true); @@ -64,10 +63,11 @@ ViewProviderShapeBinder::ViewProviderShapeBinder() PointSize.setStatus(App::Property::Hidden, true); DisplayMode.setStatus(App::Property::Hidden, true); - //get the datum coloring scheme - // set default color for datums (golden yellow with 60% transparency) + // get the datum coloring scheme + // set default color for datums (golden yellow with 60% transparency) ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/PartDesign"); + "User parameter:BaseApp/Preferences/Mod/PartDesign" + ); unsigned long shcol = hGrp->GetUnsigned("DefaultDatumColor", 0xFFD70099); Base::Color col((uint32_t)shcol); @@ -80,7 +80,8 @@ ViewProviderShapeBinder::ViewProviderShapeBinder() ViewProviderShapeBinder::~ViewProviderShapeBinder() = default; -bool ViewProviderShapeBinder::setEdit(int ModNum) { +bool ViewProviderShapeBinder::setEdit(int ModNum) +{ // TODO Share code with other view providers (2015-09-11, Fat-Zer) if (ModNum == ViewProvider::Default || ModNum == 1) { @@ -96,10 +97,12 @@ bool ViewProviderShapeBinder::setEdit(int ModNum) { msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); int ret = msgBox.exec(); - if (ret == QMessageBox::Yes) + if (ret == QMessageBox::Yes) { Gui::Control().reject(); - else + } + else { return false; + } } // clear the selection (convenience) @@ -107,10 +110,12 @@ bool ViewProviderShapeBinder::setEdit(int ModNum) { // start the edit dialog // another pad left open its task panel - if (sbDlg) + if (sbDlg) { Gui::Control().showDialog(sbDlg); - else + } + else { Gui::Control().showDialog(new TaskDlgShapeBinder(this, ModNum == 1)); + } return true; } @@ -119,12 +124,13 @@ bool ViewProviderShapeBinder::setEdit(int ModNum) { } } -void ViewProviderShapeBinder::unsetEdit(int ModNum) { +void ViewProviderShapeBinder::unsetEdit(int ModNum) +{ PartGui::ViewProviderPart::unsetEdit(ModNum); } -void ViewProviderShapeBinder::attach(App::DocumentObject *obj) +void ViewProviderShapeBinder::attach(App::DocumentObject* obj) { if (auto geo = dynamic_cast(obj)) { geo->setMaterialAppearance(ShapeAppearance[0]); @@ -137,19 +143,28 @@ void ViewProviderShapeBinder::highlightReferences(bool on) App::GeoFeature* obj = nullptr; std::vector subs; - if (getObject()->isDerivedFrom()) - PartDesign::ShapeBinder::getFilteredReferences(&getObject()->Support, obj, subs); - else + if (getObject()->isDerivedFrom()) { + PartDesign::ShapeBinder::getFilteredReferences( + &getObject()->Support, + obj, + subs + ); + } + else { return; + } // stop if not a Part feature was found - if (!obj || !obj->isDerivedFrom()) + if (!obj || !obj->isDerivedFrom()) { return; + } PartGui::ViewProviderPart* svp = dynamic_cast( - Gui::Application::Instance->getViewProvider(obj)); - if (!svp) + Gui::Application::Instance->getViewProvider(obj) + ); + if (!svp) { return; + } if (on) { if (!subs.empty() && originalLineColors.empty()) { @@ -169,14 +184,16 @@ void ViewProviderShapeBinder::highlightReferences(bool on) if (e.compare(0, 4, "Edge") == 0) { int idx = std::stoi(e.substr(4)) - 1; assert(idx >= 0); - if (idx < static_cast(lcolors.size())) - lcolors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta + if (idx < static_cast(lcolors.size())) { + lcolors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta + } } else if (e.compare(0, 4, "Face") == 0) { int idx = std::stoi(e.substr(4)) - 1; assert(idx >= 0); - if (idx < static_cast(fcolors.size())) - fcolors[idx].diffuseColor = Base::Color(1.0, 0.0, 1.0); // magenta + if (idx < static_cast(fcolors.size())) { + fcolors[idx].diffuseColor = Base::Color(1.0, 0.0, 1.0); // magenta + } } } svp->LineColorArray.setValues(lcolors); @@ -199,7 +216,7 @@ void ViewProviderShapeBinder::setupContextMenu(QMenu* menu, QObject* receiver, c Q_UNUSED(receiver) Q_UNUSED(member) - QAction* act; + QAction* act; act = menu->addAction(QObject::tr("Edit Shape Binder")); act->setData(QVariant((int)ViewProvider::Default)); @@ -219,13 +236,15 @@ void ViewProviderShapeBinder::setupContextMenu(QMenu* menu, QObject* receiver, c PROPERTY_SOURCE(PartDesignGui::ViewProviderSubShapeBinder, PartGui::ViewProviderPart) -ViewProviderSubShapeBinder::ViewProviderSubShapeBinder() { +ViewProviderSubShapeBinder::ViewProviderSubShapeBinder() +{ sPixmap = "PartDesign_SubShapeBinder.svg"; ADD_PROPERTY_TYPE(UseBinderStyle, (false), "", (App::PropertyType)(App::Prop_None), ""); } -void ViewProviderSubShapeBinder::attach(App::DocumentObject* obj) { +void ViewProviderSubShapeBinder::attach(App::DocumentObject* obj) +{ UseBinderStyle.setValue(boost::istarts_with(obj->getNameInDocument(), "binder")); if (auto geo = dynamic_cast(obj)) { @@ -234,17 +253,17 @@ void ViewProviderSubShapeBinder::attach(App::DocumentObject* obj) { ViewProviderPart::attach(obj); } -void ViewProviderSubShapeBinder::onChanged(const App::Property* prop) { - if (prop == &UseBinderStyle - && (!getObject() || !getObject()->isRestoring())) - { +void ViewProviderSubShapeBinder::onChanged(const App::Property* prop) +{ + if (prop == &UseBinderStyle && (!getObject() || !getObject()->isRestoring())) { Base::Color shapeColor, lineColor, pointColor; int transparency, linewidth; if (UseBinderStyle.getValue()) { - //get the datum coloring scheme - // set default color for datums (golden yellow with 60% transparency) + // get the datum coloring scheme + // set default color for datums (golden yellow with 60% transparency) static ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/PartDesign"); + "User parameter:BaseApp/Preferences/Mod/PartDesign" + ); shapeColor.setPackedValue(hGrp->GetUnsigned("DefaultDatumColor", 0xFFD70099)); lineColor = shapeColor; pointColor = shapeColor; @@ -268,43 +287,59 @@ void ViewProviderSubShapeBinder::onChanged(const App::Property* prop) { ViewProviderPart::onChanged(prop); } -bool ViewProviderSubShapeBinder::canDropObjectEx(App::DocumentObject*, - App::DocumentObject*, const char*, const std::vector&) const +bool ViewProviderSubShapeBinder::canDropObjectEx( + App::DocumentObject*, + App::DocumentObject*, + const char*, + const std::vector& +) const { return true; } -std::string ViewProviderSubShapeBinder::dropObjectEx(App::DocumentObject* obj, App::DocumentObject* owner, - const char* subname, const std::vector& elements) +std::string ViewProviderSubShapeBinder::dropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements +) { auto self = getObject(); - if (!self) + if (!self) { return {}; - std::map > values; - if (!subname) subname = ""; + } + std::map> values; + if (!subname) { + subname = ""; + } std::string sub(subname); - if (sub.empty()) + if (sub.empty()) { values[owner ? owner : obj] = elements; + } else { std::vector subs; if (!elements.empty()) { subs.reserve(elements.size()); - for (auto& element : elements) + for (auto& element : elements) { subs.push_back(sub + element); + } } - else + else { subs.push_back(sub); + } values[owner ? owner : obj] = std::move(subs); } self->setLinks(std::move(values), QApplication::keyboardModifiers() == Qt::ControlModifier); - if (self->Relative.getValue()) + if (self->Relative.getValue()) { updatePlacement(false); + } return {}; } -bool ViewProviderSubShapeBinder::doubleClicked() { +bool ViewProviderSubShapeBinder::doubleClicked() +{ updatePlacement(true); return true; } @@ -319,44 +354,56 @@ void ViewProviderSubShapeBinder::setupContextMenu(QMenu* menu, QObject* receiver ViewProviderPart::setupContextMenu(menu, receiver, member); } -bool ViewProviderSubShapeBinder::setEdit(int ModNum) { +bool ViewProviderSubShapeBinder::setEdit(int ModNum) +{ switch (ModNum) { - case Synchronize: - updatePlacement(true); - break; - case SelectObject: { - auto self = getObject(); - if (!self || !self->Support.getValue()) + case Synchronize: + updatePlacement(true); break; + case SelectObject: { + auto self = getObject(); + if (!self || !self->Support.getValue()) { + break; + } - Gui::Selection().selStackPush(); - Gui::Selection().clearSelection(); - for (auto& link : self->Support.getSubListValues()) { - auto obj = link.getValue(); - if (!obj || !obj->isAttachedToDocument()) - continue; - const auto& subs = link.getSubValues(); - if (!subs.empty()) - Gui::Selection().addSelections(obj->getDocument()->getName(), - obj->getNameInDocument(), subs); - else - Gui::Selection().addSelection(obj->getDocument()->getName(), - obj->getNameInDocument()); + Gui::Selection().selStackPush(); + Gui::Selection().clearSelection(); + for (auto& link : self->Support.getSubListValues()) { + auto obj = link.getValue(); + if (!obj || !obj->isAttachedToDocument()) { + continue; + } + const auto& subs = link.getSubValues(); + if (!subs.empty()) { + Gui::Selection().addSelections( + obj->getDocument()->getName(), + obj->getNameInDocument(), + subs + ); + } + else { + Gui::Selection().addSelection( + obj->getDocument()->getName(), + obj->getNameInDocument() + ); + } + } + Gui::Selection().selStackPush(); + break; } - Gui::Selection().selStackPush(); - break; - } - default: - return ViewProviderPart::setEdit(ModNum); + default: + return ViewProviderPart::setEdit(ModNum); } return false; } -void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { +void ViewProviderSubShapeBinder::updatePlacement(bool transaction) +{ auto self = getObject(); - if (!self || !self->Support.getValue()) + if (!self || !self->Support.getValue()) { return; + } std::vector mats; bool relative = self->Relative.getValue(); @@ -364,9 +411,8 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { std::string parentSub; if (relative && !self->getParents().empty()) { const auto& sel = Gui::Selection().getSelection("", Gui::ResolveMode::NoResolve); - if (sel.size() != 1 || !sel[0].pObject || - sel[0].pObject->getSubObject(sel[0].SubName) != self) - { + if (sel.size() != 1 || !sel[0].pObject + || sel[0].pObject->getSubObject(sel[0].SubName) != self) { FC_WARN("invalid selection"); } else { @@ -376,8 +422,9 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { } if (!transaction) { - if (relative) + if (relative) { self->Context.setValue(parent, parentSub.c_str()); + } try { self->update(PartDesign::SubShapeBinder::UpdateForced); } @@ -389,8 +436,9 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { App::GetApplication().setActiveTransaction("Sync binder"); try { - if (relative) + if (relative) { self->Context.setValue(parent, parentSub.c_str()); + } self->update(PartDesign::SubShapeBinder::UpdateForced); App::GetApplication().closeActiveTransaction(); return; @@ -402,32 +450,40 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { std::ostringstream str; Standard_CString msg = e.GetMessageString(); str << typeid(e).name() << " "; - if (msg) { str << msg; } - else { str << "No OCCT Exception Message"; } + if (msg) { + str << msg; + } + else { + str << "No OCCT Exception Message"; + } FC_ERR(str.str()); } App::GetApplication().closeActiveTransaction(true); } -std::vector ViewProviderSubShapeBinder::claimChildren() const { +std::vector ViewProviderSubShapeBinder::claimChildren() const +{ std::vector ret; auto self = freecad_cast(getObject()); if (self && self->ClaimChildren.getValue() && self->Support.getValue()) { std::set objSet; for (auto& l : self->Support.getSubListValues()) { auto obj = l.getValue(); - if (!obj) + if (!obj) { continue; + } const auto& subs = l.getSubValues(); if (subs.empty()) { - if (objSet.insert(obj).second) + if (objSet.insert(obj).second) { ret.push_back(obj); + } continue; } for (auto& sub : subs) { auto sobj = obj->getSubObject(sub.c_str()); - if (sobj && objSet.insert(sobj).second) + if (sobj && objSet.insert(sobj).second) { ret.push_back(sobj); + } } } } @@ -436,8 +492,11 @@ std::vector ViewProviderSubShapeBinder::claimChildren() co //////////////////////////////////////////////////////////////////////////////////////// -namespace Gui { -PROPERTY_SOURCE_TEMPLATE(PartDesignGui::ViewProviderSubShapeBinderPython, - PartDesignGui::ViewProviderSubShapeBinder) +namespace Gui +{ +PROPERTY_SOURCE_TEMPLATE( + PartDesignGui::ViewProviderSubShapeBinderPython, + PartDesignGui::ViewProviderSubShapeBinder +) template class PartDesignGuiExport ViewProviderFeaturePythonT; -} +} // namespace Gui diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h index 6aa012472b..5f56eaf660 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h @@ -27,9 +27,10 @@ #include #include -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderShapeBinder : public PartGui::ViewProviderPart +class PartDesignGuiExport ViewProviderShapeBinder: public PartGui::ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderShapeBinder); @@ -44,15 +45,14 @@ public: protected: bool setEdit(int ModNum) override; void unsetEdit(int ModNum) override; - void attach(App::DocumentObject *obj) override; + void attach(App::DocumentObject* obj) override; private: std::vector originalLineColors; std::vector originalFaceAppearance; - }; -class PartDesignGuiExport ViewProviderSubShapeBinder : public PartGui::ViewProviderPart +class PartDesignGuiExport ViewProviderSubShapeBinder: public PartGui::ViewProviderPart { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderShapeBinder); @@ -62,22 +62,37 @@ public: /// Constructor ViewProviderSubShapeBinder(); - bool canDropObjects() const override {return true;} - bool canDragAndDropObject(App::DocumentObject*) const override {return false;} - bool canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, - const char *subname, const std::vector &elements) const override; - std::string dropObjectEx(App::DocumentObject*, App::DocumentObject*, const char *, - const std::vector &) override; + bool canDropObjects() const override + { + return true; + } + bool canDragAndDropObject(App::DocumentObject*) const override + { + return false; + } + bool canDropObjectEx( + App::DocumentObject* obj, + App::DocumentObject* owner, + const char* subname, + const std::vector& elements + ) const override; + std::string dropObjectEx( + App::DocumentObject*, + App::DocumentObject*, + const char*, + const std::vector& + ) override; std::vector claimChildren() const override; bool doubleClicked() override; void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; bool setEdit(int ModNum) override; - void attach(App::DocumentObject *obj) override; - void onChanged(const App::Property *prop) override; + void attach(App::DocumentObject* obj) override; + void onChanged(const App::Property* prop) override; private: - enum { + enum + { Synchronize = 0, SelectObject = 4 // must be higher than 3 (EditMode::Color) }; @@ -86,7 +101,7 @@ private: using ViewProviderSubShapeBinderPython = Gui::ViewProviderFeaturePythonT; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderShapeBinder_H +#endif // PARTGUI_ViewProviderShapeBinder_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp index 125c904a66..4c7a8e211a 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp @@ -20,7 +20,7 @@ * * ***************************************************************************/ -# include +#include #include #include @@ -41,9 +41,9 @@ using namespace PartDesignGui; PROPERTY_SOURCE(PartDesignGui::ViewProviderSketchBased, PartDesignGui::ViewProvider) -ViewProviderSketchBased::ViewProviderSketchBased() : - pcProfileToggle(new SoToggleSwitch), - pcProfileShape(new PartGui::SoPreviewShape) +ViewProviderSketchBased::ViewProviderSketchBased() + : pcProfileToggle(new SoToggleSwitch) + , pcProfileShape(new PartGui::SoPreviewShape) { auto annotation = new Gui::So3DAnnotation; annotation->addChild(pcProfileShape); @@ -61,20 +61,24 @@ ViewProviderSketchBased::ViewProviderSketchBased() : updateProfileVisibility(); auto* styleParametersManager = Base::provideService(); - pcProfileShape->transparency = 1.0F - static_cast( - styleParametersManager->resolve(StyleParameters::PreviewProfileOpacity).value); + pcProfileShape->transparency = 1.0F + - static_cast(styleParametersManager->resolve(StyleParameters::PreviewProfileOpacity) + .value); pcProfileShape->lineWidth = static_cast( - styleParametersManager->resolve(StyleParameters::PreviewProfileLineWidth).value); + styleParametersManager->resolve(StyleParameters::PreviewProfileLineWidth).value + ); } ViewProviderSketchBased::~ViewProviderSketchBased() = default; -std::vector ViewProviderSketchBased::claimChildren() const { +std::vector ViewProviderSketchBased::claimChildren() const +{ std::vector temp; App::DocumentObject* sketch = getObject()->Profile.getValue(); - if (sketch && !sketch->isDerivedFrom()) + if (sketch && !sketch->isDerivedFrom()) { temp.push_back(sketch); + } return temp; } @@ -100,7 +104,9 @@ void ViewProviderSketchBased::updateProfileShape() auto profileShape = profileBased->getTopoShapeVerifiedFace(true); // set the correct coordinate space for the profile shape - profileShape.setPlacement(profileShape.getPlacement() * profileBased->Placement.getValue().inverse()); + profileShape.setPlacement( + profileShape.getPlacement() * profileBased->Placement.getValue().inverse() + ); updatePreviewShape(profileShape, pcProfileShape); } @@ -117,7 +123,6 @@ void ViewProviderSketchBased::updateData(const App::Property* prop) if (prop == &profileBased->Profile) { updateProfileShape(); } - } void ViewProviderSketchBased::updatePreview() { diff --git a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h index 0294730692..799ca67f48 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h +++ b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h @@ -28,12 +28,13 @@ #include #include -namespace PartDesignGui { +namespace PartDesignGui +{ /** * A common base class for Sketch based view providers */ -class PartDesignGuiExport ViewProviderSketchBased : public ViewProvider +class PartDesignGuiExport ViewProviderSketchBased: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderSketchBased); @@ -59,10 +60,11 @@ private: Gui::CoinPtr pcProfileShape; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/PartDesign/Preview"); + "User parameter:BaseApp/Preferences/Mod/PartDesign/Preview" + ); Gui::ParamHandlers handlers; }; -} /* PartDesignGui */ +} // namespace PartDesignGui #endif /* end of include guard: VIEWPROVIDERSKETCHBASED_H_QKP3UG9A */ diff --git a/src/Mod/PartDesign/Gui/ViewProviderThickness.cpp b/src/Mod/PartDesign/Gui/ViewProviderThickness.cpp index 92957156f5..eaf5d6b4fa 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderThickness.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderThickness.cpp @@ -21,16 +21,16 @@ ***************************************************************************/ - #include "TaskThicknessParameters.h" #include "ViewProviderThickness.h" using namespace PartDesignGui; -PROPERTY_SOURCE(PartDesignGui::ViewProviderThickness,PartDesignGui::ViewProviderDressUp) +PROPERTY_SOURCE(PartDesignGui::ViewProviderThickness, PartDesignGui::ViewProviderDressUp) -const std::string & ViewProviderThickness::featureName() const { +const std::string& ViewProviderThickness::featureName() const +{ static const std::string name = "Thickness"; return name; } @@ -41,6 +41,7 @@ void ViewProviderThickness::setupContextMenu(QMenu* menu, QObject* receiver, con PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); } -TaskDlgFeatureParameters *ViewProviderThickness::getEditDialog() { - return new TaskDlgThicknessParameters (this); +TaskDlgFeatureParameters* ViewProviderThickness::getEditDialog() +{ + return new TaskDlgThicknessParameters(this); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderThickness.h b/src/Mod/PartDesign/Gui/ViewProviderThickness.h index d4e5e5d4b4..70af4732da 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderThickness.h +++ b/src/Mod/PartDesign/Gui/ViewProviderThickness.h @@ -27,9 +27,10 @@ #include "ViewProviderDressUp.h" -namespace PartDesignGui { +namespace PartDesignGui +{ -class PartDesignGuiExport ViewProviderThickness : public ViewProviderDressUp +class PartDesignGuiExport ViewProviderThickness: public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderThickness) PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderThickness); @@ -37,19 +38,21 @@ class PartDesignGuiExport ViewProviderThickness : public ViewProviderDressUp public: /// constructor ViewProviderThickness() - { sPixmap = "PartDesign_Thickness.svg"; - menuName = tr("Thickness Parameters"); } + { + sPixmap = "PartDesign_Thickness.svg"; + menuName = tr("Thickness Parameters"); + } /// return "Thickness" - const std::string & featureName() const override; + const std::string& featureName() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - TaskDlgFeatureParameters *getEditDialog() override; + TaskDlgFeatureParameters* getEditDialog() override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderThickness_H +#endif // PARTGUI_ViewProviderThickness_H diff --git a/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp b/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp index 80f87b4cab..d5e203d228 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderTransformed.cpp @@ -21,13 +21,12 @@ ******************************************************************************/ - -# include -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include +#include #include @@ -47,7 +46,7 @@ using namespace PartDesignGui; PROPERTY_SOURCE(PartDesignGui::ViewProviderTransformed, PartDesignGui::ViewProvider) -const std::string & ViewProviderTransformed::featureName() const +const std::string& ViewProviderTransformed::featureName() const { static const std::string name = "undefined"; return name; @@ -66,7 +65,8 @@ void ViewProviderTransformed::setupContextMenu(QMenu* menu, QObject* receiver, c ViewProvider::setupContextMenu(menu, receiver, member); } -Gui::ViewProvider *ViewProviderTransformed::startEditing(int ModNum) { +Gui::ViewProvider* ViewProviderTransformed::startEditing(int ModNum) +{ auto* pcTransformed = getObject(); if (!pcTransformed->Originals.getSize()) { @@ -94,8 +94,7 @@ bool ViewProviderTransformed::setEdit(int ModNum) } void ViewProviderTransformed::attachPreview() -{ -} +{} void ViewProviderTransformed::updatePreview() { @@ -129,16 +128,19 @@ void ViewProviderTransformed::updatePreview() pcPreviewRoot->addChild(sep); } } - } catch (const Base::ValueError&) { + } + catch (const Base::ValueError&) { // no-op - ignore misconfigured objects - } catch (const Base::Exception& e) { + } + catch (const Base::Exception& e) { e.reportException(); } ViewProvider::updatePreview(); } -void ViewProviderTransformed::handleTransformedResult(PartDesign::Transformed* pcTransformed) { +void ViewProviderTransformed::handleTransformedResult(PartDesign::Transformed* pcTransformed) +{ unsigned rejected = 0; TopoDS_Shape cShape = pcTransformed->rejected; @@ -150,12 +152,17 @@ void ViewProviderTransformed::handleTransformedResult(PartDesign::Transformed* p if (rejected > 0) { if (rejected == 1) { - Base::Console().translatedUserWarning("ViewProviderTransformed", - "One transformed shape does not intersect the support"); + Base::Console().translatedUserWarning( + "ViewProviderTransformed", + "One transformed shape does not intersect the support" + ); } else { - Base::Console().translatedUserWarning("ViewProviderTransformed", - "%d transformed shapes do not intersect the support", rejected); + Base::Console().translatedUserWarning( + "ViewProviderTransformed", + "%d transformed shapes do not intersect the support", + rejected + ); } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderTransformed.h b/src/Mod/PartDesign/Gui/ViewProviderTransformed.h index 933fdaf7b3..a9923eeec7 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderTransformed.h +++ b/src/Mod/PartDesign/Gui/ViewProviderTransformed.h @@ -28,38 +28,43 @@ #include -namespace PartDesign { - class Transformed; +namespace PartDesign +{ +class Transformed; } -namespace PartDesignGui { +namespace PartDesignGui +{ class TaskDlgTransformedParameters; -class PartDesignGuiExport ViewProviderTransformed : public ViewProvider +class PartDesignGuiExport ViewProviderTransformed: public ViewProvider { PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderTransformed); public: ViewProviderTransformed() = default; - ~ViewProviderTransformed() override = default; + ~ViewProviderTransformed() override = default; // The feature name of the subclass - virtual const std::string & featureName() const; + virtual const std::string& featureName() const; std::string featureIcon() const; - void recomputeFeature(bool recompute=true); + void recomputeFeature(bool recompute = true); void setupContextMenu(QMenu*, QObject*, const char*) override; /// signals if the transformation contains errors - boost::signals2::signal signalDiagnosis; + boost::signals2::signal signalDiagnosis; // Name of menu dialog QString menuName; - Gui::ViewProvider *startEditing(int ModNum=0) override; + Gui::ViewProvider* startEditing(int ModNum = 0) override; - QString getMessage() const { return diagMessage; } + QString getMessage() const + { + return diagMessage; + } protected: bool setEdit(int ModNum) override; @@ -75,7 +80,7 @@ protected: }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTGUI_ViewProviderTransformed_H +#endif // PARTGUI_ViewProviderTransformed_H diff --git a/src/Mod/PartDesign/Gui/Workbench.cpp b/src/Mod/PartDesign/Gui/Workbench.cpp index f66d6bc046..df6f5f8ea0 100644 --- a/src/Mod/PartDesign/Gui/Workbench.cpp +++ b/src/Mod/PartDesign/Gui/Workbench.cpp @@ -21,7 +21,6 @@ ***************************************************************************/ - #include #include #include @@ -38,7 +37,7 @@ using namespace PartDesignGui; namespace sp = std::placeholders; -#if 0 // needed for Qt's lupdate utility +#if 0 // needed for Qt's lupdate utility qApp->translate("Workbench", "&Sketch"); // qApp->translate("Workbench", "&Part Design"); @@ -80,25 +79,24 @@ void Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) con auto selection = Gui::Selection().getSelection(); // Add move Tip Command if (!selection.empty()) { - App::DocumentObject *feature = selection.front().pObject; - PartDesign::Body *body = nullptr; + App::DocumentObject* feature = selection.front().pObject; + PartDesign::Body* body = nullptr; - body = PartDesignGui::getBodyFor (feature, false, false, true); + body = PartDesignGui::getBodyFor(feature, false, false, true); // lote of assertion so feature should be marked as a tip - if ( selection.size() == 1 && feature && body && ( - feature->isDerivedFrom() || - ( feature->isDerivedFrom() && - body->BaseFeature.getValue() == feature ) - ) ) { + if (selection.size() == 1 && feature && body + && (feature->isDerivedFrom() + || (feature->isDerivedFrom() + && body->BaseFeature.getValue() == feature))) { *item << "PartDesign_MoveTip"; } if (strcmp(recipient, "Tree") == 0) { - Gui::MDIView *activeView = Gui::Application::Instance->activeView(); + Gui::MDIView* activeView = Gui::Application::Instance->activeView(); - if (activeView ) { - if (feature && feature->isDerivedFrom()){ - *item << "Std_ToggleFreeze"; + if (activeView) { + if (feature && feature->isDerivedFrom()) { + *item << "Std_ToggleFreeze"; } if (activeView->getAppDocument()->countObjectsOfType() > 0) { @@ -107,29 +105,30 @@ void Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) con for (auto sel : selection) { // if at least one selected feature cannot be moved to a body // disable the entry - if ( addMoveFeature && !PartDesign::Body::isAllowed ( sel.pObject ) ) { + if (addMoveFeature && !PartDesign::Body::isAllowed(sel.pObject)) { addMoveFeature = false; } // if all at least one selected feature doesn't belong to the same body // disable the menu entry - if ( addMoveFeatureInTree && !body->hasObject ( sel.pObject ) ) { + if (addMoveFeatureInTree && !body->hasObject(sel.pObject)) { addMoveFeatureInTree = false; } - if ( !addMoveFeatureInTree && !addMoveFeature ) { + if (!addMoveFeatureInTree && !addMoveFeature) { break; } } if (addMoveFeature) { - *item << "PartDesign_MoveFeature"; + *item << "PartDesign_MoveFeature"; } if (addMoveFeatureInTree) { - *item << "PartDesign_MoveFeatureInTree"; + *item << "PartDesign_MoveFeatureInTree"; } } } - if (Gui::Selection().countObjectsOfType() - - Gui::Selection().countObjectsOfType() == 1 ) { + if (Gui::Selection().countObjectsOfType() + - Gui::Selection().countObjectsOfType() + == 1) { *item << "PartDesign_MultiTransform"; } } @@ -149,12 +148,8 @@ void Workbench::activated() std::vector Watcher; - const char* Vertex[] = { - "Part_DatumPoint", - "Part_DatumLine", - "Part_DatumPlane", - "Part_CoordinateSystem", - nullptr}; + const char* Vertex[] + = {"Part_DatumPoint", "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem", nullptr}; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Vertex COUNT 1..", Vertex, @@ -167,7 +162,8 @@ void Workbench::activated() "PartDesign_Line", "PartDesign_Plane", "PartDesign_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Vertex COUNT 1..", Vertex1, @@ -182,7 +178,8 @@ void Workbench::activated() "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Edge COUNT 1..", Edge, @@ -195,7 +192,8 @@ void Workbench::activated() "PartDesign_Line", "PartDesign_Plane", "PartDesign_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Edge COUNT 1..", Edge1, @@ -213,7 +211,8 @@ void Workbench::activated() "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Face COUNT 1", Face, @@ -226,7 +225,8 @@ void Workbench::activated() "PartDesign_Line", "PartDesign_Plane", "PartDesign_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Face COUNT 1", Face1, @@ -234,9 +234,7 @@ void Workbench::activated() "PartDesign_CoordinateSystem" )); - const char* Body[] = { - "PartDesign_NewSketch", - nullptr}; + const char* Body[] = {"PartDesign_NewSketch", nullptr}; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Body COUNT 1", Body, @@ -244,9 +242,7 @@ void Workbench::activated() "PartDesign_Body" )); - const char* Body2[] = { - "PartDesign_Boolean", - nullptr}; + const char* Body2[] = {"PartDesign_Boolean", nullptr}; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Body COUNT 1..", Body2, @@ -260,7 +256,8 @@ void Workbench::activated() "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT App::Plane COUNT 1", Plane1, @@ -274,7 +271,8 @@ void Workbench::activated() "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Plane COUNT 1", Plane2, @@ -287,7 +285,8 @@ void Workbench::activated() "PartDesign_Line", "PartDesign_Plane", "PartDesign_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT App::Plane COUNT 1", Plane3, @@ -300,7 +299,8 @@ void Workbench::activated() "PartDesign_Line", "PartDesign_Plane", "PartDesign_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Plane COUNT 1", Plane4, @@ -308,11 +308,7 @@ void Workbench::activated() "PartDesign_CoordinateSystem" )); - const char* Line[] = { - "Part_DatumPoint", - "Part_DatumLine", - "Part_DatumPlane", - nullptr}; + const char* Line[] = {"Part_DatumPoint", "Part_DatumLine", "Part_DatumPlane", nullptr}; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Line COUNT 1", Line, @@ -320,11 +316,7 @@ void Workbench::activated() "PartDesign_Body" )); - const char* Line1[] = { - "PartDesign_Point", - "PartDesign_Line", - "PartDesign_Plane", - nullptr}; + const char* Line1[] = {"PartDesign_Point", "PartDesign_Line", "PartDesign_Plane", nullptr}; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Line COUNT 1", Line1, @@ -332,12 +324,8 @@ void Workbench::activated() "PartDesign_CoordinateSystem" )); - const char* Point[] = { - "Part_DatumPoint", - "Part_DatumLine", - "Part_DatumPlane", - "Part_CoordinateSystem", - nullptr}; + const char* Point[] + = {"Part_DatumPoint", "Part_DatumLine", "Part_DatumPlane", "Part_CoordinateSystem", nullptr}; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Point COUNT 1", Point, @@ -350,7 +338,8 @@ void Workbench::activated() "PartDesign_Line", "PartDesign_Plane", "PartDesign_CoordinateSystem", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::Point COUNT 1", Point1, @@ -358,21 +347,18 @@ void Workbench::activated() "PartDesign_CoordinateSystem" )); - const char* NoSel[] = { - "PartDesign_Body", - nullptr}; - Watcher.push_back(new Gui::TaskView::TaskWatcherCommandsEmptySelection( - NoSel, - "Start Part", - "Part_Box_Parametric" - )); + const char* NoSel[] = {"PartDesign_Body", nullptr}; + Watcher.push_back( + new Gui::TaskView::TaskWatcherCommandsEmptySelection(NoSel, "Start Part", "Part_Box_Parametric") + ); const char* Faces[] = { "PartDesign_Fillet", "PartDesign_Chamfer", "PartDesign_Draft", "PartDesign_Thickness", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Part::Feature SUBELEMENT Face COUNT 2..", Faces, @@ -393,7 +379,8 @@ void Workbench::activated() "PartDesign_SubtractivePipe", "PartDesign_AdditiveHelix", "PartDesign_SubtractiveHelix", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Sketcher::SketchObject COUNT 1", Sketch, @@ -406,7 +393,8 @@ void Workbench::activated() "PartDesign_SubtractiveLoft", "PartDesign_AdditivePipe", "PartDesign_SubtractivePipe", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT Sketcher::SketchObject COUNT 2..", Sketches, @@ -423,7 +411,8 @@ void Workbench::activated() "PartDesign_SubtractiveLoft", "PartDesign_AdditivePipe", "PartDesign_SubtractivePipe", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::ShapeBinder COUNT 1", ShapeBinder, @@ -440,7 +429,8 @@ void Workbench::activated() "PartDesign_SubtractiveLoft", "PartDesign_AdditivePipe", "PartDesign_SubtractivePipe", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::SubShapeBinder COUNT 1", SubShapeBinder, @@ -453,7 +443,8 @@ void Workbench::activated() "PartDesign_LinearPattern", "PartDesign_PolarPattern", "PartDesign_MultiTransform", - nullptr}; + nullptr + }; Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( "SELECT PartDesign::SketchBased", Transformed, @@ -462,15 +453,21 @@ void Workbench::activated() )); addTaskWatcher(Watcher); - if(App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/PartDesign")->GetBool("SwitchToTask", true)) + if (App::GetApplication() + .GetUserParameter() + .GetGroup("BaseApp") + ->GetGroup("Preferences") + ->GetGroup("Mod/PartDesign") + ->GetBool("SwitchToTask", true)) { Gui::Control().showTaskView(); + } } void Workbench::deactivated() { removeTaskWatcher(); // reset the active Body - Gui::Command::doCommand(Gui::Command::Doc,"import PartDesignGui"); + Gui::Command::doCommand(Gui::Command::Doc, "import PartDesignGui"); Gui::Workbench::deactivated(); } @@ -541,17 +538,9 @@ Gui::MenuItem* Workbench::setupMenuBar() const << "PartDesign_ShapeBinder" << "PartDesign_SubShapeBinder" << "PartDesign_Clone" - << "Separator" - << additives - << "PartDesign_CompPrimitiveAdditive" - << "Separator" - << subtractives - << "PartDesign_CompPrimitiveSubtractive" - << "Separator" - << dressups - << "Separator" - << transformations - << "Separator" + << "Separator" << additives << "PartDesign_CompPrimitiveAdditive" + << "Separator" << subtractives << "PartDesign_CompPrimitiveSubtractive" + << "Separator" << dressups << "Separator" << transformations << "Separator" << "PartDesign_Boolean" << "Separator" << "Materials_InspectAppearance" diff --git a/src/Mod/PartDesign/Gui/Workbench.h b/src/Mod/PartDesign/Gui/Workbench.h index af2bf5137b..7b4439f562 100644 --- a/src/Mod/PartDesign/Gui/Workbench.h +++ b/src/Mod/PartDesign/Gui/Workbench.h @@ -27,18 +27,20 @@ #include #include -namespace Gui { +namespace Gui +{ class MenuItem; } -namespace PartDesignGui { +namespace PartDesignGui +{ /** * @author Werner Mayer */ -class PartDesignGuiExport Workbench : public Gui::StdWorkbench +class PartDesignGuiExport Workbench: public Gui::StdWorkbench { TYPESYSTEM_HEADER_WITH_OVERRIDE(); @@ -59,7 +61,7 @@ protected: Gui::ToolBarItem* setupToolBars() const override; }; -} // namespace PartDesignGui +} // namespace PartDesignGui -#endif // PARTDESIGN_WORKBENCH_H +#endif // PARTDESIGN_WORKBENCH_H diff --git a/src/Mod/PartDesign/Gui/WorkflowManager.cpp b/src/Mod/PartDesign/Gui/WorkflowManager.cpp index dab60469f6..8f143aab40 100644 --- a/src/Mod/PartDesign/Gui/WorkflowManager.cpp +++ b/src/Mod/PartDesign/Gui/WorkflowManager.cpp @@ -21,8 +21,8 @@ ***************************************************************************/ -# include -# include +#include +#include #include @@ -38,91 +38,106 @@ using namespace PartDesignGui; namespace sp = std::placeholders; -WorkflowManager * WorkflowManager::_instance = nullptr; +WorkflowManager* WorkflowManager::_instance = nullptr; -WorkflowManager::WorkflowManager() { +WorkflowManager::WorkflowManager() +{ // Fill the map with already opened documents - for ( auto doc : App::GetApplication().getDocuments() ) { - slotFinishRestoreDocument ( *doc ); - } + for (auto doc : App::GetApplication().getDocuments()) { + slotFinishRestoreDocument(*doc); + } - //NOLINTBEGIN + // NOLINTBEGIN connectNewDocument = App::GetApplication().signalNewDocument.connect( - std::bind( &WorkflowManager::slotNewDocument, this, sp::_1 ) ); + std::bind(&WorkflowManager::slotNewDocument, this, sp::_1) + ); connectFinishRestoreDocument = App::GetApplication().signalFinishRestoreDocument.connect( - std::bind( &WorkflowManager::slotFinishRestoreDocument, this, sp::_1 ) ); + std::bind(&WorkflowManager::slotFinishRestoreDocument, this, sp::_1) + ); connectDeleteDocument = App::GetApplication().signalDeleteDocument.connect( - std::bind( &WorkflowManager::slotDeleteDocument, this, sp::_1 ) ); - //NOLINTEND + std::bind(&WorkflowManager::slotDeleteDocument, this, sp::_1) + ); + // NOLINTEND } -WorkflowManager::~WorkflowManager() { +WorkflowManager::~WorkflowManager() +{ // they won't be automatically disconnected on destruction! - connectNewDocument.disconnect (); - connectFinishRestoreDocument.disconnect (); - connectDeleteDocument.disconnect (); + connectNewDocument.disconnect(); + connectFinishRestoreDocument.disconnect(); + connectDeleteDocument.disconnect(); } // Those destruction/construction is not really needed and could be done in the instance() // but to make things a bit more clear, better to keep them around. -void WorkflowManager::init() { +void WorkflowManager::init() +{ if (!_instance) { _instance = new WorkflowManager(); - } else { - //throw Base::RuntimeError( "Trying to init the workflow manager second time." ); + } + else { + // throw Base::RuntimeError( "Trying to init the workflow manager second time." ); } } -WorkflowManager *WorkflowManager::instance() { +WorkflowManager* WorkflowManager::instance() +{ if (!_instance) { WorkflowManager::init(); } return _instance; } -void WorkflowManager::destruct() { +void WorkflowManager::destruct() +{ if (_instance) { delete _instance; _instance = nullptr; } } -void WorkflowManager::slotNewDocument( const App::Document &doc ) { +void WorkflowManager::slotNewDocument(const App::Document& doc) +{ // new document always uses new workflow dwMap[&doc] = Workflow::Modern; } -void WorkflowManager::slotFinishRestoreDocument( const App::Document &doc ) { - Workflow wf = guessWorkflow (&doc); +void WorkflowManager::slotFinishRestoreDocument(const App::Document& doc) +{ + Workflow wf = guessWorkflow(&doc); // Mark document as undetermined if the guessed workflow is not new - if( wf != Workflow::Modern ) { + if (wf != Workflow::Modern) { wf = Workflow::Undetermined; } dwMap[&doc] = wf; } -void WorkflowManager::slotDeleteDocument( const App::Document &doc ) { +void WorkflowManager::slotDeleteDocument(const App::Document& doc) +{ dwMap.erase(&doc); } -Workflow WorkflowManager::getWorkflowForDocument( App::Document *doc) { - assert (doc); +Workflow WorkflowManager::getWorkflowForDocument(App::Document* doc) +{ + assert(doc); auto it = dwMap.find(doc); - if ( it!=dwMap.end() ) { + if (it != dwMap.end()) { return it->second; - } else { + } + else { // We haven't yet checked the file workflow // May happen if e.g. file not completely loaded yet return Workflow::Undetermined; } } -Workflow WorkflowManager::determineWorkflow(App::Document *doc) { - Workflow rv = getWorkflowForDocument (doc); +Workflow WorkflowManager::determineWorkflow(App::Document* doc) +{ + Workflow rv = getWorkflowForDocument(doc); if (rv != Workflow::Undetermined) { // Return if workflow is known @@ -130,85 +145,108 @@ Workflow WorkflowManager::determineWorkflow(App::Document *doc) { } // Guess the workflow again - rv = guessWorkflow (doc); + rv = guessWorkflow(doc); if (rv != Workflow::Modern) { QMessageBox msgBox(Gui::getMainWindow()); - if ( rv == Workflow::Legacy ) { // legacy messages - msgBox.setText( QObject::tr( "The document \"%1\" you are editing was designed with an old version of " - "Part Design workbench." ).arg( QString::fromStdString ( doc->getName()) ) ); - msgBox.setInformativeText ( - QObject::tr( "Migrate in order to use modern Part Design features?" ) ); + if (rv == Workflow::Legacy) { // legacy messages + msgBox.setText( + QObject::tr( + "The document \"%1\" you are editing was designed with an old version of " + "Part Design workbench." + ) + .arg(QString::fromStdString(doc->getName())) + ); + msgBox.setInformativeText( + QObject::tr("Migrate in order to use modern Part Design features?") + ); } - else { // The document is already in the middle of migration - msgBox.setText( QObject::tr( "The document \"%1\" seems to be either in the middle of" - " the migration process from legacy Part Design or have a slightly broken structure." - ).arg( QString::fromStdString ( doc->getName()) ) ); - msgBox.setInformativeText ( - QObject::tr( "Make the migration automatically?" ) ); + else { // The document is already in the middle of migration + msgBox.setText( + QObject::tr( + "The document \"%1\" seems to be either in the middle of" + " the migration process from legacy Part Design or have a slightly broken " + "structure." + ) + .arg(QString::fromStdString(doc->getName())) + ); + msgBox.setInformativeText(QObject::tr("Make the migration automatically?")); } - msgBox.setDetailedText( QObject::tr( "Note: If you choose to migrate you won't be able to edit" - " the file with an older FreeCAD version.\n" - "If you refuse to migrate you won't be able to use new PartDesign features" - " like Bodies and Parts. As a result you also won't be able to use your parts" - " in the assembly workbench.\n" - "Although you will be able to migrate any moment later with 'Part Design -> Migrate'." ) ); - msgBox.setIcon( QMessageBox::Question ); - QPushButton * yesBtn = msgBox.addButton ( QMessageBox::Yes ); - QPushButton * manuallyBtn = msgBox.addButton ( - QObject::tr ( "Migrate Manually" ), QMessageBox::YesRole ); + msgBox.setDetailedText( + QObject::tr( + "Note: If you choose to migrate you won't be able to edit" + " the file with an older FreeCAD version.\n" + "If you refuse to migrate you won't be able to use new PartDesign features" + " like Bodies and Parts. As a result you also won't be able to use your parts" + " in the assembly workbench.\n" + "Although you will be able to migrate any moment later with 'Part Design -> " + "Migrate'." + ) + ); + msgBox.setIcon(QMessageBox::Question); + QPushButton* yesBtn = msgBox.addButton(QMessageBox::Yes); + QPushButton* manuallyBtn + = msgBox.addButton(QObject::tr("Migrate Manually"), QMessageBox::YesRole); - // If it is already a document in the middle of the migration the user shouldn't refuse to migrate - if ( rv != Workflow::Undetermined ) { - msgBox.addButton ( QMessageBox::No ); + // If it is already a document in the middle of the migration the user shouldn't refuse to + // migrate + if (rv != Workflow::Undetermined) { + msgBox.addButton(QMessageBox::No); } - msgBox.setDefaultButton ( yesBtn ); + msgBox.setDefaultButton(yesBtn); // TODO: Add some description of manual migration mode (2015-08-09, Fat-Zer) msgBox.exec(); - if ( msgBox.clickedButton() == yesBtn ) { + if (msgBox.clickedButton() == yesBtn) { Gui::Application::Instance->commandManager().runCommandByName("PartDesign_Migrate"); rv = Workflow::Modern; - } else if ( msgBox.clickedButton() == manuallyBtn ) { + } + else if (msgBox.clickedButton() == manuallyBtn) { rv = Workflow::Undetermined; - } else { + } + else { rv = Workflow::Legacy; } } // Actually set the result in our map - dwMap[ doc ] = rv; + dwMap[doc] = rv; return rv; } -void WorkflowManager::forceWorkflow(const App::Document *doc, Workflow wf) { - dwMap[ doc ] = wf; +void WorkflowManager::forceWorkflow(const App::Document* doc, Workflow wf) +{ + dwMap[doc] = wf; } -Workflow WorkflowManager::guessWorkflow(const App::Document *doc) { +Workflow WorkflowManager::guessWorkflow(const App::Document* doc) +{ // Retrieve bodies of the document - auto features = doc->getObjectsOfType( PartDesign::Feature::getClassTypeId() ); + auto features = doc->getObjectsOfType(PartDesign::Feature::getClassTypeId()); - if( features.empty() ) { + if (features.empty()) { // a new file should be done in the new workflow return Workflow::Modern; - } else { - auto bodies = doc->getObjectsOfType( PartDesign::Body::getClassTypeId() ); + } + else { + auto bodies = doc->getObjectsOfType(PartDesign::Body::getClassTypeId()); if (bodies.empty()) { // If there are no bodies workflow is legacy return Workflow::Legacy; - } else { + } + else { bool features_without_bodies = false; - for( auto feat: features ) { - if( !PartDesign::Body::findBodyOf( feat ) ) { + for (auto feat : features) { + if (!PartDesign::Body::findBodyOf(feat)) { features_without_bodies = true; break; } } - // if there are features not belonging to any body it means that migration was incomplete, otherwise it's Modern + // if there are features not belonging to any body it means that migration was + // incomplete, otherwise it's Modern return features_without_bodies ? Workflow::Undetermined : Workflow::Modern; } } diff --git a/src/Mod/PartDesign/Gui/WorkflowManager.h b/src/Mod/PartDesign/Gui/WorkflowManager.h index baf60419db..7a74a9bb1e 100644 --- a/src/Mod/PartDesign/Gui/WorkflowManager.h +++ b/src/Mod/PartDesign/Gui/WorkflowManager.h @@ -23,74 +23,79 @@ #ifndef WORKFLOWMANAGER_H_PB7A5GCM #define WORKFLOWMANAGER_H_PB7A5GCM -namespace App { - class Document; +namespace App +{ +class Document; } -namespace PartDesignGui { +namespace PartDesignGui +{ /** * Defines allowded tool set provided by the workbench * Legacy mode provides a free PartDesign features but forbids bodies and parts */ -enum class Workflow { - Undetermined = 0, ///< No workflow was chosen yet - Legacy = 1<<0, ///< Old-style workflow with free features and no bodies - Modern = 1<<1, ///< New-style workflow with bodies, parts etc +enum class Workflow +{ + Undetermined = 0, ///< No workflow was chosen yet + Legacy = 1 << 0, ///< Old-style workflow with free features and no bodies + Modern = 1 << 1, ///< New-style workflow with bodies, parts etc }; /** * This class controls the workflow of each file. * It has been introduced to support legacy files migrating to the new workflow. */ -class PartDesignGuiExport WorkflowManager { +class PartDesignGuiExport WorkflowManager +{ public: - virtual ~WorkflowManager (); + virtual ~WorkflowManager(); /** * Lookup the workflow of the document in the map. * If the document not in the map yet return Workflow::Undetermined. */ - Workflow getWorkflowForDocument(App::Document *doc); + Workflow getWorkflowForDocument(App::Document* doc); /** - * Asserts the workflow of the document to be determined and prompt user to migrate if it is not modern. + * Asserts the workflow of the document to be determined and prompt user to migrate if it is not + * modern. * * If workflow was already chosen return it. - * If the guesed workflow is Workflow::Legacy or Workflow::Mixed the user will be prompted to migrate. - * If the user agrees the file will be migrated and the workflow will be set as modern. + * If the guesed workflow is Workflow::Legacy or Workflow::Mixed the user will be prompted to + * migrate. If the user agrees the file will be migrated and the workflow will be set as modern. * If the user refuses to migrate use the old workflow. */ - Workflow determineWorkflow(App::Document *doc); + Workflow determineWorkflow(App::Document* doc); /** * Force the desired workflow in document */ - void forceWorkflow (const App::Document *doc, Workflow wf); + void forceWorkflow(const App::Document* doc, Workflow wf); /** @name Init, Destruct an Access methods */ //@{ /// Creates an instance of the manager, should be called before any instance() - static void init (); + static void init(); /// Return an instance of the WorkflofManager. static WorkflowManager* instance(); /// destroy the manager - static void destruct (); + static void destruct(); //@} private: /// The class is not intended to be constructed outside of itself - WorkflowManager (); + WorkflowManager(); /// Get the signal on New document created - void slotNewDocument (const App::Document& doc); + void slotNewDocument(const App::Document& doc); /// Get the signal on document getting loaded - void slotFinishRestoreDocument (const App::Document& doc); + void slotFinishRestoreDocument(const App::Document& doc); /// Get the signal on document close and remove it from our list - void slotDeleteDocument (const App::Document& doc); + void slotDeleteDocument(const App::Document& doc); /// Guess the Workflow of the document out of it's content - Workflow guessWorkflow(const App::Document *doc); + Workflow guessWorkflow(const App::Document* doc); private: std::map dwMap; @@ -103,25 +108,29 @@ private: }; /// Assures that workflow of the given document is determined and returns true if it is Workflow::Legacy -inline bool assureLegacyWorkflow (App::Document *doc) { - return WorkflowManager::instance()->determineWorkflow( doc ) == Workflow::Legacy ; +inline bool assureLegacyWorkflow(App::Document* doc) +{ + return WorkflowManager::instance()->determineWorkflow(doc) == Workflow::Legacy; } /// Assures that workflow of the given document is determined and returns true if it is Workflow::Modern -inline bool assureModernWorkflow (App::Document *doc) { - return WorkflowManager::instance()->determineWorkflow( doc ) == Workflow::Modern ; +inline bool assureModernWorkflow(App::Document* doc) +{ + return WorkflowManager::instance()->determineWorkflow(doc) == Workflow::Modern; } /// Returns true if the workflow of the given document is Workflow::Legacy -inline bool isLegacyWorkflow (App::Document *doc) { - return WorkflowManager::instance()->getWorkflowForDocument( doc ) == Workflow::Legacy ; +inline bool isLegacyWorkflow(App::Document* doc) +{ + return WorkflowManager::instance()->getWorkflowForDocument(doc) == Workflow::Legacy; } /// Returns true if the workflow of the given document is Workflow::Modern -inline bool isModernWorkflow (App::Document *doc) { - return WorkflowManager::instance()->getWorkflowForDocument( doc ) == Workflow::Modern ; +inline bool isModernWorkflow(App::Document* doc) +{ + return WorkflowManager::instance()->getWorkflowForDocument(doc) == Workflow::Modern; } -} /* PartDesignGui */ +} // namespace PartDesignGui #endif /* end of include guard: WORKFLOWMANAGER_H_PB7A5GCM */ diff --git a/src/Mod/PartDesign/Init.py b/src/Mod/PartDesign/Init.py index d36504c91e..6b0a7260a0 100644 --- a/src/Mod/PartDesign/Init.py +++ b/src/Mod/PartDesign/Init.py @@ -1,26 +1,26 @@ -#*************************************************************************** -#* Copyright (c) 2001,2002 Juergen Riegel * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD 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 Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#***************************************************************************/ +# *************************************************************************** +# * Copyright (c) 2001,2002 Juergen Riegel * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD 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 Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# ***************************************************************************/ # FreeCAD init script of the PartDesign module -FreeCAD.__unit_test__ += [ "TestPartDesignApp" ] +FreeCAD.__unit_test__ += ["TestPartDesignApp"] diff --git a/src/Mod/PartDesign/InitGui.py b/src/Mod/PartDesign/InitGui.py index 13af01b55c..09427c6aab 100644 --- a/src/Mod/PartDesign/InitGui.py +++ b/src/Mod/PartDesign/InitGui.py @@ -1,25 +1,25 @@ -#*************************************************************************** -#* Copyright (c) 2002,2003 Juergen Riegel * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD 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 Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#***************************************************************************/ +# *************************************************************************** +# * Copyright (c) 2002,2003 Juergen Riegel * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD 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 Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# ***************************************************************************/ # PartDesign gui init module # @@ -27,10 +27,14 @@ # This is the second one of three init scripts, the third one # runs when the gui is up -class PartDesignWorkbench ( Workbench ): + +class PartDesignWorkbench(Workbench): "PartDesign workbench object" + def __init__(self): - self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/PartDesign/Resources/icons/PartDesignWorkbench.svg" + self.__class__.Icon = ( + FreeCAD.getResourceDir() + "Mod/PartDesign/Resources/icons/PartDesignWorkbench.svg" + ) self.__class__.MenuText = "Part Design" self.__class__.ToolTip = "Part Design workbench" @@ -40,7 +44,7 @@ class PartDesignWorkbench ( Workbench ): import traceback from PartDesign.WizardShaft import WizardShaft except RuntimeError: - print ("{}".format(traceback.format_exc())) + print("{}".format(traceback.format_exc())) except ImportError: print("Wizard shaft module cannot be loaded") try: @@ -52,14 +56,17 @@ class PartDesignWorkbench ( Workbench ): import PartDesign from PartDesign.InvoluteGearFeature import CommandInvoluteGear - Gui.addCommand('PartDesign_InvoluteGear', CommandInvoluteGear()) + + Gui.addCommand("PartDesign_InvoluteGear", CommandInvoluteGear()) from PartDesign.SprocketFeature import CommandSprocket - FreeCADGui.addCommand('PartDesign_Sprocket', CommandSprocket()) + + FreeCADGui.addCommand("PartDesign_Sprocket", CommandSprocket()) def GetClassName(self): return "PartDesignGui::Workbench" + Gui.addWorkbench(PartDesignWorkbench()) -FreeCAD.__unit_test__ += [ "TestPartDesignGui" ] +FreeCAD.__unit_test__ += ["TestPartDesignGui"] diff --git a/src/Mod/PartDesign/InvoluteGearFeature.py b/src/Mod/PartDesign/InvoluteGearFeature.py index 3a5a25e13a..8bbb0f275a 100644 --- a/src/Mod/PartDesign/InvoluteGearFeature.py +++ b/src/Mod/PartDesign/InvoluteGearFeature.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2014 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2014 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import pathlib import FreeCAD, Part @@ -29,35 +29,40 @@ if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui -__title__="PartDesign InvoluteGearObject management" +__title__ = "PartDesign InvoluteGearObject management" __author__ = "Juergen Riegel" __url__ = "https://www.freecad.org" def makeInvoluteGear(name): - '''makeInvoluteGear(name): makes an InvoluteGear''' - obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",name) + """makeInvoluteGear(name): makes an InvoluteGear""" + obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", name) _InvoluteGear(obj) if FreeCAD.GuiUp: _ViewProviderInvoluteGear(obj.ViewObject) - #FreeCAD.ActiveDocument.recompute() + # FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: - body=FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody") - part=FreeCADGui.ActiveDocument.ActiveView.getActiveObject("part") + body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody") + part = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("part") if body: - body.Group=body.Group+[obj] + body.Group = body.Group + [obj] elif part: - part.Group=part.Group+[obj] + part.Group = part.Group + [obj] return obj class CommandInvoluteGear: "GUI command to create an InvoluteGear" + def GetResources(self): - return {'Pixmap' : 'PartDesign_InternalExternalGear', - 'MenuText': QtCore.QT_TRANSLATE_NOOP("PartDesign_InvoluteGear","Involute Gear"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("PartDesign_InvoluteGear","Creates or edits the involute gear definition")} + return { + "Pixmap": "PartDesign_InternalExternalGear", + "MenuText": QtCore.QT_TRANSLATE_NOOP("PartDesign_InvoluteGear", "Involute Gear"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "PartDesign_InvoluteGear", "Creates or edits the involute gear definition" + ), + } def Activated(self): FreeCAD.ActiveDocument.openTransaction("Create involute gear") @@ -74,7 +79,8 @@ class CommandInvoluteGear: class _InvoluteGear: "The InvoluteGear object" - def __init__(self,obj): + + def __init__(self, obj): self.Type = "InvoluteGear" self._ensure_properties(obj, is_restore=False) obj.Proxy = self @@ -94,45 +100,94 @@ class _InvoluteGear: # for details about the property's docstring translation, # see https://tracker.freecad.org/view.php?id=2524 - ensure_property("App::PropertyInteger", "NumberOfTeeth", + ensure_property( + "App::PropertyInteger", + "NumberOfTeeth", doc=QtCore.QT_TRANSLATE_NOOP("App::Property", "Number of gear teeth"), - default=26) - ensure_property("App::PropertyLength", "Modules", + default=26, + ) + ensure_property( + "App::PropertyLength", + "Modules", doc=QtCore.QT_TRANSLATE_NOOP("App::Property", "Module of the gear"), - default="2.5 mm") - ensure_property("App::PropertyAngle", "PressureAngle", + default="2.5 mm", + ) + ensure_property( + "App::PropertyAngle", + "PressureAngle", doc=QtCore.QT_TRANSLATE_NOOP("App::Property", "Pressure angle of gear teeth"), - default="20 deg") - ensure_property("App::PropertyBool", "HighPrecision", - doc=QtCore.QT_TRANSLATE_NOOP("App::Property", - "True=2 curves with each 3 control points, False=1 curve with 4 control points."), - default=True) - ensure_property("App::PropertyBool", "ExternalGear", - doc=QtCore.QT_TRANSLATE_NOOP("App::Property", "True=external Gear, False=internal Gear"), - default=True) - ensure_property("App::PropertyFloat", "AddendumCoefficient", - doc=QtCore.QT_TRANSLATE_NOOP("App::Property", - "The height of the tooth from the pitch circle up to its tip, normalized by the module."), - default=lambda: 1.0 if obj.ExternalGear else 0.6) - ensure_property("App::PropertyFloat","DedendumCoefficient", - doc=QtCore.QT_TRANSLATE_NOOP("App::Property", - "The height of the tooth from the pitch circle down to its root, normalized by the module."), - default=1.25) - ensure_property("App::PropertyFloat","RootFilletCoefficient", - doc=QtCore.QT_TRANSLATE_NOOP("App::Property", - "The radius of the fillet at the root of the tooth, normalized by the module."), - default=lambda: 0.375 if is_restore else 0.38) - ensure_property("App::PropertyFloat","ProfileShiftCoefficient", - doc=QtCore.QT_TRANSLATE_NOOP("App::Property", - "The distance by which the reference profile is shifted outwards, normalized by the module."), - default=0.0) + default="20 deg", + ) + ensure_property( + "App::PropertyBool", + "HighPrecision", + doc=QtCore.QT_TRANSLATE_NOOP( + "App::Property", + "True=2 curves with each 3 control points, False=1 curve with 4 control points.", + ), + default=True, + ) + ensure_property( + "App::PropertyBool", + "ExternalGear", + doc=QtCore.QT_TRANSLATE_NOOP( + "App::Property", "True=external Gear, False=internal Gear" + ), + default=True, + ) + ensure_property( + "App::PropertyFloat", + "AddendumCoefficient", + doc=QtCore.QT_TRANSLATE_NOOP( + "App::Property", + "The height of the tooth from the pitch circle up to its tip, normalized by the module.", + ), + default=lambda: 1.0 if obj.ExternalGear else 0.6, + ) + ensure_property( + "App::PropertyFloat", + "DedendumCoefficient", + doc=QtCore.QT_TRANSLATE_NOOP( + "App::Property", + "The height of the tooth from the pitch circle down to its root, normalized by the module.", + ), + default=1.25, + ) + ensure_property( + "App::PropertyFloat", + "RootFilletCoefficient", + doc=QtCore.QT_TRANSLATE_NOOP( + "App::Property", + "The radius of the fillet at the root of the tooth, normalized by the module.", + ), + default=lambda: 0.375 if is_restore else 0.38, + ) + ensure_property( + "App::PropertyFloat", + "ProfileShiftCoefficient", + doc=QtCore.QT_TRANSLATE_NOOP( + "App::Property", + "The distance by which the reference profile is shifted outwards, normalized by the module.", + ), + default=0.0, + ) - def execute(self,obj): + def execute(self, obj): w = fcgear.FCWireBuilder() - generator_func = involute.CreateExternalGear if obj.ExternalGear else involute.CreateInternalGear - generator_func(w, obj.Modules.Value, obj.NumberOfTeeth, obj.PressureAngle.Value, - split=obj.HighPrecision, addCoeff=obj.AddendumCoefficient, dedCoeff=obj.DedendumCoefficient, - filletCoeff=obj.RootFilletCoefficient, shiftCoeff=obj.ProfileShiftCoefficient) + generator_func = ( + involute.CreateExternalGear if obj.ExternalGear else involute.CreateInternalGear + ) + generator_func( + w, + obj.Modules.Value, + obj.NumberOfTeeth, + obj.PressureAngle.Value, + split=obj.HighPrecision, + addCoeff=obj.AddendumCoefficient, + dedCoeff=obj.DedendumCoefficient, + filletCoeff=obj.RootFilletCoefficient, + shiftCoeff=obj.ProfileShiftCoefficient, + ) gearw = Part.Wire([o.toShape() for o in w.wire]) obj.Shape = gearw obj.positionBySupport() @@ -142,7 +197,7 @@ class _InvoluteGear: class _ViewProviderInvoluteGear: "A View Provider for the InvoluteGear object" - def __init__(self,vobj): + def __init__(self, vobj): vobj.Proxy = self def getIcon(self): @@ -152,62 +207,77 @@ class _ViewProviderInvoluteGear: self.ViewObject = vobj self.Object = vobj.Object - def setEdit(self,vobj,mode): - taskd = _InvoluteGearTaskPanel(self.Object,mode) + def setEdit(self, vobj, mode): + taskd = _InvoluteGearTaskPanel(self.Object, mode) taskd.obj = vobj.Object taskd.update() FreeCADGui.Control.showDialog(taskd) return True - def unsetEdit(self,vobj,mode): + def unsetEdit(self, vobj, mode): FreeCADGui.Control.closeDialog() return def dumps(self): return None - def loads(self,state): + def loads(self, state): return None class _InvoluteGearTaskPanel: - '''The editmode TaskPanel for InvoluteGear objects''' - def __init__(self,obj,mode): + """The editmode TaskPanel for InvoluteGear objects""" + + def __init__(self, obj, mode): self.obj = obj - self.form=FreeCADGui.PySideUic.loadUi(str(pathlib.Path(__file__).with_suffix(".ui"))) + self.form = FreeCADGui.PySideUic.loadUi(str(pathlib.Path(__file__).with_suffix(".ui"))) self.form.setWindowIcon(QtGui.QIcon(":/icons/PartDesign_InternalExternalGear.svg")) self.assignToolTipsFromPropertyDocs() def assignValue(property_name, fitView=False): """Returns a function that takes a single value and assigns it to the given property""" + def assigner(value): setattr(self.obj, property_name, value) self.obj.Proxy.execute(self.obj) if fitView: FreeCAD.Gui.SendMsgToActiveView("ViewFit") + return assigner def assignIndexAsBool(property_name): """Variant of assignValue that transforms the index of a Yes/No Combobox to a bool.""" assigner = assignValue(property_name) + def transformingAssigner(value): assigner(True if value == 0 else False) + return transformingAssigner self.form.Quantity_Modules.valueChanged.connect(assignValue("Modules", fitView=True)) self.form.Quantity_PressureAngle.valueChanged.connect(assignValue("PressureAngle")) - self.form.spinBox_NumberOfTeeth.valueChanged.connect(assignValue("NumberOfTeeth", fitView=True)) - self.form.comboBox_HighPrecision.currentIndexChanged.connect(assignIndexAsBool("HighPrecision")) - self.form.comboBox_ExternalGear.currentIndexChanged.connect(assignIndexAsBool("ExternalGear")) + self.form.spinBox_NumberOfTeeth.valueChanged.connect( + assignValue("NumberOfTeeth", fitView=True) + ) + self.form.comboBox_HighPrecision.currentIndexChanged.connect( + assignIndexAsBool("HighPrecision") + ) + self.form.comboBox_ExternalGear.currentIndexChanged.connect( + assignIndexAsBool("ExternalGear") + ) self.form.doubleSpinBox_Addendum.valueChanged.connect(assignValue("AddendumCoefficient")) self.form.doubleSpinBox_Dedendum.valueChanged.connect(assignValue("DedendumCoefficient")) - self.form.doubleSpinBox_RootFillet.valueChanged.connect(assignValue("RootFilletCoefficient")) - self.form.doubleSpinBox_ProfileShift.valueChanged.connect(assignValue("ProfileShiftCoefficient")) + self.form.doubleSpinBox_RootFillet.valueChanged.connect( + assignValue("RootFilletCoefficient") + ) + self.form.doubleSpinBox_ProfileShift.valueChanged.connect( + assignValue("ProfileShiftCoefficient") + ) self.update() - if mode == 0: # fresh created + if mode == 0: # fresh created self.obj.Proxy.execute(self.obj) # calculate once FreeCAD.Gui.SendMsgToActiveView("ViewFit") @@ -226,8 +296,14 @@ class _InvoluteGearTaskPanel: assign("ExternalGear", self.form.comboBox_ExternalGear, self.form.label_ExternalGear) assign("AddendumCoefficient", self.form.doubleSpinBox_Addendum, self.form.label_Addendum) assign("DedendumCoefficient", self.form.doubleSpinBox_Dedendum, self.form.label_Dedendum) - assign("RootFilletCoefficient", self.form.doubleSpinBox_RootFillet, self.form.label_RootFillet) - assign("ProfileShiftCoefficient", self.form.doubleSpinBox_ProfileShift, self.form.label_ProfileShift) + assign( + "RootFilletCoefficient", self.form.doubleSpinBox_RootFillet, self.form.label_RootFillet + ) + assign( + "ProfileShiftCoefficient", + self.form.doubleSpinBox_ProfileShift, + self.form.label_ProfileShift, + ) def changeEvent(self, event): if event == QtCore.QEvent.LanguageChange: @@ -235,11 +311,15 @@ class _InvoluteGearTaskPanel: def transferTo(self): "Transfer from the dialog to the object" - self.obj.NumberOfTeeth = self.form.spinBox_NumberOfTeeth.value() - self.obj.Modules = self.form.Quantity_Modules.text() - self.obj.PressureAngle = self.form.Quantity_PressureAngle.text() - self.obj.HighPrecision = True if self.form.comboBox_HighPrecision.currentIndex() == 0 else False - self.obj.ExternalGear = True if self.form.comboBox_ExternalGear.currentIndex() == 0 else False + self.obj.NumberOfTeeth = self.form.spinBox_NumberOfTeeth.value() + self.obj.Modules = self.form.Quantity_Modules.text() + self.obj.PressureAngle = self.form.Quantity_PressureAngle.text() + self.obj.HighPrecision = ( + True if self.form.comboBox_HighPrecision.currentIndex() == 0 else False + ) + self.obj.ExternalGear = ( + True if self.form.comboBox_ExternalGear.currentIndex() == 0 else False + ) self.obj.AddendumCoefficient = self.form.doubleSpinBox_Addendum.value() self.obj.DedendumCoefficient = self.form.doubleSpinBox_Dedendum.value() self.obj.RootFilletCoefficient = self.form.doubleSpinBox_RootFillet.value() @@ -258,15 +338,17 @@ class _InvoluteGearTaskPanel: self.form.doubleSpinBox_ProfileShift.setValue(self.obj.ProfileShiftCoefficient) def getStandardButtons(self): - return QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Apply + return ( + QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Apply + ) - def clicked(self,button): + def clicked(self, button): if button == QtGui.QDialogButtonBox.Apply: self.transferTo() self.obj.Proxy.execute(self.obj) def update(self): - 'fills the widgets' + "fills the widgets" self.transferFrom() def accept(self): diff --git a/src/Mod/PartDesign/PartDesignGlobal.h b/src/Mod/PartDesign/PartDesignGlobal.h index 521ff7f231..bca9ddcdf8 100644 --- a/src/Mod/PartDesign/PartDesignGlobal.h +++ b/src/Mod/PartDesign/PartDesignGlobal.h @@ -29,20 +29,20 @@ // PartDesign #ifndef PartDesignExport -#ifdef PartDesign_EXPORTS -# define PartDesignExport FREECAD_DECL_EXPORT -#else -# define PartDesignExport FREECAD_DECL_IMPORT -#endif +# ifdef PartDesign_EXPORTS +# define PartDesignExport FREECAD_DECL_EXPORT +# else +# define PartDesignExport FREECAD_DECL_IMPORT +# endif #endif // PartDesignGui #ifndef PartDesignGuiExport -#ifdef PartDesignGui_EXPORTS -# define PartDesignGuiExport FREECAD_DECL_EXPORT -#else -# define PartDesignGuiExport FREECAD_DECL_IMPORT -#endif +# ifdef PartDesignGui_EXPORTS +# define PartDesignGuiExport FREECAD_DECL_EXPORT +# else +# define PartDesignGuiExport FREECAD_DECL_IMPORT +# endif #endif -#endif //PARTDESIGN_GLOBAL_H +#endif // PARTDESIGN_GLOBAL_H diff --git a/src/Mod/PartDesign/PartDesignTests/TestActiveObject.py b/src/Mod/PartDesign/PartDesignTests/TestActiveObject.py index c4b83e011d..18a48cbfd4 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestActiveObject.py +++ b/src/Mod/PartDesign/PartDesignTests/TestActiveObject.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2024 Werner Mayer * -#* * -#* This file is part of FreeCAD. * -#* * -#* FreeCAD is free software: you can redistribute it and/or modify it * -#* under the terms of the GNU Lesser General Public License as * -#* published by the Free Software Foundation, either version 2.1 of the * -#* License, or (at your option) any later version. * -#* * -#* FreeCAD 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 * -#* Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Lesser General Public * -#* License along with FreeCAD. If not, see * -#* . * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2024 Werner Mayer * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * FreeCAD 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** import unittest @@ -25,6 +25,8 @@ import FreeCAD import FreeCADGui """ Test active object list """ + + class TestActiveObject(unittest.TestCase): def setUp(self): self.doc = FreeCAD.newDocument("PartDesignTestSketch") @@ -33,26 +35,26 @@ class TestActiveObject(unittest.TestCase): def testPartBody(self): self.doc.openTransaction("Create part") part = self.doc.addObject("App::Part", "Part") - FreeCADGui.activateView('Gui::View3DInventor', True) - FreeCADGui.activeView().setActiveObject('part', part) + FreeCADGui.activateView("Gui::View3DInventor", True) + FreeCADGui.activeView().setActiveObject("part", part) self.doc.commitTransaction() self.doc.openTransaction("Create body") - body = self.doc.addObject('PartDesign::Body', 'Body') + body = self.doc.addObject("PartDesign::Body", "Body") part.addObject(body) - FreeCADGui.activateView('Gui::View3DInventor', True) - FreeCADGui.activeView().setActiveObject('pdbody', body) + FreeCADGui.activateView("Gui::View3DInventor", True) + FreeCADGui.activeView().setActiveObject("pdbody", body) self.doc.commitTransaction() - self.doc.undo() # undo body creation - self.doc.undo() # undo part creation + self.doc.undo() # undo body creation + self.doc.undo() # undo part creation FreeCADGui.updateGui() self.doc.openTransaction("Create body") - body = self.doc.addObject('PartDesign::Body', 'Body') - FreeCADGui.activateView('Gui::View3DInventor', True) - FreeCADGui.activeView().setActiveObject('pdbody', body) + body = self.doc.addObject("PartDesign::Body", "Body") + FreeCADGui.activateView("Gui::View3DInventor", True) + FreeCADGui.activeView().setActiveObject("pdbody", body) self.doc.commitTransaction() FreeCADGui.updateGui() diff --git a/src/Mod/PartDesign/PartDesignTests/TestBoolean.py b/src/Mod/PartDesign/PartDesignTests/TestBoolean.py index bd68415d57..a7bf801ce5 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestBoolean.py +++ b/src/Mod/PartDesign/PartDesignTests/TestBoolean.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest @@ -26,78 +26,91 @@ from pivy import coin App = FreeCAD + class TestBoolean(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestBoolean") def testBooleanFuseCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=10 - self.Box.Width=10 - self.Box.Height=10 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 10 + self.Box.Width = 10 + self.Box.Height = 10 self.Body.addObject(self.Box) self.Doc.recompute() - self.Body001 = self.Doc.addObject('PartDesign::Body','Body001') - self.Box001 = self.Doc.addObject('PartDesign::AdditiveBox','Box001') - self.Box001.Length=10 - self.Box001.Width=10 - self.Box001.Height=10 - self.Box001.Placement.Base = App.Vector(-5,0,0) + self.Body001 = self.Doc.addObject("PartDesign::Body", "Body001") + self.Box001 = self.Doc.addObject("PartDesign::AdditiveBox", "Box001") + self.Box001.Length = 10 + self.Box001.Width = 10 + self.Box001.Height = 10 + self.Box001.Placement.Base = App.Vector(-5, 0, 0) self.Body001.addObject(self.Box001) self.Doc.recompute() - self.BooleanFuse = self.Doc.addObject('PartDesign::Boolean','BooleanFuse') + self.BooleanFuse = self.Doc.addObject("PartDesign::Boolean", "BooleanFuse") self.Body001.addObject(self.BooleanFuse) self.Doc.recompute() - self.BooleanFuse.setObjects([self.Body,]) + self.BooleanFuse.setObjects( + [ + self.Body, + ] + ) self.BooleanFuse.Type = 0 self.Doc.recompute() self.assertAlmostEqual(self.BooleanFuse.Shape.Volume, 1500) def testBooleanCutCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=10 - self.Box.Width=10 - self.Box.Height=10 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 10 + self.Box.Width = 10 + self.Box.Height = 10 self.Body.addObject(self.Box) self.Doc.recompute() - self.Body001 = self.Doc.addObject('PartDesign::Body','Body001') - self.Box001 = self.Doc.addObject('PartDesign::AdditiveBox','Box001') - self.Box001.Length=10 - self.Box001.Width=10 - self.Box001.Height=10 - self.Box001.Placement.Base = App.Vector(-5,0,0) + self.Body001 = self.Doc.addObject("PartDesign::Body", "Body001") + self.Box001 = self.Doc.addObject("PartDesign::AdditiveBox", "Box001") + self.Box001.Length = 10 + self.Box001.Width = 10 + self.Box001.Height = 10 + self.Box001.Placement.Base = App.Vector(-5, 0, 0) self.Body001.addObject(self.Box001) self.Doc.recompute() - self.BooleanCut = self.Doc.addObject('PartDesign::Boolean','BooleanCut') + self.BooleanCut = self.Doc.addObject("PartDesign::Boolean", "BooleanCut") self.Body001.addObject(self.BooleanCut) self.Doc.recompute() - self.BooleanCut.setObjects([self.Body,]) + self.BooleanCut.setObjects( + [ + self.Body, + ] + ) self.BooleanCut.Type = 1 self.Doc.recompute() self.assertAlmostEqual(self.BooleanCut.Shape.Volume, 500) def testBooleanCommonCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=10 - self.Box.Width=10 - self.Box.Height=10 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 10 + self.Box.Width = 10 + self.Box.Height = 10 self.Body.addObject(self.Box) self.Doc.recompute() - self.Body001 = self.Doc.addObject('PartDesign::Body','Body001') - self.Box001 = self.Doc.addObject('PartDesign::AdditiveBox','Box001') - self.Box001.Length=10 - self.Box001.Width=10 - self.Box001.Height=10 - self.Box001.Placement.Base = App.Vector(-5,0,0) + self.Body001 = self.Doc.addObject("PartDesign::Body", "Body001") + self.Box001 = self.Doc.addObject("PartDesign::AdditiveBox", "Box001") + self.Box001.Length = 10 + self.Box001.Width = 10 + self.Box001.Height = 10 + self.Box001.Placement.Base = App.Vector(-5, 0, 0) self.Body001.addObject(self.Box001) self.Doc.recompute() - self.BooleanCommon = self.Doc.addObject('PartDesign::Boolean','BooleanCommon') + self.BooleanCommon = self.Doc.addObject("PartDesign::Boolean", "BooleanCommon") self.Body001.addObject(self.BooleanCommon) self.Doc.recompute() - self.BooleanCommon.setObjects([self.Body,]) + self.BooleanCommon.setObjects( + [ + self.Body, + ] + ) self.BooleanCommon.Type = 2 self.Doc.recompute() self.assertAlmostEqual(self.BooleanCommon.Shape.Volume, 500) @@ -106,24 +119,26 @@ class TestBoolean(unittest.TestCase): if not App.GuiUp: return # Arrange - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=10 - self.Box.Width=10 - self.Box.Height=10 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 10 + self.Box.Width = 10 + self.Box.Height = 10 self.Body.addObject(self.Box) self.Doc.recompute() - self.Body001 = self.Doc.addObject('PartDesign::Body','Body001') - self.Box001 = self.Doc.addObject('PartDesign::AdditiveBox','Box001') - self.Box001.Length=10 - self.Box001.Width=10 - self.Box001.Height=10 - self.Box001.Placement.Base = App.Vector(-5,0,0) + self.Body001 = self.Doc.addObject("PartDesign::Body", "Body001") + self.Box001 = self.Doc.addObject("PartDesign::AdditiveBox", "Box001") + self.Box001.Length = 10 + self.Box001.Width = 10 + self.Box001.Height = 10 + self.Box001.Placement.Base = App.Vector(-5, 0, 0) self.Body001.addObject(self.Box001) - self.Body002 = self.Doc.addObject('PartDesign::Body','Body002') - self.BooleanFuse = self.Doc.addObject('PartDesign::Boolean','BooleanFuse') - self.BooleanFuse.Group = [ self.Body, self.Body001 ] - self.BooleanFuse.ViewObject.Display="Result" # TODO: This is a required redundancy or it doesn't init right + self.Body002 = self.Doc.addObject("PartDesign::Body", "Body002") + self.BooleanFuse = self.Doc.addObject("PartDesign::Boolean", "BooleanFuse") + self.BooleanFuse.Group = [self.Body, self.Body001] + self.BooleanFuse.ViewObject.Display = ( + "Result" # TODO: This is a required redundancy or it doesn't init right + ) self.Body002.addObject(self.BooleanFuse) self.Doc.recompute() # Act @@ -136,9 +151,7 @@ class TestBoolean(unittest.TestCase): App.Gui.Selection.addSelection("", "Body002", "Face14") App.Gui.updateGui() # Assert - self.assertEqual( - len(App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames), 7 - ) + self.assertEqual(len(App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames), 7) self.assertEqual( App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames[0][-8:], ",F.Face2", @@ -163,7 +176,5 @@ class TestBoolean(unittest.TestCase): def tearDown(self): if hasattr(App, "KeepTestDoc") and App.KeepTestDoc: return - #closing doc. + # closing doc. FreeCAD.closeDocument("PartDesignTestBoolean") - - diff --git a/src/Mod/PartDesign/PartDesignTests/TestChamfer.py b/src/Mod/PartDesign/PartDesignTests/TestChamfer.py index 904584bae7..2201942a52 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestChamfer.py +++ b/src/Mod/PartDesign/PartDesignTests/TestChamfer.py @@ -1,66 +1,65 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD + class TestChamfer(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestChamfer") def testChamferCubeToOctahedron(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.Chamfer = self.Doc.addObject("PartDesign::Chamfer","Chamfer") - self.Chamfer.Base = (self.Box, ['Face'+str(i+1) for i in range(6)]) + self.Chamfer = self.Doc.addObject("PartDesign::Chamfer", "Chamfer") + self.Chamfer.Base = (self.Box, ["Face" + str(i + 1) for i in range(6)]) self.Chamfer.Size = 4.999999 self.Body.addObject(self.Chamfer) self.Doc.recompute() self.MajorFaces = [face for face in self.Chamfer.Shape.Faces if face.Area > 1e-3] self.assertEqual(len(self.MajorFaces), 8) - #test UseAllEdges property + # test UseAllEdges property self.Chamfer.UseAllEdges = True - self.Chamfer.Base = (self.Box, ['']) # no subobjects, should still work + self.Chamfer.Base = (self.Box, [""]) # no subobjects, should still work self.Doc.recompute() self.MajorFaces = [face for face in self.Chamfer.Shape.Faces if face.Area > 1e-3] self.assertEqual(len(self.MajorFaces), 8) - self.Chamfer.Base = (self.Box, ['Face50']) # non-existent face, test topo naming resilience + self.Chamfer.Base = (self.Box, ["Face50"]) # non-existent face, test topo naming resilience self.Doc.recompute() self.MajorFaces = [face for face in self.Chamfer.Shape.Faces if face.Area > 1e-3] self.assertEqual(len(self.MajorFaces), 8) self.Chamfer.UseAllEdges = False - self.Chamfer.Base = (self.Box, ['Face1']) + self.Chamfer.Base = (self.Box, ["Face1"]) self.Doc.recompute() self.MajorFaces = [face for face in self.Chamfer.Shape.Faces if face.Area > 1e-3] self.assertEqual(len(self.MajorFaces), 9) - def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestChamfer") # print ("omit closing document for debugging") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestDatum.py b/src/Mod/PartDesign/PartDesignTests/TestDatum.py index de5deb5181..cb6fd16dc9 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestDatum.py +++ b/src/Mod/PartDesign/PartDesignTests/TestDatum.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest @@ -25,58 +25,60 @@ import FreeCAD App = FreeCAD + class TestDatumPoint(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestDatumPoint") def testOriginDatumPoint(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.DatumPoint = self.Doc.addObject('PartDesign::Point','DatumPoint') - self.DatumPoint.AttachmentSupport = [(self.Doc.XY_Plane,'')] - self.DatumPoint.MapMode = 'ObjectOrigin' + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.DatumPoint = self.Doc.addObject("PartDesign::Point", "DatumPoint") + self.DatumPoint.AttachmentSupport = [(self.Doc.XY_Plane, "")] + self.DatumPoint.MapMode = "ObjectOrigin" self.Body.addObject(self.DatumPoint) self.Doc.recompute() self.assertEqual(self.DatumPoint.AttachmentOffset.Base, App.Vector(0)) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestDatumPoint") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") + class TestDatumLine(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestDatumLine") def testXAxisDatumLine(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.DatumLine = self.Doc.addObject('PartDesign::Line','DatumLine') - self.DatumLine.AttachmentSupport = [(self.Doc.XY_Plane,'')] - self.DatumLine.MapMode = 'ObjectX' + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.DatumLine = self.Doc.addObject("PartDesign::Line", "DatumLine") + self.DatumLine.AttachmentSupport = [(self.Doc.XY_Plane, "")] + self.DatumLine.MapMode = "ObjectX" self.Body.addObject(self.DatumLine) self.Doc.recompute() - self.assertNotIn('Invalid', self.DatumLine.State) + self.assertNotIn("Invalid", self.DatumLine.State) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestDatumLine") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") + class TestDatumPlane(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestDatumPlane") def testXYDatumPlane(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.DatumPlane = self.Doc.addObject('PartDesign::Plane','DatumPlane') - self.DatumPlane.AttachmentSupport = [(self.Doc.XY_Plane,'')] - self.DatumPlane.MapMode = 'FlatFace' + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.DatumPlane = self.Doc.addObject("PartDesign::Plane", "DatumPlane") + self.DatumPlane.AttachmentSupport = [(self.Doc.XY_Plane, "")] + self.DatumPlane.MapMode = "FlatFace" self.Body.addObject(self.DatumPlane) self.Doc.recompute() self.DatumPlaneNormal = self.DatumPlane.Shape.Surface.Axis - self.assertEqual(abs(self.DatumPlaneNormal.dot(App.Vector(0,0,1))), 1) + self.assertEqual(abs(self.DatumPlaneNormal.dot(App.Vector(0, 0, 1))), 1) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestDatumPlane") - #print ("omit closing document for debugging") - + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestDraft.py b/src/Mod/PartDesign/PartDesignTests/TestDraft.py index fd495f5d4a..160c639de5 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestDraft.py +++ b/src/Mod/PartDesign/PartDesignTests/TestDraft.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest @@ -25,6 +25,7 @@ import FreeCAD App = FreeCAD + class TestDraft(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestDraft") @@ -33,46 +34,50 @@ class TestDraft(unittest.TestCase): # fix: create datum plane on YZ. create datum line on Z + 10i # find top face by first making list comprehension of Z-normal faces # and then find which has the higher center of mass Z-value - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.DatumPlane = self.Doc.addObject('PartDesign::Plane','DatumPlane') - self.DatumPlane.AttachmentSupport = [(self.Doc.YZ_Plane,'')] - self.DatumPlane.MapMode = 'FlatFace' + self.DatumPlane = self.Doc.addObject("PartDesign::Plane", "DatumPlane") + self.DatumPlane.AttachmentSupport = [(self.Doc.YZ_Plane, "")] + self.DatumPlane.MapMode = "FlatFace" self.Body.addObject(self.DatumPlane) self.Doc.recompute() - self.DatumLine = self.Doc.addObject('PartDesign::Line','DatumLine') - self.DatumLine.AttachmentSupport = [(self.Doc.X_Axis,'')] - self.DatumLine.MapMode = 'TwoPointLine' + self.DatumLine = self.Doc.addObject("PartDesign::Line", "DatumLine") + self.DatumLine.AttachmentSupport = [(self.Doc.X_Axis, "")] + self.DatumLine.MapMode = "TwoPointLine" self.Body.addObject(self.DatumLine) self.Doc.recompute() - self.Draft = self.Doc.addObject("PartDesign::Draft","Draft") + self.Draft = self.Doc.addObject("PartDesign::Draft", "Draft") # Draft.Base needs to be top face self.Faces = self.Box.Shape.Faces # Grab the two faces with Z-normals and find the higher one - self.ZFaceIndexes = [i for i in range(len(self.Faces)) if self.Faces[i].Surface.Axis == App.Vector(0,0,1)] - if self.Faces[self.ZFaceIndexes[0]].CenterOfMass.z > self.Faces[self.ZFaceIndexes[1]].CenterOfMass.z: + self.ZFaceIndexes = [ + i for i in range(len(self.Faces)) if self.Faces[i].Surface.Axis == App.Vector(0, 0, 1) + ] + if ( + self.Faces[self.ZFaceIndexes[0]].CenterOfMass.z + > self.Faces[self.ZFaceIndexes[1]].CenterOfMass.z + ): self.TopFaceIndex = self.ZFaceIndexes[0] else: self.TopFaceIndex = self.ZFaceIndexes[1] - self.Draft.Base = (self.Box, ["Face"+str(self.TopFaceIndex+1)]) - self.Draft.NeutralPlane = (self.DatumPlane, ['']) - self.Draft.PullDirection = (self.DatumLine, ['']) + self.Draft.Base = (self.Box, ["Face" + str(self.TopFaceIndex + 1)]) + self.Draft.NeutralPlane = (self.DatumPlane, [""]) + self.Draft.PullDirection = (self.DatumLine, [""]) self.Draft.Angle = 45.0 self.Draft.Reversed = 1 self.Body.addObject(self.Draft) self.Doc.recompute() - if 'Invalid' in self.Draft.State: + if "Invalid" in self.Draft.State: self.Draft.Reversed = 0 self.Doc.recompute() self.assertAlmostEqual(self.Draft.Shape.Volume, 1500) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestDraft") # print ("omit closing document for debugging") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestFillet.py b/src/Mod/PartDesign/PartDesignTests/TestFillet.py index 5ec5da3c86..5b10a7852b 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestFillet.py +++ b/src/Mod/PartDesign/PartDesignTests/TestFillet.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** from __future__ import division from math import pi @@ -25,39 +25,39 @@ import unittest import FreeCAD + class TestFillet(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestFillet") def testFilletCubeToSphere(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.Fillet = self.Doc.addObject("PartDesign::Fillet","Fillet") - self.Fillet.Base = (self.Box, ['Face'+str(i+1) for i in range(6)]) + self.Fillet = self.Doc.addObject("PartDesign::Fillet", "Fillet") + self.Fillet.Base = (self.Box, ["Face" + str(i + 1) for i in range(6)]) self.Fillet.Radius = 4.999999 self.Body.addObject(self.Fillet) self.Doc.recompute() - self.assertAlmostEqual(self.Fillet.Shape.Volume, 4/3 * pi * 5**3, places=3) - #test UseAllEdges property + self.assertAlmostEqual(self.Fillet.Shape.Volume, 4 / 3 * pi * 5**3, places=3) + # test UseAllEdges property self.Fillet.UseAllEdges = True - self.Fillet.Base = (self.Box, ['']) # no subobjects, should still work + self.Fillet.Base = (self.Box, [""]) # no subobjects, should still work self.Doc.recompute() - self.assertAlmostEqual(self.Fillet.Shape.Volume, 4/3 * pi * 5**3, places=3) - self.Fillet.Base = (self.Box, ['Face50']) # non-existent face, topo naming resilience + self.assertAlmostEqual(self.Fillet.Shape.Volume, 4 / 3 * pi * 5**3, places=3) + self.Fillet.Base = (self.Box, ["Face50"]) # non-existent face, topo naming resilience self.Doc.recompute() - self.assertAlmostEqual(self.Fillet.Shape.Volume, 4/3 * pi * 5**3, places=3) + self.assertAlmostEqual(self.Fillet.Shape.Volume, 4 / 3 * pi * 5**3, places=3) self.Fillet.UseAllEdges = False - self.Fillet.Base = (self.Box, ['Face1']) + self.Fillet.Base = (self.Box, ["Face1"]) self.Doc.recompute() - self.assertNotAlmostEqual(self.Fillet.Shape.Volume, 4/3 * pi * 5**3, places=3) + self.assertNotAlmostEqual(self.Fillet.Shape.Volume, 4 / 3 * pi * 5**3, places=3) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestFillet") # print ("omit closing document for debugging") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestHelix.py b/src/Mod/PartDesign/PartDesignTests/TestHelix.py index 1f4a816ace..7d44dc38d4 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestHelix.py +++ b/src/Mod/PartDesign/PartDesignTests/TestHelix.py @@ -1,24 +1,24 @@ -#*************************************************************************** -#* Copyright (c) 2023 Werner Mayer * -#* Copyright (c) 2023 * -#* * -#* This file is part of FreeCAD. * -#* * -#* FreeCAD is free software: you can redistribute it and/or modify it * -#* under the terms of the GNU Lesser General Public License as * -#* published by the Free Software Foundation, either version 2.1 of the * -#* License, or (at your option) any later version. * -#* * -#* FreeCAD 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 * -#* Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Lesser General Public * -#* License along with FreeCAD. If not, see * -#* . * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2023 Werner Mayer * +# * Copyright (c) 2023 * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * FreeCAD 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** from math import pi import unittest @@ -30,16 +30,19 @@ import Sketcher import TestSketcherApp """ Test various helixes """ + + class TestHelix(unittest.TestCase): - """ Test various helixes """ + """Test various helixes""" + def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestHelix") def testHelicalTubeCase(self): - body = self.Doc.addObject('PartDesign::Body','Body') - sketch = body.newObject('Sketcher::SketchObject','Sketch') - sketch.AttachmentSupport = (self.Doc.getObject('XY_Plane'),['']) - sketch.MapMode = 'FlatFace' + body = self.Doc.addObject("PartDesign::Body", "Body") + sketch = body.newObject("Sketcher::SketchObject", "Sketch") + sketch.AttachmentSupport = (self.Doc.getObject("XY_Plane"), [""]) + sketch.MapMode = "FlatFace" geoList = [] geoList.append(Part.Circle(Base.Vector(-40.0, 0.0, 0.0), Base.Vector(0.0, 0.0, 1.0), 7.5)) @@ -47,13 +50,13 @@ class TestHelix(unittest.TestCase): sketch.addGeometry(geoList, False) del geoList - sketch.addConstraint(Sketcher.Constraint('PointOnObject', 0, 3, -1)) - sketch.addConstraint(Sketcher.Constraint('Coincident', 1, 3, 0, 3)) + sketch.addConstraint(Sketcher.Constraint("PointOnObject", 0, 3, -1)) + sketch.addConstraint(Sketcher.Constraint("Coincident", 1, 3, 0, 3)) self.Doc.recompute() - helix = body.newObject('PartDesign::AdditiveHelix','AdditiveHelix') + helix = body.newObject("PartDesign::AdditiveHelix", "AdditiveHelix") helix.Profile = sketch - helix.ReferenceAxis = (sketch, ['V_Axis']) + helix.ReferenceAxis = (sketch, ["V_Axis"]) helix.Mode = 0 helix.Pitch = 35 helix.Height = 100 @@ -66,42 +69,44 @@ class TestHelix(unittest.TestCase): self.Doc.recompute() self.assertEqual(len(helix.Shape.Solids), 1) - def testCircleQ1(self): - """ Test helix based on circle in Quadrant 1 """ - body = self.Doc.addObject('PartDesign::Body','Body') - profileSketch = self.Doc.addObject('Sketcher::SketchObject', 'ProfileSketch') + """Test helix based on circle in Quadrant 1""" + body = self.Doc.addObject("PartDesign::Body", "Body") + profileSketch = self.Doc.addObject("Sketcher::SketchObject", "ProfileSketch") body.addObject(profileSketch) TestSketcherApp.CreateCircleSketch(profileSketch, (2, 0), 1) self.Doc.recompute() - helix = self.Doc.addObject("PartDesign::AdditiveHelix","AdditiveHelix") + helix = self.Doc.addObject("PartDesign::AdditiveHelix", "AdditiveHelix") body.addObject(helix) helix.Profile = profileSketch - helix.ReferenceAxis = (profileSketch,"V_Axis") - helix.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0), - FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0), - FreeCAD.Vector(0,0,0)) + helix.ReferenceAxis = (profileSketch, "V_Axis") + helix.Placement = FreeCAD.Placement( + FreeCAD.Vector(0, 0, 0), + FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0), + FreeCAD.Vector(0, 0, 0), + ) helix.Pitch = 3 helix.Height = 9 helix.Turns = 2 helix.Angle = 0 helix.Mode = 1 self.Doc.recompute() - self.assertAlmostEqual(helix.Shape.Volume, 78.957,places=3) + self.assertAlmostEqual(helix.Shape.Volume, 78.957, places=3) helix.Angle = 25 self.Doc.recompute() - self.assertAlmostEqual(helix.Shape.Volume, 134.17,places=2) + self.assertAlmostEqual(helix.Shape.Volume, 134.17, places=2) - profileSketch.addGeometry(Part.Circle(FreeCAD.Vector(2, 0, 0), FreeCAD.Vector(0,0,1), 0.5) ) + profileSketch.addGeometry( + Part.Circle(FreeCAD.Vector(2, 0, 0), FreeCAD.Vector(0, 0, 1), 0.5) + ) self.Doc.recompute() - self.assertAlmostEqual(helix.Shape.Volume, 100.63,places=2) - + self.assertAlmostEqual(helix.Shape.Volume, 100.63, places=2) def testRectangle(self): - """ Test helix based on a rectangle """ - body = self.Doc.addObject('PartDesign::Body','GearBody') - gearSketch = self.Doc.addObject('Sketcher::SketchObject', 'GearSketch') + """Test helix based on a rectangle""" + body = self.Doc.addObject("PartDesign::Body", "GearBody") + gearSketch = self.Doc.addObject("Sketcher::SketchObject", "GearSketch") body.addObject(gearSketch) TestSketcherApp.CreateRectangleSketch(gearSketch, (0, 0), (5, 5)) self.Doc.recompute() @@ -109,11 +114,15 @@ class TestHelix(unittest.TestCase): # xz_plane = body.Origin.OriginFeatures[4] # coneSketch.AttachmentSupport = xz_plane # coneSketch.MapMode = 'FlatFace' - helix = self.Doc.addObject("PartDesign::AdditiveHelix","AdditiveHelix") + helix = self.Doc.addObject("PartDesign::AdditiveHelix", "AdditiveHelix") body.addObject(helix) helix.Profile = gearSketch - helix.ReferenceAxis = (gearSketch,"V_Axis") - helix.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0), FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0), FreeCAD.Vector(0,0,0)) + helix.ReferenceAxis = (gearSketch, "V_Axis") + helix.Placement = FreeCAD.Placement( + FreeCAD.Vector(0, 0, 0), + FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0), + FreeCAD.Vector(0, 0, 0), + ) helix.Pitch = 50 helix.Height = 150 @@ -122,7 +131,7 @@ class TestHelix(unittest.TestCase): helix.Mode = 0 self.Doc.recompute() bbox = helix.Shape.BoundBox - self.assertAlmostEqual(bbox.YMin,0) + self.assertAlmostEqual(bbox.YMin, 0) # Computed exact value # with r = radius, l = length of square, t = turns # pi * r**2 * l * t @@ -130,157 +139,205 @@ class TestHelix(unittest.TestCase): self.assertAlmostEqual(helix.Shape.Volume, expected, places=2) def testGiantHelix(self): - """ Test giant helix """ - _OCC_VERSION=[ int(v) for v in Part.OCC_VERSION.split('.') if v.isnumeric() ] - if _OCC_VERSION[0]>7 or (_OCC_VERSION[0]==7 and _OCC_VERSION[1]>3): - mine=-1 - maxe=10 + """Test giant helix""" + _OCC_VERSION = [int(v) for v in Part.OCC_VERSION.split(".") if v.isnumeric()] + if _OCC_VERSION[0] > 7 or (_OCC_VERSION[0] == 7 and _OCC_VERSION[1] > 3): + mine = -1 + maxe = 10 else: - mine=-1 - maxe=9 - for iexponent in range(mine,maxe): + mine = -1 + maxe = 9 + for iexponent in range(mine, maxe): exponent = float(iexponent) - body = self.Doc.addObject('PartDesign::Body','GearBody') - gearSketch = self.Doc.addObject('Sketcher::SketchObject', 'GearSketch') + body = self.Doc.addObject("PartDesign::Body", "GearBody") + gearSketch = self.Doc.addObject("Sketcher::SketchObject", "GearSketch") body.addObject(gearSketch) - TestSketcherApp.CreateRectangleSketch(gearSketch, (10*(10**exponent), 0), (1*(10**exponent), 1*(10**exponent))) + TestSketcherApp.CreateRectangleSketch( + gearSketch, (10 * (10**exponent), 0), (1 * (10**exponent), 1 * (10**exponent)) + ) xz_plane = body.Origin.OriginFeatures[4] gearSketch.AttachmentSupport = xz_plane - gearSketch.MapMode = 'FlatFace' + gearSketch.MapMode = "FlatFace" self.Doc.recompute() - helix = self.Doc.addObject("PartDesign::AdditiveHelix","AdditiveHelix") + helix = self.Doc.addObject("PartDesign::AdditiveHelix", "AdditiveHelix") body.addObject(helix) helix.Profile = gearSketch - helix.ReferenceAxis = (gearSketch,"V_Axis") - helix.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0), FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0), FreeCAD.Vector(0,0,0)) + helix.ReferenceAxis = (gearSketch, "V_Axis") + helix.Placement = FreeCAD.Placement( + FreeCAD.Vector(0, 0, 0), + FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0), + FreeCAD.Vector(0, 0, 0), + ) - helix.Pitch = 2*(10**exponent) + helix.Pitch = 2 * (10**exponent) helix.Turns = 2 - helix.Height = helix.Turns* helix.Pitch + helix.Height = helix.Turns * helix.Pitch helix.Angle = 0 helix.Mode = 0 self.Doc.recompute() self.assertTrue(helix.Shape.isValid()) bbox = helix.Shape.BoundBox - self.assertAlmostEqual(bbox.ZMin/((10**exponent)**3),0,places=4) + self.assertAlmostEqual(bbox.ZMin / ((10**exponent) ** 3), 0, places=4) # Computed exact value # with r = radius, l = length of square, t = turns # pi * r**2 * l * t - expected = pi * ( ((11*(10**exponent))**2) - ((10*(10**exponent))**2) ) * 1*(10**exponent) * helix.Turns - self.assertAlmostEqual(helix.Shape.Volume/ ((10**exponent)**3),expected/ ((10**exponent)**3),places=2) + expected = ( + pi + * (((11 * (10**exponent)) ** 2) - ((10 * (10**exponent)) ** 2)) + * 1 + * (10**exponent) + * helix.Turns + ) + self.assertAlmostEqual( + helix.Shape.Volume / ((10**exponent) ** 3), + expected / ((10**exponent) ** 3), + places=2, + ) def testGiantHelixAdditive(self): - """ Test giant helix added to Cylinder """ - _OCC_VERSION=[ int(v) for v in Part.OCC_VERSION.split('.') if v.isnumeric() ] - if _OCC_VERSION[0]>7 or (_OCC_VERSION[0]==7 and _OCC_VERSION[1]>3): - mine=-1 - maxe=8 + """Test giant helix added to Cylinder""" + _OCC_VERSION = [int(v) for v in Part.OCC_VERSION.split(".") if v.isnumeric()] + if _OCC_VERSION[0] > 7 or (_OCC_VERSION[0] == 7 and _OCC_VERSION[1] > 3): + mine = -1 + maxe = 8 else: - mine=-1 - maxe=6 - for iexponent in range(mine,maxe): + mine = -1 + maxe = 6 + for iexponent in range(mine, maxe): exponent = float(iexponent) - body = self.Doc.addObject('PartDesign::Body','GearBody') - gearSketch = self.Doc.addObject('Sketcher::SketchObject', 'GearSketch') + body = self.Doc.addObject("PartDesign::Body", "GearBody") + gearSketch = self.Doc.addObject("Sketcher::SketchObject", "GearSketch") body.addObject(gearSketch) - TestSketcherApp.CreateRectangleSketch(gearSketch, (10*(10**exponent), 0), (1*(10**exponent), 1*(10**exponent))) + TestSketcherApp.CreateRectangleSketch( + gearSketch, (10 * (10**exponent), 0), (1 * (10**exponent), 1 * (10**exponent)) + ) xz_plane = body.Origin.OriginFeatures[4] gearSketch.AttachmentSupport = xz_plane - gearSketch.MapMode = 'FlatFace' + gearSketch.MapMode = "FlatFace" self.Doc.recompute() - cylinder = self.Doc.addObject('PartDesign::AdditiveCylinder','Cylinder') - cylinder.Radius = 10*(10**exponent) - cylinder.Height = 8*(10**exponent) + cylinder = self.Doc.addObject("PartDesign::AdditiveCylinder", "Cylinder") + cylinder.Radius = 10 * (10**exponent) + cylinder.Height = 8 * (10**exponent) cylinder.Angle = 360 body.addObject(cylinder) self.Doc.recompute() - helix = self.Doc.addObject("PartDesign::AdditiveHelix","AdditiveHelix") + helix = self.Doc.addObject("PartDesign::AdditiveHelix", "AdditiveHelix") body.addObject(helix) helix.Profile = gearSketch - helix.ReferenceAxis = (gearSketch,"V_Axis") - helix.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0), FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0), FreeCAD.Vector(0,0,0)) + helix.ReferenceAxis = (gearSketch, "V_Axis") + helix.Placement = FreeCAD.Placement( + FreeCAD.Vector(0, 0, 0), + FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0), + FreeCAD.Vector(0, 0, 0), + ) - helix.Pitch = 2*(10**exponent) - helix.Turns = 2.5 # workaround for OCCT bug with very large helices - full turns truncate the cylinder due to seam alignment - helix.Height = helix.Turns* helix.Pitch + helix.Pitch = 2 * (10**exponent) + helix.Turns = 2.5 # workaround for OCCT bug with very large helices - full turns truncate the cylinder due to seam alignment + helix.Height = helix.Turns * helix.Pitch helix.Angle = 0 helix.Mode = 0 self.Doc.recompute() self.assertTrue(helix.Shape.isValid()) bbox = helix.Shape.BoundBox - self.assertAlmostEqual(bbox.ZMin/((10**exponent)**3),0,places=4) + self.assertAlmostEqual(bbox.ZMin / ((10**exponent) ** 3), 0, places=4) # Computed exact value # with r = radius, l = length of square, t = turns # pi * r**2 * l * t - cyl = pi * ((10*(10**exponent))**2) * 8*(10**exponent) - expected = cyl + (pi * ( ((11*(10**exponent))**2) - ((10*(10**exponent))**2) ) * 1*(10**exponent) * helix.Turns ) - self.assertAlmostEqual(helix.Shape.Volume/ ((10**exponent)**3),expected/ ((10**exponent)**3),places=2) + cyl = pi * ((10 * (10**exponent)) ** 2) * 8 * (10**exponent) + expected = cyl + ( + pi + * (((11 * (10**exponent)) ** 2) - ((10 * (10**exponent)) ** 2)) + * 1 + * (10**exponent) + * helix.Turns + ) + self.assertAlmostEqual( + helix.Shape.Volume / ((10**exponent) ** 3), + expected / ((10**exponent) ** 3), + places=2, + ) def testGiantHelixSubtractive(self): - """ Test giant helix subtracted from Cylinder """ - _OCC_VERSION=[ int(v) for v in Part.OCC_VERSION.split('.') if v.isnumeric() ] - if _OCC_VERSION[0]>7 or (_OCC_VERSION[0]==7 and _OCC_VERSION[1]>3): - mine=-1 - maxe=8 + """Test giant helix subtracted from Cylinder""" + _OCC_VERSION = [int(v) for v in Part.OCC_VERSION.split(".") if v.isnumeric()] + if _OCC_VERSION[0] > 7 or (_OCC_VERSION[0] == 7 and _OCC_VERSION[1] > 3): + mine = -1 + maxe = 8 else: - mine=-1 - maxe=6 - for iexponent in range(mine,maxe): + mine = -1 + maxe = 6 + for iexponent in range(mine, maxe): exponent = float(iexponent) - body = self.Doc.addObject('PartDesign::Body','GearBody') - gearSketch = self.Doc.addObject('Sketcher::SketchObject', 'GearSketch') + body = self.Doc.addObject("PartDesign::Body", "GearBody") + gearSketch = self.Doc.addObject("Sketcher::SketchObject", "GearSketch") body.addObject(gearSketch) - TestSketcherApp.CreateRectangleSketch(gearSketch, (10*(10**exponent), 0), (1*(10**exponent), 1*(10**exponent))) + TestSketcherApp.CreateRectangleSketch( + gearSketch, (10 * (10**exponent), 0), (1 * (10**exponent), 1 * (10**exponent)) + ) xz_plane = body.Origin.OriginFeatures[4] gearSketch.AttachmentSupport = xz_plane - gearSketch.MapMode = 'FlatFace' + gearSketch.MapMode = "FlatFace" self.Doc.recompute() - cylinder = self.Doc.addObject('PartDesign::AdditiveCylinder','Cylinder') - cylinder.Radius = 11*(10**exponent) - cylinder.Height = 8*(10**exponent) + cylinder = self.Doc.addObject("PartDesign::AdditiveCylinder", "Cylinder") + cylinder.Radius = 11 * (10**exponent) + cylinder.Height = 8 * (10**exponent) cylinder.Angle = 360 body.addObject(cylinder) self.Doc.recompute() - helix = self.Doc.addObject("PartDesign::SubtractiveHelix","SubtractiveHelix") + helix = self.Doc.addObject("PartDesign::SubtractiveHelix", "SubtractiveHelix") body.addObject(helix) helix.Profile = gearSketch - helix.ReferenceAxis = (gearSketch,"V_Axis") - helix.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0), FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0), FreeCAD.Vector(0,0,0)) + helix.ReferenceAxis = (gearSketch, "V_Axis") + helix.Placement = FreeCAD.Placement( + FreeCAD.Vector(0, 0, 0), + FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0), + FreeCAD.Vector(0, 0, 0), + ) - helix.Pitch = 2*(10**exponent) - helix.Turns = 2.5 # workaround for OCCT bug with very large helices - full turns truncate the cylinder due to seam alignment - helix.Height = helix.Turns* helix.Pitch + helix.Pitch = 2 * (10**exponent) + helix.Turns = 2.5 # workaround for OCCT bug with very large helices - full turns truncate the cylinder due to seam alignment + helix.Height = helix.Turns * helix.Pitch helix.Angle = 0 helix.Mode = 0 self.Doc.recompute() self.assertTrue(helix.Shape.isValid()) bbox = helix.Shape.BoundBox - self.assertAlmostEqual(bbox.ZMin/((10**exponent)**3),0,places=4) + self.assertAlmostEqual(bbox.ZMin / ((10**exponent) ** 3), 0, places=4) # Computed exact value # with r = radius, l = length of square, t = turns # pi * r**2 * l * t - cyl = pi * ((11*(10**exponent))**2) * 8*(10**exponent) - expected = cyl - (pi * ( ((11*(10**exponent))**2) - ((10*(10**exponent))**2) ) * 1*(10**exponent) * helix.Turns ) - self.assertAlmostEqual(helix.Shape.Volume/ ((10**exponent)**3),expected/ ((10**exponent)**3),places=2) + cyl = pi * ((11 * (10**exponent)) ** 2) * 8 * (10**exponent) + expected = cyl - ( + pi + * (((11 * (10**exponent)) ** 2) - ((10 * (10**exponent)) ** 2)) + * 1 + * (10**exponent) + * helix.Turns + ) + self.assertAlmostEqual( + helix.Shape.Volume / ((10**exponent) ** 3), + expected / ((10**exponent) ** 3), + places=2, + ) def testCone(self): - """ Test helix following a cone """ - body = self.Doc.addObject('PartDesign::Body','ConeBody') - coneSketch = self.Doc.addObject('Sketcher::SketchObject', 'ConeSketch') + """Test helix following a cone""" + body = self.Doc.addObject("PartDesign::Body", "ConeBody") + coneSketch = self.Doc.addObject("Sketcher::SketchObject", "ConeSketch") body.addObject(coneSketch) geoList = [] - geoList.append(Part.LineSegment(FreeCAD.Vector(-5, -5, 0), FreeCAD.Vector(-3, 0, 0)) ) - geoList.append(Part.LineSegment(FreeCAD.Vector(-3, 0, 0), FreeCAD.Vector(-2, 0, 0)) ) - geoList.append(Part.LineSegment(FreeCAD.Vector(-2, 0, 0), FreeCAD.Vector(-4, -5, 0)) ) + geoList.append(Part.LineSegment(FreeCAD.Vector(-5, -5, 0), FreeCAD.Vector(-3, 0, 0))) + geoList.append(Part.LineSegment(FreeCAD.Vector(-3, 0, 0), FreeCAD.Vector(-2, 0, 0))) + geoList.append(Part.LineSegment(FreeCAD.Vector(-2, 0, 0), FreeCAD.Vector(-4, -5, 0))) geoList.append(Part.LineSegment(FreeCAD.Vector(-4, -5, 0), FreeCAD.Vector(-5, -5, 0))) (l1, l2, l3, l4) = coneSketch.addGeometry(geoList) @@ -290,7 +347,9 @@ class TestHelix(unittest.TestCase): conList.append(Sketcher.Constraint("Coincident", 2, 2, 3, 1)) conList.append(Sketcher.Constraint("Coincident", 3, 2, 0, 1)) conList.append(Sketcher.Constraint("Horizontal", 1)) - conList.append(Sketcher.Constraint("Angle", l3, 1, -2, 2, FreeCAD.Units.Quantity("30.000000 deg"))) + conList.append( + Sketcher.Constraint("Angle", l3, 1, -2, 2, FreeCAD.Units.Quantity("30.000000 deg")) + ) conList.append(Sketcher.Constraint("DistanceX", 1, 2, -5)) conList.append(Sketcher.Constraint("DistanceY", 1, 2, 0)) conList.append(Sketcher.Constraint("Equal", 0, 2)) @@ -301,12 +360,16 @@ class TestHelix(unittest.TestCase): xz_plane = body.Origin.OriginFeatures[4] coneSketch.AttachmentSupport = xz_plane - coneSketch.MapMode = 'FlatFace' - helix = self.Doc.addObject("PartDesign::AdditiveHelix","AdditiveHelix") + coneSketch.MapMode = "FlatFace" + helix = self.Doc.addObject("PartDesign::AdditiveHelix", "AdditiveHelix") body.addObject(helix) helix.Profile = coneSketch - helix.ReferenceAxis = (coneSketch,"V_Axis") - helix.Placement = FreeCAD.Placement(FreeCAD.Vector(0,0,0), FreeCAD.Rotation(FreeCAD.Vector(0,0,1),0), FreeCAD.Vector(0,0,0)) + helix.ReferenceAxis = (coneSketch, "V_Axis") + helix.Placement = FreeCAD.Placement( + FreeCAD.Vector(0, 0, 0), + FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), 0), + FreeCAD.Vector(0, 0, 0), + ) helix.Pitch = 50 helix.Height = 110 @@ -315,12 +378,12 @@ class TestHelix(unittest.TestCase): helix.Mode = 0 helix.Reversed = True self.Doc.recompute() - self.assertAlmostEqual(helix.Shape.Volume/1e5, 3.8828,places=4) + self.assertAlmostEqual(helix.Shape.Volume / 1e5, 3.8828, places=4) def testNegativeCone(self): - """ Test helix following a cone with a negative angle """ - body = self.Doc.addObject('PartDesign::Body','ConeBody') - coneSketch = self.Doc.addObject('Sketcher::SketchObject', 'ConeSketch') + """Test helix following a cone with a negative angle""" + body = self.Doc.addObject("PartDesign::Body", "ConeBody") + coneSketch = self.Doc.addObject("Sketcher::SketchObject", "ConeSketch") body.addObject(coneSketch) geoList = [] @@ -347,7 +410,7 @@ class TestHelix(unittest.TestCase): xz_plane = body.Origin.OriginFeatures[4] coneSketch.AttachmentSupport = xz_plane - coneSketch.MapMode = 'FlatFace' + coneSketch.MapMode = "FlatFace" helix = self.Doc.addObject("PartDesign::AdditiveHelix", "AdditiveHelix") body.addObject(helix) helix.Profile = coneSketch @@ -359,8 +422,7 @@ class TestHelix(unittest.TestCase): helix.Mode = 0 helix.Reversed = False self.Doc.recompute() - self.assertAlmostEqual(helix.Shape.Volume/1e5, 6.0643, places=4) + self.assertAlmostEqual(helix.Shape.Volume / 1e5, 6.0643, places=4) def tearDown(self): FreeCAD.closeDocument("PartDesignTestHelix") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestHole.py b/src/Mod/PartDesign/PartDesignTests/TestHole.py index 37b0aa443b..254cc0fd55 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestHole.py +++ b/src/Mod/PartDesign/PartDesignTests/TestHole.py @@ -1,4 +1,4 @@ -#************************************************************************** +# ************************************************************************** # Copyright (c) 2017 Kurt Kremitzki * # * # This file is part of the FreeCAD CAx development system. * @@ -18,7 +18,7 @@ # License along with FreeCAD; if not, write to the Free Software * # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # USA * -#************************************************************************** +# ************************************************************************** from math import pi import unittest @@ -27,22 +27,23 @@ import TestSketcherApp App = FreeCAD + class TestHole(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestHole") - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=10 - self.Box.Width=10 - self.Box.Height=10 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 10 + self.Box.Width = 10 + self.Box.Height = 10 self.Body.addObject(self.Box) self.Doc.recompute() - self.HoleSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchHole') - self.HoleSketch.AttachmentSupport = (self.Doc.XY_Plane, ['']) - self.HoleSketch.MapMode = 'FlatFace' + self.HoleSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchHole") + self.HoleSketch.AttachmentSupport = (self.Doc.XY_Plane, [""]) + self.HoleSketch.MapMode = "FlatFace" self.HoleSketch.MapReversed = True self.Body.addObject(self.HoleSketch) - TestSketcherApp.CreateCircleSketch(self.HoleSketch, (-5, 5), 1) + TestSketcherApp.CreateCircleSketch(self.HoleSketch, (-5, 5), 1) self.Doc.recompute() self.Hole = self.Doc.addObject("PartDesign::Hole", "Hole") self.Hole.Profile = self.HoleSketch @@ -55,13 +56,13 @@ class TestHole(unittest.TestCase): # self.Hole.DrillPointAngle = 118.000000 # self.Hole.TaperedAngle = 90 self.Hole.ThreadType = 0 - self.Hole.HoleCutType = 0 # 1 = Counterbore, 2 = Countersink + self.Hole.HoleCutType = 0 # 1 = Counterbore, 2 = Countersink # self.Hole.HoleCutDiameter = 5 # self.Hole.HoleCutCountersinkAngle = 90 # self.Hole.HoleCutDepth = 2 # Counterbore - self.Hole.DepthType = 0 # 1 = Through all - self.Hole.DrillPoint = 0 # 1 = Angled - self.Hole.Tapered = 0 # On/off + self.Hole.DepthType = 0 # 1 = Through all + self.Hole.DrillPoint = 0 # 1 = Angled + self.Hole.Tapered = 0 # On/off self.Doc.recompute() self.assertAlmostEqual(self.Hole.Shape.Volume, 10**3 - pi * 3**2 * 10) @@ -118,19 +119,19 @@ class TestHole(unittest.TestCase): def testNoRefineHole(self): # Add a second box to get a shape with more faces - self.Box2 = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box2.Length=10 - self.Box2.Width=10 - self.Box2.Height=10 - self.Box2.AttacherEngine = u"Engine 3D" + self.Box2 = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box2.Length = 10 + self.Box2.Width = 10 + self.Box2.Height = 10 + self.Box2.AttacherEngine = "Engine 3D" self.Box2.AttachmentOffset = App.Placement( App.Vector(1.0000000000, 0.0000000000, 0.0000000000), App.Rotation(0.0000000000, 0.0000000000, 0.0000000000), ) self.Box2.MapReversed = False - self.Box2.AttachmentSupport = self.Doc.getObject('XY_Plane') + self.Box2.AttachmentSupport = self.Doc.getObject("XY_Plane") self.Box2.MapPathParameter = 0.000000 - self.Box2.MapMode = 'FlatFace' + self.Box2.MapMode = "FlatFace" # Set the Refine option to False, otherwise adding the second box would be useless self.Box2.Refine = False @@ -139,7 +140,7 @@ class TestHole(unittest.TestCase): # Move the Hole on top of the Body self.Body.removeObject(self.Hole) - self.Body.insertObject(self.Hole,self.Box2, True) + self.Body.insertObject(self.Hole, self.Box2, True) self.Body.Tip = self.Hole self.Hole.Diameter = 6 self.Hole.Depth = 10 @@ -157,19 +158,19 @@ class TestHole(unittest.TestCase): def testRefineHole(self): # Add a second box to get a shape with more faces - self.Box2 = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box2.Length=10 - self.Box2.Width=10 - self.Box2.Height=10 - self.Box2.AttacherEngine = u"Engine 3D" + self.Box2 = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box2.Length = 10 + self.Box2.Width = 10 + self.Box2.Height = 10 + self.Box2.AttacherEngine = "Engine 3D" self.Box2.AttachmentOffset = App.Placement( App.Vector(1.0000000000, 0.0000000000, 0.0000000000), App.Rotation(0.0000000000, 0.0000000000, 0.0000000000), ) self.Box2.MapReversed = False - self.Box2.AttachmentSupport = self.Doc.getObject('XY_Plane') + self.Box2.AttachmentSupport = self.Doc.getObject("XY_Plane") self.Box2.MapPathParameter = 0.000000 - self.Box2.MapMode = 'FlatFace' + self.Box2.MapMode = "FlatFace" # Set the Refine option to False, otherwise adding the second box would be useless self.Box2.Refine = False @@ -178,7 +179,7 @@ class TestHole(unittest.TestCase): # Move the Hole on top of the Body self.Body.removeObject(self.Hole) - self.Body.insertObject(self.Hole,self.Box2, True) + self.Body.insertObject(self.Hole, self.Box2, True) self.Body.Tip = self.Hole self.Hole.Diameter = 6 self.Hole.Depth = 10 @@ -194,125 +195,446 @@ class TestHole(unittest.TestCase): self.Doc.recompute() self.assertEqual(len(self.Hole.Shape.Faces), 7) - def testThreadEnums(self): """Test thread enums for correct order""" # Due to the savefile use of indexes and not strings # The correct mapping needs to be ensured to not break savefiles # The order of the arrays and elements is critical thread_types = { - 'ISOMetricProfile': [ - "M1x0.25", "M1.1x0.25", "M1.2x0.25", "M1.4x0.3", "M1.6x0.35", - "M1.8x0.35", "M2x0.4", "M2.2x0.45", "M2.5x0.45", "M3x0.5", - "M3.5x0.6", "M4x0.7", "M4.5x0.75", "M5x0.8", "M6x1.0", - "M7x1.0", "M8x1.25", "M9x1.25", "M10x1.5", "M11x1.5", - "M12x1.75", "M14x2.0", "M16x2.0", "M18x2.5", "M20x2.5", - "M22x2.5", "M24x3.0", "M27x3.0", "M30x3.5", "M33x3.5", - "M36x4.0", "M39x4.0", "M42x4.5", "M45x4.5", "M48x5.0", - "M52x5.0", "M56x5.5", "M60x5.5", "M64x6.0", "M68x6.0", + "ISOMetricProfile": [ + "M1x0.25", + "M1.1x0.25", + "M1.2x0.25", + "M1.4x0.3", + "M1.6x0.35", + "M1.8x0.35", + "M2x0.4", + "M2.2x0.45", + "M2.5x0.45", + "M3x0.5", + "M3.5x0.6", + "M4x0.7", + "M4.5x0.75", + "M5x0.8", + "M6x1.0", + "M7x1.0", + "M8x1.25", + "M9x1.25", + "M10x1.5", + "M11x1.5", + "M12x1.75", + "M14x2.0", + "M16x2.0", + "M18x2.5", + "M20x2.5", + "M22x2.5", + "M24x3.0", + "M27x3.0", + "M30x3.5", + "M33x3.5", + "M36x4.0", + "M39x4.0", + "M42x4.5", + "M45x4.5", + "M48x5.0", + "M52x5.0", + "M56x5.5", + "M60x5.5", + "M64x6.0", + "M68x6.0", ], - 'ISOMetricFineProfile': [ - "M1x0.2", "M1.1x0.2", "M1.2x0.2", "M1.4x0.2", - "M1.6x0.2", "M1.8x0.2", "M2x0.25", "M2.2x0.25", - "M2.5x0.35", "M3x0.35", "M3.5x0.35", - "M4x0.5", "M4.5x0.5", "M5x0.5", "M5.5x0.5", - "M6x0.75", "M7x0.75", "M8x0.75", "M8x1.0", - "M9x0.75", "M9x1.0", "M10x0.75", "M10x1.0", - "M10x1.25", "M11x0.75", "M11x1.0", "M12x1.0", - "M12x1.25", "M12x1.5", "M14x1.0", "M14x1.25", - "M14x1.5", "M15x1.0", "M15x1.5", "M16x1.0", - "M16x1.5", "M17x1.0", "M17x1.5", "M18x1.0", - "M18x1.5", "M18x2.0", "M20x1.0", "M20x1.5", - "M20x2.0", "M22x1.0", "M22x1.5", "M22x2.0", - "M24x1.0", "M24x1.5", "M24x2.0", "M25x1.0", - "M25x1.5", "M25x2.0", "M27x1.0", "M27x1.5", - "M27x2.0", "M28x1.0", "M28x1.5", "M28x2.0", - "M30x1.0", "M30x1.5", "M30x2.0", "M30x3.0", - "M32x1.5", "M32x2.0", "M33x1.5", "M33x2.0", - "M33x3.0", "M35x1.5", "M35x2.0", "M36x1.5", - "M36x2.0", "M36x3.0", "M39x1.5", "M39x2.0", - "M39x3.0", "M40x1.5", "M40x2.0", "M40x3.0", - "M42x1.5", "M42x2.0", "M42x3.0", "M42x4.0", - "M45x1.5", "M45x2.0", "M45x3.0", "M45x4.0", - "M48x1.5", "M48x2.0", "M48x3.0", "M48x4.0", - "M50x1.5", "M50x2.0", "M50x3.0", "M52x1.5", - "M52x2.0", "M52x3.0", "M52x4.0", "M55x1.5", - "M55x2.0", "M55x3.0", "M55x4.0", "M56x1.5", - "M56x2.0", "M56x3.0", "M56x4.0", "M58x1.5", - "M58x2.0", "M58x3.0", "M58x4.0", "M60x1.5", - "M60x2.0", "M60x3.0", "M60x4.0", "M62x1.5", - "M62x2.0", "M62x3.0", "M62x4.0", "M64x1.5", - "M64x2.0", "M64x3.0", "M64x4.0", "M65x1.5", - "M65x2.0", "M65x3.0", "M65x4.0", "M68x1.5", - "M68x2.0", "M68x3.0", "M68x4.0", "M70x1.5", - "M70x2.0", "M70x3.0", "M70x4.0", "M70x6.0", - "M72x1.5", "M72x2.0", "M72x3.0", "M72x4.0", - "M72x6.0", "M75x1.5", "M75x2.0", "M75x3.0", - "M75x4.0", "M75x6.0", "M76x1.5", "M76x2.0", - "M76x3.0", "M76x4.0", "M76x6.0", "M80x1.5", - "M80x2.0", "M80x3.0", "M80x4.0", "M80x6.0", - "M85x2.0", "M85x3.0", "M85x4.0", "M85x6.0", - "M90x2.0", "M90x3.0", "M90x4.0", "M90x6.0", - "M95x2.0", "M95x3.0", "M95x4.0", "M95x6.0", - "M100x2.0", "M100x3.0", "M100x4.0", "M100x6.0", + "ISOMetricFineProfile": [ + "M1x0.2", + "M1.1x0.2", + "M1.2x0.2", + "M1.4x0.2", + "M1.6x0.2", + "M1.8x0.2", + "M2x0.25", + "M2.2x0.25", + "M2.5x0.35", + "M3x0.35", + "M3.5x0.35", + "M4x0.5", + "M4.5x0.5", + "M5x0.5", + "M5.5x0.5", + "M6x0.75", + "M7x0.75", + "M8x0.75", + "M8x1.0", + "M9x0.75", + "M9x1.0", + "M10x0.75", + "M10x1.0", + "M10x1.25", + "M11x0.75", + "M11x1.0", + "M12x1.0", + "M12x1.25", + "M12x1.5", + "M14x1.0", + "M14x1.25", + "M14x1.5", + "M15x1.0", + "M15x1.5", + "M16x1.0", + "M16x1.5", + "M17x1.0", + "M17x1.5", + "M18x1.0", + "M18x1.5", + "M18x2.0", + "M20x1.0", + "M20x1.5", + "M20x2.0", + "M22x1.0", + "M22x1.5", + "M22x2.0", + "M24x1.0", + "M24x1.5", + "M24x2.0", + "M25x1.0", + "M25x1.5", + "M25x2.0", + "M27x1.0", + "M27x1.5", + "M27x2.0", + "M28x1.0", + "M28x1.5", + "M28x2.0", + "M30x1.0", + "M30x1.5", + "M30x2.0", + "M30x3.0", + "M32x1.5", + "M32x2.0", + "M33x1.5", + "M33x2.0", + "M33x3.0", + "M35x1.5", + "M35x2.0", + "M36x1.5", + "M36x2.0", + "M36x3.0", + "M39x1.5", + "M39x2.0", + "M39x3.0", + "M40x1.5", + "M40x2.0", + "M40x3.0", + "M42x1.5", + "M42x2.0", + "M42x3.0", + "M42x4.0", + "M45x1.5", + "M45x2.0", + "M45x3.0", + "M45x4.0", + "M48x1.5", + "M48x2.0", + "M48x3.0", + "M48x4.0", + "M50x1.5", + "M50x2.0", + "M50x3.0", + "M52x1.5", + "M52x2.0", + "M52x3.0", + "M52x4.0", + "M55x1.5", + "M55x2.0", + "M55x3.0", + "M55x4.0", + "M56x1.5", + "M56x2.0", + "M56x3.0", + "M56x4.0", + "M58x1.5", + "M58x2.0", + "M58x3.0", + "M58x4.0", + "M60x1.5", + "M60x2.0", + "M60x3.0", + "M60x4.0", + "M62x1.5", + "M62x2.0", + "M62x3.0", + "M62x4.0", + "M64x1.5", + "M64x2.0", + "M64x3.0", + "M64x4.0", + "M65x1.5", + "M65x2.0", + "M65x3.0", + "M65x4.0", + "M68x1.5", + "M68x2.0", + "M68x3.0", + "M68x4.0", + "M70x1.5", + "M70x2.0", + "M70x3.0", + "M70x4.0", + "M70x6.0", + "M72x1.5", + "M72x2.0", + "M72x3.0", + "M72x4.0", + "M72x6.0", + "M75x1.5", + "M75x2.0", + "M75x3.0", + "M75x4.0", + "M75x6.0", + "M76x1.5", + "M76x2.0", + "M76x3.0", + "M76x4.0", + "M76x6.0", + "M80x1.5", + "M80x2.0", + "M80x3.0", + "M80x4.0", + "M80x6.0", + "M85x2.0", + "M85x3.0", + "M85x4.0", + "M85x6.0", + "M90x2.0", + "M90x3.0", + "M90x4.0", + "M90x6.0", + "M95x2.0", + "M95x3.0", + "M95x4.0", + "M95x6.0", + "M100x2.0", + "M100x3.0", + "M100x4.0", + "M100x6.0", ], - 'UNC': [ - "#1", "#2", "#3", "#4", "#5", "#6", - "#8", "#10", "#12", - "1/4", "5/16", "3/8", "7/16", "1/2", "9/16", - "5/8", "3/4", "7/8", "1", "1 1/8", "1 1/4", - "1 3/8", "1 1/2", "1 3/4", "2", "2 1/4", - "2 1/2", "2 3/4", "3", "3 1/4", "3 1/2", - "3 3/4", "4", + "UNC": [ + "#1", + "#2", + "#3", + "#4", + "#5", + "#6", + "#8", + "#10", + "#12", + "1/4", + "5/16", + "3/8", + "7/16", + "1/2", + "9/16", + "5/8", + "3/4", + "7/8", + "1", + "1 1/8", + "1 1/4", + "1 3/8", + "1 1/2", + "1 3/4", + "2", + "2 1/4", + "2 1/2", + "2 3/4", + "3", + "3 1/4", + "3 1/2", + "3 3/4", + "4", ], - 'UNF': [ - "#0", "#1", "#2", "#3", "#4", "#5", "#6", - "#8", "#10", "#12", - "1/4", "5/16", "3/8", "7/16", "1/2", "9/16", - "5/8", "3/4", "7/8", "1", "1 1/8", "1 3/16", "1 1/4", - "1 3/8", "1 1/2", + "UNF": [ + "#0", + "#1", + "#2", + "#3", + "#4", + "#5", + "#6", + "#8", + "#10", + "#12", + "1/4", + "5/16", + "3/8", + "7/16", + "1/2", + "9/16", + "5/8", + "3/4", + "7/8", + "1", + "1 1/8", + "1 3/16", + "1 1/4", + "1 3/8", + "1 1/2", ], - 'UNEF': [ - "#12", "1/4", "5/16", "3/8", "7/16", "1/2", - "9/16", "5/8", "11/16", "3/4", "13/16", "7/8", - "15/16", "1", "1 1/16", "1 1/8", "1 1/4", - "1 5/16", "1 3/8", "1 7/16", "1 1/2", "1 9/16", - "1 5/8", "1 11/16", + "UNEF": [ + "#12", + "1/4", + "5/16", + "3/8", + "7/16", + "1/2", + "9/16", + "5/8", + "11/16", + "3/4", + "13/16", + "7/8", + "15/16", + "1", + "1 1/16", + "1 1/8", + "1 1/4", + "1 5/16", + "1 3/8", + "1 7/16", + "1 1/2", + "1 9/16", + "1 5/8", + "1 11/16", ], - 'NPT': [ - "1/16", "1/8", "1/4", "3/8", "1/2", "3/4", - "1", "1 1/4", "1 1/2", - "2", "2 1/2", - "3", "3 1/2", - "4", "5", "6", "8", "10", "12", + "NPT": [ + "1/16", + "1/8", + "1/4", + "3/8", + "1/2", + "3/4", + "1", + "1 1/4", + "1 1/2", + "2", + "2 1/2", + "3", + "3 1/2", + "4", + "5", + "6", + "8", + "10", + "12", ], - 'BSP': [ - "1/16", "1/8", "1/4", "3/8", "1/2", "5/8", "3/4", "7/8", - "1", "1 1/8", "1 1/4", "1 1/2", "1 3/4", - "2", "2 1/4", "2 1/2", "2 3/4", - "3", "3 1/2", "4", "4 1/2", - "5", "5 1/2", "6", + "BSP": [ + "1/16", + "1/8", + "1/4", + "3/8", + "1/2", + "5/8", + "3/4", + "7/8", + "1", + "1 1/8", + "1 1/4", + "1 1/2", + "1 3/4", + "2", + "2 1/4", + "2 1/2", + "2 3/4", + "3", + "3 1/2", + "4", + "4 1/2", + "5", + "5 1/2", + "6", ], - 'BSW': [ - "1/8", "3/16", "1/4", "5/16", "3/8", "7/16", - "1/2", "9/16", "5/8", "11/16", "3/4", "7/8", - "1", "1 1/8", "1 1/4", "1 1/2", "1 3/4", - "2", "2 1/4", "2 1/2", "2 3/4", - "3", "3 1/4", "3 1/2", "3 3/4", - "4", "4 1/2", "5", "5 1/2", "6", + "BSW": [ + "1/8", + "3/16", + "1/4", + "5/16", + "3/8", + "7/16", + "1/2", + "9/16", + "5/8", + "11/16", + "3/4", + "7/8", + "1", + "1 1/8", + "1 1/4", + "1 1/2", + "1 3/4", + "2", + "2 1/4", + "2 1/2", + "2 3/4", + "3", + "3 1/4", + "3 1/2", + "3 3/4", + "4", + "4 1/2", + "5", + "5 1/2", + "6", ], - 'BSF': [ - "3/16", "7/32", "1/4", "9/32", "5/16", "3/8", "7/16", - "1/2", "9/16", "5/8", "11/16", "3/4", "7/8", - "1", "1 1/8", "1 1/4", "1 3/8", "1 1/2", "1 5/8", "1 3/4", - "2", "2 1/4", "2 1/2", "2 3/4", - "3", "3 1/4", "3 1/2", "3 3/4", - "4", "4 1/4", + "BSF": [ + "3/16", + "7/32", + "1/4", + "9/32", + "5/16", + "3/8", + "7/16", + "1/2", + "9/16", + "5/8", + "11/16", + "3/4", + "7/8", + "1", + "1 1/8", + "1 1/4", + "1 3/8", + "1 1/2", + "1 5/8", + "1 3/4", + "2", + "2 1/4", + "2 1/2", + "2 3/4", + "3", + "3 1/4", + "3 1/2", + "3 3/4", + "4", + "4 1/4", ], - 'ISOTyre': [ - "5v1", "5v2", "6v1", "8v1", "9v1", "10v2", - "12v1", "13v1", "8v2", "10v1", "11v1", "13v2", - "15v1", "16v1", "17v1", "17v2", "17v3", "19v1", "20v1", + "ISOTyre": [ + "5v1", + "5v2", + "6v1", + "8v1", + "9v1", + "10v2", + "12v1", + "13v1", + "8v2", + "10v1", + "11v1", + "13v2", + "15v1", + "16v1", + "17v1", + "17v2", + "17v3", + "19v1", + "20v1", ], } allowed_types = self.Hole.getEnumerationsOfProperty("ThreadType") @@ -333,9 +655,10 @@ class TestHole(unittest.TestCase): def _helperNotCorrectMessage(self, value, comparison): self.assertEqual( - value, comparison, + value, + comparison, f"{comparison} is not in the correct position\n\n" - "it will break compatibility with older saves" + "it will break compatibility with older saves", ) def _helperNotFoundMessage(self, prop, allowed_props): @@ -346,7 +669,6 @@ class TestHole(unittest.TestCase): ) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestHole") - #print ("omit closing document for debugging") - + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestInvoluteGear.py b/src/Mod/PartDesign/PartDesignTests/TestInvoluteGear.py index 5ac7c9729f..7de169a570 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestInvoluteGear.py +++ b/src/Mod/PartDesign/PartDesignTests/TestInvoluteGear.py @@ -1,36 +1,38 @@ -#*************************************************************************** -#* Copyright (c) 2021 Jonas Bähr * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2021 Jonas Bähr * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import pathlib from math import pi, tan, cos, acos import FreeCAD -Quantity = FreeCAD.Units.Quantity # FIXME from FreeCAD.Units import Quantity doesn't work + +Quantity = FreeCAD.Units.Quantity # FIXME from FreeCAD.Units import Quantity doesn't work from FreeCAD import Vector from Part import makeCircle, Precision, Solid import InvoluteGearFeature FIXTURE_PATH = pathlib.Path(__file__).parent / "Fixtures" + class TestInvoluteGear(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestInvoluteGear") @@ -41,56 +43,58 @@ class TestInvoluteGear(unittest.TestCase): FreeCAD.closeDocument(self.Doc.Name) def testDefaultGearProfile(self): - InvoluteGearFeature.makeInvoluteGear('TestGear') - gear = self.Doc.getObject('TestGear') + InvoluteGearFeature.makeInvoluteGear("TestGear") + gear = self.Doc.getObject("TestGear") self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) def testDefaultInternalGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") gear.ExternalGear = False self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) def testLowPrecisionGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") gear.HighPrecision = False self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) def testLowPrecisionInternalGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") gear.ExternalGear = False gear.HighPrecision = False self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) def testExternalGearProfileOrientation(self): - gear = InvoluteGearFeature.makeInvoluteGear('TestGear') + gear = InvoluteGearFeature.makeInvoluteGear("TestGear") self.assertSuccessfulRecompute(gear) tip_diameter = (gear.NumberOfTeeth + 2 * gear.AddendumCoefficient) * gear.Modules - delta = 0.01 # yes, we do not reach micrometer precision - tip_probe = makeCircle(delta, Vector(tip_diameter/2, 0, 0)) - self.assertIntersection(gear.Shape, tip_probe, - msg=f"First tooth tip does not lay on the positive X-axis") + delta = 0.01 # yes, we do not reach micrometer precision + tip_probe = makeCircle(delta, Vector(tip_diameter / 2, 0, 0)) + self.assertIntersection( + gear.Shape, tip_probe, msg=f"First tooth tip does not lay on the positive X-axis" + ) def testInternalGearProfileOrientation(self): - gear = InvoluteGearFeature.makeInvoluteGear('TestGear') + gear = InvoluteGearFeature.makeInvoluteGear("TestGear") gear.ExternalGear = False self.assertSuccessfulRecompute(gear) tip_diameter = (gear.NumberOfTeeth - 2 * gear.AddendumCoefficient) * gear.Modules - delta = 0.01 # yes, we do not reach micrometer precision - tip_probe = makeCircle(delta, Vector(tip_diameter/2, 0, 0)) - self.assertIntersection(gear.Shape, tip_probe, - msg=f"First tooth tip does not lay on the positive X-axis") + delta = 0.01 # yes, we do not reach micrometer precision + tip_probe = makeCircle(delta, Vector(tip_diameter / 2, 0, 0)) + self.assertIntersection( + gear.Shape, tip_probe, msg=f"First tooth tip does not lay on the positive X-axis" + ) def testCustomizedGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") z = 12 m = 1 gear.NumberOfTeeth = z - gear.Modules = f'{m} mm' - gear.PressureAngle = '14.5 deg' + gear.Modules = f"{m} mm" + gear.PressureAngle = "14.5 deg" self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) pitch_diameter = m * z @@ -101,19 +105,25 @@ class TestInvoluteGear(unittest.TestCase): # the test purpose here is just to ensure the gear's parameters are used, # not super precise profile verification. Thus a lax delta is just file here. delta = 0.01 - self.assertIntersection(gear.Shape, makeCircle(pitch_diameter/2), "Expecting intersection at pitch circle") - self.assertNoIntersection(gear.Shape, makeCircle(tip_diameter/2 + delta), "Teeth extent beyond tip circle") - self.assertNoIntersection(gear.Shape, makeCircle(root_diameter/2 - delta), "Teeth extend below root circle") + self.assertIntersection( + gear.Shape, makeCircle(pitch_diameter / 2), "Expecting intersection at pitch circle" + ) + self.assertNoIntersection( + gear.Shape, makeCircle(tip_diameter / 2 + delta), "Teeth extent beyond tip circle" + ) + self.assertNoIntersection( + gear.Shape, makeCircle(root_diameter / 2 - delta), "Teeth extend below root circle" + ) def testCustomizedGearProfileForSplinedShaft(self): - spline = InvoluteGearFeature.makeInvoluteGear('InvoluteSplinedShaft') + spline = InvoluteGearFeature.makeInvoluteGear("InvoluteSplinedShaft") z = 12 m = 2 add_coef = 0.5 ded_coef = 0.9 spline.NumberOfTeeth = z - spline.Modules = f'{m} mm' - spline.PressureAngle = '30 deg' + spline.Modules = f"{m} mm" + spline.PressureAngle = "30 deg" spline.AddendumCoefficient = add_coef spline.DedendumCoefficient = ded_coef spline.RootFilletCoefficient = 0.4 @@ -125,20 +135,26 @@ class TestInvoluteGear(unittest.TestCase): # the test purpose here is just to ensure the gear's parameters are used, # not super precise profile verification. Thus a lax delta is just file here. delta = 0.01 - self.assertIntersection(spline.Shape, makeCircle(pitch_diameter/2), "Expecting intersection at pitch circle") - self.assertNoIntersection(spline.Shape, makeCircle(tip_diameter/2 + delta), "Teeth extent beyond tip circle") - self.assertNoIntersection(spline.Shape, makeCircle(root_diameter/2 - delta), "Teeth extend below root circle") + self.assertIntersection( + spline.Shape, makeCircle(pitch_diameter / 2), "Expecting intersection at pitch circle" + ) + self.assertNoIntersection( + spline.Shape, makeCircle(tip_diameter / 2 + delta), "Teeth extent beyond tip circle" + ) + self.assertNoIntersection( + spline.Shape, makeCircle(root_diameter / 2 - delta), "Teeth extend below root circle" + ) def testCustomizedGearProfileForSplinedHub(self): - hub = InvoluteGearFeature.makeInvoluteGear('InvoluteSplinedHub') + hub = InvoluteGearFeature.makeInvoluteGear("InvoluteSplinedHub") hub.ExternalGear = False z = 12 m = 2 add_coef = 0.5 ded_coef = 0.9 hub.NumberOfTeeth = z - hub.Modules = f'{m} mm' - hub.PressureAngle = '30 deg' + hub.Modules = f"{m} mm" + hub.PressureAngle = "30 deg" hub.AddendumCoefficient = add_coef hub.DedendumCoefficient = ded_coef hub.RootFilletCoefficient = 0.4 @@ -150,13 +166,19 @@ class TestInvoluteGear(unittest.TestCase): # the test purpose here is just to ensure the gear's parameters are used, # not super precise profile verification. Thus a lax delta is just file here. delta = 0.01 - self.assertIntersection(hub.Shape, makeCircle(pitch_diameter/2), "Expecting intersection at pitch circle") - self.assertNoIntersection(hub.Shape, makeCircle(tip_diameter/2 - delta), "Teeth extent below tip circle") - self.assertNoIntersection(hub.Shape, makeCircle(root_diameter/2 + delta), "Teeth extend beyond root circle") + self.assertIntersection( + hub.Shape, makeCircle(pitch_diameter / 2), "Expecting intersection at pitch circle" + ) + self.assertNoIntersection( + hub.Shape, makeCircle(tip_diameter / 2 - delta), "Teeth extent below tip circle" + ) + self.assertNoIntersection( + hub.Shape, makeCircle(root_diameter / 2 + delta), "Teeth extend beyond root circle" + ) def testShiftedExternalGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') - gear.NumberOfTeeth = 9 # odd number to have a tooth space on the negative X-axis + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") + gear.NumberOfTeeth = 9 # odd number to have a tooth space on the negative X-axis gear.ProfileShiftCoefficient = 0.6 self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) @@ -165,27 +187,40 @@ class TestInvoluteGear(unittest.TestCase): Rref = gear.NumberOfTeeth * gear.Modules / 2 Rtip = Rref + gear.AddendumCoefficient * gear.Modules + xm Rroot = Rref - gear.DedendumCoefficient * gear.Modules + xm - delta = Quantity("20 um") # 20 micron is as good as it gets - self.assertIntersection(gear.Shape, makeCircle(Rref), "Expecting intersection at reference circle") - self.assertNoIntersection(gear.Shape, makeCircle(Rtip + delta), "Teeth extent beyond tip circle") - self.assertNoIntersection(gear.Shape, makeCircle(Rroot - delta), "Teeth extend below root circle") + delta = Quantity("20 um") # 20 micron is as good as it gets + self.assertIntersection( + gear.Shape, makeCircle(Rref), "Expecting intersection at reference circle" + ) + self.assertNoIntersection( + gear.Shape, makeCircle(Rtip + delta), "Teeth extent beyond tip circle" + ) + self.assertNoIntersection( + gear.Shape, makeCircle(Rroot - delta), "Teeth extend below root circle" + ) # to verify the angular dimensions, we use an "over pin measurement" Dpin, Rc = external_pin_diameter_and_distance( z=gear.NumberOfTeeth, - m=gear.Modules.getValueAs('mm'), - a=gear.PressureAngle.getValueAs('rad'), - x=gear.ProfileShiftCoefficient) + m=gear.Modules.getValueAs("mm"), + a=gear.PressureAngle.getValueAs("rad"), + x=gear.ProfileShiftCoefficient, + ) Rpin = Quantity(f"{Dpin/2} mm") - delta = Quantity("1 um") # our angular precision is much greater then the radial one - self.assertIntersection(gear.Shape, makeCircle(Rpin + delta, Vector(-Rc)), - msg="Expecting intersection with enlarged pin") - self.assertNoIntersection(gear.Shape, makeCircle(Rpin - delta, Vector(-Rc)), - msg="Expecting no intersection with reduced pin") + delta = Quantity("1 um") # our angular precision is much greater then the radial one + self.assertIntersection( + gear.Shape, + makeCircle(Rpin + delta, Vector(-Rc)), + msg="Expecting intersection with enlarged pin", + ) + self.assertNoIntersection( + gear.Shape, + makeCircle(Rpin - delta, Vector(-Rc)), + msg="Expecting no intersection with reduced pin", + ) def testShiftedInternalGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') - gear.NumberOfTeeth = 11 # odd number to have a tooth space on the negative X-axis - gear.ExternalGear = False # to ensure "clean" flanks we need to tweak some more props + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") + gear.NumberOfTeeth = 11 # odd number to have a tooth space on the negative X-axis + gear.ExternalGear = False # to ensure "clean" flanks we need to tweak some more props gear.ProfileShiftCoefficient = 0.4 gear.AddendumCoefficient = 0.6 gear.DedendumCoefficient = 0.8 @@ -197,25 +232,38 @@ class TestInvoluteGear(unittest.TestCase): # For internal, too, positive shift is outwards. So this is *not* inverted. Rtip = Rref - gear.AddendumCoefficient * gear.Modules + xm Rroot = Rref + gear.DedendumCoefficient * gear.Modules + xm - delta = Quantity("20 um") # 20 micron is as good as it gets - self.assertIntersection(gear.Shape, makeCircle(Rref), "Expecting intersection at reference circle") - self.assertNoIntersection(gear.Shape, makeCircle(Rtip - delta), "Teeth extent below tip circle") - self.assertNoIntersection(gear.Shape, makeCircle(Rroot + delta), "Teeth extend beyond root circle") + delta = Quantity("20 um") # 20 micron is as good as it gets + self.assertIntersection( + gear.Shape, makeCircle(Rref), "Expecting intersection at reference circle" + ) + self.assertNoIntersection( + gear.Shape, makeCircle(Rtip - delta), "Teeth extent below tip circle" + ) + self.assertNoIntersection( + gear.Shape, makeCircle(Rroot + delta), "Teeth extend beyond root circle" + ) # to verify the angular dimensions, we use an "over pin measurement" Dpin, Rc = internal_pin_diameter_and_distance( z=gear.NumberOfTeeth, - m=gear.Modules.getValueAs('mm'), - a=gear.PressureAngle.getValueAs('rad'), - x=gear.ProfileShiftCoefficient) + m=gear.Modules.getValueAs("mm"), + a=gear.PressureAngle.getValueAs("rad"), + x=gear.ProfileShiftCoefficient, + ) Rpin = Quantity(f"{Dpin/2} mm") - delta = Quantity("1 um") # our angular precision is much greater then the radial one - self.assertIntersection(gear.Shape, makeCircle(Rpin + delta, Vector(-Rc)), - msg="Expecting intersection with enlarged pin") - self.assertNoIntersection(gear.Shape, makeCircle(Rpin - delta, Vector(-Rc)), - msg="Expecting no intersection with reduced pin") + delta = Quantity("1 um") # our angular precision is much greater then the radial one + self.assertIntersection( + gear.Shape, + makeCircle(Rpin + delta, Vector(-Rc)), + msg="Expecting intersection with enlarged pin", + ) + self.assertNoIntersection( + gear.Shape, + makeCircle(Rpin - delta, Vector(-Rc)), + msg="Expecting no intersection with reduced pin", + ) def testZeroFilletExternalGearProfile_BaseAboveRoot(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") # below 42 teeth, with default dedendum 1.25, we have some non-involute flanks gear.NumberOfTeeth = 41 gear.RootFilletCoefficient = 0 @@ -223,7 +271,7 @@ class TestInvoluteGear(unittest.TestCase): self.assertClosedWire(gear.Shape) def testZeroFilletExternalGearProfile_BaseBelowRoot(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") # above 41 teeth, with default dedendum 1.25, the root is within the involute flank gear.NumberOfTeeth = 42 gear.RootFilletCoefficient = 0 @@ -231,90 +279,114 @@ class TestInvoluteGear(unittest.TestCase): self.assertClosedWire(gear.Shape) def testZeroFilletInternalGearProfile(self): - gear = InvoluteGearFeature.makeInvoluteGear('InvoluteGear') + gear = InvoluteGearFeature.makeInvoluteGear("InvoluteGear") gear.ExternalGear = False gear.RootFilletCoefficient = 0 self.assertSuccessfulRecompute(gear) self.assertClosedWire(gear.Shape) def testUsagePadGearProfile(self): - profile = InvoluteGearFeature.makeInvoluteGear('GearProfile') - body = self.Doc.addObject('PartDesign::Body','GearBody') + profile = InvoluteGearFeature.makeInvoluteGear("GearProfile") + body = self.Doc.addObject("PartDesign::Body", "GearBody") body.addObject(profile) - pad = body.newObject("PartDesign::Pad","GearPad") + pad = body.newObject("PartDesign::Pad", "GearPad") pad.Profile = profile - pad.Length = '5 mm' # that our gear's "Face Width" + pad.Length = "5 mm" # that our gear's "Face Width" self.assertSuccessfulRecompute() self.assertSolid(pad.Shape) def testUsagePocketInternalGearProfile(self): - profile = InvoluteGearFeature.makeInvoluteGear('GearProfile') + profile = InvoluteGearFeature.makeInvoluteGear("GearProfile") profile.ExternalGear = False # boolean cuts with lots of B-splines are quite slow, so let's make it less complex profile.HighPrecision = False profile.NumberOfTeeth = 8 - body = self.Doc.addObject('PartDesign::Body','GearBody') + body = self.Doc.addObject("PartDesign::Body", "GearBody") body.addObject(profile) - cylinder = body.newObject('PartDesign::AdditiveCylinder','GearCylinder') + cylinder = body.newObject("PartDesign::AdditiveCylinder", "GearCylinder") default_dedendum = 1.25 rim_width = 3 * FreeCAD.Units.MilliMetre - cylinder.Height = '5 mm' # that our gear's "Face Width" - cylinder.Radius = profile.NumberOfTeeth * profile.Modules / 2 + default_dedendum * profile.Modules + rim_width - pocket = body.newObject('PartDesign::Pocket','GearPocket') + cylinder.Height = "5 mm" # that our gear's "Face Width" + cylinder.Radius = ( + profile.NumberOfTeeth * profile.Modules / 2 + + default_dedendum * profile.Modules + + rim_width + ) + pocket = body.newObject("PartDesign::Pocket", "GearPocket") pocket.Profile = profile - pocket.Reversed = True # need to "pocket upwards" into the cylinder - pocket.Type = 'ThroughAll' + pocket.Reversed = True # need to "pocket upwards" into the cylinder + pocket.Type = "ThroughAll" self.assertSuccessfulRecompute() - self.assertSolid(Solid(pocket.Shape)) # Can be a compound, make that into a Solid if needed. + self.assertSolid( + Solid(pocket.Shape) + ) # Can be a compound, make that into a Solid if needed. def testRecomputeExternalGearFromV020(self): - FreeCAD.closeDocument(self.Doc.Name) # this was created in setUp(self) + FreeCAD.closeDocument(self.Doc.Name) # this was created in setUp(self) self.Doc = FreeCAD.openDocument(str(FIXTURE_PATH / "InvoluteGear_v0-20.FCStd")) created_with = f"created with {self.Doc.getProgramVersion()}" - gear = self.Doc.InvoluteGear # from fixture - fixture_length = 187.752 # from fixture, rounded to micrometer - self.assertClosedWire(gear.Shape) # no recompute yet, i.e. check original - self.assertAlmostEqual(fixture_length, gear.Shape.Length, places=3, - msg=f"Total wire length does not match fixture for gear {created_with}") + gear = self.Doc.InvoluteGear # from fixture + fixture_length = 187.752 # from fixture, rounded to micrometer + self.assertClosedWire(gear.Shape) # no recompute yet, i.e. check original + self.assertAlmostEqual( + fixture_length, + gear.Shape.Length, + places=3, + msg=f"Total wire length does not match fixture for gear {created_with}", + ) gear.enforceRecompute() self.assertSuccessfulRecompute(gear, msg=f"Cannot recompute gear {created_with}") - relative_tolerance_per_tooth = 1e-3 # wild guess: changes of <0.1%/tooth are ok + relative_tolerance_per_tooth = 1e-3 # wild guess: changes of <0.1%/tooth are ok length_delta = fixture_length * relative_tolerance_per_tooth * gear.NumberOfTeeth - self.assertAlmostEqual(fixture_length, gear.Shape.Length, delta=length_delta, - msg=f"Total wire length changed after recomputing gear {created_with}") + self.assertAlmostEqual( + fixture_length, + gear.Shape.Length, + delta=length_delta, + msg=f"Total wire length changed after recomputing gear {created_with}", + ) def testRecomputeInternalGearFromV020(self): - FreeCAD.closeDocument(self.Doc.Name) # this was created in setUp(self) + FreeCAD.closeDocument(self.Doc.Name) # this was created in setUp(self) self.Doc = FreeCAD.openDocument(str(FIXTURE_PATH / "InternalInvoluteGear_v0-20.FCStd")) created_with = f"created with {self.Doc.getProgramVersion()}" - gear = self.Doc.InvoluteGear # from fixture - fixture_length = 165.408 # from fixture, rounded to micrometer - self.assertClosedWire(gear.Shape) # no recompute yet, i.e. check original - self.assertAlmostEqual(fixture_length, gear.Shape.Length, places=3, - msg=f"Total wire length does not match fixture for gear {created_with}") + gear = self.Doc.InvoluteGear # from fixture + fixture_length = 165.408 # from fixture, rounded to micrometer + self.assertClosedWire(gear.Shape) # no recompute yet, i.e. check original + self.assertAlmostEqual( + fixture_length, + gear.Shape.Length, + places=3, + msg=f"Total wire length does not match fixture for gear {created_with}", + ) gear.enforceRecompute() self.assertSuccessfulRecompute(gear, msg=f"Cannot recompute gear {created_with}") - relative_tolerance_per_tooth = 1e-3 # wild guess: changes of <0.1%/tooth are ok + relative_tolerance_per_tooth = 1e-3 # wild guess: changes of <0.1%/tooth are ok length_delta = fixture_length * relative_tolerance_per_tooth * gear.NumberOfTeeth - self.assertAlmostEqual(fixture_length, gear.Shape.Length, delta=length_delta, - msg=f"Total wire length changed after recomputing gear {created_with}") + self.assertAlmostEqual( + fixture_length, + gear.Shape.Length, + delta=length_delta, + msg=f"Total wire length changed after recomputing gear {created_with}", + ) def assertSuccessfulRecompute(self, *objs, msg=None): - if (len(objs) == 0): + if len(objs) == 0: self.Doc.recompute() objs = self.Doc.Objects else: self.Doc.recompute(objs) - failed_objects = [o.Name for o in objs if 'Invalid' in o.State] - if (len(failed_objects) > 0): + failed_objects = [o.Name for o in objs if "Invalid" in o.State] + if len(failed_objects) > 0: self.fail(msg or f"Recompute failed for {failed_objects}") def assertClosedWire(self, shape, msg=None): - self.assertEqual(shape.ShapeType, 'Wire', msg=msg) + self.assertEqual(shape.ShapeType, "Wire", msg=msg) self.assertTrue(shape.isClosed(), msg=msg) def assertIntersection(self, shape1, shape2, msg=None): - self.assertTrue(self._check_intersection(shape1, shape2), msg or "Given shapes do not intersect.") + self.assertTrue( + self._check_intersection(shape1, shape2), msg or "Given shapes do not intersect." + ) def assertNoIntersection(self, shape1, shape2, msg=None): self.assertFalse(self._check_intersection(shape1, shape2), msg or "Given shapes intersect.") diff --git a/src/Mod/PartDesign/PartDesignTests/TestLinearPattern.py b/src/Mod/PartDesign/PartDesignTests/TestLinearPattern.py index e1ed9f7572..a9d431651a 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestLinearPattern.py +++ b/src/Mod/PartDesign/PartDesignTests/TestLinearPattern.py @@ -1,44 +1,45 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD import TestSketcherApp + class TestLinearPattern(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestLinearPattern") def testXAxisLinearPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Originals = [self.Box] - self.LinearPattern.Direction = (self.Doc.X_Axis,[""]) + self.LinearPattern.Direction = (self.Doc.X_Axis, [""]) self.LinearPattern.Length = 90.0 self.LinearPattern.Occurrences = 10 self.LinearPattern.Refine = True @@ -58,16 +59,16 @@ class TestLinearPattern(unittest.TestCase): self.assertEqual(self.LinearPattern.Shape.ElementMapSize, 26) def testYAxisLinearPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Originals = [self.Box] - self.LinearPattern.Direction = (self.Doc.Y_Axis,[""]) + self.LinearPattern.Direction = (self.Doc.Y_Axis, [""]) self.LinearPattern.Length = 90.0 self.LinearPattern.Occurrences = 10 self.LinearPattern.Refine = True @@ -78,16 +79,16 @@ class TestLinearPattern(unittest.TestCase): self.assertEqual(self.LinearPattern.Shape.ElementMapSize, 26) def testZAxisLinearPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Originals = [self.Box] - self.LinearPattern.Direction = (self.Doc.Z_Axis,[""]) + self.LinearPattern.Direction = (self.Doc.Z_Axis, [""]) self.LinearPattern.Length = 90.0 self.LinearPattern.Occurrences = 10 self.LinearPattern.Refine = True @@ -98,8 +99,8 @@ class TestLinearPattern(unittest.TestCase): self.assertEqual(self.LinearPattern.Shape.ElementMapSize, 26) def testNormalSketchAxisLinearPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -108,9 +109,9 @@ class TestLinearPattern(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Originals = [self.Pad] - self.LinearPattern.Direction = (self.PadSketch,["N_Axis"]) + self.LinearPattern.Direction = (self.PadSketch, ["N_Axis"]) self.LinearPattern.Length = 90.0 self.LinearPattern.Occurrences = 10 self.LinearPattern.Refine = True @@ -121,8 +122,8 @@ class TestLinearPattern(unittest.TestCase): self.assertEqual(self.LinearPattern.Shape.ElementMapSize, 26) def testVerticalSketchAxisLinearPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -131,9 +132,9 @@ class TestLinearPattern(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Originals = [self.Pad] - self.LinearPattern.Direction = (self.PadSketch,["V_Axis"]) + self.LinearPattern.Direction = (self.PadSketch, ["V_Axis"]) self.LinearPattern.Length = 90.0 self.LinearPattern.Occurrences = 10 self.LinearPattern.Refine = True @@ -144,8 +145,8 @@ class TestLinearPattern(unittest.TestCase): self.assertEqual(self.LinearPattern.Shape.ElementMapSize, 26) def testHorizontalSketchAxisLinearPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -154,9 +155,9 @@ class TestLinearPattern(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Originals = [self.Pad] - self.LinearPattern.Direction = (self.PadSketch,["H_Axis"]) + self.LinearPattern.Direction = (self.PadSketch, ["H_Axis"]) self.LinearPattern.Length = 90.0 self.LinearPattern.Occurrences = 10 self.LinearPattern.Refine = True @@ -168,7 +169,6 @@ class TestLinearPattern(unittest.TestCase): self.assertEqual(self.LinearPattern.Shape.ElementMapSize, 26) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestLinearPattern") # print ("omit closing document for debugging") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestLoft.py b/src/Mod/PartDesign/PartDesignTests/TestLoft.py index c314b7e101..b8cab2f835 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestLoft.py +++ b/src/Mod/PartDesign/PartDesignTests/TestLoft.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import math @@ -29,25 +29,27 @@ import Part import Sketcher import TestSketcherApp + class TestLoft(unittest.TestCase): - """ Loft Tests """ + """Loft Tests""" + def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestLoft") def testSimpleAdditiveLoftCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.ProfileSketch = self.Doc.addObject('Sketcher::SketchObject', 'ProfileSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.ProfileSketch = self.Doc.addObject("Sketcher::SketchObject", "ProfileSketch") self.Body.addObject(self.ProfileSketch) TestSketcherApp.CreateRectangleSketch(self.ProfileSketch, (0, 0), (1, 1)) self.Doc.recompute() - self.LoftSketch = self.Doc.addObject('Sketcher::SketchObject', 'LoftSketch') + self.LoftSketch = self.Doc.addObject("Sketcher::SketchObject", "LoftSketch") self.Body.addObject(self.LoftSketch) - self.LoftSketch.MapMode = 'FlatFace' - self.LoftSketch.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.LoftSketch.MapMode = "FlatFace" + self.LoftSketch.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.LoftSketch, (0, 1), (1, 1)) self.Doc.recompute() - self.AdditiveLoft = self.Doc.addObject("PartDesign::AdditiveLoft","AdditiveLoft") + self.AdditiveLoft = self.Doc.addObject("PartDesign::AdditiveLoft", "AdditiveLoft") self.Body.addObject(self.AdditiveLoft) self.AdditiveLoft.Profile = self.ProfileSketch self.AdditiveLoft.Sections = [self.LoftSketch] @@ -55,8 +57,8 @@ class TestLoft(unittest.TestCase): self.assertAlmostEqual(self.AdditiveLoft.Shape.Volume, 1) def testSimpleSubtractiveLoftCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (1, 1)) self.Doc.recompute() @@ -65,18 +67,18 @@ class TestLoft(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 2 self.Doc.recompute() - self.ProfileSketch = self.Doc.addObject('Sketcher::SketchObject', 'ProfileSketch') + self.ProfileSketch = self.Doc.addObject("Sketcher::SketchObject", "ProfileSketch") self.Body.addObject(self.ProfileSketch) TestSketcherApp.CreateRectangleSketch(self.ProfileSketch, (0, 0), (1, 1)) self.Doc.recompute() - self.LoftSketch = self.Doc.addObject('Sketcher::SketchObject', 'LoftSketch') + self.LoftSketch = self.Doc.addObject("Sketcher::SketchObject", "LoftSketch") self.Body.addObject(self.LoftSketch) - self.LoftSketch.MapMode = 'FlatFace' - self.LoftSketch.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.LoftSketch.MapMode = "FlatFace" + self.LoftSketch.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.LoftSketch, (0, 1), (1, 1)) self.Doc.recompute() - self.SubtractiveLoft = self.Doc.addObject("PartDesign::SubtractiveLoft","SubtractiveLoft") + self.SubtractiveLoft = self.Doc.addObject("PartDesign::SubtractiveLoft", "SubtractiveLoft") self.Body.addObject(self.SubtractiveLoft) self.SubtractiveLoft.Profile = self.ProfileSketch self.SubtractiveLoft.Sections = [self.LoftSketch] @@ -84,52 +86,60 @@ class TestLoft(unittest.TestCase): self.assertAlmostEqual(self.SubtractiveLoft.Shape.Volume, 1) def testClosedAdditiveLoftCase(self): - """ Test issue #6156: Loft tool "Closed" option not working """ - body = self.Doc.addObject('PartDesign::Body','Body') + """Test issue #6156: Loft tool "Closed" option not working""" + body = self.Doc.addObject("PartDesign::Body", "Body") - sketch1 = body.newObject('Sketcher::SketchObject','Sketch') - sketch1.AttachmentSupport = (self.Doc.XZ_Plane,['']) - sketch1.MapMode = 'FlatFace' - sketch1.addGeometry(Part.Circle(Base.Vector(-40.0,0.0,0.0),Base.Vector(0,0,1),10.0), False) - sketch1.addConstraint(Sketcher.Constraint('PointOnObject',0,3,-1)) - sketch1.addConstraint(Sketcher.Constraint('Diameter',0,20.0)) - sketch1.setDatum(1,Units.Quantity('20.000000 mm')) - sketch1.addConstraint(Sketcher.Constraint('Distance',-1,1,0,3,40.0)) - sketch1.setDatum(2,Units.Quantity('40.000000 mm')) + sketch1 = body.newObject("Sketcher::SketchObject", "Sketch") + sketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) + sketch1.MapMode = "FlatFace" + sketch1.addGeometry( + Part.Circle(Base.Vector(-40.0, 0.0, 0.0), Base.Vector(0, 0, 1), 10.0), False + ) + sketch1.addConstraint(Sketcher.Constraint("PointOnObject", 0, 3, -1)) + sketch1.addConstraint(Sketcher.Constraint("Diameter", 0, 20.0)) + sketch1.setDatum(1, Units.Quantity("20.000000 mm")) + sketch1.addConstraint(Sketcher.Constraint("Distance", -1, 1, 0, 3, 40.0)) + sketch1.setDatum(2, Units.Quantity("40.000000 mm")) - sketch2 = body.newObject('Sketcher::SketchObject','Sketch001') - sketch2.AttachmentSupport = (self.Doc.YZ_Plane,'') - sketch2.MapMode = 'FlatFace' - sketch2.addGeometry(Part.Circle(Base.Vector(-10.0,0.0,0.0),Base.Vector(0,0,1),10.0),False) - sketch2.addConstraint(Sketcher.Constraint('PointOnObject',0,3,-1)) - sketch2.addConstraint(Sketcher.Constraint('Diameter',0,20.0)) - sketch2.setDatum(1,Units.Quantity('20.000000 mm')) - sketch2.addConstraint(Sketcher.Constraint('Distance',-1,1,0,3,40.0)) - sketch2.setDatum(2,Units.Quantity('40.000000 mm')) + sketch2 = body.newObject("Sketcher::SketchObject", "Sketch001") + sketch2.AttachmentSupport = (self.Doc.YZ_Plane, "") + sketch2.MapMode = "FlatFace" + sketch2.addGeometry( + Part.Circle(Base.Vector(-10.0, 0.0, 0.0), Base.Vector(0, 0, 1), 10.0), False + ) + sketch2.addConstraint(Sketcher.Constraint("PointOnObject", 0, 3, -1)) + sketch2.addConstraint(Sketcher.Constraint("Diameter", 0, 20.0)) + sketch2.setDatum(1, Units.Quantity("20.000000 mm")) + sketch2.addConstraint(Sketcher.Constraint("Distance", -1, 1, 0, 3, 40.0)) + sketch2.setDatum(2, Units.Quantity("40.000000 mm")) - sketch3 = body.newObject('Sketcher::SketchObject','Sketch002') - sketch3.AttachmentSupport = (self.Doc.getObject('YZ_Plane'),'') - sketch3.MapMode = 'FlatFace' - sketch3.addGeometry(Part.Circle(Base.Vector(40.0,0.0,0.0),Base.Vector(0,0,1),10.0),False) - sketch3.addConstraint(Sketcher.Constraint('PointOnObject',0,3,-1)) - sketch3.addConstraint(Sketcher.Constraint('Distance',-1,1,0,3,40.0)) - sketch3.setDatum(1,Units.Quantity('40.000000 mm')) - sketch3.addConstraint(Sketcher.Constraint('Diameter',0,20.0)) - sketch3.setDatum(2,Units.Quantity('20.000000 mm')) + sketch3 = body.newObject("Sketcher::SketchObject", "Sketch002") + sketch3.AttachmentSupport = (self.Doc.getObject("YZ_Plane"), "") + sketch3.MapMode = "FlatFace" + sketch3.addGeometry( + Part.Circle(Base.Vector(40.0, 0.0, 0.0), Base.Vector(0, 0, 1), 10.0), False + ) + sketch3.addConstraint(Sketcher.Constraint("PointOnObject", 0, 3, -1)) + sketch3.addConstraint(Sketcher.Constraint("Distance", -1, 1, 0, 3, 40.0)) + sketch3.setDatum(1, Units.Quantity("40.000000 mm")) + sketch3.addConstraint(Sketcher.Constraint("Diameter", 0, 20.0)) + sketch3.setDatum(2, Units.Quantity("20.000000 mm")) - sketch4 = body.newObject('Sketcher::SketchObject','Sketch003') - sketch4.AttachmentSupport = (self.Doc.XZ_Plane,'') - sketch4.MapMode = 'FlatFace' - sketch4.addGeometry(Part.Circle(Base.Vector(40.0,0.0,0.0),Base.Vector(0,0,1),10.0),False) - sketch4.addConstraint(Sketcher.Constraint('PointOnObject',0,3,-1)) - sketch4.addConstraint(Sketcher.Constraint('Distance',-1,1,0,3,40.0)) - sketch4.setDatum(1,Units.Quantity('40.000000 mm')) - sketch4.addConstraint(Sketcher.Constraint('Diameter',0,20.0)) - sketch4.setDatum(2,Units.Quantity('20.000000 mm')) + sketch4 = body.newObject("Sketcher::SketchObject", "Sketch003") + sketch4.AttachmentSupport = (self.Doc.XZ_Plane, "") + sketch4.MapMode = "FlatFace" + sketch4.addGeometry( + Part.Circle(Base.Vector(40.0, 0.0, 0.0), Base.Vector(0, 0, 1), 10.0), False + ) + sketch4.addConstraint(Sketcher.Constraint("PointOnObject", 0, 3, -1)) + sketch4.addConstraint(Sketcher.Constraint("Distance", -1, 1, 0, 3, 40.0)) + sketch4.setDatum(1, Units.Quantity("40.000000 mm")) + sketch4.addConstraint(Sketcher.Constraint("Diameter", 0, 20.0)) + sketch4.setDatum(2, Units.Quantity("20.000000 mm")) self.Doc.recompute() - loft = body.newObject('PartDesign::AdditiveLoft','AdditiveLoft') + loft = body.newObject("PartDesign::AdditiveLoft", "AdditiveLoft") loft.Profile = sketch1 loft.Sections = [sketch2, sketch4, sketch3] loft.Closed = True @@ -141,77 +151,98 @@ class TestLoft(unittest.TestCase): self.Doc.recompute() - self.assertGreater(loft.Shape.Volume, 80000.0) # 85105.5788704151 + self.assertGreater(loft.Shape.Volume, 80000.0) # 85105.5788704151 def testPadOnLoftBetweenCones(self): - """ Test issue #15138 adapted from a script by chennes """ - body = self.Doc.addObject('PartDesign::Body', 'Body') - body.Label = 'Body' - coneBottomSketch = body.newObject('Sketcher::SketchObject', 'ConeBottomSketch') - coneBottomSketch.AttachmentSupport = (self.Doc.getObject('XY_Plane'), ['']) - coneBottomSketch.MapMode = 'FlatFace' - - geoList = [] - geoList.append(Part.Circle(Base.Vector(0.000000, 0.000000, 0.000000), - Base.Vector(0.000000, 0.000000, 1.000000), - 25.000000)) - coneBottomSketch.addGeometry(geoList, False) - del geoList - - constraintList = [] - coneBottomSketch.addConstraint(Sketcher.Constraint('Diameter', 0, 25.000000)) - coneBottomSketch.addConstraint(Sketcher.Constraint('Coincident', 0, 3, -1, 1)) - - geoList = [] - geoList.append(Part.Circle(Base.Vector(0.000000, 0.000000, 0.000000), - Base.Vector(0.000000, 0.000000, 1.000000), - 40.000000)) - coneBottomSketch.addGeometry(geoList, False) - del geoList - - constraintList = [] - coneBottomSketch.addConstraint(Sketcher.Constraint('Diameter', 1, 40.000000)) - coneBottomSketch.addConstraint(Sketcher.Constraint('Coincident', 1, 3, 0, 3)) - - coneTopSketch = body.newObject('Sketcher::SketchObject', 'ConeTopSketch') - coneTopSketch.AttachmentSupport = (self.Doc.getObject('XY_Plane'), ['']) - coneTopSketch.MapMode = 'FlatFace' + """Test issue #15138 adapted from a script by chennes""" + body = self.Doc.addObject("PartDesign::Body", "Body") + body.Label = "Body" + coneBottomSketch = body.newObject("Sketcher::SketchObject", "ConeBottomSketch") + coneBottomSketch.AttachmentSupport = (self.Doc.getObject("XY_Plane"), [""]) + coneBottomSketch.MapMode = "FlatFace" geoList = [] geoList.append( - Part.Circle(Base.Vector(0.000000, 0.000000, 0.000000), - Base.Vector(0.000000, 0.000000, 1.000000), - 8.000000)) - coneTopSketch.addGeometry(geoList, False) + Part.Circle( + Base.Vector(0.000000, 0.000000, 0.000000), + Base.Vector(0.000000, 0.000000, 1.000000), + 25.000000, + ) + ) + coneBottomSketch.addGeometry(geoList, False) del geoList constraintList = [] - coneTopSketch.addConstraint(Sketcher.Constraint('Diameter', 0, 8.000000)) - coneTopSketch.addConstraint(Sketcher.Constraint('Coincident', 0, 3, -1, 1)) + coneBottomSketch.addConstraint(Sketcher.Constraint("Diameter", 0, 25.000000)) + coneBottomSketch.addConstraint(Sketcher.Constraint("Coincident", 0, 3, -1, 1)) geoList = [] - geoList.append(Part.Circle(Base.Vector(0.000000, 0.000000, 0.000000), - Base.Vector(0.000000, 0.000000, 1.000000), - 15.000000)) + geoList.append( + Part.Circle( + Base.Vector(0.000000, 0.000000, 0.000000), + Base.Vector(0.000000, 0.000000, 1.000000), + 40.000000, + ) + ) + coneBottomSketch.addGeometry(geoList, False) + del geoList + + constraintList = [] + coneBottomSketch.addConstraint(Sketcher.Constraint("Diameter", 1, 40.000000)) + coneBottomSketch.addConstraint(Sketcher.Constraint("Coincident", 1, 3, 0, 3)) + + coneTopSketch = body.newObject("Sketcher::SketchObject", "ConeTopSketch") + coneTopSketch.AttachmentSupport = (self.Doc.getObject("XY_Plane"), [""]) + coneTopSketch.MapMode = "FlatFace" + + geoList = [] + geoList.append( + Part.Circle( + Base.Vector(0.000000, 0.000000, 0.000000), + Base.Vector(0.000000, 0.000000, 1.000000), + 8.000000, + ) + ) coneTopSketch.addGeometry(geoList, False) del geoList constraintList = [] - coneTopSketch.addConstraint(Sketcher.Constraint('Diameter', 1, 15.000000)) - coneTopSketch.addConstraint(Sketcher.Constraint('Coincident', 1, 3, 0, 3)) - coneTopSketch.AttachmentOffset = Base.Placement(Base.Vector(0, 0, 20), - Base.Rotation(Base.Vector(0, 0, 1), 0)) + coneTopSketch.addConstraint(Sketcher.Constraint("Diameter", 0, 8.000000)) + coneTopSketch.addConstraint(Sketcher.Constraint("Coincident", 0, 3, -1, 1)) + + geoList = [] + geoList.append( + Part.Circle( + Base.Vector(0.000000, 0.000000, 0.000000), + Base.Vector(0.000000, 0.000000, 1.000000), + 15.000000, + ) + ) + coneTopSketch.addGeometry(geoList, False) + del geoList + + constraintList = [] + coneTopSketch.addConstraint(Sketcher.Constraint("Diameter", 1, 15.000000)) + coneTopSketch.addConstraint(Sketcher.Constraint("Coincident", 1, 3, 0, 3)) + coneTopSketch.AttachmentOffset = Base.Placement( + Base.Vector(0, 0, 20), Base.Rotation(Base.Vector(0, 0, 1), 0) + ) self.Doc.recompute() - cone = body.newObject('PartDesign::AdditiveLoft', 'Cone') + cone = body.newObject("PartDesign::AdditiveLoft", "Cone") cone.Profile = coneBottomSketch - cone.Sections = [(coneTopSketch, [''])] + cone.Sections = [(coneTopSketch, [""])] coneBottomSketch.Visibility = False coneTopSketch.Visibility = False self.Doc.recompute() - pad = body.newObject('PartDesign::Pad', 'Pad') - pad.Profile = (cone, ['Face3', ]) + pad = body.newObject("PartDesign::Pad", "Pad") + pad.Profile = ( + cone, + [ + "Face3", + ], + ) pad.Length = 10.000000 pad.TaperAngle = 0.000000 pad.UseCustomVector = 0 @@ -233,22 +264,42 @@ class TestLoft(unittest.TestCase): coneHeight = 20.0 padHeight = 10.0 # Frustum volumes - outerConeVolume = 1.0 / 3.0 * math.pi * coneHeight * ( - outerConeBottomRadius ** 2 + outerConeTopRadius ** 2 + - outerConeBottomRadius * outerConeTopRadius ) - innerConeVolume = 1.0 / 3.0 * math.pi * coneHeight * ( - innerConeBottomRadius ** 2 + innerConeTopRadius ** 2 + - innerConeBottomRadius * innerConeTopRadius ) + outerConeVolume = ( + 1.0 + / 3.0 + * math.pi + * coneHeight + * ( + outerConeBottomRadius**2 + + outerConeTopRadius**2 + + outerConeBottomRadius * outerConeTopRadius + ) + ) + innerConeVolume = ( + 1.0 + / 3.0 + * math.pi + * coneHeight + * ( + innerConeBottomRadius**2 + + innerConeTopRadius**2 + + innerConeBottomRadius * innerConeTopRadius + ) + ) frustumVolume = outerConeVolume - innerConeVolume - topArea = math.pi * (outerConeTopRadius ** 2) - math.pi * (innerConeTopRadius ** 2) - bottomArea = math.pi * (outerConeBottomRadius ** 2) - math.pi * (innerConeBottomRadius ** 2) + topArea = math.pi * (outerConeTopRadius**2) - math.pi * (innerConeTopRadius**2) + bottomArea = math.pi * (outerConeBottomRadius**2) - math.pi * (innerConeBottomRadius**2) padVolume = topArea * padHeight self.assertEqual(len(cone.Shape.Faces), 4) # Bottom, Inner, Top, Outer self.assertAlmostEqual(cone.Shape.Faces[2].Area, topArea) self.assertAlmostEqual(cone.Shape.Faces[0].Area, bottomArea) self.assertAlmostEqual(cone.Shape.Volume, frustumVolume) - self.assertAlmostEqual(pad.Shape.Volume, frustumVolume + padVolume) # contains volume of previous in Body - self.assertAlmostEqual(body.Shape.Volume, frustumVolume + padVolume) # Overall body volume matches + self.assertAlmostEqual( + pad.Shape.Volume, frustumVolume + padVolume + ) # contains volume of previous in Body + self.assertAlmostEqual( + body.Shape.Volume, frustumVolume + padVolume + ) # Overall body volume matches def testTwoFacesAdditiveLoftCase(self): """Test issue #19183: Loft tool "Loft between faces no longer works""" @@ -272,9 +323,7 @@ class TestLoft(unittest.TestCase): ) sketch1.addGeometry( Part.ArcOfCircle( - Part.Circle( - Base.Vector(0.418837, -1.275699, 0), Base.Vector(0, 0, 1), 32.879378 - ), + Part.Circle(Base.Vector(0.418837, -1.275699, 0), Base.Vector(0, 0, 1), 32.879378), -1.751723, -1.454683, ), @@ -338,9 +387,7 @@ class TestLoft(unittest.TestCase): ) sketch2.addGeometry( Part.ArcOfCircle( - Part.Circle( - Base.Vector(0.418837, -1.275699, 0), Base.Vector(0, 0, 1), 32.879378 - ), + Part.Circle(Base.Vector(0.418837, -1.275699, 0), Base.Vector(0, 0, 1), 32.879378), -1.751723, -1.454683, ), @@ -432,6 +479,6 @@ class TestLoft(unittest.TestCase): self.Doc.recompute() def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestLoft") # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestMaterial.py b/src/Mod/PartDesign/PartDesignTests/TestMaterial.py index 78200d19a6..3242d75ac9 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestMaterial.py +++ b/src/Mod/PartDesign/PartDesignTests/TestMaterial.py @@ -1,28 +1,29 @@ -#*************************************************************************** -#* Copyright (c) 2024 David Carter * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2024 David Carter * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD + class TestMaterial(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestMaterial") @@ -38,59 +39,63 @@ class TestMaterial(unittest.TestCase): def testDiffuseColor(self): print("PartDesignTestMaterial.testDiffuseColor()") - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.Body.ViewObject.DiffuseColor = [(1.,0.,0.,0.), - (.9,0.,0.,0.), - (.8,0.,0.,0.), - (.7,0.,0.,0.), - (.6,1.,0.,0.), - (.5,1.,0.,0.)] + self.Body.ViewObject.DiffuseColor = [ + (1.0, 0.0, 0.0, 0.0), + (0.9, 0.0, 0.0, 0.0), + (0.8, 0.0, 0.0, 0.0), + (0.7, 0.0, 0.0, 0.0), + (0.6, 1.0, 0.0, 0.0), + (0.5, 1.0, 0.0, 0.0), + ] self.Doc.recompute() self.assertEqual(len(self.Body.ViewObject.DiffuseColor), 6) colors = self.Body.ViewObject.DiffuseColor - self.compareColors(colors[0], (1.,0.,0.,0.)) - self.compareColors(colors[1], (.9,0.,0.,0.)) - self.compareColors(colors[2], (.8,0.,0.,0.)) - self.compareColors(colors[3], (.7,0.,0.,0.)) - self.compareColors(colors[4], (.6,1.,0.,0.)) - self.compareColors(colors[5], (.5,1.,0.,0.)) + self.compareColors(colors[0], (1.0, 0.0, 0.0, 0.0)) + self.compareColors(colors[1], (0.9, 0.0, 0.0, 0.0)) + self.compareColors(colors[2], (0.8, 0.0, 0.0, 0.0)) + self.compareColors(colors[3], (0.7, 0.0, 0.0, 0.0)) + self.compareColors(colors[4], (0.6, 1.0, 0.0, 0.0)) + self.compareColors(colors[5], (0.5, 1.0, 0.0, 0.0)) - self.Body.ViewObject.DiffuseColor = [(1.,0.,0.,0.)] + self.Body.ViewObject.DiffuseColor = [(1.0, 0.0, 0.0, 0.0)] self.Doc.recompute() self.assertEqual(len(self.Body.ViewObject.DiffuseColor), 1) colors = self.Body.ViewObject.DiffuseColor - self.compareColors(colors[0], (1.,0.,0.,0.)) + self.compareColors(colors[0], (1.0, 0.0, 0.0, 0.0)) - self.Box.ViewObject.DiffuseColor = [(1.,0.,0.,0.), - (.9,0.,0.,0.), - (.8,0.,0.,0.), - (.7,0.,0.,0.), - (.6,1.,0.,0.), - (.5,1.,0.,0.)] + self.Box.ViewObject.DiffuseColor = [ + (1.0, 0.0, 0.0, 0.0), + (0.9, 0.0, 0.0, 0.0), + (0.8, 0.0, 0.0, 0.0), + (0.7, 0.0, 0.0, 0.0), + (0.6, 1.0, 0.0, 0.0), + (0.5, 1.0, 0.0, 0.0), + ] self.Doc.recompute() self.assertEqual(len(self.Box.ViewObject.DiffuseColor), 6) colors = self.Box.ViewObject.DiffuseColor - self.compareColors(colors[0], (1.,0.,0.,0.)) - self.compareColors(colors[1], (.9,0.,0.,0.)) - self.compareColors(colors[2], (.8,0.,0.,0.)) - self.compareColors(colors[3], (.7,0.,0.,0.)) - self.compareColors(colors[4], (.6,1.,0.,0.)) - self.compareColors(colors[5], (.5,1.,0.,0.)) + self.compareColors(colors[0], (1.0, 0.0, 0.0, 0.0)) + self.compareColors(colors[1], (0.9, 0.0, 0.0, 0.0)) + self.compareColors(colors[2], (0.8, 0.0, 0.0, 0.0)) + self.compareColors(colors[3], (0.7, 0.0, 0.0, 0.0)) + self.compareColors(colors[4], (0.6, 1.0, 0.0, 0.0)) + self.compareColors(colors[5], (0.5, 1.0, 0.0, 0.0)) - self.Box.ViewObject.DiffuseColor = [(1.,0.,0.,0.)] + self.Box.ViewObject.DiffuseColor = [(1.0, 0.0, 0.0, 0.0)] self.Doc.recompute() self.assertEqual(len(self.Box.ViewObject.DiffuseColor), 1) colors = self.Box.ViewObject.DiffuseColor - self.compareColors(colors[0], (1.,0.,0.,0.)) + self.compareColors(colors[0], (1.0, 0.0, 0.0, 0.0)) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestMaterial") # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestMirrored.py b/src/Mod/PartDesign/PartDesignTests/TestMirrored.py index d6dd41b216..ce7c6b55ab 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestMirrored.py +++ b/src/Mod/PartDesign/PartDesignTests/TestMirrored.py @@ -1,29 +1,30 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD import TestSketcherApp + class TestMirrored(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestMirrored") @@ -33,17 +34,17 @@ class TestMirrored(unittest.TestCase): Creates a unit cube cornered at the origin and mirrors it about the Y axis. This operation should create a rectangular prism with volume 2.0. """ - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Rect = self.Doc.addObject('Sketcher::SketchObject','Rect') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Rect = self.Doc.addObject("Sketcher::SketchObject", "Rect") self.Body.addObject(self.Rect) TestSketcherApp.CreateRectangleSketch(self.Rect, (0, 0), (1, 1)) self.Doc.recompute() - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.Pad.Profile = self.Rect self.Pad.Length = 1 self.Body.addObject(self.Pad) self.Doc.recompute() - self.Mirrored = self.Doc.addObject("PartDesign::Mirrored","Mirrored") + self.Mirrored = self.Doc.addObject("PartDesign::Mirrored", "Mirrored") self.Mirrored.Originals = [self.Pad] self.Mirrored.MirrorPlane = (self.Rect, ["V_Axis"]) self.Body.addObject(self.Mirrored) @@ -56,11 +57,11 @@ class TestMirrored(unittest.TestCase): but is designed to ensure the same end result occurs with a different base object. """ - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=1 - self.Box.Width=1 - self.Box.Height=1 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 1 + self.Box.Width = 1 + self.Box.Height = 1 self.Body.addObject(self.Box) self.Doc.recompute() self.Mirrored = self.Doc.addObject("PartDesign::Mirrored", "Mirrored") @@ -71,17 +72,17 @@ class TestMirrored(unittest.TestCase): self.assertAlmostEqual(self.Mirrored.Shape.Volume, 2.0) def testMirroredOffsetCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Rect = self.Doc.addObject('Sketcher::SketchObject','Rect') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Rect = self.Doc.addObject("Sketcher::SketchObject", "Rect") self.Body.addObject(self.Rect) TestSketcherApp.CreateRectangleSketch(self.Rect, (0, 1), (1, 1)) self.Doc.recompute() - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.Pad.Profile = self.Rect self.Pad.Length = 1 self.Body.addObject(self.Pad) self.Doc.recompute() - self.Mirrored = self.Doc.addObject("PartDesign::Mirrored","Mirrored") + self.Mirrored = self.Doc.addObject("PartDesign::Mirrored", "Mirrored") self.Mirrored.Originals = [self.Pad] self.Mirrored.MirrorPlane = (self.Rect, ["H_Axis"]) self.Body.addObject(self.Mirrored) @@ -89,6 +90,6 @@ class TestMirrored(unittest.TestCase): self.assertIn("Up-to-date", self.Mirrored.State) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestMirrored") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestMultiTransform.py b/src/Mod/PartDesign/PartDesignTests/TestMultiTransform.py index f75ebc6df8..ad410bdc4f 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestMultiTransform.py +++ b/src/Mod/PartDesign/PartDesignTests/TestMultiTransform.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import math @@ -27,15 +27,16 @@ import TestSketcherApp App = FreeCAD + class TestMultiTransform(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestMultiTransform") FreeCAD.ConfigSet("SuppressRecomputeRequiredDialog", "True") def testMultiTransform(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -44,36 +45,36 @@ class TestMultiTransform(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.MultiTransform = self.Doc.addObject("PartDesign::MultiTransform","MultiTransform") + self.MultiTransform = self.Doc.addObject("PartDesign::MultiTransform", "MultiTransform") self.Doc.recompute() self.MultiTransform.Originals = [self.Pad] self.MultiTransform.Shape = self.Pad.Shape self.Body.addObject(self.MultiTransform) self.Doc.recompute() - self.Mirrored = self.Doc.addObject("PartDesign::Mirrored","Mirrored") + self.Mirrored = self.Doc.addObject("PartDesign::Mirrored", "Mirrored") self.Mirrored.MirrorPlane = (self.PadSketch, ["H_Axis"]) self.Body.addObject(self.Mirrored) - self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern","LinearPattern") + self.LinearPattern = self.Doc.addObject("PartDesign::LinearPattern", "LinearPattern") self.LinearPattern.Direction = (self.PadSketch, ["H_Axis"]) self.LinearPattern.Length = 20 self.LinearPattern.Occurrences = 3 self.Body.addObject(self.LinearPattern) - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Axis = (self.PadSketch, ["N_Axis"]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.Body.addObject(self.PolarPattern) - self.MultiTransform.Transformations = [self.Mirrored,self.LinearPattern,self.PolarPattern] + self.MultiTransform.Transformations = [self.Mirrored, self.LinearPattern, self.PolarPattern] self.Doc.recompute() self.assertAlmostEqual(self.MultiTransform.Shape.Volume, 20000) def testMultiTransformDressup(self): # Arrange Doc = self.Doc - Body = Doc.addObject('PartDesign::Body','Body') + Body = Doc.addObject("PartDesign::Body", "Body") Body.AllowCompound = False # Make first offset cube Pad - PadSketch = Doc.addObject('Sketcher::SketchObject', 'SketchPad') + PadSketch = Doc.addObject("Sketcher::SketchObject", "SketchPad") Body.addObject(PadSketch) xw = yw = zw = 10 TestSketcherApp.CreateRectangleSketch(PadSketch, (0, 0), (xw, yw)) @@ -83,47 +84,59 @@ class TestMultiTransform(unittest.TestCase): Pad.Profile = PadSketch Pad.Length = zw Doc.recompute() - MultiTransform = Doc.addObject("PartDesign::MultiTransform","MultiTransform") + MultiTransform = Doc.addObject("PartDesign::MultiTransform", "MultiTransform") Doc.recompute() MultiTransform.Originals = [Pad] MultiTransform.Shape = Pad.Shape Body.addObject(MultiTransform) Doc.recompute() - Mirrored = Doc.addObject("PartDesign::Mirrored","Mirrored") - Mirrored.MirrorPlane = (Doc.getObject('XY_Plane'), ['']) + Mirrored = Doc.addObject("PartDesign::Mirrored", "Mirrored") + Mirrored.MirrorPlane = (Doc.getObject("XY_Plane"), [""]) Mirrored.Refine = True Body.addObject(Mirrored) - Mirrored2 = Doc.addObject("PartDesign::Mirrored","Mirrored") - Mirrored2.MirrorPlane = (Doc.getObject('XZ_Plane'), [""]) + Mirrored2 = Doc.addObject("PartDesign::Mirrored", "Mirrored") + Mirrored2.MirrorPlane = (Doc.getObject("XZ_Plane"), [""]) Mirrored2.Refine = True Body.addObject(Mirrored2) - MultiTransform.Transformations = [Mirrored,Mirrored2] + MultiTransform.Transformations = [Mirrored, Mirrored2] MultiTransform.Refine = True Doc.recompute() - Fillet = Doc.addObject("PartDesign::Fillet","Fillet") - Fillet.Base = (MultiTransform, [ "Face1", "Face2" ]) + Fillet = Doc.addObject("PartDesign::Fillet", "Fillet") + Fillet.Base = (MultiTransform, ["Face1", "Face2"]) radius = 3 Fillet.Radius = radius Body.addObject(Fillet) # Broken out calculation of volume with two adjacent filleted faces = 5 long edges, 2 short edges, # 2 fully rounded corners and 4 corners with only 2 fillets meeting - cubeVolume = xw * yw * zw * 2 * 2 # Mirrored and mirrored again. - filletOuter = radius ** 2 * ( xw - radius * 2 ) # Volume of the rect prisms the fillets are in. - filletCorner = radius ** 3 # Volume of the rect prism corners - qRoundArea = math.pi * radius ** 2 / 4 # Area of the quarter round fillet profile - filletPrism = qRoundArea * ( xw - radius * 2 ) # Volume of fillet minus corners - fillet3Corner = math.pi * radius ** 3 * 4 / 3 / 8 # Volume of a fully rounded corner ( Sphere / 8 ) - fillet2Corner = radius ** 2 * 2 # Volume of corner with two fillets intersecting - fillet1Corner = math.pi * radius ** 2 / 4 * radius # Volume of corner with stopped single fillet - extraFillet = qRoundArea * xw # extra fillet in a mirrored direction - filletOuterExt = radius ** 2 * 10 # extra rect prim surrounding fillet - rectBox = cubeVolume - (4 + 3) * (filletOuter + filletCorner ) - 5 * filletOuterExt + filletCorner - fillets = ( 4 + 3 ) * filletPrism + 5 * extraFillet + fillet3Corner * 2 + fillet2Corner * 4 + fillet1Corner * 0 + cubeVolume = xw * yw * zw * 2 * 2 # Mirrored and mirrored again. + filletOuter = radius**2 * (xw - radius * 2) # Volume of the rect prisms the fillets are in. + filletCorner = radius**3 # Volume of the rect prism corners + qRoundArea = math.pi * radius**2 / 4 # Area of the quarter round fillet profile + filletPrism = qRoundArea * (xw - radius * 2) # Volume of fillet minus corners + fillet3Corner = ( + math.pi * radius**3 * 4 / 3 / 8 + ) # Volume of a fully rounded corner ( Sphere / 8 ) + fillet2Corner = radius**2 * 2 # Volume of corner with two fillets intersecting + fillet1Corner = ( + math.pi * radius**2 / 4 * radius + ) # Volume of corner with stopped single fillet + extraFillet = qRoundArea * xw # extra fillet in a mirrored direction + filletOuterExt = radius**2 * 10 # extra rect prim surrounding fillet + rectBox = ( + cubeVolume - (4 + 3) * (filletOuter + filletCorner) - 5 * filletOuterExt + filletCorner + ) + fillets = ( + (4 + 3) * filletPrism + + 5 * extraFillet + + fillet3Corner * 2 + + fillet2Corner * 4 + + fillet1Corner * 0 + ) volume = rectBox + fillets # Act - Link = Doc.addObject('App::Link','Link001') + Link = Doc.addObject("App::Link", "Link001") Link.setLink(Doc.Body) - Link.Label='Body001' + Link.Label = "Body001" Doc.recompute() # Assert self.assertAlmostEqual(abs(Body.Shape.Volume), volume, 6) @@ -137,8 +150,7 @@ class TestMultiTransform(unittest.TestCase): # self.Mirrored.TransformMode="Transform tools" def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestMultiTransform") FreeCAD.ConfigSet("SuppressRecomputeRequiredDialog", "") - #print ("omit closing document for debugging") - + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestPad.py b/src/Mod/PartDesign/PartDesignTests/TestPad.py index 3a88c8a1f2..5f90b219ef 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestPad.py +++ b/src/Mod/PartDesign/PartDesignTests/TestPad.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest @@ -25,55 +25,56 @@ import FreeCAD from FreeCAD import Base import TestSketcherApp + class TestPad(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestPad") def testBoxCase(self): - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject','SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") TestSketcherApp.CreateSlotPlateSet(self.PadSketch) self.Doc.recompute() - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.Pad.Profile = self.PadSketch self.Doc.recompute() self.assertEqual(len(self.Pad.Shape.Faces), 6) def testSketchOnBasePlane(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject','SketchPad') - self.PadSketch.AttachmentSupport = (self.Doc.XY_Plane, ['']) - self.PadSketch.MapMode = 'FlatFace' + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") + self.PadSketch.AttachmentSupport = (self.Doc.XY_Plane, [""]) + self.PadSketch.MapMode = "FlatFace" self.Body.addObject(self.PadSketch) TestSketcherApp.CreateSlotPlateSet(self.PadSketch) self.Doc.recompute() - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.Pad.Profile = self.PadSketch self.Body.addObject(self.Pad) self.Doc.recompute() self.assertEqual(len(self.Pad.Shape.Faces), 6) def testSketchOnDatumPlane(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.DatumPlane = self.Doc.addObject('PartDesign::Plane','DatumPlane') - self.DatumPlane.AttachmentSupport = (self.Doc.XY_Plane, ['']) - self.DatumPlane.MapMode = 'FlatFace' + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.DatumPlane = self.Doc.addObject("PartDesign::Plane", "DatumPlane") + self.DatumPlane.AttachmentSupport = (self.Doc.XY_Plane, [""]) + self.DatumPlane.MapMode = "FlatFace" self.Body.addObject(self.DatumPlane) - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject','SketchPad') - self.PadSketch.AttachmentSupport = (self.DatumPlane, ['']) - self.PadSketch.MapMode = 'FlatFace' + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") + self.PadSketch.AttachmentSupport = (self.DatumPlane, [""]) + self.PadSketch.MapMode = "FlatFace" self.Body.addObject(self.PadSketch) TestSketcherApp.CreateSlotPlateSet(self.PadSketch) self.Doc.recompute() - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.Pad.Profile = self.PadSketch self.Body.addObject(self.Pad) self.Doc.recompute() self.assertEqual(len(self.Pad.Shape.Faces), 6) def testPadToFirstCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 1), (1, 1)) self.Doc.recompute() @@ -83,10 +84,10 @@ class TestPad(unittest.TestCase): self.Pad.Length = 1 self.Doc.recompute() # Make second pad on different plane and pad to first - self.PadSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad1') + self.PadSketch1 = self.Doc.addObject("Sketcher::SketchObject", "SketchPad1") self.Body.addObject(self.PadSketch1) - self.PadSketch1.MapMode = 'FlatFace' - self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PadSketch1.MapMode = "FlatFace" + self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PadSketch1, (0, 0), (1, 1)) self.Doc.recompute() @@ -99,9 +100,9 @@ class TestPad(unittest.TestCase): self.assertAlmostEqual(self.Pad1.Shape.Volume, 2.0) def testPadtoLastCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0.5, 1), (0.5, 2)) self.Doc.recompute() @@ -111,10 +112,10 @@ class TestPad(unittest.TestCase): self.Pad.Length = 1 self.Doc.recompute() # Make second pad on different plane and pad to first - self.PadSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad1') + self.PadSketch1 = self.Doc.addObject("Sketcher::SketchObject", "SketchPad1") self.Body.addObject(self.PadSketch1) - self.PadSketch1.MapMode = 'FlatFace' - self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PadSketch1.MapMode = "FlatFace" + self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PadSketch1, (0, 0), (1, 1)) self.Doc.recompute() @@ -127,9 +128,9 @@ class TestPad(unittest.TestCase): self.assertAlmostEqual(self.Pad1.Shape.Volume, 3.0) def testPadToFaceCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 1), (1, 1)) self.Doc.recompute() @@ -139,10 +140,10 @@ class TestPad(unittest.TestCase): self.Pad.Length = 1 self.Doc.recompute() # Make second pad on different plane and pad to face on first - self.PadSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad1') + self.PadSketch1 = self.Doc.addObject("Sketcher::SketchObject", "SketchPad1") self.Body.addObject(self.PadSketch1) - self.PadSketch1.MapMode = 'FlatFace' - self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PadSketch1.MapMode = "FlatFace" + self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PadSketch1, (0, 0), (1, 1)) self.Doc.recompute() @@ -156,9 +157,9 @@ class TestPad(unittest.TestCase): self.assertAlmostEqual(self.Pad1.Shape.Volume, 2.0) def testPadTwoDimensionsCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 1), (1, 1)) self.Doc.recompute() @@ -168,10 +169,10 @@ class TestPad(unittest.TestCase): self.Pad.Length = 1 self.Doc.recompute() # Make second pad on different plane and pad to face on first - self.PadSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad1') + self.PadSketch1 = self.Doc.addObject("Sketcher::SketchObject", "SketchPad1") self.Body.addObject(self.PadSketch1) - self.PadSketch1.MapMode = 'FlatFace' - self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PadSketch1.MapMode = "FlatFace" + self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PadSketch1, (0, 0), (1, 1)) self.Doc.recompute() @@ -186,20 +187,20 @@ class TestPad(unittest.TestCase): self.assertAlmostEqual(self.Pad1.Shape.Volume, 4.0) def testPadToConcaveCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make a half revolution - self.RevolutionSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.RevolutionSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.RevolutionSketch) TestSketcherApp.CreateRectangleSketch(self.RevolutionSketch, (9, 0), (10, 5)) self.Doc.recompute() self.Revolution = self.Doc.addObject("PartDesign::Revolution", "Revolution") self.Body.addObject(self.Revolution) self.Revolution.Profile = self.RevolutionSketch - self.Revolution.ReferenceAxis = (self.RevolutionSketch, ['V_Axis']) + self.Revolution.ReferenceAxis = (self.RevolutionSketch, ["V_Axis"]) self.Revolution.Angle = 180 self.Doc.recompute() # Make a sketch and pad to first - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (1, 1)) @@ -213,9 +214,9 @@ class TestPad(unittest.TestCase): self.assertAlmostEqual(self.Pad.Shape.Volume, 2208.0963, places=4) def testPadToShapeCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 1), (1, 1)) self.Doc.recompute() @@ -225,12 +226,12 @@ class TestPad(unittest.TestCase): self.Pad.Length = 1 self.Doc.recompute() # Make second pad on different plane and pad to first - self.PadSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad1') + self.PadSketch1 = self.Doc.addObject("Sketcher::SketchObject", "SketchPad1") self.Body.addObject(self.PadSketch1) - self.PadSketch1.MapMode = 'FlatFace' - self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) - self.PadSketch1.AttachmentOffset.Rotation.Axis = Base.Vector(0,1,0) - self.PadSketch1.AttachmentOffset.Rotation.Angle = 0.436332 # 25° + self.PadSketch1.MapMode = "FlatFace" + self.PadSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) + self.PadSketch1.AttachmentOffset.Rotation.Axis = Base.Vector(0, 1, 0) + self.PadSketch1.AttachmentOffset.Rotation.Angle = 0.436332 # 25° self.PadSketch1.AttachmentOffset.Base.z = 1 self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PadSketch1, (1, 0), (1, 1)) @@ -243,9 +244,9 @@ class TestPad(unittest.TestCase): self.assertAlmostEqual(self.Pad1.Shape.Volume, 2.58787, places=4) def testPadToPlaneCustomDir(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") # Make first offset cube Pad - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 1), (1, 1)) self.Doc.recompute() @@ -254,13 +255,12 @@ class TestPad(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Type = 3 self.Doc.Pad.UseCustomVector = True - self.Doc.Pad.Direction = Base.Vector(0,1,1) - self.Pad.UpToFace = (self.Doc.XZ_Plane, ['']) + self.Doc.Pad.Direction = Base.Vector(0, 1, 1) + self.Pad.UpToFace = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() self.assertAlmostEqual(self.Pad.Shape.Volume, 1.5) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestPad") - #print ("omit closing document for debugging") - + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestPipe.py b/src/Mod/PartDesign/PartDesignTests/TestPipe.py index 5340cf346e..d4a1efe149 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestPipe.py +++ b/src/Mod/PartDesign/PartDesignTests/TestPipe.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest @@ -28,27 +28,30 @@ import TestSketcherApp App = FreeCAD + class TestPipe(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestPipe") def testSimpleAdditivePipeCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.ProfileSketch = self.Doc.addObject('Sketcher::SketchObject', 'ProfileSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.ProfileSketch = self.Doc.addObject("Sketcher::SketchObject", "ProfileSketch") self.Body.addObject(self.ProfileSketch) TestSketcherApp.CreateCircleSketch(self.ProfileSketch, (0, 0), 1) self.Doc.recompute() - self.SpineSketch = self.Doc.addObject('Sketcher::SketchObject', 'SpineSketch') + self.SpineSketch = self.Doc.addObject("Sketcher::SketchObject", "SpineSketch") self.Body.addObject(self.SpineSketch) - self.SpineSketch.MapMode = 'FlatFace' - self.SpineSketch.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.SpineSketch.MapMode = "FlatFace" + self.SpineSketch.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() - self.SpineSketch.addGeometry(Part.LineSegment(App.Vector(0.0,0.0,0),App.Vector(0,1,0)),False) - self.SpineSketch.addConstraint(Sketcher.Constraint('Coincident',0,1,-1,1)) - self.SpineSketch.addConstraint(Sketcher.Constraint('PointOnObject',0,2,-2)) - self.SpineSketch.addConstraint(Sketcher.Constraint('DistanceY',0,1,0,2,1)) + self.SpineSketch.addGeometry( + Part.LineSegment(App.Vector(0.0, 0.0, 0), App.Vector(0, 1, 0)), False + ) + self.SpineSketch.addConstraint(Sketcher.Constraint("Coincident", 0, 1, -1, 1)) + self.SpineSketch.addConstraint(Sketcher.Constraint("PointOnObject", 0, 2, -2)) + self.SpineSketch.addConstraint(Sketcher.Constraint("DistanceY", 0, 1, 0, 2, 1)) self.Doc.recompute() - self.AdditivePipe = self.Doc.addObject("PartDesign::AdditivePipe","AdditivePipe") + self.AdditivePipe = self.Doc.addObject("PartDesign::AdditivePipe", "AdditivePipe") self.Body.addObject(self.AdditivePipe) self.AdditivePipe.Profile = self.ProfileSketch self.AdditivePipe.Spine = self.SpineSketch @@ -56,22 +59,24 @@ class TestPipe(unittest.TestCase): self.assertAlmostEqual(self.AdditivePipe.Shape.Volume, 3.14159265) def testSimpleSubtractivePipeCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.ProfileSketch = self.Doc.addObject('Sketcher::SketchObject', 'ProfileSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.ProfileSketch = self.Doc.addObject("Sketcher::SketchObject", "ProfileSketch") self.Body.addObject(self.ProfileSketch) TestSketcherApp.CreateCircleSketch(self.ProfileSketch, (0, 0), 1) self.Doc.recompute() - self.SpineSketch = self.Doc.addObject('Sketcher::SketchObject', 'SpineSketch') + self.SpineSketch = self.Doc.addObject("Sketcher::SketchObject", "SpineSketch") self.Body.addObject(self.SpineSketch) - self.SpineSketch.MapMode = 'FlatFace' - self.SpineSketch.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.SpineSketch.MapMode = "FlatFace" + self.SpineSketch.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() - self.SpineSketch.addGeometry(Part.LineSegment(App.Vector(0.0,0.0,0),App.Vector(0,1,0)),False) - self.SpineSketch.addConstraint(Sketcher.Constraint('Coincident',0,1,-1,1)) - self.SpineSketch.addConstraint(Sketcher.Constraint('PointOnObject',0,2,-2)) - self.SpineSketch.addConstraint(Sketcher.Constraint('DistanceY',0,1,0,2,1)) + self.SpineSketch.addGeometry( + Part.LineSegment(App.Vector(0.0, 0.0, 0), App.Vector(0, 1, 0)), False + ) + self.SpineSketch.addConstraint(Sketcher.Constraint("Coincident", 0, 1, -1, 1)) + self.SpineSketch.addConstraint(Sketcher.Constraint("PointOnObject", 0, 2, -2)) + self.SpineSketch.addConstraint(Sketcher.Constraint("DistanceY", 0, 1, 0, 2, 1)) self.Doc.recompute() - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'PadSketch') + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "PadSketch") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (-5, -5), (10, 10)) self.Doc.recompute() @@ -80,7 +85,7 @@ class TestPipe(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 1.0 self.Doc.recompute() - self.SubtractivePipe = self.Doc.addObject("PartDesign::SubtractivePipe","SubtractivePipe") + self.SubtractivePipe = self.Doc.addObject("PartDesign::SubtractivePipe", "SubtractivePipe") self.Body.addObject(self.SubtractivePipe) self.SubtractivePipe.Profile = self.ProfileSketch self.SubtractivePipe.Spine = self.SpineSketch @@ -88,7 +93,6 @@ class TestPipe(unittest.TestCase): self.assertAlmostEqual(self.SubtractivePipe.Shape.Volume, 100 - 3.14159265) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestPipe") - #print ("omit closing document for debugging") - + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestPocket.py b/src/Mod/PartDesign/PartDesignTests/TestPocket.py index 52795c0dbc..fb52f604cf 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestPocket.py +++ b/src/Mod/PartDesign/PartDesignTests/TestPocket.py @@ -1,36 +1,37 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD import TestSketcherApp + class TestPocket(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestPocket") def testPocketDimensionCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'PadSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "PadSketch") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -40,7 +41,7 @@ class TestPocket(unittest.TestCase): self.Pad.Length = 1 self.Pad.Reversed = 1 self.Doc.recompute() - self.PocketSketch = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch) TestSketcherApp.CreateRectangleSketch(self.PocketSketch, (2.5, 2.5), (5, 5)) self.Doc.recompute() @@ -52,8 +53,8 @@ class TestPocket(unittest.TestCase): self.assertAlmostEqual(self.Pocket.Shape.Volume, 75.0) def testPocketThroughAllCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'PadSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "PadSketch") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -63,7 +64,7 @@ class TestPocket(unittest.TestCase): self.Pad.Length = 1 self.Pad.Reversed = 1 self.Doc.recompute() - self.PocketSketch = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch) TestSketcherApp.CreateRectangleSketch(self.PocketSketch, (2.5, 2.5), (5, 5)) self.Doc.recompute() @@ -72,10 +73,10 @@ class TestPocket(unittest.TestCase): self.Pocket.Profile = self.PocketSketch self.Pocket.Length = 1 self.Doc.recompute() - self.PocketSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch1 = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch1) - self.PocketSketch1.MapMode = 'FlatFace' - self.PocketSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PocketSketch1.MapMode = "FlatFace" + self.PocketSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PocketSketch1, (2.5, -0.75), (5, 0.50)) self.Doc.recompute() @@ -87,8 +88,8 @@ class TestPocket(unittest.TestCase): self.assertAlmostEqual(self.Pocket001.Shape.Volume, 62.5) def testPocketToFirstCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'PadSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "PadSketch") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -98,7 +99,7 @@ class TestPocket(unittest.TestCase): self.Pad.Length = 1 self.Pad.Reversed = 1 self.Doc.recompute() - self.PocketSketch = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch) TestSketcherApp.CreateRectangleSketch(self.PocketSketch, (2.5, 2.5), (5, 5)) self.Doc.recompute() @@ -107,10 +108,10 @@ class TestPocket(unittest.TestCase): self.Pocket.Profile = self.PocketSketch self.Pocket.Length = 1 self.Doc.recompute() - self.PocketSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch1 = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch1) - self.PocketSketch1.MapMode = 'FlatFace' - self.PocketSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PocketSketch1.MapMode = "FlatFace" + self.PocketSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PocketSketch1, (2.5, -1), (5, 1)) self.Doc.recompute() @@ -122,8 +123,8 @@ class TestPocket(unittest.TestCase): self.assertAlmostEqual(self.Pocket001.Shape.Volume, 62.5) def testPocketToFaceCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'PadSketch') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "PadSketch") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -133,7 +134,7 @@ class TestPocket(unittest.TestCase): self.Pad.Length = 1 self.Pad.Reversed = 1 self.Doc.recompute() - self.PocketSketch = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch) TestSketcherApp.CreateRectangleSketch(self.PocketSketch, (2.5, 2.5), (5, 5)) self.Doc.recompute() @@ -142,10 +143,10 @@ class TestPocket(unittest.TestCase): self.Pocket.Profile = self.PocketSketch self.Pocket.Length = 1 self.Doc.recompute() - self.PocketSketch1 = self.Doc.addObject('Sketcher::SketchObject', 'PocketSketch') + self.PocketSketch1 = self.Doc.addObject("Sketcher::SketchObject", "PocketSketch") self.Body.addObject(self.PocketSketch1) - self.PocketSketch1.MapMode = 'FlatFace' - self.PocketSketch1.AttachmentSupport = (self.Doc.XZ_Plane, ['']) + self.PocketSketch1.MapMode = "FlatFace" + self.PocketSketch1.AttachmentSupport = (self.Doc.XZ_Plane, [""]) self.Doc.recompute() TestSketcherApp.CreateRectangleSketch(self.PocketSketch1, (0, -1), (10, 1)) self.Doc.recompute() @@ -155,15 +156,17 @@ class TestPocket(unittest.TestCase): self.Pocket001.Type = 3 # Handle face-naming inconsistency in OCC < 7 self.FaceNumber = 7 - self.Pocket001.UpToFace = (self.Pocket, ["Face"+str(self.FaceNumber)]) + self.Pocket001.UpToFace = (self.Pocket, ["Face" + str(self.FaceNumber)]) self.Doc.recompute() - while (('Invalid' in self.Pocket001.State or round(self.Pocket001.Shape.Volume, 7) != 50.0) and self.FaceNumber < 11): + while ( + "Invalid" in self.Pocket001.State or round(self.Pocket001.Shape.Volume, 7) != 50.0 + ) and self.FaceNumber < 11: self.FaceNumber += 1 - self.Pocket001.UpToFace = (self.Pocket, ["Face"+str(self.FaceNumber)]) + self.Pocket001.UpToFace = (self.Pocket, ["Face" + str(self.FaceNumber)]) self.Doc.recompute() self.assertAlmostEqual(self.Pocket001.Shape.Volume, 50.0) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestPocket") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestPolarPattern.py b/src/Mod/PartDesign/PartDesignTests/TestPolarPattern.py index 7ef76a373c..68fe0a21f3 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestPolarPattern.py +++ b/src/Mod/PartDesign/PartDesignTests/TestPolarPattern.py @@ -1,44 +1,45 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD import TestSketcherApp + class TestPolarPattern(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestPolarPattern") def testXAxisPolarPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Originals = [self.Box] - self.PolarPattern.Axis = (self.Doc.X_Axis,[""]) + self.PolarPattern.Axis = (self.Doc.X_Axis, [""]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.PolarPattern.Refine = True @@ -49,16 +50,16 @@ class TestPolarPattern(unittest.TestCase): self.assertEqual(self.PolarPattern.Shape.ElementMapSize, 26) def testYAxisPolarPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Originals = [self.Box] - self.PolarPattern.Axis = (self.Doc.Y_Axis,[""]) + self.PolarPattern.Axis = (self.Doc.Y_Axis, [""]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.PolarPattern.Refine = True @@ -69,16 +70,16 @@ class TestPolarPattern(unittest.TestCase): self.assertEqual(self.PolarPattern.Shape.ElementMapSize, 26) def testZAxisPolarPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Originals = [self.Box] - self.PolarPattern.Axis = (self.Doc.Z_Axis,[""]) + self.PolarPattern.Axis = (self.Doc.Z_Axis, [""]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.PolarPattern.Refine = True @@ -89,8 +90,8 @@ class TestPolarPattern(unittest.TestCase): self.assertEqual(self.PolarPattern.Shape.ElementMapSize, 26) def testNormalSketchAxisPolarPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -99,9 +100,9 @@ class TestPolarPattern(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Originals = [self.Pad] - self.PolarPattern.Axis = (self.PadSketch,["N_Axis"]) + self.PolarPattern.Axis = (self.PadSketch, ["N_Axis"]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.PolarPattern.Refine = True @@ -112,8 +113,8 @@ class TestPolarPattern(unittest.TestCase): self.assertEqual(self.PolarPattern.Shape.ElementMapSize, 26) def testVerticalSketchAxisPolarPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -122,9 +123,9 @@ class TestPolarPattern(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Originals = [self.Pad] - self.PolarPattern.Axis = (self.PadSketch,["V_Axis"]) + self.PolarPattern.Axis = (self.PadSketch, ["V_Axis"]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.PolarPattern.Refine = True @@ -135,8 +136,8 @@ class TestPolarPattern(unittest.TestCase): self.assertEqual(self.PolarPattern.Shape.ElementMapSize, 26) def testHorizontalSketchAxisPolarPattern(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.PadSketch = self.Doc.addObject('Sketcher::SketchObject', 'SketchPad') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.PadSketch = self.Doc.addObject("Sketcher::SketchObject", "SketchPad") self.Body.addObject(self.PadSketch) TestSketcherApp.CreateRectangleSketch(self.PadSketch, (0, 0), (10, 10)) self.Doc.recompute() @@ -145,9 +146,9 @@ class TestPolarPattern(unittest.TestCase): self.Pad.Profile = self.PadSketch self.Pad.Length = 10 self.Doc.recompute() - self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern","PolarPattern") + self.PolarPattern = self.Doc.addObject("PartDesign::PolarPattern", "PolarPattern") self.PolarPattern.Originals = [self.Pad] - self.PolarPattern.Axis = (self.PadSketch,["H_Axis"]) + self.PolarPattern.Axis = (self.PadSketch, ["H_Axis"]) self.PolarPattern.Angle = 360 self.PolarPattern.Occurrences = 4 self.PolarPattern.Refine = True @@ -162,7 +163,6 @@ class TestPolarPattern(unittest.TestCase): self.assertEqual(self.PolarPattern.Shape.ElementMapSize, 26) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestPolarPattern") # print ("omit closing document for debugging") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestPrimitive.py b/src/Mod/PartDesign/PartDesignTests/TestPrimitive.py index 80402f2566..78a89c5c08 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestPrimitive.py +++ b/src/Mod/PartDesign/PartDesignTests/TestPrimitive.py @@ -1,58 +1,59 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** from math import pi, sqrt import unittest import FreeCAD + class TestPrimitive(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestPrimitive") def testPrimitiveBox(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Box.Length = 11 self.Box.Width = 11 self.Box.Height = 11 self.Body.addObject(self.Box) self.Doc.recompute() - self.Box001 = self.Doc.addObject('PartDesign::SubtractiveBox','Box001') + self.Box001 = self.Doc.addObject("PartDesign::SubtractiveBox", "Box001") self.Box001.Length = 10 self.Box001.Width = 10 self.Box001.Height = 10 self.Body.addObject(self.Box001) self.Doc.recompute() - self.assertAlmostEqual(self.Box001.Shape.Volume, 11**3-10**3) + self.assertAlmostEqual(self.Box001.Shape.Volume, 11**3 - 10**3) def testPrimitiveCylinder(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Cylinder = self.Doc.addObject('PartDesign::AdditiveCylinder','Cylinder') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Cylinder = self.Doc.addObject("PartDesign::AdditiveCylinder", "Cylinder") self.Cylinder.Radius = 11 self.Cylinder.Height = 10 self.Cylinder.Angle = 360 self.Body.addObject(self.Cylinder) self.Doc.recompute() - self.Cylinder001 = self.Doc.addObject('PartDesign::SubtractiveCylinder','Cylinder001') + self.Cylinder001 = self.Doc.addObject("PartDesign::SubtractiveCylinder", "Cylinder001") self.Cylinder001.Radius = 10 self.Cylinder001.Height = 10 self.Cylinder001.Angle = 360 @@ -61,55 +62,57 @@ class TestPrimitive(unittest.TestCase): self.assertAlmostEqual(self.Cylinder001.Shape.Volume, pi * 10 * (11**2 - 10**2)) def testPrimitiveSphere(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Sphere = self.Doc.addObject('PartDesign::AdditiveSphere','Sphere') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Sphere = self.Doc.addObject("PartDesign::AdditiveSphere", "Sphere") self.Sphere.Radius = 6 self.Body.addObject(self.Sphere) self.Doc.recompute() - self.Sphere001 = self.Doc.addObject('PartDesign::SubtractiveSphere','Sphere001') + self.Sphere001 = self.Doc.addObject("PartDesign::SubtractiveSphere", "Sphere001") self.Sphere001.Radius = 5 self.Body.addObject(self.Sphere001) self.Doc.recompute() - self.assertAlmostEqual(self.Sphere001.Shape.Volume, 4/3.0 * pi * (6**3 - 5**3)) + self.assertAlmostEqual(self.Sphere001.Shape.Volume, 4 / 3.0 * pi * (6**3 - 5**3)) def testPrimitiveCone(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Cone = self.Doc.addObject('PartDesign::AdditiveCone','Cone') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Cone = self.Doc.addObject("PartDesign::AdditiveCone", "Cone") self.Cone.Radius1 = 0 self.Cone.Radius2 = 4 self.Cone.Height = 10 self.Body.addObject(self.Cone) self.Doc.recompute() - self.Cone001 = self.Doc.addObject('PartDesign::SubtractiveCone','Cone') + self.Cone001 = self.Doc.addObject("PartDesign::SubtractiveCone", "Cone") self.Cone001.Radius1 = 0 self.Cone001.Radius2 = 3 self.Cone001.Height = 10 self.Body.addObject(self.Cone001) self.Doc.recompute() - self.assertAlmostEqual(self.Cone001.Shape.Volume, 1/3.0 * pi * 10 * (4**2 - 3**2)) + self.assertAlmostEqual(self.Cone001.Shape.Volume, 1 / 3.0 * pi * 10 * (4**2 - 3**2)) def testPrimitiveEllipsoid(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Ellipsoid = self.Doc.addObject('PartDesign::AdditiveEllipsoid','Ellipsoid') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Ellipsoid = self.Doc.addObject("PartDesign::AdditiveEllipsoid", "Ellipsoid") self.Ellipsoid.Radius1 = 2 self.Ellipsoid.Radius2 = 4 self.Body.addObject(self.Ellipsoid) self.Doc.recompute() - self.Ellipsoid001 = self.Doc.addObject('PartDesign::SubtractiveEllipsoid','Ellipsoid001') + self.Ellipsoid001 = self.Doc.addObject("PartDesign::SubtractiveEllipsoid", "Ellipsoid001") self.Ellipsoid001.Radius1 = 1.5 self.Ellipsoid001.Radius2 = 3 self.Body.addObject(self.Ellipsoid001) self.Doc.recompute() - self.assertAlmostEqual(self.Ellipsoid001.Shape.Volume, 4/3.0 * pi * (2*4**2 - 1.5*3**2), places=1) + self.assertAlmostEqual( + self.Ellipsoid001.Shape.Volume, 4 / 3.0 * pi * (2 * 4**2 - 1.5 * 3**2), places=1 + ) def testPrimitiveTorus(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Torus = self.Doc.addObject('PartDesign::AdditiveTorus','Torus') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Torus = self.Doc.addObject("PartDesign::AdditiveTorus", "Torus") self.Torus.Radius1 = 10 self.Torus.Radius2 = 4 self.Body.addObject(self.Torus) self.Doc.recompute() - self.Torus001 = self.Doc.addObject('PartDesign::SubtractiveTorus','Torus001') + self.Torus001 = self.Doc.addObject("PartDesign::SubtractiveTorus", "Torus001") self.Torus001.Radius1 = 10 self.Torus001.Radius2 = 3 self.Body.addObject(self.Torus001) @@ -117,31 +120,31 @@ class TestPrimitive(unittest.TestCase): self.assertAlmostEqual(self.Torus001.Shape.Volume, 2 * pi**2 * 10 * (4**2 - 3**2)) def testPrimitivePrism(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Prism = self.Doc.addObject('PartDesign::AdditivePrism','Prism') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Prism = self.Doc.addObject("PartDesign::AdditivePrism", "Prism") self.Prism.Polygon = 6 self.Prism.Circumradius = 4 self.Prism.Height = 10 self.Body.addObject(self.Prism) self.Doc.recompute() - self.Prism001 = self.Doc.addObject('PartDesign::SubtractivePrism','Prism001') + self.Prism001 = self.Doc.addObject("PartDesign::SubtractivePrism", "Prism001") self.Prism001.Polygon = 6 self.Prism001.Circumradius = 3 self.Prism001.Height = 10 self.Body.addObject(self.Prism001) self.Doc.recompute() - self.assertAlmostEqual(self.Prism001.Shape.Volume, 3*sqrt(3)/2.0 * 10 * (4**2 - 3**2)) + self.assertAlmostEqual(self.Prism001.Shape.Volume, 3 * sqrt(3) / 2.0 * 10 * (4**2 - 3**2)) def testPrimitiveWedge(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Wedge = self.Doc.addObject('PartDesign::AdditiveWedge','Wedge') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Wedge = self.Doc.addObject("PartDesign::AdditiveWedge", "Wedge") self.Wedge.X2min = 5 self.Wedge.X2max = 5 self.Wedge.Z2min = 0 self.Wedge.Z2max = 10 self.Body.addObject(self.Wedge) self.Doc.recompute() - self.Wedge001 = self.Doc.addObject('PartDesign::SubtractiveWedge','Wedge001') + self.Wedge001 = self.Doc.addObject("PartDesign::SubtractiveWedge", "Wedge001") self.Wedge001.Xmin = 1 self.Wedge001.Xmax = 9 self.Wedge001.Ymax = 9 @@ -151,10 +154,9 @@ class TestPrimitive(unittest.TestCase): self.Wedge001.Z2max = 10 self.Body.addObject(self.Wedge001) self.Doc.recompute() - self.assertAlmostEqual(self.Wedge001.Shape.Volume, 1/2.0 * (10*10 - 9*8) * 10) + self.assertAlmostEqual(self.Wedge001.Shape.Volume, 1 / 2.0 * (10 * 10 - 9 * 8) * 10) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestPrimitive") - #print ("omit closing document for debugging") - + # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestRevolve.py b/src/Mod/PartDesign/PartDesignTests/TestRevolve.py index ec218bd682..a70b522c01 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestRevolve.py +++ b/src/Mod/PartDesign/PartDesignTests/TestRevolve.py @@ -1,43 +1,44 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD + class TestRevolve(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestRevolve") def testRevolveFace(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.Revolution = self.Doc.addObject("PartDesign::Revolution","Revolution") + self.Revolution = self.Doc.addObject("PartDesign::Revolution", "Revolution") self.Revolution.Profile = (self.Box, ["Face6"]) - self.Revolution.ReferenceAxis = (self.Doc.Y_Axis,[""]) + self.Revolution.ReferenceAxis = (self.Doc.Y_Axis, [""]) self.Revolution.Angle = 180.0 self.Revolution.Reversed = 1 self.Body.addObject(self.Revolution) @@ -46,16 +47,16 @@ class TestRevolve(unittest.TestCase): self.assertIn(len(self.Revolution.Shape.Faces), (8, 10)) def testGrooveFace(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() - self.Groove = self.Doc.addObject("PartDesign::Groove","Groove") + self.Groove = self.Doc.addObject("PartDesign::Groove", "Groove") self.Groove.Profile = (self.Box, ["Face6"]) - self.Groove.ReferenceAxis = (self.Doc.X_Axis,[""]) + self.Groove.ReferenceAxis = (self.Doc.X_Axis, [""]) self.Groove.Angle = 180.0 self.Groove.Reversed = 1 self.Body.addObject(self.Groove) @@ -63,7 +64,6 @@ class TestRevolve(unittest.TestCase): self.assertEqual(len(self.Groove.Shape.Faces), 5) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestRevolve") # print ("omit closing document for debugging") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestShapeBinder.py b/src/Mod/PartDesign/PartDesignTests/TestShapeBinder.py index 87ab19b2b7..ea06d6f995 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestShapeBinder.py +++ b/src/Mod/PartDesign/PartDesignTests/TestShapeBinder.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import math @@ -27,30 +27,31 @@ from FreeCAD import Base import Part import Sketcher + class TestShapeBinder(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestShapeBinder") def testTwoBodyShapeBinderCase(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.Box.Length=1 - self.Box.Width=1 - self.Box.Height=1 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.Box.Length = 1 + self.Box.Width = 1 + self.Box.Height = 1 self.Body.addObject(self.Box) self.Doc.recompute() - self.Body001 = self.Doc.addObject('PartDesign::Body','Body001') - self.ShapeBinder = self.Doc.addObject('PartDesign::ShapeBinder','ShapeBinder') - self.ShapeBinder.Support = [(self.Box, 'Face1')] + self.Body001 = self.Doc.addObject("PartDesign::Body", "Body001") + self.ShapeBinder = self.Doc.addObject("PartDesign::ShapeBinder", "ShapeBinder") + self.ShapeBinder.Support = [(self.Box, "Face1")] self.Body001.addObject(self.ShapeBinder) self.Doc.recompute() - self.assertIn('Box', self.ShapeBinder.OutList[0].Label) - self.assertIn('Body001', self.ShapeBinder.InList[0].Label) + self.assertIn("Box", self.ShapeBinder.OutList[0].Label) + self.assertIn("Body001", self.ShapeBinder.InList[0].Label) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestShapeBinder") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") class TestSubShapeBinder(unittest.TestCase): @@ -62,67 +63,83 @@ class TestSubShapeBinder(unittest.TestCase): def testOffsetBinder(self): # See PR 7445 - body = self.Doc.addObject('PartDesign::Body','Body') - box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + body = self.Doc.addObject("PartDesign::Body", "Body") + box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") body.addObject(box) - box.Length=10.00000 - box.Width=10.00000 - box.Height=10.00000 + box.Length = 10.00000 + box.Width = 10.00000 + box.Height = 10.00000 - binder = body.newObject('PartDesign::SubShapeBinder','Binder') - binder.Support=[(box, ("Edge2", "Edge12", "Edge6", "Edge10"))] + binder = body.newObject("PartDesign::SubShapeBinder", "Binder") + binder.Support = [(box, ("Edge2", "Edge12", "Edge6", "Edge10"))] self.Doc.recompute() self.assertAlmostEqual(binder.Shape.Length, 40) - binder.OffsetJoinType="Tangent" + binder.OffsetJoinType = "Tangent" binder.Offset = 5.00000 self.Doc.recompute() self.assertAlmostEqual(binder.Shape.Length, 80) def testBinderBeforeOrAfterPad(self): - """ Test case for PR #8763 """ - body = self.Doc.addObject('PartDesign::Body','Body') - sketch = body.newObject('Sketcher::SketchObject','Sketch') - sketch.AttachmentSupport = (self.Doc.XZ_Plane,['']) - sketch.MapMode = 'FlatFace' + """Test case for PR #8763""" + body = self.Doc.addObject("PartDesign::Body", "Body") + sketch = body.newObject("Sketcher::SketchObject", "Sketch") + sketch.AttachmentSupport = (self.Doc.XZ_Plane, [""]) + sketch.MapMode = "FlatFace" self.Doc.recompute() geoList = [] - geoList.append(Part.LineSegment(Base.Vector(-21.762587,19.904083,0),Base.Vector(32.074337,19.904083,0))) - geoList.append(Part.LineSegment(Base.Vector(32.074337,19.904083,0),Base.Vector(32.074337,-27.458027,0))) - geoList.append(Part.LineSegment(Base.Vector(32.074337,-27.458027,0),Base.Vector(-21.762587,-27.458027,0))) - geoList.append(Part.LineSegment(Base.Vector(-21.762587,-27.458027,0),Base.Vector(-21.762587,19.904083,0))) - sketch.addGeometry(geoList,False) + geoList.append( + Part.LineSegment( + Base.Vector(-21.762587, 19.904083, 0), Base.Vector(32.074337, 19.904083, 0) + ) + ) + geoList.append( + Part.LineSegment( + Base.Vector(32.074337, 19.904083, 0), Base.Vector(32.074337, -27.458027, 0) + ) + ) + geoList.append( + Part.LineSegment( + Base.Vector(32.074337, -27.458027, 0), Base.Vector(-21.762587, -27.458027, 0) + ) + ) + geoList.append( + Part.LineSegment( + Base.Vector(-21.762587, -27.458027, 0), Base.Vector(-21.762587, 19.904083, 0) + ) + ) + sketch.addGeometry(geoList, False) conList = [] - conList.append(Sketcher.Constraint('Coincident',0,2,1,1)) - conList.append(Sketcher.Constraint('Coincident',1,2,2,1)) - conList.append(Sketcher.Constraint('Coincident',2,2,3,1)) - conList.append(Sketcher.Constraint('Coincident',3,2,0,1)) - conList.append(Sketcher.Constraint('Horizontal',0)) - conList.append(Sketcher.Constraint('Horizontal',2)) - conList.append(Sketcher.Constraint('Vertical',1)) - conList.append(Sketcher.Constraint('Vertical',3)) + conList.append(Sketcher.Constraint("Coincident", 0, 2, 1, 1)) + conList.append(Sketcher.Constraint("Coincident", 1, 2, 2, 1)) + conList.append(Sketcher.Constraint("Coincident", 2, 2, 3, 1)) + conList.append(Sketcher.Constraint("Coincident", 3, 2, 0, 1)) + conList.append(Sketcher.Constraint("Horizontal", 0)) + conList.append(Sketcher.Constraint("Horizontal", 2)) + conList.append(Sketcher.Constraint("Vertical", 1)) + conList.append(Sketcher.Constraint("Vertical", 3)) sketch.addConstraint(conList) del geoList, conList self.Doc.recompute() - binder1 = body.newObject('PartDesign::SubShapeBinder','Binder') + binder1 = body.newObject("PartDesign::SubShapeBinder", "Binder") binder1.Support = sketch self.Doc.recompute() - pad = body.newObject('PartDesign::Pad','Pad') + pad = body.newObject("PartDesign::Pad", "Pad") pad.Profile = sketch pad.Length = 10 self.Doc.recompute() - pad.ReferenceAxis = (sketch,['N_Axis']) + pad.ReferenceAxis = (sketch, ["N_Axis"]) sketch.Visibility = False self.Doc.recompute() - binder2 = body.newObject('PartDesign::SubShapeBinder','Binder001') + binder2 = body.newObject("PartDesign::SubShapeBinder", "Binder001") binder2.Support = [pad, "Sketch."] self.Doc.recompute() @@ -130,15 +147,15 @@ class TestSubShapeBinder(unittest.TestCase): self.assertAlmostEqual(binder1.Shape.BoundBox.YLength, binder2.Shape.BoundBox.YLength, 2) self.assertAlmostEqual(binder1.Shape.BoundBox.ZLength, binder2.Shape.BoundBox.ZLength, 2) - nor1 = binder1.Shape.Face1.normalAt(0,0) - nor2 = binder2.Shape.Face1.normalAt(0,0) + nor1 = binder1.Shape.Face1.normalAt(0, 0) + nor2 = binder2.Shape.Face1.normalAt(0, 0) self.assertAlmostEqual(nor1.getAngle(nor2), 0.0, 2) def testBinderWithRevolution(self): doc = self.Doc - body = doc.addObject('PartDesign::Body', 'Body') + body = doc.addObject("PartDesign::Body", "Body") doc.recompute() - sketch = body.newObject('Sketcher::SketchObject', 'Sketch') + sketch = body.newObject("Sketcher::SketchObject", "Sketch") geoList = [] geoList.append(Part.LineSegment(Base.Vector(10, 10, 0), Base.Vector(30, 10, 0))) geoList.append(Part.LineSegment(Base.Vector(30, 10, 0), Base.Vector(30, 15, 0))) @@ -147,22 +164,27 @@ class TestSubShapeBinder(unittest.TestCase): sketch.addGeometry(geoList, False) del geoList constraintList = [] - constraintList.append(Sketcher.Constraint('Coincident', 0, 2, 1, 1)) - constraintList.append(Sketcher.Constraint('Coincident', 1, 2, 2, 1)) - constraintList.append(Sketcher.Constraint('Coincident', 2, 2, 3, 1)) - constraintList.append(Sketcher.Constraint('Coincident', 3, 2, 0, 1)) - constraintList.append(Sketcher.Constraint('Horizontal', 0)) - constraintList.append(Sketcher.Constraint('Horizontal', 2)) - constraintList.append(Sketcher.Constraint('Vertical', 1)) - constraintList.append(Sketcher.Constraint('Vertical', 3)) + constraintList.append(Sketcher.Constraint("Coincident", 0, 2, 1, 1)) + constraintList.append(Sketcher.Constraint("Coincident", 1, 2, 2, 1)) + constraintList.append(Sketcher.Constraint("Coincident", 2, 2, 3, 1)) + constraintList.append(Sketcher.Constraint("Coincident", 3, 2, 0, 1)) + constraintList.append(Sketcher.Constraint("Horizontal", 0)) + constraintList.append(Sketcher.Constraint("Horizontal", 2)) + constraintList.append(Sketcher.Constraint("Vertical", 1)) + constraintList.append(Sketcher.Constraint("Vertical", 3)) sketch.addConstraint(constraintList) del constraintList doc.recompute() - binder = body.newObject('PartDesign::SubShapeBinder', 'Binder') + binder = body.newObject("PartDesign::SubShapeBinder", "Binder") binder.Support = sketch - revolution = body.newObject('PartDesign::Revolution', 'Revolution') - revolution.Profile = (binder, ['', ]) - revolution.ReferenceAxis = (doc.getObject('Y_Axis'), ['']) + revolution = body.newObject("PartDesign::Revolution", "Revolution") + revolution.Profile = ( + binder, + [ + "", + ], + ) + revolution.ReferenceAxis = (doc.getObject("Y_Axis"), [""]) revolution.Angle = 360.0 revolution.Reversed = 1 doc.recompute() diff --git a/src/Mod/PartDesign/PartDesignTests/TestSketch.py b/src/Mod/PartDesign/PartDesignTests/TestSketch.py index 844bf04974..67e093e5a3 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestSketch.py +++ b/src/Mod/PartDesign/PartDesignTests/TestSketch.py @@ -1,29 +1,31 @@ -#*************************************************************************** -#* Copyright (c) 2024 Werner Mayer * -#* * -#* This file is part of FreeCAD. * -#* * -#* FreeCAD is free software: you can redistribute it and/or modify it * -#* under the terms of the GNU Lesser General Public License as * -#* published by the Free Software Foundation, either version 2.1 of the * -#* License, or (at your option) any later version. * -#* * -#* FreeCAD 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 * -#* Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Lesser General Public * -#* License along with FreeCAD. If not, see * -#* . * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2024 Werner Mayer * +# * * +# * This file is part of FreeCAD. * +# * * +# * FreeCAD is free software: you can redistribute it and/or modify it * +# * under the terms of the GNU Lesser General Public License as * +# * published by the Free Software Foundation, either version 2.1 of the * +# * License, or (at your option) any later version. * +# * * +# * FreeCAD 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with FreeCAD. If not, see * +# * . * +# * * +# *************************************************************************** import unittest import FreeCAD """ Test transaction interaction """ + + class TestSketch(unittest.TestCase): def setUp(self): self.doc = FreeCAD.newDocument("PartDesignTestSketch") @@ -36,32 +38,32 @@ class TestSketch(unittest.TestCase): self.doc.recompute() self.doc.openTransaction("Create sketch") - body = self.doc.addObject('PartDesign::Body', 'Body') - plane = self.doc.getObject('XY_Plane') + body = self.doc.addObject("PartDesign::Body", "Body") + plane = self.doc.getObject("XY_Plane") self.doc.commitTransaction() self.doc.openTransaction("Rename object") box.Label = "Object" self.doc.commitTransaction() - sketch = body.newObject('Sketcher::SketchObject', 'Sketch') - sketch.AttachmentSupport = (plane, ['']) - sketch.MapMode = 'FlatFace' + sketch = body.newObject("Sketcher::SketchObject", "Sketch") + sketch.AttachmentSupport = (plane, [""]) + sketch.MapMode = "FlatFace" self.doc.recompute() self.assertEqual(sketch.InList, [body]) self.assertEqual(sketch.OutList, [plane]) sketch.AttachmentSupport == [(plane, ("",))] - self.doc.undo() # undo renaming - self.doc.undo() # undo body creation - self.doc.undo() # undo box creation + self.doc.undo() # undo renaming + self.doc.undo() # undo body creation + self.doc.undo() # undo box creation self.doc.openTransaction("Remove sketch") self.doc.removeObject(sketch.Name) self.doc.commitTransaction() - self.doc.undo() # undo removal + self.doc.undo() # undo removal self.assertEqual(sketch.InList, []) self.assertEqual(sketch.OutList, []) @@ -74,28 +76,27 @@ class TestSketch(unittest.TestCase): self.doc.recompute() self.doc.openTransaction("Create sketch") - body = self.doc.addObject('PartDesign::Body', 'Body') - plane = self.doc.getObject('XY_Plane') + body = self.doc.addObject("PartDesign::Body", "Body") + plane = self.doc.getObject("XY_Plane") self.doc.commitTransaction() self.doc.openTransaction("Rename object") box.Label = "Object" self.doc.commitTransaction() - sketch = body.newObject('Sketcher::SketchObject', 'Sketch') - sketch.AttachmentSupport = (plane, ['']) - sketch.MapMode = 'FlatFace' + sketch = body.newObject("Sketcher::SketchObject", "Sketch") + sketch.AttachmentSupport = (plane, [""]) + sketch.MapMode = "FlatFace" self.doc.recompute() sketch.OutList sketch.AttachmentSupport - self.doc.undo() # undo renaming - self.doc.undo() # undo body creation - self.doc.undo() # undo box creation + self.doc.undo() # undo renaming + self.doc.undo() # undo body creation + self.doc.undo() # undo box creation self.doc.DependencyGraph def tearDown(self): FreeCAD.closeDocument("PartDesignTestSketch") - diff --git a/src/Mod/PartDesign/PartDesignTests/TestThickness.py b/src/Mod/PartDesign/PartDesignTests/TestThickness.py index 9338c97a3e..987e12185f 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestThickness.py +++ b/src/Mod/PartDesign/PartDesignTests/TestThickness.py @@ -1,39 +1,40 @@ -#*************************************************************************** -#* Copyright (c) 2011 Juergen Riegel * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2011 Juergen Riegel * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import unittest import FreeCAD + class TestThickness(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestThickness") def testReversedThickness(self): - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) - self.Box.Length=10.00 - self.Box.Width=10.00 - self.Box.Height=10.00 + self.Box.Length = 10.00 + self.Box.Width = 10.00 + self.Box.Height = 10.00 self.Doc.recompute() self.Thickness = self.Doc.addObject("PartDesign::Thickness", "Thickness") self.Thickness.Base = (self.Box, ["Face1"]) @@ -48,9 +49,9 @@ class TestThickness(unittest.TestCase): self.assertEqual(len(self.Thickness.Shape.Faces), 11) # 6 faces of outer box + 4 faces of inner box + 16 edges outer, 8 inner, # + 8 vertexes outer, 8 inner + 1 solid = 51 - self.assertEqual(self.Thickness.Shape.ElementMapSize,51) + self.assertEqual(self.Thickness.Shape.ElementMapSize, 51) def tearDown(self): - #closing doc + # closing doc FreeCAD.closeDocument("PartDesignTestThickness") # print ("omit closing document for debugging") diff --git a/src/Mod/PartDesign/PartDesignTests/TestTopologicalNamingProblem.py b/src/Mod/PartDesign/PartDesignTests/TestTopologicalNamingProblem.py index 11f3c6d0dd..2a91412723 100644 --- a/src/Mod/PartDesign/PartDesignTests/TestTopologicalNamingProblem.py +++ b/src/Mod/PartDesign/PartDesignTests/TestTopologicalNamingProblem.py @@ -21,7 +21,7 @@ # * * # *************************************************************************** -""" Tests related to the Topological Naming Problem """ +"""Tests related to the Topological Naming Problem""" import os import math @@ -115,13 +115,9 @@ class TestTopologicalNamingProblem(unittest.TestCase): self.assertTrue(self.Pad1.isValid()) if self.Body.Shape.ElementMapVersion == "": # Should be '4' as of Mar 2023. - self.assertFalse( - self.Pad2.isValid() - ) # TNP problem is present without ElementMaps + self.assertFalse(self.Pad2.isValid()) # TNP problem is present without ElementMaps else: - self.assertTrue( - self.Pad2.isValid() - ) # TNP problem is not present with ElementMaps + self.assertTrue(self.Pad2.isValid()) # TNP problem is not present with ElementMaps def testPartDesignElementMapSketch(self): """Test that creating a sketch results in a correct element map.""" @@ -153,9 +149,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): if App.GuiUp: mat = App.Material() mat.AmbientColor = (128, 0, 0) - box1.ViewObject.ShapeAppearance = ( - mat # Change color ( material ) for at least one - ) + box1.ViewObject.ShapeAppearance = mat # Change color ( material ) for at least one box2 = doc.addObject("Part::Box", "Box001") box3 = doc.addObject("Part::Box", "Box002") cyl1 = doc.addObject("Part::Cylinder", "Cylinder") @@ -482,9 +476,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): if body.Shape.ElementMapVersion == "": # Should be '4' as of Mar 2023. return # Act - subellipsoid = self.Doc.addObject( - "PartDesign::SubtractiveEllipsoid", "Ellipsoid" - ) + subellipsoid = self.Doc.addObject("PartDesign::SubtractiveEllipsoid", "Ellipsoid") subellipsoid.BaseFeature = box body.addObject(subellipsoid) self.Doc.recompute() @@ -567,15 +559,11 @@ class TestTopologicalNamingProblem(unittest.TestCase): self.assertEqual(body.Shape.childShapes()[0].ElementMapSize, 30) # The pad self.assertEqual(body.Shape.ElementMapSize, 26) self.assertEqual(sketch.Shape.ElementMapSize, 12) - self.assertEqual( - pad.Shape.ElementMapSize, 30 - ) # pad has the 26 plus the 4 original + self.assertEqual(pad.Shape.ElementMapSize, 30) # pad has the 26 plus the 4 original self.assertNotEqual( pad.Shape.ElementReverseMap["Vertex1"], "Vertex1" ) # NewName, not OldName - self.assertEqual( - self.countFacesEdgesVertexes(pad.Shape.ElementReverseMap), (6, 12, 8) - ) + self.assertEqual(self.countFacesEdgesVertexes(pad.Shape.ElementReverseMap), (6, 12, 8)) # Todo: Offer a way to turn on hashing and check that with a # starting # Pad -> Extrusion -> makes compounds and does booleans, thus the resulting newName element maps @@ -585,32 +573,32 @@ class TestTopologicalNamingProblem(unittest.TestCase): # App.KeepTestDoc = True # Uncomment this if you want to keep the test document to examine self.Doc.UseHasher = False # Arrange - body = self.Doc.addObject('PartDesign::Body', 'Body') - sketch = self.Doc.addObject('Sketcher::SketchObject', 'Sketch') + body = self.Doc.addObject("PartDesign::Body", "Body") + sketch = self.Doc.addObject("Sketcher::SketchObject", "Sketch") TestSketcherApp.CreateRectangleSketch(sketch, (0, 1), (3, 2)) # (pt), (w,l) body.addObject(sketch) self.Doc.recompute() - pad = self.Doc.addObject('PartDesign::Pad', 'Pad') + pad = self.Doc.addObject("PartDesign::Pad", "Pad") pad.Profile = sketch pad.Length = 3 body.addObject(pad) self.Doc.recompute() - sketch2 = self.Doc.addObject('Sketcher::SketchObject', 'Sketch001') + sketch2 = self.Doc.addObject("Sketcher::SketchObject", "Sketch001") TestSketcherApp.CreateRectangleSketch(sketch2, (2, -3), (1, 2)) # (pt), (w,l) sketch2.AttachmentSupport = (pad, ["Face5"]) - sketch2.MapMode = 'FlatFace' + sketch2.MapMode = "FlatFace" body.addObject(sketch2) self.Doc.recompute() - revolution = self.Doc.addObject('PartDesign::Revolution', 'Revolution') - revolution.ReferenceAxis = (sketch2, ['V_Axis']) + revolution = self.Doc.addObject("PartDesign::Revolution", "Revolution") + revolution.ReferenceAxis = (sketch2, ["V_Axis"]) revolution.Reversed = 1 revolution.Profile = sketch2 - revolution.Angle=180 + revolution.Angle = 180 revolution.Refine = True body.addObject(revolution) - volume = (math.pi * 3 * 3 - math.pi * 2 * 2) * 2 / 2 - padVolume = 3 * 3 * 2 # 50.26548245743668 + volume = (math.pi * 3 * 3 - math.pi * 2 * 2) * 2 / 2 + padVolume = 3 * 3 * 2 # 50.26548245743668 # Act self.Doc.recompute() # Assert the Shape is correct @@ -620,10 +608,11 @@ class TestTopologicalNamingProblem(unittest.TestCase): # Assert the element map is correct self.assertEqual(body.Shape.childShapes()[0].ElementMapSize, 46) self.assertEqual(revolution.Shape.ElementMapSize, 46) - self.assertEqual(self.countFacesEdgesVertexes(revolution.Shape.ElementReverseMap), - (9, 21, 14)) - self.assertEqual( revolution.Shape.ElementReverseMap["Vertex9"][1].count(";"), 3) - self.assertEqual( revolution.Shape.ElementReverseMap["Face9"].count(";"), 19) + self.assertEqual( + self.countFacesEdgesVertexes(revolution.Shape.ElementReverseMap), (9, 21, 14) + ) + self.assertEqual(revolution.Shape.ElementReverseMap["Vertex9"][1].count(";"), 3) + self.assertEqual(revolution.Shape.ElementReverseMap["Face9"].count(";"), 19) ### This test has been removed because FeatureRevolution generates improper element maps when the user select the # UpToFace mode. That behavior seems to be the fault of OpenCASCADE itself, and we need to rewrite that section @@ -655,40 +644,68 @@ class TestTopologicalNamingProblem(unittest.TestCase): def testPartDesignBinderRevolution(self): doc = self.Doc - body = doc.addObject('PartDesign::Body', 'Body') - sketch = body.newObject('Sketcher::SketchObject', 'Sketch') - sketch.AttachmentSupport = (doc.getObject('XY_Plane'), ['']) - sketch.MapMode = 'FlatFace' + body = doc.addObject("PartDesign::Body", "Body") + sketch = body.newObject("Sketcher::SketchObject", "Sketch") + sketch.AttachmentSupport = (doc.getObject("XY_Plane"), [""]) + sketch.MapMode = "FlatFace" doc.recompute() geoList = [] - geoList.append(Part.LineSegment(App.Vector(-44.107212, 34.404858, 0.000000), App.Vector(-44.107212, 9.881049, 0.000000))) - geoList.append(Part.LineSegment(App.Vector(-44.107212, 9.881049, 0.0000000), App.Vector(-10.297691, 9.881049, 0.000000))) - geoList.append(Part.LineSegment(App.Vector(-10.297691, 9.881049, 0.0000000), App.Vector(-10.297691, 34.404858, 0.00000))) - geoList.append(Part.LineSegment(App.Vector(-10.297691, 34.404858, 0.000000), App.Vector(-44.107212, 34.404858, 0.00000))) + geoList.append( + Part.LineSegment( + App.Vector(-44.107212, 34.404858, 0.000000), + App.Vector(-44.107212, 9.881049, 0.000000), + ) + ) + geoList.append( + Part.LineSegment( + App.Vector(-44.107212, 9.881049, 0.0000000), + App.Vector(-10.297691, 9.881049, 0.000000), + ) + ) + geoList.append( + Part.LineSegment( + App.Vector(-10.297691, 9.881049, 0.0000000), + App.Vector(-10.297691, 34.404858, 0.00000), + ) + ) + geoList.append( + Part.LineSegment( + App.Vector(-10.297691, 34.404858, 0.000000), + App.Vector(-44.107212, 34.404858, 0.00000), + ) + ) sketch.addGeometry(geoList, False) del geoList constraintList = [] - constraintList.append(Sketcher.Constraint('Coincident', 0, 2, 1, 1)) - constraintList.append(Sketcher.Constraint('Coincident', 1, 2, 2, 1)) - constraintList.append(Sketcher.Constraint('Coincident', 2, 2, 3, 1)) - constraintList.append(Sketcher.Constraint('Coincident', 3, 2, 0, 1)) - constraintList.append(Sketcher.Constraint('Vertical', 0)) - constraintList.append(Sketcher.Constraint('Vertical', 2)) - constraintList.append(Sketcher.Constraint('Horizontal', 1)) - constraintList.append(Sketcher.Constraint('Horizontal', 3)) + constraintList.append(Sketcher.Constraint("Coincident", 0, 2, 1, 1)) + constraintList.append(Sketcher.Constraint("Coincident", 1, 2, 2, 1)) + constraintList.append(Sketcher.Constraint("Coincident", 2, 2, 3, 1)) + constraintList.append(Sketcher.Constraint("Coincident", 3, 2, 0, 1)) + constraintList.append(Sketcher.Constraint("Vertical", 0)) + constraintList.append(Sketcher.Constraint("Vertical", 2)) + constraintList.append(Sketcher.Constraint("Horizontal", 1)) + constraintList.append(Sketcher.Constraint("Horizontal", 3)) sketch.addConstraint(constraintList) del constraintList doc.recompute() - binder = body.newObject('PartDesign::ShapeBinder','ShapeBinder') - binder.Support = [sketch, (''),] + binder = body.newObject("PartDesign::ShapeBinder", "ShapeBinder") + binder.Support = [ + sketch, + (""), + ] binder.Visibility = False doc.recompute() - revolve = body.newObject('PartDesign::Revolution','Revolution') - revolve.Profile = (doc.getObject('ShapeBinder'), ['',]) - revolve.ReferenceAxis = (doc.getObject('Y_Axis'), ['']) + revolve = body.newObject("PartDesign::Revolution", "Revolution") + revolve.Profile = ( + doc.getObject("ShapeBinder"), + [ + "", + ], + ) + revolve.ReferenceAxis = (doc.getObject("Y_Axis"), [""]) revolve.Angle = 360.0 doc.recompute() self.assertTrue(revolve.isValid()) @@ -720,9 +737,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): revMap = body.Shape.ElementReverseMap self.assertNotEqual(loft.Shape.ElementReverseMap["Vertex1"], "Vertex1") self.assertNotEqual(revMap["Vertex1"], "Vertex1") - self.assertEqual( - self.countFacesEdgesVertexes(loft.Shape.ElementReverseMap), (6, 12, 8) - ) + self.assertEqual(self.countFacesEdgesVertexes(loft.Shape.ElementReverseMap), (6, 12, 8)) volume = 7.0 self.assertAlmostEqual(loft.Shape.Volume, volume) @@ -830,9 +845,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): self.assertNotEqual( pocket.Shape.ElementReverseMap["Vertex1"], "Vertex1" ) # NewName, not OldName - self.assertEqual( - self.countFacesEdgesVertexes(pocket.Shape.ElementReverseMap), (11, 24, 16) - ) + self.assertEqual(self.countFacesEdgesVertexes(pocket.Shape.ElementReverseMap), (11, 24, 16)) volume = 1000 - 5 * 1 * 1 self.assertAlmostEqual(pocket.Shape.Volume, volume) @@ -860,10 +873,10 @@ class TestTopologicalNamingProblem(unittest.TestCase): self.assertEqual(body.Shape.childShapes()[0].ElementMapSize, 32) self.assertEqual(body.Shape.ElementMapSize, 32) self.assertEqual(sketch.Shape.ElementMapSize, 2) - self.assertNotEqual(body.Shape.ElementReverseMap['Vertex1'],"Vertex1") # NewName, not OldName - self.assertEqual( - self.countFacesEdgesVertexes(body.Shape.ElementReverseMap), (7, 15, 10) - ) + self.assertNotEqual( + body.Shape.ElementReverseMap["Vertex1"], "Vertex1" + ) # NewName, not OldName + self.assertEqual(self.countFacesEdgesVertexes(body.Shape.ElementReverseMap), (7, 15, 10)) volume = 1000 - 10 * math.pi * 3 * 3 self.assertAlmostEqual(hole.Shape.Volume, volume) @@ -885,9 +898,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): if body.Shape.ElementMapVersion == "": # Should be '4' as of Mar 2023. return # Assert - revMap = ( - groove.Shape.ElementReverseMap - ) # body.Shape.childShapes()[0].ElementReverseMap + revMap = groove.Shape.ElementReverseMap # body.Shape.childShapes()[0].ElementReverseMap self.assertEqual(self.countFacesEdgesVertexes(revMap), (5, 9, 6)) volume = 785.3981633974482 # TODO: math formula to calc this. Maybe make a sketch as the Profile. self.assertAlmostEqual(groove.Shape.Volume, volume) @@ -913,9 +924,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): if body.Shape.ElementMapVersion == "": # Should be '4' as of Mar 2023. return # Assert - revMap = ( - loft.Shape.ElementReverseMap - ) # body.Shape.childShapes()[0].ElementReverseMap + revMap = loft.Shape.ElementReverseMap # body.Shape.childShapes()[0].ElementReverseMap self.assertEqual(self.countFacesEdgesVertexes(revMap), (11, 24, 16)) volume = 993 # TODO: math formula to calc this. self.assertAlmostEqual(loft.Shape.Volume, volume) @@ -1070,9 +1079,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") if body.Shape.ElementMapVersion == "": # Skip without element maps. return - multitransform = self.Doc.addObject( - "PartDesign::MultiTransform", "MultiTransform" - ) + multitransform = self.Doc.addObject("PartDesign::MultiTransform", "MultiTransform") scaled = self.Doc.addObject("PartDesign::Scaled", "Scaled") scaled.Factor = 2 scaled.Occurrences = 2 @@ -1107,9 +1114,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): # Arrange body = self.Doc.addObject("PartDesign::Body", "Body") box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") - subshapebinder = self.Doc.addObject( - "PartDesign::SubShapeBinder", "SubShapeBinder" - ) + subshapebinder = self.Doc.addObject("PartDesign::SubShapeBinder", "SubShapeBinder") if body.Shape.ElementMapVersion == "": # Skip without element maps. return # Act / Assert @@ -1136,9 +1141,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): return # Assert self.assertEqual(sketch.Shape.ElementMapSize, 12) - self.assertEqual( - pad.Shape.ElementMapSize, 30 - ) # The sketch plus the pad in the map + self.assertEqual(pad.Shape.ElementMapSize, 30) # The sketch plus the pad in the map # TODO: differing results between main and LS3 on these values. Does it matter? # self.assertEqual(body.Shape.ElementMapSize,0) # 8? # self.assertEqual(body.Shape.ElementMapSize,30) # 26 @@ -1365,9 +1368,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): doc.getObject("TNP_Test_Body_SubShape").Label = "TNP_Test_Body_SubShape" doc.recompute() - doc.getObject("TNP_Test_Body_SubShape").newObject( - "Sketcher::SketchObject", "Sketch" - ) + doc.getObject("TNP_Test_Body_SubShape").newObject("Sketcher::SketchObject", "Sketch") doc.Sketch.AttachmentSupport = (doc.getObject("XY_Plane"), [""]) doc.Sketch.MapMode = "FlatFace" doc.recompute() @@ -1447,9 +1448,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): ) obj.Support = (doc.getObject("TNP_Test_Body_SubShape"), ["Face6"]) doc.recompute() - doc.getObject("TNP_Test_Body_Second").newObject( - "Sketcher::SketchObject", "Sketch001" - ) + doc.getObject("TNP_Test_Body_Second").newObject("Sketcher::SketchObject", "Sketch001") doc.getObject("Sketch001").AttachmentSupport = ( doc.getObject("ShapeBinder"), [""], @@ -1619,9 +1618,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): doc.addObject("PartDesign::Body", "Body001") doc.getObject("Body001").Label = "Body" doc.recompute() - binder = doc.getObject("Body001").newObject( - "PartDesign::SubShapeBinder", "Binder" - ) + binder = doc.getObject("Body001").newObject("PartDesign::SubShapeBinder", "Binder") binder.Support = self.Body doc.getObject("Body001").newObject("Sketcher::SketchObject", "Sketch001") doc.getObject("Sketch001").AttachmentSupport = ( @@ -1754,18 +1751,10 @@ class TestTopologicalNamingProblem(unittest.TestCase): 11, ) geoList = [] - geoList.append( - Part.LineSegment(App.Vector(x1, y1, 0.0), App.Vector(x1, y2, 0.0)) - ) - geoList.append( - Part.LineSegment(App.Vector(x1, y2, 0.0), App.Vector(x2, y2, 0.0)) - ) - geoList.append( - Part.LineSegment(App.Vector(x2, y2, 0.0), App.Vector(x2, y1, 0.0)) - ) - geoList.append( - Part.LineSegment(App.Vector(x2, y1, 0.0), App.Vector(x1, y1, 0.0)) - ) + geoList.append(Part.LineSegment(App.Vector(x1, y1, 0.0), App.Vector(x1, y2, 0.0))) + geoList.append(Part.LineSegment(App.Vector(x1, y2, 0.0), App.Vector(x2, y2, 0.0))) + geoList.append(Part.LineSegment(App.Vector(x2, y2, 0.0), App.Vector(x2, y1, 0.0))) + geoList.append(Part.LineSegment(App.Vector(x2, y1, 0.0), App.Vector(x1, y1, 0.0))) doc.Sketch.addGeometry(geoList, False) del geoList @@ -1816,9 +1805,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): boxVolume = 10 * 10 * 10 chamferVolume = 1 * 1 * 0.5 * 10 # cut area is rectangle with sqrt(2) as one side minus 2 isosceles right triangles - cutArea = (2 * math.sqrt(2)) * 3 - ( - (math.sqrt(2) / 2 * math.sqrt(2) / 2) / 2 - ) * 2 + cutArea = (2 * math.sqrt(2)) * 3 - ((math.sqrt(2) / 2 * math.sqrt(2) / 2) / 2) * 2 cutVolume = cutArea * 4 # height is 4 ( 11-6 with a limit of 10 from the box ) self.assertAlmostEqual(volume1, boxVolume) self.assertAlmostEqual(volume2, boxVolume - 3 * chamferVolume) @@ -1856,18 +1843,10 @@ class TestTopologicalNamingProblem(unittest.TestCase): x1, x2, y1, y2 = 4, 6, 6, 11 geoList = [] - geoList.append( - Part.LineSegment(App.Vector(x1, y1, 0.0), App.Vector(x1, y2, 0.0)) - ) - geoList.append( - Part.LineSegment(App.Vector(x1, y2, 0.0), App.Vector(x2, y2, 0.0)) - ) - geoList.append( - Part.LineSegment(App.Vector(x2, y2, 0.0), App.Vector(x2, y1, 0.0)) - ) - geoList.append( - Part.LineSegment(App.Vector(x2, y1, 0.0), App.Vector(x1, y1, 0.0)) - ) + geoList.append(Part.LineSegment(App.Vector(x1, y1, 0.0), App.Vector(x1, y2, 0.0))) + geoList.append(Part.LineSegment(App.Vector(x1, y2, 0.0), App.Vector(x2, y2, 0.0))) + geoList.append(Part.LineSegment(App.Vector(x2, y2, 0.0), App.Vector(x2, y1, 0.0))) + geoList.append(Part.LineSegment(App.Vector(x2, y1, 0.0), App.Vector(x1, y1, 0.0))) doc.Sketch.addGeometry(geoList, False) del geoList @@ -2016,9 +1995,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): doc.Pad.ReferenceAxis = (doc.Sketch, ["N_Axis"]) doc.Sketch.Visibility = False doc.recompute() - expected_volume = ( - math.pi * radius * radius * 10 * 4 - ) # Volume of 4 padded circles + expected_volume = math.pi * radius * radius * 10 * 4 # Volume of 4 padded circles # self.assertAlmostEqual(doc.Body.Shape.Volume, expected_volume ) # TODO ENABLE THIS ASSERTION WHEN IT PASSES # # Add additional code to attach another sketch, then change the original sketch and check TNP @@ -2218,18 +2195,10 @@ class TestTopologicalNamingProblem(unittest.TestCase): ) doc.Sketch001.MapMode = "FlatFace" geoList = [] - geoList.append( - Part.LineSegment(App.Vector(-5, 5, 0.000000), App.Vector(-5, -5, 0.000000)) - ) - geoList.append( - Part.LineSegment(App.Vector(-5, -5, 0.000000), App.Vector(5, -5, 0.000000)) - ) - geoList.append( - Part.LineSegment(App.Vector(5, -5, 0.000000), App.Vector(5, 5, 0.000000)) - ) - geoList.append( - Part.LineSegment(App.Vector(5, 5, 0.000000), App.Vector(-5, 5, 0.000000)) - ) + geoList.append(Part.LineSegment(App.Vector(-5, 5, 0.000000), App.Vector(-5, -5, 0.000000))) + geoList.append(Part.LineSegment(App.Vector(-5, -5, 0.000000), App.Vector(5, -5, 0.000000))) + geoList.append(Part.LineSegment(App.Vector(5, -5, 0.000000), App.Vector(5, 5, 0.000000))) + geoList.append(Part.LineSegment(App.Vector(5, 5, 0.000000), App.Vector(-5, 5, 0.000000))) doc.Sketch001.addGeometry(geoList, False) del geoList constraintList = [] @@ -2381,15 +2350,15 @@ class TestTopologicalNamingProblem(unittest.TestCase): doc.Pad.Visibility = False doc.Sketch001.Visibility = False - self.assertAlmostEqual(doc.Pad.Shape.Volume,8000) + self.assertAlmostEqual(doc.Pad.Shape.Volume, 8000) - doc.Sketch.split(0, App.Vector(10,0,0)) # Geo 0 moves to Geo 3, create Geo4 - doc.Sketch.split(4, App.Vector(30,0,0)) # Create Geo5 - doc.Sketch.moveGeometry(4, 1, App.Vector(10,2,0), False) + doc.Sketch.split(0, App.Vector(10, 0, 0)) # Geo 0 moves to Geo 3, create Geo4 + doc.Sketch.split(4, App.Vector(30, 0, 0)) # Create Geo5 + doc.Sketch.moveGeometry(4, 1, App.Vector(10, 2, 0), False) doc.Sketch.moveGeometry(4, 2, App.Vector(30, 2, 0), False) doc.recompute() - self.assertAlmostEqual(doc.Pad.Shape.Volume,7400) # Prove the points moved - self.assertTrue(doc.Sketch001.isValid()) # Check for a TNP fail. + self.assertAlmostEqual(doc.Pad.Shape.Volume, 7400) # Prove the points moved + self.assertTrue(doc.Sketch001.isValid()) # Check for a TNP fail. # If Sketch001 is still at the right start point, we are good. self.assertTrue(doc.Sketch001.AttachmentOffset.Matrix == App.Matrix()) matrix1 = App.Matrix() @@ -2451,13 +2420,9 @@ class TestTopologicalNamingProblem(unittest.TestCase): # Act App.Gui.Selection.addSelection("", extrude.Name, "Face2") # Assert - self.assertEqual( - len(App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames), 1 - ) + self.assertEqual(len(App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames), 1) if extrude.ElementMapVersion == "": # Should be '4' as of Mar 2023. - self.assertEqual( - App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames[0], "Face2" - ) + self.assertEqual(App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames[0], "Face2") else: self.assertEqual( App.Gui.Selection.getSelectionEx("", 0)[0].SubElementNames[0][-8:], @@ -2543,9 +2508,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): self.assertEqual( doc.Body001.BaseFeature.Shape.ElementMapSize, 26 ) # base feature lookup should have element map - self.assertEqual( - doc.Body001.Shape.ElementMapSize, 26 - ) # Body Shape should have element map + self.assertEqual(doc.Body001.Shape.ElementMapSize, 26) # Body Shape should have element map def testBaseFeatureAttachmentSupport(self): # Arrange @@ -2584,24 +2547,16 @@ class TestTopologicalNamingProblem(unittest.TestCase): doc.recompute() geoList = [] geoList.append( - Part.LineSegment( - App.Vector(12.0, 13.0, 0.000000), App.Vector(12.0, 11.0, 0.000000) - ) + Part.LineSegment(App.Vector(12.0, 13.0, 0.000000), App.Vector(12.0, 11.0, 0.000000)) ) geoList.append( - Part.LineSegment( - App.Vector(12.0, 11, 0.000000), App.Vector(14.0, 11.0, 0.000000) - ) + Part.LineSegment(App.Vector(12.0, 11, 0.000000), App.Vector(14.0, 11.0, 0.000000)) ) geoList.append( - Part.LineSegment( - App.Vector(14.0, 11, 0.000000), App.Vector(14.0, 13.0, 0.000000) - ) + Part.LineSegment(App.Vector(14.0, 11, 0.000000), App.Vector(14.0, 13.0, 0.000000)) ) geoList.append( - Part.LineSegment( - App.Vector(14.0, 13.0, 0.000000), App.Vector(12, 13.0, 0.000000) - ) + Part.LineSegment(App.Vector(14.0, 13.0, 0.000000), App.Vector(12, 13.0, 0.000000)) ) doc.Sketch.addGeometry(geoList, False) del geoList @@ -2657,9 +2612,7 @@ class TestTopologicalNamingProblem(unittest.TestCase): ) doc.recompute() # Assert - self.assertEqual( - len(doc.Body.Shape.Faces), 17 - ) # Check that the object seems right. + self.assertEqual(len(doc.Body.Shape.Faces), 17) # Check that the object seems right. self.assertEqual(len(doc.Body.Shape.Edges), 42) self.assertEqual(len(doc.Body.Shape.Vertexes), 28) self.assertEqual(len(doc.Body.Shape.Shells), 1) diff --git a/src/Mod/PartDesign/Resources/Hole/din7984.json b/src/Mod/PartDesign/Resources/Hole/din7984.json index 6418161325..3bf7d26521 100644 --- a/src/Mod/PartDesign/Resources/Hole/din7984.json +++ b/src/Mod/PartDesign/Resources/Hole/din7984.json @@ -3,21 +3,85 @@ "cut_type": "counterbore", "thread_type": "metric", "data": [ - { "thread": "M2x0.4", "diameter": 4.3, "depth": 1.6 }, - { "thread": "M2.5x0.45", "diameter": 5.0, "depth": 2.0 }, - { "thread": "M3x0.5", "diameter": 6.0, "depth": 2.4 }, - { "thread": "M3.5x0.6", "diameter": 6.5, "depth": 2.9 }, - { "thread": "M4x0.7", "diameter": 8.0, "depth": 3.2 }, - { "thread": "M5x0.8", "diameter": 10.0, "depth": 4.0 }, - { "thread": "M6x1.0", "diameter": 11.0, "depth": 4.7 }, - { "thread": "M8x1.25", "diameter": 15.0, "depth": 6.0 }, - { "thread": "M10x1.5", "diameter": 18.0, "depth": 7.0 }, - { "thread": "M12x1.75", "diameter": 20.0, "depth": 8.0 }, - { "thread": "M14x2.0", "diameter": 24.0, "depth": 9.0 }, - { "thread": "M16x2.0", "diameter": 26.0, "depth": 10.5 }, - { "thread": "M18x2.5", "diameter": 30.0, "depth": 11.5 }, - { "thread": "M20x2.5", "diameter": 33.0, "depth": 12.5 }, - { "thread": "M22x2.5", "diameter": 36.0, "depth": 13.5 }, - { "thread": "M24x3.0", "diameter": 40.0, "depth": 14.5 } + { + "thread": "M2x0.4", + "diameter": 4.3, + "depth": 1.6 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.0, + "depth": 2.0 + }, + { + "thread": "M3x0.5", + "diameter": 6.0, + "depth": 2.4 + }, + { + "thread": "M3.5x0.6", + "diameter": 6.5, + "depth": 2.9 + }, + { + "thread": "M4x0.7", + "diameter": 8.0, + "depth": 3.2 + }, + { + "thread": "M5x0.8", + "diameter": 10.0, + "depth": 4.0 + }, + { + "thread": "M6x1.0", + "diameter": 11.0, + "depth": 4.7 + }, + { + "thread": "M8x1.25", + "diameter": 15.0, + "depth": 6.0 + }, + { + "thread": "M10x1.5", + "diameter": 18.0, + "depth": 7.0 + }, + { + "thread": "M12x1.75", + "diameter": 20.0, + "depth": 8.0 + }, + { + "thread": "M14x2.0", + "diameter": 24.0, + "depth": 9.0 + }, + { + "thread": "M16x2.0", + "diameter": 26.0, + "depth": 10.5 + }, + { + "thread": "M18x2.5", + "diameter": 30.0, + "depth": 11.5 + }, + { + "thread": "M20x2.5", + "diameter": 33.0, + "depth": 12.5 + }, + { + "thread": "M22x2.5", + "diameter": 36.0, + "depth": 13.5 + }, + { + "thread": "M24x3.0", + "diameter": 40.0, + "depth": 14.5 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso10642-fine.json b/src/Mod/PartDesign/Resources/Hole/iso10642-fine.json index c81a54e8da..58cb1c1023 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso10642-fine.json +++ b/src/Mod/PartDesign/Resources/Hole/iso10642-fine.json @@ -4,22 +4,73 @@ "thread_type": "metricfine", "angle": 90, "data": [ - { "thread": "M1.6x0.2", "diameter": 3.6 }, - { "thread": "M2x0.25", "diameter": 4.5 }, - { "thread": "M2.5x0.35", "diameter": 5.6 }, - { "thread": "M3x0.35", "diameter": 6.7 }, - { "thread": "M4x0.5", "diameter": 9.0 }, - { "thread": "M5x0.5", "diameter": 11.2 }, - { "thread": "M6x0.75", "diameter": 13.5 }, - { "thread": "M8x0.75", "diameter": 18.0 }, - { "thread": "M8x1.0", "diameter": 18.0 }, - { "thread": "M10x1.0", "diameter": 22.4 }, - { "thread": "M10x1.25", "diameter": 22.4 }, - { "thread": "M12x1.25", "diameter": 26.8 }, - { "thread": "M12x1.5", "diameter": 26.8 }, - { "thread": "M14x1.5", "diameter": 30.9 }, - { "thread": "M16x1.5", "diameter": 33.6 }, - { "thread": "M20x1.5", "diameter": 40.3 }, - { "thread": "M20x2.0", "diameter": 40.3 } + { + "thread": "M1.6x0.2", + "diameter": 3.6 + }, + { + "thread": "M2x0.25", + "diameter": 4.5 + }, + { + "thread": "M2.5x0.35", + "diameter": 5.6 + }, + { + "thread": "M3x0.35", + "diameter": 6.7 + }, + { + "thread": "M4x0.5", + "diameter": 9.0 + }, + { + "thread": "M5x0.5", + "diameter": 11.2 + }, + { + "thread": "M6x0.75", + "diameter": 13.5 + }, + { + "thread": "M8x0.75", + "diameter": 18.0 + }, + { + "thread": "M8x1.0", + "diameter": 18.0 + }, + { + "thread": "M10x1.0", + "diameter": 22.4 + }, + { + "thread": "M10x1.25", + "diameter": 22.4 + }, + { + "thread": "M12x1.25", + "diameter": 26.8 + }, + { + "thread": "M12x1.5", + "diameter": 26.8 + }, + { + "thread": "M14x1.5", + "diameter": 30.9 + }, + { + "thread": "M16x1.5", + "diameter": 33.6 + }, + { + "thread": "M20x1.5", + "diameter": 40.3 + }, + { + "thread": "M20x2.0", + "diameter": 40.3 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso10642.json b/src/Mod/PartDesign/Resources/Hole/iso10642.json index 9db88620e0..e0066f5b1f 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso10642.json +++ b/src/Mod/PartDesign/Resources/Hole/iso10642.json @@ -4,17 +4,53 @@ "thread_type": "metric", "angle": 90, "data": [ - { "thread": "M2x0.4", "diameter": 4.7 }, - { "thread": "M2.5x0.45", "diameter": 5.9 }, - { "thread": "M3x0.5", "diameter": 6.7 }, - { "thread": "M4x0.7", "diameter": 9.0 }, - { "thread": "M5x0.8", "diameter": 11.2 }, - { "thread": "M6x1.0", "diameter": 13.4 }, - { "thread": "M8x1.25", "diameter": 17.9 }, - { "thread": "M10x1.5", "diameter": 22.4 }, - { "thread": "M12x1.75", "diameter": 26.9 }, - { "thread": "M14x2.0", "diameter": 30.8 }, - { "thread": "M16x2.0", "diameter": 33.6 }, - { "thread": "M20x2.5", "diameter": 40.3 } + { + "thread": "M2x0.4", + "diameter": 4.7 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.9 + }, + { + "thread": "M3x0.5", + "diameter": 6.7 + }, + { + "thread": "M4x0.7", + "diameter": 9.0 + }, + { + "thread": "M5x0.8", + "diameter": 11.2 + }, + { + "thread": "M6x1.0", + "diameter": 13.4 + }, + { + "thread": "M8x1.25", + "diameter": 17.9 + }, + { + "thread": "M10x1.5", + "diameter": 22.4 + }, + { + "thread": "M12x1.75", + "diameter": 26.9 + }, + { + "thread": "M14x2.0", + "diameter": 30.8 + }, + { + "thread": "M16x2.0", + "diameter": 33.6 + }, + { + "thread": "M20x2.5", + "diameter": 40.3 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso12474-fine.json b/src/Mod/PartDesign/Resources/Hole/iso12474-fine.json index 155f363b06..e045b03de7 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso12474-fine.json +++ b/src/Mod/PartDesign/Resources/Hole/iso12474-fine.json @@ -3,21 +3,85 @@ "cut_type": "counterbore", "thread_type": "metricfine", "data": [ - { "thread": "M8x1.0", "diameter": 15.0, "depth": 8.6 }, - { "thread": "M10x1.0", "diameter": 18.0, "depth": 10.6 }, - { "thread": "M10x1.25", "diameter": 18.0, "depth": 10.6 }, - { "thread": "M12x1.25", "diameter": 20.0, "depth": 12.6 }, - { "thread": "M12x1.5", "diameter": 20.0, "depth": 12.6 }, - { "thread": "M14x1.5", "diameter": 24.0, "depth": 14.6 }, - { "thread": "M16x1.5", "diameter": 26.0, "depth": 16.6 }, - { "thread": "M18x1.5", "diameter": 30.0, "depth": 18.6 }, - { "thread": "M20x1.5", "diameter": 33.0, "depth": 20.6 }, - { "thread": "M20x2.0", "diameter": 33.0, "depth": 20.6 }, - { "thread": "M22x1.5", "diameter": 36.0, "depth": 22.8 }, - { "thread": "M24x2.0", "diameter": 40.0, "depth": 24.8 }, - { "thread": "M30x2.0", "diameter": 50.0, "depth": 31.0 }, - { "thread": "M33x1.5", "diameter": 54.0, "depth": 34.0 }, - { "thread": "M36x3.0", "diameter": 58.0, "depth": 37.0 }, - { "thread": "M42x3.0", "diameter": 69.0, "depth": 41.0 } + { + "thread": "M8x1.0", + "diameter": 15.0, + "depth": 8.6 + }, + { + "thread": "M10x1.0", + "diameter": 18.0, + "depth": 10.6 + }, + { + "thread": "M10x1.25", + "diameter": 18.0, + "depth": 10.6 + }, + { + "thread": "M12x1.25", + "diameter": 20.0, + "depth": 12.6 + }, + { + "thread": "M12x1.5", + "diameter": 20.0, + "depth": 12.6 + }, + { + "thread": "M14x1.5", + "diameter": 24.0, + "depth": 14.6 + }, + { + "thread": "M16x1.5", + "diameter": 26.0, + "depth": 16.6 + }, + { + "thread": "M18x1.5", + "diameter": 30.0, + "depth": 18.6 + }, + { + "thread": "M20x1.5", + "diameter": 33.0, + "depth": 20.6 + }, + { + "thread": "M20x2.0", + "diameter": 33.0, + "depth": 20.6 + }, + { + "thread": "M22x1.5", + "diameter": 36.0, + "depth": 22.8 + }, + { + "thread": "M24x2.0", + "diameter": 40.0, + "depth": 24.8 + }, + { + "thread": "M30x2.0", + "diameter": 50.0, + "depth": 31.0 + }, + { + "thread": "M33x1.5", + "diameter": 54.0, + "depth": 34.0 + }, + { + "thread": "M36x3.0", + "diameter": 58.0, + "depth": 37.0 + }, + { + "thread": "M42x3.0", + "diameter": 69.0, + "depth": 41.0 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso14583.json b/src/Mod/PartDesign/Resources/Hole/iso14583.json index efcb38b55c..adc7316010 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso14583.json +++ b/src/Mod/PartDesign/Resources/Hole/iso14583.json @@ -3,14 +3,50 @@ "cut_type": "counterbore", "thread_type": "metric", "data": [ - { "thread": "M2x0.4", "diameter": 4.4, "depth": 2.0 }, - { "thread": "M2.5x0.45", "diameter": 5.4, "depth": 2.5 }, - { "thread": "M3x0.5", "diameter": 6.0, "depth": 2.8 }, - { "thread": "M3.5x0.6", "diameter": 7.6, "depth": 3.0 }, - { "thread": "M4x0.7", "diameter": 8.6, "depth": 3.5 }, - { "thread": "M5x0.8", "diameter": 10.1, "depth": 4.1 }, - { "thread": "M6x1.0", "diameter": 12.6, "depth": 5.0 }, - { "thread": "M8x1.25", "diameter": 16.6, "depth": 6.6 }, - { "thread": "M10x1.5", "diameter": 20.8, "depth": 8.1 } + { + "thread": "M2x0.4", + "diameter": 4.4, + "depth": 2.0 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.4, + "depth": 2.5 + }, + { + "thread": "M3x0.5", + "diameter": 6.0, + "depth": 2.8 + }, + { + "thread": "M3.5x0.6", + "diameter": 7.6, + "depth": 3.0 + }, + { + "thread": "M4x0.7", + "diameter": 8.6, + "depth": 3.5 + }, + { + "thread": "M5x0.8", + "diameter": 10.1, + "depth": 4.1 + }, + { + "thread": "M6x1.0", + "diameter": 12.6, + "depth": 5.0 + }, + { + "thread": "M8x1.25", + "diameter": 16.6, + "depth": 6.6 + }, + { + "thread": "M10x1.5", + "diameter": 20.8, + "depth": 8.1 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso14583part.json b/src/Mod/PartDesign/Resources/Hole/iso14583part.json index 72749795df..f0bda57966 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso14583part.json +++ b/src/Mod/PartDesign/Resources/Hole/iso14583part.json @@ -3,14 +3,50 @@ "cut_type": "counterbore", "thread_type": "metric", "data": [ - { "thread": "M2x0.4", "diameter": 4.4, "depth": 1.0 }, - { "thread": "M2.5x0.45", "diameter": 5.4, "depth": 1.4 }, - { "thread": "M3x0.5", "diameter": 6.0, "depth": 1.7 }, - { "thread": "M3.5x0.6", "diameter": 7.6, "depth": 1.7 }, - { "thread": "M4x0.7", "diameter": 8.6, "depth": 2.0 }, - { "thread": "M5x0.8", "diameter": 10.1, "depth": 2.5 }, - { "thread": "M6x1.0", "diameter": 12.6, "depth": 3.0 }, - { "thread": "M8x1.25", "diameter": 16.6, "depth": 3.9 }, - { "thread": "M10x1.5", "diameter": 20.8, "depth": 4.6 } + { + "thread": "M2x0.4", + "diameter": 4.4, + "depth": 1.0 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.4, + "depth": 1.4 + }, + { + "thread": "M3x0.5", + "diameter": 6.0, + "depth": 1.7 + }, + { + "thread": "M3.5x0.6", + "diameter": 7.6, + "depth": 1.7 + }, + { + "thread": "M4x0.7", + "diameter": 8.6, + "depth": 2.0 + }, + { + "thread": "M5x0.8", + "diameter": 10.1, + "depth": 2.5 + }, + { + "thread": "M6x1.0", + "diameter": 12.6, + "depth": 3.0 + }, + { + "thread": "M8x1.25", + "diameter": 16.6, + "depth": 3.9 + }, + { + "thread": "M10x1.5", + "diameter": 20.8, + "depth": 4.6 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso2009.json b/src/Mod/PartDesign/Resources/Hole/iso2009.json index d7dc64ca38..6088118d02 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso2009.json +++ b/src/Mod/PartDesign/Resources/Hole/iso2009.json @@ -4,14 +4,41 @@ "thread_type": "metric", "angle": 90, "data": [ - { "thread": "M2x0.4", "diameter": 4.3 }, - { "thread": "M2.5x0.45", "diameter": 5.3 }, - { "thread": "M3x0.5", "diameter": 6.3 }, - { "thread": "M4x0.7", "diameter": 9.5 }, - { "thread": "M5x0.8", "diameter": 10.5 }, - { "thread": "M6x1.0", "diameter": 12.7 }, - { "thread": "M8x1.25", "diameter": 17.7 }, - { "thread": "M10x1.5", "diameter": 20.2 }, - { "thread": "M12x1.75", "diameter": 24.7 } + { + "thread": "M2x0.4", + "diameter": 4.3 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.3 + }, + { + "thread": "M3x0.5", + "diameter": 6.3 + }, + { + "thread": "M4x0.7", + "diameter": 9.5 + }, + { + "thread": "M5x0.8", + "diameter": 10.5 + }, + { + "thread": "M6x1.0", + "diameter": 12.7 + }, + { + "thread": "M8x1.25", + "diameter": 17.7 + }, + { + "thread": "M10x1.5", + "diameter": 20.2 + }, + { + "thread": "M12x1.75", + "diameter": 24.7 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso4762-fine.json b/src/Mod/PartDesign/Resources/Hole/iso4762-fine.json index 3c0978628b..ffbdc08b0c 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso4762-fine.json +++ b/src/Mod/PartDesign/Resources/Hole/iso4762-fine.json @@ -3,33 +3,145 @@ "cut_type": "counterbore", "thread_type": "metricfine", "data": [ - { "thread": "M1.6x0.2", "diameter": 3.5, "depth": 1.7 }, - { "thread": "M2x0.25", "diameter": 4.3, "depth": 2.1 }, - { "thread": "M2.5x0.35", "diameter": 5.0, "depth": 3.0 }, - { "thread": "M3x0.35", "diameter": 6.0, "depth": 3.4 }, - { "thread": "M3.5x0.35", "diameter": 6.5, "depth": 3.9 }, - { "thread": "M4x0.5", "diameter": 8.0, "depth": 4.4 }, - { "thread": "M5x0.5", "diameter": 10.0, "depth": 5.4 }, - { "thread": "M6x0.75", "diameter": 11.0, "depth": 6.4 }, - { "thread": "M8x0.75", "diameter": 15.0, "depth": 8.6 }, - { "thread": "M8x1.0", "diameter": 15.0, "depth": 8.6 }, - { "thread": "M10x1.0", "diameter": 18.0, "depth": 10.6 }, - { "thread": "M10x1.25", "diameter": 18.0, "depth": 10.6 }, - { "thread": "M12x1.25", "diameter": 20.0, "depth": 12.6 }, - { "thread": "M12x1.5", "diameter": 20.0, "depth": 12.6 }, - { "thread": "M14x1.5", "diameter": 24.0, "depth": 14.6 }, - { "thread": "M16x1.5", "diameter": 26.0, "depth": 16.6 }, - { "thread": "M18x1.5", "diameter": 30.0, "depth": 18.6 }, - { "thread": "M18x2.0", "diameter": 30.0, "depth": 18.6 }, - { "thread": "M20x1.5", "diameter": 33.0, "depth": 20.6 }, - { "thread": "M20x2.0", "diameter": 33.0, "depth": 20.6 }, - { "thread": "M22x1.5", "diameter": 36.0, "depth": 22.8 }, - { "thread": "M22x2.0", "diameter": 36.0, "depth": 22.8 }, - { "thread": "M24x2.0", "diameter": 40.0, "depth": 24.8 }, - { "thread": "M30x2.0", "diameter": 50.0, "depth": 31.0 }, - { "thread": "M33x2.0", "diameter": 54.0, "depth": 34.0 }, - { "thread": "M36x3.0", "diameter": 58.0, "depth": 37.0 }, - { "thread": "M42x3.0", "diameter": 69.0, "depth": 43.0 }, - { "thread": "M48x3.0", "diameter": 78.0, "depth": 49.0 } + { + "thread": "M1.6x0.2", + "diameter": 3.5, + "depth": 1.7 + }, + { + "thread": "M2x0.25", + "diameter": 4.3, + "depth": 2.1 + }, + { + "thread": "M2.5x0.35", + "diameter": 5.0, + "depth": 3.0 + }, + { + "thread": "M3x0.35", + "diameter": 6.0, + "depth": 3.4 + }, + { + "thread": "M3.5x0.35", + "diameter": 6.5, + "depth": 3.9 + }, + { + "thread": "M4x0.5", + "diameter": 8.0, + "depth": 4.4 + }, + { + "thread": "M5x0.5", + "diameter": 10.0, + "depth": 5.4 + }, + { + "thread": "M6x0.75", + "diameter": 11.0, + "depth": 6.4 + }, + { + "thread": "M8x0.75", + "diameter": 15.0, + "depth": 8.6 + }, + { + "thread": "M8x1.0", + "diameter": 15.0, + "depth": 8.6 + }, + { + "thread": "M10x1.0", + "diameter": 18.0, + "depth": 10.6 + }, + { + "thread": "M10x1.25", + "diameter": 18.0, + "depth": 10.6 + }, + { + "thread": "M12x1.25", + "diameter": 20.0, + "depth": 12.6 + }, + { + "thread": "M12x1.5", + "diameter": 20.0, + "depth": 12.6 + }, + { + "thread": "M14x1.5", + "diameter": 24.0, + "depth": 14.6 + }, + { + "thread": "M16x1.5", + "diameter": 26.0, + "depth": 16.6 + }, + { + "thread": "M18x1.5", + "diameter": 30.0, + "depth": 18.6 + }, + { + "thread": "M18x2.0", + "diameter": 30.0, + "depth": 18.6 + }, + { + "thread": "M20x1.5", + "diameter": 33.0, + "depth": 20.6 + }, + { + "thread": "M20x2.0", + "diameter": 33.0, + "depth": 20.6 + }, + { + "thread": "M22x1.5", + "diameter": 36.0, + "depth": 22.8 + }, + { + "thread": "M22x2.0", + "diameter": 36.0, + "depth": 22.8 + }, + { + "thread": "M24x2.0", + "diameter": 40.0, + "depth": 24.8 + }, + { + "thread": "M30x2.0", + "diameter": 50.0, + "depth": 31.0 + }, + { + "thread": "M33x2.0", + "diameter": 54.0, + "depth": 34.0 + }, + { + "thread": "M36x3.0", + "diameter": 58.0, + "depth": 37.0 + }, + { + "thread": "M42x3.0", + "diameter": 69.0, + "depth": 43.0 + }, + { + "thread": "M48x3.0", + "diameter": 78.0, + "depth": 49.0 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso4762.json b/src/Mod/PartDesign/Resources/Hole/iso4762.json index 67a675577d..1d0c4db261 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso4762.json +++ b/src/Mod/PartDesign/Resources/Hole/iso4762.json @@ -3,29 +3,125 @@ "cut_type": "counterbore", "thread_type": "metric", "data": [ - { "thread": "M1.6x0.35", "diameter": 3.5, "depth": 1.7 }, - { "thread": "M2x0.4", "diameter": 4.3, "depth": 2.1 }, - { "thread": "M2.5x0.45", "diameter": 5.0, "depth": 3.0 }, - { "thread": "M3x0.5", "diameter": 6.0, "depth": 3.4 }, - { "thread": "M3.5x0.6", "diameter": 6.5, "depth": 3.9 }, - { "thread": "M4x0.7", "diameter": 8.0, "depth": 4.4 }, - { "thread": "M5x0.8", "diameter": 10.0, "depth": 5.4 }, - { "thread": "M6x1.0", "diameter": 11.0, "depth": 6.4 }, - { "thread": "M8x1.25", "diameter": 15.0, "depth": 8.6 }, - { "thread": "M10x1.5", "diameter": 18.0, "depth": 10.6 }, - { "thread": "M12x1.75", "diameter": 20.0, "depth": 12.6 }, - { "thread": "M14x2.0", "diameter": 24.0, "depth": 14.6 }, - { "thread": "M16x2.0", "diameter": 26.0, "depth": 16.6 }, - { "thread": "M18x2.5", "diameter": 30.0, "depth": 18.6 }, - { "thread": "M20x2.5", "diameter": 33.0, "depth": 20.6 }, - { "thread": "M22x2.5", "diameter": 36.0, "depth": 22.8 }, - { "thread": "M24x3.0", "diameter": 40.0, "depth": 24.8 }, - { "thread": "M30x3.5", "diameter": 50.0, "depth": 31.0 }, - { "thread": "M33x3.5", "diameter": 54.0, "depth": 34.0 }, - { "thread": "M36x4.0", "diameter": 58.0, "depth": 37.0 }, - { "thread": "M42x4.5", "diameter": 69.0, "depth": 43.0 }, - { "thread": "M48x5.0", "diameter": 78.0, "depth": 49.0 }, - { "thread": "M56x5.5", "diameter": 90.0, "depth": 57.0 }, - { "thread": "M64x6.0", "diameter": 103.0, "depth": 65.0 } + { + "thread": "M1.6x0.35", + "diameter": 3.5, + "depth": 1.7 + }, + { + "thread": "M2x0.4", + "diameter": 4.3, + "depth": 2.1 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.0, + "depth": 3.0 + }, + { + "thread": "M3x0.5", + "diameter": 6.0, + "depth": 3.4 + }, + { + "thread": "M3.5x0.6", + "diameter": 6.5, + "depth": 3.9 + }, + { + "thread": "M4x0.7", + "diameter": 8.0, + "depth": 4.4 + }, + { + "thread": "M5x0.8", + "diameter": 10.0, + "depth": 5.4 + }, + { + "thread": "M6x1.0", + "diameter": 11.0, + "depth": 6.4 + }, + { + "thread": "M8x1.25", + "diameter": 15.0, + "depth": 8.6 + }, + { + "thread": "M10x1.5", + "diameter": 18.0, + "depth": 10.6 + }, + { + "thread": "M12x1.75", + "diameter": 20.0, + "depth": 12.6 + }, + { + "thread": "M14x2.0", + "diameter": 24.0, + "depth": 14.6 + }, + { + "thread": "M16x2.0", + "diameter": 26.0, + "depth": 16.6 + }, + { + "thread": "M18x2.5", + "diameter": 30.0, + "depth": 18.6 + }, + { + "thread": "M20x2.5", + "diameter": 33.0, + "depth": 20.6 + }, + { + "thread": "M22x2.5", + "diameter": 36.0, + "depth": 22.8 + }, + { + "thread": "M24x3.0", + "diameter": 40.0, + "depth": 24.8 + }, + { + "thread": "M30x3.5", + "diameter": 50.0, + "depth": 31.0 + }, + { + "thread": "M33x3.5", + "diameter": 54.0, + "depth": 34.0 + }, + { + "thread": "M36x4.0", + "diameter": 58.0, + "depth": 37.0 + }, + { + "thread": "M42x4.5", + "diameter": 69.0, + "depth": 43.0 + }, + { + "thread": "M48x5.0", + "diameter": 78.0, + "depth": 49.0 + }, + { + "thread": "M56x5.5", + "diameter": 90.0, + "depth": 57.0 + }, + { + "thread": "M64x6.0", + "diameter": 103.0, + "depth": 65.0 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso4762_7089.json b/src/Mod/PartDesign/Resources/Hole/iso4762_7089.json index 7e5080b27d..4118f50db3 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso4762_7089.json +++ b/src/Mod/PartDesign/Resources/Hole/iso4762_7089.json @@ -3,25 +3,105 @@ "cut_type": "counterbore", "thread_type": "metric", "data": [ - { "thread": "M2x0.4", "diameter": 6.0, "depth": 2.4 }, - { "thread": "M2.5x0.45","diameter": 7.0, "depth": 3.5 }, - { "thread": "M3x0.5", "diameter": 9.0, "depth": 3.9 }, - { "thread": "M3.5x0.6", "diameter": 9.0, "depth": 4.4 }, - { "thread": "M4x0.7", "diameter": 10.0, "depth": 5.2 }, - { "thread": "M5x0.8", "diameter": 13.0, "depth": 6.4 }, - { "thread": "M6x1.0", "diameter": 15.0, "depth": 8.0 }, - { "thread": "M8x1.25", "diameter": 18.0, "depth": 10.2 }, - { "thread": "M10x1.5", "diameter": 24.0, "depth": 12.6 }, - { "thread": "M12x1.75", "diameter": 26.0, "depth": 15.1 }, - { "thread": "M14x2.0", "diameter": 30.0, "depth": 17.1 }, - { "thread": "M16x2.0", "diameter": 33.0, "depth": 16.6 }, - { "thread": "M18x2.5", "diameter": 36.0, "depth": 21.6 }, - { "thread": "M20x2.5", "diameter": 40.0, "depth": 23.6 }, - { "thread": "M22x2.5", "diameter": 43.0, "depth": 25.8 }, - { "thread": "M24x3.0", "diameter": 48.0, "depth": 29.8 }, - { "thread": "M27x3.0", "diameter": 54.0, "depth": 35.0 }, - { "thread": "M30x3.5", "diameter": 61.0, "depth": 38.0 }, - { "thread": "M33x3.5", "diameter": 63.0, "depth": 41.0 }, - { "thread": "M36x4.0", "diameter": 69.0, "depth": 42.0 } + { + "thread": "M2x0.4", + "diameter": 6.0, + "depth": 2.4 + }, + { + "thread": "M2.5x0.45", + "diameter": 7.0, + "depth": 3.5 + }, + { + "thread": "M3x0.5", + "diameter": 9.0, + "depth": 3.9 + }, + { + "thread": "M3.5x0.6", + "diameter": 9.0, + "depth": 4.4 + }, + { + "thread": "M4x0.7", + "diameter": 10.0, + "depth": 5.2 + }, + { + "thread": "M5x0.8", + "diameter": 13.0, + "depth": 6.4 + }, + { + "thread": "M6x1.0", + "diameter": 15.0, + "depth": 8.0 + }, + { + "thread": "M8x1.25", + "diameter": 18.0, + "depth": 10.2 + }, + { + "thread": "M10x1.5", + "diameter": 24.0, + "depth": 12.6 + }, + { + "thread": "M12x1.75", + "diameter": 26.0, + "depth": 15.1 + }, + { + "thread": "M14x2.0", + "diameter": 30.0, + "depth": 17.1 + }, + { + "thread": "M16x2.0", + "diameter": 33.0, + "depth": 16.6 + }, + { + "thread": "M18x2.5", + "diameter": 36.0, + "depth": 21.6 + }, + { + "thread": "M20x2.5", + "diameter": 40.0, + "depth": 23.6 + }, + { + "thread": "M22x2.5", + "diameter": 43.0, + "depth": 25.8 + }, + { + "thread": "M24x3.0", + "diameter": 48.0, + "depth": 29.8 + }, + { + "thread": "M27x3.0", + "diameter": 54.0, + "depth": 35.0 + }, + { + "thread": "M30x3.5", + "diameter": 61.0, + "depth": 38.0 + }, + { + "thread": "M33x3.5", + "diameter": 63.0, + "depth": 41.0 + }, + { + "thread": "M36x4.0", + "diameter": 69.0, + "depth": 42.0 + } ] } diff --git a/src/Mod/PartDesign/Resources/Hole/iso7046.json b/src/Mod/PartDesign/Resources/Hole/iso7046.json index 9adc88dba1..6f010f58f3 100644 --- a/src/Mod/PartDesign/Resources/Hole/iso7046.json +++ b/src/Mod/PartDesign/Resources/Hole/iso7046.json @@ -4,15 +4,45 @@ "thread_type": "metric", "angle": 90, "data": [ - { "thread": "M1.6x0.35", "diameter": 3.6 }, - { "thread": "M2x0.4", "diameter": 4.4 }, - { "thread": "M2.5x0.45", "diameter": 5.5 }, - { "thread": "M3x0.5", "diameter": 6.3 }, - { "thread": "M3.5x0.6", "diameter": 8.2 }, - { "thread": "M4x0.7", "diameter": 9.4 }, - { "thread": "M5x0.8", "diameter": 10.4 }, - { "thread": "M6x1.0", "diameter": 12.6 }, - { "thread": "M8x1.25", "diameter": 17.3 }, - { "thread": "M10x1.5", "diameter": 20.0 } + { + "thread": "M1.6x0.35", + "diameter": 3.6 + }, + { + "thread": "M2x0.4", + "diameter": 4.4 + }, + { + "thread": "M2.5x0.45", + "diameter": 5.5 + }, + { + "thread": "M3x0.5", + "diameter": 6.3 + }, + { + "thread": "M3.5x0.6", + "diameter": 8.2 + }, + { + "thread": "M4x0.7", + "diameter": 9.4 + }, + { + "thread": "M5x0.8", + "diameter": 10.4 + }, + { + "thread": "M6x1.0", + "diameter": 12.6 + }, + { + "thread": "M8x1.25", + "diameter": 17.3 + }, + { + "thread": "M10x1.5", + "diameter": 20.0 + } ] } diff --git a/src/Mod/PartDesign/Scripts/DistanceBolt.py b/src/Mod/PartDesign/Scripts/DistanceBolt.py index be0f6241fb..09ae217e89 100644 --- a/src/Mod/PartDesign/Scripts/DistanceBolt.py +++ b/src/Mod/PartDesign/Scripts/DistanceBolt.py @@ -10,13 +10,26 @@ __author__ = "Werner Mayer " import FreeCAD, Part, math from FreeCAD import Base + class DistanceBolt: def __init__(self, obj): - ''' Add the properties: Length, Edges, Radius, Height ''' - obj.addProperty("App::PropertyInteger","Edges","Bolt","Number of edges of the outline", locked=True).Edges=6 - obj.addProperty("App::PropertyLength","Length","Bolt","Length of the edges of the outline", locked=True).Length=10.0 - obj.addProperty("App::PropertyLength","Radius","Bolt","Radius of the inner circle", locked=True).Radius=4.0 - obj.addProperty("App::PropertyLength","Height","Bolt","Height of the extrusion", locked=True).Height=20.0 + """Add the properties: Length, Edges, Radius, Height""" + obj.addProperty( + "App::PropertyInteger", "Edges", "Bolt", "Number of edges of the outline", locked=True + ).Edges = 6 + obj.addProperty( + "App::PropertyLength", + "Length", + "Bolt", + "Length of the edges of the outline", + locked=True, + ).Length = 10.0 + obj.addProperty( + "App::PropertyLength", "Radius", "Bolt", "Radius of the inner circle", locked=True + ).Radius = 4.0 + obj.addProperty( + "App::PropertyLength", "Height", "Bolt", "Height of the extrusion", locked=True + ).Height = 20.0 obj.Proxy = self def onChanged(self, fp, prop): @@ -31,12 +44,12 @@ class DistanceBolt: radius = fp.Radius height = fp.Height - m=Base.Matrix() - m.rotateZ(math.radians(360.0/edges)) + m = Base.Matrix() + m.rotateZ(math.radians(360.0 / edges)) # create polygon polygon = [] - v=Base.Vector(length,0,0) + v = Base.Vector(length, 0, 0) for i in range(edges): polygon.append(v) v = m.multiply(v) @@ -44,20 +57,21 @@ class DistanceBolt: wire = Part.makePolygon(polygon) # create circle - circ=Part.makeCircle(radius) + circ = Part.makeCircle(radius) # Create the face with the polygon as outline and the circle as hole - face=Part.Face([wire,Part.Wire(circ)]) + face = Part.Face([wire, Part.Wire(circ)]) # Extrude in z to create the final solid - extrude=face.extrude(Base.Vector(0,0,height)) + extrude = face.extrude(Base.Vector(0, 0, height)) fp.Shape = extrude + def makeDistanceBolt(): doc = FreeCAD.activeDocument() if doc is None: doc = FreeCAD.newDocument() - bolt=doc.addObject("Part::FeaturePython","Distance_Bolt") + bolt = doc.addObject("Part::FeaturePython", "Distance_Bolt") bolt.Label = "Distance bolt" DistanceBolt(bolt) - bolt.ViewObject.Proxy=0 + bolt.ViewObject.Proxy = 0 diff --git a/src/Mod/PartDesign/Scripts/Epitrochoid.py b/src/Mod/PartDesign/Scripts/Epitrochoid.py index 53a909784b..1a19040a10 100644 --- a/src/Mod/PartDesign/Scripts/Epitrochoid.py +++ b/src/Mod/PartDesign/Scripts/Epitrochoid.py @@ -2,67 +2,84 @@ # (c) 2011 Werner Mayer LGPL # -from __future__ import division # allows floating point division from integers +from __future__ import division # allows floating point division from integers import FreeCAD, Part, math from FreeCAD import Base + class Epitrochoid: def __init__(self, obj): - ''' Add the properties: Radius1, Radius2, Distance, Segments ''' - obj.addProperty("App::PropertyLength","Radius1","Epitrochoid","Interior radius", locked=True).Radius1=60.0 - obj.addProperty("App::PropertyLength","Radius2","Epitrochoid","Exterior radius", locked=True).Radius2=20.0 - obj.addProperty("App::PropertyLength","Distance","Epitrochoid","Distance", locked=True).Distance=10.0 - obj.addProperty("App::PropertyInteger","Segments","Epitrochoid","Number of the line segments", locked=True).Segments=72 + """Add the properties: Radius1, Radius2, Distance, Segments""" + obj.addProperty( + "App::PropertyLength", "Radius1", "Epitrochoid", "Interior radius", locked=True + ).Radius1 = 60.0 + obj.addProperty( + "App::PropertyLength", "Radius2", "Epitrochoid", "Exterior radius", locked=True + ).Radius2 = 20.0 + obj.addProperty( + "App::PropertyLength", "Distance", "Epitrochoid", "Distance", locked=True + ).Distance = 10.0 + obj.addProperty( + "App::PropertyInteger", + "Segments", + "Epitrochoid", + "Number of the line segments", + locked=True, + ).Segments = 72 obj.Proxy = self def onChanged(self, fp, prop): - if prop == "Radius1" or prop == "Radius2" or prop == "Distance" or prop == "Segments": #if one of these is changed + if ( + prop == "Radius1" or prop == "Radius2" or prop == "Distance" or prop == "Segments" + ): # if one of these is changed self.execute(fp) - def execute(self, fp): #main part of script - steps=fp.Segments #get value from property - dang=math.radians(360/steps) - r2=fp.Radius2 - r1=fp.Radius1 + def execute(self, fp): # main part of script + steps = fp.Segments # get value from property + dang = math.radians(360 / steps) + r2 = fp.Radius2 + r1 = fp.Radius1 f1 = r1 + r2 f2 = f1 / r2 - d=fp.Distance - ang=0 - z=0 + d = fp.Distance + ang = 0 + z = 0 if r2 == 0: raise ValueError("Exterior radius must not be zero") for i in range(steps): - if i==0: - x1=f1*math.cos(ang)-d*math.cos(f2*ang) #coords for line startpoint - y1=f1*math.sin(ang)-d*math.sin(f2*ang) - ang=dang - x2=f1*math.cos(ang)-d*math.cos(f2*ang) #coords for line endpoint - y2=f1*math.sin(ang)-d*math.sin(f2*ang) - seg=Part.makeLine((x1,y1,z),(x2,y2,z)) - wire=Part.Wire([seg]) - x1=x2 - y1=y2 + if i == 0: + x1 = f1 * math.cos(ang) - d * math.cos(f2 * ang) # coords for line startpoint + y1 = f1 * math.sin(ang) - d * math.sin(f2 * ang) + ang = dang + x2 = f1 * math.cos(ang) - d * math.cos(f2 * ang) # coords for line endpoint + y2 = f1 * math.sin(ang) - d * math.sin(f2 * ang) + seg = Part.makeLine((x1, y1, z), (x2, y2, z)) + wire = Part.Wire([seg]) + x1 = x2 + y1 = y2 else: - x2=f1*math.cos(ang)-d*math.cos(f2*ang) - y2=f1*math.sin(ang)-d*math.sin(f2*ang) - seg=Part.makeLine((x1,y1,z),(x2,y2,z)) - wire=Part.Wire([wire,seg]) - x1=x2 - y1=y2 - ang=ang+dang #increment angle - fp.Shape = wire #result shape + x2 = f1 * math.cos(ang) - d * math.cos(f2 * ang) + y2 = f1 * math.sin(ang) - d * math.sin(f2 * ang) + seg = Part.makeLine((x1, y1, z), (x2, y2, z)) + wire = Part.Wire([wire, seg]) + x1 = x2 + y1 = y2 + ang = ang + dang # increment angle + fp.Shape = wire # result shape + def makeEpitrochoid(): doc = FreeCAD.activeDocument() if doc is None: doc = FreeCAD.newDocument() - epitrochoid=doc.addObject("Part::FeaturePython","Epitrochoid") #add object to document + epitrochoid = doc.addObject("Part::FeaturePython", "Epitrochoid") # add object to document epitrochoid.Label = "Epitrochoid" Epitrochoid(epitrochoid) - epitrochoid.ViewObject.Proxy=0 + epitrochoid.ViewObject.Proxy = 0 doc.recompute() -if __name__ == "__main__": #feature will be generated after macro execution + +if __name__ == "__main__": # feature will be generated after macro execution makeEpitrochoid() diff --git a/src/Mod/PartDesign/Scripts/FilletArc.py b/src/Mod/PartDesign/Scripts/FilletArc.py index 26c8b3b466..17ca7eda16 100644 --- a/src/Mod/PartDesign/Scripts/FilletArc.py +++ b/src/Mod/PartDesign/Scripts/FilletArc.py @@ -10,6 +10,7 @@ __author__ = "Werner Mayer " import math + # 3d vector class class Vector: def __init__(self, x, y, z): @@ -18,25 +19,26 @@ class Vector: self.z = z def add(self, vec): - return Vector(self.x+vec.x, self.y+vec.y, self.z+vec.z) + return Vector(self.x + vec.x, self.y + vec.y, self.z + vec.z) def sub(self, vec): - return Vector(self.x-vec.x, self.y-vec.y, self.z-vec.z) + return Vector(self.x - vec.x, self.y - vec.y, self.z - vec.z) def dot(self, vec): - return self.x*vec.x+self.y*vec.y+self.z*vec.z + return self.x * vec.x + self.y * vec.y + self.z * vec.z def mult(self, s): - return Vector(self.x*s, self.y*s, self.z*s) + return Vector(self.x * s, self.y * s, self.z * s) - def cross(self,vec): + def cross(self, vec): return Vector( self.y * vec.z - self.z * vec.y, self.z * vec.x - self.x * vec.z, - self.x * vec.y - self.y * vec.x) + self.x * vec.y - self.y * vec.x, + ) def length(self): - return math.sqrt(self.x*self.x+self.y*self.y+self.z*self.z) + return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) def norm(self): l = self.length() @@ -67,7 +69,7 @@ def sgn(val): # ccw ... counter-clockwise means which part of the arc is given. ccw must be either True or False -def makeFilletArc(M1,P,Q,N,r2,ccw): +def makeFilletArc(M1, P, Q, N, r2, ccw): u = Q.sub(P) v = P.sub(M1) if ccw: @@ -83,14 +85,14 @@ def makeFilletArc(M1,P,Q,N,r2,ccw): # distinguish between internal and external fillets r2 *= sgn(uv) - cc = 2.0 * r2 * (b.dot(v)-r1) + cc = 2.0 * r2 * (b.dot(v) - r1) dd = uv * uv - uu * cc if dd < 0: raise RuntimeError("Unable to calculate intersection points") t1 = (-uv + math.sqrt(dd)) / uu t2 = (-uv - math.sqrt(dd)) / uu - if (abs(t1) < abs(t2)): + if abs(t1) < abs(t2): t = t1 else: t = t2 @@ -100,13 +102,12 @@ def makeFilletArc(M1,P,Q,N,r2,ccw): ut = u.mult(t) print(ut) M2 = P.add(ut).add(br2) - S1 = M1.mult(r2/(r1+r2)).add(M2.mult(r1/(r1+r2))) + S1 = M1.mult(r2 / (r1 + r2)).add(M2.mult(r1 / (r1 + r2))) S2 = M2.sub(br2) return (S1, S2, M2) - def test(): from FreeCAD import Base import Part @@ -126,6 +127,13 @@ def test(): Part.show(Part.makeLine(P3, Q)) Part.show(arc.toShape()) - (S1, S2, M2) = makeArc(Vector(C.x,C.y,C.z), Vector(P3.x,P3.y,P3.z), Vector(Q.x, Q.y, Q.z), Vector(axis.x, axis.y, axis.z), r2, ccw) + (S1, S2, M2) = makeArc( + Vector(C.x, C.y, C.z), + Vector(P3.x, P3.y, P3.z), + Vector(Q.x, Q.y, Q.z), + Vector(axis.x, axis.y, axis.z), + r2, + ccw, + ) circle = Part.Circle(Base.Vector(M2.x, M2.y, M2.z), Base.Vector(0, 0, 1), math.fabs(r2)) Part.show(circle.toShape()) diff --git a/src/Mod/PartDesign/Scripts/Gear.py b/src/Mod/PartDesign/Scripts/Gear.py index d357b52e34..a85a1da31a 100644 --- a/src/Mod/PartDesign/Scripts/Gear.py +++ b/src/Mod/PartDesign/Scripts/Gear.py @@ -36,36 +36,36 @@ def compute(): N = int(l1.text()) p = float(l2.text()) alfa = int(l3.text()) - y = float(l4.text()) # standard value y<1 for gear drives y>1 for Gear pumps - m = p/math.pi # standard value 0.06, 0.12, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 60 (polish norm) - c = float(l5.text())*m # standard value 0,1*m - 0,3*m - j = float(l6.text())*m # standard value 0,015 - 0,04*m - width = float(l7.text()) # gear width + y = float(l4.text()) # standard value y<1 for gear drives y>1 for Gear pumps + m = ( + p / math.pi + ) # standard value 0.06, 0.12, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 60 (polish norm) + c = float(l5.text()) * m # standard value 0,1*m - 0,3*m + j = float(l6.text()) * m # standard value 0,015 - 0,04*m + width = float(l7.text()) # gear width except ValueError: FreeCAD.Console.PrintError("Wrong input! Only numbers allowed.\n") - # tooth height - h = 2*y*m+c + h = 2 * y * m + c # pitch diameter - d = N*m + d = N * m # root diameter - df = d - 2*y*m - 2*c # df=d-2hf where and hf=y*m+c + df = d - 2 * y * m - 2 * c # df=d-2hf where and hf=y*m+c # addendum diameter - da = d + 2*y*m # da=d+2ha where ha=y*m + da = d + 2 * y * m # da=d+2ha where ha=y*m # base diameter for involute db = d * math.cos(math.radians(alfa)) - - #Base circle + # Base circle baseCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "BaseCircle") Draft._Circle(baseCircle) Draft._ViewProviderDraft(baseCircle.ViewObject) - baseCircle.Radius = db/2 + baseCircle.Radius = db / 2 baseCircle.FirstAngle = 0.0 baseCircle.LastAngle = 0.0 @@ -73,7 +73,7 @@ def compute(): rootCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "RootCircle") Draft._Circle(rootCircle) Draft._ViewProviderDraft(rootCircle.ViewObject) - rootCircle.Radius = df/2 + rootCircle.Radius = df / 2 rootCircle.FirstAngle = 0.0 rootCircle.LastAngle = 0.0 @@ -81,7 +81,7 @@ def compute(): addendumCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "AddendumCircle") Draft._Circle(addendumCircle) Draft._ViewProviderDraft(addendumCircle.ViewObject) - addendumCircle.Radius = da/2 + addendumCircle.Radius = da / 2 addendumCircle.FirstAngle = 0.0 addendumCircle.LastAngle = 0.0 @@ -89,105 +89,122 @@ def compute(): pitchCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "PitchCircle") Draft._Circle(pitchCircle) Draft._ViewProviderDraft(pitchCircle.ViewObject) - pitchCircle.Radius = d/2 + pitchCircle.Radius = d / 2 pitchCircle.FirstAngle = 0.0 pitchCircle.LastAngle = 0.0 -#************ Calculating right sides of teeth + # ************ Calculating right sides of teeth # Involute of base circle involute = [] involutee = [] involutesav = [] for t in range(0, 60, 1): - x = db/2*(math.cos(math.radians(t))+math.radians(t)*math.sin(math.radians(t))) - y = db/2*(math.sin(math.radians(t))-math.radians(t)*math.cos(math.radians(t))) + x = db / 2 * (math.cos(math.radians(t)) + math.radians(t) * math.sin(math.radians(t))) + y = db / 2 * (math.sin(math.radians(t)) - math.radians(t) * math.cos(math.radians(t))) involute.append(Part.Vertex(x, y, 0).Point) -#************ Drawing right sides of teeth + # ************ Drawing right sides of teeth involutesav.extend(involute) involutee.extend(involute) - for angle in range(1, N+1, 1): + for angle in range(1, N + 1, 1): involuteobj = FreeCAD.ActiveDocument.addObject("Part::Feature", "InvoluteL" + str(angle)) involutee.insert(0, (0, 0, 0)) involuteshape = Part.makePolygon(involutee) - involuteobj.Shape=involuteshape + involuteobj.Shape = involuteshape involutee = [] for num in range(0, 60, 1): point = involute.pop() - pointt = Part.Vertex(point.x*math.cos(math.radians(angle*360/N)) - point.y*math.sin(math.radians(angle*360/N)),point.x*math.sin(math.radians(angle*360/N)) + point.y*math.cos(math.radians(angle*360/N)),0).Point - involutee.insert(0,pointt) + pointt = Part.Vertex( + point.x * math.cos(math.radians(angle * 360 / N)) + - point.y * math.sin(math.radians(angle * 360 / N)), + point.x * math.sin(math.radians(angle * 360 / N)) + + point.y * math.cos(math.radians(angle * 360 / N)), + 0, + ).Point + involutee.insert(0, pointt) involute.extend(involutesav) involutee = [] -#************ Calculating difference between tooth spacing on BaseCircle and PitchCircle + # ************ Calculating difference between tooth spacing on BaseCircle and PitchCircle pc = App.ActiveDocument.getObject("PitchCircle") inv = App.ActiveDocument.getObject("InvoluteL1") cut = inv.Shape.cut(pc.Shape) -# FreeCAD.ActiveDocument.addObject("Part::Feature","CutInv").Shape=cut + # FreeCAD.ActiveDocument.addObject("Part::Feature","CutInv").Shape=cut invPoint = cut.Vertexes[0].Point - diff = invPoint.y*2 # instead of making axial symmetry and calculating point distance. - anglediff = 2*math.asin(diff/d) + diff = invPoint.y * 2 # instead of making axial symmetry and calculating point distance. + anglediff = 2 * math.asin(diff / d) -#************ Calculating left sides of teeth + # ************ Calculating left sides of teeth -#************ Inversing Involute + # ************ Inversing Involute for num in range(0, 60, 1): point = involute.pop() - pointt = Part.Vertex(point.x, point.y*-1, 0).Point + pointt = Part.Vertex(point.x, point.y * -1, 0).Point involutee.insert(0, pointt) involute.extend(involutee) involutee = [] -#Normal tooth size calculated as: 0,5* p - j j = m * 0,1 below are calculations -# 0,5* p - m * 0,1 -# 0,5* p - p /pi * 0,1 -# 0,5*360/N - ((360/N)/pi)* 0,1 -# 0,5*360/N - (360/N)*((1/pi)*0,1) j = (p/pi)*0,1 -# 0,5*360/N - (360/N)*((p/pi)*0,1)/p -# 0,5*360/N - (360/N)*( j )/p + # Normal tooth size calculated as: 0,5* p - j j = m * 0,1 below are calculations + # 0,5* p - m * 0,1 + # 0,5* p - p /pi * 0,1 + # 0,5*360/N - ((360/N)/pi)* 0,1 + # 0,5*360/N - (360/N)*((1/pi)*0,1) j = (p/pi)*0,1 + # 0,5*360/N - (360/N)*((p/pi)*0,1)/p + # 0,5*360/N - (360/N)*( j )/p for num in range(0, 60, 1): point = involute.pop() - pointt = Part.Vertex(point.x*math.cos(math.radians(180/N-(360/N)*(j/p))+anglediff) - point.y*math.sin(math.radians(180/N-(360/N)*(j/p))+anglediff),point.x*math.sin(math.radians(180/N-(360/N)*(j/p))+anglediff) + point.y*math.cos(math.radians(180/N-(360/N)*(j/p))+anglediff),0).Point + pointt = Part.Vertex( + point.x * math.cos(math.radians(180 / N - (360 / N) * (j / p)) + anglediff) + - point.y * math.sin(math.radians(180 / N - (360 / N) * (j / p)) + anglediff), + point.x * math.sin(math.radians(180 / N - (360 / N) * (j / p)) + anglediff) + + point.y * math.cos(math.radians(180 / N - (360 / N) * (j / p)) + anglediff), + 0, + ).Point involutee.insert(0, pointt) involute.extend(involutee) involutesav = [] involutesav.extend(involute) -#************ Drawing left sides of teeth - for angle in range(1, N+1, 1): + # ************ Drawing left sides of teeth + for angle in range(1, N + 1, 1): involuteobj = FreeCAD.ActiveDocument.addObject("Part::Feature", "InvoluteR" + str(angle)) involutee.insert(0, (0, 0, 0)) involuteshape = Part.makePolygon(involutee) involuteobj.Shape = involuteshape involutee = [] - for num in range(0,60,1): + for num in range(0, 60, 1): point = involute.pop() - pointt = Part.Vertex(point.x*math.cos(math.radians(angle*360/N)) - point.y*math.sin(math.radians(angle*360/N)),point.x*math.sin(math.radians(angle*360/N)) + point.y*math.cos(math.radians(angle*360/N)),0).Point - involutee.insert(0,pointt) + pointt = Part.Vertex( + point.x * math.cos(math.radians(angle * 360 / N)) + - point.y * math.sin(math.radians(angle * 360 / N)), + point.x * math.sin(math.radians(angle * 360 / N)) + + point.y * math.cos(math.radians(angle * 360 / N)), + 0, + ).Point + involutee.insert(0, pointt) involute.extend(involutesav) Gui.SendMsgToActiveView("ViewFit") -#************ Forming teeth + # ************ Forming teeth cutCircle = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "CutCircle") Draft._Circle(cutCircle) Draft._ViewProviderDraft(cutCircle.ViewObject) - cutCircle.Radius = da # da because must be bigger than addendumCircle and bigger than whole construction da is right for this but it not has to be. + cutCircle.Radius = da # da because must be bigger than addendumCircle and bigger than whole construction da is right for this but it not has to be. cutCircle.FirstAngle = 0.0 cutCircle.LastAngle = 0.0 - cutTool = cutCircle.Shape.cut(addendumCircle.Shape) # cutshape = Part.show(cutTool) gearShape = rootCircle.Shape - for invNum in range(1, N+1, 1): + for invNum in range(1, N + 1, 1): invL = App.ActiveDocument.getObject("InvoluteL" + str(invNum)) invR = App.ActiveDocument.getObject("InvoluteR" + str(invNum)) cutL = invL.Shape.cut(cutTool) @@ -200,11 +217,10 @@ def compute(): toothWhole = toothWhole.fuse(faceEdge) toothWire = Part.Wire(toothWhole.Edges) toothShape = Part.Face(toothWire) -# tooth = App.ActiveDocument.addObject("Part::Feature", "Tooth" +str(invNum)) -# tooth.Shape=toothShape + # tooth = App.ActiveDocument.addObject("Part::Feature", "Tooth" +str(invNum)) + # tooth.Shape=toothShape gearShape = gearShape.fuse(toothShape) - for o in App.ActiveDocument.Objects: if oldDocumentObjects.count(o) == 0: App.ActiveDocument.removeObject(o.Name) @@ -218,12 +234,13 @@ def compute(): gear.Dir = (0, 0, width) App.ActiveDocument.recompute() - if c1.isChecked(): gearMesh = App.ActiveDocument.addObject("Mesh::Feature", "Gear3D-mesh") faces = [] - triangles = gear.Shape.tessellate(1) # the number represents the precision of the tessellation) + triangles = gear.Shape.tessellate( + 1 + ) # the number represents the precision of the tessellation) for tri in triangles[1]: face = [] for i in range(3): @@ -236,20 +253,20 @@ def compute(): App.ActiveDocument.removeObject(gear.Name) App.ActiveDocument.removeObject(gearFlat.Name) - App.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") QtGui.QApplication.restoreOverrideCursor() - hide() + def hide(): dialog.hide() + dialog = QtGui.QDialog() -dialog.resize(200,450) +dialog.resize(200, 450) dialog.setWindowTitle("Gear") la = QtGui.QVBoxLayout(dialog) t1 = QtGui.QLabel("Number of teeth (N)") @@ -296,7 +313,7 @@ la.addWidget(e1) okbox = QtGui.QDialogButtonBox(dialog) okbox.setOrientation(QtCore.Qt.Horizontal) -okbox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) +okbox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok) la.addWidget(okbox) QtCore.QObject.connect(okbox, QtCore.SIGNAL("accepted()"), proceed) QtCore.QObject.connect(okbox, QtCore.SIGNAL("rejected()"), hide) diff --git a/src/Mod/PartDesign/Scripts/Parallelepiped.py b/src/Mod/PartDesign/Scripts/Parallelepiped.py index 5662e34ae8..6c1baf9d02 100644 --- a/src/Mod/PartDesign/Scripts/Parallelepiped.py +++ b/src/Mod/PartDesign/Scripts/Parallelepiped.py @@ -10,12 +10,19 @@ __author__ = "Werner Mayer " import FreeCAD, Part, math from FreeCAD import Base + class Parallelepiped: def __init__(self, obj): - ''' Add the properties: Length, Edges, Radius, Height ''' - obj.addProperty("App::PropertyVector","A","Parallelepiped","Vector", locked=True).A=Base.Vector(1,0,0) - obj.addProperty("App::PropertyVector","B","Parallelepiped","Vector", locked=True).B=Base.Vector(0,1,0) - obj.addProperty("App::PropertyVector","C","Parallelepiped","Vector", locked=True).C=Base.Vector(0,0,1) + """Add the properties: Length, Edges, Radius, Height""" + obj.addProperty("App::PropertyVector", "A", "Parallelepiped", "Vector", locked=True).A = ( + Base.Vector(1, 0, 0) + ) + obj.addProperty("App::PropertyVector", "B", "Parallelepiped", "Vector", locked=True).B = ( + Base.Vector(0, 1, 0) + ) + obj.addProperty("App::PropertyVector", "C", "Parallelepiped", "Vector", locked=True).C = ( + Base.Vector(0, 0, 1) + ) obj.Proxy = self def onChanged(self, fp, prop): @@ -27,24 +34,31 @@ class Parallelepiped: b = fp.B c = fp.C - m=Base.Matrix() - m.A11=a.x - m.A12=a.y - m.A13=a.z - m.A21=b.x - m.A22=b.y - m.A23=b.z - m.A31=c.x - m.A32=c.y - m.A33=c.z - box = Part.makeBox(1,1,1) + m = Base.Matrix() + m.A11 = a.x + m.A12 = a.y + m.A13 = a.z + m.A21 = b.x + m.A22 = b.y + m.A23 = b.z + m.A31 = c.x + m.A32 = c.y + m.A33 = c.z + box = Part.makeBox(1, 1, 1) fp.Shape = box.transformGeometry(m) + class BoxCylinder: def __init__(self, obj): - obj.addProperty("App::PropertyFloat","Length","BoxCylinder","Length", locked=True).Length=10.0 - obj.addProperty("App::PropertyFloat","Width","BoxCylinder","Width", locked=True).Width=10.0 - obj.addProperty("App::PropertyLink","Source","BoxCylinder","Source", locked=True).Source=None + obj.addProperty( + "App::PropertyFloat", "Length", "BoxCylinder", "Length", locked=True + ).Length = 10.0 + obj.addProperty( + "App::PropertyFloat", "Width", "BoxCylinder", "Width", locked=True + ).Width = 10.0 + obj.addProperty( + "App::PropertyLink", "Source", "BoxCylinder", "Source", locked=True + ).Source = None obj.Proxy = self def onChanged(self, fp, prop): @@ -52,36 +66,37 @@ class BoxCylinder: self.execute(fp) def execute(self, fp): - FreeCAD.Console.PrintMessage(str(fp.Source)+"\n") + FreeCAD.Console.PrintMessage(str(fp.Source) + "\n") if fp.Source is None: return r = fp.Source.Radius l = fp.Length w = fp.Width - h = 2*r+10 - fp.Shape = Part.makeBox(l,w,h) + h = 2 * r + 10 + fp.Shape = Part.makeBox(l, w, h) + def makeParallelepiped(): doc = FreeCAD.activeDocument() if doc is None: doc = FreeCAD.newDocument() - obj=doc.addObject("Part::FeaturePython","Parallelepiped") + obj = doc.addObject("Part::FeaturePython", "Parallelepiped") obj.Label = "Parallelepiped" Parallelepiped(obj) - obj.ViewObject.Proxy=0 + obj.ViewObject.Proxy = 0 def makeBoxCylinder(): doc = FreeCAD.activeDocument() if doc is None: doc = FreeCAD.newDocument() - cyl=doc.addObject("Part::Cylinder","Cylinder") - cyl.Radius=16.0 - cyl.Height=800.0 - obj=doc.addObject("Part::FeaturePython","Box") + cyl = doc.addObject("Part::Cylinder", "Cylinder") + cyl.Radius = 16.0 + cyl.Height = 800.0 + obj = doc.addObject("Part::FeaturePython", "Box") BoxCylinder(obj) - obj.Source=cyl - obj.Length=800.0 - obj.Width=600.0 - obj.ViewObject.Proxy=0 + obj.Source = cyl + obj.Length = 800.0 + obj.Width = 600.0 + obj.ViewObject.Proxy = 0 doc.recompute() diff --git a/src/Mod/PartDesign/Scripts/RadialCopy.py b/src/Mod/PartDesign/Scripts/RadialCopy.py index 98ca5a4cad..b65597ed53 100644 --- a/src/Mod/PartDesign/Scripts/RadialCopy.py +++ b/src/Mod/PartDesign/Scripts/RadialCopy.py @@ -10,6 +10,7 @@ import FreeCAD, FreeCADGui, Part, math from PySide import QtGui from FreeCAD import Base + def makeCopy(shape, radius, angle): mat = Base.Matrix() mat.rotateZ(math.radians(angle)) @@ -25,14 +26,16 @@ def makeCopy(shape, radius, angle): class RadialCopy: def __init__(self, obj): - obj.addProperty("App::PropertyLength","Radius","","Radius", locked=True).Radius=10.0 - obj.addProperty("App::PropertyLength","Angle" ,"","Angle", locked=True).Angle=20.0 - obj.addProperty("App::PropertyLink","Source" ,"","Source shape", locked=True).Source=None + obj.addProperty("App::PropertyLength", "Radius", "", "Radius", locked=True).Radius = 10.0 + obj.addProperty("App::PropertyLength", "Angle", "", "Angle", locked=True).Angle = 20.0 + obj.addProperty("App::PropertyLink", "Source", "", "Source shape", locked=True).Source = ( + None + ) obj.Proxy = self -# def onChanged(self, fp, prop): -# if prop == "Angle" or prop == "Radius": -# self.execute(fp) + # def onChanged(self, fp, prop): + # if prop == "Angle" or prop == "Radius": + # self.execute(fp) def execute(self, fp): shape = fp.Source.Shape @@ -40,6 +43,7 @@ class RadialCopy: angle = fp.Angle fp.Shape = makeCopy(shape, radius, angle) + def makeRadialCopy(): sel = FreeCADGui.Selection.getSelection() try: @@ -47,13 +51,12 @@ def makeRadialCopy(): shape = sel.Shape name = sel.Label except (IndexError, AttributeError): - QtGui.QMessageBox.critical(None,"Wrong selection","Please select a shape object") - #raise Exception("Nothing selected") + QtGui.QMessageBox.critical(None, "Wrong selection", "Please select a shape object") + # raise Exception("Nothing selected") else: doc = sel.Document - rc = doc.addObject("Part::FeaturePython","RadialCopy") - rc.Label = name+"(Radial Copy)" + rc = doc.addObject("Part::FeaturePython", "RadialCopy") + rc.Label = name + "(Radial Copy)" RadialCopy(rc) rc.Source = sel - rc.ViewObject.Proxy=0 - + rc.ViewObject.Proxy = 0 diff --git a/src/Mod/PartDesign/Scripts/Spring.py b/src/Mod/PartDesign/Scripts/Spring.py index d5005c5c8e..d27608a908 100644 --- a/src/Mod/PartDesign/Scripts/Spring.py +++ b/src/Mod/PartDesign/Scripts/Spring.py @@ -1,51 +1,61 @@ #! python # (c) 2011 Adrian Przekwas LGPL -from __future__ import division # allows floating point division from integers +from __future__ import division # allows floating point division from integers import FreeCAD, Part from FreeCAD import Base + class MySpring: - def __init__(self, obj): - ''' Add the properties: Pitch, Diameter, Height, BarDiameter ''' - obj.addProperty("App::PropertyLength", "Pitch", "MySpring", "Pitch of the helix", locked=True).Pitch = 5.0 - obj.addProperty("App::PropertyLength", "Diameter", "MySpring", "Diameter of the helix", locked=True).Diameter = 6.0 - obj.addProperty("App::PropertyLength", "Height", "MySpring", "Height of the helix", locked=True).Height = 30.0 - obj.addProperty("App::PropertyLength", "BarDiameter", "MySpring", "Diameter of the bar", locked=True).BarDiameter = 3.0 - obj.Proxy = self + def __init__(self, obj): + """Add the properties: Pitch, Diameter, Height, BarDiameter""" + obj.addProperty( + "App::PropertyLength", "Pitch", "MySpring", "Pitch of the helix", locked=True + ).Pitch = 5.0 + obj.addProperty( + "App::PropertyLength", "Diameter", "MySpring", "Diameter of the helix", locked=True + ).Diameter = 6.0 + obj.addProperty( + "App::PropertyLength", "Height", "MySpring", "Height of the helix", locked=True + ).Height = 30.0 + obj.addProperty( + "App::PropertyLength", "BarDiameter", "MySpring", "Diameter of the bar", locked=True + ).BarDiameter = 3.0 + obj.Proxy = self - def onChanged(self, fp, prop): - if prop == "Pitch" or prop == "Diameter" or prop == "Height" or prop == "BarDiameter": - self.execute(fp) + def onChanged(self, fp, prop): + if prop == "Pitch" or prop == "Diameter" or prop == "Height" or prop == "BarDiameter": + self.execute(fp) + + def execute(self, fp): + pitch = fp.Pitch + radius = fp.Diameter / 2 + height = fp.Height + barradius = fp.BarDiameter / 2 + myhelix = Part.makeHelix(pitch, height, radius) + g = myhelix.Edges[0].Curve + c = Part.Circle() + c.Center = g.value(0) # start point of the helix + c.Axis = (0, 1, 0) + c.Radius = barradius + p = c.toShape() + section = Part.Wire([p]) + makeSolid = True + isFrenet = True + myspring = Part.Wire(myhelix).makePipeShell([section], makeSolid, isFrenet) + fp.Shape = myspring - def execute(self, fp): - pitch = fp.Pitch - radius = fp.Diameter/2 - height = fp.Height - barradius = fp.BarDiameter/2 - myhelix = Part.makeHelix(pitch, height, radius) - g = myhelix.Edges[0].Curve - c = Part.Circle() - c.Center = g.value(0) # start point of the helix - c.Axis = (0, 1, 0) - c.Radius = barradius - p = c.toShape() - section = Part.Wire([p]) - makeSolid = True - isFrenet = True - myspring = Part.Wire(myhelix).makePipeShell([section], makeSolid, isFrenet) - fp.Shape = myspring def makeMySpring(): - doc = FreeCAD.activeDocument() - if doc is None: - doc = FreeCAD.newDocument() - spring = doc.addObject("Part::FeaturePython", "My_Spring") - spring.Label = "My Spring" - MySpring(spring) - spring.ViewObject.Proxy = 0 - doc.recompute() + doc = FreeCAD.activeDocument() + if doc is None: + doc = FreeCAD.newDocument() + spring = doc.addObject("Part::FeaturePython", "My_Spring") + spring.Label = "My Spring" + MySpring(spring) + spring.ViewObject.Proxy = 0 + doc.recompute() if __name__ == "__main__": - makeMySpring() + makeMySpring() diff --git a/src/Mod/PartDesign/SprocketFeature.py b/src/Mod/PartDesign/SprocketFeature.py index 35afaace08..bdc466ba77 100644 --- a/src/Mod/PartDesign/SprocketFeature.py +++ b/src/Mod/PartDesign/SprocketFeature.py @@ -1,23 +1,23 @@ -#*************************************************************************** -#* Copyright (c) 2020 Adam Spontarelli * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program 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 program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2020 Adam Spontarelli * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program 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 program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** import FreeCAD, Part from fcsprocket import fcsprocket @@ -28,7 +28,7 @@ if FreeCAD.GuiUp: from PySide import QtCore, QtGui from FreeCADGui import PySideUic as uic -__title__="PartDesign SprocketObject management" +__title__ = "PartDesign SprocketObject management" __author__ = "Adam Spontarelli" __url__ = "https://www.freecad.org" @@ -37,31 +37,35 @@ def makeSprocket(name): """ makeSprocket(name): makes a Sprocket """ - obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython",name) + obj = FreeCAD.ActiveDocument.addObject("Part::Part2DObjectPython", name) Sprocket(obj) if FreeCAD.GuiUp: ViewProviderSprocket(obj.ViewObject) - #FreeCAD.ActiveDocument.recompute() + # FreeCAD.ActiveDocument.recompute() if FreeCAD.GuiUp: - body=FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody") - part=FreeCADGui.ActiveDocument.ActiveView.getActiveObject("part") + body = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("pdbody") + part = FreeCADGui.ActiveDocument.ActiveView.getActiveObject("part") if body: - body.Group=body.Group+[obj] + body.Group = body.Group + [obj] elif part: - part.Group=part.Group+[obj] + part.Group = part.Group + [obj] return obj -class CommandSprocket: +class CommandSprocket: """ the Fem Sprocket command definition """ def GetResources(self): - return {'Pixmap' : 'PartDesign_Sprocket', - 'MenuText': QtCore.QT_TRANSLATE_NOOP("PartDesign_Sprocket","Sprocket"), - 'Accel': "", - 'ToolTip': QtCore.QT_TRANSLATE_NOOP("PartDesign_Sprocket","Creates or edits the sprocket definition.")} + return { + "Pixmap": "PartDesign_Sprocket", + "MenuText": QtCore.QT_TRANSLATE_NOOP("PartDesign_Sprocket", "Sprocket"), + "Accel": "", + "ToolTip": QtCore.QT_TRANSLATE_NOOP( + "PartDesign_Sprocket", "Creates or edits the sprocket definition." + ), + } def Activated(self): @@ -136,7 +140,8 @@ class Sprocket: "App::PropertyEnumeration", "SprocketReference", "Sprocket", - "Sprocket Reference", locked=True, + "Sprocket Reference", + locked=True, ) obj.SprocketReference = list(self.sprockRef) obj.Proxy = self @@ -154,13 +159,9 @@ class Sprocket: else: setattr(obj, name, default) - ensure_property( - "App::PropertyInteger", "NumberOfTeeth", "Number of gear teeth", 50 - ) + ensure_property("App::PropertyInteger", "NumberOfTeeth", "Number of gear teeth", 50) ensure_property("App::PropertyLength", "Pitch", "Chain Pitch", "0.375 in") - ensure_property( - "App::PropertyLength", "RollerDiameter", "Roller Diameter", "0.20 in" - ) + ensure_property("App::PropertyLength", "RollerDiameter", "Roller Diameter", "0.20 in") ensure_property( "App::PropertyLength", "Thickness", @@ -170,9 +171,7 @@ class Sprocket: def execute(self, obj): w = fcsprocket.FCWireBuilder() - sprocket.CreateSprocket( - w, obj.Pitch.Value, obj.NumberOfTeeth, obj.RollerDiameter.Value - ) + sprocket.CreateSprocket(w, obj.Pitch.Value, obj.NumberOfTeeth, obj.RollerDiameter.Value) sprocketw = Part.Wire([o.toShape() for o in w.wire]) obj.Shape = sprocketw @@ -285,13 +284,9 @@ class SprocketTaskPanel: def sprocketReferenceChanged(self, size): self.obj.Pitch = str(Sprocket.SprocketReferenceRollerTable[size][0]) + " in" - self.obj.RollerDiameter = ( - str(Sprocket.SprocketReferenceRollerTable[size][1]) + " in" - ) + self.obj.RollerDiameter = str(Sprocket.SprocketReferenceRollerTable[size][1]) + " in" self.obj.Thickness = str(Sprocket.SprocketReferenceRollerTable[size][2]) + " in" - self.obj.SprocketReference = self.obj.getEnumerationsOfProperty( - "SprocketReference" - )[size] + self.obj.SprocketReference = self.obj.getEnumerationsOfProperty("SprocketReference")[size] self.form.Quantity_Pitch.setText(self.obj.Pitch.UserString) self.form.Quantity_RollerDiameter.setText(self.obj.RollerDiameter.UserString) self.form.Quantity_Thickness.setText(self.obj.Thickness.UserString) @@ -312,7 +307,9 @@ class SprocketTaskPanel: self.obj.Proxy.execute(self.obj) def getStandardButtons(self): - return QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Apply + return ( + QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Apply + ) def clicked(self, button): if button == QtGui.QDialogButtonBox.Apply: diff --git a/src/Mod/PartDesign/TestPartDesignApp.py b/src/Mod/PartDesign/TestPartDesignApp.py index be25234622..08a1b3a324 100644 --- a/src/Mod/PartDesign/TestPartDesignApp.py +++ b/src/Mod/PartDesign/TestPartDesignApp.py @@ -1,4 +1,4 @@ -#************************************************************************** +# ************************************************************************** # Copyright (c) 2011 Juergen Riegel * # * # This file is part of the FreeCAD CAx development system. * @@ -18,11 +18,11 @@ # License along with FreeCAD; if not, write to the Free Software * # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # USA * -#************************************************************************** +# ************************************************************************** -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- # define the test cases to test the FreeCAD PartDesign module -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- # datum tools from PartDesignTests.TestDatum import TestDatumPoint, TestDatumLine, TestDatumPlane diff --git a/src/Mod/PartDesign/TestPartDesignGui.py b/src/Mod/PartDesign/TestPartDesignGui.py index 84f84fb5d6..515dfacf43 100644 --- a/src/Mod/PartDesign/TestPartDesignGui.py +++ b/src/Mod/PartDesign/TestPartDesignGui.py @@ -1,4 +1,4 @@ -#************************************************************************** +# ************************************************************************** # Copyright (c) 2011 Juergen Riegel * # * # This file is part of the FreeCAD CAx development system. * @@ -18,7 +18,7 @@ # License along with FreeCAD; if not, write to the Free Software * # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * # USA * -#************************************************************************** +# ************************************************************************** import FreeCAD import FreeCADGui @@ -37,112 +37,126 @@ from PySide.QtGui import QApplication from PartDesignTests.TestMaterial import TestMaterial from PartDesignTests.TestActiveObject import TestActiveObject -#timer runs this class in order to access modal dialog + +# timer runs this class in order to access modal dialog class CallableCheckWorkflow: def __init__(self, test): self.test = test + def __call__(self): dialog = QApplication.activeModalWidget() self.test.assertIsNotNone(dialog, "Dialog box could not be found") - if (dialog is not None): + if dialog is not None: dialogcheck = CallableCheckDialogWasClosed(self.test) QtCore.QTimer.singleShot(500, dialogcheck) - QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT('accept()')) + QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT("accept()")) + class CallableCheckDialogWasClosed: def __init__(self, test): self.test = test + def __call__(self): dialog = QApplication.activeModalWidget() self.test.assertIsNone(dialog, "Dialog box was not closed by accept()") + class CallableCheckWarning: def __init__(self, test): self.test = test + def __call__(self): dialog = QApplication.activeModalWidget() self.test.assertIsNotNone(dialog, "Input dialog box could not be found") - if (dialog is not None): - QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT('accept()')) + if dialog is not None: + QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT("accept()")) + class CallableComboBox: def __init__(self, test): self.test = test + def __call__(self): dialog = QApplication.activeModalWidget() self.test.assertIsNotNone(dialog, "Warning dialog box could not be found") - if (dialog is not None): + if dialog is not None: cbox = dialog.findChild(QtGui.QComboBox) self.test.assertIsNotNone(cbox, "ComboBox widget could not be found") - if (cbox is not None): - QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT('accept()')) + if cbox is not None: + QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT("accept()")) class CallableCheckExemptionDialog: def __init__(self, test): self.test = test + def __call__(self): dialog = QApplication.activeModalWidget() if dialog is not None: dialogcheck = CallableCheckExemptionDialogWasClosed(self.test) QtCore.QTimer.singleShot(100, dialogcheck) - QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT('accept()')) + QtCore.QTimer.singleShot(0, dialog, QtCore.SLOT("accept()")) + class CallableCheckExemptionDialogWasClosed: def __init__(self, test): self.test = test + def __call__(self): dialog = QApplication.activeModalWidget() self.test.assertIsNone(dialog, "Dialog box was not closed by accept()") - App = FreeCAD Gui = FreeCADGui -#--------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- # define the test cases to test the FreeCAD PartDesign module -#--------------------------------------------------------------------------- +# --------------------------------------------------------------------------- class PartDesignGuiTestCases(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("SketchGuiTest") def testRefuseToMoveSingleFeature(self): - FreeCAD.Console.PrintMessage('Testing refuse to move the feature with dependencies from one body to another\n') - self.BodySource = self.Doc.addObject('PartDesign::Body','Body') - Gui.activateView('Gui::View3DInventor', True) - Gui.activeView().setActiveObject('pdbody', self.BodySource) + FreeCAD.Console.PrintMessage( + "Testing refuse to move the feature with dependencies from one body to another\n" + ) + self.BodySource = self.Doc.addObject("PartDesign::Body", "Body") + Gui.activateView("Gui::View3DInventor", True) + Gui.activeView().setActiveObject("pdbody", self.BodySource) - self.BoxObj = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.BoxObj.Length=10.0 - self.BoxObj.Width=10.0 - self.BoxObj.Height=10.0 + self.BoxObj = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.BoxObj.Length = 10.0 + self.BoxObj.Width = 10.0 + self.BoxObj.Height = 10.0 self.BodySource.addObject(self.BoxObj) App.ActiveDocument.recompute() - self.Sketch = self.Doc.addObject('Sketcher::SketchObject','Sketch') - self.Sketch.AttachmentSupport = (self.BoxObj, ('Face3',)) - self.Sketch.MapMode = 'FlatFace' + self.Sketch = self.Doc.addObject("Sketcher::SketchObject", "Sketch") + self.Sketch.AttachmentSupport = (self.BoxObj, ("Face3",)) + self.Sketch.MapMode = "FlatFace" self.BodySource.addObject(self.Sketch) geoList = [] - geoList.append(Part.LineSegment(App.Vector(2.0,8.0,0),App.Vector(8.0,8.0,0))) - geoList.append(Part.LineSegment(App.Vector(8.0,8.0,0),App.Vector(8.0,2.0,0))) - geoList.append(Part.LineSegment(App.Vector(8.0,2.0,0),App.Vector(2.0,2.0,0))) - geoList.append(Part.LineSegment(App.Vector(2.0,2.0,0),App.Vector(2.0,8.0,0))) - self.Sketch.addGeometry(geoList,False) + geoList.append(Part.LineSegment(App.Vector(2.0, 8.0, 0), App.Vector(8.0, 8.0, 0))) + geoList.append(Part.LineSegment(App.Vector(8.0, 8.0, 0), App.Vector(8.0, 2.0, 0))) + geoList.append(Part.LineSegment(App.Vector(8.0, 2.0, 0), App.Vector(2.0, 2.0, 0))) + geoList.append(Part.LineSegment(App.Vector(2.0, 2.0, 0), App.Vector(2.0, 8.0, 0))) + self.Sketch.addGeometry(geoList, False) conList = [] - conList.append(Sketcher.Constraint('Coincident',0,2,1,1)) - conList.append(Sketcher.Constraint('Coincident',1,2,2,1)) - conList.append(Sketcher.Constraint('Coincident',2,2,3,1)) - conList.append(Sketcher.Constraint('Coincident',3,2,0,1)) - conList.append(Sketcher.Constraint('Horizontal',0)) - conList.append(Sketcher.Constraint('Horizontal',2)) - conList.append(Sketcher.Constraint('Vertical',1)) - conList.append(Sketcher.Constraint('Vertical',3)) + conList.append(Sketcher.Constraint("Coincident", 0, 2, 1, 1)) + conList.append(Sketcher.Constraint("Coincident", 1, 2, 2, 1)) + conList.append(Sketcher.Constraint("Coincident", 2, 2, 3, 1)) + conList.append(Sketcher.Constraint("Coincident", 3, 2, 0, 1)) + conList.append(Sketcher.Constraint("Horizontal", 0)) + conList.append(Sketcher.Constraint("Horizontal", 2)) + conList.append(Sketcher.Constraint("Vertical", 1)) + conList.append(Sketcher.Constraint("Vertical", 3)) self.Sketch.addConstraint(conList) - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.Pad.Profile = self.Sketch self.Pad.Length = 10.000000 self.Pad.Length2 = 100.000000 @@ -157,46 +171,61 @@ class PartDesignGuiTestCases(unittest.TestCase): self.Doc.recompute() Gui.SendMsgToActiveView("ViewFit") - self.BodyTarget = self.Doc.addObject('PartDesign::Body','Body') + self.BodyTarget = self.Doc.addObject("PartDesign::Body", "Body") Gui.Selection.addSelection(App.ActiveDocument.Pad) cobj = CallableCheckWarning(self) QtCore.QTimer.singleShot(500, cobj) - Gui.runCommand('PartDesign_MoveFeature') - #assert dependencies of the Sketch + Gui.runCommand("PartDesign_MoveFeature") + # assert dependencies of the Sketch self.assertEqual(len(self.BodySource.Group), 3, "Source body feature count is wrong") self.assertEqual(len(self.BodyTarget.Group), 0, "Target body feature count is wrong") def testMoveSingleFeature(self): - FreeCAD.Console.PrintMessage('Testing moving one feature from one body to another\n') - self.BodySource = self.Doc.addObject('PartDesign::Body','Body') - Gui.activateView('Gui::View3DInventor', True) - Gui.activeView().setActiveObject('pdbody', self.BodySource) + FreeCAD.Console.PrintMessage("Testing moving one feature from one body to another\n") + self.BodySource = self.Doc.addObject("PartDesign::Body", "Body") + Gui.activateView("Gui::View3DInventor", True) + Gui.activeView().setActiveObject("pdbody", self.BodySource) - self.Sketch = self.Doc.addObject('Sketcher::SketchObject','Sketch') + self.Sketch = self.Doc.addObject("Sketcher::SketchObject", "Sketch") self.BodySource.addObject(self.Sketch) - self.Sketch.AttachmentSupport = (self.BodySource.Origin.OriginFeatures[3], ['']) - self.Sketch.MapMode = 'FlatFace' - + self.Sketch.AttachmentSupport = (self.BodySource.Origin.OriginFeatures[3], [""]) + self.Sketch.MapMode = "FlatFace" geoList = [] - geoList.append(Part.LineSegment(App.Vector(-10.000000,10.000000,0),App.Vector(10.000000,10.000000,0))) - geoList.append(Part.LineSegment(App.Vector(10.000000,10.000000,0),App.Vector(10.000000,-10.000000,0))) - geoList.append(Part.LineSegment(App.Vector(10.000000,-10.000000,0),App.Vector(-10.000000,-10.000000,0))) - geoList.append(Part.LineSegment(App.Vector(-10.000000,-10.000000,0),App.Vector(-10.000000,10.000000,0))) - self.Sketch.addGeometry(geoList,False) + geoList.append( + Part.LineSegment( + App.Vector(-10.000000, 10.000000, 0), App.Vector(10.000000, 10.000000, 0) + ) + ) + geoList.append( + Part.LineSegment( + App.Vector(10.000000, 10.000000, 0), App.Vector(10.000000, -10.000000, 0) + ) + ) + geoList.append( + Part.LineSegment( + App.Vector(10.000000, -10.000000, 0), App.Vector(-10.000000, -10.000000, 0) + ) + ) + geoList.append( + Part.LineSegment( + App.Vector(-10.000000, -10.000000, 0), App.Vector(-10.000000, 10.000000, 0) + ) + ) + self.Sketch.addGeometry(geoList, False) conList = [] - conList.append(Sketcher.Constraint('Coincident',0,2,1,1)) - conList.append(Sketcher.Constraint('Coincident',1,2,2,1)) - conList.append(Sketcher.Constraint('Coincident',2,2,3,1)) - conList.append(Sketcher.Constraint('Coincident',3,2,0,1)) - conList.append(Sketcher.Constraint('Horizontal',0)) - conList.append(Sketcher.Constraint('Horizontal',2)) - conList.append(Sketcher.Constraint('Vertical',1)) - conList.append(Sketcher.Constraint('Vertical',3)) + conList.append(Sketcher.Constraint("Coincident", 0, 2, 1, 1)) + conList.append(Sketcher.Constraint("Coincident", 1, 2, 2, 1)) + conList.append(Sketcher.Constraint("Coincident", 2, 2, 3, 1)) + conList.append(Sketcher.Constraint("Coincident", 3, 2, 0, 1)) + conList.append(Sketcher.Constraint("Horizontal", 0)) + conList.append(Sketcher.Constraint("Horizontal", 2)) + conList.append(Sketcher.Constraint("Vertical", 1)) + conList.append(Sketcher.Constraint("Vertical", 3)) self.Sketch.addConstraint(conList) - self.Pad = self.Doc.addObject("PartDesign::Pad","Pad") + self.Pad = self.Doc.addObject("PartDesign::Pad", "Pad") self.BodySource.addObject(self.Pad) self.Pad.Profile = self.Sketch self.Pad.Length = 10.000000 @@ -210,48 +239,53 @@ class PartDesignGuiTestCases(unittest.TestCase): self.Doc.recompute() Gui.SendMsgToActiveView("ViewFit") - self.BodyTarget = self.Doc.addObject('PartDesign::Body','Body') + self.BodyTarget = self.Doc.addObject("PartDesign::Body", "Body") Gui.Selection.addSelection(App.ActiveDocument.Pad) cobj = CallableComboBox(self) QtCore.QTimer.singleShot(500, cobj) - Gui.runCommand('PartDesign_MoveFeature') - #assert dependencies of the Sketch + Gui.runCommand("PartDesign_MoveFeature") + # assert dependencies of the Sketch self.Doc.recompute() - self.assertFalse(self.Sketch.AttachmentSupport[0][0] in self.BodySource.Origin.OriginFeatures) - self.assertTrue(self.Sketch.AttachmentSupport[0][0] in self.BodyTarget.Origin.OriginFeatures) + self.assertFalse( + self.Sketch.AttachmentSupport[0][0] in self.BodySource.Origin.OriginFeatures + ) + self.assertTrue( + self.Sketch.AttachmentSupport[0][0] in self.BodyTarget.Origin.OriginFeatures + ) self.assertEqual(len(self.BodySource.Group), 0, "Source body feature count is wrong") self.assertEqual(len(self.BodyTarget.Group), 2, "Target body feature count is wrong") def tearDown(self): FreeCAD.closeDocument("SketchGuiTest") + class PartDesignTransformed(unittest.TestCase): def setUp(self): self.Doc = App.newDocument("PartDesignTransformed") - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.BoxObj = self.Doc.addObject('PartDesign::AdditiveBox','Box') - self.BoxObj.Length=10.0 - self.BoxObj.Width=10.0 - self.BoxObj.Height=10.0 + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.BoxObj = self.Doc.addObject("PartDesign::AdditiveBox", "Box") + self.BoxObj.Length = 10.0 + self.BoxObj.Width = 10.0 + self.BoxObj.Height = 10.0 App.ActiveDocument.recompute() - #not adding box to the body to imitate undertermined workflow + # not adding box to the body to imitate undertermined workflow tempDir = tempfile.gettempdir() - self.TempDoc = os.path.join(tempDir, 'PartDesignTransformed.FCStd') + self.TempDoc = os.path.join(tempDir, "PartDesignTransformed.FCStd") if os.path.exists(self.TempDoc): os.remove(self.TempDoc) App.ActiveDocument.saveAs(self.TempDoc) App.closeDocument("PartDesignTransformed") def tearDown(self): - #closing doc - if (App.ActiveDocument is not None and App.ActiveDocument.Name == PartDesignTransformed): + # closing doc + if App.ActiveDocument is not None and App.ActiveDocument.Name == PartDesignTransformed: App.closeDocument("PartDesignTransformed") - #print ("omit closing document for debugging") + # print ("omit closing document for debugging") def testMultiTransformCase(self): - App.Console.PrintMessage('Testing applying MultiTransform to the Box outside the body\n') + App.Console.PrintMessage("Testing applying MultiTransform to the Box outside the body\n") App.open(self.TempDoc) App.setActiveDocument("PartDesignTransformed") Gui.Selection.addSelection(App.ActiveDocument.Box) @@ -283,14 +317,15 @@ class CreateSketch(unittest.TestCase): workflowcheck = CallableCheckExemptionDialog(self) QtCore.QTimer.singleShot(100, workflowcheck) FreeCADGui.runCommand("PartDesign_CompSketches", 0) - taskspanel = mw.findChild(QtGui.QWidget,"PartDesignGui__TaskFeaturePick") + taskspanel = mw.findChild(QtGui.QWidget, "PartDesignGui__TaskFeaturePick") self.assertTrue(taskspanel is not None) if taskspanel is not None: QtCore.QTimer.singleShot(0, taskspanel, QtCore.SLOT("hide()")) App.closeDocument(App.ActiveDocument.Name) param.SetBool("NewSketchUseAttachmentDialog", useAttachmentSaved) -#class PartDesignGuiTestCases(unittest.TestCase): + +# class PartDesignGuiTestCases(unittest.TestCase): # def setUp(self): # self.Doc = FreeCAD.newDocument("SketchGuiTest") # @@ -305,6 +340,7 @@ class CreateSketch(unittest.TestCase): # #closing doc # FreeCAD.closeDocument("SketchGuiTest") + class TestShapeBinder(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("PartDesignTestShapeBinder") @@ -314,17 +350,22 @@ class TestShapeBinder(unittest.TestCase): A shape binder uses a different default color than a Part feature. This color must still be set after its creation. """ - self.Body = self.Doc.addObject('PartDesign::Body','Body') - self.Box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + self.Body = self.Doc.addObject("PartDesign::Body", "Body") + self.Box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") self.Body.addObject(self.Box) self.Doc.recompute() - binder = self.Doc.addObject('PartDesign::ShapeBinder','ShapeBinder') - binder.Support = [(self.Box, 'Face1')] + binder = self.Doc.addObject("PartDesign::ShapeBinder", "ShapeBinder") + binder.Support = [(self.Box, "Face1")] grp = App.ParamGet("User parameter:BaseApp/Preferences/Mod/PartDesign") packed_color = grp.GetUnsigned("DefaultDatumColor", 0xFFD70099) r, g, b, a = binder.ViewObject.ShapeColor - color = int(r * 255.0 + 0.5) << 24 | int(g * 255.0 + 0.5) << 16 | int(b * 255.0 + 0.5) << 8 | int(a * 255.0 + 0.5) + color = ( + int(r * 255.0 + 0.5) << 24 + | int(g * 255.0 + 0.5) << 16 + | int(b * 255.0 + 0.5) << 8 + | int(a * 255.0 + 0.5) + ) self.assertEqual(packed_color, color) @@ -344,18 +385,23 @@ class TestSubShapeBinder(unittest.TestCase): A sub-shape binder uses a different default color than a Part feature. This color must still be set after its creation. """ - body = self.Doc.addObject('PartDesign::Body','Body') - box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + body = self.Doc.addObject("PartDesign::Body", "Body") + box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") body.addObject(box) self.Doc.recompute() - binder = body.newObject('PartDesign::SubShapeBinder','Binder') + binder = body.newObject("PartDesign::SubShapeBinder", "Binder") binder.Support = [(box, ("Face1"))] grp = App.ParamGet("User parameter:BaseApp/Preferences/Mod/PartDesign") packed_color = grp.GetUnsigned("DefaultDatumColor", 0xFFD70099) r, g, b, a = binder.ViewObject.ShapeColor - color = int(r * 255.0 + 0.5) << 24 | int(g * 255.0 + 0.5) << 16 | int(b * 255.0 + 0.5) << 8 | int(a * 255.0 + 0.5) + color = ( + int(r * 255.0 + 0.5) << 24 + | int(g * 255.0 + 0.5) << 16 + | int(b * 255.0 + 0.5) << 8 + | int(a * 255.0 + 0.5) + ) self.assertEqual(packed_color, color) @@ -372,20 +418,24 @@ class TestDatumPlane(unittest.TestCase): A datum object uses a different default color than a Part feature. This color must still be set after its creation. """ - body = self.Doc.addObject('PartDesign::Body','Body') - box = self.Doc.addObject('PartDesign::AdditiveBox','Box') + body = self.Doc.addObject("PartDesign::Body", "Body") + box = self.Doc.addObject("PartDesign::AdditiveBox", "Box") body.addObject(box) self.Doc.recompute() - datum = body.newObject('PartDesign::Plane','DatumPlane') - datum.AttachmentSupport = [(box, 'Face6')] - datum.MapMode = 'FlatFace' + datum = body.newObject("PartDesign::Plane", "DatumPlane") + datum.AttachmentSupport = [(box, "Face6")] + datum.MapMode = "FlatFace" self.Doc.recompute() grp = App.ParamGet("User parameter:BaseApp/Preferences/Mod/PartDesign") packed_color = grp.GetUnsigned("DefaultDatumColor", 0xFFD70099) r, g, b, a = datum.ViewObject.ShapeColor - color = int(r * 255.0 + 0.5) << 24 | int(g * 255.0 + 0.5) << 16 | int(b * 255.0 + 0.5) << 8 | int(a * 255.0 + 0.5) + color = ( + int(r * 255.0 + 0.5) << 24 + | int(g * 255.0 + 0.5) << 16 + | int(b * 255.0 + 0.5) << 8 + | int(a * 255.0 + 0.5) + ) self.assertEqual(packed_color, color) - diff --git a/src/Mod/PartDesign/WizardShaft/SegmentFunction.py b/src/Mod/PartDesign/WizardShaft/SegmentFunction.py index a9ee010e37..89efc6a63d 100644 --- a/src/Mod/PartDesign/WizardShaft/SegmentFunction.py +++ b/src/Mod/PartDesign/WizardShaft/SegmentFunction.py @@ -1,4 +1,4 @@ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * @@ -20,9 +20,10 @@ # * * # ******************************************************************************/ -import FreeCAD # just for debug printing to console... +import FreeCAD # just for debug printing to console... import numpy as np + class SegmentFunctionSegment: "One segment of a segment function" @@ -34,12 +35,12 @@ class SegmentFunctionSegment: def hasStart(self, xval): "Return true if the start of this segment is xval" - #FIXME: 1E-9 is arbitrary here. But since units are in meters, 1E-9 is a nanometer... - return abs(self.start - xval) < 1E-9 + # FIXME: 1E-9 is arbitrary here. But since units are in meters, 1E-9 is a nanometer... + return abs(self.start - xval) < 1e-9 def isZero(self): - #FIXME: 1E-9 is arbitrary here. But since units are in meters, 1E-9 is a nanometer... - return abs(self.coefficient) < 1E-5 + # FIXME: 1E-9 is arbitrary here. But since units are in meters, 1E-9 is a nanometer... + return abs(self.coefficient) < 1e-5 def value(self, xval): if xval < self.start: @@ -55,10 +56,14 @@ class SegmentFunctionSegment: return self def negated(self): - return SegmentFunctionSegment(self.start, self.variable, self.coefficient * -1.0, self.exponent) + return SegmentFunctionSegment( + self.start, self.variable, self.coefficient * -1.0, self.exponent + ) - def __mul__(self, value): - return SegmentFunctionSegment(self.start, self.variable, self.coefficient * value, self.exponent) + def __mul__(self, value): + return SegmentFunctionSegment( + self.start, self.variable, self.coefficient * value, self.exponent + ) def integrate(self): self.exponent = self.exponent + 1 @@ -68,15 +73,16 @@ class SegmentFunctionSegment: def asString(self): return "%f * {%s - %f}^%i" % (self.coefficient, self.variable, self.start, self.exponent) + class SegmentFunction: "Function that is defined segment-wise" - def __init__(self, name = "f(x)"): + def __init__(self, name="f(x)"): self.variable = "x" self.segments = [] self.name = name - def findSegment(self, xval): + def findSegment(self, xval): "Find segment valid for the given xval" for s in self.segments: if s.start <= xval: @@ -101,7 +107,7 @@ class SegmentFunction: result.segments.append(s.negated()) return result - def __mul__(self, value): + def __mul__(self, value): result = SegmentFunction() result.variable = self.variable for s in self.segments: @@ -121,16 +127,18 @@ class SegmentFunction: def buildFromDict(self, var, dict): self.variable = var for key in sorted(dict): - #if abs(dict[key]) > 1E-9: + # if abs(dict[key]) > 1E-9: self.segments.append(SegmentFunctionSegment(key, var, dict[key], 0)) - def addSegment(self, st, coeff, exp = 0.0): - if abs(coeff) > 1E-9: - self.segments.insert(self.index(st), SegmentFunctionSegment(st, self.variable, coeff, exp)) + def addSegment(self, st, coeff, exp=0.0): + if abs(coeff) > 1e-9: + self.segments.insert( + self.index(st), SegmentFunctionSegment(st, self.variable, coeff, exp) + ) def addSegments(self, dict): for key in sorted(dict): - self.addSegment(key, dict[key]) + self.addSegment(key, dict[key]) def setMaxX(self, mx): self.maxX = mx @@ -146,7 +154,7 @@ class SegmentFunction: "Return the value of the previous segment at the specified x value" result = 0 for s in self.segments: - result = result + s.value(xval - 1E-8) + result = result + s.value(xval - 1e-8) return result def clone(self): @@ -173,7 +181,7 @@ class SegmentFunction: offset = (maxX - self.segments[0].start) / (pointsX - 1) xvals = set([self.segments[0].start + s * offset for s in range(pointsX)]) starts = set([self.segments[i].start for i in range(len(self.segments))]) - xvals = xvals.union(starts) # Make sure we have a point on each segment start + xvals = xvals.union(starts) # Make sure we have a point on each segment start xresult = [] yresult = [] for xval in sorted(xvals): @@ -193,6 +201,7 @@ class SegmentFunction: FreeCAD.Console.PrintMessage(" + ") FreeCAD.Console.PrintMessage("\n") + class IntervalFunction: "Function defined in intervals" @@ -200,27 +209,27 @@ class IntervalFunction: self.intervals = [] self.values = [] - def addInterval(self, begin, length, value): - self.intervals.append((begin, length)) + def addInterval(self, begin, length, value): + self.intervals.append((begin, length)) self.values.append(value) - def value(self, xval): + def value(self, xval): for i in range(len(self.intervals)): if xval >= self.intervals[i][0] and xval < self.intervals[i][0] + self.intervals[i][1]: - return self.values[i] - return self.values[len(self.values)-1] + return self.values[i] + return self.values[len(self.values) - 1] - def lowervalue(self, xval): - return self.value(xval - 1E-8) + def lowervalue(self, xval): + return self.value(xval - 1e-8) - def index(self, xval): + def index(self, xval): lastStart = 0.0 for i in range(len(self.intervals)): newStart = self.intervals[i][0] if (xval >= lastStart) and (xval < newStart): - return i-1 + return i - 1 lastStart = newStart - return len(self.intervals)-1 + return len(self.intervals) - 1 def interval(self, xval): "Return interval (begin, length) for this xval" @@ -232,13 +241,17 @@ class IntervalFunction: def length(self, xval): return self.intervals[self.index(xval)][1] + class StressFunction: "Specialization for segment-wise display of stresses" + # The hairy thing about this is that the segments of the segfunc usually do not correspond with the intervals of the intfunc! - def __init__(self, f, i): - self.segfunc = f # The segment function for the force/moment - self.intfunc = i # The divisors, an interval function giving a specific value for each interval + def __init__(self, f, i): + self.segfunc = f # The segment function for the force/moment + self.intfunc = ( + i # The divisors, an interval function giving a specific value for each interval + ) name = "sigma" def isZero(self): @@ -249,7 +262,7 @@ class StressFunction: offset = (maxX - self.segfunc.segments[0].start) / (pointsX - 1) xvals = set([self.segfunc.segments[0].start + s * offset for s in range(pointsX)]) starts = set([self.segfunc.segments[i].start for i in range(len(self.segfunc.segments))]) - xvals = xvals.union(starts) # Make sure we have a point on each segment start + xvals = xvals.union(starts) # Make sure we have a point on each segment start divs = set([self.intfunc.intervals[i][0] for i in range(len(self.intfunc.intervals))]) xvals = xvals.union(divs) @@ -260,7 +273,7 @@ class StressFunction: # create double point at segment border xresult.append(xval) yresult.append(self.segfunc.lowervalue(xval) / self.intfunc.value(xval)) - if (xval in divs): + if xval in divs: # create double point at divisor border xresult.append(xval) yresult.append(self.segfunc.value(xval) / self.intfunc.lowervalue(xval)) @@ -268,21 +281,24 @@ class StressFunction: yresult.append(self.segfunc.value(xval) / self.intfunc.value(xval)) return (xresult, yresult) + class TranslationFunction: "Specialization for segment-wise display of translations" - def __init__(self, f, E, d, tangents, translations): + def __init__(self, f, E, d, tangents, translations): if f.isZero(): self.transfunc = None return # Note: Integration has to be segment-wise because the area moment is not constant in different segments. But this only becomes relevant # when boundary conditions are being applied # E I_i w_i'(x) = tangfunc + C_i0 - self.tangfunc = f.integrated() # The segment function for the tangent to the bending line + self.tangfunc = f.integrated() # The segment function for the tangent to the bending line self.tangfunc.name = "w'" self.tangfunc.output() # E I_i w_i(x) = transfunc + C_i0 x + C_i1 - self.transfunc = self.tangfunc.integrated() # + C_i0 * x + C_i1 (integration constants for interval number i) + self.transfunc = ( + self.tangfunc.integrated() + ) # + C_i0 * x + C_i1 (integration constants for interval number i) self.transfunc.name = "w" self.transfunc.output() self.module = E @@ -295,9 +311,9 @@ class TranslationFunction: # Note that the relevant boundaries are those of the intfunc (where the area moment of the shaft cross-section changes) # Every interval of the transfunc has two integration constants C_i0 and C_i1 that need to be defined # Matrix of coefficients - A = np.zeros(shape = (2 * len(self.intfunc.intervals), 2 * len(self.intfunc.intervals))) + A = np.zeros(shape=(2 * len(self.intfunc.intervals), 2 * len(self.intfunc.intervals))) # Vector of RHS values - b = np.zeros(shape = 2 * len(self.intfunc.intervals)) + b = np.zeros(shape=2 * len(self.intfunc.intervals)) # Current row where coefficients of next equation will be added row = 0 @@ -305,8 +321,8 @@ class TranslationFunction: for bound in tangents: xval = bound[0] tang = bound[1] - i = self.intfunc.index(xval) # index of this segment - I_i = self.intfunc.value(xval) # Area moment of this segment + i = self.intfunc.index(xval) # index of this segment + I_i = self.intfunc.value(xval) # Area moment of this segment # w_i'(xval) = tang => (tangfunc(xval) + C_i0) / (E * I_i) = tang => C_i0 = tang * (E * I_i) - tangfunc(xval) A[row][2 * i] = 1.0 b[row] = tang * E * I_i - self.tangfunc.value(xval) @@ -314,8 +330,8 @@ class TranslationFunction: for bound in translations: xval = bound[0] trans = bound[1] - i = self.intfunc.index(xval) # index of this segment - I_i = self.intfunc.value(xval) # Area moment of this segment + i = self.intfunc.index(xval) # index of this segment + I_i = self.intfunc.value(xval) # Area moment of this segment # w_i(xval) = trans => (transfunc(xval) + C_i0 * xval + C_i1) / (E * I_i) = trans => xval / (E * I_i) * C_i0 + 1 / (E * I_i) * C_i1 = trans - transfunc(xval) / (E * I_i) A[row][2 * i] = xval / (E * I_i) A[row][2 * i + 1] = 1 / (E * I_i) @@ -326,30 +342,34 @@ class TranslationFunction: for i in range(len(self.intfunc.intervals) - 1): x_start = self.intfunc.intervals[i][0] x_end = x_start + self.intfunc.intervals[i][1] - I_i = self.intfunc.value(x_start) # Area moment of this segment + I_i = self.intfunc.value(x_start) # Area moment of this segment I_ip1 = self.intfunc.value(x_end) # w_i'(x_end) = w_i+1'(xend) => (tangfunc(x_end) + C_i0) / (E * I_i) = (tangfunc(x_end) * C_i+1,0) / (E * I_i+1) # => 1 / (E * I_i) C_i0 - 1 / (E * I_i+1) * C_i+1,0 = tangfunc(x_end) / (E * I_i+1) - tangfunc(x_end) / (E * I_i) A[row][2 * i] = 1 / (E * I_i) - A[row][2 * (i+1)] = -1 / (E * I_ip1) - b[row] = self.tangfunc.value(x_end) / (E * I_ip1) - self.tangfunc.value(x_end) / (E * I_i) + A[row][2 * (i + 1)] = -1 / (E * I_ip1) + b[row] = self.tangfunc.value(x_end) / (E * I_ip1) - self.tangfunc.value(x_end) / ( + E * I_i + ) row += 1 # w_i(x_end) = w_i+1(xend) => (transfunc(x_end) + C_i0 * x_end + C_i1) / (E * I_i) = (transfunc(x_end) * C_i+1,0) * x_end + C_i+1,1) / (E * I_i+1) # => x_end / (E * I_i) C_i0 + 1 / (E * I_i) C_i1 - x_end / (E * I_i+1) * C_i+1,0 - 1 / (E * I_i+1) * C_i+1,1 = transfunc(x_end) / (E * I_i+1) - transfunc(x_end) / (E * I_i) A[row][2 * i] = x_end / (E * I_i) A[row][2 * i + 1] = 1 / (E * I_i) - A[row][2 * (i+1)] = -x_end / (E * I_ip1) - A[row][2 * (i+1) + 1] = -1 / (E * I_ip1) - b[row] = self.transfunc.value(x_end) / (E * I_ip1) - self.transfunc.value(x_end) / (E * I_i) + A[row][2 * (i + 1)] = -x_end / (E * I_ip1) + A[row][2 * (i + 1) + 1] = -1 / (E * I_ip1) + b[row] = self.transfunc.value(x_end) / (E * I_ip1) - self.transfunc.value(x_end) / ( + E * I_i + ) row += 1 - #FreeCAD.Console.PrintMessage(A) - #FreeCAD.Console.PrintMessage(" * x = ") - #FreeCAD.Console.PrintMessage(b) - #FreeCAD.Console.PrintMessage("\n") + # FreeCAD.Console.PrintMessage(A) + # FreeCAD.Console.PrintMessage(" * x = ") + # FreeCAD.Console.PrintMessage(b) + # FreeCAD.Console.PrintMessage("\n") try: - self.boundaries = np.linalg.solve(A, b) # A * self.boundaries = b + self.boundaries = np.linalg.solve(A, b) # A * self.boundaries = b except np.linalg.linalg.LinAlgError as e: FreeCAD.Console.PrintMessage(e.message) FreeCAD.Console.PrintMessage(". No solution possible.\n") @@ -364,8 +384,10 @@ class TranslationFunction: # Note: This usually creates a few more points than specified in pointsX offset = (maxX - self.transfunc.segments[0].start) / (pointsX - 1) xvals = set([self.transfunc.segments[0].start + s * offset for s in range(pointsX)]) - starts = set([self.transfunc.segments[i].start for i in range(len(self.transfunc.segments))]) - xvals = xvals.union(starts) # Make sure we have a point on each segment start + starts = set( + [self.transfunc.segments[i].start for i in range(len(self.transfunc.segments))] + ) + xvals = xvals.union(starts) # Make sure we have a point on each segment start divs = set([self.intfunc.intervals[i][0] for i in range(len(self.intfunc.intervals))]) xvals = xvals.union(divs) E = self.module @@ -377,16 +399,18 @@ class TranslationFunction: for xval in sorted(xvals): if xval in divs: i = self.intfunc.index(xval) - (begin, length) = self.intfunc.interval(xval) + (begin, length) = self.intfunc.interval(xval) I_i = self.intfunc.value(xval) C_i0 = self.boundaries[2 * i] C_i1 = self.boundaries[2 * i + 1] - FreeCAD.Console.PrintMessage("Interval %u: %f to %f, I_i: %f, C_i0: %f, C_i1: %f\n" % (i, begin, length, I_i, C_i0, C_i1)) + FreeCAD.Console.PrintMessage( + "Interval %u: %f to %f, I_i: %f, C_i0: %f, C_i1: %f\n" + % (i, begin, length, I_i, C_i0, C_i1) + ) xresult.append(xval) # w(xval) = (transfunc(xval) + C_i0 * xval + C_i1) / (E * I_i) - value = (self.transfunc.value(xval) + C_i0 * xval + C_i1) / (E * I_i) + value = (self.transfunc.value(xval) + C_i0 * xval + C_i1) / (E * I_i) yresult.append(value) return (xresult, yresult) - diff --git a/src/Mod/PartDesign/WizardShaft/Shaft.py b/src/Mod/PartDesign/WizardShaft/Shaft.py index e9d321d713..b9eca5eb5e 100644 --- a/src/Mod/PartDesign/WizardShaft/Shaft.py +++ b/src/Mod/PartDesign/WizardShaft/Shaft.py @@ -1,4 +1,4 @@ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * @@ -21,11 +21,12 @@ # ******************************************************************************/ import FreeCAD, FreeCADGui -from .SegmentFunction import SegmentFunction, IntervalFunction, StressFunction, TranslationFunction +from .SegmentFunction import SegmentFunction, IntervalFunction, StressFunction, TranslationFunction from .ShaftFeature import ShaftFeature from .ShaftDiagram import Diagram import math + class ShaftSegment: def __init__(self, l, d, di): self.length = l @@ -34,30 +35,42 @@ class ShaftSegment: self.constraintType = "None" self.constraint = None + class Shaft: "The axis of the shaft is always assumed to correspond to the X-axis" + # Names (note Qy corresponds with Mz, and Qz with My) - Fstr = ["Nx","Qy","Qz"] # Forces - Mstr = ["Mx","Mz","My"] # Moments - wstr = ["", "wy", "wz"] # Translations - sigmaNstr = ["sigmax","sigmay","sigmaz"] # Normal/shear stresses - sigmaBstr = ["taut","sigmabz", "sigmaby"] # Torsion/bending stresses + Fstr = ["Nx", "Qy", "Qz"] # Forces + Mstr = ["Mx", "Mz", "My"] # Moments + wstr = ["", "wy", "wz"] # Translations + sigmaNstr = ["sigmax", "sigmay", "sigmaz"] # Normal/shear stresses + sigmaBstr = ["taut", "sigmabz", "sigmaby"] # Torsion/bending stresses # For diagram labeling - Qstrings = (("Normal force [x]", "x", "mm", "N_x", "N"), - ("Shear force [y]", "x", "mm", "Q_y", "N"), - ("Shear force [z]", "x", "mm", "Q_z", "N")) - Mstrings = (("Torque [x]", "x", "mm", "M_t", "Nm"), - ("Bending moment [z]", "x", "mm", "M_{b,z}", "Nm"), - ("Bending moment [y]", "x", "mm", "M_{b,y}", "Nm")) - wstrings = (("", "", "", "", ""), - ("Translation [y]", "x", "mm", "w_y", "mm"), - ("Translation [z]", "x", "mm", "w_z", "mm")) - sigmaNstrings = (("Normal stress [x]", "x", "mm", "\\sigma_x", u"N/mm²"), - ("Shear stress [y]", "x", "mm", "\\sigma_y", u"N/mm²"), - ("Shear stress [z]", "x", "mm", "\\sigma_z", u"N/mm²")) - sigmaBstrings = (("Torque stress [x]", "x", "mm", "\\tau_t", u"N/mm²"), - ("Bending stress [z]", "x", "mm", "\\sigma_{b,z}", u"N/mm²"), - ("Bending stress [y]", "x", "mm", "\\sigma_{b,y}", u"N/mm²")) + Qstrings = ( + ("Normal force [x]", "x", "mm", "N_x", "N"), + ("Shear force [y]", "x", "mm", "Q_y", "N"), + ("Shear force [z]", "x", "mm", "Q_z", "N"), + ) + Mstrings = ( + ("Torque [x]", "x", "mm", "M_t", "Nm"), + ("Bending moment [z]", "x", "mm", "M_{b,z}", "Nm"), + ("Bending moment [y]", "x", "mm", "M_{b,y}", "Nm"), + ) + wstrings = ( + ("", "", "", "", ""), + ("Translation [y]", "x", "mm", "w_y", "mm"), + ("Translation [z]", "x", "mm", "w_z", "mm"), + ) + sigmaNstrings = ( + ("Normal stress [x]", "x", "mm", "\\sigma_x", "N/mm²"), + ("Shear stress [y]", "x", "mm", "\\sigma_y", "N/mm²"), + ("Shear stress [z]", "x", "mm", "\\sigma_z", "N/mm²"), + ) + sigmaBstrings = ( + ("Torque stress [x]", "x", "mm", "\\tau_t", "N/mm²"), + ("Bending stress [z]", "x", "mm", "\\sigma_{b,z}", "N/mm²"), + ("Bending stress [y]", "x", "mm", "\\sigma_{b,y}", "N/mm²"), + ) def __init__(self, parent): self.parent = parent @@ -66,13 +79,21 @@ class Shaft: # List of shaft segments (each segment has a different diameter) self.segments = [] # The diagrams - self.diagrams = {} # map of function name against Diagram object + self.diagrams = {} # map of function name against Diagram object # Calculation of shaft - self.F = [None, None, None] # force in direction of [x,y,z]-axis - self.M = [None, None, None] # bending moment around [x,z,y]-axis - self.w = [None, None, None] # Shaft translation due to bending - self.sigmaN = [None, None, None] # normal stress in direction of x-axis, shear stress in direction of [y,z]-axis - self.sigmaB = [None, None, None] # # torque stress around x-axis, maximum bending stress in direction of [y,z]-axis + self.F = [None, None, None] # force in direction of [x,y,z]-axis + self.M = [None, None, None] # bending moment around [x,z,y]-axis + self.w = [None, None, None] # Shaft translation due to bending + self.sigmaN = [ + None, + None, + None, + ] # normal stress in direction of x-axis, shear stress in direction of [y,z]-axis + self.sigmaB = [ + None, + None, + None, + ] # # torque stress around x-axis, maximum bending stress in direction of [y,z]-axis def getLengthTo(self, index): "Get the total length of all segments up to the given one" @@ -82,20 +103,22 @@ class Shaft: return result def addSegment(self, l, d, di): - self.segments.append(ShaftSegment(l,d,di)) + self.segments.append(ShaftSegment(l, d, di)) self.feature.addSegment(l, d, di) # We don't call equilibrium() here because the new segment has no constraints defined yet # Fix face reference of fixed segment if it is the last one - for i in range(1, len(self.segments)): + for i in range(1, len(self.segments)): if self.segments[i].constraintType != "Fixed": continue if i == len(self.segments) - 1: - self.segments[index].constraint.References = [( self.feature.feature, "Face%u" % (2 * (index+1) + 1) )] + self.segments[index].constraint.References = [ + (self.feature.feature, "Face%u" % (2 * (index + 1) + 1)) + ] else: # Remove reference since it is now in the middle of the shaft (which is not allowed) - self.segments[index].constraint.References = [(None, "")] + self.segments[index].constraint.References = [(None, "")] - def updateSegment(self, index, length = None, diameter = None, innerdiameter = None): + def updateSegment(self, index, length=None, diameter=None, innerdiameter=None): oldLength = self.segments[index].length if length is not None: @@ -105,14 +128,22 @@ class Shaft: if innerdiameter is not None: self.segments[index].innerdiameter = innerdiameter - self.feature.updateSegment(index, oldLength, self.segments[index].length, self.segments[index].diameter, self.segments[index].innerdiameter) + self.feature.updateSegment( + index, + oldLength, + self.segments[index].length, + self.segments[index].diameter, + self.segments[index].innerdiameter, + ) self.equilibrium() self.updateDiagrams() def updateConstraint(self, index, constraintType): - if (constraintType is not None): + if constraintType is not None: # Did the constraint type change? - if (self.segments[index].constraintType != "None") and (self.segments[index].constraintType != constraintType): + if (self.segments[index].constraintType != "None") and ( + self.segments[index].constraintType != constraintType + ): self.doc.removeObject(self.segments[index].constraint.Name) self.segments[index].constraint = None @@ -120,42 +151,48 @@ class Shaft: # Create constraint if it does not exist yet or has changed if self.segments[index].constraint is None: - if (constraintType == "Force"): + if constraintType == "Force": # TODO: Create a reference point and put the force onto it - constraint = self.doc.addObject("Fem::ConstraintForce","ShaftConstraintForce") + constraint = self.doc.addObject("Fem::ConstraintForce", "ShaftConstraintForce") constraint.Force = 1000.0 self.segments[index].constraint = constraint - elif (constraintType == "Fixed"): + elif constraintType == "Fixed": # TODO: Use robust reference as soon as it is available for the face - constraint = self.doc.addObject("Fem::ConstraintFixed","ShaftConstraintFixed") + constraint = self.doc.addObject("Fem::ConstraintFixed", "ShaftConstraintFixed") if index == 0: - constraint.References = [( self.feature.feature, "Face1")] + constraint.References = [(self.feature.feature, "Face1")] elif index == len(self.segments) - 1: - constraint.References = [( self.feature.feature, "Face%u" % (2 * (index+1) + 1) )] + constraint.References = [ + (self.feature.feature, "Face%u" % (2 * (index + 1) + 1)) + ] self.segments[index].constraint = constraint - elif (constraintType == "Bearing"): + elif constraintType == "Bearing": # TODO: Use robust reference as soon as it is available for the cylindrical face reference - constraint = self.doc.addObject("Fem::ConstraintBearing","ShaftConstraintBearing") - constraint.References = [( self.feature.feature, "Face%u" % (2 * (index+1)) )] + constraint = self.doc.addObject( + "Fem::ConstraintBearing", "ShaftConstraintBearing" + ) + constraint.References = [(self.feature.feature, "Face%u" % (2 * (index + 1)))] constraint.AxialFree = True self.segments[index].constraint = constraint - elif (constraintType == "Pulley"): - constraint= self.doc.addObject("Fem::ConstraintPulley","ShaftConstraintPulley") - constraint.References = [( self.feature.feature, "Face%u" % (2 * (index+1)) )] + elif constraintType == "Pulley": + constraint = self.doc.addObject( + "Fem::ConstraintPulley", "ShaftConstraintPulley" + ) + constraint.References = [(self.feature.feature, "Face%u" % (2 * (index + 1)))] self.segments[index].constraint = constraint - elif (constraintType == "Gear"): - constraint = self.doc.addObject("Fem::ConstraintGear","ShaftConstraintGear") - constraint.References = [( self.feature.feature, "Face%u" % (2 * (index+1)) )] + elif constraintType == "Gear": + constraint = self.doc.addObject("Fem::ConstraintGear", "ShaftConstraintGear") + constraint.References = [(self.feature.feature, "Face%u" % (2 * (index + 1)))] self.segments[index].constraint = constraint self.equilibrium() self.updateDiagrams() - def editConstraint(self, index): - if (self.segments[index].constraint is not None): + def editConstraint(self, index): + if self.segments[index].constraint is not None: FreeCADGui.activeDocument().setEdit(self.segments[index].constraint.Name) - def getConstraint(self, index): + def getConstraint(self, index): return self.segments[index].constraint def updateEdge(self, column, start): @@ -196,21 +233,31 @@ class Shaft: for ax in range(3): if self.F[ax] is not None: if self.F[ax].name in self.diagrams: - self.diagrams[self.F[ax].name].update(self.F[ax], self.getLengthTo(len(self.segments)) / 1000.0) + self.diagrams[self.F[ax].name].update( + self.F[ax], self.getLengthTo(len(self.segments)) / 1000.0 + ) if self.M[ax] is not None: if self.M[ax].name in self.diagrams: - self.diagrams[self.M[ax].name].update(self.M[ax], self.getLengthTo(len(self.segments)) / 1000.0) + self.diagrams[self.M[ax].name].update( + self.M[ax], self.getLengthTo(len(self.segments)) / 1000.0 + ) if self.w[ax] is not None: if self.w[ax].name in self.diagrams: - self.diagrams[self.w[ax].name].update(self.w[ax], self.getLengthTo(len(self.segments)) / 1000.0) + self.diagrams[self.w[ax].name].update( + self.w[ax], self.getLengthTo(len(self.segments)) / 1000.0 + ) if self.sigmaN[ax] is not None: if self.sigmaN[ax].name in self.diagrams: - self.diagrams[self.sigmaN[ax].name].update(self.sigmaN[ax], self.getLengthTo(len(self.segments)) / 1000.0) + self.diagrams[self.sigmaN[ax].name].update( + self.sigmaN[ax], self.getLengthTo(len(self.segments)) / 1000.0 + ) if self.sigmaB[ax] is not None: if self.sigmaB[ax].name in self.diagrams: - self.diagrams[self.sigmaB[ax].name].update(self.sigmaB[ax], self.getLengthTo(len(self.segments)) / 1000.0) + self.diagrams[self.sigmaB[ax].name].update( + self.sigmaB[ax], self.getLengthTo(len(self.segments)) / 1000.0 + ) - def showDiagram(self, which): + def showDiagram(self, which): if which in self.Fstr: ax = self.Fstr.index(which) text = self.Qstrings[ax] @@ -220,10 +267,21 @@ class Shaft: if self.F[ax].name in self.diagrams: # Diagram is already open, close it again self.diagrams[self.F[ax].name].close() - del (self.diagrams[self.F[ax].name]) + del self.diagrams[self.F[ax].name] return self.diagrams[self.F[ax].name] = Diagram() - self.diagrams[self.F[ax].name].create(text[0], self.F[ax], self.getLengthTo(len(self.segments)) / 1000.0, text[1], text[2], 1000.0, text[3], text[4], 1.0, 10) + self.diagrams[self.F[ax].name].create( + text[0], + self.F[ax], + self.getLengthTo(len(self.segments)) / 1000.0, + text[1], + text[2], + 1000.0, + text[3], + text[4], + 1.0, + 10, + ) elif which in self.Mstr: ax = self.Mstr.index(which) text = self.Mstrings[ax] @@ -233,10 +291,21 @@ class Shaft: if self.M[ax].name in self.diagrams: # Diagram is already open, close it again self.diagrams[self.M[ax].name].close() - del (self.diagrams[self.M[ax].name]) + del self.diagrams[self.M[ax].name] return self.diagrams[self.M[ax].name] = Diagram() - self.diagrams[self.M[ax].name].create(text[0], self.M[ax], self.getLengthTo(len(self.segments)) / 1000.0, text[1], text[2], 1000.0, text[3], text[4], 1.0, 20) + self.diagrams[self.M[ax].name].create( + text[0], + self.M[ax], + self.getLengthTo(len(self.segments)) / 1000.0, + text[1], + text[2], + 1000.0, + text[3], + text[4], + 1.0, + 20, + ) elif which in self.wstr: ax = self.wstr.index(which) text = self.wstrings[ax] @@ -246,10 +315,21 @@ class Shaft: if self.w[ax].name in self.diagrams: # Diagram is already open, close it again self.diagrams[self.w[ax].name].close() - del (self.diagrams[self.w[ax].name]) + del self.diagrams[self.w[ax].name] return self.diagrams[self.w[ax].name] = Diagram() - self.diagrams[self.w[ax].name].create(text[0], self.w[ax], self.getLengthTo(len(self.segments)) / 1000.0, text[1], text[2], 1000.0, text[3], text[4], 1000.0, 30) + self.diagrams[self.w[ax].name].create( + text[0], + self.w[ax], + self.getLengthTo(len(self.segments)) / 1000.0, + text[1], + text[2], + 1000.0, + text[3], + text[4], + 1000.0, + 30, + ) elif which in self.sigmaNstr: ax = self.sigmaNstr.index(which) text = self.sigmaNstrings[ax] @@ -259,10 +339,21 @@ class Shaft: if self.sigmaN[ax].name in self.diagrams: # Diagram is already open, close it again self.diagrams[self.sigmaN[ax].name].close() - del (self.diagrams[self.sigmaN[ax].name]) + del self.diagrams[self.sigmaN[ax].name] return self.diagrams[self.sigmaN[ax].name] = Diagram() - self.diagrams[self.sigmaN[ax].name].create(text[0], self.sigmaN[ax], self.getLengthTo(len(self.segments)) / 1000.0, text[1], text[2], 1000.0, text[3], text[4], 1.0E-6, 10) + self.diagrams[self.sigmaN[ax].name].create( + text[0], + self.sigmaN[ax], + self.getLengthTo(len(self.segments)) / 1000.0, + text[1], + text[2], + 1000.0, + text[3], + text[4], + 1.0e-6, + 10, + ) elif which in self.sigmaBstr: ax = self.sigmaBstr.index(which) text = self.sigmaBstrings[ax] @@ -272,12 +363,23 @@ class Shaft: if self.sigmaB[ax].name in self.diagrams: # Diagram is already open, close it again self.diagrams[self.sigmaB[ax].name].close() - del (self.diagrams[self.sigmaB[ax].name]) + del self.diagrams[self.sigmaB[ax].name] return self.diagrams[self.sigmaB[ax].name] = Diagram() - self.diagrams[self.sigmaB[ax].name].create(text[0], self.sigmaB[ax], self.getLengthTo(len(self.segments)) / 1000.0, text[1], text[2], 1000.0, text[3], text[4], 1.0E-6, 20) + self.diagrams[self.sigmaB[ax].name].create( + text[0], + self.sigmaB[ax], + self.getLengthTo(len(self.segments)) / 1000.0, + text[1], + text[2], + 1000.0, + text[3], + text[4], + 1.0e-6, + 20, + ) - def addTo(self, dict, location, value): + def addTo(self, dict, location, value): if location not in dict: dict[location] = value else: @@ -296,14 +398,14 @@ class Shaft: # created from them will have signs as by the convention in # http://www.umwelt-campus.de/ucb/fileadmin/users/90_t.preussler/dokumente/Skripte/TEMECH/TMI/Ebene_Balkenstatik.pdf (page 10) # (see also example on page 19) - forces = [{0.0:0.0}, {0.0:0.0}, {0.0:0.0}] - moments = [{0.0:0.0}, {0.0:0.0}, {0.0:0.0}] + forces = [{0.0: 0.0}, {0.0: 0.0}, {0.0: 0.0}] + moments = [{0.0: 0.0}, {0.0: 0.0}, {0.0: 0.0}] # Boundary conditions for shaft bending line - tangents = [[], [], []] # Tangents to shaft bending line - translations = [[], [], []] # Shaft displacement + tangents = [[], [], []] # Tangents to shaft bending line + translations = [[], [], []] # Shaft displacement # Variable names, e.g. Fx, Mz. Because the system must be exactly determined, not more than two independent variables for each # force/moment per axis are possible (if there are more no solution is calculated) - variableNames = [[""], [""], [""]] + variableNames = [[""], [""], [""]] # # dictionary of (variableName : location) giving the x-coordinate at which the force/moment represented by the variable acts on the shaft locations = {} # Coefficients of the equilibrium equations in the form a = b * F1 + c * F2 and d = e * M1 + f * M2 @@ -322,10 +424,12 @@ class Shaft: location = 0 elif i == len(self.segments) - 1: # At end of shaft - location = self.getLengthTo(len(self.segments)) / 1000.0 # convert to meters + location = self.getLengthTo(len(self.segments)) / 1000.0 # convert to meters else: # TODO: Better error message - FreeCAD.Console.PrintMessage("Fixed constraint must be at beginning or end of shaft\n") + FreeCAD.Console.PrintMessage( + "Fixed constraint must be at beginning or end of shaft\n" + ) return for ax in range(3): @@ -335,11 +439,15 @@ class Shaft: # Register location of reaction force locations["%s%u" % (self.Fstr[ax], i)] = location # Boundary conditions for the translations - tangents[ax].append((location, 0.0)) - translations[ax].append((location, 0.0)) - coefficientsM[0].append(0) # Reaction force contributes no moment around x axis - coefficientsM[1].append(location) # Reaction force contributes a positive moment around z axis - coefficientsM[2].append(-location) # Reaction force contributes a negative moment around y axis + tangents[ax].append((location, 0.0)) + translations[ax].append((location, 0.0)) + coefficientsM[0].append(0) # Reaction force contributes no moment around x axis + coefficientsM[1].append( + location + ) # Reaction force contributes a positive moment around z axis + coefficientsM[2].append( + -location + ) # Reaction force contributes a negative moment around y axis for ax in range(3): # Create a new reaction moment @@ -352,78 +460,114 @@ class Shaft: # Static force (currently force on midpoint of segment only) force = constraint.DirectionVector.multiply(constraint.Force) # TODO: Extract value of the location from geometry - location = (self.getLengthTo(i) + self.segments[i].length/2.0) / 1000.0 + location = (self.getLengthTo(i) + self.segments[i].length / 2.0) / 1000.0 # The force itself for ax in range(3): if abs(force[ax]) > 0.0: - coefficientsF[ax][0] = coefficientsF[ax][0] - force[ax] # neg. because this coefficient is on the LHS of the equilibrium equation - self.addTo(forces[ax], location, -force[ax]) # neg. to fulfill the convention mentioned above + coefficientsF[ax][0] = ( + coefficientsF[ax][0] - force[ax] + ) # neg. because this coefficient is on the LHS of the equilibrium equation + self.addTo( + forces[ax], location, -force[ax] + ) # neg. to fulfill the convention mentioned above # Moments created by the force (by definition no moment is created by the force in x-direction) if abs(force[1]) > 0.0: - coefficientsM[1][0] = coefficientsM[1][0] - force[1] * location # moment around z-axis - self.addTo(moments[1], location, 0) + coefficientsM[1][0] = ( + coefficientsM[1][0] - force[1] * location + ) # moment around z-axis + self.addTo(moments[1], location, 0) if abs(force[2]) > 0.0: - coefficientsM[2][0] = coefficientsM[2][0] + force[2] * location # moment around y-axis - self.addTo(moments[2], location, 0) # No outer moment acts here! + coefficientsM[2][0] = ( + coefficientsM[2][0] + force[2] * location + ) # moment around y-axis + self.addTo(moments[2], location, 0) # No outer moment acts here! elif cType == "Bearing": - location = constraint.BasePoint.x / 1000.0 # TODO: This assumes that the shaft feature starts with the first segment at (0,0,0) and its axis corresponds to the x-axis - # Bearing reaction forces. TODO: the bearing is assumed to not induce any reaction moments - start = (0 if constraint.AxialFree == False else 1) - for ax in range(start, 3): + location = ( + constraint.BasePoint.x / 1000.0 + ) # TODO: This assumes that the shaft feature starts with the first segment at (0,0,0) and its axis corresponds to the x-axis + # Bearing reaction forces. TODO: the bearing is assumed to not induce any reaction moments + start = 0 if constraint.AxialFree == False else 1 + for ax in range(start, 3): variableNames[ax].append("%s%u" % (self.Fstr[ax], i)) coefficientsF[ax].append(1) locations["%s%u" % (self.Fstr[ax], i)] = location # Boundary condition - translations[ax].append((location, 0.0)) - if constraint.AxialFree == False: - coefficientsM[0].append(0) # Reaction force contributes no moment around x axis - coefficientsM[1].append(location) # Reaction force contributes a positive moment around z axis - coefficientsM[2].append(-location) # Reaction force contributes a negative moment around y axis + translations[ax].append((location, 0.0)) + if constraint.AxialFree == False: + coefficientsM[0].append(0) # Reaction force contributes no moment around x axis + coefficientsM[1].append( + location + ) # Reaction force contributes a positive moment around z axis + coefficientsM[2].append( + -location + ) # Reaction force contributes a negative moment around y axis elif cType == "Gear": force = constraint.DirectionVector.multiply(constraint.Force) location = constraint.BasePoint.x / 1000.0 - lever = [0, constraint.Diameter/2.0/1000.0 * math.sin(constraint.ForceAngle / 180.0 * math.pi), - constraint.Diameter/2.0 /1000.0* math.cos(constraint.ForceAngle / 180.0 * math.pi)] + lever = [ + 0, + constraint.Diameter + / 2.0 + / 1000.0 + * math.sin(constraint.ForceAngle / 180.0 * math.pi), + constraint.Diameter + / 2.0 + / 1000.0 + * math.cos(constraint.ForceAngle / 180.0 * math.pi), + ] # Effect of the gear force for ax in range(3): if abs(force[ax]) > 0.0: # Effect of the force coefficientsF[ax][0] = coefficientsF[ax][0] - force[ax] - self.addTo(forces[ax], location, -force[ax]) + self.addTo(forces[ax], location, -force[ax]) # Moments created by the force (by definition no moment is created by the force in x-direction) if abs(force[1]) > 0.0: - coefficientsM[1][0] = coefficientsM[1][0] - force[1] * location # moment around z-axis - self.addTo(moments[1], location, 0) + coefficientsM[1][0] = ( + coefficientsM[1][0] - force[1] * location + ) # moment around z-axis + self.addTo(moments[1], location, 0) if abs(force[2]) > 0.0: - coefficientsM[2][0] = coefficientsM[2][0] + force[2] * location # moment around y-axis - self.addTo(moments[2], location, 0) # No outer moment acts here! + coefficientsM[2][0] = ( + coefficientsM[2][0] + force[2] * location + ) # moment around y-axis + self.addTo(moments[2], location, 0) # No outer moment acts here! # Moments created by the force and lever if abs(force[0]) > 0.0: momenty = force[0] * lever[2] momentz = force[0] * lever[1] - coefficientsM[1][0] = coefficientsM[1][0] + momentz # moment around z-axis - self.addTo(moments[1], location, momentz) - coefficientsM[2][0] = coefficientsM[2][0] - momenty # moment around y-axis - self.addTo(moments[2], location, -momenty) + coefficientsM[1][0] = coefficientsM[1][0] + momentz # moment around z-axis + self.addTo(moments[1], location, momentz) + coefficientsM[2][0] = coefficientsM[2][0] - momenty # moment around y-axis + self.addTo(moments[2], location, -momenty) if abs(force[1]) > 0.0: moment = force[1] * lever[2] coefficientsM[0][0] = coefficientsM[0][0] + moment - self.addTo(moments[0], location, moment) + self.addTo(moments[0], location, moment) if abs(force[2]) > 0.0: moment = force[2] * lever[1] coefficientsM[0][0] = coefficientsM[0][0] - moment - self.addTo(moments[0], location, -moment) + self.addTo(moments[0], location, -moment) elif cType == "Pulley": - forceAngle1 = (constraint.ForceAngle + constraint.BeltAngle + 90.0) / 180.0 * math.pi - forceAngle2 = (constraint.ForceAngle - constraint.BeltAngle + 90.0) / 180.0 * math.pi - #FreeCAD.Console.PrintMessage("BeltForce1: %f, BeltForce2: %f\n" % (constraint.BeltForce1, constraint.BeltForce2)) - #FreeCAD.Console.PrintMessage("Angle1: %f, Angle2: %f\n" % (forceAngle1, forceAngle2)) - force = [0, -constraint.BeltForce1 * math.sin(forceAngle1) - constraint.BeltForce2 * math.sin(forceAngle2), - constraint.BeltForce1 * math.cos(forceAngle1) + constraint.BeltForce2 * math.cos(forceAngle2)] + forceAngle1 = ( + (constraint.ForceAngle + constraint.BeltAngle + 90.0) / 180.0 * math.pi + ) + forceAngle2 = ( + (constraint.ForceAngle - constraint.BeltAngle + 90.0) / 180.0 * math.pi + ) + # FreeCAD.Console.PrintMessage("BeltForce1: %f, BeltForce2: %f\n" % (constraint.BeltForce1, constraint.BeltForce2)) + # FreeCAD.Console.PrintMessage("Angle1: %f, Angle2: %f\n" % (forceAngle1, forceAngle2)) + force = [ + 0, + -constraint.BeltForce1 * math.sin(forceAngle1) + - constraint.BeltForce2 * math.sin(forceAngle2), + constraint.BeltForce1 * math.cos(forceAngle1) + + constraint.BeltForce2 * math.cos(forceAngle2), + ] location = constraint.BasePoint.x / 1000.0 # Effect of the pulley forces @@ -431,69 +575,77 @@ class Shaft: if abs(force[ax]) > 0.0: # Effect of the force coefficientsF[ax][0] = coefficientsF[ax][0] - force[ax] - self.addTo(forces[ax], location, -force[ax]) + self.addTo(forces[ax], location, -force[ax]) # Moments created by the force (by definition no moment is created by the force in x-direction) - if abs(force[1] ) > 0.0: - coefficientsM[1][0] = coefficientsM[1][0] - force[1] * location # moment around z-axis - self.addTo(moments[1], location, 0) + if abs(force[1]) > 0.0: + coefficientsM[1][0] = ( + coefficientsM[1][0] - force[1] * location + ) # moment around z-axis + self.addTo(moments[1], location, 0) if abs(force[2]) > 0.0: - coefficientsM[2][0] = coefficientsM[2][0] + force[2] * location # moment around y-axis - self.addTo(moments[2], location, 0) # No outer moment acts here! + coefficientsM[2][0] = ( + coefficientsM[2][0] + force[2] * location + ) # moment around y-axis + self.addTo(moments[2], location, 0) # No outer moment acts here! # Torque moment = constraint.Force * (1 if constraint.IsDriven is True else -1) coefficientsM[0][0] = coefficientsM[0][0] + moment - self.addTo(moments[0], location, moment) + self.addTo(moments[0], location, moment) - areas = [None, None, None] - areamoments = [None, None, None] - bendingmoments = [None, None, None] - torquemoments = [None, None, None] + areas = [None, None, None] + areamoments = [None, None, None] + bendingmoments = [None, None, None] + torquemoments = [None, None, None] for ax in range(3): - FreeCAD.Console.PrintMessage("Axis: %u\n" % ax) + FreeCAD.Console.PrintMessage("Axis: %u\n" % ax) self.printEquilibrium(variableNames[ax], coefficientsF[ax]) self.printEquilibrium(variableNames[ax], coefficientsM[ax]) - if len(coefficientsF[ax]) <= 1: + if len(coefficientsF[ax]) <= 1: # Note: coefficientsF and coefficientsM always have the same length FreeCAD.Console.PrintMessage("Matrix is singular, no solution possible\n") - self.parent.updateButtons(ax, False) + self.parent.updateButtons(ax, False) continue # Handle special cases. Note that the code above should ensure that coefficientsF and coefficientsM always have same length - solution = [None, None] + solution = [None, None] if len(coefficientsF[ax]) == 2: if coefficientsF[ax][1] != 0.0 and coefficientsF[ax][0] != 0.0: solution[0] = coefficientsF[ax][0] / coefficientsF[ax][1] if coefficientsM[ax][1] != 0.0 and coefficientsM[ax][0] != 0.0: solution[1] = coefficientsM[ax][0] / coefficientsM[ax][1] - if abs(solution[0] - solution[1]) < 1E9: - FreeCAD.Console.PrintMessage("System is statically undetermined. No solution possible.\n") - self.parent.updateButtons(ax, False) + if abs(solution[0] - solution[1]) < 1e9: + FreeCAD.Console.PrintMessage( + "System is statically undetermined. No solution possible.\n" + ) + self.parent.updateButtons(ax, False) continue else: # Build matrix and vector for linear algebra solving algorithm - # TODO: This could easily be done manually... there are only 2 variables and 6 coefficients + # TODO: This could easily be done manually... there are only 2 variables and 6 coefficients A = np.array([coefficientsF[ax][1:], coefficientsM[ax][1:]]) b = np.array([coefficientsF[ax][0], coefficientsM[ax][0]]) try: - solution = np.linalg.solve(A, b) # A * solution = b + solution = np.linalg.solve(A, b) # A * solution = b except np.linalg.linalg.LinAlgError as e: FreeCAD.Console.PrintMessage(str(e)) FreeCAD.Console.PrintMessage(". No solution possible.\n") - self.parent.updateButtons(ax, False) + self.parent.updateButtons(ax, False) continue # Complete dictionary of forces and moments with the two reaction forces that were calculated for i in range(2): if solution[i] is None: continue - FreeCAD.Console.PrintMessage("Reaction force/moment: %s = %f\n" % (variableNames[ax][i+1], solution[i])) - if variableNames[ax][i+1][0] == "M": - moments[ax][locations[variableNames[ax][i+1]]] = -solution[i] + FreeCAD.Console.PrintMessage( + "Reaction force/moment: %s = %f\n" % (variableNames[ax][i + 1], solution[i]) + ) + if variableNames[ax][i + 1][0] == "M": + moments[ax][locations[variableNames[ax][i + 1]]] = -solution[i] else: - forces[ax][locations[variableNames[ax][i+1]]] = -solution[i] + forces[ax][locations[variableNames[ax][i + 1]]] = -solution[i] FreeCAD.Console.PrintMessage(forces[ax]) FreeCAD.Console.PrintMessage("\n") @@ -503,61 +655,69 @@ class Shaft: # Forces self.F[ax] = SegmentFunction(self.Fstr[ax]) self.F[ax].buildFromDict("x", forces[ax]) - self.parent.updateButton(1, ax, not self.F[ax].isZero()) + self.parent.updateButton(1, ax, not self.F[ax].isZero()) self.F[ax].output() # Moments if ax == 0: self.M[0] = SegmentFunction(self.Mstr[0]) - self.M[0].buildFromDict("x", moments[0]) + self.M[0].buildFromDict("x", moments[0]) elif ax == 1: self.M[1] = self.F[1].integrated().negate() self.M[1].name = self.Mstr[1] - self.M[1].addSegments(moments[1]) # takes care of boundary conditions + self.M[1].addSegments(moments[1]) # takes care of boundary conditions elif ax == 2: self.M[2] = self.F[2].integrated() self.M[2].name = self.Mstr[2] - self.M[2].addSegments(moments[2]) # takes care of boundary conditions - self.parent.updateButton(2, ax, not self.M[ax].isZero()) + self.M[2].addSegments(moments[2]) # takes care of boundary conditions + self.parent.updateButton(2, ax, not self.M[ax].isZero()) self.M[ax].output() # Areas and area moments location = 0.0 - areas[ax] = IntervalFunction() # A [m²] - areamoments[ax] = IntervalFunction() # I [m⁴] - bendingmoments[ax] = IntervalFunction() # W_b [m³] - torquemoments[ax] = IntervalFunction() # W_t [m³] + areas[ax] = IntervalFunction() # A [m²] + areamoments[ax] = IntervalFunction() # I [m⁴] + bendingmoments[ax] = IntervalFunction() # W_b [m³] + torquemoments[ax] = IntervalFunction() # W_t [m³] for i in range(len(self.segments)): - od = self.segments[i].diameter/1000.0 - id = self.segments[i].innerdiameter/1000.0 - length = self.segments[i].length/1000.0 - areas[ax].addInterval(location, length, math.pi/4.0 * (math.pow(od, 2.0) - math.pow(id, 2.0))) - areamoment = math.pi/64.0 * (math.pow(od, 4.0) - math.pow(id, 4.0)) - areamoments[ax].addInterval(location, length, areamoment) - bendingmoments[ax].addInterval(location, length, areamoment / (od / 2.0)) - torquemoments[ax].addInterval(location, length, 2 * (areamoment / (od / 2.0))) + od = self.segments[i].diameter / 1000.0 + id = self.segments[i].innerdiameter / 1000.0 + length = self.segments[i].length / 1000.0 + areas[ax].addInterval( + location, length, math.pi / 4.0 * (math.pow(od, 2.0) - math.pow(id, 2.0)) + ) + areamoment = math.pi / 64.0 * (math.pow(od, 4.0) - math.pow(id, 4.0)) + areamoments[ax].addInterval(location, length, areamoment) + bendingmoments[ax].addInterval(location, length, areamoment / (od / 2.0)) + torquemoments[ax].addInterval(location, length, 2 * (areamoment / (od / 2.0))) location += length # Bending line if ax > 0: - if len(tangents[ax])+ len(translations[ax]) == 2: + if len(tangents[ax]) + len(translations[ax]) == 2: # TODO: Get Young's module from material type instead of using 210000 N/mm² = 2.1E12 N/m² - self.w[ax] = TranslationFunction(self.M[ax].negated(), 2.1E12, areamoments[ax], tangents[ax], translations[ax]) - self.w[ax].name= self.wstr[ax] - self.parent.updateButton(3, ax, not self.w[ax].isZero()) + self.w[ax] = TranslationFunction( + self.M[ax].negated(), + 2.1e12, + areamoments[ax], + tangents[ax], + translations[ax], + ) + self.w[ax].name = self.wstr[ax] + self.parent.updateButton(3, ax, not self.w[ax].isZero()) else: - self.parent.updateButton(3, ax, False) + self.parent.updateButton(3, ax, False) # Normal/shear stresses and torque/bending stresses - self.sigmaN[ax] = StressFunction(self.F[ax], areas[ax]) + self.sigmaN[ax] = StressFunction(self.F[ax], areas[ax]) self.sigmaN[ax].name = self.sigmaNstr[ax] - self.parent.updateButton(4, ax, not self.sigmaN[ax].isZero()) + self.parent.updateButton(4, ax, not self.sigmaN[ax].isZero()) if ax == 0: - self.sigmaB[ax] = StressFunction(self.M[ax] , torquemoments[ax]) + self.sigmaB[ax] = StressFunction(self.M[ax], torquemoments[ax]) else: - self.sigmaB[ax] = StressFunction(self.M[ax], bendingmoments[ax]) + self.sigmaB[ax] = StressFunction(self.M[ax], bendingmoments[ax]) self.sigmaB[ax].name = self.sigmaBstr[ax] - self.parent.updateButton(5, ax, not self.sigmaB[ax].isZero()) + self.parent.updateButton(5, ax, not self.sigmaB[ax].isZero()) def printEquilibrium(self, var, coeff): # Auxiliary method for debugging purposes diff --git a/src/Mod/PartDesign/WizardShaft/ShaftDiagram.py b/src/Mod/PartDesign/WizardShaft/ShaftDiagram.py index c5fa7b78a3..f53962cf29 100644 --- a/src/Mod/PartDesign/WizardShaft/ShaftDiagram.py +++ b/src/Mod/PartDesign/WizardShaft/ShaftDiagram.py @@ -1,4 +1,4 @@ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * @@ -23,12 +23,16 @@ from PySide import QtCore, QtGui import FreeCAD, FreeCADGui + class Diagram: - def create(self, title, function, xlength, xname, xunit, xscale, yname, yunit, yscale, numxpoints): + def create( + self, title, function, xlength, xname, xunit, xscale, yname, yunit, yscale, numxpoints + ): # Initialize from FreeCAD.Plot import Plot + self.title = title - self.function = function # This is assumed to be always a SegmentFunction + self.function = function # This is assumed to be always a SegmentFunction self.xlength = xlength self.xname = xname self.xunit = xunit @@ -52,7 +56,7 @@ class Diagram: # Create plot self.plot() - def update(self, function = None, xlength = None): + def update(self, function=None, xlength=None): if function is not None: self.function = function if xlength is not None: @@ -78,7 +82,7 @@ class Diagram: self.thePlot.plot(self.xpoints, self.ypoints) plots = self.thePlot.series axes = plots[0].axes - axes.set_xlim(right = max(self.xpoints) * 1.05) + axes.set_xlim(right=max(self.xpoints) * 1.05) axes.set_ylim(min(self.ypoints) * 1.05, max(self.ypoints) * 1.05) self.thePlot.update() diff --git a/src/Mod/PartDesign/WizardShaft/ShaftFeature.py b/src/Mod/PartDesign/WizardShaft/ShaftFeature.py index d2973bdf07..72c5e8d76f 100644 --- a/src/Mod/PartDesign/WizardShaft/ShaftFeature.py +++ b/src/Mod/PartDesign/WizardShaft/ShaftFeature.py @@ -1,4 +1,4 @@ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * @@ -23,8 +23,10 @@ import FreeCAD, FreeCADGui import Part, Sketcher + class ShaftFeature: "Creates and updates the feature of the shaft" + App = FreeCAD Gui = FreeCADGui @@ -33,13 +35,15 @@ class ShaftFeature: self.Doc = doc # TODO: Discover existing sketch and get data from it - self.sketch = self.Doc.addObject("Sketcher::SketchObject","SketchShaft") - self.sketch.Placement = self.App.Placement(self.App.Vector(0,0,0),self.App.Rotation(0,0,0,1)) + self.sketch = self.Doc.addObject("Sketcher::SketchObject", "SketchShaft") + self.sketch.Placement = self.App.Placement( + self.App.Vector(0, 0, 0), self.App.Rotation(0, 0, 0, 1) + ) self.feature = 0 - self.segments = 0 # number of segments - self.totalLength = 0 # total length of all segments - self.lastRadius = 0 # radius of last segment (required for adding segments) + self.segments = 0 # number of segments + self.totalLength = 0 # total length of all segments + self.lastRadius = 0 # radius of last segment (required for adding segments) def addSegment(self, length, diameter, innerdiameter): "Add a segment at the end of the shaft" @@ -70,47 +74,76 @@ class ShaftFeature: if oldLength == 0: # First segment of shaft # Create centerline - self.sketch.addGeometry(Part.LineSegment(self.App.Vector(0,0,0), self.App.Vector(self.totalLength,0,0))) - self.sketch.addConstraint(Sketcher.Constraint('DistanceX',0, self.totalLength)) # Constraint1 - self.sketch.addConstraint(Sketcher.Constraint('DistanceY', -1,1,0,1,innerradius)) # Constraint2 - self.sketch.addConstraint(Sketcher.Constraint('PointOnObject',0,1,-2)) # Constraint3 - self.sketch.addConstraint(Sketcher.Constraint('Horizontal', 0)) # Constraint4 + self.sketch.addGeometry( + Part.LineSegment(self.App.Vector(0, 0, 0), self.App.Vector(self.totalLength, 0, 0)) + ) + self.sketch.addConstraint( + Sketcher.Constraint("DistanceX", 0, self.totalLength) + ) # Constraint1 + self.sketch.addConstraint( + Sketcher.Constraint("DistanceY", -1, 1, 0, 1, innerradius) + ) # Constraint2 + self.sketch.addConstraint(Sketcher.Constraint("PointOnObject", 0, 1, -2)) # Constraint3 + self.sketch.addConstraint(Sketcher.Constraint("Horizontal", 0)) # Constraint4 # Create first segment - self.sketch.addGeometry(Part.LineSegment(self.App.Vector(0,innerradius,0), self.App.Vector(0,radius,0))) - self.sketch.addConstraint(Sketcher.Constraint('DistanceY',-1,1,1,2,radius)) # Constraint5 - self.sketch.addConstraint(Sketcher.Constraint('Coincident',0,1,1,1)) # Constraint6 - self.sketch.addConstraint(Sketcher.Constraint('Vertical',1)) # Constraint7 - self.sketch.addGeometry(Part.LineSegment(self.App.Vector(0,radius,0), self.App.Vector(length,radius,0))) - self.sketch.addConstraint(Sketcher.Constraint('DistanceX',2,length)) # Constraint8 - self.sketch.addConstraint(Sketcher.Constraint('Coincident',2,1,1,2)) # Constraint9 - self.sketch.addConstraint(Sketcher.Constraint('Horizontal',2)) # Constraint10 + self.sketch.addGeometry( + Part.LineSegment(self.App.Vector(0, innerradius, 0), self.App.Vector(0, radius, 0)) + ) + self.sketch.addConstraint( + Sketcher.Constraint("DistanceY", -1, 1, 1, 2, radius) + ) # Constraint5 + self.sketch.addConstraint(Sketcher.Constraint("Coincident", 0, 1, 1, 1)) # Constraint6 + self.sketch.addConstraint(Sketcher.Constraint("Vertical", 1)) # Constraint7 + self.sketch.addGeometry( + Part.LineSegment(self.App.Vector(0, radius, 0), self.App.Vector(length, radius, 0)) + ) + self.sketch.addConstraint(Sketcher.Constraint("DistanceX", 2, length)) # Constraint8 + self.sketch.addConstraint(Sketcher.Constraint("Coincident", 2, 1, 1, 2)) # Constraint9 + self.sketch.addConstraint(Sketcher.Constraint("Horizontal", 2)) # Constraint10 else: # remove line that closes the shaft self.sketch.delGeometry(prevSegEnd) # TODO: Delete the two constraints? Or will they disappear automatically? # Adjust length of centerline - self.sketch.setDatum(0,self.totalLength) + self.sketch.setDatum(0, self.totalLength) # Add segment at the end - self.sketch.addGeometry(Part.LineSegment(self.App.Vector(oldLength,self.lastRadius,0), self.App.Vector(oldLength,radius,0))) - self.sketch.addConstraint(Sketcher.Constraint('DistanceY', -1,1, segRadius, 2, radius)) - self.sketch.addConstraint(Sketcher.Constraint('Coincident',segRadius,1,prevSegLength,2)) - self.sketch.addConstraint(Sketcher.Constraint('Vertical',segRadius)) - self.sketch.addGeometry(Part.LineSegment(self.App.Vector(oldLength,radius,0), self.App.Vector(oldLength+length,radius,0))) - self.sketch.addConstraint(Sketcher.Constraint('DistanceX',segLength,length)) - self.sketch.addConstraint(Sketcher.Constraint('Coincident',segLength,1,segRadius,2)) - self.sketch.addConstraint(Sketcher.Constraint('Horizontal',segLength)) + self.sketch.addGeometry( + Part.LineSegment( + self.App.Vector(oldLength, self.lastRadius, 0), + self.App.Vector(oldLength, radius, 0), + ) + ) + self.sketch.addConstraint(Sketcher.Constraint("DistanceY", -1, 1, segRadius, 2, radius)) + self.sketch.addConstraint( + Sketcher.Constraint("Coincident", segRadius, 1, prevSegLength, 2) + ) + self.sketch.addConstraint(Sketcher.Constraint("Vertical", segRadius)) + self.sketch.addGeometry( + Part.LineSegment( + self.App.Vector(oldLength, radius, 0), + self.App.Vector(oldLength + length, radius, 0), + ) + ) + self.sketch.addConstraint(Sketcher.Constraint("DistanceX", segLength, length)) + self.sketch.addConstraint(Sketcher.Constraint("Coincident", segLength, 1, segRadius, 2)) + self.sketch.addConstraint(Sketcher.Constraint("Horizontal", segLength)) # close the sketch - self.sketch.addGeometry(Part.LineSegment(self.App.Vector(oldLength+length,radius,0), self.App.Vector(oldLength+length,innerradius,0))) - self.sketch.addConstraint(Sketcher.Constraint('Coincident',0,2,segEnd,2)) - self.sketch.addConstraint(Sketcher.Constraint('Coincident',segEnd,1,segLength,2)) + self.sketch.addGeometry( + Part.LineSegment( + self.App.Vector(oldLength + length, radius, 0), + self.App.Vector(oldLength + length, innerradius, 0), + ) + ) + self.sketch.addConstraint(Sketcher.Constraint("Coincident", 0, 2, segEnd, 2)) + self.sketch.addConstraint(Sketcher.Constraint("Coincident", segEnd, 1, segLength, 2)) self.lastRadius = radius if oldLength == 0: # create feature - self.feature = self.Doc.addObject("PartDesign::Revolution","RevolutionShaft") + self.feature = self.Doc.addObject("PartDesign::Revolution", "RevolutionShaft") self.feature.Profile = self.sketch - self.feature.ReferenceAxis = (self.sketch,['H_Axis']) + self.feature.ReferenceAxis = (self.sketch, ["H_Axis"]) self.feature.Angle = 360.0 self.Doc.recompute() self.Gui.hide("SketchShaft") @@ -122,17 +155,17 @@ class ShaftFeature: def updateSegment(self, segment, oldLength, length, diameter, innerdiameter): constrRadius = 4 + segment * 6 constrLength = 7 + segment * 6 - constrInnerRadius = 1 # Currently we don't allow multiple different innner diameters + constrInnerRadius = 1 # Currently we don't allow multiple different innner diameters # update total length self.totalLength = self.totalLength - oldLength + length # Adjust length of centerline - self.sketch.setDatum(0,self.totalLength) + self.sketch.setDatum(0, self.totalLength) # Adjust segment length self.sketch.setDatum(constrLength, length) # Adjust diameter - self.sketch.setDatum(constrRadius, diameter/2) + self.sketch.setDatum(constrRadius, diameter / 2) # Adjust inner diameter - self.sketch.setDatum(constrInnerRadius, innerdiameter/2) + self.sketch.setDatum(constrInnerRadius, innerdiameter / 2) # Update feature self.Doc.recompute() self.Gui.SendMsgToActiveView("ViewFit") diff --git a/src/Mod/PartDesign/WizardShaft/WizardShaft.py b/src/Mod/PartDesign/WizardShaft/WizardShaft.py index e384b2ab3b..d682aef8e0 100644 --- a/src/Mod/PartDesign/WizardShaft/WizardShaft.py +++ b/src/Mod/PartDesign/WizardShaft/WizardShaft.py @@ -1,4 +1,4 @@ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * @@ -28,14 +28,16 @@ from .Shaft import Shaft translate = FreeCAD.Qt.translate + class TaskWizardShaft: "Shaft Wizard" + App = FreeCAD Gui = FreeCADGui def __init__(self, doc): mw = QtGui.QApplication.activeWindow() - #cw = mw.centralWidget() # This is a qmdiarea widget + # cw = mw.centralWidget() # This is a qmdiarea widget cw = mw.findChild(QtGui.QMdiArea) self.doc = doc @@ -53,24 +55,35 @@ class TaskWizardShaft: # Buttons for diagram display buttonLayout = QtGui.QGridLayout() all = translate("TaskWizardShaft", "All") - bnames = [[f"{all} [x]", f"{all} [y]", f"{all} [z]" ], - ["N [x]", "Q [y]", "Q [z]"], - ["Mt [x]", "Mb [z]", "Mb [y]"], - ["", "w [y]", "w [z]"], - ["sigma [x]", "sigma [y]", "sigma [z]"], - ["tau [x]", "sigmab [z]", "sigmab [y]"]] - slots = [[self.slotAllx, self.slotAlly, self.slotAllz], - [self.slotFx, self.slotQy, self.slotQz], - [self.slotMx, self.slotMz, self.slotMy], - [self.slotNone, self.slotWy, self.slotWz], - [self.slotSigmax, self.slotSigmay, self.slotSigmaz], - [self.slotTaut, self.slotSigmabz, self.slotSigmaby]] - self.buttons = [[None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None], [None, None, None]] + bnames = [ + [f"{all} [x]", f"{all} [y]", f"{all} [z]"], + ["N [x]", "Q [y]", "Q [z]"], + ["Mt [x]", "Mb [z]", "Mb [y]"], + ["", "w [y]", "w [z]"], + ["sigma [x]", "sigma [y]", "sigma [z]"], + ["tau [x]", "sigmab [z]", "sigmab [y]"], + ] + slots = [ + [self.slotAllx, self.slotAlly, self.slotAllz], + [self.slotFx, self.slotQy, self.slotQz], + [self.slotMx, self.slotMz, self.slotMy], + [self.slotNone, self.slotWy, self.slotWz], + [self.slotSigmax, self.slotSigmay, self.slotSigmaz], + [self.slotTaut, self.slotSigmabz, self.slotSigmaby], + ] + self.buttons = [ + [None, None, None], + [None, None, None], + [None, None, None], + [None, None, None], + [None, None, None], + [None, None, None], + ] for col in range(3): for row in range(6): button = QtGui.QPushButton(bnames[row][col]) - buttonLayout.addWidget(button, row, col) + buttonLayout.addWidget(button, row, col) self.buttons[row][col] = button button.clicked.connect(slots[row][col]) @@ -82,16 +95,18 @@ class TaskWizardShaft: # The top layout will contain the Shaft Wizard layout plus the elements of the FEM constraints dialog layout = QtGui.QVBoxLayout() - layout.setObjectName("ShaftWizard") # Do not change or translate: Required to detect whether Shaft Wizard is running in FemGui::ViewProviderFemConstraintXXX + layout.setObjectName( + "ShaftWizard" + ) # Do not change or translate: Required to detect whether Shaft Wizard is running in FemGui::ViewProviderFemConstraintXXX sublayout = QtGui.QVBoxLayout() - sublayout.setObjectName("ShaftWizardLayout") # Do not change or translate + sublayout.setObjectName("ShaftWizardLayout") # Do not change or translate sublayout.addWidget(self.table.widget) sublayout.addLayout(buttonLayout) layout.addLayout(sublayout) self.form.setLayout(layout) # Switch to feature window - mdi=FreeCADGui.getMainWindow().findChild(QtGui.QMdiArea) + mdi = FreeCADGui.getMainWindow().findChild(QtGui.QMdiArea) cw.setActiveSubWindow(featureWindow) def showDiagram(self, diagram): @@ -101,57 +116,75 @@ class TaskWizardShaft: msgBox = QtGui.QMessageBox() msgBox.setIcon(msgBox.Information) msgBox.setWindowTitle(translate("TaskWizardShaft", "Missing Module")) - msgBox.setText(translate("TaskWizardShaft", "The Plot add-on is not installed. Install it to enable this feature.")) + msgBox.setText( + translate( + "TaskWizardShaft", + "The Plot add-on is not installed. Install it to enable this feature.", + ) + ) msgBox.setDetailedText(traceback.format_exc()) msgBox.exec_() + def slotAllx(self): self.showDiagram("Allx") + def slotAlly(self): self.showDiagram("Ally") + def slotAllz(self): self.showDiagram("Allz") def slotFx(self): self.showDiagram("Nx") + def slotQy(self): self.showDiagram("Qy") + def slotQz(self): self.showDiagram("Qz") def slotMx(self): self.showDiagram("Mx") + def slotMz(self): self.showDiagram("Mz") + def slotMy(self): self.showDiagram("My") def slotNone(self): pass + def slotWy(self): self.showDiagram("wy") + def slotWz(self): self.showDiagram("wz") def slotSigmax(self): self.showDiagram("sigmax") + def slotSigmay(self): self.showDiagram("sigmay") + def slotSigmaz(self): self.showDiagram("sigmaz") def slotTaut(self): self.showDiagram("taut") + def slotSigmabz(self): self.showDiagram("sigmabz") + def slotSigmaby(self): self.showDiagram("sigmaby") - def updateButton(self, row, col, flag): + def updateButton(self, row, col, flag): self.buttons[row][col].setEnabled(flag) - def updateButtons(self, col, flag): + def updateButtons(self, col, flag): for row in range(len(self.buttons)): - self.updateButton(row, col, flag) + self.updateButton(row, col, flag) def getStandardButtons(self): return QtGui.QDialogButtonBox.Ok @@ -168,6 +201,7 @@ class TaskWizardShaft: def isAllowedAlterDocument(self): return False + # HACK: Workaround to allow a callback # Problem: From the FemConstraint ViewProvider, we need to tell the Shaft instance that the user finished editing the constraint # We can find the Shaft Wizard dialog object from C++, but there is no way to reach the Shaft instance @@ -176,6 +210,7 @@ class TaskWizardShaft: # in the python code WizardShaftDlg = None + class WizardShaftGui: def Activated(self): global WizardShaftDlg @@ -185,10 +220,10 @@ class WizardShaftGui: def GetResources(self): IconPath = FreeCAD.ConfigGet("AppHomePath") + "Mod/PartDesign/WizardShaft/WizardShaft.svg" MenuText = QtCore.QT_TRANSLATE_NOOP("PartDesign_WizardShaft", "Shaft Design Wizard") - ToolTip = QtCore.QT_TRANSLATE_NOOP("PartDesign_WizardShaft", "Starts the shaft design wizard") - return {'Pixmap': IconPath, - 'MenuText': MenuText, - 'ToolTip': ToolTip} + ToolTip = QtCore.QT_TRANSLATE_NOOP( + "PartDesign_WizardShaft", "Starts the shaft design wizard" + ) + return {"Pixmap": IconPath, "MenuText": MenuText, "ToolTip": ToolTip} def IsActive(self): return FreeCAD.ActiveDocument is not None @@ -197,6 +232,7 @@ class WizardShaftGui: global WizardShaftDlg WizardShaftDlg = None + class WizardShaftGuiCallback: def Activated(self): global WizardShaftDlg @@ -205,18 +241,21 @@ class WizardShaftGuiCallback: def isActive(self): global WizardShaftDlg - return (WizardShaftDlg is not None) + return WizardShaftDlg is not None def GetResources(self): IconPath = FreeCAD.ConfigGet("AppHomePath") + "Mod/PartDesign/WizardShaft/WizardShaft.svg" - MenuText = QtCore.QT_TRANSLATE_NOOP("PartDesign_WizardShaftCallBack", "Shaft design wizard...") - ToolTip = QtCore.QT_TRANSLATE_NOOP("PartDesign_WizardShaftCallBack", "Start the shaft design wizard") - return {'Pixmap': IconPath, - 'MenuText': MenuText, - 'ToolTip': ToolTip} + MenuText = QtCore.QT_TRANSLATE_NOOP( + "PartDesign_WizardShaftCallBack", "Shaft design wizard..." + ) + ToolTip = QtCore.QT_TRANSLATE_NOOP( + "PartDesign_WizardShaftCallBack", "Start the shaft design wizard" + ) + return {"Pixmap": IconPath, "MenuText": MenuText, "ToolTip": ToolTip} -FreeCADGui.addCommand('PartDesign_WizardShaft', WizardShaftGui()) -FreeCADGui.addCommand('PartDesign_WizardShaftCallBack', WizardShaftGuiCallback()) -#Note: Start wizard in Python Console with +FreeCADGui.addCommand("PartDesign_WizardShaft", WizardShaftGui()) +FreeCADGui.addCommand("PartDesign_WizardShaftCallBack", WizardShaftGuiCallback()) + +# Note: Start wizard in Python Console with # Gui.runCommand('PartDesign_WizardShaft') diff --git a/src/Mod/PartDesign/WizardShaft/WizardShaftTable.py b/src/Mod/PartDesign/WizardShaft/WizardShaftTable.py index 3c682b24dc..f782e39d6d 100644 --- a/src/Mod/PartDesign/WizardShaft/WizardShaftTable.py +++ b/src/Mod/PartDesign/WizardShaft/WizardShaftTable.py @@ -1,4 +1,4 @@ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * @@ -25,19 +25,21 @@ import FreeCAD translate = FreeCAD.Qt.translate + class WizardShaftTable: "The table widget that contains all the data of the shaft" + # Dictionary to access different parameters without using a numeric row index that might change # as the code evolves rowDict = { - "Length" : 0, - "Diameter" : 1, - "InnerDiameter" : 2, + "Length": 0, + "Diameter": 1, + "InnerDiameter": 2, "ConstraintType": 3, - "StartEdgeType" : 4, - "StartEdgeSize" : 5, - "EndEdgeType" : 6, - "EndEdgeSize" : 7 + "StartEdgeType": 4, + "StartEdgeSize": 5, + "EndEdgeType": 6, + "EndEdgeSize": 7, } rowDictReverse = {} headers = [ @@ -48,8 +50,8 @@ class WizardShaftTable: translate("WizardShaftTable", "Start edge type"), translate("WizardShaftTable", "Start edge size"), translate("WizardShaftTable", "End edge type"), - translate("WizardShaftTable", "End edge size") - ] + translate("WizardShaftTable", "End edge size"), + ] def __init__(self, w, s): for key, val in self.rowDict.items(): @@ -59,17 +61,20 @@ class WizardShaftTable: self.shaft = s # Create table widget self.widget = QtGui.QTableWidget(len(self.rowDict), 0) - self.widget.setObjectName("ShaftWizardTable") # Do not change or translate: Used in ViewProviderFemConstraintXXX + self.widget.setObjectName( + "ShaftWizardTable" + ) # Do not change or translate: Used in ViewProviderFemConstraintXXX self.widget.setWindowTitle(translate("WizardShaftTable", "Shaft Wizard")) - self.widget.resize(QtCore.QSize(300,200)) + self.widget.resize(QtCore.QSize(300, 200)) self.editedRow = None self.editedColumn = None # Label rows and columns self.widget.setVerticalHeaderLabels(self.headers) - self.widget.setHorizontalHeaderLabels([ - translate("WizardShaftTable", "Section 1"), translate("WizardShaftTable", "Section 2")]) - #self.widget.columnMoved.connect(column, oldIndex, newIndex) + self.widget.setHorizontalHeaderLabels( + [translate("WizardShaftTable", "Section 1"), translate("WizardShaftTable", "Section 2")] + ) + # self.widget.columnMoved.connect(column, oldIndex, newIndex) # Create context menu action = QtGui.QAction(translate("WizardShaftTable", "Add column"), self.widget) @@ -104,13 +109,13 @@ class WizardShaftTable: index = self.widget.columnCount() # Make an intelligent guess at the length/dia of the next segment if index > 0: - length = self.shaft.segments[index-1].length - diameter = self.shaft.segments[index-1].diameter + length = self.shaft.segments[index - 1].length + diameter = self.shaft.segments[index - 1].diameter if index > 2: diameter -= 5.0 else: diameter += 5.0 - innerdiameter = self.shaft.segments[index-1].innerdiameter + innerdiameter = self.shaft.segments[index - 1].innerdiameter else: length = 20.0 diameter = 10.0 @@ -118,12 +123,15 @@ class WizardShaftTable: self.shaft.addSegment(length, diameter, innerdiameter) self.widget.insertColumn(index) - self.widget.setHorizontalHeaderItem(index + 1, QtGui.QTableWidgetItem(translate("WizardShaftTable", "Section %s") % (index + 1))) + self.widget.setHorizontalHeaderItem( + index + 1, + QtGui.QTableWidgetItem(translate("WizardShaftTable", "Section %s") % (index + 1)), + ) # Length widget = QtGui.QDoubleSpinBox(self.widget) widget.setMinimum(0) - widget.setMaximum(1E9) + widget.setMaximum(1e9) self.widget.setCellWidget(self.rowDict["Length"], index, widget) widget.setValue(length) widget.valueChanged.connect(self.slotValueChanged) @@ -131,7 +139,7 @@ class WizardShaftTable: # Diameter widget = QtGui.QDoubleSpinBox(self.widget) widget.setMinimum(0) - widget.setMaximum(1E9) + widget.setMaximum(1e9) self.widget.setCellWidget(self.rowDict["Diameter"], index, widget) widget.setValue(diameter) widget.valueChanged.connect(self.slotValueChanged) @@ -139,7 +147,7 @@ class WizardShaftTable: # inner Diameter widget = QtGui.QDoubleSpinBox(self.widget) widget.setMinimum(0) - widget.setMaximum(1E9) + widget.setMaximum(1e9) self.widget.setCellWidget(self.rowDict["InnerDiameter"], index, widget) widget.setValue(innerdiameter) widget.valueChanged.connect(self.slotValueChanged) @@ -158,39 +166,48 @@ class WizardShaftTable: widget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) self.widget.setCellWidget(self.rowDict["ConstraintType"], index, widget) widget.setCurrentIndex(0) - self.widget.connect(widget, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.slotConstraintType) + self.widget.connect( + widget, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.slotConstraintType + ) # Start edge type widget = QtGui.QComboBox(self.widget) - widget.insertItem(0, translate("WizardShaftTable", "None"), "None",) + widget.insertItem( + 0, + translate("WizardShaftTable", "None"), + "None", + ) widget.insertItem(1, translate("WizardShaftTable", "Chamfer"), "Chamfer") widget.insertItem(2, translate("WizardShaftTable", "Fillet"), "Fillet") self.widget.setCellWidget(self.rowDict["StartEdgeType"], index, widget) widget.setCurrentIndex(0) widget.setEnabled(False) - #self.widget.connect(widget, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.slotLoadType) + # self.widget.connect(widget, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.slotLoadType) # Start edge size widget = QtGui.QDoubleSpinBox(self.widget) widget.setMinimum(0) - widget.setMaximum(1E9) - self.widget.setCellWidget(self.rowDict["StartEdgeSize"],index, widget) + widget.setMaximum(1e9) + self.widget.setCellWidget(self.rowDict["StartEdgeSize"], index, widget) widget.setValue(1) widget.valueChanged.connect(self.slotValueChanged) widget.editingFinished.connect(self.slotEditingFinished) widget.setEnabled(False) # End edge type widget = QtGui.QComboBox(self.widget) - widget.insertItem(0, "None",) + widget.insertItem( + 0, + "None", + ) widget.insertItem(1, "Chamfer") widget.insertItem(2, "Fillet") - self.widget.setCellWidget(self.rowDict["EndEdgeType"],index, widget) + self.widget.setCellWidget(self.rowDict["EndEdgeType"], index, widget) widget.setCurrentIndex(0) widget.setEnabled(False) - #self.widget.connect(widget, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.slotLoadType) + # self.widget.connect(widget, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.slotLoadType) # End edge size widget = QtGui.QDoubleSpinBox(self.widget) widget.setMinimum(0) - widget.setMaximum(1E9) - self.widget.setCellWidget(self.rowDict["EndEdgeSize"],index, widget) + widget.setMaximum(1e9) + self.widget.setCellWidget(self.rowDict["EndEdgeSize"], index, widget) widget.setValue(1) widget.valueChanged.connect(self.slotValueChanged) widget.editingFinished.connect(self.slotEditingFinished) @@ -207,13 +224,21 @@ class WizardShaftTable: if rowName is None: return if rowName == "Length": - self.shaft.updateSegment(self.editedColumn, length = self.getDoubleValue(rowName, self.editedColumn)) + self.shaft.updateSegment( + self.editedColumn, length=self.getDoubleValue(rowName, self.editedColumn) + ) elif rowName == "Diameter": - self.shaft.updateSegment(self.editedColumn, diameter = self.getDoubleValue(rowName, self.editedColumn)) + self.shaft.updateSegment( + self.editedColumn, diameter=self.getDoubleValue(rowName, self.editedColumn) + ) elif rowName == "InnerDiameter": - self.shaft.updateSegment(self.editedColumn, innerdiameter = self.getDoubleValue(rowName, self.editedColumn)) + self.shaft.updateSegment( + self.editedColumn, innerdiameter=self.getDoubleValue(rowName, self.editedColumn) + ) elif rowName == "ConstraintType": - self.shaft.updateConstraint(self.editedColumn, self.getListValue(rowName, self.editedColumn)) + self.shaft.updateConstraint( + self.editedColumn, self.getListValue(rowName, self.editedColumn) + ) elif rowName == "StartEdgeType": pass elif rowName == "StartEdgeSize": @@ -224,7 +249,9 @@ class WizardShaftTable: pass def slotEditConstraint(self): - (self.editedRow, self.editedColumn) = self.getFocusedCell() # Because finishEditConstraint() will trigger slotEditingFinished() which requires this information + (self.editedRow, self.editedColumn) = ( + self.getFocusedCell() + ) # Because finishEditConstraint() will trigger slotEditingFinished() which requires this information self.shaft.editConstraint(self.editedColumn) def finishEditConstraint(self): @@ -232,26 +259,26 @@ class WizardShaftTable: def setLength(self, column, l): self.setDoubleValue("Length", column, l) - self.shaft.updateSegment(column, length = l) + self.shaft.updateSegment(column, length=l) def getLength(self, column): return self.getDoubleValue("Length", column) def setDiameter(self, column, d): self.setDoubleValue("Diameter", column, d) - self.shaft.updateSegment(column, diameter = d) + self.shaft.updateSegment(column, diameter=d) def getDiameter(self, column): return self.getDoubleValue("Diameter", column) def setInnerDiameter(self, column, d): self.setDoubleValue("InnerDiameter", column, d) - self.shaft.updateSegment(column, innerdiameter = d) + self.shaft.updateSegment(column, innerdiameter=d) def getInnerDiameter(self, column): return self.getDoubleValue("InnerDiameter", column) - @QtCore.Slot('QString') + @QtCore.Slot("QString") def slotConstraintType(self, text): self.shaft.updateConstraint(self.getFocusedColumn(), text) @@ -319,7 +346,7 @@ class WizardShaftTable: # If the widget has user data attached, assume that is the "value" we are seeking return widget.data(QtCore.Qt.UserRole) else: - return widget.currentText() #[0].upper() + return widget.currentText() # [0].upper() else: return None diff --git a/src/Mod/PartDesign/WizardShaft/__init__.py b/src/Mod/PartDesign/WizardShaft/__init__.py index d32e9e3c29..8f6c570f0d 100644 --- a/src/Mod/PartDesign/WizardShaft/__init__.py +++ b/src/Mod/PartDesign/WizardShaft/__init__.py @@ -2,7 +2,7 @@ Shaft Wizard """ -#/****************************************************************************** +# /****************************************************************************** # * Copyright (c) 2012 Jan Rheinländer * # * * # * This file is part of the FreeCAD CAx development system. * diff --git a/src/Mod/PartDesign/__init__.py b/src/Mod/PartDesign/__init__.py index 29a70ae509..07964eba79 100644 --- a/src/Mod/PartDesign/__init__.py +++ b/src/Mod/PartDesign/__init__.py @@ -1,3 +1,3 @@ import _PartDesign -makeFilletArc = _PartDesign.makeFilletArc +makeFilletArc = _PartDesign.makeFilletArc diff --git a/src/Mod/PartDesign/fcgear/fcgear.py b/src/Mod/PartDesign/fcgear/fcgear.py index d5ade2e154..ec99ca8d51 100644 --- a/src/Mod/PartDesign/fcgear/fcgear.py +++ b/src/Mod/PartDesign/fcgear/fcgear.py @@ -20,6 +20,7 @@ from math import acos import FreeCAD, Part from FreeCAD import Base from . import involute + rotate = involute.rotate @@ -37,6 +38,7 @@ def makeGear(m, Z, angle, split=True): class FCWireBuilder(object): """A helper class to prepare a Part.Wire object""" + def __init__(self): self.pos = None self.theta = 0.0 @@ -54,7 +56,7 @@ class FCWireBuilder(object): self.pos = end def arc(self, p, r, sweep): - """"Add an arc from self.pos to p which radius is r + """ "Add an arc from self.pos to p which radius is r sweep (0 or 1) determine the orientation of the arc """ p = rotate(p, self.theta) @@ -77,6 +79,7 @@ class FCWireBuilder(object): def close(self): pass + def midpoints(p1, p2, r): """A very ugly function that returns the midpoint of a p1 and p2 on the circle which radius is r and which pass through p1 and @@ -84,24 +87,24 @@ def midpoints(p1, p2, r): Return the 2 possible solutions """ - vx, vy = p2[0]-p1[0], p2[1]-p1[1] - b = (vx**2 + vy**2)**.5 - v = (vx/b, vy/b) - cosA = b**2 / (2*b*r) + vx, vy = p2[0] - p1[0], p2[1] - p1[1] + b = (vx**2 + vy**2) ** 0.5 + v = (vx / b, vy / b) + cosA = b**2 / (2 * b * r) A = acos(cosA) vx, vy = rotate(v, A) - c1 = (p1[0]+r*vx, p1[1]+r*vy) - m1x, m1y = ((p1[0]+p2[0])/2 - c1[0], (p1[1]+p2[1])/2 - c1[1]) - dm1 = (m1x**2+m1y**2)**.5 - m1x, m1y = (c1[0] + r*m1x/dm1, c1[1] + r*m1y/dm1) + c1 = (p1[0] + r * vx, p1[1] + r * vy) + m1x, m1y = ((p1[0] + p2[0]) / 2 - c1[0], (p1[1] + p2[1]) / 2 - c1[1]) + dm1 = (m1x**2 + m1y**2) ** 0.5 + m1x, m1y = (c1[0] + r * m1x / dm1, c1[1] + r * m1y / dm1) m1 = (m1x, m1y) vx, vy = rotate(v, -A) - c2 = (p1[0]+r*vx, p1[1]+r*vy) - m2x, m2y = ((p1[0]+p2[0])/2 - c2[0], (p1[1]+p2[1])/2 - c2[1]) - dm2 = (m2x**2+m2y**2)**.5 - m2x, m2y = (c2[0] + r*m2x/dm2, c2[1] + r*m2y/dm2) + c2 = (p1[0] + r * vx, p1[1] + r * vy) + m2x, m2y = ((p1[0] + p2[0]) / 2 - c2[0], (p1[1] + p2[1]) / 2 - c2[1]) + dm2 = (m2x**2 + m2y**2) ** 0.5 + m2x, m2y = (c2[0] + r * m2x / dm2, c2[1] + r * m2y / dm2) m2 = (m2x, m2y) return m1, m2 diff --git a/src/Mod/PartDesign/fcgear/involute.py b/src/Mod/PartDesign/fcgear/involute.py index 924e48eb73..6717c8b502 100644 --- a/src/Mod/PartDesign/fcgear/involute.py +++ b/src/Mod/PartDesign/fcgear/involute.py @@ -27,11 +27,9 @@ from math import cos, sin, tan, pi, acos, asin, atan, sqrt, radians from math import comb as binom -def CreateExternalGear(w, m, Z, phi, - split=True, - addCoeff=1.0, dedCoeff=1.25, - filletCoeff=0.375, - shiftCoeff=0.0): +def CreateExternalGear( + w, m, Z, phi, split=True, addCoeff=1.0, dedCoeff=1.25, filletCoeff=0.375, shiftCoeff=0.0 +): """ Create an external gear @@ -59,14 +57,13 @@ def CreateExternalGear(w, m, Z, phi, outer_height_coefficient=addCoeff, inner_height_coefficient=dedCoeff, inner_fillet_coefficient=filletCoeff, - profile_shift_coefficient=shiftCoeff) + profile_shift_coefficient=shiftCoeff, + ) -def CreateInternalGear(w, m, Z, phi, - split=True, - addCoeff=0.6, dedCoeff=1.25, - filletCoeff=0.375, - shiftCoeff=0.0): +def CreateInternalGear( + w, m, Z, phi, split=True, addCoeff=0.6, dedCoeff=1.25, filletCoeff=0.375, shiftCoeff=0.0 +): """ Create an internal gear @@ -97,25 +94,27 @@ def CreateInternalGear(w, m, Z, phi, number_of_teeth=Z, pressure_angle=radians(phi), split_involute=split, - rotation=pi/Z, # rotate by half a tooth to align the "inner" tooth with the X-axis + rotation=pi / Z, # rotate by half a tooth to align the "inner" tooth with the X-axis outer_height_coefficient=dedCoeff, inner_height_coefficient=addCoeff, outer_fillet_coefficient=filletCoeff, - profile_shift_coefficient=shiftCoeff) + profile_shift_coefficient=shiftCoeff, + ) def _create_involute_profile( - wire_builder, - module, - number_of_teeth, - pressure_angle=radians(20.0), - split_involute=True, - rotation=radians(0), - outer_height_coefficient=1.0, - inner_height_coefficient=1.0, - outer_fillet_coefficient=0.0, - inner_fillet_coefficient=0.0, - profile_shift_coefficient=0.0): + wire_builder, + module, + number_of_teeth, + pressure_angle=radians(20.0), + split_involute=True, + rotation=radians(0), + outer_height_coefficient=1.0, + inner_height_coefficient=1.0, + outer_fillet_coefficient=0.0, + inner_fillet_coefficient=0.0, + profile_shift_coefficient=0.0, +): """ Create an involute gear profile in the given wire builder @@ -133,28 +132,28 @@ def _create_involute_profile( """ profile_shift = profile_shift_coefficient * module - outer_height = outer_height_coefficient * module + profile_shift # ext: addendum, int: dedednum - inner_height = inner_height_coefficient * module - profile_shift # ext: dedendum, int: addednum + outer_height = outer_height_coefficient * module + profile_shift # ext: addendum, int: dedednum + inner_height = inner_height_coefficient * module - profile_shift # ext: dedendum, int: addednum # ****** calculate radii # All distances from the center of the profile start with "R". # As those are mostly used in mathematical formulae, we use "symbols" rather than "speaking # names" to keep them short. Otherwise the math becomes unreadable. - Rref = number_of_teeth * module / 2 # reference circle radius - Rb = Rref * cos(pressure_angle) # base circle radius - Ro = Rref + outer_height # radius of outer circle (tip for external, root for internal gears) - Ri = Rref - inner_height # radius of inner circle (root for external, tip for internal gears) + Rref = number_of_teeth * module / 2 # reference circle radius + Rb = Rref * cos(pressure_angle) # base circle radius + Ro = Rref + outer_height # radius of outer circle (tip for external, root for internal gears) + Ri = Rref - inner_height # radius of inner circle (root for external, tip for internal gears) - fi = inner_fillet_coefficient * module # fillet radius at inner circle (ext: root fillet) - Rci = Ri + fi # radius at which the center of the inner fillet circle sits - Rfi = Rci # radius at which the inner fillet ends (for now assuming some non-involute flank) + fi = inner_fillet_coefficient * module # fillet radius at inner circle (ext: root fillet) + Rci = Ri + fi # radius at which the center of the inner fillet circle sits + Rfi = Rci # radius at which the inner fillet ends (for now assuming some non-involute flank) - fo = outer_fillet_coefficient * module # fillet radius at outer circle (int: root fillet) - Rco = Ro - fo # radius at which the center of the outer fillet circle sits - Rfo = Ro # radius at which the outer fillet ends (for now assuming no outer fillet) + fo = outer_fillet_coefficient * module # fillet radius at outer circle (int: root fillet) + Rco = Ro - fo # radius at which the center of the outer fillet circle sits + Rfo = Ro # radius at which the outer fillet ends (for now assuming no outer fillet) - has_non_involute_flank = Rfi < Rb # above the base circle we have the involute, - # below we have a straight line towards the center. + has_non_involute_flank = Rfi < Rb # above the base circle we have the involute, + # below we have a straight line towards the center. has_inner_fillet = fi > 0 has_outer_fillet = fo > 0 @@ -190,10 +189,11 @@ def _create_involute_profile( # of teeth, Ri...Rci as in this case the base circle is below the inner circle. # The graph of q is strictly monotnonous and very steep, no surprises to expect. # To simplify the above equations and to find the derivative, SageMath was used. - q = lambda r: (sqrt(r**2 - Rb**2) / Rb - - asin((-r**2 + fi**2 + Rci**2) / (2 * fi * Rci))) - q_prime = lambda r: (r / (sqrt(-Rb**2 + r**2) * Rb) - + r / (fi * Rci * sqrt(1 - 1/4 * (r**2 - fi**2 - Rci**2)**2 / (fi**2 * Rci**2)))) + q = lambda r: (sqrt(r**2 - Rb**2) / Rb - asin((-(r**2) + fi**2 + Rci**2) / (2 * fi * Rci))) + q_prime = lambda r: ( + r / (sqrt(-(Rb**2) + r**2) * Rb) + + r / (fi * Rci * sqrt(1 - 1 / 4 * (r**2 - fi**2 - Rci**2) ** 2 / (fi**2 * Rci**2))) + ) Rfi = findRootNewton(q, q_prime, x_min=max(Rb, Ri), x_max=Rci) if has_outer_fillet: @@ -220,46 +220,48 @@ def _create_involute_profile( # X-axis, we assume the (real) polar angle of its center position being fo below the # involute's end at Ro. phi_corr = genInvolutePolar(Rb, Ro) + atan(fo / Ro) - q = lambda r: (sqrt(r**2 - Rb**2) / Rb - - asin((r**2 - fo**2 - Rco**2) / (2 * fo * Rco)) - - phi_corr) - q_prime = lambda r: (r / (sqrt(-Rb**2 + r**2) * Rb) - - r / (fo * Rco * sqrt(1 - 1/4 * (r**2 - fo**2 - Rco**2)**2 / (fo**2 * Rco**2)))) + q = lambda r: ( + sqrt(r**2 - Rb**2) / Rb - asin((r**2 - fo**2 - Rco**2) / (2 * fo * Rco)) - phi_corr + ) + q_prime = lambda r: ( + r / (sqrt(-(Rb**2) + r**2) * Rb) + - r / (fo * Rco * sqrt(1 - 1 / 4 * (r**2 - fo**2 - Rco**2) ** 2 / (fo**2 * Rco**2))) + ) Rfo = findRootNewton(q, q_prime, x_min=max(Rb, Rco), x_max=Ro) # ****** calculate angles (all in radians) - angular_pitch = 2 * pi / number_of_teeth # angle subtended by complete tooth/space pair - base_to_ref = genInvolutePolar(Rb, Rref) # angle between base and reference circle - ref_to_stop = genInvolutePolar(Rb, Rfo) - base_to_ref # angle between ref and involute end - if has_non_involute_flank: # involute starts at base circle + angular_pitch = 2 * pi / number_of_teeth # angle subtended by complete tooth/space pair + base_to_ref = genInvolutePolar(Rb, Rref) # angle between base and reference circle + ref_to_stop = genInvolutePolar(Rb, Rfo) - base_to_ref # angle between ref and involute end + if has_non_involute_flank: # involute starts at base circle start_to_ref = base_to_ref - else: # involute starts at top of inner fillet, i.e. somewhat above the base circle + else: # involute starts at top of inner fillet, i.e. somewhat above the base circle start_to_ref = base_to_ref - genInvolutePolar(Rb, Rfi) - inner_fillet_width = sqrt(fi**2 - (Rci - Rfi)**2) + inner_fillet_width = sqrt(fi**2 - (Rci - Rfi) ** 2) inner_fillet_angle = atan(inner_fillet_width / Rfi) - outer_fillet_width = sqrt(fo**2 - (Rfo - Rco)**2) + outer_fillet_width = sqrt(fo**2 - (Rfo - Rco) ** 2) outer_fillet_angle = atan(outer_fillet_width / Rfo) # ****** generate Higuchi involute approximation - fe = 1 # fraction of involute length at end of approx - fs = 0.01 # fraction of length offset from base to avoid singularity - if (not has_non_involute_flank): + fe = 1 # fraction of involute length at end of approx + fs = 0.01 # fraction of length offset from base to avoid singularity + if not has_non_involute_flank: fs = (Rfi**2 - Rb**2) / (Rfo**2 - Rb**2) # offset start to top of fillet if split_involute: # approximate in 2 sections, split 25% along the involute - fm = fs + (fe - fs) / 4 # fraction of length at junction (25% along involute) + fm = fs + (fe - fs) / 4 # fraction of length at junction (25% along involute) part1 = BezCoeffs(Rb, Rfo, 3, fs, fm) part2 = BezCoeffs(Rb, Rfo, 3, fm, fe) - inv = part1 + part2[1:] # join the 2 sets of coeffs (skip duplicate mid point) + inv = part1 + part2[1:] # join the 2 sets of coeffs (skip duplicate mid point) else: inv = BezCoeffs(Rb, Rfo, 4, fs, fe) # ****** calculate angular tooth thickness at reference circle enlargement_by_shift = profile_shift * tan(pressure_angle) / Rref tooth_thickness_half_angle = angular_pitch / 4 + enlargement_by_shift - psi = tooth_thickness_half_angle # for the formulae below, a symbol is more readable + psi = tooth_thickness_half_angle # for the formulae below, a symbol is more readable # rotate all points to make the tooth symmetric to the X axis inv = [rotate(pt, -base_to_ref - psi) for pt in inv] @@ -270,8 +272,8 @@ def _create_involute_profile( # ****** calculate section junction points. # Those are the points where the named element ends (start is the end of the previous element). # Suffix _back is back of this tooth, suffix _next is front of next tooth. - inner_fillet = toCartesian(Rfi, -psi - start_to_ref) # top of fillet - inner_fillet_back = mirror(inner_fillet) # flip to make same point on back of tooth + inner_fillet = toCartesian(Rfi, -psi - start_to_ref) # top of fillet + inner_fillet_back = mirror(inner_fillet) # flip to make same point on back of tooth inner_circle_back = toCartesian(Ri, psi + start_to_ref + inner_fillet_angle) inner_circle_next = toCartesian(Ri, angular_pitch - psi - start_to_ref - inner_fillet_angle) inner_fillet_next = rotate(inner_fillet, angular_pitch) # top of fillet, front of next tooth @@ -296,8 +298,8 @@ def _create_involute_profile( for theta in thetas: wire_builder.theta = theta - if (has_non_involute_flank): - wire_builder.line(inv[0]) # line from inner fillet up to base circle + if has_non_involute_flank: + wire_builder.line(inv[0]) # line from inner fillet up to base circle # front involute if split_involute: @@ -307,13 +309,13 @@ def _create_involute_profile( wire_builder.curve(*inv[1:]) # is there a section of outer circle between outer fillets? - if (outer_circle[1] > outer_fillet[1]): + if outer_circle[1] > outer_fillet[1]: if has_outer_fillet: - wire_builder.arc(outer_fillet, fo, 1) # outer fillet - wire_builder.arc(outer_circle, Ro, 1) # arc across the outer circle + wire_builder.arc(outer_fillet, fo, 1) # outer fillet + wire_builder.arc(outer_circle, Ro, 1) # arc across the outer circle if has_outer_fillet: - wire_builder.arc(invR[-1], fo, 1) # outer fillet on back side + wire_builder.arc(invR[-1], fo, 1) # outer fillet on back side # back involute if split_involute: @@ -322,14 +324,14 @@ def _create_involute_profile( else: wire_builder.curve(*invR[-2::-1]) - if (has_non_involute_flank): - wire_builder.line(inner_fillet_back) # line down to top of inner fillet + if has_non_involute_flank: + wire_builder.line(inner_fillet_back) # line down to top of inner fillet # is there a section of inner circle between inner fillets? - if (inner_circle_next[1] > inner_circle_back[1]): + if inner_circle_next[1] > inner_circle_back[1]: if has_inner_fillet: - wire_builder.arc(inner_circle_back, fi, 0) # inner fillet on back side - wire_builder.arc(inner_circle_next, Ri, 1) # arc across the inner circle + wire_builder.arc(inner_circle_back, fi, 0) # inner fillet on back side + wire_builder.arc(inner_circle_next, Ri, 1) # arc across the inner circle if has_inner_fillet: wire_builder.arc(inner_fillet_next, fi, 0) @@ -341,15 +343,14 @@ def genInvolutePolar(Rb, R): """return the involute angle as function of radius R. Rb = base circle radius """ - return (sqrt(R*R - Rb*Rb) / Rb) - acos(Rb / R) + return (sqrt(R * R - Rb * Rb) / Rb) - acos(Rb / R) def rotate(pt, rads): """rotate pt by rads radians about origin""" sinA = sin(rads) cosA = cos(rads) - return (pt[0] * cosA - pt[1] * sinA, - pt[0] * sinA + pt[1] * cosA) + return (pt[0] * cosA - pt[1] * sinA, pt[0] * sinA + pt[1] * cosA) def mirror(pt): @@ -379,23 +380,23 @@ def findRootNewton(f, f_prime, x_min, x_max): f_x = f(x) if abs(f_x) < PRECISION_INTERSECTION: return x - x = x - f_x/f_prime(x) + x = x - f_x / f_prime(x) raise RuntimeError(f"No convergence after {i+1} iterations.") def chebyExpnCoeffs(j, func): - N = 50 # a suitably large number N>>p + N = 50 # a suitably large number N>>p c = 0 for k in range(1, N + 1): c += func(cos(pi * (k - 0.5) / N)) * cos(pi * j * (k - 0.5) / N) - return 2 *c / N + return 2 * c / N def chebyPolyCoeffs(p, func): - coeffs = [0]*(p+1) + coeffs = [0] * (p + 1) fnCoeff = [] - T = [coeffs[:] for i in range(p+1)] + T = [coeffs[:] for i in range(p + 1)] T[0][0] = 1 T[1][1] = 1 # now generate the Chebyshev polynomial coefficient using @@ -428,8 +429,8 @@ def chebyPolyCoeffs(p, func): def bezCoeff(i, p, polyCoeffs): - '''generate the polynomial coeffs in one go''' - return sum(binom(i, j) * polyCoeffs[j] / binom(p, j) for j in range(i+1)) + """generate the polynomial coeffs in one go""" + return sum(binom(i, j) * polyCoeffs[j] / binom(p, j) for j in range(i + 1)) def BezCoeffs(baseRadius, limitRadius, order, fstart, fstop): @@ -445,10 +446,10 @@ def BezCoeffs(baseRadius, limitRadius, order, fstart, fstop): """ Rb = baseRadius Ra = limitRadius - ta = sqrt(Ra * Ra - Rb * Rb) / Rb # involute angle at the limit radius - te = sqrt(fstop) * ta # involute angle, theta, at end of approx - ts = sqrt(fstart) * ta # involute angle, theta, at start of approx - p = order # order of Bezier approximation + ta = sqrt(Ra * Ra - Rb * Rb) / Rb # involute angle at the limit radius + te = sqrt(fstop) * ta # involute angle, theta, at end of approx + ts = sqrt(fstart) * ta # involute angle, theta, at start of approx + p = order # order of Bezier approximation def involuteXbez(t): "Equation of involute using the Bezier parameter t as variable" @@ -475,4 +476,3 @@ def BezCoeffs(baseRadius, limitRadius, order, fstart, fstop): by = bezCoeff(i, p, polyCoeffsY) bzCoeffs.append((bx, by)) return bzCoeffs - diff --git a/src/Mod/PartDesign/fcgear/svggear.py b/src/Mod/PartDesign/fcgear/svggear.py index cb1cee926e..ff7721cef6 100644 --- a/src/Mod/PartDesign/fcgear/svggear.py +++ b/src/Mod/PartDesign/fcgear/svggear.py @@ -18,6 +18,7 @@ import itertools from involute import CreateExternalGear, CreateInternalGear, rotate + class SVGWireBuilder(object): def __init__(self): self.theta = 0.0 @@ -26,17 +27,17 @@ class SVGWireBuilder(object): def move(self, p): p = rotate(p, self.theta) - self.svg.append('M %s,%s' % (p[0], p[1])) + self.svg.append("M %s,%s" % (p[0], p[1])) self.pos = p def line(self, p): p = rotate(p, self.theta) - self.svg.append('L %s,%s' % (p[0], p[1])) + self.svg.append("L %s,%s" % (p[0], p[1])) self.pos = p def arc(self, p, r, sweep): p = rotate(p, self.theta) - self.svg.append('A %s,%s 0,0,%s %s,%s' % (r, r, str(sweep), p[0], p[1])) + self.svg.append("A %s,%s 0,0,%s %s,%s" % (r, r, str(sweep), p[0], p[1])) self.pos = p def curve(self, *points): @@ -46,48 +47,90 @@ class SVGWireBuilder(object): """ assert len(points) == 3 points = [rotate(p, self.theta) for p in points] - self.svg.append('C %s,%s %s,%s %s,%s' % tuple(itertools.chain(*points))) + self.svg.append("C %s,%s %s,%s %s,%s" % tuple(itertools.chain(*points))) self.pos = points[-1] def close(self): - self.svg.append('Z') + self.svg.append("Z") -if __name__ == '__main__': +if __name__ == "__main__": from optparse import OptionParser + p = OptionParser( usage="usage: %prog [options] [[MODULE] NUMER_OF_TEETH]", - description=("Generates the outline of a metric, involute gear. " + description=( + "Generates the outline of a metric, involute gear. " "Prints out an SVG path. " "This is mainly a debugging tool to quickly inspect the gear visually. " "For this, online tools like https://yqnn.github.io/svg-path-editor/ are handy. " "Most of the time it's enough to just use the first 20 lines or so, e.g.:\n\t" - "%prog -z50 | head -n20 | pbcopy")) - p.add_option('-z', '--numer-of-teeth', + "%prog -z50 | head -n20 | pbcopy" + ), + ) + p.add_option( + "-z", + "--numer-of-teeth", help="The number of teeth for the gear.", - metavar='NUMER_OF_TEETH', type='int') - p.add_option('-m', '--module', + metavar="NUMER_OF_TEETH", + type="int", + ) + p.add_option( + "-m", + "--module", help="The metric module, in svg user unit, i.e. unit-less. [default: %default]", - metavar='MODULE', type='float', default=1) - p.add_option('-p', '--pressure-angle', + metavar="MODULE", + type="float", + default=1, + ) + p.add_option( + "-p", + "--pressure-angle", help="The pressure angle, in degree. [default: %default]", - metavar='PRESSURE_ANGLE', type='float', default=20) - p.add_option('-i', '--internal', - help=("Generates an internal gear, i.e. the addednum points towards the center " - "and the root fillet is at the outside. [default: %default]"), - action='store_true', default=False) - p.add_option('-a', '--addendum', - help=("The tooth height above the pitch line, normalized by the MODULE. " - "[default: %default]"), - metavar='ADDENDUM_COEFFICIENT', type='float', default=1) - p.add_option('-d', '--dedendum', - help=("The tooth height from the root to the pitch line, normalized by the MODULE. " - "[default: %default]"), - metavar='DEDENDUM_COEFFICIENT', type='float', default=1.25) - p.add_option('-f', '--fillet-radius', - help=("The radius of the root fillet, normalized by the MODULE. " - "[default: %default]"), - metavar='FILLET_RADIUS_COEFFICIENT', type='float', default=0.38) + metavar="PRESSURE_ANGLE", + type="float", + default=20, + ) + p.add_option( + "-i", + "--internal", + help=( + "Generates an internal gear, i.e. the addednum points towards the center " + "and the root fillet is at the outside. [default: %default]" + ), + action="store_true", + default=False, + ) + p.add_option( + "-a", + "--addendum", + help=( + "The tooth height above the pitch line, normalized by the MODULE. " + "[default: %default]" + ), + metavar="ADDENDUM_COEFFICIENT", + type="float", + default=1, + ) + p.add_option( + "-d", + "--dedendum", + help=( + "The tooth height from the root to the pitch line, normalized by the MODULE. " + "[default: %default]" + ), + metavar="DEDENDUM_COEFFICIENT", + type="float", + default=1.25, + ) + p.add_option( + "-f", + "--fillet-radius", + help=("The radius of the root fillet, normalized by the MODULE. " "[default: %default]"), + metavar="FILLET_RADIUS_COEFFICIENT", + type="float", + default=0.38, + ) opts, args = p.parse_args() errors = [] @@ -106,10 +149,15 @@ if __name__ == '__main__': w = SVGWireBuilder() generator_func = CreateInternalGear if opts.internal else CreateExternalGear - generator_func(w, opts.module, opts.numer_of_teeth, opts.pressure_angle, - addCoeff=opts.addendum, dedCoeff=opts.dedendum, - filletCoeff=opts.fillet_radius) + generator_func( + w, + opts.module, + opts.numer_of_teeth, + opts.pressure_angle, + addCoeff=opts.addendum, + dedCoeff=opts.dedendum, + filletCoeff=opts.fillet_radius, + ) for l in w.svg: print(l) - diff --git a/src/Mod/PartDesign/fcsprocket/__init__.py b/src/Mod/PartDesign/fcsprocket/__init__.py index 8b13789179..e69de29bb2 100644 --- a/src/Mod/PartDesign/fcsprocket/__init__.py +++ b/src/Mod/PartDesign/fcsprocket/__init__.py @@ -1 +0,0 @@ - diff --git a/src/Mod/PartDesign/fcsprocket/fcsprocket.py b/src/Mod/PartDesign/fcsprocket/fcsprocket.py index 344ea1e94c..5d61d18b72 100644 --- a/src/Mod/PartDesign/fcsprocket/fcsprocket.py +++ b/src/Mod/PartDesign/fcsprocket/fcsprocket.py @@ -20,8 +20,10 @@ from math import acos import FreeCAD, Part from FreeCAD import Base from . import sprocket + rotate = sprocket.rotate + def makeSprocket(P, N, Dr): if FreeCAD.ActiveDocument is None: FreeCAD.newDocument("Sprocket") @@ -33,8 +35,10 @@ def makeSprocket(P, N, Dr): sprocketf.Shape = sprocketw return sprocketf + class FCWireBuilder(object): """A helper class to prepare a Part.Wire object""" + def __init__(self): self.pos = None self.theta = 0.0 @@ -52,7 +56,7 @@ class FCWireBuilder(object): self.pos = end def arc(self, p, r, sweep): - """"Add an arc from self.pos to p which radius is r + """ "Add an arc from self.pos to p which radius is r sweep (0 or 1) determine the orientation of the arc """ p = rotate(p, self.theta) @@ -75,6 +79,7 @@ class FCWireBuilder(object): def close(self): pass + def midpoints(p1, p2, r): """A very ugly function that returns the midpoint of a p1 and p2 on the circle which radius is r and which pass through p1 and @@ -82,24 +87,24 @@ def midpoints(p1, p2, r): Return the 2 possible solutions """ - vx, vy = p2[0]-p1[0], p2[1]-p1[1] - b = (vx**2 + vy**2)**.5 - v = (vx/b, vy/b) - cosA = b**2 / (2*b*r) + vx, vy = p2[0] - p1[0], p2[1] - p1[1] + b = (vx**2 + vy**2) ** 0.5 + v = (vx / b, vy / b) + cosA = b**2 / (2 * b * r) A = acos(cosA) vx, vy = rotate(v, A) - c1 = (p1[0]+r*vx, p1[1]+r*vy) - m1x, m1y = ((p1[0]+p2[0])/2 - c1[0], (p1[1]+p2[1])/2 - c1[1]) - dm1 = (m1x**2+m1y**2)**.5 - m1x, m1y = (c1[0] + r*m1x/dm1, c1[1] + r*m1y/dm1) + c1 = (p1[0] + r * vx, p1[1] + r * vy) + m1x, m1y = ((p1[0] + p2[0]) / 2 - c1[0], (p1[1] + p2[1]) / 2 - c1[1]) + dm1 = (m1x**2 + m1y**2) ** 0.5 + m1x, m1y = (c1[0] + r * m1x / dm1, c1[1] + r * m1y / dm1) m1 = (m1x, m1y) vx, vy = rotate(v, -A) - c2 = (p1[0]+r*vx, p1[1]+r*vy) - m2x, m2y = ((p1[0]+p2[0])/2 - c2[0], (p1[1]+p2[1])/2 - c2[1]) - dm2 = (m2x**2+m2y**2)**.5 - m2x, m2y = (c2[0] + r*m2x/dm2, c2[1] + r*m2y/dm2) + c2 = (p1[0] + r * vx, p1[1] + r * vy) + m2x, m2y = ((p1[0] + p2[0]) / 2 - c2[0], (p1[1] + p2[1]) / 2 - c2[1]) + dm2 = (m2x**2 + m2y**2) ** 0.5 + m2x, m2y = (c2[0] + r * m2x / dm2, c2[1] + r * m2y / dm2) m2 = (m2x, m2y) return m1, m2 diff --git a/src/Mod/PartDesign/fcsprocket/fcsprocketdialog.py b/src/Mod/PartDesign/fcsprocket/fcsprocketdialog.py index 455ade00b1..99aac38873 100644 --- a/src/Mod/PartDesign/fcsprocket/fcsprocketdialog.py +++ b/src/Mod/PartDesign/fcsprocket/fcsprocketdialog.py @@ -18,6 +18,7 @@ from PySide import QtGui as qt import FreeCAD, FreeCADGui + class SprocketCreationFrame(qt.QFrame): def __init__(self, parent=None): super(SprocketCreationFrame, self).__init__(parent) @@ -27,9 +28,9 @@ class SprocketCreationFrame(qt.QFrame): l = qt.QFormLayout(self) l.setFieldGrowthPolicy(l.ExpandingFieldsGrow) - l.addRow('Number of teeth:', self.N) - l.addRow('Chain Pitch (in):', self.P) - l.addRow('Roller Diameter (in):', self.Dr) + l.addRow("Number of teeth:", self.N) + l.addRow("Chain Pitch (in):", self.P) + l.addRow("Roller Diameter (in):", self.Dr) class SprocketDialog(qt.QDialog): @@ -38,27 +39,27 @@ class SprocketDialog(qt.QDialog): self.gc = SprocketCreationFrame() btns = qt.QDialogButtonBox.Ok | qt.QDialogButtonBox.Cancel - buttonBox = qt.QDialogButtonBox(btns, - accepted=self.accept, - rejected=self.reject) + buttonBox = qt.QDialogButtonBox(btns, accepted=self.accept, rejected=self.reject) l = qt.QVBoxLayout(self) l.addWidget(self.gc) l.addWidget(buttonBox) - self.setWindowTitle('Sprocket Creation Dialog') + self.setWindowTitle("Sprocket Creation Dialog") def accept(self): if FreeCAD.ActiveDocument is None: FreeCAD.newDocument("Sprocket") - gear_unused = fcgear.makeSprocket(self.gc.m.value(), - self.gc.Z.value(), - self.gc.angle.value(), - not self.gc.split.currentIndex()) + gear_unused = fcgear.makeSprocket( + self.gc.m.value(), + self.gc.Z.value(), + self.gc.angle.value(), + not self.gc.split.currentIndex(), + ) FreeCADGui.SendMsgToActiveView("ViewFit") return super(SprocketDialog, self).accept() -if __name__ == '__main__': +if __name__ == "__main__": a = qt.QApplication([]) w = SprocketDialog() w.show() diff --git a/src/Mod/PartDesign/fcsprocket/sprocket.py b/src/Mod/PartDesign/fcsprocket/sprocket.py index 0c09f4d7bd..39a0396597 100644 --- a/src/Mod/PartDesign/fcsprocket/sprocket.py +++ b/src/Mod/PartDesign/fcsprocket/sprocket.py @@ -31,37 +31,38 @@ def CreateSprocket(w, P, N, Dr): """ Ds = 1.005 * Dr + (0.003 * 25.4) R = Ds / 2 - M = 0.8 * Dr * cos(radians(35) + radians(60/N)) - T = 0.8 * Dr * sin(radians(35) + radians(60/N)) + M = 0.8 * Dr * cos(radians(35) + radians(60 / N)) + T = 0.8 * Dr * sin(radians(35) + radians(60 / N)) E = 1.3025 * Dr + (0.0015 * 25.4) - W = 1.4 * Dr * cos(radians(180/N)) - V = 1.4 * Dr * sin(radians(180/N)) - F = Dr * (0.8 * cos(radians(18) - radians(56)/N) + 1.4 * - cos(radians(17) - radians(64) / N) - 1.3025) - (0.0015 * 25.4) - PD = P / (sin(radians(180)/N)) + W = 1.4 * Dr * cos(radians(180 / N)) + V = 1.4 * Dr * sin(radians(180 / N)) + F = Dr * ( + 0.8 * cos(radians(18) - radians(56) / N) + 1.4 * cos(radians(17) - radians(64) / N) - 1.3025 + ) - (0.0015 * 25.4) + PD = P / (sin(radians(180) / N)) # H = sqrt(F**2 - (1.4 * Dr - P/2)**2) # OD = P * (0.6 + 1/tan(radians(180/N))) # The sprocket tooth gullet consists of four segments x0 = 0 - y0 = PD/2 - R + y0 = PD / 2 - R # ---- Segment 1 ----- - alpha = 35 + 60/N + alpha = 35 + 60 / N x1 = -R * cos(radians(alpha)) - y1 = PD/2 - R * sin(radians(alpha)) + y1 = PD / 2 - R * sin(radians(alpha)) # ---- Segment 2 ----- - alpha = 35 + 60/N + alpha = 35 + 60 / N beta = 18 - 56 / N - x2 = M - E * cos(radians(alpha-beta)) - y2 = T - E * sin(radians(alpha-beta)) + PD/2 + x2 = M - E * cos(radians(alpha - beta)) + y2 = T - E * sin(radians(alpha - beta)) + PD / 2 # # ---- Segment 3 ----- - y2o = y2 - PD/2 - hyp = sqrt((-W-x2)**2 + (-V-y2o)**2) + y2o = y2 - PD / 2 + hyp = sqrt((-W - x2) ** 2 + (-V - y2o) ** 2) AP = sqrt(hyp**2 - F**2) - gamma = atan((y2o + V)/(x2 + W)) + gamma = atan((y2o + V) / (x2 + W)) alpha = asin(AP / hyp) beta = 180 - (90 - degrees(alpha)) - (90 - degrees(gamma)) x3o = AP * sin(radians(beta)) @@ -70,28 +71,28 @@ def CreateSprocket(w, P, N, Dr): y3 = y2 + y3o # ---- Segment 4 ----- - alpha = 180/N - m = -1/tan(radians(alpha)) - yf = PD/2 - V + alpha = 180 / N + m = -1 / tan(radians(alpha)) + yf = PD / 2 - V A = 1 + m**2 - B = 2*m*yf - 2*W + B = 2 * m * yf - 2 * W C = W**2 + yf**2 - F**2 # x4a = (-B - sqrt(B**2 - 4 * A * C)) / (2*A) - x4b = (-B + sqrt(B**2 - 4 * A * C)) / (2*A) + x4b = (-B + sqrt(B**2 - 4 * A * C)) / (2 * A) x4 = -x4b y4 = m * x4 - p0 = [x0,y0] - p1 = [x1,y1] - p2 = [x2,y2] - p3 = [x3,y3] - p4 = [x4,y4] - p5 = [-x1,y1] - p6 = [-x2,y2] - p7 = [-x3,y3] - p8 = [-x4,y4] + p0 = [x0, y0] + p1 = [x1, y1] + p2 = [x2, y2] + p3 = [x3, y3] + p4 = [x4, y4] + p5 = [-x1, y1] + p6 = [-x2, y2] + p7 = [-x3, y3] + p8 = [-x4, y4] - w.move(p4) # vectors are lists [x,y] + w.move(p4) # vectors are lists [x,y] w.arc(p3, F, 0) w.line(p2) w.arc(p1, E, 1) @@ -104,19 +105,19 @@ def CreateSprocket(w, P, N, Dr): w.arc(p8, F, 0) # ---- Polar Array ---- - alpha = -radians(360/N) - for n in range(1,N): + alpha = -radians(360 / N) + for n in range(1, N): # falling gullet slope - w.arc(rotate(p3, alpha*n), F, 0) - w.line(rotate(p2, alpha*n)) - w.arc(rotate(p1, alpha*n), E, 1) - w.arc(rotate(p0, alpha*n), R, 1) + w.arc(rotate(p3, alpha * n), F, 0) + w.line(rotate(p2, alpha * n)) + w.arc(rotate(p1, alpha * n), E, 1) + w.arc(rotate(p0, alpha * n), R, 1) # rising gullet slope - w.arc(rotate(p5, alpha*n), R, 1) - w.line(rotate(p6, alpha*n)) - w.arc(rotate(p7, alpha*n), E, 0) - w.arc(rotate(p8, alpha*n), F, 0) + w.arc(rotate(p5, alpha * n), R, 1) + w.line(rotate(p6, alpha * n)) + w.arc(rotate(p7, alpha * n), E, 0) + w.arc(rotate(p8, alpha * n), F, 0) w.close() @@ -129,8 +130,4 @@ def rotate(pt, rads): """ sinA = sin(rads) cosA = cos(rads) - return (pt[0] * cosA - pt[1] * sinA, - pt[0] * sinA + pt[1] * cosA) - - - + return (pt[0] * cosA - pt[1] * sinA, pt[0] * sinA + pt[1] * cosA) diff --git a/src/Mod/PartDesign/partdesign.dox b/src/Mod/PartDesign/partdesign.dox index 4523ea669e..2689483420 100644 --- a/src/Mod/PartDesign/partdesign.dox +++ b/src/Mod/PartDesign/partdesign.dox @@ -2,4 +2,3 @@ * \ingroup CWORKBENCHES * \brief Complete suite of tools to design Parts based on Sketches */ - diff --git a/src/Mod/Points/App/AppPointsPy.cpp b/src/Mod/Points/App/AppPointsPy.cpp index a5ebfbc591..4954919f45 100644 --- a/src/Mod/Points/App/AppPointsPy.cpp +++ b/src/Mod/Points/App/AppPointsPy.cpp @@ -52,10 +52,12 @@ public: add_varargs_method("open", &Module::open); add_varargs_method("insert", &Module::importer); add_varargs_method("export", &Module::exporter); - add_varargs_method("show", - &Module::show, - "show(points,[string]) -- Add the points to the active document or " - "create one if no document exists. Returns document object."); + add_varargs_method( + "show", + &Module::show, + "show(points,[string]) -- Add the points to the active document or " + "create one if no document exists. Returns document object." + ); initialize("This module is the Points module."); // register with Python } @@ -97,9 +99,11 @@ private: } else if (file.hasExtension("e57")) { auto setting = readE57Settings(); - reader = std::make_unique(std::get<0>(setting), - std::get<1>(setting), - std::get<2>(setting)); + reader = std::make_unique( + std::get<0>(setting), + std::get<1>(setting), + std::get<2>(setting) + ); } else if (file.hasExtension("ply")) { reader = std::make_unique(); @@ -121,13 +125,15 @@ private: if (reader->isStructured()) { pcFeature = new Points::StructuredCustom(); - App::PropertyInteger* width = - static_cast(pcFeature->getPropertyByName("Width")); + App::PropertyInteger* width = static_cast( + pcFeature->getPropertyByName("Width") + ); if (width) { width->setValue(reader->getWidth()); } - App::PropertyInteger* height = - static_cast(pcFeature->getPropertyByName("Height")); + App::PropertyInteger* height = static_cast( + pcFeature->getPropertyByName("Height") + ); if (height) { height->setValue(reader->getHeight()); } @@ -139,10 +145,9 @@ private: pcFeature->Points.setValue(reader->getPoints()); // add gray values if (reader->hasIntensities()) { - Points::PropertyGreyValueList* prop = - static_cast( - pcFeature->addDynamicProperty("Points::PropertyGreyValueList", - "Intensity")); + Points::PropertyGreyValueList* prop = static_cast( + pcFeature->addDynamicProperty("Points::PropertyGreyValueList", "Intensity") + ); if (prop) { prop->setValues(reader->getIntensities()); } @@ -150,7 +155,8 @@ private: // add colors if (reader->hasColors()) { App::PropertyColorList* prop = static_cast( - pcFeature->addDynamicProperty("App::PropertyColorList", "Color")); + pcFeature->addDynamicProperty("App::PropertyColorList", "Color") + ); if (prop) { prop->setValues(reader->getColors()); } @@ -158,7 +164,8 @@ private: // add normals if (reader->hasNormals()) { Points::PropertyNormalList* prop = static_cast( - pcFeature->addDynamicProperty("Points::PropertyNormalList", "Normal")); + pcFeature->addDynamicProperty("Points::PropertyNormalList", "Normal") + ); if (prop) { prop->setValues(reader->getNormals()); } @@ -219,9 +226,11 @@ private: } else if (file.hasExtension("e57")) { auto setting = readE57Settings(); - reader = std::make_unique(std::get<0>(setting), - std::get<1>(setting), - std::get<2>(setting)); + reader = std::make_unique( + std::get<0>(setting), + std::get<1>(setting), + std::get<2>(setting) + ); } else if (file.hasExtension("ply")) { reader = std::make_unique(); @@ -246,13 +255,15 @@ private: if (reader->isStructured()) { pcFeature = new Points::StructuredCustom(); - App::PropertyInteger* width = - static_cast(pcFeature->getPropertyByName("Width")); + App::PropertyInteger* width = static_cast( + pcFeature->getPropertyByName("Width") + ); if (width) { width->setValue(reader->getWidth()); } - App::PropertyInteger* height = - static_cast(pcFeature->getPropertyByName("Height")); + App::PropertyInteger* height = static_cast( + pcFeature->getPropertyByName("Height") + ); if (height) { height->setValue(reader->getHeight()); } @@ -264,10 +275,9 @@ private: pcFeature->Points.setValue(reader->getPoints()); // add gray values if (reader->hasIntensities()) { - Points::PropertyGreyValueList* prop = - static_cast( - pcFeature->addDynamicProperty("Points::PropertyGreyValueList", - "Intensity")); + Points::PropertyGreyValueList* prop = static_cast( + pcFeature->addDynamicProperty("Points::PropertyGreyValueList", "Intensity") + ); if (prop) { prop->setValues(reader->getIntensities()); } @@ -275,7 +285,8 @@ private: // add colors if (reader->hasColors()) { App::PropertyColorList* prop = static_cast( - pcFeature->addDynamicProperty("App::PropertyColorList", "Color")); + pcFeature->addDynamicProperty("App::PropertyColorList", "Color") + ); if (prop) { prop->setValues(reader->getColors()); } @@ -283,7 +294,8 @@ private: // add normals if (reader->hasNormals()) { Points::PropertyNormalList* prop = static_cast( - pcFeature->addDynamicProperty("Points::PropertyNormalList", "Normal")); + pcFeature->addDynamicProperty("Points::PropertyNormalList", "Normal") + ); if (prop) { prop->setValues(reader->getNormals()); } @@ -331,8 +343,8 @@ private: for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { PyObject* item = (*it).ptr(); if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = - static_cast(item)->getDocumentObjectPtr(); + App::DocumentObject* obj + = static_cast(item)->getDocumentObjectPtr(); if (obj->isDerivedFrom()) { // get relative placement Points::Feature* fea = static_cast(obj); @@ -354,32 +366,36 @@ private: } // get additional properties if there - App::PropertyInteger* width = - dynamic_cast(fea->getPropertyByName("Width")); + App::PropertyInteger* width = dynamic_cast( + fea->getPropertyByName("Width") + ); if (width) { writer->setWidth(width->getValue()); } - App::PropertyInteger* height = - dynamic_cast(fea->getPropertyByName("Height")); + App::PropertyInteger* height = dynamic_cast( + fea->getPropertyByName("Height") + ); if (height) { writer->setHeight(height->getValue()); } // get gray values - Points::PropertyGreyValueList* grey = - dynamic_cast( - fea->getPropertyByName("Intensity")); + Points::PropertyGreyValueList* grey = dynamic_cast( + fea->getPropertyByName("Intensity") + ); if (grey) { writer->setIntensities(grey->getValues()); } // get colors - App::PropertyColorList* col = - dynamic_cast(fea->getPropertyByName("Color")); + App::PropertyColorList* col = dynamic_cast( + fea->getPropertyByName("Color") + ); if (col) { writer->setColors(col->getValues()); } // get normals - Points::PropertyNormalList* nor = - dynamic_cast(fea->getPropertyByName("Normal")); + Points::PropertyNormalList* nor = dynamic_cast( + fea->getPropertyByName("Normal") + ); if (nor) { writer->setNormals(nor->getValues()); } @@ -390,8 +406,10 @@ private: break; } else { - Base::Console().message("'%s' is not a point object, export will be ignored.\n", - obj->Label.getValue()); + Base::Console().message( + "'%s' is not a point object, export will be ignored.\n", + obj->Label.getValue() + ); } } } diff --git a/src/Mod/Points/App/Points.cpp b/src/Mod/Points/App/Points.cpp index 505f175f91..e21e1020a4 100644 --- a/src/Mod/Points/App/Points.cpp +++ b/src/Mod/Points/App/Points.cpp @@ -37,7 +37,7 @@ #ifdef _MSC_VER -#include +# include #endif using namespace Points; @@ -93,9 +93,7 @@ void PointKernel::transformGeometry(const Base::Matrix4D& rclMat) value = rclMat * value; }); #else - QtConcurrent::blockingMap(kernel, [rclMat](value_type& value) { - rclMat.multVec(value, value); - }); + QtConcurrent::blockingMap(kernel, [rclMat](value_type& value) { rclMat.multVec(value, value); }); #endif } @@ -108,9 +106,7 @@ void PointKernel::moveGeometry(const Base::Vector3d& vec) value += offset; }); #else - QtConcurrent::blockingMap(kernel, [offset](value_type& value) { - value += offset; - }); + QtConcurrent::blockingMap(kernel, [offset](value_type& value) { value += offset; }); #endif } @@ -123,16 +119,12 @@ Base::BoundBox3d PointKernel::getBoundBox() const Concurrency::combinable bbs; // Cannot use a const_point_iterator here as it is *not* a proper iterator (fails the for_each // template) - Concurrency::parallel_for_each(_Points.begin(), - _Points.end(), - [this, &bbs](const value_type& value) { - Base::Vector3d vertd(value.x, value.y, value.z); - bbs.local().Add(this->_Mtrx * vertd); - }); - // Combine each thread-local bounding box in the final bounding box - bbs.combine_each([&bnd](const Base::BoundBox3d& lbb) { - bnd.Add(lbb); + Concurrency::parallel_for_each(_Points.begin(), _Points.end(), [this, &bbs](const value_type& value) { + Base::Vector3d vertd(value.x, value.y, value.z); + bbs.local().Add(this->_Mtrx * vertd); }); + // Combine each thread-local bounding box in the final bounding box + bbs.combine_each([&bnd](const Base::BoundBox3d& lbb) { bnd.Add(lbb); }); #else for (const auto& it : *this) { bnd.Add(it); @@ -185,9 +177,11 @@ std::vector PointKernel::getValidPoints() const valid.reserve(countValid()); for (const auto& it : *this) { if (!(boost::math::isnan(it.x) || boost::math::isnan(it.y) || boost::math::isnan(it.z))) { - valid.emplace_back(static_cast(it.x), - static_cast(it.y), - static_cast(it.z)); + valid.emplace_back( + static_cast(it.x), + static_cast(it.y), + static_cast(it.z) + ); } } return valid; @@ -264,10 +258,12 @@ void PointKernel::save(std::ostream& out) const } } -void PointKernel::getPoints(std::vector& Points, - std::vector& /*Normals*/, - double /*Accuracy*/, - uint16_t /*flags*/) const +void PointKernel::getPoints( + std::vector& Points, + std::vector& /*Normals*/, + double /*Accuracy*/, + uint16_t /*flags*/ +) const { unsigned long ctpoints = _Points.size(); Points.reserve(ctpoints); @@ -280,7 +276,8 @@ void PointKernel::getPoints(std::vector& Points, PointKernel::const_point_iterator::const_point_iterator( const PointKernel* kernel, - std::vector::const_iterator index) + std::vector::const_iterator index +) : _kernel(kernel) , _p_it(index) { @@ -291,18 +288,22 @@ PointKernel::const_point_iterator::const_point_iterator( } PointKernel::const_point_iterator::const_point_iterator( - const PointKernel::const_point_iterator& fi) = default; + const PointKernel::const_point_iterator& fi +) = default; -PointKernel::const_point_iterator::const_point_iterator(PointKernel::const_point_iterator&& fi) = - default; +PointKernel::const_point_iterator::const_point_iterator( + PointKernel::const_point_iterator&& fi +) = default; PointKernel::const_point_iterator::~const_point_iterator() = default; -PointKernel::const_point_iterator& -PointKernel::const_point_iterator::operator=(const PointKernel::const_point_iterator& pi) = default; +PointKernel::const_point_iterator& PointKernel::const_point_iterator::operator=( + const PointKernel::const_point_iterator& pi +) = default; -PointKernel::const_point_iterator& -PointKernel::const_point_iterator::operator=(PointKernel::const_point_iterator&& pi) = default; +PointKernel::const_point_iterator& PointKernel::const_point_iterator::operator=( + PointKernel::const_point_iterator&& pi +) = default; void PointKernel::const_point_iterator::dereference() { @@ -322,14 +323,12 @@ const PointKernel::const_point_iterator::value_type* PointKernel::const_point_it return &(this->_point); } -bool PointKernel::const_point_iterator::operator==( - const PointKernel::const_point_iterator& pi) const +bool PointKernel::const_point_iterator::operator==(const PointKernel::const_point_iterator& pi) const { return (this->_kernel == pi._kernel) && (this->_p_it == pi._p_it); } -bool PointKernel::const_point_iterator::operator!=( - const PointKernel::const_point_iterator& pi) const +bool PointKernel::const_point_iterator::operator!=(const PointKernel::const_point_iterator& pi) const { return !operator==(pi); } @@ -360,36 +359,33 @@ PointKernel::const_point_iterator PointKernel::const_point_iterator::operator--( return tmp; } -PointKernel::const_point_iterator -PointKernel::const_point_iterator::operator+(difference_type off) const +PointKernel::const_point_iterator PointKernel::const_point_iterator::operator+(difference_type off) const { PointKernel::const_point_iterator tmp = *this; return (tmp += off); } -PointKernel::const_point_iterator -PointKernel::const_point_iterator::operator-(difference_type off) const +PointKernel::const_point_iterator PointKernel::const_point_iterator::operator-(difference_type off) const { PointKernel::const_point_iterator tmp = *this; return (tmp -= off); } -PointKernel::const_point_iterator& -PointKernel::const_point_iterator::operator+=(difference_type off) +PointKernel::const_point_iterator& PointKernel::const_point_iterator::operator+=(difference_type off) { (this->_p_it) += off; return *this; } -PointKernel::const_point_iterator& -PointKernel::const_point_iterator::operator-=(difference_type off) +PointKernel::const_point_iterator& PointKernel::const_point_iterator::operator-=(difference_type off) { (this->_p_it) -= off; return *this; } -PointKernel::difference_type -PointKernel::const_point_iterator::operator-(const PointKernel::const_point_iterator& right) const +PointKernel::difference_type PointKernel::const_point_iterator::operator-( + const PointKernel::const_point_iterator& right +) const { return this->_p_it - right._p_it; } diff --git a/src/Mod/Points/App/Points.h b/src/Mod/Points/App/Points.h index 0e0cf23e88..670bad9dd8 100644 --- a/src/Mod/Points/App/Points.h +++ b/src/Mod/Points/App/Points.h @@ -103,10 +103,12 @@ public: this->_Points.swap(pts); } - void getPoints(std::vector& Points, - std::vector& Normals, - double Accuracy, - uint16_t flags = 0) const override; + void getPoints( + std::vector& Points, + std::vector& Normals, + double Accuracy, + uint16_t flags = 0 + ) const override; void transformGeometry(const Base::Matrix4D& rclMat) override; void moveGeometry(const Base::Vector3d& vec); Base::BoundBox3d getBoundBox() const override; diff --git a/src/Mod/Points/App/PointsAlgos.cpp b/src/Mod/Points/App/PointsAlgos.cpp index d0c0c1984a..09ed26a4f6 100644 --- a/src/Mod/Points/App/PointsAlgos.cpp +++ b/src/Mod/Points/App/PointsAlgos.cpp @@ -25,7 +25,7 @@ #include #ifdef FC_OS_LINUX -#include +# include #endif #include #include @@ -67,9 +67,11 @@ void PointsAlgos::Load(PointKernel& points, const char* FileName) void PointsAlgos::LoadAscii(PointKernel& points, const char* FileName) { - boost::regex rx("^\\s*([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$"); + boost::regex rx( + "^\\s*([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" + "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)\\s*$" + ); // boost::regex rx("(\\b[0-9]+\\.([0-9]+\\b)?|\\.[0-9]+\\b)"); // boost::regex // rx("^\\s*(-?[0-9]*)\\.([0-9]+)\\s+(-?[0-9]*)\\.([0-9]+)\\s+(-?[0-9]*)\\.([0-9]+)\\s*$"); @@ -285,9 +287,11 @@ protected: { return _end - _cur; } - pos_type seekoff(std::streambuf::off_type off, - std::ios_base::seekdir way, - std::ios_base::openmode mode = std::ios::in | std::ios::out) override + pos_type seekoff( + std::streambuf::off_type off, + std::ios_base::seekdir way, + std::ios_base::openmode mode = std::ios::in | std::ios::out + ) override { (void)mode; int p_pos = -1; @@ -313,8 +317,10 @@ protected: return ((p_pos + off) - _beg); } - pos_type seekpos(std::streambuf::pos_type pos, - std::ios_base::openmode which = std::ios::in | std::ios::out) override + pos_type seekpos( + std::streambuf::pos_type pos, + std::ios_base::openmode which = std::ios::in | std::ios::out + ) override { (void)which; return seekoff(pos, std::ios_base::beg); @@ -333,8 +339,12 @@ private: // NOLINTBEGIN // Taken from https://github.com/PointCloudLibrary/pcl/blob/master/io/src/lzf.cpp -unsigned int -lzfDecompress(const void* const in_data, unsigned int in_len, void* out_data, unsigned int out_len) +unsigned int lzfDecompress( + const void* const in_data, + unsigned int in_len, + void* out_data, + unsigned int out_len +) { unsigned char const* ip = static_cast(in_data); unsigned char* op = static_cast(out_data); @@ -698,10 +708,12 @@ void PlyReader::read(const std::string& filename) if (alpha != max_size) { a = static_cast(data(i, alpha)); } - colors.emplace_back(static_cast(r) / 255.0F, - static_cast(g) / 255.0F, - static_cast(b) / 255.0F, - static_cast(a) / 255.0F); + colors.emplace_back( + static_cast(r) / 255.0F, + static_cast(g) / 255.0F, + static_cast(b) / 255.0F, + static_cast(a) / 255.0F + ); } } else if (types[red] == "float") { @@ -718,12 +730,14 @@ void PlyReader::read(const std::string& filename) } } -std::size_t PlyReader::readHeader(std::istream& in, - std::string& format, - std::size_t& offset, - std::vector& fields, - std::vector& types, - std::vector& sizes) +std::size_t PlyReader::readHeader( + std::istream& in, + std::string& format, + std::size_t& offset, + std::vector& fields, + std::vector& types, + std::vector& sizes +) { std::string line; std::string element; @@ -921,12 +935,14 @@ void PlyReader::readAscii(std::istream& inp, std::size_t offset, Eigen::MatrixXd } } -void PlyReader::readBinary(bool swapByteOrder, - std::istream& inp, - std::size_t offset, - const std::vector& types, - const std::vector& sizes, - Eigen::MatrixXd& data) +void PlyReader::readBinary( + bool swapByteOrder, + std::istream& inp, + std::size_t offset, + const std::vector& types, + const std::vector& sizes, + Eigen::MatrixXd& data +) { Eigen::Index numPoints = data.rows(); Eigen::Index numFields = data.cols(); @@ -1173,8 +1189,7 @@ void PcdReader::read(const std::string& filename) } } else if (types[rgba] == "F") { - static_assert(sizeof(float) == sizeof(uint32_t), - "float and uint32_t have different sizes"); + static_assert(sizeof(float) == sizeof(uint32_t), "float and uint32_t have different sizes"); for (Eigen::Index i = 0; i < numPoints; i++) { float f = static_cast(data(i, rgba)); uint32_t packed {}; @@ -1187,11 +1202,13 @@ void PcdReader::read(const std::string& filename) } } -std::size_t PcdReader::readHeader(std::istream& in, - std::string& format, - std::vector& fields, - std::vector& types, - std::vector& sizes) +std::size_t PcdReader::readHeader( + std::istream& in, + std::string& format, + std::vector& fields, + std::vector& types, + std::vector& sizes +) { std::string line; std::vector counts; @@ -1286,11 +1303,13 @@ void PcdReader::readAscii(std::istream& inp, Eigen::MatrixXd& data) } } -void PcdReader::readBinary(bool transpose, - std::istream& inp, - const std::vector& types, - const std::vector& sizes, - Eigen::MatrixXd& data) +void PcdReader::readBinary( + bool transpose, + std::istream& inp, + const std::vector& types, + const std::vector& sizes, + Eigen::MatrixXd& data +) { Eigen::Index numPoints = data.rows(); Eigen::Index numFields = data.cols(); @@ -1484,16 +1503,21 @@ private: for (int i = 0; i < prototype.childCount(); ++i) { e57::Node node(prototype.get(i)); if ((node.type() == e57::E57_FLOAT) || (node.type() == e57::E57_SCALED_INTEGER)) { - if (readCartesian(node, proto)) {} - else if (readNormal(node, proto)) {} - else if (readItensity(node, proto)) {} + if (readCartesian(node, proto)) { + } + else if (readNormal(node, proto)) { + } + else if (readItensity(node, proto)) { + } else { readOther(node, proto); } } else if (node.type() == e57::E57_INTEGER) { - if (readColor(node, proto)) {} - else if (readCartesianInvalidState(node, proto)) {} + if (readColor(node, proto)) { + } + else if (readCartesianInvalidState(node, proto)) { + } else { readOther(node, proto); } @@ -1507,26 +1531,41 @@ private: { if (node.elementName() == "cartesianX") { proto.cnt_xyz++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.xData.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.xData.data(), + buf_size, + true, + true - ); + ); return true; } else if (node.elementName() == "cartesianY") { proto.cnt_xyz++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.yData.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.yData.data(), + buf_size, + true, + true - ); + ); return true; } else if (node.elementName() == "cartesianZ") { proto.cnt_xyz++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.zData.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.zData.data(), + buf_size, + true, + true - ); + ); return true; } @@ -1537,26 +1576,41 @@ private: { if (node.elementName() == "nor:normalX") { proto.cnt_nor++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.xNormal.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.xNormal.data(), + buf_size, + true, + true - ); + ); return true; } else if (node.elementName() == "nor:normalY") { proto.cnt_nor++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.yNormal.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.yNormal.data(), + buf_size, + true, + true - ); + ); return true; } else if (node.elementName() == "nor:normalZ") { proto.cnt_nor++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.zNormal.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.zNormal.data(), + buf_size, + true, + true - ); + ); return true; } @@ -1567,10 +1621,15 @@ private: { if (node.elementName() == "cartesianInvalidState") { proto.inv_state = true; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.state.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.state.data(), + buf_size, + true, + true - ); + ); return true; } @@ -1581,26 +1640,41 @@ private: { if (node.elementName() == "colorRed") { proto.cnt_rgb++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.redData.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.redData.data(), + buf_size, + true, + true - ); + ); return true; } if (node.elementName() == "colorGreen") { proto.cnt_rgb++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.greenData.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.greenData.data(), + buf_size, + true, + true - ); + ); return true; } if (node.elementName() == "colorBlue") { proto.cnt_rgb++; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.blueData.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.blueData.data(), + buf_size, + true, + true - ); + ); return true; } @@ -1611,10 +1685,15 @@ private: { if (node.elementName() == "intensity") { proto.inty = true; - proto.sdb - .emplace_back(imfi, node.elementName(), proto.intensity.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.intensity.data(), + buf_size, + true, + true - ); + ); return true; } @@ -1623,15 +1702,23 @@ private: void readOther(const e57::Node& node, Proto& proto) { - proto.sdb.emplace_back(imfi, node.elementName(), proto.nil.data(), buf_size, true, true + proto.sdb.emplace_back( + imfi, + node.elementName(), + proto.nil.data(), + buf_size, + true, + true ); } - void processProto(e57::CompressedVectorNode& cvn, - const Proto& proto, - bool hasPlacement, - const Base::Placement& plm) + void processProto( + e57::CompressedVectorNode& cvn, + const Proto& proto, + bool hasPlacement, + const Base::Placement& plm + ) { if (proto.cnt_xyz != 3) { throw Base::BadFormatError("Missing channels xyz"); @@ -1680,8 +1767,12 @@ private: } } - Base::Vector3d - getCoord(const Proto& proto, size_t index, bool hasPlacement, const Base::Placement& plm) const + Base::Vector3d getCoord( + const Proto& proto, + size_t index, + bool hasPlacement, + const Base::Placement& plm + ) const { Base::Vector3d pt; pt.x = proto.xData[index]; @@ -1693,8 +1784,12 @@ private: return pt; } - Base::Vector3f - getNormal(const Proto& proto, size_t index, bool hasPlacement, const Base::Rotation& rot) const + Base::Vector3f getNormal( + const Proto& proto, + size_t index, + bool hasPlacement, + const Base::Rotation& rot + ) const { Base::Vector3f pt; pt.x = proto.xNormal[index]; diff --git a/src/Mod/Points/App/PointsAlgos.h b/src/Mod/Points/App/PointsAlgos.h index 9bfb7127a1..5a83f1fbb4 100644 --- a/src/Mod/Points/App/PointsAlgos.h +++ b/src/Mod/Points/App/PointsAlgos.h @@ -97,19 +97,23 @@ public: void read(const std::string& filename) override; private: - std::size_t readHeader(std::istream&, - std::string& format, - std::size_t& offset, - std::vector& fields, - std::vector& types, - std::vector& sizes); + std::size_t readHeader( + std::istream&, + std::string& format, + std::size_t& offset, + std::vector& fields, + std::vector& types, + std::vector& sizes + ); void readAscii(std::istream&, std::size_t offset, Eigen::MatrixXd& data); - void readBinary(bool swapByteOrder, - std::istream&, - std::size_t offset, - const std::vector& types, - const std::vector& sizes, - Eigen::MatrixXd& data); + void readBinary( + bool swapByteOrder, + std::istream&, + std::size_t offset, + const std::vector& types, + const std::vector& sizes, + Eigen::MatrixXd& data + ); }; class PointsExport PcdReader: public Reader @@ -119,17 +123,21 @@ public: void read(const std::string& filename) override; private: - std::size_t readHeader(std::istream&, - std::string& format, - std::vector& fields, - std::vector& types, - std::vector& sizes); + std::size_t readHeader( + std::istream&, + std::string& format, + std::vector& fields, + std::vector& types, + std::vector& sizes + ); void readAscii(std::istream&, Eigen::MatrixXd& data); - void readBinary(bool transpose, - std::istream&, - const std::vector& types, - const std::vector& sizes, - Eigen::MatrixXd& data); + void readBinary( + bool transpose, + std::istream&, + const std::vector& types, + const std::vector& sizes, + Eigen::MatrixXd& data + ); }; class PointsExport E57Reader: public Reader diff --git a/src/Mod/Points/App/PointsGrid.cpp b/src/Mod/Points/App/PointsGrid.cpp index 5c1f91fbad..504ffb626b 100644 --- a/src/Mod/Points/App/PointsGrid.cpp +++ b/src/Mod/Points/App/PointsGrid.cpp @@ -58,10 +58,7 @@ PointsGrid::PointsGrid() , _fMinZ(0.0F) {} -PointsGrid::PointsGrid(const PointKernel& rclM, - unsigned long ulX, - unsigned long ulY, - unsigned long ulZ) +PointsGrid::PointsGrid(const PointKernel& rclM, unsigned long ulX, unsigned long ulY, unsigned long ulZ) : _pclPoints(&rclM) , _ulCtElements(0) , _ulCtGridsX(0) @@ -110,9 +107,11 @@ PointsGrid::PointsGrid(const PointKernel& rclM, double fGridLen) for (const auto& pnt : *_pclPoints) { clBBPts.Add(pnt); } - PointsGrid::Rebuild(std::max((unsigned long)(clBBPts.LengthX() / fGridLen), 1), - std::max((unsigned long)(clBBPts.LengthY() / fGridLen), 1), - std::max((unsigned long)(clBBPts.LengthZ() / fGridLen), 1)); + PointsGrid::Rebuild( + std::max((unsigned long)(clBBPts.LengthX() / fGridLen), 1), + std::max((unsigned long)(clBBPts.LengthY() / fGridLen), 1), + std::max((unsigned long)(clBBPts.LengthZ() / fGridLen), 1) + ); } void PointsGrid::Attach(const PointKernel& rclM) @@ -213,9 +212,11 @@ void PointsGrid::InitGrid() } } -unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, - std::vector& raulElements, - bool bDelDoubles) const +unsigned long PointsGrid::InSide( + const Base::BoundBox3d& rclBB, + std::vector& raulElements, + bool bDelDoubles +) const { unsigned long ulMinX {}; unsigned long ulMinY {}; @@ -233,9 +234,8 @@ unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, for (auto i = ulMinX; i <= ulMaxX; i++) { for (auto j = ulMinY; j <= ulMaxY; j++) { for (auto k = ulMinZ; k <= ulMaxZ; k++) { - raulElements.insert(raulElements.end(), - _aulGrid[i][j][k].begin(), - _aulGrid[i][j][k].end()); + raulElements + .insert(raulElements.end(), _aulGrid[i][j][k].begin(), _aulGrid[i][j][k].end()); } } } @@ -243,18 +243,19 @@ unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, if (bDelDoubles) { // remove duplicate mentions std::sort(raulElements.begin(), raulElements.end()); - raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), - raulElements.end()); + raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), raulElements.end()); } return raulElements.size(); } -unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, - std::vector& raulElements, - const Base::Vector3d& rclOrg, - double fMaxDist, - bool bDelDoubles) const +unsigned long PointsGrid::InSide( + const Base::BoundBox3d& rclBB, + std::vector& raulElements, + const Base::Vector3d& rclOrg, + double fMaxDist, + bool bDelDoubles +) const { unsigned long ulMinX {}, ulMinY {}, ulMinZ {}; unsigned long ulMaxX {}, ulMaxY {}, ulMaxZ {}; @@ -271,9 +272,11 @@ unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, for (auto j = ulMinY; j <= ulMaxY; j++) { for (auto k = ulMinZ; k <= ulMaxZ; k++) { if (Base::DistanceP2(GetBoundBox(i, j, k).GetCenter(), rclOrg) < fMinDistP2) { - raulElements.insert(raulElements.end(), - _aulGrid[i][j][k].begin(), - _aulGrid[i][j][k].end()); + raulElements.insert( + raulElements.end(), + _aulGrid[i][j][k].begin(), + _aulGrid[i][j][k].end() + ); } } } @@ -282,15 +285,13 @@ unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, if (bDelDoubles) { // remove duplicate mentions std::sort(raulElements.begin(), raulElements.end()); - raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), - raulElements.end()); + raulElements.erase(std::unique(raulElements.begin(), raulElements.end()), raulElements.end()); } return raulElements.size(); } -unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, - std::set& raulElements) const +unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, std::set& raulElements) const { unsigned long ulMinX {}, ulMinY {}, ulMinZ {}; unsigned long ulMaxX {}, ulMaxY {}, ulMaxZ {}; @@ -312,33 +313,41 @@ unsigned long PointsGrid::InSide(const Base::BoundBox3d& rclBB, return raulElements.size(); } -void PointsGrid::Position(const Base::Vector3d& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +void PointsGrid::Position( + const Base::Vector3d& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { if (rclPoint.x <= _fMinX) { rulX = 0; } else { - rulX = std::min((unsigned long)((rclPoint.x - _fMinX) / _fGridLenX), - _ulCtGridsX - 1); + rulX = std::min( + (unsigned long)((rclPoint.x - _fMinX) / _fGridLenX), + _ulCtGridsX - 1 + ); } if (rclPoint.y <= _fMinY) { rulY = 0; } else { - rulY = std::min((unsigned long)((rclPoint.y - _fMinY) / _fGridLenY), - _ulCtGridsY - 1); + rulY = std::min( + (unsigned long)((rclPoint.y - _fMinY) / _fGridLenY), + _ulCtGridsY - 1 + ); } if (rclPoint.z <= _fMinZ) { rulZ = 0; } else { - rulZ = std::min((unsigned long)((rclPoint.z - _fMinZ) / _fGridLenZ), - _ulCtGridsZ - 1); + rulZ = std::min( + (unsigned long)((rclPoint.z - _fMinZ) / _fGridLenZ), + _ulCtGridsZ - 1 + ); } } @@ -354,13 +363,11 @@ void PointsGrid::CalculateGridLength(unsigned long ulCtGrid, unsigned long ulMax double fVolElem {}; if (_ulCtElements > (ulMaxGrids * ulCtGrid)) { - fVolElem = - (clBBPtsEnlarged.LengthX() * clBBPtsEnlarged.LengthY() * clBBPtsEnlarged.LengthZ()) + fVolElem = (clBBPtsEnlarged.LengthX() * clBBPtsEnlarged.LengthY() * clBBPtsEnlarged.LengthZ()) / float(ulMaxGrids * ulCtGrid); } else { - fVolElem = - (clBBPtsEnlarged.LengthX() * clBBPtsEnlarged.LengthY() * clBBPtsEnlarged.LengthZ()) + fVolElem = (clBBPtsEnlarged.LengthX() * clBBPtsEnlarged.LengthY() * clBBPtsEnlarged.LengthZ()) / float(_ulCtElements); } @@ -368,12 +375,9 @@ void PointsGrid::CalculateGridLength(unsigned long ulCtGrid, unsigned long ulMax double fGridLen = float(pow((float)fVol, 1.0F / 3.0F)); if (fGridLen > 0) { - _ulCtGridsX = - std::max((unsigned long)(clBBPtsEnlarged.LengthX() / fGridLen), 1); - _ulCtGridsY = - std::max((unsigned long)(clBBPtsEnlarged.LengthY() / fGridLen), 1); - _ulCtGridsZ = - std::max((unsigned long)(clBBPtsEnlarged.LengthZ() / fGridLen), 1); + _ulCtGridsX = std::max((unsigned long)(clBBPtsEnlarged.LengthX() / fGridLen), 1); + _ulCtGridsY = std::max((unsigned long)(clBBPtsEnlarged.LengthY() / fGridLen), 1); + _ulCtGridsZ = std::max((unsigned long)(clBBPtsEnlarged.LengthZ() / fGridLen), 1); } else { // Degenerated grid @@ -528,8 +532,7 @@ void PointsGrid::CalculateGridLength(int iCtGridPerAxis) } } -void PointsGrid::SearchNearestFromPoint(const Base::Vector3d& rclPt, - std::set& raclInd) const +void PointsGrid::SearchNearestFromPoint(const Base::Vector3d& rclPt, std::set& raclInd) const { raclInd.clear(); Base::BoundBox3d clBB = GetBoundBox(); @@ -627,11 +630,13 @@ void PointsGrid::SearchNearestFromPoint(const Base::Vector3d& rclPt, } } -void PointsGrid::GetHull(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - unsigned long ulDistance, - std::set& raclInd) const +void PointsGrid::GetHull( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + unsigned long ulDistance, + std::set& raclInd +) const { int nX1 = std::max(0, int(ulX) - int(ulDistance)); int nY1 = std::max(0, int(ulY) - int(ulDistance)); @@ -678,10 +683,12 @@ void PointsGrid::GetHull(unsigned long ulX, } } -unsigned long PointsGrid::GetElements(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - std::set& raclInd) const +unsigned long PointsGrid::GetElements( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + std::set& raclInd +) const { const std::set& rclSet = _aulGrid[ulX][ulY][ulZ]; if (!rclSet.empty()) { @@ -760,18 +767,22 @@ void PointsGrid::RebuildGrid() } } -void PointsGrid::Pos(const Base::Vector3d& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const +void PointsGrid::Pos( + const Base::Vector3d& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ +) const { rulX = (unsigned long)((rclPoint.x - _fMinX) / _fGridLenX); rulY = (unsigned long)((rclPoint.y - _fMinY) / _fGridLenY); rulZ = (unsigned long)((rclPoint.z - _fMinZ) / _fGridLenZ); } -unsigned long PointsGrid::FindElements(const Base::Vector3d& rclPoint, - std::set& aulElements) const +unsigned long PointsGrid::FindElements( + const Base::Vector3d& rclPoint, + std::set& aulElements +) const { unsigned long ulX {}, ulY {}, ulZ {}; Pos(rclPoint, ulX, ulY, ulZ); @@ -792,19 +803,23 @@ PointsGridIterator::PointsGridIterator(const PointsGrid& rclG) , _clDir(0.0F, 0.0F, 0.0F) {} -bool PointsGridIterator::InitOnRay(const Base::Vector3d& rclPt, - const Base::Vector3d& rclDir, - float fMaxSearchArea, - std::vector& raulElements) +bool PointsGridIterator::InitOnRay( + const Base::Vector3d& rclPt, + const Base::Vector3d& rclDir, + float fMaxSearchArea, + std::vector& raulElements +) { bool ret = InitOnRay(rclPt, rclDir, raulElements); _fMaxSearchArea = fMaxSearchArea; return ret; } -bool PointsGridIterator::InitOnRay(const Base::Vector3d& rclPt, - const Base::Vector3d& rclDir, - std::vector& raulElements) +bool PointsGridIterator::InitOnRay( + const Base::Vector3d& rclPt, + const Base::Vector3d& rclDir, + std::vector& raulElements +) { // needed in NextOnRay() to avoid an infinite loop _cSearchPositions.clear(); @@ -820,17 +835,21 @@ bool PointsGridIterator::InitOnRay(const Base::Vector3d& rclPt, // point lies within global BB if (_rclGrid.GetBoundBox().IsInBox(rclPt)) { // determine the voxel by the starting point _rclGrid.Position(rclPt, _ulX, _ulY, _ulZ); - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); _bValidRay = true; } else { // StartPoint outside Base::Vector3d cP0, cP1; - if (_rclGrid.GetBoundBox().IntersectWithLine(rclPt, - rclDir, - cP0, - cP1)) { // determine the next point + if (_rclGrid.GetBoundBox().IntersectWithLine( + rclPt, + rclDir, + cP0, + cP1 + )) { // determine the next point if ((cP0 - rclPt).Length() < (cP1 - rclPt).Length()) { _rclGrid.Position(cP0, _ulX, _ulY, _ulZ); } @@ -838,9 +857,11 @@ bool PointsGridIterator::InitOnRay(const Base::Vector3d& rclPt, _rclGrid.Position(cP1, _ulX, _ulY, _ulZ); } - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); _bValidRay = true; } } @@ -859,8 +880,8 @@ bool PointsGridIterator::NextOnRay(std::vector& raulElements) Base::Vector3d clIntersectPoint; // Look for the next adjacent BB on the search beam - Base::BoundBox3d::SIDE tSide = - _rclGrid.GetBoundBox(_ulX, _ulY, _ulZ).GetSideFromRay(_clPt, _clDir, clIntersectPoint); + Base::BoundBox3d::SIDE tSide + = _rclGrid.GetBoundBox(_ulX, _ulY, _ulZ).GetSideFromRay(_clPt, _clDir, clIntersectPoint); // Search area // @@ -896,17 +917,18 @@ bool PointsGridIterator::NextOnRay(std::vector& raulElements) GridElement pos(_ulX, _ulY, _ulZ); if (_cSearchPositions.find(pos) != _cSearchPositions.end()) { - _bValidRay = - false; // grid element already visited => result from GetSideFromRay invalid + _bValidRay = false; // grid element already visited => result from GetSideFromRay invalid } } if (_bValidRay && _rclGrid.CheckPos(_ulX, _ulY, _ulZ)) { GridElement pos(_ulX, _ulY, _ulZ); _cSearchPositions.insert(pos); - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); } else { _bValidRay = false; // ray exited diff --git a/src/Mod/Points/App/PointsGrid.h b/src/Mod/Points/App/PointsGrid.h index ee5bf2833a..d447628be6 100644 --- a/src/Mod/Points/App/PointsGrid.h +++ b/src/Mod/Points/App/PointsGrid.h @@ -80,8 +80,10 @@ public: * grid gets rebuilt automatically. */ virtual void Attach(const PointKernel& rclM); /** Rebuilds the grid structure. */ - virtual void Rebuild(unsigned long ulPerGrid = POINTS_CT_GRID, - unsigned long ulMaxGrid = POINTS_MAX_GRIDS); + virtual void Rebuild( + unsigned long ulPerGrid = POINTS_CT_GRID, + unsigned long ulMaxGrid = POINTS_MAX_GRIDS + ); /** Rebuilds the grid structure. */ virtual void Rebuild(int iCtGridPerAxis = POINTS_CT_GRID_PER_AXIS); /** Rebuilds the grid structure. */ @@ -90,18 +92,24 @@ public: /** @name Search */ //@{ /** Searches for elements lying in the intersection area of the grid and the bounding box. */ - virtual unsigned long InSide(const Base::BoundBox3d& rclBB, - std::vector& raulElements, - bool bDelDoubles = true) const; + virtual unsigned long InSide( + const Base::BoundBox3d& rclBB, + std::vector& raulElements, + bool bDelDoubles = true + ) const; /** Searches for elements lying in the intersection area of the grid and the bounding box. */ - virtual unsigned long InSide(const Base::BoundBox3d& rclBB, - std::set& raulElementss) const; + virtual unsigned long InSide( + const Base::BoundBox3d& rclBB, + std::set& raulElementss + ) const; /** Searches for elements lying in the intersection area of the grid and the bounding box. */ - virtual unsigned long InSide(const Base::BoundBox3d& rclBB, - std::vector& raulElements, - const Base::Vector3d& rclOrg, - double fMaxDist, - bool bDelDoubles = true) const; + virtual unsigned long InSide( + const Base::BoundBox3d& rclBB, + std::vector& raulElements, + const Base::Vector3d& rclOrg, + double fMaxDist, + bool bDelDoubles = true + ) const; /** Searches for the nearest grids that contain elements from a point, the result are grid * indices. */ void SearchNearestFromPoint(const Base::Vector3d& rclPt, std::set& rclInd) const; @@ -125,8 +133,7 @@ public: /** @name Boundings */ //@{ /** Returns the bounding box of a given grid element. */ - inline Base::BoundBox3d - GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const; + inline Base::BoundBox3d GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const; /** Returns the bounding box of the whole. */ inline Base::BoundBox3d GetBoundBox() const; //@} @@ -136,8 +143,7 @@ public: return _aulGrid[ulX][ulY][ulZ].size(); } /** Finds all points that lie in the same grid as the point \a rclPoint. */ - unsigned long FindElements(const Base::Vector3d& rclPoint, - std::set& aulElements) const; + unsigned long FindElements(const Base::Vector3d& rclPoint, std::set& aulElements) const; /** Validates the grid structure and rebuilds it if needed. */ virtual void Validate(const PointKernel& rclM); /** Validates the grid structure and rebuilds it if needed. */ @@ -146,15 +152,19 @@ public: virtual bool Verify() const; /** Returns the indices of the grid this point lies in. If the point is outside the grid then * the indices of the nearest grid element are taken.*/ - virtual void Position(const Base::Vector3d& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + virtual void Position( + const Base::Vector3d& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; /** Returns the indices of the elements in the given grid. */ - unsigned long GetElements(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - std::set& raclInd) const; + unsigned long GetElements( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + std::set& raclInd + ) const; protected: /** Checks if this is a valid grid position. */ @@ -176,15 +186,17 @@ protected: } /** Get the indices of all elements lying in the grids around a given grid with distance \a * ulDistance. */ - void GetHull(unsigned long ulX, - unsigned long ulY, - unsigned long ulZ, - unsigned long ulDistance, - std::set& raclInd) const; + void GetHull( + unsigned long ulX, + unsigned long ulY, + unsigned long ulZ, + unsigned long ulDistance, + std::set& raclInd + ) const; private: - std::vector>>> - _aulGrid; /**< Grid data structure. */ + std::vector>>> _aulGrid; /**< Grid data + structure. */ const PointKernel* _pclPoints; /**< The point kernel. */ unsigned long _ulCtElements; /**< Number of grid elements for validation issues. */ unsigned long _ulCtGridsX; /**< Number of grid elements in z. */ @@ -207,10 +219,12 @@ protected: * ulPtIndex the corresponding index in the point kernel. */ void AddPoint(const Base::Vector3d& rclPt, unsigned long ulPtIndex, float fEpsilon = 0.0F); /** Returns the grid numbers to the given point \a rclPoint. */ - void Pos(const Base::Vector3d& rclPoint, - unsigned long& rulX, - unsigned long& rulY, - unsigned long& rulZ) const; + void Pos( + const Base::Vector3d& rclPoint, + unsigned long& rulX, + unsigned long& rulY, + unsigned long& rulZ + ) const; }; /** @@ -230,9 +244,11 @@ public: /** Returns indices of the elements in the current grid. */ void GetElements(std::vector& raulElements) const { - raulElements.insert(raulElements.end(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), - _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end()); + raulElements.insert( + raulElements.end(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].begin(), + _rclGrid._aulGrid[_ulX][_ulY][_ulZ].end() + ); } /** @name Iteration */ //@{ @@ -268,14 +284,18 @@ public: /** @name Tests with rays */ //@{ /** Searches for facets around the ray. */ - bool InitOnRay(const Base::Vector3d& rclPt, - const Base::Vector3d& rclDir, - std::vector& raulElements); + bool InitOnRay( + const Base::Vector3d& rclPt, + const Base::Vector3d& rclDir, + std::vector& raulElements + ); /** Searches for facets around the ray. */ - bool InitOnRay(const Base::Vector3d& rclPt, - const Base::Vector3d& rclDir, - float fMaxSearchArea, - std::vector& raulElements); + bool InitOnRay( + const Base::Vector3d& rclPt, + const Base::Vector3d& rclDir, + float fMaxSearchArea, + std::vector& raulElements + ); /** Searches for facets around the ray. */ bool NextOnRay(std::vector& raulElements); //@} @@ -328,8 +348,7 @@ private: // -------------------------------------------------------------- -inline Base::BoundBox3d -PointsGrid::GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const +inline Base::BoundBox3d PointsGrid::GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const { double fX = _fMinX + (double(ulX) * _fGridLenX); double fY = _fMinY + (double(ulY) * _fGridLenY); @@ -340,12 +359,14 @@ PointsGrid::GetBoundBox(unsigned long ulX, unsigned long ulY, unsigned long ulZ) inline Base::BoundBox3d PointsGrid::GetBoundBox() const { - return Base::BoundBox3d(_fMinX, - _fMinY, - _fMinZ, - _fMinX + (_fGridLenX * double(_ulCtGridsX)), - _fMinY + (_fGridLenY * double(_ulCtGridsY)), - _fMinZ + (_fGridLenZ * double(_ulCtGridsZ))); + return Base::BoundBox3d( + _fMinX, + _fMinY, + _fMinZ, + _fMinX + (_fGridLenX * double(_ulCtGridsX)), + _fMinY + (_fGridLenY * double(_ulCtGridsY)), + _fMinZ + (_fGridLenZ * double(_ulCtGridsZ)) + ); } inline bool PointsGrid::CheckPos(unsigned long ulX, unsigned long ulY, unsigned long ulZ) const diff --git a/src/Mod/Points/App/PointsPyImp.cpp b/src/Mod/Points/App/PointsPyImp.cpp index 4b9fd737a9..07c719d78f 100644 --- a/src/Mod/Points/App/PointsPyImp.cpp +++ b/src/Mod/Points/App/PointsPyImp.cpp @@ -179,10 +179,12 @@ PyObject* PointsPy::addPoints(PyObject* args) } } catch (const Py::Exception&) { - PyErr_SetString(PyExc_TypeError, - "either expect\n" - "-- [Vector,...] \n" - "-- [(x,y,z),...]"); + PyErr_SetString( + PyExc_TypeError, + "either expect\n" + "-- [Vector,...] \n" + "-- [(x,y,z),...]" + ); return nullptr; } diff --git a/src/Mod/Points/App/Properties.cpp b/src/Mod/Points/App/Properties.cpp index 623bd95946..d8901589cb 100644 --- a/src/Mod/Points/App/Properties.cpp +++ b/src/Mod/Points/App/Properties.cpp @@ -39,7 +39,7 @@ #include "Properties.h" #ifdef _MSC_VER -#include +# include #endif @@ -384,11 +384,9 @@ void PropertyNormalList::transformGeometry(const Base::Matrix4D& mat) // Rotate the normal vectors #ifdef _MSC_VER - Concurrency::parallel_for_each(_lValueList.begin(), - _lValueList.end(), - [rot](Base::Vector3f& value) { - value = rot * value; - }); + Concurrency::parallel_for_each(_lValueList.begin(), _lValueList.end(), [rot](Base::Vector3f& value) { + value = rot * value; + }); #else QtConcurrent::blockingMap(_lValueList, [rot](Base::Vector3f& value) { rot.multVec(value, value); @@ -415,8 +413,7 @@ void PropertyNormalList::removeIndices(const std::vector& uIndice remainValue.reserve(rValueList.size() - uSortedInds.size()); std::vector::iterator pos = uSortedInds.begin(); - for (std::vector::const_iterator it = rValueList.begin(); - it != rValueList.end(); + for (std::vector::const_iterator it = rValueList.begin(); it != rValueList.end(); ++it) { unsigned long index = it - rValueList.begin(); if (pos == uSortedInds.end()) { @@ -545,8 +542,7 @@ void PropertyCurvatureList::removeIndices(const std::vector& uInd remainValue.reserve(_lValueList.size() - uSortedInds.size()); std::vector::iterator pos = uSortedInds.begin(); - for (std::vector::const_iterator it = _lValueList.begin(); - it != _lValueList.end(); + for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { unsigned long index = it - _lValueList.begin(); if (pos == uSortedInds.end()) { diff --git a/src/Mod/Points/App/Tools.h b/src/Mod/Points/App/Tools.h index 60e1e4d244..ab6087cfc2 100644 --- a/src/Mod/Points/App/Tools.h +++ b/src/Mod/Points/App/Tools.h @@ -31,9 +31,11 @@ namespace Points { template -bool copyProperty(App::DocumentObject* target, - std::vector source, - const char* propertyName) +bool copyProperty( + App::DocumentObject* target, + std::vector source, + const char* propertyName +) { // check for properties if (std::all_of(std::begin(source), std::end(source), [=](auto obj) { @@ -41,7 +43,8 @@ bool copyProperty(App::DocumentObject* target, })) { auto target_prop = freecad_cast( - target->addDynamicProperty(PropertyT::getClassTypeId().getName(), propertyName)); + target->addDynamicProperty(PropertyT::getClassTypeId().getName(), propertyName) + ); if (target_prop) { auto values = target_prop->getValues(); for (auto it : source) { diff --git a/src/Mod/Points/Gui/AppPointsGui.cpp b/src/Mod/Points/Gui/AppPointsGui.cpp index 54eae65add..7455d73747 100644 --- a/src/Mod/Points/Gui/AppPointsGui.cpp +++ b/src/Mod/Points/Gui/AppPointsGui.cpp @@ -95,8 +95,10 @@ PyMOD_INIT_FUNC(PointsGui) PointsGui::ViewProviderPython ::init(); PointsGui::Workbench ::init(); // clang-format on - Gui::ViewProviderBuilder::add(Points::PropertyPointKernel::getClassTypeId(), - PointsGui::ViewProviderPoints::getClassTypeId()); + Gui::ViewProviderBuilder::add( + Points::PropertyPointKernel::getClassTypeId(), + PointsGui::ViewProviderPoints::getClassTypeId() + ); // add resources and reloads the translators loadPointsResource(); diff --git a/src/Mod/Points/Gui/Command.cpp b/src/Mod/Points/Gui/Command.cpp index 54fa174cea..4e0c714dd0 100644 --- a/src/Mod/Points/Gui/Command.cpp +++ b/src/Mod/Points/Gui/Command.cpp @@ -82,7 +82,8 @@ void CmdPointsImport::activated(int iMsg) QString(), QString(), QStringLiteral("%1 (*.asc *.pcd *.ply *.e57);;%2 (*.*)") - .arg(QObject::tr("Point formats"), QObject::tr("All Files"))); + .arg(QObject::tr("Point formats"), QObject::tr("All Files")) + ); if (fn.isEmpty()) { return; } @@ -92,10 +93,7 @@ void CmdPointsImport::activated(int iMsg) App::Document* doc = getActiveDocument(); openCommand(QT_TRANSLATE_NOOP("Command", "Import points")); addModule(Command::App, "Points"); - doCommand(Command::Doc, - "Points.insert(\"%s\", \"%s\")", - fn.toUtf8().data(), - doc->getName()); + doCommand(Command::Doc, "Points.insert(\"%s\", \"%s\")", fn.toUtf8().data(), doc->getName()); commitCommand(); updateActive(); @@ -114,9 +112,12 @@ void CmdPointsImport::activated(int iMsg) QMessageBox msgBox(Gui::getMainWindow()); msgBox.setIcon(QMessageBox::Question); msgBox.setWindowTitle(QObject::tr("Points not at Origin")); - msgBox.setText(QObject::tr( - "The bounding box of the imported points does not contain the origin. " - "Translate it to the origin?")); + msgBox.setText( + QObject::tr( + "The bounding box of the imported points does not contain the origin. " + "Translate it to the origin?" + ) + ); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); auto ret = msgBox.exec(); @@ -160,25 +161,29 @@ void CmdPointsExport::activated(int iMsg) Q_UNUSED(iMsg); addModule(Command::App, "Points"); - std::vector points = - getSelection().getObjectsOfType(Points::Feature::getClassTypeId()); + std::vector points = getSelection().getObjectsOfType( + Points::Feature::getClassTypeId() + ); for (auto point : points) { QString fn = Gui::FileDialog::getSaveFileName( Gui::getMainWindow(), QString(), QString(), QStringLiteral("%1 (*.asc *.pcd *.ply);;%2 (*.*)") - .arg(QObject::tr("Point formats"), QObject::tr("All Files"))); + .arg(QObject::tr("Point formats"), QObject::tr("All Files")) + ); if (fn.isEmpty()) { break; } if (!fn.isEmpty()) { fn = Base::Tools::escapeEncodeFilename(fn); - doCommand(Command::Doc, - "Points.export([App.ActiveDocument.%s], \"%s\")", - point->getNameInDocument(), - fn.toUtf8().data()); + doCommand( + Command::Doc, + "Points.export([App.ActiveDocument.%s], \"%s\")", + point->getNameInDocument(), + fn.toUtf8().data() + ); } } } @@ -210,19 +215,21 @@ void CmdPointsConvert::activated(int iMsg) int decimals = Base::UnitsApi::getDecimals(); double tolerance_from_decimals = pow(10., -decimals); - double minimal_tolerance = - tolerance_from_decimals < STD_OCC_TOLERANCE ? STD_OCC_TOLERANCE : tolerance_from_decimals; + double minimal_tolerance = tolerance_from_decimals < STD_OCC_TOLERANCE ? STD_OCC_TOLERANCE + : tolerance_from_decimals; bool ok; - double tol = QInputDialog::getDouble(Gui::getMainWindow(), - QObject::tr("Distance"), - QObject::tr("Enter maximum distance:"), - 0.1, - minimal_tolerance, - 10.0, - decimals, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + double tol = QInputDialog::getDouble( + Gui::getMainWindow(), + QObject::tr("Distance"), + QObject::tr("Enter maximum distance:"), + 0.1, + minimal_tolerance, + 10.0, + decimals, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (!ok) { return; } @@ -247,8 +254,7 @@ void CmdPointsConvert::activated(int iMsg) } Py::Module commands(module, true); - commands.callMemberFunction("make_points_from_geometry", - Py::TupleN(list, Py::Float(tol))); + commands.callMemberFunction("make_points_from_geometry", Py::TupleN(list, Py::Float(tol))); return true; } @@ -294,10 +300,10 @@ void CmdPointsPolyCut::activated(int iMsg) { Q_UNUSED(iMsg); - std::vector docObj = - Gui::Selection().getObjectsOfType(Points::Feature::getClassTypeId()); - for (std::vector::iterator it = docObj.begin(); it != docObj.end(); - ++it) { + std::vector docObj = Gui::Selection().getObjectsOfType( + Points::Feature::getClassTypeId() + ); + for (std::vector::iterator it = docObj.begin(); it != docObj.end(); ++it) { if (it == docObj.begin()) { Gui::Document* doc = getActiveGuiDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -305,8 +311,10 @@ void CmdPointsPolyCut::activated(int iMsg) Gui::View3DInventorViewer* viewer = ((Gui::View3DInventor*)view)->getViewer(); viewer->setEditing(true); viewer->startSelection(Gui::View3DInventorViewer::Lasso); - viewer->addEventCallback(SoMouseButtonEvent::getClassTypeId(), - PointsGui::ViewProviderPoints::clipPointsCallback); + viewer->addEventCallback( + SoMouseButtonEvent::getClassTypeId(), + PointsGui::ViewProviderPoints::clipPointsCallback + ); } else { return; @@ -347,8 +355,9 @@ void CmdPointsMerge::activated(int iMsg) Points::Feature* pts = doc->addObject("Merged Points"); Points::PointKernel* kernel = pts->Points.startEditing(); - std::vector docObj = - Gui::Selection().getObjectsOfType(Points::Feature::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Points::Feature::getClassTypeId() + ); for (auto it : docObj) { const Points::PointKernel& k = static_cast(it)->Points.getValue(); std::size_t numPts = kernel->size(); @@ -373,7 +382,8 @@ void CmdPointsMerge::activated(int iMsg) } if (auto vp = dynamic_cast( - Gui::Application::Instance->getViewProvider(pts))) { + Gui::Application::Instance->getViewProvider(pts) + )) { vp->DisplayMode.setValue(displayMode.c_str()); } @@ -407,8 +417,9 @@ void CmdPointsStructure::activated(int iMsg) App::Document* doc = App::GetApplication().getActiveDocument(); doc->openTransaction("Structure point cloud"); - std::vector docObj = - Gui::Selection().getObjectsOfType(Points::Feature::getClassTypeId()); + std::vector docObj = Gui::Selection().getObjectsOfType( + Points::Feature::getClassTypeId() + ); for (auto it : docObj) { std::string name = it->Label.getValue(); name += " (Structured)"; @@ -458,8 +469,7 @@ void CmdPointsStructure::activated(int iMsg) // Pre-fill the vector with points and afterwards replace them // with valid point coordinates double nan = std::numeric_limits::quiet_NaN(); - std::vector sortedPoints(width_l * height_l, - Base::Vector3d(nan, nan, nan)); + std::vector sortedPoints(width_l * height_l, Base::Vector3d(nan, nan, nan)); for (std::size_t i = 0; i < k.size(); ++i) { Base::Vector3d pnt = k.getPoint(i); diff --git a/src/Mod/Points/Gui/DlgPointsReadImp.h b/src/Mod/Points/Gui/DlgPointsReadImp.h index e621b83895..5b648b337f 100644 --- a/src/Mod/Points/Gui/DlgPointsReadImp.h +++ b/src/Mod/Points/Gui/DlgPointsReadImp.h @@ -42,9 +42,11 @@ class DlgPointsReadImp: public QDialog Q_OBJECT public: - explicit DlgPointsReadImp(const char* FileName, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit DlgPointsReadImp( + const char* FileName, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~DlgPointsReadImp() override; private: diff --git a/src/Mod/Points/Gui/ViewProvider.cpp b/src/Mod/Points/Gui/ViewProvider.cpp index dd8b9820e2..c0c6cc4ead 100644 --- a/src/Mod/Points/Gui/ViewProvider.cpp +++ b/src/Mod/Points/Gui/ViewProvider.cpp @@ -102,8 +102,8 @@ void ViewProviderPoints::onChanged(const App::Property* prop) pcPointStyle->pointSize = PointSize.getValue(); } else if (prop == &SelectionStyle) { - pcHighlight->style = - SelectionStyle.getValue() ? Gui::SoFCSelection::BOX : Gui::SoFCSelection::EMISSIVE; + pcHighlight->style = SelectionStyle.getValue() ? Gui::SoFCSelection::BOX + : Gui::SoFCSelection::EMISSIVE; } else { ViewProviderGeometryObject::onChanged(prop); @@ -172,7 +172,8 @@ void ViewProviderPoints::setDisplayMode(const char* ModeName) "ViewProviderPoints::setDisplayMode", "The number of points (%d) doesn't match with the number of colors (%d).", numPoints, - colors->getSize()); + colors->getSize() + ); #endif // fallback setDisplayMaskMode("Point"); @@ -191,15 +192,17 @@ void ViewProviderPoints::setDisplayMode(const char* ModeName) for (const auto& it : Map) { Base::Type type = it.second->getTypeId(); if (type == Points::PropertyGreyValueList::getClassTypeId()) { - Points::PropertyGreyValueList* greyValues = - static_cast(it.second); + Points::PropertyGreyValueList* greyValues + = static_cast(it.second); if (numPoints != greyValues->getSize()) { #ifdef FC_DEBUG - SoDebugError::postWarning("ViewProviderPoints::setDisplayMode", - "The number of points (%d) doesn't match with the " - "number of grey values (%d).", - numPoints, - greyValues->getSize()); + SoDebugError::postWarning( + "ViewProviderPoints::setDisplayMode", + "The number of points (%d) doesn't match with the " + "number of grey values (%d).", + numPoints, + greyValues->getSize() + ); #endif // Intensity mode is not possible then set the default () mode instead. setDisplayMaskMode("Point"); @@ -218,15 +221,17 @@ void ViewProviderPoints::setDisplayMode(const char* ModeName) for (const auto& it : Map) { Base::Type type = it.second->getTypeId(); if (type == Points::PropertyNormalList::getClassTypeId()) { - Points::PropertyNormalList* normals = - static_cast(it.second); + Points::PropertyNormalList* normals = static_cast( + it.second + ); if (numPoints != normals->getSize()) { #ifdef FC_DEBUG SoDebugError::postWarning( "ViewProviderPoints::setDisplayMode", "The number of points (%d) doesn't match with the number of normals (%d).", numPoints, - normals->getSize()); + normals->getSize() + ); #endif // fallback setDisplayMaskMode("Point"); @@ -265,8 +270,7 @@ std::vector ViewProviderPoints::getDisplayModes() const std::map Map; pcObject->getPropertyMap(Map); - for (std::map::iterator it = Map.begin(); it != Map.end(); - ++it) { + for (std::map::iterator it = Map.begin(); it != Map.end(); ++it) { Base::Type type = it->second->getTypeId(); if (type == Points::PropertyNormalList::getClassTypeId()) { StrList.push_back("Shaded"); @@ -348,8 +352,9 @@ void ViewProviderPoints::clipPointsCallback(void*, SoEventCallback* n) clPoly.push_back(clPoly.front()); } - std::vector views = - view->getViewProvidersOfType(ViewProviderPoints::getClassTypeId()); + std::vector views = view->getViewProvidersOfType( + ViewProviderPoints::getClassTypeId() + ); for (auto it : views) { ViewProviderPoints* that = static_cast(it); if (that->getEditingMode() > -1) { @@ -443,8 +448,7 @@ void ViewProviderScattered::updateData(const App::Property* prop) } } -void ViewProviderScattered::cut(const std::vector& picked, - Gui::View3DInventorViewer& Viewer) +void ViewProviderScattered::cut(const std::vector& picked, Gui::View3DInventorViewer& Viewer) { // create the polygon from the picked points Base::Polygon2d cPoly; @@ -464,8 +468,7 @@ void ViewProviderScattered::cut(const std::vector& picked, removeIndices.reserve(points.size()); unsigned long index = 0; - for (Points::PointKernel::const_iterator jt = points.begin(); jt != points.end(); - ++jt, ++index) { + for (Points::PointKernel::const_iterator jt = points.begin(); jt != points.end(); ++jt, ++index) { SbVec3f pt(jt->x, jt->y, jt->z); // project from 3d to 2d @@ -481,7 +484,8 @@ void ViewProviderScattered::cut(const std::vector& picked, // Remove the points from the cloud and open a transaction object for the undo/redo stuff Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Cut points")); + QT_TRANSLATE_NOOP("Command", "Cut points") + ); // sets the points outside the polygon to update the Inventor node fea->Points.removeIndices(removeIndices); @@ -499,8 +503,8 @@ void ViewProviderScattered::cut(const std::vector& picked, } else if (type == App::PropertyColorList::getClassTypeId()) { // static_cast(it->second)->removeIndices(removeIndices); - const std::vector& colors = - static_cast(it.second)->getValues(); + const std::vector& colors + = static_cast(it.second)->getValues(); if (removeIndices.size() > colors.size()) { break; @@ -606,8 +610,7 @@ void ViewProviderStructured::updateData(const App::Property* prop) } } -void ViewProviderStructured::cut(const std::vector& picked, - Gui::View3DInventorViewer& Viewer) +void ViewProviderStructured::cut(const std::vector& picked, Gui::View3DInventorViewer& Viewer) { // create the polygon from the picked points Base::Polygon2d cPoly; @@ -649,7 +652,8 @@ void ViewProviderStructured::cut(const std::vector& picked, if (invalidatePoints) { // Remove the points from the cloud and open a transaction object for the undo/redo stuff Gui::Application::Instance->activeDocument()->openCommand( - QT_TRANSLATE_NOOP("Command", "Cut points")); + QT_TRANSLATE_NOOP("Command", "Cut points") + ); // sets the points outside the polygon to update the Inventor node fea->Points.setValue(newKernel); @@ -674,8 +678,7 @@ template class PointsGuiExport ViewProviderFeaturePythonT& nodes) const +void ViewProviderPointsBuilder::buildNodes(const App::Property* prop, std::vector& nodes) const { SoCoordinate3* pcPointsCoord = nullptr; SoPointSet* pcPoints = nullptr; @@ -700,12 +703,15 @@ void ViewProviderPointsBuilder::buildNodes(const App::Property* prop, } } -void ViewProviderPointsBuilder::createPoints(const App::Property* prop, - SoCoordinate3* coords, - SoPointSet* points) const +void ViewProviderPointsBuilder::createPoints( + const App::Property* prop, + SoCoordinate3* coords, + SoPointSet* points +) const { - const Points::PropertyPointKernel* prop_points = - static_cast(prop); + const Points::PropertyPointKernel* prop_points = static_cast( + prop + ); const Points::PointKernel& cPts = prop_points->getValue(); coords->point.setNum(cPts.size()); @@ -724,12 +730,15 @@ void ViewProviderPointsBuilder::createPoints(const App::Property* prop, coords->point.finishEditing(); } -void ViewProviderPointsBuilder::createPoints(const App::Property* prop, - SoCoordinate3* coords, - SoIndexedPointSet* points) const +void ViewProviderPointsBuilder::createPoints( + const App::Property* prop, + SoCoordinate3* coords, + SoIndexedPointSet* points +) const { - const Points::PropertyPointKernel* prop_points = - static_cast(prop); + const Points::PropertyPointKernel* prop_points = static_cast( + prop + ); const Points::PointKernel& cPts = prop_points->getValue(); coords->point.setNum(cPts.size()); @@ -745,8 +754,7 @@ void ViewProviderPointsBuilder::createPoints(const App::Property* prop, ++it, idx++) { vec[idx].setValue(it->x, it->y, it->z); // valid point? - if (!(boost::math::isnan(it->x) || boost::math::isnan(it->y) - || boost::math::isnan(it->z))) { + if (!(boost::math::isnan(it->x) || boost::math::isnan(it->y) || boost::math::isnan(it->z))) { indices.push_back(idx); } } diff --git a/src/Mod/Points/PointsGlobal.h b/src/Mod/Points/PointsGlobal.h index 969fed20b8..acca989228 100644 --- a/src/Mod/Points/PointsGlobal.h +++ b/src/Mod/Points/PointsGlobal.h @@ -25,25 +25,25 @@ #include #ifndef POINTS_GLOBAL_H -#define POINTS_GLOBAL_H +# define POINTS_GLOBAL_H // Points -#ifndef PointsExport -#ifdef Points_EXPORTS -#define PointsExport FREECAD_DECL_EXPORT -#else -#define PointsExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PointsExport +# ifdef Points_EXPORTS +# define PointsExport FREECAD_DECL_EXPORT +# else +# define PointsExport FREECAD_DECL_IMPORT +# endif +# endif // PointsGui -#ifndef PointsGuiExport -#ifdef PointsGui_EXPORTS -#define PointsGuiExport FREECAD_DECL_EXPORT -#else -#define PointsGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef PointsGuiExport +# ifdef PointsGui_EXPORTS +# define PointsGuiExport FREECAD_DECL_EXPORT +# else +# define PointsGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // POINTS_GLOBAL_H diff --git a/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp b/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp index 699ab07e5d..a13b122818 100644 --- a/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp +++ b/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp @@ -35,9 +35,9 @@ #include #include #if defined(HAVE_PCL_FILTERS) -#include -#include -#include +# include +# include +# include #endif #include "ApproxSurface.h" diff --git a/src/Mod/ReverseEngineering/App/ApproxSurface.cpp b/src/Mod/ReverseEngineering/App/ApproxSurface.cpp index d11fabc947..fad3dc567f 100644 --- a/src/Mod/ReverseEngineering/App/ApproxSurface.cpp +++ b/src/Mod/ReverseEngineering/App/ApproxSurface.cpp @@ -48,10 +48,12 @@ SplineBasisfunction::SplineBasisfunction(int iSize) , _iOrder(1) {} -SplineBasisfunction::SplineBasisfunction(TColStd_Array1OfReal& vKnots, - TColStd_Array1OfInteger& vMults, - int iSize, - int iOrder) +SplineBasisfunction::SplineBasisfunction( + TColStd_Array1OfReal& vKnots, + TColStd_Array1OfInteger& vMults, + int iSize, + int iOrder +) : _vKnotVector(0, iSize - 1) { int sum = 0; @@ -94,9 +96,7 @@ void SplineBasisfunction::SetKnots(TColStd_Array1OfReal& vKnots, int iOrder) _iOrder = iOrder; } -void SplineBasisfunction::SetKnots(TColStd_Array1OfReal& vKnots, - TColStd_Array1OfInteger& vMults, - int iOrder) +void SplineBasisfunction::SetKnots(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iOrder) { int sum = 0; for (int h = vMults.Lower(); h <= vMults.Upper(); h++) { @@ -124,10 +124,12 @@ BSplineBasis::BSplineBasis(int iSize) : SplineBasisfunction(iSize) {} -BSplineBasis::BSplineBasis(TColStd_Array1OfReal& vKnots, - TColStd_Array1OfInteger& vMults, - int iSize, - int iOrder) +BSplineBasis::BSplineBasis( + TColStd_Array1OfReal& vKnots, + TColStd_Array1OfInteger& vMults, + int iSize, + int iOrder +) : SplineBasisfunction(vKnots, vMults, iSize, iOrder) {} @@ -257,10 +259,12 @@ double BSplineBasis::BasisFunction(int iIndex, double fParam) return N(0); } -void BSplineBasis::DerivativesOfBasisFunction(int iIndex, - int iMaxDer, - double fParam, - TColStd_Array1OfReal& Derivat) +void BSplineBasis::DerivativesOfBasisFunction( + int iIndex, + int iMaxDer, + double fParam, + TColStd_Array1OfReal& Derivat +) { int iMax = iMaxDer; if (Derivat.Length() != iMax + 1) { @@ -482,8 +486,7 @@ double BSplineBasis::GetIntegralOfProductOfBSplines(int iIdx1, int iIdx2, int iO return dIntegral; } -void BSplineBasis::GenerateRootsAndWeights(TColStd_Array1OfReal& vRoots, - TColStd_Array1OfReal& vWeights) +void BSplineBasis::GenerateRootsAndWeights(TColStd_Array1OfReal& vRoots, TColStd_Array1OfReal& vWeights) { int iSize = vRoots.Length(); @@ -635,10 +638,12 @@ int BSplineBasis::CalcSize(int r, int s) /////////////////// ParameterCorrection -ParameterCorrection::ParameterCorrection(unsigned usUOrder, - unsigned usVOrder, - unsigned usUCtrlpoints, - unsigned usVCtrlpoints) +ParameterCorrection::ParameterCorrection( + unsigned usUOrder, + unsigned usVOrder, + unsigned usUCtrlpoints, + unsigned usVCtrlpoints +) : _usUOrder(usUOrder) , _usVOrder(usVOrder) , _usUCtrlpoints(usUCtrlpoints) @@ -768,9 +773,7 @@ void ParameterCorrection::SetUV(const Base::Vector3d& clU, const Base::Vector3d& } } -void ParameterCorrection::GetUVW(Base::Vector3d& clU, - Base::Vector3d& clV, - Base::Vector3d& clW) const +void ParameterCorrection::GetUVW(Base::Vector3d& clU, Base::Vector3d& clV, Base::Vector3d& clW) const { clU = _clU; clV = _clV; @@ -807,10 +810,12 @@ void ParameterCorrection::ProjectControlPointsOnPlane() } } -Handle(Geom_BSplineSurface) ParameterCorrection::CreateSurface(const TColgp_Array1OfPnt& points, - int iIter, - bool bParaCor, - double fSizeFactor) +Handle(Geom_BSplineSurface) ParameterCorrection::CreateSurface( + const TColgp_Array1OfPnt& points, + int iIter, + bool bParaCor, + double fSizeFactor +) { if (_pvcPoints) { delete _pvcPoints; @@ -844,13 +849,15 @@ Handle(Geom_BSplineSurface) ParameterCorrection::CreateSurface(const TColgp_Arra DoParameterCorrection(iIter); } - return new Geom_BSplineSurface(_vCtrlPntsOfSurf, - _vUKnots, - _vVKnots, - _vUMults, - _vVMults, - _usUOrder - 1, - _usVOrder - 1); + return new Geom_BSplineSurface( + _vCtrlPntsOfSurf, + _vUKnots, + _vVKnots, + _vUMults, + _vVMults, + _usUOrder - 1, + _usVOrder - 1 + ); } void ParameterCorrection::EnableSmoothing(bool bSmooth, double fSmoothInfl) @@ -862,10 +869,12 @@ void ParameterCorrection::EnableSmoothing(bool bSmooth, double fSmoothInfl) /////////////////// BSplineParameterCorrection -BSplineParameterCorrection::BSplineParameterCorrection(unsigned usUOrder, - unsigned usVOrder, - unsigned usUCtrlpoints, - unsigned usVCtrlpoints) +BSplineParameterCorrection::BSplineParameterCorrection( + unsigned usUOrder, + unsigned usVOrder, + unsigned usUCtrlpoints, + unsigned usVCtrlpoints +) : ParameterCorrection(usUOrder, usVOrder, usUCtrlpoints, usVCtrlpoints) , _clUSpline(usUCtrlpoints + usUOrder) , _clVSpline(usVCtrlpoints + usVOrder) @@ -963,21 +972,24 @@ void BSplineParameterCorrection::DoParameterCorrection(int iIter) double fMaxDiff = 0.0, fMaxScalar = 1.0; double fWeight = _fSmoothInfluence; - Base::SequencerLauncher seq("Calc surface...", - static_cast(iIter) - * static_cast(_pvcPoints->Length())); + Base::SequencerLauncher seq( + "Calc surface...", + static_cast(iIter) * static_cast(_pvcPoints->Length()) + ); do { fMaxScalar = 1.0; fMaxDiff = 0.0; - Handle(Geom_BSplineSurface) pclBSplineSurf = new Geom_BSplineSurface(_vCtrlPntsOfSurf, - _vUKnots, - _vVKnots, - _vUMults, - _vVMults, - _usUOrder - 1, - _usVOrder - 1); + Handle(Geom_BSplineSurface) pclBSplineSurf = new Geom_BSplineSurface( + _vCtrlPntsOfSurf, + _vUKnots, + _vVKnots, + _vUMults, + _vVMults, + _usUOrder - 1, + _usVOrder - 1 + ); for (int ii = _pvcPoints->Lower(); ii <= _pvcPoints->Upper(); ii++) { double fDeltaU, fDeltaV, fU, fV; @@ -1203,8 +1215,8 @@ bool BSplineParameterCorrection::SolveWithSmoothing(double fWeight) std::generate(columns.begin(), columns.end(), Base::iotaGen(0)); ScalarProduct scalar(M); // NOLINTBEGIN - QFuture> future = - QtConcurrent::mapped(columns, std::bind(&ScalarProduct::multiply, &scalar, sp::_1)); + QFuture> future + = QtConcurrent::mapped(columns, std::bind(&ScalarProduct::multiply, &scalar, sp::_1)); // NOLINTEND QFutureWatcher> watcher; watcher.setFuture(future); @@ -1214,8 +1226,7 @@ bool BSplineParameterCorrection::SolveWithSmoothing(double fWeight) int rowIndex = 0; for (const auto& it : future) { int colIndex = 0; - for (std::vector::const_iterator jt = it.begin(); jt != it.end(); - ++jt, colIndex++) { + for (std::vector::const_iterator jt = it.begin(); jt != it.end(); ++jt, colIndex++) { MTM(rowIndex, colIndex) = *jt; } rowIndex++; @@ -1267,17 +1278,15 @@ bool BSplineParameterCorrection::SolveWithSmoothing(double fWeight) return true; } -void BSplineParameterCorrection::CalcSmoothingTerms(bool bRecalc, - double fFirst, - double fSecond, - double fThird) +void BSplineParameterCorrection::CalcSmoothingTerms(bool bRecalc, double fFirst, double fSecond, double fThird) { if (bRecalc) { - Base::SequencerLauncher seq("Initializing...", - static_cast(3) * static_cast(_usUCtrlpoints) - * static_cast(_usUCtrlpoints) - * static_cast(_usVCtrlpoints) - * static_cast(_usVCtrlpoints)); + Base::SequencerLauncher seq( + "Initializing...", + static_cast(3) * static_cast(_usUCtrlpoints) + * static_cast(_usUCtrlpoints) * static_cast(_usVCtrlpoints) + * static_cast(_usVCtrlpoints) + ); CalcFirstSmoothMatrix(seq); CalcSecondSmoothMatrix(seq); CalcThirdSmoothMatrix(seq); @@ -1371,11 +1380,13 @@ void BSplineParameterCorrection::EnableSmoothing(bool bSmooth, double fSmoothInf EnableSmoothing(bSmooth, fSmoothInfl, 1.0, 0.0, 0.0); } -void BSplineParameterCorrection::EnableSmoothing(bool bSmooth, - double fSmoothInfl, - double fFirst, - double fSec, - double fThird) +void BSplineParameterCorrection::EnableSmoothing( + bool bSmooth, + double fSmoothInfl, + double fFirst, + double fSec, + double fThird +) { if (_bSmoothing && bSmooth) { CalcSmoothingTerms(false, fFirst, fSec, fThird); diff --git a/src/Mod/ReverseEngineering/App/ApproxSurface.h b/src/Mod/ReverseEngineering/App/ApproxSurface.h index 2d640c96e1..f588dbb75b 100644 --- a/src/Mod/ReverseEngineering/App/ApproxSurface.h +++ b/src/Mod/ReverseEngineering/App/ApproxSurface.h @@ -78,10 +78,12 @@ public: * and the sum of the values in @a vMults has to be identical to @a iSize. * @param iOrder Order (degree + 1) of the basic polynomial */ - SplineBasisfunction(TColStd_Array1OfReal& vKnots, - TColStd_Array1OfInteger& vMults, - int iSize, - int iOrder = 1); + SplineBasisfunction( + TColStd_Array1OfReal& vKnots, + TColStd_Array1OfInteger& vMults, + int iSize, + int iOrder = 1 + ); virtual ~SplineBasisfunction(); @@ -115,10 +117,12 @@ public: * * The list must be sufficiently long for iMaxDer+1 elements. */ - virtual void DerivativesOfBasisFunction(int iIndex, - int iMaxDer, - double fParam, - TColStd_Array1OfReal& Derivat) = 0; + virtual void DerivativesOfBasisFunction( + int iIndex, + int iMaxDer, + double fParam, + TColStd_Array1OfReal& Derivat + ) = 0; /** * Calculates the kth derivative at the point fParam @@ -136,8 +140,7 @@ public: * is passed on. Internally, this is converted into a knot vector in the form of (value, 1). * The size of this new vector has to be exactly as big as specified in the constructor. */ - virtual void - SetKnots(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iOrder = 1); + virtual void SetKnots(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iOrder = 1); protected: // Member // Knot vector @@ -172,10 +175,7 @@ public: * sum of the values in @a vMults has to be identical to @a iSize. * @param iOrder Order (degree + 1) of the basic polynomial */ - BSplineBasis(TColStd_Array1OfReal& vKnots, - TColStd_Array1OfInteger& vMults, - int iSize, - int iOrder = 1); + BSplineBasis(TColStd_Array1OfReal& vKnots, TColStd_Array1OfInteger& vMults, int iSize, int iOrder = 1); /** * Specifies the knot index for the parameter value (from: Piegl/Tiller 96 The NURBS-Book) @@ -224,10 +224,12 @@ public: * The list must be sufficiently long for iMaxDer+1 elements. * @return List of function values */ - void DerivativesOfBasisFunction(int iIndex, - int iMaxDer, - double fParam, - TColStd_Array1OfReal& Derivat) override; + void DerivativesOfBasisFunction( + int iIndex, + int iMaxDer, + double fParam, + TColStd_Array1OfReal& Derivat + ) override; /** * Calculates the kth derivative at the point fParam @@ -250,8 +252,10 @@ protected: /** * Calculates the roots of the Legendre-Polynomials and the corresponding weights */ - virtual void GenerateRootsAndWeights(TColStd_Array1OfReal& vAbscissas, - TColStd_Array1OfReal& vWeights); + virtual void GenerateRootsAndWeights( + TColStd_Array1OfReal& vAbscissas, + TColStd_Array1OfReal& vWeights + ); /** * Calculates the limits of integration (Indexes of the knots) @@ -271,10 +275,11 @@ class ReenExport ParameterCorrection public: // Constructor explicit ParameterCorrection( - unsigned usUOrder = 4, // Order in u-direction (order = degree + 1) - unsigned usVOrder = 4, // Order in v-direction - unsigned usUCtrlpoints = 6, // Qty. of the control points in the u-direction - unsigned usVCtrlpoints = 6); // Qty. of the control points in the v-direction + unsigned usUOrder = 4, // Order in u-direction (order = degree + 1) + unsigned usVOrder = 4, // Order in v-direction + unsigned usUCtrlpoints = 6, // Qty. of the control points in the u-direction + unsigned usVCtrlpoints = 6 + ); // Qty. of the control points in the v-direction virtual ~ParameterCorrection() { @@ -327,10 +332,12 @@ public: /** * Calculates a B-spline surface from the given points */ - virtual Handle(Geom_BSplineSurface) CreateSurface(const TColgp_Array1OfPnt& points, - int iIter, - bool bParaCor, - double fSizeFactor = 0.0f); + virtual Handle(Geom_BSplineSurface) CreateSurface( + const TColgp_Array1OfPnt& points, + int iIter, + bool bParaCor, + double fSizeFactor = 0.0f + ); /** * Setting the u/v directions * The third parameter specifies whether the directions should actually be used. @@ -387,10 +394,11 @@ class ReenExport BSplineParameterCorrection: public ParameterCorrection public: // Constructor explicit BSplineParameterCorrection( - unsigned usUOrder = 4, // Order in u-direction (order = degree + 1) - unsigned usVOrder = 4, // Order in the v-direction - unsigned usUCtrlpoints = 6, // Qty. of the control points in u-direction - unsigned usVCtrlpoints = 6); // Qty. of the control points in v-direction + unsigned usUOrder = 4, // Order in u-direction (order = degree + 1) + unsigned usVOrder = 4, // Order in the v-direction + unsigned usUCtrlpoints = 6, // Qty. of the control points in u-direction + unsigned usVCtrlpoints = 6 + ); // Qty. of the control points in v-direction ~BSplineParameterCorrection() override = default; @@ -465,8 +473,7 @@ public: /** * Use smoothing-terms */ - virtual void - EnableSmoothing(bool bSmooth, double fSmoothInfl, double fFirst, double fSec, double fThird); + virtual void EnableSmoothing(bool bSmooth, double fSmoothInfl, double fFirst, double fSec, double fThird); protected: /** diff --git a/src/Mod/ReverseEngineering/App/BSplineFitting.cpp b/src/Mod/ReverseEngineering/App/BSplineFitting.cpp index fb9715a05a..d114e0e353 100644 --- a/src/Mod/ReverseEngineering/App/BSplineFitting.cpp +++ b/src/Mod/ReverseEngineering/App/BSplineFitting.cpp @@ -23,24 +23,24 @@ ***************************************************************************/ #if defined(HAVE_PCL_OPENNURBS) -#include +# include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include -#include +# include -#include "BSplineFitting.h" +# include "BSplineFitting.h" -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include using namespace Reen; @@ -201,16 +201,18 @@ Handle(Geom_BSplineSurface) BSplineFitting::perform() vMultArray.SetValue(index, it->second); } - Handle(Geom_BSplineSurface) spline = new Geom_BSplineSurface(poles, - weights, - uKnotArray, - vKnotArray, - uMultArray, - vMultArray, - uDegree, - vDegree, - uPeriodic, - vPeriodic); + Handle(Geom_BSplineSurface) spline = new Geom_BSplineSurface( + poles, + weights, + uKnotArray, + vKnotArray, + uMultArray, + vMultArray, + uDegree, + vDegree, + uPeriodic, + vPeriodic + ); return spline; } #endif // HAVE_PCL_OPENNURBS diff --git a/src/Mod/ReverseEngineering/App/BSplineFitting.h b/src/Mod/ReverseEngineering/App/BSplineFitting.h index 3ce719b2d6..613e34c881 100644 --- a/src/Mod/ReverseEngineering/App/BSplineFitting.h +++ b/src/Mod/ReverseEngineering/App/BSplineFitting.h @@ -26,10 +26,10 @@ #define REEN_BSPLINEFITTING_H #if defined(HAVE_PCL_OPENNURBS) -#include +# include -#include -#include +# include +# include namespace Reen diff --git a/src/Mod/ReverseEngineering/App/PreCompiled.h b/src/Mod/ReverseEngineering/App/PreCompiled.h index 749ab8e186..5d62635317 100644 --- a/src/Mod/ReverseEngineering/App/PreCompiled.h +++ b/src/Mod/ReverseEngineering/App/PreCompiled.h @@ -29,7 +29,7 @@ // pcl headers include instead of #ifndef BOOST_BIND_GLOBAL_PLACEHOLDERS -#define BOOST_BIND_GLOBAL_PLACEHOLDERS +# define BOOST_BIND_GLOBAL_PLACEHOLDERS #endif diff --git a/src/Mod/ReverseEngineering/App/RegionGrowing.cpp b/src/Mod/ReverseEngineering/App/RegionGrowing.cpp index 2e91faa1c8..82f098c006 100644 --- a/src/Mod/ReverseEngineering/App/RegionGrowing.cpp +++ b/src/Mod/ReverseEngineering/App/RegionGrowing.cpp @@ -32,15 +32,15 @@ #if defined(HAVE_PCL_FILTERS) -#include -#include +# include +# include #endif #if defined(HAVE_PCL_SEGMENTATION) -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include using namespace std; using namespace Reen; @@ -58,8 +58,7 @@ void RegionGrowing::perform(int ksearch) pcl::PointCloud::Ptr cloud(new pcl::PointCloud); cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(pcl::PointXYZ(it->x, it->y, it->z)); } } @@ -95,8 +94,7 @@ void RegionGrowing::perform(int ksearch) std::vector clusters; reg.extract(clusters); - for (std::vector::iterator it = clusters.begin(); it != clusters.end(); - ++it) { + for (std::vector::iterator it = clusters.begin(); it != clusters.end(); ++it) { myClusters.push_back(std::vector()); myClusters.back().swap(it->indices); } @@ -149,8 +147,7 @@ void RegionGrowing::perform(const std::vector& myNormals) std::vector clusters; reg.extract(clusters); - for (std::vector::iterator it = clusters.begin(); it != clusters.end(); - ++it) { + for (std::vector::iterator it = clusters.begin(); it != clusters.end(); ++it) { myClusters.push_back(std::vector()); myClusters.back().swap(it->indices); } diff --git a/src/Mod/ReverseEngineering/App/SampleConsensus.cpp b/src/Mod/ReverseEngineering/App/SampleConsensus.cpp index 626c669843..1f534eb4a7 100644 --- a/src/Mod/ReverseEngineering/App/SampleConsensus.cpp +++ b/src/Mod/ReverseEngineering/App/SampleConsensus.cpp @@ -32,13 +32,13 @@ #if defined(HAVE_PCL_SAMPLE_CONSENSUS) -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include using namespace std; using namespace Reen; @@ -46,9 +46,11 @@ using pcl::PointCloud; using pcl::PointNormal; using pcl::PointXYZ; -SampleConsensus::SampleConsensus(SacModel sac, - const Points::PointKernel& pts, - const std::vector& nor) +SampleConsensus::SampleConsensus( + SacModel sac, + const Points::PointKernel& pts, + const std::vector& nor +) : mySac(sac) , myPoints(pts) , myNormals(nor) @@ -59,8 +61,7 @@ double SampleConsensus::perform(std::vector& parameters, std::vector pcl::PointCloud::Ptr cloud(new pcl::PointCloud); cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(pcl::PointXYZ(it->x, it->y, it->z)); } } @@ -71,7 +72,7 @@ double SampleConsensus::perform(std::vector& parameters, std::vector pcl::PointCloud::Ptr normals(new pcl::PointCloud()); if (mySac == SACMODEL_CONE || mySac == SACMODEL_CYLINDER) { -#if 0 +# if 0 // Create search tree pcl::search::KdTree::Ptr tree; tree.reset (new pcl::search::KdTree (false)); @@ -84,7 +85,7 @@ double SampleConsensus::perform(std::vector& parameters, std::vector n.setSearchMethod (tree); n.setKSearch (ksearch); n.compute (*normals); -#else +# else normals->reserve(myNormals.size()); for (std::vector::const_iterator it = myNormals.begin(); it != myNormals.end(); @@ -94,7 +95,7 @@ double SampleConsensus::perform(std::vector& parameters, std::vector normals->push_back(pcl::Normal(it->x, it->y, it->z)); } } -#endif +# endif } // created RandomSampleConsensus object and compute the appropriated model @@ -110,14 +111,16 @@ double SampleConsensus::perform(std::vector& parameters, std::vector } case SACMODEL_CONE: { pcl::SampleConsensusModelCone::Ptr model_c( - new pcl::SampleConsensusModelCone(cloud)); + new pcl::SampleConsensusModelCone(cloud) + ); model_c->setInputNormals(normals); model_p = model_c; break; } case SACMODEL_CYLINDER: { pcl::SampleConsensusModelCylinder::Ptr model_c( - new pcl::SampleConsensusModelCylinder(cloud)); + new pcl::SampleConsensusModelCylinder(cloud) + ); model_c->setInputNormals(normals); model_p = model_c; break; diff --git a/src/Mod/ReverseEngineering/App/Segmentation.cpp b/src/Mod/ReverseEngineering/App/Segmentation.cpp index 782535c22a..e7fa7ac93c 100644 --- a/src/Mod/ReverseEngineering/App/Segmentation.cpp +++ b/src/Mod/ReverseEngineering/App/Segmentation.cpp @@ -29,21 +29,21 @@ #if defined(HAVE_PCL_FILTERS) -#include -#include -#include +# include +# include +# include #endif #if defined(HAVE_PCL_SAMPLE_CONSENSUS) -#include -#include +# include +# include #endif #if defined(HAVE_PCL_SEGMENTATION) -#include -#include -#include -#include +# include +# include +# include +# include #endif using namespace std; @@ -180,7 +180,7 @@ void NormalEstimation::perform(std::vector& normals) cloud->width = int(cloud->points.size()); cloud->height = 1; -#if 0 +# if 0 // Build a passthrough filter to remove spurious NaNs pcl::PointCloud::Ptr cloud_filtered (new pcl::PointCloud); pcl::PassThrough pass; @@ -188,7 +188,7 @@ void NormalEstimation::perform(std::vector& normals) pass.setFilterFieldName ("z"); pass.setFilterLimits (0, 1.5); pass.filter (*cloud_filtered); -#endif +# endif // Estimate point normals pcl::PointCloud::Ptr cloud_normals(new pcl::PointCloud); diff --git a/src/Mod/ReverseEngineering/App/SurfaceTriangulation.cpp b/src/Mod/ReverseEngineering/App/SurfaceTriangulation.cpp index 8ccc95c774..38d8c1a014 100644 --- a/src/Mod/ReverseEngineering/App/SurfaceTriangulation.cpp +++ b/src/Mod/ReverseEngineering/App/SurfaceTriangulation.cpp @@ -35,26 +35,26 @@ // http://svn.pointclouds.org/pcl/tags/pcl-1.5.1/test/ #if defined(HAVE_PCL_SURFACE) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include -#ifndef PCL_REVISION_VERSION -#define PCL_REVISION_VERSION 0 -#endif +# ifndef PCL_REVISION_VERSION +# define PCL_REVISION_VERSION 0 +# endif using namespace pcl; using namespace pcl::io; @@ -80,8 +80,7 @@ void SurfaceTriangulation::perform(int ksearch) cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(PointXYZ(it->x, it->y, it->z)); } } @@ -206,8 +205,7 @@ void PoissonReconstruction::perform(int ksearch) cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(PointXYZ(it->x, it->y, it->z)); } } @@ -325,8 +323,7 @@ void GridReconstruction::perform(int ksearch) cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(PointXYZ(it->x, it->y, it->z)); } } @@ -420,10 +417,12 @@ void GridReconstruction::perform(const std::vector& normals) // ---------------------------------------------------------------------------- -ImageTriangulation::ImageTriangulation(int width, - int height, - const Points::PointKernel& pts, - Mesh::MeshObject& mesh) +ImageTriangulation::ImageTriangulation( + int width, + int height, + const Points::PointKernel& pts, + Mesh::MeshObject& mesh +) : width(width) , height(height) , myPoints(pts) @@ -516,8 +515,7 @@ void Reen::MarchingCubesRBF::perform(int ksearch) cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(PointXYZ(it->x, it->y, it->z)); } } @@ -628,8 +626,7 @@ void Reen::MarchingCubesHoppe::perform(int ksearch) cloud->reserve(myPoints.size()); for (Points::PointKernel::const_iterator it = myPoints.begin(); it != myPoints.end(); ++it) { - if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) - && !boost::math::isnan(it->z)) { + if (!boost::math::isnan(it->x) && !boost::math::isnan(it->y) && !boost::math::isnan(it->z)) { cloud->push_back(PointXYZ(it->x, it->y, it->z)); } } @@ -747,10 +744,12 @@ void MeshConversion::convert(const pcl::PolygonMesh& pclMesh, Mesh::MeshObject& && (pclMesh.cloud.fields[d].name == "x" || pclMesh.cloud.fields[d].name == "y" || pclMesh.cloud.fields[d].name == "z")) { float value; - memcpy(&value, - &pclMesh.cloud.data[i * point_size + pclMesh.cloud.fields[d].offset - + c * sizeof(float)], - sizeof(float)); + memcpy( + &value, + &pclMesh.cloud + .data[i * point_size + pclMesh.cloud.fields[d].offset + c * sizeof(float)], + sizeof(float) + ); vertex[xyz] = value; if (++xyz == 3) { points.push_back(vertex); diff --git a/src/Mod/ReverseEngineering/Gui/Command.cpp b/src/Mod/ReverseEngineering/Gui/Command.cpp index 0b79942a02..3177f2fa38 100644 --- a/src/Mod/ReverseEngineering/Gui/Command.cpp +++ b/src/Mod/ReverseEngineering/Gui/Command.cpp @@ -76,9 +76,11 @@ void CmdApproxCurve::activated(int) App::DocumentObjectT objT; auto obj = Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); if (obj.size() != 1 || !(obj.at(0)->isDerivedFrom())) { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Reen_ApproxSurface", "Wrong selection"), - qApp->translate("Reen_ApproxSurface", "Select a point cloud.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Reen_ApproxSurface", "Wrong selection"), + qApp->translate("Reen_ApproxSurface", "Select a point cloud.") + ); return; } @@ -108,15 +110,16 @@ CmdApproxSurface::CmdApproxSurface() void CmdApproxSurface::activated(int) { App::DocumentObjectT objT; - std::vector obj = - Gui::Selection().getObjectsOfType(App::GeoFeature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + App::GeoFeature::getClassTypeId() + ); if (obj.size() != 1 - || !(obj.at(0)->isDerivedFrom() - || obj.at(0)->isDerivedFrom())) { + || !(obj.at(0)->isDerivedFrom() || obj.at(0)->isDerivedFrom())) { QMessageBox::warning( Gui::getMainWindow(), qApp->translate("Reen_ApproxSurface", "Wrong selection"), - qApp->translate("Reen_ApproxSurface", "Select a point cloud or mesh.")); + qApp->translate("Reen_ApproxSurface", "Select a point cloud or mesh.") + ); return; } @@ -153,8 +156,8 @@ void CmdApproxPlane::activated(int) it->getPropertyList(List); for (const auto& jt : List) { if (jt->isDerivedFrom()) { - const Data::ComplexGeoData* data = - static_cast(jt)->getComplexData(); + const Data::ComplexGeoData* data + = static_cast(jt)->getComplexData(); if (data) { data->getPoints(aPoints, aNormals, 0.01f); if (!aPoints.empty()) { @@ -199,15 +202,12 @@ void CmdApproxPlane::activated(int) Base::CoordinateSystem cs; cs.setPosition(Base::convertTo(base)); - cs.setAxes(Base::convertTo(norm), - Base::convertTo(dirU)); + cs.setAxes(Base::convertTo(norm), Base::convertTo(dirU)); Base::Placement pm = Base::CoordinateSystem().displacement(cs); double q0, q1, q2, q3; pm.getRotation().getValue(q0, q1, q2, q3); - Base::Console().log("RMS value for plane fit with %lu points: %.4f\n", - aData.size(), - sigma); + Base::Console().log("RMS value for plane fit with %lu points: %.4f\n", aData.size(), sigma); Base::Console().log(" Plane base(%.4f, %.4f, %.4f)\n", base.x, base.y, base.z); Base::Console().log(" Plane normal(%.4f, %.4f, %.4f)\n", norm.x, norm.y, norm.z); @@ -378,8 +378,8 @@ void CmdApproxPolynomial::activated(int) fit.AddPoints(kernel.GetPoints()); if (fit.Fit() < std::numeric_limits::max()) { Base::BoundBox3f bbox = fit.GetBoundings(); - std::vector poles = - fit.toBezier(bbox.MinX, bbox.MaxX, bbox.MinY, bbox.MaxY); + std::vector poles + = fit.toBezier(bbox.MinX, bbox.MaxX, bbox.MinY, bbox.MaxY); fit.Transform(poles); TColgp_Array2OfPnt grid(1, 3, 1, 3); @@ -394,8 +394,7 @@ void CmdApproxPolynomial::activated(int) grid.SetValue(3, 3, Base::convertTo(poles.at(8))); Handle(Geom_BezierSurface) bezier(new Geom_BezierSurface(grid)); - Part::Feature* part = - static_cast(doc->addObject("Part::Spline", "Bezier")); + Part::Feature* part = static_cast(doc->addObject("Part::Spline", "Bezier")); part->Shape.setValue(Part::GeomBezierSurface(bezier).toShape()); } } @@ -604,12 +603,15 @@ CmdPoissonReconstruction::CmdPoissonReconstruction() void CmdPoissonReconstruction::activated(int) { App::DocumentObjectT objT; - std::vector obj = - Gui::Selection().getObjectsOfType(Points::Feature::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Points::Feature::getClassTypeId() + ); if (obj.size() != 1) { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Reen_ApproxSurface", "Wrong selection"), - qApp->translate("Reen_ApproxSurface", "Select a single point cloud.")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Reen_ApproxSurface", "Wrong selection"), + qApp->translate("Reen_ApproxSurface", "Select a single point cloud.") + ); return; } @@ -637,8 +639,9 @@ CmdViewTriangulation::CmdViewTriangulation() void CmdViewTriangulation::activated(int) { - std::vector obj = - Gui::Selection().getObjectsOfType(Points::Structured::getClassTypeId()); + std::vector obj = Gui::Selection().getObjectsOfType( + Points::Structured::getClassTypeId() + ); addModule(App, "ReverseEngineering"); openCommand(QT_TRANSLATE_NOOP("Command", "View triangulation")); try { @@ -647,11 +650,13 @@ void CmdViewTriangulation::activated(int) QString document = QString::fromStdString(objT.getDocumentPython()); QString object = QString::fromStdString(objT.getObjectPython()); - QString command = QStringLiteral("%1.addObject('Mesh::Feature', 'View mesh').Mesh " - "= ReverseEngineering.viewTriangulation(" - "Points=%2.Points," - "Width=%2.Width," - "Height=%2.Height)") + QString command = QStringLiteral( + "%1.addObject('Mesh::Feature', 'View mesh').Mesh " + "= ReverseEngineering.viewTriangulation(" + "Points=%2.Points," + "Width=%2.Width," + "Height=%2.Height)" + ) .arg(document, object); runCommand(Doc, command.toLatin1()); } @@ -661,9 +666,11 @@ void CmdViewTriangulation::activated(int) } catch (const Base::Exception& e) { abortCommand(); - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Reen_ViewTriangulation", "View triangulation failed"), - QString::fromLatin1(e.what())); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Reen_ViewTriangulation", "View triangulation failed"), + QString::fromLatin1(e.what()) + ); } } diff --git a/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp b/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp index 104b86ee6e..96a0c5ba29 100644 --- a/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp +++ b/src/Mod/ReverseEngineering/Gui/FitBSplineCurve.cpp @@ -99,8 +99,7 @@ void FitBSplineCurveWidget::tryAccept() QString object = QString::fromStdString(d->obj.getObjectPython()); QStringList arguments; - arguments.append( - QStringLiteral("Points=getattr(%1, %1.getPropertyNameOfGeometry())").arg(object)); + arguments.append(QStringLiteral("Points=getattr(%1, %1.getPropertyNameOfGeometry())").arg(object)); if (!d->ui.groupBoxSmooth->isChecked()) { arguments.append(QStringLiteral("MinDegree = %1").arg(d->ui.degreeMin->value())); } @@ -123,8 +122,10 @@ void FitBSplineCurveWidget::tryAccept() } QString argument = arguments.join(QLatin1String(", ")); - QString command = QStringLiteral("%1.addObject(\"Part::Spline\", \"Spline\").Shape = " - "ReverseEngineering.approxCurve(%2).toShape()") + QString command = QStringLiteral( + "%1.addObject(\"Part::Spline\", \"Spline\").Shape = " + "ReverseEngineering.approxCurve(%2).toShape()" + ) .arg(document, argument); tryCommand(command); diff --git a/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp b/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp index a4aed95181..8e06862861 100644 --- a/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp +++ b/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.cpp @@ -59,10 +59,12 @@ FitBSplineSurfaceWidget::FitBSplineSurfaceWidget(const App::DocumentObjectT& obj { Q_UNUSED(parent); d->ui.setupUi(this); - connect(d->ui.makePlacement, - &QPushButton::clicked, - this, - &FitBSplineSurfaceWidget::onMakePlacementClicked); + connect( + d->ui.makePlacement, + &QPushButton::clicked, + this, + &FitBSplineSurfaceWidget::onMakePlacementClicked + ); d->obj = obj; restoreSettings(); } @@ -114,12 +116,12 @@ void FitBSplineSurfaceWidget::onMakePlacementClicked() geom->getComplexData()->getPoints(points, normals, 0.001); std::vector data; - std::transform(points.begin(), - points.end(), - std::back_inserter(data), - [](const Base::Vector3d& v) { - return Base::convertTo(v); - }); + std::transform( + points.begin(), + points.end(), + std::back_inserter(data), + [](const Base::Vector3d& v) { return Base::convertTo(v); } + ); MeshCore::PlaneFit fit; fit.AddPoints(data); if (fit.Fit() < std::numeric_limits::max()) { @@ -129,14 +131,18 @@ void FitBSplineSurfaceWidget::onMakePlacementClicked() Base::CoordinateSystem cs; cs.setPosition(Base::convertTo(base)); - cs.setAxes(Base::convertTo(norm), - Base::convertTo(dirU)); + cs.setAxes( + Base::convertTo(norm), + Base::convertTo(dirU) + ); Base::Placement pm = Base::CoordinateSystem().displacement(cs); double q0, q1, q2, q3; pm.getRotation().getValue(q0, q1, q2, q3); - QString argument = QStringLiteral("Base.Placement(Base.Vector(%1, %2, " - "%3), Base.Rotation(%4, %5, %6, %7))") + QString argument = QStringLiteral( + "Base.Placement(Base.Vector(%1, %2, " + "%3), Base.Rotation(%4, %5, %6, %7))" + ) .arg(base.x) .arg(base.y) .arg(base.z) @@ -146,10 +152,10 @@ void FitBSplineSurfaceWidget::onMakePlacementClicked() .arg(q3); QString document = QString::fromStdString(d->obj.getDocumentPython()); - QString command = - QStringLiteral( - R"(%1.addObject("App::Placement", "Placement").Placement = %2)") - .arg(document, argument); + QString command = QStringLiteral( + R"(%1.addObject("App::Placement", "Placement").Placement = %2)" + ) + .arg(document, argument); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Placement")); Gui::Command::runCommand(Gui::Command::Doc, "from FreeCAD import Base"); @@ -172,24 +178,28 @@ bool FitBSplineSurfaceWidget::accept() QString document = QString::fromStdString(d->obj.getDocumentPython()); QString object = QString::fromStdString(d->obj.getObjectPython()); - QString argument = QStringLiteral("Points=getattr(%1, %1.getPropertyNameOfGeometry()), " - "UDegree=%2, VDegree=%3, " - "NbUPoles=%4, NbVPoles=%5, " - "Smooth=%6, " - "Weight=%7, " - "Grad=%8, " - "Bend=%9, " - "Curv=%10, " - "Iterations=%11, " - "PatchFactor=%12, " - "Correction=True") + QString argument = QStringLiteral( + "Points=getattr(%1, %1.getPropertyNameOfGeometry()), " + "UDegree=%2, VDegree=%3, " + "NbUPoles=%4, NbVPoles=%5, " + "Smooth=%6, " + "Weight=%7, " + "Grad=%8, " + "Bend=%9, " + "Curv=%10, " + "Iterations=%11, " + "PatchFactor=%12, " + "Correction=True" + ) .arg(object) .arg(d->ui.degreeU->value()) .arg(d->ui.degreeV->value()) .arg(d->ui.polesU->value()) .arg(d->ui.polesV->value()) - .arg(d->ui.groupBoxSmooth->isChecked() ? QLatin1String("True") - : QLatin1String("False")) + .arg( + d->ui.groupBoxSmooth->isChecked() ? QLatin1String("True") + : QLatin1String("False") + ) .arg(d->ui.totalWeight->value()) .arg(d->ui.gradient->value()) .arg(d->ui.bending->value()) @@ -197,13 +207,14 @@ bool FitBSplineSurfaceWidget::accept() .arg(d->ui.iterations->value()) .arg(d->ui.sizeFactor->value()); if (d->ui.uvdir->isChecked()) { - std::vector selection = - Gui::Selection().getObjectsOfType(); + std::vector selection + = Gui::Selection().getObjectsOfType(); if (selection.size() != 1) { QMessageBox::warning( this, tr("Wrong selection"), - tr("Select a single placement object to get the local orientation.")); + tr("Select a single placement object to get the local orientation.") + ); return false; } @@ -212,17 +223,18 @@ bool FitBSplineSurfaceWidget::accept() Base::Vector3d v(0, 1, 0); rot.multVec(u, u); rot.multVec(v, v); - argument += - QStringLiteral(", UVDirs=(FreeCAD.Vector(%1,%2,%3), FreeCAD.Vector(%4,%5,%6))") - .arg(u.x) - .arg(u.y) - .arg(u.z) - .arg(v.x) - .arg(v.y) - .arg(v.z); + argument += QStringLiteral(", UVDirs=(FreeCAD.Vector(%1,%2,%3), FreeCAD.Vector(%4,%5,%6))") + .arg(u.x) + .arg(u.y) + .arg(u.z) + .arg(v.x) + .arg(v.y) + .arg(v.z); } - QString command = QStringLiteral("%1.addObject(\"Part::Spline\", \"Spline\").Shape = " - "ReverseEngineering.approxSurface(%2).toShape()") + QString command = QStringLiteral( + "%1.addObject(\"Part::Spline\", \"Spline\").Shape = " + "ReverseEngineering.approxSurface(%2).toShape()" + ) .arg(document, argument); Gui::WaitCursor wc; diff --git a/src/Mod/ReverseEngineering/Gui/Poisson.cpp b/src/Mod/ReverseEngineering/Gui/Poisson.cpp index 11e47a527b..304dbae3aa 100644 --- a/src/Mod/ReverseEngineering/Gui/Poisson.cpp +++ b/src/Mod/ReverseEngineering/Gui/Poisson.cpp @@ -66,16 +66,20 @@ bool PoissonWidget::accept() QString document = QString::fromStdString(d->obj.getDocumentPython()); QString object = QString::fromStdString(d->obj.getObjectPython()); - QString argument = QStringLiteral("Points=%1.Points, " - "OctreeDepth=%2, " - "SolverDivide=%3, " - "SamplesPerNode=%4") + QString argument = QStringLiteral( + "Points=%1.Points, " + "OctreeDepth=%2, " + "SolverDivide=%3, " + "SamplesPerNode=%4" + ) .arg(object) .arg(d->ui.octreeDepth->value()) .arg(d->ui.solverDivide->value()) .arg(d->ui.samplesPerNode->value()); - QString command = QStringLiteral("%1.addObject(\"Mesh::Feature\", \"Poisson\").Mesh = " - "ReverseEngineering.poissonReconstruction(%2)") + QString command = QStringLiteral( + "%1.addObject(\"Mesh::Feature\", \"Poisson\").Mesh = " + "ReverseEngineering.poissonReconstruction(%2)" + ) .arg(document, argument); Gui::WaitCursor wc; diff --git a/src/Mod/ReverseEngineering/Gui/Segmentation.cpp b/src/Mod/ReverseEngineering/Gui/Segmentation.cpp index 91880e497f..336dfb2daf 100644 --- a/src/Mod/ReverseEngineering/Gui/Segmentation.cpp +++ b/src/Mod/ReverseEngineering/Gui/Segmentation.cpp @@ -97,9 +97,12 @@ void Segmentation::accept() std::vector segm; if (ui->groupBoxPln->isChecked()) { segm.emplace_back( - std::make_shared(meshCurv.GetCurvature(), - ui->numPln->value(), - ui->curvTolPln->value())); + std::make_shared( + meshCurv.GetCurvature(), + ui->numPln->value(), + ui->curvTolPln->value() + ) + ); } finder.FindSegments(segm); @@ -117,14 +120,15 @@ void Segmentation::accept() if (fit.Fit() < std::numeric_limits::max()) { Base::Vector3f base = fit.GetBase(); Base::Vector3f axis = fit.GetNormal(); - MeshCore::AbstractSurfaceFit* fitter = - new MeshCore::PlaneSurfaceFit(base, axis); + MeshCore::AbstractSurfaceFit* fitter = new MeshCore::PlaneSurfaceFit(base, axis); segmSurf.emplace_back( std::make_shared( fitter, kernel, ui->numPln->value(), - ui->distToPln->value())); + ui->distToPln->value() + ) + ); } } } @@ -147,8 +151,8 @@ void Segmentation::accept() for (const auto& it : segmSurf) { const std::vector& data = it->GetSegments(); - std::shared_ptr genSegm = - std::dynamic_pointer_cast(it); + std::shared_ptr genSegm + = std::dynamic_pointer_cast(it); bool isPlanar = (strcmp(genSegm->GetType(), "Plane") == 0); for (const auto& jt : data) { @@ -156,8 +160,9 @@ void Segmentation::accept() algo.ResetFacetsFlag(jt, MeshCore::MeshFacet::TMP0); Mesh::MeshObject* segment = mesh->meshFromSegment(jt); - Mesh::Feature* feaSegm = - static_cast(group->addObject("Mesh::Feature", "Segment")); + Mesh::Feature* feaSegm = static_cast( + group->addObject("Mesh::Feature", "Segment") + ); Mesh::MeshObject* feaMesh = feaSegm->Mesh.startEditing(); feaMesh->swap(*segment); feaSegm->Mesh.finishEditing(); @@ -190,7 +195,8 @@ void Segmentation::accept() [&hPlane](const Base::Vector3f& v) { gp_Pnt p(v.x, v.y, v.z); return GeomAPI_ProjectPointOnSurf(p, hPlane).NearestPoint(); - }); + } + ); BRepBuilderAPI_MakePolygon mkPoly; for (std::vector::reverse_iterator it = polygon.rbegin(); @@ -210,14 +216,18 @@ void Segmentation::accept() } else { failures.push_back(feaSegm); - Base::Console().warning("Failed to create face from %s\n", - feaSegm->Label.getValue()); + Base::Console().warning( + "Failed to create face from %s\n", + feaSegm->Label.getValue() + ); } } catch (Standard_Failure&) { failures.push_back(feaSegm); - Base::Console().error("Fatal failure to create face from %s\n", - feaSegm->Label.getValue()); + Base::Console().error( + "Fatal failure to create face from %s\n", + feaSegm->Label.getValue() + ); } } } @@ -231,22 +241,25 @@ void Segmentation::accept() if (!unusedFacets.empty()) { std::unique_ptr segment(mesh->meshFromSegment(unusedFacets)); - Mesh::Feature* feaSegm = - static_cast(group->addObject("Mesh::Feature", "Unused")); + Mesh::Feature* feaSegm = static_cast( + group->addObject("Mesh::Feature", "Unused") + ); Mesh::MeshObject* feaMesh = feaSegm->Mesh.startEditing(); feaMesh->swap(*segment); feaSegm->Mesh.finishEditing(); } } if (createCompound) { - Part::Feature* shapeFea = - static_cast(group->addObject("Part::Feature", "Compound")); + Part::Feature* shapeFea = static_cast( + group->addObject("Part::Feature", "Compound") + ); shapeFea->Shape.setValue(compound); // create a sub-group where to move the problematic segments if (!failures.empty()) { App::DocumentObjectGroup* subgroup = static_cast( - group->addObject("App::DocumentObjectGroup", "Failed")); + group->addObject("App::DocumentObjectGroup", "Failed") + ); failures = group->removeObjects(failures); subgroup->Group.setValues(failures); } diff --git a/src/Mod/ReverseEngineering/Gui/Segmentation.h b/src/Mod/ReverseEngineering/Gui/Segmentation.h index a61bda1b12..53011add18 100644 --- a/src/Mod/ReverseEngineering/Gui/Segmentation.h +++ b/src/Mod/ReverseEngineering/Gui/Segmentation.h @@ -48,9 +48,11 @@ class Segmentation: public QWidget Q_OBJECT public: - explicit Segmentation(Mesh::Feature* mesh, - QWidget* parent = nullptr, - Qt::WindowFlags fl = Qt::WindowFlags()); + explicit Segmentation( + Mesh::Feature* mesh, + QWidget* parent = nullptr, + Qt::WindowFlags fl = Qt::WindowFlags() + ); ~Segmentation() override; void accept(); diff --git a/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp b/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp index 1eaa2515d7..4d793a15c3 100644 --- a/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp +++ b/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp @@ -60,44 +60,22 @@ SegmentationManual::~SegmentationManual() = default; void SegmentationManual::setupConnections() { - connect(ui->selectRegion, - &QPushButton::clicked, - this, - &SegmentationManual::onSelectRegionClicked); + connect(ui->selectRegion, &QPushButton::clicked, this, &SegmentationManual::onSelectRegionClicked); connect(ui->selectAll, &QPushButton::clicked, this, &SegmentationManual::onSelectAllClicked); - connect(ui->selectComponents, - &QPushButton::clicked, - this, - &SegmentationManual::onSelectComponentsClicked); - connect(ui->selectTriangle, - &QPushButton::clicked, - this, - &SegmentationManual::onSelectTriangleClicked); - connect(ui->deselectAll, - &QPushButton::clicked, - this, - &SegmentationManual::onDeselectAllClicked); - connect(ui->visibleTriangles, - &QCheckBox::toggled, - this, - &SegmentationManual::onVisibleTrianglesToggled); - connect(ui->screenTriangles, - &QCheckBox::toggled, - this, - &SegmentationManual::onScreenTrianglesToggled); + connect( + ui->selectComponents, + &QPushButton::clicked, + this, + &SegmentationManual::onSelectComponentsClicked + ); + connect(ui->selectTriangle, &QPushButton::clicked, this, &SegmentationManual::onSelectTriangleClicked); + connect(ui->deselectAll, &QPushButton::clicked, this, &SegmentationManual::onDeselectAllClicked); + connect(ui->visibleTriangles, &QCheckBox::toggled, this, &SegmentationManual::onVisibleTrianglesToggled); + connect(ui->screenTriangles, &QCheckBox::toggled, this, &SegmentationManual::onScreenTrianglesToggled); connect(ui->cbSelectComp, &QCheckBox::toggled, this, &SegmentationManual::onSelectCompToggled); - connect(ui->planeDetect, - &QPushButton::clicked, - this, - &SegmentationManual::onPlaneDetectClicked); - connect(ui->cylinderDetect, - &QPushButton::clicked, - this, - &SegmentationManual::onCylinderDetectClicked); - connect(ui->sphereDetect, - &QPushButton::clicked, - this, - &SegmentationManual::onSphereDetectClicked); + connect(ui->planeDetect, &QPushButton::clicked, this, &SegmentationManual::onPlaneDetectClicked); + connect(ui->cylinderDetect, &QPushButton::clicked, this, &SegmentationManual::onCylinderDetectClicked); + connect(ui->sphereDetect, &QPushButton::clicked, this, &SegmentationManual::onSphereDetectClicked); } void SegmentationManual::changeEvent(QEvent* e) @@ -153,8 +131,11 @@ public: static void findGeometry( int minFaces, double tolerance, - std::function&, - const std::vector&)> fitFunc) + std::function&, + const std::vector& + )> fitFunc + ) { Gui::Document* gdoc = Gui::Application::Instance->activeDocument(); if (!gdoc) { @@ -164,8 +145,9 @@ public: App::Document* adoc = gdoc->getDocument(); std::vector meshes = adoc->getObjectsOfType(); for (auto it : meshes) { - MeshGui::ViewProviderMesh* vpm = - static_cast(gdoc->getViewProvider(it)); + MeshGui::ViewProviderMesh* vpm = static_cast( + gdoc->getViewProvider(it) + ); const Mesh::MeshObject& mesh = it->Mesh.getValue(); if (mesh.hasSelectedFacets()) { @@ -192,7 +174,9 @@ public: surfFit, kernel, minFaces, - tolerance)); + tolerance + ) + ); finder.FindSegments(segm); for (const auto& segmIt : segm) { diff --git a/src/Mod/ReverseEngineering/ReverseEngineeringGlobal.h b/src/Mod/ReverseEngineering/ReverseEngineeringGlobal.h index 995ca7e060..4764eefda2 100644 --- a/src/Mod/ReverseEngineering/ReverseEngineeringGlobal.h +++ b/src/Mod/ReverseEngineering/ReverseEngineeringGlobal.h @@ -25,25 +25,25 @@ #include #ifndef REEN_GLOBAL_H -#define REEN_GLOBAL_H +# define REEN_GLOBAL_H // Reen -#ifndef ReenExport -#ifdef ReverseEngineering_EXPORTS -#define ReenExport FREECAD_DECL_EXPORT -#else -#define ReenExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef ReenExport +# ifdef ReverseEngineering_EXPORTS +# define ReenExport FREECAD_DECL_EXPORT +# else +# define ReenExport FREECAD_DECL_IMPORT +# endif +# endif // ReenGui -#ifndef ReenGuiExport -#ifdef ReverseEngineeringGui_EXPORTS -#define ReenGuiExport FREECAD_DECL_EXPORT -#else -#define ReenGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef ReenGuiExport +# ifdef ReverseEngineeringGui_EXPORTS +# define ReenGuiExport FREECAD_DECL_EXPORT +# else +# define ReenGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // REEN_GLOBAL_H diff --git a/src/Mod/Robot/App/AppRobot.cpp b/src/Mod/Robot/App/AppRobot.cpp index 218818d47a..caca1332c3 100644 --- a/src/Mod/Robot/App/AppRobot.cpp +++ b/src/Mod/Robot/App/AppRobot.cpp @@ -47,10 +47,12 @@ public: Module() : Py::ExtensionModule("Robot") { - add_varargs_method("simulateToFile", - &Module::simulateToFile, - "simulateToFile(Robot,Trajectory,TickSize,FileName) - runs the " - "simulation and write the result to a file."); + add_varargs_method( + "simulateToFile", + &Module::simulateToFile, + "simulateToFile(Robot,Trajectory,TickSize,FileName) - runs the " + "simulation and write the result to a file." + ); initialize("This module is the Robot module."); // register with Python } @@ -62,14 +64,16 @@ private: float tick; char* FileName; - if (!PyArg_ParseTuple(args.ptr(), - "O!O!fs", - &(Robot6AxisPy::Type), - &pcRobObj, - &(TrajectoryPy::Type), - &pcTracObj, - &tick, - &FileName)) { + if (!PyArg_ParseTuple( + args.ptr(), + "O!O!fs", + &(Robot6AxisPy::Type), + &pcRobObj, + &(TrajectoryPy::Type), + &pcTracObj, + &tick, + &FileName + )) { throw Py::Exception(); } diff --git a/src/Mod/Robot/App/Edge2TracObject.cpp b/src/Mod/Robot/App/Edge2TracObject.cpp index fcbada9faa..45d6bc6fdb 100644 --- a/src/Mod/Robot/App/Edge2TracObject.cpp +++ b/src/Mod/Robot/App/Edge2TracObject.cpp @@ -44,16 +44,8 @@ PROPERTY_SOURCE(Robot::Edge2TracObject, Robot::TrajectoryObject) Edge2TracObject::Edge2TracObject() { - ADD_PROPERTY_TYPE(Source, - (nullptr), - "Edge2Trac", - Prop_None, - "Edges to generate the Trajectory"); - ADD_PROPERTY_TYPE(SegValue, - (0.5), - "Edge2Trac", - Prop_None, - "Max deviation from original geometry"); + ADD_PROPERTY_TYPE(Source, (nullptr), "Edge2Trac", Prop_None, "Edges to generate the Trajectory"); + ADD_PROPERTY_TYPE(SegValue, (0.5), "Edge2Trac", Prop_None, "Max deviation from original geometry"); ADD_PROPERTY_TYPE(UseRotation, (0), "Edge2Trac", Prop_None, "use orientation of the edge"); NbrOfEdges = 0; NbrOfCluster = 0; @@ -137,8 +129,7 @@ App::DocumentObjectExecReturn* Edge2TracObject::execute() P2 = tmpP; } if (first) { - Waypoint wp("Pt", - Base::Placement(Base::Vector3d(P1.X(), P1.Y(), P1.Z()), R1)); + Waypoint wp("Pt", Base::Placement(Base::Vector3d(P1.X(), P1.Y(), P1.Z()), R1)); trac.addWaypoint(wp); first = false; } @@ -167,8 +158,10 @@ App::DocumentObjectExecReturn* Edge2TracObject::execute() else { beg += stp; } - Base::SequencerLauncher seq("Create waypoints", - static_cast((end - beg) / stp)); + Base::SequencerLauncher seq( + "Create waypoints", + static_cast((end - beg) / stp) + ); if (reversed) { for (; beg > end; beg += stp) { gp_Pnt P = adapt.Value(beg); @@ -179,8 +172,7 @@ App::DocumentObjectExecReturn* Edge2TracObject::execute() // R1 = ; } - Waypoint wp("Pt", - Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); + Waypoint wp("Pt", Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); trac.addWaypoint(wp); seq.next(); } @@ -194,8 +186,7 @@ App::DocumentObjectExecReturn* Edge2TracObject::execute() // here get the orientation of the start and end point... // R1 = ; } - Waypoint wp("Pt", - Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); + Waypoint wp("Pt", Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); trac.addWaypoint(wp); seq.next(); } @@ -225,8 +216,7 @@ App::DocumentObjectExecReturn* Edge2TracObject::execute() // here get the orientation of the start and end point... // R1 = ; } - Waypoint wp("Pt", - Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); + Waypoint wp("Pt", Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); trac.addWaypoint(wp); } } @@ -246,8 +236,7 @@ App::DocumentObjectExecReturn* Edge2TracObject::execute() // here get the orientation of the start and end point... // R1 = ; } - Waypoint wp("Pt", - Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); + Waypoint wp("Pt", Base::Placement(Base::Vector3d(P.X(), P.Y(), P.Z()), R1)); trac.addWaypoint(wp); } } diff --git a/src/Mod/Robot/App/Robot6Axis.cpp b/src/Mod/Robot/App/Robot6Axis.cpp index a46a4ad264..a6d0d06c75 100644 --- a/src/Mod/Robot/App/Robot6Axis.cpp +++ b/src/Mod/Robot/App/Robot6Axis.cpp @@ -74,11 +74,15 @@ void Robot6Axis::setKinematic(const AxisDefinition KinDef[6]) for (int i = 0; i < 6; i++) { - temp.addSegment(Segment(Joint(Joint::RotZ), - Frame::DH(KinDef[i].a, - Base::toRadians(KinDef[i].alpha), - KinDef[i].d, - Base::toRadians(KinDef[i].theta)))); + temp.addSegment(Segment( + Joint(Joint::RotZ), + Frame::DH( + KinDef[i].a, + Base::toRadians(KinDef[i].alpha), + KinDef[i].d, + Base::toRadians(KinDef[i].theta) + ) + )); RotDir[i] = KinDef[i].rotDir; Max(i) = Base::toRadians(KinDef[i].maxAngle); Min(i) = Base::toRadians(KinDef[i].minAngle); @@ -186,13 +190,19 @@ void Robot6Axis::Restore(XMLReader& reader) // read my Element reader.readElement("Axis"); // get the value of the placement - Tip = Base::Placement(Base::Vector3d(reader.getAttribute("Px"), - reader.getAttribute("Py"), - reader.getAttribute("Pz")), - Base::Rotation(reader.getAttribute("Q0"), - reader.getAttribute("Q1"), - reader.getAttribute("Q2"), - reader.getAttribute("Q3"))); + Tip = Base::Placement( + Base::Vector3d( + reader.getAttribute("Px"), + reader.getAttribute("Py"), + reader.getAttribute("Pz") + ), + Base::Rotation( + reader.getAttribute("Q0"), + reader.getAttribute("Q1"), + reader.getAttribute("Q2"), + reader.getAttribute("Q3") + ) + ); Temp.addSegment(Segment(Joint(Joint::RotZ), toFrame(Tip))); @@ -223,24 +233,29 @@ bool Robot6Axis::setTo(const Placement& To) // Creation of the solvers: ChainFkSolverPos_recursive fksolver1(Kinematic); // Forward position solver ChainIkSolverVel_pinv iksolver1v(Kinematic); // Inverse velocity solver - ChainIkSolverPos_NR_JL iksolver1(Kinematic, - Min, - Max, - fksolver1, - iksolver1v, - 100, - 1e-6); // Maximum 100 iterations, stop at accuracy 1e-6 + ChainIkSolverPos_NR_JL iksolver1( + Kinematic, + Min, + Max, + fksolver1, + iksolver1v, + 100, + 1e-6 + ); // Maximum 100 iterations, stop at accuracy 1e-6 // Creation of jntarrays: JntArray result(Kinematic.getNrOfJoints()); // Set destination frame - Frame F_dest = - Frame(KDL::Rotation::Quaternion(To.getRotation()[0], - To.getRotation()[1], - To.getRotation()[2], - To.getRotation()[3]), - KDL::Vector(To.getPosition()[0], To.getPosition()[1], To.getPosition()[2])); + Frame F_dest = Frame( + KDL::Rotation::Quaternion( + To.getRotation()[0], + To.getRotation()[1], + To.getRotation()[2], + To.getRotation()[3] + ), + KDL::Vector(To.getPosition()[0], To.getPosition()[1], To.getPosition()[2]) + ); // solve if (iksolver1.CartToJnt(Actual, F_dest, result) < 0) { @@ -257,8 +272,7 @@ Base::Placement Robot6Axis::getTcp() { double x, y, z, w; Tcp.M.GetQuaternion(x, y, z, w); - return Base::Placement(Base::Vector3d(Tcp.p[0], Tcp.p[1], Tcp.p[2]), - Base::Rotation(x, y, z, w)); + return Base::Placement(Base::Vector3d(Tcp.p[0], Tcp.p[1], Tcp.p[2]), Base::Rotation(x, y, z, w)); } bool Robot6Axis::calcTcp() diff --git a/src/Mod/Robot/App/Robot6AxisPyImp.cpp b/src/Mod/Robot/App/Robot6AxisPyImp.cpp index a9f59a36d4..187465fe9c 100644 --- a/src/Mod/Robot/App/Robot6AxisPyImp.cpp +++ b/src/Mod/Robot/App/Robot6AxisPyImp.cpp @@ -151,8 +151,7 @@ void Robot6AxisPy::setTcp(Py::Object value) getRobot6AxisPtr()->setTo(p); } else if (PyObject_TypeCheck(*value, &(Base::PlacementPy::Type))) { - if (!getRobot6AxisPtr()->setTo( - *static_cast(*value)->getPlacementPtr())) { + if (!getRobot6AxisPtr()->setTo(*static_cast(*value)->getPlacementPtr())) { throw Base::RuntimeError("Can not reach Point"); } } diff --git a/src/Mod/Robot/App/RobotAlgos.cpp b/src/Mod/Robot/App/RobotAlgos.cpp index 04382ff4fa..c2fbbdb780 100644 --- a/src/Mod/Robot/App/RobotAlgos.cpp +++ b/src/Mod/Robot/App/RobotAlgos.cpp @@ -85,11 +85,13 @@ void RobotAlgos::Test() // Creation of the solvers: ChainFkSolverPos_recursive fksolver1(chain); // Forward position solver ChainIkSolverVel_pinv iksolver1v(chain); // Inverse velocity solver - ChainIkSolverPos_NR iksolver1(chain, - fksolver1, - iksolver1v, - 100, - 1e-6); // Maximum 100 iterations, stop at accuracy 1e-6 + ChainIkSolverPos_NR iksolver1( + chain, + fksolver1, + iksolver1v, + 100, + 1e-6 + ); // Maximum 100 iterations, stop at accuracy 1e-6 // Creation of jntarrays: JntArray result(chain.getNrOfJoints()); diff --git a/src/Mod/Robot/App/RobotAlgos.h b/src/Mod/Robot/App/RobotAlgos.h index a5bc66f9cb..1bd53b86c0 100644 --- a/src/Mod/Robot/App/RobotAlgos.h +++ b/src/Mod/Robot/App/RobotAlgos.h @@ -47,11 +47,15 @@ public: inline KDL::Frame toFrame(const Base::Placement& To) { - return KDL::Frame(KDL::Rotation::Quaternion(To.getRotation()[0], - To.getRotation()[1], - To.getRotation()[2], - To.getRotation()[3]), - KDL::Vector(To.getPosition()[0], To.getPosition()[1], To.getPosition()[2])); + return KDL::Frame( + KDL::Rotation::Quaternion( + To.getRotation()[0], + To.getRotation()[1], + To.getRotation()[2], + To.getRotation()[3] + ), + KDL::Vector(To.getPosition()[0], To.getPosition()[1], To.getPosition()[2]) + ); } inline Base::Placement toPlacement(const KDL::Frame& To) { diff --git a/src/Mod/Robot/App/RobotObject.cpp b/src/Mod/Robot/App/RobotObject.cpp index ec80dd5281..c1c05893e0 100644 --- a/src/Mod/Robot/App/RobotObject.cpp +++ b/src/Mod/Robot/App/RobotObject.cpp @@ -37,70 +37,58 @@ PROPERTY_SOURCE(Robot::RobotObject, App::GeoFeature) RobotObject::RobotObject() { - ADD_PROPERTY_TYPE(RobotVrmlFile, - (nullptr), - "Robot definition", - Prop_None, - "Included file with the VRML representation of the robot"); - ADD_PROPERTY_TYPE(RobotKinematicFile, - (nullptr), - "Robot definition", - Prop_None, - "Included file with kinematic definition of the robot Axis"); + ADD_PROPERTY_TYPE( + RobotVrmlFile, + (nullptr), + "Robot definition", + Prop_None, + "Included file with the VRML representation of the robot" + ); + ADD_PROPERTY_TYPE( + RobotKinematicFile, + (nullptr), + "Robot definition", + Prop_None, + "Included file with kinematic definition of the robot Axis" + ); - ADD_PROPERTY_TYPE(Axis1, - (0.0), - "Robot kinematic", - Prop_None, - "Axis 1 angle of the robot in degre"); - ADD_PROPERTY_TYPE(Axis2, - (0.0), - "Robot kinematic", - Prop_None, - "Axis 2 angle of the robot in degre"); - ADD_PROPERTY_TYPE(Axis3, - (0.0), - "Robot kinematic", - Prop_None, - "Axis 3 angle of the robot in degre"); - ADD_PROPERTY_TYPE(Axis4, - (0.0), - "Robot kinematic", - Prop_None, - "Axis 4 angle of the robot in degre"); - ADD_PROPERTY_TYPE(Axis5, - (0.0), - "Robot kinematic", - Prop_None, - "Axis 5 angle of the robot in degre"); - ADD_PROPERTY_TYPE(Axis6, - (0.0), - "Robot kinematic", - Prop_None, - "Axis 6 angle of the robot in degre"); + ADD_PROPERTY_TYPE(Axis1, (0.0), "Robot kinematic", Prop_None, "Axis 1 angle of the robot in degre"); + ADD_PROPERTY_TYPE(Axis2, (0.0), "Robot kinematic", Prop_None, "Axis 2 angle of the robot in degre"); + ADD_PROPERTY_TYPE(Axis3, (0.0), "Robot kinematic", Prop_None, "Axis 3 angle of the robot in degre"); + ADD_PROPERTY_TYPE(Axis4, (0.0), "Robot kinematic", Prop_None, "Axis 4 angle of the robot in degre"); + ADD_PROPERTY_TYPE(Axis5, (0.0), "Robot kinematic", Prop_None, "Axis 5 angle of the robot in degre"); + ADD_PROPERTY_TYPE(Axis6, (0.0), "Robot kinematic", Prop_None, "Axis 6 angle of the robot in degre"); ADD_PROPERTY_TYPE(Error, (""), "Robot kinematic", Prop_None, "Robot error while moving"); ADD_PROPERTY_TYPE(Tcp, (Base::Placement()), "Robot kinematic", Prop_None, "Tcp of the robot"); - ADD_PROPERTY_TYPE(Base, - (Base::Placement()), - "Robot kinematic", - Prop_None, - "Actual base frame of the robot"); - ADD_PROPERTY_TYPE(Tool, - (Base::Placement()), - "Robot kinematic", - Prop_None, - "Tool frame of the robot (Tool)"); - ADD_PROPERTY_TYPE(ToolShape, - (nullptr), - "Robot definition", - Prop_None, - "Link to the Shape is used as Tool"); - ADD_PROPERTY_TYPE(ToolBase, - (Base::Placement()), - "Robot definition", - Prop_None, - "Defines where to connect the ToolShape"); + ADD_PROPERTY_TYPE( + Base, + (Base::Placement()), + "Robot kinematic", + Prop_None, + "Actual base frame of the robot" + ); + ADD_PROPERTY_TYPE( + Tool, + (Base::Placement()), + "Robot kinematic", + Prop_None, + "Tool frame of the robot (Tool)" + ); + ADD_PROPERTY_TYPE( + ToolShape, + (nullptr), + "Robot definition", + Prop_None, + "Link to the Shape is used as Tool" + ); + ADD_PROPERTY_TYPE( + ToolBase, + (Base::Placement()), + "Robot definition", + Prop_None, + "Defines where to connect the ToolShape" + ); // ADD_PROPERTY_TYPE(Position,(Base::Placement()),"Robot definition",Prop_None,"Position of the // robot in the simulation"); ADD_PROPERTY_TYPE(Home, (0), "Robot kinematic", Prop_None, "Axis position for home"); diff --git a/src/Mod/Robot/App/Trajectory.cpp b/src/Mod/Robot/App/Trajectory.cpp index 299c0e3e1b..03821df8cf 100644 --- a/src/Mod/Robot/App/Trajectory.cpp +++ b/src/Mod/Robot/App/Trajectory.cpp @@ -185,11 +185,13 @@ void Trajectory::generateTrajectory() pcRoundComp = std::make_unique( 3, 3, - new KDL::RotationalInterpolation_SingleAxis()); + new KDL::RotationalInterpolation_SingleAxis() + ); // the velocity of the first waypoint is used - pcVelPrf = - std::make_unique((*it)->Velocity, - (*it)->Acceleration); + pcVelPrf = std::make_unique( + (*it)->Velocity, + (*it)->Acceleration + ); pcRoundComp->Add(Last); pcRoundComp->Add(Next); @@ -204,27 +206,32 @@ void Trajectory::generateTrajectory() pcRoundComp->Add(Next); pcRoundComp->Finish(); pcVelPrf->SetProfile(0, pcRoundComp->PathLength()); - pcTrak = - std::make_unique(pcRoundComp.release(), - pcVelPrf.release()); + pcTrak = std::make_unique( + pcRoundComp.release(), + pcVelPrf.release() + ); // normal block } else if (!Cont && !pcRoundComp) { KDL::Path* pcPath; - pcPath = - new KDL::Path_Line(Last, - Next, - new KDL::RotationalInterpolation_SingleAxis(), - 1.0, - true); + pcPath = new KDL::Path_Line( + Last, + Next, + new KDL::RotationalInterpolation_SingleAxis(), + 1.0, + true + ); - pcVelPrf = - std::make_unique((*it)->Velocity, - (*it)->Acceleration); + pcVelPrf = std::make_unique( + (*it)->Velocity, + (*it)->Acceleration + ); pcVelPrf->SetProfile(0, pcPath->PathLength()); - pcTrak = std::make_unique(pcPath, - pcVelPrf.release()); + pcTrak = std::make_unique( + pcPath, + pcVelPrf.release() + ); } Last = Next; break; diff --git a/src/Mod/Robot/App/TrajectoryCompound.cpp b/src/Mod/Robot/App/TrajectoryCompound.cpp index 934e489a74..9b11a029b7 100644 --- a/src/Mod/Robot/App/TrajectoryCompound.cpp +++ b/src/Mod/Robot/App/TrajectoryCompound.cpp @@ -44,15 +44,14 @@ App::DocumentObjectExecReturn* TrajectoryCompound::execute() for (auto it : Tracs) { if (it->isDerivedFrom()) { - const std::vector& wps = - static_cast(it)->Trajectory.getValue().getWaypoints(); + const std::vector& wps + = static_cast(it)->Trajectory.getValue().getWaypoints(); for (auto wp : wps) { result.addWaypoint(*wp); } } else { - return new App::DocumentObjectExecReturn( - "Not all objects in compound are trajectories!"); + return new App::DocumentObjectExecReturn("Not all objects in compound are trajectories!"); } } diff --git a/src/Mod/Robot/App/TrajectoryDressUpObject.cpp b/src/Mod/Robot/App/TrajectoryDressUpObject.cpp index ac254fb146..523176acfc 100644 --- a/src/Mod/Robot/App/TrajectoryDressUpObject.cpp +++ b/src/Mod/Robot/App/TrajectoryDressUpObject.cpp @@ -30,16 +30,16 @@ using namespace App; PROPERTY_SOURCE(Robot::TrajectoryDressUpObject, Robot::TrajectoryObject) -const char* TrajectoryDressUpObject::ContTypeEnums[] = {"DontChange", - "Continues", - "Discontinues", - nullptr}; -const char* TrajectoryDressUpObject::AddTypeEnums[] = {"DontChange", - "UseOrientation", - "AddPosition", - "AddOrintation", - "AddPositionAndOrientation", - nullptr}; +const char* TrajectoryDressUpObject::ContTypeEnums[] + = {"DontChange", "Continues", "Discontinues", nullptr}; +const char* TrajectoryDressUpObject::AddTypeEnums[] = { + "DontChange", + "UseOrientation", + "AddPosition", + "AddOrintation", + "AddPositionAndOrientation", + nullptr +}; TrajectoryDressUpObject::TrajectoryDressUpObject() { @@ -48,27 +48,35 @@ TrajectoryDressUpObject::TrajectoryDressUpObject() ADD_PROPERTY_TYPE(Speed, (1000), "TrajectoryDressUp", Prop_None, "Speed to use"); ADD_PROPERTY_TYPE(UseSpeed, (0), "TrajectoryDressUp", Prop_None, "Switch the speed usage on"); ADD_PROPERTY_TYPE(Acceleration, (1000), "TrajectoryDressUp", Prop_None, "Acceleration to use"); - ADD_PROPERTY_TYPE(UseAcceleration, - (0), - "TrajectoryDressUp", - Prop_None, - "Switch the acceleration usage on"); - ADD_PROPERTY_TYPE(ContType, - ((long)0), - "TrajectoryDressUp", - Prop_None, - "Define the dress up of continuity"); + ADD_PROPERTY_TYPE( + UseAcceleration, + (0), + "TrajectoryDressUp", + Prop_None, + "Switch the acceleration usage on" + ); + ADD_PROPERTY_TYPE( + ContType, + ((long)0), + "TrajectoryDressUp", + Prop_None, + "Define the dress up of continuity" + ); ContType.setEnums(ContTypeEnums); - ADD_PROPERTY_TYPE(PosAdd, - (Base::Placement()), - "TrajectoryDressUp", - Prop_None, - "Position & Orientation to use"); - ADD_PROPERTY_TYPE(AddType, - ((long)0), - "TrajectoryDressUp", - Prop_None, - "How to change the Position & Orientation"); + ADD_PROPERTY_TYPE( + PosAdd, + (Base::Placement()), + "TrajectoryDressUp", + Prop_None, + "Position & Orientation to use" + ); + ADD_PROPERTY_TYPE( + AddType, + ((long)0), + "TrajectoryDressUp", + Prop_None, + "How to change the Position & Orientation" + ); AddType.setEnums(AddTypeEnums); } @@ -84,8 +92,8 @@ App::DocumentObjectExecReturn* TrajectoryDressUpObject::execute() return new App::DocumentObjectExecReturn("Linked object is not a Trajectory object"); } - const std::vector& wps = - static_cast(link)->Trajectory.getValue().getWaypoints(); + const std::vector& wps + = static_cast(link)->Trajectory.getValue().getWaypoints(); for (auto wp : wps) { Waypoint wpt = *wp; if (UseSpeed.getValue()) { diff --git a/src/Mod/Robot/App/TrajectoryObject.cpp b/src/Mod/Robot/App/TrajectoryObject.cpp index 4d2bf2da19..072aa058b3 100644 --- a/src/Mod/Robot/App/TrajectoryObject.cpp +++ b/src/Mod/Robot/App/TrajectoryObject.cpp @@ -36,16 +36,8 @@ PROPERTY_SOURCE(Robot::TrajectoryObject, App::GeoFeature) TrajectoryObject::TrajectoryObject() { - ADD_PROPERTY_TYPE(Base, - (Base::Placement()), - "Trajectory", - Prop_None, - "Base frame of the trajectory"); - ADD_PROPERTY_TYPE(Trajectory, - (Robot::Trajectory()), - "Trajectory", - Prop_None, - "Trajectory object"); + ADD_PROPERTY_TYPE(Base, (Base::Placement()), "Trajectory", Prop_None, "Base frame of the trajectory"); + ADD_PROPERTY_TYPE(Trajectory, (Robot::Trajectory()), "Trajectory", Prop_None, "Trajectory object"); } short TrajectoryObject::mustExecute() const diff --git a/src/Mod/Robot/App/TrajectoryPyImp.cpp b/src/Mod/Robot/App/TrajectoryPyImp.cpp index 70bcd7343f..30a62f8051 100644 --- a/src/Mod/Robot/App/TrajectoryPyImp.cpp +++ b/src/Mod/Robot/App/TrajectoryPyImp.cpp @@ -65,8 +65,7 @@ int TrajectoryPy::PyInit(PyObject* args, PyObject* /*kwd*/) Py::List list(pcObj); for (Py::List::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Robot::WaypointPy::Type))) { - Robot::Waypoint& wp = - *static_cast((*it).ptr())->getWaypointPtr(); + Robot::Waypoint& wp = *static_cast((*it).ptr())->getWaypointPtr(); getTrajectoryPtr()->addWaypoint(wp); } } @@ -103,8 +102,7 @@ PyObject* TrajectoryPy::insertWaypoints(PyObject* args) Py::List list(o); for (Py::List::iterator it = list.begin(); it != list.end(); ++it) { if (PyObject_TypeCheck((*it).ptr(), &(Robot::WaypointPy::Type))) { - Robot::Waypoint& wp = - *static_cast((*it).ptr())->getWaypointPtr(); + Robot::Waypoint& wp = *static_cast((*it).ptr())->getWaypointPtr(); getTrajectoryPtr()->addWaypoint(wp); } } @@ -157,8 +155,9 @@ Py::List TrajectoryPy::getWaypoints() const { Py::List list; for (unsigned int i = 0; i < getTrajectoryPtr()->getSize(); i++) { - list.append(Py::asObject( - new Robot::WaypointPy(new Robot::Waypoint(getTrajectoryPtr()->getWaypoint(i))))); + list.append( + Py::asObject(new Robot::WaypointPy(new Robot::Waypoint(getTrajectoryPtr()->getWaypoint(i)))) + ); } return list; diff --git a/src/Mod/Robot/App/Waypoint.cpp b/src/Mod/Robot/App/Waypoint.cpp index c5ebb2f16d..17d9218bdc 100644 --- a/src/Mod/Robot/App/Waypoint.cpp +++ b/src/Mod/Robot/App/Waypoint.cpp @@ -36,14 +36,16 @@ using namespace KDL; TYPESYSTEM_SOURCE(Robot::Waypoint, Base::Persistence) -Waypoint::Waypoint(const char* name, - const Base::Placement& endPos, - WaypointType type, - float velocity, - float acceleration, - bool cont, - unsigned int tool, - unsigned int base) +Waypoint::Waypoint( + const char* name, + const Base::Placement& endPos, + WaypointType type, + float velocity, + float acceleration, + bool cont, + unsigned int tool, + unsigned int base +) : Name(name) , Type(type) @@ -111,13 +113,19 @@ void Waypoint::Restore(XMLReader& reader) reader.readElement("Waypoint"); Name = reader.getAttribute("name"); // get the value of the placement - EndPos = Base::Placement(Base::Vector3d(reader.getAttribute("Px"), - reader.getAttribute("Py"), - reader.getAttribute("Pz")), - Base::Rotation(reader.getAttribute("Q0"), - reader.getAttribute("Q1"), - reader.getAttribute("Q2"), - reader.getAttribute("Q3"))); + EndPos = Base::Placement( + Base::Vector3d( + reader.getAttribute("Px"), + reader.getAttribute("Py"), + reader.getAttribute("Pz") + ), + Base::Rotation( + reader.getAttribute("Q0"), + reader.getAttribute("Q1"), + reader.getAttribute("Q2"), + reader.getAttribute("Q3") + ) + ); Velocity = (float)reader.getAttribute("vel"); Acceleration = (float)reader.getAttribute("acc"); diff --git a/src/Mod/Robot/App/Waypoint.h b/src/Mod/Robot/App/Waypoint.h index 99f4007c37..22d84db1ec 100644 --- a/src/Mod/Robot/App/Waypoint.h +++ b/src/Mod/Robot/App/Waypoint.h @@ -49,14 +49,16 @@ public: Waypoint(); /// full constructor - Waypoint(const char* name, - const Base::Placement& endPos, - WaypointType type = Waypoint::LINE, - float velocity = 2000.0, - float acceleration = 100.0, - bool cont = false, - unsigned int tool = 0, - unsigned int base = 0); + Waypoint( + const char* name, + const Base::Placement& endPos, + WaypointType type = Waypoint::LINE, + float velocity = 2000.0, + float acceleration = 100.0, + bool cont = false, + unsigned int tool = 0, + unsigned int base = 0 + ); ~Waypoint() override; diff --git a/src/Mod/Robot/App/WaypointPyImp.cpp b/src/Mod/Robot/App/WaypointPyImp.cpp index 2724b115f6..5ba2f6d313 100644 --- a/src/Mod/Robot/App/WaypointPyImp.cpp +++ b/src/Mod/Robot/App/WaypointPyImp.cpp @@ -100,19 +100,21 @@ int WaypointPy::PyInit(PyObject* args, PyObject* kwd) static const std::array kwlist {"Pos", "type", "name", "vel", "cont", "tool", "base", "acc", nullptr}; - if (!Base::Wrapped_ParseTupleAndKeywords(args, - kwd, - "O!|ssOiiiO", - kwlist, - &(Base::PlacementPy::Type), - &pos, // the placement object - &type, - &name, - &vel, - &cont, - &tool, - &base, - &acc)) { + if (!Base::Wrapped_ParseTupleAndKeywords( + args, + kwd, + "O!|ssOiiiO", + kwlist, + &(Base::PlacementPy::Type), + &pos, // the placement object + &type, + &name, + &vel, + &cont, + &tool, + &base, + &acc + )) { return -1; } diff --git a/src/Mod/Robot/Gui/Command.cpp b/src/Mod/Robot/Gui/Command.cpp index fd463e7928..f908d7ef91 100644 --- a/src/Mod/Robot/Gui/Command.cpp +++ b/src/Mod/Robot/Gui/Command.cpp @@ -65,9 +65,11 @@ void CmdRobotSetHomePos::activated(int) pcRobotObject = static_cast(filter.Result[0][0].getObject()); } else { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Robot to set home position")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Robot to set home position") + ); return; } @@ -76,18 +78,20 @@ void CmdRobotSetHomePos::activated(int) const char* n = FeatName.c_str(); openCommand("Set home"); - doCommand(Doc, - "App.activeDocument().%s.Home = " - "[App.activeDocument().%s.Axis1,App.activeDocument().%s.Axis2,App.activeDocument().%" - "s.Axis3,App.activeDocument().%s.Axis4,App.activeDocument().%s.Axis5,App." - "activeDocument().%s.Axis6]", - n, - n, - n, - n, - n, - n, - n); + doCommand( + Doc, + "App.activeDocument().%s.Home = " + "[App.activeDocument().%s.Axis1,App.activeDocument().%s.Axis2,App.activeDocument().%" + "s.Axis3,App.activeDocument().%s.Axis4,App.activeDocument().%s.Axis5,App." + "activeDocument().%s.Axis6]", + n, + n, + n, + n, + n, + n, + n + ); updateActive(); commitCommand(); } @@ -124,9 +128,11 @@ void CmdRobotRestoreHomePos::activated(int) pcRobotObject = static_cast(filter.Result[0][0].getObject()); } else { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Robot")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Robot") + ); return; } @@ -175,17 +181,19 @@ void CmdRobotConstraintAxle::activated(int) std::string KinematicPath = "Mod/Robot/Lib/Kuka/kr500_1.csv"; openCommand("Place robot"); - doCommand(Doc, - "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - RobotPath.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - KinematicPath.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + RobotPath.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + KinematicPath.c_str() + ); doCommand(Doc, "App.activeDocument().%s.Axis2 = -90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis3 = 90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis5 = 45", FeatName.c_str()); @@ -230,9 +238,11 @@ void CmdRobotSimulate::activated(int) pcTrajectoryObject = static_cast(filter.Result[1][0].getObject()); } else { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Robot and one Trajectory object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Robot and one Trajectory object.") + ); return; } @@ -240,7 +250,8 @@ void CmdRobotSimulate::activated(int) QMessageBox::warning( Gui::getMainWindow(), QObject::tr("Trajectory not valid"), - QObject::tr("You need at least two waypoints in a trajectory to simulate.")); + QObject::tr("You need at least two waypoints in a trajectory to simulate.") + ); return; } diff --git a/src/Mod/Robot/Gui/CommandExport.cpp b/src/Mod/Robot/Gui/CommandExport.cpp index 62ac369bc8..63ab4816d7 100644 --- a/src/Mod/Robot/Gui/CommandExport.cpp +++ b/src/Mod/Robot/Gui/CommandExport.cpp @@ -56,9 +56,11 @@ void CmdRobotExportKukaCompact::activated(int) unsigned int n2 = getSelection().countObjectsOfType(); if (n1 != 1 || n2 != 1) { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Robot and one Trajectory object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Robot and one Trajectory object.") + ); return; } @@ -86,20 +88,24 @@ void CmdRobotExportKukaCompact::activated(int) QStringList filter; filter << QStringLiteral("%1 (*.src)").arg(QObject::tr("KRL file")); filter << QStringLiteral("%1 (*.*)").arg(QObject::tr("All Files")); - QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), - QObject::tr("Export program"), - QString(), - filter.join(QLatin1String(";;"))); + QString fn = Gui::FileDialog::getSaveFileName( + Gui::getMainWindow(), + QObject::tr("Export program"), + QString(), + filter.join(QLatin1String(";;")) + ); if (fn.isEmpty()) { return; } doCommand(Doc, "from KukaExporter import ExportCompactSub"); - doCommand(Doc, - "ExportCompactSub(App.activeDocument().%s,App.activeDocument().%s,'%s')", - pcRobotObject->getNameInDocument(), - pcTrajectoryObject->getNameInDocument(), - (const char*)fn.toLatin1()); + doCommand( + Doc, + "ExportCompactSub(App.activeDocument().%s,App.activeDocument().%s,'%s')", + pcRobotObject->getNameInDocument(), + pcTrajectoryObject->getNameInDocument(), + (const char*)fn.toLatin1() + ); } bool CmdRobotExportKukaCompact::isActive() @@ -131,9 +137,11 @@ void CmdRobotExportKukaFull::activated(int) unsigned int n2 = getSelection().countObjectsOfType(); if (n1 != 1 || n2 != 1) { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Robot and one Trajectory object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Robot and one Trajectory object.") + ); return; } @@ -161,20 +169,24 @@ void CmdRobotExportKukaFull::activated(int) QStringList filter; filter << QStringLiteral("%1 (*.src)").arg(QObject::tr("KRL file")); filter << QStringLiteral("%1 (*.*)").arg(QObject::tr("All Files")); - QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), - QObject::tr("Export program"), - QString(), - filter.join(QLatin1String(";;"))); + QString fn = Gui::FileDialog::getSaveFileName( + Gui::getMainWindow(), + QObject::tr("Export program"), + QString(), + filter.join(QLatin1String(";;")) + ); if (fn.isEmpty()) { return; } doCommand(Doc, "from KukaExporter import ExportFullSub"); - doCommand(Doc, - "ExportFullSub(App.activeDocument().%s,App.activeDocument().%s,'%s')", - pcRobotObject->getNameInDocument(), - pcTrajectoryObject->getNameInDocument(), - (const char*)fn.toLatin1()); + doCommand( + Doc, + "ExportFullSub(App.activeDocument().%s,App.activeDocument().%s,'%s')", + pcRobotObject->getNameInDocument(), + pcTrajectoryObject->getNameInDocument(), + (const char*)fn.toLatin1() + ); } bool CmdRobotExportKukaFull::isActive() diff --git a/src/Mod/Robot/Gui/CommandInsertRobot.cpp b/src/Mod/Robot/Gui/CommandInsertRobot.cpp index 2bbe5e8839..c69ebb8a80 100644 --- a/src/Mod/Robot/Gui/CommandInsertRobot.cpp +++ b/src/Mod/Robot/Gui/CommandInsertRobot.cpp @@ -57,23 +57,23 @@ void CmdRobotInsertKukaIR500::activated(int) std::string KinematicPath = "Mod/Robot/Lib/Kuka/kr500_1.csv"; openCommand("Place robot"); - doCommand(Doc, - "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - RobotPath.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - KinematicPath.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + RobotPath.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + KinematicPath.c_str() + ); doCommand(Doc, "App.activeDocument().%s.Axis2 = -90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis3 = 90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis5 = 45", FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.Home = [0.0,-90.0,90.0,0.0,45.0,0.0]", - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().%s.Home = [0.0,-90.0,90.0,0.0,45.0,0.0]", FeatName.c_str()); updateActive(); commitCommand(); } @@ -108,17 +108,19 @@ void CmdRobotInsertKukaIR16::activated(int) std::string KinematicPath = "Mod/Robot/Lib/Kuka/kr_16.csv"; openCommand("Place robot"); - doCommand(Doc, - "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - RobotPath.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - KinematicPath.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + RobotPath.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + KinematicPath.c_str() + ); doCommand(Doc, "App.activeDocument().%s.Axis2 = -90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis3 = 90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis5 = 45", FeatName.c_str()); @@ -156,17 +158,19 @@ void CmdRobotInsertKukaIR210::activated(int) std::string KinematicPath = "Mod/Robot/Lib/Kuka/kr_210_2.csv"; openCommand("Place robot"); - doCommand(Doc, - "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - RobotPath.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - KinematicPath.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + RobotPath.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + KinematicPath.c_str() + ); doCommand(Doc, "App.activeDocument().%s.Axis2 = -90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis3 = 90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis5 = 45", FeatName.c_str()); @@ -203,17 +207,19 @@ void CmdRobotInsertKukaIR125::activated(int) std::string KinematicPath = "Mod/Robot/Lib/Kuka/kr_125.csv"; openCommand("Place robot"); - doCommand(Doc, - "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - RobotPath.c_str()); - doCommand(Doc, - "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", - FeatName.c_str(), - KinematicPath.c_str()); + doCommand(Doc, "App.activeDocument().addObject(\"Robot::RobotObject\",\"%s\")", FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.RobotVrmlFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + RobotPath.c_str() + ); + doCommand( + Doc, + "App.activeDocument().%s.RobotKinematicFile = App.getResourceDir()+\"%s\"", + FeatName.c_str(), + KinematicPath.c_str() + ); doCommand(Doc, "App.activeDocument().%s.Axis2 = -90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis3 = 90", FeatName.c_str()); doCommand(Doc, "App.activeDocument().%s.Axis5 = 45", FeatName.c_str()); @@ -246,17 +252,22 @@ CmdRobotAddToolShape::CmdRobotAddToolShape() void CmdRobotAddToolShape::activated(int) { - std::vector robots = - getSelection().getObjectsOfType(Robot::RobotObject::getClassTypeId()); - std::vector shapes = - getSelection().getObjectsOfType(Base::Type::fromName("Part::Feature")); - std::vector VRMLs = - getSelection().getObjectsOfType(Base::Type::fromName("App::VRMLObject")); + std::vector robots = getSelection().getObjectsOfType( + Robot::RobotObject::getClassTypeId() + ); + std::vector shapes = getSelection().getObjectsOfType( + Base::Type::fromName("Part::Feature") + ); + std::vector VRMLs = getSelection().getObjectsOfType( + Base::Type::fromName("App::VRMLObject") + ); if (robots.size() != 1 || (shapes.size() != 1 && VRMLs.size() != 1)) { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one robot and one shape or VRML object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one robot and one shape or VRML object.") + ); return; } @@ -270,10 +281,12 @@ void CmdRobotAddToolShape::activated(int) } openCommand("Add tool to robot"); - doCommand(Doc, - "App.activeDocument().%s.ToolShape = App.activeDocument().%s", - RoboName.c_str(), - ShapeName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.ToolShape = App.activeDocument().%s", + RoboName.c_str(), + ShapeName.c_str() + ); // doCommand(Gui,"Gui.activeDocument().hide(\"%s\")",ShapeName.c_str()); updateActive(); commitCommand(); diff --git a/src/Mod/Robot/Gui/CommandTrajectory.cpp b/src/Mod/Robot/Gui/CommandTrajectory.cpp index 2cc9e2e763..323e856ae5 100644 --- a/src/Mod/Robot/Gui/CommandTrajectory.cpp +++ b/src/Mod/Robot/Gui/CommandTrajectory.cpp @@ -64,9 +64,11 @@ void CmdRobotCreateTrajectory::activated(int) std::string FeatName = getUniqueObjectName("Trajectory"); openCommand("Create trajectory"); - doCommand(Doc, - "App.activeDocument().addObject(\"Robot::TrajectoryObject\",\"%s\")", - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject(\"Robot::TrajectoryObject\",\"%s\")", + FeatName.c_str() + ); updateActive(); commitCommand(); } @@ -100,9 +102,11 @@ void CmdRobotInsertWaypoint::activated(int) unsigned int n2 = getSelection().countObjectsOfType(); if (n1 != 1 || n2 != 1) { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Robot and one Trajectory object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Robot and one Trajectory object.") + ); return; } @@ -127,15 +131,17 @@ void CmdRobotInsertWaypoint::activated(int) std::string TrakName = pcTrajectoryObject->getNameInDocument(); openCommand("Insert waypoint"); - doCommand(Doc, - "App.activeDocument().%s.Trajectory = " - "App.activeDocument().%s.Trajectory.insertWaypoints(Robot.Waypoint(App." - "activeDocument().%s.Tcp.multiply(App.activeDocument().%s.Tool),type='LIN',name='Pt'," - "vel=_DefSpeed,cont=_DefCont,acc=_DefAcceleration,tool=1))", - TrakName.c_str(), - TrakName.c_str(), - RoboName.c_str(), - RoboName.c_str()); + doCommand( + Doc, + "App.activeDocument().%s.Trajectory = " + "App.activeDocument().%s.Trajectory.insertWaypoints(Robot.Waypoint(App." + "activeDocument().%s.Tcp.multiply(App.activeDocument().%s.Tool),type='LIN',name='Pt'," + "vel=_DefSpeed,cont=_DefCont,acc=_DefAcceleration,tool=1))", + TrakName.c_str(), + TrakName.c_str(), + RoboName.c_str(), + RoboName.c_str() + ); updateActive(); commitCommand(); } @@ -167,9 +173,11 @@ void CmdRobotInsertWaypointPreselect::activated(int) { if (getSelection().size() != 1) { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Trajectory object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Trajectory object.") + ); return; } @@ -186,9 +194,11 @@ void CmdRobotInsertWaypointPreselect::activated(int) pcTrajectoryObject = static_cast(Sel[0].pObject); } else { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select one Trajectory object.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select one Trajectory object.") + ); return; } std::string TrakName = pcTrajectoryObject->getNameInDocument(); @@ -197,22 +207,27 @@ void CmdRobotInsertWaypointPreselect::activated(int) QMessageBox::warning( Gui::getMainWindow(), QObject::tr("No preselection"), - QObject::tr("You have to hover above a geometry (Preselection) with the mouse to use " - "this command. See documentation for details.")); + QObject::tr( + "You have to hover above a geometry (Preselection) with the mouse to use " + "this command. See documentation for details." + ) + ); return; } openCommand("Insert waypoint"); - doCommand(Doc, - "App.activeDocument().%s.Trajectory = " - "App.activeDocument().%s.Trajectory.insertWaypoints(Robot.Waypoint(FreeCAD.Placement(" - "FreeCAD.Vector(%f,%f,%f)+_DefDisplacement,_DefOrientation),type='LIN',name='Pt',vel=" - "_DefSpeed,cont=_DefCont,acc=_DefAcceleration,tool=1))", - TrakName.c_str(), - TrakName.c_str(), - x, - y, - z); + doCommand( + Doc, + "App.activeDocument().%s.Trajectory = " + "App.activeDocument().%s.Trajectory.insertWaypoints(Robot.Waypoint(FreeCAD.Placement(" + "FreeCAD.Vector(%f,%f,%f)+_DefDisplacement,_DefOrientation),type='LIN',name='Pt',vel=" + "_DefSpeed,cont=_DefCont,acc=_DefAcceleration,tool=1))", + TrakName.c_str(), + TrakName.c_str(), + x, + y, + z + ); updateActive(); commitCommand(); } @@ -232,8 +247,9 @@ CmdRobotSetDefaultOrientation::CmdRobotSetDefaultOrientation() sAppModule = "Robot"; sGroup = QT_TR_NOOP("Robot"); sMenuText = QT_TR_NOOP("Set Default Orientation"); - sToolTipText = - QT_TR_NOOP("Sets the default orientation for subsequent commands for waypoint creation"); + sToolTipText = QT_TR_NOOP( + "Sets the default orientation for subsequent commands for waypoint creation" + ); sWhatsThis = "Robot_SetDefaultOrientation"; sStatusTip = sToolTipText; sPixmap = nullptr; @@ -251,12 +267,7 @@ void CmdRobotSetDefaultOrientation::activated(int) place = Dlg.getPlacement(); Base::Rotation rot = place.getRotation(); Base::Vector3d disp = place.getPosition(); - doCommand(Doc, - "_DefOrientation = FreeCAD.Rotation(%f,%f,%f,%f)", - rot[0], - rot[1], - rot[2], - rot[3]); + doCommand(Doc, "_DefOrientation = FreeCAD.Rotation(%f,%f,%f,%f)", rot[0], rot[1], rot[2], rot[3]); doCommand(Doc, "_DefDisplacement = FreeCAD.Vector(%f,%f,%f)", disp[0], disp[1], disp[2]); } } @@ -276,8 +287,10 @@ CmdRobotSetDefaultValues::CmdRobotSetDefaultValues() sAppModule = "Robot"; sGroup = QT_TR_NOOP("Robot"); sMenuText = QT_TR_NOOP("Set Default Values"); - sToolTipText = QT_TR_NOOP("Sets the default values for speed, acceleration, and continuity for " - "subsequent commands of waypoint creation"); + sToolTipText = QT_TR_NOOP( + "Sets the default values for speed, acceleration, and continuity for " + "subsequent commands of waypoint creation" + ); sWhatsThis = "Robot_SetDefaultValues"; sStatusTip = sToolTipText; sPixmap = nullptr; @@ -288,13 +301,15 @@ void CmdRobotSetDefaultValues::activated(int) { bool ok; - QString text = QInputDialog::getText(nullptr, - QObject::tr("Set default speed"), - QObject::tr("speed: (e.g. 1 m/s or 3 cm/s)"), - QLineEdit::Normal, - QStringLiteral("1 m/s"), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString text = QInputDialog::getText( + nullptr, + QObject::tr("Set default speed"), + QObject::tr("speed: (e.g. 1 m/s or 3 cm/s)"), + QLineEdit::Normal, + QStringLiteral("1 m/s"), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok && !text.isEmpty()) { doCommand(Doc, "_DefSpeed = '%s'", text.toLatin1().constData()); } @@ -302,27 +317,31 @@ void CmdRobotSetDefaultValues::activated(int) QStringList items; items << QStringLiteral("False") << QStringLiteral("True"); - QString item = QInputDialog::getItem(nullptr, - QObject::tr("Set default continuity"), - QObject::tr("continuous ?"), - items, - 0, - false, - &ok, - Qt::MSWindowsFixedSizeDialogHint); + QString item = QInputDialog::getItem( + nullptr, + QObject::tr("Set default continuity"), + QObject::tr("continuous ?"), + items, + 0, + false, + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok && !item.isEmpty()) { doCommand(Doc, "_DefCont = %s", item.toLatin1().constData()); } text.clear(); - text = QInputDialog::getText(nullptr, - QObject::tr("Set default acceleration"), - QObject::tr("acceleration: (e.g. 1 m/s^2 or 3 cm/s^2)"), - QLineEdit::Normal, - QStringLiteral("1 m/s^2"), - &ok, - Qt::MSWindowsFixedSizeDialogHint); + text = QInputDialog::getText( + nullptr, + QObject::tr("Set default acceleration"), + QObject::tr("acceleration: (e.g. 1 m/s^2 or 3 cm/s^2)"), + QLineEdit::Normal, + QStringLiteral("1 m/s^2"), + &ok, + Qt::MSWindowsFixedSizeDialogHint + ); if (ok && !text.isEmpty()) { doCommand(Doc, "_DefAcceleration = '%s'", text.toLatin1().constData()); } @@ -378,8 +397,9 @@ void CmdRobotEdge2Trac::activated(int) Gui::SelectionFilter EdgeFilter("SELECT Part::Feature SUBELEMENT Edge COUNT 1.."); if (ObjectFilter.match()) { - Robot::Edge2TracObject* EdgeObj = - static_cast(ObjectFilter.Result[0][0].getObject()); + Robot::Edge2TracObject* EdgeObj = static_cast( + ObjectFilter.Result[0][0].getObject() + ); openCommand("Edit Edge2TracObject"); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", EdgeObj->getNameInDocument()); } @@ -391,9 +411,7 @@ void CmdRobotEdge2Trac::activated(int) std::string FeatName = getUniqueObjectName("Edge2Trac"); openCommand("Create a new Edge2TracObject"); - doCommand(Doc, - "App.activeDocument().addObject('Robot::Edge2TracObject','%s')", - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject('Robot::Edge2TracObject','%s')", FeatName.c_str()); doCommand(Gui, "App.activeDocument().%s.Source = %s", FeatName.c_str(), obj_sub.c_str()); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } @@ -401,9 +419,7 @@ void CmdRobotEdge2Trac::activated(int) std::string FeatName = getUniqueObjectName("Edge2Trac"); openCommand("Create a new Edge2TracObject"); - doCommand(Doc, - "App.activeDocument().addObject('Robot::Edge2TracObject','%s')", - FeatName.c_str()); + doCommand(Doc, "App.activeDocument().addObject('Robot::Edge2TracObject','%s')", FeatName.c_str()); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } } @@ -437,29 +453,37 @@ void CmdRobotTrajectoryDressUp::activated(int) if (ObjectFilterDressUp.match()) { Robot::TrajectoryDressUpObject* Object = static_cast( - ObjectFilterDressUp.Result[0][0].getObject()); + ObjectFilterDressUp.Result[0][0].getObject() + ); openCommand("Edit Sketch"); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", Object->getNameInDocument()); } else if (ObjectFilter.match()) { std::string FeatName = getUniqueObjectName("DressUpObject"); - Robot::TrajectoryObject* Object = - static_cast(ObjectFilter.Result[0][0].getObject()); + Robot::TrajectoryObject* Object = static_cast( + ObjectFilter.Result[0][0].getObject() + ); openCommand("Create a new TrajectoryDressUp"); - doCommand(Doc, - "App.activeDocument().addObject('Robot::TrajectoryDressUpObject','%s')", - FeatName.c_str()); - doCommand(Gui, - "App.activeDocument().%s.Source = App.activeDocument().%s", - FeatName.c_str(), - Object->getNameInDocument()); + doCommand( + Doc, + "App.activeDocument().addObject('Robot::TrajectoryDressUpObject','%s')", + FeatName.c_str() + ); + doCommand( + Gui, + "App.activeDocument().%s.Source = App.activeDocument().%s", + FeatName.c_str(), + Object->getNameInDocument() + ); doCommand(Gui, "Gui.activeDocument().hide(\"%s\")", Object->getNameInDocument()); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } else { - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("Wrong selection"), - QObject::tr("Select the Trajectory which you want to dress up.")); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("Wrong selection"), + QObject::tr("Select the Trajectory which you want to dress up.") + ); return; } } @@ -491,8 +515,9 @@ void CmdRobotTrajectoryCompound::activated(int) Gui::SelectionFilter ObjectFilter("SELECT Robot::TrajectoryCompound COUNT 1"); if (ObjectFilter.match()) { - Robot::TrajectoryCompound* Object = - static_cast(ObjectFilter.Result[0][0].getObject()); + Robot::TrajectoryCompound* Object = static_cast( + ObjectFilter.Result[0][0].getObject() + ); openCommand("Edit TrajectoryCompound"); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", Object->getNameInDocument()); } @@ -500,9 +525,11 @@ void CmdRobotTrajectoryCompound::activated(int) std::string FeatName = getUniqueObjectName("TrajectoryCompound"); openCommand("Create a new TrajectoryDressUp"); - doCommand(Doc, - "App.activeDocument().addObject('Robot::TrajectoryCompound','%s')", - FeatName.c_str()); + doCommand( + Doc, + "App.activeDocument().addObject('Robot::TrajectoryCompound','%s')", + FeatName.c_str() + ); doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } } diff --git a/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp b/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp index a5cb94cdd3..a5123ac204 100644 --- a/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp +++ b/src/Mod/Robot/Gui/TaskDlgEdge2Trac.cpp @@ -45,9 +45,10 @@ TaskDlgEdge2Trac::TaskDlgEdge2Trac(Robot::Edge2TracObject* obj) , Edge2TaskObject(obj) { param = new TaskEdge2TracParameter(obj); - select = - new Gui::TaskView::TaskSelectLinkProperty("SELECT Part::Feature SUBELEMENT Edge COUNT 1..", - &(obj->Source)); + select = new Gui::TaskView::TaskSelectLinkProperty( + "SELECT Part::Feature SUBELEMENT Edge COUNT 1..", + &(obj->Source) + ); Content.push_back(param); Content.push_back(select); @@ -71,8 +72,7 @@ void TaskDlgEdge2Trac::clicked(int button) select->sendSelection2Property(); // May throw an exception which we must handle here Edge2TaskObject->execute(); - param->setEdgeAndClusterNbr(Edge2TaskObject->NbrOfEdges, - Edge2TaskObject->NbrOfCluster); + param->setEdgeAndClusterNbr(Edge2TaskObject->NbrOfEdges, Edge2TaskObject->NbrOfCluster); } else { QApplication::beep(); diff --git a/src/Mod/Robot/Gui/TaskDlgSimulate.cpp b/src/Mod/Robot/Gui/TaskDlgSimulate.cpp index 1e74d411c7..c41b1cc351 100644 --- a/src/Mod/Robot/Gui/TaskDlgSimulate.cpp +++ b/src/Mod/Robot/Gui/TaskDlgSimulate.cpp @@ -31,8 +31,10 @@ using namespace RobotGui; // TaskDialog //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TaskDlgSimulate::TaskDlgSimulate(Robot::RobotObject* pcRobotObject, - Robot::TrajectoryObject* pcTrajectoryObject) +TaskDlgSimulate::TaskDlgSimulate( + Robot::RobotObject* pcRobotObject, + Robot::TrajectoryObject* pcTrajectoryObject +) : TaskDialog() { rob = new TaskRobot6Axis(pcRobotObject); diff --git a/src/Mod/Robot/Gui/TaskDlgTrajectoryCompound.cpp b/src/Mod/Robot/Gui/TaskDlgTrajectoryCompound.cpp index ef2f72fd15..e8effdac3a 100644 --- a/src/Mod/Robot/Gui/TaskDlgTrajectoryCompound.cpp +++ b/src/Mod/Robot/Gui/TaskDlgTrajectoryCompound.cpp @@ -41,8 +41,10 @@ TaskDlgTrajectoryCompound::TaskDlgTrajectoryCompound(Robot::TrajectoryCompound* : TaskDialog() , TrajectoryCompound(obj) { - select = new Gui::TaskView::TaskSelectLinkProperty("SELECT Robot::TrajectoryObject COUNT 1..", - &(obj->Source)); + select = new Gui::TaskView::TaskSelectLinkProperty( + "SELECT Robot::TrajectoryObject COUNT 1..", + &(obj->Source) + ); Content.push_back(select); } diff --git a/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp b/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp index 08ab1a9dd6..e8de77894b 100644 --- a/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp +++ b/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp @@ -36,10 +36,7 @@ using namespace RobotGui; using namespace Gui; TaskEdge2TracParameter::TaskEdge2TracParameter(Robot::Edge2TracObject* pcObject, QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap("Robot_Edge2Trac"), - tr("TaskEdge2TracParameter"), - true, - parent) + : TaskBox(Gui::BitmapFactory().pixmap("Robot_Edge2Trac"), tr("TaskEdge2TracParameter"), true, parent) , pcObject(pcObject) , HideShowObj(nullptr) { diff --git a/src/Mod/Robot/Gui/TaskRobot6Axis.cpp b/src/Mod/Robot/Gui/TaskRobot6Axis.cpp index 02cab68bf6..584693452c 100644 --- a/src/Mod/Robot/Gui/TaskRobot6Axis.cpp +++ b/src/Mod/Robot/Gui/TaskRobot6Axis.cpp @@ -102,13 +102,15 @@ void TaskRobot6Axis::setRobot(Robot::RobotObject* pcRobotObject) ui->horizontalSlider_Axis6->setMaximum((int)Rob->getMaxAngle(5)); ui->horizontalSlider_Axis6->setMinimum((int)Rob->getMinAngle(5)); - setAxis(pcRobot->Axis1.getValue(), - pcRobot->Axis2.getValue(), - pcRobot->Axis3.getValue(), - pcRobot->Axis4.getValue(), - pcRobot->Axis5.getValue(), - pcRobot->Axis6.getValue(), - pcRobot->Tcp.getValue()); + setAxis( + pcRobot->Axis1.getValue(), + pcRobot->Axis2.getValue(), + pcRobot->Axis3.getValue(), + pcRobot->Axis4.getValue(), + pcRobot->Axis5.getValue(), + pcRobot->Axis6.getValue(), + pcRobot->Tcp.getValue() + ); viewTool(pcRobot->Tool.getValue()); } @@ -218,13 +220,15 @@ void TaskRobot6Axis::setColor(int i, float angle, QLineEdit& lineEdit) } } -void TaskRobot6Axis::setAxis(float A1, - float A2, - float A3, - float A4, - float A5, - float A6, - const Base::Placement& Tcp) +void TaskRobot6Axis::setAxis( + float A1, + float A2, + float A3, + float A4, + float A5, + float A6, + const Base::Placement& Tcp +) { ui->horizontalSlider_Axis1->setSliderPosition((int)A1); ui->lineEdit_Axis1->setText(QStringLiteral("%1°").arg(A1, 0, 'f', 1)); diff --git a/src/Mod/Robot/Gui/TaskRobot6Axis.h b/src/Mod/Robot/Gui/TaskRobot6Axis.h index 40cab83691..197a25d984 100644 --- a/src/Mod/Robot/Gui/TaskRobot6Axis.h +++ b/src/Mod/Robot/Gui/TaskRobot6Axis.h @@ -55,8 +55,7 @@ public: void setRobot(Robot::RobotObject* pcRobotObject); public Q_SLOTS: - void - setAxis(float A1, float A2, float A3, float A4, float A5, float A6, const Base::Placement& Tcp); + void setAxis(float A1, float A2, float A3, float A4, float A5, float A6, const Base::Placement& Tcp); void changeSliderA1(int value); void changeSliderA2(int value); void changeSliderA3(int value); diff --git a/src/Mod/Robot/Gui/TaskRobotControl.cpp b/src/Mod/Robot/Gui/TaskRobotControl.cpp index 1a955248f1..6b5c6d1723 100644 --- a/src/Mod/Robot/Gui/TaskRobotControl.cpp +++ b/src/Mod/Robot/Gui/TaskRobotControl.cpp @@ -31,10 +31,7 @@ using namespace RobotGui; using namespace Gui; TaskRobotControl::TaskRobotControl(Robot::RobotObject* pcRobotObject, QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap("Robot_CreateRobot"), - tr("TaskRobotControl"), - true, - parent) + : TaskBox(Gui::BitmapFactory().pixmap("Robot_CreateRobot"), tr("TaskRobotControl"), true, parent) , pcRobot(pcRobotObject) { // we need a separate container widget to add all controls to diff --git a/src/Mod/Robot/Gui/TaskTrajectory.cpp b/src/Mod/Robot/Gui/TaskTrajectory.cpp index a284169367..53f593bcd3 100644 --- a/src/Mod/Robot/Gui/TaskTrajectory.cpp +++ b/src/Mod/Robot/Gui/TaskTrajectory.cpp @@ -32,9 +32,11 @@ using namespace RobotGui; using namespace Gui; -TaskTrajectory::TaskTrajectory(Robot::RobotObject* pcRobotObject, - Robot::TrajectoryObject* pcTrajectoryObject, - QWidget* parent) +TaskTrajectory::TaskTrajectory( + Robot::RobotObject* pcRobotObject, + Robot::TrajectoryObject* pcTrajectoryObject, + QWidget* parent +) : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Trajectory"), true, parent) , sim(pcTrajectoryObject->Trajectory.getValue(), pcRobotObject->getRobot()) , pcRobot(pcRobotObject) @@ -79,9 +81,7 @@ TaskTrajectory::TaskTrajectory(Robot::RobotObject* pcRobotObject, ui->trajectoryTable->setItem(i, 0, new QTableWidgetItem(QStringLiteral("UNDEF"))); break; } - ui->trajectoryTable->setItem(i, - 1, - new QTableWidgetItem(QString::fromUtf8(pt.Name.c_str()))); + ui->trajectoryTable->setItem(i, 1, new QTableWidgetItem(QString::fromUtf8(pt.Name.c_str()))); if (pt.Cont) { ui->trajectoryTable->setItem(i, 2, new QTableWidgetItem(QStringLiteral("|"))); } @@ -114,7 +114,8 @@ TaskTrajectory::TaskTrajectory(Robot::RobotObject* pcRobotObject, // get the view provider ViewProv = freecad_cast( - Gui::Application::Instance->activeDocument()->getViewProvider(pcRobotObject)); + Gui::Application::Instance->activeDocument()->getViewProvider(pcRobotObject) + ); setTo(); } @@ -150,20 +151,24 @@ void TaskTrajectory::setTo() else { sim.setToTime(timePos); } - ViewProv->setAxisTo(sim.Axis[0], - sim.Axis[1], - sim.Axis[2], - sim.Axis[3], - sim.Axis[4], - sim.Axis[5], - sim.Rob.getTcp()); - Q_EMIT axisChanged(sim.Axis[0], - sim.Axis[1], - sim.Axis[2], - sim.Axis[3], - sim.Axis[4], - sim.Axis[5], - sim.Rob.getTcp()); + ViewProv->setAxisTo( + sim.Axis[0], + sim.Axis[1], + sim.Axis[2], + sim.Axis[3], + sim.Axis[4], + sim.Axis[5], + sim.Rob.getTcp() + ); + Q_EMIT axisChanged( + sim.Axis[0], + sim.Axis[1], + sim.Axis[2], + sim.Axis[3], + sim.Axis[4], + sim.Axis[5], + sim.Rob.getTcp() + ); viewTool(sim.Rob.getTcp()); } diff --git a/src/Mod/Robot/Gui/TaskTrajectory.h b/src/Mod/Robot/Gui/TaskTrajectory.h index 9112bbbd40..c81b1155db 100644 --- a/src/Mod/Robot/Gui/TaskTrajectory.h +++ b/src/Mod/Robot/Gui/TaskTrajectory.h @@ -52,13 +52,17 @@ class TaskTrajectory: public Gui::TaskView::TaskBox Q_OBJECT public: - TaskTrajectory(Robot::RobotObject* pcRobotObject, - Robot::TrajectoryObject* pcTrajectoryObject, - QWidget* parent = nullptr); + TaskTrajectory( + Robot::RobotObject* pcRobotObject, + Robot::TrajectoryObject* pcTrajectoryObject, + QWidget* parent = nullptr + ); ~TaskTrajectory() override; /// Observer message from the Selection - void OnChange(Gui::SelectionSingleton::SubjectType& rCaller, - Gui::SelectionSingleton::MessageType Reason); + void OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason + ); private Q_SLOTS: void start(); @@ -73,13 +77,7 @@ private Q_SLOTS: void valueChanged(double d); Q_SIGNALS: - void axisChanged(float A1, - float A2, - float A3, - float A4, - float A5, - float A6, - const Base::Placement& Tcp); + void axisChanged(float A1, float A2, float A3, float A4, float A5, float A6, const Base::Placement& Tcp); protected: void setTo(); diff --git a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp index 308ba848e3..24f33d9707 100644 --- a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp +++ b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp @@ -34,12 +34,11 @@ using namespace RobotGui; using namespace Gui; -TaskTrajectoryDressUpParameter::TaskTrajectoryDressUpParameter(Robot::TrajectoryDressUpObject* obj, - QWidget* parent) - : TaskBox(Gui::BitmapFactory().pixmap("Robot_TrajectoryDressUp"), - tr("Dress Up Parameter"), - true, - parent) +TaskTrajectoryDressUpParameter::TaskTrajectoryDressUpParameter( + Robot::TrajectoryDressUpObject* obj, + QWidget* parent +) + : TaskBox(Gui::BitmapFactory().pixmap("Robot_TrajectoryDressUp"), tr("Dress Up Parameter"), true, parent) , pcObject(obj) { // we need a separate container widget to add all controls to @@ -61,10 +60,12 @@ TaskTrajectoryDressUpParameter::TaskTrajectoryDressUpParameter(Robot::Trajectory PosAdd = pcObject->PosAdd.getValue(); viewPlacement(); - QObject::connect(ui->toolButtonChoosePlacement, - &QToolButton::clicked, - this, - &TaskTrajectoryDressUpParameter::createPlacementDlg); + QObject::connect( + ui->toolButtonChoosePlacement, + &QToolButton::clicked, + this, + &TaskTrajectoryDressUpParameter::createPlacementDlg + ); } diff --git a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h index 5a857b75be..87873dc19f 100644 --- a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h +++ b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h @@ -36,8 +36,10 @@ class TaskTrajectoryDressUpParameter: public Gui::TaskView::TaskBox Q_OBJECT public: - explicit TaskTrajectoryDressUpParameter(Robot::TrajectoryDressUpObject* obj, - QWidget* parent = nullptr); + explicit TaskTrajectoryDressUpParameter( + Robot::TrajectoryDressUpObject* obj, + QWidget* parent = nullptr + ); ~TaskTrajectoryDressUpParameter() override; /// this methode write the values from the Gui to the object, usually in accept() diff --git a/src/Mod/Robot/Gui/TrajectorySimulate.cpp b/src/Mod/Robot/Gui/TrajectorySimulate.cpp index 0fb09f788e..a51ad65d30 100644 --- a/src/Mod/Robot/Gui/TrajectorySimulate.cpp +++ b/src/Mod/Robot/Gui/TrajectorySimulate.cpp @@ -34,9 +34,11 @@ using namespace RobotGui; using namespace Gui; -TrajectorySimulate::TrajectorySimulate(Robot::RobotObject* pcRobotObject, - Robot::TrajectoryObject* pcTrajectoryObject, - QWidget* parent) +TrajectorySimulate::TrajectorySimulate( + Robot::RobotObject* pcRobotObject, + Robot::TrajectoryObject* pcTrajectoryObject, + QWidget* parent +) : QDialog(parent) , sim(pcTrajectoryObject->Trajectory.getValue(), pcRobotObject->getRobot()) , Run(false) @@ -76,9 +78,7 @@ TrajectorySimulate::TrajectorySimulate(Robot::RobotObject* pcRobotObject, ui->trajectoryTable->setItem(i, 0, new QTableWidgetItem(QStringLiteral("UNDEF"))); break; } - ui->trajectoryTable->setItem(i, - 1, - new QTableWidgetItem(QString::fromUtf8(pt.Name.c_str()))); + ui->trajectoryTable->setItem(i, 1, new QTableWidgetItem(QString::fromUtf8(pt.Name.c_str()))); if (pt.Cont) { ui->trajectoryTable->setItem(i, 2, new QTableWidgetItem(QStringLiteral("|"))); } @@ -109,7 +109,8 @@ TrajectorySimulate::TrajectorySimulate(Robot::RobotObject* pcRobotObject, // get the view provider ViewProv = static_cast( - Gui::Application::Instance->activeDocument()->getViewProvider(pcRobotObject)); + Gui::Application::Instance->activeDocument()->getViewProvider(pcRobotObject) + ); setTo(); } @@ -119,13 +120,15 @@ TrajectorySimulate::~TrajectorySimulate() = default; void TrajectorySimulate::setTo() { sim.setToTime(timePos); - ViewProv->setAxisTo(sim.Axis[0], - sim.Axis[1], - sim.Axis[2], - sim.Axis[3], - sim.Axis[4], - sim.Axis[5], - sim.Rob.getTcp()); + ViewProv->setAxisTo( + sim.Axis[0], + sim.Axis[1], + sim.Axis[2], + sim.Axis[3], + sim.Axis[4], + sim.Axis[5], + sim.Rob.getTcp() + ); } void TrajectorySimulate::start() diff --git a/src/Mod/Robot/Gui/TrajectorySimulate.h b/src/Mod/Robot/Gui/TrajectorySimulate.h index 866c4d2f04..a4ee3fe5e4 100644 --- a/src/Mod/Robot/Gui/TrajectorySimulate.h +++ b/src/Mod/Robot/Gui/TrajectorySimulate.h @@ -43,9 +43,11 @@ class TrajectorySimulate: public QDialog Q_OBJECT public: - TrajectorySimulate(Robot::RobotObject* pcRobotObject, - Robot::TrajectoryObject* pcTrajectoryObject, - QWidget* parent = nullptr); + TrajectorySimulate( + Robot::RobotObject* pcRobotObject, + Robot::TrajectoryObject* pcTrajectoryObject, + QWidget* parent = nullptr + ); ~TrajectorySimulate() override; private Q_SLOTS: diff --git a/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp b/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp index 8422ccef7f..761ffd9291 100644 --- a/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp +++ b/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp @@ -88,12 +88,11 @@ void ViewProviderRobotObject::setDragger() Robot::RobotObject* robObj = static_cast(pcObject); Base::Placement loc = robObj->Tcp.getValue(); SbMatrix M; - M.setTransform(SbVec3f(loc.getPosition().x, loc.getPosition().y, loc.getPosition().z), - SbRotation(loc.getRotation()[0], - loc.getRotation()[1], - loc.getRotation()[2], - loc.getRotation()[3]), - SbVec3f(150, 150, 150)); + M.setTransform( + SbVec3f(loc.getPosition().x, loc.getPosition().y, loc.getPosition().z), + SbRotation(loc.getRotation()[0], loc.getRotation()[1], loc.getRotation()[2], loc.getRotation()[3]), + SbVec3f(150, 150, 150) + ); pcDragger->setMotionMatrix(M); } @@ -263,105 +262,140 @@ void ViewProviderRobotObject::updateData(const App::Property* prop) } } if (Axis1Node) { - Axis1Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis1.getValue())); + Axis1Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis1.getValue()) + ); } if (Axis2Node) { - Axis2Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis2.getValue())); + Axis2Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis2.getValue()) + ); } if (Axis3Node) { - Axis3Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis3.getValue())); + Axis3Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis3.getValue()) + ); } if (Axis4Node) { - Axis4Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis4.getValue())); + Axis4Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis4.getValue()) + ); } if (Axis5Node) { - Axis5Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis5.getValue())); + Axis5Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis5.getValue()) + ); } if (Axis6Node) { - Axis6Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis6.getValue())); + Axis6Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis6.getValue()) + ); } } else if (prop == &robObj->Axis1) { if (Axis1Node) { - Axis1Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis1.getValue())); + Axis1Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis1.getValue()) + ); if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } } else if (prop == &robObj->Axis2) { if (Axis2Node) { - Axis2Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis2.getValue())); + Axis2Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis2.getValue()) + ); if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } } else if (prop == &robObj->Axis3) { if (Axis3Node) { - Axis3Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis3.getValue())); + Axis3Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis3.getValue()) + ); if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } } else if (prop == &robObj->Axis4) { if (Axis4Node) { - Axis4Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis4.getValue())); + Axis4Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis4.getValue()) + ); if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } } else if (prop == &robObj->Axis5) { if (Axis5Node) { - Axis5Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis5.getValue())); + Axis5Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis5.getValue()) + ); if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } } else if (prop == &robObj->Axis6) { if (Axis6Node) { - Axis6Node->rotation.setValue(SbVec3f(0.0, 1.0, 0.0), - Base::toRadians(robObj->Axis6.getValue())); + Axis6Node->rotation.setValue( + SbVec3f(0.0, 1.0, 0.0), + Base::toRadians(robObj->Axis6.getValue()) + ); if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } } else if (prop == &robObj->Tcp) { Base::Placement loc = robObj->Tcp.getValue(); SbMatrix M; - M.setTransform(SbVec3f(loc.getPosition().x, loc.getPosition().y, loc.getPosition().z), - SbRotation(loc.getRotation()[0], - loc.getRotation()[1], - loc.getRotation()[2], - loc.getRotation()[3]), - SbVec3f(150, 150, 150)); + M.setTransform( + SbVec3f(loc.getPosition().x, loc.getPosition().y, loc.getPosition().z), + SbRotation( + loc.getRotation()[0], + loc.getRotation()[1], + loc.getRotation()[2], + loc.getRotation()[3] + ), + SbVec3f(150, 150, 150) + ); if (pcDragger) { pcDragger->setMotionMatrix(M); } if (toolShape) { toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } } else if (prop == &robObj->ToolShape) { @@ -370,20 +404,23 @@ void ViewProviderRobotObject::updateData(const App::Property* prop) if (o && (o->isDerivedFrom() || o->isDerivedFrom())) { toolShape = Gui::Application::Instance->getViewProvider(o); toolShape->setTransformation( - (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix()); + (robObj->Tcp.getValue() * (robObj->ToolBase.getValue().inverse())).toMatrix() + ); } else { toolShape = nullptr; } } } -void ViewProviderRobotObject::setAxisTo(float A1, - float A2, - float A3, - float A4, - float A5, - float A6, - const Base::Placement& Tcp) +void ViewProviderRobotObject::setAxisTo( + float A1, + float A2, + float A3, + float A4, + float A5, + float A6, + const Base::Placement& Tcp +) { Robot::RobotObject* robObj = static_cast(pcObject); diff --git a/src/Mod/Robot/Gui/ViewProviderRobotObject.h b/src/Mod/Robot/Gui/ViewProviderRobotObject.h index a865eed01c..62af4db1fd 100644 --- a/src/Mod/Robot/Gui/ViewProviderRobotObject.h +++ b/src/Mod/Robot/Gui/ViewProviderRobotObject.h @@ -58,13 +58,7 @@ public: void onChanged(const App::Property* prop) override; /// for simulation without changing the document: - void setAxisTo(float A1, - float A2, - float A3, - float A4, - float A5, - float A6, - const Base::Placement& Tcp); + void setAxisTo(float A1, float A2, float A3, float A4, float A5, float A6, const Base::Placement& Tcp); protected: static void sDraggerMotionCallback(void* data, SoDragger* dragger); diff --git a/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp b/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp index 3da814e95d..0d63653691 100644 --- a/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp +++ b/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp @@ -93,7 +93,8 @@ void ViewProviderTrajectory::attach(App::DocumentObject* pcObj) "CROSS", App::GetApplication() .GetParameterGroupByPath("User parameter:BaseApp/Preferences/View") - ->GetInt("MarkerSize", 5)); + ->GetInt("MarkerSize", 5) + ); linesep->addChild(markcol); linesep->addChild(marker); diff --git a/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp b/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp index bb2ca67f41..664f1317bb 100644 --- a/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp +++ b/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp @@ -44,8 +44,9 @@ PROPERTY_SOURCE(RobotGui::ViewProviderTrajectoryCompound, RobotGui::ViewProvider bool ViewProviderTrajectoryCompound::setEdit(int) { - Gui::TaskView::TaskDialog* dlg = - new TaskDlgTrajectoryCompound(getObject()); + Gui::TaskView::TaskDialog* dlg = new TaskDlgTrajectoryCompound( + getObject() + ); Gui::Control().showDialog(dlg); return true; } diff --git a/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp b/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp index 03e22f808b..0d6959d90f 100644 --- a/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp +++ b/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp @@ -43,8 +43,9 @@ PROPERTY_SOURCE(RobotGui::ViewProviderTrajectoryDressUp, RobotGui::ViewProviderT bool ViewProviderTrajectoryDressUp::setEdit(int) { - Gui::TaskView::TaskDialog* dlg = - new TaskDlgTrajectoryDressUp(getObject()); + Gui::TaskView::TaskDialog* dlg = new TaskDlgTrajectoryDressUp( + getObject() + ); Gui::Control().showDialog(dlg); return true; } diff --git a/src/Mod/Robot/Gui/Workbench.cpp b/src/Mod/Robot/Gui/Workbench.cpp index 227b1cecde..a989eeadbd 100644 --- a/src/Mod/Robot/Gui/Workbench.cpp +++ b/src/Mod/Robot/Gui/Workbench.cpp @@ -67,12 +67,18 @@ void Workbench::activated() if (!fi.exists()) { Gui::WaitCursor wc; wc.restoreCursor(); - QMessageBox::warning(Gui::getMainWindow(), - QObject::tr("No robot files installed"), - QObject::tr("Visit %1 and copy the robot VRML and CSV files to %2") - .arg(QStringLiteral("https://www.kuka.com/en-us/services/downloads" - "/src/Mod/Robot/Lib/Kuka"), - dir)); + QMessageBox::warning( + Gui::getMainWindow(), + QObject::tr("No robot files installed"), + QObject::tr("Visit %1 and copy the robot VRML and CSV files to %2") + .arg( + QStringLiteral( + "https://www.kuka.com/en-us/services/downloads" + "/src/Mod/Robot/Lib/Kuka" + ), + dir + ) + ); wc.setWaitCursor(); } @@ -80,16 +86,15 @@ void Workbench::activated() const char* RobotAndTrac[] = {"Robot_InsertWaypoint", "Robot_InsertWaypointPreselect", nullptr}; - const char* Robot[] = {"Robot_AddToolShape", - "Robot_SetHomePos", - "Robot_RestoreHomePos", - nullptr}; + const char* Robot[] = {"Robot_AddToolShape", "Robot_SetHomePos", "Robot_RestoreHomePos", nullptr}; - const char* Empty[] = {"Robot_InsertKukaIR500", - "Robot_InsertKukaIR16", - "Robot_InsertKukaIR210", - "Robot_InsertKukaIR125", - nullptr}; + const char* Empty[] = { + "Robot_InsertKukaIR500", + "Robot_InsertKukaIR16", + "Robot_InsertKukaIR210", + "Robot_InsertKukaIR125", + nullptr + }; const char* TracSingle[] = {"Robot_TrajectoryDressUp", nullptr}; @@ -97,34 +102,40 @@ void Workbench::activated() std::vector Watcher; - Watcher.push_back( - new Gui::TaskView::TaskWatcherCommands("SELECT Robot::TrajectoryObject COUNT 1" - "SELECT Robot::RobotObject COUNT 1", - RobotAndTrac, - "Trajectory Tools", - "Robot_InsertWaypoint")); + Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( + "SELECT Robot::TrajectoryObject COUNT 1" + "SELECT Robot::RobotObject COUNT 1", + RobotAndTrac, + "Trajectory Tools", + "Robot_InsertWaypoint" + )); Watcher.push_back(new TaskWatcherRobot); - Watcher.push_back(new Gui::TaskView::TaskWatcherCommands("SELECT Robot::RobotObject COUNT 1", - Robot, - "Robot Tools", - "Robot_CreateRobot")); + Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( + "SELECT Robot::RobotObject COUNT 1", + Robot, + "Robot Tools", + "Robot_CreateRobot" + )); + + Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( + "SELECT Robot::TrajectoryObject COUNT 1", + TracSingle, + "Trajectory Tools", + "Robot_CreateRobot" + )); + + Watcher.push_back(new Gui::TaskView::TaskWatcherCommands( + "SELECT Robot::TrajectoryObject COUNT 2..", + TracMore, + "Trajectory Tools", + "Robot_CreateRobot" + )); Watcher.push_back( - new Gui::TaskView::TaskWatcherCommands("SELECT Robot::TrajectoryObject COUNT 1", - TracSingle, - "Trajectory Tools", - "Robot_CreateRobot")); - - Watcher.push_back( - new Gui::TaskView::TaskWatcherCommands("SELECT Robot::TrajectoryObject COUNT 2..", - TracMore, - "Trajectory Tools", - "Robot_CreateRobot")); - - Watcher.push_back( - new Gui::TaskView::TaskWatcherCommandsEmptyDoc(Empty, "Insert Robot", "Robot_CreateRobot")); + new Gui::TaskView::TaskWatcherCommandsEmptyDoc(Empty, "Insert Robot", "Robot_CreateRobot") + ); addTaskWatcher(Watcher); diff --git a/src/Mod/Robot/RobotGlobal.h b/src/Mod/Robot/RobotGlobal.h index 7830659c0e..c65084d98d 100644 --- a/src/Mod/Robot/RobotGlobal.h +++ b/src/Mod/Robot/RobotGlobal.h @@ -27,20 +27,20 @@ // Robot #ifndef RobotExport -#ifdef Robot_EXPORTS -#define RobotExport FREECAD_DECL_EXPORT -#else -#define RobotExport FREECAD_DECL_IMPORT -#endif +# ifdef Robot_EXPORTS +# define RobotExport FREECAD_DECL_EXPORT +# else +# define RobotExport FREECAD_DECL_IMPORT +# endif #endif // RobotGui #ifndef RobotGuiExport -#ifdef RobotGui_EXPORTS -#define RobotGuiExport FREECAD_DECL_EXPORT -#else -#define RobotGuiExport FREECAD_DECL_IMPORT -#endif +# ifdef RobotGui_EXPORTS +# define RobotGuiExport FREECAD_DECL_EXPORT +# else +# define RobotGuiExport FREECAD_DECL_IMPORT +# endif #endif #endif // ROBOT_GLOBAL_H diff --git a/src/Mod/Sketcher/App/AppSketcher.cpp b/src/Mod/Sketcher/App/AppSketcher.cpp index f77d2dee7c..d130c64598 100644 --- a/src/Mod/Sketcher/App/AppSketcher.cpp +++ b/src/Mod/Sketcher/App/AppSketcher.cpp @@ -64,18 +64,22 @@ PyMOD_INIT_FUNC(Sketcher) // Add Types to module Base::Interpreter().addType(&Sketcher::ConstraintPy ::Type, sketcherModule, "Constraint"); Base::Interpreter().addType(&Sketcher::SketchPy ::Type, sketcherModule, "Sketch"); - Base::Interpreter().addType(&Sketcher::ExternalGeometryExtensionPy ::Type, - sketcherModule, - "ExternalGeometryExtension"); - Base::Interpreter().addType(&Sketcher::SketchGeometryExtensionPy ::Type, - sketcherModule, - "SketchGeometryExtension"); - Base::Interpreter().addType(&Sketcher::GeometryFacadePy ::Type, - sketcherModule, - "GeometryFacade"); - Base::Interpreter().addType(&Sketcher::ExternalGeometryFacadePy ::Type, - sketcherModule, - "ExternalGeometryFacade"); + Base::Interpreter().addType( + &Sketcher::ExternalGeometryExtensionPy ::Type, + sketcherModule, + "ExternalGeometryExtension" + ); + Base::Interpreter().addType( + &Sketcher::SketchGeometryExtensionPy ::Type, + sketcherModule, + "SketchGeometryExtension" + ); + Base::Interpreter().addType(&Sketcher::GeometryFacadePy ::Type, sketcherModule, "GeometryFacade"); + Base::Interpreter().addType( + &Sketcher::ExternalGeometryFacadePy ::Type, + sketcherModule, + "ExternalGeometryFacade" + ); // NOTE: To finish the initialization of our own type objects we must diff --git a/src/Mod/Sketcher/App/Constraint.cpp b/src/Mod/Sketcher/App/Constraint.cpp index 3d78ef1d35..ba5b2e73c2 100644 --- a/src/Mod/Sketcher/App/Constraint.cpp +++ b/src/Mod/Sketcher/App/Constraint.cpp @@ -173,16 +173,11 @@ void Constraint::Save(Writer& writer) const << "ThirdPos=\"" << getElement(2).posIdAsInt() << "\" "; #if SKETCHER_CONSTRAINT_USE_LEGACY_ELEMENTS auto elements = std::views::iota(size_t {0}, this->elements.size()) - | std::views::transform([&](size_t i) { - return getElement(i); - }); + | std::views::transform([&](size_t i) { return getElement(i); }); #endif - auto geoIds = elements | std::views::transform([](const GeoElementId& e) { - return e.GeoId; - }); - auto posIds = elements | std::views::transform([](const GeoElementId& e) { - return e.posIdAsInt(); - }); + auto geoIds = elements | std::views::transform([](const GeoElementId& e) { return e.GeoId; }); + auto posIds = elements + | std::views::transform([](const GeoElementId& e) { return e.posIdAsInt(); }); const std::string ids = fmt::format("{}", fmt::join(geoIds, " ")); const std::string positions = fmt::format("{}", fmt::join(posIds, " ")); @@ -252,9 +247,7 @@ void Constraint::Restore(XMLReader& reader) } return token; }) - | std::views::filter([](const std::string& s) { - return !s.empty(); - }); + | std::views::filter([](const std::string& s) { return !s.empty(); }); return std::vector(tokens.begin(), tokens.end()); }; @@ -266,10 +259,14 @@ void Constraint::Restore(XMLReader& reader) const auto positions = splitAndClean(elementPositions); if (ids.size() != positions.size()) { - throw Base::ParserError(fmt::format("ElementIds and ElementPositions do not match in " - "size. Got {} ids and {} positions.", - ids.size(), - positions.size())); + throw Base::ParserError( + fmt::format( + "ElementIds and ElementPositions do not match in " + "size. Got {} ids and {} positions.", + ids.size(), + positions.size() + ) + ); } elements.clear(); @@ -322,10 +319,7 @@ void Constraint::substituteIndex(int fromGeoId, int toGeoId) #endif } -void Constraint::substituteIndexAndPos(int fromGeoId, - PointPos fromPosId, - int toGeoId, - PointPos toPosId) +void Constraint::substituteIndexAndPos(int fromGeoId, PointPos fromPosId, int toGeoId, PointPos toPosId) { const GeoElementId from {fromGeoId, fromPosId}; @@ -358,10 +352,8 @@ std::string Constraint::internalAlignmentTypeToString(InternalAlignmentType alig bool Constraint::involvesGeoId(int geoId) const { #if SKETCHER_CONSTRAINT_USE_LEGACY_ELEMENTS - auto elements = - std::views::iota(size_t {0}, this->elements.size()) | std::views::transform([&](size_t i) { - return getElement(i); - }); + auto elements = std::views::iota(size_t {0}, this->elements.size()) + | std::views::transform([&](size_t i) { return getElement(i); }); #endif return std::ranges::any_of(elements, [geoId](const auto& element) { return element.GeoId == geoId; @@ -371,10 +363,8 @@ bool Constraint::involvesGeoId(int geoId) const bool Constraint::involvesGeoIdAndPosId(int geoId, PointPos posId) const { #if SKETCHER_CONSTRAINT_USE_LEGACY_ELEMENTS - auto elements = - std::views::iota(size_t {0}, this->elements.size()) | std::views::transform([&](size_t i) { - return getElement(i); - }); + auto elements = std::views::iota(size_t {0}, this->elements.size()) + | std::views::transform([&](size_t i) { return getElement(i); }); #endif return std::ranges::find(elements, GeoElementId(geoId, posId)) != elements.end(); } diff --git a/src/Mod/Sketcher/App/Constraint.h b/src/Mod/Sketcher/App/Constraint.h index c8595845a4..aa3cc59dea 100644 --- a/src/Mod/Sketcher/App/Constraint.h +++ b/src/Mod/Sketcher/App/Constraint.h @@ -192,18 +192,20 @@ private: // clang-format on constexpr static std::array - internalAlignmentType2str {{"Undef", - "EllipseMajorDiameter", - "EllipseMinorDiameter", - "EllipseFocus1", - "EllipseFocus2", - "HyperbolaMajor", - "HyperbolaMinor", - "HyperbolaFocus", - "ParabolaFocus", - "BSplineControlPoint", - "BSplineKnotPoint", - "ParabolaFocalAxis"}}; + internalAlignmentType2str { + {"Undef", + "EllipseMajorDiameter", + "EllipseMinorDiameter", + "EllipseFocus1", + "EllipseFocus2", + "HyperbolaMajor", + "HyperbolaMinor", + "HyperbolaFocus", + "ParabolaFocus", + "BSplineControlPoint", + "BSplineKnotPoint", + "ParabolaFocalAxis"} + }; public: ConstraintType Type {None}; diff --git a/src/Mod/Sketcher/App/ConstraintPyImp.cpp b/src/Mod/Sketcher/App/ConstraintPyImp.cpp index 64077f1617..017cef571c 100644 --- a/src/Mod/Sketcher/App/ConstraintPyImp.cpp +++ b/src/Mod/Sketcher/App/ConstraintPyImp.cpp @@ -47,8 +47,10 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) // The first argument must be a string (the constraint type). PyObject* typeObj = PyTuple_GetItem(args, 0); if (!PyUnicode_Check(typeObj)) { - PyErr_SetString(PyExc_TypeError, - "First argument to Constraint must be a string (the constraint type)"); + PyErr_SetString( + PyExc_TypeError, + "First argument to Constraint must be a string (the constraint type)" + ); return -1; } @@ -65,12 +67,14 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) // The most critical check is for non-numeric types being passed for an index. if (Py_TYPE(current_arg)->tp_as_number == NULL && !PyBool_Check(current_arg) && !PyList_Check(current_arg)) { - PyErr_Format(PyExc_TypeError, - "Invalid argument type for Constraint. " - "Expected an integer for a geometry or point index, but got type '%s' at " - "argument %d.", - Py_TYPE(current_arg)->tp_name, - i + 1); + PyErr_Format( + PyExc_TypeError, + "Invalid argument type for Constraint. " + "Expected an integer for a geometry or point index, but got type '%s' at " + "argument %d.", + Py_TYPE(current_arg)->tp_name, + i + 1 + ); return -1; } } @@ -195,8 +199,9 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } else if (strcmp("Angle", ConstraintType) == 0) { if (PyObject_TypeCheck(index_or_value, &(Base::QuantityPy::Type))) { - Base::Quantity q = - *(static_cast(index_or_value)->getQuantityPtr()); + Base::Quantity q = *( + static_cast(index_or_value)->getQuantityPtr() + ); if (q.getUnit() == Base::Unit::Angle) { Value = q.getValueAs(Base::Quantity::Radian); } @@ -255,13 +260,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siOOO", - &ConstraintType, - &FirstIndex, - &index_or_value, - &activated, - &driving)) { + if (PyArg_ParseTuple(args, "siOOO", &ConstraintType, &FirstIndex, &index_or_value, &activated, &driving)) { if (PyBool_Check(activated) && PyBool_Check(driving)) { if (handleSiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -330,8 +329,9 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) Value = PyFloat_AsDouble(index_or_value); if (strcmp("Angle", ConstraintType) == 0) { if (PyObject_TypeCheck(index_or_value, &(Base::QuantityPy::Type))) { - Base::Quantity q = - *(static_cast(index_or_value)->getQuantityPtr()); + Base::Quantity q = *( + static_cast(index_or_value)->getQuantityPtr() + ); if (q.getUnit() == Base::Unit::Angle) { Value = q.getValueAs(Base::Quantity::Radian); } @@ -374,13 +374,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiOO", - &ConstraintType, - &FirstIndex, - &any_index, - &index_or_value, - &activated)) { + if (PyArg_ParseTuple(args, "siiOO", &ConstraintType, &FirstIndex, &any_index, &index_or_value, &activated)) { if (PyBool_Check(activated)) { if (handleSiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -390,14 +384,16 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiOOO", - &ConstraintType, - &FirstIndex, - &any_index, - &index_or_value, - &activated, - &driving)) { + if (PyArg_ParseTuple( + args, + "siiOOO", + &ConstraintType, + &FirstIndex, + &any_index, + &index_or_value, + &activated, + &driving + )) { if (PyBool_Check(activated) && PyBool_Check(driving)) { if (handleSiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -458,9 +454,11 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) constraint->ThirdPos = static_cast(intArg4); return true; } - else if (strstr(ConstraintType, - "InternalAlignment")) { // InteralAlignment with - // InternalElementIndex argument + else if (strstr( + ConstraintType, + "InternalAlignment" + )) { // InteralAlignment with + // InternalElementIndex argument constraint->Type = InternalAlignment; valid = true; @@ -514,14 +512,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiiOO", - &ConstraintType, - &intArg1, - &intArg2, - &intArg3, - &oNumArg4, - &activated)) { + if (PyArg_ParseTuple(args, "siiiOO", &ConstraintType, &intArg1, &intArg2, &intArg3, &oNumArg4, &activated)) { if (PyBool_Check(activated)) { if (handleSiiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -531,15 +522,17 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiiOOO", - &ConstraintType, - &intArg1, - &intArg2, - &intArg3, - &oNumArg4, - &activated, - &driving)) { + if (PyArg_ParseTuple( + args, + "siiiOOO", + &ConstraintType, + &intArg1, + &intArg2, + &intArg3, + &oNumArg4, + &activated, + &driving + )) { if (PyBool_Check(activated) && PyBool_Check(driving)) { if (handleSiiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -581,8 +574,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } else if (strcmp("Angle", ConstraintType) == 0) { if (PyObject_TypeCheck(oNumArg5, &(Base::QuantityPy::Type))) { - Base::Quantity q = - *(static_cast(oNumArg5)->getQuantityPtr()); + Base::Quantity q = *(static_cast(oNumArg5)->getQuantityPtr()); if (q.getUnit() == Base::Unit::Angle) { Value = q.getValueAs(Base::Quantity::Radian); } @@ -591,8 +583,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } else if (strcmp("AngleViaPoint", ConstraintType) == 0) { if (PyObject_TypeCheck(oNumArg5, &(Base::QuantityPy::Type))) { - Base::Quantity q = - *(static_cast(oNumArg5)->getQuantityPtr()); + Base::Quantity q = *(static_cast(oNumArg5)->getQuantityPtr()); if (q.getUnit() == Base::Unit::Angle) { Value = q.getValueAs(Base::Quantity::Radian); } @@ -622,29 +613,24 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) return false; }; - if (PyArg_ParseTuple(args, - "siiiiO", - &ConstraintType, - &intArg1, - &intArg2, - &intArg3, - &intArg4, - &oNumArg5)) { + if (PyArg_ParseTuple(args, "siiiiO", &ConstraintType, &intArg1, &intArg2, &intArg3, &intArg4, &oNumArg5)) { if (handleSiiiiO()) { return 0; } } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiiiOO", - &ConstraintType, - &intArg1, - &intArg2, - &intArg3, - &intArg4, - &oNumArg5, - &activated)) { + if (PyArg_ParseTuple( + args, + "siiiiOO", + &ConstraintType, + &intArg1, + &intArg2, + &intArg3, + &intArg4, + &oNumArg5, + &activated + )) { if (PyBool_Check(activated)) { if (handleSiiiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -654,16 +640,18 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiiiOOO", - &ConstraintType, - &intArg1, - &intArg2, - &intArg3, - &intArg4, - &oNumArg5, - &activated, - &driving)) { + if (PyArg_ParseTuple( + args, + "siiiiOOO", + &ConstraintType, + &intArg1, + &intArg2, + &intArg3, + &intArg4, + &oNumArg5, + &activated, + &driving + )) { if (PyBool_Check(activated) && PyBool_Check(driving)) { if (handleSiiiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -708,31 +696,35 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) return false; }; - if (PyArg_ParseTuple(args, - "siiiiiO", - &ConstraintType, - &FirstIndex, - &FirstPos, - &SecondIndex, - &SecondPos, - &ThirdIndex, - &index_or_value)) { + if (PyArg_ParseTuple( + args, + "siiiiiO", + &ConstraintType, + &FirstIndex, + &FirstPos, + &SecondIndex, + &SecondPos, + &ThirdIndex, + &index_or_value + )) { if (handleSiiiiiO()) { return 0; } } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiiiiOO", - &ConstraintType, - &FirstIndex, - &FirstPos, - &SecondIndex, - &SecondPos, - &ThirdIndex, - &index_or_value, - &activated)) { + if (PyArg_ParseTuple( + args, + "siiiiiOO", + &ConstraintType, + &FirstIndex, + &FirstPos, + &SecondIndex, + &SecondPos, + &ThirdIndex, + &index_or_value, + &activated + )) { if (PyBool_Check(activated)) { if (handleSiiiiiO()) { constraint->isActive = PyObject_IsTrue(activated); @@ -742,17 +734,19 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); - if (PyArg_ParseTuple(args, - "siiiiiOOO", - &ConstraintType, - &FirstIndex, - &FirstPos, - &SecondIndex, - &SecondPos, - &ThirdIndex, - &index_or_value, - &activated, - &driving)) { + if (PyArg_ParseTuple( + args, + "siiiiiOOO", + &ConstraintType, + &FirstIndex, + &FirstPos, + &SecondIndex, + &SecondPos, + &ThirdIndex, + &index_or_value, + &activated, + &driving + )) { if (PyBool_Check(activated) && PyBool_Check(driving)) { if (handleSiiiiiO()) { constraint->isActive = PyObject_IsTrue(activated); diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp b/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp index 35c562a157..856f9243b7 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp @@ -89,14 +89,13 @@ PyObject* ExternalGeometryExtension::getPyObject() return new ExternalGeometryExtensionPy(new ExternalGeometryExtension(*this)); } -bool ExternalGeometryExtension::getFlagsFromName(std::string str, - ExternalGeometryExtension::Flag& flag) +bool ExternalGeometryExtension::getFlagsFromName(std::string str, ExternalGeometryExtension::Flag& flag) { - auto pos = std::find_if(ExternalGeometryExtension::flag2str.begin(), - ExternalGeometryExtension::flag2str.end(), - [str](const char* val) { - return strcmp(val, str.c_str()) == 0; - }); + auto pos = std::find_if( + ExternalGeometryExtension::flag2str.begin(), + ExternalGeometryExtension::flag2str.end(), + [str](const char* val) { return strcmp(val, str.c_str()) == 0; } + ); if (pos != ExternalGeometryExtension::flag2str.end()) { int index = std::distance(ExternalGeometryExtension::flag2str.begin(), pos); diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtension.h b/src/Mod/Sketcher/App/ExternalGeometryExtension.h index 338d70f064..bc4b9ba6cf 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtension.h +++ b/src/Mod/Sketcher/App/ExternalGeometryExtension.h @@ -84,7 +84,8 @@ public: // constexpr static std::array flag2str { - {"Defining", "Frozen", "Detached", "Missing", "Sync"}}; + {"Defining", "Frozen", "Detached", "Missing", "Sync"} + }; public: ExternalGeometryExtension() = default; diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp index 1d242b1ad6..0e2db02641 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp @@ -89,9 +89,11 @@ int ExternalGeometryExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, - "ExternalGeometryExtension constructor accepts:\n" - "-- empty parameter list\n"); + PyErr_SetString( + PyExc_TypeError, + "ExternalGeometryExtension constructor accepts:\n" + "-- empty parameter list\n" + ); return -1; } @@ -104,7 +106,8 @@ PyObject* ExternalGeometryExtensionPy::testFlag(PyObject* args) const if (getExternalGeometryExtensionPtr()->getFlagsFromName(flag, flagtype)) { return new_reference_to( - Py::Boolean(this->getExternalGeometryExtensionPtr()->testFlag(flagtype))); + Py::Boolean(this->getExternalGeometryExtensionPtr()->testFlag(flagtype)) + ); } PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp index 88fe721278..06d6decf2e 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp @@ -61,8 +61,9 @@ std::unique_ptr ExternalGeometryFacade::getFacade(Part:: } } -std::unique_ptr -ExternalGeometryFacade::getFacade(const Part::Geometry* geometry) +std::unique_ptr ExternalGeometryFacade::getFacade( + const Part::Geometry* geometry +) { if (geometry) { return std::unique_ptr(new ExternalGeometryFacade(geometry)); @@ -99,8 +100,7 @@ void ExternalGeometryFacade::initExtensions() if (!Geo->hasExtension(ExternalGeometryExtension::getClassTypeId())) { - getGeo()->setExtension( - std::make_unique()); // Create getExtension + getGeo()->setExtension(std::make_unique()); // Create getExtension // The following warning was commented out as part of the Toponaming problem mitigation, and // left for potential usefulness to future developers making a custom build for debugging. @@ -110,31 +110,39 @@ void ExternalGeometryFacade::initExtensions() } SketchGeoExtension = std::static_pointer_cast( - (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock()); + (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock() + ); ExternalGeoExtension = std::static_pointer_cast( - (Geo->getExtension(ExternalGeometryExtension::getClassTypeId())).lock()); + (Geo->getExtension(ExternalGeometryExtension::getClassTypeId())).lock() + ); } void ExternalGeometryFacade::initExtensions() const { if (!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) { - THROWM(Base::ValueError, - "ExternalGeometryFacade for const::Geometry without SketchGeometryExtension"); + THROWM( + Base::ValueError, + "ExternalGeometryFacade for const::Geometry without SketchGeometryExtension" + ); } if (!Geo->hasExtension(ExternalGeometryExtension::getClassTypeId())) { - THROWM(Base::ValueError, - "ExternalGeometryFacade for const::Geometry without ExternalGeometryExtension"); + THROWM( + Base::ValueError, + "ExternalGeometryFacade for const::Geometry without ExternalGeometryExtension" + ); } auto ext = std::static_pointer_cast( - Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock()); + Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock() + ); const_cast(this)->SketchGeoExtension = ext; auto extext = std::static_pointer_cast( - Geo->getExtension(ExternalGeometryExtension::getClassTypeId()).lock()); + Geo->getExtension(ExternalGeometryExtension::getClassTypeId()).lock() + ); const_cast(this)->ExternalGeoExtension = extext; } diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp index 5d270101f0..32b5161998 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp @@ -47,9 +47,11 @@ std::string ExternalGeometryFacadePy::representation() const return str.str(); } -PyObject* ExternalGeometryFacadePy::PyMake(struct _typeobject*, - PyObject*, - PyObject*) // Python wrapper +PyObject* ExternalGeometryFacadePy::PyMake( + struct _typeobject*, + PyObject*, + PyObject* +) // Python wrapper { // create a new instance of PointPy and the Twin object return new ExternalGeometryFacadePy(new ExternalGeometryFacade()); @@ -67,9 +69,11 @@ int ExternalGeometryFacadePy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, - "Sketcher::ExternalGeometryFacade constructor accepts:\n" - "-- Part.Geometry\n"); + PyErr_SetString( + PyExc_TypeError, + "Sketcher::ExternalGeometryFacade constructor accepts:\n" + "-- Part.Geometry\n" + ); return -1; } @@ -78,17 +82,16 @@ PyObject* ExternalGeometryFacadePy::testFlag(PyObject* args) const char* flag; if (PyArg_ParseTuple(args, "s", &flag)) { - auto pos = std::find_if(ExternalGeometryExtension::flag2str.begin(), - ExternalGeometryExtension::flag2str.end(), - [flag](const char* val) { - return strcmp(val, flag) == 0; - }); + auto pos = std::find_if( + ExternalGeometryExtension::flag2str.begin(), + ExternalGeometryExtension::flag2str.end(), + [flag](const char* val) { return strcmp(val, flag) == 0; } + ); if (pos != ExternalGeometryExtension::flag2str.end()) { int index = std::distance(ExternalGeometryExtension::flag2str.begin(), pos); - return new_reference_to( - Py::Boolean(this->getExternalGeometryFacadePtr()->testFlag(index))); + return new_reference_to(Py::Boolean(this->getExternalGeometryFacadePtr()->testFlag(index))); } PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); @@ -105,11 +108,11 @@ PyObject* ExternalGeometryFacadePy::setFlag(PyObject* args) PyObject* bflag = Py_True; if (PyArg_ParseTuple(args, "s|O!", &flag, &PyBool_Type, &bflag)) { - auto pos = std::find_if(ExternalGeometryExtension::flag2str.begin(), - ExternalGeometryExtension::flag2str.end(), - [flag](const char* val) { - return strcmp(val, flag) == 0; - }); + auto pos = std::find_if( + ExternalGeometryExtension::flag2str.begin(), + ExternalGeometryExtension::flag2str.end(), + [flag](const char* val) { return strcmp(val, flag) == 0; } + ); if (pos != ExternalGeometryExtension::flag2str.end()) { int index = std::distance(ExternalGeometryExtension::flag2str.begin(), pos); @@ -193,20 +196,17 @@ PyObject* ExternalGeometryFacadePy::mirror(PyObject* args) PyErr_Clear(); PyObject* axis; - if (PyArg_ParseTuple(args, - "O!O!", - &(Base::VectorPy::Type), - &o, - &(Base::VectorPy::Type), - &axis)) { + if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &o, &(Base::VectorPy::Type), &axis)) { Base::Vector3d pnt = static_cast(o)->value(); Base::Vector3d dir = static_cast(axis)->value(); getExternalGeometryFacadePtr()->mirror(pnt, dir); Py_Return; } - PyErr_SetString(Part::PartExceptionOCCError, - "either a point (vector) or axis (vector, vector) must be given"); + PyErr_SetString( + Part::PartExceptionOCCError, + "either a point (vector) or axis (vector, vector) must be given" + ); return nullptr; } @@ -304,7 +304,8 @@ PyObject* ExternalGeometryFacadePy::getExtensionOfType(PyObject* args) const if (!type.isBad()) { try { std::shared_ptr ext( - this->getExternalGeometryFacadePtr()->getExtension(type)); + this->getExternalGeometryFacadePtr()->getExtension(type) + ); // we create a copy and transfer this copy's memory management responsibility to // Python @@ -316,13 +317,17 @@ PyObject* ExternalGeometryFacadePy::getExtensionOfType(PyObject* args) const return nullptr; } catch (const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not exist anymore."); + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not exist anymore." + ); return nullptr; } catch (Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not implement a Python counterpart."); + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart." + ); return nullptr; } } @@ -332,8 +337,10 @@ PyObject* ExternalGeometryFacadePy::getExtensionOfType(PyObject* args) const } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the name of the geometry extension type was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the name of the geometry extension type was expected" + ); return nullptr; } @@ -344,7 +351,8 @@ PyObject* ExternalGeometryFacadePy::getExtensionOfName(PyObject* args) const try { std::shared_ptr ext( - this->getExternalGeometryFacadePtr()->getExtension(std::string(o))); + this->getExternalGeometryFacadePtr()->getExtension(std::string(o)) + ); // we create a copy and transfer this copy's memory management responsibility to Python PyObject* cpy = ext->copyPyObject(); @@ -355,19 +363,22 @@ PyObject* ExternalGeometryFacadePy::getExtensionOfName(PyObject* args) const return nullptr; } catch (const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not exist anymore."); + PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not exist anymore."); return nullptr; } catch (Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not implement a Python counterpart."); + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart." + ); return nullptr; } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the name of the geometry extension was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the name of the geometry extension was expected" + ); return nullptr; } @@ -381,7 +392,8 @@ PyObject* ExternalGeometryFacadePy::hasExtensionOfType(PyObject* args) const if (!type.isBad()) { try { return Py::new_reference_to( - Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(type))); + Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(type)) + ); } catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); @@ -394,8 +406,10 @@ PyObject* ExternalGeometryFacadePy::hasExtensionOfType(PyObject* args) const } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the type of the geometry extension was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected" + ); return nullptr; } @@ -406,7 +420,8 @@ PyObject* ExternalGeometryFacadePy::hasExtensionOfName(PyObject* args) const try { return Py::new_reference_to( - Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(std::string(o)))); + Py::Boolean(this->getExternalGeometryFacadePtr()->hasExtension(std::string(o))) + ); } catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); @@ -414,8 +429,10 @@ PyObject* ExternalGeometryFacadePy::hasExtensionOfName(PyObject* args) const } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the type of the geometry extension was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected" + ); return nullptr; } @@ -461,8 +478,7 @@ PyObject* ExternalGeometryFacadePy::deleteExtensionOfName(PyObject* args) } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the name of the extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the extension was expected"); return nullptr; } @@ -474,8 +490,8 @@ PyObject* ExternalGeometryFacadePy::getExtensions(PyObject* args) const } try { - const std::vector> ext = - this->getExternalGeometryFacadePtr()->getExtensions(); + const std::vector> ext + = this->getExternalGeometryFacadePtr()->getExtensions(); Py::List list; diff --git a/src/Mod/Sketcher/App/GeoList.cpp b/src/Mod/Sketcher/App/GeoList.cpp index 4bd308ed98..2518f87985 100644 --- a/src/Mod/Sketcher/App/GeoList.cpp +++ b/src/Mod/Sketcher/App/GeoList.cpp @@ -44,8 +44,10 @@ GeoListModel::GeoListModel(std::vector&& geometrylist, int intgeocount, bo // Vector is shallow copied (copy constructed) template -GeoListModel::GeoListModel(const std::vector& geometrylist, - int intgeocount) +GeoListModel::GeoListModel( + const std::vector& geometrylist, + int intgeocount +) : geomlist(geometrylist) , // copy constructed here intGeoCount(intgeocount) @@ -64,15 +66,13 @@ GeoListModel::~GeoListModel() } template -GeoListModel -GeoListModel::getGeoListModel(std::vector&& geometrylist, int intgeocount, bool ownerT) +GeoListModel GeoListModel::getGeoListModel(std::vector&& geometrylist, int intgeocount, bool ownerT) { return GeoListModel(std::move(geometrylist), intgeocount, ownerT); } template -const GeoListModel GeoListModel::getGeoListModel(const std::vector& geometrylist, - int intgeocount) +const GeoListModel GeoListModel::getGeoListModel(const std::vector& geometrylist, int intgeocount) { return GeoListModel(geometrylist, intgeocount); } @@ -92,8 +92,7 @@ int GeoListModel::getGeoIdFromGeomListIndex(int index) const } template -const Part::Geometry* GeoListModel::getGeometryFromGeoId(const std::vector& geometrylist, - int geoId) +const Part::Geometry* GeoListModel::getGeometryFromGeoId(const std::vector& geometrylist, int geoId) { if constexpr (std::is_same()) { if (geoId >= 0) { @@ -114,8 +113,10 @@ const Part::Geometry* GeoListModel::getGeometryFromGeoId(const std::vector } template -const Sketcher::GeometryFacade* -GeoListModel::getGeometryFacadeFromGeoId(const std::vector& geometrylist, int geoId) +const Sketcher::GeometryFacade* GeoListModel::getGeometryFacadeFromGeoId( + const std::vector& geometrylist, + int geoId +) { if constexpr (std::is_same()) { if (geoId >= 0) { @@ -267,9 +268,11 @@ void GeoListModel::rebuildVertexIndex() const auto addGeoElement = [this, &pointId](int geoId, PointPos pos) { VertexId2GeoElementId.emplace_back(geoId, pos); - GeoElementId2VertexId.emplace(std::piecewise_construct, - std::forward_as_tuple(geoId, pos), - std::forward_as_tuple(pointId++)); + GeoElementId2VertexId.emplace( + std::piecewise_construct, + std::forward_as_tuple(geoId, pos), + std::forward_as_tuple(pointId++) + ); }; if (geomlist.size() <= 2) { @@ -282,8 +285,7 @@ void GeoListModel::rebuildVertexIndex() const if constexpr (std::is_same::value) { type = (*it)->getTypeId(); } - else if constexpr (std::is_same>::value) { + else if constexpr (std::is_same>::value) { type = (*it)->getGeometry()->getTypeId(); } @@ -350,7 +352,8 @@ template<> GeoListModel::GeoListModel( std::vector&& geometrylist, int intgeocount, - bool ownerT) + bool ownerT +) : geomlist(std::move(geometrylist)) , intGeoCount(intgeocount) , OwnerT(false) @@ -372,7 +375,8 @@ GeoListModel::GeoListModel( template<> GeoListModel::GeoListModel( const std::vector& geometrylist, - int intgeocount) + int intgeocount +) : intGeoCount(intgeocount) , OwnerT(false) , indexInit(false) @@ -404,25 +408,31 @@ template class SketcherExport GeoListModel::getGeometryFromGeoId(int geoId) const; -template SketcherExport const Sketcher::GeometryFacade* -GeoListModel::getGeometryFacadeFromGeoId(int geoId) const; -template SketcherExport int -GeoListModel::getGeoIdFromGeomListIndex(int index) const; +template SketcherExport const Part::Geometry* GeoListModel::getGeometryFromGeoId( + int geoId +) const; +template SketcherExport const Sketcher::GeometryFacade* GeoListModel< + GeometryFacadeUniquePtr>::getGeometryFacadeFromGeoId(int geoId) const; +template SketcherExport int GeoListModel::getGeoIdFromGeomListIndex( + int index +) const; template SketcherExport int GeoListModel::getVertexIdFromGeoElementId( - const Sketcher::GeoElementId&) const; + const Sketcher::GeoElementId& +) const; template SketcherExport GeoElementId GeoListModel::getGeoElementIdFromVertexId(int); -template SketcherExport Base::Vector3d -GeoListModel::getPoint(int geoId, Sketcher::PointPos pos) const; -template SketcherExport Base::Vector3d -GeoListModel::getPoint(const GeoElementId&) const; -template SketcherExport GeoListModel -GeoListModel::getGeoListModel( +template SketcherExport Base::Vector3d GeoListModel::getPoint( + int geoId, + Sketcher::PointPos pos +) const; +template SketcherExport Base::Vector3d GeoListModel::getPoint( + const GeoElementId& +) const; +template SketcherExport GeoListModel GeoListModel::getGeoListModel( std::vector&& geometrylist, int intgeocount, - bool ownerT); + bool ownerT +); #endif @@ -437,8 +447,7 @@ GeoListFacade Sketcher::getGeoListFacade(const GeoList& geolist) facade.push_back(GeometryFacade::getFacade(geo)); } - auto geolistfacade = - GeoListFacade::getGeoListModel(std::move(facade), geolist.getInternalCount()); + auto geolistfacade = GeoListFacade::getGeoListModel(std::move(facade), geolist.getInternalCount()); return geolistfacade; } diff --git a/src/Mod/Sketcher/App/GeoList.h b/src/Mod/Sketcher/App/GeoList.h index 212eaa571c..cb8ff7808d 100644 --- a/src/Mod/Sketcher/App/GeoList.h +++ b/src/Mod/Sketcher/App/GeoList.h @@ -132,10 +132,12 @@ public: * assertion is raised if this happens. The ownership needs to be specified on the GeoListFacade * objects themselves (setOwner method). */ - static GeoListModel - getGeoListModel(std::vector&& geometrylist, int intgeocount, bool ownerT = false); - static const GeoListModel getGeoListModel(const std::vector& geometrylist, - int intgeocount); + static GeoListModel getGeoListModel( + std::vector&& geometrylist, + int intgeocount, + bool ownerT = false + ); + static const GeoListModel getGeoListModel(const std::vector& geometrylist, int intgeocount); /** @brief @@ -171,8 +173,7 @@ public: * * @param index: the index of the list of geometry in geomlist format. */ - static const Part::Geometry* getGeometryFromGeoId(const std::vector& geometrylist, - int geoId); + static const Part::Geometry* getGeometryFromGeoId(const std::vector& geometrylist, int geoId); /** @brief returns a geometry facade * @warning If the underlying model of the list is a naked pointed (Part::Geometry *), the @@ -181,8 +182,10 @@ public: * This is not a problem when the model of the list is a * std::unique_ptr, because the lifetime is tied to the model itself. */ - static const Sketcher::GeometryFacade* - getGeometryFacadeFromGeoId(const std::vector& geometrylist, int geoId); + static const Sketcher::GeometryFacade* getGeometryFacadeFromGeoId( + const std::vector& geometrylist, + int geoId + ); /** @brief * Obtain a GeoElementId class {GeoId, Pos} given a VertexId. @@ -254,8 +257,9 @@ private: int intGeoCount; bool OwnerT; mutable bool indexInit; - mutable std::vector - VertexId2GeoElementId; // these maps a lazy initialised on first demand. + mutable std::vector VertexId2GeoElementId; // these maps a lazy + // initialised on first + // demand. mutable std::map GeoElementId2VertexId; }; diff --git a/src/Mod/Sketcher/App/GeometryFacade.cpp b/src/Mod/Sketcher/App/GeometryFacade.cpp index 51e3a9edd0..9d5419b45f 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.cpp +++ b/src/Mod/Sketcher/App/GeometryFacade.cpp @@ -53,8 +53,7 @@ GeometryFacade::~GeometryFacade() } } -std::unique_ptr GeometryFacade::getFacade(const Part::Geometry* geometry, - bool owner) +std::unique_ptr GeometryFacade::getFacade(const Part::Geometry* geometry, bool owner) { if (geometry) { return std::unique_ptr(new GeometryFacade(geometry, owner)); @@ -89,20 +88,24 @@ void GeometryFacade::initExtension() } SketchGeoExtension = std::static_pointer_cast( - (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock()); + (Geo->getExtension(SketchGeometryExtension::getClassTypeId())).lock() + ); } void GeometryFacade::initExtension() const { // const Geometry without SketchGeometryExtension cannot initialise a GeometryFacade if (!Geo->hasExtension(SketchGeometryExtension::getClassTypeId())) { - THROWM(Base::ValueError, - "Cannot create a GeometryFacade out of a const Geometry pointer not having a " - "SketchGeometryExtension!"); + THROWM( + Base::ValueError, + "Cannot create a GeometryFacade out of a const Geometry pointer not having a " + "SketchGeometryExtension!" + ); } auto ext = std::static_pointer_cast( - Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock()); + Geo->getExtension(SketchGeometryExtension::getClassTypeId()).lock() + ); const_cast(this)->SketchGeoExtension = ext; } diff --git a/src/Mod/Sketcher/App/GeometryFacade.h b/src/Mod/Sketcher/App/GeometryFacade.h index 1fdcd706f8..376c265132 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.h +++ b/src/Mod/Sketcher/App/GeometryFacade.h @@ -118,8 +118,7 @@ protected: friend class GeometryFacadePy; public: // Factory methods - static std::unique_ptr getFacade(const Part::Geometry* geometry, - bool owner = false); + static std::unique_ptr getFacade(const Part::Geometry* geometry, bool owner = false); public: // Utility methods static void ensureSketchGeometryExtension(Part::Geometry* geometry); @@ -396,9 +395,11 @@ private: template class SketcherExport GeometryTypedFacade: public GeometryFacade { - static_assert(std::is_base_of::type>::value - && !std::is_same::type>::value, - "Only for classes derived from Geometry!"); + static_assert( + std::is_base_of::type>::value + && !std::is_same::type>::value, + "Only for classes derived from Geometry!" + ); private: explicit GeometryTypedFacade(const Part::Geometry* geometry, bool owner = false) @@ -409,23 +410,28 @@ private: {} public: // Factory methods - static std::unique_ptr> getTypedFacade(GeometryT* geometry, - bool owner = false) + static std::unique_ptr> getTypedFacade( + GeometryT* geometry, + bool owner = false + ) { if (geometry) { return std::unique_ptr>( - new GeometryTypedFacade(geometry, owner)); + new GeometryTypedFacade(geometry, owner) + ); } else { return std::unique_ptr>(nullptr); } } - static std::unique_ptr> - getTypedFacade(const GeometryT* geometry) + static std::unique_ptr> getTypedFacade( + const GeometryT* geometry + ) { if (geometry) { return std::unique_ptr>( - new GeometryTypedFacade(geometry)); + new GeometryTypedFacade(geometry) + ); } else { return std::unique_ptr>(nullptr); @@ -436,8 +442,7 @@ public: // Factory methods template static std::unique_ptr> getTypedFacade(Args&&... args) { - return GeometryTypedFacade::getTypedFacade(new GeometryT(std::forward(args)...), - true); + return GeometryTypedFacade::getTypedFacade(new GeometryT(std::forward(args)...), true); } // Geometry Element diff --git a/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp b/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp index 2418fd5160..55044e0446 100644 --- a/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp +++ b/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp @@ -65,9 +65,11 @@ int GeometryFacadePy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } - PyErr_SetString(PyExc_TypeError, - "Sketcher::GeometryFacade constructor accepts:\n" - "-- Part.Geometry\n"); + PyErr_SetString( + PyExc_TypeError, + "Sketcher::GeometryFacade constructor accepts:\n" + "-- Part.Geometry\n" + ); return -1; } @@ -169,20 +171,17 @@ PyObject* GeometryFacadePy::mirror(PyObject* args) PyErr_Clear(); PyObject* axis; - if (PyArg_ParseTuple(args, - "O!O!", - &(Base::VectorPy::Type), - &o, - &(Base::VectorPy::Type), - &axis)) { + if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &o, &(Base::VectorPy::Type), &axis)) { Base::Vector3d pnt = static_cast(o)->value(); Base::Vector3d dir = static_cast(axis)->value(); getGeometryFacadePtr()->mirror(pnt, dir); Py_Return; } - PyErr_SetString(Part::PartExceptionOCCError, - "either a point (vector) or axis (vector, vector) must be given"); + PyErr_SetString( + Part::PartExceptionOCCError, + "either a point (vector) or axis (vector, vector) must be given" + ); return nullptr; } @@ -280,7 +279,8 @@ PyObject* GeometryFacadePy::getExtensionOfType(PyObject* args) const if (!type.isBad()) { try { std::shared_ptr ext( - this->getGeometryFacadePtr()->getExtension(type)); + this->getGeometryFacadePtr()->getExtension(type) + ); // we create a copy and transfer this copy's memory management responsibility to // Python @@ -292,13 +292,17 @@ PyObject* GeometryFacadePy::getExtensionOfType(PyObject* args) const return nullptr; } catch (const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not exist anymore."); + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not exist anymore." + ); return nullptr; } catch (Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not implement a Python counterpart."); + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart." + ); return nullptr; } } @@ -308,8 +312,10 @@ PyObject* GeometryFacadePy::getExtensionOfType(PyObject* args) const } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the name of the geometry extension type was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the name of the geometry extension type was expected" + ); return nullptr; } @@ -320,7 +326,8 @@ PyObject* GeometryFacadePy::getExtensionOfName(PyObject* args) const try { std::shared_ptr ext( - this->getGeometryFacadePtr()->getExtension(std::string(o))); + this->getGeometryFacadePtr()->getExtension(std::string(o)) + ); // we create a copy and transfer this copy's memory management responsibility to Python PyObject* cpy = ext->copyPyObject(); @@ -331,19 +338,22 @@ PyObject* GeometryFacadePy::getExtensionOfName(PyObject* args) const return nullptr; } catch (const std::bad_weak_ptr&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not exist anymore."); + PyErr_SetString(Part::PartExceptionOCCError, "Geometry extension does not exist anymore."); return nullptr; } catch (Base::NotImplementedError&) { - PyErr_SetString(Part::PartExceptionOCCError, - "Geometry extension does not implement a Python counterpart."); + PyErr_SetString( + Part::PartExceptionOCCError, + "Geometry extension does not implement a Python counterpart." + ); return nullptr; } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the name of the geometry extension was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the name of the geometry extension was expected" + ); return nullptr; } @@ -357,7 +367,8 @@ PyObject* GeometryFacadePy::hasExtensionOfType(PyObject* args) const if (!type.isBad()) { try { return Py::new_reference_to( - Py::Boolean(this->getGeometryFacadePtr()->hasExtension(type))); + Py::Boolean(this->getGeometryFacadePtr()->hasExtension(type)) + ); } catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); @@ -370,8 +381,10 @@ PyObject* GeometryFacadePy::hasExtensionOfType(PyObject* args) const } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the type of the geometry extension was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected" + ); return nullptr; } @@ -382,7 +395,8 @@ PyObject* GeometryFacadePy::hasExtensionOfName(PyObject* args) const try { return Py::new_reference_to( - Py::Boolean(this->getGeometryFacadePtr()->hasExtension(std::string(o)))); + Py::Boolean(this->getGeometryFacadePtr()->hasExtension(std::string(o))) + ); } catch (const Base::ValueError& e) { PyErr_SetString(Part::PartExceptionOCCError, e.what()); @@ -390,8 +404,10 @@ PyObject* GeometryFacadePy::hasExtensionOfName(PyObject* args) const } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the type of the geometry extension was expected"); + PyErr_SetString( + Part::PartExceptionOCCError, + "A string with the type of the geometry extension was expected" + ); return nullptr; } @@ -437,8 +453,7 @@ PyObject* GeometryFacadePy::deleteExtensionOfName(PyObject* args) } } - PyErr_SetString(Part::PartExceptionOCCError, - "A string with the name of the extension was expected"); + PyErr_SetString(Part::PartExceptionOCCError, "A string with the name of the extension was expected"); return nullptr; } @@ -450,8 +465,8 @@ PyObject* GeometryFacadePy::getExtensions(PyObject* args) const } try { - const std::vector> ext = - this->getGeometryFacadePtr()->getExtensions(); + const std::vector> ext + = this->getGeometryFacadePtr()->getExtensions(); Py::List list; diff --git a/src/Mod/Sketcher/App/PreCompiled.h b/src/Mod/Sketcher/App/PreCompiled.h index bb59d2261a..d3f44ca0b3 100644 --- a/src/Mod/Sketcher/App/PreCompiled.h +++ b/src/Mod/Sketcher/App/PreCompiled.h @@ -21,91 +21,91 @@ ***************************************************************************/ #ifndef SKETCHER_APP_PRECOMPILED_H -#define SKETCHER_APP_PRECOMPILED_H +# define SKETCHER_APP_PRECOMPILED_H -#include +# include // standard -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include // Qt -#include +# include // Boost -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include // OpenCasCade -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include #elif defined(FC_OS_WIN32) -#include +# include #endif diff --git a/src/Mod/Sketcher/App/PropertyConstraintList.cpp b/src/Mod/Sketcher/App/PropertyConstraintList.cpp index ea32d3d736..40c261124e 100644 --- a/src/Mod/Sketcher/App/PropertyConstraintList.cpp +++ b/src/Mod/Sketcher/App/PropertyConstraintList.cpp @@ -58,8 +58,7 @@ PropertyConstraintList::PropertyConstraintList() PropertyConstraintList::~PropertyConstraintList() { - for (std::vector::iterator it = _lValueList.begin(); it != _lValueList.end(); - ++it) { + for (std::vector::iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { if (*it) { delete *it; } @@ -74,8 +73,8 @@ App::ObjectIdentifier PropertyConstraintList::makeArrayPath(int idx) App::ObjectIdentifier PropertyConstraintList::makeSimplePath(const Constraint* c) { return App::ObjectIdentifier(*this) << App::ObjectIdentifier::SimpleComponent( - App::ObjectIdentifier::String(c->Name, - !ExpressionParser::isTokenAnIndentifier(c->Name))); + App::ObjectIdentifier::String(c->Name, !ExpressionParser::isTokenAnIndentifier(c->Name)) + ); } App::ObjectIdentifier PropertyConstraintList::makePath(int idx, const Constraint* c) @@ -206,8 +205,9 @@ void PropertyConstraintList::applyValues(std::vector&& lValue) /* Check for renames */ for (unsigned int i = 0; i < lValue.size(); i++) { - boost::unordered_map::const_iterator j = - valueMap.find(lValue[i]->tag); + boost::unordered_map::const_iterator j = valueMap.find( + lValue[i]->tag + ); if (j != valueMap.end()) { if (i != j->second || _lValueList[j->second]->Name != lValue[i]->Name) { @@ -260,8 +260,7 @@ PyObject* PropertyConstraintList::getPyObject() return list; } -bool PropertyConstraintList::getPyPathValue(const App::ObjectIdentifier& path, - Py::Object& res) const +bool PropertyConstraintList::getPyPathValue(const App::ObjectIdentifier& path, Py::Object& res) const { if (path.numSubComponents() != 2 || path.getPropertyComponent(0).getName() != getName()) { return false; @@ -636,8 +635,7 @@ void PropertyConstraintList::getPaths(std::vector& paths) cons for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { if (!(*it)->Name.empty()) { - paths.push_back(ObjectIdentifier(*this) - << ObjectIdentifier::SimpleComponent((*it)->Name)); + paths.push_back(ObjectIdentifier(*this) << ObjectIdentifier::SimpleComponent((*it)->Name)); } } } diff --git a/src/Mod/Sketcher/App/PythonConverter.cpp b/src/Mod/Sketcher/App/PythonConverter.cpp index e2f827ae67..bfb918c01a 100644 --- a/src/Mod/Sketcher/App/PythonConverter.cpp +++ b/src/Mod/Sketcher/App/PythonConverter.cpp @@ -40,8 +40,9 @@ std::string PythonConverter::convert(const Part::Geometry* geo, Mode mode) std::string command; auto sg = process(geo); - command = boost::str(boost::format("addGeometry(%s,%s)\n") % sg.creation - % (sg.construction ? "True" : "False")); + command = boost::str( + boost::format("addGeometry(%s,%s)\n") % sg.creation % (sg.construction ? "True" : "False") + ); // clang-format off: keep line breaks for readability if ((!geo->is() @@ -68,9 +69,11 @@ std::string PythonConverter::convert(const Sketcher::Constraint* constraint, Geo return command; } -std::string PythonConverter::convert(const std::string& doc, - const std::vector& geos, - Mode mode) +std::string PythonConverter::convert( + const std::string& doc, + const std::vector& geos, + Mode mode +) { if (geos.empty()) { return std::string(); @@ -83,14 +86,18 @@ std::string PythonConverter::convert(const std::string& doc, if (ngeos > 0) { if (construction) { command = boost::str( - boost::format("constrGeoList = []\n%s%s.addGeometry(constrGeoList,%s)\n" - "del constrGeoList\n") - % geolist % doc % "True"); + boost::format( + "constrGeoList = []\n%s%s.addGeometry(constrGeoList,%s)\n" + "del constrGeoList\n" + ) + % geolist % doc % "True" + ); } else { command = boost::str( boost::format("geoList = []\n%s%s.addGeometry(geoList,%s)\ndel geoList\n") - % geolist % doc % "False"); + % geolist % doc % "False" + ); } } @@ -131,8 +138,7 @@ std::string PythonConverter::convert(const std::string& doc, } if (sg.construction) { - geolist = - boost::str(boost::format("%sconstrGeoList.append(%s)\n") % geolist % sg.creation); + geolist = boost::str(boost::format("%sconstrGeoList.append(%s)\n") % geolist % sg.creation); } else { geolist = boost::str(boost::format("%sgeoList.append(%s)\n") % geolist % sg.creation); @@ -164,9 +170,11 @@ std::string PythonConverter::convert(const std::string& doc, return command; } -std::string PythonConverter::convert(const std::string& doc, - const std::vector& constraints, - GeoIdMode geoIdMode) +std::string PythonConverter::convert( + const std::string& doc, + const std::vector& constraints, + GeoIdMode geoIdMode +) { if (constraints.size() == 1) { auto cg = convert(constraints[0], geoIdMode); @@ -179,14 +187,16 @@ std::string PythonConverter::convert(const std::string& doc, for (auto constraint : constraints) { auto cg = process(constraint, geoIdMode); - constraintlist = - boost::str(boost::format("%s\nconstraintList.append(%s)") % constraintlist % cg); + constraintlist = boost::str( + boost::format("%s\nconstraintList.append(%s)") % constraintlist % cg + ); } if (!constraints.empty()) { - constraintlist = - boost::str(boost::format("%s\n%s.addConstraint(constraintList)\ndel constraintList\n") - % constraintlist % doc); + constraintlist = boost::str( + boost::format("%s\n%s.addConstraint(constraintList)\ndel constraintList\n") + % constraintlist % doc + ); } return constraintlist; @@ -217,17 +227,17 @@ std::string makeSplineInfoArrayString(const std::vector& rInfoVec) PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* geo) { - static std::map> - converterMap = { + static std::map> converterMap + = { {Part::GeomLineSegment::getClassTypeId(), [](const Part::Geometry* geo) { auto sgeo = static_cast(geo); SingleGeometry sg; sg.creation = boost::str( - boost::format( - "Part.LineSegment(App.Vector(%f, %f, %f),App.Vector(%f, %f, %f))") + boost::format("Part.LineSegment(App.Vector(%f, %f, %f),App.Vector(%f, %f, %f))") % sgeo->getStartPoint().x % sgeo->getStartPoint().y % sgeo->getStartPoint().z - % sgeo->getEndPoint().x % sgeo->getEndPoint().y % sgeo->getEndPoint().z); + % sgeo->getEndPoint().x % sgeo->getEndPoint().y % sgeo->getEndPoint().z + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -238,11 +248,14 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g arc->getRange(startAngle, endAngle, /*emulateCCWXY=*/true); SingleGeometry sg; sg.creation = boost::str( - boost::format("Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, " - "%f), App.Vector(%f, %f, %f), %f), %f, %f)") + boost::format( + "Part.ArcOfCircle(Part.Circle(App.Vector(%f, %f, " + "%f), App.Vector(%f, %f, %f), %f), %f, %f)" + ) % arc->getCenter().x % arc->getCenter().y % arc->getCenter().z % arc->getAxisDirection().x % arc->getAxisDirection().y - % arc->getAxisDirection().z % arc->getRadius() % startAngle % endAngle); + % arc->getAxisDirection().z % arc->getRadius() % startAngle % endAngle + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -250,9 +263,10 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g [](const Part::Geometry* geo) { auto sgeo = static_cast(geo); SingleGeometry sg; - sg.creation = - boost::str(boost::format("Part.Point(App.Vector(%f, %f, %f))") - % sgeo->getPoint().x % sgeo->getPoint().y % sgeo->getPoint().z); + sg.creation = boost::str( + boost::format("Part.Point(App.Vector(%f, %f, %f))") % sgeo->getPoint().x + % sgeo->getPoint().y % sgeo->getPoint().z + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -263,11 +277,14 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g auto center = ellipse->getCenter(); auto periapsis = center + ellipse->getMajorAxisDir() * ellipse->getMajorRadius(); auto positiveB = center + ellipse->getMinorAxisDir() * ellipse->getMinorRadius(); - sg.creation = - boost::str(boost::format("Part.Ellipse(App.Vector(%f, %f, %f), App.Vector(%f, " - "%f, %f), App.Vector(%f, %f, %f))") - % periapsis.x % periapsis.y % periapsis.z % positiveB.x - % positiveB.y % positiveB.z % center.x % center.y % center.z); + sg.creation = boost::str( + boost::format( + "Part.Ellipse(App.Vector(%f, %f, %f), App.Vector(%f, " + "%f, %f), App.Vector(%f, %f, %f))" + ) + % periapsis.x % periapsis.y % periapsis.z % positiveB.x % positiveB.y + % positiveB.z % center.x % center.y % center.z + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -283,9 +300,11 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g sg.creation = boost::str( boost::format( "Part.ArcOfEllipse(Part.Ellipse(App.Vector(%f, %f, %f), App.Vector(%f, " - "%f, %f), App.Vector(%f, %f, %f)), %f, %f)") + "%f, %f), App.Vector(%f, %f, %f)), %f, %f)" + ) % periapsis.x % periapsis.y % periapsis.z % positiveB.x % positiveB.y - % positiveB.z % center.x % center.y % center.z % startAngle % endAngle); + % positiveB.z % center.x % center.y % center.z % startAngle % endAngle + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -299,11 +318,14 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g auto majAxisPoint = center + aoh->getMajorAxisDir() * aoh->getMajorRadius(); auto minAxisPoint = center + aoh->getMinorAxisDir() * aoh->getMinorRadius(); sg.creation = boost::str( - boost::format("Part.ArcOfHyperbola(Part.Hyperbola(App.Vector(%f, %f, %f), " - "App.Vector(%f, %f, %f), App.Vector(%f, %f, %f)), %f, %f)") + boost::format( + "Part.ArcOfHyperbola(Part.Hyperbola(App.Vector(%f, %f, %f), " + "App.Vector(%f, %f, %f), App.Vector(%f, %f, %f)), %f, %f)" + ) % majAxisPoint.x % majAxisPoint.y % majAxisPoint.z % minAxisPoint.x % minAxisPoint.y % minAxisPoint.z % center.x % center.y % center.z % startAngle - % endAngle); + % endAngle + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -316,10 +338,13 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g auto focus = aop->getFocus(); auto axisPoint = aop->getCenter(); sg.creation = boost::str( - boost::format("Part.ArcOfParabola(Part.Parabola(App.Vector(%f, %f, %f), " - "App.Vector(%f, %f, %f), App.Vector(0, 0, 1)), %f, %f)") + boost::format( + "Part.ArcOfParabola(Part.Parabola(App.Vector(%f, %f, %f), " + "App.Vector(%f, %f, %f), App.Vector(0, 0, 1)), %f, %f)" + ) % focus.x % focus.y % focus.z % axisPoint.x % axisPoint.y % axisPoint.z - % startAngle % endAngle); + % startAngle % endAngle + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -333,24 +358,24 @@ PythonConverter::SingleGeometry PythonConverter::process(const Part::Geometry* g std::string weights = makeSplineInfoArrayString(bSpline->getWeights()); SingleGeometry sg; - sg.creation = - boost::str(boost::format("Part.BSplineCurve(%s, %s, %s, %s, %d, %s, False)") - % controlpoints.c_str() % mults.c_str() % knots.c_str() - % (bSpline->isPeriodic() ? "True" : "False") % bSpline->getDegree() - % weights.c_str()); + sg.creation = boost::str( + boost::format("Part.BSplineCurve(%s, %s, %s, %s, %d, %s, False)") + % controlpoints.c_str() % mults.c_str() % knots.c_str() + % (bSpline->isPeriodic() ? "True" : "False") % bSpline->getDegree() + % weights.c_str() + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, - {Part::GeomCircle::getClassTypeId(), - [](const Part::Geometry* geo) { + {Part::GeomCircle::getClassTypeId(), [](const Part::Geometry* geo) { auto circle = static_cast(geo); SingleGeometry sg; sg.creation = boost::str( - boost::format( - "Part.Circle(App.Vector(%f, %f, %f), App.Vector(%f, %f, %f), %f)") + boost::format("Part.Circle(App.Vector(%f, %f, %f), App.Vector(%f, %f, %f), %f)") % circle->getCenter().x % circle->getCenter().y % circle->getCenter().z % circle->getAxisDirection().x % circle->getAxisDirection().y - % circle->getAxisDirection().z % circle->getRadius()); + % circle->getAxisDirection().z % circle->getRadius() + ); sg.construction = Sketcher::GeometryFacade::getConstruction(geo); return sg; }}, @@ -381,17 +406,18 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo static std::map< const Sketcher::ConstraintType, - std::function< - std::string(const Sketcher::Constraint*, std::string&, std::string&, std::string&)>> + std::function> converterMap = { {Sketcher::Coincident, [](const Sketcher::Constraint* constr, std::string& geoId1, std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('Coincident', %s, %i, %s, %i") - % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos)); + return boost::str( + boost::format("Sketcher.Constraint('Coincident', %s, %i, %s, %i") % geoId1 + % static_cast(constr->FirstPos) % geoId2 + % static_cast(constr->SecondPos) + ); }}, {Sketcher::Horizontal, [](const Sketcher::Constraint* constr, @@ -399,14 +425,14 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Horizontal', %s") - % geoId1); + return boost::str(boost::format("Sketcher.Constraint('Horizontal', %s") % geoId1); } else { return boost::str( boost::format("Sketcher.Constraint('Horizontal', %s, %i, %s, %i") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos)); + % static_cast(constr->SecondPos) + ); } }}, {Sketcher::Vertical, @@ -415,14 +441,14 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Vertical', %s") - % geoId1); + return boost::str(boost::format("Sketcher.Constraint('Vertical', %s") % geoId1); } else { return boost::str( boost::format("Sketcher.Constraint('Vertical', %s, %i, %s, %i") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos)); + % static_cast(constr->SecondPos) + ); } }}, {Sketcher::Block, @@ -438,18 +464,22 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->FirstPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Tangent', %s, %s") - % geoId1 % geoId2); + return boost::str( + boost::format("Sketcher.Constraint('Tangent', %s, %s") % geoId1 % geoId2 + ); } else if (constr->SecondPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Tangent', %s, %i, %s") - % geoId1 % static_cast(constr->FirstPos) % geoId2); + return boost::str( + boost::format("Sketcher.Constraint('Tangent', %s, %i, %s") % geoId1 + % static_cast(constr->FirstPos) % geoId2 + ); } else { return boost::str( boost::format("Sketcher.Constraint('Tangent', %s, %i, %s, %i") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos)); + % static_cast(constr->SecondPos) + ); } }}, {Sketcher::Parallel, @@ -457,8 +487,9 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId1, std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('Parallel', %s, %s") % geoId1 - % geoId2); + return boost::str( + boost::format("Sketcher.Constraint('Parallel', %s, %s") % geoId1 % geoId2 + ); }}, {Sketcher::Perpendicular, []([[maybe_unused]] const Sketcher::Constraint* constr, @@ -466,19 +497,22 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->FirstPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Perpendicular', %s, %s") - % geoId1 % geoId2); + return boost::str( + boost::format("Sketcher.Constraint('Perpendicular', %s, %s") % geoId1 % geoId2 + ); } else if (constr->SecondPos == Sketcher::PointPos::none) { return boost::str( boost::format("Sketcher.Constraint('Perpendicular', %s, %i, %s") % geoId1 - % static_cast(constr->FirstPos) % geoId2); + % static_cast(constr->FirstPos) % geoId2 + ); } else { return boost::str( boost::format("Sketcher.Constraint('Perpendicular', %s, %i, %s, %i") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos)); + % static_cast(constr->SecondPos) + ); } }}, {Sketcher::Equal, @@ -486,8 +520,9 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId1, std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('Equal', %s, %s") % geoId1 - % geoId2); + return boost::str( + boost::format("Sketcher.Constraint('Equal', %s, %s") % geoId1 % geoId2 + ); }}, {Sketcher::InternalAlignment, [](const Sketcher::Constraint* constr, @@ -501,7 +536,8 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo || constr->AlignmentType == ParabolaFocalAxis) { return boost::str( boost::format("Sketcher.Constraint('InternalAlignment:%s', %s, %s") - % constr->internalAlignmentTypeToString() % geoId1 % geoId2); + % constr->internalAlignmentTypeToString() % geoId1 % geoId2 + ); } else if (constr->AlignmentType == EllipseFocus1 || constr->AlignmentType == EllipseFocus2 @@ -510,24 +546,25 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo return boost::str( boost::format("Sketcher.Constraint('InternalAlignment:%s', %s, %i, %s") % constr->internalAlignmentTypeToString() % geoId1 - % static_cast(constr->FirstPos) % geoId2); + % static_cast(constr->FirstPos) % geoId2 + ); } else if (constr->AlignmentType == BSplineControlPoint) { return boost::str( boost::format("Sketcher.Constraint('InternalAlignment:%s', %s, %i, %s, %i") % constr->internalAlignmentTypeToString() % geoId1 - % static_cast(constr->FirstPos) % geoId2 - % constr->InternalAlignmentIndex); + % static_cast(constr->FirstPos) % geoId2 % constr->InternalAlignmentIndex + ); } else if (constr->AlignmentType == BSplineKnotPoint) { return boost::str( boost::format("Sketcher.Constraint('InternalAlignment:%s', %s, 1, %s, %i") % constr->internalAlignmentTypeToString() % geoId1 % geoId2 - % constr->InternalAlignmentIndex); + % constr->InternalAlignmentIndex + ); } - THROWM(Base::ValueError, - "PythonConverter: Constraint Alignment Type not supported") + THROWM(Base::ValueError, "PythonConverter: Constraint Alignment Type not supported") }}, {Sketcher::Distance, [](const Sketcher::Constraint* constr, @@ -535,23 +572,29 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Distance', %s, %f") - % geoId1 % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Distance', %s, %f") % geoId1 + % constr->getValue() + ); } else if (constr->FirstPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Distance', %s, %s, %f") - % geoId1 % geoId2 % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Distance', %s, %s, %f") % geoId1 + % geoId2 % constr->getValue() + ); } else if (constr->SecondPos == Sketcher::PointPos::none) { return boost::str( boost::format("Sketcher.Constraint('Distance', %s, %i, %s, %f") % geoId1 - % static_cast(constr->FirstPos) % geoId2 % constr->getValue()); + % static_cast(constr->FirstPos) % geoId2 % constr->getValue() + ); } else { return boost::str( boost::format("Sketcher.Constraint('Distance', %s, %i, %s, %i, %f") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos) % constr->getValue()); + % static_cast(constr->SecondPos) % constr->getValue() + ); } }}, {Sketcher::Angle, @@ -560,26 +603,32 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, std::string& geoId3) { if (constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('Angle', %s, %f") % geoId1 - % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Angle', %s, %f") % geoId1 + % constr->getValue() + ); } else if (constr->Third == GeoEnum::GeoUndef) { if (constr->SecondPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('Angle', %s, %s, %f") - % geoId1 % geoId2 % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Angle', %s, %s, %f") % geoId1 + % geoId2 % constr->getValue() + ); } else { return boost::str( boost::format("Sketcher.Constraint('Angle', %s, %i, %s, %i, %f") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos) % constr->getValue()); + % static_cast(constr->SecondPos) % constr->getValue() + ); } } else { return boost::str( boost::format("Sketcher.Constraint('AngleViaPoint', %s, %s, %s, %i, %f") % geoId1 % geoId2 % geoId3 % static_cast(constr->ThirdPos) - % constr->getValue()); + % constr->getValue() + ); } }}, {Sketcher::DistanceX, @@ -588,19 +637,23 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('DistanceX', %s, %f") - % geoId1 % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('DistanceX', %s, %f") % geoId1 + % constr->getValue() + ); } else if (constr->SecondPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('DistanceX', %s, %i, %f") - % geoId1 % static_cast(constr->FirstPos) - % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('DistanceX', %s, %i, %f") % geoId1 + % static_cast(constr->FirstPos) % constr->getValue() + ); } else { return boost::str( boost::format("Sketcher.Constraint('DistanceX', %s, %i, %s, %i, %f") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos) % constr->getValue()); + % static_cast(constr->SecondPos) % constr->getValue() + ); } }}, {Sketcher::DistanceY, @@ -609,19 +662,23 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId2, [[maybe_unused]] std::string& geoId3) { if (constr->Second == GeoEnum::GeoUndef) { - return boost::str(boost::format("Sketcher.Constraint('DistanceY', %s, %f") - % geoId1 % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('DistanceY', %s, %f") % geoId1 + % constr->getValue() + ); } else if (constr->SecondPos == Sketcher::PointPos::none) { - return boost::str(boost::format("Sketcher.Constraint('DistanceY', %s, %i, %f") - % geoId1 % static_cast(constr->FirstPos) - % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('DistanceY', %s, %i, %f") % geoId1 + % static_cast(constr->FirstPos) % constr->getValue() + ); } else { return boost::str( boost::format("Sketcher.Constraint('DistanceY', %s, %i, %s, %i, %f") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos) % constr->getValue()); + % static_cast(constr->SecondPos) % constr->getValue() + ); } }}, {Sketcher::Radius, @@ -629,32 +686,40 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo std::string& geoId1, [[maybe_unused]] std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('Radius', %s, %f") % geoId1 - % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Radius', %s, %f") % geoId1 + % constr->getValue() + ); }}, {Sketcher::Diameter, [](const Sketcher::Constraint* constr, std::string& geoId1, [[maybe_unused]] std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('Diameter', %s, %f") % geoId1 - % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Diameter', %s, %f") % geoId1 + % constr->getValue() + ); }}, {Sketcher::Weight, [](const Sketcher::Constraint* constr, std::string& geoId1, [[maybe_unused]] std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('Weight', %s, %f") % geoId1 - % constr->getValue()); + return boost::str( + boost::format("Sketcher.Constraint('Weight', %s, %f") % geoId1 + % constr->getValue() + ); }}, {Sketcher::PointOnObject, [](const Sketcher::Constraint* constr, std::string& geoId1, std::string& geoId2, [[maybe_unused]] std::string& geoId3) { - return boost::str(boost::format("Sketcher.Constraint('PointOnObject', %s, %i, %s") - % geoId1 % static_cast(constr->FirstPos) % geoId2); + return boost::str( + boost::format("Sketcher.Constraint('PointOnObject', %s, %i, %s") % geoId1 + % static_cast(constr->FirstPos) % geoId2 + ); }}, {Sketcher::Symmetric, [](const Sketcher::Constraint* constr, @@ -665,14 +730,16 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo return boost::str( boost::format("Sketcher.Constraint('Symmetric', %s, %i, %s, %i, %s") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos) % geoId3); + % static_cast(constr->SecondPos) % geoId3 + ); } else { return boost::str( boost::format("Sketcher.Constraint('Symmetric', %s, %i, %s, %i, %s, %i") % geoId1 % static_cast(constr->FirstPos) % geoId2 % static_cast(constr->SecondPos) % geoId3 - % static_cast(constr->ThirdPos)); + % static_cast(constr->ThirdPos) + ); } }}, {Sketcher::SnellsLaw, @@ -683,7 +750,8 @@ std::string PythonConverter::process(const Sketcher::Constraint* constraint, Geo return boost::str( boost::format("Sketcher.Constraint('SnellsLaw', %s, %i, %s, %i, %s, %f") % geoId1 % static_cast(constr->FirstPos) % geoId2 - % static_cast(constr->SecondPos) % geoId3 % constr->getValue()); + % static_cast(constr->SecondPos) % geoId3 % constr->getValue() + ); }}, }; diff --git a/src/Mod/Sketcher/App/PythonConverter.h b/src/Mod/Sketcher/App/PythonConverter.h index 8062064589..56cac3b8f1 100644 --- a/src/Mod/Sketcher/App/PythonConverter.h +++ b/src/Mod/Sketcher/App/PythonConverter.h @@ -73,24 +73,32 @@ public: static std::string convert(const Part::Geometry* geo, Mode mode = Mode::CreateInternalGeometry); /// Convert a vector of geometries into the string representing the command creating them - static std::string convert(const std::string& doc, - const std::vector& geos, - Mode mode = Mode::CreateInternalGeometry); + static std::string convert( + const std::string& doc, + const std::vector& geos, + Mode mode = Mode::CreateInternalGeometry + ); - static std::string convert(const Sketcher::Constraint* constraint, - GeoIdMode geoIdMode = GeoIdMode::DoNotChangeGeoIds); + static std::string convert( + const Sketcher::Constraint* constraint, + GeoIdMode geoIdMode = GeoIdMode::DoNotChangeGeoIds + ); - static std::string convert(const std::string& doc, - const std::vector& constraints, - GeoIdMode geoIdMode = GeoIdMode::DoNotChangeGeoIds); + static std::string convert( + const std::string& doc, + const std::vector& constraints, + GeoIdMode geoIdMode = GeoIdMode::DoNotChangeGeoIds + ); static std::vector multiLine(std::string&& singlestring); private: static SingleGeometry process(const Part::Geometry* geo); - static std::string process(const Sketcher::Constraint* constraint, - GeoIdMode geoIdMode = GeoIdMode::DoNotChangeGeoIds); + static std::string process( + const Sketcher::Constraint* constraint, + GeoIdMode geoIdMode = GeoIdMode::DoNotChangeGeoIds + ); }; } // namespace Sketcher diff --git a/src/Mod/Sketcher/App/Sketch.cpp b/src/Mod/Sketcher/App/Sketch.cpp index c6fdf42bb5..95b030bb9b 100644 --- a/src/Mod/Sketcher/App/Sketch.cpp +++ b/src/Mod/Sketcher/App/Sketch.cpp @@ -135,10 +135,12 @@ void Sketch::clear() MalformedConstraints.clear(); } -bool Sketch::analyseBlockedGeometry(const std::vector& internalGeoList, - const std::vector& constraintList, - std::vector& onlyblockedGeometry, - std::vector& blockedGeoIds) const +bool Sketch::analyseBlockedGeometry( + const std::vector& internalGeoList, + const std::vector& constraintList, + std::vector& onlyblockedGeometry, + std::vector& blockedGeoIds +) const { // To understand this function read the documentation in Sketch.h // It is important that "onlyblockedGeometry" ONLY identifies blocked geometry @@ -183,9 +185,11 @@ bool Sketch::analyseBlockedGeometry(const std::vector& internal return doesBlockAffectOtherConstraints; } -int Sketch::setUpSketch(const std::vector& GeoList, - const std::vector& ConstraintList, - int extGeoCount) +int Sketch::setUpSketch( + const std::vector& GeoList, + const std::vector& ConstraintList, + int extGeoCount +) { Base::TimeElapsed start_time; @@ -208,8 +212,8 @@ int Sketch::setUpSketch(const std::vector& GeoList, // Pre-analysis of blocked geometry (new block constraint) to fix geometry only affected by a // block constraint (see comment in Sketch.h) std::vector blockedGeoIds; - bool doesBlockAffectOtherConstraints = - analyseBlockedGeometry(intGeoList, ConstraintList, onlyBlockedGeometry, blockedGeoIds); + bool doesBlockAffectOtherConstraints + = analyseBlockedGeometry(intGeoList, ConstraintList, onlyBlockedGeometry, blockedGeoIds); #ifdef DEBUG_BLOCK_CONSTRAINT if (doesBlockAffectOtherConstraints) { @@ -266,8 +270,8 @@ int Sketch::setUpSketch(const std::vector& GeoList, std::vector params_to_block; - bool unsatisfied_groups = - analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); + bool unsatisfied_groups + = analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); // I am unsure if more than one QR iterations are needed with the current implementation. // @@ -283,12 +287,11 @@ int Sketch::setUpSketch(const std::vector& GeoList, // Another QR iteration fixParametersAndDiagnose(params_to_block); - unsatisfied_groups = - analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); + unsatisfied_groups + = analyseBlockedConstraintDependentParameters(blockedGeoIds, params_to_block); if (debugMode == GCS::IterationLevel) { - Base::Console().log("Sketcher::setUpSketch()-BlockConstraint-PostAnalysis:%d\n", - index); + Base::Console().log("Sketcher::setUpSketch()-BlockConstraint-PostAnalysis:%d\n", index); } index++; } @@ -309,7 +312,8 @@ int Sketch::setUpSketch(const std::vector& GeoList, "\n Param=%x ,GeoId=%d, GeoPos=%d", param2geoelement.find(*std::next(groups[i].begin(), j))->first, param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, - param2geoelement.find(*std::next(groups[i].begin(), j))->second.second); + param2geoelement.find(*std::next(groups[i].begin(), j))->second.second + ); } } } @@ -327,8 +331,10 @@ int Sketch::setUpSketch(const std::vector& GeoList, if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { Base::TimeElapsed end_time; - Base::Console().log("Sketcher::setUpSketch()-T:%s\n", - Base::TimeElapsed::diffTime(start_time, end_time).c_str()); + Base::Console().log( + "Sketcher::setUpSketch()-T:%s\n", + Base::TimeElapsed::diffTime(start_time, end_time).c_str() + ); } return GCSsys.dofsNumber(); @@ -370,7 +376,8 @@ void Sketch::fixParametersAndDiagnose(std::vector& params_to_block) bool Sketch::analyseBlockedConstraintDependentParameters( std::vector& blockedGeoIds, - std::vector& params_to_block) const + std::vector& params_to_block +) const { // 1. Retrieve solver information std::vector> groups; @@ -393,7 +400,8 @@ bool Sketch::analyseBlockedConstraintDependentParameters( "\n Param=%x ,GeoId=%d, GeoPos=%d", param2geoelement.find(*std::next(groups[i].begin(), j))->first, param2geoelement.find(*std::next(groups[i].begin(), j))->second.first, - param2geoelement.find(*std::next(groups[i].begin(), j))->second.second); + param2geoelement.find(*std::next(groups[i].begin(), j))->second.second + ); } } #endif // DEBUG_BLOCK_CONSTRAINT @@ -403,8 +411,7 @@ bool Sketch::analyseBlockedConstraintDependentParameters( double* thisparam = *std::next(groups[i].begin(), j); - if (auto element = param2geoelement.find(thisparam); - element != param2geoelement.end()) { + if (auto element = param2geoelement.find(thisparam); element != param2geoelement.end()) { if (auto blockable = std::ranges::find(blockedGeoIds, std::get<0>(element->second)); blockable != blockedGeoIds.end()) { @@ -471,7 +478,8 @@ void Sketch::calculateDependentParametersElements() } auto solvext = std::static_pointer_cast( - geo.geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock()); + geo.geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock() + ); if (GCSsys.isEmptyDiagnoseMatrix()) { solvext->init(SolverGeometryExtension::Dependent); @@ -493,9 +501,8 @@ void Sketch::calculateDependentParametersElements() auto geoid = std::get<0>(element->second); auto geopos = std::get<1>(element->second); auto solvext = std::static_pointer_cast( - Geoms[geoid] - .geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()) - .lock()); + Geoms[geoid].geo->getExtension(Sketcher::SolverGeometryExtension::getClassTypeId()).lock() + ); auto index = std::get<2>(element->second); @@ -544,7 +551,8 @@ void Sketch::calculateDependentParametersElements() if (element != param2geoelement.end()) { pDependencyGroups[i].insert( - std::pair(std::get<0>(element->second), std::get<1>(element->second))); + std::pair(std::get<0>(element->second), std::get<1>(element->second)) + ); } } } @@ -573,12 +581,16 @@ void Sketch::calculateDependentParametersElements() size_t endcount = pDependencyGroups.size() - 1; for (size_t i = 0; i < endcount; i++) { - if (havecommonelement(pDependencyGroups[i].begin(), - pDependencyGroups[i].end(), - pDependencyGroups[i + 1].begin(), - pDependencyGroups[i + 1].end())) { - pDependencyGroups[i].insert(pDependencyGroups[i + 1].begin(), - pDependencyGroups[i + 1].end()); + if (havecommonelement( + pDependencyGroups[i].begin(), + pDependencyGroups[i].end(), + pDependencyGroups[i + 1].begin(), + pDependencyGroups[i + 1].end() + )) { + pDependencyGroups[i].insert( + pDependencyGroups[i + 1].begin(), + pDependencyGroups[i + 1].end() + ); pDependencyGroups.erase(pDependencyGroups.begin() + i + 1); endcount--; } @@ -586,8 +598,7 @@ void Sketch::calculateDependentParametersElements() } } -std::set> Sketch::getDependencyGroup(int geoId, - PointPos pos) const +std::set> Sketch::getDependencyGroup(int geoId, PointPos pos) const { geoId = checkGeoId(geoId); @@ -712,8 +723,7 @@ int Sketch::addGeometry(const Part::Geometry* geo, bool fixed) return addBSpline(*bsp, fixed); } else { - throw Base::TypeError( - "Sketch::addGeometry(): Unknown or unsupported type added to a sketch"); + throw Base::TypeError("Sketch::addGeometry(): Unknown or unsupported type added to a sketch"); } } @@ -726,8 +736,7 @@ int Sketch::addGeometry(const std::vector& geos, bool fixed) return ret; } -int Sketch::addGeometry(const std::vector& geos, - const std::vector& blockedGeometry) +int Sketch::addGeometry(const std::vector& geos, const std::vector& blockedGeometry) { assert(geos.size() == blockedGeometry.size()); @@ -774,11 +783,13 @@ int Sketch::addPoint(const Part::GeomPoint& point, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); } // return the position of the newly added geometry @@ -839,19 +850,23 @@ int Sketch::addLineSegment(const Part::GeomLineSegment& lineSegment, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1) + ); } // return the position of the newly added geometry @@ -930,39 +945,48 @@ int Sketch::addArc(const Part::GeomArcOfCircle& circleSegment, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(r), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a1), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a2), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2) + ); } // return the position of the newly added geometry @@ -1058,47 +1082,58 @@ int Sketch::addArcOfEllipse(const Part::GeomArcOfEllipse& ellipseSegment, bool f param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(f1X), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(f1Y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(rmin), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a1), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a2), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 4)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 4) + ); } // return the position of the newly added geometry @@ -1192,47 +1227,58 @@ int Sketch::addArcOfHyperbola(const Part::GeomArcOfHyperbola& hyperbolaSegment, param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(f1X), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(f1Y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(rmin), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a1), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a2), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 4)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 4) + ); } @@ -1317,43 +1363,53 @@ int Sketch::addArcOfParabola(const Part::GeomArcOfParabola& parabolaSegment, boo param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p3.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p4.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p4.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a1), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(a2), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 3) + ); } // return the position of the newly added geometry @@ -1427,11 +1483,13 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve& bspline, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p.x), - std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++)); + std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p.y), - std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++)); + std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++) + ); } } @@ -1446,7 +1504,8 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve& bspline, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(r), - std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++)); + std::forward_as_tuple(Geoms.size(), Sketcher::PointPos::none, i++) + ); } } @@ -1535,19 +1594,23 @@ int Sketch::addBSpline(const Part::GeomBSplineCurve& bspline, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::start, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p2.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::end, 1) + ); } // return the position of the newly added geometry @@ -1597,15 +1660,18 @@ int Sketch::addCircle(const Part::GeomCircle& cir, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(p1.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(r), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0) + ); } // return the position of the newly added geometry @@ -1670,31 +1736,38 @@ int Sketch::addEllipse(const Part::GeomEllipse& elip, bool fixed) param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(c.x), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(c.y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::mid, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(f1X), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 0) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(f1Y), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 1) + ); param2geoelement.emplace( std::piecewise_construct, std::forward_as_tuple(rmin), - std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2)); + std::forward_as_tuple(Geoms.size() - 1, Sketcher::PointPos::none, 2) + ); } // return the position of the newly added geometry return Geoms.size() - 1; } -std::vector Sketch::extractGeometry(bool withConstructionElements, - bool withExternalElements) const +std::vector Sketch::extractGeometry( + bool withConstructionElements, + bool withExternalElements +) const { std::vector temp; temp.reserve(Geoms.size()); @@ -1741,9 +1814,7 @@ Py::Tuple Sketch::getPyGeometry() const for (auto it = Geoms.begin(); it != Geoms.end(); ++it, ++i) { switch (it->type) { case Point: { - Base::Vector3d temp(*(Points[it->startPointId].x), - *(Points[it->startPointId].y), - 0); + Base::Vector3d temp(*(Points[it->startPointId].x), *(Points[it->startPointId].y), 0); tuple[i] = Py::asObject(new VectorPy(temp)); break; } @@ -1852,7 +1923,8 @@ int Sketch::addConstraint(const Constraint* constraint) { if (Geoms.empty()) { throw Base::ValueError( - "Sketch::addConstraint. Can't add constraint to a sketch with no geometry!"); + "Sketch::addConstraint. Can't add constraint to a sketch with no geometry!" + ); } int rtn = -1; @@ -1884,13 +1956,9 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addCoordinateXConstraint(constraint->First, - constraint->FirstPos, - c.value, - c.driving); + rtn = addCoordinateXConstraint(constraint->First, constraint->FirstPos, c.value, c.driving); } - else if (constraint->SecondPos - != PointPos::none) { // point to point horizontal distance + else if (constraint->SecondPos != PointPos::none) { // point to point horizontal distance c.value = new double(constraint->getValue()); if (c.driving) { FixParameters.push_back(c.value); @@ -1900,12 +1968,14 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addDistanceXConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - c.value, - c.driving); + rtn = addDistanceXConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving + ); } break; case DistanceY: @@ -1931,10 +2001,7 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addCoordinateYConstraint(constraint->First, - constraint->FirstPos, - c.value, - c.driving); + rtn = addCoordinateYConstraint(constraint->First, constraint->FirstPos, c.value, c.driving); } else if (constraint->SecondPos != PointPos::none) { // point to point vertical distance c.value = new double(constraint->getValue()); @@ -1946,12 +2013,14 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addDistanceYConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - c.value, - c.driving); + rtn = addDistanceYConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving + ); } break; case Horizontal: @@ -1959,10 +2028,12 @@ int Sketch::addConstraint(const Constraint* constraint) rtn = addHorizontalConstraint(constraint->First); } else { // two points on the same horizontal line - rtn = addHorizontalConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos); + rtn = addHorizontalConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos + ); } break; case Vertical: @@ -1970,17 +2041,21 @@ int Sketch::addConstraint(const Constraint* constraint) rtn = addVerticalConstraint(constraint->First); } else { // two points on the same vertical line - rtn = addVerticalConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos); + rtn = addVerticalConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos + ); } break; case Coincident: - rtn = addPointCoincidentConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos); + rtn = addPointCoincidentConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos + ); break; case PointOnObject: if (Geoms[checkGeoId(constraint->Second)].type == BSpline) { @@ -1988,15 +2063,19 @@ int Sketch::addConstraint(const Constraint* constraint) // Driving doesn't make sense here Parameters.push_back(c.value); - rtn = addPointOnObjectConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - c.value); + rtn = addPointOnObjectConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + c.value + ); } else { - rtn = addPointOnObjectConstraint(constraint->First, - constraint->FirstPos, - constraint->Second); + rtn = addPointOnObjectConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second + ); } break; case Parallel: @@ -2019,15 +2098,17 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addAngleAtPointConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - constraint->Third, - constraint->ThirdPos, - c.value, - constraint->Type, - c.driving); + rtn = addAngleAtPointConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos, + c.value, + constraint->Type, + c.driving + ); } break; case Tangent: { @@ -2056,9 +2137,11 @@ int Sketch::addConstraint(const Constraint* constraint) if (Geoms[linegeoid].type == Line) { if (constraint->SecondPos == PointPos::none) { - rtn = addTangentLineAtBSplineKnotConstraint(linegeoid, - bsplinegeoid, - knotgeoId); + rtn = addTangentLineAtBSplineKnotConstraint( + linegeoid, + bsplinegeoid, + knotgeoId + ); isSpecialCase = true; } @@ -2068,7 +2151,8 @@ int Sketch::addConstraint(const Constraint* constraint) linegeoid, constraint->SecondPos, bsplinegeoid, - knotgeoId); + knotgeoId + ); isSpecialCase = true; } @@ -2088,15 +2172,17 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addAngleAtPointConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - constraint->Third, - constraint->ThirdPos, - c.value, - constraint->Type, - c.driving); + rtn = addAngleAtPointConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos, + c.value, + constraint->Type, + c.driving + ); } break; } @@ -2110,18 +2196,19 @@ int Sketch::addConstraint(const Constraint* constraint) Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addDistanceConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - c.value, - c.driving); + rtn = addDistanceConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving + ); } - else if (constraint->FirstPos == PointPos::none - && constraint->SecondPos == PointPos::none + else if (constraint->FirstPos == PointPos::none && constraint->SecondPos == PointPos::none && constraint->Second != GeoEnum::GeoUndef - && constraint->Third - == GeoEnum::GeoUndef) { // circle to circle, circle to arc, etc. + && constraint->Third == GeoEnum::GeoUndef) { // circle to circle, circle to + // arc, etc. c.value = new double(constraint->getValue()); if (c.driving) { @@ -2131,10 +2218,7 @@ int Sketch::addConstraint(const Constraint* constraint) Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addDistanceConstraint(constraint->First, - constraint->Second, - c.value, - c.driving); + rtn = addDistanceConstraint(constraint->First, constraint->Second, c.value, c.driving); } else if (constraint->Second != GeoEnum::GeoUndef) { if (constraint->FirstPos != PointPos::none) { // point to line distance @@ -2146,11 +2230,13 @@ int Sketch::addConstraint(const Constraint* constraint) Parameters.push_back(c.value); DrivenParameters.push_back(c.value); } - rtn = addDistanceConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - c.value, - c.driving); + rtn = addDistanceConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + c.value, + c.driving + ); } } else { // line length, arc length @@ -2177,15 +2263,17 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addAngleAtPointConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - constraint->Third, - constraint->ThirdPos, - c.value, - constraint->Type, - c.driving); + rtn = addAngleAtPointConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos, + c.value, + constraint->Type, + c.driving + ); } // angle between two lines (with explicit start points) else if (constraint->SecondPos != PointPos::none) { @@ -2198,12 +2286,14 @@ int Sketch::addConstraint(const Constraint* constraint) DrivenParameters.push_back(c.value); } - rtn = addAngleConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - c.value, - c.driving); + rtn = addAngleConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + c.value, + c.driving + ); } else if (constraint->Second != GeoEnum::GeoUndef) { // angle between two lines c.value = new double(constraint->getValue()); @@ -2274,30 +2364,32 @@ int Sketch::addConstraint(const Constraint* constraint) break; case Symmetric: if (constraint->ThirdPos != PointPos::none) { - rtn = addSymmetricConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - constraint->Third, - constraint->ThirdPos); + rtn = addSymmetricConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + constraint->ThirdPos + ); } else { - rtn = addSymmetricConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - constraint->Third); + rtn = addSymmetricConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third + ); } break; case InternalAlignment: switch (constraint->AlignmentType) { case EllipseMajorDiameter: - rtn = addInternalAlignmentEllipseMajorDiameter(constraint->First, - constraint->Second); + rtn = addInternalAlignmentEllipseMajorDiameter(constraint->First, constraint->Second); break; case EllipseMinorDiameter: - rtn = addInternalAlignmentEllipseMinorDiameter(constraint->First, - constraint->Second); + rtn = addInternalAlignmentEllipseMinorDiameter(constraint->First, constraint->Second); break; case EllipseFocus1: rtn = addInternalAlignmentEllipseFocus1(constraint->First, constraint->Second); @@ -2306,12 +2398,16 @@ int Sketch::addConstraint(const Constraint* constraint) rtn = addInternalAlignmentEllipseFocus2(constraint->First, constraint->Second); break; case HyperbolaMajor: - rtn = addInternalAlignmentHyperbolaMajorDiameter(constraint->First, - constraint->Second); + rtn = addInternalAlignmentHyperbolaMajorDiameter( + constraint->First, + constraint->Second + ); break; case HyperbolaMinor: - rtn = addInternalAlignmentHyperbolaMinorDiameter(constraint->First, - constraint->Second); + rtn = addInternalAlignmentHyperbolaMinorDiameter( + constraint->First, + constraint->Second + ); break; case HyperbolaFocus: rtn = addInternalAlignmentHyperbolaFocus(constraint->First, constraint->Second); @@ -2320,19 +2416,24 @@ int Sketch::addConstraint(const Constraint* constraint) rtn = addInternalAlignmentParabolaFocus(constraint->First, constraint->Second); break; case BSplineControlPoint: - rtn = - addInternalAlignmentBSplineControlPoint(constraint->First, - constraint->Second, - constraint->InternalAlignmentIndex); + rtn = addInternalAlignmentBSplineControlPoint( + constraint->First, + constraint->Second, + constraint->InternalAlignmentIndex + ); break; case BSplineKnotPoint: - rtn = addInternalAlignmentKnotPoint(constraint->First, - constraint->Second, - constraint->InternalAlignmentIndex); + rtn = addInternalAlignmentKnotPoint( + constraint->First, + constraint->Second, + constraint->InternalAlignmentIndex + ); break; case ParabolaFocalAxis: - rtn = addInternalAlignmentParabolaFocalDistance(constraint->First, - constraint->Second); + rtn = addInternalAlignmentParabolaFocalDistance( + constraint->First, + constraint->Second + ); break; default: break; @@ -2354,14 +2455,16 @@ int Sketch::addConstraint(const Constraint* constraint) } // assert(constraint->ThirdPos==none); //will work anyway... - rtn = addSnellsLawConstraint(constraint->First, - constraint->FirstPos, - constraint->Second, - constraint->SecondPos, - constraint->Third, - c.value, - c.secondvalue, - c.driving); + rtn = addSnellsLawConstraint( + constraint->First, + constraint->FirstPos, + constraint->Second, + constraint->SecondPos, + constraint->Third, + c.value, + c.secondvalue, + c.driving + ); } break; case Sketcher::None: // ambiguous enum value case Sketcher::Block: // handled separately while adding geometry @@ -2383,8 +2486,7 @@ int Sketch::addConstraints(const std::vector& ConstraintList) if (rtn == -1) { int humanConstraintId = cid + 1; - Base::Console().error("Sketcher constraint number %d is malformed!\n", - humanConstraintId); + Base::Console().error("Sketcher constraint number %d is malformed!\n", humanConstraintId); MalformedConstraints.push_back(humanConstraintId); } } @@ -2392,8 +2494,10 @@ int Sketch::addConstraints(const std::vector& ConstraintList) return rtn; } -int Sketch::addConstraints(const std::vector& ConstraintList, - const std::vector& unenforceableConstraints) +int Sketch::addConstraints( + const std::vector& ConstraintList, + const std::vector& unenforceableConstraints +) { int rtn = -1; @@ -2404,8 +2508,7 @@ int Sketch::addConstraints(const std::vector& ConstraintList, if (rtn == -1) { int humanConstraintId = cid + 1; - Base::Console().error("Sketcher constraint number %d is malformed!\n", - humanConstraintId); + Base::Console().error("Sketcher constraint number %d is malformed!\n", humanConstraintId); MalformedConstraints.push_back(humanConstraintId); } } @@ -2417,9 +2520,11 @@ int Sketch::addConstraints(const std::vector& ConstraintList, return rtn; } -void Sketch::getBlockedGeometry(std::vector& blockedGeometry, - std::vector& unenforceableConstraints, - const std::vector& ConstraintList) const +void Sketch::getBlockedGeometry( + std::vector& blockedGeometry, + std::vector& unenforceableConstraints, + const std::vector& ConstraintList +) const { std::vector internalAlignmentConstraintIndex; std::vector internalAlignmentgeo; @@ -2452,8 +2557,8 @@ void Sketch::getBlockedGeometry(std::vector& blockedGeometry, if (blockedGeometry[ConstraintList[idx]->Second]) { blockedGeometry[ConstraintList[idx]->First] = true; // associated geometry gets the same blocking constraint index as the blocked element - geo2blockingconstraintindex[ConstraintList[idx]->First] = - geo2blockingconstraintindex[ConstraintList[idx]->Second]; + geo2blockingconstraintindex[ConstraintList[idx]->First] + = geo2blockingconstraintindex[ConstraintList[idx]->Second]; internalAlignmentgeo.push_back(ConstraintList[idx]->First); unenforceableConstraints[idx] = true; } @@ -2479,8 +2584,7 @@ void Sketch::getBlockedGeometry(std::vector& blockedGeometry, // unenforceable if ((*it)->Second == GeoEnum::GeoUndef && (*it)->Third == GeoEnum::GeoUndef && (*it)->First >= 0) { - if (blockedGeometry[(*it)->First] - && i < geo2blockingconstraintindex[(*it)->First]) { + if (blockedGeometry[(*it)->First] && i < geo2blockingconstraintindex[(*it)->First]) { unenforceableConstraints[i] = true; } } @@ -2600,12 +2704,14 @@ int Sketch::addDistanceYConstraint(int geoId, double* value, bool driving) return ConstraintsCounter; } -int Sketch::addDistanceXConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving) +int Sketch::addDistanceXConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving +) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -2625,12 +2731,14 @@ int Sketch::addDistanceXConstraint(int geoId1, return -1; } -int Sketch::addDistanceYConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving) +int Sketch::addDistanceYConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving +) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -2788,9 +2896,11 @@ int Sketch::addPerpendicularConstraint(int geoId1, int geoId2) } } - Base::Console().warning("Perpendicular constraints between %s and %s are not supported.\n", - nameByType(Geoms[geoId1].type), - nameByType(Geoms[geoId2].type)); + Base::Console().warning( + "Perpendicular constraints between %s and %s are not supported.\n", + nameByType(Geoms[geoId1].type), + nameByType(Geoms[geoId2].type) + ); return -1; } @@ -2848,8 +2958,10 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().error("Direct tangency constraint between line and B-spline is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between line and B-spline is not " + "supported. Use tangent-via-point instead." + ); return -1; } } @@ -2862,8 +2974,10 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - Base::Console().error("Direct tangency constraint between circle and ellipse is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between circle and ellipse is not " + "supported. Use tangent-via-point instead." + ); return -1; } else if (Geoms[geoId2].type == Arc) { @@ -2873,25 +2987,33 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().error("Direct tangency constraint between circle and B-spline is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between circle and B-spline is not " + "supported. Use tangent-via-point instead." + ); return -1; } } else if (Geoms[geoId1].type == Ellipse) { if (Geoms[geoId2].type == Circle) { - Base::Console().error("Direct tangency constraint between circle and ellipse is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between circle and ellipse is not " + "supported. Use tangent-via-point instead." + ); return -1; } else if (Geoms[geoId2].type == Arc) { - Base::Console().error("Direct tangency constraint between arc and ellipse is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between arc and ellipse is not " + "supported. Use tangent-via-point instead." + ); return -1; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().error("Direct tangency constraint between ellipse and B-spline is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between ellipse and B-spline is not " + "supported. Use tangent-via-point instead." + ); return -1; } } @@ -2904,8 +3026,10 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == Ellipse) { - Base::Console().error("Direct tangency constraint between arc and ellipse is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between arc and ellipse is not " + "supported. Use tangent-via-point instead." + ); return -1; } else if (Geoms[geoId2].type == Arc) { @@ -2915,23 +3039,29 @@ int Sketch::addTangentConstraint(int geoId1, int geoId2) return ConstraintsCounter; } else if (Geoms[geoId2].type == BSpline) { - Base::Console().error("Direct tangency constraint between arc and B-spline is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint between arc and B-spline is not " + "supported. Use tangent-via-point instead." + ); return -1; } } else if (Geoms[geoId1].type == BSpline) { - Base::Console().error("Direct tangency constraint including B-splines is not " - "supported. Use tangent-via-point instead."); + Base::Console().error( + "Direct tangency constraint including B-splines is not " + "supported. Use tangent-via-point instead." + ); return -1; } return -1; } -int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, - int checkedbsplinegeoId, - int checkedknotgeoid) +int Sketch::addTangentLineAtBSplineKnotConstraint( + int checkedlinegeoId, + int checkedbsplinegeoId, + int checkedknotgeoid +) { GCS::BSpline& b = BSplines[Geoms[checkedbsplinegeoId].index]; GCS::Line& l = Lines[Geoms[checkedlinegeoId].index]; @@ -2949,8 +3079,10 @@ int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, if (b.mult[knotindex] >= b.degree) { if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size() - 1))) { - Base::Console().error("addTangentLineAtBSplineKnotConstraint: cannot set constraint " - "when B-spline slope is discontinuous at knot!\n"); + Base::Console().error( + "addTangentLineAtBSplineKnotConstraint: cannot set constraint " + "when B-spline slope is discontinuous at knot!\n" + ); return -1; } else { @@ -2964,23 +3096,26 @@ int Sketch::addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, // For now we just throw an error. Base::Console().error( "addTangentLineAtBSplineKnotConstraint: This method cannot set tangent constraints " - "at end knots of a B-spline. Constrain the start/end points instead.\n"); + "at end knots of a B-spline. Constrain the start/end points instead.\n" + ); return -1; } } else { // increases ConstraintsCounter - int tag = - Sketch::addPointOnObjectConstraint(checkedknotgeoid, PointPos::start, checkedlinegeoId); + int tag + = Sketch::addPointOnObjectConstraint(checkedknotgeoid, PointPos::start, checkedlinegeoId); GCSsys.addConstraintTangentAtBSplineKnot(b, l, knotindex, tag); return ConstraintsCounter; } } -int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, - PointPos endpointPos, - int checkedbsplinegeoId, - int checkedknotgeoid) +int Sketch::addTangentLineEndpointAtBSplineKnotConstraint( + int checkedlinegeoId, + PointPos endpointPos, + int checkedbsplinegeoId, + int checkedknotgeoid +) { GCS::BSpline& b = BSplines[Geoms[checkedbsplinegeoId].index]; GCS::Line& l = Lines[Geoms[checkedlinegeoId].index]; @@ -3002,8 +3137,10 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, if (b.mult[knotindex] >= b.degree) { if (b.periodic || (knotindex > 0 && knotindex < (b.knots.size() - 1))) { - Base::Console().error("addTangentLineEndpointAtBSplineKnotConstraint: cannot set " - "constraint when B-spline slope is discontinuous at knot!\n"); + Base::Console().error( + "addTangentLineEndpointAtBSplineKnotConstraint: cannot set " + "constraint when B-spline slope is discontinuous at knot!\n" + ); return -1; } else { @@ -3015,9 +3152,11 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, // nullptr, Tangent, true); // For now we just throw an error. - Base::Console().error("addTangentLineEndpointAtBSplineKnotConstraint: This method " - "cannot set tangent constraint at end knots of a B-spline. " - "Constrain the start/end points instead.\n"); + Base::Console().error( + "addTangentLineEndpointAtBSplineKnotConstraint: This method " + "cannot set tangent constraint at end knots of a B-spline. " + "Constrain the start/end points instead.\n" + ); return -1; } } @@ -3035,15 +3174,17 @@ int Sketch::addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, // geoid1, geoid2 and geoid3 as in the constraint object. // For perp-ty and tangency, angle is used to lock the direction. // angle==0 - autodetect direction. +pi/2, -pi/2 - specific direction. -int Sketch::addAngleAtPointConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - int geoId3, - PointPos pos3, - double* value, - ConstraintType cTyp, - bool driving) +int Sketch::addAngleAtPointConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + int geoId3, + PointPos pos3, + double* value, + ConstraintType cTyp, + bool driving +) { using std::numbers::pi; if (!(cTyp == Angle || cTyp == Tangent || cTyp == Perpendicular)) { @@ -3126,8 +3267,7 @@ int Sketch::addAngleAtPointConstraint(int geoId1, angleDesire = pi / 2; } - if (*value - == 0.0) { // autodetect tangency internal/external (and same for perpendicularity) + if (*value == 0.0) { // autodetect tangency internal/external (and same for perpendicularity) double angleErr = GCSsys.calculateAngleViaPoint(*crv1, *crv2, p) - angleDesire; // bring angleErr to -pi..pi if (angleErr > pi) { @@ -3161,25 +3301,23 @@ int Sketch::addAngleAtPointConstraint(int geoId1, Parameters.push_back(pointparam); --ConstraintsCounter; // Do this just before point-on-object because ConstraintsCounter // is increased again before being used - tag = addPointOnObjectConstraint(geoId1, - pos1, - geoId2, - pointparam, - driving); // increases ConstraintsCounter - GCSsys.addConstraintAngleViaPointAndParam(*crv2, - *crv1, - p, - pointparam, - angle, - tag, - driving); + tag = addPointOnObjectConstraint( + geoId1, + pos1, + geoId2, + pointparam, + driving + ); // increases ConstraintsCounter + GCSsys.addConstraintAngleViaPointAndParam(*crv2, *crv1, p, pointparam, angle, tag, driving); } else { // increases ConstraintsCounter - tag = Sketch::addPointOnObjectConstraint(geoId1, - pos1, - geoId2, - driving); // increases ConstraintsCounter + tag = Sketch::addPointOnObjectConstraint( + geoId1, + pos1, + geoId2, + driving + ); // increases ConstraintsCounter GCSsys.addConstraintAngleViaPoint(*crv1, *crv2, p, angle, tag, driving); } } @@ -3205,30 +3343,36 @@ int Sketch::addAngleAtPointConstraint(int geoId1, Parameters.push_back(pointparam1); --ConstraintsCounter; // Do this just before point-on-object because // ConstraintsCounter is increased again before being used - addPointOnObjectConstraint(geoId3, - pos3, - geoId1, - pointparam1, - driving); // increases ConstraintsCounter + addPointOnObjectConstraint( + geoId3, + pos3, + geoId1, + pointparam1, + driving + ); // increases ConstraintsCounter partBsp = static_cast(Geoms[geoId2].geo); partBsp->closestParameter(Base::Vector3d(*p3.x, *p3.y, 0.0), uNear); double* pointparam2 = new double(uNear); --ConstraintsCounter; // Do this just before point-on-object because // ConstraintsCounter is increased again before being used - addPointOnObjectConstraint(geoId3, - pos3, - geoId2, - pointparam2, - driving); // increases ConstraintsCounter + addPointOnObjectConstraint( + geoId3, + pos3, + geoId2, + pointparam2, + driving + ); // increases ConstraintsCounter Parameters.push_back(pointparam2); - GCSsys.addConstraintAngleViaPointAndTwoParams(*crv1, - *crv2, - p, - pointparam1, - pointparam2, - angle, - tag, - driving); + GCSsys.addConstraintAngleViaPointAndTwoParams( + *crv1, + *crv2, + p, + pointparam1, + pointparam2, + angle, + tag, + driving + ); } else { if (Geoms[geoId1].type != BSpline) { @@ -3246,18 +3390,14 @@ int Sketch::addAngleAtPointConstraint(int geoId1, Parameters.push_back(pointparam); --ConstraintsCounter; // Do this just before point-on-object because // ConstraintsCounter is increased again before being used - addPointOnObjectConstraint(geoId3, - pos3, - geoId1, - pointparam, - driving); // increases ConstraintsCounter - GCSsys.addConstraintAngleViaPointAndParam(*crv1, - *crv2, - p, - pointparam, - angle, - tag, - driving); + addPointOnObjectConstraint( + geoId3, + pos3, + geoId1, + pointparam, + driving + ); // increases ConstraintsCounter + GCSsys.addConstraintAngleViaPointAndParam(*crv1, *crv2, p, pointparam, angle, tag, driving); } } else { @@ -3289,11 +3429,7 @@ int Sketch::addDistanceConstraint(int geoId, double* value, bool driving) } // point to line or circular distance constraint -int Sketch::addDistanceConstraint(int geoId1, - PointPos pos1, - int geoId2, - double* value, - bool driving) +int Sketch::addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double* value, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3329,12 +3465,14 @@ int Sketch::addDistanceConstraint(int geoId1, } // point to point distance constraint -int Sketch::addDistanceConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving) +int Sketch::addDistanceConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving +) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3481,12 +3619,7 @@ int Sketch::addAngleConstraint(int geoId1, int geoId2, double* value, bool drivi } // line to line angle constraint (with explicitly given start points) -int Sketch::addAngleConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving) +int Sketch::addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, double* value, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3623,9 +3756,11 @@ int Sketch::addEqualConstraint(int geoId1, int geoId2) } } - Base::Console().warning("Equality constraints between %s and %s are not supported.\n", - nameByType(Geoms[geoId1].type), - nameByType(Geoms[geoId2].type)); + Base::Console().warning( + "Equality constraints between %s and %s are not supported.\n", + nameByType(Geoms[geoId1].type), + nameByType(Geoms[geoId2].type) + ); return -1; } @@ -3686,11 +3821,7 @@ int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, bo return -1; } -int Sketch::addPointOnObjectConstraint(int geoId1, - PointPos pos1, - int geoId2, - double* pointparam, - bool driving) +int Sketch::addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, double* pointparam, bool driving) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3795,12 +3926,14 @@ int Sketch::addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointP return -1; } -int Sketch::addSymmetricConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - int geoId3, - PointPos pos3) +int Sketch::addSymmetricConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + int geoId3, + PointPos pos3 +) { geoId1 = checkGeoId(geoId1); geoId2 = checkGeoId(geoId2); @@ -3822,14 +3955,16 @@ int Sketch::addSymmetricConstraint(int geoId1, return -1; } -int Sketch::addSnellsLawConstraint(int geoIdRay1, - PointPos posRay1, - int geoIdRay2, - PointPos posRay2, - int geoIdBnd, - double* value, - double* secondvalue, - bool driving) +int Sketch::addSnellsLawConstraint( + int geoIdRay1, + PointPos posRay1, + int geoIdRay2, + PointPos posRay2, + int geoIdBnd, + double* value, + double* secondvalue, + bool driving +) { geoIdRay1 = checkGeoId(geoIdRay1); @@ -3879,16 +4014,18 @@ int Sketch::addSnellsLawConstraint(int geoIdRay1, // tag = Sketch::addPointOnObjectConstraint(geoIdRay1, posRay1, geoIdBnd); tag = ++ConstraintsCounter; // GCSsys.addConstraintP2PCoincident(p1, p2, tag); - GCSsys.addConstraintSnellsLaw(*ray1, - *ray2, - *boundary, - p1, - n1, - n2, - posRay1 == PointPos::start, - posRay2 == PointPos::end, - tag, - driving); + GCSsys.addConstraintSnellsLaw( + *ray1, + *ray2, + *boundary, + p1, + n1, + n2, + posRay1 == PointPos::start, + posRay2 == PointPos::end, + tag, + driving + ); return ConstraintsCounter; } @@ -4409,8 +4546,10 @@ void Sketch::updatePoint(const GeoDef& def) void Sketch::updateLineSegment(const GeoDef& def) { GeomLineSegment* lineSeg = static_cast(def.geo); - lineSeg->setPoints(Vector3d(*Lines[def.index].p1.x, *Lines[def.index].p1.y, 0.0), - Vector3d(*Lines[def.index].p2.x, *Lines[def.index].p2.y, 0.0)); + lineSeg->setPoints( + Vector3d(*Lines[def.index].p1.x, *Lines[def.index].p1.y, 0.0), + Vector3d(*Lines[def.index].p2.x, *Lines[def.index].p2.y, 0.0) + ); } void Sketch::updateArcOfCircle(const GeoDef& def) @@ -4632,9 +4771,11 @@ int Sketch::solve() if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().log("Sketcher::Solve()-%s-T:%s\n", - solvername.c_str(), - Base::TimeElapsed::diffTime(start_time, end_time).c_str()); + Base::Console().log( + "Sketcher::Solve()-%s-T:%s\n", + solvername.c_str(), + Base::TimeElapsed::diffTime(start_time, end_time).c_str() + ); } SolveTime = Base::TimeElapsed::diffTimeF(start_time, end_time); @@ -4694,8 +4835,7 @@ int Sketch::internalSolve(std::string& solvername, int level) valid_solution = false; if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().log("Sketcher::Solve()-%s- Failed!! Falling back...\n", - solvername.c_str()); + Base::Console().log("Sketcher::Solve()-%s- Failed!! Falling back...\n", solvername.c_str()); } } @@ -4726,9 +4866,11 @@ int Sketch::internalSolve(std::string& solvername, int level) int i = 0; for (auto it = Parameters.begin(); it != Parameters.end(); ++it, ++i) { InitParameters[i] = **it; - GCSsys.addConstraintEqual(*it, - &InitParameters[i], - GCS::DefaultTemporaryConstraint); + GCSsys.addConstraintEqual( + *it, + &InitParameters[i], + GCS::DefaultTemporaryConstraint + ); } GCSsys.initSolution(); ret = GCSsys.solve(isFine); @@ -4742,8 +4884,7 @@ int Sketch::internalSolve(std::string& solvername, int level) if (!valid_solution) { GCSsys.undoSolution(); updateGeometry(); - Base::Console().warning("Invalid solution from %s solver.\n", - solvername.c_str()); + Base::Console().warning("Invalid solution from %s solver.\n", solvername.c_str()); ret = GCS::SuccessfulSolutionInvalid; } else { @@ -4753,8 +4894,10 @@ int Sketch::internalSolve(std::string& solvername, int level) else { valid_solution = false; if (debugMode == GCS::Minimal || debugMode == GCS::IterationLevel) { - Base::Console().log("Sketcher::Solve()-%s- Failed!! Falling back...\n", - solvername.c_str()); + Base::Console().log( + "Sketcher::Solve()-%s- Failed!! Falling back...\n", + solvername.c_str() + ); } } @@ -4764,16 +4907,22 @@ int Sketch::internalSolve(std::string& solvername, int level) if (valid_solution) { if (soltype == 1) { - Base::Console().log("Important: the LevenbergMarquardt solver succeeded where " - "the DogLeg solver had failed.\n"); + Base::Console().log( + "Important: the LevenbergMarquardt solver succeeded where " + "the DogLeg solver had failed.\n" + ); } else if (soltype == 2) { - Base::Console().log("Important: the BFGS solver succeeded where the DogLeg and " - "LevenbergMarquardt solvers have failed.\n"); + Base::Console().log( + "Important: the BFGS solver succeeded where the DogLeg and " + "LevenbergMarquardt solvers have failed.\n" + ); } else if (soltype == 3) { - Base::Console().log("Important: the SQP solver succeeded where all single " - "subsystem solvers have failed.\n"); + Base::Console().log( + "Important: the SQP solver succeeded where all single " + "subsystem solvers have failed.\n" + ); } else if (soltype > 0) { Base::Console().log("All solvers failed.\n"); @@ -4873,8 +5022,7 @@ int Sketch::initMove(const std::vector& geoEltIds, bool fine) GCSsys.addConstraintPointOnCircle(p0, c, GCS::DefaultTemporaryConstraint); p1.x = &MoveParameters.emplace_back(*center.x); p1.y = &MoveParameters.emplace_back(*center.y); - int i = - GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } @@ -4910,8 +5058,7 @@ int Sketch::initMove(const std::vector& geoEltIds, bool fine) p1.x = &MoveParameters.emplace_back(*center.x); p1.y = &MoveParameters.emplace_back(*center.y); - int i = - GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } @@ -4932,8 +5079,7 @@ int Sketch::initMove(const std::vector& geoEltIds, bool fine) GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); p1.x = &MoveParameters.emplace_back(*center.x); p1.y = &MoveParameters.emplace_back(*center.y); - int i = - GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } @@ -4954,8 +5100,7 @@ int Sketch::initMove(const std::vector& geoEltIds, bool fine) GCSsys.addConstraintP2PCoincident(p0, p, GCS::DefaultTemporaryConstraint); p1.x = &MoveParameters.emplace_back(*center.x); p1.y = &MoveParameters.emplace_back(*center.y); - int i = - GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } @@ -5002,8 +5147,7 @@ int Sketch::initMove(const std::vector& geoEltIds, bool fine) p1.x = &MoveParameters.emplace_back(*center.x); p1.y = &MoveParameters.emplace_back(*center.y); - int i = - GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); GCSsys.rescaleConstraint(i - 2, 0.01); GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); @@ -5025,8 +5169,7 @@ int Sketch::initMove(const std::vector& geoEltIds, bool fine) p1.x = &MoveParameters.emplace_back(*center.x); p1.y = &MoveParameters.emplace_back(*center.y); - int i = - GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); + int i = GCSsys.addConstraintP2PCoincident(p1, center, GCS::DefaultTemporaryConstraint); GCSsys.rescaleConstraint(i - 1, 0.01); GCSsys.rescaleConstraint(i, 0.01); } @@ -5052,10 +5195,7 @@ void Sketch::resetInitMove() isInitMove = false; } -int Sketch::initBSplinePieceMove(int geoId, - PointPos pos, - const Base::Vector3d& firstPoint, - bool fine) +int Sketch::initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, bool fine) { isFine = fine; @@ -5086,10 +5226,9 @@ int Sketch::initBSplinePieceMove(int geoId, double uNear; partBsp->closestParameter(firstPoint, uNear); auto& knots = bsp.knots; - auto upperknot = - std::upper_bound(knots.begin(), knots.end(), uNear, [](double u, double* element) { - return u < *element; - }); + auto upperknot = std::upper_bound(knots.begin(), knots.end(), uNear, [](double u, double* element) { + return u < *element; + }); size_t idx = 0; // skipping the first knot for adjustment @@ -5121,9 +5260,7 @@ int Sketch::initBSplinePieceMove(int geoId, return 0; } -int Sketch::moveGeometries(const std::vector& geoEltIds, - Base::Vector3d toPoint, - bool relative) +int Sketch::moveGeometries(const std::vector& geoEltIds, Base::Vector3d toPoint, bool relative) { if (hasConflicts()) { // don't try to move sketches that contain conflicting constraints diff --git a/src/Mod/Sketcher/App/Sketch.h b/src/Mod/Sketcher/App/Sketch.h index 6547a0a479..5d4cb3186b 100644 --- a/src/Mod/Sketcher/App/Sketch.h +++ b/src/Mod/Sketcher/App/Sketch.h @@ -74,9 +74,11 @@ public: * a fully constrained or under-constrained sketch may contain conflicting * constraints or may not */ - int setUpSketch(const std::vector& GeoList, - const std::vector& ConstraintList, - int extGeoCount = 0); + int setUpSketch( + const std::vector& GeoList, + const std::vector& ConstraintList, + int extGeoCount = 0 + ); /// return the actual geometry of the sketch a TopoShape Part::TopoShape toShape() const; /// add unspecified geometry @@ -85,15 +87,18 @@ public: int addGeometry(const std::vector& geos, bool fixed = false); /// add unspecified geometry, where each element's "fixed" status is given by the /// blockedGeometry array - int addGeometry(const std::vector& geos, - const std::vector& blockedGeometry); + int addGeometry(const std::vector& geos, const std::vector& blockedGeometry); /// get boolean list indicating whether the geometry is to be blocked or not - void getBlockedGeometry(std::vector& blockedGeometry, - std::vector& unenforceableConstraints, - const std::vector& ConstraintList) const; + void getBlockedGeometry( + std::vector& blockedGeometry, + std::vector& unenforceableConstraints, + const std::vector& ConstraintList + ) const; /// returns the actual geometry - std::vector extractGeometry(bool withConstructionElements = true, - bool withExternalElements = false) const; + std::vector extractGeometry( + bool withConstructionElements = true, + bool withExternalElements = false + ) const; GeoListFacade extractGeoListFacade() const; @@ -167,10 +172,7 @@ public: /** Initializes a B-spline piece drag by setting the current * sketch status as a reference. Only moves piece around `firstPoint`. */ - int initBSplinePieceMove(int geoId, - PointPos pos, - const Base::Vector3d& firstPoint, - bool fine = true); + int initBSplinePieceMove(int geoId, PointPos pos, const Base::Vector3d& firstPoint, bool fine = true); /** Resets the initialization of a point or curve drag */ @@ -185,9 +187,11 @@ public: * a condition for satisfying the new point location! * The relative flag permits moving relatively to the current position */ - int moveGeometries(const std::vector& geoEltIds, - Base::Vector3d toPoint, - bool relative = false); + int moveGeometries( + const std::vector& geoEltIds, + Base::Vector3d toPoint, + bool relative = false + ); int moveGeometry(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative = false); /** @@ -199,8 +203,7 @@ public: return RecalculateInitialSolutionWhileMovingPoint; } - void - setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) + void setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) { RecalculateInitialSolutionWhileMovingPoint = recalculateInitialSolutionWhileMovingPoint; } @@ -235,8 +238,10 @@ public: /// add all constraints in the list int addConstraints(const std::vector& ConstraintList); /// add all constraints in the list, provided that are enforceable - int addConstraints(const std::vector& ConstraintList, - const std::vector& unenforceableConstraints); + int addConstraints( + const std::vector& ConstraintList, + const std::vector& unenforceableConstraints + ); /// add one constraint to the sketch int addConstraint(const Constraint* constraint); @@ -271,12 +276,14 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addDistanceXConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving = true); + int addDistanceXConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving = true + ); /** * add a vertical distance constraint to two points or line ends * @@ -292,12 +299,14 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addDistanceYConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving = true); + int addDistanceYConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving = true + ); /// add a horizontal constraint to a geometry int addHorizontalConstraint(int geoId); int addHorizontalConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2); @@ -321,11 +330,7 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addDistanceConstraint(int geoId1, - PointPos pos1, - int geoId2, - double* value, - bool driving = true); + int addDistanceConstraint(int geoId1, PointPos pos1, int geoId2, double* value, bool driving = true); /** * add a length or distance constraint * @@ -333,12 +338,14 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addDistanceConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving = true); + int addDistanceConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving = true + ); /** * add a length or distance constraint * @@ -354,22 +361,28 @@ public: int addPerpendicularConstraint(int geoId1, int geoId2); /// add a tangency constraint between two geometries int addTangentConstraint(int geoId1, int geoId2); - int addTangentLineAtBSplineKnotConstraint(int checkedlinegeoId, - int checkedbsplinegeoId, - int checkedknotgeoid); - int addTangentLineEndpointAtBSplineKnotConstraint(int checkedlinegeoId, - PointPos endpointPos, - int checkedbsplinegeoId, - int checkedknotgeoid); - int addAngleAtPointConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - int geoId3, - PointPos pos3, - double* value, - ConstraintType cTyp, - bool driving = true); + int addTangentLineAtBSplineKnotConstraint( + int checkedlinegeoId, + int checkedbsplinegeoId, + int checkedknotgeoid + ); + int addTangentLineEndpointAtBSplineKnotConstraint( + int checkedlinegeoId, + PointPos endpointPos, + int checkedbsplinegeoId, + int checkedknotgeoid + ); + int addAngleAtPointConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + int geoId3, + PointPos pos3, + double* value, + ConstraintType cTyp, + bool driving = true + ); /** * add a radius constraint on a circle or an arc * @@ -409,12 +422,14 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addAngleConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - double* value, - bool driving = true); + int addAngleConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + double* value, + bool driving = true + ); /** * add angle-via-point constraint between any two curves * @@ -422,32 +437,38 @@ public: * constraint value and already inserted into either the FixParameters or * Parameters array, as the case may be. */ - int addAngleViaPointConstraint(int geoId1, - int geoId2, - int geoId3, - PointPos pos3, - double value, - bool driving = true); + int addAngleViaPointConstraint( + int geoId1, + int geoId2, + int geoId3, + PointPos pos3, + double value, + bool driving = true + ); /// add an equal length or radius constraints between two lines or between circles and arcs int addEqualConstraint(int geoId1, int geoId2); /// add a point on line constraint int addPointOnObjectConstraint(int geoId1, PointPos pos1, int geoId2, bool driving = true); /// add a point on B-spline constraint: needs a parameter - int addPointOnObjectConstraint(int geoId1, - PointPos pos1, - int geoId2, - double* pointparam, - bool driving = true); + int addPointOnObjectConstraint( + int geoId1, + PointPos pos1, + int geoId2, + double* pointparam, + bool driving = true + ); /// add a symmetric constraint between two points with respect to a line int addSymmetricConstraint(int geoId1, PointPos pos1, int geoId2, PointPos pos2, int geoId3); /// add a symmetric constraint between three points, the last point is in the middle of the /// first two - int addSymmetricConstraint(int geoId1, - PointPos pos1, - int geoId2, - PointPos pos2, - int geoId3, - PointPos pos3); + int addSymmetricConstraint( + int geoId1, + PointPos pos1, + int geoId2, + PointPos pos2, + int geoId3, + PointPos pos3 + ); /** * add a snell's law constraint * @@ -459,14 +480,16 @@ public: * second may be initialized to any value, however the solver will * provide n1 in value and n2 in second. */ - int addSnellsLawConstraint(int geoIdRay1, - PointPos posRay1, - int geoIdRay2, - PointPos posRay2, - int geoIdBnd, - double* value, - double* second, - bool driving = true); + int addSnellsLawConstraint( + int geoIdRay1, + PointPos posRay1, + int geoIdRay2, + PointPos posRay2, + int geoIdBnd, + double* value, + double* second, + bool driving = true + ); //@} /// Internal Alignment constraints @@ -749,10 +772,12 @@ private: * requires a post-analysis, see analyseBlockedConstraintDependentParameters, to fix just the * parameters that fulfil the dependacy groups. */ - bool analyseBlockedGeometry(const std::vector& internalGeoList, - const std::vector& constraintList, - std::vector& onlyblockedGeometry, - std::vector& blockedGeoIds) const; + bool analyseBlockedGeometry( + const std::vector& internalGeoList, + const std::vector& constraintList, + std::vector& onlyblockedGeometry, + std::vector& blockedGeoIds + ) const; /* This function performs a post-analysis of blocked geometries (see analyseBlockedGeometry for * more detail on the pre-analysis). @@ -799,8 +824,10 @@ private: * solution in one iteration. * */ - bool analyseBlockedConstraintDependentParameters(std::vector& blockedGeoIds, - std::vector& params_to_block) const; + bool analyseBlockedConstraintDependentParameters( + std::vector& blockedGeoIds, + std::vector& params_to_block + ) const; /// utility function refactoring fixing the provided parameters and running a new diagnose void fixParametersAndDiagnose(std::vector& params_to_block); diff --git a/src/Mod/Sketcher/App/SketchAnalysis.cpp b/src/Mod/Sketcher/App/SketchAnalysis.cpp index c5e0471fb0..1a4c70714a 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.cpp +++ b/src/Mod/Sketcher/App/SketchAnalysis.cpp @@ -248,8 +248,10 @@ struct PointConstraints vertexIds.push_back(id); } - std::list getMissingCoincidences(std::vector& allcoincid, - double precision) + std::list getMissingCoincidences( + std::vector& allcoincid, + double precision + ) { std::list missingCoincidences; // Holds the list of missing coincidences @@ -498,8 +500,7 @@ private: } // namespace -int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, - bool includeconstruction /*=true*/) +int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool includeconstruction /*=true*/) { PointConstraints pointConstr; @@ -531,8 +532,8 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, } // Holds the list of missing coincidences - std::list missingCoincidences = - pointConstr.getMissingCoincidences(coincidences, precision); + std::list missingCoincidences + = pointConstr.getMissingCoincidences(coincidences, precision); // Update list of missing constraints stored as member variable of sketch this->vertexConstraints.clear(); @@ -568,8 +569,7 @@ void SketchAnalysis::analyseMissingPointOnPointCoincident(double angleprecision) Base::Vector3d dir2 = segm2->getEndPoint() - segm2->getStartPoint(); if ((checkVertical(dir1, angleprecision) || checkHorizontal(dir1, angleprecision)) - && (checkVertical(dir2, angleprecision) - || checkHorizontal(dir2, angleprecision))) { + && (checkVertical(dir2, angleprecision) || checkHorizontal(dir2, angleprecision))) { // this is a job for horizontal/vertical constraints alone continue; } @@ -593,8 +593,10 @@ void SketchAnalysis::analyseMissingPointOnPointCoincident(double angleprecision) } } catch (Base::Exception&) { - Base::Console().warning("Point-On-Point Coincidence analysis: unable to obtain " - "derivative. Detection ignored.\n"); + Base::Console().warning( + "Point-On-Point Coincidence analysis: unable to obtain " + "derivative. Detection ignored.\n" + ); continue; } } @@ -668,10 +670,14 @@ void SketchAnalysis::makeMissingPointOnPointCoincident() void SketchAnalysis::makeMissingPointOnPointCoincidentOneByOne() { - makeConstraintsOneByOne(vertexConstraints, - QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch while " - "applying coincident constraints.")); + makeConstraintsOneByOne( + vertexConstraints, + QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstraint error: Unsolvable sketch while " + "applying coincident constraints." + ) + ); } int SketchAnalysis::detectMissingVerticalHorizontalConstraints(double angleprecision) @@ -715,10 +721,14 @@ void SketchAnalysis::makeMissingVerticalHorizontal() void SketchAnalysis::makeMissingVerticalHorizontalOneByOne() { - makeConstraintsOneByOne(verthorizConstraints, - QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch while " - "applying vertical/horizontal constraints.")); + makeConstraintsOneByOne( + verthorizConstraints, + QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstraint error: Unsolvable sketch while " + "applying vertical/horizontal constraints." + ) + ); } bool SketchAnalysis::checkVertical(Base::Vector3d dir, double angleprecision) @@ -751,12 +761,8 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) std::vector constraint = sketch->Constraints.getValues(); for (auto it : constraint) { if (it->Type == Sketcher::Equal) { - ConstraintIds id {Base::Vector3d {}, - it->First, - it->Second, - it->FirstPos, - it->SecondPos, - it->Type}; + ConstraintIds + id {Base::Vector3d {}, it->First, it->Second, it->FirstPos, it->SecondPos, it->Type}; auto pos = std::find_if(equallines.begin(), equallines.end(), Constraint_Equal(id)); @@ -792,9 +798,11 @@ int SketchAnalysis::detectMissingEqualityConstraints(double precision) void SketchAnalysis::makeMissingEquality() { std::vector equalities(lineequalityConstraints); - equalities.insert(equalities.end(), - radiusequalityConstraints.begin(), - radiusequalityConstraints.end()); + equalities.insert( + equalities.end(), + radiusequalityConstraints.begin(), + radiusequalityConstraints.end() + ); makeConstraints(equalities); lineequalityConstraints.clear(); @@ -804,14 +812,20 @@ void SketchAnalysis::makeMissingEquality() void SketchAnalysis::makeMissingEqualityOneByOne() { std::vector equalities(lineequalityConstraints); - equalities.insert(equalities.end(), - radiusequalityConstraints.begin(), - radiusequalityConstraints.end()); + equalities.insert( + equalities.end(), + radiusequalityConstraints.begin(), + radiusequalityConstraints.end() + ); - makeConstraintsOneByOne(equalities, - QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch while " - "applying equality constraints.")); + makeConstraintsOneByOne( + equalities, + QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstraint error: Unsolvable sketch while " + "applying equality constraints." + ) + ); lineequalityConstraints.clear(); radiusequalityConstraints.clear(); } @@ -849,8 +863,9 @@ void SketchAnalysis::autoDeleteAllConstraints() doc->commitTransaction(); // a failure should not be possible at this moment as we start from a clean situation - solveSketch(QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch without constraints.")); + solveSketch( + QT_TRANSLATE_NOOP("Exceptions", "Autoconstraint error: Unsolvable sketch without constraints.") + ); } void SketchAnalysis::autoHorizontalVerticalConstraints() @@ -863,9 +878,11 @@ void SketchAnalysis::autoHorizontalVerticalConstraints() // finish the transaction and update doc->commitTransaction(); - solveSketch(QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch after applying " - "horizontal and vertical constraints.")); + solveSketch(QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstraint error: Unsolvable sketch after applying " + "horizontal and vertical constraints." + )); } void SketchAnalysis::autoPointOnPointCoincident() @@ -878,9 +895,11 @@ void SketchAnalysis::autoPointOnPointCoincident() // finish the transaction and update doc->commitTransaction(); - solveSketch(QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch after applying " - "point-on-point constraints.")); + solveSketch(QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstraint error: Unsolvable sketch after applying " + "point-on-point constraints." + )); } void SketchAnalysis::autoMissingEquality() @@ -899,14 +918,14 @@ void SketchAnalysis::autoMissingEquality() // finish the transaction and update doc->commitTransaction(); - solveSketch(QT_TRANSLATE_NOOP("Exceptions", - "Autoconstraint error: Unsolvable sketch after " - "applying equality constraints.")); + solveSketch(QT_TRANSLATE_NOOP( + "Exceptions", + "Autoconstraint error: Unsolvable sketch after " + "applying equality constraints." + )); } -int SketchAnalysis::autoconstraint(double precision, - double angleprecision, - bool includeconstruction) +int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool includeconstruction) { autoDeleteAllConstraints(); @@ -927,11 +946,13 @@ int SketchAnalysis::autoconstraint(double precision, // STAGE 3: Equality constraint detection int ne = detectMissingEqualityConstraints(precision); - Base::Console().log("Constraints: Vertical/Horizontal: %d found. " - "Point-on-point: %d. Equality: %d\n", - nhv, - nc, - ne); + Base::Console().log( + "Constraints: Vertical/Horizontal: %d found. " + "Point-on-point: %d. Equality: %d\n", + nhv, + nc, + ne + ); // Applying STAGE 1, if any if (nhv > 0) { diff --git a/src/Mod/Sketcher/App/SketchAnalysis.h b/src/Mod/Sketcher/App/SketchAnalysis.h index dc354b6d80..632846e57d 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.h +++ b/src/Mod/Sketcher/App/SketchAnalysis.h @@ -91,8 +91,10 @@ public: /// Point on Point constraint simple routine Detect step (see constructor) /// Detect detects only coincident constraints, Analyse converts coincident to endpoint /// perpendicular/tangent where appropriate - int detectMissingPointOnPointConstraints(double precision = Precision::Confusion() * 1000, - bool includeconstruction = true); + int detectMissingPointOnPointConstraints( + double precision = Precision::Confusion() * 1000, + bool includeconstruction = true + ); /// Point on Point constraint simple routine Analyse step (see constructor) void analyseMissingPointOnPointCoincident(double angleprecision = std::numbers::pi / 8); /// Point on Point constraint simple routine Get step (see constructor) @@ -167,9 +169,11 @@ public: /// makes assumptions to avoid redundancies. /// /// It applies coincidents - vertical/horizontal constraints and equality constraints. - int autoconstraint(double precision = Precision::Confusion() * 1000, - double angleprecision = std::numbers::pi / 8, - bool includeconstruction = true); + int autoconstraint( + double precision = Precision::Confusion() * 1000, + double angleprecision = std::numbers::pi / 8, + bool includeconstruction = true + ); // helper functions, which may be used by more complex methods, and/or called directly by user // space (python) methods diff --git a/src/Mod/Sketcher/App/SketchGeometryExtension.cpp b/src/Mod/Sketcher/App/SketchGeometryExtension.cpp index d9d790d8c6..9a41d26d94 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/SketchGeometryExtension.cpp @@ -109,14 +109,13 @@ PyObject* SketchGeometryExtension::getPyObject() return new SketchGeometryExtensionPy(new SketchGeometryExtension(*this)); } -bool SketchGeometryExtension::getInternalTypeFromName(std::string str, - InternalType::InternalType& type) +bool SketchGeometryExtension::getInternalTypeFromName(std::string str, InternalType::InternalType& type) { - auto pos = std::find_if(SketchGeometryExtension::internaltype2str.begin(), - SketchGeometryExtension::internaltype2str.end(), - [str](const char* val) { - return strcmp(val, str.c_str()) == 0; - }); + auto pos = std::find_if( + SketchGeometryExtension::internaltype2str.begin(), + SketchGeometryExtension::internaltype2str.end(), + [str](const char* val) { return strcmp(val, str.c_str()) == 0; } + ); if (pos != SketchGeometryExtension::internaltype2str.end()) { int index = std::distance(SketchGeometryExtension::internaltype2str.begin(), pos); @@ -128,14 +127,13 @@ bool SketchGeometryExtension::getInternalTypeFromName(std::string str, return false; } -bool SketchGeometryExtension::getGeometryModeFromName(std::string str, - GeometryMode::GeometryMode& type) +bool SketchGeometryExtension::getGeometryModeFromName(std::string str, GeometryMode::GeometryMode& type) { - auto pos = std::find_if(SketchGeometryExtension::geometrymode2str.begin(), - SketchGeometryExtension::geometrymode2str.end(), - [str](const char* val) { - return strcmp(val, str.c_str()) == 0; - }); + auto pos = std::find_if( + SketchGeometryExtension::geometrymode2str.begin(), + SketchGeometryExtension::geometrymode2str.end(), + [str](const char* val) { return strcmp(val, str.c_str()) == 0; } + ); if (pos != SketchGeometryExtension::geometrymode2str.end()) { int index = std::distance(SketchGeometryExtension::geometrymode2str.begin(), pos); diff --git a/src/Mod/Sketcher/App/SketchGeometryExtension.h b/src/Mod/Sketcher/App/SketchGeometryExtension.h index 588ee9fb2d..2e8373aa07 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtension.h +++ b/src/Mod/Sketcher/App/SketchGeometryExtension.h @@ -53,7 +53,7 @@ enum InternalType ParabolaFocalAxis = 11, NumInternalGeometryType // Must be the last }; -} +} // namespace InternalType namespace GeometryMode { @@ -63,7 +63,7 @@ enum GeometryMode Construction = 1, NumGeometryMode // Must be the last }; -} +} // namespace GeometryMode class ISketchGeometryExtension { @@ -135,22 +135,24 @@ public: GeometryLayer = geolayer; } - constexpr static std::array - internaltype2str {{"None", - "EllipseMajorDiameter", - "EllipseMinorDiameter", - "EllipseFocus1", - "EllipseFocus2", - "HyperbolaMajor", - "HyperbolaMinor", - "HyperbolaFocus", - "ParabolaFocus", - "BSplineControlPoint", - "BSplineKnotPoint", - "ParabolaFocalAxis"}}; + constexpr static std::array internaltype2str { + {"None", + "EllipseMajorDiameter", + "EllipseMinorDiameter", + "EllipseFocus1", + "EllipseFocus2", + "HyperbolaMajor", + "HyperbolaMinor", + "HyperbolaFocus", + "ParabolaFocus", + "BSplineControlPoint", + "BSplineKnotPoint", + "ParabolaFocalAxis"} + }; constexpr static std::array geometrymode2str { - {"Blocked", "Construction"}}; + {"Blocked", "Construction"} + }; static bool getInternalTypeFromName(std::string str, InternalType::InternalType& type); diff --git a/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp index 96593d616a..ab4f9bde6c 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp @@ -68,10 +68,12 @@ int SketchGeometryExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } - PyErr_SetString(PyExc_TypeError, - "SketchGeometryExtension constructor accepts:\n" - "-- empty parameter list\n" - "-- int\n"); + PyErr_SetString( + PyExc_TypeError, + "SketchGeometryExtension constructor accepts:\n" + "-- empty parameter list\n" + "-- int\n" + ); return -1; } @@ -93,8 +95,7 @@ Py::String SketchGeometryExtensionPy::getInternalType() const throw Py::NotImplementedError("String name of enum not implemented"); } - std::string typestr = - this->getSketchGeometryExtensionPtr()->internaltype2str[internaltypeindex]; + std::string typestr = this->getSketchGeometryExtensionPtr()->internaltype2str[internaltypeindex]; return Py::String(typestr); } @@ -124,8 +125,7 @@ void SketchGeometryExtensionPy::setBlocked(Py::Boolean arg) Py::Boolean SketchGeometryExtensionPy::getConstruction() const { - return Py::Boolean( - getSketchGeometryExtensionPtr()->testGeometryMode(GeometryMode::Construction)); + return Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(GeometryMode::Construction)); } void SketchGeometryExtensionPy::setConstruction(Py::Boolean arg) @@ -142,7 +142,8 @@ PyObject* SketchGeometryExtensionPy::testGeometryMode(PyObject* args) const if (getSketchGeometryExtensionPtr()->getGeometryModeFromName(flag, mode)) { return new_reference_to( - Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(mode))); + Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(mode)) + ); } PyErr_SetString(PyExc_TypeError, "Flag string does not exist."); diff --git a/src/Mod/Sketcher/App/SketchObject.cpp b/src/Mod/Sketcher/App/SketchObject.cpp index 11aa798366..d35dde28c3 100644 --- a/src/Mod/Sketcher/App/SketchObject.cpp +++ b/src/Mod/Sketcher/App/SketchObject.cpp @@ -333,9 +333,11 @@ void SketchObject::buildShape() if (!vertex.hasElementMap()) { vertex.resetElementMap(std::make_shared()); } - vertex.setElementName(Data::IndexedName::fromConst("Vertex", 1), - Data::MappedName::fromRawData(name.c_str()), - 0L); + vertex.setElementName( + Data::IndexedName::fromConst("Vertex", 1), + Data::MappedName::fromRawData(name.c_str()), + 0L + ); vertices.push_back(vertex); vertices.back().copyElementMap(vertex, Part::OpCodes::Sketch); }; @@ -356,8 +358,10 @@ void SketchObject::buildShape() } if (geo->isDerivedFrom()) { int idx = getVertexIndexGeoPos(geoId - 1, Sketcher::PointPos::start); - addVertex(Part::TopoShape {TopoDS::Vertex(geo->toShape())}, - convertSubName(Data::IndexedName::fromConst("Vertex", idx + 1), false)); + addVertex( + Part::TopoShape {TopoDS::Vertex(geo->toShape())}, + convertSubName(Data::IndexedName::fromConst("Vertex", idx + 1), false) + ); } else { auto indexedName = Data::IndexedName::fromConst("Edge", geoId); @@ -379,8 +383,10 @@ void SketchObject::buildShape() auto indexedName = Data::IndexedName::fromConst("ExternalEdge", i - 1); if (geo->isDerivedFrom()) { - addVertex(Part::TopoShape {TopoDS::Vertex(geo->toShape())}, - convertSubName(indexedName, false)); + addVertex( + Part::TopoShape {TopoDS::Vertex(geo->toShape())}, + convertSubName(indexedName, false) + ); } else { addEdge(geo, indexedName); @@ -2174,7 +2180,8 @@ int SketchObject::setConstruction(int GeoId, bool on) // clang-format on int SketchObject::toggleExternalGeometryFlag( const std::vector& geoIds, - const std::vector& flags) + const std::vector& flags +) { if (flags.empty()) { return 0; @@ -2509,8 +2516,10 @@ int SketchObject::delConstraintOnPoint(int geoId, PointPos posId, bool onlyCoinc case Sketcher::Distance: case Sketcher::DistanceX: case Sketcher::DistanceY: { - return (transferToReplacement(constr->First, constr->FirstPos) - || transferToReplacement(constr->Second, constr->SecondPos)); + return ( + transferToReplacement(constr->First, constr->FirstPos) + || transferToReplacement(constr->Second, constr->SecondPos) + ); } case Sketcher::PointOnObject: { return transferToReplacement(constr->First, constr->FirstPos); @@ -2540,8 +2549,8 @@ int SketchObject::delConstraintOnPoint(int geoId, PointPos posId, bool onlyCoinc // with the given point const bool isOneOfDistanceTypes = constr->Type == Sketcher::Distance || constr->Type == Sketcher::DistanceX || constr->Type == Sketcher::DistanceY; - const bool involvesEntireCurve = - constr->First == geoId && constr->FirstPos == PointPos::none; + const bool involvesEntireCurve = constr->First == geoId + && constr->FirstPos == PointPos::none; const bool isPosAnEndpoint = posId == PointPos::start || posId == PointPos::end; if (isOneOfDistanceTypes && involvesEntireCurve && isPosAnEndpoint) { continue; @@ -2745,11 +2754,13 @@ void SketchObject::transferFilletConstraints(int geoId1, PointPos posId1, int ge } // clang-format on -int SketchObject::transferConstraints(int fromGeoId, - PointPos fromPosId, - int toGeoId, - PointPos toPosId, - bool doNotTransformTangencies) +int SketchObject::transferConstraints( + int fromGeoId, + PointPos fromPosId, + int toGeoId, + PointPos toPosId, + bool doNotTransformTangencies +) { // no need to check input data validity as this is an sketchobject managed operation. Base::StateLocker lock(managedoperation, true); @@ -3094,12 +3105,14 @@ void SketchObject::changeConstraintAfterDeletingGeo(Constraint* constr, } // clang-format on -bool SketchObject::seekTrimPoints(int GeoId, - const Base::Vector3d& point, - int& GeoId1, - Base::Vector3d& intersect1, - int& GeoId2, - Base::Vector3d& intersect2) +bool SketchObject::seekTrimPoints( + int GeoId, + const Base::Vector3d& point, + int& GeoId1, + Base::Vector3d& intersect1, + int& GeoId2, + Base::Vector3d& intersect2 +) { if (GeoId < 0 || GeoId > getHighestCurveIndex()) { return false; @@ -3113,13 +3126,7 @@ bool SketchObject::seekTrimPoints(int GeoId, // Not found in will be returned as -1, not as GeoUndef, Part WB is agnostic to the concept of // GeoUndef - if (!Part2DObject::seekTrimPoints(geos, - GeoId, - point, - localindex1, - intersect1, - localindex2, - intersect2)) { + if (!Part2DObject::seekTrimPoints(geos, GeoId, point, localindex1, intersect1, localindex2, intersect2)) { return false; } @@ -3133,9 +3140,7 @@ bool SketchObject::seekTrimPoints(int GeoId, // given a geometry and a point, returns the corresponding parameter of the geometry point // closest to the point. Wrapped around a try-catch so the calling operation can fail without // throwing an exception. -bool getIntersectionParameter(const Part::Geometry* geo, - const Base::Vector3d point, - double& pointParam) +bool getIntersectionParameter(const Part::Geometry* geo, const Base::Vector3d point, double& pointParam) { const auto* curve = static_cast(geo); @@ -3166,10 +3171,7 @@ bool areParamsWithinApproximation(double param1, double param2) // returns true if the point defined by (GeoId1, pos1) can be considered to be coincident with // point. -bool isPointAtPosition(const SketchObject* obj, - int GeoId1, - PointPos pos1, - const Base::Vector3d& point) +bool isPointAtPosition(const SketchObject* obj, int GeoId1, PointPos pos1, const Base::Vector3d& point) { Base::Vector3d pp = obj->getPoint(GeoId1, pos1); @@ -3180,13 +3182,15 @@ bool isPointAtPosition(const SketchObject* obj, // Preexisting point on object constraints get converted to coincidents. // Returns: // - The constraint that should be used to constraint GeoId and cuttingGeoId -std::unique_ptr transformPreexistingConstraintForTrim(const SketchObject* obj, - const Constraint* constr, - int GeoId, - int cuttingGeoId, - const Base::Vector3d& cutPointVec, - int newGeoId, - PointPos newPosId) +std::unique_ptr transformPreexistingConstraintForTrim( + const SketchObject* obj, + const Constraint* constr, + int GeoId, + int cuttingGeoId, + const Base::Vector3d& cutPointVec, + int newGeoId, + PointPos newPosId +) { /* TODO: It is possible that the trimming entity has both a PointOnObject constraint to the * trimmed entity, and a simple Tangent constraint to the trimmed entity. In this case we @@ -3237,11 +3241,13 @@ std::unique_ptr transformPreexistingConstraintForTrim(const SketchOb return newConstr; } -std::unique_ptr getNewConstraintAtTrimCut(const SketchObject* obj, - int cuttingGeoId, - int cutGeoId, - PointPos cutPosId, - const Base::Vector3d& cutPointVec) +std::unique_ptr getNewConstraintAtTrimCut( + const SketchObject* obj, + int cuttingGeoId, + int cutGeoId, + PointPos cutPosId, + const Base::Vector3d& cutPointVec +) { auto newConstr = std::make_unique(); newConstr->First = cutGeoId; @@ -3271,11 +3277,13 @@ bool isGeoIdAllowedForTrim(const SketchObject* obj, int GeoId) && GeometryFacade::isInternalType(geo, InternalType::None); } -bool getParamLimitsOfNewGeosForTrim(const SketchObject* obj, - int GeoId, - std::array& cuttingGeoIds, - std::array& cutPoints, - std::vector>& paramsOfNewGeos) +bool getParamLimitsOfNewGeosForTrim( + const SketchObject* obj, + int GeoId, + std::array& cuttingGeoIds, + std::array& cutPoints, + std::vector>& paramsOfNewGeos +) { const auto* geoAsCurve = obj->getGeometry(GeoId); double firstParam = geoAsCurve->getFirstParameter(); @@ -3324,9 +3332,11 @@ bool getParamLimitsOfNewGeosForTrim(const SketchObject* obj, return true; } -void createArcsFromGeoWithLimits(const Part::GeomCurve* geo, - const std::vector>& paramsOfNewGeos, - std::vector& newGeos) +void createArcsFromGeoWithLimits( + const Part::GeomCurve* geo, + const std::vector>& paramsOfNewGeos, + std::vector& newGeos +) { for (auto& [u1, u2] : paramsOfNewGeos) { auto newGeo = static_cast(geo)->createArc(u1, u2); @@ -3335,15 +3345,17 @@ void createArcsFromGeoWithLimits(const Part::GeomCurve* geo, } } -void createNewConstraintsForTrim(const SketchObject* obj, - const int GeoId, - const std::array& cuttingGeoIds, - const std::array& cutPoints, - const std::vector& newIds, - const std::vector newGeos, - std::vector& idsOfOldConstraints, - std::vector& newConstraints, - std::set>& geoIdsToBeDeleted) +void createNewConstraintsForTrim( + const SketchObject* obj, + const int GeoId, + const std::array& cuttingGeoIds, + const std::array& cutPoints, + const std::vector& newIds, + const std::vector newGeos, + std::vector& idsOfOldConstraints, + std::vector& newConstraints, + std::set>& geoIdsToBeDeleted +) { const auto& allConstraints = obj->Constraints.getValues(); @@ -3357,24 +3369,28 @@ void createNewConstraintsForTrim(const SketchObject* obj, geoIdsToBeDeleted.insert(con->First); continue; } - if (auto newConstr = transformPreexistingConstraintForTrim(obj, - con, - GeoId, - cuttingGeoIds[0], - cutPoints[0], - newIds.front(), - PointPos::end)) { + if (auto newConstr = transformPreexistingConstraintForTrim( + obj, + con, + GeoId, + cuttingGeoIds[0], + cutPoints[0], + newIds.front(), + PointPos::end + )) { newConstraints.push_back(newConstr.release()); isPoint1ConstrainedOnGeoId1 = true; continue; } - if (auto newConstr = transformPreexistingConstraintForTrim(obj, - con, - GeoId, - cuttingGeoIds[1], - cutPoints[1], - newIds.back(), - PointPos::start)) { + if (auto newConstr = transformPreexistingConstraintForTrim( + obj, + con, + GeoId, + cuttingGeoIds[1], + cutPoints[1], + newIds.back(), + PointPos::start + )) { newConstraints.push_back(newConstr.release()); isPoint2ConstrainedOnGeoId2 = true; continue; @@ -3394,21 +3410,17 @@ void createNewConstraintsForTrim(const SketchObject* obj, // TODO: Tangent/perpendicular not yet covered if (cuttingGeoIds[0] != GeoEnum::GeoUndef && !isPoint1ConstrainedOnGeoId1) { - newConstraints.emplace_back(getNewConstraintAtTrimCut(obj, - cuttingGeoIds[0], - newIds.front(), - PointPos::end, - cutPoints[0]) - .release()); + newConstraints.emplace_back( + getNewConstraintAtTrimCut(obj, cuttingGeoIds[0], newIds.front(), PointPos::end, cutPoints[0]) + .release() + ); } if (cuttingGeoIds[1] != GeoEnum::GeoUndef && !isPoint2ConstrainedOnGeoId2) { - newConstraints.emplace_back(getNewConstraintAtTrimCut(obj, - cuttingGeoIds[1], - newIds.back(), - PointPos::start, - cutPoints[1]) - .release()); + newConstraints.emplace_back( + getNewConstraintAtTrimCut(obj, cuttingGeoIds[1], newIds.back(), PointPos::start, cutPoints[1]) + .release() + ); } } @@ -3446,12 +3458,14 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) // != GeoUndef and cuttingGeoIds[1] != GeoUndef // // FirstParam < point1param < point2param < LastParam - if (!SketchObject::seekTrimPoints(GeoId, - point, - cuttingGeoIds[0], - cutPoints[0], - cuttingGeoIds[1], - cutPoints[1])) { + if (!SketchObject::seekTrimPoints( + GeoId, + point, + cuttingGeoIds[0], + cutPoints[0], + cuttingGeoIds[1], + cutPoints[1] + )) { // If no suitable trim points are found, then trim defaults to deleting the geometry delGeometry(GeoId); return 0; @@ -3507,33 +3521,32 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) // remove the constraints that we want to manually transfer // We could transfer beforehand but in case of exception that transfer is permanent if (!isOriginalCurvePeriodic) { - std::erase_if(idsOfOldConstraints, - [&GeoId, &allConstraints, &cuttingGeoIds](const auto& i) { - auto* constr = allConstraints[i]; - bool involvesStart = - constr->involvesGeoIdAndPosId(GeoId, PointPos::start); - bool involvesEnd = constr->involvesGeoIdAndPosId(GeoId, PointPos::end); - bool keepStart = cuttingGeoIds[0] != GeoEnum::GeoUndef; - bool keepEnd = cuttingGeoIds[1] != GeoEnum::GeoUndef; - bool involvesBothButNotBothKept = - involvesStart && involvesEnd && !(keepStart && keepEnd); - return !involvesBothButNotBothKept - && ((involvesStart && keepStart) || (involvesEnd && keepEnd)); - }); + std::erase_if(idsOfOldConstraints, [&GeoId, &allConstraints, &cuttingGeoIds](const auto& i) { + auto* constr = allConstraints[i]; + bool involvesStart = constr->involvesGeoIdAndPosId(GeoId, PointPos::start); + bool involvesEnd = constr->involvesGeoIdAndPosId(GeoId, PointPos::end); + bool keepStart = cuttingGeoIds[0] != GeoEnum::GeoUndef; + bool keepEnd = cuttingGeoIds[1] != GeoEnum::GeoUndef; + bool involvesBothButNotBothKept = involvesStart && involvesEnd && !(keepStart && keepEnd); + return !involvesBothButNotBothKept + && ((involvesStart && keepStart) || (involvesEnd && keepEnd)); + }); } std::erase_if(idsOfOldConstraints, [&GeoId, &allConstraints](const auto& i) { return (allConstraints[i]->involvesGeoIdAndPosId(GeoId, PointPos::mid)); }); - createNewConstraintsForTrim(this, - GeoId, - cuttingGeoIds, - cutPoints, - newIds, - newGeosAsConsts, - idsOfOldConstraints, - newConstraints, - geoIdsToBeDeleted); + createNewConstraintsForTrim( + this, + GeoId, + cuttingGeoIds, + cutPoints, + newIds, + newGeosAsConsts, + idsOfOldConstraints, + newConstraints, + geoIdsToBeDeleted + ); //******************* Step D => Replacing geometries and constraints //****************************************// @@ -3621,10 +3634,12 @@ int SketchObject::trim(int GeoId, const Base::Vector3d& point) return 0; } -bool SketchObject::deriveConstraintsForPieces(const int oldId, - const std::vector& newIds, - const Constraint* con, - std::vector& newConstraints) const +bool SketchObject::deriveConstraintsForPieces( + const int oldId, + const std::vector& newIds, + const Constraint* con, + std::vector& newConstraints +) const { std::vector newGeos; for (auto& newId : newIds) { @@ -3634,11 +3649,13 @@ bool SketchObject::deriveConstraintsForPieces(const int oldId, return deriveConstraintsForPieces(oldId, newIds, newGeos, con, newConstraints); } -bool SketchObject::deriveConstraintsForPieces(const int oldId, - const std::vector& newIds, - const std::vector& newGeos, - const Constraint* con, - std::vector& newConstraints) const +bool SketchObject::deriveConstraintsForPieces( + const int oldId, + const std::vector& newIds, + const std::vector& newGeos, + const Constraint* con, + std::vector& newConstraints +) const { const Part::Geometry* geo = getGeometry(oldId); int conId = con->First; @@ -3680,9 +3697,9 @@ bool SketchObject::deriveConstraintsForPieces(const int oldId, // TODO: Choose piece based on parameters ("values" of the constraint) for (size_t i = 0; i < newIds.size(); ++i) { std::vector> intersections; - bool intersects = - static_cast(newGeos[i]) - ->intersect(static_cast(conGeo), intersections); + bool intersects + = static_cast(newGeos[i]) + ->intersect(static_cast(conGeo), intersections); if (intersects) { Constraint* trans = con->copy(); @@ -3721,10 +3738,10 @@ bool SketchObject::deriveConstraintsForPieces(const int oldId, // Choose based on where the closest point lies // If it's not there, just leave this constraint out for (size_t i = 0; i < newIds.size(); ++i) { - double newGeoFirstParam = - static_cast(newGeos[i])->getFirstParameter(); - double newGeoLastParam = - static_cast(newGeos[i])->getLastParameter(); + double newGeoFirstParam + = static_cast(newGeos[i])->getFirstParameter(); + double newGeoLastParam + = static_cast(newGeos[i])->getLastParameter(); // For periodic curves the point may need a full revolution if ((newGeoFirstParam - conParam) > Precision::PApproximation() && isClosedCurve(geo)) { @@ -3751,8 +3768,7 @@ bool SketchObject::deriveConstraintsForPieces(const int oldId, // curve is a conic or its arc // TODO: Some equalities may be transferred, using something along the lines of // `getDirectlyCoincidentPoints` - if (geo->isDerivedFrom() - || geo->isDerivedFrom()) { + if (geo->isDerivedFrom() || geo->isDerivedFrom()) { Constraint* trans = con->copy(); trans->substituteIndex(oldId, newIds.front()); newConstraints.push_back(trans); @@ -3802,7 +3818,8 @@ int SketchObject::split(int GeoId, const Base::Vector3d& point) // TODO: find trim parameters std::vector> paramsOfNewGeos( isOriginalCurvePeriodic ? 1 : 2, - {geoAsCurve->getFirstParameter(), geoAsCurve->getLastParameter()}); + {geoAsCurve->getFirstParameter(), geoAsCurve->getLastParameter()} + ); paramsOfNewGeos.front().second = isOriginalCurvePeriodic ? (splitParam + geoAsCurve->getLastParameter() - geoAsCurve->getFirstParameter()) : splitParam; @@ -6615,22 +6632,25 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m if (GeoId < 0 || GeoId > getHighestCurveIndex()) { THROWMT( Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", "B-spline Geometry Index (GeoID) is out of bounds.")); + QT_TRANSLATE_NOOP("Exceptions", "B-spline Geometry Index (GeoID) is out of bounds.") + ); } if (multiplicityincr == 0) { // no change in multiplicity THROWMT( Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", "You are requesting no change in knot multiplicity.")); + QT_TRANSLATE_NOOP("Exceptions", "You are requesting no change in knot multiplicity.") + ); } const Part::Geometry* geo = getGeometry(GeoId); if (!geo->is()) { - THROWMT(Base::TypeError, - QT_TRANSLATE_NOOP("Exceptions", - "The Geometry Index (GeoId) provided is not a B-spline.")); + THROWMT( + Base::TypeError, + QT_TRANSLATE_NOOP("Exceptions", "The Geometry Index (GeoId) provided is not a B-spline.") + ); } const auto* bsp = static_cast(geo); @@ -6639,10 +6659,14 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m if (knotIndex > bsp->countKnots() || knotIndex < 1) { // knotindex in OCC 1 -> countKnots - THROWMT(Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", - "The knot index is out of bounds. Note that in accordance with " - "OCC notation, the first knot has index 1 and not zero.")); + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP( + "Exceptions", + "The knot index is out of bounds. Note that in accordance with " + "OCC notation, the first knot has index 1 and not zero." + ) + ); } std::unique_ptr bspline; @@ -6651,17 +6675,21 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m // zero is removing the knot, degree is just positional continuity if ((curmult + multiplicityincr) > degree) { - THROWMT(Base::ValueError, - QT_TRANSLATE_NOOP( - "Exceptions", - "The multiplicity cannot be increased beyond the degree of the B-spline.")); + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP( + "Exceptions", + "The multiplicity cannot be increased beyond the degree of the B-spline." + ) + ); } // zero is removing the knot, degree is just positional continuity if ((curmult + multiplicityincr) < 0) { THROWMT( Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", "The multiplicity cannot be decreased beyond zero.")); + QT_TRANSLATE_NOOP("Exceptions", "The multiplicity cannot be decreased beyond zero.") + ); } try { @@ -6674,10 +6702,14 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m bool result = bspline->removeKnot(knotIndex, curmult + multiplicityincr, 1E6); if (!result) { - THROWMT(Base::CADKernelError, - QT_TRANSLATE_NOOP("Exceptions", - "OCC is unable to decrease the multiplicity within the " - "maximum tolerance.")); + THROWMT( + Base::CADKernelError, + QT_TRANSLATE_NOOP( + "Exceptions", + "OCC is unable to decrease the multiplicity within the " + "maximum tolerance." + ) + ); } } } @@ -6699,7 +6731,8 @@ bool SketchObject::modifyBSplineKnotMultiplicity(int GeoId, int knotIndex, int m std::map> indexInNew { {Sketcher::BSplineControlPoint, {}}, - {Sketcher::BSplineKnotPoint, {}}}; + {Sketcher::BSplineKnotPoint, {}} + }; indexInNew[Sketcher::BSplineControlPoint].reserve(poles.size()); indexInNew[Sketcher::BSplineKnotPoint].reserve(knots.size()); @@ -6777,20 +6810,24 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) if (GeoId < 0 || GeoId > getHighestCurveIndex()) { THROWMT( Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", "B-spline Geometry Index (GeoID) is out of bounds.")); + QT_TRANSLATE_NOOP("Exceptions", "B-spline Geometry Index (GeoID) is out of bounds.") + ); } if (multiplicity == 0) { - THROWMT(Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", "Knot cannot have zero multiplicity.")); + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "Knot cannot have zero multiplicity.") + ); } const Part::Geometry* geo = getGeometry(GeoId); if (!geo->is()) { - THROWMT(Base::TypeError, - QT_TRANSLATE_NOOP("Exceptions", - "The Geometry Index (GeoId) provided is not a B-spline.")); + THROWMT( + Base::TypeError, + QT_TRANSLATE_NOOP("Exceptions", "The Geometry Index (GeoId) provided is not a B-spline.") + ); } const auto* bsp = static_cast(geo); @@ -6800,16 +6837,20 @@ bool SketchObject::insertBSplineKnot(int GeoId, double param, int multiplicity) double lastParam = bsp->getLastParameter(); if (multiplicity > degree) { - THROWMT(Base::ValueError, - QT_TRANSLATE_NOOP( - "Exceptions", - "Knot multiplicity cannot be higher than the degree of the B-spline.")); + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP( + "Exceptions", + "Knot multiplicity cannot be higher than the degree of the B-spline." + ) + ); } if (param > lastParam || param < firstParam) { - THROWMT(Base::ValueError, - QT_TRANSLATE_NOOP("Exceptions", - "Knot cannot be inserted outside the B-spline parameter range.")); + THROWMT( + Base::ValueError, + QT_TRANSLATE_NOOP("Exceptions", "Knot cannot be inserted outside the B-spline parameter range.") + ); } std::unique_ptr bspline; @@ -7125,10 +7166,7 @@ int SketchObject::carbonCopy(App::DocumentObject* pObj, bool construction) } // clang-format on -int SketchObject::addExternal(App::DocumentObject* Obj, - const char* SubName, - bool defining, - bool intersection) +int SketchObject::addExternal(App::DocumentObject* Obj, const char* SubName, bool defining, bool intersection) { // no need to check input data validity as this is an sketchobject managed operation. Base::StateLocker lock(managedoperation, true); @@ -7138,17 +7176,17 @@ int SketchObject::addExternal(App::DocumentObject* Obj, return -1; } - auto wholeShape = - Part::Feature::getTopoShape(Obj, - Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + auto wholeShape = Part::Feature::getTopoShape( + Obj, + Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform + ); auto shape = wholeShape.getSubTopoShape(SubName, /*silent*/ true); TopAbs_ShapeEnum shapeType = TopAbs_SHAPE; if (shape.shapeType(/*silent*/ true) != TopAbs_FACE) { if (shape.hasSubShape(TopAbs_FACE)) { shapeType = TopAbs_FACE; } - else if (shape.shapeType(/*silent*/ true) != TopAbs_EDGE - && shape.hasSubShape(TopAbs_EDGE)) { + else if (shape.shapeType(/*silent*/ true) != TopAbs_EDGE && shape.hasSubShape(TopAbs_EDGE)) { shapeType = TopAbs_EDGE; } } @@ -7167,9 +7205,11 @@ int SketchObject::addExternal(App::DocumentObject* Obj, Rot.multVec(dN, dN); Base::Vector3d dX(1, 0, 0); Rot.multVec(dX, dX); - gp_Ax3 sketchAx3(gp_Pnt(Pos.x, Pos.y, Pos.z), - gp_Dir(dN.x, dN.y, dN.z), - gp_Dir(dX.x, dX.y, dX.z)); + gp_Ax3 sketchAx3( + gp_Pnt(Pos.x, Pos.y, Pos.z), + gp_Dir(dN.x, dN.y, dN.z), + gp_Dir(dX.x, dX.y, dX.z) + ); sketchPlane.SetPosition(sketchAx3); } for (const auto& subShape : shape.getSubShapes(shapeType)) { @@ -7209,8 +7249,10 @@ int SketchObject::addExternal(App::DocumentObject* Obj, if (Objects.size() != SubElements.size()) { assert(0 /*counts of objects and subelements in external geometry links do not match*/); - Base::Console().error("Internal error: counts of objects and subelements in external " - "geometry links do not match\n"); + Base::Console().error( + "Internal error: counts of objects and subelements in external " + "geometry links do not match\n" + ); return -1; } @@ -7233,9 +7275,9 @@ int SketchObject::addExternal(App::DocumentObject* Obj, // add the new ones Objects.push_back(Obj); SubElements.emplace_back(SubName); - Types.push_back( - static_cast(intersection ? ExtType::Intersection : ExtType::Projection)); - if (intersection) {} + Types.push_back(static_cast(intersection ? ExtType::Intersection : ExtType::Projection)); + if (intersection) { + } // set the Link list. ExternalGeometry.setValues(Objects, SubElements); diff --git a/src/Mod/Sketcher/App/SketchObject.h b/src/Mod/Sketcher/App/SketchObject.h index 10582f9d4a..e77f238d90 100644 --- a/src/Mod/Sketcher/App/SketchObject.h +++ b/src/Mod/Sketcher/App/SketchObject.h @@ -48,8 +48,8 @@ namespace Sketcher enum class DeleteOption { NoFlag = 0, - IncludeInternalGeometry = - 1, // Only makes sense when deleting a geometry - (default for deleting a single geometry) + IncludeInternalGeometry = 1, // Only makes sense when deleting a geometry - (default for + // deleting a single geometry) UpdateGeometry = 2, // Should the solver update the geometries ? (default) - has no effect if // noRecompute is false NoSolve = 4, // Can be useful if the call will do many operations and a single solve @@ -170,19 +170,22 @@ public: \param deleteinternalgeo - if true deletes the associated and unconstraint internal geometry, otherwise deletes only the GeoId \retval int - 0 if successful */ - int delGeometry(int GeoId, - DeleteOptions options = DeleteOption::UpdateGeometry - | DeleteOption::IncludeInternalGeometry); + int delGeometry( + int GeoId, + DeleteOptions options = DeleteOption::UpdateGeometry | DeleteOption::IncludeInternalGeometry + ); /// Deletes just the GeoIds indicated, it does not look for internal geometry - int delGeometriesExclusiveList(const std::vector& GeoIds, - DeleteOptions options = DeleteOption::UpdateGeometry); + int delGeometriesExclusiveList( + const std::vector& GeoIds, + DeleteOptions options = DeleteOption::UpdateGeometry + ); /// Does the same as \a delGeometry but allows one to delete several geometries in one step - int delGeometries(const std::vector& GeoIds, - DeleteOptions options = DeleteOption::UpdateGeometry); + int delGeometries( + const std::vector& GeoIds, + DeleteOptions options = DeleteOption::UpdateGeometry + ); template - int delGeometries(InputIt first, - InputIt last, - DeleteOptions options = DeleteOption::UpdateGeometry); + int delGeometries(InputIt first, InputIt last, DeleteOptions options = DeleteOption::UpdateGeometry); /// deletes all the elements/constraints of the sketch except for external geometry int deleteAllGeometry(DeleteOptions options = DeleteOption::UpdateGeometry); /// deletes all the constraints of the sketch @@ -204,26 +207,29 @@ public: * updategeometry=false, prevents the update. This allows one to update the solve status (e.g. * dof), without updating the geometry (i.e. make it move to fulfil the constraints). */ - int delConstraints(std::vector ConstrIds, - DeleteOptions options = DeleteOption::UpdateGeometry); + int delConstraints(std::vector ConstrIds, DeleteOptions options = DeleteOption::UpdateGeometry); int delConstraintOnPoint(int GeoId, PointPos PosId, bool onlyCoincident = true); int delConstraintOnPoint(int VertexId, bool onlyCoincident = true); /// Deletes all constraints referencing an external geometry int delConstraintsToExternal(DeleteOptions options = DeleteOption::UpdateGeometry); /// transfers all constraints of a point to a new - int transferConstraints(int fromGeoId, - PointPos fromPosId, - int toGeoId, - PointPos toPosId, - bool doNotTransformTangencies = false); + int transferConstraints( + int fromGeoId, + PointPos fromPosId, + int toGeoId, + PointPos toPosId, + bool doNotTransformTangencies = false + ); /// Carbon copy another sketch geometry and constraints int carbonCopy(App::DocumentObject* pObj, bool construction = true); /// add an external geometry reference - int addExternal(App::DocumentObject* Obj, - const char* SubName, - bool defining = false, - bool intersection = false); + int addExternal( + App::DocumentObject* Obj, + const char* SubName, + bool defining = false, + bool intersection = false + ); /** delete external * ExtGeoId >= 0 with 0 corresponding to the first user defined * external geometry @@ -231,8 +237,7 @@ public: int delExternal(int ExtGeoId); int delExternal(const std::vector& ExtGeoIds); /// attach a link reference to an external geometry - int - attachExternal(const std::vector& geoIds, App::DocumentObject* Obj, const char* SubName); + int attachExternal(const std::vector& geoIds, App::DocumentObject* Obj, const char* SubName); int detachExternal(const std::vector& geoIds); /** deletes all external geometry */ @@ -373,8 +378,7 @@ public: std::string getConstraintExpression(int constNum) const; // Set a constraint associated expression void setConstraintExpression(int constNum, const std::string& newExpression); - void setExpression(const App::ObjectIdentifier& path, - std::shared_ptr expr) override; + void setExpression(const App::ObjectIdentifier& path, std::shared_ptr expr) override; /// set the driving status of this constraint and solve int setVirtualSpace(int ConstrId, bool isinvirtualspace); @@ -389,15 +393,19 @@ public: /// set the visibility of a group of constraints at once int setVisibility(std::vector constrIds, bool isVisible); /// move this point to a new location and solve - int moveGeometries(const std::vector& geoEltIds, - const Base::Vector3d& toPoint, - bool relative = false, - bool updateGeoBeforeMoving = false); - int moveGeometry(int GeoId, - PointPos PosId, - const Base::Vector3d& toPoint, - bool relative = false, - bool updateGeoBeforeMoving = false); + int moveGeometries( + const std::vector& geoEltIds, + const Base::Vector3d& toPoint, + bool relative = false, + bool updateGeoBeforeMoving = false + ); + int moveGeometry( + int GeoId, + PointPos PosId, + const Base::Vector3d& toPoint, + bool relative = false, + bool updateGeoBeforeMoving = false + ); /// retrieves the coordinates of a point static Base::Vector3d getPoint(const Part::Geometry* geo, PointPos PosId); Base::Vector3d getPoint(int GeoId, PointPos PosId) const; @@ -421,12 +429,14 @@ public: \param createCorner - keep geoId/pos as a Point and keep as many constraints as possible \retval - 0 on success, -1 on failure */ - int fillet(int geoId, - PointPos pos, - double radius, - bool trim = true, - bool preserveCorner = false, - bool chamfer = false); + int fillet( + int geoId, + PointPos pos, + double radius, + bool trim = true, + bool preserveCorner = false, + bool chamfer = false + ); /*! \brief More general form of fillet \param geoId1, geoId2 - geoId for two lines (which don't necessarily have to coincide) @@ -436,14 +446,16 @@ public: meet and keep as many of the existing constraints as possible \retval - 0 on success, -1 on failure */ - int fillet(int geoId1, - int geoId2, - const Base::Vector3d& refPnt1, - const Base::Vector3d& refPnt2, - double radius, - bool trim = true, - bool createCorner = false, - bool chamfer = false); + int fillet( + int geoId1, + int geoId2, + const Base::Vector3d& refPnt1, + const Base::Vector3d& refPnt2, + double radius, + bool trim = true, + bool createCorner = false, + bool chamfer = false + ); /// trim a curve int trim(int geoId, const Base::Vector3d& point); @@ -454,16 +466,20 @@ public: /// assuming all constraints on the end points of the old curve have been transferred or /// destroyed /// Returns whether or not new constraint(s) was/were added. - bool deriveConstraintsForPieces(const int oldId, - const std::vector& newIds, - const Constraint* con, - std::vector& newConstraints) const; + bool deriveConstraintsForPieces( + const int oldId, + const std::vector& newIds, + const Constraint* con, + std::vector& newConstraints + ) const; // Explicitly giving `newGeos` for cases where they are not yet added - bool deriveConstraintsForPieces(const int oldId, - const std::vector& newIds, - const std::vector& newGeo, - const Constraint* con, - std::vector& newConstraints) const; + bool deriveConstraintsForPieces( + const int oldId, + const std::vector& newIds, + const std::vector& newGeo, + const Constraint* con, + std::vector& newConstraints + ) const; /// split a curve int split(int geoId, const Base::Vector3d& point); @@ -473,37 +489,44 @@ public: \param geoId1, posId1, geoId2, posId2: the end points to join \retval - 0 on success, -1 on failure */ - int join(int geoId1, - Sketcher::PointPos posId1, - int geoId2, - Sketcher::PointPos posId2, - int continuity = 0); + int join( + int geoId1, + Sketcher::PointPos posId1, + int geoId2, + Sketcher::PointPos posId2, + int continuity = 0 + ); /// adds symmetric geometric elements with respect to the refGeoId (line or point) - int addSymmetric(const std::vector& geoIdList, - int refGeoId, - Sketcher::PointPos refPosId = Sketcher::PointPos::none, - bool addSymmetryConstraints = false); + int addSymmetric( + const std::vector& geoIdList, + int refGeoId, + Sketcher::PointPos refPosId = Sketcher::PointPos::none, + bool addSymmetryConstraints = false + ); // get the symmetric geometries of the geoIdList - std::vector - getSymmetric(const std::vector& geoIdList, - std::map& geoIdMap, - std::map& isStartEndInverted, - int refGeoId, - Sketcher::PointPos refPosId = Sketcher::PointPos::none); + std::vector getSymmetric( + const std::vector& geoIdList, + std::map& geoIdMap, + std::map& isStartEndInverted, + int refGeoId, + Sketcher::PointPos refPosId = Sketcher::PointPos::none + ); /// with default parameters adds a copy of the geometric elements displaced by the displacement /// vector. It creates an array of csize elements in the direction of the displacement vector by /// rsize elements in the direction perpendicular to the displacement vector, wherein the /// modulus of this perpendicular vector is scaled by perpscale. - int addCopy(const std::vector& geoIdList, - const Base::Vector3d& displacement, - bool moveonly = false, - bool clone = false, - int csize = 2, - int rsize = 1, - bool constraindisplacement = false, - double perpscale = 1.0); + int addCopy( + const std::vector& geoIdList, + const Base::Vector3d& displacement, + bool moveonly = false, + bool clone = false, + int csize = 2, + int rsize = 1, + bool constraindisplacement = false, + double perpscale = 1.0 + ); int removeAxesAlignment(const std::vector& geoIdList); static bool isClosedCurve(const Part::Geometry* geo); @@ -599,23 +622,29 @@ public: const std::vector> getCoincidenceGroups(); // returns if the given geoId is fixed (coincident) with external geometry on any of the // possible relevant points - void isCoincidentWithExternalGeometry(int GeoId, - bool& start_external, - bool& mid_external, - bool& end_external); + void isCoincidentWithExternalGeometry( + int GeoId, + bool& start_external, + bool& mid_external, + bool& end_external + ); // returns a map containing all the GeoIds that are coincident with the given point as keys, and // the PosIds as values associated with the keys. const std::map getAllCoincidentPoints(int GeoId, PointPos PosId); /// retrieves for a Vertex number a list with all coincident points (sharing a single /// coincidence constraint) - void getDirectlyCoincidentPoints(int GeoId, - PointPos PosId, - std::vector& GeoIdList, - std::vector& PosIdList); - void getDirectlyCoincidentPoints(int VertexId, - std::vector& GeoIdList, - std::vector& PosIdList); + void getDirectlyCoincidentPoints( + int GeoId, + PointPos PosId, + std::vector& GeoIdList, + std::vector& PosIdList + ); + void getDirectlyCoincidentPoints( + int VertexId, + std::vector& GeoIdList, + std::vector& PosIdList + ); bool arePointsCoincident(int GeoId1, PointPos PosId1, int GeoId2, PointPos PosId2); /// returns a list of indices of all constraints involving given GeoId @@ -641,9 +670,11 @@ public: unsigned int getMemSize() const override; void Save(Base::Writer& /*writer*/) const override; void Restore(Base::XMLReader& /*reader*/) override; - void handleChangedPropertyType(Base::XMLReader& reader, - const char* TypeName, - App::Property* prop) override; + void handleChangedPropertyType( + Base::XMLReader& reader, + const char* TypeName, + App::Property* prop + ) override; /// returns the number of construction lines (to be used as axes) int getAxisCount() const override; @@ -727,11 +758,13 @@ public: /* Solver exposed interface */ } /// enables/disables solver initial solution recalculation when moving point mode (useful for /// dragging) - inline void - setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) + inline void setRecalculateInitialSolutionWhileMovingPoint( + bool recalculateInitialSolutionWhileMovingPoint + ) { solvedSketch.setRecalculateInitialSolutionWhileMovingPoint( - recalculateInitialSolutionWhileMovingPoint); + recalculateInitialSolutionWhileMovingPoint + ); } /// Forwards a request for a temporary initMove to the solver using the current sketch state as /// a reference (enables dragging) @@ -740,19 +773,27 @@ public: /* Solver exposed interface */ inline int initTemporaryMove(int geoId, PointPos pos, bool fine = true); /// Forwards a request for a temporary initBSplinePieceMove to the solver using the current /// sketch state as a reference (enables dragging) - inline int initTemporaryBSplinePieceMove(int geoId, - PointPos pos, - const Base::Vector3d& firstPoint, - bool fine = true); + inline int initTemporaryBSplinePieceMove( + int geoId, + PointPos pos, + const Base::Vector3d& firstPoint, + bool fine = true + ); /** Forwards a request for point or curve temporary movement to the solver using the current * state as a reference (enables dragging). NOTE: A temporary move operation must always be * preceded by a initTemporaryMove() operation. */ - inline int moveGeometriesTemporary(std::vector moved, - Base::Vector3d toPoint, - bool relative = false); - inline int - moveGeometryTemporary(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative = false); + inline int moveGeometriesTemporary( + std::vector moved, + Base::Vector3d toPoint, + bool relative = false + ); + inline int moveGeometryTemporary( + int geoId, + PointPos pos, + Base::Vector3d toPoint, + bool relative = false + ); /// forwards a request to update an extension of a geometry of the solver to the solver. inline void updateSolverExtension(int geoId, std::unique_ptr&& ext) { @@ -799,28 +840,32 @@ public: }; /// Return true if this object is allowed as external geometry for the /// sketch. rsn argument receives the reason for disallowing. - bool isExternalAllowed(App::Document* pDoc, - App::DocumentObject* pObj, - eReasonList* rsn = nullptr) const; + bool isExternalAllowed(App::Document* pDoc, App::DocumentObject* pObj, eReasonList* rsn = nullptr) const; - bool isCarbonCopyAllowed(App::Document* pDoc, - App::DocumentObject* pObj, - bool& xinv, - bool& yinv, - eReasonList* rsn = nullptr) const; + bool isCarbonCopyAllowed( + App::Document* pDoc, + App::DocumentObject* pObj, + bool& xinv, + bool& yinv, + eReasonList* rsn = nullptr + ) const; - DocumentObject* getSubObject(const char* subname, - PyObject** pyObj = 0, - Base::Matrix4D* mat = 0, - bool transform = true, - int depth = 0) const override; + DocumentObject* getSubObject( + const char* subname, + PyObject** pyObj = 0, + Base::Matrix4D* mat = 0, + bool transform = true, + int depth = 0 + ) const override; Part::TopoShape getEdge(const Part::Geometry* geo, const char* name) const; std::vector getElementTypes(bool all = true) const override; - std::vector getHigherElements(const char* element, - bool silent = false) const override; + std::vector getHigherElements( + const char* element, + bool silent = false + ) const override; Data::IndexedName checkSubName(const char* subname) const; @@ -866,21 +911,27 @@ public: * - it includes internal and external intersecting geometry. * - it returns GeoEnum::GeoUndef if no intersection is found. */ - bool seekTrimPoints(int GeoId, - const Base::Vector3d& point, - int& GeoId1, - Base::Vector3d& intersect1, - int& GeoId2, - Base::Vector3d& intersect2); + bool seekTrimPoints( + int GeoId, + const Base::Vector3d& point, + int& GeoId1, + Base::Vector3d& intersect1, + int& GeoId2, + Base::Vector3d& intersect2 + ); public: // Analyser functions - int autoConstraint(double precision = Precision::Confusion() * 1000, - double angleprecision = std::numbers::pi / 20, - bool includeconstruction = true); + int autoConstraint( + double precision = Precision::Confusion() * 1000, + double angleprecision = std::numbers::pi / 20, + bool includeconstruction = true + ); - int detectMissingPointOnPointConstraints(double precision = Precision::Confusion() * 1000, - bool includeconstruction = true); + int detectMissingPointOnPointConstraints( + double precision = Precision::Confusion() * 1000, + bool includeconstruction = true + ); void analyseMissingPointOnPointCoincident(double angleprecision = std::numbers::pi / 8); int detectMissingVerticalHorizontalConstraints(double angleprecision = std::numbers::pi / 8); int detectMissingEqualityConstraints(double precision); @@ -930,8 +981,10 @@ public: // geometry extension functionalities for single element sketch object protected: // Only the first flag is toggled, the rest of the flags is set or cleared following the first // flag. - int toggleExternalGeometryFlag(const std::vector& geoIds, - const std::vector& flags); + int toggleExternalGeometryFlag( + const std::vector& geoIds, + const std::vector& flags + ); void buildShape(); /// get called by the container when a property has changed @@ -955,8 +1008,10 @@ protected: void restoreFinished() override; void onSketchRestore(); - std::string validateExpression(const App::ObjectIdentifier& path, - std::shared_ptr expr); + std::string validateExpression( + const App::ObjectIdentifier& path, + std::shared_ptr expr + ); void constraintsRenamed(const std::map& renamed); void constraintsRemoved(const std::set& removed); @@ -965,8 +1020,7 @@ protected: \param geoList - the geometry list \retval list - the supported geometry list */ - std::vector - supportedGeometry(const std::vector& geoList) const; + std::vector supportedGeometry(const std::vector& geoList) const; void updateGeoHistory(); void generateId(const Part::Geometry* geo); @@ -1001,10 +1055,12 @@ protected: // migration functions void migrateSketch(); - static void appendConstraintsMsg(const std::vector& vector, - const std::string& singularmsg, - const std::string& pluralmsg, - std::string& msg); + static void appendConstraintsMsg( + const std::vector& vector, + const std::string& singularmsg, + const std::string& pluralmsg, + std::string& msg + ); // retrieves redundant, conflicting and malformed constraint information from the solver void retrieveSolverDiagnostics(); @@ -1015,36 +1071,43 @@ protected: // retrieves the geometry blocked state corresponding to this constraint // returns true of the constraint is of InternalAlignment type, false otherwise - bool getInternalTypeState(const Constraint* cstr, - Sketcher::InternalType::InternalType& internaltypestate) const; + bool getInternalTypeState( + const Constraint* cstr, + Sketcher::InternalType::InternalType& internaltypestate + ) const; // Checks whether the geometry state stored in the geometry extension matches the current // sketcher situation (e.g. constraints) and corrects the state if not matching. void synchroniseGeometryState(); // helper function to create a new constraint and move it to the Constraint Property - void addConstraint(Sketcher::ConstraintType constrType, - int firstGeoId, - Sketcher::PointPos firstPos, - int secondGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos secondPos = Sketcher::PointPos::none, - int thirdGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos thirdPos = Sketcher::PointPos::none); + void addConstraint( + Sketcher::ConstraintType constrType, + int firstGeoId, + Sketcher::PointPos firstPos, + int secondGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos secondPos = Sketcher::PointPos::none, + int thirdGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos thirdPos = Sketcher::PointPos::none + ); // creates a new constraint - std::unique_ptr - createConstraint(Sketcher::ConstraintType constrType, - int firstGeoId, - Sketcher::PointPos firstPos, - int secondGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos secondPos = Sketcher::PointPos::none, - int thirdGeoId = GeoEnum::GeoUndef, - Sketcher::PointPos thirdPos = Sketcher::PointPos::none); + std::unique_ptr createConstraint( + Sketcher::ConstraintType constrType, + int firstGeoId, + Sketcher::PointPos firstPos, + int secondGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos secondPos = Sketcher::PointPos::none, + int thirdGeoId = GeoEnum::GeoUndef, + Sketcher::PointPos thirdPos = Sketcher::PointPos::none + ); public: // FIXME: These may not need to be public. Decide before merging. - std::unique_ptr getConstraintAfterDeletingGeo(const Constraint* constr, - const int deletedGeoId) const; + std::unique_ptr getConstraintAfterDeletingGeo( + const Constraint* constr, + const int deletedGeoId + ) const; void changeConstraintAfterDeletingGeo(Constraint* constr, const int deletedGeoId) const; @@ -1154,10 +1217,12 @@ inline int SketchObject::initTemporaryMove(int geoId, PointPos pos, bool fine /* return initTemporaryMove(moved, fine); } -inline int SketchObject::initTemporaryBSplinePieceMove(int geoId, - PointPos pos, - const Base::Vector3d& firstPoint, - bool fine) +inline int SketchObject::initTemporaryBSplinePieceMove( + int geoId, + PointPos pos, + const Base::Vector3d& firstPoint, + bool fine +) { // if a previous operation did not update the geometry (including geometry extensions) // or constraints (including any deleted pointer, as in renameConstraint) of the solver, @@ -1169,16 +1234,12 @@ inline int SketchObject::initTemporaryBSplinePieceMove(int geoId, return solvedSketch.initBSplinePieceMove(geoId, pos, firstPoint, fine); } -inline int SketchObject::moveGeometriesTemporary(std::vector geoEltIds, - Base::Vector3d toPoint, - bool relative /*=false*/) +inline int SketchObject:: + moveGeometriesTemporary(std::vector geoEltIds, Base::Vector3d toPoint, bool relative /*=false*/) { return solvedSketch.moveGeometries(geoEltIds, toPoint, relative); } -inline int SketchObject::moveGeometryTemporary(int geoId, - PointPos pos, - Base::Vector3d toPoint, - bool relative /*=false*/) +inline int SketchObject::moveGeometryTemporary(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative /*=false*/) { std::vector moved = {GeoElementId(geoId, pos)}; return moveGeometriesTemporary(moved, toPoint, relative); diff --git a/src/Mod/Sketcher/App/SketchObjectPyImp.cpp b/src/Mod/Sketcher/App/SketchObjectPyImp.cpp index 754fb7973f..4dc119591f 100644 --- a/src/Mod/Sketcher/App/SketchObjectPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchObjectPyImp.cpp @@ -123,8 +123,7 @@ PyObject* SketchObjectPy::addGeometry(PyObject* args) } return Py::new_reference_to(Py::Long(ret)); } - else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) - || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoList; std::vector> tmpList; Py::Sequence list(pcObj); @@ -134,11 +133,9 @@ PyObject* SketchObjectPy::addGeometry(PyObject* args) // An arc created with Part.Arc will be converted into a Part.ArcOfCircle if (geo->is()) { - Handle(Geom_TrimmedCurve) trim = - Handle(Geom_TrimmedCurve)::DownCast(geo->handle()); + Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast(geo->handle()); Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(trim->BasisCurve()); - Handle(Geom_Ellipse) ellipse = - Handle(Geom_Ellipse)::DownCast(trim->BasisCurve()); + Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(trim->BasisCurve()); if (!circle.IsNull()) { // create the definition struct for that geom std::shared_ptr aoc(new Part::GeomArcOfCircle()); @@ -202,7 +199,8 @@ PyObject* SketchObjectPy::delGeometry(PyObject* args) if (this->getSketchObjectPtr()->delGeometry( Index, - Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry)) { + Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry + )) { std::stringstream str; str << "Not able to delete a geometry with the given index: " << Index; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -232,7 +230,8 @@ PyObject* SketchObjectPy::delGeometries(PyObject* args) if (this->getSketchObjectPtr()->delGeometries( geoIdList, - Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry)) { + Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry + )) { std::stringstream str; str << "Not able to delete geometries"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -255,7 +254,8 @@ PyObject* SketchObjectPy::deleteAllGeometry(PyObject* args) } if (this->getSketchObjectPtr()->deleteAllGeometry( - Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry)) { + Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry + )) { std::stringstream str; str << "Unable to delete Geometry"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -368,8 +368,7 @@ PyObject* SketchObjectPy::addConstraint(PyObject* args) } if (PyObject_TypeCheck(pcObj, &(Sketcher::ConstraintPy::Type))) { - Sketcher::Constraint* constr = - static_cast(pcObj)->getConstraintPtr(); + Sketcher::Constraint* constr = static_cast(pcObj)->getConstraintPtr(); if (!this->getSketchObjectPtr()->evaluateConstraint(constr)) { PyErr_SetString(PyExc_IndexError, "Constraint has invalid indexes"); return nullptr; @@ -400,8 +399,7 @@ PyObject* SketchObjectPy::addConstraint(PyObject* args) } return Py::new_reference_to(Py::Long(ret)); } - else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) - || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector values; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -417,7 +415,9 @@ PyObject* SketchObjectPy::addConstraint(PyObject* args) PyExc_IndexError, QT_TRANSLATE_NOOP( "Notifications", - "The constraint has invalid index information and is malformed.")); + "The constraint has invalid index information and is malformed." + ) + ); return nullptr; } } @@ -447,7 +447,8 @@ PyObject* SketchObjectPy::delConstraint(PyObject* args) if (this->getSketchObjectPtr()->delConstraint( Index, - Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry)) { + Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::UpdateGeometry + )) { std::stringstream str; str << "Not able to delete a constraint with the given index: " << Index; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -462,13 +463,7 @@ PyObject* SketchObjectPy::delConstraints(PyObject* args) PyObject* updateGeometry = Py_True; PyObject* noSolve = Py_False; - if (!PyArg_ParseTuple(args, - "O|O!O!", - &pcObj, - &PyBool_Type, - &updateGeometry, - &PyBool_Type, - &noSolve)) { + if (!PyArg_ParseTuple(args, "O|O!O!", &pcObj, &PyBool_Type, &updateGeometry, &PyBool_Type, &noSolve)) { return nullptr; } @@ -484,9 +479,9 @@ PyObject* SketchObjectPy::delConstraints(PyObject* args) if (this->getSketchObjectPtr()->delConstraints( constraintIdList, - (Base::asBoolean(updateGeometry) ? DeleteOption::UpdateGeometry - : DeleteOption::NoFlag) - | (Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::NoFlag)) + (Base::asBoolean(updateGeometry) ? DeleteOption::UpdateGeometry : DeleteOption::NoFlag) + | (Base::asBoolean(noSolve) ? DeleteOption::NoSolve : DeleteOption::NoFlag) + ) == -1) { std::stringstream str; str << "Not able to delete constraints, invalid indices"; @@ -531,8 +526,7 @@ PyObject* SketchObjectPy::renameConstraint(PyObject* args) return nullptr; } - const std::vector& vals = - getSketchObjectPtr()->Constraints.getValues(); + const std::vector& vals = getSketchObjectPtr()->Constraints.getValues(); for (std::size_t i = 0; i < vals.size(); ++i) { if (static_cast(i) != Index && Name == vals[i]->Name) { PyErr_SetString(PyExc_ValueError, "Duplicate constraint not allowed"); @@ -614,14 +608,16 @@ PyObject* SketchObjectPy::addExternal(PyObject* args) char* SubName = nullptr; PyObject* defining = Py_False; PyObject* intersection = Py_False; - if (!PyArg_ParseTuple(args, - "ss|O!O!", - &ObjectName, - &SubName, - &PyBool_Type, - &defining, - &PyBool_Type, - &intersection)) { + if (!PyArg_ParseTuple( + args, + "ss|O!O!", + &ObjectName, + &SubName, + &PyBool_Type, + &defining, + &PyBool_Type, + &intersection + )) { return nullptr; } @@ -683,9 +679,8 @@ PyObject* SketchObjectPy::delConstraintOnPoint(PyObject* args) if (pos >= static_cast(Sketcher::PointPos::none) && pos <= static_cast(Sketcher::PointPos::mid)) { // This is the whole range of valid positions - if (this->getSketchObjectPtr()->delConstraintOnPoint( - Index, - static_cast(pos))) { + if (this->getSketchObjectPtr() + ->delConstraintOnPoint(Index, static_cast(pos))) { std::stringstream str; str << "Not able to delete a constraint on point with the given index: " << Index << " and position: " << pos; @@ -757,8 +752,7 @@ PyObject* SketchObjectPy::setDatum(PyObject* args) int i = 0; Index = -1; - const std::vector& vals = - this->getSketchObjectPtr()->Constraints.getValues(); + const std::vector& vals = this->getSketchObjectPtr()->Constraints.getValues(); for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it, ++i) { if ((*it)->Name == constrName) { @@ -784,8 +778,7 @@ PyObject* SketchObjectPy::setDatum(PyObject* args) Quantity.setValue(Datum); int i = 0; Index = -1; - const std::vector& vals = - this->getSketchObjectPtr()->Constraints.getValues(); + const std::vector& vals = this->getSketchObjectPtr()->Constraints.getValues(); for (std::vector::const_iterator it = vals.begin(); it != vals.end(); ++it, ++i) { if ((*it)->Name == constrName) { @@ -1017,8 +1010,10 @@ PyObject* SketchObjectPy::setVirtualSpace(PyObject* args) } try { - int ret = this->getSketchObjectPtr()->setVirtualSpace(constrIds, - Base::asBoolean(invirtualspace)); + int ret = this->getSketchObjectPtr()->setVirtualSpace( + constrIds, + Base::asBoolean(invirtualspace) + ); if (ret == -1) { throw Py::TypeError("Impossible to set virtual space!"); @@ -1031,8 +1026,8 @@ PyObject* SketchObjectPy::setVirtualSpace(PyObject* args) Py_Return; } else if (PyLong_Check(id_or_ids)) { - if (this->getSketchObjectPtr()->setVirtualSpace(PyLong_AsLong(id_or_ids), - Base::asBoolean(invirtualspace))) { + if (this->getSketchObjectPtr() + ->setVirtualSpace(PyLong_AsLong(id_or_ids), Base::asBoolean(invirtualspace))) { std::stringstream str; str << "Not able set virtual space for constraint with the given index: " << PyLong_AsLong(id_or_ids); @@ -1068,8 +1063,7 @@ PyObject* SketchObjectPy::setVisibility(PyObject* args) } try { - int ret = - this->getSketchObjectPtr()->setVisibility(constrIds, Base::asBoolean(isVisible)); + int ret = this->getSketchObjectPtr()->setVisibility(constrIds, Base::asBoolean(isVisible)); if (ret == -1) { throw Py::TypeError("Impossible to set visibility!"); @@ -1082,8 +1076,8 @@ PyObject* SketchObjectPy::setVisibility(PyObject* args) Py_Return; } else if (PyLong_Check(id_or_ids)) { - if (this->getSketchObjectPtr()->setVisibility(PyLong_AsLong(id_or_ids), - Base::asBoolean(isVisible))) { + if (this->getSketchObjectPtr() + ->setVisibility(PyLong_AsLong(id_or_ids), Base::asBoolean(isVisible))) { std::stringstream str; str << "Not able set visibility for constraint with the given index: " << PyLong_AsLong(id_or_ids); @@ -1264,13 +1258,15 @@ PyObject* SketchObjectPy::moveGeometries(PyObject* args) int relative = 0; // Parse arguments: list of pairs, Base::VectorPy, optional relative flag - if (!PyArg_ParseTuple(args, - "O!O!|i", - &PyList_Type, - &pyList, // List of pairs (geoId, pointPos) - &(Base::VectorPy::Type), - &pcObj, // Target vector - &relative)) { // Optional relative flag + if (!PyArg_ParseTuple( + args, + "O!O!|i", + &PyList_Type, + &pyList, // List of pairs (geoId, pointPos) + &(Base::VectorPy::Type), + &pcObj, // Target vector + &relative + )) { // Optional relative flag return nullptr; } @@ -1315,25 +1311,16 @@ PyObject* SketchObjectPy::moveGeometry(PyObject* args) int GeoId, PointType; int relative = 0; - if (!PyArg_ParseTuple(args, - "iiO!|i", - &GeoId, - &PointType, - &(Base::VectorPy::Type), - &pcObj, - &relative)) { + if (!PyArg_ParseTuple(args, "iiO!|i", &GeoId, &PointType, &(Base::VectorPy::Type), &pcObj, &relative)) { return nullptr; } Base::Vector3d v1 = static_cast(pcObj)->value(); - if (this->getSketchObjectPtr()->moveGeometry(GeoId, - static_cast(PointType), - v1, - (relative > 0))) { + if (this->getSketchObjectPtr() + ->moveGeometry(GeoId, static_cast(PointType), v1, (relative > 0))) { std::stringstream str; - str << "Not able to move point with the id and type: (" << GeoId << ", " << PointType - << ")"; + str << "Not able to move point with the id and type: (" << GeoId << ", " << PointType << ")"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); return nullptr; } @@ -1377,7 +1364,8 @@ PyObject* SketchObjectPy::getPoint(PyObject* args) const } return new Base::VectorPy( - new Base::Vector3d(obj->getPoint(GeoId, static_cast(PointType)))); + new Base::Vector3d(obj->getPoint(GeoId, static_cast(PointType))) + ); } PyObject* SketchObjectPy::getAxis(PyObject* args) const @@ -1400,34 +1388,38 @@ PyObject* SketchObjectPy::fillet(PyObject* args) double radius; // Two Lines, radius - if (PyArg_ParseTuple(args, - "iiO!O!d|iO!O!", - &geoId1, - &geoId2, - &(Base::VectorPy::Type), - &pcObj1, - &(Base::VectorPy::Type), - &pcObj2, - &radius, - &trim, - &PyBool_Type, - &createCorner, - &PyBool_Type, - &chamfer)) { + if (PyArg_ParseTuple( + args, + "iiO!O!d|iO!O!", + &geoId1, + &geoId2, + &(Base::VectorPy::Type), + &pcObj1, + &(Base::VectorPy::Type), + &pcObj2, + &radius, + &trim, + &PyBool_Type, + &createCorner, + &PyBool_Type, + &chamfer + )) { // The i for &trim should probably have been a bool like &createCorner, but we'll leave it // an int for backward compatibility (and because python will accept a bool there anyway) Base::Vector3d v1 = static_cast(pcObj1)->value(); Base::Vector3d v2 = static_cast(pcObj2)->value(); - if (this->getSketchObjectPtr()->fillet(geoId1, - geoId2, - v1, - v2, - radius, - trim, - Base::asBoolean(createCorner), - Base::asBoolean(chamfer))) { + if (this->getSketchObjectPtr()->fillet( + geoId1, + geoId2, + v1, + v2, + radius, + trim, + Base::asBoolean(createCorner), + Base::asBoolean(chamfer) + )) { std::stringstream str; str << "Not able to fillet curves with ids : (" << geoId1 << ", " << geoId2 << ") and points (" << v1.x << ", " << v1.y << ", " << v1.z << ") & " @@ -1440,22 +1432,26 @@ PyObject* SketchObjectPy::fillet(PyObject* args) PyErr_Clear(); // Point, radius - if (PyArg_ParseTuple(args, - "iid|iO!O!", - &geoId1, - &posId1, - &radius, - &trim, - &PyBool_Type, - &createCorner, - &PyBool_Type, - &chamfer)) { - if (this->getSketchObjectPtr()->fillet(geoId1, - static_cast(posId1), - radius, - trim, - Base::asBoolean(createCorner), - Base::asBoolean(chamfer))) { + if (PyArg_ParseTuple( + args, + "iid|iO!O!", + &geoId1, + &posId1, + &radius, + &trim, + &PyBool_Type, + &createCorner, + &PyBool_Type, + &chamfer + )) { + if (this->getSketchObjectPtr()->fillet( + geoId1, + static_cast(posId1), + radius, + trim, + Base::asBoolean(createCorner), + Base::asBoolean(chamfer) + )) { std::stringstream str; str << "Not able to fillet point with ( geoId: " << geoId1 << ", PointPos: " << posId1 << " )"; @@ -1465,10 +1461,12 @@ PyObject* SketchObjectPy::fillet(PyObject* args) Py_Return; } - PyErr_SetString(PyExc_TypeError, - "fillet() method accepts:\n" - "-- int,int,Vector,Vector,float,[bool],[bool]\n" - "-- int,int,float,[bool],[bool]\n"); + PyErr_SetString( + PyExc_TypeError, + "fillet() method accepts:\n" + "-- int,int,Vector,Vector,float,[bool],[bool]\n" + "-- int,int,float,[bool],[bool]\n" + ); return nullptr; } @@ -1500,9 +1498,8 @@ PyObject* SketchObjectPy::extend(PyObject* args) int GeoId; if (PyArg_ParseTuple(args, "idi", &GeoId, &increment, &endPoint)) { - if (this->getSketchObjectPtr()->extend(GeoId, - increment, - static_cast(endPoint))) { + if (this->getSketchObjectPtr() + ->extend(GeoId, increment, static_cast(endPoint))) { std::stringstream str; str << "Not able to extend geometry with id : (" << GeoId << ") for increment (" << increment << ") and point position (" << endPoint << ")"; @@ -1512,9 +1509,11 @@ PyObject* SketchObjectPy::extend(PyObject* args) Py_Return; } - PyErr_SetString(PyExc_TypeError, - "extend() method accepts:\n" - "-- int,float,int\n"); + PyErr_SetString( + PyExc_TypeError, + "extend() method accepts:\n" + "-- int,float,int\n" + ); return nullptr; } @@ -1554,11 +1553,8 @@ PyObject* SketchObjectPy::join(PyObject* args) return nullptr; } - if (this->getSketchObjectPtr()->join(GeoId1, - (Sketcher::PointPos)PosId1, - GeoId2, - (Sketcher::PointPos)PosId2, - continuity)) { + if (this->getSketchObjectPtr() + ->join(GeoId1, (Sketcher::PointPos)PosId1, GeoId2, (Sketcher::PointPos)PosId2, continuity)) { std::stringstream str; str << "Not able to join the curves with end points: (" << GeoId1 << ", " << PosId1 << "), (" << GeoId2 << ", " << PosId2 << ")"; @@ -1588,10 +1584,8 @@ PyObject* SketchObjectPy::addSymmetric(PyObject* args) } } - int ret = - this->getSketchObjectPtr()->addSymmetric(geoIdList, - refGeoId, - static_cast(refPosId)) + int ret = this->getSketchObjectPtr() + ->addSymmetric(geoIdList, refGeoId, static_cast(refPosId)) + 1; if (ret == -1) { @@ -1618,13 +1612,7 @@ PyObject* SketchObjectPy::addCopy(PyObject* args) PyObject *pcObj, *pcVect; PyObject* clone = Py_False; - if (!PyArg_ParseTuple(args, - "OO!|O!", - &pcObj, - &(Base::VectorPy::Type), - &pcVect, - &PyBool_Type, - &clone)) { + if (!PyArg_ParseTuple(args, "OO!|O!", &pcObj, &(Base::VectorPy::Type), &pcVect, &PyBool_Type, &clone)) { return nullptr; } @@ -1640,8 +1628,7 @@ PyObject* SketchObjectPy::addCopy(PyObject* args) } try { - int ret = - this->getSketchObjectPtr()->addCopy(geoIdList, vect, false, Base::asBoolean(clone)) + int ret = this->getSketchObjectPtr()->addCopy(geoIdList, vect, false, Base::asBoolean(clone)) + 1; if (ret == -1) { @@ -1704,18 +1691,20 @@ PyObject* SketchObjectPy::addRectangularArray(PyObject* args) PyObject* constraindisplacement = Py_False; PyObject* clone = Py_False; - if (!PyArg_ParseTuple(args, - "OO!O!ii|O!d", - &pcObj, - &(Base::VectorPy::Type), - &pcVect, - &PyBool_Type, - &clone, - &rows, - &cols, - &PyBool_Type, - &constraindisplacement, - &perpscale)) { + if (!PyArg_ParseTuple( + args, + "OO!O!ii|O!d", + &pcObj, + &(Base::VectorPy::Type), + &pcVect, + &PyBool_Type, + &clone, + &rows, + &cols, + &PyBool_Type, + &constraindisplacement, + &perpscale + )) { return nullptr; } @@ -1731,14 +1720,16 @@ PyObject* SketchObjectPy::addRectangularArray(PyObject* args) } try { - int ret = this->getSketchObjectPtr()->addCopy(geoIdList, - vect, - false, - Base::asBoolean(clone), - rows, - cols, - Base::asBoolean(constraindisplacement), - perpscale) + int ret = this->getSketchObjectPtr()->addCopy( + geoIdList, + vect, + false, + Base::asBoolean(clone), + rows, + cols, + Base::asBoolean(constraindisplacement), + perpscale + ) + 1; if (ret == -1) { @@ -1989,9 +1980,7 @@ PyObject* SketchObjectPy::modifyBSplineKnotMultiplicity(PyObject* args) return nullptr; } - if (!this->getSketchObjectPtr()->modifyBSplineKnotMultiplicity(GeoId, - knotIndex, - multiplicity)) { + if (!this->getSketchObjectPtr()->modifyBSplineKnotMultiplicity(GeoId, knotIndex, multiplicity)) { std::stringstream str; str << "Multiplicity modification failed for: " << GeoId; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -2028,18 +2017,12 @@ PyObject* SketchObjectPy::autoconstraint(PyObject* args) PyObject* includeconstruction = Py_True; - if (!PyArg_ParseTuple(args, - "|ddO!", - &precision, - &angleprecision, - &PyBool_Type, - &includeconstruction)) { + if (!PyArg_ParseTuple(args, "|ddO!", &precision, &angleprecision, &PyBool_Type, &includeconstruction)) { return nullptr; } - if (this->getSketchObjectPtr()->autoConstraint(precision, - angleprecision, - Base::asBoolean(includeconstruction))) { + if (this->getSketchObjectPtr() + ->autoConstraint(precision, angleprecision, Base::asBoolean(includeconstruction))) { std::stringstream str; str << "Unable to autoconstraint"; PyErr_SetString(PyExc_ValueError, str.str().c_str()); @@ -2061,7 +2044,9 @@ PyObject* SketchObjectPy::detectMissingPointOnPointConstraints(PyObject* args) return Py::new_reference_to( Py::Long(this->getSketchObjectPtr()->detectMissingPointOnPointConstraints( precision, - Base::asBoolean(includeconstruction)))); + Base::asBoolean(includeconstruction) + )) + ); } PyObject* SketchObjectPy::detectMissingVerticalHorizontalConstraints(PyObject* args) @@ -2072,8 +2057,9 @@ PyObject* SketchObjectPy::detectMissingVerticalHorizontalConstraints(PyObject* a return nullptr; } - return Py::new_reference_to(Py::Long( - this->getSketchObjectPtr()->detectMissingVerticalHorizontalConstraints(angleprecision))); + return Py::new_reference_to( + Py::Long(this->getSketchObjectPtr()->detectMissingVerticalHorizontalConstraints(angleprecision)) + ); } PyObject* SketchObjectPy::detectMissingEqualityConstraints(PyObject* args) @@ -2085,7 +2071,8 @@ PyObject* SketchObjectPy::detectMissingEqualityConstraints(PyObject* args) } return Py::new_reference_to( - Py::Long(this->getSketchObjectPtr()->detectMissingEqualityConstraints(precision))); + Py::Long(this->getSketchObjectPtr()->detectMissingEqualityConstraints(precision)) + ); } PyObject* SketchObjectPy::analyseMissingPointOnPointCoincident(PyObject* args) @@ -2162,7 +2149,8 @@ PyObject* SketchObjectPy::autoRemoveRedundants(PyObject* args) } this->getSketchObjectPtr()->autoRemoveRedundants( - Base::asBoolean(updategeo) ? DeleteOption::UpdateGeometry : DeleteOption::NoFlag); + Base::asBoolean(updategeo) ? DeleteOption::UpdateGeometry : DeleteOption::NoFlag + ); Py_Return; } @@ -2176,8 +2164,7 @@ PyObject* SketchObjectPy::toPythonCommands(PyObject* args) auto sketch = this->getSketchObjectPtr(); std::string geometry = PythonConverter::convert("ActiveSketch", sketch->Geometry.getValues()); - std::string constraints = - PythonConverter::convert("ActiveSketch", sketch->Constraints.getValues()); + std::string constraints = PythonConverter::convert("ActiveSketch", sketch->Constraints.getValues()); auto geometrymulti = PythonConverter::multiLine(std::move(geometry)); auto constraintmulti = PythonConverter::multiLine(std::move(constraints)); @@ -2204,24 +2191,32 @@ PyObject* SketchObjectPy::toPythonCommands(PyObject* args) Py::List SketchObjectPy::getMissingPointOnPointConstraints() const { - std::vector constraints = - this->getSketchObjectPtr()->getMissingPointOnPointConstraints(); + std::vector constraints + = this->getSketchObjectPtr()->getMissingPointOnPointConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(5); t.setItem(0, Py::Long(c.First)); - t.setItem(1, - Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 - : (c.FirstPos == Sketcher::PointPos::start) ? 1 - : (c.FirstPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 1, + Py::Long( + ((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, - Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 - : (c.SecondPos == Sketcher::PointPos::start) ? 1 - : (c.SecondPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 3, + Py::Long( + ((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); t.setItem(4, Py::Long(c.Type)); list.append(t); } @@ -2236,11 +2231,13 @@ void SketchObjectPy::setMissingPointOnPointConstraints(Py::List arg) auto checkitem = [](Py::Tuple& t, int i, int val) { return long(Py::Long(t.getItem(i))) == val; }; - return (checkitem(t, i, 0) - ? Sketcher::PointPos::none - : (checkitem(t, i, 1) ? Sketcher::PointPos::start - : (checkitem(t, i, 2) ? Sketcher::PointPos::end - : Sketcher::PointPos::mid))); + return ( + checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) + ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end : Sketcher::PointPos::mid)) + ); }; for (const auto& ti : arg) { @@ -2260,24 +2257,32 @@ void SketchObjectPy::setMissingPointOnPointConstraints(Py::List arg) Py::List SketchObjectPy::getMissingVerticalHorizontalConstraints() const { - std::vector constraints = - this->getSketchObjectPtr()->getMissingVerticalHorizontalConstraints(); + std::vector constraints + = this->getSketchObjectPtr()->getMissingVerticalHorizontalConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(5); t.setItem(0, Py::Long(c.First)); - t.setItem(1, - Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 - : (c.FirstPos == Sketcher::PointPos::start) ? 1 - : (c.FirstPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 1, + Py::Long( + ((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, - Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 - : (c.SecondPos == Sketcher::PointPos::start) ? 1 - : (c.SecondPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 3, + Py::Long( + ((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); t.setItem(4, Py::Long(c.Type)); list.append(t); } @@ -2292,11 +2297,13 @@ void SketchObjectPy::setMissingVerticalHorizontalConstraints(Py::List arg) auto checkitem = [](Py::Tuple& t, int i, int val) { return long(Py::Long(t.getItem(i))) == val; }; - return (checkitem(t, i, 0) - ? Sketcher::PointPos::none - : (checkitem(t, i, 1) ? Sketcher::PointPos::start - : (checkitem(t, i, 2) ? Sketcher::PointPos::end - : Sketcher::PointPos::mid))); + return ( + checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) + ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end : Sketcher::PointPos::mid)) + ); }; for (const auto& ti : arg) { @@ -2316,24 +2323,32 @@ void SketchObjectPy::setMissingVerticalHorizontalConstraints(Py::List arg) Py::List SketchObjectPy::getMissingLineEqualityConstraints() const { - std::vector constraints = - this->getSketchObjectPtr()->getMissingLineEqualityConstraints(); + std::vector constraints + = this->getSketchObjectPtr()->getMissingLineEqualityConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(4); t.setItem(0, Py::Long(c.First)); - t.setItem(1, - Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 - : (c.FirstPos == Sketcher::PointPos::start) ? 1 - : (c.FirstPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 1, + Py::Long( + ((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, - Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 - : (c.SecondPos == Sketcher::PointPos::start) ? 1 - : (c.SecondPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 3, + Py::Long( + ((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); list.append(t); } return list; @@ -2347,11 +2362,13 @@ void SketchObjectPy::setMissingLineEqualityConstraints(Py::List arg) auto checkitem = [](Py::Tuple& t, int i, int val) { return long(Py::Long(t.getItem(i))) == val; }; - return (checkitem(t, i, 0) - ? Sketcher::PointPos::none - : (checkitem(t, i, 1) ? Sketcher::PointPos::start - : (checkitem(t, i, 2) ? Sketcher::PointPos::end - : Sketcher::PointPos::mid))); + return ( + checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) + ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end : Sketcher::PointPos::mid)) + ); }; for (const auto& ti : arg) { @@ -2371,24 +2388,31 @@ void SketchObjectPy::setMissingLineEqualityConstraints(Py::List arg) Py::List SketchObjectPy::getMissingRadiusConstraints() const { - std::vector constraints = - this->getSketchObjectPtr()->getMissingRadiusConstraints(); + std::vector constraints = this->getSketchObjectPtr()->getMissingRadiusConstraints(); Py::List list; for (auto c : constraints) { Py::Tuple t(4); t.setItem(0, Py::Long(c.First)); - t.setItem(1, - Py::Long(((c.FirstPos == Sketcher::PointPos::none) ? 0 - : (c.FirstPos == Sketcher::PointPos::start) ? 1 - : (c.FirstPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 1, + Py::Long( + ((c.FirstPos == Sketcher::PointPos::none) ? 0 + : (c.FirstPos == Sketcher::PointPos::start) ? 1 + : (c.FirstPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); t.setItem(2, Py::Long(c.Second)); - t.setItem(3, - Py::Long(((c.SecondPos == Sketcher::PointPos::none) ? 0 - : (c.SecondPos == Sketcher::PointPos::start) ? 1 - : (c.SecondPos == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 3, + Py::Long( + ((c.SecondPos == Sketcher::PointPos::none) ? 0 + : (c.SecondPos == Sketcher::PointPos::start) ? 1 + : (c.SecondPos == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); list.append(t); } return list; @@ -2402,11 +2426,13 @@ void SketchObjectPy::setMissingRadiusConstraints(Py::List arg) auto checkitem = [](Py::Tuple& t, int i, int val) { return long(Py::Long(t.getItem(i))) == val; }; - return (checkitem(t, i, 0) - ? Sketcher::PointPos::none - : (checkitem(t, i, 1) ? Sketcher::PointPos::start - : (checkitem(t, i, 2) ? Sketcher::PointPos::end - : Sketcher::PointPos::mid))); + return ( + checkitem(t, i, 0) + ? Sketcher::PointPos::none + : (checkitem(t, i, 1) + ? Sketcher::PointPos::start + : (checkitem(t, i, 2) ? Sketcher::PointPos::end : Sketcher::PointPos::mid)) + ); }; for (const auto& ti : arg) { @@ -2438,11 +2464,15 @@ PyObject* SketchObjectPy::getGeometryWithDependentParameters(PyObject* args) for (auto pair : geometrymap) { Py::Tuple t(2); t.setItem(0, Py::Long(pair.first)); - t.setItem(1, - Py::Long(((pair.second == Sketcher::PointPos::none) ? 0 - : (pair.second == Sketcher::PointPos::start) ? 1 - : (pair.second == Sketcher::PointPos::end) ? 2 - : 3))); + t.setItem( + 1, + Py::Long( + ((pair.second == Sketcher::PointPos::none) ? 0 + : (pair.second == Sketcher::PointPos::start) ? 1 + : (pair.second == Sketcher::PointPos::end) ? 2 + : 3) + ) + ); list.append(t); } return Py::new_reference_to(list); @@ -2486,8 +2516,9 @@ Py::List SketchObjectPy::getGeometryFacadeList() const for (int i = 0; i < getSketchObjectPtr()->Geometry.getSize(); i++) { // we create a python copy and add it to the list - std::unique_ptr geofacade = - GeometryFacade::getFacade(getSketchObjectPtr()->Geometry[i]->clone()); + std::unique_ptr geofacade = GeometryFacade::getFacade( + getSketchObjectPtr()->Geometry[i]->clone() + ); geofacade->setOwner(true); Py::Object gfp = Py::Object(new GeometryFacadePy(geofacade.release()), true); diff --git a/src/Mod/Sketcher/App/SketchObjectSF.cpp b/src/Mod/Sketcher/App/SketchObjectSF.cpp index 932182f86e..d0026cb59d 100644 --- a/src/Mod/Sketcher/App/SketchObjectSF.cpp +++ b/src/Mod/Sketcher/App/SketchObjectSF.cpp @@ -32,11 +32,13 @@ PROPERTY_SOURCE(Sketcher::SketchObjectSF, Part::Part2DObject) SketchObjectSF::SketchObjectSF() { - ADD_PROPERTY_TYPE(SketchFlatFile, - (nullptr), - "", - (App::PropertyType)(App::Prop_None), - "SketchFlat file (*.skf) which defines this sketch"); + ADD_PROPERTY_TYPE( + SketchFlatFile, + (nullptr), + "", + (App::PropertyType)(App::Prop_None), + "SketchFlat file (*.skf) which defines this sketch" + ); } short SketchObjectSF::mustExecute() const @@ -51,7 +53,8 @@ App::DocumentObjectExecReturn* SketchObjectSF::execute() { Base::Console().warning( "%s: This feature is deprecated and won't be longer supported in future FreeCAD versions\n", - this->getNameInDocument()); + this->getNameInDocument() + ); // do nothing return App::DocumentObject::StdReturn; } diff --git a/src/Mod/Sketcher/App/SketchPyImp.cpp b/src/Mod/Sketcher/App/SketchPyImp.cpp index 252a9ac571..5e964f2c49 100644 --- a/src/Mod/Sketcher/App/SketchPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchPyImp.cpp @@ -75,8 +75,7 @@ PyObject* SketchPy::addGeometry(PyObject* args) Part::Geometry* geo = static_cast(pcObj)->getGeometryPtr(); return Py::new_reference_to(Py::Long(this->getSketchPtr()->addGeometry(geo))); } - else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) - || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { + else if (PyObject_TypeCheck(pcObj, &(PyList_Type)) || PyObject_TypeCheck(pcObj, &(PyTuple_Type))) { std::vector geoList; Py::Sequence list(pcObj); for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { @@ -155,22 +154,17 @@ PyObject* SketchPy::moveGeometry(PyObject* args) int index1, index2; PyObject* pcObj; int relative = 0; - if (!PyArg_ParseTuple(args, - "iiO!|i", - &index1, - &index2, - &(Base::VectorPy::Type), - &pcObj, - &relative)) { + if (!PyArg_ParseTuple(args, "iiO!|i", &index1, &index2, &(Base::VectorPy::Type), &pcObj, &relative)) { return nullptr; } Base::Vector3d* toPoint = static_cast(pcObj)->getVectorPtr(); return Py::new_reference_to( - Py::Long(getSketchPtr()->moveGeometry(index1, - static_cast(index2), - *toPoint, - (relative > 0)))); + Py::Long( + getSketchPtr() + ->moveGeometry(index1, static_cast(index2), *toPoint, (relative > 0)) + ) + ); } // +++ attributes implementer ++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/src/Mod/Sketcher/App/SolverGeometryExtension.cpp b/src/Mod/Sketcher/App/SolverGeometryExtension.cpp index bce419003a..a46182a9e9 100644 --- a/src/Mod/Sketcher/App/SolverGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/SolverGeometryExtension.cpp @@ -60,8 +60,9 @@ PyObject* SolverGeometryExtension::getPyObject() THROWM(Base::NotImplementedError, "SolverGeometryExtension does not have a Python counterpart"); } -SolverGeometryExtension::PointParameterStatus -SolverGeometryExtension::getPoint(Sketcher::PointPos pos) const +SolverGeometryExtension::PointParameterStatus SolverGeometryExtension::getPoint( + Sketcher::PointPos pos +) const { if (pos == Sketcher::PointPos::start) { return getStartPoint(); @@ -96,8 +97,7 @@ void SolverGeometryExtension::notifyAttachment(Part::Geometry* geo) auto result = edgeParamMap.find(GeometryType); if (result == edgeParamMap.end()) { - THROWM(Base::TypeError, - "SolverGeometryExtension - notifyAttachment - Geometry not supported!!"); + THROWM(Base::TypeError, "SolverGeometryExtension - notifyAttachment - Geometry not supported!!"); } auto nedgeparams = (*result).second; @@ -110,8 +110,10 @@ void SolverGeometryExtension::notifyAttachment(Part::Geometry* geo) void SolverGeometryExtension::ensureType(const Base::Type& type) { if (GeometryType != type) { - THROWM(Base::TypeError, - "SolverGeometryExtension - requested edge parameters do not match underlying type!"); + THROWM( + Base::TypeError, + "SolverGeometryExtension - requested edge parameters do not match underlying type!" + ); } } diff --git a/src/Mod/Sketcher/App/SolverGeometryExtension.h b/src/Mod/Sketcher/App/SolverGeometryExtension.h index 3c3ed9cefc..2eedfd2ecd 100644 --- a/src/Mod/Sketcher/App/SolverGeometryExtension.h +++ b/src/Mod/Sketcher/App/SolverGeometryExtension.h @@ -143,11 +143,11 @@ public: ParameterStatus getStatus() const { - return std::all_of(pstatus.begin(), - pstatus.end(), - [](const auto& v) { - return v == Independent; - }) + return std::all_of( + pstatus.begin(), + pstatus.end(), + [](const auto& v) { return v == Independent; } + ) ? Independent : Dependent; } diff --git a/src/Mod/Sketcher/App/planegcs/Constraints.cpp b/src/Mod/Sketcher/App/planegcs/Constraints.cpp index 63bb44cf91..ed5640619f 100644 --- a/src/Mod/Sketcher/App/planegcs/Constraints.cpp +++ b/src/Mod/Sketcher/App/planegcs/Constraints.cpp @@ -21,7 +21,7 @@ ***************************************************************************/ #ifdef _MSC_VER -#pragma warning(disable : 4251) +# pragma warning(disable : 4251) #endif #include @@ -30,7 +30,7 @@ #include #define DEBUG_DERIVS 0 #if DEBUG_DERIVS -#include +# include #endif #include @@ -140,7 +140,8 @@ double ConstraintEqual::grad(double* param) ConstraintWeightedLinearCombination::ConstraintWeightedLinearCombination( size_t givennumpoles, const std::vector& givenpvec, - const std::vector& givenfactors) + const std::vector& givenfactors +) : factors(givenfactors) , numpoles(givennumpoles) { @@ -209,8 +210,10 @@ double ConstraintWeightedLinearCombination::grad(double* param) // -------------------------------------------------------- // Center of Gravity -ConstraintCenterOfGravity::ConstraintCenterOfGravity(const std::vector& givenpvec, - const std::vector& givenweights) +ConstraintCenterOfGravity::ConstraintCenterOfGravity( + const std::vector& givenpvec, + const std::vector& givenweights +) : weights(givenweights) , numpoints(givenpvec.size() - 1) { @@ -296,10 +299,12 @@ ConstraintSlopeAtBSplineKnot::ConstraintSlopeAtBSplineKnot(BSpline& b, Line& l, factors.resize(numpoles); slopefactors.resize(numpoles); for (size_t i = 0; i < numpoles + 1; ++i) { - tempfactors[i] = b.getLinCombFactor(*(b.knots[knotindex]), - startpole + b.degree, - startpole + i, - b.degree - 1) + tempfactors[i] = b.getLinCombFactor( + *(b.knots[knotindex]), + startpole + b.degree, + startpole + i, + b.degree - 1 + ) / (b.flattenedknots[startpole + b.degree + i] - b.flattenedknots[startpole + i]); } for (size_t i = 0; i < numpoles; ++i) { @@ -477,10 +482,12 @@ double ConstraintSlopeAtBSplineKnot::grad(double* param) // -------------------------------------------------------- // Point On BSpline -ConstraintPointOnBSpline::ConstraintPointOnBSpline(double* point, - double* initparam, - int coordidx, - BSpline& b) +ConstraintPointOnBSpline::ConstraintPointOnBSpline( + double* point, + double* initparam, + int coordidx, + BSpline& b +) : bsp(b) { // This is always going to be true @@ -546,19 +553,11 @@ double ConstraintPointOnBSpline::error() for (size_t i = 0; i < numpoints; ++i) { d[i] = *poleat(i) * *weightat(i); } - sum = BSpline::splineValue(*theparam(), - startpole + bsp.degree, - bsp.degree, - d, - bsp.flattenedknots); + sum = BSpline::splineValue(*theparam(), startpole + bsp.degree, bsp.degree, d, bsp.flattenedknots); for (size_t i = 0; i < numpoints; ++i) { d[i] = *weightat(i); } - wsum = BSpline::splineValue(*theparam(), - startpole + bsp.degree, - bsp.degree, - d, - bsp.flattenedknots); + wsum = BSpline::splineValue(*theparam(), startpole + bsp.degree, bsp.degree, d, bsp.flattenedknots); // TODO: Change the poles as the point moves between pieces @@ -573,11 +572,13 @@ double ConstraintPointOnBSpline::grad(double* gcsparam) for (size_t i = 0; i < numpoints; ++i) { d[i] = *weightat(i); } - double wsum = BSpline::splineValue(*theparam(), - startpole + bsp.degree, - bsp.degree, - d, - bsp.flattenedknots); + double wsum = BSpline::splineValue( + *theparam(), + startpole + bsp.degree, + bsp.degree, + d, + bsp.flattenedknots + ); deriv += wsum; } @@ -585,36 +586,36 @@ double ConstraintPointOnBSpline::grad(double* gcsparam) VEC_D d(numpoints - 1); for (size_t i = 1; i < numpoints; ++i) { d[i - 1] = (*poleat(i) * *weightat(i) - *poleat(i - 1) * *weightat(i - 1)) - / (bsp.flattenedknots[startpole + i + bsp.degree] - - bsp.flattenedknots[startpole + i]); + / (bsp.flattenedknots[startpole + i + bsp.degree] - bsp.flattenedknots[startpole + i]); } - double slopevalue = BSpline::splineValue(*theparam(), - startpole + bsp.degree, - bsp.degree - 1, - d, - bsp.flattenedknots); + double slopevalue = BSpline::splineValue( + *theparam(), + startpole + bsp.degree, + bsp.degree - 1, + d, + bsp.flattenedknots + ); for (size_t i = 1; i < numpoints; ++i) { d[i - 1] = (*weightat(i) - *weightat(i - 1)) - / (bsp.flattenedknots[startpole + i + bsp.degree] - - bsp.flattenedknots[startpole + i]); + / (bsp.flattenedknots[startpole + i + bsp.degree] - bsp.flattenedknots[startpole + i]); } - double wslopevalue = BSpline::splineValue(*theparam(), - startpole + bsp.degree, - bsp.degree - 1, - d, - bsp.flattenedknots); + double wslopevalue = BSpline::splineValue( + *theparam(), + startpole + bsp.degree, + bsp.degree - 1, + d, + bsp.flattenedknots + ); deriv += (*thepoint() * wslopevalue - slopevalue) * bsp.degree; } for (size_t i = 0; i < numpoints; ++i) { if (gcsparam == poleat(i)) { - auto factorsI = - bsp.getLinCombFactor(*theparam(), startpole + bsp.degree, startpole + i); + auto factorsI = bsp.getLinCombFactor(*theparam(), startpole + bsp.degree, startpole + i); deriv += -(*weightat(i) * factorsI); } if (gcsparam == weightat(i)) { - auto factorsI = - bsp.getLinCombFactor(*theparam(), startpole + bsp.degree, startpole + i); + auto factorsI = bsp.getLinCombFactor(*theparam(), startpole + bsp.degree, startpole + i); deriv += (*thepoint() - *poleat(i)) * factorsI; } } @@ -1269,11 +1270,7 @@ ConstraintL2LAngle::ConstraintL2LAngle(Line& l1, Line& l2, double* a) rescale(); } -ConstraintL2LAngle::ConstraintL2LAngle(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - double* a) +ConstraintL2LAngle::ConstraintL2LAngle(Point& l1p1, Point& l1p2, Point& l2p1, Point& l2p2, double* a) { pvec.push_back(l1p1.x); pvec.push_back(l1p1.y); @@ -1391,10 +1388,7 @@ ConstraintMidpointOnLine::ConstraintMidpointOnLine(Line& l1, Line& l2) rescale(); } -ConstraintMidpointOnLine::ConstraintMidpointOnLine(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2) +ConstraintMidpointOnLine::ConstraintMidpointOnLine(Point& l1p1, Point& l1p2, Point& l2p1, Point& l2p2) { pvec.push_back(l1p1.x); pvec.push_back(l1p1.y); @@ -1471,11 +1465,13 @@ double ConstraintMidpointOnLine::grad(double* param) // -------------------------------------------------------- // TangentCircumf -ConstraintTangentCircumf::ConstraintTangentCircumf(Point& p1, - Point& p2, - double* rad1, - double* rad2, - bool internal_) +ConstraintTangentCircumf::ConstraintTangentCircumf( + Point& p1, + Point& p2, + double* rad1, + double* rad2, + bool internal_ +) : internal(internal_) { @@ -1732,7 +1728,8 @@ void ConstraintEllipseTangentLine::errorgrad(double* err, double* grad, double* ConstraintInternalAlignmentPoint2Ellipse::ConstraintInternalAlignmentPoint2Ellipse( Ellipse& e, Point& p1, - InternalAlignmentType alignmentType) + InternalAlignmentType alignmentType +) : e(e) , p(p1) , AlignmentType(alignmentType) @@ -1781,9 +1778,9 @@ void ConstraintInternalAlignmentPoint2Ellipse::errorgrad(double* err, double* gr double a, da; a = e.getRadMaj(c, f1, b, db, da); - DeriVector2 poa; // point to align to - bool by_y_not_by_x = - false; // a flag to indicate if the alignment error function is for y (false - x, true - y) + DeriVector2 poa; // point to align to + bool by_y_not_by_x = false; // a flag to indicate if the alignment error function is for y + // (false - x, true - y) switch (AlignmentType) { case EllipsePositiveMajorX: @@ -1829,7 +1826,8 @@ void ConstraintInternalAlignmentPoint2Ellipse::errorgrad(double* err, double* gr ConstraintInternalAlignmentPoint2Hyperbola::ConstraintInternalAlignmentPoint2Hyperbola( Hyperbola& e, Point& p1, - InternalAlignmentType alignmentType) + InternalAlignmentType alignmentType +) : e(e) , p(p1) , AlignmentType(alignmentType) @@ -1879,9 +1877,9 @@ void ConstraintInternalAlignmentPoint2Hyperbola::errorgrad(double* err, double* double a, da; a = e.getRadMaj(c, f1, b, db, da); - DeriVector2 poa; // point to align to - bool by_y_not_by_x = - false; // a flag to indicate if the alignment error function is for y (false - x, true - y) + DeriVector2 poa; // point to align to + bool by_y_not_by_x = false; // a flag to indicate if the alignment error function is for y + // (false - x, true - y) switch (AlignmentType) { case HyperbolaPositiveMajorX: @@ -1928,8 +1926,7 @@ void ConstraintInternalAlignmentPoint2Hyperbola::errorgrad(double* err, double* // -------------------------------------------------------- // ConstraintEqualMajorAxesEllipse -ConstraintEqualMajorAxesConic::ConstraintEqualMajorAxesConic(MajorRadiusConic* a1, - MajorRadiusConic* a2) +ConstraintEqualMajorAxesConic::ConstraintEqualMajorAxesConic(MajorRadiusConic* a1, MajorRadiusConic* a2) : e1(a1) , e2(a2) { @@ -2400,11 +2397,13 @@ double ConstraintAngleViaPoint::grad(double* param) // -------------------------------------------------------- // ConstraintAngleViaTwoPoints -ConstraintAngleViaTwoPoints::ConstraintAngleViaTwoPoints(Curve& acrv1, - Curve& acrv2, - Point p1, - Point p2, - double* angle) +ConstraintAngleViaTwoPoints::ConstraintAngleViaTwoPoints( + Curve& acrv1, + Curve& acrv2, + Point p1, + Point p2, + double* angle +) : crv1(acrv1.Copy()) , crv2(acrv2.Copy()) { @@ -2497,11 +2496,13 @@ double ConstraintAngleViaTwoPoints::grad(double* param) // -------------------------------------------------------- // ConstraintAngleViaPointAndParam -ConstraintAngleViaPointAndParam::ConstraintAngleViaPointAndParam(Curve& acrv1, - Curve& acrv2, - Point p, - double* cparam, - double* angle) +ConstraintAngleViaPointAndParam::ConstraintAngleViaPointAndParam( + Curve& acrv1, + Curve& acrv2, + Point p, + double* cparam, + double* angle +) : crv1(acrv1.Copy()) , crv2(acrv2.Copy()) { @@ -2590,12 +2591,14 @@ double ConstraintAngleViaPointAndParam::grad(double* param) // -------------------------------------------------------- // ConstraintAngleViaPointAndTwoParams -ConstraintAngleViaPointAndTwoParams::ConstraintAngleViaPointAndTwoParams(Curve& acrv1, - Curve& acrv2, - Point p, - double* cparam1, - double* cparam2, - double* angle) +ConstraintAngleViaPointAndTwoParams::ConstraintAngleViaPointAndTwoParams( + Curve& acrv1, + Curve& acrv2, + Point p, + double* cparam1, + double* cparam2, + double* angle +) : crv1(acrv1.Copy()) , crv2(acrv2.Copy()) { @@ -2687,14 +2690,16 @@ double ConstraintAngleViaPointAndTwoParams::grad(double* param) // -------------------------------------------------------- // ConstraintSnell -ConstraintSnell::ConstraintSnell(Curve& r1, - Curve& r2, - Curve& b, - Point p, - double* n1, - double* n2, - bool flipn1, - bool flipn2) +ConstraintSnell::ConstraintSnell( + Curve& r1, + Curve& r2, + Curve& b, + Point p, + double* n1, + double* n2, + bool flipn1, + bool flipn2 +) : ray1(r1.Copy()) , ray2(r2.Copy()) , boundary(b.Copy()) diff --git a/src/Mod/Sketcher/App/planegcs/Constraints.h b/src/Mod/Sketcher/App/planegcs/Constraints.h index e9512e51e9..d696daedeb 100644 --- a/src/Mod/Sketcher/App/planegcs/Constraints.h +++ b/src/Mod/Sketcher/App/planegcs/Constraints.h @@ -31,9 +31,9 @@ // #define _GCS_EXTRACT_SOLVER_SUBSYSTEM_ #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ -#define _PROTECTED_UNLESS_EXTRACT_MODE_ public +# define _PROTECTED_UNLESS_EXTRACT_MODE_ public #else -#define _PROTECTED_UNLESS_EXTRACT_MODE_ protected +# define _PROTECTED_UNLESS_EXTRACT_MODE_ protected #endif @@ -246,8 +246,10 @@ public: /// Let `pvec = [q, p_1, p_2,...]`, and /// `givenweights = [f_1, f_2,...]`, then this constraint ensures /// `q = sum(p_i*f_i)`. - ConstraintCenterOfGravity(const std::vector& givenpvec, - const std::vector& givenweights); + ConstraintCenterOfGravity( + const std::vector& givenpvec, + const std::vector& givenweights + ); ConstraintType getTypeId() override; double error() override; double grad(double*) override; @@ -286,9 +288,11 @@ public: /// In that case, `q` is the x (or y) coordinate of the knot, `p_i` are /// the x (or y) coordinates of the poles, and `w_i` are their weights. /// Finally, `f_i` are obtained using `BSpline::getLinCombFactor()`. - ConstraintWeightedLinearCombination(size_t givennumpoints, - const std::vector& givenpvec, - const std::vector& givenfactors); + ConstraintWeightedLinearCombination( + size_t givennumpoints, + const std::vector& givenpvec, + const std::vector& givenfactors + ); ConstraintType getTypeId() override; double error() override; double grad(double*) override; @@ -839,11 +843,7 @@ private: bool internal; public: - ConstraintTangentCircumf(Point& p1, - Point& p2, - double* rd1, - double* rd2, - bool internal_ = false); + ConstraintTangentCircumf(Point& p1, Point& p2, double* rd1, double* rd2, bool internal_ = false); #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ ConstraintTangentCircumf(bool internal_) { @@ -920,9 +920,7 @@ public: class ConstraintInternalAlignmentPoint2Ellipse: public Constraint { public: - ConstraintInternalAlignmentPoint2Ellipse(Ellipse& e, - Point& p1, - InternalAlignmentType alignmentType); + ConstraintInternalAlignmentPoint2Ellipse(Ellipse& e, Point& p1, InternalAlignmentType alignmentType); ConstraintType getTypeId() override; private: @@ -937,9 +935,11 @@ private: class ConstraintInternalAlignmentPoint2Hyperbola: public Constraint { public: - ConstraintInternalAlignmentPoint2Hyperbola(Hyperbola& e, - Point& p1, - InternalAlignmentType alignmentType); + ConstraintInternalAlignmentPoint2Hyperbola( + Hyperbola& e, + Point& p1, + InternalAlignmentType alignmentType + ); ConstraintType getTypeId() override; private: @@ -1176,14 +1176,16 @@ private: public: // n1dn2 = n1 divided by n2. from n1 to n2. flipn1 = true instructs to flip ray1's tangent - ConstraintSnell(Curve& ray1, - Curve& ray2, - Curve& boundary, - Point p, - double* n1, - double* n2, - bool flipn1, - bool flipn2); + ConstraintSnell( + Curve& ray1, + Curve& ray2, + Curve& boundary, + Point p, + double* n1, + double* n2, + bool flipn1, + bool flipn2 + ); ~ConstraintSnell() override; ConstraintType getTypeId() override; }; @@ -1212,15 +1214,10 @@ private: Point poa; // poa=point of angle //needs to be reconstructed if pvec was redirected/reverted. // The point is easily shallow-copied by C++, so no pointer type here and no delete // is necessary. - void - ReconstructGeomPointers(); // writes pointers in pvec to the parameters of crv1, crv2 and poa + void ReconstructGeomPointers(); // writes pointers in pvec to the parameters of crv1, crv2 and poa public: // We assume first curve needs param1 - ConstraintAngleViaPointAndParam(Curve& acrv1, - Curve& acrv2, - Point p, - double* param1, - double* angle); + ConstraintAngleViaPointAndParam(Curve& acrv1, Curve& acrv2, Point p, double* param1, double* angle); ~ConstraintAngleViaPointAndParam() override; ConstraintType getTypeId() override; double error() override; @@ -1256,15 +1253,16 @@ private: Point poa; // poa=point of angle //needs to be reconstructed if pvec was redirected/reverted. // The point is easily shallow-copied by C++, so no pointer type here and no delete // is necessary. - void - ReconstructGeomPointers(); // writes pointers in pvec to the parameters of crv1, crv2 and poa + void ReconstructGeomPointers(); // writes pointers in pvec to the parameters of crv1, crv2 and poa public: - ConstraintAngleViaPointAndTwoParams(Curve& acrv1, - Curve& acrv2, - Point p, - double* param1, - double* param2, - double* angle); + ConstraintAngleViaPointAndTwoParams( + Curve& acrv1, + Curve& acrv2, + Point p, + double* param1, + double* param2, + double* angle + ); ~ConstraintAngleViaPointAndTwoParams() override; ConstraintType getTypeId() override; double error() override; diff --git a/src/Mod/Sketcher/App/planegcs/GCS.cpp b/src/Mod/Sketcher/App/planegcs/GCS.cpp index 93fbe53310..fc28de328b 100644 --- a/src/Mod/Sketcher/App/planegcs/GCS.cpp +++ b/src/Mod/Sketcher/App/planegcs/GCS.cpp @@ -21,9 +21,9 @@ ***************************************************************************/ #ifdef _MSC_VER -#pragma warning(disable : 4251) -#pragma warning(disable : 4244) -#pragma warning(disable : 4996) +# pragma warning(disable : 4251) +# pragma warning(disable : 4244) +# pragma warning(disable : 4996) #endif #undef _GCS_DEBUG @@ -33,7 +33,7 @@ // This has to be included BEFORE any EIGEN include // This format is Sage compatible, so you can just copy/paste the matrix into Sage #ifdef _GCS_DEBUG -#define EIGEN_DEFAULT_IO_FORMAT Eigen::IOFormat(3, 0, ",", ",\n", "[", "]", "[", "]") +# define EIGEN_DEFAULT_IO_FORMAT Eigen::IOFormat(3, 0, ",", ",\n", "[", "]", "[", "]") /* Parameters: * * StreamPrecision, @@ -64,9 +64,9 @@ // Extraction of Q matrix for Debugging used to crash #ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX -#if EIGEN_VERSION >= 30304 -#define SPARSE_Q_MATRIX -#endif +# if EIGEN_VERSION >= 30304 +# define SPARSE_Q_MATRIX +# endif #endif #if EIGEN_VERSION > 30290 // This regulates that only starting in Eigen 3.3, the problem with @@ -74,25 +74,25 @@ // was solved in Eigen: // https://forum.freecad.org/viewtopic.php?f=10&t=12769&start=60#p106492 // https://forum.kde.org/viewtopic.php?f=74&t=129439 -#define EIGEN_STOCK_FULLPIVLU_COMPUTE +# define EIGEN_STOCK_FULLPIVLU_COMPUTE #endif // #undef EIGEN_SPARSEQR_COMPATIBLE #ifdef EIGEN_SPARSEQR_COMPATIBLE -#include +# include #endif // _GCS_EXTRACT_SOLVER_SUBSYSTEM_ to be enabled in Constraints.h when needed. #if defined(_GCS_EXTRACT_SOLVER_SUBSYSTEM_) || defined(_DEBUG_TO_FILE) -#include +# include -#define CASE_NOT_IMP(X) \ - case X: { \ - subsystemfile << "//" #X "not yet implemented" << std::endl; \ - break; \ - } +# define CASE_NOT_IMP(X) \ + case X: { \ + subsystemfile << "//" #X "not yet implemented" << std::endl; \ + break; \ + } #endif #include @@ -191,8 +191,8 @@ FullPivLU& FullPivLU::compute(const MatrixdType& matri m_lu.col(k).tail(rows - k - 1) /= m_lu.coeff(k, k); } if (k < size - 1) { - m_lu.block(k + 1, k + 1, rows - k - 1, cols - k - 1).noalias() -= - m_lu.col(k).tail(rows - k - 1) * m_lu.row(k).tail(cols - k - 1); + m_lu.block(k + 1, k + 1, rows - k - 1, cols - k - 1).noalias() + -= m_lu.col(k).tail(rows - k - 1) * m_lu.row(k).tail(cols - k - 1); } } @@ -235,16 +235,14 @@ public: inline void LogToFile(const std::string& str); - void LogQRSystemInformation(const System& system, - int paramsNum = 0, - int constrNum = 0, - int rank = 0); + void LogQRSystemInformation(const System& system, int paramsNum = 0, int constrNum = 0, int rank = 0); - void LogGroupOfConstraints(const std::string& str, - std::vector> constraintgroups); + void LogGroupOfConstraints( + const std::string& str, + std::vector> constraintgroups + ); void LogSetOfConstraints(const std::string& str, std::set constraintset); - void LogGroupOfParameters(const std::string& str, - std::vector> parametergroups); + void LogGroupOfParameters(const std::string& str, std::vector> parametergroups); void LogMatrix(const std::string str, Eigen::MatrixXd matrix); void LogMatrix(const std::string str, MatrixIndexType matrix); @@ -328,17 +326,20 @@ void SolverReportingManager::LogString(const std::string& str) #endif } -void SolverReportingManager::LogQRSystemInformation(const System& system, - int paramsNum, - int constrNum, - int rank) +void SolverReportingManager::LogQRSystemInformation( + const System& system, + int paramsNum, + int constrNum, + int rank +) { std::stringstream tempstream; - tempstream << (system.qrAlgorithm == EigenSparseQR - ? "EigenSparseQR" - : (system.qrAlgorithm == EigenDenseQR ? "DenseQR" : "")); + tempstream + << (system.qrAlgorithm == EigenSparseQR + ? "EigenSparseQR" + : (system.qrAlgorithm == EigenDenseQR ? "DenseQR" : "")); if (paramsNum > 0) { tempstream @@ -367,7 +368,8 @@ void SolverReportingManager::LogQRSystemInformation(const System& system, void SolverReportingManager::LogGroupOfConstraints( const std::string& str, - std::vector> constraintgroups) + std::vector> constraintgroups +) { std::stringstream tempstream; @@ -386,8 +388,10 @@ void SolverReportingManager::LogGroupOfConstraints( LogString(tempstream.str()); } -void SolverReportingManager::LogSetOfConstraints(const std::string& str, - std::set constraintset) +void SolverReportingManager::LogSetOfConstraints( + const std::string& str, + std::set constraintset +) { std::stringstream tempstream; @@ -402,8 +406,10 @@ void SolverReportingManager::LogSetOfConstraints(const std::string& str, LogString(tempstream.str()); } -void SolverReportingManager::LogGroupOfParameters(const std::string& str, - std::vector> parametergroups) +void SolverReportingManager::LogGroupOfParameters( + const std::string& str, + std::vector> parametergroups +) { std::stringstream tempstream; @@ -591,11 +597,13 @@ void System::removeConstraint(Constraint* constr) // basic constraints -int System::addConstraintEqual(double* param1, - double* param2, - int tagId, - bool driving, - Constraint::Alignment internalalignment) +int System::addConstraintEqual( + double* param1, + double* param2, + int tagId, + bool driving, + Constraint::Alignment internalalignment +) { Constraint* constr = new ConstraintEqual(param1, param2); constr->setTag(tagId); @@ -604,11 +612,7 @@ int System::addConstraintEqual(double* param1, return addConstraint(constr); } -int System::addConstraintProportional(double* param1, - double* param2, - double ratio, - int tagId, - bool driving) +int System::addConstraintProportional(double* param1, double* param2, double ratio, int tagId, bool driving) { Constraint* constr = new ConstraintEqual(param1, param2, ratio); constr->setTag(tagId); @@ -616,11 +620,7 @@ int System::addConstraintProportional(double* param1, return addConstraint(constr); } -int System::addConstraintDifference(double* param1, - double* param2, - double* difference, - int tagId, - bool driving) +int System::addConstraintDifference(double* param1, double* param2, double* difference, int tagId, bool driving) { Constraint* constr = new ConstraintDifference(param1, param2, difference); constr->setTag(tagId); @@ -628,11 +628,7 @@ int System::addConstraintDifference(double* param1, return addConstraint(constr); } -int System::addConstraintP2PDistance(Point& p1, - Point& p2, - double* distance, - int tagId, - bool driving) +int System::addConstraintP2PDistance(Point& p1, Point& p2, double* distance, int tagId, bool driving) { Constraint* constr = new ConstraintP2PDistance(p1, p2, distance); constr->setTag(tagId); @@ -640,12 +636,7 @@ int System::addConstraintP2PDistance(Point& p1, return addConstraint(constr); } -int System::addConstraintP2PAngle(Point& p1, - Point& p2, - double* angle, - double incrAngle, - int tagId, - bool driving) +int System::addConstraintP2PAngle(Point& p1, Point& p2, double* angle, double incrAngle, int tagId, bool driving) { Constraint* constr = new ConstraintP2PAngle(p1, p2, angle, incrAngle); constr->setTag(tagId); @@ -690,11 +681,7 @@ int System::addConstraintPointOnPerpBisector(Point& p, Line& l, int tagId, bool return addConstraint(constr); } -int System::addConstraintPointOnPerpBisector(Point& p, - Point& lp1, - Point& lp2, - int tagId, - bool driving) +int System::addConstraintPointOnPerpBisector(Point& p, Point& lp1, Point& lp2, int tagId, bool driving) { Constraint* constr = new ConstraintPointOnPerpBisector(p, lp1, lp2); constr->setTag(tagId); @@ -718,12 +705,14 @@ int System::addConstraintPerpendicular(Line& l1, Line& l2, int tagId, bool drivi return addConstraint(constr); } -int System::addConstraintPerpendicular(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - int tagId, - bool driving) +int System::addConstraintPerpendicular( + Point& l1p1, + Point& l1p2, + Point& l2p1, + Point& l2p2, + int tagId, + bool driving +) { Constraint* constr = new ConstraintPerpendicular(l1p1, l1p2, l2p1, l2p2); constr->setTag(tagId); @@ -739,13 +728,15 @@ int System::addConstraintL2LAngle(Line& l1, Line& l2, double* angle, int tagId, return addConstraint(constr); } -int System::addConstraintL2LAngle(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - double* angle, - int tagId, - bool driving) +int System::addConstraintL2LAngle( + Point& l1p1, + Point& l1p2, + Point& l2p1, + Point& l2p2, + double* angle, + int tagId, + bool driving +) { Constraint* constr = new ConstraintL2LAngle(l1p1, l1p2, l2p1, l2p2, angle); constr->setTag(tagId); @@ -753,12 +744,7 @@ int System::addConstraintL2LAngle(Point& l1p1, return addConstraint(constr); } -int System::addConstraintAngleViaPoint(Curve& crv1, - Curve& crv2, - Point& p, - double* angle, - int tagId, - bool driving) +int System::addConstraintAngleViaPoint(Curve& crv1, Curve& crv2, Point& p, double* angle, int tagId, bool driving) { Constraint* constr = new ConstraintAngleViaPoint(crv1, crv2, p, angle); constr->setTag(tagId); @@ -766,13 +752,15 @@ int System::addConstraintAngleViaPoint(Curve& crv1, return addConstraint(constr); } -int System::addConstraintAngleViaTwoPoints(Curve& crv1, - Curve& crv2, - Point& p1, - Point& p2, - double* angle, - int tagId, - bool driving) +int System::addConstraintAngleViaTwoPoints( + Curve& crv1, + Curve& crv2, + Point& p1, + Point& p2, + double* angle, + int tagId, + bool driving +) { Constraint* constr = new ConstraintAngleViaTwoPoints(crv1, crv2, p1, p2, angle); constr->setTag(tagId); @@ -780,13 +768,15 @@ int System::addConstraintAngleViaTwoPoints(Curve& crv1, return addConstraint(constr); } -int System::addConstraintAngleViaPointAndParam(Curve& crv1, - Curve& crv2, - Point& p, - double* cparam, - double* angle, - int tagId, - bool driving) +int System::addConstraintAngleViaPointAndParam( + Curve& crv1, + Curve& crv2, + Point& p, + double* cparam, + double* angle, + int tagId, + bool driving +) { Constraint* constr = new ConstraintAngleViaPointAndParam(crv1, crv2, p, cparam, angle); constr->setTag(tagId); @@ -794,17 +784,19 @@ int System::addConstraintAngleViaPointAndParam(Curve& crv1, return addConstraint(constr); } -int System::addConstraintAngleViaPointAndTwoParams(Curve& crv1, - Curve& crv2, - Point& p, - double* cparam1, - double* cparam2, - double* angle, - int tagId, - bool driving) +int System::addConstraintAngleViaPointAndTwoParams( + Curve& crv1, + Curve& crv2, + Point& p, + double* cparam1, + double* cparam2, + double* angle, + int tagId, + bool driving +) { - Constraint* constr = - new ConstraintAngleViaPointAndTwoParams(crv1, crv2, p, cparam1, cparam2, angle); + Constraint* constr + = new ConstraintAngleViaPointAndTwoParams(crv1, crv2, p, cparam1, cparam2, angle); constr->setTag(tagId); constr->setDriving(driving); return addConstraint(constr); @@ -818,12 +810,14 @@ int System::addConstraintMidpointOnLine(Line& l1, Line& l2, int tagId, bool driv return addConstraint(constr); } -int System::addConstraintMidpointOnLine(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - int tagId, - bool driving) +int System::addConstraintMidpointOnLine( + Point& l1p1, + Point& l1p2, + Point& l2p1, + Point& l2p2, + int tagId, + bool driving +) { Constraint* constr = new ConstraintMidpointOnLine(l1p1, l1p2, l2p1, l2p2); constr->setTag(tagId); @@ -831,13 +825,15 @@ int System::addConstraintMidpointOnLine(Point& l1p1, return addConstraint(constr); } -int System::addConstraintTangentCircumf(Point& p1, - Point& p2, - double* rad1, - double* rad2, - bool internal, - int tagId, - bool driving) +int System::addConstraintTangentCircumf( + Point& p1, + Point& p2, + double* rad1, + double* rad2, + bool internal, + int tagId, + bool driving +) { Constraint* constr = new ConstraintTangentCircumf(p1, p2, rad1, rad2, internal); constr->setTag(tagId); @@ -845,11 +841,13 @@ int System::addConstraintTangentCircumf(Point& p1, return addConstraint(constr); } -int System::addConstraintTangentAtBSplineKnot(BSpline& b, - Line& l, - unsigned int knotindex, - int tagId, - bool driving) +int System::addConstraintTangentAtBSplineKnot( + BSpline& b, + Line& l, + unsigned int knotindex, + int tagId, + bool driving +) { Constraint* constr = new ConstraintSlopeAtBSplineKnot(b, l, knotindex); constr->setTag(tagId); @@ -963,11 +961,7 @@ int System::addConstraintPointOnParabolicArc(Point& p, ArcOfParabola& e, int tag return addConstraint(constr); } -int System::addConstraintPointOnBSpline(Point& p, - BSpline& b, - double* pointparam, - int tagId, - bool driving) +int System::addConstraintPointOnBSpline(Point& p, BSpline& b, double* pointparam, int tagId, bool driving) { Constraint* constr = new ConstraintPointOnBSpline(p.x, pointparam, 0, b); constr->setTag(tagId); @@ -1015,11 +1009,7 @@ int System::addConstraintPointOnArc(Point& p, Arc& a, int tagId, bool driving) return addConstraintP2PDistance(p, a.center, a.rad, tagId, driving); } -int System::addConstraintPerpendicularLine2Arc(Point& p1, - Point& p2, - Arc& a, - int tagId, - bool driving) +int System::addConstraintPerpendicularLine2Arc(Point& p1, Point& p2, Arc& a, int tagId, bool driving) { using std::numbers::pi; @@ -1034,11 +1024,7 @@ int System::addConstraintPerpendicularLine2Arc(Point& p1, } } -int System::addConstraintPerpendicularArc2Line(Arc& a, - Point& p1, - Point& p2, - int tagId, - bool driving) +int System::addConstraintPerpendicularArc2Line(Arc& a, Point& p1, Point& p2, int tagId, bool driving) { using std::numbers::pi; @@ -1053,11 +1039,7 @@ int System::addConstraintPerpendicularArc2Line(Arc& a, } } -int System::addConstraintPerpendicularCircle2Arc(Point& center, - double* radius, - Arc& a, - int tagId, - bool driving) +int System::addConstraintPerpendicularCircle2Arc(Point& center, double* radius, Arc& a, int tagId, bool driving) { using std::numbers::pi; @@ -1074,11 +1056,7 @@ int System::addConstraintPerpendicularCircle2Arc(Point& center, } } -int System::addConstraintPerpendicularArc2Circle(Arc& a, - Point& center, - double* radius, - int tagId, - bool driving) +int System::addConstraintPerpendicularArc2Circle(Arc& a, Point& center, double* radius, int tagId, bool driving) { using std::numbers::pi; @@ -1095,12 +1073,14 @@ int System::addConstraintPerpendicularArc2Circle(Arc& a, } } -int System::addConstraintPerpendicularArc2Arc(Arc& a1, - bool reverse1, - Arc& a2, - bool reverse2, - int tagId, - bool driving) +int System::addConstraintPerpendicularArc2Arc( + Arc& a1, + bool reverse1, + Arc& a2, + bool reverse2, + int tagId, + bool driving +) { Point& p1 = reverse1 ? a1.start : a1.end; Point& p2 = reverse2 ? a2.end : a2.start; @@ -1131,13 +1111,15 @@ int System::addConstraintTangent(Circle& c1, Circle& c2, int tagId, bool driving double dx = *(c2.center.x) - *(c1.center.x); double dy = *(c2.center.y) - *(c1.center.y); double d = sqrt(dx * dx + dy * dy); - return addConstraintTangentCircumf(c1.center, - c2.center, - c1.rad, - c2.rad, - (d < *c1.rad || d < *c2.rad), - tagId, - driving); + return addConstraintTangentCircumf( + c1.center, + c2.center, + c1.rad, + c2.rad, + (d < *c1.rad || d < *c2.rad), + tagId, + driving + ); } int System::addConstraintTangent(Arc& a1, Arc& a2, int tagId, bool driving) @@ -1145,13 +1127,15 @@ int System::addConstraintTangent(Arc& a1, Arc& a2, int tagId, bool driving) double dx = *(a2.center.x) - *(a1.center.x); double dy = *(a2.center.y) - *(a1.center.y); double d = sqrt(dx * dx + dy * dy); - return addConstraintTangentCircumf(a1.center, - a2.center, - a1.rad, - a2.rad, - (d < *a1.rad || d < *a2.rad), - tagId, - driving); + return addConstraintTangentCircumf( + a1.center, + a2.center, + a1.rad, + a2.rad, + (d < *a1.rad || d < *a2.rad), + tagId, + driving + ); } int System::addConstraintTangent(Circle& c, Arc& a, int tagId, bool driving) @@ -1159,13 +1143,15 @@ int System::addConstraintTangent(Circle& c, Arc& a, int tagId, bool driving) double dx = *(a.center.x) - *(c.center.x); double dy = *(a.center.y) - *(c.center.y); double d = sqrt(dx * dx + dy * dy); - return addConstraintTangentCircumf(c.center, - a.center, - c.rad, - a.rad, - (d < *c.rad || d < *a.rad), - tagId, - driving); + return addConstraintTangentCircumf( + c.center, + a.center, + c.rad, + a.rad, + (d < *c.rad || d < *a.rad), + tagId, + driving + ); } int System::addConstraintCircleRadius(Circle& c, double* radius, int tagId, bool driving) @@ -1251,16 +1237,18 @@ int System::addConstraintP2PSymmetric(Point& p1, Point& p2, Point& p, int tagId, return addConstraintPointOnLine(p, p1, p2, tagId, driving); } -int System::addConstraintSnellsLaw(Curve& ray1, - Curve& ray2, - Curve& boundary, - Point p, - double* n1, - double* n2, - bool flipn1, - bool flipn2, - int tagId, - bool driving) +int System::addConstraintSnellsLaw( + Curve& ray1, + Curve& ray2, + Curve& boundary, + Point p, + double* n1, + double* n2, + bool flipn1, + bool flipn2, + int tagId, + bool driving +) { Constraint* constr = new ConstraintSnell(ray1, ray2, boundary, p, n1, n2, flipn1, flipn2); constr->setTag(tagId); @@ -1268,11 +1256,13 @@ int System::addConstraintSnellsLaw(Curve& ray1, return addConstraint(constr); } -int System::addConstraintInternalAlignmentPoint2Ellipse(Ellipse& e, - Point& p1, - InternalAlignmentType alignmentType, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentPoint2Ellipse( + Ellipse& e, + Point& p1, + InternalAlignmentType alignmentType, + int tagId, + bool driving +) { Constraint* constr = new ConstraintInternalAlignmentPoint2Ellipse(e, p1, alignmentType); constr->setTag(tagId); @@ -1281,11 +1271,13 @@ int System::addConstraintInternalAlignmentPoint2Ellipse(Ellipse& e, return addConstraint(constr); } -int System::addConstraintInternalAlignmentPoint2Hyperbola(Hyperbola& e, - Point& p1, - InternalAlignmentType alignmentType, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentPoint2Hyperbola( + Hyperbola& e, + Point& p1, + InternalAlignmentType alignmentType, + int tagId, + bool driving +) { Constraint* constr = new ConstraintInternalAlignmentPoint2Hyperbola(e, p1, alignmentType); constr->setTag(tagId); @@ -1294,11 +1286,13 @@ int System::addConstraintInternalAlignmentPoint2Hyperbola(Hyperbola& e, return addConstraint(constr); } -int System::addConstraintInternalAlignmentEllipseMajorDiameter(Ellipse& e, - Point& p1, - Point& p2, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentEllipseMajorDiameter( + Ellipse& e, + Point& p1, + Point& p2, + int tagId, + bool driving +) { double X_1 = *p1.x; double Y_1 = *p1.y; @@ -1310,11 +1304,11 @@ int System::addConstraintInternalAlignmentEllipseMajorDiameter(Ellipse& e, double Y_F1 = *e.focus1.y; double b = *e.radmin; - double closertopositivemajor = - pow(X_1 - X_c - - (X_F1 - X_c) * sqrt(pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) - / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), - 2) + double closertopositivemajor + = pow(X_1 - X_c + - (X_F1 - X_c) * sqrt(pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) + / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), + 2) - pow(X_2 - X_c - (X_F1 - X_c) * sqrt(pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), @@ -1333,30 +1327,24 @@ int System::addConstraintInternalAlignmentEllipseMajorDiameter(Ellipse& e, addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipsePositiveMajorX, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipsePositiveMajorY, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipseNegativeMajorX, tagId, driving); - return addConstraintInternalAlignmentPoint2Ellipse(e, - p1, - EllipseNegativeMajorY, - tagId, - driving); + return addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipseNegativeMajorY, tagId, driving); } else { // p1 is closer to positivemajor addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipsePositiveMajorX, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipsePositiveMajorY, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipseNegativeMajorX, tagId, driving); - return addConstraintInternalAlignmentPoint2Ellipse(e, - p2, - EllipseNegativeMajorY, - tagId, - driving); + return addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipseNegativeMajorY, tagId, driving); } } -int System::addConstraintInternalAlignmentEllipseMinorDiameter(Ellipse& e, - Point& p1, - Point& p2, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentEllipseMinorDiameter( + Ellipse& e, + Point& p1, + Point& p2, + int tagId, + bool driving +) { double X_1 = *p1.x; double Y_1 = *p1.y; @@ -1368,8 +1356,8 @@ int System::addConstraintInternalAlignmentEllipseMinorDiameter(Ellipse& e, double Y_F1 = *e.focus1.y; double b = *e.radmin; - double closertopositiveminor = - pow(X_1 - X_c + b * (Y_F1 - Y_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), 2) + double closertopositiveminor + = pow(X_1 - X_c + b * (Y_F1 - Y_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), 2) - pow(X_2 - X_c + b * (Y_F1 - Y_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), 2) + pow(-Y_1 + Y_c + b * (X_F1 - X_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), 2) - pow(-Y_2 + Y_c + b * (X_F1 - X_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), 2); @@ -1378,51 +1366,35 @@ int System::addConstraintInternalAlignmentEllipseMinorDiameter(Ellipse& e, addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipsePositiveMinorX, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipsePositiveMinorY, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipseNegativeMinorX, tagId, driving); - return addConstraintInternalAlignmentPoint2Ellipse(e, - p1, - EllipseNegativeMinorY, - tagId, - driving); + return addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipseNegativeMinorY, tagId, driving); } else { addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipsePositiveMinorX, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipsePositiveMinorY, tagId, driving); addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipseNegativeMinorX, tagId, driving); - return addConstraintInternalAlignmentPoint2Ellipse(e, - p2, - EllipseNegativeMinorY, - tagId, - driving); + return addConstraintInternalAlignmentPoint2Ellipse(e, p2, EllipseNegativeMinorY, tagId, driving); } } -int System::addConstraintInternalAlignmentEllipseFocus1(Ellipse& e, - Point& p1, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentEllipseFocus1(Ellipse& e, Point& p1, int tagId, bool driving) { addConstraintEqual(e.focus1.x, p1.x, tagId, driving, Constraint::Alignment::InternalAlignment); - return addConstraintEqual(e.focus1.y, - p1.y, - tagId, - driving, - Constraint::Alignment::InternalAlignment); + return addConstraintEqual(e.focus1.y, p1.y, tagId, driving, Constraint::Alignment::InternalAlignment); } -int System::addConstraintInternalAlignmentEllipseFocus2(Ellipse& e, - Point& p1, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentEllipseFocus2(Ellipse& e, Point& p1, int tagId, bool driving) { addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipseFocus2X, tagId, driving); return addConstraintInternalAlignmentPoint2Ellipse(e, p1, EllipseFocus2Y, tagId, driving); } -int System::addConstraintInternalAlignmentHyperbolaMajorDiameter(Hyperbola& e, - Point& p1, - Point& p2, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentHyperbolaMajorDiameter( + Hyperbola& e, + Point& p1, + Point& p2, + int tagId, + bool driving +) { double X_1 = *p1.x; double Y_1 = *p1.y; @@ -1434,11 +1406,11 @@ int System::addConstraintInternalAlignmentHyperbolaMajorDiameter(Hyperbola& e, double Y_F1 = *e.focus1.y; double b = *e.radmin; - double closertopositivemajor = - pow(-X_1 + X_c - + (X_F1 - X_c) * (-pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) - / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), - 2) + double closertopositivemajor = pow(-X_1 + X_c + + (X_F1 - X_c) + * (-pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) + / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), + 2) - pow(-X_2 + X_c + (X_F1 - X_c) * (-pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), @@ -1454,57 +1426,27 @@ int System::addConstraintInternalAlignmentHyperbolaMajorDiameter(Hyperbola& e, if (closertopositivemajor > 0) { // p2 is closer to positivemajor. Assign constraints back-to-front. - addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaPositiveMajorX, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaPositiveMajorY, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaNegativeMajorX, - tagId, - driving); - return addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaNegativeMajorY, - tagId, - driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaPositiveMajorX, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaPositiveMajorY, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaNegativeMajorX, tagId, driving); + return addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaNegativeMajorY, tagId, driving); } else { // p1 is closer to positivemajor - addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaPositiveMajorX, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaPositiveMajorY, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaNegativeMajorX, - tagId, - driving); - return addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaNegativeMajorY, - tagId, - driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaPositiveMajorX, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaPositiveMajorY, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaNegativeMajorX, tagId, driving); + return addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaNegativeMajorY, tagId, driving); } } -int System::addConstraintInternalAlignmentHyperbolaMinorDiameter(Hyperbola& e, - Point& p1, - Point& p2, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentHyperbolaMinorDiameter( + Hyperbola& e, + Point& p1, + Point& p2, + int tagId, + bool driving +) { double X_1 = *p1.x; double Y_1 = *p1.y; @@ -1516,11 +1458,11 @@ int System::addConstraintInternalAlignmentHyperbolaMinorDiameter(Hyperbola& e, double Y_F1 = *e.focus1.y; double b = *e.radmin; - double closertopositiveminor = - pow(-X_1 + X_c + b * (Y_F1 - Y_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) - + (X_F1 - X_c) * (-pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) - / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), - 2) + double closertopositiveminor + = pow(-X_1 + X_c + b * (Y_F1 - Y_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) + + (X_F1 - X_c) * (-pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) + / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), + 2) - pow(-X_2 + X_c + b * (Y_F1 - Y_c) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) + (X_F1 - X_c) * (-pow(b, 2) + pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)) / sqrt(pow(X_F1 - X_c, 2) + pow(Y_F1 - Y_c, 2)), @@ -1535,105 +1477,69 @@ int System::addConstraintInternalAlignmentHyperbolaMinorDiameter(Hyperbola& e, 2); if (closertopositiveminor < 0) { - addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaPositiveMinorX, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaPositiveMinorY, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaNegativeMinorX, - tagId, - driving); - return addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaNegativeMinorY, - tagId, - driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaPositiveMinorX, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaPositiveMinorY, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaNegativeMinorX, tagId, driving); + return addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaNegativeMinorY, tagId, driving); } else { - addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaPositiveMinorX, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p1, - HyperbolaPositiveMinorY, - tagId, - driving); - addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaNegativeMinorX, - tagId, - driving); - return addConstraintInternalAlignmentPoint2Hyperbola(e, - p2, - HyperbolaNegativeMinorY, - tagId, - driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaPositiveMinorX, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p1, HyperbolaPositiveMinorY, tagId, driving); + addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaNegativeMinorX, tagId, driving); + return addConstraintInternalAlignmentPoint2Hyperbola(e, p2, HyperbolaNegativeMinorY, tagId, driving); } } -int System::addConstraintInternalAlignmentHyperbolaFocus(Hyperbola& e, - Point& p1, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentHyperbolaFocus(Hyperbola& e, Point& p1, int tagId, bool driving) { addConstraintEqual(e.focus1.x, p1.x, tagId, driving, Constraint::Alignment::InternalAlignment); - return addConstraintEqual(e.focus1.y, - p1.y, - tagId, - driving, - Constraint::Alignment::InternalAlignment); + return addConstraintEqual(e.focus1.y, p1.y, tagId, driving, Constraint::Alignment::InternalAlignment); } -int System::addConstraintInternalAlignmentParabolaFocus(Parabola& e, - Point& p1, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentParabolaFocus(Parabola& e, Point& p1, int tagId, bool driving) { addConstraintEqual(e.focus1.x, p1.x, tagId, driving, Constraint::Alignment::InternalAlignment); - return addConstraintEqual(e.focus1.y, - p1.y, - tagId, - driving, - Constraint::Alignment::InternalAlignment); + return addConstraintEqual(e.focus1.y, p1.y, tagId, driving, Constraint::Alignment::InternalAlignment); } -int System::addConstraintInternalAlignmentBSplineControlPoint(BSpline& b, - Circle& c, - unsigned int poleindex, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentBSplineControlPoint( + BSpline& b, + Circle& c, + unsigned int poleindex, + int tagId, + bool driving +) { - addConstraintEqual(b.poles[poleindex].x, - c.center.x, - tagId, - driving, - Constraint::Alignment::InternalAlignment); - addConstraintEqual(b.poles[poleindex].y, - c.center.y, - tagId, - driving, - Constraint::Alignment::InternalAlignment); - return addConstraintEqual(b.weights[poleindex], - c.rad, - tagId, - driving, - Constraint::Alignment::InternalAlignment); + addConstraintEqual( + b.poles[poleindex].x, + c.center.x, + tagId, + driving, + Constraint::Alignment::InternalAlignment + ); + addConstraintEqual( + b.poles[poleindex].y, + c.center.y, + tagId, + driving, + Constraint::Alignment::InternalAlignment + ); + return addConstraintEqual( + b.weights[poleindex], + c.rad, + tagId, + driving, + Constraint::Alignment::InternalAlignment + ); } -int System::addConstraintInternalAlignmentKnotPoint(BSpline& b, - Point& p, - unsigned int knotindex, - int tagId, - bool driving) +int System::addConstraintInternalAlignmentKnotPoint( + BSpline& b, + Point& p, + unsigned int knotindex, + int tagId, + bool driving +) { if (b.periodic && knotindex == 0) { // This is done here since knotpoints themselves aren't stored @@ -1679,8 +1585,7 @@ int System::addConstraintInternalAlignmentKnotPoint(BSpline& b, // cleanest way to handle it. if (numpoles > 1) { for (size_t i = 0; i < numpoles; ++i) { - factors[i] = - b.getLinCombFactor(*(b.knots[knotindex]), startpole + b.degree, startpole + i); + factors[i] = b.getLinCombFactor(*(b.knots[knotindex]), startpole + b.degree, startpole + i); } } @@ -1724,28 +1629,26 @@ double System::calculateAngleViaPoint(const Curve& crv1, const Curve& crv2, Poin return calculateAngleViaPoint(crv1, crv2, p, p); } -double -System::calculateAngleViaPoint(const Curve& crv1, const Curve& crv2, Point& p1, Point& p2) const +double System::calculateAngleViaPoint(const Curve& crv1, const Curve& crv2, Point& p1, Point& p2) const { GCS::DeriVector2 n1 = crv1.CalculateNormal(p1); GCS::DeriVector2 n2 = crv2.CalculateNormal(p2); return atan2(-n2.x * n1.y + n2.y * n1.x, n2.x * n1.x + n2.y * n1.y); } -double System::calculateAngleViaParams(const Curve& crv1, - const Curve& crv2, - double* param1, - double* param2) const +double System::calculateAngleViaParams( + const Curve& crv1, + const Curve& crv2, + double* param1, + double* param2 +) const { GCS::DeriVector2 n1 = crv1.CalculateNormal(param1); GCS::DeriVector2 n2 = crv2.CalculateNormal(param2); return atan2(-n2.x * n1.y + n2.y * n1.x, n2.x * n1.x + n2.y * n1.y); } -void System::calculateNormalAtPoint(const Curve& crv, - const Point& p, - double& rtnX, - double& rtnY) const +void System::calculateNormalAtPoint(const Curve& crv, const Point& p, double& rtnX, double& rtnY) const { GCS::DeriVector2 n1 = crv.CalculateNormal(p); rtnX = n1.x; @@ -1923,12 +1826,12 @@ void System::initSolution(Algorithm alg) subSystemsAux.resize(clists.size(), nullptr); for (std::size_t cid = 0; cid < clists.size(); ++cid) { std::vector clist0, clist1; - std::ranges::partition_copy(clists[cid], - std::back_inserter(clist0), - std::back_inserter(clist1), - [](auto constr) { - return constr->getTag() >= 0; - }); + std::ranges::partition_copy( + clists[cid], + std::back_inserter(clist0), + std::back_inserter(clist1), + [](auto constr) { return constr->getTag() >= 0; } + ); if (!clist0.empty()) { subSystems[cid] = new SubSystem(clist0, plists[cid], reductionmaps[cid]); @@ -1984,8 +1887,7 @@ int System::solve(bool isFine, Algorithm alg, bool isRedundantsolving) isReset = true; } if (subSystems[cid] && subSystemsAux[cid]) { - res = std::max(res, - solve(subSystems[cid], subSystemsAux[cid], isFine, isRedundantsolving)); + res = std::max(res, solve(subSystems[cid], subSystemsAux[cid], isFine, isRedundantsolving)); } else if (subSystems[cid]) { res = std::max(res, solve(subSystems[cid], isFine, alg, isRedundantsolving)); @@ -2065,8 +1967,7 @@ int System::solve_BFGS(SubSystem* subsys, bool /*isFine*/, bool isRedundantsolvi int maxIterNumber = (sketchSizeMultiplier ? maxIter * xsize : maxIter); double convCriterion = convergence; if (isRedundantsolving) { - maxIterNumber = - (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant); + maxIterNumber = (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant); convCriterion = convergenceRedundant; } @@ -2189,8 +2090,7 @@ int System::solve_LM(SubSystem* subsys, bool isRedundantsolving) double tau = LM_tau; if (isRedundantsolving) { - maxIterNumber = - (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant); + maxIterNumber = (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant); eps = LM_epsRedundant; eps1 = LM_eps1Redundant; tau = LM_tauRedundant; @@ -2358,8 +2258,7 @@ int System::solve_DL(SubSystem* subsys, bool isRedundantsolving) tolx = DL_tolxRedundant; tolf = DL_tolfRedundant; - maxIterNumber = - (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant); + maxIterNumber = (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant); } if (debugMode == IterationLevel) { @@ -2571,10 +2470,9 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) int ip = 0; - subsystemfile << "GCS::VEC_pD plist_;" << std::endl; // all SYSTEM params - subsystemfile << "std::vector clist_;" - << std::endl; // SUBSYSTEM constraints - subsystemfile << "GCS::VEC_pD plistsub_;" << std::endl; // all SUBSYSTEM params + subsystemfile << "GCS::VEC_pD plist_;" << std::endl; // all SYSTEM params + subsystemfile << "std::vector clist_;" << std::endl; // SUBSYSTEM constraints + subsystemfile << "GCS::VEC_pD plistsub_;" << std::endl; // all SUBSYSTEM params // constraint params not within SYSTEM params subsystemfile << "GCS::VEC_pD clist_params_;" << std::endl; @@ -2844,10 +2742,9 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << std::endl; break; } case P2PAngle: { // 5 @@ -2971,10 +2868,9 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << std::endl; break; } case P2LDistance: { // 7 @@ -3144,11 +3040,10 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << "," << (*it)->pvec[5] << "," << (*it)->pvec[6] - << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << "," << (*it)->pvec[5] + << "," << (*it)->pvec[6] << std::endl; break; } case PointOnLine: { // 6 @@ -3641,11 +3536,10 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << "," << (*it)->pvec[5] << "," << (*it)->pvec[6] - << "," << (*it)->pvec[7] << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << "," << (*it)->pvec[5] + << "," << (*it)->pvec[6] << "," << (*it)->pvec[7] << std::endl; break; } case Perpendicular: { // 8 @@ -3838,11 +3732,10 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << "," << (*it)->pvec[5] << "," << (*it)->pvec[6] - << "," << (*it)->pvec[7] << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << "," << (*it)->pvec[5] + << "," << (*it)->pvec[6] << "," << (*it)->pvec[7] << std::endl; break; } case L2LAngle: { // 9 @@ -4255,11 +4148,10 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << "," << (*it)->pvec[5] << "," << (*it)->pvec[6] - << "," << (*it)->pvec[7] << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << "," << (*it)->pvec[5] + << "," << (*it)->pvec[6] << "," << (*it)->pvec[7] << std::endl; break; } case TangentCircumf: { // 6 @@ -4583,11 +4475,10 @@ void System::extractSubsystem(SubSystem* subsys, bool isRedundantsolving) << "]);" << std::endl; subsystemfile << "c" << ic << "->origpvec=c" << ic << "->pvec;" << std::endl; subsystemfile << "c" << ic << "->rescale();" << std::endl; - subsystemfile << "clist_.push_back(c" << ic - << "); // addresses = " << (*it)->pvec[0] << "," << (*it)->pvec[1] - << "," << (*it)->pvec[2] << "," << (*it)->pvec[3] << "," - << (*it)->pvec[4] << "," << (*it)->pvec[5] << "," << (*it)->pvec[6] - << std::endl; + subsystemfile << "clist_.push_back(c" << ic << "); // addresses = " << (*it)->pvec[0] + << "," << (*it)->pvec[1] << "," << (*it)->pvec[2] << "," + << (*it)->pvec[3] << "," << (*it)->pvec[4] << "," << (*it)->pvec[5] + << "," << (*it)->pvec[6] << std::endl; break; } CASE_NOT_IMP(TangentEllipseLine) @@ -4622,11 +4513,7 @@ int System::solve(SubSystem* subsysA, SubSystem* subsysB, bool /*isFine*/, bool std::sort(plistB.begin(), plistB.end()); VEC_pD::const_iterator it; - it = std::set_union(plistA.begin(), - plistA.end(), - plistB.begin(), - plistB.end(), - plistAB.begin()); + it = std::set_union(plistA.begin(), plistA.end(), plistB.begin(), plistB.end(), plistAB.begin()); plistAB.resize(it - plistAB.begin()); } int xsize = plistAB.size(); @@ -4656,10 +4543,10 @@ int System::solve(SubSystem* subsysA, SubSystem* subsysB, bool /*isFine*/, bool subsysA->calcResidual(resA); // double convergence = isFine ? XconvergenceFine : XconvergenceRough; - int maxIterNumber = - (isRedundantsolving - ? (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant) - : (sketchSizeMultiplier ? maxIter * xsize : maxIter)); + int maxIterNumber + = (isRedundantsolving + ? (sketchSizeMultiplierRedundant ? maxIterRedundant * xsize : maxIterRedundant) + : (sketchSizeMultiplier ? maxIter * xsize : maxIter)); double divergingLim = 1e6 * subsysA->error() + 1e12; @@ -4685,9 +4572,11 @@ int System::solve(SubSystem* subsysA, SubSystem* subsysB, bool /*isFine*/, bool alpha = std::min(alpha, subsysA->maxStep(plistAB, xdir)); // Eq. 18.36 - mu = std::max(mu, - (grad.dot(xdir) + std::max(0., 0.5 * xdir.dot(B * xdir))) - / ((1. - rho) * resA.lpNorm<1>())); + mu = std::max( + mu, + (grad.dot(xdir) + std::max(0., 0.5 * xdir.dot(B * xdir))) + / ((1. - rho) * resA.lpNorm<1>()) + ); // Eq. 18.27 double f0 = subsysB->error() + mu * resA.lpNorm<1>(); @@ -4751,8 +4640,7 @@ int System::solve(SubSystem* subsysA, SubSystem* subsysB, bool /*isFine*/, bool } double err = subsysA->error(); - if (h.norm() <= (isRedundantsolving ? convergenceRedundant : convergence) - && err <= smallF) { + if (h.norm() <= (isRedundantsolving ? convergenceRedundant : convergence) && err <= smallF) { break; } if (err > divergingLim || err != err) { // check for diverging and NaN @@ -4798,10 +4686,12 @@ void System::undoSolution() resetToReference(); } -void System::makeReducedJacobian(Eigen::MatrixXd& J, - std::map& jacobianconstraintmap, - GCS::VEC_pD& pdiagnoselist, - std::map& tagmultiplicity) +void System::makeReducedJacobian( + Eigen::MatrixXd& J, + std::map& jacobianconstraintmap, + GCS::VEC_pD& pdiagnoselist, + std::map& tagmultiplicity +) { // construct specific parameter list for diagonose ignoring driven constraint parameters for (int j = 0; j < int(plist.size()); j++) { @@ -4964,8 +4854,10 @@ int System::diagnose(Algorithm alg) #ifndef EIGEN_SPARSEQR_COMPATIBLE if (qrAlgorithm == EigenSparseQR) { - Base::Console().warning("SparseQR not supported by you current version of Eigen. It " - "requires Eigen 3.2.2 or higher. Falling back to Dense QR\n"); + Base::Console().warning( + "SparseQR not supported by you current version of Eigen. It " + "requires Eigen 3.2.2 or higher. Falling back to Dense QR\n" + ); qrAlgorithm = EigenDenseQR; } #endif @@ -4997,12 +4889,14 @@ int System::diagnose(Algorithm alg) // // identifyDependentParametersDenseQR(J, jacobianconstraintmap, pdiagnoselist, true) // - auto fut = std::async(&System::identifyDependentParametersDenseQR, - this, - J, - jacobianconstraintmap, - pdiagnoselist, - true); + auto fut = std::async( + &System::identifyDependentParametersDenseQR, + this, + J, + jacobianconstraintmap, + pdiagnoselist, + true + ); makeDenseQRDecomposition(J, jacobianconstraintmap, qrJT, rank, R); @@ -5023,15 +4917,17 @@ int System::diagnose(Algorithm alg) if (constrNum > rank) { // conflicting or redundant constraints int nonredundantconstrNum; - identifyConflictingRedundantConstraints(alg, - qrJT, - jacobianconstraintmap, - tagmultiplicity, - pdiagnoselist, - R, - constrNum, - rank, - nonredundantconstrNum); + identifyConflictingRedundantConstraints( + alg, + qrJT, + jacobianconstraintmap, + tagmultiplicity, + pdiagnoselist, + R, + constrNum, + rank, + nonredundantconstrNum + ); if (paramsNum == rank && nonredundantconstrNum > rank) { // over-constrained dofs = paramsNum - nonredundantconstrNum; } @@ -5048,9 +4944,9 @@ int System::diagnose(Algorithm alg) #ifdef EIGEN_SPARSEQR_COMPATIBLE else if (qrAlgorithm == EigenSparseQR) { -#ifdef PROFILE_DIAGNOSE +# ifdef PROFILE_DIAGNOSE Base::TimeElapsed SparseQR_start_time; -#endif +# endif int rank = 0; Eigen::MatrixXd R; Eigen::SparseQR, Eigen::COLAMDOrdering> SqrJT; @@ -5070,20 +4966,24 @@ int System::diagnose(Algorithm alg) // auto fut = // std::async(std::launch::deferred,&System::identifyDependentParametersSparseQR, this, // J, jacobianconstraintmap, pdiagnoselist, false); - auto fut = std::async(&System::identifyDependentParametersSparseQR, - this, - J, - jacobianconstraintmap, - pdiagnoselist, - /*silent=*/true); + auto fut = std::async( + &System::identifyDependentParametersSparseQR, + this, + J, + jacobianconstraintmap, + pdiagnoselist, + /*silent=*/true + ); - makeSparseQRDecomposition(J, - jacobianconstraintmap, - SqrJT, - rank, - R, - /*transposed=*/true, - /*silent=*/false); + makeSparseQRDecomposition( + J, + jacobianconstraintmap, + SqrJT, + rank, + R, + /*transposed=*/true, + /*silent=*/false + ); int paramsNum = SqrJT.rows(); int constrNum = SqrJT.cols(); @@ -5096,15 +4996,17 @@ int System::diagnose(Algorithm alg) if (constrNum > rank) { int nonredundantconstrNum; - identifyConflictingRedundantConstraints(alg, - SqrJT, - jacobianconstraintmap, - tagmultiplicity, - pdiagnoselist, - R, - constrNum, - rank, - nonredundantconstrNum); + identifyConflictingRedundantConstraints( + alg, + SqrJT, + jacobianconstraintmap, + tagmultiplicity, + pdiagnoselist, + R, + constrNum, + rank, + nonredundantconstrNum + ); if (paramsNum == rank && nonredundantconstrNum > rank) { // over-constrained @@ -5112,26 +5014,28 @@ int System::diagnose(Algorithm alg) } } -#ifdef PROFILE_DIAGNOSE +# ifdef PROFILE_DIAGNOSE Base::TimeElapsed SparseQR_end_time; auto SolveTime = Base::TimeElapsed::diffTimeF(SparseQR_start_time, SparseQR_end_time); Base::Console().log("\nSparseQR - Lapsed Time: %f seconds\n", SolveTime); -#endif +# endif } #endif return dofs; } -void System::makeDenseQRDecomposition(const Eigen::MatrixXd& J, - const std::map& jacobianconstraintmap, - Eigen::FullPivHouseholderQR& qrJT, - int& rank, - Eigen::MatrixXd& R, - bool transposeJ, - bool silent) +void System::makeDenseQRDecomposition( + const Eigen::MatrixXd& J, + const std::map& jacobianconstraintmap, + Eigen::FullPivHouseholderQR& qrJT, + int& rank, + Eigen::MatrixXd& R, + bool transposeJ, + bool silent +) { #ifdef _GCS_DEBUG @@ -5211,7 +5115,8 @@ void System::makeSparseQRDecomposition( int& rank, Eigen::MatrixXd& R, bool transposeJ, - bool silent) + bool silent +) { Eigen::SparseMatrix SJ; @@ -5222,17 +5127,17 @@ void System::makeSparseQRDecomposition( SJ = J.sparseView(); SJ.makeCompressed(); -#ifdef _GCS_DEBUG +# ifdef _GCS_DEBUG if (!silent) { SolverReportingManager::Manager().LogMatrix("J", J); } -#endif +# endif -#ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX +# ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX Eigen::MatrixXd Q; // Obtaining the Q matrix with Sparse QR is buggy, see comments below Eigen::MatrixXd R2; // Intended for a trapezoidal matrix, where R is the top triangular matrix // of the R2 trapezoidal matrix -#endif +# endif // For a transposed J SJG rows are paramsNum and cols are constrNum // For a non-transposed J SJG rows are constrNum and cols are paramsNum @@ -5253,10 +5158,10 @@ void System::makeSparseQRDecomposition( // Do not ask for Q Matrix!! // At Eigen 3.2 still has a bug that this only works for square matrices // if enabled it will crash -#ifdef SPARSE_Q_MATRIX +# ifdef SPARSE_Q_MATRIX Q = SqrJT.matrixQ(); // Q = QS; -#endif +# endif rowsNum = SqrJT.rows(); colsNum = SqrJT.cols(); @@ -5270,9 +5175,9 @@ void System::makeSparseQRDecomposition( R = SqrJT.matrixR().topRows(colsNum).triangularView(); } -#ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX +# ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX R2 = SqrJT.matrixR(); -#endif +# endif } else { rowsNum = SJG.rows(); @@ -5284,25 +5189,27 @@ void System::makeSparseQRDecomposition( SolverReportingManager::Manager().LogQRSystemInformation(*this, rowsNum, colsNum, rank); } -#ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX +# ifdef _GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX if (J.rows() > 0 && !silent) { SolverReportingManager::Manager().LogMatrix("R", R); SolverReportingManager::Manager().LogMatrix("R2", R2); -#ifdef SPARSE_Q_MATRIX +# ifdef SPARSE_Q_MATRIX SolverReportingManager::Manager().LogMatrix("Q", Q); -#endif +# endif } -#endif //_GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX +# endif //_GCS_DEBUG_SOLVER_JACOBIAN_QR_DECOMPOSITION_TRIANGULAR_MATRIX } #endif // EIGEN_SPARSEQR_COMPATIBLE -void System::identifyDependentParametersDenseQR(const Eigen::MatrixXd& J, - const std::map& jacobianconstraintmap, - const GCS::VEC_pD& pdiagnoselist, - bool silent) +void System::identifyDependentParametersDenseQR( + const Eigen::MatrixXd& J, + const std::map& jacobianconstraintmap, + const GCS::VEC_pD& pdiagnoselist, + bool silent +) { Eigen::FullPivHouseholderQR qrJ; Eigen::MatrixXd Rparams; @@ -5315,34 +5222,40 @@ void System::identifyDependentParametersDenseQR(const Eigen::MatrixXd& J, } #ifdef EIGEN_SPARSEQR_COMPATIBLE -void System::identifyDependentParametersSparseQR(const Eigen::MatrixXd& J, - const std::map& jacobianconstraintmap, - const GCS::VEC_pD& pdiagnoselist, - bool silent) +void System::identifyDependentParametersSparseQR( + const Eigen::MatrixXd& J, + const std::map& jacobianconstraintmap, + const GCS::VEC_pD& pdiagnoselist, + bool silent +) { Eigen::SparseQR, Eigen::COLAMDOrdering> SqrJ; Eigen::MatrixXd Rparams; int nontransprank; - makeSparseQRDecomposition(J, - jacobianconstraintmap, - SqrJ, - nontransprank, - Rparams, - false, - true); // do not transpose allow one to diagnose parameters + makeSparseQRDecomposition( + J, + jacobianconstraintmap, + SqrJ, + nontransprank, + Rparams, + false, + true + ); // do not transpose allow one to diagnose parameters identifyDependentParameters(SqrJ, Rparams, nontransprank, pdiagnoselist, silent); } #endif template -void System::identifyDependentParameters(T& qrJ, - Eigen::MatrixXd& Rparams, - int rank, - const GCS::VEC_pD& pdiagnoselist, - bool silent) +void System::identifyDependentParameters( + T& qrJ, + Eigen::MatrixXd& Rparams, + int rank, + const GCS::VEC_pD& pdiagnoselist, + bool silent +) { (void)silent; // silent is only used in debug code, but it is important as Base::Console is not // thread-safe. Removes warning in non Debug mode. @@ -5376,11 +5289,15 @@ void System::identifyDependentParameters(T& qrJ, #ifdef _GCS_DEBUG if (!silent) { - SolverReportingManager::Manager().LogMatrix("PermMatrix", - (Eigen::MatrixXd)qrJ.colsPermutation()); + SolverReportingManager::Manager().LogMatrix( + "PermMatrix", + (Eigen::MatrixXd)qrJ.colsPermutation() + ); - SolverReportingManager::Manager().LogGroupOfParameters("ParameterGroups", - pDependentParametersGroups); + SolverReportingManager::Manager().LogGroupOfParameters( + "ParameterGroups", + pDependentParametersGroups + ); } #endif @@ -5390,7 +5307,8 @@ void System::identifyDependentGeometryParametersInTransposedJacobianDenseQRDecom const Eigen::FullPivHouseholderQR& qrJT, const GCS::VEC_pD& pdiagnoselist, int paramsNum, - int rank) + int rank +) { // DETECTING CONSTRAINT SOLVER PARAMETERS // @@ -5483,8 +5401,8 @@ void System::eliminateNonZerosOverPivotInUpperTriangularMatrix(Eigen::MatrixXd& for (int row = 0; row < i; row++) { if (R(row, i) != 0) { double coef = R(row, i) / R(i, i); - R.block(row, i + 1, 1, R.cols() - i - 1) -= - coef * R.block(i, i + 1, 1, R.cols() - i - 1); + R.block(row, i + 1, 1, R.cols() - i - 1) -= coef + * R.block(i, i + 1, 1, R.cols() - i - 1); R(row, i) = 0; } } @@ -5501,7 +5419,8 @@ void System::identifyConflictingRedundantConstraints( Eigen::MatrixXd& R, int constrNum, int rank, - int& nonredundantconstrNum) + int& nonredundantconstrNum +) { eliminateNonZerosOverPivotInUpperTriangularMatrix(R, rank); @@ -5523,7 +5442,8 @@ void System::identifyConflictingRedundantConstraints( if (debugMode == IterationLevel) { SolverReportingManager::Manager().LogGroupOfConstraints( "Analysing groups of constraints of special interest", - conflictGroups); + conflictGroups + ); } // try to remove the conflicting constraints and solve the @@ -5544,8 +5464,8 @@ void System::identifyConflictingRedundantConstraints( } for (const auto& constr : conflictGroups[i]) { - bool isinternalalignment = - (constr->isInternalAlignment() == Constraint::Alignment::InternalAlignment); + bool isinternalalignment + = (constr->isInternalAlignment() == Constraint::Alignment::InternalAlignment); bool priorityconstraint = (constr->getTag() == 0); if (!priorityconstraint && !isinternalalignment) { // exclude constraints tagged with zero and internal alignment @@ -5584,13 +5504,15 @@ void System::identifyConflictingRedundantConstraints( auto tag1 = pair1.first->getTag(); auto tag2 = pair2.first->getTag(); - return (sizeOfSet2 > sizeOfSet1 // (1) - || (sizeOfSet2 == sizeOfSet1 - && tagmultiplicity.at(tag2) < tagmultiplicity.at(tag1)) // (2) - || (sizeOfSet2 == sizeOfSet1 - && tagmultiplicity.at(tag2) == tagmultiplicity.at(tag1) - && tag2 > tag1)); // (3) - }); + return ( + sizeOfSet2 > sizeOfSet1 // (1) + || (sizeOfSet2 == sizeOfSet1 + && tagmultiplicity.at(tag2) < tagmultiplicity.at(tag1)) // (2) + || (sizeOfSet2 == sizeOfSet1 + && tagmultiplicity.at(tag2) == tagmultiplicity.at(tag1) && tag2 > tag1) + ); // (3) + } + ); Constraint* mostPopular = iterMostPopular->first; int maxPopularity = iterMostPopular->second.size(); @@ -5647,12 +5569,14 @@ void System::identifyConflictingRedundantConstraints( if (res == Success) { subSysTmp->applySolution(); - std::ranges::copy_if(skipped, - std::inserter(redundant, redundant.begin()), - [this](const auto& constr) { - double err = constr->error(); - return (err * err < this->convergenceRedundant); - }); + std::ranges::copy_if( + skipped, + std::inserter(redundant, redundant.begin()), + [this](const auto& constr) { + double err = constr->error(); + return (err * err < this->convergenceRedundant); + } + ); resetToReference(); if (debugMode == Minimal || debugMode == IterationLevel) { @@ -5663,10 +5587,10 @@ void System::identifyConflictingRedundantConstraints( std::vector> conflictGroupsOrig = conflictGroups; conflictGroups.clear(); for (int i = conflictGroupsOrig.size() - 1; i >= 0; i--) { - auto iterRedundantEntry = - std::ranges::find_if(conflictGroupsOrig[i], [this](const auto item) { - return (this->redundant.count(item) > 0); - }); + auto iterRedundantEntry = std::ranges::find_if( + conflictGroupsOrig[i], + [this](const auto item) { return (this->redundant.count(item) > 0); } + ); bool hasRedundant = (iterRedundantEntry != conflictGroupsOrig[i].end()); if (!hasRedundant) { conflictGroups.push_back(conflictGroupsOrig[i]); @@ -5674,10 +5598,12 @@ void System::identifyConflictingRedundantConstraints( } if (debugMode == IterationLevel) { - Base::Console().log("(Partially) Redundant, Group %d, index %d, Tag: %d\n", - i, - iterRedundantEntry - conflictGroupsOrig[i].begin(), - (*iterRedundantEntry)->getTag()); + Base::Console().log( + "(Partially) Redundant, Group %d, index %d, Tag: %d\n", + i, + iterRedundantEntry - conflictGroupsOrig[i].begin(), + (*iterRedundantEntry)->getTag() + ); } constrNum--; @@ -5689,14 +5615,15 @@ void System::identifyConflictingRedundantConstraints( SET_I conflictingTagsSet; for (const auto& cGroup : conflictGroups) { // exclude internal alignment - std::ranges::transform(cGroup, - std::inserter(conflictingTagsSet, conflictingTagsSet.begin()), - [](const auto& constr) { - bool isinternalalignment = - (constr->isInternalAlignment() - == Constraint::Alignment::InternalAlignment); - return (isinternalalignment ? 0 : constr->getTag()); - }); + std::ranges::transform( + cGroup, + std::inserter(conflictingTagsSet, conflictingTagsSet.begin()), + [](const auto& constr) { + bool isinternalalignment + = (constr->isInternalAlignment() == Constraint::Alignment::InternalAlignment); + return (isinternalalignment ? 0 : constr->getTag()); + } + ); } // exclude constraints tagged with zero diff --git a/src/Mod/Sketcher/App/planegcs/GCS.h b/src/Mod/Sketcher/App/planegcs/GCS.h index 440c8d278e..930c227b78 100644 --- a/src/Mod/Sketcher/App/planegcs/GCS.h +++ b/src/Mod/Sketcher/App/planegcs/GCS.h @@ -29,12 +29,12 @@ #include "SubSystem.h" -#define EIGEN_VERSION \ +#define EIGEN_VERSION \ (EIGEN_WORLD_VERSION * 10000 + EIGEN_MAJOR_VERSION * 100 + EIGEN_MINOR_VERSION) #if EIGEN_VERSION >= 30202 -#define EIGEN_SPARSEQR_COMPATIBLE -#include +# define EIGEN_SPARSEQR_COMPATIBLE +# include #endif namespace GCS @@ -147,18 +147,22 @@ private: int solve_LM(SubSystem* subsys, bool isRedundantsolving = false); int solve_DL(SubSystem* subsys, bool isRedundantsolving = false); - void makeReducedJacobian(Eigen::MatrixXd& J, - std::map& jacobianconstraintmap, - GCS::VEC_pD& pdiagnoselist, - std::map& tagmultiplicity); + void makeReducedJacobian( + Eigen::MatrixXd& J, + std::map& jacobianconstraintmap, + GCS::VEC_pD& pdiagnoselist, + std::map& tagmultiplicity + ); - void makeDenseQRDecomposition(const Eigen::MatrixXd& J, - const std::map& jacobianconstraintmap, - Eigen::FullPivHouseholderQR& qrJT, - int& rank, - Eigen::MatrixXd& R, - bool transposeJ = true, - bool silent = false); + void makeDenseQRDecomposition( + const Eigen::MatrixXd& J, + const std::map& jacobianconstraintmap, + Eigen::FullPivHouseholderQR& qrJT, + int& rank, + Eigen::MatrixXd& R, + bool transposeJ = true, + bool silent = false + ); #ifdef EIGEN_SPARSEQR_COMPATIBLE void makeSparseQRDecomposition( @@ -168,7 +172,8 @@ private: int& rank, Eigen::MatrixXd& R, bool transposeJ = true, - bool silent = false); + bool silent = false + ); #endif // This function name is long for a reason: // - Only for DenseQR @@ -177,39 +182,48 @@ private: const Eigen::FullPivHouseholderQR& qrJT, const GCS::VEC_pD& pdiagnoselist, int paramsNum, - int rank); + int rank + ); template - void identifyConflictingRedundantConstraints(Algorithm alg, - const T& qrJT, - const std::map& jacobianconstraintmap, - const std::map& tagmultiplicity, - GCS::VEC_pD& pdiagnoselist, - Eigen::MatrixXd& R, - int constrNum, - int rank, - int& nonredundantconstrNum); + void identifyConflictingRedundantConstraints( + Algorithm alg, + const T& qrJT, + const std::map& jacobianconstraintmap, + const std::map& tagmultiplicity, + GCS::VEC_pD& pdiagnoselist, + Eigen::MatrixXd& R, + int constrNum, + int rank, + int& nonredundantconstrNum + ); void eliminateNonZerosOverPivotInUpperTriangularMatrix(Eigen::MatrixXd& R, int rank); #ifdef EIGEN_SPARSEQR_COMPATIBLE - void identifyDependentParametersSparseQR(const Eigen::MatrixXd& J, - const std::map& jacobianconstraintmap, - const GCS::VEC_pD& pdiagnoselist, - bool silent = true); + void identifyDependentParametersSparseQR( + const Eigen::MatrixXd& J, + const std::map& jacobianconstraintmap, + const GCS::VEC_pD& pdiagnoselist, + bool silent = true + ); #endif - void identifyDependentParametersDenseQR(const Eigen::MatrixXd& J, - const std::map& jacobianconstraintmap, - const GCS::VEC_pD& pdiagnoselist, - bool silent = true); + void identifyDependentParametersDenseQR( + const Eigen::MatrixXd& J, + const std::map& jacobianconstraintmap, + const GCS::VEC_pD& pdiagnoselist, + bool silent = true + ); template - void identifyDependentParameters(T& qrJ, - Eigen::MatrixXd& Rparams, - int rank, - const GCS::VEC_pD& pdiagnoselist, - bool silent = true); + void identifyDependentParameters( + T& qrJ, + Eigen::MatrixXd& Rparams, + int rank, + const GCS::VEC_pD& pdiagnoselist, + bool silent = true + ); #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ void extractSubsystem(SubSystem* subsys, bool isRedundantsolving); @@ -256,108 +270,124 @@ public: double* param2, int tagId = 0, bool driving = true, - Constraint::Alignment internalalignment = Constraint::Alignment::NoInternalAlignment); - int addConstraintProportional(double* param1, - double* param2, - double ratio, - int tagId, - bool driving = true); - int addConstraintDifference(double* param1, - double* param2, - double* difference, - int tagId = 0, - bool driving = true); - int addConstraintP2PDistance(Point& p1, - Point& p2, - double* distance, - int tagId = 0, - bool driving = true); - int addConstraintP2PAngle(Point& p1, - Point& p2, - double* angle, - double incrAngle, - int tagId = 0, - bool driving = true); - int - addConstraintP2PAngle(Point& p1, Point& p2, double* angle, int tagId = 0, bool driving = true); - int addConstraintP2LDistance(Point& p, - Line& l, - double* distance, - int tagId = 0, - bool driving = true); + Constraint::Alignment internalalignment = Constraint::Alignment::NoInternalAlignment + ); + int addConstraintProportional( + double* param1, + double* param2, + double ratio, + int tagId, + bool driving = true + ); + int addConstraintDifference( + double* param1, + double* param2, + double* difference, + int tagId = 0, + bool driving = true + ); + int addConstraintP2PDistance(Point& p1, Point& p2, double* distance, int tagId = 0, bool driving = true); + int addConstraintP2PAngle( + Point& p1, + Point& p2, + double* angle, + double incrAngle, + int tagId = 0, + bool driving = true + ); + int addConstraintP2PAngle(Point& p1, Point& p2, double* angle, int tagId = 0, bool driving = true); + int addConstraintP2LDistance(Point& p, Line& l, double* distance, int tagId = 0, bool driving = true); int addConstraintPointOnLine(Point& p, Line& l, int tagId = 0, bool driving = true); - int - addConstraintPointOnLine(Point& p, Point& lp1, Point& lp2, int tagId = 0, bool driving = true); + int addConstraintPointOnLine(Point& p, Point& lp1, Point& lp2, int tagId = 0, bool driving = true); int addConstraintPointOnPerpBisector(Point& p, Line& l, int tagId = 0, bool driving = true); - int addConstraintPointOnPerpBisector(Point& p, - Point& lp1, - Point& lp2, - int tagId = 0, - bool driving = true); + int addConstraintPointOnPerpBisector( + Point& p, + Point& lp1, + Point& lp2, + int tagId = 0, + bool driving = true + ); int addConstraintParallel(Line& l1, Line& l2, int tagId = 0, bool driving = true); int addConstraintPerpendicular(Line& l1, Line& l2, int tagId = 0, bool driving = true); - int addConstraintPerpendicular(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - int tagId = 0, - bool driving = true); - int - addConstraintL2LAngle(Line& l1, Line& l2, double* angle, int tagId = 0, bool driving = true); - int addConstraintL2LAngle(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - double* angle, - int tagId = 0, - bool driving = true); - int addConstraintAngleViaPoint(Curve& crv1, - Curve& crv2, - Point& p, - double* angle, - int tagId = 0, - bool driving = true); - int addConstraintAngleViaTwoPoints(Curve& crv1, - Curve& crv2, - Point& p1, - Point& p2, - double* angle, - int tagId = 0, - bool driving = true); - int addConstraintAngleViaPointAndParam(Curve& crv1, - Curve& crv2, - Point& p, - double* cparam, - double* angle, - int tagId = 0, - bool driving = true); - int addConstraintAngleViaPointAndTwoParams(Curve& crv1, - Curve& crv2, - Point& p, - double* cparam1, - double* cparam2, - double* angle, - int tagId = 0, - bool driving = true); + int addConstraintPerpendicular( + Point& l1p1, + Point& l1p2, + Point& l2p1, + Point& l2p2, + int tagId = 0, + bool driving = true + ); + int addConstraintL2LAngle(Line& l1, Line& l2, double* angle, int tagId = 0, bool driving = true); + int addConstraintL2LAngle( + Point& l1p1, + Point& l1p2, + Point& l2p1, + Point& l2p2, + double* angle, + int tagId = 0, + bool driving = true + ); + int addConstraintAngleViaPoint( + Curve& crv1, + Curve& crv2, + Point& p, + double* angle, + int tagId = 0, + bool driving = true + ); + int addConstraintAngleViaTwoPoints( + Curve& crv1, + Curve& crv2, + Point& p1, + Point& p2, + double* angle, + int tagId = 0, + bool driving = true + ); + int addConstraintAngleViaPointAndParam( + Curve& crv1, + Curve& crv2, + Point& p, + double* cparam, + double* angle, + int tagId = 0, + bool driving = true + ); + int addConstraintAngleViaPointAndTwoParams( + Curve& crv1, + Curve& crv2, + Point& p, + double* cparam1, + double* cparam2, + double* angle, + int tagId = 0, + bool driving = true + ); int addConstraintMidpointOnLine(Line& l1, Line& l2, int tagId = 0, bool driving = true); - int addConstraintMidpointOnLine(Point& l1p1, - Point& l1p2, - Point& l2p1, - Point& l2p2, - int tagId = 0, - bool driving = true); - int addConstraintTangentCircumf(Point& p1, - Point& p2, - double* rd1, - double* rd2, - bool internal = false, - int tagId = 0, - bool driving = true); - int addConstraintTangentAtBSplineKnot(BSpline& b, - Line& l, - unsigned int knotindex, - int tagId = 0, - bool driving = true); + int addConstraintMidpointOnLine( + Point& l1p1, + Point& l1p2, + Point& l2p1, + Point& l2p2, + int tagId = 0, + bool driving = true + ); + int addConstraintTangentCircumf( + Point& p1, + Point& p2, + double* rd1, + double* rd2, + bool internal = false, + int tagId = 0, + bool driving = true + ); + int addConstraintTangentAtBSplineKnot( + BSpline& b, + Line& l, + unsigned int knotindex, + int tagId = 0, + bool driving = true + ); // derived constraints int addConstraintP2PCoincident(Point& p1, Point& p2, int tagId = 0, bool driving = true); @@ -370,50 +400,44 @@ public: int addConstraintArcRules(Arc& a, int tagId = 0, bool driving = true); int addConstraintPointOnCircle(Point& p, Circle& c, int tagId = 0, bool driving = true); int addConstraintPointOnEllipse(Point& p, Ellipse& e, int tagId = 0, bool driving = true); - int addConstraintPointOnHyperbolicArc(Point& p, - ArcOfHyperbola& e, - int tagId = 0, - bool driving = true); - int addConstraintPointOnParabolicArc(Point& p, - ArcOfParabola& e, - int tagId = 0, - bool driving = true); - int addConstraintPointOnBSpline(Point& p, - BSpline& b, - double* pointparam, - int tagId, - bool driving = true); + int addConstraintPointOnHyperbolicArc(Point& p, ArcOfHyperbola& e, int tagId = 0, bool driving = true); + int addConstraintPointOnParabolicArc(Point& p, ArcOfParabola& e, int tagId = 0, bool driving = true); + int addConstraintPointOnBSpline( + Point& p, + BSpline& b, + double* pointparam, + int tagId, + bool driving = true + ); int addConstraintArcOfEllipseRules(ArcOfEllipse& a, int tagId = 0, bool driving = true); int addConstraintCurveValue(Point& p, Curve& a, double* u, int tagId = 0, bool driving = true); int addConstraintArcOfHyperbolaRules(ArcOfHyperbola& a, int tagId = 0, bool driving = true); int addConstraintArcOfParabolaRules(ArcOfParabola& a, int tagId = 0, bool driving = true); int addConstraintPointOnArc(Point& p, Arc& a, int tagId = 0, bool driving = true); - int addConstraintPerpendicularLine2Arc(Point& p1, - Point& p2, - Arc& a, - int tagId = 0, - bool driving = true); - int addConstraintPerpendicularArc2Line(Arc& a, - Point& p1, - Point& p2, - int tagId = 0, - bool driving = true); - int addConstraintPerpendicularCircle2Arc(Point& center, - double* radius, - Arc& a, - int tagId = 0, - bool driving = true); - int addConstraintPerpendicularArc2Circle(Arc& a, - Point& center, - double* radius, - int tagId = 0, - bool driving = true); - int addConstraintPerpendicularArc2Arc(Arc& a1, - bool reverse1, - Arc& a2, - bool reverse2, - int tagId = 0, - bool driving = true); + int addConstraintPerpendicularLine2Arc(Point& p1, Point& p2, Arc& a, int tagId = 0, bool driving = true); + int addConstraintPerpendicularArc2Line(Arc& a, Point& p1, Point& p2, int tagId = 0, bool driving = true); + int addConstraintPerpendicularCircle2Arc( + Point& center, + double* radius, + Arc& a, + int tagId = 0, + bool driving = true + ); + int addConstraintPerpendicularArc2Circle( + Arc& a, + Point& center, + double* radius, + int tagId = 0, + bool driving = true + ); + int addConstraintPerpendicularArc2Arc( + Arc& a1, + bool reverse1, + Arc& a2, + bool reverse2, + int tagId = 0, + bool driving = true + ); int addConstraintTangent(Line& l, Circle& c, int tagId = 0, bool driving = true); int addConstraintTangent(Line& l, Ellipse& e, int tagId = 0, bool driving = true); int addConstraintTangent(Line& l, Arc& a, int tagId = 0, bool driving = true); @@ -423,111 +447,125 @@ public: int addConstraintCircleRadius(Circle& c, double* radius, int tagId = 0, bool driving = true); int addConstraintArcRadius(Arc& a, double* radius, int tagId = 0, bool driving = true); - int - addConstraintCircleDiameter(Circle& c, double* diameter, int tagId = 0, bool driving = true); + int addConstraintCircleDiameter(Circle& c, double* diameter, int tagId = 0, bool driving = true); int addConstraintArcDiameter(Arc& a, double* diameter, int tagId = 0, bool driving = true); int addConstraintEqualLength(Line& l1, Line& l2, int tagId = 0, bool driving = true); int addConstraintEqualRadius(Circle& c1, Circle& c2, int tagId = 0, bool driving = true); int addConstraintEqualRadii(Ellipse& e1, Ellipse& e2, int tagId = 0, bool driving = true); - int addConstraintEqualRadii(ArcOfHyperbola& a1, - ArcOfHyperbola& a2, - int tagId = 0, - bool driving = true); + int addConstraintEqualRadii(ArcOfHyperbola& a1, ArcOfHyperbola& a2, int tagId = 0, bool driving = true); int addConstraintEqualRadius(Circle& c1, Arc& a2, int tagId = 0, bool driving = true); int addConstraintEqualRadius(Arc& a1, Arc& a2, int tagId = 0, bool driving = true); - int addConstraintEqualFocus(ArcOfParabola& a1, - ArcOfParabola& a2, - int tagId = 0, - bool driving = true); - int - addConstraintP2PSymmetric(Point& p1, Point& p2, Line& l, int tagId = 0, bool driving = true); - int - addConstraintP2PSymmetric(Point& p1, Point& p2, Point& p, int tagId = 0, bool driving = true); - int addConstraintSnellsLaw(Curve& ray1, - Curve& ray2, - Curve& boundary, - Point p, - double* n1, - double* n2, - bool flipn1, - bool flipn2, - int tagId, - bool driving = true); + int addConstraintEqualFocus(ArcOfParabola& a1, ArcOfParabola& a2, int tagId = 0, bool driving = true); + int addConstraintP2PSymmetric(Point& p1, Point& p2, Line& l, int tagId = 0, bool driving = true); + int addConstraintP2PSymmetric(Point& p1, Point& p2, Point& p, int tagId = 0, bool driving = true); + int addConstraintSnellsLaw( + Curve& ray1, + Curve& ray2, + Curve& boundary, + Point p, + double* n1, + double* n2, + bool flipn1, + bool flipn2, + int tagId, + bool driving = true + ); - int - addConstraintC2CDistance(Circle& c1, Circle& c2, double* dist, int tagId, bool driving = true); + int addConstraintC2CDistance(Circle& c1, Circle& c2, double* dist, int tagId, bool driving = true); int addConstraintC2LDistance(Circle& c, Line& l, double* dist, int tagId, bool driving = true); - int addConstraintP2CDistance(Point& p, - Circle& c, - double* distance, - int tagId = 0, - bool driving = true); + int addConstraintP2CDistance(Point& p, Circle& c, double* distance, int tagId = 0, bool driving = true); int addConstraintArcLength(Arc& a, double* dist, int tagId, bool driving = true); // internal alignment constraints - int addConstraintInternalAlignmentPoint2Ellipse(Ellipse& e, - Point& p1, - InternalAlignmentType alignmentType, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentEllipseMajorDiameter(Ellipse& e, - Point& p1, - Point& p2, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentEllipseMinorDiameter(Ellipse& e, - Point& p1, - Point& p2, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentEllipseFocus1(Ellipse& e, - Point& p1, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentEllipseFocus2(Ellipse& e, - Point& p1, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentPoint2Hyperbola(Hyperbola& e, - Point& p1, - InternalAlignmentType alignmentType, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentHyperbolaMajorDiameter(Hyperbola& e, - Point& p1, - Point& p2, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentHyperbolaMinorDiameter(Hyperbola& e, - Point& p1, - Point& p2, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentHyperbolaFocus(Hyperbola& e, - Point& p1, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentParabolaFocus(Parabola& e, - Point& p1, - int tagId = 0, - bool driving = true); - int addConstraintInternalAlignmentBSplineControlPoint(BSpline& b, - Circle& c, - unsigned int poleindex, - int tag = 0, - bool driving = true); - int addConstraintInternalAlignmentKnotPoint(BSpline& b, - Point& p, - unsigned int knotindex, - int tagId = 0, - bool driving = true); + int addConstraintInternalAlignmentPoint2Ellipse( + Ellipse& e, + Point& p1, + InternalAlignmentType alignmentType, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentEllipseMajorDiameter( + Ellipse& e, + Point& p1, + Point& p2, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentEllipseMinorDiameter( + Ellipse& e, + Point& p1, + Point& p2, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentEllipseFocus1( + Ellipse& e, + Point& p1, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentEllipseFocus2( + Ellipse& e, + Point& p1, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentPoint2Hyperbola( + Hyperbola& e, + Point& p1, + InternalAlignmentType alignmentType, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentHyperbolaMajorDiameter( + Hyperbola& e, + Point& p1, + Point& p2, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentHyperbolaMinorDiameter( + Hyperbola& e, + Point& p1, + Point& p2, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentHyperbolaFocus( + Hyperbola& e, + Point& p1, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentParabolaFocus( + Parabola& e, + Point& p1, + int tagId = 0, + bool driving = true + ); + int addConstraintInternalAlignmentBSplineControlPoint( + BSpline& b, + Circle& c, + unsigned int poleindex, + int tag = 0, + bool driving = true + ); + int addConstraintInternalAlignmentKnotPoint( + BSpline& b, + Point& p, + unsigned int knotindex, + int tagId = 0, + bool driving = true + ); double calculateAngleViaPoint(const Curve& crv1, const Curve& crv2, Point& p) const; double calculateAngleViaPoint(const Curve& crv1, const Curve& crv2, Point& p1, Point& p2) const; - double calculateAngleViaParams(const Curve& crv1, - const Curve& crv2, - double* param1, - double* param2) const; + double calculateAngleViaParams( + const Curve& crv1, + const Curve& crv2, + double* param1, + double* param2 + ) const; void calculateNormalAtPoint(const Curve& crv, const Point& p, double& rtnX, double& rtnY) const; // Calculates errors of all constraints which have a tag equal to @@ -544,18 +582,14 @@ public: void initSolution(Algorithm alg = DogLeg); int solve(bool isFine = true, Algorithm alg = DogLeg, bool isRedundantsolving = false); - int solve(VEC_pD& params, - bool isFine = true, - Algorithm alg = DogLeg, - bool isRedundantsolving = false); - int solve(SubSystem* subsys, - bool isFine = true, - Algorithm alg = DogLeg, - bool isRedundantsolving = false); - int solve(SubSystem* subsysA, - SubSystem* subsysB, - bool isFine = true, - bool isRedundantsolving = false); + int solve(VEC_pD& params, bool isFine = true, Algorithm alg = DogLeg, bool isRedundantsolving = false); + int solve( + SubSystem* subsys, + bool isFine = true, + Algorithm alg = DogLeg, + bool isRedundantsolving = false + ); + int solve(SubSystem* subsysA, SubSystem* subsysB, bool isFine = true, bool isRedundantsolving = false); void applySolution(); void undoSolution(); @@ -590,8 +624,7 @@ public: { pdependentparameterlist = pDependentParameters; } - void - getDependentParamsGroups(std::vector>& pdependentparametergroups) const + void getDependentParamsGroups(std::vector>& pdependentparametergroups) const { pdependentparametergroups = pDependentParametersGroups; } diff --git a/src/Mod/Sketcher/App/planegcs/Geo.cpp b/src/Mod/Sketcher/App/planegcs/Geo.cpp index 84fc1e17fd..2ff8399ea7 100644 --- a/src/Mod/Sketcher/App/planegcs/Geo.cpp +++ b/src/Mod/Sketcher/App/planegcs/Geo.cpp @@ -266,11 +266,13 @@ Arc* Arc::Copy() //--------------ellipse // this function is exposed to allow reusing pre-filled derivectors in constraints code -double Ellipse::getRadMaj(const DeriVector2& center, - const DeriVector2& f1, - double b, - double db, - double& ret_dRadMaj) const +double Ellipse::getRadMaj( + const DeriVector2& center, + const DeriVector2& f1, + double b, + double db, + double& ret_dRadMaj +) const { double cf, dcf; cf = f1.subtr(center).length(dcf); @@ -278,8 +280,9 @@ double Ellipse::getRadMaj(const DeriVector2& center, b, cf, db, - dcf); // hack = a nonsense vector to calculate major radius with derivatives, useful just - // because the calculation formula is the same as vector length formula + dcf + ); // hack = a nonsense vector to calculate major radius with derivatives, useful just + // because the calculation formula is the same as vector length formula return hack.length(ret_dRadMaj); } @@ -428,11 +431,13 @@ ArcOfEllipse* ArcOfEllipse::Copy() //---------------hyperbola // this function is exposed to allow reusing pre-filled derivectors in constraints code -double Hyperbola::getRadMaj(const DeriVector2& center, - const DeriVector2& f1, - double b, - double db, - double& ret_dRadMaj) const +double Hyperbola::getRadMaj( + const DeriVector2& center, + const DeriVector2& f1, + double b, + double db, + double& ret_dRadMaj +) const { double cf, dcf; cf = f1.subtr(center).length(dcf); @@ -470,8 +475,8 @@ DeriVector2 Hyperbola::CalculateNormal(const Point& p, const double* derivparam) DeriVector2 f2v = cv.linCombi(2.0, f1v, -1.0); // 2*cv - f1v // pf1, pf2 = vectors from p to focus1,focus2 - DeriVector2 pf1 = f1v.subtr(pv).mult( - -1.0); // <--- differs from ellipse normal calculation code by inverting this vector + DeriVector2 pf1 = f1v.subtr(pv).mult(-1.0); // <--- differs from ellipse normal calculation + // code by inverting this vector DeriVector2 pf2 = f2v.subtr(pv); // return sum of normalized pf2, pf2 @@ -786,15 +791,14 @@ DeriVector2 BSpline::CalculateNormal(const double* param, const double* derivpar double factor = splineValue(*param, startpole + degree, degree, d, flattenedknots); VEC_D sd(numpoints - 1); if (i > 0) { - sd[i - 1] = - 1.0 / (flattenedknots[startpole + i + degree] - flattenedknots[startpole + i]); + sd[i - 1] = 1.0 + / (flattenedknots[startpole + i + degree] - flattenedknots[startpole + i]); } if (i < numpoints - 1) { sd[i] = -1.0 / (flattenedknots[startpole + i + 1 + degree] - flattenedknots[startpole + i + 1]); } - double slopefactor = - splineValue(*param, startpole + degree, degree - 1, sd, flattenedknots); + double slopefactor = splineValue(*param, startpole + degree, degree - 1, sd, flattenedknots); if (derivparam == polexat(i)) { result.dx = *weightat(i) * (wsum * slopefactor - wslopesum * factor); @@ -921,19 +925,23 @@ DeriVector2 BSpline::Value(double u, double /*du*/, const double* /*derivparam*/ } double wslopesum = degree * splineValue(u, startpole + degree, degree - 1, d, flattenedknots); - return {xsum / wsum, - ysum / wsum, - (wsum * xslopesum - wslopesum * xsum) / wsum / wsum, - (wsum * yslopesum - wslopesum * ysum) / wsum / wsum}; + return { + xsum / wsum, + ysum / wsum, + (wsum * xslopesum - wslopesum * xsum) / wsum / wsum, + (wsum * yslopesum - wslopesum * ysum) / wsum / wsum + }; } -void BSpline::valueHomogenous(const double u, - double* xw, - double* yw, - double* w, - double* dxwdu, - double* dywdu, - double* dwdu) const +void BSpline::valueHomogenous( + const double u, + double* xw, + double* yw, + double* w, + double* dxwdu, + double* dywdu, + double* dwdu +) const { // TODO: is there any advantage in making this a `static`? size_t startpole = 0; @@ -1089,8 +1097,8 @@ double BSpline::splineValue(double x, size_t k, unsigned int p, VEC_D& d, const { for (size_t r = 1; r < p + 1; ++r) { for (size_t j = p; j > r - 1; --j) { - double alpha = - (x - flatknots[j + k - p]) / (flatknots[j + 1 + k - r] - flatknots[j + k - p]); + double alpha = (x - flatknots[j + k - p]) + / (flatknots[j + 1 + k - r] - flatknots[j + k - p]); d[j] = (1.0 - alpha) * d[j - 1] + alpha * d[j]; } } diff --git a/src/Mod/Sketcher/App/planegcs/Geo.h b/src/Mod/Sketcher/App/planegcs/Geo.h index f9d326d207..567dac64cb 100644 --- a/src/Mod/Sketcher/App/planegcs/Geo.h +++ b/src/Mod/Sketcher/App/planegcs/Geo.h @@ -28,7 +28,7 @@ #include "../../SketcherGlobal.h" #ifdef _MSC_VER -#pragma warning(disable : 4251) +# pragma warning(disable : 4251) #endif @@ -171,12 +171,10 @@ public: // derivparam is a pointer to a curve parameter (or point coordinate) to // compute the derivative for. The derivative is returned through dx,dy // fields of DeriVector2. - virtual DeriVector2 CalculateNormal(const Point& p, - const double* derivparam = nullptr) const = 0; + virtual DeriVector2 CalculateNormal(const Point& p, const double* derivparam = nullptr) const = 0; // returns normal vector at parameter instead of at the given point. - virtual DeriVector2 CalculateNormal(const double* param, - const double* derivparam = nullptr) const + virtual DeriVector2 CalculateNormal(const double* param, const double* derivparam = nullptr) const { DeriVector2 pointDV = Value(*param, 0.0); Point p(&pointDV.x, &pointDV.y); @@ -244,11 +242,14 @@ public: class SketcherExport MajorRadiusConic: public Curve { public: - virtual double getRadMaj(const DeriVector2& center, - const DeriVector2& f1, - double b, - double db, - double& ret_dRadMaj) const = 0; + virtual double getRadMaj( + const DeriVector2& center, + const DeriVector2& f1, + double b, + double db, + double& ret_dRadMaj + ) const + = 0; virtual double getRadMaj(double* derivparam, double& ret_dRadMaj) const = 0; virtual double getRadMaj() const = 0; // DeriVector2 CalculateNormal(Point &p, double* derivparam = 0) = 0; @@ -260,11 +261,13 @@ public: Point center; Point focus1; double* radmin {nullptr}; - double getRadMaj(const DeriVector2& center, - const DeriVector2& f1, - double b, - double db, - double& ret_dRadMaj) const override; + double getRadMaj( + const DeriVector2& center, + const DeriVector2& f1, + double b, + double db, + double& ret_dRadMaj + ) const override; double getRadMaj(double* derivparam, double& ret_dRadMaj) const override; double getRadMaj() const override; DeriVector2 CalculateNormal(const Point& p, const double* derivparam = nullptr) const override; @@ -296,11 +299,13 @@ public: Point center; Point focus1; double* radmin {nullptr}; - double getRadMaj(const DeriVector2& center, - const DeriVector2& f1, - double b, - double db, - double& ret_dRadMaj) const override; + double getRadMaj( + const DeriVector2& center, + const DeriVector2& f1, + double b, + double db, + double& ret_dRadMaj + ) const override; double getRadMaj(double* derivparam, double& ret_dRadMaj) const override; double getRadMaj() const override; DeriVector2 CalculateNormal(const Point& p, const double* derivparam = nullptr) const override; @@ -372,17 +377,18 @@ public: VEC_D flattenedknots; DeriVector2 CalculateNormal(const Point& p, const double* derivparam = nullptr) const override; // TODO: override parametric version - DeriVector2 CalculateNormal(const double* param, - const double* derivparam = nullptr) const override; + DeriVector2 CalculateNormal(const double* param, const double* derivparam = nullptr) const override; DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; // Returns value in homogeneous coordinates (x*w, y*w, w) at given parameter u - void valueHomogenous(const double u, - double* xw, - double* yw, - double* w, - double* dxwdu, - double* dywdu, - double* dwdu) const; + void valueHomogenous( + const double u, + double* xw, + double* yw, + double* w, + double* dxwdu, + double* dywdu, + double* dwdu + ) const; int PushOwnParams(VEC_pD& pvec) override; void ReconstructOnNewPvec(VEC_pD& pvec, int& cnt) override; BSpline* Copy() override; diff --git a/src/Mod/Sketcher/App/planegcs/SubSystem.cpp b/src/Mod/Sketcher/App/planegcs/SubSystem.cpp index 9d88131681..1ccafbb448 100644 --- a/src/Mod/Sketcher/App/planegcs/SubSystem.cpp +++ b/src/Mod/Sketcher/App/planegcs/SubSystem.cpp @@ -21,7 +21,7 @@ ***************************************************************************/ #ifdef _MSC_VER -#pragma warning(disable : 4251) +# pragma warning(disable : 4251) #endif #include @@ -62,16 +62,11 @@ void SubSystem::initialize(VEC_pD& params, MAP_pD_pD& reductionmap) SET_pD s2; for (std::vector::iterator constr = clist.begin(); constr != clist.end(); ++constr) { - (*constr) - ->revertParams(); // ensure that the constraint points to the original parameters + (*constr)->revertParams(); // ensure that the constraint points to the original parameters VEC_pD constr_params = (*constr)->params(); s2.insert(constr_params.begin(), constr_params.end()); } - std::set_intersection(s1.begin(), - s1.end(), - s2.begin(), - s2.end(), - std::back_inserter(tmpplist)); + std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(tmpplist)); } plist.clear(); @@ -83,8 +78,7 @@ void SubSystem::initialize(VEC_pD& params, MAP_pD_pD& reductionmap) MAP_pD_pD::const_iterator itr = reductionmap.find(*itt); if (itr != reductionmap.end()) { MAP_pD_I::const_iterator itp = pindex.find(itr->second); - if (itp - == pindex.end()) { // the reduction target is not in plist yet, so add it now + if (itp == pindex.end()) { // the reduction target is not in plist yet, so add it now plist.push_back(itr->second); rindex[itr->first] = i; pindex[itr->second] = i; @@ -118,8 +112,7 @@ void SubSystem::initialize(VEC_pD& params, MAP_pD_pD& reductionmap) c2p.clear(); p2c.clear(); - for (std::vector::iterator constr = clist.begin(); constr != clist.end(); - ++constr) { + for (std::vector::iterator constr = clist.begin(); constr != clist.end(); ++constr) { (*constr)->revertParams(); // ensure that the constraint points to the original parameters VEC_pD constr_params_orig = (*constr)->params(); SET_pD constr_params; @@ -147,8 +140,7 @@ void SubSystem::redirectParams() } // redirect constraints to point to pvals - for (std::vector::iterator constr = clist.begin(); constr != clist.end(); - ++constr) { + for (std::vector::iterator constr = clist.begin(); constr != clist.end(); ++constr) { (*constr)->revertParams(); // this line will normally not be necessary (*constr)->redirectParams(pmap); } @@ -156,8 +148,7 @@ void SubSystem::redirectParams() void SubSystem::revertParams() { - for (std::vector::iterator constr = clist.begin(); constr != clist.end(); - ++constr) { + for (std::vector::iterator constr = clist.begin(); constr != clist.end(); ++constr) { (*constr)->revertParams(); } } @@ -312,8 +303,7 @@ double SubSystem::maxStep(VEC_pD& params, Eigen::VectorXd& xdir) } double alpha = 1e10; - for (std::vector::iterator constr = clist.begin(); constr != clist.end(); - ++constr) { + for (std::vector::iterator constr = clist.begin(); constr != clist.end(); ++constr) { alpha = (*constr)->maxStep(dir, alpha); } diff --git a/src/Mod/Sketcher/App/planegcs/qp_eq.cpp b/src/Mod/Sketcher/App/planegcs/qp_eq.cpp index 4cc37c2ce7..ac7fce9a0d 100644 --- a/src/Mod/Sketcher/App/planegcs/qp_eq.cpp +++ b/src/Mod/Sketcher/App/planegcs/qp_eq.cpp @@ -21,7 +21,7 @@ ***************************************************************************/ #ifdef _MSC_VER -#pragma warning(disable : 4244) +# pragma warning(disable : 4244) #endif #include diff --git a/src/Mod/Sketcher/App/planegcs/qp_eq.h b/src/Mod/Sketcher/App/planegcs/qp_eq.h index fdb85c1bc4..965d3bc65a 100644 --- a/src/Mod/Sketcher/App/planegcs/qp_eq.h +++ b/src/Mod/Sketcher/App/planegcs/qp_eq.h @@ -21,10 +21,12 @@ ***************************************************************************/ #include -int qp_eq(Eigen::MatrixXd& H, - Eigen::VectorXd& g, - Eigen::MatrixXd& A, - Eigen::VectorXd& c, - Eigen::VectorXd& x, - Eigen::MatrixXd& Y, - Eigen::MatrixXd& Z); +int qp_eq( + Eigen::MatrixXd& H, + Eigen::VectorXd& g, + Eigen::MatrixXd& A, + Eigen::VectorXd& c, + Eigen::VectorXd& x, + Eigen::MatrixXd& Y, + Eigen::MatrixXd& Z +); diff --git a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp index 3939a488ac..1dec670b91 100644 --- a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp +++ b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp @@ -123,9 +123,11 @@ 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(); @@ -138,13 +140,17 @@ PyMOD_INIT_FUNC(SketcherGui) SketcherGui::ViewProviderSketchGeometryExtension ::init(); (void)new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Sketcher")); + QT_TRANSLATE_NOOP("QObject", "Sketcher") + ); (void)new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Sketcher")); + QT_TRANSLATE_NOOP("QObject", "Sketcher") + ); (void)new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Sketcher")); + QT_TRANSLATE_NOOP("QObject", "Sketcher") + ); (void)new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Sketcher")); + QT_TRANSLATE_NOOP("QObject", "Sketcher") + ); // add resources and reloads the translators loadSketcherResource(); diff --git a/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp b/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp index 6ca501e5ba..70c40e8e31 100644 --- a/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp +++ b/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp @@ -44,8 +44,7 @@ bool isAlterGeoActive(Gui::Document* doc) { if (doc) { // checks if a Sketch Viewprovider is in Edit - if (doc->getInEdit() - && doc->getInEdit()->isDerivedFrom()) { + if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom()) { return true; } } @@ -126,8 +125,7 @@ void CmdSketcherToggleConstruction::updateAction(int mode) act->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_ToggleConstruction")); break; case GeometryCreationMode::Construction: - act->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_ToggleConstruction_Constr")); + act->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_ToggleConstruction_Constr")); break; } } @@ -154,25 +152,28 @@ void CmdSketcherToggleConstruction::activated(int iMsg) { // get the selection std::vector selection; - selection = - getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); + selection = getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); auto* 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 edges from the sketch")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select edges from the sketch") + ); return; } // get the needed lists and objects const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("Select edges from the sketch")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("Select edges from the sketch") + ); return; } diff --git a/src/Mod/Sketcher/Gui/CommandConstraints.h b/src/Mod/Sketcher/Gui/CommandConstraints.h index 4f5de25d9c..ec3aba037f 100644 --- a/src/Mod/Sketcher/Gui/CommandConstraints.h +++ b/src/Mod/Sketcher/Gui/CommandConstraints.h @@ -38,18 +38,17 @@ namespace SketcherGui // These functions are declared here to promote code reuse from other modules /// Makes an angle constraint between 2 lines -void makeAngleBetweenTwoLines(Sketcher::SketchObject* Obj, - Gui::Command* cmd, - int geoId1, - int geoId2); +void makeAngleBetweenTwoLines(Sketcher::SketchObject* Obj, Gui::Command* cmd, int geoId1, int geoId2); // Find the angle between two lines. Return false if geoIds are not lines. -bool calculateAngle(Sketcher::SketchObject* Obj, - int& geoId1, - int& geoId2, - Sketcher::PointPos& PosId1, - Sketcher::PointPos& PosId2, - double& ActAngle); +bool calculateAngle( + Sketcher::SketchObject* Obj, + int& geoId1, + int& geoId2, + Sketcher::PointPos& PosId1, + Sketcher::PointPos& PosId2, + double& ActAngle +); /// Makes a tangency constraint using external construction line between /// ellipse => an ellipse @@ -59,11 +58,13 @@ bool calculateAngle(Sketcher::SketchObject* Obj, /// 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) @@ -72,11 +73,13 @@ void makeTangentToEllipseviaNewPoint(Sketcher::SketchObject* Obj, /// 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 makeTangentToArcOfEllipseviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfEllipse* aoe, - const Part::Geometry* geom2, - int geoId1, - int geoId2); +void makeTangentToArcOfEllipseviaNewPoint( + Sketcher::SketchObject* Obj, + 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 @@ -86,11 +89,13 @@ void makeTangentToArcOfEllipseviaNewPoint(Sketcher::SketchObject* Obj, /// 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 makeTangentToArcOfHyperbolaviaNewPoint(Sketcher::SketchObject* Obj, - const Part::GeomArcOfHyperbola* aoh, - const Part::Geometry* geom2, - int geoId1, - int geoId2); +void makeTangentToArcOfHyperbolaviaNewPoint( + Sketcher::SketchObject* Obj, + 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 @@ -102,24 +107,30 @@ void makeTangentToArcOfHyperbolaviaNewPoint(Sketcher::SketchObject* Obj, /// 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); +void makeTangentToArcOfParabolaviaNewPoint( + Sketcher::SketchObject* Obj, + 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 diff --git a/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp b/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp index f72d5ece38..a076c2e261 100644 --- a/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp +++ b/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp @@ -74,22 +74,22 @@ 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 (static_cast(mode)) { \ - case GeometryCreationMode::Normal: \ - act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON)); \ - break; \ - case GeometryCreationMode::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 (static_cast(mode)) { \ + case GeometryCreationMode::Normal: \ + act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON)); \ + break; \ + case GeometryCreationMode::Construction: \ + act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON "_Constr")); \ + break; \ + } \ + } \ } namespace SketcherGui @@ -168,8 +168,7 @@ public: getAction()->setIcon(al[index]->icon()); break; case GeometryCreationMode::Construction: - al[0]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePolyline_Constr")); + al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePolyline_Constr")); al[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine_Constr")); getAction()->setIcon(al[index]->icon()); break; @@ -228,8 +227,9 @@ CmdSketcherCreatePolyline::CmdSketcherCreatePolyline() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Polyline"); - sToolTipText = - QT_TR_NOOP("Creates a continuous polyline. Press the 'M' key to switch segment modes"); + sToolTipText = QT_TR_NOOP( + "Creates a continuous polyline. Press the 'M' key to switch segment modes" + ); sWhatsThis = "Sketcher_CreatePolyline"; sStatusTip = sToolTipText; sPixmap = "Sketcher_CreatePolyline"; @@ -298,14 +298,16 @@ public: break; case GeometryCreationMode::Construction: al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc_Constr")); - al[1]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc_Constr")); + al[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc_Constr")); al[2]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc_Constr") + ); al[3]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc_Constr") + ); al[4]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateParabolic_Arc_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateParabolic_Arc_Constr") + ); getAction()->setIcon(al[index]->icon()); break; } @@ -375,9 +377,12 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointArc, "Sketcher_Create3PointArc void CmdSketcherCreate3PointArc::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::CircleEllipseConstructionMethod::ThreeRim)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::CircleEllipseConstructionMethod::ThreeRim + ) + ); } bool CmdSketcherCreate3PointArc::isActive() @@ -516,20 +521,21 @@ public: case GeometryCreationMode::Normal: al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle")); al[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle")); - al[2]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); - al[3]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); + al[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); + al[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); getAction()->setIcon(al[index]->icon()); break; case GeometryCreationMode::Construction: al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle_Constr")); al[1]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle_Constr") + ); al[2]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr") + ); al[3]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr") + ); getAction()->setIcon(al[index]->icon()); break; } @@ -598,9 +604,12 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointCircle, "Sketcher_Create3Point void CmdSketcherCreate3PointCircle::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::CircleEllipseConstructionMethod::ThreeRim)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::CircleEllipseConstructionMethod::ThreeRim + ) + ); } bool CmdSketcherCreate3PointCircle::isActive() @@ -670,9 +679,12 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseBy3Points, "Sketcher_CreateEl void CmdSketcherCreateEllipseBy3Points::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::CircleEllipseConstructionMethod::ThreeRim)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::CircleEllipseConstructionMethod::ThreeRim + ) + ); } bool CmdSketcherCreateEllipseBy3Points::isActive() @@ -718,16 +730,15 @@ public: switch (static_cast(mode)) { case GeometryCreationMode::Normal: al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle")); - al[1]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center")); + al[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center")); al[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong")); getAction()->setIcon(al[index]->icon()); break; case GeometryCreationMode::Construction: - al[0]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr")); + al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr")); al[1]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr") + ); al[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong_Constr")); getAction()->setIcon(al[index]->icon()); break; @@ -766,9 +777,12 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangle, "Sketcher_CreateRectangle void CmdSketcherCreateRectangle::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::RectangleConstructionMethod::Diagonal)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::RectangleConstructionMethod::Diagonal + ) + ); } bool CmdSketcherCreateRectangle::isActive() @@ -799,9 +813,12 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangleCenter, "Sketcher_CreateRec void CmdSketcherCreateRectangleCenter::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::RectangleConstructionMethod::CenterAndCorner)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::RectangleConstructionMethod::CenterAndCorner + ) + ); } bool CmdSketcherCreateRectangleCenter::isActive() @@ -833,10 +850,13 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOblong, "Sketcher_CreateOblong") void CmdSketcherCreateOblong::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::RectangleConstructionMethod::Diagonal, - true)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::RectangleConstructionMethod::Diagonal, + true + ) + ); } bool CmdSketcherCreateOblong::isActive() @@ -895,17 +915,15 @@ public: getAction()->setIcon(al[index]->icon()); break; case GeometryCreationMode::Construction: - al[0]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateTriangle_Constr")); + al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateTriangle_Constr")); al[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSquare_Constr")); - al[2]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePentagon_Constr")); + al[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePentagon_Constr")); al[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHexagon_Constr")); - al[4]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHeptagon_Constr")); + al[4]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHeptagon_Constr")); al[5]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOctagon_Constr")); al[6]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRegularPolygon_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRegularPolygon_Constr") + ); getAction()->setIcon(al[index]->icon()); break; } @@ -1133,8 +1151,7 @@ void CmdSketcherCreateRegularPolygon::activated(int iMsg) // Pop-up asking for values SketcherRegularPolygonDialog srpd; if (srpd.exec() == QDialog::Accepted) { - ActivateHandler(getActiveGuiDocument(), - std::make_unique(srpd.sides)); + ActivateHandler(getActiveGuiDocument(), std::make_unique(srpd.sides)); } } @@ -1301,22 +1318,28 @@ public: switch (static_cast(mode)) { case GeometryCreationMode::Normal: al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline")); - al[1]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline")); + al[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline")); al[2]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation")); - al[3]->setIcon(Gui::BitmapFactory().iconFromTheme( - "Sketcher_CreatePeriodicBSplineByInterpolation")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation") + ); + al[3]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePeriodicBSplineByInterpolation") + ); getAction()->setIcon(al[index]->icon()); break; case GeometryCreationMode::Construction: al[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline_Constr")); al[1]->setIcon( - Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline_Constr")); - al[2]->setIcon(Gui::BitmapFactory().iconFromTheme( - "Sketcher_CreateBSplineByInterpolation_Constr")); - al[3]->setIcon(Gui::BitmapFactory().iconFromTheme( - "Sketcher_CreatePeriodicBSplineByInterpolation_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline_Constr") + ); + al[2]->setIcon( + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation_Constr") + ); + al[3]->setIcon( + Gui::BitmapFactory().iconFromTheme( + "Sketcher_CreatePeriodicBSplineByInterpolation_Constr" + ) + ); getAction()->setIcon(al[index]->icon()); break; } @@ -1354,9 +1377,12 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSpline, "Sketcher_CreateBSpline") void CmdSketcherCreateBSpline::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::BSplineConstructionMethod::ControlPoints)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::BSplineConstructionMethod::ControlPoints + ) + ); } bool CmdSketcherCreateBSpline::isActive() @@ -1391,10 +1417,13 @@ CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSpline, "Sketcher_Create_Pe void CmdSketcherCreatePeriodicBSpline::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::BSplineConstructionMethod::ControlPoints, - true)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::BSplineConstructionMethod::ControlPoints, + true + ) + ); } bool CmdSketcherCreatePeriodicBSpline::isActive() @@ -1422,15 +1451,15 @@ CmdSketcherCreateBSplineByInterpolation::CmdSketcherCreateBSplineByInterpolation eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSplineByInterpolation, - "Sketcher_CreateBSplineByInterpolation") +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSplineByInterpolation, "Sketcher_CreateBSplineByInterpolation") void CmdSketcherCreateBSplineByInterpolation::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::BSplineConstructionMethod::Knots)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique(ConstructionMethods::BSplineConstructionMethod::Knots) + ); } bool CmdSketcherCreateBSplineByInterpolation::isActive() @@ -1459,17 +1488,22 @@ CmdSketcherCreatePeriodicBSplineByInterpolation::CmdSketcherCreatePeriodicBSplin eType = ForEdit; } -CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSplineByInterpolation, - "Sketcher_CreatePeriodicBSplineByInterpolation") +CONSTRUCTION_UPDATE_ACTION( + CmdSketcherCreatePeriodicBSplineByInterpolation, + "Sketcher_CreatePeriodicBSplineByInterpolation" +) void CmdSketcherCreatePeriodicBSplineByInterpolation::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::BSplineConstructionMethod::Knots, - true)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique( + ConstructionMethods::BSplineConstructionMethod::Knots, + true + ) + ); } bool CmdSketcherCreatePeriodicBSplineByInterpolation::isActive() @@ -1534,9 +1568,10 @@ CmdSketcherCreateFillet::CmdSketcherCreateFillet() void CmdSketcherCreateFillet::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::FilletConstructionMethod::Fillet)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique(ConstructionMethods::FilletConstructionMethod::Fillet) + ); } bool CmdSketcherCreateFillet::isActive() @@ -1565,9 +1600,10 @@ CmdSketcherCreateChamfer::CmdSketcherCreateChamfer() void CmdSketcherCreateChamfer::activated(int iMsg) { Q_UNUSED(iMsg); - ActivateHandler(getActiveGuiDocument(), - std::make_unique( - ConstructionMethods::FilletConstructionMethod::Chamfer)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique(ConstructionMethods::FilletConstructionMethod::Chamfer) + ); } bool CmdSketcherCreateChamfer::isActive() @@ -1712,8 +1748,9 @@ public: sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("External Geometry"); - sToolTipText = - QT_TR_NOOP("Creates sketch elements linked to geometry defined outside the sketch"); + sToolTipText = QT_TR_NOOP( + "Creates sketch elements linked to geometry defined outside the sketch" + ); sWhatsThis = "Sketcher_CompExternal"; sStatusTip = sToolTipText; sAccel = "G, X"; @@ -1785,8 +1822,10 @@ void CmdSketcherProjection::activated(int iMsg) bool extGeoRef = Gui::WindowParameter::getDefaultParameter() ->GetGroup("Mod/Sketcher/General") ->GetBool("AlwaysExtGeoReference", false); - ActivateHandler(getActiveGuiDocument(), - std::make_unique(extGeoRef, false)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique(extGeoRef, false) + ); } bool CmdSketcherProjection::isActive() @@ -1804,8 +1843,7 @@ CmdSketcherIntersection::CmdSketcherIntersection() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("External Intersection"); - sToolTipText = - QT_TR_NOOP("Creates the intersection of external geometry with the sketch plane"); + sToolTipText = QT_TR_NOOP("Creates the intersection of external geometry with the sketch plane"); sWhatsThis = "Sketcher_Intersection"; sStatusTip = sToolTipText; sPixmap = "Sketcher_Intersection"; @@ -1821,8 +1859,10 @@ void CmdSketcherIntersection::activated(int iMsg) bool extGeoRef = Gui::WindowParameter::getDefaultParameter() ->GetGroup("Mod/Sketcher/General") ->GetBool("AlwaysExtGeoReference", false); - ActivateHandler(getActiveGuiDocument(), - std::make_unique(extGeoRef, true)); + ActivateHandler( + getActiveGuiDocument(), + std::make_unique(extGeoRef, true) + ); } bool CmdSketcherIntersection::isActive() diff --git a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp index 0a13e5d849..e56ba9399c 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp @@ -50,10 +50,10 @@ void ActivateBSplineHandler(Gui::Document* doc, DrawSketchHandler* handler) { std::unique_ptr ptr(handler); if (doc) { - if (doc->getInEdit() - && doc->getInEdit()->isDerivedFrom()) { - SketcherGui::ViewProviderSketch* vp = - static_cast(doc->getInEdit()); + if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom()) { + SketcherGui::ViewProviderSketch* vp = static_cast( + doc->getInEdit() + ); vp->purgeHandler(); vp->activateHandler(std::move(ptr)); } @@ -64,11 +64,13 @@ void ActivateBSplineHandler(Gui::Document* doc, DrawSketchHandler* handler) /// 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 @@ -162,9 +164,11 @@ void CmdSketcherConvertToNURBS::activated(int iMsg) if (GeoIdList.empty()) { abortCommand(); - Gui::TranslatedUserWarning(Obj, - QObject::tr("Wrong selection"), - QObject::tr("None of the selected elements is an edge.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr("None of the selected elements is an edge.") + ); } else { commitCommand(); @@ -233,10 +237,14 @@ 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.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "At least one of the selected " + "objects was not a B-spline and was ignored." + ) + ); } commitCommand(); @@ -297,9 +305,7 @@ void CmdSketcherDecreaseDegree::activated(int iMsg) const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->is()) { - 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 @@ -316,10 +322,14 @@ 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.")); + Gui::TranslatedUserWarning( + Obj, + QObject::tr("Wrong selection"), + QObject::tr( + "At least one of the selected " + "objects was not a B-spline and was ignored." + ) + ); } commitCommand(); @@ -338,9 +348,10 @@ bool isCommandNeedingBSplineKnotActive(Gui::Document* doc) return false; } - std::vector sel = - Gui::Selection().getSelectionEx(doc->getDocument()->getName(), - Sketcher::SketchObject::getClassTypeId()); + std::vector sel = Gui::Selection().getSelectionEx( + doc->getDocument()->getName(), + Sketcher::SketchObject::getClassTypeId() + ); if (sel.size() == 1) { const std::vector& names = sel[0].getSubNames(); if (names.size() != 1) { @@ -405,7 +416,8 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) Gui::TranslatedUserWarning( getActiveGuiDocument()->getDocument(), QObject::tr("Wrong selection"), - QObject::tr("The selection comprises more than one item. Select just one knot.")); + QObject::tr("The selection comprises more than one item. Select just one knot.") + ); return; } @@ -421,19 +433,23 @@ 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) { bsplinetag = Obj->getGeometry(splineGeoId)->getTag(); try { - Gui::cmdAppObjectArgs(selection[0].getObject(), - "modifyBSplineKnotMultiplicity(%d, %d, %d) ", - splineGeoId, - knotIndexOCC, - 1); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "modifyBSplineKnotMultiplicity(%d, %d, %d) ", + splineGeoId, + knotIndexOCC, + 1 + ); applied = true; // Warning: GeoId list might have changed @@ -443,18 +459,22 @@ 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(); } @@ -464,7 +484,8 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) Gui::TranslatedUserWarning( Obj, QObject::tr("Wrong selection"), - QObject::tr("None of the selected elements is a knot of a B-spline")); + QObject::tr("None of the selected elements is a knot of a B-spline") + ); } if (applied) { @@ -485,14 +506,14 @@ 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(); } } @@ -552,7 +573,8 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) Gui::TranslatedUserWarning( getActiveGuiDocument()->getDocument(), QObject::tr("Wrong selection"), - QObject::tr("The selection comprises more than one item. Select just one knot.")); + QObject::tr("The selection comprises more than one item. Select just one knot.") + ); return; } @@ -568,28 +590,34 @@ 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) { bsplinetag = Obj->getGeometry(splineGeoId)->getTag(); try { - Gui::cmdAppObjectArgs(selection[0].getObject(), - "modifyBSplineKnotMultiplicity(%d, %d, %d) ", - splineGeoId, - knotIndexOCC, - -1); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "modifyBSplineKnotMultiplicity(%d, %d, %d) ", + 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. } 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(); } @@ -599,7 +627,8 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) Gui::TranslatedUserWarning( Obj, QObject::tr("Wrong selection"), - QObject::tr("None of the selected elements is a knot of a B-spline")); + QObject::tr("None of the selected elements is a knot of a B-spline") + ); } if (applied) { @@ -620,14 +649,14 @@ 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(); } } @@ -724,23 +753,37 @@ void CmdSketcherCompModifyKnotMultiplicity::languageChange() QList a = pcAction->actions(); QAction* c1 = a[0]; - c1->setText(QApplication::translate("CmdSketcherCompModifyKnotMultiplicity", - "Increase knot multiplicity")); + 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")); + 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")); + 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->setText( + QApplication::translate("CmdSketcherCompModifyKnotMultiplicity", "Decrease knot multiplicity") + ); c2->setToolTip( - QApplication::translate("Sketcher_BSplineDecreaseKnotMultiplicity", - "Decreases the multiplicity of the selected knot of a B-spline")); + 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")); + QApplication::translate( + "Sketcher_BSplineDecreaseKnotMultiplicity", + "Decreases the multiplicity of the selected knot of a B-spline" + ) + ); } void CmdSketcherCompModifyKnotMultiplicity::updateAction(int /*mode*/) @@ -818,17 +861,21 @@ 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()) + ); } } @@ -839,8 +886,7 @@ public: // find new geoid for B-spline as GeoId might have changed const std::vector& gvals = Obj->getInternalGeometry(); - for (std::vector::const_iterator geo = gvals.begin(); - geo != gvals.end(); + for (std::vector::const_iterator geo = gvals.begin(); geo != gvals.end(); geo++, newGeoId++) { if ((*geo) && (*geo)->getTag() == bsplinetag) { newGeoIdFound = true; @@ -854,9 +900,11 @@ 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() + ); } } } @@ -871,7 +919,8 @@ public: tryAutoRecomputeIfNotSolve(Obj); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode && newGeoIdFound) { // This code enables the continuous creation mode. @@ -886,8 +935,7 @@ 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; @@ -914,9 +962,10 @@ CmdSketcherInsertKnot::CmdSketcherInsertKnot() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Insert Knot"); - sToolTipText = - QT_TR_NOOP("Inserts a knot at a given parameter. If a knot already exists at that " - "parameter, its multiplicity is increased by 1."); + sToolTipText = QT_TR_NOOP( + "Inserts a knot at a given parameter. If a knot already exists at that " + "parameter, its multiplicity is increased by 1." + ); sWhatsThis = "Sketcher_BSplineInsertKnot"; sStatusTip = sToolTipText; sPixmap = "Sketcher_BSplineInsertKnot"; @@ -943,9 +992,11 @@ void CmdSketcherInsertKnot::activated(int iMsg) 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. Select a B-spline.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument()->getDocument(), + QObject::tr("Selection is empty"), + QObject::tr("Nothing is selected. Select a B-spline.") + ); return; } @@ -956,15 +1007,20 @@ void CmdSketcherInsertKnot::activated(int iMsg) const Part::Geometry* geo = Obj->getGeometry(GeoId); if (geo->is()) { - ActivateBSplineHandler(getActiveGuiDocument(), - new DrawSketchHandlerBSplineInsertKnot(Obj, GeoId)); + ActivateBSplineHandler( + getActiveGuiDocument(), + new DrawSketchHandlerBSplineInsertKnot(Obj, GeoId) + ); } else { Gui::TranslatedUserWarning( Obj, QObject::tr("Wrong selection"), - QObject::tr("Select a B-spline to insert a knot (not a knot on it). " - "If the curve is not a B-spline, convert it into one first.")); + QObject::tr( + "Select a B-spline to insert a knot (not a knot on it). " + "If the curve is not a B-spline, convert it into one first." + ) + ); } getSelection().clearSelection(); @@ -1018,7 +1074,8 @@ void CmdSketcherJoinCurves::activated(int iMsg) Gui::TranslatedUserWarning( Obj, QObject::tr("Selection is empty"), - QObject::tr("Nothing is selected. Select end points of curves.")); + QObject::tr("Nothing is selected. Select end points of curves.") + ); return; } case 1: { @@ -1046,18 +1103,25 @@ void CmdSketcherJoinCurves::activated(int iMsg) 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.")); + QObject::tr( + "Exactly two curves should end at the selected point to be " + "able to join them." + ) + ); 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.")); + 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; } @@ -1073,7 +1137,8 @@ void CmdSketcherJoinCurves::activated(int iMsg) Gui::TranslatedUserWarning( Obj, QObject::tr("Wrong selection"), - QObject::tr("Two end points, or coincident point should be selected.")); + QObject::tr("Two end points, or coincident point should be selected.") + ); return; } @@ -1096,21 +1161,25 @@ void CmdSketcherJoinCurves::activated(int iMsg) bool applied = false; try { - Gui::cmdAppObjectArgs(selection[0].getObject(), - "join(%d, %d, %d, %d, %d) ", - GeoIds[0], - static_cast(PosIds[0]), - GeoIds[1], - static_cast(PosIds[1]), - tangentConstraintExists ? 1 : 0); + Gui::cmdAppObjectArgs( + selection[0].getObject(), + "join(%d, %d, %d, %d, %d) ", + GeoIds[0], + static_cast(PosIds[0]), + GeoIds[1], + static_cast(PosIds[1]), + tangentConstraintExists ? 1 : 0 + ); 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(); } diff --git a/src/Mod/Sketcher/Gui/CommandSketcherOverlay.cpp b/src/Mod/Sketcher/Gui/CommandSketcherOverlay.cpp index 97af887df9..40ca2e3b7f 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherOverlay.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherOverlay.cpp @@ -48,7 +48,8 @@ using namespace Sketcher; void ShowRestoreInformationLayer(const char* visibleelementname) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/General" + ); bool status = hGrp->GetBool(visibleelementname, true); hGrp->SetBool(visibleelementname, !status); } @@ -201,8 +202,7 @@ bool CmdSketcherBSplinePoleWeight::isActive() // Composite drop down menu for show/hide BSpline information layer DEF_STD_CMD_ACLU(CmdSketcherCompBSplineShowHideGeometryInformation) -CmdSketcherCompBSplineShowHideGeometryInformation:: - CmdSketcherCompBSplineShowHideGeometryInformation() +CmdSketcherCompBSplineShowHideGeometryInformation::CmdSketcherCompBSplineShowHideGeometryInformation() : Command("Sketcher_CompBSplineShowHideGeometryInformation") { sAppModule = "Sketcher"; @@ -289,51 +289,98 @@ void CmdSketcherCompBSplineShowHideGeometryInformation::languageChange() QList a = pcAction->actions(); QAction* c1 = a[0]; - c1->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", - "Toggle B-Spline Degree")); + c1->setText( + QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", "Toggle B-Spline Degree") + ); c1->setToolTip( - QApplication::translate("Sketcher_BSplineDegree", - "Toggles the visibility of the degree for all B-splines")); + QApplication::translate( + "Sketcher_BSplineDegree", + "Toggles the visibility of the degree for all B-splines" + ) + ); c1->setStatusTip( - QApplication::translate("Sketcher_BSplineDegree", - "Toggles the visibility of the degree for all B-splines")); + QApplication::translate( + "Sketcher_BSplineDegree", + "Toggles the visibility of the degree for all B-splines" + ) + ); QAction* c2 = a[1]; - c2->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", - "Toggle B-Spline Control Polygon")); - c2->setToolTip(QApplication::translate( - "Sketcher_BSplinePolygon", - "Toggles the visibility of the control polygons for all B-splines")); - c2->setStatusTip(QApplication::translate( - "Sketcher_BSplinePolygon", - "Toggles the visibility of the control polygons for all B-splines")); + c2->setText( + QApplication::translate( + "CmdSketcherCompBSplineShowHideGeometryInformation", + "Toggle B-Spline Control Polygon" + ) + ); + c2->setToolTip( + QApplication::translate( + "Sketcher_BSplinePolygon", + "Toggles the visibility of the control polygons for all B-splines" + ) + ); + c2->setStatusTip( + QApplication::translate( + "Sketcher_BSplinePolygon", + "Toggles the visibility of the control polygons for all B-splines" + ) + ); QAction* c3 = a[2]; - c3->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", - "Toggle B-Spline Curvature Comb")); + c3->setText( + QApplication::translate( + "CmdSketcherCompBSplineShowHideGeometryInformation", + "Toggle B-Spline Curvature Comb" + ) + ); c3->setToolTip( - QApplication::translate("Sketcher_BSplineComb", - "Toggles the visibility of the curvature comb for all B-splines")); + QApplication::translate( + "Sketcher_BSplineComb", + "Toggles the visibility of the curvature comb for all B-splines" + ) + ); c3->setStatusTip( - QApplication::translate("Sketcher_BSplineComb", - "Toggles the visibility of the curvature comb for all B-splines")); + QApplication::translate( + "Sketcher_BSplineComb", + "Toggles the visibility of the curvature comb for all B-splines" + ) + ); QAction* c4 = a[3]; - c4->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", - "Toggle B-Spline Knot Multiplicity")); - c4->setToolTip(QApplication::translate( - "Sketcher_BSplineKnotMultiplicity", - "Toggles the visibility of the knot multiplicity for all B-splines")); - c4->setStatusTip(QApplication::translate( - "Sketcher_BSplineKnotMultiplicity", - "Toggles the visibility of the knot multiplicity for all B-splines")); + c4->setText( + QApplication::translate( + "CmdSketcherCompBSplineShowHideGeometryInformation", + "Toggle B-Spline Knot Multiplicity" + ) + ); + c4->setToolTip( + QApplication::translate( + "Sketcher_BSplineKnotMultiplicity", + "Toggles the visibility of the knot multiplicity for all B-splines" + ) + ); + c4->setStatusTip( + QApplication::translate( + "Sketcher_BSplineKnotMultiplicity", + "Toggles the visibility of the knot multiplicity for all B-splines" + ) + ); QAction* c5 = a[4]; - c5->setText(QApplication::translate("CmdSketcherCompBSplineShowHideGeometryInformation", - "Toggle B-Spline Control Point Weight")); - c5->setToolTip(QApplication::translate( - "Sketcher_BSplinePoleWeight", - "Toggles the visibility of the control point weight for all B-splines")); - c5->setStatusTip(QApplication::translate( - "Sketcher_BSplinePoleWeight", - "Toggles the visibility of the control point weight for all B-splines")); + c5->setText( + QApplication::translate( + "CmdSketcherCompBSplineShowHideGeometryInformation", + "Toggle B-Spline Control Point Weight" + ) + ); + c5->setToolTip( + QApplication::translate( + "Sketcher_BSplinePoleWeight", + "Toggles the visibility of the control point weight for all B-splines" + ) + ); + c5->setStatusTip( + QApplication::translate( + "Sketcher_BSplinePoleWeight", + "Toggles the visibility of the control point weight for all B-splines" + ) + ); } void CmdSketcherCompBSplineShowHideGeometryInformation::updateAction(int /*mode*/) diff --git a/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp b/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp index 68548a5a09..e3a78fb560 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp @@ -49,8 +49,7 @@ 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()) { + if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom()) { if (static_cast(doc->getInEdit())->getSketchMode() == ViewProviderSketch::STATUS_NONE) { if (!actsOnSelection) { @@ -69,10 +68,10 @@ void ActivateVirtualSpaceHandler(Gui::Document* doc, DrawSketchHandler* handler) { std::unique_ptr ptr(handler); if (doc) { - if (doc->getInEdit() - && doc->getInEdit()->isDerivedFrom()) { - SketcherGui::ViewProviderSketch* vp = - static_cast(doc->getInEdit()); + if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom()) { + SketcherGui::ViewProviderSketch* vp = static_cast( + doc->getInEdit() + ); vp->purgeHandler(); vp->activateHandler(std::move(ptr)); } @@ -88,8 +87,9 @@ CmdSketcherSwitchVirtualSpace::CmdSketcherSwitchVirtualSpace() 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"); + sToolTipText = QT_TR_NOOP( + "Switches the selected constraints or the view to the other virtual space" + ); sWhatsThis = "Sketcher_SwitchVirtualSpace"; sStatusTip = sToolTipText; sPixmap = "Sketcher_SwitchVirtualSpace"; @@ -111,18 +111,22 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) // only one sketch with its subelements are allowed to be selected if (selection.size() != 1 || !selection[0].isObjectTypeOf(Sketcher::SketchObject::getClassTypeId())) { - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + QObject::tr("Wrong selection"), + QObject::tr("Select constraints from the sketch.") + ); return; } // get the needed lists and objects const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + QObject::tr("Wrong selection"), + QObject::tr("Select constraints from the sketch.") + ); return; } @@ -138,8 +142,9 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) if (modeChange) { 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) @@ -147,15 +152,18 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) // get the needed lists and objects const std::vector& SubNames = selection[0].getSubNames(); if (SubNames.empty()) { - Gui::TranslatedUserWarning(getActiveGuiDocument(), - QObject::tr("Wrong selection"), - QObject::tr("Select constraints from the sketch.")); + Gui::TranslatedUserWarning( + getActiveGuiDocument(), + QObject::tr("Wrong selection"), + QObject::tr("Select constraints 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 @@ -169,7 +177,8 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) 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")); + QT_TRANSLATE_NOOP("Command", "Update constraint's virtual space") + ); try { Gui::cmdAppObjectArgs(Obj, "toggleVirtualSpace(%d)", ConstrId); } diff --git a/src/Mod/Sketcher/Gui/ConstraintFilters.h b/src/Mod/Sketcher/Gui/ConstraintFilters.h index ec0e58897d..20904c290f 100644 --- a/src/Mod/Sketcher/Gui/ConstraintFilters.h +++ b/src/Mod/Sketcher/Gui/ConstraintFilters.h @@ -68,8 +68,9 @@ enum class FilterValue 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 { @@ -78,8 +79,9 @@ enum class SpecialFilterValue 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; @@ -111,42 +113,46 @@ constexpr decltype(auto) buildBitset(Args... args) /// 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::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) @@ -160,15 +166,17 @@ constexpr std::array filterAggregates { 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::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) diff --git a/src/Mod/Sketcher/Gui/DrawSketchControllableHandler.h b/src/Mod/Sketcher/Gui/DrawSketchControllableHandler.h index 2067ed4397..a5bdc06507 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchControllableHandler.h +++ b/src/Mod/Sketcher/Gui/DrawSketchControllableHandler.h @@ -40,11 +40,11 @@ namespace SketcherGui * controlling entities such as widgets and on-screen controls. */ template -class DrawSketchControllableHandler - : public DrawSketchDefaultHandler +class DrawSketchControllableHandler: public DrawSketchDefaultHandler< + typename ControllerT::HandlerType, + typename ControllerT::SelectModeType, + ControllerT::AutoConstraintInitialSize, + typename ControllerT::ContructionMethodType> { /** @name Meta-programming definitions and members */ //@{ @@ -55,10 +55,8 @@ class DrawSketchControllableHandler /** @name Convenience definitions */ //@{ - using DSDefaultHandler = DrawSketchDefaultHandler; + using DSDefaultHandler + = DrawSketchDefaultHandler; using ConstructionMachine = ConstructionMethodMachine; //@} @@ -71,7 +69,8 @@ class DrawSketchControllableHandler public: DrawSketchControllableHandler( - ConstructionMethodType constructionmethod = static_cast(0)) + ConstructionMethodType constructionmethod = static_cast(0) + ) : DSDefaultHandler(constructionmethod) , toolWidgetManager(static_cast(this)) {} diff --git a/src/Mod/Sketcher/Gui/DrawSketchController.h b/src/Mod/Sketcher/Gui/DrawSketchController.h index f2fede79f7..aba9215b73 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchController.h +++ b/src/Mod/Sketcher/Gui/DrawSketchController.h @@ -87,14 +87,18 @@ namespace sp = std::placeholders; * DrawSketchDefaultWidgetController. For custom widgets, an appropriate class, preferably deriving * from this controller needs to be provided. */ -template // The enum comprising all the - // supported construction methods +template< + typename HandlerT, // The name of the actual handler of the tool + typename SelectModeT, // The state machine defining the working of the tool + int PAutoConstraintSize, // The initial size of the AutoConstraint vector + typename OnViewParametersT, // The number of parameter spinboxes in the 3D view (one + // value per construction mode) + typename ConstructionMethodT = ConstructionMethods::DefaultConstructionMethod> // The enum + // comprising + // all the + // supported + // construction + // methods class DrawSketchController { public: @@ -110,8 +114,8 @@ public: /** @name Convenience definitions */ //@{ - using DSDefaultHandler = - DrawSketchDefaultHandler; + using DSDefaultHandler + = DrawSketchDefaultHandler; using ConstructionMachine = ConstructionMethodMachine; using ConstructionMethod = ConstructionMethodT; @@ -167,7 +171,8 @@ private: void init() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); dimConstrColor = SbColor(1.0f, 0.149f, 0.0f); // NOLINT dimConstrDeactivatedColor = SbColor(0.5f, 0.5f, 0.5f); // NOLINT @@ -219,8 +224,8 @@ private: case OnViewParameterVisibility::Hidden: return dynamicOverride; case OnViewParameterVisibility::OnlyDimensional: { - auto isDimensional = - (ovp->getFunction() == Gui::EditableDatumLabel::Function::Dimensioning); + auto isDimensional + = (ovp->getFunction() == Gui::EditableDatumLabel::Function::Dimensioning); return isDimensional != dynamicOverride; } @@ -246,10 +251,12 @@ private: void init() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools" + ); onViewParameterVisibility = static_cast( - hGrp->GetInt("OnViewParameterVisibility", 1)); + hGrp->GetInt("OnViewParameterVisibility", 1) + ); } OnViewParameterVisibility onViewParameterVisibility; @@ -437,8 +444,10 @@ public: handler->setState(getState(onviewparameterindex)); }*/ - adaptDrawingToOnViewParameterChange(onviewparameterindex, - value); // specialisation interface + adaptDrawingToOnViewParameterChange( + onviewparameterindex, + value + ); // specialisation interface finishControlsChanged(); } @@ -535,8 +544,7 @@ public: virtual void afterHandlerModeChanged() { if (handler && (!handler->isState(SelectModeT::End) || handler->continuousMode)) { - auto snapHandle = - std::make_unique(nullptr, prevCursorPosition); + auto snapHandle = std::make_unique(nullptr, prevCursorPosition); handler->mouseMove(*snapHandle); } } @@ -555,17 +563,18 @@ public: } } - void - drawWidthHeightAtCursor(const Base::Vector2d& position, const double val1, const double val2) + void drawWidthHeightAtCursor(const Base::Vector2d& position, const double val1, const double val2) { if (shouldDrawDimensionsAtCursor()) { handler->drawWidthHeightAtCursor(position, val1, val2); } } - void drawDoubleAtCursor(const Base::Vector2d& position, - const double radius, - Base::Unit unit = Base::Unit::Length) + void drawDoubleAtCursor( + const Base::Vector2d& position, + const double radius, + Base::Unit unit = Base::Unit::Length + ) { if (shouldDrawDimensionsAtCursor()) { handler->drawDoubleAtCursor(position, radius, unit); @@ -640,8 +649,8 @@ protected: computeNextDrawSketchHandlerMode(); auto nextState = handler->getNextState(); - bool shouldProcessLastPosWithNextState = - nextState && nextState != SelectMode::End && nextState != currentstate && firstMoveInit; + bool shouldProcessLastPosWithNextState = nextState && nextState != SelectMode::End + && nextState != currentstate && firstMoveInit; // the handler will be destroyed in applyNextState if the nextState is End handler->applyNextState(); @@ -649,8 +658,7 @@ protected: // reset) if (shouldProcessLastPosWithNextState) { // mode has changed, so reprocess the previous position to the new widget state - auto snapHandle = - std::make_unique(nullptr, prevCursorPosition); + auto snapHandle = std::make_unique(nullptr, prevCursorPosition); handler->mouseMove(*snapHandle); } } @@ -669,30 +677,33 @@ protected: // the returned is a naked pointer auto parameter = onViewParameters - .emplace_back(std::make_unique( - viewer, - placement, - colorManager.dimConstrDeactivatedColor, - /*autoDistance = */ true, - /*avoidMouseCursor = */ true)) + .emplace_back( + std::make_unique( + viewer, + placement, + colorManager.dimConstrDeactivatedColor, + /*autoDistance = */ true, + /*avoidMouseCursor = */ true + ) + ) .get(); - QObject::connect(parameter, - &Gui::EditableDatumLabel::valueChanged, - [this, parameter, i](double value) { - parameter->setColor(colorManager.dimConstrColor); - onViewValueChanged(i, value); - }); + QObject::connect( + parameter, + &Gui::EditableDatumLabel::valueChanged, + [this, parameter, i](double value) { + parameter->setColor(colorManager.dimConstrColor); + onViewValueChanged(i, value); + } + ); // this gets triggered whenever user deletes content in OVP, we remove the // constraints and unset everything to give user another change to select stuff // with mouse - QObject::connect(parameter, - &Gui::EditableDatumLabel::parameterUnset, - [this, parameter]() { - unsetOnViewParameter(parameter); - finishControlsChanged(); - }); + QObject::connect(parameter, &Gui::EditableDatumLabel::parameterUnset, [this, parameter]() { + unsetOnViewParameter(parameter); + finishControlsChanged(); + }); // Connect Ctrl+Enter signal to apply values to all visible OVPs in current stage QObject::connect(parameter, &Gui::EditableDatumLabel::finishEditingOnAllOVPs, [this]() { @@ -710,9 +721,11 @@ protected: onViewParameter->setLockedAppearance(false); } - void setOnViewParameterValue(OnViewParameter index, - double val, - const Base::Unit& unit = Base::Unit::Length) + void setOnViewParameterValue( + OnViewParameter index, + double val, + const Base::Unit& unit = Base::Unit::Length + ) { bool visible = isOnViewParameterVisible(index); @@ -853,13 +866,15 @@ private: bool shouldDrawPositionAtCursor() const { return !(ovpVisibilityManager.isVisibility( - OnViewParameterVisibilityManager::OnViewParameterVisibility::ShowAll)); + OnViewParameterVisibilityManager::OnViewParameterVisibility::ShowAll + )); } bool shouldDrawDimensionsAtCursor() const { return (ovpVisibilityManager.isVisibility( - OnViewParameterVisibilityManager::OnViewParameterVisibility::Hidden)); + OnViewParameterVisibilityManager::OnViewParameterVisibility::Hidden + )); } //@} diff --git a/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h b/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h index 84969a05b9..ed8d948793 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h +++ b/src/Mod/Sketcher/Gui/DrawSketchDefaultHandler.h @@ -283,7 +283,8 @@ class ConstructionMethodMachine { public: ConstructionMethodMachine( - ConstructionMethodT constructionmethod = static_cast(0)) + ConstructionMethodT constructionmethod = static_cast(0) + ) : ConstructionMode(constructionmethod) {} virtual ~ConstructionMethodMachine() @@ -399,17 +400,19 @@ private: * DrawSketchDefaultWidgetHandler. Then you will have to implement the code that is exclusively * necessary for the default widget to work. */ -template - typename ConstructionMethodT = ConstructionMethods::DefaultConstructionMethod> +template< + typename HandlerT, // A type for which the handler template is instantiated + typename SelectModeT, // The state machine defining the states that the handle iterates + int PInitAutoConstraintSize, // The initial size of the AutoConstraint> + typename ConstructionMethodT = ConstructionMethods::DefaultConstructionMethod> class DrawSketchDefaultHandler: public DrawSketchHandler, public StateMachine, public ConstructionMethodMachine { public: DrawSketchDefaultHandler( - ConstructionMethodT constructionmethod = static_cast(0)) + ConstructionMethodT constructionmethod = static_cast(0) + ) : ConstructionMethodMachine(constructionmethod) , sugConstraints(PInitAutoConstraintSize) , avoidRedundants(true) @@ -634,11 +637,12 @@ protected: /** @brief Minimal handle activation respecting avoid redundants and continuous mode.*/ void activated() override { - avoidRedundants = - sketchgui->AvoidRedundant.getValue() && sketchgui->Autoconstraints.getValue(); + avoidRedundants = sketchgui->AvoidRedundant.getValue() + && sketchgui->Autoconstraints.getValue(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); continuousMode = hGrp->GetBool("ContinuousCreationMode", true); } @@ -675,9 +679,11 @@ protected: //@{ // TODO: Figure out and explain what it actually returns - bool generateOneAutoConstraintFromSuggestion(const AutoConstraint& ac, - int geoId1, - Sketcher::PointPos posId1) + bool generateOneAutoConstraintFromSuggestion( + const AutoConstraint& ac, + int geoId1, + Sketcher::PointPos posId1 + ) { int geoId2 = ac.GeoId; Sketcher::PointPos posId2 = ac.PosId; @@ -701,7 +707,8 @@ protected: std::tuple {Sketcher::Tangent, geoId1, geoId2}, [](const auto& ace) { return std::tuple {ace->Type, ace->First, ace->Second}; - }); + } + ); } if (itOfTangentConstraint != AutoConstraints.end()) { @@ -728,18 +735,16 @@ protected: auto itOfTangentConstraint = AutoConstraints.end(); if (isStartOrEnd(posId1)) { - itOfTangentConstraint = - std::ranges::find_if(AutoConstraints, [&](const auto& ace) { - return ace->Type == Sketcher::Tangent && ace->involvesGeoId(geoId1) - && ace->involvesGeoId(geoId2); - }); + itOfTangentConstraint = std::ranges::find_if(AutoConstraints, [&](const auto& ace) { + return ace->Type == Sketcher::Tangent && ace->involvesGeoId(geoId1) + && ace->involvesGeoId(geoId2); + }); } // if tangency, convert to point-to-edge tangency if (itOfTangentConstraint != AutoConstraints.end()) { if ((*itOfTangentConstraint)->First != geoId1) { - std::swap((*itOfTangentConstraint)->Second, - (*itOfTangentConstraint)->First); + std::swap((*itOfTangentConstraint)->Second, (*itOfTangentConstraint)->First); } (*itOfTangentConstraint)->FirstPos = posId1; @@ -809,8 +814,7 @@ protected: // arc of ellipse tangency support using external elements if (geom1 && geom2 - && (geom1->is() - || geom2->is())) { + && (geom1->is() || geom2->is())) { if (!geom1->is()) { std::swap(geoId1, geoId2); } @@ -838,11 +842,10 @@ protected: && ace->Second == geoId2; }); - auto resultPointOnObject = - std::ranges::find_if(AutoConstraints, [&](const auto& ace) { - return ace->Type == Sketcher::PointOnObject && ace->involvesGeoId(geoId1) - && ace->involvesGeoId(geoId2); - }); + auto resultPointOnObject = std::ranges::find_if(AutoConstraints, [&](const auto& ace) { + return ace->Type == Sketcher::PointOnObject && ace->involvesGeoId(geoId1) + && ace->involvesGeoId(geoId2); + }); if (resultCoincident != AutoConstraints.end() && isStartOrEnd((*resultCoincident)->FirstPos) @@ -857,8 +860,7 @@ protected: } else if (resultCoincident != AutoConstraints.end() && (*resultCoincident)->FirstPos == Sketcher::PointPos::mid - && (*resultCoincident)->SecondPos == Sketcher::PointPos::mid && geom1 - && geom2 + && (*resultCoincident)->SecondPos == Sketcher::PointPos::mid && geom1 && geom2 && (geom1->is() || geom1->is()) && (geom2->is() || geom2->is())) { // equality @@ -888,9 +890,11 @@ protected: * * This generates actual Sketcher::Constraint which can be used for diagnostic before addition. */ - void generateAutoConstraintsOnElement(const std::vector& autoConstrs, - int geoId1, - Sketcher::PointPos posId1) + void generateAutoConstraintsOnElement( + const std::vector& autoConstrs, + int geoId1, + Sketcher::PointPos posId1 + ) { if (!sketchgui->Autoconstraints.getValue()) { return; @@ -934,9 +938,12 @@ protected: Gui::Command::doCommand( Gui::Command::Doc, - Sketcher::PythonConverter::convert(Gui::Command::getObjectCmd(sketchgui->getObject()), - autoConstraints) - .c_str()); + Sketcher::PythonConverter::convert( + Gui::Command::getObjectCmd(sketchgui->getObject()), + autoConstraints + ) + .c_str() + ); } /** @brief Convenience function to remove redundant autoconstraints from the AutoConstraints @@ -968,8 +975,8 @@ protected: if (sketchobject->getLastHasRedundancies()) { Base::Console().warning( - QT_TRANSLATE_NOOP("Notifications", - "Autoconstraints cause redundancy. Removing them") "\n"); + QT_TRANSLATE_NOOP("Notifications", "Autoconstraints cause redundancy. Removing them") "\n" + ); auto lastsketchconstraintindex = sketchobject->Constraints.getSize() - 1; @@ -986,11 +993,14 @@ protected: // 1) Geometry (and constraints of the geometry in case of a multicurve shape) // are created 2) No autoconstrains are actually added 3) No widget mandated // constraints are added - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Redundant constraint is not an autoconstraint. No autoconstraints " - "or additional constraints were added. Please report!") "\n"); + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Redundant constraint is not an autoconstraint. No autoconstraints " + "or additional constraints were added. Please report!" + ) "\n" + ); } } @@ -1034,16 +1044,21 @@ protected: sketchobject->diagnoseAdditionalConstraints(autoConstraints); if (sketchobject->getLastHasRedundancies() || sketchobject->getLastHasConflicts()) { - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP("Notifications", - "Unexpected Redundancy/Conflicting constraint. Check the " - "constraints and autoconstraints of this operation.") "\n"); + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Unexpected Redundancy/Conflicting constraint. Check the " + "constraints and autoconstraints of this operation." + ) "\n" + ); } } /** @brief Function to obtain detailed solver information on one point type geometric element.*/ - Sketcher::SolverGeometryExtension::PointParameterStatus - getPointInfo(const Sketcher::GeoElementId& element) + Sketcher::SolverGeometryExtension::PointParameterStatus getPointInfo( + const Sketcher::GeoElementId& element + ) { if (element.isCurve()) { THROWM(Base::TypeError, "getPointInfo: Provided geometry element is not a point!") @@ -1062,16 +1077,17 @@ protected: return pointinfo; } - THROWM(Base::ValueError, - "Geometry element does not have solver information (possibly when trying to apply " - "widget constraints)!") + THROWM( + Base::ValueError, + "Geometry element does not have solver information (possibly when trying to apply " + "widget constraints)!" + ) } /** @brief Function to obtain detailed DoFs of one line type geometric element.*/ int getLineDoFs(int geoid) { - auto startpointinfo = - getPointInfo(Sketcher::GeoElementId(geoid, Sketcher::PointPos::start)); + auto startpointinfo = getPointInfo(Sketcher::GeoElementId(geoid, Sketcher::PointPos::start)); auto endpointinfo = getPointInfo(Sketcher::GeoElementId(geoid, Sketcher::PointPos::end)); @@ -1093,14 +1109,16 @@ protected: auto solvext = solvedsketch.getSolverExtension(geoid); if (solvext) { - Sketcher::SolverGeometryExtension::EdgeParameterStatus edgeinfo = - solvext->getEdgeParameters(); + Sketcher::SolverGeometryExtension::EdgeParameterStatus edgeinfo + = solvext->getEdgeParameters(); return edgeinfo; } - THROWM(Base::ValueError, - "Geometry does not have solver extension when trying to apply widget constraints!") + THROWM( + Base::ValueError, + "Geometry does not have solver extension when trying to apply widget constraints!" + ) } /** @brief Function to add shape inherent constraints (the ones that define the shape) to the @@ -1110,13 +1128,15 @@ protected: * inherent part of it and the shape would not go without them. Lower priority constraints are * AutoConstraints and constraints mandated by the widget/on-screen parameters. * .*/ - auto addToShapeConstraints(Sketcher::ConstraintType type, - int first, - Sketcher::PointPos firstPos = Sketcher::PointPos::none, - int second = Sketcher::GeoEnum::GeoUndef, - Sketcher::PointPos secondPos = Sketcher::PointPos::none, - int third = Sketcher::GeoEnum::GeoUndef, - Sketcher::PointPos thirdPos = Sketcher::PointPos::none) + auto addToShapeConstraints( + Sketcher::ConstraintType type, + int first, + Sketcher::PointPos firstPos = Sketcher::PointPos::none, + int second = Sketcher::GeoEnum::GeoUndef, + Sketcher::PointPos secondPos = Sketcher::PointPos::none, + int third = Sketcher::GeoEnum::GeoUndef, + Sketcher::PointPos thirdPos = Sketcher::PointPos::none + ) { auto constr = std::make_unique(); constr->Type = type; @@ -1135,24 +1155,18 @@ protected: auto line = std::make_unique(); line->setPoints(p1, p2); Sketcher::GeometryFacade::setConstruction(line.get(), constructionMode); - return static_cast( - ShapeGeometry.emplace_back(std::move(line)).get()); + return static_cast(ShapeGeometry.emplace_back(std::move(line)).get()); } /** @brief Function to add an arc to the ShapeGeometry vector.*/ - auto addArcToShapeGeometry(Base::Vector3d p1, - double start, - double end, - double radius, - bool constructionMode) + auto addArcToShapeGeometry(Base::Vector3d p1, double start, double end, double radius, bool constructionMode) { auto arc = std::make_unique(); arc->setCenter(p1); arc->setRange(start, end, true); arc->setRadius(radius); Sketcher::GeometryFacade::setConstruction(arc.get(), constructionMode); - return static_cast( - ShapeGeometry.emplace_back(std::move(arc)).get()); + return static_cast(ShapeGeometry.emplace_back(std::move(arc)).get()); } /** @brief Function to add a point to the ShapeGeometry vector.*/ @@ -1165,11 +1179,13 @@ protected: } /** @brief Function to add an ellipse to the ShapeGeometry vector.*/ - auto addEllipseToShapeGeometry(Base::Vector3d centerPoint, - Base::Vector3d majorAxisDirection, - double majorRadius, - double minorRadius, - bool constructionMode) + auto addEllipseToShapeGeometry( + Base::Vector3d centerPoint, + Base::Vector3d majorAxisDirection, + double majorRadius, + double minorRadius, + bool constructionMode + ) { auto ellipse = std::make_unique(); ellipse->setMajorRadius(majorRadius); @@ -1177,8 +1193,7 @@ protected: ellipse->setMajorAxisDir(majorAxisDirection); ellipse->setCenter(centerPoint); Sketcher::GeometryFacade::setConstruction(ellipse.get(), constructionMode); - return static_cast( - ShapeGeometry.emplace_back(std::move(ellipse)).get()); + return static_cast(ShapeGeometry.emplace_back(std::move(ellipse)).get()); } /** @brief Function to add a circle to the ShapeGeometry vector.*/ @@ -1198,18 +1213,22 @@ protected: auto shapeGeometry = toPointerVector(ShapeGeometry); std::string sketchObj = Gui::Command::getObjectCmd(sketchgui->getObject()); Gui::Command::doCommand(Gui::Command::Doc, "ActiveSketch = %s\n", sketchObj.c_str()); - Gui::Command::doCommand(Gui::Command::Doc, - Sketcher::PythonConverter::convert( - sketchObj, - shapeGeometry, - Sketcher::PythonConverter::Mode::OmitInternalGeometry) - .c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + Sketcher::PythonConverter::convert( + sketchObj, + shapeGeometry, + Sketcher::PythonConverter::Mode::OmitInternalGeometry + ) + .c_str() + ); size_t initialConstraintCount = sketchgui->getSketchObject()->Constraints.getSize(); auto shapeConstraints = toPointerVector(ShapeConstraints); Gui::Command::doCommand( Gui::Command::Doc, - Sketcher::PythonConverter::convert(sketchObj, shapeConstraints).c_str()); + Sketcher::PythonConverter::convert(sketchObj, shapeConstraints).c_str() + ); reassignVirtualSpace(initialConstraintCount); } @@ -1253,9 +1272,11 @@ private: } try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "setVirtualSpace([%s], True)", - stream.str().c_str()); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "setVirtualSpace([%s], True)", + stream.str().c_str() + ); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); diff --git a/src/Mod/Sketcher/Gui/DrawSketchDefaultWidgetController.h b/src/Mod/Sketcher/Gui/DrawSketchDefaultWidgetController.h index b8655691e4..8be55dcefd 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchDefaultWidgetController.h +++ b/src/Mod/Sketcher/Gui/DrawSketchDefaultWidgetController.h @@ -65,30 +65,25 @@ namespace sp = std::placeholders; * * This class is not intended to control based on a custom widget. */ -template // The handler template or class having this as inner class -class DrawSketchDefaultWidgetController: public DrawSketchController +template< + typename HandlerT, // The name of the actual handler of the tool + typename SelectModeT, // The state machine defining the working of the tool + int PAutoConstraintSize, // The initial size of the AutoConstraint vector + typename OnViewParametersT, // The number of parameter spinboxes in the 3D view + typename WidgetParametersT, // The number of parameter spinboxes in the default widget + typename WidgetCheckboxesT, // The number of checkboxes in the default widget + typename WidgetComboboxesT, // The number of comboboxes in the default widget + typename ConstructionMethodT = ConstructionMethods::DefaultConstructionMethod, + bool PFirstComboboxIsConstructionMethod = false> // The handler template or class having this + // as inner class +class DrawSketchDefaultWidgetController + : public DrawSketchController { public: /** @name Meta-programming definitions and members */ //@{ - using ControllerBase = DrawSketchController; + using ControllerBase + = DrawSketchController; //@} private: @@ -313,8 +308,8 @@ protected: if (parameterindex < static_cast(nParameter)) { toolWidget->setParameterFocus(parameterindex); - ControllerBase::parameterWithFocus = - ControllerBase::onViewParameters.size() + parameterindex; + ControllerBase::parameterWithFocus = ControllerBase::onViewParameters.size() + + parameterindex; } } } @@ -362,34 +357,28 @@ private: toolWidget = static_cast(widget); // NOLINT connectionParameterTabOrEnterPressed = toolWidget->registerParameterTabOrEnterPressed( - std::bind(&DrawSketchDefaultWidgetController::parameterTabOrEnterPressed, - this, - sp::_1)); + std::bind(&DrawSketchDefaultWidgetController::parameterTabOrEnterPressed, this, sp::_1) + ); connectionParameterValueChanged = toolWidget->registerParameterValueChanged( - std::bind(&DrawSketchDefaultWidgetController::parameterValueChanged, - this, - sp::_1, - sp::_2)); + std::bind(&DrawSketchDefaultWidgetController::parameterValueChanged, this, sp::_1, sp::_2) + ); connectionCheckboxCheckedChanged = toolWidget->registerCheckboxCheckedChanged( - std::bind(&DrawSketchDefaultWidgetController::checkboxCheckedChanged, - this, - sp::_1, - sp::_2)); + std::bind(&DrawSketchDefaultWidgetController::checkboxCheckedChanged, this, sp::_1, sp::_2) + ); connectionComboboxSelectionChanged = toolWidget->registerComboboxSelectionChanged( - std::bind(&DrawSketchDefaultWidgetController::comboboxSelectionChanged, - this, - sp::_1, - sp::_2)); + std::bind(&DrawSketchDefaultWidgetController::comboboxSelectionChanged, this, sp::_1, sp::_2) + ); } /// Resets the widget void resetDefaultWidget() { boost::signals2::shared_connection_block parameter_focus_block( - connectionParameterTabOrEnterPressed); + connectionParameterTabOrEnterPressed + ); boost::signals2::shared_connection_block parameter_block(connectionParameterValueChanged); boost::signals2::shared_connection_block checkbox_block(connectionCheckboxCheckedChanged); boost::signals2::shared_connection_block combobox_block(connectionComboboxSelectionChanged); @@ -413,7 +402,8 @@ private: if (currentindex != methodint) { // avoid triggering of method change boost::signals2::shared_connection_block combobox_block( - connectionComboboxSelectionChanged); + connectionComboboxSelectionChanged + ); toolWidget->setComboboxIndex(WCombobox::FirstCombo, methodint); } } @@ -463,7 +453,8 @@ private: if (constructionmethod != actualconstructionmethod) { boost::signals2::shared_connection_block combobox_block( - connectionComboboxSelectionChanged); + connectionComboboxSelectionChanged + ); toolWidget->setComboboxIndex(WCombobox::FirstCombo, actualconstructionmethod); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp index 76738d2b4d..ede34362cb 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp @@ -48,22 +48,25 @@ 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); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::setPositionText(ViewProviderSketch& vp, - const Base::Vector2d& Pos) +inline void ViewProviderSketchDrawSketchHandlerAttorney::setPositionText( + ViewProviderSketch& vp, + const Base::Vector2d& Pos +) { vp.setPositionText(Pos); } @@ -73,16 +76,18 @@ inline void ViewProviderSketchDrawSketchHandlerAttorney::resetPositionText(ViewP 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) + const std::list>& list +) { vp.drawEdit(list); } @@ -90,20 +95,21 @@ inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEdit( inline void ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers( ViewProviderSketch& vp, const std::vector& EditMarkers, - unsigned int augmentationlevel) + 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); } @@ -113,49 +119,52 @@ inline void ViewProviderSketchDrawSketchHandlerAttorney::ensureFocus(ViewProvide vp.ensureFocus(); } -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(); } -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); } -inline void ViewProviderSketchDrawSketchHandlerAttorney::moveConstraint(ViewProviderSketch& vp, - int constNum, - const Base::Vector2d& toPos, - OffsetMode offset) +inline void ViewProviderSketchDrawSketchHandlerAttorney::moveConstraint( + ViewProviderSketch& vp, + int constNum, + const Base::Vector2d& toPos, + OffsetMode offset +) { vp.moveConstraint(constNum, toPos, offset); } -inline void -ViewProviderSketchDrawSketchHandlerAttorney::signalToolChanged(const ViewProviderSketch& vp, - const std::string& toolname) +inline void ViewProviderSketchDrawSketchHandlerAttorney::signalToolChanged( + const ViewProviderSketch& vp, + const std::string& toolname +) { vp.signalToolChanged(toolname); } @@ -166,14 +175,13 @@ CurveConverter::CurveConverter() { try { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "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()); + Base::Console().developerError("CurveConverter", "Malformed parameter string: %s\n", e.what()); } updateCurvedEdgeCountSegmentsParameter(); @@ -209,8 +217,8 @@ std::vector CurveConverter::toVector2D(const Part::Geometry* geo 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++) { emplaceasvector2d(geo->value(geo->getFirstParameter() + i * segment)); @@ -223,8 +231,9 @@ std::vector CurveConverter::toVector2D(const Part::Geometry* geo return vector2d; } -std::list> -CurveConverter::toVector2DList(const std::vector& geometries) +std::list> CurveConverter::toVector2DList( + const std::vector& geometries +) { std::list> list; @@ -237,8 +246,9 @@ CurveConverter::toVector2DList(const std::vector& geometries) 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 @@ -378,8 +388,9 @@ int DrawSketchHandler::getHighestCurveIndex() return sketchgui->getSketchObject()->getHighestCurveIndex(); } -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 @@ -409,8 +420,10 @@ DrawSketchHandler::suggestedConstraintsPixmaps(std::vector& sugg } if (!iconType.isEmpty()) { constexpr int iconWidth = 16; - 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); } } @@ -482,7 +495,8 @@ void DrawSketchHandler::seekPreselectionAutoConstraint( std::vector& suggestedConstraints, const Base::Vector2d& Pos, const Base::Vector2d& Dir, - AutoConstraint::TargetType type) + AutoConstraint::TargetType type +) { PreselectionData preSel = getPreselectionData(); @@ -531,7 +545,8 @@ void DrawSketchHandler::seekPreselectionAutoConstraint( void DrawSketchHandler::seekAlignmentAutoConstraint( std::vector& suggestedConstraints, - const Base::Vector2d& Dir) + const Base::Vector2d& Dir +) { using std::numbers::pi; constexpr double angleDevRad = Base::toRadians(2); @@ -555,9 +570,11 @@ void DrawSketchHandler::seekAlignmentAutoConstraint( } } -void DrawSketchHandler::seekTangentAutoConstraint(std::vector& suggestedConstraints, - const Base::Vector2d& Pos, - const Base::Vector2d& Dir) +void DrawSketchHandler::seekTangentAutoConstraint( + std::vector& suggestedConstraints, + const Base::Vector2d& Pos, + const Base::Vector2d& Dir +) { using std::numbers::pi; SketchObject* obj = sketchgui->getSketchObject(); @@ -691,9 +708,10 @@ void DrawSketchHandler::seekTangentAutoConstraint(std::vector& s -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 * pi); + * ((tmpPos.x - center.x) * majdir.x + (tmpPos.y - center.y) * majdir.y) + ) - startAngle, + 2.f * pi + ); while (angle < startAngle) { angle += 2 * pi; // Bring it to range of arc @@ -720,10 +738,12 @@ void DrawSketchHandler::seekTangentAutoConstraint(std::vector& s } } -int DrawSketchHandler::seekAutoConstraint(std::vector& suggestedConstraints, - const Base::Vector2d& Pos, - const Base::Vector2d& Dir, - AutoConstraint::TargetType type) +int DrawSketchHandler::seekAutoConstraint( + std::vector& suggestedConstraints, + const Base::Vector2d& Pos, + const Base::Vector2d& Dir, + AutoConstraint::TargetType type +) { suggestedConstraints.clear(); @@ -744,10 +764,12 @@ 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 @@ -777,7 +799,8 @@ void DrawSketchHandler::createAutoConstraints(const std::vector& geoId1, static_cast(posId1), cstr.GeoId, - static_cast(cstr.PosId)); + static_cast(cstr.PosId) + ); } break; case Sketcher::PointOnObject: { Sketcher::PointPos posId2 = cstr.PosId; @@ -792,7 +815,8 @@ void DrawSketchHandler::createAutoConstraints(const std::vector& "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d)) ", geoId1, static_cast(posId1), - geoId2); + geoId2 + ); } break; case Sketcher::Symmetric: { Gui::cmdAppObjectArgs( @@ -801,7 +825,8 @@ void DrawSketchHandler::createAutoConstraints(const std::vector& geoId2, geoId2, geoId1, - static_cast(posId1)); + static_cast(posId1) + ); } 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 @@ -809,14 +834,18 @@ void DrawSketchHandler::createAutoConstraints(const std::vector& // 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); + 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); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Vertical',%d)) ", + geoId2 != GeoEnum::GeoUndef ? geoId2 : geoId1 + ); } break; case Sketcher::Tangent: { Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); @@ -837,15 +866,15 @@ void DrawSketchHandler::createAutoConstraints(const std::vector& geom2 = Obj->getGeometry(geoId2); if (geom2->is() || geom2->is() - || geom2->is() - || geom2->is()) { + || geom2->is() || geom2->is()) { // in all these cases an intermediate element is needed makeTangentToEllipseviaNewPoint( Obj, static_cast(geom1), geom2, geoId1, - geoId2); + geoId2 + ); return; } } @@ -871,15 +900,18 @@ void DrawSketchHandler::createAutoConstraints(const std::vector& static_cast(geom1), geom2, geoId1, - geoId2); + geoId2 + ); return; } } - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Tangent',%d, %d)) ", - geoId1, - cstr.GeoId); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Tangent',%d, %d)) ", + geoId1, + cstr.GeoId + ); } break; default: break; @@ -898,7 +930,8 @@ int DrawSketchHandler::seekAndRenderAutoConstraint( std::vector& suggestedConstraints, const Base::Vector2d& Pos, const Base::Vector2d& Dir, - AutoConstraint::TargetType type) + AutoConstraint::TargetType type +) { if (seekAutoConstraint(suggestedConstraints, Pos, Dir, type)) { renderSuggestConstraintsCursor(suggestedConstraints); @@ -910,8 +943,7 @@ int DrawSketchHandler::seekAndRenderAutoConstraint( return suggestedConstraints.size(); } -void DrawSketchHandler::renderSuggestConstraintsCursor( - std::vector& suggestedConstraints) +void DrawSketchHandler::renderSuggestConstraintsCursor(std::vector& suggestedConstraints) { std::vector pixmaps = suggestedConstraintsPixmaps(suggestedConstraints); addCursorTail(pixmaps); @@ -967,8 +999,7 @@ 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) { if (!showCursorCoords()) { return; @@ -984,9 +1015,11 @@ void DrawSketchHandler::drawDirectionAtCursor(const Base::Vector2d& position, setPositionText(position, text); } -void DrawSketchHandler::drawWidthHeightAtCursor(const Base::Vector2d& position, - const double val1, - const double val2) +void DrawSketchHandler::drawWidthHeightAtCursor( + const Base::Vector2d& position, + const double val1, + const double val2 +) { if (!showCursorCoords()) { return; @@ -999,9 +1032,7 @@ void DrawSketchHandler::drawWidthHeightAtCursor(const Base::Vector2d& position, setPositionText(position, text); } -void DrawSketchHandler::drawDoubleAtCursor(const Base::Vector2d& position, - const double val, - Base::Unit unit) +void DrawSketchHandler::drawDoubleAtCursor(const Base::Vector2d& position, const double val, Base::Unit unit) { if (!showCursorCoords()) { return; @@ -1035,12 +1066,16 @@ QString DrawSketchHandler::getToolWidgetHeaderText() const return getToolWidgetText(); } -void DrawSketchHandler::drawEditMarkers(const std::vector& EditMarkers, - unsigned int augmentationlevel) const +void DrawSketchHandler::drawEditMarkers( + const std::vector& EditMarkers, + unsigned int augmentationlevel +) const { - ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers(*sketchgui, - EditMarkers, - augmentationlevel); + ViewProviderSketchDrawSketchHandlerAttorney::drawEditMarkers( + *sketchgui, + EditMarkers, + augmentationlevel + ); } void DrawSketchHandler::setAxisPickStyle(bool on) @@ -1085,17 +1120,12 @@ Sketcher::SketchObject* DrawSketchHandler::getSketchObject() void DrawSketchHandler::setAngleSnapping(bool enable, Base::Vector2d referencePoint) { - ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping(*sketchgui, - enable, - referencePoint); + ViewProviderSketchDrawSketchHandlerAttorney::setAngleSnapping(*sketchgui, enable, referencePoint); } void DrawSketchHandler::moveConstraint(int constNum, const Base::Vector2d& toPos, OffsetMode offset) { - ViewProviderSketchDrawSketchHandlerAttorney::moveConstraint(*sketchgui, - constNum, - toPos, - offset); + ViewProviderSketchDrawSketchHandlerAttorney::moveConstraint(*sketchgui, constNum, toPos, offset); } void DrawSketchHandler::signalToolChanged() const diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.h b/src/Mod/Sketcher/Gui/DrawSketchHandler.h index 935b9078ba..72cc5aeedc 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.h @@ -73,8 +73,9 @@ public: std::vector toVector2D(const Part::Geometry* geometry); - std::list> - toVector2DList(const std::vector& geometries); + std::list> toVector2DList( + const std::vector& geometries + ); private: void updateCurvedEdgeCountSegmentsParameter(); @@ -95,33 +96,43 @@ 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, + 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 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 ensureFocus(ViewProviderSketch& vp); 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 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 void moveConstraint(ViewProviderSketch& vp, - int constNum, - const Base::Vector2d& toPos, - OffsetMode offset = NoOffset); + static inline void moveConstraint( + ViewProviderSketch& vp, + int constNum, + const Base::Vector2d& toPos, + OffsetMode offset = NoOffset + ); static inline void signalToolChanged(const ViewProviderSketch& vp, const std::string& toolname); @@ -181,23 +192,29 @@ 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, - AutoConstraint::TargetType type = AutoConstraint::VERTEX); + int seekAutoConstraint( + std::vector& suggestedConstraints, + const Base::Vector2d& Pos, + const Base::Vector2d& Dir, + AutoConstraint::TargetType type = AutoConstraint::VERTEX + ); - int seekAndRenderAutoConstraint(std::vector& suggestedConstraints, - const Base::Vector2d& Pos, - const Base::Vector2d& Dir, - AutoConstraint::TargetType type = AutoConstraint::VERTEX); + int seekAndRenderAutoConstraint( + 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); + 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); @@ -253,8 +270,10 @@ protected: void drawEdit(const std::vector& EditCurve) const; void drawEdit(const std::list>& list) const; void drawEdit(const std::vector& geometries) const; - void drawEditMarkers(const std::vector& EditMarkers, - unsigned int augmentationlevel = 0) const; + void drawEditMarkers( + const std::vector& EditMarkers, + unsigned int augmentationlevel = 0 + ) const; void clearEdit() const; void clearEditMarkers() const; @@ -266,11 +285,12 @@ protected: void drawPositionAtCursor(const Base::Vector2d& position); void drawDirectionAtCursor(const Base::Vector2d& position, const Base::Vector2d& origin); - void - drawWidthHeightAtCursor(const Base::Vector2d& position, const double val1, const double val2); - void drawDoubleAtCursor(const Base::Vector2d& position, - const double radius, - Base::Unit unit = Base::Unit::Length); + void drawWidthHeightAtCursor(const Base::Vector2d& position, const double val1, const double val2); + void drawDoubleAtCursor( + const Base::Vector2d& position, + const double radius, + Base::Unit unit = Base::Unit::Length + ); int getPreselectPoint() const; int getPreselectCurve() const; @@ -296,26 +316,28 @@ protected: }; PreselectionData getPreselectionData(); - void seekPreselectionAutoConstraint(std::vector& constraints, - const Base::Vector2d& Pos, - const Base::Vector2d& Dir, - AutoConstraint::TargetType type); + void seekPreselectionAutoConstraint( + std::vector& constraints, + const Base::Vector2d& Pos, + const Base::Vector2d& Dir, + AutoConstraint::TargetType type + ); bool isLineCenterAutoConstraint(int GeoId, const Base::Vector2d& Pos) const; - void seekAlignmentAutoConstraint(std::vector& constraints, - const Base::Vector2d& Dir); + void seekAlignmentAutoConstraint(std::vector& constraints, const Base::Vector2d& Dir); - void seekTangentAutoConstraint(std::vector& constraints, - const Base::Vector2d& Pos, - const Base::Vector2d& Dir); + void seekTangentAutoConstraint( + std::vector& constraints, + const Base::Vector2d& Pos, + const Base::Vector2d& Dir + ); protected: /** * Returns constraints icons scaled to width. **/ - std::vector - suggestedConstraintsPixmaps(std::vector& suggestedConstraints); + std::vector suggestedConstraintsPixmaps(std::vector& suggestedConstraints); ViewProviderSketch* sketchgui; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h index 90cdb653cc..0cbb2ae763 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h @@ -54,16 +54,16 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerArc; -using DSHArcController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT - ConstructionMethods::CircleEllipseConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHArcController = DrawSketchDefaultWidgetController< + DrawSketchHandlerArc, + StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/3, + /*OnViewParametersT =*/OnViewParameters<5, 6>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT + ConstructionMethods::CircleEllipseConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHArcControllerBase = DSHArcController::ControllerBase; @@ -153,9 +153,7 @@ private: firstPoint = onSketchPos; } - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { if (constructionMethod() == ConstructionMethod::Center) { @@ -178,9 +176,7 @@ private: toolWidgetManager.drawPositionAtCursor(onSketchPos); } - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[1], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekThird: { double startAngleBackup = startAngle; @@ -204,8 +200,8 @@ private: // If points are collinear then we can't calculate the center. return; } - centerPoint = - Part::Geom2dCircle::getCircleCenter(firstPoint, secondPoint, onSketchPos); + centerPoint + = Part::Geom2dCircle::getCircleCenter(firstPoint, secondPoint, onSketchPos); radius = (onSketchPos - centerPoint).Length(); double angle1 = (firstPoint - centerPoint).Angle(); @@ -248,16 +244,16 @@ private: if (constructionMethod() == ConstructionMethod::Center) { startAngle = startAngleBackup; toolWidgetManager.drawDoubleAtCursor(onSketchPos, arcAngle, Base::Unit::Angle); - seekAndRenderAutoConstraint(sugConstraints[2], - onSketchPos, - Base::Vector2d(0.0, 0.0)); + seekAndRenderAutoConstraint(sugConstraints[2], onSketchPos, Base::Vector2d(0.0, 0.0)); } else { toolWidgetManager.drawPositionAtCursor(onSketchPos); - seekAndRenderAutoConstraint(sugConstraints[2], - onSketchPos, - Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[2], + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE + ); } } break; @@ -294,11 +290,14 @@ private: QT_TRANSLATE_NOOP("Notifications", "Failed to add arc"));*/ Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -314,29 +313,35 @@ private: generateAutoConstraintsOnElement( ac1, ArcGeoId, - Sketcher::PointPos::mid); // add auto constraints for the center point - generateAutoConstraintsOnElement(ac2, - ArcGeoId, - (arcAngle > 0) ? Sketcher::PointPos::start - : Sketcher::PointPos::end); - generateAutoConstraintsOnElement(ac3, - ArcGeoId, - (arcAngle > 0) ? Sketcher::PointPos::end - : Sketcher::PointPos::start); + Sketcher::PointPos::mid + ); // add auto constraints for the center point + generateAutoConstraintsOnElement( + ac2, + ArcGeoId, + (arcAngle > 0) ? Sketcher::PointPos::start : Sketcher::PointPos::end + ); + generateAutoConstraintsOnElement( + ac3, + ArcGeoId, + (arcAngle > 0) ? Sketcher::PointPos::end : Sketcher::PointPos::start + ); } else { generateAutoConstraintsOnElement( ac1, ArcGeoId, - arcPos1); // add auto constraints for the second picked point + arcPos1 + ); // add auto constraints for the second picked point generateAutoConstraintsOnElement( ac2, ArcGeoId, - arcPos2); // add auto constraints for thesecond picked point + arcPos2 + ); // add auto constraints for thesecond picked point generateAutoConstraintsOnElement( ac3, ArcGeoId, - Sketcher::PointPos::none); // add auto constraints for the third picked point + Sketcher::PointPos::none + ); // add auto constraints for the third picked point } // Ensure temporary autoconstraints do not generate a redundancy and that the geometry @@ -432,11 +437,13 @@ private: return; } - addArcToShapeGeometry(toVector3d(centerPoint), - startAngle, - endAngle, - radius, - isConstructionMode()); + addArcToShapeGeometry( + toVector3d(centerPoint), + startAngle, + endAngle, + radius, + isConstructionMode() + ); } if (onlyeditoutline) { @@ -445,38 +452,48 @@ private: const double scale = 0.8; addLineToShapeGeometry( toVector3d(centerPoint), - Base::Vector3d(centerPoint.x + cos(startAngle) * scale * radius, - centerPoint.y + sin(startAngle) * scale * radius, - 0.), - isConstructionMode()); + Base::Vector3d( + centerPoint.x + cos(startAngle) * scale * radius, + centerPoint.y + sin(startAngle) * scale * radius, + 0. + ), + isConstructionMode() + ); addLineToShapeGeometry( toVector3d(centerPoint), - Base::Vector3d(centerPoint.x + cos(endAngle) * scale * radius, - centerPoint.y + sin(endAngle) * scale * radius, - 0.), - isConstructionMode()); + Base::Vector3d( + centerPoint.x + cos(endAngle) * scale * radius, + centerPoint.y + sin(endAngle) * scale * radius, + 0. + ), + isConstructionMode() + ); } } else { if (state() == SelectMode::SeekSecond) { - addLineToShapeGeometry(toVector3d(firstPoint), - toVector3d(secondPoint), - isConstructionMode()); + addLineToShapeGeometry( + toVector3d(firstPoint), + toVector3d(secondPoint), + isConstructionMode() + ); } else if (state() == SelectMode::SeekThird) { const double scale = 0.8; - addLineToShapeGeometry(toVector3d(centerPoint), - toVector3d(centerPoint) - + (toVector3d(secondPoint) - toVector3d(centerPoint)) - * scale, - isConstructionMode()); + addLineToShapeGeometry( + toVector3d(centerPoint), + toVector3d(centerPoint) + + (toVector3d(secondPoint) - toVector3d(centerPoint)) * scale, + isConstructionMode() + ); - addLineToShapeGeometry(toVector3d(centerPoint), - toVector3d(centerPoint) - + (toVector3d(firstPoint) - toVector3d(centerPoint)) - * scale, - isConstructionMode()); + addLineToShapeGeometry( + toVector3d(centerPoint), + toVector3d(centerPoint) + + (toVector3d(firstPoint) - toVector3d(centerPoint)) * scale, + isConstructionMode() + ); } } } @@ -513,29 +530,35 @@ template<> void DSHArcController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - QStringList names = {QApplication::translate("Sketcher_CreateArc", "Center"), - QApplication::translate("Sketcher_CreateArc", "3 rim points")}; + QStringList names = { + QApplication::translate("Sketcher_CreateArc", "Center"), + QApplication::translate("Sketcher_CreateArc", "3 rim points") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArc") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointArc") + ); } } @@ -552,13 +575,16 @@ void DSHArcController::configureToolWidget() else { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } } @@ -812,8 +838,7 @@ void DSHArcController::addConstraints() auto p5set = onViewParameters[OnViewParameter::Fifth]->isSet; - PointPos pos1 = - handler->constructionMethod() == DrawSketchHandlerArc::ConstructionMethod::Center + PointPos pos1 = handler->constructionMethod() == DrawSketchHandlerArc::ConstructionMethod::Center ? PointPos::mid : handler->arcPos1; @@ -826,31 +851,29 @@ void DSHArcController::addConstraints() }; auto constraintp3radius = [&]() { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve, - fabs(p3)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve, + fabs(p3) + ); }; auto constraintp5angle = [&]() { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%f)) ", - firstCurve, - fabs(handler->arcAngle)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%f)) ", + firstCurve, + fabs(handler->arcAngle) + ); }; auto constraintp3x = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, handler->arcPos2), - GeoElementId::VAxis, - p3, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, handler->arcPos2), GeoElementId::VAxis, p3, obj); }; auto constraintp4y = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, handler->arcPos2), - GeoElementId::HAxis, - p4, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, handler->arcPos2), GeoElementId::HAxis, p4, obj); }; @@ -879,10 +902,12 @@ void DSHArcController::addConstraints() } else { if (p3set && p4set && p3 == 0. && p4 == 0.) { - ConstraintToAttachment(GeoElementId(firstCurve, handler->arcPos2), - GeoElementId::RtPnt, - 0., - obj); + ConstraintToAttachment( + GeoElementId(firstCurve, handler->arcPos2), + GeoElementId::RtPnt, + 0., + obj + ); } else { if (p3set) { diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h index 14bf10d685..ac820852c6 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h @@ -75,9 +75,9 @@ public: if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); - seekAndRenderAutoConstraint(sugConstr1, - onSketchPos, - Base::Vector2d(0.f, 0.f)); // TODO: ellipse prio 1 + seekAndRenderAutoConstraint(sugConstr1, onSketchPos, Base::Vector2d(0.f, 0.f)); // TODO: + // ellipse + // prio 1 } else if (Mode == STATUS_SEEK_Second) { double rx0 = onSketchPos.x - EditCurve[0].x; @@ -102,10 +102,12 @@ public: } drawEdit(EditCurve); - seekAndRenderAutoConstraint(sugConstr2, - onSketchPos, - onSketchPos - centerPoint, - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstr2, + onSketchPos, + onSketchPos - centerPoint, + AutoConstraint::CURVE + ); } else if (Mode == STATUS_SEEK_Third) { // angle between the major axis of the ellipse and the X axis @@ -113,9 +115,10 @@ public: 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 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)); @@ -149,21 +152,28 @@ public: // 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))); + / (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))) + 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) * pi; @@ -184,10 +194,7 @@ public: std::string aString = lengthToDisplayFormat(a, 1); std::string bString = lengthToDisplayFormat(b, 1); std::string angleString = angleToDisplayFormat(arcAngle * 180.0 / 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); } @@ -243,16 +250,21 @@ public: // 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))); + / (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))) + 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) * pi; @@ -298,34 +310,34 @@ public: 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, - constructionModeAsBooleanText()); + 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, + constructionModeAsBooleanText() + ); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "exposeInternalGeometry(%d)", - currentgeoid); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception&) { Gui::NotifyError( sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc of ellipse")); + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc of ellipse") + ); Gui::Command::abortCommand(); tryAutoRecomputeIfNotSolve(sketchgui->getObject()); @@ -349,26 +361,29 @@ 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(sketchgui->getObject()); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { // This code enables the continuous creation mode. diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h index 39503a7b2e..2afe622653 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h @@ -85,10 +85,12 @@ public: } drawEdit(EditCurve); - seekAndRenderAutoConstraint(sugConstr2, - onSketchPos, - Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstr2, + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE + ); } else if (Mode == STATUS_SEEK_Third) { // angle between the major axis of the hyperbola and the X axis @@ -96,9 +98,11 @@ public: 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 angleatpoint = acosh( + ((onSketchPos.x - centerPoint.x) * cos(phi) + + (onSketchPos.y - centerPoint.y) * sin(phi)) + / a + ); double b = ((onSketchPos.y - centerPoint.y) * cos(phi) - (onSketchPos.x - centerPoint.x) * sin(phi)) / sinh(angleatpoint); @@ -132,9 +136,11 @@ public: 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 angleatstartingpoint = acosh( + ((startingPoint.x - centerPoint.x) * cos(phi) + + (startingPoint.y - centerPoint.y) * sin(phi)) + / a + ); double b = ((startingPoint.y - centerPoint.y) * cos(phi) - (startingPoint.x - centerPoint.x) * sin(phi)) / sinh(angleatstartingpoint); @@ -144,12 +150,14 @@ public: // 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; @@ -230,9 +238,11 @@ public: 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 angleatstartingpoint = acosh( + ((startingPoint.x - centerPoint.x) * cos(phi) + + (startingPoint.y - centerPoint.y) * sin(phi)) + / a + ); double b = ((startingPoint.y - centerPoint.y) * cos(phi) - (startingPoint.x - centerPoint.x) * sin(phi)) @@ -246,9 +256,9 @@ public: 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)); + / (((endPoint.x - centerPoint.x) * cos(phi) + (endPoint.y - centerPoint.y) * sin(phi)) + * b) + ); if (boost::math::isnan(startAngle) || boost::math::isnan(endAngle)) { Gui::NotifyError( @@ -256,7 +266,9 @@ public: QT_TRANSLATE_NOOP("Notifications", "Error"), QT_TRANSLATE_NOOP( "Notifications", - "Cannot create arc of hyperbola from invalid angles, try again!")); + "Cannot create arc of hyperbola from invalid angles, try again!" + ) + ); sketchgui->purgeHandler(); return false; } @@ -303,37 +315,37 @@ public: 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, - constructionModeAsBooleanText()); + 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, + constructionModeAsBooleanText() + ); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "exposeInternalGeometry(%d)", - currentgeoid); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception&) { Gui::NotifyError( sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of hyperbola")); + QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of hyperbola") + ); Gui::Command::abortCommand(); tryAutoRecomputeIfNotSolve(sketchgui->getObject()); @@ -357,26 +369,29 @@ 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(sketchgui->getObject()); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h index 9edaf33fcd..72834977f4 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h @@ -102,8 +102,9 @@ public: // 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; @@ -136,13 +137,15 @@ public: // 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; @@ -209,8 +212,9 @@ public: 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 startAngle = ustartpoint; @@ -230,33 +234,33 @@ public: 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, - constructionModeAsBooleanText()); + 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, + constructionModeAsBooleanText() + ); currentgeoid++; - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "exposeInternalGeometry(%d)", - currentgeoid); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } catch (const Base::Exception&) { Gui::NotifyError( sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of parabola")); + QT_TRANSLATE_NOOP("Notifications", "Cannot create arc of parabola") + ); Gui::Command::abortCommand(); tryAutoRecomputeIfNotSolve(sketchgui->getObject()); @@ -280,26 +284,29 @@ 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(sketchgui->getObject()); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { // This code enables the continuous creation mode. diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcSlot.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcSlot.h index 5522fb17cf..06defae1b3 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcSlot.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcSlot.h @@ -57,18 +57,18 @@ enum class ArcSlotConstructionMethod End // Must be the last one }; -} +} // namespace ConstructionMethods -using DSHArcSlotController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT - ConstructionMethods::ArcSlotConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHArcSlotController = DrawSketchDefaultWidgetController< + DrawSketchHandlerArcSlot, + StateMachines::FourSeekEnd, + /*PAutoConstraintSize =*/3, // NOLINT + /*OnViewParametersT =*/OnViewParameters<6, 6>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT + ConstructionMethods::ArcSlotConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHArcSlotControllerBase = DSHArcSlotController::ControllerBase; @@ -137,9 +137,7 @@ private: centerPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { toolWidgetManager.drawDirectionAtCursor(onSketchPos, centerPoint); @@ -151,9 +149,7 @@ private: CreateAndDrawShapeGeometry(); - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[1], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekThird: { endPoint = centerPoint + (onSketchPos - centerPoint).Normalize() * radius; @@ -178,9 +174,7 @@ private: toolWidgetManager.drawDoubleAtCursor(onSketchPos, arcAngle, Base::Unit::Angle); - seekAndRenderAutoConstraint(sugConstraints[2], - onSketchPos, - Base::Vector2d(0.0, 0.0)); + seekAndRenderAutoConstraint(sugConstraints[2], onSketchPos, Base::Vector2d(0.0, 0.0)); } break; case SelectMode::SeekFourth: { @@ -212,16 +206,21 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc slot")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc slot") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -233,25 +232,24 @@ private: generateAutoConstraintsOnElement( sugConstraints[0], getHighestCurveIndex() - 3, - Sketcher::PointPos::mid); // add auto constraints for the center point + Sketcher::PointPos::mid + ); // add auto constraints for the center point if (constructionMethod() == ConstructionMethod::ArcSlot) { - generateAutoConstraintsOnElement(ac2, - getHighestCurveIndex() - 2, - Sketcher::PointPos::mid); - generateAutoConstraintsOnElement(ac3, - getHighestCurveIndex() - 1, - Sketcher::PointPos::mid); + generateAutoConstraintsOnElement(ac2, getHighestCurveIndex() - 2, Sketcher::PointPos::mid); + generateAutoConstraintsOnElement(ac3, getHighestCurveIndex() - 1, Sketcher::PointPos::mid); } else { - generateAutoConstraintsOnElement(ac2, - getHighestCurveIndex() - 3, - (arcAngle > 0) ? Sketcher::PointPos::start - : Sketcher::PointPos::end); - generateAutoConstraintsOnElement(ac3, - getHighestCurveIndex() - 3, - (arcAngle > 0) ? Sketcher::PointPos::end - : Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + ac2, + getHighestCurveIndex() - 3, + (arcAngle > 0) ? Sketcher::PointPos::start : Sketcher::PointPos::end + ); + generateAutoConstraintsOnElement( + ac3, + getHighestCurveIndex() - 3, + (arcAngle > 0) ? Sketcher::PointPos::end : Sketcher::PointPos::start + ); } // Ensure temporary autoconstraints do not generate a redundancy and that the geometry @@ -362,38 +360,48 @@ private: } if (constructionMethod() == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { - addArcToShapeGeometry(toVector3d(centerPoint), - startAngle, - endAngle, - radius + r, - isConstructionMode()); + addArcToShapeGeometry( + toVector3d(centerPoint), + startAngle, + endAngle, + radius + r, + isConstructionMode() + ); - addArcToShapeGeometry(toVector3d(startPoint), - angleReversed ? endAngle : startAngle + pi, - angleReversed ? endAngle + pi : startAngle + 2 * pi, - r, - isConstructionMode()); + addArcToShapeGeometry( + toVector3d(startPoint), + angleReversed ? endAngle : startAngle + pi, + angleReversed ? endAngle + pi : startAngle + 2 * pi, + r, + isConstructionMode() + ); - addArcToShapeGeometry(toVector3d(endPoint), - angleReversed ? startAngle + pi : endAngle, - angleReversed ? startAngle + 2 * pi : pi + endAngle, - r, - isConstructionMode()); + addArcToShapeGeometry( + toVector3d(endPoint), + angleReversed ? startAngle + pi : endAngle, + angleReversed ? startAngle + 2 * pi : pi + endAngle, + r, + isConstructionMode() + ); if (radius - r > Precision::Confusion()) { - addArcToShapeGeometry(toVector3d(centerPoint), - startAngle, - endAngle, - radius - r, - isConstructionMode()); + addArcToShapeGeometry( + toVector3d(centerPoint), + startAngle, + endAngle, + radius - r, + isConstructionMode() + ); } } else { - Part::GeomArcOfCircle* arc1 = addArcToShapeGeometry(toVector3d(centerPoint), - startAngle, - endAngle, - radius, - isConstructionMode()); + Part::GeomArcOfCircle* arc1 = addArcToShapeGeometry( + toVector3d(centerPoint), + startAngle, + endAngle, + radius, + isConstructionMode() + ); Base::Vector3d p11 = arc1->getStartPoint(); Base::Vector3d p12 = arc1->getEndPoint(); @@ -429,42 +437,40 @@ private: if (constructionMethod() == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { bool allArcs = fabs(radius - r) > Precision::Confusion(); - Sketcher::PointPos pos1 = - angleReversed ? Sketcher::PointPos::start : Sketcher::PointPos::end; - Sketcher::PointPos pos2 = - angleReversed ? Sketcher::PointPos::end : Sketcher::PointPos::start; + Sketcher::PointPos pos1 = angleReversed ? Sketcher::PointPos::start + : Sketcher::PointPos::end; + Sketcher::PointPos pos2 = angleReversed ? Sketcher::PointPos::end + : Sketcher::PointPos::start; if (allArcs) { - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::mid, - firstCurve + 3, - Sketcher::PointPos::mid); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::mid, + firstCurve + 3, + Sketcher::PointPos::mid + ); - addToShapeConstraints(Sketcher::Tangent, - firstCurve + 3, - pos1, - firstCurve + 2, - pos1); + addToShapeConstraints(Sketcher::Tangent, firstCurve + 3, pos1, firstCurve + 2, pos1); - addToShapeConstraints(Sketcher::Tangent, - firstCurve + 3, - pos2, - firstCurve + 1, - pos2); + addToShapeConstraints(Sketcher::Tangent, firstCurve + 3, pos2, firstCurve + 1, pos2); } else { - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::mid, - firstCurve + 1, - pos2); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::mid, + firstCurve + 1, + pos2 + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::mid, - firstCurve + 2, - pos1); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::mid, + firstCurve + 2, + pos1 + ); } addToShapeConstraints(Sketcher::Tangent, firstCurve, pos1, firstCurve + 2, pos2); @@ -474,62 +480,80 @@ private: else { bool allGeos = r > Precision::Confusion(); - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve, - Sketcher::PointPos::none, - firstCurve + 1, - Sketcher::PointPos::none); + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve, + Sketcher::PointPos::none, + firstCurve + 1, + Sketcher::PointPos::none + ); - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve, - Sketcher::PointPos::none, - firstCurve + 2, - Sketcher::PointPos::none); + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve, + Sketcher::PointPos::none, + firstCurve + 2, + Sketcher::PointPos::none + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::start, - firstCurve + 1, - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::start, + firstCurve + 1, + Sketcher::PointPos::start + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::end, - firstCurve + 2, - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::end, + firstCurve + 2, + Sketcher::PointPos::start + ); if (allGeos) { - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::mid, - firstCurve + 3, - Sketcher::PointPos::mid); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::mid, + firstCurve + 3, + Sketcher::PointPos::mid + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 3, - Sketcher::PointPos::start, - firstCurve + 1, - Sketcher::PointPos::end); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 3, + Sketcher::PointPos::start, + firstCurve + 1, + Sketcher::PointPos::end + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 3, - Sketcher::PointPos::end, - firstCurve + 2, - Sketcher::PointPos::end); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 3, + Sketcher::PointPos::end, + firstCurve + 2, + Sketcher::PointPos::end + ); } else { - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::mid, - firstCurve + 1, - Sketcher::PointPos::end); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::mid, + firstCurve + 1, + Sketcher::PointPos::end + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve, - Sketcher::PointPos::mid, - firstCurve + 2, - Sketcher::PointPos::end); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve, + Sketcher::PointPos::mid, + firstCurve + 2, + Sketcher::PointPos::end + ); } } } @@ -581,29 +605,35 @@ template<> void DSHArcSlotController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - QStringList names = {QApplication::translate("Sketcher_CreateArcSlot", "Arc ends"), - QApplication::translate("Sketcher_CreateArcSlot", "Flat ends")}; + QStringList names = { + QApplication::translate("Sketcher_CreateArcSlot", "Arc ends"), + QApplication::translate("Sketcher_CreateArcSlot", "Flat ends") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArcSlot_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArcSlot_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangleSlot_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangleSlot_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArcSlot")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateArcSlot") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangleSlot")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangleSlot") + ); } } @@ -611,23 +641,28 @@ void DSHArcSlotController::configureToolWidget() onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); if (handler->constructionMethod() == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { onViewParameters[OnViewParameter::Sixth]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } else { onViewParameters[OnViewParameter::Sixth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } } @@ -708,8 +743,8 @@ void DSHArcSlotControllerBase::doEnforceControlParameters(Base::Vector2d& onSket unsetOnViewParameter(sixthParam.get()); } else { - onSketchPos = - handler->centerPoint + Base::Vector2d(handler->radius + radius2, 0.); + onSketchPos = handler->centerPoint + + Base::Vector2d(handler->radius + radius2, 0.); } } } break; @@ -788,8 +823,8 @@ void DSHArcSlotController::adaptParameters(Base::Vector2d onSketchPos) } Base::Vector3d start = toVector3d(handler->endPoint); - Base::Vector3d end = - start + (start - toVector3d(handler->centerPoint)).Normalize() * dist; + Base::Vector3d end = start + + (start - toVector3d(handler->centerPoint)).Normalize() * dist; sixthParam->setPoints(start, end); } break; @@ -857,67 +892,66 @@ void DSHArcSlotController::addConstraints() auto slotRadiusSet = onViewParameters[OnViewParameter::Sixth]->isSet; auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::VAxis, - x0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), GeoElementId::VAxis, x0, obj); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::HAxis, - y0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), GeoElementId::HAxis, y0, obj); }; auto constraintRadius = [&]() { - if (handler->constructionMethod() - == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", - firstCurve, - 3, - firstCurve + 2, - 3, - fabs(radius)); + if (handler->constructionMethod() == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", + firstCurve, + 3, + firstCurve + 2, + 3, + fabs(radius) + ); } else { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve, - fabs(radius)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve, + fabs(radius) + ); } }; auto constraintArcAngle = [&]() { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%f)) ", - firstCurve, - fabs(handler->arcAngle)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%f)) ", + firstCurve, + fabs(handler->arcAngle) + ); }; auto constraintSlotRadius = [&]() { - if (handler->constructionMethod() - == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve + 2, - fabs(slotRadius)); + if (handler->constructionMethod() == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve + 2, + fabs(slotRadius) + ); } else { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%f)) ", - firstCurve + 2, - fabs(slotRadius)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%f)) ", + firstCurve + 2, + fabs(slotRadius) + ); } }; if (handler->AutoConstraints.empty()) { // No valid diagnosis. Every constraint can be added. if (x0set && y0set && x0 == 0. && y0 == 0.) { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::RtPnt, - 0., - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), GeoElementId::RtPnt, 0., obj); } else { if (x0set) { @@ -986,8 +1020,7 @@ void DSHArcSlotController::addConstraints() DoFs = startpointinfo.getDoFs(); DoFs += endpointinfo.getDoFs(); - if (handler->constructionMethod() - == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { + if (handler->constructionMethod() == DrawSketchHandlerArcSlot::ConstructionMethod::ArcSlot) { midpointinfo = handler->getPointInfo(GeoElementId(firstCurve + 2, PointPos::mid)); DoFs += midpointinfo.getDoFs(); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h index 0c06769886..acdf2f70b9 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h @@ -54,18 +54,18 @@ enum class BSplineConstructionMethod Knots, End // Must be the last one }; -} +} // namespace ConstructionMethods -using DSHBSplineController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<1, 1>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<1, 1>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT - ConstructionMethods::BSplineConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHBSplineController = DrawSketchDefaultWidgetController< + DrawSketchHandlerBSpline, + /*SelectModeT*/ StateMachines::TwoSeekEnd, + /*PAutoConstraintSize =*/2, + /*OnViewParametersT =*/OnViewParameters<4, 4>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<1, 1>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<1, 1>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT + ConstructionMethods::BSplineConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHBSplineControllerBase = DSHBSplineController::ControllerBase; @@ -80,7 +80,8 @@ class DrawSketchHandlerBSpline: public DrawSketchHandlerBSplineBase public: explicit DrawSketchHandlerBSpline( ConstructionMethod constrMethod = ConstructionMethod::ControlPoints, - bool periodic = false) + bool periodic = false + ) : DrawSketchHandlerBSplineBase(constrMethod) , SplineDegree(3) , periodic(periodic) @@ -103,9 +104,7 @@ private: case SelectMode::SeekFirst: { toolWidgetManager.drawPositionAtCursor(onSketchPos); - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { toolWidgetManager.drawDirectionAtCursor(onSketchPos, getLastPoint()); @@ -116,9 +115,7 @@ private: catch (const Base::ValueError&) { } // equal points while hovering raise an objection that can be safely ignored - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[1], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; default: break; @@ -181,9 +178,7 @@ private: 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); } else { int myDegree = 3; @@ -206,13 +201,11 @@ private: streams.back() << "App.Vector(" << points[i].x << "," << points[i].y << "),"; if (multiplicities[i] >= myDegree) { streams.emplace_back(); - streams.back() - << "App.Vector(" << points[i].x << "," << points[i].y << "),"; + streams.back() << "App.Vector(" << points[i].x << "," << points[i].y << "),"; } } // The last point - streams.back() << "App.Vector(" << points.back().x << "," << points.back().y - << "),"; + streams.back() << "App.Vector(" << points.back().x << "," << points.back().y << "),"; // Note the plural of plurals. Each element is a separate sequence. std::vector controlpointses; @@ -251,9 +244,11 @@ private: Gui::Command::runCommand(Gui::Command::Gui, "_bsps = []"); for (auto& controlpoints : controlpointses) { // TODO: variable degrees? - QString cmdstr = QStringLiteral("_bsps.append(Part.BSplineCurve())\n" - "_bsps[-1].interpolate(%1, PeriodicFlag=%2)\n" - "_bsps[-1].increaseDegree(%3)") + QString cmdstr = QStringLiteral( + "_bsps.append(Part.BSplineCurve())\n" + "_bsps[-1].interpolate(%1, PeriodicFlag=%2)\n" + "_bsps[-1].increaseDegree(%3)" + ) .arg(QString::fromLatin1(controlpoints.c_str())) .arg(QString::fromLatin1(periodic ? "True" : "False")) .arg(myDegree); @@ -261,26 +256,37 @@ private: // Adjust internal knots here (raise multiplicity) // How this contributes to the final B-spline if (controlpoints == controlpointses.front()) { - Gui::Command::runCommand(Gui::Command::Gui, - "_finalbsp_poles.extend(_bsps[-1].getPoles())"); - Gui::Command::runCommand(Gui::Command::Gui, - "_finalbsp_knots.extend(_bsps[-1].getKnots())"); Gui::Command::runCommand( Gui::Command::Gui, - "_finalbsp_mults.extend(_bsps[-1].getMultiplicities())"); + "_finalbsp_poles.extend(_bsps[-1].getPoles())" + ); + Gui::Command::runCommand( + Gui::Command::Gui, + "_finalbsp_knots.extend(_bsps[-1].getKnots())" + ); + Gui::Command::runCommand( + Gui::Command::Gui, + "_finalbsp_mults.extend(_bsps[-1].getMultiplicities())" + ); } else { Gui::Command::runCommand( Gui::Command::Gui, - "_finalbsp_poles.extend(_bsps[-1].getPoles()[1:])"); - Gui::Command::runCommand(Gui::Command::Gui, - "_finalbsp_knots.extend([_finalbsp_knots[-1] + i " - "for i in _bsps[-1].getKnots()[1:]])"); - Gui::Command::runCommand(Gui::Command::Gui, - "_finalbsp_mults[-1] = 3"); // FIXME: Hardcoded + "_finalbsp_poles.extend(_bsps[-1].getPoles()[1:])" + ); Gui::Command::runCommand( Gui::Command::Gui, - "_finalbsp_mults.extend(_bsps[-1].getMultiplicities()[1:])"); + "_finalbsp_knots.extend([_finalbsp_knots[-1] + i " + "for i in _bsps[-1].getKnots()[1:]])" + ); + Gui::Command::runCommand( + Gui::Command::Gui, + "_finalbsp_mults[-1] = 3" + ); // FIXME: Hardcoded + Gui::Command::runCommand( + Gui::Command::Gui, + "_finalbsp_mults.extend(_bsps[-1].getMultiplicities()[1:])" + ); } } @@ -292,7 +298,8 @@ private: "(_finalbsp_poles,_finalbsp_mults,_finalbsp_knots,%s,%d,None,False),%s)", periodic ? "True" : "False", myDegree, - constructionModeAsBooleanText()); + constructionModeAsBooleanText() + ); currentgeoid++; // TODO: Confirm we do not need to delete individual elements @@ -348,11 +355,13 @@ private: // Change the knot multiplicity here because the user asked and it's not C0 // NOTE: The knot number here has to be provided in the OCCT ordering. if (multiplicities[i] > 1 && multiplicities[i] < myDegree) { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "modifyBSplineKnotMultiplicity(%d, %d, %d) ", - currentgeoid, - knotNumber + 1, - multiplicities[i] - 1); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "modifyBSplineKnotMultiplicity(%d, %d, %d) ", + currentgeoid, + knotNumber + 1, + multiplicities[i] - 1 + ); } knotNumber++; } @@ -365,17 +374,17 @@ private: Gui::Command::doCommand(Gui::Command::Doc, cstream.str().c_str()); // for showing the rest of internal geometry on creation - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "exposeInternalGeometry(%d)", - currentgeoid); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", currentgeoid); } Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error creating B-spline")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error creating B-spline") + ); Gui::Command::abortCommand(); tryAutoRecomputeIfNotSolve(sketchgui->getSketchObject()); @@ -532,9 +541,8 @@ private: } else { // The coincidence with first point may be indirect - const auto coincidents = - sketchgui->getSketchObject()->getAllCoincidentPoints(ac.GeoId, - ac.PosId); + const auto coincidents + = sketchgui->getSketchObject()->getAllCoincidentPoints(ac.GeoId, ac.PosId); if (coincidents.find(geoIds[0]) != coincidents.end()) { isClosed = true; } @@ -657,9 +665,11 @@ private: updateDataAndDrawToPosition(prevCursorPosition); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error deleting last pole/knot")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error deleting last pole/knot") + ); // some commands might have already deleted some constraints/geometries but not // others Gui::Command::abortCommand(); @@ -708,28 +718,35 @@ private: ? "addGeometry(Part.Circle(App.Vector(%f,%f,0),App.Vector(0,0,1),10),True)" : "addGeometry(Part.Point(App.Vector(%f,%f,0)),True)", pos.x, - pos.y); + pos.y + ); if (constructionMethod() == ConstructionMethod::ControlPoints) { if (firstPoint) { // First pole defaults to 1.0 weight - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Weight',%d,%f)) ", - geoId, - 1.0); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Weight',%d,%f)) ", + geoId, + 1.0 + ); } else { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Equal',%d,%d)) ", - geoIds[0], - geoId); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Equal',%d,%d)) ", + geoIds[0], + geoId + ); } } } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Error adding B-spline pole/knot")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Error adding B-spline pole/knot") + ); Gui::Command::abortCommand(); @@ -821,12 +838,14 @@ private: mults.resize(vSize + 1, 1); } - auto bSpline = std::make_unique(bsplinePoints3D, - weights, - knots, - mults, - degree, - periodic); + auto bSpline = std::make_unique( + bsplinePoints3D, + weights, + knots, + mults, + degree, + periodic + ); bSpline->setPoles(bsplinePoints3D); Sketcher::GeometryFacade::setConstruction(bSpline.get(), isConstructionMode()); ShapeGeometry.emplace_back(std::move(bSpline)); @@ -908,51 +927,62 @@ void DSHBSplineController::configureToolWidget() if (!init) { // Code to be executed only upon initialisation toolWidget->setNoticeVisible(true); toolWidget->setNoticeText( - QApplication::translate("TaskSketcherTool_c1_bspline", "Press F to undo last point.")); + QApplication::translate("TaskSketcherTool_c1_bspline", "Press F to undo last point.") + ); QStringList names = { QApplication::translate("Sketcher_CreateBSpline", "From control points"), - QApplication::translate("Sketcher_CreateBSpline", "From knots")}; + QApplication::translate("Sketcher_CreateBSpline", "From knots") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); toolWidget->setCheckboxLabel( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_bspline", "Periodic (R)")); + QApplication::translate("TaskSketcherTool_c1_bspline", "Periodic (R)") + ); toolWidget->setCheckboxToolTip( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_bspline", "Create a periodic B-spline.")); + QApplication::translate("TaskSketcherTool_c1_bspline", "Create a periodic B-spline.") + ); syncCheckboxToHandler(WCheckbox::FirstBox, handler->periodic); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation_Constr") + ); toolWidget->setCheckboxIcon( WCheckbox::FirstBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSplineByInterpolation") + ); toolWidget->setCheckboxIcon( WCheckbox::FirstBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create_Periodic_BSpline") + ); } toolWidget->setParameterLabel( WParameter::First, - QApplication::translate("ToolWidgetManager_p4", "Degree (+'U'/ -'J')")); + QApplication::translate("ToolWidgetManager_p4", "Degree (+'U'/ -'J')") + ); toolWidget->configureParameterUnit(WParameter::First, Base::Unit()); toolWidget->configureParameterMin(WParameter::First, 1.0); // NOLINT toolWidget->configureParameterMax(WParameter::First, Geom_BSplineCurve::MaxDegree()); @@ -973,10 +1003,12 @@ void DSHBSplineController::configureToolWidget() onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } template<> @@ -1112,9 +1144,11 @@ void DSHBSplineController::adaptParameters(Base::Vector2d onSketchPos) double range = (onSketchPos - prevPoint).Angle(); if (!fourthParam->isSet) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(range), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(range), + Base::Unit::Angle + ); } thirdParam->setPoints(start, end); @@ -1230,7 +1264,8 @@ void DSHBSplineController::addConstraints() static_cast(pPos), handler->geoIds[i + 1], static_cast(pPos), - handler->distances[i + 1]); + handler->distances[i + 1] + ); } } }; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h index 89d4b4fc68..d464f182bb 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h @@ -62,11 +62,13 @@ public: 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)); + 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; @@ -75,38 +77,45 @@ public: 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; @@ -155,8 +164,9 @@ public: 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"); } @@ -167,10 +177,12 @@ public: try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create a carbon copy")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "carbonCopy(\"%s\",%s)", - msg.pObjectName, - constructionModeAsBooleanText()); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "carbonCopy(\"%s\",%s)", + msg.pObjectName, + constructionModeAsBooleanText() + ); Gui::Command::commitCommand(); @@ -186,7 +198,8 @@ public: Gui::NotifyError( sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add carbon copy")); + QT_TRANSLATE_NOOP("Notifications", "Failed to add carbon copy") + ); Gui::Command::abortCommand(); } return true; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h index 440f3371f1..e01d9a05b7 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h @@ -48,16 +48,16 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerCircle; -using DSHCircleController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT - ConstructionMethods::CircleEllipseConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHCircleController = DrawSketchDefaultWidgetController< + DrawSketchHandlerCircle, + /*SelectModeT*/ StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/3, + /*OnViewParametersT =*/OnViewParameters<3, 6>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT + ConstructionMethods::CircleEllipseConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHCircleControllerBase = DSHCircleController::ControllerBase; @@ -137,10 +137,12 @@ private: else { firstPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[0], + onSketchPos, + Base::Vector2d(), + AutoConstraint::CURVE + ); } } break; case SelectMode::SeekSecond: { @@ -160,12 +162,13 @@ private: toolWidgetManager.drawPositionAtCursor(onSketchPos); } - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - constructionMethod() == ConstructionMethod::Center - ? onSketchPos - centerPoint - : Base::Vector2d(), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[1], + onSketchPos, + constructionMethod() == ConstructionMethod::Center ? onSketchPos - centerPoint + : Base::Vector2d(), + AutoConstraint::CURVE + ); } break; case SelectMode::SeekThird: { try { @@ -174,8 +177,8 @@ private: return; } - centerPoint = - Part::Geom2dCircle::getCircleCenter(firstPoint, secondPoint, onSketchPos); + centerPoint + = Part::Geom2dCircle::getCircleCenter(firstPoint, secondPoint, onSketchPos); radius = (onSketchPos - centerPoint).Length(); @@ -183,10 +186,12 @@ private: CreateAndDrawShapeGeometry(); - seekAndRenderAutoConstraint(sugConstraints[2], - onSketchPos, - Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[2], + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE + ); } catch (Base::ValueError& e) { e.reportException(); @@ -209,16 +214,21 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add circle")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add circle") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -233,11 +243,13 @@ private: generateAutoConstraintsOnElement( ac1, CircleGeoId, - Sketcher::PointPos::mid); // add auto constraints for the center point + Sketcher::PointPos::mid + ); // add auto constraints for the center point generateAutoConstraintsOnElement( ac2, CircleGeoId, - Sketcher::PointPos::none); // add auto constraints for the edge + Sketcher::PointPos::none + ); // add auto constraints for the edge } else { @@ -248,15 +260,18 @@ private: generateAutoConstraintsOnElement( ac1, CircleGeoId, - Sketcher::PointPos::none); // add auto constraints for the first point + Sketcher::PointPos::none + ); // add auto constraints for the first point generateAutoConstraintsOnElement( ac2, CircleGeoId, - Sketcher::PointPos::none); // add auto constraints for the second point + Sketcher::PointPos::none + ); // add auto constraints for the second point generateAutoConstraintsOnElement( ac3, CircleGeoId, - Sketcher::PointPos::none); // add auto constraints for the second point + Sketcher::PointPos::none + ); // add auto constraints for the second point } // Ensure temporary autoconstraints do not generate a redundancy and that the geometry @@ -368,8 +383,7 @@ auto DSHCircleControllerBase::getState(int labelindex) const return SelectMode::SeekSecond; break; default: - THROWM(Base::ValueError, - "OnViewParameter index without an associated machine state") + THROWM(Base::ValueError, "OnViewParameter index without an associated machine state") } } else { // ConstructionMethod::ThreeRim @@ -396,34 +410,41 @@ template<> void DSHCircleController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - QStringList names = {QApplication::translate("Sketcher_CreateCircle", "Center"), - QApplication::translate("Sketcher_CreateCircle", "3 rim points")}; + QStringList names = { + QApplication::translate("Sketcher_CreateCircle", "Center"), + QApplication::translate("Sketcher_CreateCircle", "3 rim points") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateCircle") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle")); + Gui::BitmapFactory().iconFromTheme("Sketcher_Create3PointCircle") + ); } ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); bool dimensioningDiameter = hGrp->GetBool("DimensioningDiameter", true); bool dimensioningRadius = hGrp->GetBool("DimensioningRadius", true); @@ -444,19 +465,22 @@ void DSHCircleController::configureToolWidget() } else { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); bool dimensioningDiameter = hGrp->GetBool("DimensioningDiameter", true); bool dimensioningRadius = hGrp->GetBool("DimensioningRadius", true); if (dimensioningRadius && !dimensioningDiameter) { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } else { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DIAMETER, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } } } @@ -480,8 +504,7 @@ void DSHCircleControllerBase::doEnforceControlParameters(Base::Vector2d& onSketc case SelectMode::SeekSecond: { auto& thirdParam = onViewParameters[OnViewParameter::Third]; - if (handler->constructionMethod() - == DrawSketchHandlerCircle::ConstructionMethod::Center) { + if (handler->constructionMethod() == DrawSketchHandlerCircle::ConstructionMethod::Center) { if (thirdParam->isSet) { double radius = (handler->isDiameter ? 0.5 : 1) * thirdParam->getValue(); if (radius < Precision::Confusion() && thirdParam->hasFinishedEditing) { @@ -562,10 +585,10 @@ void DSHCircleController::adaptParameters(Base::Vector2d onSketchPos) case SelectMode::SeekSecond: { auto& thirdParam = onViewParameters[OnViewParameter::Third]; - if (handler->constructionMethod() - == DrawSketchHandlerCircle::ConstructionMethod::Center) { + if (handler->constructionMethod() == DrawSketchHandlerCircle::ConstructionMethod::Center) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); bool dimDiameter = hGrp->GetBool("DimensioningDiameter", true); bool dimRadius = hGrp->GetBool("DimensioningRadius", true); bool useRadius = dimRadius && !dimDiameter; @@ -690,35 +713,43 @@ void DSHCircleController::addConstraints() using namespace Sketcher; auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::VAxis, - x0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::mid), + GeoElementId::VAxis, + x0, + handler->sketchgui->getObject() + ); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::HAxis, - y0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::mid), + GeoElementId::HAxis, + y0, + handler->sketchgui->getObject() + ); }; auto constraintradius = [&]() { if (handler->isDiameter) { - Gui::cmdAppObjectArgs(handler->sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Diameter',%d,%f)) ", - firstCurve, - handler->radius * 2); + Gui::cmdAppObjectArgs( + handler->sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Diameter',%d,%f)) ", + firstCurve, + handler->radius * 2 + ); } else { - Gui::cmdAppObjectArgs(handler->sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve, - handler->radius); + Gui::cmdAppObjectArgs( + handler->sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve, + handler->radius + ); } - const std::vector& ConStr = - handler->sketchgui->getSketchObject()->Constraints.getValues(); + const std::vector& ConStr + = handler->sketchgui->getSketchObject()->Constraints.getValues(); int index = static_cast(ConStr.size()) - 1; handler->moveConstraint(index, prevCursorPosition); }; @@ -750,7 +781,8 @@ void DSHCircleController::addConstraints() // after each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::mid)); // get updated point position + GeoElementId(firstCurve, PointPos::mid) + ); // get updated point position } // if Autoconstraints is empty we do not have a diagnosed system and the parameter will diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h index 9408beab2d..04296db987 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h @@ -52,16 +52,16 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe /* Ellipse ==============================================================================*/ class DrawSketchHandlerEllipse; -using DSHEllipseController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT - ConstructionMethods::CircleEllipseConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHEllipseController = DrawSketchDefaultWidgetController< + DrawSketchHandlerEllipse, + StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/3, + /*OnViewParametersT =*/OnViewParameters<5, 6>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT + ConstructionMethods::CircleEllipseConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHEllipseControllerBase = DSHEllipseController::ControllerBase; @@ -145,17 +145,17 @@ private: if (constructionMethod() == ConstructionMethod::Center) { centerPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } else { apoapsis = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[0], + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE + ); } } break; case SelectMode::SeekSecond: { @@ -172,10 +172,12 @@ private: toolWidgetManager.drawPositionAtCursor(onSketchPos); } - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[1], + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE + ); } break; case SelectMode::SeekThird: { calculateThroughPointMinorAxisParameters(onSketchPos); @@ -183,18 +185,18 @@ private: CreateAndDrawShapeGeometry(); if (constructionMethod() == ConstructionMethod::Center) { - toolWidgetManager.drawWidthHeightAtCursor(onSketchPos, - firstRadius, - secondRadius); + toolWidgetManager.drawWidthHeightAtCursor(onSketchPos, firstRadius, secondRadius); } else { toolWidgetManager.drawPositionAtCursor(onSketchPos); } - seekAndRenderAutoConstraint(sugConstraints[2], - onSketchPos, - Base::Vector2d(0.f, 0.f), - AutoConstraint::CURVE); + seekAndRenderAutoConstraint( + sugConstraints[2], + onSketchPos, + Base::Vector2d(0.f, 0.f), + AutoConstraint::CURVE + ); } break; default: break; @@ -215,24 +217,27 @@ private: // in the exceptional event that this may lead to a circle, do not // exposeInternalGeometry if (!ShapeGeometry.empty() && ShapeGeometry[0]->is()) { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "exposeInternalGeometry(%d)", - ellipseGeoId); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "exposeInternalGeometry(%d)", ellipseGeoId); } Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add ellipse")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add ellipse") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -248,15 +253,18 @@ private: generateAutoConstraintsOnElement( ac1, ellipseGeoId, - Sketcher::PointPos::mid); // add auto constraints for the center point + Sketcher::PointPos::mid + ); // add auto constraints for the center point generateAutoConstraintsOnElement( ac2, ellipseGeoId, - Sketcher::PointPos::none); // add auto constraints for the edge + Sketcher::PointPos::none + ); // add auto constraints for the edge generateAutoConstraintsOnElement( ac3, ellipseGeoId, - Sketcher::PointPos::none); // add auto constraints for the edge + Sketcher::PointPos::none + ); // add auto constraints for the edge } else { @@ -267,15 +275,18 @@ private: generateAutoConstraintsOnElement( ac1, ellipseGeoId, - Sketcher::PointPos::none); // add auto constraints for the first point + Sketcher::PointPos::none + ); // add auto constraints for the first point generateAutoConstraintsOnElement( ac2, ellipseGeoId, - Sketcher::PointPos::none); // add auto constraints for the second point + Sketcher::PointPos::none + ); // add auto constraints for the second point generateAutoConstraintsOnElement( ac3, ellipseGeoId, - Sketcher::PointPos::none); // add auto constraints for the edge + Sketcher::PointPos::none + ); // add auto constraints for the edge } // Ensure temporary autoconstraints do not generate a redundancy and that the geometry // parameters are accurate This is particularly important for adding widget mandated @@ -369,8 +380,10 @@ private: // we calculate the ellipse that will pass via the cursor as per de la Hire Base::Vector2d projx; - projx.ProjectToLine(onSketchPos - centerPoint, - firstAxis); // projection onto the major axis + projx.ProjectToLine( + onSketchPos - centerPoint, + firstAxis + ); // projection onto the major axis auto projy = onSketchPos - centerPoint - projx; @@ -429,11 +442,13 @@ private: addCircleToShapeGeometry(toVector3d(centerPoint), firstRadius, isConstructionMode()); } else { - addEllipseToShapeGeometry(toVector3d(centerPoint), - toVector3d(majorAxis), - majorRadius, - minorRadius, - isConstructionMode()); + addEllipseToShapeGeometry( + toVector3d(centerPoint), + toVector3d(majorAxis), + majorRadius, + minorRadius, + isConstructionMode() + ); } } @@ -478,29 +493,35 @@ void DSHEllipseController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - QStringList names = {QApplication::translate("Sketcher_CreateEllipse", "Center"), - QApplication::translate("Sketcher_CreateEllipse", "Axis endpoints")}; + QStringList names = { + QApplication::translate("Sketcher_CreateEllipse", "Center"), + QApplication::translate("Sketcher_CreateEllipse", "Axis endpoints") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points") + ); } } @@ -517,13 +538,16 @@ void DSHEllipseController::configureToolWidget() else { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } } @@ -596,9 +620,7 @@ void DSHEllipseControllerBase::doEnforceControlParameters(Base::Vector2d& onSket if (fifthParam->isSet) { auto minorradius = fifthParam->getValue(); onSketchPos = handler->centerPoint - + (handler->periapsis - handler->centerPoint) - .Perpendicular(true) - .Normalize() + + (handler->periapsis - handler->centerPoint).Perpendicular(true).Normalize() * minorradius; } } @@ -796,17 +818,21 @@ void DSHEllipseController::addConstraints() // always goes with firstRadiusSet. auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::VAxis, - x0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::mid), + GeoElementId::VAxis, + x0, + handler->sketchgui->getObject() + ); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::HAxis, - y0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::mid), + GeoElementId::HAxis, + y0, + handler->sketchgui->getObject() + ); }; auto constraintFirstRadius = [&]() { @@ -817,7 +843,8 @@ void DSHEllipseController::addConstraints() 3, firstLine, 1, - handler->firstRadius); + handler->firstRadius + ); }; auto constraintSecondRadius = [&]() { @@ -828,14 +855,17 @@ void DSHEllipseController::addConstraints() 3, secondLine, 1, - handler->secondRadius); + handler->secondRadius + ); }; auto constraintAngle = [&]() { - Gui::cmdAppObjectArgs(handler->sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Angle',%d,%f)) ", - firstLine, - angle); + Gui::cmdAppObjectArgs( + handler->sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Angle',%d,%f)) ", + firstLine, + angle + ); }; // NOTE: if AutoConstraints is empty, we can add constraints directly without any @@ -867,20 +897,19 @@ void DSHEllipseController::addConstraints() } } else { // There is a valid diagnose. - auto centerpointinfo = - handler->getPointInfo(GeoElementId(firstCurve, PointPos::mid)); + auto centerpointinfo = handler->getPointInfo(GeoElementId(firstCurve, PointPos::mid)); // if Autoconstraints is empty we do not have a diagnosed system and the parameter // will always be set if (x0set && centerpointinfo.isXDoF()) { constraintx0(); - handler - ->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters - // after each constraint addition + handler->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters + // after each constraint addition centerpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::mid)); // get updated point position + GeoElementId(firstCurve, PointPos::mid) + ); // get updated point position } // if Autoconstraints is empty we do not have a diagnosed system and the parameter @@ -888,9 +917,8 @@ void DSHEllipseController::addConstraints() if (y0set && centerpointinfo.isYDoF()) { constrainty0(); - handler - ->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters - // after each constraint addition + handler->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters + // after each constraint addition } // Major axis (it is not a solver parameter in the solver implementation) @@ -899,19 +927,17 @@ void DSHEllipseController::addConstraints() if (firstRadiusSet && leftDoFs > 0) { constraintFirstRadius(); - handler - ->diagnoseWithAutoConstraints(); // It is not a normal line as it is - // constrained by the Ellipse, so we need - // to recalculate after radius addition + handler->diagnoseWithAutoConstraints(); // It is not a normal line as it is + // constrained by the Ellipse, so we need + // to recalculate after radius addition leftDoFs = handler->getLineDoFs(firstLine); } if (angleSet && leftDoFs > 0) { constraintAngle(); - handler - ->diagnoseWithAutoConstraints(); // It is not a normal line as it is - // constrained by the Ellipse, so we need - // to recalculate after radius addition + handler->diagnoseWithAutoConstraints(); // It is not a normal line as it is + // constrained by the Ellipse, so we need + // to recalculate after radius addition } // Minor axis (it is a solver parameter in the solver implementation) @@ -937,24 +963,30 @@ void DSHEllipseController::addConstraints() using namespace Sketcher; auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::VAxis, - x0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::mid), + GeoElementId::VAxis, + x0, + handler->sketchgui->getObject() + ); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::HAxis, - y0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::mid), + GeoElementId::HAxis, + y0, + handler->sketchgui->getObject() + ); }; auto constraintradius = [&]() { - Gui::cmdAppObjectArgs(handler->sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve, - handler->firstRadius); + Gui::cmdAppObjectArgs( + handler->sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve, + handler->firstRadius + ); }; // NOTE: if AutoConstraints is empty, we can add constraints directly without any @@ -973,20 +1005,19 @@ void DSHEllipseController::addConstraints() } } else { // There is a valid diagnose. - auto startpointinfo = - handler->getPointInfo(GeoElementId(firstCurve, PointPos::mid)); + auto startpointinfo = handler->getPointInfo(GeoElementId(firstCurve, PointPos::mid)); // if Autoconstraints is empty we do not have a diagnosed system and the parameter // will always be set if (x0set && startpointinfo.isXDoF()) { constraintx0(); - handler - ->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters - // after each constraint addition + handler->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters + // after each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::mid)); // get updated point position + GeoElementId(firstCurve, PointPos::mid) + ); // get updated point position } // if Autoconstraints is empty we do not have a diagnosed system and the parameter @@ -994,9 +1025,8 @@ void DSHEllipseController::addConstraints() if (y0set && startpointinfo.isYDoF()) { constrainty0(); - handler - ->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters - // after each constraint addition + handler->diagnoseWithAutoConstraints(); // ensure we have recalculated parameters + // after each constraint addition } auto edgeinfo = handler->getEdgeInfo(firstCurve); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h index 324e013848..fa8d11730b 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h @@ -117,8 +117,7 @@ public: if (Mode == STATUS_SEEK_Second) { const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(BaseGeoId); if (geom->is()) { - 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(); @@ -144,19 +143,20 @@ public: * If out-of-curve, the intuitive behavior is for the closest line endpoint to * expand. */ - bool inCurve = (projection.Length() < recenteredLine.Length() - && projection.GetAngle(recenteredLine) - < 0.1); // Two possible values here, pi and 0, but 0.1 is to - // avoid floating point problems. + bool inCurve + = (projection.Length() < recenteredLine.Length() + && projection.GetAngle(recenteredLine) < 0.1); // Two possible values here, + // 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); + ExtendFromStart = onSketchPos.Distance(startPoint) + < onSketchPos.Distance(endPoint); Increment = ExtendFromStart ? projection.Length() : projection.Length() - recenteredLine.Length(); } @@ -171,13 +171,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); @@ -230,8 +230,10 @@ public: 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)); + EditCurve[i] = Base::Vector2d( + center.x + radius * cos(angle), + center.y + radius * sin(angle) + ); } drawEdit(EditCurve); } @@ -256,31 +258,27 @@ public: if (BaseGeoId > -1) { const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(BaseGeoId); if (geom->is()) { - 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->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geom); + 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; } @@ -290,16 +288,19 @@ public: 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"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool autoRecompute = hGrp->GetBool("AutoRecompute", false); if (autoRecompute) { Gui::Command::updateActive(); @@ -307,10 +308,11 @@ public: // 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); @@ -334,16 +336,17 @@ public: } } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to extend edge")); + Gui::NotifyError( + sketchgui, + 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 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 } updateHint(); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h index 97d67a5d31..9ff0104b48 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h @@ -68,19 +68,20 @@ public: if (!sketch->isExternalAllowed(pDoc, pObj, &msg)) { switch (msg) { case Sketcher::SketchObject::rlCircularReference: - this->notAllowedReason = - QT_TR_NOOP("Linking this will cause circular dependency."); + 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."); + 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."); + this->notAllowedReason = QT_TR_NOOP( + "This object belongs to another part, can't link." + ); break; default: break; @@ -161,8 +162,9 @@ public: 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"); } @@ -173,15 +175,15 @@ public: || (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\", %s, %s)", - msg.pObjectName, - msg.pSubName, - alwaysReference || isConstructionMode() ? "False" - : "True", - intersection ? "True" : "False"); + Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add external geometry")); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addExternal(\"%s\",\"%s\", %s, %s)", + msg.pObjectName, + msg.pSubName, + alwaysReference || isConstructionMode() ? "False" : "True", + intersection ? "True" : "False" + ); Gui::Command::commitCommand(); @@ -202,7 +204,8 @@ public: Gui::NotifyError( sketchgui, QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add external geometry")); + QT_TRANSLATE_NOOP("Notifications", "Failed to add external geometry") + ); Gui::Selection().clearSelection(); Gui::Command::abortCommand(); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h index 6186f22706..6a4159af10 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h @@ -100,18 +100,18 @@ enum class FilletConstructionMethod End // Must be the last one }; -} +} // namespace ConstructionMethods -using DSHFilletController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<1, 1>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT - ConstructionMethods::FilletConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHFilletController = DrawSketchDefaultWidgetController< + DrawSketchHandlerFillet, + StateMachines::TwoSeekEnd, + /*PAutoConstraintSize =*/0, + /*OnViewParametersT =*/OnViewParameters<0, 0>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0, 0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<1, 1>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, // NOLINT + ConstructionMethods::FilletConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHFilletControllerBase = DSHFilletController::ControllerBase; @@ -204,14 +204,16 @@ private: // create fillet at point try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create fillet")); - Gui::cmdAppObjectArgs(obj, - "fillet(%d,%d,%f,%s,%s,%s)", - GeoId, - static_cast(PosId), - radius, - "True", - preserveCorner ? "True" : "False", - isChamfer ? "True" : "False"); + Gui::cmdAppObjectArgs( + obj, + "fillet(%d,%d,%f,%s,%s,%s)", + GeoId, + static_cast(PosId), + radius, + "True", + preserveCorner ? "True" : "False", + isChamfer ? "True" : "False" + ); if (construction) { Gui::cmdAppObjectArgs(obj, "toggleConstruction(%d) ", filletGeoId); @@ -223,7 +225,8 @@ private: Gui::NotifyUserError( obj, QT_TRANSLATE_NOOP("Notifications", "Failed to create fillet"), - e.what()); + e.what() + ); Gui::Command::abortCommand(); } @@ -238,8 +241,8 @@ private: const Part::Geometry* geo1 = obj->getGeometry(geoId1); const Part::Geometry* geo2 = obj->getGeometry(geoId2); - construction = - GeometryFacade::getConstruction(geo1) && GeometryFacade::getConstruction(geo2); + construction = GeometryFacade::getConstruction(geo1) + && GeometryFacade::getConstruction(geo2); double radius = 0; @@ -271,14 +274,17 @@ private: radius, "True", preserveCorner ? "True" : "False", - isChamfer ? "True" : "False"); + isChamfer ? "True" : "False" + ); Gui::Command::commitCommand(); } catch (const Base::CADKernelError& e) { if (e.getTranslatable()) { - Gui::TranslatedUserError(sketchgui, - tr("CAD Kernel Error"), - tr(e.getMessage().c_str())); + Gui::TranslatedUserError( + sketchgui, + tr("CAD Kernel Error"), + tr(e.getMessage().c_str()) + ); } Gui::Selection().clearSelection(); Gui::Command::abortCommand(); @@ -392,7 +398,8 @@ private: ss.str().c_str(), onSketchPos.x, onSketchPos.y, - 0.f); + 0.f + ); moveToNextMode(); } } @@ -415,25 +422,26 @@ public: using enum Gui::InputHint::UserInput; const Gui::InputHint switchModeHint {.message = tr("%1 switch mode"), .sequences = {KeyM}}; - const Gui::InputHint preserveCornerHint {.message = tr("%1 toggle preserve corner"), - .sequences = {KeyU}}; + const Gui::InputHint preserveCornerHint { + .message = tr("%1 toggle preserve corner"), + .sequences = {KeyU} + }; return Gui::lookupHints( state(), { {.state = SelectMode::SeekFirst, - .hints = {{tr("%1 pick first edge or point"), {MouseLeft}}, - switchModeHint, - preserveCornerHint}}, + .hints + = {{tr("%1 pick first edge or point"), {MouseLeft}}, + switchModeHint, + preserveCornerHint}}, {.state = SelectMode::SeekSecond, - .hints = {{tr("%1 pick second edge"), {MouseLeft}}, - switchModeHint, - preserveCornerHint}}, + .hints + = {{tr("%1 pick second edge"), {MouseLeft}}, switchModeHint, preserveCornerHint}}, {.state = SelectMode::End, - .hints = {{tr("%1 create fillet"), {MouseLeft}}, - switchModeHint, - preserveCornerHint}}, - }); + .hints = {{tr("%1 create fillet"), {MouseLeft}}, switchModeHint, preserveCornerHint}}, + } + ); } }; @@ -447,23 +455,30 @@ void DSHFilletController::configureToolWidget() toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateFillet")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateFillet") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateChamfer")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateChamfer") + ); toolWidget->setCheckboxLabel( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_fillet", "Preserve corner (U)")); + QApplication::translate("TaskSketcherTool_c1_fillet", "Preserve corner (U)") + ); toolWidget->setCheckboxToolTip( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_fillet", - "Preserves intersection point and most constraints")); + QApplication::translate( + "TaskSketcherTool_c1_fillet", + "Preserves intersection point and most constraints" + ) + ); toolWidget->setCheckboxIcon( WCheckbox::FirstBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePointFillet")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePointFillet") + ); } syncCheckboxToHandler(WCheckbox::FirstBox, handler->preserveCorner); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h index 1a2bf0cebd..d8d6a870b5 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h @@ -59,18 +59,18 @@ enum class LineConstructionMethod End // Must be the last one }; -} +} // namespace ConstructionMethods -using DSHLineController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0, 0, 0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0, 0>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1, 1>, // NOLINT - ConstructionMethods::LineConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHLineController = DrawSketchDefaultWidgetController< + DrawSketchHandlerLine, + /*SelectModeT*/ StateMachines::TwoSeekEnd, + /*PAutoConstraintSize =*/2, + /*OnViewParametersT =*/OnViewParameters<4, 4, 4>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0, 0, 0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<0, 0, 0>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1, 1>, // NOLINT + ConstructionMethods::LineConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHLineControllerBase = DSHLineController::ControllerBase; @@ -84,7 +84,8 @@ class DrawSketchHandlerLine: public DrawSketchHandlerLineBase public: explicit DrawSketchHandlerLine( - ConstructionMethod constrMethod = ConstructionMethod::OnePointLengthAngle) + ConstructionMethod constrMethod = ConstructionMethod::OnePointLengthAngle + ) : DrawSketchHandlerLineBase(constrMethod) , length(0.0) , lengthSign(0) @@ -101,9 +102,7 @@ private: startPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { toolWidgetManager.drawDirectionAtCursor(onSketchPos, startPoint); @@ -116,9 +115,7 @@ private: catch (const Base::ValueError&) { } // equal points while hovering raise an objection that can be safely ignored - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - onSketchPos - startPoint); + seekAndRenderAutoConstraint(sugConstraints[1], onSketchPos, onSketchPos - startPoint); } break; default: break; @@ -137,16 +134,21 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add line")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add line") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -156,9 +158,7 @@ private: // Generate temporary autoconstraints (but do not actually add them to the sketch) if (avoidRedundants) { - removeRedundantHorizontalVertical(getSketchObject(), - sugConstraints[0], - sugConstraints[1]); + removeRedundantHorizontalVertical(getSketchObject(), sugConstraints[0], sugConstraints[1]); } auto& ac1 = sugConstraints[0]; @@ -205,7 +205,8 @@ private: bool isWidgetVisible() const override { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools" + ); auto index = hGrp->GetInt("OnViewParameterVisibility", 1); return index != 0; }; @@ -266,9 +267,7 @@ private: length = vecL.Length(); if (length > Precision::Confusion()) { - addLineToShapeGeometry(toVector3d(startPoint), - toVector3d(endPoint), - isConstructionMode()); + addLineToShapeGeometry(toVector3d(startPoint), toVector3d(endPoint), isConstructionMode()); } } @@ -348,38 +347,46 @@ template<> void DSHLineController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - QStringList names = {QApplication::translate("Sketcher_CreateLine", "Point, length, angle"), - QApplication::translate("Sketcher_CreateLine", "Point, width, height"), - QApplication::translate("Sketcher_CreateLine", "2 points")}; + QStringList names = { + QApplication::translate("Sketcher_CreateLine", "Point, length, angle"), + QApplication::translate("Sketcher_CreateLine", "Point, width, height"), + QApplication::translate("Sketcher_CreateLine", "2 points") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineAngleLength_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineAngleLength_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineLengthWidth_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineLengthWidth_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 2, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineAngleLength")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineAngleLength") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineLengthWidth")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLineLengthWidth") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 2, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine") + ); } } @@ -389,26 +396,32 @@ void DSHLineController::configureToolWidget() if (handler->constructionMethod() == ConstructionMethod::OnePointLengthAngle) { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } else if (handler->constructionMethod() == ConstructionMethod::TwoPoints) { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCEX, - Gui::EditableDatumLabel::Function::Positioning); + Gui::EditableDatumLabel::Function::Positioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::DISTANCEY, - Gui::EditableDatumLabel::Function::Positioning); + Gui::EditableDatumLabel::Function::Positioning + ); } else { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCEX, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::DISTANCEY, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } } @@ -505,8 +518,10 @@ void DSHLineControllerBase::doEnforceControlParameters(Base::Vector2d& onSketchP } else if (fourthParam->isSet) { // only angle is set, project current position onto that angle - onSketchPos.ProjectToLine(onSketchPos - handler->startPoint, - handler->capturedDirection); + onSketchPos.ProjectToLine( + onSketchPos - handler->startPoint, + handler->capturedDirection + ); onSketchPos += handler->startPoint; } } @@ -590,16 +605,20 @@ void DSHLineController::adaptParameters(Base::Vector2d onSketchPos) double range = (handler->endPoint - handler->startPoint).Angle(); if (!fourthParam->isSet) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(range), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(range), + Base::Unit::Angle + ); } else if (vec.Length() > Precision::Confusion()) { double ovpRange = Base::toRadians(fourthParam->getValue()); if (fabs(range - ovpRange) > Precision::Confusion()) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(range), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(range), + Base::Unit::Angle + ); } } @@ -675,73 +694,63 @@ void DSHLineController::addConstraints() using namespace Sketcher; auto constraintToOrigin = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::RtPnt, - x0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), GeoElementId::RtPnt, x0, obj); }; auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::VAxis, - x0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), GeoElementId::VAxis, x0, obj); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::HAxis, - y0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), GeoElementId::HAxis, y0, obj); }; auto constraintp3DistanceX = [&]() { if (fabs(p3) < Precision::Confusion()) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Vertical',%d)) ", - firstCurve); + Gui::cmdAppObjectArgs(obj, "addConstraint(Sketcher.Constraint('Vertical',%d)) ", firstCurve); } else { bool reverse = (handler->endPoint.x - handler->startPoint.x) < 0; - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f)) ", - firstCurve, - reverse ? 2 : 1, - firstCurve, - reverse ? 1 : 2, - fabs(p3)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%d,%d,%f)) ", + firstCurve, + reverse ? 2 : 1, + firstCurve, + reverse ? 1 : 2, + fabs(p3) + ); } }; auto constraintp3length = [&]() { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%f)) ", - firstCurve, - fabs(p3)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%f)) ", + firstCurve, + fabs(p3) + ); }; auto constraintp3x = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::end), - GeoElementId::VAxis, - p3, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::end), GeoElementId::VAxis, p3, obj); }; auto constraintp4DistanceY = [&]() { if (fabs(p4) < Precision::Confusion()) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Horizontal',%d)) ", - firstCurve); + Gui::cmdAppObjectArgs(obj, "addConstraint(Sketcher.Constraint('Horizontal',%d)) ", firstCurve); } else { bool reverse = (handler->endPoint.y - handler->startPoint.y) < 0; - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f)) ", - firstCurve, - reverse ? 2 : 1, - firstCurve, - reverse ? 1 : 2, - fabs(p4)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%d,%d,%f)) ", + firstCurve, + reverse ? 2 : 1, + firstCurve, + reverse ? 1 : 2, + fabs(p4) + ); } }; @@ -750,10 +759,7 @@ void DSHLineController::addConstraints() }; auto constraintp4y = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::end), - GeoElementId::HAxis, - p4, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::end), GeoElementId::HAxis, p4, obj); }; if (handler->AutoConstraints.empty()) { // No valid diagnosis. Every constraint can be added. @@ -811,7 +817,8 @@ void DSHLineController::addConstraints() // each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::start)); // get updated point position + GeoElementId(firstCurve, PointPos::start) + ); // get updated point position } if (y0set && startpointinfo.isYDoF()) { @@ -821,7 +828,8 @@ void DSHLineController::addConstraints() // each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::start)); // get updated point position + GeoElementId(firstCurve, PointPos::start) + ); // get updated point position } auto endpointinfo = handler->getPointInfo(GeoElementId(firstCurve, PointPos::end)); @@ -864,7 +872,8 @@ void DSHLineController::addConstraints() // after each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::start)); // get updated point position + GeoElementId(firstCurve, PointPos::start) + ); // get updated point position endpointinfo = handler->getPointInfo(GeoElementId(firstCurve, PointPos::end)); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h index b8f2bf022a..7ebbaf70ae 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h @@ -235,9 +235,7 @@ public: } if (TransitionMode == TRANSITION_MODE_Free) { - seekAndRenderAutoConstraint(sugConstr2, - onSketchPos, - onSketchPos - EditCurve[0]); + seekAndRenderAutoConstraint(sugConstr2, onSketchPos, onSketchPos - EditCurve[0]); } } else if (SegmentMode == SEGMENT_MODE_Arc) { @@ -281,8 +279,8 @@ public: 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; @@ -347,21 +345,24 @@ public: // (peviousCurve, previousPosId, dirVec, TransitionMode) 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); + const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry( + sugConstr1[i].GeoId + ); if ((geom->is() || geom->is()) && (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->is()) { 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; } } @@ -388,7 +389,8 @@ public: drawEdit(EditCurve); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { @@ -425,19 +427,15 @@ public: int GeoId; Sketcher::PointPos PosId; sketchgui->getSketchObject()->getGeoVertexIndex(getPreselectPoint(), GeoId, PosId); - if (sketchgui->getSketchObject()->arePointsCoincident(GeoId, - PosId, - firstCurve, - firstPosId)) { + 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; } } @@ -457,7 +455,8 @@ public: try { // open the transaction Gui::Command::openCommand( - QT_TRANSLATE_NOOP("Command", "Add line to sketch polyline")); + QT_TRANSLATE_NOOP("Command", "Add line to sketch polyline") + ); Gui::cmdAppObjectArgs( sketchgui->getObject(), "addGeometry(Part.LineSegment(App.Vector(%f,%f,0),App.Vector(%f,%f,0)),%s)", @@ -465,13 +464,16 @@ public: EditCurve[0].y, EditCurve[1].x, EditCurve[1].y, - constructionModeAsBooleanText()); + constructionModeAsBooleanText() + ); } catch (const Base::Exception&) { addedGeometry = false; - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add line")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add line") + ); Gui::Command::abortCommand(); } @@ -485,7 +487,8 @@ public: try { Gui::Command::openCommand( - QT_TRANSLATE_NOOP("Command", "Add arc to sketch polyline")); + QT_TRANSLATE_NOOP("Command", "Add arc to sketch polyline") + ); Gui::cmdAppObjectArgs( sketchgui->getObject(), "addGeometry(Part.ArcOfCircle" @@ -495,13 +498,16 @@ public: std::abs(arcRadius), std::min(startAngle, endAngle), std::max(startAngle, endAngle), - constructionModeAsBooleanText()); + constructionModeAsBooleanText() + ); } catch (const Base::Exception&) { addedGeometry = false; - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add arc")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add arc") + ); Gui::Command::abortCommand(); } @@ -512,12 +518,12 @@ public: int lastCurve = getHighestCurveIndex(); // issue the constraint if (addedGeometry && (previousPosId != Sketcher::PointPos::none)) { - Sketcher::PointPos lastStartPosId = - (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) + 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 lastEndPosId = (SegmentMode == SEGMENT_MODE_Arc + && startAngle > endAngle) ? Sketcher::PointPos::start : Sketcher::PointPos::end; // in case of a tangency constraint, the coincident constraint is redundant @@ -531,13 +537,15 @@ public: 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, @@ -547,14 +555,17 @@ public: // #3974: if in radians, the printf %f defaults to six decimals, which leads to // loss of precision - double arcAngle = abs(round((endAngle - startAngle) / (std::numbers::pi / 4)) - * 45); // in degrees + double arcAngle = abs( + round((endAngle - startAngle) / (std::numbers::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 @@ -564,7 +575,8 @@ public: lastCurve, static_cast(lastEndPosId), firstCurve, - static_cast(firstPosId)); + static_cast(firstPosId) + ); firstsegment = true; } Gui::Command::commitCommand(); @@ -573,9 +585,10 @@ public: } ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); - bool avoidredundant = - sketchgui->AvoidRedundant.getValue() && sketchgui->Autoconstraints.getValue(); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); + bool avoidredundant = sketchgui->AvoidRedundant.getValue() + && sketchgui->Autoconstraints.getValue(); if (Mode == STATUS_Close) { @@ -585,13 +598,15 @@ public: removeRedundantHorizontalVertical( sketchgui->getObject(), sugConstr1, - sugConstr2); + sugConstr2 + ); } else { removeRedundantHorizontalVertical( sketchgui->getObject(), virtualsugConstr1, - sugConstr2); + sugConstr2 + ); } } } @@ -604,9 +619,7 @@ public: sugConstr.push_back(sugConstr2[i]); } } - createAutoConstraints(sugConstr, - getHighestCurveIndex(), - Sketcher::PointPos::end); + createAutoConstraints(sugConstr, getHighestCurveIndex(), Sketcher::PointPos::end); sugConstr2.clear(); } @@ -619,7 +632,8 @@ public: drawEdit(EditCurve); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); if (continuousMode) { @@ -652,9 +666,7 @@ public: // Add auto constraints if (!sugConstr1.empty()) { // this is relevant only to the very first point - createAutoConstraints(sugConstr1, - getHighestCurveIndex(), - Sketcher::PointPos::start); + createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr1.clear(); } @@ -665,26 +677,30 @@ public: removeRedundantHorizontalVertical( sketchgui->getObject(), sugConstr1, - sugConstr2); + sugConstr2 + ); } else { removeRedundantHorizontalVertical( sketchgui->getObject(), virtualsugConstr1, - sugConstr2); + 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(); } @@ -730,7 +746,8 @@ public: // and now just like any other Handler, ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool continuousMode = hGrp->GetBool("ContinuousCreationMode", true); @@ -822,13 +839,14 @@ protected: const Part::Geometry* geom = sketchgui->getSketchObject()->getGeometry(GeoId); if (geom->is()) { const Part::GeomLineSegment* lineSeg = static_cast(geom); - dirVec.Set(lineSeg->getEndPoint().x - lineSeg->getStartPoint().x, - lineSeg->getEndPoint().y - lineSeg->getStartPoint().y, - 0.f); + 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); @@ -837,14 +855,18 @@ protected: else if (geom->is()) { 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); + 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); + 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()); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h index 355524ce38..28a036b981 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerOffset.h @@ -95,16 +95,16 @@ enum class ModeEnums { };*/ } // namespace ConstructionMethods -using DSHOffsetController = - DrawSketchDefaultWidgetController, - /*WidgetParametersT =*/WidgetParameters<0, 0>, - /*WidgetCheckboxesT =*/WidgetCheckboxes<2, 2>, - /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, - ConstructionMethods::OffsetConstructionMethod, - /*bool PFirstComboboxIsConstructionMethod =*/true>; +using DSHOffsetController = DrawSketchDefaultWidgetController< + DrawSketchHandlerOffset, + StateMachines::OneSeekEnd, + /*PAutoConstraintSize =*/0, + /*OnViewParametersT =*/OnViewParameters<1, 1>, + /*WidgetParametersT =*/WidgetParameters<0, 0>, + /*WidgetCheckboxesT =*/WidgetCheckboxes<2, 2>, + /*WidgetComboboxesT =*/WidgetComboboxes<1, 1>, + ConstructionMethods::OffsetConstructionMethod, + /*bool PFirstComboboxIsConstructionMethod =*/true>; using DSHOffsetControllerBase = DSHOffsetController::ControllerBase; @@ -116,8 +116,10 @@ class DrawSketchHandlerOffset: public DrawSketchHandlerOffsetBase friend DSHOffsetControllerBase; public: - DrawSketchHandlerOffset(std::vector listOfGeoIds, - ConstructionMethod constrMethod = ConstructionMethod::Arc) + DrawSketchHandlerOffset( + std::vector listOfGeoIds, + ConstructionMethod constrMethod = ConstructionMethod::Arc + ) : DrawSketchHandlerOffsetBase(constrMethod) , listOfGeoIds(listOfGeoIds) , deleteOriginal(false) @@ -226,8 +228,9 @@ private: TopoDS_Shape makeOffsetShape(bool allowOpenResult = false) { // in OCC the JointTypes are : Arc(0), Tangent(1), Intersection(2) - short joinType = - constructionMethod() == DrawSketchHandlerOffset::ConstructionMethod::Arc ? 0 : 2; + short joinType = constructionMethod() == DrawSketchHandlerOffset::ConstructionMethod::Arc + ? 0 + : 2; // Offset will fail for single lines if we don't set a plane in ctor. // But if we set a plane, then the direction of offset is forced... @@ -255,7 +258,8 @@ private: } catch (...) { throw Base::CADKernelError( - "BRepOffsetAPI_MakeOffset has crashed! (Unknown exception caught)"); + "BRepOffsetAPI_MakeOffset has crashed! (Unknown exception caught)" + ); } TopoDS_Shape offsetShape = mkOffset.Shape(); @@ -359,8 +363,7 @@ private: } } - void getOffsetGeos(std::vector& geometriesToAdd, - std::vector& listOfOffsetGeoIds) + void getOffsetGeos(std::vector& geometriesToAdd, std::vector& listOfOffsetGeoIds) { TopoDS_Shape offsetShape = makeOffsetShape(); if (offsetShape.IsNull()) { @@ -409,7 +412,8 @@ private: Gui::NotifyUserError( Obj, QT_TRANSLATE_NOOP("Notifications", "Offset Error"), - QT_TRANSLATE_NOOP("Notifications", "Offset could not be created.")); + QT_TRANSLATE_NOOP("Notifications", "Offset could not be created.") + ); return; } @@ -444,9 +448,7 @@ private: // Here we make coincidences based on distance. So they must change after. Base::Vector3d firstStartPoint, firstEndPoint, secondStartPoint, secondEndPoint; if (!getFirstSecondPoints(listOfOffsetGeoIds[i], firstStartPoint, firstEndPoint) - || !getFirstSecondPoints(listOfOffsetGeoIds[j], - secondStartPoint, - secondEndPoint)) { + || !getFirstSecondPoints(listOfOffsetGeoIds[j], secondStartPoint, secondEndPoint)) { continue; } @@ -475,8 +477,8 @@ private: } if (create) { - bool tangent = - needTangent(listOfOffsetGeoIds[i], listOfOffsetGeoIds[j], posi, posj); + bool tangent + = needTangent(listOfOffsetGeoIds[i], listOfOffsetGeoIds[j], posi, posj); stream << "conList.append(Sketcher.Constraint('" << (tangent ? "Tangent" : "Coincident"); stream << "'," << listOfOffsetGeoIds[i] << "," << static_cast(posi) << ", " @@ -551,9 +553,7 @@ private: } stream << listOfGeoIds[listOfGeoIds.size() - 1]; try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "delGeometries([%s])", - stream.str().c_str()); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "delGeometries([%s])", stream.str().c_str()); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); @@ -672,14 +672,12 @@ private: p2[0] = lineSeg2->getStartPoint(); p2[1] = lineSeg2->getEndPoint(); // if lines are parallel - if (((p1[1] - p1[0]) % (p2[1] - p2[0])).Length() - < Precision::Intersection()) { + if (((p1[1] - p1[0]) % (p2[1] - p2[0])).Length() < Precision::Intersection()) { // If the lines are space by offsetLength distance Base::Vector3d projectedP; projectedP.ProjectToLine(p1[0] - p2[0], p2[1] - p2[0]); - if ((projectedP).Length() - fabs(offsetLength) - < Precision::Confusion()) { + if ((projectedP).Length() - fabs(offsetLength) < Precision::Confusion()) { if (!forceCreate && !rerunningFirst) { stream << "conList.append(Sketcher.Constraint('Parallel'," << curve[j] << ", " << geoId << "))\n"; @@ -815,7 +813,8 @@ private: // const Part::GeomArcOfParabola* arcOfParabola = static_cast(geo2); } - else if (isBSplineCurve(*geo) && isBSplineCurve(*geo2)) {} + else if (isBSplineCurve(*geo) && isBSplineCurve(*geo2)) { + } } if (newCurveCounter != prevCurveCounter) { prevCurveCounter = newCurveCounter; @@ -912,18 +911,14 @@ private: if (k == 0) { std::reverse(vcc[j].begin(), vcc[j].end()); } - vcc[j].insert(vcc[j].end(), - vcc[insertedIn].begin(), - vcc[insertedIn].end()); + vcc[j].insert(vcc[j].end(), vcc[insertedIn].begin(), vcc[insertedIn].end()); vcc.erase(vcc.begin() + insertedIn); } else { if (k != 0) { // ie k is vcc[j].size()-1 std::reverse(vcc[j].begin(), vcc[j].end()); } - vcc[insertedIn].insert(vcc[insertedIn].end(), - vcc[j].begin(), - vcc[j].end()); + vcc[insertedIn].insert(vcc[insertedIn].end(), vcc[j].begin(), vcc[j].end()); vcc.erase(vcc.begin() + j); } j--; @@ -1000,9 +995,11 @@ private: // find direction if (BRep_Tool::IsClosed(wire)) { TopoDS_Face aFace = BRepBuilderAPI_MakeFace(wire); - BRepClass_FaceClassifier checkPoint(aFace, - {endpoint.x, endpoint.y, 0.0}, - Precision::Confusion()); + BRepClass_FaceClassifier checkPoint( + aFace, + {endpoint.x, endpoint.y, 0.0}, + Precision::Confusion() + ); if (checkPoint.State() == TopAbs_IN) { newOffsetLength = -newOffsetLength; } @@ -1089,10 +1086,12 @@ private: return false; } - return ((p11 - p21).Length() < Precision::Confusion() - || (p11 - p22).Length() < Precision::Confusion() - || (p12 - p21).Length() < Precision::Confusion() - || (p12 - p22).Length() < Precision::Confusion()); + return ( + (p11 - p21).Length() < Precision::Confusion() + || (p11 - p22).Length() < Precision::Confusion() + || (p12 - p21).Length() < Precision::Confusion() + || (p12 - p22).Length() < Precision::Confusion() + ); } bool areTangentCoincident(int geoId1, int geoId2) @@ -1144,29 +1143,37 @@ template<> void DSHOffsetController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - QStringList names = {QApplication::translate("Sketcher_CreateOffset", "Arc"), - QApplication::translate("Sketcher_CreateOffset", "Intersection")}; + QStringList names = { + QApplication::translate("Sketcher_CreateOffset", "Arc"), + QApplication::translate("Sketcher_CreateOffset", "Intersection") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); - toolWidget->setComboboxItemIcon(WCombobox::FirstCombo, - 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_OffsetArc")); + toolWidget->setComboboxItemIcon( + WCombobox::FirstCombo, + 0, + Gui::BitmapFactory().iconFromTheme("Sketcher_OffsetArc") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_OffsetIntersection")); + Gui::BitmapFactory().iconFromTheme("Sketcher_OffsetIntersection") + ); - toolWidget->setCheckboxLabel(WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_offset", - "Delete original geometries (U)")); + toolWidget->setCheckboxLabel( + WCheckbox::FirstBox, + QApplication::translate("TaskSketcherTool_c1_offset", "Delete original geometries (U)") + ); toolWidget->setCheckboxLabel( WCheckbox::SecondBox, - QApplication::translate("TaskSketcherTool_c2_offset", "Add offset constraint (J)")); + QApplication::translate("TaskSketcherTool_c2_offset", "Add offset constraint (J)") + ); } onViewParameters[OnViewParameter::First]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Forced); + Gui::EditableDatumLabel::Function::Forced + ); } template<> @@ -1184,7 +1191,8 @@ void DSHOffsetControllerBase::adaptDrawingToOnViewParameterChange(int labelindex Gui::NotifyUserError( handler->sketchgui->getSketchObject(), QT_TRANSLATE_NOOP("Notifications", "Invalid Value"), - QT_TRANSLATE_NOOP("Notifications", "Offset value can't be 0.")); + QT_TRANSLATE_NOOP("Notifications", "Offset value can't be 0.") + ); } else { handler->offsetLengthSet = true; @@ -1244,14 +1252,12 @@ void DSHOffsetController::adaptParameters(Base::Vector2d onSketchPos) Base::Vector2d direction = handler->endpoint - handler->pointOnSourceWire; if (direction.Length() > Precision::Confusion()) { direction.Normalize(); - Base::Vector2d correctedEndpoint = - handler->pointOnSourceWire + direction * handler->offsetLength; - dimensionEndpoint = - Base::Vector3d(correctedEndpoint.x, correctedEndpoint.y, 0.); + Base::Vector2d correctedEndpoint = handler->pointOnSourceWire + + direction * handler->offsetLength; + dimensionEndpoint = Base::Vector3d(correctedEndpoint.x, correctedEndpoint.y, 0.); } else { - dimensionEndpoint = - Base::Vector3d(handler->endpoint.x, handler->endpoint.y, 0.); + dimensionEndpoint = Base::Vector3d(handler->endpoint.x, handler->endpoint.y, 0.); } } else { @@ -1261,7 +1267,8 @@ void DSHOffsetController::adaptParameters(Base::Vector2d onSketchPos) firstParam->setPoints( dimensionEndpoint, - Base::Vector3d(handler->pointOnSourceWire.x, handler->pointOnSourceWire.y, 0.)); + Base::Vector3d(handler->pointOnSourceWire.x, handler->pointOnSourceWire.y, 0.) + ); } break; default: break; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h index 858a8dbe88..40989b5f7f 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h @@ -46,10 +46,11 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerPoint; -using DSHPointController = DrawSketchController>; +using DSHPointController = DrawSketchController< + DrawSketchHandlerPoint, + StateMachines::OneSeekEnd, + /*PAutoConstraintSize =*/1, + /*OnViewParametersT =*/OnViewParameters<2>>; using DrawSketchHandlerPointBase = DrawSketchControllableHandler; @@ -79,9 +80,7 @@ private: editPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; default: break; @@ -92,18 +91,22 @@ private: { try { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add sketch point")); - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "addGeometry(Part.Point(App.Vector(%f,%f,0)), %s)", - editPoint.x, - editPoint.y, - isConstructionMode() ? "True" : "False"); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "addGeometry(Part.Point(App.Vector(%f,%f,0)), %s)", + editPoint.x, + editPoint.y, + isConstructionMode() ? "True" : "False" + ); Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add point")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add point") + ); Gui::Command::abortCommand(); } @@ -113,9 +116,11 @@ private: { if (!sugConstraints[0].empty()) { - DrawSketchHandler::createAutoConstraints(sugConstraints[0], - getHighestCurveIndex(), - Sketcher::PointPos::start); + DrawSketchHandler::createAutoConstraints( + sugConstraints[0], + getHighestCurveIndex(), + Sketcher::PointPos::start + ); sugConstraints[0].clear(); } } @@ -172,10 +177,12 @@ void DSHPointController::adaptDrawingToOnViewParameterChange(int labelindex, dou } onViewParameters[OnViewParameter::First]->setPoints( Base::Vector3d(0., 0., 0.), - Base::Vector3d(handler->editPoint.x, handler->editPoint.y, 0.)); + Base::Vector3d(handler->editPoint.x, handler->editPoint.y, 0.) + ); onViewParameters[OnViewParameter::Second]->setPoints( Base::Vector3d(0., 0., 0.), - Base::Vector3d(handler->editPoint.x, handler->editPoint.y, 0.)); + Base::Vector3d(handler->editPoint.x, handler->editPoint.y, 0.) + ); } template<> @@ -218,10 +225,14 @@ void DSHPointController::adaptParameters(Base::Vector2d onSketchPos) bool sameSign = onSketchPos.x * onSketchPos.y > 0.; firstParam->setLabelAutoDistanceReverse(!sameSign); secondParam->setLabelAutoDistanceReverse(sameSign); - firstParam->setPoints(Base::Vector3d(0., 0., 0.), - Base::Vector3d(onSketchPos.x, onSketchPos.y, 0.)); - secondParam->setPoints(Base::Vector3d(0., 0., 0.), - Base::Vector3d(onSketchPos.x, onSketchPos.y, 0.)); + firstParam->setPoints( + Base::Vector3d(0., 0., 0.), + Base::Vector3d(onSketchPos.x, onSketchPos.y, 0.) + ); + secondParam->setPoints( + Base::Vector3d(0., 0., 0.), + Base::Vector3d(onSketchPos.x, onSketchPos.y, 0.) + ); } break; default: break; @@ -260,24 +271,30 @@ void DSHPointController::addConstraints() using namespace Sketcher; if (x0set && y0set && x0 == 0. && y0 == 0.) { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::RtPnt, - x0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::start), + GeoElementId::RtPnt, + x0, + handler->sketchgui->getObject() + ); } else { if (x0set) { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::VAxis, - x0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::start), + GeoElementId::VAxis, + x0, + handler->sketchgui->getObject() + ); } if (y0set) { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::HAxis, - y0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::start), + GeoElementId::HAxis, + y0, + handler->sketchgui->getObject() + ); } } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h index 789b6bd545..bbdd326103 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h @@ -49,14 +49,14 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerPolygon; -using DSHPolygonController = - DrawSketchDefaultWidgetController, - /*WidgetParametersT =*/WidgetParameters<1>, - /*WidgetCheckboxesT =*/WidgetCheckboxes<0>, - /*WidgetComboboxesT =*/WidgetComboboxes<0>>; +using DSHPolygonController = DrawSketchDefaultWidgetController< + DrawSketchHandlerPolygon, + StateMachines::TwoSeekEnd, + /*PAutoConstraintSize =*/2, + /*OnViewParametersT =*/OnViewParameters<4>, + /*WidgetParametersT =*/WidgetParameters<1>, + /*WidgetCheckboxesT =*/WidgetCheckboxes<0>, + /*WidgetComboboxesT =*/WidgetComboboxes<0>>; using DSHPolygonControllerBase = DSHPolygonController::ControllerBase; @@ -84,9 +84,7 @@ private: centerPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { toolWidgetManager.drawDirectionAtCursor(onSketchPos, centerPoint); @@ -95,9 +93,7 @@ private: CreateAndDrawShapeGeometry(); - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[1], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; default: break; @@ -111,33 +107,40 @@ private: Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add polygon")); 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(), - numberOfCorners, - centerPoint.x, - centerPoint.y, - firstCorner.x, - firstCorner.y, - constructionModeAsBooleanText()); + 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(), + numberOfCorners, + centerPoint.x, + centerPoint.y, + firstCorner.x, + firstCorner.y, + constructionModeAsBooleanText() + ); Gui::Command::commitCommand(); tryAutoRecomputeIfNotSolve(sketchgui->getObject()); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add polygon")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add polygon") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -147,16 +150,12 @@ private: int circlegeoid = getHighestCurveIndex(); int lastsidegeoid = getHighestCurveIndex() - 1; if (sugConstraints[0].size() > 0) { - generateAutoConstraintsOnElement(sugConstraints[0], - circlegeoid, - Sketcher::PointPos::mid); + generateAutoConstraintsOnElement(sugConstraints[0], circlegeoid, Sketcher::PointPos::mid); } // add auto constraints to the last side of the polygon if (sugConstraints[1].size() > 0) { - generateAutoConstraintsOnElement(sugConstraints[1], - lastsidegeoid, - Sketcher::PointPos::end); + generateAutoConstraintsOnElement(sugConstraints[1], lastsidegeoid, Sketcher::PointPos::end); } // Ensure temporary autoconstraints do not generate a redundancy and that the geometry @@ -243,8 +242,8 @@ private: return; } - double angleOfSeparation = - 2.0 * std::numbers::pi / static_cast(numberOfCorners); // NOLINT + double angleOfSeparation = 2.0 * std::numbers::pi + / static_cast(numberOfCorners); // NOLINT double cos_v = cos(angleOfSeparation); double sin_v = sin(angleOfSeparation); @@ -256,9 +255,7 @@ private: rx = cos_v * rx - sin_v * ry; ry = cos_v * ry + sin_v * old_rx; Base::Vector2d newCorner = Base::Vector2d(centerPoint.x + rx, centerPoint.y + ry); - addLineToShapeGeometry(toVector3d(prevCorner), - toVector3d(newCorner), - isConstructionMode()); + addLineToShapeGeometry(toVector3d(prevCorner), toVector3d(newCorner), isConstructionMode()); prevCorner = newCorner; } } @@ -326,7 +323,8 @@ void DSHPolygonController::configureToolWidget() toolWidget->setParameterLabel( WParameter::First, - QApplication::translate("ToolWidgetManager_p4", "Sides (+'U'/ -'J')")); + QApplication::translate("ToolWidgetManager_p4", "Sides (+'U'/ -'J')") + ); toolWidget->setParameter(WParameter::First, handler->numberOfCorners); // unconditionally set toolWidget->configureParameterUnit(WParameter::First, Base::Unit()); @@ -339,10 +337,12 @@ void DSHPolygonController::configureToolWidget() onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } template<> @@ -438,9 +438,11 @@ void DSHPolygonController::adaptParameters(Base::Vector2d onSketchPos) double range = (handler->firstCorner - handler->centerPoint).Angle(); if (!fourthParam->isSet) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(range), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(range), + Base::Unit::Angle + ); } thirdParam->setPoints(start, end); @@ -494,24 +496,30 @@ void DSHPolygonController::addConstraints() using namespace Sketcher; auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(lastCurve, PointPos::mid), - GeoElementId::VAxis, - x0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(lastCurve, PointPos::mid), + GeoElementId::VAxis, + x0, + handler->sketchgui->getObject() + ); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(lastCurve, PointPos::mid), - GeoElementId::HAxis, - y0, - handler->sketchgui->getObject()); + ConstraintToAttachment( + GeoElementId(lastCurve, PointPos::mid), + GeoElementId::HAxis, + y0, + handler->sketchgui->getObject() + ); }; auto constraintradius = [&]() { - Gui::cmdAppObjectArgs(handler->sketchgui->getObject(), - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - lastCurve, - radius); + Gui::cmdAppObjectArgs( + handler->sketchgui->getObject(), + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + lastCurve, + radius + ); }; // NOTE: if AutoConstraints is empty, we can add constraints directly without any diagnose. No @@ -541,7 +549,8 @@ void DSHPolygonController::addConstraints() // each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(lastCurve, PointPos::mid)); // get updated point position + GeoElementId(lastCurve, PointPos::mid) + ); // get updated point position } // if Autoconstraints is empty we do not have a diagnosed system and the parameter will diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h index 90c94b9452..4bdde0e660 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h @@ -58,7 +58,7 @@ enum class RectangleConstructionMethod End // Must be the last one }; -} +} // namespace ConstructionMethods using DSHRectangleController = DrawSketchDefaultWidgetController< DrawSketchHandlerRectangle, @@ -83,9 +83,11 @@ class DrawSketchHandlerRectangle: public DrawSketchHandlerRectangleBase friend DSHRectangleControllerBase; public: - DrawSketchHandlerRectangle(ConstructionMethod constrMethod = ConstructionMethod::Diagonal, - bool roundcorners = false, - bool frame = false) + DrawSketchHandlerRectangle( + ConstructionMethod constrMethod = ConstructionMethod::Diagonal, + bool roundcorners = false, + bool frame = false + ) : DrawSketchHandlerRectangleBase(constrMethod) , roundCorners(roundcorners) , makeFrame(frame) @@ -117,8 +119,10 @@ private: using enum Gui::InputHint::UserInput; const Gui::InputHint switchHint {.message = tr("%1 switch mode"), .sequences = {KeyM}}; - const Gui::InputHint roundedCornersHint {.message = tr("%1 toggle rounded corners"), - .sequences = {KeyU}}; + const Gui::InputHint roundedCornersHint { + .message = tr("%1 toggle rounded corners"), + .sequences = {KeyU} + }; const Gui::InputHint frameHint {.message = tr("%1 toggle frame"), .sequences = {KeyJ}}; return Gui::lookupHints( @@ -279,9 +283,7 @@ private: center = onSketchPos; } - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { if (constructionMethod() == ConstructionMethod::Diagonal) { @@ -367,9 +369,7 @@ private: catch (const Base::ValueError&) { } // equal points while hovering raise an objection that can be safely ignored - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - Base::Vector2d(0.0, 0.0)); + seekAndRenderAutoConstraint(sugConstraints[1], onSketchPos, Base::Vector2d(0.0, 0.0)); } break; case SelectMode::SeekThird: { if (constructionMethod() == ConstructionMethod::Diagonal @@ -399,15 +399,18 @@ private: Base::Vector2d b = corner3 - corner2; if (fabs((sqrt(a.x * a.x + a.y * a.y) * sqrt(b.x * b.x + b.y * b.y))) > Precision::Confusion()) { - angle123 = - acos((a.x * b.x + a.y * b.y) - / (sqrt(a.x * a.x + a.y * a.y) * sqrt(b.x * b.x + b.y * b.y))); + angle123 = acos( + (a.x * b.x + a.y * b.y) + / (sqrt(a.x * a.x + a.y * a.y) * sqrt(b.x * b.x + b.y * b.y)) + ); } angle412 = pi - angle123; if (roundCorners) { radius = std::min(length, width) / 6 // NOLINT - * std::min(sqrt(1 - cos(angle412) * cos(angle412)), - sqrt(1 - cos(angle123) * cos(angle123))); + * std::min( + sqrt(1 - cos(angle412) * cos(angle412)), + sqrt(1 - cos(angle123) * cos(angle123)) + ); } else { radius = 0.; @@ -428,15 +431,18 @@ private: Base::Vector2d b = corner2 - corner1; if (fabs((sqrt(a.x * a.x + a.y * a.y) * sqrt(b.x * b.x + b.y * b.y))) > Precision::Confusion()) { - angle412 = - acos((a.x * b.x + a.y * b.y) - / (sqrt(a.x * a.x + a.y * a.y) * sqrt(b.x * b.x + b.y * b.y))); + angle412 = acos( + (a.x * b.x + a.y * b.y) + / (sqrt(a.x * a.x + a.y * a.y) * sqrt(b.x * b.x + b.y * b.y)) + ); } angle123 = pi - angle412; if (roundCorners) { radius = std::min(length, width) / 6 // NOLINT - * std::min(sqrt(1 - cos(angle412) * cos(angle412)), - sqrt(1 - cos(angle123) * cos(angle123))); + * std::min( + sqrt(1 - cos(angle412) * cos(angle412)), + sqrt(1 - cos(angle123) * cos(angle123)) + ); } else { radius = 0.; @@ -453,9 +459,7 @@ private: if ((constructionMethod() == ConstructionMethod::ThreePoints || constructionMethod() == ConstructionMethod::CenterAnd3Points)) { - seekAndRenderAutoConstraint(sugConstraints[2], - onSketchPos, - Base::Vector2d(0.0, 0.0)); + seekAndRenderAutoConstraint(sugConstraints[2], onSketchPos, Base::Vector2d(0.0, 0.0)); } } break; case SelectMode::SeekFourth: { @@ -502,16 +506,21 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add box")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add box") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } thickness = 0.; @@ -524,139 +533,179 @@ private: // add auto constraints at the start of the first side if (radius > Precision::Confusion()) { if (!sugConstraints[0].empty()) { - generateAutoConstraintsOnElement(sugConstraints[0], - constructionPointOneId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[0], + constructionPointOneId, + Sketcher::PointPos::start + ); } if (!sugConstraints[1].empty()) { - generateAutoConstraintsOnElement(sugConstraints[1], - constructionPointTwoId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + constructionPointTwoId, + Sketcher::PointPos::start + ); } } else { if (!sugConstraints[0].empty()) { - generateAutoConstraintsOnElement(sugConstraints[0], - firstCurve, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[0], + firstCurve, + Sketcher::PointPos::start + ); } if (!sugConstraints[1].empty()) { - generateAutoConstraintsOnElement(sugConstraints[1], - firstCurve + 1, - Sketcher::PointPos::end); + generateAutoConstraintsOnElement( + sugConstraints[1], + firstCurve + 1, + Sketcher::PointPos::end + ); } } } else if (constructionMethod() == ConstructionMethod::CenterAndCorner) { // add auto constraints at center if (!sugConstraints[0].empty()) { - generateAutoConstraintsOnElement(sugConstraints[0], - centerPointId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[0], + centerPointId, + Sketcher::PointPos::start + ); } // add auto constraints for the line segment end if (!sugConstraints[1].empty()) { if (radius > Precision::Confusion()) { - generateAutoConstraintsOnElement(sugConstraints[1], - constructionPointOneId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + constructionPointOneId, + Sketcher::PointPos::start + ); } else { - generateAutoConstraintsOnElement(sugConstraints[1], - firstCurve + 1, - Sketcher::PointPos::end); + generateAutoConstraintsOnElement( + sugConstraints[1], + firstCurve + 1, + Sketcher::PointPos::end + ); } } } else if (constructionMethod() == ConstructionMethod::ThreePoints) { if (radius > Precision::Confusion()) { if (!sugConstraints[0].empty()) { - generateAutoConstraintsOnElement(sugConstraints[0], - constructionPointOneId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[0], + constructionPointOneId, + Sketcher::PointPos::start + ); } if (!sugConstraints[1].empty()) { - generateAutoConstraintsOnElement(sugConstraints[1], - constructionPointTwoId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + constructionPointTwoId, + Sketcher::PointPos::start + ); } if (!sugConstraints[2].empty()) { - generateAutoConstraintsOnElement(sugConstraints[2], - constructionPointThreeId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[2], + constructionPointThreeId, + Sketcher::PointPos::start + ); } } else { if (!sugConstraints[0].empty()) { - generateAutoConstraintsOnElement(sugConstraints[0], - firstCurve, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[0], + firstCurve, + Sketcher::PointPos::start + ); } if (!sugConstraints[1].empty()) { if (!cornersReversed) { - generateAutoConstraintsOnElement(sugConstraints[1], - firstCurve + 1, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + firstCurve + 1, + Sketcher::PointPos::start + ); } else { - generateAutoConstraintsOnElement(sugConstraints[1], - firstCurve + 3, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + firstCurve + 3, + Sketcher::PointPos::start + ); } } if (!sugConstraints[2].empty()) { - generateAutoConstraintsOnElement(sugConstraints[2], - firstCurve + 2, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[2], + firstCurve + 2, + Sketcher::PointPos::start + ); } } } else if (constructionMethod() == ConstructionMethod::CenterAnd3Points) { // add auto constraints at center if (!sugConstraints[0].empty()) { - generateAutoConstraintsOnElement(sugConstraints[0], - centerPointId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[0], + centerPointId, + Sketcher::PointPos::start + ); } // add auto constraints for the line segment end if (radius > Precision::Confusion()) { if (!sugConstraints[1].empty()) { - generateAutoConstraintsOnElement(sugConstraints[1], - constructionPointOneId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + constructionPointOneId, + Sketcher::PointPos::start + ); } if (!sugConstraints[2].empty()) { - generateAutoConstraintsOnElement(sugConstraints[2], - constructionPointTwoId, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[2], + constructionPointTwoId, + Sketcher::PointPos::start + ); } } else { if (!sugConstraints[1].empty()) { - generateAutoConstraintsOnElement(sugConstraints[1], - firstCurve, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[1], + firstCurve, + Sketcher::PointPos::start + ); } if (!sugConstraints[2].empty()) { if (!cornersReversed) { - generateAutoConstraintsOnElement(sugConstraints[2], - firstCurve + 1, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[2], + firstCurve + 1, + Sketcher::PointPos::start + ); } else { - generateAutoConstraintsOnElement(sugConstraints[2], - firstCurve + 3, - Sketcher::PointPos::start); + generateAutoConstraintsOnElement( + sugConstraints[2], + firstCurve + 3, + Sketcher::PointPos::start + ); } } } @@ -878,8 +927,7 @@ private: } } - void - createFirstRectangleGeometries(Base::Vector2d vecL, Base::Vector2d vecW, double L1, double L2) + void createFirstRectangleGeometries(Base::Vector2d vecL, Base::Vector2d vecW, double L1, double L2) { createFirstRectangleLines(vecL, vecW, L1, L2); @@ -890,18 +938,26 @@ private: void createFirstRectangleLines(Base::Vector2d vecL, Base::Vector2d vecW, double L1, double L2) { - addLineToShapeGeometry(toVector3d(corner1 + vecL * L2 * cos(angle412 / 2)), - toVector3d(corner2 - vecL * L1 * cos(angle123 / 2)), - isConstructionMode()); - addLineToShapeGeometry(toVector3d(corner2 + vecW * L1 * cos(angle123 / 2)), - toVector3d(corner3 - vecW * L2 * cos(angle412 / 2)), - isConstructionMode()); - addLineToShapeGeometry(toVector3d(corner3 - vecL * L2 * cos(angle412 / 2)), - toVector3d(corner4 + vecL * L1 * cos(angle123 / 2)), - isConstructionMode()); - addLineToShapeGeometry(toVector3d(corner4 - vecW * L1 * cos(angle123 / 2)), - toVector3d(corner1 + vecW * L2 * cos(angle412 / 2)), - isConstructionMode()); + addLineToShapeGeometry( + toVector3d(corner1 + vecL * L2 * cos(angle412 / 2)), + toVector3d(corner2 - vecL * L1 * cos(angle123 / 2)), + isConstructionMode() + ); + addLineToShapeGeometry( + toVector3d(corner2 + vecW * L1 * cos(angle123 / 2)), + toVector3d(corner3 - vecW * L2 * cos(angle412 / 2)), + isConstructionMode() + ); + addLineToShapeGeometry( + toVector3d(corner3 - vecL * L2 * cos(angle412 / 2)), + toVector3d(corner4 + vecL * L1 * cos(angle123 / 2)), + isConstructionMode() + ); + addLineToShapeGeometry( + toVector3d(corner4 - vecW * L1 * cos(angle123 / 2)), + toVector3d(corner1 + vecW * L2 * cos(angle412 / 2)), + isConstructionMode() + ); } void createFirstRectangleFillets(Base::Vector2d vecL, Base::Vector2d vecW, double L1, double L2) @@ -925,8 +981,7 @@ private: addArcToShapeGeometry(center4, end - pi, end - angle123, radius, isConstructionMode()); } - void - createSecondRectangleGeometries(Base::Vector2d vecL, Base::Vector2d vecW, double L1, double L2) + void createSecondRectangleGeometries(Base::Vector2d vecL, Base::Vector2d vecW, double L1, double L2) { using std::numbers::pi; @@ -954,43 +1009,59 @@ private: L2F = L2 * radiusFrame / radius; } - addLineToShapeGeometry(toVector3d(frameCorner1 + vecLF / lengthF * L2F * cos(angle412 / 2)), - toVector3d(frameCorner2 - vecLF / lengthF * L1F * cos(angle123 / 2)), - isConstructionMode()); - addLineToShapeGeometry(toVector3d(frameCorner2 + vecWF / widthF * L1F * cos(angle123 / 2)), - toVector3d(frameCorner3 - vecWF / widthF * L2F * cos(angle412 / 2)), - isConstructionMode()); - addLineToShapeGeometry(toVector3d(frameCorner3 - vecLF / lengthF * L2F * cos(angle412 / 2)), - toVector3d(frameCorner4 + vecLF / lengthF * L1F * cos(angle123 / 2)), - isConstructionMode()); - addLineToShapeGeometry(toVector3d(frameCorner4 - vecWF / widthF * L1F * cos(angle123 / 2)), - toVector3d(frameCorner1 + vecWF / widthF * L2F * cos(angle412 / 2)), - isConstructionMode()); + addLineToShapeGeometry( + toVector3d(frameCorner1 + vecLF / lengthF * L2F * cos(angle412 / 2)), + toVector3d(frameCorner2 - vecLF / lengthF * L1F * cos(angle123 / 2)), + isConstructionMode() + ); + addLineToShapeGeometry( + toVector3d(frameCorner2 + vecWF / widthF * L1F * cos(angle123 / 2)), + toVector3d(frameCorner3 - vecWF / widthF * L2F * cos(angle412 / 2)), + isConstructionMode() + ); + addLineToShapeGeometry( + toVector3d(frameCorner3 - vecLF / lengthF * L2F * cos(angle412 / 2)), + toVector3d(frameCorner4 + vecLF / lengthF * L1F * cos(angle123 / 2)), + isConstructionMode() + ); + addLineToShapeGeometry( + toVector3d(frameCorner4 - vecWF / widthF * L1F * cos(angle123 / 2)), + toVector3d(frameCorner1 + vecWF / widthF * L2F * cos(angle412 / 2)), + isConstructionMode() + ); if (roundCorners && radiusFrame > Precision::Confusion()) { Base::Vector2d b1 = (vecL + vecW) / (vecL + vecW).Length(); Base::Vector2d b2 = (vecL - vecW) / (vecL - vecW).Length(); - addArcToShapeGeometry(toVector3d(frameCorner1 + b1 * L2F), - end - pi + angle412, - end, - radiusFrame, - isConstructionMode()); - addArcToShapeGeometry(toVector3d(frameCorner2 - b2 * L1F), - end, - end - pi - angle123, - radiusFrame, - isConstructionMode()); - addArcToShapeGeometry(toVector3d(frameCorner3 - b1 * L2F), - end + angle412, - end - pi, - radiusFrame, - isConstructionMode()); - addArcToShapeGeometry(toVector3d(frameCorner4 + b2 * L1F), - end - pi, - end - angle123, - radiusFrame, - isConstructionMode()); + addArcToShapeGeometry( + toVector3d(frameCorner1 + b1 * L2F), + end - pi + angle412, + end, + radiusFrame, + isConstructionMode() + ); + addArcToShapeGeometry( + toVector3d(frameCorner2 - b2 * L1F), + end, + end - pi - angle123, + radiusFrame, + isConstructionMode() + ); + addArcToShapeGeometry( + toVector3d(frameCorner3 - b1 * L2F), + end + angle412, + end - pi, + radiusFrame, + isConstructionMode() + ); + addArcToShapeGeometry( + toVector3d(frameCorner4 + b2 * L1F), + end - pi, + end - angle123, + radiusFrame, + isConstructionMode() + ); } } @@ -1047,26 +1118,34 @@ private: { // In this case the corners of the second rectangle are coincident // with the centers of the arcs of the first rectangle. - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 8, // NOLINT - Sketcher::PointPos::start, - firstCurve + 4, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 9, // NOLINT - Sketcher::PointPos::start, - firstCurve + 5, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 10, // NOLINT - Sketcher::PointPos::start, - firstCurve + 6, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 11, // NOLINT - Sketcher::PointPos::start, - firstCurve + 7, // NOLINT - Sketcher::PointPos::mid); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 8, // NOLINT + Sketcher::PointPos::start, + firstCurve + 4, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 9, // NOLINT + Sketcher::PointPos::start, + firstCurve + 5, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 10, // NOLINT + Sketcher::PointPos::start, + firstCurve + 6, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 11, // NOLINT + Sketcher::PointPos::start, + firstCurve + 7, // NOLINT + Sketcher::PointPos::mid + ); } void finishOblongFrameCase2() @@ -1080,85 +1159,115 @@ private: addLineToShapeGeometry(center3, Base::Vector3d(frameCorner3.x, frameCorner3.y, 0.), true); addLineToShapeGeometry(center4, Base::Vector3d(frameCorner4.x, frameCorner4.y, 0.), true); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 12, // NOLINT - Sketcher::PointPos::start, - firstCurve + 4, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 12, // NOLINT - Sketcher::PointPos::end, - firstCurve + 8, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 13, // NOLINT - Sketcher::PointPos::start, - firstCurve + 5, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 13, // NOLINT - Sketcher::PointPos::end, - firstCurve + 9, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 14, // NOLINT - Sketcher::PointPos::start, - firstCurve + 6, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 14, // NOLINT - Sketcher::PointPos::end, - firstCurve + 10, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 15, // NOLINT - Sketcher::PointPos::start, - firstCurve + 7, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 15, // NOLINT - Sketcher::PointPos::end, - firstCurve + 11, // NOLINT - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 12, // NOLINT + Sketcher::PointPos::start, + firstCurve + 4, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 12, // NOLINT + Sketcher::PointPos::end, + firstCurve + 8, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 13, // NOLINT + Sketcher::PointPos::start, + firstCurve + 5, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 13, // NOLINT + Sketcher::PointPos::end, + firstCurve + 9, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 14, // NOLINT + Sketcher::PointPos::start, + firstCurve + 6, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 14, // NOLINT + Sketcher::PointPos::end, + firstCurve + 10, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 15, // NOLINT + Sketcher::PointPos::start, + firstCurve + 7, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 15, // NOLINT + Sketcher::PointPos::end, + firstCurve + 11, // NOLINT + Sketcher::PointPos::start + ); - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve + 12, // NOLINT - Sketcher::PointPos::none, - firstCurve + 13); // NOLINT - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve + 13, // NOLINT - Sketcher::PointPos::none, - firstCurve + 14); // NOLINT - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve + 14, // NOLINT - Sketcher::PointPos::none, - firstCurve + 15); // NOLINT + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve + 12, // NOLINT + Sketcher::PointPos::none, + firstCurve + 13 + ); // NOLINT + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve + 13, // NOLINT + Sketcher::PointPos::none, + firstCurve + 14 + ); // NOLINT + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve + 14, // NOLINT + Sketcher::PointPos::none, + firstCurve + 15 + ); // NOLINT } void finishOblongFrameCase3() { addTangentCoincidences(firstCurve + 8); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 4, // NOLINT - Sketcher::PointPos::mid, - firstCurve + 12, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 5, // NOLINT - Sketcher::PointPos::mid, - firstCurve + 13, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 6, // NOLINT - Sketcher::PointPos::mid, - firstCurve + 14, // NOLINT - Sketcher::PointPos::mid); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 7, // NOLINT - Sketcher::PointPos::mid, - firstCurve + 15, // NOLINT - Sketcher::PointPos::mid); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 4, // NOLINT + Sketcher::PointPos::mid, + firstCurve + 12, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 5, // NOLINT + Sketcher::PointPos::mid, + firstCurve + 13, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 6, // NOLINT + Sketcher::PointPos::mid, + firstCurve + 14, // NOLINT + Sketcher::PointPos::mid + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 7, // NOLINT + Sketcher::PointPos::mid, + firstCurve + 15, // NOLINT + Sketcher::PointPos::mid + ); addFrameAlignmentConstraints(firstCurve + 8, false); } @@ -1186,43 +1295,59 @@ private: addPointToShapeGeometry(Base::Vector3d(corner1.x, corner1.y, 0.), true); if (!cornersReversed) { addPointToShapeGeometry(Base::Vector3d(corner2.x, corner2.y, 0.), true); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 1); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 1 + ); } else { addPointToShapeGeometry(Base::Vector3d(corner4.x, corner4.y, 0.), true); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 2); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 3); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 2 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 3 + ); } addPointToShapeGeometry(Base::Vector3d(corner3.x, corner3.y, 0.), true); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve + 3); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointThreeId, - Sketcher::PointPos::start, - firstCurve + 1); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointThreeId, - Sketcher::PointPos::start, - firstCurve + 2); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + 3 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointThreeId, + Sketcher::PointPos::start, + firstCurve + 1 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointThreeId, + Sketcher::PointPos::start, + firstCurve + 2 + ); } void finishOblongCenterAnd3Points(bool thicknessNotZero, bool negThicknessEqualRadius) @@ -1248,42 +1373,56 @@ private: addPointToShapeGeometry(Base::Vector3d(corner1.x, corner1.y, 0.), true); if (!cornersReversed) { addPointToShapeGeometry(Base::Vector3d(corner2.x, corner2.y, 0.), true); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 1); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 1 + ); } else { addPointToShapeGeometry(Base::Vector3d(corner4.x, corner4.y, 0.), true); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 2); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 3); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 2 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 3 + ); } addPointToShapeGeometry(Base::Vector3d(center.x, center.y, 0.), true); - addToShapeConstraints(Sketcher::Symmetric, - firstCurve + 2, - Sketcher::PointPos::start, - firstCurve, - Sketcher::PointPos::start, - centerPointId, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve + 3); // NOLINT + addToShapeConstraints( + Sketcher::Symmetric, + firstCurve + 2, + Sketcher::PointPos::start, + firstCurve, + Sketcher::PointPos::start, + centerPointId, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + 3 + ); // NOLINT } void finishOblongCenterAndCorner(bool thicknessNotZero, bool negThicknessEqualRadius) @@ -1305,21 +1444,27 @@ private: addPointToShapeGeometry(Base::Vector3d(corner3.x, corner3.y, 0.), true); addPointToShapeGeometry(Base::Vector3d(center.x, center.y, 0.), true); - addToShapeConstraints(Sketcher::Symmetric, - firstCurve + 2, - Sketcher::PointPos::start, - firstCurve, - Sketcher::PointPos::start, - centerPointId, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve + 1); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve + 2); + addToShapeConstraints( + Sketcher::Symmetric, + firstCurve + 2, + Sketcher::PointPos::start, + firstCurve, + Sketcher::PointPos::start, + centerPointId, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + 1 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + 2 + ); } void finishOblongDiagonal(bool thicknessNotZero, bool negThicknessEqualRadius) @@ -1341,82 +1486,112 @@ private: addPointToShapeGeometry(Base::Vector3d(corner1.x, corner1.y, 0.), true); addPointToShapeGeometry(Base::Vector3d(corner3.x, corner3.y, 0.), true); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointOneId, - Sketcher::PointPos::start, - firstCurve + 3); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 1); - addToShapeConstraints(Sketcher::PointOnObject, - constructionPointTwoId, - Sketcher::PointPos::start, - firstCurve + 2); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointOneId, + Sketcher::PointPos::start, + firstCurve + 3 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 1 + ); + addToShapeConstraints( + Sketcher::PointOnObject, + constructionPointTwoId, + Sketcher::PointPos::start, + firstCurve + 2 + ); } void addTangentCoincidences(int geoId) { - addToShapeConstraints(Sketcher::Tangent, - geoId, - Sketcher::PointPos::start, - geoId + 4, // NOLINT - Sketcher::PointPos::end); - addToShapeConstraints(Sketcher::Tangent, - geoId, - Sketcher::PointPos::end, - geoId + 5, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Tangent, - geoId + 1, // NOLINT - Sketcher::PointPos::start, - geoId + 5, // NOLINT - Sketcher::PointPos::end); - addToShapeConstraints(Sketcher::Tangent, - geoId + 1, // NOLINT - Sketcher::PointPos::end, - geoId + 6, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Tangent, - geoId + 2, // NOLINT - Sketcher::PointPos::start, - geoId + 6, // NOLINT - Sketcher::PointPos::end); - addToShapeConstraints(Sketcher::Tangent, - geoId + 2, // NOLINT - Sketcher::PointPos::end, - geoId + 7, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Tangent, - geoId + 3, // NOLINT - Sketcher::PointPos::start, - geoId + 7, // NOLINT - Sketcher::PointPos::end); - addToShapeConstraints(Sketcher::Tangent, - geoId + 3, // NOLINT - Sketcher::PointPos::end, - geoId + 4, // NOLINT - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Tangent, + geoId, + Sketcher::PointPos::start, + geoId + 4, // NOLINT + Sketcher::PointPos::end + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId, + Sketcher::PointPos::end, + geoId + 5, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId + 1, // NOLINT + Sketcher::PointPos::start, + geoId + 5, // NOLINT + Sketcher::PointPos::end + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId + 1, // NOLINT + Sketcher::PointPos::end, + geoId + 6, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId + 2, // NOLINT + Sketcher::PointPos::start, + geoId + 6, // NOLINT + Sketcher::PointPos::end + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId + 2, // NOLINT + Sketcher::PointPos::end, + geoId + 7, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId + 3, // NOLINT + Sketcher::PointPos::start, + geoId + 7, // NOLINT + Sketcher::PointPos::end + ); + addToShapeConstraints( + Sketcher::Tangent, + geoId + 3, // NOLINT + Sketcher::PointPos::end, + geoId + 4, // NOLINT + Sketcher::PointPos::start + ); } void addArcEqualities() { - addToShapeConstraints(Sketcher::Equal, - firstCurve + 4, // NOLINT - Sketcher::PointPos::none, - firstCurve + 5); // NOLINT - addToShapeConstraints(Sketcher::Equal, - firstCurve + 5, // NOLINT - Sketcher::PointPos::none, - firstCurve + 6); // NOLINT - addToShapeConstraints(Sketcher::Equal, - firstCurve + 6, // NOLINT - Sketcher::PointPos::none, - firstCurve + 7); // NOLINT + addToShapeConstraints( + Sketcher::Equal, + firstCurve + 4, // NOLINT + Sketcher::PointPos::none, + firstCurve + 5 + ); // NOLINT + addToShapeConstraints( + Sketcher::Equal, + firstCurve + 5, // NOLINT + Sketcher::PointPos::none, + firstCurve + 6 + ); // NOLINT + addToShapeConstraints( + Sketcher::Equal, + firstCurve + 6, // NOLINT + Sketcher::PointPos::none, + firstCurve + 7 + ); // NOLINT } void finishRectangleCreation(bool thicknessNotZero) @@ -1437,26 +1612,34 @@ private: void addRectangleCoincidences(int geoId) { - addToShapeConstraints(Sketcher::Coincident, - geoId, - Sketcher::PointPos::end, - geoId + 1, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - geoId + 1, - Sketcher::PointPos::end, - geoId + 2, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - geoId + 2, - Sketcher::PointPos::end, - geoId + 3, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - geoId + 3, - Sketcher::PointPos::end, - geoId, - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Coincident, + geoId, + Sketcher::PointPos::end, + geoId + 1, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + geoId + 1, + Sketcher::PointPos::end, + geoId + 2, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + geoId + 2, + Sketcher::PointPos::end, + geoId + 3, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + geoId + 3, + Sketcher::PointPos::end, + geoId, + Sketcher::PointPos::start + ); } void addAlignmentConstraints() @@ -1468,8 +1651,7 @@ private: typeB = Sketcher::Horizontal; } - if (fabs(angle) < Precision::Confusion() - || constructionMethod() == ConstructionMethod::Diagonal + if (fabs(angle) < Precision::Confusion() || constructionMethod() == ConstructionMethod::Diagonal || constructionMethod() == ConstructionMethod::CenterAndCorner) { addToShapeConstraints(typeA, firstCurve); addToShapeConstraints(typeA, firstCurve + 2); @@ -1477,19 +1659,25 @@ private: addToShapeConstraints(typeB, firstCurve + 3); } else { - addToShapeConstraints(Sketcher::Parallel, - firstCurve, - Sketcher::PointPos::none, - firstCurve + 2); - addToShapeConstraints(Sketcher::Parallel, - firstCurve + 1, - Sketcher::PointPos::none, - firstCurve + 3); + addToShapeConstraints( + Sketcher::Parallel, + firstCurve, + Sketcher::PointPos::none, + firstCurve + 2 + ); + addToShapeConstraints( + Sketcher::Parallel, + firstCurve + 1, + Sketcher::PointPos::none, + firstCurve + 3 + ); if (fabs(angle123 - std::numbers::pi / 2) < Precision::Confusion()) { - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve, - Sketcher::PointPos::none, - firstCurve + 1); + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve, + Sketcher::PointPos::none, + firstCurve + 1 + ); } } } @@ -1512,8 +1700,7 @@ private: typeB = Sketcher::Horizontal; } - if (fabs(angle) < Precision::Confusion() - || constructionMethod() == ConstructionMethod::Diagonal + if (fabs(angle) < Precision::Confusion() || constructionMethod() == ConstructionMethod::Diagonal || constructionMethod() == ConstructionMethod::CenterAndCorner) { addToShapeConstraints(typeA, geoId); // NOLINT addToShapeConstraints(typeA, geoId + 2); // NOLINT @@ -1523,95 +1710,133 @@ private: } } else { - addToShapeConstraints(Sketcher::Parallel, - geoId, // NOLINT - Sketcher::PointPos::none, - geoId + 2); // NOLINT - addToShapeConstraints(Sketcher::Parallel, - geoId + 1, // NOLINT - Sketcher::PointPos::none, - geoId + 3); // NOLINT - addToShapeConstraints(Sketcher::Parallel, - firstCurve, - Sketcher::PointPos::none, - geoId); // NOLINT + addToShapeConstraints( + Sketcher::Parallel, + geoId, // NOLINT + Sketcher::PointPos::none, + geoId + 2 + ); // NOLINT + addToShapeConstraints( + Sketcher::Parallel, + geoId + 1, // NOLINT + Sketcher::PointPos::none, + geoId + 3 + ); // NOLINT + addToShapeConstraints( + Sketcher::Parallel, + firstCurve, + Sketcher::PointPos::none, + geoId + ); // NOLINT if (addLast) { - addToShapeConstraints(Sketcher::Parallel, - firstCurve + 1, // NOLINT - Sketcher::PointPos::none, - geoId + 1); // NOLINT + addToShapeConstraints( + Sketcher::Parallel, + firstCurve + 1, // NOLINT + Sketcher::PointPos::none, + geoId + 1 + ); // NOLINT } } } void addRectangleFrameConstructionLines() { - addLineToShapeGeometry(Base::Vector3d(corner1.x, corner1.y, 0.), - Base::Vector3d(frameCorner1.x, frameCorner1.y, 0.), - true); - addLineToShapeGeometry(Base::Vector3d(corner2.x, corner2.y, 0.), - Base::Vector3d(frameCorner2.x, frameCorner2.y, 0.), - true); - addLineToShapeGeometry(Base::Vector3d(corner3.x, corner3.y, 0.), - Base::Vector3d(frameCorner3.x, frameCorner3.y, 0.), - true); - addLineToShapeGeometry(Base::Vector3d(corner4.x, corner4.y, 0.), - Base::Vector3d(frameCorner4.x, frameCorner4.y, 0.), - true); + addLineToShapeGeometry( + Base::Vector3d(corner1.x, corner1.y, 0.), + Base::Vector3d(frameCorner1.x, frameCorner1.y, 0.), + true + ); + addLineToShapeGeometry( + Base::Vector3d(corner2.x, corner2.y, 0.), + Base::Vector3d(frameCorner2.x, frameCorner2.y, 0.), + true + ); + addLineToShapeGeometry( + Base::Vector3d(corner3.x, corner3.y, 0.), + Base::Vector3d(frameCorner3.x, frameCorner3.y, 0.), + true + ); + addLineToShapeGeometry( + Base::Vector3d(corner4.x, corner4.y, 0.), + Base::Vector3d(frameCorner4.x, frameCorner4.y, 0.), + true + ); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 8, // NOLINT - Sketcher::PointPos::start, - firstCurve, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 8, // NOLINT - Sketcher::PointPos::end, - firstCurve + 4, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 9, // NOLINT - Sketcher::PointPos::start, - firstCurve + 1, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 9, // NOLINT - Sketcher::PointPos::end, - firstCurve + 5, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 10, // NOLINT - Sketcher::PointPos::start, - firstCurve + 2, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 10, // NOLINT - Sketcher::PointPos::end, - firstCurve + 6, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 11, // NOLINT - Sketcher::PointPos::start, - firstCurve + 3, // NOLINT - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Coincident, - firstCurve + 11, // NOLINT - Sketcher::PointPos::end, - firstCurve + 7, // NOLINT - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 8, // NOLINT + Sketcher::PointPos::start, + firstCurve, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 8, // NOLINT + Sketcher::PointPos::end, + firstCurve + 4, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 9, // NOLINT + Sketcher::PointPos::start, + firstCurve + 1, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 9, // NOLINT + Sketcher::PointPos::end, + firstCurve + 5, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 10, // NOLINT + Sketcher::PointPos::start, + firstCurve + 2, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 10, // NOLINT + Sketcher::PointPos::end, + firstCurve + 6, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 11, // NOLINT + Sketcher::PointPos::start, + firstCurve + 3, // NOLINT + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Coincident, + firstCurve + 11, // NOLINT + Sketcher::PointPos::end, + firstCurve + 7, // NOLINT + Sketcher::PointPos::start + ); - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve + 8, // NOLINT - Sketcher::PointPos::none, - firstCurve + 9); // NOLINT - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve + 9, // NOLINT - Sketcher::PointPos::none, - firstCurve + 10); // NOLINT - addToShapeConstraints(Sketcher::Perpendicular, - firstCurve + 10, // NOLINT - Sketcher::PointPos::none, - firstCurve + 11); // NOLINT + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve + 8, // NOLINT + Sketcher::PointPos::none, + firstCurve + 9 + ); // NOLINT + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve + 9, // NOLINT + Sketcher::PointPos::none, + firstCurve + 10 + ); // NOLINT + addToShapeConstraints( + Sketcher::Perpendicular, + firstCurve + 10, // NOLINT + Sketcher::PointPos::none, + firstCurve + 11 + ); // NOLINT } void finishCenteredRectangleCreation(bool thicknessNotZero) @@ -1624,19 +1849,23 @@ private: } addPointToShapeGeometry(Base::Vector3d(center.x, center.y, 0.), true); - addToShapeConstraints(Sketcher::Symmetric, - firstCurve + 2, // NOLINT - Sketcher::PointPos::start, - firstCurve, - Sketcher::PointPos::start, - centerPointId, - Sketcher::PointPos::start); + addToShapeConstraints( + Sketcher::Symmetric, + firstCurve + 2, // NOLINT + Sketcher::PointPos::start, + firstCurve, + Sketcher::PointPos::start, + centerPointId, + Sketcher::PointPos::start + ); } - int getPointSideOfVector(Base::Vector2d pointToCheck, - Base::Vector2d separatingVector, - Base::Vector2d pointOnVector) + int getPointSideOfVector( + Base::Vector2d pointToCheck, + Base::Vector2d separatingVector, + Base::Vector2d pointOnVector + ) { Base::Vector2d secondPointOnVec = pointOnVector + separatingVector; double d = (pointToCheck.x - pointOnVector.x) * (secondPointOnVec.y - pointOnVector.y) @@ -1673,37 +1902,46 @@ private: else { if (du < length - du && dv < width - dv) { radius = (du + dv - + std::max(2 * sqrt(du * dv) * sin(angle412 / 2), - -2 * sqrt(du * dv) * sin(angle412 / 2))) + + std::max( + 2 * sqrt(du * dv) * sin(angle412 / 2), + -2 * sqrt(du * dv) * sin(angle412 / 2) + )) * tan(angle412 / 2); } else if (du > length - du && dv < width - dv) { du = length - du; radius = (du + dv - + std::max(2 * sqrt(du * dv) * sin(angle123 / 2), - -2 * sqrt(du * dv) * sin(angle123 / 2))) + + std::max( + 2 * sqrt(du * dv) * sin(angle123 / 2), + -2 * sqrt(du * dv) * sin(angle123 / 2) + )) * tan(angle123 / 2); } else if (du < length - du && dv > width - dv) { dv = width - dv; radius = (du + dv - + std::max(2 * sqrt(du * dv) * sin(angle123 / 2), - -2 * sqrt(du * dv) * sin(angle123 / 2))) + + std::max( + 2 * sqrt(du * dv) * sin(angle123 / 2), + -2 * sqrt(du * dv) * sin(angle123 / 2) + )) * tan(angle123 / 2); } else { du = length - du; dv = width - dv; radius = (du + dv - + std::max(2 * sqrt(du * dv) * sin(angle412 / 2), - -2 * sqrt(du * dv) * sin(angle412 / 2))) + + std::max( + 2 * sqrt(du * dv) * sin(angle412 / 2), + -2 * sqrt(du * dv) * sin(angle412 / 2) + )) * tan(angle412 / 2); } radius = std::min( radius, std::min(length * 0.999, width * 0.999) // NOLINT / (cos(angle412 / 2) / sqrt(1 - cos(angle412 / 2) * cos(angle412 / 2)) - + cos(angle123 / 2) / sqrt(1 - cos(angle123 / 2) * cos(angle123 / 2)))); + + cos(angle123 / 2) / sqrt(1 - cos(angle123 / 2) * cos(angle123 / 2))) + ); } } @@ -1723,12 +1961,16 @@ private: obliqueThickness = std::min(fabs(du), fabs(length - du)); } else if (du > 0 && du < length && dv > 0 && dv < width) { - obliqueThickness = -std::min(std::min(fabs(du), fabs(length - du)), - std::min(fabs(dv), fabs(width - dv))); + obliqueThickness = -std::min( + std::min(fabs(du), fabs(length - du)), + std::min(fabs(dv), fabs(width - dv)) + ); } else { - obliqueThickness = std::max(std::min(fabs(du), fabs(length - du)), - std::min(fabs(dv), fabs(width - dv))); + obliqueThickness = std::max( + std::min(fabs(du), fabs(length - du)), + std::min(fabs(dv), fabs(width - dv)) + ); } @@ -1829,75 +2071,97 @@ void DSHRectangleController::configureToolWidget() QApplication::translate("TaskSketcherTool_c1_rectangle", "Corner, width, height"), QApplication::translate("TaskSketcherTool_c1_rectangle", "Center, width, height"), QApplication::translate("TaskSketcherTool_c1_rectangle", "3 corners"), - QApplication::translate("TaskSketcherTool_c1_rectangle", "Center, 2 corners")}; + QApplication::translate("TaskSketcherTool_c1_rectangle", "Center, 2 corners") + }; toolWidget->setComboboxElements(WCombobox::FirstCombo, names); toolWidget->setCheckboxLabel( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_rectangle", "Rounded corners (U)")); + QApplication::translate("TaskSketcherTool_c1_rectangle", "Rounded corners (U)") + ); toolWidget->setCheckboxToolTip( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_rectangle", - "Create a rectangle with rounded corners.")); + QApplication::translate( + "TaskSketcherTool_c1_rectangle", + "Create a rectangle with rounded corners." + ) + ); syncCheckboxToHandler(WCheckbox::FirstBox, handler->roundCorners); toolWidget->setCheckboxLabel( WCheckbox::SecondBox, - QApplication::translate("TaskSketcherTool_c2_rectangle", "Frame (J)")); + QApplication::translate("TaskSketcherTool_c2_rectangle", "Frame (J)") + ); toolWidget->setCheckboxToolTip( WCheckbox::SecondBox, - QApplication::translate("TaskSketcherTool_c2_rectangle", - "Create two rectangles with a constant offset.")); + QApplication::translate( + "TaskSketcherTool_c2_rectangle", + "Create two rectangles with a constant offset." + ) + ); syncCheckboxToHandler(WCheckbox::SecondBox, handler->makeFrame); if (isConstructionMode()) { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 2, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points_Constr")); - toolWidget->setComboboxItemIcon(WCombobox::FirstCombo, - 3, - Gui::BitmapFactory().iconFromTheme( - "Sketcher_CreateRectangle3Points_Center_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points_Constr") + ); + toolWidget->setComboboxItemIcon( + WCombobox::FirstCombo, + 3, + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points_Center_Constr") + ); toolWidget->setCheckboxIcon( WCheckbox::FirstBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong_Constr") + ); toolWidget->setCheckboxIcon( WCheckbox::SecondBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateFrame_Constr")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateFrame_Constr") + ); } else { toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 0, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 1, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 2, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points") + ); toolWidget->setComboboxItemIcon( WCombobox::FirstCombo, 3, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points_Center")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle3Points_Center") + ); toolWidget->setCheckboxIcon( WCheckbox::FirstBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong")); - toolWidget->setCheckboxIcon(WCheckbox::SecondBox, - Gui::BitmapFactory().iconFromTheme("Sketcher_CreateFrame")); + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong") + ); + toolWidget->setCheckboxIcon( + WCheckbox::SecondBox, + Gui::BitmapFactory().iconFromTheme("Sketcher_CreateFrame") + ); } } @@ -1908,52 +2172,66 @@ void DSHRectangleController::configureToolWidget() || handler->constructionMethod() == ConstructionMethod::CenterAndCorner) { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCEX, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::DISTANCEY, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Sixth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } else if (handler->constructionMethod() == ConstructionMethod::ThreePoints) { onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Sixth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Seventh]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Eighth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } else if (handler->constructionMethod() == ConstructionMethod::CenterAnd3Points) { onViewParameters[OnViewParameter::Third]->setLabelType(Gui::SoDatumLabel::DISTANCEX); onViewParameters[OnViewParameter::Fourth]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Sixth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Seventh]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Eighth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } } @@ -2001,8 +2279,7 @@ void DSHRectangleControllerBase::doEnforceControlParameters(Base::Vector2d& onSk if (handler->constructionMethod() == ConstructionMethod::Diagonal) { if (handler->lengthSign == 0) { - handler->lengthSign = - (onSketchPos.x - handler->corner1.x) >= 0 ? 1 : -1; + handler->lengthSign = (onSketchPos.x - handler->corner1.x) >= 0 ? 1 : -1; } onSketchPos.x = handler->corner1.x + handler->lengthSign * length; } @@ -2049,8 +2326,9 @@ void DSHRectangleControllerBase::doEnforceControlParameters(Base::Vector2d& onSk } if (onViewParameters[OnViewParameter::Fourth]->isSet) { - double angle = - Base::toRadians(onViewParameters[OnViewParameter::Fourth]->getValue()); + double angle = Base::toRadians( + onViewParameters[OnViewParameter::Fourth]->getValue() + ); onSketchPos.x = handler->corner1.x + cos(angle) * length; onSketchPos.y = handler->corner1.y + sin(angle) * length; } @@ -2114,18 +2392,20 @@ void DSHRectangleControllerBase::doEnforceControlParameters(Base::Vector2d& onSk onSketchPos = handler->corner2Initial + width * dir.Normalize(); } if (onViewParameters[OnViewParameter::Sixth]->isSet) { - double angle = - Base::toRadians(onViewParameters[OnViewParameter::Sixth]->getValue()); + double angle = Base::toRadians( + onViewParameters[OnViewParameter::Sixth]->getValue() + ); if (fmod(angle, std::numbers::pi) < Precision::Confusion() && onViewParameters[OnViewParameter::Sixth]->hasFinishedEditing) { unsetOnViewParameter(onViewParameters[OnViewParameter::Sixth].get()); return; } - int sign1 = - handler->getPointSideOfVector(onSketchPos, - handler->corner2Initial - handler->corner1, - handler->corner1); + int sign1 = handler->getPointSideOfVector( + onSketchPos, + handler->corner2Initial - handler->corner1, + handler->corner1 + ); int sign = handler->side != sign1 ? 1 : -1; @@ -2153,20 +2433,23 @@ void DSHRectangleControllerBase::doEnforceControlParameters(Base::Vector2d& onSk onSketchPos = handler->corner1 + width * dir.Normalize(); } if (onViewParameters[OnViewParameter::Sixth]->isSet) { - double c = - Base::toRadians(onViewParameters[OnViewParameter::Sixth]->getValue()); + double c = Base::toRadians(onViewParameters[OnViewParameter::Sixth]->getValue()); if (fmod(c, std::numbers::pi) < Precision::Confusion() && onViewParameters[OnViewParameter::Sixth]->hasFinishedEditing) { unsetOnViewParameter(onViewParameters[OnViewParameter::Sixth].get()); return; } - double a = asin(width * sin(std::numbers::pi - c) - / (handler->corner3 - handler->corner1).Length()); + double a = asin( + width * sin(std::numbers::pi - c) + / (handler->corner3 - handler->corner1).Length() + ); - int sign1 = handler->getPointSideOfVector(onSketchPos, - handler->corner3 - handler->corner1, - handler->corner1); + int sign1 = handler->getPointSideOfVector( + onSketchPos, + handler->corner3 - handler->corner1, + handler->corner1 + ); int sign = handler->side != sign1 ? 1 : -1; @@ -2201,8 +2484,7 @@ void DSHRectangleControllerBase::doEnforceControlParameters(Base::Vector2d& onSk if (handler->constructionMethod() == ConstructionMethod::CenterAnd3Points) { angleToUse = handler->angle123 / 2; } - Base::Vector2d vecL = - (handler->corner2Initial - handler->corner1).Normalize(); + Base::Vector2d vecL = (handler->corner2Initial - handler->corner1).Normalize(); double L2 = onViewParameters[OnViewParameter::Seventh]->getValue() / sqrt(1 - cos(angleToUse) * cos(angleToUse)); onSketchPos = handler->corner1 + vecL * L2 * cos(angleToUse); @@ -2286,10 +2568,14 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) bool sameSign = onSketchPos.x * onSketchPos.y > 0.; onViewParameters[OnViewParameter::First]->setLabelAutoDistanceReverse(!sameSign); onViewParameters[OnViewParameter::Second]->setLabelAutoDistanceReverse(sameSign); - onViewParameters[OnViewParameter::First]->setPoints(Base::Vector3d(), - toVector3d(onSketchPos)); - onViewParameters[OnViewParameter::Second]->setPoints(Base::Vector3d(), - toVector3d(onSketchPos)); + onViewParameters[OnViewParameter::First]->setPoints( + Base::Vector3d(), + toVector3d(onSketchPos) + ); + onViewParameters[OnViewParameter::Second]->setPoints( + Base::Vector3d(), + toVector3d(onSketchPos) + ); } break; case SelectMode::SeekSecond: { if (handler->constructionMethod() == ConstructionMethod::Diagonal @@ -2313,29 +2599,38 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) onViewParameters[OnViewParameter::Third]->setPoints( start, - toVector3d(handler->cornersReversed ? handler->corner4 : handler->corner2)); + toVector3d(handler->cornersReversed ? handler->corner4 : handler->corner2) + ); onViewParameters[OnViewParameter::Fourth]->setPoints( start, - toVector3d(handler->cornersReversed ? handler->corner2 : handler->corner4)); + toVector3d(handler->cornersReversed ? handler->corner2 : handler->corner4) + ); } else if (handler->constructionMethod() == ConstructionMethod::ThreePoints) { if (!onViewParameters[OnViewParameter::Third]->isSet) { setOnViewParameterValue(OnViewParameter::Third, handler->length); } - onViewParameters[OnViewParameter::Third]->setPoints(toVector3d(handler->corner4), - toVector3d(handler->corner3)); + onViewParameters[OnViewParameter::Third]->setPoints( + toVector3d(handler->corner4), + toVector3d(handler->corner3) + ); if (!onViewParameters[OnViewParameter::Fourth]->isSet) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(handler->angle), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(handler->angle), + Base::Unit::Angle + ); } - onViewParameters[OnViewParameter::Fourth]->setPoints(toVector3d(handler->corner1), - Base::Vector3d()); + onViewParameters[OnViewParameter::Fourth]->setPoints( + toVector3d(handler->corner1), + Base::Vector3d() + ); onViewParameters[OnViewParameter::Fourth]->setLabelRange( - (handler->corner2 - handler->corner1).Angle()); + (handler->corner2 - handler->corner1).Angle() + ); } else { if (!onViewParameters[OnViewParameter::Third]->isSet) { @@ -2349,10 +2644,14 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) bool sameSign = onSketchPos.x * onSketchPos.y > 0.; onViewParameters[OnViewParameter::Third]->setLabelAutoDistanceReverse(!sameSign); onViewParameters[OnViewParameter::Fourth]->setLabelAutoDistanceReverse(sameSign); - onViewParameters[OnViewParameter::Third]->setPoints(Base::Vector3d(), - toVector3d(onSketchPos)); - onViewParameters[OnViewParameter::Fourth]->setPoints(Base::Vector3d(), - toVector3d(onSketchPos)); + onViewParameters[OnViewParameter::Third]->setPoints( + Base::Vector3d(), + toVector3d(onSketchPos) + ); + onViewParameters[OnViewParameter::Fourth]->setPoints( + Base::Vector3d(), + toVector3d(onSketchPos) + ); } } break; case SelectMode::SeekThird: { @@ -2379,27 +2678,32 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) } Base::Vector3d start = toVector3d(handler->corner3); - Base::Vector3d end = - Base::Vector3d(handler->corner3.x, handler->frameCorner3.y, 0.0); + Base::Vector3d end + = Base::Vector3d(handler->corner3.x, handler->frameCorner3.y, 0.0); onViewParameters[OnViewParameter::Sixth]->setPoints(start, end); } } else if (handler->constructionMethod() == ConstructionMethod::ThreePoints) { - onViewParameters[OnViewParameter::Third]->setPoints(toVector3d(handler->corner4), - toVector3d(handler->corner3)); + onViewParameters[OnViewParameter::Third]->setPoints( + toVector3d(handler->corner4), + toVector3d(handler->corner3) + ); bool reversed = handler->cornersReversed; if (!onViewParameters[OnViewParameter::Fifth]->isSet) { - setOnViewParameterValue(OnViewParameter::Fifth, - reversed ? handler->length : handler->width); + setOnViewParameterValue( + OnViewParameter::Fifth, + reversed ? handler->length : handler->width + ); } Base::Vector3d start = toVector3d(handler->corner1); onViewParameters[OnViewParameter::Fifth]->setLabelAutoDistanceReverse(reversed); onViewParameters[OnViewParameter::Fifth]->setPoints( start, - toVector3d(reversed ? handler->corner2 : handler->corner4)); + toVector3d(reversed ? handler->corner2 : handler->corner4) + ); if (!onViewParameters[OnViewParameter::Sixth]->isSet) { @@ -2409,7 +2713,8 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) onViewParameters[OnViewParameter::Sixth]->setPoints( toVector3d(reversed ? handler->corner4 : handler->corner2), - Base::Vector3d()); + Base::Vector3d() + ); double startAngle = reversed ? (handler->corner1 - handler->corner4).Angle() : (handler->corner3 - handler->corner2).Angle(); onViewParameters[OnViewParameter::Sixth]->setLabelStartAngle(startAngle); @@ -2419,15 +2724,18 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) bool reversed = handler->cornersReversed; if (!onViewParameters[OnViewParameter::Fifth]->isSet) { - setOnViewParameterValue(OnViewParameter::Fifth, - reversed ? handler->width : handler->length); + setOnViewParameterValue( + OnViewParameter::Fifth, + reversed ? handler->width : handler->length + ); } Base::Vector3d start = toVector3d(handler->corner1); onViewParameters[OnViewParameter::Fifth]->setLabelAutoDistanceReverse(true); onViewParameters[OnViewParameter::Fifth]->setPoints( start, - toVector3d(reversed ? handler->corner4 : handler->corner2)); + toVector3d(reversed ? handler->corner4 : handler->corner2) + ); if (!onViewParameters[OnViewParameter::Sixth]->isSet) { @@ -2435,8 +2743,10 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) setOnViewParameterValue(OnViewParameter::Sixth, val, Base::Unit::Angle); } - onViewParameters[OnViewParameter::Sixth]->setPoints(toVector3d(handler->corner1), - Base::Vector3d()); + onViewParameters[OnViewParameter::Sixth]->setPoints( + toVector3d(handler->corner1), + Base::Vector3d() + ); double startAngle = (handler->corner2 - handler->corner1).Angle(); onViewParameters[OnViewParameter::Sixth]->setLabelStartAngle(startAngle); onViewParameters[OnViewParameter::Sixth]->setLabelRange(handler->angle412); @@ -2451,8 +2761,7 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) } Base::Vector3d start = toVector3d(handler->corner3); - Base::Vector3d end = - Base::Vector3d(handler->corner3.x, handler->frameCorner3.y, 0.0); + Base::Vector3d end = Base::Vector3d(handler->corner3.x, handler->frameCorner3.y, 0.0); onViewParameters[OnViewParameter::Sixth]->setPoints(start, end); } else { @@ -2477,8 +2786,7 @@ void DSHRectangleController::adaptParameters(Base::Vector2d onSketchPos) } Base::Vector3d start = toVector3d(handler->corner3); - Base::Vector3d vec = - toVector3d((handler->corner3 - handler->corner2).Normalize()); + Base::Vector3d vec = toVector3d((handler->corner3 - handler->corner2).Normalize()); Base::Vector3d end = start + handler->thickness * vec; onViewParameters[OnViewParameter::Eighth]->setPoints(start, end); } @@ -2581,8 +2889,7 @@ void DSHRectangleController::computeNextDrawSketchHandlerMode() } } break; case SelectMode::SeekFifth: { - if (handler->makeFrame - && onViewParameters[OnViewParameter::Eighth]->hasFinishedEditing) { + if (handler->makeFrame && onViewParameters[OnViewParameter::Eighth]->hasFinishedEditing) { handler->setNextState(SelectMode::End); } } break; @@ -2656,41 +2963,39 @@ void DSHRectangleController::addConstraints() } auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstPointId, PointPos::start), - GeoElementId::VAxis, - x0, - obj); + ConstraintToAttachment(GeoElementId(firstPointId, PointPos::start), GeoElementId::VAxis, x0, obj); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstPointId, PointPos::start), - GeoElementId::HAxis, - y0, - obj); + ConstraintToAttachment(GeoElementId(firstPointId, PointPos::start), GeoElementId::HAxis, y0, obj); }; auto constraintlength = [&]() { int curveId = reverse ? firstCurve : firstCurve + 1; - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", - curveId, - 1, - curveId + 2, - 2, - fabs(length)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", + curveId, + 1, + curveId + 2, + 2, + fabs(length) + ); }; auto constraintwidth = [&]() { int curveId = reverse ? firstCurve + 1 : firstCurve; - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", - curveId, - 1, - curveId + 2, - 2, - fabs(width)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", + curveId, + 1, + curveId + 2, + 2, + fabs(width) + ); }; // NOTE: if AutoConstraints is empty, we can add constraints directly without any diagnose. No @@ -2722,7 +3027,8 @@ void DSHRectangleController::addConstraints() // each constraint addition firstpointinfo = handler->getPointInfo( - GeoElementId(firstPointId, PointPos::start)); // get updated point position + GeoElementId(firstPointId, PointPos::start) + ); // get updated point position } if (y0set && firstpointinfo.isYDoF()) { @@ -2771,60 +3077,72 @@ void DSHRectangleController::addConstraints() if (innerAngleSet) { if (fabs(innerAngle - pi / 2) > Precision::Confusion()) { // if 90? then perpendicular already created. - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f)) ", - firstCurve + 1, - 1, - firstCurve, - 2, - innerAngle); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f)) ", + firstCurve + 1, + 1, + firstCurve, + 2, + innerAngle + ); } } } else if (handler->constructionMethod() == ConstructionMethod::CenterAnd3Points) { if (corner1xSet) { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::VAxis, - corner1x, - obj); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::start), + GeoElementId::VAxis, + corner1x, + obj + ); } if (corner1ySet) { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::start), - GeoElementId::HAxis, - corner1y, - obj); + ConstraintToAttachment( + GeoElementId(firstCurve, PointPos::start), + GeoElementId::HAxis, + corner1y, + obj + ); } if (innerAngleSet) { if (fabs(innerAngle - pi / 2) > Precision::Confusion()) { // if 90? then perpendicular already created. - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f)) ", - firstCurve, - 1, - firstCurve + 3, - 2, - innerAngle); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%d,%d,%f)) ", + firstCurve, + 1, + firstCurve + 3, + 2, + innerAngle + ); } } } if (radiusSet && radius > Precision::Confusion()) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve + 5, // NOLINT - radius); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve + 5, // NOLINT + radius + ); } bool negThicknessEqualRadius = fabs(radius + thickness) < Precision::Confusion(); // in the case where negative thickness = radius, the inner rectangle has its corner // constrained to the mid of the arcs of the outer rectangle. So thickness would be redundant if (thicknessSet && !negThicknessEqualRadius) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%f)) ", - firstCurve + (handler->roundCorners == true ? 8 : 4), // NOLINT - 1, - firstCurve, - fabs(thickness)); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%f)) ", + firstCurve + (handler->roundCorners == true ? 8 : 4), // NOLINT + 1, + firstCurve, + fabs(thickness) + ); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h index 3616afc32f..9c7788a159 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerRotate.h @@ -45,14 +45,14 @@ namespace SketcherGui class DrawSketchHandlerRotate; -using DSHRotateController = - DrawSketchDefaultWidgetController, - /*WidgetParametersT =*/WidgetParameters<1>, - /*WidgetCheckboxesT =*/WidgetCheckboxes<1>, - /*WidgetComboboxesT =*/WidgetComboboxes<0>>; +using DSHRotateController = DrawSketchDefaultWidgetController< + DrawSketchHandlerRotate, + StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/0, + /*OnViewParametersT =*/OnViewParameters<4>, + /*WidgetParametersT =*/WidgetParameters<1>, + /*WidgetCheckboxesT =*/WidgetCheckboxes<1>, + /*WidgetComboboxesT =*/WidgetComboboxes<0>>; using DSHRotateControllerBase = DSHRotateController::ControllerBase; @@ -150,11 +150,13 @@ private: commandAddShapeGeometryAndConstraints(); - expressionHelper.copyExpressionsToNewConstraints(sketchgui->getSketchObject(), - listOfGeoIds, - ShapeGeometry.size(), - numberOfCopies, - 1); + expressionHelper.copyExpressionsToNewConstraints( + sketchgui->getSketchObject(), + listOfGeoIds, + ShapeGeometry.size(), + numberOfCopies, + 1 + ); if (deleteOriginal) { deleteOriginalGeos(); @@ -164,16 +166,21 @@ private: } catch (const Base::Exception& e) { e.reportException(); - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to rotate")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to rotate") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -256,9 +263,7 @@ private: } stream << listOfGeoIds[listOfGeoIds.size() - 1]; try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "delGeometries([%s])", - stream.str().c_str()); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "delGeometries([%s])", stream.str().c_str()); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); @@ -273,9 +278,11 @@ private: if (state() == SelectMode::SeekSecond) { if (length > Precision::Confusion()) { - addLineToShapeGeometry(toVector3d(centerPoint), - toVector3d(startPoint), - isConstructionMode()); + addLineToShapeGeometry( + toVector3d(centerPoint), + toVector3d(startPoint), + isConstructionMode() + ); } return; } @@ -347,15 +354,13 @@ private: } else if ((cstr->Type == Coincident || cstr->Type == Tangent || cstr->Type == Symmetric || cstr->Type == Perpendicular - || cstr->Type == Parallel || cstr->Type == Equal - || cstr->Type == Angle || cstr->Type == PointOnObject - || cstr->Type == InternalAlignment) + || cstr->Type == Parallel || cstr->Type == Equal || cstr->Type == Angle + || cstr->Type == PointOnObject || cstr->Type == InternalAlignment) && firstIndex >= 0 && secondIndex >= 0 && thirdIndex == GeoEnum::GeoUndef) { newConstr->Second = secondIndexi; } - else if ((cstr->Type == Radius || cstr->Type == Diameter - || cstr->Type == Weight) + else if ((cstr->Type == Radius || cstr->Type == Diameter || cstr->Type == Weight) && firstIndex >= 0) { if (deleteOriginal || !cloneConstraints) { newConstr->setValue(cstr->getValue()); @@ -462,30 +467,37 @@ void DSHRotateController::configureToolWidget() if (!init) { // Code to be executed only upon initialisation toolWidget->setCheckboxLabel( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_offset", "Apply equal constraints")); + QApplication::translate("TaskSketcherTool_c1_offset", "Apply equal constraints") + ); toolWidget->setCheckboxToolTip( WCheckbox::FirstBox, QStringLiteral("

      ") - + QApplication::translate("TaskSketcherTool_c1_offset", - "If this option is selected dimensional constraints are " - "excluded from the operation.\n" - "Instead equal constraints are applied between the " - "original objects and their copies.") - + QStringLiteral("

      ")); + + QApplication::translate( + "TaskSketcherTool_c1_offset", + "If this option is selected dimensional constraints are " + "excluded from the operation.\n" + "Instead equal constraints are applied between the " + "original objects and their copies." + ) + + QStringLiteral("

      ") + ); } onViewParameters[OnViewParameter::First]->setLabelType(Gui::SoDatumLabel::DISTANCEX); onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); toolWidget->setParameterLabel( WParameter::First, - QApplication::translate("TaskSketcherTool_p4_rotate", "Copies (+'U'/ -'J')")); + QApplication::translate("TaskSketcherTool_p4_rotate", "Copies (+'U'/ -'J')") + ); toolWidget->setParameter(OnViewParameter::First, 0.0); toolWidget->configureParameterUnit(OnViewParameter::First, Base::Unit()); toolWidget->configureParameterMin(OnViewParameter::First, 0.0); // NOLINT diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h index 8389192d2a..97d6003aed 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerScale.h @@ -52,14 +52,14 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerScale; -using DSHScaleController = - DrawSketchDefaultWidgetController, - /*WidgetParametersT =*/WidgetParameters<0>, - /*WidgetCheckboxesT =*/WidgetCheckboxes<1>, - /*WidgetComboboxesT =*/WidgetComboboxes<0>>; +using DSHScaleController = DrawSketchDefaultWidgetController< + DrawSketchHandlerScale, + StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/0, + /*OnViewParametersT =*/OnViewParameters<3>, + /*WidgetParametersT =*/WidgetParameters<0>, + /*WidgetCheckboxesT =*/WidgetCheckboxes<1>, + /*WidgetComboboxesT =*/WidgetComboboxes<0>>; using DSHScaleControllerBase = DSHScaleController::ControllerBase; @@ -90,8 +90,11 @@ public: ~DrawSketchHandlerScale() override = default; - static std::unique_ptr - make_centerScaleAll(SketcherGui::ViewProviderSketch* vp, double scaleFactor, bool abortOnFail) + static std::unique_ptr make_centerScaleAll( + SketcherGui::ViewProviderSketch* vp, + double scaleFactor, + bool abortOnFail + ) { std::vector allGeoIds(vp->getSketchObject()->Geometry.getValues().size()); std::iota(allGeoIds.begin(), allGeoIds.end(), 0); @@ -113,8 +116,11 @@ public: if (scaleFactor <= Precision::Confusion() || !std::isfinite(scaleFactor)) { THROWM( Base::ValueError, - QT_TRANSLATE_NOOP("Notifications", - "Invalid scale factor. Scale factor must be a positive number.")); + QT_TRANSLATE_NOOP( + "Notifications", + "Invalid scale factor. Scale factor must be a positive number." + ) + ); } try { @@ -136,18 +142,23 @@ public: } catch (const Base::Exception& e) { e.reportException(); - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to scale")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to scale") + ); if (abortOnFail) { Gui::Command::abortCommand(); } - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -292,9 +303,11 @@ private: } stream << listOfGeoIds[listOfGeoIds.size() - 1]; try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "delGeometries([%s], True)", - stream.str().c_str()); + Gui::cmdAppObjectArgs( + sketchgui->getObject(), + "delGeometries([%s], True)", + stream.str().c_str() + ); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); @@ -315,9 +328,7 @@ private: } stream << "(" << geoId << "," << listOfFacadeIds.back() << ")"; try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "setGeometryIds([%s])", - stream.str().c_str()); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "setGeometryIds([%s])", stream.str().c_str()); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); @@ -360,12 +371,15 @@ private: auto* arcOfCircle = static_cast(geo); // NOLINT arcOfCircle->setRadius(arcOfCircle->getRadius() * scaleFactor); arcOfCircle->setCenter( - getScaledPoint(arcOfCircle->getCenter(), referencePoint, scaleFactor)); + getScaledPoint(arcOfCircle->getCenter(), referencePoint, scaleFactor) + ); } else if (isLineSegment(*geo)) { auto* line = static_cast(geo); // NOLINT - line->setPoints(getScaledPoint(line->getStartPoint(), referencePoint, scaleFactor), - getScaledPoint(line->getEndPoint(), referencePoint, scaleFactor)); + line->setPoints( + getScaledPoint(line->getStartPoint(), referencePoint, scaleFactor), + getScaledPoint(line->getEndPoint(), referencePoint, scaleFactor) + ); } else if (isEllipse(*geo)) { auto* ellipse = static_cast(geo); // NOLINT @@ -381,8 +395,7 @@ private: ellipse->setMajorRadius(ellipse->getMajorRadius() * scaleFactor); ellipse->setMinorRadius(ellipse->getMinorRadius() * scaleFactor); } - ellipse->setCenter( - getScaledPoint(ellipse->getCenter(), referencePoint, scaleFactor)); + ellipse->setCenter(getScaledPoint(ellipse->getCenter(), referencePoint, scaleFactor)); } else if (isArcOfEllipse(*geo)) { auto* arcOfEllipse = static_cast(geo); // NOLINT @@ -397,14 +410,16 @@ private: arcOfEllipse->setMinorRadius(arcOfEllipse->getMinorRadius() * scaleFactor); } arcOfEllipse->setCenter( - getScaledPoint(arcOfEllipse->getCenter(), referencePoint, scaleFactor)); + getScaledPoint(arcOfEllipse->getCenter(), referencePoint, scaleFactor) + ); } else if (isArcOfHyperbola(*geo)) { auto* arcOfHyperbola = static_cast(geo); // NOLINT arcOfHyperbola->setMajorRadius(arcOfHyperbola->getMajorRadius() * scaleFactor); arcOfHyperbola->setMinorRadius(arcOfHyperbola->getMinorRadius() * scaleFactor); arcOfHyperbola->setCenter( - getScaledPoint(arcOfHyperbola->getCenter(), referencePoint, scaleFactor)); + getScaledPoint(arcOfHyperbola->getCenter(), referencePoint, scaleFactor) + ); } else if (isArcOfParabola(*geo)) { auto* arcOfParabola = static_cast(geo); // NOLINT @@ -413,7 +428,8 @@ private: arcOfParabola->getRange(start, end, true); arcOfParabola->setRange(start * scaleFactor, end * scaleFactor, true); arcOfParabola->setCenter( - getScaledPoint(arcOfParabola->getCenter(), referencePoint, scaleFactor)); + getScaledPoint(arcOfParabola->getCenter(), referencePoint, scaleFactor) + ); } else if (isBSplineCurve(*geo)) { auto* bSpline = static_cast(geo); // NOLINT @@ -482,15 +498,13 @@ private: newConstr->First = firstIndex; newConstr->setValue(newConstr->getValue() * scaleFactor); } - else if ((cstr->Type == Distance || cstr->Type == DistanceX - || cstr->Type == DistanceY) + else if ((cstr->Type == Distance || cstr->Type == DistanceX || cstr->Type == DistanceY) && firstIndex != GeoEnum::GeoUndef && secondIndex != GeoEnum::GeoUndef) { newConstr->First = firstIndex; newConstr->Second = secondIndex; newConstr->setValue(newConstr->getValue() * scaleFactor); } - else if ((cstr->Type == Distance || cstr->Type == DistanceX - || cstr->Type == DistanceY) + else if ((cstr->Type == Distance || cstr->Type == DistanceX || cstr->Type == DistanceY) && firstIndex != GeoEnum::GeoUndef && cstr->Second == GeoEnum::GeoUndef) { newConstr->First = firstIndex; newConstr->setValue(newConstr->getValue() * scaleFactor); @@ -554,9 +568,11 @@ private: } return index + firstCurveCreated; } - Base::Vector3d getScaledPoint(Base::Vector3d&& pointToScale, - const Base::Vector2d& referencePoint, - double scaleFactor) + Base::Vector3d getScaledPoint( + Base::Vector3d&& pointToScale, + const Base::Vector2d& referencePoint, + double scaleFactor + ) { Base::Vector2d pointToScale2D; pointToScale2D.x = pointToScale.x; @@ -592,14 +608,16 @@ void DSHScaleController::configureToolWidget() if (!init) { // Code to be executed only upon initialisation toolWidget->setCheckboxLabel( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_scale", "Keep original geometries (U)")); + QApplication::translate("TaskSketcherTool_c1_scale", "Keep original geometries (U)") + ); } onViewParameters[OnViewParameter::First]->setLabelType(Gui::SoDatumLabel::DISTANCEX); onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Forced); + Gui::EditableDatumLabel::Function::Forced + ); } template<> @@ -656,10 +674,14 @@ void DSHScaleController::adaptParameters(Base::Vector2d onSketchPos) bool sameSign = onSketchPos.x * onSketchPos.y > 0.; onViewParameters[OnViewParameter::First]->setLabelAutoDistanceReverse(!sameSign); onViewParameters[OnViewParameter::Second]->setLabelAutoDistanceReverse(sameSign); - onViewParameters[OnViewParameter::First]->setPoints(Base::Vector3d(), - toVector3d(onSketchPos)); - onViewParameters[OnViewParameter::Second]->setPoints(Base::Vector3d(), - toVector3d(onSketchPos)); + onViewParameters[OnViewParameter::First]->setPoints( + Base::Vector3d(), + toVector3d(onSketchPos) + ); + onViewParameters[OnViewParameter::Second]->setPoints( + Base::Vector3d(), + toVector3d(onSketchPos) + ); } break; case SelectMode::SeekThird: { if (!onViewParameters[OnViewParameter::Third]->isSet) { diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h index de778a4cee..5d23e575fc 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h @@ -50,14 +50,14 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerSlot; -using DSHSlotController = - DrawSketchDefaultWidgetController, // NOLINT - /*WidgetParametersT =*/WidgetParameters<0>, // NOLINT - /*WidgetCheckboxesT =*/WidgetCheckboxes<0>, // NOLINT - /*WidgetComboboxesT =*/WidgetComboboxes<0>>; // NOLINT +using DSHSlotController = DrawSketchDefaultWidgetController< + DrawSketchHandlerSlot, + StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/2, + /*OnViewParametersT =*/OnViewParameters<5>, // NOLINT + /*WidgetParametersT =*/WidgetParameters<0>, // NOLINT + /*WidgetCheckboxesT =*/WidgetCheckboxes<0>, // NOLINT + /*WidgetComboboxesT =*/WidgetComboboxes<0>>; // NOLINT using DSHSlotControllerBase = DSHSlotController::ControllerBase; @@ -113,9 +113,7 @@ private: startPoint = onSketchPos; - seekAndRenderAutoConstraint(sugConstraints[0], - onSketchPos, - Base::Vector2d(0.f, 0.f)); + seekAndRenderAutoConstraint(sugConstraints[0], onSketchPos, Base::Vector2d(0.f, 0.f)); } break; case SelectMode::SeekSecond: { toolWidgetManager.drawDirectionAtCursor(onSketchPos, startPoint); @@ -128,10 +126,12 @@ private: CreateAndDrawShapeGeometry(); - seekAndRenderAutoConstraint(sugConstraints[1], - onSketchPos, - secondPoint - startPoint, - AutoConstraint::VERTEX_NO_TANGENCY); + seekAndRenderAutoConstraint( + sugConstraints[1], + onSketchPos, + secondPoint - startPoint, + AutoConstraint::VERTEX_NO_TANGENCY + ); } break; case SelectMode::SeekThird: { /*To follow the cursor, r should adapt depending on the position of the cursor. If @@ -140,17 +140,18 @@ private: are both less than or equal to ninety degrees. An angle ?ABC is greater than ninety degrees iff AB^2 + BC^2 < AC^2.*/ - double L1 = (onSketchPos - startPoint) - .Length(); // distance between first center and onSketchPos - double L2 = (onSketchPos - secondPoint) - .Length(); // distance between second center and onSketchPos + double L1 = (onSketchPos - startPoint).Length(); // distance between first center + // and onSketchPos + double L2 = (onSketchPos - secondPoint).Length(); // distance between second center + // and onSketchPos - if ((L1 * L1 + length * length > L2 * L2) - && (L2 * L2 + length * length > L1 * L1)) { + if ((L1 * L1 + length * length > L2 * L2) && (L2 * L2 + length * length > L1 * L1)) { // distance of onSketchPos to the line StartPos-SecondPos - radius = (abs((secondPoint.y - startPoint.y) * onSketchPos.x - - (secondPoint.x - startPoint.x) * onSketchPos.y - + secondPoint.x * startPoint.y - secondPoint.y * startPoint.x)) + radius = (abs( + (secondPoint.y - startPoint.y) * onSketchPos.x + - (secondPoint.x - startPoint.x) * onSketchPos.y + + secondPoint.x * startPoint.y - secondPoint.y * startPoint.x + )) / length; } else { @@ -180,16 +181,21 @@ private: Gui::Command::commitCommand(); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add slot")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add slot") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -206,19 +212,21 @@ private: } if (avoidRedundants && alignmentCstr) { - removeRedundantHorizontalVertical(getSketchObject(), - sugConstraints[0], - sugConstraints[1]); + removeRedundantHorizontalVertical(getSketchObject(), sugConstraints[0], sugConstraints[1]); } // add auto constraints for the center of 1st arc - generateAutoConstraintsOnElement(sugConstraints[0], - getHighestCurveIndex() - 3, - Sketcher::PointPos::mid); + generateAutoConstraintsOnElement( + sugConstraints[0], + getHighestCurveIndex() - 3, + Sketcher::PointPos::mid + ); - generateAutoConstraintsOnElement(sugConstraints[1], - getHighestCurveIndex() - 2, - Sketcher::PointPos::mid); + generateAutoConstraintsOnElement( + sugConstraints[1], + getHighestCurveIndex() - 2, + Sketcher::PointPos::mid + ); // Ensure temporary autoconstraints do not generate a redundancy and that the geometry // parameters are accurate This is particularly important for adding widget mandated @@ -287,17 +295,21 @@ private: return; } - Part::GeomArcOfCircle* arc1 = addArcToShapeGeometry(toVector3d(startPoint), - pi / 2 + angle, - 1.5 * pi + angle, - radius, - isConstructionMode()); + Part::GeomArcOfCircle* arc1 = addArcToShapeGeometry( + toVector3d(startPoint), + pi / 2 + angle, + 1.5 * pi + angle, + radius, + isConstructionMode() + ); - Part::GeomArcOfCircle* arc2 = addArcToShapeGeometry(toVector3d(secondPoint), - 1.5 * pi + angle, - pi / 2 + angle, - radius, - isConstructionMode()); + Part::GeomArcOfCircle* arc2 = addArcToShapeGeometry( + toVector3d(secondPoint), + 1.5 * pi + angle, + pi / 2 + angle, + radius, + isConstructionMode() + ); Base::Vector3d p11 = arc1->getStartPoint(); Base::Vector3d p12 = arc1->getEndPoint(); @@ -309,30 +321,35 @@ private: addLineToShapeGeometry(p12, p21, isConstructionMode()); if (!onlyeditoutline) { - addToShapeConstraints(Sketcher::Tangent, - firstCurve, - Sketcher::PointPos::start, - firstCurve + 2, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Tangent, - firstCurve, - Sketcher::PointPos::end, - firstCurve + 3, - Sketcher::PointPos::start); - addToShapeConstraints(Sketcher::Tangent, - firstCurve + 1, - Sketcher::PointPos::end, - firstCurve + 2, - Sketcher::PointPos::end); - addToShapeConstraints(Sketcher::Tangent, - firstCurve + 1, - Sketcher::PointPos::start, - firstCurve + 3, - Sketcher::PointPos::end); - addToShapeConstraints(Sketcher::Equal, - firstCurve, - Sketcher::PointPos::none, - firstCurve + 1); + addToShapeConstraints( + Sketcher::Tangent, + firstCurve, + Sketcher::PointPos::start, + firstCurve + 2, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Tangent, + firstCurve, + Sketcher::PointPos::end, + firstCurve + 3, + Sketcher::PointPos::start + ); + addToShapeConstraints( + Sketcher::Tangent, + firstCurve + 1, + Sketcher::PointPos::end, + firstCurve + 2, + Sketcher::PointPos::end + ); + addToShapeConstraints( + Sketcher::Tangent, + firstCurve + 1, + Sketcher::PointPos::start, + firstCurve + 3, + Sketcher::PointPos::end + ); + addToShapeConstraints(Sketcher::Equal, firstCurve, Sketcher::PointPos::none, firstCurve + 1); } } @@ -372,13 +389,16 @@ void DSHSlotController::configureToolWidget() onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::RADIUS, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); } template<> @@ -427,8 +447,7 @@ void DSHSlotControllerBase::doEnforceControlParameters(Base::Vector2d& onSketchP onSketchPos = handler->startPoint + length * handler->capturedDirection; } else if (fourthParam->isSet) { - onSketchPos.ProjectToLine(onSketchPos - handler->startPoint, - handler->capturedDirection); + onSketchPos.ProjectToLine(onSketchPos - handler->startPoint, handler->capturedDirection); onSketchPos += handler->startPoint; } } break; @@ -488,17 +507,21 @@ void DSHSlotController::adaptParameters(Base::Vector2d onSketchPos) double range = (handler->secondPoint - handler->startPoint).Angle(); if (!fourthParam->isSet) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(range), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(range), + Base::Unit::Angle + ); } else if (vec.Length() > Precision::Confusion()) { double ovpRange = Base::toRadians(fourthParam->getValue()); if (fabs(range - ovpRange) > Precision::Confusion()) { - setOnViewParameterValue(OnViewParameter::Fourth, - Base::toDegrees(range), - Base::Unit::Angle); + setOnViewParameterValue( + OnViewParameter::Fourth, + Base::toDegrees(range), + Base::Unit::Angle + ); } } @@ -576,34 +599,27 @@ void DSHSlotController::addConstraints() using namespace Sketcher; auto constraintToOrigin = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::RtPnt, - x0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), GeoElementId::RtPnt, x0, obj); }; auto constraintx0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::VAxis, - x0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), GeoElementId::VAxis, x0, obj); }; auto constrainty0 = [&]() { - ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), - GeoElementId::HAxis, - y0, - obj); + ConstraintToAttachment(GeoElementId(firstCurve, PointPos::mid), GeoElementId::HAxis, y0, obj); }; auto constraintLength = [&]() { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", - firstCurve, - 3, - firstCurve + 1, - 3, - handler->length); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Distance',%d,%d,%d,%d,%f)) ", + firstCurve, + 3, + firstCurve + 1, + 3, + handler->length + ); }; auto constraintAngle = [&]() { @@ -612,11 +628,13 @@ void DSHSlotController::addConstraints() : handler->sugConstraints[1].back().Type; if (lastType != Sketcher::Horizontal && lastType != Sketcher::Vertical && lastType != Sketcher::Perpendicular && lastType != Sketcher::Parallel) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%d,%f)) ", - Sketcher::GeoEnum::HAxis, - firstCurve + 2, - handler->angle); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%f)) ", + Sketcher::GeoEnum::HAxis, + firstCurve + 2, + handler->angle + ); } }; @@ -653,7 +671,8 @@ void DSHSlotController::addConstraints() // each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::start)); // get updated point position + GeoElementId(firstCurve, PointPos::start) + ); // get updated point position } if (y0set && startpointinfo.isYDoF()) { @@ -663,7 +682,8 @@ void DSHSlotController::addConstraints() // each constraint addition startpointinfo = handler->getPointInfo( - GeoElementId(firstCurve, PointPos::start)); // get updated point position + GeoElementId(firstCurve, PointPos::start) + ); // get updated point position } auto endpointinfo = handler->getPointInfo(GeoElementId(firstCurve + 1, PointPos::mid)); @@ -683,10 +703,12 @@ void DSHSlotController::addConstraints() // No auto constraint in seekThird. if (radiusSet) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", - firstCurve, - handler->radius); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Radius',%d,%f)) ", + firstCurve, + handler->radius + ); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h index 4b900218a8..9779c24c9d 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h @@ -137,12 +137,14 @@ public: // 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()) { GeoId = (*conIt)->Second; @@ -153,18 +155,22 @@ 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(sketchgui->getObject()); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to add edge")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to add edge") + ); Gui::Command::abortCommand(); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h index 75d7a9a358..c0537e97b2 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSymmetry.h @@ -49,14 +49,14 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGe class DrawSketchHandlerSymmetry; -using DSHSymmetryController = - DrawSketchDefaultWidgetController, - /*WidgetParametersT =*/WidgetParameters<0>, - /*WidgetCheckboxesT =*/WidgetCheckboxes<2>, - /*WidgetComboboxesT =*/WidgetComboboxes<0>>; +using DSHSymmetryController = DrawSketchDefaultWidgetController< + DrawSketchHandlerSymmetry, + StateMachines::OneSeekEnd, + /*PAutoConstraintSize =*/0, + /*OnViewParametersT =*/OnViewParameters<0>, + /*WidgetParametersT =*/WidgetParameters<0>, + /*WidgetCheckboxesT =*/WidgetCheckboxes<2>, + /*WidgetComboboxesT =*/WidgetComboboxes<0>>; using DSHSymmetryControllerBase = DSHSymmetryController::ControllerBase; @@ -146,16 +146,21 @@ private: } catch (const Base::Exception& e) { e.reportException(); - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to create symmetry")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to create symmetry") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -233,9 +238,7 @@ public: } stream << listOfGeoIds[listOfGeoIds.size() - 1]; try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "delGeometries([%s])", - stream.str().c_str()); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "delGeometries([%s])", stream.str().c_str()); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); @@ -255,8 +258,8 @@ public: if (onlyeditoutline) { std::map dummy1; std::map dummy2; - std::vector symGeos = - Obj->getSymmetric(listOfGeoIds, dummy1, dummy2, refGeoId, refPosId); + std::vector symGeos + = Obj->getSymmetric(listOfGeoIds, dummy1, dummy2, refGeoId, refPosId); for (auto* geo : symGeos) { ShapeGeometry.emplace_back(geo); @@ -269,12 +272,14 @@ template<> void DSHSymmetryController::configureToolWidget() { if (!init) { // Code to be executed only upon initialisation - toolWidget->setCheckboxLabel(WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_symmetry", - "Delete original geometries (U)")); - toolWidget->setCheckboxLabel(WCheckbox::SecondBox, - QApplication::translate("TaskSketcherTool_c2_symmetry", - "Create symmetry constraints (J)")); + toolWidget->setCheckboxLabel( + WCheckbox::FirstBox, + QApplication::translate("TaskSketcherTool_c1_symmetry", "Delete original geometries (U)") + ); + toolWidget->setCheckboxLabel( + WCheckbox::SecondBox, + QApplication::translate("TaskSketcherTool_c2_symmetry", "Create symmetry constraints (J)") + ); } } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h index cdd9dddd1a..3f1bbcab99 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerTranslate.h @@ -52,14 +52,14 @@ namespace SketcherGui class DrawSketchHandlerTranslate; -using DSHTranslateController = - DrawSketchDefaultWidgetController, - /*WidgetParametersT =*/WidgetParameters<2>, - /*WidgetCheckboxesT =*/WidgetCheckboxes<1>, - /*WidgetComboboxesT =*/WidgetComboboxes<0>>; +using DSHTranslateController = DrawSketchDefaultWidgetController< + DrawSketchHandlerTranslate, + StateMachines::ThreeSeekEnd, + /*PAutoConstraintSize =*/0, + /*OnViewParametersT =*/OnViewParameters<6>, + /*WidgetParametersT =*/WidgetParameters<2>, + /*WidgetCheckboxesT =*/WidgetCheckboxes<1>, + /*WidgetComboboxesT =*/WidgetComboboxes<0>>; using DSHTranslateControllerBase = DSHTranslateController::ControllerBase; @@ -123,11 +123,13 @@ private: commandAddShapeGeometryAndConstraints(); - expressionHelper.copyExpressionsToNewConstraints(sketchgui->getSketchObject(), - listOfGeoIds, - ShapeGeometry.size(), - numberOfCopies, - secondNumberOfCopies); + expressionHelper.copyExpressionsToNewConstraints( + sketchgui->getSketchObject(), + listOfGeoIds, + ShapeGeometry.size(), + numberOfCopies, + secondNumberOfCopies + ); if (deleteOriginal) { deleteOriginalGeos(); @@ -137,16 +139,21 @@ private: } catch (const Base::Exception& e) { e.reportException(); - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to translate")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to translate") + ); Gui::Command::abortCommand(); - THROWM(Base::RuntimeError, - QT_TRANSLATE_NOOP( - "Notifications", - "Tool execution aborted") "\n") // This prevents constraints from being - // applied on non existing geometry + THROWM( + Base::RuntimeError, + QT_TRANSLATE_NOOP( + "Notifications", + "Tool execution aborted" + ) "\n" + ) // This prevents constraints from being + // applied on non existing geometry } } @@ -211,8 +218,7 @@ private: return false; } if (state() == SelectMode::SeekThird - && secondTranslationVector.Length() < Precision::Confusion() - && secondNumberOfCopies > 1) { + && secondTranslationVector.Length() < Precision::Confusion() && secondNumberOfCopies > 1) { return false; } return true; @@ -247,9 +253,7 @@ private: } stream << listOfGeoIds[listOfGeoIds.size() - 1]; try { - Gui::cmdAppObjectArgs(sketchgui->getObject(), - "delGeometries([%s])", - stream.str().c_str()); + Gui::cmdAppObjectArgs(sketchgui->getObject(), "delGeometries([%s])", stream.str().c_str()); } catch (const Base::Exception& e) { Base::Console().error("%s\n", e.what()); @@ -288,28 +292,25 @@ private: circle->setCenter(circle->getCenter() + vec); } else if (isArcOfCircle(*geo)) { - Part::GeomArcOfCircle* arc = - static_cast(geo); // NOLINT + Part::GeomArcOfCircle* arc = static_cast(geo); // NOLINT arc->setCenter(arc->getCenter() + vec); } else if (isEllipse(*geo)) { - Part::GeomEllipse* ellipse = - static_cast(geo); // NOLINT + Part::GeomEllipse* ellipse = static_cast(geo); // NOLINT ellipse->setCenter(ellipse->getCenter() + vec); } else if (isArcOfEllipse(*geo)) { - Part::GeomArcOfEllipse* aoe = - static_cast(geo); // NOLINT + Part::GeomArcOfEllipse* aoe = static_cast(geo); // NOLINT aoe->setCenter(aoe->getCenter() + vec); } else if (isArcOfHyperbola(*geo)) { - Part::GeomArcOfHyperbola* aoh = - static_cast(geo); // NOLINT + Part::GeomArcOfHyperbola* aoh = static_cast( + geo + ); // NOLINT aoh->setCenter(aoh->getCenter() + vec); } else if (isArcOfParabola(*geo)) { - Part::GeomArcOfParabola* aop = - static_cast(geo); // NOLINT + Part::GeomArcOfParabola* aop = static_cast(geo); // NOLINT aop->setCenter(aop->getCenter() + vec); } else if (isLineSegment(*geo)) { @@ -337,15 +338,19 @@ private: if (onlyeditoutline) { // Add the lines to show angle if (firstTranslationVector.Length() > Precision::Confusion()) { - addLineToShapeGeometry(toVector3d(referencePoint), - toVector3d(firstTranslationPoint), - true); + addLineToShapeGeometry( + toVector3d(referencePoint), + toVector3d(firstTranslationPoint), + true + ); } if (secondTranslationVector.Length() > Precision::Confusion()) { - addLineToShapeGeometry(toVector3d(referencePoint), - toVector3d(secondTranslationPoint), - true); + addLineToShapeGeometry( + toVector3d(referencePoint), + toVector3d(secondTranslationPoint), + true + ); } } else { @@ -386,10 +391,9 @@ private: } else if ((cstr->Type == Coincident || cstr->Type == Tangent || cstr->Type == Symmetric || cstr->Type == Perpendicular - || cstr->Type == Parallel || cstr->Type == Equal - || cstr->Type == Angle || cstr->Type == PointOnObject - || cstr->Type == Horizontal || cstr->Type == Vertical - || cstr->Type == InternalAlignment) + || cstr->Type == Parallel || cstr->Type == Equal || cstr->Type == Angle + || cstr->Type == PointOnObject || cstr->Type == Horizontal + || cstr->Type == Vertical || cstr->Type == InternalAlignment) && firstIndex >= 0 && secondIndex >= 0 && thirdIndex == GeoEnum::GeoUndef) { newConstr->Second = secondIndexi; @@ -450,11 +454,11 @@ public: {{.state = SelectMode::SeekFirst, .hints = {{tr("%1 pick reference point", "Sketcher Translate: hint"), {MouseLeft}}}}, {.state = SelectMode::SeekSecond, - .hints = {{tr("%1 set translation vector", "Sketcher Translate: hint"), - {MouseLeft}}}}, + .hints = {{tr("%1 set translation vector", "Sketcher Translate: hint"), {MouseLeft}}}}, {.state = SelectMode::SeekThird, - .hints = {{tr("%1 set second translation vector", "Sketcher Translate: hint"), - {MouseLeft}}}}}); + .hints + = {{tr("%1 set second translation vector", "Sketcher Translate: hint"), {MouseLeft}}}}} + ); } }; @@ -517,38 +521,48 @@ void DSHTranslateController::configureToolWidget() if (!init) { // Code to be executed only upon initialisation toolWidget->setCheckboxLabel( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_translate", "Apply equal constraints")); + QApplication::translate("TaskSketcherTool_c1_translate", "Apply equal constraints") + ); toolWidget->setCheckboxToolTip( WCheckbox::FirstBox, - QApplication::translate("TaskSketcherTool_c1_translate", - "If this option is selected dimensional constraints are " - "excluded from the operation.\n" - "Instead equal constraints are applied between the original " - "objects and their copies.")); + QApplication::translate( + "TaskSketcherTool_c1_translate", + "If this option is selected dimensional constraints are " + "excluded from the operation.\n" + "Instead equal constraints are applied between the original " + "objects and their copies." + ) + ); } onViewParameters[OnViewParameter::First]->setLabelType(Gui::SoDatumLabel::DISTANCEX); onViewParameters[OnViewParameter::Second]->setLabelType(Gui::SoDatumLabel::DISTANCEY); onViewParameters[OnViewParameter::Third]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fourth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Fifth]->setLabelType( Gui::SoDatumLabel::DISTANCE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); onViewParameters[OnViewParameter::Sixth]->setLabelType( Gui::SoDatumLabel::ANGLE, - Gui::EditableDatumLabel::Function::Dimensioning); + Gui::EditableDatumLabel::Function::Dimensioning + ); toolWidget->setParameterLabel( WParameter::First, - QApplication::translate("TaskSketcherTool_p3_translate", "Copies (+'U'/-'J')")); + QApplication::translate("TaskSketcherTool_p3_translate", "Copies (+'U'/-'J')") + ); toolWidget->setParameterLabel( WParameter::Second, - QApplication::translate("TaskSketcherTool_p5_translate", "Rows (+'R'/-'F')")); + QApplication::translate("TaskSketcherTool_p5_translate", "Rows (+'R'/-'F')") + ); toolWidget->setParameter(OnViewParameter::First, 0.0); toolWidget->setParameter(OnViewParameter::Second, 1.0); @@ -689,8 +703,10 @@ void DSHTranslateController::adaptParameters(Base::Vector2d onSketchPos) setOnViewParameterValue(OnViewParameter::Third, length); } - Base::Vector2d vec2d = Base::Vector2d(handler->firstTranslationVector.x, - handler->firstTranslationVector.y); + Base::Vector2d vec2d = Base::Vector2d( + handler->firstTranslationVector.x, + handler->firstTranslationVector.y + ); double angle = vec2d.Angle(); double range = angle * 180 / std::numbers::pi; @@ -714,8 +730,10 @@ void DSHTranslateController::adaptParameters(Base::Vector2d onSketchPos) setOnViewParameterValue(OnViewParameter::Fifth, length); } - Base::Vector2d vec2d = Base::Vector2d(handler->secondTranslationVector.x, - handler->secondTranslationVector.y); + Base::Vector2d vec2d = Base::Vector2d( + handler->secondTranslationVector.x, + handler->secondTranslationVector.y + ); double angle = vec2d.Angle(); double range = angle * 180 / std::numbers::pi; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h index 35e9616bb8..1688b2d775 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h @@ -107,12 +107,14 @@ public: auto sk = 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 + )) { return; } @@ -175,18 +177,22 @@ public: || geo->is() || geo->is()) { 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(sketchgui->getObject()); } catch (const Base::Exception&) { - Gui::NotifyError(sketchgui, - QT_TRANSLATE_NOOP("Notifications", "Error"), - QT_TRANSLATE_NOOP("Notifications", "Failed to trim edge")); + Gui::NotifyError( + sketchgui, + QT_TRANSLATE_NOOP("Notifications", "Error"), + QT_TRANSLATE_NOOP("Notifications", "Failed to trim edge") + ); Gui::Command::abortCommand(); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchKeyboardManager.cpp b/src/Mod/Sketcher/Gui/DrawSketchKeyboardManager.cpp index 8df2615a5c..f2d3961770 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchKeyboardManager.cpp +++ b/src/Mod/Sketcher/Gui/DrawSketchKeyboardManager.cpp @@ -52,9 +52,7 @@ DrawSketchKeyboardManager::DrawSketchKeyboardManager() timer.setSingleShot(true); - QObject::connect(&timer, &QTimer::timeout, [this]() { - onTimeOut(); - }); + QObject::connect(&timer, &QTimer::timeout, [this]() { onTimeOut(); }); } bool DrawSketchKeyboardManager::isMode(KeyboardEventHandlingMode mode) diff --git a/src/Mod/Sketcher/Gui/EditDatumDialog.cpp b/src/Mod/Sketcher/Gui/EditDatumDialog.cpp index 4a8f651852..e4846b4874 100644 --- a/src/Mod/Sketcher/Gui/EditDatumDialog.cpp +++ b/src/Mod/Sketcher/Gui/EditDatumDialog.cpp @@ -54,16 +54,18 @@ using namespace SketcherGui; /* TRANSLATOR SketcherGui::EditDatumDialog */ -bool SketcherGui::checkConstraintName(const Sketcher::SketchObject* sketch, - std::string constraintName) +bool SketcherGui::checkConstraintName(const Sketcher::SketchObject* sketch, std::string constraintName) { if (constraintName != Base::Tools::getIdentifier(constraintName)) { Gui::NotifyUserError( sketch, QT_TRANSLATE_NOOP("Notifications", "Value Error"), - QT_TRANSLATE_NOOP("Notifications", - "Invalid constraint name (must only contain alphanumericals and " - "underscores, and must not start with digit)")); + QT_TRANSLATE_NOOP( + "Notifications", + "Invalid constraint name (must only contain alphanumericals and " + "underscores, and must not start with digit)" + ) + ); return false; } @@ -97,10 +99,14 @@ int EditDatumDialog::exec(bool atCursor) if (Constr->isDimensional()) { if (sketch->hasConflicts()) { - Gui::TranslatedUserWarning(sketch, - QObject::tr("Dimensional constraint"), - QObject::tr("Not allowed to edit the datum because the " - "sketch contains conflicting constraints")); + Gui::TranslatedUserWarning( + sketch, + QObject::tr("Dimensional constraint"), + QObject::tr( + "Not allowed to edit the datum because the " + "sketch contains conflicting constraints" + ) + ); return QDialog::Rejected; } @@ -120,33 +126,38 @@ int EditDatumDialog::exec(bool atCursor) init_val.setUnit(Base::Unit::Angle); ui_ins_datum->label->setText(tr("Angle:")); ui_ins_datum->labelEdit->setParamGrpPath( - QByteArray("User parameter:BaseApp/History/SketcherAngle")); + 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")); + 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")); + 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")); + 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")); + QByteArray("User parameter:BaseApp/History/SketcherRefrIndexRatio") + ); ui_ins_datum->labelEdit->setSingleStep(0.05); } else { @@ -154,7 +165,8 @@ int EditDatumDialog::exec(bool atCursor) init_val.setUnit(Base::Unit::Length); ui_ins_datum->label->setText(tr("Length:")); ui_ins_datum->labelEdit->setParamGrpPath( - QByteArray("User parameter:BaseApp/History/SketcherLength")); + QByteArray("User parameter:BaseApp/History/SketcherLength") + ); } init_val.setValue(datum); @@ -167,18 +179,19 @@ int EditDatumDialog::exec(bool atCursor) 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); @@ -229,11 +242,13 @@ void EditDatumDialog::accepted() performAutoScale(newDatum); - Gui::cmdAppObjectArgs(sketch, - "setDatum(%i,App.Units.Quantity('%f %s'))", - ConstrNbr, - newDatum, - unitString); + Gui::cmdAppObjectArgs( + sketch, + "setDatum(%i,App.Units.Quantity('%f %s'))", + ConstrNbr, + newDatum, + unitString + ); } } @@ -245,10 +260,12 @@ void EditDatumDialog::accepted() constraintName = currConstraintName; } - Gui::cmdAppObjectArgs(sketch, - "renameConstraint(%d, u'%s')", - ConstrNbr, - constraintName.c_str()); + Gui::cmdAppObjectArgs( + sketch, + "renameConstraint(%d, u'%s')", + ConstrNbr, + constraintName.c_str() + ); } Gui::Command::commitCommand(); @@ -274,9 +291,7 @@ void EditDatumDialog::accepted() success = true; } 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(); @@ -312,8 +327,7 @@ void EditDatumDialog::drivingToggled(bool state) void EditDatumDialog::datumChanged() { - if (ui_ins_datum->labelEdit->text() - != std::as_const(ui_ins_datum->labelEdit)->getHistory()[0]) { + if (ui_ins_datum->labelEdit->text() != std::as_const(ui_ins_datum->labelEdit)->getHistory()[0]) { ui_ins_datum->cbDriving->setChecked(false); } } @@ -394,9 +408,10 @@ bool hasVisualFeature(App::DocumentObject* obj, App::DocumentObject* rootObj, Gu void EditDatumDialog::performAutoScale(double newDatum) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); - long autoScaleMode = - hGrp->GetInt("AutoScaleMode", static_cast(SketcherGui::AutoScaleMode::Always)); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); + long autoScaleMode + = hGrp->GetInt("AutoScaleMode", static_cast(SketcherGui::AutoScaleMode::Always)); // There is a single constraint in the sketch so it can // be used as a reference to scale the geometries around the origin @@ -404,8 +419,7 @@ void EditDatumDialog::performAutoScale(double newDatum) // was drawn with these geometries as scale references (use <= 2 because // the sketch axis are considered as external geometries) if ((autoScaleMode == static_cast(SketcherGui::AutoScaleMode::Always) - || (autoScaleMode - == static_cast(SketcherGui::AutoScaleMode::WhenNoScaleFeatureIsVisible) + || (autoScaleMode == static_cast(SketcherGui::AutoScaleMode::WhenNoScaleFeatureIsVisible) && !hasVisualFeature(sketch, nullptr, Gui::Application::Instance->activeDocument()))) && sketch->getExternalGeometryCount() <= 2) { try { diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp index e2cbc29740..56eeedbc9c 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp @@ -78,70 +78,54 @@ void EditModeCoinManager::ParameterObserver::initParameters() // 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); }}, {"BSplineControlPolygonVisible", [this](const std::string& param) { - updateOverlayVisibilityParameter< - OverlayVisibilityParameter::BSplineControlPolygonVisible>(param); + updateOverlayVisibilityParameter( + param + ); }}, {"BSplineCombVisible", [this](const std::string& param) { - updateOverlayVisibilityParameter( - param); + updateOverlayVisibilityParameter(param); }}, {"BSplineKnotMultiplicityVisible", [this](const std::string& param) { - updateOverlayVisibilityParameter< - OverlayVisibilityParameter::BSplineKnotMultiplicityVisible>(param); + updateOverlayVisibilityParameter( + param + ); }}, {"BSplinePoleWeightVisible", [this](const std::string& param) { updateOverlayVisibilityParameter( - param); + param + ); }}, {"ArcCircleHelperVisible", [this](const std::string& param) { updateOverlayVisibilityParameter( - param); + 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) { - Client.updateElementSizeParameters(); - }}, - {"MarkerSize", - [this](const std::string& param) { - Client.updateElementSizeParameters(); - }}, + [this](const std::string& param) { Client.updateElementSizeParameters(); }}, + {"MarkerSize", [this](const std::string& param) { Client.updateElementSizeParameters(); }}, {"EditSketcherFontSize", - [this](const std::string& param) { - Client.updateElementSizeParameters(); - }}, + [this](const std::string& param) { Client.updateElementSizeParameters(); }}, {"EdgeWidth", [this, &drawingParameters = Client.drawingParameters](const std::string& param) { updateWidth(drawingParameters.CurveWidth, param, 2); @@ -258,10 +242,7 @@ void EditModeCoinManager::ParameterObserver::initParameters() [this, drawingParameters = Client.drawingParameters](const std::string& param) { updateColor(drawingParameters.CursorTextColor, param); }}, - {"UserSchema", - [this](const std::string& param) { - updateUnit(param); - }}, + {"UserSchema", [this](const std::string& param) { updateUnit(param); }}, }; for (auto& val : str2updatefunction) { @@ -273,10 +254,12 @@ void EditModeCoinManager::ParameterObserver::initParameters() } void EditModeCoinManager::ParameterObserver::updateCurvedEdgeCountSegmentsParameter( - const std::string& parametername) + 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) { @@ -287,100 +270,111 @@ void EditModeCoinManager::ParameterObserver::updateCurvedEdgeCountSegmentsParame } void EditModeCoinManager::ParameterObserver::updateLineRenderingOrderParameters( - const std::string& parametername) + const std::string& parametername +) { (void)parametername; ParameterGrp::handle hGrpp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "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) + const std::string& parametername +) { (void)parametername; ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); Client.constraintParameters.bHideUnits = hGrpskg->GetBool("HideUnits", false); - Client.constraintParameters.bShowDimensionalName = - hGrpskg->GetBool("ShowDimensionalName", true); - Client.constraintParameters.sDimensionalStringFormat = - QString::fromStdString(hGrpskg->GetASCII("DimensionalStringFormat", "%N = %V")); + Client.constraintParameters.bShowDimensionalName = hGrpskg->GetBool("ShowDimensionalName", true); + Client.constraintParameters.sDimensionalStringFormat = QString::fromStdString( + hGrpskg->GetASCII("DimensionalStringFormat", "%N = %V") + ); } template void EditModeCoinManager::ParameterObserver::updateOverlayVisibilityParameter( - const std::string& parametername) + const std::string& parametername +) { ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/General" + ); if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplineDegree) { - Client.overlayParameters.bSplineDegreeVisible = - 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); + 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); + Client.overlayParameters.bSplineKnotMultiplicityVisible + = hGrpsk->GetBool(parametername.c_str(), true); } - else if constexpr (visibilityparameter - == OverlayVisibilityParameter::BSplinePoleWeightVisible) { - Client.overlayParameters.bSplinePoleWeightVisible = - hGrpsk->GetBool(parametername.c_str(), true); + else if constexpr (visibilityparameter == OverlayVisibilityParameter::BSplinePoleWeightVisible) { + 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::updateWidth(int& width, - const std::string& parametername, - int def) +void EditModeCoinManager::ParameterObserver::updateWidth( + int& width, + const std::string& parametername, + int def +) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/View"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/View" + ); width = hGrp->GetInt(parametername.c_str(), def); Client.updateInventorWidths(); } -void EditModeCoinManager::ParameterObserver::updatePattern(unsigned int& pattern, - const std::string& parametername, - unsigned int def) +void EditModeCoinManager::ParameterObserver::updatePattern( + unsigned int& pattern, + const std::string& parametername, + unsigned int def +) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/View"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/View" + ); pattern = hGrp->GetInt(parametername.c_str(), def); Client.updateInventorPatterns(); } -void EditModeCoinManager::ParameterObserver::updateColor(SbColor& sbcolor, - const std::string& parametername) +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()); @@ -401,26 +395,29 @@ void EditModeCoinManager::ParameterObserver::subscribeToParameters() { try { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); hGrp->Attach(this); ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/General" + ); hGrpsk->Attach(this); ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); hGrpskg->Attach(this); ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Units"); + "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()); + Base::Console() + .developerError("EditModeCoinManager", "Malformed parameter string: %s\n", e.what()); } } @@ -428,32 +425,37 @@ void EditModeCoinManager::ParameterObserver::unsubscribeToParameters() { try { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/View"); + "User parameter:BaseApp/Preferences/View" + ); hGrp->Detach(this); ParameterGrp::handle hGrpsk = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/General" + ); hGrpsk->Detach(this); ParameterGrp::handle hGrpskg = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); hGrpskg->Detach(this); ParameterGrp::handle hGrpu = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Units"); + "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; @@ -474,21 +476,23 @@ 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(); @@ -499,15 +503,16 @@ EditModeCoinManager::EditModeCoinManager(ViewProviderSketch& 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; @@ -527,8 +532,8 @@ void EditModeCoinManager::drawEditMarkers(const std::vector& Edi } 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()); @@ -540,10 +545,12 @@ void EditModeCoinManager::drawEditMarkers(const std::vector& Edi 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); + verts[i].setValue( + it->x, + it->y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zEdit + ); color[i] = drawingParameters.InformationColor; } @@ -552,8 +559,7 @@ void EditModeCoinManager::drawEditMarkers(const std::vector& Edi editModeScenegraphNodes.EditMarkerSet->markerIndex.finishEditing(); } -void EditModeCoinManager::drawEdit(const std::vector& EditCurve, - GeometryCreationMode mode) +void EditModeCoinManager::drawEdit(const std::vector& EditCurve, GeometryCreationMode mode) { editModeScenegraphNodes.EditCurveSet->numVertices.setNum(1); editModeScenegraphNodes.EditCurvesCoordinate->point.setNum(EditCurve.size()); @@ -567,10 +573,12 @@ void EditModeCoinManager::drawEdit(const std::vector& EditCurve, 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); + verts[i].setValue( + it->x, + it->y, + ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) + * drawingParameters.zEdit + ); switch (mode) { case GeometryCreationMode::Normal: color[i] = drawingParameters.CurveColor; @@ -587,8 +595,10 @@ void EditModeCoinManager::drawEdit(const std::vector& EditCurve, editModeScenegraphNodes.EditCurvesMaterials->diffuseColor.finishEditing(); } -void EditModeCoinManager::drawEdit(const std::list>& list, - GeometryCreationMode mode) +void EditModeCoinManager::drawEdit( + const std::list>& list, + GeometryCreationMode mode +) { int ncoords = 0; @@ -613,7 +623,8 @@ void EditModeCoinManager::drawEdit(const std::list>& p.x, p.y, ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) - * drawingParameters.zEdit); + * drawingParameters.zEdit + ); switch (mode) { case GeometryCreationMode::Normal: @@ -638,11 +649,11 @@ void EditModeCoinManager::drawEdit(const std::list>& 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) @@ -671,8 +682,7 @@ void EditModeCoinManager::setAxisPickStyle(bool on) } } -EditModeCoinManager::PreselectionResult -EditModeCoinManager::detectPreselection(SoPickedPoint* Point) +EditModeCoinManager::PreselectionResult EditModeCoinManager::detectPreselection(SoPickedPoint* Point) { EditModeCoinManager::PreselectionResult result; @@ -703,7 +713,8 @@ EditModeCoinManager::detectPreselection(SoPickedPoint* Point) int pindex = static_cast(point_detail)->getCoordinateIndex(); result.PointIndex = coinMapping.getPointVertexId( pindex, - l); // returns -1 for root, global VertexId for the rest of vertices. + l + ); // returns -1 for root, global VertexId for the rest of vertices. if (result.PointIndex == -1) { result.Cross = PreselectionResult::Axes::RootPoint; @@ -716,8 +727,7 @@ EditModeCoinManager::detectPreselection(SoPickedPoint* Point) // checking for a hit in the curves for (int t = 0; t < geometryLayerParameters.getSubLayerCount(); t++) { if (tail == editModeScenegraphNodes.CurveSet[l][t]) { - const SoDetail* curve_detail = - Point->getDetail(editModeScenegraphNodes.CurveSet[l][t]); + const SoDetail* curve_detail = Point->getDetail(editModeScenegraphNodes.CurveSet[l][t]); if (curve_detail && curve_detail->getTypeId() == SoLineDetail::getClassTypeId()) { // get the index int curveIndex = static_cast(curve_detail)->getLineIndex(); @@ -772,7 +782,8 @@ SoGroup* EditModeCoinManager::getSelectedConstraints() void EditModeCoinManager::processGeometryConstraintsInformationOverlay( const GeoListFacade& geolistfacade, - bool rebuildinformationlayer) + bool rebuildinformationlayer +) { overlayParameters.rebuildInformationLayer = rebuildinformationlayer; @@ -791,8 +802,7 @@ void EditModeCoinManager::updateOverlayParameters() > (2 * overlayParameters.currentBSplineCombRepresentationScale)) || (analysisResults.combRepresentationScale < (overlayParameters.currentBSplineCombRepresentationScale / 2))) { - overlayParameters.currentBSplineCombRepresentationScale = - analysisResults.combRepresentationScale; + overlayParameters.currentBSplineCombRepresentationScale = analysisResults.combRepresentationScale; } } @@ -803,10 +813,12 @@ void EditModeCoinManager::processGeometryInformationOverlay(const GeoListFacade& 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 @@ -828,14 +840,10 @@ void EditModeCoinManager::updateAxesLength(const Base::BoundBox2d& bb) { auto zCrossH = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) * drawingParameters.zCross; - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(0, - SbVec3f(bb.MinX, 0.0f, zCrossH)); - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(1, - SbVec3f(bb.MaxX, 0.0f, zCrossH)); - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(2, - SbVec3f(0.0f, bb.MinY, zCrossH)); - editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(3, - SbVec3f(0.0f, bb.MaxY, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(0, SbVec3f(bb.MinX, 0.0f, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(1, SbVec3f(bb.MaxX, 0.0f, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(2, SbVec3f(0.0f, bb.MinY, zCrossH)); + editModeScenegraphNodes.RootCrossCoordinate->point.set1Value(3, SbVec3f(0.0f, bb.MaxY, zCrossH)); } void EditModeCoinManager::updateColor() @@ -877,8 +885,7 @@ 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; @@ -899,18 +906,13 @@ 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; @@ -932,8 +934,8 @@ void EditModeCoinManager::createEditModeInventorNodes() editModeScenegraphNodes.OriginPointDrawStyle = new SoDrawStyle; editModeScenegraphNodes.OriginPointDrawStyle->setName("OriginPointDrawStyle"); - editModeScenegraphNodes.OriginPointDrawStyle->pointSize = - 8 * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.OriginPointDrawStyle->pointSize = 8 + * drawingParameters.pixelScalingFactor; originPointRoot->addChild(editModeScenegraphNodes.OriginPointDrawStyle); editModeScenegraphNodes.OriginPointCoordinate = new SoCoordinate3; @@ -944,8 +946,8 @@ void EditModeCoinManager::createEditModeInventorNodes() editModeScenegraphNodes.OriginPointSet = new SoMarkerSet; editModeScenegraphNodes.OriginPointSet->setName("OriginPointSet"); - editModeScenegraphNodes.OriginPointSet->markerIndex = - Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", drawingParameters.markerSize); + editModeScenegraphNodes.OriginPointSet->markerIndex + = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", drawingParameters.markerSize); originPointRoot->addChild(editModeScenegraphNodes.OriginPointSet); // stuff for the EditCurves +++++++++++++++++++++++++++++++++++++++ @@ -961,8 +963,8 @@ void EditModeCoinManager::createEditModeInventorNodes() editModeScenegraphNodes.EditCurvesDrawStyle = new SoDrawStyle; editModeScenegraphNodes.EditCurvesDrawStyle->setName("EditCurvesDrawStyle"); - editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = - 3 * drawingParameters.pixelScalingFactor; // Default value will be overridden in drawEdit() + editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = 3 + * drawingParameters.pixelScalingFactor; // Default value will be overridden in drawEdit() editCurvesRoot->addChild(editModeScenegraphNodes.EditCurvesDrawStyle); editModeScenegraphNodes.EditCurveSet = new SoLineSet; @@ -982,14 +984,14 @@ 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 ++++++++++++++++++++++++++++++++++++++ @@ -1033,8 +1035,8 @@ void EditModeCoinManager::createEditModeInventorNodes() // 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 @@ -1062,23 +1064,23 @@ void EditModeCoinManager::setEditDrawStyle(GeometryCreationMode mode) editModeScenegraphNodes.EditCurvesDrawStyle->lineWidth = toCopy->lineWidth; editModeScenegraphNodes.EditCurvesDrawStyle->linePattern = toCopy->linePattern; - editModeScenegraphNodes.EditCurvesDrawStyle->linePatternScaleFactor = - toCopy->linePatternScaleFactor; + editModeScenegraphNodes.EditCurvesDrawStyle->linePatternScaleFactor = toCopy->linePatternScaleFactor; } void EditModeCoinManager::updateElementSizeParameters() { // Add scaling to Constraint icons - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); double viewScalingFactor = hGrp->GetFloat("ViewScalingFactor", 1.0); viewScalingFactor = std::clamp(viewScalingFactor, 0.5, 5.0); int markerSize = hGrp->GetInt("MarkerSize", 7); - int defaultFontSizePixels = - defaultApplicationFontSizePixels(); // returns height in pixels, not points + int defaultFontSizePixels = defaultApplicationFontSizePixels(); // returns height in pixels, + // not points int sketcherfontSize = hGrp->GetInt("EditSketcherFontSize", defaultFontSizePixels); int constraintSymbolSizePref = hGrp->GetInt("ConstraintSymbolSize", defaultFontSizePixels); @@ -1093,16 +1095,17 @@ void EditModeCoinManager::updateElementSizeParameters() // 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. - drawingParameters.coinFontSize = - std::lround(sketcherfontSize * devicePixelRatio); // in pixels (Coin uses pixels) - drawingParameters.labelFontSize = std::lround(sketcherfontSize * devicePixelRatio * 72.0f - / dpi); // in points (SoDatumLabel uses points) + drawingParameters.coinFontSize = std::lround( + sketcherfontSize * devicePixelRatio + ); // in pixels (Coin uses pixels) + drawingParameters.labelFontSize = std::lround( + sketcherfontSize * devicePixelRatio * 72.0f / dpi + ); // in points (SoDatumLabel uses points) drawingParameters.constraintIconSize = constraintSymbolSizePref; auto supportedsizes = Gui::Inventor::MarkerBitmaps::getSupportedSizes("CIRCLE_LINE"); auto scaledMarkerSize = std::lround(markerSize * devicePixelRatio); - auto const it = - std::lower_bound(supportedsizes.begin(), supportedsizes.end(), scaledMarkerSize); + auto const it = std::lower_bound(supportedsizes.begin(), supportedsizes.end(), scaledMarkerSize); if (it != supportedsizes.end()) { scaledMarkerSize = *it; } @@ -1153,30 +1156,28 @@ void EditModeCoinManager::updateInventorNodeSizes() updateInventorWidths(); 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.PointsDrawStyle[l]->pointSize = 8 + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.PointSet[l]->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex( + "CIRCLE_FILLED", + drawingParameters.markerSize + ); } - editModeScenegraphNodes.OriginPointDrawStyle->pointSize = - 8 * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.OriginPointSet->markerIndex = - Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", drawingParameters.markerSize); + editModeScenegraphNodes.OriginPointDrawStyle->pointSize = 8 + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.OriginPointSet->markerIndex + = Gui::Inventor::MarkerBitmaps::getMarkerIndex("CIRCLE_FILLED", drawingParameters.markerSize); - 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); @@ -1185,39 +1186,33 @@ void EditModeCoinManager::updateInventorNodeSizes() void EditModeCoinManager::updateInventorWidths() { - editModeScenegraphNodes.CurvesDrawStyle->lineWidth = - drawingParameters.CurveWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesConstructionDrawStyle->lineWidth = - drawingParameters.ConstructionWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesInternalDrawStyle->lineWidth = - drawingParameters.InternalWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesExternalDrawStyle->lineWidth = - drawingParameters.ExternalWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->lineWidth = - drawingParameters.ExternalDefiningWidth * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesDrawStyle->lineWidth = drawingParameters.CurveWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesConstructionDrawStyle->lineWidth = drawingParameters.ConstructionWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesInternalDrawStyle->lineWidth = drawingParameters.InternalWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesExternalDrawStyle->lineWidth = drawingParameters.ExternalWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->lineWidth + = drawingParameters.ExternalDefiningWidth * drawingParameters.pixelScalingFactor; } void EditModeCoinManager::updateInventorPatterns() { editModeScenegraphNodes.CurvesDrawStyle->linePattern = drawingParameters.CurvePattern; - editModeScenegraphNodes.CurvesConstructionDrawStyle->linePattern = - drawingParameters.ConstructionPattern; - editModeScenegraphNodes.CurvesInternalDrawStyle->linePattern = - drawingParameters.InternalPattern; - editModeScenegraphNodes.CurvesExternalDrawStyle->linePattern = - drawingParameters.ExternalPattern; - editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->linePattern = - drawingParameters.ExternalDefiningPattern; + editModeScenegraphNodes.CurvesConstructionDrawStyle->linePattern + = drawingParameters.ConstructionPattern; + editModeScenegraphNodes.CurvesInternalDrawStyle->linePattern = drawingParameters.InternalPattern; + editModeScenegraphNodes.CurvesExternalDrawStyle->linePattern = drawingParameters.ExternalPattern; + editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->linePattern + = drawingParameters.ExternalDefiningPattern; } 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 c6c02a6660..cfbbba75cd 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.h @@ -209,8 +209,7 @@ public: /** @name Temporary edit curves and markers */ //@{ - void drawEditMarkers(const std::vector& EditMarkers, - unsigned int augmentationlevel); + void drawEditMarkers(const std::vector& EditMarkers, unsigned int augmentationlevel); void drawEdit(const std::vector& EditCurve, GeometryCreationMode mode); void drawEdit(const std::list>& list, GeometryCreationMode mode); void setPositionText(const Base::Vector2d& Pos, const SbString& txt); @@ -227,8 +226,10 @@ public: //@} /** @name update coin nodes*/ - void processGeometryConstraintsInformationOverlay(const GeoListFacade& geolistfacade, - bool rebuildinformationlayer); + void processGeometryConstraintsInformationOverlay( + const GeoListFacade& geolistfacade, + bool rebuildinformationlayer + ); void updateVirtualSpace(); @@ -249,8 +250,7 @@ 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*/ diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp index f53abf569f..45e2925e7a 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.cpp @@ -32,8 +32,7 @@ using namespace SketcherGui; -int GeometryLayerParameters::getSubLayerIndex(const int geoId, - const Sketcher::GeometryFacade* geom) const +int GeometryLayerParameters::getSubLayerIndex(const int geoId, const Sketcher::GeometryFacade* geom) const { bool isConstruction = geom->getConstruction(); bool isInternal = geom->isInternalAligned(); @@ -45,10 +44,12 @@ int GeometryLayerParameters::getSubLayerIndex(const int geoId, } } - return static_cast(isExternal ? SubLayer::External - : isInternal ? SubLayer::Internal - : isConstruction ? SubLayer::Construction - : SubLayer::Normal); + return static_cast( + isExternal ? SubLayer::External + : isInternal ? SubLayer::Internal + : isConstruction ? SubLayer::Construction + : SubLayer::Normal + ); } SbColor DrawingParameters::InformationColor(0.0f, 1.0f, 0.0f); // #00FF00 -> ( 0,255, 0) @@ -66,34 +67,35 @@ SbColor DrawingParameters::CrossColorV(Vcolor.r, Vcolor.g, Vcolor.b); 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::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::FullyConstraintElementColor(0.50f, - 0.81f, - 0.62f); // #80D0A0 -> (128,208,160) +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::CurveExternalDefiningColor(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::CurveExternalDefiningColor(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::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.5f, 0.5f, 0.5f); // ##7f7f7f -> (127,127,127) -SbColor DrawingParameters::CursorTextColor(0.0f, 0.0f, 1.0f); // #0000FF -> (0,0,255) +SbColor DrawingParameters::DeactivatedConstrDimColor(0.5f, 0.5f, 0.5f); // ##7f7f7f -> (127,127,127) +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 5305cdb15e..37425a2a65 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManagerParameters.h @@ -112,20 +112,19 @@ struct DrawingParameters static SbColor FullyConstraintElementColor; // Color for a fully constrained element static SbColor CurveColor; // Color for curves static SbColor PreselectColor; // Color used for preselection - static SbColor - PreselectSelectedColor; // Color used for preselection when geometry is already selected - static SbColor SelectColor; // Color used for selected geometry - static SbColor CurveExternalColor; // Color used for external geometry + static SbColor PreselectSelectedColor; // Color used for preselection when geometry is already + // selected + static SbColor SelectColor; // Color used for selected geometry + static SbColor CurveExternalColor; // Color used for external geometry static SbColor CurveExternalDefiningColor; // Color used for external defining 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 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 //@} @@ -134,8 +133,8 @@ struct DrawingParameters //@{ 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 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 @@ -145,12 +144,11 @@ struct DrawingParameters int ExternalWidth = 1; // width of external edges int ExternalDefiningWidth = 1; // width of external defining edges - unsigned int CurvePattern = 0b1111111111111111; // pattern of normal edges - unsigned int ConstructionPattern = 0b1111110011111100; // pattern of construction edges - unsigned int InternalPattern = 0b1111110011111100; // pattern of internal edges - unsigned int ExternalPattern = 0b1111110011111100; // pattern of external edges - unsigned int ExternalDefiningPattern = - 0b1111111111111111; // pattern of external defining edges + unsigned int CurvePattern = 0b1111111111111111; // pattern of normal edges + unsigned int ConstructionPattern = 0b1111110011111100; // pattern of construction edges + unsigned int InternalPattern = 0b1111110011111100; // pattern of internal edges + unsigned int ExternalPattern = 0b1111110011111100; // pattern of external edges + unsigned int ExternalDefiningPattern = 0b1111111111111111; // pattern of external defining edges //@} DrawingParameters() @@ -240,8 +238,7 @@ namespace std 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) @@ -390,9 +387,8 @@ struct OverlayParameters */ struct ConstraintParameters { - bool bHideUnits; // whether units should be hidden or not - bool - bShowDimensionalName; // whether the name of dimensional constraints should be shown or not + 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 }; @@ -581,8 +577,7 @@ struct CoinMapping //* These map a MF index (second index) within a coin layer (first index) for points or curves // to a GeoId */ - std::vector>> - CurvIdToGeoId; // conversion of SoLineSet index to GeoId + std::vector>> CurvIdToGeoId; // conversion of SoLineSet index to GeoId std::vector> PointIdToGeoId; // conversion of SoCoordinate3 index to GeoId std::vector> PointIdToPosId; // SoCoordinate3 index to PosId diff --git a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp index 196646edc4..141fac541c 100644 --- a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp @@ -77,7 +77,8 @@ EditModeConstraintCoinManager::EditModeConstraintCoinManager( GeometryLayerParameters& geometryLayerParams, ConstraintParameters& constraintParams, EditModeScenegraphNodes& editModeScenegraph, - CoinMapping& coinMap) + CoinMapping& coinMap +) : viewProvider(vp) , drawingParameters(drawingParams) , geometryLayerParameters(geometryLayerParams) @@ -91,8 +92,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); @@ -143,32 +144,31 @@ Restart: // update the virtual space updateVirtualSpace(); - auto getNormal = [](const GeoListFacade& geolistfacade, - const int geoid, - const Base::Vector3d& pointoncurve) { - auto geom = geolistfacade.getGeometryFromGeoId(geoid); - auto curve = dynamic_cast(geom); + auto getNormal = + [](const GeoListFacade& geolistfacade, const int geoid, const Base::Vector3d& pointoncurve) { + auto geom = geolistfacade.getGeometryFromGeoId(geoid); + auto curve = dynamic_cast(geom); - auto line = dynamic_cast(curve); + auto line = dynamic_cast(curve); - if (line) { - Base::Vector3d linedir = line->getEndPoint() - line->getStartPoint(); - return Base::Vector3d(-linedir.y, linedir.x, 0); - } - else { - Base::Vector3d normal; - try { - if (!(curve && curve->normalAt(pointoncurve, normal))) { + if (line) { + Base::Vector3d linedir = line->getEndPoint() - line->getStartPoint(); + return Base::Vector3d(-linedir.y, linedir.x, 0); + } + else { + Base::Vector3d normal; + try { + if (!(curve && curve->normalAt(pointoncurve, normal))) { + normal = Base::Vector3d(1, 0, 0); + } + } + catch (const Base::CADKernelError&) { normal = Base::Vector3d(1, 0, 0); } - } - catch (const Base::CADKernelError&) { - normal = Base::Vector3d(1, 0, 0); - } - return normal; - } - }; + return normal; + } + }; // go through the constraints and update the position int i = 0; @@ -185,8 +185,9 @@ Restart: } try { // because calculateNormalAtPoint, used in there, can throw // root separator for this constraint - SoSeparator* sep = - static_cast(editModeScenegraphNodes.constrGroup->getChild(i)); + SoSeparator* sep = static_cast( + editModeScenegraphNodes.constrGroup->getChild(i) + ); const Constraint* Constr = *it; if (Constr->First < -extGeoCount || Constr->First >= intGeoCount @@ -219,8 +220,8 @@ Restart: Base::Vector3d norm; if (geo->is()) { - const Part::GeomLineSegment* lineSeg = - static_cast(geo); + const Part::GeomLineSegment* lineSeg + = static_cast(geo); // calculate the half distance between the start and endpoint midpos = ((lineSeg->getEndPoint() + lineSeg->getStartPoint()) / 2); @@ -231,8 +232,8 @@ Restart: norm = Base::Vector3d(-dir.y, dir.x, 0); } else if (geo->is()) { - const Part::GeomBSplineCurve* bsp = - static_cast(geo); + const Part::GeomBSplineCurve* bsp + = static_cast(geo); midpos = Base::Vector3d(0, 0, 0); std::vector poles = bsp->getPoles(); @@ -260,15 +261,15 @@ Restart: angleplus = 0.; // arc angle (t parameter for ellipses) if (geo->is()) { - const Part::GeomCircle* circle = - static_cast(geo); + const Part::GeomCircle* circle + = static_cast(geo); ra = circle->getRadius(); angle = pi / 4; midpos = circle->getCenter(); } else if (geo->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo); + const Part::GeomArcOfCircle* arc + = static_cast(geo); ra = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); @@ -276,8 +277,8 @@ Restart: midpos = arc->getCenter(); } else if (geo->is()) { - const Part::GeomEllipse* ellipse = - static_cast(geo); + const Part::GeomEllipse* ellipse + = static_cast(geo); ra = ellipse->getMajorRadius(); rb = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); @@ -286,8 +287,8 @@ Restart: midpos = ellipse->getCenter(); } else if (geo->is()) { - const Part::GeomArcOfEllipse* aoe = - static_cast(geo); + const Part::GeomArcOfEllipse* aoe + = static_cast(geo); ra = aoe->getMajorRadius(); rb = aoe->getMinorRadius(); double startangle, endangle; @@ -298,8 +299,8 @@ Restart: midpos = aoe->getCenter(); } else if (geo->is()) { - const Part::GeomArcOfHyperbola* aoh = - static_cast(geo); + const Part::GeomArcOfHyperbola* aoh + = static_cast(geo); ra = aoh->getMajorRadius(); rb = aoh->getMinorRadius(); double startangle, endangle; @@ -310,8 +311,8 @@ Restart: midpos = aoh->getCenter(); } else if (geo->is()) { - const Part::GeomArcOfParabola* aop = - static_cast(geo); + const Part::GeomArcOfParabola* aop + = static_cast(geo); ra = aop->getFocal(); double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); @@ -328,21 +329,26 @@ Restart: || geo->is()) { 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; + 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. + 0 + ); // DeepSOIC: I'm not sure what dir is supposed to mean. } else { norm = Base::Vector3d(cos(angle), sin(angle), 0); @@ -356,21 +362,25 @@ Restart: norm, dir, 2.5, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); auto translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::FirstTranslationIndex))); + static_cast(ConstraintNodePosition::FirstTranslationIndex) + )); - translation->abPos = - SbVec3f(midpos.x, midpos.y, zConstrH); // Absolute Reference + 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); } else { assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); - assert(Constr->FirstPos != Sketcher::PointPos::none - && Constr->SecondPos != Sketcher::PointPos::none); + assert( + Constr->FirstPos != Sketcher::PointPos::none + && Constr->SecondPos != Sketcher::PointPos::none + ); Base::Vector3d midpos1, dir1, norm1; Base::Vector3d midpos2, dir2, norm2; @@ -388,10 +398,12 @@ Restart: norm1, dir1, 4.0, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); auto translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::FirstTranslationIndex))); + static_cast(ConstraintNodePosition::FirstTranslationIndex) + )); translation->abPos = SbVec3f(midpos1.x, midpos1.y, zConstrH); translation->translation = SbVec3f(relpos1.x, relpos1.y, 0); @@ -401,16 +413,18 @@ Restart: norm2, dir2, 4.0, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); Base::Vector3d secondPos = midpos2 - midpos1; translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::SecondTranslationIndex))); + static_cast(ConstraintNodePosition::SecondTranslationIndex) + )); translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); - translation->translation = - SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); + translation->translation + = SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); } } break; case Perpendicular: { @@ -424,10 +438,9 @@ Restart: 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 - if (Constr->Third != GeoEnum::GeoUndef || // perpty via point - Constr->FirstPos - != Sketcher::PointPos::none) { // endpoint-to-curve or - // endpoint-to-endpoint perpty + 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; @@ -466,16 +479,15 @@ Restart: else if (Constr->FirstPos == Sketcher::PointPos::none) { if (geo1->is()) { - const Part::GeomLineSegment* lineSeg1 = - static_cast(geo1); + const Part::GeomLineSegment* lineSeg1 + = static_cast(geo1); midpos1 = ((lineSeg1->getEndPoint() + lineSeg1->getStartPoint()) / 2); - dir1 = - (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()).Normalize(); + dir1 = (lineSeg1->getEndPoint() - lineSeg1->getStartPoint()).Normalize(); norm1 = Base::Vector3d(-dir1.y, dir1.x, 0.); } else if (geo1->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo1); + const Part::GeomArcOfCircle* arc + = static_cast(geo1); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle) / 2; @@ -484,8 +496,7 @@ Restart: midpos1 = arc->getCenter() + arc->getRadius() * norm1; } else if (geo1->is()) { - const Part::GeomCircle* circle = - static_cast(geo1); + const Part::GeomCircle* circle = static_cast(geo1); norm1 = Base::Vector3d(cos(pi / 4), sin(pi / 4), 0); dir1 = Base::Vector3d(-norm1.y, norm1.x, 0); midpos1 = circle->getCenter() + circle->getRadius() * norm1; @@ -495,16 +506,15 @@ Restart: } if (geo2->is()) { - const Part::GeomLineSegment* lineSeg2 = - static_cast(geo2); + const Part::GeomLineSegment* lineSeg2 + = static_cast(geo2); midpos2 = ((lineSeg2->getEndPoint() + lineSeg2->getStartPoint()) / 2); - dir2 = - (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()).Normalize(); + dir2 = (lineSeg2->getEndPoint() - lineSeg2->getStartPoint()).Normalize(); norm2 = Base::Vector3d(-dir2.y, dir2.x, 0.); } else if (geo2->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo2); + const Part::GeomArcOfCircle* arc + = static_cast(geo2); double startangle, endangle, midangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); midangle = (startangle + endangle) / 2; @@ -513,8 +523,7 @@ Restart: midpos2 = arc->getCenter() + arc->getRadius() * norm2; } else if (geo2->is()) { - const Part::GeomCircle* circle = - static_cast(geo2); + const Part::GeomCircle* circle = static_cast(geo2); norm2 = Base::Vector3d(cos(pi / 4), sin(pi / 4), 0); dir2 = Base::Vector3d(-norm2.y, norm2.x, 0); midpos2 = circle->getCenter() + circle->getRadius() * norm2; @@ -525,15 +534,17 @@ Restart: twoIcons = true; } - Base::Vector3d relpos1 = - seekConstraintPosition(midpos1, - norm1, - dir1, - 4.0, - editModeScenegraphNodes.constrGroup->getChild(i)); + 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); @@ -544,14 +555,16 @@ Restart: norm2, dir2, 4.0, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); Base::Vector3d secondPos = midpos2 - midpos1; auto translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::SecondTranslationIndex))); + static_cast(ConstraintNodePosition::SecondTranslationIndex) + )); translation->abPos = SbVec3f(secondPos.x, secondPos.y, zConstrH); - translation->translation = - SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); + translation->translation + = SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); } } break; @@ -568,21 +581,20 @@ Restart: if (!geo1->is() || !geo2->is()) { 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). + double angle1, angle1plus = 0., angle2, + angle2plus = 0.; // angle1 = rotation of object as a + // whole; angle1plus = arc angle (t + // parameter for ellipses). if (geo1->is()) { - const Part::GeomCircle* circle = - static_cast(geo1); + const Part::GeomCircle* circle + = static_cast(geo1); r1a = circle->getRadius(); angle1 = pi / 4; midpos1 = circle->getCenter(); } else if (geo1->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo1); + const Part::GeomArcOfCircle* arc + = static_cast(geo1); r1a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); @@ -590,8 +602,8 @@ Restart: midpos1 = arc->getCenter(); } else if (geo1->is()) { - const Part::GeomEllipse* ellipse = - static_cast(geo1); + const Part::GeomEllipse* ellipse + = static_cast(geo1); r1a = ellipse->getMajorRadius(); r1b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); @@ -600,8 +612,8 @@ Restart: midpos1 = ellipse->getCenter(); } else if (geo1->is()) { - const Part::GeomArcOfEllipse* aoe = - static_cast(geo1); + const Part::GeomArcOfEllipse* aoe + = static_cast(geo1); r1a = aoe->getMajorRadius(); r1b = aoe->getMinorRadius(); double startangle, endangle; @@ -612,8 +624,8 @@ Restart: midpos1 = aoe->getCenter(); } else if (geo1->is()) { - const Part::GeomArcOfHyperbola* aoh = - static_cast(geo1); + const Part::GeomArcOfHyperbola* aoh + = static_cast(geo1); r1a = aoh->getMajorRadius(); r1b = aoh->getMinorRadius(); double startangle, endangle; @@ -624,8 +636,8 @@ Restart: midpos1 = aoh->getCenter(); } else if (geo1->is()) { - const Part::GeomArcOfParabola* aop = - static_cast(geo1); + const Part::GeomArcOfParabola* aop + = static_cast(geo1); r1a = aop->getFocal(); double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); @@ -639,15 +651,15 @@ Restart: } if (geo2->is()) { - const Part::GeomCircle* circle = - static_cast(geo2); + const Part::GeomCircle* circle + = static_cast(geo2); r2a = circle->getRadius(); angle2 = pi / 4; midpos2 = circle->getCenter(); } else if (geo2->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo2); + const Part::GeomArcOfCircle* arc + = static_cast(geo2); r2a = arc->getRadius(); double startangle, endangle; arc->getRange(startangle, endangle, /*emulateCCW=*/true); @@ -655,8 +667,8 @@ Restart: midpos2 = arc->getCenter(); } else if (geo2->is()) { - const Part::GeomEllipse* ellipse = - static_cast(geo2); + const Part::GeomEllipse* ellipse + = static_cast(geo2); r2a = ellipse->getMajorRadius(); r2b = ellipse->getMinorRadius(); Base::Vector3d majdir = ellipse->getMajorAxisDir(); @@ -665,8 +677,8 @@ Restart: midpos2 = ellipse->getCenter(); } else if (geo2->is()) { - const Part::GeomArcOfEllipse* aoe = - static_cast(geo2); + const Part::GeomArcOfEllipse* aoe + = static_cast(geo2); r2a = aoe->getMajorRadius(); r2b = aoe->getMinorRadius(); double startangle, endangle; @@ -677,8 +689,8 @@ Restart: midpos2 = aoe->getCenter(); } else if (geo2->is()) { - const Part::GeomArcOfHyperbola* aoh = - static_cast(geo2); + const Part::GeomArcOfHyperbola* aoh + = static_cast(geo2); r2a = aoh->getMajorRadius(); r2b = aoh->getMinorRadius(); double startangle, endangle; @@ -689,8 +701,8 @@ Restart: midpos2 = aoh->getCenter(); } else if (geo2->is()) { - const Part::GeomArcOfParabola* aop = - static_cast(geo2); + const Part::GeomArcOfParabola* aop + = static_cast(geo2); r2a = aop->getFocal(); double startangle, endangle; aop->getRange(startangle, endangle, /*emulateCCW=*/true); @@ -707,12 +719,16 @@ Restart: || geo1->is()) { 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 + 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; @@ -721,7 +737,8 @@ Restart: dir1 = Base::Vector3d( -rvec.y, rvec.x, - 0); // DeepSOIC: I'm not sure what dir is supposed to mean. + 0 + ); // DeepSOIC: I'm not sure what dir is supposed to mean. } else { norm1 = Base::Vector3d(cos(angle1), sin(angle1), 0); @@ -734,12 +751,16 @@ Restart: || geo2->is()) { 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 + 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; @@ -758,10 +779,10 @@ Restart: } } else { - 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); // calculate the half distance between the start and endpoint midpos1 = ((lineSeg1->getEndPoint() + lineSeg1->getStartPoint()) / 2); @@ -773,24 +794,26 @@ Restart: 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)); + 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))); + auto translation = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex)) + ); - translation->abPos = - SbVec3f(midpos1.x, midpos1.y, zConstrH); // Absolute Reference + 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); @@ -798,14 +821,14 @@ Restart: Base::Vector3d secondPos = midpos2 - midpos1; translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::SecondTranslationIndex))); + static_cast(ConstraintNodePosition::SecondTranslationIndex) + )); - translation->abPos = - SbVec3f(secondPos.x, secondPos.y, zConstrH); // Absolute Reference + 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->translation = SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); } break; case Distance: @@ -904,8 +927,9 @@ Restart: asciiText->datumtype = SoDatumLabel::ARCLENGTH; asciiText->param1 = Constr->LabelDistance; - asciiText->string = - SbString(getPresentationString(Constr, "◠ ").toUtf8().constData()); + asciiText->string = SbString( + getPresentationString(Constr, "◠ ").toUtf8().constData() + ); asciiText->pnts.setNum(3); SbVec3f* verts = asciiText->pnts.startEditing(); @@ -927,8 +951,7 @@ Restart: auto* asciiText = static_cast(sep->getChild(index)); // NOLINT // Get presentation string (w/o units if option is set) - asciiText->string = - SbString(getPresentationString(Constr).toUtf8().constData()); + asciiText->string = SbString(getPresentationString(Constr).toUtf8().constData()); if (Constr->Type == Distance) { asciiText->datumtype = SoDatumLabel::DISTANCE; @@ -950,17 +973,14 @@ Restart: radius1 = arc->getRadius(); center1 = arc->getCenter(); - double angle = - toVector2d(isLineSegment(*geo2) ? pnt2 - center1 : pnt1 - center1) - .Angle(); + double angle = toVector2d( + isLineSegment(*geo2) ? pnt2 - center1 : pnt1 - center1 + ) + .Angle(); double startAngle, endAngle; arc->getRange(startAngle, endAngle, /*emulateCCW=*/true); - findHelperAngles(helperStartAngle1, - helperRange1, - angle, - startAngle, - endAngle); + findHelperAngles(helperStartAngle1, helperRange1, angle, startAngle, endAngle); if (helperRange1 != 0.) { // We override to draw the full helper as it does not look good @@ -977,16 +997,11 @@ Restart: radius2 = arc->getRadius(); center2 = arc->getCenter(); - double angle = - toVector2d(pnt2 - center2).Angle(); // between -pi and pi - double startAngle, endAngle; // between 0 and 2*pi + double angle = toVector2d(pnt2 - center2).Angle(); // between -pi and pi + double startAngle, endAngle; // between 0 and 2*pi arc->getRange(startAngle, endAngle, /*emulateCCW=*/true); - findHelperAngles(helperStartAngle2, - helperRange2, - angle, - startAngle, - endAngle); + findHelperAngles(helperStartAngle2, helperRange2, angle, startAngle, endAngle); if (helperRange2 != 0.) { helperStartAngle2 = endAngle; @@ -1048,13 +1063,14 @@ Restart: assert(Constr->Second >= -extGeoCount && Constr->Second < intGeoCount); Base::Vector3d pos, relPos; - if (Constr->Type == PointOnObject || Constr->Type == SnellsLaw + 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 + && Constr->FirstPos != Sketcher::PointPos::none) // endpoint-to-curve or + // endpoint-to-endpoint + // tangency ) { // find the point of tangency/point that is on object @@ -1095,36 +1111,35 @@ Restart: norm, dir, 2.5, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); auto translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::FirstTranslationIndex))); + 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); + const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId(Constr->First); + const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId(Constr->Second); - if (geo1->is() - && geo2->is()) { - const Part::GeomLineSegment* lineSeg1 = - static_cast(geo1); - const Part::GeomLineSegment* lineSeg2 = - static_cast(geo2); + if (geo1->is() && geo2->is()) { + 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 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); @@ -1133,31 +1148,37 @@ Restart: norm1, dir1, 4.0, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); Base::Vector3d relpos2 = seekConstraintPosition( midpos2, norm2, dir2, 4.0, - editModeScenegraphNodes.constrGroup->getChild(i)); + editModeScenegraphNodes.constrGroup->getChild(i) + ); auto translation = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::FirstTranslationIndex))); + static_cast(ConstraintNodePosition::FirstTranslationIndex) + )); - translation->abPos = - SbVec3f(midpos1.x, midpos1.y, zConstrH); // Absolute Reference + 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))); + 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); + translation->abPos = SbVec3f( + secondPos.x, + secondPos.y, + zConstrH + ); // Absolute Reference + translation->translation + = SbVec3f(relpos2.x - relpos1.x, relpos2.y - relpos1.y, 0); break; } @@ -1166,17 +1187,16 @@ Restart: } if (geo1->is()) { - const Part::GeomLineSegment* lineSeg = - static_cast(geo1); - Base::Vector3d dir = - (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Normalize(); + 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->is()) { - const Part::GeomCircle* circle = - static_cast(geo2); + const Part::GeomCircle* circle + = static_cast(geo2); // tangency between a line and a circle - float length = - (circle->getCenter() - lineSeg->getStartPoint()) * dir; + float length = (circle->getCenter() - lineSeg->getStartPoint()) * dir; pos = lineSeg->getStartPoint() + dir * length; relPos = norm * 1; // TODO Huh? @@ -1186,13 +1206,13 @@ Restart: Base::Vector3d center; if (geo2->is()) { - const Part::GeomEllipse* ellipse = - static_cast(geo2); + const Part::GeomEllipse* ellipse + = static_cast(geo2); center = ellipse->getCenter(); } else { - const Part::GeomArcOfEllipse* aoc = - static_cast(geo2); + const Part::GeomArcOfEllipse* aoc + = static_cast(geo2); center = aoc->getCenter(); } @@ -1203,8 +1223,8 @@ Restart: relPos = norm * 1; } else if (geo2->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo2); + const Part::GeomArcOfCircle* arc + = static_cast(geo2); // tangency between a line and an arc float length = (arc->getCenter() - lineSeg->getStartPoint()) * dir; @@ -1214,13 +1234,15 @@ Restart: } if (geo1->is() && geo2->is()) { - const Part::GeomCircle* circle1 = - static_cast(geo1); - const Part::GeomCircle* circle2 = - static_cast(geo2); + const Part::GeomCircle* circle1 = static_cast( + geo1 + ); + const Part::GeomCircle* circle2 = static_cast( + geo2 + ); // tangency between two circles - Base::Vector3d dir = - (circle2->getCenter() - circle1->getCenter()).Normalize(); + Base::Vector3d dir + = (circle2->getCenter() - circle1->getCenter()).Normalize(); pos = circle1->getCenter() + dir * circle1->getRadius(); relPos = dir * 1; } @@ -1229,30 +1251,28 @@ Restart: } if (geo1->is() && geo2->is()) { - const Part::GeomCircle* circle = - static_cast(geo1); - const Part::GeomArcOfCircle* arc = - static_cast(geo2); + 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(); + Base::Vector3d dir = (arc->getCenter() - circle->getCenter()).Normalize(); pos = circle->getCenter() + dir * circle->getRadius(); relPos = dir * 1; } else if (geo1->is() && geo2->is()) { - const Part::GeomArcOfCircle* arc1 = - static_cast(geo1); - const Part::GeomArcOfCircle* arc2 = - static_cast(geo2); + 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(); + 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))); + static_cast(ConstraintNodePosition::FirstTranslationIndex) + )); translation->abPos = SbVec3f(pos.x, pos.y, zConstrH); // Absolute Reference translation->translation = SbVec3f(relPos.x, relPos.y, 0); @@ -1272,7 +1292,8 @@ Restart: SbVec3f norm(-dir[1], dir[0], 0); SoDatumLabel* asciiText = static_cast( - sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex)) + ); asciiText->datumtype = SoDatumLabel::SYMMETRIC; asciiText->pnts.setNum(2); @@ -1283,15 +1304,18 @@ Restart: 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); + assert( + (Constr->Second >= -extGeoCount && Constr->Second < intGeoCount) + || Constr->Second == GeoEnum::GeoUndef + ); SbVec3f p0; double distance = Constr->LabelDistance; @@ -1301,10 +1325,12 @@ Restart: 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); + const Part::Geometry* geo1 = geolistfacade.getGeometryFromGeoId( + Constr->First + ); + const Part::Geometry* geo2 = geolistfacade.getGeometryFromGeoId( + Constr->Second + ); if (!isLineSegment(*geo1) || !isLineSegment(*geo2)) { break; } @@ -1317,14 +1343,14 @@ Restart: * (line1->getEndPoint() - line1->getStartPoint()).Normalize(); dir2 = (flip2 ? -1. : 1.) * (line2->getEndPoint() - line2->getStartPoint()).Normalize(); - Base::Vector3d pnt1 = - flip1 ? line1->getEndPoint() : line1->getStartPoint(); - Base::Vector3d pnt2 = - flip2 ? line2->getEndPoint() : line2->getStartPoint(); - Base::Vector3d pnt12 = - flip1 ? line1->getStartPoint() : line1->getEndPoint(); - Base::Vector3d pnt22 = - flip2 ? line2->getStartPoint() : line2->getEndPoint(); + Base::Vector3d pnt1 = flip1 ? line1->getEndPoint() + : line1->getStartPoint(); + Base::Vector3d pnt2 = flip2 ? line2->getEndPoint() + : line2->getStartPoint(); + Base::Vector3d pnt12 = flip1 ? line1->getStartPoint() + : line1->getEndPoint(); + Base::Vector3d pnt22 = flip2 ? line2->getStartPoint() + : line2->getEndPoint(); // line-line intersection Base::Vector3d intersection; @@ -1377,8 +1403,7 @@ Restart: : 0.0; } else { // angle-via-point - Base::Vector3d p = - geolistfacade.getPoint(Constr->Third, Constr->ThirdPos); + Base::Vector3d p = geolistfacade.getPoint(Constr->Third, Constr->ThirdPos); p0 = SbVec3f(p.x, p.y, 0); dir1 = getNormal(geolistfacade, Constr->First, p); // TODO: Check @@ -1392,17 +1417,19 @@ Restart: dir2.RotateZ(-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); + range = atan2( + dir1.x * dir2.y - dir1.y * dir2.x, + dir1.x * dir2.x + dir1.y * dir2.y + ); } } else if (Constr->First != GeoEnum::GeoUndef) { - const Part::Geometry* geo = - geolistfacade.getGeometryFromGeoId(Constr->First); + const Part::Geometry* geo = geolistfacade.getGeometryFromGeoId(Constr->First); if (geo->is()) { auto* lineSeg = static_cast(geo); p0 = Base::convertTo( - (lineSeg->getEndPoint() + lineSeg->getStartPoint()) / 2); + (lineSeg->getEndPoint() + lineSeg->getStartPoint()) / 2 + ); double l1 = 2 * distance - (lineSeg->getEndPoint() - lineSeg->getStartPoint()).Length() / 2; endLineLength1 = 2 * distance; @@ -1432,9 +1459,9 @@ Restart: } SoDatumLabel* asciiText = static_cast( - sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); - asciiText->string = - SbString(getPresentationString(Constr).toUtf8().constData()); + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex)) + ); + asciiText->string = SbString(getPresentationString(Constr).toUtf8().constData()); asciiText->datumtype = SoDatumLabel::ANGLE; asciiText->param1 = distance; asciiText->param2 = startangle; @@ -1476,17 +1503,9 @@ Restart: angle = (startAngle + endAngle) / 2; } - findHelperAngles(startHelperAngle, - startHelperRange, - angle, - startAngle, - endAngle); + findHelperAngles(startHelperAngle, startHelperRange, angle, startAngle, endAngle); - findHelperAngles(endHelperAngle, - endHelperRange, - angle + pi, - startAngle, - endAngle); + findHelperAngles(endHelperAngle, endHelperRange, angle + pi, startAngle, endAngle); Base::Vector3d center = arc->getCenter(); pnt1 = center - radius * Base::Vector3d(cos(angle), sin(angle), 0.); @@ -1511,11 +1530,13 @@ Restart: SbVec3f p2(pnt2.x, pnt2.y, zConstrH); SoDatumLabel* asciiText = static_cast( - sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex)) + ); // Get display string with units hidden if so requested - asciiText->string = - SbString(getPresentationString(Constr, "⌀").toUtf8().constData()); + asciiText->string = SbString( + getPresentationString(Constr, "⌀").toUtf8().constData() + ); asciiText->datumtype = SoDatumLabel::DIAMETER; asciiText->param1 = Constr->LabelDistance; @@ -1557,11 +1578,7 @@ Restart: angle = (startAngle + endAngle) / 2; } - findHelperAngles(helperStartAngle, - helperRange, - angle, - startAngle, - endAngle); + findHelperAngles(helperStartAngle, helperRange, angle, startAngle, endAngle); pnt1 = arc->getCenter(); pnt2 = pnt1 + radius * Base::Vector3d(cos(angle), sin(angle), 0.); @@ -1589,16 +1606,19 @@ Restart: SbVec3f p2(pnt2.x, pnt2.y, zConstrH); SoDatumLabel* asciiText = static_cast( - sep->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + 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()); + asciiText->string = SbString( + QString::number(Constr->getValue()).toStdString().c_str() + ); } else { - asciiText->string = - SbString(getPresentationString(Constr, "R").toUtf8().constData()); + asciiText->string = SbString( + getPresentationString(Constr, "R").toUtf8().constData() + ); } asciiText->datumtype = SoDatumLabel::RADIUS; @@ -1623,23 +1643,29 @@ Restart: } } catch (Base::Exception& e) { - Base::Console().developerError("EditModeConstraintCoinManager", - "Exception during draw: %s\n", - e.what()); + Base::Console().developerError( + "EditModeConstraintCoinManager", + "Exception during draw: %s\n", + e.what() + ); e.reportException(); } catch (...) { - Base::Console().developerError("EditModeConstraintCoinManager", - "Exception during draw: unknown\n"); + Base::Console().developerError( + "EditModeConstraintCoinManager", + "Exception during draw: unknown\n" + ); } } } -void EditModeConstraintCoinManager::findHelperAngles(double& helperStartAngle, - double& helperRange, - double angle, - double startAngle, - double endAngle) +void EditModeConstraintCoinManager::findHelperAngles( + double& helperStartAngle, + double& helperRange, + double angle, + double startAngle, + double endAngle +) { using std::numbers::pi; @@ -1670,11 +1696,13 @@ void EditModeConstraintCoinManager::findHelperAngles(double& helperStartAngle, } } -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); @@ -1732,7 +1760,8 @@ Base::Vector3d EditModeConstraintCoinManager::seekConstraintPosition(const Base: } void EditModeConstraintCoinManager::updateConstraintColor( - const std::vector& constraints) + const std::vector& constraints +) { // Because coincident constraints are selected using the point color, we need to edit the point // materials. @@ -1748,20 +1777,21 @@ void EditModeConstraintCoinManager::updateConstraintColor( CurvNum.emplace_back(); color.emplace_back(); for (int t = 0; t < geometryLayerParameters.getSubLayerCount(); t++) { - CurvNum[l].push_back( - editModeScenegraphNodes.CurvesMaterials[l][t]->diffuseColor.getNum()); + CurvNum[l].push_back(editModeScenegraphNodes.CurvesMaterials[l][t]->diffuseColor.getNum()); color[l].push_back( - editModeScenegraphNodes.CurvesMaterials[l][t]->diffuseColor.startEditing()); + editModeScenegraphNodes.CurvesMaterials[l][t]->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]; @@ -1774,10 +1804,10 @@ void EditModeConstraintCoinManager::updateConstraintColor( 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; @@ -1798,8 +1828,7 @@ void EditModeConstraintCoinManager::updateConstraintColor( 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; } } @@ -1827,7 +1856,8 @@ void EditModeConstraintCoinManager::updateConstraintColor( if (ViewProviderSketchCoinAttorney::isConstraintSelected(viewProvider, i)) { if (hasDatumLabel) { SoDatumLabel* l = static_cast( - s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex)) + ); l->textColor = drawingParameters.SelectColor; } else if (hasMaterial) { @@ -1862,7 +1892,8 @@ void EditModeConstraintCoinManager::updateConstraintColor( else if (ViewProviderSketchCoinAttorney::isConstraintPreselected(viewProvider, i)) { if (hasDatumLabel) { SoDatumLabel* l = static_cast( - s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex)) + ); l->textColor = drawingParameters.PreselectColor; } else if (hasMaterial) { @@ -1872,7 +1903,8 @@ void EditModeConstraintCoinManager::updateConstraintColor( else { if (hasDatumLabel) { SoDatumLabel* l = static_cast( - s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex))); + s->getChild(static_cast(ConstraintNodePosition::DatumLabelIndex)) + ); l->textColor = constraint->isActive ? ViewProviderSketchCoinAttorney::constraintHasExpression(viewProvider, i) @@ -1917,8 +1949,8 @@ void EditModeConstraintCoinManager::setConstraintSelectability(bool enabled /* = 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); @@ -1942,7 +1974,8 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes(const GeoListFacade& void EditModeConstraintCoinManager::rebuildConstraintNodes( const GeoListFacade& geolistfacade, const std::vector constrlist, - SbVec3f norm) + SbVec3f norm +) { for (std::vector::const_iterator it = constrlist.begin(); @@ -2053,10 +2086,10 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes( if (!geo1 || !geo2) { Base::Console().developerWarning( "EditModeConstraintCoinManager", - "Tangent constraint references non-existing geometry\n"); + "Tangent constraint references non-existing geometry\n" + ); } - else if (geo1->is() - && geo2->is()) { + else if (geo1->is() && geo2->is()) { // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_TRANSLATION 4 sep->addChild(new SoZoomTranslation()); // #define CONSTRAINT_SEPARATOR_INDEX_SECOND_ICON 5 @@ -2100,8 +2133,10 @@ void EditModeConstraintCoinManager::rebuildConstraintNodes( } } -QString EditModeConstraintCoinManager::getPresentationString(const Constraint* constraint, - std::string prefix) +QString EditModeConstraintCoinManager::getPresentationString( + const Constraint* constraint, + std::string prefix +) { /** * Hide units if @@ -2168,8 +2203,7 @@ QString EditModeConstraintCoinManager::getPresentationString(const Constraint* c auto it = std::find(constrlist.begin(), constrlist.end(), constraint); if (it != constrlist.end()) { constraintIndex = std::distance(constrlist.begin(), it); - if (ViewProviderSketchCoinAttorney::constraintHasExpression(viewProvider, - constraintIndex)) { + if (ViewProviderSketchCoinAttorney::constraintHasExpression(viewProvider, constraintIndex)) { fixedValueStr += QStringLiteral(" (ƒ𝑥)"); } } @@ -2212,8 +2246,9 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi continue; } - QString constrIdsStr = - QString::fromLatin1(constrIdsNode->string.getValue().getString()); + QString constrIdsStr = QString::fromLatin1( + constrIdsNode->string.getValue().getString() + ); if (combinedConstrBoxes.count(constrIdsStr)) { @@ -2224,7 +2259,8 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi // SoZoomTranslation node. SoZoomTranslation* translation = nullptr; SoNode* firstTransNode = sep->getChild( - static_cast(ConstraintNodePosition::FirstTranslationIndex)); + static_cast(ConstraintNodePosition::FirstTranslationIndex) + ); if (dynamic_cast(firstTransNode)) { translation = static_cast(firstTransNode); } @@ -2242,7 +2278,8 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi SoNode* secondIconNode = sep->getChild(secondIndex); if (tail == secondIconNode) { auto translation2 = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::SecondTranslationIndex))); + static_cast(ConstraintNodePosition::SecondTranslationIndex) + )); absPos += translation2->abPos.getValue(); trans += translation2->translation.getValue(); scaleFactor = translation2->getScaleFactor(); @@ -2255,24 +2292,27 @@ std::set EditModeConstraintCoinManager::detectPreselectionConstr(const SoPi // 4. Project both the icon's center and the picked point to screen coordinates // (device independent pixels). This is the key: both points are now in the same // coordinate system. - SbVec2f iconGroupScreenCenter = - ViewProviderSketchCoinAttorney::getScreenCoordinates( - viewProvider, - SbVec2f(iconGroupWorldPos[0], iconGroupWorldPos[1])); + SbVec2f iconGroupScreenCenter = ViewProviderSketchCoinAttorney::getScreenCoordinates( + viewProvider, + SbVec2f(iconGroupWorldPos[0], iconGroupWorldPos[1]) + ); SbVec2f cursorScreenPos = ViewProviderSketchCoinAttorney::getScreenCoordinates( viewProvider, - SbVec2f(Point->getPoint()[0], Point->getPoint()[1])); + SbVec2f(Point->getPoint()[0], Point->getPoint()[1]) + ); // 5. Calculate cursor position relative to the icon group's top-left corner. // - QRect/QImage assumes a top-left origin (Y increases downwards). // - Coin3D screen coordinates have a bottom-left origin (Y increases // upwards). // - We must flip the Y-axis for the check. - int relativeX = static_cast(cursorScreenPos[0] - iconGroupScreenCenter[0] - + iconGroupSize[0] / 2.0f); - int relativeY = static_cast(iconGroupScreenCenter[1] - cursorScreenPos[1] - + iconGroupSize[1] / 2.0f); + int relativeX = static_cast( + cursorScreenPos[0] - iconGroupScreenCenter[0] + iconGroupSize[0] / 2.0f + ); + int relativeY = static_cast( + iconGroupScreenCenter[1] - cursorScreenPos[1] + iconGroupSize[1] / 2.0f + ); // 6. Perform the hit test on each icon in the group. for (const auto& boxInfo : combinedConstrBoxes[constrIdsStr]) { @@ -2330,13 +2370,15 @@ void EditModeConstraintCoinManager::drawConstraintIcons() 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]; @@ -2392,20 +2434,23 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade& geo if (constrId >= editModeScenegraphNodes.constrGroup->getNumChildren()) { Base::Console().developerWarning( "EditModeConstraintManager", - "Can't update constraint icons because view is not in sync with sketch\n"); + "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))); + sep->getChild(static_cast(ConstraintNodePosition::FirstTranslationIndex)) + ); if (dynamic_cast(translationPtr)) { absPos = static_cast(translationPtr)->abPos.getValue(); @@ -2415,9 +2460,11 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade& geo } SoImage* coinIconPtr = dynamic_cast( - sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex))); + sep->getChild(static_cast(ConstraintNodePosition::FirstIconIndex)) + ); SoInfo* infoPtr = static_cast( - sep->getChild(static_cast(ConstraintNodePosition::FirstConstraintIdIndex))); + sep->getChild(static_cast(ConstraintNodePosition::FirstConstraintIdIndex)) + ); constrIconQueueItem thisIcon; thisIcon.type = icoType; @@ -2430,16 +2477,15 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade& geo && constraint->isVisible; if (constraint->Type == Symmetric) { - Base::Vector3d startingpoint = - geolistfacade.getPoint(constraint->First, constraint->FirstPos); - Base::Vector3d endpoint = - geolistfacade.getPoint(constraint->Second, constraint->SecondPos); + 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); - thisIcon.iconRotation = - ViewProviderSketchCoinAttorney::getRotation(viewProvider, pos0, pos1); + thisIcon.iconRotation + = ViewProviderSketchCoinAttorney::getRotation(viewProvider, pos0, pos1); } else { thisIcon.iconRotation = 0; @@ -2459,20 +2505,23 @@ void EditModeConstraintCoinManager::drawConstraintIcons(const GeoListFacade& geo // // See note ~30 lines up. if (numChildren > static_cast(ConstraintNodePosition::SecondConstraintIdIndex)) { - translationPtr = static_cast(sep->getChild( - static_cast(ConstraintNodePosition::SecondTranslationIndex))); + translationPtr = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::SecondTranslationIndex)) + ); if (dynamic_cast(translationPtr)) { - thisIcon.position += - static_cast(translationPtr)->abPos.getValue(); + 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))); + sep->getChild(static_cast(ConstraintNodePosition::SecondIconIndex)) + ); + thisIcon.infoPtr = static_cast( + sep->getChild(static_cast(ConstraintNodePosition::SecondConstraintIdIndex)) + ); } } else { @@ -2632,23 +2681,27 @@ void EditModeConstraintCoinManager::drawMergedConstraintIcons(IconQueue iconQueu // Render the icon here. if (compositeIcon.isNull()) { - compositeIcon = renderConstrIcon(thisType, - iconColor, - labels, - labelColors, - iconRotation, - &boundingBoxesVec, - &lastVPad); + compositeIcon = renderConstrIcon( + thisType, + iconColor, + labels, + labelColors, + iconRotation, + &boundingBoxesVec, + &lastVPad + ); } else { int thisVPad; - QImage partialIcon = renderConstrIcon(thisType, - iconColor, - labels, - labelColors, - iconRotation, - &boundingBoxesVec, - &thisVPad); + QImage partialIcon = renderConstrIcon( + thisType, + iconColor, + labels, + labelColors, + iconRotation, + &boundingBoxesVec, + &thisVPad + ); // Stack vertically for now. Down the road, it might make sense // to figure out the best orientation automatically. @@ -2660,10 +2713,12 @@ 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); @@ -2674,8 +2729,7 @@ 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(); + for (std::vector::iterator bb = boundingBoxesVec.begin(); bb != boundingBoxesVec.end(); ++bb) { nextIds.clear(); @@ -2704,13 +2758,15 @@ 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 = QStringLiteral(", "); @@ -2722,9 +2778,12 @@ QImage EditModeConstraintCoinManager::renderConstrIcon(const QString& type, 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 + QSizeF(drawingParameters.constraintIconSize, drawingParameters.constraintIconSize) + ); + Gui::BitmapFactory().addPixmapToCache( + constraintName.str().c_str(), + pxMap + ); // Cache for speed, avoiding pixmapFromSvg } QImage icon = pxMap.toImage(); // The pixmap was already scaled so we don't need to scale the image @@ -2792,8 +2851,7 @@ QImage EditModeConstraintCoinManager::renderConstrIcon(const QString& type, if (boundingBoxes) { labelBB = qfm.boundingRect(labelStr); - labelBB.moveTo(icon.width() + cursorOffset, - icon.height() - qfm.height() + pxBelowBase); + labelBB.moveTo(icon.width() + cursorOffset, icon.height() - qfm.height() + pxBelowBase); boundingBoxes->push_back(labelBB); } @@ -2808,11 +2866,8 @@ void EditModeConstraintCoinManager::drawTypicalConstraintIcon(const constrIconQu { 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); @@ -2852,8 +2907,7 @@ QString EditModeConstraintCoinManager::iconTypeFromConstraint(Constraint* constr } } -void EditModeConstraintCoinManager::sendConstraintIconToCoin(const QImage& icon, - SoImage* soImagePtr) +void EditModeConstraintCoinManager::sendConstraintIconToCoin(const QImage& icon, SoImage* soImagePtr) { SoSFImage icondata = SoSFImage(); @@ -2877,9 +2931,7 @@ 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); @@ -2930,13 +2982,12 @@ void EditModeConstraintCoinManager::createEditModeInventorNodes() // 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; diff --git a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h index 789191aed0..aa9eb023a5 100644 --- a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.h @@ -94,12 +94,14 @@ private: }; 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(); @@ -140,16 +142,20 @@ public: private: 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. @@ -231,18 +237,20 @@ private: 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, - //! Gets populated with bounding boxes (in icon - //! image coordinates) for the icon at left, then - //! labels for different constraints. - 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); + 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, + //! If not NULL, gets set to the number of pixels + //! that the text extends below the icon base. + int* vPad = nullptr + ); /// Copies a QImage constraint icon into a SoImage* /*! Used by drawTypicalConstraintIcon() and drawMergedConstraintIcons() */ @@ -252,11 +260,13 @@ private: void clearCoinImage(SoImage* soImagePtr); /// Find helper angle for radius/diameter constraint - void findHelperAngles(double& helperStartAngle, - double& helperRange, - double angle, - double startAngle, - double endAngle); + void findHelperAngles( + double& helperStartAngle, + double& helperRange, + double angle, + double startAngle, + double endAngle + ); //@} private: diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp index 1eeff36fe7..8d33ac0fee 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.cpp @@ -39,7 +39,8 @@ EditModeGeometryCoinConverter::EditModeGeometryCoinConverter( GeometryLayerNodes& geometrylayernodes, DrawingParameters& drawingparameters, GeometryLayerParameters& geometryLayerParams, - CoinMapping& coinMap) + CoinMapping& coinMap +) : viewProvider(vp) , geometryLayerNodes(geometrylayernodes) , drawingParameters(drawingparameters) @@ -81,11 +82,13 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli pointCounter.resize(geometryLayerParameters.getCoinLayerCount(), 0); - auto setTracking = [this](int geoId, - int coinLayer, - EditModeGeometryCoinConverter::PointsMode pointmode, - int numberCurves, - int sublayer) { + auto setTracking = [this]( + int geoId, + int coinLayer, + EditModeGeometryCoinConverter::PointsMode pointmode, + int numberCurves, + int sublayer + ) { int numberPoints = 0; if (pointmode == PointsMode::InsertSingle) { @@ -94,7 +97,8 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::start), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); } else if (pointmode == PointsMode::InsertStartEnd) { numberPoints = 2; @@ -102,12 +106,14 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::start), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::end), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); } else if (pointmode == PointsMode::InsertMidOnly) { numberPoints = 1; @@ -115,7 +121,8 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::mid), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); } else if (pointmode == PointsMode::InsertStartEndMid) { numberPoints = 3; @@ -123,17 +130,20 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::start), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::end), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); coinMapping.GeoElementId2SetId.emplace( std::piecewise_construct, std::forward_as_tuple(geoId, Sketcher::PointPos::mid), - std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer)); + std::forward_as_tuple(pointCounter[coinLayer]++, coinLayer) + ); } for (int i = 0; i < numberPoints; i++) { @@ -165,7 +175,9 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli std::forward_as_tuple( static_cast(coinMapping.CurvIdToGeoId[coinLayer][sublayer].size()), coinLayer, - sublayer)); + sublayer + ) + ); } for (int i = 0; i < numberCurves; i++) { @@ -185,72 +197,80 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli auto coinLayer = geometryLayerParameters.getSafeCoinLayer(layerId); if (type == Part::GeomPoint::getClassTypeId()) { // add a point - convert(geom, - GeoId, - subLayerId); - setTracking(GeoId, - coinLayer, - EditModeGeometryCoinConverter::PointsMode::InsertSingle, - 0, - subLayerId); + convert< + Part::GeomPoint, + EditModeGeometryCoinConverter::PointsMode::InsertSingle, + EditModeGeometryCoinConverter::CurveMode::NoCurve, + EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitude>(geom, GeoId, subLayerId); + setTracking( + GeoId, + coinLayer, + EditModeGeometryCoinConverter::PointsMode::InsertSingle, + 0, + subLayerId + ); } else if (type == Part::GeomLineSegment::getClassTypeId()) { // add a line - convert(geom, - GeoId, - subLayerId); - setTracking(GeoId, - coinLayer, - EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, - 1, - subLayerId); + convert< + Part::GeomLineSegment, + EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, + EditModeGeometryCoinConverter::CurveMode::StartEndPointsOnly, + EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitude>(geom, GeoId, subLayerId); + setTracking( + GeoId, + coinLayer, + EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, + 1, + subLayerId + ); } - else if (type.isDerivedFrom( - Part::GeomConic::getClassTypeId())) { // add a closed curve conic - convert(geom, - GeoId, - subLayerId); - setTracking(GeoId, - coinLayer, - EditModeGeometryCoinConverter::PointsMode::InsertMidOnly, - 1, - subLayerId); + 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, subLayerId); + setTracking( + GeoId, + coinLayer, + EditModeGeometryCoinConverter::PointsMode::InsertMidOnly, + 1, + subLayerId + ); } - else if (type.isDerivedFrom( - Part::GeomArcOfConic::getClassTypeId())) { // add an arc of conic - convert(geom, - GeoId, - subLayerId); - setTracking(GeoId, - coinLayer, - EditModeGeometryCoinConverter::PointsMode::InsertStartEndMid, - 1, - subLayerId); + 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, subLayerId); + setTracking( + GeoId, + coinLayer, + EditModeGeometryCoinConverter::PointsMode::InsertStartEndMid, + 1, + subLayerId + ); arcGeoIds.push_back(GeoId); } else if (type == Part::GeomBSplineCurve::getClassTypeId()) { // add a bspline (a bounded // curve that is not a conic) - convert(geom, GeoId, subLayerId); - setTracking(GeoId, - coinLayer, - EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, - 1, - subLayerId); + convert< + Part::GeomBSplineCurve, + EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, + EditModeGeometryCoinConverter::CurveMode::OpenCurve, + EditModeGeometryCoinConverter::AnalyseMode::BoundingBoxMagnitudeAndBSplineCurvature>( + geom, + GeoId, + subLayerId + ); + setTracking( + GeoId, + coinLayer, + EditModeGeometryCoinConverter::PointsMode::InsertStartEnd, + 1, + subLayerId + ); bsplineGeoIds.push_back(GeoId); } } @@ -295,13 +315,16 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeoListFacade& geoli } } -template -void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade* geometryfacade, - [[maybe_unused]] int geoid, - [[maybe_unused]] int subLayer) +template< + typename GeoType, + EditModeGeometryCoinConverter::PointsMode pointmode, + EditModeGeometryCoinConverter::CurveMode curvemode, + EditModeGeometryCoinConverter::AnalyseMode analysemode> +void EditModeGeometryCoinConverter::convert( + const Sketcher::GeometryFacade* geometryfacade, + [[maybe_unused]] int geoid, + [[maybe_unused]] int subLayer +) { auto geo = static_cast(geometryfacade->getGeometry()); auto layerId = getSafeGeomLayerId(geometryfacade); @@ -385,8 +408,7 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade* geom 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); } @@ -421,7 +443,8 @@ void EditModeGeometryCoinConverter::convert(const Sketcher::GeometryFacade* geom Base::Console().developerError( "EditModeGeometryCoinConverter", "Curvature graph for B-spline with GeoId=%d could not be calculated.\n", - geoid); // TODO: Fix identification of curve. + geoid + ); // TODO: Fix identification of curve. curvaturelist[i] = 0; } diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h index afbf6e4310..b4136848b8 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinConverter.h @@ -109,11 +109,13 @@ 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. @@ -152,9 +154,11 @@ public: private: template - void convert(const Sketcher::GeometryFacade* geometryfacade, - [[maybe_unused]] int geoId, - [[maybe_unused]] int subLayerId = 0); + void convert( + const Sketcher::GeometryFacade* geometryfacade, + [[maybe_unused]] int geoId, + [[maybe_unused]] int subLayerId = 0 + ); private: /// Reference to ViewProviderSketch in order to access the public and the Attorney Interface @@ -180,8 +184,8 @@ private: // 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; }; diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp index 93e157d331..bc5932f946 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.cpp @@ -57,7 +57,8 @@ EditModeGeometryCoinManager::EditModeGeometryCoinManager( GeometryLayerParameters& geometryLayerParams, AnalysisResults& analysisResultStruct, EditModeScenegraphNodes& editModeScenegraph, - CoinMapping& coinMap) + CoinMapping& coinMap +) : viewProvider(vp) , drawingParameters(drawingParams) , geometryLayerParameters(geometryLayerParams) @@ -74,7 +75,8 @@ void EditModeGeometryCoinManager::processGeometry(const GeoListFacade& geolistfa // enable all layers editModeScenegraphNodes.PointsGroup->enable.setNum(geometryLayerParameters.getCoinLayerCount()); editModeScenegraphNodes.CurvesGroup->enable.setNum( - geometryLayerParameters.getCoinLayerCount() * geometryLayerParameters.getSubLayerCount()); + geometryLayerParameters.getCoinLayerCount() * geometryLayerParameters.getSubLayerCount() + ); SbBool* swsp = editModeScenegraphNodes.PointsGroup->enable.startEditing(); SbBool* swsc = editModeScenegraphNodes.CurvesGroup->enable.startEditing(); @@ -94,18 +96,22 @@ void EditModeGeometryCoinManager::processGeometry(const GeoListFacade& geolistfa 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); @@ -114,21 +120,24 @@ void EditModeGeometryCoinManager::processGeometry(const GeoListFacade& geolistfa 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 isDefinedGeomPoint = [&geolistfacade](int GeoId, Sketcher::PointPos PosId) { auto geom = geolistfacade.getGeometryFacadeFromGeoId(GeoId); if (geom) { - bool isStartOrEnd = - PosId == Sketcher::PointPos::start || PosId == Sketcher::PointPos::end; + bool isStartOrEnd = PosId == Sketcher::PointPos::start + || PosId == Sketcher::PointPos::end; return isStartOrEnd && !geom->getConstruction(); } return false; @@ -145,8 +154,8 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli }; auto isCoincident = [&](int GeoId, Sketcher::PointPos PosId) { - const std::vector& constraints = - ViewProviderSketchCoinAttorney::getConstraints(viewProvider); + const std::vector& constraints + = ViewProviderSketchCoinAttorney::getConstraints(viewProvider); for (auto& constr : constraints) { if (constr->Type == Coincident || (constr->Type == Tangent && constr->FirstPos != Sketcher::PointPos::none) @@ -176,37 +185,37 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli 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; }; - bool sketchFullyConstrained = - ViewProviderSketchCoinAttorney::isSketchFullyConstrained(viewProvider); + bool sketchFullyConstrained = ViewProviderSketchCoinAttorney::isSketchFullyConstrained( + viewProvider + ); // Update Colors SbColor* crosscolor = editModeScenegraphNodes.RootCrossMaterials->diffuseColor.startEditing(); - auto viewOrientationFactor = - ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider); + auto viewOrientationFactor = ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider); // Origin point auto preselectcross = ViewProviderSketchCoinAttorney::getPreselectCross(viewProvider); if (preselectcross == 0) { // 0 means the RootPoint is preselected - editModeScenegraphNodes.OriginPointMaterial->diffuseColor = - drawingParameters.PreselectColor; + editModeScenegraphNodes.OriginPointMaterial->diffuseColor = drawingParameters.PreselectColor; } else { - editModeScenegraphNodes.OriginPointMaterial->diffuseColor = - drawingParameters.FullyConstraintElementColor; + editModeScenegraphNodes.OriginPointMaterial->diffuseColor + = drawingParameters.FullyConstraintElementColor; } editModeScenegraphNodes.OriginPointCoordinate->point.set1Value( 0, - SbVec3f(0, 0, viewOrientationFactor * drawingParameters.zRootPoint)); + SbVec3f(0, 0, viewOrientationFactor * drawingParameters.zRootPoint) + ); for (auto l = 0; l < geometryLayerParameters.getCoinLayerCount(); l++) { float x, y, z; @@ -290,10 +299,12 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli // update rendering height of points - auto getRenderHeight = [this](DrawingParameters::GeometryRendering renderingtype, - float toprendering, - float midrendering, - float lowrendering) { + auto getRenderHeight = [this]( + DrawingParameters::GeometryRendering renderingtype, + float toprendering, + float midrendering, + float lowrendering + ) { if (drawingParameters.topRenderingGeometry == renderingtype) { return toprendering; } @@ -305,15 +316,19 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli } }; - float zNormPoint = getRenderHeight(DrawingParameters::GeometryRendering::NormalGeometry, - drawingParameters.zHighPoints, - drawingParameters.zMidPoints, - drawingParameters.zMidPoints); + float zNormPoint = getRenderHeight( + DrawingParameters::GeometryRendering::NormalGeometry, + drawingParameters.zHighPoints, + drawingParameters.zMidPoints, + drawingParameters.zMidPoints + ); - float zConstrPoint = getRenderHeight(DrawingParameters::GeometryRendering::Construction, - drawingParameters.zHighPoints, - drawingParameters.zMidPoints, - drawingParameters.zMidPoints); + float zConstrPoint = getRenderHeight( + DrawingParameters::GeometryRendering::Construction, + drawingParameters.zHighPoints, + drawingParameters.zMidPoints, + drawingParameters.zMidPoints + ); for (int i = 0; i < PtNum; i++) { if (!coinMapping.isValidPointId(i, l)) { @@ -357,8 +372,7 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli MultiFieldId preselectpointmfid; if (preselectcross == 0) { - editModeScenegraphNodes.OriginPointMaterial->diffuseColor = - drawingParameters.PreselectColor; + editModeScenegraphNodes.OriginPointMaterial->diffuseColor = drawingParameters.PreselectColor; } else if (preselectpoint != -1) { preselectpointmfid = coinMapping.getIndexLayer(preselectpoint); @@ -367,8 +381,10 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli pcolor[preselectpointmfid.fieldIndex] = drawingParameters.PreselectColor; - raisePoint(pverts[preselectpointmfid.fieldIndex], - viewOrientationFactor * drawingParameters.zHighlight); + raisePoint( + pverts[preselectpointmfid.fieldIndex], + viewOrientationFactor * drawingParameters.zHighlight + ); } } @@ -387,8 +403,8 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli auto pointindex = coinMapping.getIndexLayer(i); if (pointindex.fieldIndex == -1) { // It's the origin - editModeScenegraphNodes.OriginPointMaterial->diffuseColor = - drawingParameters.SelectColor; + editModeScenegraphNodes.OriginPointMaterial->diffuseColor + = drawingParameters.SelectColor; return; } @@ -398,32 +414,40 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli ? drawingParameters.PreselectSelectedColor : drawingParameters.SelectColor; - raisePoint(pverts[pointindex.fieldIndex], - viewOrientationFactor * drawingParameters.zHighlight); + raisePoint( + pverts[pointindex.fieldIndex], + viewOrientationFactor * drawingParameters.zHighlight + ); } - }); + } + ); // update colors and rendering height of the curves - float zNormLine = getRenderHeight(DrawingParameters::GeometryRendering::NormalGeometry, - drawingParameters.zHighLines, - drawingParameters.zMidLines, - drawingParameters.zLowLines); + float zNormLine = getRenderHeight( + DrawingParameters::GeometryRendering::NormalGeometry, + drawingParameters.zHighLines, + drawingParameters.zMidLines, + drawingParameters.zLowLines + ); - float zConstrLine = getRenderHeight(DrawingParameters::GeometryRendering::Construction, - drawingParameters.zHighLines, - drawingParameters.zMidLines, - drawingParameters.zLowLines); + float zConstrLine = getRenderHeight( + DrawingParameters::GeometryRendering::Construction, + drawingParameters.zHighLines, + drawingParameters.zMidLines, + drawingParameters.zLowLines + ); - float zExtLine = getRenderHeight(DrawingParameters::GeometryRendering::ExternalGeometry, - drawingParameters.zHighLines, - drawingParameters.zMidLines, - drawingParameters.zLowLines); + float zExtLine = getRenderHeight( + DrawingParameters::GeometryRendering::ExternalGeometry, + drawingParameters.zHighLines, + drawingParameters.zMidLines, + drawingParameters.zLowLines + ); for (auto t = 0; t < geometryLayerParameters.getSubLayerCount(); t++) { int CurvNum = editModeScenegraphNodes.CurvesMaterials[l][t]->diffuseColor.getNum(); - SbColor* color = - editModeScenegraphNodes.CurvesMaterials[l][t]->diffuseColor.startEditing(); + SbColor* color = editModeScenegraphNodes.CurvesMaterials[l][t]->diffuseColor.startEditing(); SbVec3f* verts = editModeScenegraphNodes.CurvesCoordinate[l][t]->point.startEditing(); int j = 0; // vertexindex @@ -437,8 +461,7 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli // edit->CurveSet->numVertices => [i] indicates number of vertex for line i. int indexes = (editModeScenegraphNodes.CurveSet[l][t]->numVertices[i]); - bool selected = - ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, GeoId); + bool selected = ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, GeoId); bool preselected = (preselectcurve == GeoId); bool constrainedElement = isFullyConstraintElement(GeoId); bool isExternal = GeoId < -1; @@ -450,8 +473,7 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli for (int k = j; j < k + indexes; j++) { verts[j].getValue(x, y, z); - verts[j] = - SbVec3f(x, y, viewOrientationFactor * drawingParameters.zHighLine); + verts[j] = SbVec3f(x, y, viewOrientationFactor * drawingParameters.zHighLine); } } else if (isExternal) { @@ -532,8 +554,7 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli // colors of the cross if (l == 0) { // only in layer 0 - if (ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, - Sketcher::GeoEnum::HAxis)) { + if (ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, Sketcher::GeoEnum::HAxis)) { crosscolor[0] = drawingParameters.SelectColor; } else if (preselectcross == 1) { // cross only in layer 0 @@ -543,8 +564,7 @@ void EditModeGeometryCoinManager::updateGeometryColor(const GeoListFacade& geoli crosscolor[0] = drawingParameters.CrossColorH; } - if (ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, - Sketcher::GeoEnum::VAxis)) { + if (ViewProviderSketchCoinAttorney::isCurveSelected(viewProvider, Sketcher::GeoEnum::VAxis)) { crosscolor[1] = drawingParameters.SelectColor; } else if (preselectcross == 2) { @@ -634,16 +654,17 @@ void EditModeGeometryCoinManager::createEditModePointInventorNodes() 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]->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]->markerIndex = Gui::Inventor::MarkerBitmaps::getMarkerIndex( + "CIRCLE_FILLED", + drawingParameters.markerSize + ); sep->addChild(editModeScenegraphNodes.PointSet[i]); editModeScenegraphNodes.PointsGroup->addChild(sep); @@ -655,42 +676,39 @@ void EditModeGeometryCoinManager::createEditModeCurveInventorNodes() { editModeScenegraphNodes.CurvesDrawStyle = new SoDrawStyle; editModeScenegraphNodes.CurvesDrawStyle->setName("CurvesDrawStyle"); - editModeScenegraphNodes.CurvesDrawStyle->lineWidth = - drawingParameters.CurveWidth * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesDrawStyle->lineWidth = drawingParameters.CurveWidth + * drawingParameters.pixelScalingFactor; editModeScenegraphNodes.CurvesDrawStyle->linePattern = drawingParameters.CurvePattern; editModeScenegraphNodes.CurvesDrawStyle->linePatternScaleFactor = 2; editModeScenegraphNodes.CurvesConstructionDrawStyle = new SoDrawStyle; editModeScenegraphNodes.CurvesConstructionDrawStyle->setName("CurvesConstructionDrawStyle"); - editModeScenegraphNodes.CurvesConstructionDrawStyle->lineWidth = - drawingParameters.ConstructionWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesConstructionDrawStyle->linePattern = - drawingParameters.ConstructionPattern; + editModeScenegraphNodes.CurvesConstructionDrawStyle->lineWidth = drawingParameters.ConstructionWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesConstructionDrawStyle->linePattern + = drawingParameters.ConstructionPattern; editModeScenegraphNodes.CurvesConstructionDrawStyle->linePatternScaleFactor = 2; editModeScenegraphNodes.CurvesInternalDrawStyle = new SoDrawStyle; editModeScenegraphNodes.CurvesInternalDrawStyle->setName("CurvesInternalDrawStyle"); - editModeScenegraphNodes.CurvesInternalDrawStyle->lineWidth = - drawingParameters.InternalWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesInternalDrawStyle->linePattern = - drawingParameters.InternalPattern; + editModeScenegraphNodes.CurvesInternalDrawStyle->lineWidth = drawingParameters.InternalWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesInternalDrawStyle->linePattern = drawingParameters.InternalPattern; editModeScenegraphNodes.CurvesInternalDrawStyle->linePatternScaleFactor = 2; editModeScenegraphNodes.CurvesExternalDrawStyle = new SoDrawStyle; editModeScenegraphNodes.CurvesExternalDrawStyle->setName("CurvesExternalDrawStyle"); - editModeScenegraphNodes.CurvesExternalDrawStyle->lineWidth = - drawingParameters.ExternalWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesExternalDrawStyle->linePattern = - drawingParameters.ExternalPattern; + editModeScenegraphNodes.CurvesExternalDrawStyle->lineWidth = drawingParameters.ExternalWidth + * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesExternalDrawStyle->linePattern = drawingParameters.ExternalPattern; editModeScenegraphNodes.CurvesExternalDrawStyle->linePatternScaleFactor = 2; editModeScenegraphNodes.CurvesExternalDefiningDrawStyle = new SoDrawStyle; - editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->setName( - "CurvesExternalDefiningDrawStyle"); - editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->lineWidth = - drawingParameters.ExternalDefiningWidth * drawingParameters.pixelScalingFactor; - editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->linePattern = - drawingParameters.ExternalDefiningPattern; + editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->setName("CurvesExternalDefiningDrawStyle"); + editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->lineWidth + = drawingParameters.ExternalDefiningWidth * drawingParameters.pixelScalingFactor; + editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->linePattern + = drawingParameters.ExternalDefiningPattern; editModeScenegraphNodes.CurvesExternalDefiningDrawStyle->linePatternScaleFactor = 2; for (int i = 0; i < geometryLayerParameters.getCoinLayerCount(); i++) { diff --git a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h index cd96446e2c..acc4949769 100644 --- a/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeGeometryCoinManager.h @@ -86,12 +86,14 @@ 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(); diff --git a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp index 151b055607..ec88d29e93 100644 --- a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp +++ b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.cpp @@ -45,7 +45,8 @@ EditModeInformationOverlayCoinConverter::EditModeInformationOverlayCoinConverter ViewProviderSketch& vp, SoGroup* infogroup, OverlayParameters& overlayparameters, - DrawingParameters& drawingparameters) + DrawingParameters& drawingparameters +) : viewProvider(vp) , infoGroup(infogroup) , overlayParameters(overlayparameters) @@ -87,8 +88,10 @@ void EditModeInformationOverlayCoinConverter::addToInfoGroup(SoSwitch* sw) } template -void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* geometry, - [[maybe_unused]] int geoid) +void EditModeInformationOverlayCoinConverter::calculate( + const Part::Geometry* geometry, + [[maybe_unused]] int geoid +) { if constexpr (calculation == CalculationType::ArcCircleHelper) { @@ -161,8 +164,8 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* ge 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) { @@ -192,10 +195,9 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* ge 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]); + 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); @@ -215,7 +217,8 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* ge Base::Console().developerError( "EditModeInformationOverlayCoinConverter", "Curvature graph for B-spline with GeoId=%d could not be calculated.\n", - geoid); + geoid + ); curvaturelist.emplace_back(0); } @@ -237,33 +240,40 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* ge pointatcomblist.emplace_back( pointatcurvelist[i] - overlayParameters.currentBSplineCombRepresentationScale * curvaturelist[i] - * normallist[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.indices.reserve(ndiv + 1); // ndiv separate segments of radials + 1 + // segment connecting at comb end 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 } 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 @@ -292,8 +302,8 @@ void EditModeInformationOverlayCoinConverter::calculate(const Part::Geometry* ge for (size_t i = 0; i < poles.size(); i++) { poleWeights.positions.emplace_back(poles[i]); - QString WeightString = - QStringLiteral("[%1]").arg(weights[i], 0, 'f', Base::UnitsApi::getDecimals()); + QString WeightString + = QStringLiteral("[%1]").arg(weights[i], 0, 'f', Base::UnitsApi::getDecimals()); poleWeights.strings.emplace_back(WeightString.toStdString()); } @@ -337,9 +347,11 @@ bool EditModeInformationOverlayCoinConverter::isVisible() } template -void EditModeInformationOverlayCoinConverter::setPolygon(const Result& result, - SoLineSet* polygonlineset, - SoCoordinate3* polygoncoords) +void EditModeInformationOverlayCoinConverter::setPolygon( + const Result& result, + SoLineSet* polygonlineset, + SoCoordinate3* polygoncoords +) { polygoncoords->point.setNum(result.coordinates.size()); @@ -349,10 +361,12 @@ void EditModeInformationOverlayCoinConverter::setPolygon(const Result& result, 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++) { @@ -425,7 +439,8 @@ void EditModeInformationOverlayCoinConverter::addNode(const Result& result) result.positions[i].x, result.positions[i].y, ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) - * drawingParameters.zInfo); + * drawingParameters.zInfo + ); SoFont* font = new SoFont; font->name.setValue("Helvetica"); @@ -503,19 +518,21 @@ void EditModeInformationOverlayCoinConverter::updateNode(const Result& result) 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)); static_cast( - sep->getChild(static_cast(TextNodePosition::TextCoordinates))) + sep->getChild(static_cast(TextNodePosition::TextCoordinates)) + ) ->translation.setValue( result.positions[i].x, result.positions[i].y, ViewProviderSketchCoinAttorney::getViewOrientationFactor(viewProvider) - * drawingParameters.zInfo); + * 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 @@ -524,14 +541,20 @@ void EditModeInformationOverlayCoinConverter::updateNode(const Result& result) // 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)))); + 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++; @@ -548,10 +571,12 @@ void EditModeInformationOverlayCoinConverter::updateNode(const Result& result) SoSeparator* sep = static_cast(sw->getChild(0)); SoCoordinate3* polygoncoords = static_cast( - sep->getChild(static_cast(PolygonNodePosition::PolygonCoordinates))); + sep->getChild(static_cast(PolygonNodePosition::PolygonCoordinates)) + ); SoLineSet* polygonlineset = static_cast( - sep->getChild(static_cast(PolygonNodePosition::PolygonLineSet))); + 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 9eb94ef3c0..9469d34c1d 100644 --- a/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.h +++ b/src/Mod/Sketcher/Gui/EditModeInformationOverlayCoinConverter.h @@ -154,10 +154,12 @@ 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 diff --git a/src/Mod/Sketcher/Gui/GeometryCreationMode.h b/src/Mod/Sketcher/Gui/GeometryCreationMode.h index 20c6fc7f40..ec126c0f72 100644 --- a/src/Mod/Sketcher/Gui/GeometryCreationMode.h +++ b/src/Mod/Sketcher/Gui/GeometryCreationMode.h @@ -31,6 +31,6 @@ enum class GeometryCreationMode Normal = 0, Construction = 1 }; -} +} // namespace SketcherGui #endif // SKETCHERGUI_GEOMETRYCREATIONMODE_H diff --git a/src/Mod/Sketcher/Gui/PreCompiled.h b/src/Mod/Sketcher/Gui/PreCompiled.h index 4fecadd51f..7d718010b9 100644 --- a/src/Mod/Sketcher/Gui/PreCompiled.h +++ b/src/Mod/Sketcher/Gui/PreCompiled.h @@ -43,7 +43,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // OpenCasCade diff --git a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp index 2883afbe6f..b89d5896e1 100644 --- a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp +++ b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.cpp @@ -62,8 +62,8 @@ QString PropertyConstraintListItem::toString(const QVariant& prop) const void PropertyConstraintListItem::initialize() { - const Sketcher::PropertyConstraintList* list = - static_cast(getPropertyData()[0]); + const Sketcher::PropertyConstraintList* list + = static_cast(getPropertyData()[0]); const std::vector& vals = list->getValues(); int id = 1; @@ -114,8 +114,7 @@ void PropertyConstraintListItem::initialize() // now deal with the unnamed if (iNamed == 0) { onlyUnnamed = true; - for (std::vector::const_iterator it = unnamed.begin(); - it != unnamed.end(); + for (std::vector::const_iterator it = unnamed.begin(); it != unnamed.end(); ++it) { (*it)->setParent(this); this->appendChild((*it)); @@ -124,8 +123,9 @@ 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); @@ -149,8 +149,8 @@ void PropertyConstraintListItem::assignProperty(const App::Property* prop) return; } - const Sketcher::PropertyConstraintList* list = - static_cast(prop); + 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 @@ -183,7 +183,8 @@ void PropertyConstraintListItem::assignProperty(const App::Property* prop) // search inside the group item for unnamed constraints if (!unnamed) { unnamed = static_cast( - PropertyConstraintListItem::create()); + PropertyConstraintListItem::create() + ); unnamed->setPropertyName(tr("Unnamed")); } @@ -248,8 +249,8 @@ QVariant PropertyConstraintListItem::value(const App::Property* prop) const QList subquantities; bool onlyNamed = true; - const std::vector& vals = - static_cast(prop)->getValues(); + 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 @@ -278,12 +279,15 @@ QVariant PropertyConstraintListItem::value(const App::Property* prop) const onlyNamed = false; subquantities.append(quant); PropertyItem* child = self->child(self->childCount() - 1); - PropertyConstraintListItem* unnamednode = - qobject_cast(child); + 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 { @@ -293,8 +297,7 @@ 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; } } @@ -325,7 +328,8 @@ bool PropertyConstraintListItem::event(QEvent* ev) int id = 0; if (dynamic_cast(this->parent())) { item = static_cast( - this->parent()->getFirstProperty()); + this->parent()->getFirstProperty() + ); } else { item = static_cast(getFirstProperty()); @@ -366,9 +370,11 @@ void PropertyConstraintListItem::setValue(const QVariant& value) Q_UNUSED(value); } -QWidget* PropertyConstraintListItem::createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const +QWidget* PropertyConstraintListItem::createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption +) const { Q_UNUSED(method); QLineEdit* le = new QLineEdit(parent); diff --git a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h index 4a178d65cb..a2c9a2e076 100644 --- a/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h +++ b/src/Mod/Sketcher/Gui/PropertyConstraintListItem.h @@ -40,9 +40,11 @@ class PropertyConstraintListItem: public Gui::PropertyEditor::PropertyItem ~PropertyConstraintListItem() override; void assignProperty(const App::Property* prop) override; - QWidget* createEditor(QWidget* parent, - const std::function& method, - FrameOption frameOption) const override; + QWidget* createEditor( + QWidget* parent, + const std::function& method, + FrameOption frameOption + ) const override; void setEditorData(QWidget* editor, const QVariant& data) const override; QVariant editorData(QWidget* editor) const override; diff --git a/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp b/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp index d02a227a85..c93ef8e484 100644 --- a/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp @@ -75,8 +75,7 @@ void SketchOrientationDialog::accept() } 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 { @@ -118,7 +117,8 @@ 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/SketcherSettings.cpp b/src/Mod/Sketcher/Gui/SketcherSettings.cpp index 845de3072c..847a62e2e3 100644 --- a/src/Mod/Sketcher/Gui/SketcherSettings.cpp +++ b/src/Mod/Sketcher/Gui/SketcherSettings.cpp @@ -122,7 +122,8 @@ void SketcherSettings::saveSettings() // Dimensioning constraints mode ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); bool singleTool = true; bool SeparatedTools = false; int index = ui->dimensioningMode->currentIndex(); @@ -168,7 +169,8 @@ void SketcherSettings::saveSettings() hGrp->SetInt("AutoScaleMode", index); hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools" + ); index = ui->ovpVisibility->currentIndex(); hGrp->SetInt("OnViewParameterVisibility", index); @@ -198,16 +200,19 @@ void SketcherSettings::loadSettings() ui->dimensioningMode->addItem(tr("Both")); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); bool singleTool = hGrp->GetBool("SingleDimensioningTool", true); bool SeparatedTools = hGrp->GetBool("SeparatedDimensioningTools", false); int index = SeparatedTools ? (singleTool ? 2 : 1) : 0; ui->dimensioningMode->setCurrentIndex(index); setProperty("dimensioningMode", index); - connect(ui->dimensioningMode, - QOverload::of(&QComboBox::currentIndexChanged), - this, - &SketcherSettings::dimensioningModeChanged); + connect( + ui->dimensioningMode, + QOverload::of(&QComboBox::currentIndexChanged), + this, + &SketcherSettings::dimensioningModeChanged + ); ui->radiusDiameterMode->setEnabled(index != 1); @@ -233,7 +238,8 @@ void SketcherSettings::loadSettings() ui->autoScaleMode->setCurrentIndex(index); hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools" + ); ui->ovpVisibility->clear(); ui->ovpVisibility->addItem(tr("None")); ui->ovpVisibility->addItem(tr("Dimensions only")); @@ -253,8 +259,7 @@ void SketcherSettings::checkForRestart() if (property("dimensioningMode").toInt() != ui->dimensioningMode->currentIndex()) { SketcherSettings::requireRestart(); } - if (property("checkBoxUnifiedCoincident").toBool() - != ui->checkBoxUnifiedCoincident->isChecked()) { + if (property("checkBoxUnifiedCoincident").toBool() != ui->checkBoxUnifiedCoincident->isChecked()) { SketcherSettings::requireRestart(); } if (property("checkBoxHorVerAuto").toBool() != ui->checkBoxHorVerAuto->isChecked()) { @@ -283,7 +288,8 @@ void SketcherSettings::resetSettingsToDefaults() ParameterGrp::handle hGrp; hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); // reset "Dimension tools" parameters hGrp->RemoveBool("SingleDimensioningTool"); hGrp->RemoveBool("SeparatedDimensioningTools"); @@ -295,7 +301,8 @@ void SketcherSettings::resetSettingsToDefaults() hGrp->RemoveInt("AutoScaleMode"); hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Tools" + ); // reset "OVP visibility" parameter hGrp->RemoveInt("OnViewParameterVisibility"); @@ -354,7 +361,8 @@ void SketcherSettingsGrid::saveSettings() ui->gridNumberSubdivision->onSave(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/General" + ); QVariant data = ui->gridLinePattern->itemData(ui->gridLinePattern->currentIndex()); int pattern = data.toInt(); hGrp->SetInt("GridLinePattern", pattern); @@ -377,7 +385,8 @@ void SketcherSettingsGrid::loadSettings() ui->gridNumberSubdivision->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/General"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/General" + ); int pattern = hGrp->GetInt("GridLinePattern", 0b0000111100001111); int index = ui->gridLinePattern->findData(QVariant(pattern)); if (index < 0) { @@ -413,10 +422,7 @@ SketcherSettingsDisplay::SketcherSettingsDisplay(QWidget* parent) { ui->setupUi(this); - connect(ui->btnTVApply, - &QPushButton::clicked, - this, - &SketcherSettingsDisplay::onBtnTVApplyClicked); + connect(ui->btnTVApply, &QPushButton::clicked, this, &SketcherSettingsDisplay::onBtnTVApplyClicked); } /** @@ -489,21 +495,23 @@ void SketcherSettingsDisplay::onBtnTVApplyClicked(bool) { QString errMsg; 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"); + 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) { Base::Console().developerError("SketcherSettings", "error in onBtnTVApplyClicked:\n"); @@ -600,7 +608,8 @@ void SketcherSettingsAppearance::saveSettings() ui->InternalFaceColor->onSave(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/View"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/View" + ); QVariant data = ui->EdgePattern->itemData(ui->EdgePattern->currentIndex()); int pattern = data.toInt(); hGrp->SetInt("EdgePattern", pattern); @@ -658,7 +667,8 @@ void SketcherSettingsAppearance::loadSettings() ui->InternalFaceColor->onRestore(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/View"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/View" + ); int pattern = hGrp->GetInt("EdgePattern", 0b1111111111111111); int index = ui->EdgePattern->findData(QVariant(pattern)); if (index < 0) { diff --git a/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.cpp b/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.cpp index a0fb3cf2c7..d2d795af02 100644 --- a/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.cpp +++ b/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.cpp @@ -71,74 +71,88 @@ SketcherToolDefaultWidget::~SketcherToolDefaultWidget() = default; void SketcherToolDefaultWidget::setupConnections() { - connect(ui->parameterOne, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterOne_valueChanged); - connect(ui->parameterTwo, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterTwo_valueChanged); - connect(ui->parameterThree, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterThree_valueChanged); - connect(ui->parameterFour, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterFour_valueChanged); - connect(ui->parameterFive, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterFive_valueChanged); - connect(ui->parameterSix, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterSix_valueChanged); - connect(ui->parameterSeven, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterSeven_valueChanged); - connect(ui->parameterEight, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterEight_valueChanged); - connect(ui->parameterNine, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterNine_valueChanged); - connect(ui->parameterTen, - qOverload(&Gui::QuantitySpinBox::valueChanged), - this, - &SketcherToolDefaultWidget::parameterTen_valueChanged); - connect(ui->checkBoxTS1, - &QCheckBox::toggled, - this, - &SketcherToolDefaultWidget::checkBoxTS1_toggled); - connect(ui->checkBoxTS2, - &QCheckBox::toggled, - this, - &SketcherToolDefaultWidget::checkBoxTS2_toggled); - connect(ui->checkBoxTS3, - &QCheckBox::toggled, - this, - &SketcherToolDefaultWidget::checkBoxTS3_toggled); - connect(ui->checkBoxTS4, - &QCheckBox::toggled, - this, - &SketcherToolDefaultWidget::checkBoxTS4_toggled); - connect(ui->comboBox1, - qOverload(&QComboBox::currentIndexChanged), - this, - &SketcherToolDefaultWidget::comboBox1_currentIndexChanged); - connect(ui->comboBox2, - qOverload(&QComboBox::currentIndexChanged), - this, - &SketcherToolDefaultWidget::comboBox2_currentIndexChanged); - connect(ui->comboBox3, - qOverload(&QComboBox::currentIndexChanged), - this, - &SketcherToolDefaultWidget::comboBox3_currentIndexChanged); + connect( + ui->parameterOne, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterOne_valueChanged + ); + connect( + ui->parameterTwo, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterTwo_valueChanged + ); + connect( + ui->parameterThree, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterThree_valueChanged + ); + connect( + ui->parameterFour, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterFour_valueChanged + ); + connect( + ui->parameterFive, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterFive_valueChanged + ); + connect( + ui->parameterSix, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterSix_valueChanged + ); + connect( + ui->parameterSeven, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterSeven_valueChanged + ); + connect( + ui->parameterEight, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterEight_valueChanged + ); + connect( + ui->parameterNine, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterNine_valueChanged + ); + connect( + ui->parameterTen, + qOverload(&Gui::QuantitySpinBox::valueChanged), + this, + &SketcherToolDefaultWidget::parameterTen_valueChanged + ); + connect(ui->checkBoxTS1, &QCheckBox::toggled, this, &SketcherToolDefaultWidget::checkBoxTS1_toggled); + connect(ui->checkBoxTS2, &QCheckBox::toggled, this, &SketcherToolDefaultWidget::checkBoxTS2_toggled); + connect(ui->checkBoxTS3, &QCheckBox::toggled, this, &SketcherToolDefaultWidget::checkBoxTS3_toggled); + connect(ui->checkBoxTS4, &QCheckBox::toggled, this, &SketcherToolDefaultWidget::checkBoxTS4_toggled); + connect( + ui->comboBox1, + qOverload(&QComboBox::currentIndexChanged), + this, + &SketcherToolDefaultWidget::comboBox1_currentIndexChanged + ); + connect( + ui->comboBox2, + qOverload(&QComboBox::currentIndexChanged), + this, + &SketcherToolDefaultWidget::comboBox2_currentIndexChanged + ); + connect( + ui->comboBox3, + qOverload(&QComboBox::currentIndexChanged), + this, + &SketcherToolDefaultWidget::comboBox3_currentIndexChanged + ); } // preselect the number of the spinbox when it gets the focus. @@ -305,8 +319,7 @@ void SketcherToolDefaultWidget::setParameterVisible(int parameterindex, bool vis } } -void SketcherToolDefaultWidget::setParameterFilteringObject(int parameterindex, - QObject* filteringObject) +void SketcherToolDefaultWidget::setParameterFilteringObject(int parameterindex, QObject* filteringObject) { if (parameterindex < nParameters) { getParameterSpinBox(parameterindex)->installEventFilter(filteringObject); @@ -314,8 +327,7 @@ void SketcherToolDefaultWidget::setParameterFilteringObject(int parameterindex, return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::setParameterLabel(int parameterindex, const QString& string) @@ -333,8 +345,7 @@ void SketcherToolDefaultWidget::setParameter(int parameterindex, double val) return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::setParameterWithoutPassingFocus(int parameterindex, double val) @@ -360,8 +371,7 @@ void SketcherToolDefaultWidget::configureParameterUnit(int parameterindex, const return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::configureParameterDecimals(int parameterindex, int val) @@ -373,8 +383,7 @@ void SketcherToolDefaultWidget::configureParameterDecimals(int parameterindex, i return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::configureParameterMin(int parameterindex, double val) @@ -386,8 +395,7 @@ void SketcherToolDefaultWidget::configureParameterMin(int parameterindex, double return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::configureParameterMax(int parameterindex, double val) @@ -399,8 +407,7 @@ void SketcherToolDefaultWidget::configureParameterMax(int parameterindex, double return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::setParameterEnabled(int parameterindex, bool active) @@ -411,8 +418,7 @@ void SketcherToolDefaultWidget::setParameterEnabled(int parameterindex, bool act return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::setParameterFocus(int parameterindex) @@ -425,8 +431,7 @@ void SketcherToolDefaultWidget::setParameterFocus(int parameterindex) return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } void SketcherToolDefaultWidget::setParameterFontStyle(int parameterindex, FontStyle fontStyle) @@ -452,8 +457,7 @@ void SketcherToolDefaultWidget::setParameterFontStyle(int parameterindex, FontSt return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } QLabel* SketcherToolDefaultWidget::getParameterLabel(int parameterindex) @@ -550,9 +554,7 @@ bool SketcherToolDefaultWidget::isParameterSet(int parameterindex) THROWM(Base::IndexError, "ToolWidget parameter index out of range"); } -void SketcherToolDefaultWidget::updateVisualValue(int parameterindex, - double val, - const Base::Unit& unit) +void SketcherToolDefaultWidget::updateVisualValue(int parameterindex, double val, const Base::Unit& unit) { if (parameterindex < nParameters) { Base::StateLocker lock(blockParameterSlots, true); @@ -568,8 +570,7 @@ void SketcherToolDefaultWidget::updateVisualValue(int parameterindex, return; } - THROWM(Base::IndexError, - QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); + THROWM(Base::IndexError, QT_TRANSLATE_NOOP("Exceptions", "ToolWidget parameter index out of range")); } // checkbox functions @@ -677,8 +678,7 @@ bool SketcherToolDefaultWidget::getCheckboxChecked(int checkboxindex) THROWM(Base::IndexError, "ToolWidget checkbox index out of range"); } -void SketcherToolDefaultWidget::setCheckboxPrefEntry(int checkboxindex, - const std::string& prefEntry) +void SketcherToolDefaultWidget::setCheckboxPrefEntry(int checkboxindex, const std::string& prefEntry) { if (checkboxindex < nCheckbox) { QByteArray byteArray(prefEntry.c_str(), prefEntry.length()); @@ -707,8 +707,7 @@ void SketcherToolDefaultWidget::setComboboxItemIcon(int comboboxindex, int index } } -void SketcherToolDefaultWidget::setComboboxPrefEntry(int comboboxindex, - const std::string& prefEntry) +void SketcherToolDefaultWidget::setComboboxPrefEntry(int comboboxindex, const std::string& prefEntry) { if (comboboxindex < nCombobox) { QByteArray byteArray(prefEntry.c_str(), prefEntry.length()); diff --git a/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.h b/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.h index 479d66d6c8..1712109f6a 100644 --- a/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.h +++ b/src/Mod/Sketcher/Gui/SketcherToolDefaultWidget.h @@ -116,8 +116,7 @@ public: void configureParameterMin(int parameterindex, double val); double getParameter(int parameterindex); bool isParameterSet(int parameterindex); - void - updateVisualValue(int parameterindex, double val, const Base::Unit& unit = Base::Unit::Length); + void updateVisualValue(int parameterindex, double val, const Base::Unit& unit = Base::Unit::Length); void setParameterEnabled(int parameterindex, bool active = true); void setParameterFocus(int parameterindex); diff --git a/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.cpp b/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.cpp index 9fda4f7821..f6224dc6b8 100644 --- a/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.cpp +++ b/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.cpp @@ -30,7 +30,8 @@ using namespace SketcherGui; void SketcherTransformationExpressionHelper::storeOriginalExpressions( Sketcher::SketchObject* sketchObject, - const std::vector& listOfGeoIds) + const std::vector& listOfGeoIds +) { if (!sketchObject) { return; @@ -48,15 +49,15 @@ void SketcherTransformationExpressionHelper::storeOriginalExpressions( || (cstr->Second == geoId && cstr->Type != Sketcher::Radius && cstr->Type != Sketcher::Diameter && cstr->Type != Sketcher::Weight))) { - App::ObjectIdentifier spath = - sketchObject->Constraints.createPath(static_cast(i)); - App::PropertyExpressionEngine::ExpressionInfo expr_info = - sketchObject->getExpression(spath); + App::ObjectIdentifier spath = sketchObject->Constraints.createPath(static_cast(i)); + App::PropertyExpressionEngine::ExpressionInfo expr_info + = sketchObject->getExpression(spath); if (expr_info.expression) { // map expression to geoid as a key - originalExpressions[geoId] = - std::shared_ptr(expr_info.expression->copy()); + originalExpressions[geoId] = std::shared_ptr( + expr_info.expression->copy() + ); } } } @@ -68,7 +69,8 @@ void SketcherTransformationExpressionHelper::copyExpressionsToNewConstraints( const std::vector& listOfGeoIds, size_t shapeGeometrySize, int numberOfCopies, - int secondNumberOfCopies) + int secondNumberOfCopies +) { // apply stored expressions to new constraints, but bail out if we haven't stored anything if (originalExpressions.empty() || !sketchObject) { @@ -78,8 +80,8 @@ void SketcherTransformationExpressionHelper::copyExpressionsToNewConstraints( std::string sketchObj = Gui::Command::getObjectCmd(sketchObject); const std::vector& vals = sketchObject->Constraints.getValues(); - CopyCalculationParams params = - calculateCopyParams(sketchObject, listOfGeoIds, shapeGeometrySize, numberOfCopies); + CopyCalculationParams params + = calculateCopyParams(sketchObject, listOfGeoIds, shapeGeometrySize, numberOfCopies); for (size_t i = 0; i < vals.size(); i++) { const auto& cstr = vals[i]; if (!cstr->isDriving || !cstr->isDimensional()) { @@ -93,13 +95,15 @@ void SketcherTransformationExpressionHelper::copyExpressionsToNewConstraints( int originalIndex = indexOfGeoId(listOfGeoIds, originalGeoId); if (originalIndex >= 0) { - expressionApplied = tryApplyExpressionToConstraint(cstr, - i, - originalIndex, - params, - secondNumberOfCopies, - exprPair.second, - sketchObj); + expressionApplied = tryApplyExpressionToConstraint( + cstr, + i, + originalIndex, + params, + secondNumberOfCopies, + exprPair.second, + sketchObj + ); if (expressionApplied) { break; @@ -119,15 +123,16 @@ bool SketcherTransformationExpressionHelper::hasStoredExpressions() const return !originalExpressions.empty(); } -SketcherTransformationExpressionHelper::CopyCalculationParams -SketcherTransformationExpressionHelper::calculateCopyParams(Sketcher::SketchObject* sketchObject, - const std::vector& listOfGeoIds, - size_t shapeGeometrySize, - int numberOfCopies) const +SketcherTransformationExpressionHelper::CopyCalculationParams SketcherTransformationExpressionHelper::calculateCopyParams( + Sketcher::SketchObject* sketchObject, + const std::vector& listOfGeoIds, + size_t shapeGeometrySize, + int numberOfCopies +) const { CopyCalculationParams params; - params.firstCurveCreated = - sketchObject->getHighestCurveIndex() + 1 - static_cast(shapeGeometrySize); + params.firstCurveCreated = sketchObject->getHighestCurveIndex() + 1 + - static_cast(shapeGeometrySize); params.size = static_cast(listOfGeoIds.size()); params.numberOfCopiesToMake = numberOfCopies == 0 ? 1 : numberOfCopies; return params; @@ -140,7 +145,8 @@ bool SketcherTransformationExpressionHelper::tryApplyExpressionToConstraint( const CopyCalculationParams& params, int secondNumberOfCopies, const std::shared_ptr& expression, - const std::string& sketchObj) const + const std::string& sketchObj +) const { // check all copies of this geometry as we assign them the same expression for (int k = 0; k < secondNumberOfCopies; k++) { @@ -150,11 +156,13 @@ bool SketcherTransformationExpressionHelper::tryApplyExpressionToConstraint( // if this constraint references our copied geometry, apply the expression if (constraintReferencesGeometry(cstr, expectedNewGeoId)) { - Gui::Command::doCommand(Gui::Command::Doc, - "%s.setExpression('Constraints[%d]', '%s')", - sketchObj.c_str(), - static_cast(constraintIndex), - expression->toString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "%s.setExpression('Constraints[%d]', '%s')", + sketchObj.c_str(), + static_cast(constraintIndex), + expression->toString().c_str() + ); return true; } } @@ -164,7 +172,8 @@ bool SketcherTransformationExpressionHelper::tryApplyExpressionToConstraint( bool SketcherTransformationExpressionHelper::constraintReferencesGeometry( const Sketcher::Constraint* cstr, - int geoId) const + int geoId +) const { return cstr->First == geoId || (cstr->Second == geoId && cstr->Type != Sketcher::Radius diff --git a/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.h b/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.h index f8ae8d9dfb..e8d39d5050 100644 --- a/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.h +++ b/src/Mod/Sketcher/Gui/SketcherTransformationExpressionHelper.h @@ -51,8 +51,10 @@ public: * @param sketchObject The sketch object containing the constraints * @param listOfGeoIds List of geometry IDs that are being transformed */ - void storeOriginalExpressions(Sketcher::SketchObject* sketchObject, - const std::vector& listOfGeoIds); + void storeOriginalExpressions( + Sketcher::SketchObject* sketchObject, + const std::vector& listOfGeoIds + ); /** @brief Apply stored expressions to new constraints after transformation * @@ -63,11 +65,13 @@ public: * geometry) * @param secondNumberOfCopies Number of rows for array operations */ - void copyExpressionsToNewConstraints(Sketcher::SketchObject* sketchObject, - const std::vector& listOfGeoIds, - size_t shapeGeometrySize, - int numberOfCopies, - int secondNumberOfCopies); + void copyExpressionsToNewConstraints( + Sketcher::SketchObject* sketchObject, + const std::vector& listOfGeoIds, + size_t shapeGeometrySize, + int numberOfCopies, + int secondNumberOfCopies + ); void clear(); bool hasStoredExpressions() const; @@ -81,19 +85,23 @@ private: }; /// calculate parameters needed for copy operations - CopyCalculationParams calculateCopyParams(Sketcher::SketchObject* sketchObject, - const std::vector& listOfGeoIds, - size_t shapeGeometrySize, - int numberOfCopies) const; + CopyCalculationParams calculateCopyParams( + Sketcher::SketchObject* sketchObject, + const std::vector& listOfGeoIds, + size_t shapeGeometrySize, + int numberOfCopies + ) const; /// try to apply an expression to a constraint if it matches copied geometry - bool tryApplyExpressionToConstraint(const Sketcher::Constraint* cstr, - size_t constraintIndex, - int originalIndex, - const CopyCalculationParams& params, - int secondNumberOfCopies, - const std::shared_ptr& expression, - const std::string& sketchObj) const; + bool tryApplyExpressionToConstraint( + const Sketcher::Constraint* cstr, + size_t constraintIndex, + int originalIndex, + const CopyCalculationParams& params, + int secondNumberOfCopies, + const std::shared_ptr& expression, + const std::string& sketchObj + ) const; /// check if a constraint references the specified geometry ID bool constraintReferencesGeometry(const Sketcher::Constraint* cstr, int geoId) const; diff --git a/src/Mod/Sketcher/Gui/SnapManager.cpp b/src/Mod/Sketcher/Gui/SnapManager.cpp index e7eb287986..612477ddd7 100644 --- a/src/Mod/Sketcher/Gui/SnapManager.cpp +++ b/src/Mod/Sketcher/Gui/SnapManager.cpp @@ -69,22 +69,10 @@ void SnapManager::ParameterObserver::initParameters() // key->first => String of parameter, // key->second => Update function to be called for the parameter, str2updatefunction = { - {"Snap", - [this](const std::string& param) { - updateSnapParameter(param); - }}, - {"SnapToObjects", - [this](const std::string& param) { - updateSnapToObjectParameter(param); - }}, - {"SnapToGrid", - [this](const std::string& param) { - updateSnapToGridParameter(param); - }}, - {"SnapAngle", - [this](const std::string& param) { - updateSnapAngleParameter(param); - }}, + {"Snap", [this](const std::string& param) { updateSnapParameter(param); }}, + {"SnapToObjects", [this](const std::string& param) { updateSnapToObjectParameter(param); }}, + {"SnapToGrid", [this](const std::string& param) { updateSnapToGridParameter(param); }}, + {"SnapAngle", [this](const std::string& param) { updateSnapAngleParameter(param); }}, }; for (auto& val : str2updatefunction) { @@ -120,8 +108,8 @@ void SnapManager::ParameterObserver::updateSnapAngleParameter(const std::string& { ParameterGrp::handle hGrp = getParameterGrpHandle(); - client.snapAngle = - fmod(Base::toRadians(hGrp->GetFloat(parametername.c_str(), 5.)), 2 * std::numbers::pi); + client.snapAngle + = fmod(Base::toRadians(hGrp->GetFloat(parametername.c_str(), 5.)), 2 * std::numbers::pi); } void SnapManager::ParameterObserver::subscribeToParameters() @@ -142,15 +130,14 @@ 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; @@ -166,7 +153,8 @@ void SnapManager::ParameterObserver::OnChange(Base::Subject& rCalle ParameterGrp::handle SnapManager::ParameterObserver::getParameterGrpHandle() { return App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Snap"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Snap" + ); } //**************************** SnapManager class ****************************** @@ -291,15 +279,13 @@ bool SnapManager::snapToObject(Base::Vector2d inputPos, Base::Vector2d& snapPos, // If it is a line, then we check if we need to snap to the middle. if (geo->is()) { - const Part::GeomLineSegment* line = - static_cast(geo); + 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 (geo->is()) { - const Part::GeomArcOfCircle* arc = - static_cast(geo); + const Part::GeomArcOfCircle* arc = static_cast(geo); snapToArcMiddle(pointToOverride, arc); } @@ -341,8 +327,7 @@ bool SnapManager::snapToGrid(Base::Vector2d inputPos, Base::Vector2d& snapPos) 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(); diff --git a/src/Mod/Sketcher/Gui/StyleParameters.h b/src/Mod/Sketcher/Gui/StyleParameters.h index 4bc217cd52..9a0a05d1a8 100644 --- a/src/Mod/Sketcher/Gui/StyleParameters.h +++ b/src/Mod/Sketcher/Gui/StyleParameters.h @@ -31,10 +31,12 @@ namespace SketcherGui::StyleParameters // rubberband selection colors DEFINE_STYLE_PARAMETER( SketcherRubberbandTouchSelectionColor, - Base::Color(0.0F, 1.0F, 0.0F, 1.0F)); // green for touch selection (right to left) + Base::Color(0.0F, 1.0F, 0.0F, 1.0F) +); // green for touch selection (right to left) DEFINE_STYLE_PARAMETER( SketcherRubberbandWindowSelectionColor, - Base::Color(0.0F, 0.4F, 1.0F, 1.0F)); // blue for window selection (left to right) + Base::Color(0.0F, 0.4F, 1.0F, 1.0F) +); // blue for window selection (left to right) } // namespace SketcherGui::StyleParameters #endif // SKETCHER_STYLEPARAMETERS_H diff --git a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp index c5baa544c4..cb90c02bd2 100644 --- a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp +++ b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.cpp @@ -48,7 +48,8 @@ TaskDlgEditSketch::TaskDlgEditSketch(ViewProviderSketch* sketchView) SolverAdvanced = new TaskSketcherSolverAdvanced(sketchView); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); setEscapeButtonEnabled(hGrp->GetBool("LeaveSketchWithEscape", true)); Content.push_back(ToolSettings); @@ -75,7 +76,8 @@ TaskDlgEditSketch::TaskDlgEditSketch(ViewProviderSketch* sketchView) } connectionToolSettings = sketchView->registerToolChanged( - std::bind(&SketcherGui::TaskDlgEditSketch::slotToolChanged, this, sp::_1)); + std::bind(&SketcherGui::TaskDlgEditSketch::slotToolChanged, this, sp::_1) + ); ToolSettings->setHidden(true); @@ -123,7 +125,8 @@ bool TaskDlgEditSketch::accept() bool TaskDlgEditSketch::reject() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); hGrp->SetBool("ExpandedMessagesWidget", Messages->isGroupVisible()); hGrp->SetBool("ExpandedSolverAdvancedWidget", SolverAdvanced->isGroupVisible()); hGrp->SetBool("ExpandedConstraintsWidget", Constraints->isGroupVisible()); @@ -134,12 +137,8 @@ bool TaskDlgEditSketch::reject() } 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()); + 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/TaskSketcherConstraints.h b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h index dff3ff514e..d793a576a9 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h @@ -103,8 +103,7 @@ protected: 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}, @@ -208,13 +207,12 @@ 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; }; diff --git a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp index 7738f16de6..4d66391b42 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.cpp @@ -66,14 +66,16 @@ void TaskSketcherCreateCommands::changeEvent(QEvent* e) } /// @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 + if (Reason.Type == SelectionChanges::AddSelection || Reason.Type == SelectionChanges::RmvSelection || Reason.Type == SelectionChanges::SetSelection - || Reason.Type == SelectionChanges::ClrSelection) {} + || Reason.Type == SelectionChanges::ClrSelection) { + } } /// @endcond DOXERR diff --git a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h index a03303f1cc..3878a589a2 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h @@ -47,8 +47,10 @@ public: explicit TaskSketcherCreateCommands(QWidget* parent = nullptr); ~TaskSketcherCreateCommands() override; /// Observer message from the Selection - void OnChange(Gui::SelectionSingleton::SubjectType& rCaller, - Gui::SelectionSingleton::MessageType Reason) override; + void OnChange( + Gui::SelectionSingleton::SubjectType& rCaller, + Gui::SelectionSingleton::MessageType Reason + ) override; private Q_SLOTS: diff --git a/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp b/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp index 052075c3c6..dd448e1869 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp @@ -189,14 +189,16 @@ public: Hidden = 2, }; - ElementItem(int elementnr, - int startingVertex, - int midVertex, - int endVertex, - Base::Type geometryType, - GeometryState state, - const QString& lab, - ViewProviderSketch* sketchView) + ElementItem( + int elementnr, + int startingVertex, + int midVertex, + int endVertex, + Base::Type geometryType, + GeometryState state, + const QString& lab, + ViewProviderSketch* sketchView + ) : ElementNbr(elementnr) , StartingVertex(startingVertex) , MidVertex(midVertex) @@ -940,9 +942,11 @@ ElementItemDelegate::ElementItemDelegate(ElementView* parent) { // This class relies on the parent being an ElementView, see getElementtItem } -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 = getElementItem(index); @@ -971,9 +975,11 @@ void ElementItemDelegate::paint(QPainter* painter, drawSubControl(SubControl::Label, painter, option, index); } -QRect ElementItemDelegate::subControlRect(SubControl element, - const QStyleOptionViewItem& option, - const QModelIndex& index) const +QRect ElementItemDelegate::subControlRect( + SubControl element, + const QStyleOptionViewItem& option, + const QModelIndex& index +) const { auto itemOption = option; @@ -981,19 +987,18 @@ QRect ElementItemDelegate::subControlRect(SubControl element, initStyleOption(&itemOption, index); - QRect checkBoxRect = - style->subElementRect(QStyle::SE_CheckBoxIndicator, &itemOption, option.widget); + QRect checkBoxRect + = style->subElementRect(QStyle::SE_CheckBoxIndicator, &itemOption, option.widget); - checkBoxRect.moveTo(gap, - option.rect.top() + (option.rect.height() - checkBoxRect.height()) / 2); + checkBoxRect.moveTo(gap, option.rect.top() + (option.rect.height() - checkBoxRect.height()) / 2); if (element == SubControl::CheckBox) { return checkBoxRect; } - QRect selectRect = - style->subElementRect(QStyle::SE_ItemViewItemDecoration, &itemOption, option.widget) - .translated(checkBoxRect.right() + gap, 0); + QRect selectRect + = style->subElementRect(QStyle::SE_ItemViewItemDecoration, &itemOption, option.widget) + .translated(checkBoxRect.right() + gap, 0); unsigned pos = element - SubControl::LineSelect; @@ -1008,10 +1013,12 @@ QRect ElementItemDelegate::subControlRect(SubControl element, return rect; } -void ElementItemDelegate::drawSubControl(SubControl element, - QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex& index) const +void ElementItemDelegate::drawSubControl( + SubControl element, + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index +) const { auto item = getElementItem(index); auto style = option.widget ? option.widget->style() : QApplication::style(); @@ -1066,10 +1073,12 @@ void ElementItemDelegate::drawSubControl(SubControl element, checkboxOption.state |= QStyle::State_Off; } - style->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck, - &checkboxOption, - painter, - option.widget); + style->drawPrimitive( + QStyle::PE_IndicatorItemViewItemCheck, + &checkboxOption, + painter, + option.widget + ); break; } @@ -1099,10 +1108,11 @@ void ElementItemDelegate::drawSubControl(SubControl element, auto labelBoundingBox = painter->fontMetrics().tightBoundingRect(item->label); - painter->drawText(rect.x(), - option.rect.bottom() - - (option.rect.height() - labelBoundingBox.height()) / 2, - item->label); + painter->drawText( + rect.x(), + option.rect.bottom() - (option.rect.height() - labelBoundingBox.height()) / 2, + item->label + ); break; } @@ -1508,8 +1518,7 @@ void TaskSketcherElements::onSelectionChanged(const Gui::SelectionChanges& msg) 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) { + || strcmp(msg.pObjectName, sketchView->getSketchObject()->getNameInDocument()) != 0) { return; } if (!msg.pSubName) { diff --git a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp index d95c91a75b..cd84f79fea 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp @@ -52,10 +52,7 @@ using namespace SketcherGui; using namespace Gui::TaskView; TaskSketcherSolverAdvanced::TaskSketcherSolverAdvanced(ViewProviderSketch* sketchView) - : TaskBox(Gui::BitmapFactory().pixmap("document-new"), - tr("Advanced Solver Controls"), - true, - nullptr) + : TaskBox(Gui::BitmapFactory().pixmap("document-new"), tr("Advanced Solver Controls"), true, nullptr) , sketchView(sketchView) , ui(new Ui_TaskSketcherSolverAdvanced) { @@ -87,106 +84,151 @@ 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->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 + ); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - connect(ui->checkBoxSketchSizeMultiplier, - &QCheckBox::checkStateChanged, - this, - &TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged); + connect( + ui->checkBoxSketchSizeMultiplier, + &QCheckBox::checkStateChanged, + this, + &TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged + ); #else - connect(ui->checkBoxSketchSizeMultiplier, - &QCheckBox::stateChanged, - this, - &TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged); + connect( + ui->checkBoxSketchSizeMultiplier, + &QCheckBox::stateChanged, + this, + &TaskSketcherSolverAdvanced::onCheckBoxSketchSizeMultiplierStateChanged + ); #endif - 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->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 + ); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - connect(ui->checkBoxRedundantSketchSizeMultiplier, - &QCheckBox::checkStateChanged, - this, - &TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged); + connect( + ui->checkBoxRedundantSketchSizeMultiplier, + &QCheckBox::checkStateChanged, + this, + &TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged + ); #else - connect(ui->checkBoxRedundantSketchSizeMultiplier, - &QCheckBox::stateChanged, - this, - &TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged); + connect( + ui->checkBoxRedundantSketchSizeMultiplier, + &QCheckBox::stateChanged, + this, + &TaskSketcherSolverAdvanced::onCheckBoxRedundantSketchSizeMultiplierStateChanged + ); #endif - 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->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"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced" + ); int currentindex = ui->comboBoxDefaultSolver->currentIndex(); int redundantcurrentindex = ui->comboBoxRedundantDefaultSolver->currentIndex(); @@ -219,15 +261,23 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() 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 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( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditSolverParam2->setText(QString::number(eps1).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditSolverParam3->setText(QString::number(tau).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); + ui->lineEditSolverParam1->setText( + QString::number(eps).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditSolverParam2->setText( + QString::number(eps1).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditSolverParam3->setText( + QString::number(tau).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("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 @@ -249,18 +299,24 @@ 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( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditSolverParam2->setText(QString::number(tolx).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditSolverParam3->setText(QString::number(tolf).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); + 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( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditSolverParam2->setText( + QString::number(tolx).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditSolverParam3->setText( + QString::number(tolf).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); const_cast(sketchView->getSketchObject()->getSolvedSketch()) .setDL_tolg(tolg); const_cast(sketchView->getSketchObject()->getSolvedSketch()) @@ -275,7 +331,8 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced" + ); int currentindex = ui->comboBoxDefaultSolver->currentIndex(); int redundantcurrentindex = ui->comboBoxRedundantDefaultSolver->currentIndex(); @@ -308,17 +365,29 @@ void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() ui->lineEditRedundantSolverParam2->setEnabled(true); ui->lineEditRedundantSolverParam3->setEnabled(true); double eps = ::atof( - hGrp->GetASCII("Redundant_LM_eps", QString::number(LM_EPS).toUtf8()).c_str()); + 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()); + 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( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditRedundantSolverParam2->setText(QString::number(eps1).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditRedundantSolverParam3->setText(QString::number(tau).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); + hGrp->GetASCII("Redundant_LM_tau", QString::number(LM_TAU).toUtf8()).c_str() + ); + ui->lineEditRedundantSolverParam1->setText( + QString::number(eps).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditRedundantSolverParam2->setText( + QString::number(eps1).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditRedundantSolverParam3->setText( + QString::number(tau).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); const_cast(sketchView->getSketchObject()->getSolvedSketch()) .setLM_epsRedundant(eps); const_cast(sketchView->getSketchObject()->getSolvedSketch()) @@ -336,17 +405,29 @@ void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() ui->lineEditRedundantSolverParam2->setEnabled(true); ui->lineEditRedundantSolverParam3->setEnabled(true); double tolg = ::atof( - hGrp->GetASCII("Redundant_DL_tolg", QString::number(DL_TOLG).toUtf8()).c_str()); + 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()); + 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( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditRedundantSolverParam2->setText(QString::number(tolx).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); - ui->lineEditRedundantSolverParam3->setText(QString::number(tolf).remove( - QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper())); + hGrp->GetASCII("Redundant_DL_tolf", QString::number(DL_TOLF).toUtf8()).c_str() + ); + ui->lineEditRedundantSolverParam1->setText( + QString::number(tolg).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditRedundantSolverParam2->setText( + QString::number(tolx).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); + ui->lineEditRedundantSolverParam3->setText( + QString::number(tolf).remove( + QStringLiteral("+").replace(QStringLiteral("e0"), QStringLiteral("E")).toUpper() + ) + ); const_cast(sketchView->getSketchObject()->getSolvedSketch()) .setDL_tolgRedundant(tolg); const_cast(sketchView->getSketchObject()->getSolvedSketch()) @@ -535,8 +616,8 @@ 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(); } @@ -594,8 +675,7 @@ void TaskSketcherSolverAdvanced::onLineEditConvergenceEditingFinished() ui->lineEditConvergence->onSave(); - const_cast(sketchView->getSketchObject()->getSolvedSketch()) - .setConvergence(val); + const_cast(sketchView->getSketchObject()->getSolvedSketch()).setConvergence(val); } void TaskSketcherSolverAdvanced::onLineEditRedundantConvergenceEditingFinished() @@ -623,8 +703,8 @@ void TaskSketcherSolverAdvanced::onComboBoxQRMethodCurrentIndexChanged(int index 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(); } @@ -667,7 +747,8 @@ void TaskSketcherSolverAdvanced::onPushButtonDefaultsClicked(bool checked /* = f Q_UNUSED(checked); // Algorithm params for default solvers ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); + "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()); @@ -719,9 +800,8 @@ void TaskSketcherSolverAdvanced::updateSketchObject() .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()).defaultSolverRedundant + = static_cast(ui->comboBoxRedundantDefaultSolver->currentIndex()); const_cast(sketchView->getSketchObject()->getSolvedSketch()) .setQRAlgorithm((GCS::QRAlgorithm)ui->comboBoxQRMethod->currentIndex()); const_cast(sketchView->getSketchObject()->getSolvedSketch()) @@ -734,8 +814,8 @@ void TaskSketcherSolverAdvanced::updateSketchObject() .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()).defaultSolver + = static_cast(ui->comboBoxDefaultSolver->currentIndex()); const_cast(sketchView->getSketchObject()->getSolvedSketch()) .setDogLegGaussStep((GCS::DogLegGaussStep)ui->comboBoxDogLegGaussStep->currentIndex()); diff --git a/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp b/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp index 2c931420a9..c80207157f 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp @@ -156,11 +156,10 @@ void SketcherValidation::onFindButtonClicked() } } - sketch->detectMissingPointOnPointConstraints(prec, - !ui->checkBoxIgnoreConstruction->isChecked()); + sketch->detectMissingPointOnPointConstraints(prec, !ui->checkBoxIgnoreConstruction->isChecked()); - std::vector& vertexConstraints = - sketch->getMissingPointOnPointConstraints(); + std::vector& vertexConstraints + = sketch->getMissingPointOnPointConstraints(); std::vector points; points.reserve(vertexConstraints.size()); @@ -171,9 +170,11 @@ 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); } @@ -182,7 +183,8 @@ void SketcherValidation::onFindButtonClicked() Gui::TranslatedUserWarning( *sketch, tr("Missing coincidences"), - tr("%1 missing coincidences found").arg(vertexConstraints.size())); + tr("%1 missing coincidences found").arg(vertexConstraints.size()) + ); ui->fixButton->setEnabled(true); } @@ -232,16 +234,16 @@ void SketcherValidation::onFindConstraintClicked() } 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); } @@ -290,7 +292,8 @@ void SketcherValidation::onFindReversedClicked() "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)); + .arg(nc) + ); ui->swapReversed->setEnabled(true); } @@ -301,15 +304,18 @@ void SketcherValidation::onFindReversedClicked() tr("%1 reversed external geometry arcs were found. Their endpoints are " "encircled in the 3D view.\n\n" "However, no constraints linking to the endpoints were found.") - .arg(points.size() / 2)); + .arg(points.size() / 2) + ); ui->swapReversed->setEnabled(false); } } else { - Gui::TranslatedNotification(*sketch, - tr("Reversed external geometry"), - tr("No reversed external geometry arcs were found.")); + Gui::TranslatedNotification( + *sketch, + tr("Reversed external geometry"), + tr("No reversed external geometry arcs were found.") + ); } } @@ -326,7 +332,8 @@ void SketcherValidation::onSwapReversedClicked() Gui::TranslatedNotification( *sketch, tr("Reversed external geometry"), - tr("%1 changes were made to constraints linking to endpoints of reversed arcs.").arg(n)); + tr("%1 changes were made to constraints linking to endpoints of reversed arcs.").arg(n) + ); hidePoints(); ui->swapReversed->setEnabled(false); @@ -350,7 +357,8 @@ void SketcherValidation::onOrientLockEnableClicked() tr("Orientation locking was enabled and recomputed for %1 constraints. The" " constraints have been listed in the report view (menu View → Panels →" " Report view).") - .arg(n)); + .arg(n) + ); doc->commitTransaction(); } @@ -372,7 +380,8 @@ void SketcherValidation::onOrientLockDisableClicked() " constraints have been listed in the report view (menu View → Panels →" " Report view). Note that for all future constraints, the locking still" " defaults to ON.") - .arg(n)); + .arg(n) + ); doc->commitTransaction(); } @@ -390,7 +399,8 @@ void SketcherValidation::onDelConstrExtrClicked() "useful to rescue a sketch with broken or changed links to external geometry. Delete " "the constraints?"), QMessageBox::No | QMessageBox::Yes, - QMessageBox::No); + QMessageBox::No + ); if (reply != QMessageBox::Yes) { return; } @@ -405,7 +415,8 @@ void SketcherValidation::onDelConstrExtrClicked() Gui::TranslatedNotification( *sketch, tr("Delete constraints to external geom."), - tr("All constraints that deal with external geometry were deleted.")); + tr("All constraints that deal with external geometry were deleted.") + ); } void SketcherValidation::showPoints(const std::vector& pts) @@ -473,16 +484,20 @@ void SketcherValidation::onFindDegeneratedClicked() int count = sketch->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); } diff --git a/src/Mod/Sketcher/Gui/Utils.cpp b/src/Mod/Sketcher/Gui/Utils.cpp index ccc62fd6c6..592ac74f13 100644 --- a/src/Mod/Sketcher/Gui/Utils.cpp +++ b/src/Mod/Sketcher/Gui/Utils.cpp @@ -118,7 +118,8 @@ std::tuple Sketcher::getRadiusCenterCircleArc(const Part bool SketcherGui::tryAutoRecompute(Sketcher::SketchObject* obj, bool& autoremoveredundants) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher"); + "User parameter:BaseApp/Preferences/Mod/Sketcher" + ); bool autoRecompute = hGrp->GetBool("AutoRecompute", false); bool autoRemoveRedundants = hGrp->GetBool("AutoRemoveRedundants", false); @@ -176,10 +177,10 @@ std::string SketcherGui::getStrippedPythonExceptionString(const Base::Exception& bool SketcherGui::ReleaseHandler(Gui::Document* doc) { if (doc) { - if (doc->getInEdit() - && doc->getInEdit()->isDerivedFrom()) { - SketcherGui::ViewProviderSketch* vp = - static_cast(doc->getInEdit()); + if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom()) { + SketcherGui::ViewProviderSketch* vp = static_cast( + doc->getInEdit() + ); if (static_cast(doc->getInEdit())->getSketchMode() == ViewProviderSketch::STATUS_SKETCH_UseHandler) { @@ -192,10 +193,12 @@ bool SketcherGui::ReleaseHandler(Gui::Document* doc) return false; } -void SketcherGui::getIdsFromName(const std::string& name, - const Sketcher::SketchObject* Obj, - int& GeoId, - PointPos& PosId) +void SketcherGui::getIdsFromName( + const std::string& name, + const Sketcher::SketchObject* Obj, + int& GeoId, + PointPos& PosId +) { GeoId = GeoEnum::GeoUndef; PosId = Sketcher::PointPos::none; @@ -222,8 +225,10 @@ void SketcherGui::getIdsFromName(const std::string& name, } } -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; @@ -232,8 +237,7 @@ std::vector SketcherGui::getGeoIdsOfEdgesFromNames(const Sketcher::SketchOb 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; @@ -273,9 +277,7 @@ bool SketcherGui::isPointOrSegmentFixed(const Sketcher::SketchObject* Obj, int G } } -bool SketcherGui::areBothPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, - int GeoId1, - int GeoId2) +bool SketcherGui::areBothPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, int GeoId1, int GeoId2) { const std::vector& vals = Obj->Constraints.getValues(); @@ -283,17 +285,21 @@ bool SketcherGui::areBothPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj return false; } else { - return ((checkConstraint(vals, Sketcher::Block, GeoId1, Sketcher::PointPos::none) - || GeoId1 <= Sketcher::GeoEnum::RtPnt) - && (checkConstraint(vals, Sketcher::Block, GeoId2, Sketcher::PointPos::none) - || GeoId2 <= Sketcher::GeoEnum::RtPnt)); + return ( + (checkConstraint(vals, Sketcher::Block, GeoId1, Sketcher::PointPos::none) + || GeoId1 <= Sketcher::GeoEnum::RtPnt) + && (checkConstraint(vals, Sketcher::Block, GeoId2, Sketcher::PointPos::none) + || GeoId2 <= Sketcher::GeoEnum::RtPnt) + ); } } -bool SketcherGui::areAllPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, - int GeoId1, - int GeoId2, - int GeoId3) +bool SketcherGui::areAllPointsOrSegmentsFixed( + const Sketcher::SketchObject* Obj, + int GeoId1, + int GeoId2, + int GeoId3 +) { const std::vector& vals = Obj->Constraints.getValues(); @@ -301,12 +307,14 @@ bool SketcherGui::areAllPointsOrSegmentsFixed(const Sketcher::SketchObject* Obj, return false; } else { - return ((checkConstraint(vals, Sketcher::Block, GeoId1, Sketcher::PointPos::none) - || GeoId1 <= Sketcher::GeoEnum::RtPnt) - && (checkConstraint(vals, Sketcher::Block, GeoId2, Sketcher::PointPos::none) - || GeoId2 <= Sketcher::GeoEnum::RtPnt) - && (checkConstraint(vals, Sketcher::Block, GeoId3, Sketcher::PointPos::none) - || GeoId3 <= Sketcher::GeoEnum::RtPnt)); + return ( + (checkConstraint(vals, Sketcher::Block, GeoId1, Sketcher::PointPos::none) + || GeoId1 <= Sketcher::GeoEnum::RtPnt) + && (checkConstraint(vals, Sketcher::Block, GeoId2, Sketcher::PointPos::none) + || GeoId2 <= Sketcher::GeoEnum::RtPnt) + && (checkConstraint(vals, Sketcher::Block, GeoId3, Sketcher::PointPos::none) + || GeoId3 <= Sketcher::GeoEnum::RtPnt) + ); } } @@ -334,9 +342,11 @@ bool SketcherGui::isBsplineKnot(const Sketcher::SketchObject* Obj, int GeoId) return (gf && gf->getInternalType() == Sketcher::InternalType::BSplineKnotPoint); } -bool SketcherGui::isBsplineKnotOrEndPoint(const Sketcher::SketchObject* Obj, - int GeoId, - Sketcher::PointPos PosId) +bool SketcherGui::isBsplineKnotOrEndPoint( + const Sketcher::SketchObject* Obj, + int GeoId, + Sketcher::PointPos PosId +) { // check first using geometry facade if (isBsplineKnot(Obj, GeoId)) { @@ -353,10 +363,12 @@ bool SketcherGui::isBsplineKnotOrEndPoint(const Sketcher::SketchObject* Obj, return false; } -bool SketcherGui::IsPointAlreadyOnCurve(int GeoIdCurve, - int GeoIdPoint, - Sketcher::PointPos PosIdPoint, - Sketcher::SketchObject* Obj) +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 @@ -405,10 +417,12 @@ bool SketcherGui::isBsplinePole(const Sketcher::SketchObject* Obj, int GeoId) return isBsplinePole(geom); } -bool SketcherGui::checkConstraint(const std::vector& vals, - ConstraintType type, - int geoid, - PointPos pos) +bool SketcherGui::checkConstraint( + const std::vector& vals, + ConstraintType type, + int geoid, + PointPos pos +) { for (std::vector::const_iterator itc = vals.begin(); itc != vals.end(); ++itc) { @@ -432,10 +446,12 @@ 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::Geometry* geom1, - const Part::Geometry* geom2, - Base::Vector3d& point1, - Base::Vector3d& point2) +void SketcherGui::GetCirclesMinimalDistance( + const Part::Geometry* geom1, + const Part::Geometry* geom2, + Base::Vector3d& point1, + Base::Vector3d& point2 +) { // This will throw if geom1 or geom2 are not circles or arcs auto [radius1, center1] = getRadiusCenterCircleArc(geom1); @@ -473,10 +489,10 @@ void SketcherGui::GetCirclesMinimalDistance(const Part::Geometry* geom1, void SketcherGui::ActivateHandler(Gui::Document* doc, std::unique_ptr handler) { if (doc) { - if (doc->getInEdit() - && doc->getInEdit()->isDerivedFrom()) { - SketcherGui::ViewProviderSketch* vp = - static_cast(doc->getInEdit()); + if (doc->getInEdit() && doc->getInEdit()->isDerivedFrom()) { + SketcherGui::ViewProviderSketch* vp = static_cast( + doc->getInEdit() + ); vp->purgeHandler(); vp->activateHandler(std::move(handler)); } @@ -496,8 +512,7 @@ bool SketcherGui::isSketchInEdit(Gui::Document* doc) bool SketcherGui::isCommandActive(Gui::Document* doc) { if (isSketchInEdit(doc)) { - auto mode = - static_cast(doc->getInEdit())->getSketchMode(); + auto mode = static_cast(doc->getInEdit())->getSketchMode(); if (mode == ViewProviderSketch::STATUS_NONE || mode == ViewProviderSketch::STATUS_SKETCH_UseHandler) { @@ -514,9 +529,10 @@ bool SketcherGui::isCommandNeedingConstraintActive(Gui::Document* doc) return false; } - std::vector sel = - Gui::Selection().getSelectionEx(doc->getDocument()->getName(), - Sketcher::SketchObject::getClassTypeId()); + std::vector sel = Gui::Selection().getSelectionEx( + doc->getDocument()->getName(), + Sketcher::SketchObject::getClassTypeId() + ); if (sel.size() == 1) { for (const std::string& name : sel[0].getSubNames()) { if (name.starts_with("Constraint")) { @@ -533,9 +549,10 @@ bool SketcherGui::isCommandNeedingGeometryActive(Gui::Document* doc) return false; } - std::vector sel = - Gui::Selection().getSelectionEx(doc->getDocument()->getName(), - Sketcher::SketchObject::getClassTypeId()); + std::vector sel = Gui::Selection().getSelectionEx( + doc->getDocument()->getName(), + Sketcher::SketchObject::getClassTypeId() + ); if (sel.size() == 1) { auto* Obj = static_cast(sel[0].getObject()); for (const std::string& name : sel[0].getSubNames()) { @@ -557,9 +574,10 @@ bool SketcherGui::isCommandNeedingBSplineActive(Gui::Document* doc) return false; } - std::vector sel = - Gui::Selection().getSelectionEx(doc->getDocument()->getName(), - Sketcher::SketchObject::getClassTypeId()); + std::vector sel = Gui::Selection().getSelectionEx( + doc->getDocument()->getName(), + Sketcher::SketchObject::getClassTypeId() + ); if (sel.size() == 1) { auto* Obj = static_cast(sel[0].getObject()); for (const std::string& name : sel[0].getSubNames()) { @@ -580,8 +598,9 @@ bool SketcherGui::isCommandNeedingBSplineActive(Gui::Document* doc) return false; } -SketcherGui::ViewProviderSketch* -SketcherGui::getInactiveHandlerEditModeSketchViewProvider(Gui::Document* doc) +SketcherGui::ViewProviderSketch* SketcherGui::getInactiveHandlerEditModeSketchViewProvider( + Gui::Document* doc +) { if (doc) { return dynamic_cast(doc->getInEdit()); @@ -597,9 +616,11 @@ SketcherGui::ViewProviderSketch* SketcherGui::getInactiveHandlerEditModeSketchVi return getInactiveHandlerEditModeSketchViewProvider(doc); } -void SketcherGui::removeRedundantHorizontalVertical(Sketcher::SketchObject* psketch, - std::vector& sug1, - std::vector& sug2) +void SketcherGui::removeRedundantHorizontalVertical( + Sketcher::SketchObject* psketch, + std::vector& sug1, + std::vector& sug2 +) { if (sug1.empty() || sug2.empty()) { return; @@ -618,8 +639,8 @@ void SketcherGui::removeRedundantHorizontalVertical(Sketcher::SketchObject* pske for (auto& it : sug) { if (it.Type == Sketcher::Coincident && !ext) { - const std::map coincidents = - psketch->getAllCoincidentPoints(it.GeoId, it.PosId); + 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 @@ -643,8 +664,9 @@ void SketcherGui::removeRedundantHorizontalVertical(Sketcher::SketchObject* pske } } else if (it.Type == Sketcher::PointOnObject && !axis) { - axis = ((it.GeoId == -1 && it.PosId == Sketcher::PointPos::none) - || (it.GeoId == -2 && it.PosId == Sketcher::PointPos::none)); + axis + = ((it.GeoId == -1 && it.PosId == Sketcher::PointPos::none) + || (it.GeoId == -2 && it.PosId == Sketcher::PointPos::none)); } } }; @@ -656,9 +678,10 @@ void SketcherGui::removeRedundantHorizontalVertical(Sketcher::SketchObject* pske detectredundant(sug2, secondext, secondorig, secondaxis); - rmvhorvert = ((firstext && secondext) || // coincident with external on both endpoints - (firstorig && secondaxis) || // coincident origin and point on object on other - (secondorig && firstaxis)); + rmvhorvert + = ((firstext && secondext) || // coincident with external on both endpoints + (firstorig && secondaxis) || // coincident origin and point on object on other + (secondorig && firstaxis)); if (rmvhorvert) { for (std::vector::reverse_iterator it = sug2.rbegin(); it != sug2.rend(); @@ -671,43 +694,53 @@ void SketcherGui::removeRedundantHorizontalVertical(Sketcher::SketchObject* pske } } -void SketcherGui::ConstraintToAttachment(Sketcher::GeoElementId element, - Sketcher::GeoElementId attachment, - double distance, - App::DocumentObject* obj) +void SketcherGui::ConstraintToAttachment( + Sketcher::GeoElementId element, + Sketcher::GeoElementId attachment, + double distance, + App::DocumentObject* obj +) { if (distance == 0.) { if (attachment.isCurve()) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d)) ", - element.GeoId, - element.posIdAsInt(), - attachment.GeoId); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('PointOnObject',%d,%d,%d)) ", + element.GeoId, + element.posIdAsInt(), + attachment.GeoId + ); } else { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d)) ", - element.GeoId, - element.posIdAsInt(), - attachment.GeoId, - attachment.posIdAsInt()); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Coincident',%d,%d,%d,%d)) ", + element.GeoId, + element.posIdAsInt(), + attachment.GeoId, + attachment.posIdAsInt() + ); } } else { if (attachment == Sketcher::GeoElementId::VAxis) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%f)) ", - element.GeoId, - element.posIdAsInt(), - distance); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('DistanceX',%d,%d,%f)) ", + element.GeoId, + element.posIdAsInt(), + distance + ); } else if (attachment == Sketcher::GeoElementId::HAxis) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%f)) ", - element.GeoId, - element.posIdAsInt(), - distance); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('DistanceY',%d,%d,%f)) ", + element.GeoId, + element.posIdAsInt(), + distance + ); } } } @@ -728,41 +761,41 @@ void SketcherGui::ConstraintLineByAngle(int geoId, double angle, App::DocumentOb Gui::cmdAppObjectArgs(obj, "addConstraint(Sketcher.Constraint('Vertical',%d)) ", geoId); } else { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%d,%f)) ", - Sketcher::GeoEnum::HAxis, - geoId, - angle); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%f)) ", + Sketcher::GeoEnum::HAxis, + geoId, + angle + ); } } -void SketcherGui::Constraint2LinesByAngle(int geoId1, - int geoId2, - double angle, - App::DocumentObject* obj) +void SketcherGui::Constraint2LinesByAngle(int geoId1, int geoId2, double angle, App::DocumentObject* obj) { using std::numbers::pi; double angleModPi = std::fmod(angle, pi); double angleModHalfPi = std::fmod(angle, pi / 2); if (fabs(angleModPi) < Precision::Confusion()) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Parallel',%d,%d)) ", - geoId1, - geoId2); + Gui::cmdAppObjectArgs(obj, "addConstraint(Sketcher.Constraint('Parallel',%d,%d)) ", geoId1, geoId2); } else if (fabs(angleModHalfPi) < Precision::Confusion()) { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d)) ", - geoId1, - geoId2); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Perpendicular',%d,%d)) ", + geoId1, + geoId2 + ); } else { - Gui::cmdAppObjectArgs(obj, - "addConstraint(Sketcher.Constraint('Angle',%d,%d,%f)) ", - geoId1, - geoId2, - angle); + Gui::cmdAppObjectArgs( + obj, + "addConstraint(Sketcher.Constraint('Angle',%d,%d,%f)) ", + geoId1, + geoId2, + angle + ); } } @@ -821,8 +854,8 @@ std::string SketcherGui::lengthToDisplayFormat(double value, int digits) std::string unitPart = " " + unitString; // get the numeric part of the user string - QRegularExpression rxNoUnits( - QStringLiteral("(.*) \\D*$")); // text before space + any non digits at end of string + QRegularExpression rxNoUnits(QStringLiteral("(.*) \\D*$")); // text before space + any non + // digits at end of string QRegularExpressionMatch match = rxNoUnits.match(QString::fromStdString(userString)); if (!match.hasMatch()) { // no units in userString? @@ -887,8 +920,9 @@ std::string SketcherGui::angleToDisplayFormat(double value, int digits) auto decimalSep = QLocale().decimalPoint(); // get the numeric part of the user string - QRegularExpression rxNoUnits(QStringLiteral("(\\d*\\%1?\\d*)(\\D*)$") - .arg(decimalSep)); // number + non digits at end of string + QRegularExpression rxNoUnits( + QStringLiteral("(\\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? @@ -915,9 +949,11 @@ std::string SketcherGui::angleToDisplayFormat(double value, int digits) } -bool SketcherGui::areCollinear(const Base::Vector2d& p1, - const Base::Vector2d& p2, - const Base::Vector2d& p3) +bool SketcherGui::areCollinear( + const Base::Vector2d& p1, + const Base::Vector2d& p2, + const Base::Vector2d& p3 +) { Base::Vector2d u = p2 - p1; Base::Vector2d v = p3 - p2; diff --git a/src/Mod/Sketcher/Gui/Utils.h b/src/Mod/Sketcher/Gui/Utils.h index f41c23387b..f07f8e3caa 100644 --- a/src/Mod/Sketcher/Gui/Utils.h +++ b/src/Mod/Sketcher/Gui/Utils.h @@ -101,14 +101,18 @@ 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); @@ -116,10 +120,7 @@ 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); @@ -131,14 +132,14 @@ bool isSimpleVertex(const Sketcher::SketchObject* Obj, int GeoId, Sketcher::Poin 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); +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); @@ -146,10 +147,12 @@ 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& vals, - Sketcher::ConstraintType type, - int geoid, - Sketcher::PointPos pos); +bool checkConstraint( + const std::vector& vals, + Sketcher::ConstraintType type, + int geoid, + Sketcher::PointPos pos +); inline bool isVertex(int GeoId, Sketcher::PointPos PosId) { @@ -184,10 +187,12 @@ inline const char* constructionModeAsBooleanText() double GetPointAngle(const Base::Vector2d& p1, const Base::Vector2d& p2); // Set the two points on circles at minimal distance -void GetCirclesMinimalDistance(const Part::Geometry* geom1, - const Part::Geometry* geom2, - Base::Vector3d& point1, - Base::Vector3d& point2); +void GetCirclesMinimalDistance( + const Part::Geometry* geom1, + const Part::Geometry* geom2, + Base::Vector3d& point1, + Base::Vector3d& point2 +); void ActivateHandler(Gui::Document* doc, std::unique_ptr handler); @@ -205,14 +210,18 @@ SketcherGui::ViewProviderSketch* getInactiveHandlerEditModeSketchViewProvider(Gu SketcherGui::ViewProviderSketch* getInactiveHandlerEditModeSketchViewProvider(); -void removeRedundantHorizontalVertical(Sketcher::SketchObject* psketch, - std::vector& sug1, - std::vector& sug2); +void removeRedundantHorizontalVertical( + Sketcher::SketchObject* psketch, + 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 +); void ConstraintLineByAngle(int geoId, double angle, App::DocumentObject* obj); void Constraint2LinesByAngle(int geoId1, int geoId2, double angle, App::DocumentObject* obj); @@ -258,9 +267,7 @@ 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; } @@ -276,11 +283,9 @@ 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()); + auto vpext = std::static_pointer_cast( + geom->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock() + ); layerId = vpext->getVisualLayerId(); } @@ -301,8 +306,8 @@ void setSafeGeomLayerId(T geom, int layerindex) } auto vpext = std::static_pointer_cast( - geom->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()) - .lock()); + geom->getExtension(SketcherGui::ViewProviderSketchGeometryExtension::getClassTypeId()).lock() + ); vpext->setVisualLayerId(layerindex); } diff --git a/src/Mod/Sketcher/Gui/ViewProviderPython.cpp b/src/Mod/Sketcher/Gui/ViewProviderPython.cpp index e6e12e6449..91fae3e9cf 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderPython.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderPython.cpp @@ -64,7 +64,8 @@ void ViewProviderCustom::updateData(const App::Property* prop) if (view->isDerivedFrom()) { static_cast(view)->attach(this->getObject()); static_cast(view)->setDisplayMode( - this->getActiveDisplayMode().c_str()); + this->getActiveDisplayMode().c_str() + ); } propView[prop] = view; view->updateData(prop); diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp index 4c114f0780..11fb4321cc 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp @@ -3254,10 +3254,12 @@ bool ViewProviderSketch::getElementPicked(const SoPickedPoint* pp, std::string& return ViewProvider2DObject::getElementPicked(pp, subname); } -bool ViewProviderSketch::getDetailPath(const char* subname, - SoFullPath* pPath, - bool append, - SoDetail*& det) const +bool ViewProviderSketch::getDetailPath( + const char* subname, + SoFullPath* pPath, + bool append, + SoDetail*& det +) const { const auto getLastPartOfName = [](const char* subname) -> const char* { const char* realName = strrchr(subname, '.'); diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.h b/src/Mod/Sketcher/Gui/ViewProviderSketch.h index a57f805b6e..d62997a884 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.h @@ -197,17 +197,18 @@ private: void updateFromParameter(const char* property); private: - void - updateBoolProperty(const std::string& string, App::Property* property, bool defaultvalue); + 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); + void updateColorProperty( + const std::string& string, + App::Property* property, + float r, + float g, + float b + ); void updateShapeAppearanceProperty(const std::string& string, App::Property* property); @@ -215,14 +216,16 @@ private: 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*>> + std::map< + std::string, + std::tuple, App::Property*>> parameterMap; }; @@ -467,13 +470,11 @@ private: 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; - int stdCountSegments = - 50; // preferences controlled default geometry sampling for selection + int stdCountSegments = 50; // preferences controlled default geometry sampling for selection }; /** @brief Private struct grouping ViewProvider and RenderManager node, to be used as SoNode @@ -674,13 +675,17 @@ public: /// 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; //@} void deleteSelected(); @@ -744,9 +749,11 @@ protected: /// Auxiliary function to generate messages about conflicting, redundant and malformed /// constraints - static QString appendConstraintMsg(const QString& singularmsg, - const QString& pluralmsg, - const std::vector& vector); + static QString appendConstraintMsg( + const QString& singularmsg, + const QString& pluralmsg, + const std::vector& vector + ); //@} /** @name manage updates during undo/redo operations */ @@ -768,22 +775,19 @@ protected: void finishRestoring() override; bool getElementPicked(const SoPickedPoint* pp, std::string& subname) const override; - bool getDetailPath(const char* subname, - SoFullPath* pPath, - bool append, - SoDetail*& det) const override; + bool getDetailPath(const char* subname, SoFullPath* pPath, bool append, SoDetail*& det) const override; private: /// function to handle OCCT BSpline weight calculation singularities and representation void scaleBSplinePoleCirclesAndUpdateSolverAndSketchObjectGeometry( GeoListFacade& geolist, - bool geometrywithmemoryallocation); + 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; @@ -815,9 +819,11 @@ private: /** @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); @@ -827,19 +833,23 @@ private: 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); - void preselectToSelection(const std::stringstream& ss, - boost::scoped_ptr& pp, - bool toggle); + void preselectToSelection( + const std::stringstream& ss, + boost::scoped_ptr& pp, + bool toggle + ); //@} /** @name miscelanea utilities */ //@{ /// moves a selected constraint void moveConstraint(int constNum, const Base::Vector2d& toPos, OffsetMode offset = NoOffset); - void moveConstraint(Sketcher::Constraint*, - int constNum, - const Base::Vector2d& toPos, - OffsetMode offset = NoOffset); + void moveConstraint( + Sketcher::Constraint*, + int constNum, + const Base::Vector2d& toPos, + OffsetMode offset = NoOffset + ); void moveAngleConstraint(Sketcher::Constraint*, int constNum, const Base::Vector2d& toPos); /// returns whether the sketch is in edit mode. @@ -923,8 +933,10 @@ private: 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); diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h b/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h index 30f8b77bc7..85bf6bc696 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchCoinAttorney.h @@ -83,8 +83,7 @@ class ViewProviderSketchCoinAttorney { private: static inline bool constraintHasExpression(const ViewProviderSketch& vp, int constrid); - static inline const std::vector - getConstraints(const ViewProviderSketch& vp); + 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); @@ -92,8 +91,7 @@ private: 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 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); @@ -118,8 +116,10 @@ private: 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; @@ -128,14 +128,17 @@ 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(); } @@ -150,8 +153,7 @@ const GeoListFacade ViewProviderSketchCoinAttorney::getGeoListFacade(const ViewP return vp.getGeoListFacade(); } -inline Base::Placement -ViewProviderSketchCoinAttorney::getEditingPlacement(const ViewProviderSketch& vp) +inline Base::Placement ViewProviderSketchCoinAttorney::getEditingPlacement(const ViewProviderSketch& vp) { return vp.getEditingPlacement(); } @@ -161,8 +163,9 @@ inline bool ViewProviderSketchCoinAttorney::isShownVirtualSpace(const ViewProvid 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(); } @@ -172,8 +175,10 @@ inline float ViewProviderSketchCoinAttorney::getScaleFactor(const ViewProviderSk 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); } @@ -183,15 +188,16 @@ inline QFont ViewProviderSketchCoinAttorney::getApplicationFont(const ViewProvid 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); } -inline int -ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(const ViewProviderSketch& vp) +inline int ViewProviderSketchCoinAttorney::defaultApplicationFontSizePixels(const ViewProviderSketch& vp) { return vp.defaultFontSizePixels(); } @@ -221,8 +227,7 @@ inline bool ViewProviderSketchCoinAttorney::isSketchFullyConstrained(const ViewP return vp.isSketchFullyConstrained(); } -inline bool -ViewProviderSketchCoinAttorney::haveConstraintsInvalidGeometry(const ViewProviderSketch& vp) +inline bool ViewProviderSketchCoinAttorney::haveConstraintsInvalidGeometry(const ViewProviderSketch& vp) { return vp.haveConstraintsInvalidGeometry(); } @@ -232,8 +237,7 @@ inline void ViewProviderSketchCoinAttorney::addNodeToRoot(ViewProviderSketch& vp vp.addNodeToRoot(node); } -inline void ViewProviderSketchCoinAttorney::removeNodeFromRoot(ViewProviderSketch& vp, - SoSeparator* node) +inline void ViewProviderSketchCoinAttorney::removeNodeFromRoot(ViewProviderSketch& vp, SoSeparator* node) { vp.removeNodeFromRoot(node); } @@ -253,33 +257,36 @@ inline int ViewProviderSketchCoinAttorney::getPreselectCross(const ViewProviderS 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) + std::function&& operation +) { vp.executeOnSelectionPointSet(std::move(operation)); } diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp index 37a941afbb..efc768a1c4 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp @@ -33,8 +33,7 @@ using namespace SketcherGui; //---------- Geometry Extension -TYPESYSTEM_SOURCE(SketcherGui::ViewProviderSketchGeometryExtension, - Part::GeometryPersistenceExtension) +TYPESYSTEM_SOURCE(SketcherGui::ViewProviderSketchGeometryExtension, Part::GeometryPersistenceExtension) ViewProviderSketchGeometryExtension::ViewProviderSketchGeometryExtension() @@ -45,8 +44,8 @@ ViewProviderSketchGeometryExtension::ViewProviderSketchGeometryExtension() void ViewProviderSketchGeometryExtension::copyAttributes(Part::GeometryExtension* cpy) const { Part::GeometryExtension::copyAttributes(cpy); - static_cast(cpy)->RepresentationFactor = - this->RepresentationFactor; + static_cast(cpy)->RepresentationFactor + = this->RepresentationFactor; static_cast(cpy)->VisualLayerId = this->VisualLayerId; } @@ -78,6 +77,5 @@ void ViewProviderSketchGeometryExtension::saveAttributes(Base::Writer& writer) c 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 000b508318..edd4c53034 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h @@ -30,8 +30,7 @@ namespace SketcherGui { -class SketcherGuiExport ViewProviderSketchGeometryExtension - : public Part::GeometryPersistenceExtension +class SketcherGuiExport ViewProviderSketchGeometryExtension: public Part::GeometryPersistenceExtension { TYPESYSTEM_HEADER_WITH_OVERRIDE(); diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp index 6af26f509e..114c00c2fd 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtensionPyImp.cpp @@ -38,9 +38,11 @@ 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); @@ -62,10 +64,12 @@ 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; } @@ -84,8 +88,7 @@ PyObject* ViewProviderSketchGeometryExtensionPy::getCustomAttributes(const char* 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 dd621f5485..a5686d96cd 100644 --- a/src/Mod/Sketcher/Gui/VisualLayer.cpp +++ b/src/Mod/Sketcher/Gui/VisualLayer.cpp @@ -69,8 +69,7 @@ void VisualLayer::setVisible(bool show) void VisualLayer::Save(Base::Writer& writer) const { writer.Stream() << writer.ind() << "" << std::endl; } diff --git a/src/Mod/Sketcher/Gui/VisualLayer.h b/src/Mod/Sketcher/Gui/VisualLayer.h index eb8683d68e..d49c21752b 100644 --- a/src/Mod/Sketcher/Gui/VisualLayer.h +++ b/src/Mod/Sketcher/Gui/VisualLayer.h @@ -43,9 +43,7 @@ namespace SketcherGui 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; diff --git a/src/Mod/Sketcher/Gui/Workbench.cpp b/src/Mod/Sketcher/Gui/Workbench.cpp index 24aecf0e25..cbc22bc6d4 100644 --- a/src/Mod/Sketcher/Gui/Workbench.cpp +++ b/src/Mod/Sketcher/Gui/Workbench.cpp @@ -110,33 +110,33 @@ Gui::ToolBarItem* Workbench::setupToolBars() const sketcher->setCommand("Sketcher"); addSketcherWorkbenchSketchActions(*sketcher); - Gui::ToolBarItem* sketcherEditMode = - new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); + Gui::ToolBarItem* sketcherEditMode + = new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); sketcherEditMode->setCommand("Edit Mode"); addSketcherWorkbenchSketchEditModeActions(*sketcherEditMode); - Gui::ToolBarItem* geom = - new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); + Gui::ToolBarItem* geom + = new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); geom->setCommand("Geometries"); addSketcherWorkbenchGeometries(*geom); - Gui::ToolBarItem* cons = - new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); + Gui::ToolBarItem* cons + = new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); cons->setCommand("Constraints"); addSketcherWorkbenchConstraints(*cons); - Gui::ToolBarItem* consaccel = - new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); + Gui::ToolBarItem* consaccel + = new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); consaccel->setCommand("Sketcher Tools"); addSketcherWorkbenchTools(*consaccel); - Gui::ToolBarItem* bspline = - new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); + Gui::ToolBarItem* bspline + = new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); bspline->setCommand("B-Spline Tools"); addSketcherWorkbenchBSplines(*bspline); - Gui::ToolBarItem* visual = - new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); + Gui::ToolBarItem* visual + = new Gui::ToolBarItem(root, Gui::ToolBarItem::DefaultVisibility::Unavailable); visual->setCommand("Visual Helpers"); addSketcherWorkbenchVisual(*visual); @@ -155,13 +155,15 @@ namespace { inline const QStringList editModeToolbarNames() { - return QStringList {QStringLiteral("Edit Mode"), - QStringLiteral("Geometries"), - QStringLiteral("Constraints"), - QStringLiteral("Sketcher Tools"), - QStringLiteral("B-Spline Tools"), - QStringLiteral("Visual Helpers"), - QStringLiteral("Sketcher Edit Tools")}; + return QStringList { + QStringLiteral("Edit Mode"), + QStringLiteral("Geometries"), + QStringLiteral("Constraints"), + QStringLiteral("Sketcher Tools"), + QStringLiteral("B-Spline Tools"), + QStringLiteral("Visual Helpers"), + QStringLiteral("Sketcher Edit Tools") + }; } inline const QStringList nonEditModeToolbarNames() @@ -188,11 +190,15 @@ void Workbench::activated() */ Gui::Document* doc = Gui::Application::Instance->activeDocument(); if (isSketchInEdit(doc)) { - Gui::ToolBarManager::getInstance()->setState(editModeToolbarNames(), - Gui::ToolBarManager::State::ForceAvailable); + Gui::ToolBarManager::getInstance()->setState( + editModeToolbarNames(), + Gui::ToolBarManager::State::ForceAvailable + ); - Gui::ToolBarManager::getInstance()->setState(nonEditModeToolbarNames(), - Gui::ToolBarManager::State::ForceHidden); + Gui::ToolBarManager::getInstance()->setState( + nonEditModeToolbarNames(), + Gui::ToolBarManager::State::ForceHidden + ); } } @@ -201,13 +207,19 @@ void Workbench::enterEditMode() /* Ensure the state left by the non-edit mode toolbars is saved (in case of changing to edit * mode) without changing workbench */ - Gui::ToolBarManager::getInstance()->setState(nonEditModeToolbarNames(), - Gui::ToolBarManager::State::SaveState); + Gui::ToolBarManager::getInstance()->setState( + nonEditModeToolbarNames(), + Gui::ToolBarManager::State::SaveState + ); - Gui::ToolBarManager::getInstance()->setState(editModeToolbarNames(), - Gui::ToolBarManager::State::ForceAvailable); - Gui::ToolBarManager::getInstance()->setState(nonEditModeToolbarNames(), - Gui::ToolBarManager::State::ForceHidden); + Gui::ToolBarManager::getInstance()->setState( + editModeToolbarNames(), + Gui::ToolBarManager::State::ForceAvailable + ); + Gui::ToolBarManager::getInstance()->setState( + nonEditModeToolbarNames(), + Gui::ToolBarManager::State::ForceHidden + ); } void Workbench::leaveEditMode() @@ -222,14 +234,20 @@ void Workbench::leaveEditMode() auto* workbench = Gui::WorkbenchManager::instance()->active(); if (workbench->name() == "SketcherWorkbench") { - Gui::ToolBarManager::getInstance()->setState(editModeToolbarNames(), - Gui::ToolBarManager::State::SaveState); + Gui::ToolBarManager::getInstance()->setState( + editModeToolbarNames(), + Gui::ToolBarManager::State::SaveState + ); } - Gui::ToolBarManager::getInstance()->setState(editModeToolbarNames(), - Gui::ToolBarManager::State::RestoreDefault); - Gui::ToolBarManager::getInstance()->setState(nonEditModeToolbarNames(), - Gui::ToolBarManager::State::RestoreDefault); + Gui::ToolBarManager::getInstance()->setState( + editModeToolbarNames(), + Gui::ToolBarManager::State::RestoreDefault + ); + Gui::ToolBarManager::getInstance()->setState( + nonEditModeToolbarNames(), + Gui::ToolBarManager::State::RestoreDefault + ); } namespace SketcherGui @@ -297,7 +315,8 @@ template<> inline void SketcherAddWorkspaceLines(Gui::ToolBarItem& geom) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Commands"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Commands" + ); if (hGrp->GetBool("UnifiedLineCommands", false)) { geom << "Sketcher_CompLine"; @@ -447,7 +466,8 @@ template<> inline void SketcherAddWorkbenchConstraints(Gui::MenuItem& cons) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Constraints"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Constraints" + ); if (hGrp->GetBool("UnifiedCoincident", true)) { cons << "Sketcher_ConstrainCoincidentUnified"; @@ -485,7 +505,8 @@ template<> inline void SketcherAddWorkbenchConstraints(Gui::ToolBarItem& cons) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/dimensioning" + ); if (hGrp->GetBool("SingleDimensioningTool", true)) { if (!hGrp->GetBool("SeparatedDimensioningTools", false)) { @@ -508,7 +529,8 @@ inline void SketcherAddWorkbenchConstraints(Gui::ToolBarItem& cons << "Separator"; hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Sketcher/Constraints"); + "User parameter:BaseApp/Preferences/Mod/Sketcher/Constraints" + ); if (hGrp->GetBool("UnifiedCoincident", true)) { cons << "Sketcher_ConstrainCoincidentUnified"; diff --git a/src/Mod/Sketcher/SketcherGlobal.h b/src/Mod/Sketcher/SketcherGlobal.h index ac7544489b..401f49a566 100644 --- a/src/Mod/Sketcher/SketcherGlobal.h +++ b/src/Mod/Sketcher/SketcherGlobal.h @@ -23,25 +23,25 @@ #include #ifndef SKETCHER_GLOBAL_H -#define SKETCHER_GLOBAL_H +# define SKETCHER_GLOBAL_H // Sketcher -#ifndef SketcherExport -#ifdef Sketcher_EXPORTS -#define SketcherExport FREECAD_DECL_EXPORT -#else -#define SketcherExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef SketcherExport +# ifdef Sketcher_EXPORTS +# define SketcherExport FREECAD_DECL_EXPORT +# else +# define SketcherExport FREECAD_DECL_IMPORT +# endif +# endif // SketcherGui -#ifndef SketcherGuiExport -#ifdef SketcherGui_EXPORTS -#define SketcherGuiExport FREECAD_DECL_EXPORT -#else -#define SketcherGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef SketcherGuiExport +# ifdef SketcherGui_EXPORTS +# define SketcherGuiExport FREECAD_DECL_EXPORT +# else +# define SketcherGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // SKETCHER_GLOBAL_H diff --git a/src/Mod/Spreadsheet/App/Cell.cpp b/src/Mod/Spreadsheet/App/Cell.cpp index 15f5a325d0..a800a2194f 100644 --- a/src/Mod/Spreadsheet/App/Cell.cpp +++ b/src/Mod/Spreadsheet/App/Cell.cpp @@ -44,10 +44,10 @@ FC_LOG_LEVEL_INIT("Spreadsheet", true, true) #ifdef _MSC_VER -#define __func__ __FUNCTION__ -#ifdef PropertySheet -#undef PropertySheet // Microsoft's #define conflicts with the use below -#endif +# define __func__ __FUNCTION__ +# ifdef PropertySheet +# undef PropertySheet // Microsoft's #define conflicts with the use below +# endif #endif using namespace App; @@ -190,8 +190,9 @@ void Cell::setExpression(App::ExpressionPtr&& expr) if (expr && !expr->comment.empty()) { if (!boost::starts_with(expr->comment, "sheet()->getFullName() << '.' - << address.toString()); + FC_WARN( + "Unknown style of cell " << owner->sheet()->getFullName() << '.' << address.toString() + ); } else { try { @@ -202,9 +203,10 @@ void Cell::setExpression(App::ExpressionPtr&& expr) } catch (Base::Exception& e) { e.reportException(); - FC_ERR("Failed to restore style of cell " << owner->sheet()->getFullName() << '.' - << address.toString() << ": " - << e.what()); + FC_ERR( + "Failed to restore style of cell " << owner->sheet()->getFullName() << '.' + << address.toString() << ": " << e.what() + ); } } expr->comment.clear(); @@ -344,35 +346,35 @@ void Cell::setContent(const char* value) // 1/2, 1m/2, 1/2s, 1m/2s, 1/m // check for numbers in (de)nominator - const bool isNumberNom = - freecad_cast(fraction->getLeft()); - const bool isNumberDenom = - freecad_cast(fraction->getRight()); + const bool isNumberNom = freecad_cast( + fraction->getLeft() + ); + const bool isNumberDenom = freecad_cast( + fraction->getRight() + ); // check for numbers with units in (de)nominator - const auto opNom = - freecad_cast(fraction->getLeft()); - const auto opDenom = - freecad_cast(fraction->getRight()); - const bool isQuantityNom = - opNom && opNom->getOperator() == OperatorExpression::UNIT; - const bool isQuantityDenom = - opDenom && opDenom->getOperator() == OperatorExpression::UNIT; + const auto opNom = freecad_cast(fraction->getLeft()); + const auto opDenom = freecad_cast( + fraction->getRight() + ); + const bool isQuantityNom = opNom + && opNom->getOperator() == OperatorExpression::UNIT; + const bool isQuantityDenom = opDenom + && opDenom->getOperator() == OperatorExpression::UNIT; // check for units in denomainator const auto uDenom = freecad_cast(fraction->getRight()); const bool isUnitDenom = uDenom && uDenom->is(); const bool isNomValid = isNumberNom || isQuantityNom; - const bool isDenomValid = - isNumberDenom || isQuantityDenom || isUnitDenom; + const bool isDenomValid = isNumberDenom || isQuantityDenom || isUnitDenom; if (isNomValid && isDenomValid) { newExpr = std::move(parsedExpr); } } } - else if (const auto number = - freecad_cast(parsedExpr.get())) { + else if (const auto number = freecad_cast(parsedExpr.get())) { // NumbersExpressions can accept more than can be parsed with strtod. // Example: 12.34 and 12,34 are both valid NumberExpressions newExpr = std::move(parsedExpr); @@ -411,8 +413,8 @@ void Cell::setAlignment(int _alignment) alignment = _alignment; setUsed( ALIGNMENT_SET, - alignment - != (ALIGNMENT_HIMPLIED | ALIGNMENT_LEFT | ALIGNMENT_VIMPLIED | ALIGNMENT_VCENTER)); + alignment != (ALIGNMENT_HIMPLIED | ALIGNMENT_LEFT | ALIGNMENT_VIMPLIED | ALIGNMENT_VCENTER) + ); setDirty(); signaller.tryInvoke(); } @@ -528,7 +530,8 @@ void Cell::setDisplayUnit(const std::string& unit) DisplayUnit newDisplayUnit; if (!unit.empty()) { std::shared_ptr e( - ExpressionParser::parseUnit(owner->sheet(), unit.c_str())); + ExpressionParser::parseUnit(owner->sheet(), unit.c_str()) + ); if (!e) { throw Base::UnitsMismatchError("Invalid unit"); @@ -728,12 +731,14 @@ void Cell::moveAbsolute(CellAddress newAddress) void Cell::restore(Base::XMLReader& reader, bool checkAlias) { - const char* style = - reader.hasAttribute("style") ? reader.getAttribute("style") : nullptr; - const char* alignment = - reader.hasAttribute("alignment") ? reader.getAttribute("alignment") : nullptr; - const char* content = - reader.hasAttribute("content") ? reader.getAttribute("content") : ""; + const char* style = reader.hasAttribute("style") ? reader.getAttribute("style") + : nullptr; + const char* alignment = reader.hasAttribute("alignment") + ? reader.getAttribute("alignment") + : nullptr; + const char* content = reader.hasAttribute("content") + ? reader.getAttribute("content") + : ""; const char* foregroundColor = reader.hasAttribute("foregroundColor") ? reader.getAttribute("foregroundColor") : nullptr; @@ -743,12 +748,14 @@ void Cell::restore(Base::XMLReader& reader, bool checkAlias) const char* displayUnit = reader.hasAttribute("displayUnit") ? reader.getAttribute("displayUnit") : nullptr; - const char* alias = - reader.hasAttribute("alias") ? reader.getAttribute("alias") : nullptr; - const char* rowSpan = - reader.hasAttribute("rowSpan") ? reader.getAttribute("rowSpan") : nullptr; - const char* colSpan = - reader.hasAttribute("colSpan") ? reader.getAttribute("colSpan") : nullptr; + const char* alias = reader.hasAttribute("alias") ? reader.getAttribute("alias") + : nullptr; + const char* rowSpan = reader.hasAttribute("rowSpan") + ? reader.getAttribute("rowSpan") + : nullptr; + const char* colSpan = reader.hasAttribute("colSpan") + ? reader.getAttribute("colSpan") + : nullptr; // Don't trigger multiple updates below; wait until everything is loaded by calling unfreeze() // below. @@ -765,8 +772,7 @@ void Cell::restore(Base::XMLReader& reader, bool checkAlias) std::string line = std::string(style); tokenizer> tok(line, e); - for (tokenizer>::iterator i = tok.begin(); i != tok.end(); - ++i) { + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); ++i) { styleSet.insert(*i); } setStyle(styleSet); @@ -779,8 +785,7 @@ void Cell::restore(Base::XMLReader& reader, bool checkAlias) std::string line = std::string(alignment); tokenizer> tok(line, e); - for (tokenizer>::iterator i = tok.begin(); i != tok.end(); - ++i) { + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); ++i) { alignmentCode = decodeAlignment(*i, alignmentCode); } @@ -1111,8 +1116,8 @@ std::string Cell::getFormattedQuantity() qFormatted = QLocale().toString(rawVal, 'f', Base::UnitsApi::getDecimals()); if (hasDisplayUnit) { if (computedUnit == Unit::One || computedUnit == du.unit) { - QString number = - QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); + QString number + = QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); qFormatted = number + QString::fromStdString(" " + displayUnit.stringRep); } } @@ -1124,8 +1129,7 @@ std::string Cell::getFormattedQuantity() double duScale = du.scaler; qFormatted = QLocale().toString(rawVal, 'f', Base::UnitsApi::getDecimals()); if (hasDisplayUnit) { - QString number = - QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); + QString number = QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); qFormatted = number + QString::fromStdString(" " + displayUnit.stringRep); } } @@ -1137,8 +1141,7 @@ std::string Cell::getFormattedQuantity() int iRawVal = std::round(rawVal); qFormatted = QLocale().toString(iRawVal); if (hasDisplayUnit) { - QString number = - QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); + QString number = QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); qFormatted = number + QString::fromStdString(" " + displayUnit.stringRep); } } diff --git a/src/Mod/Spreadsheet/App/Cell.h b/src/Mod/Spreadsheet/App/Cell.h index 05d082e9d4..e4fad0afa5 100644 --- a/src/Mod/Spreadsheet/App/Cell.h +++ b/src/Mod/Spreadsheet/App/Cell.h @@ -113,8 +113,7 @@ public: bool hasException() const { - return isUsed(EXCEPTION_SET) || isUsed(PARSE_EXCEPTION_SET) - || isUsed(RESOLVE_EXCEPTION_SET); + return isUsed(EXCEPTION_SET) || isUsed(PARSE_EXCEPTION_SET) || isUsed(RESOLVE_EXCEPTION_SET); } void moveAbsolute(App::CellAddress newAddress); diff --git a/src/Mod/Spreadsheet/App/DisplayUnit.h b/src/Mod/Spreadsheet/App/DisplayUnit.h index 9440ee7d22..d0ffb6959d 100644 --- a/src/Mod/Spreadsheet/App/DisplayUnit.h +++ b/src/Mod/Spreadsheet/App/DisplayUnit.h @@ -38,9 +38,11 @@ public: Base::Unit unit; double scaler; - explicit DisplayUnit(const std::string _stringRep = "", - const Base::Unit _unit = Base::Unit(), - double _scaler = 0.0) + explicit DisplayUnit( + const std::string _stringRep = "", + const Base::Unit _unit = Base::Unit(), + double _scaler = 0.0 + ) : stringRep(std::move(_stringRep)) , unit(_unit) , scaler(_scaler) diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp b/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp index 85e8043efe..34ba6ee3cd 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp @@ -133,10 +133,10 @@ void PropertyColumnWidths::Restore(Base::XMLReader& reader) Cnt = reader.hasAttribute("Count") ? reader.getAttribute("Count") : 0; for (int i = 0; i < Cnt; i++) { reader.readElement("Column"); - const char* name = - reader.hasAttribute("name") ? reader.getAttribute("name") : nullptr; - const char* width = - reader.hasAttribute("width") ? reader.getAttribute("width") : nullptr; + const char* name = reader.hasAttribute("name") ? reader.getAttribute("name") + : nullptr; + const char* width = reader.hasAttribute("width") ? reader.getAttribute("width") + : nullptr; try { if (name && width) { diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp index cdf389b1f0..fbd19a9505 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp @@ -39,8 +39,7 @@ std::string PropertyColumnWidthsPy::representation() const return {""}; } -PyObject* -PropertyColumnWidthsPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* PropertyColumnWidthsPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper { // create a new instance of PropertyColumnWidthsPy and the Twin object return new PropertyColumnWidthsPy(new PropertyColumnWidths); diff --git a/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp b/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp index 02e3d03a31..6661591281 100644 --- a/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp +++ b/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp @@ -126,10 +126,11 @@ void PropertyRowHeights::Restore(Base::XMLReader& reader) Cnt = reader.hasAttribute("Count") ? reader.getAttribute("Count") : 0; for (int i = 0; i < Cnt; i++) { reader.readElement("Row"); - const char* name = - reader.hasAttribute("name") ? reader.getAttribute("name") : nullptr; - const char* height = - reader.hasAttribute("height") ? reader.getAttribute("height") : nullptr; + const char* name = reader.hasAttribute("name") ? reader.getAttribute("name") + : nullptr; + const char* height = reader.hasAttribute("height") + ? reader.getAttribute("height") + : nullptr; try { if (name && height) { diff --git a/src/Mod/Spreadsheet/App/PropertySheet.cpp b/src/Mod/Spreadsheet/App/PropertySheet.cpp index c92ab35ba0..0517bef125 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.cpp +++ b/src/Mod/Spreadsheet/App/PropertySheet.cpp @@ -163,8 +163,7 @@ bool PropertySheet::isValidAlias(const std::string& candidate) } /* Check to make sure it doesn't clash with a reserved name */ - if (ExpressionParser::isTokenAUnit(candidate) - || ExpressionParser::isTokenAConstant(candidate)) { + if (ExpressionParser::isTokenAUnit(candidate) || ExpressionParser::isTokenAConstant(candidate)) { return false; } @@ -341,8 +340,10 @@ void PropertySheet::Paste(const Property& from) *cell = *(ifrom->second); // Exists; assign cell directly } else { - cell = new Cell(this, - *(ifrom->second)); // Doesn't exist, copy using Cell's copy constructor + cell = new Cell( + this, + *(ifrom->second) + ); // Doesn't exist, copy using Cell's copy constructor if (cell->getSpans(rows, cols)) { spanChanges.push_back(ifrom->first); } @@ -431,8 +432,9 @@ void PropertySheet::Restore(Base::XMLReader& reader) for (int i = 0; i < Cnt; i++) { reader.readElement("Cell"); - const char* strAddress = - reader.hasAttribute("address") ? reader.getAttribute("address") : ""; + const char* strAddress = reader.hasAttribute("address") + ? reader.getAttribute("address") + : ""; try { CellAddress address(strAddress); @@ -442,8 +444,7 @@ void PropertySheet::Restore(Base::XMLReader& reader) int rows, cols; if (cell->getSpans(rows, cols) && (rows > 1 || cols > 1)) { - mergeCells(address, - CellAddress(address.row() + rows - 1, address.col() + cols - 1)); + mergeCells(address, CellAddress(address.row() + rows - 1, address.col() + cols - 1)); } } catch (const Base::Exception&) { @@ -541,8 +542,10 @@ void PropertySheet::pasteCells(XMLReader& reader, Range dstRange) while (src != *range) { for (int r = 0; r < rcount; ++r) { for (int c = 0; c < ccount; ++c) { - CellAddress dst(range.row() + roffset + r * range.rowCount(), - range.column() + coffset + c * range.colCount()); + CellAddress dst( + range.row() + roffset + r * range.rowCount(), + range.column() + coffset + c * range.colCount() + ); if (!dst.isValid()) { continue; } @@ -555,8 +558,10 @@ void PropertySheet::pasteCells(XMLReader& reader, Range dstRange) CellAddress newCellAddr; for (int r = 0; r < rcount; ++r) { for (int c = 0; c < ccount; ++c) { - CellAddress dst(src.row() + roffset + r * range.rowCount(), - src.col() + coffset + c * range.colCount()); + CellAddress dst( + src.row() + roffset + r * range.rowCount(), + src.col() + coffset + c * range.colCount() + ); if (!dst.isValid()) { continue; } @@ -577,10 +582,11 @@ void PropertySheet::pasteCells(XMLReader& reader, Range dstRange) auto newCell = owner->getCell(newCellAddr); const Expression* expr; if (!newCell || !(expr = newCell->getExpression(true))) { - FC_THROWM(Base::RuntimeError, - "Failed to copy cell " << getFullName() << '.' - << dst.toString() << " from " - << newCellAddr.toString()); + FC_THROWM( + Base::RuntimeError, + "Failed to copy cell " << getFullName() << '.' << dst.toString() + << " from " << newCellAddr.toString() + ); } cell->setExpression(ExpressionPtr(expr->copy())); } @@ -594,9 +600,11 @@ void PropertySheet::pasteCells(XMLReader& reader, Range dstRange) } if (roffset_cur || coffset_cur) { - OffsetCellsExpressionVisitor visitor(*this, - roffset_cur, - coffset_cur); + OffsetCellsExpressionVisitor visitor( + *this, + roffset_cur, + coffset_cur + ); cell->visit(visitor); if (visitor.changed()) { recomputeDependencies(dst); @@ -610,8 +618,10 @@ void PropertySheet::pasteCells(XMLReader& reader, Range dstRange) do { for (int r = 0; r < rcount; ++r) { for (int c = 0; c < ccount; ++c) { - CellAddress dst(range.row() + roffset + r * range.rowCount(), - range.column() + coffset + c * range.colCount()); + CellAddress dst( + range.row() + roffset + r * range.rowCount(), + range.column() + coffset + c * range.colCount() + ); if (!dst.isValid()) { continue; } @@ -765,8 +775,9 @@ void PropertySheet::setAlias(CellAddress address, const std::string& alias) * disappears */ std::string fullName = owner->getFullName() + "." + address.toString(); - std::map>::const_iterator j = - propertyNameToCellMap.find(fullName); + std::map>::const_iterator j = propertyNameToCellMap.find( + fullName + ); if (j != propertyNameToCellMap.end()) { std::set::const_iterator k = j->second.begin(); @@ -858,9 +869,11 @@ void PropertySheet::moveAlias(CellAddress currPos, CellAddress newPos) } } -void PropertySheet::moveCell(CellAddress currPos, - CellAddress newPos, - std::map& renames) +void PropertySheet::moveCell( + CellAddress currPos, + CellAddress newPos, + std::map& renames +) { std::map::const_iterator i = data.find(currPos); std::map::const_iterator j = data.find(newPos); @@ -900,8 +913,8 @@ void PropertySheet::moveCell(CellAddress currPos, setDirty(newPos); - renames[ObjectIdentifier(owner, currPos.toString())] = - ObjectIdentifier(owner, newPos.toString()); + renames[ObjectIdentifier(owner, currPos.toString())] + = ObjectIdentifier(owner, newPos.toString()); } signaller.tryInvoke(); } @@ -915,27 +928,21 @@ void PropertySheet::insertRows(int row, int count) boost::copy(data | boost::adaptors::map_keys, std::back_inserter(keys)); /* Sort them */ - std::sort(keys.begin(), - keys.end(), - std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); // NOLINT + std::sort(keys.begin(), keys.end(), std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); // NOLINT - MoveCellsExpressionVisitor visitor(*this, - CellAddress(row, CellAddress::MAX_COLUMNS), - count, - 0); + MoveCellsExpressionVisitor + visitor(*this, CellAddress(row, CellAddress::MAX_COLUMNS), count, 0); AtomicPropertyChange signaller(*this); // move all the aliases first so dependencies can be calculated correctly - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); - ++i) { + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { if (i->row() >= row) { moveAlias(*i, CellAddress(i->row() + count, i->col())); } } - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); - ++i) { + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { std::map::iterator j = data.find(*i); assert(j != data.end()); @@ -956,10 +963,9 @@ void PropertySheet::insertRows(int row, int count) } const App::DocumentObject* docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, - [docObj](const App::DocumentObject* obj) { - return obj != docObj; - }); + owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } @@ -1000,15 +1006,10 @@ void PropertySheet::removeRows(int row, int count) boost::copy(data | boost::adaptors::map_keys, std::back_inserter(keys)); /* Sort them */ - std::sort(keys.begin(), - keys.end(), - std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); + std::sort(keys.begin(), keys.end(), std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); - MoveCellsExpressionVisitor visitor( - *this, - CellAddress(row + count - 1, CellAddress::MAX_COLUMNS), - -count, - 0); + MoveCellsExpressionVisitor + visitor(*this, CellAddress(row + count - 1, CellAddress::MAX_COLUMNS), -count, 0); AtomicPropertyChange signaller(*this); @@ -1051,16 +1052,17 @@ void PropertySheet::removeRows(int row, int count) else { spanRows = key.row() - row; } - mergeCells(j->first, - CellAddress(j->first.row() + spanRows - 1, j->first.col() + spanCols - 1)); + mergeCells( + j->first, + CellAddress(j->first.row() + spanRows - 1, j->first.col() + spanCols - 1) + ); } } const App::DocumentObject* docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, - [docObj](const App::DocumentObject* obj) { - return obj != docObj; - }); + owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } @@ -1075,23 +1077,19 @@ void PropertySheet::insertColumns(int col, int count) /* Sort them */ std::sort(keys.begin(), keys.end()); - MoveCellsExpressionVisitor visitor(*this, - CellAddress(CellAddress::MAX_ROWS, col), - 0, - count); + MoveCellsExpressionVisitor + visitor(*this, CellAddress(CellAddress::MAX_ROWS, col), 0, count); AtomicPropertyChange signaller(*this); // move all the aliases first so dependencies can be calculated correctly - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); - ++i) { + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { if (i->col() >= col) { moveAlias(*i, CellAddress(i->row(), i->col() + count)); } } - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); - ++i) { + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { std::map::iterator j = data.find(*i); assert(j != data.end()); @@ -1112,10 +1110,9 @@ void PropertySheet::insertColumns(int col, int count) } const App::DocumentObject* docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, - [docObj](const App::DocumentObject* obj) { - return obj != docObj; - }); + owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } @@ -1156,15 +1153,10 @@ void PropertySheet::removeColumns(int col, int count) boost::copy(data | boost::adaptors::map_keys, std::back_inserter(keys)); /* Sort them */ - std::sort(keys.begin(), - keys.end(), - std::bind(&PropertySheet::colSortFunc, this, sp::_1, sp::_2)); // NOLINT + std::sort(keys.begin(), keys.end(), std::bind(&PropertySheet::colSortFunc, this, sp::_1, sp::_2)); // NOLINT - MoveCellsExpressionVisitor visitor( - *this, - CellAddress(CellAddress::MAX_ROWS, col + count - 1), - 0, - -count); + MoveCellsExpressionVisitor + visitor(*this, CellAddress(CellAddress::MAX_ROWS, col + count - 1), 0, -count); AtomicPropertyChange signaller(*this); @@ -1207,16 +1199,17 @@ void PropertySheet::removeColumns(int col, int count) else { spanCols = key.col() - col; } - mergeCells(j->first, - CellAddress(j->first.row() + spanRows - 1, j->first.col() + spanCols - 1)); + mergeCells( + j->first, + CellAddress(j->first.row() + spanRows - 1, j->first.col() + spanCols - 1) + ); } } const App::DocumentObject* docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, - [docObj](const App::DocumentObject* obj) { - return obj != docObj; - }); + owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } @@ -1419,8 +1412,7 @@ void PropertySheet::removeDependencies(CellAddress key) std::set::const_iterator j = i1->second.begin(); while (j != i1->second.end()) { - std::map>::iterator k = - propertyNameToCellMap.find(*j); + std::map>::iterator k = propertyNameToCellMap.find(*j); // assert(k != propertyNameToCellMap.end()); if (k != propertyNameToCellMap.end()) { @@ -1440,8 +1432,7 @@ void PropertySheet::removeDependencies(CellAddress key) std::set::const_iterator j = i2->second.begin(); while (j != i2->second.end()) { - std::map>::iterator k = - documentObjectToCellMap.find(*j); + std::map>::iterator k = documentObjectToCellMap.find(*j); if (k != documentObjectToCellMap.end()) { k->second.erase(key); @@ -1558,7 +1549,8 @@ void PropertySheet::onAddDep(App::DocumentObject* obj) { // NOLINTBEGIN depConnections[obj] = obj->signalChanged.connect( - std::bind(&PropertySheet::slotChangedObject, this, sp::_1, sp::_2)); + std::bind(&PropertySheet::slotChangedObject, this, sp::_1, sp::_2) + ); // NOLINTEND } @@ -1588,7 +1580,8 @@ void PropertySheet::onRenameDynamicProperty(const App::Property& prop, const cha } void PropertySheet::renameObjectIdentifiers( - const std::map& paths) + const std::map& paths +) { RenameObjectIdentifierExpressionVisitor v {*this, paths, *this}; for (auto& c : data) { @@ -1626,8 +1619,7 @@ void PropertySheet::documentSet() const std::set& PropertySheet::getDeps(const std::string& name) const { static std::set empty; - std::map>::const_iterator i = - propertyNameToCellMap.find(name); + std::map>::const_iterator i = propertyNameToCellMap.find(name); if (i != propertyNameToCellMap.end()) { return i->second; @@ -1640,8 +1632,7 @@ const std::set& PropertySheet::getDeps(const std::string& name) con const std::set& PropertySheet::getDeps(CellAddress pos) const { static std::set empty; - std::map>::const_iterator i = - cellToPropertyNameMap.find(pos); + std::map>::const_iterator i = cellToPropertyNameMap.find(pos); if (i != cellToPropertyNameMap.end()) { return i->second; @@ -1854,8 +1845,7 @@ bool PropertySheet::referenceChanged() const return false; } -Property* -PropertySheet::CopyOnImportExternal(const std::map& nameMap) const +Property* PropertySheet::CopyOnImportExternal(const std::map& nameMap) const { std::map> changed; for (auto& d : data) { @@ -1879,9 +1869,11 @@ PropertySheet::CopyOnImportExternal(const std::map& na return copy.release(); } -Property* PropertySheet::CopyOnLabelChange(App::DocumentObject* obj, - const std::string& ref, - const char* newLabel) const +Property* PropertySheet::CopyOnLabelChange( + App::DocumentObject* obj, + const std::string& ref, + const char* newLabel +) const { std::map> changed; for (auto& d : data) { @@ -1905,9 +1897,11 @@ Property* PropertySheet::CopyOnLabelChange(App::DocumentObject* obj, return copy.release(); } -Property* PropertySheet::CopyOnLinkReplace(const App::DocumentObject* parent, - App::DocumentObject* oldObj, - App::DocumentObject* newObj) const +Property* PropertySheet::CopyOnLinkReplace( + const App::DocumentObject* parent, + App::DocumentObject* oldObj, + App::DocumentObject* newObj +) const { std::map> changed; for (auto& d : data) { @@ -2030,10 +2024,12 @@ App::Range PropertySheet::getRange(const char* range, bool silent) const return App::Range(from, to); } -bool PropertySheet::isBindingPath(const ObjectIdentifier& path, - CellAddress* from, - CellAddress* to, - bool* href) const +bool PropertySheet::isBindingPath( + const ObjectIdentifier& path, + CellAddress* from, + CellAddress* to, + bool* href +) const { const auto& comps = path.getComponents(); if (comps.size() != 4 || !comps[2].isSimple() || !comps[3].isSimple() @@ -2054,10 +2050,12 @@ bool PropertySheet::isBindingPath(const ObjectIdentifier& path, return true; } -PropertySheet::BindingType PropertySheet::getBinding(const Range& range, - ExpressionPtr* pStart, - ExpressionPtr* pEnd, - App::ObjectIdentifier* pTarget) const +PropertySheet::BindingType PropertySheet::getBinding( + const Range& range, + ExpressionPtr* pStart, + ExpressionPtr* pEnd, + App::ObjectIdentifier* pTarget +) const { if (!owner) { return BindingNone; @@ -2075,8 +2073,7 @@ PropertySheet::BindingType PropertySheet::getBinding(const Range& range, if ((expr->getFunction() != FunctionExpression::HIDDENREF && expr->getFunction() != FunctionExpression::HREF) || expr->getArgs().size() != 1 - || !expr->getArgs().front()->isDerivedFrom( - FunctionExpression::getClassTypeId())) { + || !expr->getArgs().front()->isDerivedFrom(FunctionExpression::getClassTypeId())) { continue; } expr = static_cast(expr->getArgs().front()); @@ -2110,8 +2107,10 @@ void PropertySheet::setPathValue(const ObjectIdentifier& path, const boost::any& bool href = false; CellAddress from, to; if (!isBindingPath(path, &from, &to, &href)) { - FC_THROWM(Base::IndexError, - "Invalid binding of '" << path.toString() << "' in " << getFullName()); + FC_THROWM( + Base::IndexError, + "Invalid binding of '" << path.toString() << "' in " << getFullName() + ); } Base::PyGILStateLocker lock; @@ -2125,16 +2124,17 @@ void PropertySheet::setPathValue(const ObjectIdentifier& path, const boost::any& auto other = static_cast(seq[0].ptr())->getPropertySheetPtr(); auto otherOwner = freecad_cast(other->getContainer()); if (!otherOwner) { - FC_THROWM(Base::RuntimeError, - "Invalid binding of '" << other->getFullName() << " in " - << getFullName()); + FC_THROWM( + Base::RuntimeError, + "Invalid binding of '" << other->getFullName() << " in " << getFullName() + ); } - App::CellAddress targetFrom = - other->getCellAddress(Py::Object(seq[1].ptr()).as_string().c_str(), false); + App::CellAddress targetFrom + = other->getCellAddress(Py::Object(seq[1].ptr()).as_string().c_str(), false); - App::CellAddress targetTo = - other->getCellAddress(Py::Object(seq[2].ptr()).as_string().c_str(), false); + App::CellAddress targetTo + = other->getCellAddress(Py::Object(seq[2].ptr()).as_string().c_str(), false); std::string expr(href ? "hiddenref(" : ""); if (other != this) { @@ -2185,14 +2185,18 @@ void PropertySheet::setPathValue(const ObjectIdentifier& path, const boost::any& targetFrom.setRow(targetFrom.row() + rowCount); } - range = App::Range(range.from().row(), - range.from().col(), - range.from().row() + rowCount - 1, - range.from().col() + colCount - 1); - rangeTarget = App::Range(rangeTarget.from().row(), - rangeTarget.from().col(), - rangeTarget.from().row() + rowCount - 1, - rangeTarget.from().col() + colCount - 1); + range = App::Range( + range.from().row(), + range.from().col(), + range.from().row() + rowCount - 1, + range.from().col() + colCount - 1 + ); + rangeTarget = App::Range( + rangeTarget.from().row(), + rangeTarget.from().col(), + rangeTarget.from().row() + rowCount - 1, + rangeTarget.from().col() + colCount - 1 + ); do { CellAddress target(*rangeTarget); CellAddress source(*range); @@ -2281,13 +2285,15 @@ bool PropertySheet::hasSpan() const return !mergedCells.empty(); } -void PropertySheet::getLinksTo(std::vector& identifiers, - App::DocumentObject* obj, - const char* subname, - bool all) const +void PropertySheet::getLinksTo( + std::vector& identifiers, + App::DocumentObject* obj, + const char* subname, + bool all +) const { - Expression::DepOption option = - all ? Expression::DepOption::DepAll : Expression::DepOption::DepNormal; + Expression::DepOption option = all ? Expression::DepOption::DepAll + : Expression::DepOption::DepNormal; App::SubObjectT objT(obj, subname); auto subObject = objT.getSubObject(); @@ -2307,17 +2313,21 @@ void PropertySheet::getLinksTo(std::vector& identifiers, identifiers.emplace_back(owner, cellName.toString()); break; } - if (std::any_of(paths.begin(), - paths.end(), - [subname, obj, subObject, &subElement](const auto& path) { - if (path.getSubObjectName() == subname) { - return true; - } + if (std::any_of( + paths.begin(), + paths.end(), + [subname, obj, subObject, &subElement](const auto& path) { + if (path.getSubObjectName() == subname) { + return true; + } - App::SubObjectT sobjT(obj, path.getSubObjectName().c_str()); - return (sobjT.getSubObject() == subObject - && sobjT.getOldElementName() == subElement); - })) { + App::SubObjectT sobjT(obj, path.getSubObjectName().c_str()); + return ( + sobjT.getSubObject() == subObject + && sobjT.getOldElementName() == subElement + ); + } + )) { identifiers.emplace_back(owner, cellName.toString()); } } diff --git a/src/Mod/Spreadsheet/App/PropertySheet.h b/src/Mod/Spreadsheet/App/PropertySheet.h index 4c7ff198a4..403e63ce4e 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.h +++ b/src/Mod/Spreadsheet/App/PropertySheet.h @@ -26,9 +26,9 @@ #define PROPERTYSHEET_H #ifdef _MSC_VER -#ifdef PropertySheet -#undef PropertySheet // Microsoft's #define conflicts with the use below -#endif +# ifdef PropertySheet +# undef PropertySheet // Microsoft's #define conflicts with the use below +# endif #endif #include @@ -63,19 +63,24 @@ public: void onRelabeledDocument(const App::Document& doc) override; void onRenameDynamicProperty(const App::Property& prop, const char* oldName) override; - void updateElementReference(App::DocumentObject* feature, - bool reverse = false, - bool notify = false) override; + void updateElementReference( + App::DocumentObject* feature, + bool reverse = false, + bool notify = false + ) override; bool referenceChanged() const override; bool adjustLink(const std::set& inList) override; - Property* - CopyOnImportExternal(const std::map& nameMap) const override; - Property* CopyOnLabelChange(App::DocumentObject* obj, - const std::string& ref, - const char* newLabel) const override; - Property* CopyOnLinkReplace(const App::DocumentObject* parent, - App::DocumentObject* oldObj, - App::DocumentObject* newObj) const override; + Property* CopyOnImportExternal(const std::map& nameMap) const override; + Property* CopyOnLabelChange( + App::DocumentObject* obj, + const std::string& ref, + const char* newLabel + ) const override; + Property* CopyOnLinkReplace( + const App::DocumentObject* parent, + App::DocumentObject* oldObj, + App::DocumentObject* newObj + ) const override; void breakLink(App::DocumentObject* obj, bool clear) override; void afterRestore() override; @@ -89,10 +94,12 @@ public: void Restore(Base::XMLReader& reader) override; - void getLinksTo(std::vector& identifiers, - App::DocumentObject* obj, - const char* subname = nullptr, - bool all = false) const override; + void getLinksTo( + std::vector& identifiers, + App::DocumentObject* obj, + const char* subname = nullptr, + bool all = false + ) const override; void copyCells(Base::Writer& writer, const std::vector& ranges) const; @@ -176,8 +183,7 @@ public: return dirty.size() > 0; } - void - pasteCells(const std::map& cells, int rowOffset, int colOffset); + void pasteCells(const std::map& cells, int rowOffset, int colOffset); void insertRows(int row, int count); @@ -220,8 +226,7 @@ public: void invalidateDependants(const App::DocumentObject* docObj); - void - renameObjectIdentifiers(const std::map& paths); + void renameObjectIdentifiers(const std::map& paths); void deletedDocumentObject(const App::DocumentObject* docObj); @@ -239,10 +244,12 @@ public: unsigned getBindingBorder(App::CellAddress address) const; - bool isBindingPath(const App::ObjectIdentifier& path, - App::CellAddress* from = nullptr, - App::CellAddress* to = nullptr, - bool* href = nullptr) const; + bool isBindingPath( + const App::ObjectIdentifier& path, + App::CellAddress* from = nullptr, + App::CellAddress* to = nullptr, + bool* href = nullptr + ) const; enum BindingType { @@ -250,10 +257,12 @@ public: BindingNormal, BindingHiddenRef, }; - BindingType getBinding(const App::Range& range, - App::ExpressionPtr* pStart = nullptr, - App::ExpressionPtr* pEnd = nullptr, - App::ObjectIdentifier* pTarget = nullptr) const; + BindingType getBinding( + const App::Range& range, + App::ExpressionPtr* pStart = nullptr, + App::ExpressionPtr* pEnd = nullptr, + App::ObjectIdentifier* pTarget = nullptr + ) const; protected: void hasSetValue() override; @@ -302,9 +311,11 @@ private: void moveAlias(App::CellAddress currPos, App::CellAddress newPos); - void moveCell(App::CellAddress currPos, - App::CellAddress newPos, - std::map& renames); + void moveCell( + App::CellAddress currPos, + App::CellAddress newPos, + std::map& renames + ); /* * Cell dependency tracking diff --git a/src/Mod/Spreadsheet/App/Sheet.cpp b/src/Mod/Spreadsheet/App/Sheet.cpp index 8254873b0d..e0fb337f07 100644 --- a/src/Mod/Spreadsheet/App/Sheet.cpp +++ b/src/Mod/Spreadsheet/App/Sheet.cpp @@ -80,21 +80,27 @@ Sheet::Sheet() , cells(this) { ADD_PROPERTY_TYPE(cells, (), "Spreadsheet", (PropertyType)(Prop_Hidden), "Cell contents"); - ADD_PROPERTY_TYPE(columnWidths, - (), - "Spreadsheet", - (PropertyType)(Prop_ReadOnly | Prop_Hidden | Prop_Output), - "Column widths"); - ADD_PROPERTY_TYPE(rowHeights, - (), - "Spreadsheet", - (PropertyType)(Prop_ReadOnly | Prop_Hidden | Prop_Output), - "Row heights"); - ADD_PROPERTY_TYPE(rowHeights, - (), - "Spreadsheet", - (PropertyType)(Prop_ReadOnly | Prop_Hidden), - "Row heights"); + ADD_PROPERTY_TYPE( + columnWidths, + (), + "Spreadsheet", + (PropertyType)(Prop_ReadOnly | Prop_Hidden | Prop_Output), + "Column widths" + ); + ADD_PROPERTY_TYPE( + rowHeights, + (), + "Spreadsheet", + (PropertyType)(Prop_ReadOnly | Prop_Hidden | Prop_Output), + "Row heights" + ); + ADD_PROPERTY_TYPE( + rowHeights, + (), + "Spreadsheet", + (PropertyType)(Prop_ReadOnly | Prop_Hidden), + "Row heights" + ); ExpressionEngine.expressionChanged.connect([this](const App::ObjectIdentifier&) { this->updateBindings(); }); @@ -116,7 +122,8 @@ Sheet::~Sheet() // Don't let an exception propagate out of a destructor (calls terminate()) Base::Console().error( "clearAll() resulted in an exception when deleting the spreadsheet : %s\n", - getNameInDocument()); + getNameInDocument() + ); } } @@ -151,11 +158,11 @@ bool Sheet::getCharsFromPrefs(char& delim, char& quote, char& escape, std::strin { bool isValid = true; ParameterGrp::handle group = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Spreadsheet"); + "User parameter:BaseApp/Preferences/Mod/Spreadsheet" + ); QString delimiter = QString::fromStdString(group->GetASCII("ImportExportDelimiter", "tab")); QString quoteChar = QString::fromStdString(group->GetASCII("ImportExportQuoteCharacter", "\"")); - QString escapeChar = - QString::fromStdString(group->GetASCII("ImportExportEscapeCharacter", "\\")); + QString escapeChar = QString::fromStdString(group->GetASCII("ImportExportEscapeCharacter", "\\")); delim = delimiter.size() == 1 ? delimiter[0].toLatin1() : '\0'; if (delimiter.compare(QLatin1String("tab"), Qt::CaseInsensitive) == 0 @@ -208,10 +215,7 @@ bool Sheet::getCharsFromPrefs(char& delim, char& quote, char& escape, std::strin * @returns True if successful, false if something failed. */ -bool Sheet::importFromFile(const std::string& filename, - char delimiter, - char quoteChar, - char escapeChar) +bool Sheet::importFromFile(const std::string& filename, char delimiter, char quoteChar, char escapeChar) { Base::FileInfo fi(filename); Base::ifstream file(fi, std::ios::in); @@ -302,10 +306,7 @@ static void writeEscaped(std::string const& s, char quoteChar, char escapeChar, * */ -bool Sheet::exportToFile(const std::string& filename, - char delimiter, - char quoteChar, - char escapeChar) const +bool Sheet::exportToFile(const std::string& filename, char delimiter, char quoteChar, char escapeChar) const { Base::ofstream file; int prevRow = -1, prevCol = -1; @@ -355,8 +356,7 @@ bool Sheet::exportToFile(const std::string& filename, std::string str = field.str(); - if (quoteChar - && str.find_first_of(std::string(quoteChar, delimiter)) != std::string::npos) { + if (quoteChar && str.find_first_of(std::string(quoteChar, delimiter)) != std::string::npos) { writeEscaped(str, quoteChar, escapeChar, file); } else { @@ -586,12 +586,13 @@ Property* Sheet::setFloatProperty(CellAddress key, double value) this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - floatProp = freecad_cast( - addDynamicProperty("App::PropertyFloat", - name.c_str(), - nullptr, - nullptr, - Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + floatProp = freecad_cast(addDynamicProperty( + "App::PropertyFloat", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist + )); } else { floatProp = static_cast(prop); @@ -614,12 +615,13 @@ Property* Sheet::setIntegerProperty(CellAddress key, long value) this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - intProp = freecad_cast( - addDynamicProperty("App::PropertyInteger", - name.c_str(), - nullptr, - nullptr, - Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + intProp = freecad_cast(addDynamicProperty( + "App::PropertyInteger", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist + )); } else { intProp = static_cast(prop); @@ -654,11 +656,13 @@ Property* Sheet::setQuantityProperty(CellAddress key, double value, const Base:: this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - Property* p = addDynamicProperty("Spreadsheet::PropertySpreadsheetQuantity", - name.c_str(), - nullptr, - nullptr, - Prop_ReadOnly | Prop_Hidden | Prop_NoPersist); + Property* p = addDynamicProperty( + "Spreadsheet::PropertySpreadsheetQuantity", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist + ); quantityProp = freecad_cast(p); } else { @@ -695,12 +699,13 @@ Property* Sheet::setStringProperty(CellAddress key, const std::string& value) this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - stringProp = freecad_cast( - addDynamicProperty("App::PropertyString", - name.c_str(), - nullptr, - nullptr, - Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + stringProp = freecad_cast(addDynamicProperty( + "App::PropertyString", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist + )); } propAddress[stringProp] = key; @@ -720,12 +725,13 @@ Property* Sheet::setObjectProperty(CellAddress key, Py::Object object) this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - pyProp = freecad_cast( - addDynamicProperty("App::PropertyPythonObject", - name.c_str(), - nullptr, - nullptr, - Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + pyProp = freecad_cast(addDynamicProperty( + "App::PropertyPythonObject", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist + )); } propAddress[pyProp] = key; @@ -949,10 +955,12 @@ void Sheet::recomputeCell(CellAddress p) } } -PropertySheet::BindingType Sheet::getCellBinding(Range& range, - ExpressionPtr* pStart, - ExpressionPtr* pEnd, - App::ObjectIdentifier* pTarget) const +PropertySheet::BindingType Sheet::getCellBinding( + Range& range, + ExpressionPtr* pStart, + ExpressionPtr* pEnd, + App::ObjectIdentifier* pTarget +) const { range.normalize(); do { @@ -971,9 +979,11 @@ PropertySheet::BindingType Sheet::getCellBinding(Range& range, return PropertySheet::BindingNone; } -static inline unsigned _getBorder(const Sheet* sheet, - const std::vector& ranges, - const App::CellAddress& address) +static inline unsigned _getBorder( + const Sheet* sheet, + const std::vector& ranges, + const App::CellAddress& address +) { unsigned flags = 0; int rows, cols; @@ -1152,8 +1162,10 @@ DocumentObjectExecReturn* Sheet::execute() } catch (std::exception&) { // TODO: evaluate using a more specific exception (not_a_dag) // Cycle detected; flag all with errors - Base::Console().error("Cyclic dependency detected in spreadsheet : %s\n", - getNameInDocument()); + Base::Console().error( + "Cyclic dependency detected in spreadsheet : %s\n", + getNameInDocument() + ); std::ostringstream ss; ss << "Cyclic dependency"; int count = 0; diff --git a/src/Mod/Spreadsheet/App/Sheet.h b/src/Mod/Spreadsheet/App/Sheet.h index c4d57a4b48..e4a788a752 100644 --- a/src/Mod/Spreadsheet/App/Sheet.h +++ b/src/Mod/Spreadsheet/App/Sheet.h @@ -26,8 +26,8 @@ #define SRC_MOD_SPREADSHEET_APP_SHEET_H_ #ifdef signals -#undef signals -#define signals signals +# undef signals +# define signals signals #endif #include @@ -89,17 +89,21 @@ public: return "SpreadsheetGui::ViewProviderSheet"; } - bool importFromFile(const std::string& filename, - char delimiter = '\t', - char quoteChar = '\0', - char escapeChar = '\\'); + bool importFromFile( + const std::string& filename, + char delimiter = '\t', + char quoteChar = '\0', + char escapeChar = '\\' + ); bool getCharsFromPrefs(char& delimiter, char& quote, char& escape, std::string& errMsg); - bool exportToFile(const std::string& filename, - char delimiter = '\t', - char quoteChar = '\0', - char escapeChar = '\\') const; + bool exportToFile( + const std::string& filename, + char delimiter = '\t', + char quoteChar = '\0', + char escapeChar = '\\' + ) const; bool mergeCells(const App::Range& range); @@ -119,10 +123,12 @@ public: }; unsigned getCellBindingBorder(App::CellAddress address) const; - PropertySheet::BindingType getCellBinding(App::Range& range, - App::ExpressionPtr* pStart = nullptr, - App::ExpressionPtr* pEnd = nullptr, - App::ObjectIdentifier* pTarget = nullptr) const; + PropertySheet::BindingType getCellBinding( + App::Range& range, + App::ExpressionPtr* pStart = nullptr, + App::ExpressionPtr* pEnd = nullptr, + App::ObjectIdentifier* pTarget = nullptr + ) const; void setCell(const char* address, const char* value); @@ -194,8 +200,7 @@ public: App::Property* getDynamicPropertyByName(const char* name) const override; - void - getPropertyNamedList(std::vector>& List) const override; + void getPropertyNamedList(std::vector>& List) const override; /// See PropertyContainer::visitProperties for semantics void visitProperties(const std::function& visitor) const override; @@ -237,7 +242,8 @@ public: boost::signals2::signal rowHeightChanged; void renameObjectIdentifiers( - const std::map& paths) override; + const std::map& paths + ) override; void setCopyOrCutRanges(const std::vector& ranges, bool copy = true); const std::vector& getCopyOrCutRange(bool copy = true) const; diff --git a/src/Mod/Spreadsheet/App/SheetObserver.cpp b/src/Mod/Spreadsheet/App/SheetObserver.cpp index b8de033ba4..4f3cfc6c3b 100644 --- a/src/Mod/Spreadsheet/App/SheetObserver.cpp +++ b/src/Mod/Spreadsheet/App/SheetObserver.cpp @@ -71,7 +71,8 @@ void SheetObserver::slotDeletedObject(const DocumentObject& Obj) void SheetObserver::slotChangedObject(const DocumentObject& Obj, const Property& Prop) { - if (&Prop == &Obj.Label) {} + if (&Prop == &Obj.Label) { + } else { const char* name = Obj.getPropertyName(&Prop); diff --git a/src/Mod/Spreadsheet/App/SheetPyImp.cpp b/src/Mod/Spreadsheet/App/SheetPyImp.cpp index eb8acb99ee..65e4a1311b 100644 --- a/src/Mod/Spreadsheet/App/SheetPyImp.cpp +++ b/src/Mod/Spreadsheet/App/SheetPyImp.cpp @@ -120,11 +120,13 @@ PyObject* SheetPy::get(PyObject* args) do { App::Property* prop = getSheetPtr()->getPropertyByName(range.address().c_str()); if (!prop) { - PyErr_Format(PyExc_ValueError, - "Invalid address '%s' in range %s:%s", - range.address().c_str(), - address, - address2); + PyErr_Format( + PyExc_ValueError, + "Invalid address '%s' in range %s:%s", + range.address().c_str(), + address, + address2 + ); return nullptr; } tuple.setItem(i++, Py::Object(prop->getPyObject(), true)); @@ -222,12 +224,7 @@ PyObject* SheetPy::importFile(PyObject* args) const char* quoteChar = "\""; const char* escapeChar = "\\"; - if (!PyArg_ParseTuple(args, - "s|sss:importFile", - &filename, - &delimiter, - "eChar, - &escapeChar)) { + if (!PyArg_ParseTuple(args, "s|sss:importFile", &filename, &delimiter, "eChar, &escapeChar)) { return nullptr; } @@ -246,12 +243,7 @@ PyObject* SheetPy::exportFile(PyObject* args) const char* quoteChar = "\""; const char* escapeChar = "\\"; - if (!PyArg_ParseTuple(args, - "s|sss:exportFile", - &filename, - &delimiter, - "eChar, - &escapeChar)) { + if (!PyArg_ParseTuple(args, "s|sss:exportFile", &filename, &delimiter, "eChar, &escapeChar)) { return nullptr; } @@ -386,14 +378,13 @@ PyObject* SheetPy::setStyle(PyObject* args) std::string line = PyUnicode_AsUTF8(value); tokenizer> tok(line, e); - for (tokenizer>::iterator i = tok.begin(); i != tok.end(); - ++i) { + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); ++i) { style.insert(*i); } } else { - std::string error = - std::string("style must be either set or string, not ") + value->ob_type->tp_name; + std::string error = std::string("style must be either set or string, not ") + + value->ob_type->tp_name; PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } @@ -476,7 +467,8 @@ PyObject* SheetPy::setStyle(PyObject* args) else { PyErr_SetString( PyExc_ValueError, - "Optional parameter must be either 'replace', 'add', 'remove', or 'invert'"); + "Optional parameter must be either 'replace', 'add', 'remove', or 'invert'" + ); return nullptr; } @@ -684,16 +676,15 @@ PyObject* SheetPy::setAlignment(PyObject* args) std::string line = PyUnicode_AsUTF8(value); tokenizer> tok(line, e); - for (tokenizer>::iterator i = tok.begin(); i != tok.end(); - ++i) { + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); ++i) { if (!i->empty()) { alignment = Cell::decodeAlignment(*i, alignment); } } } else { - std::string error = - std::string("style must be either set or string, not ") + value->ob_type->tp_name; + std::string error = std::string("style must be either set or string, not ") + + value->ob_type->tp_name; PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } diff --git a/src/Mod/Spreadsheet/App/Utils.cpp b/src/Mod/Spreadsheet/App/Utils.cpp index 61ee9329bf..6ceeb0c74c 100644 --- a/src/Mod/Spreadsheet/App/Utils.cpp +++ b/src/Mod/Spreadsheet/App/Utils.cpp @@ -73,8 +73,10 @@ std::string Spreadsheet::rowName(int row) } -void Spreadsheet::createRectangles(std::set>& cells, - std::map, std::pair>& rectangles) +void Spreadsheet::createRectangles( + std::set>& cells, + std::map, std::pair>& rectangles +) { while (!cells.empty()) { int row, col; diff --git a/src/Mod/Spreadsheet/App/Utils.h b/src/Mod/Spreadsheet/App/Utils.h index 39d5ba57af..db17239a79 100644 --- a/src/Mod/Spreadsheet/App/Utils.h +++ b/src/Mod/Spreadsheet/App/Utils.h @@ -39,9 +39,10 @@ namespace Spreadsheet SpreadsheetExport std::string columnName(int col); SpreadsheetExport std::string rowName(int row); -SpreadsheetExport void -createRectangles(std::set>& cells, - std::map, std::pair>& rectangles); +SpreadsheetExport void createRectangles( + std::set>& cells, + std::map, std::pair>& rectangles +); SpreadsheetExport std::string quote(const std::string& input); SpreadsheetExport std::string unquote(const std::string& input); diff --git a/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp b/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp index f37e7911ad..2805b8be6a 100644 --- a/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp +++ b/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp @@ -90,8 +90,9 @@ private: std::string EncodedName = std::string(Name); PyMem_Free(Name); - App::Document* pcDoc = - App::GetApplication().newDocument(DocName ? DocName : QT_TR_NOOP("Unnamed")); + App::Document* pcDoc = App::GetApplication().newDocument( + DocName ? DocName : QT_TR_NOOP("Unnamed") + ); load(pcDoc, EncodedName); return Py::None(); @@ -147,7 +148,8 @@ PyMOD_INIT_FUNC(SpreadsheetGui) // register preference page new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Spreadsheet")); + QT_TRANSLATE_NOOP("QObject", "Spreadsheet") + ); // add resources and reloads the translators loadSpreadsheetResource(); diff --git a/src/Mod/Spreadsheet/Gui/Command.cpp b/src/Mod/Spreadsheet/Gui/Command.cpp index 332fd64c0e..66009fa1ce 100644 --- a/src/Mod/Spreadsheet/Gui/Command.cpp +++ b/src/Mod/Spreadsheet/Gui/Command.cpp @@ -27,7 +27,7 @@ #include #if defined(FC_OS_WIN32) -#include +# include #endif #include @@ -71,8 +71,7 @@ void CmdSpreadsheetMergeCells::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -84,10 +83,12 @@ void CmdSpreadsheetMergeCells::activated(int iMsg) std::vector::const_iterator i = ranges.begin(); for (; i != ranges.end(); ++i) { if (i->size() > 1) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.mergeCells('%s')", - sheet->getNameInDocument(), - i->rangeString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.mergeCells('%s')", + sheet->getNameInDocument(), + i->rangeString().c_str() + ); } } Gui::Command::commitCommand(); @@ -101,8 +102,7 @@ bool CmdSpreadsheetMergeCells::isActive() { if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { return (sheetView->selectedIndexesRaw().size() > 1); @@ -132,8 +132,7 @@ void CmdSpreadsheetSplitCell::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -142,10 +141,12 @@ void CmdSpreadsheetSplitCell::activated(int iMsg) if (current.isValid()) { std::string address = CellAddress(current.row(), current.column()).toString(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Sp&lit cell")); - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.splitCell('%s')", - sheet->getNameInDocument(), - address.c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.splitCell('%s')", + sheet->getNameInDocument(), + address.c_str() + ); Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } @@ -157,16 +158,17 @@ bool CmdSpreadsheetSplitCell::isActive() { if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { QModelIndex current = sheetView->currentIndex(); Sheet* sheet = sheetView->getSheet(); if (current.isValid()) { - return (sheetView->selectedIndexesRaw().size() == 1 - && sheet->isMergedCell(CellAddress(current.row(), current.column()))); + return ( + sheetView->selectedIndexesRaw().size() == 1 + && sheet->isMergedCell(CellAddress(current.row(), current.column())) + ); } } } @@ -194,11 +196,13 @@ void CmdSpreadsheetImport::activated(int iMsg) Q_UNUSED(iMsg); QString selectedFilter; QString formatList = QObject::tr("CSV (*.csv *.CSV);;All (*)"); - QString fileName = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), - QObject::tr("Import file"), - QString(), - formatList, - &selectedFilter); + QString fileName = Gui::FileDialog::getOpenFileName( + Gui::getMainWindow(), + QObject::tr("Import file"), + QString(), + formatList, + &selectedFilter + ); if (!fileName.isEmpty()) { std::string FeatName = getUniqueObjectName("Spreadsheet"); auto* doc = App::GetApplication().getActiveDocument(); @@ -246,8 +250,7 @@ void CmdSpreadsheetExport::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -292,8 +295,7 @@ void CmdSpreadsheetAlignLeft::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -308,7 +310,8 @@ void CmdSpreadsheetAlignLeft::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setAlignment('%s', 'left', 'keep')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -349,8 +352,7 @@ void CmdSpreadsheetAlignCenter::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -365,7 +367,8 @@ void CmdSpreadsheetAlignCenter::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setAlignment('%s', 'center', 'keep')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -406,8 +409,7 @@ void CmdSpreadsheetAlignRight::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -422,7 +424,8 @@ void CmdSpreadsheetAlignRight::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setAlignment('%s', 'right', 'keep')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -463,8 +466,7 @@ void CmdSpreadsheetAlignTop::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -479,7 +481,8 @@ void CmdSpreadsheetAlignTop::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setAlignment('%s', 'top', 'keep')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -520,8 +523,7 @@ void CmdSpreadsheetAlignBottom::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -536,7 +538,8 @@ void CmdSpreadsheetAlignBottom::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setAlignment('%s', 'bottom', 'keep')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -577,8 +580,7 @@ void CmdSpreadsheetAlignVCenter::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -593,7 +595,8 @@ void CmdSpreadsheetAlignVCenter::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setAlignment('%s', 'vcenter', 'keep')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -635,8 +638,7 @@ void CmdSpreadsheetStyleBold::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -669,14 +671,16 @@ void CmdSpreadsheetStyleBold::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setStyle('%s', 'bold', 'add')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } else { Gui::Command::doCommand( Gui::Command::Doc, "App.ActiveDocument.%s.setStyle('%s', 'bold', 'remove')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } } Gui::Command::commitCommand(); @@ -719,8 +723,7 @@ void CmdSpreadsheetStyleItalic::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -753,14 +756,16 @@ void CmdSpreadsheetStyleItalic::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setStyle('%s', 'italic', 'add')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } else { Gui::Command::doCommand( Gui::Command::Doc, "App.ActiveDocument.%s.setStyle('%s', 'italic', 'remove')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } } Gui::Command::commitCommand(); @@ -803,8 +808,7 @@ void CmdSpreadsheetStyleUnderline::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -837,14 +841,16 @@ void CmdSpreadsheetStyleUnderline::activated(int iMsg) Gui::Command::Doc, "App.ActiveDocument.%s.setStyle('%s', 'underline', 'add')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } else { Gui::Command::doCommand( Gui::Command::Doc, "App.ActiveDocument.%s.setStyle('%s', 'underline', 'remove')", sheet->getNameInDocument(), - i->rangeString().c_str()); + i->rangeString().c_str() + ); } } Gui::Command::commitCommand(); @@ -887,8 +893,7 @@ void CmdSpreadsheetSetAlias::activated(int iMsg) Q_UNUSED(iMsg); if (getActiveGuiDocument()) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -897,13 +902,14 @@ void CmdSpreadsheetSetAlias::activated(int iMsg) if (selection.size() == 1) { std::vector range; - range.emplace_back(selection[0].row(), - selection[0].column(), - selection[0].row(), - selection[0].column()); + range.emplace_back( + selection[0].row(), + selection[0].column(), + selection[0].row(), + selection[0].column() + ); - std::unique_ptr dialog( - new PropertiesDialog(sheet, range, sheetView)); + std::unique_ptr dialog(new PropertiesDialog(sheet, range, sheetView)); dialog->selectAlias(); @@ -921,8 +927,9 @@ bool CmdSpreadsheetSetAlias::isActive() Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); if (activeWindow) { - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast( + activeWindow + ); if (sheetView) { QModelIndexList selection = sheetView->selectedIndexes(); diff --git a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp index 0b8f1d7d6c..d895014c1d 100644 --- a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp @@ -100,8 +100,10 @@ DlgBindSheet::DlgBindSheet(Sheet* sheet, const std::vector& ranges, QWidg ui->lineEditToStart->setText(QLatin1String(toStart.c_str())); ui->lineEditToEnd->setText(QLatin1String(toEnd.c_str())); - ui->comboBox->addItem(QStringLiteral(". (%1)").arg(QString::fromUtf8(sheet->Label.getValue())), - QByteArray("")); + ui->comboBox->addItem( + QStringLiteral(". (%1)").arg(QString::fromUtf8(sheet->Label.getValue())), + QByteArray("") + ); App::DocumentObject* target = bindingTarget.getDocumentObject(); for (auto obj : sheet->getDocument()->getObjectsOfType()) { @@ -110,8 +112,10 @@ DlgBindSheet::DlgBindSheet(Sheet* sheet, const std::vector& ranges, QWidg } QString label; if (obj->Label.getStrValue() != obj->getNameInDocument()) { - label = QStringLiteral("%1 (%2)").arg(QString::fromLatin1(obj->getNameInDocument()), - QString::fromUtf8(obj->Label.getValue())); + label = QStringLiteral("%1 (%2)").arg( + QString::fromLatin1(obj->getNameInDocument()), + QString::fromUtf8(obj->Label.getValue()) + ); } else { label = QLatin1String(obj->getNameInDocument()); @@ -132,8 +136,10 @@ DlgBindSheet::DlgBindSheet(Sheet* sheet, const std::vector& ranges, QWidg std::string fullname = obj->getFullName(); QString label; if (obj->Label.getStrValue() != obj->getNameInDocument()) { - label = QStringLiteral("%1 (%2)").arg(QString::fromLatin1(fullname.c_str()), - QString::fromUtf8(obj->Label.getValue())); + label = QStringLiteral("%1 (%2)").arg( + QString::fromLatin1(fullname.c_str()), + QString::fromUtf8(obj->Label.getValue()) + ); } else { label = QLatin1String(fullname.c_str()); @@ -220,12 +226,14 @@ void DlgBindSheet::accept() App::Range fromRange(fromCellStart, fromCellEnd, true); App::Range toRange(toCellStart, toCellEnd, true); if (fromRange.size() != toRange.size()) { - auto res = QMessageBox::warning(this, - tr("Bind Cells"), - tr("Source and target cell count mismatch. " - "Partial binding may still work.\n\n" - "Continue?"), - QMessageBox::Yes | QMessageBox::No); + auto res = QMessageBox::warning( + this, + tr("Bind Cells"), + tr("Source and target cell count mismatch. " + "Partial binding may still work.\n\n" + "Continue?"), + QMessageBox::Yes | QMessageBox::No + ); if (res == QMessageBox::No) { return; } @@ -237,10 +245,7 @@ void DlgBindSheet::accept() commandActive = true; if (ui->checkBoxHREF->isChecked()) { - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.Bind.%s.%s', None)", - fromStart, - fromEnd); + Gui::cmdAppObjectArgs(sheet, "setExpression('.cells.Bind.%s.%s', None)", fromStart, fromEnd); Gui::cmdAppObjectArgs( sheet, "setExpression('.cells.BindHiddenRef.%s.%s', 'hiddenref(tuple(%s.cells, %s, %s))')", @@ -248,20 +253,25 @@ void DlgBindSheet::accept() fromEnd, ref, toStart, - toEnd); + toEnd + ); } else { - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.BindHiddenRef.%s.%s', None)", - fromStart, - fromEnd); - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.Bind.%s.%s', 'tuple(%s.cells, %s, %s)')", - fromStart, - fromEnd, - ref, - toStart, - toEnd); + Gui::cmdAppObjectArgs( + sheet, + "setExpression('.cells.BindHiddenRef.%s.%s', None)", + fromStart, + fromEnd + ); + Gui::cmdAppObjectArgs( + sheet, + "setExpression('.cells.Bind.%s.%s', 'tuple(%s.cells, %s, %s)')", + fromStart, + fromEnd, + ref, + toStart, + toEnd + ); } Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); Gui::Command::commitCommand(); @@ -269,9 +279,11 @@ void DlgBindSheet::accept() } catch (Base::Exception& e) { e.reportException(); - QMessageBox::critical(this, - tr("Bind Spreadsheet Cells"), - tr("Error:\n") + QString::fromUtf8(e.what())); + QMessageBox::critical( + this, + tr("Bind Spreadsheet Cells"), + tr("Error:\n") + QString::fromUtf8(e.what()) + ); if (commandActive) { Gui::Command::abortCommand(); } @@ -284,14 +296,13 @@ void DlgBindSheet::onDiscard() std::string fromStart(ui->lineEditFromStart->text().trimmed().toLatin1().constData()); std::string fromEnd(ui->lineEditFromEnd->text().trimmed().toLatin1().constData()); Gui::Command::openCommand("Unbind cells"); - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.Bind.%s.%s', None)", - fromStart, - fromEnd); - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.BindHiddenRef.%s.%s', None)", - fromStart, - fromEnd); + Gui::cmdAppObjectArgs(sheet, "setExpression('.cells.Bind.%s.%s', None)", fromStart, fromEnd); + Gui::cmdAppObjectArgs( + sheet, + "setExpression('.cells.BindHiddenRef.%s.%s', None)", + fromStart, + fromEnd + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); Gui::Command::commitCommand(); reject(); diff --git a/src/Mod/Spreadsheet/Gui/DlgBindSheet.h b/src/Mod/Spreadsheet/Gui/DlgBindSheet.h index 043f854a56..9198576e18 100644 --- a/src/Mod/Spreadsheet/Gui/DlgBindSheet.h +++ b/src/Mod/Spreadsheet/Gui/DlgBindSheet.h @@ -41,9 +41,11 @@ class DlgBindSheet: public QDialog Q_OBJECT public: - explicit DlgBindSheet(Spreadsheet::Sheet* sheet, - const std::vector& range, - QWidget* parent = nullptr); + explicit DlgBindSheet( + Spreadsheet::Sheet* sheet, + const std::vector& range, + QWidget* parent = nullptr + ); ~DlgBindSheet() override; void accept() override; diff --git a/src/Mod/Spreadsheet/Gui/DlgSettingsImp.cpp b/src/Mod/Spreadsheet/Gui/DlgSettingsImp.cpp index 8572a38ac5..6f21657278 100644 --- a/src/Mod/Spreadsheet/Gui/DlgSettingsImp.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgSettingsImp.cpp @@ -52,7 +52,8 @@ void DlgSettingsImp::saveSettings() * we'll check for validity during import/export */ ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Spreadsheet"); + "User parameter:BaseApp/Preferences/Mod/Spreadsheet" + ); QString delimiter = ui->delimiterComboBox->currentText(); hGrp->SetASCII("ImportExportDelimiter", delimiter.toStdString().c_str()); ui->quoteCharLineEdit->onSave(); @@ -69,7 +70,8 @@ void DlgSettingsImp::loadSettings() */ ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Spreadsheet"); + "User parameter:BaseApp/Preferences/Mod/Spreadsheet" + ); QString delimiter = QString::fromStdString(hGrp->GetASCII("ImportExportDelimiter", "tab")); int idx = ui->delimiterComboBox->findText(delimiter, Qt::MatchFixedString); if (idx != -1) { diff --git a/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp b/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp index 2f1be9f1ad..2f3d833f10 100644 --- a/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgSheetConf.cpp @@ -80,11 +80,13 @@ DlgSheetConf::~DlgSheetConf() delete ui; } -App::Property* DlgSheetConf::prepare(CellAddress& from, - CellAddress& to, - std::string& rangeConf, - ObjectIdentifier& path, - bool init) +App::Property* DlgSheetConf::prepare( + CellAddress& from, + CellAddress& to, + std::string& rangeConf, + ObjectIdentifier& path, + bool init +) { from = sheet->getCellAddress(ui->lineEditStart->text().trimmed().toLatin1().constData()); to = sheet->getCellAddress(ui->lineEditEnd->text().trimmed().toLatin1().constData()); @@ -187,10 +189,11 @@ void DlgSheetConf::accept() continue; } } - FC_THROWM(Base::RuntimeError, - "Expects cell " << r.address() << " evaluates to string.\n" - << rangeConf - << " is supposed to contain a list of configuration names"); + FC_THROWM( + Base::RuntimeError, + "Expects cell " << r.address() << " evaluates to string.\n" + << rangeConf << " is supposed to contain a list of configuration names" + ); } while (r.next()); std::string exprTxt(ui->lineEditProp->text().trimmed().toUtf8().constData()); @@ -210,12 +213,13 @@ void DlgSheetConf::accept() if (!binding) { break; } - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.%s.%s.%s', None)", - binding == PropertySheet::BindingNormal ? "Bind" - : "BindHiddenRef", - r.from().toString(), - r.to().toString()); + Gui::cmdAppObjectArgs( + sheet, + "setExpression('.cells.%s.%s.%s', None)", + binding == PropertySheet::BindingNormal ? "Bind" : "BindHiddenRef", + r.from().toString(), + r.to().toString() + ); } auto obj = path.getDocumentObject(); @@ -227,9 +231,11 @@ void DlgSheetConf::accept() std::string propName = path.getPropertyName(); QString groupName = ui->lineEditGroup->text().trimmed(); if (!prop) { - prop = obj->addDynamicProperty("App::PropertyEnumeration", - propName.c_str(), - groupName.toUtf8().constData()); + prop = obj->addDynamicProperty( + "App::PropertyEnumeration", + propName.c_str(), + groupName.toUtf8().constData() + ); } else if (groupName.size()) { obj->changeDynamicProperty(prop, groupName.toUtf8().constData(), nullptr); @@ -237,11 +243,13 @@ void DlgSheetConf::accept() prop->setStatus(App::Property::CopyOnChange, true); // Bind the enumeration items to the column of configuration names - Gui::cmdAppObjectArgs(obj, - "setExpression('%s.Enum', '%s.cells[<<%s>>]')", - propName, - sheet->getFullName(), - rangeConf); + Gui::cmdAppObjectArgs( + obj, + "setExpression('%s.Enum', '%s.cells[<<%s>>]')", + propName, + sheet->getFullName(), + rangeConf + ); Gui::cmdAppObjectArgs(obj, "recompute()"); @@ -249,10 +257,12 @@ void DlgSheetConf::accept() // could have just bind the entire row as below, but binding the first // cell separately using a simpler expression can make it easy for us // to extract the name of the PropertyEnumeration for editing or unsetup. - Gui::cmdAppObjectArgs(sheet, - "set('%s', '=hiddenref(%s.String)')", - from.toString(CellAddress::Cell::ShowRowColumn), - prop->getFullName()); + Gui::cmdAppObjectArgs( + sheet, + "set('%s', '=hiddenref(%s.String)')", + from.toString(CellAddress::Cell::ShowRowColumn), + prop->getFullName() + ); // Adjust the range to skip the first cell range = Range(from.row(), from.col() + 1, to.row(), to.col()); @@ -270,7 +280,8 @@ void DlgSheetConf::accept() from.row() + 2, range.to().toString(CellAddress::Cell::ShowColumn), prop->getFullName(), - from.row() + 2); + from.row() + 2 + ); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); Gui::Command::commitCommand(); @@ -307,17 +318,16 @@ void DlgSheetConf::onDiscard() if (!binding) { break; } - Gui::cmdAppObjectArgs(sheet, - "setExpression('.cells.%s.%s.%s', None)", - binding == PropertySheet::BindingNormal ? "Bind" - : "BindHiddenRef", - r.from().toString(), - r.to().toString()); + Gui::cmdAppObjectArgs( + sheet, + "setExpression('.cells.%s.%s.%s', None)", + binding == PropertySheet::BindingNormal ? "Bind" : "BindHiddenRef", + r.from().toString(), + r.to().toString() + ); } - Gui::cmdAppObjectArgs(sheet, - "clear('%s')", - from.toString(CellAddress::Cell::ShowRowColumn)); + Gui::cmdAppObjectArgs(sheet, "clear('%s')", from.toString(CellAddress::Cell::ShowRowColumn)); if (prop && prop->getName()) { auto obj = path.getDocumentObject(); diff --git a/src/Mod/Spreadsheet/Gui/DlgSheetConf.h b/src/Mod/Spreadsheet/Gui/DlgSheetConf.h index f8aa1775d0..d5ab0db2cf 100644 --- a/src/Mod/Spreadsheet/Gui/DlgSheetConf.h +++ b/src/Mod/Spreadsheet/Gui/DlgSheetConf.h @@ -46,11 +46,13 @@ public: void accept() override; - App::Property* prepare(App::CellAddress& from, - App::CellAddress& to, - std::string& rangeConf, - App::ObjectIdentifier& path, - bool init); + App::Property* prepare( + App::CellAddress& from, + App::CellAddress& to, + std::string& rangeConf, + App::ObjectIdentifier& path, + bool init + ); public Q_SLOTS: void onDiscard(); diff --git a/src/Mod/Spreadsheet/Gui/LineEdit.cpp b/src/Mod/Spreadsheet/Gui/LineEdit.cpp index ecd1145798..1b9883a075 100644 --- a/src/Mod/Spreadsheet/Gui/LineEdit.cpp +++ b/src/Mod/Spreadsheet/Gui/LineEdit.cpp @@ -55,8 +55,10 @@ void LineEdit::setDocumentObject(const App::DocumentObject* currentDocObj, bool QPointer active_view = Gui::MainWindow::getInstance()->activeWindow(); if (!active_view) { - Base::Console().developerWarning("LineEdit::setDocumentObject", - "The active view is not a spreadsheet"); + Base::Console().developerWarning( + "LineEdit::setDocumentObject", + "The active view is not a spreadsheet" + ); return; } QPointer zv = active_view->findChild(); @@ -86,8 +88,9 @@ void LineEdit::setDocumentObject(const App::DocumentObject* currentDocObj, bool auto getPopupPos = [proxy_lineedit, zv]() { - const QPointF scene_pos = - proxy_lineedit->mapToScene(proxy_lineedit->boundingRect().bottomLeft()); + const QPointF scene_pos = proxy_lineedit->mapToScene( + proxy_lineedit->boundingRect().bottomLeft() + ); const QPoint view_pos = zv->mapFromScene(scene_pos); const QPoint global_pos = zv->viewport()->mapToGlobal(view_pos); diff --git a/src/Mod/Spreadsheet/Gui/PreCompiled.h b/src/Mod/Spreadsheet/Gui/PreCompiled.h index d2d60e7f67..0cf699cc28 100644 --- a/src/Mod/Spreadsheet/Gui/PreCompiled.h +++ b/src/Mod/Spreadsheet/Gui/PreCompiled.h @@ -36,7 +36,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // Qt Toolkit diff --git a/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp b/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp index 9c5c32a3c4..9e47862958 100644 --- a/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp +++ b/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp @@ -37,9 +37,7 @@ using namespace App; using namespace Spreadsheet; using namespace SpreadsheetGui; -PropertiesDialog::PropertiesDialog(Sheet* _sheet, - const std::vector& _ranges, - QWidget* parent) +PropertiesDialog::PropertiesDialog(Sheet* _sheet, const std::vector& _ranges, QWidget* parent) : QDialog(parent) , sheet(_sheet) , ranges(_ranges) @@ -73,14 +71,12 @@ PropertiesDialog::PropertiesDialog(Sheet* _sheet, orgDisplayUnit = displayUnit; orgAlias = alias; - ui->foregroundColor->setCurrentColor(QColor::fromRgbF(foregroundColor.r, - foregroundColor.g, - foregroundColor.b, - foregroundColor.a)); - ui->backgroundColor->setCurrentColor(QColor::fromRgbF(backgroundColor.r, - backgroundColor.g, - backgroundColor.b, - backgroundColor.a)); + ui->foregroundColor->setCurrentColor( + QColor::fromRgbF(foregroundColor.r, foregroundColor.g, foregroundColor.b, foregroundColor.a) + ); + ui->backgroundColor->setCurrentColor( + QColor::fromRgbF(backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a) + ); if (alignment & Cell::ALIGNMENT_LEFT) { ui->alignLeft->setChecked(true); @@ -117,14 +113,18 @@ PropertiesDialog::PropertiesDialog(Sheet* _sheet, ui->alias->setText(QString::fromStdString(alias)); // Colors - connect(ui->foregroundColor, - &QtColorPicker::colorChanged, - this, - &PropertiesDialog::foregroundColorChanged); - connect(ui->backgroundColor, - &QtColorPicker::colorChanged, - this, - &PropertiesDialog::backgroundColorChanged); + connect( + ui->foregroundColor, + &QtColorPicker::colorChanged, + this, + &PropertiesDialog::foregroundColorChanged + ); + connect( + ui->backgroundColor, + &QtColorPicker::colorChanged, + this, + &PropertiesDialog::backgroundColorChanged + ); // Alignment connect(ui->alignLeft, &QRadioButton::clicked, this, &PropertiesDialog::alignmentChanged); @@ -223,7 +223,8 @@ void PropertiesDialog::displayUnitChanged(const QString& text) QPalette palette = ui->displayUnit->palette(); try { std::unique_ptr expr( - App::ExpressionParser::parseUnit(sheet, text.toUtf8().constData())); + App::ExpressionParser::parseUnit(sheet, text.toUtf8().constData()) + ); if (expr) { displayUnit = DisplayUnit(text.toStdString(), expr->getUnit(), expr->getScaler()); @@ -271,54 +272,62 @@ void PropertiesDialog::apply() for (; i != ranges.end(); ++i) { if (orgAlignment != alignment) { - Gui::cmdAppObjectArgs(sheet, - "setAlignment('%s', '%s')", - i->rangeString().c_str(), - Cell::encodeAlignment(alignment).c_str()); + Gui::cmdAppObjectArgs( + sheet, + "setAlignment('%s', '%s')", + i->rangeString().c_str(), + Cell::encodeAlignment(alignment).c_str() + ); changes = true; } if (orgStyle != style) { - Gui::cmdAppObjectArgs(sheet, - "setStyle('%s', '%s')", - i->rangeString().c_str(), - Cell::encodeStyle(style).c_str()); + Gui::cmdAppObjectArgs( + sheet, + "setStyle('%s', '%s')", + i->rangeString().c_str(), + Cell::encodeStyle(style).c_str() + ); changes = true; } if (orgForegroundColor != foregroundColor) { - Gui::cmdAppObjectArgs(sheet, - "setForeground('%s', (%f,%f,%f,%f))", - i->rangeString().c_str(), - foregroundColor.r, - foregroundColor.g, - foregroundColor.b, - foregroundColor.a); + Gui::cmdAppObjectArgs( + sheet, + "setForeground('%s', (%f,%f,%f,%f))", + i->rangeString().c_str(), + foregroundColor.r, + foregroundColor.g, + foregroundColor.b, + foregroundColor.a + ); changes = true; } if (orgBackgroundColor != backgroundColor) { - Gui::cmdAppObjectArgs(sheet, - "setBackground('%s', (%f,%f,%f,%f))", - i->rangeString().c_str(), - backgroundColor.r, - backgroundColor.g, - backgroundColor.b, - backgroundColor.a); + Gui::cmdAppObjectArgs( + sheet, + "setBackground('%s', (%f,%f,%f,%f))", + i->rangeString().c_str(), + backgroundColor.r, + backgroundColor.g, + backgroundColor.b, + backgroundColor.a + ); changes = true; } if (orgDisplayUnit != displayUnit) { - std::string escapedstr = - Base::Tools::escapedUnicodeFromUtf8(displayUnit.stringRep.c_str()); + std::string escapedstr = Base::Tools::escapedUnicodeFromUtf8( + displayUnit.stringRep.c_str() + ); escapedstr = Base::Tools::escapeQuotesFromString(escapedstr); - Gui::cmdAppObjectArgs(sheet, - "setDisplayUnit('%s', '%s')", - i->rangeString().c_str(), - escapedstr.c_str()); + Gui::cmdAppObjectArgs( + sheet, + "setDisplayUnit('%s', '%s')", + i->rangeString().c_str(), + escapedstr.c_str() + ); changes = true; } if (ranges.size() == 1 && ranges[0].size() == 1 && orgAlias != alias) { - Gui::cmdAppObjectArgs(sheet, - "setAlias('%s', '%s')", - i->address().c_str(), - alias.c_str()); + Gui::cmdAppObjectArgs(sheet, "setAlias('%s', '%s')", i->address().c_str(), alias.c_str()); changes = true; } } diff --git a/src/Mod/Spreadsheet/Gui/PropertiesDialog.h b/src/Mod/Spreadsheet/Gui/PropertiesDialog.h index cf1f4c877d..bdd6987250 100644 --- a/src/Mod/Spreadsheet/Gui/PropertiesDialog.h +++ b/src/Mod/Spreadsheet/Gui/PropertiesDialog.h @@ -41,9 +41,11 @@ class PropertiesDialog: public QDialog Q_OBJECT public: - explicit PropertiesDialog(Spreadsheet::Sheet* _sheet, - const std::vector& _ranges, - QWidget* parent = nullptr); + explicit PropertiesDialog( + Spreadsheet::Sheet* _sheet, + const std::vector& _ranges, + QWidget* parent = nullptr + ); ~PropertiesDialog() override; void apply(); diff --git a/src/Mod/Spreadsheet/Gui/SheetModel.cpp b/src/Mod/Spreadsheet/Gui/SheetModel.cpp index bb51bf4a72..d919edd398 100644 --- a/src/Mod/Spreadsheet/Gui/SheetModel.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetModel.cpp @@ -48,31 +48,34 @@ SheetModel::SheetModel(Sheet* _sheet, QObject* parent) , sheet(_sheet) { // NOLINTBEGIN - cellUpdatedConnection = - sheet->cellUpdated.connect(std::bind(&SheetModel::cellUpdated, this, sp::_1)); - rangeUpdatedConnection = - sheet->rangeUpdated.connect(std::bind(&SheetModel::rangeUpdated, this, sp::_1)); + cellUpdatedConnection = sheet->cellUpdated.connect( + std::bind(&SheetModel::cellUpdated, this, sp::_1) + ); + rangeUpdatedConnection = sheet->rangeUpdated.connect( + std::bind(&SheetModel::rangeUpdated, this, sp::_1) + ); // NOLINTEND ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Spreadsheet"); - aliasBgColor = - QColor(QString::fromStdString(hGrp->GetASCII("AliasedCellBackgroundColor", "#feff9e"))); + "User parameter:BaseApp/Preferences/Mod/Spreadsheet" + ); + aliasBgColor = QColor( + QString::fromStdString(hGrp->GetASCII("AliasedCellBackgroundColor", "#feff9e")) + ); textFgColor = QColor(QString::fromStdString(hGrp->GetASCII("TextColor", "#000000"))); - positiveFgColor = - QColor(QString::fromStdString(hGrp->GetASCII("PositiveNumberColor", "#000000"))); - negativeFgColor = - QColor(QString::fromStdString(hGrp->GetASCII("NegativeNumberColor", "#000000"))); + positiveFgColor = QColor(QString::fromStdString(hGrp->GetASCII("PositiveNumberColor", "#000000"))); + negativeFgColor = QColor(QString::fromStdString(hGrp->GetASCII("NegativeNumberColor", "#000000"))); - const QStringList alphabet { - QStringLiteral("A"), QStringLiteral("B"), QStringLiteral("C"), QStringLiteral("D"), - QStringLiteral("E"), QStringLiteral("F"), QStringLiteral("G"), QStringLiteral("H"), - QStringLiteral("I"), QStringLiteral("J"), QStringLiteral("K"), QStringLiteral("L"), - QStringLiteral("M"), QStringLiteral("N"), QStringLiteral("O"), QStringLiteral("P"), - QStringLiteral("Q"), QStringLiteral("R"), QStringLiteral("S"), QStringLiteral("T"), - QStringLiteral("U"), QStringLiteral("V"), QStringLiteral("W"), QStringLiteral("X"), - QStringLiteral("Y"), QStringLiteral("Z")}; + const QStringList alphabet {QStringLiteral("A"), QStringLiteral("B"), QStringLiteral("C"), + QStringLiteral("D"), QStringLiteral("E"), QStringLiteral("F"), + QStringLiteral("G"), QStringLiteral("H"), QStringLiteral("I"), + QStringLiteral("J"), QStringLiteral("K"), QStringLiteral("L"), + QStringLiteral("M"), QStringLiteral("N"), QStringLiteral("O"), + QStringLiteral("P"), QStringLiteral("Q"), QStringLiteral("R"), + QStringLiteral("S"), QStringLiteral("T"), QStringLiteral("U"), + QStringLiteral("V"), QStringLiteral("W"), QStringLiteral("X"), + QStringLiteral("Y"), QStringLiteral("Z")}; for (const QString& letter : alphabet) { columnLabels << letter; @@ -112,11 +115,13 @@ namespace QVariant formatCellDisplay(QString value, const Cell* cell) { std::string alias; - static auto hGrpSpreadsheet = - App::GetApplication().GetUserParameter().GetGroup("BaseApp/Preferences/Mod/Spreadsheet"); + static auto hGrpSpreadsheet = App::GetApplication().GetUserParameter().GetGroup( + "BaseApp/Preferences/Mod/Spreadsheet" + ); if (cell->getAlias(alias) && hGrpSpreadsheet->GetBool("showAliasName", false)) { QString formatStr = QString::fromStdString( - hGrpSpreadsheet->GetASCII("DisplayAliasFormatString", "%V = %A")); + hGrpSpreadsheet->GetASCII("DisplayAliasFormatString", "%V = %A") + ); if (formatStr.contains(QLatin1String("%V")) || formatStr.contains(QLatin1String("%A"))) { formatStr.replace(QLatin1String("%A"), QString::fromStdString(alias)); formatStr.replace(QLatin1String("%V"), value); @@ -183,7 +188,8 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const case Qt::DisplayRole: { #ifdef DEBUG_DEPS return QVariant::fromValue( - QStringLiteral("#ERR: %1").arg(Tools::fromStdString(cell->getException()))); + QStringLiteral("#ERR: %1").arg(Tools::fromStdString(cell->getException())) + ); #else std::string str; if (cell->getStringContent(str)) { @@ -220,7 +226,8 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const if (cell->getBackground(color)) { return QVariant::fromValue( - QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a)); + QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a) + ); } else { std::string alias; @@ -280,9 +287,11 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const if (!prop || dirty) { switch (role) { case Qt::ForegroundRole: { - return QColor(0, - 0, - 255.0); // TODO: Remove this hardcoded color, replace with preference + return QColor( + 0, + 0, + 255.0 + ); // TODO: Remove this hardcoded color, replace with preference } case Qt::TextAlignmentRole: { qtAlignment = Qt::AlignHCenter | Qt::AlignVCenter; @@ -320,7 +329,8 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const if (cell->getForeground(color)) { return QVariant::fromValue( - QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a)); + QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a) + ); } else { return QVariant(QColor(textFgColor)); @@ -355,7 +365,8 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const if (cell->getForeground(color)) { return QVariant::fromValue( - QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a)); + QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a) + ); } else { if (floatProp->getValue() < 0) { @@ -385,10 +396,11 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const // Display locale specific decimal separator (#0003875,#0003876) if (cell->getDisplayUnit(displayUnit)) { if (computedUnit == Base::Unit::One || computedUnit == displayUnit.unit) { - QString number = - QLocale().toString(floatProp->getValue() / displayUnit.scaler, - 'f', - Base::UnitsApi::getDecimals()); + QString number = QLocale().toString( + floatProp->getValue() / displayUnit.scaler, + 'f', + Base::UnitsApi::getDecimals() + ); // QString number = QString::number(floatProp->getValue() / // displayUnit.scaler); v = number + QString::fromStdString(" " + displayUnit.stringRep); @@ -431,7 +443,8 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const if (cell->getForeground(color)) { return QVariant::fromValue( - QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a)); + QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a) + ); } else { if (d < 0) { @@ -459,9 +472,11 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const // Display locale specific decimal separator (#0003875,#0003876) if (cell->getDisplayUnit(displayUnit)) { - QString number = QLocale().toString(d / displayUnit.scaler, - 'f', - Base::UnitsApi::getDecimals()); + QString number = QLocale().toString( + d / displayUnit.scaler, + 'f', + Base::UnitsApi::getDecimals() + ); // QString number = QString::number(d / displayUnit.scaler); v = number + QString::fromStdString(" " + displayUnit.stringRep); } @@ -487,7 +502,8 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const if (cell->getForeground(color)) { return QVariant::fromValue( - QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a)); + QColor(255.0 * color.r, 255.0 * color.g, 255.0 * color.b, 255.0 * color.a) + ); } else { return QVariant(QColor(textFgColor)); @@ -536,11 +552,12 @@ QVariant SheetModel::data(const QModelIndex& index, int role) const QVariant SheetModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::SizeHintRole) { - const int width = - (orientation == Qt::Horizontal ? sheet->getColumnWidth(section) - : PropertyColumnWidths::defaultHeaderWidth); - const int height = (orientation == Qt::Horizontal ? PropertyRowHeights::defaultHeight - : sheet->getRowHeight(section)); + const int width + = (orientation == Qt::Horizontal ? sheet->getColumnWidth(section) + : PropertyColumnWidths::defaultHeaderWidth); + const int height + = (orientation == Qt::Horizontal ? PropertyRowHeights::defaultHeight + : sheet->getRowHeight(section)); return QSize {width, height}; } if (role == Qt::DisplayRole) { @@ -588,11 +605,13 @@ bool SheetModel::setData(const QModelIndex& index, const QVariant& value, int ro } } - QMetaObject::invokeMethod(this, - "setCellData", - Qt::QueuedConnection, - Q_ARG(QModelIndex, index), - Q_ARG(QString, str)); + QMetaObject::invokeMethod( + this, + "setCellData", + Qt::QueuedConnection, + Q_ARG(QModelIndex, index), + Q_ARG(QString, str) + ); } return true; } diff --git a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp index 7fd2ab34b7..e7fb931511 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp @@ -142,8 +142,7 @@ SheetTableView::SheetTableView(QWidget* parent) connect(insertBefore, &QAction::triggered, this, &SheetTableView::insertRows); if (max < model()->rowCount() - 1) { - auto insertAfter = - menu.addAction(tr("Insert %n Row(s) Below", "", selection.size())); + auto insertAfter = menu.addAction(tr("Insert %n Row(s) Below", "", selection.size())); connect(insertAfter, &QAction::triggered, this, &SheetTableView::insertRowsAfter); } } @@ -169,17 +168,14 @@ SheetTableView::SheetTableView(QWidget* parent) connect(insertAbove, &QAction::triggered, this, &SheetTableView::insertColumns); if (max < model()->columnCount() - 1) { - auto insertAfter = - menu.addAction(tr("Insert %n Column(s) Right", "", selection.size())); - connect(insertAfter, - &QAction::triggered, - this, - &SheetTableView::insertColumnsAfter); + auto insertAfter = menu.addAction( + tr("Insert %n Column(s) Right", "", selection.size()) + ); + connect(insertAfter, &QAction::triggered, this, &SheetTableView::insertColumnsAfter); } } else { - auto insert = - menu.addAction(tr("Insert %n Non-Contiguous Columns", "", selection.size())); + auto insert = menu.addAction(tr("Insert %n Non-Contiguous Columns", "", selection.size())); connect(insert, &QAction::triggered, this, &SheetTableView::insertColumns); } auto remove = menu.addAction(tr("Remove Column(s)", "", selection.size())); @@ -197,24 +193,26 @@ SheetTableView::SheetTableView(QWidget* parent) actionProperties = createAction("", tr("Properties…"), &SheetTableView::cellProperties); contextMenu.addSeparator(); - actionRecompute = - createAction(":/icons/view-refresh.svg", tr("Recompute"), &SheetTableView::onRecompute); + actionRecompute + = createAction(":/icons/view-refresh.svg", tr("Recompute"), &SheetTableView::onRecompute); actionBind = createAction("", tr("Bind…"), &SheetTableView::onBind); actionConf = createAction("", tr("Configuration Table…"), &SheetTableView::onConfSetup); contextMenu.addSeparator(); - actionMerge = createAction(":/icons/SpreadsheetMergeCells.svg", - tr("Merge Cells"), - &SheetTableView::mergeCells); - actionSplit = createAction(":/icons/SpreadsheetSplitCell.svg", - tr("Split Cell"), - &SheetTableView::splitCell); + actionMerge = createAction( + ":/icons/SpreadsheetMergeCells.svg", + tr("Merge Cells"), + &SheetTableView::mergeCells + ); + actionSplit = createAction( + ":/icons/SpreadsheetSplitCell.svg", + tr("Split Cell"), + &SheetTableView::splitCell + ); contextMenu.addSeparator(); actionCut = createAction(":/icons/edit-cut.svg", tr("Cut"), &SheetTableView::cutSelection); actionCopy = createAction(":/icons/edit-copy.svg", tr("Copy"), &SheetTableView::copySelection); - actionPaste = - createAction(":/icons/edit-paste.svg", tr("Paste"), &SheetTableView::pasteClipboard); - actionDel = - createAction(":/icons/edit-delete.svg", tr("Delete"), &SheetTableView::deleteSelection); + actionPaste = createAction(":/icons/edit-paste.svg", tr("Paste"), &SheetTableView::pasteClipboard); + actionDel = createAction(":/icons/edit-delete.svg", tr("Delete"), &SheetTableView::deleteSelection); addAction(actionProperties); @@ -236,10 +234,12 @@ void SheetTableView::onRecompute() { Gui::Command::openCommand("Recompute Cells"); for (auto& range : selectedRanges()) { - Gui::cmdAppObjectArgs(sheet, - "recomputeCells('%s', '%s')", - range.fromCellString(), - range.toCellString()); + Gui::cmdAppObjectArgs( + sheet, + "recomputeCells('%s', '%s')", + range.fromCellString(), + range.toCellString() + ); } Gui::Command::commitCommand(); } @@ -453,10 +453,7 @@ void SheetTableView::insertColumnsAfter() Q_UNUSED(min) Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Insert Columns")); - Gui::cmdAppObjectArgs(sheet, - "insertColumns('%s', %d)", - columnName(max + 1).c_str(), - columns.size()); + Gui::cmdAppObjectArgs(sheet, "insertColumns('%s', %d)", columnName(max + 1).c_str(), columns.size()); Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); } @@ -684,10 +681,12 @@ void SheetTableView::deleteSelection() std::vector::const_iterator i = ranges.begin(); for (; i != ranges.end(); ++i) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.clear('%s')", - sheet->getNameInDocument(), - i->rangeString().c_str()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.clear('%s')", + sheet->getNameInDocument(), + i->rangeString().c_str() + ); } Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); Gui::Command::commitCommand(); @@ -811,17 +810,17 @@ void SheetTableView::pasteClipboard() } catch (Base::Exception& e) { e.reportException(); - QMessageBox::critical(Gui::getMainWindow(), - QObject::tr("Copy & Paste Failed"), - QString::fromLatin1(e.what())); + QMessageBox::critical( + Gui::getMainWindow(), + QObject::tr("Copy & Paste Failed"), + QString::fromLatin1(e.what()) + ); return; } clearSelection(); } -void SheetTableView::finishEditWithMove(int keyPressed, - Qt::KeyboardModifiers modifiers, - bool handleTabMotion) +void SheetTableView::finishEditWithMove(int keyPressed, Qt::KeyboardModifiers modifiers, bool handleTabMotion) { // A utility lambda for finding the beginning and ending of data regions auto scanForRegionBoundary = [this](int& r, int& c, int dr, int dc) { @@ -935,8 +934,8 @@ void SheetTableView::finishEditWithMove(int keyPressed, scanForRegionBoundary(targetRow, targetColumn, 0, 1); } else { - targetColumn += - colSpan; // Unrecognized modifier combination: default to just moving one cell + targetColumn += colSpan; // Unrecognized modifier combination: default to just + // moving one cell } tabCounter = 0; break; @@ -968,8 +967,8 @@ void SheetTableView::finishEditWithMove(int keyPressed, scanForRegionBoundary(targetRow, targetColumn, 1, 0); } else { - targetRow += - rowSpan; // Unrecognized modifier combination: default to just moving one cell + targetRow += rowSpan; // Unrecognized modifier combination: default to just moving + // one cell } tabCounter = 0; break; @@ -1013,8 +1012,10 @@ void SheetTableView::finishEditWithMove(int keyPressed, || keyPressed == Qt::Key_Return) { // We have to use this method so that Ctrl-modifier combinations don't result in multiple // selection - this->selectionModel()->setCurrentIndex(model()->index(targetRow, targetColumn), - QItemSelectionModel::ClearAndSelect); + this->selectionModel()->setCurrentIndex( + model()->index(targetRow, targetColumn), + QItemSelectionModel::ClearAndSelect + ); } else if (modifiers & Qt::ShiftModifier) { // With shift down, this motion becomes a block selection command, rather than just simple @@ -1065,16 +1066,20 @@ void SheetTableView::ModifyBlockSelection(int targetRow, int targetCol) } QItemSelection oldRange(range.topLeft(), range.bottomRight()); this->selectionModel()->select(oldRange, QItemSelectionModel::Deselect); - QItemSelection newRange(model()->index(rangeMinRow, rangeMinCol), - model()->index(rangeMaxRow, rangeMaxCol)); + QItemSelection newRange( + model()->index(rangeMinRow, rangeMinCol), + model()->index(rangeMaxRow, rangeMaxCol) + ); this->selectionModel()->select(newRange, QItemSelectionModel::Select); } break; } } - this->selectionModel()->setCurrentIndex(model()->index(targetRow, targetCol), - QItemSelectionModel::Current); + this->selectionModel()->setCurrentIndex( + model()->index(targetRow, targetCol), + QItemSelectionModel::Current + ); } void SheetTableView::mergeCells() @@ -1098,8 +1103,7 @@ void SheetTableView::mousePressEvent(QMouseEvent* event) QTableView::mousePressEvent(event); } -void SheetTableView::selectionChanged(const QItemSelection& selected, - const QItemSelection& deselected) +void SheetTableView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) { Gui::getMainWindow()->updateActions(); QTableView::selectionChanged(selected, deselected); @@ -1129,7 +1133,8 @@ void SheetTableView::contextMenuEvent(QContextMenuEvent*) actionDel->setEnabled(true); actionSplit->setEnabled( selectedIndexesRaw().size() == 1 - && sheet->isMergedCell(CellAddress(currentIndex().row(), currentIndex().column()))); + && sheet->isMergedCell(CellAddress(currentIndex().row(), currentIndex().column())) + ); actionMerge->setEnabled(selectedIndexesRaw().size() > 1); } diff --git a/src/Mod/Spreadsheet/Gui/SheetTableView.h b/src/Mod/Spreadsheet/Gui/SheetTableView.h index 913f71c05a..063a24ae5c 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableView.h +++ b/src/Mod/Spreadsheet/Gui/SheetTableView.h @@ -78,9 +78,7 @@ public Q_SLOTS: void copySelection(); void cutSelection(); void pasteClipboard(); - void finishEditWithMove(int keyPressed, - Qt::KeyboardModifiers modifiers, - bool handleTabMotion = false); + void finishEditWithMove(int keyPressed, Qt::KeyboardModifiers modifiers, bool handleTabMotion = false); void ModifyBlockSelection(int targetRow, int targetColumn); protected Q_SLOTS: @@ -102,8 +100,7 @@ protected: bool event(QEvent* event) override; void closeEditor(QWidget* editor, QAbstractItemDelegate::EndEditHint hint) override; void mousePressEvent(QMouseEvent* event) override; - void selectionChanged(const QItemSelection& selected, - const QItemSelection& deselected) override; + void selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) override; void contextMenuEvent(QContextMenuEvent* e) override; diff --git a/src/Mod/Spreadsheet/Gui/SheetTableViewAccessibleInterface.cpp b/src/Mod/Spreadsheet/Gui/SheetTableViewAccessibleInterface.cpp index 86d1e01bee..8782be67d0 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableViewAccessibleInterface.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetTableViewAccessibleInterface.cpp @@ -39,7 +39,8 @@ namespace SpreadsheetGui { SheetTableViewAccessibleInterface::SheetTableViewAccessibleInterface( - SpreadsheetGui::SheetTableView* view) + SpreadsheetGui::SheetTableView* view +) : QAccessibleWidget(view) {} @@ -82,8 +83,7 @@ QAccessibleInterface* SheetTableViewAccessibleInterface::child(int index) const QAccessibleInterface* SheetTableViewAccessibleInterface::ifactory(const QString& key, QObject* obj) { if (key == QStringLiteral("SpreadsheetGui::SheetTableView")) { - return new SheetTableViewAccessibleInterface( - static_cast(obj)); + return new SheetTableViewAccessibleInterface(static_cast(obj)); } return nullptr; } diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.cpp b/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.cpp index 956963fd70..eff6385a4e 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.cpp +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.cpp @@ -47,9 +47,11 @@ SpreadsheetDelegate::SpreadsheetDelegate(Spreadsheet::Sheet* _sheet, QWidget* pa , sheet(_sheet) {} -QWidget* SpreadsheetDelegate::createEditor(QWidget* parent, - const QStyleOptionViewItem&, - const QModelIndex& index) const +QWidget* SpreadsheetDelegate::createEditor( + QWidget* parent, + const QStyleOptionViewItem&, + const QModelIndex& index +) const { App::CellAddress addr(index.row(), index.column()); App::Range range(addr, addr); @@ -60,10 +62,12 @@ QWidget* SpreadsheetDelegate::createEditor(QWidget* parent, SpreadsheetGui::LineEdit* editor = new SpreadsheetGui::LineEdit(parent); editor->setDocumentObject(sheet); - connect(editor, - &SpreadsheetGui::LineEdit::finishedWithKey, - this, - &SpreadsheetDelegate::onEditorFinishedWithKey); + connect( + editor, + &SpreadsheetGui::LineEdit::finishedWithKey, + this, + &SpreadsheetDelegate::onEditorFinishedWithKey + ); return editor; } @@ -76,9 +80,11 @@ void SpreadsheetDelegate::setEditorData(QWidget* editor, const QModelIndex& inde } } -void SpreadsheetDelegate::setModelData(QWidget* editor, - QAbstractItemModel* model, - const QModelIndex& index) const +void SpreadsheetDelegate::setModelData( + QWidget* editor, + QAbstractItemModel* model, + const QModelIndex& index +) const { QLineEdit* edit = qobject_cast(editor); if (edit) { @@ -92,11 +98,13 @@ void SpreadsheetDelegate::onEditorFinishedWithKey(int key, Qt::KeyboardModifiers Q_EMIT finishedWithKey(key, modifiers); } -static inline void drawBorder(QPainter* painter, - const QStyleOptionViewItem& option, - unsigned flags, - QColor color, - Qt::PenStyle style) +static inline void drawBorder( + QPainter* painter, + const QStyleOptionViewItem& option, + unsigned flags, + QColor color, + Qt::PenStyle style +) { if (!flags) { return; @@ -125,9 +133,11 @@ static inline void drawBorder(QPainter* painter, } } -void SpreadsheetDelegate::paint(QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex& index) const +void SpreadsheetDelegate::paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index +) const { QStyledItemDelegate::paint(painter, option, index); if (!sheet) { diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h b/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h index ac4810c0a7..60ed2cf5cd 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h @@ -42,16 +42,18 @@ class SpreadsheetDelegate: public QStyledItemDelegate Q_OBJECT public: explicit SpreadsheetDelegate(Spreadsheet::Sheet* sheet, QWidget* parent = nullptr); - QWidget* createEditor(QWidget* parent, - const QStyleOptionViewItem&, - const QModelIndex& index) const override; + QWidget* createEditor( + QWidget* parent, + const QStyleOptionViewItem&, + const QModelIndex& index + ) const override; void setEditorData(QWidget* editor, const QModelIndex& index) const override; - void setModelData(QWidget* editor, - QAbstractItemModel* model, - const QModelIndex& index) const override; - void paint(QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex& index) const override; + void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; + void paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override; Q_SIGNALS: void finishedWithKey(int key, Qt::KeyboardModifiers modifiers); diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp b/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp index 1bba9f814b..4f2f6d0549 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp @@ -84,33 +84,30 @@ SheetView::SheetView(Gui::Document* pcDocument, App::DocumentObject* docObj, QWi ui->cells->setSheet(sheet); // Connect signals - connect(ui->cells->selectionModel(), - &QItemSelectionModel::currentChanged, - this, - &SheetView::currentChanged); + connect( + ui->cells->selectionModel(), + &QItemSelectionModel::currentChanged, + this, + &SheetView::currentChanged + ); - connect(qobject_cast(ui->cells->horizontalHeader()), - &SheetViewHeader::resizeFinished, - this, - &SheetView::columnResizeFinished); - connect(ui->cells->horizontalHeader(), - &QHeaderView::sectionResized, - this, - &SheetView::columnResized); + connect( + qobject_cast(ui->cells->horizontalHeader()), + &SheetViewHeader::resizeFinished, + this, + &SheetView::columnResizeFinished + ); + connect(ui->cells->horizontalHeader(), &QHeaderView::sectionResized, this, &SheetView::columnResized); - connect(qobject_cast(ui->cells->verticalHeader()), - &SheetViewHeader::resizeFinished, - this, - &SheetView::rowResizeFinished); - connect(ui->cells->verticalHeader(), - &QHeaderView::sectionResized, - this, - &SheetView::rowResized); + connect( + qobject_cast(ui->cells->verticalHeader()), + &SheetViewHeader::resizeFinished, + this, + &SheetView::rowResizeFinished + ); + connect(ui->cells->verticalHeader(), &QHeaderView::sectionResized, this, &SheetView::rowResized); - connect(delegate, - &SpreadsheetDelegate::finishedWithKey, - this, - &SheetView::editingFinishedWithKey); + connect(delegate, &SpreadsheetDelegate::finishedWithKey, this, &SheetView::editingFinishedWithKey); connect(ui->cellContent, &ExpressionLineEdit::returnPressed, this, [this]() { confirmContentChanged(ui->cellContent->text()); }); @@ -121,9 +118,11 @@ SheetView::SheetView(Gui::Document* pcDocument, App::DocumentObject* docObj, QWi // NOLINTBEGIN columnWidthChangedConnection = sheet->columnWidthChanged.connect( - std::bind(&SheetView::resizeColumn, this, sp::_1, sp::_2)); - rowHeightChangedConnection = - sheet->rowHeightChanged.connect(std::bind(&SheetView::resizeRow, this, sp::_1, sp::_2)); + std::bind(&SheetView::resizeColumn, this, sp::_1, sp::_2) + ); + rowHeightChangedConnection = sheet->rowHeightChanged.connect( + std::bind(&SheetView::resizeRow, this, sp::_1, sp::_2) + ); // NOLINTEND connect(model, &QAbstractItemModel::dataChanged, this, &SheetView::modelUpdated); @@ -134,13 +133,15 @@ SheetView::SheetView(Gui::Document* pcDocument, App::DocumentObject* docObj, QWi ui->cells->setPalette(palette); QList bgList = Gui::getMainWindow()->findChildren( - QStringLiteral("Spreadsheet_BackgroundColor")); + QStringLiteral("Spreadsheet_BackgroundColor") + ); if (!bgList.empty()) { bgList[0]->setCurrentColor(palette.color(QPalette::Base)); } QList fgList = Gui::getMainWindow()->findChildren( - QStringLiteral("Spreadsheet_ForegroundColor")); + QStringLiteral("Spreadsheet_ForegroundColor") + ); if (!fgList.empty()) { fgList[0]->setCurrentColor(palette.color(QPalette::Text)); } @@ -276,10 +277,7 @@ void SheetView::printPreview() QPrinter printer(QPrinter::ScreenResolution); printer.setPageOrientation(QPageLayout::Landscape); QPrintPreviewDialog dlg(&printer, this); - connect(&dlg, - &QPrintPreviewDialog::paintRequested, - this, - qOverload(&SheetView::print)); + connect(&dlg, &QPrintPreviewDialog::paintRequested, this, qOverload(&SheetView::print)); dlg.exec(); } @@ -298,11 +296,12 @@ void SheetView::print(QPrinter* printer) */ void SheetView::printPdf() { - QString filename = - FileDialog::getSaveFileName(this, - tr("Export PDF"), - QString(), - QStringLiteral("%1 (*.pdf)").arg(tr("PDF file"))); + QString filename = FileDialog::getSaveFileName( + this, + tr("Export PDF"), + QString(), + QStringLiteral("%1 (*.pdf)").arg(tr("PDF file")) + ); if (!filename.isEmpty()) { QPrinter printer(QPrinter::ScreenResolution); // setPdfVersion sets the printed PDF Version to what is chosen in @@ -498,8 +497,11 @@ void SheetView::aliasChanged(const QString& text) else { // go back to normal ui->cellAlias->setToolTip( - QObject::tr("Refer to cell by alias, for example\nSpreadsheet.my_alias_name instead of " - "Spreadsheet.B1")); + QObject::tr( + "Refer to cell by alias, for example\nSpreadsheet.my_alias_name instead of " + "Spreadsheet.B1" + ) + ); ui->cellAlias->setStyleSheet(originalStylesheet); } } @@ -551,20 +553,24 @@ QModelIndexList SheetView::selectedIndexesRaw() const return ui->cells->selectedIndexesRaw(); } -void SpreadsheetGui::SheetView::select(App::CellAddress cell, - QItemSelectionModel::SelectionFlags flags) +void SpreadsheetGui::SheetView::select(App::CellAddress cell, QItemSelectionModel::SelectionFlags flags) { ui->cells->selectionModel()->select(model->index(cell.row(), cell.col()), flags); } -void SpreadsheetGui::SheetView::select(App::CellAddress topLeft, - App::CellAddress bottomRight, - QItemSelectionModel::SelectionFlags flags) +void SpreadsheetGui::SheetView::select( + App::CellAddress topLeft, + App::CellAddress bottomRight, + QItemSelectionModel::SelectionFlags flags +) { ui->cells->selectionModel()->select( - QItemSelection(model->index(topLeft.row(), topLeft.col()), - model->index(bottomRight.row(), bottomRight.col())), - flags); + QItemSelection( + model->index(topLeft.row(), topLeft.col()), + model->index(bottomRight.row(), bottomRight.col()) + ), + flags + ); } void SheetView::deleteSelection() @@ -608,30 +614,36 @@ void SheetViewPy::init_type() behaviors().supportGetattr(); behaviors().supportSetattr(); - add_varargs_method("selectedRanges", - &SheetViewPy::selectedRanges, - "selectedRanges(): Get a list of all selected ranges"); - add_varargs_method("selectedCells", - &SheetViewPy::selectedCells, - "selectedCells(): Get a list of all selected cells"); + add_varargs_method( + "selectedRanges", + &SheetViewPy::selectedRanges, + "selectedRanges(): Get a list of all selected ranges" + ); + add_varargs_method( + "selectedCells", + &SheetViewPy::selectedCells, + "selectedCells(): Get a list of all selected cells" + ); add_varargs_method( "select", &SheetViewPy::select, "select(cell,flags): Select (or deselect) the given cell, applying " "QItemSelectionModel.SelectionFlags\nselect(topLeft,bottomRight,flags): Select (or " - "deselect) the given range, applying QItemSelectionModel.SelectionFlags"); - add_varargs_method("currentIndex", - &SheetViewPy::currentIndex, - "currentIndex(): Get the current index"); + "deselect) the given range, applying QItemSelectionModel.SelectionFlags" + ); + add_varargs_method( + "currentIndex", + &SheetViewPy::currentIndex, + "currentIndex(): Get the current index" + ); add_varargs_method( "setCurrentIndex", &SheetViewPy::setCurrentIndex, - "setCurrentIndex(cell): Set the current index to the named cell (e.g. 'A1')"); + "setCurrentIndex(cell): Set the current index to the named cell (e.g. 'A1')" + ); add_varargs_method("getSheet", &SheetViewPy::getSheet, "getSheet()"); - add_varargs_method("cast_to_base", - &SheetViewPy::cast_to_base, - "cast_to_base() cast to MDIView class"); + add_varargs_method("cast_to_base", &SheetViewPy::cast_to_base, "cast_to_base() cast to MDIView class"); behaviors().readyType(); } @@ -739,27 +751,37 @@ Py::Object SheetViewPy::select(const Py::Tuple& _args) const char* bottomRight; int flags = 0; if (args.size() == 2 && PyArg_ParseTuple(_args.ptr(), "si", &cell, &flags)) { - sheetView->select(App::CellAddress(cell), - static_cast(flags)); + sheetView->select( + App::CellAddress(cell), + static_cast(flags) + ); } else if (args.size() == 3 && PyArg_ParseTuple(_args.ptr(), "ssi", &topLeft, &bottomRight, &flags)) { - sheetView->select(App::CellAddress(topLeft), - App::CellAddress(bottomRight), - static_cast(flags)); + sheetView->select( + App::CellAddress(topLeft), + App::CellAddress(bottomRight), + static_cast(flags) + ); } else { if (args.size() == 2) { - throw Base::TypeError("Expects the arguments to be a cell name (e.g. 'A1') and " - "QItemSelectionModel.SelectionFlags"); + throw Base::TypeError( + "Expects the arguments to be a cell name (e.g. 'A1') and " + "QItemSelectionModel.SelectionFlags" + ); } else if (args.size() == 3) { - throw Base::TypeError("Expects the arguments to be a cell name (e.g. 'A1'), a second " - "cell name (e.g. 'B5'), and QItemSelectionModel.SelectionFlags"); + throw Base::TypeError( + "Expects the arguments to be a cell name (e.g. 'A1'), a second " + "cell name (e.g. 'B5'), and QItemSelectionModel.SelectionFlags" + ); } else { - throw Base::TypeError("Wrong arguments to select: specify either a cell, or two cells " - "(for a range), and QItemSelectionModel.SelectionFlags"); + throw Base::TypeError( + "Wrong arguments to select: specify either a cell, or two cells " + "(for a range), and QItemSelectionModel.SelectionFlags" + ); } } return Py::None(); diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetView.h b/src/Mod/Spreadsheet/Gui/SpreadsheetView.h index 431b5e0b4d..2870ed380e 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetView.h +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetView.h @@ -100,9 +100,11 @@ public: void select(App::CellAddress cell, QItemSelectionModel::SelectionFlags flags); - void select(App::CellAddress topLeft, - App::CellAddress bottomRight, - QItemSelectionModel::SelectionFlags flags); + void select( + App::CellAddress topLeft, + App::CellAddress bottomRight, + QItemSelectionModel::SelectionFlags flags + ); QModelIndex currentIndex() const; diff --git a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp index 5608c649a8..6009a61b1b 100644 --- a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp +++ b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp @@ -105,11 +105,13 @@ void ViewProviderSheet::exportAsFile() auto* sheet = getObject(); QString selectedFilter; QString formatList = QObject::tr("CSV (*.csv *.CSV);;All (*)"); - QString fileName = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), - QObject::tr("Export File"), - QString(), - formatList, - &selectedFilter); + QString fileName = Gui::FileDialog::getSaveFileName( + Gui::getMainWindow(), + QObject::tr("Export File"), + QString(), + formatList, + &selectedFilter + ); if (!fileName.isEmpty()) { if (sheet) { char delim = '\0'; diff --git a/src/Mod/Spreadsheet/Gui/Workbench.cpp b/src/Mod/Spreadsheet/Gui/Workbench.cpp index db201148e1..8395679abd 100644 --- a/src/Mod/Spreadsheet/Gui/Workbench.cpp +++ b/src/Mod/Spreadsheet/Gui/Workbench.cpp @@ -67,8 +67,9 @@ Workbench::~Workbench() = default; void Workbench::activated() { if (!initialized) { - QList bars = - Gui::getMainWindow()->findChildren(QStringLiteral("Spreadsheet")); + QList bars = Gui::getMainWindow()->findChildren( + QStringLiteral("Spreadsheet") + ); if (bars.size() == 1) { QToolBar* bar = bars[0]; @@ -77,7 +78,8 @@ void Workbench::activated() QPalette palette = Gui::getMainWindow()->palette(); QList fgList = Gui::getMainWindow()->findChildren( - QStringLiteral("Spreadsheet_ForegroundColor")); + QStringLiteral("Spreadsheet_ForegroundColor") + ); if (!fgList.empty()) { foregroundColor = fgList[0]; } @@ -86,10 +88,12 @@ void Workbench::activated() foregroundColor->setObjectName(QStringLiteral("Spreadsheet_ForegroundColor")); foregroundColor->setStandardColors(); foregroundColor->setCurrentColor(palette.color(QPalette::WindowText)); - QObject::connect(foregroundColor, - &QtColorPicker::colorSet, - workbenchHelper.get(), - &WorkbenchHelper::setForegroundColor); + QObject::connect( + foregroundColor, + &QtColorPicker::colorSet, + workbenchHelper.get(), + &WorkbenchHelper::setForegroundColor + ); } foregroundColor->setToolTip(QObject::tr("Sets the text color of cells")); foregroundColor->setWhatsThis(QObject::tr("Sets the text color of spreadsheet cells")); @@ -97,7 +101,8 @@ void Workbench::activated() bar->addWidget(foregroundColor); QList bgList = Gui::getMainWindow()->findChildren( - QStringLiteral("Spreadsheet_BackgroundColor")); + QStringLiteral("Spreadsheet_BackgroundColor") + ); if (!bgList.empty()) { backgroundColor = bgList[0]; } @@ -106,14 +111,15 @@ void Workbench::activated() backgroundColor->setObjectName(QStringLiteral("Spreadsheet_BackgroundColor")); backgroundColor->setStandardColors(); backgroundColor->setCurrentColor(palette.color(QPalette::Base)); - QObject::connect(backgroundColor, - &QtColorPicker::colorSet, - workbenchHelper.get(), - &WorkbenchHelper::setBackgroundColor); + QObject::connect( + backgroundColor, + &QtColorPicker::colorSet, + workbenchHelper.get(), + &WorkbenchHelper::setBackgroundColor + ); } backgroundColor->setToolTip(QObject::tr("Sets the background color of cells")); - backgroundColor->setWhatsThis( - QObject::tr("Sets the spreadsheet cells background color")); + backgroundColor->setWhatsThis(QObject::tr("Sets the spreadsheet cells background color")); backgroundColor->setStatusTip(QObject::tr("Sets the background color of cells")); bar->addWidget(backgroundColor); @@ -128,8 +134,7 @@ void WorkbenchHelper::setForegroundColor(const QColor& color) if (doc) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -141,13 +146,15 @@ void WorkbenchHelper::setForegroundColor(const QColor& color) Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Set text color")); for (; i != ranges.end(); ++i) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.setForeground('%s', (%f,%f,%f))", - sheet->getNameInDocument(), - i->rangeString().c_str(), - color.redF(), - color.greenF(), - color.blueF()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.setForeground('%s', (%f,%f,%f))", + sheet->getNameInDocument(), + i->rangeString().c_str(), + color.redF(), + color.greenF(), + color.blueF() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); @@ -162,8 +169,7 @@ void WorkbenchHelper::setBackgroundColor(const QColor& color) if (doc) { Gui::MDIView* activeWindow = Gui::getMainWindow()->activeWindow(); - SpreadsheetGui::SheetView* sheetView = - freecad_cast(activeWindow); + SpreadsheetGui::SheetView* sheetView = freecad_cast(activeWindow); if (sheetView) { Sheet* sheet = sheetView->getSheet(); @@ -175,13 +181,15 @@ void WorkbenchHelper::setBackgroundColor(const QColor& color) Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Set background color")); for (; i != ranges.end(); ++i) { - Gui::Command::doCommand(Gui::Command::Doc, - "App.ActiveDocument.%s.setBackground('%s', (%f,%f,%f))", - sheet->getNameInDocument(), - i->rangeString().c_str(), - color.redF(), - color.greenF(), - color.blueF()); + Gui::Command::doCommand( + Gui::Command::Doc, + "App.ActiveDocument.%s.setBackground('%s', (%f,%f,%f))", + sheet->getNameInDocument(), + i->rangeString().c_str(), + color.redF(), + color.greenF(), + color.blueF() + ); } Gui::Command::commitCommand(); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.recompute()"); diff --git a/src/Mod/Spreadsheet/Gui/ZoomableView.cpp b/src/Mod/Spreadsheet/Gui/ZoomableView.cpp index 82988cce34..a5842a5560 100644 --- a/src/Mod/Spreadsheet/Gui/ZoomableView.cpp +++ b/src/Mod/Spreadsheet/Gui/ZoomableView.cpp @@ -40,8 +40,10 @@ ZoomableView::ZoomableView(Ui::Sheet* ui) else { QLayoutItem* li_stv = stv->parentWidget()->layout()->replaceWidget(stv, this); if (li_stv == nullptr) { - Base::Console().developerWarning("ZoomableView", - "Failed to replace the SheetTableView object"); + Base::Console().developerWarning( + "ZoomableView", + "Failed to replace the SheetTableView object" + ); deleteLater(); return; } @@ -88,21 +90,20 @@ ZoomableView::ZoomableView(Ui::Sheet* ui) connect(dummySB_h, &QAbstractSlider::valueChanged, this, &ZoomableView::updateView); connect(dummySB_v, &QAbstractSlider::valueChanged, this, &ZoomableView::updateView); - connect(this, - &ZoomableView::zoomLevelChanged, - ui->zoomTB, - [zoomTB = ui->zoomTB](int new_zoomLevel) { - zoomTB->setText(QStringLiteral("%1%").arg(new_zoomLevel)); - }); + connect(this, &ZoomableView::zoomLevelChanged, ui->zoomTB, [zoomTB = ui->zoomTB](int new_zoomLevel) { + zoomTB->setText(QStringLiteral("%1%").arg(new_zoomLevel)); + }); - connect(this, - &ZoomableView::zoomLevelChanged, - ui->zoomSlider, - [zoomSlider = ui->zoomSlider](int new_zoomLevel) { - zoomSlider->blockSignals(true); - zoomSlider->setValue(new_zoomLevel); - zoomSlider->blockSignals(false); - }); + connect( + this, + &ZoomableView::zoomLevelChanged, + ui->zoomSlider, + [zoomSlider = ui->zoomSlider](int new_zoomLevel) { + zoomSlider->blockSignals(true); + zoomSlider->setValue(new_zoomLevel); + zoomSlider->blockSignals(false); + } + ); connect(ui->zoomPlus, &QToolButton::clicked, this, &ZoomableView::zoomIn); connect(ui->zoomSlider, &QSlider::valueChanged, this, &ZoomableView::setZoomLevel); @@ -113,8 +114,7 @@ ZoomableView::ZoomableView(Ui::Sheet* ui) constexpr int min = ZoomableView::min, max = ZoomableView::max, step = 10; const int val = zoomSlider->value(); bool ok; - const int new_val = - QInputDialog::getInt(zoomSlider, title, label, val, min, max, step, &ok); + const int new_val = QInputDialog::getInt(zoomSlider, title, label, val, min, max, step, &ok); if (ok) { zoomSlider->setValue(new_val); @@ -125,12 +125,12 @@ ZoomableView::ZoomableView(Ui::Sheet* ui) auto connectCursorChangedSignal = [this](QHeaderView* hv) { auto header = qobject_cast(hv); - connect(header, - &SpreadsheetGui::SheetViewHeader::cursorChanged, - this, - [this](const QCursor& newerCursor) { - qpw->setCursor(newerCursor); - }); + connect( + header, + &SpreadsheetGui::SheetViewHeader::cursorChanged, + this, + [this](const QCursor& newerCursor) { qpw->setCursor(newerCursor); } + ); }; connectCursorChangedSignal(stv->horizontalHeader()); connectCursorChangedSignal(stv->verticalHeader()); diff --git a/src/Mod/Spreadsheet/Gui/ZoomableView.h b/src/Mod/Spreadsheet/Gui/ZoomableView.h index 0992690288..673d84ba97 100644 --- a/src/Mod/Spreadsheet/Gui/ZoomableView.h +++ b/src/Mod/Spreadsheet/Gui/ZoomableView.h @@ -58,9 +58,8 @@ Q_SIGNALS: /// used to show the zoom level in the zoom button. public Q_SLOTS: - void zoomIn(void); /// This function is the slot for the zoomIn button and a keyboard shortcut - void - zoomOut(void); /// This function is the slot for the zoomOut button and a keyboard shortcut + void zoomIn(void); /// This function is the slot for the zoomIn button and a keyboard shortcut + void zoomOut(void); /// This function is the slot for the zoomOut button and a keyboard shortcut void resetZoom(void); /// This function is the slot for a keyboard shortcut private: diff --git a/src/Mod/Spreadsheet/SpreadsheetGlobal.h b/src/Mod/Spreadsheet/SpreadsheetGlobal.h index 9ea7cfa3a8..c0e9b15e27 100644 --- a/src/Mod/Spreadsheet/SpreadsheetGlobal.h +++ b/src/Mod/Spreadsheet/SpreadsheetGlobal.h @@ -30,20 +30,20 @@ // Spreadsheet #ifndef SpreadsheetExport -#ifdef Spreadsheet_EXPORTS -#define SpreadsheetExport FREECAD_DECL_EXPORT -#else -#define SpreadsheetExport FREECAD_DECL_IMPORT -#endif +# ifdef Spreadsheet_EXPORTS +# define SpreadsheetExport FREECAD_DECL_EXPORT +# else +# define SpreadsheetExport FREECAD_DECL_IMPORT +# endif #endif // SpreadsheetGui #ifndef SpreadsheetGuiExport -#ifdef SpreadsheetGui_EXPORTS -#define SpreadsheetGuiExport FREECAD_DECL_EXPORT -#else -#define SpreadsheetGuiExport FREECAD_DECL_IMPORT -#endif +# ifdef SpreadsheetGui_EXPORTS +# define SpreadsheetGuiExport FREECAD_DECL_EXPORT +# else +# define SpreadsheetGuiExport FREECAD_DECL_IMPORT +# endif #endif #endif // SPREADSHEET_GLOBAL_H diff --git a/src/Mod/Start/App/CustomFolderModel.cpp b/src/Mod/Start/App/CustomFolderModel.cpp index 1439591a08..cfbfffe23a 100644 --- a/src/Mod/Start/App/CustomFolderModel.cpp +++ b/src/Mod/Start/App/CustomFolderModel.cpp @@ -35,7 +35,8 @@ CustomFolderModel::CustomFolderModel(QObject* parent) { Base::Reference parameterGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); _customFolderPathSpec = QString::fromStdString(parameterGroup->GetASCII("CustomFolder", "")); @@ -58,21 +59,25 @@ void CustomFolderModel::loadCustomFolder() if (!customFolderDirectory.exists()) { Base::Console().warning( "BaseApp/Preferences/Mod/Start/CustomFolder: custom folder %s does not exist\n", - customFolderDirectory.absolutePath().toStdString().c_str()); + customFolderDirectory.absolutePath().toStdString().c_str() + ); continue; } if (!customFolderDirectory.isReadable()) { Base::Console().warning( "BaseApp/Preferences/Mod/Start/CustomFolder: cannot read custom folder %s\n", - customFolderDirectory.absolutePath().toStdString().c_str()); + customFolderDirectory.absolutePath().toStdString().c_str() + ); continue; } if (_showOnlyFCStd) { customFolderDirectory.setNameFilters(QStringList() << QStringLiteral("*.FCStd")); } - auto entries = customFolderDirectory.entryList(QDir::Filter::Files | QDir::Filter::Readable, - QDir::SortFlag::Name); + auto entries = customFolderDirectory.entryList( + QDir::Filter::Files | QDir::Filter::Readable, + QDir::SortFlag::Name + ); for (const auto& entry : entries) { addFile(customFolderDirectory.filePath(entry)); } diff --git a/src/Mod/Start/App/DisplayedFilesModel.cpp b/src/Mod/Start/App/DisplayedFilesModel.cpp index e70171b8d4..97bf266a56 100644 --- a/src/Mod/Start/App/DisplayedFilesModel.cpp +++ b/src/Mod/Start/App/DisplayedFilesModel.cpp @@ -52,8 +52,7 @@ FileStats fileInfoFromFreeCADFile(const std::string& path) auto metadata = proj.getMetadata(); FileStats result; result.insert(std::make_pair(DisplayedFilesModelRoles::author, metadata.createdBy)); - result.insert( - std::make_pair(DisplayedFilesModelRoles::modifiedTime, metadata.lastModifiedDate)); + result.insert(std::make_pair(DisplayedFilesModelRoles::modifiedTime, metadata.lastModifiedDate)); result.insert(std::make_pair(DisplayedFilesModelRoles::creationTime, metadata.creationDate)); result.insert(std::make_pair(DisplayedFilesModelRoles::company, metadata.company)); result.insert(std::make_pair(DisplayedFilesModelRoles::license, metadata.license)); @@ -100,7 +99,8 @@ FileStats getFileInfo(const std::string& path) } else { result.insert( - std::make_pair(DisplayedFilesModelRoles::modifiedTime, getLastModifiedAsString(file))); + std::make_pair(DisplayedFilesModelRoles::modifiedTime, getLastModifiedAsString(file)) + ); } result.insert(std::make_pair(DisplayedFilesModelRoles::path, path)); result.insert(std::make_pair(DisplayedFilesModelRoles::size, humanReadableSize(file.size()))); @@ -112,10 +112,10 @@ bool freecadCanOpen(const QString& extension) { std::string ext = extension.toStdString(); auto importTypes = App::GetApplication().getImportTypes(); - return std::ranges::find_if(importTypes, - [&ext](const auto& item) { - return boost::iequals(item, ext); - }) + return std::ranges::find_if( + importTypes, + [&ext](const auto& item) { return boost::iequals(item, ext); } + ) != importTypes.end(); } @@ -160,8 +160,7 @@ QVariant DisplayedFilesModel::data(const QModelIndex& index, int role) const } break; case DisplayedFilesModelRoles::image: { - if (const auto path = - QString::fromStdString(mapEntry.at(DisplayedFilesModelRoles::path)); + if (const auto path = QString::fromStdString(mapEntry.at(DisplayedFilesModelRoles::path)); _imageCache.contains(path)) { return _imageCache[path]; } @@ -193,11 +192,13 @@ void DisplayedFilesModel::addFile(const QString& filePath) _fileInfoCache.emplace_back(getFileInfo(filePath.toStdString())); const auto lowercaseExtension = qfi.suffix().toLower(); - const QStringList ignoredExtensions {QLatin1String("fcmacro"), - QLatin1String("py"), - QLatin1String("pyi"), - QLatin1String("csv"), - QLatin1String("txt")}; + const QStringList ignoredExtensions { + QLatin1String("fcmacro"), + QLatin1String("py"), + QLatin1String("pyi"), + QLatin1String("csv"), + QLatin1String("txt") + }; if (lowercaseExtension == QLatin1String("fcstd")) { if (const auto thumbnail = loadFCStdThumbnail(filePath); !thumbnail.isEmpty()) { _imageCache.insert(filePath, thumbnail); @@ -209,10 +210,12 @@ void DisplayedFilesModel::addFile(const QString& filePath) } else { const auto runner = new ThumbnailSource(filePath); - connect(runner->signals(), - &ThumbnailSourceSignals::thumbnailAvailable, - this, - &DisplayedFilesModel::processNewThumbnail); + connect( + runner->signals(), + &ThumbnailSourceSignals::thumbnailAvailable, + this, + &DisplayedFilesModel::processNewThumbnail + ); QThreadPool::globalInstance()->start(runner); } } diff --git a/src/Mod/Start/App/ExamplesModel.cpp b/src/Mod/Start/App/ExamplesModel.cpp index 616b9bc88a..e8e875caf3 100644 --- a/src/Mod/Start/App/ExamplesModel.cpp +++ b/src/Mod/Start/App/ExamplesModel.cpp @@ -42,11 +42,15 @@ void ExamplesModel::loadExamples() beginResetModel(); clear(); if (!_examplesDirectory.isReadable()) { - Base::Console().warning("Cannot read %s", - _examplesDirectory.absolutePath().toStdString().c_str()); + Base::Console().warning( + "Cannot read %s", + _examplesDirectory.absolutePath().toStdString().c_str() + ); } - auto entries = _examplesDirectory.entryList(QDir::Filter::Files | QDir::Filter::Readable, - QDir::SortFlag::Name); + auto entries = _examplesDirectory.entryList( + QDir::Filter::Files | QDir::Filter::Readable, + QDir::SortFlag::Name + ); for (const auto& entry : entries) { addFile(_examplesDirectory.filePath(entry)); } diff --git a/src/Mod/Start/App/FileUtilities.h b/src/Mod/Start/App/FileUtilities.h index c919918064..7d46c2c691 100644 --- a/src/Mod/Start/App/FileUtilities.h +++ b/src/Mod/Start/App/FileUtilities.h @@ -45,8 +45,7 @@ const QLatin1String defaultThumbnailName ("FreeCADStartThumbnails"); #endif -const QDir thumbnailsParentDir { - QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation)}; +const QDir thumbnailsParentDir {QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation)}; const QDir thumbnailsDir {thumbnailsParentDir.absoluteFilePath(defaultThumbnailName)}; diff --git a/src/Mod/Start/App/RecentFilesModel.cpp b/src/Mod/Start/App/RecentFilesModel.cpp index dbd5d4b56c..09f541ac80 100644 --- a/src/Mod/Start/App/RecentFilesModel.cpp +++ b/src/Mod/Start/App/RecentFilesModel.cpp @@ -31,7 +31,8 @@ RecentFilesModel::RecentFilesModel(QObject* parent) : DisplayedFilesModel(parent) { _parameterGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/RecentFiles"); + "User parameter:BaseApp/Preferences/RecentFiles" + ); } void RecentFilesModel::loadRecentFiles() diff --git a/src/Mod/Start/App/ThumbnailSource.cpp b/src/Mod/Start/App/ThumbnailSource.cpp index 5ab4faad45..6789b02ab4 100644 --- a/src/Mod/Start/App/ThumbnailSource.cpp +++ b/src/Mod/Start/App/ThumbnailSource.cpp @@ -61,7 +61,8 @@ void ThumbnailSource::run() return; } const ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); const auto f3d = QString::fromUtf8(hGrp->GetASCII("f3d", "f3d").c_str()); QStringList args(_f3d.baseArgs); args << QLatin1String("--output=") + _thumbnailPath << _file; @@ -82,9 +83,11 @@ void ThumbnailSource::run() Base::Console().log("Creating thumbnail for %s failed\n", _file.toStdString()); return; } - Base::Console().log("Creating thumbnail for %s succeeded, wrote to %s\n", - _file.toStdString(), - _thumbnailPath.toStdString()); + Base::Console().log( + "Creating thumbnail for %s succeeded, wrote to %s\n", + _file.toStdString(), + _thumbnailPath.toStdString() + ); } if (QFile thumbnailFile(_thumbnailPath); thumbnailFile.exists()) { thumbnailFile.open(QIODevice::OpenModeFlag::ReadOnly); @@ -108,7 +111,8 @@ std::tuple extractF3DVersion(const QString& stdoutString) } catch (...) { Base::Console().log( - "Could not determine F3D version, disabling thumbnail generation\n"); + "Could not determine F3D version, disabling thumbnail generation\n" + ); } } break; @@ -166,7 +170,8 @@ void ThumbnailSource::setupF3D() _f3d.initialized = true; // Set immediately so we can use early-return below const ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); const auto f3d = QString::fromUtf8(hGrp->GetASCII("f3d", "f3d").c_str()); const QStringList args {QLatin1String("--version")}; QProcess process; diff --git a/src/Mod/Start/Gui/AppStartGui.cpp b/src/Mod/Start/Gui/AppStartGui.cpp index 4e67f0e141..8448a9cff3 100644 --- a/src/Mod/Start/Gui/AppStartGui.cpp +++ b/src/Mod/Start/Gui/AppStartGui.cpp @@ -72,21 +72,18 @@ public: StartLauncher() { // QTimers don't fire until the event loop starts, which is our signal that the GUI is up - QTimer::singleShot(100, [this] { - Launch(); - }); + QTimer::singleShot(100, [this] { Launch(); }); } void Launch() { auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); bool showOnStartup = hGrp->GetBool("ShowOnStartup", true); if (showOnStartup) { Gui::Application::Instance->commandManager().runCommandByName("Start_Start"); - QTimer::singleShot(100, [this] { - EnsureLaunched(); - }); + QTimer::singleShot(100, [this] { EnsureLaunched(); }); } } @@ -125,8 +122,7 @@ PyMOD_INIT_FUNC(StartGui) Base::Console().log("done\n"); // register preferences pages - new Gui::PrefPageProducer( - QT_TRANSLATE_NOOP("QObject", "Start")); + new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Start")); PyMOD_Return(mod); } diff --git a/src/Mod/Start/Gui/FileCardDelegate.cpp b/src/Mod/Start/Gui/FileCardDelegate.cpp index f0aa420d5e..940cc813c3 100644 --- a/src/Mod/Start/Gui/FileCardDelegate.cpp +++ b/src/Mod/Start/Gui/FileCardDelegate.cpp @@ -50,25 +50,29 @@ FileCardDelegate::FileCardDelegate(QObject* parent) : QStyledItemDelegate(parent) { _parameterGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); setObjectName(QStringLiteral("thumbnailWidget")); // Initialize cache size based on thumbnail size (only once) if (_thumbnailCache.maxCost() == 0) { - int thumbnailSize = - static_cast(_parameterGroup->GetInt("FileThumbnailIconsSize", 128)); + int thumbnailSize = static_cast(_parameterGroup->GetInt("FileThumbnailIconsSize", 128)); int thumbnailMemory = thumbnailSize * thumbnailSize * 4; // rgba int maxCacheItems = (CACHE_SIZE_MB * 1024 * 1024) / thumbnailMemory; _thumbnailCache.setMaxCost(maxCacheItems); - Base::Console().log("FileCardDelegate: Initialized thumbnail cache for %d items (%d MB)\n", - maxCacheItems, - CACHE_SIZE_MB); + Base::Console().log( + "FileCardDelegate: Initialized thumbnail cache for %d items (%d MB)\n", + maxCacheItems, + CACHE_SIZE_MB + ); } } -void FileCardDelegate::paint(QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex& index) const +void FileCardDelegate::paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index +) const { painter->save(); // Step 1: Styling @@ -89,8 +93,7 @@ void FileCardDelegate::paint(QPainter* painter, qApp->style()->drawControl(QStyle::CE_PushButton, &buttonOption, painter, &styleButton); // Step 2: Fetch required data - auto thumbnailSize = - static_cast(_parameterGroup->GetInt("FileThumbnailIconsSize", 128)); // NOLINT + auto thumbnailSize = static_cast(_parameterGroup->GetInt("FileThumbnailIconsSize", 128)); // NOLINT auto baseName = index.data(static_cast(DisplayedFilesModelRoles::baseName)).toString(); auto elidedName = painter->fontMetrics().elidedText(baseName, Qt::ElideRight, thumbnailSize); auto size = index.data(static_cast(DisplayedFilesModelRoles::size)).toString(); @@ -105,24 +108,27 @@ void FileCardDelegate::paint(QPainter* painter, pixmap = generateThumbnail(path); } - QPixmap scaledPixmap = pixmap.scaled(QSize(thumbnailSize, thumbnailSize), - Qt::KeepAspectRatio, - Qt::SmoothTransformation); + QPixmap scaledPixmap = pixmap.scaled( + QSize(thumbnailSize, thumbnailSize), + Qt::KeepAspectRatio, + Qt::SmoothTransformation + ); // Step 4: Positioning - QRect thumbnailRect(option.rect.x() + margin, - option.rect.y() + margin, - thumbnailSize, - thumbnailSize); - QRect textRect(option.rect.x() + margin, - thumbnailRect.bottom() + margin, - thumbnailSize, - painter->fontMetrics().lineSpacing()); + QRect thumbnailRect(option.rect.x() + margin, option.rect.y() + margin, thumbnailSize, thumbnailSize); + QRect textRect( + option.rect.x() + margin, + thumbnailRect.bottom() + margin, + thumbnailSize, + painter->fontMetrics().lineSpacing() + ); - QRect sizeRect(option.rect.x() + margin, - textRect.bottom() + textspacing, - thumbnailSize, - painter->fontMetrics().lineSpacing() + margin); + QRect sizeRect( + option.rect.x() + margin, + textRect.bottom() + textspacing, + thumbnailSize, + painter->fontMetrics().lineSpacing() + margin + ); // Step 5: Draw QRect pixmapRect(thumbnailRect.topLeft(), scaledPixmap.size()); @@ -151,8 +157,7 @@ QSize FileCardDelegate::sizeHint(const QStyleOptionViewItem& option, const QMode QPixmap FileCardDelegate::generateThumbnail(const QString& path) const { - auto thumbnailSize = - static_cast(_parameterGroup->GetInt("FileThumbnailIconsSize", 128)); // NOLINT + auto thumbnailSize = static_cast(_parameterGroup->GetInt("FileThumbnailIconsSize", 128)); // NOLINT // check if we have this thumbnail already inside cache, don't load it once again QString cacheKey = getCacheKey(path, thumbnailSize); @@ -201,8 +206,7 @@ QPixmap FileCardDelegate::loadAndCacheThumbnail(const QString& path, int thumbna // get original size to calculate proper aspect-preserving scaled size QSize originalSize = reader.size(); if (originalSize.isValid()) { - QSize scaledSize = - originalSize.scaled(thumbnailSize, thumbnailSize, Qt::KeepAspectRatio); + QSize scaledSize = originalSize.scaled(thumbnailSize, thumbnailSize, Qt::KeepAspectRatio); reader.setScaledSize(scaledSize); } @@ -211,9 +215,11 @@ QPixmap FileCardDelegate::loadAndCacheThumbnail(const QString& path, int thumbna thumbnail = QPixmap::fromImage(image); } else { - Base::Console().log("FileCardDelegate: Failed to load image %s: %s\n", - path.toStdString().c_str(), - reader.errorString().toStdString().c_str()); + Base::Console().log( + "FileCardDelegate: Failed to load image %s: %s\n", + path.toStdString().c_str(), + reader.errorString().toStdString().c_str() + ); } } diff --git a/src/Mod/Start/Gui/FileCardDelegate.h b/src/Mod/Start/Gui/FileCardDelegate.h index a072c074a4..0e12b64ced 100644 --- a/src/Mod/Start/Gui/FileCardDelegate.h +++ b/src/Mod/Start/Gui/FileCardDelegate.h @@ -38,9 +38,11 @@ class FileCardDelegate: public QStyledItemDelegate public: explicit FileCardDelegate(QObject* parent = nullptr); - void paint(QPainter* painter, - const QStyleOptionViewItem& option, - const QModelIndex& index) const override; + void paint( + QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index + ) const override; QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const override; diff --git a/src/Mod/Start/Gui/FileCardView.cpp b/src/Mod/Start/Gui/FileCardView.cpp index f0e5795374..adeae7f7ad 100644 --- a/src/Mod/Start/Gui/FileCardView.cpp +++ b/src/Mod/Start/Gui/FileCardView.cpp @@ -33,8 +33,7 @@ namespace StartGui FileCardView::FileCardView(QWidget* parent) : QListView(parent) { - QSizePolicy sizePolicy(QSizePolicy::Policy::MinimumExpanding, - QSizePolicy::Policy::MinimumExpanding); + QSizePolicy sizePolicy(QSizePolicy::Policy::MinimumExpanding, QSizePolicy::Policy::MinimumExpanding); sizePolicy.setHeightForWidth(true); setSizePolicy(sizePolicy); setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff); @@ -46,7 +45,8 @@ FileCardView::FileCardView(QWidget* parent) setMouseTracking(true); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); m_cardSpacing = static_cast(hGrp->GetInt("FileCardSpacing", 16)); // NOLINT setSpacing(m_cardSpacing); @@ -62,8 +62,9 @@ int FileCardView::heightForWidth(int width) const int numCards = model->rowCount(); auto cardSize = delegate->sizeHint(QStyleOptionViewItem(), model->index(0, 0)); int cardsPerRow = std::max(1, static_cast(width / (cardSize.width() + m_cardSpacing))); - int numRows = - static_cast(ceil(static_cast(numCards) / static_cast(cardsPerRow))); + int numRows = static_cast( + ceil(static_cast(numCards) / static_cast(cardsPerRow)) + ); int neededHeight = numRows * cardSize.height(); constexpr int extra = 4; // avoid tiny scrollbars return neededHeight + m_cardSpacing * (numRows - 1) + 2 * m_cardSpacing + extra; @@ -79,8 +80,10 @@ QSize FileCardView::sizeHint() const } int numCards = model->rowCount(); auto cardSize = delegate->sizeHint(QStyleOptionViewItem(), model->index(0, 0)); - return {(cardSize.width() + m_cardSpacing) * numCards + m_cardSpacing, - cardSize.height() + 2 * m_cardSpacing}; + return { + (cardSize.width() + m_cardSpacing) * numCards + m_cardSpacing, + cardSize.height() + 2 * m_cardSpacing + }; } } // namespace StartGui diff --git a/src/Mod/Start/Gui/FirstStartWidget.cpp b/src/Mod/Start/Gui/FirstStartWidget.cpp index b21042a67f..1ea0cf545c 100644 --- a/src/Mod/Start/Gui/FirstStartWidget.cpp +++ b/src/Mod/Start/Gui/FirstStartWidget.cpp @@ -91,9 +91,11 @@ void FirstStartWidget::retranslateUi() { _doneButton->setText(tr("Done")); QString application = QString::fromUtf8(App::Application::Config()["ExeName"].c_str()); - _welcomeLabel->setText(QLatin1String("

      ") + tr("Welcome to %1").arg(application) - + QLatin1String("

      ")); + _welcomeLabel->setText( + QLatin1String("

      ") + tr("Welcome to %1").arg(application) + QLatin1String("

      ") + ); _descriptionLabel->setText( tr("Set your basic configuration options below.") + QLatin1String(" ") - + tr("These options (and many more) can be changed later in the preferences.")); + + tr("These options (and many more) can be changed later in the preferences.") + ); } diff --git a/src/Mod/Start/Gui/FlowLayout.cpp b/src/Mod/Start/Gui/FlowLayout.cpp index 3befc298d9..aa32fb4e6c 100644 --- a/src/Mod/Start/Gui/FlowLayout.cpp +++ b/src/Mod/Start/Gui/FlowLayout.cpp @@ -163,16 +163,20 @@ int FlowLayout::doLayout(const QRect& rect, bool testOnly) const int spaceX = horizontalSpacing(); if (spaceX == -1) { - spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, - QSizePolicy::PushButton, - Qt::Horizontal); + spaceX = wid->style()->layoutSpacing( + QSizePolicy::PushButton, + QSizePolicy::PushButton, + Qt::Horizontal + ); } int spaceY = verticalSpacing(); if (spaceY == -1) { - spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, - QSizePolicy::PushButton, - Qt::Vertical); + spaceY = wid->style()->layoutSpacing( + QSizePolicy::PushButton, + QSizePolicy::PushButton, + Qt::Vertical + ); } int nextX = x + itemSizeHint.width() + spaceX; @@ -182,8 +186,10 @@ int FlowLayout::doLayout(const QRect& rect, bool testOnly) const // Apply row height to all items in the current row for (auto rowItem : currentRow) { if (!testOnly) { - rowItem->setGeometry(QRect(QPoint(rowItem->geometry().x(), y), - QSize(rowItem->sizeHint().width(), lineHeight))); + rowItem->setGeometry(QRect( + QPoint(rowItem->geometry().x(), y), + QSize(rowItem->sizeHint().width(), lineHeight) + )); } } @@ -206,8 +212,10 @@ int FlowLayout::doLayout(const QRect& rect, bool testOnly) const // Step 2: Apply the last row's height for (auto rowItem : currentRow) { if (!testOnly) { - rowItem->setGeometry(QRect(QPoint(rowItem->geometry().x(), y), - QSize(rowItem->sizeHint().width(), lineHeight))); + rowItem->setGeometry(QRect( + QPoint(rowItem->geometry().x(), y), + QSize(rowItem->sizeHint().width(), lineHeight) + )); } } diff --git a/src/Mod/Start/Gui/FlowLayout.h b/src/Mod/Start/Gui/FlowLayout.h index 2518df809d..575a348d6b 100644 --- a/src/Mod/Start/Gui/FlowLayout.h +++ b/src/Mod/Start/Gui/FlowLayout.h @@ -41,10 +41,7 @@ class FlowLayout: public QLayout Q_OBJECT public: - explicit FlowLayout(QWidget* parent = nullptr, - int margin = -1, - int hSpacing = -1, - int vSpacing = -1); + explicit FlowLayout(QWidget* parent = nullptr, int margin = -1, int hSpacing = -1, int vSpacing = -1); ~FlowLayout() override; void addItem(QLayoutItem* item) override; diff --git a/src/Mod/Start/Gui/GeneralSettingsWidget.cpp b/src/Mod/Start/Gui/GeneralSettingsWidget.cpp index 3082d3987b..cbc78bc967 100644 --- a/src/Mod/Start/Gui/GeneralSettingsWidget.cpp +++ b/src/Mod/Start/Gui/GeneralSettingsWidget.cpp @@ -96,8 +96,9 @@ QString GeneralSettingsWidget::createLabelText(const QString& translatedText) co gsl::owner GeneralSettingsWidget::createLanguageComboBox() { - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/General" + ); auto langToStr = Gui::Translator::instance()->activeLanguage(); QByteArray language = hGrp->GetASCII("Language", langToStr.c_str()).c_str(); auto comboBox = gsl::owner(new QComboBox); @@ -132,10 +133,12 @@ gsl::owner GeneralSettingsWidget::createLanguageComboBox() model->sort(0); } _languageComboBox = comboBox; - connect(_languageComboBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &GeneralSettingsWidget::onLanguageChanged); + connect( + _languageComboBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &GeneralSettingsWidget::onLanguageChanged + ); return comboBox; } @@ -144,10 +147,12 @@ gsl::owner GeneralSettingsWidget::createUnitSystemComboBox() // Contents are created in retranslateUi() auto comboBox = gsl::owner(new QComboBox); _unitSystemComboBox = comboBox; - connect(_unitSystemComboBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &GeneralSettingsWidget::onUnitSystemChanged); + connect( + _unitSystemComboBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &GeneralSettingsWidget::onUnitSystemChanged + ); return comboBox; } @@ -156,10 +161,12 @@ gsl::owner GeneralSettingsWidget::createNavigationStyleComboBox() // Contents are created in retranslateUi() auto comboBox = gsl::owner(new QComboBox); _navigationStyleComboBox = comboBox; - connect(_navigationStyleComboBox, - qOverload(&QComboBox::currentIndexChanged), - this, - &GeneralSettingsWidget::onNavigationStyleChanged); + connect( + _navigationStyleComboBox, + qOverload(&QComboBox::currentIndexChanged), + this, + &GeneralSettingsWidget::onNavigationStyleChanged + ); return comboBox; } @@ -169,9 +176,11 @@ void GeneralSettingsWidget::onLanguageChanged(int index) return; // happens when clearing the combo box in retranslateUi() } Gui::Translator::instance()->activateLanguage( - _languageComboBox->itemData(index).toByteArray().data()); - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General"); + _languageComboBox->itemData(index).toByteArray().data() + ); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/General" + ); auto langToStr = Gui::Translator::instance()->activeLanguage(); hGrp->SetASCII("Language", langToStr.c_str()); } @@ -182,8 +191,9 @@ void GeneralSettingsWidget::onUnitSystemChanged(int index) return; // happens when clearing the combo box in retranslateUi() } Base::UnitsApi::setSchema(index); - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Units" + ); hGrp->SetInt("UserSchema", index); } @@ -193,8 +203,9 @@ void GeneralSettingsWidget::onNavigationStyleChanged(int index) return; // happens when clearing the combo box in retranslateUi() } auto navStyleName = _navigationStyleComboBox->itemData(index).toByteArray(); - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); hGrp->SetASCII("NavigationStyle", navStyleName.constData()); } @@ -213,8 +224,9 @@ void GeneralSettingsWidget::retranslateUi() _unitSystemComboBox->clear(); - const ParameterGrp::handle hGrpUnits = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Units"); + const ParameterGrp::handle hGrpUnits = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Units" + ); auto userSchema = hGrpUnits->GetInt("UserSchema", 0); auto addItem = [&, index {0}](const std::string& item) mutable { @@ -227,10 +239,11 @@ void GeneralSettingsWidget::retranslateUi() _navigationStyleLabel->setText(createLabelText(tr("Navigation Style"))); _navigationStyleComboBox->clear(); - ParameterGrp::handle hGrpNav = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - auto navStyleName = - hGrpNav->GetASCII("NavigationStyle", Gui::CADNavigationStyle::getClassTypeId().getName()); + ParameterGrp::handle hGrpNav = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/View" + ); + auto navStyleName + = hGrpNav->GetASCII("NavigationStyle", Gui::CADNavigationStyle::getClassTypeId().getName()); std::map styles = Gui::UserNavigationStyle::getUserFriendlyNames(); for (const auto& style : styles) { QByteArray data(style.first.getName()); diff --git a/src/Mod/Start/Gui/NewFileButton.cpp b/src/Mod/Start/Gui/NewFileButton.cpp index cd6a68c0f7..e8573af021 100644 --- a/src/Mod/Start/Gui/NewFileButton.cpp +++ b/src/Mod/Start/Gui/NewFileButton.cpp @@ -42,7 +42,8 @@ NewFileButton::NewFileButton(const NewButton& newButton) { setObjectName(QStringLiteral("newFileButton")); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); constexpr int defaultWidth = 180; // #newFileButton width in QSS labelWidth = int(hGrp->GetInt("FileCardLabelWith", defaultWidth)); diff --git a/src/Mod/Start/Gui/StartView.cpp b/src/Mod/Start/Gui/StartView.cpp index bd75e3544b..65a1ebeaaa 100644 --- a/src/Mod/Start/Gui/StartView.cpp +++ b/src/Mod/Start/Gui/StartView.cpp @@ -74,7 +74,8 @@ StartView::StartView(QWidget* parent) { setObjectName(QLatin1String("StartView")); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); auto cardSpacing = hGrp->GetInt("FileCardSpacing", 15); // NOLINT auto showExamples = hGrp->GetBool("ShowExamples", true); // NOLINT @@ -94,10 +95,7 @@ StartView::StartView(QWidget* parent) auto firstStartRegion = gsl::owner(new QHBoxLayout(firstStartScrollWidget)); firstStartRegion->setAlignment(Qt::AlignCenter); auto firstStartWidget = gsl::owner(new FirstStartWidget(this)); - connect(firstStartWidget, - &FirstStartWidget::dismissed, - this, - &StartView::firstStartWidgetDismissed); + connect(firstStartWidget, &FirstStartWidget::dismissed, this, &StartView::firstStartWidgetDismissed); firstStartRegion->addWidget(firstStartWidget); _contents->addWidget(firstStartScrollArea); @@ -169,8 +167,9 @@ StartView::StartView(QWidget* parent) _showOnStartupCheckBox = gsl::owner(new QCheckBox()); bool showOnStartup = hGrp->GetBool("ShowOnStartup", true); - _showOnStartupCheckBox->setCheckState(showOnStartup ? Qt::CheckState::Unchecked - : Qt::CheckState::Checked); + _showOnStartupCheckBox->setCheckState( + showOnStartup ? Qt::CheckState::Unchecked : Qt::CheckState::Checked + ); connect(_showOnStartupCheckBox, &QCheckBox::toggled, this, &StartView::showOnStartupChanged); footerLayout->addWidget(_openFirstStart); @@ -201,30 +200,34 @@ StartView::StartView(QWidget* parent) void StartView::configureNewFileButtons(QLayout* layout) const { - auto newEmptyFile = - gsl::owner(new NewFileButton({tr("Empty File"), - tr("Creates a new empty FreeCAD file"), - QLatin1String(":/icons/document-new.svg")})); - auto openFile = - gsl::owner(new NewFileButton({tr("Open File"), - tr("Opens an existing CAD file or 3D model"), - QLatin1String(":/icons/document-open.svg")})); - auto partDesign = gsl::owner( - new NewFileButton({tr("Parametric Body"), - tr("Creates a body with the Part Design workbench"), - QLatin1String(":/icons/PartDesignWorkbench.svg")})); - auto assembly = gsl::owner( - new NewFileButton({tr("Assembly"), - tr("Creates an assembly project"), - QLatin1String(":/icons/AssemblyWorkbench.svg")})); - auto draft = gsl::owner( - new NewFileButton({tr("2D Draft"), - tr("Creates a 2D Draft document"), - QLatin1String(":/icons/DraftWorkbench.svg")})); - auto arch = - gsl::owner(new NewFileButton({tr("BIM/Architecture"), - tr("Creates an architectural project"), - QLatin1String(":/icons/BIMWorkbench.svg")})); + auto newEmptyFile = gsl::owner(new NewFileButton( + {tr("Empty File"), + tr("Creates a new empty FreeCAD file"), + QLatin1String(":/icons/document-new.svg")} + )); + auto openFile = gsl::owner(new NewFileButton( + {tr("Open File"), + tr("Opens an existing CAD file or 3D model"), + QLatin1String(":/icons/document-open.svg")} + )); + auto partDesign = gsl::owner(new NewFileButton( + {tr("Parametric Body"), + tr("Creates a body with the Part Design workbench"), + QLatin1String(":/icons/PartDesignWorkbench.svg")} + )); + auto assembly = gsl::owner(new NewFileButton( + {tr("Assembly"), + tr("Creates an assembly project"), + QLatin1String(":/icons/AssemblyWorkbench.svg")} + )); + auto draft = gsl::owner(new NewFileButton( + {tr("2D Draft"), tr("Creates a 2D Draft document"), QLatin1String(":/icons/DraftWorkbench.svg")} + )); + auto arch = gsl::owner(new NewFileButton( + {tr("BIM/Architecture"), + tr("Creates an architectural project"), + QLatin1String(":/icons/BIMWorkbench.svg")} + )); // TODO: Ensure all of the required WBs are actually available layout->addWidget(partDesign); @@ -254,15 +257,15 @@ void StartView::configureFileCardWidget(QListView* fileCardWidget) } -void StartView::configureRecentFilesListWidget(QListView* recentFilesListWidget, - QLabel* recentFilesLabel) +void StartView::configureRecentFilesListWidget(QListView* recentFilesListWidget, QLabel* recentFilesLabel) { _recentFilesModel.loadRecentFiles(); recentFilesListWidget->setModel(&_recentFilesModel); configureFileCardWidget(recentFilesListWidget); auto recentFilesGroup = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/RecentFiles"); + "User parameter:BaseApp/Preferences/RecentFiles" + ); auto numRecentFiles {recentFilesGroup->GetInt("RecentFiles", 0)}; if (numRecentFiles == 0) { recentFilesListWidget->hide(); @@ -347,7 +350,8 @@ void StartView::newArchFile() // Set the camera zoom level to 10 m, which is more appropriate for architectural projects Gui::Command::doCommand( Gui::Command::Gui, - "Gui.activeDocument().activeView().viewDefaultOrientation(None, 10000.0)"); + "Gui.activeDocument().activeView().viewDefaultOrientation(None, 10000.0)" + ); postStart(PostStartBehavior::doNotSwitchWorkbench); } @@ -363,7 +367,8 @@ bool StartView::onHasMsg(const char* pMsg) const void StartView::postStart(PostStartBehavior behavior) { auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); if (behavior == PostStartBehavior::switchWorkbench) { auto wb = hGrp->GetASCII("AutoloadModule", ""); @@ -390,8 +395,7 @@ void StartView::postStart(PostStartBehavior behavior) void StartView::fileCardSelected(const QModelIndex& index) { try { - auto filename = - index.data(static_cast(Start::DisplayedFilesModelRoles::path)).toString(); + auto filename = index.data(static_cast(Start::DisplayedFilesModelRoles::path)).toString(); Gui::ModuleIO::verifyAndOpenFile(filename); } catch (Base::PyException& e) { @@ -408,12 +412,14 @@ void StartView::fileCardSelected(const QModelIndex& index) void StartView::showOnStartupChanged(bool checked) { auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); hGrp->SetBool( "ShowOnStartup", - !checked); // The sense of this option has been reversed: the checkbox actually says - // "*Don't* show on startup" now, but the option is preserved in its - // original sense, so is stored inverted. + !checked + ); // The sense of this option has been reversed: the checkbox actually says + // "*Don't* show on startup" now, but the option is preserved in its + // original sense, so is stored inverted. } void StartView::openFirstStartClicked() @@ -424,7 +430,8 @@ void StartView::openFirstStartClicked() void StartView::firstStartWidgetDismissed() { auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); hGrp->SetBool("FirstStart2024", false); _contents->setCurrentIndex(1); } @@ -453,11 +460,13 @@ void StartView::showEvent(QShowEvent* event) { if (auto mainWindow = Gui::getMainWindow()) { if (auto mdiArea = mainWindow->findChild()) { - connect(mdiArea, - &QMdiArea::subWindowActivated, - this, - &StartView::onMdiSubWindowActivated, - Qt::UniqueConnection); + connect( + mdiArea, + &QMdiArea::subWindowActivated, + this, + &StartView::onMdiSubWindowActivated, + Qt::UniqueConnection + ); } } Gui::MDIView::showEvent(event); @@ -496,7 +505,8 @@ void StartView::retranslateUi() _recentFilesLabel->setText(h1Start + tr("Recent Files") + h1End); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Start"); + "User parameter:BaseApp/Preferences/Mod/Start" + ); std::string customFolder(hGrp->GetASCII("CustomFolder", "")); bool shortCustomFolder = hGrp->GetBool("ShortCustomFolder", true); // false shows full path if (!customFolder.empty()) { @@ -509,6 +519,5 @@ void StartView::retranslateUi() QString application = QString::fromUtf8(App::Application::Config()["ExeName"].c_str()); _openFirstStart->setText(tr("Open First Start Setup")); - _showOnStartupCheckBox->setText( - tr("Do not show this Start page again (start with blank screen)")); + _showOnStartupCheckBox->setText(tr("Do not show this Start page again (start with blank screen)")); } diff --git a/src/Mod/Start/Gui/ThemeSelectorWidget.cpp b/src/Mod/Start/Gui/ThemeSelectorWidget.cpp index 8f6a41ab56..22cf026d21 100644 --- a/src/Mod/Start/Gui/ThemeSelectorWidget.cpp +++ b/src/Mod/Start/Gui/ThemeSelectorWidget.cpp @@ -38,7 +38,7 @@ #include #ifdef FC_OS_MACOSX -#include +# include #endif using namespace StartGui; @@ -58,7 +58,7 @@ static bool isSystemInDarkMode() const auto window = defaultPalette.color(QPalette::Window); return text.lightness() > window.lightness(); #else -#ifdef FC_OS_MACOSX +# ifdef FC_OS_MACOSX auto key = CFSTR("AppleInterfaceStyle"); if (auto value = CFPreferencesCopyAppValue(key, kCFPreferencesAnyApplication)) { // If the value is "Dark", Dark Mode is enabled @@ -71,8 +71,8 @@ static bool isSystemInDarkMode() } CFRelease(value); } -#endif // FC_OS_MACOSX -#endif // QT_VERSION >= 6.4+ +# endif // FC_OS_MACOSX +#endif // QT_VERSION >= 6.4+ return false; } @@ -110,15 +110,19 @@ void ThemeSelectorWidget::setupButtons(QBoxLayout* layout) if (!layout) { return; } - std::map themeMap {{Theme::Classic, tr("FreeCAD Classic")}, - {Theme::Dark, tr("FreeCAD Dark")}, - {Theme::Light, tr("FreeCAD Light")}}; + std::map themeMap { + {Theme::Classic, tr("FreeCAD Classic")}, + {Theme::Dark, tr("FreeCAD Dark")}, + {Theme::Light, tr("FreeCAD Light")} + }; std::map iconMap { {Theme::Classic, QIcon(QLatin1String(":/thumbnails/Theme_thumbnail_classic.png"))}, {Theme::Light, QIcon(QLatin1String(":/thumbnails/Theme_thumbnail_light.png"))}, - {Theme::Dark, QIcon(QLatin1String(":/thumbnails/Theme_thumbnail_dark.png"))}}; + {Theme::Dark, QIcon(QLatin1String(":/thumbnails/Theme_thumbnail_dark.png"))} + }; auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/MainWindow"); + "User parameter:BaseApp/Preferences/MainWindow" + ); auto styleSheetName = QString::fromStdString(hGrp->GetASCII("StyleSheet")); for (const auto& theme : themeMap) { auto button = gsl::owner(new QToolButton()); @@ -137,18 +141,20 @@ void ThemeSelectorWidget::setupButtons(QBoxLayout* layout) button->setChecked(true); } else if (theme.first == Theme::Light - && styleSheetName.contains(QLatin1String("FreeCAD Light"), - Qt::CaseSensitivity::CaseInsensitive)) { + && styleSheetName.contains( + QLatin1String("FreeCAD Light"), + Qt::CaseSensitivity::CaseInsensitive + )) { button->setChecked(true); } else if (theme.first == Theme::Dark - && styleSheetName.contains(QLatin1String("FreeCAD Dark"), - Qt::CaseSensitivity::CaseInsensitive)) { + && styleSheetName.contains( + QLatin1String("FreeCAD Dark"), + Qt::CaseSensitivity::CaseInsensitive + )) { button->setChecked(true); } - connect(button, &QToolButton::clicked, this, [this, theme] { - themeChanged(theme.first); - }); + connect(button, &QToolButton::clicked, this, [this, theme] { themeChanged(theme.first); }); layout->addWidget(button); _buttons[static_cast(theme.first)] = button; } @@ -178,8 +184,9 @@ void ThemeSelectorWidget::onLinkActivated(const QString& link) // Set the user preferences to include only preference packs. // This is a quick and dirty way to open Addon Manager with only themes. - auto pref = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Addons"); + auto pref = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Addons" + ); pref->SetInt("PackageTypeSelection", 3); // 3 stands for Preference Packs pref->SetInt("StatusSelection", 0); // 0 stands for any installation status @@ -190,7 +197,8 @@ void ThemeSelectorWidget::preselectThemeFromSystemSettings() { auto nullStyle(""); auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/MainWindow"); + "User parameter:BaseApp/Preferences/MainWindow" + ); auto styleSheetName = QString::fromStdString(hGrp->GetASCII("StyleSheet", nullStyle)); if (styleSheetName == QString::fromStdString(nullStyle)) { auto theme = isSystemInDarkMode() ? Theme::Dark : Theme::Light; @@ -213,8 +221,9 @@ void ThemeSelectorWidget::themeChanged(Theme newTheme) prefPackManager->apply("FreeCAD Light"); break; } - ParameterGrp::handle hGrp = - App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Themes"); + ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Themes" + ); const unsigned long nonExistentColor = -1434171135; const unsigned long defaultAccentColor = 1434171135; unsigned long longAccentColor1 = hGrp->GetUnsigned("ThemeAccentColor1", nonExistentColor); @@ -237,8 +246,10 @@ void ThemeSelectorWidget::retranslateUi() { _titleLabel->setText(QLatin1String("

      ") + tr("Theme") + QLatin1String("

      ")); if (Gui::Application::Instance->commandManager().getCommandByName("Std_AddonMgr")) { - _descriptionLabel->setText(tr("Looking for more themes? You can obtain them using " - "Addon Manager.")); + _descriptionLabel->setText( + tr("Looking for more themes? You can obtain them using " + "Addon Manager.") + ); } else { _descriptionLabel->hide(); diff --git a/src/Mod/Start/StartGlobal.h b/src/Mod/Start/StartGlobal.h index 2f8f4b5374..1be93dbfbb 100644 --- a/src/Mod/Start/StartGlobal.h +++ b/src/Mod/Start/StartGlobal.h @@ -24,25 +24,25 @@ #include #ifndef LAUNCHER_GLOBAL_H -#define LAUNCHER_GLOBAL_H +# define LAUNCHER_GLOBAL_H // Start -#ifndef StartExport -#ifdef Start_EXPORTS -#define StartExport FREECAD_DECL_EXPORT -#else -#define StartExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef StartExport +# ifdef Start_EXPORTS +# define StartExport FREECAD_DECL_EXPORT +# else +# define StartExport FREECAD_DECL_IMPORT +# endif +# endif // StartGui -#ifndef StartGuiExport -#ifdef StartGui_EXPORTS -#define StartGuiExport FREECAD_DECL_EXPORT -#else -#define StartGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef StartGuiExport +# ifdef StartGui_EXPORTS +# define StartGuiExport FREECAD_DECL_EXPORT +# else +# define StartGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // LAUNCHER_GLOBAL_H diff --git a/src/Mod/Surface/App/Blending/BlendCurve.cpp b/src/Mod/Surface/App/Blending/BlendCurve.cpp index 25bbcb9f14..dc3b62ec2e 100644 --- a/src/Mod/Surface/App/Blending/BlendCurve.cpp +++ b/src/Mod/Surface/App/Blending/BlendCurve.cpp @@ -90,13 +90,15 @@ Handle(Geom_BezierCurve) BlendCurve::compute() for (size_t i = 0; i < nb_pts; ++i) { math_Matrix bezier_eval(1, blendPoints[i].nbVectors(), 1, num_poles, 0.0); Standard_Integer first_non_zero; - BSplCLib::EvalBsplineBasis(blendPoints[i].nbVectors() - 1, - num_poles, - knots, - params(cons_idx), - first_non_zero, - bezier_eval, - Standard_False); + BSplCLib::EvalBsplineBasis( + blendPoints[i].nbVectors() - 1, + num_poles, + knots, + params(cons_idx), + first_non_zero, + bezier_eval, + Standard_False + ); int idx2 = 1; for (int it2 = 0; it2 < blendPoints[i].nbVectors(); ++it2) { OCCmatrix.SetRow(row_idx, bezier_eval.Row(idx2)); diff --git a/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp b/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp index c873b85444..4a2315b933 100644 --- a/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp +++ b/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp @@ -49,12 +49,14 @@ int BlendCurvePy::PyInit(PyObject* args, PyObject* /*kwds*/) PyObject* b1; PyObject* b2; - if (!PyArg_ParseTuple(args, - "O!O!", - &(Surface::BlendPointPy::Type), - &b1, - &(Surface::BlendPointPy::Type), - &b2)) { + if (!PyArg_ParseTuple( + args, + "O!O!", + &(Surface::BlendPointPy::Type), + &b1, + &(Surface::BlendPointPy::Type), + &b2 + )) { return -1; } diff --git a/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp b/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp index 531db8ac6f..e2c94c787a 100644 --- a/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp +++ b/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp @@ -92,8 +92,7 @@ int BlendPointPy::PyInit(PyObject* args, PyObject*) if (PyArg_ParseTuple(args, "O!di", &(Part::TopoShapePy::Type), &pcObj, ¶m, &cont)) { try { gp_Pnt Pt; - TopoDS_Shape shape = - static_cast(pcObj)->getTopoShapePtr()->getShape(); + TopoDS_Shape shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); const TopoDS_Edge& e = TopoDS::Edge(shape); BRepAdaptor_Curve adapt(e); if (param < adapt.FirstParameter() || param > adapt.LastParameter()) { @@ -120,11 +119,13 @@ int BlendPointPy::PyInit(PyObject* args, PyObject*) } } - PyErr_SetString(PyExc_TypeError, - "supported signatures:\n" - "BlendPoint()\n" - "BlendPoint(list of Vector)\n" - "BlendPoint(edge, parameter and continiuity)\n"); + PyErr_SetString( + PyExc_TypeError, + "supported signatures:\n" + "BlendPoint()\n" + "BlendPoint(list of Vector)\n" + "BlendPoint(edge, parameter and continiuity)\n" + ); return -1; } diff --git a/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp b/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp index 6226a46602..2c7152dc5c 100644 --- a/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp +++ b/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp @@ -47,52 +47,38 @@ PROPERTY_SOURCE(Surface::FeatureBlendCurve, Part::Spline) FeatureBlendCurve::FeatureBlendCurve() { - ADD_PROPERTY_TYPE(StartEdge, - (nullptr), - "FirstEdge", - App::Prop_None, - "Edge support of the start point"); - ADD_PROPERTY_TYPE(StartContinuity, - (2), - "FirstEdge", - App::Prop_None, - "Geometric continuity at start point"); + ADD_PROPERTY_TYPE(StartEdge, (nullptr), "FirstEdge", App::Prop_None, "Edge support of the start point"); + ADD_PROPERTY_TYPE( + StartContinuity, + (2), + "FirstEdge", + App::Prop_None, + "Geometric continuity at start point" + ); StartContinuity.setConstraints(&ContinuityConstraint); - ADD_PROPERTY_TYPE(StartParameter, - (0.0f), - "FirstEdge", - App::Prop_None, - "Parameter of start point along edge"); + ADD_PROPERTY_TYPE( + StartParameter, + (0.0f), + "FirstEdge", + App::Prop_None, + "Parameter of start point along edge" + ); StartParameter.setConstraints(&ParameterConstraint); - ADD_PROPERTY_TYPE(StartSize, - (1.0f), - "FirstEdge", - App::Prop_None, - "Size of derivatives at start point"); + ADD_PROPERTY_TYPE(StartSize, (1.0f), "FirstEdge", App::Prop_None, "Size of derivatives at start point"); StartSize.setConstraints(&SizeConstraint); - ADD_PROPERTY_TYPE(EndEdge, - (nullptr), - "SecondEdge", - App::Prop_None, - "Edge support of the end point"); - ADD_PROPERTY_TYPE(EndContinuity, - (2), - "SecondEdge", - App::Prop_None, - "Geometric continuity at end point"); + ADD_PROPERTY_TYPE(EndEdge, (nullptr), "SecondEdge", App::Prop_None, "Edge support of the end point"); + ADD_PROPERTY_TYPE(EndContinuity, (2), "SecondEdge", App::Prop_None, "Geometric continuity at end point"); EndContinuity.setConstraints(&ContinuityConstraint); - ADD_PROPERTY_TYPE(EndParameter, - (0.0f), - "SecondEdge", - App::Prop_None, - "Parameter of end point along edge"); + ADD_PROPERTY_TYPE( + EndParameter, + (0.0f), + "SecondEdge", + App::Prop_None, + "Parameter of end point along edge" + ); EndParameter.setConstraints(&ParameterConstraint); - ADD_PROPERTY_TYPE(EndSize, - (1.0f), - "SecondEdge", - App::Prop_None, - "Size of derivatives at end point"); + ADD_PROPERTY_TYPE(EndSize, (1.0f), "SecondEdge", App::Prop_None, "Size of derivatives at end point"); EndSize.setConstraints(&SizeConstraint); Handle(Geom_BezierCurve) maxDegreeCurve; @@ -128,23 +114,25 @@ short FeatureBlendCurve::mustExecute() const return 0; } -BlendPoint FeatureBlendCurve::GetBlendPoint(App::PropertyLinkSub& link, - App::PropertyFloatConstraint& param, - App::PropertyIntegerConstraint& continuity) +BlendPoint FeatureBlendCurve::GetBlendPoint( + App::PropertyLinkSub& link, + App::PropertyFloatConstraint& param, + App::PropertyIntegerConstraint& continuity +) { auto linked = link.getValue(); TopoDS_Shape axEdge; if (link.getSubValues().size() > 0 && link.getSubValues()[0].length() > 0) { - axEdge = Part::Feature::getShape(linked, - Part::ShapeOption::NeedSubElement - | Part::ShapeOption::ResolveLink - | Part::ShapeOption::Transform, - link.getSubValues()[0].c_str()); + axEdge = Part::Feature::getShape( + linked, + Part::ShapeOption::NeedSubElement | Part::ShapeOption::ResolveLink + | Part::ShapeOption::Transform, + link.getSubValues()[0].c_str() + ); } else { - axEdge = Feature::getShape(linked, - Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); + axEdge = Feature::getShape(linked, Part::ShapeOption::ResolveLink | Part::ShapeOption::Transform); } if (axEdge.IsNull()) { diff --git a/src/Mod/Surface/App/Blending/FeatureBlendCurve.h b/src/Mod/Surface/App/Blending/FeatureBlendCurve.h index 39af352db3..212695e9fd 100644 --- a/src/Mod/Surface/App/Blending/FeatureBlendCurve.h +++ b/src/Mod/Surface/App/Blending/FeatureBlendCurve.h @@ -62,9 +62,11 @@ public: } private: - BlendPoint GetBlendPoint(App::PropertyLinkSub& link, - App::PropertyFloatConstraint& param, - App::PropertyIntegerConstraint& Continuity); + BlendPoint GetBlendPoint( + App::PropertyLinkSub& link, + App::PropertyFloatConstraint& param, + App::PropertyIntegerConstraint& Continuity + ); double RelativeToRealParameters(double, double, double); protected: diff --git a/src/Mod/Surface/App/FeatureCut.cpp b/src/Mod/Surface/App/FeatureCut.cpp index 740755d447..88e511cb7c 100644 --- a/src/Mod/Surface/App/FeatureCut.cpp +++ b/src/Mod/Surface/App/FeatureCut.cpp @@ -56,7 +56,8 @@ App::DocumentObjectExecReturn* Cut::execute() std::vector shapes = ShapeList.getValues(); if (shapes.size() != 2) { return new App::DocumentObjectExecReturn( - "Two shapes must be entered at a time for a cut operation"); + "Two shapes must be entered at a time for a cut operation" + ); } Part::TopoShape ts1; diff --git a/src/Mod/Surface/App/FeatureExtend.cpp b/src/Mod/Surface/App/FeatureExtend.cpp index bf7ff0766c..19f44af0a2 100644 --- a/src/Mod/Surface/App/FeatureExtend.cpp +++ b/src/Mod/Surface/App/FeatureExtend.cpp @@ -43,9 +43,7 @@ using namespace Surface; -const App::PropertyIntegerConstraint::Constraints SampleRange = {2, - std::numeric_limits::max(), - 1}; +const App::PropertyIntegerConstraint::Constraints SampleRange = {2, std::numeric_limits::max(), 1}; const App::PropertyFloatConstraint::Constraints ToleranceRange = {0.0, 10.0, 0.01}; const App::PropertyFloatConstraint::Constraints ExtendRange = {-0.5, 10.0, 0.01}; PROPERTY_SOURCE(Surface::Extend, Part::Spline) @@ -106,8 +104,9 @@ App::DocumentObjectExecReturn* Extend::execute() return new App::DocumentObjectExecReturn("Not exactly one sub-shape linked."); } - TopoDS_Shape shape = - static_cast(part)->Shape.getShape().getSubShape(faces[0].c_str()); + TopoDS_Shape shape = static_cast(part)->Shape.getShape().getSubShape( + faces[0].c_str() + ); if (shape.IsNull() || shape.ShapeType() != TopAbs_FACE) { return new App::DocumentObjectExecReturn("Sub-shape is not a face."); } @@ -188,13 +187,10 @@ void Extend::onChanged(const App::Property* prop) Part::Spline::onChanged(prop); } -void Extend::handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) +void Extend::handleChangedPropertyName(Base::XMLReader& reader, const char* TypeName, const char* PropName) { Base::Type type = Base::Type::fromName(TypeName); - if (App::PropertyFloatConstraint::getClassTypeId() == type - && strcmp(PropName, "ExtendU") == 0) { + if (App::PropertyFloatConstraint::getClassTypeId() == type && strcmp(PropName, "ExtendU") == 0) { App::PropertyFloatConstraint v; v.Restore(reader); ExtendUNeg.setValue(v.getValue()); diff --git a/src/Mod/Surface/App/FeatureExtend.h b/src/Mod/Surface/App/FeatureExtend.h index 5bf2983cfd..33cad12425 100644 --- a/src/Mod/Surface/App/FeatureExtend.h +++ b/src/Mod/Surface/App/FeatureExtend.h @@ -62,9 +62,11 @@ public: protected: void onChanged(const App::Property* prop) override; - void handleChangedPropertyName(Base::XMLReader& reader, - const char* TypeName, - const char* PropName) override; + void handleChangedPropertyName( + Base::XMLReader& reader, + const char* TypeName, + const char* PropName + ) override; private: bool lockOnChangeMutex {false}; diff --git a/src/Mod/Surface/App/FeatureFilling.cpp b/src/Mod/Surface/App/FeatureFilling.cpp index 78813301c9..eaa6f34583 100644 --- a/src/Mod/Surface/App/FeatureFilling.cpp +++ b/src/Mod/Surface/App/FeatureFilling.cpp @@ -106,11 +106,13 @@ short Filling::mustExecute() const return 0; } -void Filling::addConstraints(BRepFill_Filling& builder, - const App::PropertyLinkSubList& edges, - const App::PropertyStringList& faces, - const App::PropertyIntegerList& orders, - Standard_Boolean bnd) +void Filling::addConstraints( + BRepFill_Filling& builder, + const App::PropertyLinkSubList& edges, + const App::PropertyStringList& faces, + const App::PropertyIntegerList& orders, + Standard_Boolean bnd +) { auto edge_obj = edges.getValues(); auto edge_sub = edges.getSubValues(); @@ -164,7 +166,8 @@ void Filling::addConstraints(BRepFill_Filling& builder, } else { Standard_Failure::Raise( - "Boundary edges must be added in a consecutive order"); + "Boundary edges must be added in a consecutive order" + ); } } } @@ -183,7 +186,8 @@ void Filling::addConstraints(BRepFill_Filling& builder, } else { Standard_Failure::Raise( - "Boundary edges must be added in a consecutive order"); + "Boundary edges must be added in a consecutive order" + ); } } } @@ -204,9 +208,11 @@ void Filling::addConstraints(BRepFill_Filling& builder, } // Add free support faces with their continuities -void Filling::addConstraints(BRepFill_Filling& builder, - const App::PropertyLinkSubList& faces, - const App::PropertyIntegerList& orders) +void Filling::addConstraints( + BRepFill_Filling& builder, + const App::PropertyLinkSubList& faces, + const App::PropertyIntegerList& orders +) { auto face_obj = faces.getValues(); auto face_sub = faces.getSubValues(); @@ -268,20 +274,11 @@ App::DocumentObjectExecReturn* Filling::execute() unsigned int maxseg = MaximumSegments.getValue(); try { - BRepFill_Filling builder(degree, - ptsoncurve, - numIter, - anisotropy, - tol2d, - tol3d, - tolG1, - tolG2, - maxdeg, - maxseg); + BRepFill_Filling + builder(degree, ptsoncurve, numIter, anisotropy, tol2d, tol3d, tolG1, tolG2, maxdeg, maxseg); if ((BoundaryEdges.getSize()) < 1) { - return new App::DocumentObjectExecReturn( - "Border must have at least one curve defined."); + return new App::DocumentObjectExecReturn("Border must have at least one curve defined."); } // Load the initial surface if set diff --git a/src/Mod/Surface/App/FeatureFilling.h b/src/Mod/Surface/App/FeatureFilling.h index 8ce5a2bb26..635024f547 100644 --- a/src/Mod/Surface/App/FeatureFilling.h +++ b/src/Mod/Surface/App/FeatureFilling.h @@ -43,8 +43,8 @@ public: Filling(); // Properties of Curves - App::PropertyLinkSubList - BoundaryEdges; // Boundary Edges (C0 is required for edges without a corresponding face) + App::PropertyLinkSubList BoundaryEdges; // Boundary Edges (C0 is required for edges without a + // corresponding face) App::PropertyStringList BoundaryFaces; // Boundary Faces (C0, G1 and G2 are possible) App::PropertyIntegerList BoundaryOrder; // Order of constraint on border faces App::PropertyLinkSubList UnboundEdges; // Unbound constraint edges (C0 is required for edges @@ -78,14 +78,18 @@ public: } private: - void addConstraints(BRepFill_Filling& builder, - const App::PropertyLinkSubList& edges, - const App::PropertyStringList& faces, - const App::PropertyIntegerList& orders, - Standard_Boolean bnd); - void addConstraints(BRepFill_Filling& builder, - const App::PropertyLinkSubList& faces, - const App::PropertyIntegerList& orders); + void addConstraints( + BRepFill_Filling& builder, + const App::PropertyLinkSubList& edges, + const App::PropertyStringList& faces, + const App::PropertyIntegerList& orders, + Standard_Boolean bnd + ); + void addConstraints( + BRepFill_Filling& builder, + const App::PropertyLinkSubList& faces, + const App::PropertyIntegerList& orders + ); void addConstraints(BRepFill_Filling& builder, const App::PropertyLinkSubList& points); }; diff --git a/src/Mod/Surface/App/FeatureGeomFillSurface.cpp b/src/Mod/Surface/App/FeatureGeomFillSurface.cpp index 7b930b49ad..a6e140b17d 100644 --- a/src/Mod/Surface/App/FeatureGeomFillSurface.cpp +++ b/src/Mod/Surface/App/FeatureGeomFillSurface.cpp @@ -77,8 +77,8 @@ void ShapeValidator::checkEdge(const TopoDS_Shape& shape) Standard_Real u0; // contains output Standard_Real u1; // contains output Handle(Geom_Curve) c_geom = BRep_Tool::Curve(etmp, heloc, u0, u1); // The geometric curve - Handle(Geom_BezierCurve) bez_geom = - Handle(Geom_BezierCurve)::DownCast(c_geom); // Try to get Bezier curve + Handle(Geom_BezierCurve) bez_geom = Handle(Geom_BezierCurve)::DownCast(c_geom); // Try to get + // Bezier curve // if not a Bezier then try to create a B-spline surface from the edges if (bez_geom.IsNull()) { @@ -98,9 +98,11 @@ void ShapeValidator::checkAndAdd(const TopoDS_Shape& shape, Handle(ShapeExtend_W } } -void ShapeValidator::checkAndAdd(const Part::TopoShape& ts, - const char* subName, - Handle(ShapeExtend_WireData) * aWD) +void ShapeValidator::checkAndAdd( + const Part::TopoShape& ts, + const char* subName, + Handle(ShapeExtend_WireData) * aWD +) { try { if (subName && *subName != '\0') { @@ -181,7 +183,8 @@ App::DocumentObjectExecReturn* GeomFillSurface::execute() } catch (StdFail_NotDone&) { return new App::DocumentObjectExecReturn( - "A curve was not a B-spline and could not be converted into one."); + "A curve was not a B-spline and could not be converted into one." + ); } catch (Standard_Failure& e) { return new App::DocumentObjectExecReturn(e.GetMessageString()); @@ -197,8 +200,7 @@ GeomFill_FillingStyle GeomFillSurface::getFillingStyle() case GeomFill_CurvedStyle: return static_cast(FillType.getValue()); default: - Standard_Failure::Raise( - "Filling style must be 0 (Stretch), 1 (Coons), or 2 (Curved).\n"); + Standard_Failure::Raise("Filling style must be 0 (Stretch), 1 (Coons), or 2 (Curved).\n"); return GeomFill_StretchStyle; // this is to shut up the compiler } } @@ -217,8 +219,7 @@ bool GeomFillSurface::getWire(TopoDS_Wire& aWire) for (const auto& set : boundary) { if (set.first->isDerivedFrom()) { for (const auto& jt : set.second) { - const Part::TopoShape& ts = - static_cast(set.first)->Shape.getShape(); + const Part::TopoShape& ts = static_cast(set.first)->Shape.getShape(); validator.checkAndAdd(ts, jt.c_str(), &aWD); } } @@ -279,8 +280,8 @@ void GeomFillSurface::createBezierSurface(TopoDS_Wire& aWire) const TopoDS_Edge hedge = TopoDS::Edge(anExp.Current()); TopLoc_Location heloc; // this will be output Handle(Geom_Curve) c_geom = BRep_Tool::Curve(hedge, heloc, u1, u2); // The geometric curve - Handle(Geom_BezierCurve) bezier = - Handle(Geom_BezierCurve)::DownCast(c_geom); // Try to get Bezier curve + Handle(Geom_BezierCurve) bezier = Handle(Geom_BezierCurve)::DownCast(c_geom); // Try to get + // Bezier curve if (!bezier.IsNull()) { bezier->Segment(u1, u2); // DownCast(c_geom) will not trim bezier, so DIY @@ -330,8 +331,9 @@ void GeomFillSurface::createBSplineSurface(TopoDS_Wire& aWire) const TopoDS_Edge& edge = TopoDS::Edge(anExp.Current()); TopLoc_Location heloc; // this will be output Handle(Geom_Curve) c_geom = BRep_Tool::Curve(edge, heloc, u1, u2); // The geometric curve - Handle(Geom_BSplineCurve) bspline = - Handle(Geom_BSplineCurve)::DownCast(c_geom); // Try to get BSpline curve + Handle(Geom_BSplineCurve) bspline = Handle(Geom_BSplineCurve)::DownCast( + c_geom + ); // Try to get BSpline curve gp_Trsf transf = heloc.Transformation(); if (!bspline.IsNull()) { @@ -355,11 +357,12 @@ void GeomFillSurface::createBSplineSurface(TopoDS_Wire& aWire) else { // GeomConvert failed, try ShapeConstruct_Curve now ShapeConstruct_Curve scc; - Handle(Geom_BSplineCurve) spline = - scc.ConvertToBSpline(c_geom, u1, u2, Precision::Confusion()); + Handle(Geom_BSplineCurve) spline + = scc.ConvertToBSpline(c_geom, u1, u2, Precision::Confusion()); if (spline.IsNull()) { Standard_Failure::Raise( - "A curve was not a B-spline and could not be converted into one."); + "A curve was not a B-spline and could not be converted into one." + ); } spline->Transform(transf); // apply original transformation to control points curves.push_back(spline); diff --git a/src/Mod/Surface/App/FeatureGeomFillSurface.h b/src/Mod/Surface/App/FeatureGeomFillSurface.h index bba5288dbb..840316d6d9 100644 --- a/src/Mod/Surface/App/FeatureGeomFillSurface.h +++ b/src/Mod/Surface/App/FeatureGeomFillSurface.h @@ -49,9 +49,11 @@ public: void initValidator(); void checkEdge(const TopoDS_Shape& shape); void checkAndAdd(const TopoDS_Shape& shape, Handle(ShapeExtend_WireData) * aWD = nullptr); - void checkAndAdd(const Part::TopoShape& ts, - const char* subName, - Handle(ShapeExtend_WireData) * aWire = nullptr); + void checkAndAdd( + const Part::TopoShape& ts, + const char* subName, + Handle(ShapeExtend_WireData) * aWire = nullptr + ); bool isBezier() const { diff --git a/src/Mod/Surface/App/FeatureSections.cpp b/src/Mod/Surface/App/FeatureSections.cpp index 217473478a..704179145d 100644 --- a/src/Mod/Surface/App/FeatureSections.cpp +++ b/src/Mod/Surface/App/FeatureSections.cpp @@ -63,10 +63,11 @@ App::DocumentObjectExecReturn* Sections::execute() if (!edge.IsNull() && edge.ShapeType() == TopAbs_EDGE) { BRepAdaptor_Curve curve_adapt(TopoDS::Edge(edge)); const TopLoc_Location& loc = edge.Location(); - Handle(Geom_TrimmedCurve) hCurve = - new Geom_TrimmedCurve(curve_adapt.Curve().Curve(), - curve_adapt.FirstParameter(), - curve_adapt.LastParameter()); + Handle(Geom_TrimmedCurve) hCurve = new Geom_TrimmedCurve( + curve_adapt.Curve().Curve(), + curve_adapt.FirstParameter(), + curve_adapt.LastParameter() + ); if (!loc.IsIdentity()) { hCurve->Transform(loc.Transformation()); } diff --git a/src/Mod/Surface/App/FeatureSewing.cpp b/src/Mod/Surface/App/FeatureSewing.cpp index 08b5a2aba3..834df9b8dd 100644 --- a/src/Mod/Surface/App/FeatureSewing.cpp +++ b/src/Mod/Surface/App/FeatureSewing.cpp @@ -39,17 +39,9 @@ PROPERTY_SOURCE(Surface::Sewing, Part::Feature) Sewing::Sewing() { ADD_PROPERTY_TYPE(ShapeList, (nullptr, ""), "Sewing", App::Prop_None, "Input shapes"); - ADD_PROPERTY_TYPE(Tolerance, - (Precision::Confusion()), - "Sewing", - App::Prop_None, - "Sewing tolerance"); + ADD_PROPERTY_TYPE(Tolerance, (Precision::Confusion()), "Sewing", App::Prop_None, "Sewing tolerance"); ADD_PROPERTY_TYPE(SewingOption, (true), "Sewing", App::Prop_None, "Sewing option"); - ADD_PROPERTY_TYPE(DegenerateShape, - (true), - "Sewing", - App::Prop_None, - "Analysis of degenerated shapes"); + ADD_PROPERTY_TYPE(DegenerateShape, (true), "Sewing", App::Prop_None, "Analysis of degenerated shapes"); ADD_PROPERTY_TYPE(CutFreeEdges, (true), "Sewing", App::Prop_None, "Cutting of free edges"); ADD_PROPERTY_TYPE(Nonmanifold, (false), "Sewing", App::Prop_None, "Non-manifold processing"); diff --git a/src/Mod/Surface/Gui/Blending/TaskBlendCurve.cpp b/src/Mod/Surface/Gui/Blending/TaskBlendCurve.cpp index cef2da14d8..6de85d25be 100644 --- a/src/Mod/Surface/Gui/Blending/TaskBlendCurve.cpp +++ b/src/Mod/Surface/Gui/Blending/TaskBlendCurve.cpp @@ -352,8 +352,10 @@ QString BlendCurvePanel::linkToString(const App::PropertyLinkSub& link) const auto& sub = link.getSubValues(); std::string name = sub.empty() ? "" : sub.front(); - return QString::fromLatin1("%1 [%2]").arg(QString::fromLatin1(obj->Label.getValue()), - QString::fromStdString(name)); + return QString::fromLatin1("%1 [%2]").arg( + QString::fromLatin1(obj->Label.getValue()), + QString::fromStdString(name) + ); } void BlendCurvePanel::setStartEdge(App::DocumentObject* obj, const std::string& subname) diff --git a/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp b/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp index 5fd73857ad..67c36ef7f9 100644 --- a/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp +++ b/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp @@ -44,11 +44,10 @@ void ViewProviderBlendCurve::setupContextMenu(QMenu* menu, QObject* receiver, co { auto func = new Gui::ActionFunction(menu); QAction* act = menu->addAction( - QObject::tr("Edit %1").arg(QString::fromUtf8(getObject()->Label.getValue()))); + QObject::tr("Edit %1").arg(QString::fromUtf8(getObject()->Label.getValue())) + ); act->setData(QVariant((int)ViewProvider::Default)); - func->trigger(act, [this]() { - this->startDefaultEditMode(); - }); + func->trigger(act, [this]() { this->startDefaultEditMode(); }); ViewProviderSpline::setupContextMenu(menu, receiver, member); } diff --git a/src/Mod/Surface/Gui/Command.cpp b/src/Mod/Surface/Gui/Command.cpp index ff6981d611..12844333fd 100644 --- a/src/Mod/Surface/Gui/Command.cpp +++ b/src/Mod/Surface/Gui/Command.cpp @@ -111,9 +111,11 @@ CmdSurfaceFilling::CmdSurfaceFilling() sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Filling"); - sToolTipText = QT_TR_NOOP("Creates a surface from a series of selected boundary edges.\n" - "Additionally, the surface may be constrained by edges and\n" - "vertices that are not on the boundary."); + sToolTipText = QT_TR_NOOP( + "Creates a surface from a series of selected boundary edges.\n" + "Additionally, the surface may be constrained by edges and\n" + "vertices that are not on the boundary." + ); sStatusTip = sToolTipText; sWhatsThis = "Surface_Filling"; sPixmap = "Surface_Filling"; @@ -162,9 +164,7 @@ void CmdSurfaceGeomFillSurface::activated(int iMsg) std::string FeatName = getUniqueObjectName("Surface"); openCommand(QT_TRANSLATE_NOOP("Command", "Create surface")); - doCommand(Doc, - "App.ActiveDocument.addObject(\"Surface::GeomFillSurface\",\"%s\")", - FeatName.c_str()); + doCommand(Doc, "App.ActiveDocument.addObject(\"Surface::GeomFillSurface\",\"%s\")", FeatName.c_str()); doCommand(Doc, "Gui.ActiveDocument.setEdit('%s',0)", FeatName.c_str()); } @@ -177,8 +177,10 @@ CmdSurfaceCurveOnMesh::CmdSurfaceCurveOnMesh() sAppModule = "MeshPart"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Curve on Mesh"); - sToolTipText = QT_TR_NOOP("Creates an approximated curve on top of a mesh.\n" - "This command only works with a mesh object."); + sToolTipText = QT_TR_NOOP( + "Creates an approximated curve on top of a mesh.\n" + "This command only works with a mesh object." + ); sWhatsThis = "Surface_CurveOnMesh"; sStatusTip = sToolTipText; sPixmap = "Surface_CurveOnMesh"; @@ -187,9 +189,11 @@ CmdSurfaceCurveOnMesh::CmdSurfaceCurveOnMesh() void CmdSurfaceCurveOnMesh::activated(int) { - doCommand(Doc, - "import MeshPartGui, FreeCADGui\n" - "FreeCADGui.runCommand('MeshPart_CurveOnMesh')\n"); + doCommand( + Doc, + "import MeshPartGui, FreeCADGui\n" + "FreeCADGui.runCommand('MeshPart_CurveOnMesh')\n" + ); } bool CmdSurfaceCurveOnMesh::isActive() @@ -227,8 +231,8 @@ void CmdBlendCurve::activated(int) std::string objName[2]; std::string edge[2]; std::string featName = getUniqueObjectName("BlendCurve"); - std::vector sel = - getSelection().getSelectionEx(nullptr, Part::Feature::getClassTypeId()); + std::vector sel + = getSelection().getSelectionEx(nullptr, Part::Feature::getClassTypeId()); objName[0] = sel[0].getFeatName(); edge[0] = sel[0].getSubNames()[0]; @@ -242,21 +246,27 @@ void CmdBlendCurve::activated(int) edge[1] = sel[1].getSubNames()[0]; } openCommand(QT_TRANSLATE_NOOP("Command", "Blend Curve")); - doCommand(Doc, - "App.ActiveDocument.addObject(\"Surface::FeatureBlendCurve\",\"%s\")", - featName.c_str()); - doCommand(Doc, - "App.ActiveDocument.%s.StartEdge = (App.getDocument('%s').getObject('%s'),['%s'])", - featName.c_str(), - docName.c_str(), - objName[0].c_str(), - edge[0].c_str()); - doCommand(Doc, - "App.ActiveDocument.%s.EndEdge = (App.getDocument('%s').getObject('%s'),['%s'])", - featName.c_str(), - docName.c_str(), - objName[1].c_str(), - edge[1].c_str()); + doCommand( + Doc, + "App.ActiveDocument.addObject(\"Surface::FeatureBlendCurve\",\"%s\")", + featName.c_str() + ); + doCommand( + Doc, + "App.ActiveDocument.%s.StartEdge = (App.getDocument('%s').getObject('%s'),['%s'])", + featName.c_str(), + docName.c_str(), + objName[0].c_str(), + edge[0].c_str() + ); + doCommand( + Doc, + "App.ActiveDocument.%s.EndEdge = (App.getDocument('%s').getObject('%s'),['%s'])", + featName.c_str(), + docName.c_str(), + objName[1].c_str(), + edge[1].c_str() + ); updateActive(); commitCommand(); } @@ -275,8 +285,10 @@ CmdSurfaceExtendFace::CmdSurfaceExtendFace() sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Extend Face"); - sToolTipText = QT_TR_NOOP("Extrapolates the selected face or surface at its boundaries with " - "its local U and V parameters"); + sToolTipText = QT_TR_NOOP( + "Extrapolates the selected face or surface at its boundaries with " + "its local U and V parameters" + ); sWhatsThis = "Surface_ExtendFace"; sStatusTip = sToolTipText; sPixmap = "Surface_ExtendFace"; @@ -291,21 +303,18 @@ void CmdSurfaceExtendFace::activated(int) openCommand(QT_TRANSLATE_NOOP("Command", "Extend surface")); std::string FeatName = getUniqueObjectName("Surface"); std::string supportString = faceFilter.Result[0][0].getAsPropertyLinkSubString(); - doCommand(Doc, - "App.ActiveDocument.addObject(\"Surface::Extend\",\"%s\")", - FeatName.c_str()); - doCommand(Doc, - "App.ActiveDocument.%s.Face = %s", - FeatName.c_str(), - supportString.c_str()); + doCommand(Doc, "App.ActiveDocument.addObject(\"Surface::Extend\",\"%s\")", FeatName.c_str()); + doCommand(Doc, "App.ActiveDocument.%s.Face = %s", FeatName.c_str(), supportString.c_str()); updateActive(); commitCommand(); } } else { - QMessageBox::warning(Gui::getMainWindow(), - qApp->translate("Surface_ExtendFace", "Wrong selection"), - qApp->translate("Surface_ExtendFace", "Select a single face")); + QMessageBox::warning( + Gui::getMainWindow(), + qApp->translate("Surface_ExtendFace", "Wrong selection"), + qApp->translate("Surface_ExtendFace", "Select a single face") + ); } } diff --git a/src/Mod/Surface/Gui/TaskFilling.cpp b/src/Mod/Surface/Gui/TaskFilling.cpp index 5a4259e90b..9ddc115619 100644 --- a/src/Mod/Surface/Gui/TaskFilling.cpp +++ b/src/Mod/Surface/Gui/TaskFilling.cpp @@ -111,7 +111,8 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& Part::Feature* base = dynamic_cast(it.first); if (base) { PartGui::ViewProviderPartExt* svp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); + Gui::Application::Instance->getViewProvider(base) + ); if (svp) { switch (type) { case ViewProviderFilling::Vertex: @@ -124,8 +125,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& for (const auto& jt : it.second) { // check again that the index is in range because it's possible that // the sub-names are invalid - std::size_t idx = - static_cast(std::stoi(jt.substr(6)) - 1); + std::size_t idx = static_cast(std::stoi(jt.substr(6)) - 1); if (idx < colors.size()) { colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } @@ -145,8 +145,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& colors.resize(eMap.Extent(), svp->LineColor.getValue()); for (const auto& jt : it.second) { - std::size_t idx = - static_cast(std::stoi(jt.substr(4)) - 1); + std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that // the sub-names are invalid if (idx < colors.size()) { @@ -168,13 +167,11 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& materials.resize(fMap.Extent(), svp->ShapeAppearance[0]); for (const auto& jt : it.second) { - std::size_t idx = - static_cast(std::stoi(jt.substr(4)) - 1); + std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that // the sub-names are invalid if (idx < materials.size()) { - materials[idx].diffuseColor = - Base::Color(1.0, 0.0, 1.0); // magenta + materials[idx].diffuseColor = Base::Color(1.0, 0.0, 1.0); // magenta } } @@ -342,8 +339,10 @@ void FillingPanel::setEditedObject(Surface::Filling* fea) App::DocumentObject* initFace = editedObject->InitialFace.getValue(); const std::vector& subList = editedObject->InitialFace.getSubValues(); if (initFace && subList.size() == 1) { - QString text = QStringLiteral("%1.%2").arg(QString::fromUtf8(initFace->Label.getValue()), - QString::fromStdString(subList.front())); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(initFace->Label.getValue()), + QString::fromStdString(subList.front()) + ); ui->lineInitFaceName->setText(text); } @@ -375,8 +374,10 @@ void FillingPanel::setEditedObject(Surface::Filling* fea) QListWidgetItem* item = new QListWidgetItem(ui->listBoundary); ui->listBoundary->addItem(item); - QString text = QStringLiteral("%1.%2").arg(QString::fromUtf8(obj->Label.getValue()), - QString::fromStdString(edge)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(obj->Label.getValue()), + QString::fromStdString(edge) + ); item->setText(text); // The user data field of a list widget item @@ -414,14 +415,15 @@ void FillingPanel::open() checkOpenCommand(); // highlight the boundary edges - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + true + ); // highlight the referenced face std::vector links; - links.emplace_back(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues()); + links.emplace_back(editedObject->InitialFace.getValue(), editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, true); Gui::Selection().clearSelection(); @@ -462,14 +464,18 @@ void FillingPanel::slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) // If this view provider is being deleted then reset the colors of // referenced part objects. The dialog will be deleted later. if (this->vp == &Obj) { - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + false + ); // unhighlight the referenced face std::vector links; - links.emplace_back(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues()); + links.emplace_back( + editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues() + ); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); } } @@ -483,20 +489,23 @@ bool FillingPanel::accept() editedObject->recomputeFeature(); } if (!editedObject->isValid()) { - QMessageBox::warning(this, - tr("Invalid object"), - QString::fromLatin1(editedObject->getStatusString())); + QMessageBox::warning( + this, + tr("Invalid object"), + QString::fromLatin1(editedObject->getStatusString()) + ); return false; } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + false + ); // unhighlight the referenced face std::vector links; - links.emplace_back(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues()); + links.emplace_back(editedObject->InitialFace.getValue(), editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); return true; @@ -505,14 +514,18 @@ bool FillingPanel::accept() bool FillingPanel::reject() { if (!editedObject.expired()) { - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + false + ); // unhighlight the referenced face std::vector links; - links.emplace_back(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues()); + links.emplace_back( + editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues() + ); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); } @@ -529,8 +542,10 @@ void FillingPanel::onLineInitFaceNameTextChanged(const QString& text) // unhighlight the referenced face std::vector links; - links.emplace_back(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues()); + links.emplace_back( + editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues() + ); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); editedObject->InitialFace.setValue(nullptr); @@ -593,10 +608,7 @@ void FillingPanel::onListBoundaryItemDoubleClicked(QListWidgetItem* item) TopTools_IndexedMapOfShape faces; TopExp::MapShapes(shape.getShape(), TopAbs_FACE, faces); TopTools_IndexedDataMapOfShapeListOfShape edge2Face; - TopExp::MapShapesAndAncestors(shape.getShape(), - TopAbs_EDGE, - TopAbs_FACE, - edge2Face); + TopExp::MapShapesAndAncestors(shape.getShape(), TopAbs_EDGE, TopAbs_FACE, edge2Face); const TopTools_ListOfShape& adj_faces = edge2Face.FindFromKey(edge); if (adj_faces.Extent() > 0) { int n = adj_faces.Extent(); @@ -629,9 +641,8 @@ void FillingPanel::onListBoundaryItemDoubleClicked(QListWidgetItem* item) } } - Gui::Selection().addSelection(data[0].toByteArray(), - data[1].toByteArray(), - data[2].toByteArray()); + Gui::Selection() + .addSelection(data[0].toByteArray(), data[1].toByteArray(), data[2].toByteArray()); } catch (...) { } @@ -648,9 +659,10 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) checkOpenCommand(); if (selectionMode == InitFace) { Gui::SelectionObject sel(msg); - QString text = - QStringLiteral("%1.%2").arg(QString::fromUtf8(sel.getObject()->Label.getValue()), - QString::fromLatin1(msg.pSubName)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName) + ); ui->lineInitFaceName->setText(text); std::vector subList; @@ -670,9 +682,10 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) ui->listBoundary->addItem(item); Gui::SelectionObject sel(msg); - QString text = - QStringLiteral("%1.%2").arg(QString::fromUtf8(sel.getObject()->Label.getValue()), - QString::fromLatin1(msg.pSubName)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName) + ); item->setText(text); QList data; @@ -702,9 +715,11 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) editedObject->BoundaryOrder.setValues(conts); } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + true + ); } else if (selectionMode == RemoveEdge) { Gui::SelectionObject sel(msg); @@ -724,9 +739,11 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) } } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + false + ); App::DocumentObject* obj = sel.getObject(); std::string sub = msg.pSubName; auto objects = editedObject->BoundaryEdges.getValues(); @@ -758,9 +775,11 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) break; } } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + true + ); } editedObject->recomputeFeature(); @@ -786,9 +805,11 @@ void FillingPanel::onDeleteEdge() auto element = editedObject->BoundaryEdges.getSubValues(); auto it = objects.begin(); auto jt = element.begin(); - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + false + ); for (; it != objects.end() && jt != element.end(); ++it, ++jt) { if (*it == obj && *jt == sub) { std::size_t index = std::distance(objects.begin(), it); @@ -813,9 +834,11 @@ void FillingPanel::onDeleteEdge() break; } } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->BoundaryEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->BoundaryEdges.getSubListValues(), + true + ); editedObject->recomputeFeature(); } diff --git a/src/Mod/Surface/Gui/TaskFillingEdge.cpp b/src/Mod/Surface/Gui/TaskFillingEdge.cpp index 93f1d2467f..37264eac53 100644 --- a/src/Mod/Surface/Gui/TaskFillingEdge.cpp +++ b/src/Mod/Surface/Gui/TaskFillingEdge.cpp @@ -153,26 +153,36 @@ FillingEdgePanel::~FillingEdgePanel() void FillingEdgePanel::setupConnections() { - connect(ui->buttonUnboundEdgeAdd, - &QToolButton::toggled, - this, - &FillingEdgePanel::onButtonUnboundEdgeAddToggled); - connect(ui->buttonUnboundEdgeRemove, - &QToolButton::toggled, - this, - &FillingEdgePanel::onButtonUnboundEdgeRemoveToggled); - connect(ui->listUnbound, - &QListWidget::itemDoubleClicked, - this, - &FillingEdgePanel::onListUnboundItemDoubleClicked); - connect(ui->buttonUnboundAccept, - &QPushButton::clicked, - this, - &FillingEdgePanel::onButtonUnboundAcceptClicked); - connect(ui->buttonUnboundIgnore, - &QPushButton::clicked, - this, - &FillingEdgePanel::onButtonUnboundIgnoreClicked); + connect( + ui->buttonUnboundEdgeAdd, + &QToolButton::toggled, + this, + &FillingEdgePanel::onButtonUnboundEdgeAddToggled + ); + connect( + ui->buttonUnboundEdgeRemove, + &QToolButton::toggled, + this, + &FillingEdgePanel::onButtonUnboundEdgeRemoveToggled + ); + connect( + ui->listUnbound, + &QListWidget::itemDoubleClicked, + this, + &FillingEdgePanel::onListUnboundItemDoubleClicked + ); + connect( + ui->buttonUnboundAccept, + &QPushButton::clicked, + this, + &FillingEdgePanel::onButtonUnboundAcceptClicked + ); + connect( + ui->buttonUnboundIgnore, + &QPushButton::clicked, + this, + &FillingEdgePanel::onButtonUnboundIgnoreClicked + ); } void FillingEdgePanel::appendButtons(Gui::ButtonGroup* buttonGroup) @@ -214,8 +224,10 @@ void FillingEdgePanel::setEditedObject(Surface::Filling* fea) QListWidgetItem* item = new QListWidgetItem(ui->listUnbound); ui->listUnbound->addItem(item); - QString text = QStringLiteral("%1.%2").arg(QString::fromUtf8(obj->Label.getValue()), - QString::fromStdString(edge)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(obj->Label.getValue()), + QString::fromStdString(edge) + ); item->setText(text); // The user data field of a list widget item @@ -253,9 +265,11 @@ void FillingEdgePanel::open() checkOpenCommand(); // highlight the boundary edges - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + true + ); Gui::Selection().clearSelection(); } @@ -290,9 +304,11 @@ void FillingEdgePanel::slotDeletedObject(const Gui::ViewProviderDocumentObject& // If this view provider is being deleted then reset the colors of // referenced part objects. The dialog will be deleted later. if (this->vp == &Obj) { - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + false + ); } } @@ -305,23 +321,29 @@ bool FillingEdgePanel::accept() editedObject->recomputeFeature(); } if (!editedObject->isValid()) { - QMessageBox::warning(this, - tr("Invalid object"), - QString::fromLatin1(editedObject->getStatusString())); + QMessageBox::warning( + this, + tr("Invalid object"), + QString::fromLatin1(editedObject->getStatusString()) + ); return false; } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + false + ); return true; } bool FillingEdgePanel::reject() { - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + false + ); selectionMode = None; Gui::Selection().rmvSelectionGate(); @@ -377,10 +399,7 @@ void FillingEdgePanel::onListUnboundItemDoubleClicked(QListWidgetItem* item) TopTools_IndexedMapOfShape faces; TopExp::MapShapes(shape.getShape(), TopAbs_FACE, faces); TopTools_IndexedDataMapOfShapeListOfShape edge2Face; - TopExp::MapShapesAndAncestors(shape.getShape(), - TopAbs_EDGE, - TopAbs_FACE, - edge2Face); + TopExp::MapShapesAndAncestors(shape.getShape(), TopAbs_EDGE, TopAbs_FACE, edge2Face); const TopTools_ListOfShape& adj_faces = edge2Face.FindFromKey(edge); if (adj_faces.Extent() > 0) { int n = adj_faces.Extent(); @@ -389,12 +408,9 @@ void FillingEdgePanel::onListUnboundItemDoubleClicked(QListWidgetItem* item) // fill up the combo boxes modifyBoundary(true); ui->comboBoxUnboundFaces->addItem(tr("None"), QByteArray("")); - ui->comboBoxUnboundCont->addItem(QStringLiteral("C0"), - static_cast(GeomAbs_C0)); - ui->comboBoxUnboundCont->addItem(QStringLiteral("G1"), - static_cast(GeomAbs_G1)); - ui->comboBoxUnboundCont->addItem(QStringLiteral("G2"), - static_cast(GeomAbs_G2)); + ui->comboBoxUnboundCont->addItem(QStringLiteral("C0"), static_cast(GeomAbs_C0)); + ui->comboBoxUnboundCont->addItem(QStringLiteral("G1"), static_cast(GeomAbs_G1)); + ui->comboBoxUnboundCont->addItem(QStringLiteral("G2"), static_cast(GeomAbs_G2)); TopTools_ListIteratorOfListOfShape it(adj_faces); for (; it.More(); it.Next()) { const TopoDS_Shape& F = it.Value(); @@ -416,9 +432,8 @@ void FillingEdgePanel::onListUnboundItemDoubleClicked(QListWidgetItem* item) } } - Gui::Selection().addSelection(data[0].toByteArray(), - data[1].toByteArray(), - data[2].toByteArray()); + Gui::Selection() + .addSelection(data[0].toByteArray(), data[1].toByteArray(), data[2].toByteArray()); } catch (...) { } @@ -438,9 +453,10 @@ void FillingEdgePanel::onSelectionChanged(const Gui::SelectionChanges& msg) ui->listUnbound->addItem(item); Gui::SelectionObject sel(msg); - QString text = - QStringLiteral("%1.%2").arg(QString::fromUtf8(sel.getObject()->Label.getValue()), - QString::fromLatin1(msg.pSubName)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName) + ); item->setText(text); QList data; @@ -470,9 +486,11 @@ void FillingEdgePanel::onSelectionChanged(const Gui::SelectionChanges& msg) editedObject->UnboundOrder.setValues(conts); } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + true + ); } else if (selectionMode == RemoveEdge) { Gui::SelectionObject sel(msg); @@ -492,9 +510,11 @@ void FillingEdgePanel::onSelectionChanged(const Gui::SelectionChanges& msg) } } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + false + ); App::DocumentObject* obj = sel.getObject(); std::string sub = msg.pSubName; auto objects = editedObject->UnboundEdges.getValues(); @@ -526,9 +546,11 @@ void FillingEdgePanel::onSelectionChanged(const Gui::SelectionChanges& msg) break; } } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + true + ); } editedObject->recomputeFeature(); @@ -554,9 +576,11 @@ void FillingEdgePanel::onDeleteUnboundEdge() auto element = editedObject->UnboundEdges.getSubValues(); auto it = objects.begin(); auto jt = element.begin(); - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + false + ); for (; it != objects.end() && jt != element.end(); ++it, ++jt) { if (*it == obj && *jt == sub) { std::size_t index = std::distance(objects.begin(), it); @@ -581,9 +605,11 @@ void FillingEdgePanel::onDeleteUnboundEdge() break; } } - this->vp->highlightReferences(ViewProviderFilling::Edge, - editedObject->UnboundEdges.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Edge, + editedObject->UnboundEdges.getSubListValues(), + true + ); editedObject->recomputeFeature(); } @@ -596,8 +622,7 @@ void FillingEdgePanel::onButtonUnboundAcceptClicked() QList data; data = item->data(Qt::UserRole).toList(); - QVariant face = - ui->comboBoxUnboundFaces->itemData(ui->comboBoxUnboundFaces->currentIndex()); + QVariant face = ui->comboBoxUnboundFaces->itemData(ui->comboBoxUnboundFaces->currentIndex()); QVariant cont = ui->comboBoxUnboundCont->itemData(ui->comboBoxUnboundCont->currentIndex()); if (data.size() == 5) { data[3] = face; diff --git a/src/Mod/Surface/Gui/TaskFillingVertex.cpp b/src/Mod/Surface/Gui/TaskFillingVertex.cpp index 82a201b3e5..aa091484b1 100644 --- a/src/Mod/Surface/Gui/TaskFillingVertex.cpp +++ b/src/Mod/Surface/Gui/TaskFillingVertex.cpp @@ -146,14 +146,13 @@ FillingVertexPanel::~FillingVertexPanel() void FillingVertexPanel::setupConnections() { - connect(ui->buttonVertexAdd, - &QToolButton::toggled, - this, - &FillingVertexPanel::onButtonVertexAddToggled); - connect(ui->buttonVertexRemove, - &QToolButton::toggled, - this, - &FillingVertexPanel::onButtonVertexRemoveToggled); + connect(ui->buttonVertexAdd, &QToolButton::toggled, this, &FillingVertexPanel::onButtonVertexAddToggled); + connect( + ui->buttonVertexRemove, + &QToolButton::toggled, + this, + &FillingVertexPanel::onButtonVertexRemoveToggled + ); } void FillingVertexPanel::appendButtons(Gui::ButtonGroup* buttonGroup) @@ -177,8 +176,10 @@ void FillingVertexPanel::setEditedObject(Surface::Filling* obj) QListWidgetItem* item = new QListWidgetItem(ui->listFreeVertex); ui->listFreeVertex->addItem(item); - QString text = QStringLiteral("%1.%2").arg(QString::fromUtf8((*it)->Label.getValue()), - QString::fromStdString(*jt)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8((*it)->Label.getValue()), + QString::fromStdString(*jt) + ); item->setText(text); QList data; @@ -203,17 +204,21 @@ void FillingVertexPanel::changeEvent(QEvent* e) void FillingVertexPanel::open() { checkOpenCommand(); - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + true + ); Gui::Selection().clearSelection(); } void FillingVertexPanel::reject() { - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + false + ); } void FillingVertexPanel::clearSelection() @@ -246,9 +251,11 @@ void FillingVertexPanel::slotDeletedObject(const Gui::ViewProviderDocumentObject // If this view provider is being deleted then reset the colors of // referenced part objects. The dialog will be deleted later. if (this->vp == &Obj) { - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + false + ); } } @@ -289,9 +296,10 @@ void FillingVertexPanel::onSelectionChanged(const Gui::SelectionChanges& msg) ui->listFreeVertex->addItem(item); Gui::SelectionObject sel(msg); - QString text = - QStringLiteral("%1.%2").arg(QString::fromUtf8(sel.getObject()->Label.getValue()), - QString::fromLatin1(msg.pSubName)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName) + ); item->setText(text); QList data; @@ -305,9 +313,11 @@ void FillingVertexPanel::onSelectionChanged(const Gui::SelectionChanges& msg) auto element = editedObject->Points.getSubValues(); element.emplace_back(msg.pSubName); editedObject->Points.setValues(objects, element); - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + true + ); } else if (selectionMode == RemoveVertex) { Gui::SelectionObject sel(msg); @@ -323,9 +333,11 @@ void FillingVertexPanel::onSelectionChanged(const Gui::SelectionChanges& msg) } } - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + false + ); App::DocumentObject* obj = sel.getObject(); std::string sub = msg.pSubName; auto objects = editedObject->Points.getValues(); @@ -340,9 +352,11 @@ void FillingVertexPanel::onSelectionChanged(const Gui::SelectionChanges& msg) break; } } - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + true + ); } editedObject->recomputeFeature(); @@ -368,9 +382,11 @@ void FillingVertexPanel::onDeleteVertex() auto element = editedObject->Points.getSubValues(); auto it = objects.begin(); auto jt = element.begin(); - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + false + ); for (; it != objects.end() && jt != element.end(); ++it, ++jt) { if (*it == obj && *jt == sub) { @@ -382,9 +398,11 @@ void FillingVertexPanel::onDeleteVertex() } } - this->vp->highlightReferences(ViewProviderFilling::Vertex, - editedObject->Points.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderFilling::Vertex, + editedObject->Points.getSubListValues(), + true + ); } } diff --git a/src/Mod/Surface/Gui/TaskFillingVertex.h b/src/Mod/Surface/Gui/TaskFillingVertex.h index 219a057aa2..79349bf579 100644 --- a/src/Mod/Surface/Gui/TaskFillingVertex.h +++ b/src/Mod/Surface/Gui/TaskFillingVertex.h @@ -45,9 +45,7 @@ namespace SurfaceGui class ViewProviderFilling; class Ui_TaskFillingVertex; -class FillingVertexPanel: public QWidget, - public Gui::SelectionObserver, - public Gui::DocumentObserver +class FillingVertexPanel: public QWidget, public Gui::SelectionObserver, public Gui::DocumentObserver { Q_OBJECT diff --git a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp index 621ac32348..8e261fed69 100644 --- a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp +++ b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp @@ -55,9 +55,7 @@ PROPERTY_SOURCE(SurfaceGui::ViewProviderGeomFillSurface, PartGui::ViewProviderSp namespace SurfaceGui { -void ViewProviderGeomFillSurface::setupContextMenu(QMenu* menu, - QObject* receiver, - const char* member) +void ViewProviderGeomFillSurface::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { QAction* act; act = menu->addAction(QObject::tr("Edit Filling"), receiver, member); @@ -118,7 +116,8 @@ void ViewProviderGeomFillSurface::highlightReferences(bool on) Part::Feature* base = dynamic_cast(it.first); if (base) { PartGui::ViewProviderPartExt* svp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); + Gui::Application::Instance->getViewProvider(base) + ); if (svp) { if (on) { std::vector colors; @@ -162,9 +161,7 @@ private: Surface::GeomFillSurface* editedObject; }; -bool GeomFillSurface::EdgeSelection::allow(App::Document*, - App::DocumentObject* pObj, - const char* sSubName) +bool GeomFillSurface::EdgeSelection::allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) { // don't allow references to itself if (pObj == editedObject) { @@ -240,38 +237,26 @@ GeomFillSurface::~GeomFillSurface() void GeomFillSurface::setupConnections() { - connect(ui->fillType_stretch, - &QRadioButton::clicked, - this, - &GeomFillSurface::onFillTypeStretchClicked); - connect(ui->fillType_coons, - &QRadioButton::clicked, - this, - &GeomFillSurface::onFillTypeCoonsClicked); - connect(ui->fillType_curved, - &QRadioButton::clicked, - this, - &GeomFillSurface::onFillTypeCurvedClicked); - connect(ui->buttonEdgeAdd, - &QToolButton::toggled, - this, - &GeomFillSurface::onButtonEdgeAddToggled); - connect(ui->buttonEdgeRemove, - &QToolButton::toggled, - this, - &GeomFillSurface::onButtonEdgeRemoveToggled); - connect(ui->listWidget, - &QListWidget::itemDoubleClicked, - this, - &GeomFillSurface::onListWidgetItemDoubleClicked); + connect(ui->fillType_stretch, &QRadioButton::clicked, this, &GeomFillSurface::onFillTypeStretchClicked); + connect(ui->fillType_coons, &QRadioButton::clicked, this, &GeomFillSurface::onFillTypeCoonsClicked); + connect(ui->fillType_curved, &QRadioButton::clicked, this, &GeomFillSurface::onFillTypeCurvedClicked); + connect(ui->buttonEdgeAdd, &QToolButton::toggled, this, &GeomFillSurface::onButtonEdgeAddToggled); + connect(ui->buttonEdgeRemove, &QToolButton::toggled, this, &GeomFillSurface::onButtonEdgeRemoveToggled); + connect( + ui->listWidget, + &QListWidget::itemDoubleClicked, + this, + &GeomFillSurface::onListWidgetItemDoubleClicked + ); } // stores object pointer, its old fill type and adjusts radio buttons according to it. void GeomFillSurface::setEditedObject(Surface::GeomFillSurface* obj) { editedObject = obj; - GeomFill_FillingStyle curtype = - static_cast(editedObject->FillType.getValue()); + GeomFill_FillingStyle curtype = static_cast( + editedObject->FillType.getValue() + ); switch (curtype) { case GeomFill_StretchStyle: ui->fillType_stretch->setChecked(true); @@ -309,8 +294,10 @@ void GeomFillSurface::setEditedObject(Surface::GeomFillSurface* obj) } ui->listWidget->addItem(item); - QString text = QStringLiteral("%1.%2").arg(QString::fromUtf8((*it)->Label.getValue()), - QString::fromStdString(*jt)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8((*it)->Label.getValue()), + QString::fromStdString(*jt) + ); item->setText(text); QList data; @@ -386,15 +373,19 @@ bool GeomFillSurface::accept() int count = ui->listWidget->count(); if (count > 4) { - QMessageBox::warning(this, - tr("Too many edges"), - tr("The tool requires two, three or four edges")); + QMessageBox::warning( + this, + tr("Too many edges"), + tr("The tool requires two, three or four edges") + ); return false; } else if (count < 2) { - QMessageBox::warning(this, - tr("Too less edges"), - tr("The tool requires two, three or four edges")); + QMessageBox::warning( + this, + tr("Too less edges"), + tr("The tool requires two, three or four edges") + ); return false; } @@ -402,9 +393,11 @@ bool GeomFillSurface::accept() editedObject->recomputeFeature(); } if (!editedObject->isValid()) { - QMessageBox::warning(this, - tr("Invalid object"), - QString::fromLatin1(editedObject->getStatusString())); + QMessageBox::warning( + this, + tr("Invalid object"), + QString::fromLatin1(editedObject->getStatusString()) + ); return false; } @@ -445,8 +438,9 @@ void GeomFillSurface::onFillTypeCurvedClicked() void GeomFillSurface::changeFillType(GeomFill_FillingStyle fillType) { - GeomFill_FillingStyle curtype = - static_cast(editedObject->FillType.getValue()); + GeomFill_FillingStyle curtype = static_cast( + editedObject->FillType.getValue() + ); if (curtype != fillType) { checkOpenCommand(); editedObject->FillType.setValue(static_cast(fillType)); @@ -493,9 +487,10 @@ void GeomFillSurface::onSelectionChanged(const Gui::SelectionChanges& msg) ui->listWidget->addItem(item); Gui::SelectionObject sel(msg); - QString text = - QStringLiteral("%1.%2").arg(QString::fromUtf8(sel.getObject()->Label.getValue()), - QString::fromLatin1(msg.pSubName)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName) + ); item->setText(text); QList data; @@ -660,8 +655,7 @@ void GeomFillSurface::exitSelectionMode() // ---------------------------------------------------------------------------- -TaskGeomFillSurface::TaskGeomFillSurface(ViewProviderGeomFillSurface* vp, - Surface::GeomFillSurface* obj) +TaskGeomFillSurface::TaskGeomFillSurface(ViewProviderGeomFillSurface* vp, Surface::GeomFillSurface* obj) { widget = new GeomFillSurface(vp, obj); widget->setWindowTitle(QObject::tr("Surface")); diff --git a/src/Mod/Surface/Gui/TaskSections.cpp b/src/Mod/Surface/Gui/TaskSections.cpp index 672fe324fe..f7eef49b94 100644 --- a/src/Mod/Surface/Gui/TaskSections.cpp +++ b/src/Mod/Surface/Gui/TaskSections.cpp @@ -112,7 +112,8 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& Part::Feature* base = dynamic_cast(it.first); if (base) { PartGui::ViewProviderPartExt* svp = dynamic_cast( - Gui::Application::Instance->getViewProvider(base)); + Gui::Application::Instance->getViewProvider(base) + ); if (svp) { switch (type) { case ViewProviderSections::Vertex: @@ -125,8 +126,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& for (const auto& jt : it.second) { // check again that the index is in range because it's possible that // the sub-names are invalid - std::size_t idx = - static_cast(std::stoi(jt.substr(6)) - 1); + std::size_t idx = static_cast(std::stoi(jt.substr(6)) - 1); if (idx < colors.size()) { colors[idx] = Base::Color(1.0, 0.0, 1.0); // magenta } @@ -146,8 +146,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& colors.resize(eMap.Extent(), svp->LineColor.getValue()); for (const auto& jt : it.second) { - std::size_t idx = - static_cast(std::stoi(jt.substr(4)) - 1); + std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that // the sub-names are invalid if (idx < colors.size()) { @@ -169,8 +168,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& materials.resize(fMap.Extent(), svp->ShapeAppearance[0]); for (const auto& jt : it.second) { - std::size_t idx = - static_cast(std::stoi(jt.substr(4)) - 1); + std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that // the sub-names are invalid if (idx < materials.size()) { @@ -287,10 +285,7 @@ SectionsPanel::SectionsPanel(ViewProviderSections* vp, Surface::Sections* obj) connect(action, &QAction::triggered, this, &SectionsPanel::onDeleteEdge); ui->listSections->setContextMenuPolicy(Qt::ActionsContextMenu); - connect(ui->listSections->model(), - &QAbstractItemModel::rowsMoved, - this, - &SectionsPanel::onIndexesMoved); + connect(ui->listSections->model(), &QAbstractItemModel::rowsMoved, this, &SectionsPanel::onIndexesMoved); } /* @@ -301,10 +296,7 @@ SectionsPanel::~SectionsPanel() = default; void SectionsPanel::setupConnections() { connect(ui->buttonEdgeAdd, &QToolButton::toggled, this, &SectionsPanel::onButtonEdgeAddToggled); - connect(ui->buttonEdgeRemove, - &QToolButton::toggled, - this, - &SectionsPanel::onButtonEdgeRemoveToggled); + connect(ui->buttonEdgeRemove, &QToolButton::toggled, this, &SectionsPanel::onButtonEdgeRemoveToggled); } // stores object pointer, its old fill type and adjusts radio buttons according to it. @@ -325,8 +317,10 @@ void SectionsPanel::setEditedObject(Surface::Sections* fea) QListWidgetItem* item = new QListWidgetItem(ui->listSections); ui->listSections->addItem(item); - QString text = QStringLiteral("%1.%2").arg(QString::fromUtf8(obj->Label.getValue()), - QString::fromStdString(edge)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(obj->Label.getValue()), + QString::fromStdString(edge) + ); item->setText(text); // The user data field of a list widget item @@ -360,9 +354,11 @@ void SectionsPanel::open() checkOpenCommand(); // highlight the boundary edges - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + true + ); Gui::Selection().clearSelection(); @@ -402,9 +398,11 @@ void SectionsPanel::slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj // If this view provider is being deleted then reset the colors of // referenced part objects. The dialog will be deleted later. if (this->vp == &Obj) { - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + false + ); } } @@ -417,24 +415,30 @@ bool SectionsPanel::accept() editedObject->recomputeFeature(); } if (!editedObject->isValid()) { - QMessageBox::warning(this, - tr("Invalid object"), - QString::fromLatin1(editedObject->getStatusString())); + QMessageBox::warning( + this, + tr("Invalid object"), + QString::fromLatin1(editedObject->getStatusString()) + ); return false; } - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + false + ); return true; } bool SectionsPanel::reject() { - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + false + ); selectionMode = None; Gui::Selection().rmvSelectionGate(); @@ -479,9 +483,10 @@ void SectionsPanel::onSelectionChanged(const Gui::SelectionChanges& msg) ui->listSections->addItem(item); Gui::SelectionObject sel(msg); - QString text = - QStringLiteral("%1.%2").arg(QString::fromUtf8(sel.getObject()->Label.getValue()), - QString::fromLatin1(msg.pSubName)); + QString text = QStringLiteral("%1.%2").arg( + QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName) + ); item->setText(text); QList data; @@ -573,16 +578,20 @@ void SectionsPanel::appendCurve(App::DocumentObject* obj, const std::string& sub element.push_back(subname); editedObject->NSections.setValues(objects, element); - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + true + ); } void SectionsPanel::removeCurve(App::DocumentObject* obj, const std::string& subname) { - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - false); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + false + ); auto objects = editedObject->NSections.getValues(); auto element = editedObject->NSections.getSubValues(); @@ -597,9 +606,11 @@ void SectionsPanel::removeCurve(App::DocumentObject* obj, const std::string& sub break; } } - this->vp->highlightReferences(ViewProviderSections::Edge, - editedObject->NSections.getSubListValues(), - true); + this->vp->highlightReferences( + ViewProviderSections::Edge, + editedObject->NSections.getSubListValues(), + true + ); } void SectionsPanel::exitSelectionMode() diff --git a/src/Mod/Surface/SurfaceGlobal.h b/src/Mod/Surface/SurfaceGlobal.h index 67a5a8f5f7..051ad62b73 100644 --- a/src/Mod/Surface/SurfaceGlobal.h +++ b/src/Mod/Surface/SurfaceGlobal.h @@ -24,25 +24,25 @@ #include #ifndef SURFACE_GLOBAL_H -#define SURFACE_GLOBAL_H +# define SURFACE_GLOBAL_H // Surface -#ifndef SurfaceExport -#ifdef Surface_EXPORTS -#define SurfaceExport FREECAD_DECL_EXPORT -#else -#define SurfaceExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef SurfaceExport +# ifdef Surface_EXPORTS +# define SurfaceExport FREECAD_DECL_EXPORT +# else +# define SurfaceExport FREECAD_DECL_IMPORT +# endif +# endif // SurfaceGui -#ifndef SurfaceGuiExport -#ifdef SurfaceGui_EXPORTS -#define SurfaceGuiExport FREECAD_DECL_EXPORT -#else -#define SurfaceGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef SurfaceGuiExport +# ifdef SurfaceGui_EXPORTS +# define SurfaceGuiExport FREECAD_DECL_EXPORT +# else +# define SurfaceGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // SURFACE_GLOBAL_H diff --git a/src/Mod/Test/Gui/AppTestGui.cpp b/src/Mod/Test/Gui/AppTestGui.cpp index 12810e5dcd..ef8b1c2131 100644 --- a/src/Mod/Test/Gui/AppTestGui.cpp +++ b/src/Mod/Test/Gui/AppTestGui.cpp @@ -49,11 +49,13 @@ public: buffer.clear(); } - void sendLog(const std::string& notifiername, - const std::string& msg, - Base::LogStyle level, - Base::IntendedRecipient recipient, - Base::ContentType content) override + void sendLog( + const std::string& notifiername, + const std::string& msg, + Base::LogStyle level, + Base::IntendedRecipient recipient, + Base::ContentType content + ) override { (void)notifiername; (void)msg; @@ -91,8 +93,9 @@ public: Base::Console().error("ERR"); Base::Console().critical("CMS"); if (buffer.str() != expectedResult) { - throw Py::RuntimeError("ILoggerTest: " + buffer.str() + " different from " - + expectedResult); + throw Py::RuntimeError( + "ILoggerTest: " + buffer.str() + " different from " + expectedResult + ); } } @@ -105,16 +108,18 @@ public: } runSingleTest("Print all", "LOGMSGWRNERRCMS"); { - Base::ILoggerBlocker blocker("ILoggerBlockerTest", - Base::ConsoleSingleton::MsgType_Err - | Base::ConsoleSingleton::MsgType_Wrn); + Base::ILoggerBlocker blocker( + "ILoggerBlockerTest", + Base::ConsoleSingleton::MsgType_Err | Base::ConsoleSingleton::MsgType_Wrn + ); runSingleTest("Error & Warning blocked", "LOGMSGCMS"); } runSingleTest("Print all", "LOGMSGWRNERRCMS"); { - Base::ILoggerBlocker blocker("ILoggerBlockerTest", - Base::ConsoleSingleton::MsgType_Log - | Base::ConsoleSingleton::MsgType_Txt); + Base::ILoggerBlocker blocker( + "ILoggerBlockerTest", + Base::ConsoleSingleton::MsgType_Log | Base::ConsoleSingleton::MsgType_Txt + ); runSingleTest("Log & Message blocked", "WRNERRCMS"); } runSingleTest("Print all", "LOGMSGWRNERRCMS"); @@ -122,21 +127,22 @@ public: Base::ILoggerBlocker blocker("ILoggerBlockerTest", Base::ConsoleSingleton::MsgType_Err); runSingleTest("Nested : Error blocked", "LOGMSGWRNCMS"); { - Base::ILoggerBlocker blocker2("ILoggerBlockerTest", - Base::ConsoleSingleton::MsgType_Err - | Base::ConsoleSingleton::MsgType_Wrn); + Base::ILoggerBlocker blocker2( + "ILoggerBlockerTest", + Base::ConsoleSingleton::MsgType_Err | Base::ConsoleSingleton::MsgType_Wrn + ); runSingleTest( "Nested : Warning blocked + Error (from nesting) + Error (redundancy)", - "LOGMSGCMS"); + "LOGMSGCMS" + ); } runSingleTest("Nested : Error still blocked", "LOGMSGWRNCMS"); } runSingleTest("Print all", "LOGMSGWRNERRCMS"); { Base::ILoggerBlocker blocker("ILoggerBlockerTest"); - Base::Console().setEnabledMsgType("ILoggerBlockerTest", - Base::ConsoleSingleton::MsgType_Log, - true); + Base::Console() + .setEnabledMsgType("ILoggerBlockerTest", Base::ConsoleSingleton::MsgType_Log, true); runSingleTest("Log is enabled but a warning is triggered in debug mode", "LOG"); } runSingleTest("Print all", "LOGMSGWRNERRCMS"); diff --git a/src/Mod/Test/Gui/UnitTestImp.cpp b/src/Mod/Test/Gui/UnitTestImp.cpp index f021d62e35..171ca81c85 100644 --- a/src/Mod/Test/Gui/UnitTestImp.cpp +++ b/src/Mod/Test/Gui/UnitTestImp.cpp @@ -99,10 +99,12 @@ UnitTestDialog::~UnitTestDialog() = default; void UnitTestDialog::setupConnections() { - connect(ui->treeViewFailure, - &QTreeWidget::itemDoubleClicked, - this, - &UnitTestDialog::onTreeViewFailureItemDoubleClicked); + connect( + ui->treeViewFailure, + &QTreeWidget::itemDoubleClicked, + this, + &UnitTestDialog::onTreeViewFailureItemDoubleClicked + ); connect(ui->helpButton, &QPushButton::clicked, this, &UnitTestDialog::onHelpButtonClicked); connect(ui->aboutButton, &QPushButton::clicked, this, &UnitTestDialog::onAboutButtonClicked); connect(ui->startButton, &QPushButton::clicked, this, &UnitTestDialog::onStartButtonClicked); @@ -113,14 +115,16 @@ void UnitTestDialog::setupConnections() */ void UnitTestDialog::setProgressColor(const QColor& col) { - QString qss = QStringLiteral("QProgressBar {\n" - " border: 2px solid grey;\n" - " border-radius: 5px;\n" - "}\n" - "\n" - "QProgressBar::chunk {\n" - " background-color: %1;\n" - "}") + QString qss = QStringLiteral( + "QProgressBar {\n" + " border: 2px solid grey;\n" + " border-radius: 5px;\n" + "}\n" + "\n" + "QProgressBar::chunk {\n" + " background-color: %1;\n" + "}" + ) .arg(col.name()); ui->progressBar->setStyleSheet(qss); } @@ -164,7 +168,8 @@ void UnitTestDialog::onHelpButtonClicked() tr("Enter the name of a callable object which, when called, will return a TestCase.\n" "Click 'start', and the test thus produced will be run.\n\n" "Double click on an error in the tree view to see more information about it, " - "including the stack trace.")); + "including the stack trace.") + ); } /** @@ -177,7 +182,8 @@ void UnitTestDialog::onAboutButtonClicked() tr("About FreeCAD UnitTest"), tr("Copyright (c) Werner Mayer\n\n" "FreeCAD UnitTest is part of FreeCAD and supports writing Unit Tests for " - "ones own modules.")); + "ones own modules.") + ); } /** @@ -189,11 +195,13 @@ void UnitTestDialog::onStartButtonClicked() setProgressColor(QColor(40, 210, 43)); // a darker green ui->startButton->setDisabled(true); try { - Base::Interpreter().runString("import qtunittest, gc\n" - "__qt_test__=qtunittest.QtTestRunner(0,\"\")\n" - "__qt_test__.runClicked()\n" - "del __qt_test__\n" - "gc.collect()\n"); + Base::Interpreter().runString( + "import qtunittest, gc\n" + "__qt_test__=qtunittest.QtTestRunner(0,\"\")\n" + "__qt_test__.runClicked()\n" + "del __qt_test__\n" + "gc.collect()\n" + ); } catch (const Base::PyException& e) { std::string msg = e.what(); diff --git a/src/Mod/Test/Gui/UnitTestPy.cpp b/src/Mod/Test/Gui/UnitTestPy.cpp index b8d98422ba..3dcf4c3db2 100644 --- a/src/Mod/Test/Gui/UnitTestPy.cpp +++ b/src/Mod/Test/Gui/UnitTestPy.cpp @@ -47,9 +47,7 @@ void UnitTestDialogPy::init_type() add_varargs_method("setUnitTest", &UnitTestDialogPy::setUnitTest, "setUnitTest"); add_varargs_method("getUnitTest", &UnitTestDialogPy::getUnitTest, "getUnitTest"); add_varargs_method("setStatusText", &UnitTestDialogPy::setStatusText, "setStatusText"); - add_varargs_method("setProgressFraction", - &UnitTestDialogPy::setProgressFrac, - "setProgressFraction"); + add_varargs_method("setProgressFraction", &UnitTestDialogPy::setProgressFrac, "setProgressFraction"); add_varargs_method("errorDialog", &UnitTestDialogPy::errorDialog, "errorDialog"); add_varargs_method("setRunCount", &UnitTestDialogPy::setRunCount, "setRunCount"); add_varargs_method("setFailCount", &UnitTestDialogPy::setFailCount, "setFailCount"); @@ -96,8 +94,7 @@ Py::Object UnitTestDialogPy::insertError(const Py::Tuple& args) throw Py::Exception(); } - UnitTestDialog::instance()->insertError(QString::fromLatin1(failure), - QString::fromLatin1(details)); + UnitTestDialog::instance()->insertError(QString::fromLatin1(failure), QString::fromLatin1(details)); return Py::None(); } diff --git a/src/Mod/Web/App/AppWeb.cpp b/src/Mod/Web/App/AppWeb.cpp index fdba0ee6ef..55c8a24a75 100644 --- a/src/Mod/Web/App/AppWeb.cpp +++ b/src/Mod/Web/App/AppWeb.cpp @@ -66,18 +66,24 @@ public: Module() : Py::ExtensionModule("Web") { - add_varargs_method("startServer", - &Module::startServer, - "startServer(address=127.0.0.1,port=0) -- Start a server."); - add_varargs_method("waitForConnection", - &Module::waitForConnection, - "waitForConnection(address=127.0.0.1,port=0,timeout=0)\n" - "Start a server, wait for connection and close server.\n" - "Its use is disadvised in a the GUI version, since it will\n" - "stop responding until the function returns."); - add_varargs_method("registerServerFirewall", - &Module::registerServerFirewall, - "registerServerFirewall(callable(string)) -- Register a firewall."); + add_varargs_method( + "startServer", + &Module::startServer, + "startServer(address=127.0.0.1,port=0) -- Start a server." + ); + add_varargs_method( + "waitForConnection", + &Module::waitForConnection, + "waitForConnection(address=127.0.0.1,port=0,timeout=0)\n" + "Start a server, wait for connection and close server.\n" + "Its use is disadvised in a the GUI version, since it will\n" + "stop responding until the function returns." + ); + add_varargs_method( + "registerServerFirewall", + &Module::registerServerFirewall, + "registerServerFirewall(callable(string)) -- Register a firewall." + ); initialize("This module is the Web module."); // register with Python } diff --git a/src/Mod/Web/WebGlobal.h b/src/Mod/Web/WebGlobal.h index 9b3fbea621..7f6714ddd6 100644 --- a/src/Mod/Web/WebGlobal.h +++ b/src/Mod/Web/WebGlobal.h @@ -25,25 +25,25 @@ #include #ifndef WEB_GLOBAL_H -#define WEB_GLOBAL_H +# define WEB_GLOBAL_H // Web -#ifndef WebExport -#ifdef Web_EXPORTS -#define WebExport FREECAD_DECL_EXPORT -#else -#define WebExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef WebExport +# ifdef Web_EXPORTS +# define WebExport FREECAD_DECL_EXPORT +# else +# define WebExport FREECAD_DECL_IMPORT +# endif +# endif // WebGui -#ifndef WebGuiExport -#ifdef WebGui_EXPORTS -#define WebGuiExport FREECAD_DECL_EXPORT -#else -#define WebGuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef WebGuiExport +# ifdef WebGui_EXPORTS +# define WebGuiExport FREECAD_DECL_EXPORT +# else +# define WebGuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif // WEB_GLOBAL_H diff --git a/src/Tools/ThumbnailProvider/Common.h b/src/Tools/ThumbnailProvider/Common.h index e3c4c5c306..7af03d5606 100644 --- a/src/Tools/ThumbnailProvider/Common.h +++ b/src/Tools/ThumbnailProvider/Common.h @@ -38,15 +38,17 @@ STDAPI_(HINSTANCE) DllInstance(); // {4BBBEAB5-BE00-41f4-A209-FE838660B9B1} #define szCLSID_SampleThumbnailProvider L"{4BBBEAB5-BE00-41f4-A209-FE838660B9B1}" -DEFINE_GUID(CLSID_SampleThumbnailProvider, - 0x4bbbeab5, - 0xbe00, - 0x41f4, - 0xa2, - 0x9, - 0xfe, - 0x83, - 0x86, - 0x60, - 0xb9, - 0xb1); +DEFINE_GUID( + CLSID_SampleThumbnailProvider, + 0x4bbbeab5, + 0xbe00, + 0x41f4, + 0xa2, + 0x9, + 0xfe, + 0x83, + 0x86, + 0x60, + 0xb9, + 0xb1 +); diff --git a/src/Tools/ThumbnailProvider/FCConfig.h b/src/Tools/ThumbnailProvider/FCConfig.h index 0239575e0c..375c4b6408 100644 --- a/src/Tools/ThumbnailProvider/FCConfig.h +++ b/src/Tools/ThumbnailProvider/FCConfig.h @@ -38,60 +38,60 @@ // First check for *WIN64* since the *WIN32* are also set on 64-bit platforms #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) -#ifndef FC_OS_WIN32 -#define FC_OS_WIN32 -#endif -#ifndef FC_OS_WIN64 -#define FC_OS_WIN64 -#endif +# ifndef FC_OS_WIN32 +# define FC_OS_WIN32 +# endif +# ifndef FC_OS_WIN64 +# define FC_OS_WIN64 +# endif #elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) -#ifndef FC_OS_WIN32 -#define FC_OS_WIN32 -#endif -#if defined(__MINGW32__) -#if HAVE_CONFIG_H -#include -#endif // HAVE_CONFIG_H -#endif +# ifndef FC_OS_WIN32 +# define FC_OS_WIN32 +# endif +# if defined(__MINGW32__) +# if HAVE_CONFIG_H +# include +# endif // HAVE_CONFIG_H +# endif #elif defined(__MWERKS__) && defined(__INTEL__) -#ifndef FC_OS_WIN32 -#define FC_OS_WIN32 -#endif +# ifndef FC_OS_WIN32 +# define FC_OS_WIN32 +# endif #elif defined(__APPLE__) -#ifndef FC_OS_MACOSX -#define FC_OS_MACOSX -#endif +# ifndef FC_OS_MACOSX +# define FC_OS_MACOSX +# endif #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__GLIBC__) -#ifndef FC_OS_LINUX -#define FC_OS_LINUX -#endif +# ifndef FC_OS_LINUX +# define FC_OS_LINUX +# endif #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) -#ifndef FC_OS_BSD -#define FC_OS_BSD -#endif +# ifndef FC_OS_BSD +# define FC_OS_BSD +# endif #elif defined(__CYGWIN__) -#ifndef FC_OS_CYGWIN -#define FC_OS_CYGWIN +# ifndef FC_OS_CYGWIN +# define FC_OS_CYGWIN // Avoid conflicts with Inventor -#define HAVE_INT8_T -#define HAVE_UINT8_T -#define HAVE_INT16_T -#define HAVE_UINT16_T -#define HAVE_INT32_T -#define HAVE_UINT32_T -#define HAVE_INT64_T -#define HAVE_UINT64_T -#define HAVE_INTPTR_T -#define HAVE_UINTPTR_T -#endif +# define HAVE_INT8_T +# define HAVE_UINT8_T +# define HAVE_INT16_T +# define HAVE_UINT16_T +# define HAVE_INT32_T +# define HAVE_UINT32_T +# define HAVE_INT64_T +# define HAVE_UINT64_T +# define HAVE_INTPTR_T +# define HAVE_UINTPTR_T +# endif #else -#error "FreeCAD is not ported to this OS yet. For help see www.freecad.org" +# error "FreeCAD is not ported to this OS yet. For help see www.freecad.org" #endif #ifdef FC_OS_WIN32 -#define PATHSEP '\\' +# define PATHSEP '\\' #else -#define PATHSEP '/' +# define PATHSEP '/' #endif //************************************************************************** @@ -101,45 +101,45 @@ // nothing specific here #elif defined(FC_OS_WIN64) || defined(FC_OS_WIN32) -#ifndef HAVE_INT8_T -#define HAVE_INT8_T +# ifndef HAVE_INT8_T +# define HAVE_INT8_T typedef signed char int8_t; -#endif +# endif -#ifndef HAVE_UINT8_T -#define HAVE_UINT8_T +# ifndef HAVE_UINT8_T +# define HAVE_UINT8_T typedef unsigned char uint8_t; -#endif +# endif -#ifndef HAVE_INT16_T -#define HAVE_INT16_T +# ifndef HAVE_INT16_T +# define HAVE_INT16_T typedef short int16_t; -#endif +# endif -#ifndef HAVE_UINT16_T -#define HAVE_UINT16_T +# ifndef HAVE_UINT16_T +# define HAVE_UINT16_T typedef unsigned short uint16_t; -#endif +# endif -#ifndef HAVE_INT32_T -#define HAVE_INT32_T +# ifndef HAVE_INT32_T +# define HAVE_INT32_T typedef int int32_t; -#endif +# endif -#ifndef HAVE_UINT32_T -#define HAVE_UINT32_T +# ifndef HAVE_UINT32_T +# define HAVE_UINT32_T typedef unsigned int uint32_t; -#endif +# endif -#ifndef HAVE_INT64_T -#define HAVE_INT64_T +# ifndef HAVE_INT64_T +# define HAVE_INT64_T typedef __int64 int64_t; -#endif +# endif -#ifndef HAVE_UINT64_T -#define HAVE_UINT64_T +# ifndef HAVE_UINT64_T +# define HAVE_UINT64_T typedef unsigned __int64 uint64_t; -#endif +# endif #endif @@ -147,28 +147,28 @@ typedef unsigned __int64 uint64_t; //************************************************************************** // Windows import export DLL defines #ifndef BaseExport -#define BaseExport +# define BaseExport #endif #ifndef GuiExport -#define GuiExport +# define GuiExport #endif #ifndef AppExport -#define AppExport +# define AppExport #endif #ifndef DataExport -#define DataExport +# define DataExport #endif //************************************************************************** // point at which warnings of overly long specifiers disabled (needed for VC6) #ifdef _MSC_VER -#pragma warning(disable : 4251) -#pragma warning(disable : 4996) // suppress deprecated warning for e.g. open() -#if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) -#pragma warning(disable : 4244) -#pragma warning(disable : 4267) -#endif +# pragma warning(disable : 4251) +# pragma warning(disable : 4996) // suppress deprecated warning for e.g. open() +# if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) +# pragma warning(disable : 4244) +# pragma warning(disable : 4267) +# endif #endif diff --git a/src/Tools/ThumbnailProvider/Main.cpp b/src/Tools/ThumbnailProvider/Main.cpp index 154027edcd..04d54aca57 100644 --- a/src/Tools/ThumbnailProvider/Main.cpp +++ b/src/Tools/ThumbnailProvider/Main.cpp @@ -134,7 +134,8 @@ STDAPI DllRegisterServer() L".FCBak\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", NULL, REG_SZ, - (DWORD_PTR)szCLSID_SampleThumbnailProvider}}; + (DWORD_PTR)szCLSID_SampleThumbnailProvider} + }; return CreateRegistryKeys(keys, ARRAYSIZE(keys)); } @@ -172,12 +173,14 @@ STDAPI CreateRegistryKey(REGKEY_SUBKEY_AND_VALUE* pKey) } if (SUCCEEDED(hr)) { - LSTATUS status = SHSetValue(pKey->hKey, - pKey->lpszSubKey, - pKey->lpszValue, - pKey->dwType, - pvData, - (DWORD)cbData); + LSTATUS status = SHSetValue( + pKey->hKey, + pKey->lpszSubKey, + pKey->lpszValue, + pKey->dwType, + pvData, + (DWORD)cbData + ); if (NOERROR != status) { hr = HRESULT_FROM_WIN32(status); } diff --git a/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp b/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp index 4d0314f8c2..7a4481b26d 100644 --- a/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp +++ b/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp @@ -87,11 +87,13 @@ IWICBitmapSource* LoadBitmapFromStream(IStream* ipImageStream) // load WIC's PNG decoder IWICBitmapDecoder* ipDecoder = NULL; - if (FAILED(CoCreateInstance(CLSID_WICPngDecoder, - NULL, - CLSCTX_INPROC_SERVER, - __uuidof(ipDecoder), - reinterpret_cast(&ipDecoder)))) { + if (FAILED(CoCreateInstance( + CLSID_WICPngDecoder, + NULL, + CLSCTX_INPROC_SERVER, + __uuidof(ipDecoder), + reinterpret_cast(&ipDecoder) + ))) { goto Return; } diff --git a/src/Tools/_TEMPLATE_/App/PreCompiled.h b/src/Tools/_TEMPLATE_/App/PreCompiled.h index a606f896f6..b1733b8303 100644 --- a/src/Tools/_TEMPLATE_/App/PreCompiled.h +++ b/src/Tools/_TEMPLATE_/App/PreCompiled.h @@ -30,9 +30,9 @@ // Exporting of App classes #ifdef FC_OS_WIN32 -#define _TEMPLATE_AppExport __declspec(dllexport) +# define _TEMPLATE_AppExport __declspec(dllexport) #else // for Linux -#define _TEMPLATE_AppExport +# define _TEMPLATE_AppExport #endif // standard diff --git a/src/Tools/_TEMPLATE_/Gui/PreCompiled.h b/src/Tools/_TEMPLATE_/Gui/PreCompiled.h index e6264c6fc9..e407e0b549 100644 --- a/src/Tools/_TEMPLATE_/Gui/PreCompiled.h +++ b/src/Tools/_TEMPLATE_/Gui/PreCompiled.h @@ -30,11 +30,11 @@ // Importing of App classes #ifdef FC_OS_WIN32 -#define _TEMPLATE_AppExport __declspec(dllimport) -#define _TEMPLATE_GuiExport __declspec(dllexport) +# define _TEMPLATE_AppExport __declspec(dllimport) +# define _TEMPLATE_GuiExport __declspec(dllexport) #else // for Linux -#define _TEMPLATE_AppExport -#define _TEMPLATE_GuiExport +# define _TEMPLATE_AppExport +# define _TEMPLATE_GuiExport #endif // standard @@ -57,7 +57,7 @@ #include #ifdef FC_OS_WIN32 -#include +# include #endif // Qt Toolkit diff --git a/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h b/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h index 5d5e24fbfd..b1f8a9ef28 100644 --- a/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h +++ b/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h @@ -25,25 +25,25 @@ #include #ifndef _TEMPLATE__GLOBAL_H -#define _TEMPLATE__GLOBAL_H +# define _TEMPLATE__GLOBAL_H // _TEMPLATE_ -#ifndef _TEMPLATE_Export -#ifdef _TEMPLATE__EXPORTS -#define _TEMPLATE_Export FREECAD_DECL_EXPORT -#else -#define _TEMPLATE_Export FREECAD_DECL_IMPORT -#endif -#endif +# ifndef _TEMPLATE_Export +# ifdef _TEMPLATE__EXPORTS +# define _TEMPLATE_Export FREECAD_DECL_EXPORT +# else +# define _TEMPLATE_Export FREECAD_DECL_IMPORT +# endif +# endif // _TEMPLATE_Gui -#ifndef _TEMPLATE_GuiExport -#ifdef _TEMPLATE_Gui_EXPORTS -#define _TEMPLATE_GuiExport FREECAD_DECL_EXPORT -#else -#define _TEMPLATE_GuiExport FREECAD_DECL_IMPORT -#endif -#endif +# ifndef _TEMPLATE_GuiExport +# ifdef _TEMPLATE_Gui_EXPORTS +# define _TEMPLATE_GuiExport FREECAD_DECL_EXPORT +# else +# define _TEMPLATE_GuiExport FREECAD_DECL_IMPORT +# endif +# endif #endif //_TEMPLATE__GLOBAL_H diff --git a/src/Tools/embedded/Qt/cxx/PreCompiled.h b/src/Tools/embedded/Qt/cxx/PreCompiled.h index 4016c18530..d758b7c15a 100644 --- a/src/Tools/embedded/Qt/cxx/PreCompiled.h +++ b/src/Tools/embedded/Qt/cxx/PreCompiled.h @@ -5,15 +5,15 @@ #ifdef FC_OS_WIN32 // cmake generates this define -#if defined(FreeCADPlugin_EXPORTS) -#define FC_PLUGIN_EXPORT __declspec(dllexport) -#else -#define FC_PLUGIN_EXPORT __declspec(dllimport) -#endif -#define MeshExport __declspec(dllimport) +# if defined(FreeCADPlugin_EXPORTS) +# define FC_PLUGIN_EXPORT __declspec(dllexport) +# else +# define FC_PLUGIN_EXPORT __declspec(dllimport) +# endif +# define MeshExport __declspec(dllimport) #else // for Linux -#define FC_PLUGIN_EXPORT -#define MeshExport +# define FC_PLUGIN_EXPORT +# define MeshExport #endif diff --git a/src/Tools/embedded/Qt/mainwindow.cpp b/src/Tools/embedded/Qt/mainwindow.cpp index ff232464c1..79a963118a 100644 --- a/src/Tools/embedded/Qt/mainwindow.cpp +++ b/src/Tools/embedded/Qt/mainwindow.cpp @@ -6,7 +6,7 @@ #include #include #if defined(Q_WS_X11) -#include +# include #endif #include "mainwindow.h" diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp b/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp index f7c82bf317..cf35e2cb4b 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp +++ b/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp @@ -110,17 +110,19 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) hInst = hInstance; // Store instance handle in our global variable - hWnd = CreateWindow(szWindowClass, - szTitle, - WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, - 0, - CW_USEDEFAULT, - 0, - NULL, - NULL, - hInstance, - NULL); + hWnd = CreateWindow( + szWindowClass, + szTitle, + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + 0, + CW_USEDEFAULT, + 0, + NULL, + NULL, + hInstance, + NULL + ); if (!hWnd) { return FALSE; diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/resource.h b/src/Tools/embedded/Win32/FreeCAD_widget/resource.h index b6079abc91..442f832604 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/resource.h +++ b/src/Tools/embedded/Win32/FreeCAD_widget/resource.h @@ -22,11 +22,11 @@ // Next default values for new objects // #ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 129 -#define _APS_NEXT_COMMAND_VALUE 32774 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 110 -#endif +# ifndef APSTUDIO_READONLY_SYMBOLS +# define _APS_NO_MFC 1 +# define _APS_NEXT_RESOURCE_VALUE 129 +# define _APS_NEXT_COMMAND_VALUE 32774 +# define _APS_NEXT_CONTROL_VALUE 1000 +# define _APS_NEXT_SYMED_VALUE 110 +# endif #endif diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h b/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h index 3caafcd4e5..5bd3c27595 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h +++ b/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h @@ -9,20 +9,20 @@ // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef WINVER // Specifies that the minimum required platform is Windows Vista. -#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. +#ifndef WINVER // Specifies that the minimum required platform is Windows Vista. +# define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. -#define _WIN32_WINNT \ - 0x0600 // Change this to the appropriate value to target other versions of Windows. +# define _WIN32_WINNT \ + 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. -#define _WIN32_WINDOWS \ - 0x0410 // Change this to the appropriate value to target Windows Me or later. +# define _WIN32_WINDOWS \ + 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif -#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. -#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. +#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. +# define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. #endif diff --git a/src/Tools/embedded/glib/main.c b/src/Tools/embedded/glib/main.c index 1830695845..716a3ca28d 100644 --- a/src/Tools/embedded/glib/main.c +++ b/src/Tools/embedded/glib/main.c @@ -8,16 +8,20 @@ static void helloWorld(GtkWidget* wid, GtkWidget* win) { PyObject* mmod = PyImport_AddModule("__main__"); PyObject* dict = PyModule_GetDict(mmod); - PyRun_String("import sys\n" - "sys.path.append(\"/home/werner/FreeCAD/lib\")", - Py_file_input, - dict, - dict); - PyObject* result = PyRun_String("import FreeCADGui\n" - "FreeCADGui.showMainWindow()", - Py_file_input, - dict, - dict); + PyRun_String( + "import sys\n" + "sys.path.append(\"/home/werner/FreeCAD/lib\")", + Py_file_input, + dict, + dict + ); + PyObject* result = PyRun_String( + "import FreeCADGui\n" + "FreeCADGui.showMainWindow()", + Py_file_input, + dict, + dict + ); if (result) { Py_DECREF(result); } @@ -28,12 +32,14 @@ static void helloWorld(GtkWidget* wid, GtkWidget* win) const char* error = PyUnicode_AsUTF8(pystring); GtkWidget* dialog = NULL; - dialog = gtk_message_dialog_new(GTK_WINDOW(win), - GTK_DIALOG_MODAL, - GTK_MESSAGE_INFO, - GTK_BUTTONS_CLOSE, - "%s", - error); + dialog = gtk_message_dialog_new( + GTK_WINDOW(win), + GTK_DIALOG_MODAL, + GTK_MESSAGE_INFO, + GTK_BUTTONS_CLOSE, + "%s", + error + ); gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); diff --git a/src/Tools/plugins/widget/customwidgets.cpp b/src/Tools/plugins/widget/customwidgets.cpp index bfe40808c5..6a660431c8 100644 --- a/src/Tools/plugins/widget/customwidgets.cpp +++ b/src/Tools/plugins/widget/customwidgets.cpp @@ -57,9 +57,7 @@ UrlLabel::~UrlLabel() void UrlLabel::mouseReleaseEvent(QMouseEvent*) { - QMessageBox::information(this, - "Browser", - QString("This starts your browser with url %1").arg(_url)); + QMessageBox::information(this, "Browser", QString("This starts your browser with url %1").arg(_url)); } QString UrlLabel::url() const @@ -177,19 +175,11 @@ void FileChooser::chooseFile() QFileDialog::Options dlgOpt = QFileDialog::DontUseNativeDialog; QString fn; if (mode() == File) { - fn = QFileDialog::getOpenFileName(this, - tr("Select a file"), - lineEdit->text(), - _filter, - 0, - dlgOpt); + fn = QFileDialog::getOpenFileName(this, tr("Select a file"), lineEdit->text(), _filter, 0, dlgOpt); } else { QFileDialog::Options option = QFileDialog::ShowDirsOnly | dlgOpt; - fn = QFileDialog::getExistingDirectory(this, - tr("Select a directory"), - lineEdit->text(), - option); + fn = QFileDialog::getExistingDirectory(this, tr("Select a directory"), lineEdit->text(), option); } if (!fn.isEmpty()) { @@ -822,13 +812,11 @@ public: } break; case 2: - if (copy.at(1) == locale.decimalPoint() - && (plus && copy.at(0) == QLatin1Char('+'))) { + if (copy.at(1) == locale.decimalPoint() && (plus && copy.at(0) == QLatin1Char('+'))) { state = QValidator::Intermediate; goto end; } - if (copy.at(1) == locale.decimalPoint() - && (minus && copy.at(0) == QLatin1Char('-'))) { + if (copy.at(1) == locale.decimalPoint() && (minus && copy.at(0) == QLatin1Char('-'))) { state = QValidator::Intermediate; copy.insert(1, QLatin1Char('0')); pos++; @@ -1169,8 +1157,7 @@ void QuantitySpinBox::clearSchema() updateText(d->quantity); } -QString -QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor, QString& unitString) const +QString QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor, QString& unitString) const { return val.getUserString(factor, unitString); } @@ -1872,8 +1859,8 @@ void ColorButton::paintEvent(QPaintEvent* e) QPushButton::paintEvent(e); // repaint the rectangle area - QPalette::ColorGroup group = - isEnabled() ? hasFocus() ? QPalette::Active : QPalette::Inactive : QPalette::Disabled; + QPalette::ColorGroup group = isEnabled() ? hasFocus() ? QPalette::Active : QPalette::Inactive + : QPalette::Disabled; QColor pen = palette().color(group, QPalette::ButtonText); { QPainter paint(this); diff --git a/src/Tools/plugins/widget/plugin.cpp b/src/Tools/plugins/widget/plugin.cpp index 0f142a9e5d..146a15c845 100644 --- a/src/Tools/plugins/widget/plugin.cpp +++ b/src/Tools/plugins/widget/plugin.cpp @@ -39,32 +39,34 @@ /* XPM */ -static const char* urllabel_pixmap[] = {"22 22 3 1", - "# c #000000", - "x c #ffffff", - ". c None", - "......................", - ".......##.............", - "......#xx#............", - "......#xx#............", - "......#xx#............", - "......#xx#............", - "......#xx###..........", - "......#xx#xx###.......", - "......#xx#xx#xx##.....", - "...##.#xx#xx#xx#x#....", - "..#xx##xx#xx#xx#x#....", - "..#xxx#xxxxxxxxxx#....", - "...#xxxxxxxxxxxxx#....", - "....#xxxxxxxxxxxx#....", - "....#xxxxxxxxxxxx#....", - ".....#xxxxxxxxxx#.....", - ".....#xxxxxxxxxx#.....", - "......#xxxxxxxx#......", - "......#xxxxxxxx#......", - "......##########......", - "......##########......", - "......##########......"}; +static const char* urllabel_pixmap[] = { + "22 22 3 1", + "# c #000000", + "x c #ffffff", + ". c None", + "......................", + ".......##.............", + "......#xx#............", + "......#xx#............", + "......#xx#............", + "......#xx#............", + "......#xx###..........", + "......#xx#xx###.......", + "......#xx#xx#xx##.....", + "...##.#xx#xx#xx#x#....", + "..#xx##xx#xx#xx#x#....", + "..#xxx#xxxxxxxxxx#....", + "...#xxxxxxxxxxxxx#....", + "....#xxxxxxxxxxxx#....", + "....#xxxxxxxxxxxx#....", + ".....#xxxxxxxxxx#.....", + ".....#xxxxxxxxxx#.....", + "......#xxxxxxxx#......", + "......#xxxxxxxx#......", + "......##########......", + "......##########......", + "......##########......" +}; class UrlLabelPlugin: public QDesignerCustomWidgetInterface { @@ -161,37 +163,39 @@ public: } }; -static const char* filechooser_pixmap[] = {"22 22 8 1", - " c Gray100", - ". c Gray97", - "X c #4f504f", - "o c #00007f", - "O c Gray0", - "+ c none", - "@ c Gray0", - "# c Gray0", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "+OOOOOOOOOOOOOOOOOOOO+", - "OOXXXXXXXXXXXXXXXXXXOO", - "OXX. OO OO O", - "OX. oo O O", - "OX. oo O .O", - "OX ooo oooo O O", - "OX oo oo oo O O", - "OX oooo oo oo O O", - "OX oo oo oo oo O O", - "OX oo oo oo oo O O", - "OX oooo oooo O O", - "OX OO OO O", - "OO..................OO", - "+OOOOOOOOOOOOOOOOOOOO+", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++"}; +static const char* filechooser_pixmap[] = { + "22 22 8 1", + " c Gray100", + ". c Gray97", + "X c #4f504f", + "o c #00007f", + "O c Gray0", + "+ c none", + "@ c Gray0", + "# c Gray0", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "+OOOOOOOOOOOOOOOOOOOO+", + "OOXXXXXXXXXXXXXXXXXXOO", + "OXX. OO OO O", + "OX. oo O O", + "OX. oo O .O", + "OX ooo oooo O O", + "OX oo oo oo O O", + "OX oooo oo oo O O", + "OX oo oo oo oo O O", + "OX oo oo oo oo O O", + "OX oooo oooo O O", + "OX OO OO O", + "OO..................OO", + "+OOOOOOOOOOOOOOOOOOOO+", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++" +}; class FileChooserPlugin: public QDesignerCustomWidgetInterface { @@ -289,35 +293,37 @@ public: }; /* XPM */ -static const char* lineedit_pixmap[] = {"22 22 6 1", - "a c #000000", - "# c #000080", - "b c #008080", - "c c #808080", - "d c #c0c0c0", - ". c #ffffff", - "......................", - "......................", - "......................", - "...#aaaaaaaaaaaaaa#...", - ".baccccccccccccccccab.", - ".acccddddddddddddddca.", - "#ccd................d#", - "acc.................da", - "acd.......d....ca.ac.a", - "acd......db......a...a", - "acd.dbbb.dbbbd...a...a", - "acd.ccdbddb.db...a...a", - "acd.dbbbddb..b...a...a", - "acd.bd.bddb..b...a...a", - "acd.bbbbddbbbc...a...a", - "acd..d.....dd..ca.acda", - "#cd.................d#", - ".ac................da.", - ".badd............dda#.", - "...#aaaaaaaaaaaaaa#...", - "......................", - "......................"}; +static const char* lineedit_pixmap[] = { + "22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.................da", + "acd.......d....ca.ac.a", + "acd......db......a...a", + "acd.dbbb.dbbbd...a...a", + "acd.ccdbddb.db...a...a", + "acd.dbbbddb..b...a...a", + "acd.bd.bddb..b...a...a", + "acd.bbbbddbbbc...a...a", + "acd..d.....dd..ca.acda", + "#cd.................d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#...", + "......................", + "......................" +}; class AccelLineEditPlugin: public QDesignerCustomWidgetInterface { @@ -367,35 +373,37 @@ public: }; /* XPM */ -static const char* actionselector_pixmap[] = {"22 22 6 1", - "a c #000000", - "# c #000080", - "b c #008080", - "c c #808080", - "d c #c0c0c0", - ". c #ffffff", - "......................", - "......................", - "......................", - "...#aaaaaaaaaaaaaa#...", - ".baccccccccccccccccab.", - ".acccddddddddddddddca.", - "#ccd................d#", - "acc.................da", - "acd.......d....ca.ac.a", - "acd......db......a...a", - "acd.dbbb.dbbbd...a...a", - "acd.ccdbddb.db...a...a", - "acd.dbbbddb..b...a...a", - "acd.bd.bddb..b...a...a", - "acd.bbbbddbbbc...a...a", - "acd..d.....dd..ca.acda", - "#cd.................d#", - ".ac................da.", - ".badd............dda#.", - "...#aaaaaaaaaaaaaa#...", - "......................", - "......................"}; +static const char* actionselector_pixmap[] = { + "22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.................da", + "acd.......d....ca.ac.a", + "acd......db......a...a", + "acd.dbbb.dbbbd...a...a", + "acd.ccdbddb.db...a...a", + "acd.dbbbddb..b...a...a", + "acd.bd.bddb..b...a...a", + "acd.bbbbddbbbc...a...a", + "acd..d.....dd..ca.acda", + "#cd.................d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#...", + "......................", + "......................" +}; class ActionSelectorPlugin: public QDesignerCustomWidgetInterface { @@ -445,35 +453,37 @@ public: }; /* XPM */ -static const char* inputfield_pixmap[] = {"22 22 6 1", - "a c #000000", - "# c #000080", - "b c #008080", - "c c #808080", - "d c #c0c0c0", - ". c #ffffff", - "......................", - "......................", - "......................", - "...#aaaaaaaaaaaaaa#...", - ".baccccccccccccccccab.", - ".acccddddddddddddddca.", - "#ccd................d#", - "acc.................da", - "acd.......d....ca.ac.a", - "acd......db......a...a", - "acd.dbbb.dbbbd...a...a", - "acd.ccdbddb.db...a...a", - "acd.dbbbddb..b...a...a", - "acd.bd.bddb..b...a...a", - "acd.bbbbddbbbc...a...a", - "acd..d.....dd..ca.acda", - "#cd.................d#", - ".ac................da.", - ".badd............dda#.", - "...#aaaaaaaaaaaaaa#...", - "......................", - "......................"}; +static const char* inputfield_pixmap[] = { + "22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.................da", + "acd.......d....ca.ac.a", + "acd......db......a...a", + "acd.dbbb.dbbbd...a...a", + "acd.ccdbddb.db...a...a", + "acd.dbbbddb..b...a...a", + "acd.bd.bddb..b...a...a", + "acd.bbbbddbbbc...a...a", + "acd..d.....dd..ca.acda", + "#cd.................d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#...", + "......................", + "......................" +}; class InputFieldPlugin: public QDesignerCustomWidgetInterface { @@ -576,35 +586,37 @@ public: }; /* XPM */ -static const char* quantityspinbox_pixmap[] = {"22 22 6 1", - "a c #000000", - "# c #000080", - "b c #008080", - "c c #808080", - "d c #c0c0c0", - ". c #ffffff", - "...#aaaaaaaaaaaaaa#...", - ".baccccccccccccccccab.", - ".acccddddddddddddddca.", - "#ccd................d#", - "acc.............dcd.da", - "acd.............dbd..a", - "acd............dcbbd.a", - "acd.d..dd..d...dbbbc.a", - "acddb.dbbdcbb.dbbb#bda", - "acd.b.d.cc..b.bb###bda", - "acd.b...bd.cb.dddccdda", - "acd.b...b..db...dddd.a", - "acd.b..cd...bdddccbbda", - "acd.b.dbbccdb.ccbbbbda", - "acddd.ddd.dd..dbbb#cda", - "acd............bb##cda", - "acd............db#cd.a", - "acd.............bbcdda", - "#cd.............ddd.d#", - ".ac................da.", - ".badd............dda#.", - "...#aaaaaaaaaaaaaa#..."}; +static const char* quantityspinbox_pixmap[] = { + "22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.............dcd.da", + "acd.............dbd..a", + "acd............dcbbd.a", + "acd.d..dd..d...dbbbc.a", + "acddb.dbbdcbb.dbbb#bda", + "acd.b.d.cc..b.bb###bda", + "acd.b...bd.cb.dddccdda", + "acd.b...b..db...dddd.a", + "acd.b..cd...bdddccbbda", + "acd.b.dbbccdb.ccbbbbda", + "acddd.ddd.dd..dbbb#cda", + "acd............bb##cda", + "acd............db#cd.a", + "acd.............bbcdda", + "#cd.............ddd.d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#..." +}; class QuantitySpinBoxPlugin: public QDesignerCustomWidgetInterface { @@ -751,39 +763,41 @@ public: }; /* XPM */ -static const char* iconview_pixmap[] = {"22 22 10 1", - "# c #000000", - "h c #000080", - "f c #0000ff", - "d c #008000", - "e c #008080", - "a c #800000", - "b c #808080", - "c c #c0c0c0", - "g c #ff0000", - ". c #ffffff", - "...################...", - ".a#bbccccccccccccbb#a.", - ".#bcc..............b#.", - "#bb......c.....c....c#", - "#bbbbc..cbbc...bbbc.c#", - "#cccdd....bdb..ccdd..#", - "#cbcb#c.cbcbd..bcb#c.#", - "#cbbb#b..bbb#..cbb#c.#", - "#c..c##...cb#c...c##.#", - "#c...................#", - "#ccbbc..c#bbc..cbbcc.#", - "#c...................#", - "#cbbbaa.cb..cc..c.bb.#", - "#cbccca.c#ccb..cecf#.#", - "#cbcgba..c#b...bfbfh.#", - "#cacbba..bb#c..bbhb#.#", - "#caaaaa.bc.bb..bb###.#", - "#b..................c#", - "#b.bbcc..cbbbb.cbbc.c#", - ".#b................c#.", - ".a#cc............cc##.", - "...################..."}; +static const char* iconview_pixmap[] = { + "22 22 10 1", + "# c #000000", + "h c #000080", + "f c #0000ff", + "d c #008000", + "e c #008080", + "a c #800000", + "b c #808080", + "c c #c0c0c0", + "g c #ff0000", + ". c #ffffff", + "...################...", + ".a#bbccccccccccccbb#a.", + ".#bcc..............b#.", + "#bb......c.....c....c#", + "#bbbbc..cbbc...bbbc.c#", + "#cccdd....bdb..ccdd..#", + "#cbcb#c.cbcbd..bcb#c.#", + "#cbbb#b..bbb#..cbb#c.#", + "#c..c##...cb#c...c##.#", + "#c...................#", + "#ccbbc..c#bbc..cbbcc.#", + "#c...................#", + "#cbbbaa.cb..cc..c.bb.#", + "#cbccca.c#ccb..cecf#.#", + "#cbcgba..c#b...bfbfh.#", + "#cacbba..bb#c..bbhb#.#", + "#caaaaa.bc.bb..bb###.#", + "#b..................c#", + "#b.bbcc..cbbbb.cbbc.c#", + ".#b................c#.", + ".a#cc............cc##.", + "...################..." +}; class CommandIconViewPlugin: public QDesignerCustomWidgetInterface { @@ -833,35 +847,37 @@ public: }; /* XPM */ -static const char* spinbox_pixmap[] = {"22 22 6 1", - "a c #000000", - "# c #000080", - "b c #008080", - "c c #808080", - "d c #c0c0c0", - ". c #ffffff", - "...#aaaaaaaaaaaaaa#...", - ".baccccccccccccccccab.", - ".acccddddddddddddddca.", - "#ccd................d#", - "acc.............dcd.da", - "acd.............dbd..a", - "acd............dcbbd.a", - "acd.d..dd..d...dbbbc.a", - "acddb.dbbdcbb.dbbb#bda", - "acd.b.d.cc..b.bb###bda", - "acd.b...bd.cb.dddccdda", - "acd.b...b..db...dddd.a", - "acd.b..cd...bdddccbbda", - "acd.b.dbbccdb.ccbbbbda", - "acddd.ddd.dd..dbbb#cda", - "acd............bb##cda", - "acd............db#cd.a", - "acd.............bbcdda", - "#cd.............ddd.d#", - ".ac................da.", - ".badd............dda#.", - "...#aaaaaaaaaaaaaa#..."}; +static const char* spinbox_pixmap[] = { + "22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.............dcd.da", + "acd.............dbd..a", + "acd............dcbbd.a", + "acd.d..dd..d...dbbbc.a", + "acddb.dbbdcbb.dbbb#bda", + "acd.b.d.cc..b.bb###bda", + "acd.b...bd.cb.dddccdda", + "acd.b...b..db...dddd.a", + "acd.b..cd...bdddccbbda", + "acd.b.dbbccdb.ccbbbbda", + "acddd.ddd.dd..dbbb#cda", + "acd............bb##cda", + "acd............db#cd.a", + "acd.............bbcdda", + "#cd.............ddd.d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#..." +}; class UIntSpinBoxPlugin: public QDesignerCustomWidgetInterface { @@ -1052,35 +1068,37 @@ public: }; /* XPM */ -static const char* colorbutton_pixmap[] = {"21 21 7 1", - "d c #000000", - "b c #000080", - "e c #0000ff", - "a c #008080", - "# c #808080", - "c c #c0c0c0", - ". c #ffffff", - ".....................", - ".#abbbbbbbbbbbbbba#c.", - "c#c..............c##.", - "#c................ca.", - "#..................b.", - "#...ddddddddddd....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...deeeeeeeeed....b.", - "#...ddddddddddd....b.", - "#..................b.", - "#.................cb.", - "#cccccccccccccccccca.", - "c#cccccccccccccccc##.", - ".cccccccccccccccccc.."}; +static const char* colorbutton_pixmap[] = { + "21 21 7 1", + "d c #000000", + "b c #000080", + "e c #0000ff", + "a c #008080", + "# c #808080", + "c c #c0c0c0", + ". c #ffffff", + ".....................", + ".#abbbbbbbbbbbbbba#c.", + "c#c..............c##.", + "#c................ca.", + "#..................b.", + "#...ddddddddddd....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...ddddddddddd....b.", + "#..................b.", + "#.................cb.", + "#cccccccccccccccccca.", + "c#cccccccccccccccc##.", + ".cccccccccccccccccc.." +}; class ColorButtonPlugin: public QDesignerCustomWidgetInterface { @@ -1177,34 +1195,36 @@ public: }; /* XPM */ -static const char* slider_pixmap[] = {"22 22 5 1", - "b c #000000", - "c c #008080", - "# c #808080", - "a c #c0c0c0", - ". c #ffffff", - "......................", - "......................", - "......................", - "......................", - "......................", - ".........#............", - "........a##...........", - "........a##...........", - "........a##...........", - "..bbbb..a#bbbbbbbbbb..", - ".bbbbb..a#bbbbbbbbbbc.", - ".bb###..a#b########c#.", - ".bbb##..a#b########aa.", - "..cc##..a#b########a..", - "........a##...........", - "........a##...........", - "........a##...........", - "......#####...........", - ".......####...........", - "......................", - "......................", - "......................"}; +static const char* slider_pixmap[] = { + "22 22 5 1", + "b c #000000", + "c c #008080", + "# c #808080", + "a c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "......................", + "......................", + ".........#............", + "........a##...........", + "........a##...........", + "........a##...........", + "..bbbb..a#bbbbbbbbbb..", + ".bbbbb..a#bbbbbbbbbbc.", + ".bb###..a#b########c#.", + ".bbb##..a#b########aa.", + "..cc##..a#b########a..", + "........a##...........", + "........a##...........", + "........a##...........", + "......#####...........", + ".......####...........", + "......................", + "......................", + "......................" +}; class PrefSliderPlugin: public QDesignerCustomWidgetInterface { @@ -1254,33 +1274,35 @@ public: }; /* XPM */ -static const char* radiobutton_pixmap[] = {"22 22 4 1", - "b c #000000", - "# c #808080", - "a c #c0c0c0", - ". c #ffffff", - "......................", - "......................", - "......................", - "......................", - ".......########.......", - "......#####aaa##......", - ".....#b##a...aaa#.....", - "....###aa.aa....a#....", - "....###a.####a...a....", - "....##a.####bba..a....", - "....##.a###bbb#.......", - "....#a.a##bbbb#.......", - "....#a..bbbbbba.......", - "....#aa.abbbb#...a....", - "....##a..a##a....a....", - ".....#a.........a.....", - "......#a.......a......", - ".......#aa...aa.......", - "......................", - "......................", - "......................", - "......................"}; +static const char* radiobutton_pixmap[] = { + "22 22 4 1", + "b c #000000", + "# c #808080", + "a c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "......................", + ".......########.......", + "......#####aaa##......", + ".....#b##a...aaa#.....", + "....###aa.aa....a#....", + "....###a.####a...a....", + "....##a.####bba..a....", + "....##.a###bbb#.......", + "....#a.a##bbbb#.......", + "....#a..bbbbbba.......", + "....#aa.abbbb#...a....", + "....##a..a##a....a....", + ".....#a.........a.....", + "......#a.......a......", + ".......#aa...aa.......", + "......................", + "......................", + "......................", + "......................" +}; class PrefRadioButtonPlugin: public QDesignerCustomWidgetInterface { @@ -1330,33 +1352,35 @@ public: }; /* XPM */ -static const char* checkbox_pixmap[] = {"22 22 4 1", - "# c #000000", - "a c #808080", - "b c #c0c0c0", - ". c #ffffff", - "......................", - "......................", - "......................", - "......................", - "....###########aaa....", - "....##aaaaaaaaaabb....", - "....#aabbbbbbbbbbb....", - "....#abbbbbbbbaa......", - "....#abbbbbbba#a......", - "....#ababbbba##a......", - "....#ab#abba###a......", - "....#ab##aa###ab......", - "....#ab######abb......", - "....#abb####abbb......", - "....#abbb##abbbb......", - "....aabbbbabbbb.......", - "....abb......b........", - "....abb...............", - "......................", - "......................", - "......................", - "......................"}; +static const char* checkbox_pixmap[] = { + "22 22 4 1", + "# c #000000", + "a c #808080", + "b c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "......................", + "....###########aaa....", + "....##aaaaaaaaaabb....", + "....#aabbbbbbbbbbb....", + "....#abbbbbbbbaa......", + "....#abbbbbbba#a......", + "....#ababbbba##a......", + "....#ab#abba###a......", + "....#ab##aa###ab......", + "....#ab######abb......", + "....#abb####abbb......", + "....#abbb##abbbb......", + "....aabbbbabbbb.......", + "....abb......b........", + "....abb...............", + "......................", + "......................", + "......................", + "......................" +}; class PrefCheckBoxPlugin: public QDesignerCustomWidgetInterface { @@ -1406,37 +1430,39 @@ public: }; /* XPM */ -static const char* combobox_pixmap[] = {"22 22 8 1", - "a c #000000", - "# c #000080", - "e c #008080", - "f c #800000", - "b c #808080", - "c c #c0c0c0", - "d c #ff0000", - ". c #ffffff", - ".#aaaaaaaaaaaaaaaaaa#.", - "#bbccccccccccccccccdd#", - "accee#########e.addfaa", - "#c..............a.fa.#", - "e#aaaaaaaaaaaaaaaaaa#e", - "....#c...............#", - "....ac...............a", - "....ac.ccbbbbbbbbeb..a", - "....ac.bbbeeeeeee##c.a", - "....ac.bee########ac.a", - "....ac..cccccccccccc.a", - "....ac.ccccccccccbec.a", - "....ac.cccccccccbbec.a", - "....ac.bcbbbbbbbbbec.a", - "....ac..cccccccccccc.a", - "....ac.cbbeeeeeee#bc.a", - "....ac.bee########ac.a", - "....ab.b##aaaaaaaaacca", - "....#bc.ccccccccccccc#", - ".....ab............ca.", - ".....eacc.........ca#.", - ".......#aaaaaaaaaa#..."}; +static const char* combobox_pixmap[] = { + "22 22 8 1", + "a c #000000", + "# c #000080", + "e c #008080", + "f c #800000", + "b c #808080", + "c c #c0c0c0", + "d c #ff0000", + ". c #ffffff", + ".#aaaaaaaaaaaaaaaaaa#.", + "#bbccccccccccccccccdd#", + "accee#########e.addfaa", + "#c..............a.fa.#", + "e#aaaaaaaaaaaaaaaaaa#e", + "....#c...............#", + "....ac...............a", + "....ac.ccbbbbbbbbeb..a", + "....ac.bbbeeeeeee##c.a", + "....ac.bee########ac.a", + "....ac..cccccccccccc.a", + "....ac.ccccccccccbec.a", + "....ac.cccccccccbbec.a", + "....ac.bcbbbbbbbbbec.a", + "....ac..cccccccccccc.a", + "....ac.cbbeeeeeee#bc.a", + "....ac.bee########ac.a", + "....ab.b##aaaaaaaaacca", + "....#bc.ccccccccccccc#", + ".....ab............ca.", + ".....eacc.........ca#.", + ".......#aaaaaaaaaa#..." +}; class PrefComboBoxPlugin: public QDesignerCustomWidgetInterface { @@ -1581,37 +1607,39 @@ public: /* XPM */ -static const char* fontbox_pixmap[] = {"22 22 8 1", - "a c #000000", - "# c #000080", - "e c #008080", - "f c #800000", - "b c #808080", - "c c #c0c0c0", - "d c #ff0000", - ". c #ffffff", - ".#aaaaaaaaaaaaaaaaaa#.", - "#bbccccccccccccccccdd#", - "accee#########e.addfaa", - "#c..............a.fa.#", - "e#aaaaaaaaaaaaaaaaaa#e", - "....#c...............#", - "....ac...............a", - "....ac.ccbbbbbbbbeb..a", - "....ac.bbbeeeeeee##c.a", - "....ac.bee########ac.a", - "....ac..cccccccccccc.a", - "....ac.ccccccccccbec.a", - "....ac.cccccccccbbec.a", - "....ac.bcbbbbbbbbbec.a", - "....ac..cccccccccccc.a", - "....ac.cbbeeeeeee#bc.a", - "....ac.bee########ac.a", - "....ab.b##aaaaaaaaacca", - "....#bc.ccccccccccccc#", - ".....ab............ca.", - ".....eacc.........ca#.", - ".......#aaaaaaaaaa#..."}; +static const char* fontbox_pixmap[] = { + "22 22 8 1", + "a c #000000", + "# c #000080", + "e c #008080", + "f c #800000", + "b c #808080", + "c c #c0c0c0", + "d c #ff0000", + ". c #ffffff", + ".#aaaaaaaaaaaaaaaaaa#.", + "#bbccccccccccccccccdd#", + "accee#########e.addfaa", + "#c..............a.fa.#", + "e#aaaaaaaaaaaaaaaaaa#e", + "....#c...............#", + "....ac...............a", + "....ac.ccbbbbbbbbeb..a", + "....ac.bbbeeeeeee##c.a", + "....ac.bee########ac.a", + "....ac..cccccccccccc.a", + "....ac.ccccccccccbec.a", + "....ac.cccccccccbbec.a", + "....ac.bcbbbbbbbbbec.a", + "....ac..cccccccccccc.a", + "....ac.cbbeeeeeee#bc.a", + "....ac.bee########ac.a", + "....ab.b##aaaaaaaaacca", + "....#bc.ccccccccccccc#", + ".....ab............ca.", + ".....eacc.........ca#.", + ".......#aaaaaaaaaa#..." +}; class PrefFontBoxPlugin: public QDesignerCustomWidgetInterface { diff --git a/src/Tools/plugins/widget/wizard.cpp b/src/Tools/plugins/widget/wizard.cpp index fa9b8803fc..e389069432 100644 --- a/src/Tools/plugins/widget/wizard.cpp +++ b/src/Tools/plugins/widget/wizard.cpp @@ -220,8 +220,7 @@ WizardExtensionFactory::WizardExtensionFactory(QExtensionManager* parent) : QExtensionFactory(parent) {} -QObject* -WizardExtensionFactory::createExtension(QObject* object, const QString& iid, QObject* parent) const +QObject* WizardExtensionFactory::createExtension(QObject* object, const QString& iid, QObject* parent) const { Wizard* widget = qobject_cast(object); diff --git a/src/Tools/xmlformat/main.cpp b/src/Tools/xmlformat/main.cpp index d05f0fe9a7..6a98e114f3 100644 --- a/src/Tools/xmlformat/main.cpp +++ b/src/Tools/xmlformat/main.cpp @@ -68,15 +68,17 @@ int main(int argc, char* argv[]) // ---------------------- auto sortAttr = [&findAttr](QXmlStreamAttributes& attr) { - QStringList list = {"Name", - "Namespace", - "Twin", - "TwinPointer", - "PythonName", - "FatherInclude", - "Include", - "Father", - "FatherNamespace"}; + QStringList list = { + "Name", + "Namespace", + "Twin", + "TwinPointer", + "PythonName", + "FatherInclude", + "Include", + "Father", + "FatherNamespace" + }; QXmlStreamAttributes sorted; for (const auto& it : list) { int index = findAttr(attr, it); diff --git a/tests/src/App/ApplicationDirectories.cpp b/tests/src/App/ApplicationDirectories.cpp index ecd3c3a020..863cb1b014 100644 --- a/tests/src/App/ApplicationDirectories.cpp +++ b/tests/src/App/ApplicationDirectories.cpp @@ -43,14 +43,14 @@ class ApplicationDirectoriesTestClass: public App::ApplicationDirectories using App::ApplicationDirectories::ApplicationDirectories; public: - void wrapAppendVersionIfPossible(const fs::path& basePath, - std::vector& subdirs) const + void wrapAppendVersionIfPossible(const fs::path& basePath, std::vector& subdirs) const { appendVersionIfPossible(basePath, subdirs); } - std::tuple - wrapExtractVersionFromConfigMap(const std::map& config) + std::tuple wrapExtractVersionFromConfigMap( + const std::map& config + ) { return extractVersionFromConfigMap(config); } @@ -69,14 +69,17 @@ protected: _tempDir = MakeUniqueTempDir(); } - std::map - generateConfig(const std::map& overrides) const + std::map generateConfig( + const std::map& overrides + ) const { - std::map config {{"AppHomePath", _tempDir.string()}, - {"ExeVendor", "Vendor"}, - {"ExeName", "Test"}, - {"BuildVersionMajor", "4"}, - {"BuildVersionMinor", "2"}}; + std::map config { + {"AppHomePath", _tempDir.string()}, + {"ExeVendor", "Vendor"}, + {"ExeName", "Test"}, + {"BuildVersionMajor", "4"}, + {"BuildVersionMinor", "2"} + }; for (const auto& override : overrides) { config[override.first] = override.second; } @@ -85,8 +88,10 @@ protected: std::unique_ptr makeAppDirsForVersion(int major, int minor) { - auto configuration = generateConfig({{"BuildVersionMajor", std::to_string(major)}, - {"BuildVersionMinor", std::to_string(minor)}}); + auto configuration = generateConfig( + {{"BuildVersionMajor", std::to_string(major)}, + {"BuildVersionMinor", std::to_string(minor)}} + ); return std::make_unique(configuration); } @@ -136,8 +141,10 @@ TEST_F(ApplicationDirectoriesTest, usingCurrentVersionConfigFalseWhenDirDoesntMa / App::ApplicationDirectories::versionStringForPath(major, minor); // Act: generate a directory structure with the same version - auto configuration = generateConfig({{"BuildVersionMajor", std::to_string(major + 1)}, - {"BuildVersionMinor", std::to_string(minor)}}); + auto configuration = generateConfig( + {{"BuildVersionMajor", std::to_string(major + 1)}, + {"BuildVersionMinor", std::to_string(minor)}} + ); auto appDirs = std::make_unique(configuration); // Assert @@ -216,8 +223,10 @@ TEST_F(ApplicationDirectoriesTest, mostRecentAvailReturnsExactCurrentVersionIfDi auto appDirs = makeAppDirsForVersion(5, 4); fs::create_directories(versionedPath(tempDir(), 5, 4)); - EXPECT_EQ(appDirs->mostRecentAvailableConfigVersion(tempDir()), - App::ApplicationDirectories::versionStringForPath(5, 4)); + EXPECT_EQ( + appDirs->mostRecentAvailableConfigVersion(tempDir()), + App::ApplicationDirectories::versionStringForPath(5, 4) + ); } // No exact match in the current major: choose the highest available minor <= current @@ -229,8 +238,10 @@ TEST_F(ApplicationDirectoriesTest, mostRecentAvailPrefersSameMajorAndPicksHighes fs::create_directories(versionedPath(tempDir(), 5, 3)); fs::create_directories(versionedPath(tempDir(), 4, 99)); // distractor in lower major - EXPECT_EQ(appDirs->mostRecentAvailableConfigVersion(tempDir()), - App::ApplicationDirectories::versionStringForPath(5, 3)); + EXPECT_EQ( + appDirs->mostRecentAvailableConfigVersion(tempDir()), + App::ApplicationDirectories::versionStringForPath(5, 3) + ); } // No directories in current major: scan next lower major from 99 downward, @@ -241,8 +252,10 @@ TEST_F(ApplicationDirectoriesTest, mostRecentAvailForLowerMajorPicksHighestAvail fs::create_directories(versionedPath(tempDir(), 4, 3)); fs::create_directories(versionedPath(tempDir(), 4, 42)); - EXPECT_EQ(appDirs->mostRecentAvailableConfigVersion(tempDir()), - App::ApplicationDirectories::versionStringForPath(4, 42)); + EXPECT_EQ( + appDirs->mostRecentAvailableConfigVersion(tempDir()), + App::ApplicationDirectories::versionStringForPath(4, 42) + ); } // If the candidate path exists but is a regular file, it must be ignored and @@ -253,8 +266,10 @@ TEST_F(ApplicationDirectoriesTest, mostRecentAvailSkipsFilesAndFallsBackToNextDi touchFile(versionedPath(tempDir(), 5, 4)); // file at the current version fs::create_directories(versionedPath(tempDir(), 5, 3)); // directory at next lower minor - EXPECT_EQ(appDirs->mostRecentAvailableConfigVersion(tempDir()), - App::ApplicationDirectories::versionStringForPath(5, 3)); + EXPECT_EQ( + appDirs->mostRecentAvailableConfigVersion(tempDir()), + App::ApplicationDirectories::versionStringForPath(5, 3) + ); } // Higher minor in the current major is not considered (loop starts at the current minor); @@ -262,12 +277,13 @@ TEST_F(ApplicationDirectoriesTest, mostRecentAvailSkipsFilesAndFallsBackToNextDi TEST_F(ApplicationDirectoriesTest, mostRecentAvailIgnoresHigherMinorThanCurrentInSameMajor) { auto appDirs = makeAppDirsForVersion(5, 4); - fs::create_directories( - versionedPath(tempDir(), 5, 7)); // higher than the current minor; ignored + fs::create_directories(versionedPath(tempDir(), 5, 7)); // higher than the current minor; ignored fs::create_directories(versionedPath(tempDir(), 4, 1)); // fallback target - EXPECT_EQ(appDirs->mostRecentAvailableConfigVersion(tempDir()), - App::ApplicationDirectories::versionStringForPath(4, 1)); + EXPECT_EQ( + appDirs->mostRecentAvailableConfigVersion(tempDir()), + App::ApplicationDirectories::versionStringForPath(4, 1) + ); } // No candidates anywhere -> empty string returned. @@ -289,8 +305,7 @@ TEST_F(ApplicationDirectoriesTest, mostRecentConfigReturnsCurrentVersionDirector } // The current version missing -> falls back to most recent available in same major -TEST_F(ApplicationDirectoriesTest, - mostRecentConfigFallsBackToMostRecentInSameMajorWhenCurrentMissing) +TEST_F(ApplicationDirectoriesTest, mostRecentConfigFallsBackToMostRecentInSameMajorWhenCurrentMissing) { auto appDirs = makeAppDirsForVersion(5, 4); // There is no directory called "5.4"; provide candidates 5.3 and 5.1; also a distractor in a @@ -604,7 +619,8 @@ TEST_F(ApplicationDirectoriesTest, appendVecAlreadyVersionedBails) fs::path base = tempDir() / "bail_vec"; std::vector sub { "configs", - App::ApplicationDirectories::versionStringForPath(5, 2)}; // versioned tail + App::ApplicationDirectories::versionStringForPath(5, 2) + }; // versioned tail fs::create_directories(base / sub[0] / sub[1]); auto before = sub; @@ -704,8 +720,10 @@ TEST_F(ApplicationDirectoriesTest, extractVersionSucceedsWithPlainIntegers) TEST_F(ApplicationDirectoriesTest, extractVersionSucceedsWithWhitespace) { auto appDirs = makeAppDirsForVersion(5, 4); - std::map m {{"BuildVersionMajor", " 10 "}, - {"BuildVersionMinor", "\t3\n"}}; + std::map m { + {"BuildVersionMajor", " 10 "}, + {"BuildVersionMinor", "\t3\n"} + }; auto [maj, min] = appDirs->wrapExtractVersionFromConfigMap(m); EXPECT_EQ(maj, 10); EXPECT_EQ(min, 3); @@ -739,8 +757,10 @@ TEST_F(ApplicationDirectoriesTest, extractVersionNonNumericThrowsRuntimeError) TEST_F(ApplicationDirectoriesTest, extractVersionOverflowThrowsRuntimeError) { auto appDirs = makeAppDirsForVersion(5, 4); - std::map m {{"BuildVersionMajor", "9999999999999999999999999"}, - {"BuildVersionMinor", "1"}}; + std::map m { + {"BuildVersionMajor", "9999999999999999999999999"}, + {"BuildVersionMinor", "1"} + }; EXPECT_THROW(appDirs->wrapExtractVersionFromConfigMap(m), Base::RuntimeError); } diff --git a/tests/src/App/BackupPolicy.cpp b/tests/src/App/BackupPolicy.cpp index 33e930e31c..b0b0daa283 100644 --- a/tests/src/App/BackupPolicy.cpp +++ b/tests/src/App/BackupPolicy.cpp @@ -35,14 +35,14 @@ #include #include -#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907L && defined(_LIBCPP_VERSION) \ +#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907L && defined(_LIBCPP_VERSION) \ && _LIBCPP_VERSION >= 13000 // Apple's clang compiler did not support timezones fully until a quite recent version: // before removing this preprocessor check, verify that it compiles on our oldest-supported // macOS version. -#define CAN_USE_CHRONO_AND_FORMAT -#include -#include +# define CAN_USE_CHRONO_AND_FORMAT +# include +# include #endif @@ -56,8 +56,7 @@ protected: void SetUp() override { - _tempDir = - std::filesystem::temp_directory_path() / ("fc_backup_policy-" + randomString(16)); + _tempDir = std::filesystem::temp_directory_path() / ("fc_backup_policy-" + randomString(16)); std::filesystem::create_directory(_tempDir); } @@ -105,9 +104,7 @@ protected: std::string result; result.reserve(length); - std::ranges::generate_n(std::back_inserter(result), length, [&]() { - return chars[dis(gen)]; - }); + std::ranges::generate_n(std::back_inserter(result), length, [&]() { return chars[dis(gen)]; }); return result; } @@ -115,18 +112,20 @@ protected: std::string filenameFromDateFormatString(const std::string& fmt) { #if CAN_USE_CHRONO_AND_FORMAT - std::chrono::zoned_time local_time {std::chrono::current_zone(), - std::chrono::system_clock::now()}; + std::chrono::zoned_time local_time { + std::chrono::current_zone(), + std::chrono::system_clock::now() + }; std::string fmt_str = "{:" + fmt + "}"; std::string result = std::vformat(fmt_str, std::make_format_args(local_time)); #else std::time_t now = std::time(nullptr); std::tm local_tm {}; -#if defined(_WIN32) +# if defined(_WIN32) localtime_s(&local_tm, &now); // Windows -#else +# else localtime_r(&now, &local_tm); // POSIX -#endif +# endif constexpr size_t bufferLength = 128; std::array buffer {}; size_t bytes = std::strftime(buffer.data(), bufferLength, fmt.c_str(), &local_tm); @@ -411,11 +410,13 @@ TEST_F(BackupPolicyTest, DISABLED_TimestampWithAbsurdlyLongFormatStringThrows) // OPERATIONS, AND GENERATES AN INVALID FILENAME. FIXME. // Arrange - setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, - 1, - true, - "%A, %B %d, %Y at %H:%M:%S %Z (Day %j of the year, Week %U/%W) — This is a " - "verbose date string for demonstration purposes."); + setPolicyTerms( + App::BackupPolicy::Policy::TimeStamp, + 1, + true, + "%A, %B %d, %Y at %H:%M:%S %Z (Day %j of the year, Week %U/%W) — This is a " + "verbose date string for demonstration purposes." + ); auto source = createTempFile("source.fcstd"); auto target = createTempFile("target.fcstd"); @@ -436,7 +437,8 @@ TEST_F(BackupPolicyTest, TimestampDetectsOldBackupFormat) // Assert bool check1 = std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak")); + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak") + ); bool check2 = std::filesystem::exists(backup); EXPECT_NE(check1, check2); } @@ -455,7 +457,8 @@ TEST_F(BackupPolicyTest, TimestampDetectsOldBackupFormatIgnoresOther) // Assert bool check1 = std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak")); + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak") + ); bool check2 = std::filesystem::exists(backup); EXPECT_NE(check1, check2); EXPECT_TRUE(std::filesystem::exists(weird)); @@ -473,8 +476,11 @@ TEST_F(BackupPolicyTest, TimestampDetectsAndRetainsOldBackupWhenAllowed) apply(source.string(), target.string()); // Assert - EXPECT_TRUE(std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak"))); + EXPECT_TRUE( + std::filesystem::exists( + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak") + ) + ); EXPECT_TRUE(std::filesystem::exists(backup)); } @@ -489,8 +495,11 @@ TEST_F(BackupPolicyTest, TimestampFormatStringEndsWithSpace) apply(source.string(), target.string()); // Assert (the space is stripped, and an index is added) - EXPECT_TRUE(std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "1.FCBak"))); + EXPECT_TRUE( + std::filesystem::exists( + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "1.FCBak") + ) + ); } TEST_F(BackupPolicyTest, TimestampFormatStringEndsWithDash) @@ -504,8 +513,11 @@ TEST_F(BackupPolicyTest, TimestampFormatStringEndsWithDash) apply(source.string(), target.string()); // Assert (the dash is left, and an index is added) - EXPECT_TRUE(std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak"))); + EXPECT_TRUE( + std::filesystem::exists( + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak") + ) + ); } TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExists) @@ -521,8 +533,11 @@ TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExists) // Assert (An index is appended) EXPECT_TRUE(std::filesystem::exists(backup)); - EXPECT_TRUE(std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak"))); + EXPECT_TRUE( + std::filesystem::exists( + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak") + ) + ); } TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExistsMultipleTimes) @@ -532,12 +547,9 @@ TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExistsMultipleTimes) auto source = createTempFile("source.fcstd"); auto target = createTempFile("target.fcstd"); auto backup = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak"); - auto backup1 = - createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak"); - auto backup2 = - createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-2.FCBak"); - auto backup3 = - createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-3.FCBak"); + auto backup1 = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak"); + auto backup2 = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-2.FCBak"); + auto backup3 = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-3.FCBak"); // Act apply(source.string(), target.string()); @@ -547,6 +559,9 @@ TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExistsMultipleTimes) EXPECT_TRUE(std::filesystem::exists(backup1)); EXPECT_TRUE(std::filesystem::exists(backup2)); EXPECT_TRUE(std::filesystem::exists(backup3)); - EXPECT_TRUE(std::filesystem::exists( - getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-4.FCBak"))); + EXPECT_TRUE( + std::filesystem::exists( + getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-4.FCBak") + ) + ); } diff --git a/tests/src/App/DocumentObserver.cpp b/tests/src/App/DocumentObserver.cpp index 5779d23e62..e7a897ee02 100644 --- a/tests/src/App/DocumentObserver.cpp +++ b/tests/src/App/DocumentObserver.cpp @@ -219,12 +219,16 @@ TEST_F(DISABLED_DocumentObserverTest, normalize) // The subName is modified replacing "Part__Box" with "$Cube" to test the effect of using // SubObjectT::NormalizeOption::KeepSubName, that is leaving the "$Cube" instead of replacing it // with the name of the DocumentObject with that label ("Part__Box") - auto subObjTKeepSubName {SubObjectT(lGrp, - subName - .replace(strlen(partName) + strlen(fuseName) + 2, - strlen(boxName), - std::string("$").append(boxLabel).c_str()) - .c_str())}; + auto subObjTKeepSubName {SubObjectT( + lGrp, + subName + .replace( + strlen(partName) + strlen(fuseName) + 2, + strlen(boxName), + std::string("$").append(boxLabel).c_str() + ) + .c_str() + )}; // An App::SubObjectT object used to test SubObjectT::normalize() with the option argument set // to SubObjectT::NormalizeOption::ConvertIndex // The subName is modified replacing "App_Part" with "0" to test the effect of using @@ -255,8 +259,7 @@ TEST_F(DISABLED_DocumentObserverTest, normalize) normalizeWithoutEl = subObjTWithoutEl.normalize(SubObjectT::NormalizeOption::NoElement); normalizeNoFlatten = subObjTNoFlatten.normalize(SubObjectT::NormalizeOption::NoFlatten); normalizeKeepSubName = subObjTKeepSubName.normalize(SubObjectT::NormalizeOption::KeepSubName); - normalizeConvertIndex = - subObjTConvertIndex.normalize(SubObjectT::NormalizeOption::ConvertIndex); + normalizeConvertIndex = subObjTConvertIndex.normalize(SubObjectT::NormalizeOption::ConvertIndex); // Assert @@ -441,14 +444,14 @@ TEST_F(DISABLED_DocumentObserverTest, normalized) subObjTEmptyNormalized = subObjTEmpty.normalized(); subObjTWithoutSubObjNormalized = subObjTWithoutSubObj.normalized(); subObjTWithSubObjNormalized = subObjTWithSubObj.normalized(); - subObjTWithoutElNormalized = - subObjTWithoutEl.normalized(SubObjectT::NormalizeOption::NoElement); - subObjTNoFlattenNormalized = - subObjTNoFlatten.normalized(SubObjectT::NormalizeOption::NoFlatten); - subObjTKeepSubNameNormalized = - subObjTKeepSubName.normalized(SubObjectT::NormalizeOption::KeepSubName); - subObjTConvertIndexNormalized = - subObjTConvertIndex.normalized(SubObjectT::NormalizeOption::ConvertIndex); + subObjTWithoutElNormalized = subObjTWithoutEl.normalized(SubObjectT::NormalizeOption::NoElement); + subObjTNoFlattenNormalized = subObjTNoFlatten.normalized(SubObjectT::NormalizeOption::NoFlatten); + subObjTKeepSubNameNormalized = subObjTKeepSubName.normalized( + SubObjectT::NormalizeOption::KeepSubName + ); + subObjTConvertIndexNormalized = subObjTConvertIndex.normalized( + SubObjectT::NormalizeOption::ConvertIndex + ); // Assert diff --git a/tests/src/App/ElementMap.cpp b/tests/src/App/ElementMap.cpp index 3369b05e2f..c5b85b876f 100644 --- a/tests/src/App/ElementMap.cpp +++ b/tests/src/App/ElementMap.cpp @@ -149,8 +149,7 @@ TEST_F(ElementMapTest, setElementNameWithHashing) const Data::MappedName expectedName(element); // Act - elementMap - .encodeElementName(element.getType()[0], elementNameHolder, ss, nullptr, 0, nullptr, 0); + elementMap.encodeElementName(element.getType()[0], elementNameHolder, ss, nullptr, 0, nullptr, 0); auto resultName = elementMap.setElementName(element, elementNameHolder, 0, _sids); auto mappedToElement = elementMap.find(element); @@ -378,25 +377,29 @@ TEST_F(ElementMapTest, mimicSimpleUnion) // act: simulate a union/fuse operation auto parent = cube.elementMapPtr->getAll()[5]; Data::MappedName postfixHolder(std::string(Data::POSTFIX_MOD) + "2"); - unionPart.elementMapPtr->encodeElementName(postfixHolder[0], - postfixHolder, - ss, - nullptr, - unionPart.Tag, - nullptr, - unionPart.Tag); + unionPart.elementMapPtr->encodeElementName( + postfixHolder[0], + postfixHolder, + ss, + nullptr, + unionPart.Tag, + nullptr, + unionPart.Tag + ); auto postfixStr = postfixHolder.toString() + Data::ELEMENT_MAP_PREFIX + PartOp; // act: with the fuse op, name against the cube's Face6 Data::MappedName uface3Holder(parent.index); // we will invoke the encoder for face 3 - unionPart.elementMapPtr->encodeElementName(uface3Holder[0], - uface3Holder, - ss, - nullptr, - unionPart.Tag, - postfixStr.c_str(), - cube.Tag); + unionPart.elementMapPtr->encodeElementName( + uface3Holder[0], + uface3Holder, + ss, + nullptr, + unionPart.Tag, + postfixStr.c_str(), + cube.Tag + ); unionPart.elementMapPtr->setElementName(uface3, uface3Holder, unionPart.Tag, nullptr, true); // act: generate a full toponame string for testing purposes @@ -443,22 +446,26 @@ TEST_F(ElementMapTest, mimicOperationAgainstSelf) // Act // act: with the mystery op, name against its own Face6 for some reason Data::MappedName postfixHolder(workbenchId); - finalPart.elementMapPtr->encodeElementName(postfixHolder[0], - postfixHolder, - ss, - nullptr, - finalPart.Tag, - nullptr, - finalPart.Tag); + finalPart.elementMapPtr->encodeElementName( + postfixHolder[0], + postfixHolder, + ss, + nullptr, + finalPart.Tag, + nullptr, + finalPart.Tag + ); auto postfixStr = postfixHolder.toString() + Data::ELEMENT_MAP_PREFIX + PartOp; // we will invoke the encoder for face 3 - finalPart.elementMapPtr->encodeElementName(uface3Holder[0], - uface3Holder, - ss, - nullptr, - finalPart.Tag, - postfixStr.c_str(), - finalPart.Tag); + finalPart.elementMapPtr->encodeElementName( + uface3Holder[0], + uface3Holder, + ss, + nullptr, + finalPart.Tag, + postfixStr.c_str(), + finalPart.Tag + ); // override not forced finalPart.elementMapPtr->setElementName(uface3, uface3Holder, finalPart.Tag, nullptr, false); @@ -479,8 +486,8 @@ TEST_F(ElementMapTest, mimicOperationAgainstSelf) TEST_F(ElementMapTest, hasChildElementMapTest) { // Arrange - Data::ElementMap::MappedChildElements child = - {Data::IndexedName("face", 1), 2, 7, 4L, Data::ElementMapPtr(), QByteArray(""), _sid}; + Data::ElementMap::MappedChildElements child + = {Data::IndexedName("face", 1), 2, 7, 4L, Data::ElementMapPtr(), QByteArray(""), _sid}; std::vector children = {child}; LessComplexPart cubeFull(3L, "FullBox", _hasher); cubeFull.elementMapPtr->addChildElements(cubeFull.Tag, children); @@ -508,7 +515,8 @@ TEST_F(ElementMapTest, hashChildMapsTest) 3L, Data::ElementMapPtr(), QByteArray("abcdefghij"), // postfix must be 10 or more bytes to invoke hasher - _sid}; + _sid + }; std::vector children = {childOne}; cube.elementMapPtr->addChildElements(cube.Tag, children); auto before = _hasher->getIDMap(); @@ -533,9 +541,10 @@ TEST_F(ElementMapTest, addAndGetChildElementsTest) 3L, Data::ElementMapPtr(), QByteArray("abcdefghij"), // postfix must be 10 or more bytes to invoke hasher - _sid}; - Data::ElementMap::MappedChildElements childTwo = - {Data::IndexedName("Pong", 2), 2, 7, 4L, Data::ElementMapPtr(), QByteArray("abc"), _sid}; + _sid + }; + Data::ElementMap::MappedChildElements childTwo + = {Data::IndexedName("Pong", 2), 2, 7, 4L, Data::ElementMapPtr(), QByteArray("abc"), _sid}; std::vector children = {childOne, childTwo}; // Act @@ -544,13 +553,11 @@ TEST_F(ElementMapTest, addAndGetChildElementsTest) // Assert EXPECT_EQ(result.size(), 2); - EXPECT_TRUE( - std::any_of(result.begin(), result.end(), [](Data::ElementMap::MappedChildElements e) { - return e.indexedName.toString() == "Ping1"; - })); - EXPECT_TRUE( - std::any_of(result.begin(), result.end(), [](Data::ElementMap::MappedChildElements e) { - return e.indexedName.toString() == "Pong2"; - })); + EXPECT_TRUE(std::any_of(result.begin(), result.end(), [](Data::ElementMap::MappedChildElements e) { + return e.indexedName.toString() == "Ping1"; + })); + EXPECT_TRUE(std::any_of(result.begin(), result.end(), [](Data::ElementMap::MappedChildElements e) { + return e.indexedName.toString() == "Pong2"; + })); } // NOLINTEND(readability-magic-numbers) diff --git a/tests/src/App/ElementNamingUtils.cpp b/tests/src/App/ElementNamingUtils.cpp index 5c04a1d3cc..5da0d3e0e0 100644 --- a/tests/src/App/ElementNamingUtils.cpp +++ b/tests/src/App/ElementNamingUtils.cpp @@ -42,16 +42,20 @@ TEST_F(ElementNamingUtilsTest, findElementName) // Act Data::ElementMap elementMap = Data::ElementMap(); auto name1 = Data::findElementName("Edge1"); - auto name2 = Data::findElementName(";g5v2;SKT;:Had6,V;:G;OFS;:Had6:7,V;:G;OFS;:Had6:7,V;WIR;:" - "Had6:4,V;:G;XTR;:Had6:7,E;:H,E.Face1.Edge2"); + auto name2 = Data::findElementName( + ";g5v2;SKT;:Had6,V;:G;OFS;:Had6:7,V;:G;OFS;:Had6:7,V;WIR;:" + "Had6:4,V;:G;XTR;:Had6:7,E;:H,E.Face1.Edge2" + ); auto name3 = Data::findElementName("An.Example.Assembly.Edge3"); auto name4 = Data::findElementName(".Edge4"); // Assert EXPECT_STREQ(name1, "Edge1"); - EXPECT_STREQ(name2, - ";g5v2;SKT;:Had6,V;:G;OFS;:Had6:7,V;:G;OFS;:Had6:7,V;WIR;:" - "Had6:4,V;:G;XTR;:Had6:7,E;:H,E.Face1.Edge2"); + EXPECT_STREQ( + name2, + ";g5v2;SKT;:Had6,V;:G;OFS;:Had6:7,V;:G;OFS;:Had6:7,V;WIR;:" + "Had6:4,V;:G;XTR;:Had6:7,E;:H,E.Face1.Edge2" + ); EXPECT_STREQ(name3, "Edge3"); EXPECT_STREQ(name4, "Edge4"); } diff --git a/tests/src/App/IndexedName.cpp b/tests/src/App/IndexedName.cpp index c51eec01eb..857b13f98f 100644 --- a/tests/src/App/IndexedName.cpp +++ b/tests/src/App/IndexedName.cpp @@ -18,19 +18,23 @@ protected: // Create and return a list of invalid IndexedNames static std::vector givenInvalidIndexedNames() { - return std::vector {Data::IndexedName(), - Data::IndexedName("", 1), - Data::IndexedName("INVALID42NAME", 1), - Data::IndexedName(".EDGE", 1)}; + return std::vector { + Data::IndexedName(), + Data::IndexedName("", 1), + Data::IndexedName("INVALID42NAME", 1), + Data::IndexedName(".EDGE", 1) + }; } // Create and return a list of valid IndexedNames static std::vector givenValidIndexedNames() { - return std::vector {Data::IndexedName("NAME"), - Data::IndexedName("NAME1"), - Data::IndexedName("NAME", 1), - Data::IndexedName("NAME_WITH_UNDERSCORES12345")}; + return std::vector { + Data::IndexedName("NAME"), + Data::IndexedName("NAME1"), + Data::IndexedName("NAME", 1), + Data::IndexedName("NAME_WITH_UNDERSCORES12345") + }; } // An arbitrary list of C strings used for testing some types of construction diff --git a/tests/src/App/License.cpp b/tests/src/App/License.cpp index 5429eeca33..ac1527b761 100644 --- a/tests/src/App/License.cpp +++ b/tests/src/App/License.cpp @@ -28,9 +28,11 @@ TEST(License, UnknownIdentifier) TEST(License, direct) { int posn {App::findLicense("CC_BY_40")}; - App::TLicenseArr tt {"CC_BY_40", - "Creative Commons Attribution 4.0", - "https://creativecommons.org/licenses/by/4.0/"}; + App::TLicenseArr tt { + "CC_BY_40", + "Creative Commons Attribution 4.0", + "https://creativecommons.org/licenses/by/4.0/" + }; EXPECT_STREQ(App::licenseItems.at(posn).at(0), tt.at(0)); EXPECT_STREQ(App::licenseItems.at(posn).at(1), tt.at(1)); EXPECT_STREQ(App::licenseItems.at(posn).at(2), tt.at(2)); diff --git a/tests/src/App/MappedElement.cpp b/tests/src/App/MappedElement.cpp index 6421a6aca3..ee28ac6c46 100644 --- a/tests/src/App/MappedElement.cpp +++ b/tests/src/App/MappedElement.cpp @@ -259,9 +259,11 @@ TEST_F(MappedElementTest, comparatorThreeComplexHexNamesInMap) // The expected order depends on your comparator logic. // If you want to check the exact order, set it here: // (Replace with the correct expected order if needed) - std::vector expectedOrder = {"#19c9:e;:U;FUS;:Hce4:7,E", - "#1dadb:11;:L#1061a;FUS;:H:d,E", - "#1dae6:8;:L#1dae4;FUS;:H:d,E"}; + std::vector expectedOrder = { + "#19c9:e;:U;FUS;:Hce4:7,E", + "#1dadb:11;:L#1061a;FUS;:H:d,E", + "#1dae6:8;:L#1dae4;FUS;:H:d,E" + }; EXPECT_EQ(keys, expectedOrder); } @@ -311,7 +313,8 @@ TEST_F(MappedElementTest, comparatorLargerWorkedExampleWithMap) "g4v2;SKT;:H1234,F;:H5678:2,E;:G0(g1;SKT;:H9012,E);XTR;:H3456:2,F", "#1dad:e;:U;FUS;:Hce4:7,E", "#1dadb:11;:L#1061a;FUS;:H:d,E", - "#1dae6:8;:L#1dae4;FUS;:H:d,E"}; + "#1dae6:8;:L#1dae4;FUS;:H:d,E" + }; EXPECT_EQ(keys, expectedOrder); } diff --git a/tests/src/App/MappedName.cpp b/tests/src/App/MappedName.cpp index a53c476110..4d8fe91de8 100644 --- a/tests/src/App/MappedName.cpp +++ b/tests/src/App/MappedName.cpp @@ -583,9 +583,11 @@ TEST(MappedName, appendToBufferWithPrefix) mappedName2.appendToBufferWithPrefix(buffer); // Assert - EXPECT_EQ(buffer, - std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST") - + /*missing prefix*/ std::string("TEST")); + EXPECT_EQ( + buffer, + std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST") + + /*missing prefix*/ std::string("TEST") + ); } TEST(MappedName, toPrefixedString) @@ -609,9 +611,11 @@ TEST(MappedName, toPrefixedString) buffer += mappedName2.toPrefixedString(); // Assert - EXPECT_EQ(buffer, - std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST") - + /*missing prefix*/ std::string("TEST")); + EXPECT_EQ( + buffer, + std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST") + + /*missing prefix*/ std::string("TEST") + ); } TEST(MappedName, toBytes) @@ -849,8 +853,7 @@ TEST(MappedName, findTagInElementNameHexPositiveIndexNonrecursive) char type {0}; // Act - int result = - mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false); + int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false); // Assert EXPECT_EQ(result, 36); // The location of the tag @@ -872,8 +875,7 @@ TEST(MappedName, findTagInElementNameDecPositiveIndexNonrecursive) char type {0}; // Act - int result = - mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false); + int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false); // Assert EXPECT_EQ(result, 36); // The location of the tag @@ -895,8 +897,7 @@ TEST(MappedName, findTagInElementNameHexNegativeIndexNonrecursive) char type {0}; // Act - int result = - mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false); + int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false); // Assert EXPECT_EQ(result, 36); // The location of the tag @@ -918,8 +919,7 @@ TEST(MappedName, findTagInElementNameHexExpectedNegativeIndexNonrecursive) char type {0}; // Act - int result = - mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, true, false); + int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, true, false); // Assert EXPECT_EQ(result, 36); // The location of the tag @@ -941,8 +941,7 @@ TEST(MappedName, findTagInElementNameRecursive) char type {0}; // Act - int result = - mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, true); + int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, true); // Assert EXPECT_EQ(result, 36); // The location of the tag diff --git a/tests/src/App/Property.cpp b/tests/src/App/Property.cpp index 96e5d7c0d1..d7cb1665df 100644 --- a/tests/src/App/Property.cpp +++ b/tests/src/App/Property.cpp @@ -113,7 +113,8 @@ TEST_F(RenameProperty, renamePropertyPython) { // Act Base::Interpreter().runString( - "App.ActiveDocument.getObject('VarSet').renameProperty('Variable', 'NewName')"); + "App.ActiveDocument.getObject('VarSet').renameProperty('Variable', 'NewName')" + ); // Assert EXPECT_STREQ(varSet->getPropertyName(prop), "NewName"); @@ -170,8 +171,10 @@ TEST_F(RenameProperty, renameStaticPropertyPython) // Act / Assert EXPECT_THROW( Base::Interpreter().runString( - "App.ActiveDocument.getObject('VarSet006').renameProperty('Label', 'NewName')"), - Base::Exception); + "App.ActiveDocument.getObject('VarSet006').renameProperty('Label', 'NewName')" + ), + Base::Exception + ); // Assert EXPECT_STREQ(varSet->getPropertyName(prop), "Label"); @@ -198,8 +201,7 @@ TEST_F(RenameProperty, renameLockedProperty) TEST_F(RenameProperty, renameToExistingProperty) { // Arrange - App::Property* prop2 = - varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables"); + App::Property* prop2 = varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables"); // Act / Assert EXPECT_THROW(varSet->renameDynamicProperty(prop2, "Variable"), Base::NameError); @@ -230,7 +232,8 @@ TEST_F(RenameProperty, updateExpressionSameContainer) { // Arrange const auto* prop2 = freecad_cast( - varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")); + varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables") + ); App::ObjectIdentifier path(*prop2); std::shared_ptr expr(App::Expression::parse(varSet, "Variable")); @@ -260,7 +263,8 @@ TEST_F(RenameProperty, updateExpressionDifferentContainer) // Arrange auto* varSet2 = freecad_cast(_doc->addObject("App::VarSet", "VarSet2")); const auto* prop2 = freecad_cast( - varSet2->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")); + varSet2->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables") + ); App::ObjectIdentifier path(*prop2); std::shared_ptr expr(App::Expression::parse(varSet, "VarSet.Variable")); @@ -296,7 +300,8 @@ TEST_F(RenameProperty, updateExpressionDifferentDocument) auto* varSet2 = freecad_cast(doc->addObject("App::VarSet", "VarSet2")); const auto* prop2 = freecad_cast( - varSet2->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")); + varSet2->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables") + ); App::ObjectIdentifier path(*prop2); std::shared_ptr expr(App::Expression::parse(varSet, "test#VarSet.Variable")); @@ -330,7 +335,8 @@ TEST_F(RenameProperty, renamePropertyWithExpression) { // Arrange auto* prop2 = freecad_cast( - varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")); + varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables") + ); prop2->setValue(Value); App::ObjectIdentifier path(*prop); diff --git a/tests/src/App/Property.h b/tests/src/App/Property.h index 38ab09c4cc..f27608fda7 100644 --- a/tests/src/App/Property.h +++ b/tests/src/App/Property.h @@ -46,7 +46,8 @@ protected: { varSet = freecad_cast(_doc->addObject("App::VarSet", "VarSet")); prop = freecad_cast( - varSet->addDynamicProperty("App::PropertyInteger", "Variable", "Variables")); + varSet->addDynamicProperty("App::PropertyInteger", "Variable", "Variables") + ); prop->setValue(Value); } diff --git a/tests/src/App/StringHasher.cpp b/tests/src/App/StringHasher.cpp index 227401e360..4e86a3df7a 100644 --- a/tests/src/App/StringHasher.cpp +++ b/tests/src/App/StringHasher.cpp @@ -284,8 +284,8 @@ TEST_F(StringIDTest, fromStringWithEOFAndLengthGood) // NOLINT const std::string testString {"#1:fcad"}; // Act - auto result = - App::StringID::fromString(testString.c_str(), true, static_cast(testString.length())); + auto result + = App::StringID::fromString(testString.c_str(), true, static_cast(testString.length())); // Assert EXPECT_EQ(result.id, 1); @@ -298,10 +298,10 @@ TEST_F(StringIDTest, fromStringExtraData) // NOLINT const std::string testString {"#1:fcad#2:bad"}; // Act - auto trueResult = - App::StringID::fromString(testString.c_str(), true, static_cast(testString.length())); - auto falseResult = - App::StringID::fromString(testString.c_str(), false, static_cast(testString.length())); + auto trueResult + = App::StringID::fromString(testString.c_str(), true, static_cast(testString.length())); + auto falseResult + = App::StringID::fromString(testString.c_str(), false, static_cast(testString.length())); // Assert EXPECT_EQ(trueResult.id, -1); @@ -748,8 +748,8 @@ TEST_F(StringIDRefTest, swap) // NOLINT } #if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wself-assign-overloaded" +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wself-assign-overloaded" #endif TEST_F(StringIDRefTest, assignmentFromSelf) // NOLINT @@ -765,7 +765,7 @@ TEST_F(StringIDRefTest, assignmentFromSelf) // NOLINT } #if defined(__clang__) -#pragma clang diagnostic pop +# pragma clang diagnostic pop #endif TEST_F(StringIDRefTest, assignmentToEmptyFromStringID) // NOLINT diff --git a/tests/src/App/VarSet.cpp b/tests/src/App/VarSet.cpp index 89ed405d20..ca2fe7c451 100644 --- a/tests/src/App/VarSet.cpp +++ b/tests/src/App/VarSet.cpp @@ -89,7 +89,8 @@ TEST_F(VarSet, addProperty) // Act auto prop = dynamic_cast( - varSet->addDynamicProperty("App::PropertyInteger", "Variable", "Variables")); + varSet->addDynamicProperty("App::PropertyInteger", "Variable", "Variables") + ); prop->setValue(VALUE); // Assert diff --git a/tests/src/Base/Base64.cpp b/tests/src/Base/Base64.cpp index f20b14350d..672ed9aba4 100644 --- a/tests/src/Base/Base64.cpp +++ b/tests/src/Base/Base64.cpp @@ -54,9 +54,10 @@ TEST(Base64, exactlyFourBytes) std::string rest0_original = "abc"; // std::string rest0_reference = "YWJj"; - std::string rest0_encoded = - base64_encode(reinterpret_cast(rest0_original.c_str()), - rest0_original.length()); + std::string rest0_encoded = base64_encode( + reinterpret_cast(rest0_original.c_str()), + rest0_original.length() + ); std::string rest0_decoded = base64_decode(rest0_encoded); ASSERT_EQ(rest0_decoded, rest0_original); @@ -67,9 +68,10 @@ TEST(Base64, twoEqualsSignsPadding) std::string rest1_original = "abcd"; // std::string rest1_reference = "YWJjZA=="; - std::string rest1_encoded = - base64_encode(reinterpret_cast(rest1_original.c_str()), - rest1_original.length()); + std::string rest1_encoded = base64_encode( + reinterpret_cast(rest1_original.c_str()), + rest1_original.length() + ); std::string rest1_decoded = base64_decode(rest1_encoded); ASSERT_EQ(rest1_decoded, rest1_original); @@ -80,9 +82,10 @@ TEST(Base64, oneEqualsSignPadding) std::string rest2_original = "abcde"; // std::string rest2_reference = "YWJjZGU="; - std::string rest2_encoded = - base64_encode(reinterpret_cast(rest2_original.c_str()), - rest2_original.length()); + std::string rest2_encoded = base64_encode( + reinterpret_cast(rest2_original.c_str()), + rest2_original.length() + ); std::string rest2_decoded = base64_decode(rest2_encoded); ASSERT_EQ(rest2_decoded, rest2_original); diff --git a/tests/src/Base/BoundBox.cpp b/tests/src/Base/BoundBox.cpp index bcb0555819..06165cf899 100644 --- a/tests/src/Base/BoundBox.cpp +++ b/tests/src/Base/BoundBox.cpp @@ -1,10 +1,10 @@ #include #ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#ifndef NOMINMAX -#define NOMINMAX -#endif -#include +# define WIN32_LEAN_AND_MEAN +# ifndef NOMINMAX +# define NOMINMAX +# endif +# include #endif #include #include @@ -95,9 +95,11 @@ TEST(BoundBox, TestEmptySpan) TEST(BoundBox, TestNonEmptySpan) { - std::vector points = {Base::Vector3d {1.0, 0.0, 0.0}, - Base::Vector3d {0.0, 1.0, 0.0}, - Base::Vector3d {0.0, 0.0, 1.0}}; + std::vector points = { + Base::Vector3d {1.0, 0.0, 0.0}, + Base::Vector3d {0.0, 1.0, 0.0}, + Base::Vector3d {0.0, 0.0, 1.0} + }; Base::BoundBox3d box = createBox({points.data(), 2}); EXPECT_EQ(box.IsValid(), true); EXPECT_EQ(box.MinX, 0); @@ -110,9 +112,11 @@ TEST(BoundBox, TestNonEmptySpan) TEST(BoundBox, TestArray) { - std::vector points = {Base::Vector3d {1.0, 0.0, 0.0}, - Base::Vector3d {0.0, 1.0, 0.0}, - Base::Vector3d {0.0, 0.0, 1.0}}; + std::vector points = { + Base::Vector3d {1.0, 0.0, 0.0}, + Base::Vector3d {0.0, 1.0, 0.0}, + Base::Vector3d {0.0, 0.0, 1.0} + }; Base::BoundBox3d box(points.data(), points.size()); EXPECT_EQ(box.IsValid(), true); EXPECT_EQ(box.MinX, 0); diff --git a/tests/src/Base/Reader.cpp b/tests/src/Base/Reader.cpp index ff01d72d25..f5071611c1 100644 --- a/tests/src/Base/Reader.cpp +++ b/tests/src/Base/Reader.cpp @@ -5,8 +5,8 @@ #include #ifdef _MSC_VER -#pragma warning(disable : 4996) -#pragma warning(disable : 4305) +# pragma warning(disable : 4996) +# pragma warning(disable : 4305) #endif #include "Base/Exception.h" @@ -43,8 +43,7 @@ public: ReaderXML() { _tempDir = fs::temp_directory_path(); - fs::path filename = - std::string("unit_test_Reader-") + random_string(4) + std::string(".xml"); + fs::path filename = std::string("unit_test_Reader-") + random_string(4) + std::string(".xml"); _tempFile = _tempDir / filename; } ~ReaderXML() @@ -64,8 +63,8 @@ public: void givenDataAsXMLStream(const std::string& data) { - auto stringData = - R"()" + data + ""; + auto stringData = R"()" + data + + ""; std::istringstream stream(stringData); std::ofstream fileStream(_tempFile.string()); fileStream.write(stringData.data(), static_cast(stringData.length())); @@ -366,8 +365,7 @@ TEST_F(ReaderTest, readNextStartEndElement) // next element EXPECT_TRUE(xml.Reader()->readNextElement()); EXPECT_STREQ(xml.Reader()->localName(), "node7"); - EXPECT_EQ(xml.Reader()->getAttribute("attr"), - std::string("const char* is faster :'(")); + EXPECT_EQ(xml.Reader()->getAttribute("attr"), std::string("const char* is faster :'(")); // next element EXPECT_TRUE(xml.Reader()->readNextElement()); @@ -440,8 +438,7 @@ TEST_F(ReaderTest, validDefaults) bool value14 = xml.Reader()->getAttribute("missing", 1); bool value16 = xml.Reader()->getAttribute("missing", -10); bool value18 = xml.Reader()->getAttribute("missing", 10); - TimesIGoToBed value20 = - xml.Reader()->getAttribute("missing", TimesIGoToBed::Late); + TimesIGoToBed value20 = xml.Reader()->getAttribute("missing", TimesIGoToBed::Late); // Assert EXPECT_THROW({ xml.Reader()->getAttribute("missing"); }, Base::XMLBaseException); diff --git a/tests/src/Base/SchemaTests.cpp b/tests/src/Base/SchemaTests.cpp index 55127b67ec..2e2f87cf91 100644 --- a/tests/src/Base/SchemaTests.cpp +++ b/tests/src/Base/SchemaTests.cpp @@ -53,18 +53,19 @@ protected: void TearDown() override {} - static std::string - set(const std::string& schemaName, const Unit unit, const double value) // NOLINT + static std::string set(const std::string& schemaName, const Unit unit, const double value) // NOLINT { UnitsApi::setSchema(schemaName); const auto quantity = Quantity {value, unit}; return quantity.getSafeUserString(); } - static std::string setWithPrecision(const std::string& name, - const double value, - const Unit unit, - const int precision) + static std::string setWithPrecision( + const std::string& name, + const double value, + const Unit unit, + const int precision + ) { UnitsApi::setSchema(name); Quantity quantity {value, unit}; @@ -74,10 +75,12 @@ protected: return quantity.getSafeUserString(); } - static std::string setWithDenominator(const std::string& name, - const double value, - const Unit unit, - const int denominator) + static std::string setWithDenominator( + const std::string& name, + const double value, + const Unit unit, + const int denominator + ) { UnitsApi::setSchema(name); Quantity quantity {value, unit}; @@ -124,8 +127,8 @@ TEST_F(SchemaTest, meter_decimal_123456000_W_precision_6) TEST_F(SchemaTest, meter_decimal_123456000_V_precision_6) { - const std::string result = - setWithPrecision("MeterDecimal", 123456000.0, Unit::ElectricPotential, 6); + const std::string result + = setWithPrecision("MeterDecimal", 123456000.0, Unit::ElectricPotential, 6); const auto expect {"123.456000 V"}; EXPECT_EQ(result, expect); diff --git a/tests/src/Base/Stream.cpp b/tests/src/Base/Stream.cpp index 9c536a903f..720b861d21 100644 --- a/tests/src/Base/Stream.cpp +++ b/tests/src/Base/Stream.cpp @@ -3,7 +3,7 @@ #include #ifdef _MSC_VER -#pragma warning(disable : 4996) +# pragma warning(disable : 4996) #endif #include "Base/Stream.h" diff --git a/tests/src/Base/UnlimitedUnsigned.cpp b/tests/src/Base/UnlimitedUnsigned.cpp index 240c7ed141..ddf4a8c2ad 100644 --- a/tests/src/Base/UnlimitedUnsigned.cpp +++ b/tests/src/Base/UnlimitedUnsigned.cpp @@ -40,16 +40,20 @@ TEST(UnlimitedUnsigned, ToString) TEST(UnlimitedUnsigned, TestSubtraction1) { // Check subtraction and comparison with byte-sized number - EXPECT_EQ(Base::UnlimitedUnsigned::fromString("6842357951") - - Base::UnlimitedUnsigned::fromString("6842357948"), - 3); + EXPECT_EQ( + Base::UnlimitedUnsigned::fromString("6842357951") + - Base::UnlimitedUnsigned::fromString("6842357948"), + 3 + ); } TEST(UnlimitedUnsigned, TestSubtraction2) { // Check subtraction and comparison - EXPECT_EQ(Base::UnlimitedUnsigned::fromString("6842357951") - - Base::UnlimitedUnsigned::fromString("6000000000"), - Base::UnlimitedUnsigned::fromString("842357951")); + EXPECT_EQ( + Base::UnlimitedUnsigned::fromString("6842357951") + - Base::UnlimitedUnsigned::fromString("6000000000"), + Base::UnlimitedUnsigned::fromString("842357951") + ); } // NOLINTEND(cppcoreguidelines-*,readability-*) diff --git a/tests/src/Base/Vector3D.cpp b/tests/src/Base/Vector3D.cpp index 993e00e75c..12808ef3a4 100644 --- a/tests/src/Base/Vector3D.cpp +++ b/tests/src/Base/Vector3D.cpp @@ -218,9 +218,11 @@ TEST(Vector, TestNormalize) TEST(Vector, TestCSTransform) { Base::Vector3d vec(1, 2, 3); - vec.TransformToCoordinateSystem(Base::Vector3d(1, 1, 1), - Base::Vector3d(0, 1, 0), - Base::Vector3d(1, 0, 0)); + vec.TransformToCoordinateSystem( + Base::Vector3d(1, 1, 1), + Base::Vector3d(0, 1, 0), + Base::Vector3d(1, 0, 0) + ); EXPECT_EQ(vec.x, 1); EXPECT_EQ(vec.y, 0); EXPECT_EQ(vec.z, -2); diff --git a/tests/src/Gui/InputHintTest.cpp b/tests/src/Gui/InputHintTest.cpp index 7aa543a604..b6c8ad015f 100644 --- a/tests/src/Gui/InputHintTest.cpp +++ b/tests/src/Gui/InputHintTest.cpp @@ -47,8 +47,10 @@ TEST_F(InputHintTest, LookupHintsSimpleState) std::list hintsSeekFirst = {firstHint}; std::list hintsSeekSecond = {secondHint}; - HintTable table = {{.state = State::SeekFirst, .hints = hintsSeekFirst}, - {.state = State::SeekSecond, .hints = hintsSeekSecond}}; + HintTable table = { + {.state = State::SeekFirst, .hints = hintsSeekFirst}, + {.state = State::SeekSecond, .hints = hintsSeekSecond} + }; // Act auto resultFirst = lookupHints(State::SeekFirst, table); @@ -71,7 +73,8 @@ TEST_F(InputHintTest, LookupHintsPairState) {.state = {State::SeekFirst, Method::FirstMethod}, .hints = firstFirstHints}, {.state = {State::SeekFirst, Method::SecondMethod}, .hints = firstSecondHints}, {.state = {State::SeekSecond, Method::FirstMethod}, .hints = secondFirstHints}, - {.state = {State::SeekSecond, Method::SecondMethod}, .hints = secondSecondHints}}; + {.state = {State::SeekSecond, Method::SecondMethod}, .hints = secondSecondHints} + }; // Act auto resultFirstFirst = lookupHints({State::SeekFirst, Method::FirstMethod}, table); diff --git a/tests/src/Gui/StyleParameters/ParameterManagerTest.cpp b/tests/src/Gui/StyleParameters/ParameterManagerTest.cpp index 57bb79656c..c488ae965a 100644 --- a/tests/src/Gui/StyleParameters/ParameterManagerTest.cpp +++ b/tests/src/Gui/StyleParameters/ParameterManagerTest.cpp @@ -41,7 +41,8 @@ protected: {"PrimaryColor", "#ff0000"}, {"SecondaryColor", "#00ff00"}, }, - ParameterSource::Metadata {"Source 1"}); + ParameterSource::Metadata {"Source 1"} + ); auto source2 = std::make_unique( std::list { @@ -49,7 +50,8 @@ protected: {"Margin", "@BaseSize * 2"}, {"Padding", "@BaseSize / 2"}, }, - ParameterSource::Metadata {"Source 2"}); + ParameterSource::Metadata {"Source 2"} + ); manager.addSource(source1.get()); manager.addSource(source2.get()); @@ -160,7 +162,8 @@ TEST_F(ParameterManagerTest, SourcePriority) std::list { {"BaseSize", "24px"}, // Should override both previous sources }, - ParameterSource::Metadata {"Source 3"}); + ParameterSource::Metadata {"Source 3"} + ); manager.addSource(source3.get()); sources.push_back(std::move(source3)); @@ -254,7 +257,8 @@ TEST_F(ParameterManagerTest, CircularReferenceDetection) {"A", "@B"}, {"B", "@A"}, }, - ParameterSource::Metadata {"Circular Source"}); + ParameterSource::Metadata {"Circular Source"} + ); manager.addSource(circularSource.get()); sources.push_back(std::move(circularSource)); @@ -275,7 +279,8 @@ TEST_F(ParameterManagerTest, ComplexExpressions) {"ComplexPadding", "(@BaseSize - 2px) / 2"}, {"ColorWithFunction", "lighten(@PrimaryColor, 20)"}, }, - ParameterSource::Metadata {"Complex Source"}); + ParameterSource::Metadata {"Complex Source"} + ); manager.addSource(complexSource.get()); sources.push_back(std::move(complexSource)); @@ -317,7 +322,8 @@ TEST_F(ParameterManagerTest, ErrorHandling) std::list { {"Invalid", "invalid expression that will fail"}, }, - ParameterSource::Metadata {"Invalid Source"}); + ParameterSource::Metadata {"Invalid Source"} + ); manager.addSource(invalidSource.get()); sources.push_back(std::move(invalidSource)); diff --git a/tests/src/Gui/StyleParameters/ParserTest.cpp b/tests/src/Gui/StyleParameters/ParserTest.cpp index a2b550f34c..4df1f2e3c0 100644 --- a/tests/src/Gui/StyleParameters/ParserTest.cpp +++ b/tests/src/Gui/StyleParameters/ParserTest.cpp @@ -42,7 +42,8 @@ protected: {"TestColor", "#ff0000"}, {"TestNumber", "5"}, }, - ParameterSource::Metadata {"Test Source"}); + ParameterSource::Metadata {"Test Source"} + ); manager.addSource(source.get()); sources.push_back(std::move(source)); @@ -396,7 +397,8 @@ TEST_F(ParserTest, ParseErrors) Parser parser("#invalid"); parser.parse(); }, - Base::ParserError); + Base::ParserError + ); // Invalid RGB format EXPECT_THROW( @@ -404,7 +406,8 @@ TEST_F(ParserTest, ParseErrors) Parser parser("rgb(invalid)"); parser.parse(); }, - Base::ParserError); + Base::ParserError + ); // Missing closing parenthesis EXPECT_THROW( @@ -412,7 +415,8 @@ TEST_F(ParserTest, ParseErrors) Parser parser("(10 + 5"); parser.parse(); }, - Base::ParserError); + Base::ParserError + ); // Invalid function EXPECT_THROW( @@ -421,7 +425,8 @@ TEST_F(ParserTest, ParseErrors) auto expr = parser.parse(); expr->evaluate({&manager, {}}); }, - Base::ExpressionError); + Base::ExpressionError + ); // Division by zero EXPECT_THROW( @@ -430,7 +435,8 @@ TEST_F(ParserTest, ParseErrors) auto expr = parser.parse(); expr->evaluate({&manager, {}}); }, - Base::RuntimeError); + Base::RuntimeError + ); // Unit mismatch EXPECT_THROW( @@ -439,7 +445,8 @@ TEST_F(ParserTest, ParseErrors) auto expr = parser.parse(); expr->evaluate({&manager, {}}); }, - Base::RuntimeError); + Base::RuntimeError + ); // Unary operation on color EXPECT_THROW( @@ -448,7 +455,8 @@ TEST_F(ParserTest, ParseErrors) auto expr = parser.parse(); expr->evaluate({&manager, {}}); }, - Base::ExpressionError); + Base::ExpressionError + ); // Function with wrong number of arguments EXPECT_THROW( @@ -457,7 +465,8 @@ TEST_F(ParserTest, ParseErrors) auto expr = parser.parse(); expr->evaluate({&manager, {}}); }, - Base::ExpressionError); + Base::ExpressionError + ); // Function with wrong argument type EXPECT_THROW( @@ -466,7 +475,8 @@ TEST_F(ParserTest, ParseErrors) auto expr = parser.parse(); expr->evaluate({&manager, {}}); }, - Base::ExpressionError); + Base::ExpressionError + ); } // Test whitespace handling @@ -513,7 +523,8 @@ TEST_F(ParserTest, ParseEdgeCases) Parser parser(""); parser.parse(); }, - Base::ParserError); + Base::ParserError + ); // Just whitespace EXPECT_THROW( @@ -521,7 +532,8 @@ TEST_F(ParserTest, ParseEdgeCases) Parser parser(" "); parser.parse(); }, - Base::ParserError); + Base::ParserError + ); // Single number { diff --git a/tests/src/Gui/StyleParameters/StyleParametersApplicationTest.cpp b/tests/src/Gui/StyleParameters/StyleParametersApplicationTest.cpp index 935b1681ed..f7e3e0b886 100644 --- a/tests/src/Gui/StyleParameters/StyleParametersApplicationTest.cpp +++ b/tests/src/Gui/StyleParameters/StyleParametersApplicationTest.cpp @@ -53,7 +53,8 @@ protected: {.name = "FontSize", .value = "12px"}, {.name = "BoxWidth", .value = "100px"}, }, - {.name = "Fixture Source"})); + {.name = "Fixture Source"} + )); } }; diff --git a/tests/src/Mod/Material/App/TestMaterialProperties.cpp b/tests/src/Mod/Material/App/TestMaterialProperties.cpp index 63dfe33cd7..e80b8d60b0 100644 --- a/tests/src/Mod/Material/App/TestMaterialProperties.cpp +++ b/tests/src/Mod/Material/App/TestMaterialProperties.cpp @@ -44,25 +44,30 @@ protected: void SetUp() override { // 2D Properties - modelProp = Materials::ModelProperty(QStringLiteral("Density"), // Name - QStringLiteral("D"), // Header - QStringLiteral("2DArray"), // Type - QStringLiteral(""), // Units - QStringLiteral(""), // URL - QStringLiteral("desc")); // Description - modelProp1 = Materials::ModelProperty(QStringLiteral("Temperature"), - QStringLiteral("T"), - QStringLiteral("Quantity"), - QStringLiteral("C"), - QStringLiteral(""), - QStringLiteral("desc1")); - modelProp2 = - Materials::ModelProperty(QStringLiteral("Density"), - QStringLiteral("D"), - QStringLiteral("Quantity"), - QStringLiteral("kg/m^3"), - QStringLiteral("https://en.wikipedia.org/wiki/Density"), - QStringLiteral("desc2")); + modelProp = Materials::ModelProperty( + QStringLiteral("Density"), // Name + QStringLiteral("D"), // Header + QStringLiteral("2DArray"), // Type + QStringLiteral(""), // Units + QStringLiteral(""), // URL + QStringLiteral("desc") + ); // Description + modelProp1 = Materials::ModelProperty( + QStringLiteral("Temperature"), + QStringLiteral("T"), + QStringLiteral("Quantity"), + QStringLiteral("C"), + QStringLiteral(""), + QStringLiteral("desc1") + ); + modelProp2 = Materials::ModelProperty( + QStringLiteral("Density"), + QStringLiteral("D"), + QStringLiteral("Quantity"), + QStringLiteral("kg/m^3"), + QStringLiteral("https://en.wikipedia.org/wiki/Density"), + QStringLiteral("desc2") + ); modelProp.addColumn(modelProp1); modelProp.addColumn(modelProp2); @@ -74,26 +79,35 @@ protected: QStringLiteral("3DArray"), // Type QStringLiteral(""), // Units QStringLiteral(""), // URL - QStringLiteral("3 Dimensional array showing stress and strain as a function of " - "temperature")); // Description - model3DProp1 = Materials::ModelProperty(QStringLiteral("Temperature"), - QStringLiteral("T"), - QStringLiteral("Quantity"), - QStringLiteral("C"), - QStringLiteral(""), - QStringLiteral("desc1")); - model3DProp2 = Materials::ModelProperty(QStringLiteral("Stress"), - QStringLiteral("Stress"), - QStringLiteral("Quantity"), - QStringLiteral("MPa"), - QStringLiteral(""), - QStringLiteral("desc2")); - model3DProp3 = Materials::ModelProperty(QStringLiteral("Strain"), - QStringLiteral("Strain"), - QStringLiteral("Quantity"), - QStringLiteral("MPa"), - QStringLiteral(""), - QStringLiteral("desc3")); + QStringLiteral( + "3 Dimensional array showing stress and strain as a function of " + "temperature" + ) + ); // Description + model3DProp1 = Materials::ModelProperty( + QStringLiteral("Temperature"), + QStringLiteral("T"), + QStringLiteral("Quantity"), + QStringLiteral("C"), + QStringLiteral(""), + QStringLiteral("desc1") + ); + model3DProp2 = Materials::ModelProperty( + QStringLiteral("Stress"), + QStringLiteral("Stress"), + QStringLiteral("Quantity"), + QStringLiteral("MPa"), + QStringLiteral(""), + QStringLiteral("desc2") + ); + model3DProp3 = Materials::ModelProperty( + QStringLiteral("Strain"), + QStringLiteral("Strain"), + QStringLiteral("Quantity"), + QStringLiteral("MPa"), + QStringLiteral(""), + QStringLiteral("desc3") + ); model3DProp.addColumn(model3DProp1); model3DProp.addColumn(model3DProp2); diff --git a/tests/src/Mod/Material/App/TestMaterials.cpp b/tests/src/Mod/Material/App/TestMaterials.cpp index f29b6b1c6b..272e11812b 100644 --- a/tests/src/Mod/Material/App/TestMaterials.cpp +++ b/tests/src/Mod/Material/App/TestMaterials.cpp @@ -39,7 +39,7 @@ #include #ifdef _MSC_VER -#pragma warning(disable : 4834) +# pragma warning(disable : 4834) #endif // clang-format off diff --git a/tests/src/Mod/Mesh/App/Core/KDTree.cpp b/tests/src/Mod/Mesh/App/Core/KDTree.cpp index 69651f6cc5..6a404899c3 100644 --- a/tests/src/Mod/Mesh/App/Core/KDTree.cpp +++ b/tests/src/Mod/Mesh/App/Core/KDTree.cpp @@ -67,8 +67,10 @@ TEST_F(KDTreeTest, TestKDTreeNearestMaxDist) Base::Vector3f nor; float dist; - EXPECT_EQ(tree.FindNearest(Base::Vector3f(0.9F, 0.1F, 0.1F), 0.0F, nor, dist), - MeshCore::POINT_INDEX_MAX); + EXPECT_EQ( + tree.FindNearest(Base::Vector3f(0.9F, 0.1F, 0.1F), 0.0F, nor, dist), + MeshCore::POINT_INDEX_MAX + ); } TEST_F(KDTreeTest, TestKDTreeFindExact) diff --git a/tests/src/Mod/Part/App/Attacher.cpp b/tests/src/Mod/Part/App/Attacher.cpp index facb6d1a0d..00aff1be51 100644 --- a/tests/src/Mod/Part/App/Attacher.cpp +++ b/tests/src/Mod/Part/App/Attacher.cpp @@ -324,35 +324,43 @@ TEST_F(AttacherTest, TestAllModesBoundaries) _boxes[1]->MapMode.setValue(mmInertialCS); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mm1FaceNormal); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mmOZX); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mmOZY); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mmOXY); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mmOXZ); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mmOYZ); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); _boxes[1]->MapMode.setValue(mmOYX); _boxes[1]->recomputeFeature(); EXPECT_TRUE( - boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5))); + boxesMatch(_boxes[1]->Shape.getBoundingBox(), Base::BoundBox3d(0.5, 1, 1.5, 3.5, 2, 3.5)) + ); } diff --git a/tests/src/Mod/Part/App/FeatureChamfer.cpp b/tests/src/Mod/Part/App/FeatureChamfer.cpp index 1bf53df0d9..867e0a1ee2 100644 --- a/tests/src/Mod/Part/App/FeatureChamfer.cpp +++ b/tests/src/Mod/Part/App/FeatureChamfer.cpp @@ -22,9 +22,11 @@ protected: _boxes[0]->Width.setValue(width); _boxes[0]->Height.setValue(height); _boxes[0]->Placement.setValue( - Base::Placement(Base::Vector3d(), Base::Rotation(), Base::Vector3d())); + Base::Placement(Base::Vector3d(), Base::Rotation(), Base::Vector3d()) + ); _boxes[1]->Placement.setValue( - Base::Placement(Base::Vector3d(0, 1, height), Base::Rotation(), Base::Vector3d())); + Base::Placement(Base::Vector3d(0, 1, height), Base::Rotation(), Base::Vector3d()) + ); _boxes[1]->Length.setValue(1); _boxes[1]->Width.setValue(2); _boxes[1]->Height.setValue(3); @@ -55,8 +57,8 @@ protected: TEST_F(FeatureChamferTest, testOther) { - const double baseVolume = - _boxes[0]->Length.getValue() * _boxes[0]->Width.getValue() * _boxes[0]->Height.getValue() + const double baseVolume = _boxes[0]->Length.getValue() * _boxes[0]->Width.getValue() + * _boxes[0]->Height.getValue() + _boxes[1]->Length.getValue() * _boxes[1]->Width.getValue() * _boxes[1]->Height.getValue(); // Arrange _chamfer->Base.setValue(_fused); @@ -93,11 +95,14 @@ TEST_F(FeatureChamferTest, testMost) _fused->Refine.setValue(true); _fused->execute(); _chamfer->Base.setValue(_fused); - _chamfer->Edges.setValues(PartTestHelpers::_getFilletEdges( - {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // NOLINT magic number - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, // NOLINT magic number - 0.4, // NOLINT magic number - 0.4)); // NOLINT magic number + _chamfer->Edges.setValues( + PartTestHelpers::_getFilletEdges( + {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // NOLINT magic number + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, // NOLINT magic number + 0.4, // NOLINT magic number + 0.4 + ) + ); // NOLINT magic number // Act _chamfer->execute(); double chamferVolume = PartTestHelpers::getVolume(_chamfer->Shape.getValue()); diff --git a/tests/src/Mod/Part/App/FeatureExtrusion.cpp b/tests/src/Mod/Part/App/FeatureExtrusion.cpp index 493721ecad..32445a347d 100644 --- a/tests/src/Mod/Part/App/FeatureExtrusion.cpp +++ b/tests/src/Mod/Part/App/FeatureExtrusion.cpp @@ -165,8 +165,7 @@ TEST_F(FeatureExtrusionTest, testExecuteSymmetric) Base::BoundBox3d bb = ts.getBoundBox(); // Assert EXPECT_FLOAT_EQ(volume, len * wid * ext1); - EXPECT_TRUE( - PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0, 0, -ext1 / 2, len, wid, ext1 / 2))); + EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0, 0, -ext1 / 2, len, wid, ext1 / 2))); } TEST_F(FeatureExtrusionTest, testExecuteAngled) @@ -182,8 +181,7 @@ TEST_F(FeatureExtrusionTest, testExecuteAngled) const double centerWidth = longerSide - shorterSide; // Width of the triang prism. const double topHeight = shorterSide / tangent / 2; // Height of the truncation const double fullHeight = ext1 + topHeight; - const double fullPrismVol = - fullHeight * (shorterSide + ext1 * tangent * 2.0) / 2.0 * centerWidth; + const double fullPrismVol = fullHeight * (shorterSide + ext1 * tangent * 2.0) / 2.0 * centerWidth; const double fullPyrVol = pow(shorterSide + ext1 * tangent * 2.0, 2.0) / 3.0 * fullHeight; const double topPrismVol = topHeight * shorterSide / 2.0 * centerWidth; const double topPyrVol = pow(shorterSide, 2.0) / 3.0 * topHeight; @@ -197,13 +195,12 @@ TEST_F(FeatureExtrusionTest, testExecuteAngled) Base::BoundBox3d bb = ts.getBoundBox(); // Assert EXPECT_FLOAT_EQ(volume, targetVol); - EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, - Base::BoundBox3d(-ext1 * tangent, - -ext1 * tangent, - 0, - len + ext1 * tangent, - wid + ext1 * tangent, - ext1))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch( + bb, + Base::BoundBox3d(-ext1 * tangent, -ext1 * tangent, 0, len + ext1 * tangent, wid + ext1 * tangent, ext1) + ) + ); } TEST_F(FeatureExtrusionTest, testExecuteAngledRev) @@ -219,13 +216,13 @@ TEST_F(FeatureExtrusionTest, testExecuteAngledRev) const double centerWidth = longerSide - shorterSide; // Width of the triang prism. const double topHeight = shorterSide / tangent / 2; // Height of the truncation const double fullHeight = ext1 / 2 + topHeight; - const double fullPrismVol = - fullHeight * (shorterSide + ext1 / 2 * tangent * 2.0) / 2.0 * centerWidth; + const double fullPrismVol = fullHeight * (shorterSide + ext1 / 2 * tangent * 2.0) / 2.0 + * centerWidth; const double fullPyrVol = pow(shorterSide + ext1 / 2 * tangent * 2.0, 2.0) / 3.0 * fullHeight; const double topPrismVol = topHeight * shorterSide / 2.0 * centerWidth; const double topPyrVol = pow(shorterSide, 2.0) / 3.0 * topHeight; - const double targetVol = - (fullPyrVol + fullPrismVol) - (topPyrVol + topPrismVol) + len * wid * ext1 / 2; + const double targetVol = (fullPyrVol + fullPrismVol) - (topPyrVol + topPrismVol) + + len * wid * ext1 / 2; _extrusion->Solid.setValue(true); _extrusion->Symmetric.setValue(true); @@ -237,13 +234,19 @@ TEST_F(FeatureExtrusionTest, testExecuteAngledRev) Base::BoundBox3d bb = ts.getBoundBox(); // Assert EXPECT_FLOAT_EQ(volume, targetVol); - EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, - Base::BoundBox3d(-ext1 * tangent / 2, - -ext1 * tangent / 2, - -ext1 / 2, - len + ext1 * tangent / 2, - wid + ext1 * tangent / 2, - ext1 / 2))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch( + bb, + Base::BoundBox3d( + -ext1 * tangent / 2, + -ext1 * tangent / 2, + -ext1 / 2, + len + ext1 * tangent / 2, + wid + ext1 * tangent / 2, + ext1 / 2 + ) + ) + ); } TEST_F(FeatureExtrusionTest, testExecuteEdge) @@ -263,9 +266,12 @@ TEST_F(FeatureExtrusionTest, testExecuteEdge) Base::BoundBox3d bb = ts.getBoundBox(); // Assert EXPECT_FLOAT_EQ(volume, len * wid * ext1 * tangent); - EXPECT_TRUE(PartTestHelpers::boxesMatch( - bb, - Base::BoundBox3d(0, 0, 0, len + ext1 * tangent, wid + ext1 * tangent, ext1 * tangent))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch( + bb, + Base::BoundBox3d(0, 0, 0, len + ext1 * tangent, wid + ext1 * tangent, ext1 * tangent) + ) + ); } TEST_F(FeatureExtrusionTest, testExecuteDir) @@ -281,9 +287,9 @@ TEST_F(FeatureExtrusionTest, testExecuteDir) Base::BoundBox3d bb = ts.getBoundBox(); // Assert EXPECT_FLOAT_EQ(volume, len * wid * ext1 * sin45); - EXPECT_TRUE(PartTestHelpers::boxesMatch( - bb, - Base::BoundBox3d(0, 0, 0, len, wid + ext1 * sin45, ext1 * sin45))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0, 0, 0, len, wid + ext1 * sin45, ext1 * sin45)) + ); } TEST_F(FeatureExtrusionTest, testExecuteFaceMaker) @@ -322,8 +328,6 @@ TEST_F(FeatureExtrusionTest, testFaceWithHoles) // Assert EXPECT_FLOAT_EQ(volume, len * wid * ext1 - radius * radius * std::numbers::pi * ext1); EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0, 0, 0, len, wid, ext1))); - EXPECT_FLOAT_EQ(PartTestHelpers::getArea(face1), - len * wid + radius * radius * std::numbers::pi); - EXPECT_FLOAT_EQ(PartTestHelpers::getArea(face2), - len * wid - radius * radius * std::numbers::pi); + EXPECT_FLOAT_EQ(PartTestHelpers::getArea(face1), len * wid + radius * radius * std::numbers::pi); + EXPECT_FLOAT_EQ(PartTestHelpers::getArea(face2), len * wid - radius * radius * std::numbers::pi); } diff --git a/tests/src/Mod/Part/App/FeatureFillet.cpp b/tests/src/Mod/Part/App/FeatureFillet.cpp index 0cffb75b50..1b8d71280d 100644 --- a/tests/src/Mod/Part/App/FeatureFillet.cpp +++ b/tests/src/Mod/Part/App/FeatureFillet.cpp @@ -22,9 +22,11 @@ protected: _boxes[0]->Width.setValue(5); _boxes[0]->Height.setValue(6); _boxes[0]->Placement.setValue( - Base::Placement(Base::Vector3d(), Base::Rotation(), Base::Vector3d())); + Base::Placement(Base::Vector3d(), Base::Rotation(), Base::Vector3d()) + ); _boxes[1]->Placement.setValue( - Base::Placement(Base::Vector3d(0, 1, 6), Base::Rotation(), Base::Vector3d())); + Base::Placement(Base::Vector3d(0, 1, 6), Base::Rotation(), Base::Vector3d()) + ); _boxes[1]->Length.setValue(1); _boxes[1]->Width.setValue(2); _boxes[1]->Height.setValue(3); @@ -49,8 +51,8 @@ protected: TEST_F(FeatureFilletTest, testOtherEdges) { - const double baseVolume = - _boxes[0]->Length.getValue() * _boxes[0]->Width.getValue() * _boxes[0]->Height.getValue() + const double baseVolume = _boxes[0]->Length.getValue() * _boxes[0]->Width.getValue() + * _boxes[0]->Height.getValue() + _boxes[1]->Length.getValue() * _boxes[1]->Width.getValue() * _boxes[1]->Height.getValue(); // Arrange _fillet->Base.setValue(_fused); @@ -86,10 +88,13 @@ TEST_F(FeatureFilletTest, testMostEdges) _fused->Refine.setValue(true); // _fused->execute(); _fillet->Base.setValue(_fused); - _fillet->Edges.setValues(PartTestHelpers::_getFilletEdges( - {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 19, 20, 22, 23, 24}, - 0.4, - 0.4)); + _fillet->Edges.setValues( + PartTestHelpers::_getFilletEdges( + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 19, 20, 22, 23, 24}, + 0.4, + 0.4 + ) + ); // Act _fillet->execute(); double filletVolume = PartTestHelpers::getVolume(_fillet->Shape.getValue()); diff --git a/tests/src/Mod/Part/App/FeatureMirroring.cpp b/tests/src/Mod/Part/App/FeatureMirroring.cpp index 18e8d767d4..7c40e1fb06 100644 --- a/tests/src/Mod/Part/App/FeatureMirroring.cpp +++ b/tests/src/Mod/Part/App/FeatureMirroring.cpp @@ -54,7 +54,8 @@ TEST_F(FeatureMirroringTest, testXMirror) "Vertex1;:M;MIR;:H70c:7,V", "Vertex2;:M;MIR;:H70c:7,V", "Vertex3;:M;MIR;:H70c:7,V", "Vertex4;:M;MIR;:H70c:7,V", "Vertex5;:M;MIR;:H70c:7,V", "Vertex6;:M;MIR;:H70c:7,V", "Vertex7;:M;MIR;:H70c:7,V", "Vertex8;:M;MIR;:H70c:7,V", - })); + } + )); } TEST_F(FeatureMirroringTest, testYMirrorWithExistingElementMap) @@ -77,67 +78,69 @@ TEST_F(FeatureMirroringTest, testYMirrorWithExistingElementMap) // Mirrored it around X from 0,0,0 -> 1,2,3 to 0,0,-3 -> 1,2,0 EXPECT_TRUE(boxesMatch(bb, Base::BoundBox3d(0, 0, -3, 1, 3, 0))); // Assert correct element Map - EXPECT_TRUE(elementsMatch(_mirror->Shape.getShape(), - { - "Edge10;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge10;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge11;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge11;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge12;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge12;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge1;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge1;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge2;:M2(Edge2;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", - "Edge2;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", - "Edge2;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", - "Edge3;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge3;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge4;:M2(Edge4;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", - "Edge4;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", - "Edge4;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", - "Edge5;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge5;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge6;:M2(Edge6;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", - "Edge6;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", - "Edge6;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", - "Edge7;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge7;:H11c4,E;:M;MIR;:H11ca:7,E", - "Edge8;:M2(Edge8;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", - "Edge8;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", - "Edge8;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", - "Edge9;:H11c3,E;:M;MIR;:H11ca:7,E", - "Edge9;:H11c4,E;:M;MIR;:H11ca:7,E", - "Face1;:M2(Face1;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", - "Face1;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", - "Face1;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", - "Face2;:M2(Face2;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", - "Face2;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", - "Face2;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", - "Face3;:H11c3,F;:M;MIR;:H11ca:7,F", - "Face4;:H11c4,F;:M;MIR;:H11ca:7,F", - "Face5;:M2(Face5;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", - "Face5;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", - "Face5;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", - "Face6;:M2(Face6;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", - "Face6;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", - "Face6;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", - "Vertex1;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex1;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex2;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex2;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex3;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex3;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex4;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex4;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex5;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex5;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex6;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex6;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex7;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex7;:H11c4,V;:M;MIR;:H11ca:7,V", - "Vertex8;:H11c3,V;:M;MIR;:H11ca:7,V", - "Vertex8;:H11c4,V;:M;MIR;:H11ca:7,V", - })); + EXPECT_TRUE(elementsMatch( + _mirror->Shape.getShape(), + { + "Edge10;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge10;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge11;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge11;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge12;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge12;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge1;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge1;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge2;:M2(Edge2;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", + "Edge2;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", + "Edge2;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", + "Edge3;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge3;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge4;:M2(Edge4;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", + "Edge4;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", + "Edge4;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", + "Edge5;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge5;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge6;:M2(Edge6;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", + "Edge6;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", + "Edge6;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", + "Edge7;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge7;:H11c4,E;:M;MIR;:H11ca:7,E", + "Edge8;:M2(Edge8;:H11c4,E);FUS;:H11c3:18,E;:M;MIR;:H11ca:7,E", + "Edge8;:M2;FUS;:H11c4:8,E;:M;MIR;:H11ca:7,E", + "Edge8;:M;FUS;:H11c3:7,E;:M;MIR;:H11ca:7,E", + "Edge9;:H11c3,E;:M;MIR;:H11ca:7,E", + "Edge9;:H11c4,E;:M;MIR;:H11ca:7,E", + "Face1;:M2(Face1;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", + "Face1;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", + "Face1;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", + "Face2;:M2(Face2;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", + "Face2;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", + "Face2;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", + "Face3;:H11c3,F;:M;MIR;:H11ca:7,F", + "Face4;:H11c4,F;:M;MIR;:H11ca:7,F", + "Face5;:M2(Face5;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", + "Face5;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", + "Face5;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", + "Face6;:M2(Face6;:H11c4,F);FUS;:H11c3:18,F;:M;MIR;:H11ca:7,F", + "Face6;:M2;FUS;:H11c4:8,F;:M;MIR;:H11ca:7,F", + "Face6;:M;FUS;:H11c3:7,F;:M;MIR;:H11ca:7,F", + "Vertex1;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex1;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex2;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex2;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex3;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex3;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex4;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex4;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex5;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex5;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex6;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex6;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex7;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex7;:H11c4,V;:M;MIR;:H11ca:7,V", + "Vertex8;:H11c3,V;:M;MIR;:H11ca:7,V", + "Vertex8;:H11c4,V;:M;MIR;:H11ca:7,V", + } + )); } // NOLINTEND(readability-magic-numbers,cppcoreguidelines-avoid-magic-numbers) diff --git a/tests/src/Mod/Part/App/FeaturePartCommon.cpp b/tests/src/Mod/Part/App/FeaturePartCommon.cpp index 0e2cc3a639..d4fa3622a6 100644 --- a/tests/src/Mod/Part/App/FeaturePartCommon.cpp +++ b/tests/src/Mod/Part/App/FeaturePartCommon.cpp @@ -164,18 +164,22 @@ TEST_F(FeaturePartCommonTest, testHistory) // Manually create the histories classically generated by FreeCAD for comparison using MapList = std::map>; using List = std::vector; - MapList compare1 = {{0, List {0}}, - {1, List {5}}, // NOLINT magic number - {2, List()}, - {3, List {2}}, - {4, List {3}}, - {5, List {1}}}; // NOLINT magic number - MapList compare2 = {{0, List {0}}, - {1, List {5}}, // NOLINT magic number - {2, List {4}}, - {3, List()}, - {4, List {3}}, - {5, List {1}}}; // NOLINT magic number + MapList compare1 = { + {0, List {0}}, + {1, List {5}}, // NOLINT magic number + {2, List()}, + {3, List {2}}, + {4, List {3}}, + {5, List {1}} + }; // NOLINT magic number + MapList compare2 = { + {0, List {0}}, + {1, List {5}}, // NOLINT magic number + {2, List {4}}, + {3, List()}, + {4, List {3}}, + {5, List {1}} + }; // NOLINT magic number // Act and Assert no histories yet std::vector hist = _common->History.getValues(); @@ -185,8 +189,10 @@ TEST_F(FeaturePartCommonTest, testHistory) _common->execute(); hist = _common->History.getValues(); // Assert - ASSERT_EQ(hist.size(), - 0); // TODO: with TNP enabled, this becomes 0, matches the code. Correct? + ASSERT_EQ( + hist.size(), + 0 + ); // TODO: with TNP enabled, this becomes 0, matches the code. Correct? } TEST_F(FeaturePartCommonTest, testMapping) diff --git a/tests/src/Mod/Part/App/FeaturePartFuse.cpp b/tests/src/Mod/Part/App/FeaturePartFuse.cpp index 2b914ab78d..1f8c48d389 100644 --- a/tests/src/Mod/Part/App/FeaturePartFuse.cpp +++ b/tests/src/Mod/Part/App/FeaturePartFuse.cpp @@ -244,8 +244,8 @@ TEST_F(FeaturePartFuseTest, testRefine) // Act _fuse->execute(); Part::TopoShape ts = _fuse->Shape.getValue(); - std::vector subs = - ts.getSubTopoShapes(TopAbs_FACE); // TopAbs_WIRE alternate approach + std::vector subs = ts.getSubTopoShapes(TopAbs_FACE); // TopAbs_WIRE alternate + // approach // Assert two boxes, plus redundant faces at the joint. EXPECT_EQ(subs.size(), 14); // 14 Faces diff --git a/tests/src/Mod/Part/App/FeatureRevolution.cpp b/tests/src/Mod/Part/App/FeatureRevolution.cpp index 90247e11b3..27e3a38b11 100644 --- a/tests/src/Mod/Part/App/FeatureRevolution.cpp +++ b/tests/src/Mod/Part/App/FeatureRevolution.cpp @@ -107,9 +107,9 @@ TEST_F(FeatureRevolutionTest, testAxisLink) // Assert double puckVolume = 0; // Someday make this test use a more interesting edge angle EXPECT_FLOAT_EQ(volume, puckVolume); - EXPECT_TRUE(PartTestHelpers::boxesMatch( - bb, - Base::BoundBox3d(-ext1 / 2, -ext1 / 2, 0, ext1 / 2, ext1 / 2, 0))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-ext1 / 2, -ext1 / 2, 0, ext1 / 2, ext1 / 2, 0)) + ); } TEST_F(FeatureRevolutionTest, testSymmetric) diff --git a/tests/src/Mod/Part/App/FuzzyBoolean.cpp b/tests/src/Mod/Part/App/FuzzyBoolean.cpp index 262bf28bdf..a96eac4aba 100644 --- a/tests/src/Mod/Part/App/FuzzyBoolean.cpp +++ b/tests/src/Mod/Part/App/FuzzyBoolean.cpp @@ -59,10 +59,12 @@ TEST_F(FuzzyBooleanTest, testDefaultFuzzy) _fuse->execute(); // Verify - EXPECT_NEAR(PartTestHelpers::getVolume(_fuse->Shape.getValue()), - PartTestHelpers::getVolume(_helix1->Shape.getValue()) - + PartTestHelpers::getVolume(_cylinder1->Shape.getValue()), - 0.1); + EXPECT_NEAR( + PartTestHelpers::getVolume(_fuse->Shape.getValue()), + PartTestHelpers::getVolume(_helix1->Shape.getValue()) + + PartTestHelpers::getVolume(_cylinder1->Shape.getValue()), + 0.1 + ); // Analyse Part::TopoShape ts = _fuse->Shape.getValue(); @@ -88,10 +90,12 @@ TEST_F(FuzzyBooleanTest, testGoodFuzzy) Part::FuzzyHelper::setBooleanFuzzy(oldFuzzy); // Verify - EXPECT_NEAR(PartTestHelpers::getVolume(_fuse->Shape.getValue()), - PartTestHelpers::getVolume(_helix1->Shape.getValue()) - + PartTestHelpers::getVolume(_cylinder1->Shape.getValue()), - 0.1); + EXPECT_NEAR( + PartTestHelpers::getVolume(_fuse->Shape.getValue()), + PartTestHelpers::getVolume(_helix1->Shape.getValue()) + + PartTestHelpers::getVolume(_cylinder1->Shape.getValue()), + 0.1 + ); // Analyse Part::TopoShape ts = _fuse->Shape.getValue(); diff --git a/tests/src/Mod/Part/App/Geometry.cpp b/tests/src/Mod/Part/App/Geometry.cpp index 025bced432..c4fd1ab133 100644 --- a/tests/src/Mod/Part/App/Geometry.cpp +++ b/tests/src/Mod/Part/App/Geometry.cpp @@ -44,33 +44,29 @@ TEST_F(GeometryTest, testTrimBSpline) std::vector weights(5, 1.0); std::vector knotsNonPeriodic = {0.0, 1.0, 2.0}; std::vector multiplicitiesNonPeriodic = {degree + 1, 1, degree + 1}; - Part::GeomBSplineCurve nonPeriodicBSpline1(poles, - weights, - knotsNonPeriodic, - multiplicitiesNonPeriodic, - degree, - false); - Part::GeomBSplineCurve nonPeriodicBSpline2(poles, - weights, - knotsNonPeriodic, - multiplicitiesNonPeriodic, - degree, - false); + Part::GeomBSplineCurve nonPeriodicBSpline1( + poles, + weights, + knotsNonPeriodic, + multiplicitiesNonPeriodic, + degree, + false + ); + Part::GeomBSplineCurve nonPeriodicBSpline2( + poles, + weights, + knotsNonPeriodic, + multiplicitiesNonPeriodic, + degree, + false + ); std::vector knotsPeriodic = {0.0, 0.3, 1.0, 1.5, 1.8, 2.0}; double period = knotsPeriodic.back() - knotsPeriodic.front(); std::vector multiplicitiesPeriodic(6, 1); - Part::GeomBSplineCurve periodicBSpline1(poles, - weights, - knotsPeriodic, - multiplicitiesPeriodic, - degree, - true); - Part::GeomBSplineCurve periodicBSpline2(poles, - weights, - knotsPeriodic, - multiplicitiesPeriodic, - degree, - true); + Part::GeomBSplineCurve + periodicBSpline1(poles, weights, knotsPeriodic, multiplicitiesPeriodic, degree, true); + Part::GeomBSplineCurve + periodicBSpline2(poles, weights, knotsPeriodic, multiplicitiesPeriodic, degree, true); // NOTE: These should be within the knot range, with param1 < param2 double param1 = 0.5, param2 = 1.4; // TODO: Decide what to do if params are outside the range diff --git a/tests/src/Mod/Part/App/PartFeature.cpp b/tests/src/Mod/Part/App/PartFeature.cpp index 200e08869e..d15e69c01b 100644 --- a/tests/src/Mod/Part/App/PartFeature.cpp +++ b/tests/src/Mod/Part/App/PartFeature.cpp @@ -153,14 +153,18 @@ TEST_F(FeaturePartTest, getRelatedElements) auto label2 = _boxes[1]->Label.getValue(); const TopoShape& ts = _common->Shape.getShape(); boost::ignore_unused(ts); - auto result = Feature::getRelatedElements(_doc->getObject(label1), - "Edge2", - HistoryTraceType::followTypeChange, - true); - auto result2 = Feature::getRelatedElements(_doc->getObject(label2), - "Edge1", - HistoryTraceType::followTypeChange, - true); + auto result = Feature::getRelatedElements( + _doc->getObject(label1), + "Edge2", + HistoryTraceType::followTypeChange, + true + ); + auto result2 = Feature::getRelatedElements( + _doc->getObject(label2), + "Edge1", + HistoryTraceType::followTypeChange, + true + ); // Assert EXPECT_EQ(result.size(), 1); // Found the one. EXPECT_EQ(result2.size(), 0); // No element map, so no related elements @@ -185,11 +189,13 @@ TEST_F(FeaturePartTest, getElementFromSource) boost::ignore_unused(label1); boost::ignore_unused(label2); boost::ignore_unused(ts); - auto element = Feature::getElementFromSource(_common, - "Part__Box001", // "Edge1", - _boxes[0], - "Face1", // "Edge1", - false); + auto element = Feature::getElementFromSource( + _common, + "Part__Box001", // "Edge1", + _boxes[0], + "Face1", // "Edge1", + false + ); // Assert EXPECT_EQ(element.size(), 0); } diff --git a/tests/src/Mod/Part/App/PartTestHelpers.cpp b/tests/src/Mod/Part/App/PartTestHelpers.cpp index 392240f4fb..a0febc0ca7 100644 --- a/tests/src/Mod/Part/App/PartTestHelpers.cpp +++ b/tests/src/Mod/Part/App/PartTestHelpers.cpp @@ -41,7 +41,8 @@ void PartTestHelperClass::createTestDoc() Base::Vector3d(0, 2, 0), // Touch the first box Base::Vector3d(0, 2 + Base::Precision::Confusion(), 0), // Just Outside of touching // For the Just Inside Of Touching case, go enough that we exceed precision rounding - Base::Vector3d(0, 2 - minimalDistance, 0)}; + Base::Vector3d(0, 2 - minimalDistance, 0) + }; for (unsigned i = 0; i < _boxes.size(); i++) { auto box = _boxes[i] = _doc->addObject(); // NOLINT @@ -49,12 +50,16 @@ void PartTestHelperClass::createTestDoc() box->Width.setValue(2); box->Height.setValue(3); box->Placement.setValue( - Base::Placement(box_origins[i], Base::Rotation(), Base::Vector3d())); // NOLINT + Base::Placement(box_origins[i], Base::Rotation(), Base::Vector3d()) + ); // NOLINT } } -std::vector -_getFilletEdges(const std::vector& edges, double startRadius, double endRadius) +std::vector _getFilletEdges( + const std::vector& edges, + double startRadius, + double endRadius +) { std::vector filletElements; for (auto edge : edges) { @@ -90,8 +95,10 @@ void rectangle(double height, double width, const char* name) ExecutePython(rectstring); } -std::tuple -CreateRectFace(float len, float wid) +std::tuple CreateRectFace( + float len, + float wid +) { auto edge1 = BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(len, 0.0, 0.0)).Edge(); auto edge2 = BRepBuilderAPI_MakeEdge(gp_Pnt(len, 0.0, 0.0), gp_Pnt(len, wid, 0.0)).Edge(); @@ -102,12 +109,10 @@ CreateRectFace(float len, float wid) return {face1, wire1, edge1, edge2, edge3, edge4}; } -std::tuple -CreateFaceWithRoundHole(float len, float wid, float radius) +std::tuple CreateFaceWithRoundHole(float len, float wid, float radius) { auto [face1, wire1, edge1, edge2, edge3, edge4] = CreateRectFace(len, wid); - auto circ1 = - GC_MakeCircle(gp_Pnt(len / 2.0, wid / 2.0, 0), gp_Dir(0.0, 0.0, 1.0), radius).Value(); + auto circ1 = GC_MakeCircle(gp_Pnt(len / 2.0, wid / 2.0, 0), gp_Dir(0.0, 0.0, 1.0), radius).Value(); auto edge5 = BRepBuilderAPI_MakeEdge(circ1).Edge(); auto wire2 = BRepBuilderAPI_MakeWire(edge5).Wire(); auto face2 = BRepBuilderAPI_MakeFace(face1, wire2).Face(); @@ -116,8 +121,7 @@ CreateFaceWithRoundHole(float len, float wid, float radius) return {face2, wire1, wire2}; } -testing::AssertionResult -boxesMatch(const Base::BoundBox3d& b1, const Base::BoundBox3d& b2, double prec) +testing::AssertionResult boxesMatch(const Base::BoundBox3d& b1, const Base::BoundBox3d& b2, double prec) { if (abs(b1.MinX - b2.MinX) < prec && abs(b1.MinY - b2.MinY) < prec && abs(b1.MinZ - b2.MinZ) < prec && abs(b1.MaxX - b2.MaxX) < prec @@ -167,29 +171,31 @@ bool matchStringsWithoutClause(std::string first, std::string second, const std: * @param names The vector of names * @return An assertion usable by the gtest framework */ -testing::AssertionResult elementsMatch(const TopoShape& shape, - const std::vector& names) +testing::AssertionResult elementsMatch(const TopoShape& shape, const std::vector& names) { auto elements = shape.getElementMap(); if (!elements.empty() || !names.empty()) { for (const auto& name : names) { - if (std::find_if(elements.begin(), - elements.end(), - [&, name](const Data::MappedElement& element) { - return matchStringsWithoutClause( - element.name.toString(), - name, - "(;D|;:H|;K)-?[a-fA-F0-9]+(:[0-9]+)?|(\\(.*?\\))?"); - // ;D ;:H and ;K are the sections of an encoded name for - // Duplicate, Tag and a Face name in slices. All three of these - // can vary from run to run or platform to platform, as they are - // based on either explicit random numbers or memory addresses. - // Thus we remove the value from comparisons and just check that - // they exist. The full form could be something like ;:He59:53 - // which is what we match and remove. We also pull out any - // subexpressions wrapped in parens to keep the parse from - // becoming too complex. - }) + if (std::find_if( + elements.begin(), + elements.end(), + [&, name](const Data::MappedElement& element) { + return matchStringsWithoutClause( + element.name.toString(), + name, + "(;D|;:H|;K)-?[a-fA-F0-9]+(:[0-9]+)?|(\\(.*?\\))?" + ); + // ;D ;:H and ;K are the sections of an encoded name for + // Duplicate, Tag and a Face name in slices. All three of these + // can vary from run to run or platform to platform, as they are + // based on either explicit random numbers or memory addresses. + // Thus we remove the value from comparisons and just check that + // they exist. The full form could be something like ;:He59:53 + // which is what we match and remove. We also pull out any + // subexpressions wrapped in parens to keep the parse from + // becoming too complex. + } + ) == elements.end()) { return testing::AssertionFailure() << mappedElementVectorToString(elements); } @@ -198,14 +204,12 @@ testing::AssertionResult elementsMatch(const TopoShape& shape, return testing::AssertionSuccess(); } -testing::AssertionResult allElementsMatch(const TopoShape& shape, - const std::vector& names) +testing::AssertionResult allElementsMatch(const TopoShape& shape, const std::vector& names) { auto elements = shape.getElementMap(); if (elements.size() != names.size()) { - return testing::AssertionFailure() - << elements.size() << " != " << names.size() - << " elements: " << mappedElementVectorToString(elements); + return testing::AssertionFailure() << elements.size() << " != " << names.size() + << " elements: " << mappedElementVectorToString(elements); } return elementsMatch(shape, names); } diff --git a/tests/src/Mod/Part/App/PartTestHelpers.h b/tests/src/Mod/Part/App/PartTestHelpers.h index 9a6589ed6f..47d3b116ea 100644 --- a/tests/src/Mod/Part/App/PartTestHelpers.h +++ b/tests/src/Mod/Part/App/PartTestHelpers.h @@ -31,8 +31,11 @@ double getArea(const TopoDS_Shape& shape); double getLength(const TopoDS_Shape& shape); -std::vector -_getFilletEdges(const std::vector& edges, double startRadius, double endRadius); +std::vector _getFilletEdges( + const std::vector& edges, + double startRadius, + double endRadius +); class PartTestHelperClass { @@ -49,14 +52,22 @@ void executePython(const std::vector& python); void rectangle(double height, double width, const char* name); -std::tuple -CreateRectFace(float len = 2.0, float wid = 3.0); +std::tuple CreateRectFace( + float len = 2.0, + float wid = 3.0 +); -std::tuple -CreateFaceWithRoundHole(float len = 2.0, float wid = 3.0, float radius = 1.0); +std::tuple CreateFaceWithRoundHole( + float len = 2.0, + float wid = 3.0, + float radius = 1.0 +); -testing::AssertionResult -boxesMatch(const Base::BoundBox3d& b1, const Base::BoundBox3d& b2, double prec = 1e-05); // NOLINT +testing::AssertionResult boxesMatch( + const Base::BoundBox3d& b1, + const Base::BoundBox3d& b2, + double prec = 1e-05 +); // NOLINT std::map elementMap(const TopoShape& shape); @@ -66,8 +77,7 @@ std::map elementMap(const TopoShape& shape); * @param names The Names * @return A test result, suitable for display by the gtest framework */ -testing::AssertionResult elementsMatch(const TopoShape& shape, - const std::vector& names); +testing::AssertionResult elementsMatch(const TopoShape& shape, const std::vector& names); /** * Checks that all the names occur in the shape's element map and that there are no additional names @@ -75,8 +85,7 @@ testing::AssertionResult elementsMatch(const TopoShape& shape, * @param names The Names * @return A test result, suitable for display by the gtest framework */ -testing::AssertionResult allElementsMatch(const TopoShape& shape, - const std::vector& names); +testing::AssertionResult allElementsMatch(const TopoShape& shape, const std::vector& names); /** * diff --git a/tests/src/Mod/Part/App/PropertyTopoShape.cpp b/tests/src/Mod/Part/App/PropertyTopoShape.cpp index be33e28c1d..a7a86291b3 100644 --- a/tests/src/Mod/Part/App/PropertyTopoShape.cpp +++ b/tests/src/Mod/Part/App/PropertyTopoShape.cpp @@ -160,8 +160,8 @@ TEST_F(PropertyTopoShapeTest, testPropertyPartShapeGetPyObject) partShape.setValue(topoDsShapeIn2); auto pyObj2 = partShape.getPyObject(); // Assert the shape is no longer a compound - EXPECT_FALSE( - PyObject_TypeCheck(pyObj2, &TopoShapeCompoundPy::Type)); // _boxes[3] is not a compound. + EXPECT_FALSE(PyObject_TypeCheck(pyObj2, &TopoShapeCompoundPy::Type)); // _boxes[3] is not a + // compound. Py_XDECREF(pyObj2); // Act partShape.setPyObject(pyObj); diff --git a/tests/src/Mod/Part/App/TopoShapeCache.cpp b/tests/src/Mod/Part/App/TopoShapeCache.cpp index e886cc785c..a43fdfb37b 100644 --- a/tests/src/Mod/Part/App/TopoShapeCache.cpp +++ b/tests/src/Mod/Part/App/TopoShapeCache.cpp @@ -90,8 +90,7 @@ TEST_F(TopoShapeCacheTest, InsertRelationIntoEmptyTableCompacts) { // Arrange Data::IndexedName indexedName {"EDGE1"}; - auto mappedName = - Data::MappedName::fromRawData("#94;:G0;XTR;:H19:8,F;:H1a,F;BND:-1:0;:H1b:10,F"); + auto mappedName = Data::MappedName::fromRawData("#94;:G0;XTR;:H19:8,F;:H1a,F;BND:-1:0;:H1b:10,F"); ASSERT_TRUE(mappedName.isRaw()); Data::MappedElement mappedElement1 {indexedName, mappedName}; QVector vectorOfElements {mappedElement1}; diff --git a/tests/src/Mod/Part/App/TopoShapeExpansion.cpp b/tests/src/Mod/Part/App/TopoShapeExpansion.cpp index ba6046852f..66a5fd70c5 100644 --- a/tests/src/Mod/Part/App/TopoShapeExpansion.cpp +++ b/tests/src/Mod/Part/App/TopoShapeExpansion.cpp @@ -72,9 +72,7 @@ TEST_F(TopoShapeExpansionTest, makeElementCompoundOneShapeReturnsShape) std::vector shapes {topoShape}; // Act - topoShape.makeElementCompound(shapes, - "C", - TopoShape::SingleShapeCompoundCreationPolicy::returnShape); + topoShape.makeElementCompound(shapes, "C", TopoShape::SingleShapeCompoundCreationPolicy::returnShape); // Assert EXPECT_EQ(edge.ShapeType(), topoShape.getShape().ShapeType()); // NOT a Compound @@ -88,9 +86,11 @@ TEST_F(TopoShapeExpansionTest, makeElementCompoundOneShapeForceReturnsCompound) std::vector shapes {topoShape}; // Act - topoShape.makeElementCompound(shapes, - "C", - TopoShape::SingleShapeCompoundCreationPolicy::forceCompound); + topoShape.makeElementCompound( + shapes, + "C", + TopoShape::SingleShapeCompoundCreationPolicy::forceCompound + ); // Assert EXPECT_NE(edge.ShapeType(), topoShape.getShape().ShapeType()); // No longer the same thing @@ -161,10 +161,11 @@ TEST_F(TopoShapeExpansionTest, makeElementCompoundTwoCubes) auto elementMap = cube1TS.getElementMap(); Base::BoundBox3d bb = topoShape.getBoundBox(); // Assert shape is correct - EXPECT_EQ(22, - topoShape.getMappedChildElements() - .size()); // Changed with PR#12471. Probably will change again after importing - // other TopoNaming logics + EXPECT_EQ( + 22, + topoShape.getMappedChildElements().size() + ); // Changed with PR#12471. Probably will change again after importing + // other TopoNaming logics EXPECT_FLOAT_EQ(getVolume(topoShape.getShape()), 2); EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0, 0, 0, 2, 1, 1))); // Assert map is correct @@ -195,8 +196,9 @@ TEST_F(TopoShapeExpansionTest, makeElementCompoundTwoCubes) "Edge4;:H3,E;:H7:6,E", "Face1;:H1,F;:H7:6,F", "Face1;:H2,F;:H7:6,F", "Face1;:H3,F;:H7:6,F", "Face1;:H4,F;:H7:6,F", "Face1;:H5,F;:H7:6,F", "Face1;:H6,F;:H7:6,F", - })); // Changed with PR#12471. Probably will change again after importing - // other TopoNaming logics + } + )); // Changed with PR#12471. Probably will change again after importing + // other TopoNaming logics } TEST_F(TopoShapeExpansionTest, MapperMakerModified) @@ -217,7 +219,8 @@ TEST_F(TopoShapeExpansionTest, MapperMakerModified) auto wireMkr {BRepBuilderAPI_MakeWire( BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0)), BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 0.0, 0.0), gp_Pnt(1.0, 1.0, 0.0)), - BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 1.0, 0.0), gp_Pnt(0.0, 0.0, 0.0)))}; + BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 1.0, 0.0), gp_Pnt(0.0, 0.0, 0.0)) + )}; auto wire = wireMkr.Wire(); // Creating a Face using the Wire created before @@ -248,8 +251,10 @@ TEST_F(TopoShapeExpansionTest, MapperMakerModified) // Check the result of the operations EXPECT_EQ(transformMprMkr.modified(wire).size(), 1); // The Transformation acts on the Wire... - EXPECT_EQ(transformMprMkr.modified(face).size(), - 1); // ... and therefore on the created Face... + EXPECT_EQ( + transformMprMkr.modified(face).size(), + 1 + ); // ... and therefore on the created Face... EXPECT_EQ(transformMprMkr.modified(edge).size(), 1); // ... and on the Edge added to the Face EXPECT_EQ(splitMprMkr.modified(edge).size(), 0); // The Split doesn't modify the Edge @@ -287,12 +292,16 @@ TEST_F(TopoShapeExpansionTest, MapperMakerGenerated) // Check the result of the operations EXPECT_EQ(fuse1MprMkr.generated(edge1).size(), 1); // fuse1 has a new vertex generated by edge1 EXPECT_EQ(fuse1MprMkr.generated(edge2).size(), 1); // fuse1 has a new vertex generated by edge2 - EXPECT_EQ(fuse1MprMkr.generated(edge3).size(), - 0); // fuse1 doesn't have a new vertex generated by edge3 + EXPECT_EQ( + fuse1MprMkr.generated(edge3).size(), + 0 + ); // fuse1 doesn't have a new vertex generated by edge3 EXPECT_EQ(fuse2MprMkr.generated(edge1).size(), 1); // fuse2 has a new vertex generated by edge1 - EXPECT_EQ(fuse2MprMkr.generated(edge2).size(), - 0); // fuse2 doesn't have a new vertex generated by edge2 + EXPECT_EQ( + fuse2MprMkr.generated(edge2).size(), + 0 + ); // fuse2 doesn't have a new vertex generated by edge2 EXPECT_EQ(fuse2MprMkr.generated(edge3).size(), 1); // fuse2 has a new vertex generated by edge3 } @@ -386,12 +395,16 @@ TEST_F(TopoShapeExpansionTest, MapperHistoryGenerated) // Check the result of the operations EXPECT_EQ(fuse1MprHst.generated(edge1).size(), 1); // fuse1 has a new vertex generated by edge1 EXPECT_EQ(fuse1MprHst.generated(edge2).size(), 1); // fuse1 has a new vertex generated by edge2 - EXPECT_EQ(fuse1MprHst.generated(edge3).size(), - 0); // fuse1 doesn't have a new vertex generated by edge3 + EXPECT_EQ( + fuse1MprHst.generated(edge3).size(), + 0 + ); // fuse1 doesn't have a new vertex generated by edge3 EXPECT_EQ(fuse2MprHst.generated(edge1).size(), 1); // fuse2 has a new vertex generated by edge1 - EXPECT_EQ(fuse2MprHst.generated(edge2).size(), - 0); // fuse2 doesn't have a new vertex generated by edge2 + EXPECT_EQ( + fuse2MprHst.generated(edge2).size(), + 0 + ); // fuse2 doesn't have a new vertex generated by edge2 EXPECT_EQ(fuse2MprHst.generated(edge3).size(), 1); // fuse2 has a new vertex generated by edge3 } @@ -402,39 +415,37 @@ TEST_F(TopoShapeExpansionTest, resetElementMapTest) // A TopoShape without a map auto shapeWithoutMap { - TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(-1.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0)).Edge(), - 1)}; + TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(-1.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0)).Edge(), 1) + }; // A TopoShape without a map that will be replaced by another map auto shapeWithoutMapAfterReset {TopoShape(shapeWithoutMap)}; // A TopoShape with a map auto shapeWithMap { - TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, -1.0, 0.0), gp_Pnt(0.0, 1.0, 0.0)).Edge(), - 3)}; - shapeWithMap.makeShapeWithElementMap(shapeWithMap.getShape(), - TopoShape::Mapper(), - {shapeWithMap}); + TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, -1.0, 0.0), gp_Pnt(0.0, 1.0, 0.0)).Edge(), 3) + }; + shapeWithMap.makeShapeWithElementMap(shapeWithMap.getShape(), TopoShape::Mapper(), {shapeWithMap}); // A TopoShape with a map that will be replaced by another map auto shapeWithMapAfterReset {TopoShape(shapeWithMap)}; - shapeWithMapAfterReset.makeShapeWithElementMap(shapeWithMapAfterReset.getShape(), - TopoShape::Mapper(), - {shapeWithMapAfterReset}); + shapeWithMapAfterReset.makeShapeWithElementMap( + shapeWithMapAfterReset.getShape(), + TopoShape::Mapper(), + {shapeWithMapAfterReset} + ); // A TopoShape with a map that will be replaced by an empty map auto shapeWithMapAfterEmptyReset {TopoShape(shapeWithMap)}; - shapeWithMapAfterEmptyReset.makeShapeWithElementMap(shapeWithMapAfterEmptyReset.getShape(), - TopoShape::Mapper(), - {shapeWithMapAfterEmptyReset}); + shapeWithMapAfterEmptyReset.makeShapeWithElementMap( + shapeWithMapAfterEmptyReset.getShape(), + TopoShape::Mapper(), + {shapeWithMapAfterEmptyReset} + ); // A new map auto newElementMapPtr {std::make_shared()}; - newElementMapPtr->setElementName(IndexedName("Edge", 2), - MappedName("Edge2;:H,E"), - 3, - nullptr, - true); + newElementMapPtr->setElementName(IndexedName("Edge", 2), MappedName("Edge2;:H,E"), 3, nullptr, true); // Act shapeWithoutMapAfterReset.resetElementMap(newElementMapPtr); @@ -465,19 +476,23 @@ TEST_F(TopoShapeExpansionTest, flushElementMapTest) // A TopoShape with a map that won't be flushed auto shapeWithMapNotFlushed { - TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(-1.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0)).Edge(), - 1)}; - shapeWithMapNotFlushed.makeShapeWithElementMap(shapeWithMapNotFlushed.getShape(), - TopoShape::Mapper(), - {shapeWithMapNotFlushed}); + TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(-1.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0)).Edge(), 1) + }; + shapeWithMapNotFlushed.makeShapeWithElementMap( + shapeWithMapNotFlushed.getShape(), + TopoShape::Mapper(), + {shapeWithMapNotFlushed} + ); // A TopoShape with a map that will be reset and then flushed auto shapeWithMapFlushed { - TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, -1.0, 0.0), gp_Pnt(0.0, 1.0, 0.0)).Edge(), - 2)}; - shapeWithMapFlushed.makeShapeWithElementMap(shapeWithMapFlushed.getShape(), - TopoShape::Mapper(), - {shapeWithMapFlushed}); + TopoShape(BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, -1.0, 0.0), gp_Pnt(0.0, 1.0, 0.0)).Edge(), 2) + }; + shapeWithMapFlushed.makeShapeWithElementMap( + shapeWithMapFlushed.getShape(), + TopoShape::Mapper(), + {shapeWithMapFlushed} + ); // A child TopoShape that will be flushed auto childshapeWithMapFlushed {shapeWithMapFlushed.getSubTopoShape(TopAbs_VERTEX, 1)}; @@ -485,11 +500,7 @@ TEST_F(TopoShapeExpansionTest, flushElementMapTest) // A new map auto newElementMapPtr {std::make_shared()}; - newElementMapPtr->setElementName(IndexedName("Edge", 2), - MappedName("Edge2;:H,E"), - 3, - nullptr, - true); + newElementMapPtr->setElementName(IndexedName("Edge", 2), MappedName("Edge2;:H,E"), 3, nullptr, true); // Setting a different element map and then resetting otherwise flush won't have effect shapeWithMapFlushed.resetElementMap(newElementMapPtr); @@ -532,9 +543,7 @@ TEST_F(TopoShapeExpansionTest, cacheRelatedElements) topoShape.cacheRelatedElements(keyName2, HistoryTraceType::stopOnTypeChange, names2); topoShape.getRelatedElementsCached(keyName, traceType, returnedNames); topoShape.getRelatedElementsCached(keyName, HistoryTraceType::stopOnTypeChange, returnedNames3); - topoShape.getRelatedElementsCached(keyName2, - HistoryTraceType::stopOnTypeChange, - returnedNames2); + topoShape.getRelatedElementsCached(keyName2, HistoryTraceType::stopOnTypeChange, returnedNames2); // Assert EXPECT_EQ(returnedNames.size(), 3); EXPECT_STREQ(returnedNames[0].name.toString().c_str(), "Test1"); @@ -578,20 +587,22 @@ TEST_F(TopoShapeExpansionTest, makeElementWiresCombinesWires) EXPECT_NEAR(getLength(topoShape.getShape()), 4.4142137, 1e-6); EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0, 0, 0, 3, 2, 0))); // Assert map is correct - EXPECT_TRUE(allElementsMatch(topoShape, - { - "Edge1;WIR;:H1:4,E;WIR;:H1:4,E", - "Edge1;WIR;:H2:4,E;WIR;:H2:4,E", - "Edge1;WIR;:H4:4,E;D1;:H4:3,E;WIR;:H4:4,E", - "Edge1;WIR;:H4:4,E;WIR;:H4:4,E", - "Vertex1;WIR;:H1:4,V;WIR;:H1:4,V", - "Vertex1;WIR;:H4:4,V;WIR;:H4:4,V", - "Vertex2;WIR;:H1:4,V;WIR;:H1:4,V", - "Vertex2;WIR;:H2:4,V;WIR;:H2:4,V", - "Vertex2;WIR;:H4:4,V;D1;:H4:3,V;WIR;:H4:4,V", - "Vertex2;WIR;:H4:4,V;WIR;:H4:4,V", - })); // Changed with PR#12471. Probably will change again after - // importing other TopoNaming logics + EXPECT_TRUE(allElementsMatch( + topoShape, + { + "Edge1;WIR;:H1:4,E;WIR;:H1:4,E", + "Edge1;WIR;:H2:4,E;WIR;:H2:4,E", + "Edge1;WIR;:H4:4,E;D1;:H4:3,E;WIR;:H4:4,E", + "Edge1;WIR;:H4:4,E;WIR;:H4:4,E", + "Vertex1;WIR;:H1:4,V;WIR;:H1:4,V", + "Vertex1;WIR;:H4:4,V;WIR;:H4:4,V", + "Vertex2;WIR;:H1:4,V;WIR;:H1:4,V", + "Vertex2;WIR;:H2:4,V;WIR;:H2:4,V", + "Vertex2;WIR;:H4:4,V;D1;:H4:3,V;WIR;:H4:4,V", + "Vertex2;WIR;:H4:4,V;WIR;:H4:4,V", + } + )); // Changed with PR#12471. Probably will change again after + // importing other TopoNaming logics } TEST_F(TopoShapeExpansionTest, makeElementFaceNull) @@ -765,8 +776,8 @@ TEST_F(TopoShapeExpansionTest, setElementComboNameSimple) // isn't nullptr to eliminate the segfault. Data::MappedName edgeName("testname"); // Act - Data::MappedName result = - topoShape.setElementComboName(Data::IndexedName::fromConst("Edge", 1), {edgeName}); + Data::MappedName result + = topoShape.setElementComboName(Data::IndexedName::fromConst("Edge", 1), {edgeName}); // Assert EXPECT_STREQ(result.toString().c_str(), "testname;"); } @@ -777,18 +788,17 @@ TEST_F(TopoShapeExpansionTest, setElementComboName) // Arrange TopoShape topoShape {2L}; topoShape.setElementMap({}); - Data::MappedName edgeName = - topoShape.getMappedName(Data::IndexedName::fromConst("Edge", 1), true); - Data::MappedName faceName = - topoShape.getMappedName(Data::IndexedName::fromConst("Face", 7), true); - Data::MappedName faceName2 = - topoShape.getMappedName(Data::IndexedName::fromConst("Face", 8), true); + Data::MappedName edgeName = topoShape.getMappedName(Data::IndexedName::fromConst("Edge", 1), true); + Data::MappedName faceName = topoShape.getMappedName(Data::IndexedName::fromConst("Face", 7), true); + Data::MappedName faceName2 = topoShape.getMappedName(Data::IndexedName::fromConst("Face", 8), true); const char* op = "Copy"; // Act - Data::MappedName result = topoShape.setElementComboName(Data::IndexedName::fromConst("Edge", 1), - {edgeName, faceName, faceName2}, - OpCodes::Common, - op); + Data::MappedName result = topoShape.setElementComboName( + Data::IndexedName::fromConst("Edge", 1), + {edgeName, faceName, faceName2}, + OpCodes::Common, + op + ); // Assert EXPECT_STREQ(result.toString().c_str(), "Edge1;CMN(Face7|Face8);Copy"); // The detailed forms of names are covered in encodeElementName tests @@ -802,23 +812,23 @@ TEST_F(TopoShapeExpansionTest, setElementComboNameCompound) auto wire2 = BRepBuilderAPI_MakeWire({edge1}).Wire(); TopoShape topoShape {2L}; topoShape.makeElementCompound({wire1, wire2}); // Quality of shape doesn't matter - Data::MappedName edgeName = - topoShape.getMappedName(Data::IndexedName::fromConst("Edge", 1), true); - Data::MappedName faceName = - topoShape.getMappedName(Data::IndexedName::fromConst("Face", 7), true); - Data::MappedName faceName2 = - topoShape.getMappedName(Data::IndexedName::fromConst("Face", 8), true); + Data::MappedName edgeName = topoShape.getMappedName(Data::IndexedName::fromConst("Edge", 1), true); + Data::MappedName faceName = topoShape.getMappedName(Data::IndexedName::fromConst("Face", 7), true); + Data::MappedName faceName2 = topoShape.getMappedName(Data::IndexedName::fromConst("Face", 8), true); const char* op = "Copy"; // Act - Data::MappedName result = topoShape.setElementComboName(Data::IndexedName::fromConst("Edge", 1), - {edgeName, faceName, faceName2}, - OpCodes::Common, - op); + Data::MappedName result = topoShape.setElementComboName( + Data::IndexedName::fromConst("Edge", 1), + {edgeName, faceName, faceName2}, + OpCodes::Common, + op + ); // ASSERT EXPECT_STREQ( result.toString().c_str(), - "Edge1;:H,E;CMN(Face7|Face8);Copy"); // Changed with PR#12471. Probably will change again - // after importing other TopoNaming logics + "Edge1;:H,E;CMN(Face7|Face8);Copy" + ); // Changed with PR#12471. Probably will change again + // after importing other TopoNaming logics // The detailed forms of names are covered in encodeElementName tests } @@ -1138,21 +1148,27 @@ TEST_F(TopoShapeExpansionTest, findSubShapesWithSharedVertexEverything) exp.Init(box1, TopAbs_VERTEX); auto vertex = exp.Current(); // Act - auto shapes = box1TS.findSubShapesWithSharedVertex(face, - &names, - Data::SearchOption::CheckGeometry, - tol, - atol); - auto shapes1 = box1TS.findSubShapesWithSharedVertex(edge, - &names1, - Data::SearchOption::CheckGeometry, - tol, - atol); - auto shapes2 = box1TS.findSubShapesWithSharedVertex(vertex, - &names2, - Data::SearchOption::CheckGeometry, - tol, - atol); + auto shapes = box1TS.findSubShapesWithSharedVertex( + face, + &names, + Data::SearchOption::CheckGeometry, + tol, + atol + ); + auto shapes1 = box1TS.findSubShapesWithSharedVertex( + edge, + &names1, + Data::SearchOption::CheckGeometry, + tol, + atol + ); + auto shapes2 = box1TS.findSubShapesWithSharedVertex( + vertex, + &names2, + Data::SearchOption::CheckGeometry, + tol, + atol + ); // Assert EXPECT_EQ(shapes.size(), 6); EXPECT_EQ(names.size(), 6); @@ -1186,21 +1202,27 @@ TEST_F(TopoShapeExpansionTest, findSubShapesWithSharedVertexMid) exp.Init(box1, TopAbs_VERTEX); auto vertex = exp.Current(); // Act - auto shapes = box1TS.findSubShapesWithSharedVertex(face, - &names, - Data::SearchOption::CheckGeometry, - tol, - atol); - auto shapes1 = box1TS.findSubShapesWithSharedVertex(edge, - &names1, - Data::SearchOption::CheckGeometry, - tol, - atol); - auto shapes2 = box1TS.findSubShapesWithSharedVertex(vertex, - &names2, - Data::SearchOption::CheckGeometry, - tol, - atol); + auto shapes = box1TS.findSubShapesWithSharedVertex( + face, + &names, + Data::SearchOption::CheckGeometry, + tol, + atol + ); + auto shapes1 = box1TS.findSubShapesWithSharedVertex( + edge, + &names1, + Data::SearchOption::CheckGeometry, + tol, + atol + ); + auto shapes2 = box1TS.findSubShapesWithSharedVertex( + vertex, + &names2, + Data::SearchOption::CheckGeometry, + tol, + atol + ); // Assert EXPECT_EQ(shapes.size(), 6); EXPECT_EQ(names.size(), 6); @@ -1228,21 +1250,27 @@ TEST_F(TopoShapeExpansionTest, findSubShapesWithSharedVertexClose) exp.Init(box1, TopAbs_VERTEX); auto vertex = exp.Current(); // Act - auto shapes = box1TS.findSubShapesWithSharedVertex(face, - &names, - Data::SearchOption::CheckGeometry, - tol, - atol); - auto shapes1 = box1TS.findSubShapesWithSharedVertex(edge, - &names1, - Data::SearchOption::CheckGeometry, - tol, - atol); - auto shapes2 = box1TS.findSubShapesWithSharedVertex(vertex, - &names2, - Data::SearchOption::CheckGeometry, - tol, - atol); + auto shapes = box1TS.findSubShapesWithSharedVertex( + face, + &names, + Data::SearchOption::CheckGeometry, + tol, + atol + ); + auto shapes1 = box1TS.findSubShapesWithSharedVertex( + edge, + &names1, + Data::SearchOption::CheckGeometry, + tol, + atol + ); + auto shapes2 = box1TS.findSubShapesWithSharedVertex( + vertex, + &names2, + Data::SearchOption::CheckGeometry, + tol, + atol + ); // Assert EXPECT_EQ(shapes.size(), 1); EXPECT_EQ(names.size(), 1); @@ -1375,8 +1403,7 @@ TEST_F(TopoShapeExpansionTest, makeElementBooleanImpossibleCommon) TopoShape topoShape1 {cube1, 1L}; TopoShape topoShape2 {cube2, 2L}; // Act - TopoShape& result = - topoShape1.makeElementBoolean(Part::OpCodes::Common, {topoShape1, topoShape2}); + TopoShape& result = topoShape1.makeElementBoolean(Part::OpCodes::Common, {topoShape1, topoShape2}); auto elements = elementMap(result); // Assert shape is correct EXPECT_FLOAT_EQ(getVolume(result.getShape()), 0); @@ -1394,8 +1421,7 @@ TEST_F(TopoShapeExpansionTest, makeElementBooleanCommon) TopoShape topoShape1 {cube1, 1L}; TopoShape topoShape2 {cube2, 2L}; // Act - TopoShape& result = - topoShape1.makeElementBoolean(Part::OpCodes::Common, {topoShape1, topoShape2}); + TopoShape& result = topoShape1.makeElementBoolean(Part::OpCodes::Common, {topoShape1, topoShape2}); auto elements = elementMap(result); // Assert shape is correct EXPECT_FLOAT_EQ(getVolume(result.getShape()), 0.25); @@ -1422,47 +1448,49 @@ TEST_F(TopoShapeExpansionTest, makeElementBooleanCut) // Assert elementMap is correct EXPECT_EQ(elements.size(), 38); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);CUT;:H1:1a,V", - "Edge10;:M;CUT;:H1:7,E", - "Edge11", - "Edge11;:M;CUT;:H2:7,E", - "Edge12", - "Edge12;:M;CUT;:H2:7,E", - "Edge2", - "Edge2;:M;CUT;:H2:7,E", - "Edge3", - "Edge3;:M;CUT;:H2:7,E", - "Edge4", - "Edge4;:M;CUT;:H2:7,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);CUT;:H1:1b,V", - "Edge6;:M;CUT;:H1:7,E", - "Edge7", - "Edge8;:G(Edge11;K-1;:H2:4,E);CUT;:H1:1b,V", - "Edge8;:M;CUT;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);CUT;:H1:1a,V", - "Edge9;:M;CUT;:H1:7,E", - "Face1", - "Face1;:M;CUT;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);CUT;:H1:1a,E", - "Face2;:M;CUT;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);CUT;:H1:1a,E", - "Face3;:M;CUT;:H1:7,F", - "Face4", - "Face4;:M;CUT;:H2:7,F", - "Face5;:M;CUT;:H1:7,F", - "Face6;:M;CUT;:H1:7,F", - "Vertex1", - "Vertex2", - "Vertex3", - "Vertex3;:M;CUT;:H2:7,V", - "Vertex4", - "Vertex4;:M;CUT;:H2:7,V", - "Vertex7", - "Vertex8", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);CUT;:H1:1a,V", + "Edge10;:M;CUT;:H1:7,E", + "Edge11", + "Edge11;:M;CUT;:H2:7,E", + "Edge12", + "Edge12;:M;CUT;:H2:7,E", + "Edge2", + "Edge2;:M;CUT;:H2:7,E", + "Edge3", + "Edge3;:M;CUT;:H2:7,E", + "Edge4", + "Edge4;:M;CUT;:H2:7,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);CUT;:H1:1b,V", + "Edge6;:M;CUT;:H1:7,E", + "Edge7", + "Edge8;:G(Edge11;K-1;:H2:4,E);CUT;:H1:1b,V", + "Edge8;:M;CUT;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);CUT;:H1:1a,V", + "Edge9;:M;CUT;:H1:7,E", + "Face1", + "Face1;:M;CUT;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);CUT;:H1:1a,E", + "Face2;:M;CUT;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);CUT;:H1:1a,E", + "Face3;:M;CUT;:H1:7,F", + "Face4", + "Face4;:M;CUT;:H2:7,F", + "Face5;:M;CUT;:H1:7,F", + "Face6;:M;CUT;:H1:7,F", + "Vertex1", + "Vertex2", + "Vertex3", + "Vertex3;:M;CUT;:H2:7,V", + "Vertex4", + "Vertex4;:M;CUT;:H2:7,V", + "Vertex7", + "Vertex8", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementBooleanFuse) @@ -1475,83 +1503,84 @@ TEST_F(TopoShapeExpansionTest, makeElementBooleanFuse) TopoShape topoShape1 {cube1, 1L}; TopoShape topoShape2 {cube2, 2L}; // Act - TopoShape& result = - topoShape1.makeElementBoolean(Part::OpCodes::Fuse, {topoShape1, topoShape2}); + TopoShape& result = topoShape1.makeElementBoolean(Part::OpCodes::Fuse, {topoShape1, topoShape2}); auto elements = elementMap(result); // Assert shape is correct EXPECT_FLOAT_EQ(getVolume(result.getShape()), 1.75); // Assert element map is correct EXPECT_EQ(elements.size(), 66); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge10;:H2,E", - "Edge10;:M2;FUS;:H1:8,E", - "Edge10;:M;FUS;:H1:7,E", - "Edge11", - "Edge11;:M2;FUS;:H2:8,E", - "Edge11;:M;FUS;:H2:7,E", - "Edge12", - "Edge12;:M2;FUS;:H2:8,E", - "Edge12;:M;FUS;:H2:7,E", - "Edge1;:H2,E", - "Edge2", - "Edge2;:M2;FUS;:H2:8,E", - "Edge2;:M;FUS;:H2:7,E", - "Edge3", - "Edge4", - "Edge4;:M2;FUS;:H2:8,E", - "Edge4;:M;FUS;:H2:7,E", - "Edge5;:H2,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge6;:H2,E", - "Edge6;:M2;FUS;:H1:8,E", - "Edge6;:M;FUS;:H1:7,E", - "Edge7", - "Edge7;:H2,E", - "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge8;:H2,E", - "Edge8;:M2;FUS;:H1:8,E", - "Edge8;:M;FUS;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge9;:H2,E", - "Edge9;:M2;FUS;:H1:8,E", - "Edge9;:M;FUS;:H1:7,E", - "Face1", - "Face1;:M;FUS;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face2;:H2,F", - "Face2;:M;FUS;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face3;:H2,F", - "Face3;:M;FUS;:H1:7,F", - "Face4", - "Face4;:M;FUS;:H2:7,F", - "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", - "Face5;:M;FUS;:H1:7,F", - "Face5;:M;FUS;:H2:7,F", - "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", - "Face6;:M;FUS;:H1:7,F", - "Face6;:M;FUS;:H2:7,F", - "Vertex1", - "Vertex1;:H2,V", - "Vertex2", - "Vertex2;:H2,V", - "Vertex3", - "Vertex3;:M;FUS;:H2:7,V", - "Vertex4", - "Vertex4;:M;FUS;:H2:7,V", - "Vertex5;:H2,V", - "Vertex5;:M;FUS;:H1:7,V", - "Vertex6;:H2,V", - "Vertex6;:M;FUS;:H1:7,V", - "Vertex7", - "Vertex7;:H2,V", - "Vertex8", - "Vertex8;:H2,V", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge10;:H2,E", + "Edge10;:M2;FUS;:H1:8,E", + "Edge10;:M;FUS;:H1:7,E", + "Edge11", + "Edge11;:M2;FUS;:H2:8,E", + "Edge11;:M;FUS;:H2:7,E", + "Edge12", + "Edge12;:M2;FUS;:H2:8,E", + "Edge12;:M;FUS;:H2:7,E", + "Edge1;:H2,E", + "Edge2", + "Edge2;:M2;FUS;:H2:8,E", + "Edge2;:M;FUS;:H2:7,E", + "Edge3", + "Edge4", + "Edge4;:M2;FUS;:H2:8,E", + "Edge4;:M;FUS;:H2:7,E", + "Edge5;:H2,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge6;:H2,E", + "Edge6;:M2;FUS;:H1:8,E", + "Edge6;:M;FUS;:H1:7,E", + "Edge7", + "Edge7;:H2,E", + "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge8;:H2,E", + "Edge8;:M2;FUS;:H1:8,E", + "Edge8;:M;FUS;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge9;:H2,E", + "Edge9;:M2;FUS;:H1:8,E", + "Edge9;:M;FUS;:H1:7,E", + "Face1", + "Face1;:M;FUS;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face2;:H2,F", + "Face2;:M;FUS;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face3;:H2,F", + "Face3;:M;FUS;:H1:7,F", + "Face4", + "Face4;:M;FUS;:H2:7,F", + "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", + "Face5;:M;FUS;:H1:7,F", + "Face5;:M;FUS;:H2:7,F", + "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", + "Face6;:M;FUS;:H1:7,F", + "Face6;:M;FUS;:H2:7,F", + "Vertex1", + "Vertex1;:H2,V", + "Vertex2", + "Vertex2;:H2,V", + "Vertex3", + "Vertex3;:M;FUS;:H2:7,V", + "Vertex4", + "Vertex4;:M;FUS;:H2:7,V", + "Vertex5;:H2,V", + "Vertex5;:M;FUS;:H1:7,V", + "Vertex6;:H2,V", + "Vertex6;:M;FUS;:H1:7,V", + "Vertex7", + "Vertex7;:H2,V", + "Vertex8", + "Vertex8;:H2,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementDraft) @@ -1562,8 +1591,8 @@ TEST_F(TopoShapeExpansionTest, makeElementDraft) std::vector subShapes = cube1TS.getSubTopoShapes(TopAbs_FACE); std::vector faces {subShapes[0], subShapes[1], subShapes[2], subShapes[3]}; const gp_Dir pullDirection {0, 0, 1}; - double angle {std::numbers::pi * 10 - / 8}; // Angle should be between Pi and Pi * 1.5 ( 180 and 270 degrees ) + double angle {std::numbers::pi * 10 / 8}; // Angle should be between Pi and Pi * 1.5 ( 180 and + // 270 degrees ) const gp_Pln plane {}; // Act TopoShape& result = cube1TS.makeElementDraft(cube1TS, faces, pullDirection, angle, plane); @@ -1580,24 +1609,30 @@ TEST_F(TopoShapeExpansionTest, makeElementDraftTopoShapes) // Arrange auto [cube1TS, cube2TS] = CreateTwoTopoShapeCubes(); const gp_Dir pullDirection {0, 0, 1}; - double angle {std::numbers::pi * 10 - / 8}; // Angle should be between Pi and Pi * 1.5 ( 180 and 270 degrees ) + double angle {std::numbers::pi * 10 / 8}; // Angle should be between Pi and Pi * 1.5 ( 180 and + // 270 degrees ) const gp_Pln plane {}; // Act - TopoShape result3 = cube1TS.makeElementDraft(cube1TS.getSubTopoShapes(TopAbs_FACE), - pullDirection, - angle, - plane); // Non Reference call type - TopoShape result2 = cube1TS.makeElementDraft(cube1TS, - cube1TS.getSubTopoShapes(TopAbs_FACE), - pullDirection, - angle, - plane); // Bad use of Reference call - TopoShape& result = cube1TS.makeElementDraft(cube2TS, - cube2TS.getSubTopoShapes(TopAbs_FACE), - pullDirection, - angle, - plane); // Correct usage + TopoShape result3 = cube1TS.makeElementDraft( + cube1TS.getSubTopoShapes(TopAbs_FACE), + pullDirection, + angle, + plane + ); // Non Reference call type + TopoShape result2 = cube1TS.makeElementDraft( + cube1TS, + cube1TS.getSubTopoShapes(TopAbs_FACE), + pullDirection, + angle, + plane + ); // Bad use of Reference call + TopoShape& result = cube1TS.makeElementDraft( + cube2TS, + cube2TS.getSubTopoShapes(TopAbs_FACE), + pullDirection, + angle, + plane + ); // Correct usage auto elements = elementMap((result)); // Assert EXPECT_TRUE(result.getMappedChildElements().empty()); @@ -1680,7 +1715,8 @@ TEST_F(TopoShapeExpansionTest, makeElementRuledSurfaceEdges) "Vertex2", "Vertex2;:L(Vertex2;D1);RSF", "Vertex2;D1", - })); + } + )); } TEST_F(TopoShapeExpansionTest, makeElementRuledSurfaceWires) @@ -1690,8 +1726,10 @@ TEST_F(TopoShapeExpansionTest, makeElementRuledSurfaceWires) TopoShape cube1TS {cube1, 1L}; std::vector subWires = cube1TS.getSubTopoShapes(TopAbs_WIRE); // Act - auto surface = cube1TS.makeElementRuledSurface({subWires[0], subWires[1]}, - 0); // TODO: orientation as enum? + auto surface = cube1TS.makeElementRuledSurface( + {subWires[0], subWires[1]}, + 0 + ); // TODO: orientation as enum? auto elements = elementMap(surface); // Assert EXPECT_EQ(surface.countSubElements("Wire"), 4); @@ -1741,24 +1779,19 @@ TEST_F(TopoShapeExpansionTest, makeElementLoft) transform.SetTranslation(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(0.0, 0.0, 10.0)); auto wire2 = wire1; // Shallow copy wire2.Move(TopLoc_Location(transform)); - TopoShape wire1ts { - wire1, - 1L}; // One of these shapes should have a tag or else we won't get an Element Map - TopoShape wire2ts { - wire2, - 2L}; // If you change either tag or eliminate one it changes the resulting name. + TopoShape wire1ts {wire1, 1L}; // One of these shapes should have a tag or else we won't get an + // Element Map + TopoShape wire2ts {wire2, 2L}; // If you change either tag or eliminate one it changes the + // resulting name. std::vector shapes = {wire1ts, wire2ts}; // Act - auto& topoShape = - (new TopoShape())->makeElementLoft(shapes, IsSolid::notSolid, IsRuled::notRuled); - auto& topoShape2 = - (new TopoShape())->makeElementLoft(shapes, IsSolid::solid, IsRuled::notRuled); - auto& topoShape3 = - (new TopoShape())->makeElementLoft(shapes, IsSolid::notSolid, IsRuled::ruled); + auto& topoShape = (new TopoShape())->makeElementLoft(shapes, IsSolid::notSolid, IsRuled::notRuled); + auto& topoShape2 = (new TopoShape())->makeElementLoft(shapes, IsSolid::solid, IsRuled::notRuled); + auto& topoShape3 = (new TopoShape())->makeElementLoft(shapes, IsSolid::notSolid, IsRuled::ruled); auto& topoShape4 = (new TopoShape())->makeElementLoft(shapes, IsSolid::solid, IsRuled::ruled); - auto& topoShape5 = - (new TopoShape()) - ->makeElementLoft(shapes, IsSolid::notSolid, IsRuled::notRuled, IsClosed::closed); + auto& topoShape5 + = (new TopoShape()) + ->makeElementLoft(shapes, IsSolid::notSolid, IsRuled::notRuled, IsClosed::closed); auto elements = elementMap((topoShape)); // Assert that we haven't broken the basic Loft functionality EXPECT_EQ(topoShape.countSubElements("Wire"), 4); @@ -1782,7 +1815,8 @@ TEST_F(TopoShapeExpansionTest, makeElementLoft) "Vertex2;:G(Vertex2;K-1;:H2:4,V);LFT;:H1:1c,E", "Vertex2;:H1,V", "Vertex2;:H2,V", "Vertex3;:G(Vertex3;K-1;:H2:4,V);LFT;:H1:1c,E", "Vertex3;:H1,V", "Vertex3;:H2,V", "Vertex4;:G(Vertex4;K-1;:H2:4,V);LFT;:H1:1c,E", "Vertex4;:H1,V", "Vertex4;:H2,V", - })); + } + )); } TEST_F(TopoShapeExpansionTest, makeElementPipeShell) @@ -1860,81 +1894,83 @@ TEST_F(TopoShapeExpansionTest, makeElementGeneralFuse) // Assert elementMap is correct EXPECT_EQ(elements.size(), 72); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);GFS;:H1:1a,V", - "Edge10;:H2,E", - "Edge10;:M2;GFS;:H1:8,E", - "Edge10;:M;GFS;:H1:7,E", - "Edge11", - "Edge11;:M2;GFS;:H2:8,E", - "Edge11;:M;GFS;:H2:7,E", - "Edge12", - "Edge12;:M2;GFS;:H2:8,E", - "Edge12;:M;GFS;:H2:7,E", - "Edge1;:H2,E", - "Edge2", - "Edge2;:M2;GFS;:H2:8,E", - "Edge2;:M;GFS;:H2:7,E", - "Edge3", - "Edge3;:M;GFS;:H2:7,E", - "Edge4", - "Edge4;:M2;GFS;:H2:8,E", - "Edge4;:M;GFS;:H2:7,E", - "Edge5;:H2,E", - "Edge5;:M;GFS;:H1:7,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);GFS;:H1:1b,V", - "Edge6;:H2,E", - "Edge6;:M2;GFS;:H1:8,E", - "Edge6;:M;GFS;:H1:7,E", - "Edge7", - "Edge7;:H2,E", - "Edge8;:G(Edge11;K-1;:H2:4,E);GFS;:H1:1b,V", - "Edge8;:H2,E", - "Edge8;:M2;GFS;:H1:8,E", - "Edge8;:M;GFS;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);GFS;:H1:1a,V", - "Edge9;:H2,E", - "Edge9;:M2;GFS;:H1:8,E", - "Edge9;:M;GFS;:H1:7,E", - "Face1", - "Face1;:M2;GFS;:H2:8,F", - "Face1;:M;GFS;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);GFS;:H1:1a,E", - "Face2;:H2,F", - "Face2;:M2;GFS;:H1:8,F", - "Face2;:M;GFS;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);GFS;:H1:1a,E", - "Face3;:H2,F", - "Face3;:M2;GFS;:H1:8,F", - "Face3;:M;GFS;:H1:7,F", - "Face4", - "Face4;:M2;GFS;:H2:8,F", - "Face4;:M;GFS;:H2:7,F", - "Face5;:M2(Face5;K2;:H2:3,F);GFS;:H1:1a,F", - "Face5;:M;GFS;:H1:7,F", - "Face5;:M;GFS;:H2:7,F", - "Face6;:M2(Face6;K2;:H2:3,F);GFS;:H1:1a,F", - "Face6;:M;GFS;:H1:7,F", - "Face6;:M;GFS;:H2:7,F", - "Vertex1", - "Vertex1;:H2,V", - "Vertex2", - "Vertex2;:H2,V", - "Vertex3", - "Vertex3;:M;GFS;:H2:7,V", - "Vertex4", - "Vertex4;:M;GFS;:H2:7,V", - "Vertex5;:H2,V", - "Vertex5;:M;GFS;:H1:7,V", - "Vertex6;:H2,V", - "Vertex6;:M;GFS;:H1:7,V", - "Vertex7", - "Vertex7;:H2,V", - "Vertex8", - "Vertex8;:H2,V", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);GFS;:H1:1a,V", + "Edge10;:H2,E", + "Edge10;:M2;GFS;:H1:8,E", + "Edge10;:M;GFS;:H1:7,E", + "Edge11", + "Edge11;:M2;GFS;:H2:8,E", + "Edge11;:M;GFS;:H2:7,E", + "Edge12", + "Edge12;:M2;GFS;:H2:8,E", + "Edge12;:M;GFS;:H2:7,E", + "Edge1;:H2,E", + "Edge2", + "Edge2;:M2;GFS;:H2:8,E", + "Edge2;:M;GFS;:H2:7,E", + "Edge3", + "Edge3;:M;GFS;:H2:7,E", + "Edge4", + "Edge4;:M2;GFS;:H2:8,E", + "Edge4;:M;GFS;:H2:7,E", + "Edge5;:H2,E", + "Edge5;:M;GFS;:H1:7,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);GFS;:H1:1b,V", + "Edge6;:H2,E", + "Edge6;:M2;GFS;:H1:8,E", + "Edge6;:M;GFS;:H1:7,E", + "Edge7", + "Edge7;:H2,E", + "Edge8;:G(Edge11;K-1;:H2:4,E);GFS;:H1:1b,V", + "Edge8;:H2,E", + "Edge8;:M2;GFS;:H1:8,E", + "Edge8;:M;GFS;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);GFS;:H1:1a,V", + "Edge9;:H2,E", + "Edge9;:M2;GFS;:H1:8,E", + "Edge9;:M;GFS;:H1:7,E", + "Face1", + "Face1;:M2;GFS;:H2:8,F", + "Face1;:M;GFS;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);GFS;:H1:1a,E", + "Face2;:H2,F", + "Face2;:M2;GFS;:H1:8,F", + "Face2;:M;GFS;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);GFS;:H1:1a,E", + "Face3;:H2,F", + "Face3;:M2;GFS;:H1:8,F", + "Face3;:M;GFS;:H1:7,F", + "Face4", + "Face4;:M2;GFS;:H2:8,F", + "Face4;:M;GFS;:H2:7,F", + "Face5;:M2(Face5;K2;:H2:3,F);GFS;:H1:1a,F", + "Face5;:M;GFS;:H1:7,F", + "Face5;:M;GFS;:H2:7,F", + "Face6;:M2(Face6;K2;:H2:3,F);GFS;:H1:1a,F", + "Face6;:M;GFS;:H1:7,F", + "Face6;:M;GFS;:H2:7,F", + "Vertex1", + "Vertex1;:H2,V", + "Vertex2", + "Vertex2;:H2,V", + "Vertex3", + "Vertex3;:M;GFS;:H2:7,V", + "Vertex4", + "Vertex4;:M;GFS;:H2:7,V", + "Vertex5;:H2,V", + "Vertex5;:M;GFS;:H1:7,V", + "Vertex6;:H2,V", + "Vertex6;:M;GFS;:H1:7,V", + "Vertex7", + "Vertex7;:H2,V", + "Vertex8", + "Vertex8;:H2,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementFuse) @@ -1954,75 +1990,77 @@ TEST_F(TopoShapeExpansionTest, makeElementFuse) // Assert elementMap is correct EXPECT_EQ(elements.size(), 66); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge10;:H2,E", - "Edge10;:M2;FUS;:H1:8,E", - "Edge10;:M;FUS;:H1:7,E", - "Edge11", - "Edge11;:M2;FUS;:H2:8,E", - "Edge11;:M;FUS;:H2:7,E", - "Edge12", - "Edge12;:M2;FUS;:H2:8,E", - "Edge12;:M;FUS;:H2:7,E", - "Edge1;:H2,E", - "Edge2", - "Edge2;:M2;FUS;:H2:8,E", - "Edge2;:M;FUS;:H2:7,E", - "Edge3", - "Edge4", - "Edge4;:M2;FUS;:H2:8,E", - "Edge4;:M;FUS;:H2:7,E", - "Edge5;:H2,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge6;:H2,E", - "Edge6;:M2;FUS;:H1:8,E", - "Edge6;:M;FUS;:H1:7,E", - "Edge7", - "Edge7;:H2,E", - "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge8;:H2,E", - "Edge8;:M2;FUS;:H1:8,E", - "Edge8;:M;FUS;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge9;:H2,E", - "Edge9;:M2;FUS;:H1:8,E", - "Edge9;:M;FUS;:H1:7,E", - "Face1", - "Face1;:M;FUS;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face2;:H2,F", - "Face2;:M;FUS;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face3;:H2,F", - "Face3;:M;FUS;:H1:7,F", - "Face4", - "Face4;:M;FUS;:H2:7,F", - "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", - "Face5;:M;FUS;:H1:7,F", - "Face5;:M;FUS;:H2:7,F", - "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", - "Face6;:M;FUS;:H1:7,F", - "Face6;:M;FUS;:H2:7,F", - "Vertex1", - "Vertex1;:H2,V", - "Vertex2", - "Vertex2;:H2,V", - "Vertex3", - "Vertex3;:M;FUS;:H2:7,V", - "Vertex4", - "Vertex4;:M;FUS;:H2:7,V", - "Vertex5;:H2,V", - "Vertex5;:M;FUS;:H1:7,V", - "Vertex6;:H2,V", - "Vertex6;:M;FUS;:H1:7,V", - "Vertex7", - "Vertex7;:H2,V", - "Vertex8", - "Vertex8;:H2,V", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge10;:H2,E", + "Edge10;:M2;FUS;:H1:8,E", + "Edge10;:M;FUS;:H1:7,E", + "Edge11", + "Edge11;:M2;FUS;:H2:8,E", + "Edge11;:M;FUS;:H2:7,E", + "Edge12", + "Edge12;:M2;FUS;:H2:8,E", + "Edge12;:M;FUS;:H2:7,E", + "Edge1;:H2,E", + "Edge2", + "Edge2;:M2;FUS;:H2:8,E", + "Edge2;:M;FUS;:H2:7,E", + "Edge3", + "Edge4", + "Edge4;:M2;FUS;:H2:8,E", + "Edge4;:M;FUS;:H2:7,E", + "Edge5;:H2,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge6;:H2,E", + "Edge6;:M2;FUS;:H1:8,E", + "Edge6;:M;FUS;:H1:7,E", + "Edge7", + "Edge7;:H2,E", + "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge8;:H2,E", + "Edge8;:M2;FUS;:H1:8,E", + "Edge8;:M;FUS;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge9;:H2,E", + "Edge9;:M2;FUS;:H1:8,E", + "Edge9;:M;FUS;:H1:7,E", + "Face1", + "Face1;:M;FUS;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face2;:H2,F", + "Face2;:M;FUS;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face3;:H2,F", + "Face3;:M;FUS;:H1:7,F", + "Face4", + "Face4;:M;FUS;:H2:7,F", + "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", + "Face5;:M;FUS;:H1:7,F", + "Face5;:M;FUS;:H2:7,F", + "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", + "Face6;:M;FUS;:H1:7,F", + "Face6;:M;FUS;:H2:7,F", + "Vertex1", + "Vertex1;:H2,V", + "Vertex2", + "Vertex2;:H2,V", + "Vertex3", + "Vertex3;:M;FUS;:H2:7,V", + "Vertex4", + "Vertex4;:M;FUS;:H2:7,V", + "Vertex5;:H2,V", + "Vertex5;:M;FUS;:H1:7,V", + "Vertex6;:H2,V", + "Vertex6;:M;FUS;:H1:7,V", + "Vertex7", + "Vertex7;:H2,V", + "Vertex8", + "Vertex8;:H2,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementCut) @@ -2036,54 +2074,57 @@ TEST_F(TopoShapeExpansionTest, makeElementCut) TopoShape topoShape2 {cube2, 2L}; // Act TopoShape& result = topoShape1.makeElementCut( - {topoShape1, topoShape2}); //, const char* op = nullptr, double tol = 0); + {topoShape1, topoShape2} + ); //, const char* op = nullptr, double tol = 0); auto elements = elementMap(result); // Assert shape is correct EXPECT_FLOAT_EQ(getVolume(result.getShape()), 0.75); // Assert elementMap is correct EXPECT_EQ(elements.size(), 38); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);CUT;:H1:1a,V", - "Edge10;:M;CUT;:H1:7,E", - "Edge11", - "Edge11;:M;CUT;:H2:7,E", - "Edge12", - "Edge12;:M;CUT;:H2:7,E", - "Edge2", - "Edge2;:M;CUT;:H2:7,E", - "Edge3", - "Edge3;:M;CUT;:H2:7,E", - "Edge4", - "Edge4;:M;CUT;:H2:7,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);CUT;:H1:1b,V", - "Edge6;:M;CUT;:H1:7,E", - "Edge7", - "Edge8;:G(Edge11;K-1;:H2:4,E);CUT;:H1:1b,V", - "Edge8;:M;CUT;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);CUT;:H1:1a,V", - "Edge9;:M;CUT;:H1:7,E", - "Face1", - "Face1;:M;CUT;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);CUT;:H1:1a,E", - "Face2;:M;CUT;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);CUT;:H1:1a,E", - "Face3;:M;CUT;:H1:7,F", - "Face4", - "Face4;:M;CUT;:H2:7,F", - "Face5;:M;CUT;:H1:7,F", - "Face6;:M;CUT;:H1:7,F", - "Vertex1", - "Vertex2", - "Vertex3", - "Vertex3;:M;CUT;:H2:7,V", - "Vertex4", - "Vertex4;:M;CUT;:H2:7,V", - "Vertex7", - "Vertex8", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);CUT;:H1:1a,V", + "Edge10;:M;CUT;:H1:7,E", + "Edge11", + "Edge11;:M;CUT;:H2:7,E", + "Edge12", + "Edge12;:M;CUT;:H2:7,E", + "Edge2", + "Edge2;:M;CUT;:H2:7,E", + "Edge3", + "Edge3;:M;CUT;:H2:7,E", + "Edge4", + "Edge4;:M;CUT;:H2:7,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);CUT;:H1:1b,V", + "Edge6;:M;CUT;:H1:7,E", + "Edge7", + "Edge8;:G(Edge11;K-1;:H2:4,E);CUT;:H1:1b,V", + "Edge8;:M;CUT;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);CUT;:H1:1a,V", + "Edge9;:M;CUT;:H1:7,E", + "Face1", + "Face1;:M;CUT;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);CUT;:H1:1a,E", + "Face2;:M;CUT;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);CUT;:H1:1a,E", + "Face3;:M;CUT;:H1:7,F", + "Face4", + "Face4;:M;CUT;:H2:7,F", + "Face5;:M;CUT;:H1:7,F", + "Face6;:M;CUT;:H1:7,F", + "Vertex1", + "Vertex2", + "Vertex3", + "Vertex3;:M;CUT;:H2:7,V", + "Vertex4", + "Vertex4;:M;CUT;:H2:7,V", + "Vertex7", + "Vertex8", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementChamfer) @@ -2101,107 +2142,109 @@ TEST_F(TopoShapeExpansionTest, makeElementChamfer) EXPECT_NEAR(getArea(cube1TS.getShape()), 5.640996, 1e-6); // Assert that we're creating a correct element map EXPECT_TRUE(cube1TS.getMappedChildElements().empty()); - EXPECT_TRUE(allElementsMatch(cube1TS, - { - "Edge10;:G;CHF;:H1:7,F", - "Edge10;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge10;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge10;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge10;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge11;:G;CHF;:H1:7,F", - "Edge11;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge11;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge11;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge11;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge12;:G;CHF;:H1:7,F", - "Edge12;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge12;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge12;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge12;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge1;:G;CHF;:H1:7,F", - "Edge1;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge1;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge1;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge1;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge1;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge1;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge1;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge1;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge2;:G;CHF;:H1:7,F", - "Edge2;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge2;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge2;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge2;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge2;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge2;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge2;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge3;:G;CHF;:H1:7,F", - "Edge3;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge3;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge3;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge3;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge3;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge3;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge3;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge4;:G;CHF;:H1:7,F", - "Edge4;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge4;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge4;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge4;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge4;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge4;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge5;:G;CHF;:H1:7,F", - "Edge5;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge5;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge5;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge5;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge5;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge5;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge5;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge5;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge6;:G;CHF;:H1:7,F", - "Edge6;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge6;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge6;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge6;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge6;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge6;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge6;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge7;:G;CHF;:H1:7,F", - "Edge7;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge7;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge7;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge7;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge7;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge7;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge7;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge8;:G;CHF;:H1:7,F", - "Edge8;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge8;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", - "Edge8;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", - "Edge8;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge8;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge8;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Edge9;:G;CHF;:H1:7,F", - "Edge9;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", - "Edge9;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", - "Edge9;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", - "Edge9;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", - "Face1;:M;CHF;:H1:7,F", - "Face2;:M;CHF;:H1:7,F", - "Face3;:M;CHF;:H1:7,F", - "Face4;:M;CHF;:H1:7,F", - "Face5;:M;CHF;:H1:7,F", - "Face6;:M;CHF;:H1:7,F", - "Vertex1;:G;CHF;:H1:7,F", - "Vertex2;:G;CHF;:H1:7,F", - "Vertex3;:G;CHF;:H1:7,F", - "Vertex4;:G;CHF;:H1:7,F", - "Vertex5;:G;CHF;:H1:7,F", - "Vertex6;:G;CHF;:H1:7,F", - "Vertex7;:G;CHF;:H1:7,F", - "Vertex8;:G;CHF;:H1:7,F", - })); + EXPECT_TRUE(allElementsMatch( + cube1TS, + { + "Edge10;:G;CHF;:H1:7,F", + "Edge10;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge10;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge10;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge10;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge11;:G;CHF;:H1:7,F", + "Edge11;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge11;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge11;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge11;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge12;:G;CHF;:H1:7,F", + "Edge12;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge12;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge12;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge12;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge1;:G;CHF;:H1:7,F", + "Edge1;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge1;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge1;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge1;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge1;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge1;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge1;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge1;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge2;:G;CHF;:H1:7,F", + "Edge2;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge2;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge2;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge2;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge2;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge2;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge2;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge3;:G;CHF;:H1:7,F", + "Edge3;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge3;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge3;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge3;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge3;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge3;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge3;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge4;:G;CHF;:H1:7,F", + "Edge4;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge4;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge4;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge4;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge4;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge4;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge5;:G;CHF;:H1:7,F", + "Edge5;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge5;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge5;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge5;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge5;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge5;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge5;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge5;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge6;:G;CHF;:H1:7,F", + "Edge6;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge6;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge6;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge6;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge6;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge6;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge6;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge7;:G;CHF;:H1:7,F", + "Edge7;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge7;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge7;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge7;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge7;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge7;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge7;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge8;:G;CHF;:H1:7,F", + "Edge8;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge8;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U2;CHF;:H1:8,V", + "Edge8;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E;:U;CHF;:H1:7,V", + "Edge8;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge8;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge8;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Edge9;:G;CHF;:H1:7,F", + "Edge9;:G;CHF;:H1:7,F;:U2;CHF;:H1:8,E", + "Edge9;:G;CHF;:H1:7,F;:U3;CHF;:H1:8,E", + "Edge9;:G;CHF;:H1:7,F;:U4;CHF;:H1:8,E", + "Edge9;:G;CHF;:H1:7,F;:U;CHF;:H1:7,E", + "Face1;:M;CHF;:H1:7,F", + "Face2;:M;CHF;:H1:7,F", + "Face3;:M;CHF;:H1:7,F", + "Face4;:M;CHF;:H1:7,F", + "Face5;:M;CHF;:H1:7,F", + "Face6;:M;CHF;:H1:7,F", + "Vertex1;:G;CHF;:H1:7,F", + "Vertex2;:G;CHF;:H1:7,F", + "Vertex3;:G;CHF;:H1:7,F", + "Vertex4;:G;CHF;:H1:7,F", + "Vertex5;:G;CHF;:H1:7,F", + "Vertex6;:G;CHF;:H1:7,F", + "Vertex7;:G;CHF;:H1:7,F", + "Vertex8;:G;CHF;:H1:7,F", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementFillet) @@ -2218,115 +2261,117 @@ TEST_F(TopoShapeExpansionTest, makeElementFillet) EXPECT_NEAR(getArea(cube1TS.getShape()), 5.739646, 1e-6); // Assert that we're creating a correct element map EXPECT_TRUE(cube1TS.getMappedChildElements().empty()); - EXPECT_TRUE(elementsMatch(cube1TS, - { - "Edge10;:G;FLT;:H1:7,F", - "Edge10;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge10;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge10;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge10;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge11;:G;FLT;:H1:7,F", - "Edge11;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge11;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge11;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge11;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge12;:G;FLT;:H1:7,F", - "Edge12;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge12;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge12;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge12;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge1;:G;FLT;:H1:7,F", - "Edge1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge1;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge1;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge1;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge1;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge1;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge2;:G;FLT;:H1:7,F", - "Edge2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge2;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge2;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge2;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge2;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge3;:G;FLT;:H1:7,F", - "Edge3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge3;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge3;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge3;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge3;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge4;:G;FLT;:H1:7,F", - "Edge4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge4;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge4;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge4;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge5;:G;FLT;:H1:7,F", - "Edge5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge5;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge5;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge5;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge5;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge5;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge6;:G;FLT;:H1:7,F", - "Edge6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge6;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge6;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge6;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge6;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge7;:G;FLT;:H1:7,F", - "Edge7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge7;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge7;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge7;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge7;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge8;:G;FLT;:H1:7,F", - "Edge8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", - "Edge8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", - "Edge8;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge8;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge8;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Edge9;:G;FLT;:H1:7,F", - "Edge9;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Edge9;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", - "Edge9;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", - "Edge9;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", - "Face1;:M;FLT;:H1:7,F", - "Face2;:M;FLT;:H1:7,F", - "Face3;:M;FLT;:H1:7,F", - "Face4;:M;FLT;:H1:7,F", - "Face5;:M;FLT;:H1:7,F", - "Face6;:M;FLT;:H1:7,F", - "Vertex1;:G;FLT;:H1:7,F", - "Vertex1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex2;:G;FLT;:H1:7,F", - "Vertex2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex3;:G;FLT;:H1:7,F", - "Vertex3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex4;:G;FLT;:H1:7,F", - "Vertex4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex5;:G;FLT;:H1:7,F", - "Vertex5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex6;:G;FLT;:H1:7,F", - "Vertex6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex7;:G;FLT;:H1:7,F", - "Vertex7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - "Vertex8;:G;FLT;:H1:7,F", - "Vertex8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", - })); + EXPECT_TRUE(elementsMatch( + cube1TS, + { + "Edge10;:G;FLT;:H1:7,F", + "Edge10;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge10;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge10;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge10;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge11;:G;FLT;:H1:7,F", + "Edge11;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge11;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge11;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge11;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge12;:G;FLT;:H1:7,F", + "Edge12;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge12;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge12;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge12;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge1;:G;FLT;:H1:7,F", + "Edge1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge1;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge1;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge1;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge1;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge1;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge2;:G;FLT;:H1:7,F", + "Edge2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge2;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge2;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge2;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge2;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge3;:G;FLT;:H1:7,F", + "Edge3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge3;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge3;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge3;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge3;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge4;:G;FLT;:H1:7,F", + "Edge4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge4;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge4;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge4;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge5;:G;FLT;:H1:7,F", + "Edge5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge5;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge5;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge5;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge5;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge5;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge6;:G;FLT;:H1:7,F", + "Edge6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge6;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge6;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge6;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge6;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge7;:G;FLT;:H1:7,F", + "Edge7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge7;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge7;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge7;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge7;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge8;:G;FLT;:H1:7,F", + "Edge8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U2;FLT;:H1:8,V", + "Edge8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E;:U;FLT;:H1:7,V", + "Edge8;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge8;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge8;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Edge9;:G;FLT;:H1:7,F", + "Edge9;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Edge9;:G;FLT;:H1:7,F;:U3;FLT;:H1:8,E", + "Edge9;:G;FLT;:H1:7,F;:U4;FLT;:H1:8,E", + "Edge9;:G;FLT;:H1:7,F;:U;FLT;:H1:7,E", + "Face1;:M;FLT;:H1:7,F", + "Face2;:M;FLT;:H1:7,F", + "Face3;:M;FLT;:H1:7,F", + "Face4;:M;FLT;:H1:7,F", + "Face5;:M;FLT;:H1:7,F", + "Face6;:M;FLT;:H1:7,F", + "Vertex1;:G;FLT;:H1:7,F", + "Vertex1;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex2;:G;FLT;:H1:7,F", + "Vertex2;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex3;:G;FLT;:H1:7,F", + "Vertex3;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex4;:G;FLT;:H1:7,F", + "Vertex4;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex5;:G;FLT;:H1:7,F", + "Vertex5;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex6;:G;FLT;:H1:7,F", + "Vertex6;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex7;:G;FLT;:H1:7,F", + "Vertex7;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + "Vertex8;:G;FLT;:H1:7,F", + "Vertex8;:G;FLT;:H1:7,F;:U2;FLT;:H1:8,E", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementSlice) @@ -2344,17 +2389,19 @@ TEST_F(TopoShapeExpansionTest, makeElementSlice) EXPECT_EQ(TopAbs_ShapeEnum::TopAbs_WIRE, result.getShape().ShapeType()); // Assert that we're creating a correct element map EXPECT_TRUE(result.getMappedChildElements().empty()); - EXPECT_TRUE(elementsMatch(result, - { - "Face1;:G2;SLC;:H1:8,V;SLC;:H1:4,V", - "Face1;:G3;SLC;:H1:8,V;SLC;:H1:4,V", - "Face1;:G4;SLC;:H1:8,V;SLC;:H1:4,V", - "Face1;:G5;SLC;:H1:8,E;SLC;:H1:4,E", - "Face1;:G6;SLC;:H1:8,E;SLC;:H1:4,E", - "Face1;:G7;SLC;:H1:8,E;SLC;:H1:4,E", - "Face1;:G8;SLC;:H1:8,E;SLC;:H1:4,E", - "Face1;:G;SLC;:H1:7,V;SLC;:H1:4,V", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Face1;:G2;SLC;:H1:8,V;SLC;:H1:4,V", + "Face1;:G3;SLC;:H1:8,V;SLC;:H1:4,V", + "Face1;:G4;SLC;:H1:8,V;SLC;:H1:4,V", + "Face1;:G5;SLC;:H1:8,E;SLC;:H1:4,E", + "Face1;:G6;SLC;:H1:8,E;SLC;:H1:4,E", + "Face1;:G7;SLC;:H1:8,E;SLC;:H1:4,E", + "Face1;:G8;SLC;:H1:8,E;SLC;:H1:4,E", + "Face1;:G;SLC;:H1:7,V;SLC;:H1:4,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementSlices) @@ -2378,36 +2425,38 @@ TEST_F(TopoShapeExpansionTest, makeElementSlices) EXPECT_EQ(TopAbs_ShapeEnum::TopAbs_WIRE, subTopoShapes[2].getShape().ShapeType()); // Assert that we're creating a correct element map EXPECT_TRUE(result.getMappedChildElements().empty()); - EXPECT_TRUE(elementsMatch(result, - { - "Edge10;:G(Face1;K-2;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", - "Edge10;:G(Face1;K-2;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", - "Edge10;:G(Face1;K-2;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", - "Edge11;:G(Face1;K-3;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", - "Edge11;:G(Face1;K-3;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", - "Edge11;:G(Face1;K-3;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", - "Edge12;:G(Face1;K-4;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", - "Edge12;:G(Face1;K-4;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", - "Edge12;:G(Face1;K-4;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", - "Edge9;:G(Face1;K-1;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", - "Edge9;:G(Face1;K-1;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", - "Edge9;:G(Face1;K-1;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", - "Face1;:G5(Face3;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", - "Face1;:G6(Face4;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", - "Face1;:G7(Face5;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", - "Face1;:G8(Face6;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", - "Face3;:G(Face1;K-5;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", - "Face3;:G(Face1;K-5;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", - "Face4;:G(Face1;K-6;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", - "Face4;:G(Face1;K-6;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", - "Face5;:G(Face1;K-7;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", - "Face5;:G(Face1;K-7;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", - "Face6;:G(Face1;K-8;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", - "Face6;:G(Face1;K-8;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", - })); - EXPECT_FALSE( - subTopoShapes[0].getElementMap().empty()); // Changed with PR#12471. Probably will change - // again after importing other TopoNaming logics + EXPECT_TRUE(elementsMatch( + result, + { + "Edge10;:G(Face1;K-2;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", + "Edge10;:G(Face1;K-2;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", + "Edge10;:G(Face1;K-2;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", + "Edge11;:G(Face1;K-3;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", + "Edge11;:G(Face1;K-3;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", + "Edge11;:G(Face1;K-3;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", + "Edge12;:G(Face1;K-4;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", + "Edge12;:G(Face1;K-4;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", + "Edge12;:G(Face1;K-4;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", + "Edge9;:G(Face1;K-1;:H1:4,F);SLC;:H1:1a,V;SLC;:H1:4,V", + "Edge9;:G(Face1;K-1;:H2:4,F);SLC_2;:H1:1c,V;SLC_2;:H1:6,V", + "Edge9;:G(Face1;K-1;:H3:4,F);SLC_3;:H1:1c,V;SLC_3;:H1:6,V", + "Face1;:G5(Face3;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", + "Face1;:G6(Face4;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", + "Face1;:G7(Face5;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", + "Face1;:G8(Face6;K-1;:H1:4,F);SLC;:H1:1b,E;SLC;:H1:4,E", + "Face3;:G(Face1;K-5;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", + "Face3;:G(Face1;K-5;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", + "Face4;:G(Face1;K-6;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", + "Face4;:G(Face1;K-6;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", + "Face5;:G(Face1;K-7;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", + "Face5;:G(Face1;K-7;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", + "Face6;:G(Face1;K-8;:H2:4,F);SLC_2;:H1:1c,E;SLC_2;:H1:6,E", + "Face6;:G(Face1;K-8;:H3:4,F);SLC_3;:H1:1c,E;SLC_3;:H1:6,E", + } + )); + EXPECT_FALSE(subTopoShapes[0].getElementMap().empty()); // Changed with PR#12471. Probably will + // change again after importing other + // TopoNaming logics } TEST_F(TopoShapeExpansionTest, makeElementMirror) @@ -2428,17 +2477,18 @@ TEST_F(TopoShapeExpansionTest, makeElementMirror) EXPECT_EQ(TopAbs_ShapeEnum::TopAbs_SOLID, result.getShape().ShapeType()); // Assert that we're creating a correct element map EXPECT_TRUE(result.getMappedChildElements().empty()); - EXPECT_TRUE( - elementsMatch(result, - {"Edge10;:M;MIR;:H1:7,E", "Edge11;:M;MIR;:H1:7,E", "Edge12;:M;MIR;:H1:7,E", - "Edge1;:M;MIR;:H1:7,E", "Edge2;:M;MIR;:H1:7,E", "Edge3;:M;MIR;:H1:7,E", - "Edge4;:M;MIR;:H1:7,E", "Edge5;:M;MIR;:H1:7,E", "Edge6;:M;MIR;:H1:7,E", - "Edge7;:M;MIR;:H1:7,E", "Edge8;:M;MIR;:H1:7,E", "Edge9;:M;MIR;:H1:7,E", - "Face1;:M;MIR;:H1:7,F", "Face2;:M;MIR;:H1:7,F", "Face3;:M;MIR;:H1:7,F", - "Face4;:M;MIR;:H1:7,F", "Face5;:M;MIR;:H1:7,F", "Face6;:M;MIR;:H1:7,F", - "Vertex1;:M;MIR;:H1:7,V", "Vertex2;:M;MIR;:H1:7,V", "Vertex3;:M;MIR;:H1:7,V", - "Vertex4;:M;MIR;:H1:7,V", "Vertex5;:M;MIR;:H1:7,V", "Vertex6;:M;MIR;:H1:7,V", - "Vertex7;:M;MIR;:H1:7,V", "Vertex8;:M;MIR;:H1:7,V"})); + EXPECT_TRUE(elementsMatch( + result, + {"Edge10;:M;MIR;:H1:7,E", "Edge11;:M;MIR;:H1:7,E", "Edge12;:M;MIR;:H1:7,E", + "Edge1;:M;MIR;:H1:7,E", "Edge2;:M;MIR;:H1:7,E", "Edge3;:M;MIR;:H1:7,E", + "Edge4;:M;MIR;:H1:7,E", "Edge5;:M;MIR;:H1:7,E", "Edge6;:M;MIR;:H1:7,E", + "Edge7;:M;MIR;:H1:7,E", "Edge8;:M;MIR;:H1:7,E", "Edge9;:M;MIR;:H1:7,E", + "Face1;:M;MIR;:H1:7,F", "Face2;:M;MIR;:H1:7,F", "Face3;:M;MIR;:H1:7,F", + "Face4;:M;MIR;:H1:7,F", "Face5;:M;MIR;:H1:7,F", "Face6;:M;MIR;:H1:7,F", + "Vertex1;:M;MIR;:H1:7,V", "Vertex2;:M;MIR;:H1:7,V", "Vertex3;:M;MIR;:H1:7,V", + "Vertex4;:M;MIR;:H1:7,V", "Vertex5;:M;MIR;:H1:7,V", "Vertex6;:M;MIR;:H1:7,V", + "Vertex7;:M;MIR;:H1:7,V", "Vertex8;:M;MIR;:H1:7,V"} + )); } TEST_F(TopoShapeExpansionTest, makeElementTransformWithoutMap) @@ -2479,75 +2529,77 @@ TEST_F(TopoShapeExpansionTest, makeElementTransformWithMap) // Assert elementMap is correct EXPECT_EQ(elements.size(), 66); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge10;:H2,E", - "Edge10;:M2;FUS;:H1:8,E", - "Edge10;:M;FUS;:H1:7,E", - "Edge11", - "Edge11;:M2;FUS;:H2:8,E", - "Edge11;:M;FUS;:H2:7,E", - "Edge12", - "Edge12;:M2;FUS;:H2:8,E", - "Edge12;:M;FUS;:H2:7,E", - "Edge1;:H2,E", - "Edge2", - "Edge2;:M2;FUS;:H2:8,E", - "Edge2;:M;FUS;:H2:7,E", - "Edge3", - "Edge4", - "Edge4;:M2;FUS;:H2:8,E", - "Edge4;:M;FUS;:H2:7,E", - "Edge5;:H2,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge6;:H2,E", - "Edge6;:M2;FUS;:H1:8,E", - "Edge6;:M;FUS;:H1:7,E", - "Edge7", - "Edge7;:H2,E", - "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge8;:H2,E", - "Edge8;:M2;FUS;:H1:8,E", - "Edge8;:M;FUS;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge9;:H2,E", - "Edge9;:M2;FUS;:H1:8,E", - "Edge9;:M;FUS;:H1:7,E", - "Face1", - "Face1;:M;FUS;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face2;:H2,F", - "Face2;:M;FUS;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face3;:H2,F", - "Face3;:M;FUS;:H1:7,F", - "Face4", - "Face4;:M;FUS;:H2:7,F", - "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", - "Face5;:M;FUS;:H1:7,F", - "Face5;:M;FUS;:H2:7,F", - "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", - "Face6;:M;FUS;:H1:7,F", - "Face6;:M;FUS;:H2:7,F", - "Vertex1", - "Vertex1;:H2,V", - "Vertex2", - "Vertex2;:H2,V", - "Vertex3", - "Vertex3;:M;FUS;:H2:7,V", - "Vertex4", - "Vertex4;:M;FUS;:H2:7,V", - "Vertex5;:H2,V", - "Vertex5;:M;FUS;:H1:7,V", - "Vertex6;:H2,V", - "Vertex6;:M;FUS;:H1:7,V", - "Vertex7", - "Vertex7;:H2,V", - "Vertex8", - "Vertex8;:H2,V", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge10;:H2,E", + "Edge10;:M2;FUS;:H1:8,E", + "Edge10;:M;FUS;:H1:7,E", + "Edge11", + "Edge11;:M2;FUS;:H2:8,E", + "Edge11;:M;FUS;:H2:7,E", + "Edge12", + "Edge12;:M2;FUS;:H2:8,E", + "Edge12;:M;FUS;:H2:7,E", + "Edge1;:H2,E", + "Edge2", + "Edge2;:M2;FUS;:H2:8,E", + "Edge2;:M;FUS;:H2:7,E", + "Edge3", + "Edge4", + "Edge4;:M2;FUS;:H2:8,E", + "Edge4;:M;FUS;:H2:7,E", + "Edge5;:H2,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge6;:H2,E", + "Edge6;:M2;FUS;:H1:8,E", + "Edge6;:M;FUS;:H1:7,E", + "Edge7", + "Edge7;:H2,E", + "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge8;:H2,E", + "Edge8;:M2;FUS;:H1:8,E", + "Edge8;:M;FUS;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge9;:H2,E", + "Edge9;:M2;FUS;:H1:8,E", + "Edge9;:M;FUS;:H1:7,E", + "Face1", + "Face1;:M;FUS;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face2;:H2,F", + "Face2;:M;FUS;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face3;:H2,F", + "Face3;:M;FUS;:H1:7,F", + "Face4", + "Face4;:M;FUS;:H2:7,F", + "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", + "Face5;:M;FUS;:H1:7,F", + "Face5;:M;FUS;:H2:7,F", + "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", + "Face6;:M;FUS;:H1:7,F", + "Face6;:M;FUS;:H2:7,F", + "Vertex1", + "Vertex1;:H2,V", + "Vertex2", + "Vertex2;:H2,V", + "Vertex3", + "Vertex3;:M;FUS;:H2:7,V", + "Vertex4", + "Vertex4;:M;FUS;:H2:7,V", + "Vertex5;:H2,V", + "Vertex5;:M;FUS;:H1:7,V", + "Vertex6;:H2,V", + "Vertex6;:M;FUS;:H1:7,V", + "Vertex7", + "Vertex7;:H2,V", + "Vertex8", + "Vertex8;:H2,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementGTransformWithoutMap) @@ -2588,75 +2640,77 @@ TEST_F(TopoShapeExpansionTest, makeElementGTransformWithMap) // Assert elementMap is correct EXPECT_EQ(elements.size(), 66); EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge10;:H2,E", - "Edge10;:M2;FUS;:H1:8,E", - "Edge10;:M;FUS;:H1:7,E", - "Edge11", - "Edge11;:M2;FUS;:H2:8,E", - "Edge11;:M;FUS;:H2:7,E", - "Edge12", - "Edge12;:M2;FUS;:H2:8,E", - "Edge12;:M;FUS;:H2:7,E", - "Edge1;:H2,E", - "Edge2", - "Edge2;:M2;FUS;:H2:8,E", - "Edge2;:M;FUS;:H2:7,E", - "Edge3", - "Edge4", - "Edge4;:M2;FUS;:H2:8,E", - "Edge4;:M;FUS;:H2:7,E", - "Edge5;:H2,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge6;:H2,E", - "Edge6;:M2;FUS;:H1:8,E", - "Edge6;:M;FUS;:H1:7,E", - "Edge7", - "Edge7;:H2,E", - "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", - "Edge8;:H2,E", - "Edge8;:M2;FUS;:H1:8,E", - "Edge8;:M;FUS;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", - "Edge9;:H2,E", - "Edge9;:M2;FUS;:H1:8,E", - "Edge9;:M;FUS;:H1:7,E", - "Face1", - "Face1;:M;FUS;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face2;:H2,F", - "Face2;:M;FUS;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", - "Face3;:H2,F", - "Face3;:M;FUS;:H1:7,F", - "Face4", - "Face4;:M;FUS;:H2:7,F", - "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", - "Face5;:M;FUS;:H1:7,F", - "Face5;:M;FUS;:H2:7,F", - "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", - "Face6;:M;FUS;:H1:7,F", - "Face6;:M;FUS;:H2:7,F", - "Vertex1", - "Vertex1;:H2,V", - "Vertex2", - "Vertex2;:H2,V", - "Vertex3", - "Vertex3;:M;FUS;:H2:7,V", - "Vertex4", - "Vertex4;:M;FUS;:H2:7,V", - "Vertex5;:H2,V", - "Vertex5;:M;FUS;:H1:7,V", - "Vertex6;:H2,V", - "Vertex6;:M;FUS;:H1:7,V", - "Vertex7", - "Vertex7;:H2,V", - "Vertex8", - "Vertex8;:H2,V", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge10;:H2,E", + "Edge10;:M2;FUS;:H1:8,E", + "Edge10;:M;FUS;:H1:7,E", + "Edge11", + "Edge11;:M2;FUS;:H2:8,E", + "Edge11;:M;FUS;:H2:7,E", + "Edge12", + "Edge12;:M2;FUS;:H2:8,E", + "Edge12;:M;FUS;:H2:7,E", + "Edge1;:H2,E", + "Edge2", + "Edge2;:M2;FUS;:H2:8,E", + "Edge2;:M;FUS;:H2:7,E", + "Edge3", + "Edge4", + "Edge4;:M2;FUS;:H2:8,E", + "Edge4;:M;FUS;:H2:7,E", + "Edge5;:H2,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge6;:H2,E", + "Edge6;:M2;FUS;:H1:8,E", + "Edge6;:M;FUS;:H1:7,E", + "Edge7", + "Edge7;:H2,E", + "Edge8;:G(Edge11;K-1;:H2:4,E);FUS;:H1:1b,V", + "Edge8;:H2,E", + "Edge8;:M2;FUS;:H1:8,E", + "Edge8;:M;FUS;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);FUS;:H1:1a,V", + "Edge9;:H2,E", + "Edge9;:M2;FUS;:H1:8,E", + "Edge9;:M;FUS;:H1:7,E", + "Face1", + "Face1;:M;FUS;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face2;:H2,F", + "Face2;:M;FUS;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);FUS;:H1:1a,E", + "Face3;:H2,F", + "Face3;:M;FUS;:H1:7,F", + "Face4", + "Face4;:M;FUS;:H2:7,F", + "Face5;:M2(Face5;K2;:H2:3,F);FUS;:H1:1a,F", + "Face5;:M;FUS;:H1:7,F", + "Face5;:M;FUS;:H2:7,F", + "Face6;:M2(Face6;K2;:H2:3,F);FUS;:H1:1a,F", + "Face6;:M;FUS;:H1:7,F", + "Face6;:M;FUS;:H2:7,F", + "Vertex1", + "Vertex1;:H2,V", + "Vertex2", + "Vertex2;:H2,V", + "Vertex3", + "Vertex3;:M;FUS;:H2:7,V", + "Vertex4", + "Vertex4;:M;FUS;:H2:7,V", + "Vertex5;:H2,V", + "Vertex5;:M;FUS;:H1:7,V", + "Vertex6;:H2,V", + "Vertex6;:M;FUS;:H1:7,V", + "Vertex7", + "Vertex7;:H2,V", + "Vertex8", + "Vertex8;:H2,V", + } + )); } // Not testing _makeElementTransform as it is a thin wrapper that calls the same places as the four @@ -2702,7 +2756,8 @@ TEST_F(TopoShapeExpansionTest, makeElementSolid) "Vertex3;:C1;:H:4,V", "Vertex3;:H,V", "Vertex4;:C1;:H:4,V", "Vertex4;:H,V", "Vertex5;:C1;:H:4,V", "Vertex5;:H,V", "Vertex6;:C1;:H:4,V", "Vertex6;:H,V", "Vertex7;:C1;:H:4,V", "Vertex7;:H,V", "Vertex8;:C1;:H:4,V", "Vertex8;:H,V", - })); + } + )); } TEST_F(TopoShapeExpansionTest, makeElementRevolve) @@ -2719,36 +2774,37 @@ TEST_F(TopoShapeExpansionTest, makeElementRevolve) auto elements = elementMap(result); Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct - EXPECT_TRUE(PartTestHelpers::boxesMatch( - bb, - Base::BoundBox3d(0.0, 0.0, 0.0, 0.85090352453411933, 1.0, 1.0))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0.0, 0.0, 0.0, 0.85090352453411933, 1.0, 1.0)) + ); EXPECT_NEAR(getVolume(result.getShape()), 0.50885141, 1e-6); // Assert elementMap is correct - EXPECT_TRUE( - elementsMatch(result, - { - "Edge1;:G;RVL;:H2:7,F", - "Edge1;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E", - "Edge1;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E;:L(Edge2;:G;RVL;:H2:7,F;:U;RVL;:H2:" - "7,E|Edge3;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E|Edge4;:H2,E);RVL;:H2:5c,F", - "Edge1;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E;:U;RVL;:H2:7,V", - "Edge1;:H2,E", - "Edge2;:G;RVL;:H2:7,F", - "Edge2;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E", - "Edge2;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E;:U;RVL;:H2:7,V", - "Edge2;:H2,E", - "Edge3;:G;RVL;:H2:7,F", - "Edge3;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E", - "Edge3;:H2,E", - "Edge4;:H2,E", - "Face1;:H2,F", - "Vertex1;:G;RVL;:H2:7,E", - "Vertex1;:H2,V", - "Vertex2;:H2,V", - "Vertex3;:G;RVL;:H2:7,E", - "Vertex3;:H2,V", - "Vertex4;:H2,V", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge1;:G;RVL;:H2:7,F", + "Edge1;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E", + "Edge1;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E;:L(Edge2;:G;RVL;:H2:7,F;:U;RVL;:H2:" + "7,E|Edge3;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E|Edge4;:H2,E);RVL;:H2:5c,F", + "Edge1;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E;:U;RVL;:H2:7,V", + "Edge1;:H2,E", + "Edge2;:G;RVL;:H2:7,F", + "Edge2;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E", + "Edge2;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E;:U;RVL;:H2:7,V", + "Edge2;:H2,E", + "Edge3;:G;RVL;:H2:7,F", + "Edge3;:G;RVL;:H2:7,F;:U;RVL;:H2:7,E", + "Edge3;:H2,E", + "Edge4;:H2,E", + "Face1;:H2,F", + "Vertex1;:G;RVL;:H2:7,E", + "Vertex1;:H2,V", + "Vertex2;:H2,V", + "Vertex3;:G;RVL;:H2:7,E", + "Vertex3;:H2,V", + "Vertex4;:H2,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementPrism) @@ -2766,34 +2822,36 @@ TEST_F(TopoShapeExpansionTest, makeElementPrism) EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0.0, 0.0, 0.0, 0.75, 1.0, 1.0))); EXPECT_FLOAT_EQ(getVolume(result.getShape()), 0.75); // Assert elementMap is correct - EXPECT_TRUE(elementsMatch(result, - { - "Edge1;:G;XTR;:H2:7,F", - "Edge1;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", - "Edge1;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U2;XTR;:H2:8,V", - "Edge1;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U;XTR;:H2:7,V", - "Edge1;:H2,E", - "Edge2;:G;XTR;:H2:7,F", - "Edge2;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", - "Edge2;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U;XTR;:H2:7,V", - "Edge2;:H2,E", - "Edge3;:G;XTR;:H2:7,F", - "Edge3;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", - "Edge3;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U2;XTR;:H2:8,V", - "Edge3;:H2,E", - "Edge4;:G;XTR;:H2:7,F", - "Edge4;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", - "Edge4;:H2,E", - "Face1;:H2,F", - "Vertex1;:G;XTR;:H2:7,E", - "Vertex1;:H2,V", - "Vertex2;:G;XTR;:H2:7,E", - "Vertex2;:H2,V", - "Vertex3;:G;XTR;:H2:7,E", - "Vertex3;:H2,V", - "Vertex4;:G;XTR;:H2:7,E", - "Vertex4;:H2,V", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge1;:G;XTR;:H2:7,F", + "Edge1;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", + "Edge1;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U2;XTR;:H2:8,V", + "Edge1;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U;XTR;:H2:7,V", + "Edge1;:H2,E", + "Edge2;:G;XTR;:H2:7,F", + "Edge2;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", + "Edge2;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U;XTR;:H2:7,V", + "Edge2;:H2,E", + "Edge3;:G;XTR;:H2:7,F", + "Edge3;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", + "Edge3;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E;:U2;XTR;:H2:8,V", + "Edge3;:H2,E", + "Edge4;:G;XTR;:H2:7,F", + "Edge4;:G;XTR;:H2:7,F;:U;XTR;:H2:7,E", + "Edge4;:H2,E", + "Face1;:H2,F", + "Vertex1;:G;XTR;:H2:7,E", + "Vertex1;:H2,V", + "Vertex2;:G;XTR;:H2:7,E", + "Vertex2;:H2,V", + "Vertex3;:G;XTR;:H2:7,E", + "Vertex3;:H2,V", + "Vertex4;:G;XTR;:H2:7,E", + "Vertex4;:H2,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementPrismUntil) @@ -2804,11 +2862,13 @@ TEST_F(TopoShapeExpansionTest, makeElementPrismUntil) auto subTopoFaces = cube1TS.getSubTopoShapes(TopAbs_FACE); auto direction = gp_Vec(gp_XYZ(0.0, 0.0, 1)); // Act - TopoShape result = cube1TS.makeElementPrismUntil(subTopoFaces[4], - subTopoFaces[4], - subTopoFaces[5], - direction, - TopoShape::PrismMode::FuseWithBase); + TopoShape result = cube1TS.makeElementPrismUntil( + subTopoFaces[4], + subTopoFaces[4], + subTopoFaces[5], + direction, + TopoShape::PrismMode::FuseWithBase + ); auto elements = elementMap(result); Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct @@ -2837,22 +2897,24 @@ TEST_F(TopoShapeExpansionTest, makeElementFilledFace) EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(0.0, -0.6, -0.6, 0, 1.6, 1.6))); EXPECT_FLOAT_EQ(getArea(result.getShape()), 1); // Assert elementMap is correct - EXPECT_TRUE(elementsMatch(result, - { - "Edge1;:G;FFC;:H2:7,E", - "Edge1;:G;FFC;:H2:7,E;:L(Edge2;:G;FFC;:H2:7,E|Edge3;:G;FFC;:" - "H2:7,E|Edge4;:G;FFC;:H2:7,E);FFC;:H2:47,F", - "Edge2;:G;FFC;:H2:7,E", - "Edge3;:G;FFC;:H2:7,E", - "Edge4;:G;FFC;:H2:7,E", - // TODO: Prove that this difference is not a problem. - // The next elements vary according to platform / OCCT version - // and thus can't be absolutely tested. - // "Vertex1;:G;FFC;:H2:7,V", - // "Vertex2;:G;FFC;:H2:7,V", - // "Vertex3;:G;FFC;:H2:7,V", - // "Vertex4;:G;FFC;:H2:7,V", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge1;:G;FFC;:H2:7,E", + "Edge1;:G;FFC;:H2:7,E;:L(Edge2;:G;FFC;:H2:7,E|Edge3;:G;FFC;:" + "H2:7,E|Edge4;:G;FFC;:H2:7,E);FFC;:H2:47,F", + "Edge2;:G;FFC;:H2:7,E", + "Edge3;:G;FFC;:H2:7,E", + "Edge4;:G;FFC;:H2:7,E", + // TODO: Prove that this difference is not a problem. + // The next elements vary according to platform / OCCT version + // and thus can't be absolutely tested. + // "Vertex1;:G;FFC;:H2:7,V", + // "Vertex2;:G;FFC;:H2:7,V", + // "Vertex3;:G;FFC;:H2:7,V", + // "Vertex4;:G;FFC;:H2:7,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementBSplineFace) @@ -2880,23 +2942,28 @@ TEST_F(TopoShapeExpansionTest, makeElementBSplineFace) auto elements = elementMap(result); Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct - EXPECT_TRUE(PartTestHelpers::boxesMatch( - bb, - Base::BoundBox3d(-10, -2.0597998470594132, 2, -4, 2.1254369627132599, 2))); + EXPECT_TRUE( + PartTestHelpers::boxesMatch( + bb, + Base::BoundBox3d(-10, -2.0597998470594132, 2, -4, 2.1254369627132599, 2) + ) + ); EXPECT_NEAR(getArea(result.getShape()), 14.677052, 1e-6); // Assert elementMap is correct - EXPECT_TRUE(elementsMatch(result, - { - "Edge1", - "Edge1;BSF", - "Edge1;D1", - "Edge1;D2", - "Edge1;D3", - "Vertex1", - "Vertex1;D1", - "Vertex2", - "Vertex2;D1", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge1", + "Edge1;BSF", + "Edge1;D1", + "Edge1;D2", + "Edge1;D3", + "Vertex1", + "Vertex1;D1", + "Vertex2", + "Vertex2;D1", + } + )); } TEST_F(TopoShapeExpansionTest, replaceElementShape) @@ -2907,7 +2974,8 @@ TEST_F(TopoShapeExpansionTest, replaceElementShape) auto wire {BRepBuilderAPI_MakeWire( BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(1.0, 0.0, 0.0)), BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 0.0, 0.0), gp_Pnt(1.0, 1.0, 0.0)), - BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 1.0, 0.0), gp_Pnt(0.0, 0.0, 0.0))) + BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 1.0, 0.0), gp_Pnt(0.0, 0.0, 0.0)) + ) .Wire()}; auto shell = cube1.makeElementShell(); auto wires = shell.getSubTopoShapes(TopAbs_WIRE); @@ -2928,7 +2996,8 @@ TEST_F(TopoShapeExpansionTest, replaceElementShape) "Edge4;:H2,E", "Edge4;:H3,E", "Face1;:H2,F", "Face1;:H3,F", "Face1;:H4,F", "Face1;:H5,F", "Face1;:H6,F", "Vertex1;:H1,V", "Vertex1;:H2,V", "Vertex2;:H1,V", "Vertex2;:H2,V", "Vertex3;:H1,V", "Vertex3;:H2,V", "Vertex4;:H1,V", "Vertex4;:H2,V", - })); + } + )); } TEST_F(TopoShapeExpansionTest, removeElementShape) @@ -2946,27 +3015,30 @@ TEST_F(TopoShapeExpansionTest, removeElementShape) EXPECT_EQ(result.countSubShapes("Face"), 5); // Assert that we're creating a correct element map EXPECT_TRUE(result.getMappedChildElements().empty()); - EXPECT_TRUE( - elementsMatch(result, - { - "Edge1;:H1,E;:H7,E", "Edge1;:H2,E;:H7,E", "Edge1;:H3,E;:H7,E", - "Edge2;:H1,E;:H7,E", "Edge2;:H2,E;:H7,E", "Edge2;:H3,E;:H7,E", - "Edge3;:H1,E;:H7,E", "Edge3;:H2,E;:H7,E", "Edge3;:H3,E;:H7,E", - "Edge4;:H1,E;:H7,E", "Edge4;:H2,E;:H7,E", "Edge4;:H3,E;:H7,E", - "Face1;:H2,F;:H7,F", "Face1;:H3,F;:H7,F", "Face1;:H4,F;:H7,F", - "Face1;:H5,F;:H7,F", "Face1;:H6,F;:H7,F", "Vertex1;:H1,V;:H7,V", - "Vertex1;:H2,V;:H7,V", "Vertex2;:H1,V;:H7,V", "Vertex2;:H2,V;:H7,V", - "Vertex3;:H1,V;:H7,V", "Vertex3;:H2,V;:H7,V", "Vertex4;:H1,V;:H7,V", - "Vertex4;:H2,V;:H7,V", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge1;:H1,E;:H7,E", "Edge1;:H2,E;:H7,E", "Edge1;:H3,E;:H7,E", + "Edge2;:H1,E;:H7,E", "Edge2;:H2,E;:H7,E", "Edge2;:H3,E;:H7,E", + "Edge3;:H1,E;:H7,E", "Edge3;:H2,E;:H7,E", "Edge3;:H3,E;:H7,E", + "Edge4;:H1,E;:H7,E", "Edge4;:H2,E;:H7,E", "Edge4;:H3,E;:H7,E", + "Face1;:H2,F;:H7,F", "Face1;:H3,F;:H7,F", "Face1;:H4,F;:H7,F", + "Face1;:H5,F;:H7,F", "Face1;:H6,F;:H7,F", "Vertex1;:H1,V;:H7,V", + "Vertex1;:H2,V;:H7,V", "Vertex2;:H1,V;:H7,V", "Vertex2;:H2,V;:H7,V", + "Vertex3;:H1,V;:H7,V", "Vertex3;:H2,V;:H7,V", "Vertex4;:H1,V;:H7,V", + "Vertex4;:H2,V;:H7,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementEvolve) { - BRepBuilderAPI_MakePolygon polygon(gp_Pnt(0.0, 0.0, 0.0), - gp_Pnt(200.0, 0.0, 0.0), - gp_Pnt(200.0, 200.0, 0.0), - gp_Pnt(0.0, 200.0, 0.0)); + BRepBuilderAPI_MakePolygon polygon( + gp_Pnt(0.0, 0.0, 0.0), + gp_Pnt(200.0, 0.0, 0.0), + gp_Pnt(200.0, 200.0, 0.0), + gp_Pnt(0.0, 200.0, 0.0) + ); polygon.Close(); TopoShape spine {polygon.Wire(), 1L}; // Alternative: @@ -2984,7 +3056,8 @@ TEST_F(TopoShapeExpansionTest, makeElementEvolve) Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct EXPECT_TRUE( - PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-60.0, -60.0, -200.0, 260.0, 260.0, 0))); + PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-60.0, -60.0, -200.0, 260.0, 260.0, 0)) + ); EXPECT_FLOAT_EQ(getVolume(result.getShape()), 8910324); // Assert elementMap is correct EXPECT_EQ(topoShape.getElementMap().size(), 0); @@ -3005,7 +3078,8 @@ TEST_F(TopoShapeExpansionTest, traceElement) TopoShape topoShape2 {cube2, 2L}; // Act TopoShape& result = topoShape1.makeElementCut( - {topoShape1, topoShape2}); //, const char* op = nullptr, double tol = 0); + {topoShape1, topoShape2} + ); //, const char* op = nullptr, double tol = 0); std::string name {"Face2;:M;CUT;:H1:7,F"}; // auto faces = result.getSubTopoShapes(TopAbs_FACE); Data::MappedName mappedName(name); @@ -3029,47 +3103,49 @@ TEST_F(TopoShapeExpansionTest, traceElement) // Act result.traceElement(mappedName, cb); // Assert we have the element map we think we do. - EXPECT_TRUE(allElementsMatch(result, - { - "Edge1", - "Edge10;:G(Edge2;K-1;:H2:4,E);CUT;:H1:1a,V", - "Edge10;:M;CUT;:H1:7,E", - "Edge11", - "Edge11;:M;CUT;:H2:7,E", - "Edge12", - "Edge12;:M;CUT;:H2:7,E", - "Edge2", - "Edge2;:M;CUT;:H2:7,E", - "Edge3", - "Edge3;:M;CUT;:H2:7,E", - "Edge4", - "Edge4;:M;CUT;:H2:7,E", - "Edge6;:G(Edge12;K-1;:H2:4,E);CUT;:H1:1b,V", - "Edge6;:M;CUT;:H1:7,E", - "Edge7", - "Edge8;:G(Edge11;K-1;:H2:4,E);CUT;:H1:1b,V", - "Edge8;:M;CUT;:H1:7,E", - "Edge9;:G(Edge4;K-1;:H2:4,E);CUT;:H1:1a,V", - "Edge9;:M;CUT;:H1:7,E", - "Face1", - "Face1;:M;CUT;:H2:7,F", - "Face2;:G(Face4;K-1;:H2:4,F);CUT;:H1:1a,E", - "Face2;:M;CUT;:H1:7,F", - "Face3;:G(Face1;K-1;:H2:4,F);CUT;:H1:1a,E", - "Face3;:M;CUT;:H1:7,F", - "Face4", - "Face4;:M;CUT;:H2:7,F", - "Face5;:M;CUT;:H1:7,F", - "Face6;:M;CUT;:H1:7,F", - "Vertex1", - "Vertex2", - "Vertex3", - "Vertex3;:M;CUT;:H2:7,V", - "Vertex4", - "Vertex4;:M;CUT;:H2:7,V", - "Vertex7", - "Vertex8", - })); + EXPECT_TRUE(allElementsMatch( + result, + { + "Edge1", + "Edge10;:G(Edge2;K-1;:H2:4,E);CUT;:H1:1a,V", + "Edge10;:M;CUT;:H1:7,E", + "Edge11", + "Edge11;:M;CUT;:H2:7,E", + "Edge12", + "Edge12;:M;CUT;:H2:7,E", + "Edge2", + "Edge2;:M;CUT;:H2:7,E", + "Edge3", + "Edge3;:M;CUT;:H2:7,E", + "Edge4", + "Edge4;:M;CUT;:H2:7,E", + "Edge6;:G(Edge12;K-1;:H2:4,E);CUT;:H1:1b,V", + "Edge6;:M;CUT;:H1:7,E", + "Edge7", + "Edge8;:G(Edge11;K-1;:H2:4,E);CUT;:H1:1b,V", + "Edge8;:M;CUT;:H1:7,E", + "Edge9;:G(Edge4;K-1;:H2:4,E);CUT;:H1:1a,V", + "Edge9;:M;CUT;:H1:7,E", + "Face1", + "Face1;:M;CUT;:H2:7,F", + "Face2;:G(Face4;K-1;:H2:4,F);CUT;:H1:1a,E", + "Face2;:M;CUT;:H1:7,F", + "Face3;:G(Face1;K-1;:H2:4,F);CUT;:H1:1a,E", + "Face3;:M;CUT;:H1:7,F", + "Face4", + "Face4;:M;CUT;:H2:7,F", + "Face5;:M;CUT;:H1:7,F", + "Face6;:M;CUT;:H1:7,F", + "Vertex1", + "Vertex2", + "Vertex3", + "Vertex3;:M;CUT;:H2:7,V", + "Vertex4", + "Vertex4;:M;CUT;:H2:7,V", + "Vertex7", + "Vertex8", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementOffset) @@ -3091,7 +3167,8 @@ TEST_F(TopoShapeExpansionTest, makeElementOffset) Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct EXPECT_TRUE( - PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-0.25, -0.25, -0.25, 1.25, 1.25, 1.25))); + PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-0.25, -0.25, -0.25, 1.25, 1.25, 1.25)) + ); EXPECT_NEAR(getVolume(result.getShape()), 3.1544986, 1e-6); // Assert elementMap is correct // EXPECT_EQ(elements.size(), 98); @@ -3099,107 +3176,109 @@ TEST_F(TopoShapeExpansionTest, makeElementOffset) // EXPECT_EQ( // elements[IndexedName("Face", 1)], // MappedName("Face2;:G;OFS;:H1:7,F")); - EXPECT_TRUE(elementsMatch(result, - { - "Edge10;:G;OFS;:H1:7,F", - "Edge10;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge10;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge10;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge10;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge11;:G;OFS;:H1:7,F", - "Edge11;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge11;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge11;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge11;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge12;:G;OFS;:H1:7,F", - "Edge12;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge12;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge12;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge12;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge1;:G;OFS;:H1:7,F", - "Edge1;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge1;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge1;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge1;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge1;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge1;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge1;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge1;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge2;:G;OFS;:H1:7,F", - "Edge2;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge2;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge2;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge2;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge2;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge2;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge2;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge3;:G;OFS;:H1:7,F", - "Edge3;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge3;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge3;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge3;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge3;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge3;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge3;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge4;:G;OFS;:H1:7,F", - "Edge4;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge4;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge4;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge4;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge4;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge4;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge5;:G;OFS;:H1:7,F", - "Edge5;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge5;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge5;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge5;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge5;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge5;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge5;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge5;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge6;:G;OFS;:H1:7,F", - "Edge6;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge6;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge6;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge6;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge6;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge6;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge6;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge7;:G;OFS;:H1:7,F", - "Edge7;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge7;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge7;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge7;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge7;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge7;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge7;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge8;:G;OFS;:H1:7,F", - "Edge8;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge8;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", - "Edge8;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", - "Edge8;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge8;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge8;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Edge9;:G;OFS;:H1:7,F", - "Edge9;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", - "Edge9;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", - "Edge9;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", - "Edge9;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", - "Face1;:G;OFS;:H1:7,F", - "Face2;:G;OFS;:H1:7,F", - "Face3;:G;OFS;:H1:7,F", - "Face4;:G;OFS;:H1:7,F", - "Face5;:G;OFS;:H1:7,F", - "Face6;:G;OFS;:H1:7,F", - "Vertex1;:G;OFS;:H1:7,F", - "Vertex2;:G;OFS;:H1:7,F", - "Vertex3;:G;OFS;:H1:7,F", - "Vertex4;:G;OFS;:H1:7,F", - "Vertex5;:G;OFS;:H1:7,F", - "Vertex6;:G;OFS;:H1:7,F", - "Vertex7;:G;OFS;:H1:7,F", - "Vertex8;:G;OFS;:H1:7,F", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge10;:G;OFS;:H1:7,F", + "Edge10;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge10;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge10;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge10;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge11;:G;OFS;:H1:7,F", + "Edge11;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge11;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge11;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge11;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge12;:G;OFS;:H1:7,F", + "Edge12;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge12;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge12;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge12;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge1;:G;OFS;:H1:7,F", + "Edge1;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge1;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge1;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge1;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge1;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge1;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge1;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge1;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge2;:G;OFS;:H1:7,F", + "Edge2;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge2;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge2;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge2;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge2;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge2;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge2;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge3;:G;OFS;:H1:7,F", + "Edge3;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge3;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge3;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge3;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge3;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge3;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge3;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge4;:G;OFS;:H1:7,F", + "Edge4;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge4;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge4;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge4;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge4;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge4;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge5;:G;OFS;:H1:7,F", + "Edge5;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge5;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge5;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge5;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge5;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge5;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge5;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge5;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge6;:G;OFS;:H1:7,F", + "Edge6;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge6;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge6;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge6;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge6;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge6;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge6;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge7;:G;OFS;:H1:7,F", + "Edge7;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge7;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge7;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge7;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge7;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge7;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge7;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge8;:G;OFS;:H1:7,F", + "Edge8;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge8;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U2;OFS;:H1:8,V", + "Edge8;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E;:U;OFS;:H1:7,V", + "Edge8;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge8;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge8;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Edge9;:G;OFS;:H1:7,F", + "Edge9;:G;OFS;:H1:7,F;:U2;OFS;:H1:8,E", + "Edge9;:G;OFS;:H1:7,F;:U3;OFS;:H1:8,E", + "Edge9;:G;OFS;:H1:7,F;:U4;OFS;:H1:8,E", + "Edge9;:G;OFS;:H1:7,F;:U;OFS;:H1:7,E", + "Face1;:G;OFS;:H1:7,F", + "Face2;:G;OFS;:H1:7,F", + "Face3;:G;OFS;:H1:7,F", + "Face4;:G;OFS;:H1:7,F", + "Face5;:G;OFS;:H1:7,F", + "Face6;:G;OFS;:H1:7,F", + "Vertex1;:G;OFS;:H1:7,F", + "Vertex2;:G;OFS;:H1:7,F", + "Vertex3;:G;OFS;:H1:7,F", + "Vertex4;:G;OFS;:H1:7,F", + "Vertex5;:G;OFS;:H1:7,F", + "Vertex6;:G;OFS;:H1:7,F", + "Vertex7;:G;OFS;:H1:7,F", + "Vertex8;:G;OFS;:H1:7,F", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementOffsetFace) @@ -3213,36 +3292,37 @@ TEST_F(TopoShapeExpansionTest, makeElementOffsetFace) auto elements = elementMap(result); Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct - EXPECT_TRUE( - PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-0.25, -0.25, 0.0, 3.25, 2.25, 0.0))); + EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-0.25, -0.25, 0.0, 3.25, 2.25, 0.0))); // Assert elementMap is correct // EXPECT_EQ(elements.size(), 19); // EXPECT_EQ(elements.count(IndexedName("Face", 1)), 1); // EXPECT_EQ( // elements[IndexedName("Face", 1)], // MappedName("Edge1;:G;OFF;:H1:7,E;FAC;:H1:4,F")); - EXPECT_TRUE(elementsMatch(result, - { - "Edge1;:G;OFF;:H1:7,E", - "Edge1;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", - "Edge1;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", - "Edge1;:G;OFF;:H1:7,E;FAC;:H1:4,F", - "Edge2;:G;OFF;:H1:7,E", - "Edge2;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", - "Edge2;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", - "Edge3;:G;OFF;:H1:7,E", - "Edge3;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", - "Edge3;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", - "Edge4;:G;OFF;:H1:7,E", - "Edge4;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", - "Edge4;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", - "Edge5;:H1,E", - "Vertex1;:G;OFF;:H1:7,E", - "Vertex2;:G;OFF;:H1:7,E", - "Vertex3;:G;OFF;:H1:7,E", - "Vertex4;:G;OFF;:H1:7,E", - "Vertex5;:H1,V", - })); + EXPECT_TRUE(elementsMatch( + result, + { + "Edge1;:G;OFF;:H1:7,E", + "Edge1;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", + "Edge1;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", + "Edge1;:G;OFF;:H1:7,E;FAC;:H1:4,F", + "Edge2;:G;OFF;:H1:7,E", + "Edge2;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", + "Edge2;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", + "Edge3;:G;OFF;:H1:7,E", + "Edge3;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", + "Edge3;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", + "Edge4;:G;OFF;:H1:7,E", + "Edge4;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V", + "Edge4;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V", + "Edge5;:H1,E", + "Vertex1;:G;OFF;:H1:7,E", + "Vertex2;:G;OFF;:H1:7,E", + "Vertex3;:G;OFF;:H1:7,E", + "Vertex4;:G;OFF;:H1:7,E", + "Vertex5;:H1,V", + } + )); } TEST_F(TopoShapeExpansionTest, makeElementOffset2D) @@ -3256,28 +3336,29 @@ TEST_F(TopoShapeExpansionTest, makeElementOffset2D) auto elements = elementMap(result); Base::BoundBox3d bb = result.getBoundBox(); // Assert shape is correct - EXPECT_TRUE( - PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-0.25, -0.25, 0.0, 3.25, 2.25, 0.0))); + EXPECT_TRUE(PartTestHelpers::boxesMatch(bb, Base::BoundBox3d(-0.25, -0.25, 0.0, 3.25, 2.25, 0.0))); // Assert elementMap is correct // EXPECT_EQ(elements.size(), 10); // EXPECT_EQ(elements.count(IndexedName("Edge", 1)), 1); // EXPECT_EQ( // elements[IndexedName("Edge", 1)], // MappedName("Edge1;:G;OFF;:H1:7,E;OFF;:H1:4,E")); - EXPECT_TRUE(elementsMatch(result, + EXPECT_TRUE(elementsMatch( + result, - { - "Edge1;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V;OFF;:H1:4,V", - "Edge1;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V;OFF;:H1:4,V", - "Edge1;:G;OFF;:H1:7,E;OFF;:H1:4,E", - "Edge2;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V;OFF;:H1:4,V", - "Edge2;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V;OFF;:H1:4,V", - "Edge2;:G;OFF;:H1:7,E;OFF;:H1:4,E", - "Vertex1;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V;OFF;:H1:4,V", - "Vertex1;:G;OFF;:H1:7,E;OFF;:H1:4,E", - "Vertex3;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V;OFF;:H1:4,V", - "Vertex3;:G;OFF;:H1:7,E;OFF;:H1:4,E", - })); + { + "Edge1;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V;OFF;:H1:4,V", + "Edge1;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V;OFF;:H1:4,V", + "Edge1;:G;OFF;:H1:7,E;OFF;:H1:4,E", + "Edge2;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V;OFF;:H1:4,V", + "Edge2;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V;OFF;:H1:4,V", + "Edge2;:G;OFF;:H1:7,E;OFF;:H1:4,E", + "Vertex1;:G;OFF;:H1:7,E;:U2;OFF;:H1:8,V;OFF;:H1:4,V", + "Vertex1;:G;OFF;:H1:7,E;OFF;:H1:4,E", + "Vertex3;:G;OFF;:H1:7,E;:U;OFF;:H1:7,V;OFF;:H1:4,V", + "Vertex3;:G;OFF;:H1:7,E;OFF;:H1:4,E", + } + )); } // NOLINTEND(readability-magic-numbers,cppcoreguidelines-avoid-magic-numbers) diff --git a/tests/src/Mod/Part/App/TopoShapeMakeShape.cpp b/tests/src/Mod/Part/App/TopoShapeMakeShape.cpp index b3f895fd64..ee2ad3c55b 100644 --- a/tests/src/Mod/Part/App/TopoShapeMakeShape.cpp +++ b/tests/src/Mod/Part/App/TopoShapeMakeShape.cpp @@ -59,8 +59,10 @@ TEST_F(TopoShapeMakeShapeTests, nullShapeThrows) TopoDS_Vertex nullShape; // Act and assert - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullShape, *Mapper(), sources), - Part::NullShapeException); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullShape, *Mapper(), sources), + Part::NullShapeException + ); } TEST_F(TopoShapeMakeShapeTests, shapeVertex) @@ -92,8 +94,8 @@ TEST_F(TopoShapeMakeShapeTests, thruSections) thruMaker.AddWire(wire2); TopoShape topoShape {}; // Act - TopoShape& result = - topoShape.makeElementShape(thruMaker, {wire1ts, wire2ts}, OpCodes::ThruSections); + TopoShape& result + = topoShape.makeElementShape(thruMaker, {wire1ts, wire2ts}, OpCodes::ThruSections); auto elements = elementMap(result); // Assert EXPECT_EQ(elements.size(), 24); @@ -110,7 +112,8 @@ TEST_F(TopoShapeMakeShapeTests, thruSections) "Vertex2;:G(Vertex2;K-1;:H2:4,V);TRU;:H1:1c,E", "Vertex2;:H1,V", "Vertex2;:H2,V", "Vertex3;:G(Vertex3;K-1;:H2:4,V);TRU;:H1:1c,E", "Vertex3;:H1,V", "Vertex3;:H2,V", "Vertex4;:G(Vertex4;K-1;:H2:4,V);TRU;:H1:1c,E", "Vertex4;:H1,V", "Vertex4;:H2,V", - })); + } + )); } TEST_F(TopoShapeMakeShapeTests, sewing) @@ -128,10 +131,12 @@ TEST_F(TopoShapeMakeShapeTests, sewing) std::vector sources {{face1, 1L}, {face2, 2L}}; TopoShape topoShape {}; // Act - TopoShape& result = topoShape.makeShapeWithElementMap(sewer.SewedShape(), - MapperSewing(sewer), - sources, - OpCodes::Sewing); + TopoShape& result = topoShape.makeShapeWithElementMap( + sewer.SewedShape(), + MapperSewing(sewer), + sources, + OpCodes::Sewing + ); auto elements = elementMap(result); // Assert @@ -141,25 +146,27 @@ TEST_F(TopoShapeMakeShapeTests, sewing) EXPECT_EQ(getArea(result.getShape()), 12); // TODO: This element map is suspiciously devoid of anything OpCodes::Sewing (SEW). Is that // right? - EXPECT_TRUE(allElementsMatch(topoShape, - { - "Face1;:H1,F", - "Face1;:H2,F", - "Edge1;:H2,E", - "Edge2;:H2,E", - "Edge3;:H2,E", - "Edge4;:H2,E", - "Edge1;:H1,E", - "Edge2;:H1,E", - "Edge3;:H1,E", - "Edge4;:H1,E", - "Vertex1;:H2,V", - "Vertex2;:H2,V", - "Vertex3;:H2,V", - "Vertex4;:H2,V", - "Vertex1;:H1,V", - "Vertex2;:H1,V", - "Vertex3;:H1,V", - "Vertex4;:H1,V", - })); + EXPECT_TRUE(allElementsMatch( + topoShape, + { + "Face1;:H1,F", + "Face1;:H2,F", + "Edge1;:H2,E", + "Edge2;:H2,E", + "Edge3;:H2,E", + "Edge4;:H2,E", + "Edge1;:H1,E", + "Edge2;:H1,E", + "Edge3;:H1,E", + "Edge4;:H1,E", + "Vertex1;:H2,V", + "Vertex2;:H2,V", + "Vertex3;:H2,V", + "Vertex4;:H2,V", + "Vertex1;:H1,V", + "Vertex2;:H1,V", + "Vertex3;:H1,V", + "Vertex4;:H1,V", + } + )); } diff --git a/tests/src/Mod/Part/App/TopoShapeMakeShapeWithElementMap.cpp b/tests/src/Mod/Part/App/TopoShapeMakeShapeWithElementMap.cpp index a0f8bbabc6..a89a76514e 100644 --- a/tests/src/Mod/Part/App/TopoShapeMakeShapeWithElementMap.cpp +++ b/tests/src/Mod/Part/App/TopoShapeMakeShapeWithElementMap.cpp @@ -50,8 +50,10 @@ protected: return &_mapper; } - void testFindSourceSubShapesInElementMapForSource(const std::vector& sources, - const TopoShape& source); + void testFindSourceSubShapesInElementMapForSource( + const std::vector& sources, + const TopoShape& source + ); private: std::string _docName; @@ -75,22 +77,38 @@ TEST_F(TopoShapeMakeShapeWithElementMapTests, nullShapeThrows) TopoDS_Compound nullCompound; // Act and assert - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullVertex, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullEdge, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullWire, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullFace, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullShell, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullSolid, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullCompSolid, *Mapper(), sources), - Part::NullShapeException); - EXPECT_THROW(Shape()->makeShapeWithElementMap(nullCompound, *Mapper(), sources), - Part::NullShapeException); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullVertex, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullEdge, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullWire, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullFace, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullShell, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullSolid, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullCompSolid, *Mapper(), sources), + Part::NullShapeException + ); + EXPECT_THROW( + Shape()->makeShapeWithElementMap(nullCompound, *Mapper(), sources), + Part::NullShapeException + ); } std::map elementMap(const TopoShape& shape) @@ -135,8 +153,9 @@ TEST_F(TopoShapeMakeShapeWithElementMapTests, mapCompoundCount) EXPECT_STREQ(compound.shapeName().c_str(), "Compound"); EXPECT_EQ( 22, - compound.getMappedChildElements().size()); // Changed with PR#12471. Probably will change - // again after importing other TopoNaming logics + compound.getMappedChildElements().size() + ); // Changed with PR#12471. Probably will change + // again after importing other TopoNaming logics } TEST_F(TopoShapeMakeShapeWithElementMapTests, emptySourceShapes) @@ -153,7 +172,8 @@ TEST_F(TopoShapeMakeShapeWithElementMapTests, emptySourceShapes) EXPECT_EQ( &originalShape, - &modifiedShape.makeShapeWithElementMap(source.getShape(), *Mapper(), emptySources)); + &modifiedShape.makeShapeWithElementMap(source.getShape(), *Mapper(), emptySources) + ); } } @@ -173,34 +193,41 @@ TEST_F(TopoShapeMakeShapeWithElementMapTests, nonMappableSources) } if (canMap == 0U) { - EXPECT_EQ(&source, - &source.makeShapeWithElementMap(source.getShape(), *Mapper(), sources)); + EXPECT_EQ(&source, &source.makeShapeWithElementMap(source.getShape(), *Mapper(), sources)); } } } -void testFindSourceShapesInSingleShape(const Part::TopoShape& cmpdShape, - const Part::TopoShape& source, - const std::vector& sources, - const TopoShape::Mapper& mapper) +void testFindSourceShapesInSingleShape( + const Part::TopoShape& cmpdShape, + const Part::TopoShape& source, + const std::vector& sources, + const TopoShape::Mapper& mapper +) { std::vector tmpSources {source}; for (const auto& subSource : sources) { Part::TopoShape tmpShape {source.getShape()}; tmpShape.makeShapeWithElementMap(source.getShape(), mapper, tmpSources); if (&source == &subSource) { - EXPECT_NE(tmpShape.findShape(subSource.getShape()), - 0); // if tmpShape uses, for example, cube1 and we search for cube1 than - // we should find it + EXPECT_NE( + tmpShape.findShape(subSource.getShape()), + 0 + ); // if tmpShape uses, for example, cube1 and we search for cube1 than + // we should find it } else { - EXPECT_EQ(tmpShape.findShape(subSource.getShape()), - 0); // if tmpShape uses, for example, cube1 and we search for cube2 than - // we shouldn't find it + EXPECT_EQ( + tmpShape.findShape(subSource.getShape()), + 0 + ); // if tmpShape uses, for example, cube1 and we search for cube2 than + // we shouldn't find it } } - EXPECT_NE(cmpdShape.findShape(source.getShape()), - 0); // as cmpdShape is made with cube1 and cube2 we should find both of them + EXPECT_NE( + cmpdShape.findShape(source.getShape()), + 0 + ); // as cmpdShape is made with cube1 and cube2 we should find both of them } TEST_F(TopoShapeMakeShapeWithElementMapTests, findSourceShapesInShape) @@ -221,9 +248,11 @@ TEST_F(TopoShapeMakeShapeWithElementMapTests, findSourceShapesInShape) } } -void testFindSubShapesForSourceWithTypeAndIndex(const std::string& shapeTypeStr, - std::map& elementStdMap, - unsigned long shapeIndex) +void testFindSubShapesForSourceWithTypeAndIndex( + const std::string& shapeTypeStr, + std::map& elementStdMap, + unsigned long shapeIndex +) { std::string shapeIndexStr = std::to_string(shapeIndex); std::string shapeName {shapeTypeStr + shapeIndexStr}; @@ -242,9 +271,11 @@ void testFindSubShapesForSourceWithTypeAndIndex(const std::string& shapeTypeStr, QT_WARNING_POP } -void testFindSubShapesForSourceWithType(const TopoShape& source, - const char* shapeType, - std::map& elementStdMap) +void testFindSubShapesForSourceWithType( + const TopoShape& source, + const char* shapeType, + std::map& elementStdMap +) { std::string shapeTypeStr {shapeType}; @@ -265,7 +296,8 @@ void testFindSubShapesForSourceWithType(const TopoShape& source, void TopoShapeMakeShapeWithElementMapTests::testFindSourceSubShapesInElementMapForSource( const std::vector& sources, - const TopoShape& source) + const TopoShape& source +) { TopoShape tmpShape {source.getShape()}; tmpShape.makeShapeWithElementMap(source.getShape(), *Mapper(), sources); @@ -329,8 +361,7 @@ std::string composeTagInfo(const MappedElement& element, const TopoShape& shape) { std::string elementNameStr {element.name.constPostfix()}; std::string tagInfo = POSTFIX_TAG + std::to_string(shape.Tag); - tagInfo += - ":" + std::to_string(elementNameStr.substr(0, elementNameStr.find(tagInfo)).length()); + tagInfo += ":" + std::to_string(elementNameStr.substr(0, elementNameStr.find(tagInfo)).length()); return tagInfo; } diff --git a/tests/src/Mod/Part/App/WireJoiner.cpp b/tests/src/Mod/Part/App/WireJoiner.cpp index 982f91c4b3..b4db7cb046 100644 --- a/tests/src/Mod/Part/App/WireJoiner.cpp +++ b/tests/src/Mod/Part/App/WireJoiner.cpp @@ -150,7 +150,8 @@ TEST_F(WireJoinerTest, setOutline) // To see the correct value for this parameter refer to method WireJoinerP::canShowShape() auto hParam {App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/WireJoiner")}; + "User parameter:BaseApp/Preferences/WireJoiner" + )}; auto catchIteration {hParam->GetInt("Iteration", 0)}; hParam->SetInt("Iteration", -1); @@ -195,8 +196,8 @@ TEST_F(WireJoinerTest, setOutline) auto foundRemovedNoOutline {false}; for (const auto& obj : objsInDoc) { - foundRemovedNoOutline = - (std::string(obj->Label.getValue()).find("removed") != std::string::npos); + foundRemovedNoOutline + = (std::string(obj->Label.getValue()).find("removed") != std::string::npos); if (foundRemovedNoOutline) { break; } @@ -216,8 +217,7 @@ TEST_F(WireJoinerTest, setOutline) auto foundRemovedOutline {false}; for (const auto& obj : objsInDoc) { - foundRemovedOutline = - (std::string(obj->Label.getValue()).find("removed") != std::string::npos); + foundRemovedOutline = (std::string(obj->Label.getValue()).find("removed") != std::string::npos); if (foundRemovedOutline) { break; } @@ -473,10 +473,11 @@ TEST_F(WireJoinerTest, setTolerance) auto edge2 {BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 0.0, 0.0), gp_Pnt(1.0, 1.0, 0.0)).Edge()}; auto edge3 {BRepBuilderAPI_MakeEdge(gp_Pnt(1.0, 1.0, 0.0), gp_Pnt(0.0, 0.0, 0.0)).Edge()}; auto edge4 {BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(0.9, 0.0, 0.0)).Edge()}; - auto edge5 { - BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 0.0, 0.0), - gp_Pnt(0.9 * std::cos(pi / 18), 0.9 * std::sin(pi / 18), 0.0)) - .Edge()}; + auto edge5 {BRepBuilderAPI_MakeEdge( + gp_Pnt(0.0, 0.0, 0.0), + gp_Pnt(0.9 * std::cos(pi / 18), 0.9 * std::sin(pi / 18), 0.0) + ) + .Edge()}; // A vector of edges used as argument for wjNegtol.addShape() std::vector edgesNegtol {edge1, edge2, edge3}; @@ -712,9 +713,7 @@ TEST_F(WireJoinerTest, getResultWires) std::vector edgesNoResultWires {edge1, edge2, edge3}; // A vector of TopoShape edges used as argument for wjNoOp.addShape(). A Tag is needed for every // TopoShape, otherwise no element map will be created and no op can be found - std::vector edgesNoOp {TopoShape(edge1, 4), - TopoShape(edge2, 5), - TopoShape(edge4, 6)}; + std::vector edgesNoOp {TopoShape(edge1, 4), TopoShape(edge2, 5), TopoShape(edge4, 6)}; // A vector of TopoShape edges used as argument for wjOp.addShape(). A Tag is needed for every // TopoShape, otherwise no element map will be created and no op can be found std::vector edgesOp {TopoShape(edge1, 7), TopoShape(edge2, 8), TopoShape(edge4, 9)}; diff --git a/tests/src/Mod/PartDesign/App/BackwardCompatibility.cpp b/tests/src/Mod/PartDesign/App/BackwardCompatibility.cpp index 49e593bae0..682812b035 100644 --- a/tests/src/Mod/PartDesign/App/BackwardCompatibility.cpp +++ b/tests/src/Mod/PartDesign/App/BackwardCompatibility.cpp @@ -56,7 +56,8 @@ TEST_F(BackwardCompatibilityTest, TestOpenV021Model) // arrange auto doc = App::GetApplication().openDocument( - std::string(getTestPath() + "ModelFromV021.FCStd").c_str()); + std::string(getTestPath() + "ModelFromV021.FCStd").c_str() + ); setDocument(doc); auto chamfer = dynamic_cast(doc->getObject("Chamfer")); @@ -65,7 +66,8 @@ TEST_F(BackwardCompatibilityTest, TestOpenV021Model) std::vector chamferOriginalEdges {}; for (const auto& chamferEdgesName : chamferEdgesNames) { chamferOriginalEdges.push_back( - chamfer->getBaseTopoShape().getSubTopoShape(chamferEdgesName.c_str()).getShape()); + chamfer->getBaseTopoShape().getSubTopoShape(chamferEdgesName.c_str()).getShape() + ); } // act @@ -108,16 +110,20 @@ TEST_F(BackwardCompatibilityTest, TestOpenV021Model) EXPECT_TRUE(checkSameVertexes( chamfer->getBaseTopoShape().getSubTopoShape(chamferEdgesNames[0].c_str()).getShape(), - chamferOriginalEdges[0])); + chamferOriginalEdges[0] + )); EXPECT_TRUE(checkSameVertexes( chamfer->getBaseTopoShape().getSubTopoShape(chamferEdgesNames[1].c_str()).getShape(), - chamferOriginalEdges[1])); + chamferOriginalEdges[1] + )); EXPECT_TRUE(checkSameVertexes( chamfer->getBaseTopoShape().getSubTopoShape(chamferEdgesNames[2].c_str()).getShape(), - chamferOriginalEdges[2])); + chamferOriginalEdges[2] + )); EXPECT_TRUE(checkSameVertexes( chamfer->getBaseTopoShape().getSubTopoShape(chamferEdgesNames[3].c_str()).getShape(), - chamferOriginalEdges[3])); + chamferOriginalEdges[3] + )); } // NOLINTEND(readability-magic-numbers,cppcoreguidelines-avoid-magic-numbers) diff --git a/tests/src/Mod/PartDesign/App/ShapeBinder.cpp b/tests/src/Mod/PartDesign/App/ShapeBinder.cpp index e3105faa8b..99b65cf777 100644 --- a/tests/src/Mod/PartDesign/App/ShapeBinder.cpp +++ b/tests/src/Mod/PartDesign/App/ShapeBinder.cpp @@ -29,7 +29,8 @@ protected: _box->Width.setValue(2); _box->Height.setValue(3); _box->Placement.setValue( - Base::Placement(Base::Vector3d(), Base::Rotation(), Base::Vector3d())); // NOLINT + Base::Placement(Base::Vector3d(), Base::Rotation(), Base::Vector3d()) + ); // NOLINT // _body->addObject(_box); // Invalid, Part::Features can't go in a PartDesign::Body, // but we can bind them. _binder = _doc->addObject("ShapeBinderFoo"); diff --git a/tests/src/Mod/Sketcher/App/Constraint.cpp b/tests/src/Mod/Sketcher/App/Constraint.cpp index 73599c8f74..1f07e515b8 100644 --- a/tests/src/Mod/Sketcher/App/Constraint.cpp +++ b/tests/src/Mod/Sketcher/App/Constraint.cpp @@ -33,8 +33,7 @@ public: } }; -::testing::Environment* const xercesEnv = - ::testing::AddGlobalTestEnvironment(new XercesEnvironment); +::testing::Environment* const xercesEnv = ::testing::AddGlobalTestEnvironment(new XercesEnvironment); class ConstraintPointsAccess: public ::testing::Test { @@ -66,12 +65,18 @@ TEST_F(ConstraintPointsAccess, testDefaultGeoElementIdsAreSane) // NOLINT // New way of accessing elements #endif - EXPECT_EQ(constraint.getElement(0), - Sketcher::GeoElementId(Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none)); - EXPECT_EQ(constraint.getElement(1), - Sketcher::GeoElementId(Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none)); - EXPECT_EQ(constraint.getElement(2), - Sketcher::GeoElementId(Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none)); + EXPECT_EQ( + constraint.getElement(0), + Sketcher::GeoElementId(Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none) + ); + EXPECT_EQ( + constraint.getElement(1), + Sketcher::GeoElementId(Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none) + ); + EXPECT_EQ( + constraint.getElement(2), + Sketcher::GeoElementId(Sketcher::GeoEnum::GeoUndef, Sketcher::PointPos::none) + ); } #if SKETCHER_CONSTRAINT_USE_LEGACY_ELEMENTS @@ -89,12 +94,18 @@ TEST_F(ConstraintPointsAccess, testOldWriteIsReadByNew) // NOLINT constraint.ThirdPos = Sketcher::PointPos::mid; // Assert - EXPECT_EQ(constraint.getElement(0), - Sketcher::GeoElementId(Sketcher::GeoElementId(23, Sketcher::PointPos::start))); - EXPECT_EQ(constraint.getElement(1), - Sketcher::GeoElementId(Sketcher::GeoElementId(34, Sketcher::PointPos::end))); - EXPECT_EQ(constraint.getElement(2), - Sketcher::GeoElementId(Sketcher::GeoElementId(45, Sketcher::PointPos::mid))); + EXPECT_EQ( + constraint.getElement(0), + Sketcher::GeoElementId(Sketcher::GeoElementId(23, Sketcher::PointPos::start)) + ); + EXPECT_EQ( + constraint.getElement(1), + Sketcher::GeoElementId(Sketcher::GeoElementId(34, Sketcher::PointPos::end)) + ); + EXPECT_EQ( + constraint.getElement(2), + Sketcher::GeoElementId(Sketcher::GeoElementId(45, Sketcher::PointPos::mid)) + ); } TEST_F(ConstraintPointsAccess, testNewWriteIsReadByOld) // NOLINT @@ -260,48 +271,49 @@ TEST_F(ConstraintPointsAccess, testElementsRestoredFromSerialization) // NOLINT restoredConstraint.Restore(reader); // Assert - EXPECT_EQ(restoredConstraint.getElement(0), - Sketcher::GeoElementId(23, Sketcher::PointPos::start)); - EXPECT_EQ(restoredConstraint.getElement(1), - Sketcher::GeoElementId(34, Sketcher::PointPos::end)); - EXPECT_EQ(restoredConstraint.getElement(2), - Sketcher::GeoElementId(45, Sketcher::PointPos::mid)); + EXPECT_EQ(restoredConstraint.getElement(0), Sketcher::GeoElementId(23, Sketcher::PointPos::start)); + EXPECT_EQ(restoredConstraint.getElement(1), Sketcher::GeoElementId(34, Sketcher::PointPos::end)); + EXPECT_EQ(restoredConstraint.getElement(2), Sketcher::GeoElementId(45, Sketcher::PointPos::mid)); inputFile.close(); } -TEST_F(ConstraintPointsAccess, - testElementsRestoredFromSerializationWithoutNewElementStorage) // NOLINT +TEST_F( + ConstraintPointsAccess, + testElementsRestoredFromSerializationWithoutNewElementStorage +) // NOLINT { // Arrange // Manually craft a serialized version, only parts in "{}" are important. // New way of storing elements is not present, like if it is an older file. - std::string serializedConstraint = fmt::format("", + "/>", - 67, - 78, - 89, - static_cast(Sketcher::PointPos::mid), - static_cast(Sketcher::PointPos::start), - static_cast(Sketcher::PointPos::end)); + 67, + 78, + 89, + static_cast(Sketcher::PointPos::mid), + static_cast(Sketcher::PointPos::start), + static_cast(Sketcher::PointPos::end) + ); Base::StringWriter writer; auto& stream {writer.Stream()}; @@ -326,45 +338,46 @@ TEST_F(ConstraintPointsAccess, restoredConstraint.Restore(reader); // Assert - EXPECT_EQ(restoredConstraint.getElement(0), - Sketcher::GeoElementId(67, Sketcher::PointPos::mid)); - EXPECT_EQ(restoredConstraint.getElement(1), - Sketcher::GeoElementId(78, Sketcher::PointPos::start)); - EXPECT_EQ(restoredConstraint.getElement(2), - Sketcher::GeoElementId(89, Sketcher::PointPos::end)); + EXPECT_EQ(restoredConstraint.getElement(0), Sketcher::GeoElementId(67, Sketcher::PointPos::mid)); + EXPECT_EQ(restoredConstraint.getElement(1), Sketcher::GeoElementId(78, Sketcher::PointPos::start)); + EXPECT_EQ(restoredConstraint.getElement(2), Sketcher::GeoElementId(89, Sketcher::PointPos::end)); inputFile.close(); } -TEST_F(ConstraintPointsAccess, - testLegacyIsPreferedDuringSerializationWithoutLegacyElementStorage) // NOLINT +TEST_F( + ConstraintPointsAccess, + testLegacyIsPreferedDuringSerializationWithoutLegacyElementStorage +) // NOLINT { // Arrange // Manually craft a serialized version, only parts in "{}" are important. // Only new way of storing elements is present. - std::string serializedConstraint = fmt::format("", - // New way data - 23, - 34, - 45, - static_cast(Sketcher::PointPos::start), - static_cast(Sketcher::PointPos::end), - static_cast(Sketcher::PointPos::mid)); + "/>", + // New way data + 23, + 34, + 45, + static_cast(Sketcher::PointPos::start), + static_cast(Sketcher::PointPos::end), + static_cast(Sketcher::PointPos::mid) + ); Base::StringWriter writer; auto& stream {writer.Stream()}; @@ -389,12 +402,9 @@ TEST_F(ConstraintPointsAccess, restoredConstraint.Restore(reader); // Assert - EXPECT_EQ(restoredConstraint.getElement(0), - Sketcher::GeoElementId(23, Sketcher::PointPos::start)); - EXPECT_EQ(restoredConstraint.getElement(1), - Sketcher::GeoElementId(34, Sketcher::PointPos::end)); - EXPECT_EQ(restoredConstraint.getElement(2), - Sketcher::GeoElementId(45, Sketcher::PointPos::mid)); + EXPECT_EQ(restoredConstraint.getElement(0), Sketcher::GeoElementId(23, Sketcher::PointPos::start)); + EXPECT_EQ(restoredConstraint.getElement(1), Sketcher::GeoElementId(34, Sketcher::PointPos::end)); + EXPECT_EQ(restoredConstraint.getElement(2), Sketcher::GeoElementId(45, Sketcher::PointPos::mid)); inputFile.close(); } @@ -405,45 +415,46 @@ TEST_F(ConstraintPointsAccess, testLegacyIsPreferedDuringSerializationIfContradi // Manually craft a serialized version, only parts in "{}" are important. // It is not important if legacy is included before or after, legacy should always be preferred. - std::string serializedConstraint = - fmt::format("", - // New way data - 23, - 34, - 45, - static_cast(Sketcher::PointPos::start), - static_cast(Sketcher::PointPos::end), - static_cast(Sketcher::PointPos::mid), + "/>", + // New way data + 23, + 34, + 45, + static_cast(Sketcher::PointPos::start), + static_cast(Sketcher::PointPos::end), + static_cast(Sketcher::PointPos::mid), - // Contradicting legacy data, this should be preferred if available - 67, - 78, - 89, - static_cast(Sketcher::PointPos::mid), - static_cast(Sketcher::PointPos::start), - static_cast(Sketcher::PointPos::end)); + // Contradicting legacy data, this should be preferred if available + 67, + 78, + 89, + static_cast(Sketcher::PointPos::mid), + static_cast(Sketcher::PointPos::start), + static_cast(Sketcher::PointPos::end) + ); Base::StringWriter writer; auto& stream {writer.Stream()}; @@ -468,12 +479,9 @@ TEST_F(ConstraintPointsAccess, testLegacyIsPreferedDuringSerializationIfContradi restoredConstraint.Restore(reader); // Assert - EXPECT_EQ(restoredConstraint.getElement(0), - Sketcher::GeoElementId(67, Sketcher::PointPos::mid)); - EXPECT_EQ(restoredConstraint.getElement(1), - Sketcher::GeoElementId(78, Sketcher::PointPos::start)); - EXPECT_EQ(restoredConstraint.getElement(2), - Sketcher::GeoElementId(89, Sketcher::PointPos::end)); + EXPECT_EQ(restoredConstraint.getElement(0), Sketcher::GeoElementId(67, Sketcher::PointPos::mid)); + EXPECT_EQ(restoredConstraint.getElement(1), Sketcher::GeoElementId(78, Sketcher::PointPos::start)); + EXPECT_EQ(restoredConstraint.getElement(2), Sketcher::GeoElementId(89, Sketcher::PointPos::end)); inputFile.close(); } @@ -484,8 +492,7 @@ TEST_F(ConstraintPointsAccess, testSubstituteIndex) // NOLINT Sketcher::Constraint constraint; constraint.setElement(0, Sketcher::GeoElementId(10, Sketcher::PointPos::start)); constraint.setElement(1, Sketcher::GeoElementId(20, Sketcher::PointPos::end)); - constraint.setElement(2, - Sketcher::GeoElementId(10, Sketcher::PointPos::mid)); // same GeoId as 0 + constraint.setElement(2, Sketcher::GeoElementId(10, Sketcher::PointPos::mid)); // same GeoId as 0 // Act constraint.substituteIndex(10, 99); @@ -510,8 +517,7 @@ TEST_F(ConstraintPointsAccess, testSubstituteIndexAndPos) // NOLINT // Assert EXPECT_EQ(constraint.getElement(0), Sketcher::GeoElementId(42, Sketcher::PointPos::end)); EXPECT_EQ(constraint.getElement(1), Sketcher::GeoElementId(20, Sketcher::PointPos::start)); - EXPECT_EQ(constraint.getElement(2), - Sketcher::GeoElementId(10, Sketcher::PointPos::mid)); // unchanged + EXPECT_EQ(constraint.getElement(2), Sketcher::GeoElementId(10, Sketcher::PointPos::mid)); // unchanged } TEST_F(ConstraintPointsAccess, testInvolvesGeoId) // NOLINT diff --git a/tests/src/Mod/Sketcher/App/SketchObject.cpp b/tests/src/Mod/Sketcher/App/SketchObject.cpp index 36c1db0f26..834421f443 100644 --- a/tests/src/Mod/Sketcher/App/SketchObject.cpp +++ b/tests/src/Mod/Sketcher/App/SketchObject.cpp @@ -134,8 +134,7 @@ TEST_F(SketchObjectTest, testGetPointFromGeomPoint) auto ptMid = Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = Sketcher::SketchObject::getPoint(&point, Sketcher::PointPos::none); // Assert EXPECT_DOUBLE_EQ(ptStart[0], 1.0); @@ -157,12 +156,10 @@ TEST_F(SketchObjectTest, testGetPointFromGeomLineSegment) // Act auto ptStart = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::start); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptMid = - Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::mid); + [[maybe_unused]] auto ptMid = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = Sketcher::SketchObject::getPoint(&lineSeg, Sketcher::PointPos::none); // Assert EXPECT_DOUBLE_EQ(ptStart[0], 1.0); @@ -187,8 +184,7 @@ TEST_F(SketchObjectTest, testGetPointFromGeomCircle) // TODO: Maybe we want this to give an error instead of some default value auto ptEnd = Sketcher::SketchObject::getPoint(&circle, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&circle, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = Sketcher::SketchObject::getPoint(&circle, Sketcher::PointPos::none); // Assert // NOTE: Presently, start/end points of a circle are defined as the point on circle right of the @@ -219,8 +215,7 @@ TEST_F(SketchObjectTest, testGetPointFromGeomEllipse) // TODO: Maybe we want this to give an error instead of some default value auto ptEnd = Sketcher::SketchObject::getPoint(&ellipse, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&ellipse, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone = Sketcher::SketchObject::getPoint(&ellipse, Sketcher::PointPos::none); // Assert // NOTE: Presently, start/end points of an ellipse are defined as the point on the major axis in @@ -248,8 +243,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfCircle) auto ptMid = Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone + = Sketcher::SketchObject::getPoint(&arcOfCircle, Sketcher::PointPos::none); // Assert // NOTE: parameters for arc of circle are CCW angles from positive x-axis @@ -279,8 +274,8 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfEllipse) auto ptMid = Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone + = Sketcher::SketchObject::getPoint(&arcOfEllipse, Sketcher::PointPos::none); // Assert // NOTE: parameters for arc of ellipse are CCW angles from positive x-axis @@ -306,14 +301,14 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfHyperbola) arcOfHyperbola.setRange(startParam, endParam, true); // Act - [[maybe_unused]] auto ptStart = - Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::start); + [[maybe_unused]] auto ptStart + = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::start); auto ptMid = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::mid); - [[maybe_unused]] auto ptEnd = - Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::end); + [[maybe_unused]] auto ptEnd + = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone + = Sketcher::SketchObject::getPoint(&arcOfHyperbola, Sketcher::PointPos::none); // Assert // FIXME: Figure out how this is defined @@ -337,14 +332,14 @@ TEST_F(SketchObjectTest, testGetPointFromGeomArcOfParabola) arcOfParabola.setRange(startParam, endParam, true); // Act - [[maybe_unused]] auto ptStart = - Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::start); + [[maybe_unused]] auto ptStart + = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::start); auto ptMid = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::mid); - [[maybe_unused]] auto ptEnd = - Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::end); + [[maybe_unused]] auto ptEnd + = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone + = Sketcher::SketchObject::getPoint(&arcOfParabola, Sketcher::PointPos::none); // Assert // FIXME: Figure out how this is defined @@ -369,22 +364,18 @@ TEST_F(SketchObjectTest, testGetPointFromGeomBSplineCurveNonPeriodic) std::vector weights(5, 1.0); std::vector knotsNonPeriodic = {0.0, 1.0, 2.0}; std::vector multiplicitiesNonPeriodic = {degree + 1, 1, degree + 1}; - Part::GeomBSplineCurve nonPeriodicBSpline(poles, - weights, - knotsNonPeriodic, - multiplicitiesNonPeriodic, - degree, - false); + Part::GeomBSplineCurve + nonPeriodicBSpline(poles, weights, knotsNonPeriodic, multiplicitiesNonPeriodic, degree, false); // Act auto ptStart = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::start); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptMid = - Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::mid); + [[maybe_unused]] auto ptMid + = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::mid); auto ptEnd = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone + = Sketcher::SketchObject::getPoint(&nonPeriodicBSpline, Sketcher::PointPos::none); // Assert EXPECT_DOUBLE_EQ(ptStart[0], poles.front()[0]); @@ -406,24 +397,20 @@ TEST_F(SketchObjectTest, testGetPointFromGeomBSplineCurvePeriodic) std::vector weights(5, 1.0); std::vector knotsPeriodic = {0.0, 0.3, 1.0, 1.5, 1.8, 2.0}; std::vector multiplicitiesPeriodic(6, 1); - Part::GeomBSplineCurve periodicBSpline(poles, - weights, - knotsPeriodic, - multiplicitiesPeriodic, - degree, - true); + Part::GeomBSplineCurve + periodicBSpline(poles, weights, knotsPeriodic, multiplicitiesPeriodic, degree, true); // Act // TODO: Maybe we want this to give an error instead of some default value auto ptStart = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::start); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptMid = - Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::mid); + [[maybe_unused]] auto ptMid + = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::mid); // TODO: Maybe we want this to give an error instead of some default value auto ptEnd = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::end); // TODO: Maybe we want this to give an error instead of some default value - [[maybe_unused]] auto ptNone = - Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::none); + [[maybe_unused]] auto ptNone + = Sketcher::SketchObject::getPoint(&periodicBSpline, Sketcher::PointPos::none); // Assert // With non-trivial values for weights, knots, mults, etc, getting the coordinates is @@ -523,19 +510,20 @@ TEST_F(SketchObjectTest, testDeleteExposeInternalGeometryOfEllipse) // Ensure all internal geometry is satisfied // TODO: Also try to ensure types of geometries that have this type const auto constraints = getObject()->Constraints.getValues(); - for (auto alignmentType : {Sketcher::InternalAlignmentType::EllipseMajorDiameter, - Sketcher::InternalAlignmentType::EllipseMinorDiameter, - Sketcher::InternalAlignmentType::EllipseFocus1, - Sketcher::InternalAlignmentType::EllipseFocus2}) { + for (auto alignmentType : + {Sketcher::InternalAlignmentType::EllipseMajorDiameter, + Sketcher::InternalAlignmentType::EllipseMinorDiameter, + Sketcher::InternalAlignmentType::EllipseFocus1, + Sketcher::InternalAlignmentType::EllipseFocus2}) { // TODO: Ensure there exists one and only one curve with this type - int numConstraintsOfThisType = - std::count_if(constraints.begin(), - constraints.end(), - [&geoId, &alignmentType](const auto* constr) { - return constr->Type == Sketcher::ConstraintType::InternalAlignment - && constr->AlignmentType == alignmentType - && constr->Second == geoId; - }); + int numConstraintsOfThisType = std::count_if( + constraints.begin(), + constraints.end(), + [&geoId, &alignmentType](const auto* constr) { + return constr->Type == Sketcher::ConstraintType::InternalAlignment + && constr->AlignmentType == alignmentType && constr->Second == geoId; + } + ); EXPECT_EQ(numConstraintsOfThisType, 1); } @@ -570,18 +558,19 @@ TEST_F(SketchObjectTest, testDeleteExposeInternalGeometryOfHyperbola) // Ensure all internal geometry is satisfied // TODO: Also try to ensure types of geometries that have this type const auto constraints = getObject()->Constraints.getValues(); - for (auto alignmentType : {Sketcher::InternalAlignmentType::HyperbolaMajor, - Sketcher::InternalAlignmentType::HyperbolaMinor, - Sketcher::InternalAlignmentType::HyperbolaFocus}) { + for (auto alignmentType : + {Sketcher::InternalAlignmentType::HyperbolaMajor, + Sketcher::InternalAlignmentType::HyperbolaMinor, + Sketcher::InternalAlignmentType::HyperbolaFocus}) { // TODO: Ensure there exists one and only one curve with this type - int numConstraintsOfThisType = - std::count_if(constraints.begin(), - constraints.end(), - [&geoId, &alignmentType](const auto* constr) { - return constr->Type == Sketcher::ConstraintType::InternalAlignment - && constr->AlignmentType == alignmentType - && constr->Second == geoId; - }); + int numConstraintsOfThisType = std::count_if( + constraints.begin(), + constraints.end(), + [&geoId, &alignmentType](const auto* constr) { + return constr->Type == Sketcher::ConstraintType::InternalAlignment + && constr->AlignmentType == alignmentType && constr->Second == geoId; + } + ); EXPECT_EQ(numConstraintsOfThisType, 1); } @@ -616,17 +605,18 @@ TEST_F(SketchObjectTest, testDeleteExposeInternalGeometryOfParabola) // Ensure all internal geometry is satisfied // TODO: Also try to ensure types of geometries that have this type const auto constraints = getObject()->Constraints.getValues(); - for (auto alignmentType : {Sketcher::InternalAlignmentType::ParabolaFocalAxis, - Sketcher::InternalAlignmentType::ParabolaFocus}) { + for (auto alignmentType : + {Sketcher::InternalAlignmentType::ParabolaFocalAxis, + Sketcher::InternalAlignmentType::ParabolaFocus}) { // TODO: Ensure there exists one and only one curve with this type - int numConstraintsOfThisType = - std::count_if(constraints.begin(), - constraints.end(), - [&geoId, &alignmentType](const auto* constr) { - return constr->Type == Sketcher::ConstraintType::InternalAlignment - && constr->AlignmentType == alignmentType - && constr->Second == geoId; - }); + int numConstraintsOfThisType = std::count_if( + constraints.begin(), + constraints.end(), + [&geoId, &alignmentType](const auto* constr) { + return constr->Type == Sketcher::ConstraintType::InternalAlignment + && constr->AlignmentType == alignmentType && constr->Second == geoId; + } + ); EXPECT_EQ(numConstraintsOfThisType, 1); } @@ -664,22 +654,27 @@ TEST_F(SketchObjectTest, testDeleteExposeInternalGeometryOfBSpline) // TODO: Also try to ensure types of geometries that have this type const auto constraints = getObject()->Constraints.getValues(); std::map numConstraintsOfThisType; - for (auto alignmentType : {Sketcher::InternalAlignmentType::BSplineControlPoint, - Sketcher::InternalAlignmentType::BSplineKnotPoint}) { + for (auto alignmentType : + {Sketcher::InternalAlignmentType::BSplineControlPoint, + Sketcher::InternalAlignmentType::BSplineKnotPoint}) { // TODO: Ensure there exists one and only one curve with this type - numConstraintsOfThisType[alignmentType] = - std::count_if(constraints.begin(), - constraints.end(), - [&geoId, &alignmentType](const auto* constr) { - return constr->Type == Sketcher::ConstraintType::InternalAlignment - && constr->AlignmentType == alignmentType - && constr->Second == geoId; - }); + numConstraintsOfThisType[alignmentType] = std::count_if( + constraints.begin(), + constraints.end(), + [&geoId, &alignmentType](const auto* constr) { + return constr->Type == Sketcher::ConstraintType::InternalAlignment + && constr->AlignmentType == alignmentType && constr->Second == geoId; + } + ); } - EXPECT_EQ(numConstraintsOfThisType[Sketcher::InternalAlignmentType::BSplineControlPoint], - nonPeriodicBSpline->countPoles()); - EXPECT_EQ(numConstraintsOfThisType[Sketcher::InternalAlignmentType::BSplineKnotPoint], - nonPeriodicBSpline->countKnots()); + EXPECT_EQ( + numConstraintsOfThisType[Sketcher::InternalAlignmentType::BSplineControlPoint], + nonPeriodicBSpline->countPoles() + ); + EXPECT_EQ( + numConstraintsOfThisType[Sketcher::InternalAlignmentType::BSplineKnotPoint], + nonPeriodicBSpline->countKnots() + ); // Act // Delete internal geometry (again) @@ -837,13 +832,14 @@ TEST_F(SketchObjectTest, testGetElementName) // Act // unless it's Export, we are really just testing the superclass App::GeoFeature::getElementName // call. - auto forward_normal_name = - getObject()->getElementName((tagName + ";SKT").c_str(), - App::GeoFeature::ElementNameType::Normal); - auto reverse_normal_name = - getObject()->getElementName("Vertex2", App::GeoFeature::ElementNameType::Normal); - auto reverse_export_name = - getObject()->getElementName("Vertex1", App::GeoFeature::ElementNameType::Export); + auto forward_normal_name = getObject()->getElementName( + (tagName + ";SKT").c_str(), + App::GeoFeature::ElementNameType::Normal + ); + auto reverse_normal_name + = getObject()->getElementName("Vertex2", App::GeoFeature::ElementNameType::Normal); + auto reverse_export_name + = getObject()->getElementName("Vertex1", App::GeoFeature::ElementNameType::Export); auto map = getObject()->Shape.getShape().getElementMap(); ASSERT_EQ(map.size(), 3); EXPECT_STREQ(map[0].name.toString().c_str(), (tagName + ";SKT").c_str()); diff --git a/tests/src/Mod/Sketcher/App/SketchObjectChanges.cpp b/tests/src/Mod/Sketcher/App/SketchObjectChanges.cpp index bd8148db98..caef113ab2 100644 --- a/tests/src/Mod/Sketcher/App/SketchObjectChanges.cpp +++ b/tests/src/Mod/Sketcher/App/SketchObjectChanges.cpp @@ -234,8 +234,7 @@ TEST_F(SketchObjectTest, testTrimLineSegmentMid) // TODO: Once this line segment is trimmed, there should be two "smaller" curves in its place EXPECT_EQ(getObject()->getHighestCurveIndex(), geoId + 1); // TODO: There should be a "point-on-object" constraint on the intersecting curves - int numberOfPointOnObjectConstraints = - countConstraintsOfType(getObject(), Sketcher::PointOnObject); + int numberOfPointOnObjectConstraints = countConstraintsOfType(getObject(), Sketcher::PointOnObject); EXPECT_EQ(numberOfPointOnObjectConstraints, 1); int numberOfCoincidentConstraints = countConstraintsOfType(getObject(), Sketcher::Coincident); EXPECT_EQ(numberOfCoincidentConstraints, 1); @@ -297,8 +296,7 @@ TEST_F(SketchObjectTest, testTrimCircleMid) EXPECT_EQ(getObject()->getHighestCurveIndex(), geoId); // There should be one "coincident" and one "point-on-object" constraint on the intersecting // curves - int numberOfPointOnObjectConstraints = - countConstraintsOfType(getObject(), Sketcher::PointOnObject); + int numberOfPointOnObjectConstraints = countConstraintsOfType(getObject(), Sketcher::PointOnObject); EXPECT_EQ(numberOfPointOnObjectConstraints, 1); int numberOfCoincidentConstraints = countConstraintsOfType(getObject(), Sketcher::Coincident); EXPECT_EQ(numberOfCoincidentConstraints, 1); @@ -362,8 +360,7 @@ TEST_F(SketchObjectTest, testTrimArcOfCircleMid) EXPECT_EQ(result, 0); EXPECT_EQ(getObject()->getHighestCurveIndex(), geoId + 1); // There should be a "point-on-object" constraint on the intersecting curves - int numberOfPointOnObjectConstraints = - countConstraintsOfType(getObject(), Sketcher::PointOnObject); + int numberOfPointOnObjectConstraints = countConstraintsOfType(getObject(), Sketcher::PointOnObject); EXPECT_EQ(numberOfPointOnObjectConstraints, 1); // There should be 2 coincident constraints: one with lineSegCut1 and one between centers of the // new arcs @@ -438,8 +435,7 @@ TEST_F(SketchObjectTest, testTrimEllipseMid) EXPECT_EQ(getObject()->getHighestCurveIndex(), 2); // There should be one "coincident" and one "point-on-object" constraint on the intersecting // curves - int numberOfPointOnObjectConstraints = - countConstraintsOfType(getObject(), Sketcher::PointOnObject); + int numberOfPointOnObjectConstraints = countConstraintsOfType(getObject(), Sketcher::PointOnObject); EXPECT_EQ(numberOfPointOnObjectConstraints, 1); int numberOfCoincidentConstraints = countConstraintsOfType(getObject(), Sketcher::Coincident); EXPECT_EQ(numberOfCoincidentConstraints, 1); @@ -510,8 +506,7 @@ TEST_F(SketchObjectTest, testTrimPeriodicBSplineMid) EXPECT_EQ(getObject()->getHighestCurveIndex(), 2); // There should be one "coincident" and one "point-on-object" constraint on the intersecting // curves - int numberOfPointOnObjectConstraints = - countConstraintsOfType(getObject(), Sketcher::PointOnObject); + int numberOfPointOnObjectConstraints = countConstraintsOfType(getObject(), Sketcher::PointOnObject); EXPECT_EQ(numberOfPointOnObjectConstraints, 1); int numberOfCoincidentConstraints = countConstraintsOfType(getObject(), Sketcher::Coincident); EXPECT_EQ(numberOfCoincidentConstraints, 1); @@ -587,8 +582,7 @@ TEST_F(SketchObjectTest, testTrimNonPeriodicBSplineMid) // Only remaining: one line segment and the trimmed B-spline EXPECT_EQ(getObject()->getHighestCurveIndex(), 3); // There should be a "point-on-object" constraint on the intersecting curves - int numberOfPointOnObjectConstraints = - countConstraintsOfType(getObject(), Sketcher::PointOnObject); + int numberOfPointOnObjectConstraints = countConstraintsOfType(getObject(), Sketcher::PointOnObject); EXPECT_EQ(numberOfPointOnObjectConstraints, 1); int numberOfCoincidentConstraints = countConstraintsOfType(getObject(), Sketcher::Coincident); EXPECT_EQ(numberOfCoincidentConstraints, 1); @@ -740,9 +734,11 @@ TEST_F(SketchObjectTest, testTrimEndEffectOnUnrelatedTangent) EXPECT_EQ(result, 0); // TODO: find tangent and confirm nature const auto& constraints = getObject()->Constraints.getValues(); - auto tangIt = std::ranges::find(constraints, - Sketcher::ConstraintType::Tangent, - &Sketcher::Constraint::Type); + auto tangIt = std::ranges::find( + constraints, + Sketcher::ConstraintType::Tangent, + &Sketcher::Constraint::Type + ); EXPECT_NE(tangIt, constraints.end()); EXPECT_EQ((*tangIt)->FirstPos, Sketcher::PointPos::none); EXPECT_EQ((*tangIt)->SecondPos, Sketcher::PointPos::none); @@ -1067,9 +1063,7 @@ TEST_F(SketchObjectTest, testJoinCurvesWhenTangent) EXPECT_EQ(getObject()->getHighestCurveIndex(), 0); // TODO: Check the shape is conserved (how?) // Check there is no C-0 knot (should be possible for the chosen example) - auto mults = static_cast(getObject()->getGeometry(0)) - ->getMultiplicities(); - EXPECT_TRUE(std::all_of(mults.begin(), mults.end(), [](auto mult) { - return mult >= 1; - })); + auto mults + = static_cast(getObject()->getGeometry(0))->getMultiplicities(); + EXPECT_TRUE(std::all_of(mults.begin(), mults.end(), [](auto mult) { return mult >= 1; })); } diff --git a/tests/src/Mod/Sketcher/App/SketcherTestHelpers.cpp b/tests/src/Mod/Sketcher/App/SketcherTestHelpers.cpp index 1e3c82acf2..06f2d6ca7f 100644 --- a/tests/src/Mod/Sketcher/App/SketcherTestHelpers.cpp +++ b/tests/src/Mod/Sketcher/App/SketcherTestHelpers.cpp @@ -107,12 +107,14 @@ std::unique_ptr createTypicalNonPeriodicBSpline() std::vector weights(5, 1.0); std::vector knotsNonPeriodic = {0.0, 1.0, 2.0}; std::vector multiplicitiesNonPeriodic = {degree + 1, 1, degree + 1}; - return std::make_unique(poles, - weights, - knotsNonPeriodic, - multiplicitiesNonPeriodic, - degree, - false); + return std::make_unique( + poles, + weights, + knotsNonPeriodic, + multiplicitiesNonPeriodic, + degree, + false + ); } std::unique_ptr createTypicalPeriodicBSpline() @@ -127,12 +129,14 @@ std::unique_ptr createTypicalPeriodicBSpline() std::vector weights(5, 1.0); std::vector knotsPeriodic = {0.0, 0.3, 1.0, 1.5, 1.8, 2.0}; std::vector multiplicitiesPeriodic(6, 1); - return std::make_unique(poles, - weights, - knotsPeriodic, - multiplicitiesPeriodic, - degree, - true); + return std::make_unique( + poles, + weights, + knotsPeriodic, + multiplicitiesPeriodic, + degree, + true + ); } int countConstraintsOfType(const Sketcher::SketchObject* obj, const Sketcher::ConstraintType cType) @@ -146,7 +150,8 @@ int countConstraintsOfType(const Sketcher::SketchObject* obj, const Sketcher::Co Base::Vector3d getPointAtNormalizedParameter(const Part::GeomCurve& curve, double param) { - return curve.pointAtParameter(curve.getFirstParameter() - + (curve.getLastParameter() - curve.getFirstParameter()) * param); + return curve.pointAtParameter( + curve.getFirstParameter() + (curve.getLastParameter() - curve.getFirstParameter()) * param + ); } } // namespace SketcherTestHelpers diff --git a/tests/src/Mod/Sketcher/App/SketcherTestHelpers.h b/tests/src/Mod/Sketcher/App/SketcherTestHelpers.h index 037dfaf189..60ace6d2da 100644 --- a/tests/src/Mod/Sketcher/App/SketcherTestHelpers.h +++ b/tests/src/Mod/Sketcher/App/SketcherTestHelpers.h @@ -25,12 +25,8 @@ private: // TODO: use shared_ptr or something else here? Sketcher::SketchObject* _sketchobj; std::string _docName; - std::vector allowedTypes {"Vertex", - "Edge", - "ExternalEdge", - "H_Axis", - "V_Axis", - "RootPoint"}; + std::vector + allowedTypes {"Vertex", "Edge", "ExternalEdge", "H_Axis", "V_Axis", "RootPoint"}; }; namespace SketcherTestHelpers diff --git a/tests/src/Mod/Sketcher/App/planegcs/Constraints.cpp b/tests/src/Mod/Sketcher/App/planegcs/Constraints.cpp index 5609b03aa2..d985fd592b 100644 --- a/tests/src/Mod/Sketcher/App/planegcs/Constraints.cpp +++ b/tests/src/Mod/Sketcher/App/planegcs/Constraints.cpp @@ -113,31 +113,33 @@ TEST_F(ConstraintsTest, tangentBSplineAndArc) // NOLINT bspline.periodic = false; double bsplineParam = 0.35; - std::vector params = {point.x, - point.y, - arcStart.x, - arcStart.y, - arcEnd.x, - arcEnd.y, - arcCenter.x, - arcCenter.y, - &arcRadius, - bSplineStart.x, - bSplineStart.y, - bSplineEnd.x, - bSplineEnd.y, - &bSplineControlPointsX[0], - &bSplineControlPointsY[0], - &bSplineControlPointsX[1], - &bSplineControlPointsY[1], - &bSplineControlPointsX[2], - &bSplineControlPointsY[2], - &bSplineControlPointsX[3], - &bSplineControlPointsY[3], - &bSplineControlPointsX[4], - &bSplineControlPointsY[4], - &desiredAngle, - &bsplineParam}; + std::vector params = { + point.x, + point.y, + arcStart.x, + arcStart.y, + arcEnd.x, + arcEnd.y, + arcCenter.x, + arcCenter.y, + &arcRadius, + bSplineStart.x, + bSplineStart.y, + bSplineEnd.x, + bSplineEnd.y, + &bSplineControlPointsX[0], + &bSplineControlPointsY[0], + &bSplineControlPointsX[1], + &bSplineControlPointsY[1], + &bSplineControlPointsX[2], + &bSplineControlPointsY[2], + &bSplineControlPointsX[3], + &bSplineControlPointsY[3], + &bSplineControlPointsX[4], + &bSplineControlPointsY[4], + &desiredAngle, + &bsplineParam + }; params.insert(params.end(), weightsAsPtr.begin(), weightsAsPtr.end()); params.insert(params.end(), knotsAsPtr.begin(), knotsAsPtr.end()); @@ -146,13 +148,7 @@ TEST_F(ConstraintsTest, tangentBSplineAndArc) // NOLINT System()->addConstraintArcRules(arc); System()->addConstraintPointOnArc(point, arc, 0, true); System()->addConstraintPointOnBSpline(point, bspline, &bsplineParam, 0, true); - System()->addConstraintAngleViaPointAndParam(bspline, - arc, - point, - &bsplineParam, - &desiredAngle, - 0, - true); + System()->addConstraintAngleViaPointAndParam(bspline, arc, point, &bsplineParam, &desiredAngle, 0, true); int solveResult = System()->solve(params); if (solveResult == GCS::Success) { System()->applySolution(); @@ -161,9 +157,10 @@ TEST_F(ConstraintsTest, tangentBSplineAndArc) // NOLINT // Assert EXPECT_EQ(solveResult, GCS::Success); // is point on arc? - EXPECT_DOUBLE_EQ((arcRadius) * (arcRadius), - (pointX - arcCenterX) * (pointX - arcCenterX) - + (pointY - arcCenterY) * (pointY - arcCenterY)); + EXPECT_DOUBLE_EQ( + (arcRadius) * (arcRadius), + (pointX - arcCenterX) * (pointX - arcCenterX) + (pointY - arcCenterY) * (pointY - arcCenterY) + ); // is point on B-spline? GCS::DeriVector2 pointAtBSplineParam = bspline.Value(bsplineParam, 1.0); EXPECT_DOUBLE_EQ(pointAtBSplineParam.x, pointX); @@ -174,8 +171,10 @@ TEST_F(ConstraintsTest, tangentBSplineAndArc) // NOLINT double dprd; // FIXME: This error is probably too high. Fixing this may require improving the solver, // however. - EXPECT_NEAR(std::fabs(centerToPoint.crossProdZ(tangentBSplineAtPoint, dprd)) - / (centerToPoint.length() * tangentBSplineAtPoint.length()), - 1.0, - 0.005); + EXPECT_NEAR( + std::fabs(centerToPoint.crossProdZ(tangentBSplineAtPoint, dprd)) + / (centerToPoint.length() * tangentBSplineAtPoint.length()), + 1.0, + 0.005 + ); } diff --git a/tests/src/Mod/Spreadsheet/App/PropertySheet.cpp b/tests/src/Mod/Spreadsheet/App/PropertySheet.cpp index a3199f8966..ac3f827c3b 100644 --- a/tests/src/Mod/Spreadsheet/App/PropertySheet.cpp +++ b/tests/src/Mod/Spreadsheet/App/PropertySheet.cpp @@ -64,10 +64,12 @@ TEST_F(PropertySheetTest, isValidCellAddressNameInvalidNames) // NOLINT TEST_F(PropertySheetTest, validAliases) // NOLINT { - std::vector validAliases {"Bork", - "Bork_de_bork" - "A", - "AA123456"}; + std::vector validAliases { + "Bork", + "Bork_de_bork" + "A", + "AA123456" + }; for (const auto& name : validAliases) { EXPECT_TRUE(propertySheet()->isValidAlias(name)) << "\"" << name << "\" was not accepted as an alias name, and should be"; @@ -76,11 +78,8 @@ TEST_F(PropertySheetTest, validAliases) // NOLINT TEST_F(PropertySheetTest, invalidAliases) // NOLINT { - std::vector invalidAliases {"A1", - "ZZ1234", - "mm", - "no spaces allowed", - "\'NoLeadingQuotes"}; + std::vector + invalidAliases {"A1", "ZZ1234", "mm", "no spaces allowed", "\'NoLeadingQuotes"}; for (const auto& name : invalidAliases) { EXPECT_FALSE(propertySheet()->isValidAlias(name)) diff --git a/tests/src/Mod/Start/App/FileUtilities.cpp b/tests/src/Mod/Start/App/FileUtilities.cpp index f2de0026a3..0a7d4fb0dd 100644 --- a/tests/src/Mod/Start/App/FileUtilities.cpp +++ b/tests/src/Mod/Start/App/FileUtilities.cpp @@ -41,12 +41,14 @@ TEST_F(FileUtilitiesTest, humanReadableSizeBytesHasNoDecimal) TEST_F(FileUtilitiesTest, humanReadableSizeOthersHaveDecimal) { - constexpr std::array testSizes {1000, - 123456, - 123456789, - 123456789013, - 100000000000000, - std::numeric_limits::max()}; + constexpr std::array testSizes { + 1000, + 123456, + 123456789, + 123456789013, + 100000000000000, + std::numeric_limits::max() + }; for (const auto size : testSizes) { auto result = Start::humanReadableSize(size); EXPECT_NE(result.find('.'), std::string::npos); diff --git a/tests/src/zipios++/collectioncollection.cpp b/tests/src/zipios++/collectioncollection.cpp index 1efe494bfa..b2f9c76885 100644 --- a/tests/src/zipios++/collectioncollection.cpp +++ b/tests/src/zipios++/collectioncollection.cpp @@ -29,8 +29,7 @@ TEST(Collection, TestCopy) EXPECT_EQ(copy.getEntry("inexistant", zipios::FileCollection::MatchPath::MATCH), nullptr); EXPECT_EQ(copy.getEntry("inexistant", zipios::FileCollection::MatchPath::IGNORE), nullptr); EXPECT_EQ(copy.getInputStream("inexistant", zipios::FileCollection::MatchPath::MATCH), nullptr); - EXPECT_EQ(copy.getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), - nullptr); + EXPECT_EQ(copy.getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), nullptr); EXPECT_EQ(copy.getName(), "-"); // default name is "-" EXPECT_EQ(copy.size(), 0); } @@ -45,8 +44,7 @@ TEST(Collection, TestCopyAssign) EXPECT_EQ(copy.getEntry("inexistant", zipios::FileCollection::MatchPath::MATCH), nullptr); EXPECT_EQ(copy.getEntry("inexistant", zipios::FileCollection::MatchPath::IGNORE), nullptr); EXPECT_EQ(copy.getInputStream("inexistant", zipios::FileCollection::MatchPath::MATCH), nullptr); - EXPECT_EQ(copy.getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), - nullptr); + EXPECT_EQ(copy.getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), nullptr); EXPECT_EQ(copy.getName(), "-"); // default name is "-" EXPECT_EQ(copy.size(), 0); } @@ -59,10 +57,8 @@ TEST(Collection, TestClone) EXPECT_EQ(pointer->entries().empty(), true); EXPECT_EQ(pointer->getEntry("inexistant", zipios::FileCollection::MatchPath::MATCH), nullptr); EXPECT_EQ(pointer->getEntry("inexistant", zipios::FileCollection::MatchPath::IGNORE), nullptr); - EXPECT_EQ(pointer->getInputStream("inexistant", zipios::FileCollection::MatchPath::MATCH), - nullptr); - EXPECT_EQ(pointer->getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), - nullptr); + EXPECT_EQ(pointer->getInputStream("inexistant", zipios::FileCollection::MatchPath::MATCH), nullptr); + EXPECT_EQ(pointer->getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), nullptr); EXPECT_EQ(pointer->getName(), "-"); // default name is "-" EXPECT_EQ(pointer->size(), 0); } diff --git a/tests/src/zipios++/zipfile.cpp b/tests/src/zipios++/zipfile.cpp index f22e2d8fbb..b674ee9efa 100644 --- a/tests/src/zipios++/zipfile.cpp +++ b/tests/src/zipios++/zipfile.cpp @@ -11,14 +11,22 @@ TEST(ZipFile, TestValidity) zipios::ZipFile zf; EXPECT_EQ(zf.isValid(), false); EXPECT_THROW(zf.entries(), zipios::InvalidStateException); - EXPECT_THROW(zf.getEntry("inexistant", zipios::FileCollection::MatchPath::MATCH), - zipios::InvalidStateException); - EXPECT_THROW(zf.getEntry("inexistant", zipios::FileCollection::MatchPath::IGNORE), - zipios::InvalidStateException); - EXPECT_THROW(zf.getInputStream("inexistant", zipios::FileCollection::MatchPath::MATCH), - zipios::InvalidStateException); - EXPECT_THROW(zf.getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), - zipios::InvalidStateException); + EXPECT_THROW( + zf.getEntry("inexistant", zipios::FileCollection::MatchPath::MATCH), + zipios::InvalidStateException + ); + EXPECT_THROW( + zf.getEntry("inexistant", zipios::FileCollection::MatchPath::IGNORE), + zipios::InvalidStateException + ); + EXPECT_THROW( + zf.getInputStream("inexistant", zipios::FileCollection::MatchPath::MATCH), + zipios::InvalidStateException + ); + EXPECT_THROW( + zf.getInputStream("inexistant", zipios::FileCollection::MatchPath::IGNORE), + zipios::InvalidStateException + ); EXPECT_THROW(zf.getName(), zipios::InvalidStateException); EXPECT_THROW(zf.size(), zipios::InvalidStateException); zf.close();